Swift : 随机化视图中的 UIButton 位置
Swift : Randomize UIButton Position within View
我有一个 UIView,我希望它出现在设备宽度和高度范围内的随机位置。我还希望 Y 位置不低于 20pts。这是我所做的,但 UIView 有时会出现在屏幕外或部分出现在屏幕外:
superDab = SuperDabButton(frame:CGRectMake(CGFloat(arc4random_uniform(UInt32((self.view?.frame.size.width)! - (superDabImage!.size.width)))),
(CGFloat(arc4random_uniform(UInt32((self.view?.frame.size.height)! - (superDabImage!.size.height))))),
(superDabImage!.size.width),
(superDabImage!.size.height)),
time: 5.0)
self.view?.addSubview(superDab!)
请帮忙!谢谢!
通过这样做得到它的工作并且可以应用于具有相同概念的任何东西:
var xPos = CGFloat()
var yPos = CGFloat()
//Finds random CGFloat within the width and height
xPos = (CGFloat(arc4random_uniform(UInt32((self.view?.frame.size.width)!))))
yPos = (CGFloat(arc4random_uniform(UInt32((self.view?.frame.size.height)!))))
//If statements saying that if the x pos is larger than the width - the size of the button,
then do modulus on it using the equation below
if (xPos > ((self.view?.bounds.width)! - (self.view?.bounds.width)! * 0.20)){
xPos = xPos % ((self.view?.bounds.width)! - (self.view?.bounds.width)! * 0.20)}
if (yPos > ((self.view?.bounds.height)! - (self.view?.bounds.width)! * 0.20)){
yPos = yPos % ((self.view?.bounds.height)! - (self.view?.bounds.width)! * 0.20)}
//Note: I use the "- (self.view?.bounds.width)! * 0.20" for the ypos only because
my button is a circle, so most likely others would use the height instead of width
我有一个 UIView,我希望它出现在设备宽度和高度范围内的随机位置。我还希望 Y 位置不低于 20pts。这是我所做的,但 UIView 有时会出现在屏幕外或部分出现在屏幕外:
superDab = SuperDabButton(frame:CGRectMake(CGFloat(arc4random_uniform(UInt32((self.view?.frame.size.width)! - (superDabImage!.size.width)))),
(CGFloat(arc4random_uniform(UInt32((self.view?.frame.size.height)! - (superDabImage!.size.height))))),
(superDabImage!.size.width),
(superDabImage!.size.height)),
time: 5.0)
self.view?.addSubview(superDab!)
请帮忙!谢谢!
通过这样做得到它的工作并且可以应用于具有相同概念的任何东西:
var xPos = CGFloat()
var yPos = CGFloat()
//Finds random CGFloat within the width and height
xPos = (CGFloat(arc4random_uniform(UInt32((self.view?.frame.size.width)!))))
yPos = (CGFloat(arc4random_uniform(UInt32((self.view?.frame.size.height)!))))
//If statements saying that if the x pos is larger than the width - the size of the button,
then do modulus on it using the equation below
if (xPos > ((self.view?.bounds.width)! - (self.view?.bounds.width)! * 0.20)){
xPos = xPos % ((self.view?.bounds.width)! - (self.view?.bounds.width)! * 0.20)}
if (yPos > ((self.view?.bounds.height)! - (self.view?.bounds.width)! * 0.20)){
yPos = yPos % ((self.view?.bounds.height)! - (self.view?.bounds.width)! * 0.20)}
//Note: I use the "- (self.view?.bounds.width)! * 0.20" for the ypos only because
my button is a circle, so most likely others would use the height instead of width