Coucou Coucou - 5 months ago 15
Swift Question

Textfield add a character in the end after I add attributedText for the textfield in swift

I want to add

attributedText
to a
textfield
.

My code:

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
}


When I taped
'a'
in the
textfield
, I can check out
Abraham
in the
emailArray
, after I set
attributedText
of
Abraham
to the
textfield
.
But There is a problem, the result of
textfield
show
Abrahama
, the
textfield
add a
'a'
in the end automatic...how can I delete the
'a'
?Thank you

Answer

After the line textField.attributedText = attributedText add

return false
Comments