我正在尝试在视频播放器上添加按钮。按钮已添加,但点击事件未从iOS模拟器触发。
但是,当我以编程方式执行时,事件会被准确触发。
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
guard let url = URL(string: "https://devstreaming-cdn.apple.com/videos/streaming/examples/bipbop_adv_example_hevc/master.m3u8") else {
return
}
// Create an AVPlayer, passing it the HTTP Live Streaming URL.
let player = AVPlayer(url: url)
// Create a new AVPlayerViewController and pass it a reference to the player.
let playerLayer = AVPlayerLayer(player: player)
playerLayer.frame = self.view.bounds
let btn = UIButton(type: .roundedRect)
btn.backgroundColor = UIColor.yellow
btn.setTitle("Do stuff 1", for: .normal)
btn.frame = CGRect(x: 0, y: 330, width: 300, height: 300)
btn.isUserInteractionEnabled = true
btn.addTarget( self, action: #selector(self.pressButton(button:)), for: .touchUpInside)
//btn.sendActions(for: .touchUpInside)
//controller.contentOverlayView?.addSubview(btn)
playerLayer.addSublayer(btn.layer)
self.view.layer.addSublayer(playerLayer)
player.play()
}
请帮忙。我怎样才能解决这个问题?
您无法使用storyboard按钮按下按钮,因为它位于图层后面。
你有两个选择。
1)在故事板中创建一个单独的视图,您可以在其中添加视频图层,而不是直接添加到主视图和按钮顶部
2)改变按钮的Z位置
button.layer.zPosition = 1
问题是您要添加按钮的图层而不是将按钮添加为子视图。这是您可以剪切和粘贴的完整代码。
import UIKit
import AVFoundation
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
guard let url = URL(string: "https://devstreaming-cdn.apple.com/videos/streaming/examples/bipbop_adv_example_hevc/master.m3u8") else {
return
}
// Create an AVPlayer, passing it the HTTP Live Streaming URL.
let player = AVPlayer(url: url)
// Create a new AVPlayerViewController and pass it a reference to the player.
let playerLayer = AVPlayerLayer(player: player)
playerLayer.frame = self.view.bounds
self.view.layer.addSublayer(playerLayer)
let btn = UIButton(type: .roundedRect)
btn.backgroundColor = UIColor.yellow
btn.setTitle("Do stuff 1", for: .normal)
btn.frame = CGRect(x: 0, y: 330, width: 300, height: 300)
btn.isUserInteractionEnabled = true
btn.addTarget( self, action: #selector(self.pressButton(button:)), for: .touchUpInside)
view.addSubview(btn)
player.play()
}
@objc func pressButton(button: Any) {
print("PRESSED")
}
}
但主要的是view.addSubview(btn)。