【问题标题】:Append attributed string to attributed text of UITextField and keep all it's previous colors and attributes将属性字符串附加到 UITextField 的属性文本并保留它以前的所有颜色和属性
【发布时间】:2017-05-11 17:35:56
【问题描述】:

我正在使用属性字符串在 Swift 中工作。我的问题是如何将属性字符串附加到 UITextField 的属性文本并保留它以前的所有颜色和属性。当我附加新的属性字符串时, UITextField 中的所有先前文本都变为黑色,我不希望这样,我想保留它以前的彩色部分。这是到目前为止的代码:

var newMutableString = NSMutableAttributedString()

if let completionTextHolderText = completionTextHolderText {
    newMutableString = userTextField.attributedText?.mutableCopy() as! NSMutableAttributedString
    let choosenSuggestion = createAttributed(string: completionTextHolderText, with: .blue)
    newMutableString.append(choosenSuggestion)

    let emptySpace = createAttributed(string: " ", with: .black)
    newMutableString.append(emptySpace)
}

userTextField.attributedText = newMutableString.copy() as? NSAttributedString

//-------
    private func createAttributed(string: String, with color: UIColor) -> NSMutableAttributedString {
            let attributedString = NSMutableAttributedString(string: string, attributes: [:])
            attributedString.addAttribute(NSForegroundColorAttributeName,
                                       value: color,
                                       range: NSRange(location: 0, length: string.characters.count))
            return attributedString
    }

感谢您的帮助。

【问题讨论】:

  • 以简单的方式它应该可以工作。但是这个代码statrts时userTextField.attributedText有什么属性,createAttributed()方法有什么作用呢?
  • @AlexShubin - 我编辑了我的问题并添加了createAttributed() 函数。 userTextField.attributedText 可能包含一些蓝色或黑色文本。只有属性是NSForegroundColorAttributeName。比如黑字、黑字、蓝字、黑字、蓝字……等等。顺序不重要。
  • 我的代码现在可以运行了。我认为在您的主要部分之后会发生一些事情并重置范围的属性颜色。请为主要部分发布更多代码
  • 另外,你在任何地方都使用这个“复制”“可变”“类型转换”等东西让事情变得太复杂了,不需要例如你的 createAttributed() 可能应该返回 NSAttributedString 并且可能在一行中看起来像这样: return NSAttributedString(string: string, attributes: [NSForegroundColorAttributeName : color])
  • @AlexShubin - 非常感谢。我将对其进行更多测试,看看我的情况是什么问题。这不是我粘贴的重构代码,我尝试了更多的东西来完成这项工作。我不会留下它,就像它现在被复制一样。

标签: ios swift nsattributedstring


【解决方案1】:

我的代码现在可以运行了。我认为在您的主要部分之前或之后发生了一些事情,并重置了范围的属性颜色。

这里有一些关于如何重构它的想法:

@IBAction func buttonClick(_ sender: UIButton) {

    if let completionTextHolderText = completionTextHolderText,
        let attrStr = userTextField.attributedText {

        let newMutableString = attrStr.mutableCopy() as! NSMutableAttributedString

        newMutableString.append(
            createAttributed(string: completionTextHolderText+" ", with: .blue)
        )

        userTextField.attributedText = newMutableString
    }
}

private func createAttributed(string: String, with color: UIColor) -> NSAttributedString {
    return NSAttributedString(string: string, attributes: [NSForegroundColorAttributeName : color])
}

【讨论】:

  • 是的,在这段代码之前,我正在更改 UITextField 的文本。这是一个问题。
猜你喜欢
  • 2015-06-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-06
  • 2017-04-03
  • 1970-01-01
相关资源
最近更新 更多