【问题标题】:Adding A UIGestureRecognizer To A custom .xib View将 UIGestureRecognizer 添加到自定义 .xib 视图
【发布时间】:2020-11-23 08:22:20
【问题描述】:

我想在我的 ios swift 应用程序的自定义 .xib 文件视图中添加一个标签识别器。以下是 .xib 文件所有者类的代码:

import UIKit

class WordLabel: UILabel {
    
    
    @IBOutlet weak var wordLabel: UILabel!
    @IBOutlet var wordFrame: UIView!

    
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
        

//I added the tab recognizer here
        wordLabel.isUserInteractionEnabled = true
        let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(labelClicked(_:)))
        wordLabel.addGestureRecognizer(gestureRecognizer)

    }
        
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }
        
    func commonInit() {
        
        Bundle.main.loadNibNamed(K.wordLabelNibName, owner: self, options: nil)
        
        addSubview(wordFrame)
        wordFrame.frame = self.bounds
        wordFrame.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        

    }
    
    
    //should happen when label is tapped
    @objc func labelClicked(_ sender: Any) {
        print("UILabel clicked")
    }
    
  
}

当我在手机模拟器上运行项目时,没有出现任何错误。

App Running On The Simulator

但是当我点击显示的标签时,消息没有打印到控制台上(这意味着操作没有被触发)。我做错了什么?

感谢您的帮助。

我的项目的github链接:

https://github.com/ShaungYi/PolyLibrum/blob/main/PolyLibrum/View/BookReader/WordLabel/WordLabel.swift

【问题讨论】:

  • commonInit()中添加手势识别器

标签: ios swift xcode xib


【解决方案1】:

当您将 WordLabel 自定义 UILabel 与 xib 一起使用时,不会调用 init(frame:) 构造函数。 init(coder:) 被调用。因此,您的手势识别器不起作用。您必须将手势识别器分配移动到 commonInit() 方法。

【讨论】:

  • 我已经尝试过了,甚至在两个初始化函数中都放入了相同的代码。另外,我从识别器分配当前所在的 init 函数中打印了一些东西,并且消息到达了控制台。这应该意味着分配也得到了执行,问题在于识别器没有响应。但是非常感谢您的反馈。
【解决方案2】:

我自己解决了这个问题。似乎我将 .xib 文件的所有者类设置为从 UILabel 继承。当我将超类更改为通用 UIView 时,一切都很完美!我真的不明白这是如何解决问题的,但我的理论是,以前,所有者类将 UIGesture 事件降级到 UILabel 类而不是自身,因此不会触发绑定手势识别器。现在我把它转移到了所有者类,没有这样的问题。

那么对于遇到我的问题的其他人——如果可能的话,将所有者类的超类设置为通用 UIView?

再次感谢 Furkan Kaplan 的帮助。

【讨论】:

    猜你喜欢
    • 2013-04-07
    • 1970-01-01
    • 1970-01-01
    • 2019-11-08
    • 2012-04-09
    • 2014-02-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多