swift - How can I declare that a text field can only contain an integer? -
in swift, trying create text field allow button enabled, when text field contains integer. how can this?
make view controller uitextfielddelegate adding uitextfielddelegate class declaration. add iboutlets text field , button. in viewdidload set button's enabled property false , set self textfield.delegate. implement textfield:shouldchangecharactersinrange:replacementstring: method. method called every time text field edited. in there, check if current text field converts int calling toint() , enable/disable button desired.
here code:
class viewcontroller: uiviewcontroller, uitextfielddelegate { @iboutlet weak var textfield: uitextfield! @iboutlet weak var button: uibutton! override func viewdidload() { super.viewdidload() button.enabled = false textfield.delegate = self } func textfield(textfield: uitextfield, shouldchangecharactersinrange range: nsrange, replacementstring string: string) -> bool { // find out text field after adding current edit allow text = (textfield.text nsstring).stringbyreplacingcharactersinrange(range, withstring: string) if allow intval = text.toint() { // text field converted int button.enabled = true } else { // text field not int button.enabled = false } // homecoming true text field changed homecoming true } } text swift int uitextfield textfield
No comments:
Post a Comment