2018年1月9日 星期二

在段落中某些特定文字加入連結

  • 只有UITextView可以做到。
  • 要實作UITextViewDelegate
self.linkTextView.delegate = self; 

#pragma mark - UITextViewDelegate
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(nonnull NSURL *)URL inRange:(NSRange)characterRange {
     //可以做些判斷
    return YES;
}

  • 加入某段文字 
NSString *str = @"For help please visit our Knowledge base";
    NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:str];
    [attrStr addAttribute:NSLinkAttributeName value:[NSURL URLWithString:@"https://yourUrl.com"] range:[str rangeOfString:@"Knowledge base"]];
    self.linkTextView.attributedText = attrStr;
  
  • 整段文字
NSDictionary *dictAttr = @{NSLinkAttributeName:[NSURL URLWithString:@"http://yourUrl.com"]};
    NSAttributedString *attrStr = [[NSAttributedString alloc]initWithString:@"please visit our Knowledge base" attributes:dictAttr];
    self.linkTextView.attributedText = attrStr;

沒有留言:

張貼留言