美文网首页Swift
Swift: 常用的Extension

Swift: 常用的Extension

作者: 一欧Yiou | 来源:发表于2018-05-25 14:39 被阅读35次

    String的拓展

    extension String {
        //获取文字的宽度
        func getStringWidth(text: String, font: UIFont) -> CGFloat {
            let textSize = text.size(withAttributes: [NSAttributedStringKey.font: font])
            return textSize.width
        }
    
        //获取文字的高度(需要一个最大宽度)
        func getStringHeight(font: UIFont, maxWidth: CGFloat) -> CGFloat {
            let rect = self.boundingRect(with: CGSize.init(width: maxWidth, height: CGFloat(MAXFLOAT)), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSAttributedStringKey.font: font], context: nil)
            return rect.height
        }
    
        func stringToNumber() -> Double {
            let str = self
            var number: Double = 0
            
            if let num = Double(str) {
                number = num
            }
            
            return number
        }
        
        func stringToPercent() -> Double {
            let str = self
            var number: Double = 0
            
            if let num = Double(str) {
                number = num
            }
            
            return number/100
        }
    }
    

    UIColor的拓展

    extension UIColor {
        convenience init(hex:Int32) {
            self.init(hex: hex, alpha: 1)
        }
        //0x000000   
        convenience init(hex:Int32, alpha:CGFloat = 1) {
            let r = CGFloat((hex & 0xff0000) >> 16) / 255
            let g = CGFloat((hex & 0xff00) >> 8) / 255
            let b = CGFloat(hex & 0xff) / 255
            self.init(red: r, green: g, blue: b, alpha: alpha)
        }
    }
    

    UIImage的拓展

    extension UIImage {
        //用颜色生成图片
        convenience init(color: UIColor) {
            let size = CGSize(width: 1, height: 1)
            UIGraphicsBeginImageContext(size)
            let path = UIBezierPath(rect: CGRect(origin: .zero, size: size))
            color.set()
            path.fill()
            let image: UIImage! = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            self.init(cgImage: (image.cgImage)!)
        }
        
        //将图片百分比缩放(不是指大小)
        func convevt(quality: Float) -> UIImage? {
            if let data = UIImageJPEGRepresentation(self, CGFloat(quality)), let photo = UIImage(data: data) {
                return photo
            }
            return nil
        }
        
        //将图片缩放宽高(参数自定义)
        func reSizeImage() -> UIImage {
            //UIGraphicsBeginImageContext(reSize);
            let reSize = CGSize.init(width: 1000, height: 1000)
            UIGraphicsBeginImageContextWithOptions(reSize, false, UIScreen.main.scale);
            self.draw(in: CGRect.init(x: 0, y: 0, width: reSize.width, height: reSize.height))
            let reSizeImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()!;
            UIGraphicsEndImageContext();
            return reSizeImage;
        }
        
        //将图片裁成正方形(仍可自定义)
        func reCutImage() -> UIImage {
            let fixOrientationImage = self.fixOrientation()
            let cutFrame = CGRect.init(x: 0, y: (fixOrientationImage.size.height - fixOrientationImage.size.width) / 2, width: fixOrientationImage.size.width, height: fixOrientationImage.size.width)
            return UIImage.init(cgImage: (fixOrientationImage.cgImage?.cropping(to: cutFrame))!)
        }
        
        //调整图片的旋转方向   (回正)
        func fixOrientation() -> UIImage {
            if self.imageOrientation == .up {
                return self
            }
            
            var transform = CGAffineTransform.identity
            
            switch self.imageOrientation {
            case .down, .downMirrored:
                transform = transform.translatedBy(x: self.size.width, y: self.size.height)
                transform = transform.rotated(by: .pi)
                break
                
            case .left, .leftMirrored:
                transform = transform.translatedBy(x: self.size.width, y: 0)
                transform = transform.rotated(by: .pi / 2)
                break
                
            case .right, .rightMirrored:
                transform = transform.translatedBy(x: 0, y: self.size.height)
                transform = transform.rotated(by: -.pi / 2)
                break
                
            default:
                break
            }
            
            switch self.imageOrientation {
            case .upMirrored, .downMirrored:
                transform = transform.translatedBy(x: self.size.width, y: 0)
                transform = transform.scaledBy(x: -1, y: 1)
                break
                
            case .leftMirrored, .rightMirrored:
                transform = transform.translatedBy(x: self.size.height, y: 0);
                transform = transform.scaledBy(x: -1, y: 1)
                break
                
            default:
                break
            }
            
            let ctx = CGContext(data: nil, width: Int(self.size.width), height: Int(self.size.height), bitsPerComponent: self.cgImage!.bitsPerComponent, bytesPerRow: 0, space: self.cgImage!.colorSpace!, bitmapInfo: self.cgImage!.bitmapInfo.rawValue)
            ctx?.concatenate(transform)
            
            switch self.imageOrientation {
            case .left, .leftMirrored, .right, .rightMirrored:
                ctx?.draw(self.cgImage!, in: CGRect(x: CGFloat(0), y: CGFloat(0), width: CGFloat(size.height), height: CGFloat(size.width)))
                break
                
            default:
                ctx?.draw(self.cgImage!, in: CGRect(x: CGFloat(0), y: CGFloat(0), width: CGFloat(size.width), height: CGFloat(size.height)))
                break
            }
            
            let cgimg: CGImage = (ctx?.makeImage())!
            let img = UIImage(cgImage: cgimg)
            
            return img
        }
    }
    

    UIButton的拓展

    extension UIButton {
        func setBackgroundColor(_ color: UIColor, for states: UIControlState) {
            self.setBackgroundImage(self.createImage(color), for: states)
        }
        
        private func createImage(_ color: UIColor) -> UIImage {
            let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
            UIGraphicsBeginImageContext(rect.size)
            let context = UIGraphicsGetCurrentContext()
            context?.setFillColor(color.cgColor)
            context?.fill(rect)
            let colorImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            return colorImage!
        }
    }
    

    UITableView和UICollectionView的cell注册(方便注册Xib写的Cell)

    extension UICollectionView {
        public func registerNib(_ nibName: String) {
            let nib = UINib(nibName: nibName, bundle: Bundle.main)
            register(nib, forCellWithReuseIdentifier: nibName)
        }
        
        public func registerClass(_ className: String) {
            register(NSClassFromString(className).self, forCellWithReuseIdentifier: className)
        }
        
        public func registerNib(_ nibName: String, identifier: String) {
            let nib = UINib(nibName: nibName, bundle: Bundle.main)
            register(nib, forCellWithReuseIdentifier: identifier)
        }
    }
    
    extension UITableView {
        public func registerNib(_ nibName: String) {
            let nib = UINib(nibName: nibName, bundle: Bundle.main)
            register(nib, forCellReuseIdentifier: nibName)
        }
        
        public func registerClass(_ className: String) {
            register(NSClassFromString(className), forCellReuseIdentifier: className)
        }
    }
    

    UIStoryboard的拓展

    extension UIStoryboard {
        static public let Main = UIStoryboard.init(name: "Main", bundle: Bundle.main)
    //    static public let PG2 = UIStoryboard.init(name: "PG2", bundle: Bundle.main)
    }
    

    相关文章

      网友评论

        本文标题:Swift: 常用的Extension

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