在Swift中,相对于addGestureRecognizer(),在哪里声明UITapGestureRecognizer()?

时间:2018-08-03 16:28:47

标签: swift xcode uiview uilabel uigesturerecognizer

问题

centerLabelGesture是在viewDidLoad()范围之外定义的,因此,在调用.addGestureRecognizer(centerLabelGesture)时,尚未定义centerLabelGesture。

import UIKit
import SnapKit

class ViewController: UIViewController {

    var screen: UIView!
    var centerLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        screen = UIView()
        centerLabel = UILabel()

        view.addSubview(screen)
        screen.addSubview(centerLabel)

        screen.backgroundColor = .white
        screen.snp.makeConstraints { (make) in
            make.top.equalTo(view)
            make.right.equalTo(view)
            make.left.equalTo(view)
            make.bottom.equalTo(view)
        }

        centerLabel.text = "I hope I'm centered."
        centerLabel.snp.makeConstraints { (make) in
            make.center.equalTo(screen)
        }
        centerLabel.isUserInteractionEnabled = true
        centerLabel.addGestureRecognizer(centerLabelGesture)
    }

    let centerLabelGesture = UITapGestureRecognizer(target: self, action: #selector(centerLabelTapped))

    @objc func centerLabelTapped() {
        centerLabel.text = "Ouch, you tapped me!"
    }

}

更新1/19/2019

matt指出,centerLabelGesture必须在centerLabel.addGestureRecognizer(centerLabelGesture)内的viewDidLoad()之前声明

2 个答案:

答案 0 :(得分:1)

这是一个微妙的错误。问题是您放置此行的位置:

let centerLabelGesture = UITapGestureRecognizer(target: self, action: #selector(centerLabelTapped))

将该行移动到viewDidLoad代码中:

centerLabel.isUserInteractionEnabled = true
let centerLabelGesture = UITapGestureRecognizer(target: self, action: #selector(centerLabelTapped))
centerLabel.addGestureRecognizer(centerLabelGesture)

原因是您所在的行是实例属性,当您在实例属性初始值设定项中说self作为目标时,并不意味着您认为它做了什么(它表示 class ,而不是 instance ),因此,当您点击时,该消息将被错误定向并且不执行任何操作。

我已在此问题上提交了错误;我认为编译器至少应警告您,您正在犯潜在的错误。

答案 1 :(得分:0)

尝试在viewDidLoad中添加此行

centerLabelGesture.numberOfTapsRequired = 1