【问题标题】:How can we add a UIGestureRecognizer to Outlet Collection?我们如何将 UIGestureRecognizer 添加到 Outlet Collection?
【发布时间】:2017-03-29 13:53:31
【问题描述】:

我正在尝试将点击手势添加到标签 [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!")
        }

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

【问题讨论】:

    标签: ios swift3 uilabel uitapgesturerecognizer iboutletcollection


    【解决方案1】:

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

    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
    }
    

    【讨论】:

      【解决方案2】:

      请在 Xcode 的Attribute inspector 中检查您的UIlabelUser Interaction Enabled 属性。必须勾选User Interaction Enabled 才能检测到水龙头。请看下图,

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-03-17
        • 1970-01-01
        • 1970-01-01
        • 2013-03-22
        • 1970-01-01
        • 2011-12-18
        • 1970-01-01
        相关资源
        最近更新 更多