swift - 我的按钮的 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()
}
}
解决方案
改变这个(你需要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)
推荐阅读
- python - 如何找到可以在主题()中调整的内容
- c# - 将实体框架生成的数据库迁移到sqlserver
- go - 用于实现 RTSP 客户端的 Golang 库
- c - 如何在没有 c 中的 api 的情况下从 Google 获取“您的意思是”数据?
- matlab - 查找矩阵的子矩阵组合的最有效方法 [matlab]
- jquery - 用于mailto链接的jquery编码字符串
- python - 检查是否存在具有特定值的行,如果不存在则创建
- php - Where are the templates for the default pages in Silverstripe 4?
- google-apps-script - Google Spreadsheet Apps Script: Dialog box from HTML Service not loading when embedded
- amazon-redshift - AWS Redshift - 无法将外部表合并到本地目录中