欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Swift中extension的使用

程序员文章站 2024-03-17 21:52:16
...

由于swift中不可以使用宏定义,UI给的颜色标值,有的喜欢使用RGB有的直接 f5f5f5,所以声明两个UIcolor的extension方法

RGB

public static func RGB(R:Float,G:Float,B:Float,Alp:Float) -> UIColor {
        print(CGFloat(R/255))
        return UIColor.init(red: CGFloat(R/255.0), green: CGFloat(G/255.0), blue: CGFloat(B/255.0), alpha: CGFloat(Alp));
    }

HexStr

 public static func colorWithString(colorStr:NSString) -> UIColor{
        var cString = colorStr.trimmingCharacters(in: CharacterSet.ReferenceType.whitespacesAndNewlines) as String
        if (cString.count < 6) {
            return UIColor.clear
        }
        if cString.hasPrefix("0X") {
            cString  = String(cString[cString.index(cString.startIndex, offsetBy: 2)...])
        }
        if cString.hasPrefix("#") {
            cString  = String(cString[cString.index(cString.startIndex, offsetBy: 1)...])
        }
        
        if (cString.count != 6) {
            return UIColor.clear
        }
        let rstr = cString.mySubstring(start: 0, length: 2)
        let gstr = cString.mySubstring(start: 2, length: 2)
        let bstr = cString.mySubstring(start: 4, length: 2)
        
        var R = CUnsignedInt(),G = CUnsignedInt(),B = CUnsignedInt()
        Scanner.init(string: rstr).scanHexInt32(&R)
        Scanner.init(string: gstr).scanHexInt32(&G)
        Scanner.init(string: bstr).scanHexInt32(&B)
        return UIColor.init(red: CGFloat(R)/255.0, green: CGFloat(G)/255.0, blue: CGFloat(B)/255.0, alpha: CGFloat(1));
    }

swift里边字符串截取,个人感觉没有OC里边使用的方便

在下标为6 的字符开始截取,(包含下标为6的字符)效果与OC中substringFromIndex相同

        let hellor = "Hello,World"
        /*
         hellor.index("起始位置", offsetBy: "在起始位置偏移")
         */
        let myIndex = hellor.index(hellor.startIndex, offsetBy: 6)
        let subStr = String(hellor[myIndex..<hellor.endIndex])
        print(subStr)
        /*
         打印结果
         World
         */

在下标为0开始截取到下标为5的字符(..<不包括下标为5字符 ...包括下标为5字符)效果与OC中substringToIndex相同

        let myIndex = hellor.index(hellor.startIndex, offsetBy: 5)
        var subStr = String(hellor[..<myIndex])
        print(subStr)
        /*
         打印结果
            Hello
         */
        subStr = String(hellor[...myIndex])
        print(subStr)
        /*
         打印结果
            Hello,
         */

在指定位置向后截取指定长度的字符(包含指定位置的字符)效果与OC中的substringWithRange相同

        let startIndex = hellor.index(hellor.startIndex, offsetBy: 6)
        let len = hellor.index(startIndex, offsetBy: 3)
        let subStr = String(hellor[startIndex..<len])
        print(subStr)
        /*  打印结果
            Wor
         */

获取第一个满足指定字符之前的所有字符string.index(of: Character)

    let subStr = String(hellor[..<(hellor.index(of: ",") ?? hellor.endIndex)])
        print(subStr)
        /*
         Hello
         */

获取第一个满足指定字符之后的所有字符

 //向后偏移一个单位
        let stIndex = hellor.index((hellor.index(of: ",") ?? hellor.endIndex), offsetBy: 1)
        
        let subStr = String(hellor[stIndex..<hellor.endIndex])
        print(subStr)
        /*
         World
         */

个人感觉没有OC的简便。可以封装下使用,使用extension实现下

func mySubstring(to index:NSInteger) -> String {
        return String(self[..<self.index(self.startIndex, offsetBy: index)])
    }

        let hellor = "Hello,World"
        hellor.mySubstring(from: 3)
        hellor.mySubstring(to: 3)
        hellor.mySubstring(after: ",")
        hellor.mySubstring(before: ",")
        hellor.mySubstring(start: 2, length: 3)

其他功能的extension

  • 判断是否是准确手机号、邮箱、身份证号、连接
func isMobileNumber() -> Bool{}
func isEmailAddress() -> Bool {}
func simpleVerifyIdentityCardNum() -> Bool {}
func isValidUrl() -> Bool {}
  • 有时在开发中会遇到图片放大的展示功能,比如评论下的图片
//图片放大
    func showImage() -> Void {
        let image = self.image
        let window = UIApplication.shared.keyWindow
        let backgroundView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: (window?.frame.size.width)!, height: (window?.frame.size.height)!))
        
        backgroundView.backgroundColor = UIColor.init(white: 0.441, alpha: 1.00)
        backgroundView.alpha = 0.0
        
        
        let imageView = UIImageView.init(frame: self.convert(self.bounds, to: window))
        imageView.image = image
        imageView.contentMode = UIViewContentMode.scaleAspectFit
        imageView.tag = 1
        backgroundView.addSubview(imageView)
        window?.addSubview(backgroundView)
        
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(self.hideImage(tap:)))
        backgroundView.addGestureRecognizer(tap)
        
        UIView.animate(withDuration: 0.3, animations: {
            imageView.center = backgroundView.center
            backgroundView.alpha = 1
        }) { (finished) in
        }
    }

swift中不能声明宏定义,可以创建一个Const.swift文件
常量使用let声明,带有参数的使用方法实现,可以用类方法,在方法名前添加class或者static二选一

static func IsYESStrEmpty(obj:NSString?) -> Bool{}
class func IsNotStrEmpty( obj:NSString?) -> Bool{}

示例代码