SwiftUI Tips

Binding to UserDefaults

1
2
3
4
5
6
7
class UD: ObservableObject {
@Published var date: Date = UserDefaults.standard.value(forKey: "date") as? Date ?? Date() {
didSet {
UserDefaults.standard.set(self.date, forKey: "date")
}
}
}

AppDelegate -> SceneDelegate

Many Delegates moved from AppDelegate.swift to SceneDelegate.swift

1
2
3
4
5
6
7
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {

}
// to
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
struct ContentView: View {
@EnvironmentObject var ud: UD

var body: some View {
let url = "Title:status?date=\(String(ud.firstDate.timeIntervalSince1970))"
return NavigationView {
VStack {
qrCodeImage(for: url)!

Spacer().frame(height: 50)

Text("\(ud.firstDate)")
}.navigationBarTitle("Title")
.navigationBarItems(trailing:
HStack {
NavigationLink(destination: PickerView(firstDate: $ud.firstDate)) {
Image(systemName: "gear")
}
}
)
}
}
}

PickerView Binding

1
2
3
4
5
6
7
8
9
10
11
12
13
struct PickerView: View {
@Binding var date: Date

var body: some View {
return NavigationView {
VStack {
DatePicker(selection: $date, in: ...Date(), displayedComponents: .date) {
Text("")
}
}
}
}
}

Fix SwiftUI Image Blank View

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
var ciContext = CIContext()

func qrCodeImage(for string: String) -> Image? {
let data = string.data(using: String.Encoding.utf8)
guard let qrFilter = CIFilter(name: "CIQRCodeGenerator") else { return nil }
qrFilter.setValue(data, forKey: "inputMessage")

let transform = CGAffineTransform(scaleX: 10, y: 10)

guard let ciImage = qrFilter.outputImage?.transformed(by: transform) else {
return nil
}

let cgImage = ciContext.createCGImage(ciImage, from: ciImage.extent)
// convert to UIImage
let uiImage = UIImage(cgImage: cgImage!)
let image = Image(uiImage: uiImage)

return image
}