1

我无法让我的自定义按钮实时预览基本示例,这让我无法使用对我的开发有很大帮助的东西(IBDesignable)。

我的自定义按钮代码如下:

import Cocoa
@IBDesignable class MyButton: NSButton {

    @IBInspectable var name:String = "Bob"{
        didSet{
            setup()
        }
    }

    override init(frame frameRect: NSRect) {
        super.init(frame: frameRect)
        setup()
    }

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

    override func prepareForInterfaceBuilder() {
        setup()
    }

    func setup(){
        self.title = name
        self.setNeedsDisplay()
    }

    override func drawRect(dirtyRect: NSRect) {
        super.drawRect(dirtyRect)
        // Drawing code here.
    }

}

然后,我将自定义视图或 NSButton 拖到我的画布 (mainmenu.xib) 上,并将其在检查器窗口中的类类型调整为 MyButton。弹出可检查字段并且没有错误但是当我在属性面板中更改其值时,我的自定义按钮不会更改其名称!

此外,当我将自定义视图拖到画布上时,我得到的只是一个空白/透明矩形代替按钮(在将类更改为 MyButton 之后)。

任何帮助将不胜感激。这一直让我发疯!

4

1 回答 1

0

我不得不把按钮放在里面NSView

@IBDesignable
public class MyButton: NSView {

    @IBInspectable var name: String = "Bob" {
        didSet{
            button?.title = name
        }
    }

    public var touchUpHandler: (() -> Void)?

    private weak var button: NSButton!

    override init(frame frameRect: NSRect) {
        super.init(frame: frameRect)
        configureView()
    }

    required public init?(coder: NSCoder) {
        super.init(coder: coder)
        configureView()
    }

    private func configureView() {
        let button = NSButton(title: name, target: self, action: #selector(didTapButton(_:)))
        button.bezelStyle = .regularSquare
        button.translatesAutoresizingMaskIntoConstraints = false
        addSubview(button)
        NSLayoutConstraint.activate([
            button.topAnchor.constraint(equalTo: topAnchor),
            button.leftAnchor.constraint(equalTo: leftAnchor),
            button.rightAnchor.constraint(equalTo: rightAnchor),
            button.bottomAnchor.constraint(equalTo: bottomAnchor)
        ])
        self.button = button
    }

    func didTapButton(_ sender: NSButton) {
        touchUpHandler?()
    }

}

然后我像这样使用它:

@IBOutlet weak var myButton: MyButton!

override func viewDidLoad() {
    super.viewDidLoad()

    myButton.touchUpHandler = { [unowned self] in
        self.performSomeAction()
    }
}
于 2016-11-07T18:10:45.770 回答