UITextField 屬性和代理事件

1.使用代理事件時,首先要在視圖控制器的.h文件中聲明遵守UITextFieldDelegate協議,然後纔可以實現代理事件

2.textField.delagate = self;

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //初始化一個textField並設置他的大小
    UITextField *textField = [[UITextField alloc]initWithFrame:CGRectMake(100, 100, 120, 30)];
    
    //邊框樣式
    textField.borderStyle = UITextBorderStyleBezel;
    
    //背景顏色
    textField.backgroundColor = [UIColor orangeColor];
    //設置背景
    textField.background = [UIImage imageNamed:@"1.jpg"];
    
    //再次編輯就清空
    textField.clearsOnBeginEditing = YES;
    //刪除按鈕
    textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    //文字自適應
    textField.adjustsFontSizeToFitWidth = YES;
    
    //設置鍵盤樣式
    //textField.keyboardType = UIKeyboardTypeNumberPad;
    
    //密碼輸入
    //textField.secureTextEntry = YES;
    //return按鈕樣式
    textField.returnKeyType = UIReturnKeyDone;
    textField.delegate = self;
    
    [self.view addSubview:textField];
}

//限制文本輸入的長度
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if ([textField.text length] >= 6) {
        
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"Error" message:@"密碼爲6位" delegate:self cancelButtonTitle:nil otherButtonTitles:@"確定", nil];
        
            [alertView show];
    }else{
        return YES;
    }

    return YES;
}

//按下return建時隱藏鍵盤
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];//失去焦點
    return YES;
 //called when 'return' key pressed. return NO to ignore.
    
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章