所以我现在正试图让这个按钮工作,称为播放按钮
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 :(得分: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
吗?
答案 1 :(得分:0)
正确的方法签名是
button.addTarget(self, action: #selector(pressBackButton(_:)), for: .touchUpInside)
和
func pressBackButton(_ button: UIButton) {