动画UIButton变得隐藏和隐藏

时间:2012-04-04 22:50:22

标签: objective-c animation uibutton

所以,我有一个UIButton,当UITextField处于编辑模式时,会隐藏和取消隐藏。问题是,它完全改变(从隐藏到未隐藏),但没有动画。我已经尝试了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的答案)

1 个答案:

答案 0 :(得分: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];
}

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

干杯!