Swift-常用代码封装

279 阅读9分钟

一、使用示例

1、基础控件使用示例

    fileprivate lazy var contrainer: UIView = { ()-> UIView in
        let tmp = JKSwiftUITools.createContentView() { view in
            view.backgroundColor = .white
        }
        self.view.addSubview(tmp)
        return tmp
    }()

    fileprivate lazy var elblTitle: UILabel = { ()-> UILabel in
        let tmp = JKSwiftUITools.createLabel(text: String.localized("SettingsPageSettingsTitle"),font: UIFont.boldSystemFont(ofSize: 16),textColor: .k666666()) { label in
            label.font = UIFont(medium: UInt(Locale.specialLanguageValue([.german,.indonesian], 16, 12)))
        }
        tmp.textAlignment = .center
        self.contrainer.addSubview(tmp)
        return tmp
    }()

    fileprivate lazy var ebtnClose: UIButton = { ()-> UIButton in
        let tmp = JKSwiftUITools.createButton(title:String.localized("MultilingualCancel"),font: UIFont.regular(14))
        tmp.contentHorizontalAlignment = .left
        tmp.addTarget(self, action: #selector(onClickClose(_:)), for: .touchUpInside)
        self.contrainer.addSubview(tmp)
        return tmp
    }()

    fileprivate lazy var ebtnConfirm: UIButton = { ()-> UIButton in
        let tmp = JKSwiftUITools.createButton(title:String.localized("MultilingualComfirm"),font: UIFont(semibold: 14),titleColor: .white)
        tmp.backgroundColor = .k2180FF()
        tmp.addTarget(self, action: #selector(onClickConfirm(_:)), for: .touchUpInside)
        self.contrainer.addSubview(tmp)
        return tmp
    }()

    fileprivate lazy var ebtnDefalut: UIButton = { ()-> UIButton in
        let tmp = JKSwiftUITools.createButton(title:String.localized("SettingsPageBtnDefault"),font: UIFont(semibold: 14),titleColor: .k2180FF())
        tmp.addTarget(self, action: #selector(onClickDefalut(_:)), for: .touchUpInside)
        self.contrainer.addSubview(tmp)
        return tmp
    }()

    fileprivate lazy var ebtnDismiss: UIButton = { ()-> UIButton in
        let tmp = JKSwiftUITools.createButton()
        tmp.addTarget(self, action: #selector(onClickDismiss(_:)), for: .touchUpInside)
        self.view.addSubview(tmp)
        return tmp
    }()
    
    fileprivate lazy var eimgVoiceArrow: UIImageView = { ()-> UIImageView in
        let tmp = JKSwiftUITools.createImageView(imageName:R.image.icon_muti_voice_arrow.name)
        self.toolBar.addSubview(tmp)
        return tmp
    }()

2、常用高级控件

    fileprivate lazy var tableView: UITableView = { () -> UITableView in
        let tmp = JKSwiftUITools.createTableView(rowHeight: 80,registerNibCells: ["MFHistoryCell","MFMobileEmptyCell"]) { tableView in
            tableView.tableHeaderView = UIView(frame: CGRect.init(x: 0, y: 0, width: Constant.kScreenW, height: 15))
            tableView.tableFooterView = UIView()
            tableView.backgroundColor = .clear
        }
        tmp.delegate = self
        tmp.dataSource = self
        self.view.addSubview(tmp)
        return tmp
    }()
    
    fileprivate lazy var collectionView: UICollectionView = { ()-> UICollectionView in
        let tmp = JKSwiftUITools.createCollectionView(sectionInset:UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10),lineSpacing: 10,interitemSpacing: 10)
        tmp.delegate   = self
        tmp.dataSource = self
        tmp.register(JKHomeCollectionCell.self, forCellWithReuseIdentifier: "JKHomeCollectionCell")
        self.view.addSubview(tmp)
        return tmp
    }()

3、其他常用


//语言国际化取值(不用:NSLocalizedString("<#key#>", comment: ""))
tmp.placeHolder = String.localized("HomePageInputTextPlaceHolder")

//字体赋值
tmp.font = UIFont.regular(14)

//不同语言适配(如:德语、印尼语)
tmp.font = UIFont(medium: UInt(Locale.specialLanguageValue([.german,.indonesian], 16, 12)))

//布局适配:
    if let currentLanguageCode = Locale.current.languageCode {
        if currentLanguageCode == "de" || currentLanguageCode == "id" || currentLanguageCode == "fr" {
                // 当前设备语言是德语
                print("当前设备语言是德语")
                self.elblTextFront.font = UIFont(regular: 11)
                self.elblTryNow.font = UIFont(bold: 11)
        } else {
                // 当前设备语言不是德语
                print("当前设备语言不是德语")
                self.elblTextFront.font = UIFont(regular: 14)
                self.elblTryNow.font = UIFont(bold: 14)
        }
    } else {
            // 无法确定当前设备语言
            print("无法确定当前设备语言")
            self.elblTextFront.font = UIFont(regular: 14)
            self.elblTryNow.font = UIFont(bold: 14)
    }
    
//直接改成
    self.elblTextFront.font = UIFont(regular: UInt(Locale.specialLanguageValue([.german,.indonesian,.french], 14, 11)))
    self.elblTryNow.font    = UIFont(bold: UInt(Locale.specialLanguageValue([.german,.indonesian,.french], 14, 11)))


二、常用控件封装

1、基础控件基础封装

import GrowingTextView

struct JKSwiftUITools {

    //MARK: - 快捷创建Label
    public static func createLabel(text:String,font:UIFont? = nil,textColor:UIColor? = .black,completion: ((UILabel) -> Void)? = nil) -> UILabel {
        let tmp = UILabel()
        tmp.text = text
        tmp.textAlignment = .left
        tmp.numberOfLines = 1
        tmp.font = UIFont.systemFont(ofSize: 15)
        if let font = font {
            tmp.font = font
        }
        tmp.textColor = textColor
        completion?(tmp)
        return tmp
    }

    //MARK: - 快捷创建国际化Label
    static func createLabelMultilingual(multilingualKey:String,textColor:UIColor? = .black,completion: ((UILabel) -> Void)? = nil) -> UILabel {
        let tmp = UILabel()
        tmp.text = NSLocalizedString(multilingualKey, comment: "")
        tmp.textAlignment = .left
        tmp.numberOfLines = 1
        tmp.textColor = textColor
        tmp.font = UIFont.systemFont(ofSize: 15)
        completion?(tmp)
        return tmp
    }
}

extension JKSwiftUITools {

    //MARK: - 快捷创建基础UIButton
    static func createButton(title:String? = nil,font:UIFont? = UIFont.systemFont(ofSize: 15),titleColor:UIColor? = .black,imageName:String? = nil,backgroundImage:String? = nil,target: Any? = nil, action: Selector? = nil,completion: ((UIButton) -> Void)? = nil) -> UIButton {
        let tmp = UIButton()
        if let title = title {
            tmp.setTitle(title, for: .normal)
        }
        if let titleColor = titleColor {
            tmp.setTitleColor(titleColor, for: .normal)
        }
        if let font = font {
            tmp.titleLabel?.font = font
        }
        if let imageName = imageName {
            tmp.setImage(UIImage(named: imageName), for: .normal)
        }
        if let backgroundImage = backgroundImage {
            tmp.setBackgroundImage(UIImage(named: backgroundImage), for: .normal)
        }
        if let target = target,let action = action {
            tmp.addTarget(target, action: action, for: .touchUpInside)
        }
        completion?(tmp)
        return tmp
    }
}

extension JKSwiftUITools {

    //MARK: - 快捷创建基本UIImageView
    static func createImageView(imageName:String? = "",systemImageName:String? = "",systemImageColor:UIColor? = nil,systemImageSize:CGFloat = 0,completion: ((UIImageView) -> Void)? = nil) -> UIImageView {
        let tmp = UIImageView()
        if let imageName = imageName {
            tmp.image = UIImage(named: imageName)
        }
        if let systemImageName = systemImageName,let systemImage = MFSwiftUITools.createSystemSymbolImage(symbolName: systemImageName, color: systemImageColor, size: systemImageSize) {
            tmp.image = systemImage
        }
        /**
         scaleToFill:       缩放填充,可能会导致图片变形
         scaleAspectFit:   等比缩放把图片整体显示在ImageView中,所以可能会出现有空白部分。
         scaleAspectFill:等比缩放图片把整个填充满,所以可能会出现图片部分显示不出来。
         */
        tmp.contentMode = .scaleAspectFit
        completion?(tmp)
        return tmp
    }

    //MARK: - 通过系统SF符号表,快捷创建图片
    static func createSystemSymbolImage(symbolName: String, color: UIColor? = nil, size: CGFloat,renderingMode: UIImage.RenderingMode = .alwaysOriginal) -> UIImage? {
        /**
         注意:
         使用: self.eimgIcon.tintColor = UIColor.qmui_random()
         修改颜色
         */
        let config = UIImage.SymbolConfiguration(pointSize: size)
        return UIImage(systemName: symbolName, withConfiguration: config)?.withTintColor(color ?? .blue)
    }
}

extension JKSwiftUITools {

    //MARK: - 快捷创建UITextField
    static func createTextField(text:String? = nil,font:UIFont? = nil,placeHolder:String? = nil,placeHolderColor:UIColor? = nil,completion: ((UITextField) -> Void)? = nil) -> UITextField {
        let tmp = UITextField()
        tmp.text = text
        tmp.borderStyle = .line
        if let font = font {
            tmp.font = font
        }
        if let placeHolder = placeHolder {
            tmp.placeholder = placeHolder
        }
        //if let placeHolderColor = placeHolderColor {
        //    tmp.placeholderColor = placeHolderColor
        //}
        //tmp.textInsets = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)
        completion?(tmp)
        return tmp
    }

    //MARK: - 快捷创建UITextView(依赖: pod 'GrowingTextView', '0.7.2')
    static func createTextView(text:String? = nil,font:UIFont? = nil,placeHolder:String? = nil,placeHolderColor:UIColor? = nil,completion: ((GrowingTextView) -> Void)? = nil) -> GrowingTextView {
        //https://github.com/KennethTsang/GrowingTextView

        let tmp = GrowingTextView()
        tmp.text = text
        if let placeHolderColor = placeHolderColor {
            tmp.placeholderColor = placeHolderColor
        }
        if let placeHolder = placeHolder {
            tmp.placeholder = placeHolder
        }
        if let font = font {
            tmp.font = font
        } else {
            tmp.font = UIFont.systemFont(ofSize: 15)
        }
        tmp.autocorrectionType = .no//关闭自动联想功能
        tmp.autocapitalizationType = .none//关闭首字母大写
        completion?(tmp)
        return tmp
    }
}

extension JKSwiftUITools {

    //MARK: - 快捷创建UISegmentedControl
    static func createSegmentedControl(items:[String],nomarlColor:UIColor,selectColor:UIColor,selectIndex:Int = 0,font:UIFont = UIFont.systemFont(ofSize: 14),completion: ((UISegmentedControl) -> Void)? = nil) -> UISegmentedControl {
        let tmp = UISegmentedControl(items:items)
        tmp.selectedSegmentIndex = selectIndex
        tmp.tintColor = selectColor
        tmp.setTitleTextAttributes([NSAttributedString.Key.font:font], for: .normal)
        if #available(iOS 13.0, *) {
            tmp.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: selectColor], for: .selected)
            tmp.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: nomarlColor], for: .normal)
            tmp.selectedSegmentTintColor = selectColor
        }
        completion?(tmp)
        //添加事件
        //tmp.addTarget(self, action: #selector(segmentedControlChanged), for: UIControlEvents.valueChanged)
        return tmp
    }

    //MARK: - 快捷创建UISlider
    static func createSlider(value:CGFloat,min:CGFloat = 0,max:CGFloat = 1,nomarlCololr:UIColor = .kCADFFF(),selectColor:UIColor = .k2F82FF(),completion: ((UISlider) -> Void)? = nil) -> UISlider {

        let tmp = UISlider()
        tmp.minimumValue = Float(min)
        tmp.maximumValue = Float(max)
        tmp.maximumTrackTintColor = nomarlCololr
        tmp.minimumTrackTintColor = selectColor

        tmp.setThumbImage(UIImage(named: "settings_slider_thumb"), for: .normal)
        tmp.setThumbImage(UIImage(named: "settings_slider_thumb"), for: .highlighted)

        tmp.setValue(Float(value), animated: true) // 设置slider【初始值】
        completion?(tmp)
        //添加事件
        //tmp.addTarget(self, action: #selector(sliderTouchDown(_:)), for: .touchDown)//开始滑动
        //tmp.addTarget(self, action: #selector(sliderValueChanged(_:)), for: .valueChanged)//滑动中
        //tmp.addTarget(self, action: #selector(sliderTouchUpInside(_:)), for: .touchUpInside)//滑动结束
        return tmp
    }
}

extension MFSwiftUITools {

    //MARK: - 快捷创建UIScrollView
    static func createScrollView(bounces:Bool = false,completion: ((UIScrollView) -> Void)? = nil) -> UIScrollView {
        let scrollView = UIScrollView()
        //scrollView.delegate = delegate
        scrollView.backgroundColor = .blue
        scrollView.bounces = bounces
        completion?(scrollView)
        return scrollView
    }

    //MARK: - 快捷创建空白的UIView
    static func createContentView(bgColor:UIColor? = nil,completion: ((UIView) -> Void)? = nil) -> UIView {
        let contentView = UIView()
        if let bgColor = bgColor {
            contentView.backgroundColor = bgColor
        }
        completion?(contentView)
        return contentView
    }
}

extension JKSwiftUITools {

    //MARK: - 快捷创建UICollectionView
    static func createCollectionView(itemSize:CGSize = .zero,sectionInset:UIEdgeInsets = .zero,lineSpacing:CGFloat = 0,interitemSpacing:CGFloat = 0,direction:UICollectionView.ScrollDirection = .vertical,layout: ((UICollectionViewFlowLayout) -> Void)? = nil,completion: ((UICollectionView) -> Void)? = nil) -> UICollectionView {

        let flowLayout = UICollectionViewFlowLayout()
        //flowLayout.itemSize = itemSize//设置单元格大小
        flowLayout.minimumLineSpacing = lineSpacing//最小行间距(默认为10)
        flowLayout.minimumInteritemSpacing = interitemSpacing //最小item间距(默认为10)
        flowLayout.sectionInset = sectionInset//设置senction的内边距
        flowLayout.scrollDirection = direction;//横向UICollectionViewScrollDirectionHorizontal  纵向UICollectionViewScrollDirectionVertical
        //flowLayout.headerReferenceSize = CGSizeMake(100,0)//sectionHeader的大小,如果是竖向滚动,只需设置Y值。如果是横向,只需设置X值。
        layout?(flowLayout)

        let collecitonView = UICollectionView(frame: .zero, collectionViewLayout: flowLayout)
        completion?(collecitonView)
        return collecitonView
    }

    //MARK: - 快捷创建UITableView
    static func createTableView(rowHeight:CGFloat = 44,registerCells:[String]? = [],registerNibCells:[String]? = [],headerHeight:CGFloat = 0,footerHeight:CGFloat = 0,style:UITableView.Style = .plain,completion: ((UITableView) -> Void)? = nil) -> UITableView {
        let tmp = UITableView(frame: .zero, style: style)
        tmp.rowHeight = rowHeight
        tmp.separatorStyle  = .none
        tmp.showsVerticalScrollIndicator = false
        tmp.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        if #available(iOS 11.0, *) {
            tmp.contentInsetAdjustmentBehavior = .never
        }
        if headerHeight > 0 {
            tmp.tableHeaderView = MFSwiftUITools.createContentView() { contentView in
                contentView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: headerHeight)
            }
        }
        if footerHeight > 0 {
            tmp.tableFooterView = MFSwiftUITools.createContentView() { contentView in
                contentView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: footerHeight)
            }
        }
        if let registerCells = registerCells {
            for (_,className) in registerCells.enumerated() {
                if let classType = NSClassFromString(className) {
                    tmp.register(classType.self, forCellReuseIdentifier: className)
                }
            }
        }
        if let registerNibCells = registerNibCells {
            for (_,className) in registerNibCells.enumerated() {
                tmp.register(UINib(nibName: className, bundle: nil), forCellReuseIdentifier: className)
            }
        }
        completion?(tmp)
        return tmp
    }
}

extension JKSwiftUITools {

    //MARK: - 根据字符串名字 创建 控制器对象( 注意: MFSwiftBaseController可以改成 自己代码中的 XxxBaseController)
    static func createViewController(with className: String) -> MFSwiftBaseController? {
        // 获取命名空间
        guard let namespace = Bundle.main.infoDictionary?["CFBundleExecutable"] as? String else {
            return nil
        }
        // 根据命名空间和类名快捷创建类类型
        guard let viewControllerClass = NSClassFromString("\(namespace).\(className)") as? MFSwiftBaseController.Type else {
            return nil
        }
        // 快捷创建并返回视图控制器实例
        let viewController = viewControllerClass.init()
        return viewController
    }
}

2、其他常用的扩展

UIFont

extension UIFont {

    //MARK: - 常用的字体:regular
    @objc static func regular(_ size: CGFloat) -> UIFont {
        return UIFont(name: "Helvetica", size: size) ?? UIFont.systemFont(ofSize: size)
    }

    //MARK: - 常用的字体:semibold
    @objc static func semibold(_ size: CGFloat) -> UIFont {//粗体字体
        return UIFont(name: "Helvetica-Bold", size: size) ?? UIFont.boldSystemFont(ofSize: size)
    }
}

String

extension String {

    //MARK: 读取本地的多语言配置
    static func localized(_ text:String) -> String {
        let localText = NSLocalizedString(text, comment: "")
        if localText.mf.isBlank {//空
            return text//返回原先的
        }
        return localText
    }

    //MARK: - 将jsonList转换为string
    static func jsonListToString(_ jsonList:[Any]) -> String {
        do {
            let jsonData = try JSONSerialization.data(withJSONObject: jsonList, options: .prettyPrinted)
            if let jsonString = String(data: jsonData, encoding: .utf8) {
                return jsonString
            }
            return ""
        } catch {
            print("Error encoding JSON: \(error)")
            return ""
        }
    }

    //MARK: - 将json字符串转换为list
    static func jsonStringToList(_ jsonString:String) -> [[String: Any]] {
        if let jsonData = jsonString.data(using: .utf8) {
            do {
                let json = try JSONSerialization.jsonObject(with: jsonData, options: [])
                if let jsonArray = json as? [[String: Any]] {
                    return jsonArray
                }
            } catch {
                print("Error parsing JSON: \(error)")
                return []
            }
        } else {
            print("Invalid JSON string")
            return []
        }
        return []
    }

    //MARK: - 将Any类型的json转string
    static func jsonObjcToString(from object : Any) -> String? {
        if JSONSerialization.isValidJSONObject(object) {
            do {
                let data = try JSONSerialization.data(withJSONObject: object)
                return  String(data: data, encoding: String.Encoding(rawValue: NSUTF8StringEncoding))
            } catch  {
                print("转换json字符串失败")
            }
        }
        return nil
    }

    func base64String() -> String {
        let plainData = self.data(using: .utf8)
        let base64String = plainData?.base64EncodedString(options:NSData.Base64EncodingOptions.init(rawValue: 0))
        return base64String!
    }
}

Float

extension Float {

    //MARK: - 将字符串数值 转 数值
    static func stringToFloat(_ string: String) -> Float {
        if let float = Float(string) {
            return Float(float)
        } else {
            return 0
        }
    }
}

Locale

extension Locale {

    //MARK: 读取本地的多语言配置
    static func localized(_ text:String) -> String {
        let localText = NSLocalizedString(text, comment: "")
        if localText.mf.isBlank {//空
            return text//返回原先的
        }
        return localText
    }

    /// 指定的设备系统语言适配值
    /// - Parameters:
    ///   - languages: [语言列表],如:[法语,印尼语]
    ///   - nomarl: 正常显示的值
    ///   - special: 特殊语言的适配值
    /// - Returns: 返回值
    static func specialLanguageValue(_ languages:[MFLocalLanguageCodeType],_ nomarl:CGFloat,_ special:CGFloat) -> CGFloat {
        if Locale.isNeedUpdateContrainerLanguage(languages) {
            return special
        }
        return nomarl
    }

    /// 指定的设备系统语言要适配
    /// - Parameter languages: [语言枚举列表]
    static func isNeedUpdateContrainerLanguage(_ languages:[MFLocalLanguageCodeType]) -> Bool {
        if let currentLanguageCode = Locale.current.languageCode,let currentType = MFLocalLanguageCodeType(rawValue: currentLanguageCode) {
            if languages.contains(currentType) {
                return true
            }
            return false
        } else {
            //print("当前设备语言不需要做特殊适配")
            return false
        }
    }

    /// 指定的设备系统语言要适配
    /// - Parameter languages: [语言枚举列表]
    static func basicOfLanguageCarry(resultBlock: @escaping (_ language: String) -> Void) {
        let languages:[MFLocalLanguageCodeType] = [.english,.german,.indonesian,.spanish,.french,.chinese,.chineseTW,.portuguese,.korean,.japanese,.italian,.dutch,.arabic,.malaysian,.swedish,.polish,.thai]
        var languageStr = "english"
        if let currentLanguageCode = Locale.current.languageCode,let currentType = MFLocalLanguageCodeType(rawValue: currentLanguageCode) {
            if languages.contains(currentType) {
                switch currentType {
                case .german:
                    languageStr = "german"
                case .indonesian:
                    languageStr = "indonesian"
                case .spanish:
                    languageStr = "spanish"
                case .french:
                    languageStr = "french"
                case .chinese:
                    languageStr = "chinese"
                case .chineseTW:
                    languageStr = "chinesetw"
                case .portuguese:
                    languageStr = "portuguese"
                case .korean:
                    languageStr = "korean"
                case .japanese:
                    languageStr = "japanese"
                case .italian:
                    languageStr = "italian"
                case .dutch:
                    languageStr = "dutch"
                case .arabic:
                    languageStr = "arabic"
                case .malaysian:
                    languageStr = "malaysian"
                case .swedish:
                    languageStr = "swedish"
                case .polish:
                    languageStr = "polish"
                case .thai:
                    languageStr = "thai"
                default:
                    languageStr = "english"
                }
            }
            resultBlock(languageStr)
        } else {
            //print("当前设备语言不需要做特殊适配")
            resultBlock(languageStr)
        }
    }
}

UIImage

extension UIImage {

    //MARK: - 图片4个角不拉伸( 4个角的不被拉伸的大小 )
    static func resizingModeImage(imageName:String,_ edge:UIEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)) -> UIImage? {
        if let image = UIImage(named: imageName) {
            return image.resizableImage(withCapInsets: edge, resizingMode: .stretch)
        }
        return nil
    }
}

UIImageView

extension UIImageView {

    //MARK: - 通过gif名字,给UImageView添加gif动画
    public func loadingGifImage(_ gifName:String) {
        if let gifURL = Bundle.main.url(forResource: gifName, withExtension: nil) {
            if let gifData = try? Data(contentsOf: gifURL) {
                if let gifImage = UIImage(data: gifData) {
                    self.image = gifImage
                }
            }
        }
    }
}

UIButton

extension UIButton {

    //MARK: - 给文字添加富文本 图片(文字 + 图片)
    func addTextRightImage(text:String,font:UIFont = UIFont(bold: 14),textColor:UIColor = .white,imageName:String,frame:CGRect = CGRect(x: 0, y: -4, width: 20, height: 20)) {

        let showText = NSLocalizedString(text, comment: "")  + "  "
        var itemList = [KMCommonAttributeModel]()

        let itemPlay = KMCommonAttributeModel()
        itemPlay.content   = showText
        itemPlay.font      = font
        itemPlay.fontColor = textColor
        itemList.append(itemPlay)

        let itemCoins = KMCommonAttributeModel()
        itemCoins.image = UIImage(named: imageName)
        itemCoins.imageBounds = frame//CGRect(x: 0, y: -4, width: 20, height: 20)
        itemList.append(itemCoins)

        let attributeString = KMCommonAttributeString.initAttributeString(itemList)
        self.setAttributedTitle(attributeString, for: .normal)
    }
}

UIColor

extension UIColor {

    @objc static func k1E173D() -> UIColor {
        return UIColor.hexIntColor(hexInt: 0x1E173D)
    }
}

// MARK: - 二、使用方法设置颜色
extension UIColor {
    
    // MARK: 2.1、根据RGBA的颜色(方法)
    /// 根据RGBA的颜色(方法)
    /// - Parameters:
    ///   - r: red 颜色值
    ///   - g: green颜色值
    ///   - b: blue颜色值
    ///   - alpha: 透明度
    /// - Returns: 返回 UIColor
    static func color(r: CGFloat, g: CGFloat, b: CGFloat, alpha: CGFloat = 1.0) -> UIColor {
        return UIColor(red: r / 255.0, green: g / 255.0, blue: b / 255.0, alpha: alpha)
    }
    
    // MARK: 2.2、十六进制字符串设置颜色(方法)
    static func hexStringColor(hexString: String, alpha: CGFloat = 1.0) -> UIColor {
        let newColor = hexStringToColorRGB(hexString: hexString)
        guard let r = newColor.r, let g = newColor.g, let b = newColor.b else {
            assert(false, "颜色值有误")
            return .white
        }
        return color(r: r, g: g, b: b, alpha: alpha)
    }
    
    // MARK: 2.3、十六进制 Int 颜色的使用(方法)
    /// 十六进制颜色的使用
    /// - Parameters:
    ///   - color: 16进制 Int 颜色 0x999999
    ///   - alpha: 透明度
    /// - Returns: 返回一个 UIColor
    static func hexIntColor(hexInt: Int, alpha: CGFloat = 1) -> UIColor {
        let redComponet: Float = Float(hexInt >> 16)
        let greenComponent: Float = Float((hexInt & 0xFF00) >> 8)
        let blueComponent: Float = Float(hexInt & 0xFF)
        return UIColor(red: CGFloat(redComponet / 255.0), green: CGFloat(greenComponent / 255.0), blue: CGFloat(blueComponent / 255.0), alpha: alpha)
    }
    
    /// 随机色
    static var randomColor: UIColor {
        return UIColor(r: CGFloat(arc4random()%256), g: CGFloat(arc4random()%256), b: CGFloat(arc4random()%256), alpha: 1.0)
    }
}

三、代码块