2017-10-14 48 views
4
func addSwipe() { 
    self.isUserInteractionEnabled = true 
    let directions: [UISwipeGestureRecognizerDirection] = [.right, .left] 
    for direction in directions { 
     let gesture = UISwipeGestureRecognizer(target: self, action: #selector(ViewCardContainer.handleSwipe(sender:))) 
     gesture.direction = direction 
     self.addGestureRecognizer(gesture) 
    } 
} 

@objc func handleSwipe(sender: UISwipeGestureRecognizer) { 
    print(sender.direction) 
} 

我的UIViews輕掃手勢:UISwipeGestureRecognizer不承認視野之外發起

+----------------+ 
|    | 
|  +--------+ | 
| V1 | V2 | | 
+----------------- 

我註冊了UISwipeGestureRecognizer在V2但如果滑動手勢從V1開始通過V2去,滑動手勢贏在V2中不會被識別。

有沒有辦法讓它工作?提前致謝!

+1

這是因爲您的輕掃手勢已註冊爲V1而非V2。您可以嘗試檢測從V1啓動的手勢的觸摸位置是否低於V2並調用一些更改 – Woof

回答

7

編輯:我爲你做了一個工作示例項目。您可以從紅色方塊(v1)滑動到藍色方塊(v2),並在日誌中看到檢測到滑動。

https://github.com/QuantumProductions/so_46781856

import UIKit 

class ViewController: UIViewController { 
    var view2: UIView! 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     view.backgroundColor = UIColor.black 

     let view1 = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100)) 
     view1.backgroundColor = UIColor.red 
     view.addSubview(view1) 

     view2 = UIView(frame: CGRect(x: 100, y: 0, width: 100, height: 100)) 
     view2.backgroundColor = UIColor.blue 
     view.addSubview(view2) 

     let swipeRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(swipeDetected(_:))) 
     swipeRecognizer.direction = .right 
     view.addGestureRecognizer(swipeRecognizer) 

    } 

    func swipeDetected(_ sender: UIGestureRecognizer) { 
     let location = sender.location(ofTouch: 0, in: view2) 
     print("Location in view2") 
     print(location) 
     print("You swiped right") 
    } 
} 

原來的答案:

這是故意的。輕掃檢測是基於視圖的基礎視圖。嘗試一下Apple聯繫人等Apple應用程序,然後在滾動視圖中移動手指後,您將看到無法按導航欄中的按鈕。

如果你想你的觸摸識別爲有效的V1和V2:

  • 添加手勢識別兩個V1的父視圖& V2
  • 檢測是否觸摸是V2的矩形內(使用touch.locationInView:V2)
  • 如果爲真,運行預期功能

如果這是一個視圖控制器,你要識別器添加到self.view(從您的示例中不清楚哪個視圖添加了識別器,因爲沒有關於您的func所在的級別的上下文)

您可能需要在V1和V2上禁用用戶交互,吃東西,並把它放在父視圖上啓用。