gpt4 book ai didi

ios - 更改以空格分隔的字符串的字体

转载 作者:行者123 更新时间:2023-11-30 13:14:09 25 4
gpt4 key购买 nike

我试图在 UITextField 中将单词以空格分割为绿色,有点像编写新 iMessage 时的工作方式。我注释掉了导致运行时错误的代码部分。如果您有任何想法,请告诉我:

func textChanged(sender : UITextField) {

var myMutableString = NSMutableAttributedString()

let arr = sender.text!.componentsSeparatedByString(" ")

var c = 0

for i in arr {

/*

myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.greenColor(), range: NSRange(location:c,length:i.characters.count))

sender.attributedText = myMutableString

*/

print(c,i.characters.count)

c += i.characters.count + 1

}

}

最佳答案

您的代码至少有两个部分需要修复。

var myMutableString = NSMutableAttributedString()

这一行创建一个空的NSMutableAttributedString。对内容的任何访问都可能导致运行时错误。

另一个是i.characters.count。当您要使用的 API 基于 NSString 的行为时,您不应使用基于 Character 的位置和计数。使用基于 UTF-16 的计数。

还有一点,这并不重要,但您应该为变量使用有意义的名称。

所以,全部包括:

func textChanged(sender: UITextField) {
let text = sender.text ?? ""
let myMutableString = NSMutableAttributedString(string: text)
let components = text.componentsSeparatedByString(" ")
var currentPosition = 0
for component in components {
myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.greenColor(), range: NSRange(location: currentPosition,length: component.utf16.count))
sender.attributedText = myMutableString

print(currentPosition, component.utf16.count)
currentPosition += component.utf16.count + 1
}
}

但是这是否按您的预期工作取决于何时调用此方法。

关于ios - 更改以空格分隔的字符串的字体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38420453/

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