Swift 常用扩展类和简单封装

这是在我自学swift道路上,经常用到一些类的扩展,或者是简单封装。这里记下来 方便下次使用

这里扩展类包含了:
将16进制颜色转换为RGB
生成随机颜色
获取当前的viewControlle
给手势添加一个tag属性
String的MD5加密

简单封装包含了:
swift简单封装网络请求Alamofire

  • 将16进制颜色转换为RGB
/**
 * UIColor的扩展类 将16进制颜色转换为RGB
 * @param hexString 16进制颜色字符串
 */
extension UIColor{
    convenience init(hexString: String) {
        let scanner:Scanner = Scanner(string:hexString)
        var valueRGB:UInt32 = 0
        if scanner.scanHexInt32(&valueRGB) == false {
            self.init(red: 0,green: 0,blue: 0,alpha: 0)
        }else{
            self.init(
                red:CGFloat((valueRGB & 0xFF0000)>>16)/255.0,
                green:CGFloat((valueRGB & 0x00FF00)>>8)/255.0,
                blue:CGFloat(valueRGB & 0x0000FF)/255.0,
                alpha:CGFloat(1.0)
            )
        }
    }
}
  • 生成随机颜色
/**
 * 扩展UIColor 生成随机颜色
 */
extension UIColor {
    class var randomColor: UIColor {
        get {
            let red = CGFloat(arc4random()%256)/255.0
            let green = CGFloat(arc4random()%256)/255.0
            let blue = CGFloat(arc4random()%256)/255.0
            return UIColor(red: red, green: green, blue: blue, alpha: 1.0)
        }
    }
}
  • 获取当前的viewController
/**
 * UIViewController 的扩展类 获取当前的ViewController
 * 使用时只需let nowVC = UIViewController.currentViewController()
 */
extension UIViewController {
    class func currentViewController(base: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
        if let nav = base as? UINavigationController {
            return currentViewController(base: nav.visibleViewController)
        }
        if let tab = base as? UITabBarController {
            return currentViewController(base: tab.selectedViewController)
        }
        if let presented = base?.presentedViewController {
            return currentViewController(base: presented)
        }
        return base
    }
}
  • 给手势添加一个tag属性
/**
 * UITapGestureRecognizer 的扩展类 给手势添加一个tag属性
 */
private var tagKey: Int?
extension UITapGestureRecognizer {
    var gestureTag: Int? {
        get {
            return objc_getAssociatedObject(self, &tagKey) as? Int
        }
        set(newValue) {
            objc_setAssociatedObject(self, &tagKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_COPY)
        }
    }
}
  • String的MD5加密
/**
 * String 的扩展类
 * MD5 加密
 */
extension String {
    func getMD5() -> 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.allocate(capacity: digestLen)
        CC_MD5(str!, strLen, result)
        let hash = NSMutableString()
        for i in 0..
  • swift简单封装网络请求Alamofire
//********** 自定义网络请求封装 **********

import UIKit
import Alamofire

let RootUrl = "这里是项目的域名"

//网络类型枚举:get post
enum MethodType {
    case get, post
}

//网络请求类型地址枚举
enum APIUrl: String {
    //登录
    case login  = "***"
    //注册
    case regist = "***"
    //其他根据自己项目接口文档自定义
}

class LTNetWorkTool {

    class func requestData(_ type : MethodType, URL : String, parameters : [String : Any], callBack :  @escaping (_ result : Any) -> ()) -> Void {
        
        //1. 获取网络请求类型和网络请求地址
        let method = type == .get ? HTTPMethod.get : HTTPMethod.post
        let url = RootUrl + URL
        
        //2. 网络请求
        let request = Alamofire.request(url, method: method, parameters: parameters, encoding: URLEncoding.default, headers: nil)
        
        request.responseJSON { (response) in
            
            //3. 获取结果
            guard let result = response.result.value else {
                print("request error for : " + URL)
                print(response.result.error!)
                return
            }
            
            //4. 将结果回调出去
            callBack(result)
        }
    }
}

你可能感兴趣的:(Swift 常用扩展类和简单封装)