擴展的寫法
-
因為Swift 不需要在使用相應(yīng)的頭文件的時候引入頭文件所以可以把這些擴展方法寫到同一個文件中,這個是和OC的區(qū)別, 例子:
// 擴展 String 類型 extension String { } // 擴展UILabel extension UILabel { }
擴展String
-
獲取字符串的高度
func getTextHeight(font:CGFloat,width:CGFloat) -> CGFloat { let normalText = self as NSString let size = CGSize(width: width, height: CGFloat(MAXFLOAT)) let fontS = UIFont.systemFont(ofSize: font) let dic = NSDictionary(object: fontS, forKey: NSFontAttributeName as NSCopying) let stringSize = normalText.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: dic as? [String : AnyObject], context:nil).size return stringSize.height }
-
獲取字符串的長度
func getTexWidth(font:CGFloat,height:CGFloat) -> CGFloat { let normalText: NSString = self as NSString let size = CGSize(width: CGFloat(MAXFLOAT), height: height) let fontS = UIFont.systemFont(ofSize: font) let dic = NSDictionary(object: fontS, forKey: NSFontAttributeName as NSCopying) let stringSize = normalText.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: dic as? [String : AnyObject], context:nil).size return stringSize.width }
-
MD5 加密
var md5 : String{ let str = self.cString(using: String.Encoding.utf8) let strLen = CUnsignedInt(self.lengthOfBytes(using: String.Encoding.utf8)) let digestLen = Int(CC_MD5_DIGEST_LENGTH) let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen) CC_MD5(str!, strLen, result) let hash = NSMutableString() for i in 0 ..< digestLen { hash.appendFormat("%02x", result[i]) } result.deinitialize() return String(format: hash as String) }
-
漢字轉(zhuǎn)拼音(需要消耗不少性能,注意使用)
func transformToPinYin() -> String { let mutableString = NSMutableString(string: self) //把漢字轉(zhuǎn)為拼音 CFStringTransform(mutableString, nil, kCFStringTransformToLatin, false) //去掉拼音的音標 CFStringTransform(mutableString, nil, kCFStringTransformStripDiacritics, false) let string = String(mutableString) //去掉空格 return string.replacingOccurrences(of: " ", with: "") }
把這些方法全部放到下面的的代碼里面,即可使用
// 擴展 String 類型
extension String {
}
擴展UILabel
-
修改UILabel的行間距
func modifyTheLineSpacing(distance: CGFloat) { let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: self.text!) let paragraphStyle: NSMutableParagraphStyle = NSMutableParagraphStyle() paragraphStyle.lineSpacing = distance // 調(diào)整行間距 attributedString.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: NSMakeRange(0, (self.text! as NSString).length)) self.attributedText = attributedString; }
-
修改字體顏色
func changeTheTextColor(textColor: UIColor, textFont: CGFloat, range: NSRange) { let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: self.text!) let attris: [String: AnyObject] = [ NSForegroundColorAttributeName: textColor, NSFontAttributeName: UIFont.systemFont(ofSize: textFont), NSBackgroundColorAttributeName: self.backgroundColor! ] attributedString.addAttributes(attris, range: range) self.attributedText = attributedString; }
把這些方法全部放到下面的的代碼里面,即可使用
// 擴展 String 類型
extension UILabel {
}
擴展UIView
寫在擴展前面,因為我比較喜歡使用Frame布局,沒有使用Xib,SB,Autolayout等, 一開始使用布局的時候都是使用
self.view.frame.size.with + self.view.frame.origin.x
這樣布局, 寫著很累,對UIView進行擴展之后,想要和上面的代碼擁有相同的效果便很簡單了
self.view.maxX
是不是很簡單?
對UIView進行擴展
extension UIView {
// 獲取view左邊的坐標
var minX: CGFloat {
return self.frame.origin.x
}
// 獲取view右邊的坐標
var maxX: CGFloat {
return self.frame.origin.x + self.frame.size.width
}
// 獲取view上邊的坐標
var minY: CGFloat {
return self.frame.origin.y
}
// 獲取view下邊的坐標
var maxY: CGFloat {
return self.frame.origin.y + self.frame.size.height
}
// 獲取view的x軸的中心點
var centerX: CGFloat {
return self.center.x
}
// 獲取view的y軸的中心點
var centerY: CGFloat {
return self.center.y
}
// 獲取view的寬度
var width: CGFloat {
return self.frame.size.width
}
// 獲取view的高度
var height: CGFloat {
return self.frame.size.height
}
// 獲取view的size
var size: CGSize {
return self.frame.size
}
}
使用方法很簡單,比如
//獲取View的高度
self.view.height
//獲取View的寬度
self.view.width
擴展UIImage
extension UIImage{
// 重設(shè)圖片大小
func changeImageSize(size:CGSize) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size,false,UIScreen.main.scale);
self.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
let resizeImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext();
return resizeImage;
}
// 等比例縮放
func scaleImage(scaleSize:CGFloat) -> UIImage {
let reSize = CGSize(width: self.size.width * scaleSize, height: self.size.height * scaleSize)
return changeImageSize(size: reSize)
}
}
擴展UIColor
當設(shè)計師給的16進制顏色的時候便可以調(diào)用下面的方法
extension UIColor {
convenience init(hexString: String) {
// 存儲轉(zhuǎn)換后的數(shù)值
var red:UInt32 = 0, green:UInt32 = 0, blue:UInt32 = 0
// 分別轉(zhuǎn)換進行轉(zhuǎn)換
Scanner(string: hexString[0..<2]).scanHexInt32(&red)
Scanner(string: hexString[2..<4]).scanHexInt32(&green)
Scanner(string: hexString[4..<6]).scanHexInt32(&blue)
self.init(red: CGFloat(red)/255.0, green: CGFloat(green)/255.0, blue: CGFloat(blue)/255.0, alpha: 1.0)
}
convenience init(hexString: String, alpha: CGFloat) {
// 存儲轉(zhuǎn)換后的數(shù)值
var red:UInt32 = 0, green:UInt32 = 0, blue:UInt32 = 0
// 分別轉(zhuǎn)換進行轉(zhuǎn)換
Scanner(string: hexString[0..<2]).scanHexInt32(&red)
Scanner(string: hexString[2..<4]).scanHexInt32(&green)
Scanner(string: hexString[4..<6]).scanHexInt32(&blue)
self.init(red: CGFloat(red)/255.0, green: CGFloat(green)/255.0, blue: CGFloat(blue)/255.0, alpha: alpha)
}
}
使用方法
imageView.backgroundColor = UIColor(hexString: "eeeeee")
擴展 提示框 UIAlertController
extension UIAlertController {
class func createUIAlertController(title: String?, message: String?, leftButton: String, rightButton: String, complete: @escaping () -> Void) -> UIAlertController{
let av = UIAlertController(title: title, message: message, preferredStyle: .alert)
let cancel = UIAlertAction(title: leftButton, style: .cancel, handler: nil)
let confirm = UIAlertAction(title: rightButton, style: .destructive, handler: { (action) in
complete()
})
av.addAction(cancel)
av.addAction(confirm)
return av
}
class func createUIAlertController(title: String?, message: String?, leftButton: String, rightButton: String, cancel: @escaping() -> Void, complete: @escaping () -> Void) -> UIAlertController{
let av = UIAlertController(title: title, message: message, preferredStyle: .alert)
let cancel = UIAlertAction(title: leftButton, style: .cancel) { (action) in
cancel()
}
let confirm = UIAlertAction(title: rightButton, style: .destructive, handler: { (action) in
complete()
})
av.addAction(cancel)
av.addAction(confirm)
return av
}
}
使用方法
self.present(UIAlertController.createUIAlertController(title: "提示", message: "擴展到這里就結(jié)束了", leftButton: "取消", rightButton: "確定", cancel: {
// 點擊取消的按鈕
}, complete: {
// 點擊確定的按鈕
})
, animated: true, completion: nil)