我想创建一个动画菜单。
- 首先它隐藏在屏幕外
- 当用户点击屏幕时,它会滑入
- 用户可以点击它,它会做一些事情
- 3秒后滑出屏幕
但问题是当我点击它时它没有反应。为什么?
示例代码:所有代码都在我的 UIView 类中。
showing = NO;
box = [[UIView alloc] initWithFrame:CGRectMake(500,-200,200,200)];
box.backgroundColor = [UIColor redColor];
UITapGestureRecognizer *tapBox = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapMenuHandler:)] autorelease];
[box addGestureRecognizer:tapBox];
[self addSubView:box];
和:
-(void) tapMenuHandler: (UIView *)obj {
//Do something
NSLog(@"tap box");
}
和:
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
if (!showing) {
box.frame = CGRectMake(500, -200, 200, 200);
[UIView animateWithDuration:0.5f delay:0.3f options:(UIViewAnimationOptionAllowUserInteraction) animations:^{
box.frame = CGRectMake(500, 200, 200, 200);
} completion:^(BOOL finished) {
showing = YES;
[UIView animateWithDuration:0.5f delay:3.0f options:(UIViewAnimationOptionAllowUserInteraction) animations:^{
box.frame = CGRectMake(500, -200, 200,200);
} completion:^(BOOL finished) {
showing = NO;
}];
}];
}
感谢您的帮助,对不起我的英语:)
编辑:更多细节 我尝试在屏幕上设置开始我的盒子的原点(例如 500,600),即使我的盒子移动到另一个位置,它仍然总是在开始点(500,600)点击时响应。
更新: 我改变了使用 NSTimer 将框移出屏幕的方式,然后就可以了!
[UIView animateWithDuration:0.5f delay:0.3f options:UIViewAnimationOptionAllowUserInteraction animations:^{
box.frame = CGRectMake(500,200,200,200);
} completion:^(BOOL finished) {
isShowMenubar = YES;
//use NSTimer instead of delay
[NSTimer scheduledTimerWithTimeInterval:3.0f target:self selector:@selector(hideBox) userInfo:nil repeats:NO];
}];
和
-(void)hideBox {
[UIView animateWithDuration:0.5f delay:0.0f options:UIViewAnimationOptionAllowUserInteraction animations:^{
box.frame = CGRectMake(500,-200,200,200);} completion:^(BOOL finished) {
isShowMenubar = NO;
}];
}
最佳答案
盒子没有接收到触摸的原因与动画的工作方式有关。您的框实际上在屏幕外,但在视觉上,它正在通过动画。
即使您将延迟设置为 3.0,它仍然会提前移动框(由于仍在调用动画方法)。因此,在您当前的代码中,如果您点击 (500, -200) 处的方框,它就会收到触摸。
要解决此问题,请使用 NSTimer 或 Grand Central Dispatch 进行延迟。
NSTimer:
[NSTimer scheduledTimerWithTimeInterval:3.0 target:self action:@selector(dismissBox) userInfo:nil repeats:NO];
NSTimer 的问题在于您必须将动画代码放在单独的方法中。
中央调度:
double delayInSeconds = 3.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
[UIView animateWithDuration:0.5f animations:^{
box.frame = CGRectMake(box.frame.origin.x, -200, 200,200);
}completion:^(BOOL finished) {
showing = NO;
}];
});
关于objective-c - IOS - 动画没有响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9825241/