๐.draggable()
SwiftUI โฉ Gestures โฉ Drag โฉ .draggable()
import SwiftUI
// ๐ Draggable
struct Draggable: ViewModifier {
// ๐ธ ๆญค่ฎๆธ็ฎๅๆฒไป้บผ็จ๏ผไฝๅจๅ
ถไป็ๆณไธ๏ผไน่จฑๅฏๆดพไธ็จๅ ดใ
@State var isDragging = false
// ๐ธ ๆๆณๆ๏ผoffset ๆ้จๆๆดๆฐ๏ผไฝ dragOffset ไฟๆไธ่ฎใ
// ๆฒๆๆณๆ๏ผๅ
ฉ่
ๆฏไธๆจฃ็ใ
@State private var offset = CGSize.zero // current offset
@State private var dragOffset = CGSize.zero // prev accumulative offset
// โญ๏ธ optional event handlers
typealias OffsetHandler = (CGSize) -> Void
var onChanged: OffsetHandler?
var onEnded : OffsetHandler?
func body(content: Content) -> some View {
content
.offset(offset) // โญ๏ธ apply offset
.gesture(
DragGesture()
.onChanged { value in
isDragging = true
// update offset
offset = dragOffset + value.translation
// event handler
onChanged?(offset)
}
.onEnded { value in
isDragging = false
// update offset
offset = dragOffset + value.translation
// โญ๏ธ save accumulative offset
dragOffset = offset
// event handler
onEnded?(offset)
}
)
}
}
// ๐ View+ .draggable()
extension View {
/// `view.draggable(onChanged:onEnded:)`
func draggable(
onChanged: Draggable.OffsetHandler? = nil,
onEnded : Draggable.OffsetHandler? = nil
) -> some View {
modifier(Draggable(onChanged: onChanged, onEnded: onEnded))
}
}
โฌ๏ธ ้่ฆ๏ผ .frame(), HandlePoint
import SwiftUI
struct TestDraggable: View {
var body: some View {
VStack {
Group {
HandlePoint() // ๐ผ HandlePoint
Color.pink
.frame(50) // ๐ View+ .frame()
.draggable() // ๐ Draggable
Capsule()
.frame(200, 50) // ๐ View+ .frame()
.foregroundColor(.blue)
.draggable() // ๐ Draggable
}
.border(.secondary)
}
}
}
struct TestDraggable_Previews: PreviewProvider {
static var previews: some View {
TestDraggable()
}
}
Vasilis Akoinoglou โฉ Making a Bรฉzier Curve Editor in SwiftUI โญ๏ธ
HandlePoint - draggable point.
is ViewModifier.
Last updated