How to handle slow large dataset Picker when dragging in SwiftUI

Issue #897 During continuous events like dragging or TextField typing, and we have a Picker onscreen with large data set, it will slow down main thread. One option is to explicitly conform that view to Equatable struct FontPicker: View, Equatable { @Binding var fontFamily: String var body: some View { Picker("", selection: $fontFamily) { ForEach(NSFontManager.shared.availableFontFamilies, id: \.self) { family in Text(family) .tag(family) } } } static func == (l: FontPicker, r: FontPicker) -> Bool { l....

July 28, 2022 · 1 min · Khoa Pham

How to pass FocusState binding in SwiftUI

Issue #896 Use underscore _focus we get access to underlying FocusState object, but underscore _ is private to a View hence can’t be used in extension If we want to pass FocusState to another View or in extension, we can pass its Binding enum FocusElement: Hashable { case name case email } struct ParentView: View { @FocusState var focus: FocusElement? var body: some View { ChildView1(focus: _focus) ChildView2(focus: $focus) } } struct ChildView1: View { @FocusState var focus: FocusElement?...

July 28, 2022 · 1 min · Khoa Pham

How to move reversed List in SwiftUI

Issue #895 Apply .move on reversed array List(selection: $viewModel.selectedBook) { ForEach(viewModel.books.reversed()) { book in BookCell(book: book) } .onMove { source, dest in var reversed = Array(viewModel.books.reversed()) reversed.move(fromOffsets: source, toOffset: dest) viewModel.books = reversed.reversed() } }

July 25, 2022 · 1 min · Khoa Pham

How to set popoverPresentationController sourceView in SwiftUI

Issue #894 Use a UIView as source view and set it in background class ViewModel { lazy var sourceView = UIView() } struct SourceView: UIViewRepresentable { let viewModel: ViewModel func makeUIView(context: Context) -> UIView { viewModel.sourceView } func updateUIView(_ uiView: UIView, context: Context) {} } Button(action: { onShowAlert(viewModel.sourceView) }) { Image(systemName: "bookmark") } .background(SourceView(viewModel: viewModel)) let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) alertController.popoverPresentationController?.sourceView = viewModel.sourceView

July 8, 2022 · 1 min · Khoa Pham

Essential WWDC sample codes

Issue #892 WWDC21 Building a Great Mac App with SwiftUI Add Rich Graphics to Your SwiftUI App

June 10, 2022 · 1 min · Khoa Pham

My favorite WWDC videos

Issue #891 Below are my favorite WWDC videos. My focus is to use SwiftUI to make useful apps with great UX. I don’t pay much attention to new frameworks as they come and go, but the underlying reasons and design principles are worth remembering. WWDC23 The SwiftUI cookbook for focus Discussing some of the things that you can do with focus APIs in SwiftUI to cook up a really great user experience...

June 10, 2022 · 5 min · Khoa Pham

WWDC swiftui-lounge

Issue #890 In WWDC21, WWDC22 Apple provide a Slack channel https://wwdc22.slack.com/ for people to interact with Apple engineers in digital lounges. Here I note down some interesting Q&As WWDC22 What’s the difference between a custom ViewModifier vs View extension Q: What’s the difference between a custom ViewModifier (without DynamicProperty) that uses some built-in modifiers in body(content:), and a custom View extension func that just use those built-in modifiers? Similarly, what’s the difference between a custom ViewModifier with some DynamicProperty and a custom View with some DynamicProperty (also has a @ViewBuilder content property to receive content to modify) ?...

June 10, 2022 · 32 min · Khoa Pham

WWDC22 SwiftUI Q&A

Issue #890 Interesting SwiftUI Q&A during WWDC22 What’s the difference between a custom ViewModifier vs View extension Q: What’s the difference between a custom ViewModifier (without DynamicProperty) that uses some built-in modifiers in body(content:), and a custom View extension func that just use those built-in modifiers? Similarly, what’s the difference between a custom ViewModifier with some DynamicProperty and a custom View with some DynamicProperty (also has a @ViewBuilder content property to receive content to modify) ?...

June 10, 2022 · 25 min · Khoa Pham

What's new in SwiftUI iOS 16 at WWDC22

Issue #889 What’s new in SwiftUI New EnvironmentValues TextField inside Alert List uses UICollectionView See gist https://gist.github.com/onmyway133/fc08111964984ef544a176a6e9806c18 ButtonStyle composition Section("Hashtags") { VStack(alignment: .leading) { HStack { Toggle("#Swiftastic", isOn: $swiftastic) Toggle("#WWParty", isOn: $wwdcParty) } HStack { Toggle("#OffTheCharts", isOn: $offTheCharts) Toggle("#OneMoreThing", isOn: $oneMoreThing) } } .toggleStyle(.button) .buttonStyle(.bordered) } Customize Charts struct MonthlySalesChart: View { var body: some View { Chart(data, id: \.month) { BarMark( x: .value("Month", $0.month, unit: .month), y: .value("Sales", $0.sales) ) } ....

June 9, 2022 · 5 min · Khoa Pham

How to use SwiftUI

Issue #886 SwiftUI iOS 16 https://bigmountainstudio.github.io/What-is-new-in-SwiftUI/ https://swiftwithmajid.com/2022/06/07/what-is-new-in-swiftui-after-wwdc22/ https://www.hackingwithswift.com/articles/250/whats-new-in-swiftui-for-ios-16 SwiftUI https://www.hackingwithswift.com/articles/235/whats-new-in-swiftui-for-ios-15 https://www.hackingwithswift.com/articles/221/whats-new-in-swiftui-for-ios-14 https://talk.objc.io/collections/swiftui-layout-explained SwiftUI practices 8 Common SwiftUI Mistakes – and how to fix them! https://www.youtube.com/watch?v=qkcKTJhDyLs 5 Steps to Better SwiftUI Views https://www.youtube.com/watch?v=uC3X4FoielU SwiftUI tips and tricks https://www.hackingwithswift.com/quick-start/swiftui/swiftui-tips-and-tricks SwiftUI Tips https://www.youtube.com/watch?v=M2e1Z9enFHo Tips thread https://twitter.com/twostraws/status/1465801488920465414?s=20 Quick Friday tips https://twitter.com/search?src=typed_query&q=%22Quick%20Friday%20tip%22%20(from%3Ascottsmithdev Reference https://github.com/onmyway133/awesome-swiftui https://swiftontap.com/

June 7, 2022 · 1 min · Khoa Pham

How SwiftUI works

Issue #883 Read more https://www.objc.io/blog/2020/11/10/hstacks-child-ordering/ https://talk.objc.io/collections/swiftui-layout-explained https://rensbr.eu/blog/swiftui-escaping-closures/ https://rensbr.eu/blog/swiftui-render-loop/ https://movingparts.io/variadic-views-in-swiftui

May 31, 2022 · 1 min · Khoa Pham

How to use popover in SwiftUI

Issue #882 In SwiftUI, .popover shows as popover on Mac and iPad, but as .sheet on iPhone (compact size class) We can use minWidth, minHeight to specify sizes on Mac and iPad. On iPhone, we can check and wrap it inside NavigationView. Setting navigationTitle without being embedded in NavigationView has not effect `` .popover(isPresented: $showsEdit) { EditSnippetView( snippet: snippet ) .frame(minWidth: 300, alignment: .topLeading) .navigationTitle("Tags") .modifier( EmbedInNavigationModifier() ) }

May 29, 2022 · 1 min · Khoa Pham

How to select in List in SwiftUI

Issue #881 Specify optional value for List(selection:). This keeps selection on macOS, but not on iPad. On iPad each row in the List needs to be NavigationLink, no need for .tag. The selection is not updated, need to manually update with onTapGesture For List selection to work, make sure selection binding type matches. Preferablly using ID than Self Need to specify id in ForEach for List to infer tag. Otherwise, need to specify tag for cell struct Sidebaer: View { class ViewModel: ObservableObject { @Published var group: BookGroup?...

May 27, 2022 · 1 min · Khoa Pham

How to allow multiple selection in List in SwiftUI

Issue #878 Note that Explicit id is needed, although Book already conforms to Identifiable selection needs a default value class BookViewModel: ObservableObject { @Published var books: [Book] = [] @Published var selectedBooks: Set<Book> = [] } List(selection: $viewModel.selectedBooks) { ForEach(viewModel.books, id: \.self) { book in BookRow(book: book) } }

April 30, 2022 · 1 min · Khoa Pham

How to use ViewBuilder in SwiftUI

Issue #877 Over the course of making several SwiftUI apps, I’ve discovered quite a few hidden magic of SwiftUI that are quite fun. Here are 6 interesting SwiftUI features in View Builder many don’t know are even possible 🤯 View protocol with enum Struct is not the only way to describe #SwiftUI views. Learn how you can achieve the same thing with just enum Conform primitive type to View protocol You can also conform any value type or primitive type to View protocol...

April 11, 2022 · 2 min · Khoa Pham

How to debounce TextField search in SwiftUI

Issue #876 Make a dedicate DebounceObject to debounce (or throttle). Then we can even observe with onChange on the debouncedText or just use it directly to sort import Combine public final class DebounceObject: ObservableObject { @Published var text: String = "" @Published var debouncedText: String = "" private var bag = Set<AnyCancellable>() public init(dueTime: TimeInterval = 0.5) { $text .removeDuplicates() .debounce(for: .seconds(dueTime), scheduler: DispatchQueue.main) .sink(receiveValue: { [weak self] value in self?...

March 26, 2022 · 1 min · Khoa Pham

How to pop multiple level with NavigationView and NavigationLink in SwiftUI

Issue #858 Use isActive and isDetailLink(false) Use Introspect .introspectNavigationController { nav in self.nav = nav } Read more https://www.cuvenx.com/post/swiftui-pop-to-root-view

January 27, 2022 · 1 min · Khoa Pham

How to show QR code in SwiftUI

Issue #855 Use CoreImage to generate QR image import SwiftUI import CoreImage.CIFilterBuiltins struct QRView: View { let qrCode: String @State private var image: UIImage? var body: some View { ZStack { if let image = image { Image(uiImage: image) .resizable() .interpolation(.none) .frame(width: 210, height: 210) } } .onAppear { generateImage() } } private func generateImage() { guard image == nil else { return } let context = CIContext() let filter = CIFilter....

January 15, 2022 · 1 min · Khoa Pham

How to disable with ButtonStyle in SwiftUI

Issue #853 With ButtonStyle, the disabled modifier does not seem to work, we need to use allowsHitTesting. import SwiftUI struct ActionButtonStyle: ButtonStyle { func makeBody(configuration: Configuration) -> some View { HStack { Text("Button") } .padding() .disabled(true) // does not work .allowsHitTesting(false) } } We need to call disabled outside, after buttonStyle. In case we have onTapGesture on the entire view, touching on that disabled button will also trigger our whole view action, which is not what we want....

December 4, 2021 · 1 min · Khoa Pham

How to use dynamic shape in SwiftUI

Issue #850 Erase with AnyShape struct AnyShape: Shape { init<S: Shape>(_ wrapped: S) { innerPath = { rect in let path = wrapped.path(in: rect) return path } } func path(in rect: CGRect) -> Path { return innerPath(rect) } private let innerPath: (CGRect) -> Path } extension Shape { func erase() -> AnyShape { AnyShape(self) } } Then we can use like private struct ContentView: View { var body: some View { ZStack { Color....

September 30, 2021 · 1 min · Khoa Pham