[英]The action in addTarget of my button does not work
Xcode 没有报告错误,但是当我按下按钮时没有打印任何内容。 我用行动试过了:
#selector (print), action: #selector (self.print), action: #selector (ViewController.print)..etc..
斯威夫特 4,Xcode 10.1
class SomeViewController:UIViewController {
var button:UIButton = UIButton()
func setupButton()
{
button = UIButton(frame: CGRect(x: 140, y: 140, width: 90, height: 40))
button.addTarget(self, action: #selector(print(-:)) , for: .touchUpOutside)
navigationController?.navigationBar.addSubview(button)
button.setTitle("Convert", for: .normal)
button.backgroundColor = .yellow
view.addSubview(button)
}
@objc func print(_sender: UIButton)
{
print("Stackoverflow")
}
override func viewDidLoad()
{
super.viewDidLoad()
view.addSubview(CollectionView)
CollectionView.frame = view.frame
setupButton()
}
}
改变这个(你需要touchUpInside
而不是touchUpOutside
)
button.addTarget(self, action: #selector(print(_:)) , for: .touchUpOutside)
到
button.addTarget(self, action: #selector(printRes) , for: .touchUpInside)
@objc func printRes(_ sender: UIButton) { }
也不要使用print
作为按钮操作名称,因为它是一个保留方法
还要让按钮点击动作设置它的类型
button = UIButton(type: .system)
button.frame = CGRect(x: 140, y: 140, width: 90, height: 40)
您只需将事件类型从 .touchUpOutside 更改为 .touchUpInside
这是事件文档
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.