如下图所示,我的视频几乎涵盖了整个屏幕。我想让视频在点击它时播放/停止。代码几乎完全正常,我称之为defInteractions
函数的类也包含booked
和comments
子视图,也可以在下面找到。因此,当我们点击这些我不想要的区域时,视频也会播放/停止。
UITapGestureRecognizer触发播放/暂停视频的功能:
//set interactions
func defInteractions (){
//singletap
let singleTap = UITapGestureRecognizer(target: self, action: #selector(singleTapDetected(_:)))
singleTap.numberOfTapsRequired = 1
//singleTap.cancelsTouchesInView = false
//controlsContainerView
controlsContainerView.addGestureRecognizer(singleTap)
}
//define type
var player: AVPlayer?
//set playing to false
var isPlaying: Bool = false
func singleTapDetected(_ sender: UITapGestureRecognizer) {
//play or pause
if(!isPlaying){
//play
player?.play()
isPlaying = true
}
else{
//pause
player?.pause()
isPlaying = false
}
}
每个子视图基本上都是这样的:
//create controls container view
let comments: UIView = {
//set properties of controls container view
let commentrect = CGRect(x: viewWidth / 2, y: viewHeight - 110, width: viewWidth / 2, height: 50)
let entireCommentView = UILabel(frame: commentrect)
entireCommentView.translatesAutoresizingMaskIntoConstraints = true
entireCommentView.backgroundColor = .white
entireCommentView.font = UIFont(name: "HelveticaNeue", size: 20)
entireCommentView.text = "3 comments"
entireCommentView.textColor = .black
entireCommentView.textAlignment = .center
return entireCommentView
}()
在override
中,他们被添加为子视图。我尝试在单个子视图中设置isUserInteractionEnabled
为false(例如评论:entireCommentView.isUserInteractionEnabled = false
),这些视图无效并且不知道如何实现我的目标。有人能帮我吗?我可以在UITapGestureRecognizer
识别器中从目标中排除这些子视图吗?
[
答案 0 :(得分:0)
修改singleTapDetected,如果点击位于任何顶部或底部UIView中,则返回。
func singleTapDetected(_ sender: UITapGestureRecognizer) {
let view = sender.view
let loc = sender.location(in: controlsContainerView)
if let subview = view?.hitTest(loc, with: nil) {
if subview == entireCommentView || subview == bookedView {
return
}
}
//play or pause
player?.rate != 0 && player?.error == nil ? player?.pause() : player?.play
}
或者,您可以让UIViewController
采用UIGestureRecognizerDelegate
协议并调用以下方法来检查视图。在此方法中,检查您对touch.view的视图并返回相应的bool(是/否)。像这样:
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
return !touch.view?.isDescendant(of: controlsContainerView)
}
答案 1 :(得分:0)
您应该将喜欢和预订变量定义为UIView子类本身的属性,以使它们对singleTapDetected(_:)
方法可见