How to use Core Data

Issue #785 Core Data Responding to changes in a managed object context Calling mergeChanges on a managed object context will automatically refresh any managed objects that have changed. This ensures that your context always contains all the latest information. Note that you don’t have to call mergeChanges on a viewContext when you set its automaticallyMergesChangesFromParent property to true. In that case, Core Data will handle the merge on your behalf....

February 26, 2021 · 6 min · 1109 words · Khoa

How to force resolve Swift Package in Xcode

Issue #784 Every time I switch git branches, SPM packages seem to be invalidated and Xcode does not fetch again, no matter how many times I reopen. Running xcodebuild -resolvePackageDependencies does fetch but Xcode does not recognize the resolved packages and still reports missing packages. The good thing is under menu File -> Swift Packages there are options to reset and resolve packages

February 26, 2021 · 1 min · 63 words · Khoa

How to listen to remote changes in CloudKit CoreData

Issue #783 Remove chane notification Read Consuming Relevant Store Changes If the import happens through a batch operation, the save to the store doesn’t generate an NSManagedObjectContextDidSave notification, and the view misses these relevant updates. Alternatively, the background context may save changes to the store that don’t affect the current view—for example, inserting, modifying, or deleting Shape objects. These changes do generate context save events, so your view context processes them even though it doesn’t need to....

February 25, 2021 · 1 min · 141 words · Khoa

How to listen to Published outside of SwiftUI view

Issue #782 Use $ to access Publisher final class Store: ObservableObject { @Published var showsSideWindow: Bool = false } var anyCancellables = Set<AnyCancellable>() store.$showsSideWindow .removeDuplicates() .throttle(for: 0.2, scheduler: RunLoop.main, latest: true) .receive(on: RunLoop.main) .sink(receiveValue: { shows in preferenceManager.reloadPosition(shows: shows) }) .store(in: &anyCancellables)

February 25, 2021 · 1 min · 42 words · Khoa

How to filter non numeric digit from String in Swift

Issue #781 This sounds like an easy task, but a quick search on Stackoverflow results in this with highest votes https://stackoverflow.com/questions/29971505/filter-non-digits-from-string CharacterSet.decimalDigits contains more than just digits This splits a string by inverted set of decimalDigits and join them back. extension String { var digits: String { return components(separatedBy: CharacterSet.decimalDigits.inverted) .joined() } } Reading decimalDigits Informally, this set is the set of all characters used to represent the decimal values 0 through 9....

February 25, 2021 · 2 min · 216 words · Khoa

How to build container view in SwiftUI

Issue #780 To make a container view that accepts child content, we use ViewBuilder struct ContainerView<Content: View>: View { let content: Content init(@ViewBuilder content: () -> Content) { self.content = content() } var body: some View { content } } From Swift 5.4, it can synthesize the init, so we can declare resultBuilder for stored property struct AwesomeContainerView<Content: View>: View { @ViewBuilder let content: Content var body: some View { content } }

February 24, 2021 · 1 min · 73 words · Khoa

How to tune performance with ButtonBehavior in SwiftUI

Issue #779 With Xcode 12.4, macOS 11.0 app. Every time we switch the system dark and light mode, the CPU goes up to 100%. Instruments show that there’s an increasing number of ButtonBehavior Suspect State in a row in LazyVStack Every cell has its own toggle state struct Cell: View { enum ToggleState { case general case request case response } let item: Item @State private var toggleState: ToggleState = ....

February 24, 2021 · 1 min · 141 words · Khoa

How to use GroupBox in SwiftUI

Issue #778 For now using GroupBox has these issues in macOS Prevents dragging scroll indicator to scroll Switch from light to dark mode may cause 100% CPU usage

February 23, 2021 · 1 min · 28 words · Khoa

How to suppress selector warning in Swift

Issue #777 Sometimes we need to use dynamic selector and that triggers warning in Swift Selector("updateWithCount:") // Use '#selector' instead of explicitly constructing a 'Selector' In ObjC we can use clang macro to suppress, like below #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-implementations" - (void) deprecated_objc_method_override { } #pragma clang diagnostic pop But in Swift, we can just use a dummy NSObject that has the needed methods, like...

February 18, 2021 · 1 min · 103 words · Khoa

How to make simple search bar in SwiftUI

Issue #776 We need to use a custom Binding to trigger onChange as onEditingChanged is only called when the user selects the textField, and onCommit is only called when return or done button on keyboard is tapped. import UIKit import SwiftUI import EasySwiftUI struct SearchBar: View { @Binding var searchText: String let onChange: () -> Void @State private var showsCancelButton: Bool = false var body: some View { return HStack { textField cancelButton } } private var searchTextBinding: Binding<String> { Binding<String>(get: { searchText }, set: { newValue in DispatchQueue....

February 17, 2021 · 1 min · 201 words · Khoa

How to fix share and action extension not showing up in iOS 14

Issue #775 My share sheet and action extension not showing up in iOS 14, built-in Xcode 12.3. The solution is to restart test device, and it shows up again. Also make sure your extension targets have the same version and build number, and same deployment target <dict> <key>NSExtensionAttributes</key> <dict> <key>NSExtensionActivationRule</key> <dict> <key>NSExtensionActivationDictionaryVersion</key> <integer>2</integer> <key>NSExtensionActivationSupportsText</key> <true/> <key>NSExtensionActivationSupportsWebURLWithMaxCount</key> <integer>1</integer> <key>NSExtensionActivationSupportsWebPageWithMaxCount</key> <integer>1</integer> </dict> <key>NSExtensionJavaScriptPreprocessingFile</key> <string>MyPreprocessor</string> <key>NSExtensionActivationUsesStrictMatching</key> <integer>2</integer> </dict>

February 17, 2021 · 1 min · 65 words · Khoa

How to add home screen quick action in SwiftUI

Issue #774 Start by defining your quick actions. You can use UIApplicationShortcutIcon(type:) for predefined icons, or use UIApplicationShortcutIcon(systemImageName:) for SFSymbol enum QuickAction: String { case readPasteboard case clear var shortcutItem: UIApplicationShortcutItem { switch self { case .readPasteboard: return UIApplicationShortcutItem( type: rawValue, localizedTitle: "Read Pasteboard", localizedSubtitle: "", icon: UIApplicationShortcutIcon(type: .add), userInfo: nil ) case .clear: return UIApplicationShortcutItem( type: rawValue, localizedTitle: "Clear Pasteboard", localizedSubtitle: "", icon: UIApplicationShortcutIcon(systemImageName: SFSymbol.wind.rawValue), userInfo: nil ) } } } Add a service to store selected quick action....

February 10, 2021 · 2 min · 377 words · Khoa

How to use EquatableView in SwiftUI

Issue #773 From John Harper ’s tweet SwiftUI assumes any Equatable.== is a true equality check, so for POD views it compares each field directly instead (via reflection). For non-POD views it prefers the view’s == but falls back to its own field compare if no ==. EqView is a way to force the use of ==. When it does the per-field comparison the same rules are applied recursively to each field (to choose direct comparison or == if defined)....

February 8, 2021 · 1 min · 92 words · Khoa

How to add new property in Codable struct in SwiftUI

Issue #772 I use Codable structs in my apps for preferences, and bind them to SwiftUI views. If we add new properties to existing Codable, it can’t decode with old saved json as we require new properties. We can either do cutom decoding with container, but this can result in lots more code and mistakes if we have many properties inside our struct. The quick workaround is to declare new properties as optional, and use a computed property to wrap that....

February 8, 2021 · 1 min · 127 words · Khoa

How to show close button in NSTextField in AppKit

Issue #771 Use NSSearchField instead

February 6, 2021 · 1 min · 5 words · Khoa

How to handle escape in NSTextField in SwiftUI

Issue #770 Handle cancelOperation somewhere up in responder chain class MyWindow: NSWindow { let keyHandler = KeyHandler() override func cancelOperation(_ sender: Any?) { super.cancelOperation(sender) keyHandler.onEvent(.esc) } }

February 6, 2021 · 1 min · 27 words · Khoa

How to fit ScrollView to content in SwiftUI

Issue #769 If we place ScrollView inside HStack or VStack, it takes all remaining space. To fit ScrollView to its content, we need to get its content size and constrain ScrollView size. Use a GeometryReader as Scrollview content background, and get the local frame import SwiftUI struct HSearchBar: View { @State private var scrollViewContentSize: CGSize = .zero var body: some View { HStack { searchButton ScrollView(.horizontal, showsIndicators: false) { HStack(spacing: 12) { ForEach(store....

February 6, 2021 · 1 min · 104 words · Khoa

How to show modal window in SwiftUI for macOS

Issue #768 Use custom NSWindow, set level in becomeKey and call NSApp.runModal to show modal final class ModalWindow: NSWindow { override func becomeKey() { super.becomeKey() level = .statusBar } override func close() { super.close() NSApp.stopModal() } } let window = ModalWindow( contentRect: .zero, styleMask: [.titled, .closable], backing: .buffered, defer: false ) window.titlebarAppearsTransparent = true window.title = "Manage collections" window.center() window.isReleasedWhenClosed = false self.window = window let view = CollectionSettingsView(store: Store.shared) ....

February 3, 2021 · 1 min · 106 words · Khoa

How to use custom Key for NSCache

Issue #766 Need to use a class, best is to subclass from NSObject let cache = NSCache<Key, UIImage>() final class Key: NSObject { override func isEqual(_ object: Any?) -> Bool { guard let other = object as? Key else { return false } return url == other.url && size == other.size } override var hash: Int { return url.hashValue ^ Int(size.width) ^ Int(size.height) } let url: URL let size: CGSize init(url: URL, size: CGSize) { self....

January 30, 2021 · 1 min · 83 words · Khoa

How to show multiple popover in SwiftUI

Issue #765 In SwiftUI currently, it’s not possible to attach multiple .popover to the same View. But we can use condition to show different content struct ClipboardCell: View { enum PopoverStyle { case raw case preview } @Binding var showsPopover: Bool @Binding var popoverStyle: PopoverStyle var body: some View { VStack { header content .popover(isPresented: $showsPopover) { switch popoverStyle { case .raw: ViewRawView(item: item) case .preview: PreviewView(item: item) } } footer } } }

January 29, 2021 · 1 min · 74 words · Khoa