2014-01-24 23 views
3

enter image description hereiOS7的UITextView設置NSLinkAttributeName屬性,但不能點擊

@interface ViewController()<UITextViewDelegate> 


- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"www.google.com"]; 
    NSDictionary *linkDic = @{ NSLinkAttributeName : [NSURL URLWithString:@"http://www.google.com"] }; 
    [str setAttributes:linkDic range:[[str string] rangeOfString:@"www.google.com"]]; 
    _textView.attributedText = str; 
} 


- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange 
{ 
    NSLog(@"=============%@",URL); 
    return YES; 
} 

有什麼錯嗎?

回答

10

在IB>實用程序>屬性檢查器中設置以下內容。值得注意的是UITextView 不能是可編輯的並且啓用鏈接。

UITextView Settings

你也可以做同樣的代碼:

_textView.editable = NO; 
_textView.dataDetectorTypes = UIDataDetectorTypeLink; 
+0

吳丹的吧!非常感謝你! – jxdwinter

+4

也是必要的:textView.selectable需要是YES,否則這將無法正常工作 – Wirsing

+1

感謝您爲此添加gotcha @Wirsing!惱人的是,這意味着用戶也可能意外地選擇了文字... – jowie