如何在模拟器上使用tvOS接收触摸?我们需要知道触摸的位置。UIPress - 没有它!
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event {
// Never called
}
-(void)pressesEnded:(NSSet<UIPress *> *)presses withEvent:(nullable UIPressesEvent *)event {
// Works fine!
}
按键与物理按钮有关,比如Menu按钮。 当你开始按住这样的按钮时,一次按压就开始了,当你停止按住该按钮时,按压就结束了。 按键没有任何与屏幕相关的位置。
tvOS中的触控与iOS中的触控类似,但有一个重要的区别:它们是 "间接 "触控,即手指的位置和屏幕上的位置之间没有物理关系。
当一个触摸开始时,它将被传递到焦点视图中,触摸将被认为是在该视图的中心开始的,而不管手指在触摸表面上的绝对位置。 随着触摸的移动,其屏幕相关位置也会相应更新。
我不知道有什么API可以让你确定手指在触摸表面的绝对位置。
在你的情况下,让你的响应者成为焦点视图应该会导致它接收触摸事件。
我认为应该是 pressesBegan 而不是 touchedBegan。
(void)pressesBegan:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event
请记住tvOS没有 "触摸 "的概念,因为触摸屏幕。
官方处理 "taps "的方式是使用UITapGestureRecognizer。而这将是当一个项目处于焦点状态时,用户点击遥控器。
下面是我在用UICollectionView工作时的做法。
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
if let cell = collectionView.dequeueReusableCellWithReuseIdentifier("MovieCell", forIndexPath: indexPath) as? MovieCell {
let movie = movies[indexPath.row]
cell.configureCell(movie)
if cell.gestureRecognizers?.count == nil {
let tap = UITapGestureRecognizer(target: self, action: "tapped:")
tap.allowedPressTypes = [NSNumber(integer: UIPressType.Select.rawValue)]
cell.addGestureRecognizer(tap)
}
return cell
} else {
return MovieCell()
}
}
func tapped(gesture: UITapGestureRecognizer) {
if let cell = gesture.view as? MovieCell {
//Load the next view controller and pass in the movie
print("Tap detected...")
}
}
你可以从处理函数中传递的UITapGestureRecognizer中获取点击的位置。
也可以参考Apple TV的这个教程。https:/www.youtube.comwatch?v=XmLdEcq-QNI
一个简单的方法来做到这一点。
var tapGestureRecognizer: UITapGestureRecognizer!
override func didMoveToView(view: SKView) {
tapGestureRecognizer = UITapGestureRecognizer.init(target: self, action: Selector("tapped:"))
self.view?.addGestureRecognizer(tapGestureRecognizer)
}
func tapped(sender: UITapGestureRecognizer) {
// do something
}
看一下我的资源库。https:/github.comfredericdnddevtvOS-UITapGestureRecognizerblobmastertvOS%20GameGameScene.swift。
你可以使用触摸事件,比如 touchesBegan: withEvent:
但它们会被焦点引擎覆盖,只要屏幕上有可聚焦的项目,焦点引擎就会立即启用。
要将焦点事件与触摸事件结合起来使用,请看一下这个答案。https:/stackoverflow.coma62283786923288