UILabel未响应触摸事件



我正在使用以下代码来创建我的视图。我的UILabel在滚动视图中。现在我想要自定义标签的touchesBegan方法中的点击事件。但无法获得。

        img1 = [[customLabel alloc] initWithFrame:CGRectMake(0,height ,280,10 )];//
        [img1 setText: [self.answer_set objectAtIndex:i]];
        [img1 setTextAlignment:NSTextAlignmentLeft];
        [img1 setBackgroundColor:[UIColor colorWithRed:127.0f/255.0f green:165.0f/255.0f blue:234.0f/255.0f alpha:1.0f]];
        img1.textColor = [UIColor whiteColor];
        img1.lineBreakMode = NSLineBreakByWordWrapping;
        img1.numberOfLines = 0;
        [img1 sizeToFit];
        img1.contentMode = UIViewContentModeScaleToFill;
        img1.font = [UIFont fontWithName:@"Arial" size:14.0f] ;
        CGFloat labelHeight=[self getStringHeightforLabel:img1];
        NSLog(@"LABEL HEIGHT:: %f",labelHeight);
        //set frame after getting height
        if (labelHeight < 60.0) {
            labelHeight = 60.0;
        }
        [img1 setUserInteractionEnabled:YES];
        img1.tag = 5000;
        img1.frame=CGRectMake(-5,height,285 + 10,labelHeight + 10);
        img1.layer.cornerRadius = 5;

        /** Shadow */
        CALayer *shadowLayer = [[CALayer alloc] init];
        shadowLayer.frame = CGRectMake(-5,height ,img1.frame.size.width,img1.frame.size.height);
        shadowLayer.cornerRadius = 10;
        shadowLayer.backgroundColor = [UIColor blueColor].CGColor;
        shadowLayer.shadowColor = [UIColor colorWithRed:127.0f/255.0f green:165.0f/255.0f blue:234.0f/255.0f alpha:1.0f].CGColor;
        shadowLayer.shadowOpacity = 0.6;
        shadowLayer.shadowOffset = CGSizeMake(0,0);
        shadowLayer.shadowRadius = 5;
        [img1.layer setMasksToBounds:YES];
        [shadowLayer addSublayer:img1.layer];
        [self.ans_labels.layer addSublayer:shadowLayer];
         height += img1.frame.size.height + 15;

并获取事件:

-(void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {
UITouch *touch = [touches anyObject];
NSLog(@"worked",nil);
//[self giveAnswer:touch.view.tag];
if(touch.view.tag == 5000){
     // do here
   }
}

我本来可以早点参加活动,但今天不行。我做错了什么???

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

- (void)labelTap:(UITapGestureRecognizer *)recognize {
}

最后我得到了以下解决方案:

1) 我在UIScrollView中添加了以下代码:

scroll.userInteractionEnabled = YES;
scroll.exclusiveTouch = YES;
scroll.canCancelContentTouches = YES;
scroll.delaysContentTouches = YES; 

2) 我想要一个触摸事件,所以我在自定义类型的UILabel上添加了一个UIButton,背景颜色清晰,边框大小与标签相同。

3) 最后也是最重要的一点,我必须将UIButton添加到UIScrollView

所有这些都给了我想要的功能。

像这样尝试

-(void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {
 [super touchesBegan:touches withEvent:event];
}

最新更新