iOS開發(fā)中經(jīng)常會遇到要將一段文字添加下劃線并且附上點擊事件的需求, 默認情況下UILabel是不支持點擊事件的,那么怎樣才能實現(xiàn)這種效果呢?下面介紹一種簡單的方法,代碼如下:
- (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被點擊了");
}