RDExtensionsSwift
RDExtensionsSwift 是 Swift 的一些有用扩展集合。
它使您开发 iOS 应用程序更加容易,并允许您编写更简单、更干净的代码。
内容
- 运算符重载
- Int 和 Int64 扩展
- Double、Float 和 CGFloat 扩展
- Bool 扩展
- Character 扩展
- String 扩展
- CGRect 扩展
- CMTime 扩展
- AVPlayerItem 扩展
- Array 和 Collection 扩展
- NSObject 扩展
- NSData 扩展
- NSDate 扩展
- NSDictionary 扩展
- NSURL 扩展
- PHAsset 扩展
- UIColor 扩展
- UIImage 扩展
- UINib 扩展
- UIView 扩展
- UIScrollView 扩展
- UIAlertView 扩展
- UIAlertController 扩展
- UIImageView 扩展
- UILabel 扩展
- UITextField 扩展
- UITextView 扩展
- UIViewController 扩展
- MPMoviePlayerController 扩展
运算符重载
您可以在不进行类型转换的情况下,将其他类型变量相加、相减、相乘、相除
let intNumber : Int = 10
let doubleNumber : Double = 5.5
let sum = intNumber + doubleNumber // sum value will be 15.5 Double
您可以将两个数组连接到第一个数组中
var array1 = [1, 2, 3]
let array2 = [4, 5, 6]
array1 += array2 // array1 value will be [1, 2, 3, 4, 5, 6]
整型和 Int64 扩展
将 int 转换为 ASCII 字符
97.toCharacter // value will be Character("A")
将 int 转换为字符串
123.toString // value will be String("123")
双精度浮点数和 CGFloat 扩展
将 Double 转换为字符串
let d = 123.456789
d.toString = "123.456789"
d.toString() = "123.45"
d.toString(4) = "123.4567" // where 4 is the number of characters after point
布尔型扩展
将布尔型转换为字符串和 Int
true.toString = "true"
false.toString = "false"
true.toInt = 1
false.toInt = 0
字符扩展
将字符转换为 Int(ASCII 表转换)
Character("A").toInt = 97
字符串扩展
将字符串转换为布尔型、Int、Double、CGFloat、HTTP URL、文件路径等...
("TRUE" | "True" | "true" | "YES" | "Yes" | "yes" | "1").toBool = true
("FALSE" | "False" | "false" | "NO" | "No" | "no" | "0").toBool = false
"123".toInt = 123
"123".toDouble = Double(123)
"123".toCGFloat = CGFloat(123)
"http://example.com/".toHttpURL = NSURL(sting: "http://example.com/")
"/path/to/file".toFileURL = NSURL(fileURLWithPath: "/path/to/file")
获取字符串长度
"123456789".length = 9
从字符串中去除空白字符
" 1 2 3 4 ".condenseWhiteSpace() = "1 2 3 4"
子字符串 To、From、From 到 To、范围
"0123456789".substringTo(5) = "01234"
"0123456789".substringFrom(5) = "56789"
"0123456789".substring(4, to: 7) = "456"
获取子字符串的范围
"0123456789".range("456") = NSRange(4, 3)
追加路径组件
"/folder/subfolder".stringByAppendingPathComponent("subfolder2/file") = "/folder/subfolder/subfolder2/file"
使用 NSRange 替换字符并返回值
"0123456789".stringByReplacingCharactersInRange(NSMakeRange(4, 3), withString: "000") = "0123000789"
使用 NSRange 替换字符
var string = "0123456789"
string.replaceCharactersInRange(NSMakeRange(4, 3), withString: "000") // string value will be "0123000789"
使用正则表达式进行验证
"#hashtag".validate("#.*") = true
"#hashtag".validate("#.*")
查找正则表达式匹配
do
{
let array = try "name1 name2 name3".matches("[a-zA-Z]{4}[0-9]{1}") // array value will be ["name1", "name2", "name3"]
}
catch
{
// handle an error here
}
查找值对应的范围
do
{
let array = try "name1 name2 name3".ranges("name") // array value will be [NSMakeRange(0, 4), NSMakeRange(6, 4), NSMakeRange(12, 4)]
}
catch
{
// handle an error here
}
通过下标获取字符和子字符串
"123"[1] = Character("2") // Character value
"123"[1] = "2" // String value
"123"[NSMakeRange(1, 1)] = "2"
"123"[NSMakeRange(1, 1).toRange()!] = "2"
获取矩形内的可见字符串
let string = "string value here ..."
string.visibleStringInRect(CGRectValue, font: UIFontValue)
生成 UUID
String.UUID = "503bc59e-83f9-11e6-ae22-56b6b6499611" // value will be unique string
获取宽度和高度以及相互转换
"string value here".widthForHeight(50, font: UIFont())
"string value here".heightForWidth(50, font: UIFont())
CGRect 扩展
从 CGRect 读取和设置 x、y、centerX、centerY、lastX、lastY、center、middle 等点值
let frame = CGRectMake(10, 20, 50, 100)
frame.x = 10
frame.y = 20
frame.centerX = 30
frame.centerY = 60
frame.lastX = 60
frame.lastY = 120
frame.center = CGPointMake(30, 60)
frame.middle = CGPointMake(25, 50)
CMTime 扩展
将 CMTime 转换为秒的 NSTimeInterval
CMTimeMake(100, timescale: timescaleValue).toSeconds = 100
AVPlayerItem 扩展
从 AVPlayerItem 获取当前播放时间
let item = AVPlayerItem() // initialization here
item.currentPlaybackTime // value will be current playback time in seconds
数组与集合扩展
从数组中移除特定对象
var array = [1, 2, 3, 4, 5]
let removedObject = array.remove(2)
removedObject = 2
array = [1, 3, 4, 5]
在索引处插入数组的元素
var array1 = [1, 2, 3]
var array2 = [4, 5, 6]
let array3 = array1.insertContentsOf(array2, atIndex: 1)
array3 = [1, 4, 5, 6, 2, 3]
使用 NSIndexPath 下标二维数组
let dataSource = [[1, 2], [3]]
dataSource[NSIndexPath(forRow: 0, inSection: 1)] = 3
使用 NSIndexPath 从二维数组中移除对象
let dataSource = [[1, 2], [3]]
let removedObject = dataSource.removeAtIndexPath(NSIndexPath(forRow: 0, inSection: 1))
removedObject = 3
将字符串数组转换为整型数组
let stringArray = ["1", "2", "3"]
stringArray.toInt = [1, 2, 3]
NSObject 扩展
获取作为字符串的全类名
UIViewController.stringFromClass = "ProjectTargetName.UIViewController"
UIViewController().stringFromClass = "ProjectTargetName.UIViewController"
获取作为字符串的类名
UIViewController.className = "UIViewController"
UIViewController().className = "UIViewController"
从Nib中获取对象
NSObject.objectFromNib("NibName")
NSObject.objectFromNib("NibName", boundle: boundle, owner: owner, options: options)
NSData 扩展
从互联网下载数据
let url = NSURL(string: "https://avatars3.githubusercontent.com/u/5988751?v=3&s=466")!
let uuid = NSData.download(url, completeInMainThread: true, completion: { (data, id) in
id == uuid
data == downloaded data from url
})
NSDate 扩展
获取本地日期
NSDate.localDate = current date by device timezone
从日期,月份和年份创建日期
NSDate.dateWithDay(29, month: 7, year: 1992) = 29/07/1992
将日期转换为字符串
date.toString("dd-MM-YY") = "29-07-92"
date.toString("ss-mm-HH") = "27-35-11"
日期属性
let date = NSDate(timeIntervalSince1970: 1474647378)
let second = 18
let minute = 16
let hour = 18
let day = 23
let weekDay = 6
let weekdayOrdinal = 4
let month = 9
let year = 2016
let era = 1
self.date.second = second
self.date.minute = minute
self.date.hour = hour
self.date.day = day
self.date.weekDay = weekDay
self.date.weekdayOrdinal = weekdayOrdinal
self.date.month = month
self.date.year = year
self.date.era = era
NSDictionary 扩展
获取不区分大小写的键的值
let dict = ["kEy" : "value"]
dict.valueForLowercaseKey("key") = "value"
dict.valueForLowercaseKey("KEY") = "value"
NSURL 扩展
将 URL 从 iCould 备份中排除
let url = NSURL(fileURLWithPath: "/path/to/file")
url.excludeFromBackup(true) // exclude
url.excludeFromBackup(false) // include
检查 URL 是否已从备份中排除
let url = NSURL(fileURLWithPath: "/path/to/file")
url.excludedFromBackup = true // excluded
url.excludedFromBackup = false // included
PHAsset 扩展
检查 PHAsset 是否已从服务器获取
let asset = PHAsset() // init here
asset.downloaded = true // fetched
asset.downloaded = false // not fetched
UIColor 扩展
使用 RGB 整数和十六进制值创建 UIColor
UIColor(255, green: 0, blue: 0) // Red color
UIColor(hexValue: 0xff0000) // Red color
UIColor(hexString: "#ff0000") // Red color
获取颜色分量
let color = UIColor(1, green: 0.5, blue: 0)
color.red = 1
color.green = 0.5
color.blue = 0
获取随机颜色
UIColor.randomColor
UIImage 扩展
使用颜色创建图像
UIImage(color: UIColor.redColor(), size: CGSizeMake(100, 100))
从 URL 下载图像
let url = NSURL(string: "https://avatars3.githubusercontent.com/u/5988751?v=3&s=466")!
let uuid = UIImage.download(url, completion: { (image, id) in
id == uuid
image == downloaded image from url
})
GIF 文件创建动画图像
UIImage.gif("file.gif") // gif with name
UIImage.gif(NSURL()) // gif with url
UIImage.gif(NSData()) // gif with data
UIImage.gif(CGImageSourceRef()) // gif with source
反转透明度
let image = UIImage(named: "") // Init here
image.invertTransparancy()
使用像素获取颜色
let image = UIImage(named: "") // Init here
image.color(CGPointMake(20, 40))
调整图像大小
let image = UIImage(named: "") // Init here
image.rescale(0.5) // image will be resized by 1/2
image.resize(CGSizeMake(10, 20)) // image will be resized on (10, 20) size
image.cutCircle(10) // image will cut circle with 10 radius
旋转图像
let image = UIImage(named: "") // Init here
image.imageByRotation(90) // image will be rotated by 90 degrees
更改方向
let image = UIImage(named: "") // Init here
image.changeOrientation(UIImageOrientation.Down) // image will have Down orientation
UINib 扩展
初始化 nib
UINib.instantiateType(type, nibName: name, bundle: boundle, owner: owner, options: options)
UIView 扩展
从 nib 加载视图
UIView.loadNibNamed(nibName: String, nibClass: AnyClass)
递归获取子视图通过标签
self.view.subviews(27, recursively: true)
移除所有子视图
self.view.removeAllSubviews()
从视图获取屏幕截图
self.view.screenshot() // returns UIImage
self.view.screenshot(CGRectMake(0, 0, 100, 100)) // returns UIImage from 0, 0, 100, 100 frame
将视图转换为图像
self.view.toImage
拉伸视图布局
let view = UIView() // Init here
view.stretchLayout() // view will have the same frame as its superview
view.stretchLayout(UIView()) // view will have the same frame as another view
view.stretchLayout(UIView(), edgeInsets: UIEdgeInsetsMake()) // view will have the frame with insets to another view
通过标识符获取约束
let view = UIView() // Init here
view.constraints("identifier") // returns array of NSLayoutConstraint
遮罩视图的内外边框
let view = UIView() // Init here
view.outterMask(CGRectMake(10, 10, 80, 80, cornerRadius: 10)) // cornerRadius is optional
view.innerMask(CGRectMake(10, 10, 80, 80, cornerRadius: 10)) // cornerRadius is optional
从视图中移除遮罩
view.removeMask()
检查视图是否被遮罩
view.masked = true // masked
view.masked = false // not masked
UIScrollView 扩展
获取和设置滚动视图的内容宽度和高度
scrollview.contentWidth = 100
scrollview.contentHeight = 100
检查滚动视图是否滚动到顶部或底部
scrollview.scrolledTop = true // scrolled to top
scrollview.scrolledBottom = true // scrolled to bottom
滚动滚动视图到顶部和底部
scrollview.scrollToTop(true) // scroll to top with animation
scrollview.scrollToTop(false) // scroll to top without animation
scrollview.scrollToBottom(true) // scroll to top with animation
scrollview.scrollToBottom(false) // scroll to top without animation
UIAlertView 扩展
创建简单的 alert 视图
UIAlertView(title: String?, message: String, delegate: AnyObject?, tag: Int, style: UIAlertViewStyle, keyboardType: UIKeyboardType, cancelButtonTitle: String?, otherButtonTitles: String, String...)
UIAlertController 扩展
创建简单的 alert 控制器
UIAlertController(title: String?, message: String, style: UIAlertControllerStyle, inputFieldPlaceholders: [String], actionTitles: [String], actionBlocks: { (action) in
}, completion: {
})
UIImageView 扩展
创建带有遮罩的 UIImageView
UIImageView.imageView(UIImage(), mask: UIImage())
UILabel 扩展
根据高度、宽度和字体获取标签文本的宽度和高度
label.widthForText
label.heightForText
截断标签尾部
label.truncateTail(10, attributed: false) // truncate after 10 characters non attributed label
label.tailTruncated // check if label tail is truncated
获取可见文本矩形
label.textRect // return CGRect
通过点获取字符索引
label.characterIndex(CGPointMake(10, 10)) // returns Int
UITextField 扩展
通过高度、宽度和字体获取文本字段的宽度和高度
textField.widthForText
textField.heightForText
UITextView 扩展
通过高度、宽度和字体获取文本视图的宽度和高度
textView.widthForText
textView.heightForText
UIViewController 扩展
加载视图控制器
UIViewController.loadWithId("identifier", storyboard: "name") // storyboard name is optional. If it is not presented view controller will be loaded from Main storyboard
MyViewController.loadFromStoryboard("storyboardName") // storyboard name is optional. If it is not presented view controller will be loaded from Main storyboard
MyViewController.loadAsRootViewControllerFromStoryboard("storyboardName") // initializes viewcontroller and loads it as root. Storyboard name is optional. If it is not presented view controller will be loaded from Main storyboard
MyViewController().loadAsRootViewController() // loads view controller as root.
MPMoviePlayerController 扩展
从电影播放器获取缩略图
player.thumbnail(CMTime) // returns UIImage. Time is optional. If it is not presented thumbnail will be loaded from the first frame
安装
- 手动安装
- 作为开源项目
- 下载 RDExtensionsSwift 项目
- 将源文件夹拖放到您的项目中(如果需要,请确保勾选“复制”复选框)
- 作为嵌入框架
- 下载 RDExtensionsSwift 项目
- 为所需目标构建
- 将其复制到您的项目目录中
- 在 Xcode 导航器中,选择项目 >>湍流 >>嵌入式二进制文件:单击 "+" 按钮,选择 RDExtensionsSwift 框架。
source 'https://github.com/CocoaPods/Specs.git'
use_frameworks!
target 'ProjectName' do
# For latest version:
pod 'RDExtensionsSwift'
# For earlier verions:
pod 'RDExtensionsSwift', '~> 5.0.1' # for Swift 5.0
pod 'RDExtensionsSwift', '~> 4.2.3' # for Swift 4.2
pod 'RDExtensionsSwift', '~> 4.0.1' # for Swift 4
pod 'RDExtensionsSwift', '~> 3.1.1' # for Swift 3.2
pod 'RDExtensionsSwift', '~> 2.1.0' # for Swift 3.0
pod 'RDExtensionsSwift', '~> 1.0.7' # for Swift 2
end
运行 pod install
,现在您应该有了最新的 RDExtensionsSwift 发布版。
使用方法
只需导入库并开始编写代码即可
import RDExtensionsSwift
系统要求
- Swift 2.2或更高版本
作者
Georgi Iashvili, [email protected]
许可证
RDExtensionsSwift代码库基于MIT许可证。有关更多信息,请参阅LICENSE文件。