iOS UIScrollView和控制器返回手勢沖突解決方法

開發中,有部分UI,會將UIScrollView橫向鋪在底層,上面放tableView 或一些視圖左右滾動切換,底層的scrollView會和Nav ViewController原有的返回手勢沖突 

解決辦法,重寫UIScrollView 的gestureRecognizerShouldBegin,在ScrollView滾動到頭的時候,屏蔽ScrollView的手勢

class GesturesConflictScrollView: UIScrollView {
  override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
    back(by: gestureRecognizer)
  }

  private final func back(by gestureRecognizer: UIGestureRecognizer) -> Bool {
    
    guard gestureRecognizer == panGestureRecognizer else { return true }
    // point.x < 0 代表左滑即手指從屏幕右向左移動 反之一樣
    let point: CGPoint = panGestureRecognizer.translation(in: self)
    let state: UIGestureRecognizer.State = gestureRecognizer.state
    let locDistance: CGFloat = UIScreen.main.bounds.size.width
    
    if state == .began || state == .possible {
      let locationPoint = gestureRecognizer.location(in: self)
      if point.x > 0 && locationPoint.x < locDistance && contentOffset.x <= 0 {
        return false
      }
      let pageCount = contentSize.width / UIScreen.main.bounds.size.width
      let criticalPoint = pageCount < 2 ? locDistance : locDistance * (pageCount - 1)
      if point.x < 0 && contentOffset.x == criticalPoint {
        return false
      }
    }
    return true
  }
}

到此這篇關於iOS UIScrollView和控制器返回手勢沖突解決方法的文章就介紹到這瞭,更多相關iOS UIScrollView和控制器手勢沖突內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet! 

推薦閱讀: