UITextField - limit the length of the text not by the number of characters
Is there a way to limit the textbox but not the character count? I would like to stop being able to enter when the end of the field is reached. But since different symbols have different sizes, stopping at a certain count is not a solution. Something like "stop at the end of the line" would be ideal.
it doesn't work for me
+3
source to share
2 answers
What you want to do is not calculate the maximum number of newline characters, calculate its width in points and compare it to the width you want.
[Swift]
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let combinedString = textField.attributedText!.mutableCopy() as NSMutableAttributedString
combinedString.replaceCharactersInRange(range, withString: string)
return combinedString.size().width > textField.bounds.size.width
}
You may need to edit the attributes so that they appear on the same line.
+2
source to share