How to disable NSTextView in SwiftUI

Issue #702 The trick is to use an overlay MessageTextView(text: $input.message) .overlay(obscure) var obscure: AnyView { if store.pricingPlan.isPro { return EmptyView().erase() } else { return Color.black.opacity(0.01).erase() } }

November 27, 2020 · 1 min · 28 words · Khoa

How to add under highlight to text in css

Issue #701 Use mark. This does not work for multiline <p> <mark css={css` display: inline-block; line-height: 0em; padding-bottom: 0.5em; `}>{feature.title} </mark> </p> Another way is to use background .highlight { background: linear-gradient(180deg,rgba(255,255,255,0) 50%, #FFD0AE 50%); } Read more https://beatrizcaraballo.com/blog/low-highlight-heading-links-squarespace https://stackoverflow.com/questions/43683187/how-can-i-create-custom-underline-or-highlight-for-text-in-html-or-css https://medium.com/@codingdudecom/highlight-text-css-97331a5b71b5 Updated at 2020-11-20 05:23:59

November 20, 2020 · 1 min · 45 words · Khoa

How to use default system fonts in React apps

Issue #700 In index.css body { margin: 0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } code { font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', monospace; } Updated at 2020-11-18 06:29:29

November 18, 2020 · 1 min · 44 words · Khoa

How to make simple overlay container in React

Issue #699 Use term ZStack like in SwiftUI, we declare container as relative position. For now it uses only 2 items from props.children but can be tweaked to support mutiple class App extends React.Component { render() { return ( <ZStack> <Header /> <div css={css` padding-top: 50px; `}> <Showcase factory={factory} /> <Footer /> </div> </ZStack> ) } } /** @jsx jsx */ import React from 'react'; import { css, jsx } from '@emotion/core' export default function ZStack(props) { return ( <div css={css` position: relative; border: 1px solid red; `}> <div css={css` position: absolute; top: 0; left: 0; width: 100%; z-index: -1; `}> {props....

November 18, 2020 · 1 min · 110 words · Khoa

How to search using regular expression in Xcode

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 search based on references, definitions, call hierarchy, and 🎉 regular expressions. Searching for regular expression gives us extra power when it comes to limit our search based on some criteria....

November 17, 2020 · 2 min · 352 words · Khoa

How to write to temporary file in Swift

Issue #697 Use temporaryDirectory from FileManager and String.write func writeTempFile(books: [Book]) -> URL { let url = FileManager.default.temporaryDirectory .appendingPathComponent(UUID().uuidString) .appendingPathExtension("txt") let string = books .map({ "book '\($0.url.path)'" }) .joined(separator: "\n") try? string.write(to: url, atomically: true, encoding: .utf8) return url }

November 15, 2020 · 1 min · 40 words · Khoa

How to use functions with default arguments in Swift

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=\(a) and c=\(c)") } init(a: Int = 1, b: Int = 2, c: Int = 3) { self.a = a self.b = b self.c = c print("Init with a\(a), b=\(b) and c=\(c)") } } let r1 = Robot(c: 10) let r2 = Robot(a: 5, c: 10) let r3 = Robot(a: 5, b: 7, c: 10) let r4 = Robot(a: 5) let r5 = Robot(b: 5) The log is...

November 14, 2020 · 1 min · 139 words · Khoa

How to check IAP Transaction error

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.error else { return } let nsError = error as NSError guard nsError.domain == SKError.errorDomain else { return } switch nsError.code { case SKError.clientInvalid.rawValue, SKError.paymentNotAllowed.rawValue: showAlert(text: "You are not allowed to make payment.") case SKError.paymentCancelled.rawValue: showAlert(text: "Payment has been cancelled....

November 14, 2020 · 1 min · 86 words · Khoa

How to use nested ObservableObject in SwiftUI

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() } struct Preferences { var opensAtLogin: Bool = true } final class PricingPlan: ObservableObject { @Published var isPro: Bool = true } SwiftUI for now does not work with nested ObservableObject, so if I pass Store to PricingView, changes in PricingPlan does not trigger view update in PricingView....

November 14, 2020 · 1 min · 212 words · Khoa

How to check dark mode in AppKit for macOS apps

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 = LightTheme() static var theme: Theme { let isDark = UserDefaults.standard.string(forKey: "AppleInterfaceStyle") == "Dark" return isDark ? dark : light } } Another way is to rely on appearance on NSView. You can quickly check via NSApp....

November 10, 2020 · 2 min · 216 words · Khoa

How to check dark mode with color scheme in SwiftUI

Issue #692 Use colorScheme environment, for now it has 2 cases dark and light struct MainView: View { @Environment(\.colorScheme) var colorScheme var body: some View { Text(colorScheme == .dark ? "Dark Mode" : "Light Mode") } }

November 10, 2020 · 1 min · 37 words · Khoa

How to avoid multiple match elements in UITests from iOS 13

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 UIToolbar, we need to specify the correct one to avoid multiple match errors let editButton = app.toolbars["EditArticle.Toolbar"].buttons["Edit"] Updated at 2020-11-04 10:02:29

November 4, 2020 · 1 min · 61 words · Khoa

How to use accessibility container in UITests

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 let viewLabel: UILabel let deleteButton: UIButton private func setupAccessibility() { contentView.isAccessibilityElement = true contentView.accessibilityLabel = "This article is written by Nobita on Dec 4th 2020" viewLabel.isAccessibilityElement = true // Default is false viewLabel.accessibilityTraits.insert(.button) // Treat UILabel as button to VoiceOver accessibilityElements = [contentView, viewLabel, deleteButton] isAccessibilityElement = false } } This works OK under Voice Over and Accessibility Inspector....

November 4, 2020 · 1 min · 134 words · Khoa

How to make full size content view in SwiftUI for macOS

Issue #689 func applicationDidFinishLaunching(_ aNotification: Notification) { // extend to title bar let contentView = ContentView() // .padding(.top, 24) // can padding to give some space .edgesIgnoringSafeArea(.top) // specify fullSizeContentView window = NSWindow( contentRect: NSRect(x: 0, y: 0, width: 800, height: 600), styleMask: [.titled, .closable, .miniaturizable, .texturedBackground, .resizable, .fullSizeContentView], backing: .buffered, defer: false ) window.center() window.setFrameAutosaveName("My App") // window.title = ... // no title // window.toolbar = NSToolbar() // use toolbar if wanted....

November 3, 2020 · 1 min · 135 words · Khoa

How to override styles in SwiftUI

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 down the view hierachy. struct MainView: View { var body: some View { HSplitView { ListView() RightView() } .foregroundColor(R.color.text) .background(R.color.background) } } This works great regardless of system light or dark mode, but in light mode it does not look good, as my designed theme is similar to dark mode....

October 31, 2020 · 2 min · 215 words · Khoa

When to use function vs property in Swift

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. Although the semantics are similar, there are some stylistic conventions on when to prefer one to another. Prefer a property over a function when the underlying algorithm: does not throw is cheap to calculate (or cached on the first run) returns the same result over invocations if the object state hasn’t changed Updated at 2020-10-27 09:56:38

October 27, 2020 · 1 min · 81 words · Khoa

How to use CoreData safely

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 viewContext together with newBackgroundContext attached to that NSPersistentContainer In Core Data, each context has a queue, except for viewContext using the DispatchQueue.main, and each NSManagedObject retrieved from 1 context is supposed to use within that context queue only, except for objectId property....

October 25, 2020 · 2 min · 299 words · Khoa

How to pass ObservedObject as parameter in SwiftUI

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 @State private var selectedTask: AnyTask init(store: ObservedObject<Store>) { _selectedTask = State(initialValue: tasks.first!) _store = store } } struct ParentView: View { @ObservedObject var store: Store var body: some View { ChildView(store: _store) }

October 24, 2020 · 1 min · 71 words · Khoa

How to do equal width in SwiftUI

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 flex-grow property. The same applies in vertical direct also. struct ContentView: View { var body: some View { HStack(spacing: 0) { VStack { Spacer() } .frame(maxWidth: .infinity) .background(Color.red) VStack { Spacer() } ....

October 23, 2020 · 1 min · 135 words · Khoa

What define a good developer

Issue #683 I always find myself asking this question “What define a good developer?” I ’ve asked many people and the answers vary, they ’re all correct in certain aspects Good programmer is someone who has a solid knowledge of the “how-to” both in theory and in practices. Understanding customer requirements clearly and having a vision to fulfill it through dedication and execution ! Good programmer is one who has in depth knowledge of one particular major and wide understanding of many thing else...

October 16, 2020 · 2 min · 221 words · Khoa