自定义 UIButton - IBAction 不起作用



我有一个默认的UIButton链接到IBAction(内部润色(。这工作正常,所以我知道我的连接没问题。一旦我将 UIButton 类更改为我的自定义按钮,就不再触发 IBAction。下面是我的自定义 UIButton 的代码。知道为什么会这样吗?

import UIKit
@IBDesignable
class PrimaryButton: UIButton {
override init(frame: CGRect) {
super.init(frame: frame)
initView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initView()
}

private func initView() {
let view = viewFromNibForClass()
view.frame = bounds
view.autoresizingMask = [
UIViewAutoresizing.flexibleWidth,
UIViewAutoresizing.flexibleHeight
]
addSubview(view)
}
private func viewFromNibForClass() ->UIView {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: String(describing: type(of: self)), bundle: bundle)
let view = nib.instantiate(withOwner: self, options: nil).first as! UIView
return view
}
}

您的代码不起作用,因为按钮不再接收触摸。所有触摸都将发送到您添加的最顶层自定义视图。

设置view.userInteractionEnabled = false使其对触摸透明。

您添加的视图覆盖了您的自定义按钮。

最新更新