Swift3-扩展方法

扩展的写法

  • 因为Swift 不需要在使用相应的头文件的时候引入头文件所以可以把这些扩展方法写到同一个文件中,这个是和OC的区别, 例子:

    // 扩展 String 类型
    
    extension String {
    
    }
    
    // 扩展UILabel
    
    extension UILabel {
    
    }
    

扩展String

  1. 获取字符串的高度

    func getTextHeight(font:CGFloat,width:CGFloat) -> CGFloat {
         
         let normalText = self as NSString
         
         let size = CGSize(width: width, height: CGFloat(MAXFLOAT))
         
         let fontS = UIFont.systemFont(ofSize: font)
         
         let dic = NSDictionary(object: fontS, forKey: NSFontAttributeName as NSCopying)
         
         let stringSize = normalText.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: dic as? [String : AnyObject], context:nil).size
         
         return stringSize.height
         
    }
    
  2. 获取字符串的长度

    func getTexWidth(font:CGFloat,height:CGFloat) -> CGFloat {
         
         let normalText: NSString = self as NSString
         
         let size = CGSize(width: CGFloat(MAXFLOAT), height: height)
         
         let fontS = UIFont.systemFont(ofSize: font)
         
         let dic = NSDictionary(object: fontS, forKey: NSFontAttributeName as NSCopying)
         
         let stringSize = normalText.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: dic as? [String : AnyObject], context:nil).size
         
         return stringSize.width
         
    }
    
  3. MD5 加密

    var md5 : 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 ..< digestLen {
             
            hash.appendFormat("%02x", result[i])
             
        }
         
        result.deinitialize()
         
        return String(format: hash as String)
         
    }
    
  4. 汉字转拼音(需要消耗不少性能,注意使用)

    func transformToPinYin() -> String {
         
        let mutableString = NSMutableString(string: self)
         
        //把汉字转为拼音
         
        CFStringTransform(mutableString, nil, kCFStringTransformToLatin, false)
         
        //去掉拼音的音标
         
        CFStringTransform(mutableString, nil, kCFStringTransformStripDiacritics, false)
         
        let string = String(mutableString)
         
        //去掉空格
         
        return string.replacingOccurrences(of: " ", with: "")
        
    }
    

把这些方法全部放到下面的的代码里面,即可使用

// 扩展 String 类型
  
extension String {
  
}

扩展UILabel

  1. 修改UILabel的行间距

    func modifyTheLineSpacing(distance: CGFloat) {
         
         let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: self.text!)
         
         let paragraphStyle: NSMutableParagraphStyle = NSMutableParagraphStyle()
         
         paragraphStyle.lineSpacing = distance       // 调整行间距
         
         attributedString.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: NSMakeRange(0, (self.text! as NSString).length))
         
         self.attributedText = attributedString;
         
    }
    
  2. 修改字体颜色

    func changeTheTextColor(textColor: UIColor, textFont: CGFloat, range: NSRange) {
         
         let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: self.text!)
         
         let attris: [String: AnyObject] = [
             
             NSForegroundColorAttributeName: textColor,
             
             NSFontAttributeName: UIFont.systemFont(ofSize: textFont),
             
             NSBackgroundColorAttributeName: self.backgroundColor!
             
         ]
         
         attributedString.addAttributes(attris, range: range)
         
         self.attributedText = attributedString;
         
    }
    

把这些方法全部放到下面的的代码里面,即可使用

// 扩展 String 类型
  
extension UILabel {
  
}

扩展UIView

写在扩展前面,因为我比较喜欢使用Frame布局,没有使用Xib,SB,Autolayout等, 一开始使用布局的时候都是使用

self.view.frame.size.with + self.view.frame.origin.x

这样布局, 写着很累,对UIView进行扩展之后,想要和上面的代码拥有相同的效果便很简单了

self.view.maxX

是不是很简单?

UIView进行扩展

extension UIView {
    
    // 获取view左边的坐标
    
    var minX: CGFloat {
        
        return self.frame.origin.x
        
    }
    
    // 获取view右边的坐标
    
    var maxX: CGFloat {
        
        return self.frame.origin.x + self.frame.size.width
        
    }
    
    // 获取view上边的坐标
    
    var minY: CGFloat {
        
        return self.frame.origin.y
        
    }
    
    // 获取view下边的坐标
    
    var maxY: CGFloat {
        
        return self.frame.origin.y + self.frame.size.height
        
    }
    
    // 获取view的x轴的中心点
    
    var centerX: CGFloat {
        
        return self.center.x
        
    }
    
    // 获取view的y轴的中心点
    
    var centerY: CGFloat {
        
        return self.center.y
        
    }
    
    // 获取view的宽度
    
    var width: CGFloat {
        
        return self.frame.size.width
        
    }
    
    // 获取view的高度
    
    var height: CGFloat {
        
        return self.frame.size.height
        
    }
    
    // 获取view的size
    
    var size: CGSize {
        
        return self.frame.size
        
    }

}

使用方法很简单,比如

//获取View的高度

self.view.height

//获取View的宽度

self.view.width

扩展UIImage

extension UIImage{
    
    // 重设图片大小
    
    func changeImageSize(size:CGSize) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(size,false,UIScreen.main.scale);
        
        self.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
        
        let resizeImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        
        UIGraphicsEndImageContext();
        
        return resizeImage;
    }
    
    // 等比例缩放
    
    func scaleImage(scaleSize:CGFloat) -> UIImage {
        
        let reSize = CGSize(width: self.size.width * scaleSize, height: self.size.height * scaleSize)
        
        return changeImageSize(size: reSize)
        
    }
    
}

扩展UIColor

当设计师给的16进制颜色的时候便可以调用下面的方法

extension UIColor {
    
    convenience init(hexString: String) {
        
        // 存储转换后的数值
        
        var red:UInt32 = 0, green:UInt32 = 0, blue:UInt32 = 0
        
        // 分别转换进行转换
        
        Scanner(string: hexString[0..<2]).scanHexInt32(&red)
        
        Scanner(string: hexString[2..<4]).scanHexInt32(&green)
        
        Scanner(string: hexString[4..<6]).scanHexInt32(&blue)
        
        self.init(red: CGFloat(red)/255.0, green: CGFloat(green)/255.0, blue: CGFloat(blue)/255.0, alpha: 1.0)
    }
    
    
    convenience init(hexString: String, alpha: CGFloat) {
        
        // 存储转换后的数值
        
        var red:UInt32 = 0, green:UInt32 = 0, blue:UInt32 = 0
        
        // 分别转换进行转换
        
        Scanner(string: hexString[0..<2]).scanHexInt32(&red)
        
        Scanner(string: hexString[2..<4]).scanHexInt32(&green)
        
        Scanner(string: hexString[4..<6]).scanHexInt32(&blue)
        
        self.init(red: CGFloat(red)/255.0, green: CGFloat(green)/255.0, blue: CGFloat(blue)/255.0, alpha: alpha)
    }
    
}

使用方法

imageView.backgroundColor = UIColor(hexString: "eeeeee")

扩展 提示框 UIAlertController

extension UIAlertController {
    
    class func createUIAlertController(title: String?, message: String?, leftButton: String, rightButton: String, complete: @escaping () -> Void) -> UIAlertController{
        
        let av = UIAlertController(title: title, message: message, preferredStyle: .alert)
        
        let cancel = UIAlertAction(title: leftButton, style: .cancel, handler: nil)
        
        let confirm = UIAlertAction(title: rightButton, style: .destructive, handler: { (action) in
            
            complete()
          
        })
        
        av.addAction(cancel)
        
        av.addAction(confirm)
        
        return av
        
    }

    
    class func createUIAlertController(title: String?, message: String?, leftButton: String, rightButton: String, cancel: @escaping() -> Void, complete: @escaping () -> Void) -> UIAlertController{
        
        let av = UIAlertController(title: title, message: message, preferredStyle: .alert)
        
        let cancel = UIAlertAction(title: leftButton, style: .cancel) { (action) in
            
            cancel()
            
        }
        
        let confirm = UIAlertAction(title: rightButton, style: .destructive, handler: { (action) in
            
            complete()
           
        })
        
        av.addAction(cancel)
        
        av.addAction(confirm)
        
        return av
        
    }

}

使用方法

self.present(UIAlertController.createUIAlertController(title: "提示", message: "扩展到这里就结束了", leftButton: "取消", rightButton: "确定", cancel: {
                
                // 点击取消的按钮
                
            }, complete: {
                
                // 点击确定的按钮
                
            })
                , animated: true, completion: nil)

你可能感兴趣的:(Swift3-扩展方法)