DragGesture
SwiftUI imo-ishoralar: DragGesture
Barmoq harakatini kuzating va DragGesture ga javoban view joylashuvi yoki state’ni yangilang.
Sintaksis
Sudrash: DragGesture() ni biriktiring va .onChanged/.onEnded ni qayta ishlang.
Siljishni (translation) .offset orqali qo‘llang.
Sudrab ko‘chirish
Yorliqni sudrab, uni joyidan ko‘chiring. Qo‘yib yuborilganda u spring animatsiyasi yordamida joyiga qaytadi.
Misol
import SwiftUI
struct DragDemo: View {
@State private var offset: CGSize = .zero
var body: some View {
Text("Drag me")
.padding(12)
.background(.blue.opacity(0.1))
.cornerRadius(8)
.offset(offset)
.gesture(
DragGesture()
.onChanged { value in offset = value.translation }
.onEnded { _ in withAnimation(.spring()) { offset = .zero } }
)
}
}
import SwiftUI
struct ContentView: View {
var body: some View { DragDemo() }
}
import SwiftUI
@main
struct MyApp: App {
var body: some Scene {
WindowGroup { ContentView() }
}
}
Yuqoridagi misolda yorliq sudraladi va qo‘yib yuboriladi.
.onEnded ishlovchisi uni spring animatsiyasi yordamida joyiga qaytaradi.
Sudrashni chegaralar ichida cheklash
View konteyner ichida qolishi uchun sudrash siljishini cheklang (clamp).
Misol
import SwiftUI
struct DragBoundsDemo: View {
@State private var offset: CGSize = .zero
let limit: CGFloat = 120
func clamp(_ v: CGFloat) -> CGFloat { min(max(v, -limit), limit) }
var body: some View {
ZStack {
RoundedRectangle(cornerRadius: 12)
.stroke(.gray.opacity(0.4), lineWidth: 1)
.frame(width: 280, height: 160)
Circle()
.fill(.blue.opacity(0.2))
.frame(width: 44, height: 44)
.offset(x: offset.width, y: offset.height)
.gesture(
DragGesture()
.onChanged { value in
offset = CGSize(width: clamp(value.translation.width), height: clamp(value.translation.height))
}
.onEnded { _ in withAnimation(.spring()) { offset = .zero } }
)
}
.padding()
}
}
import SwiftUI
struct ContentView: View {
var body: some View { DragBoundsDemo() }
}
import SwiftUI
@main
struct MyApp: App {
var body: some Scene {
WindowGroup { ContentView() }
}
}
Yuqoridagi misolda doira sudraladi va qo‘yib yuboriladi.
.onEnded ishlovchisi uni spring animatsiyasi yordamida joyiga qaytaradi.
W3Schools Pathfinder
Yutuqlaringizni kuzating – bu bepul!
