我有一个用 xib 文件创建的自定义 UIButton。当我在我的 View 上使用我的自定义按钮时,当我按下它时它不起作用。
我的 RoundBtn.swift 文件:
import UIKit
@IBDesignable class RoundBtn: UIButton {
var nibName = "RoundBtn"
@IBOutlet weak var btnImageView: UIImageView!
@IBOutlet weak var btnLabel: UILabel!
@IBInspectable var image: UIImage? {
get {
return btnImageView.image
} set(image) {
btnImageView.image = image
}
}
@IBInspectable var label: String? {
get {
return btnLabel.text
} set(label) {
btnLabel.text = label
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
func setup() {
let view = loadViewFromNib()
view.frame = self.bounds
view.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
btnImageView.layer.cornerRadius = 60/2
btnImageView.layer.borderColor = UIColor(red: 5/255,
green: 66/255, blue: 38/255, alpha: 1).CGColor
btnImageView.layer.borderWidth = 2
btnLabel.font = UIFont.boldSystemFontOfSize(14.0)
btnImageView.userInteractionEnabled = true
btnLabel.userInteractionEnabled = true
view.userInteractionEnabled = true
addSubview(view)
}
func loadViewFromNib() -> UIButton {
let bundle = NSBundle(forClass: self.dynamicType)
let nib = UINib(nibName: nibName, bundle: bundle)
let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIButton
return view
}
}
我的 RoundBtn.xib 文件:
查看我在哪里使用了我的自定义按钮:
我在所有 View 组件上启用了 userInteractionEnabled
。当我点击我的自定义按钮时,它不起作用。我尝试以编程方式定义点击并定义 Action segue(显示)。
@IBAction func myCartBtnPressed(sender: AnyObject) {
print("my cart btn pressed")
}
最佳答案
我认为这是因为您使用 userInteractionEnabled 向当前的 UIButton 添加了几个 UIViews subview ,这意味着它们正在处理用户输入。
如果你这样做:
view.isUserInteractionEnabled = false
RoundBtn 本身将获取所有触摸事件,而不是您在顶部的 UIViews。
关于ios - Swift,自定义 UIButton 单击时不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35317796/