美文网首页
Swift 扩展

Swift 扩展

作者: 单抽律化娜 | 来源:发表于2019-12-17 09:26 被阅读0次

扩展UIView

extension UIView {
    /// 移除所有子元素
    public func removeSubviews() {
        subviews.forEach{$0.removeFromSuperview()}
    }

    /// 获取宽度
    public func getWidth() -> CGFloat {
        return sizeThatFits(CGSize(width: CGFloat.greatestFiniteMagnitude, height: frame.height)).width
    }
    
    /// 获取高度
    public func getHeight() -> CGFloat {
        return sizeThatFits(CGSize(width: frame.width, height: CGFloat.greatestFiniteMagnitude)).height
    }

    /// 转为图片
    public func toImage() -> UIImage {
        UIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque, 0.0)
        drawHierarchy(in: bounds, afterScreenUpdates: false)
        let image = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        return image
    }

    /// 根视图
    public func rootView() -> UIView {
        guard let superview = superview else {
            return self
        }
        return superview.rootView()
    }
}

扩展String

extension String {
    
    /// 替换字符串
    public mutating func replace(_ string: String, with: String) -> String {
        return replacingOccurrences(of: string, with: with)
    }
    
    /// 计算宽高
    public func getSize(_ size: CGSize, attributes: [NSAttributedStringKey: Any]) -> CGSize {
        let rect = NSString(string: self).boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: attributes, context: nil)
        return CGSize(width: ceil(rect.width), height: ceil(rect.height))
    }

    /// 转为Int类型
    public func toInt() -> Int? {
        if let num = NumberFormatter().number(from: self) {
            return num.intValue
        } else {
            return nil
        }
    }
    
    /// 转为Double类型
    public func toDouble() -> Double? {
        if let num = NumberFormatter().number(from: self) {
            return num.doubleValue
        } else {
            return nil
        }
    }
    
    /// 转为Float类型
    public func toFloat() -> Float? {
        if let num = NumberFormatter().number(from: self) {
            return num.floatValue
        } else {
            return nil
        }
    }
    
    /// 转为CGFloat类型
    public func toCGFloat() -> CGFloat? {
        if let num = NumberFormatter().number(from: self) {
            return CGFloat(num.doubleValue)
        } else {
            return nil
        }
    }

    /// 添加下标索引
    public subscript(start: Int, length: Int) -> String {
        get {
            let index1 = index(startIndex, offsetBy: start)
            let index2 = index(index1, offsetBy: length)
            return String(self[index1..<index2])
        }
        set {
            let tmp = self
            var s = ""
            var e = ""
            for (idx, item) in tmp.enumerated() {
                if (idx < start) {
                    s += "\(item)"
                }
                if (idx >= start + length) {
                    e += "\(item)"
                }
            }
            self = s + newValue + e
        }
    }
    
    /// 添加下标索引
    public subscript(index: Int) -> String {
        get {
            return String(self[self.index(startIndex, offsetBy: index)])
        }
        set {
            let tmp = self
            self = ""
            for (idx, item) in tmp.enumerated() {
                if idx == index {
                    self += "\(newValue)"
                } else {
                    self += "\(item)"
                }
            }
        }
    }
}

扩展UIColor

extension UIColor {
    
    /// 16进制字符初始化
    public convenience init(hex string: String, alpha: CGFloat = 1.0) {
        
        let hexString = string.trimmingCharacters(in: .whitespacesAndNewlines)
        let scanner = Scanner(string: hexString)
        
        if hexString.hasPrefix("#") {
            scanner.scanLocation = 1
        }
        
        var color: UInt32 = 0
        scanner.scanHexInt32(&color)
        
        let mask = 0x000000FF
        let r = Int(color >> 16) & mask
        let g = Int(color >> 8) & mask
        let b = Int(color) & mask
        
        let red   = CGFloat(r) / 255.0
        let green = CGFloat(g) / 255.0
        let blue  = CGFloat(b) / 255.0
        
        self.init(red: red, green: green, blue: blue, alpha: alpha)
    }
    
    /// rgba初始化
    public convenience init(red: Int, green: Int, blue: Int, alpha: CGFloat = 1.0) {
        self.init(
            red: CGFloat(red) / 255.0,
            green: CGFloat(green) / 255.0,
            blue: CGFloat(blue) / 255.0,
            alpha: alpha
        )
    }

    /// UIColor 的十六进制色值
    var hexValue: String {
        var r: CGFloat = 0
        var g: CGFloat = 0
        var b: CGFloat = 0
        var a: CGFloat = 0
        guard getRed(&r, green: &g, blue: &b, alpha: &a) else { return "" }
        if a == 1.0 {
            return String(format: "%0.2X%0.2X%0.2X", UInt(r * 255), UInt(g * 255), UInt(b * 255))
        } else {
            return String(format: "%0.2X%0.2X%0.2X%0.2X", UInt(r * 255), UInt(g * 255), UInt(b * 255), UInt(a * 255))
        }
    }
    
    /// UIColor 的 0~255 区间的 RGB 色值
    var rgbValue: String {
        var r: CGFloat = 0
        var g: CGFloat = 0
        var b: CGFloat = 0
        var a: CGFloat = 0
        guard getRed(&r, green: &g, blue: &b, alpha: &a) else { return "" }
        return "\(UInt(r * 255)),\(UInt(g * 255)),\(UInt(b * 255)),\(UInt(a * 255))"
    }
}

扩展UIButton

extension UIButton {
    
    /// 扩展背景色
    public func setBackgroundColor(_ color: UIColor, for state: UIControlState, size: CGSize = CGSize(width: 1, height: 1)) {
        UIGraphicsBeginImageContext(size)
        defer {
            UIGraphicsEndImageContext()
        }
        let ctx = UIGraphicsGetCurrentContext()
        ctx?.setFillColor(color.cgColor)
        ctx?.fill(CGRect(origin: .zero, size: size))
        guard let image = UIGraphicsGetImageFromCurrentImageContext() else {
            return
        }
        setBackgroundImage(image, for: state)
    }
}

扩展String

extension String {
     
    /// 计算宽高
    public func getSize(_ size: CGSize, attributes: [NSAttributedStringKey: Any]) -> CGSize {
        let rect = NSString(string: self).boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: attributes, context: nil)
        return CGSize(width: ceil(rect.width), height: ceil(rect.height))
    }
}

扩展UIImage

import ImageIO
extension UIImage {
    
    /// 通过颜色创建图片
    public convenience init(_ color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) {
        UIGraphicsBeginImageContext(size)
        defer {
            UIGraphicsEndImageContext()
        }
        let ctx = UIGraphicsGetCurrentContext()
        ctx?.setFillColor(color.cgColor)
        ctx?.fill(CGRect(origin: .zero, size: size))
        guard let cgImage = UIGraphicsGetImageFromCurrentImageContext()?.cgImage else {
            self.init()
            return
        }
        self.init(cgImage: cgImage)
    }
    
    /// 通过字符串创建二维码图片  
    public convenience init?(qrcode: String, op: Any?) {
        /// 创建黑白滤镜
        let filter = CIFilter(name: "CIQRCodeGenerator")
        filter?.setDefaults()
        filter?.setValue(qrcode.data(using: .utf8), forKey: "inputMessage")
        filter?.setValue("H", forKey: "inputCorrectionLevel")
        /// 输出图片
        var image: UIImage? = nil 
        if let ciImage = filter?.outputImage?.transformed(by: CGAffineTransform(scaleX: 20, y: 20)) { 
            image = UIImage(ciImage: ciImage)
            /// 判断是否有logo图
            if let op = op as? (logo: UIImage?, size: CGSize), let logo = op.logo, let size = image?.size {
                /// 绘制logo图
                UIGraphicsBeginImageContext(size) 
                image?.draw(in: CGRect(origin: .zero, size: size)) 
                logo.draw(in: CGRect(
                    x: (size.width - op.size.width) * 0.5,
                    y: (size.height - op.size.height) * 0.5,
                    width: op.size.width,
                    height: op.size.height
                )) 
                image = UIGraphicsGetImageFromCurrentImageContext() 
                UIGraphicsEndImageContext()
            }
        }
        /// 创建图片
        if let ciImage = image?.ciImage {
            self.init(ciImage: ciImage)
        } else if let cgImage = image?.cgImage {
            self.init(cgImage: cgImage)
        } else {
            self.init()
        }
    }
    
    /// 通过gif创建动态图片
    public func gifImage(_ name: String) -> ([UIImage], TimeInterval) {
        guard let path = Bundle.main.path(forResource: name, ofType: "gif"), let data = NSData(contentsOfFile: path), let imageSource = CGImageSourceCreateWithData(data, nil) else {
            return ([], 0)
        }
        let imageCount = CGImageSourceGetCount(imageSource) 
        // 3.遍历所有的图片
        var images = [UIImage]()
        var totalDuration : TimeInterval = 0
        for i in 0..<imageCount {
            guard let cgImage = CGImageSourceCreateImageAtIndex(imageSource, i, nil) else { continue }
            let image = UIImage(cgImage: cgImage)
            images.append(image)
            guard let properties = CGImageSourceCopyPropertiesAtIndex(imageSource, i, nil) as NSDictionary?, let gifDict = properties[kCGImagePropertyGIFDictionary] as? NSDictionary, let frameDuration = gifDict[kCGImagePropertyGIFDelayTime] as? NSNumber else { continue }
            totalDuration += frameDuration.doubleValue
        }
        return (images, totalDuration)
    }
    
    /// 圆形图片
    public func circleImage() -> UIImage {
        
        let shotest = min(size.width, size.height)
        let outputRect = CGRect(x: 0, y: 0, width: shotest, height: shotest)
        UIGraphicsBeginImageContextWithOptions(outputRect.size, false, 0)
        let context = UIGraphicsGetCurrentContext()
        context?.addEllipse(in: outputRect)
        context?.clip()
      
        draw(in: CGRect(
            x: (shotest - size.width) * 0.5,
            y: (shotest - size.height) * 0.5,
            width: size.width,
            height: size.height)
        )
        
        let maskedImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        return maskedImage
    }
}

扩展Array

extension Array {
    
    /// 寻找符合要求的元素
    public func findObj(_ method: (Element)->Bool) -> (Element?, Int) {
        var i = -1
        for obj in self {
            i+=1
            if method(obj) {
                return (obj, i)
            }
        }
        return (nil, i)
    }
    
    /// 移除符合要求的元素
    public mutating func removeObj(_ method: (Element)->Bool) {
        let (_, index) = findObj(method)
        if index > -1 {
            remove(at: index)
        }
    }

    /// 随机元素
    public func random() -> Element? {
        guard self.count > 0 else {
            return nil
        }
        let index = Int(arc4random_uniform(UInt32(self.count)))
        return self[index]
    }
}

扩展UIDevice

extension UIDevice {
    
    /// 设备唯一标识
    public class func idForVendor() -> String {
        return UIDevice.current.identifierForVendor!.uuidString
    }
    
    /// 系统名
    public class func systemName() -> String {
        return UIDevice.current.systemName
    }
    
    /// 系统版本
    public class func systemVersion() -> String {
        return UIDevice.current.systemVersion
    }
    
    /// 设备名
    public class func deviceName() -> String {
        return UIDevice.current.name
    }
    
    /// 设备语音
    public class func deviceLanguage() -> String {
        return Bundle.main.preferredLocalizations[0]
    }
    
    /// 设备型号
    public class func deviceModel() -> String {
        return UIDevice.current.model
    }
    
    /// 设备区域化型号
    public class func deviceLocalizedModel() -> String {
        return UIDevice.current.localizedModel
    }
}

相关文章

网友评论

      本文标题:Swift 扩展

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