FHExtensions

Xcode Build Version License Tweet

一些有用的 Foundation 和 UIKit 扩展。

会随着时间推移而扩展。

系统要求

安装

Swift Package Manager

将以下内容添加到你的 Package.swift 文件的依赖项中

.package(url: "https://github.com/FelixHerrmann/FHExtensions.git", from: "x.x.x")

手动

下载 Sources 文件夹并将其拖到你的项目中。

用法

Array

subscript(safe index: Index) -> Element?

此下标检查索引是否在范围内。

像这样获取数组值

let array = [0, 1, 2]

print(array[1]) // 1
print(array[safe: 1]) // Optional(1)

print(array[3]) // Fatal error: Index out of range
print(array[safe: 3]) // nil

安全地设置数组值也像这样

var array = [0, 1, 2]

array[safe: 2] = 3
print(array) // [0, 1, 3]

array[safe: 3] = 4
print(array) // [0, 1, 3]

Bundle

versionNumber, buildNumber

Info.plist 字典中 CFBundleShortVersionStringCFBundleVersion 键的值。

CGRect

坐标:x, y, top, bottom, left, right, center

CGRect 坐标的便捷属性。

这些属性也包含 setter,它们将完全重新创建 frame。

Date

init?(_:_:_:hour:minute:second:timeZone)

此初始化器可以通过日期组件创建 Date 对象。如果找不到与组件匹配的日期,则可能会失败。

let date = Date(23, 2, 1999)
let dateWithTimeAndTimeZone = Date(23, 2, 1999, hour: 9, minute: 41, second: 0, timeZone: TimeZone(secondsFromGMT: 0))

时间值和时区是可选的。

JSONDecoder

DateDecodingStrategy.iso8601withFractionalSeconds

具有小数秒的 ISO 8601 DateDecodingStrategy。类似 1999-02-23T09:41:00.000Z 的格式将适用于解码器。

JSONEncoder

DateEncodingStrategy.iso8601withFractionalSeconds

具有小数秒的 ISO 8601 DateEncodingStrategy。类似 1999-02-23T09:41:00.000Z 的格式将是编码器的输出。

String

capitalizedFirst

字符串的副本,其中首字母大写。

UIColor

RGB: red, green, blue, alpha

这些属性基于 getRed(_:green:blue:alpha) 方法。

init?(hex:)

此初始化器可以通过十六进制字符串创建 UIColor 对象。如果字符串格式不正确,则可能会失败。它允许带或不带 alpha 的十六进制字符串,哈希符号不是必需的,并且大小写无关紧要。

let yellow: UIColor? = UIColor(hex: "#ffff00ff")

createHex(alpha:hashSymbol:)

此方法从颜色实例创建十六进制字符串。

let yellow = UIColor(red: 1, green: 1, blue: 0, alpha: 1)
let hexString: String = yellow.createHex(alpha: true)
print(hexString) // "#ffff00ff"

UIDevice

modelIdentifier

使用 UIDevice.current.modelIdentifier 你可以获取当前设备的型号标识符,类型为 String

这也适用于 Mac (Catalyst)。

UIDirectionalPanGestureRecognizer

UIPanGestureRecognizer 的具体子类,如果指定的方向不匹配,则取消手势。

let directionalPanRecognizer = UIDirectionalPanGestureRecognizer(target: self, action: #selector(handlePan(_:)))
directionalPanRecognizer.direction = .vertical
view.addGestureRecognizer(directionalPanRecognizer)

在触控板和鼠标事件上不会调用 touchesMoved(_:with:)。如果 allowedScrollTypesMask 设置为 UIScrollTypeMask.discreteUIScrollTypeMask.continuous,请改用 UIGestureRecognizerDelegate.gestureRecognizerShouldBegin(_:)

NSColor

RGB: red, green, blue, alpha

这些属性基于 getRed(_:green:blue:alpha) 方法。

init?(hex:)

此初始化器可以通过十六进制字符串创建 NSColor 对象。如果字符串格式不正确,则可能会失败。它允许带或不带 alpha 的十六进制字符串,哈希符号不是必需的,并且大小写无关紧要。

let yellow: NSColor? = NSColor(hex: "#ffff00ff")

createHex(alpha:hashSymbol:)

此方法从颜色实例创建十六进制字符串。

let yellow = NSColor(red: 1, green: 1, blue: 0, alpha: 1)
let hexString: String = yellow.createHex(alpha: true)
print(hexString) // "#ffff00ff"

许可

FHExtensions 在 MIT 许可下可用。有关更多信息,请参阅 LICENSE 文件。