gpt4 book ai didi

ios - 将属性字符串附加到 UITextField 的属性文本并保留其所有以前的颜色和属性

转载 作者:行者123 更新时间:2023-11-28 08:10:30 25 4
gpt4 key购买 nike

我在 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
}

感谢您的帮助。

最佳答案

我现在已经让你的代码工作了。我认为在您的主要部分之前或之后发生了一些事情,并重置了范围的属性颜色。

下面是关于如何重构它的一些想法:

@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])
}

关于ios - 将属性字符串附加到 UITextField 的属性文本并保留其所有以前的颜色和属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43909364/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com