iOS中为label添加下划线以及点击事件的方法(上)

iOS开发中经常会遇到要将一段文字添加下划线并且附上点击事件的需求, 默认情况下UILabel是不支持点击事件的,那么怎样才能实现这种效果呢?下面介绍一种简单的方法,代码如下:

- (void)viewDidLoad {
    [super viewDidLoad];
    UILabel *underlineLabel = [[UILabel alloc] initWithFrame:(CGRectMake(100, 50, 150, 30))];
    NSString *textStr = @"$1234567890";
    
    // 下划线
    //注意: NSStrikethroughStyleAttributeName 是添加中划线,这时textStr如果是中文字符则没有效果
    NSDictionary *attribtDic = @{NSUnderlineStyleAttributeName : [NSNumber numberWithInteger:NSUnderlineStyleSingle], NSUnderlineColorAttributeName : [UIColor redColor]};
    NSMutableAttributedString *attribtStr = [[NSMutableAttributedString alloc]initWithString:textStr attributes:attribtDic];
    
    //赋值
    underlineLabel.attributedText = attribtStr;
    
    UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(labelClick)];
    
    [underlineLabel addGestureRecognizer:gestureRecognizer];
    underlineLabel.userInteractionEnabled = YES;
    
    [self.view addSubview:underlineLabel];
}

- (void)labelClick {
    NSLog(@"underlineLabel被点击了");
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 175,335评论 25 709
  • 小时候,至少是参加工作之前,我很少受到来自家庭的鼓励和肯定,印象中都是不满意的脸不屑的指责我粗心大意浮躁不踏实,这...
    玉镯少艾阅读 741评论 0 0
  • 我们的父母,是世间最大的福田,佛是出世间最大的福田。 以前佛在世的时候,有一年遇到饥饿灾荒,许多人都饿死了,到处都...
    本自清净阅读 3,369评论 0 0