xcode 在两点之间移动 UIButton 的正确方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13805320/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Correct Way To Move UIButton Between Two Points?
提问by William Robinson
Trying to make a small tapping game, where you have a grid of squares and need to tap them in different orders. Occasionally these squares will swap places with each other.
尝试制作一个小型敲击游戏,其中您有一个正方形网格,需要以不同的顺序敲击它们。有时,这些方块会相互交换位置。
I figure that I will need to put the locations of each square into an array. Then when it is time to move, go from the current location to a one selected at random from the array, and then deleting that location in the array so I don't get multiple buttons in the same place.
我想我需要将每个方块的位置放入一个数组中。然后当需要移动时,从当前位置移动到从数组中随机选择的一个位置,然后在数组中删除该位置,这样我就不会在同一个位置得到多个按钮。
Unfortunately I can't even get the UIButtons to move, let alone interpolate between two positions.
不幸的是,我什至无法让 UIButton 移动,更不用说在两个位置之间进行插值了。
Currently this will move a button:
目前这将移动一个按钮:
-(IBAction)button:(id)sender
{
button.center = CGPointMake(200, 200);
}
But I don't want it to work like that, I want it to work something like this and it doesn't work:
但我不希望它像那样工作,我希望它像这样工作,但它不起作用:
if (allButtonsPressed == YES)
{
button.center = CGPointMake(200, 200);
}
It won't even move if placed like this:
如果这样放置它甚至不会移动:
-(void)viewDidLoad
{
[super viewDidLoad];
button.center = CGPointMake(200, 200);
}
For clarity, the button is added through Interface Builder, and all these situations work when doing other things, so I'm guessing UIButtons need to moved/animated in specific ways?
为了清楚起见,按钮是通过 Interface Builder 添加的,所有这些情况在做其他事情时都有效,所以我猜 UIButtons 需要以特定方式移动/动画?
回答by Ryan Poolos
viewDidLoad occurs before the view is visible so it will move just not animated. You could try putting it in the viewDidAppear method.
viewDidLoad 发生在视图可见之前,因此它会移动而不是动画。您可以尝试将其放入 viewDidAppear 方法中。
You can wrap things in UIView animation blocks like so if you want them to animate instead of blink into position.
如果您希望它们动画而不是闪烁到位,您可以像这样将东西包裹在 UIView 动画块中。
[UIView animateWithDuration:0.5 animations:^{
button.center = CGPointMake(200.0, 200.0);
}];
Since you're using interface builder I'm assuming your using properties to keep track of the buttons. This can work if you're only using a few set buttons but I'd expect in a game those will change so you may want to move to code or atleast use IBOutletCollections to keep track of the buttons.
由于您使用的是界面构建器,因此我假设您使用属性来跟踪按钮。如果您只使用几个设置按钮,这可以工作,但我希望在游戏中这些按钮会发生变化,因此您可能想要移动到代码或至少使用 IBOutletCollections 来跟踪按钮。
Swift 3.0
斯威夫特 3.0
UIView.animate(withDuration: 0.5) { [weak self] in
self?.button.center = CGPoint(x: 200, y: 200)
}