Swift 3中的AddGesture有什么不同?

时间:2016-11-20 16:02:05

标签: swift uitapgesturerecognizer

我不知道为什么我的代码无效:

let profileImageView: UIImageView = {
    let image = UIImageView()
    image.image = UIImage(named: "gameofthrones_splash")
    image.translatesAutoresizingMaskIntoConstraints = false
    image.contentMode = .scaleAspectFill
    let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleSelectProfileImageView))
    image.addGestureRecognizer(tapGesture)
    image.isUserInteractionEnabled = true

    return image
}()

此imageView加载到ViewDidLoad(我可以看到)

func handleSelectProfileImageView() {
    print("123")
}

但是当我点击它时,控制台中没有任何东西返回! WTF?

4 个答案:

答案 0 :(得分:1)

好的解决方案实际上非常简单。你必须把它变成一个懒惰的var而不是let。

lazy var profileImageView: UIImageView = {
    let image = UIImageView()
    image.image = UIImage(named: "gameofthrones_splash")
    image.translatesAutoresizingMaskIntoConstraints = false
    image.contentMode = .scaleAspectFill
    let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleSelectProfileImageView))
    image.addGestureRecognizer(tapGesture)
    image.isUserInteractionEnabled = true

return image
}()

答案 1 :(得分:1)

它在目标中。这在放置在viewDidLoad()中时有效:

profileImageView.frame = CGRect(x: 60, y: 60, width: 70, height: 70)
view.addSubview(profileImageView)
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleSelectProfileImageView))
profileImageView.addGestureRecognizer(tapGesture)

目标是“self”,它是UIViewController(不是UIImageView)。在大多数情况下(我确定有异常值)你想在视图中记录手势,但在视图控制器中使用手势。

答案 2 :(得分:0)

Swift 3.0: 我删除了一些错误 - 将此代码放在viewdidLoad

 override func viewDidLoad() {
        super.viewDidLoad()

        var profileImageView:UIImageView {
            var image = UIImageView()
            image.backgroundColor = UIColor.red;
            image.frame = CGRect(x: 0, y: 0, width: 44, height: 44)
            image.translatesAutoresizingMaskIntoConstraints = false
            image.contentMode = .scaleAspectFill
            let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleSelectProfileImageView))
            image.addGestureRecognizer(tapGesture)
            image.isUserInteractionEnabled = true

            return image
        }

        view.addSubview(profileImageView);


        // Do any additional setup after loading the view.
    }

 func handleSelectProfileImageView() {
        print("123")
    }

为了测试我删除了图片,您可以添加它。但它工作正常。

答案 3 :(得分:0)

我使用UIButton修改了这个问题 - >

let profileImageView: UIButton = {
    let iv = UIButton()
    let image = UIImage(named: "r2d2")
    iv.setImage(image, for: .normal)
    iv.translatesAutoresizingMaskIntoConstraints = false
    iv.addTarget(self, action: #selector(selectProfileImage), for: .touchUpInside)
    iv.isUserInteractionEnabled = true
    return iv
}()

@objc func selectProfileImage(){
    print("Hello")
}