這篇博客主要講限制輸入長度的問題,前幾天有人問我這個問題,說限制長度會出現(xiàn)無法刪除問題,于是正好一塊發(fā)出來給大家看看。textField的縮進(jìn),一張背景圖片搞定的事,我這里用了leftView純屬附帶。
好了廢話少說,貼代碼,很簡單,大家一看便知。
//先創(chuàng)建一個textField 和 一個button。
#import "ViewController.h"@interface ViewController ()<UITextFieldDelegate> { UITextField *currentTextFeild; UIButton *touchButton;}@end@implementation ViewController- (void)viewDidLoad { [super viewDidLoad]; // 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 = @"請輸入手機(jī)號"; 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:@"沒內(nèi)容不可點擊" forState:UIControlStateNormal]; [enableButton setTitle:@"可以按了" forState:UIControlStateSelected]; [enableButton setTitle:@"按下去了" forState:UIControlStateHighlighted]; enableButton.enabled = NO; [enableButton addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:enableButton]; touchButton = enableButton;}- (void)btnClick { }
//設(shè)置textField代理
#PRagma mark - UITextFieldDelegate- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField { return YES;}- (void)textFieldDidEndEditing:(UITextField *)textField { }- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { //用來判斷是否可以繼續(xù)輸入, - range.length是為了判斷是否可以刪除 NSInteger currentLength = textField.text.length - range.length + string.length; if (currentLength > 11) { return NO; } //判斷按鈕是否可以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; } return YES;}- (BOOL)textFieldShouldClear:(UITextField *)textField { if (currentTextFeild.tag == 11 || currentTextFeild.tag == 12) { //手機(jī)號 touchButton.enabled = NO; touchButton.selected = NO;; } return YES;}- (BOOL)textFieldShouldReturn:(UITextField *)textField { [textField resignFirstResponder]; return YES;}
大家看了代碼,差不多就明白了。
新聞熱點
疑難解答