【问题标题】:Animation issue of Button in IOSIOS中Button的动画问题
【发布时间】:2017-10-27 12:32:03
【问题描述】:

我在主视图控制器中有三个按钮。当我单击 but1 时,它会执行动画并向右移动,持续时间为特定宽度。当 but1 达到其给定宽度时,它会隐藏并在那里显示 but2。当我点击but2时,它会执行动画并移回but1的相同位置。它就像一个打开和关闭按钮的场景。现在我面临的问题是,当我打开 but1 时,它会移动其给定宽度,当我关闭时,它会移回原来的 but1 位置,现在按钮打开和关闭,但是当我们再次尝试打开时,它不会使用 but1 打开。我希望每当用户单击 but1 时,它应该随着动画向右移动,并且每次用户想要关闭按钮时,它都应该关闭它,而不是只打开或关闭一次。我打开按钮的代码是这样的,

- (IBAction)openHome:(id)sender {

[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.75];
CGAffineTransform transform = CGAffineTransformMakeTranslation(108, 0);
[_openHome setTransform:transform];
[UIView commitAnimations];
[NSTimer scheduledTimerWithTimeInterval:0.75
                                  target:self
                               selector:@selector(targetMethod:)
                               userInfo:nil
                                repeats:NO];

}

-(void)targetMethod:(NSTimer *)myTimer{
_home.hidden=NO;
_openHome.hidden=YES;
_closeHome.hidden=NO;

[myTimer invalidate];

}

关闭按钮就是这个,

- (IBAction)closeHome:(id)sender {
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:2.0];
CGAffineTransform transform = CGAffineTransformMakeTranslation(-110, 0);
[_closeHome setTransform:transform];
[UIView commitAnimations];
[NSTimer scheduledTimerWithTimeInterval:0.75
                                 target:self
                               selector:@selector(targetMethoded:)
                               userInfo:nil
                                repeats:NO];

}

-(void)targetMethoded:(NSTimer *)myTimer{
_home.hidden=YES;
_openHome.hidden=YES;
_closeHome.hidden=NO;

[myTimer invalidate];

}

按钮的打开之前的画面是这个,

按钮打开后的画面,

【问题讨论】:

  • 在“打开”时是否需要整个矩形(带有标签和图标)作为 UIButton?还是只是按钮部分的图标(房屋图像)?

标签: ios objective-c animation


【解决方案1】:

无需使用 CGAffineTransform 来更改位置,而是直接更改按钮框架。还可以使用以下代码,它使用完成处理程序来调用 targetMethod 而不是使用 NSTimer:

[UIView animateWithDuration:0.75 animations:^{
    _openHome.frame = CGRectMake(_openHome.frame.origin.x+110, _openHome.frame.origin.y, _openHome.frame.size.width, _openHome.frame.size.height);
} completion:^(BOOL finished) {
    [self targetMethod];
}];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-19
    • 1970-01-01
    • 2011-10-23
    • 1970-01-01
    • 1970-01-01
    • 2016-12-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多