swift3 限制text field只能輸入3個字,無法輸入第4個字(利用到繼承UITextFieldDelegate的方法shouldChangeCharactersIn)

(一) first step inherit the protocol UITextFieldDelegate , then implement the shouldChangeCharactersIn function
 (二) Testview has a property delegate , need to assign “View controller ” as agent

(三)

(replacementString string )
 if string != “” , mean if you input a…z or numbers is ok ,string will has “Value”,but if you press the keyboard “delete” button ,string will become empty

(四)why i need to plus 1 in testview.text!.characters.count ??
 A: when execute the function shouldChangeCharactersIn will first get testview.text!.characters.count = 0 because function shouldChangeCharactersIn has not done yet ,so textview will not show the character until loop “return” ,then textview finally show the character(like: a or 1)

(五)what deferent in return True or False in function shouldChangeCharactersIn ?

  1. if true mean -> you will alow to change the textview.text
  2. if false mean -> you will not alow to change the textview.text

Originally published at swifthao的ios學習紀錄blog.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.