0

我正在尝试将点击手势添加到标签 [UILabel] 的插座集合中,如下所示:

@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!")
        }

我试图将它添加到情节提要中的单个标签上;但没有工作。

4

2 回答 2

4

首先,您需要允许标签上的用户交互(默认关闭):

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)
}

二、一种用于标签父视图的手势识别器

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
}
于 2017-03-29T14:32:30.107 回答
1

请检查您的Xcode中的User Interaction Enabled属性。必须勾选以检测水龙头。请看下图,UIlabelAttribute inspectorUser Interaction Enabled

在此处输入图像描述

于 2017-03-29T14:19:03.823 回答