问题
centerLabelGesture的定义超出了viewDidLoad()的范围,因此在调用.addGestureRecognizer(centerLabelGesture)时,尚未定义CenterLabel手势。

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

}

2019年1月19日更新
马特指出centerLabelGesture需要在centerLabel.addGestureRecognizer(centerLabelGesture)之前声明,在viewDidLoad()内部

最佳答案

这是一个微妙的错误。问题是你把这句话放在哪里:

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

将该行移到viewDidLoad代码中:
centerLabel.isUserInteractionEnabled = true
let centerLabelGesture = UITapGestureRecognizer(target: self, action: #selector(centerLabelTapped))
centerLabel.addGestureRecognizer(centerLabelGesture)

原因是,在你得到那一行的地方,它是一个实例属性,当你说self作为实例属性初始值设定项中的目标时,它并不意味着你认为它做了什么(它意味着类,而不是实例),所以当你点击时的消息被误导了,什么也不做。
我在这个问题上提出了一个错误;在我看来,编译器至少应该警告你,你正在犯一个潜在的错误。

关于swift - 在Swift中,相对于addGestureRecognizer(),在哪里声明UITapGestureRecognizer()?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51676744/

10-09 06:55