Limit the length of the input problem, here is the perfect solution!
Create a TextField and a button first.
| 12345678910111213141516171819202122232425262728293031323334353637383940414243 |
#import "ViewController.h"@interfaceViewController ()<UITextFieldDelegate> { UITextField *currentTextFeild; UIButton *touchButton;}@end @implementationViewController- (void)viewDidLoad { [superviewDidLoad]; // Do any additional setup after loading the view, typically from a nib. UITextField *textFields = [[UITextField alloc] initWithFrame:CGRectMake(15, 50, self.view.bounds.size.width-15*2, 40)]; textFields.backgroundColor = [UIColor brownColor]; textFields.layer.cornerRadius = 5; textFields.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 40)]; textFields.leftViewMode = UITextFieldViewModeAlways;//这两行是为了不让Text太贴textField的左边 textFields.placeholder = @"请输入手机号"; textFields.delegate = self; [self.view addSubview:textFields]; currentTextFeild = textFields; UIButton *enableButton = [UIButton buttonWithType:UIButtonTypeCustom]; enableButton.frame = CGRectMake(15, 100, self.view.bounds.size.width-15*2, 40); enableButton.layer.cornerRadius = 5; enableButton.backgroundColor = [UIColor grayColor]; [enableButton setTitle:@"没内容不可点击"forState:UIControlStateNormal]; [enableButton setTitle:@"可以按了"forState:UIControlStateSelected]; [enableButton setTitle:@"按下去了"forState:UIControlStateHighlighted]; enableButton.enabled = NO; [enableButton addTarget:selfaction:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:enableButton]; touchButton = enableButton;}- (void)btnClick { } |
Setting up the TextField agent
| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657 |
#pragma mark - UITextFieldDelegate- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField { returnYES;}- (void)textFieldDidEndEditing:(UITextField *)textField { }- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString*)string { //用来判断是否可以继续输入, - range.length是为了判断是否可以删除 NSIntegercurrentLength = textField.text.length - range.length + string.length; if(currentLength > 11) { returnNO; } //判断按钮是否可以enable = YES if (currentTextFeild.text && currentTextFeild.text.length > 0 && currentLength > 0) { touchButton.enabled = YES; touchButton.selected = YES; }else { touchButton.enabled = NO; touchButton.selected = NO; } if(currentLength <= 0) { touchButton.enabled = NO; touchButton.selected = NO; } returnYES;}- (BOOL)textFieldShouldClear:(UITextField *)textField { if(currentTextFeild.tag == 11 || currentTextFeild.tag == 12) { //手机号 touchButton.enabled = NO; touchButton.selected = NO;; } returnYES;}- (BOOL)textFieldShouldReturn:(UITextField *)textField { [textField resignFirstResponder]; returnYES;} |
As long as there is a basic, almost can see understand ...
Ios-uitextfield Limit Input Length