将目标添加到自定义按钮 Swift 4



我在 Swift 4 中addTarget自定义按钮时遇到问题。我尝试了所有方法,但仍然无法定义选择器,因为结果总是错误。

知道吗?

let myButton = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 50))
myButton.center = CGPoint(x: 200, y: 400)
myButton.backgroundColor = UIColor.purple
myButton.layer.cornerRadius = 18.0
myButton.setTitle("Tap Me", for: UIControlState.normal)
myButton.setTitleColor(UIColor.white, for: UIControlState.normal)
myButton.actions(forTarget: self, forControlEvent: UIControlEvents.touchUpInside)
myButton.isHighlighted = true
self.view.addSubview(myButton)

试试这个

myButton.addTarget(self, action: #selector(self.btnClickAction(_:)), for: .touchUpInside)

按钮操作方法

@objc func btnClickAction(_ sender:UIButton) {
print("My custom button action")
}

最新更新