UILabel没有响应触摸事件

时间:2013-12-09 06:49:07

标签: ios objective-c 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
   }
}

我能够提前获得活动,但不是今天。我做错了什么?

3 个答案:

答案 0 :(得分:6)

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


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

答案 1 :(得分:2)

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

1)我将以下代码添加到UIScrollView

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

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

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

所有这些都为我提供了我想要的确切功能。

答案 2 :(得分:1)

试试这个

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