我有一個UINavigationItem,我將它的titleView設置爲一個UIView,它具有嵌入的UILabel和UIImageView。我試圖添加一個UITapGestureRecognizer到視圖,但它似乎不工作。任何解決方案此外,添加一個gestureRecognizer到整個navigationBar是不是一個選項,因爲我有一個rightBarButtonItem,並希望利用後退按鈕。Swift UITapGesture在標題視圖不工作
這裏是我的代碼:
func configureTitleView() {
guard let profile = profile else {
// Pop navController
return
}
let titleView = UIView()
titleView.frame = CGRect(x: 0, y: 0, width: 100, height: 40)
let containerView = UIView()
containerView.translatesAutoresizingMaskIntoConstraints = false
titleView.addSubview(containerView)
let profileImageView = UIImageView()
profileImageView.translatesAutoresizingMaskIntoConstraints = false
profileImageView.contentMode = .scaleAspectFill
profileImageView.clipsToBounds = true
let imageURL = URL(string: profile!.firstProfilePicture!)
profileImageView.sd_setImage(with: imageURL)
containerView.addSubview(profileImageView)
profileImageView.leftAnchor.constraint(equalTo: containerView.leftAnchor).isActive = true
profileImageView.centerYAnchor.constraint(equalTo: containerView.centerYAnchor).isActive = true
profileImageView.widthAnchor.constraint(equalToConstant: 36).isActive = true
profileImageView.heightAnchor.constraint(equalToConstant: 36).isActive = true
profileImageView.layer.cornerRadius = 36/2
let nameLabel = UILabel()
containerView.addSubview(nameLabel)
nameLabel.text = profile!.displayName!
nameLabel.textColor = .white
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: containerView.rightAnchor).isActive = true
nameLabel.heightAnchor.constraint(equalTo: profileImageView.heightAnchor).isActive = true
containerView.centerXAnchor.constraint(equalTo: titleView.centerXAnchor).isActive = true
containerView.centerYAnchor.constraint(equalTo: titleView.centerYAnchor).isActive = true
self.navigationItem.titleView = titleView
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.openProfile))
tapGesture.numberOfTapsRequired = 1
titleView.addGestureRecognizer(tapGesture)
titleView.isUserInteractionEnabled = true
}
你可以分享你的代碼如何在導航欄中添加所有這些項目嗎?我希望你在背景視圖中添加輕擊手勢,並且圖像視圖和標籤位於視圖上方,因此手勢沒有響應。 – Bharath
一個建議,您可以嘗試添加一個清晰顏色的按鈕,而不是點擊手勢,就像添加另外兩個按鈕併爲該按鈕添加目標一樣。 – Bharath
@Bharath我已經添加了我的代碼...有沒有一種方法可以在不使用按鈕的情況下進行? –