[英]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.