SwiftUI:Gesture var 是不是可能移入 EnvironmentObject?
Posted
技术标签:
【中文标题】SwiftUI:Gesture var 是不是可能移入 EnvironmentObject?【英文标题】:SwiftUI: is possible Gesture var move into EnvironmentObject?SwiftUI:Gesture var 是否可能移入 EnvironmentObject? 【发布时间】:2021-10-22 10:18:24 【问题描述】:我不熟悉 SWIFTUI 和闭包。这里将一些手势代码移动到扩展功能,除了 var drag。 对于手势,是否可以将拖动移动到 environmentObject 中?如何初始化?
class ViewState:ObservableObject
@Published var isDragging = false
@Published var size: CGFloat = 100.0
struct ContentView: View
@StateObject var viewState:ViewState=ViewState()
var drag:some Gesture isDrag(viewState)
var body: some View
Circle()
.fill(viewState.isDragging ? Color.red: Color.blue)
.frame(width:viewState.size, height:viewState.size, alignment: .center)
.gesture(drag)
extension ContentView
func isDrag(_ viewState:ViewState)->some Gesture
DragGesture()
.onChanged _ in
viewState.isDragging = true
viewState.size += 10.0
.onEnded_ in
viewState.isDragging = false
viewState.size = 100.0
【问题讨论】:
【参考方案1】:完成,闭包就是函数!现在,我可以将此代码移动到其他视图,但仍会更新视图风险。并且声明的数据(environmentObject)不是独立的。
class ViewState:ObservableObject
@Published var isDragging = false
@Published var size: CGFloat = 100.0
struct ContentView: View
@StateObject var viewState:ViewState=ViewState()
// var drag:some Gesture
var body: some View
Circle()
.fill(viewState.isDragging ? Color.red: Color.blue)
.frame(width:viewState.size, height:viewState.size, alignment: .center)
.isDragged(viewState)
extension View
func drag(_ viewState:ViewState)->some Gesture
DragGesture()
.onChanged _ in
viewState.isDragging = true
viewState.size += 10.0
.onEnded_ in
viewState.isDragging = false
viewState.size = 100.0
@ViewBuilder func isDragged(_ viewState:ViewState) -> some View
self.gesture(drag(viewState))
【讨论】:
以上是关于SwiftUI:Gesture var 是不是可能移入 EnvironmentObject?的主要内容,如果未能解决你的问题,请参考以下文章
SwiftUI手势(Gesture)进阶 : 实现任意视图的长按惯性加速行为
SwiftUI手势(Gesture)进阶 : 实现任意视图的长按惯性加速行为
Swiftui 如何在 foreach 循环中对整行使用 Tap Gesture
Swift / SwiftUI:如何检查环境 /binding var 是不是为空字符串(.isEmpty 出现构建错误)