Section 07 : Dismiss and Drag Anchors

Section 07 : Dismiss and Drag Anchors - 设定锚点(14’05")

Snap the card to different positions using multiple conditions and operators in SwiftUI.

在 SwiftUI 中使用多个条件和操作符将卡片置于不同位置

1. 设定状态变量

(1)一共要监视两个状态:1. 是否显示整张卡;2. 卡片目前的顶端相对位置,初始值是 0

@State var bottomState = CGSize.zero    // 记录 BottomCardView 的顶端相对位置
@State var showFull = false             // 是否显示整张 BottomCardView
卡片状态 self.showCard self.showFull self.bottomState.height
不显示 false - 0
半张卡 true false 0
整张卡 true true -300

(2)在 ContentView 中 BottomCardView 组件的上面加一个临时的 Text,用于监视相对位置的值。

Text("bottomState.height \n \(bottomState.height)").offset(y: -320)		// 监视相对高度位置,\n 是换行

**注意:**这里的文本中间不要键入,会报错的。

2. 确定动作的锚点

(1)显示整张卡时,

  • 不能向上移动,
  • 向下移动相对偏移量小于 250,保持整张卡;
  • 向下移动相对偏移量大于 250且小于50,保持半张卡;
  • 向下移动到相对偏移量大于 50,令showCard为false,卡消失。

(2)显示半张卡时,

  • 向上移动,相对偏移量小于 -100,显示整张卡;
  • 相对偏移量介于 -100 到 50之间,显示半张卡;
  • 相对偏移量大于 50, 卡消失

3. 修改 BottomCardView 组件

在 ContentView 中的 BottomCardView 组件中增加相对偏移量的偏移修饰和拖拽手势修饰,然后将刚才临时监视的文本框注释。

BottomCardView()
    .offset(x: 0, y: showCard ? 360 : 1000) // 默认不显示,单击切换 showCard 为 true 时显示
    .offset(y: bottomState.height)          // 使用相对偏移量控制卡片顶端位置
    .blur(radius: show ? 20 : 0)
    .animation(.timingCurve(0.2, 0.8, 0.2, 1, duration: 0.8))   // 时序曲线动画
    .gesture(
    	DragGesture()                       // 使用拖拽手势
        	.onChanged { value in           // 拖拽中
                self.bottomState = value.translation
                if self.showFull {
                	self.bottomState.height += -300
                }
                if self.bottomState.height < -300 {
                	self.bottomState.height = -300
                }
        }
        .onEnded { value in                 // 拖拽停止时
        	if self.bottomState.height > 50 {
            	self.showCard = false
            }    
            if (self.bottomState.height < -100 && !self.showFull) || (self.bottomState.height < -250 && 				self.showFull) {
            	self.bottomState.height = -300
                self.showFull = true
            } else {
            	self.bottomState = .zero
                self.showFull = false
            }
        }
    )

本节小结

本节代码请参见 GitHub码云

  • 拖拽手势 DragGesture 的使用,两个常用的方法:onChanged 和 onEnded。
  • 根据需要选择锚点,分析手势操作逻辑
  • 使用状态变量对卡片的位置进行控制
  • if 语句的使用。

接下来

SF Symbol,图标以及如何向组件传递属性。

发布了51 篇原创文章 · 获赞 15 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/hh680821/article/details/104989353
今日推荐