一个视图上有多个UITextField

ale*_*ash 2 iphone uitextfield

我对uitextfield有点问题.我在视图中使用其中两个,当我向第二个字段写入内容时,第一个字符串也会被更改.这是我的代码

-(BOOL)textFieldShouldReturn:(UITextField *)textField{

textString = textField.text;
NSLog(@"the string1 %@",textString);
[textField resignFirstResponder];


textString2 = textField2.text;
NSLog(@"the string2 %@",textString2);
[textField2 resignFirstResponder];

return YES;}
Run Code Online (Sandbox Code Playgroud)

所以我需要一些帮助.

Swa*_*uke 11

textFieldShouldReturn为两个字段调用您的方法,因此您需要区分每个字段的操作.

为两个文本字段设置标记:

myTextField1.tag = 100;
myTextField2.tag = 101;
Run Code Online (Sandbox Code Playgroud)

并检查方法中的标记textFieldShouldReturn:

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if(textField.tag == 100)
    {
        textString = textField.text;
    }
    else if(textField.tag == 101)
    {
        textString2 = textField.text;
    }

    [textField resignFirstResponder];
}
Run Code Online (Sandbox Code Playgroud)

这里textField是传递给委托的对象,即你点击返回的对象.所以使用它而不是你的IBOutlet对象.

请避免将文本字段命名为textField和textField2,这是一种非常糟糕的编码习惯.

祝好运