【问题标题】:How to remember text attributes in UITextView when the user starts typing用户开始输入时如何记住 UITextView 中的文本属性
【发布时间】:2015-08-11 16:55:38
【问题描述】:

我正在使用UITextView,并尝试在用户键入时使用attributedText 属性显示文本。

这是我当前的代码:

textView.attributedText = NSMutableAttributedString(
    string: "",
    attributes: [
        NSFontAttributeName: UIFont(name: "AvenirNextLTPro-Regular", size: 12.5)!,
        NSForegroundColorAttributeName: UIColor.colorFromCode(0x262626),
        NSKernAttributeName: 0.5,
        NSParagraphStyleAttributeName: paragraphStyle
    ]
)

问题在于,如果您提供一个空字符串,当用户开始输入时,文本不会使用attributedText 属性进行格式化。

但是,我注意到如果我提供一个字符串,当用户开始附加该字符串时,文本会使用attributedText 属性进行格式化。

我认为完成我需要的唯一方法是覆盖此函数并将文本设置为每次用户输入键时的属性:

func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool

没有其他更好的方法吗?

【问题讨论】:

    标签: ios swift uitextview uitextviewdelegate


    【解决方案1】:

    您需要使用typingAttributes 属性,而不是设置一个空的属性字符串。

    textView.typingAttributes = [
        NSFontAttributeName: UIFont(name: "AvenirNextLTPro-Regular", size: 12.5)!,
        NSForegroundColorAttributeName: UIColor.colorFromCode(0x262626),
        NSKernAttributeName: 0.5,
        NSParagraphStyleAttributeName: paragraphStyle
    ]
    

    另请参阅official documentation

    应用于用户输入的新文本的属性。

    【讨论】:

    • 有没有办法用 UILabel 做类似的事情?例如,我有一个没有文本的 UILabel,但是当我解析我的 JSON 时,我正在向其中添加文本
    • @Thomas 恐怕不会。在 UILabel 上,您必须使用 attributedText 属性。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-02
    • 2017-08-09
    • 1970-01-01
    • 2020-09-16
    相关资源
    最近更新 更多