分享一些Swift的干货

Array+Extension

   mutating func arrayFromArray(_ arr:Array) {
        for item  in arr {
            self.append(item)
        }
    }

Color+Extension

extension  UIColor
{
    class func colorWithCustom(_ r: CGFloat, g:CGFloat, b:CGFloat, alpha : CGFloat = 1) -> UIColor {
        return UIColor(red: r / 255.0, green: g / 255.0, blue: b / 255.0, alpha: alpha)
    }
    
    class func randomColor() -> UIColor {
        let r = CGFloat(arc4random_uniform(256))
        let g = CGFloat(arc4random_uniform(256))
        let b = CGFloat(arc4random_uniform(256))
        return UIColor.colorWithCustom(r, g: g, b: b)
    }          
    
   class func colorWithHexString (_ hex:String, alpha: CGFloat = 1.0)-> UIColor {
                                                                                                                                                                                                                                                           
    var formatted = hex.replacingOccurrences(of: "0x", with: "")
    formatted = formatted.replacingOccurrences(of: "#", with: "")
    if let hex = Int(formatted, radix: 16) {
        let red = CGFloat(CGFloat((hex & 0xFF0000) >> 16)/255.0)
        let green = CGFloat(CGFloat((hex & 0x00FF00) >> 8)/255.0)
        let blue = CGFloat(CGFloat((hex & 0x0000FF) >> 0)/255.0)
        return UIColor(red: red, green: green, blue: blue, alpha: alpha)
        
    } else {
        return UIColor.white
    }
    
  }
    

}

NSDateEXT+Lunar

 extension Date{

    static fileprivate let lunarDayStrs = ["初一","初二","初三","初四","初五","初六","初七","初八","初九","初十",
        "十一","十二","十三","十四","十五","十六","十七","十八","十九","二十",
        "廿一","廿二","廿三","廿四","廿五","廿六","廿七","廿八","廿九","三十","卅一","卅二"]
    static fileprivate let lunarMonthStrs = ["春节","二月","三月","四月","五月","六月","七月","八月","九月","十月","冬月","腊月"]
    

    /**
     
     公历转化为农历
     */
    public static func Conventer2lunarStr(_ solar: Date) -> String{
        let cal = Calendar(identifier: Calendar.Identifier.chinese)
        let unitFlag = NSCalendar.Unit.day.rawValue | NSCalendar.Unit.month.rawValue
        let components = (cal as NSCalendar).components(NSCalendar.Unit(rawValue: unitFlag), from: solar)
        if components.day != 1 {
            return lunarDayStrs[components.day! - 1]
        }
        else{
            return lunarMonthStrs[components.month! - 1]
        }
    }


}

NSDateEXT

 extension Date{
    
    /**
     获取数字的Date
     
     
     - returns: <#return value description#>
     */
    public static func getDateforInt(year : Int, month : Int, day: Int) -> Date{
        let dateFormatter:DateFormatter = DateFormatter();
        
        dateFormatter.dateFormat = "yyyy-MM-dd";
        var currentDay = day
        let tempDate:Date? = dateFormatter.date(from: String(format:"%04d-%02d-%02d",year,month,1));
        assert(tempDate != nil, "输入的时期是无效的")
        if day > Date.getDateMonthDayCount(tempDate!) {
            currentDay = Date.getDateMonthDayCount(tempDate!)
        }
        
        
        let dayDate:Date? = dateFormatter.date(from: String(format:"%04d-%02d-%02d",year,month,currentDay));
        
        assert(dayDate != nil, "输入的时期是无效的")
        return dayDate!
        
        
    }
    
    /**
     获取每月的天数count
     */
    public static func getDateMonthDayCount (_ date:Date) -> Int{
        let range = (Calendar.current as NSCalendar).range(of: NSCalendar.Unit.day, in: NSCalendar.Unit.month, for: date)
        return range.length
    }
    
    
    
    /**
     获取该月的每一天
     */
    public static func getDateMonthDays (_ date : Date) ->Array {
        
        let count = self .getDateMonthDayCount(date)
        let year = date.yearHPPData();
        let month = date.monthHPPData()
        
        var days :Array = []
        for i in 1 ..< count + 1 {
            
            let day = i
            
            days.append(Date.getDateforInt(year: year, month: month, day: day))
        }
        return days
        
    }
    
    
    /**
     获取该月的第一天是周几
     */
    public static func getDateMonthFirstDayIsWeedDay (_ date:Date) -> Int{
        
        
        return Date.getWeekDay(year: date.yearHPPData(), month: date.monthHPPData(), day: 1);
    }
    
    /**
     获取某一天 的 星期状态
     
     - parameter year:  年
     - parameter month: 月
     - parameter day:   日
     
     - returns: weakday
     */
    //    public class func getWeekDay(year year:Int,month:Int,day:Int) ->Int{
    //        let dateFormatter:NSDateFormatter = NSDateFormatter();
    //        dateFormatter.dateFormat = "yyyy/MM/dd";
    //        let date:NSDate? = dateFormatter.dateFromString(String(format:"%04d/%02d/%02d",year,month,day));
    //        if date != nil {
    //            let calendar:NSCalendar = NSCalendar.currentCalendar()
    //            let dateComp:NSDateComponents = calendar.components(NSCalendarUnit.Weekday, fromDate: date!)
    //            return dateComp.weekday;
    //        }
    //        return 0;
    //    }
    
    public static func getWeekDay(year:Int,month:Int,day:Int) ->Int{
        let dateFmt = DateFormatter()
        dateFmt.dateFormat =  "yyyy/MM/dd HH:mm:ss"
        
        
        let date = dateFmt.date(from: String(format:"%04d/%02d/%02d 12:00:00",year,month,day))
        let interval = Int(date!.timeIntervalSince1970)
        let days = Int(interval/86400) // 24*60*60
        let weekday = ((days + 4)%7+7)%7
        return weekday == 0 ? 7 : weekday
    }
    
    /**
     获取某一天 的 星期状态
     
     - returns: weakday
     */
    public static func getWeekDay(_ date : Date) -> Int{
        return Date.getWeekDay(year: date.yearHPPData(), month: date.monthHPPData(), day: date.dayHPPData());
    }
    
    /**
     年
     
     - returns: 年
     */
    public func yearHPPData() -> Int {
        let calendar:Calendar = Calendar.current
        let dateComp:DateComponents = (calendar as NSCalendar).components(NSCalendar.Unit.year, from: self)
        return dateComp.year!;
        
    }
    /**
     月
     
     - returns: 月
     */
    public func monthHPPData() -> Int {
        let calendar:Calendar = Calendar.current
        let dateComp:DateComponents = (calendar as NSCalendar).components(NSCalendar.Unit.month, from: self)
        return dateComp.month!;
        
    }
    /**
     日
     
     - returns: 日
     */
    public func dayHPPData() -> Int {
        let calendar:Calendar = Calendar.current
        let dateComp:DateComponents = (calendar as NSCalendar).components(NSCalendar.Unit.day, from: self)
        return dateComp.day!;
        
    }
    /**
     上个月
     
     - returns:
     */
    public func proMonth() -> Date{
        let calendar = Calendar.current
        
        let dateComponents = (calendar as NSCalendar).components([NSCalendar.Unit.year,NSCalendar.Unit.month,NSCalendar.Unit.day], from: self)
        let year = dateComponents.year
        let month = dateComponents.month
        let day = dateComponents.day
        
        if (dateComponents.month == 1){
            return Date.getDateforInt(year: year! - NSInteger(1), month: 12, day: day!)
        }
        return Date.getDateforInt(year: dateComponents.year!, month:month! - NSInteger(1) , day: day!)
        
        
    }
    /**
     下个月
     
     - returns: <#return value description#>
     */
    public func nextMonth() -> Date{
        
        //        let dateComponents = NSDateComponents()
        //        dateComponents.month += 1
        //        let newDate = NSCalendar.currentCalendar().dateByAddingComponents(dateComponents, toDate: self, options: NSCalendarOptions.WrapComponents)
        //        return newDate!
        let calendar = Calendar.current
        
        let dateComponents = (calendar as NSCalendar).components([NSCalendar.Unit.year,NSCalendar.Unit.month,NSCalendar.Unit.day], from: self)
        
        
        let year = dateComponents.year
        let month = dateComponents.month
        let day = dateComponents.day
        if(dateComponents.month == 12){
            return Date.getDateforInt(year: year! + NSInteger(1), month: 1, day: day!)
            
            
        }
        
        return Date.getDateforInt(year: dateComponents.year!, month:month! + NSInteger(1) , day: day!)
        
        
    }
    
    /**
     传入一个时间格式  返回字符串时间
     
     */
    public func dateWithformatter(_ formatterString: String) ->String {
        
        let fmt = DateFormatter()
        fmt.dateFormat = formatterString
        return fmt.string(from: self)
        
    }
    
    
    /**
     是否是今天
     */
    public func isTodayHPPData() -> Bool {
        
        let today = Date()
        return (self.yearHPPData() == today.yearHPPData()  && self.monthHPPData() == today.monthHPPData() && self.dayHPPData() == today.dayHPPData())
        
    }
    
    
    /** String转时间戳 13位
     */
    func stringTotimeTamp() -> String {
        let dateStamp:TimeInterval = self.timeIntervalSince1970*1000
        let dateSt:Int64 = Int64(dateStamp)
        return String(dateSt)
    }

    
    /**
     返回精确到天的时间戳
     */
    func toDayTampString() -> String  {
        
        let dateStr = self.toString(format: "yyyy-MM-dd")
        let date = Date(fromString: dateStr, format:  "yyyy-MM-dd")
        let dateStamp:TimeInterval = date!.timeIntervalSince1970*1000
        let dateSt:Int64 = Int64(dateStamp)
//        let str = String(dateSt) as NSString
//        var s =  str.substringToIndex(7);
//        s = s.stringByAppendingString("000000")
        return String(dateSt)
    }
    
    
    
}

NSObject+Extension

extension  NSObject
{

    func alertShow(_ title: String,canel:String, sure:String,sureBlock :@escaping (() -> ()),canelBlcok: @escaping (() -> ()))  {
        
        //        UIViewController.
        let alertController = UIAlertController(title: nil, message: title, preferredStyle: .alert)
        
        let xiangcetAction = UIAlertAction(title: sure, style: .default, handler:{   alertAction in
            sureBlock()
            
        })
     
        let canelAction = UIAlertAction(title: canel, style: .cancel, handler: {  alertAction in
            canelBlcok()
        })
        alertController.addAction(xiangcetAction)
        alertController.addAction(canelAction)
      
        UIApplication.shared.keyWindow?.rootViewController!.present(alertController, animated: true, completion: nil)
        
        
    }
    
    
    
    func delay(_ delay:Double, closure:@escaping ()->()) {
        DispatchQueue.main.asyncAfter(
            deadline: DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: closure)
    }
    
}



你可能感兴趣的:(博客)