[英]The action in addTarget of my button does not work
Xcode did not report errors but nothing was printed when I pressed the button. Xcode 没有报告错误,但是当我按下按钮时没有打印任何内容。 I tried it with action:
我用行动试过了:
#selector (print), action: #selector (self.print), action: #selector (ViewController.print)..etc..
Swift 4, Xcode 10.1斯威夫特 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()
}
}
Change this ( You need touchUpInside
instead of touchUpOutside
)改变这个(你需要
touchUpInside
而不是touchUpOutside
)
button.addTarget(self, action: #selector(print(_:)) , for: .touchUpOutside)
to到
button.addTarget(self, action: #selector(printRes) , for: .touchUpInside)
@objc func printRes(_ sender: UIButton) { }
Also don't use print
as button action name because it's a reserved method也不要使用
print
作为按钮操作名称,因为它是一个保留方法
Also to get the button click action set it's type还要让按钮点击动作设置它的类型
button = UIButton(type: .system)
button.frame = CGRect(x: 140, y: 140, width: 90, height: 40)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.