我宣布了2个IBActions" rightButtonPress"和" leftButtonPress"我将它们链接到2个IBOutlets并在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模拟器中时它只移动我的物体,当我按住它然后它停止,如果你再次触摸它然后物体移动一次。但是有没有一个链接选项,当我按住它时,我可以让它在屏幕上做一个平滑的动画,然后当我放手时停止?感谢。
答案 0 :(得分:1)
这里有三个组成部分:
我建议在按下按钮时使用NSTimer为视图设置动画。当按下按钮(touchDown:
)时,此计时器将被初始化并启动;当按钮被释放时,此计时器将被无效/无效(touchUpInside:
和touchUpOutside:
)。
首先,将触摸事件绑定到按钮。 (我假设您正在界面构建器中创建这些按钮,这很好。如果是这样,您可以跳过初始化并直接进入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);
}
冲洗并重复右键动画。