ios AVPlayer按钮动作不被触发

时间:2019-03-08 22:24:11

标签: ios swift avplayer

我正在尝试在视频播放器顶部添加按钮。已添加按钮,但未从iOS模拟器触发click事件。

但是,当我以编程方式进行操作时,事件会被准确触发。

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

请帮助。我该如何解决?

2 个答案:

答案 0 :(得分:0)

您无法使用情节提要按钮来按下按钮,因为它位于图层的后面。

您有两个选择。

1)在情节提要中创建一个单独的视图,您可以在其中添加视频层,而不是直接将其添加到主视图和其按钮顶部

2)更改按钮的Z位置

button.layer.zPosition = 1

答案 1 :(得分:0)

问题是您要添加按钮的图层,而不是将按钮添加为子视图。这是您可以剪切和粘贴的完整代码。

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)