How to make custom navigation bar in SwiftUI

Issue #823 Make atomic components and compose them. Firstly with NavigationBar that has custom leading and trailing content, there we can customize padding. import SwiftUI struct NavigationBar<Leading: View, Trailing: View>: View { @ViewBuilder let leading: Leading @ViewBuilder let trailing: Trailing var body: some View { HStack { leading Spacer() trailing } .padding(.horizontal, 8) } } struct NavigationBarWithBackButton: View { let onBack: () -> Void var body: some View { NavigationBar( leading: backButton, trailing: EmptyView....

July 20, 2021 路 1 min 路 Khoa Pham

How to convert NSEvent locationInWindow to window coordinate

Issue #822 Get active screen with mouse func activeScreen() -> NSScreen? { let mouseLocation = NSEvent.mouseLocation let screens = NSScreen.screens let screenWithMouse = (screens.first { NSMouseInRect(mouseLocation, $0.frame, false) }) return screenWithMouse } Reposition our NSWIndow if window.frame != screen.frame { window.setFrameOrigin(screen.frame.origin) window.setContentSize(screen.frame.size) } Flip y as AppKit has coordinate origin starting from bottom left of the screen, while our SwiftUI starts from top left var point = window.convertPoint(fromScreen: event.locationInWindow) point.y = window....

July 13, 2021 路 1 min 路 Khoa Pham

How to sync width for child views in SwiftUI

Issue #821 Suppose we have a 16:9 preview Image and we want the title Text to be the same width First we need PreferenceKey to store and sync size struct SizePreferenceKey: PreferenceKey { typealias Value = CGSize static var defaultValue: Value = .zero static func reduce(value: inout Value, nextValue: () -> Value) { value = nextValue() } } For our Image, we use a GeometryReader in the background with invisible View Color....

July 6, 2021 路 1 min 路 Khoa Pham

How to conform UIImage to Codable

Issue #819 Either use EasyStash or make a simple CodableImage struct CodableImage: Codable { let image: UIImage? init(image: UIImage) { self.image = image } enum CodingKeys: CodingKey { case data case scale } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let scale = try container.decode(CGFloat.self, forKey: .scale) let data = try container.decode(Data.self, forKey: .data) self.image = UIImage(data: data, scale: scale) } public func encode(to encoder: Encoder) throws { var container = encoder....

July 4, 2021 路 1 min 路 Khoa Pham

How to show custom context menu in SwiftUI

Issue #818 There鈥檚 a lot to do to imitate iOS ContextMenu look and feel vibrancy blur background haptics feedback targeted view position interaction dismiss gesture For now here鈥檚 a rough implementation of a custom context menu where we can show using .overlay import SwiftUI struct CustomContextMenu<Content: View>: View { @Binding var shows: Bool @ViewBuilder let content: Content var body: some View { ZStack { Color.black.opacity(0.1) .onTapGesture { shows = false } VStack(alignment: ....

July 2, 2021 路 1 min 路 Khoa Pham

How to declare View with ViewBuilder in SwiftUI

Issue #817 Thanks to resultBuilder and container type in Swift, the following are possible in SwiftUI Local variable struct ChartView { var body: some View { computation } @ViewBuilder var computation: some View { let left = 10 let right = 20 if left + right == 30 { Text("Correct") } } } if and switch statement struct ChartView: View { @State private var showsOverlay: Bool = false @State private var overlayKind: OverlayKind?...

July 2, 2021 路 2 min 路 Khoa Pham

How to make custom Menu in SwiftUI

Issue #816 SwiftUI supports Menu but the menu items only appear after the menu button is touched. We can initiate the look and feel of Menu with a custom implementation import SwiftUI struct CustomMenu<Content: View>: View { @ViewBuilder let content: Content var body: some View { VStack(spacing: 0) { content } .frame(width: 234) .background( Color(UIColor.systemBackground) .opacity(0.8) .blur(radius: 50) ) .cornerRadius(14) } } struct CustomMenuButtonStyle: ButtonStyle { let symbol: String let color: Color func makeBody(configuration: Configuration) -> some View { HStack { configuration....

July 1, 2021 路 1 min 路 Khoa Pham

How ObservableObject work in SwiftUI

Issue #815 When ever a property marked with @Published change, ObservableObject will emit objectWillChange.send hence telling the View that observes it to reinvalidate. In WWDC 2021 session Discover concurrency in SwiftUI they mention how objectWillChange is used to grab before-change data to diff the changes. In the below example, we have 2 ObservableObject Store with just count value being used in the View, while flag is not used Store2 with count not being used But since the View observes these 2 objects, whenever any @Publish property changes, SwiftUI thinks that the data changes, then invalidates the body again to see if it needs to redraw....

June 30, 2021 路 2 min 路 Khoa Pham

How to cancel vertical scrolling on paging TabView in SwiftUI

Issue #814 From iOS 14, TabView has the PageTabViewStyle that turns TabView into the equivalent UIPageViewController. We can of course implement our own Pager but the simple DragGesture does not bring the true experience of a paging UIScrollView or paging TabView. We can also use UIPageViewController under the hood but it鈥檚 hard to do lazy. Paging TabView in iOS 14 is built int and optimized for us. We just need to specify PageTabViewStyle, or just ....

June 29, 2021 路 3 min 路 Khoa Pham

How to update Firestore value with KeyPath in Swift

Issue #810 struct User { var createdAt: Date var name: Sttring var locked: Bool } extension KeyPath where Root == User { var keyPathString: String { switch self { case \User.createdAt: return "createdAt" case \User.name: return "name" case \User.locked: return "locked" default: return "" } } } Then we can call reference .collection("users") .document(user.id) .updateData([ (\User.locked).keyPathString:. true ])

June 26, 2021 路 1 min 路 Khoa Pham

How to show context menu with custom preview in SwiftUI

Issue #809 Add a hidden overlay UIContextMenuInteraction. Provide preview in previewProvider and actions in actionProvider. Use @ViewBuilder to make declaring preview easy. extension View { func contextMenuWithPreview<Content: View>( actions: [UIAction], @ViewBuilder preview: @escaping () -> Content ) -> some View { self.overlay( InteractionView( preview: preview, menu: UIMenu(title: "", children: actions), didTapPreview: {} ) ) } } private struct InteractionView<Content: View>: UIViewRepresentable { @ViewBuilder let preview: () -> Content let menu: UIMenu let didTapPreview: () -> Void func makeUIView(context: Context) -> UIView { let view = UIView() view....

June 26, 2021 路 3 min 路 Khoa Pham

How to login with Apple in SwiftUI

Issue #808 Make SignInWithAppleButton Wrap ASAuthorizationAppleIDButton inside UIViewRepresentable import SwiftUI import UIKit import AuthenticationServices struct SignInWithAppleButton: View { @Environment(\.colorScheme) private var colorScheme: ColorScheme var body: some View { ButtonInside(colorScheme: colorScheme) .frame(width: 280, height: 45) } } private struct ButtonInside: UIViewRepresentable { let colorScheme: ColorScheme func makeUIView(context: Context) -> ASAuthorizationAppleIDButton { switch colorScheme { case .dark: return ASAuthorizationAppleIDButton(type: .signIn, style: .white) default: return ASAuthorizationAppleIDButton(type: .signIn, style: .black) } } func updateUIView(_ uiView: ASAuthorizationAppleIDButton, context: Context) { // No op } } struct SignInWithAppleButton_Previews: PreviewProvider { static var previews: some View { SignInWithAppleButton() } } Handle logic in ViewModel import SwiftUI import AuthenticationServices import Resolver import Firebase import FirebaseAuth final class AuthViewModel: NSObject, ObservableObject { enum RequestState: String { case signIn case link case reauth } let firebaseService: FirebaseService var window: UIWindow?...

June 25, 2021 路 3 min 路 Khoa Pham

How to show modal window in AppKit

Issue #806 Use runModal https://developer.apple.com/documentation/appkit/nsapplication/1428590-runmodalsession Blocks main queue A loop that uses this method is similar in some ways to a modal event loop run with runModal(for:), except with this method your code can do some additional work between method invocations. When you invoke this method, events for the NSWindow object of this session are dispatched as normal. This method returns when there are no more events. You must invoke this method frequently enough in your loop that the window remains responsive to events....

June 24, 2021 路 1 min 路 Khoa Pham

How to perform action during long press in SwiftUI

Issue #805 Use LongPressGesture to detect when long-press gesture has been recognized, and chain with DragGesture to check when pressing still occurs Image(systemName: SFSymbol.deleteLeft.rawValue) .imageScale(.medium) .onTapGesture { onKeyCommand(.backspace) } .gesture( LongPressGesture() .onEnded { _ in self.timer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { _ in self.onKeyCommand(.backspace) } } .sequenced( before: DragGesture(minimumDistance: 0) .onEnded { _ in self.timer?.invalidate() self.timer = nil } ) )

June 20, 2021 路 1 min 路 Khoa Pham

How to use SwiftGen and LocalizedStringKey in SwiftUI

Issue #798 swiftgen.yml strings: inputs: PastePal/Resources/Localizable/en.lproj outputs: - templatePath: swiftgen-swiftui-template.stencil output: PastePal/Resources/Strings.swift Template from https://github.com/SwiftGen/SwiftGen/issues/685 swiftgen-swiftui-template.stencil // Generated using SwiftGen 鈥 https://github.com/SwiftGen/SwiftGen {% if tables.count > 0 %} import SwiftUI // MARK: - Strings {% macro parametersBlock types %}{% filter removeNewlines:"leading" %} {% for type in types %} {% if type == "String" %} _ p{{forloop.counter}}: Any {% else %} _ p{{forloop.counter}}: {{type}} {% endif %} {{ ", " if not forloop....

April 27, 2021 路 2 min 路 Khoa Pham

How to use ForEach with indices in SwiftUI

Issue #796 One seemingly obvious way to use ForEach on array with indices is using enumerated struct Book: Hashable, Identifiable { let id: UUID let name: String } struct BooksView: View { let books: [Book] var body: some View { List { ForEach(Array(books.enumerated()), id: \.element) { index, book in Text(book.name) .background(index % 2 == 0 ? Color.green : Color.orange) } } } } Reading the documentation for enumerated closely When you enumerate a collection, the integer part of each pair is a counter for the enumeration, but is not necessarily the index of the paired value....

April 20, 2021 路 2 min 路 Khoa Pham

How to resize NSImage with padding

Issue #795 extension NSImage { func resize(width: CGFloat, height: CGFloat, padding: CGFloat) -> NSImage { let img = NSImage(size: CGSize(width: width, height: height)) img.lockFocus() let ctx = NSGraphicsContext.current ctx?.imageInterpolation = .high self.draw( in: NSMakeRect(0, 0, width, height), from: NSMakeRect(0, -padding, size.width, size.height - padding), operation: .copy, fraction: 1 ) img.unlockFocus() return img } } So we can use like button.image = NSImage(named: NSImage.Name("pastePal"))?.resize(width: 22, height: 22, padding: -4)

April 15, 2021 路 1 min 路 Khoa Pham

How to convert from paid to freemium in SwiftUI with RevenueCat

Issue #794 I鈥檝e been distributing my apps PastePal and Push Hero as a paid upfront apps on Appstore. I鈥檝e quickly come to realize the importance of trials since many have requested a tryout before purchasing. Manual sending out trials comes with its own problem. I need to notarize and package the app as a dmg file, and not to even mention implement my own trial mechanism to check and notify of expired builds....

April 11, 2021 路 5 min 路 Khoa Pham

How to repeat array of object in Swift

Issue #793 To create array containing number of repeated value in Swift, we can use Array.init(repeating:count:) let fiveZs = Array(repeating: "Z", count: 5) print(fiveZs) // Prints "["Z", "Z", "Z", "Z", "Z"]" However, if we read Collection Types guide about Creating an Array with a Default Value Swift鈥檚 Array type also provides an initializer for creating an array of a certain size with all of its values set to the same default value....

March 22, 2021 路 2 min 路 Khoa Pham

How to use dynamic color in iOS

Issue #792 iOS 13 introduced Dark Mode with User Interface Style that makes it easy to support dark and light theme in our apps. Before we dive in, here are some official resources WWDC 2019 Implementing Dark Mode on iOS Supporting Dark Mode in Your Interface Choosing a Specific Interface Style for Your iOS App Adaptive color Like adaptive layout that adapts to different screen sizes, adaptive colors adapt to different user interface styles, for now they are light and dark mode....

March 13, 2021 路 7 min 路 Khoa Pham