Handling Touch Event in UILabel and hooking it up to an IBAction

后端 未结 4 741
旧巷少年郎
旧巷少年郎 2020-11-30 18:09

Ok, so I have a UILabel created in interface builder that displays some some default text of \"tap to begin\".

When the user taps the UILabel

相关标签:
4条回答
  • 2020-11-30 18:49

    UILabel inherits from UIView which inherits from UIResponder. All UIresponder objects can handle touch events. So in your class file which knows about your view (which contains the UIlabel) implement:

    -(void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event;
    

    In interface builder set the UILabel's tag value. when touches occur in your touchesBegan method, check the tag value of the view to which the tag belongs:

    UITouch *touch = [touches anyObject];
    
    if(touch.view.tag == MY_TAG_VAL)
    label.text = @"new text";
    

    You connect your code in your class file with the UILabel object in interface builder by declaring your UILabel instance variable with the IBOutlet prefix:

    IBOutlet UILabel *label;
    

    Then in interface builder you can connect them up.

    0 讨论(0)
  • 2020-11-30 18:49

    You can use a UIButton, make it transparent, i.e. custom type without an image, and add a UILabel on it (centered). Then wire up the normal button events.

    0 讨论(0)
  • 2020-11-30 18:55

    Swift 3

    You have an IBOutlet

    @IBOutlet var label: UILabel!
    

    In which you enable user interaction and add a gesture recognizer

    label.isUserInteractionEnabled = true
    let tapGesture = UITapGestureRecognizer(target: self, action: #selector(userDidTapLabel(tapGestureRecognizer:)))
    label.addGestureRecognizer(tapGesture)
    

    And finally, handle the tap

    func userDidTapLabel(tapGestureRecognizer: UITapGestureRecognizer) {
      // Your code goes here
    }
    
    0 讨论(0)
  • 2020-11-30 18:57

    Check it out:

    UILabel *label = ...
    label.userInteractionEnabled = YES;
    UITapGestureRecognizer *tapGesture =
          [[UITapGestureRecognizer alloc] initWithTarget:self 
                                                  action:@selector(labelTap)];
    [label addGestureRecognizer:tapGesture];
    

    The trick is to enable user interaction.

    0 讨论(0)
提交回复
热议问题