How to show img tag from GitHub markdown in Hugo

Issue #788 I just convert my blog from Hexo.js back to Hugo again. Hugo now uses goldmark as the default markdown processor instead of blackfriday All works well, except that I use GitHub markdown to write articles, which use raw HTML img tag for uploaded images. Hugo works well with ![]() syntax but it ignores img tag <img width="574" alt="Screenshot 2021-02-26 at 10 08 38" src=""> The solution is to tell goldmark to accept raw HTML....

March 2, 2021 路 1 min 路 Khoa Pham

How to name Boolean property in Swift

Issue #787 In Swift, property, especially for Boolean flagging, uses the regular verb form for the third person. There are few exceptions, such as enable NSManagedObjectContext.automaticallyMergesChangesFromParent UIView.clipsToBounds UIView.translatesAutoresizingMaskIntoConstraints SwiftUI.Transaction.disablesAnimations UIScrollView.scrollsToTop NSView.isHidden UndoManager.enableUndoRegistration

February 28, 2021 路 1 min 路 Khoa Pham

How to use with block configure in Swift

Issue #786 Sometimes we need to update some properties between objects, for example = = book.publishedAt = updatedBook.publishedAt Repeating the caller book is tedious and error-prone. In Kotlin, there is with block which is handy to access the receiver properties and methods without referring to it. with(book) { name = page = publishedAt = updatedBook.publishedAt } In Swift, there are no such thing, we can write some extension like...

February 28, 2021 路 1 min 路 Khoa Pham

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鈥檛 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 路 5 min 路 Khoa Pham

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 路 Khoa Pham

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鈥檛 generate an NSManagedObjectContextDidSave notification, and the view misses these relevant updates. Alternatively, the background context may save changes to the store that don鈥檛 affect the current view鈥攆or example, inserting, modifying, or deleting Shape objects. These changes do generate context save events, so your view context processes them even though it doesn鈥檛 need to....

February 25, 2021 路 1 min 路 Khoa Pham

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 路 Khoa Pham

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 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 路 Khoa Pham

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 路 Khoa Pham

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鈥檚 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 路 Khoa Pham

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 路 Khoa Pham

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 路 Khoa Pham

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 路 Khoa Pham

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 路 Khoa Pham

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 路 Khoa Pham

How to use EquatableView in SwiftUI

Issue #773 From John Harper 鈥檚 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鈥檚 == 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 路 Khoa Pham

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鈥檛 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 路 Khoa Pham

How to show close button in NSTextField in AppKit

Issue #771 Use NSSearchField instead

February 6, 2021 路 1 min 路 Khoa Pham

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 路 Khoa Pham

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 路 Khoa Pham