一、簡介
SwiftExtension 是一個優化 Swift 開發過程的開源框架,它包含了很多常用方法的拓展,能夠節約我們開發時間,提高開發效率。同時,SwiftExtension 的功能模塊化,方便我們按需引入。
二、常用方法
1. UIView+
UIView 拓展了很多對界面開發非常常用的方法,比如對 UIView 進行圓角、設置邊框、添加陰影、設置漸變等。這些方法都是非常常用的,能夠省去我們自己編寫方法的時間。
extension UIView {
// 對UIView進行圓角設置
func roundCorners(_ corners: UIRectCorner, radius: CGFloat) {
let maskPath = UIBezierPath(roundedRect: bounds,
byRoundingCorners: corners,
cornerRadii: CGSize(width: radius, height: radius))
let maskLayer = CAShapeLayer()
maskLayer.frame = bounds
maskLayer.path = maskPath.cgPath
layer.mask = maskLayer
}
// 在UIView上添加漸變效果
func addGradientLayer(colors: [UIColor],
startPoint: CGPoint = CGPoint(x: 0, y: 0),
endPoint: CGPoint = CGPoint(x: 1, y: 1)) {
let gradientLayer = CAGradientLayer()
gradientLayer.frame = bounds
gradientLayer.colors = colors.map { $0.cgColor }
gradientLayer.startPoint = startPoint
gradientLayer.endPoint = endPoint
layer.insertSublayer(gradientLayer, at: 0)
}
}
2. UIImage+
UIImage 拓展了圖片壓縮、裁剪、旋轉等功能,這些對於圖片處理非常常見的方法,也藉助 SwiftExtension 使得處理過程更加簡單。
extension UIImage {
// 將圖片壓縮至指定大小
func compressed(maxSize: Int) -> UIImage? {
guard let imageData = jpegData(compressionQuality: 1.0) else { return nil }
if imageData.count UIImage {
guard let cgImage = cgImage else { return self }
let height = CGFloat(cgImage.height)
let width = CGFloat(cgImage.width)
if height == width { return self }
let rect: CGRect
if height > width {
let yOffset = (height - width) / 2
rect = CGRect(x: 0, y: yOffset, width: width, height: width)
} else {
let xOffset = (width - height) / 2
rect = CGRect(x: xOffset, y: 0, width: height, height: height)
}
guard let croppedCGImage = cgImage.cropping(to: rect) else { return self }
return UIImage(cgImage: croppedCGImage)
}
}
3. String+
String 拓展了很多字符串的處理方法,比如字符串是否為空、取中間字符、是否匹配正則表達式等。這些方法也是非常常用的。
extension String {
// 判斷字符串是否為空
var isNotEmpty: Bool {
return !isEmpty
}
// 獲取兩個字符串中間的子串
func substring(with prefix: String, suffix: String) -> String? {
guard let prefixRange = range(of: prefix), let suffixRange = range(of: suffix) else {
return nil
}
let range = prefixRange.upperBound .. Bool {
let regular = try? NSRegularExpression(pattern: pattern, options: .caseInsensitive)
let matchCount = regular?.numberOfMatches(in: self, options: [], range: NSRange(location: 0, length: count)) ?? 0
return matchCount > 0
}
}
三、代碼示例
下面是一段使用 SwiftExtension 中拓展的 UIView 方法來設置一個 UIView 圓角和漸變效果的代碼:
let view = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
view.backgroundColor = .white
view.roundCorners([.bottomLeft, .bottomRight], radius: 10)
view.addGradientLayer(colors: [.red, .yellow])
這段代碼簡明扼要,通過 SwiftExtension 中的方法,我們可以輕鬆地為一個 UIView 設置圓角和漸變效果,而不需要手寫多餘的代碼。
四、總結
SwiftExtension 作為一個優化 Swift 開發過程的工具,提供了很多常用的方法拓展,能夠讓我們在編寫 Swift 代碼時更加輕鬆和高效。通過使用 SwiftExtension,我們可以節約時間,降低出錯概率,並且提高代碼的可讀性和可維護性。
原創文章,作者:ASRAK,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/334146.html