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 · 87 words · Khoa

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 · 31 words · Khoa

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 · 22 words · Khoa

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 · 139 words · Khoa

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 · 42 words · Khoa

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 · 282 words · Khoa

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 · 205 words · Khoa

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 · 18 words · Khoa

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 · 53 words · Khoa

How to use TabView with enum in SwiftUI

Issue #599 Specify tag enum Authentication: Int, Codable { case key case certificate } TabView(selection: $authentication) { KeyAuthenticationView() .tabItem { Text("🔑 Key") } .tag(Authentication.key) CertificateAuthenticationView() .tabItem { Text("📰 Certificate") } .tag(Authentication.certificate) }

February 11, 2020 · 1 min · 32 words · Khoa

How to build SwiftUI style UICollectionView data source in Swift

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 if we abstract over it, then it becomes super hard to customize. Every app is unique, and any attempt to wrap around UICollectionView will fail horribly. A sensable approach for a good abstraction is to make it super easy for normal cases, and easy to customize for advanced scenarios....

February 9, 2020 · 4 min · 832 words · Khoa

How to make round border in SwiftUI

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.inputBorderFocus : Color.clear, lineWidth: 1) )

February 5, 2020 · 1 min · 24 words · Khoa

How to mock in Swift

Issue #596 Unavailable init UNUserNotificationCenter.current().getNotificationSettings(completionHandler: { (settings: UNNotificationSettings) in let status: UNAuthorizationStatus = .authorized settings.setValue(status.rawValue, forKey: "authorizationStatus") completionHandler(settings) })

February 4, 2020 · 1 min · 19 words · Khoa

How to change background color in List in SwiftUI for macOS

Issue #595 SwiftUI uses ListCoreScrollView and ListCoreClipView under the hood. For now the workaround, is to avoid using List List { ForEach } use VStack { ForEach }

February 4, 2020 · 1 min · 28 words · Khoa

How to add drag and drop in SwiftUI

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, .text ] } func handleDrop(info: DropInfo) -> Bool { for provider in info.itemProviders(for: dropTypes) { for type in dropTypes { provider.loadDataRepresentation(forTypeIdentifier: type.identifier) { data, _ in guard let data = data, let string = String(data: data, encoding: .utf8) else { return } DispatchQueue....

February 4, 2020 · 2 min · 218 words · Khoa

How to make radio button group in SwiftUI

Issue #592 Use picker with Radio style Hard to customize Picker(selection: Binding<Bool>.constant(true), label: EmptyView()) { Text("Production").tag(0) Text("Sandbox").tag(1) }.pickerStyle(RadioGroupPickerStyle()) Use custom view Use contentShape to make whole button tappable. Make custom Binding for our enum struct EnvironmentView: View { @Binding var input: Input var body: some View { VStack(alignment: .leading) { RadioButton(text: "Production", isOn: binding(for: .production)) RadioButton(text: "Sandbox", isOn: binding(for: .sandbox)) } } private func binding(for environment: Input.Environment) -> Binding<Bool> { Binding<Bool>( get: { self....

February 1, 2020 · 1 min · 157 words · Khoa

How to set font to NSTextField in macOS

Issue #591 Use NSTextView instead

January 29, 2020 · 1 min · 5 words · Khoa

How to make borderless material NSTextField in SwiftUI for macOS

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 { VStack(alignment: .leading, spacing: 0) { BorderlessTextField(placeholder: placeholder, text: $text, isFocus: $isFocus) .frame(maxHeight: 40) Rectangle() .foregroundColor(isFocus ? R.color.separatorFocus : R.color.separator) .frame(height: isFocus ? 2 : 1) } } } class FocusAwareTextField: NSTextField { var onFocusChange: (Bool) -> Void = { _ in } override func becomeFirstResponder() -> Bool { let textView = window?...

January 29, 2020 · 2 min · 231 words · Khoa

How to make focusable NSTextField in macOS

Issue #589 Use onTapGesture 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, placeholder: placeholder, isFocus: $isFocus) .padding() .cornerRadius(4) .overlay( RoundedRectangle(cornerRadius: 4) .stroke(isFocus ? Color.accentColor: Color.separator) ) .onTapGesture { isFocus = true } } } private struct FocusTextField: NSViewRepresentable { @Binding var text: String let placeholder: String @Binding var isFocus: Bool func makeNSView(context: Context) -> NSTextField { let tf = NSTextField() tf....

January 29, 2020 · 2 min · 367 words · Khoa

How to observe focus event of NSTextField in macOS

Issue #589 becomeFirstResponder class FocusAwareTextField: NSTextField { var onFocusChange: (Bool) -> Void = { _ in } override func becomeFirstResponder() -> Bool { let textView = window?.fieldEditor(true, for: nil) as? NSTextView textView?.insertionPointColor = R.nsColor.action onFocusChange(true) return super.becomeFirstResponder() } } textField.delegate // NSTextFieldDelegate func controlTextDidEndEditing(_ obj: Notification) { onFocusChange(false) } NSTextField and NSText https://stackoverflow.com/questions/25692122/how-to-detect-when-nstextfield-has-the-focus-or-is-its-content-selected-cocoa When you clicked on search field, search field become first responder once, but NSText will be prepared sometime somewhere later, and the focus will be moved to the NSText....

January 29, 2020 · 1 min · 186 words · Khoa