我在UIImageView中添加了一个AVPlayerLayer层,在UIImageView中添加了UITapGestureRecognizer。是的,我给了委托,并且UIImageView也启用了用户交互。但是水龙头不起作用。

有谁详细了解AVPlayerLayer。

let imageViewTap = UITapGestureRecognizer(target: self, action: #selector(imageViewTapped))
imageViewTap.numberOfTapsRequired = 1
imageView.addGestureRecognizer(imageViewTap)

let item = AVPlayerItem(asset: videoAsset)
videoPlayer = AVPlayer(playerItem: item)
videoPlayerLayer = AVPlayerLayer(player: videoPlayer)
videoPlayerLayer.frame = imageView.bounds
videoPlayerLayer.backgroundColor = UIColor.black.cgColor
imageView.layer.insertSublayer(videoPlayerLayer, at: 0)

 @objc func imageViewTapped(){
        print("my code here")
}

最佳答案

检查是否添加了AVPlayerLayer。在index O处添加图层,而不是将其添加到顶部。

使用insertSublayer(_:at:)而不是addSublayer(_:)

class ViewController: UIViewController, UIGestureRecognizerDelegate {
    @IBOutlet weak var imageView: UIImageView!

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        self.imageView.isUserInteractionEnabled = true
        self.addPlayer()
    }

    func addPlayer() {
        if let url = URL(string: "https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4") {
            let player = AVPlayer(url: url)
            let playerLayer = AVPlayerLayer(player: player)
            playerLayer.frame = self.imageView.bounds
            playerLayer.videoGravity = .resizeAspect
            self.imageView.layer.insertSublayer(playerLayer, at: 0)
            player.play()
        }

        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(tapHandler(_:)))
        tapGesture.delegate = self
        self.imageView.addGestureRecognizer(tapGesture)
    }

    @objc func tapHandler(_ sender: UIGestureRecognizerDelegate) {
        print("view tapped")
    }
}

现在,只要您点击view,就会调用tapHandler(_:)方法。

不要忘记手动启用userInteractionimageView
self.imageView.isUserInteractionEnabled = true

关于ios - 无法触摸包含AVPlayerLayer的UIView,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56181076/

10-12 05:39