在開發(fā)中經(jīng)常遇到登錄界面 【請(qǐng)同意《隱私協(xié)議》和《隱私內(nèi)容》】 如果使用button、label進(jìn)行拼接十分費(fèi)勁核蘸∥∨矗可以考慮使用UITextView來實(shí)現(xiàn)部分文字跳轉(zhuǎn)的效果。
如圖:image.png
步驟如下:
一客扎、實(shí)現(xiàn)UITextView
-(UITextView *)agreementTF {
if (!_agreementTF) {
_agreementTF = [[UITextView alloc] init];
_agreementTF.editable = NO;
_agreementTF.scrollEnabled = NO;
_agreementTF.selectable = NO;
_agreementTF.backgroundColor = [UIColor clearColor];
_agreementTF.font = kMediumFontOfSize(12);
NSString *fristStr = @"閱讀并同意";
NSString *secondStr = [NSString stringWithFormat:@"《%@會(huì)員服務(wù)協(xié)議》",[XZScreenUnit manager].app_name];
NSString *allStr = [NSString stringWithFormat:@"%@%@",fristStr,secondStr];
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:allStr];
[attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithHexString:@"#999999"] range:[[attributedString string] rangeOfString:fristStr]];
[attributedString addAttribute:NSLinkAttributeName value:@"firstmanager" range:[[attributedString string] rangeOfString:secondStr]];
_agreementTF.attributedText = attributedString;
//設(shè)置點(diǎn)擊部分的文字顏色
_agreementTF.linkTextAttributes = @{NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#03CA82"]};
//為textview添加手勢(shì)
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(addGestureRecognizer:)];
[_agreementTF addGestureRecognizer:tap];
}
return _agreementTF;
}
注意:
1.把UITextView的編輯祟峦、滾動(dòng)、選中都置為NO徙鱼。
2.為textview添加手勢(shì)宅楞,通過關(guān)鍵字區(qū)分點(diǎn)擊事件。上面關(guān)鍵字為firstmanager袱吆,并且確保下面一致厌衙。
3.上面代碼中app_name為獲取app的名字拼接的。
二绞绒、實(shí)現(xiàn)手勢(shì)方法
#pragma mark -- textVeiw 手勢(shì)及自定義方法實(shí)現(xiàn)
- (void)addGestureRecognizer:(UITapGestureRecognizer*)gestureRecognizer {
if ([gestureRecognizer isKindOfClass:[UITapGestureRecognizer class]]) {
CGPoint topLocation = [gestureRecognizer locationInView:self.agreementTF];
UITextPosition *textPosition = [self.agreementTF closestPositionToPoint:topLocation];
NSDictionary *attributes = [self.agreementTF textStylingAtPosition:textPosition inDirection:UITextStorageDirectionBackward];
NSURL *url = attributes[NSLinkAttributeName];
if(url) {
NSString *secondStr = [NSString stringWithFormat:@"《%@會(huì)員服務(wù)協(xié)議》",[XZScreenUnit manager].app_name];
NSRange range = [self.agreementTF.text rangeOfString:secondStr];
[self textViews:self.agreementTF houldInteractWithURL:url inRange:range];
}
}
}
//實(shí)現(xiàn)手勢(shì)里面的方法
- (void)textViews:(UITextView *)textViews houldInteractWithURL:(NSURL*)URL inRange:(NSRange)characterRange{
if ([(NSString *)URL isEqualToString:@"firstmanager"]) {
//此處進(jìn)行網(wǎng)頁界面跳轉(zhuǎn)
}
}
注意:firstmanager關(guān)鍵字要和上面保持一致婶希。