From 363aae886005052a553034a9d1506294315e5b8e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BC=A0=E6=99=BA=E6=9D=B0?= Date: Fri, 3 Mar 2017 10:01:07 +0800 Subject: [PATCH] Convert to Swift3, make it more swifty! --- EPCalendar.xcodeproj/project.pbxproj | 6 + EPCalendar/AppDelegate.swift | 12 +- .../EPCalendarPicker/EPCalendarCell1.swift | 18 +- .../EPCalendarConstants.swift | 6 +- .../EPCalendarHeaderView.swift | 12 +- .../EPCalendarPicker/EPCalendarPicker.swift | 154 +++++++------- .../EPCalendarPicker/EPExtensions.swift | 190 +++++++++--------- EPCalendar/ViewController.swift | 14 +- EPCalendarTests/EPCalendarTests.swift | 4 +- 9 files changed, 207 insertions(+), 209 deletions(-) diff --git a/EPCalendar.xcodeproj/project.pbxproj b/EPCalendar.xcodeproj/project.pbxproj index 782bf49..c28f30e 100644 --- a/EPCalendar.xcodeproj/project.pbxproj +++ b/EPCalendar.xcodeproj/project.pbxproj @@ -174,9 +174,11 @@ TargetAttributes = { F4C1C9B81BE7A305001AA643 = { CreatedOnToolsVersion = 7.0; + LastSwiftMigration = 0820; }; F4C1C9CC1BE7A306001AA643 = { CreatedOnToolsVersion = 7.0; + LastSwiftMigration = 0820; TestTargetID = F4C1C9B81BE7A305001AA643; }; }; @@ -366,6 +368,7 @@ LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = com.prabaharan.epcalendar.EPCalendar; PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 3.0; }; name = Debug; }; @@ -377,6 +380,7 @@ LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = com.prabaharan.epcalendar.EPCalendar; PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 3.0; }; name = Release; }; @@ -388,6 +392,7 @@ LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = com.prabaharan.epcalendar.EPCalendarTests; PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 3.0; TEST_HOST = "$(BUILT_PRODUCTS_DIR)/EPCalendar.app/EPCalendar"; }; name = Debug; @@ -400,6 +405,7 @@ LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = com.prabaharan.epcalendar.EPCalendarTests; PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 3.0; TEST_HOST = "$(BUILT_PRODUCTS_DIR)/EPCalendar.app/EPCalendar"; }; name = Release; diff --git a/EPCalendar/AppDelegate.swift b/EPCalendar/AppDelegate.swift index 1055354..80c9c70 100644 --- a/EPCalendar/AppDelegate.swift +++ b/EPCalendar/AppDelegate.swift @@ -14,30 +14,30 @@ class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? - func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { + func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } - func applicationWillResignActive(application: UIApplication) { + func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } - func applicationDidEnterBackground(application: UIApplication) { + func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } - func applicationWillEnterForeground(application: UIApplication) { + func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } - func applicationDidBecomeActive(application: UIApplication) { + func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } - func applicationWillTerminate(application: UIApplication) { + func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } diff --git a/EPCalendar/EPCalendarPicker/EPCalendarCell1.swift b/EPCalendar/EPCalendarPicker/EPCalendarCell1.swift index 5e585e5..01ae013 100644 --- a/EPCalendar/EPCalendarPicker/EPCalendarCell1.swift +++ b/EPCalendar/EPCalendarPicker/EPCalendarCell1.swift @@ -10,7 +10,7 @@ import UIKit class EPCalendarCell1: UICollectionViewCell { - var currentDate: NSDate! + var currentDate: Date! var isCellSelectable: Bool? @IBOutlet weak var lblDay: UILabel! @@ -18,22 +18,22 @@ class EPCalendarCell1: UICollectionViewCell { super.awakeFromNib() } - func selectedForLabelColor(color: UIColor) { + func selectedForLabelColor(_ color: UIColor) { self.lblDay.layer.cornerRadius = self.lblDay.frame.size.width/2 - self.lblDay.layer.backgroundColor = color.CGColor - self.lblDay.textColor = UIColor.whiteColor() + self.lblDay.layer.backgroundColor = color.cgColor + self.lblDay.textColor = UIColor.white } - func deSelectedForLabelColor(color: UIColor) { - self.lblDay.layer.backgroundColor = UIColor.clearColor().CGColor + func deSelectedForLabelColor(_ color: UIColor) { + self.lblDay.layer.backgroundColor = UIColor.clear.cgColor self.lblDay.textColor = color } - func setTodayCellColor(backgroundColor: UIColor) { + func setTodayCellColor(_ backgroundColor: UIColor) { self.lblDay.layer.cornerRadius = self.lblDay.frame.size.width/2 - self.lblDay.layer.backgroundColor = backgroundColor.CGColor - self.lblDay.textColor = UIColor.whiteColor() + self.lblDay.layer.backgroundColor = backgroundColor.cgColor + self.lblDay.textColor = UIColor.white } } diff --git a/EPCalendar/EPCalendarPicker/EPCalendarConstants.swift b/EPCalendar/EPCalendarPicker/EPCalendarConstants.swift index 8adbca5..331e266 100644 --- a/EPCalendar/EPCalendarPicker/EPCalendarConstants.swift +++ b/EPCalendar/EPCalendarPicker/EPCalendarConstants.swift @@ -15,7 +15,7 @@ struct EPDefaults { static let multiSelection = false //Colors - static let dayDisabledTintColor = UIColor.lightGrayColor() + static let dayDisabledTintColor = UIColor.lightGray static let weekdayTintColor = EPColors.EmeraldColor static let weekendTintColor = EPColors.PomegranateColor static let dateSelectionColor = EPColors.PeterRiverColor @@ -23,10 +23,10 @@ struct EPDefaults { static let todayTintColor = EPColors.AmethystColor static let tintColor = EPColors.PomegranateColor - static let barTintColor = UIColor.whiteColor() + static let barTintColor = UIColor.white //HeaderSize - static let headerSize = CGSizeMake(100,60) + static let headerSize = CGSize(width: 100,height: 60) } struct EPColors{ diff --git a/EPCalendar/EPCalendarPicker/EPCalendarHeaderView.swift b/EPCalendar/EPCalendarPicker/EPCalendarHeaderView.swift index 5726665..b64f55a 100644 --- a/EPCalendar/EPCalendarPicker/EPCalendarHeaderView.swift +++ b/EPCalendar/EPCalendarPicker/EPCalendarHeaderView.swift @@ -22,10 +22,10 @@ class EPCalendarHeaderView: UICollectionReusableView { override func awakeFromNib() { super.awakeFromNib() - let calendar = NSCalendar.currentCalendar() + let calendar = Calendar.current let weeksDayList = calendar.shortWeekdaySymbols - if NSCalendar.currentCalendar().firstWeekday == 2 { + if Calendar.current.firstWeekday == 2 { lblFirst.text = weeksDayList[1] lblSecond.text = weeksDayList[2] lblThird.text = weeksDayList[3] @@ -44,9 +44,9 @@ class EPCalendarHeaderView: UICollectionReusableView { } } - func updateWeekendLabelColor(color: UIColor) + func updateWeekendLabelColor(_ color: UIColor) { - if NSCalendar.currentCalendar().firstWeekday == 2 { + if Calendar.current.firstWeekday == 2 { lblSixth.textColor = color lblSeventh.textColor = color } else { @@ -55,8 +55,8 @@ class EPCalendarHeaderView: UICollectionReusableView { } } - func updateWeekdaysLabelColor(color: UIColor) { - if NSCalendar.currentCalendar().firstWeekday == 2 { + func updateWeekdaysLabelColor(_ color: UIColor) { + if Calendar.current.firstWeekday == 2 { lblFirst.textColor = color lblSecond.textColor = color lblThird.textColor = color diff --git a/EPCalendar/EPCalendarPicker/EPCalendarPicker.swift b/EPCalendar/EPCalendarPicker/EPCalendarPicker.swift index 1ffc5b6..07bf996 100644 --- a/EPCalendar/EPCalendarPicker/EPCalendarPicker.swift +++ b/EPCalendar/EPCalendarPicker/EPCalendarPicker.swift @@ -11,39 +11,39 @@ import UIKit private let reuseIdentifier = "Cell" @objc public protocol EPCalendarPickerDelegate{ - optional func epCalendarPicker(_: EPCalendarPicker, didCancel error : NSError) - optional func epCalendarPicker(_: EPCalendarPicker, didSelectDate date : NSDate) - optional func epCalendarPicker(_: EPCalendarPicker, didSelectMultipleDate dates : [NSDate]) + @objc optional func epCalendarPicker(_: EPCalendarPicker, didCancel error : NSError) + @objc optional func epCalendarPicker(_: EPCalendarPicker, didSelectDate date : Date) + @objc optional func epCalendarPicker(_: EPCalendarPicker, didSelectMultipleDate dates : [Date]) } -public class EPCalendarPicker: UICollectionViewController { +open class EPCalendarPicker: UICollectionViewController { - public var calendarDelegate : EPCalendarPickerDelegate? - public var multiSelectEnabled: Bool - public var showsTodaysButton: Bool = true - private var arrSelectedDates = [NSDate]() - public var tintColor: UIColor + open var calendarDelegate : EPCalendarPickerDelegate? + open var multiSelectEnabled: Bool + open var showsTodaysButton: Bool = true + fileprivate var arrSelectedDates = [Date]() + open var tintColor: UIColor - public var dayDisabledTintColor: UIColor - public var weekdayTintColor: UIColor - public var weekendTintColor: UIColor - public var todayTintColor: UIColor - public var dateSelectionColor: UIColor - public var monthTitleColor: UIColor + open var dayDisabledTintColor: UIColor + open var weekdayTintColor: UIColor + open var weekendTintColor: UIColor + open var todayTintColor: UIColor + open var dateSelectionColor: UIColor + open var monthTitleColor: UIColor // new options - public var startDate: NSDate? - public var hightlightsToday: Bool = true - public var hideDaysFromOtherMonth: Bool = false - public var barTintColor: UIColor + open var startDate: Date? + open var hightlightsToday: Bool = true + open var hideDaysFromOtherMonth: Bool = false + open var barTintColor: UIColor - public var backgroundImage: UIImage? - public var backgroundColor: UIColor? + open var backgroundImage: UIImage? + open var backgroundColor: UIColor? - private(set) public var startYear: Int - private(set) public var endYear: Int + fileprivate(set) open var startYear: Int + fileprivate(set) open var endYear: Int - override public func viewDidLoad() { + override open func viewDidLoad() { super.viewDidLoad() // setup Navigationbar @@ -53,17 +53,17 @@ public class EPCalendarPicker: UICollectionViewController { // setup collectionview self.collectionView?.delegate = self - self.collectionView?.backgroundColor = UIColor.clearColor() + self.collectionView?.backgroundColor = UIColor.clear self.collectionView?.showsHorizontalScrollIndicator = false self.collectionView?.showsVerticalScrollIndicator = false // Register cell classes - self.collectionView!.registerNib(UINib(nibName: "EPCalendarCell1", bundle: NSBundle(forClass: EPCalendarPicker.self )), forCellWithReuseIdentifier: reuseIdentifier) - self.collectionView!.registerNib(UINib(nibName: "EPCalendarHeaderView", bundle: NSBundle(forClass: EPCalendarPicker.self )), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "Header") + self.collectionView!.register(UINib(nibName: "EPCalendarCell1", bundle: Bundle(for: EPCalendarPicker.self )), forCellWithReuseIdentifier: reuseIdentifier) + self.collectionView!.register(UINib(nibName: "EPCalendarHeaderView", bundle: Bundle(for: EPCalendarPicker.self )), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "Header") inititlizeBarButtons() - dispatch_async(dispatch_get_main_queue()) { () -> Void in + DispatchQueue.main.async { () -> Void in self.scrollToToday() } @@ -72,7 +72,7 @@ public class EPCalendarPicker: UICollectionViewController { } else if backgroundColor != nil { self.collectionView?.backgroundColor = backgroundColor } else { - self.collectionView?.backgroundColor = UIColor.whiteColor() + self.collectionView?.backgroundColor = UIColor.white } } @@ -80,18 +80,18 @@ public class EPCalendarPicker: UICollectionViewController { func inititlizeBarButtons(){ - let cancelButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Cancel, target: self, action: #selector(EPCalendarPicker.onTouchCancelButton)) + let cancelButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.cancel, target: self, action: #selector(EPCalendarPicker.onTouchCancelButton)) self.navigationItem.leftBarButtonItem = cancelButton var arrayBarButtons = [UIBarButtonItem]() if multiSelectEnabled { - let doneButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done, target: self, action: #selector(EPCalendarPicker.onTouchDoneButton)) + let doneButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.done, target: self, action: #selector(EPCalendarPicker.onTouchDoneButton)) arrayBarButtons.append(doneButton) } if showsTodaysButton { - let todayButton = UIBarButtonItem(title: "Today", style: UIBarButtonItemStyle.Plain, target: self, action:#selector(EPCalendarPicker.onTouchTodayButton)) + let todayButton = UIBarButtonItem(title: "Today", style: UIBarButtonItemStyle.plain, target: self, action:#selector(EPCalendarPicker.onTouchTodayButton)) arrayBarButtons.append(todayButton) todayButton.tintColor = todayTintColor } @@ -100,7 +100,7 @@ public class EPCalendarPicker: UICollectionViewController { } - override public func didReceiveMemoryWarning() { + override open func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @@ -122,7 +122,7 @@ public class EPCalendarPicker: UICollectionViewController { self.init(startYear: EPDefaults.startYear, endYear: EPDefaults.endYear, multiSelection: multiSelection, selectedDates: nil) } - public init(startYear: Int, endYear: Int, multiSelection: Bool, selectedDates: [NSDate]?) { + public init(startYear: Int, endYear: Int, multiSelection: Bool, selectedDates: [Date]?) { self.startYear = startYear self.endYear = endYear @@ -146,7 +146,7 @@ public class EPCalendarPicker: UICollectionViewController { layout.minimumLineSpacing = 1 layout.headerReferenceSize = EPDefaults.headerSize if let _ = selectedDates { - self.arrSelectedDates.appendContentsOf(selectedDates!) + self.arrSelectedDates.append(contentsOf: selectedDates!) } super.init(collectionViewLayout: layout) } @@ -158,7 +158,7 @@ public class EPCalendarPicker: UICollectionViewController { // MARK: UICollectionViewDataSource - override public func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { + override open func numberOfSections(in collectionView: UICollectionView) -> Int { // #warning Incomplete implementation, return the number of sections if startYear > endYear { return 0 @@ -169,61 +169,61 @@ public class EPCalendarPicker: UICollectionViewController { } - override public func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { + override open func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { - let startDate = NSDate(year: startYear, month: 1, day: 1) + let startDate = Date(year: startYear, month: 1, day: 1) let firstDayOfMonth = startDate.dateByAddingMonths(section) - let addingPrefixDaysWithMonthDyas = ( firstDayOfMonth.numberOfDaysInMonth() + firstDayOfMonth.weekday() - NSCalendar.currentCalendar().firstWeekday ) + let addingPrefixDaysWithMonthDyas = (firstDayOfMonth.numberOfDaysInMonth + firstDayOfMonth.weekday - Calendar.current.firstWeekday) let addingSuffixDays = addingPrefixDaysWithMonthDyas%7 var totalNumber = addingPrefixDaysWithMonthDyas if addingSuffixDays != 0 { - totalNumber = totalNumber + (7 - addingSuffixDays) +// totalNumber = totalNumber + (7 - addingSuffixDays) } return totalNumber } - override public func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { + override open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { - let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! EPCalendarCell1 + let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! EPCalendarCell1 - let calendarStartDate = NSDate(year:startYear, month: 1, day: 1) + let calendarStartDate = Date(year:startYear, month: 1, day: 1) let firstDayOfThisMonth = calendarStartDate.dateByAddingMonths(indexPath.section) - let prefixDays = ( firstDayOfThisMonth.weekday() - NSCalendar.currentCalendar().firstWeekday) + let prefixDays = (firstDayOfThisMonth.weekday - Calendar.current.firstWeekday) if indexPath.row >= prefixDays { cell.isCellSelectable = true let currentDate = firstDayOfThisMonth.dateByAddingDays(indexPath.row-prefixDays) - let nextMonthFirstDay = firstDayOfThisMonth.dateByAddingDays(firstDayOfThisMonth.numberOfDaysInMonth()-1) + let nextMonthFirstDay = firstDayOfThisMonth.dateByAddingDays(firstDayOfThisMonth.numberOfDaysInMonth-1) cell.currentDate = currentDate - cell.lblDay.text = "\(currentDate.day())" + cell.lblDay.text = "\(currentDate.day)" if arrSelectedDates.filter({ $0.isDateSameDay(currentDate) - }).count > 0 && (firstDayOfThisMonth.month() == currentDate.month()) { + }).count > 0 && (firstDayOfThisMonth.month == currentDate.month) { cell.selectedForLabelColor(dateSelectionColor) } else{ cell.deSelectedForLabelColor(weekdayTintColor) - if cell.currentDate.isSaturday() || cell.currentDate.isSunday() { + if cell.currentDate.isSaturday || cell.currentDate.isSunday { cell.lblDay.textColor = weekendTintColor } if (currentDate > nextMonthFirstDay) { cell.isCellSelectable = false if hideDaysFromOtherMonth { - cell.lblDay.textColor = UIColor.clearColor() + cell.lblDay.textColor = UIColor.clear } else { cell.lblDay.textColor = self.dayDisabledTintColor } } - if currentDate.isToday() && hightlightsToday { + if currentDate.isToday && hightlightsToday { cell.setTodayCellColor(todayTintColor) } if startDate != nil { - if NSCalendar.currentCalendar().startOfDayForDate(cell.currentDate) < NSCalendar.currentCalendar().startOfDayForDate(startDate!) { + if Calendar.current.startOfDay(for: cell.currentDate) < Calendar.current.startOfDay(for: startDate!) { cell.isCellSelectable = false cell.lblDay.textColor = self.dayDisabledTintColor } @@ -235,45 +235,45 @@ public class EPCalendarPicker: UICollectionViewController { cell.isCellSelectable = false let previousDay = firstDayOfThisMonth.dateByAddingDays(-( prefixDays - indexPath.row)) cell.currentDate = previousDay - cell.lblDay.text = "\(previousDay.day())" + cell.lblDay.text = "\(previousDay.day)" if hideDaysFromOtherMonth { - cell.lblDay.textColor = UIColor.clearColor() + cell.lblDay.textColor = UIColor.clear } else { cell.lblDay.textColor = self.dayDisabledTintColor } } - cell.backgroundColor = UIColor.clearColor() + cell.backgroundColor = UIColor.clear return cell } - func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize + func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize { - let rect = UIScreen.mainScreen().bounds + let rect = UIScreen.main.bounds let screenWidth = rect.size.width - 7 - return CGSizeMake(screenWidth/7, screenWidth/7); + return CGSize(width: screenWidth/7, height: screenWidth/7); } - func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets + func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets { return UIEdgeInsetsMake(5, 0, 5, 0); //top,left,bottom,right } - override public func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView { + override open func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { if kind == UICollectionElementKindSectionHeader { - let header = collectionView.dequeueReusableSupplementaryViewOfKind(UICollectionElementKindSectionHeader, withReuseIdentifier: "Header", forIndexPath: indexPath) as! EPCalendarHeaderView + let header = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "Header", for: indexPath) as! EPCalendarHeaderView - let startDate = NSDate(year: startYear, month: 1, day: 1) + let startDate = Date(year: startYear, month: 1, day: 1) let firstDayOfMonth = startDate.dateByAddingMonths(indexPath.section) - header.lblTitle.text = firstDayOfMonth.monthNameFull() + header.lblTitle.text = firstDayOfMonth.monthNameFull header.lblTitle.textColor = monthTitleColor header.updateWeekdaysLabelColor(weekdayTintColor) header.updateWeekendLabelColor(weekendTintColor) - header.backgroundColor = UIColor.clearColor() + header.backgroundColor = UIColor.clear return header; } @@ -281,12 +281,12 @@ public class EPCalendarPicker: UICollectionViewController { return UICollectionReusableView() } - override public func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { - let cell = collectionView.cellForItemAtIndexPath(indexPath) as! EPCalendarCell1 + override open func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { + let cell = collectionView.cellForItem(at: indexPath) as! EPCalendarCell1 if !multiSelectEnabled && cell.isCellSelectable! { calendarDelegate?.epCalendarPicker!(self, didSelectDate: cell.currentDate) cell.selectedForLabelColor(dateSelectionColor) - dismissViewControllerAnimated(true, completion: nil) + dismiss(animated: true, completion: nil) return } @@ -296,7 +296,7 @@ public class EPCalendarPicker: UICollectionViewController { arrSelectedDates.append(cell.currentDate) cell.selectedForLabelColor(dateSelectionColor) - if cell.currentDate.isToday() { + if cell.currentDate.isToday { cell.setTodayCellColor(dateSelectionColor) } } @@ -304,13 +304,13 @@ public class EPCalendarPicker: UICollectionViewController { arrSelectedDates = arrSelectedDates.filter(){ return !($0.isDateSameDay(cell.currentDate)) } - if cell.currentDate.isSaturday() || cell.currentDate.isSunday() { + if cell.currentDate.isSaturday || cell.currentDate.isSunday { cell.deSelectedForLabelColor(weekendTintColor) } else { cell.deSelectedForLabelColor(weekdayTintColor) } - if cell.currentDate.isToday() && hightlightsToday{ + if cell.currentDate.isToday && hightlightsToday{ cell.setTodayCellColor(todayTintColor) } } @@ -323,14 +323,14 @@ public class EPCalendarPicker: UICollectionViewController { internal func onTouchCancelButton() { //TODO: Create a cancel delegate calendarDelegate?.epCalendarPicker!(self, didCancel: NSError(domain: "EPCalendarPickerErrorDomain", code: 2, userInfo: [ NSLocalizedDescriptionKey: "User Canceled Selection"])) - dismissViewControllerAnimated(true, completion: nil) + dismiss(animated: true, completion: nil) } internal func onTouchDoneButton() { //gathers all the selected dates and pass it to the delegate calendarDelegate?.epCalendarPicker!(self, didSelectMultipleDate: arrSelectedDates) - dismissViewControllerAnimated(true, completion: nil) + dismiss(animated: true, completion: nil) } internal func onTouchTodayButton() { @@ -338,17 +338,17 @@ public class EPCalendarPicker: UICollectionViewController { } - public func scrollToToday () { - let today = NSDate() + open func scrollToToday () { + let today = Date() scrollToMonthForDate(today) } - public func scrollToMonthForDate (date: NSDate) { + open func scrollToMonthForDate (_ date: Date) { - let month = date.month() - let year = date.year() + let month = date.month + let year = date.year let section = ((year - startYear) * 12) + month - let indexPath = NSIndexPath(forRow:1, inSection: section-1) + let indexPath = IndexPath(row:1, section: section-1) self.collectionView?.scrollToIndexpathByShowingHeader(indexPath) } diff --git a/EPCalendar/EPCalendarPicker/EPExtensions.swift b/EPCalendar/EPCalendarPicker/EPExtensions.swift index 0739cd2..2a47492 100644 --- a/EPCalendar/EPCalendarPicker/EPExtensions.swift +++ b/EPCalendar/EPCalendarPicker/EPExtensions.swift @@ -6,37 +6,36 @@ // Copyright © 2015 Prabaharan Elangovan. All rights reserved. // -import Foundation import UIKit //MARK: UIViewController Extensions extension UIViewController { - func showAlert(message: String) { + func showAlert(_ message: String) { showAlert(message, andTitle: "") } - func showAlert(message: String, andTitle title: String) { - let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert) + func showAlert(_ message: String, andTitle title: String) { + let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert) // add an action (button) - alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)) + alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)) // show the alert - self.presentViewController(alert, animated: true, completion: nil) + self.present(alert, animated: true, completion: nil) } } //MARK: UICollectionView Extension extension UICollectionView { - func scrollToIndexpathByShowingHeader(indexPath: NSIndexPath) { - let sections = self.numberOfSections() + func scrollToIndexpathByShowingHeader(_ indexPath: IndexPath) { + let sections = self.numberOfSections if indexPath.section <= sections{ - let attributes = self.layoutAttributesForSupplementaryElementOfKind(UICollectionElementKindSectionHeader, atIndexPath: indexPath) - let topOfHeader = CGPointMake(0, attributes!.frame.origin.y - self.contentInset.top) + let attributes = self.layoutAttributesForSupplementaryElement(ofKind: UICollectionElementKindSectionHeader, at: indexPath) + let topOfHeader = CGPoint(x: 0, y: attributes!.frame.origin.y - self.contentInset.top) self.setContentOffset(topOfHeader, animated:false) } } @@ -44,162 +43,155 @@ extension UICollectionView { //MARK: NSDate Extensions -extension NSDate { +extension Date { func sharedCalendar(){ } - func firstDayOfMonth () -> NSDate { - let calendar = NSCalendar.currentCalendar() - let dateComponent = calendar.components([.Year, .Month, .Day ], fromDate: self) + var firstDayOfMonth: Date { + let calendar = Calendar.current + var dateComponent = calendar.dateComponents([.year, .month, .day], from: self) dateComponent.day = 1 - return calendar.dateFromComponents(dateComponent)! + return calendar.date(from: dateComponent)! } - convenience init(year : Int, month : Int, day : Int) { - - let calendar = NSCalendar.currentCalendar() - let dateComponent = NSDateComponents() + init(year : Int, month : Int, day : Int) { + let calendar = Calendar.current + var dateComponent = DateComponents() dateComponent.year = year dateComponent.month = month dateComponent.day = day - self.init(timeInterval:0, sinceDate:calendar.dateFromComponents(dateComponent)!) + self = Date(timeInterval: 0, since: calendar.date(from: dateComponent)!) } - func dateByAddingMonths(months : Int ) -> NSDate { - let calendar = NSCalendar.currentCalendar() - let dateComponent = NSDateComponents() - dateComponent.month = months - return calendar.dateByAddingComponents(dateComponent, toDate: self, options: NSCalendarOptions.MatchNextTime)! + func dateByAddingMonths(_ months : Int ) -> Date { + return Calendar.current.date(byAdding: .month, value: months, to: self)! } - func dateByAddingDays(days : Int ) -> NSDate { - let calendar = NSCalendar.currentCalendar() - let dateComponent = NSDateComponents() - dateComponent.day = days - return calendar.dateByAddingComponents(dateComponent, toDate: self, options: NSCalendarOptions.MatchNextTime)! + func dateByAddingDays(_ days : Int ) -> Date { + return Calendar.current.date(byAdding: .day, value: days, to: self)! + } - func hour() -> Int { - let calendar = NSCalendar.currentCalendar() - let dateComponent = calendar.components(.Hour, fromDate: self) - return dateComponent.hour + var hour: Int { + let calendar = Calendar.current + let dateComponent = calendar.dateComponents([.hour], from: self) + return dateComponent.hour! } - func second() -> Int { - let calendar = NSCalendar.currentCalendar() - let dateComponent = calendar.components(.Second, fromDate: self) - return dateComponent.second + var second: Int { + let calendar = Calendar.current + let dateComponent = calendar.dateComponents([.second], from: self) + return dateComponent.second! } - func minute() -> Int { - let calendar = NSCalendar.currentCalendar() - let dateComponent = calendar.components(.Minute, fromDate: self) - return dateComponent.minute + var minute: Int { + let calendar = Calendar.current + let dateComponent = calendar.dateComponents([.minute], from: self) + return dateComponent.minute! } - func day() -> Int { - let calendar = NSCalendar.currentCalendar() - let dateComponent = calendar.components(.Day, fromDate: self) - return dateComponent.day + var day: Int { + let calendar = Calendar.current + let dateComponent = calendar.dateComponents([.day], from: self) + return dateComponent.day! } - func weekday() -> Int { - let calendar = NSCalendar.currentCalendar() - let dateComponent = calendar.components(.Weekday, fromDate: self) - return dateComponent.weekday + var weekday: Int { + let calendar = Calendar.current + let dateComponent = calendar.dateComponents([.weekday], from: self) + return dateComponent.weekday! } - func month() -> Int { - let calendar = NSCalendar.currentCalendar() - let dateComponent = calendar.components(.Month, fromDate: self) - return dateComponent.month + var month: Int { + let calendar = Calendar.current + let dateComponent = calendar.dateComponents([.month], from: self) + return dateComponent.month! } - func year() -> Int { - let calendar = NSCalendar.currentCalendar() - let dateComponent = calendar.components(.Year, fromDate: self) - return dateComponent.year + var year: Int { + let calendar = Calendar.current + let dateComponent = calendar.dateComponents([.year], from: self) + return dateComponent.year! } - func numberOfDaysInMonth() -> Int { - let calendar = NSCalendar.currentCalendar() - let days = calendar.rangeOfUnit(NSCalendarUnit.Day, inUnit: NSCalendarUnit.Month, forDate: self) - return days.length + var numberOfDaysInMonth: Int { + let calendar = Calendar.current + let days = calendar.range(of: .day, in: .month, for: self)! + return days.count } - func dateByIgnoringTime() -> NSDate { - let calendar = NSCalendar.currentCalendar() - let dateComponent = calendar.components([.Year, .Month, .Day ], fromDate: self) - return calendar.dateFromComponents(dateComponent)! + var dateByIgnoringTime: Date { + let calendar = Calendar.current + let dateComponent = calendar.dateComponents([.year, .month, .day], from: self) + return calendar.date(from: dateComponent)! } - func monthNameFull() -> String { - let dateFormatter = NSDateFormatter() + var monthNameFull: String { + let dateFormatter = DateFormatter() dateFormatter.dateFormat = "MMMM YYYY" - return dateFormatter.stringFromDate(self) + return dateFormatter.string(from: self) } - func isSunday() -> Bool + var isSunday: Bool { - return (self.getWeekday() == 1) + return (self.getWeekday == 1) } - func isMonday() -> Bool + var isMonday: Bool { - return (self.getWeekday() == 2) + return (self.getWeekday == 2) } - func isTuesday() -> Bool + var isTuesday: Bool { - return (self.getWeekday() == 3) + return (self.getWeekday == 3) } - func isWednesday() -> Bool + var isWednesday: Bool { - return (self.getWeekday() == 4) + return (self.getWeekday == 4) } - func isThursday() -> Bool + var isThursday: Bool { - return (self.getWeekday() == 5) + return (self.getWeekday == 5) } - func isFriday() -> Bool + var isFriday: Bool { - return (self.getWeekday() == 6) + return (self.getWeekday == 6) } - func isSaturday() -> Bool + var isSaturday: Bool { - return (self.getWeekday() == 7) + return (self.getWeekday == 7) } - func getWeekday() -> Int { - let calendar = NSCalendar.currentCalendar() - return calendar.components( .Weekday, fromDate: self).weekday + var getWeekday: Int { + let calendar = Calendar.current + return calendar.dateComponents([.weekday], from: self).weekday! } - func isToday() -> Bool { - return self.isDateSameDay(NSDate()) + var isToday: Bool { + return self.isDateSameDay(Date()) } - func isDateSameDay(date: NSDate) -> Bool { + func isDateSameDay(_ date: Date) -> Bool { - return (self.day() == date.day()) && (self.month() == date.month() && (self.year() == date.year())) + return (self.day == date.day) && (self.month == date.month && (self.year == date.year)) } -} -func ==(lhs: NSDate, rhs: NSDate) -> Bool { - return lhs.compare(rhs) == NSComparisonResult.OrderedSame + + static func <(lhs: Date, rhs: Date) -> Bool { + return lhs.compare(rhs) == ComparisonResult.orderedAscending + } + + static func >(lhs: Date, rhs: Date) -> Bool { + return rhs.compare(lhs) == ComparisonResult.orderedAscending + } } -func <(lhs: NSDate, rhs: NSDate) -> Bool { - return lhs.compare(rhs) == NSComparisonResult.OrderedAscending -} -func >(lhs: NSDate, rhs: NSDate) -> Bool { - return rhs.compare(lhs) == NSComparisonResult.OrderedAscending -} \ No newline at end of file diff --git a/EPCalendar/ViewController.swift b/EPCalendar/ViewController.swift index 38b7356..dd0e607 100644 --- a/EPCalendar/ViewController.swift +++ b/EPCalendar/ViewController.swift @@ -23,34 +23,34 @@ class ViewController: UIViewController, EPCalendarPickerDelegate { // Dispose of any resources that can be recreated. } - @IBAction func onTouchShowMeCalendarButton(sender: AnyObject) { + @IBAction func onTouchShowMeCalendarButton(_ sender: AnyObject) { let calendarPicker = EPCalendarPicker(startYear: 2016, endYear: 2017, multiSelection: true, selectedDates: []) calendarPicker.calendarDelegate = self - calendarPicker.startDate = NSDate() + calendarPicker.startDate = Date() calendarPicker.hightlightsToday = true calendarPicker.showsTodaysButton = true calendarPicker.hideDaysFromOtherMonth = true - calendarPicker.tintColor = UIColor.orangeColor() + calendarPicker.tintColor = UIColor.orange // calendarPicker.barTintColor = UIColor.greenColor() - calendarPicker.dayDisabledTintColor = UIColor.grayColor() + calendarPicker.dayDisabledTintColor = UIColor.gray calendarPicker.title = "Date Picker" // calendarPicker.backgroundImage = UIImage(named: "background_image") // calendarPicker.backgroundColor = UIColor.blueColor() let navigationController = UINavigationController(rootViewController: calendarPicker) - self.presentViewController(navigationController, animated: true, completion: nil) + self.present(navigationController, animated: true, completion: nil) } func epCalendarPicker(_: EPCalendarPicker, didCancel error : NSError) { txtViewDetail.text = "User cancelled selection" } - func epCalendarPicker(_: EPCalendarPicker, didSelectDate date : NSDate) { + func epCalendarPicker(_: EPCalendarPicker, didSelectDate date : Date) { txtViewDetail.text = "User selected date: \n\(date)" } - func epCalendarPicker(_: EPCalendarPicker, didSelectMultipleDate dates : [NSDate]) { + func epCalendarPicker(_: EPCalendarPicker, didSelectMultipleDate dates : [Date]) { txtViewDetail.text = "User selected dates: \n\(dates)" } diff --git a/EPCalendarTests/EPCalendarTests.swift b/EPCalendarTests/EPCalendarTests.swift index 793bb83..74cf614 100644 --- a/EPCalendarTests/EPCalendarTests.swift +++ b/EPCalendarTests/EPCalendarTests.swift @@ -25,9 +25,9 @@ class EPCalendarTests: XCTestCase { let calendarPicker = EPCalendarPicker(startYear: 2000, endYear: 2001, multiSelection: true) let navigationController = UINavigationController(rootViewController: calendarPicker) - UIViewController().presentViewController(navigationController, animated: true, completion: nil) + UIViewController().present(navigationController, animated: true, completion: nil) - let numOfSections = calendarPicker.collectionView?.numberOfSections() + let numOfSections = calendarPicker.collectionView?.numberOfSections XCTAssertEqual(numOfSections, 24)