0

我試圖點擊手勢添加標籤[的UILabel]的出口集合,像這樣:我們如何將UIGestureRecognizer添加到Outlet Collection?

@IBOutlet var subLabels: [UILabel]! 

    override func viewDidLoad() { 
      super.viewDidLoad() 

      let tap = UITapGestureRecognizer(target: self, action: #selector(HomePageViewController.selectSubLabel(tap:))) 
      tap.numberOfTapsRequired = 1 
      tap.cancelsTouchesInView = false 

      for i in (0..<(subLabels.count)) { 
       subLabels[i].addGestureRecognizer(tap) 
      } 
    } 

    func selectSubLabel(tap: UITapGestureRecognizer) { 
      print("Gesture Is WORKING!") 
     } 

,我試圖將其添加在故事板單個標籤上;但NONE正在工作。

回答

1

請檢查您的UIlabelUser Interaction Enabled屬性在 Xcode。必須勾選User Interaction Enabled以檢測水龍頭。請參考下面的圖片,

enter image description here

3

首先,你需要允許在標籤上的用戶交互(它是默認關閉):

for i in (0..<(subLabels.count)) { 
    subLabels[i].isUserInteractionEnabled = true 
    subLabels[i].addGestureRecognizer(tap) 
} 

但手勢識別器可以觀察到的手勢只在一個視圖。 所以,有兩種選擇:

一專用手勢識別每一個標籤

for i in (0..<(labels.count)) { 
    let tap = UITapGestureRecognizer(target: self, action: #selector(selectSubLabel(tap:))) 
    labels[i].isUserInteractionEnabled = true 
    labels[i].addGestureRecognizer(tap) 
} 

II。一個用於標籤父視圖的手勢識別器

override func viewDidLoad() { 
    super.viewDidLoad() 

    for i in (0..<(labels.count)) { 
     subLabels[i].isUserInteractionEnabled = true 
    } 

    let tap = UITapGestureRecognizer(target: self, action: #selector(selectSubLabel(tap:))) 
    view.addGestureRecognizer(tap) 
} 

func selectSubLabel(tap: UITapGestureRecognizer) { 
    let touchPoint = tap.location(in: view) 
    guard let label = subLabels.first(where: { $0.frame.contains(touchPoint) }) else { return } 

    // Do your stuff with the label 
} 
相關問題