How can I determine if a UILabel was touched?

前端 未结 6 1213
天命终不由人
天命终不由人 2020-12-25 08:39

I am trying to determine if a UILabel was touched and if so do something. Give ..

.
.
.
UILabel * site = [[UILabel alloc] initWithFrame:CGRectMake(0, 185, 32         


        
6条回答
  •  一生所求
    2020-12-25 09:12

    Another late answer ...

    Like @Kevin Sylvestre suggests, you can test for the touch over a UILabel by overriding -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event in your view controller.

    However, rather than testing if the touch is located with the rect of the UILabel, I find it easier to test if the touch was on the 'view' of UILabel (remember UILabel inherits from UIView).

    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
        [super touchesBegan:touches withEvent:event];
    
        NSSet *touchedViews = [touches valueForKeyPath:@"view"];
        if ([touchedViews containsObject:self.myLabel]) {
            // do something
        }
    }
    

    This technique can easily be applied to other interface objects that inherit from UIView.

    Also, it is also necessary for the UILabel to have 'user interaction enabled' to react to the touch event. This can be done in Interface Builder (Attributes Inspector > View > User Interaction Enabled) or programatically - eg: self.myLabel.userInteractionEnabled = YES;

提交回复
热议问题