I've added 2 UIViews on my screen and I want to detect if they collide. If so, then I need to show an alert on the screen.
what about
if (CGRectIntersectsRect(secondView.frame, sender.frame)) {
// Do something
}
You can check wether 2 views are intersecting by checking if their frames are intersecting. Here is an example:
let view1 = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
let view2 = UIView(frame: CGRect(x: 90, y: 90, width: 50, height: 50))
extension UIView {
func intersects(_ otherView: UIView) -> Bool {
if self === otherView { return false }
return self.frame.intersects(otherView.frame)
}
}
print(view1.intersects(view2)) // Prints true because the 2 views are intersecting
You can call intersects(_:)
every time you update any of your views frames (ie. change their size and/or position). If the method returns true
, show an alert using UIAlertController
.
// The Pan Gesture
func createPanGestureRecognizer(targetView: UIImageView)
{
var panGesture = UIPanGestureRecognizer(target: self, action:("handlePanGesture:"))
targetView.addGestureRecognizer(panGesture)
}
// THE HANDLE
func handlePanGesture(panGesture: UIPanGestureRecognizer) {
// get translation
var translation = panGesture.translationInView(view)
panGesture.setTranslation(CGPointZero, inView: view)
println(translation)
//create a new Label and give it the parameters of the old one
var label = panGesture.view as UIImageView
label.center = CGPoint(x: label.center.x+translation.x, y: label.center.y+translation.y)
label.multipleTouchEnabled = true
label.userInteractionEnabled = true
if panGesture.state == UIGestureRecognizerState.Began {
//add something you want to happen when the Label Panning has started
}
if panGesture.state == UIGestureRecognizerState.Ended {
//add something you want to happen when the Label Panning has ended
}
if panGesture.state == UIGestureRecognizerState.Changed {
//add something you want to happen when the Label Panning has been change ( during the moving/panning )
}
else {
// or something when its not moving
}
}
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.