gpt4 book ai didi

ios - UITapGestureRecognizer 仅适用于最后一项

转载 作者:搜寻专家 更新时间:2023-11-01 06:40:35 24 4
gpt4 key购买 nike

我正在创建一个简历应用程序(主要是为了好玩),但似乎无法让点击手势识别器为我工作。我想要的是让一个标签显示信息,并根据他们在下面点击的标题标签来改变它。这是我写的代码:

import UIKit

class WorkHistoryViewController: UIViewController {

// MARK: Properties

@IBOutlet weak var jobOne: UILabel!
@IBOutlet weak var jobTwo: UILabel!
@IBOutlet weak var jobThree: UILabel!
@IBOutlet weak var jobFour: UILabel!
@IBOutlet weak var jobFive: UILabel!
@IBOutlet weak var workHistoryDescriptionLabel: UILabel!
let tapRec = UITapGestureRecognizer()

override func viewDidLoad() {
super.viewDidLoad()
tapRec.addTarget(self, action: "tappedLabel")
jobOne.addGestureRecognizer(tapRec)
jobTwo.addGestureRecognizer(tapRec)
jobThree.addGestureRecognizer(tapRec)
jobFour.addGestureRecognizer(tapRec)
jobFive.addGestureRecognizer(tapRec)
}

// MARK: Methods

func tappedLabel() {
workHistoryDescriptionLabel.text = "It worked!"
}
}

发生的事情是,最后一个在 viewDidLoad() 中调用 addGestureRecognizer() 的标签是唯一有效的标签。如果我注释掉最后一行,那么只有上面的标签有效。我还尝试以编程方式在每个标签和属性检查器上启用用户交互,但都没有改变任何东西。

最佳答案

根据 Apple 的事件处理指南

Gesture Recognizers Are Attached to a View

Every gesture recognizer is associated with one view. By contrast, a view can have multiple gesture recognizers, because a single view might respond to many different gestures. For a gesture recognizer to recognize touches that occur in a particular view, you must attach the gesture recognizer to that view. When a user touches that view, the gesture recognizer receives a message that a touch occurred before the view object does. As a result, the gesture recognizer can respond to touches on behalf of the view.

因此您需要创建多个 UITapGestureRecognizer 实例并将它们附加到每个 View ,即使它们执行相同的操作也是如此。

例如,

let tapRecOne = UITapGestureRecognizer()
tapRecOne.addTarget(self, action: "tappedLabel")
jobOne.addGestureRecognizer(tapRecOne)

let tapRecTwo = UITapGestureRecognizer()
tapRecTwo.addTarget(self, action: "tappedLabel")
jobTwo.addGestureRecognizer(tapRecTwo)

等等。

关于ios - UITapGestureRecognizer 仅适用于最后一项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35909159/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com