ios - 如何为在 swift 3 中以编程方式定义的按钮设置监听器功能
<p><p>我正在尝试为我的按钮设置监听器功能,但我不断收到错误消息。这是如何做到的:</p>
<pre><code>import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//Create the BackGround
self.view.backgroundColor = UIColor.black
let startButton = UIButton()
startButton.setTitle( " start ", for: UIControlState.normal)
startButton.setTitleColor(UIColor.blue, for: UIControlState.normal)
startButton.frame = CGRect(x: 10, y:40 , width: 250, height: 25)
self.view.addSubview(startButton)
startButton.addTarget(self, action: "buttonPressed:" , for: .touchUpInside)
}
func buttonPressed(sender: UIButton!) {
print("hello")
}
}
</code></pre>
<p>有谁知道我在哪里犯了错误? :) </p></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>你很亲密。只需替换</p>
<pre><code>startButton.addTarget(self, action: "buttonPressed:" , for: .touchUpInside)
</code></pre>
<p>用这个:</p>
<pre><code>startButton.addTarget(self, action: #selector(ViewController.buttonPressed(sender:)) , for: .touchUpInside)
</code></pre></p>
<p style="font-size: 20px;">关于ios - 如何为在 swift 3 中以编程方式定义的按钮设置监听器功能,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/39961299/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/39961299/
</a>
</p>
页:
[1]