2016-11-20 63 views
0

我不知道爲什麼我的代碼不工作:Swift 3中的AddGesture不同?

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?

+0

設法留住ImageView的。實例可能會被釋放。全局初始化圖像並添加手勢。 – Gyanendra

+0

你是什麼意思? – petaire

+0

讓圖像= UIImageView()把它放在其他地方,如viewDidLoad和在這個方法裏面使用圖像變量 – Gyanendra

回答

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) 

的目標是 「自我」,這是的UIViewController(而不是UIImageView的)。在大多數情況下(我確定存在異常值),您希望在視圖中記錄手勢,但在視圖控制器中使用手勢。

+0

不,但我只是不得不添加一個懶惰......它是固定的。 – petaire

1

好的解決方案其實很簡單。你必須讓它成爲一個懶惰的變量而不是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 
}() 
0

雨燕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") 
    } 

只是爲了測試我刪除的圖像,你可以添加它。但它工作正常。

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