美文网首页我的Swift开发
Swift 常用的Extension

Swift 常用的Extension

作者: 绍清_shao | 来源:发表于2019-10-19 16:51 被阅读0次

    内容

    • 颜色UIColor+Extension
      • hex & rgb
    • UIView+Extension
      • 方便设置Frame
      • 方便在Storyboard中设置Layer层
    • UIViewController+Extension
      • 查找顶层控制器
    • String+Extension
      • 常用正则表达式

    颜色UIColor+Extension

    • hex & rgb
    extension UIColor {
        
        // 系统色
        static let theme: UIColor = UIColor.hexString("#4286F6")
        
    }
    
    extension UIColor {
        
        static func hexString(_ hex:String) -> UIColor {
            var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
            
            if (cString.hasPrefix("#")) {
                cString.remove(at: cString.startIndex)
            }
            
            if ((cString.count) != 6) {
                return UIColor.gray
            }
            
            var rgbValue:UInt32 = 0
            Scanner(string: cString).scanHexInt32(&rgbValue)
            
            return UIColor(
                red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
                green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
                blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
                alpha: CGFloat(1.0)
            )
        }
        
    //    UIColor.hexString("#2D73F1")
        
        static func fromRGB(_ rgbValue: UInt) -> UIColor {
            return UIColor(
                red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
                green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
                blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
                alpha: CGFloat(1.0)
            )
        }
        
    //    UIColor.fromRGB(0x209624)
        
    }
    

    UIView+Extension

    • 方便设置Frame
    // Frame
    extension UIView {
        var width: CGFloat {
            get { return self.frame.size.width }
            set {
                var frame = self.frame
                frame.size.width = newValue
                self.frame = frame
            }
        }
    
        var height: CGFloat {
            get { return self.frame.size.height }
            set {
                var frame = self.frame
                frame.size.height = newValue
                self.frame = frame
            }
        }
        
        var size: CGSize  {
            get { return self.frame.size }
            set {
                var frame = self.frame
                frame.size = newValue
                self.frame = frame
            }
        }
    
        var origin: CGPoint {
            get { return self.frame.origin }
            set {
                var frame = self.frame
                frame.origin = newValue
                self.frame = frame
            }
        }
        
        var x: CGFloat {
            get { return self.frame.origin.x }
            set {
                var frame = self.frame
                frame.origin.x = newValue
                self.frame = frame
            }
        }
        var y: CGFloat {
            get { return self.frame.origin.y }
            set {
                var frame = self.frame
                frame.origin.y = newValue
                self.frame = frame
            }
        }
        
        var centerX: CGFloat {
            get { return self.center.x }
            set {
                self.center = CGPoint(x: newValue, y: self.center.y)
            }
        }
        
        var centerY: CGFloat {
            get { return self.center.y }
            set {
                self.center = CGPoint(x: self.center.x, y: newValue)
            }
        }
        
        var top : CGFloat {
            get { return self.frame.origin.y }
            set {
                var frame = self.frame
                frame.origin.y = newValue
                self.frame = frame
            }
        }
        
        var bottom : CGFloat {
            get { return frame.origin.y + frame.size.height }
            set {
                var frame = self.frame
                frame.origin.y = newValue - self.frame.size.height
                self.frame = frame
            }
        }
        
        var right : CGFloat {
            get { return self.frame.origin.x + self.frame.size.width }
            set {
                var frame = self.frame
                frame.origin.x = newValue - self.frame.size.width
                self.frame = frame
            }
        }
        
        var left : CGFloat {
            get { return self.frame.origin.x }
            set {
                var frame = self.frame
                frame.origin.x  = newValue
                self.frame = frame
            }
        }
    }
    
    • 方便在Storyboard中设置Layer层,圆角、边框、边框宽度和颜色
    // 设置圆角、边框
    extension UIView {
        
        @IBInspectable var cornerRadius: CGFloat {
            get {
                return layer.cornerRadius
            }
            set {
                layer.cornerRadius = newValue
                layer.masksToBounds = newValue > 0
            }
        }
        
        @IBInspectable var borderColor: UIColor {
            get {
                return UIColor.init(cgColor: layer.borderColor ??
                    UIColor.white.cgColor)
            }
            set {
                layer.borderColor = newValue.cgColor
            }
        }
        
        @IBInspectable var borderWidth: CGFloat {
            get {
                return layer.borderWidth
            }
            set {
                layer.borderWidth = newValue
            }
        }
        
    }
    

    效果:


    UIViewController+Extension

    • 查找顶层控制器
    extension UIViewController {
        // MARK: - 查找顶层控制器、
        // 获取顶层控制器 根据window
        func getTopVC() -> (UIViewController?) {
            var window = UIApplication.shared.keyWindow
            //是否为当前显示的window
            if window?.windowLevel != UIWindow.Level.normal{
                let windows = UIApplication.shared.windows
                for  windowTemp in windows{
                    if windowTemp.windowLevel == UIWindow.Level.normal{
                        window = windowTemp
                        break
                    }
                }
            }
            let vc = window?.rootViewController
            return getTopVC(withCurrentVC: vc)
        }
        ///根据控制器获取 顶层控制器
        func getTopVC(withCurrentVC VC :UIViewController?) -> UIViewController? {
            if VC == nil {
                print("🌶: 找不到顶层控制器")
                return nil
            }
            if let presentVC = VC?.presentedViewController {
                //modal出来的 控制器
                return getTopVC(withCurrentVC: presentVC)
            }else if let tabVC = VC as? UITabBarController {
                // tabBar 的跟控制器
                if let selectVC = tabVC.selectedViewController {
                    return getTopVC(withCurrentVC: selectVC)
                }
                return nil
            } else if let naiVC = VC as? UINavigationController {
                // 控制器是 nav
                return getTopVC(withCurrentVC:naiVC.visibleViewController)
            } else {
                // 返回顶控制器
                return VC
            }
        }
    }
    

    String+Extension

    • 常用正则表达式
    extension String {
        /// 正则匹配手机号
        var isMobile: Bool {
            /**
             * 手机号码
             * 移动:134 135 136 137 138 139 147 148 150 151 152 157 158 159  165 172 178 182 183 184 187 188 198
             * 联通:130 131 132 145 146 155 156 166 171 175 176 185 186
             * 电信:133 149 153 173 174 177 180 181 189 199
             * 虚拟:170
             */
            return isMatch("^(1[3-9])\\d{9}$")
        }
        
        /// 正则匹配用户身份证号15或18位
        var isUserIdCard: Bool {
            return isMatch("(^[0-9]{15}$)|([0-9]{17}([0-9]|X)$)")
        }
        
        /// 正则匹配用户密码6-12位数字和字母组合
        var isPassword: Bool {
            return isMatch("^(?![0-9]+$)(?![a-zA-Z]+$)[a-zA-Z0-9]{6,12}")
        }
        
        /// 正则匹配URL
        var isURL: Bool {
            return isMatch("^[0-9A-Za-z]{1,50}")
        }
        
        /// 正则匹配用户姓名,20位的中文或英文
        var isUserName: Bool {
            return isMatch("^[a-zA-Z\\u4E00-\\u9FA5]{1,20}")
        }
        
        /// 正则匹配用户email
        var isEmail: Bool {
            return isMatch("[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}")
        }
        
        /// 判断是否都是数字
        var isNumber: Bool {
            return isMatch("^[0-9]*$")
        }
        
        /// 只能输入由26个英文字母组成的字符串
        var isLetter: Bool {
            return isMatch("^[A-Za-z]+$")
        }
        
        private func isMatch(_ pred: String ) -> Bool {
            let pred = NSPredicate(format: "SELF MATCHES %@", pred)
            let isMatch: Bool = pred.evaluate(with: self)
            return isMatch
        }
        
    }
    

    相关文章

      网友评论

        本文标题:Swift 常用的Extension

        本文链接:https://www.haomeiwen.com/subject/dgknmctx.html