首页 > 解决方案 > 我的按钮的 addTarget 中的操作不起作用

问题描述

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()
 }
}

标签: swift

解决方案


改变这个(你需要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)

推荐阅读