在UIView之间拖放UIImageView

时间:2017-01-12 11:09:52

标签: swift uiview drag-and-drop uiimageview

我是IOS应用程序的新手,我正在尝试在两个uiView(子视图)之间拖动一个imageView,我坚持让uiView点放置它。

enter image description here

mycode的:

import UIKit

class ViewController: UIViewController {
    fileprivate var xOffset: CGFloat = 0.0
    fileprivate var yOffset: CGFloat = 0.0
    var originalPosition = CGPoint(x:0,y:0)
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    @IBOutlet weak var dropView2: UIView!
    @IBOutlet weak var dropView: UIView!
    @IBOutlet weak var imageView: UIImageView!
    //1
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        let touch:UITouch = touches.first!       
        originalPosition = self.imageView.center
        xOffset = originalPosition.x - self.imageView.center.x
        yOffset = originalPosition.y - self.imageView.center.y       

    }

    //2
    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {        
     if let touch = touches.first {
        print(touch.view?.superview == dropView)       
        let point = touch.location(in: self.view)
        self.imageView.center = CGPoint(x: point.x - xOffset, y: point.y - yOffset)

        }
    }

    //3
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {

        if let touch = touches.first {

            let point = touch.location(in: self.view)            

            if dropView.frame.contains(point) {
                // could drag
                self.imageView.center = CGPoint(x: point.x - xOffset, y: point.y - yOffset)
                imageView.superview?.bringSubview(toFront: imageView)
            }
            else if dropView2.frame.contains(point) {
                // could drag
                self.imageView.center = CGPoint(x: point.x - xOffset, y: point.y - yOffset)               
                imageView.superview?.bringSubview(toFront: imageView)
            }             
            else {
                // stop dragging
                self.imageView.center = originalPosition
            }

        }


    }

}

拖动,但它没有掉下来查看它来到原始位置,请任何人提供我想要获得正确的touchend位置只能在两个视图上删除。

0 个答案:

没有答案