2

所以,我有一个UIButton,当 aUITextField处于编辑模式时,它会变得隐藏和不隐藏。问题是,它的变化非常好(从隐藏到不隐藏),但没有动画。我已经尝试过setAlpha:了,但这仅在将其 alpha 从 0 设置为 100,而不是从 100 设置为 0 时才有效。到目前为止,这是我的代码:

-(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 setHidden:YES];

return YES;
}

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

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

         [negButton setHidden:NO];
         [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 setHidden:YES];
         [negButton removeFromSuperview];

         [textField setFrame:frame];
     } 
     ];
}

编辑:我解决了这个问题。我只是不必调用该removeFromSuperview函数,我必须从隐藏切换到 alpha。(见下面@David的回答)

4

1 回答 1

1

你的动画有问题。将其更改为以下内容:

-(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]; 
[self.view addSubView:negButton];

return YES;
}

-(void) textFieldDidBeginEditing:(UITextField *)textField
{
if ([textField isEditing])
    {
     CGRect frame = textField.frame;

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

     [UIView beginAnimations:nil context:nil];
     [UIView setAnimationDuration:0.3];
     [negButton setAlpha:1];
     [textField setFrame:frame];
     [UIView commitAnimations];
    }
}

-(void) textFieldDidEndEditing:(UITextField *)textField
{

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

     [UIView beginAnimations:nil context:nil];
     [UIView setAnimationDuration:0.3];
     [negButton setAlpha:0];
     [textField setFrame:frame];
     [UIView commitAnimations];

     [self performSelector:@selector(removeBtn) withObject:negButton afterDelay:0.3];
}

- (void)removeBtn:(UIButton*)button
{
    [button removeFromSuperView];
}

您正在立即从视图中删除该按钮,而不是在它消失后将其删除。

干杯!

于 2012-04-04T22:59:49.647 回答