Skip to content

Instantly share code, notes, and snippets.

@dagronf
dagronf / ArbitraryAnimationLayer.swift
Last active July 13, 2019 04:42
A layer implementation to connect any item to an animation (swift)
/// A simple layer class to expose an animation progress for a CAAnimation.
public class ArbitraryAnimationLayer: CALayer {
static let KeyPath: String = "progress"
override init() {
super.init()
}
var progressCallback: ((CGFloat) -> Void)?
@dagronf
dagronf / synchronized.swift
Last active October 17, 2023 12:33
Swift method to provide the equivalent of `@synchronised` from objc
/// Provide the equivalent of @synchronised on objc
private func synchronized<T>(_ lock: AnyObject, _ body: () throws -> T) rethrows -> T {
objc_sync_enter(lock)
defer { objc_sync_exit(lock) }
return try body()
}
/// Simple lockable class
class Lockable {
private var lockable: AnyObject
@dagronf
dagronf / AutoselectOnFocusTextField.swift
Last active August 16, 2019 07:42
NSTextField overload that automatically selects all text within the field when focussed.
import Cocoa
class AutoselectOnFocusTextField: NSTextField {
override func becomeFirstResponder() -> Bool {
guard super.becomeFirstResponder() else {
return false
}
if let editor = self.currentEditor() {
editor.perform(#selector(selectAll(_:)), with: self, afterDelay: 0)
}
@dagronf
dagronf / ShowSystemPreferencePanes.swift
Last active April 29, 2024 17:21
macOS: Open system preferences at a specified pane using Swift (or Objective-C) using x-apple.systempreferences
// Applescript: tell application "System Preferences" to get anchors of current pane
// Result:
// { anchor "Privacy_Reminders" of pane id "com.apple.preference.security" of application "System Preferences",
// anchor "Privacy_SystemServices" of pane id "com.apple.preference.security" of application "System Preferences",
// anchor "Privacy_Calendars" of pane id "com.apple.preference.security" of application "System Preferences",
// anchor "Firewall" of pane id "com.apple.preference.security" of application "System Preferences",
// anchor "Privacy_Assistive" of pane id "com.apple.preference.security" of application "System Preferences",
// anchor "Privacy_LinkedIn" of pane id "com.apple.preference.security" of application "System Preferences",
// anchor "Privacy_Accessibility" of pane id "com.apple.preference.security" of application "System Preferences",
@dagronf
dagronf / UITextView+popover.swift
Created September 6, 2019 23:31
UITextView add other items to selection popover
let menuController = UIMenuController.shared
let item1 = UIMenuItem(title: "Item 1", action: #selector(performItem1))
let item2 = UIMenuItem(title: "Item 2", action: #selector(performItem2))
menuController.menuItems = [item1, item2]
menuController.setMenuVisible(true, animated: true)
@dagronf
dagronf / UIColor+contrasting.swift
Last active September 16, 2019 06:27
Get a contrasting UIColor for a background UIColor that could be used for text (for eg.)
import UIKit
extension UIColor {
private struct ColorComponents {
var r: CGFloat = 0.0
var g: CGFloat = 0.0
var b: CGFloat = 0.0
var a: CGFloat = 0.0
}
@dagronf
dagronf / XCTTest+extensions.swift
Created September 21, 2019 22:28
XCTTest helper function for unwrapping optionals within a test case using try/catch. Makes for a much cleaner test
/// From https://www.rightpoint.com/rplabs/xctassert-optional-unwrapping
// Usage :-
//
// class TestCaseUnwrap: XCTestCase {
// func testUnwrap() throws {
// let string: String? = nil
// let newString = try AssertNotNilAndUnwrap(string)
// XCTAssert(newString.lengthOfBytes(using: .utf8) > 0)
// }
@dagronf
dagronf / Unique.swift
Last active October 4, 2019 23:24
SWIFT: Return the unique elements of a sequence, both using the Equatable protocol and by using a predicate
public extension Sequence {
/// Return unique elements in an array, given a predicate
/// - Parameter includeElement: block determining whether the elements are equivalent
func unique(_ predicate: (_ lhs: Element, _ rhs: Element) -> Bool) -> [Element] {
var results = [Element]()
forEach { (element) in
if results.filter( { predicate(element, $0) }).count == 0 {
results.append(element)
}
}
@dagronf
dagronf / With.swift
Created October 7, 2019 23:42
SWIFT: Perform an immediate transform of a given subject
/// Perform an immediate `transform` of a given `subject`. The `transform`
/// function may just mutate the given `subject`, or replace it entirely.
///
/// ```
/// let oneAndTwo = with([1]) {
/// $0.append(2)
/// }
/// ```
///
/// - Parameters:
@dagronf
dagronf / FileManager+UniqueFileURL.swift
Last active November 27, 2019 01:50
An extension on FileManager in Swift that returns a unique file url given a 'base' filename and a destination folder url
extension FileManager {
/// Returns a unique URL for the specified filename and directory. Not thread safe
/// - Parameter filename: the `lastPathComponent` of a URL (for example, `IMG-2002.jpg`)
/// - Parameter directory: the directory in which to check
/// - Returns: a unique URL
static func UniqueFileURL(for filename: String, in directory: URL) -> URL {
// Filename is lastPathComponent
let fm = FileManager.default