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被点击了");
}
网友评论