2017-03-22 49 views
0

http://pastebin.com/MgQ7wx3g編程按鈕不起作用

所以目前我正在試圖讓這個按鈕的工作叫做Play按鈕

let playButton: UIButton = { 
    let button = UIButton() 
    let image = UIImage(named: "VideoIcon.png") as UIImage? 
    button.backgroundImage(for: .normal) 
    button.addTarget(self, action: #selector(pressBackButton(button:)), for: .touchUpInside) 
    button.setImage(image, for: .normal) 

    return button 
}() 

func pressBackButton(button: UIButton) { 
print("test") 
    if let playVideoButtonURL = post?.videourl { 

     let player = AVPlayer(url: playVideoButtonURL as URL) 
     let playerLayer = AVPlayerLayer(player:player) 
     playerLayer.frame = CGRect(x: 100, y: 200, width: 100, height: 100) 
     playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill 
     self.layer.addSublayer(playerLayer) 
     player.play() 

    } 

} 

當我點擊它沒有任何反應,即使在視頻編碼是錯誤的它仍然應該打印測試。它在啓動時不會給我帶來任何錯誤。粘貼箱有我的完整代碼。

回答

0

我試過你給出的代碼,並明確設置了框架。

override func viewDidLoad() { 
    super.viewDidLoad() 

    // Set Frame 
    self.playButton.frame = CGRect(origin: CGPoint(x: self.view.frame.width/2, y: self.view.frame.height/2), size: CGSize(width: 30, height: 30)) 
    self.view.addSubview(playButton) 
} 

它的工作完美,「測試」是打印。

然後我檢查了您在特定鏈接中發佈的代碼。在那裏,我發現這種方法addConstraintsWithFormat設置自動佈局與視覺格式語言。我用這種方法替換了我的代碼。

self.view.addConstraintsWithFormat(format: "H:|-280-[v0(44)]", view: playButton) 
self.view.addConstraintsWithFormat(format: "V:|-90-[v0(44)]", view: playButton) 

它也在工作。

從您的代碼我可以發現它是一個CollectionViewCell。可以請嘗試添加子視圖到contentView

+0

所以我試圖改變addSubview到contentView.addsubview按鈕仍然顯示,但是當我在它 – Tim

+0

@Tim我覺得還是點擊沒有任何反應它的一些約束問題。首先,我只設置了水平約束並忘記了垂直約束,並且它不工作。 –

+0

啊好吧。然後我會研究它。謝謝你的幫助! – Tim

0

正確的方法簽名是

button.addTarget(self, action: #selector(pressBackButton(_:)), for: .touchUpInside) 

func pressBackButton(_ button: UIButton) {