1.通过tag值访问
通过tag放问UItextFiel内的值,首先要设置UITextField的tag值,如下例代码所示:
/添加usernameTextField
_usernameTextField = [[UITextField alloc]initWithFrame:CGRectMake(CGRectGetMaxX(_usernameLabel.frame), CGRectGetMinY(_usernameLabel.frame), CGRectGetWidth(_usernameLabel.frame) + 150, CGRectGetHeight(_usernameLabel.frame))];
_usernameTextField.placeholder = @"用户名/手机号/邮箱";
<span style="background-color: rgb(255, 0, 0);">_usernameTextField.tag = 101;</span>
_usernameTextField.borderStyle = UITextBorderStyleRoundedRect;
[_LoginView addSubview:_usernameTextField];
[_usernameTextField release];
//添加pwdTextField
_pwdTextField = [[UITextField alloc]initWithFrame:CGRectMake(CGRectGetMinX(_usernameTextField.frame), CGRectGetMinY(_pwdLabel.frame), CGRectGetWidth(_usernameTextField.frame), CGRectGetHeight(_usernameTextField.frame))];
_pwdTextField.placeholder = @"请输入密码";
_pwdTextField.borderStyle = UITextBorderStyleRoundedRect;
<span style="background-color: rgb(255, 0, 0);">_pwdTextField.tag = 102;</span>
[_LoginView addSubview:_pwdTextField];
[_pwdTextField release];
然后通过tag值获取UITextField(注意:在此获取UITextField时,只能是与usernameTextField和pwdTextField同级的<span style="background-color: rgb(255, 0, 0);">父视图</span>才可以)
如下代码:
//-(void)login:(UIButton *)sender;是button的触发事件
<pre name="code" class="objc">-(void)login:(UIButton *)sender{
// 获取textField的值
UITextField *usernameText = <span style="background-color: rgb(51, 204, 0);">(UITextField *)</span>[[<span style="color:#FF0000;">sender superview</span>] viewWithTag:101];
UITextField *pwdText = <span style="background-color: rgb(51, 204, 0);">(UITextField *)</span>[[<span style="color:#FF0000;">sender superview</span>] viewWithTag:102];
if ([usernameText.text isEqualToString:@"sdfg"] && [pwdText.text isEqualToString:@"123456"]) {
UIAlertView *alter = [[UIAlertView alloc]initWithTitle:@"提示" message:@"欢迎回来" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
[alter show];
}else{
UIAlertView *alter = [[UIAlertView alloc]initWithTitle:@"提示" message:@"用户名或密码错误,请重新输入" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
[alter show];
}
}
2.通过属性访问UitextField的值
首先设置属性:
@property(nonatomic,retain)UITextField *usernameTextField;
@property(nonatomic,retain)UITextField *pwdTextField;
其次通过属性访问UITextField内的值<pre name="code" class="objc">if ([<span style="background-color: rgb(255, 0, 0);">_usernameTextField.text</span> isEqualToString:@"sdfg"] && [<span style="background-color: rgb(255, 0, 0);">_pwdTextField.text</span> isEqualToString:@"123456"]) {
UIAlertView *alter = [[UIAlertView alloc]initWithTitle:@"提示" message:@"欢迎回来" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
[alter show];
}else{
UIAlertView *alter = [[UIAlertView alloc]initWithTitle:@"提示" message:@"用户名或密码错误,请重新输入" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
[alter show];
}