【问题标题】:how to set a UITextView's text to be bolded and not clickable如何将 UITextView 的文本设置为粗体且不可点击
【发布时间】:2014-02-27 09:34:28
【问题描述】:

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

是我的身体作为笔记

<a href="/arc/item/21">food item - more item stuff</a>;`

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

【问题讨论】:

    标签: ios textkit


    【解决方案1】:

    更新(使用UITextView's 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";
    

    正如您在 cmets 中看到的,我无法为 linkTextAttributes 设置新字体,尽管颜色属性按预期工作。

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


    以前的(替代解决方案)

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

    请参阅: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;
    ...
    

    【讨论】:

    • 谢谢 Damir - 我可能问了一个糟糕的问题。我的错 - 我真正想做的只是将该链接压缩为粗体。不单独处理链接。有什么方法可以告诉它处理链接-> 使用 linksWithAttributes 加粗。我在代码中做这一切 - 这是原因之一,这有点问题。将有数百个。
    • linksWithAttributes: 你这是什么意思?我不记得这种方法了。如果我错了,请纠正/参考我。
    • 感谢 Damir - 需要睡觉了;我现在是凌晨 3 点。最好的
    • 是的,它在 UITextView 文档developer.apple.com/library/ios/documentation/uikit/reference/… 中,但实际上没有关于它的信息
    • @timpone 查看我的更新
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-31
    • 1970-01-01
    • 1970-01-01
    • 2015-11-20
    • 2013-12-16
    • 2014-09-21
    • 1970-01-01
    相关资源
    最近更新 更多