How to change caret color of NSTextField in macOS

Issue #588 class FocusAwareTextField: NSTextField { var onFocus: () -> Void = {} var onUnfocus: () -> Void = {} override func becomeFirstResponder() -> Bool { onFocus() let textView = window?.fieldEditor(true, for: nil) as? NSTextView textView?.insertionPointColor = R.nsColor.action return super.becomeFirstResponder() } override func resignFirstResponder() -> Bool { onUnfocus() return super.resignFirstResponder() } }

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

How to make TextView in SwiftUI for macOS

Issue #587 Use NSTextVIew From https://github.com/twostraws/ControlRoom/blob/main/ControlRoom/NSViewWrappers/TextView.swift import SwiftUI /// A wrapper around NSTextView so we can get multiline text editing in SwiftUI. struct TextView: NSViewRepresentable { @Binding private var text: String private let isEditable: Bool init(text: Binding<String>, isEditable: Bool = true) { _text = text self.isEditable = isEditable } init(text: String) { self.init(text: Binding<String>.constant(text), isEditable: false) } func makeNSView(context: Context) -> NSScrollView { let text = NSTextView() text.backgroundColor = isEditable ?...

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

How to use custom font in SwiftUI

Issue #586 In macOS Add fonts to target. In Info.plist, just need to specify font locations, most of the time they are at Resources folder ATSApplicationFontsPath (String - macOS) identifies the location of a font file or directory of fonts in the bundle’s Resources directory. If present, macOS activates the fonts at the specified path for use by the bundled app. The fonts are activated only for the bundled app and not for the system as a whole....

January 28, 2020 · 2 min · 265 words · Khoa

How to test drag and drop in UITests

Issue #583 In UITests, we can use press from XCUIElement to test drag and drop let fromCat = app.buttons["cat1"].firstMatch let toCat = app.buttons["cat2"] let fromCoordinate = fromCat.coordinate(withNormalizedOffset: CGVector(dx: 0, dy: 0)) let toCoordinate = toCat.coordinate(withNormalizedOffset: CGVector(dx: 0, dy: -0.5)) fromCoordinate.press(forDuration: 1, thenDragTo: toCoordinate) and then take screenshot let screenshot = XCUIScreen.main.screenshot() let attachment = XCTAttachment(screenshot: screenshot) attachment.lifetime = .keepAlways attachment.name = name add(attachment) Screenshot capturing happens after the action, so it may be too late....

January 23, 2020 · 1 min · 167 words · Khoa

How to set corner radius in iOS

Issue #582 Use View Debugging Run on device, Xcode -> Debug -> View debugging -> Rendering -> Color blended layer On Simulator -> Debug -> Color Blended Layer Corner radius https://twitter.com/timoliverau/status/1135999854176395264 Okay. Talked to a Core Animation engineer again: cornerRadius was deliberately improved in Metal so it could be used everywhere. Using a bitmap is WAY heavier in terms of memory and performance. CALayer maskLayer is still heavy. https://developer.apple.com/documentation/quartzcore/calayer/1410818-cornerradius Setting the radius to a value greater than 0....

January 22, 2020 · 4 min · 790 words · Khoa

How to deal with Swift slow compile time

Issue #581 Read more https://engineering.circle.com/swift-compiler-performance-tips-and-tricks-e86a53a5b42a https://swiftrocks.com/reducing-ios-build-times-by-using-interface-targets.html

January 21, 2020 · 1 min · 6 words · Khoa

How to work with SceneDelegate in iOS 12

Issue #580 Events open url https://stackoverflow.com/questions/58624786/method-applicationopenurloptions-is-not-called Implement scene(_:openURLContexts:) in your scene delegate. If the URL launches your app, you will get scene(_:willConnectTo:options:) instead and it’s in the options. life cycle https://stackoverflow.com/questions/56508764/app-delegate-methods-arent-being-called-in-ios-13 Here’s how it works: If you have an “Application Scene Manifest” in your Info.plist and your app delegate has a configurationForConnectingSceneSession method, the UIApplication won’t send background and foreground lifecycle messages to your app delegate. That means the code in these methods won’t run:...

January 20, 2020 · 2 min · 300 words · Khoa

How to handle radio group for NSButton

Issue #579 Use same action, or we can roll our own implementation An NSButton configured as a radio button (with the -buttonType set to NSRadioButton), will now operate in a radio button group for applications linked on 10.8 and later. To have the button work in a radio group, use the same -action for each NSButton instance, and have the same superview for each button. When these conditions are met, checking one button (by changing the -state to 1), will uncheck all other buttons (by setting their -state to 0)....

January 17, 2020 · 1 min · 111 words · Khoa

How to specify locale in Swift

Issue #578 Locale Read Language and Locale IDs zh-Hans_HK [language designator]-[script designator]_[region designator] Language IDs A language ID identifies a language used in many regions, a dialect used in a specific region, or a script used in multiple regions. To specify a language used in many regions, use a language designator by itself. To specify a specific dialect, use a hyphen to combine a language designator with a region designator. To specify a script, combine a language designator with a script designator....

January 14, 2020 · 2 min · 364 words · Khoa

How to workaround URLSession issue in watchOS 6.1.1

Issue #577 https://stackoverflow.com/questions/59724731/class-avassetdownloadtask-is-implemented-in-both-cfnetwork-and-avfoundation objc[45250]: Class AVAssetDownloadTask is implemented in both /Applications/Xcode.app/Contents/Developer/Platforms/WatchOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/watchOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/CFNetwork.framework/CFNetwork (0x4ddd0ec) and /Applications/Xcode.app/Contents/Developer/Platforms/WatchOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/watchOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/AVFoundation.framework/AVFoundation (0x16aea494). One of the two will be used. Which one is undefined. objc[45250]: Class AVAssetDownloadURLSession is implemented in both /Applications/Xcode.app/Contents/Developer/Platforms/WatchOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/watchOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/CFNetwork.framework/CFNetwork (0x4dddd44) and /Applications/Xcode.app/Contents/Developer/Platforms/WatchOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/watchOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/AVFoundation.framework/AVFoundation (0x16aea4bc). One of the two will be used. Which one is undefined. Then URLSession stops working. 2020-01-13 22:50:12.430920+0100 MyAppWatch WatchKit Extension[45250:2099229] Task <3CECDE81-59B9-4EDE-A4ED-1BA173646037>.<1> finished with error [-999] Error Domain=NSURLErrorDomain Code=-999 "cancelled" UserInfo={NSErrorFailingURLKey=https://myapp.com/def.json, NSErrorFailingURLStringKey=https://myapp.com/def.json, NSLocalizedDescription=cancelled} The workaround is to remove Combine based API, and use completion block....

January 13, 2020 · 1 min · 165 words · Khoa

How to generate XCTest test methods

Issue #576 Code See Spek Override testInvocations to specify test methods https://developer.apple.com/documentation/xctest/xctestcase/1496271-testinvocations Returns an array of invocations representing each test method in the test case. Because testInvocations is unavailable in Swift, we need to use ObjC #import "include/SpekHelperTestCase.h" @implementation SpekHelperTestCase - (instancetype)init { self = [super initWithInvocation: nil]; return self; } + (NSArray<NSInvocation *> *)testInvocations { NSArray<NSString *> *selectorStrings = [self spekGenerateTestMethodNames]; NSMutableArray<NSInvocation *> *invocations = [NSMutableArray arrayWithCapacity:selectorStrings.count]; for (NSString *selectorString in selectorStrings) { SEL selector = NSSelectorFromString(selectorString); NSMethodSignature *signature = [self instanceMethodSignatureForSelector:selector]; NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature]; invocation....

January 12, 2020 · 2 min · 215 words · Khoa

How to use ObjC in Swift Package Manager

Issue #575 Create Objc target http://ankit.im/swift/2016/05/21/creating-objc-cpp-packages-with-swift-package-manager/ Check runtime Check for example _runtime(_ObjC) or os(macOS if you plan to use platform specific feature https://github.com/Quick/Quick/blob/master/Package.swift https://github.com/Quick/Quick/pull/687/files For example, in test we use XCTest which is run via Xcode and is a macOS framework, so we need to check for os(macOS) Note that in Objc framework, the header files must be in include folder targets: { var targets: [Target] = [ .testTarget( name: "QuickTests", dependencies: [ "Quick", "Nimble" ], exclude: [ "QuickAfterSuiteTests/AfterSuiteTests+ObjC....

January 11, 2020 · 1 min · 115 words · Khoa

How to expression cast type in lldb in Swit

Issue #574 expr -l Swift -- import UIKit expr -l Swift -- let $collectionView = unsafeBitCast(0x7fddd8180000, to: UICollectionView.self) expr -l Swift -- $collectionView.safeAreaInsets

January 10, 2020 · 1 min · 23 words · Khoa

How to disable implicit decoration view animation in UICollectionView

Issue #569 From documentation https://developer.apple.com/documentation/uikit/uicollectionviewlayout/1617726-initiallayoutattributesforappear This method is called after the prepare(forCollectionViewUpdates:) method and before the finalizeCollectionViewUpdates() method for any decoration views that are about to be inserted. Your implementation should return the layout information that describes the initial position and state of the view. The collection view uses this information as the starting point for any animations. (The end point of the animation is the view’s new location in the collection view....

January 6, 2020 · 1 min · 179 words · Khoa

How to make simple tracker via swizzling in Swift

Issue #568 Code EasyTracker Swizzle viewDidAppear https://github.com/onmyway133/EasyTracker/blob/master/Sources/Trackers.swift import UIKit var mapping: [String: (UIViewController) -> Void] = [:] var hasSwizzled = false public func track<T: UIViewController>(_ type: T.Type, block: @escaping (T) -> Void) { let original = #selector(UIViewController.viewDidAppear(_:)) let swizled = #selector(UIViewController.trackers_viewDidAppear(_:)) if !hasSwizzled { swizzle(kClass: UIViewController.self, originalSelector: original, swizzledSelector: swizled) hasSwizzled = true } mapping[NSStringFromClass(type)] = { controller in if let controller = controller as? T { block(controller) } } } extension UIViewController { func trackers_viewDidAppear(_ animated: Bool) { trackers_viewDidAppear(animated) let string = NSStringFromClass(type(of: self)) mapping[string]?...

January 4, 2020 · 1 min · 158 words · Khoa

How to make simple adapter for delegate and datasource for UICollectionView and UITableView

Issue #567 Code Upstream Make open Adapter https://github.com/onmyway133/Upstream import UIKit public protocol AdapterDelegate: class { /// Apply model to view func configure(model: Any, view: UIView, indexPath: IndexPath) /// Handle view selection func select(model: Any) /// Size the view func size(model: Any, containerSize: CGSize) -> CGSize } /// Act as DataSource and Delegate for UICollectionView, UITableView open class Adapter: NSObject, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UITableViewDataSource, UITableViewDelegate { public var sections: [Section] = [] public weak var collectionView: UICollectionView?...

January 4, 2020 · 5 min · 963 words · Khoa

How to make progress HUD in Swift

Issue #566 Code FantasticDisplay Create a container that has blur effect public class HUDContainer: UIVisualEffectView, AnimationAware { private let innerContentView: UIView & AnimationAware public let label = UILabel() public var text: String? { didSet { label.text = text label.sizeToFit() label.isHidden = text == nil } } public init(contentView: UIView & AnimationAware) { self.innerContentView = contentView super.init(effect: UIBlurEffect(style: .light)) self.contentView.addSubview(innerContentView) self.contentView.addSubview(label) innerContentView.pinEdgesToSuperview() configure() } public required init?(coder aDecoder: NSCoder) { fatalError() } public func configure() { layer....

January 4, 2020 · 4 min · 682 words · Khoa

How to specify year in date formatter in Swift

Issue #565 Serious Security: The decade-ending Y2K bug that wasnt Challenges of DateFormatters

January 3, 2020 · 1 min · 13 words · Khoa

How to build static site using Publish

Issue #564 Code https://github.com/JohnSundell/publish Example https://github.com/pumaswift/pumaswift.github.io Steps Step 1: Create executable swift package init --type executable Step 2: Edit package // swift-tools-version:5.1 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "PumaSwiftWeb", dependencies: [ .package(url: "https://github.com/johnsundell/publish.git", from: "0.1.0") ], targets: [ .target( name: "PumaSwiftWeb", dependencies: [ "Publish" ] ) ] ) Step 3: Double click Package.swift, Xcode opens that in a generated project Step 4: Declare website....

January 2, 2020 · 1 min · 166 words · Khoa

How to use Timer and RunLoop in Swift

Issue #562 Run Timer in command line application Timer.scheduledTimer(withTimeInterval: seconds, repeats: false, block: { _ in completion(.success(())) }) RunLoop.current.run() Read more https://www.hackingwithswift.com/articles/117/the-ultimate-guide-to-timer https://learnappmaking.com/timer-swift-how-to/

January 1, 2020 · 1 min · 23 words · Khoa