我正在开发一个涉及一整套按钮的应用程序,这些按钮将采用完全相同的格式设置-相同的大小,布局,颜色,文本标签等。类似于它与“表格视图”中的“原型”单元格一起使用的方式,容器视图,我试图在外部xib中创建“原型”按钮的一个实例作为UIButton的自定义类,可以将其拉入主视图控制器并根据需要重复。

我在引入按钮方面没有任何麻烦,并且在自定义文本标签等方面也没有任何问题。因此,这并不像“原型”未正确输出那样。

似乎不起作用的是实际的按钮点击。

我有两个按钮-button1和button2,分别被分配了tag = 1和tag = 2。为了测试按钮操作,我设置了一条打印语句,该语句将发送方的标签号打印到控制台。

如果我在主故事板上创建了一个简单的普通按钮,并为其指定了标签号,则该按钮的行为将正确。但是自定义类按钮不会将任何内容发送到控制台。

我错过了一步吗?我的直觉是我遗漏了外部xib的一个额外细节...但是我认为具体细节(标签号等)需要与每个实例相关联,而不是与原型相关联。

    import UIKit

class ViewController: UIViewController {

@IBOutlet weak var button1: customButton!
@IBOutlet weak var button2: customButton!

override func viewDidLoad() {
    super.viewDidLoad()
    button1.customTitle.text = "This is Button 1"
    button2.customTitle.text = "This is Button 2"
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

@IBAction func buttonPressed(_ sender: UIButton) {

    print(sender.tag)

    }
}


编辑:这是从xib生成按钮的代码。

import UIKit

class customButton: UIButton {

    @IBOutlet var contentView: UIView!
    @IBAction func buttonPressed(_ sender: UIButton) {
}

    override init(frame: CGRect) { // for using CustomView in code
        super.init(frame: frame)
        commonInit()
    }

    required init?(coder aDecoder: NSCoder) { // for using CustomView in IB
        super.init(coder: aDecoder)
        commonInit()
    }

    private func commonInit() {
        Bundle.main.loadNibNamed("customButton", owner: self, options: nil)
        addSubview(contentView)
        contentView.frame = self.bounds
        contentView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
    }
}

最佳答案

现在,我在修改后的答案中看到,您已将contentView添加为子视图。将其启用交互的状态设置为false,这样它就不会在乎触摸本身,并且应该触发按钮动作。

在您的按钮文件中,可能是commonInit:

contentView.isUserInteractionEnabled = false

10-08 09:13
查看更多