如何将UITextView的文本设置为粗体而不是可点击的

tim*_*one 0 ios textkit

我在a中有以下HTML,UITextView并希望将其呈现为UITextView

是我注意的身体

<a href="/arc/item/21">food item - more item stuff</a>;`
Run Code Online (Sandbox Code Playgroud)

让我补充一点:它目前显示为蓝色并带下划线且无法点击.我想把它加粗而不是可点击的.我已经阅读过有关文档的内容,linkTextAttributes但是,没有使用它,它有点超出我的范围,我真的没有看到任何简单的方法来操纵它.我如何才能将上面的链接渲染为粗体和黑色(不是蓝色)并保持不可点击的性质?

dam*_*hec 5

UPDATE(使用UITextView的linkTextAttributes的解决方案)

self.testTextView.editable = NO;
self.testTextView.selectable = YES;
self.testTextView.userInteractionEnabled = NO;  // workaround to disable link - CAUTION: it also disables scrolling of UITextView content
self.testTextView.dataDetectorTypes = UIDataDetectorTypeLink;
self.testTextView.linkTextAttributes = @{NSFontAttributeName : [UIFont boldSystemFontOfSize:14.0f], // NOT WORKING !?
                                         NSForegroundColorAttributeName : [UIColor redColor]};

...

self.testTextView.text = @"Lorem ipsum http://www.apple.com Lorem ipsum";
Run Code Online (Sandbox Code Playgroud)

正如您在注释中看到的那样,虽然color属性按预期工作,但我无法将新字体设置为linkTextAttributes.

如果您可以使用颜色属性或其他文本属性来设置URL的样式,并且您不必担心禁用UITextView滚动,那么这可能是您的解决方案.


上一个(替代解决方案)

如果您正在使用Storyboard/xib,请确保已取消选择UITextView的Detection - > Links.您可以通过将其容器字体设置为粗体字来使链接变为粗体.如果要在一个字符串对象中支持不同的文本/字体样式,那么您应该真正寻找NSAttributedString或NSMutableAttributedString.

请参阅:https://developer.apple.com/library/ios/documentation/cocoa/reference/foundation/classes/NSAttributedString_Class/Reference/Reference.html.

示例:

UIFont *linkFont = [UIFont fontWithName:@"SomeBoldTypeface" size:12];
NSString *link = @"food item - more item stuff";

NSMutableAttributedString *someString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"is my body for the note %@; let me ad", link]];
[someString addAttribute:NSFontAttributeName value:linkFont range:NSMakeRange(24, link.length)];

UITextView *textView = [[UITextView alloc] init];
textView.attributedText = someString;
...
Run Code Online (Sandbox Code Playgroud)