ios - How do I unable the "Space" Key on the keyboard in Swift? -
i'm creating login system , don't want spaces allowed in username field. instead of check , validating field, want prevent spaces being added.
so, every time user presses spacebar, nothing should happen. how can that? i've seen instagram this.
this code far:
import uikit class viewcontroller: uiviewcontroller, uitextfielddelegate { @iboutlet weak var signup: uibarbuttonitem! @iboutlet weak var navbar: uinavigationbar! @iboutlet weak var usernametext: uitextfield! override func viewdidload() { super.viewdidload() self.navigationcontroller?.navigationbar.clipstobounds = true usernametext.attributedplaceholder = nsattributedstring(string:"typeyourusername", attributes:[nsforegroundcolorattributename: uicolor.whitecolor()]) func textfield(usernametext: uitextfield, shouldchangecharactersinrange range: nsrange, replacementstring string: string) -> bool { if (string == " ") { return false } return true } } override func didreceivememorywarning() { super.didreceivememorywarning() // dispose of resources can recreated. } override func viewwillappear(animated: bool) { usernametext.becomefirstresponder() } override func prefersstatusbarhidden() -> bool { return true } }
yes can it. override uitextfield
delegate method shouldchangecharactersinrange
. , in method check space character. if found return false.
note: don't forget set delegate textfield.
func textfield(textfield: uitextfield, shouldchangecharactersinrange range: nsrange, replacementstring string: string) -> bool { if (string == " ") { return false } return true }
edit: more code
class viewcontroller : uiviewcontroller, uitextfielddelegate { @iboutlet weak var textfield : uitextfield! override func viewdidload() { super.viewdidload() textfield.delegate = self } func textfield(textfield: uitextfield, shouldchangecharactersinrange range: nsrange, replacementstring string: string) -> bool { if (string == " ") { return false } return true } }
here textfield
object iboutlet. means text field control in storyboard , connected variable.
Comments
Post a Comment