当我之前创建一个按钮时,它能够成为一个"action“IBA函数。
我如何用标签创建相同的东西?因此,当我单击标签时,我的应用程序将转到一个新页面。(我怎样才能转到一个新的页面呢?我是否必须创建一个全新的视图,并以某种方式将其与之相关联?)
请不要忘记,我是一个全新的swift新手,并且已经开始了我的程序,但它是来自几个教程的片段,因此我可能很难在第一时间理解你的答案。
发布于 2015-10-30 14:59:00
您可以使用UITapGestureRecognizer来完成此操作,下面是一个简单的示例:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let label = UILabel(frame: CGRectMake(0, 0, 200, 21))
label.center = CGPointMake(160, 284)
label.textAlignment = NSTextAlignment.Center
label.userInteractionEnabled = true
label.text = "I'am a test label"
self.view.addSubview(label)
let gestureRecognizer = UITapGestureRecognizer(target: self, action: "handleTap:")
label.addGestureRecognizer(gestureRecognizer)
}
func handleTap(gestureRecognizer: UIGestureRecognizer) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("next")
self.presentViewController(vc, animated: true, completion: nil)
}
}结果:

有关详细信息,请参阅Project sample。
发布于 2018-02-06 02:17:13
Swift 3
1-确保在属性检查器中选中了"User Interaction Enabled“。
2-代码:
let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(YourVC.labelTapped))
yourLabel.addGestureRecognizer(gestureRecognizer)3-使用函数:
func labelTapped() {
print("labelTapped tapped")
}https://stackoverflow.com/questions/33430270
复制相似问题