How to check if NSColor is light

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 } let brightness = ((components[0] * 299) + (components[1] * 587) + (components[2] * 114)) / 1000 return brightness > 0.5 } } Then we can apply contrast color for our Text extension Text { func applyColorBaseOnBackground(_ color: NSColor?) -> some View { guard let color = color else { return self } if color....

March 20, 2020 路 1 min 路 Khoa Pham

How to trigger onAppear in SwiftUI for macOS

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: NSViewRepresentableContext<AppearAware>) -> AwareView { let view = AwareView() view.onAppear = onAppear return view } func updateNSView(_ nsView: AwareView, context: NSViewRepresentableContext<AppearAware>) { } } final class AwareView: NSView { private var trigged: Bool = false var onAppear: () -> Void = {} override func viewDidMoveToSuperview() { super....

March 18, 2020 路 1 min 路 Khoa Pham

How to force refresh in ForEach in SwiftUI for macOS

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 } List { ForEach(notes) { note in NoteRow(note: note, id: UUID()) } } Updated at 2020-11-20 03:29:39

March 17, 2020 路 1 min 路 Khoa Pham

How to access bookmark url in macOS

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鈥檒l have to take advantage of a system called Security-Scoped Bookmarks. Add entitlements Use of app-scoped bookmarks and URLs <key>com.apple.security.files.user-selected.read-only</key> <true/> <key>com.apple.security.files.bookmarks.app-scope</key> <true/> Enabling Security-Scoped Bookmark and URL Access...

March 17, 2020 路 2 min 路 Khoa Pham

How to batch delete in Core Data

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 persistence layer and those entities are also in memory, it is important that you notify the application that the objects in memory are stale and need to be refreshed....

March 15, 2020 路 1 min 路 Khoa Pham

How to make TextField focus in SwiftUI for macOS

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 { true } } Furthermore to customize TextField, consider using custom import SwiftUI import AppKit struct MyTextField: NSViewRepresentable { @Binding var text: String func makeNSView(context: NSViewRepresentableContext<MyTextField>) -> NSTextField { let tf = NSTextField() tf.focusRingType = ....

March 13, 2020 路 1 min 路 Khoa Pham

How to show popover for item in ForEach in SwiftUI

Issue #618 Create custom Binding List { ForEach(self.items) { (item: item) in ItemRowView(item: item) .popover(isPresented: self.makeIsPresented(item: item)) { ItemDetailView(item: item) } } } func makeIsPresented(item: Item) -> Binding<Bool> { return .init(get: { return self.selectedId == item.id }, set: { _ in self.selectedId = nil }) }

March 11, 2020 路 1 min 路 Khoa Pham

How to make tooltip in SwiftUI for macOS

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 tooltip import SwiftUI struct Tooltip: NSViewRepresentable { let tooltip: String func makeNSView(context: NSViewRepresentableContext<Tooltip>) -> NSView { let view = NSView() view.toolTip = tooltip return view } func updateNSView(_ nsView: NSView, context: NSViewRepresentableContext<Tooltip>) { nsView....

March 11, 2020 路 1 min 路 Khoa Pham

How to make tab view in SwiftUI

Issue #614 struct MyTabView: View { @EnvironmentObject var preferenceManager: PreferenceManager var body: some View { VOrH(isVertical: preferenceManager.preference.position.isVertical) { OneTabView(image: "one", text: "One", tab: .one) OneTabView(image: "two", text: "Two", tab: .two) OneTabView(image: "three", text: "Three", tab: .three) Spacer() } } } struct OneTabView: View { @EnvironmentObject var preferenceManager: PreferenceManager let image: String let text: String let tab: Tab var selected: Bool { preferenceManager.preference.tab == tab } var body: some View { Button(action: { self....

March 2, 2020 路 1 min 路 Khoa Pham

How to present NSWindow modally

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 yourself.) While the app is in that loop, it does not respond to any other events (including mouse, keyboard, or window-close events) unless they are associated with the window....

March 2, 2020 路 1 min 路 Khoa Pham

How to use Picker with enum in SwiftUI

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) { Text($0.rawValue) } }

February 29, 2020 路 1 min 路 Khoa Pham

How to use visual effect view in NSWindow

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(\.managedObjectContext, coreDataManager.container.viewContext) window = NSWindow( contentRect: .zero, styleMask: [.fullSizeContentView], backing: .buffered, defer: false ) window.titlebarAppearsTransparent = true window.center() window.level = .statusBar window.setFrameAutosaveName("MyApp") let visualEffect = NSVisualEffectView() visualEffect.blendingMode = .behindWindow visualEffect.state = ....

February 27, 2020 路 1 min 路 Khoa Pham

How to animate NSWindow

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(rect, display: true, animate: true) }, completionHandler: { })

February 23, 2020 路 1 min 路 Khoa Pham

How to find active application in macOS

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 聽

February 22, 2020 路 1 min 路 Khoa Pham

How to compare for nearly equal in Swift

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, _ alpha: CGFloat) { self.red = red self.green = green self.blue = blue self.alpha = alpha } static func round(_ value: CGFloat) -> CGFloat { (value * 100).rounded() / 100 } static func == (left: RGBA, right: RGBA) -> Bool { let r = Self....

February 19, 2020 路 1 min 路 Khoa Pham

How to conform to Hashable for class in Swift

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) } func hash(into hasher: inout Hasher) { hasher.combine(ObjectIdentifier(self)) } }

February 17, 2020 路 1 min 路 Khoa Pham

How to edit selected item in list in SwiftUI

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(context: Context) -> NSTextView { let textView = NSTextView() textView.delegate = context.coordinator return textView } func updateNSView(_ nsView: NSTextView, context: Context) { guard nsView.string != text else { return } nsView.string = text } class Coordinator: NSObject, NSTextViewDelegate { let parent: TextView init(_ textView: TextView) { self....

February 14, 2020 路 2 min 路 Khoa Pham

How to mask with UILabel

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.foregroundColor = UIColor.white.cgColor textLayer.string = "Hello world" textLayer.font = UIFont.preferredFont(forTextStyle: .largeTitle) textLayer.frame = aView.bounds aView.layer.mask = textLayer Use sizeToFit to ensure frame for UILabel let label = UILabel() label.frame.origin = CGPoint(x: 80, y: 80) label....

February 13, 2020 路 1 min 路 Khoa Pham

How to avoid pitfalls in SwiftUI

Issue #602 Identify by unique id ForEach(store.blogs.enumerated().map({ $0 }), id: \.element.id) { index, blog in } ``` ##

February 12, 2020 路 1 min 路 Khoa Pham

How to sync multiple CAAnimation

Issue #600 Use same CACurrentMediaTime final class AnimationSyncer { static let now = CACurrentMediaTime() func makeAnimation() -> CABasicAnimation { let animation = CABasicAnimation(keyPath: "opacity") animation.fillMode = .forwards animation.fromValue = 0 animation.toValue = 1 animation.repeatCount = .infinity animation.duration = 2 animation.beginTime = Self.now animation.autoreverses = true animation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut) return animation } }

February 11, 2020 路 1 min 路 Khoa Pham