gpt4 book ai didi

ios - 如何在 Objective C 中为 float 的 UIView 设置动画

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:07:10 28 4
gpt4 key购买 nike

我正在尝试将 UIView 设置为 float 对象或气球 :DUIView 位于屏幕中间,我希望它围绕其第一个启动点随机 float 。不跨越屏幕或类似的东西,只是漂浮在它周围 5 个像素的区域内。

有什么建议吗? :D

我试过这个:

[UIView animateWithDuration:0.1
delay:0.0
options: UIViewAnimationOptionRepeat | UIViewAnimationOptionAutoreverse | UIViewAnimationOptionAllowUserInteraction
animations:^{
myCircleUIView.transform = CGAffineTransformMakeTranslation([self randomFloatingGenerator], [self randomFloatingGenerator]);
}
completion:NULL];

randomFloatingGenerator 生成一个介于 -5 和 5 之间的数字。问题是,它只执行一次,并不断重复相同的随机值。

编辑 1:现在我试过了这个

-(void)animationLoop{

[UIView animateWithDuration:1.0
animations: ^{ myCircleUIView.transform = CGAffineTransformMakeTranslation([self randomFloatingGenerator], [self randomFloatingGenerator]); }
completion:
^(BOOL finished) {
[UIView animateWithDuration:1.0
animations:^{ myCircleUIView.transform = CGAffineTransformMakeTranslation(0,0);
}
completion:
^(BOOL finished) {[self animationLoop];}];
}];

但它仍然无法正常工作,动画是......糟糕......我想我正在犯一些愚蠢的错误,我需要另一双眼睛来帮助我。

编辑 2:修复它。

 -(void)animationLoop{
CGPoint oldPoint = CGPointMake(myCircleUIView.frame.origin.x, myCircleUIView.frame.origin.y);
[UIView animateWithDuration:1.0
animations: ^{ myCircleUIView.frame = CGRectMake(myCircleUIView.frame.origin.x + [self randomFloatingGenerator], myCircleUIView.frame.origin.y + [self randomFloatingGenerator], myCircleUIView.frame.size.width, myCircleUIView.frame.size.height); }
completion:
^(BOOL finished) {
[UIView animateWithDuration:1.0
animations:^{ myCircleUIView.frame = CGRectMake(oldPoint.x, oldPoint.y, myCircleUIView.frame.size.width, myCircleUIView.frame.size.height);}
completion:
^(BOOL finished) {[self animationLoop];}];
}];
}

感谢任何人的帮助。

编辑 3:

有人发布了增强代码。

最佳答案

@Shamy 的解决方案,经过改进、修复和 CPU 安全。

-(void)animateFloatView:(UIView*)view{

// Abort the recursive loop
if (!view)
return;

CGPoint oldPoint = CGPointMake(view.frame.origin.x, view.frame.origin.y);
[UIView animateWithDuration:0.6
animations: ^{ view.frame = CGRectMake(view.frame.origin.x, view.frame.origin.y - 15, view.frame.size.width, view.frame.size.height); }
completion:
^(BOOL finished) {

if (finished) {
[UIView animateWithDuration:0.6
animations:^{ view.frame = CGRectMake(oldPoint.x, oldPoint.y, view.frame.size.width, view.frame.size.height);}
completion:
^(BOOL finished2) {
if(finished2)
[self animateFloatView:view];
}];

}
}];
}

每当您想停止动画时(离开 View Controller 时需要),使用nil 调用该函数,如下所示:

    [self recursiveFloatingAnimation:nil];

不停止动画会导致递归循环无限运行并压垮 CPU 堆栈。

关于ios - 如何在 Objective C 中为 float 的 UIView 设置动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25763710/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com