UILabel文字可點選
TTTAttributedLabel 庫地址 https://github.com/TTTAttributedLabel/TTTAttributedLabel
#import "ViewController.h"
@interfaceViewController () <TTTAttributedLabelDelegate>
@end
@implementation ViewController
- (void)viewDidLoad {
[superviewDidLoad];
TTTAttributedLabel *label = [[TTTAttributedLabelalloc
label.font = [UIFontsystemFontOfSize:14];
label.textColor = [UIColorblackColor];
label.lineBreakMode = NSLineBreakByCharWrapping;
label.numberOfLines = 0;
//設定高亮顏色
label.highlightedTextColor = [UIColorgreenColor];
//檢測url
label.enabledTextCheckingTypes =
//對齊方式
label.verticalAlignment = TTTAttributedLabelVerticalAlignmentCenter;
//行間距
label.lineSpacing = 8;
//設定陰影
label.shadowColor = [UIColorgrayColor];
label.delegate = self; // Delegate
//NO 不顯示下劃線
label.linkAttributes = [NSDictionarydictionaryWithObject:[
NSString *text = @"冷清風 讚了 王戰 的說說";
[label setText:text afterInheritingLabelAttributesAndConfiguringWithBlock:^ NSMutableAttributedString *(NSMutableAttributedString*mutableAttributedString)
{
//設定可點選文字的範圍
NSRange boldRange = [[mutableAttributedString string] rangeOfString:@"冷清風"options:NSCaseInsensitiveSearch];
//設定可點選文字的的大小
UIFont *boldSystemFont = [UIFont boldSystemFontOfSize:16];
CTFontRef font = CTFontCreateWithName((__bridgeCFStringRef)boldSystemFont.fontName, boldSystemFont.pointSize, NULL);
if (font) {
//設定可點選文字的大小
[mutableAttributedString addAttribute:(NSString *)kCTFontAttributeName value:(__bridge id)font range:boldRange];
//設定可點選文字的顏色
[mutableAttributedString addAttribute:(NSString*)kCTForegroundColorAttributeNamevalue:(id)[[UIColorblueColor] CGColor] range:boldRange];
CFRelease(font);
}
return mutableAttributedString;
}];
//正則
NSRegularExpression *regexp = NameRegularExpression();
NSRange linkRange = [regexp rangeOfFirstMatchInString:text options:0range:NSMakeRange(0, 3)];
NSURL *url = [NSURLURLWithString:[NSStringstringWithFormat:@"http://www.exiucai.com/"]];
//設定連結的url
[label addLinkToURL:url withRange:linkRange];
[self.view addSubview:label];
}
- (void)attributedLabel:(__unused TTTAttributedLabel *)label
didSelectLinkWithURL:(NSURL *)url
{
NSLog(@"click點選");
}