0
我是Swift的新手,我一直在研究一個項目,並遇到了一個我修復的特殊問題,但並不確定解決方案的工作原因。創建變量時,爲什麼不需要輕敲手勢識別器?
我有一個類UserViewController
在那裏我做這樣的事情:
class UserViewController: UIViewController {
let profileImageView: UIImageView = {
let imageView = UIImageView()
imageView.image = UIImage(named: "profilepic")
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .scaleAspectFit
imageView.frame = CGRect.init(x: 0, y: 0, width: 30, height: 30) //CGRectMake(0, 0, 30, 30)
imageView.layer.cornerRadius = 0.5 * imageView.bounds.size.width
imageView.clipsToBounds = true
return imageView
}()
override func viewDidLoad() {
super.viewDidLoad()
setupView()
}
func setupView() {
view.addSubview(profileImageView)
profileImageView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
profileImageView.topAnchor.constraint(equalTo:topLayoutGuide.bottomAnchor, constant: 24).isActive = true
profileImageView.widthAnchor.constraint(equalToConstant: 80).isActive = true
profileImageView.heightAnchor.constraint(equalToConstant: 80).isActive = true
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleSelectProfilePicture))
profileImageView.addGestureRecognizer(tapGestureRecognizer)
profileImageView.isUserInteractionEnabled = true
}
我試圖敲擊手勢識別器添加到我的UIImageView
。我在做什麼之前,實際上是添加在我的初始化識別爲profileImageView
這樣的:
let profileImageView: UIImageView = {
let imageView = UIImageView()
imageView.image = UIImage(named: "profilepic")
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .scaleAspectFit
imageView.frame = CGRect.init(x: 0, y: 0, width: 30, height: 30) //CGRectMake(0, 0, 30, 30)
imageView.layer.cornerRadius = 0.5 * imageView.bounds.size.width
imageView.clipsToBounds = true
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleSelectProfilePicture))
profileImageView.addGestureRecognizer(tapGestureRecognizer)
profileImageView.isUserInteractionEnabled = true
return imageView
}()
當我這樣做,識別器不工作(我會挖掘圖像上並沒有什麼會發生,處理程序函數從未被調用)。當我拿出創建/添加手勢識別器的三條線到我的圖像視圖中,並將它們移動到setupView()
時,水龍頭被識別出來,並且一切按預期工作。
爲了更好的理解,爲什麼會出現這種情況?爲什麼我不能在我的圖像視圖的初始化中添加識別的手勢並讓它工作?
在此先感謝。