如何从 SwiftUI 识别 Siri Remote 滑动手势。
我似乎还没有实施,那么我该如何解决呢?
另一种(更可靠但更老套)的方法是使用 GameController 低级 x/y 值进行 dPad 控制,
Siri遥控器也被认为是一个游戏控制器,它是第一个连接到苹果电视的游戏控制器,
所以在出现 SwiftUI 视图时,您可以执行以下操作:
import SwiftUI
import GameController
struct SwipeTestView: View
{
var body: some View
{
Text("This can be some full screen image or what not")
.onAppear(perform: {
let gcController = GCController.controllers().first
let microGamepad = gcController!.microGamepad
microGamepad!.reportsAbsoluteDpadValues = true
microGamepad!.dpad.valueChangedHandler = { pad, x, y in
let fingerDistanceFromSiriRemoteCenter: Float = 0.7
let swipeValues: String = "x: \(x), y: \(y), pad.left: \(pad.left), pad.right: \(pad.right), pad.down: \(pad.down), pad.up: \(pad.up), pad.xAxis: \(pad.xAxis), pad.yAxis: \(pad.yAxis)"
if y > fingerDistanceFromSiriRemoteCenter
{
print(">>> up \(swipeValues)")
}
else if y < -fingerDistanceFromSiriRemoteCenter
{
print(">>> down \(swipeValues)")
}
else if x < -fingerDistanceFromSiriRemoteCenter
{
print(">>> left \(swipeValues)")
}
else if x > fingerDistanceFromSiriRemoteCenter
{
print(">>> right \(swipeValues)")
}
else
{
//print(">>> tap \(swipeValues)")
}
}
})
.focusable() // <-- this is required only if you want to capture 'press' and 'LongPress'
.onLongPressGesture(minimumDuration: 1, perform: { // on press action
print(">>> Long press")
})
.onLongPressGesture(minimumDuration: 0.01, perform: { // on press action
print(">>> press")
})
}
}
这是一个更可靠的解决方案,并且每次都有效,您所要做的就是将手指从 Siri 遥控器的中心向外滑动到您想要的滑动方向(上/下/左/右),
你也可以实现这种方式上+左,上+右,下+左,下+右,循环顺时针滑动或循环逆时针以及任何你想要的。
您甚至可以使用同时手势()实现放大手势等
GCController.controllers().first
将返回 nil,您需要真正的硬件来尝试,看这个答案我在此基础上编写了几个扩展并进行了测试(tvOS 14.7),这是一个可以用作 tvOS 的 SwipeGesture 的扩展:
import SwiftUI
import GameController
// MARK: - View+swipeGestures
struct SwipeGestureActions: ViewModifier
{
// swipeDistance is how much x/y values needs to be acumelated by a gesture in order to consider a swipe (the distance the finger must travel)
let swipeDistance: Float = 0.7
// how much pause in milliseconds should be between gestures in order for a gesture to be considered a new gesture and not a remenat x/y values from the previous gesture
let secondsBetweenInteractions: Double = 0.2
// the closures to execute when up/down/left/right gesture are detected
var onUp: () -> Void = {}
var onDown: () -> Void = {}
var onRight: () -> Void = {}
var onLeft: () -> Void = {}
@State var lastY: Float = 0
@State var lastX: Float = 0
@State var totalYSwipeDistance: Float = 0
@State var totalXSwipeDistance: Float = 0
@State var lastInteractionTimeInterval: TimeInterval = Date().timeIntervalSince1970
@State var isNewSwipe: Bool = true
func resetCounters(x: Float, y: Float)
{
isNewSwipe = true
lastY = y // start counting from the y point the finger is touching
totalYSwipeDistance = 0
lastX = x // start counting from the x point the finger is touching
totalXSwipeDistance = 0
}
func body(content: Content) -> some View
{
content
.onAppear(perform: {
let gcController = GCController.controllers().first
let microGamepad = gcController!.microGamepad
microGamepad!.reportsAbsoluteDpadValues = false // assumes the location where the user first touches the pad is the origin value (0.0,0.0)
let currentHandler = microGamepad!.dpad.valueChangedHandler
microGamepad!.dpad.valueChangedHandler = { pad, x, y in
// if there is already a hendler set - execute it as well
if currentHandler != nil {
currentHandler!(pad, x, y)
}
/* check how much time passed since the last interaction on the siri remote,
* if enough time has passed - reset counters and consider these coming values as a new gesture values
*/
let nowTimestamp = Date().timeIntervalSince1970
let elapsedNanoSinceLastInteraction = nowTimestamp - lastInteractionTimeInterval
lastInteractionTimeInterval = nowTimestamp // update the last interaction interval
if elapsedNanoSinceLastInteraction > secondsBetweenInteractions
{
resetCounters(x: x, y: y)
}
/* accumelate the Y axis swipe travel distance */
let currentYSwipeDistance = y - lastY
lastY = y
totalYSwipeDistance = totalYSwipeDistance + currentYSwipeDistance
/* accumelate the X axis swipe travel distance */
let currentXSwipeDistance = x - lastX
lastX = x
totalXSwipeDistance = totalXSwipeDistance + currentXSwipeDistance
// print("y: \(y), x: \(x), totalY: \(totalYSwipeDistance) totalX: \(totalXSwipeDistance)")
/* check if swipe travel goal has been reached in one of the directions (up/down/left/right)
* as long as it is consedered a new swipe (and not a swipe that was already detected and executed
* and waiting for a few milliseconds stop between interactions)
*/
if (isNewSwipe)
{
if totalYSwipeDistance > swipeDistance && totalYSwipeDistance > 0 // swipe up detected
{
isNewSwipe = false // lock so next values will be disregarded until a few milliseconds of 'remote silence' achieved
onUp() // execute the appropriate closure for this detected swipe
}
else if totalYSwipeDistance < -swipeDistance && totalYSwipeDistance < 0 // swipe down detected
{
isNewSwipe = false
onDown()
}
else if totalXSwipeDistance > swipeDistance && totalXSwipeDistance > 0 // swipe right detected
{
isNewSwipe = false
onRight()
}
else if totalXSwipeDistance < -swipeDistance && totalXSwipeDistance < 0 // swipe left detected
{
isNewSwipe = false
onLeft()
}
else
{
//print(">>> tap")
}
}
}
})
}
}
extension View
{
func swipeGestures(onUp: @escaping () -> Void = {},
onDown: @escaping () -> Void = {},
onRight: @escaping () -> Void = {},
onLeft: @escaping () -> Void = {}) -> some View
{
self.modifier(SwipeGestureActions(onUp: onUp,
onDown: onDown,
onRight: onRight,
onLeft: onLeft))
}
}
你可以像这样使用它:
struct TVOSSwipeTestView: View
{
@State var markerX: CGFloat = UIScreen.main.nativeBounds.size.width / 2
@State var markerY: CGFloat = UIScreen.main.nativeBounds.size.height / 2
var body: some View
{
VStack
{
Circle()
.stroke(Color.white, lineWidth: 5)
.frame(width: 40, height: 40)
.position(x: markerX, y: markerY)
.animation(.easeInOut(duration: 0.5), value: markerX)
.animation(.easeInOut(duration: 0.5), value: markerY)
}
.background(Color.blue)
.ignoresSafeArea(.all)
.edgesIgnoringSafeArea(.all)
.swipeGestures(onUp: {
print("onUp()")
markerY = markerY - 40
},
onDown: {
print("onDown()")
markerY = markerY + 40
},
onRight: {
print("onRight()")
markerX = markerX + 40
},
onLeft: {
print("onLeft()")
markerX = markerX - 40
})
.focusable() // <-- this is required only if you want to capture 'press' and 'LongPress'
.onLongPressGesture(minimumDuration: 1, perform: { // on press action
print(">>> Long press")
})
.onLongPressGesture(minimumDuration: 0.01, perform: { // on press action go to middle of the screen
markerX = UIScreen.main.nativeBounds.size.width / 2
markerY = UIScreen.main.nativeBounds.size.height / 2
})
}
}
这个问题我有2个答案,我会分开回答,让你们决定哪个最好,
首先是苹果方式(显然并非总是有效,捕获的点击次数更多然后滑动):
import SwiftUI
struct SwipeTestView: View
{
var body: some View
{
Text("This can be some full screen image or what not")
.focusable() // <-- this is a must
.onMoveCommand { direction in // <-- this $#!* can't tell a move swipe from a touch (direction is of type: MoveCommandDirection)
print("Direction: \(direction)")
if direction == .left { print(">>> left swipe detected") }
if direction == .right { print(">>> right swipe detected") }
if direction == .up { print(">>> up swipe detected") }
if direction == .down { print(">>> down swipe detected") }
}
}
}
你真的(我不能强调这一点)必须在 Siri-remote 或 iPhone Siri 远程小部件的最边缘滑动,
因此,请尝试在这些黄色区域上滑动,并尽量不要用手指轻敲然后滑动,而是轻轻向外滑动,让您的手指完全脱离远程边缘
预期结果:
在成功捕获滑动之前我确实尝试了 100 多次(显然不是用于生产的东西),希望 tvOS 15 及更高版本能够解决这个问题