skip to Main Content

I want to add a tab recognizer to a custom .xib file view in my ios swift app. Here’s the code from the owner class of the .xib file:

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")
    }
    
  
}

When I ran the project on a phone simulator, there were no errors.

App Running On The Simulator

But when I clicked the labels that showed up, the message was not printed onto the console (meaning that the action was not triggered). What am I doing wrong?

Thank you for your help.

github link to my project:

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

2

Answers


  1. Chosen as BEST ANSWER

    I solved the problem on my own. It seems that I set the owner class of the .xib file to inherit from a UILabel. When I changed the superclass to the generic UIView, everything worked out perfectly! I don't really understand how this fixed the problem, but my theory is that previously, the owner class relegated the UIGesture event to the UILabel class instead of itself, thus not triggering the bound gesture recognizer. Now That I diverted that to the owner class, there's no such problem.

    So for anyone else who has my problem- set the owner class' superclass to the generic UIView if possible?

    Thanks again to Furkan Kaplan for his help.


  2. When you use WordLabel custom UILabel with xib, init(frame:) constructor is not called. init(coder:) is called instead. Because of that, your gesture recognizer doesn’t work. You must to move the gesture recognizer assignment to commonInit() method.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search