3

is there a way to limit a textfield but not by character count? I would like to stop the ability to type when the end of the field is reached. But as different characters have different dimensions stopping at a certain count ist not really a solution. Something like "stop at the end of the line" would be perfect.

this doesn't work for me

Max length UITextField

Community
  • 1
  • 1
greg
  • 33
  • 4

2 Answers2

3

What you want to do is instead of calculating the maximum number of characters of the new string, calculate it's width in points and compare it to the width you need.

[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 might need to edit the attributes to get it to render on a single line.

Stephen Furlani
  • 6,794
  • 4
  • 31
  • 60
  • Hey i just implemented it and it seems to work pretty fine. I just had to flip the ">" to "<" at this point "combinedString.size().width > textField.bounds.size.width". Thank you very much. – greg Dec 07 '14 at 19:08
  • @greg no problem! Please up-vote my answer and mark it as accepted! (this goes a long way to getting help in the future) – Stephen Furlani Dec 07 '14 at 19:13
0

Subscribe to controlTextDidChange and calculate the size of the text via

let s = NSString(string: <yourtext>)
let size = s.boundingRectWithSize(<#size: NSSize#>, options: <#NSStringDrawingOptions#>, attributes: <#[NSObject : AnyObject]?#>)

Now you can check if the text is too large.

qwerty_so
  • 35,448
  • 8
  • 62
  • 86
  • Stephen's example to subscribe to `shouldChange...` is definitely the better way. – qwerty_so Dec 07 '14 at 16:25
  • I have a textfield with just one line. I want the user to be able to type untill the end of the line is reached. Will your example work in this case? – greg Dec 07 '14 at 16:27
  • Not directly. `controlTextDidChange` is called after the new char(s) are already added. You could reduce the result, but Stephen's example is better as it informs you that the user is *about* to make a change and you can decide whether it should be allowed. – qwerty_so Dec 07 '14 at 16:33