SwiftUI應用中的常見界面模式是內容卡片,該卡片可滑到其他內容上,無論是最小化的內容,還是半屏或全屏位置。例如,手機里面的地圖和股票應用。這里效果如何實現呢,下面讓我們來制作個浮動面板吧
本文價值與收獲
看完本文后,您將能夠作出下面的界面
看完本文您將掌握的技能
- 實現卡片拖拽和全屏
- 實現動畫效果
- 掌握自定義struct的方法
- 掌握ViewModifier使用
- 掌握MapKit技巧,實現地圖展示
代碼
1、主界面
import SwiftUI
import MapKit
struct ContentView : View {
@State private var position = CardPosition.top
@State private var background = BackgroundStyle.blur
var body: some View {
ZStack(alignment: Alignment.top) {
MapView()
VStack {
Picker(selection: self.$position, label: Text("Position")) {
Text("Bottom").tag(CardPosition.bottom)
Text("Middle").tag(CardPosition.middle)
Text("Top").tag(CardPosition.top)
Text("Full").tag(CardPosition.full)
}.pickerStyle(SegmentedPickerStyle())
Picker(selection: self.$background, label: Text("Background")) {
Text("Blur").tag(BackgroundStyle.blur)
Text("Clear").tag(BackgroundStyle.clear)
Text("Solid").tag(BackgroundStyle.solid)
}.pickerStyle(SegmentedPickerStyle())
}.padding().padding(.top, 25)
SlideOverCard($position, backgroundStyle: $background) {
VStack {
Text("可拖拽的內容卡片").font(.title)
Spacer()
}
}.zIndex(1)
}
.edgesIgnoringSafeArea(.vertical)
}
}
2、 封裝MapView
struct MapView : UIViewRepresentable {
func makeUIView(context: Context) -> MKMapView {
MKMapView(frame: .zero)
}
func updateUIView(_ view: MKMapView, context: Context) {
let coordinate = CLLocationCoordinate2D(latitude: 39.9042, longitude: 116.4074)
let span = MKCoordinateSpan(latitudeDelta: 0.2, longitudeDelta: 0.2)
let region = MKCoordinateRegion(center: coordinate, span: span)
view.setRegion(region, animated: true)
}
}
3、 完整代碼