更改由空格分隔的字符串的字体

时间:2016-07-17 10:54:20

标签: ios swift uitextfield

我试图在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

    }

}

2 个答案:

答案 0 :(得分:0)

您创建一个空的属性字符串,但从不在其中安装任何文本。

addAttribute调用apples属性到字符串中的文本。如果您尝试将属性应用于不包含文本的范围,则会崩溃。

您需要将未归因的字符串的内容安装到属性字符串中,然后应用属性。

请注意,您应该移动

sender.attributedText = myMutableString

在你的for循环之外。当您为每个单词添加颜色属性时,没有充分的理由将重复的字符串安装到文本字段。

请注意addAttribute上的Xcode文档中的这一位:

  

如果aRange的任何部分超出了范围,则引发... NSRangeException   接收者的角色结束。

如果你得到一个NSRangeException,那将是你当前代码出了什么问题的线索。请特别注意您收到的错误消息。他们通常会提供关于出错的重要线索。

答案 1 :(得分:0)

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

var myMutableString = NSMutableAttributedString()

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

另一个是i.characters.count。当您要使用的API基于Character的行为时,您不应使用基于NSString的位置和计数。使用基于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
    }
}

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