我有一个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!)
请帮忙!谢谢!
答案 0 :(得分:0)
通过这样做可以实现这一点,并且可以应用于具有相同概念的任何事物:
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