ios - 添加到 UILabel 的点击手势识别器不起作用

标签 ios swift

我使用以下代码将手势识别器添加到 UILabel。 Storyboard中的标签已启用用户交互,但当我点击标签时,不会调用 onUserClickingSendToken 方法。

class ViewController: UIViewController, MFMailComposeViewControllerDelegate {

    @IBOutlet weak var tokenDisplay: UILabel!
    var tapGestureRecognizer:UITapGestureRecognizer = UITapGestureRecognizer(target:self, action:  #selector(onUserClickingSendToken(_:)))

    override func viewDidLoad() {
        super.viewDidLoad()
        tapGestureRecognizer.numberOfTapsRequired = 1
        tokenDisplay.addGestureRecognizer(tapGestureRecognizer)
    }

    func onUserClickingSendToken(_ sender: Any)
    {
      ....

最佳答案

初始化 viewDidLoad 中的 tapRecognizer 应该可以做到,因为您在初始化 View 之前以自身为目标

class ViewController: UIViewController, MFMailComposeViewControllerDelegate {

@IBOutlet weak var tokenDisplay: UILabel!
var tapGestureRecognizer:UITapGestureRecognizer!

override func viewDidLoad() {
    super.viewDidLoad()
    tapGestureRecognizer = UITapGestureRecognizer(target:self, action:      #selector(onUserClickingSendToken(_:)))
    tapGestureRecognizer.numberOfTapsRequired = 1
    tokenDisplay.isUserInteractionEnabled = true
    tokenDisplay.addGestureRecognizer(tapGestureRecognizer)
}

@objc func onUserClickingSendToken(_ sender: Any)
{
  ....

关于ios - 添加到 UILabel 的点击手势识别器不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41772783/

相关文章:

ios - 选择文本和更改属性错误?

使用 Swift 4 从 HTML 数据到 JSON 到字符串

ios - 如何为 iOS 构建杂志应用程序

ios - dateFormat 错误返回 nil

ios - 具有非标准化数据的 Realm 迁移

iphone - 在编译器中为 NSLog 设置一个标志不显示

ios - 如何使用 RxSwift 管理绑定(bind)到 TableViewCell 的树状数据模型

objective-c - XCode - UIScrollView 分页不显示 subview (自动布局?)

ios - 是否可以从 Storyboard预览中截取屏幕截图?

ios - 构建具有多个目标的框架