1

我目前正在用 Swift 编写一个 Cocoa 应用程序来练习该语言。我对 AppKit 框架还不太熟悉,但现在我遇到了一个有趣的问题。

它只包含一个 NSWindow 和我的自定义 NSView。使用自动布局,我可以控制 NSView 的大小,具体取决于调整大小的窗口。

基础结构

至于我的自定义视图,我想将我的 NSView 作为一个容器,并且里面有一个 NSTextView。

import Foundation
import AppKit

class Fucky2View: NSView 
{
    var textView : NSTextView!

    required init?(coder aDecoder: NSCoder) 
    {
        super.init(coder: aDecoder)
        commonInit()
    }

    override init(frame: CGRect) 
    {
        super.init(frame: frame)
        commonInit()
    }

    func commonInit()
    {
        print("initing")

        self.wantsLayer = true
        self.layer?.backgroundColor = NSColor.red.cgColor

        textView = NSTextView.init(frame: self.bounds)
        self.addSubview(textView)

        self.translatesAutoresizingMaskIntoConstraints = false
        textView.translatesAutoresizingMaskIntoConstraints = false

        textView.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true
        textView.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true
        textView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
        textView.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true

    }

    func displayText(_ text : String)
    {
        let attrStr : NSAttributedString = NSAttributedString(string: text+"\n") 
        textView.textStorage?.append(attrStr)
    }
}

所以我只想保持 NSTextView 与视图本身的大小相同。我将视图背景着色为红色,以查看其填充是否正确,但这就是发生的情况: https ://www.youtube.com/watch?v=LTQndoGzzEM

textview 的高度有时设置正确,但大多数时候没有。

我使用 UIKit、UIViewController、UIView 和 UITextView 重新创建了完全相同的应用程序,并在 iPhone 上进行了测试(我通过旋转调整了屏幕大小),并且工作正常。

有人知道吗?我与优先事项一起玩,但没有帮助。从 NSView、并发绘制等尝试了几件事,但没有帮助。尝试使用 NSLayoutConstraint 而不是锚点,没有变化。唯一的事情是如果我在自定义 NSView 的 drawRect: 方法中设置 TextView 的框架,但我想做一个更好的解决方案。

或者有没有人有其他想法?macOS Sierra 10.12.6、XCode 9.2

谢谢

4

0 回答 0