Search code examples
swiftuiviewpositionlocation

Swift : Randomize UIButton Position within View


I have a UIView that i want to appear in a random location within the width and height of the device. I also want the Y location to not be below 20pts. Here is what I've done, but the UIView sometimes appears off the screen or partially off the screen:

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!)

Please help! Thank you!


Solution

  • Got this to work by doing this and can be applied to anything with the same concept:

    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