如何让我的backgroundImageView可以拖动而不是主视图

时间:2017-03-03 00:06:36

标签: ios swift swift3

class PhotoViewController: UIViewController {

override var prefersStatusBarHidden: Bool {
    return true
}

private var backgroundImage: UIImage

init(image: UIImage) {
    self.backgroundImage = image
    super.init(nibName: nil, bundle: nil)
    print(image)
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

override func viewDidLoad() {
    super.viewDidLoad()


    self.view.backgroundColor = UIColor.gray
    let backgroundImageView = UIImageView(frame: view.frame)
    backgroundImageView.image = backgroundImage
    backgroundImageView.isUserInteractionEnabled = true


    let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(panGestureRecognizerAction(_:)))
    backgroundImageView.addGestureRecognizer(panGestureRecognizer)


    view.addSubview(backgroundImageView)
}




func panGestureRecognizerAction(_ gesture: UIPanGestureRecognizer){
    let translation = gesture.translation(in: view)
    view.frame.origin.y = translation.y

    if gesture.state == .ended{

        let velocity = gesture.velocity(in: view)

        if velocity.y > 1500{
            UIView.animate(withDuration: 0.5, animations: { 
                self.dismiss(animated: true, completion: nil)
            })
        } else{
            UIView.animate(withDuration: 0.3, animations: { 

                self.view.frame.origin = CGPoint(x: 0, y: 0)
            })
        }
    }
}

我的整个视图移动并显示背后的黑色背景。我如何让backgroundImageView移动?我想在下面显示一个视图。如果需要任何其他信息,请告诉我。

1 个答案:

答案 0 :(得分:0)

panGestureRecognizerAction中,您要求它移动view,即viewController的view。相反,请使用分配给gestureRecognizer的view说:

if let bgImage = gesture.view {
    bgImage.frame.origin.y = translation.y
}

gesture.view是可选的,这就是我先检查它的原因。你也可以说gesture.view?.frame.origin.y = translation.y并且它也可以正常工作。