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

本文详细介绍了在iOS应用中如何通过设置`userInteractionEnabled`属性和使用`UITapGestureRecognizer`来实现单击事件,以及如何通过`UILongPressGestureRecognizer`实现长按事件。同时提供了一个自定义视图类的例子,展示如何在`view`的方法中自定义触摸事件处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先需要声明的是: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就可以了 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值