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)
在初始化程序之外访问自身的函数或属性。
class TestViewController: UIViewController {
let playButton: UIButton = {
let button = UIButton()
let image = UIImage(named: "VideoIcon.png") as UIImage?
button.backgroundImage(for: .normal)
button.setImage(image, for: .normal)
return button
}()
override func viewDidLoad() {
super.viewDidLoad()
button.addTarget(self, action: #selector(pressBackButton(button:)), for: .touchUpInside)
}
}
答案 1 :(得分:0)
而不是:
let playButton: UIButton = {
...
...
return button
}()
哪个不起作用(因为你试图在错误的时间创建playButton
- 这是在视图加载之前或即将出现之前)
在viewDidLoad
或viewWillAppear
中,创建按钮,定义目标并将其添加为子视图。
override func viewDidLoad() {
super.viewDidLoad()
let button = UIButton()
if 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)
}
self.addSubview(button)
}
将按钮添加为子视图increments the retain count(即它不会消失),但如果您想将其保留为属性,只需将其声明为:
var playButton : UIButton?
然后在playButton = button
的末尾设置viewDidLoad
。