ios - Need explanation of UITextField max length implementation -
so implemented solution limit size of uitextfield in following link max length uitextfield however, cannot understand why must use
var newlength = countelements(textfield.text) + countelements(string) - range.length return !(newlength > 5)
instead of initial solution of
var newlength = countelements(textfield.text) return !(newlength > 4)
both solutions limit string size 5 digits in uitextfield, first solution allows user use backspace delete characters, second solution (my initial solution) not allow user use backspace delete characters. can please explain?
assuming snippets in question extracted uitextfielddelegate
method:
textfield(textfield: uitextfield, shouldchangecharactersinrange range: nsrange, replacementstring string: string) -> bool
the problem becomes pretty clear when realize apple tries make method names plain-english readable. method called should change characters. verb tense of method name implies method called before text field's characters changed. , returns bool
. it's asking whether or not should change characters.
importantly, means whatever textfield.text
is, hasn't taken account change user attempting make yet. equally important, method called when user pressing delete/backspace key when user selected range of text , pasting new in.
so, why second method fail in scenarios?
your goal assure maximum length number of characters, correct? if press backspace key, our delegate method called range of last index , length of 1 (we're deleting last character), , string
argument emptry string: ""
. if return true
, string's length 1 character shorter.
but keep in mind, textfield.text
still holds same value did before user pressed button @ point. approach @ length, see string @ maximum length, , disallow changes because approach assumes call shouldchangecharactersinrange
means length in increasing, isn't case.
the alternate approach calculates length would be if return true
method , based on that calculation, returns true or false appropriately.
effectively, length
part of range
variable number of characters user removing textfield.text
, , length
part of string
variable number of characters user adding textfield.text
.
Comments
Post a Comment