0

UIButton每次我完成编辑时,我都会消失,UITextField我调用该textFieldDidEndEditing:方法,只是让按钮消失。这很好用,除非我切换到另一个文本字段而不单击第一个。因此,例如,我在文本字段 A 上,只需点击文本字段 B,键盘仍然保持不变,按钮也是如此。我不相信有一种方法可以覆盖这样的文本字段切换,只有在所有文本字段都完成编辑时。我错了吗?这是我的代码:

-(BOOL) textFieldShouldBeginEditing:(UITextField *)textField
{
negButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
negButton.frame = CGRectMake(textField.frame.origin.x, textField.frame.origin.y, 37, textField.frame.size.height);
[negButton setAlpha:0];

return YES;
}

-(void) textFieldDidBeginEditing:(UITextField *)textField
{
if ([textField isEditing])
{
    [UIView animateWithDuration:0.3 animations:^
     {
         field = textField;

         CGRect frame = textField.frame;

         frame.size.width -= 40;
         frame.origin.x += 40;

         [negButton setAlpha:1];
         [textField setFrame:frame];
         [self.view addSubview:negButton];
     }];
}
}

-(void) textFieldDidEndEditing:(UITextField *)textField
{
    [UIView animateWithDuration:0.3 animations:^
     {

         CGRect frame = textField.frame;
         frame.size.width += 40;
         frame.origin.x -= 40;

         [negButton setAlpha:0];

         [textField setFrame:frame];
     } 
     ];
}
4

2 回答 2

1

在我看来,您正在调用按钮以显示在

textFieldShouldBeginEditing 

方法,这很好,你正在删除它

textFieldDidEndEditing 

方法,也不错。为什么在切换到另一个文本框时按钮没有消失是因为当您点击该文本框时,在endEditing方法之后立即调用shouldBeginEditing方法,导致按钮在删除后立即重新出现。

这是它应该工作的方式,如果你希望它以不同的方式工作,你将不得不使代码特定于每个文本字段

前任:

- (BOOL)textFieldShouldBeginEditing:(UITextField*)textField
{
    if(textField == myField1)
    {
        //make button appear
    }
    else if(textField == myField2)
    {
        //Something else
    }
}

瞧!

于 2012-04-04T23:14:00.197 回答
0

这里的问题是您的委托方法被调用的顺序。

假设您要从 textField1 转到 textField2。

一旦 textField1 已经处于活动状态并且您单击 textField2,它们就会像这样被调用:

textFieldShouldBeginEditing (textField2)
textFieldShouldEndEditing   (textField1)
textFieldDidEndEditing      (textField1)
textFieldDidBeginEditing    (textField2)

您正在创建 negButton的,textFieldShouldBeginEditing其中通过在 textField2 旁边创建一个并存储它的引用来覆盖对“旧”按钮(在 textField1 旁边)的引用。接下来,您调用textFieldDidEndEditingtextFieldDidBeginEditing在新按钮上。

您要做的是将当前位于的代码移动textFieldShouldBeginEditing到开头,textFieldDidBeginEditing以便在创建新方法之前,前两种方法作用于适当的按钮。

于 2012-04-05T21:53:31.867 回答