相信大家很多都遇到過這種情況,尤其是在登錄注冊界面,需要同意一個什么什么協議才能繼續往下進行。而這個協議的文字是一個字符串,但是內容的顏色
不同,有時候內容的字體大小
也不同,而且最最重要的一點是這個字符串的一部分是可以響應事件的。
是不是?肯定不少人都遇到過這種情況。
其實,蘋果公司早在ios6的時候,就有了相應的方案。。。。
算了,不啰嗦了,直接上代碼吧!
1.初始化:
寫了一個繼承自UIView
的類,
- (instancetype)initWithFrame:(CGRect)frame{
if (self = [super initWithFrame:frame]) {
_textView = [[UITextView alloc]initWithFrame:self.bounds];
_textView.delegate = self;
_textView.editable = NO;//必須禁止輸入,否則點擊將會彈出輸入鍵盤
_textView.scrollEnabled = NO;//可選的,視具體情況而定
[self addSubview:_textView];
}
return self;
}
2.賦值
聲明一個屬性content
為了傳遞文本內容,重寫它的setter
方法:
- (void)setContent:(NSString *)content {
_content = content;
NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc]initWithString:content];
[attStr addAttribute:NSLinkAttributeName value:@"click://" range:NSMakeRange(6, 9)];
[attStr addAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:20]} range:NSMakeRange(6, 9)];
_textView.attributedText = attStr;
}
將值賦給了textView
。
3.實現協議:
要想讓這段文本可點擊,需要實現UITextView的一個協議方法:
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange{
if ([[URL scheme] isEqualToString:@"click"]) {
NSAttributedString *abStr = [textView.attributedText attributedSubstringFromRange:characterRange];
if (self.eventBlock) {
self.eventBlock(abStr);
}
return NO;
}
return YES;
}
這里我寫了一個block將點擊的部分對應的文字信息傳出去。
4.調用
最后,在controller中調用:
AttributeTouchLabel*label = [[AttributeTouchLabel alloc]initWithFrame:CGRectMake(10, 100, 300, 60)];
label.content = @"您將同意《 巴拉巴拉小魔仙協議 》";
[label returnWithBlock:^(NSAttributedString *abStr) {
NSLog(@"%@",abStr);
}];
[self.view addSubview:label];
附上效果圖:
巴拉巴拉小魔仙
這里的藍色部分是可以響應事件的!點擊后打印的結果:
2017-03-23 16:27:41.749 AttributedStringClick[29792:1371671] 巴拉巴拉小魔仙協議{
NSColor = "UIExtendedSRGBColorSpace 1 0.5 0 1";
NSFont = "<UICTFont: 0x7fc34fd0ee10> font-family: \".PingFangSC-Regular\"; font-weight: normal; font-style: normal; font-size: 20.00pt";
NSLink = "click://";
NSOriginalFont = "<UICTFont: 0x7fc34fe07cc0> font-family: \"Helvetica\"; font-weight: normal; font-style: normal; font-size: 12.00pt";
}