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 
} 
相关问题