1. 程式人生 > >iOS swift

iOS swift

原文:

http://blog.csdn.net/liulicsdn/article/details/44244567

http://blog.sina.com.cn/s/blog_71715bf80102vfl7.html

在以前的C 和 OC 中經常使用巨集常亮,簡化程式碼。swift 可以直接建一個swift 檔案,寫在裡面的常亮可以全域性呼叫。

// 當前系統版本 
let  version = (UIDevice.currentDevice().systemVersion as NSString).floatValue

// 螢幕寬度
let screenHeight = UIScreen.mainScreen().bounds.height
// 螢幕高度
let screenWidth = UIScreen.mainScreen().bounds.width
// 預設圖片
let defaultImg = UIImage(named: "photo_define")
// NSUserDefault
let userDefault = NSUserDefaults.standardUserDefaults()
// 通知中心
let notice = NSNotificationCenter.defaultCenter()
//判斷是不是plus
let currentModeSize = UIScreen.mainScreen().currentMode?.size
let isPlus = UIScreen.instancesRespondToSelector("currentMode") ? CGSizeEqualToSize(CGSizeMake(1242, 2208), currentModeSize!) : false
//判斷字串是否為空
func trimString(#str:String)->String{
    var nowStr = str.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
    return nowStr
}

//去除空格和回車
func trimLineString(#str:String)->String{
    var nowStr = str.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
    return nowStr
}
//根據鍵盤監控  獲取鍵盤高度
func getKeyBoardHeight(#aNotification:NSNotification)->CGFloat{
    var uInfo   = aNotification.userInfo as NSDictionary!
    let avalue = uInfo["UIKeyboardFrameEndUserInfoKey"] as NSValue
    let keyrect : CGRect = avalue.CGRectValue()
    let keyheight : CGFloat = keyrect.size.height;
    return keyheight
}
//獲取目錄下儲存的json檔案並解析為集合
func getNativeJson(#filename : String,#fileext : String)->AnyObject{
    let pathsBun = NSBundle.mainBundle()
    let paths = pathsBun.pathForResource(filename, ofType : fileext)
    var errors:NSError?
    var content : NSData = NSData(contentsOfFile: paths!, options : .DataReadingMappedIfSafe, error: nil)!
    var returneddata: AnyObject?  = NSJSONSerialization.JSONObjectWithData(content as NSData, options:NSJSONReadingOptions.MutableContainers, error:&errors)
        return returneddata!
}
//訊息提醒
func showAlertView(#title:String,#message:String)
{
    var alert = UIAlertView()
    alert.title = title
    alert.message = message
    alert.addButtonWithTitle("好")
    alert.show()
}
//獲取本地儲存資料
func get_userDefaults(#key : String)->AnyObject?{
  
    var saveStr : AnyObject! = userDefault.objectForKey(key)
    saveStr = (saveStr == nil) ? "" : saveStr
    return saveStr
}
//儲存資料
func save_userDefaults(#key : String,#value:AnyObject?){
    
    userDefault.setObject(value!, forKey:key)
}
//字串轉陣列
func stringToArray(#str:String)->NSArray{
    var dataArray:[String] = []
    for items in str{
        dataArray.append("\(items)")
    }
    return dataArray
}

還有RGBA

func RGBA (r:CGFloat, g:CGFloat, b:CGFloat, a:CGFloat) { return UIColor (red: r/255.0, green: g/255.0, blue: b/255.0, alpha: a) }
使用方式:
var theColor : UIColor = RGBA (255, 255, 0, 1)