添加目标
所以我知道您可以在按钮上使用 addTarget 像这样:
import UIKit
class ViewController: UIViewController {
func calledMethod(_ sender: UIButton!) {
print("Clicked")
}
override func viewDidLoad() {
super.viewDidLoad()
let btn = UIButton(frame: CGRect(x: 30, y: 30, width: 60, height: 30))
btn.backgroundColor = UIColor.darkGray
btn.addTarget(self, action: #selector(self.calledMethod(_:)), for: UIControlEvents.touchUpInside)
self.view.addSubview(btn)
}
}
这绝对没问题,但我只是想知道是否有另一种方法来检测何时单击某些内容并在单击时运行一些代码。
最佳答案
您可以在 Storyboard 中添加按钮并为其操作创建导出。
@IBAction func buttonAction(_ sender: UIButton) {
//implement your code here
}
关于ios - 是否有与 UIButton 上的 addTarget 不同的选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49739253/