A better way to update UICollectionView data in Swift with diff framework
Issue #1010
A Better Way to Update UICollectionView Data in Swift with Diff Framework
Familiar Friends
It’s hard …
Issue #1010
It’s hard …
Issue #1009
SwiftUI’s Observation framework makes reactive UI updates effortless—when a property changes, views that depend on it automatically refresh. But what happens when your data lives in UserDefaults? You might want subscription status, …
Issue #1007
Testing in Swift has always required inheriting from XCTestCase and prefixing every method with test. Sound familiar? With Swift 6, Apple introduced Swift Testing — a framework that feels native to modern Swift …
Issue #1006
When building macOS apps, you often need images that fill their container while keeping their aspect ratio - like cover photos or thumbnails. NSImageView doesn’t do this well out of the box. Here’s how to build a custom …
Issue #998
Traditionally, if we wanted to quickly test a function or a piece of logic, we would open a separate Playground file (.playground).
From Xcode 26 we can have access to the new #Playground macro in Swift 6.2. This allows us to declare a …
Issue #997
An interesting feature in iOS 26 is the ability to create morph “Liquid Glass” effects, where views with the .glassEffect() modifier can fluidly morph into one another. This is achieved using GlassEffectContainer and the …
Issue #996
When creating widgets for iOS, especially those that need user input to be useful, one common challenge is guiding the user to configure them. Before iOS 18, a user would add a widget, but then would have to know to long-press it and …
Issue #995
With iOS 18, SwiftUI introduces matchedTransitionSource and navigationtransition as a powerful new way to create zoom animations between views. This allows you to smoothly transition from a small view to a larger, more detailed view, …
Issue #994
With iOS 18, Apple introduced a powerful new tool for creating beautiful, dynamic backgrounds: MeshGradient. Forget simple two-color gradients; mesh gradients let you blend a whole grid of colors together smoothly, creating stunning, …
Issue #993
Before iOS 17, if you wanted to animate a number changing, SwiftUI would just fade the old number out and fade the new one in. It worked, but it wasn’t very exciting.
Here’s how that looked:
struct OldCounterView: View {
@ …Issue #992
In the past, making your screen update when data changed in UIKit meant writing extra code, either with didSet, Combine or some other callbacks. Now, it’s automatic.
With the latest iOS 26 updates, UIKit can automatically watch your …
Issue #989
In Swift 6, Apple introduced stricter rules to help make your code safer when using concurrency (like async, await, Task, and actor). These rules check that types used in concurrent code are safe to share across threads.
Types that are …
Issue #988
When working with Core Data, there are times we have optional NSManagedObject to pass around. These objects conform to ObservableObject, and in SwiftUI we can’t @ObservedObject on optional ObservableObject
One way we can workaround …
Issue #986
When using TextField in SwiftUI List on Mac, it has unwanted background color when focused. We can turn it off using introspection or a custom TextField wrapper
TextField("Search", text: $searchText)
.introspect(.textField, on: …Issue #984
The WidgetBundle lets us expose multiple widgets from a single widget extension
It uses WidgetBundleBuilder to constructs a widget bundle’s body.
In iOS 18, if we include ControlWidget then we need to check iOSApplicationExtension iOS 18. …
Issue #983
In iOS 18, we can make Control Widget in Widget extension
import WidgetKit
import SwiftUI
@available(iOS 18.0, *)
struct BookControlWidget: ControlWidget {
var body: some ControlWidgetConfiguration {
StaticControlConfiguration …Issue #982
If you’re using NSFetchedResultsController in Core Data, it might take up a lot of memory, especially when working with large datasets. To keep your app running smoothly, it’s important to manage memory efficiently
Issue #981
NSDragOperation represent which operations the dragging source can perform on dragging items.
There are several types of drag operations, and each one has a different purpose and visual cue.
.copyIssue #980
NSCollectionView, available since macOS 10.5+, is a good choice to present a list of content. Let’s make a SwiftUI wrapper for NSCollectionView with diffable data source and compositional layout
Issue #977
Show ASAuthorizationController with a simple nonce. Once we have the idToken, create an OAuthProvider.appleCredential and pass to Firebase Auth
final class AppleLoginService: NSObject {
static let shared = AppleLoginService() …Issue #973
Before iOS 11, we used to use CIDetector and CIDetectorTypeQRCode to detect QR code
An image processor that identifies notable features, such as faces and barcodes, in a still image or video.
A detector …
Issue #972
We want to have a swifty UserDefaults API that works with subscript and in a type safe manner.
extension Defaults.Keys {
static let string = Defaults.Key("string", default: "0")
}
XCTAssertEqual(defaults[.string], …Issue #970
We can use Logger to log and OSLogStore to retrieve logs
import OSLog
import ReuseAcross
final class LogService {
static let shared = LogService()
let logger = Logger(
subsystem: "com.example.myapp", …Issue #963
In the world of Swift programming, we often come across situations where we need to work with string literals that contain special characters. These characters can include new lines, tabs, backslashes, and quotes — all of which need to be …
Issue #961
NSTextField uses NSFieldEditor under the hood, you can check currentEditor if it is the firstResponder
extension NSTextField {
var isFirstResponder: Bool {
currentEditor() == window?.firstResponder
}
}
Issue #960
Also written on Fritz
Math might be scary, but it’s an essential part of everyday life. Wouldn’t it be cool if we could build an app, point our phone’s camera at an expression, and let the app compute the result? Whenever I’ve needed to …
Issue #959
Decoding JSON in Swift is most of the time very straightforward with help of Codable protocol and JSONDecoder.
Sometimes the json contains dynamic key, like
{
"shipmunk": {
"name": "Shipmunk", …Issue #958
We can use any bundler, like Parcel, Webpack or Vite. Here I use Webpack 5
npm install @babel/polyfill webpack webpack-cli --save-dev
@babel/polyfill is a package provided by Babel, a popular JavaScript compiler. …
Issue #957
Define console object and set log function to point to our Swift function
import JavaScriptCore
extension JSContext {
func injectConsoleLog() {
evaluateScript(
"""
var console = {}; …Issue #955
Besides WWDC videos & documentation, Apple also has interactive tutorials and books. Below are some of my favorites learning resources
Tutorials
Issue #954
From iOS 15, there’s a handy safeAreaInset that allows us to place additional content extending the safe area.
Shows the specified content beside the modified view.
safeAreaInset allows us to customize which edge and alignment we …
Issue #949
AppStorage and SceneStorage accepts RawRepresentable where value is Int or String.
Creates a property that can read and write to a string user default, transforming that to RawRepresentable data type.
init( …Issue #948
iOS 17 has a new Stand by mode so SwiftUI introduces containerBackground for the system to decide when to draw background. It also automatically applies margin to widget so we may need to disable that
To update existing widgets, we can …
Issue #945
The default SwiftGen generate generated strings L10n file like this
extension L10n {
private static func tr(_ table: String, _ key: String, _ args: CVarArg..., fallback value: String) -> String {
let format = BundleToken.bundle. …Issue #944
SwiftUI in iOS 16 supports Layout protocol to arrange subviews
We need to implement 2 methods
Issue #943
In this tutorial, we’ll learn how to use Swift Charts to visualize ranking data.
We use default AxisMarks and AxisMarks to let Swift Charts interpolate x and y grid lines. For y axis, I want to have finer grain control over the …
Issue #939
Instead of letting the Image decide the size, we can put it as background or overlay. I use clipped and contentShape to avoid the fill image obscuring touch event
Color.clear
.frame(height: 100)
.overlay {
AsyncImage(url: …Issue #938
To let app and extension to talk to the same database, we need to use AppGroup. Here is how to use replacePersistentStore
Replaces one persistent store with another
actor DatabaseMigrator {
@AppStorage( …Issue #937
First, you need to enable iCloud Documents capability. Go to target settings -> Signing & Capabilities -> iCloud
`
Then inside your Info.plist, add this with your iCloud identifier and app name …
Issue #934
There are a few keychain wrappers around but for simple needs, you can write it yourself
Here is a basic implementation. I use actor to go with async/await, and a struct KeychainError to contain status code in case we want to deal with …
Issue #932
Add Share extension and Action extension respectively in Xcode. We can use the same code to both extension
I usually make a ShareView in SwiftUI with ShareViewModel to control the logic
struct ShareView: View {
@ …Issue #928
For iOS, use string
Setting this property replaces all current items in the pasteboard with the new item. If the first item has no value of the indicated type, nil is returned.
let pasteboard = UIPasteboard.general
pasteboard.string = …Issue #925
Use AES.GCM method with 128 bits key
import CryptoKit
public extension Optional {
func tryUnwrap() throws -> Wrapped {
if let value = self {
return value
} else {
throw NSError(domain: …Issue #924
Note
the navigation split view coordinates with the List in its first …
Issue #923
NavigationLink on Mac applies the default button style. We can style it using ButtonStyle, here to use plain style we can just
NavigationLink(value: DetailRoute.books) {
BooksView()
}
.buttonStyle(.plain)
Issue #913
Use QuickLookThumbnailing framework
import AppKit
import QuickLookThumbnailing
actor QuicklookService {
static let shared = QuicklookService()
private let generator = QLThumbnailGenerator.shared
func image( …Issue #912
Perform check before and after suspension point
actor Worker {
var isDoing = false
var toBeDone = Set<String>()
func work(string: String) async {
if isDoing {
toBeDone.insert(string) …Issue #911
Make an parallelTask function that wraps TaskGroup
public func parallelTask(@ParallelTaskBuilder builder: () -> [ParallelTaskBuilder.Work]) async {
await withTaskGroup(of: Void.self) { group in
for work in builder() { …Issue #910
let string = "Hello world"
string[string.startIndex...] // Hello world
string[..<string.endIndex] // Hello world
let string = "Hello world"
let range = string.startIndex ..< …Issue #908
When we add another UIWindow, then its rootViewController will decide the style of the status bar, not the rootViewController of the keyWindow anymore
The usual way to fix this is to defer the decision to the correct …
Issue #905
Protect mutable state with Swift actors
Actor reentrancy
Imagine we have two different concurrent tasks trying to fetch the same image at the same time. The first sees that there is no cache entry, proceeds to start downloading the …
Issue #904
Consider this code where we have an ObservableObject with fetch1 and async fetch2, and a fetch inside ContentView
Here the observation in Xcode 14
Issue #903
let image = NSImage(contentsOf: url)
let imageView = NSImageView(image: image)
image.animates = true
Issue #900
Listen to didActivateApplicationNotification and check that it is not our app
NSWorkspace.shared.notificationCenter
.publisher(for: NSWorkspace.didActivateApplicationNotification)
.sink(receiveValue: { [weak self] note in …Issue #899
Use NSTitlebarAccessoryViewController
var titleBarAccessoryVC: NSTitlebarAccessoryViewController {
let vc = NSTitlebarAccessoryViewController()
let view = HStack {
Spacer()
Button {
} label: { …Issue #898
Change element position using either offset or position, and use DragGesture
Use GestureState to store the updating startDragLocation to keep the start location when drag begins, so we can add translation
struct MoveModifier: ViewModifier …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 …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. …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 …
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
Issue #889



See gist https://gist.github.com/onmyway133/fc08111964984ef544a176a6e9806c18

Section("Hashtags") { …Issue #888
This generic pattern is really common, so there’s a simpler way to express it. Instead of writing a type parameter explicitly, we can express this abstract type in terms of the protocol conformance by writing …
Issue #885
Create NSBitmapImageRep with preferred size and draw NSImage onto that.
Need to construct NSBitmapImageRep specifically instead of using convenient initializers like NSBitmapImageRep(data:), NSBitmapImageRep(cgImage:) to avoid device …
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 …
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 …
Issue #878
Note that
id is needed, although Book already conforms to Identifiableselection needs a default valueclass BookViewModel: ObservableObject {
@Published var books: [Book] = []
@Published var selectedBooks: Set<Book …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 🤯
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 …Issue #875
Read newDocument
This method calls openUntitledDocumentAndDisplay(_:).
Read openUntitledDocumentAndDisplay
The default implementation of this method calls defaultType to determine the type of new document to create, calls …
Issue #874
From iOS 13, use UITabBarAppearance and UITabBarItemAppearance
let appearance = UITabBarAppearance()
let itemAppearance = UITabBarItemAppearance(style: .stacked)
itemAppearance.normal.badgeBackgroundColor = .clear
itemAppearance.normal. …Issue #873
Use assistant
let assistant = MCAdvertiserAssistant(serviceType: "my-service, discoveryInfo: nil, session: mcSession)
assistant.start()
let browser = MCBrowserViewController(serviceType: "my-service", session: mcSession) …Issue #871
Use libraries
import web3
import web3keystore
import KeychainAccess
private final class KeyStorage: EthereumKeyStorageProtocol {
enum Key: String { …Issue #869
We can use PropertyListEncoder from Swift 4
let encoder = PropertyListEncoder()
encoder.outputFormat = .xml
let data = try encoder.encode(model)
Or we can manually do with resultBuilder style
Declare @resultBuilder for PlistBuilder that …
Issue #868
Use JWTKit and code from AppStoreConnect library
import JWTKit
public struct Credential {
let issuerId: String
let privateKeyId: String
let privateKey: String
public init(
issuerId: String,
privateKeyId: …Issue #864
Since async URLSession.shared.data is available in iOS 15+, we can build a custom one with withCheckedThrowingContinuation
import UIKit
enum HTTPMethod: String {
case get = "GET"
case post = "POST"
}
extension …Issue #863
We will check USDC token balance on Solana testnet.
Firstly, we will use https://usdcfaucet.com/ to airdrop some USDC tokens into our wallet. Secondly, we check USDC token mint address on testnet cluster using Solana Explorer …
Issue #861
Make it easy to access common cases, for example UserDefaults
extension UserDefaults {
enum Key: String {
case hasBackup
}
subscript(key: Key) -> Bool {
get {
bool(forKey: key.rawValue)
} …Issue #860
JSONEncoder deals with type-safe, so we need to declare an enum JSONValue for all possible types. We also need a custom initializer to init JSONValue from a JSON Dictionary
import Foundation
enum JSONValue {
case string(String) …Issue #859
To parse PKPayment and used with Wyre CreateAppleOrder API, we can declare some Encodable structs
import PassKit
import Foundation
struct PaymentObject: Encodable {
var billingContact: Contact?
var shippingContact: Contact? …Issue #858
isDetailLink(false).introspectNavigationController { nav in
self.nav = nav
}
Issue #857
Use Solana.swift and Mnemonic seed phrase. For production, change endpoint to mainnet
import UIKit
import Solana
import KeychainAccess
enum SolanaError: Swift.Error {
case accountFailed
case unauthorized
}
final class …Issue #856
Use PKPaymentRequest and PKPaymentAuthorizationViewController
@MainActor
final class WalletViewModel: NSObject, ObservableObject {
var canMakePayments: Bool {
PKPaymentAuthorizationViewController.canMakePayments()
} …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 = …Issue #854
If you use enum case as key in Dictionary, JSONEncoder will encode it as Array. For example
enum Vehicle: String, Codable {
case car
case truck
}
struct Container: Codable {
var map: [Vehicle: String]
}
struct Container2: …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 { …Issue #852
Supposed we have Book object
struct Book: Identifiable, Codable, Hashable {
@DocumentID var id: String?
}
We should use FieldPath instead of id for query
let booksRef: CollectionReference = ...
let ids: [String] = ...
booksRef
. …Issue #851
Use DefaultValue to provide defaultValue in our property wrapper DefaultCodable
public protocol DefaultValue {
associatedtype Value: Codable
static var defaultValue: Value { get }
}
public enum DefaultBy {
public enum True: …Issue #849
We need to explicitly specify optional in tag
extension AVCaptureDevice: Identifiable {
public var id: String { uniqueID }
}
@State var device: AVCaptureDevice?
Picker("Camera", selection: $device) {
ForEach(manager. …Issue #847
We should use Dynamic Font Type as much as possible, as per Typography guide and https://www.iosfontsizes.com/
But in case we have to use a specific font, we can scale it with UIFontMetrics
import SwiftUI
import UIKit
extension Font { …Issue #845
Suppose we have struct Payment as the state, we declare custom Binding<String> that derives from our state.
struct Payment {
var amount: Int = 0
}
To show our suffix view, we use .fixedSize(horizontal: true, vertical: false) to …
Issue #844
Use custom Binding and validate the text. In case of zero, return empty string to let TextField display placeholder
var textField: some View {
let text = Binding<String>(
get: {
state.amount > 0 ? "$\( …Issue #842
Declare EnvironmentKey and read safeAreaInsets from key window in connectedScenes
struct SafeAreaInsetsKey: EnvironmentKey {
static var defaultValue: EdgeInsets {
UIApplication.shared.keyWindow?.safeAreaInsets.swiftUIInsets ?? …Issue #841
Declare generic on RawRepresentable
import SwiftUI
struct TabStrip<T: RawRepresentable & Hashable>: View where T.RawValue == String {
let values: [T]
@Binding var selected: T
var body: some View {
ScrollView …Issue #840
Used to replace credit card regex 30[0-5]#-######-###L in EasyFake
We can use ? to have non-greedy behavior, or I here use square bracket to fine-tune the expression \{[\d*,]*\d*\}
Also, I need to reversed the matches because each …
Issue #839
Use locales data from faker.js to https://github.com/onmyway133/EasyFake, renaming files since files, regardless of sub directories in Xcode, must have different name.
We use enumerator API on FileManager to traverse all files in all …
Issue #838
We can write our custom Binding
import SwiftUI
extension Binding where Value == Date? {
func flatten(defaultValue: Date) -> Binding<Date> {
Binding<Date>(
get: { wrappedValue ?? defaultValue }, …Issue #837
I usually use GeometryReader in background to get size of view, and encapsulate it inside a ViewModifier
struct GetHeightModifier: ViewModifier {
@Binding var height: CGFloat
func body(content: Content) -> some View { …Issue #836
If we have a Picker inside a View that has DragGesture, chances are when we scroll the wheel, the DragGesture is detected too
To prevent this, we can attach a dummy DragGesture to our Picker
Picker("", selection: $number) { …Issue #835
I usually define ButtonStyle to encapsulate common styles related to buttons. Here we specify .frame(maxWidth: .infinity) to let this button take the whole width as possible
struct MyActionButtonStyle: ButtonStyle {
func makeBody( …Issue #834
In iOS 15, we can use UISheetPresentationController to show bottom sheet like native Maps app. But before that there’s no such built in bottom sheet in UIKit or SwiftUI.
We can start defining API for it. There are 3 ways to show …
Issue #833
Use RelativeDateTimeFormatter. This assumes US locale is used
extension Date {
private static let relativeFormatter: RelativeDateTimeFormatter = {
let formatter = RelativeDateTimeFormatter()
formatter.calendar = …Issue #831
We can normally listen to sub ObservableObject by either listen to its objectWillChange or its Publisher
class SubModel: ObservableObject {
@Published var count = 0
}
class AppModel: ObservableObject {
@Published var submodel: …Issue #829
Use PreferenceKey with a custom coordinateSpace to make our own TrackableScrollView. Note that the offset here is in reversed to contentOffset in normal UIScrollView
import SwiftUI
struct TrackableScrollView<Content: View>: View { …Issue #828
Use focused(_:) for single TextField, and focused(_:equals:) for multiple TextField
struct FormView: View {
@FocusState private var isFocused: Bool
@State private var name = ""
var body: some …Issue #827
I’m trying a simple Future and sink. As long as I have debounce, only receiveCompletion gets called, but not receiveValue
private var bag = Set<AnyCancellable>()
let future = Future<Int, Never> { promise in
promise(. …Issue #826
Use isActive binding
@State private var goesToDetail: Bool = false
NavigationLink(
destination: DetailView(viewModel: viewModel),
isActive: $goesToDetail) {
Button(action: { goesToDetail = true }) {
Text("Next" …Issue #825
For many apps that require user authentication, a common practice is to define a shared UserManager with an optional User. This is convenient but it requires us to constantly unwrap and check that user
class UserManager {
static let …Issue #824
Use a custom NavigationLink with EmptyView as the background, this failable initializer accepts Binding of optional value. This works well as the destination are made lazily.
extension NavigationLink where Label == EmptyView {
init …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 {
@ …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) }) …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: …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 …Issue #818
There’s a lot to do to imitate iOS ContextMenu look and feel
For now here’s a rough implementation of a custom context menu where we …
Issue #817
Thanks to resultBuilder and container type in Swift, the following are possible in SwiftUI
struct ChartView {
var body: some View {
computation
}
@ViewBuilder
var computation: some View {
let …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 …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 …
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 …
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" …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>( …Issue #808
Wrap ASAuthorizationAppleIDButton inside UIViewRepresentable
import SwiftUI
import UIKit
import AuthenticationServices
struct SignInWithAppleButton: View {
@Environment(\.colorScheme)
private var …Issue #806
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 …
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 { …Issue #798
swiftgen.yml
strings:
inputs: PastePal/Resources/Localizable/en.lproj
outputs:
- templatePath: swiftgen-swiftui-template.stencil
output: PastePal/Resources/Strings.swift
Template from …
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 { …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. …Issue #794
I’ve been distributing my apps PastePal and Push Hero as a paid upfront apps on Appstore. I’ve quickly come to realize the importance of trials since many have requested a tryout before purchasing.
Manual sending out trials …
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", …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
Issue #791
SwiftUI has View protocol which represents part of your app’s user interface and provides modifiers that you use to configure views.
You create custom views by declaring types that conform to the View protocol. Implement the required …
Issue #790
Use UIImageWriteToSavedPhotosAlbum
Adds the specified image to the user’s Camera Roll album.
Let’s make an NSObject delegate class so we can perform target action to notify about completion
import UIKit
struct ImageService { …Issue #789
New in SwiftUI 2.0 for iOS 14 and macOS 11.0 is WindwGroup which is used in App protocol. WindowGroup is ideal for document based applications where you can open multiple windows for different content or files. For …
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. …Issue #786
Sometimes we need to update some properties between objects, for example
book.name = updatedBook.name
book.page = updatedBook.page
book.publishedAt = updatedBook.publishedAt
Repeating the caller book is tedious and error-prone. In Kotlin, …
Issue #785
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 …
Issue #783
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 …
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, …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
This …
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()
} …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
Every cell has …
Issue #778
For now using GroupBox has these issues in macOS
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 …
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 …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 …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 …
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 …
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) …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 …
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() { …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 { …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
} …Issue #764
Use a custom KeyAwareView that uses an NSView that checks for keyDown method. In case we can’t handle certain keys, call super.keyDown(with: event)
import SwiftUI
import KeyboardShortcuts
struct KeyAwareView: NSViewRepresentable { …Issue #763
I usually break down a big struct into smaller views and extensions. For example I have a ClipboardCell that has a lot of onReceive so I want to move these to another component.
One way to do that is to extend ClipboardCell
struct …Issue #762
To install, use CocoaPods
platform …Issue #761
Explicitly specify id
ScrollView {
ScrollViewReader { proxy in
LazyVStack(spacing: 10) {
ForEach(items) { item in
Cell(item: item)
.id(item.id)
}
}
. …Issue #760
import AppKit
import Omnia
class MyWindow: NSWindow {
override func keyDown(with event: NSEvent) {
super.keyDown(with: event)
if isKey(NSDeleteCharacter, event: event) {
NotificationCenter.default.post( …Issue #758
extension NSToolbarItem.Identifier {
static let searchItem: NSToolbarItem.Identifier = NSToolbarItem.Identifier("SearchItem")
}
let searchItem = NSSearchToolbarItem(itemIdentifier: .searchItem)
extension AppDelegate: …Issue #757
Library/LoginItemshelper_dir="$BUILT_PRODUCTS_DIR/$CONTENTS_FOLDER_PATH …Issue #756
extension NavigationLink {
func fixOverlap() -> AnyView {
if UIDevice.current.userInterfaceIdiom == .phone {
return self.isDetailLink(false).erase()
} else {
return self.erase()
} …Issue #749
Some apps want to support alternative app icons in Settings where user can choose to update app icon. Here’s some must do to make it work, as of Xcode 12.2
CFBundleIcons with both CFBundlePrimaryIcon and …Issue #748
There is said to be PopUpButtonPickerStyle and MenuPickerStyle but these don’t seem to work.
There’s Menu button it shows a dropdown style. We fake it by fading this and overlay with a button. allowsHitTesting does not work, …
Issue #747
Need to use Coordinator conforming to UITextViewDelegate to apply changes back to Binding
import SwiftUI
import UIKit
struct MyTextView: UIViewRepresentable {
@Binding
var text: String
final class Coordinator: NSObject, …Issue #746
From iOS 13, the default is to support multiple scene, so the the old UIApplicationDelegate lifecycle does not work. Double check your Info.plist for UIApplicationSceneManifest key
<key>UIApplicationSceneManifest</key> …Issue #745
I used to use selection with Binding where wrappedValue is optional, together with tag in SwiftUI for macOS, and it shows current selection
@Binding
var selection: Tag? = .all
List(section: $selection) {
Text("All")
. …Issue #744
As someone who builds lots of apps, I try to find quick ways to do things. One of them is to avoid repetitive and cumbersome APIs. That’s why I built Anchors to make Auto Layout more convenient, Omnia to add missing extensions. The next …
Issue #742
Auto Layout has been around since macOS 10.7 and iOS 6.0 as a nicer way to do layouts over the old resizing masks. Besides some rare cases when we need to manually specify origins and sizes, Auto Layout is the preferred way to do …
Issue #737
Use resizingMode of .tile with a tile image from https://www.transparenttextures.com/
Image("transparentTile")
.resizable(capInsets: .init(), resizingMode: .tile)
.scaleEffect(2)
.aspectRatio(contentMode: .fit)
. …Issue #736
struct MyWebView: NSViewRepresentable {
let url: URL
@Binding
var isLoading: Bool
func makeCoordinator() -> Coordinator {
Coordinator(parent: self)
}
func makeNSView(context: Context) -> WKWebView { …Issue #735
From my previous post How to use flexible frame in SwiftUI we know that certain views have different frame behaviors. 2 of them are .overlay and GeometryReader that takes up whole size proposed by parent.
By default GeometryReader takes up …
Issue #734
In SwiftUI there are fixed frame and flexible frame modifiers.
Use this method to specify a fixed size for a view’s width, height, or both. If you only …
Issue #733
NSTextView has this handy method to make scrollable NSTextView NSTextView.scrollableTextView(). The solution is to get to the responder outside enclosing NSScrollView, in my case it is the SwiftUI hosting view
class DisabledScrollTextView: …Issue #732
Use NSMutableAttributedString and add attribute for whole range
let a: NSAttributedString
let m: NSMutableAttributedString = NSMutableAttributedString(attributedString: a)
let range = NSRange(location: 0, length: a.length)
m.addAttribute(. …Issue #731
Sometimes we don’t want to show progress view right away
HUDProgressView()
.transition(
AnyTransition.asymmetric(
insertion: AnyTransition.opacity.animation(Animation.default.delay(1)),
removal: …Issue #730
Use NSTextField with maximumNumberOfLines
import AppKit
import SwiftUI
struct AttributedText: NSViewRepresentable {
let attributedString: NSAttributedString
init(_ attributedString: NSAttributedString) {
self. …Issue #729
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
@IBAction func copy(_ sender: Any) {
print("copy", sender)
}
@IBAction func paste(_ sender: Any) {
print("paste", sender) …Issue #728
NSItemProvider(object: StringProvider(string: string))
class StringProvider: NSObject, NSItemProviderWriting {
let string: String
init(string: String) {
self.string = string
super.init()
}
static var …Issue #727
Use # in Swift 5 to specify raw string, for example regular expression
#"^#?(?:[0-9a-fA-F]{3}){1,2}$"#
Issue #726
@propertyWrapper
struct UserDefault<Value> {
let key: String
let defaultValue: Value
let container: UserDefaults = .standard
var wrappedValue: Value {
get {
return container.object(forKey: key) as …Issue #725
When you want to check for existence using Bool, consider using Set over Dictionary with Bool, as Set guarantee uniqueness. If using Dictionary instead, the value for key is Optional<Bool> where we have to check for both optional and …
Issue #724
We can use .blur modifier, but with VisualEffectView gives us more options for material and blending mode.
public struct VisualEffectView: NSViewRepresentable {
let material: NSVisualEffectView.Material
let blendingMode: …Issue #723
Use @ViewBuilder to build dynamic content for our HUD. For blur effect, here I use NSVisualEffectView, but we can use .blur modifier also
struct HUD<Content>: View where Content: View {
let content: () -> Content
init(@ …Issue #721
For setFrame to take effect
mainWindow.setFrame(rect, display: true)
we can remove auto save frame flag
mainWindow.setFrameAutosaveName("MyApp.MainWindow")
Issue #720
NSStatusItem is backed by NSButton, we can animate this inner button. We need to specify position and anchorPoint for button’s layer so it rotates around its center point
guard
let button = statusItem.button
else { return }
let …Issue #718
Use NSSharingService.sharingServices(forItems:) with an array of one empty string gives a list of sharing items. There we show image and title of each menu item.
We should cache sharing items as that can cause performance issue
import …Issue #714
Below is an example of a parent ContentView with State and a child Sidebar with a Binding.
The didSet is only called for the property that is changed.
When we click Button in ContentView, that changes State property, so only the didSet in …
Issue #713
To setup toolbar, we need to implement NSToolbarDelegate that provides toolbar items. This delegate is responsible for many things
toolbarDefaultItemIdentifiersitemForItemIdentifier …Issue #712
Describe all possible paths in your program with enum. This is great to track down bugs and to not miss representing potential cases in UI. Errors can come from app layer, backend layer to network issues.
Enum is handy in both UIKit and …
Issue #711
List has a selection parameter where we can pass selection binding. As we can see here selection is of type optional Binding<Set<SelectionValue>>? where SelectionValue is any thing conforming to Hasable
@available(iOS 13.0, …Issue #708
The best way to test is to not have to mock at all. The second best way is to have your own abstraction over the things you would like to test, either it is in form of protocol or some function injection.
But in case you want a quick way …
Issue #707
The trick is to set the button oinside of statusItem to send actions on both leftMouseUp and rightMouseUp.
Another thing to note is we use popUpMenu on NSStatusItem, although it is marked as deprecated on macOS 10.14. We can set menu but …
Issue #706
Use Mirror and set key value as NSManagedObject subclasses from NSObject
import CoreData
final class ManagedObjectConverter {
func convert<M>(m: M, context: NSManagedObjectContext) throws -> NSManagedObject {
let …Issue #704
We used to declare enum that conforms to Error, but any type like struct or class can conform to Error as well.
enum NetworkError: Error {
case failToCreateRequest
case failToParseResponse
case failToReachServe
}
struct …Issue #703
Read When to refresh a receipt vs restore purchases in iOS?
From iOS 7, every app downloaded from the store has a receipt (for downloading/buying the app) at appStoreReceiptURL. When users purchases something via In App …
Issue #698
Xcode has powerful search. We can constrain search to be scoped in workspace, project or some folders. We can also constrain case sensitivity.
Another cool thing that people tend to overlook is, besides searching based on text, we can …
Issue #697
Use temporaryDirectory from FileManager and String.write
func writeTempFile(books: [Book]) -> URL {
let url = FileManager.default.temporaryDirectory
.appendingPathComponent(UUID().uuidString)
.appendingPathExtension( …Issue #696
Which methods do you think are used here
import Cocoa
struct Robot {
let a: Int
let b: Int
let c: Int
init(a: Int = 1, c: Int = 3) {
self.a = a
self.b = 0
self.c = c
print("Init with a= …Issue #695
Inspect SKPaymentTransaction for error. In Swift, any Error can be safely bridged into NSError there you can check errorDomain and code
private func handleFailure(_ transaction: SKPaymentTransaction) {
guard let error = transaction. …Issue #694
I usually structure my app to have 1 main ObservableObject called Store with multiple properties in it.
final class Store: ObservableObject {
@Published var pricingPlan: PricingPlan()
@Published var preferences: Preferences()
} …Issue #693
AppKit app has its theme information stored in UserDefaults key AppleInterfaceStyle, if is dark, it contains String Dark.
Another way is to detect appearance via NSView
struct R {
static let dark = DarkTheme()
static let light = …Issue #691
Supposed we want to present a ViewController, and there exist both UIToolbar in both the presenting and presented view controllers.
From iOS 13, the model style is not full screen and interactive. From UITests perspective there are 2 …
Issue #690
Use accessibilityElements to specify containment for contentView and buttons. You can use Accessibility Inspector from Xcode to verify.
class ArticleCell: UICollectionViewCell {
let authorLabel: UILabel
let dateLabel: UILabel …Issue #689
func applicationDidFinishLaunching(_ aNotification: Notification) {
// extend to title bar
let contentView = ContentView()
// .padding(.top, 24) // can padding to give some space
.edgesIgnoringSafeArea(.top)
// …Issue #688
In the app I’m working on Elegant Converter, I usually like preset theme with a custom background color and a matching foreground color.
Thanks to SwiftUI style cascading, I can just declare in root MainView and it will be inherited …
Issue #687
Although I do Swift, I often follow Kotlin guideline https://kotlinlang.org/docs/reference/coding-conventions.html#functions-vs-properties
In some cases functions with no arguments might be interchangeable with read-only properties. …
Issue #686
I now use Core Data more often now. Here is how I usually use it, for example in Push Hero
From iOS 10 and macOS 10.12, NSPersistentContainer that simplifies Core Data setup quite a lot. I usually use 1 NSPersistentContainer and its …
Issue #685
Since we have custom init in ChildView to manually set a State, we need to pass ObservedObject. In the ParentView, use underscore _ to access property wrapper type.
struct ChildView: View {
@ObservedObject
var store: Store
@ …Issue #684
In SwiftUI, specifying maxWidth as .infinity means taking the whole available width of the container.
If many children ask for max width, then they will be divided equally.
This is similar to weight in LinearLayout in Android or css …
Issue #682
After has recently reminded about his updating APNs provider API which makes me realised a lot has changed about push notifications, both in terms of client and provider approach.
The HTTP/2-based Apple Push Notification service (APNs) …
Issue #681
Only need to specify fixedSize on text to preserve ideal height.
The maximum number of lines is 1 if the value is less than 1. If the value is nil, the text uses as many lines as required. The default is nil.
Text(longText)
.lineLimit …Issue #680
For List in SwiftUI for macOS, it has default background color because of the enclosing NSScrollView via NSTableView that List uses under the hood. Using listRowBackground also gives no effect
The solution is to use a library like …
Issue #679
While redesigning UI for my app Push Hero, I ended up with an accordion style to toggle section.
It worked great so far, but after 1 collapsing, all image and text views have reduced opacity. This does not happen for other elements like …
Issue #678
Use enumerated to get index so we can assign to item in list. Here is how I show list of device tokens in my app Push Hero
private var textViews: some View {
let withIndex = input.deviceTokens.enumerated().map({ $0 })
let binding: …Issue #677
The quick way to add new properties without breaking current saved Codable is to declare them as optional. For example if you use EasyStash library to save and load Codable models.
import SwiftUI
struct Input: Codable {
var bundleId: …Issue #675
Use wrappedValue to get the underlying value that Binding contains
extension View {
func addOverlay(shows: Binding<Bool>) -> some View {
HStack {
self
Spacer()
}
.overlay( …Issue #674
Specify minWidth to ensure miminum width, and use .layoutPriority(1) for the most important pane.
import SwiftUI
struct MainView: View {
@EnvironmentObject var store: Store
var body: some View {
HSplitView { …Issue #673
To draw rounded 2 corners at top left and top right, let’s start from bottom left
let path = UIBezierPath()
// bottom left
path.move(to: CGPoint(x: 0, y: bounds.height))
// top left corner
path.addArc(withCenter: CGPoint(x: radius, y …Issue #672
Supposed we want to stitch magazines array into books array. The requirement is to sort them by publishedDate, but must keep preferredOrder of books. One way to solve this is to declare an enum to hold all possible cases, and then do a …
Issue #671
Use adjustsFontForContentSizeCategory
A Boolean that indicates whether the object automatically updates its font when the device’s content size category changes.
If you set this property to YES, the element adjusts for a new …
Issue #670
To test for viewWillDisappear during UINavigationController popViewController in unit test, we need to simulate UIWindow so view appearance works.
final class PopTests: XCTestCase {
func testPop() {
let window = UIWindow(frame: …Issue #660
Apply tintColor does not seem to have effect.
datePicker.setValue(UIColor.label, forKeyPath: "textColor")
datePicker.setValue(false, forKey: "highlightsToday")
Issue #656
Lately I’ve been challenging myself to declare switch statement in SwiftUI, or in a more generalized way, execute any anonymous function that can return a View
Note that this approach does not work yet, as …
Issue #646
Pass DispatchQueue and call queue.sync to sync all async works before asserting
Use DispatchQueueType and in mock, call the work immediately
import Foundation
public protocol DispatchQueueType {
func …Issue #644
import XCTest
extension XCTestCase {
/// Asynchronously assertion
func XCTAssertWait(
timeout: TimeInterval = 1,
_ expression: @escaping () -> Void,
_: String = "",
file _: StaticString = …Issue #639
Never use String(format: "%.2f %%", 1.2 because each region can have different separator and placement of percent sign.
Use NumberFormatter instead
let formatter = NumberFormatter()
formatter.numberStyle = .percent
formatter. …Issue #638
Use commandDefinitions in XCSourceEditorExtension.
import Foundation
import XcodeKit
class SourceEditorExtension: NSObject, XCSourceEditorExtension {
func extensionDidFinishLaunching() {
}
var commandDefinitions: [[ …Issue #638
Use commandDefinitions in XCSourceEditorExtension.
import Foundation
import XcodeKit
class SourceEditorExtension: NSObject, XCSourceEditorExtension {
func extensionDidFinishLaunching() {
}
var commandDefinitions: [[ …Issue #636
Normally we can just wrap NSTextField
struct SearchTextField: NSViewRepresentable {
@Binding var text: String
var hint: String
var onCommit: (String) -> Void
func makeNSView(context: NSViewRepresentableContext< …Issue #635
textField.delegate = self
NSTextFieldDelegate
func control(_ control: NSControl, textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool {
if (commandSelector == #selector(NSResponder.insertNewline(_:))) {
// …Issue #634
public enum Weapon: String, Decodable {
case sword = "SWORD"
case gun = "GUN"
case unknown = "UNKNOWN"
public init(from decoder: Decoder) throws {
let rawValue = try decoder. …Issue #633
Use autoclosure and AnyView
@available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
public extension View {
func applyIf<T: View>(_ condition: @autoclosure () -> Bool, apply: (Self) -> T) -> AnyView {
if …Issue #630
For SwiftUI app using NSPopover, to show context popover menu, we can ask for windows array, get the _NSPopoverWindow and calculate the position. Note that origin of macOS screen is bottom left
(lldb) po NSApp.windows
▿ 2 elements
- 0 : …Issue #628
extension XCUIElementQuery: Sequence {
public typealias Iterator = AnyIterator<XCUIElement>
public func makeIterator() -> Iterator {
var index = UInt(0)
return AnyIterator {
guard index < …Issue #627
Algorithm from https://www.w3.org/WAI/ER/WD-AERT/#color-contrast
extension NSColor {
var isLight: Bool {
guard
let components = cgColor.components,
components.count >= 3
else { return false } …Issue #626
SwiftUI does not trigger onAppear and onDisappear like we expect. We can use NSView to trigger
import SwiftUI
struct AppearAware: NSViewRepresentable {
var onAppear: () -> Void
func makeNSView(context: …Issue #625
For some strange reasons, content inside ForEach does not update with changes in Core Data NSManagedObject. The workaround is to introduce salt, like UUID just to make state change
struct NoteRow: View {
let note: Note
let id: UUID …Issue #624
By default the approaches above grant you access while the app remains open. When you quit the app, any folder access you had is lost.
To gain persistent access to a folder even on subsequent launches, we’ll have to take advantage of a …
Issue #622
Read Implementing Batch Deletes
If the entities that are being deleted are not loaded into memory, there is no need to update your application after the NSBatchDeleteRequest has been executed. However, if you are deleting objects in the …
Issue #620
For NSWindow having levelother than .normal, need to override key and main property to allow TextField to be focusable
class FocusWindow: NSWindow {
override var canBecomeKey: Bool { true }
override var canBecomeMain: Bool { …Issue #618
Create custom Binding
List {
ForEach(self.items) { (item: item) in
ItemRowView(item: item)
.popover(isPresented: self.makeIsPresented(item: item)) {
ItemDetailView(item: item)
}
}
} …Issue #617
On macOS 11, we can use .help modifier to add tooltip
Button()
.help("Click here to open settings")
If you support macOS 10.15, then create empty NSView and use as overlay. Need to updateNSView in case we toggle the state of …
Issue #614
struct MyTabView: View {
@EnvironmentObject
var preferenceManager: PreferenceManager
var body: some View {
VOrH(isVertical: preferenceManager.preference.position.isVertical) {
OneTabView(image: …Issue #612
Use runModal
This method runs a modal event loop for the specified window synchronously. It displays the specified window, makes it key, starts the run loop, and processes events for that window. (You do not need to show the window …
Issue #611
enum WindowPosition: String, CaseIterable {
case left
case top
case bottom
case right
}
Picker(selection: $preference.position, label: Text("Position")) {
ForEach(WindowPosition.allCases, id: \.self) { …Issue #610
Set NSVisualEffectView as contentView of NSWindow, and our main view as subview of it. Remember to set frame or autoresizing mask as non-direct content view does not get full size as the window
let mainView = MainView()
.environment(\. …Issue #609
Use animator proxy and animate parameter
var rect = window.frame
rect.frame.origin.x = 1000
NSAnimationContext.runAnimationGroup({ context in
context.timingFunction = CAMediaTimingFunction(name: .easeIn)
window.animator().setFrame( …Issue #608
An NSRunningApplication instance for the current application.
NSRunningApplication.current
The running app instance for the app that receives key events.
NSWorkspace.shared.frontmostApplication
Issue #607
Implement Equatable and Comparable and use round
struct RGBA: Equatable, Comparable {
let red: CGFloat
let green: CGFloat
let blue: CGFloat
let alpha: CGFloat
init(_ red: CGFloat, _ green: CGFloat, _ blue: CGFloat, _ …Issue #606
Use ObjectIdentifier
A unique identifier for a class instance or metatype.
final class Worker: Hashable {
static func == (lhs: Worker, rhs: Worker) -> Bool {
return ObjectIdentifier(lhs) == ObjectIdentifier(rhs)
} …Issue #605
I use custom TextView in a master detail application.
import SwiftUI
struct TextView: NSViewRepresentable {
@Binding var text: String
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
func makeNSView …Issue #603
Need to set correct frame for mask layer or UILabel, as it is relative to the coordinate of the view to be masked
let aView = UIView(frame: .init(x: 100, y: 110, width: 200, height: 100))
let textLayer = CATextLayer()
textLayer. …Issue #602
ForEach(store.blogs.enumerated().map({ $0 }), id: \.element.id) { index, blog in
}
```
##
Issue #600
Use same CACurrentMediaTime
final class AnimationSyncer {
static let now = CACurrentMediaTime()
func makeAnimation() -> CABasicAnimation {
let animation = CABasicAnimation(keyPath: "opacity")
animation. …Issue #599
Specify tag
enum Authentication: Int, Codable {
case key
case certificate
}
TabView(selection: $authentication) {
KeyAuthenticationView()
.tabItem {
Text("🔑 Key")
}
.tag( …Issue #598
It’s hard to see any iOS app which don’t use UITableView or UICollectionView, as they are the basic and important foundation to represent data. UICollectionView is very basic to use, yet a bit tedious for common use cases, but …
Issue #597
TextView(font: R.font.text!, lineCount: nil, text: $text, isFocus: $isFocus)
.padding(8)
.background(R.color.inputBackground)
.cornerRadius(10)
.overlay(
RoundedRectangle(cornerRadius: 10)
.stroke(isFocus ? R.color. …Issue #596
UNUserNotificationCenter.current().getNotificationSettings(completionHandler: { (settings: UNNotificationSettings) in
let status: UNAuthorizationStatus = .authorized
settings.setValue(status.rawValue, forKey: …Issue #594
In some case, we should not use base type like UTType.text but to be more specific like UTType.utf8PlainText
import UniformTypeIdentifiers
var dropTypes: [UTType] {
[
.fileURL,
.url,
.utf8PlainText,
. …Issue #592
Hard to customize
Picker(selection: Binding<Bool>.constant(true), label: EmptyView()) {
Text("Production").tag(0)
Text("Sandbox").tag(1)
}.pickerStyle(RadioGroupPickerStyle())
Issue #590
Use custom NSTextField as it is hard to customize TextFieldStyle
import SwiftUI
struct MaterialTextField: View {
let placeholder: String
@Binding var text: String
@State var isFocus: Bool = false
var body: some View { …Issue #589
import SwiftUI
struct MyTextField: View {
@Binding
var text: String
let placeholder: String
@State
private var isFocus: Bool = false
var body: some View {
FocusTextField(text: $text, …Issue #589
class FocusAwareTextField: NSTextField {
var onFocusChange: (Bool) -> Void = { _ in }
override func becomeFirstResponder() -> Bool {
let textView = window?.fieldEditor(true, for: nil) as? …Issue #588
class FocusAwareTextField: NSTextField {
var onFocus: () -> Void = {}
var onUnfocus: () -> Void = {}
override func becomeFirstResponder() -> Bool {
onFocus()
let textView = window?.fieldEditor(true, …Issue #587
From https://github.com/twostraws/ControlRoom/blob/main/ControlRoom/NSViewWrappers/TextView.swift
import SwiftUI
/// A wrapper around NSTextView so we can get multiline text editing in SwiftUI.
struct TextView: …Issue #586
Add fonts to target. In Info.plist, just need to specify font locations, most of the time they are at Resources folder
ATSApplicationFontsPath (String - macOS) identifies the location of a font file or directory of fonts in the …
Issue #583
In UITests, we can use press from XCUIElement to test drag and drop
let fromCat = app.buttons["cat1"].firstMatch
let toCat = app.buttons["cat2"]
let fromCoordinate = fromCat.coordinate(withNormalizedOffset: CGVector(dx: 0, …Issue #582
Run on device, Xcode -> Debug -> View debugging -> Rendering -> Color blended layer
On Simulator -> Debug -> Color Blended Layer
Issue #580
Implement scene(_:openURLContexts:) in your scene delegate.
If the URL launches your app, you will get …
Issue #579
Use same action, or we can roll our own implementation
An NSButton configured as a radio button (with the -buttonType set to NSRadioButton), will now operate in a radio button group for applications linked on 10.8 and later. To have the …
Issue #578
zh-Hans_HK
[language designator]-[script designator]_[region designator]
A language ID identifies a language used in many regions, a dialect used in a specific region, or a script used in …
Issue #577
objc[45250]: Class AVAssetDownloadTask is implemented in both /Applications/Xcode.app/Contents/Developer/Platforms/ …Issue #576
See Spek
https://developer.apple.com/documentation/xctest/xctestcase/1496271-testinvocations
Returns an array of invocations representing each test method in the test case.
Because …
Issue #575
Check for example _runtime(_ObjC) or os(macOS if you plan to use platform specific feature …
Issue #574
expr -l Swift -- import UIKit
expr -l Swift -- let $collectionView = unsafeBitCast(0x7fddd8180000, to: UICollectionView.self)
expr -l Swift -- $collectionView.safeAreaInsets
Issue #569
From documentation https://developer.apple.com/documentation/uikit/uicollectionviewlayout/1617726-initiallayoutattributesforappear
This method is called after the prepare(forCollectionViewUpdates:) method and before the …
Issue #568
import UIKit
var mapping: [String: (UIViewController) -> Void] = [:]
var hasSwizzled = false
public func track< …Issue #567
import UIKit
public protocol AdapterDelegate: class {
/// Apply model to view
func configure(model: Any, view: UIView, indexPath: IndexPath)
/// Handle …Issue #566
public class HUDContainer: UIVisualEffectView, AnimationAware {
private let innerContentView: UIView & AnimationAware
public let label = UILabel()
public var …Issue #564
Step 1: Create executable
swift package init --type executable
Step 2: Edit package
// swift-tools-version:5.1
// The …Issue #562
Timer.scheduledTimer(withTimeInterval: seconds, repeats: false, block: { _ in
completion(.success(()))
})
RunLoop.current.run()
Issue #560
After adding bot to …
Issue #559
public class GetDestinations {
public init() {}
public func getAvailable(workflow: Workflow) throws -> [Destination] {
let processHandler = DefaultProcessHandler(filter: { $0.starts(with: "name=") })
let …Issue #558
public class GetDestinations {
public init() {}
public func getAvailable(workflow: Workflow) throws -> [Destination] {
let processHandler = DefaultProcessHandler(filter: { $0.starts(with: "name=") })
let …Issue #556
Instead of learning XMLParser, we can make a lightweight version
import Foundation
public protocol XmlItem {
func toLines() -> [String]
}
public struct XmlString: XmlItem {
public let key: String
public let value: String …Issue #554
A class must inherit from NSObject, and we have 3 ways to trigger property change
Use setValue(value: AnyObject?, forKey key: String) from NSKeyValueCoding
class MyObjectToObserve: NSObject {
var myDate = NSDate()
func …
Issue #553
Read Swift asserts - the missing manual
debug release release
function -Onone -O -Ounchecked
assert() YES NO NO
assertionFailure() YES NO NO** …Issue #551
import Foundation
public extension String {
func matches(pattern: String) throws -> [String] {
let regex = try NSRegularExpression(pattern: pattern)
let results = regex.matches(in: self, options: [], …Issue #549
public class Sequence: Task {
public func run(workflow: Workflow, completion: @escaping TaskCompletion) {
let semaphore = DispatchSemaphore(value: 0)
runFirst(tasks: tasks, workflow: workflow, completion: …Issue #547
func sync<T>(_ work: (@escaping ([T]) -> Void) -> Void) -> [T] {
let semaphore = DispatchSemaphore(value: 1)
var results = [T]()
work { values in
results = values
semaphore.signal()
} …Issue #542
See code Puma
Build is UsesXcodeBuild is UsesCommandLine
/// Any task that uses command line
public protocol UsesCommandLine: AnyObject {}
public extension UsesCommandLine {
func runBash(
workflow: …Issue #533
struct ContentView: View {
@Environment(\.locale) var locale: Locale
var body: some View {
VStack {
Text(LocalizedStringKey("hello"))
.font(.largeTitle)
Text(flag(from: …Issue #532
func flag(from country: String) -> String {
let base : UInt32 = 127397
var s = ""
for v in country.uppercased().unicodeScalars {
s.unicodeScalars.append(UnicodeScalar(base + v.value)!)
}
return s
} …Issue #528
A lens is a first-class reference to a subpart of some data type. For instance, we have _1 which is the lens that …
Issue #527
import Foundation
import Combine
public typealias TaskCompletion = (Result<(), Error>) -> Void
public protocol Task: AnyObject {
var name: String { get }
func run(workflow: Workflow, completion: TaskCompletion)
}
public …Issue #526
public class Build: UsesXcodeBuild {
public var arguments = [String]()
public init(_ closure: (Build) -> Void = { _ in }) {
closure(self)
}
}
public class Workflow {
public var …Issue #525
Example Puma

Puma.xcodeproj as a sub project of our test projectLink Binary with Libraries, select Puma framework …Issue #524
/// Any task that uses command line
public protocol UsesCommandLine: AnyObject {
var program: String { get }
var arguments: Set<String> { get set }
}
public extension UsesCommandLine {
func run() throws {
let …Issue #523
In Puma I want to make build tools for iOS and Android, which should share some common infrastructure. So we can organize dependencies like.
Puma -> PumaAndroid, PumaiOS -> PumaCore -> xcbeautify, Files, Colorizer
// …Issue #522
Sometimes ago I created Puma, which is a thin wrapper around Xcode commandline tools, for example xcodebuild
There’s lots of arguments to pass in xcodebuild, and there are many tasks like build, test and archive that all uses this …
Issue #518
let userDefaults = UserDefaults(suiteName: suiteName)
userDefaults.removePersistentDomain(forName: suiteName)
https://developer.apple.com/documentation/foundation/userdefaults/1417339-removepersistentdomain
Calling this method is …
Issue #510
Use Dictionary(grouping:by:)
func groups(countries: [Country]) -> [Group] {
let dictionary = Dictionary(grouping: countries, by: { String($0.name.prefix(1)) })
let groups = dictionary
.map({ (key: String, value: [Country …Issue #506
When a function expects AnyPublisher<[Book], Error> but in mock, we have Just
func getBooks() -> AnyPublisher<[Book], Error> {
return Just([
Book(id: "1", name: "Book 1"),
Book(id: …Issue #504
https://twitter.com/NeoNacho/status/1181245484867801088?s=20
There’s no way to have platform specific sources or targets today, so you’ll have to take a different approach. I would recommend wrapping all OS specific files in #if os and …
Issue #493
Declare in Podfile
pod 'Firebase/Core'
pod 'Firebase/RemoteConfig'
Use RemoteConfigHandler to encapsulate logic. We introduce Key with CaseIterable and defaultValue of type NSNumber to manage default values.
import Firebase …Issue #485
The easiest way to show image picker in iOS is to use UIImagePickerController, and we can bridge that to SwiftUI via UIViewControllerRepresentable
We conform to UIViewControllerRepresentable and make a …
Issue #483
Every item in list must be uniquely identifiable
List {
ForEach(books, id: \.bookId) { book in
NavigationLink(destination:
BookView(book: book)
.navigationBarTitle(book.name)
) { …Issue #479
From ISO8601 spec, the problems are the representation and time zone
ISO 8601 = year-month-day time timezone
For date and time, there are basic (YYYYMMDD, hhmmss, ...) and extended format (YYYY-MM-DD, hh:mm:ss, ...)
Time zone can be Zulu, …Issue #477
@available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
public extension View {
}
#if canImport(UIKit)
import UIKit
#elseif canImport(OSX)
import AppKit
#endif
In watchOS app, it still can import …
Issue #475
For a snack bar or image viewing, it’s handy to be able to just flick or toss to dismiss
We can use UIKit Dynamic, which was introduced in iOS 7, to make this happen.
Use UIPanGestureRecognizer to drag view around, UISnapBehavior to …
Issue #474
Go to Project -> Swift Packages, add package. For example https://github.com/onmyway133/EasyStash
Select your WatchKit Extension target, under Frameworks, Libraries and Embedded Content add the library
If we use CocoaPods, …
Issue #473
Use UIScreen.didConnectNotification
NotificationCenter.default.addObserver(forName: UIScreen.didConnectNotification,
object: nil, queue: nil) { (notification) in
// Get the new screen …Issue #472
Use convenient code from Omnia
To make view height dynamic, pin UILabel to edges and center
import UIKit
final class ErrorMessageView: UIView {
let box: UIView = {
let view = UIView()
view. …Issue #471
let navigationController = UINavigationController(rootViewController: viewControllerA)
navigationController.pushViewController(viewControllerB, animated: true)
In view controller B, need to set hidesBottomBarWhenPushed in init
final class …Issue #470
Use NSTextAttachment inside NSAttributedString
extension UILabel {
func addTrailing(image: UIImage) {
let attachment = NSTextAttachment()
attachment.image = image
let attachmentString = NSAttributedString( …Issue #469
If there are lots of logics and states inside a screen, it is best to introduce parent and child container, and switch child depends on state. Each child acts as a State handler.
In less logic case, we can introduce a Scenario class that …
Issue #465
Use EasyStash
import EasyStash
final class Store<T: Codable & ItemProtocol>: Codable {
var items = [T]()
func bookmark(item: T) {
items.append(item)
}
func unbookmark(item: T) {
guard let index …Issue #464
typealias Completion = (Result<User, Error>) -> Void
func validate(completion: @escaping Completion, then: (String, String, @escaping Completion) -> Void) {}
Issue #463
func zoom(location1: CLLocation, location2: CLLocation) {
let bounds = GMSCoordinateBounds(coordinate: location1.coordinate, coordinate: location2.coordinate)
let update = GMSCameraUpdate.fit(bounds, withPadding: 16)
mapView. …Issue #462
Using object, we don’t need to care about nil vs false like in UserDefaults, our object is the source of truth
class StoringHandler<T: Codable> {
private let key: Storage.Keys
private let storage = Deps.storage …Issue #461
With UIAlertController we can add buttons and textfields, and just that
func addAction(UIAlertAction)
func addTextField(configurationHandler: ((UITextField) -> Void)?)
To add custom content to UIAlertController, there are some …
Issue #460
extension UIView {
func findRecursively<T: UIView>(type: T.Type, match: (T) -> Bool) -> T? {
for view in subviews {
if let subview = view as? T, match(subview) {
return subview …Issue #456
From WWDC 2018 What’s New in User Notifications
Instead, the notifications from your app will automatically start getting delivered.
Notifications that are delivered with provisional authorization will have a prompt like this on …
Issue #455
There are times we want to log if user can receive push notification. We may be tempted to merely use isRegisteredForRemoteNotifications but that is not enough. From a user ’s point of view, they can either receive push notification …
Issue #453
From documentation
A type-erased hashable value.
DiscussionThe AnyHashable type forwards equality comparisons and hashing operations to an underlying hashable value, hiding its specific underlying type.You can store mixed-type keys in …
Issue #452
Use UserNotifications framework
import FirebaseMessaging
import UserNotifications
final class PushHandler: NSObject {
private let center = UNUserNotificationCenter.current()
private let options: UNAuthorizationOptions = [.alert] …Issue #451
For some services, we need to deal with separated APIs for getting ids and getting detail based on id.
To chain requests, we can use flatMap and Sequence, then collect to wait and get all elements in a single publish
Transforms …
Issue #450
Following the signatures of ScrollView and Group, we can create our own container
public struct ScrollView<Content> : View where Content : View {
/// The content of the scroll view.
public var content: Content
}
extension …Issue #446
Suppose we have Service protocol, and want to use in List
protocol Service {
var name: String { get }
}
struct MainView: View {
let services = [
Car()
Plane()
]
var body: some View {
List(services) …Issue #445
Run swift package init
Check enum for version for each platform https://developer.apple.com/documentation/swift_packages/supportedplatform/tvosversion
Example …
Issue #444
To avoid compiler error Unprintable ASCII character found in source file, from Swift 5, we can use isASCII.
Run this from the generator app that generates Swift code.
let normalized = weirdString.filter({ $0.isASCII })
For more check, see …
Issue #443
let textField = NSTextField()
textField.focusRingType = .none
let textView = NSTextView()
textView.insertionPointColor = R.color.caret
textView.isRichText = false
textView.importsGraphics = false
textView.isEditable = true
textView. …Issue #442
On macOS, coordinate origin is bottom left
let window = NSWindow(contentRect: rect, styleMask: .borderless, backing: .buffered, defer: false)
window.center()
let frame = window.frame
window.setFrameOrigin(CGPoint(x: frame.origin.x, y: 100 …Issue #441
Make object conform to Equatable and Hashable and use Set to eliminate duplications. Set loses order so we need to sort after uniquing
struct App: Equatable, Hashable {
static func == (lhs: App, rhs: App) -> Bool {
return …Issue #439
We need to provide NSLocalizedDescriptionKey inside user info dictionary, otherwise the outputt string may not be what we want.
Issue #438
In Storyboard, NSTextField has an Action option that specify whether Send on Send on Enter only` should be the default behaviour.

In code, NSTextFieldDelegate notifies whenever text field value changes, and target action …
Issue #437
Use Omnia for itemId extension
HeaderCell.swift
final class HeaderCell: NSView, NSCollectionViewSectionHeaderView {
let label: NSTextField = withObject(NSTextField(labelWithString: "")) {
$0.textColor = R.color. …Issue #435
Use NSMenu and popUp
func showQuitMenu() {
let menu = NSMenu()
let aboutItem = NSMenuItem(
title: "About",
action: #selector(onAboutTouched(_:)),
keyEquivalent: ""
)
let quitItem = …Issue #434
When calling collectionView.reloadData(), selected indexpath stays the same, but be aware that order of data may have changed
let selectedData = ...
let indexPathForSelectedData = ...
collectionView.scrollToItem(
at: …Issue #433
style and isOn propertylet checkButton = NSButton(checkboxWithTitle: "", target: nil, action: nil)
checkButton.stylePlain(title: "Autosave", color: R.color.text, font: R.font.text)
checkButton. …Issue #432
Read Container Directories and File System Access
When you adopt App Sandbox, your application has access to the following locations:
The app container directory. Upon first launch, the operating system creates a special directory for …
Issue #429
Use https://github.com/markedjs/marked
<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title>Marked in the browser</title>
</head>
<body>
<div id="content" …Issue #428
Need to set target
let item = NSMenuItem(
title: title,
action: #selector(onMenuItemClicked(_:)),
keyEquivalent: ""
)
item.target = self
Sometimes, need to check autoenablesItems
Indicates whether the menu …
Issue #427
Use ClickedCollectionView to detect clicked index for context menu.
Embed NSCollectionView inside NSScrollView to enable scrolling
import AppKit
public class CollectionViewHandler<Item: Equatable, Cell: …Issue #426
https://rxmarbles.com/#throttle
Returns an Observable that emits the first and the latest item emitted by the source Observable during sequential time windows of a specified duration. This operator makes sure that no two …
Issue #425
flatMap: map and flatten array of arrays
compactMap: map and flatten array of optionals
Issue #422
To constrain views outside to elements inside UICollectionViewCell, we can use UILayoutGuide.
Need to make layout guide the same constraints as the real elements
let imageViewGuide = UILayoutGuide()
collectionView.addLayoutGuide( …Issue #421
private func maskCvcIfAny() {
guard
let view = paymentTextField.subviews.first(where: { !($0 is UIImageView) }),
let cvcField = view.subviews
.compactMap({ $0 as? UITextField })
.first(where: { $0.tag == 2 …Issue #414
Codable is awesome, but sometimes we just need to quickly get value in a deepy nested JSON. In the same way I did for Dart How to resolve deep json object in Dart, let’s make that in Swift.
See …
Issue #412
When the value of this property is true, the …
Issue #411
class ViewController: UIViewController, UICollectionViewDropDelegate, UICollectionViewDragDelegate {
// MARK: - UICollectionViewDragDelegate
func collectionView(_ collectionView: UICollectionView, …Issue #410
import AppKit
import Anchors
class DraggingView: NSView {
var didDrag: ((FileInfo) -> Void)?
let highlightView = NSView()
override init(frame frameRect: NSRect) {
super.init(frame: frameRect) …Issue #409
let stepper = NSStepper()
let textField = NSTextField(wrappingLabelWithString: "\(myLocalCount)")
stepper.integerValue = myLocalCount
stepper.minValue = 5
stepper.maxValue = 24
stepper.valueWraps = false
stepper.target = self …Issue #408
Podfile
pod 'MASShortcut'
let shortcut = MASShortcut(keyCode: kVK_ANSI_K, modifierFlags: [.command, .shift])
MASShortcutMonitor.shared()?.register(shortcut, withAction: {
self.showPopover(sender: self.statusItem.button)
})
Issue #407
https://developer.apple.com/documentation/appkit/nsworkspace/1524399-selectfile
In macOS 10.5 and later, this method does not follow symlinks when selecting the file. If the fullPath parameter contains any symlinks, this method selects …
Issue #406
let progressIndicator = NSProgressIndicator()
progressIndicator.isIndeterminate = true
progressIndicator.style = .spinning
progressIndicator.startAnimation(nil)
Issue #405
Enable Read/Write for User Selected File under Sandbox to avoid bridge absent error
func showSave(
name: String,
window: NSWindow
) async -> URL? {
let panel = NSSavePanel()
panel.directoryURL = FileManager.default. …Issue #404
let animation = CAKeyframeAnimation(keyPath: "position.y")
animation.values = [50, 20, 50]
animation.keyTimes = [0.0, 0.5, 1.0]
animation.duration = 2
animation.repeatCount = Float.greatestFiniteMagnitude
animation.autoreverses = …Issue #403
The application sends this message to your delegate when the application’s last window is closed. It sends this …
Issue #402
I want to test if a date has passed another date
let base = Date(timeIntervalSince1970: 1567756697)
XCTAssertEqual(validator.hasPassed(event: event, date: base), true)
My hasPassed is using Calendar.current
func minuteSinceMidnight(date: …Issue #395
Prefer static enum to avoid repetition and error. The Log should have methods with all required fields so the call site is as simple as possible. How to format and assign parameters is encapsulated in this Analytics.
import Foundation …Issue #377
OneSignal is an alternative for Parse for push notifications but the sdk has many extra stuff and assumptions and lots of swizzling.
We can just use Rest to make API calls. From https://github.com/onmyway133/Dust
Every official push …
Issue #376
https://github.com/onmyway133/Omnia/blob/master/Sources/Shared/Debouncer.swift
import Foundation
public class Debouncer {
private let delay: TimeInterval
private var workItem: DispatchWorkItem?
public init(delay: TimeInterval …Issue #375
final class LifecyclerHandler {
private var observer: AnyObject!
var action: (() -> Void)?
private let debouncer = Debouncer(delay: 1.0)
func setup() {
observer = NotificationCenter.default.addObserver( …Issue #374
Add accessibilityIdentifier to the parent view of GMSMapView. Setting directly onto GMSMapView has no effect
accessibilityIdentifier = "MapView"
let map = app.otherElements.matching(identifier: …Issue #373
UIButton.contentEdgeInsets does not play well with Auto Layout, we need to use intrinsicContentSize
final class InsetButton: UIButton {
required init(text: String) {
super.init(frame: .zero)
titleLabel?.textColor = . …Issue #371
Scrolling UIScrollView is used in common scenarios like steps, onboarding.
From iOS 11, UIScrollView has contentLayoutGuide and frameLayoutGuide
https://developer.apple.com/documentation/uikit/uiscrollview/2865870-contentlayoutguide …
Issue #368
See https://github.com/onmyway133/Omnia/blob/master/Sources/iOS/NSLayoutConstraint.swift
extension NSLayoutConstraint {
/// Disable auto resizing mask and activate constraints
///
/// - Parameter constraints: constraints to …Issue #365
import WebKit
import SafariServices
final class WebViewHandler: NSObject, WKNavigationDelegate {
var show: ((UIViewController) -> Void)?
let supportedSchemes = ["http", "https"]
func webView(_ webView: …Issue #364
AppFlowController.swift
import UIKit
import GoogleMaps
import Stripe
final class AppFlowController: UIViewController {
private lazy var window = UIWindow(frame: UIScreen.main.bounds)
func configure() {
GMSServices. …Issue #362
let tapGR = UITapGestureRecognizer(target: self, action: #selector(handleTap(_:)))
@objc private func handleTap(_ gr: UITapGestureRecognizer) {
didTouch?()
}
We need to use lazy instead of let for gesture to work
lazy var tapGR = …Issue #361
protocol Task {}
struct Build: Task {}
struct Test: Task {}
@_functionBuilder
public struct TaskBuilder {
public static func buildBlock(_ tasks: Task...) -> [Task] {
tasks
}
}
public func run(@TaskBuilder builder: () …Issue #360
Given a streaming service
service Server {
rpc GetUsers(GetUsersRequest) returns (stream GetUsersResponse);
}
To get a response list in Swift, we need to do observe stream, which is a subclass of ClientCallServerStreaming
func getUsers( …Issue #356
StripeHandler.swift
From Stripe 16.0.0 https://github.com/stripe/stripe-ios/blob/master/CHANGELOG.md#1600-2019-07-18
Migrates STPPaymentCardTextField.cardParams property type from STPCardParams to STPPaymentMethodCardParams
final class …Issue #355
final class CurrencyFormatter {
func format(amount: UInt64, decimalCount: Int) -> String {
let formatter = NumberFormatter()
formatter.minimumFractionDigits = 0
formatter.maximumFractionDigits = decimalCount …Issue #354
In Construction, we have a build method to apply closure to inout struct.
We can explicitly define that with withValue
func withValue<T>(_ value: T, closure: (inout T) -> Void) -> T {
var mutableValue = value
closure …Issue #350
Read Authenticate with Firebase on iOS using a Phone Number
Info.plist
<key>FirebaseAppDelegateProxyEnabled</key>
<string>NO</string>
Enable Capability -> Background …
Issue #347
Add a hidden UITextField to view hierarchy, and add UITapGestureRecognizer to activate that textField.
Use padding string with limit to the number of labels, and prefix to get exactly n characters.
DigitView.swift
import UIKit
final …Issue #346
We have FrontCard that contains number and expiration date, BackCard that contains CVC. CardView is used to contain front and back sides for flipping transition.
We leverage STPPaymentCardTextField from Stripe for working input fields, …
Issue #345
UIButton with system type has implicit animation for setTitle(_:for:)
Use this method to set the title for the button. The title you specify derives its formatting from the button’s associated label object. If you set both a title and an …
Issue #344
addSubview can trigger viewDidLayoutSubviews, so be careful to just do layout stuff in viewDidLayoutSubviews
This method establishes a strong reference to view and sets its next responder to the receiver, which is its new superview. …
Issue #340
https://nshipster.com/formatter/#datecomponentsformatter
Results in no padding 0
func format(second: TimeInterval) -> String? {
let formatter = DateComponentsFormatter()
formatter.unitsStyle = . …Issue #337
Normally we just present from any UIViewController in any UINavigationController in UITabBarController and it will present over tabbar
present(detailViewController, animated: true, completion: nil)
If we have animation with …
Issue #336
Use NSPopUpButton
var pullsDown: Bool
A Boolean value indicating whether the button displays a pull-down or pop-up menu.
func addItem(withTitle: String)
Adds an item with the specified title to the end of the menu.
Should disable …
Issue #335
This is useful when we want to get the first meaningful line in a big paragraph
let scanner = Scanner(string: text)
var result: NSString? = ""
scanner.scanUpTo("\n", into: &result)
return result as String?
Issue #334
NSSecureCoding has been around since iOS 6 and has had some API changes in iOS 12
A protocol that enables encoding and decoding in a manner that is robust against object substitution attacks. …
Issue #333
In a traditional pager with many pages of content, and a bottom navigation with previous and next button. Each page may have different content, and depending on each state, may block the next button.
The state of next button should state …
Issue #332
From moveItem(at:to:)
Moves an item from one location to another in the collection view.
After rearranging items in your data source object, use this method to synchronize those changes with the collection view. Calling this method lets …
Issue #331
From NSSegmentedControl
The features of a segmented control include the following: A segment can have an image, text (label), menu, tooltip, and tag. A segmented control can contain images or text, but not both.
let languageMenu = NSMenu( …Issue #330
When adding NSTextView in xib, we see it is embedded under NSClipView. But if we try to use NSClipView to replicate what’s in the xib, it does not scroll.
To make it work, we can follow Putting an NSTextView Object in an NSScrollView …
Issue #329
Firstly, to make UIStackView scrollable, embed it inside UIScrollView. Read How to embed UIStackView inside UIScrollView in iOS
It’s best to listen to keyboardWillChangeFrameNotification as it contains frame changes for Keyboard in …
Issue #328
Sometimes we want to validate forms with many fields, for example name, phone, email, and with different rules. If validation fails, we show error message.
We can make simple Validator and Rule
class Validator {
func validate(text: …Issue #327
In terms of tests, we usually have files for unit test, UI test, integeration test and mock.
Out of sight, out of mind.
Unit tests are for checking specific functions and classes, it’s more convenient to browse them side by side …
Issue #326
Traditionally, from Swift 4.2 we need guard let self
addButton.didTouch = { [weak self] in
guard
let self = self,
let product = self.purchasedProduct()
else {
return
self.delegate?.productViewController …Issue #325
UILabel as placeholder and move itoffsetX for translation is 10%Issue #324
view.addSubview(scrollView)
scrollView.addSubview(stackView)
NSLayoutConstraint.on([
scrollView.pinEdges(view: view),
stackView.pinEdges(view: scrollView)
])
NSLayoutConstraint.on([
stackView.widthAnchor.constraint(equalTo: …Issue #323
Use proxy animator()
let indexPath = IndexPath(item: index, section: 0)
collectionView.animator().deleteItems(at: Set(arrayLiteral: indexPath))
let indexPath = IndexPath(item: 0, section: 0)
collectionView.animator().insertItems(at: Set( …Issue #322
lazy var gr = NSClickGestureRecognizer(target: self, action: #selector(onPress(_:)))
gr.buttonMask = 0x2
gr.numberOfClicksRequired = 1
view.addGestureRecognizer(gr)
Issue #321
class ClickedCollectionView: NSCollectionView {
var clickedIndex: Int?
override func menu(for event: NSEvent) -> NSMenu? {
clickedIndex = nil
let point = convert(event. …Issue #320
NSTextAttachmentCellProtocolRich Text and GraphicsIssue #319
ATSApplicationFontsPath …
Issue #318
I do UI in code, and usually separate between View and ViewController.
class ProfileView: UIView {}
class ProfileViewController: UIViewController {
override func loadView() {
self.view = ProfileView()
}
}
But in places where …
Issue #315
extension PanCollectionViewController: UIGestureRecognizerDelegate {
func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
let velocity = panGR.velocity(in: panGR.view)
return abs( …Issue #312
class ClosableWindow: NSWindow {
override func close() {
self.orderOut(NSApp)
}
}
let window = ClosableWindow(
contentRect: rect,
styleMask: [.titled, .closable],
backing: .buffered,
defer: false
}
window. …Issue #311
See Omnia https://github.com/onmyway133/Omnia/blob/master/Sources/iOS/UICollectionView.swift#L30
extension HorizontalUsersViewController: UIScrollViewDelegate {
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { …Issue #309
let placemark = MKPlacemark(coordinate: coordinate, addressDictionary: nil)
let mapItem = MKMapItem(placemark: placemark)
mapItem.name = shop.name
mapItem.openInMaps(launchOptions: [:])
Issue #308
If you don’t want to use https://github.com/onmyway133/EasyClosure yet, it’s easy to roll out a closure based UIButton. The cool thing about closure is it captures variables
final class ClosureButton: UIButton {
var …Issue #307
import MapKit
let formatter = MKDistanceFormatter()
formatter.unitStyle = .abbreviated
formatter.units = .metric
distanceLabel.text = formatter.string(fromDistance: distance) // 700m, 1.7km
Issue #306
let json: [String: Any] = [
"id": "123",
"name": "Thor",
"isInMarvel": true
]
let data = try JSONSerialization.data(withJSONObject: json, options: [])
let string = String(data: data, …Issue #305

This year I’m lucky enough to get the ticket to WWDC and I couldn’t be more satisfied. 5 conference days full of awesomeness, talks, labs and networking, all make WWDC special and memorial conference for every attendee.
As …
Issue #303
Instead of setting up custom framework and Playground, we can just display that specific view as root view controller
window.rootViewController = makeTestPlayground()
func makeTestPlayground() -> UIViewController {
let content = …Issue #302
final class CarouselLayout: UICollectionViewFlowLayout {
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
guard let attributes = super. …Issue #301
Make it more composable using UIViewController subclass and ThroughView to pass hit events to underlying views.
class PanViewController: UIViewController {
var animator = UIViewPropertyAnimator(duration: 0, curve: .easeOut)
lazy …Issue #297
let button = NSButton()
button.wantsLayer = true
button.isBordered = false
button.setButtonType(.momentaryChange)
button.attributedTitle = NSAttributedString(
string: "Click me",
attributes: [
NSAttributedString.Key …Issue #296
Original answer https://stackoverflow.com/a/54793979/1418457
In your NSCollectionViewItem subclass, override isSelected and change background color of the layer. Test in macOS 10.14 and Swift 4.2
class Cell: NSCollectionViewItem { …Issue #288
Use this property to specify a …
Issue #270
As you know, in the Pragmatic Programmer, section Your Knowledge Portfolio, it is said that
Learn at least one new language every year. Different languages solve the same problems in different ways. By learning several different …
Issue #243
From https://developer.apple.com/documentation/coregraphics/1455137-cgwindowlistcopywindowinfo
Generates and returns information about the selected windows in the current user session.
struct MyWindowInfo {
let frame: CGRect
let …Issue #233
Shake
let midX = box.layer?.position.x ?? 0
let midY = box.layer?.position.y ?? 0
let animation = CABasicAnimation(keyPath: "position")
animation.duration = 0.06
animation.repeatCount = 4 …Issue #232
From https://github.com/xhamr/paintcode-path-scale with some updates
extension CGRect {
var center: CGPoint {
return CGPoint( x: self.size.width/2.0,y: self.size.height/2.0)
}
}
extension CGPoint {
func vector(to p1: …Issue #230
CAReplicatorLayer is a layer that creates a specified number of sublayer copies with varying geometric, temporal, and color transformations
Here we use instanceTransform which applies transformation matrix around the center of the …
Issue #229
let animation = CASpringAnimation(keyPath: #keyPath(CALayer.transform))
animation.fromValue = 0
animation.valueFunction = CAValueFunction(name: CAValueFunctionName.rotateZ)
animation.timingFunction = CAMediaTimingFunction(name: …Issue #228
CAAnimation is about presentation layer, after animation completes, the view snaps back to its original state. If we want to keep the state after animation, then the wrong way is to use CAMediaTimingFillMode.forward and …
Issue #227
final class SearchBox: UIView {
lazy var textField: UITextField = {
let textField = UITextField()
let imageView = UIImageView(image: R.image.search()!)
imageView.frame.size = CGSize(width: 20 + 8, height: 20) …Issue #226
Take screenshot
xcrun simctl io booted screenshot image.png
Record video
xcrun simctl io booted recordVideo video.mp4
Issue #225
<key>UIAppFonts</key>
<array>
<string>OpenSans-Bold.ttf</string>
<string>OpenSans-BoldItalic.ttf</string>
<string>OpenSans-ExtraBold.ttf</string>
<string> …Issue #224
let tabBarController = UITabBarController()
let navigationController1 = UINavigationController(rootViewController: viewController1)
let navigationController2 = UINavigationController(rootViewController: viewController2)
let …Issue #222
For more mature networking, visit https://github.com/onmyway133/Miami
final class NetworkClient {
let session: URLSession
let baseUrl: URL
init(session: URLSession = .shared, baseUrl: URL) {
self.session = session …Issue #219
import UIKit
import Stripe
final class MainController: UIViewController {
func showPayment() {
let addCardViewController = …Issue #218
Recorderclass …Issue #216
https://docs.sonarqube.org/latest/setup/get-started-2-minutes/
~/sonarqube~/sonarqube/bin/macosx-universal-64/sonar.sh …Issue #214
extension Result {
func to(subject: PublishSubject<Success>) {
switch self {
case .success(let value):
subject.onNext(value)
case .failure(let error):
subject.onError(error) …Issue #212
Pre iOS 10
func schedule() {
DispatchQueue.main.async {
self.timer = Timer.scheduledTimer(timeInterval: 20, target: self,
selector: #selector(self.timerDidFire(timer:)), userInfo: nil, repeats: …Issue #211
Functions in Swift are distinguishable by
so that these are all valid, and works for subscript as well
struct A {
// return type
func get() -> String { return "" } …Issue #200
let home = NSSearchPathForDirectoriesInDomains(.applicationScriptsDirectory, .userDomainMask, true).first!
let path = home.appending(".XcodeWayExtensions/XcodeWayScript.scpt")
let exists = FileManager.default.fileExists(atPath: …Issue #197
https://grpc.io/docs/quickstart/go.html
Install the protoc compiler that is used to generate gRPC service code. The simplest way to do this is to download pre-compiled binaries for your platform(protoc-
- .zip) from here: …
Issue #195
URLSession offer tons of thing that it’s hard to use with wrappers like AlamofireIssue #194
DispatchWorkItemIssue #193
var components = URLComponents(string: "https://google.com/")
components?.path = "abc/"
components?.url
-> nil
var components = URLComponents(string: "https://google.com/")
components?.path = "/abc/" …Issue #185
You may encounter curry in everyday code without knowing it. Here is a bit of my reflections on curry and how to apply it in Javascript and Swift.
In Haskell, all function officially takes only 1 parameter. …
Issue #176
Enable executable
chmod +x executable
Add executable file to target
Use Process with correct launchPad
import Foundation
protocol TaskDelegate: class {
func task(task: Task, didOutput string: String)
func taskDidComplete(task: Task)
} …Issue #175
let process = Process()
process.launchPath = "/bin/pwd"
process.arguments = []
Should be the same as FileManager.default.currentDirectoryPath
Issue #174
Disable vibrancy mode of NSPopover
let popover = NSPopover()
popover.appearance = NSAppearance(named: NSAppearance.Name.aqua)
Issue #173
You might need to flip NSClipView
import AppKit
import Anchors
import Omnia
final class ScrollableStackView: NSView {
final class FlippedClipView: NSClipView {
override var isFlipped: Bool {
return true
} …Issue #171
var views: NSArray?
NSNib(nibNamed: NSNib.Name("ProfileView"), bundle: nil)?.instantiate(withOwner: nil, topLevelObjects: &views)
let profileView = views!.compactMap({ $0 as? ProfileView }).first!
Issue #154
The most common UI element in iOS is UITableView, and the most common task is to display the UITableViewCell using the model.
Although the title specifies UITableViewCell, but the problem involves other views (UICollectionView, custom …
Issue #148
From https://github.com/devxoul/Pure/blob/master/Sources/Pure/FactoryModule.swift
public protocol FactoryModule: Module {
/// A factory for `Self`.
associatedtype Factory = Pure.Factory<Self>
/// Creates an instance of a …Issue #147
Each language and platform has its own coding style guide. This goes true when it comes to abbreviations. I’ve had some debates about whether to use JSON or Json, URL or Url, HTTP or Http.
I personally prefer camelCase, so I’m …
Issue #144
There are times we want the same UIViewController to look good when it’s presented modally or pushed from UINavigationController stack. Take a look at BarcodeScanner and the PR https://github.com/hyperoslo/BarcodeScanner/pull/82
When …
Issue #140
I need to generate QR code in https://github.com/onmyway133/AddressGenerator. Fortunately with CoreImage filter, it is very easy. Code is in Swift 4
import AppKit
final class QRCodeGenerator {
func generate(string: String, size: CGSize) …Issue #137
Use a custom NavigationController
import UIKit
class NavigationController: UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
navigationBar.tintColor = .white
navigationBar.barStyle = .black …Issue #131
Here’s how to create NSCollectionView programatically. We need to embed it inside NScrollView for scrolling to work. Code is in Swift 4
let layout = NSCollectionViewFlowLayout()
layout.minimumLineSpacing = 4 …Issue #130
Code is in Swift 4
let byteCount = 32
let result = UnsafeMutablePointer<UInt8>.allocate(capacity: byteCount)
extension Data {
func toPointer() -> UnsafePointer<UInt8 …Issue #124
We all know that there’s a potential crash with UIVisualEffectView on iOS 11. The fix is to not add sub views directly to UIVisualEffectView, but to its contentView. So we should change
effectView.addSubview(button)
to
effectView. …Issue #122
From Set
You can create a set with any element type that conforms to the Hashable protocol. By default, most types in the standard library are hashable, including strings, numeric and Boolean types, enumeration cases without associated …
Issue #121
These are different
class DiffService<T: MKAnnotation & Equatable>
class DiffService<T: MKAnnotation, Equatable>
Issue #119
This is about collection update, how to provide correct IndexPath and a simple diffing algorithm
Issue #113
This is a follow up from my post Learning from Open Source: Using Playground on how to actually add a playground to your production project.
The idea is simple: create a framework so that Playground can access the code. This demo an iOS …
Issue #110
Medium version https://medium.com/@onmyway133/url-routing-with-compass-d59c0061e7e2
Apps often have many screens, and UIViewController works well as the basis for a screen, together with presentation and navigation APIs. Things are fine …
Issue #106
Every new architecture that comes out, either iOS or Android, makes me very excited. I’m always looking for ways to structure apps in a better way. But after some times, I see that we’re too creative in creating architecture, …
Issue #105
Are you willing to take vaccines you don’t know about?
I like open source. I ’ve made some and contributed to some. I also use other people ’s open source libraries and learn a lot from them 😇
Open source can help us …
Issue #99
I’ve been searching for efficient ways to diff collections, here are some interesting papers that I find
Myers
Issue #98
The safeAreaLayoutGuide was introduced in iOS 11. And it is advised to stop using topLayoutGuide bottomLayoutGuide as these are deprecated.
To use safeAreaLayoutGuide, you need to do iOS version check
if #available(iOS 11.0, *) { …Issue #97
The Coordinator pattern can be useful to manage dependencies and handle navigation for your view controllers. It can be seen from BackchannelSDK-iOS, take a look at BAKCreateProfileCoordinator for example
@implementation …Issue #96
Another cool thing about ios-oss is how it manages dependencies. Usually you have a lot of dependencies, and it’s good to keep them in one place, and inject it to the objects that need.
The Environment is simply a struct that holds …
Issue #94
One thing I like about kickstarter-ios is how they use Playground to quickly protoyping views.
We use Swift Playgrounds for iterative development and styling. Most major screens in the app get a corresponding playground where we can see a …
Issue #93
Hi, here is how I indent my code. Let me know what you think 😉
When possible, configure your editor to use 2 spaces for tab size. You will love it ❤️

If there are many parameters, …
Issue #75
We should use DispatchQueue to build thread safe code. The idea is to prevent two read and write from happening at the same time from 2 different threads, which cause data corruption and unexpected behaviors. Note that you should try to …
Issue #58
Do you know that an optional can itself contain an optional, that contains another optional? In that case, we need to unwrap multiple times

You mostly see it when you try to access window
let window = UIApplication.shared.delegate?.window …Issue #54
Today I’m trying to change the year of a Date object to 2000 in Swift.
let date = Date()
Firstly, I tried with date(bySetting:) but it does not work with past year. It simply returns nil
Calendar.current.date(bySetting: .year, value: …Issue #48
Continue my post https://github.com/onmyway133/blog/issues/45. When you work with features, like map view, you mostly need permissions, and in UITests you need to test for system alerts.
This is the code. Note that …
Issue #45
You should mock a location to ensure reliable test
Go to Xcode -> File -> New -> GPX File

It looks like
<?xml version="1.0"?>
<gpx version="1.1" creator="Xcode" …Issue #36
Usually in an app, we have these flows: onboarding, login, main. And we usually set OnboardingController, LoginController and MainController as the root view controller respectively depending on the state.
I find it useful to have the …
Issue #35
Auto Layout is awesome. Just declare the constraints and the views are resized accordingly to their parent ’s bounds changes. But sometimes it does not look good, because we have fixed values for padding, width, height, and even fixed …
Issue #34
In an iOS project, we often see this in AppDelegate
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions …Issue #33
I see that my answer to the question What’s the meaning of Base SDK, iOS deployment target, Target, and Project in xcode gets lots of views, so I think I need to elaborate more about it
Good read
Issue #26
When working on Scale I think it’s good to have a way to group the digit so that it is easier to reason
Luckily, Swift already supports this. See The Swift Programming Language - Numeric Literals
Numeric literals can contain extra …
Issue #24
There is Lighter View Controllers, and there is Lighter AppDelegate, too
Since working with iOS, I really like the delegate pattern, in which it helps us defer the decision to another party.
The iOS application delegates its event to …
Issue #21
The other day I was trying t
Issue #20
The other day I was doing refresh control, and I saw this Swift Protocols with Default Implementations as UI Mixins
extension Refreshable where Self: UIViewController
{
/// Install the refresh control on the table view
func …Issue #17
I always forget how to write correct #available( or #if swift(>=3.0) or just lazy to write required init?(coder aDecoder: NSCoder) every time I make a subclass. That’s why I made SwiftSnippets to save time for these tedious tasks. …
Issue #13
There is time we have models that have some kind of inheritance, like Dog, Cat, Mouse can be Animal. We can use composition to imitate inheritance, we just need to make sure it has unique primary key
These are pretty much basic …
Issue #10
There is time we want to execute an action only once. We can surely introduce a flag, but it will be nicer if we abstract that out using composition. Then we have
class Once {
var already: Bool = false
func run(@noescape block: () …Issue #4
Realm is great. But without primary key, it will duplicate the record, like https://github.com/realm/realm-java/issues/2730, http://stackoverflow.com/questions/32322460/should-i-define-the-primary-key-for-each-entity-in-realm, … So to …
Issue #2
When I was reading through Swinject, I found something interesting https://github.com/Swinject/Swinject/blob/master/Sources/Container.swift
public convenience init(parent: Container? = nil, registeringClosure: (Container) -> Void) { …