我创建了一个 UIButton,我希望它在按下时打印一些消息。
所以我做了这样的事情: 在 loadView() 中
button.addTarget(self, action: #selector(ViewController.pressButton(button:)), for: .touchUpInside)
一个方法:
func pressButton(button: UIButton) {
NSLog("pressed!")
}
但是当我点击按钮时没有任何反应。
最佳答案
在您的 viewDidLoad
中添加按钮代码,它将为您工作:
override func viewDidLoad() {
super.viewDidLoad()
let button = UIButton(frame: CGRect(x: 10, y: 10, width: 100, height: 100))
button.backgroundColor = UIColor.gray
button.addTarget(self, action: #selector(pressButton(button:)), for: .touchUpInside)
self.view.addSubview(button)
}
func pressButton(button: UIButton) {
NSLog("pressed!")
}
您不需要将 ViewController.pressButton
添加到 selector
,使用 function name
就足够了。
Swift 4.x 版本:
let button = UIButton(frame: CGRect(x: 10, y: 10, width: 100, height: 100))
button.backgroundColor = .gray
button.tag = 0
button.addTarget(self, action: #selector(pressButton(_:)), for: .touchUpInside)
self.view.addSubview(button)
@objc func pressButton(_ button: UIButton) {
print("Button with tag: \(button.tag) clicked!")
}
Swift 5.1 版本:
let button = UIButton(frame: CGRect(x: 10, y: 10, width: 100, height: 100))
button.backgroundColor = .gray
button.tag = 100
button.addTarget(self, action: #selector(pressButton), for: .touchUpInside)
self.view.addSubview(button)
@objc func pressButton(button: UIButton) {
print("Button with tag: \(button.tag) clicked!")
}
关于ios - 坚持以编程方式将目标添加到按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39815352/