我声明了 2 个 IBActions“rightButtonPress”和“leftButtonPress”,我将它们链接到 2 个 IBOutlet 并在 IBactions 中运行了一段代码:
-(void)leftButtonPress:(id)sender{
PlayerSprite.center = CGPointMake(PlayerSprite.center.x - 1, PlayerSprite.center.y);
}
-(void)rightButtonPress:(id)sender{
PlayerSprite.center = CGPointMake(PlayerSprite.center.x + 1, PlayerSprite.center.y);
}
我还创建了 2 个计时器:
- (void)viewDidLoad
{
TouchLeftCheck = [NSTimer scheduledTimerWithTimeInterval:.01
target:self
selector:@selector(leftButtonPress:)
userInfo:nil
repeats:YES];
TouchRightCheck = [NSTimer scheduledTimerWithTimeInterval:.01
target:self
selector:@selector(rightButtonPress:)
userInfo:nil
repeats:YES];
BarrelEntrance = [NSTimer scheduledTimerWithTimeInterval:.01
target:self
selector:@selector(barrelStartDown)
userInfo:nil
repeats:YES];
[self frontBarrelAnimation];
[super viewDidLoad];
// Do any additional setup after loading the view.
}
一切都很好,但是当我将它链接到两个 IBObject 按钮时,有些东西不起作用,当我将 IBActions 链接到我的对象(按钮)时,使用“Touch Down”它不起作用。当我在 ios 模拟器中时,它只在我按住时移动我的对象,然后它停止,如果你再次触摸它,则对象会再次移动一次。但是是否有一个链接选项可以让我在按住它时在屏幕上制作平滑的动画,然后在松开时停止?谢谢。
最佳答案
这里有三个组成部分:
- 动画计时器
- 开始触摸事件
- 结束触摸事件
我建议在按下按钮时使用 NSTimer 为 View 设置动画。当按下按钮(touchDown:
)时,此计时器将初始化并启动,并在释放按钮(touchUpInside:
和 touchUpOutside:
)时失效/无效。
因此,首先,将触摸事件绑定(bind)到按钮。 (我假设您正在界面生成器中创建这些按钮,这很好。如果是这样,您可以跳过初始化并直接转到 addTarget:
方法):
UIButton* leftButton = [[UIButton alloc] initWithFrame:...];
[leftButton addTarget:self action:@selector(startLeftAnimation) forControlEvents:UIControlEventTouchDown];
[leftButton addTarget:self action:@selector(stopAnimation) forControlEvents:UIControlEventTouchUpInside];
[leftButton addTarget:self action:@selector(stopAnimation) forControlEvents:UIControlEventTouchUpOutside];
接下来声明一个实例变量timer:
@interface MyViewController
{
NSTimer* animationTimer;
}
为按钮事件创建方法:
- (void)startLeftAnimation
{
animationTimer = [NSTimer scheduledTimerWithInterval: 0.02 target:self selector:@selector(animateLeft) userInfo:nil repeats:YES];
}
- (void)stopAnimation
{
if(animationTimer != nil)
{
[animationTimer invalidate];
animationTimer = nil;
}
}
最后,创建动画方法
- (void)animateLeft
{
PlayerSprite.center = CGPointMake(PlayerSprite.center.x - 1, PlayerSprite.center.y);
}
冲洗并重复右键动画。
关于ios - 按住按钮时如何移动 UIImage?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22584565/