如何让UILabel或UIImageView接受一个单击事件或者其他事件

来源:互联网 发布:网络审查制度的利弊 编辑:程序博客网 时间:2024/06/05 14:40
首先需要声明的是:UILabel或UIImageView的 userInteractionEnabled属性默认为no,也就是说默认不接受事件。

所以方法一:

label.userInteractionEnabled = YES;//设置userInteractionEnabled属性为yes。

 

UITapGestureRecognizer *labelTap = [[UITapGestureRecognizer alloc] initWithTarget:selfaction:@selector(labelTap:)];//初始化一个单击手势

[label addGestureRecognizer:labelTap];//给label添加单击手势


如果是添加长按事件,则是UILongPressGestureRecognizer。


方法二:添加一个他们的子类,重写view的touch方法

#import


@interface untitled : UIImageView {

}

@end

#import "untitled.h"


@implementation untitled


- (id)initWithFrame:(CGRect)frame {
    if ((self = [super initWithFrame:frame])) {
        // Initialization code
        self.userInteractionEnabled=YES;
    }
    return self;
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    
}

- (void)dealloc {
    [super dealloc];
}


@end
在touch事件种添加你自己想要的操作就可以了
然后定义自己的image就用untitled就可以了 

0 0
原创粉丝点击