Reputation: 1413
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?
Upvotes: 0
Views: 704
Reputation: 1760
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)
}
Upvotes: 2
Reputation: 3130
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))
}
Upvotes: 1