Skip to content

Instantly share code, notes, and snippets.

@KrisRJack
Last active February 22, 2025 13:41
Show Gist options
  • Save KrisRJack/b18cd9c66fdd06a5f43dc8913318b9dc to your computer and use it in GitHub Desktop.
Save KrisRJack/b18cd9c66fdd06a5f43dc8913318b9dc to your computer and use it in GitHub Desktop.
Helpful Swift Extensions
import UIKit
extension Array where Element == NSLayoutConstraint {
/// Activates each constraint in an array of `NSLayoutConstraint`.
///
/// Example usage: `[view.heightAnchor.constraint(equalToConstant: 30), view.widthAnchor.constraint(equalToConstant: 30)].activate()`
func activate() {
NSLayoutConstraint.activate(self)
}
/// Deactivates each constraint in an array of `NSLayoutConstraint`.
///
/// Example usage: `[view.heightAnchor.constraint(equalToConstant: 30), view.widthAnchor.constraint(equalToConstant: 30)].deactivate()`
func deactivate() {
NSLayoutConstraint.deactivate(self)
}
}
import Foundation
extension Dictionary {
@discardableResult
/// Combines the contents of a given dictionary into the current dictionary. If a `key` already exists, function will update the value.
/// - Parameter dictionary: New dictionary to merge into the current dictionary.
/// - Returns: Returns the current dictionary with merged `key: values` pairs.
mutating func merge(_ dictionary: [Key: Value]) -> [Key: Value] {
for (key, value) in dictionary {
updateValue(value, forKey: key)
}
return self
}
}
import UIKit
extension NSMutableAttributedString {
/**
Appends an attributed string to an `NSMutableAttributedString`
- Parameter text: Text intended to be formatted.
- Parameter font: Preferred `UIFont` of the attributed text.
- Parameter color: Preferred `UIColor` of the attributed text.
- Returns: Returns the `NSMutableAttributedString` with appended text.
Example usage:
```
let label = UILabel()
label.attributedText = NSMutableAttributedString()
.append("This text will be 12 point font and black. ", withFont: .systemFont(ofSize: 12), color: .black)
.append("This text will be 15 point font and gray.", withFont: .systemFont(ofSize: 15), color: .gray)
```
*/
@discardableResult
func append(_ text: String, withFont font: UIFont, color: UIColor = .label) -> NSMutableAttributedString {
let attrs: [NSAttributedString.Key: Any] = [.font: font, .foregroundColor: color]
let string = NSMutableAttributedString(string:text, attributes: attrs)
append(string)
return self
}
}
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0
import UIKit
extension UIColor {
// Example usage:
// let someColor = UIColor(rgb: 0xFC707D)
public convenience init(rgb: Int) {
self.init(
red: CGFloat((rgb & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgb & 0x00FF00) >> 8) / 255.0,
blue: CGFloat((rgb & 0x0000FF) >> 0) / 255.0,
alpha: 1
)
}
// Example usage:
// let someColor = UIColor(rgba: 0xEF445626)
// Hexadecimal color code for transparency: https://gist.github.com/lopspower/03fb1cc0ac9f32ef38f4
public convenience init(rgba: UInt64) {
self.init(
red: CGFloat((rgba & 0xFF000000) >> 24) / 255.0,
green: CGFloat((rgba & 0x00FF0000) >> 16) / 255.0,
blue: CGFloat((rgba & 0x0000FF00) >> 8) / 255.0,
alpha: CGFloat((rgba & 0x000000FF) >> 0) / 255.0
)
}
}
import UIKit
extension UIView {
/// Adds multiple views to the end of the receiver’s list of subviews.
/// - Parameter subviews: Collection of subviews to be added to view
func addSubviews(_ subviews: UIView...) {
subviews.forEach ({
$0.translatesAutoresizingMaskIntoConstraints = false
addSubview($0)
})
}
/// Makes the edge constraints (`topAnchor`, `bottomAnchor`, `leadingAnchor`, `trailingAnchor`) of a view equaled to the edge constraints of another view.
/// - Parameters:
/// - view: The view that we are constraining the current view's edges to.
/// For example : `currentView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true`
/// - padding: An equal amount of spacing between each edge of the current view and `view`.
/// In a superview and subview relationship, `padding` is the equal space that surrounds the subview inside of the superview.
func edges(equalTo view: UIView, padding: CGFloat = 0) {
view.addSubview(self)
translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
topAnchor.constraint(equalTo: view.topAnchor, constant: padding),
bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -padding),
leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: padding),
trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -padding)
])
}
/// Makes the edge constraints (`topAnchor`, `bottomAnchor`, `leadingAnchor`, `trailingAnchor`) of a view equaled to the edge constraints of another view.
/// - Parameters:
/// - view: The view that we are constraining the current view's edges to.
/// For example : `currentView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true`
/// - inset: Edge inset distance. Bottom and right edge inset values are multiplied by -1 for convenience.
func edges(equalTo view: UIView, inset: UIEdgeInsets) {
view.addSubview(self)
translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
topAnchor.constraint(equalTo: view.topAnchor, constant: inset.top),
bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -inset.bottom),
leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: inset.left),
trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -inset.right)
])
}
/// Makes the edge constraints (`topAnchor`, `bottomAnchor`, `leadingAnchor`, `trailingAnchor`) of a view equaled to the layout margins of another view.
/// - Parameters:
/// - view: The view that we are constraining the current view's edges to.
/// For example : `currentView.topAnchor.constraint(equalTo: view.layoutMarginsGuide.topAnchor).isActive = true`
/// - padding: An equal amount of spacing between each edge of the current view and `view`.
/// In a superview and subview relationship, `padding` is the equal space that surrounds the subview inside of the superview.
func edges(equalToLayoutMarginIn view: UIView, padding: CGFloat = 0) {
view.addSubview(self)
translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
topAnchor.constraint(equalTo: view.layoutMarginsGuide.topAnchor, constant: padding),
bottomAnchor.constraint(equalTo: view.layoutMarginsGuide.bottomAnchor, constant: -padding),
leadingAnchor.constraint(equalTo: view.layoutMarginsGuide.leadingAnchor, constant: padding),
trailingAnchor.constraint(equalTo: view.layoutMarginsGuide.trailingAnchor, constant: -padding)
])
}
/// Makes the edge constraints (`topAnchor`, `bottomAnchor`, `leadingAnchor`, `trailingAnchor`) of a view equaled to the safe area of another view.
/// - Parameters:
/// - view: The view that we are constraining the current view's edges to.
/// For example : `currentView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true`
/// - padding: An equal amount of spacing between each edge of the current view and `view`.
/// In a superview and subview relationship, `padding` is the equal space that surrounds the subview inside of the superview.
func edges(equalToSafeAreaIn view: UIView, padding: CGFloat = 0) {
view.addSubview(self)
translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: padding),
bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -padding),
leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: padding),
trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -padding)
])
}
/// Makes the center x and y anchors of a view equaled to the center x and y anchors of another view.
/// - Parameter view: The view that we're constraining the current view's center anchors to.
/// For example : `currentView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true`
func center(equalTo view: UIView) {
view.addSubview(self)
translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
centerXAnchor.constraint(equalTo: view.centerXAnchor),
centerYAnchor.constraint(equalTo: view.centerYAnchor)
])
}
/// Adds corner radius to specified corners. If no corners are specified, adds corner radius to all corners.
/// - Parameters:
/// - cornerRadius: The radius to use when drawing rounded corners for the layer’s background.
/// - corners: Array of corners that will to apply corner radius. Passing `nil` or an empty array will add corner radius to all corners. Function will ignore reference to `UIRectCorner.allCorners`.
func cornerRadius(_ cornerRadius: CGFloat, corners: [UIRectCorner]? = nil) {
guard let corners = corners, !corners.isEmpty else {
layer.cornerRadius = cornerRadius
return
}
var maskedCorners: CACornerMask = []
for corner in corners {
switch corner {
case .topLeft:
maskedCorners.update(with: .layerMinXMinYCorner)
case .topRight:
maskedCorners.update(with: .layerMaxXMinYCorner)
case .bottomLeft:
maskedCorners.update(with: .layerMinXMaxYCorner)
case .bottomRight:
maskedCorners.update(with: .layerMaxXMaxYCorner)
default:
continue
}
}
layer.cornerRadius = cornerRadius
layer.maskedCorners = maskedCorners
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment