【问题标题】:How to get UILabel to respond to tap?如何让 UILabel 响应点击?
【发布时间】:2011-11-01 12:45:42
【问题描述】:

我发现我可以比 UITextField 更快地创建 UILabel,并且我计划大部分时间将 UILabel 用于我的数据显示应用程序。

长话短说,我希望让用户点击 UILabel 并让我的回调响应它。这可能吗?

谢谢。

【问题讨论】:

  • 您需要指定userInteractionEnabled = true

标签: ios ipad uilabel


【解决方案1】:

您可以将UITapGestureRecognizer 实例添加到您的UILabel。

例如:

UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(labelTapped)];
tapGestureRecognizer.numberOfTapsRequired = 1;
[myLabel addGestureRecognizer:tapGestureRecognizer];
myLabel.userInteractionEnabled = YES;

【讨论】:

  • 啊哈,这里的“userInteractionEnabled”属性是关键(因为其他配置可以而且应该最好在情节提要中设置)。标签默认关闭交互,以便通过它们传递触摸 - 但在这种情况下,它们需要观察触摸以激活手势识别器。谢谢!
  • 不错的一个!我只是在标签上轻按一下,完全忘记了启用用户交互。谢谢!
【解决方案2】:

如果您使用情节提要,您可以在情节提要中完成整个过程,而无需额外的代码。向情节提要添加标签,然后向标签添加点击手势。在“实用程序”窗格中,确保为标签选中“已启用用户交互”。从点击手势(在情节提要中视图控制器的底部),ctrl+单击并拖动到您的 ViewController.h 文件并创建一个动作。然后在 ViewController.m 文件中实现动作。

【讨论】:

  • 方法也可单独使用界面生成器,无需故事板
  • 确保在 Attributes 检查器的 View 部分下选中了“User Interaction Enabled”,而不仅仅是 Accessibility Traits。
【解决方案3】:

Swift 3.0

初始化tempLabel的手势

tempLabel?.text = "Label"
let tapAction = UITapGestureRecognizer(target: self, action: #selector(self.actionTapped(_:)))
tempLabel?.isUserInteractionEnabled = true
tempLabel?.addGestureRecognizer(tapAction)

动作接收器

func actionTapped(_ sender: UITapGestureRecognizer) {
    // code here
}

Swift 4.0

初始化tempLabel的手势

tempLabel?.text = "Label"
let tapAction = UITapGestureRecognizer(target: self, action:@selector(actionTapped(_:)))
tempLabel?.isUserInteractionEnabled = true
tempLabel?.addGestureRecognizer(tapAction)

动作接收器

func actionTapped(_ sender: UITapGestureRecognizer) {
    // code here
}

【讨论】:

  • 如何从发件人对象中获取标签文本?或者说如何识别发件人?
  • Swift 4 版本有@selector 而不是#selector。
【解决方案4】:

Swift 2.0:

我正在添加一个 nsmutable 字符串作为 sampleLabel 的文本,启用用户交互,添加一个点击手势并触发一个方法。

override func viewDidLoad() {
    super.viewDidLoad()

    let newsString: NSMutableAttributedString = NSMutableAttributedString(string: "Tap here to read the latest Football News.")
    newsString.addAttributes([NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleDouble.rawValue], range: NSMakeRange(4, 4))
    sampleLabel.attributedText = newsString.copy() as? NSAttributedString

    let tapGesture: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "tapResponse:")
    tapGesture.numberOfTapsRequired = 1
    sampleLabel.userInteractionEnabled =  true
    sampleLabel.addGestureRecognizer(tapGesture)

}
func tapResponse(recognizer: UITapGestureRecognizer) {
    print("tap")
}

【讨论】:

    【解决方案5】:

    您可以改用 UIButton 并将文本设置为您想要的。如果您不想,按钮不必看起来像按钮

    【讨论】:

    • 关于这一点,我一直遇到 UIButton 左对齐多行文本的问题。即使我将左对齐设置为居中,它仍然会发生。
    • 我确实尝试了 UIButton,它非常好。只是多行按钮有问题。谢谢。
    【解决方案6】:

    在 UILable 上添加 Tap 手势

    UITapGestureRecognizer *tapAction = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(lblClick:)];
    tapAction.delegate =self;
    tapAction.numberOfTapsRequired = 1;
    
    //Enable the lable UserIntraction
    lblAction.userInteractionEnabled = YES;
    [lblAction addGestureRecognizer:tapAction];   
    

    并评估选择器方法

    - (void)lblClick:(UITapGestureRecognizer *)tapGesture {
    
    }
    

    注意:在 .h 文件中添加 UIGestureRecognizerDelegate

    【讨论】:

      【解决方案7】:

      Swift 版本: var tapGesture : UITapGestureRecognizer = UITapGestureRecognizer()

      然后在viewDidLoad()里面,添加这个:

        let yourLbl=UILabel(frame: CGRectMake(x,y,width,height)) as UILabel!
      
          yourLbl.text = "SignUp"
          tapGesture.numberOfTapsRequired = 1
          yourLbl.addGestureRecognizer(tapGesture)
          yourLbl.userInteractionEnabled = true
          tapGesture.addTarget(self, action: "yourLblTapped:")
      

      【讨论】:

        【解决方案8】:

        如果您想在按钮中使用多行文本,请创建一个带有多行文本的 UILabel,并将其作为子视图添加到您的按钮中。

        例如:

        yourLabel=[Uilabel alloc]init];
        yourLabel.frame=yourButtom.Frame;//(frame size should be equal to your button's frame)
        [yourButton addSubView:yourLabel]
        

        【讨论】:

          【解决方案9】:

          来自阿尔文·乔治的 Swift 3

          override func viewDidLoad() {
              super.viewDidLoad()
              let newsString: NSMutableAttributedString = NSMutableAttributedString(string: "Tap here to read the latest Football News.")
              newsString.addAttributes([NSUnderlineStyleAttributeName: NSUnderlineStyle.styleDouble.rawValue], range: NSMakeRange(4, 4))
              sampleLabel.attributedText = newsString.copy() as? NSAttributedString
          
              let tapGesture: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(ViewController.tapResponse))
              tapGesture.numberOfTapsRequired = 1
              sampleLabel.isUserInteractionEnabled =  true
              sampleLabel.addGestureRecognizer(tapGesture)
          }
          
          func tapResponse(recognizer: UITapGestureRecognizer) {
              print("tap")
          }
          

          【讨论】:

            【解决方案10】:

            这在 Xcode 12 和 Swift 5

            中效果很好
            let tapAction = UITapGestureRecognizer(target: self,action:#selector(actionTapped(_:)))
            
            userLabel?.isUserInteractionEnabled = true
            
            userLabel?.addGestureRecognizer(tapAction)
            

            和动作方法一样-

            @objc func actionTapped(_ sender: UITapGestureRecognizer) {
                    print("tapped")
                }
            

            【讨论】:

              【解决方案11】:

              Swift 版本如下所示:

              func addGestureRecognizerLabel(){
                  //Create a instance, in this case I used UITapGestureRecognizer,
                  //in the docs you can see all kinds of gestures
                  let gestureRecognizer = UITapGestureRecognizer()
              
                  //Gesture configuration
                  gestureRecognizer.numberOfTapsRequired = 1
                  gestureRecognizer.numberOfTouchesRequired = 1
                  /*Add the target (You can use UITapGestureRecognizer's init() for this)
                  This method receives two arguments, a target(in this case is my ViewController) 
                  and the callback, or function that you want to invoke when the user tap it view)*/
                  gestureRecognizer.addTarget(self, action: "showDatePicker")
              
                  //Add this gesture to your view, and "turn on" user interaction
                  dateLabel.addGestureRecognizer(gestureRecognizer)
                  dateLabel.userInteractionEnabled = true
              }
              
              //How you can see, this function is my "callback"
              func showDatePicker(){
                  //Your code here
                  print("Hi, was clicked")
              }
              
              //To end just invoke to addGestureRecognizerLabel() when
              //your viewDidLoad() method is called
              
              override func viewDidLoad() {
                  super.viewDidLoad()
                  addGestureRecognizerLabel()
              }
              

              【讨论】:

                【解决方案12】:

                我个人更喜欢为 UILabel 编写扩展的方法。这是我用的。

                import UIKit
                
                extension UILabel {
                    /**
                     * A map of actions, mapped as [ instanceIdentifier : action ].
                     */
                    private static var _tapHandlers = [String:(()->Void)]()
                
                    /**
                     * Retrieve the address for this UILabel as a String.
                     */
                    private func getAddressAsString() -> String {
                        let addr = Unmanaged.passUnretained(self).toOpaque()
                        return "\(addr)"
                    }
                
                    /**
                     * Set the on tapped event for the label
                     */
                    func setOnTapped(_ handler: @escaping (()->Void)) {
                        UILabel._tapHandlers[getAddressAsString()] = handler
                        let gr = UITapGestureRecognizer(target: self, action: #selector(onTapped))
                        gr.numberOfTapsRequired = 1
                        self.addGestureRecognizer(gr)
                        self.isUserInteractionEnabled = true
                    }
                
                    /**
                     * Handle the tap event.
                     */
                    @objc private func onTapped() {
                        UILabel._tapHandlers[self.getAddressAsString()]?()
                    }
                }
                

                然后您可以在任何 UILabel 实例中像这样使用它:

                myLabel.setOnTapped {
                    // do something
                }
                

                我认为这可能会导致一些内存泄漏,但我还没有确定如何最好地解决它们。

                【讨论】:

                  猜你喜欢
                  • 1970-01-01
                  • 1970-01-01
                  • 2019-02-02
                  • 1970-01-01
                  • 1970-01-01
                  • 2011-01-12
                  • 2016-02-13
                  • 2020-10-07
                  相关资源
                  最近更新 更多