在我为swift中的textfield添加attributesText后,Textfield最后添加了一个字符

时间:2016-06-23 08:47:05

标签: swift swift2

我想将attributedText添加到textfield

我的代码:

let emailArray = ["Abraham", "John Doe", "John Smith", "Awesome"]

func textField(textField: UITextField!, shouldChangeCharactersInRange range: NSRange, replacementString string: String!) -> Bool
{
    for value in self.emailArray {

        print(value)
        print(textField.text!)

        if(value.lowercaseString.hasPrefix(textField.text! + string))
        {
            print(range.location)
            print(value)
            var attributedText: NSMutableAttributedString = NSMutableAttributedString(string: value)

            //attributedText.addAttributes([NSFontAttributeName: UIFont.boldSystemFontOfSize(14)], range: NSRange(location: 1, length: 6))
            attributedText.addAttributes([NSForegroundColorAttributeName: UIColor.grayColor()], range: NSRange(location: (range.location + 1), length: (value.characters.count - range.location - 1)))

            textField.attributedText = attributedText

            print(textField.text)
        }
    }
    return true
}

当我在'a'中录制textfield时,在设置Abraham emailArray之后,我可以在attributedText中查看Abrahamtextfield。 但是有一个问题,textfield显示Abrahama的结果,textfield自动添加'a' ...如何删除{{1}谢谢

1 个答案:

答案 0 :(得分:0)

在行textField.attributedText = attributedText添加

之后
return false