UITextview 給給定的字串新增link屬性 指定字串新增點選方法
- (void)viewDidLoad {
[superviewDidLoad];
//XIB 拖控制元件textview 要將其link 屬性勾選上
//textview設定代理非編輯狀態下才可以連線url
self.textview.delegate =self;
self.textview.editable =NO;
[selftestAttribute];
}
//給字串新增屬性
-(void)testAttribute{
NSMutableAttributedString *attStr0 = [[NSMutableAttributedString
NSMutableAttributedString *attStr1 = [[NSMutableAttributedStringalloc]initWithString:@"----今天"attributes:@{NSForegroundColorAttributeName:[UIColorpurpleColor],NSFontAttributeName:[UIFontsystemFontOfSize
[attStr1 addAttribute:NSLinkAttributeNamevalue:[NSStringstringWithFormat:@"http://www.baidu.com"]range:NSMakeRange(0, attStr1.length)];
[attStr0 appendAttributedString:attStr1];
NSMutableAttributedString *attStr2 = [[NSMutableAttributedStringalloc]initWithString:@"----天氣真好!"attributes
[attStr0 appendAttributedString:attStr2];
self.textview.attributedText = attStr0;
}
//textview代理事件
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange{
if ([URL.absoluteStringisEqualToString:@"http://www.baidu.com"]) {
//點選attStr連線會觸發此代理方法
//新增點選事件
returnYES;
}
returnNO;
}