Set the maximum character length of a UITextField

前端 未结 30 1709
难免孤独
难免孤独 2020-11-22 02:27

How can I set the maximum amount of characters in a UITextField on the iPhone SDK when I load up a UIView?

30条回答
  •  梦谈多话
    2020-11-22 02:51

    I created this UITextFieldLimit subclass:

    • Multiple textfields supported
    • Set the text length limit
    • Paste prevention
    • Displays a label of left characters inside the textfield, get hidden when you stop editing.
    • Shake animation when no characters left.

    Grab the UITextFieldLimit.h and UITextFieldLimit.m from this GitHub repository:

    https://github.com/JonathanGurebo/UITextFieldLimit

    and begin to test!

    Mark your storyboard-created UITextField and link it to my subclass using the Identity Inspector:

    Identity Inspector

    Then you can link it to an IBOutlet and set the limit(default is 10).


    Your ViewController.h file should contain: (if you wan't to modify the setting, like the limit)

    #import "UITextFieldLimit.h"
    
    /.../
    
    @property (weak, nonatomic) IBOutlet UITextFieldLimit *textFieldLimit; // <--Your IBOutlet
    

    Your ViewController.m file should @synthesize textFieldLimit.


    Set the text length limit in your ViewController.m file:

    - (void)viewDidLoad
    {
        [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
        [textFieldLimit setLimit:25];// <-- and you won't be able to put more than 25 characters in the TextField.
    }
    

    Hope the class helps you. Good luck!

提交回复
热议问题