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.
    
}



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