gpt4 book ai didi

ios - UITapGestureRecognizer 不在导航栏标题 View 中的 UIView 上工作?

转载 作者:行者123 更新时间:2023-11-28 13:38:43 25 4
gpt4 key购买 nike

我正在尝试在 navigationBar titleView 上添加 tapGesture 但没有收到任何事件。请告诉我如何解决这个问题。

 let titleView = UIView()
titleView.frame = CGRect(x: 0, y: 0, width: 100, height: 60)
titleView.backgroundColor = UIColor.yellow

let profileImageView = UIImageView()
profileImageView.contentMode = .scaleAspectFill
profileImageView.layer.cornerRadius = 20
profileImageView.clipsToBounds = true
profileImageView.loadImageUsingCacheWithUrlString(urlString: user.image)
titleView.addSubview(profileImageView)
profileImageView.translatesAutoresizingMaskIntoConstraints = false
profileImageView.leftAnchor.constraint(equalTo: titleView.leftAnchor).isActive = true
profileImageView.centerYAnchor.constraint(equalTo: titleView.centerYAnchor).isActive = true
profileImageView.widthAnchor.constraint(equalToConstant: 40).isActive = true
profileImageView.heightAnchor.constraint(equalToConstant: 40).isActive = true

let nameLabel = UILabel()
nameLabel.text = user.name
nameLabel.font = UIFont(name: "HelveticaNeue-Medium", size: 17)
titleView.addSubview(nameLabel)
nameLabel.translatesAutoresizingMaskIntoConstraints = false
nameLabel.leftAnchor.constraint(equalTo: profileImageView.rightAnchor, constant: 8).isActive = true
nameLabel.centerYAnchor.constraint(equalTo: profileImageView.centerYAnchor).isActive = true
nameLabel.rightAnchor.constraint(equalTo: titleView.rightAnchor).isActive = true
nameLabel.heightAnchor.constraint(equalTo: profileImageView.heightAnchor).isActive = true

self.navigationItem.titleView = titleView
titleView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(showChatTableViewController)))

最佳答案

确保将 isUserInteractionEnabled 设置为 true。默认情况下它是 true 但如果它在你的情况下不起作用然后尝试设置 true

确保调试您的代码并检查添加 titleView 后是否能够打印出 self.navigationItem.titleView

let titleView = UIView()
titleView.frame = CGRect(x: 0, y: 0, width: 100, height: 60)
titleView.backgroundColor = UIColor.yellow
titleView.isUserInteractionEnabled = true

self.navigationItem.titleView = titleView
titleView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(showChatTableViewController)))

@objc func showChatTableViewController() {
print("tapped")
}

关于ios - UITapGestureRecognizer 不在导航栏标题 View 中的 UIView 上工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56302220/

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