简体   繁体   中英

Move view within superview's bounds (iOS)

In an app I am attempting to have a view move within another view to a random location. I have been able to do this as follows:

mySmallerView.center = randomizeLocation()

func randomizeLocation() -> CGPoint {
    let randomX = arc4random_uniform(UInt32(mainView.frame.width))
    let randomY = arc4random_uniform(UInt32(mainView.frame.height))

    return CGPointMake(CGFloat(randomX), CGFloat(randomY))
}

This moves it around quite nicely, BUT it uses center, so sometimes, the left is off the screen, or the right, top and/or bottom go off the screen because its center can be pushing the limits of the view's frame.

How would I improve randomizeLocation() to where it would ensure the BOUNDS/FRAME of the view to be moved do not exceed the bounds/frame of its superview?

Is there a way to do this?

i think it should be like this the max randomX must not able to be the mianView.frame.width

func randomizeLocation() -> CGPoint {

    let randomX = arc4random_uniform(UInt32(mainView.frame.width - (mySmallerView.frame.width))) + (mySmallerView.frame.width / 2)
    let randomY = arc4random_uniform(UInt32(mainView.frame.height - (mySmallerView.frame.height))) + (mySmallerView.frame.height / 2)

}

I think you need to make sure you don't put your smaller view too far out or down (by adding - (mySmallerView.frame.width / 2) ). You also want to make sure you don't go too far to the left or up (by adding + (mySmallerView.frame.width / 2) ).

func randomizeLocation() -> CGPoint {

   let randomX = arc4random_uniform(UInt32(mainView.frame.width - (mySmallerView.frame.width / 2))) + (mySmallerView.frame.width / 2)
   let randomY = arc4random_uniform(UInt32(mainView.frame.height - (mySmallerView.frame.height / 2))) + (mySmallerView.frame.height / 2)

   return CGPointMake(CGFloat(randomX), CGFloat(randomY))
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM