[英]Pass UILongPressGestureRecognizer between UIViewControllers
我在網上等其他地方閑逛,還沒有找到解決方案。 我在一個視圖控制器上有一個UILongPressGestureRecognizer,它在UIView上執行動畫,然后顯示另一個視圖控制器(如果用戶在動畫過程中沒有移動手指)。 當用戶抬起手指時,我想關閉第二個視圖控制器,但是我遇到了麻煩。
我當前的方法是向第二個視圖控制器中添加另一個UILongPressGestureRecognizer,並在結束其狀態時關閉視圖控制器。 但是我不知道如何將兩個手勢識別器綁定在一起,這樣我才能在一個視圖控制器中開始觸摸,而在另一個視圖控制器中結束。
我已附上以下相關代碼
在第一個View Controller中
@objc private func pinAnimation(sender: UILongPressGestureRecognizer) {
if let headerView = projectView.projectCollectionView.supplementaryView(forElementKind: UICollectionElementKindSectionHeader, at: IndexPath(row: 0, section: 0)) as? ProjectHeaderView {
switch sender.state {
case .began:
let frame = headerView.pinButton.frame
UIView.setAnimationCurve(.linear)
UIView.animate(withDuration: 1, animations: {
headerView.pinProgressView.frame = frame
}, completion: { (_) in
if (headerView.pinProgressView.frame == headerView.pinButton.frame) {
let notification = UINotificationFeedbackGenerator()
notification.notificationOccurred(.success)
let homeVC = HomeViewController()
self.present(homeVC, animated: true, completion: {
homeVC.longPress(sender)
let height = headerView.pinButton.frame.height
let minX = headerView.pinButton.frame.minX
let minY = headerView.pinButton.frame.minY
headerView.pinProgressView.frame = CGRect(x: minX, y: minY, width: 0, height: height)
})
}
})
case .ended:
//cancel current animation
let height = headerView.pinProgressView.frame.height
let minX = headerView.pinProgressView.frame.minX
let minY = headerView.pinProgressView.frame.minY
UIView.setAnimationCurve(.linear)
UIView.animate(withDuration: 0.5) {
headerView.pinProgressView.frame = CGRect(x: minX, y: minY, width: 0, height: height)
}
default:
break
}
}
}
在第二個View Controller中
override func viewDidLoad() {
super.viewDidLoad()
let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(longPress(_:)))
view.addGestureRecognizer(longPressRecognizer)
}
@objc func longPress(_ sender: UILongPressGestureRecognizer) {
switch sender.state {
case .ended:
self.dismiss(animated: true, completion: nil)
default:
break
}
}
任何幫助/指導將不勝感激!
我建議您使用委托模式:
為您的第一個ViewController創建委托
protocol FirstViewControllerDelegate {
func longPressEnded()
}
然后將delegate
變量添加到您的第一個ViewController
class FirstViewController {
var delegate: FirstViewControllerDelegate?
...
}
長按結束時代表上的下一個調用方法
@objc private func pinAnimation(sender: UILongPressGestureRecognizer) {
...
switch sender.state {
case .began:
...
case .ended:
...
delegate?.longPressEnded()
default:
break
}
}
之后,當您展示第二個ViewController時,將第一個ViewController的delegate
設置為homeVC
let homeVC = HomeViewController()
self.delegate = homeVC
然后將該委托實現到第二個ViewController並定義長按結束時應該發生的情況
class HomeViewController: UIViewController, FirstViewControllerDelegate {
...
func longPressEnded() {
dismiss(animated: true, completion: nil)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.