2017-03-03 58 views
0
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移動?我正試圖在下面顯示一個視圖。如果需要其他信息,請告訴我。如何讓我的backgroundImageView可以拖動而不是主視圖

回答

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,那也可以。

+0

工程很好。非常感謝! –

相關問題