repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
nate-parrott/Ratty
RattyApp/RattyApp/MenuViewController.swift
1
12429
// // MenuViewController.swift // RattyApp // // Created by Nate Parrott on 2/16/15. // Copyright (c) 2015 Nate Parrott. All rights reserved. // import UIKit enum Meal { case Index(i: Int) case Nearest } func arePositionsEqual(p1: (date: NSDate, meal: Meal), p2: (date: NSDate, meal: Meal)) -> Bool { let (date1, meal1): (NSDate, Meal) = p1 let (date2, meal2): (NSDate, Meal) = p2 var mealsEqual = false switch (meal1, meal2) { case (.Index(let i1), .Index(let i2)): mealsEqual = i1 == i2 case (.Nearest, .Nearest): mealsEqual = true default: mealsEqual = false } return date1.compare(date2) == .OrderedSame && mealsEqual } class MenuViewController: UIViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate { lazy var pageViewController: UIPageViewController = { let pageVC = UIPageViewController(transitionStyle: .Scroll, navigationOrientation: .Horizontal, options: nil) pageVC.dataSource = self pageVC.delegate = self self.addChildViewController(pageVC) return pageVC }() var pageTransitionTracker: PageTransitionTracker! lazy var gradientLayer: CAGradientLayer = { let g = CAGradientLayer() return g }() override func viewDidLoad() { super.viewDidLoad() pageTransitionTracker = PageTransitionTracker(pageViewController: pageViewController) pageTransitionTracker.trackingCallback = { [weak self] in self!.updateCurrentPage() } NSNotificationCenter.defaultCenter().addObserver(self, selector: "jumpToCurrentMeal", name: ShouldJumpToCurrentMealNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "jumpToMealWithNotification:", name: JumpToMealAndDateNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "reload", name: ReloadMenuNotification, object: nil) // index 0 is the splash image view view.layer.insertSublayer(gradientLayer, atIndex: 1) view.insertSubview(pageViewController.view, atIndex: 2) statusBarCover = UIView() view.addSubview(statusBarCover) navContainer.addSubview(navView) navView.onPrevDayClicked = { [unowned self] in self.jumpDays(-1) } navView.onNextDayClicked = { [unowned self] in self.jumpDays(1) } navView.onSelectedMealChanged = { [unowned self] in self.jumpToMeal(Int(self.navView.selectedMeal)) } // update page view controller: let menuVC = MenuTableViewController() menuVC.time = (date: NSDate(), meal: 1) pageViewController.setViewControllers([menuVC], direction: .Forward, animated: false, completion: nil) updateCurrentPage() pageViewController.view.alpha = 0 navView.userInteractionEnabled = false navView.alpha = 0.5 jumpToCurrentMeal() } deinit { NSNotificationCenter.defaultCenter().removeObserver(self, name: nil, object: nil) } var initialLoad: Bool = false { didSet { UIView.animateWithDuration(0.3, animations: { () -> Void in self.pageViewController.view.alpha = 1 self.navView.alpha = 1 }) navView.userInteractionEnabled = true } } func reload() { let p = currentPosition currentPosition = p } func jumpToCurrentMeal() { currentPosition = (date: NSDate(), meal: Meal.Nearest) } func jumpToMealWithNotification(notif: NSNotification) { currentPosition = (date: notif.userInfo!["date"]! as! NSDate, meal: Meal.Index(i: notif.userInfo!["meal"]! as! Int)) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() pageViewController.view.frame = view.bounds navView.frame = navContainer.bounds statusBarCover.frame = CGRectMake(0, 0, view.bounds.size.width, topLayoutGuide.length) gradientLayer.frame = CGRectMake(0, statusBarCover.frame.size.height, view.bounds.size.width, view.bounds.size.height - statusBarCover.frame.size.height) } func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? { if let (date, meal) = (viewController as! MenuTableViewController).time { let prev = MenuTableViewController() if meal == 0 { prev.time = (date.byAddingSeconds(-24 * 60 * 60), 2) } else { prev.time = (date, meal-1) } return prev } return nil } func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? { if let (date, meal) = (viewController as! MenuTableViewController).time { let next = MenuTableViewController() if meal == 2 { next.time = (date.byAddingSeconds(24 * 60 * 60), 0) } else { next.time = (date, meal+1) } return next } return nil } func pageViewController(pageViewController: UIPageViewController, willTransitionToViewControllers pendingViewControllers: [UIViewController]) { updateCurrentPage() pageTransitionTracker.startTracking() if let tableVC = pendingViewControllers.first as! MenuTableViewController? { tableVC.shouldReturnToToday = { [weak self] in self!.currentPosition = (date: NSDate(), meal: Meal.Nearest) } } } func pageViewController(pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) { pageTransitionTracker.stopTracking() updateCurrentPage() } @IBOutlet var navContainer: UIView! @IBOutlet var statusBarCover: UIView! // MARK: Navigation var currentPosition: (date: NSDate, meal: Meal) = (date: NSDate(), meal: Meal.Nearest) { didSet { switch currentPosition.meal { case .Nearest: // load the current date, then update this: let posAtStartOfLoad = currentPosition SharedDiningAPI().getMenu("ratty", date: NSDate()) { (let menusOpt, let errorOpt) -> () in if arePositionsEqual(posAtStartOfLoad, p2: self.currentPosition) { if let mealMenus = menusOpt { if let meal = SharedDiningAPI().indexOfNearestMeal(mealMenus) { self.currentPosition = (date: NSDate(), meal: Meal.Index(i: meal)) } } else { // that's an error; just fallback and show breakfast (with an error msg): self.currentPosition = (date: NSDate(), meal: Meal.Index(i: 0)) } } } case .Index(let mealIndex): let animate = initialLoad initialLoad = true if currentPosition.date != _showingDate() || mealIndex != _showingMealIndex() { let isInFuture = _showingDate().compare(currentPosition.date) == .OrderedAscending || (_showingDate().compare(currentPosition.date) == .OrderedSame && _showingMealIndex() < mealIndex) let pageVC = MenuTableViewController() pageVC.time = (currentPosition.date, mealIndex) pageVC.shouldReturnToToday = { [weak self] in self!.currentPosition = (date: NSDate(), meal: Meal.Nearest) } pageViewController.setViewControllers([pageVC], direction: isInFuture ? .Forward : .Reverse, animated: animate, completion: nil) if animate { UIView.animateWithDuration(0.25, animations: { () -> Void in self.updateCurrentPage(false) }, completion: nil) } else { self.updateCurrentPage(true) } } } } } func jumpDays(days: Int) { currentPosition = (date: currentPosition.date.byAddingSeconds(NSTimeInterval(days * 24 * 60 * 60)), meal: currentPosition.meal) } func jumpToMeal(meal: Int) { currentPosition = (date: currentPosition.date, meal: Meal.Index(i: meal)) } private func _showingDate() -> NSDate { if let firstVC = pageViewController.viewControllers?.first, let tableVC = firstVC as? MenuTableViewController, let date = tableVC.time?.date { return date } else { return NSDate() } } private func _showingMealIndex() -> Int { if let firstVC = pageViewController.viewControllers?.first, let tableVC = firstVC as? MenuTableViewController, let idx = tableVC.time?.meal { return idx } else { return 0 } } // MARK: Page transitions func updateCurrentPage(supressGradientAnimation: Bool = true) { switch currentPosition.meal { case .Index(i: _): currentPosition = (date: _showingDate(), meal: Meal.Index(i: _showingMealIndex())) case .Nearest: 1 + 1 // do nothing } var interpolatedMeal = CGFloat(_showingMealIndex()) if pageTransitionTracker.isTracking { interpolatedMeal = CGFloat((pageTransitionTracker.trackingViewController! as! MenuTableViewController).time.meal) + pageTransitionTracker.progress } navView.selectedMeal = interpolatedMeal gradientLayer.actions = supressGradientAnimation ? ["colors" as String: NSNull()] : nil let (color1, color2) = gradientForMeal(interpolatedMeal) gradientLayer.colors = [color1.CGColor, color2.CGColor] let trim = colorForMeal(interpolatedMeal) navView.backgroundColor = trim statusBarCover.backgroundColor = color1 } func gradientForMeal(var meal: CGFloat) -> (UIColor, UIColor) { if !initialLoad { return (UIColor(white: 0, alpha: 0), UIColor(white: 0, alpha: 0)) } let colorPairs = [ (UIColor(red: 0.078, green: 0.392, blue: 0.584, alpha: 1), UIColor(red: 0.988, green: 0.698, blue: 0.000, alpha: 1)), (UIColor(red: 0.322, green: 0.455, blue: 0.729, alpha: 1), UIColor(red: 0.749, green: 0.863, blue: 0.843, alpha: 1)), //(UIColor(red: 1.0, green:0.565297424793, blue:0.550667464733, alpha:1.0), UIColor(red: 1.0, green:0.745570778847, blue:0.0, alpha:1.0)), (UIColor(red: 0.88181167841, green:0.601593911648, blue:0.0619730427861, alpha:1.0), UIColor(red: 0.859640955925, green:0.223587602377, blue:0.290304690599, alpha:1.0)) ] // (UIColor(red: 0.463, green: 0.624, blue: 0.973, alpha: 1), UIColor(red: 0.674502670765, green:0.312217831612, blue:0.678681373596, alpha:1.0)) if meal < 0 { meal += 3 } let i1 = Int(floor(meal)) % 3 let i2 = Int(ceil(meal)) % 3 let mix = meal - floor(meal) let pair1 = colorPairs[i1] let pair2 = colorPairs[i2] return (pair1.0.mix(pair2.0, amount: mix), pair1.1.mix(pair2.1, amount: mix)) } func colorForMeal(meal: CGFloat, dark: Bool = false) -> UIColor { let (c1, c2) = gradientForMeal(meal) return c1.mix(c2, amount: 0.5) } // MARK: View controller methods override func preferredStatusBarStyle() -> UIStatusBarStyle { return .LightContent } // MARK: Views lazy var navView: NavigationView = { let nav = UINib(nibName: "Navigation", bundle: nil).instantiateWithOwner(nil, options: nil)[0] as! NavigationView return nav }() }
mit
d049fd614258aa4d1913022de76eb324
39.884868
203
0.599163
4.729452
false
false
false
false
gsaslis/Rocket.Chat.iOS
Rocket.Chat.iOS/ViewControllers/Auth/LoginViewController.swift
1
12557
// // LoginViewController.swift // Rocket.Chat.iOS // // Created by Kornelakis Michael on 8/8/15. // Copyright © 2015 Rocket.Chat. All rights reserved. // import UIKit import JSQCoreDataKit import MMDrawerController class LoginViewController: UIViewController, UIPopoverPresentationControllerDelegate { @IBOutlet var userNameTextField: UITextField! @IBOutlet var passwordTextField: UITextField! //variable to get the logged in user var currentUser = User?() var users = [User]() override func viewDidLoad() { super.viewDidLoad() //set password textfield to secure entry textfield passwordTextField.secureTextEntry = true //Add listener for the textinput for when input changes userNameTextField.addTarget(self, action: "textFieldDidChange", forControlEvents: UIControlEvents.EditingChanged) passwordTextField.addTarget(self, action: "textFieldDidChange", forControlEvents: UIControlEvents.EditingChanged) //Prefill text inputs to make login easier for developing // userNameTextField.text = "[email protected]" // passwordTextField.text = "123qwe" let delegate = UIApplication.sharedApplication().delegate as! AppDelegate let context = delegate.stack!.context //Check for already logged in user let ent = entity(name: "User", context: context) let request = FetchRequest<User>(entity: ent) //Users that we have password for only request.predicate = NSPredicate(format: "password != nil") users = [User]() do{ users = try fetch(request: request, inContext: context) }catch{ print("Error fetching users \(error)") } // if exists { // loginButtonTapped(userNameTextField.text!) // } // if !users.isEmpty { // userNameTextField.text = users[0].username // passwordTextField.text = users[0].password // loginButtonTapped(users) // } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //Function to return popovers as modals to all devices. func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle { return .None } //Login action @IBAction func loginButtonTapped(sender: AnyObject) { //Check if username is empty if(userNameTextField.text == ""){ //if empty change username textfield border color to red userNameTextField.layer.borderColor = UIColor.redColor().CGColor userNameTextField.layer.borderWidth = 1.0 //Create View Controller let popoverVC = storyboard?.instantiateViewControllerWithIdentifier("loginPopover") //Set it as popover popoverVC!.modalPresentationStyle = .Popover //Set the size popoverVC!.preferredContentSize = CGSizeMake(250, 50) if let popoverController = popoverVC!.popoverPresentationController { //Specify the anchor location popoverController.sourceView = userNameTextField popoverController.sourceRect = userNameTextField.bounds //Popover above the textfield popoverController.permittedArrowDirections = .Down //Set the delegate popoverController.delegate = self } //Show the popover presentViewController(popoverVC!, animated: true, completion: nil) } //Check if password is empty else if(passwordTextField.text == ""){ //if empty change password textfield border color to red passwordTextField.layer.borderColor = UIColor.redColor().CGColor passwordTextField.layer.borderWidth = 1.0 //Create popover controller let popoverVC = storyboard?.instantiateViewControllerWithIdentifier("loginPopover") //Set it as popover popoverVC!.modalPresentationStyle = .Popover //Set the size popoverVC?.preferredContentSize = CGSizeMake(250, 50) if let popoverController = popoverVC!.popoverPresentationController { //Specify the anchor location popoverController.sourceView = passwordTextField popoverController.sourceRect = passwordTextField.bounds //Popover above the textfield popoverController.permittedArrowDirections = .Down //Set the delegate popoverController.delegate = self //Show the popover presentViewController(popoverVC!, animated: true, completion: nil) } } //if username and password is OK else if(userAndPassVerify(userNameTextField.text!, passWord:passwordTextField.text!)) { self.view.endEditing(true) //get the appdelegate and store it in a variable let appDelegate:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate //THIS NEEDS TO MOVE (?) // let context = appDelegate.stack!.context // // let user = User(context: context, id: "NON-YET", username: userNameTextField.text!, avatar: "avatar.png", status: .ONLINE, timezone: NSTimeZone.systemTimeZone()) // user.password = passwordTextField.text! // //User is automatically is added to CoreData, but not saved, so we need to call // //save context next. // //This is dump, because it writes the same user again, and again // // saveContext(context, wait: true, completion:{(error: NSError?) -> Void in // if let err = error { // let alert = UIAlertController(title: "Alert", message: "Error \(err.userInfo)", preferredStyle: UIAlertControllerStyle.Alert) // alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.Default, handler: nil)) // self.presentViewController(alert, animated: true, completion: nil) // } // // //set the logged in user // self.currentUser = user // // // }) //let rootViewController = appDelegate.window!.rootViewController //get the storyboard an store it in a variable let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil) //Create and store the center the left and the right views and keep them in variables //center view let centerViewController = mainStoryboard.instantiateViewControllerWithIdentifier("viewController") as! ViewController //left view let leftViewController = mainStoryboard.instantiateViewControllerWithIdentifier("leftView") as! LeftViewController //right view let rightViewController = mainStoryboard.instantiateViewControllerWithIdentifier("rightView") as! RightViewController //send the logged in user in the ViewController centerViewController.currentUser = currentUser //Set the left, right and center views as the rootviewcontroller for the navigation controller (one rootviewcontroller at a time) //Set the left view as the rootview for the navigation controller and keep it in a variable let leftSideNav = UINavigationController(rootViewController: leftViewController) leftSideNav.setNavigationBarHidden(true, animated: false) //Set the center view as the rootview for the navigation controller and keep it in a variable let centerNav = UINavigationController(rootViewController: centerViewController) //Set the right view as the rootview for the navigation controller and keep it in a variable let rightNav = UINavigationController(rootViewController: rightViewController) //Create the MMDrawerController and keep it in a variable named center container let centerContainer:MMDrawerController = MMDrawerController(centerViewController: centerNav, leftDrawerViewController: leftSideNav,rightDrawerViewController:rightNav) //Open and Close gestures for the center container //Set the open gesture for the center container centerContainer.openDrawerGestureModeMask = MMOpenDrawerGestureMode.PanningCenterView; //Setting the width of th right view //centerContainer.setMaximumRightDrawerWidth(appDelegate.window!.frame.width, animated: true, completion: nil) //Set the close gesture for the center container centerContainer.closeDrawerGestureModeMask = MMCloseDrawerGestureMode.PanningCenterView; //Set the centerContainer in the appDelegate.swift as the center container appDelegate.centerContainer = centerContainer //Set the rootViewController as the center container appDelegate.window!.rootViewController = appDelegate.centerContainer appDelegate.window!.makeKeyAndVisible() } //if username or password is wrong else { //create an alert let alert = UIAlertView(title: "Warning!", message: "Check your username / password combination", delegate: self, cancelButtonTitle: "Dismiss") //empty textfields userNameTextField.text = "" passwordTextField.text = "" //show the alert alert.show() //userNameTextField gets the focus userNameTextField.becomeFirstResponder() } } //Function to check username and password func userAndPassVerify(userName:String, passWord:String) -> Bool { var exists = false //If there are registered users if !self.users.isEmpty{ for i in self.users { if i.username == userNameTextField.text && i.password == passwordTextField.text{ exists = true self.currentUser = i print("CurrentUser set " + i.username) } } } //Return if exists or not return exists } func textFieldDidChange() { //Reset textField's border color and width userNameTextField.layer.borderColor = UIColor.blackColor().CGColor userNameTextField.layer.borderWidth = 0.0 passwordTextField.layer.borderColor = UIColor.blackColor().CGColor passwordTextField.layer.borderWidth = 0.0 } //Register a new acoount action @IBAction func registerNewAccountTapped(sender: AnyObject) { } //Forgot password action @IBAction func forgotPasswordTapped(sender: AnyObject) { } //Dismissing the keyboard @IBAction func dismissKeyboard(sender: AnyObject) { self.resignFirstResponder() } //Dismissing the keyboard when user taps outside override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { self.view.endEditing(true) } }
mit
54bb290070f3e14004cafc471f86d685
34.874286
178
0.58474
6.455527
false
false
false
false
Felix0805/Notes
Notes/Notes/func.swift
1
1143
// // func.swift // Notes // // Created by FelixXiao on 2017/1/12. // Copyright © 2017年 FelixXiao. All rights reserved. // import Foundation func dateFromString (_ dateStr: String) -> Date? { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd" let date = dateFormatter.date(from: dateStr) return date } //时间小的排前面,时间相同按优先级排序, func reminderSort(r1: RemindersModel, r2: RemindersModel) -> Bool{ let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd" let date = NSDate() let timeFormatter = DateFormatter() timeFormatter.dateFormat = "yyyy-MM-dd" let strNowTime = timeFormatter.string(from: date as Date) as String //两者都过期 var d1: String var d2: String d1 = formatter.string(from: r1.date) d2 = formatter.string(from: r2.date) if formatter.string(from: r1.date) < strNowTime { d1 = "3"+d1 } if formatter.string(from: r2.date) < strNowTime { d2 = "3" + d2 } if d1 == d2 { return r1.level > r2.level } else { return d1 < d2 } }
mit
4ee4b55022aafe241787bc4b77660626
23.266667
71
0.631868
3.269461
false
false
false
false
ikesyo/Rex
Source/UIKit/UIView.swift
3
1083
// // UIView.swift // Rex // // Created by Andy Jacobs on 21/10/15. // Copyright © 2015 Neil Pankey. All rights reserved. // import ReactiveCocoa import UIKit extension UIView { /// Wraps a view's `alpha` value in a bindable property. public var rex_alpha: MutableProperty<CGFloat> { return associatedProperty(self, key: &alphaKey, initial: { $0.alpha }, setter: { $0.alpha = $1 }) } /// Wraps a view's `hidden` state in a bindable property. public var rex_hidden: MutableProperty<Bool> { return associatedProperty(self, key: &hiddenKey, initial: { $0.hidden }, setter: { $0.hidden = $1 }) } /// Wraps a view's `userInteractionEnabled` state in a bindable property. public var rex_userInteractionEnabled: MutableProperty<Bool> { return associatedProperty(self, key: &userInteractionEnabledKey, initial: { $0.userInteractionEnabled }, setter: { $0.userInteractionEnabled = $1 }) } } private var alphaKey: UInt8 = 0 private var hiddenKey: UInt8 = 0 private var userInteractionEnabledKey: UInt8 = 0
mit
2d80c5372a0e65823f226f5c79991f3f
32.8125
156
0.676525
3.934545
false
false
false
false
xedin/swift
test/IRGen/lazy_globals.swift
6
2238
// RUN: %target-swift-frontend -parse-as-library -emit-ir -primary-file %s | %FileCheck %s // REQUIRES: CPU=x86_64 // CHECK: @globalinit_[[T:.*]]_token0 = internal global i64 0, align 8 // CHECK: @"$s12lazy_globals1xSivp" = hidden global %TSi zeroinitializer, align 8 // CHECK: @"$s12lazy_globals1ySivp" = hidden global %TSi zeroinitializer, align 8 // CHECK: @"$s12lazy_globals1zSivp" = hidden global %TSi zeroinitializer, align 8 // CHECK: define internal void @globalinit_[[T]]_func0() {{.*}} { // CHECK: entry: // CHECK: store i64 1, i64* getelementptr inbounds (%TSi, %TSi* @"$s12lazy_globals1xSivp", i32 0, i32 0), align 8 // CHECK: store i64 2, i64* getelementptr inbounds (%TSi, %TSi* @"$s12lazy_globals1ySivp", i32 0, i32 0), align 8 // CHECK: store i64 3, i64* getelementptr inbounds (%TSi, %TSi* @"$s12lazy_globals1zSivp", i32 0, i32 0), align 8 // CHECK: ret void // CHECK: } // CHECK: define hidden swiftcc i8* @"$s12lazy_globals1xSivau"() {{.*}} { // CHECK: entry: // CHECK: call void @swift_once(i64* @globalinit_[[T]]_token0, i8* bitcast (void ()* @globalinit_[[T]]_func0 to i8*), i8* undef) // CHECK: ret i8* bitcast (%TSi* @"$s12lazy_globals1xSivp" to i8*) // CHECK: } // CHECK: define hidden swiftcc i8* @"$s12lazy_globals1ySivau"() {{.*}} { // CHECK: entry: // CHECK: call void @swift_once(i64* @globalinit_[[T]]_token0, i8* bitcast (void ()* @globalinit_[[T]]_func0 to i8*), i8* undef) // CHECK: ret i8* bitcast (%TSi* @"$s12lazy_globals1ySivp" to i8*) // CHECK: } // CHECK: define hidden swiftcc i8* @"$s12lazy_globals1zSivau"() {{.*}} { // CHECK: entry: // CHECK: call void @swift_once(i64* @globalinit_[[T]]_token0, i8* bitcast (void ()* @globalinit_[[T]]_func0 to i8*), i8* undef) // CHECK: ret i8* bitcast (%TSi* @"$s12lazy_globals1zSivp" to i8*) // CHECK: } var (x, y, z) = (1, 2, 3) // CHECK: define hidden swiftcc i64 @"$s12lazy_globals4getXSiyF"() {{.*}} { // CHECK: entry: // CHECK: %0 = call swiftcc i8* @"$s12lazy_globals1xSivau"() // CHECK: %1 = bitcast i8* %0 to %TSi* // CHECK: %._value = getelementptr inbounds %TSi, %TSi* %1, i32 0, i32 0 // CHECK: [[V:%.*]] = load i64, i64* %._value, align 8 // CHECK: ret i64 [[V]] // CHECK: } func getX() -> Int { return x }
apache-2.0
10568bb1f73975835db9fb67bea1c483
47.652174
130
0.630474
2.902724
false
false
false
false
venticake/RetricaImglyKit-iOS
RetricaImglyKit/Classes/Frontend/Editor/PathHelper.swift
1
2028
// This file is part of the PhotoEditor Software Development Kit. // Copyright (C) 2016 9elements GmbH <[email protected]> // All rights reserved. // Redistribution and use in source and binary forms, without // modification, are permitted provided that the following license agreement // is approved and a legal/financial contract was signed by the user. // The license agreement can be found under the following link: // https://www.photoeditorsdk.com/LICENSE.txt import UIKit /** * The `PathHelper` class bundles helper methods to work with paths. */ @available(iOS 8, *) @objc(IMGLYPathHelper) public class PathHelper: NSObject { /** Can be used to add a rounded rectangle path to a context. - parameter context: The context to add the path to. - parameter width: The width of the rectangle. - parameter height: The height of the rectangle. - parameter ovalWidth: The horizontal corner radius. - parameter ovalHeight: The vertical corner radius. */ static public func clipCornersToOvalWidth(context: CGContextRef, width: CGFloat, height: CGFloat, ovalWidth: CGFloat, ovalHeight: CGFloat) { var fw = CGFloat(0) var fh = CGFloat(0) let rect = CGRect(x: 0.0, y: 0.0, width: width, height: height) if ovalWidth == 0 || ovalHeight == 0 { CGContextAddRect(context, rect) return } CGContextSaveGState(context) CGContextTranslateCTM(context, rect.minX, rect.minY) CGContextScaleCTM(context, ovalWidth, ovalHeight) fw = rect.width / ovalWidth fh = rect.height / ovalHeight CGContextMoveToPoint(context, fw, fh / 2) CGContextAddArcToPoint(context, fw, fh, fw / 2, fh, 1) CGContextAddArcToPoint(context, 0, fh, 0, fh / 2, 1) CGContextAddArcToPoint(context, 0, 0, fw / 2, 0, 1) CGContextAddArcToPoint(context, fw, 0, fw, fh / 2, 1) CGContextClosePath(context) CGContextRestoreGState(context) } }
mit
1f876c39020cd434a548d36c0e6aaf74
40.387755
144
0.673077
4.242678
false
false
false
false
apatronl/Rain
CAPSPageMenu.swift
1
58035
// CAPSPageMenu.swift // // Niklas Fahl // // Copyright (c) 2014 The Board of Trustees of The University of Alabama All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: // // Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. // // Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. // // Neither the name of the University nor the names of the contributors may be used to endorse or promote products derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A // PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import UIKit @objc public protocol CAPSPageMenuDelegate { // MARK: - Delegate functions @objc optional func willMoveToPage(_ controller: UIViewController, index: Int) @objc optional func didMoveToPage(_ controller: UIViewController, index: Int) } class MenuItemView: UIView { // MARK: - Menu item view var titleLabel : UILabel? var menuItemSeparator : UIView? func setUpMenuItemView(_ menuItemWidth: CGFloat, menuScrollViewHeight: CGFloat, indicatorHeight: CGFloat, separatorPercentageHeight: CGFloat, separatorWidth: CGFloat, separatorRoundEdges: Bool, menuItemSeparatorColor: UIColor) { titleLabel = UILabel(frame: CGRect(x: 0.0, y: 0.0, width: menuItemWidth, height: menuScrollViewHeight - indicatorHeight)) menuItemSeparator = UIView(frame: CGRect(x: menuItemWidth - (separatorWidth / 2), y: floor(menuScrollViewHeight * ((1.0 - separatorPercentageHeight) / 2.0)), width: separatorWidth, height: floor(menuScrollViewHeight * separatorPercentageHeight))) menuItemSeparator!.backgroundColor = menuItemSeparatorColor if separatorRoundEdges { menuItemSeparator!.layer.cornerRadius = menuItemSeparator!.frame.width / 2 } menuItemSeparator!.isHidden = true self.addSubview(menuItemSeparator!) self.addSubview(titleLabel!) } func setTitleText(_ text: NSString) { if titleLabel != nil { titleLabel!.text = text as String titleLabel!.numberOfLines = 0 titleLabel!.sizeToFit() } } } public enum CAPSPageMenuOption { case selectionIndicatorBottomOffset(CGFloat) case selectionIndicatorHeight(CGFloat) case menuItemSeparatorWidth(CGFloat) case scrollMenuBackgroundColor(UIColor) case viewBackgroundColor(UIColor) case bottomMenuHairlineColor(UIColor) case selectionIndicatorColor(UIColor) case menuItemSeparatorColor(UIColor) case menuMargin(CGFloat) case menuItemMargin(CGFloat) case menuHeight(CGFloat) case selectedMenuItemLabelColor(UIColor) case unselectedMenuItemLabelColor(UIColor) case useMenuLikeSegmentedControl(Bool) case menuItemSeparatorRoundEdges(Bool) case menuItemFont(UIFont) case menuItemSeparatorPercentageHeight(CGFloat) case menuItemWidth(CGFloat) case enableHorizontalBounce(Bool) case addBottomMenuHairline(Bool) case menuItemWidthBasedOnTitleTextWidth(Bool) case titleTextSizeBasedOnMenuItemWidth(Bool) case scrollAnimationDurationOnMenuItemTap(Int) case centerMenuItems(Bool) case hideTopMenuBar(Bool) case menuShadowRadius(CGFloat) case menuShadowOpacity(Float) case menuShadowColor(UIColor) case menuShadowOffset(CGFloat) case addBottomMenuShadow(Bool) case iconIndicator(Bool) case iconIndicatorView(UIView) case showStepperView(Bool) } open class CAPSPageMenu: UIViewController, UIScrollViewDelegate, UIGestureRecognizerDelegate { // MARK: - Properties let menuScrollView = UIScrollView() open let controllerScrollView = UIScrollView() var controllerArray : [UIViewController] = [] var menuItems : [MenuItemView] = [] var menuItemWidths : [CGFloat] = [] open var menuHeight : CGFloat = 34.0 open var menuMargin : CGFloat = 15.0 open var menuItemWidth : CGFloat = 111.0 open var selectionIndicatorBottomOffset : CGFloat = 0.0 open var selectionIndicatorHeight : CGFloat = 3.0 var totalMenuItemWidthIfDifferentWidths : CGFloat = 0.0 open var scrollAnimationDurationOnMenuItemTap : Int = 500 // Millisecons var startingMenuMargin : CGFloat = 0.0 var menuItemMargin : CGFloat = 0.0 var iconIndicator:Bool = false var selectionIndicatorCustomView: UIView? var selectionIndicatorView : UIView = UIView() var stepperView : UIView = UIView() var currentPageIndex : Int = 0 var lastPageIndex : Int = 0 open var selectionIndicatorColor : UIColor = UIColor.white open var selectedMenuItemLabelColor : UIColor = UIColor.white open var unselectedMenuItemLabelColor : UIColor = UIColor.lightGray open var scrollMenuBackgroundColor : UIColor = UIColor.black open var viewBackgroundColor : UIColor = UIColor.white open var bottomMenuHairlineColor : UIColor = UIColor.white open var menuItemSeparatorColor : UIColor = UIColor.lightGray open var menuItemFont : UIFont = UIFont.systemFont(ofSize: 15.0) open var menuItemSeparatorPercentageHeight : CGFloat = 0.2 open var menuItemSeparatorWidth : CGFloat = 0.5 open var menuItemSeparatorRoundEdges : Bool = false open var addBottomMenuHairline : Bool = true open var menuItemWidthBasedOnTitleTextWidth : Bool = false open var titleTextSizeBasedOnMenuItemWidth : Bool = false open var useMenuLikeSegmentedControl : Bool = false open var centerMenuItems : Bool = false open var enableHorizontalBounce : Bool = true open var hideTopMenuBar : Bool = false open var showStepperView : Bool = false public var menuShadowRadius : CGFloat = 0 public var menuShadowOpacity : Float = 0 public var menuShadowColor : UIColor = UIColor.white public var menuShadowOffset : CGFloat = 0 public var addBottomMenuShadow : Bool = false var currentOrientationIsPortrait : Bool = true var pageIndexForOrientationChange : Int = 0 var didLayoutSubviewsAfterRotation : Bool = false var didScrollAlready : Bool = false var lastControllerScrollViewContentOffset : CGFloat = 0.0 var lastScrollDirection : CAPSPageMenuScrollDirection = .other var startingPageForScroll : Int = 0 var didTapMenuItemToScroll : Bool = false var pagesAddedDictionary : [Int : Int] = [:] open weak var delegate : CAPSPageMenuDelegate? var tapTimer : Timer? enum CAPSPageMenuScrollDirection : Int { case left case right case other } // MARK: - View life cycle /** Initialize PageMenu with view controllers :parameter viewControllers: List of view controllers that must be subclasses of UIViewController :parameter frame: Frame for page menu view :parameter options: Dictionary holding any customization options user might want to set */ public init(viewControllers: [UIViewController], frame: CGRect, options: [String: AnyObject]?) { super.init(nibName: nil, bundle: nil) controllerArray = viewControllers self.view.frame = frame } public convenience init(viewControllers: [UIViewController], frame: CGRect, pageMenuOptions: [CAPSPageMenuOption]?) { self.init(viewControllers:viewControllers, frame:frame, options:nil) if let options = pageMenuOptions { for option in options { switch (option) { case let .selectionIndicatorBottomOffset(value): selectionIndicatorBottomOffset = value case let .selectionIndicatorHeight(value): selectionIndicatorHeight = value case let .menuItemSeparatorWidth(value): menuItemSeparatorWidth = value case let .scrollMenuBackgroundColor(value): scrollMenuBackgroundColor = value case let .viewBackgroundColor(value): viewBackgroundColor = value case let .bottomMenuHairlineColor(value): bottomMenuHairlineColor = value case let .selectionIndicatorColor(value): selectionIndicatorColor = value case let .menuItemSeparatorColor(value): menuItemSeparatorColor = value case let .menuMargin(value): menuMargin = value case let .menuItemMargin(value): menuItemMargin = value case let .menuHeight(value): menuHeight = value case let .selectedMenuItemLabelColor(value): selectedMenuItemLabelColor = value case let .unselectedMenuItemLabelColor(value): unselectedMenuItemLabelColor = value case let .useMenuLikeSegmentedControl(value): useMenuLikeSegmentedControl = value case let .menuItemSeparatorRoundEdges(value): menuItemSeparatorRoundEdges = value case let .menuItemFont(value): menuItemFont = value case let .menuItemSeparatorPercentageHeight(value): menuItemSeparatorPercentageHeight = value case let .menuItemWidth(value): menuItemWidth = value case let .enableHorizontalBounce(value): enableHorizontalBounce = value case let .addBottomMenuHairline(value): addBottomMenuHairline = value case let .menuItemWidthBasedOnTitleTextWidth(value): menuItemWidthBasedOnTitleTextWidth = value case let .titleTextSizeBasedOnMenuItemWidth(value): titleTextSizeBasedOnMenuItemWidth = value case let .scrollAnimationDurationOnMenuItemTap(value): scrollAnimationDurationOnMenuItemTap = value case let .centerMenuItems(value): centerMenuItems = value case let .hideTopMenuBar(value): hideTopMenuBar = value case let .menuShadowRadius(value): menuShadowRadius = value case let .menuShadowOpacity(value): menuShadowOpacity = value case let .menuShadowColor(value): menuShadowColor = value case let .menuShadowOffset(value): menuShadowOffset = value case let .addBottomMenuShadow(value): addBottomMenuShadow = value case let .iconIndicator(value): iconIndicator = value case let .iconIndicatorView(value): selectionIndicatorCustomView = value case let .showStepperView(value): showStepperView = value } } if hideTopMenuBar { addBottomMenuHairline = false menuHeight = 0.0 addBottomMenuShadow = false } } setUpUserInterface() if menuScrollView.subviews.count == 0 { configureUserInterface() } if iconIndicator { moveSelectionIndicator(currentPageIndex) } } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } // MARK: - Container View Controller open override var shouldAutomaticallyForwardAppearanceMethods : Bool { return true } open override func shouldAutomaticallyForwardRotationMethods() -> Bool { return true } // MARK: - UI Setup func setUpUserInterface() { let viewsDictionary = ["menuScrollView":menuScrollView, "controllerScrollView":controllerScrollView] // Set up controller scroll view controllerScrollView.isPagingEnabled = true controllerScrollView.translatesAutoresizingMaskIntoConstraints = false controllerScrollView.alwaysBounceHorizontal = enableHorizontalBounce controllerScrollView.bounces = enableHorizontalBounce controllerScrollView.frame = CGRect(x: 0.0, y: menuHeight, width: self.view.frame.width, height: self.view.frame.height) self.view.addSubview(controllerScrollView) let controllerScrollView_constraint_H:Array = NSLayoutConstraint.constraints(withVisualFormat: "H:|[controllerScrollView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewsDictionary) let controllerScrollView_constraint_V:Array = NSLayoutConstraint.constraints(withVisualFormat: "V:|[controllerScrollView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewsDictionary) self.view.addConstraints(controllerScrollView_constraint_H) self.view.addConstraints(controllerScrollView_constraint_V) // Set up menu scroll view menuScrollView.translatesAutoresizingMaskIntoConstraints = false menuScrollView.frame = CGRect(x: 0.0, y: 0.0, width: self.view.frame.width, height: menuHeight) self.view.addSubview(menuScrollView) let menuScrollView_constraint_H:Array = NSLayoutConstraint.constraints(withVisualFormat: "H:|[menuScrollView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewsDictionary) let menuScrollView_constraint_V:Array = NSLayoutConstraint.constraints(withVisualFormat: "V:[menuScrollView(\(menuHeight))]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewsDictionary) self.view.addConstraints(menuScrollView_constraint_H) self.view.addConstraints(menuScrollView_constraint_V) // Add hairline to menu scroll view if addBottomMenuHairline { let menuBottomHairline : UIView = UIView() menuBottomHairline.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(menuBottomHairline) let menuBottomHairline_constraint_H:Array = NSLayoutConstraint.constraints(withVisualFormat: "H:|[menuBottomHairline]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["menuBottomHairline":menuBottomHairline]) let menuBottomHairline_constraint_V:Array = NSLayoutConstraint.constraints(withVisualFormat: "V:|-\(menuHeight)-[menuBottomHairline(0.5)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["menuBottomHairline":menuBottomHairline]) self.view.addConstraints(menuBottomHairline_constraint_H) self.view.addConstraints(menuBottomHairline_constraint_V) menuBottomHairline.backgroundColor = bottomMenuHairlineColor } if addBottomMenuShadow { menuScrollView.layer.shadowColor = menuShadowColor.cgColor menuScrollView.layer.shadowRadius = menuShadowRadius menuScrollView.layer.shadowOpacity = menuShadowOpacity menuScrollView.layer.shadowOffset = CGSize(width:0, height:menuShadowOffset) menuScrollView.layer.masksToBounds = true } // Disable scroll bars menuScrollView.showsHorizontalScrollIndicator = false menuScrollView.showsVerticalScrollIndicator = false controllerScrollView.showsHorizontalScrollIndicator = false controllerScrollView.showsVerticalScrollIndicator = false // Set background color behind scroll views and for menu scroll view self.view.backgroundColor = viewBackgroundColor menuScrollView.backgroundColor = scrollMenuBackgroundColor } func configureUserInterface() { // Add tap gesture recognizer to controller scroll view to recognize menu item selection let menuItemTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(CAPSPageMenu.handleMenuItemTap(_:))) menuItemTapGestureRecognizer.numberOfTapsRequired = 1 menuItemTapGestureRecognizer.numberOfTouchesRequired = 1 menuItemTapGestureRecognizer.delegate = self menuScrollView.addGestureRecognizer(menuItemTapGestureRecognizer) // Set delegate for controller scroll view controllerScrollView.delegate = self // When the user taps the status bar, the scroll view beneath the touch which is closest to the status bar will be scrolled to top, // but only if its `scrollsToTop` property is YES, its delegate does not return NO from `shouldScrollViewScrollToTop`, and it is not already at the top. // If more than one scroll view is found, none will be scrolled. // Disable scrollsToTop for menu and controller scroll views so that iOS finds scroll views within our pages on status bar tap gesture. menuScrollView.scrollsToTop = false; controllerScrollView.scrollsToTop = false; // Configure menu scroll view if useMenuLikeSegmentedControl { menuScrollView.isScrollEnabled = false menuScrollView.contentSize = CGSize(width: self.view.frame.width, height: menuHeight) menuMargin = 0.0 } else { menuScrollView.contentSize = CGSize(width: (menuItemWidth + menuMargin) * CGFloat(controllerArray.count) + menuMargin, height: menuHeight) } // Configure controller scroll view content size controllerScrollView.contentSize = CGSize(width: self.view.frame.width * CGFloat(controllerArray.count), height: 0.0) var index : CGFloat = 0.0 for controller in controllerArray { if index == 0.0 { // Add first two controllers to scrollview and as child view controller addPageAtIndex(0) } // Set up menu item for menu scroll view var menuItemFrame : CGRect = CGRect() if useMenuLikeSegmentedControl { //**************************拡張************************************* if menuItemMargin > 0 { let marginSum = menuItemMargin * CGFloat(controllerArray.count + 1) let menuItemWidth = (self.view.frame.width - marginSum) / CGFloat(controllerArray.count) menuItemFrame = CGRect(x: CGFloat(menuItemMargin * (index + 1)) + menuItemWidth * CGFloat(index), y: 0.0, width: CGFloat(self.view.frame.width) / CGFloat(controllerArray.count), height: menuHeight) } else { menuItemFrame = CGRect(x: self.view.frame.width / CGFloat(controllerArray.count) * CGFloat(index), y: 0.0, width: CGFloat(self.view.frame.width) / CGFloat(controllerArray.count), height: menuHeight) } //**************************拡張ここまで************************************* } else if menuItemWidthBasedOnTitleTextWidth { let controllerTitle : String? = controller.title let titleText : String = controllerTitle != nil ? controllerTitle! : "Menu \(Int(index) + 1)" let itemWidthRect : CGRect = (titleText as NSString).boundingRect(with: CGSize(width: 1000, height: 1000), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSFontAttributeName:menuItemFont], context: nil) menuItemWidth = itemWidthRect.width menuItemFrame = CGRect(x: totalMenuItemWidthIfDifferentWidths + menuMargin + (menuMargin * index), y: 0.0, width: menuItemWidth, height: menuHeight) totalMenuItemWidthIfDifferentWidths += itemWidthRect.width menuItemWidths.append(itemWidthRect.width) } else { if centerMenuItems && index == 0.0 { startingMenuMargin = ((self.view.frame.width - ((CGFloat(controllerArray.count) * menuItemWidth) + (CGFloat(controllerArray.count - 1) * menuMargin))) / 2.0) - menuMargin if startingMenuMargin < 0.0 { startingMenuMargin = 0.0 } menuItemFrame = CGRect(x: startingMenuMargin + menuMargin, y: 0.0, width: menuItemWidth, height: menuHeight) } else { menuItemFrame = CGRect(x: menuItemWidth * index + menuMargin * (index + 1) + startingMenuMargin, y: 0.0, width: menuItemWidth, height: menuHeight) } } let menuItemView : MenuItemView = MenuItemView(frame: menuItemFrame) if useMenuLikeSegmentedControl { //**************************拡張************************************* if menuItemMargin > 0 { let marginSum = menuItemMargin * CGFloat(controllerArray.count + 1) let menuItemWidth = (self.view.frame.width - marginSum) / CGFloat(controllerArray.count) menuItemView.setUpMenuItemView(menuItemWidth, menuScrollViewHeight: menuHeight, indicatorHeight: selectionIndicatorHeight, separatorPercentageHeight: menuItemSeparatorPercentageHeight, separatorWidth: menuItemSeparatorWidth, separatorRoundEdges: menuItemSeparatorRoundEdges, menuItemSeparatorColor: menuItemSeparatorColor) } else { menuItemView.setUpMenuItemView(CGFloat(self.view.frame.width) / CGFloat(controllerArray.count), menuScrollViewHeight: menuHeight, indicatorHeight: selectionIndicatorHeight, separatorPercentageHeight: menuItemSeparatorPercentageHeight, separatorWidth: menuItemSeparatorWidth, separatorRoundEdges: menuItemSeparatorRoundEdges, menuItemSeparatorColor: menuItemSeparatorColor) } //**************************拡張ここまで************************************* } else { menuItemView.setUpMenuItemView(menuItemWidth, menuScrollViewHeight: menuHeight, indicatorHeight: selectionIndicatorHeight, separatorPercentageHeight: menuItemSeparatorPercentageHeight, separatorWidth: menuItemSeparatorWidth, separatorRoundEdges: menuItemSeparatorRoundEdges, menuItemSeparatorColor: menuItemSeparatorColor) } // Configure menu item label font if font is set by user menuItemView.titleLabel!.font = menuItemFont menuItemView.titleLabel!.textAlignment = NSTextAlignment.center menuItemView.titleLabel!.textColor = unselectedMenuItemLabelColor //**************************拡張************************************* menuItemView.titleLabel!.adjustsFontSizeToFitWidth = titleTextSizeBasedOnMenuItemWidth //**************************拡張ここまで************************************* // Set title depending on if controller has a title set if controller.title != nil { menuItemView.titleLabel!.text = controller.title! } else { menuItemView.titleLabel!.text = "Menu \(Int(index) + 1)" } // Add separator between menu items when using as segmented control if useMenuLikeSegmentedControl { if Int(index) < controllerArray.count - 1 { menuItemView.menuItemSeparator!.isHidden = false } } // Add menu item view to menu scroll view menuScrollView.addSubview(menuItemView) menuItems.append(menuItemView) index += 1 } // Set new content size for menu scroll view if needed if menuItemWidthBasedOnTitleTextWidth { menuScrollView.contentSize = CGSize(width: (totalMenuItemWidthIfDifferentWidths + menuMargin) + CGFloat(controllerArray.count) * menuMargin, height: menuHeight) } // Set selected color for title label of selected menu item if menuItems.count > 0 { if menuItems[currentPageIndex].titleLabel != nil { menuItems[currentPageIndex].titleLabel!.textColor = selectedMenuItemLabelColor } } // Configure selection indicator view var selectionIndicatorFrame : CGRect = CGRect() if useMenuLikeSegmentedControl { selectionIndicatorFrame = CGRect(x: 0.0, y: menuHeight - selectionIndicatorHeight - selectionIndicatorBottomOffset, width: self.view.frame.width / CGFloat(controllerArray.count), height: selectionIndicatorHeight) } else if menuItemWidthBasedOnTitleTextWidth { selectionIndicatorFrame = CGRect(x: menuMargin, y: menuHeight - selectionIndicatorHeight - selectionIndicatorBottomOffset, width: menuItemWidths[0], height: selectionIndicatorHeight) } else { if centerMenuItems { selectionIndicatorFrame = CGRect(x: startingMenuMargin + menuMargin, y: menuHeight - selectionIndicatorHeight - selectionIndicatorBottomOffset, width: menuItemWidth, height: selectionIndicatorHeight) } else { selectionIndicatorFrame = CGRect(x: menuMargin, y: menuHeight - selectionIndicatorHeight - selectionIndicatorBottomOffset, width: menuItemWidth, height: selectionIndicatorHeight) } } selectionIndicatorView = UIView(frame: selectionIndicatorFrame) selectionIndicatorView.backgroundColor = selectionIndicatorColor menuScrollView.addSubview(selectionIndicatorView) //Stepper view if showStepperView { selectionIndicatorFrame = CGRect(x: 0.0, y: menuHeight - selectionIndicatorHeight, width: menuScrollView.frame.width, height: selectionIndicatorHeight) stepperView = UIView(frame: selectionIndicatorFrame) menuScrollView.addSubview(self.stepperView) } //Check if icon indicator is active and has a valid icon indicator view if let indicatorView = self.selectionIndicatorCustomView, self.iconIndicator { //modify bounds of icon indicator indicatorView.frame.origin.x = selectionIndicatorFrame.size.width/2-selectionIndicatorFrame.size.height/2 //add icon indicator to selection view container selectionIndicatorView.addSubview(indicatorView) } //Hide background of selectionIndicatorView if icon indicator was setter selectionIndicatorView.backgroundColor = self.iconIndicator ? UIColor.clear : selectionIndicatorColor if menuItemWidthBasedOnTitleTextWidth && centerMenuItems { self.configureMenuItemWidthBasedOnTitleTextWidthAndCenterMenuItems() let leadingAndTrailingMargin = self.getMarginForMenuItemWidthBasedOnTitleTextWidthAndCenterMenuItems() selectionIndicatorView.frame = CGRect(x: leadingAndTrailingMargin, y: menuHeight - selectionIndicatorHeight, width: menuItemWidths[0], height: selectionIndicatorHeight) } } // Adjusts the menu item frames to size item width based on title text width and center all menu items in the center // if the menuItems all fit in the width of the view. Otherwise, it will adjust the frames so that the menu items // appear as if only menuItemWidthBasedOnTitleTextWidth is true. fileprivate func configureMenuItemWidthBasedOnTitleTextWidthAndCenterMenuItems() { // only center items if the combined width is less than the width of the entire view's bounds if menuScrollView.contentSize.width < self.view.bounds.width { // compute the margin required to center the menu items let leadingAndTrailingMargin = self.getMarginForMenuItemWidthBasedOnTitleTextWidthAndCenterMenuItems() // adjust the margin of each menu item to make them centered for (index, menuItem) in menuItems.enumerated() { let controllerTitle = controllerArray[index].title! let itemWidthRect = controllerTitle.boundingRect(with: CGSize(width: 1000, height: 1000), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSFontAttributeName:menuItemFont], context: nil) menuItemWidth = itemWidthRect.width var margin: CGFloat if index == 0 { // the first menu item should use the calculated margin margin = leadingAndTrailingMargin } else { // the other menu items should use the menuMargin let previousMenuItem = menuItems[index-1] let previousX = previousMenuItem.frame.maxX margin = previousX + menuMargin } menuItem.frame = CGRect(x: margin, y: 0.0, width: menuItemWidth, height: menuHeight) } } else { // the menuScrollView.contentSize.width exceeds the view's width, so layout the menu items normally (menuItemWidthBasedOnTitleTextWidth) for (index, menuItem) in menuItems.enumerated() { var menuItemX: CGFloat if index == 0 { menuItemX = menuMargin } else { menuItemX = menuItems[index-1].frame.maxX + menuMargin } menuItem.frame = CGRect(x: menuItemX, y: 0.0, width: menuItem.bounds.width, height: menuItem.bounds.height) } } } // Returns the size of the left and right margins that are neccessary to layout the menuItems in the center. fileprivate func getMarginForMenuItemWidthBasedOnTitleTextWidthAndCenterMenuItems() -> CGFloat { let menuItemsTotalWidth = menuScrollView.contentSize.width - menuMargin * 2 let leadingAndTrailingMargin = (self.view.bounds.width - menuItemsTotalWidth) / 2 return leadingAndTrailingMargin } // MARK: - Scroll view delegate open func scrollViewDidScroll(_ scrollView: UIScrollView) { if !didLayoutSubviewsAfterRotation { if scrollView.isEqual(controllerScrollView) { if scrollView.contentOffset.x >= 0.0 && scrollView.contentOffset.x <= (CGFloat(controllerArray.count - 1) * self.view.frame.width) { if (currentOrientationIsPortrait && UIApplication.shared.statusBarOrientation.isPortrait) || (!currentOrientationIsPortrait && UIApplication.shared.statusBarOrientation.isLandscape) { // Check if scroll direction changed if !didTapMenuItemToScroll { if didScrollAlready { var newScrollDirection : CAPSPageMenuScrollDirection = .other if (CGFloat(startingPageForScroll) * scrollView.frame.width > scrollView.contentOffset.x) { newScrollDirection = .right } else if (CGFloat(startingPageForScroll) * scrollView.frame.width < scrollView.contentOffset.x) { newScrollDirection = .left } if newScrollDirection != .other { if lastScrollDirection != newScrollDirection { let index : Int = newScrollDirection == .left ? currentPageIndex + 1 : currentPageIndex - 1 if index >= 0 && index < controllerArray.count { // Check dictionary if page was already added if pagesAddedDictionary[index] != index { addPageAtIndex(index) pagesAddedDictionary[index] = index } } } } lastScrollDirection = newScrollDirection } if !didScrollAlready { if (lastControllerScrollViewContentOffset > scrollView.contentOffset.x) { if currentPageIndex != controllerArray.count - 1 { // Add page to the left of current page let index : Int = currentPageIndex - 1 if pagesAddedDictionary[index] != index && index < controllerArray.count && index >= 0 { addPageAtIndex(index) pagesAddedDictionary[index] = index } lastScrollDirection = .right } } else if (lastControllerScrollViewContentOffset < scrollView.contentOffset.x) { if currentPageIndex != 0 { // Add page to the right of current page let index : Int = currentPageIndex + 1 if pagesAddedDictionary[index] != index && index < controllerArray.count && index >= 0 { addPageAtIndex(index) pagesAddedDictionary[index] = index } lastScrollDirection = .left } } didScrollAlready = true } lastControllerScrollViewContentOffset = scrollView.contentOffset.x } var ratio : CGFloat = 1.0 // Calculate ratio between scroll views ratio = (menuScrollView.contentSize.width - self.view.frame.width) / (controllerScrollView.contentSize.width - self.view.frame.width) if menuScrollView.contentSize.width > self.view.frame.width { var offset : CGPoint = menuScrollView.contentOffset offset.x = controllerScrollView.contentOffset.x * ratio menuScrollView.setContentOffset(offset, animated: false) } // Calculate current page let width : CGFloat = controllerScrollView.frame.size.width; let page : Int = Int((controllerScrollView.contentOffset.x + (0.5 * width)) / width) // Update page if changed if page != currentPageIndex { lastPageIndex = currentPageIndex currentPageIndex = page if pagesAddedDictionary[page] != page && page < controllerArray.count && page >= 0 { addPageAtIndex(page) pagesAddedDictionary[page] = page } if !didTapMenuItemToScroll { // Add last page to pages dictionary to make sure it gets removed after scrolling if pagesAddedDictionary[lastPageIndex] != lastPageIndex { pagesAddedDictionary[lastPageIndex] = lastPageIndex } // Make sure only up to 3 page views are in memory when fast scrolling, otherwise there should only be one in memory let indexLeftTwo : Int = page - 2 if pagesAddedDictionary[indexLeftTwo] == indexLeftTwo { pagesAddedDictionary.removeValue(forKey: indexLeftTwo) removePageAtIndex(indexLeftTwo) } let indexRightTwo : Int = page + 2 if pagesAddedDictionary[indexRightTwo] == indexRightTwo { pagesAddedDictionary.removeValue(forKey: indexRightTwo) removePageAtIndex(indexRightTwo) } } } // Move selection indicator view when swiping moveSelectionIndicator(page) } } else { var ratio : CGFloat = 1.0 ratio = (menuScrollView.contentSize.width - self.view.frame.width) / (controllerScrollView.contentSize.width - self.view.frame.width) if menuScrollView.contentSize.width > self.view.frame.width { var offset : CGPoint = menuScrollView.contentOffset offset.x = controllerScrollView.contentOffset.x * ratio menuScrollView.setContentOffset(offset, animated: false) } } } } else { didLayoutSubviewsAfterRotation = false // Move selection indicator view when swiping moveSelectionIndicator(currentPageIndex) } } open func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { if scrollView.isEqual(controllerScrollView) { // Call didMoveToPage delegate function let currentController = controllerArray[currentPageIndex] delegate?.didMoveToPage?(currentController, index: currentPageIndex) // Remove all but current page after decelerating for key in pagesAddedDictionary.keys { if key != currentPageIndex { removePageAtIndex(key) } } didScrollAlready = false startingPageForScroll = currentPageIndex // Empty out pages in dictionary pagesAddedDictionary.removeAll(keepingCapacity: false) } } func scrollViewDidEndTapScrollingAnimation() { // Call didMoveToPage delegate function let currentController = controllerArray[currentPageIndex] delegate?.didMoveToPage?(currentController, index: currentPageIndex) // Remove all but current page after decelerating for key in pagesAddedDictionary.keys { if key != currentPageIndex { removePageAtIndex(key) } } startingPageForScroll = currentPageIndex didTapMenuItemToScroll = false // Empty out pages in dictionary pagesAddedDictionary.removeAll(keepingCapacity: false) } // MARK: - Handle Selection Indicator func moveSelectionIndicator(_ pageIndex: Int) { if pageIndex >= 0 && pageIndex < controllerArray.count { UIView.animate(withDuration: 0.15, animations: { () -> Void in var selectionIndicatorWidth : CGFloat = self.selectionIndicatorView.frame.width var selectionIndicatorX : CGFloat = 0.0 if self.useMenuLikeSegmentedControl { selectionIndicatorX = CGFloat(pageIndex) * (self.view.frame.width / CGFloat(self.controllerArray.count)) selectionIndicatorWidth = self.view.frame.width / CGFloat(self.controllerArray.count) } else if self.menuItemWidthBasedOnTitleTextWidth { selectionIndicatorWidth = self.menuItemWidths[pageIndex] selectionIndicatorX = self.menuItems[pageIndex].frame.minX } else { if self.centerMenuItems && pageIndex == 0 { selectionIndicatorX = self.startingMenuMargin + self.menuMargin } else { selectionIndicatorX = self.menuItemWidth * CGFloat(pageIndex) + self.menuMargin * CGFloat(pageIndex + 1) + self.startingMenuMargin } } self.selectionIndicatorView.frame = CGRect(x: selectionIndicatorX, y: self.selectionIndicatorView.frame.origin.y, width: selectionIndicatorWidth, height: self.selectionIndicatorView.frame.height) //If icon indicator was setted and has a valid icon indicator if let indicatorView = self.selectionIndicatorCustomView, self.iconIndicator{ //Modify the frame position indicatorView.frame = CGRect(x: self.selectionIndicatorView.frame.size.width/2-self.selectionIndicatorView.frame.size.height/2, y: 0, width: self.selectionIndicatorView.frame.size.height, height: self.selectionIndicatorView.frame.size.height) } // Switch newly selected menu item title label to selected color and old one to unselected color if self.menuItems.count > 0 { if self.menuItems[self.lastPageIndex].titleLabel != nil && self.menuItems[self.currentPageIndex].titleLabel != nil { self.menuItems[self.lastPageIndex].titleLabel!.textColor = self.unselectedMenuItemLabelColor self.menuItems[self.currentPageIndex].titleLabel!.textColor = self.selectedMenuItemLabelColor } } }) } } // MARK: - Tap gesture recognizer selector func handleMenuItemTap(_ gestureRecognizer : UITapGestureRecognizer) { let tappedPoint : CGPoint = gestureRecognizer.location(in: menuScrollView) if tappedPoint.y < menuScrollView.frame.height { // Calculate tapped page var itemIndex : Int = 0 if useMenuLikeSegmentedControl { itemIndex = Int(tappedPoint.x / (self.view.frame.width / CGFloat(controllerArray.count))) } else if menuItemWidthBasedOnTitleTextWidth { var menuItemLeftBound: CGFloat var menuItemRightBound: CGFloat if centerMenuItems { menuItemLeftBound = menuItems[0].frame.minX menuItemRightBound = menuItems[menuItems.count-1].frame.maxX if (tappedPoint.x >= menuItemLeftBound && tappedPoint.x <= menuItemRightBound) { for (index, _) in controllerArray.enumerated() { menuItemLeftBound = menuItems[index].frame.minX menuItemRightBound = menuItems[index].frame.maxX if tappedPoint.x >= menuItemLeftBound && tappedPoint.x <= menuItemRightBound { itemIndex = index break } } } } else { // Base case being first item menuItemLeftBound = 0.0 menuItemRightBound = menuItemWidths[0] + menuMargin + (menuMargin / 2) if !(tappedPoint.x >= menuItemLeftBound && tappedPoint.x <= menuItemRightBound) { for i in 1...controllerArray.count - 1 { menuItemLeftBound = menuItemRightBound + 1.0 menuItemRightBound = menuItemLeftBound + menuItemWidths[i] + menuMargin if tappedPoint.x >= menuItemLeftBound && tappedPoint.x <= menuItemRightBound { itemIndex = i break } } } } } else { let rawItemIndex : CGFloat = ((tappedPoint.x - startingMenuMargin) - menuMargin / 2) / (menuMargin + menuItemWidth) // Prevent moving to first item when tapping left to first item if rawItemIndex < 0 { itemIndex = -1 } else { itemIndex = Int(rawItemIndex) } } if itemIndex >= 0 && itemIndex < controllerArray.count { // Update page if changed if itemIndex != currentPageIndex { startingPageForScroll = itemIndex lastPageIndex = currentPageIndex currentPageIndex = itemIndex didTapMenuItemToScroll = true // Add pages in between current and tapped page if necessary let smallerIndex : Int = lastPageIndex < currentPageIndex ? lastPageIndex : currentPageIndex let largerIndex : Int = lastPageIndex > currentPageIndex ? lastPageIndex : currentPageIndex if smallerIndex + 1 != largerIndex { for index in (smallerIndex + 1)...(largerIndex - 1) { if pagesAddedDictionary[index] != index { addPageAtIndex(index) pagesAddedDictionary[index] = index } } } addPageAtIndex(itemIndex) // Add page from which tap is initiated so it can be removed after tap is done pagesAddedDictionary[lastPageIndex] = lastPageIndex } // Move controller scroll view when tapping menu item let duration : Double = Double(scrollAnimationDurationOnMenuItemTap) / Double(1000) UIView.animate(withDuration: duration, animations: { () -> Void in let xOffset : CGFloat = CGFloat(itemIndex) * self.controllerScrollView.frame.width self.controllerScrollView.setContentOffset(CGPoint(x: xOffset, y: self.controllerScrollView.contentOffset.y), animated: false) }) if tapTimer != nil { tapTimer!.invalidate() } let timerInterval : TimeInterval = Double(scrollAnimationDurationOnMenuItemTap) * 0.001 tapTimer = Timer.scheduledTimer(timeInterval: timerInterval, target: self, selector: #selector(CAPSPageMenu.scrollViewDidEndTapScrollingAnimation), userInfo: nil, repeats: false) } } } // MARK: - Remove/Add Page func addPageAtIndex(_ index : Int) { // Call didMoveToPage delegate function let currentController = controllerArray[index] delegate?.willMoveToPage?(currentController, index: index) let newVC = controllerArray[index] newVC.willMove(toParentViewController: self) newVC.view.frame = CGRect(x: self.view.frame.width * CGFloat(index), y: menuHeight, width: self.view.frame.width, height: self.view.frame.height - menuHeight) self.addChildViewController(newVC) self.controllerScrollView.addSubview(newVC.view) newVC.didMove(toParentViewController: self) } func removePageAtIndex(_ index : Int) { let oldVC = controllerArray[index] oldVC.willMove(toParentViewController: nil) oldVC.view.removeFromSuperview() oldVC.removeFromParentViewController() } // MARK: - Orientation Change override open func viewDidLayoutSubviews() { // Configure controller scroll view content size controllerScrollView.contentSize = CGSize(width: self.view.frame.width * CGFloat(controllerArray.count), height: self.view.frame.height - menuHeight) let oldCurrentOrientationIsPortrait : Bool = currentOrientationIsPortrait currentOrientationIsPortrait = UIApplication.shared.statusBarOrientation.isPortrait if (oldCurrentOrientationIsPortrait && UIDevice.current.orientation.isLandscape) || (!oldCurrentOrientationIsPortrait && UIDevice.current.orientation.isPortrait) { didLayoutSubviewsAfterRotation = true //Resize menu items if using as segmented control if useMenuLikeSegmentedControl { menuScrollView.contentSize = CGSize(width: self.view.frame.width, height: menuHeight) // Resize selectionIndicator bar let selectionIndicatorX : CGFloat = CGFloat(currentPageIndex) * (self.view.frame.width / CGFloat(self.controllerArray.count)) let selectionIndicatorWidth : CGFloat = self.view.frame.width / CGFloat(self.controllerArray.count) selectionIndicatorView.frame = CGRect(x: selectionIndicatorX, y: self.selectionIndicatorView.frame.origin.y, width: selectionIndicatorWidth, height: self.selectionIndicatorView.frame.height) // Resize menu items var index : Int = 0 for item : MenuItemView in menuItems as [MenuItemView] { item.frame = CGRect(x: self.view.frame.width / CGFloat(controllerArray.count) * CGFloat(index), y: 0.0, width: self.view.frame.width / CGFloat(controllerArray.count), height: menuHeight) item.titleLabel!.frame = CGRect(x: 0.0, y: 0.0, width: self.view.frame.width / CGFloat(controllerArray.count), height: menuHeight) item.menuItemSeparator!.frame = CGRect(x: item.frame.width - (menuItemSeparatorWidth / 2), y: item.menuItemSeparator!.frame.origin.y, width: item.menuItemSeparator!.frame.width, height: item.menuItemSeparator!.frame.height) index += 1 } } else if menuItemWidthBasedOnTitleTextWidth && centerMenuItems { self.configureMenuItemWidthBasedOnTitleTextWidthAndCenterMenuItems() let selectionIndicatorX = menuItems[currentPageIndex].frame.minX selectionIndicatorView.frame = CGRect(x: selectionIndicatorX, y: menuHeight - selectionIndicatorHeight, width: menuItemWidths[currentPageIndex], height: selectionIndicatorHeight) } else if centerMenuItems { startingMenuMargin = ((self.view.frame.width - ((CGFloat(controllerArray.count) * menuItemWidth) + (CGFloat(controllerArray.count - 1) * menuMargin))) / 2.0) - menuMargin if startingMenuMargin < 0.0 { startingMenuMargin = 0.0 } let selectionIndicatorX : CGFloat = self.menuItemWidth * CGFloat(currentPageIndex) + self.menuMargin * CGFloat(currentPageIndex + 1) + self.startingMenuMargin selectionIndicatorView.frame = CGRect(x: selectionIndicatorX, y: self.selectionIndicatorView.frame.origin.y, width: self.selectionIndicatorView.frame.width, height: self.selectionIndicatorView.frame.height) // Recalculate frame for menu items if centered var index : Int = 0 for item : MenuItemView in menuItems as [MenuItemView] { if index == 0 { item.frame = CGRect(x: startingMenuMargin + menuMargin, y: 0.0, width: menuItemWidth, height: menuHeight) } else { item.frame = CGRect(x: menuItemWidth * CGFloat(index) + menuMargin * CGFloat(index + 1) + startingMenuMargin, y: 0.0, width: menuItemWidth, height: menuHeight) } index += 1 } } for view : UIView in controllerScrollView.subviews { view.frame = CGRect(x: self.view.frame.width * CGFloat(currentPageIndex), y: menuHeight, width: controllerScrollView.frame.width, height: self.view.frame.height - menuHeight) } let xOffset : CGFloat = CGFloat(self.currentPageIndex) * controllerScrollView.frame.width controllerScrollView.setContentOffset(CGPoint(x: xOffset, y: controllerScrollView.contentOffset.y), animated: false) let ratio : CGFloat = (menuScrollView.contentSize.width - self.view.frame.width) / (controllerScrollView.contentSize.width - self.view.frame.width) if menuScrollView.contentSize.width > self.view.frame.width { var offset : CGPoint = menuScrollView.contentOffset offset.x = controllerScrollView.contentOffset.x * ratio menuScrollView.setContentOffset(offset, animated: false) } } // Hsoi 2015-02-05 - Running on iOS 7.1 complained: "'NSInternalInconsistencyException', reason: 'Auto Layout // still required after sending -viewDidLayoutSubviews to the view controller. ViewController's implementation // needs to send -layoutSubviews to the view to invoke auto layout.'" // // http://stackoverflow.com/questions/15490140/auto-layout-error // // Given the SO answer and caveats presented there, we'll call layoutIfNeeded() instead. self.view.layoutIfNeeded() } // MARK: - Move to page index /** Move to page at index :parameter index: Index of the page to move to */ open func moveToPage(_ index: Int) { if index >= 0 && index < controllerArray.count { // Update page if changed if index != currentPageIndex { startingPageForScroll = index lastPageIndex = currentPageIndex currentPageIndex = index didTapMenuItemToScroll = true // Add pages in between current and tapped page if necessary let smallerIndex : Int = lastPageIndex < currentPageIndex ? lastPageIndex : currentPageIndex let largerIndex : Int = lastPageIndex > currentPageIndex ? lastPageIndex : currentPageIndex if smallerIndex + 1 != largerIndex { for i in (smallerIndex + 1)...(largerIndex - 1) { if pagesAddedDictionary[i] != i { addPageAtIndex(i) pagesAddedDictionary[i] = i } } } addPageAtIndex(index) // Add page from which tap is initiated so it can be removed after tap is done pagesAddedDictionary[lastPageIndex] = lastPageIndex } // Move controller scroll view when tapping menu item let duration : Double = Double(scrollAnimationDurationOnMenuItemTap) / Double(1000) UIView.animate(withDuration: duration, animations: { () -> Void in let xOffset : CGFloat = CGFloat(index) * self.controllerScrollView.frame.width self.controllerScrollView.setContentOffset(CGPoint(x: xOffset, y: self.controllerScrollView.contentOffset.y), animated: false) }) } } }
mit
5feb350cca628db5b2fc5d9b2d5936d0
52.542936
392
0.597393
6.538904
false
false
false
false
xiaomudegithub/iosstar
iOSStar/Scenes/Login/LoginVC.swift
3
7308
// // LoginVC.swift // iOSStar // // Created by sum on 2017/4/26. // Copyright © 2017年 YunDian. All rights reserved. // import UIKit import SVProgressHUD class LoginVC: UIViewController ,UIGestureRecognizerDelegate,UITextFieldDelegate{ @IBOutlet weak var backView: UIView! @IBOutlet weak var contentView: UIView! //定义block来判断选择哪个试图 var resultBlock: CompleteBlock? //左边距 @IBOutlet var left: NSLayoutConstraint! //右边距 @IBOutlet weak var height: NSLayoutConstraint! @IBOutlet var right: NSLayoutConstraint! //上边距 @IBOutlet var top: NSLayoutConstraint! @IBOutlet weak var width: NSLayoutConstraint! @IBOutlet var loginBtn: UIButton! var uid : Int = 0 // 登录密码 @IBOutlet weak var passPwd: UITextField! // 手机号 @IBOutlet weak var phone: UITextField! override func viewDidLoad() { super.viewDidLoad() initNav() initUI() passPwd.delegate = self passPwd.returnKeyType = .done } func textFieldDidEndEditing(_ textField: UITextField) { textField.resignFirstResponder() } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } func textFieldShouldEndEditing(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } func initUI(){ loginBtn.titleLabel?.setAttributeText(text: "还没有账户 现在注册", firstFont: 14, secondFont: 14, firstColor: UIColor.init(hexString: "999999"), secondColor: UIColor.init(hexString: AppConst.Color.main), range: NSRange(location: 6, length: 4)) let backViewTap = UITapGestureRecognizer.init(target: self, action: #selector(backViewTapClick)) backView.addGestureRecognizer(backViewTap) backViewTap.delegate = self self.automaticallyAdjustsScrollViewInsets = false height.constant = 120 + UIScreen.main.bounds.size.height width.constant = UIScreen.main.bounds.size.width let h = UIScreen.main.bounds.size.height <= 568 ? 60.0 : 80 self.top.constant = UIScreen.main.bounds.size.height/568.0 * CGFloat.init(h) print(self.top.constant) self.left.constant = UIScreen.main.bounds.size.width/320.0 * 30 self.right.constant = UIScreen.main.bounds.size.width/320.0 * 30 } func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { if (touch.view?.isDescendant(of: contentView))! { return false; } return true; } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController?.setNavigationBarHidden(true, animated: false) } func backViewTapClick() { didClose() } // MARK: - 导航栏 func initNav(){ let btn = UIButton.init(frame: CGRect.init(x: 0, y: 0, width: 20, height: 20)) btn.setBackgroundImage(UIImage.init(named: "close"), for: .normal) let navaitem = UIBarButtonItem.init(customView: btn) self.navigationItem.leftBarButtonItem = navaitem btn.addTarget(self, action: #selector(didClose), for: .touchUpInside) if (UserDefaults.standard.object(forKey: "lastLogin")) != nil { phone.text = UserDefaults.standard.object(forKey: "lastLogin") as? String } } //MARK: 界面消失 func didClose(){ let win : UIWindow = ((UIApplication.shared.delegate?.window)!)! let tabar : BaseTabBarController = win.rootViewController as! BaseTabBarController if tabar.selectedIndex == 1 { } else { tabar.selectedIndex = 0 } self.dismissController() } //MARK: 注册 @IBAction func doRegist(_ sender: Any) { view.endEditing(true) self.phone.text = "" self.passPwd.text = "" ShareDataModel.share().isweichaLogin = false self.resultBlock!(doStateClick.doRegist as AnyObject?) } //MARK:- 登录 @IBAction func doLogin(_ sender: Any) { if !checkTextFieldEmpty([phone]) { return } if !checkTextFieldEmpty([passPwd]) { return } if !isTelNumber(num: phone.text!) { SVProgressHUD.showErrorMessage(ErrorMessage: "手机号码格式错误", ForDuration: 2.0, completion: nil) return } if !isPassWord(pwd: passPwd.text!) { SVProgressHUD.showErrorMessage(ErrorMessage: "请输入6位字符以上密码", ForDuration: 2.0, completion: nil) return } SVProgressHUD.showProgressMessage(ProgressMessage: "登录中······") if isTelNumber(num: phone.text!) && checkTextFieldEmpty([passPwd]) { let loginRequestModel = LoginRequestModel() loginRequestModel.phone = phone.text! loginRequestModel.pwd = (passPwd.text?.md5_string())! AppAPIHelper.login().login(model: loginRequestModel, complete: {[weak self] (result) in SVProgressHUD.dismiss() let datadic = result as? StarUserModel SVProgressHUD.showSuccessMessage(SuccessMessage: "登录成功", ForDuration: 2.0, completion: { if let _ = datadic { UserDefaults.standard.set(self?.phone.text, forKey: "phone") UserDefaults.standard.set(self?.phone.text, forKey: "tokenvalue") self?.uid = Int(datadic!.userinfo!.id) UserDefaults.standard.synchronize() self?.dismissController() NotificationCenter.default.post(name: NSNotification.Name(rawValue: AppConst.loginSuccess), object: nil, userInfo:nil) StarUserModel.upateUserInfo(userObject: datadic!) AppConfigHelper.shared().updateDeviceToken() } }) }, error: { (error) in self.didRequestError(error) // SVProgressHUD.showErrorMessage(ErrorMessage: "网络连接超时", ForDuration: 2.0, completion: nil) }) } } @IBAction func law(_ sender: Any) { let vc = BaseWebVC() vc.loadRequest = "http://122.144.169.219:3389/law" vc.navtitle = "法律说明" self.navigationController?.pushViewController(vc, animated: true) } //MARK:- 微信登录 @IBAction func wechatLogin(_ sender: Any) { let req = SendAuthReq.init() req.scope = AppConst.WechatKey.Scope req.state = AppConst.WechatKey.State WXApi.send(req) } // MARK: - 关闭视图 @IBAction func didMiss(_ sender: Any) { didClose() } //MARK: 重置密码 @IBAction func doResetPass(_ sender: Any) { self.resultBlock!(doStateClick.doResetPwd as AnyObject) } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { view.endEditing(true) } }
gpl-3.0
29fb69e56ced5be7e64b751266938195
33.519417
241
0.60765
4.599612
false
false
false
false
WangYang-iOS/YiDeXuePin_Swift
DiYa/DiYa/Class/Home/View/GoodsDetailViews/YYGoodsSkuView.swift
1
3396
// // YYGoodsSkuView.swift // DiYa // // Created by wangyang on 2017/12/14. // Copyright © 2017年 wangyang. All rights reserved. // import UIKit @objc protocol YYGoodsSkuViewDelegate { @objc optional func didSelectedGoodsWith(skuValue:String,number:Int) } class YYGoodsSkuView: UIView { @IBOutlet weak var priceLabel: UILabel! @IBOutlet weak var inventoryLabel: UILabel! @IBOutlet weak var skuView: UIView! @IBOutlet weak var skuViewHeight: NSLayoutConstraint! @IBOutlet weak var changeNumberView: YYChangeNumberView! weak var delegate : YYGoodsSkuViewDelegate? var lastMaxY : CGFloat = 0 var goodsSkuViewHieght : CGFloat = 0 var dic = [Int:String]() var goodsSkuList = [GoodsSkuModel]() var goodsModel : GoodsModel? { didSet { guard let goodsModel = goodsModel else { return } priceLabel.text = "¥" + goodsModel.price inventoryLabel.text = "库存" + goodsModel.inventory + "件" } } var skuId = "" var skuValue = "" var skuList : [SkuCategoryModel]? { didSet { guard let skuList = skuList else { return } for (i,model) in skuList.enumerated() { let skuSingleView = YYSkuView.loadXib1() as! YYSkuView skuSingleView.delegate = self skuSingleView.tag = 10 + i skuView.addSubview(skuSingleView) skuSingleView.skuModel = model lastMaxY = skuSingleView.lastMaxY + lastMaxY } skuViewHeight.constant = lastMaxY self.layoutIfNeeded() goodsSkuViewHieght = skuView.frame.origin.y + skuView.frame.size.height + CGFloat(54 + 84) } } @IBAction func clickButton(_ sender: UIButton) { if sender.tag == 1000 { //取消 YYGoodsManager.shareManagre.hiddenSelectView() }else { //确定 delegate?.didSelectedGoodsWith?(skuValue: skuValue, number: changeNumberView.number) } } } extension YYGoodsSkuView : YYSkuViewDelegate { func didSelectedItem(skuView: YYSkuView, title: String) { dic[skuView.tag - 10] = title skuValue = "" guard let skuList = skuList else { return } //如果选择的规格和规格数组的元素数量相同,则改变库存和价格 if dic.count == skuList.count { // let dictionary = dic.sorted(by: { (t1, t2) -> Bool in return t1.0 < t2.0 ? true : false }) for (key,value) in dictionary { print(key,value) skuValue = skuValue + "," + value } skuValue = (skuValue as NSString).substring(from: 1) for (_,model) in goodsSkuList.enumerated() { if skuValue == model.skuValue { skuId = model.id priceLabel.text = "¥" + model.discountPrice inventoryLabel.text = "库存" + model.inventory + "件" break }else { priceLabel.text = "¥" + model.price inventoryLabel.text = "库存" + "0" + "件" } } } } }
mit
6962c5d68617965e2a44c0583b508d80
31.116505
102
0.541717
4.341207
false
false
false
false
SwiftGit2/SwiftGit2
SwiftGit2/References.swift
1
5588
// // References.swift // SwiftGit2 // // Created by Matt Diephouse on 1/2/15. // Copyright (c) 2015 GitHub, Inc. All rights reserved. // import Clibgit2 /// A reference to a git object. public protocol ReferenceType { /// The full name of the reference (e.g., `refs/heads/master`). var longName: String { get } /// The short human-readable name of the reference if one exists (e.g., `master`). var shortName: String? { get } /// The OID of the referenced object. var oid: OID { get } } public extension ReferenceType { static func == (lhs: Self, rhs: Self) -> Bool { return lhs.longName == rhs.longName && lhs.oid == rhs.oid } func hash(into hasher: inout Hasher) { hasher.combine(longName) hasher.combine(oid) } } /// Create a Reference, Branch, or TagReference from a libgit2 `git_reference`. internal func referenceWithLibGit2Reference(_ pointer: OpaquePointer) -> ReferenceType { if git_reference_is_branch(pointer) != 0 || git_reference_is_remote(pointer) != 0 { return Branch(pointer)! } else if git_reference_is_tag(pointer) != 0 { return TagReference(pointer)! } else { return Reference(pointer) } } /// A generic reference to a git object. public struct Reference: ReferenceType, Hashable { /// The full name of the reference (e.g., `refs/heads/master`). public let longName: String /// The short human-readable name of the reference if one exists (e.g., `master`). public let shortName: String? /// The OID of the referenced object. public let oid: OID /// Create an instance with a libgit2 `git_reference` object. public init(_ pointer: OpaquePointer) { let shorthand = String(validatingUTF8: git_reference_shorthand(pointer))! longName = String(validatingUTF8: git_reference_name(pointer))! shortName = (shorthand == longName ? nil : shorthand) oid = OID(git_reference_target(pointer).pointee) } } /// A git branch. public struct Branch: ReferenceType, Hashable { /// The full name of the reference (e.g., `refs/heads/master`). public let longName: String /// The short human-readable name of the branch (e.g., `master`). public let name: String /// A pointer to the referenced commit. public let commit: PointerTo<Commit> // MARK: Derived Properties /// The short human-readable name of the branch (e.g., `master`). /// /// This is the same as `name`, but is declared with an Optional type to adhere to /// `ReferenceType`. public var shortName: String? { return name } /// The OID of the referenced object. /// /// This is the same as `commit.oid`, but is declared here to adhere to `ReferenceType`. public var oid: OID { return commit.oid } /// Whether the branch is a local branch. public var isLocal: Bool { return longName.hasPrefix("refs/heads/") } /// Whether the branch is a remote branch. public var isRemote: Bool { return longName.hasPrefix("refs/remotes/") } /// Create an instance with a libgit2 `git_reference` object. /// /// Returns `nil` if the pointer isn't a branch. public init?(_ pointer: OpaquePointer) { var namePointer: UnsafePointer<Int8>? = nil let success = git_branch_name(&namePointer, pointer) guard success == GIT_OK.rawValue else { return nil } name = String(validatingUTF8: namePointer!)! longName = String(validatingUTF8: git_reference_name(pointer))! var oid: OID if git_reference_type(pointer).rawValue == GIT_REFERENCE_SYMBOLIC.rawValue { var resolved: OpaquePointer? = nil let success = git_reference_resolve(&resolved, pointer) guard success == GIT_OK.rawValue else { return nil } oid = OID(git_reference_target(resolved).pointee) git_reference_free(resolved) } else { oid = OID(git_reference_target(pointer).pointee) } commit = PointerTo<Commit>(oid) } } /// A git tag reference, which can be either a lightweight tag or a Tag object. public enum TagReference: ReferenceType, Hashable { /// A lightweight tag, which is just a name and an OID. case lightweight(String, OID) /// An annotated tag, which points to a Tag object. case annotated(String, Tag) /// The full name of the reference (e.g., `refs/tags/my-tag`). public var longName: String { switch self { case let .lightweight(name, _): return name case let .annotated(name, _): return name } } /// The short human-readable name of the branch (e.g., `master`). public var name: String { return String(longName["refs/tags/".endIndex...]) } /// The OID of the target object. /// /// If this is an annotated tag, the OID will be the tag's target. public var oid: OID { switch self { case let .lightweight(_, oid): return oid case let .annotated(_, tag): return tag.target.oid } } // MARK: Derived Properties /// The short human-readable name of the branch (e.g., `master`). /// /// This is the same as `name`, but is declared with an Optional type to adhere to /// `ReferenceType`. public var shortName: String? { return name } /// Create an instance with a libgit2 `git_reference` object. /// /// Returns `nil` if the pointer isn't a branch. public init?(_ pointer: OpaquePointer) { if git_reference_is_tag(pointer) == 0 { return nil } let name = String(validatingUTF8: git_reference_name(pointer))! let repo = git_reference_owner(pointer) var oid = git_reference_target(pointer).pointee var pointer: OpaquePointer? = nil let result = git_object_lookup(&pointer, repo, &oid, GIT_OBJECT_TAG) if result == GIT_OK.rawValue { self = .annotated(name, Tag(pointer!)) } else { self = .lightweight(name, OID(oid)) } git_object_free(pointer) } }
mit
43d0f5f8e96fd7ea7cbc25611fbdf24a
28.566138
89
0.689871
3.445129
false
false
false
false
luosheng/OpenSim
OpenSim/RevealInFinderAction.swift
1
652
// // RevealInFinderAction.swift // OpenSim // // Created by Luo Sheng on 07/05/2017. // Copyright © 2017 Luo Sheng. All rights reserved. // import Cocoa final class RevealInFinderAction: ApplicationActionable { var application: Application? let title = UIConstants.strings.actionRevealInFinder let icon = templatize(#imageLiteral(resourceName: "reveal")) let isAvailable: Bool = true init(application: Application) { self.application = application } func perform() { if let url = application?.sandboxUrl { NSWorkspace.shared.open(url) } } }
mit
4f5e226c6c9036c235c974865854e3df
20
64
0.637481
4.428571
false
false
false
false
natecook1000/swift
test/SILOptimizer/devirt_inherited_conformance.swift
2
5255
// RUN: %target-swift-frontend -O %s -emit-sil | %FileCheck %s // Make sure that we can dig all the way through the class hierarchy and // protocol conformances. // CHECK-LABEL: sil @$S28devirt_inherited_conformance6driveryyF : $@convention(thin) () -> () { // CHECK: bb0 // CHECK: [[UNKNOWN2a:%.*]] = function_ref @unknown2a : $@convention(thin) () -> () // CHECK: apply [[UNKNOWN2a]] // CHECK: apply [[UNKNOWN2a]] // CHECK: [[UNKNOWN3a:%.*]] = function_ref @unknown3a : $@convention(thin) () -> () // CHECK: apply [[UNKNOWN3a]] // CHECK: apply [[UNKNOWN3a]] // CHECK: return @_silgen_name("unknown1a") func unknown1a() -> () @_silgen_name("unknown1b") func unknown1b() -> () @_silgen_name("unknown2a") func unknown2a() -> () @_silgen_name("unknown2b") func unknown2b() -> () @_silgen_name("unknown3a") func unknown3a() -> () @_silgen_name("unknown3b") func unknown3b() -> () struct Int32 {} protocol P { // We do not specialize typealias's correctly now. //typealias X func doSomething(_ x : Int32) // This exposes a SILGen bug. FIXME: Fix up this test in the future. // class func doSomethingMeta() } class B : P { // We do not specialize typealias's correctly now. //typealias X = B func doSomething(_ x : Int32) { unknown1a() } // See comment in protocol P //class func doSomethingMeta() { // unknown1b() //} } class B2 : B { // When we have covariance in protocols, change this to B2. // We do not specialize typealias correctly now. //typealias X = B override func doSomething(_ x : Int32) { unknown2a() } // See comment in protocol P //override class func doSomethingMeta() { // unknown2b() //} } class B3 : B { // When we have covariance in protocols, change this to B3. // We do not specialize typealias correctly now. //typealias X = B override func doSomething(_ x : Int32) { unknown3a() } // See comment in protocol P //override class func doSomethingMeta() { // unknown3b() //} } func WhatShouldIDo<T : P>(_ t : T, _ x : Int32) { t.doSomething(x) } func WhatShouldIDo2(_ p : P, _ x : Int32) { p.doSomething(x) } public func driver() -> () { let b2 = B2() let b3 = B3() let x = Int32() WhatShouldIDo(b2, x) WhatShouldIDo2(b2, x) WhatShouldIDo(b3, x) WhatShouldIDo2(b3, x) } // Test that inherited conformances work properly with // standard operators like == and custom operators like --- // Comparable is similar to Equatable, but uses a usual method // instead of an operator. public protocol Comparable { func compare(_: Self, _: Self) -> Bool } // Define a custom operator to be used instead of == infix operator --- // Simple is a protocol that simply defines an operator and // a few methods with different number of arguments. public protocol Simple { func foo(_: Self) -> Bool func boo(_: Self, _: Self) -> Bool static func ---(_: Self, _: Self) -> Bool } public class C: Equatable, Comparable, Simple { public func compare(_ c1:C, _ c2:C) -> Bool { return c1 == c2 } public func foo(_ c:C) -> Bool { return true } public func boo(_ c1:C, _ c2:C) -> Bool { return false } } // D inherits a bunch of conformances from C. // We want to check that compiler can handle // them properly and is able to devirtualize // them. public class D: C { } public func ==(lhs: C, rhs: C) -> Bool { return true } public func ---(lhs: C, rhs: C) -> Bool { return true } public func compareEquals<T:Equatable>(_ x: T, _ y:T) -> Bool { return x == y } public func compareMinMinMin<T:Simple>(_ x: T, _ y:T) -> Bool { return x --- y } public func compareComparable<T:Comparable>(_ x: T, _ y:T) -> Bool { return x.compare(x, y) } // Check that a call of inherited Equatable.== can be devirtualized. // CHECK-LABEL: sil @$S28devirt_inherited_conformance17testCompareEqualsSbyF : $@convention(thin) () -> Bool { // CHECK: bb0 // CHECK-NEXT: integer_literal $Builtin.Int1, -1 // CHECK-NEXT: struct $Bool // CHECK: return // CHECK: } public func testCompareEquals() -> Bool { return compareEquals(D(), D()) } // Check that a call of inherited Simple.== can be devirtualized. // CHECK-LABEL: sil @$S28devirt_inherited_conformance014testCompareMinfF0SbyF : $@convention(thin) () -> Bool { // CHECK: bb0 // CHECK-NEXT: integer_literal $Builtin.Int1, -1 // CHECK-NEXT: struct $Bool // CHECK: return public func testCompareMinMinMin() -> Bool { return compareMinMinMin(D(), D()) } // Check that a call of inherited Comparable.== can be devirtualized. // CHECK-LABEL: sil @$S28devirt_inherited_conformance21testCompareComparableSbyF : $@convention(thin) () -> Bool { // CHECK: bb0 // CHECK-NEXT: integer_literal $Builtin.Int1, -1 // CHECK-NEXT: struct $Bool // CHECK: return public func testCompareComparable() -> Bool { return compareComparable(D(), D()) } public func BooCall<T:Simple>(_ x:T, _ y:T) -> Bool { return x.boo(y, y) } // Check that a call of inherited Simple.boo can be devirtualized. // CHECK-LABEL: sil @$S28devirt_inherited_conformance11testBooCallSbyF : $@convention(thin) () -> Bool { // CHECK: bb0 // CHECK-NEXT: integer_literal $Builtin.Int1, 0 // CHECK-NEXT: struct $Bool // CHECK: return public func testBooCall() -> Bool { return BooCall(D(), D()) }
apache-2.0
5d526b2969d59db3421f443db77a4060
24.264423
114
0.655756
3.315457
false
false
false
false
dbruzzone/wishing-tree
iOS/Time/Time/InitialTableViewController.swift
1
5007
// // InitialTableViewController.swift // Time // // Created by Davide Bruzzone on 10/10/15. // Copyright © 2015 Davide Bruzzone. All rights reserved. // import UIKit class InitialTableViewController: UITableViewController { var activities = [ "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen", "Twenty"] var timer = NSTimer() var counter = 0 let searchCharacter: Character = ":" override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() self.title = "Time" let statusBarHeight = UIApplication.sharedApplication().statusBarFrame.size.height self.tableView.contentInset = UIEdgeInsetsMake(statusBarHeight, 0, 0, 0) timer = NSTimer.scheduledTimerWithTimeInterval(2.0, target: self, selector: "logTime", userInfo: nil, repeats: true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return activities.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) // Configure the cell... cell.textLabel?.text = activities[indexPath.row] return cell } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ func logTime() { let visibleIndexPaths = self.tableView.indexPathsForVisibleRows for visibleIndexPath in visibleIndexPaths! { let activity = activities[visibleIndexPath.row] // Update the activities that are currently visible in the table view... let searchCharacterIndex = activity.characters.indexOf(searchCharacter) if (searchCharacterIndex != nil) { // If the activity contains a ':', get all the its characters up to but not // including the ':' let beginning = activity.substringToIndex((searchCharacterIndex)!) activities[visibleIndexPath.row] = "\(beginning): \(String(counter))" } else { // If the activity doesn't contain a ':'... activities[visibleIndexPath.row] = "\(activity): \(String(counter))" } } self.tableView.reloadRowsAtIndexPaths(visibleIndexPaths!, withRowAnimation: UITableViewRowAnimation.None) counter++ } }
gpl-3.0
a81d7d453a3fd529305bfa4a17631e91
35.275362
157
0.667
5.354011
false
false
false
false
tinypass/piano-sdk-for-ios
PianoAPI/Models/UserSubscription.swift
1
1731
import Foundation @objc(PianoAPIUserSubscription) public class UserSubscription: NSObject, Codable { /// User subscription id @objc public var subscriptionId: String? = nil @objc public var term: Term? = nil /// User subscription auto renew @objc public var autoRenew: OptionalBool? = nil /// Grace period start date @objc public var gracePeriodStartDate: Date? = nil /// User subscription next bill date @objc public var nextBillDate: Date? = nil /// The start date. @objc public var startDate: Date? = nil /// User subscription status @objc public var status: String? = nil /// Whether this subscription could be cancelled. Cancel means that access no longer be prolongated and current access will be revoked @objc public var cancelable: OptionalBool? = nil /// Whether this subscription could be cancelled and the payment for the last period could be refunded. Cancel means that access no longer be prolongated and current access will be revoked @objc public var cancelableAndRefundadle: OptionalBool? = nil /// Term billing plan description @objc public var paymentBillingPlanDescription: String? = nil public enum CodingKeys: String, CodingKey { case subscriptionId = "subscription_id" case term = "term" case autoRenew = "auto_renew" case gracePeriodStartDate = "grace_period_start_date" case nextBillDate = "next_bill_date" case startDate = "start_date" case status = "status" case cancelable = "cancelable" case cancelableAndRefundadle = "cancelable_and_refundadle" case paymentBillingPlanDescription = "payment_billing_plan_description" } }
apache-2.0
284c2814005b7c0e0978e74ad24edb74
35.0625
192
0.701329
4.628342
false
false
false
false
superk589/DereGuide
DereGuide/Unit/Controller/UnitTableViewController.swift
2
14137
// // UnitTableViewController.swift // DereGuide // // Created by zzk on 16/7/28. // Copyright © 2016 zzk. All rights reserved. // import UIKit import CoreData class UnitTableViewController: BaseViewController, UIPopoverPresentationControllerDelegate, UITableViewDelegate, UITableViewDataSource { let tableView = UITableView() private(set) lazy var addItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addUnit)) private(set) lazy var deleteItem = UIBarButtonItem(barButtonSystemItem: .trash, target: self, action: #selector(commitDeletion)) private(set) lazy var selectItem = UIBarButtonItem(title: NSLocalizedString("全选", comment: ""), style: .plain, target: self, action: #selector(selectAllAction)) private(set) lazy var deselectItem = UIBarButtonItem(title: NSLocalizedString("全部取消", comment: ""), style: .plain, target: self, action: #selector(deselectAllAction)) private(set) lazy var copyItem = UIBarButtonItem(title: NSLocalizedString("复制", comment: ""), style: .plain, target: self, action: #selector(copyAction)) private(set) lazy var spaceItem = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) var fetchedResultsController: NSFetchedResultsController<Unit>? var context: NSManagedObjectContext { return CoreDataStack.default.viewContext } var units: [Unit] { get { return fetchedResultsController?.fetchedObjects ?? [Unit]() } } let hintLabel = UILabel() override func viewDidLoad() { super.viewDidLoad() view.addSubview(tableView) tableView.snp.makeConstraints { (make) in make.edges.equalToSuperview() } tableView.register(UnitTableViewCell.self, forCellReuseIdentifier: UnitTableViewCell.description()) tableView.delegate = self tableView.dataSource = self tableView.rowHeight = UITableView.automaticDimension tableView.estimatedRowHeight = 133 tableView.tableFooterView = UIView() tableView.cellLayoutMarginsFollowReadableWidth = false tableView.keyboardDismissMode = .onDrag hintLabel.textColor = .darkGray hintLabel.text = NSLocalizedString("还没有队伍,点击右上+创建一个吧", comment: "") hintLabel.numberOfLines = 0 hintLabel.textAlignment = .center view.addSubview(hintLabel) hintLabel.snp.makeConstraints { (make) in make.center.equalToSuperview() make.left.greaterThanOrEqualToSuperview() make.right.lessThanOrEqualToSuperview() } // NotificationCenter.default.addObserver(self, selector: #selector(handleUnitModifiedNotification), name: .unitModified, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(handleUpdateEnd), name: .updateEnd, object: nil) // NotificationCenter.default.addObserver(self, selector: #selector(handleUbiquityIdentityChange), name: .NSUbiquityIdentityDidChange, object: nil) prepareToolbar() prepareFetchRequest() hintLabel.isHidden = units.count != 0 } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) tableView.indexPathsForSelectedRows?.forEach { tableView.deselectRow(at: $0, animated: true) } } private func prepareToolbar() { navigationItem.rightBarButtonItem = addItem navigationItem.leftBarButtonItem = editButtonItem } private func prepareFetchRequest() { let request: NSFetchRequest<Unit> = Unit.sortedFetchRequest request.returnsObjectsAsFaults = false fetchedResultsController = NSFetchedResultsController(fetchRequest: request, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil) fetchedResultsController?.delegate = self try? fetchedResultsController?.performFetch() } @objc func handleUnitModifiedNotification() { tableView.reloadData() } @objc func handleUpdateEnd() { tableView.reloadData() } deinit { NotificationCenter.default.removeObserver(self) } @objc func addUnit() { if units.count >= Config.maxNumberOfStoredUnits { showTooManyUnitsAlert() } else { let vc = UnitEditingController() vc.hidesBottomBarWhenPushed = true navigationController?.pushViewController(vc, animated: true) } } @objc func commitDeletion() { // 采用倒序删除法 for indexPath in (tableView.indexPathsForSelectedRows ?? [IndexPath]()).sorted(by: { $0.row > $1.row }) { // for indexPath in (tableView.indexPathsForSelectedRows?.reversed() ?? [IndexPath]()) { units[indexPath.row].markForRemoteDeletion() // Delete the row from the data source } context.saveOrRollback() setEditing(false, animated: true) } @objc func selectAllAction() { if isEditing { for i in 0..<units.count { tableView.selectRow(at: IndexPath.init(row: i, section: 0), animated: false, scrollPosition: .none) } } } @objc func deselectAllAction() { if isEditing { for i in 0..<units.count { tableView.deselectRow(at: IndexPath.init(row: i, section: 0), animated: false) } } } private func showTooManyUnitsAlert() { UIAlertController.showHintMessage(String.init(format: NSLocalizedString("您无法创建超过 %d 个队伍", comment: ""), Config.maxNumberOfStoredUnits), in: nil) } @objc func copyAction() { if let selectedIndexPaths = tableView.indexPathsForSelectedRows, isEditing { if selectedIndexPaths.count + units.count > Config.maxNumberOfStoredUnits { showTooManyUnitsAlert() } else { for indexPath in selectedIndexPaths { Unit.insert(into: context, anotherUnit: units[indexPath.row]) } context.saveOrRollback() } } } // MARK: - Table view data source func numberOfSections(in tableView: UITableView) -> Int { return fetchedResultsController?.sections?.count ?? 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let sections = fetchedResultsController?.sections, sections.count > 0 { return sections[section].numberOfObjects } else { return 0 } } override func setEditing(_ editing: Bool, animated: Bool) { super.setEditing(editing, animated: animated) if isEditing { navigationItem.rightBarButtonItem = deleteItem navigationController?.setToolbarHidden(false, animated: true) toolbarItems = [selectItem, spaceItem, deselectItem, spaceItem, copyItem] } else { navigationItem.rightBarButtonItem = addItem navigationController?.setToolbarHidden(true, animated: true) setToolbarItems(nil, animated: true) } tableView.beginUpdates() tableView.setEditing(editing, animated: animated) tableView.endUpdates() } // 实现了这两个方法 delete 手势才不会调用 setediting func tableView(_ tableView: UITableView, willBeginEditingRowAt indexPath: IndexPath) { navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(doneAction)) } func tableView(_ tableView: UITableView, didEndEditingRowAt indexPath: IndexPath?) { navigationItem.leftBarButtonItem = editButtonItem } @objc func doneAction() { tableView.setEditing(false, animated: true) } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: UnitTableViewCell.description(), for: indexPath) as! UnitTableViewCell cell.setup(with: units[indexPath.row]) return cell } func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle { if isEditing { // 编辑状态时 为多选删除模式 return UITableViewCell.EditingStyle(rawValue: 0b11)! } else { // 非编辑状态时 为左滑删除模式 return .delete } } // override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // return true // } // // override func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) { // guard sourceIndexPath.row != destinationIndexPath.row else { // return // } // fetchedResultsController?.delegate = nil // let step = (destinationIndexPath.row - sourceIndexPath.row).signum() // stride(from: sourceIndexPath.row, to: destinationIndexPath.row, by: step).forEach({ (index) in // let unit1 = units[index + step] // let unit2 = units[index] // (unit1.updatedAt, unit2.updatedAt) = (unit2.updatedAt, unit1.updatedAt) // }) // context.saveOrRollback() // fetchedResultsController?.delegate = self // } // Override to support editing the table view. func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { units[indexPath.row].markForRemoteDeletion() context.saveOrRollback() } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } // 下面这两个方法可以让分割线左侧顶格显示 不再留15像素 override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() tableView.separatorInset = .zero tableView.layoutMargins = .zero } func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { cell.separatorInset = .zero cell.layoutMargins = .zero } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if tableView.isEditing { return } // 这种情况下 cell不会自动去除选中状态 故手动置为非选中状态 tableView.cellForRow(at: indexPath)?.isSelected = false // 检查队伍数据的完整性, 用户删除数据后, 可能导致队伍中队员的数据缺失, 导致程序崩溃 let unit = units[indexPath.row] if unit.validateMembers() { let vc = UDTabViewController(unit: unit) vc.unit = unit vc.hidesBottomBarWhenPushed = true navigationController?.pushViewController(vc, animated: true) } else { let alert = UIAlertController(title: NSLocalizedString("数据缺失", comment: "弹出框标题"), message: NSLocalizedString("因数据更新导致队伍数据不完整,建议等待当前更新完成,或尝试在卡片页面下拉更新数据。", comment: "弹出框正文"), preferredStyle: .alert) alert.addAction(UIAlertAction(title: NSLocalizedString("确定", comment: "弹出框按钮"), style: .default, handler: { alert in tableView.deselectRow(at: indexPath, animated: true) })) self.navigationController?.present(alert, animated: true, completion: nil) } } // private var isUserDrivenMoving = false // // override func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) { // if !isUserDrivenMoving { // super.controller(controller, didChange: anObject, at: indexPath, for: type, newIndexPath: newIndexPath) // // } // } } extension UnitTableViewController: NSFetchedResultsControllerDelegate { // MARK: NSFetchedResultsControllerDelegate func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { tableView.beginUpdates() } func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) { switch type { case .insert: tableView.insertSections([sectionIndex], with: .fade) case .delete: tableView.deleteSections([sectionIndex], with: .fade) default: break } } func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) { switch type { case .insert: tableView.insertRows(at: [newIndexPath!], with: .automatic) case .delete: tableView.deleteRows(at: [indexPath!], with: .fade) case .update: tableView.reloadRows(at: [indexPath!], with: .none) case .move: tableView.deleteRows(at: [indexPath!], with: .fade) tableView.insertRows(at: [newIndexPath!], with: .automatic) @unknown default: fatalError() } } func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { tableView.endUpdates() if units.count != 0 { hintLabel.isHidden = true } else { hintLabel.isHidden = false } } }
mit
cf6dfbb5e9dcca2eb704908c3451fdab
39.708333
211
0.653531
5.230593
false
false
false
false
matrix-org/matrix-ios-sdk
MatrixSDK/Contrib/Swift/MXIdentityServerRestClient.swift
1
7059
/* Copyright 2019 The Matrix.org Foundation C.I.C Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation public extension MXIdentityServerRestClient { // MARK: - Setup /** Create an instance based on identity server url. - parameters: - identityServer: The identity server address. - accessToken: The identity server access token if known - handler: the block called to handle unrecognized certificate (`nil` if unrecognized certificates are ignored). - returns: a `MXIdentityServerRestClient` instance. */ @nonobjc convenience init(identityServer: URL, accessToken: String?, unrecognizedCertificateHandler handler: MXHTTPClientOnUnrecognizedCertificate?) { self.init(__identityServer: identityServer.absoluteString, accessToken: accessToken, andOnUnrecognizedCertificateBlock: handler) } // MARK: - // MARK: Association lookup /** Retrieve a user matrix id from a 3rd party id. - parameters: - descriptor: the 3PID descriptor of the user in the 3rd party system. - completion: A block object called when the operation completes. - response: Provides the Matrix user id (or `nil` if the user is not found) on success. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func lookup3PID(_ descriptor: MX3PID, completion: @escaping (_ response: MXResponse<String?>) -> Void) -> MXHTTPOperation { return __lookup3pid(descriptor.address, forMedium: descriptor.medium.identifier, success: currySuccess(completion), failure: curryFailure(completion)) } /** Retrieve user matrix ids from a list of 3rd party ids. - parameters: - descriptors: the list of 3rd party id descriptors - completion: A block object called when the operation completes. - response: Provides the user ID for each MX3PID submitted. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func lookup3PIDs(_ descriptors: [MX3PID], completion: @escaping (_ response: MXResponse<[MX3PID: String]>) -> Void) -> MXHTTPOperation { // The API expects the form: [[<(MX3PIDMedium)media1>, <(NSString*)address1>], [<(MX3PIDMedium)media2>, <(NSString*)address2>], ...] let ids = descriptors.map({ return [$0.medium.identifier, $0.address] as [String] }) return __lookup3pids(ids, success: currySuccess(transform: { (triplets) -> [MX3PID : String]? in // The API returns the data as an array of arrays: // [[<(MX3PIDMedium)media>, <(NSString*)address>, <(NSString*)userId>], ...]. var responseDictionary = [MX3PID: String]() triplets .compactMap { return $0 as? [String] } .forEach { triplet in // Make sure the array contains 3 items guard triplet.count >= 3 else { return } // Build the MX3PID struct, and add ito the dictionary let medium = MX3PID(medium: .init(identifier: triplet[0]), address: triplet[1]) responseDictionary[medium] = triplet[2] } return responseDictionary }, completion), failure: curryFailure(completion)) } // MARK: Establishing associations /** Request the validation of an email address. The identity server will send an email to this address. The end user will have to click on the link it contains to validate the address. Use the returned sid to complete operations that require authenticated email like `MXRestClient.add3PID(_:)`. - parameters: - email: the email address to validate. - clientSecret: a secret key generated by the client. (`MXTools.generateSecret()` creates such key) - sendAttempt: the number of the attempt for the validation request. Increment this value to make the identity server resend the email. Keep it to retry the request in case the previous request failed. - nextLink: the link the validation page will automatically open. Can be nil - completion: A block object called when the operation completes. - response: Provides provides the id of the email validation session on success. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func requestEmailValidation(_ email: String, clientSecret: String, sendAttempt: UInt, nextLink: String?, completion: @escaping (_ response: MXResponse<String>) -> Void) -> MXHTTPOperation { return __requestEmailValidation(email, clientSecret: clientSecret, sendAttempt: sendAttempt, nextLink: nextLink, success: currySuccess(completion), failure: curryFailure(completion)) } /** Submit the validation token received by an email or a sms. In case of success, the related third-party id has been validated - parameters: - token: the token received in the email. - medium the type of the third-party id (see kMX3PIDMediumEmail, kMX3PIDMediumMSISDN). - clientSecret: the clientSecret in the email. - sid: the email validation session id in the email. - completion: A block object called when the operation completes. - response: Indicates whether the operation was successful. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func submit3PIDValidationToken(_ token: String, medium: String, clientSecret: String, sid: String, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation { return __submit3PIDValidationToken(token, medium: medium, clientSecret: clientSecret, sid: sid, success: currySuccess(completion), failure: curryFailure(completion)) } // MARK: Other /** Sign a 3PID URL. - parameters: - signUrl: the URL that will be called for signing. - mxid: the user matrix id. - completion: A block object called when the operation completes. - response: Provides the signed data on success. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func signUrl(_ signUrl: String, mxid: String, completion: @escaping (_ response: MXResponse<[String: Any]>) -> Void) -> MXHTTPOperation { return __signUrl(signUrl, mxid: mxid, success: currySuccess(completion), failure: curryFailure(completion)) } }
apache-2.0
5bb26fc9f994a2c6044f3e9512f3d810
44.25
221
0.671342
4.838245
false
false
false
false
bandit412/SwiftCodeCollection
MathUtilities/Matrix.swift
1
16769
// // Matrix.swift // MathUtilities // // Created by Allan Anderson on 07/11/2014. // Copyright (c) 2014 Allan Anderson. All rights reserved. // import Foundation struct Matrix { var rows:Int var cols:Int init(rows inRows:Int, cols inCols:Int){ self.rows = inRows self.cols = inCols // create the Matrix as a [[Double]] var matrix = Array<Array<Double>>() for _ in 0...self.rows - 1 { matrix.append(Array(repeating: Double(), count: self.cols)) } } } struct Matrix2{ var m00:Double = 0.0, m01:Double = 0.0 var m10:Double = 0.0, m11:Double = 0.0 init(){} mutating func createIdentity(){ m00 = 1.0 m11 = 1.0 } } struct Matrix3{ var m00:Double = 0.0, m01:Double = 0.0, m02:Double = 0.0 var m10:Double = 0.0, m11:Double = 0.0, m12:Double = 0.0 var m20:Double = 0.0, m21:Double = 0.0, m22:Double = 0.0 init(){} init(scale s:Point, by shift:Point){ m00 = scale.xCoordinate m01 = 0.0 m02 = shift.xCoordinate m10 = 0.0 m11 = scale.yCoordinate m12 = shift.yCoordinate m20 = 0.0 m21 = 0.0 m22 = 1.0 } mutating func createIdentity(){ m00 = 1.0 m01 = 0.0 m02 = 0.0 m10 = 0.0 m11 = 1.0 m12 = 0.0 m20 = 0.0 m21 = 0.0 m22 = 1.0 } mutating func create2DRotation(angle r:Double, point p:Point3){ let cosine = cos(r) let sine = sin(r) m00 = cosine m01 = -1 * sine m02 = p.xCoordinate - p.xCoordinate * cosine + p.yCoordinate * sine m10 = -1 * m01 m11 = m00 m12 = p.yCoordinate - p.xCoordinate * sine - p.yCoordinate * cosine m20 = 0.0 m21 = 0.0 m22 = 1.0 } } struct Matrix4 { var m00:Double = 0.0, m01:Double = 0.0, m02:Double = 0.0, m03:Double = 0.0 var m10:Double = 0.0, m11:Double = 0.0, m12:Double = 0.0, m13:Double = 0.0 var m20:Double = 0.0, m21:Double = 0.0, m22:Double = 0.0, m23:Double = 0.0 var m30:Double = 0.0, m31:Double = 0.0, m32:Double = 0.0, m33:Double = 0.0 init(){} init(scale:Point3, by shift:Point3){ m00 = scale.xCoordinate m01 = 0.0 m02 = 0.0 m03 = shift.xCoordinate m10 = 0.0 m11 = scale.yCoordinate m12 = 0.0 m13 = shift.yCoordinate m20 = 0.0 m21 = 0.0 m22 = scale.zCoordinate m23 = shift.zCoordinate m30 = 0.0 m31 = 0.0 m32 = 0.0 m33 = 1.0 } mutating func createIdentity(){ m00 = 1.0 m01 = 0.0 m02 = 0.0 m03 = 0.0 m10 = 0.0 m11 = 1.0 m12 = 0.0 m13 = 0.0 m20 = 0.0 m21 = 0.0 m22 = 1.0 m23 = 0.0 m30 = 0.0 m31 = 0.0 m32 = 0.0 m33 = 1.0 } } struct Matrix13{ var m00 = 0.0 var m10 = 0.0 var m20 = 1.0 init() {} init(p point2:Point){ m00 = point2.xCoordinate m10 = point2.yCoordinate m20 = 1.0 } } struct Matrix14{ var m00 = 0.0 var m10 = 0.0 var m20 = 0.0 var m30 = 1.0 init() {} init(p point3:Point3){ m00 = point3.xCoordinate m10 = point3.yCoordinate m20 = point3.zCoordinate m30 = 1.0 } } func addMatrices2(a aMatrix:Matrix2, b bMatrix:Matrix2) -> Matrix2{ var aPlusB:Matrix2 = Matrix2() aPlusB.m00 = aMatrix.m00 + bMatrix.m00 aPlusB.m01 = aMatrix.m01 + bMatrix.m01 aPlusB.m10 = aMatrix.m10 + bMatrix.m10 aPlusB.m11 = aMatrix.m11 + bMatrix.m11 return aPlusB } func addMatrices3(a aMatrix:Matrix3, b bMatrix:Matrix3) -> Matrix3{ var aPlusB:Matrix3 = Matrix3() aPlusB.m00 = aMatrix.m00 + bMatrix.m00 aPlusB.m01 = aMatrix.m01 + bMatrix.m01 aPlusB.m02 = aMatrix.m02 + bMatrix.m02 aPlusB.m10 = aMatrix.m10 + bMatrix.m10 aPlusB.m11 = aMatrix.m11 + bMatrix.m11 aPlusB.m12 = aMatrix.m12 + bMatrix.m12 aPlusB.m20 = aMatrix.m20 + bMatrix.m20 aPlusB.m21 = aMatrix.m21 + bMatrix.m21 aPlusB.m22 = aMatrix.m22 + bMatrix.m22 return aPlusB } func addMatrices4(a aMatrix:Matrix4, b bMatrix:Matrix4) -> Matrix4{ var aPlusB:Matrix4 = Matrix4() aPlusB.m00 = aMatrix.m00 + bMatrix.m00 aPlusB.m01 = aMatrix.m01 + bMatrix.m01 aPlusB.m02 = aMatrix.m02 + bMatrix.m02 aPlusB.m03 = aMatrix.m03 + bMatrix.m03 aPlusB.m10 = aMatrix.m10 + bMatrix.m10 aPlusB.m11 = aMatrix.m11 + bMatrix.m11 aPlusB.m12 = aMatrix.m12 + bMatrix.m12 aPlusB.m13 = aMatrix.m13 + bMatrix.m13 aPlusB.m20 = aMatrix.m20 + bMatrix.m20 aPlusB.m21 = aMatrix.m21 + bMatrix.m21 aPlusB.m22 = aMatrix.m22 + bMatrix.m22 aPlusB.m23 = aMatrix.m23 + bMatrix.m23 aPlusB.m30 = aMatrix.m30 + bMatrix.m30 aPlusB.m31 = aMatrix.m31 + bMatrix.m31 aPlusB.m32 = aMatrix.m32 + bMatrix.m32 aPlusB.m33 = aMatrix.m33 + bMatrix.m33 return aPlusB } func multiplyMatrix(_ a:Matrix2, by b:Matrix2) ->Matrix2{ var aTimesB = Matrix2() aTimesB.m00 = a.m00 * b.m00 + a.m01 * b.m10 aTimesB.m01 = a.m00 * b.m10 + a.m01 * b.m11 aTimesB.m10 = a.m10 * b.m00 + a.m11 * b.m10 aTimesB.m11 = a.m10 * b.m10 + a.m11 * b.m11 return aTimesB } func multiplyMatrix(_ a:Matrix3, by b:Matrix3) ->Matrix3{ var aTimesB = Matrix3() aTimesB.m00 = a.m00 * b.m00 + a.m01 * b.m10 + a.m02 * b.m20 aTimesB.m01 = a.m00 * b.m01 + a.m01 * b.m11 + a.m02 * b.m21 aTimesB.m02 = a.m00 * b.m02 + a.m01 * b.m12 + a.m02 * b.m22 aTimesB.m10 = a.m10 * b.m00 + a.m11 * b.m10 + a.m12 * b.m20 aTimesB.m11 = a.m10 * b.m01 + a.m11 * b.m11 + a.m12 * b.m21 aTimesB.m12 = a.m10 * b.m02 + a.m11 * b.m12 + a.m12 * b.m22 aTimesB.m20 = a.m20 * b.m00 + a.m21 * b.m10 + a.m22 * b.m20 aTimesB.m21 = a.m20 * b.m01 + a.m21 * b.m11 + a.m22 * b.m21 aTimesB.m22 = a.m20 * b.m02 + a.m21 * b.m12 + a.m22 * b.m22 return aTimesB } func multiplyMatrix(_ a:Matrix4, by b:Matrix4) ->Matrix4{ var aTimesB = Matrix4() aTimesB.m00 = a.m00 * b.m00 + a.m01 * b.m10 + a.m02 * b.m20 + a.m03 * b.m30 aTimesB.m01 = a.m00 * b.m01 + a.m01 * b.m11 + a.m02 * b.m21 + a.m03 * b.m31 aTimesB.m02 = a.m00 * b.m02 + a.m01 * b.m12 + a.m02 * b.m22 + a.m03 * b.m32 aTimesB.m03 = a.m00 * b.m03 + a.m01 * b.m13 + a.m02 * b.m23 + a.m03 * b.m33 aTimesB.m10 = a.m10 * b.m00 + a.m11 * b.m10 + a.m12 * b.m20 + a.m13 * b.m30 aTimesB.m11 = a.m10 * b.m01 + a.m11 * b.m11 + a.m12 * b.m21 + a.m13 * b.m31 aTimesB.m12 = a.m10 * b.m02 + a.m11 * b.m12 + a.m12 * b.m22 + a.m13 * b.m32 aTimesB.m13 = a.m10 * b.m03 + a.m11 * b.m13 + a.m12 * b.m23 + a.m13 * b.m33 aTimesB.m20 = a.m20 * b.m00 + a.m21 * b.m10 + a.m22 * b.m20 + a.m23 * b.m30 aTimesB.m21 = a.m20 * b.m01 + a.m21 * b.m11 + a.m22 * b.m21 + a.m23 * b.m31 aTimesB.m22 = a.m20 * b.m02 + a.m21 * b.m12 + a.m22 * b.m22 + a.m23 * b.m32 aTimesB.m23 = a.m20 * b.m03 + a.m21 * b.m13 + a.m22 * b.m23 + a.m23 * b.m33 aTimesB.m30 = a.m30 * b.m00 + a.m31 * b.m10 + a.m32 * b.m20 + a.m33 * b.m30 aTimesB.m31 = a.m30 * b.m01 + a.m31 * b.m11 + a.m32 * b.m21 + a.m33 * b.m31 aTimesB.m32 = a.m30 * b.m02 + a.m31 * b.m12 + a.m32 * b.m22 + a.m33 * b.m32 aTimesB.m33 = a.m30 * b.m03 + a.m31 * b.m13 + a.m32 * b.m23 + a.m33 * b.m33 return aTimesB } func multiplyMatrix(_ a:Matrix3, by b:Matrix13) ->Matrix13{ var aTimesB = Matrix13() aTimesB.m00 = a.m00 * b.m00 + a.m01 * b.m10 + a.m02 * b.m20 aTimesB.m10 = a.m10 * b.m00 + a.m11 * b.m10 + a.m12 * b.m20 aTimesB.m20 = a.m20 * b.m00 + a.m21 * b.m10 + a.m22 * b.m20 return aTimesB } func multiplyMatrix(_ a:Matrix4, by b:Matrix14) ->Matrix14{ var aTimesB = Matrix14() aTimesB.m00 = a.m00 * b.m00 + a.m01 * b.m10 + a.m02 * b.m20 + a.m03 * b.m30 aTimesB.m10 = a.m10 * b.m00 + a.m11 * b.m10 + a.m12 * b.m20 + a.m13 * b.m30 aTimesB.m20 = a.m20 * b.m00 + a.m21 * b.m10 + a.m22 * b.m20 + a.m23 * b.m30 aTimesB.m30 = a.m30 * b.m00 + a.m31 * b.m10 + a.m32 * b.m20 + a.m33 * b.m30 return aTimesB } func detMatrix(matrix2 a:Matrix2) -> Double{ return a.m00 * a.m11 - a.m01 * a.m10 } func detMatrix(matrix3 a:Matrix3) -> Double{ var da1 = Matrix2() var da2 = Matrix2() var da3 = Matrix2() // assign values //da1 da1.m00 = a.m11 da1.m01 = a.m12 da1.m10 = a.m21 da1.m11 = a.m22 //da2 da2.m00 = a.m10 da2.m01 = a.m12 da2.m10 = a.m20 da2.m11 = a.m22 //da3 da3.m00 = a.m10 da3.m01 = a.m11 da3.m10 = a.m20 da3.m11 = a.m21 return a.m00 * detMatrix(matrix2: da1) - a.m01 * detMatrix(matrix2: da2) + a.m02 * detMatrix(matrix2: da3) } func detMatrix(matrix4 a:Matrix4) -> Double{ var da1 = Matrix3() var da2 = Matrix3() var da3 = Matrix3() var da4 = Matrix3() // assign values //da1 da1.m00 = a.m11 da1.m01 = a.m12 da1.m02 = a.m13 da1.m10 = a.m21 da1.m11 = a.m22 da1.m12 = a.m23 da1.m20 = a.m31 da1.m21 = a.m32 da1.m22 = a.m33 //da2 da2.m00 = a.m10 da2.m01 = a.m12 da2.m02 = a.m13 da2.m10 = a.m20 da2.m01 = a.m22 da2.m02 = a.m23 da2.m20 = a.m30 da2.m21 = a.m32 da2.m22 = a.m33 //da3 da3.m00 = a.m10 da3.m01 = a.m11 da3.m02 = a.m13 da3.m10 = a.m20 da3.m11 = a.m21 da3.m12 = a.m23 da3.m20 = a.m30 da3.m21 = a.m31 da3.m22 = a.m33 //da4 da4.m00 = a.m10 da4.m01 = a.m11 da4.m02 = a.m12 da4.m10 = a.m20 da4.m11 = a.m21 da4.m12 = a.m22 da4.m20 = a.m30 da4.m21 = a.m31 da4.m22 = a.m32 // calculate determinant return a.m00 * detMatrix(matrix3: da1) - a.m01 * detMatrix(matrix3: da2) + a.m02 * detMatrix(matrix3: da3) - a.m03 * detMatrix(matrix3: da4) } func invMatrix(matrix2 a:Matrix2) -> Matrix2{ var inverse = Matrix2() let det = detMatrix(matrix2: a) inverse.m00 = a.m11 / det inverse.m01 = -1 * a.m01 / det inverse.m10 = -1 * a.m10 / det inverse.m11 = a.m00 / det return inverse } func invMatrix(matrix3 a:Matrix3) -> Matrix3{ var inverse = Matrix3() // cofactor matrices var c00 = Matrix2() var c01 = Matrix2() var c02 = Matrix2() var c10 = Matrix2() var c11 = Matrix2() var c12 = Matrix2() var c20 = Matrix2() var c21 = Matrix2() var c22 = Matrix2() // cofactor matrix var cof = Matrix3() let det = detMatrix(matrix3: a) //1. setup cofactor array using determinants c00.m00 = a.m11 c00.m01 = a.m12 c00.m10 = a.m21 c00.m11 = a.m22 c01.m00 = a.m10 c01.m01 = a.m12 c01.m10 = a.m20 c01.m11 = a.m22 c02.m00 = a.m10 c02.m01 = a.m11 c02.m10 = a.m20 c02.m11 = a.m21 c10.m00 = a.m01 c10.m01 = a.m02 c10.m10 = a.m21 c10.m11 = a.m22 c11.m00 = a.m00 c11.m01 = a.m02 c11.m10 = a.m20 c11.m11 = a.m22 c12.m00 = a.m00 c12.m01 = a.m01 c12.m10 = a.m20 c12.m11 = a.m21 c20.m00 = a.m01 c20.m01 = a.m02 c20.m10 = a.m11 c20.m11 = a.m12 c21.m00 = a.m00 c21.m01 = a.m02 c21.m10 = a.m10 c21.m11 = a.m12 c22.m00 = a.m00 c22.m01 = a.m01 c22.m10 = a.m10 c22.m11 = a.m11 cof.m00 = detMatrix(matrix2: c00) cof.m01 = detMatrix(matrix2: c01) * -1 cof.m02 = detMatrix(matrix2: c02) cof.m10 = detMatrix(matrix2: c10) * -1 cof.m11 = detMatrix(matrix2: c11) cof.m12 = detMatrix(matrix2: c12) * -1 cof.m20 = detMatrix(matrix2: c20) cof.m21 = detMatrix(matrix2: c21) * -1 cof.m22 = detMatrix(matrix2: c22) //2. transpose the cofactor matrix & divide by the determinant inverse.m00 = cof.m00 / det inverse.m01 = cof.m10 / det inverse.m02 = cof.m20 / det inverse.m10 = cof.m01 / det inverse.m11 = cof.m11 / det inverse.m12 = cof.m21 / det inverse.m20 = cof.m02 / det inverse.m21 = cof.m12 / det inverse.m22 = cof.m22 / det // return return inverse } func invMatrix(matrix4 a:Matrix4) -> Matrix4{ var inverse = Matrix4() // cofactor matrices var c00 = Matrix3() var c01 = Matrix3() var c02 = Matrix3() var c03 = Matrix3() var c10 = Matrix3() var c11 = Matrix3() var c12 = Matrix3() var c13 = Matrix3() var c20 = Matrix3() var c21 = Matrix3() var c22 = Matrix3() var c23 = Matrix3() var c30 = Matrix3() var c31 = Matrix3() var c32 = Matrix3() var c33 = Matrix3() // cofactor matrix var cof = Matrix4() let det = detMatrix(matrix4: a) //1. setup cofactor array using determinants c00.m00 = a.m11 c00.m01 = a.m12 c00.m02 = a.m13 c00.m10 = a.m21 c00.m11 = a.m22 c00.m12 = a.m23 c00.m20 = a.m31 c00.m21 = a.m32 c00.m22 = a.m33 c01.m00 = a.m10 c01.m01 = a.m12 c01.m02 = a.m13 c01.m10 = a.m20 c01.m11 = a.m22 c01.m12 = a.m23 c01.m20 = a.m30 c01.m21 = a.m32 c01.m22 = a.m33 c02.m00 = a.m10 c02.m01 = a.m11 c02.m02 = a.m13 c02.m10 = a.m20 c02.m11 = a.m21 c02.m12 = a.m23 c02.m20 = a.m30 c02.m21 = a.m31 c02.m22 = a.m33 c03.m00 = a.m10 c03.m01 = a.m11 c03.m02 = a.m12 c03.m10 = a.m20 c03.m11 = a.m21 c03.m12 = a.m22 c03.m20 = a.m30 c03.m21 = a.m31 c03.m22 = a.m32 c10.m00 = a.m01 c10.m01 = a.m02 c10.m02 = a.m03 c10.m10 = a.m21 c10.m11 = a.m22 c10.m12 = a.m23 c10.m20 = a.m31 c10.m21 = a.m32 c10.m22 = a.m33 c11.m00 = a.m00 c11.m01 = a.m02 c11.m02 = a.m03 c11.m10 = a.m20 c11.m11 = a.m22 c11.m12 = a.m23 c11.m20 = a.m30 c11.m21 = a.m32 c11.m22 = a.m33 c12.m00 = a.m00 c12.m01 = a.m01 c12.m02 = a.m03 c12.m10 = a.m20 c12.m11 = a.m21 c12.m12 = a.m23 c12.m20 = a.m30 c12.m21 = a.m31 c12.m22 = a.m33 c13.m00 = a.m00 c13.m01 = a.m01 c13.m02 = a.m02 c13.m10 = a.m20 c13.m11 = a.m21 c13.m12 = a.m22 c13.m20 = a.m30 c13.m21 = a.m31 c13.m22 = a.m32 c20.m00 = a.m01 c20.m01 = a.m02 c20.m02 = a.m03 c20.m10 = a.m11 c20.m11 = a.m12 c20.m12 = a.m13 c20.m20 = a.m31 c20.m21 = a.m32 c20.m22 = a.m33 c21.m00 = a.m00 c21.m01 = a.m02 c21.m02 = a.m03 c21.m10 = a.m10 c21.m11 = a.m12 c21.m12 = a.m13 c21.m20 = a.m30 c21.m21 = a.m32 c21.m22 = a.m33 c22.m00 = a.m00 c22.m01 = a.m01 c22.m02 = a.m03 c22.m10 = a.m10 c22.m11 = a.m11 c22.m12 = a.m13 c22.m20 = a.m30 c22.m21 = a.m31 c22.m22 = a.m33 c23.m00 = a.m00 c23.m01 = a.m01 c23.m02 = a.m02 c23.m10 = a.m10 c23.m11 = a.m11 c23.m12 = a.m12 c23.m20 = a.m30 c23.m21 = a.m31 c23.m22 = a.m32 c30.m00 = a.m01 c30.m01 = a.m02 c30.m02 = a.m03 c30.m10 = a.m11 c30.m11 = a.m12 c30.m12 = a.m13 c30.m20 = a.m21 c30.m21 = a.m22 c30.m22 = a.m23 c31.m00 = a.m00 c31.m01 = a.m02 c31.m02 = a.m03 c31.m10 = a.m10 c31.m11 = a.m12 c31.m12 = a.m13 c31.m20 = a.m20 c31.m21 = a.m22 c31.m22 = a.m23 c32.m00 = a.m00 c32.m01 = a.m01 c32.m02 = a.m03 c32.m10 = a.m10 c32.m11 = a.m11 c32.m12 = a.m13 c32.m20 = a.m20 c32.m21 = a.m21 c32.m22 = a.m23 c33.m00 = a.m00 c33.m01 = a.m01 c33.m02 = a.m02 c33.m10 = a.m10 c33.m11 = a.m11 c33.m12 = a.m12 c33.m20 = a.m20 c33.m21 = a.m21 c33.m22 = a.m22 cof.m00 = detMatrix(matrix3: c00) cof.m01 = detMatrix(matrix3: c01) * -1 cof.m02 = detMatrix(matrix3: c02) cof.m03 = detMatrix(matrix3: c03) * -1 cof.m10 = detMatrix(matrix3: c10) * -1 cof.m11 = detMatrix(matrix3: c11) cof.m12 = detMatrix(matrix3: c12) * -1 cof.m13 = detMatrix(matrix3: c13) cof.m20 = detMatrix(matrix3: c20) cof.m21 = detMatrix(matrix3: c21) * -1 cof.m22 = detMatrix(matrix3: c22) cof.m23 = detMatrix(matrix3: c23) * -1 cof.m30 = detMatrix(matrix3: c30) * -1 cof.m31 = detMatrix(matrix3: c31) cof.m32 = detMatrix(matrix3: c32) * -1 cof.m33 = detMatrix(matrix3: c33) //2. transpose the cofactor matrix & divide by the determinant inverse.m00 = cof.m00 / det inverse.m01 = cof.m10 / det inverse.m02 = cof.m20 / det inverse.m03 = cof.m30 / det inverse.m10 = cof.m01 / det inverse.m11 = cof.m11 / det inverse.m12 = cof.m21 / det inverse.m13 = cof.m31 / det inverse.m20 = cof.m02 / det inverse.m21 = cof.m12 / det inverse.m22 = cof.m22 / det inverse.m23 = cof.m32 / det inverse.m30 = cof.m03 / det inverse.m31 = cof.m13 / det inverse.m32 = cof.m23 / det inverse.m33 = cof.m33 / det // return return inverse }
gpl-3.0
5d77c12f31dae01c34971c1fa3f1d51a
25.61746
144
0.554535
2.216949
false
false
false
false
agrippa1994/iOS-PLC
Pods/Charts/Charts/Classes/Renderers/ChartXAxisRendererBarChart.swift
5
5377
// // ChartXAxisRendererBarChart.swift // Charts // // Created by Daniel Cohen Gindi on 3/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics import UIKit public class ChartXAxisRendererBarChart: ChartXAxisRenderer { internal weak var _chart: BarChartView! public init(viewPortHandler: ChartViewPortHandler, xAxis: ChartXAxis, transformer: ChartTransformer!, chart: BarChartView) { super.init(viewPortHandler: viewPortHandler, xAxis: xAxis, transformer: transformer) self._chart = chart } /// draws the x-labels on the specified y-position internal override func drawLabels(context context: CGContext?, pos: CGFloat) { if (_chart.data === nil) { return } let paraStyle = NSParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle paraStyle.alignment = .Center let labelAttrs = [NSFontAttributeName: _xAxis.labelFont, NSForegroundColorAttributeName: _xAxis.labelTextColor, NSParagraphStyleAttributeName: paraStyle] let barData = _chart.data as! BarChartData let step = barData.dataSetCount let valueToPixelMatrix = transformer.valueToPixelMatrix var position = CGPoint(x: 0.0, y: 0.0) var labelMaxSize = CGSize() if (_xAxis.isWordWrapEnabled) { labelMaxSize.width = _xAxis.wordWrapWidthPercent * valueToPixelMatrix.a } for (var i = _minX, maxX = min(_maxX + 1, _xAxis.values.count); i < maxX; i += _xAxis.axisLabelModulus) { let label = i >= 0 && i < _xAxis.values.count ? _xAxis.values[i] : nil if (label == nil) { continue } position.x = CGFloat(i * step) + CGFloat(i) * barData.groupSpace + barData.groupSpace / 2.0 position.y = 0.0 // consider groups (center label for each group) if (step > 1) { position.x += (CGFloat(step) - 1.0) / 2.0 } position = CGPointApplyAffineTransform(position, valueToPixelMatrix) if (viewPortHandler.isInBoundsX(position.x)) { if (_xAxis.isAvoidFirstLastClippingEnabled) { // avoid clipping of the last if (i == _xAxis.values.count - 1) { let width = label!.sizeWithAttributes(labelAttrs).width if (width > viewPortHandler.offsetRight * 2.0 && position.x + width > viewPortHandler.chartWidth) { position.x -= width / 2.0 } } else if (i == 0) { // avoid clipping of the first let width = label!.sizeWithAttributes(labelAttrs).width position.x += width / 2.0 } } ChartUtils.drawMultilineText(context: context, text: label!, point: CGPoint(x: position.x, y: pos), align: .Center, attributes: labelAttrs, constrainedToSize: labelMaxSize) } } } private var _gridLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint()) public override func renderGridLines(context context: CGContext?) { if (!_xAxis.isDrawGridLinesEnabled || !_xAxis.isEnabled) { return } let barData = _chart.data as! BarChartData let step = barData.dataSetCount CGContextSaveGState(context) CGContextSetStrokeColorWithColor(context, _xAxis.gridColor.CGColor) CGContextSetLineWidth(context, _xAxis.gridLineWidth) if (_xAxis.gridLineDashLengths != nil) { CGContextSetLineDash(context, _xAxis.gridLineDashPhase, _xAxis.gridLineDashLengths, _xAxis.gridLineDashLengths.count) } else { CGContextSetLineDash(context, 0.0, nil, 0) } let valueToPixelMatrix = transformer.valueToPixelMatrix var position = CGPoint(x: 0.0, y: 0.0) for (var i = _minX; i < _maxX; i += _xAxis.axisLabelModulus) { position.x = CGFloat(i * step) + CGFloat(i) * barData.groupSpace - 0.5 position.y = 0.0 position = CGPointApplyAffineTransform(position, valueToPixelMatrix) if (viewPortHandler.isInBoundsX(position.x)) { _gridLineSegmentsBuffer[0].x = position.x _gridLineSegmentsBuffer[0].y = viewPortHandler.contentTop _gridLineSegmentsBuffer[1].x = position.x _gridLineSegmentsBuffer[1].y = viewPortHandler.contentBottom CGContextStrokeLineSegments(context, _gridLineSegmentsBuffer, 2) } } CGContextRestoreGState(context) } }
mit
ac8fb09bdb4ed67fde7de1817c2ea178
34.615894
188
0.555328
5.447822
false
false
false
false
YotrolZ/RazzleDazzle
Example/RazzleDazzleTests/RAZInterpolatableSpec.swift
24
2317
// // InterpolatableSpec.swift // RazzleDazzle // // Created by Laura Skelton on 6/17/15. // Copyright (c) 2015 IFTTT. All rights reserved. // import RazzleDazzle import Nimble import Quick class InterpolatableSpec: QuickSpec { override func spec() { describe("Interpolatable-CGFloat") { it("should interpolate floats") { let middleFloat = CGFloat.interpolateFrom(1, to: 3, withProgress: 0.5) expect(middleFloat).to(equal(2)) } it("should interpolate floats with less than halfway progress") { let middleFloat = CGFloat.interpolateFrom(1, to: 2, withProgress: 0.25) expect(middleFloat).to(equal(1.25)) } it("should interpolate floats with greater than halfway progress") { let middleFloat = CGFloat.interpolateFrom(1, to: 2, withProgress: 0.75) expect(middleFloat).to(equal(1.75)) } it("should interpolate floats with no progress") { let middleFloat = CGFloat.interpolateFrom(1, to: 2, withProgress: 0) expect(middleFloat).to(equal(1)) } it("should interpolate floats with full progress") { let middleFloat = CGFloat.interpolateFrom(1, to: 2, withProgress: 1) expect(middleFloat).to(equal(2)) } } describe("Interpolatable-CGPoint") { it("should interpolate points") { let middlePoint = CGPoint.interpolateFrom(CGPointMake(1, 2), to: CGPointMake(3, 6), withProgress: 0.5) expect(middlePoint).to(equal(CGPointMake(2, 4))) } } describe("Interpolatable-CGSize") { it("should interpolate sizes") { let middleSize = CGSize.interpolateFrom(CGSizeMake(1, 2), to: CGSizeMake(3, 6), withProgress: 0.5) expect(middleSize).to(equal(CGSizeMake(2, 4))) } } describe("Interpolatable-CGRect") { it("should interpolate rects") { let middleRect = CGRect.interpolateFrom(CGRectMake(1, 2, 10, 20), to: CGRectMake(3, 6, 30, 60), withProgress: 0.5) expect(middleRect).to(equal(CGRectMake(2, 4, 20, 40))) } } } }
mit
a098a801888ee9d7a194787fe43b5cf8
39.649123
130
0.57445
4.251376
false
false
false
false
marmelroy/PeekPop
PeekPop/PeekPop.swift
1
3389
// // PeekPop.swift // PeekPop // // Created by Roy Marmelstein on 06/03/2016. // Copyright © 2016 Roy Marmelstein. All rights reserved. // import Foundation /// PeekPop class open class PeekPop: NSObject { //MARK: Variables fileprivate var previewingContexts = [PreviewingContext]() internal var viewController: UIViewController internal var peekPopGestureRecognizer: PeekPopGestureRecognizer? /// Fallback to Apple's peek and pop implementation for devices that support it. fileprivate var forceTouchDelegate: ForceTouchDelegate? //MARK: Lifecycle /** Peek pop initializer - parameter viewController: hosting UIViewController - returns: PeekPop object */ public init(viewController: UIViewController) { self.viewController = viewController } //MARK: Delegate registration /// Registers a view controller to participate with 3D Touch preview (peek) and commit (pop). open func registerForPreviewingWithDelegate(_ delegate: PeekPopPreviewingDelegate, sourceView: UIView) -> PreviewingContext { let previewing = PreviewingContext(delegate: delegate, sourceView: sourceView) previewingContexts.append(previewing) // If force touch is available, use Apple's implementation. Otherwise, use PeekPop's. if isForceTouchCapable() { let delegate = ForceTouchDelegate(delegate: delegate) delegate.registerFor3DTouch(sourceView, viewController: viewController) forceTouchDelegate = delegate } else { let gestureRecognizer = PeekPopGestureRecognizer(peekPop: self) gestureRecognizer.context = previewing gestureRecognizer.cancelsTouchesInView = false gestureRecognizer.delaysTouchesBegan = true gestureRecognizer.delegate = self sourceView.addGestureRecognizer(gestureRecognizer) peekPopGestureRecognizer = gestureRecognizer } return previewing } /// Check whether force touch is available func isForceTouchCapable() -> Bool { if #available(iOS 9.0, *) { return (self.viewController.traitCollection.forceTouchCapability == UIForceTouchCapability.available && TARGET_OS_SIMULATOR != 1) } return false } } /// Previewing context struct open class PreviewingContext { /// Previewing delegate open weak var delegate: PeekPopPreviewingDelegate? /// Source view open let sourceView: UIView /// Source rect open var sourceRect: CGRect init(delegate: PeekPopPreviewingDelegate, sourceView: UIView) { self.delegate = delegate self.sourceView = sourceView self.sourceRect = sourceView.frame } } /// Peek pop previewing delegate public protocol PeekPopPreviewingDelegate: class { /// Provide view controller for previewing context in location. If you return nil, a preview presentation will not be performed. func previewingContext(_ previewingContext: PreviewingContext, viewControllerForLocation location: CGPoint) -> UIViewController? /// Commit view controller when preview is committed. func previewingContext(_ previewingContext: PreviewingContext, commitViewController viewControllerToCommit: UIViewController) }
mit
b30a50fd2ee9a352aa03f46ee18b6128
33.571429
141
0.696281
5.892174
false
false
false
false
ACChe/eidolon
Kiosk/App/GlobalFunctions.swift
1
2759
import ReactiveCocoa import Reachability import Moya // Ideally a Pod. For now a file. func delayToMainThread(delay:Double, closure:()->()) { dispatch_after ( dispatch_time( DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC)) ), dispatch_get_main_queue(), closure) } func logPath() -> NSURL { let docs = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).last! return docs.URLByAppendingPathComponent("logger.txt") } let logger = Logger(destination: logPath()) private let reachabilityManager = ReachabilityManager() // A signal that completes when the app gets online (possibly completes immediately). func connectedToInternetOrStubbingSignal() -> RACSignal { let online = reachabilityManager.reachSignal let stubbing = RACSignal.`return`(APIKeys.sharedKeys.stubResponses) return RACSignal.combineLatest([online, stubbing]).or() } func responseIsOK(object: AnyObject!) -> AnyObject { if let response = object as? MoyaResponse { return response.statusCode == 200 } return false } // Adapted from https://github.com/FUKUZAWA-Tadashi/FHCCommander/blob/67c67757ee418a106e0ce0c0820459299b3d77bb/fhcc/Convenience.swift#L33-L44 func getSSID() -> String? { let interfaces: CFArray! = CNCopySupportedInterfaces() if interfaces == nil { return nil } let if0: UnsafePointer<Void>? = CFArrayGetValueAtIndex(interfaces, 0) if if0 == nil { return nil } let interfaceName: CFStringRef = unsafeBitCast(if0!, CFStringRef.self) let dictionary = CNCopyCurrentNetworkInfo(interfaceName) as NSDictionary? if dictionary == nil { return nil } return dictionary?[kCNNetworkInfoKeySSID as String] as? String } /// Looks for a connection to an Artsy WiFi network. func detectDevelopmentEnvironment() -> Bool { var developmentEnvironment = false #if (arch(i386) || arch(x86_64)) && os(iOS) developmentEnvironment = true #else developmentEnvironment = getSSID()?.lowercaseString.containsString("artsy") ?? false #endif return developmentEnvironment } private class ReachabilityManager: NSObject { let reachSignal: RACSignal = RACReplaySubject(capacity: 1) private let reachability = Reachability.reachabilityForInternetConnection() override init() { super.init() reachability.reachableBlock = { (_) in return (self.reachSignal as! RACSubject).sendNext(true) } reachability.unreachableBlock = { (_) in return (self.reachSignal as! RACSubject).sendNext(false) } reachability.startNotifier() (reachSignal as! RACSubject).sendNext(reachability.isReachable()) } }
mit
272782cce6ad9161d830dda2890ecf81
31.458824
141
0.70569
4.464401
false
false
false
false
maxgoedjen/M3U8
M3U8/String+M3U8Attributes.swift
1
1502
// // String+M3U8Attributes.swift // M3U8 // // Created by Max Goedjen on 8/10/15. // Copyright © 2015 Max Goedjen. All rights reserved. // import Foundation public extension String { public var m3u8Attributes: [String: String] { guard let firstLine = componentsSeparatedByString("\n").first else { return [:] } // Wooooooo string escapes // Reference Ruby-style regex: /([A-z-]+)\s*=\s*("[^"]*"|[^,]*)/ do { let regex = try NSRegularExpression(pattern: "([A-z-]+)\\s*=\\s*(\"[^\"]*\"|[^,]*)", options: []) let matches = regex.matchesInString(firstLine, options: [], range: NSMakeRange(0, (firstLine as NSString).length)) return matches.reduce([:] as [String: String]) { acc, next in let nsStrung = firstLine as NSString let key = nsStrung.substringWithRange(next.rangeAtIndex(1)) let value = nsStrung.substringWithRange(next.rangeAtIndex(2)).stringByReplacingOccurrencesOfString("\"", withString: "") var modifiedAccum = acc modifiedAccum[key] = value return modifiedAccum } } catch _ { return [:] } } } public extension Bool { public init?(string: String?) { guard let string = string else { return nil } self = (string as NSString).boolValue } public var m3u8Description: String { return self == true ? "YES" : "NO" } }
mit
303eef636cc640b1de996c7644243986
32.377778
136
0.568288
4.30086
false
false
false
false
einsteinx2/iSub
Classes/Extensions/Data.swift
1
1267
// // Data.swift // iSub // // Created by Benjamin Baron on 1/13/17. // Copyright © 2017 Ben Baron. All rights reserved. // import Foundation extension Int { var hex: String { return String(format: "%02X", self) } } extension Data { var hex: String { return self.map{Int($0).hex}.joined() } var md5: String { var result = Data(count: Int(CC_MD5_DIGEST_LENGTH)) _ = result.withUnsafeMutableBytes { resultPtr in self.withUnsafeBytes { bytes in CC_MD5(bytes, CC_LONG(count), resultPtr) } } return result.hex } var sha1: String { var result = Data(count: Int(CC_SHA1_DIGEST_LENGTH)) _ = result.withUnsafeMutableBytes { resultPtr in self.withUnsafeBytes() { bytes in CC_SHA1(bytes, CC_LONG(count), resultPtr) } } return result.hex } var sha256: String { var result = Data(count: Int(CC_SHA256_DIGEST_LENGTH)) _ = result.withUnsafeMutableBytes { resultPtr in self.withUnsafeBytes { bytes in CC_SHA256(bytes, CC_LONG(count), resultPtr) } } return result.hex } }
gpl-3.0
847f9fb484b980714ab4a6377d80f731
23.346154
62
0.543444
3.993691
false
false
false
false
AnnMic/FestivalArchitect
FestivalArchitect/Visitor.swift
1
700
// // Visitor.swift // FestivalArchitect // // Created by Ann Michelsen on 11/11/14. // Copyright (c) 2014 AnnMi. All rights reserved. // import Foundation class Visitor : NSObject { var currentState:AIState var coins:Int = 0 var thirsty:Int = 0 var hungry:Int = 0 var fatigue:Int = 0 var location:CGPoint! init(currentState:AIState) { self.currentState = currentState } /* func changeState(newState:AIState){ currentState.exit(self) currentState = newState newState.enter(self) } func update(dt: Float) { // update thirsty++ currentState.execute(self) } */ }
mit
af1829875536cd5166253d0cefcd56ff
17.421053
50
0.591429
3.888889
false
false
false
false
ryanbooker/Swiftz
Sources/HList.swift
1
7319
// // HList.swift // Swiftz // // Created by Maxwell Swadling on 19/06/2014. // Copyright (c) 2014-2016 Maxwell Swadling. All rights reserved. // #if !XCODE_BUILD import Operadics import Swiftx #endif /// An HList can be thought of like a tuple, but with list-like operations on /// the types. Unlike tuples there is no simple construction syntax as with the /// `(,)` operator. But what HLists lack in convenience they gain in /// flexibility. /// /// An HList is a purely static entity. All its attributes including its /// length, the type of each element, and compatible operations on said elements /// exist fully at compile time. HLists, like regular lists, support folds, /// maps, and appends, only at the type rather than term level. public protocol HList { associatedtype Head associatedtype Tail static var isNil : Bool { get } static var length : Int { get } } /// The cons HList node. public struct HCons<H, T : HList> : HList { public typealias Head = H public typealias Tail = T public let head : H public let tail : T public init(h : H, t : T) { head = h tail = t } public static var isNil : Bool { return false } public static var length : Int { return Tail.length.advanced(by: 1) } } /// The Nil HList node. public struct HNil : HList { public typealias Head = Never public typealias Tail = Never public init() {} public static var isNil : Bool { return true } public static var length : Int { return 0 } } /// `HAppend` is a type-level append of two `HList`s. They are instantiated /// with the type of the first list (XS), the type of the second list (YS) and /// the type of the result (XYS). When constructed, `HAppend` provides a safe /// append operation that yields the appropriate HList for the given types. public struct HAppend<XS, YS, XYS> { public let append : (XS, YS) -> XYS private init(_ append : @escaping (XS, YS) -> XYS) { self.append = append } /// Creates an HAppend that appends Nil to a List. public static func makeAppend<L : HList>() -> HAppend<HNil, L, L> { return HAppend<HNil, L, L> { (_, l) in return l } } /// Creates an HAppend that appends two non-HNil HLists. public static func makeAppend<T, A : HList, B : HList, C : HList>(h : HAppend<A, B, C>) -> HAppend<HCons<T, A>, B, HCons<T, C>> { return HAppend<HCons<T, A>, B, HCons<T, C>> { (c, l) in return HCons(h: c.head, t: h.append(c.tail, l)) } } } /// `HMap` is a type-level map of a function (F) over an `HList`. An `HMap` /// must, at the very least, takes values of its input type (A) to values of its /// output type (R). The function parameter (F) does not necessarily have to be /// a function, and can be used as an index for extra information that the map /// function may need in its computation. public struct HMap<F, A, R> { public let map : (F, A) -> R public init(_ map : @escaping (F, A) -> R) { self.map = map } /// Returns an `HMap` that leaves all elements in the HList unchanged. public static func identity<T>() -> HMap<(), T, T> { return HMap<(), T, T> { (_, x) in return x } } /// Returns an `HMap` that applies a function to the elements of an HList. public static func apply<T, U>() -> HMap<(T) -> U, T, U> { return HMap<(T) -> U, T, U> { (f, x) in return f(x) } } /// Returns an `HMap` that composes two functions, then applies the new /// function to elements of an `HList`. public static func compose<X, Y, Z>() -> HMap<(), ((X) -> Y, (Y) -> Z), (X) -> Z> { return HMap<(), ((X) -> Y, (Y) -> Z), (X) -> Z> { (_, fs) in return fs.1 • fs.0 } } /// Returns an `HMap` that creates an `HCons` node out of a tuple of the /// head and tail of an `HList`. public static func hcons<H, T : HList>() -> HMap<(), (H, T), HCons<H, T>> { return HMap<(), (H, T), HCons<H, T>> { (_, p) in return HCons(h: p.0, t: p.1) } } /// Returns an `HMap` that uses an `HAppend` operation to append two /// `HList`s together. public static func happend<A, B, C>() -> HMap<HAppend<A, B, C>, (A, B), C> { return HMap<HAppend<A, B, C>, (A, B), C> { (f, p) in return f.append(p.0, p.1) } } } /// `HFold` is a type-level right fold over the values in an `HList`. Like an /// `HMap`, an HFold carries a context (of type G). The actual fold takes /// values of type V and an accumulator A to values of type R. /// /// Using an `HFold` necessitates defining the type of its starting and ending /// data. For example, a fold that reduces /// `HCons<(Int) -> Int, HCons<(Int) -> Int, HCons<(Int) -> Int, HNil>>>` to /// `(Int) -> Int` through composition will define two `typealias`es: /// /// public typealias FList = HCons<(Int) -> Int, HCons<(Int) -> Int, HCons<(Int) -> Int, HNil>>> /// /// public typealias FBegin = HFold<(), (Int) -> Int, FList, (Int) -> Int> /// public typealias FEnd = HFold<(), (Int) -> Int, HNil, (Int) -> Int> /// /// The fold above doesn't depend on a context, and carries values of type /// `(Int) -> Int`, contained in a list of type `FList`, to an `HNil` node and /// an ending value of type `(Int) -> Int`. public struct HFold<G, V, A, R> { public let fold : (G, V, A) -> R private init(fold : @escaping (G, V, A) -> R) { self.fold = fold } /// Creates an `HFold` object that folds a function over an `HNil` node. /// /// This operation returns the starting value of the fold. public static func makeFold<G, V>() -> HFold<G, V, HNil, V> { return HFold<G, V, HNil, V> { (f, v, n) in return v } } /// Creates an `HFold` object that folds a function over an `HCons` node. public static func makeFold<H, G, V, T : HList, R, RR>(_ p : HMap<G, (H, R), RR>, _ h : HFold<G, V, T, R>) -> HFold<G, V, HCons<H, T>, RR> { return HFold<G, V, HCons<H, T>, RR> { (f, v, c) in return p.map(f, (c.head, h.fold(f, v, c.tail))) } } } /// Uncomment if Swift decides to allow tuple patterns. rdar://20989362 ///// HCons<HCons<...>> Matcher (Induction Step): If we've hit this overloading, we should have a cons ///// node, or at least something that matches HCons<HNil> //public func ~=<H : HList where H.Head : Equatable, H.Tail : HList, H.Tail.Head : Equatable, H.Tail.Tail : HList>(pattern : (H.Head, H.Tail), predicate : H) -> Bool { // if H.isNil { // return false // } // // if let p = (predicate as? HCons<H.Head, H.Tail>), let ps = (p.tail as? HCons<H.Tail.Head, H.Tail.Tail>), let pt = (pattern.1 as? HCons<H.Tail.Head, H.Tail.Tail>) { // return (p.head == predicate.0) && ((ps.head, ps.tail) ~= pt) // } else if let p = (predicate as? HCons<H.Head, H.Tail>), let ps = (p.tail as? HNil) { // return (p.head == pattern.0) // } // return error("Pattern match on HList expected HCons<HSCons<...>> or HCons<HNil> but got neither.") //} // ///// HCons<HNil> or HNil Matcher //public func ~=<H : HList where H.Head : Equatable, H.Tail : HList>(pattern : (H.Head, H.Tail), predicate : H) -> Bool { // if H.isNil { // return false // } // if let p = (predicate as? HCons<H.Head, H.Tail>) { // return (p.head == pattern.0) // } else if let p = (predicate as? HNil) { // return false // } // return error("Pattern match on HList expected HCons<HNil> or HNil but got neither.") //} // ///// HNil matcher. //public func ~=<H : HList>(pattern : (), predicate : H) -> Bool { // return H.isNil //}
bsd-3-clause
2ef22b66766d9d70bada9a0b8f98bc79
32.718894
167
0.622933
2.857087
false
false
false
false
AlohaYos/SiriRemoteTutorDemo
SiriRemoteTutorDemo/ViewController.swift
1
3029
// // ViewController.swift // SiriRemoteTutor // // Created by Yos Hashimoto on 2015/10/07. // Copyright © 2015 Newton Japan. All rights reserved. // import UIKit import SpriteKit class ViewController: UIViewController { // MARK: Properties var remoteTutor : SiriRemoteTutor? var config : NSDictionary? var demoTimer : NSTimer? var demoIndex = 0 // MARK: View Life Cycle override func viewDidLoad() { super.viewDidLoad() // init scene let demoScene = SKScene(size:view.bounds.size) demoScene.backgroundColor = UIColor.clearColor() let skFrame = CGRectMake(0, 0, view.frame.size.width, view.frame.size.height) let skView = SKView(frame: skFrame) skView.presentScene(demoScene, transition: SKTransition.crossFadeWithDuration(0.5)) view.addSubview(skView) // load config let path = NSBundle.mainBundle().pathForResource("configDemo", ofType: "json")! let data = NSData(contentsOfFile: path)! do { let json = try NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.AllowFragments) as! NSDictionary config = NSDictionary.init(dictionary: json) } catch { // json read error ! } // Create Siri Remote Node let remoteDic = config?["siri_remote_tutor"] as! NSDictionary #if true // center of the screen let x = CGRectGetMidX(view.frame) let y = CGRectGetMidY(view.frame) #else // anywhere you want let x = remoteDic["x"] as! CGFloat let y = remoteDic["y"] as! CGFloat #endif let w = remoteDic["width"] as! CGFloat let h = remoteDic["height"] as! CGFloat remoteTutor = SiriRemoteTutor.init(rect: CGRectMake(x, y, w, h), scene: demoScene) startDemo() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: Demo func startDemo() { demoIndex = 0 let demoSpeed = config?["demo_speed"] as! NSTimeInterval demoTimer = NSTimer.scheduledTimerWithTimeInterval(demoSpeed, target: self, selector: Selector("demoJob"), userInfo: nil, repeats: true) } func stopDemo() { remoteTutor?.hide() demoTimer?.invalidate() demoTimer=nil } func demoJob() { let actions = config?["demo_action"] as! NSArray let currentAction = actions[demoIndex] as! NSDictionary let action = currentAction["action"] as! NSString if(action == "nothing") { demoIndex++ return } if(action == "siri_remote") { let siri_action = currentAction["command"] as! NSString if(siri_action == "show") { remoteTutor?.show() } if(siri_action == "hide") { remoteTutor?.hide() } if(siri_action == "swipe_right") { remoteTutor?.swipeRight() } if(siri_action == "swipe_left") { remoteTutor?.swipeLeft() } if(siri_action == "swipe_up") { remoteTutor?.swipeUp() } if(siri_action == "swipe_down") { remoteTutor?.swipeDown() } if(siri_action == "click") { remoteTutor?.click() } } if(action == "repeat") { demoIndex = 0-1; } demoIndex++ } }
mit
f57d2e69ac5f7e427ab2466f26089efa
23.224
138
0.674042
3.356984
false
true
false
false
codescv/DQuery
TodoDemoSwift/TodoListViewController.swift
1
7441
// // Copyright 2016 DQuery // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // TodoListViewController.swift // // Created by chi on 16/1/10. // import UIKit class TodoListViewController: UIViewController { var innerTableViewController: TodoListTableViewController? @IBAction func newTodoItem(sender: AnyObject) { innerTableViewController?.startComposingNewTodoItem() } } class TodoListTableViewController: UITableViewController { enum Section: Int { case Todo = 0 case Done func name() -> String { switch self { case .Todo: return "TODO" case .Done: return "DONE" } } static var count = 2 } enum Cell: String { case NewItemCell = "NewTodoItemIdentifier" case TodoItemCell = "TodoItemCellIdentifier" case DoneItemCell = "DoneItemCellIdentifier" var identifier: String { return self.rawValue } } var isComposingNewTodoItem: Bool = false let dataController = TodoListDataController() override func didMoveToParentViewController(parent: UIViewController?) { if let todoListVC = parent as? TodoListViewController { todoListVC.innerTableViewController = self } } override func viewDidLoad() { tableView.estimatedRowHeight = 40 tableView.separatorStyle = .None dataController.reloadDataFromDB({ self.tableView.reloadData() }) } // MARK: table view override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return UITableViewAutomaticDimension } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let (row, section) = (indexPath.row, indexPath.section) switch Section(rawValue: section)! { case .Todo: var itemRow = row if self.isComposingNewTodoItem { if row == 0 { // the composing cell let cell = tableView.dequeueReusableCellWithIdentifier(Cell.NewItemCell.identifier) as! NewTodoItemCell cell.textView.text = "" cell.actionTriggered = { [weak self] (cell, action) in let inserted = action == .OK self?.endComposingNewTodoItem(insertedNewItem: inserted) } return cell } else { itemRow -= 1 } } // a todo item cell let cell = tableView.dequeueReusableCellWithIdentifier(Cell.TodoItemCell.identifier) as! TodoItemCell let viewModel = self.dataController.todoItemAtRow(itemRow) cell.configureWithViewModel(viewModel) cell.actionTriggered = { [weak self] (cell, action) in if action == .MarkAsDone { self?.markItemAsDoneForCell(cell) } } return cell case .Done: // done item cell let cell = tableView.dequeueReusableCellWithIdentifier(Cell.DoneItemCell.identifier) as! DoneItemCell let viewModel = self.dataController.doneItemAtRow(indexPath.row) cell.configureWithViewModel(viewModel) cell.actionTriggered = { [weak self] (cell, action) in if action == .Delete { self?.deleteDoneItemForCell(cell) } } return cell } } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return Section.count } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return Section(rawValue: section)!.name() } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch Section(rawValue: section)! { case .Todo: let count = self.dataController.todoItemsCount if self.isComposingNewTodoItem { return count + 1 } return count case .Done: return self.dataController.doneItemsCount } } // MARK: cell actions func deleteDoneItemForCell(cell: DoneItemCell) { if let indexPath = self.tableView.indexPathForCell(cell) { self.dataController.deleteDoneItemAtRow(indexPath.row) { self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic) } } } func markItemAsDoneForCell(cell: TodoItemCell) { if let indexPath = self.tableView.indexPathForCell(cell) { self.dataController.markTodoItemAsDoneAtRow(indexPath.row) { self.tableView.beginUpdates() self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic) self.tableView.insertRowsAtIndexPaths([NSIndexPath(forRow: 0, inSection: Section.Done.rawValue)], withRowAnimation: .Automatic) self.tableView.endUpdates() } } } // MARK: composing func startComposingNewTodoItem() { if self.isComposingNewTodoItem { return } self.isComposingNewTodoItem = true self.tableView.beginUpdates() self.tableView.insertRowsAtIndexPaths([NSIndexPath(forRow: 0, inSection: 0)], withRowAnimation: .Left) self.tableView.endUpdates() } func endComposingNewTodoItem(insertedNewItem insertedNewItem: Bool) { if !self.isComposingNewTodoItem { return } if let newTodoItemCell = self.tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 0)) as? NewTodoItemCell { newTodoItemCell.textView.resignFirstResponder() if insertedNewItem { let title = newTodoItemCell.textView.text self.dataController.insertTodoItem(title: title) { self.isComposingNewTodoItem = false self.tableView.beginUpdates() self.tableView.deleteRowsAtIndexPaths([NSIndexPath(forRow: 0, inSection: 0)], withRowAnimation: .Automatic) if insertedNewItem { self.tableView.insertRowsAtIndexPaths([NSIndexPath(forRow: 0, inSection: 0)], withRowAnimation: .Automatic) } self.tableView.endUpdates() } } else { self.isComposingNewTodoItem = false self.tableView.deleteRowsAtIndexPaths([NSIndexPath(forRow: 0, inSection: 0)], withRowAnimation: .Left) } } } }
apache-2.0
8f4029b84f9ab649b26b4b210a80ed15
36.21
143
0.607311
5.403776
false
false
false
false
Awalz/ark-ios-monitor
ArkMonitor/Settings/Server Selection/SettingsCustomServerViewController.swift
1
6349
// Copyright (c) 2016 Ark // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // import UIKit class SettingsCustomServerViewController: ArkViewController { fileprivate var tableview : ArkTableView! fileprivate var serverName : String? fileprivate var ipAddress : String? fileprivate var port : Int? fileprivate var isSSL = false override func viewDidLoad() { super.viewDidLoad() navigationItem.title = "Custom" tableview = ArkTableView(CGRect.zero) tableview.delegate = self tableview.dataSource = self view.addSubview(tableview) tableview.snp.makeConstraints { (make) in make.left.right.top.bottom.equalToSuperview() } } } // MARK: UITableViewDelegate extension SettingsCustomServerViewController: UITableViewDelegate { func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { view.endEditing(true) } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return CGFloat.leastNormalMagnitude } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { return nil } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return CGFloat.leastNormalMagnitude } func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { return nil } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { switch indexPath.row { case 0, 1, 2, 3: return 50 default: return 100.0 } } } // MARK: UITableViewDataSource extension SettingsCustomServerViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 5 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch indexPath.row { case 0: let cell = SettingsServerNameTableViewCell(reuseIdentifier: "cell") cell.delegate = self return cell case 1: let cell = SettingsIPTableViewCell(reuseIdentifier: "cell") cell.delegate = self return cell case 2: let cell = SettingsPortTableViewCell(reuseIdentifier: "cell") cell.delegate = self return cell case 3: let cell = SettingsSSLTableViewCell(reuseIdentifier: "cell") cell.delegate = self return cell default: let cell = SettingsSaveTableViewCell(reuseIdentifier: "cell") cell.delegate = self return cell } } } // MARK: SettingsServerNameTableViewCellDelegate extension SettingsCustomServerViewController : SettingsServerNameTableViewCellDelegate { func ipCell(_ cell: SettingsServerNameTableViewCell, didChangeText text: String?) { self.serverName = text } } // MARK: SettingsIPTableViewCellDelegate extension SettingsCustomServerViewController : SettingsIPTableViewCellDelegate { func ipCell(_ cell: SettingsIPTableViewCell, didChangeText text: String?) { self.ipAddress = text } } // MARK: SettingsPortTableViewCellDelegate extension SettingsCustomServerViewController : SettingsPortTableViewCellDelegate { func portCell(_ cell: SettingsPortTableViewCell, didChangeText text: String?) { if let portString = text { self.port = Int(portString) } } } // MARK: SettingsSSLTableViewCellDelegate extension SettingsCustomServerViewController : SettingsSSLTableViewCellDelegate { func sslCell(_ cell: SettingsSSLTableViewCell, didChangeStatus enabled: Bool) { self.isSSL = enabled } } // MARK: SettingsSaveTableViewCellDelegate extension SettingsCustomServerViewController : SettingsSaveTableViewCellDelegate { func saveCellButtonWasTapped(_ cell: SettingsSaveTableViewCell) { guard let currentServerName = serverName else { ArkActivityView.showMessage("Server name cannot be blank", style: .warning) return } guard let ip = ipAddress else { ArkActivityView.showMessage("IP Address cannot be blank", style: .warning) return } guard let currentPort = port else { ArkActivityView.showMessage("Port cannot be blank", style: .warning) return } let newCustomServer = CustomServer(currentServerName, ipAddress: ip, port: currentPort, isSSL: isSSL) ArkNetworkManager.add(newCustomServer) { (success) in if success == true { ArkActivityView.showMessage("Successfully added server", style: .success) self.navigationController?.popViewController(animated: true) } else { ArkActivityView.showMessage("Server already exists with that name", style: .warning) return } } } }
mit
ddb96d14d28bdf99e890549295c24ab7
35.073864
137
0.669712
5.431138
false
false
false
false
genedelisa/Swift3MIDI
Swift3MIDI/MIDIClassPlayground.playground/Contents.swift
1
9761
//: MIDIPlayground - sloppy hack just to see if MIDI works in a playground import UIKit import CoreMIDI import AudioToolbox // deprecated //import XCPlayground import PlaygroundSupport PlaygroundSupport.PlaygroundPage.current.needsIndefiniteExecution = true // NB these are deprecated now //XCPlaygroundPage.currentPage.needsIndefiniteExecution = true //XCPSetExecutionShouldContinueIndefinitely(continueIndefinitely: true) class MIDIFrob : NSObject { var midiClient = MIDIClientRef() var outputPort = MIDIPortRef() var inputPort = MIDIPortRef() var sequence:MusicSequence? var musicPlayer:MusicPlayer? override init() { super.init() let notifyBlock = MyMIDINotifyBlock var status = MIDIClientCreateWithBlock("com.rockhoppertech.MyMIDIClient" as CFString, &midiClient, notifyBlock) if status == noErr { print("created client \(midiClient)") } else { print("error creating client : \(status)") } let readBlock:MIDIReadBlock = MyMIDIReadBlock if status == noErr { // doesn't like this status = MIDIInputPortCreateWithBlock(midiClient, "com.rockhoppertech.MIDIInputPort" as CFString, &inputPort, MyMIDIReadBlock) // if status == noErr { // print("created input port \(inputPort)") // } else { // print("error creating input port : \(status)") // } status = MIDIOutputPortCreate(midiClient, "com.rockhoppertech.OutputPort" as CFString, &outputPort) if status == noErr { print("created output port \(outputPort)") } else { print("error creating output port : \(status)") } } sequence = createMusicSequence()! musicPlayer = createMusicPlayer(musicSequence: sequence!) } func MyMIDINotifyBlock(midiNotification: UnsafePointer<MIDINotification>) { print("\ngot a MIDINotification!") } // cannot set up input port in a playground it seems @objc func MyMIDIReadBlock(packetList: UnsafePointer<MIDIPacketList>, srcConnRefCon: UnsafeMutableRawPointer?) -> Swift.Void { let packets = packetList.pointee let packet:MIDIPacket = packets.packet // etc. } // doesn't enable it. this code works in an app func enableNetwork() { MIDINetworkSession.default().isEnabled = true MIDINetworkSession.default().connectionPolicy = .anyone print("net session enabled \(MIDINetworkSession.default().isEnabled)") print("net session networkPort \(MIDINetworkSession.default().networkPort)") print("net session networkName \(MIDINetworkSession.default().networkName)") print("net session localName \(MIDINetworkSession.default().localName)") } internal func createMusicSequence() -> MusicSequence? { var musicSequence:MusicSequence? var status = NewMusicSequence(&musicSequence) if status != noErr { print("\(#line) bad status \(status) creating sequence") } if let sequence = musicSequence { // add a track var newtrack: MusicTrack? status = MusicSequenceNewTrack(sequence, &newtrack) if status != noErr { print("error creating track \(status)") } if let track = newtrack { // bank select msb var chanmess = MIDIChannelMessage(status: 0xB0, data1: 0, data2: 0, reserved: 0) status = MusicTrackNewMIDIChannelEvent(track, 0, &chanmess) if status != noErr { print("creating bank select event \(status)") } // bank select lsb chanmess = MIDIChannelMessage(status: 0xB0, data1: 32, data2: 0, reserved: 0) status = MusicTrackNewMIDIChannelEvent(track, 0, &chanmess) if status != noErr { print("creating bank select event \(status)") } // program change. first data byte is the patch, the second data byte is unused for program change messages. chanmess = MIDIChannelMessage(status: 0xC0, data1: 0, data2: 0, reserved: 0) status = MusicTrackNewMIDIChannelEvent(track, 0, &chanmess) if status != noErr { print("creating program change event \(status)") } // now make some notes and put them on the track var beat = MusicTimeStamp(0.0) let duration = Float32(1.0) for i:UInt8 in 60...72 { var mess = MIDINoteMessage(channel: 0, note: i, velocity: 64, releaseVelocity: 0, duration: duration ) status = MusicTrackNewMIDINoteEvent(track, beat, &mess) if status != noErr { print("creating new midi note event \(status)") } beat += 1 } // associate the AUGraph with the sequence. In this case, I'm using a virtual destination // which will forward the messages so this is commented out here. // status = MusicSequenceSetAUGraph(sequence, self.processingGraph) // checkError(status) // send it to our virtual destination (which will forward it // status = MusicSequenceSetMIDIEndpoint(sequence, self.virtualDestinationEndpointRef) let sequencerCallback: MusicSequenceUserCallback = { (clientData:UnsafeMutableRawPointer?, sequence:MusicSequence, track:MusicTrack, eventTime:MusicTimeStamp, eventData:UnsafePointer<MusicEventUserData>, startSliceBeat:MusicTimeStamp, endSliceBeat:MusicTimeStamp) -> Void in let userData = eventData.pointee if userData.data == 0xAA { print("got user event AA of length \(userData.length)") } } status = MusicSequenceSetUserCallback(sequence, sequencerCallback, nil) var event = MusicEventUserData(length: 1, data: (0xAA)) // add the user event let status = MusicTrackNewUserEvent(track, beat + MusicTimeStamp(duration), &event) if status != noErr { } // Let's see it CAShow(UnsafeMutablePointer<MusicSequence>(sequence)) let info = MusicSequenceGetInfoDictionary(sequence) print("sequence info \(info)") //info[kAFInfoDictionary_Copyright] = "2016 bozosoft" return sequence } } return nil } internal func createMusicPlayer(musicSequence:MusicSequence) -> MusicPlayer? { var musicPlayer: MusicPlayer? var status = noErr status = NewMusicPlayer(&musicPlayer) if status != noErr { print("bad status \(status) creating player") } if let player = musicPlayer { status = MusicPlayerSetSequence(player, musicSequence) if status != noErr { print("setting sequence \(status)") } status = MusicPlayerPreroll(player) if status != noErr { print("prerolling player \(status)") } return player } else { print("musicplayer is nil") return nil } } internal func playMusicPlayer() { var status = noErr var playing = DarwinBoolean(false) if let player = musicPlayer { status = MusicPlayerIsPlaying(player, &playing) if playing != false { print("music player is playing. stopping") status = MusicPlayerStop(player) if status != noErr { print("Error stopping \(status)") return } } else { print("music player is not playing.") } status = MusicPlayerSetTime(player, 0) if status != noErr { print("Error setting time \(status)") return } print("starting to play") status = MusicPlayerStart(player) if status != noErr { print("Error starting \(status)") return } } } } var frob = MIDIFrob() frob.playMusicPlayer()
mit
85da582f4c655a595e0280f91f2d86e7
34.365942
138
0.509476
5.704851
false
false
false
false
jkolb/midnightbacon
MidnightBacon/Reddit/RedditRequest.swift
1
4238
// // RedditRequest.swift // MidnightBacon // // Copyright (c) 2015 Justin Kolb - http://franticapparatus.net // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation import Common public class RedditRequest { let clientID: String let redirectURI: NSURL let mapperFactory = RedditFactory() let scope: [OAuthScope] = [ .Account, .Edit, .History, .Identity, .MySubreddits, .PrivateMessages, .Read, .Report, .Save, .Submit, .Subscribe, .Vote ] let duration = TokenDuration.Permanent public var tokenPrototype: NSURLRequest! public var oauthPrototype: NSURLRequest! public init(clientID: String, redirectURI: NSURL) { self.clientID = clientID self.redirectURI = redirectURI } public func authorizeURL(state: String) -> NSURL { let request = AuthorizeRequest(clientID: clientID, state: state, redirectURI: redirectURI, duration: duration, scope: scope) return request.buildURL(tokenPrototype.URL!)! } public func userAccessToken(authorizeResponse: OAuthAuthorizeResponse) -> APIRequestOf<OAuthAccessToken> { return APIRequestOf(OAuthAuthorizationCodeRequest(mapperFactory: mapperFactory, prototype: tokenPrototype, clientID: clientID, authorizeResponse: authorizeResponse, redirectURI: redirectURI)) } public func refreshAccessToken(accessToken: OAuthAccessToken) -> APIRequestOf<OAuthAccessToken> { return APIRequestOf(OAuthRefreshTokenRequest(mapperFactory: mapperFactory, prototype: tokenPrototype, clientID: clientID, accessToken: accessToken)) } public func applicationAccessToken(deviceID: NSUUID) -> APIRequestOf<OAuthAccessToken> { return APIRequestOf(OAuthInstalledClientRequest(mapperFactory: mapperFactory, prototype: tokenPrototype, clientID: clientID, deviceID: deviceID)) } public func userAccount() -> APIRequestOf<Account> { return APIRequestOf(MeRequest(mapperFactory: mapperFactory, prototype: oauthPrototype)) } public func subredditLinks(path: String, after: String? = nil) -> APIRequestOf<Listing> { return APIRequestOf(SubredditRequest(mapperFactory: mapperFactory, prototype: oauthPrototype, path: path, after: after)) } public func linkComments(link: Link) -> APIRequestOf<(Listing, [Thing])> { return APIRequestOf(CommentsRequest(mapperFactory: mapperFactory, prototype: oauthPrototype, article: link)) } public func submit(kind kind: SubmitKind, subreddit: String, title: String, url: NSURL?, text: String?, sendReplies: Bool) -> APIRequestOf<Bool> { return APIRequestOf(SubmitRequest(prototype: oauthPrototype, kind: kind, subreddit: subreddit, title: title, url: url, text: text, sendReplies: sendReplies)) } public func privateMessagesWhere(messageWhere: MessageWhere) -> APIRequestOf<Listing> { return APIRequestOf(MessageRequest(mapperFactory: mapperFactory, prototype: oauthPrototype, messageWhere: messageWhere, mark: nil, mid: nil, after: nil, before: nil, count: nil, limit: nil, show: nil, expandSubreddits: nil)) } }
mit
fab1d3a89f837123ed5c64d8b3c45bff
45.065217
232
0.726286
4.714127
false
false
false
false
zhou9734/ZCJImagePicker
ZCJImagePicker/RootViewController.swift
1
4227
// // ViewController.swift // ZCJImagePicker // // Created by zhoucj on 16/8/28. // Copyright © 2016年 zhoucj. All rights reserved. // import UIKit let SelectedPhotoIdentifier = "SelectedPhotoIdentifier" let SelectedPhotoDone = "SelectedPhotoDone" class RootViewController: UIViewController { var alassetModels = [ALAssentModel]() override func viewDidLoad() { super.viewDidLoad() view.addSubview(collectionView) view.backgroundColor = UIColor.whiteColor() // navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightBtn) navigationItem.title = "图片选择器" collectionView.translatesAutoresizingMaskIntoConstraints = false var cons = NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[collectionView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["collectionView": collectionView]) cons += NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[collectionView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["collectionView": collectionView]) view.addConstraints(cons) NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("selectedPhotoDown:"), name: SelectedPhotoDone, object: nil) alassetModels.append(ALAssentModel(alsseet: nil)) } private lazy var collectionView: UICollectionView = { let flowLayout = UICollectionViewFlowLayout() let width = (UIScreen.mainScreen().bounds.size.width - 4) / 3 flowLayout.itemSize = CGSize(width: width, height: width) flowLayout.minimumLineSpacing = 2 flowLayout.minimumInteritemSpacing = 2 let clv = UICollectionView(frame: CGRectZero, collectionViewLayout: flowLayout) clv.registerClass(SelectedPhotoCell.self, forCellWithReuseIdentifier: SelectedPhotoIdentifier) clv.backgroundColor = UIColor(red: 234.0/255.0, green: 234.0/255.0, blue: 241.0/255.0, alpha: 1) clv.dataSource = self clv.delegate = self clv.alwaysBounceVertical = true return clv }() @objc private func selectPhotoClick(){ navigationController?.pushViewController(PhotoViewController(selectedAlassennt: alassetModels), animated: true) } @objc private func selectedPhotoDown(notice: NSNotification){ guard let models = notice.userInfo!["alassentModels"] as? [ALAssentModel] else{ return } alassetModels = models let aModel = ALAssentModel(alsseet: nil) alassetModels.append(aModel) collectionView.reloadData() } deinit{ NSNotificationCenter.defaultCenter().removeObserver(self) } } extension RootViewController: UICollectionViewDataSource{ func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return alassetModels.count ?? 0 } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(SelectedPhotoIdentifier, forIndexPath: indexPath) as! SelectedPhotoCell if let assent = alassetModels[indexPath.item].alsseet{ cell.alsseet = assent cell.isLast = false }else{ cell.isLast = true } if let image = alassetModels[indexPath.item].takePhtoto{ cell.image = image } cell.delegate = self return cell } } extension RootViewController: UICollectionViewDelegate{ func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { let cell = collectionView.cellForItemAtIndexPath(indexPath) as! SelectedPhotoCell if cell.isLast{ selectPhotoClick() } } } extension RootViewController: SelectedPhotoCellDelegate{ func deletePhoto(cell: SelectedPhotoCell) { let indexPath = collectionView.indexPathForCell(cell) alassetModels.removeAtIndex(indexPath!.item) collectionView.reloadData() } }
mit
03892a160624612d92cddc7e6239a215
42.010204
197
0.710726
5.120292
false
false
false
false
mukeshthawani/UXMPDFKit
Pod/Classes/Annotations/PDFPathAnnotation.swift
1
3222
// // PDFPathAnnotation.swift // Pods // // Created by Chris Anderson on 6/24/16. // // import UIKit class PDFPathAnnotation { var page: Int? var path: UIBezierPath = UIBezierPath() var color: UIColor = UIColor.black { didSet { color.setStroke() path.stroke() } } var fill: Bool = false var lineWidth: CGFloat = 3.0 { didSet { path.lineWidth = lineWidth } } var rect: CGRect = CGRect(x: 0, y: 0, width: 1000, height: 1000) { didSet { view.frame = rect } } lazy var view: PDFPathView = PDFPathView(parent: self, frame: self.rect) var incrementalImage: UIImage? fileprivate var points: [CGPoint] = [CGPoint.zero, CGPoint.zero, CGPoint.zero, CGPoint.zero, CGPoint.zero] fileprivate var ctr: Int = 0 func drawRect(_ frame: CGRect) { self.incrementalImage?.draw(in: rect) self.color.setStroke() self.path.stroke() } } class PDFPathView: UIView { var parent: PDFPathAnnotation? convenience init(parent: PDFPathAnnotation, frame: CGRect) { self.init() self.frame = frame self.parent = parent backgroundColor = UIColor.clear isOpaque = false } override func draw(_ rect: CGRect) { parent?.drawRect(rect) } } extension PDFPathAnnotation: PDFAnnotation { func mutableView() -> UIView { view = PDFPathView(parent: self, frame: rect) return view } func touchStarted(_ touch: UITouch, point: CGPoint) { ctr = 0 points[0] = point } func touchMoved(_ touch: UITouch, point: CGPoint) { ctr += 1 points[ctr] = point if ctr == 4 { points[3] = CGPoint( x: (points[2].x + points[4].x) / 2.0, y: (points[2].y + points[4].y) / 2.0 ) path.move(to: points[0]) path.addCurve(to: points[3], controlPoint1: points[1], controlPoint2: points[2]) view.setNeedsDisplay() points[0] = points[3] points[1] = points[4] ctr = 1 } } func touchEnded(_ touch: UITouch, point: CGPoint) { drawBitmap() view.setNeedsDisplay() path.removeAllPoints() ctr = 0 } func drawBitmap() { UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, 0.0) if incrementalImage == nil { let path = UIBezierPath(rect: view.bounds) UIColor.clear.setFill() path.fill() } incrementalImage?.draw(at: CGPoint.zero) color.setStroke() path.stroke() incrementalImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() } func drawInContext(_ context: CGContext) { drawBitmap() drawRect(rect) } } class PDFHighlighterAnnotation: PDFPathAnnotation { override init() { super.init() color = UIColor.yellow.withAlphaComponent(0.3) lineWidth = 10.0 } }
mit
cb60fdda7c0553f5340e487ce8b88bc9
23.784615
110
0.545934
4.354054
false
false
false
false
Jamnitzer/Metal_ImageProcessing
Metal_ImageProcessing/Metal_ImageProcessing/TQuad.swift
1
6097
//------------------------------------------------------------------------------ // Derived from Apple's WWDC example "MetalImageProcessing" // Created by Jim Wrenholt on 12/6/14. //------------------------------------------------------------------------------ import UIKit import Metal import QuartzCore import Foundation // Keys for setting or getting indices let kQuadIndexKeyVertex = UInt8(0) let kQuadIndexKeyTexCoord = UInt8(1) let kQuadIndexKeySampler = UInt8(2) let kQuadIndexMax = UInt8(3) //------------------------------------------------------------------------------ let kCntQuadTexCoords:Int = 6 let kSzQuadTexCoords:Int = kCntQuadTexCoords * sizeof(Float) * 2 let kCntQuadVertices:Int = kCntQuadTexCoords let kSzQuadVertices:Int = kCntQuadVertices * sizeof(Float) * 4 //------------------------------------------------------------------------------ let kQuadVertices:[V4f] = [ V4f(-1.0, -1.0, 0.0, 1.0 ), V4f( 1.0, -1.0, 0.0, 1.0 ), V4f(-1.0, 1.0, 0.0, 1.0 ), V4f( 1.0, -1.0, 0.0, 1.0 ), V4f(-1.0, 1.0, 0.0, 1.0 ), V4f( 1.0, 1.0, 0.0, 1.0 ) ] //------------------------------------------------------------------------------ let kQuadTexCoords:[V2f] = [ V2f(0.0, 0.0 ), V2f(1.0, 0.0 ), V2f(0.0, 1.0 ), V2f(1.0, 0.0 ), V2f(0.0, 1.0 ), V2f(1.0, 1.0 ) ] //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ class TQuad { //------------------------------------------------------------------------- // Utility class for creating a quad. //------------------------------------------------------------------------- // Indices var mVertexIndex:Int = 0 var mTexCoordIndex:Int = 1 var mSamplerIndex:Int = 0 // Dimensions var size = CGSizeMake(0, 0) // Get the quad size var bounds = CGRectMake(0, 0, 0, 0) // Get the bounding view rectangle var aspect = Float(1.0) // Get the aspect ratio // textured Quad var m_VertexBuffer:MTLBuffer? = nil var m_TexCoordBuffer:MTLBuffer? = nil // Scale var m_Scale = V2f(1.0, 1.0) //------------------------------------------------------------------------- // Designated initializer //------------------------------------------------------------------------- init(device:MTLDevice) { m_VertexBuffer = device.newBufferWithBytes( UnsafePointer<Void>(kQuadVertices), length: kSzQuadVertices, options: MTLResourceOptions.OptionCPUCacheModeDefault) if (m_VertexBuffer == nil) { print(">> ERROR: Failed creating a vertex buffer for a quad!") return } m_VertexBuffer!.label = "quad vertices" m_TexCoordBuffer = device.newBufferWithBytes( UnsafePointer<Void>(kQuadTexCoords), length: kSzQuadTexCoords, options: MTLResourceOptions.OptionCPUCacheModeDefault) if (m_TexCoordBuffer == nil) { print(">> ERROR: Failed creating a 2d texture coordinate buffer!") return } m_TexCoordBuffer!.label = "quad texcoords" } //------------------------------------------------------------------------- func setBounds(bounds:CGRect) { self.bounds = bounds self.aspect = Float(abs(bounds.size.width / bounds.size.height)) let Aspect:Float = 1.0 / self.aspect let scale = V2f( Aspect * Float(self.size.width / bounds.size.width), Float(self.size.height / bounds.size.height )) //-------------------------------------------------- // Did the scaling factor change //-------------------------------------------------- let bNewScale:Bool = (scale.x != m_Scale.x) || (scale.y != m_Scale.y) //-------------------------------------------------- // Set the (x, y) bounds of the quad //-------------------------------------------------- if (bNewScale) { //-------------------------------------------------- // Update the scaling factor //-------------------------------------------------- m_Scale = scale //-------------------------------------------------- // Update the vertex buffer with the quad bounds //-------------------------------------------------- let pVertices = UnsafeMutablePointer<V4f>(m_VertexBuffer!.contents()) if (pVertices != nil) { // First triangle pVertices[0].x = -m_Scale.x pVertices[0].y = -m_Scale.y pVertices[1].x = +m_Scale.x pVertices[1].y = -m_Scale.y pVertices[2].x = -m_Scale.x pVertices[2].y = +m_Scale.y // Second triangle pVertices[3].x = +m_Scale.x pVertices[3].y = -m_Scale.y pVertices[4].x = -m_Scale.x pVertices[4].y = +m_Scale.y pVertices[5].x = +m_Scale.x pVertices[5].y = +m_Scale.y } } } //------------------------------------------------------------------------- func encode(renderEncoder:MTLRenderCommandEncoder) { if (m_VertexBuffer == nil) { print("m_VertexBuffer == nil") } if (m_TexCoordBuffer == nil) { print("m_TexCoordBuffer == nil") } renderEncoder.setVertexBuffer( m_VertexBuffer!, offset: Int(0), atIndex: Int(mVertexIndex) ) renderEncoder.setVertexBuffer( m_TexCoordBuffer!, offset: Int(0), atIndex: Int(mTexCoordIndex) ) } // encode //------------------------------------------------------------------------- } ////------------------------------------------------------------------------------
bsd-2-clause
1cda0328b52c551f792dafce0797fcb4
34.04023
82
0.393308
4.789474
false
false
false
false
thetotaljim/thetotaljim.github.io
Stopwatch/Stopwatch/WatchView.swift
1
7531
// // WatchView.swift // Stopwatch // // Created by James Steimel on 11/13/16. // Copyright © 2016 David Vaughn. All rights reserved. // import UIKit class WatchView: UIView { private(set) var watchLayer: WatchLayer? /* // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing codeet layer let image = UIImageView(image: UIImage(named: "stopwatch-light")) image.contentMode = UIViewContentMode.scaleAspectFit self.addSubview(image) } */ /* override func draw(_ rect: CGRect) { // Drawing code // obtain context let ctx = UIGraphicsGetCurrentContext() // radius let rad = rect.width/2.01 //let rad = rect.width/3.5 //let endAngle = CGFloat(2*M_PI) // add circle to the context //CGContextAddArc(ctx, rect.midX, rect.midY, rad, 0, endAngle, 1) //let center = CGPoint(x: rect.midX, y: rect.midY) // possible change 60 -> 360 for i in 1...240 { // save the original position and origin ctx?.saveGState() // make translation ctx?.translateBy(x: rect.midX, y: rect.midY) // make rotation // possible chang CGFloat(i)*6 -> CGFloat(i) ctx?.rotate(by: degree2radian(a: CGFloat(i)*1.5))//*6)) if i % 20 == 0 { drawSecondMarker(ctx: ctx!, x: rad-20, y: 0, radius: rad, color: UIColor.black) } else if i % 4 == 0 { drawSecondMarker(ctx: ctx!, x: rad-15, y: 0, radius: rad, color: UIColor.gray) } else { drawSecondMarker(ctx: ctx!, x: rad-10, y: 0, radius: rad, color: UIColor.gray) } ctx?.restoreGState() } drawText(rect:rect, ctx: ctx!, x: rect.midX, y: rect.midY, radius: rad, sides: 12, color: UIColor.black) }*/*/ override func draw(_ rect: CGRect) { watchLayer?.frame = rect layer.addSublayer(watchLayer!) watchLayer?.setNeedsDisplay() } /* func degree2radian(a: CGFloat) -> CGFloat { let b = CGFloat(M_PI)*(a/180) return b } func drawSecondMarker(ctx: CGContext, x: CGFloat, y: CGFloat, radius: CGFloat, color:UIColor){ // generate a path let path = CGMutablePath() // move to starting point on edge of circle path.move(to: CGPoint(x: radius, y: 0.0 )) // the above is different from original code due to changes // in Swift 3 : missing the nil part path.addLine(to: CGPoint(x: x, y: y) ) path.closeSubpath() ctx.addPath(path) ctx.setLineWidth(1.5) ctx.setStrokeColor(color.cgColor) ctx.strokePath() } func circleCircumferencePoints(sides:Int,x:CGFloat,y:CGFloat,radius:CGFloat,adjustment:CGFloat=0)->[CGPoint] { let angle = degree2radian(a: 360/CGFloat(sides)) let cx = x // x origin let cy = y // y origin let r = radius // radius of circle var i = sides var points = [CGPoint]() while points.count <= sides { let xpo = cx - r * cos(angle * CGFloat(i)+degree2radian(a: adjustment)) let ypo = cy - r * sin(angle * CGFloat(i)+degree2radian(a: adjustment)) points.append(CGPoint(x: xpo, y: ypo)) i -= 1; } return points } // To then draw the second markers a further function is necessary: func secondMarkers(ctx:CGContext, x:CGFloat, y:CGFloat, radius:CGFloat, sides:Int, color:UIColor) { // retrieve points let points = circleCircumferencePoints(sides: sides,x: x,y: y,radius: radius) // create path let path = CGMutablePath() // determine length of marker as a fraction of the total radius var divider:CGFloat = 1/16 for p in points.enumerated(){ if p.offset % 5 == 0 { divider = 1/8 print("Working out of 1/8") } else { divider = 1/16 print("Working out of 1/8") } let xn = p.element.x + divider*(x-p.element.x) let yn = p.element.y + divider*(y-p.element.y) // build path path.move(to: CGPoint(x: p.element.x, y: p.element.y)) //CGPathMoveToPoint(path, nil, p.element.x, p.element.y) path.addLine(to: CGPoint(x: xn, y: yn)) //CGPathAddLineToPoint(path, nil, xn, yn) //CGPathCloseSubpath(path) path.closeSubpath() // add path to context //CGContextAddPath(ctx, path) ctx.addPath(path) } // set path color let cgcolor = color.cgColor ctx.setStrokeColor(cgcolor) ctx.setLineWidth(1.5) ctx.strokePath() } override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } func setup () { } /* HERE IS CODE FOR NUMBERS ON FACE */ func drawText(rect:CGRect, ctx:CGContext, x:CGFloat, y:CGFloat, radius:CGFloat, sides:Int, color:UIColor) { // Flip text co-ordinate space ctx.translateBy(x: 0.0, y: rect.height) ctx.scaleBy(x: 1.0, y: -1.0) // dictates on how inset the ring of numbers will be let inset:CGFloat = radius/3.5 // An adjustment of 270 degrees to position numbers correctly let points = circleCircumferencePoints(sides: sides,x: x,y: y,radius: radius-inset,adjustment:270) let path = CGMutablePath() for p in points.enumerated() { if p.offset > 0 { let aFont = UIFont(name: "HelveticaNeue-Light", size: radius/8) // create a dictionary of attributes to be applied to the string let attr : CFDictionary = [NSFontAttributeName: aFont!, NSForegroundColorAttributeName:UIColor.black] as CFDictionary // create the attributed string let val = p.offset*5 let text = CFAttributedStringCreate(nil, val.description as CFString!, attr) // create the line of text let line = CTLineCreateWithAttributedString(text!) // retrieve the bounds of the text let bounds = CTLineGetBoundsWithOptions(line, CTLineBoundsOptions.useOpticalBounds) // set the line width to stroke the text with ctx.setLineWidth(1.5) // set the drawing mode to stroke ctx.setTextDrawingMode(CGTextDrawingMode.fillStroke) // Set text position and draw the line into the graphics context, text length and height is adjusted for let xn = p.element.x - bounds.width/2 let yn = p.element.y - bounds.midY //CGContextSetTextPosition(ctx, xn, yn) ctx.textPosition = CGPoint(x: xn, y: yn) // draw the line of text CTLineDraw(line, ctx) } } } */ }
mit
8052cce2e8d0d410c434c8998c245b3c
34.352113
134
0.549535
4.251835
false
false
false
false
lexicalparadox/Chirppy
Chirppy/TimelineViewController.swift
1
4556
// // TimelineViewController.swift // Chirppy // // Created by Alexander Doan on 9/26/17. // Copyright © 2017 Alexander Doan. All rights reserved. // import UIKit class TimelineViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var signoutButton: UIBarButtonItem! var tweets: [Tweet]? var animated: Set<Int>? let client = TwitterClient.sharedInstance override func viewDidLoad() { super.viewDidLoad() // setup table self.tableView.delegate = self self.tableView.dataSource = self self.tableView.rowHeight = UITableViewAutomaticDimension self.tableView.estimatedRowHeight = 500 // for pull-down refresh action let refreshControl = UIRefreshControl() refreshControl.addTarget(self, action: #selector(refreshControlAction(_:)), for: UIControlEvents.valueChanged) refreshControl.attributedTitle = NSAttributedString(string: "Fetching...") self.tableView.insertSubview(refreshControl, at: 0) // get the timeline client.getHomeTimeline(success: timeline, failure: error) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let tweets = tweets { return tweets.count } else { return 0 } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if let tweets = tweets { let cell = tableView.dequeueReusableCell(withIdentifier: "TimelineTweetCell", for: indexPath) as! TimelineTweetCell let tweet = tweets[indexPath.row] cell.tweet = tweet if !(animated?.contains(indexPath.row))! { cell.backgroundColor = .white cell.alpha = 0 UIView.animate(withDuration: 0.50, animations: { cell.alpha = 1 self.animated!.insert(indexPath.row) }) } return cell } else { return TimelineTweetCell() } } @IBAction func onSignoutButton(_ sender: Any) { User.currentUser = nil TwitterClient.sharedInstance.signout() let loginVC = self.storyboard?.instantiateViewController(withIdentifier: "LoginViewController") as! LoginViewController self.present(loginVC, animated: true, completion: nil) } private func timeline(_ tweets : [Tweet]) { self.tweets = tweets self.animated = [] self.tableView.reloadData() } private func error(_ error : Error) { print("error in fetching hometimeline -> \(error)") } @objc private func refreshControlAction(_ refreshControl: UIRefreshControl) { client.getHomeTimeline(success: timeline, failure: error) refreshControl.endRefreshing() } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { print("TimelineVC: The segue is to -> \(segue.identifier)") if let segueId = segue.identifier { switch segueId { case "homeToComposeVC": let navigationController = segue.destination as! UINavigationController let composeVC = navigationController.topViewController as! ComposeViewController case "homeToReplyVC": let navigationController = segue.destination as! UINavigationController let replyVC = navigationController.topViewController as! ReplyViewController if let cell = sender as? TimelineTweetCell, let indexPath = tableView.indexPath(for: cell) { tableView.deselectRow(at: indexPath, animated: true) replyVC.tweet = self.tweets?[indexPath.row] } case "homeToLoginVC": print("TimelieVC: User signed out, segue back to homeLogin") default: print("TimelineVC: No segue case found") return } } } }
apache-2.0
c3fa32d581f6b19d1128dc1f6cf87594
35.44
127
0.609879
5.609606
false
false
false
false
julienbodet/wikipedia-ios
Wikipedia/Code/WMFChangePasswordViewController.swift
1
6534
import WMF import UIKit class WMFChangePasswordViewController: WMFScrollViewController, Themeable { @IBOutlet fileprivate var titleLabel: UILabel! @IBOutlet fileprivate var subTitleLabel: UILabel! @IBOutlet fileprivate var passwordField: ThemeableTextField! @IBOutlet fileprivate var retypeField: ThemeableTextField! @IBOutlet fileprivate var passwordTitleLabel: UILabel! @IBOutlet fileprivate var retypeTitleLabel: UILabel! @IBOutlet fileprivate var saveButton: WMFAuthButton! fileprivate var theme: Theme = Theme.standard public var funnel: WMFLoginFunnel? public var userName:String? @IBAction fileprivate func saveButtonTapped(withSender sender: UIButton) { save() } @IBAction func textFieldDidChange(_ sender: UITextField) { guard let password = passwordField.text, let retype = retypeField.text else{ enableProgressiveButton(false) return } enableProgressiveButton((password.count > 0 && retype.count > 0)) } fileprivate func passwordFieldsMatch() -> Bool { return passwordField.text == retypeField.text } func enableProgressiveButton(_ highlight: Bool) { saveButton.isEnabled = highlight } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) enableProgressiveButton(false) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) passwordField.becomeFirstResponder() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) enableProgressiveButton(false) } public func textFieldShouldReturn(_ textField: UITextField) -> Bool { if (textField == passwordField) { retypeField.becomeFirstResponder() } else if (textField == retypeField) { save() } return true } override func viewDidLoad() { super.viewDidLoad() navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named:"close"), style: .plain, target:self, action:#selector(closeButtonPushed(_:))) navigationItem.leftBarButtonItem?.accessibilityLabel = CommonStrings.closeButtonAccessibilityLabel titleLabel.text = WMFLocalizedString("new-password-title", value:"Set your password", comment:"Title for password change interface") subTitleLabel.text = WMFLocalizedString("new-password-instructions", value:"You logged in with a temporary password. To finish logging in set a new password here.", comment:"Instructions for password change interface") passwordField.placeholder = WMFLocalizedString("field-new-password-placeholder", value:"enter new password", comment:"Placeholder text shown inside new password field until user taps on it") retypeField.placeholder = WMFLocalizedString("field-new-password-confirm-placeholder", value:"re-enter new password", comment:"Placeholder text shown inside confirm new password field until user taps on it") passwordTitleLabel.text = WMFLocalizedString("field-new-password-title", value:"New password", comment:"Title for new password field") retypeTitleLabel.text = WMFLocalizedString("field-new-password-confirm-title", value:"Confirm new password", comment:"Title for confirm new password field") view.wmf_configureSubviewsForDynamicType() apply(theme: theme) } @objc func closeButtonPushed(_ : UIBarButtonItem) { dismiss(animated: true, completion: nil) } fileprivate func save() { guard passwordFieldsMatch() else { WMFAlertManager.sharedInstance.showErrorAlertWithMessage(WMFLocalizedString("account-creation-passwords-mismatched", value:"Password fields do not match.", comment:"Alert shown if the user doesn't enter the same password in both password boxes"), sticky: true, dismissPreviousAlerts: true, tapCallBack: nil) passwordField.text = nil retypeField.text = nil passwordField.becomeFirstResponder() return } wmf_hideKeyboard() enableProgressiveButton(false) WMFAlertManager.sharedInstance.dismissAlert() guard let userName = userName else { return } WMFAuthenticationManager.sharedInstance .login(username: userName, password: passwordField.text!, retypePassword: retypeField.text!, oathToken: nil, captchaID: nil, captchaWord: nil, success: { _ in let loggedInMessage = String.localizedStringWithFormat(WMFLocalizedString("main-menu-account-title-logged-in", value:"Logged in as %1$@", comment:"Header text used when account is logged in. %1$@ will be replaced with current username."), userName) WMFAlertManager.sharedInstance.showSuccessAlert(loggedInMessage, sticky: false, dismissPreviousAlerts: true, tapCallBack: nil) self.dismiss(animated: true, completion: nil) self.funnel?.logSuccess() }, failure: { error in self.enableProgressiveButton(true) WMFAlertManager.sharedInstance.showErrorAlert(error as NSError, sticky: true, dismissPreviousAlerts: true, tapCallBack: nil) self.funnel?.logError(error.localizedDescription) if let error = error as? URLError { if error.code != .notConnectedToInternet { self.passwordField.text = nil self.retypeField.text = nil } } }) } func apply(theme: Theme) { self.theme = theme guard viewIfLoaded != nil else { return } view.backgroundColor = theme.colors.paperBackground view.tintColor = theme.colors.link let labels = [titleLabel, subTitleLabel, passwordTitleLabel, retypeTitleLabel] for label in labels { label?.textColor = theme.colors.secondaryText } let fields = [passwordField, retypeField] for field in fields { field?.apply(theme: theme) } saveButton.apply(theme: theme) } }
mit
cf2bba5f31ef34dbc0b04e3128861386
41.154839
319
0.646312
5.813167
false
false
false
false
CoderXiaoming/Ronaldo
SaleManager/SaleManager/Customer/Model/SAMCustomerModel.swift
1
1517
// // SAMCustomerModel.swift // SaleManager // // Created by apple on 16/11/16. // Copyright © 2016年 YZH. All rights reserved. // import UIKit class SAMCustomerModel: NSObject { ///存放客户数据模型数组单例 static let models = NSMutableArray() //MARK: - 对外提供的返回数据模型数组的类方法 class func modelArr() -> NSMutableArray { return models } var id = "" ///客户拼音简记码 var CGUnitBM = "" ///客户名称 var CGUnitName = "" { didSet{ CGUnitName = ((CGUnitName == "") ? "---" : CGUnitName) } } ///联系人 var contactPerson = "" ///省份 var province = "" ///城市 var city = "" ///地址 var address = "" { didSet{ address = ((address == "") ? "---" : address) } } ///手机 var mobilePhone = "" { didSet{ mobilePhone = ((mobilePhone == "") ? "---" : mobilePhone) } } ///固定电话 var phoneNumber = "" { didSet{ phoneNumber = ((phoneNumber == "") ? "---" : phoneNumber) } } ///传真 var faxNumber = "" { didSet{ faxNumber = ((faxNumber == "") ? "---" : faxNumber) } } ///备注 var memoInfo = "" { didSet{ memoInfo = ((memoInfo == "") ? "---" : memoInfo) } } ///部门 var deptName = "" ///员工名 var employeeName = "" }
apache-2.0
aa7497312752ee561b82b0ec4ada9225
18.8
69
0.448773
3.745946
false
false
false
false
texuf/outandabout
outandabout/outandabout/RSBarcodes/RSUPCEGenerator.swift
4
3939
// // RSUPCEGenerator.swift // RSBarcodesSample // // Created by R0CKSTAR on 6/11/14. // Copyright (c) 2014 P.D.Q. All rights reserved. // import UIKit // http://www.sly.com.tw/skill/know/new_page_6.htm // http://mdn.morovia.com/kb/UPCE-Specification-10634.html // http://mdn.morovia.com/kb/UPCA-Specification-10632.html // http://www.barcodeisland.com/upce.phtml public class RSUPCEGenerator: RSAbstractCodeGenerator, RSCheckDigitGenerator { let UPCE_ODD_ENCODINGS = [ "0001101", "0011001", "0010011", "0111101", "0100011", "0110001", "0101111", "0111011", "0110111", "0001011" ] let UPCE_EVEN_ENCODINGS = [ "0100111", "0110011", "0011011", "0100001", "0011101", "0111001", "0000101", "0010001", "0001001", "0010111" ] let UPCE_SEQUENCES = [ "000111", "001011", "001101", "001110", "010011", "011001", "011100", "010101", "010110", "011010" ] func convert2UPC_A(contents:String) -> String { let code = contents.substring(1, length: contents.length() - 2) let lastDigit = code[code.length() - 1].toInt()! var insertDigits = "0000" var upc_a = "" switch lastDigit { case 0...2: upc_a += code.substring(0, length: 2) + String(lastDigit) + insertDigits + code.substring(2, length: 3) case 3:lastDigit insertDigits = "00000" upc_a += code.substring(0, length: 3) + insertDigits + code.substring(3, length: 2) case 4:lastDigit insertDigits = "00000" upc_a += code.substring(0, length: 4) + insertDigits + code.substring(4, length: 1) default: upc_a += code.substring(0, length: 5) + insertDigits + String(lastDigit) } return "00" + upc_a } override public func isValid(contents: String) -> Bool { return super.isValid(contents) && contents.length() == 8 && contents[0].toInt()! == 0 && contents[contents.length() - 1] == self.checkDigit(contents) } override public func initiator() -> String { return "101" } override public func terminator() -> String { return "010101" } override public func barcode(contents: String) -> String { let checkValue = contents[contents.length() - 1].toInt()! let sequence = UPCE_SEQUENCES[checkValue] var barcode = "" for i in 1..<contents.length() - 1 { let digit = contents[i].toInt()! if sequence[i - 1].toInt()! % 2 == 0 { barcode += UPCE_EVEN_ENCODINGS[digit] } else { barcode += UPCE_ODD_ENCODINGS[digit] } } return barcode } // MARK: RSCheckDigitGenerator public func checkDigit(contents: String) -> String { /* UPC-A check digit is calculated using standard Mod10 method. Here outlines the steps to calculate UPC-A check digit: From the right to left, start with odd position, assign the odd/even position to each digit. Sum all digits in odd position and multiply the result by 3. Sum all digits in even position. Sum the results of step 3 and step 4. divide the result of step 4 by 10. The check digit is the number which adds the remainder to 10. */ let upc_a = self.convert2UPC_A(contents) var sum_odd = 0 var sum_even = 0 for i in 0..<upc_a.length() { let digit = upc_a[i].toInt()! if i % 2 == 0 { sum_even += digit } else { sum_odd += digit } } return String(10 - (sum_even + sum_odd * 3) % 10) } }
mit
b2a7a69dce90dbd5536a7f3277d1c698
29.3
124
0.540239
3.758588
false
false
false
false
KrishMunot/swift
test/SILGen/import_as_member.swift
1
1673
// RUN: %target-swift-frontend -emit-silgen -I %S/../IDE/Inputs/custom-modules %s 2>&1 | FileCheck --check-prefix=SIL %s // REQUIRES: objc_interop import ImportAsMember.A import ImportAsMember.Proto import ImportAsMember.Class public func returnGlobalVar() -> Double { return Struct1.globalVar } // SIL-LABEL: sil {{.*}}returnGlobalVar{{.*}} () -> Double { // SIL: %0 = global_addr @IAMStruct1GlobalVar : $*Double // SIL: %2 = load %0 : $*Double // SIL: return %2 : $Double // SIL-NEXT: } // SIL-LABEL: sil {{.*}}useProto{{.*}} (@owned IAMProto) -> () { // TODO: Add in body checks public func useProto(p: IAMProto) { p.mutateSomeState() let v = p.someValue p.someValue = v+1 } // SIL-LABEL: sil {{.*}}anchor{{.*}} () -> () { func anchor() {} // SIL-LABEL: sil {{.*}}useClass{{.*}} // SIL: bb0([[D:%[0-9]+]] : $Double, [[OPTS:%[0-9]+]] : $SomeClass.Options): public func useClass(d: Double, opts: SomeClass.Options) { // SIL: [[CTOR:%[0-9]+]] = function_ref @MakeIAMSomeClass : $@convention(c) (Double) -> @autoreleased SomeClass // SIL: [[OBJ:%[0-9]+]] = apply [[CTOR]]([[D]]) let o = SomeClass(value: d) // SIL: [[APPLY_FN:%[0-9]+]] = function_ref @IAMSomeClassApplyOptions : $@convention(c) (SomeClass, SomeClass.Options) -> () // SIL: apply [[APPLY_FN]]([[OBJ]], [[OPTS]]) o.applyOptions(opts) } extension SomeClass { // SIL-LABEL: sil hidden @_TFE16import_as_memberCSo9SomeClasscfT6doubleSd_S0_ // SIL: bb0([[DOUBLE:%[0-9]+]] : $Double // SIL-NOT: value_metatype // SIL: [[FNREF:%[0-9]+]] = function_ref @MakeIAMSomeClass // SIL: apply [[FNREF]]([[DOUBLE]]) convenience init(double: Double) { self.init(value: double) } }
apache-2.0
e115f6c019437172e0f2aaab6951ee12
33.854167
126
0.620442
3.186667
false
false
false
false
noppoMan/aws-sdk-swift
Sources/Soto/Services/Shield/Shield_Paginator.swift
1
5870
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. import SotoCore // MARK: Paginators extension Shield { /// Returns all ongoing DDoS attacks or all DDoS attacks during a specified time period. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listAttacksPaginator<Result>( _ input: ListAttacksRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListAttacksResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listAttacks, tokenKey: \ListAttacksResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listAttacksPaginator( _ input: ListAttacksRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListAttacksResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listAttacks, tokenKey: \ListAttacksResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Lists all Protection objects for the account. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listProtectionsPaginator<Result>( _ input: ListProtectionsRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListProtectionsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listProtections, tokenKey: \ListProtectionsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listProtectionsPaginator( _ input: ListProtectionsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListProtectionsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listProtections, tokenKey: \ListProtectionsResponse.nextToken, on: eventLoop, onPage: onPage ) } } extension Shield.ListAttacksRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> Shield.ListAttacksRequest { return .init( endTime: self.endTime, maxResults: self.maxResults, nextToken: token, resourceArns: self.resourceArns, startTime: self.startTime ) } } extension Shield.ListProtectionsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> Shield.ListProtectionsRequest { return .init( maxResults: self.maxResults, nextToken: token ) } }
apache-2.0
7ebd602de334327ef4c8c2f7a120d331
39.763889
168
0.629131
5.064711
false
false
false
false
qualaroo/QualarooSDKiOS
Qualaroo/Survey/Body/Question/Binary/AnswerBinaryView.swift
1
2324
// // AnswerBinaryView.swift // Qualaroo // // Copyright (c) 2018, Qualaroo, Inc. All Rights Reserved. // // Please refer to the LICENSE.md file for the terms and conditions // under which redistribution and use of this file is permitted. // import Foundation class AnswerBinaryView: UIView { private struct Const { static let buttonLabelMargin: CGFloat = 12 } private var interactor: AnswerBinaryInteractor! @IBOutlet weak var leftButton: UIButton! @IBOutlet weak var rightButton: UIButton! @IBOutlet weak var buttonsHeightConstraint: NSLayoutConstraint! @IBOutlet weak var buttonsEdgeMarginConstraint: NSLayoutConstraint! func setupView(backgroundColor: UIColor, buttonTextColor: UIColor, buttonBackgroundColor: UIColor, leftTitle: String, rightTitle: String, interactor: AnswerBinaryInteractor) { configureButtons(textColor: buttonTextColor, background: buttonBackgroundColor, leftTitle: leftTitle, rightTitle: rightTitle) self.backgroundColor = backgroundColor self.interactor = interactor } private func configureButtons(textColor: UIColor, background: UIColor, leftTitle: String, rightTitle: String) { leftButton.setTitle(leftTitle, for: .normal) rightButton.setTitle(rightTitle, for: .normal) let buttons: [UIButton] = [leftButton, rightButton] buttons.forEach { $0.setBackgroundColor(color: background, forState: .normal) $0.setTitleColor(textColor, for: .normal) $0.titleLabel?.textAlignment = .center $0.layer.cornerRadius = SurveyView.Const.buttonsCornerRadius $0.layoutIfNeeded() } let heights = buttons.map { $0.titleLabel?.frame.height }.removeNils() let maxHeight = heights.max() ?? SurveyView.Const.buttonsHeight buttonsHeightConstraint.constant = maxHeight + 2*AnswerBinaryView.Const.buttonLabelMargin buttonsEdgeMarginConstraint.constant = SurveyView.Const.edgeMargin } @IBAction func leftButtonPressed() { interactor.selectLeftAnswer() } @IBAction func rightButtonPressed() { interactor.selectRightAnswer() } }
mit
e8326ac6d1d4c60ae5187e027cf58994
33.686567
93
0.670826
5.085339
false
false
false
false
Rag0n/QuNotes
Carthage/Checkouts/WSTagsField/Source/WSTagsField.swift
1
19122
// // WSTagsField.swift // Whitesmith // // Created by Ricardo Pereira on 12/05/16. // Copyright © 2016 Whitesmith. All rights reserved. // import UIKit open class WSTagsField: UIView { fileprivate static let HSPACE: CGFloat = 0.0 fileprivate static let TEXT_FIELD_HSPACE: CGFloat = WSTagView.xPadding fileprivate static let VSPACE: CGFloat = 4.0 fileprivate static let MINIMUM_TEXTFIELD_WIDTH: CGFloat = 56.0 fileprivate static let STANDARD_ROW_HEIGHT: CGFloat = 25.0 fileprivate static let FIELD_MARGIN_X: CGFloat = WSTagView.xPadding fileprivate let textField = BackspaceDetectingTextField() open override var tintColor: UIColor! { didSet { tagViews.forEach() { item in item.tintColor = self.tintColor } } } open var textColor: UIColor? { didSet { tagViews.forEach() { item in item.textColor = self.textColor } } } open var selectedColor: UIColor? { didSet { tagViews.forEach() { item in item.selectedColor = self.selectedColor } } } open var selectedTextColor: UIColor? { didSet { tagViews.forEach() { item in item.selectedTextColor = self.selectedTextColor } } } open var delimiter: String? { didSet { tagViews.forEach() { item in item.displayDelimiter = self.delimiter ?? "" } } } open var fieldTextColor: UIColor? { didSet { textField.textColor = fieldTextColor } } open var placeholder: String = "Tags" { didSet { updatePlaceholderTextVisibility() } } open var font: UIFont? { didSet { textField.font = font tagViews.forEach() { item in item.font = self.font } } } open var readOnly: Bool = false { didSet { unselectAllTagViewsAnimated() textField.isEnabled = !readOnly repositionViews() } } open var padding: UIEdgeInsets = UIEdgeInsets(top: 10.0, left: 8.0, bottom: 10.0, right: 8.0) { didSet { repositionViews() } } open var spaceBetweenTags: CGFloat = 2.0 { didSet { repositionViews() } } public var keyboardType: UIKeyboardType { get { return textField.keyboardType } set { textField.keyboardType = newValue } } public var returnKeyType: UIReturnKeyType { get { return textField.returnKeyType } set { textField.returnKeyType = newValue } } public var spellCheckingType: UITextSpellCheckingType { get { return textField.spellCheckingType } set { textField.spellCheckingType = newValue } } public var autocapitalizationType: UITextAutocapitalizationType { get { return textField.autocapitalizationType } set { textField.autocapitalizationType = newValue } } public var autocorrectionType: UITextAutocorrectionType { get { return textField.autocorrectionType } set { textField.autocorrectionType = newValue } } public var enablesReturnKeyAutomatically: Bool { get { return textField.enablesReturnKeyAutomatically } set { textField.enablesReturnKeyAutomatically = newValue } } public var text: String? { get { return textField.text } set { textField.text = newValue } } @available(iOS, unavailable) override open var inputAccessoryView: UIView? { get { return super.inputAccessoryView } } open var inputFieldAccessoryView: UIView? { get { return textField.inputAccessoryView } set { textField.inputAccessoryView = newValue } } open fileprivate(set) var tags = [WSTag]() internal var tagViews = [WSTagView]() fileprivate var intrinsicContentHeight: CGFloat = 0.0 // MARK: - Events /// Called when the text field begins editing. open var onDidEndEditing: ((WSTagsField) -> Void)? /// Called when the text field ends editing. open var onDidBeginEditing: ((WSTagsField) -> Void)? /// Called when the text field should return. open var onShouldReturn: ((WSTagsField) -> Bool)? /// Called when the text field text has changed. You should update your autocompleting UI based on the text supplied. open var onDidChangeText: ((WSTagsField, _ text: String?) -> Void)? /// Called when a tag has been added. You should use this opportunity to update your local list of selected items. open var onDidAddTag: ((WSTagsField, _ tag: WSTag) -> Void)? /// Called when a tag has been removed. You should use this opportunity to update your local list of selected items. open var onDidRemoveTag: ((WSTagsField, _ tag: WSTag) -> Void)? /// Called when a tag has been selected. open var onDidSelectTagView: ((WSTagsField, _ tag: WSTagView) -> Void)? /// Called when a tag has been unselected. open var onDidUnselectTagView: ((WSTagsField, _ tag: WSTagView) -> Void)? /** * Called when the user attempts to press the Return key with text partially typed. * @return A Tag for a match (typically the first item in the matching results), * or nil if the text shouldn't be accepted. */ open var onVerifyTag: ((WSTagsField, _ text: String) -> Bool)? /** * Called when the view has updated its own height. If you are * not using Autolayout, you should use this method to update the * frames to make sure the tag view still fits. */ open var onDidChangeHeightTo: ((WSTagsField, _ height: CGFloat) -> Void)? // MARK: - public override init(frame: CGRect) { super.init(frame: frame) internalInit() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) internalInit() } fileprivate func internalInit() { textColor = .white selectedColor = .gray selectedTextColor = .black clipsToBounds = true textField.backgroundColor = .clear textField.autocorrectionType = UITextAutocorrectionType.no textField.autocapitalizationType = UITextAutocapitalizationType.none textField.spellCheckingType = .no textField.delegate = self textField.font = font textField.textColor = fieldTextColor addSubview(textField) textField.onDeleteBackwards = { [weak self] in if self?.readOnly ?? true { return } if self?.textField.text?.isEmpty ?? true, let tagView = self?.tagViews.last { self?.selectTagView(tagView, animated: true) self?.textField.resignFirstResponder() } } textField.addTarget(self, action: #selector(onTextFieldDidChange(_:)), for:UIControlEvents.editingChanged) intrinsicContentHeight = WSTagsField.STANDARD_ROW_HEIGHT repositionViews() } open override var intrinsicContentSize: CGSize { return CGSize(width: self.frame.size.width - padding.left - padding.right, height: max(45, self.intrinsicContentHeight)) } fileprivate func repositionViews() { let rightBoundary: CGFloat = self.bounds.width - padding.right let firstLineRightBoundary: CGFloat = rightBoundary var curX: CGFloat = padding.left var curY: CGFloat = padding.top var totalHeight: CGFloat = WSTagsField.STANDARD_ROW_HEIGHT var isOnFirstLine = true // Position Tag views var tagRect = CGRect.null for tagView in tagViews { tagRect = CGRect(origin: CGPoint.zero, size: tagView.sizeToFit(self.intrinsicContentSize)) let tagBoundary = isOnFirstLine ? firstLineRightBoundary : rightBoundary if curX + tagRect.width > tagBoundary { // Need a new line curX = padding.left curY += WSTagsField.STANDARD_ROW_HEIGHT + WSTagsField.VSPACE totalHeight += WSTagsField.STANDARD_ROW_HEIGHT isOnFirstLine = false } tagRect.origin.x = curX // Center our tagView vertically within STANDARD_ROW_HEIGHT tagRect.origin.y = curY + ((WSTagsField.STANDARD_ROW_HEIGHT - tagRect.height)/2.0) tagView.frame = tagRect tagView.setNeedsLayout() curX = tagRect.maxX + WSTagsField.HSPACE + self.spaceBetweenTags } // Always indent TextField by a little bit curX += max(0, WSTagsField.TEXT_FIELD_HSPACE - self.spaceBetweenTags) let textBoundary: CGFloat = isOnFirstLine ? firstLineRightBoundary : rightBoundary var availableWidthForTextField: CGFloat = textBoundary - curX if availableWidthForTextField < WSTagsField.MINIMUM_TEXTFIELD_WIDTH { isOnFirstLine = false // If in the future we add more UI elements below the tags, // isOnFirstLine will be useful, and this calculation is important. // So leaving it set here, and marking the warning to ignore it curX = padding.left + WSTagsField.TEXT_FIELD_HSPACE curY += WSTagsField.STANDARD_ROW_HEIGHT + WSTagsField.VSPACE totalHeight += WSTagsField.STANDARD_ROW_HEIGHT // Adjust the width availableWidthForTextField = rightBoundary - curX } var textFieldRect = CGRect.zero textFieldRect.origin.y = curY textFieldRect.size.height = WSTagsField.STANDARD_ROW_HEIGHT if textField.isEnabled { textFieldRect.origin.x = curX textFieldRect.size.width = availableWidthForTextField textField.isHidden = false } else { textField.isHidden = true } self.textField.frame = textFieldRect let oldContentHeight: CGFloat = self.intrinsicContentHeight intrinsicContentHeight = max(totalHeight, textFieldRect.maxY + padding.bottom) invalidateIntrinsicContentSize() if oldContentHeight != self.intrinsicContentHeight { let newContentHeight = intrinsicContentSize.height if let didChangeHeightToEvent = self.onDidChangeHeightTo { didChangeHeightToEvent(self, newContentHeight) } if constraints.isEmpty { frame.size.height = newContentHeight } } else if frame.size.height != oldContentHeight { if constraints.isEmpty { frame.size.height = oldContentHeight } } setNeedsDisplay() } fileprivate func updatePlaceholderTextVisibility() { if tags.count > 0 { textField.placeholder = nil } else { textField.placeholder = self.placeholder } } open override func layoutSubviews() { super.layoutSubviews() tagViews.forEach { $0.setNeedsLayout() } repositionViews() } /// Take the text inside of the field and make it a Tag. open func acceptCurrentTextAsTag() { if let currentText = tokenizeTextFieldText() , (self.textField.text?.isEmpty ?? true) == false { self.addTag(currentText) } } open var isEditing: Bool { return self.textField.isEditing } open func beginEditing() { self.textField.becomeFirstResponder() self.unselectAllTagViewsAnimated(false) } open func endEditing() { // NOTE: We used to check if .isFirstResponder and then resign first responder, but sometimes we noticed that it would be the first responder, but still return isFirstResponder=NO. So always attempt to resign without checking. self.textField.resignFirstResponder() } // MARK: - Adding / Removing Tags open func addTags(_ tags: [String]) { tags.forEach() { addTag($0) } } open func addTags(_ tags: [WSTag]) { tags.forEach() { addTag($0) } } open func addTag(_ tag: String) { addTag(WSTag(tag)) } open func addTag(_ tag: WSTag) { if self.tags.contains(tag) { return } self.tags.append(tag) let tagView = WSTagView(tag: tag) tagView.font = self.font tagView.tintColor = self.tintColor tagView.textColor = self.textColor tagView.selectedColor = self.selectedColor tagView.selectedTextColor = self.selectedTextColor tagView.displayDelimiter = self.delimiter ?? "" tagView.onDidRequestSelection = { [weak self] tagView in self?.selectTagView(tagView, animated: true) } tagView.onDidRequestDelete = { [weak self] tagView, replacementText in // First, refocus the text field self?.textField.becomeFirstResponder() if (replacementText?.isEmpty ?? false) == false { self?.textField.text = replacementText } // Then remove the view from our data if let index = self?.tagViews.index(of: tagView) { self?.removeTagAtIndex(index) } } tagView.onDidInputText = { [weak self] tagView, text in if text == "\n" { self?.selectNextTag() } else { self?.textField.becomeFirstResponder() self?.textField.text = text } } self.tagViews.append(tagView) addSubview(tagView) self.textField.text = "" if let didAddTagEvent = onDidAddTag { didAddTagEvent(self, tag) } // Clearing text programmatically doesn't call this automatically onTextFieldDidChange(self.textField) updatePlaceholderTextVisibility() repositionViews() } open func removeTag(_ tag: String) { removeTag(WSTag(tag)) } open func removeTag(_ tag: WSTag) { if let index = self.tags.index(of: tag) { removeTagAtIndex(index) } } open func removeTagAtIndex(_ index: Int) { if index < 0 || index >= self.tags.count { return } let tagView = self.tagViews[index] tagView.removeFromSuperview() self.tagViews.remove(at: index) let removedTag = self.tags[index] self.tags.remove(at: index) if let didRemoveTagEvent = onDidRemoveTag { didRemoveTagEvent(self, removedTag) } updatePlaceholderTextVisibility() repositionViews() } open func removeTags() { self.tags.enumerated().reversed().forEach { (arg) in let (index, _) = arg removeTagAtIndex(index) } } @discardableResult open func tokenizeTextFieldText() -> WSTag? { let text = self.textField.text?.trimmingCharacters(in: CharacterSet.whitespaces) ?? "" if text.isEmpty == false && (onVerifyTag?(self, text) ?? true) { let tag = WSTag(text) addTag(tag) self.textField.text = "" onTextFieldDidChange(self.textField) return tag } return nil } // MARK: - Actions @objc open func onTextFieldDidChange(_ sender: AnyObject) { if let didChangeTextEvent = onDidChangeText { didChangeTextEvent(self, textField.text) } } // MARK: - Tag selection open func selectNextTag() { guard let selectedIndex = tagViews.index(where: { $0.selected }) else { return } let nextIndex = tagViews.index(after: selectedIndex) if nextIndex < tagViews.count { tagViews[selectedIndex].selected = false tagViews[nextIndex].selected = true } } open func selectPrevTag() { guard let selectedIndex = tagViews.index(where: { $0.selected }) else { return } let prevIndex = tagViews.index(before: selectedIndex) if prevIndex >= 0 { tagViews[selectedIndex].selected = false tagViews[prevIndex].selected = true } } open func selectTagView(_ tagView: WSTagView, animated: Bool = false) { if self.readOnly { return } tagView.selected = true tagViews.forEach() { item in if item != tagView { item.selected = false onDidUnselectTagView?(self, item) } } onDidSelectTagView?(self, tagView) } open func unselectAllTagViewsAnimated(_ animated: Bool = false) { tagViews.forEach() { item in item.selected = false onDidUnselectTagView?(self, item) } } } public func ==(lhs: UITextField, rhs: WSTagsField) -> Bool { return lhs == rhs.textField } extension WSTagsField: UITextFieldDelegate { public func textFieldDidBeginEditing(_ textField: UITextField) { if let didBeginEditingEvent = onDidBeginEditing { didBeginEditingEvent(self) } unselectAllTagViewsAnimated(true) } public func textFieldDidEndEditing(_ textField: UITextField) { if let didEndEditingEvent = onDidEndEditing { didEndEditingEvent(self) } } public func textFieldShouldReturn(_ textField: UITextField) -> Bool { tokenizeTextFieldText() var shouldDoDefaultBehavior = false if let shouldReturnEvent = onShouldReturn { shouldDoDefaultBehavior = shouldReturnEvent(self) } return shouldDoDefaultBehavior } public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { return true } } private protocol BackspaceDetectingTextFieldDelegate: UITextFieldDelegate { /// Notify whenever the backspace key is pressed func textFieldDidDeleteBackwards(_ textField: UITextField) } private class BackspaceDetectingTextField: UITextField { var onDeleteBackwards: Optional<()->()> init() { super.init(frame: CGRect.zero) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func deleteBackward() { if let deleteBackwardsEvent = onDeleteBackwards { deleteBackwardsEvent() } // Call super afterwards. The `text` property will return text prior to the delete. super.deleteBackward() } }
gpl-3.0
dba72e9a250c022384cd3830fd5ead84
29.447452
234
0.602008
4.956195
false
false
false
false
gifsy/Gifsy
Frameworks/Bond/BondTests/NSTableViewTests.swift
18
3930
// // NSTableViewTests.swift // Bond // // Created by Michail Pishchagin on 15/08/2015. // Copyright (c) 2015 Bond. All rights reserved. // import Bond import Cocoa import XCTest enum TableOperation { case InsertRows(NSIndexSet) case RemoveRows(NSIndexSet) case ReloadRows(NSIndexSet, NSIndexSet) case ReloadData } func ==(op0: TableOperation, op1: TableOperation) -> Bool { switch (op0, op1) { case let (.InsertRows(set0), .InsertRows(set1)): return set0 == set1 case let (.RemoveRows(set0), .RemoveRows(set1)): return set0 == set1 case let (.ReloadRows(setRows0, setColumns0), .ReloadRows(setRows1, setColumns1)): return setRows0 == setRows1 && setColumns0 == setColumns1 case (.ReloadData, .ReloadData): return true default: return false } } extension TableOperation: Equatable, CustomStringConvertible { var description: String { switch self { case let .InsertRows(indexSet): return "InsertRows(\(indexSet)" case let .RemoveRows(indexSet): return "RemoveRows(\(indexSet)" case let .ReloadRows(rowsSet, columnsSet): return "ReloadRows(\(rowsSet), \(columnsSet)" case .ReloadData: return "ReloadData" } } } class TestTableView: NSTableView { var operations = [TableOperation]() override func insertRowsAtIndexes(indexes: NSIndexSet, withAnimation animationOptions: NSTableViewAnimationOptions) { operations.append(.InsertRows(indexes)) super.insertRowsAtIndexes(indexes, withAnimation: animationOptions) } override func removeRowsAtIndexes(indexes: NSIndexSet, withAnimation animationOptions: NSTableViewAnimationOptions) { operations.append(.RemoveRows(indexes)) super.removeRowsAtIndexes(indexes, withAnimation: animationOptions) } override func reloadDataForRowIndexes(rowIndexes: NSIndexSet, columnIndexes: NSIndexSet) { operations.append(.ReloadRows(rowIndexes, columnIndexes)) super.reloadDataForRowIndexes(rowIndexes, columnIndexes: columnIndexes) } override func reloadData() { operations.append(.ReloadData) super.reloadData() } } class TestTableViewDelegate: BNDTableViewDelegate { @objc func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn?, row: Int) -> NSView? { fatalError("should be unused in tests, as we never show the NSTableView") } func createCell(row: Int, array: ObservableArray<Int>, tableView: NSTableView) -> NSTableCellView { fatalError("should be unused in tests, as we never show the NSTableView") } } class NSTableViewDataSourceTests: XCTestCase { var tableView: TestTableView! var delegate: TestTableViewDelegate! var array: ObservableArray<Int>! var expectedOperations: [TableOperation]! override func setUp() { self.array = ObservableArray([1, 2]) self.tableView = TestTableView() self.delegate = TestTableViewDelegate() expectedOperations = [] array.bindTo(tableView, delegate: delegate) expectedOperations.append(.ReloadData) // `tableView` will get a `reloadData` when the bond is attached } // func testReload() { // array.value = [] // expectedOperations.append(.ReloadData) // XCTAssertEqual(expectedOperations, tableView.operations, "operation sequence did not match") // } func testInsertARow() { array.append(3) expectedOperations.append(.InsertRows(NSIndexSet(index: 2))) XCTAssertEqual(expectedOperations, tableView.operations, "operation sequence did not match") } func testDeleteARow() { array.removeLast() expectedOperations.append(.RemoveRows(NSIndexSet(index: 1))) XCTAssertEqual(expectedOperations, tableView.operations, "operation sequence did not match") } func testReloadARow() { array[1] = 5 expectedOperations.append(.ReloadRows(NSIndexSet(index: 1), NSIndexSet())) XCTAssertEqual(expectedOperations, tableView.operations, "operation sequence did not match") } }
apache-2.0
fcd7c1eaeaa40f0102e6962fd5d2c09a
30.693548
119
0.735369
4.391061
false
true
false
false
Bouke/HAP
Sources/HAP/Base/Predefined/Characteristics/Characteristic.SecuritySystemAlarmType.swift
1
2091
import Foundation public extension AnyCharacteristic { static func securitySystemAlarmType( _ value: UInt8 = 0, permissions: [CharacteristicPermission] = [.read, .events], description: String? = "Security System Alarm Type", format: CharacteristicFormat? = .uint8, unit: CharacteristicUnit? = nil, maxLength: Int? = nil, maxValue: Double? = 1, minValue: Double? = 0, minStep: Double? = 1, validValues: [Double] = [], validValuesRange: Range<Double>? = nil ) -> AnyCharacteristic { AnyCharacteristic( PredefinedCharacteristic.securitySystemAlarmType( value, permissions: permissions, description: description, format: format, unit: unit, maxLength: maxLength, maxValue: maxValue, minValue: minValue, minStep: minStep, validValues: validValues, validValuesRange: validValuesRange) as Characteristic) } } public extension PredefinedCharacteristic { static func securitySystemAlarmType( _ value: UInt8 = 0, permissions: [CharacteristicPermission] = [.read, .events], description: String? = "Security System Alarm Type", format: CharacteristicFormat? = .uint8, unit: CharacteristicUnit? = nil, maxLength: Int? = nil, maxValue: Double? = 1, minValue: Double? = 0, minStep: Double? = 1, validValues: [Double] = [], validValuesRange: Range<Double>? = nil ) -> GenericCharacteristic<UInt8> { GenericCharacteristic<UInt8>( type: .securitySystemAlarmType, value: value, permissions: permissions, description: description, format: format, unit: unit, maxLength: maxLength, maxValue: maxValue, minValue: minValue, minStep: minStep, validValues: validValues, validValuesRange: validValuesRange) } }
mit
30ff86abfe63dac5b2bf9f15a60d1193
33.278689
67
0.585366
5.334184
false
false
false
false
jacobwhite/firefox-ios
Client/Frontend/Share/ShareExtensionHelper.swift
1
6127
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import OnePasswordExtension private let log = Logger.browserLogger class ShareExtensionHelper: NSObject { fileprivate weak var selectedTab: Tab? fileprivate let selectedURL: URL fileprivate var onePasswordExtensionItem: NSExtensionItem! fileprivate let browserFillIdentifier = "org.appextension.fill-browser-action" init(url: URL, tab: Tab?) { self.selectedURL = tab?.canonicalURL?.displayURL ?? url self.selectedTab = tab } func createActivityViewController(_ completionHandler: @escaping (_ completed: Bool, _ activityType: String?) -> Void) -> UIActivityViewController { var activityItems = [AnyObject]() let printInfo = UIPrintInfo(dictionary: nil) let absoluteString = selectedTab?.url?.absoluteString ?? selectedURL.absoluteString printInfo.jobName = absoluteString printInfo.outputType = .general activityItems.append(printInfo) if let tab = selectedTab { activityItems.append(TabPrintPageRenderer(tab: tab)) } if let title = selectedTab?.title { activityItems.append(TitleActivityItemProvider(title: title)) } activityItems.append(self) let activityViewController = UIActivityViewController(activityItems: activityItems, applicationActivities: nil) // Hide 'Add to Reading List' which currently uses Safari. // We would also hide View Later, if possible, but the exclusion list doesn't currently support // third-party activity types (rdar://19430419). activityViewController.excludedActivityTypes = [ UIActivityType.addToReadingList, ] // This needs to be ready by the time the share menu has been displayed and // activityViewController(activityViewController:, activityType:) is called, // which is after the user taps the button. So a million cycles away. findLoginExtensionItem() activityViewController.completionWithItemsHandler = { activityType, completed, returnedItems, activityError in if !completed { completionHandler(completed, activityType.map { $0.rawValue }) return } // Bug 1392418 - When copying a url using the share extension there are 2 urls in the pasteboard. // This is a iOS 11.0 bug. Fixed in 11.2 if UIPasteboard.general.hasURLs, let url = UIPasteboard.general.urls?.first { UIPasteboard.general.urls = [url] } if self.isPasswordManagerActivityType(activityType.map { $0.rawValue }) { if let logins = returnedItems { self.fillPasswords(logins as [AnyObject]) } } completionHandler(completed, activityType.map { $0.rawValue }) } return activityViewController } } extension ShareExtensionHelper: UIActivityItemSource { func activityViewControllerPlaceholderItem(_ activityViewController: UIActivityViewController) -> Any { return selectedURL } func activityViewController(_ activityViewController: UIActivityViewController, itemForActivityType activityType: UIActivityType?) -> Any? { if let type = activityType, isPasswordManagerActivityType(type.rawValue) { return onePasswordExtensionItem } else { // Return the URL for the selected tab. If we are in reader view then decode // it so that we copy the original and not the internal localhost one. return selectedURL.isReaderModeURL ? selectedURL.decodeReaderModeURL : selectedURL } } func activityViewController(_ activityViewController: UIActivityViewController, dataTypeIdentifierForActivityType activityType: UIActivityType?) -> String { if let type = activityType, isPasswordManagerActivityType(type.rawValue) { return browserFillIdentifier } return activityType == nil ? browserFillIdentifier : kUTTypeURL as String } } private extension ShareExtensionHelper { func isPasswordManagerActivityType(_ activityType: String?) -> Bool { // A 'password' substring covers the most cases, such as pwsafe and 1Password. // com.agilebits.onepassword-ios.extension // com.app77.ios.pwsafe2.find-login-action-password-actionExtension // If your extension's bundle identifier does not contain "password", simply submit a pull request by adding your bundle identifier. return (activityType?.range(of: "password") != nil) || (activityType == "com.lastpass.ilastpass.LastPassExt") || (activityType == "in.sinew.Walletx.WalletxExt") || (activityType == "com.8bit.bitwarden.find-login-action-extension") } func findLoginExtensionItem() { guard let selectedWebView = selectedTab?.webView else { return } // Add 1Password to share sheet OnePasswordExtension.shared().createExtensionItem(forWebView: selectedWebView, completion: {(extensionItem, error) -> Void in if extensionItem == nil { log.error("Failed to create the password manager extension item: \(error.debugDescription).") return } // Set the 1Password extension item property self.onePasswordExtensionItem = extensionItem }) } func fillPasswords(_ returnedItems: [AnyObject]) { guard let selectedWebView = selectedTab?.webView else { return } OnePasswordExtension.shared().fillReturnedItems(returnedItems, intoWebView: selectedWebView, completion: { (success, returnedItemsError) -> Void in if !success { log.error("Failed to fill item into webview: \(returnedItemsError ??? "nil").") } }) } }
mpl-2.0
975fab8e991a5682422db141d390d869
41.548611
160
0.669985
5.564941
false
false
false
false
kotdark/watchOS-2-Sampler
watchOS2Sampler WatchKit Extension/TableAnimationInterfaceController.swift
14
1545
// // TableAnimationInterfaceController.swift // watchOS2Sampler // // Created by Shuichi Tsutsumi on 2015/06/13. // Copyright © 2015年 Shuichi Tsutsumi. All rights reserved. // import WatchKit import Foundation class TableAnimationInterfaceController: WKInterfaceController { @IBOutlet weak var table: WKInterfaceTable! var numberOfRows: Int = 3 override func awakeWithContext(context: AnyObject?) { super.awakeWithContext(context) } override func willActivate() { super.willActivate() table.setNumberOfRows(numberOfRows, withRowType: "Cell") self.loadTableData() } override func didDeactivate() { // This method is called when watch view controller is no longer visible super.didDeactivate() } private func loadTableData() { for (var i=0; i<numberOfRows; i++) { let row = table.rowControllerAtIndex(i) as! RowController row.showItem("\(i)", detail: "") } } // ========================================================================= // MARK: - Actions @IBAction func insertBtnTapped() { table.insertRowsAtIndexes(NSIndexSet(index: 0), withRowType: "Cell") numberOfRows++ self.loadTableData() } @IBAction func removeBtnTapped() { if numberOfRows <= 1 { return } table.removeRowsAtIndexes(NSIndexSet(index: 0)) numberOfRows-- self.loadTableData() } }
mit
a1075aa801a10cae0892deaba78df358
22.723077
80
0.5869
5.244898
false
false
false
false
kickstarter/ios-oss
Library/ViewModels/ActivitySampleFollowCellViewModel.swift
1
2069
import Foundation import KsApi import Prelude import ReactiveExtensions import ReactiveSwift public protocol ActivitySampleFollowCellViewModelInputs { /// Call to configure cell with activity value. func configureWith(activity: Activity) /// Call when the see all activity button is tapped. func seeAllActivityTapped() } public protocol ActivitySampleFollowCellViewModelOutputs { /// Emits the friend follow to be displayed. var friendFollowText: Signal<String, Never> { get } /// Emits the friend image url to be displayed. var friendImageURL: Signal<URL?, Never> { get } /// Emits when should go to activities screen. var goToActivity: Signal<Void, Never> { get } } public protocol ActivitySampleFollowCellViewModelType { var inputs: ActivitySampleFollowCellViewModelInputs { get } var outputs: ActivitySampleFollowCellViewModelOutputs { get } } public final class ActivitySampleFollowCellViewModel: ActivitySampleFollowCellViewModelInputs, ActivitySampleFollowCellViewModelOutputs, ActivitySampleFollowCellViewModelType { public init() { let activity = self.activityProperty.signal.skipNil() self.friendFollowText = activity .map { Strings.activity_user_name_is_now_following_you(user_name: $0.user?.name ?? "") } self.friendImageURL = activity .map { ($0.user?.avatar.medium).flatMap(URL.init) } self.goToActivity = self.seeAllActivityTappedProperty.signal } fileprivate let activityProperty = MutableProperty<Activity?>(nil) public func configureWith(activity: Activity) { self.activityProperty.value = activity } fileprivate let seeAllActivityTappedProperty = MutableProperty(()) public func seeAllActivityTapped() { self.seeAllActivityTappedProperty.value = () } public let friendFollowText: Signal<String, Never> public let friendImageURL: Signal<URL?, Never> public let goToActivity: Signal<Void, Never> public var inputs: ActivitySampleFollowCellViewModelInputs { return self } public var outputs: ActivitySampleFollowCellViewModelOutputs { return self } }
apache-2.0
6878b5559aa188e00ef98fe5b1d570ea
32.918033
94
0.775254
4.597778
false
false
false
false
cldershem/elevenchat
ElevenChat/RootViewController.swift
1
8272
// // ViewController.swift // ElevenChat // // Created by Cameron Dershem on 9/10/14. // Copyright (c) 2014 Cameron Dershem. All rights reserved. // import UIKit class RootViewController: UIPageViewController, UIPageViewControllerDataSource, PFLogInViewControllerDelegate, PFSignUpViewControllerDelegate { var messagesViewController : MessagesViewController! var cameraViewController : CameraViewController! var friendsViewController : FriendsViewController! override func viewDidLoad() { super.viewDidLoad() // set UIPageViewControllerDataSource self.dataSource = self // Reference all of the view controllers on the storyboard self.messagesViewController = self.storyboard?.instantiateViewControllerWithIdentifier("messagesViewController") as? MessagesViewController self.messagesViewController.title = "Messages" println("Messages!") self.cameraViewController = self.storyboard?.instantiateViewControllerWithIdentifier("cameraViewController") as? CameraViewController self.cameraViewController.title = "Camera" println("Camera!") self.friendsViewController = self.storyboard?.instantiateViewControllerWithIdentifier("friendsViewController") as? FriendsViewController self.friendsViewController.title = "Friends" println("Friends!") // Set starting view controllers var startingViewControllers : NSArray = [self.cameraViewController] self.setViewControllers(startingViewControllers, direction: .Forward, animated: false, completion: nil) println("Captain Planet!") } override func viewDidAppear(animated: Bool) { self.checkAuth() } func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? { switch viewController.title! { case "Messages": return nil case "Camera": return messagesViewController case "Friends": return cameraViewController default: return nil } } // pink green blue func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? { switch viewController.title! { case "Messages": return cameraViewController case "Camera": return friendsViewController case "Friends": return nil default: return nil } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func checkAuth() { // check if logged in if ChatUser.currentUser() == nil { // 1: create and show login controller var loginViewController = PFLogInViewController() loginViewController.delegate = self // 2: Hide cancel button loginViewController.fields = PFLogInFields.UsernameAndPassword | PFLogInFields.LogInButton | PFLogInFields.SignUpButton | PFLogInFields.PasswordForgotten // 3: Customize Logo var logo = UIImage(named: "Logo") loginViewController.logInView.logo = UIImageView(image: logo) // 4: create sign up view contorller var signUpViewController = PFSignUpViewController() signUpViewController.fields = PFSignUpFields.UsernameAndPassword | PFSignUpFields.Email | PFSignUpFields.Additional | PFSignUpFields.SignUpButton | PFSignUpFields.DismissButton signUpViewController.delegate = self // 5: customize logo signUpViewController.signUpView.logo = UIImageView(image: logo) // 6: "Repurpose" the additional field as our phone number signup field var signupColor = UIColor.lightGrayColor() var additionalFieldText = NSAttributedString(string: "Phone Number", attributes: [NSForegroundColorAttributeName: signupColor]) signUpViewController.signUpView.additionalField.attributedPlaceholder = additionalFieldText // 7: Assign our signup controller to be displayed from the login controller loginViewController.signUpController = signUpViewController // 8: Present the login view controller self.presentViewController(loginViewController, animated: true, completion: nil) } } func logInViewController(logInController: PFLogInViewController!, shouldBeginLogInWithUsername username: String!, password: String!) -> Bool { if username != nil && password != nil && countElements(username) != 0 && countElements(password) != 0 { return true // Begin login process } if let ios8Alert: AnyClass = NSClassFromString("UIAlertController") { var alert = UIAlertController(title: "Error", message: "Username and Password are required!", preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) } else { let alert = UIAlertView(title: "Error", message: "Username and Password are required!", delegate: nil, cancelButtonTitle: "OK") alert.show() } return false } // this also sets ChatUser() func logInViewController(logInController: PFLogInViewController!, didLogInUser user: PFUser!) { self.dismissViewControllerAnimated(true, completion: nil) } func logInViewController(logInController: PFLogInViewController!, didFailToLogInWithError error: NSError!) { if let ios8Alert: AnyClass = NSClassFromString("UIAlertController") { var alert = UIAlertController(title: "Login Failed", message: "Login Failed", preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) } else { let alert = UIAlertView(title: "Login Failed", message: "Please check your username and password", delegate: nil, cancelButtonTitle: "OK") alert.show() } } func signUpViewController(signUpController: PFSignUpViewController!, didSignUpUser user: PFUser!) { self.dismissViewControllerAnimated(true, completion: nil) } func signUpViewController(signUpController: PFSignUpViewController!, shouldBeginSignUp info: [NSObject : AnyObject]!) -> Bool { var eInfo = info as NSDictionary var infoComplete = true for (key,val) in eInfo { if let field = eInfo.objectForKey(key) as? NSString { if field.length == 0 { infoComplete = false break } } } if !infoComplete { if let ios8Alert: AnyClass = NSClassFromString("UIAlertController") { var alert = UIAlertController(title: "Signup Failed", message: "All fields are required", preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) } else { let alert = UIAlertView(title: "Signup Failed", message: "All fields are required", delegate: nil, cancelButtonTitle: "OK") alert.show() } } return infoComplete } }
mit
5c32fa61333de32310d3742857315299
38.966184
161
0.635517
6.228916
false
false
false
false
DianQK/Flix
Flix/Builder/_CollectionViewBuilder.swift
1
5744
// // _CollectionViewBuilder.swift // Flix // // Created by DianQK on 22/10/2017. // Copyright © 2017 DianQK. All rights reserved. // import UIKit import RxSwift import RxCocoa import RxDataSources protocol _CollectionViewBuilder: Builder { var disposeBag: DisposeBag { get } var delegateProxy: CollectionViewDelegateProxy { get } var collectionView: UICollectionView { get } var nodeProviders: [String: _CollectionViewMultiNodeProvider] { get } var footerSectionProviders: [String: _SectionPartionCollectionViewProvider] { get } var headerSectionProviders: [String: _SectionPartionCollectionViewProvider] { get } } extension _CollectionViewBuilder { func build<S: FlixSectionModelType>(dataSource: CollectionViewSectionedDataSource<S>) where S.Item: _Node, S.Section: _SectionNode { dataSource.canMoveItemAtIndexPath = { [weak collectionView, weak self] (dataSource, indexPath) in guard let collectionView = collectionView else { return false } let node = dataSource[indexPath] guard let provider = self?.nodeProviders[node.providerIdentity] else { return false } if let provider = provider as? _CollectionViewMoveable { return provider._collectionView(collectionView, canMoveItemAt: indexPath, node: node) } else { return false } } dataSource.moveItem = { [weak collectionView, weak self] (dataSource, sourceIndexPath, destinationIndexPath) in guard let collectionView = collectionView else { return } let node = dataSource[destinationIndexPath] guard let provider = self?.nodeProviders[node.providerIdentity] as? _CollectionViewMoveable else { return } provider._collectionView( collectionView, moveItemAt: sourceIndexPath.row - node.providerStartIndexPath.row, to: destinationIndexPath.row - node.providerStartIndexPath.row, node: node ) } self.delegateProxy.targetIndexPathForMoveFromItemAt = { [weak self] (collectionView, originalIndexPath, proposedIndexPath) -> IndexPath in let node = dataSource[originalIndexPath] let providerIdentity = node.providerIdentity let provider = self?.nodeProviders[providerIdentity]! if let _ = provider as? _CollectionViewMoveable { if (proposedIndexPath <= node.providerStartIndexPath) { return node.providerStartIndexPath } else if (proposedIndexPath >= node.providerEndIndexPath) { return node.providerEndIndexPath } else { return proposedIndexPath } } else { return proposedIndexPath } } collectionView.rx.itemSelected .subscribe(onNext: { [weak collectionView, unowned self] (indexPath) in guard let `collectionView` = collectionView else { return } let node = dataSource[indexPath] let provider = self.nodeProviders[node.providerIdentity]! provider._itemSelected(collectionView, indexPath: indexPath, node: node) }) .disposed(by: disposeBag) collectionView.rx.itemDeselected .subscribe(onNext: { [weak collectionView, unowned self] (indexPath) in guard let `collectionView` = collectionView else { return } let node = dataSource[indexPath] let provider = self.nodeProviders[node.providerIdentity]! provider._itemDeselected(collectionView, indexPath: indexPath, node: node) }) .disposed(by: disposeBag) self.delegateProxy.sizeForItem = { [unowned self] collectionView, flowLayout, indexPath in let node = dataSource[indexPath] let providerIdentity = node.providerIdentity let provider = self.nodeProviders[providerIdentity]! return provider._collectionView(collectionView, layout: flowLayout, sizeForItemAt: indexPath, node: node) } self.delegateProxy.shouldSelectItemAt = { [unowned self] collectionView, indexPath in let node = dataSource[indexPath] let providerIdentity = node.providerIdentity let provider = self.nodeProviders[providerIdentity]! return provider._collectionView(collectionView, shouldSelectItemAt: indexPath, node: node) } self.delegateProxy.referenceSizeForFooterInSection = { [unowned self] collectionView, collectionViewLayout, section in guard let footerNode = dataSource[section].model.footerNode else { return CGSize.zero } let providerIdentity = footerNode.providerIdentity let provider = self.footerSectionProviders[providerIdentity]! return provider._collectionView(collectionView, layout: collectionViewLayout, referenceSizeInSection: section, node: footerNode) } self.delegateProxy.referenceSizeForHeaderInSection = { [unowned self] collectionView, collectionViewLayout, section in guard let footerNode = dataSource[section].model.headerNode else { return CGSize.zero } let providerIdentity = footerNode.providerIdentity let provider = self.headerSectionProviders[providerIdentity]! return provider._collectionView(collectionView, layout: collectionViewLayout, referenceSizeInSection: section, node: footerNode) } collectionView.rx.setDelegate(self.delegateProxy).disposed(by: disposeBag) } }
mit
f589a44bf6f2f2adfc2c6f47146f0161
47.260504
146
0.661327
5.613881
false
false
false
false
material-motion/material-motion-swift
examples/FabTransitionExample.swift
1
6962
/* Copyright 2016-present The Material Motion Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import UIKit import MaterialMotion class FabTransitionExampleViewController: ExampleViewController, TransitionContextViewRetriever { var actionButton: UIButton! override func viewDidLoad() { super.viewDidLoad() actionButton = UIButton(type: .custom) actionButton.backgroundColor = .primaryColor actionButton.bounds = .init(x: 0, y: 0, width: 50, height: 50) actionButton.layer.cornerRadius = actionButton.bounds.width / 2 actionButton.layer.position = .init(x: view.bounds.width - actionButton.bounds.width / 2 - 24, y: view.bounds.height - actionButton.bounds.height / 2 - 24) actionButton.autoresizingMask = [.flexibleLeftMargin, .flexibleTopMargin] actionButton.layer.shadowOpacity = 0.5 actionButton.layer.shadowOffset = .init(width: 0, height: 3) actionButton.layer.shadowRadius = 2 actionButton.layer.shadowPath = UIBezierPath(ovalIn: actionButton.bounds).cgPath view.addSubview(actionButton) actionButton.addTarget(self, action: #selector(didTap), for: .touchUpInside) } func didTap() { let vc = ModalViewController() vc.transitionController.transition = CircularRevealTransition() present(vc, animated: true) } func contextViewForTransition(foreViewController: UIViewController) -> UIView? { return actionButton } override func exampleInformation() -> ExampleInfo { return .init(title: type(of: self).catalogBreadcrumbs().last!, instructions: "Tap the floating action button to start a transition.") } } private class ModalViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .primaryColor let exampleView = center(createExampleView(), within: view) exampleView.backgroundColor = .white view.addSubview(exampleView) view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(didTap))) } func didTap() { dismiss(animated: true) } } let floodFillOvershootRatio: CGFloat = 1.2 private class CircularRevealTransition: TransitionWithTermination { // TODO: Support for transient views. var floodFillView: UIView! var foreViewLayer: CALayer! func didEndTransition(withContext ctx: TransitionContext, runtime: MotionRuntime) { floodFillView.removeFromSuperview() foreViewLayer.mask = nil } func willBeginTransition(withContext ctx: TransitionContext, runtime: MotionRuntime) -> [Stateful] { foreViewLayer = ctx.fore.view.layer let contextView = ctx.contextView()! floodFillView = UIView() floodFillView.backgroundColor = contextView.backgroundColor floodFillView.layer.cornerRadius = contextView.layer.cornerRadius floodFillView.layer.shadowColor = contextView.layer.shadowColor floodFillView.layer.shadowOffset = contextView.layer.shadowOffset floodFillView.layer.shadowOpacity = contextView.layer.shadowOpacity floodFillView.layer.shadowRadius = contextView.layer.shadowRadius floodFillView.layer.shadowPath = contextView.layer.shadowPath floodFillView.frame = ctx.containerView().convert(contextView.bounds, from: contextView) ctx.containerView().addSubview(floodFillView) let maskLayer = CAShapeLayer() let maskPathBounds = floodFillView.frame.insetBy(dx: 1, dy: 1) maskLayer.path = UIBezierPath(ovalIn: maskPathBounds).cgPath ctx.fore.view.layer.mask = maskLayer // The distance from the center of the context view to the top left of the screen is the desired // radius of the circle fill. If the context view is placed in a different corner of the screen // then this will need to be replaced with an algorithm that determines the furthest corner from // the center of the view. let outerRadius = CGFloat(sqrt(floodFillView.center.x * floodFillView.center.x + floodFillView.center.y * floodFillView.center.y)) * floodFillOvershootRatio let expandedSize = CGSize(width: outerRadius * 2, height: outerRadius * 2) let expansion = tween(back: floodFillView.bounds.size, fore: expandedSize, ctx: ctx) let fadeOut = tween(back: CGFloat(1), fore: CGFloat(0), ctx: ctx) let radius = tween(back: floodFillView.layer.cornerRadius, fore: outerRadius, ctx: ctx) let foreShadowPath = CGRect(origin: .zero(), size: expandedSize) let shadowPath = tween(back: floodFillView.layer.shadowPath!, fore: UIBezierPath(ovalIn: foreShadowPath).cgPath, ctx: ctx) let floodLayer = runtime.get(floodFillView).layer runtime.add(expansion, to: floodLayer.size) runtime.add(fadeOut, to: floodLayer.opacity) runtime.add(radius, to: floodLayer.cornerRadius) runtime.add(shadowPath, to: floodLayer.shadowPath) let shiftIn = tween(back: ctx.fore.view.layer.position.y + 40, fore: ctx.fore.view.layer.position.y, ctx: ctx) runtime.add(shiftIn, to: runtime.get(ctx.fore.view).layer.positionY) let maskShiftIn = tween(back: CGFloat(-40), fore: CGFloat(0), ctx: ctx) runtime.add(maskShiftIn, to: runtime.get(maskLayer).positionY) let foreMaskBounds = CGRect(x: floodFillView.center.x - outerRadius, y: floodFillView.center.y - outerRadius, width: outerRadius * 2, height: outerRadius * 2) let maskReveal = tween(back: maskLayer.path!, fore: UIBezierPath(ovalIn: foreMaskBounds).cgPath, ctx: ctx) runtime.add(maskReveal, to: runtime.get(maskLayer).path) runtime.add(Hidden(), to: contextView) return [expansion, fadeOut, radius, shadowPath, shiftIn] } private func tween<T>(back: T, fore: T, ctx: TransitionContext) -> Tween<T> { let values: [T] if ctx.direction.value == .forward { values = [back, fore] } else { values = [fore, back] } return Tween(duration: 0.4 * simulatorDragCoefficient(), values: values) } } // TODO: The need here is we want to hide a given view will the transition is active. This // implementation does not register a stream with the runtime. private class Hidden: Interaction { deinit { for view in hiddenViews { view.isHidden = false } } func add(to view: UIView, withRuntime runtime: MotionRuntime, constraints: NoConstraints) { view.isHidden = true hiddenViews.insert(view) } var hiddenViews = Set<UIView>() }
apache-2.0
c8695bd6bf58d81dc5c26138a79ba185
39.011494
160
0.726084
4.384131
false
false
false
false
UniqHu/Youber
Youber/Youber/View/UserInfoSetPage.swift
1
2454
// // UserInfoSetPage.swift // Youber // // Created by uniqhj on 2017/3/22. // Copyright © 2017年 Hujian 😄. All rights reserved. // import UIKit import XLActionController class UserInfoSetPage: YbBasePage ,UIImagePickerControllerDelegate,UINavigationControllerDelegate{ @IBOutlet weak var avator: UIImageView! override func viewDidLoad() { super.viewDidLoad() title = "个人信息" setNavigationItem(title: "ub_forms_return.png", selector: #selector(leftItemAction), isRight: false) setNavigationItem(title: "下一步", selector: #selector(rightItemAction), isRight: true) } override func rightItemAction() { let payPage = AddPayPage() navigationController?.pushViewController(payPage, animated: true) } @IBAction func chooseAvator(_ sender: UIButton) { let actionController = PeriscopeActionController() actionController.headerData = "编辑照片" actionController.addAction(Action("拍照", style: .destructive, handler: { action in let pick = UIImagePickerController() pick.sourceType = .camera pick.delegate = self pick.allowsEditing = true self.present(pick, animated: true, completion: nil) })) actionController.addAction(Action("从相册选择", style: .destructive, handler: { action in let pick = UIImagePickerController() pick.sourceType = .photoLibrary pick.delegate = self pick.allowsEditing = true self.present(pick, animated: true, completion: nil) })) actionController.addSection(PeriscopeSection()) actionController.addAction(Action("取消", style: .cancel, handler: { action in })) present(actionController, animated: true, completion: nil) } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { if let ediImage = info[UIImagePickerControllerEditedImage] as? UIImage{ avator.image = ediImage }else{ if let image = info[UIImagePickerControllerOriginalImage] as? UIImage{ avator.image = image } } dismiss(animated: true, completion: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
mit
aa5182cec1f5eb8f24efbcddd9e74640
31.986301
119
0.641611
5.037657
false
false
false
false
peigen/iLife
iLife/AppsVC.swift
1
2749
// // AppsVC.swift // iLife // // Created by zq on 14-7-9. // Copyright (c) 2014 Peigen.info. All rights reserved. // import UIKit class AppsVC : BaseVC,UICollectionViewDelegate,UICollectionViewDataSource { var dicApps : NSMutableArray = NSMutableArray() var appsView : UICollectionView! override func viewDidLoad() { super.viewDidLoad() customizeRightBarItemWithTarget(self, action: Selector("rightButtonPress:"),title: "通讯录") var layout = setDefaultLayout() appsView = UICollectionView(frame: CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-20-44), collectionViewLayout: layout) appsView.backgroundColor = UIColor.whiteColor() appsView.registerNib(UINib(nibName: "AppCell",bundle: nil), forCellWithReuseIdentifier: "AppCell") appsView.dataSource = self; appsView.delegate = self; appsView.backgroundColor = UIColor.clearColor() self.view.addSubview(appsView) SVProgressHUD.showWithStatus("初始化中...") MyApps().detectAppSchemes({ appDic in SVProgressHUD.dismiss() self.dicApps.addObjectsFromArray(appDic) self.appsView.reloadData() //println(self.dicApps) },failApp: { error in SVProgressHUD.showErrorWithStatus(error.localizedDescription) println(error) }) } override func rightButtonPress(sender:AnyObject?) { var adBook = storyBoardController("ADBookVC") as ADBookVC YJApp.iLifeNC!.pushViewController(adBook, animated: true) } func collectionView(collectionView: UICollectionView!, numberOfItemsInSection section: Int) -> Int { return dicApps.count } func numberOfSectionsInCollectionView(collectionView: UICollectionView!) -> Int { return 1 } func collectionView(collectionView: UICollectionView!, cellForItemAtIndexPath indexPath: NSIndexPath!) -> UICollectionViewCell! { var cell = collectionView.dequeueReusableCellWithReuseIdentifier("AppCell", forIndexPath: indexPath) as AppCell var dic = dicApps.objectAtIndex(indexPath.row*(indexPath.section+1)) as NSDictionary cell.showApp(dic) return cell } func collectionView(collectionView: UICollectionView!, didSelectItemAtIndexPath indexPath: NSIndexPath!) { var selApp = dicApps.objectAtIndex(indexPath.row*(indexPath.section+1)) as NSDictionary var scheme = selApp.objectForKey("scheme") as String sysUrl.openURLApp(scheme) } }
gpl-3.0
e644bc5c99ca07cacf03d68dd51c240b
31.559524
132
0.642413
5.19962
false
false
false
false
nathawes/swift
test/IRGen/protocol_resilience_descriptors.swift
5
6640
// RUN: %empty-directory(%t) // Resilient protocol definition // RUN: %target-swift-frontend -emit-ir -enable-library-evolution -module-name=resilient_protocol %S/../Inputs/resilient_protocol.swift | %FileCheck -DINT=i%target-ptrsize -check-prefix=CHECK-DEFINITION %s // Resilient protocol usage // RUN: %target-swift-frontend -emit-module -enable-library-evolution -emit-module-path=%t/resilient_protocol.swiftmodule -module-name=resilient_protocol %S/../Inputs/resilient_protocol.swift // RUN: %target-swift-frontend -I %t -emit-ir -enable-library-evolution %s | %FileCheck %s -DINT=i%target-ptrsize -check-prefix=CHECK-USAGE // ---------------------------------------------------------------------------- // Resilient protocol definition // ---------------------------------------------------------------------------- // CHECK: @"default assoc type x" = linkonce_odr hidden constant // CHECK-SAME: i8 -1, [1 x i8] c"x", i8 0 // CHECK: @"default assoc type \01____y2T118resilient_protocol29ProtocolWithAssocTypeDefaultsPQzG 18resilient_protocol7WrapperV" = // Protocol descriptor // CHECK-DEFINITION-LABEL: @"$s18resilient_protocol29ProtocolWithAssocTypeDefaultsMp" ={{( dllexport)?}}{{( protected)?}} constant // CHECK-DEFINITION-SAME: @"default associated conformance2T218resilient_protocol29ProtocolWithAssocTypeDefaultsP_AB014OtherResilientD0" // Associated type default + flags // CHECK-DEFINITION-SAME: getelementptr // CHECK-DEFINITION-SAME: @"default assoc type _____y2T1_____QzG 18resilient_protocol7WrapperV AA29ProtocolWithAssocTypeDefaultsP" // CHECK-DEFINITION-SAME: [[INT]] 1 // Protocol requirements base descriptor // CHECK-DEFINITION: @"$s18resilient_protocol21ResilientBaseProtocolTL" ={{( dllexport)?}}{{( protected)?}} alias %swift.protocol_requirement, getelementptr (%swift.protocol_requirement, %swift.protocol_requirement* getelementptr inbounds (<{ i32, i32, i32, i32, i32, i32, %swift.protocol_requirement }>, <{ i32, i32, i32, i32, i32, i32, %swift.protocol_requirement }>* @"$s18resilient_protocol21ResilientBaseProtocolMp", i32 0, i32 6), i32 -1) // Associated conformance descriptor for inherited protocol // CHECK-DEFINITION-LABEL: s18resilient_protocol24ResilientDerivedProtocolPAA0c4BaseE0Tb" ={{( dllexport)?}}{{( protected)?}} alias // Associated type and conformance // CHECK-DEFINITION: @"$s1T18resilient_protocol24ProtocolWithRequirementsPTl" ={{( dllexport)?}}{{( protected)?}} alias // CHECK-DEFINITION: @"$s18resilient_protocol29ProtocolWithAssocTypeDefaultsP2T2AC_AA014OtherResilientC0Tn" ={{( dllexport)?}}{{( protected)?}} alias // Default associated conformance witnesses // CHECK-DEFINITION-LABEL: define internal swiftcc i8** @"$s18resilient_protocol29ProtocolWithAssocTypeDefaultsP2T2AC_AA014OtherResilientC0TN" import resilient_protocol // ---------------------------------------------------------------------------- // Resilient witness tables // ---------------------------------------------------------------------------- // CHECK-USAGE-LABEL: $s31protocol_resilience_descriptors34ConformsToProtocolWithRequirementsVyxG010resilient_A00fgH0AAMc" = // CHECK-USAGE-SAME: {{got.|__imp_}}$s1T18resilient_protocol24ProtocolWithRequirementsPTl // CHECK-USAGE-SAME: @"symbolic x" public struct ConformsToProtocolWithRequirements<Element> : ProtocolWithRequirements { public typealias T = Element public func first() { } public func second() { } } public protocol P { } public struct ConditionallyConforms<Element> { } public struct Y { } // CHECK-USAGE-LABEL: @"$s31protocol_resilience_descriptors1YV010resilient_A022OtherResilientProtocolAAMc" = // -- flags: has generic witness table // CHECK-USAGE-SAME: i32 131072, // -- number of witness table entries // CHECK-USAGE-SAME: i16 0, // -- size of private area + 'requires instantiation' bit // CHECK-USAGE-SAME: i16 1, // -- instantiator function // CHECK-USAGE-SAME: i32 0, // -- private data area // CHECK-USAGE-SAME: "$s31protocol_resilience_descriptors1YV010resilient_A022OtherResilientProtocolAAMcMK" // -- // CHECK-USAGE-SAME: } extension Y: OtherResilientProtocol { } // CHECK-USAGE: @"$s31protocol_resilience_descriptors29ConformsWithAssocRequirementsV010resilient_A008ProtocoleF12TypeDefaultsAAMc" = // CHECK-USAGE-SAME: $s18resilient_protocol29ProtocolWithAssocTypeDefaultsP2T2AC_AA014OtherResilientC0Tn // CHECK-USAGE-SAME: @"associated conformance 31protocol_resilience_descriptors29ConformsWithAssocRequirementsV010resilient_A008ProtocoleF12TypeDefaultsAA2T2AdEP_AD014OtherResilientI0" public struct ConformsWithAssocRequirements : ProtocolWithAssocTypeDefaults { } // CHECK-USAGE: @"$s31protocol_resilience_descriptors21ConditionallyConformsVyxG010resilient_A024ProtocolWithRequirementsAaeFRzAA1YV1TRtzlMc" extension ConditionallyConforms: ProtocolWithRequirements where Element: ProtocolWithRequirements, Element.T == Y { public typealias T = Element.T public func first() { } public func second() { } } // CHECK-USAGE: @"$s31protocol_resilience_descriptors17ConformsToDerivedV010resilient_A009ResilientF8ProtocolAAMc" = // CHECK-SAME: @"associated conformance 31protocol_resilience_descriptors17ConformsToDerivedV010resilient_A009ResilientF8ProtocolAaD0h4BaseI0" public struct ConformsToDerived : ResilientDerivedProtocol { public func requirement() -> Int { return 0 } } // ---------------------------------------------------------------------------- // Resilient protocol usage // ---------------------------------------------------------------------------- // CHECK-USAGE: define{{( dllexport)?}}{{( protected)?}} swiftcc %swift.type* @"$s31protocol_resilience_descriptors17assocTypeMetadatay1TQzmxm010resilient_A024ProtocolWithRequirementsRzlF"(%swift.type* %0, %swift.type* [[PWD:%.*]], i8** [[WTABLE:%.*]]) public func assocTypeMetadata<PWR: ProtocolWithRequirements>(_: PWR.Type) -> PWR.T.Type { // CHECK-USAGE: call swiftcc %swift.metadata_response @swift_getAssociatedTypeWitness([[INT]] 0, i8** %PWR.ProtocolWithRequirements, %swift.type* %PWR, %swift.protocol_requirement* @"$s18resilient_protocol24ProtocolWithRequirementsTL", %swift.protocol_requirement* @"$s1T18resilient_protocol24ProtocolWithRequirementsPTl") return PWR.T.self } func useOtherResilientProtocol<T: OtherResilientProtocol>(_: T.Type) { } // CHECK-USAGE: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s31protocol_resilience_descriptors23extractAssocConformanceyyx010resilient_A0012ProtocolWithE12TypeDefaultsRzlF" public func extractAssocConformance<T: ProtocolWithAssocTypeDefaults>(_: T) { // CHECK-USAGE: swift_getAssociatedConformanceWitness useOtherResilientProtocol(T.T2.self) }
apache-2.0
76ccc75f39fe32e9345160064d098468
57.761062
444
0.731476
4.116553
false
false
false
false
JockerLUO/ShiftLibra
ShiftLibra/ShiftLibra/Class/Tools/SLNetworkingTool.swift
1
2564
// // SLNetworkingTool.swift // ShiftLibra // // Created by LUO on 2017/8/1. // Copyright © 2017年 JockerLuo. All rights reserved. // import UIKit import AFNetworking enum SLNteworkingToolType:String { case GET = "get" case POST = "post" } class SLNetworkingTool: AFHTTPSessionManager { static let shared = { () -> SLNetworkingTool in let shared = SLNetworkingTool() shared.responseSerializer.acceptableContentTypes?.insert("text/html") shared.responseSerializer.acceptableContentTypes?.insert("text/plain") return shared }() func requst(type: SLNteworkingToolType, URLString: String, parameters: Any?, success:@escaping (Any?)->(), failure:@escaping (Error)->()) -> () { if type == .GET { get(URLString, parameters: parameters, progress: nil, success: { (nil, Data) in success(Data) }, failure: { (nil, error) in failure(error) }) } else { post(URLString, parameters: parameters, progress: nil, success: { (nil, Data) in success(Data) }, failure: { (nil, error) in failure(error) }) } } func getQuery(success:@escaping (Any?)->(), failure:@escaping (Error)->()) -> () { let urlStr = API_QUERY_URL let parameters : [String : Any] = [ "key": APIKEY, ] self.requst(type: .GET, URLString: urlStr, parameters: parameters, success: success, failure: failure) } func getList(success:@escaping (Any?)->(), failure:@escaping (Error)->()) -> () { let urlStr = API_LIST_URL let parameters : [String : Any] = [ "key": APIKEY, ] self.requst(type: .GET, URLString: urlStr, parameters: parameters, success: success, failure: failure) } func getCurrency(from : String, to : String, success:@escaping (Any?)->(), failure:@escaping (Error)->()) -> () { let urlStr = API_CURRENCY_URL let parameters : [String : Any] = [ "key" : APIKEY, "from" : from, "to" : to ] self.requst(type: .GET, URLString: urlStr, parameters: parameters, success: success, failure: failure) } }
mit
fcc985727bb6db977babe49b8fb6d7a2
27.455556
149
0.504881
4.673358
false
false
false
false
frtlupsvn/Vietnam-To-Go
Pods/Former/Former/RowFormers/InlineDatePickerRowFormer.swift
1
4897
// // InlineDatePickerRowFormer.swift // Former-Demo // // Created by Ryo Aoyama on 8/1/15. // Copyright © 2015 Ryo Aoyama. All rights reserved. // import UIKit public protocol InlineDatePickerFormableRow: FormableRow { func formTitleLabel() -> UILabel? func formDisplayLabel() -> UILabel? } public final class InlineDatePickerRowFormer<T: UITableViewCell where T: InlineDatePickerFormableRow> : BaseRowFormer<T>, Formable, ConfigurableInlineForm { // MARK: Public public typealias InlineCellType = FormDatePickerCell public let inlineRowFormer: RowFormer override public var canBecomeEditing: Bool { return enabled } public var date: NSDate = NSDate() public var displayDisabledColor: UIColor? = .lightGrayColor() public var titleDisabledColor: UIColor? = .lightGrayColor() public var displayEditingColor: UIColor? public var titleEditingColor: UIColor? required public init( instantiateType: Former.InstantiateType = .Class, cellSetup: (T -> Void)?) { inlineRowFormer = DatePickerRowFormer<InlineCellType>(instantiateType: .Class) super.init(instantiateType: instantiateType, cellSetup: cellSetup) } public final func onDateChanged(handler: (NSDate -> Void)) -> Self { onDateChanged = handler return self } public final func displayTextFromDate(handler: (NSDate -> String)) -> Self { displayTextFromDate = handler return self } public override func update() { super.update() let titleLabel = cell.formTitleLabel() let displayLabel = cell.formDisplayLabel() displayLabel?.text = displayTextFromDate?(date) ?? "\(date)" if enabled { if isEditing { if titleColor == nil { titleColor = titleLabel?.textColor ?? .blackColor() } if displayTextColor == nil { displayTextColor = displayLabel?.textColor ?? .blackColor() } _ = titleEditingColor.map { titleLabel?.textColor = $0 } _ = displayEditingColor.map { displayLabel?.textColor = $0 } } else { _ = titleColor.map { titleLabel?.textColor = $0 } _ = displayTextColor.map { displayLabel?.textColor = $0 } titleColor = nil displayTextColor = nil } } else { if titleColor == nil { titleColor = titleLabel?.textColor ?? .blackColor() } if displayTextColor == nil { displayTextColor = displayLabel?.textColor ?? .blackColor() } _ = titleDisabledColor.map { titleLabel?.textColor = $0 } _ = displayDisabledColor.map { displayLabel?.textColor = $0 } } let inlineRowFormer = self.inlineRowFormer as! DatePickerRowFormer<InlineCellType> inlineRowFormer.configure { $0.onDateChanged(dateChanged) $0.enabled = enabled $0.date = date }.update() } public override func cellSelected(indexPath: NSIndexPath) { former?.deselect(true) } private func dateChanged(date: NSDate) { if enabled { self.date = date cell.formDisplayLabel()?.text = displayTextFromDate?(date) ?? "\(date)" onDateChanged?(date) } } public func editingDidBegin() { if enabled { let titleLabel = cell.formTitleLabel() let displayLabel = cell.formDisplayLabel() if titleColor == nil { titleColor = titleLabel?.textColor ?? .blackColor() } if displayTextColor == nil { displayTextColor = displayLabel?.textColor ?? .blackColor() } _ = titleEditingColor.map { titleLabel?.textColor = $0 } _ = displayEditingColor.map { displayLabel?.textColor = $0 } isEditing = true } } public func editingDidEnd() { let titleLabel = cell.formTitleLabel() let displayLabel = cell.formDisplayLabel() if enabled { _ = titleColor.map { titleLabel?.textColor = $0 } _ = displayTextColor.map { displayLabel?.textColor = $0 } titleColor = nil displayTextColor = nil } else { if titleColor == nil { titleColor = titleLabel?.textColor ?? .blackColor() } if displayTextColor == nil { displayTextColor = displayLabel?.textColor ?? .blackColor() } titleLabel?.textColor = titleDisabledColor displayLabel?.textColor = displayDisabledColor } isEditing = false } // MARK: Private private final var onDateChanged: (NSDate -> Void)? private final var displayTextFromDate: (NSDate -> String)? private final var titleColor: UIColor? private final var displayTextColor: UIColor? }
mit
0bd0c3713d24e9df6d8d768c92e24ae7
35.819549
106
0.610907
5.403974
false
false
false
false
runr/BreadMaker
BreadMaker.playground/Pages/13 - Autolyse.xcplaygroundpage/Contents.swift
2
1427
//: [Previous](@previous) import Interstellar struct Dough { let yield: Double var mixed = false var autolyseCompleted = false init(yield: Double) { self.yield = yield } mutating func mix() { self.mixed = true } mutating func autolyse() { self.autolyseCompleted = true } } enum BakeError: ErrorType { case MixingError case AutolyseError } struct BreadMaker { func makeBread(completion: Result<Dough> -> Void) -> Void { print("Making bread") let dough = Dough(yield: 1700) //: Then we add the rest of the steps Signal(dough) .flatMap(mix) .flatMap(autolyse) .subscribe { result in completion(result) } } private func mix(var dough: Dough) -> Result<Dough> { print("Mix") dough.mix() return dough.mixed ? .Success(dough) : .Error(BakeError.MixingError) } private func autolyse(var dough: Dough) -> Result<Dough> { print("Autolyse") dough.autolyse() return dough.autolyseCompleted ? .Success(dough) : .Error(BakeError.AutolyseError) } } BreadMaker().makeBread { result in switch result { case .Success: print("Got bread!") break case .Error: print("Error, no bread!!") } } //: [Next](@next)
mit
c4448841d1ca00e390680f67f29d8f11
19.098592
90
0.552908
4.100575
false
false
false
false
Thongpak21/NongBeer-MVVM-iOS-Demo
NongBeer/Classes/History/ViewController/HistoryDetailViewController.swift
1
1873
// // HistoryDetailViewController.swift // NongBeer // // Created by Thongpak on 4/11/2560 BE. // Copyright © 2560 Thongpak. All rights reserved. // import UIKit import IGListKit class HistoryDetailViewController: BaseViewController { lazy var adapter: IGListAdapter = { return IGListAdapter(updater: IGListAdapterUpdater(), viewController: self, workingRangeSize: 0) }() var viewModel: HistoryViewModel! var object = [HistoryModel]() let collectionView: IGListCollectionView = { let layout = UICollectionViewFlowLayout() layout.estimatedItemSize = CGSize(width: 100, height: 60) let collectionView = IGListCollectionView(frame: .zero, collectionViewLayout: layout) collectionView.backgroundColor = UIColor.clear return collectionView }() override func viewDidLoad() { super.viewDidLoad() viewModel = HistoryViewModel(delegate: self) setCollectionView() } func setCollectionView() { view.addSubview(collectionView) adapter.collectionView = collectionView adapter.dataSource = self } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() collectionView.frame = view.bounds } } extension HistoryDetailViewController: IGListAdapterDataSource { func objects(for listAdapter: IGListAdapter) -> [IGListDiffable] { return self.object } func listAdapter(_ listAdapter: IGListAdapter, sectionControllerFor object: Any) -> IGListSectionController { let sectionController = HistoryDetailSectionController() return sectionController } func emptyView(for listAdapter: IGListAdapter) -> UIView? { let nibView = Bundle.main.loadNibNamed("EmptyView", owner: nil, options: nil)!.first as! EmptyView return nibView } }
apache-2.0
7ff83a8ac1395de438a8cbfe73150607
31.842105
113
0.694444
5.554896
false
false
false
false
aikizoku/Library-iOS
Library/UITableViewCell+Separator.swift
1
2731
import Foundation import UIKit extension UITableViewCell { private var theSeparatorView: UIView? { get { return associatedObjects["theSeparatorView"] as? UIView } set { associatedObjects["theSeparatorView"] = newValue } } /** セパレータの色を設定する */ var theSeparatorColor: UIColor { get { if let theSeparatorColor = associatedObjects["theSeparatorColor"] { return theSeparatorColor as! UIColor } else { return UIColor.lightGray } } set { if let theSeparatorView = theSeparatorView { theSeparatorView.backgroundColor = newValue } associatedObjects["theSeparatorColor"] = newValue } } /** セパレータの高さを設定する */ var theSeparatorHeight: CGFloat { get { if let theSeparatorHeight = associatedObjects["theSeparatorHeight"] { return theSeparatorHeight as! CGFloat } else { return 0.5 } } set { if let theSeparatorView = theSeparatorView { theSeparatorView.height = newValue } associatedObjects["theSeparatorHeight"] = newValue } } /** セパレータを設定する */ var separator: Bool { get { if let separator = associatedObjects["separator"] { return separator as! Bool } else { return false } } set { associatedObjects["separator"] = newValue if newValue { if theSeparatorView == nil { let theSeparatorView: UIView = UIView() theSeparatorView.backgroundColor = theSeparatorColor theSeparatorView.translatesAutoresizingMaskIntoConstraints = false theSeparatorView.autoresizingMask = [.flexibleTopMargin, .flexibleWidth] theSeparatorView.frame = CGRect( x: 0, y: contentView.height - theSeparatorHeight, width: contentView.width, height: theSeparatorHeight) contentView.addSubview(theSeparatorView) self.theSeparatorView = theSeparatorView } } else { if theSeparatorView != nil { theSeparatorView!.removeFromSuperview() theSeparatorView = nil } } } } }
mit
d1dc7c2c6468210418904eec17bfae43
28.898876
92
0.50808
6.174014
false
false
false
false
huonw/swift
stdlib/public/SDK/Intents/INSetCarLockStatusIntent.swift
41
925
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_exported import Intents import Foundation #if os(iOS) || os(watchOS) @available(iOS 10.3, watchOS 3.2, *) extension INSetCarLockStatusIntent { @nonobjc public convenience init(locked: Bool?, carName: INSpeakableString?) { self.init(__locked:locked as NSNumber?, carName:carName) } @nonobjc public final var locked: Bool? { return __locked?.boolValue } } #endif
apache-2.0
f90f34d51da6a06c3e807a8952e58373
30.896552
80
0.582703
4.579208
false
false
false
false
mrlegowatch/RolePlayingCore
CharacterGenerator/CharacterGenerator/AppDelegate.swift
1
1594
// // AppDelegate.swift // CharacterGenerator // // Created by Brian Arnold on 7/4/17. // Copyright © 2017 Brian Arnold. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { let splitViewController = window!.rootViewController as! UISplitViewController let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem splitViewController.delegate = self return true } // MARK: - Split view func splitViewController(_ splitViewController: UISplitViewController, collapseSecondary secondaryViewController:UIViewController, onto primaryViewController:UIViewController) -> Bool { guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false } guard let topAsDetailController = secondaryAsNavController.topViewController as? PlayerDetailViewController else { return false } if topAsDetailController.player == nil { // Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded. return true } return false } }
mit
b5403f0347e956aa2644f1edf4597c47
40.921053
189
0.762712
6.528689
false
false
false
false
mathiasquintero/Sweeft
Sources/Sweeft/Promises/Subclasses/FailableBulkPromise.swift
1
1619
// // TryBulkPromise.swift // Sweeft // // Created by Mathias Quintero on 6/19/17. // Copyright © 2017 Mathias Quintero. All rights reserved. // public class FailableBulkPromise<R, E: Error>: SelfSettingPromise<R, E> { public typealias Factory = () -> Promise<R, E> private let factories: [Factory] private var lastError: E? private var current = 0 public convenience init<V>(inputs: [V], transform: @escaping (V) -> Promise<R, E>) { self.init(factories: inputs => { input in { transform(input) } }) } public init(factories: [Factory]) { self.factories = factories super.init() doit() } func doit() { guard current < factories.count else { if let lastError = lastError { setter.error(with: lastError) } return } let promise = factories[current]() promise.onSuccess(call: self.handleValue).onError(call: self.handleError) } func handleValue(with output: R) { setter.success(with: output) } func handleError(with error: E) { lastError = error current += 1 doit() } public func `continue`() -> FailableBulkPromise<R, E> { let factories = self.factories.array(from: current) return FailableBulkPromise(factories: factories) } } public func ??<V, E>(_ lhs: @escaping @autoclosure () -> Promise<V, E>, _ rhs: @escaping @autoclosure () -> Promise<V, E>) -> FailableBulkPromise<V, E> { return FailableBulkPromise(factories: [lhs, rhs]) }
mit
6b7ec0db39a9cefcde1a1b0a454c134a
26.896552
153
0.587145
4.065327
false
false
false
false
seanwoodward/IBAnimatable
IBAnimatable/ExplodeAnimator.swift
1
4274
// // Created by Tom Baranes on 03/04/16. // Copyright © 2016 IBAnimatable. All rights reserved. // import UIKit public class ExplodeAnimator: NSObject, AnimatedTransitioning { // MARK: - AnimatorProtocol public var transitionAnimationType: TransitionAnimationType public var transitionDuration: Duration = defaultTransitionDuration public var reverseAnimationType: TransitionAnimationType? public var interactiveGestureType: InteractiveGestureType? // MARK: - private private var xFactor: CGFloat = 10.0 private var minAngle: CGFloat = -10.0 private var maxAngle: CGFloat = 10.0 public init(params: [String], transitionDuration: Duration) { self.transitionDuration = transitionDuration self.transitionAnimationType = .Explode(params: params) self.reverseAnimationType = .Explode(params: params) if params.count == 3 { if let unwrappedXFactor = Double(params[0]), unwrappedMinAngle = Double(params[1]), unwrappedMaxAngle = Double(params[2]) { self.xFactor = CGFloat(unwrappedXFactor) self.minAngle = CGFloat(unwrappedMinAngle) self.maxAngle = CGFloat(unwrappedMaxAngle) } } super.init() } } extension ExplodeAnimator: UIViewControllerAnimatedTransitioning { public func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return retrieveTransitionDuration(transitionContext) } public func animateTransition(transitionContext: UIViewControllerContextTransitioning) { let (tempfromView, tempToView, tempContainerView) = retrieveViews(transitionContext) guard let fromView = tempfromView, toView = tempToView, containerView = tempContainerView else { transitionContext.completeTransition(true) return } containerView.insertSubview(toView, atIndex: 0) let snapshots = createSnapshots(toView: toView, fromView: fromView, containerView: containerView) containerView.sendSubviewToBack(fromView) animateSnapshotsExplode(snapshots) { if transitionContext.transitionWasCancelled() { containerView.bringSubviewToFront(fromView) } transitionContext.completeTransition(!transitionContext.transitionWasCancelled()) } } } private extension ExplodeAnimator { func createSnapshots(toView toView: UIView, fromView: UIView, containerView: UIView) -> [UIView] { let size = toView.frame.size var snapshots = [UIView]() let yFactor = xFactor * size.height / size.width let fromViewSnapshot = fromView.snapshotViewAfterScreenUpdates(false) for x in 0.0.stride(to: Double(size.width), by: Double(size.width / xFactor)) { for y in 0.0.stride(to: Double(size.height), by: Double(size.width / yFactor)) { let snapshotRegion = CGRect(x: CGFloat(x), y: CGFloat(y), width: size.width / xFactor, height: size.height / yFactor) let snapshot = fromViewSnapshot.resizableSnapshotViewFromRect(snapshotRegion, afterScreenUpdates: false, withCapInsets: UIEdgeInsetsZero) snapshot.frame = snapshotRegion containerView.addSubview(snapshot) snapshots.append(snapshot) } } return snapshots } func animateSnapshotsExplode(snapshots: [UIView], completion: AnimatableCompletion) { UIView.animateWithDuration(transitionDuration, animations: { snapshots.forEach { let xOffset = self.randomFloatBetween(lower: -100.0, upper: 100.0) let yOffset = self.randomFloatBetween(lower: -100.0, upper: 100.0) let angle = self.randomFloatBetween(lower: self.minAngle, upper: self.maxAngle) let translateTransform = CGAffineTransformMakeTranslation($0.frame.origin.x - xOffset, $0.frame.origin.y - yOffset) let angleTransform = CGAffineTransformRotate(translateTransform, angle) let scaleTransform = CGAffineTransformScale(angleTransform, 0.01, 0.01) $0.transform = scaleTransform $0.alpha = 0.0 } }, completion: { _ in snapshots.forEach { $0.removeFromSuperview() } completion() }) } func randomFloatBetween(lower lower: CGFloat, upper: CGFloat) -> CGFloat { return CGFloat(arc4random_uniform(UInt32(upper - lower))) + lower } }
mit
5530be947deb7b8235061ccaa97a72f3
37.845455
145
0.719167
4.85017
false
false
false
false
jpsim/CardsAgainst
CardsAgainst/Models/Card.swift
1
1424
// // Card.swift // CardsAgainst // // Created by JP Simard on 11/2/14. // Copyright (c) 2014 JP Simard. All rights reserved. // import Foundation let blackCardPlaceholder = "________" enum CardType: String { case white = "A", black = "Q" } struct Card: MPCSerializable { let content: String let type: CardType let expansion: String var mpcSerialized: Data { let dictionary = ["content": content, "type": type.rawValue, "expansion": expansion] return NSKeyedArchiver.archivedData(withRootObject: dictionary) } init(content: String, type: CardType, expansion: String) { self.content = content self.type = type self.expansion = expansion } init(mpcSerialized: Data) { let dict = NSKeyedUnarchiver.unarchiveObject(with: mpcSerialized) as! [String: String] content = dict["content"]! type = CardType(rawValue: dict["type"]!)! expansion = dict["expansion"]! } } struct CardArray: MPCSerializable { let array: [Card] var mpcSerialized: Data { return NSKeyedArchiver.archivedData(withRootObject: array.map { $0.mpcSerialized }) } init(array: [Card]) { self.array = array } init(mpcSerialized: Data) { let dataArray = NSKeyedUnarchiver.unarchiveObject(with: mpcSerialized) as! [Data] array = dataArray.map { return Card(mpcSerialized: $0) } } }
mit
18c21d4d11b8b50ae3d4354da5304eeb
24.428571
94
0.639747
4.05698
false
false
false
false
KimBin/DTTableViewManager
Example/XCTests/TableViewController+UnitTests.swift
1
1627
// // TableViewController+UnitTests.swift // DTTableViewManager // // Created by Denys Telezhkin on 14.07.15. // Copyright (c) 2015 Denys Telezhkin. All rights reserved. // import Foundation import DTTableViewManager import UIKit protocol ModelRetrievable { var model : Any! { get } } func recursiveForceUnwrap<T>(any: T) -> T { let mirror = _reflect(any) if mirror.disposition != .Optional { return any } let (_,some) = mirror[0] return recursiveForceUnwrap(some.value as! T) } extension DTTestTableViewController { func verifyItem<T:Equatable>(item: T, atIndexPath indexPath: NSIndexPath) -> Bool { let itemTable = (self.manager.tableView(self.tableView, cellForRowAtIndexPath: indexPath) as! ModelRetrievable).model as! T let itemDatasource = recursiveForceUnwrap(self.manager.storage.objectAtIndexPath(indexPath)!) as! T if !(item == itemDatasource) { return false } if !(item == itemTable) { return false } return true } func verifySection(section: [Int], withSectionNumber sectionNumber: Int) -> Bool { for itemNumber in 0..<section.count { if !(self.verifyItem(section[itemNumber], atIndexPath: NSIndexPath(forItem: itemNumber, inSection: sectionNumber))) { return false } } if self.manager.tableView(self.tableView, numberOfRowsInSection: sectionNumber) == section.count { return true } return false } }
mit
b1745c0a1c90cfaac7ec3a92c467ca1d
24.4375
131
0.615857
4.519444
false
false
false
false
eurofurence/ef-app_ios
Packages/EurofurenceApplication/Tests/EurofurenceApplicationTests/Test Doubles/FakeAuthenticationService.swift
1
2280
import EurofurenceModel class FakeAuthenticationService: AuthenticationService { enum AuthState { case loggedIn(User) case loggedOut } fileprivate(set) var authState: AuthState class func loggedInService(_ user: User = .random) -> FakeAuthenticationService { return FakeAuthenticationService(authState: .loggedIn(user)) } class func loggedOutService() -> FakeAuthenticationService { return FakeAuthenticationService(authState: .loggedOut) } init(authState: AuthState) { self.authState = authState } fileprivate var observers = [AuthenticationStateObserver]() func add(_ observer: AuthenticationStateObserver) { observers.append(observer) switch authState { case .loggedIn(let user): observer.userAuthenticated(user) case .loggedOut: observer.userUnauthenticated() } } private(set) var authStateDeterminedCount = 0 func determineAuthState(completionHandler: @escaping (AuthState) -> Void) { completionHandler(authState) authStateDeterminedCount += 1 } private(set) var capturedRequest: LoginArguments? fileprivate var capturedCompletionHandler: ((LoginResult) -> Void)? func login(_ arguments: LoginArguments, completionHandler: @escaping (LoginResult) -> Void) { capturedRequest = arguments capturedCompletionHandler = completionHandler } private(set) var wasToldToLogout = false private(set) var capturedLogoutHandler: ((LogoutResult) -> Void)? func logout(completionHandler: @escaping (LogoutResult) -> Void) { wasToldToLogout = true capturedLogoutHandler = completionHandler } } extension FakeAuthenticationService { func fulfillRequest() { capturedCompletionHandler?(.success(.random)) } func failRequest() { capturedCompletionHandler?(.failure) } func notifyObserversUserDidLogin(_ user: User = User(registrationNumber: 42, username: "")) { authState = .loggedIn(user) observers.forEach { $0.userAuthenticated(user) } } func notifyObserversUserDidLogout() { authState = .loggedOut observers.forEach { $0.userUnauthenticated() } } }
mit
dc54ef0877a0e36b1c068fa6135cdf70
27.860759
97
0.68114
5.217391
false
false
false
false
NoryCao/zhuishushenqi
zhuishushenqi/TXTReader/Reader/TXTReaderViewController.swift
1
12280
// // TXTReaderViewController.swift // TXTReader // // Created by Nory Chao on 16/11/24. // Copyright © 2016年 QS. All rights reserved. // import UIKit class TXTReaderViewController: UIViewController { var viewModel = ZSReaderViewModel() var isToolBarHidden:Bool = true var sideNum = 1 var curlPageStyle:QSTextCurlPageStyle = .forwards // 拟真阅读 var pageController:UIPageViewController? // 当前阅读视图控制器,处于动画中时,则表示要切换到的控制器,非动画中则表示当前的阅读控制器 var currentReaderVC:PageViewController! var window:UIWindow? var callback:QSTextCallBack? var style:ZSReaderAnimationStyle = .horMove var viewControllers:[PageViewController] = [] var record:QSRecord = QSRecord() override func viewDidLoad() { super.viewDidLoad() self.navigationController?.isNavigationBarHidden = true // 第一次进入没有record,初始化一个record setupRecord() // 初始化根控制器 createRootController() // 初始化请求 initial() // 变更书籍的更新信息 viewModel.book?.isUpdated = false if let book = viewModel.book { BookManager.shared.modifyBookshelf(book: book) } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) setNeedsStatusBarAppearanceUpdate() // 保存浏览记录 if let book = viewModel.book { BookManager.shared.addReadHistory(book: book) } } //MARK: - initial action private func createRootController(){ let pageStyle = QSReaderSetting.shared.pageStyle switch pageStyle { case .horMove: guard let _ = pageController else { setupPageController() return } view.addSubview(pageController!.view) addChild(pageController!) pageController?.setViewControllers([currentReaderVC], direction: .forward, animated: true, completion: nil) if let model = viewModel.book?.record?.chapterModel { if let chapterIndex = viewModel.book?.record?.chapter { if chapterIndex < model.pages.count { currentReaderVC.page = model.pages[chapterIndex] } } } break case .none: break case .curlPage: break default: break } } private func setupPageController(){ var transitionStyle:UIPageViewController.TransitionStyle = .pageCurl if style == .horMove { transitionStyle = .scroll } pageController = UIPageViewController(transitionStyle: transitionStyle, navigationOrientation: .horizontal, options: nil) pageController?.dataSource = self pageController?.delegate = self pageController?.isDoubleSided = (style == .horMove ? false:true) view.addSubview(pageController!.view) addChild(pageController!) pageController?.setViewControllers([initialPageViewController()], direction: .forward, animated: true, completion: nil) } func initialPageViewController()->PageViewController{ let pageVC = PageViewController() if let record = viewModel.book?.record { if let chapterModel = record.chapterModel { let pageIndex = record.page if pageIndex < chapterModel.pages.count { pageVC.page = chapterModel.pages[pageIndex] } } else if (viewModel.book?.book.localChapters.count)! > 0 { if let chapters = viewModel.book?.book.localChapters { let chapterIndex = record.chapter let pageIndex = record.page if chapterIndex < chapters.count { let chapterModel = chapters[chapterIndex] if pageIndex < chapterModel.pages.count { pageVC.page = chapterModel.pages[pageIndex] } } } } else { viewModel.fetchInitialChapter { (page) in pageVC.page = page } } } currentReaderVC = pageVC return pageVC } func initial(){ //如果是本地书籍,则不清求 if viewModel.exsitLocal() { return } viewModel.fetchAllResource { resources in self.viewModel.fetchAllChapters({ (chapters) in self.viewModel.fetchInitialChapter({ (page) in self.currentReaderVC.page = page }) }) } } func setupRecord(){ // 第一次进入没有record,初始化一个record if let book = viewModel.book { record.bookId = book._id if book.record == nil { book.record = record } } } } extension TXTReaderViewController:UIPageViewControllerDataSource,UIPageViewControllerDelegate{ //MARK: - UIPageViewControllerDataSource,UIPageViewControllerDelegate public func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController?{ //UIPageViewController的 isDoubleSided 设置为true后,会调用两次代理方法,第一次为背面的viewcontroller,第二次为正面 print("before") sideNum -= 1 curlPageStyle = .backwards let curPageViewController = viewController as! PageViewController var pageVC:PageViewController? // if viewControllers.count > 1 { // if let reusePageVC = viewControllers.first { // pageVC = reusePageVC // viewControllers.remove(at: 0) // } // } else { pageVC = PageViewController() // } let existLast = viewModel.hm_existLast(page: curPageViewController.page) if existLast { currentReaderVC = pageVC viewModel.fetchBackwardPage(page: curPageViewController.page) { (page) in pageVC?.page = page } return pageVC } return nil } func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController?{ print("after") curlPageStyle = .forwards sideNum += 1 let curPageViewController = viewController as! PageViewController var pageVC:PageViewController? if viewControllers.count > 1 { if let reusePageVC = viewControllers.first { pageVC = reusePageVC viewControllers.remove(at: 0) } } else { pageVC = PageViewController() } let existNext = viewModel.hm_existNext(page: curPageViewController.page) if existNext { pageVC?.view.alpha = 1.0 viewModel.fetchForwardPage(page: curPageViewController.page) { (page) in pageVC?.page = page } currentReaderVC = pageVC return pageVC } return nil } func pageViewController(_ pageViewController: UIPageViewController, willTransitionTo pendingViewControllers: [UIViewController]){ // currentReaderVC.qs_removeObserver() } func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool){ let preVC = previousViewControllers.first as! PageViewController if !completed { currentReaderVC = previousViewControllers.first as! PageViewController } else { // 更新阅读记录 if curlPageStyle == .forwards { viewModel.updateForwardRecord(page: preVC.page) } else if curlPageStyle == .backwards { viewModel.updateBackwardRecord(page: preVC.page) } // pageVC的重复利用 if !viewControllers.contains(preVC) { viewControllers.append(preVC) } } QSLog("ZSReaderChapter:\(viewModel.book?.record?.chapter ?? 0) \npage:\(viewModel.book?.record?.page ?? 0)") // preVC.qs_removeObserver() } // reader style change func readBg(type: Reader) { self.currentReaderVC?.bgView.image = AppStyle.shared.reader.backgroundImage } func fontChange(action:ToolBarFontChangeAction){ viewModel.fontChange(action: action) { (page) in self.currentReaderVC.page = page } } func cacheAll() { let root:RootViewController = SideViewController.shared.contentViewController as! RootViewController let type = root.reachability?.networkType //移动网络,进行提示 if type == .WWAN2G || type == .WWAN3G || type == .WWAN4G { //提示当前正在使用移动网络,是否继续 alert(with: "提示", message: "当前正在使用移动网络,是否继续", okTitle: "继续", cancelTitle: "取消", okAction: { (action) in // self.presenter?.didClickCache() }, cancelAction: { (action) in }) }else { // presenter?.didClickCache() } } func brightnessChange(value: CGFloat) { // 修改page的background与foreground } func toolbar(toolbar:ToolBar, clickMoreSetting:UIView) { let moreSettingVC = QSMoreSettingController() let nav = UINavigationController(rootViewController: moreSettingVC) present(nav, animated: true, completion: nil) } func changeSourceClicked() { let sourceVC = ChangeSourceViewController() sourceVC.viewModel = self.viewModel sourceVC.selectAction = { (index:Int,sources:[ResourceModel]?) in self.viewModel = sourceVC.viewModel self.viewModel.cachedChapter.removeAll() self.viewModel.fetchAllChapters({ (info) in self.viewModel.fetchCurrentPage({ (page) in self.currentReaderVC.page = page }) }) } let nav = UINavigationController(rootViewController: sourceVC) present(nav, animated: true) { } } @objc func updateStatusBarStyle(){ window = UIWindow(frame: CGRect(x: 0, y: UIScreen.main.bounds.size.height - 20, width: UIScreen.main.bounds.size.width, height: 20)) window?.windowLevel = UIWindow.Level.statusBar window?.makeKeyAndVisible() window?.backgroundColor = UIColor.red setNeedsStatusBarAppearanceUpdate() } //MARK: - CategoryDelegate func categoryDidSelectAtIndex(index:Int){ curlPageStyle = .none viewModel.book?.record?.chapter = index viewModel.book?.record?.page = 0 viewModel.book?.record?.chapterModel = nil if let link = viewModel.book?.chaptersInfo?[index].link { if let chapterModel = viewModel.cachedChapter[link] { viewModel.book?.record?.chapterModel = chapterModel } } let pageVC = PageViewController() if let model = viewModel.book?.record?.chapterModel { pageVC.page = model.pages[0] } else { viewModel.fetchCurrentPage { (page) in pageVC.page = page } } let backgroundVC = QSReaderBackgroundViewController() backgroundVC.setBackground(viewController: pageVC) pageController?.setViewControllers([pageVC], direction: .forward, animated: true) { (finished) in } currentReaderVC = pageVC } }
mit
169cbb5532120901b174ac37f374be29
34.121302
189
0.587903
5.243375
false
false
false
false
jaksatomovic/Snapgram
Snapgram/commentVC.swift
1
26683
// // commentVC.swift // Snapgram // // Created by Jaksa Tomovic on 28/11/16. // Copyright © 2016 Jaksa Tomovic. All rights reserved. // import UIKit import Parse var commentuuid = [String]() var commentowner = [String]() class commentVC: UIViewController, UITextViewDelegate, UITableViewDelegate, UITableViewDataSource { // UI objects @IBOutlet weak var tableView: UITableView! @IBOutlet weak var commentTxt: UITextView! @IBOutlet weak var sendBtn: UIButton! var refresher = UIRefreshControl() // values for reseting UI to default var tableViewHeight : CGFloat = 0 var commentY : CGFloat = 0 var commentHeight : CGFloat = 0 // arrays to hold server data var usernameArray = [String]() var avaArray = [PFFile]() var commentArray = [String]() var dateArray = [Date?]() // variable to hold keybarod frame var keyboard = CGRect() // page size var page : Int32 = 15 // default func override func viewDidLoad() { super.viewDidLoad() // title at the top self.navigationItem.title = "COMMENTS" // new back button self.navigationItem.hidesBackButton = true let backBtn = UIBarButtonItem(image: UIImage(named: "back"), style: .plain, target: self, action: #selector(commentVC.back(_:))) self.navigationItem.leftBarButtonItem = backBtn // swipe to go back let backSwipe = UISwipeGestureRecognizer(target: self, action: #selector(commentVC.back(_:))) backSwipe.direction = UISwipeGestureRecognizerDirection.right self.view.addGestureRecognizer(backSwipe) // catch notification if the keyboard is shown or hidden NotificationCenter.default.addObserver(self, selector: #selector(commentVC.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(commentVC.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil) // disable button from the beginning sendBtn.isEnabled = false // call functions alignment() loadComments() } // preload func override func viewWillAppear(_ animated: Bool) { // hide bottom bar self.tabBarController?.tabBar.isHidden = true // hide custom tabbar button tabBarPostButton.isHidden = true // call keyboard commentTxt.becomeFirstResponder() } // postload func - launches when we about to live current VC override func viewWillDisappear(_ animated: Bool) { // unhide tabbar self.tabBarController?.tabBar.isHidden = false // unhide custom tabbar button tabBarPostButton.isHidden = false } // func loading when keyboard is shown func keyboardWillShow(notification: NSNotification) { // defnine keyboard frame size keyboard = ((notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue)! // move UI up UIView.animate (withDuration: 0.4) { () -> Void in self.tableView.frame.size.height = self.tableViewHeight - self.keyboard.height - self.commentTxt.frame.size.height + self.commentHeight self.commentTxt.frame.origin.y = self.commentY - self.keyboard.height - self.commentTxt.frame.size.height + self.commentHeight self.sendBtn.frame.origin.y = self.commentTxt.frame.origin.y } } // func loading when keyboard is hidden func keyboardWillHide(_ notification : Notification) { // move UI down UIView.animate(withDuration: 0.4, animations: { () -> Void in self.tableView.frame.size.height = self.tableViewHeight self.commentTxt.frame.origin.y = self.commentY self.sendBtn.frame.origin.y = self.commentY }) } // alignment function func alignment() { // alignnment let width = self.view.frame.size.width let height = self.view.frame.size.height tableView.frame = CGRect(x: 0, y: 0, width: width, height: height / 1.096 - self.navigationController!.navigationBar.frame.size.height - 20) tableView.estimatedRowHeight = width / 5.333 tableView.rowHeight = UITableViewAutomaticDimension commentTxt.frame = CGRect(x: 10, y: tableView.frame.size.height + height / 56.8, width: width / 1.306, height: 33) commentTxt.layer.cornerRadius = commentTxt.frame.size.width / 50 sendBtn.frame = CGRect(x: commentTxt.frame.origin.x + commentTxt.frame.size.width + width / 32, y: commentTxt.frame.origin.y, width: width - (commentTxt.frame.origin.x + commentTxt.frame.size.width) - (width / 32) * 2, height: commentTxt.frame.size.height) // delegates commentTxt.delegate = self tableView.delegate = self tableView.dataSource = self // assign reseting values tableViewHeight = tableView.frame.size.height commentHeight = commentTxt.frame.size.height commentY = commentTxt.frame.origin.y } // while writing something func textViewDidChange(_ textView: UITextView) { // disable button if entered no text let spacing = CharacterSet.whitespacesAndNewlines if !commentTxt.text.trimmingCharacters(in: spacing).isEmpty { sendBtn.isEnabled = true } else { sendBtn.isEnabled = false } // + paragraph if textView.contentSize.height > textView.frame.size.height && textView.frame.height < 130 { // find difference to add let difference = textView.contentSize.height - textView.frame.size.height // redefine frame of commentTxt textView.frame.origin.y = textView.frame.origin.y - difference textView.frame.size.height = textView.contentSize.height // move up tableView if textView.contentSize.height + keyboard.height + commentY >= tableView.frame.size.height { tableView.frame.size.height = tableView.frame.size.height - difference } } // - paragraph else if textView.contentSize.height < textView.frame.size.height { // find difference to deduct let difference = textView.frame.size.height - textView.contentSize.height // redefine frame of commentTxt textView.frame.origin.y = textView.frame.origin.y + difference textView.frame.size.height = textView.contentSize.height // move donw tableViwe if textView.contentSize.height + keyboard.height + commentY > tableView.frame.size.height { tableView.frame.size.height = tableView.frame.size.height + difference } } } // load comments function func loadComments() { // STEP 1. Count total comments in order to skip all except (page size = 15) let countQuery = PFQuery(className: "comments") countQuery.whereKey("to", equalTo: commentuuid.last!) countQuery.countObjectsInBackground (block: { (count, error) -> Void in // if comments on the server for current post are more than (page size 15), implement pull to refresh func if self.page < count { self.refresher.addTarget(self, action: #selector(commentVC.loadMore), for: UIControlEvents.valueChanged) self.tableView.addSubview(self.refresher) } // STEP 2. Request last (page size 15) comments let query = PFQuery(className: "comments") query.whereKey("to", equalTo: commentuuid.last!) query.skip = count - self.page query.addAscendingOrder("createdAt") query.findObjectsInBackground(block: { (objects, error) -> Void in if error == nil { // clean up self.usernameArray.removeAll(keepingCapacity: false) self.avaArray.removeAll(keepingCapacity: false) self.commentArray.removeAll(keepingCapacity: false) self.dateArray.removeAll(keepingCapacity: false) // find related objects for object in objects! { self.usernameArray.append(object.object(forKey: "username") as! String) self.avaArray.append(object.object(forKey: "ava") as! PFFile) self.commentArray.append(object.object(forKey: "comment") as! String) self.dateArray.append(object.createdAt) self.tableView.reloadData() // scroll to bottom self.tableView.scrollToRow(at: IndexPath(row: self.commentArray.count - 1, section: 0), at: UITableViewScrollPosition.bottom, animated: false) } } else { print(error?.localizedDescription) } }) }) } // pagination func loadMore() { // STEP 1. Count total comments in order to skip all except (page size = 15) let countQuery = PFQuery(className: "comments") countQuery.whereKey("to", equalTo: commentuuid.last!) countQuery.countObjectsInBackground (block: { (count, error) -> Void in // self refresher self.refresher.endRefreshing() // remove refresher if loaded all comments if self.page >= count { self.refresher.removeFromSuperview() } // STEP 2. Load more comments if self.page < count { // increase page to load 30 as first paging self.page = self.page + 15 // request existing comments from the server let query = PFQuery(className: "comments") query.whereKey("to", equalTo: commentuuid.last!) query.skip = count - self.page query.addAscendingOrder("createdAt") query.findObjectsInBackground(block: { (objects, error) -> Void in if error == nil { // clean up self.usernameArray.removeAll(keepingCapacity: false) self.avaArray.removeAll(keepingCapacity: false) self.commentArray.removeAll(keepingCapacity: false) self.dateArray.removeAll(keepingCapacity: false) // find related objects for object in objects! { self.usernameArray.append(object.object(forKey: "username") as! String) self.avaArray.append(object.object(forKey: "ava") as! PFFile) self.commentArray.append(object.object(forKey: "comment") as! String) self.dateArray.append(object.createdAt) self.tableView.reloadData() } } else { print(error?.localizedDescription) } }) } }) } // clicked send button @IBAction func sendBtn_click(_ sender: AnyObject) { // STEP 1. Add row in tableView usernameArray.append(PFUser.current()!.username!) avaArray.append(PFUser.current()?.object(forKey: "ava") as! PFFile) dateArray.append(Date()) commentArray.append(commentTxt.text.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)) tableView.reloadData() // STEP 2. Send comment to server let commentObj = PFObject(className: "comments") commentObj["to"] = commentuuid.last commentObj["username"] = PFUser.current()?.username commentObj["ava"] = PFUser.current()?.value(forKey: "ava") commentObj["comment"] = commentTxt.text.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) commentObj.saveEventually() // STEP 3. Send #hashtag to server let words:[String] = commentTxt.text!.components(separatedBy: CharacterSet.whitespacesAndNewlines) // define taged word for var word in words { // save #hasthag in server if word.hasPrefix("#") { // cut symbold word = word.trimmingCharacters(in: CharacterSet.punctuationCharacters) word = word.trimmingCharacters(in: CharacterSet.symbols) let hashtagObj = PFObject(className: "hashtags") hashtagObj["to"] = commentuuid.last hashtagObj["by"] = PFUser.current()?.username hashtagObj["hashtag"] = word.lowercased() hashtagObj["comment"] = commentTxt.text hashtagObj.saveInBackground(block: { (success, error) -> Void in if success { print("hashtag \(word) is created") } else { print(error!.localizedDescription) } }) } } // STEP 4. Send notification as @mention var mentionCreated = Bool() for var word in words { // check @mentions for user if word.hasPrefix("@") { // cut symbols word = word.trimmingCharacters(in: CharacterSet.punctuationCharacters) word = word.trimmingCharacters(in: CharacterSet.symbols) let newsObj = PFObject(className: "news") newsObj["by"] = PFUser.current()?.username newsObj["ava"] = PFUser.current()?.object(forKey: "ava") as! PFFile newsObj["to"] = word newsObj["owner"] = commentowner.last newsObj["uuid"] = commentuuid.last newsObj["type"] = "mention" newsObj["checked"] = "no" newsObj.saveEventually() mentionCreated = true } } // STEP 5. Send notification as comment if commentowner.last != PFUser.current()?.username && mentionCreated == false { let newsObj = PFObject(className: "news") newsObj["by"] = PFUser.current()?.username newsObj["ava"] = PFUser.current()?.object(forKey: "ava") as! PFFile newsObj["to"] = commentowner.last newsObj["owner"] = commentowner.last newsObj["uuid"] = commentuuid.last newsObj["type"] = "comment" newsObj["checked"] = "no" newsObj.saveEventually() } // scroll to bottom self.tableView.scrollToRow(at: IndexPath(item: commentArray.count - 1, section: 0), at: UITableViewScrollPosition.bottom, animated: false) // STAEP 6. Reset UI sendBtn.isEnabled = false commentTxt.text = "" commentTxt.frame.size.height = commentHeight commentTxt.frame.origin.y = sendBtn.frame.origin.y tableView.frame.size.height = self.tableViewHeight - self.keyboard.height - self.commentTxt.frame.size.height + self.commentHeight } // TABLEVIEW // cell numb func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return commentArray.count } // cell height func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat { return UITableViewAutomaticDimension } // cell config func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // declare cell let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! commentCell cell.usernameBtn.setTitle(usernameArray[(indexPath as NSIndexPath).row], for: UIControlState()) cell.usernameBtn.sizeToFit() cell.commentLbl.text = commentArray[(indexPath as NSIndexPath).row] avaArray[(indexPath as NSIndexPath).row].getDataInBackground { (data, error) -> Void in cell.avaImg.image = UIImage(data: data!) } // calculate date let from = dateArray[(indexPath as NSIndexPath).row] let now = Date() let components : NSCalendar.Unit = [.second, .minute, .hour, .day, .weekOfMonth] let difference = (Calendar.current as NSCalendar).components(components, from: from!, to: now, options: []) if difference.second! <= 0 { cell.dateLbl.text = "now" } if difference.second! > 0 && difference.minute! == 0 { cell.dateLbl.text = "\(difference.second)s." } if difference.minute! > 0 && difference.hour! == 0 { cell.dateLbl.text = "\(difference.minute)m." } if difference.hour! > 0 && difference.day! == 0 { cell.dateLbl.text = "\(difference.hour)h." } if difference.day! > 0 && difference.weekOfMonth! == 0 { cell.dateLbl.text = "\(difference.day)d." } if difference.weekOfMonth! > 0 { cell.dateLbl.text = "\(difference.weekOfMonth)w." } // @mention is tapped cell.commentLbl.userHandleLinkTapHandler = { label, handle, rang in var mention = handle mention = String(mention.characters.dropFirst()) // if tapped on @currentUser go home, else go guest if mention.lowercased() == PFUser.current()?.username { let home = self.storyboard?.instantiateViewController(withIdentifier: "homeVC") as! homeVC self.navigationController?.pushViewController(home, animated: true) } else { guestname.append(mention.lowercased()) let guest = self.storyboard?.instantiateViewController(withIdentifier: "guestVC") as! guestVC self.navigationController?.pushViewController(guest, animated: true) } } // #hashtag is tapped cell.commentLbl.hashtagLinkTapHandler = { label, handle, range in var mention = handle mention = String(mention.characters.dropFirst()) hashtag.append(mention.lowercased()) let hashvc = self.storyboard?.instantiateViewController(withIdentifier: "hashtagsVC") as! hashtagsVC self.navigationController?.pushViewController(hashvc, animated: true) } // assign indexes of buttons cell.usernameBtn.layer.setValue(indexPath, forKey: "index") return cell } // clicked username button @IBAction func usernameBtn_click(_ sender: AnyObject) { // call index of current button let i = sender.layer.value(forKey: "index") as! IndexPath // call cell to call further cell data let cell = tableView.cellForRow(at: i) as! commentCell // if user tapped on his username go home, else go guest if cell.usernameBtn.titleLabel?.text == PFUser.current()?.username { let home = self.storyboard?.instantiateViewController(withIdentifier: "homeVC") as! homeVC self.navigationController?.pushViewController(home, animated: true) } else { guestname.append(cell.usernameBtn.titleLabel!.text!) let guest = self.storyboard?.instantiateViewController(withIdentifier: "guestVC") as! guestVC self.navigationController?.pushViewController(guest, animated: true) } } // cell editabily func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } // swipe cell for actions func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { // call cell for calling further cell data let cell = tableView.cellForRow(at: indexPath) as! commentCell // ACTION 1. Delete let delete = UITableViewRowAction(style: .normal, title: " ") { (action:UITableViewRowAction, indexPath:IndexPath) -> Void in // STEP 1. Delete comment from server let commentQuery = PFQuery(className: "comments") commentQuery.whereKey("to", equalTo: commentuuid.last!) commentQuery.whereKey("comment", equalTo: cell.commentLbl.text!) commentQuery.findObjectsInBackground (block: { (objects, error) -> Void in if error == nil { // find related objects for object in objects! { object.deleteEventually() } } else { print(error!.localizedDescription) } }) // STEP 2. Delete #hashtag from server let hashtagQuery = PFQuery(className: "hashtags") hashtagQuery.whereKey("to", equalTo: commentuuid.last!) hashtagQuery.whereKey("by", equalTo: cell.usernameBtn.titleLabel!.text!) hashtagQuery.whereKey("comment", equalTo: cell.commentLbl.text!) hashtagQuery.findObjectsInBackground(block: { (objects, error) -> Void in for object in objects! { object.deleteEventually() } }) // STEP 3. Delete notification: mention comment let newsQuery = PFQuery(className: "news") newsQuery.whereKey("by", equalTo: cell.usernameBtn.titleLabel!.text!) newsQuery.whereKey("to", equalTo: commentowner.last!) newsQuery.whereKey("uuid", equalTo: commentuuid.last!) newsQuery.whereKey("type", containedIn: ["comment", "mention"]) newsQuery.findObjectsInBackground(block: { (objects, error) -> Void in if error == nil { for object in objects! { object.deleteEventually() } } }) // close cell tableView.setEditing(false, animated: true) // STEP 3. Delete comment row from tableView self.commentArray.remove(at: (indexPath as NSIndexPath).row) self.dateArray.remove(at: (indexPath as NSIndexPath).row) self.usernameArray.remove(at: (indexPath as NSIndexPath).row) self.avaArray.remove(at: (indexPath as NSIndexPath).row) tableView.deleteRows(at: [indexPath], with: .fade) } // ACTION 2. Mention or address message to someone let address = UITableViewRowAction(style: .normal, title: " ") { (action:UITableViewRowAction, indexPath:IndexPath) -> Void in // include username in textView self.commentTxt.text = "\(self.commentTxt.text + "@" + self.usernameArray[(indexPath as NSIndexPath).row] + " ")" // enable button self.sendBtn.isEnabled = true // close cell tableView.setEditing(false, animated: true) } // ACTION 3. Complain let complain = UITableViewRowAction(style: .normal, title: " ") { (action:UITableViewRowAction, indexPath:IndexPath) -> Void in // send complain to server regarding selected comment let complainObj = PFObject(className: "complain") complainObj["by"] = PFUser.current()?.username complainObj["to"] = cell.commentLbl.text complainObj["owner"] = cell.usernameBtn.titleLabel?.text complainObj.saveInBackground(block: { (success, error) -> Void in if success { self.alert("Complain has been made successfully", message: "Thank You! We will consider your complain") } else { self.alert("ERROR", message: error!.localizedDescription) } }) // close cell tableView.setEditing(false, animated: true) } // buttons background delete.backgroundColor = UIColor(patternImage: UIImage(named: "delete.png")!) address.backgroundColor = UIColor(patternImage: UIImage(named: "address.png")!) complain.backgroundColor = UIColor(patternImage: UIImage(named: "complain.png")!) // comment beloogs to user if cell.usernameBtn.titleLabel?.text == PFUser.current()?.username { return [delete, address] } // post belongs to user else if commentowner.last == PFUser.current()?.username { return [delete, address, complain] } // post belongs to another user else { return [address, complain] } } // alert action func alert (_ title: String, message : String) { let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert) let ok = UIAlertAction(title: "OK", style: .cancel, handler: nil) alert.addAction(ok) present(alert, animated: true, completion: nil) } // go back func back(_ sender : UIBarButtonItem) { // push back self.navigationController?.popViewController(animated: true) // clean comment uui from last holding infromation if !commentuuid.isEmpty { commentuuid.removeLast() } // clean comment owner from last holding infromation if !commentowner.isEmpty { commentowner.removeLast() } } }
mit
9eac5701f3b73d9cc91d75b0b0f50f47
39.860643
264
0.574919
5.181977
false
false
false
false
byu-oit-appdev/ios-byuSuite
byuSuite/Apps/MyFinalsSchedule/model/MyFinalsScheduleClient.swift
1
1299
// // MyFinalsScheduleClient.swift // byuSuite // // Created by Erik Brady on 5/1/18. // Copyright © 2018 Brigham Young University. All rights reserved. // private let BASE_URL = "https://api.byu.edu/domains/legacy/academic/classschedule/studentexamschedule/v1" class MyFinalsScheduleClient: ByuClient2 { static func getFinalsExams(yearTerm: YearTerm2, callback: @escaping ([FinalExam]?, ByuError?) -> Void) { ByuCredentialManager.getPersonSummary { (personSummary, error) in if let personSummary = personSummary { ByuRequestManager.instance.makeRequest(ByuRequest2(url: super.url(base: BASE_URL, pathParams: [personSummary.personId, yearTerm.code])), callback: { (response) in if let responseData = response.getDataJson() as? [String: Any], let data = responseData[keyPath: "ExamStudentScheduleService.response.schedule_table"] as? [[String: Any]] { //Filter out term header. One of the finals returned has a term header (with information like which semester, credit hours, number of classes) which we do not need let finalDicts = data.filter { $0["is_term_header"] as? String != "Y" } callback(finalDicts.map { FinalExam(dict: $0) }, nil) } else { callback(nil, response.error) } }) } else { callback(nil, error) } } } }
apache-2.0
81ff3dbb6916d69badc52a223e43b136
40.870968
177
0.708783
3.595568
false
false
false
false
brave/browser-ios
brave/src/page-hooks/BraveContextMenu.swift
1
6721
/* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ // Using suggestions from: http://www.icab.de/blog/2010/07/11/customize-the-contextual-menu-of-uiwebview/ let kNotificationMainWindowTapAndHold = "kNotificationMainWindowTapAndHold" class BraveContextMenu { fileprivate var tapLocation = CGPoint.zero fileprivate var tappedElement: ContextMenuHelper.Elements? fileprivate var timer1_cancelDefaultMenu = Timer() fileprivate var timer2_showMenuIfStillPressed = Timer() static let initialDelayToCancelBuiltinMenu = 0.25 // seconds, must be <0.3 or built-in menu can't be cancelled static let totalDelayToShowContextMenu = 0.35 - initialDelayToCancelBuiltinMenu fileprivate let fingerMovedTolerance = Float(5.0) fileprivate func reset() { timer1_cancelDefaultMenu.invalidate() timer2_showMenuIfStillPressed.invalidate() tappedElement = nil tapLocation = CGPoint.zero } fileprivate func isActive() -> Bool { return tapLocation != CGPoint.zero && (timer1_cancelDefaultMenu.isValid || timer2_showMenuIfStillPressed.isValid) } fileprivate func isBrowserTopmostAndNoPanelsOpen() -> Bool { guard let top = getApp().rootViewController.visibleViewController as? BraveTopViewController else { return false } return top.mainSidePanel.view.isHidden && top.rightSidePanel.view.isHidden } fileprivate func fingerMovedTooFar(_ touch: UITouch, window: UIView) -> Bool { let p1 = touch.location(in: window) let p2 = tapLocation let distance = hypotf(Float(p1.x) - Float(p2.x), Float(p1.y) - Float(p2.y)) return distance > fingerMovedTolerance } func sendEvent(_ event: UIEvent, window: UIWindow) { if !isBrowserTopmostAndNoPanelsOpen() { reset() return } guard let braveWebView = BraveApp.getCurrentWebView() else { return } if let touches = event.touches(for: window), let touch = touches.first, touches.count == 1 { braveWebView.lastTappedTime = Date() switch touch.phase { case .began: // A finger touched the screen reset() guard let touchView = event.allTouches?.first?.view, touchView.isDescendant(of: braveWebView) else { return } tapLocation = touch.location(in: window) timer1_cancelDefaultMenu = Timer.scheduledTimer(timeInterval: BraveContextMenu.initialDelayToCancelBuiltinMenu, target: self, selector: #selector(BraveContextMenu.cancelDefaultMenuAndFindTappedItem), userInfo: nil, repeats: false) case .moved, .stationary: if isActive() && fingerMovedTooFar(touch, window: window) { // my test for this: tap with edge of finger, then roll to opposite edge while holding finger down, is 5-10 px of movement; Should still show context menu, don't want this to trigger a reset() reset() } case .ended, .cancelled: if isActive() { if let url = tappedElement?.link, !fingerMovedTooFar(touch, window: window) { BraveApp.getCurrentWebView()?.loadRequest(URLRequest(url: url as URL)) } reset() } } } else { reset() } } @objc func showContextMenu() { func showContextMenuForElement(_ tappedElement: ContextMenuHelper.Elements) { let info = ["point": NSValue(cgPoint: tapLocation)] NotificationCenter.default.post(name: Notification.Name(rawValue: kNotificationMainWindowTapAndHold), object: self, userInfo: info) guard let bvc = getApp().browserViewController else { return } if bvc.urlBar.inSearchMode { return } bvc.showContextMenu(tappedElement, touchPoint: tapLocation) reset() } if let tappedElement = tappedElement { showContextMenuForElement(tappedElement) } } // This is called 2x, once at .25 seconds to ensure the native context menu is cancelled, // then again at .5 seconds to show our context menu. (This code was borne of frustration, not ideal flow) @objc func cancelDefaultMenuAndFindTappedItem() { if !isBrowserTopmostAndNoPanelsOpen() { reset() return } guard let webView = BraveApp.getCurrentWebView() else { return } let hit: (url: String?, image: String?, urlTarget: String?)? if [".jpg", ".png", ".gif"].filter({ webView.URL?.absoluteString.endsWith($0) ?? false }).count > 0 { // web view is just showing an image hit = (url:nil, image:webView.URL!.absoluteString, urlTarget:nil) } else { hit = ElementAtPoint().getHit(tapLocation) } if hit == nil { // No link or image found, not for this class to handle reset() return } // A phone URL should be in the form "tel:x". // Sometimes, the element's URL includes the page's URL before the tel scheme ("https://example.com/tel:x"). // Remove the page's URL to get the phone URL. if let url = hit?.url { hit?.url = url.regexReplacePattern("(?:.*)(tel:)(.*)", with: "$1$2") } tappedElement = ContextMenuHelper.Elements(link: hit!.url != nil ? URL(string: hit!.url!) : nil, image: hit!.image != nil ? URL(string: hit!.image!) : nil, folder: nil) func blockOtherGestures(_ views: [UIView]?) { guard let views = views else { return } for view in views { if let gestures = view.gestureRecognizers as [UIGestureRecognizer]! { for gesture in gestures { if gesture is UILongPressGestureRecognizer { // toggling gets the gesture to ignore this long press gesture.isEnabled = false gesture.isEnabled = true } } } } } blockOtherGestures(BraveApp.getCurrentWebView()?.scrollView.subviews) timer2_showMenuIfStillPressed = Timer.scheduledTimer(timeInterval: BraveContextMenu.totalDelayToShowContextMenu, target: self, selector: #selector(BraveContextMenu.showContextMenu), userInfo: nil, repeats: false) } }
mpl-2.0
addbfc6ed137783cd7ae2196a17777d5
42.928105
246
0.615533
4.945548
false
false
false
false
darina/omim
iphone/Maps/Bookmarks/BookmarksList/BookmarksListInteractor.swift
4
4496
extension BookmarksListSortingType { init(_ sortingType: BookmarksSortingType) { switch sortingType { case .byType: self = .type case .byDistance: self = .distance case .byTime: self = .date @unknown default: fatalError() } } } enum ExportFileStatus { case success case empty case error } fileprivate final class BookmarksManagerListener: NSObject { private var callback: (ExportFileStatus) -> Void init(_ callback: @escaping (ExportFileStatus) -> Void) { self.callback = callback } } extension BookmarksManagerListener: BookmarksObserver { func onBookmarksCategoryFilePrepared(_ status: BookmarksShareStatus) { switch status { case .success: callback(.success) case .emptyCategory: callback(.empty) case .archiveError, .fileError: callback(.error) @unknown default: fatalError() } } } final class BookmarksListInteractor { private let markGroupId: MWMMarkGroupID private var bookmarksManager: BookmarksManager { BookmarksManager.shared() } private var bookmarksManagerListener: BookmarksManagerListener? init(markGroupId: MWMMarkGroupID) { self.markGroupId = markGroupId } } extension BookmarksListInteractor: IBookmarksListInteractor { func getBookmarkGroup() -> BookmarkGroup { bookmarksManager.category(withId: markGroupId) } func hasDescription() -> Bool { bookmarksManager.hasExtraInfo(markGroupId) } func prepareForSearch() { bookmarksManager.prepare(forSearch: markGroupId) } func search(_ text: String, completion: @escaping ([Bookmark]) -> Void) { bookmarksManager.searchBookmarksGroup(markGroupId, text: text) { completion($0) } } func availableSortingTypes(hasMyPosition: Bool) -> [BookmarksListSortingType] { bookmarksManager.availableSortingTypes(markGroupId, hasMyPosition: hasMyPosition).map { BookmarksSortingType(rawValue: $0.intValue)! }.map { switch $0 { case .byType: return BookmarksListSortingType.type case .byDistance: return BookmarksListSortingType.distance case .byTime: return BookmarksListSortingType.date @unknown default: fatalError() } } } func viewOnMap() { FrameworkHelper.show(onMap: markGroupId) } func viewBookmarkOnMap(_ bookmarkId: MWMMarkID) { FrameworkHelper.showBookmark(bookmarkId) } func viewTrackOnMap(_ trackId: MWMTrackID) { FrameworkHelper.showTrack(trackId) } func setGroup(_ groupId: MWMMarkGroupID, visible: Bool) { bookmarksManager.setCategory(groupId, isVisible: visible) } func sort(_ sortingType: BookmarksListSortingType, location: CLLocation?, completion: @escaping ([BookmarksSection]) -> Void) { let coreSortingType: BookmarksSortingType switch sortingType { case .distance: coreSortingType = .byDistance case .date: coreSortingType = .byTime case .type: coreSortingType = .byType } bookmarksManager.sortBookmarks(markGroupId, sortingType: coreSortingType, location: location) { sections in guard let sections = sections else { return } completion(sections) } } func resetSort() { bookmarksManager.resetLastSortingType(markGroupId) } func lastSortingType() -> BookmarksListSortingType? { guard bookmarksManager.hasLastSortingType(markGroupId) else { return nil } return BookmarksListSortingType(bookmarksManager.lastSortingType(markGroupId)) } func deleteBookmark(_ bookmarkId: MWMMarkID) { bookmarksManager.deleteBookmark(bookmarkId) } func deleteBookmarksGroup() { bookmarksManager.deleteCategory(markGroupId) } func canDeleteGroup() -> Bool { bookmarksManager.userCategories().count > 1 } func exportFile(_ completion: @escaping (URL?, ExportFileStatus) -> Void) { bookmarksManagerListener = BookmarksManagerListener({ [weak self] status in guard let self = self else { return } self.bookmarksManager.remove(self.bookmarksManagerListener!) var url: URL? = nil if status == .success { url = self.bookmarksManager.shareCategoryURL() } completion(url, status) }) bookmarksManager.add(bookmarksManagerListener!) bookmarksManager.shareCategory(markGroupId) } func finishExportFile() { bookmarksManager.finishShareCategory() } }
apache-2.0
a8e8d8b95b9b5389eeee60efa4ce453d
25.761905
91
0.693728
4.416503
false
false
false
false
buscarini/vitemo
vitemo/Carthage/Checkouts/GRMustache.swift/MustacheTests/Public/ServicesTests/NSFormatterTests.swift
4
12741
// The MIT License // // Copyright (c) 2015 Gwendal Roué // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import XCTest import Mustache class NSFormatterTests: XCTestCase { func testFormatterIsAFilterForProcessableValues() { let percentFormatter = NSNumberFormatter() percentFormatter.numberStyle = .PercentStyle percentFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") // test that number is processable XCTAssertEqual(percentFormatter.stringFromNumber(0.5)!, "50%") // test filtering a number let template = Template(string: "{{ percent(number) }}")! let box = Box(["number": Box(0.5), "percent": Box(percentFormatter)]) let rendering = template.render(box)! XCTAssertEqual(rendering, "50%") } func testFormatterIsAFilterForUnprocessableValues() { let percentFormatter = NSNumberFormatter() percentFormatter.numberStyle = .PercentStyle percentFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") // test that number is processable XCTAssertNil(percentFormatter.stringForObjectValue("foo")) // test filtering a string let template = Template(string: "{{ percent(string) }}")! let box = Box(["string": Box("foo"), "percent": Box(percentFormatter)]) let rendering = template.render(box)! XCTAssertEqual(rendering, "") } func testFormatterSectionFormatsInnerVariableTags() { let percentFormatter = NSNumberFormatter() percentFormatter.numberStyle = .PercentStyle percentFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") let template = Template(string: "{{# percent }}{{ number }} {{ number }}{{/ percent }}")! let box = Box(["number": Box(0.5), "percent": Box(percentFormatter)]) let rendering = template.render(box)! XCTAssertEqual(rendering, "50% 50%") } func testFormatterSectionDoesNotFormatUnprocessableInnerVariableTags() { let percentFormatter = NSNumberFormatter() percentFormatter.numberStyle = .PercentStyle percentFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") let template = Template(string: "{{# percent }}{{ value }}{{/ percent }}")! let box = Box(["value": Box("foo"), "percent": Box(percentFormatter)]) let rendering = template.render(box)! XCTAssertEqual(rendering, "foo") } func testFormatterAsSectionFormatsDeepInnerVariableTags() { let percentFormatter = NSNumberFormatter() percentFormatter.numberStyle = .PercentStyle percentFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") let template = Template(string: "{{# percent }}{{# number }}Number is {{ number }}.{{/ number }}{{/ percent }}")! let box = Box(["number": Box(0.5), "percent": Box(percentFormatter)]) let rendering = template.render(box)! XCTAssertEqual(rendering, "Number is 50%.") } func testFormatterAsSectionDoesNotFormatInnerSectionTags() { let percentFormatter = NSNumberFormatter() percentFormatter.numberStyle = .PercentStyle percentFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") let template = Template(string: "NO is {{ NO }}. {{^ NO }}NO is false.{{/ NO }} percent(NO) is {{ percent(NO) }}. {{# percent(NO) }}percent(NO) is true.{{/ percent(NO) }} {{# percent }}{{^ NO }}NO is now {{ NO }} and is still false.{{/ NO }}{{/ percent }}")! let box = Box(["number": Box(0.5), "NO": Box(0), "percent": Box(percentFormatter)]) let rendering = template.render(box)! XCTAssertEqual(rendering, "NO is 0. NO is false. percent(NO) is 0%. percent(NO) is true. NO is now 0% and is still false.") } func testFormatterIsTruthy() { let formatter = NSFormatter() let template = Template(string: "{{# formatter }}Formatter is true.{{/ formatter }}{{^ formatter }}Formatter is false.{{/ formatter }}")! let box = Box(["formatter": Box(formatter)]) let rendering = template.render(box)! XCTAssertEqual(rendering, "Formatter is true.") } func testFormatterRendersSelfAsSomething() { let formatter = NSFormatter() let template = Template(string: "{{ formatter }}")! let box = Box(["formatter": Box(formatter)]) let rendering = template.render(box)! XCTAssertTrue(count(rendering) > 0) } func testNumberFormatterRendersNothingForMissingValue() { // Check that NSNumberFormatter does not have surprising behavior, and // does not format nil. let percentFormatter = NSNumberFormatter() percentFormatter.numberStyle = .PercentStyle percentFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") let box = Box(["format": Box(percentFormatter)]) var template = Template(string: "<{{format(value)}}>")! var rendering = template.render(box)! XCTAssertEqual(rendering, "<>") template = Template(string: "{{#format(value)}}YES{{/}}{{^format(value)}}NO{{/}}")! rendering = template.render(box)! XCTAssertEqual(rendering, "NO") } func testNumberFormatterRendersNothingForNSNull() { let percentFormatter = NSNumberFormatter() percentFormatter.numberStyle = .PercentStyle percentFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") let box = Box(["format": Box(percentFormatter), "value": Box(NSNull())]) var template = Template(string: "<{{format(value)}}>")! var rendering = template.render(box)! XCTAssertEqual(rendering, "<>") template = Template(string: "{{#format(value)}}YES{{/}}{{^format(value)}}NO{{/}}")! rendering = template.render(box)! XCTAssertEqual(rendering, "NO") } func testNumberFormatterRendersNothingForNSString() { let percentFormatter = NSNumberFormatter() percentFormatter.numberStyle = .PercentStyle percentFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") var box = Box(["format": Box(percentFormatter), "value": Box("1")]) var template = Template(string: "<{{format(value)}}>")! var rendering = template.render(box)! XCTAssertEqual(rendering, "<>") template = Template(string: "{{#format(value)}}YES{{/}}{{^format(value)}}NO{{/}}")! rendering = template.render(box)! XCTAssertEqual(rendering, "NO") box = Box(["format": Box(percentFormatter), "value": Box("YES")]) template = Template(string: "<{{format(value)}}>")! rendering = template.render(box)! XCTAssertEqual(rendering, "<>") template = Template(string: "{{#format(value)}}YES{{/}}{{^format(value)}}NO{{/}}")! rendering = template.render(box)! XCTAssertEqual(rendering, "NO") box = Box(["format": Box(percentFormatter), "value": Box("foo")]) template = Template(string: "<{{format(value)}}>")! rendering = template.render(box)! XCTAssertEqual(rendering, "<>") template = Template(string: "{{#format(value)}}YES{{/}}{{^format(value)}}NO{{/}}")! rendering = template.render(box)! XCTAssertEqual(rendering, "NO") } func testNumberFormatterRendersNothingForNSDate() { // Check that NSNumberFormatter does not have surprising behavior, and // does not format NSDate. let percentFormatter = NSNumberFormatter() percentFormatter.numberStyle = .PercentStyle percentFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") let box = Box(["format": Box(percentFormatter), "value": Box(NSDate())]) var template = Template(string: "<{{format(value)}}>")! var rendering = template.render(box)! XCTAssertEqual(rendering, "<>") template = Template(string: "{{#format(value)}}YES{{/}}{{^format(value)}}NO{{/}}")! rendering = template.render(box)! XCTAssertEqual(rendering, "NO") } func testDateFormatterRendersNothingForMissingValue() { // Check that NSDateFormatter does not have surprising behavior, and // does not format nil. let dateFormatter = NSDateFormatter() dateFormatter.dateStyle = .FullStyle let box = Box(["format": Box(dateFormatter)]) var template = Template(string: "<{{format(value)}}>")! var rendering = template.render(box)! XCTAssertEqual(rendering, "<>") template = Template(string: "{{#format(value)}}YES{{/}}{{^format(value)}}NO{{/}}")! rendering = template.render(box)! XCTAssertEqual(rendering, "NO") } func testDateFormatterRendersNothingForNSNull() { let dateFormatter = NSDateFormatter() dateFormatter.dateStyle = .FullStyle let box = Box(["format": Box(dateFormatter), "value": Box(NSNull())]) var template = Template(string: "<{{format(value)}}>")! var rendering = template.render(box)! XCTAssertEqual(rendering, "<>") template = Template(string: "{{#format(value)}}YES{{/}}{{^format(value)}}NO{{/}}")! rendering = template.render(box)! XCTAssertEqual(rendering, "NO") } func testDateFormatterRendersNothingForNSString() { let dateFormatter = NSDateFormatter() dateFormatter.dateStyle = .FullStyle var box = Box(["format": Box(dateFormatter), "value": Box("1")]) var template = Template(string: "<{{format(value)}}>")! var rendering = template.render(box)! XCTAssertEqual(rendering, "<>") template = Template(string: "{{#format(value)}}YES{{/}}{{^format(value)}}NO{{/}}")! rendering = template.render(box)! XCTAssertEqual(rendering, "NO") box = Box(["format": Box(dateFormatter), "value": Box("YES")]) template = Template(string: "<{{format(value)}}>")! rendering = template.render(box)! XCTAssertEqual(rendering, "<>") template = Template(string: "{{#format(value)}}YES{{/}}{{^format(value)}}NO{{/}}")! rendering = template.render(box)! XCTAssertEqual(rendering, "NO") box = Box(["format": Box(dateFormatter), "value": Box("foo")]) template = Template(string: "<{{format(value)}}>")! rendering = template.render(box)! XCTAssertEqual(rendering, "<>") template = Template(string: "{{#format(value)}}YES{{/}}{{^format(value)}}NO{{/}}")! rendering = template.render(box)! XCTAssertEqual(rendering, "NO") } func testDateFormatterRendersNothingForNSNumber() { // Check that NSDateFormatter does not have surprising behavior, and // does not format NSNumber. let dateFormatter = NSDateFormatter() dateFormatter.dateStyle = .FullStyle let box = Box(["format": Box(dateFormatter), "value": Box(0)]) var template = Template(string: "<{{format(value)}}>")! var rendering = template.render(box)! XCTAssertEqual(rendering, "<>") template = Template(string: "{{#format(value)}}YES{{/}}{{^format(value)}}NO{{/}}")! rendering = template.render(box)! XCTAssertEqual(rendering, "NO") } }
mit
b400ada4c7309d5a48f127f627460122
42.333333
266
0.616641
5.114412
false
true
false
false
Kawoou/KWDrawerController
DrawerController/Transition/DrawerScaleTransition.swift
1
3438
/* The MIT License (MIT) Copyright (c) 2017 Kawoou (Jungwon An) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import UIKit open class DrawerScaleTransition: DrawerTransition { // MARK: - Public open override func initTransition(content: DrawerContent) { super.initTransition(content: content) } open override func startTransition(content: DrawerContent, side: DrawerSide) { super.startTransition(content: content, side: side) content.contentView.transform = .identity } open override func endTransition(content: DrawerContent, side: DrawerSide) { super.endTransition(content: content, side: side) content.contentView.transform = .identity } open override func transition(content: DrawerContent, side: DrawerSide, percentage: CGFloat, viewRect: CGRect) { switch content.drawerSide { case .left: if 1.0 == -percentage { content.contentView.transform = CGAffineTransform(scaleX: 0.001, y: 1.0) } else { content.contentView.transform = CGAffineTransform(scaleX: 1.0 + percentage, y: 1.0) } content.contentView.frame = CGRect( x: 0, y: viewRect.minY, width: content.contentView.frame.width, height: content.contentView.frame.height ) case .right: if 1.0 == percentage { content.contentView.transform = CGAffineTransform(scaleX: 0.001, y: 1.0) } else { content.contentView.transform = CGAffineTransform(scaleX: 1.0 - percentage, y: 1.0) } content.contentView.frame = CGRect( x: viewRect.width + content.drawerOffset - content.contentView.frame.width, y: viewRect.minY, width: content.contentView.frame.width, height: content.contentView.frame.height ) case .none: content.contentView.transform = .identity content.contentView.frame = CGRect( x: viewRect.size.width * percentage + content.drawerOffset, y: viewRect.minY, width: content.contentView.frame.width, height: content.contentView.frame.height ) } } public override init() { super.init() } }
mit
51f599660f6babfdd43ff493324a0908
37.2
116
0.646306
4.768377
false
false
false
false
USDepartmentofLabor/Public-Data-Listing-Consolidator
Public Data Listing Consolidator/AppDelegate.swift
1
1436
// // AppDelegate.swift // Public Data Listing Consolidator // // Created by Michael Pulsifer on 1/2/15. // Copyright (c) 2015 U.S. Department of Labor. All rights reserved. // import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(aNotification: NSNotification) { // Insert code here to initialize your application } func applicationWillTerminate(aNotification: NSNotification) { // Insert code here to tear down your application } @IBAction func openPDL(sender: AnyObject) { // do stuff println("it worked") let myFiledialog:NSOpenPanel = NSOpenPanel() myFiledialog.allowsMultipleSelection = false myFiledialog.canChooseDirectories = false myFiledialog.runModal() var chosenfile = myFiledialog.URL if (chosenfile != nil) { // main data.json // may not do anything with this var path = chosenfile?.path var rootPath = path?.stringByDeletingLastPathComponent let publicDataListings : PDL = PDL() publicDataListings.path = path! publicDataListings.rootPath = rootPath! publicDataListings.collectPublicDataListingFiles() publicDataListings.writeDataJSONToFile() } } }
unlicense
95bad11a00787e2475161efb051ccf84
27.72
71
0.628134
5.221818
false
false
false
false
Esri/arcgis-runtime-samples-ios
arcgis-ios-sdk-samples/Layers/Hillshade renderer/HillshadeRendererViewController.swift
1
3178
// Copyright 2016 Esri. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import UIKit import ArcGIS class HillshadeRendererViewController: UIViewController { @IBOutlet var mapView: AGSMapView! private weak var rasterLayer: AGSRasterLayer? override func viewDidLoad() { super.viewDidLoad() // add the source code button item to the right of navigation bar (navigationItem.rightBarButtonItem as! SourceCodeBarButtonItem).filenames = [ "HillshadeRendererViewController", "HillshadeSettingsViewController", "OptionsTableViewController" ] let raster = AGSRaster(name: "srtm", extension: "tiff") let rasterLayer = AGSRasterLayer(raster: raster) self.rasterLayer = rasterLayer let map = AGSMap(basemap: AGSBasemap(baseLayer: rasterLayer)) mapView.map = map // initial renderer setRenderer(altitude: 45, azimuth: 315, slopeType: .none) } private func setRenderer(altitude: Double, azimuth: Double, slopeType: AGSSlopeType) { let renderer = AGSHillshadeRenderer(altitude: altitude, azimuth: azimuth, zFactor: 0.000016, slopeType: slopeType, pixelSizeFactor: 1, pixelSizePower: 1, outputBitDepth: 8) rasterLayer?.renderer = renderer } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let navController = segue.destination as? UINavigationController, let controller = navController.viewControllers.first as? HillshadeSettingsViewController, let renderer = rasterLayer?.renderer as? AGSHillshadeRenderer { controller.preferredContentSize = CGSize(width: 375, height: 135) navController.presentationController?.delegate = self controller.delegate = self controller.altitude = renderer.altitude controller.azimuth = renderer.azimuth controller.slopeType = renderer.slopeType } } } extension HillshadeRendererViewController: HillshadeSettingsViewControllerDelegate { func hillshadeSettingsViewController(_ controller: HillshadeSettingsViewController, selectedAltitude altitude: Double, azimuth: Double, slopeType: AGSSlopeType) { setRenderer(altitude: altitude, azimuth: azimuth, slopeType: slopeType) } } extension HillshadeRendererViewController: UIAdaptivePresentationControllerDelegate { func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle { return .none } }
apache-2.0
200dce99039eddd99e922c1e6170beb7
40.815789
180
0.708307
5.101124
false
false
false
false
cloudinary/cloudinary_ios
Cloudinary/Classes/Core/Features/UploadWidget/CropView/CLDCropOverlayView.swift
1
10756
// // CLDCropOverlayView.swift // ProjectCLDWidgetEditViewController // // Created by Arkadi Yoskovitz on 8/17/20. // Copyright © 2020 Gini-Apps LTD. All rights reserved. // import UIKit private let kCLDCropOverLayerPlaceholder = CGFloat(00.0); private let kCLDCropOverLayerCornerWidth = CGFloat(20.0); @objc @objcMembers public class CLDCropOverlayView : UIView { // MARK: - public override var frame: CGRect { didSet { layoutLinesIfNeeded() } } public var gridColor : UIColor { didSet { layoutLinesIfNeeded() } } public var knobColor : UIColor { didSet { layoutLinesIfNeeded() } } // MARK: - Public Properties /** Hides the interior grid lines, sans animation. */ public var isGridHidden : Bool { set { setGridlines(hidden: newValue, animted: false) } get { areGridLinesHidden } } /** Add/Remove the interior horizontal grid lines. */ public var shouldDisplayHorizontalGridLines : Bool { set { setDisplayHorizontalGridLines(newValue) } get { displayGridLinesHorizontal } } /** Add/Remove the interior vertical grid lines. */ public var shouldDisplayVerticalGridLines : Bool { set { setDisplayVerticalGridLines(newValue) } get { displayGridLinesVertical } } // MARK: - Private Properties private var areGridLinesHidden : Bool private var displayGridLinesHorizontal: Bool private var displayGridLinesVertical : Bool private var gridLinesHorizontal : [UIView] private var gridLinesVertical : [UIView] private var outerLineViews : [UIView] // top, right, bottom, left private var topLeftLineViews : [UIView] // vertical, horizontal private var bottomLeftLineViews : [UIView] private var bottomRightLineViews : [UIView] private var topRightLineViews : [UIView] // MARK: - init public override init(frame: CGRect) { self.areGridLinesHidden = false self.displayGridLinesVertical = true self.displayGridLinesHorizontal = true self.gridColor = UIColor.white self.knobColor = UIColor.white self.gridLinesHorizontal = [UIView]() self.gridLinesVertical = [UIView]() self.outerLineViews = [UIView]() //top, right, bottom, left self.topLeftLineViews = [UIView]() self.topRightLineViews = [UIView]() self.bottomLeftLineViews = [UIView]() self.bottomRightLineViews = [UIView]() super.init(frame: frame) self.clipsToBounds = false self.outerLineViews.append(contentsOf: [ createLineView(background: gridColor), createLineView(background: gridColor), createLineView(background: gridColor), createLineView(background: gridColor) ]) self.topLeftLineViews.append(contentsOf: [ createLineView(background: gridColor), createLineView(background: gridColor) ]) self.topRightLineViews.append(contentsOf: [ createLineView(background: gridColor), createLineView(background: gridColor) ]) self.bottomLeftLineViews.append(contentsOf: [ createLineView(background: gridColor), createLineView(background: gridColor) ]) self.bottomRightLineViews.append(contentsOf: [ createLineView(background: gridColor), createLineView(background: gridColor) ]) self.setDisplayHorizontalGridLines(true) self.setDisplayVerticalGridLines(true) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - public override func didMoveToSuperview() { super.didMoveToSuperview() layoutLinesIfNeeded() } // MARK: - /** Shows and hides the interior grid lines with an optional crossfade animation. */ public func setGridlines(hidden: Bool, animted: Bool) { areGridLinesHidden = hidden; let block : () -> Void = { self.gridLinesHorizontal.forEach { $0.alpha = hidden ? 0.0 : 1.0 } self.gridLinesVertical.forEach { $0.alpha = hidden ? 0.0 : 1.0 } } switch animted { case true : UIView.animate(withDuration: hidden ? 0.35 : 0.2) { block() } case false: block() } } // MARK: - Private setter actions private func setDisplayHorizontalGridLines(_ display: Bool) { displayGridLinesHorizontal = display gridLinesHorizontal.forEach { $0.removeFromSuperview() } gridLinesHorizontal.removeAll() if displayGridLinesHorizontal { gridLinesHorizontal.append(contentsOf: [ createLineView(background: gridColor), createLineView(background: gridColor) ]) } setNeedsDisplay() } private func setDisplayVerticalGridLines(_ display: Bool) { displayGridLinesVertical = display gridLinesVertical.forEach { $0.removeFromSuperview() } gridLinesVertical.removeAll() if displayGridLinesVertical { gridLinesVertical.append(contentsOf: [ createLineView(background: gridColor), createLineView(background: gridColor) ]) } setNeedsDisplay() } // MARK: - Private methods private func layoutLinesIfNeeded() { guard !outerLineViews.isEmpty else { return } applyLayoutLines() } private func applyLayoutLines() { let boundsSize = bounds.size // Border lines outerLineViews.enumerated().forEach { (item) in let aRect : CGRect switch item.offset { case 0: aRect = CGRect(x: 0.0 , y: -1.0, width: boundsSize.width + 2.0, height: 1.0) // Top case 1: aRect = CGRect(x: boundsSize.width, y: 0.0, width: 1.0, height: boundsSize.height + 0.0) // Right case 2: aRect = CGRect(x: -1.0 , y: boundsSize.height, width: boundsSize.width + 2.0, height: 1.0) // Bottom case 3: aRect = CGRect(x: -1.0 , y: 0.0, width: 1.0, height: boundsSize.height + 1.0) // Left default: aRect = CGRect.zero } item.element.frame = aRect } // Corner liness [topLeftLineViews, topRightLineViews, bottomRightLineViews, bottomLeftLineViews].enumerated().forEach { item in var VFrame = CGRect.zero var HFrame = CGRect.zero switch item.offset { case 0: // Top left VFrame = CGRect(x: kCLDCropOverLayerPlaceholder - 3.0, y: kCLDCropOverLayerPlaceholder - 3.0, width: 3.0, height: kCLDCropOverLayerCornerWidth + 3.0) HFrame = CGRect(x: kCLDCropOverLayerPlaceholder + 0.0, y: kCLDCropOverLayerPlaceholder - 3.0, width: kCLDCropOverLayerCornerWidth + 0.0, height: 3.0) break case 1: // Top right VFrame = CGRect(x: boundsSize.width + kCLDCropOverLayerPlaceholder, y: kCLDCropOverLayerPlaceholder - 3.0, width: 3.0, height: kCLDCropOverLayerCornerWidth + 3.0) HFrame = CGRect(x: boundsSize.width - kCLDCropOverLayerCornerWidth, y: kCLDCropOverLayerPlaceholder - 3.0, width: kCLDCropOverLayerCornerWidth + 0.0, height: 3.0) break case 2: // Bottom right VFrame = CGRect(x: boundsSize.width + kCLDCropOverLayerPlaceholder, y: boundsSize.height - kCLDCropOverLayerCornerWidth, width: 3.0, height: kCLDCropOverLayerCornerWidth + 3.0) HFrame = CGRect(x: boundsSize.width - kCLDCropOverLayerCornerWidth, y: boundsSize.height + kCLDCropOverLayerPlaceholder, width: kCLDCropOverLayerCornerWidth + 0.0, height: 3.0) break case 3: // Bottom left VFrame = CGRect(x: kCLDCropOverLayerPlaceholder - 3.0, y: boundsSize.height - kCLDCropOverLayerCornerWidth, width: 3.0, height: kCLDCropOverLayerCornerWidth) HFrame = CGRect(x: kCLDCropOverLayerPlaceholder - 3.0, y: boundsSize.height + kCLDCropOverLayerPlaceholder, width: kCLDCropOverLayerCornerWidth + 3.0, height: 3.0) break default: break } item.element[0].frame = VFrame item.element[1].frame = HFrame } var padding : CGFloat var linesCount : Int let thickness = 1.0 / UIScreen.main.scale // Grid lines - horizontal linesCount = gridLinesHorizontal.count padding = (bounds.height - (thickness * CGFloat(linesCount))) / (CGFloat(linesCount) + 1.0) gridLinesHorizontal.enumerated().forEach { item in var aRect = CGRect.zero aRect.size.width = bounds.width aRect.size.height = thickness aRect.origin.y = (padding * CGFloat(item.offset + 1)) + (thickness * CGFloat(item.offset)) item.element.frame = aRect } // Grid lines - vertical linesCount = gridLinesVertical.count padding = (bounds.width - (thickness * CGFloat(linesCount))) / (CGFloat(linesCount) + 1.0) gridLinesVertical.enumerated().forEach { item in var aRect = CGRect.zero aRect.size.width = thickness aRect.size.height = bounds.height aRect.origin.x = (padding * CGFloat(item.offset + 1)) + (thickness * CGFloat(item.offset)) item.element.frame = aRect } } private func createLineView(background color: UIColor) -> UIView { let newLine = UIView(frame: .zero) newLine.backgroundColor = color addSubview(newLine) return newLine } }
mit
9a8929383bbe273d18279a48885296b2
36.086207
132
0.56941
4.773635
false
false
false
false
fgulan/letter-ml
project/LetterML/Frameworks/framework/Source/Operations/ChromaKeying.swift
9
612
public class ChromaKeying: BasicOperation { public var thresholdSensitivity:Float = 0.4 { didSet { uniformSettings["thresholdSensitivity"] = thresholdSensitivity } } public var smoothing:Float = 0.1 { didSet { uniformSettings["smoothing"] = smoothing } } public var colorToReplace:Color = Color.green { didSet { uniformSettings["colorToReplace"] = colorToReplace } } public init() { super.init(fragmentShader:ChromaKeyFragmentShader, numberOfInputs:1) ({thresholdSensitivity = 0.4})() ({smoothing = 0.1})() ({colorToReplace = Color.green})() } }
mit
a456a6c165c3034b19374393b8ec4103
46.076923
125
0.674837
4.533333
false
false
false
false
masters3d/xswift
exercises/word-count/Tests/WordCountTests/WordCountTests.swift
3
1958
import XCTest @testable import WordCount class WordCountTests: XCTestCase { func testCountOneWord() { let words = WordCount(words: "word") let expected = ["word": 1] let result = words.count() XCTAssertEqual(expected, result) } func testCountOneOfEeach() { let words = WordCount(words: "one of each") let expected = ["one": 1, "of": 1, "each": 1 ] let result = words.count() XCTAssertEqual(expected, result) } func testCountMultipleOccurrences() { let words = WordCount(words: "one fish two fish red fish blue fish") let expected = ["one": 1, "fish": 4, "two": 1, "red": 1, "blue": 1 ] let result = words.count() XCTAssertEqual(expected, result) } func testIgnorePunctation() { let words = WordCount(words: "car : carpet as java : javascript!!&$%^&") let expected = ["car": 1, "carpet": 1, "as": 1, "java": 1, "javascript": 1 ] let result = words.count() XCTAssertEqual(expected, result) } func testIncludeNumbers() { let words = WordCount(words: "testing, 1, 2 testing") let expected = [ "testing": 2, "1": 1, "2": 1 ] let result = words.count() XCTAssertEqual(expected, result) } func testNormalizeCase() { let words = WordCount(words:"go Go GO") let expected = [ "go": 3] let result = words.count() XCTAssertEqual(expected, result) } static var allTests: [(String, (WordCountTests) -> () throws -> Void)] { return [ ("testCountOneWord", testCountOneWord), ("testCountOneOfEeach", testCountOneOfEeach), ("testCountMultipleOccurrences", testCountMultipleOccurrences), ("testIgnorePunctation", testIgnorePunctation), ("testIncludeNumbers", testIncludeNumbers), ("testNormalizeCase", testNormalizeCase), ] } }
mit
1ae7aca02ef6ba3e3da0ef9c29441692
30.079365
84
0.586313
4.139535
false
true
false
false
msn0w/bgsights
bgSights/MenuTransitionManager.swift
1
3076
// // MenuTransitionManager.swift // bgSights // // Created by Deyan Marinov on 1/8/16. // Copyright © 2016 Deyan Marinov. All rights reserved. // import UIKit @objc protocol MenuTransitionManagerDelegate { func dismiss() } class MenuTransitionManager: NSObject, UIViewControllerAnimatedTransitioning, UIViewControllerTransitioningDelegate { let duration = 0.5 var isPresenting = false var snapshot:UIView? { didSet { if let delegate = delegate { let tapGestureRecognizer = UITapGestureRecognizer(target: delegate, action: "dismiss") snapshot?.addGestureRecognizer(tapGestureRecognizer) } } } var delegate:MenuTransitionManagerDelegate? func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return duration } func animateTransition(transitionContext: UIViewControllerContextTransitioning) { // Get reference to our fromView, toView and the container view let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey)! let toView = transitionContext.viewForKey(UITransitionContextToViewKey)! // Set up the transform we'll use in the animation guard let container = transitionContext.containerView() else { return } let moveDown = CGAffineTransformMakeTranslation(0, container.frame.height - 150) let moveUp = CGAffineTransformMakeTranslation(0, -50) // Add both views to the container view if isPresenting { toView.transform = moveUp snapshot = fromView.snapshotViewAfterScreenUpdates(true) container.addSubview(toView) container.addSubview(snapshot!) } // Perform the animation UIView.animateWithDuration(duration, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.8, options: [], animations: { if self.isPresenting { self.snapshot?.transform = moveDown toView.transform = CGAffineTransformIdentity } else { self.snapshot?.transform = CGAffineTransformIdentity fromView.transform = moveUp } }, completion: { finished in transitionContext.completeTransition(true) if !self.isPresenting { self.snapshot?.removeFromSuperview() } }) } func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? { isPresenting = true return self } func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { isPresenting = false return self } }
mit
4102024520c8634ad824468bda48fc9c
33.550562
217
0.645528
6.501057
false
false
false
false
hooman/swift
test/Distributed/Runtime/distributed_actor_decode.swift
2
8116
// RUN: %target-run-simple-swift(-Xfrontend -enable-experimental-distributed -parse-as-library) | %FileCheck %s // REQUIRES: executable_test // REQUIRES: concurrency // REQUIRES: distributed // UNSUPPORTED: use_os_stdlib // UNSUPPORTED: back_deployment_runtime import _Distributed @available(SwiftStdlib 5.5, *) distributed actor DA: CustomStringConvertible { nonisolated var description: String { "DA(\(self.id))" } } // ==== Fake Transport --------------------------------------------------------- @available(SwiftStdlib 5.5, *) struct ActorAddress: ActorIdentity { let address: String init(parse address : String) { self.address = address } // Explicit implementations to make our TestEncoder/Decoder simpler init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() self.address = try container.decode(String.self) print("decode ActorAddress -> \(self)") } func encode(to encoder: Encoder) throws { print("encode \(self)") var container = encoder.singleValueContainer() try container.encode(self.address) } } @available(SwiftStdlib 5.5, *) struct FakeTransport: ActorTransport { func decodeIdentity(from decoder: Decoder) throws -> AnyActorIdentity { print("FakeTransport.decodeIdentity from:\(decoder)") let address = try ActorAddress(from: decoder) return AnyActorIdentity(address) } func resolve<Act>(_ identity: AnyActorIdentity, as actorType: Act.Type) throws -> Act? where Act: DistributedActor { print("resolve type:\(actorType), address:\(identity)") return nil } func assignIdentity<Act>(_ actorType: Act.Type) -> AnyActorIdentity where Act: DistributedActor { let address = ActorAddress(parse: "xxx") print("assign type:\(actorType), address:\(address)") return .init(address) } public func actorReady<Act>(_ actor: Act) where Act: DistributedActor { print("ready actor:\(actor), address:\(actor.id)") } func resignIdentity(_ identity: AnyActorIdentity) { print("resign address:\(identity)") } } // ==== Test Coding ------------------------------------------------------------ @available(SwiftStdlib 5.5, *) class TestEncoder: Encoder { var codingPath: [CodingKey] var userInfo: [CodingUserInfoKey: Any] var data: String? = nil init(transport: ActorTransport) { self.codingPath = [] self.userInfo = [.actorTransportKey: transport] } func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> { fatalError("Not implemented: \(#function)") } func unkeyedContainer() -> UnkeyedEncodingContainer { fatalError("Not implemented: \(#function)") } func singleValueContainer() -> SingleValueEncodingContainer { TestSingleValueEncodingContainer(parent: self) } class TestSingleValueEncodingContainer: SingleValueEncodingContainer { let parent: TestEncoder init(parent: TestEncoder) { self.parent = parent } var codingPath: [CodingKey] = [] func encodeNil() throws { fatalError("Not implemented: \(#function)") } func encode(_ value: Bool) throws { fatalError("Not implemented: \(#function)") } func encode(_ value: String) throws { } func encode(_ value: Double) throws { fatalError("Not implemented: \(#function)") } func encode(_ value: Float) throws { fatalError("Not implemented: \(#function)") } func encode(_ value: Int) throws { fatalError("Not implemented: \(#function)") } func encode(_ value: Int8) throws { fatalError("Not implemented: \(#function)") } func encode(_ value: Int16) throws { fatalError("Not implemented: \(#function)") } func encode(_ value: Int32) throws { fatalError("Not implemented: \(#function)") } func encode(_ value: Int64) throws { fatalError("Not implemented: \(#function)") } func encode(_ value: UInt) throws { fatalError("Not implemented: \(#function)") } func encode(_ value: UInt8) throws { fatalError("Not implemented: \(#function)") } func encode(_ value: UInt16) throws { fatalError("Not implemented: \(#function)") } func encode(_ value: UInt32) throws { fatalError("Not implemented: \(#function)") } func encode(_ value: UInt64) throws { fatalError("Not implemented: \(#function)") } func encode<T: Encodable>(_ value: T) throws { print("encode: \(value)") if let identity = value as? AnyActorIdentity { self.parent.data = (identity.underlying as! ActorAddress).address } } } func encode<Act: DistributedActor>(_ actor: Act) throws -> String { try actor.encode(to: self) return self.data! } } @available(SwiftStdlib 5.5, *) class TestDecoder: Decoder { let encoder: TestEncoder let data: String init(encoder: TestEncoder, transport: ActorTransport, data: String) { self.encoder = encoder self.userInfo = [.actorTransportKey: transport] self.data = data } var codingPath: [CodingKey] = [] var userInfo: [CodingUserInfoKey : Any] func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> where Key : CodingKey { fatalError("Not implemented: \(#function)") } func unkeyedContainer() throws -> UnkeyedDecodingContainer { fatalError("Not implemented: \(#function)") } func singleValueContainer() throws -> SingleValueDecodingContainer { TestSingleValueDecodingContainer(parent: self) } class TestSingleValueDecodingContainer: SingleValueDecodingContainer { let parent: TestDecoder init(parent: TestDecoder) { self.parent = parent } var codingPath: [CodingKey] = [] func decodeNil() -> Bool { fatalError("Not implemented: \(#function)") } func decode(_ type: Bool.Type) throws -> Bool { fatalError("Not implemented: \(#function)") } func decode(_ type: String.Type) throws -> String { print("decode String -> \(self.parent.data)") return self.parent.data } func decode(_ type: Double.Type) throws -> Double { fatalError("Not implemented: \(#function)") } func decode(_ type: Float.Type) throws -> Float { fatalError("Not implemented: \(#function)") } func decode(_ type: Int.Type) throws -> Int { fatalError("Not implemented: \(#function)") } func decode(_ type: Int8.Type) throws -> Int8 { fatalError("Not implemented: \(#function)") } func decode(_ type: Int16.Type) throws -> Int16 { fatalError("Not implemented: \(#function)") } func decode(_ type: Int32.Type) throws -> Int32 { fatalError("Not implemented: \(#function)") } func decode(_ type: Int64.Type) throws -> Int64 { fatalError("Not implemented: \(#function)") } func decode(_ type: UInt.Type) throws -> UInt { fatalError("Not implemented: \(#function)") } func decode(_ type: UInt8.Type) throws -> UInt8 { fatalError("Not implemented: \(#function)") } func decode(_ type: UInt16.Type) throws -> UInt16 { fatalError("Not implemented: \(#function)") } func decode(_ type: UInt32.Type) throws -> UInt32 { fatalError("Not implemented: \(#function)") } func decode(_ type: UInt64.Type) throws -> UInt64 { fatalError("Not implemented: \(#function)") } func decode<T>(_ type: T.Type) throws -> T where T : Decodable { fatalError("Not implemented: \(#function)") } } } // ==== Execute ---------------------------------------------------------------- @available(SwiftStdlib 5.5, *) func test() { let transport = FakeTransport() // CHECK: assign type:DA, address:ActorAddress(address: "xxx") let da = DA(transport: transport) // CHECK: encode: AnyActorIdentity(ActorAddress(address: "xxx")) // CHECK: FakeTransport.decodeIdentity from:main.TestDecoder let encoder = TestEncoder(transport: transport) let data = try! encoder.encode(da) // CHECK: decode String -> xxx // CHECK: decode ActorAddress -> ActorAddress(address: "xxx") let da2 = try! DA(from: TestDecoder(encoder: encoder, transport: transport, data: data)) // CHECK: decoded da2: DA(AnyActorIdentity(ActorAddress(address: "xxx"))) print("decoded da2: \(da2)") } @available(SwiftStdlib 5.5, *) @main struct Main { static func main() async { test() } }
apache-2.0
17b9efcd0460b5f456361b431c8b84d3
36.229358
114
0.666092
4.358754
false
true
false
false
andrea-prearo/ContactList
ContactList/Models/Phone.swift
1
677
// // Phone.swift // ContactList // // Created by Andrea Prearo on 3/19/16. // Copyright © 2016 Andrea Prearo // import Foundation import Marshal struct Phone { let label: String? let number: String? init(label: String?, number: String?) { self.label = label self.number = number } } extension Phone: Unmarshaling { init(object: MarshaledObject) { label = try? object.value(for: "label") number = try? object.value(for: "number") } } extension Phone: Equatable {} func ==(lhs: Phone, rhs: Phone) -> Bool { return lhs.label == rhs.label && lhs.number == rhs.number }
mit
6f44055d9731a4a0fdbda310953872f9
16.333333
49
0.58284
3.614973
false
false
false
false
maranathApp/GojiiFramework
GojiiFrameWork/NSDateExtensions.swift
1
10617
// // NSDateExtensions.swift // GojiiFrameWork // // Created by Stency Mboumba on 01/06/2017. // Copyright © 2017 Stency Mboumba. All rights reserved. // import Foundation /* * Date Extension * Inspired by : https://github.com/malcommac/SwiftDate * * - Convert Numbers * - Radians Degrees */ /* --------------------------------------------------------------------------- */ // MARK: - Operations with NSDate WITH DATES (==,!=,<,>,<=,>= /* --------------------------------------------------------------------------- */ //MARK: OPERATIONS WITH DATES (==,!=,<,>,<=,>=) extension NSDate {} /** NSDate == NSDate - returns: Bool */ public func == (left: NSDate, right: NSDate) -> Bool { return (left.compare(right as Date) == ComparisonResult.orderedSame) } /** NSDate != NSDate - returns: Bool */ public func != (left: NSDate, right: NSDate) -> Bool { return !(left == right) } /** NSDate < NSDate - returns: Bool */ public func < (left: NSDate, right: NSDate) -> Bool { return (left.compare(right as Date) == ComparisonResult.orderedAscending) } /** NSDate > NSDate - returns: Bool */ public func > (left: NSDate, right: NSDate) -> Bool { return (left.compare(right as Date) == ComparisonResult.orderedDescending) } /** NSDate <= NSDate - returns: Bool */ public func <= (left: NSDate, right: NSDate) -> Bool { return !(left > right) } /** NSDate >= - returns: Bool */ public func >= (left: NSDate, right: NSDate) -> Bool { return !(left < right) } /* --------------------------------------------------------------------------- */ // MARK: - ARITHMETIC OPERATIONS WITH DATES (-,-=,+,+=) /* --------------------------------------------------------------------------- */ /** NSDate - 1.day - returns: NSDate */ public func - (left : NSDate, right: TimeInterval) -> NSDate { return left.addingTimeInterval(-right) } /** NSDate -= 1.month */ public func -= ( left: inout NSDate, right: TimeInterval) { left = left.addingTimeInterval(-right) } /** NSDate + 1.year - returns: NSDate */ public func + (left: NSDate, right: TimeInterval) -> NSDate { return left.addingTimeInterval(right) } /** NSDate += 1.month */ public func += ( left: inout NSDate, right: TimeInterval) { left = left.addingTimeInterval(right) } // MARK: - Extension NSDate BSFramework public extension Date { /* --------------------------------------------------------------------------- */ // MARK: - Get days functions /* --------------------------------------------------------------------------- */ /// Get the day component of the date public var day: Int { get { return components.day! } } /// Get the month component of the date public var month : Int { get { return components.month! } } /// Get the year component of the date public var year : Int { get { return components.year! } } /// Get the hour component of the date public var hour: Int { get { return components.hour! } } /// Get the minute component of the date public var minute: Int { get { return components.minute! } } /// Get the second component of the date public var second: Int { get { return components.second! } } /// Get the era component of the date public var era: Int { get { return components.era! } } /// Get the week of the month component of the date public var weekOfMonth: Int { get { return components.weekOfMonth! } } /// Get the week of the month component of the date public var weekOfYear: Int { get { return components.weekOfYear! } } /// Get the weekday component of the date public var weekday: Int { get { return components.weekday! } } /// Get the weekday ordinal component of the date public var weekdayOrdinal: Int { get { return components.weekdayOrdinal! } } /* --------------------------------------------------------------------------- */ // MARK: - To ( Converted ) /* --------------------------------------------------------------------------- */ public func toString (format: String) -> String { let formatter = DateFormatter () formatter.locale = NSLocale.current formatter.dateFormat = format return formatter.string(from: self as Date) } public func toTimeStamp() -> String { let timeInterval = self.timeIntervalSince1970 let result = String(format: "/Date(%.0f000)/", arguments:[timeInterval]) return result } /* --------------------------------------------------------------------------- */ // MARK: - Create days functions /* --------------------------------------------------------------------------- */ /** Create a new NSDate instance based on refDate (if nil uses current date) and set components :param: refDate reference date instance (nil to use NSDate()) :param: year year component (nil to leave it untouched) :param: month month component (nil to leave it untouched) :param: day day component (nil to leave it untouched) :param: tz time zone component (it's the abbreviation of NSTimeZone, like 'UTC' or 'GMT+2', nil to use current time zone) :returns: a new NSDate with components changed according to passed params */ public static func date(refDate: Date? = nil, year: Int? = nil, month: Int? = nil, day:Int? = nil, hour: Int? = nil, minute: Int? = nil, second: Int? = nil, tz: String? = nil) -> Date { let referenceDate = refDate ?? Date() return referenceDate.set(year: year, month: month, day: day, hour: hour, minute: minute, second: second, tz: tz)! as Date } /* --------------------------------------------------------------------------- */ // MARK: - Create day by Today, Yesteday, Tomorrow /* --------------------------------------------------------------------------- */ /** Return a new NSDate instance with the current date and time set to 00:00:00 :param: tz optional timezone abbreviation :returns: a new NSDate instance of the today's date */ public static func today() -> Date { let nowDate = Date() return Date.date(refDate: nowDate, year: nowDate.year, month: nowDate.month, day: nowDate.day) as Date } /** Return a new NSDate istance with the current date minus one day :param: tz optional timezone abbreviation :returns: a new NSDate instance which represent yesterday's date */ public static func yesterday() -> NSDate { return (today() as NSDate)-1.day } /** Return a new NSDate istance with the current date plus one day :param: tz optional timezone abbreviation :returns: a new NSDate instance which represent tomorrow's date */ public static func tomorrow() -> NSDate { return (today() as NSDate)+1.day } /* --------------------------------------------------------------------------- */ // MARK: - Is ( Tested ) /* --------------------------------------------------------------------------- */ /// Return true if the date is the weekend public var isWeekend:Bool { let calendar = Calendar.current return calendar.isDateInWeekend(self as Date) } /// Return true if current date's day is not a weekend day public var isWeekday:Bool { return !self.isWeekend } /* --------------------------------------------------------------------------- */ // MARK: - Private Create Day /* --------------------------------------------------------------------------- */ /** Individual set single component of the current date instance :param: year a non-nil value to change the year component of the instance :param: month a non-nil value to change the month component of the instance :param: day a non-nil value to change the day component of the instance :param: hour a non-nil value to change the hour component of the instance :param: minute a non-nil value to change the minute component of the instance :param: second a non-nil value to change the second component of the instance :param: tz a non-nil value (timezone abbreviation string as for NSTimeZone) to change the timezone component of the instance :returns: a new NSDate instance with changed values */ private func set(year: Int? = nil, month: Int? = nil, day: Int? = nil, hour: Int? = nil, minute: Int? = nil, second: Int? = nil, tz: String? = nil) -> Date! { var components = self.components components.year = year ?? self.year components.month = month ?? self.month components.day = day ?? self.day components.hour = hour ?? self.hour components.minute = minute ?? self.minute components.second = second ?? self.second components.timeZone = (tz != nil ? TimeZone(abbreviation: tz!) : TimeZone.current) return Calendar.current.date(from: components) } /* --------------------------------------------------------------------------- */ /* Components */ /* --------------------------------------------------------------------------- */ /// Specify calendrical units such as day and month private static var componentFlags:NSCalendar.Unit { return [NSCalendar.Unit.year , NSCalendar.Unit.month , NSCalendar.Unit.day, NSCalendar.Unit.weekOfYear, NSCalendar.Unit.hour , NSCalendar.Unit.minute , NSCalendar.Unit.second , NSCalendar.Unit.weekday , NSCalendar.Unit.weekdayOrdinal, NSCalendar.Unit.weekOfYear] } /// Return the NSDateComponents which represent current date private var components: DateComponents { //NSDate.componentFlags, fromDate: self return Calendar.current.dateComponents(in: TimeZone.current, from: self as Date) } }
mit
ca69add318fbe39c92ac7c2099cb4821
31.072508
192
0.511492
4.90573
false
false
false
false
StachkaConf/ios-app
StachkaIOS/StachkaIOS/Classes/Application/Coordinator/ApplicationCoordinatorImplementation.swift
1
3622
// // ApplicationCoordinatorImplementation.swift // StachkaIOS // // Created by m.rakhmanov on 25.03.17. // Copyright © 2017 m.rakhmanov. All rights reserved. // import UIKit import RectangleDissolve import RxSwift import RxCocoa class ApplicationCoordinatorImplementation: ApplicationCoordinator, CoordinatorWithDependencies { enum Constants { static let animationDelay = 0.5 static let animatorConfiguration = RectangleDissolveAnimatorConfiguration(rectanglesVertical: 14, rectanglesHorizontal: 8, batchSize: 10, fadeAnimationDuration: 0.5, tempo: 1000.0) } private weak var window: UIWindow? private var tabBarController: UITabBarController private var onboardingModuleAssembly: ModuleAssembly private var initialUserStoriesCoordinatorsFactory: InitialUserStoriesCoordinatorsFactory var childCoordinators: [Coordinator] = [] private let disposeBag = DisposeBag() init(window: UIWindow?, rootTabBarController: UITabBarController, onboardingModuleAssembly: ModuleAssembly, initialUserStoriesCoordinatorsFactory: InitialUserStoriesCoordinatorsFactory) { self.window = window self.tabBarController = rootTabBarController self.onboardingModuleAssembly = onboardingModuleAssembly self.initialUserStoriesCoordinatorsFactory = initialUserStoriesCoordinatorsFactory } func start() { let talksNavigationController = UINavigationController() //tabBarController.embed(viewController: talksNavigationController) let talksCoordinator = initialUserStoriesCoordinatorsFactory.talksCoordinator(rootNavigationController: talksNavigationController) add(coordinator: talksCoordinator) talksCoordinator.start() // let favouritesNavigationController = UINavigationController() // tabBarController.embed(viewController: favouritesNavigationController) // let favouritesCoordinator = initialUserStoriesCoordinatorsFactory.favouritesCoordinator(rootNavigationController: favouritesNavigationController) // add(coordinator: favouritesCoordinator) // favouritesCoordinator.start() createDismissOnboarding(andShow: talksNavigationController) .subscribe() .disposed(by: disposeBag) } // MARK: Private private func createDismissOnboarding(andShow viewController: UIViewController) -> Observable<Void> { return Observable.create { [weak self] observer in guard let strongSelf = self else { observer.onCompleted() return Disposables.create() } let onboarding = strongSelf.onboardingModuleAssembly.module() let animator = RectangleDissolveAnimator(configuration: Constants.animatorConfiguration) strongSelf.window?.rootViewController = onboarding strongSelf.window?.makeKeyAndVisible() DispatchQueue.main.asyncAfter(deadline: .now() + Constants.animationDelay) { viewController.transitioningDelegate = animator onboarding.present(viewController, animated: true, completion: { observer.onCompleted() }) } return Disposables.create() } } }
mit
28c4ed12820f678c59b5cbd2eaffa7ec
41.104651
155
0.657829
6.386243
false
false
false
false
StachkaConf/ios-app
StachkaIOS/StachkaIOS/Classes/User Stories/Talks/PresentationInfo/View/PresentationInfoViewController.swift
1
2306
// // FeedViewController.swift // StachkaIOS // // Created by m.rakhmanov on 26.03.17. // Copyright © 2017 m.rakhmanov. All rights reserved. // import UIKit import RxCocoa import RxSwift import RxDataSources class PresentationInfoViewController: UIViewController { enum Constants { static let title = "О докладе" } typealias PresentationDataSource = RxCustomTableViewDelegateDataSource<CellSectionModel> fileprivate let heightCalculator = TableViewHeightCalculatorImplementation() var viewModel: PresentationInfoViewModel? private let disposeBag = DisposeBag() private let dataSource = PresentationDataSource() @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() title = Constants.title setupTableView() setupBindings() } private func setupTableView() { tableView.register(PresentationInfoCell.self) tableView.register(AuthorInfoCell.self) tableView.register(AuthorBriefInfoCell.self) tableView.register(PresentationDescriptionCell.self) tableView.register(AuthorImageCell.self) dataSource.configureCell = { (dataSource: TableViewSectionedDataSource<CellSectionModel>, tableView: UITableView, indexPath: IndexPath, item: CellViewModel) in let cell = tableView.dequeueCell(item.associatedCell) cell.configure(with: item) return cell as! UITableViewCell } dataSource.configureCellHeight = { [weak self] item, tableView, indexPath in guard let strongSelf = self else { return 0 } return strongSelf.heightCalculator.height(for: indexPath.row, viewModel: item, tableView: tableView) } //dataSource.titleForHeaderInSection = nil } private func setupBindings() { viewModel? .presentationModels .bindTo(tableView.rx.items(dataSource: dataSource)) .disposed(by: disposeBag) tableView.rx .setDelegate(dataSource) .disposed(by: disposeBag) } } extension PresentationInfoViewController: PresentationInfoView { }
mit
23c91fa7757d90f50f471fedd4de92de
30.465753
112
0.65825
5.561743
false
false
false
false
AkshayNG/iSwift
iSwift/Extensions/UIView+Extension.swift
1
4665
// // UIView+Extension.swift // All List // // Created by Amol Bapat on 30/11/16. // Copyright © 2016 Olive. All rights reserved. // import UIKit extension UIView { func moveUp(distance:CGFloat) { var rect = self.frame rect.origin.y -= distance UIView.animate(withDuration: 0.3) { self.frame = rect; } } func moveDown(distance:CGFloat) { var rect = self.frame rect.origin.y += distance UIView.animate(withDuration: 0.1) { self.frame = rect; } } class func loadFromNib(withName nibNamed: String, bundle: Bundle?) -> UIView? { return UINib( nibName: nibNamed, bundle: bundle ).instantiate(withOwner: nil, options: nil)[0] as? UIView } @objc func gradientBackground(withColors colors:[UIColor], maskView:UIView?) { if hasGradientLayer() { return } let gradientLayer = CAGradientLayer() var cgColors:[CGColor] = [] for color in colors { cgColors.append(color.cgColor) } gradientLayer.colors = cgColors //Vertical //gradientLayer.startPoint = CGPoint.init(x: 0.5, y: 0) //gradientLayer.endPoint = CGPoint.init(x: 0.5, y: 1) //Horizontal gradientLayer.startPoint = CGPoint.init(x: 0, y: 0.5) gradientLayer.endPoint = CGPoint.init(x: 1, y: 0.5) gradientLayer.frame = self.bounds gradientLayer.accessibilityHint = "GradientLayer" self.layer.insertSublayer(gradientLayer, at: 0) self.mask = maskView } @objc func gradientBorder(colors:[UIColor], width:CGFloat, radius:CGFloat) { if hasGradientLayer() { return } let gradient = CAGradientLayer() gradient.frame = CGRect(origin: CGPoint.zero, size: self.frame.size) gradient.startPoint = CGPoint.init(x: 0, y: 0.5) gradient.endPoint = CGPoint.init(x: 1.0, y: 0.5) gradient.colors = colors.map({$0.cgColor}) gradient.cornerRadius = radius let shape = CAShapeLayer() shape.lineWidth = width shape.path = UIBezierPath.init(roundedRect: self.bounds, cornerRadius: radius).cgPath shape.strokeColor = UIColor.black.cgColor shape.fillColor = UIColor.clear.cgColor gradient.mask = shape gradient.accessibilityHint = "GradientLayer" self.layer.addSublayer(gradient) } @objc func hasGradientLayer() -> Bool { if let layers = self.layer.sublayers { for layer in layers { if layer.accessibilityHint == "GradientLayer" { return true } } } return false } @objc func removeGradientLayer() { if let layers = self.layer.sublayers { for layer in layers { if layer.accessibilityHint == "GradientLayer" { layer.removeFromSuperlayer() break } } } } @objc func flip(toView:UIView) { let transitionOptions: UIViewAnimationOptions = [.transitionFlipFromRight, .showHideTransitionViews] UIView.transition(with: self, duration: 1.0, options: transitionOptions, animations: { self.isHidden = true }) UIView.transition(with: toView, duration: 1.0, options: transitionOptions, animations: { toView.isHidden = false }) } @objc func bounce() { self.transform = CGAffineTransform.init(scaleX: 0.5, y: 0.5) UIView.animate(withDuration: 1.0, delay: 0, usingSpringWithDamping: 0.25, initialSpringVelocity: 5.0, options: .allowUserInteraction, animations: { self.transform = .identity }, completion: nil) } func findFirstResponder() -> UIView? { if (self.isFirstResponder) { return self } for subView in self.subviews { let firstResponder = subView.findFirstResponder() if firstResponder != nil { return firstResponder } } return nil } func applyShadow(withRadius radius:CGFloat) { self.layer.cornerRadius = radius self.layer.shadowColor = UIColor.lightGray.cgColor self.layer.shadowOffset = CGSize(width: 0.0, height: 4.0) self.layer.shadowOpacity = 0.5 self.layer.masksToBounds = false } }
mit
acac0408bee17dd7e976e9b6a54e7784
28.518987
155
0.56711
4.711111
false
false
false
false
gregorysholl/mocha-utilities
MochaUtilities/Classes/Network/Domain/MochaEmailAttachment.swift
1
1103
// // MochaEmailAttachment.swift // Pods // // Created by Gregory Sholl e Santos on 18/07/17. // // import UIKit // MARK: - public class MochaEmailAttachment { // MARK: Variables let data : Data let type : String let filename: String // MARK: Inits ///compressionQuality is a number between 0.0 and 1.0 public init?(jpegImage: UIImage, compressionQuality: CGFloat = 1.0, filename filenameParam: String) { guard let jpegData = jpegImage.jpegData(compressionQuality: compressionQuality) else { return nil } data = jpegData type = "image/jpeg" filename = filenameParam } public init?(pngImage: UIImage, filename filenameParam: String) { guard let pgnData = pngImage.pngData() else { return nil } data = pgnData type = "image/png" filename = filenameParam } public init(data dataParam: Data, type typeParam: String, filename filenameParam: String) { data = dataParam type = typeParam filename = filenameParam } }
mit
5aeb1a723a5a26dfade311514c429e3f
22.468085
105
0.618314
4.242308
false
false
false
false
lady12/firefox-ios
Client/Frontend/Browser/SearchLoader.swift
18
4086
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import Storage import XCGLogger private let log = Logger.browserLogger private let URLBeforePathRegex = try! NSRegularExpression(pattern: "^https?://([^/]+/)", options: []) // TODO: Swift currently requires that classes extending generic classes must also be generic. // This is a workaround until that requirement is fixed. typealias SearchLoader = _SearchLoader<AnyObject, AnyObject> /** * Shared data source for the SearchViewController and the URLBar domain completion. * Since both of these use the same SQL query, we can perform the query once and dispatch the results. */ class _SearchLoader<UnusedA, UnusedB>: Loader<Cursor<Site>, SearchViewController> { private let history: BrowserHistory private let urlBar: URLBarView private var inProgress: Cancellable? = nil init(history: BrowserHistory, urlBar: URLBarView) { self.history = history self.urlBar = urlBar super.init() } var query: String = "" { didSet { if query.isEmpty { self.load(Cursor(status: .Success, msg: "Empty query")) return } if let inProgress = inProgress { inProgress.cancel() self.inProgress = nil } let deferred = self.history.getSitesByFrecencyWithLimit(100, whereURLContains: query) inProgress = deferred as? Cancellable deferred.uponQueue(dispatch_get_main_queue()) { result in self.inProgress = nil // Failed cursors are excluded in .get(). if let cursor = result.successValue { self.load(cursor) self.urlBar.setAutocompleteSuggestion(self.getAutocompleteSuggestion(cursor)) } } } } private func getAutocompleteSuggestion(cursor: Cursor<Site>) -> String? { for result in cursor { // Extract the pre-path substring from the URL. This should be more efficient than parsing via // NSURL since we need to only look at the beginning of the string. // Note that we won't match non-HTTP(S) URLs. if let url = result?.url, match = URLBeforePathRegex.firstMatchInString(url, options: NSMatchingOptions(), range: NSRange(location: 0, length: url.characters.count)) { // If the pre-path component starts with the filter, just use it as is. let prePathURL = (url as NSString).substringWithRange(match.rangeAtIndex(0)) if prePathURL.startsWith(query) { return prePathURL } // Otherwise, find and use any matching domain. // To simplify the search, prepend a ".", and search the string for ".query". // For example, for http://en.m.wikipedia.org, domainWithDotPrefix will be ".en.m.wikipedia.org". // This allows us to use the "." as a separator, so we can match "en", "m", "wikipedia", and "org", let domain = (url as NSString).substringWithRange(match.rangeAtIndex(1)) let domainWithDotPrefix: String = ".\(domain)" if let range = domainWithDotPrefix.rangeOfString(".\(query)", options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil, locale: nil) { // We don't actually want to match the top-level domain ("com", "org", etc.) by itself, so // so make sure the result includes at least one ".". let matchedDomain: String = domainWithDotPrefix.substringFromIndex(range.startIndex.advancedBy(1)) if matchedDomain.contains(".") { return matchedDomain } } } } return nil } }
mpl-2.0
f156e8ac81798cceb9b9c4ef7f68bb95
43.413043
160
0.610377
4.989011
false
false
false
false
nerd0geek1/TableViewManager
TableViewManagerTests/classes/implementation/SectionDataSpec.swift
1
3312
// // SectionDataSpec.swift // TableViewManager // // Created by Kohei Tabata on 2016/07/04. // Copyright © 2016年 Kohei Tabata. All rights reserved. // import Quick import Nimble class SectionDataSpec: QuickSpec { override func spec() { describe("SectionData") { describe("numberOfRows()", { context("when initialized with empty array", { it("will return 0", closure: { let sectionData: SectionData = SectionData(rowDataList: []) expect(sectionData.numberOfRows()).to(equal(0)) }) }) context("when initialized with not empty array", { it("will return passed array count", closure: { let numberOfRows: Int = 10 let rowDataList: [RowData] = [Int](0..<numberOfRows).map({ _ in RowData() }) let sectionData: SectionData = SectionData(rowDataList: rowDataList) expect(sectionData.numberOfRows()).to(equal(numberOfRows)) }) }) }) describe("rowData(at index: Int)", { class DummyRowData: RowData { let index: Int let title: String init(index: Int) { self.index = index self.title = "title\(index)" } } context("with invalid index", { it("will return nil", closure: { let rowDataList: [DummyRowData] = [Int](0..<10).map({ DummyRowData.init(index: $0) }) let sectionData: SectionData = SectionData(rowDataList: rowDataList) expect(sectionData.rowData(at: -1)).to(beNil()) expect(sectionData.rowData(at: 10)).to(beNil()) }) }) context("with valid index", { it("will return RowData at selected index", closure: { let rowDataList: [DummyRowData] = [Int](0..<10).map({ DummyRowData.init(index: $0) }) let sectionData: SectionData = SectionData(rowDataList: rowDataList) let firstRowData: DummyRowData? = sectionData.rowData(at: 0) as? DummyRowData let middleRowData: DummyRowData? = sectionData.rowData(at: 4) as? DummyRowData let lastRowData: DummyRowData? = sectionData.rowData(at: 9) as? DummyRowData expect(firstRowData).notTo(beNil()) expect(firstRowData!.index).to(equal(0)) expect(firstRowData!.title).to(equal("title0")) expect(middleRowData).notTo(beNil()) expect(middleRowData!.index).to(equal(4)) expect(middleRowData!.title).to(equal("title4")) expect(lastRowData).notTo(beNil()) expect(lastRowData!.index).to(equal(9)) expect(lastRowData!.title).to(equal("title9")) }) }) }) } } }
mit
f1edc8b21a43bb6932d324d4426d1962
41.974026
109
0.48353
5.122291
false
false
false
false
practicalswift/swift
validation-test/compiler_crashers_2_fixed/0060-sr2702.swift
30
2120
// RUN: %target-swift-frontend %s -emit-ir // RUN: %target-swift-frontend %s -emit-ir -O // REQUIRES: objc_interop import Foundation /// This function returns true if inspectedClass is subclass of wantedSuperclass. /// This is achieved by climbing the class tree hierarchy using class_getSuperclass /// runtime function. This is useful when examining classes that do not have /// NSObject as root (e.g. NSProxy subclasses). private func XUClassKindOfClass(_ inspectedClass: AnyClass?, wantedSuperclass: AnyClass?) -> Bool { // We've hit the root, so no, it's not if inspectedClass == nil { return false } // It's the class, yay! if inspectedClass == wantedSuperclass { return true } // Recursively call the function on the superclass of inspectedClass return XUClassKindOfClass(class_getSuperclass(inspectedClass), wantedSuperclass: wantedSuperclass) } /// Works pretty much as +isKindOfClass: on NSObject, but will work fine even with /// NSProxy subclasses, which do not respond to +isKindOfClass: public func XUClassIsSubclassOfClass(_ superclass: AnyClass, subclass: AnyClass) -> Bool { return XUClassKindOfClass(subclass, wantedSuperclass: superclass) } /// Returns a list of subclasses of class T. Doesn't include the root T class. public func XUAllSubclassesOfClass<T: AnyObject>(_ aClass: T.Type) -> [T.Type] { var result: [T.Type] = [] var numClasses: Int32 = 0 // Get the number of classes in the ObjC runtime numClasses = objc_getClassList(nil, 0) if numClasses > 0 { // Get them all let memory = malloc(MemoryLayout<AnyClass>.size * Int(numClasses))! defer { free(memory) } let classesPtr = memory.assumingMemoryBound(to: AnyClass.self) let classes = AutoreleasingUnsafeMutablePointer<AnyClass>(classesPtr) numClasses = objc_getClassList(classes, numClasses) for i in 0 ..< Int(numClasses) { // Go through the classes, find out if the class is kind of aClass // and then add it to the list let cl = classes[i] if XUClassKindOfClass(cl, wantedSuperclass: aClass) && cl != aClass { result.append(cl as! T.Type) } } } return result }
apache-2.0
f2e365dc030d6aa909093951e9f95ec1
31.121212
99
0.73066
3.706294
false
false
false
false
huangboju/Moots
Examples/边缘侧滑/MagicMove-master/MagicMove/Transition/PresentingTransion.swift
1
1233
// // MagicMovePushTransion.swift // MagicMove // // Created by xiAo_Ju on 2018/6/12. // Copyright © 2018 Bourne. All rights reserved. // import UIKit class PresentingTransion: NSObject, UIViewControllerAnimatedTransitioning { func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.25 } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { guard let toView = transitionContext.view(forKey: .to), let toVC = transitionContext.viewController(forKey: .to) else { return } let presentedFrame = transitionContext.finalFrame(for: toVC) let containerView = transitionContext.containerView containerView.addSubview(toView) let x = containerView.frame.width - toView.bounds.minX toView.frame.origin.x = x UIView.animate(withDuration: transitionDuration(using: transitionContext), delay: 0, options: .curveEaseInOut, animations: { toView.frame = presentedFrame }, completion: { _ in transitionContext.completeTransition(!transitionContext.transitionWasCancelled) }) } }
mit
8864806f6b1e2ee1311f166fc0451b41
33.222222
132
0.693182
5.475556
false
false
false
false
huangboju/Moots
Examples/Lumia/Lumia/Component/CustomPaging/Table/TableCellInfo.swift
1
599
// // TableCellInfo.swift // CustomPaging // // Created by Ilya Lobanov on 04/08/2018. // Copyright © 2018 Ilya Lobanov. All rights reserved. // import UIKit struct TableCellInfo { var text: String var textColor: UIColor var bgColor: UIColor var height: CGFloat var font: UIFont } extension UITableViewCell { func update(with info: TableCellInfo) { textLabel?.textAlignment = .center textLabel?.text = info.text textLabel?.textColor = info.textColor textLabel?.font = info.font backgroundColor = info.bgColor } }
mit
8fbf0ca90554674781ec4340cdfc3150
19.62069
55
0.653846
4.271429
false
false
false
false
huangboju/Moots
UICollectionViewLayout/Blueprints-master/Example-OSX/RootViewController.swift
1
1253
import Cocoa class RootViewController: NSViewController { private var current: NSViewController init<T: NSViewController>(withNibName nibName: String, controllerType: T.Type) { let controller = T(nibName: nibName, bundle: nil) current = controller super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { fatalError() } override func loadView() { self.view = NSView() } override func viewWillAppear() { super.viewWillAppear() addCurrentView() } } private extension RootViewController { func addCurrentView() { view.addSubview(current.view) configureCurrentViewsConstraints() } func configureCurrentViewsConstraints() { current.view.translatesAutoresizingMaskIntoConstraints = false current.view.topAnchor.constraint(equalTo: view.topAnchor, constant: 0).isActive = true current.view.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0).isActive = true current.view.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0).isActive = true current.view.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true } }
mit
7b48f1a2b16bd7c5c7f3ccae70960ca2
28.139535
105
0.691141
4.952569
false
false
false
false
huangboju/Moots
UICollectionViewLayout/SectionReactor-master/Examples/ArticleFeed/ArticleFeed/Sources/Sections/ArticleSectionDelegate.swift
1
6248
// // ArticleSectionDelegate.swift // ArticleFeed // // Created by Suyeol Jeon on 09/09/2017. // Copyright © 2017 Suyeol Jeon. All rights reserved. // import ReusableKit import SectionReactor import UICollectionViewFlexLayout final class ArticleSectionDelegate: SectionDelegateType { typealias SectionReactor = ArticleSectionReactor fileprivate enum Reusable { static let authorCell = ReusableCell<ArticleCardAuthorCell>() static let textCell = ReusableCell<ArticleCardTextCell>() static let reactionCell = ReusableCell<ArticleCardReactionCell>() static let commentCell = ReusableCell<ArticleCardCommentCell>() static let sectionBackgroundView = ReusableView<CollectionBorderedBackgroundView>() static let itemBackgroundView = ReusableView<CollectionBorderedBackgroundView>() } func registerReusables(to collectionView: UICollectionView) { collectionView.register(Reusable.authorCell) collectionView.register(Reusable.textCell) collectionView.register(Reusable.reactionCell) collectionView.register(Reusable.commentCell) collectionView.register(Reusable.sectionBackgroundView, kind: UICollectionElementKindSectionBackground) collectionView.register(Reusable.itemBackgroundView, kind: UICollectionElementKindItemBackground) } func cell( collectionView: UICollectionView, indexPath: IndexPath, sectionItem: SectionItem, articleCardAuthorCellDependency: ArticleCardAuthorCell.Dependency, articleCardTextCellDependency: ArticleCardTextCell.Dependency, articleCardReactionCellDependency: ArticleCardReactionCell.Dependency ) -> UICollectionViewCell { switch sectionItem { case let .author(cellReactor): let cell = collectionView.dequeue(Reusable.authorCell, for: indexPath) cell.dependency = articleCardAuthorCellDependency cell.reactor = cellReactor return cell case let .text(cellReactor): let cell = collectionView.dequeue(Reusable.textCell, for: indexPath) cell.dependency = articleCardTextCellDependency cell.reactor = cellReactor return cell case let .reaction(cellReactor): let cell = collectionView.dequeue(Reusable.reactionCell, for: indexPath) cell.dependency = articleCardReactionCellDependency cell.reactor = cellReactor return cell case let .comment(cellReactor): let cell = collectionView.dequeue(Reusable.commentCell, for: indexPath) cell.reactor = cellReactor return cell } } func background( collectionView: UICollectionView, kind: String, indexPath: IndexPath, sectionItems: [SectionItem] ) -> UICollectionReusableView { switch kind { case UICollectionElementKindSectionBackground: let view = collectionView.dequeue(Reusable.sectionBackgroundView, kind: kind, for: indexPath) view.backgroundColor = .white view.borderedLayer?.borders = [.top, .bottom] return view case UICollectionElementKindItemBackground: let view = collectionView.dequeue(Reusable.itemBackgroundView, kind: kind, for: indexPath) switch sectionItems[indexPath.item] { case .comment: view.backgroundColor = 0xFAFAFA.color if self.isFirstComment(indexPath, in: sectionItems) { view.borderedLayer?.borders = [.top] } else if self.isLast(indexPath, in: collectionView) { view.borderedLayer?.borders = [.bottom] } else { view.borderedLayer?.borders = [] } default: view.backgroundColor = .white view.borderedLayer?.borders = [] } return view default: return collectionView.emptyView(for: indexPath, kind: kind) } } func cellVerticalSpacing( sectionItem: SectionItem, nextSectionItem: SectionItem ) -> CGFloat { switch (sectionItem, nextSectionItem) { case (.comment, .comment): return 0 case (_, .comment): return 15 case (.author, _): return 10 case (.text, _): return 10 case (.reaction, _): return 10 case (.comment, _): return 10 } } func cellMargin( collectionView: UICollectionView, layout: UICollectionViewFlexLayout, indexPath: IndexPath, sectionItem: SectionItem ) -> UIEdgeInsets { switch sectionItem { case .comment: let sectionPadding = layout.padding(forSectionAt: indexPath.section) let isLast = self.isLast(indexPath, in: collectionView) return UIEdgeInsets( top: 0, left: -sectionPadding.left, bottom: isLast ? -sectionPadding.bottom : 0, right: -sectionPadding.right ) default: return .zero } } func cellPadding( layout: UICollectionViewFlexLayout, indexPath: IndexPath, sectionItem: SectionItem ) -> UIEdgeInsets { switch sectionItem { case .comment: let sectionPadding = layout.padding(forSectionAt: indexPath.section) return UIEdgeInsets( top: 10, left: sectionPadding.left, bottom: 10, right: sectionPadding.right ) default: return .zero } } func cellSize(maxWidth: CGFloat, sectionItem: SectionItem) -> CGSize { switch sectionItem { case let .author(cellReactor): return Reusable.authorCell.class.size(width: maxWidth, reactor: cellReactor) case let .text(cellReactor): return Reusable.textCell.class.size(width: maxWidth, reactor: cellReactor) case let .reaction(cellReactor): return Reusable.reactionCell.class.size(width: maxWidth, reactor: cellReactor) case let .comment(cellReactor): return Reusable.commentCell.class.size(width: maxWidth, reactor: cellReactor) } } // MARK: Utils private func isFirstComment(_ indexPath: IndexPath, in sectionItems: [SectionItem]) -> Bool { let prevItemIndex = indexPath.item - 1 guard sectionItems.indices.contains(prevItemIndex) else { return true } if case .comment = sectionItems[prevItemIndex] { return false } else { return true } } private func isLast(_ indexPath: IndexPath, in collectionView: UICollectionView) -> Bool { let lastItem = collectionView.numberOfItems(inSection: indexPath.section) - 1 return indexPath.item == lastItem } }
mit
ccfbfc45988d6e89e21d3eadf7671635
31.201031
107
0.710741
4.915028
false
false
false
false
jpush/jpush-swift-demo
JPushSwiftDemo/setLocalNotificationViewController.swift
1
3268
// // setLocalNotificationViewController.swift // jpush-swift-demo // // Created by oshumini on 16/1/21. // Copyright © 2016年 HuminiOS. All rights reserved. // import UIKit class setLocalNotificationViewController: UIViewController,UITextFieldDelegate,UIGestureRecognizerDelegate { @IBOutlet weak var notificationDatePicker: UIDatePicker! @IBOutlet weak var notificationBodyTextField: UITextField! @IBOutlet weak var notificationButtonTextField: UITextField! @IBOutlet weak var notificationIdentifierTextField: UITextField! @IBOutlet weak var notificationBadgeTextField: UITextField! var localnotif:UILocalNotification? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let gesture = UITapGestureRecognizer(target: self, action:#selector(setLocalNotificationViewController.handleTap(_:))) gesture.delegate = self self.view.addGestureRecognizer(gesture) } @objc func handleTap(_ recognizer: UITapGestureRecognizer) { UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func setNotification(_ sender: AnyObject) { localnotif = JPUSHService.setLocalNotification(notificationDatePicker.date, alertBody: notificationBodyTextField.text, badge: Int32(notificationBadgeTextField.text!)!, alertAction: notificationButtonTextField.text, identifierKey: notificationIdentifierTextField.text, userInfo: nil, soundName: nil) var result:String? if localnotif != nil { result = "设置本地通知成功" } else { result = "设置本地通知失败" } let alert = UIAlertView(title: "设置", message: result, delegate: self, cancelButtonTitle: "确定") alert.show() } func clearAllInput() { notificationBadgeTextField.text = "" notificationBodyTextField.text = "" notificationButtonTextField.text = "" notificationIdentifierTextField.text = "" notificationDatePicker.date = Date().addingTimeInterval(0) } @IBAction func clearAllNotification(_ sender: AnyObject) { JPUSHService.clearAllLocalNotifications() let alert = UIAlertView(title: "设置", message: "取消所有本地通知成功", delegate: self, cancelButtonTitle: "确定") alert.show() } @IBAction func clearLastNotification(_ sender: AnyObject) { var alertMessage:String? if localnotif != nil { JPUSHService.delete(localnotif) localnotif = nil alertMessage = "取消上一个通知成功" } else { alertMessage = "不存在上一个设置通知" } let alert = UIAlertView(title: "设置", message: alertMessage, delegate: self, cancelButtonTitle: "确定") alert.show() } func textFieldDidBeginEditing(_ textField: UITextField) { } func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { if textField.tag != 10 { return true } return true } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } }
mit
49c999d37e8c03a5dd59cd702d0500c5
32.88172
302
0.729927
4.803354
false
false
false
false
ppamorim/Gradle-OSX
Gradle OSX/Extension/NSColor.swift
1
1789
import AppKit extension NSColor { public convenience init(rgba: String) { var red: CGFloat = 0.0 var green: CGFloat = 0.0 var blue: CGFloat = 0.0 var alpha: CGFloat = 1.0 if rgba.hasPrefix("#") { let index = rgba.startIndex.advancedBy(1) let hex = rgba.substringFromIndex(index) let scanner = NSScanner(string: hex) var hexValue: CUnsignedLongLong = 0 if scanner.scanHexLongLong(&hexValue) { switch (hex.characters.count) { case 3: red = CGFloat((hexValue & 0xF00) >> 8) / 15.0 green = CGFloat((hexValue & 0x0F0) >> 4) / 15.0 blue = CGFloat(hexValue & 0x00F) / 15.0 case 4: red = CGFloat((hexValue & 0xF000) >> 12) / 15.0 green = CGFloat((hexValue & 0x0F00) >> 8) / 15.0 blue = CGFloat((hexValue & 0x00F0) >> 4) / 15.0 alpha = CGFloat(hexValue & 0x000F) / 15.0 case 6: red = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0 green = CGFloat((hexValue & 0x00FF00) >> 8) / 255.0 blue = CGFloat(hexValue & 0x0000FF) / 255.0 case 8: red = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0 green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0 blue = CGFloat((hexValue & 0x0000FF00) >> 8) / 255.0 alpha = CGFloat(hexValue & 0x000000FF) / 255.0 default: print("Invalid RGB string, number of characters after '#' should be either 3, 4, 6 or 8") } } else { print("Scan hex error") } } else { print("Invalid RGB string, missing '#' as prefix") } self.init(red:red, green:green, blue:blue, alpha:alpha) } }
apache-2.0
c123b7e19631b3ac601505f8282211cb
37.913043
99
0.528787
3.592369
false
false
false
false
auth0/Auth0.swift
Auth0/Response.swift
1
1460
import Foundation func json(_ data: Data?) -> Any? { guard let data = data else { return nil } return try? JSONSerialization.jsonObject(with: data, options: []) } func string(_ data: Data?) -> String? { guard let data = data else { return nil } return String(data: data, encoding: .utf8) } struct Response<E: Auth0APIError> { let data: Data? let response: HTTPURLResponse? let error: Error? func result() throws -> Any? { guard error == nil else { throw E(cause: error!, statusCode: response?.statusCode ?? 0) } guard let response = self.response else { throw E(description: nil) } guard (200...300).contains(response.statusCode) else { if let json = json(data) as? [String: Any] { throw E(info: json, statusCode: response.statusCode) } throw E(from: self) } guard let data = self.data, !data.isEmpty else { if response.statusCode == 204 { return nil } // Not using the custom initializer because data could be empty throw E(description: nil, statusCode: response.statusCode) } if let json = json(data) { return json } // This piece of code is dedicated to our friends the backend devs :) if response.url?.lastPathComponent == "change_password" { return nil } throw E(from: self) } }
mit
975119a610c5e05d0f87d295984f5b4b
32.953488
97
0.580822
4.294118
false
false
false
false
wilmarvh/Bounce
Hooops/AppDelegate.swift
1
2750
import UIKit import NothingButNet @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { return true } func applicationWillResignActive(_ application: UIApplication) { } func applicationDidEnterBackground(_ application: UIApplication) { } func applicationWillEnterForeground(_ application: UIApplication) { } func applicationDidBecomeActive(_ application: UIApplication) { } func applicationWillTerminate(_ application: UIApplication) { } func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool { if let components = URLComponents(url: url, resolvingAgainstBaseURL: false) { if let code = components.queryItems?.filter({ $0.name == "code" }).first?.value { NothingBut.generateToken(with: code, completion: { error in UIApplication.shared.keyWindow?.rootViewController?.presentedViewController?.dismiss(animated: true, completion: nil) if let error = error { } else { } }) } } return true } func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) { if shortcutItem.type.contains("randomShot") { if let tabController = window?.rootViewController as? UITabBarController { tabController.selectedIndex = 0 if let navCon = tabController.selectedViewController as? UINavigationController { if let home = navCon.topViewController as? HomeViewController { if home.shots.count > 0 { let randomIndex = Int(arc4random_uniform(UInt32(home.shots.count))) let shot = home.shots[randomIndex] home.performSegue(withIdentifier: "showShotDetail", sender: shot) } else { home.loadData(completion: { let randomIndex = Int(arc4random_uniform(UInt32(home.shots.count))) let shot = home.shots[randomIndex] home.performSegue(withIdentifier: "showShotDetail", sender: shot) }) } } } } } } }
mit
250805d1bd82ecceba76677fa135b9e5
38.855072
155
0.574182
6.235828
false
false
false
false
taktem/TAKSwiftSupport
TAKSwiftSupport/Core/Extension/NSURL+Query.swift
1
1235
// // NSURL+Query.swift // Pods // // Created by 西村 拓 on 2015/11/22. // // import UIKit public extension NSURL { var querys: [String: AnyObject]? { return getQuerys() } final private func getQuerys() -> [String: AnyObject]? { guard let query = query else { return [:] } // クエリ文字列を各パラメータ毎に分割 let paramArray = query.componentsSeparatedByString("&") // クエリを辞書化 var result = [String: String]() for param in paramArray { guard let param = param.stringByRemovingPercentEncoding else { continue } let kvs = param.componentsSeparatedByString("=") if kvs.count > 1 { result[kvs[0]] = kvs[1] } } return result } /** クエリーに対して直接アクセス - parameter key: Query Key String - returns: Value */ subscript(key: String) -> String? { guard let querys = querys else { return nil } return querys[key] as? String } }
mit
4ab4e28d88eee658198d682177702942
19.589286
74
0.483088
4.417625
false
false
false
false
eBay/NMessenger
nMessenger/Source/MessageNodes/BubbleConfiguration/SimpleBubbleConfiguration.swift
4
1912
// // Copyright (c) 2016 eBay Software Foundation // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // import Foundation import UIKit /** Uses a simple bubble as primary and a simple bubble as secondary. Incoming color is pale grey and outgoing is mid grey */ open class SimpleBubbleConfiguration: BubbleConfigurationProtocol { open var isMasked = false public init() {} open func getIncomingColor() -> UIColor { return UIColor.n1PaleGreyColor() } open func getOutgoingColor() -> UIColor { return UIColor.n1MidGreyColor() } open func getBubble() -> Bubble { let newBubble = SimpleBubble() newBubble.hasLayerMask = isMasked return newBubble } open func getSecondaryBubble() -> Bubble { let newBubble = SimpleBubble() newBubble.hasLayerMask = isMasked return newBubble } }
mit
d01442cf8bda518f4b6d1f2cbf367089
42.454545
463
0.723849
4.992167
false
false
false
false
PureSwift/SwiftGL
Sources/Kronos/Program.swift
2
3415
// // Program.swift // Kronos // // Created by Alsey Coleman Miller on 1/20/16. // Copyright © 2016 PureSwift. All rights reserved. // #if os(iOS) || os(tvOS) import OpenGLES #endif /// OpenGL Program public struct Program { // MARK: - Properties public let name: GLuint // MARK: - Initialization /// Creates an empty program object. /// ///A program object is an object to which shader objects can be attached. This provides a mechanism to specify the shader objects that will be linked to create a program. It also provides a means for checking the compatibility of the shaders that will be used to create a program (for instance, checking the compatibility between a vertex shader and a fragment shader). When no longer needed as part of a program object, shader objects can be detached. @inline(__always) public init() { self.name = glCreateProgram() assert(self.name != 0, "Could not create program. Error: \(OpenGLError.currentError)") } @inline(__always) public init(name: GLuint) { assert(name != 0) assert(glIsProgram(name).boolValue) self.name = name } // MARK: - Methods /// Installs a program object as part of current rendering state. @inline(__always) static public func setCurrent(program: Program) { glUseProgram(program.name) } /// Attaches a shader to the program. @inline(__always) public func attach(shader: Shader) { glAttachShader(name, shader.name) } /// Detaches a shader from the program. @inline(__always) public func detach(shader: Shader) { glDetachShader(name, shader.name) } /// Links the program object specified by program. /// /// Shader objects of type `GL_VERTEX_SHADER` attached to program are used to create an executable that will run on the programmable vertex processor. /// Shader objects of type `GL_FRAGMENT_SHADER` attached to program are used to create an executable that will run on the programmable fragment processor. /// /// The status of the link operation will be stored as part of the program object's state. /// This value will be set to `GL_TRUE` if the program object was linked without errors and is ready for use, and /// `GL_FALSE` otherwise. It can be queried by calling glGetProgramiv with arguments program and `GL_LINK_STATUS`. @inline(__always) public func link() { glLinkProgram(name) } // MARK: - Accessors /// Get the link status of the program. public var linked: Bool { var linkStatus: GLint = 0 glGetProgramiv(name, GLenum(GL_LINK_STATUS), &linkStatus) return (linkStatus != 0) } /// Gets the info log. public var log: String? { var logLength: GLint = 0 glGetProgramiv(name, GLenum(GL_LINK_STATUS), &logLength) guard logLength > 0 else { return nil } let cString = UnsafeMutablePointer<CChar>(allocatingCapacity: Int(logLength)) defer { cString.deallocateCapacity(Int(logLength)) } glGetProgramInfoLog(name, GLsizei(logLength), nil, cString) return String.init(utf8String: cString)! } }
mit
7abbb70a4d4487a7a04434bd3698c4a5
30.611111
456
0.627417
4.552
false
false
false
false
JackHowa/Latr
SnapClone/PictureViewController.swift
1
9151
// // PictureViewController.swift // SnapClone // // Created by Jack Howard on 7/3/17. // Copyright © 2017 JackHowa. All rights reserved. // import UIKit import Firebase import FirebaseAuth import FirebaseDatabase // need specific firebase storage // via https://stackoverflow.com/questions/38561257/swift-use-of-unresolved-identifier-firstorage import FirebaseStorage class PictureViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate { @IBOutlet weak var imageView: UIImageView! // @IBOutlet weak var nextButton: UIButton! @IBOutlet weak var sendButton: UIButton! @IBOutlet weak var descriptionTextField: UITextField! // need to make a new ib outlet for displayable to be timefield @IBOutlet weak var datePickerText: UITextField! // new for adding the email address @IBOutlet weak var toTextField: UITextField! let datePicker = UIDatePicker() var getAtTime = "" var rawTime = "" // need to persist this unique photo id across scenes to delete from db var uuid = NSUUID().uuidString var imagePicker = UIImagePickerController() override func viewDidLoad() { super.viewDidLoad() imagePicker.delegate = self sendButton.isEnabled = false createDatePicker() // don't show toolbar self.navigationController?.setToolbarHidden(true, animated: true) } // view will or did appear may account for ui changes // func textFieldDidEndEditing() { if datePickerText.hasText && toTextField.hasText && descriptionTextField.hasText { sendButton.isEnabled = true } } @IBAction func tappedGestureAnywhere(_ sender: Any) { descriptionTextField.resignFirstResponder() datePickerText.resignFirstResponder() // update so that to responds as well to tap outside toTextField.resignFirstResponder() } func createDatePicker() { // format picker // for only date // datePicker.datePickerMode = .date // toolbar let toolbar = UIToolbar() // fit to screen toolbar.sizeToFit() // create done button icon // action is the function that will be called // selector ends the assignment to the textfield let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: #selector(donePressed)) toolbar.setItems([doneButton], animated: true) datePickerText.inputAccessoryView = toolbar // assign the datepicker to text field datePickerText.inputView = datePicker } func donePressed() { // format // dateformatter object var dateFormatter = DateFormatter() // shortened date show // dateFormatter.dateStyle = .short // dateFormatter.timeStyle = .none print("this is output of datepicker") print(datePicker.date) // 2017-08-03 20:57:21 +0000 dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z" rawTime = dateFormatter.string(from: datePicker.date) print("this is output of rawtime") print(rawTime) dateFormatter.dateStyle = .medium dateFormatter.timeStyle = .short // datePicker date is a certain style getAtTime = dateFormatter.string(from: datePicker.date) print(getAtTime) // assign input text of the returned datePicker var datePickerText.text = getAtTime // check whether able to send textFieldDidEndEditing() // close picker view self.view.endEditing(true) } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { // can also use edited image let image = info[UIImagePickerControllerOriginalImage] as! UIImage // setting the image to the view imageView.image = image imageView.backgroundColor = UIColor.clear // can now click next button // testing and debugging // authorization // send button is enabled to early here // sendButton.isEnabled = true // check whether able to send textFieldDidEndEditing() imagePicker.dismiss(animated: true, completion: nil) } @IBAction func tappedCamera(_ sender: Any) { // for testing we're going to pick one // imagePicker.sourceType = .savedPhotosAlbum // should be camera imagePicker.sourceType = .camera // would muck up the ui if allowed editing imagePicker.allowsEditing = false present(imagePicker, animated: true, completion: nil) } @IBAction func tappedLibraryPlus(_ sender: Any) { // for testing we're going to pick one imagePicker.sourceType = .savedPhotosAlbum // should be camera // imagePicker.sourceType = .camera // would muck up the ui if allowed editing imagePicker.allowsEditing = false present(imagePicker, animated: true, completion: nil) } func displayAlertMessage(userMessage:String) { let myAlert = UIAlertController(title:"Alert", message: userMessage, preferredStyle: UIAlertControllerStyle.alert); let okAction = UIAlertAction(title:"OK", style: UIAlertActionStyle.default, handler:nil); myAlert.addAction(okAction); self.present(myAlert, animated:true, completion:nil); } @IBAction func tappedSend(_ sender: Any) { sendButton.isEnabled = false let imagesFolder = Storage.storage().reference().child("images") // turns image into data // bang to know that image exists // higher compression of 0.1 vs a png let imageData = UIImageJPEGRepresentation(imageView.image!, 0.1)! // upload to firebase // uu id unique imagesFolder.child("\(uuid).jpg").putData(imageData, metadata: nil, completion: { (metadata, error) in // print("we're trying to upload") if error != nil { // print("We had an error: \(String(describing: error))") } else { // perform segue upon no error next tap upload // absolute designates the value as a string // loading the message for upload into db var message = ["from": Auth.auth().currentUser!.email!, "description": self.descriptionTextField.text!, "image_url": metadata?.downloadURL()?.absoluteString, "uuid": self.uuid, "getAt": self.rawTime] // ok need to find the user based on the email //added .lowercased(). Added "!" to .text because reasons let userEmail = self.toTextField.text!.lowercased() let ref = Database.database().reference().child("users").queryOrdered(byChild: "email").queryEqual(toValue: userEmail) ref.observeSingleEvent(of: .value, with: { (snapshot) in for snap in snapshot.children { let userSnap = snap as! DataSnapshot let uid = userSnap.key //the uid of each user // print("key = \(uid)") Database.database().reference().child("users").child(uid).child("messages").childByAutoId().setValue(message) } guard snapshot.value is NSNull else { //yes we got the user let user = snapshot // print("\(user) exists" ) // after selecting a row, go back to the root to see any remaining messages // need this pop back after viewing self.navigationController!.popToRootViewController(animated: true) return } //no there is no user with desired email // print("\(userEmail) isn't a user") self.displayAlertMessage(userMessage: "User doesn't exist") }) { (error) in // print("Failed to get snapshot", error.localizedDescription) } } }) } }
mit
8e1fb70e206ceca792e2a7ca950850e8
30.551724
215
0.558907
5.828025
false
false
false
false