From 1041002eec834b369cce44b338995081f0dd65b0 Mon Sep 17 00:00:00 2001 From: Guillaume Bellut Date: Mon, 4 Jul 2016 18:42:43 +0200 Subject: [PATCH] Swift 3 compatibility. --- Example/Example.xcodeproj/project.pbxproj | 6 ++ Example/Example/AppDelegate.swift | 12 ++-- Example/Example/Base.lproj/Main.storyboard | 77 ++++++++++++++-------- Example/Example/ConfigViewController.swift | 28 ++++---- Example/Example/ViewController.swift | 28 ++++---- Example/ExampleTests/ExampleTests.swift | 2 +- TouchVisualizer.xcodeproj/project.pbxproj | 3 + TouchVisualizer/Configuration.swift | 6 +- TouchVisualizer/TouchView.swift | 26 ++++---- TouchVisualizer/UIWindow+Swizzle.swift | 8 +-- TouchVisualizer/Visualizer.swift | 64 +++++++++--------- 11 files changed, 147 insertions(+), 113 deletions(-) diff --git a/Example/Example.xcodeproj/project.pbxproj b/Example/Example.xcodeproj/project.pbxproj index 962c5c1..29b69d1 100644 --- a/Example/Example.xcodeproj/project.pbxproj +++ b/Example/Example.xcodeproj/project.pbxproj @@ -190,9 +190,11 @@ TargetAttributes = { FF828F141A74E52500DC12EF = { CreatedOnToolsVersion = 6.1.1; + LastSwiftMigration = 0800; }; FF828F291A74E52500DC12EF = { CreatedOnToolsVersion = 6.1.1; + LastSwiftMigration = 0800; TestTargetID = FF828F141A74E52500DC12EF; }; }; @@ -383,6 +385,7 @@ PRODUCT_BUNDLE_IDENTIFIER = "com.molabo.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_NAME = "$(TARGET_NAME)"; PROVISIONING_PROFILE = ""; + SWIFT_VERSION = 3.0; TARGETED_DEVICE_FAMILY = "1,2"; }; name = Debug; @@ -400,6 +403,7 @@ PRODUCT_BUNDLE_IDENTIFIER = "com.molabo.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_NAME = "$(TARGET_NAME)"; PROVISIONING_PROFILE = ""; + SWIFT_VERSION = 3.0; TARGETED_DEVICE_FAMILY = "1,2"; }; name = Release; @@ -420,6 +424,7 @@ LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = "com.molabo.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 3.0; TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Example.app/Example"; }; name = Debug; @@ -436,6 +441,7 @@ LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = "com.molabo.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 3.0; TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Example.app/Example"; }; name = Release; diff --git a/Example/Example/AppDelegate.swift b/Example/Example/AppDelegate.swift index 559b2a7..919f5d2 100644 --- a/Example/Example/AppDelegate.swift +++ b/Example/Example/AppDelegate.swift @@ -13,7 +13,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? - func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { + func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // It's the simpest way! Visualizer.start() @@ -30,25 +30,25 @@ class AppDelegate: UIResponder, UIApplicationDelegate { 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/Example/Example/Base.lproj/Main.storyboard b/Example/Example/Base.lproj/Main.storyboard index dea16aa..c1a0f0e 100644 --- a/Example/Example/Base.lproj/Main.storyboard +++ b/Example/Example/Base.lproj/Main.storyboard @@ -1,7 +1,9 @@ - + - + + + @@ -11,65 +13,77 @@ - + + + + + + + @@ -80,42 +94,51 @@ + + + + + + @@ -132,12 +155,12 @@ - + - + @@ -161,25 +184,29 @@ - + - + + + @@ -202,7 +229,7 @@ - + @@ -220,28 +247,26 @@ - + - - + - + - + diff --git a/Example/Example/ConfigViewController.swift b/Example/Example/ConfigViewController.swift index 6ae13a7..2325f16 100644 --- a/Example/Example/ConfigViewController.swift +++ b/Example/Example/ConfigViewController.swift @@ -28,7 +28,7 @@ final class ConfigViewController: UITableViewController { // MARK: - Life Cycle - override func viewDidAppear(animated: Bool) { + override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) Visualizer.start() updateCells() @@ -36,11 +36,11 @@ final class ConfigViewController: UITableViewController { // MARK: - TableView Delegate - override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { + override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { - tableView.deselectRowAtIndexPath(indexPath, animated: true) + tableView.deselectRow(at: indexPath, animated: true) - let cell = tableView.cellForRowAtIndexPath(indexPath) + let cell = tableView.cellForRow(at: indexPath) if cell == timerCell { config.showsTimer = !config.showsTimer @@ -50,10 +50,10 @@ final class ConfigViewController: UITableViewController { let controller = UIAlertController( title: "Warning", message: "This property doesn't work on the simulator because it is not possible to read touch radius on it. Please test it on device.", - preferredStyle: .Alert + preferredStyle: .alert ) - controller.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: nil)) - self.presentViewController(controller, animated: true, completion: nil) + controller.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil)) + self.present(controller, animated: true, completion: nil) return } config.showsTouchRadius = !config.showsTouchRadius @@ -78,11 +78,11 @@ final class ConfigViewController: UITableViewController { func updateCells() { let boolCells = [timerCell, touchRadiusCell, logCell] for cell in boolCells { - cell.detailTextLabel?.text = "false" + cell?.detailTextLabel?.text = "false" } let checkmarkCells = [blueColorCell, redColorCell, greenColorCell] for cell in checkmarkCells { - cell.accessoryType = .None + cell?.accessoryType = .none } if config.showsTimer { @@ -95,23 +95,23 @@ final class ConfigViewController: UITableViewController { logCell.detailTextLabel?.text = "true" } if config.color == colors["blue"] { - blueColorCell.accessoryType = .Checkmark + blueColorCell.accessoryType = .checkmark } else if config.color == colors["red"] { - redColorCell.accessoryType = .Checkmark + redColorCell.accessoryType = .checkmark } else if config.color == colors["green"] { - greenColorCell.accessoryType = .Checkmark + greenColorCell.accessoryType = .checkmark } } // MARK: - Actions @IBAction func cancelButtonTapped(sender: UIBarButtonItem) { - dismissViewControllerAnimated(true, completion: nil) + dismiss(animated: true, completion: nil) Visualizer.start() } @IBAction func doneButtonTapped(sender: UIBarButtonItem) { - self.dismissViewControllerAnimated(true, completion: nil) + self.dismiss(animated: true, completion: nil) } func isSimulator() -> Bool { diff --git a/Example/Example/ViewController.swift b/Example/Example/ViewController.swift index a06bc43..9fb627c 100644 --- a/Example/Example/ViewController.swift +++ b/Example/Example/ViewController.swift @@ -12,7 +12,7 @@ class ViewController: UITableViewController { // MARK: - Life Cycle - override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { + override func prepare(for segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "PushToDetail" { let viewController = segue.destinationViewController as! DetailViewController if let cell = sender as? UITableViewCell { @@ -23,12 +23,12 @@ class ViewController: UITableViewController { // MARK: - TableView DataSource - override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { + override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 100 } - override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { - let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) + override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { + let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) cell.textLabel?.text = "Smooth scrolling!" cell.detailTextLabel?.text = "\(indexPath.row)" return cell @@ -37,38 +37,38 @@ class ViewController: UITableViewController { // MARK: - Actions @IBAction func rightBarButtonItemTapped(sender: AnyObject) { - let alertAction = UIAlertAction(title: "Show Alert", style: .Default, handler: { [unowned self] (alertAction) -> Void in + let alertAction = UIAlertAction(title: "Show Alert", style: .default, handler: { [unowned self] (alertAction) -> Void in let controller = UIAlertController( title: "Alert", message: "Even when alert shows, your tap is visible.", - preferredStyle: .Alert + preferredStyle: .alert ) - controller.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: nil)) - self.presentViewController(controller, animated: true, completion: nil) + controller.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil)) + self.present(controller, animated: true, completion: nil) }) var startOrStopTitle = "Start Visualizer" if Visualizer.isEnabled() { startOrStopTitle = "Stop Visualizer" } - let startOrStopAction = UIAlertAction(title: startOrStopTitle, style: .Default, handler: { [unowned self] (alertAction) -> Void in + let startOrStopAction = UIAlertAction(title: startOrStopTitle, style: .default, handler: { [unowned self] (alertAction) -> Void in if Visualizer.isEnabled() { Visualizer.stop() - self.navigationItem.leftBarButtonItem?.enabled = false + self.navigationItem.leftBarButtonItem?.isEnabled = false } else { Visualizer.start() - self.navigationItem.leftBarButtonItem?.enabled = true + self.navigationItem.leftBarButtonItem?.isEnabled = true } }) let controller = UIAlertController( title: "ActionSheet", message: "Even when action sheet shows, your tap is visible.", - preferredStyle: .ActionSheet + preferredStyle: .actionSheet ) controller.addAction(alertAction) controller.addAction(startOrStopAction) - controller.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)) - self.presentViewController(controller, animated: true, completion: nil) + controller.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) + self.present(controller, animated: true, completion: nil) } } diff --git a/Example/ExampleTests/ExampleTests.swift b/Example/ExampleTests/ExampleTests.swift index 32f85d2..0d08298 100644 --- a/Example/ExampleTests/ExampleTests.swift +++ b/Example/ExampleTests/ExampleTests.swift @@ -28,7 +28,7 @@ class ExampleTests: XCTestCase { func testPerformanceExample() { // This is an example of a performance test case. - self.measureBlock() { + self.measure() { // Put the code you want to measure the time of here. } } diff --git a/TouchVisualizer.xcodeproj/project.pbxproj b/TouchVisualizer.xcodeproj/project.pbxproj index 53b2e7b..f58e708 100644 --- a/TouchVisualizer.xcodeproj/project.pbxproj +++ b/TouchVisualizer.xcodeproj/project.pbxproj @@ -117,6 +117,7 @@ TargetAttributes = { FF1A1A9E1AFF6C2200267156 = { CreatedOnToolsVersion = 6.4; + LastSwiftMigration = 0800; }; }; }; @@ -267,6 +268,7 @@ PRODUCT_NAME = "$(TARGET_NAME)"; SKIP_INSTALL = YES; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 3.0; }; name = Debug; }; @@ -284,6 +286,7 @@ PRODUCT_BUNDLE_IDENTIFIER = "com.molabo.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_NAME = "$(TARGET_NAME)"; SKIP_INSTALL = YES; + SWIFT_VERSION = 3.0; }; name = Release; }; diff --git a/TouchVisualizer/Configuration.swift b/TouchVisualizer/Configuration.swift index 4481d0f..29b05b6 100644 --- a/TouchVisualizer/Configuration.swift +++ b/TouchVisualizer/Configuration.swift @@ -21,12 +21,12 @@ public struct Configuration { UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0) let contextRef = UIGraphicsGetCurrentContext() - CGContextSetFillColorWithColor(contextRef, Constants.defaultColor.CGColor) - CGContextFillEllipseInRect(contextRef, rect) + contextRef?.setFillColor(Constants.defaultColor.cgColor) + contextRef?.fillEllipse(in: rect) var image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() - return image.imageWithRenderingMode(.AlwaysTemplate) + return image?.withRenderingMode(.alwaysTemplate) }() /** diff --git a/TouchVisualizer/TouchView.swift b/TouchVisualizer/TouchView.swift index cfad162..28739a8 100644 --- a/TouchVisualizer/TouchView.swift +++ b/TouchVisualizer/TouchView.swift @@ -9,10 +9,10 @@ final public class TouchView: UIImageView { // MARK: - Public Variables internal weak var touch: UITouch? - private weak var timer: NSTimer? + private weak var timer: Timer? private var _config: Configuration private var previousRatio: CGFloat = 1.0 - private var startDate: NSDate? + private var startDate: Date? private var lastTimeString: String! public var config: Configuration { @@ -30,13 +30,13 @@ final public class TouchView: UIImageView { let bottom: CGFloat = 8.0 var label = UILabel() - label.frame = CGRect(x: -(size.width - CGRectGetWidth(self.frame)) / 2, + label.frame = CGRect(x: -(size.width - self.frame.width) / 2, y: -size.height - bottom, width: size.width, height: size.height) label.font = UIFont(name: "Helvetica", size: 24.0) - label.textAlignment = .Center + label.textAlignment = .center self.addSubview(label) return label @@ -44,7 +44,7 @@ final public class TouchView: UIImageView { // MARK: - Object life cycle convenience init() { - self.init(frame: CGRectZero) + self.init(frame: CGRect.zero) } override init(frame: CGRect) { @@ -69,12 +69,12 @@ final public class TouchView: UIImageView { layer.transform = CATransform3DIdentity previousRatio = 1.0 frame = CGRect(origin: frame.origin, size: _config.defaultSize) - startDate = NSDate() - timer = NSTimer.scheduledTimerWithTimeInterval(1.0 / 60.0, target: self, selector: #selector(self.update(_:)), userInfo: nil, repeats: true) + startDate = Date() + timer = Timer.scheduledTimer(timeInterval: 1.0 / 60.0, target: self, selector: #selector(self.update(_:)), userInfo: nil, repeats: true) - NSRunLoop - .mainRunLoop() - .addTimer(timer!, forMode: NSRunLoopCommonModes) + RunLoop + .main() + .add(timer!, forMode: RunLoopMode.commonModes) if _config.showsTimer { timerLabel.alpha = 1.0 @@ -90,9 +90,9 @@ final public class TouchView: UIImageView { } // MARK: - Update Functions - internal func update(timer: NSTimer) { + internal func update(_ timer: Timer) { if let startDate = startDate { - let interval = NSDate().timeIntervalSinceDate(startDate) + let interval = Date().timeIntervalSince(startDate) let timeString = String(format: "%.02f", Float(interval)) timerLabel.text = timeString } @@ -111,4 +111,4 @@ final public class TouchView: UIImageView { } } } -} \ No newline at end of file +} diff --git a/TouchVisualizer/UIWindow+Swizzle.swift b/TouchVisualizer/UIWindow+Swizzle.swift index 331b23b..3ee9358 100644 --- a/TouchVisualizer/UIWindow+Swizzle.swift +++ b/TouchVisualizer/UIWindow+Swizzle.swift @@ -11,8 +11,8 @@ extension UIWindow { } public func swizzle() { - let range = self.description.rangeOfString(swizzlingMessage, options: .LiteralSearch, range: nil, locale: nil) - if (range?.startIndex != nil) { + let range = self.description.range(of: swizzlingMessage, options: .literalSearch, range: nil, locale: nil) + if (range?.lowerBound != nil) { return } @@ -25,7 +25,7 @@ extension UIWindow { method_exchangeImplementations(description, swizzledDescription) } - public func swizzledSendEvent(event: UIEvent) { + public func swizzledSendEvent(_ event: UIEvent) { Visualizer.sharedInstance.handleEvent(event) swizzledSendEvent(event) } @@ -33,4 +33,4 @@ extension UIWindow { public func swizzledDescription() -> String { return swizzledDescription() + "; " + swizzlingMessage } -} \ No newline at end of file +} diff --git a/TouchVisualizer/Visualizer.swift b/TouchVisualizer/Visualizer.swift index 75d1620..2a9ec6d 100644 --- a/TouchVisualizer/Visualizer.swift +++ b/TouchVisualizer/Visualizer.swift @@ -17,33 +17,33 @@ final public class Visualizer:NSObject { // MARK: - Object life cycle private override init() { super.init() - NSNotificationCenter - .defaultCenter() - .addObserver(self, selector: #selector(Visualizer.orientationDidChangeNotification(_:)), name: UIDeviceOrientationDidChangeNotification, object: nil) + NotificationCenter + .default() + .addObserver(self, selector: #selector(Visualizer.orientationDidChangeNotification(_:)), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil) - NSNotificationCenter - .defaultCenter() - .addObserver(self, selector: #selector(Visualizer.applicationDidBecomeActiveNotification(_:)), name: UIApplicationDidBecomeActiveNotification, object: nil) + NotificationCenter + .default() + .addObserver(self, selector: #selector(Visualizer.applicationDidBecomeActiveNotification(_:)), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil) UIDevice - .currentDevice() + .current() .beginGeneratingDeviceOrientationNotifications() warnIfSimulator() } deinit { - NSNotificationCenter - .defaultCenter() + NotificationCenter + .default() .removeObserver(self) } // MARK: - Helper Functions - @objc internal func applicationDidBecomeActiveNotification(notification: NSNotification) { - UIApplication.sharedApplication().keyWindow?.swizzle() + @objc internal func applicationDidBecomeActiveNotification(_ notification: Notification) { + UIApplication.shared().keyWindow?.swizzle() } - @objc internal func orientationDidChangeNotification(notification: NSNotification) { + @objc internal func orientationDidChangeNotification(_ notification: Notification) { let instance = Visualizer.sharedInstance for touch in instance.touchViews { touch.removeFromSuperview() @@ -61,12 +61,12 @@ extension Visualizer { start(Configuration()) } - public class func start(config: Configuration) { + public class func start(_ config: Configuration) { let instance = sharedInstance instance.enabled = true instance.config = config - if let window = UIApplication.sharedApplication().keyWindow { + if let window = UIApplication.shared().keyWindow { for subview in window.subviews { if let subview = subview as? TouchView { subview.removeFromSuperview() @@ -102,7 +102,7 @@ extension Visualizer { return touchView! } - private func findTouchView(touch: UITouch) -> TouchView? { + private func findTouchView(_ touch: UITouch) -> TouchView? { for view in touchViews { if touch == view.touch { return view @@ -112,8 +112,8 @@ extension Visualizer { return nil } - public func handleEvent(event: UIEvent) { - if event.type != .Touches { + public func handleEvent(_ event: UIEvent) { + if event.type != .touches { return } @@ -121,31 +121,31 @@ extension Visualizer { return } - let keyWindow = UIApplication.sharedApplication().keyWindow! + let keyWindow = UIApplication.shared().keyWindow! for touch in event.allTouches()! { let phase = touch.phase switch phase { - case .Began: + case .began: let view = dequeueTouchView() view.config = Visualizer.sharedInstance.config view.touch = touch view.beginTouch() - view.center = touch.locationInView(keyWindow) + view.center = touch.location(in: keyWindow) keyWindow.addSubview(view) log(touch) - case .Moved: + case .moved: if let view = findTouchView(touch) { - view.center = touch.locationInView(keyWindow) + view.center = touch.location(in: keyWindow) } log(touch) - case .Stationary: + case .stationary: log(touch) break - case .Ended, .Cancelled: + case .ended, .cancelled: if let view = findTouchView(touch) { - UIView.animateWithDuration(0.2, delay: 0.0, options: .AllowUserInteraction, animations: { () -> Void in + UIView.animate(withDuration: 0.2, delay: 0.0, options: .allowUserInteraction, animations: { () -> Void in view.alpha = 0.0 view.endTouch() }, completion: { [unowned self] (finished) -> Void in @@ -168,7 +168,7 @@ extension Visualizer { } // MARK: - Logging - public func log(touch: UITouch) { + public func log(_ touch: UITouch) { if !config.showsLog { return } @@ -185,11 +185,11 @@ extension Visualizer { var phase: String! switch touch.phase { - case .Began: phase = "B" - case .Moved: phase = "M" - case .Ended: phase = "E" - case .Cancelled: phase = "C" - case .Stationary: phase = "S" + case .began: phase = "B" + case .moved: phase = "M" + case .ended: phase = "E" + case .cancelled: phase = "C" + case .stationary: phase = "S" } let x = String(format: "%.02f", view.center.x) @@ -220,4 +220,4 @@ extension Visualizer { previousLog = log print(log, terminator: "") } -} \ No newline at end of file +}