Khoa Pham
Khoa Pham

Ohayo

Swift Discovery

Discover all the tech

Featured

My year in review 2020

Issue #715

I remember this time last year in December 2019, I spent almost every single bit of my free time on Puma because I want a Swift friendly version of fastlane that suits my need and leverages Swift 5 features.

Here’s my review of my …

How to scroll to element in React

Issue #648

In a similar fashion to plain old javascript, note that href needs to have valid hash tag, like #features

<a
    href='#features'
    onClick={() => {
        const options = {
            behavior: 'smooth'
        } …

How to use emotion for inline css in React

Issue #647

emotion can be used in framework agnostic or with React. To use with React, follow https://emotion.sh/docs/introduction#react

npm i @emotion/core

Note that you must have /** @jsx jsx */ at the top of the file, and the unused jsx in import …

How to test DispatchQueue in Swift

Issue #646

Sync the DispatchQueue

Pass DispatchQueue and call queue.sync to sync all async works before asserting

Use mock

Use DispatchQueueType and in mock, call the work immediately

import Foundation

public protocol DispatchQueueType {
    func …

How to use webpack to bundle html css js

Issue #645

Install webpack

npm init
npm install webpack webpack-cli --save-dev
vim webpack.config.js
module.exports = {
    entry: "./index.js",
    mode: 'production',
    output: {
        filename: "./index.js"
    }
}

To …

How to assert asynchronously in XCTest

Issue #644

import XCTest

extension XCTestCase {
    /// Asynchronously assertion
    func XCTAssertWait(
        timeout: TimeInterval = 1,
        _ expression: @escaping () -> Void,
        _: String = "",
        file _: StaticString = …

How to make simple filter menu in css

Issue #643

Use material icons

<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
div#filter-container {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: …

How to make simple grid gallery in css

Issue #642

Specify container with flex-wrap and justify-content, and item with float: left

div.cards {
  display: flex;
  justify-content: center;
  flex-direction: row;
  flex-wrap: wrap;
  margin-top: 10%;
}

div.card {
  overflow: hidden;
  float: …

How to add independent page in hexo

Issue #641

Create a new page

hexo new page mydemo

Remove index.md and create index.html, you can reference external css and js in this index.html. Hexo has hexo new page mydemo --slug but it does not support page hierarchy

Specify no layout so it is …

How to use async function as parameter in TypeScript

Issue #640

async function useCache(
    collectionName: string, 
    key: string, 
    response: functions.Response<any>, 
    fetch: () => Promise<any>
): Promise<any> {
    const existing = await db.collection(collectionName). …

How to format percent in Swift

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. …

How to declare commands in Xcode extensions

Issue #638

Use commandDefinitions in XCSourceEditorExtension.

import Foundation
import XcodeKit

class SourceEditorExtension: NSObject, XCSourceEditorExtension {
    func extensionDidFinishLaunching() {

    }
    
    var commandDefinitions: [[ …

How to declare commands in Xcode extenstions

Issue #638

Use commandDefinitions in XCSourceEditorExtension.

import Foundation
import XcodeKit

class SourceEditorExtension: NSObject, XCSourceEditorExtension {
    func extensionDidFinishLaunching() {

    }
    
    var commandDefinitions: [[ …

How to disable ring type in TextField in SwiftUI

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< …

How to handle enter key in NSTextField

Issue #635

textField.delegate = self
NSTextFieldDelegate

func control(_ control: NSControl, textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool {
    if (commandSelector == #selector(NSResponder.insertNewline(_:))) {
        // …

How to decode with default case for enum in Swift

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. …

How to conditionally apply modifier in SwiftUI

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 …

How to toggle with animation in SwiftUI

Issue #632

Use Group

private func makeHeader() -> some View {
    Group {
        if showsSearch {
            SearchView(
                onSearch: onSearch
            )
            .transition(.move(edge: .leading))
        } else { …

How to use background in iOS

Issue #631

beginBackgroundTask

https://developer.apple.com/documentation/uikit/app_and_environment/scenes/preparing_your_ui_to_run_in_the_background/extending_your_app_s_background_execution_time

When your app moves to the background, the system …

How to show context popover from SwiftUI for macOS

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 : …

How to make segmented control in SwiftUI for macOS

Issue #629

Use Picker with SegmentedPickerStyle.

Picker(selection: $preferenceManager.preference.display, label: EmptyView()) {
    Image("grid")
        .resizable()
    .padding()
        .tag(0)
    Image("list")
        .resizable …

Khoa Pham

Hello, I’m Khoa

I’m a thinker and storyteller with a passion for exploring the intersection of creativity and technology

🧑‍💻 I love crafting high quality and useful apps
🔥 I love open source. My GitHub open source has 2.3k followers with packages that are integrated by 45k+ apps and over 3.4m+ downloads on CocoaPods.
✍️ I write here on my blog and on Medium, which has over 2.7k+ followers with tons of articles and 90k+ monthly views.
🖥 Follow me for sharings about Swift, SwiftUI, iOS and macOS development.
Hei