2013-07-15 88 views
2

1)我想添加一个链接到UITextView。我知道如果我在我的文字中加入了像http://stackoverflow.com这样的网址,它会自动被识别为链接。但是有没有一种方法可以让一个词链接,而不仅仅是一个网址?在HTML中一样:<a href="http://stackoverflow.com ">stackoverflow</a>UITextView链接:添加和自定义

2)我想定制这个链接,特别是它的颜色,字体类型等。有没有办法为链接添加属性?

如果这一切都很复杂,您是否看到了更好的方法来轻松实现?

谢谢!

+0

看到这里http://stackoverflow.com/a/21630187/1161906 – bcattle

回答

1

这接缝是不可能做什么,我想与UITextViews(至少不容易)。解决方案是使用UIWebView代替,并加载一个包含文本和链接的本地HTML文件。你甚至可以把一些CSS来定制颜色,尺寸...

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    // Do any additional setup after loading the view from its nib. 

    // webview 
    webview.delegate = (id<UIWebViewDelegate>)self; 
    NSString *path; 
    NSBundle *thisBundle = [NSBundle mainBundle]; 
    path = [thisBundle pathForResource:@"fileName" ofType:@"html"]; 
    NSError *error; 
    NSString *initialHTMLString = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error]; 
    [webview loadHTMLString:initialHTMLString baseURL:nil]; 

    webview.opaque = NO; 
    webview.backgroundColor = [UIColor clearColor]; 
} 


- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { 

    if (navigationType == UIWebViewNavigationTypeLinkClicked) { 

     [[UIApplication sharedApplication] openURL:[request URL]]; 

     return NO; 
    } 

return YES; 

} 

我希望这会帮助任何人有同样的问题!

+0

检查BHUPI的答案在这里,它确实是你想要的:http://stackoverflow.com/questions/2454067/display-html-text-in -uitextview – alasker

0

看看DTCoreText,它提供了一系列不同的视图,您可以使用HTMLish输入并自定义显示和处理。

3

试试这个:

self.myTextView.dataDetectorTypes = UIDataDetectorTypeLink; 
+3

谢谢,但正如我所说的,我不想承认的URL。我想要一个简单的词来形容,如在HTML中:'stackoverflow' –

0
textView.dataDetectorTypes = .link 
textView.isEditable = false 
textView.isSelectable = true 

let html = "<div style=\"font-family: 'Arial'; font-size: 20;\"><a href=\"http://www.stackoverflow.com\">stackoverflow</a></div>" 

if let dataWithHTML = html.data(using: .utf8) { 

    textView.attributedText = try? NSAttributedString(data: dataWithHTML, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue], documentAttributes: nil) 
} 
相关问题