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 log in SwiftUI

Issue #604 I see that the modifier needs to do something on the content, otherwise it is not getting called! This logs on the modifier, when the View is created. A View won鈥檛 be recreated unless necessary struct LogModifier: ViewModifier { let text: String func body(content: Content) -> some View { print(text) return content .onAppear {} } } extension View { func log(_ text: String) -> some View { self.modifier(LogModifier(text: text)) } } VStack { Text("") ....

February 14, 2020 路 1 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 use application will terminate in macOS

Issue #601 On Xcode 11, applicationWillTerminate is not called because of default automatic termination on in Info.plist. Removing NSSupportsSuddenTermination to trigger will terminate notification func applicationWillTerminate(_ notification: Notification) { save() } <key>NSSupportsAutomaticTermination</key> <true/> <key>NSSupportsSuddenTermination</key> <true/>

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

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

How to build SwiftUI style UICollectionView data source in Swift

Issue #598 It鈥檚 hard to see any iOS app which don鈥檛 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 路 Khoa Pham

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

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

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 } Updated at 2020-08-14 07:26:27

February 4, 2020 路 1 min 路 Khoa Pham

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

How to weak link Combine in macOS 10.14 and iOS 12

Issue #593 #if canImport(Combine) is not enough, need to specify in Other Linker Flags OTHER_LDFLAGS = -weak_framework Combine Read more https://stackoverflow.com/questions/57168931/optional-linking-for-swift-combine-framework-in-xcode-11

February 2, 2020 路 1 min 路 Khoa Pham

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

How to set font to NSTextField in macOS

Issue #591 Use NSTextView instead

January 29, 2020 路 1 min 路 Khoa Pham

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

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

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