gpt4 book ai didi

objective-c - 需要帮助让 IBDesignable 工作

转载 作者:行者123 更新时间:2023-11-28 09:16:20 25 4
gpt4 key购买 nike

我无法让我的自定义按钮实时预览基本示例,这让我无法使用对我的开发有很大帮助的东西 (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.
}

}

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

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

如有任何帮助,我们将不胜感激。这让我抓狂!

最佳答案

我必须将按钮放在 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()
}
}

关于objective-c - 需要帮助让 IBDesignable 工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27448062/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com