Swift

Swift常用全局函数

2016-08-25  本文已影响250人  叫我困兽
  1. 输出日志
/** 输出日志
 * parameter message:  日志消息
 * parameter file:     文件名
 * parameter function:   方法名
 * parameter line:     代码行数
 */
func log(message: String,
         function: String = #function,
         file: String = #file,
         line: Int = #line) {
    
    print("Message \"\(message)\" (File: \(file), Function: \(function), Line: \(line))")
}
  1. RGB色值转UICollor
/** RGB色值设置
 * parameter r: 红色色值
 * parameter g: 绿色色值
 * parameter b: 蓝色色值
 * parameter a: 透明度
 */
func RGB (r:CGFloat,
           g:CGFloat,
           b:CGFloat,
           alpha:CGFloat) -> UIColor
{
    return UIColor (red: r/225.0, green: g/225.0, blue: b/225.0, alpha: alpha)
}
  1. 获取系统版本及版本判断
/** 获取系统版本 */
func IOSVersion() -> Double {
       //  swfit 2.3
//    return (UIDevice.currentDevice().systemVersion as NSString).doubleValue
       //  swfit 3.0
    return (UIDevice.current.systemVersion as NSString).doubleValue
}
/** 是否大于iOS7.0 */
func IS_IOS7() -> Bool {
    return IOSVersion() >= 7.0
}
/** 是否大于iOS8.0 */
func IS_IOS8() -> Bool {
    return IOSVersion() >= 8.0
}
  1. 根据类名创建控制器
/**  根据类名创建控制器
 *  parameter className 控制器名称
 */
func ClassFromString(className: String) -> UIViewController? {
// swfit 2.3
//    let appName = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleName")
// swfit 3.0
    let appName = Bundle.main.object(forInfoDictionaryKey: "CFBundleName")

    let name = "\(appName!).\(className)"
    if let tmpClass = NSClassFromString(name) as? UIViewController.Type {
        return tmpClass.init()
    }else {
        return nil
    }
}
  1. 文字大小设置
/**  文字大小设置
 *  parameter name 字体名字 (为空时默认字体)
 *  parameter size 字体大小
 */
func kFont(name: String, size: CGFloat) -> UIFont {
    if !kIsEmpty(name) {
        return UIFont.init(name: name, size: size)!
    }else {
           //swfit 2.3
//        return UIFont.systemFontOfSize(size)
           //swfit 3.0
           return UIFont.systemFont(ofSize: size)
    }
}
  1. 判断字符串是否为空
/** 判断字符串是否为空 */
func kIsEmpty(string: String) -> Bool {
    if string.isEmpty || string == "" {
        return true
    }else {
        return false
    }
}

7.屏幕的宽高

/** 屏幕的宽 */
func kIphone_Width() -> CGFloat {
  // swift 2.3
//    return UIScreen.mainScreen().bounds.width
  // swift 3.0
  return UIScreen.main.bounds.width
}

/** 屏幕的高 */
func kIphone_Height() -> CGFloat {
      // swift 2.3
//    return UIScreen.mainScreen().bounds.height
  // swift 3.0
  return UIScreen.main.bounds.height
}
上一篇 下一篇

猜你喜欢

热点阅读