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
SergeVKom/RPAgentSwiftXCTest
RPAgentSwiftXCTest/RPConstants.swift
1
4230
// // RPConstants.swift // com.oxagile.automation.RPAgentSwiftXCTest // // Created by Sergey Komarov on 7/5/17. // Copyright © 2017 Oxagile. All rights reserved. // import Foundation import UIKit enum TestStatus: String { case passed = "PASSED" case failed = "FAILED" case stopped = "STOPPED" case skipped = "SKIPPED" case reseted = "RESETED" case cancelled = "CANCELLED" } public extension UIDevice { public var modelName: String { var model = "" var postfix = "" var systemInfo = utsname() uname(&systemInfo) let machineMirror = Mirror(reflecting: systemInfo.machine) var identifier = machineMirror.children.reduce("") { identifier, element in guard let value = element.value as? Int8, value != 0 else { return identifier } return identifier + String(UnicodeScalar(UInt8(value))) } if identifier == "i386" || identifier == "x86_64" { identifier = ProcessInfo().environment["SIMULATOR_MODEL_IDENTIFIER"] ?? "unknown" postfix = " (simulator)" } switch identifier { case "iPod5,1": model = "iPod Touch 5\(postfix)" case "iPod7,1": model = "iPod Touch 6\(postfix)" case "iPhone3,1", "iPhone3,2", "iPhone3,3": model = "iPhone 4\(postfix)" case "iPhone4,1": model = "iPhone 4s\(postfix)" case "iPhone5,1", "iPhone5,2": model = "iPhone 5\(postfix)" case "iPhone5,3", "iPhone5,4": model = "iPhone 5c\(postfix)" case "iPhone6,1", "iPhone6,2": model = "iPhone 5s\(postfix)" case "iPhone7,2": model = "iPhone 6\(postfix)" case "iPhone7,1": model = "iPhone 6 Plus\(postfix)" case "iPhone8,1": model = "iPhone 6s\(postfix)" case "iPhone8,2": model = "iPhone 6s Plus\(postfix)" case "iPhone9,1", "iPhone9,3": model = "iPhone 7\(postfix)" case "iPhone9,2", "iPhone9,4": model = "iPhone 7 Plus\(postfix)" case "iPhone10,1", "iPhone10,4": model = "iPhone 8\(postfix)" case "iPhone10,2", "iPhone10,5": model = "iPhone 8 Plus\(postfix)" case "iPhone10,3", "iPhone10,6": model = "iPhone X\(postfix)" case "iPhone8,4": model = "iPhone SE\(postfix)" case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4":model = "iPad 2\(postfix)" case "iPad3,1", "iPad3,2", "iPad3,3": model = "iPad 3\(postfix)" case "iPad3,4", "iPad3,5", "iPad3,6": model = "iPad 4\(postfix)" case "iPad4,1", "iPad4,2", "iPad4,3": model = "iPad Air\(postfix)" case "iPad5,3", "iPad5,4": model = "iPad Air 2\(postfix)" case "iPad2,5", "iPad2,6", "iPad2,7": model = "iPad Mini\(postfix)" case "iPad4,4", "iPad4,5", "iPad4,6": model = "iPad Mini 2\(postfix)" case "iPad4,7", "iPad4,8", "iPad4,9": model = "iPad Mini 3\(postfix)" case "iPad5,1", "iPad5,2": model = "iPad Mini 4\(postfix)" case "iPad6,3", "iPad6,4": model = "iPad Pro 9.7\"\(postfix)" case "iPad6,7", "iPad6,8": model = "iPad Pro 12.9\"\(postfix)" case "iPad7,1", "iPad7,2": model = "iPad Pro 2 12.9\"\(postfix)" case "iPad7,3", "iPad7,4": model = "iPad Pro 10.5\"\(postfix)" case "AppleTV2,1": model = "Apple TV 2\(postfix)" case "AppleTV3,1", "AppleTV3,2": model = "Apple TV 3\(postfix)" case "AppleTV5,3": model = "Apple TV 4\(postfix)" case "AppleTV6,2": model = "Apple TV 4K\(postfix)" default: model = identifier } return model } }
mit
6a5988f0b7dff2beb4fdcf6cc21d9f8f
53.217949
93
0.482147
3.894107
false
false
false
false
itsaboutcode/WordPress-iOS
WordPress/Classes/ViewRelated/Blog/Blog Details/Detail Header/SiteIconView.swift
1
5343
class SiteIconView: UIView { private enum Constants { static let imageSize: CGFloat = 64 static let borderRadius: CGFloat = 4 static let imageRadius: CGFloat = 2 static let spotlightOffset: CGFloat = -8 } /// Whether or not to show the spotlight animation to illustrate tapping the icon. var spotlightIsShown: Bool = true { didSet { spotlightView.isHidden = !spotlightIsShown } } /// A block to be called when the image button is tapped. var tapped: (() -> Void)? /// A block to be called when an image is dropped on to the view. var dropped: (([UIImage]) -> Void)? let imageView: UIImageView = { let imageView = UIImageView(frame: .zero) imageView.translatesAutoresizingMaskIntoConstraints = false imageView.clipsToBounds = true imageView.layer.cornerRadius = Constants.imageRadius NSLayoutConstraint.activate([ imageView.widthAnchor.constraint(equalToConstant: Constants.imageSize), imageView.heightAnchor.constraint(equalToConstant: Constants.imageSize) ]) return imageView }() let activityIndicator: UIActivityIndicatorView = { let indicatorView = UIActivityIndicatorView(style: .large) indicatorView.translatesAutoresizingMaskIntoConstraints = false return indicatorView }() private var dropInteraction: UIDropInteraction? private let button: UIButton = { let button = UIButton(frame: .zero) button.backgroundColor = UIColor.secondaryButtonBackground button.clipsToBounds = true button.layer.borderColor = UIColor.secondaryButtonBorder.cgColor button.layer.borderWidth = 1 button.layer.cornerRadius = Constants.borderRadius return button }() private let spotlightView: UIView = { let spotlightView = QuickStartSpotlightView() spotlightView.translatesAutoresizingMaskIntoConstraints = false spotlightView.isHidden = true return spotlightView }() var allowsDropInteraction: Bool = false { didSet { if allowsDropInteraction { let interaction = UIDropInteraction(delegate: self) addInteraction(interaction) dropInteraction = interaction } else { if let dropInteraction = dropInteraction { removeInteraction(dropInteraction) } } } } init(frame: CGRect, insets: UIEdgeInsets = .zero) { super.init(frame: frame) button.addSubview(imageView) button.pinSubviewToAllEdges(imageView, insets: insets) button.addTarget(self, action: #selector(touchedButton), for: .touchUpInside) button.translatesAutoresizingMaskIntoConstraints = false button.addSubview(activityIndicator) button.pinSubviewAtCenter(activityIndicator) button.accessibilityLabel = NSLocalizedString("Site Icon", comment: "Accessibility label for site icon button") accessibilityElements = [button] addSubview(button) addSubview(spotlightView) NSLayoutConstraint.activate([ trailingAnchor.constraint(equalTo: spotlightView.trailingAnchor, constant: Constants.spotlightOffset), bottomAnchor.constraint(equalTo: spotlightView.bottomAnchor, constant: Constants.spotlightOffset) ]) pinSubviewToAllEdges(button) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } @objc func touchedButton() { tapped?() } } extension SiteIconView: UIDropInteractionDelegate { func dropInteraction(_ interaction: UIDropInteraction, sessionDidEnter session: UIDropSession) { imageView.depressSpringAnimation() } func dropInteraction(_ interaction: UIDropInteraction, canHandle session: UIDropSession) -> Bool { let isImage = session.canLoadObjects(ofClass: UIImage.self) let isSingleImage = session.items.count == 1 return isImage && isSingleImage } func dropInteraction(_ interaction: UIDropInteraction, sessionDidUpdate session: UIDropSession) -> UIDropProposal { let location = session.location(in: self) let operation: UIDropOperation if bounds.contains(location) { operation = .copy } else { operation = .cancel } return UIDropProposal(operation: operation) } func dropInteraction(_ interaction: UIDropInteraction, performDrop session: UIDropSession) { activityIndicator.startAnimating() session.loadObjects(ofClass: UIImage.self) { [weak self] images in if let images = images as? [UIImage] { self?.dropped?(images) } } } func dropInteraction(_ interaction: UIDropInteraction, concludeDrop session: UIDropSession) { imageView.normalizeSpringAnimation() } func dropInteraction(_ interaction: UIDropInteraction, sessionDidExit session: UIDropSession) { imageView.normalizeSpringAnimation() } func dropInteraction(_ interaction: UIDropInteraction, sessionDidEnd session: UIDropSession) { imageView.normalizeSpringAnimation() } }
gpl-2.0
fc97a53f0b03260041062959cc8c2e37
33.031847
119
0.668538
5.542531
false
false
false
false
modum-io/ios_client
PharmaSupplyChain/AppDelegate.swift
1
9195
// // AppDelegate.swift // PharmaSupplyChain // // Created by Yury Belevskiy on 25.10.16. // Copyright © 2016 Modum. All rights reserved. // import UIKit import CoreData import Firebase import UXCam import UserNotifications @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { /* clear keychain if app was de-installed and installed again */ if UserDefaults.standard.object(forKey: "FirstLaunch") == nil { LoginManager.shared.clear() UserDefaults.standard.set(true, forKey: "FirstLaunch") } /* setting up analytics */ FIRApp.configure() UXCam.start(withKey: "4e331aa53d215bd") let storyboard = UIStoryboard.init(name: "Main", bundle: nil) window = UIWindow(frame: UIScreen.main.bounds) if let window = window { window.rootViewController = storyboard.instantiateViewController(withIdentifier: "RootViewControllerID") as? RootViewController } /* request permission to send notifications */ let notificationCenter = UNUserNotificationCenter.current() notificationCenter.delegate = self notificationCenter.getNotificationSettings(completionHandler: { [unowned notificationCenter] settings in if settings.authorizationStatus == .notDetermined { notificationCenter.requestAuthorization(options: [.alert, .badge, .sound], completionHandler: { success, error in if !success { log("Notifications are disabled for the application") } if let error = error { log("Error requesting permission to send notifications: \(error.localizedDescription)") } }) } }) /* resume pending uploads */ RecurrentUploader.shared.resumeDownloads() /* re-login user every time he starts the app */ if let username = LoginManager.shared.getUsername(), let password = LoginManager.shared.getPassword() { ServerManager.shared.login(username: username, password: password, completionHandler: { [weak self] error, response in if let appDelegate = self { if let error = error { log("Error during login! Error is: \(error.message ?? "")") /* if there is no internet and token isn't yet expired, present parcels screen */ if let authTokenExpiry = LoginManager.shared.getAuthTokenExpiry(), authTokenExpiry > Date(), error == ServerError.noInternet { if let parcelsNavigationController = storyboard.instantiateViewController(withIdentifier: "ParcelsNavigationController") as? UINavigationController { appDelegate.window!.rootViewController = parcelsNavigationController } } else { if let loginViewController = storyboard.instantiateViewController(withIdentifier: "LoginViewController") as? LoginViewController { appDelegate.window!.rootViewController = loginViewController } } } else if let response = response { /* store user credentials */ LoginManager.shared.storeUser(username: username, password: password, response: response, rememberMe: true) /* Retrieving company defaults on login and persist them in CoreData */ ServerManager.shared.getCompanyDefaults(completionHandler: { [weak self] error, companyDefaults in if let appDelegate = self { if let error = error { log("Error retrieving company defaults: \(error.message ?? "")") if let loginViewController = storyboard.instantiateViewController(withIdentifier: "LoginViewController") as? LoginViewController { appDelegate.window!.rootViewController = loginViewController } } else { if let companyDefaults = companyDefaults { if let parcelsNavigationController = storyboard.instantiateViewController(withIdentifier: "ParcelsNavigationController") as? UINavigationController { appDelegate.window!.rootViewController = parcelsNavigationController } CoreDataManager.shared.performBackgroundTask(WithBlock: { backgroundContext in let existingRecords = CoreDataManager.getAllRecords(InContext: backgroundContext, ForEntityName: "CDCompanyDefaults") existingRecords.forEach({ existingRecord in backgroundContext.delete(existingRecord as! NSManagedObject) }) let cdCompanyDefaults = NSEntityDescription.insertNewObject(forEntityName: "CDCompanyDefaults", into: backgroundContext) as! CDCompanyDefaults companyDefaults.toCoreDataObject(object: cdCompanyDefaults) CoreDataManager.shared.saveLocally(managedContext: backgroundContext) }) } } } }) } } }) } else { if let loginViewController = storyboard.instantiateViewController(withIdentifier: "LoginViewController") as? LoginViewController { window!.rootViewController = loginViewController } } window!.makeKeyAndVisible() return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. } // MARK: UNUserNotificationCenterDelegate /* called when deciding which options to use when notification is presented at foreground */ func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { completionHandler([.alert, .sound]) } }
apache-2.0
9a2adeae84916c516e9e1347f03f0c00
54.385542
285
0.577986
7.138199
false
false
false
false
Pluto-Y/SwiftyEcharts
SwiftyEcharts/Models/Graphic/GroupGraphic.swift
1
3929
// // GroupGraphic.swift // SwiftyEcharts // // Created by Pluto Y on 10/02/2017. // Copyright © 2017 com.pluto-y. All rights reserved. // /// group 是唯一的可以有子节点的容器。group 可以用来整体定位一组图形元素。 public final class GroupGraphic: Graphic { /// MARK: Graphic public var type: GraphicType { return .group } public var id: String? public var action: GraphicAction? public var left: Position? public var right: Position? public var top: Position? public var bottom: Position? public var bounding: GraphicBounding? public var z: Float? public var zlevel: Float? public var silent: Bool? public var invisible: Bool? public var cursor: String? public var draggable: Bool? public var progressive: Bool? /// 用于描述此 group 的宽。 /// /// 这个宽只用于给子节点定位。 /// /// 即便当宽度为零的时候,子节点也可以使用 left: 'center' 相对于父节点水平居中。 public var width: Float? /// 用于描述此 group 的高。 /// /// 这个高只用于给子节点定位。 /// /// 即便当高度为零的时候,子节点也可以使用 top: 'middle' 相对于父节点垂直居中。 public var height: Float? /// 子节点列表,其中项都是一个图形元素定义。 public var children: [Graphic]? } extension GroupGraphic: Enumable { public enum Enums { case id(String), action(GraphicAction), left(Position), right(Position), top(Position), bottom(Position), bounding(GraphicBounding), z(Float), zlevel(Float), silent(Bool), invisible(Bool), cursor(String), draggable(Bool), progressive(Bool), width(Float), height(Float), children([Graphic]) } public typealias ContentEnum = Enums public convenience init(_ elements: Enums...) { self.init() for ele in elements { switch ele { case let .id(id): self.id = id case let .action(action): self.action = action case let .left(left): self.left = left case let .right(right): self.right = right case let .top(top): self.top = top case let .bottom(bottom): self.bottom = bottom case let .bounding(bounding): self.bounding = bounding case let .z(z): self.z = z case let .zlevel(zlevel): self.zlevel = zlevel case let .silent(silent): self.silent = silent case let .invisible(invisible): self.invisible = invisible case let .cursor(cursor): self.cursor = cursor case let .draggable(draggable): self.draggable = draggable case let .progressive(progressive): self.progressive = progressive case let .width(width): self.width = width case let .height(height): self.height = height case let .children(children): self.children = children } } } } extension GroupGraphic: Mappable { public func mapping(_ map: Mapper) { map["type"] = type map["id"] = id map["$action"] = action map["left"] = left map["right"] = right map["top"] = top map["bottom"] = bottom map["bounding"] = bounding map["z"] = z map["zlevel"] = zlevel map["silent"] = silent map["invisible"] = invisible map["cursor"] = cursor map["draggable"] = draggable map["progressive"] = progressive map["width"] = width map["height"] = height map["children"] = children } }
mit
2d655d006e4a4e13a89789c344c73384
29.216667
297
0.549917
4.311534
false
false
false
false
adamrothman/SwiftSocketIO
SwiftSocketIO/Packet.swift
1
2012
// // Packet.swift // SwiftSocketIO // // Created by Adam Rothman on 1/25/15. // // import Foundation protocol Packet: class { var rawType: Int { get } var payload: String? { get set } } class EngineIOPacket: Packet { enum TypeCode: Int { case Open = 0 // non-ws case Close = 1 // non-ws case Ping = 2 case Pong = 3 case Message = 4 case Upgrade = 5 case NoOp = 6 } var type: TypeCode var rawType: Int { get { return type.rawValue } } var payload: String? // Convenience property - attempt to construct a SocketIOPacket from the payload var socketIOPacket: SocketIOPacket? { get { return payload != nil ? Parser.decodeSocketIOPacket(payload!) : nil } } init(type: TypeCode, payload: String? = nil) { self.type = type self.payload = payload } } class SocketIOPacket: Packet { enum TypeCode: Int { case Connect = 0 case Disconnect case Event case Ack case Error case BinaryEvent case BinaryAck } var type: TypeCode var rawType: Int { get { return type.rawValue } } var payload: String? // Convenience property var payloadObject: AnyObject? { // If payload string is JSON, decode it to native object get { if let payloadData = payload?.dataUsingEncoding(NSUTF8StringEncoding) { var error: NSError? return NSJSONSerialization.JSONObjectWithData(payloadData, options: NSJSONReadingOptions(0), error: &error) } else { return nil } } // Encode native object as JSON, store it in payload set { if newValue != nil { var error: NSError? if let payloadData = NSJSONSerialization.dataWithJSONObject(newValue!, options: NSJSONWritingOptions(0), error: &error) { payload = NSString(data: payloadData, encoding: NSUTF8StringEncoding) } } } } init(type: TypeCode, payload: String? = nil) { self.type = type self.payload = payload } }
mit
2c11998acfd7f1df15c3e8d18a01fd6f
19.323232
129
0.629722
4.040161
false
false
false
false
pawrsccouk/Stereogram
Stereogram-iPad/FullImageViewController.swift
1
12632
// // FullImageViewController.swift // Stereogram-iPad // // Created by Patrick Wallace on 16/01/2015. // Copyright (c) 2015 Patrick Wallace. All rights reserved. import UIKit @objc enum ApprovalResult: Int { case Accepted, Discarded } // MARK: Delegate Protocol /// Protocol for Image controller delegate. /// Used to notify the caller when the user approves or rejects an image and to dismiss it. @objc protocol FullImageViewControllerDelegate { /// Called if the controller is in Approval mode and the user has approved an image. /// /// :param: controller - The controller that triggered the message. /// :param: stereogram - The stereogram the user took /// :param: result - Whether the user approved or rejected the stereogram. optional func fullImageViewController(controller: FullImageViewController , approvingStereogram stereogram: Stereogram , result: ApprovalResult) /// Called if the controller is viewing an image, and the image changed. /// /// This will be called in both approval mode and regular viewing mode /// /// :param: controller - The controller that triggered the message. /// :param: stereogram - The stereogram the user took /// :param: indexPath - The path to the image the user is editing in the photo view controller. optional func fullImageViewController(controller: FullImageViewController , amendedStereogram newStereogram: Stereogram , atIndexPath indexPath: NSIndexPath?) // Called when the user has requested the controller be closed. /// On receipt of this message, the delegagte must remove the view controller from the stack. /// /// :param: controller - The controller that triggered the message. func dismissedFullImageViewController(controller: FullImageViewController) } // MARK: - /// View controller presenting a view which will show a stereogram image at full size /// /// There are two modes this controller can be in. /// - View Mode: Show an existing image read-only. /// - Approval Mode: Show a new image and allow the user to accept or reject it. class FullImageViewController: UIViewController { /// The stereogram we are displaying. private let stereogram: Stereogram /// Optional index path if we are viewing an existing stereogram. private let indexPath: NSIndexPath? /// The bar button item that launches the viewing mode menu. /// Needed as we need to anchor the menu. private weak var viewingModeItem: UIBarButtonItem! /// An activity indicator we can show during lengthy operations. private let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .WhiteLarge) /// The delegate to update according to the user's choices. unowned var delegate: FullImageViewControllerDelegate // MARK: Outlets /// The link to the image view displaying the stereogram image. @IBOutlet var imageView: UIImageView! /// The scrollview containing imageView. @IBOutlet var scrollView: UIScrollView! // MARK: Initialisers /// Designated initialiser. /// If forApproval is YES, the view gets a 'Keep' button. /// If pressed, this button calls the delegate's approvedImage function, /// which should copy the image to permanent storage. /// /// :param: stereogram - The stereogram to view /// :param: indexPath - Index path of the stereogram in the photo store. /// :param: forApproval - True if this presents a stereogram just taken for the /// user to accept or reject. /// False if this just displays a stereogram from the photo collection. /// :param: delegate - The delegate to send approval and dismissal messages. private init( stereogram: Stereogram , atIndexPath indexPath: NSIndexPath? , forApproval: Bool , delegate: FullImageViewControllerDelegate) { self.stereogram = stereogram self.indexPath = indexPath self.delegate = delegate super.init(nibName: "FullImageView", bundle: nil) let toggleViewMethodButtonItem = UIBarButtonItem(title: "Change View Method" , style: .Plain , target: self , action: "selectViewingMethod:") viewingModeItem = toggleViewMethodButtonItem // If we are using this to approve an image, then display "Keep" and "Discard" buttons. if forApproval { let keepButtonItem = UIBarButtonItem(title: "Keep" , style: .Plain , target: self , action: "keepPhoto") let discardButtonItem = UIBarButtonItem(title: "Discard" , style: .Plain , target: self , action: "discardPhoto") self.navigationItem.rightBarButtonItems = [keepButtonItem, discardButtonItem] self.navigationItem.leftBarButtonItem = toggleViewMethodButtonItem } else { self.navigationItem.rightBarButtonItem = toggleViewMethodButtonItem } } /// Open in normal mode, viewing the index at the selected index path. /// /// :param: stereogram - The stereogram to view /// :param: indexPath - Index path of the stereogram in the photo store. /// :param: delegate - The delegate to send approval and dismissal messages. convenience init(stereogram: Stereogram , atIndexPath indexPath: NSIndexPath , delegate: FullImageViewControllerDelegate) { self.init(stereogram: stereogram , atIndexPath: indexPath , forApproval: false , delegate: delegate) } /// Open in approval mode. /// /// :param: stereogram - The stereogram to view /// :param: delegate - The delegate to send approval and dismissal messages. convenience init(stereogramForApproval: Stereogram , delegate: FullImageViewControllerDelegate) { self.init(stereogram: stereogramForApproval , atIndexPath: nil , forApproval: true , delegate: delegate) } // We create this manually instead of storing it in a NIB file. // If we decide to allow this, I'll need to do the equivalent to init(image:, forApproval:) // outside the class. required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: Overrides extension FullImageViewController { override func viewDidLoad() { super.viewDidLoad() // Set the image now we know the view is loaded, // and use that to set the bounds of the scrollview it's contained in. switch stereogram.stereogramImage() { case .Success(let result): imageView.image = result.value imageView.sizeToFit() case .Error(let error): NSLog("Failed to load an image for stereogram \(stereogram)") } } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) setupActivityIndicator() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() // Called on resize or autorotate. Re-set up the scrollview to preserve the scaling factor. setupScrollviewAnimated(true) } } // MARK: - Callbacks extension FullImageViewController { /// Tell the delegate to keep this photo and then dismisss the view controller. func keepPhoto() { delegate.fullImageViewController?(self , approvingStereogram: self.stereogram , result: .Accepted) delegate.dismissedFullImageViewController(self) } /// Tell the delegate to remove the photo and then dismiss the view controller. func discardPhoto() { delegate.fullImageViewController?(self , approvingStereogram: self.stereogram , result: .Discarded) delegate.dismissedFullImageViewController(self) } /// Prompt the user with a menu of possible viewing methods they can select. func selectViewingMethod(sender: AnyObject?) { let alertController = UIAlertController(title: "Select viewing style" , message: "Choose one of the styles below" , preferredStyle: .ActionSheet) let animationAction = UIAlertAction(title: "Animation", style: .Default) { action in self.changeViewingMethod(.AnimatedGIF) } alertController.addAction(animationAction) let crossEyedAction = UIAlertAction(title: "Cross-eyed", style: .Default) { action in self.changeViewingMethod(.Crosseyed) } alertController.addAction(crossEyedAction) let wallEyedAction = UIAlertAction(title: "Wall-eyed", style: .Default) { action in self.changeViewingMethod(.Walleyed) } alertController.addAction(wallEyedAction) alertController.popoverPresentationController!.barButtonItem = viewingModeItem self.presentViewController(alertController, animated: true, completion: nil) } /// Change the viewing method of the stereogram we are viewing. /// /// Create the new images on a separate thread, /// then call back to the main thread to replace them in the photo collection. /// /// :param: viewMode The new viewing method. func changeViewingMethod(viewMode: ViewMode) { showActivityIndicator = true var sgm = stereogram, path = indexPath dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { sgm.viewingMethod = viewMode // Reload the image while we are in the background thread. let refreshResult = sgm.refresh() // Update the GUI on the main thread. dispatch_async(dispatch_get_main_queue()) { self.showActivityIndicator = false switch refreshResult { case .Success(): // Clear the activity indicator and update the image in this view. switch sgm.stereogramImage() { case .Success(let result): self.imageView.image = result.value //self.imageView.sizeToFit() self.setupScrollviewAnimated(true) // Notify the system that the image has been changed in the view. self.delegate.fullImageViewController?(self , amendedStereogram: sgm , atIndexPath: path) case .Error(let error): error.showAlertWithTitle("Error changing viewing method" , parentViewController:self) } case .Error(let error): error.showAlertWithTitle("Error changing viewing method" , parentViewController: self) } } } } } // MARK: - Activity Indicator extension FullImageViewController { /// Indicate if the activity indicator should be shown or hidden. private var showActivityIndicator: Bool { get { return !activityIndicator.hidden } set { activityIndicator.hidden = !newValue if newValue { activityIndicator.startAnimating() } else { activityIndicator.stopAnimating() } } } /// Add the activity indicator and fit it into the frame. private func setupActivityIndicator() { // Add the activity indicator to the view if it is not there already. It starts off hidden. if !activityIndicator.isDescendantOfView(view) { view.addSubview(activityIndicator) } // Ensure the activity indicator fits in the frame. let activitySize = activityIndicator.bounds.size let parentSize = view.bounds.size let frame = CGRectMake((parentSize.width / 2) - (activitySize.width / 2) , (parentSize.height / 2) - (activitySize.height / 2) , activitySize.width , activitySize.height) activityIndicator.frame = frame } } // MARK: - Private Data extension FullImageViewController { /// Calculate the appropriate size and zoom factor of the scrollview. /// /// :param: animated - If True, the scrollview will animate to show the new changes. private func setupScrollviewAnimated(animated: Bool) { assert(imageView.image != nil , "Controller \(self) imageView \(imageView) has no associated image") if let viewedImage = imageView.image { scrollView.contentSize = imageView.bounds.size // set the zoom info so the image fits in the window by default but can be zoomed in. // Respects the aspect ratio. let imageSize = viewedImage.size, viewSize = scrollView.bounds.size scrollView.maximumZoomScale = 1.0 // Cannot zoom in past original/full-size. scrollView.minimumZoomScale = min(viewSize.width / imageSize.width , viewSize.height / imageSize.height) // Default to showing the whole image. scrollView.setZoomScale(scrollView.minimumZoomScale, animated: animated) } } } // MARK: - Scrollview Delegate extension FullImageViewController: UIScrollViewDelegate { func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? { return imageView } }
mit
1c482f82df18ad9c4ab087d33f1a6a94
33.326087
97
0.696089
4.188329
false
false
false
false
a736220388/TestKitchen_1606
TestKitchen/TestKitchen/classes/common/MainTabBarController.swift
1
6627
// // MainTabBarController.swift // TestKitchen // // Created by qianfeng on 16/8/15. // Copyright © 2016年 qianfeng. All rights reserved. // import UIKit class MainTabBarController: UITabBarController { private var bgView:UIView? private var array:Array<Dictionary<String,String>>?{ get{ let path = NSBundle.mainBundle().pathForResource("Ctrl", ofType: "json") var myArray:Array<Dictionary<String,String>>? = nil if let filePath = path{ let data = NSData(contentsOfFile: filePath) if let jsonData = data{ do{ let jsonValue = try NSJSONSerialization.JSONObjectWithData(jsonData, options: .MutableContainers) if jsonValue.isKindOfClass(NSArray.self){ myArray = jsonValue as? Array<Dictionary<String,String>> } }catch{ print(error) return nil } } } return myArray } /* get{ let path = NSBundle.mainBundle().pathForResource("Ctrl", ofType: "json") var myArray:Array<Dictionary<String,String>>? = nil if let filePath = path{ let tmpArray = NSArray(contentsOfFile: path!) myArray = tmpArray as? Array<Dictionary<String,String>> } return myArray } */ } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. createViewControllers() tabBar.hidden = true } //创建试图控制器 func createViewControllers(){ var ctrlNames = [String]() var imageNames = [String]() var titleNames = [String]() if let tmpArray = self.array{ for dict in tmpArray{ let name = dict["ctrlName"] let titleName = dict["titleName"] let imageName = dict["imageName"] ctrlNames.append(name!) titleNames.append(titleName!) imageNames.append(imageName!) } }else{ ctrlNames = ["CookBookViewController","CommunityViewController","MallViewController","FoodClassViewController","ProfileViewController"] titleNames = ["食材","社区","商城","食课","我的"] imageNames = ["home","community","shop","shike","mine"] } var vCtrlArray = Array<UINavigationController>() for i in 0..<ctrlNames.count{ let ctrlName = "TestKitchen." + ctrlNames[i] let cls = NSClassFromString(ctrlName) as! UIViewController.Type let ctrl = cls.init() let navCtrl = UINavigationController(rootViewController: ctrl) vCtrlArray.append(navCtrl) } self.viewControllers = vCtrlArray createCustomTabbar(titleNames, imageNames: imageNames) } func createCustomTabbar(titleNames:[String],imageNames:[String]){ bgView = UIView.createView() bgView?.backgroundColor = UIColor.whiteColor() bgView?.layer.borderWidth = 1 bgView?.layer.borderColor = UIColor.grayColor().CGColor view.addSubview(bgView!) bgView?.snp_makeConstraints(closure: { [weak self] (make) in make.left.right.equalTo((self!.view)) make.bottom.equalTo((self!.view)) make.top.equalTo((self!.view.snp_bottom)).offset(-49) }) let width = kScreenWidth/5.0 for i in 0..<imageNames.count{ let imageName = imageNames[i] let titleName = titleNames[i] let bgImageName = imageName + "_normal" let selectBgImageName = imageName + "_select" let btn = UIButton.createBtn(nil, bgImageName: bgImageName, selectBgImageName: selectBgImageName, target: self, action: #selector(clickBtn(_:))) bgView?.addSubview(btn) btn.snp_makeConstraints(closure: { [weak self] (make) in make.top.bottom.equalTo((self!.bgView)!) make.width.equalTo(width) make.left.equalTo(width*CGFloat(i)) }) let label = UILabel.createLabel(titleName, font: UIFont.systemFontOfSize(8), textAlignment: .Center, textColor: UIColor.grayColor()) btn.addSubview(label) label.snp_makeConstraints(closure: { (make) in make.left.right.equalTo(btn) make.top.equalTo(btn).offset(32) make.height.equalTo(12) }) btn.tag = 300 + i label.tag = 400 if i == 0{ btn.selected = true label.textColor = UIColor.orangeColor() } } } func clickBtn(curBtn:UIButton){ let lastBtnView = bgView!.viewWithTag(300+selectedIndex) if let tmpBtn = lastBtnView{ let lastBtn = lastBtnView as! UIButton let lastView = tmpBtn.viewWithTag(400) if let tmpLabel = lastView{ let lastLabel = tmpLabel as! UILabel lastBtn.selected = false lastLabel.textColor = UIColor.grayColor() } } let curLabelView = curBtn.viewWithTag(400) if let tmpLabel = curLabelView{ let curLabel = tmpLabel as! UILabel curBtn.selected = true curLabel.textColor = UIColor.orangeColor() } selectedIndex = curBtn.tag - 300 } //显示tabbar func showTabbar(){ UIView.animateWithDuration(0.05) { [weak self] in self!.bgView?.hidden = false } } //隐藏tabbar func hideTabbar(){ UIView.animateWithDuration(0.05) { [weak self] in self!.bgView?.hidden = true } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // 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. } */ }
mit
d64c78d87f5b27d313e5ed470a7cae9d
34.387097
156
0.556214
5.150235
false
false
false
false
zbw209/-
StudyNotes/SwiftUI/SwiftUI/SceneDelegate.swift
1
2749
// // SceneDelegate.swift // SwiftUI // // Created by zhoubiwen on 2020/7/31. // Copyright © 2020 zbw. All rights reserved. // import UIKit import SwiftUI class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). // Create the SwiftUI view that provides the window contents. let contentView = ContentView() // Use a UIHostingController as window root view controller. if let windowScene = scene as? UIWindowScene { let window = UIWindow(windowScene: windowScene) window.rootViewController = UIHostingController(rootView: contentView) self.window = window window.makeKeyAndVisible() } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. } }
mit
e5b56e31549d931e68f9a5702d0cecf3
41.9375
147
0.703057
5.294798
false
false
false
false
noppoMan/aws-sdk-swift
Sources/Soto/Services/SageMakerRuntime/SageMakerRuntime_Error.swift
1
2302
//===----------------------------------------------------------------------===// // // 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 /// Error enum for SageMakerRuntime public struct SageMakerRuntimeErrorType: AWSErrorType { enum Code: String { case internalFailure = "InternalFailure" case modelError = "ModelError" case serviceUnavailable = "ServiceUnavailable" case validationError = "ValidationError" } private let error: Code public let context: AWSErrorContext? /// initialize SageMakerRuntime public init?(errorCode: String, context: AWSErrorContext) { guard let error = Code(rawValue: errorCode) else { return nil } self.error = error self.context = context } internal init(_ error: Code) { self.error = error self.context = nil } /// return error code string public var errorCode: String { self.error.rawValue } /// An internal failure occurred. public static var internalFailure: Self { .init(.internalFailure) } /// Model (owned by the customer in the container) returned 4xx or 5xx error code. public static var modelError: Self { .init(.modelError) } /// The service is unavailable. Try your call again. public static var serviceUnavailable: Self { .init(.serviceUnavailable) } /// Inspect your request and try again. public static var validationError: Self { .init(.validationError) } } extension SageMakerRuntimeErrorType: Equatable { public static func == (lhs: SageMakerRuntimeErrorType, rhs: SageMakerRuntimeErrorType) -> Bool { lhs.error == rhs.error } } extension SageMakerRuntimeErrorType: CustomStringConvertible { public var description: String { return "\(self.error.rawValue): \(self.message ?? "")" } }
apache-2.0
295d1cf0c60b4eb6bd2a27aebc229540
33.878788
117
0.646829
4.836134
false
false
false
false
LawrenceHan/iOS-project-playground
Homepwner_swift/Homepwner/DetailViewController.swift
1
3836
// // Copyright © 2015 Big Nerd Ranch // import UIKit class DetailViewController: UIViewController, UITextFieldDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate { @IBOutlet var nameField: UITextField! @IBOutlet var serialNumberField: UITextField! @IBOutlet var valueField: UITextField! @IBOutlet var dateLabel: UILabel! @IBOutlet var imageView: UIImageView! var item: Item! { didSet { navigationItem.title = item.name } } var imageStore: ImageStore! @IBAction func takePicture(sender: UIBarButtonItem) { let imagePicker = UIImagePickerController() // If the device has a camera, take a picture, otherwise, // just pick from photo library if UIImagePickerController.isSourceTypeAvailable(.Camera) { imagePicker.sourceType = .Camera } else { imagePicker.sourceType = .PhotoLibrary } imagePicker.delegate = self // Place image picker on the screen presentViewController(imagePicker, animated: true, completion: nil) } func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String: AnyObject]) { // Get picked image from info dictionary let image = info[UIImagePickerControllerOriginalImage] as! UIImage // Store the image in the ImageStore for the item's key imageStore.setImage(image, forKey:item.itemKey) // Put that image onto the screen in our image view imageView.image = image // Take image picker off the screen - // you must call this dismiss method dismissViewControllerAnimated(true, completion: nil) } let numberFormatter: NSNumberFormatter = { let formatter = NSNumberFormatter() formatter.numberStyle = .DecimalStyle formatter.minimumFractionDigits = 2 formatter.maximumFractionDigits = 2 return formatter }() let dateFormatter: NSDateFormatter = { let formatter = NSDateFormatter() formatter.dateStyle = .MediumStyle formatter.timeStyle = .NoStyle return formatter }() override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) nameField.text = item.name serialNumberField.text = item.serialNumber valueField.text = numberFormatter.stringFromNumber(item.valueInDollars) dateLabel.text = dateFormatter.stringFromDate(item.dateCreated) // Get the item key let key = item.itemKey // If there is an associated image with the item ... if let imageToDisplay = imageStore.imageForKey(key) { // ... display it on the image view imageView.image = imageToDisplay } } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) // Clear first responder view.endEditing(true) // "Save" changes to item item.name = nameField.text ?? "" item.serialNumber = serialNumberField.text if let valueText = valueField.text, let value = numberFormatter.numberFromString(valueText) { item.valueInDollars = value.integerValue } else { item.valueInDollars = 0 } } @IBAction func backgroundTapped(sender: UITapGestureRecognizer) { view.endEditing(true) } func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return true } }
mit
2ec825a1ddb366db663cd3117c8136be
30.694215
79
0.61721
5.97352
false
false
false
false
coinbase/coinbase-ios-sdk
Source/Network/Protocols/ResourceAPIProtocol.swift
1
2470
// // ResourceAPI.swift // Coinbase // // Copyright © 2018 Coinbase, Inc. All rights reserved. // import Foundation /// Authentication type definitions. /// /// - none: Authentication is not required. /// - token: Authentication with an access token. /// public enum AuthenticationType { /// Authentication is not required. case none /// Authentication with an access token. case token } /// HTTP request methods. public enum HTTPMethod: String { case options = "OPTIONS" case get = "GET" case head = "HEAD" case post = "POST" case put = "PUT" case patch = "PATCH" case delete = "DELETE" case trace = "TRACE" case connect = "CONNECT" } /// Parameters to pass along with the request. /// /// - body: Parameters to send in the body of the request message. /// - get: Parameters to send as URL query parameter of the request message. public enum RequestParameters { /// Parameters to send in the body of the request message. case body(_ : [String: Any]) /// Parameters to send as URL query parameter of the request message. case get(_ : [String: String]) } /// Defines required parameters to create and validate all API requests. public protocol ResourceAPIProtocol: ValidationOptionsProtocol, RequestConvertible { /// Relative path of the endpoint (i.e. `"/user/auth"`). var path: String { get } /// The HTTP request method. var method: HTTPMethod { get } /// Parameters to send along with the call. var parameters: RequestParameters? { get } /// A dictionary containing *additional* HTTP header fields required for the specific endpoint. /// /// Default value is *empty* dictionary. var headers: [String: String] { get } /// Authentication type for request. /// /// Default value is `AuthenticationType.none` var authentication: AuthenticationType { get } /// Array of fields to expand. /// /// **Online API Documentation** /// /// [Expanding resources](https://developers.coinbase.com/api/v2#expanding-resources) /// var expandOptions: [String] { get } } // MARK: - Default implementation for ResourceAPIProtocol extension ResourceAPIProtocol { public var headers: [String: String] { return [:] } public var authentication: AuthenticationType { return .none } public var expandOptions: [String] { return [] } }
apache-2.0
4b654cc28ba54beaa9c5da2db2618c97
25.836957
99
0.649251
4.408929
false
false
false
false
nalexn/ViewInspector
Tests/ViewInspectorTests/SwiftUI/LazyHGridTests.swift
1
3942
import XCTest import SwiftUI @testable import ViewInspector @available(iOS 13.0, macOS 10.15, tvOS 13.0, *) final class LazyHGridTests: XCTestCase { func testInspect() throws { guard #available(iOS 14, macOS 11.0, tvOS 14.0, watchOS 7.0, *) else { throw XCTSkip() } let view = LazyHGrid(rows: [], content: { Text("abc") }) XCTAssertNoThrow(try view.inspect()) } func testExtractionFromSingleViewContainer() throws { guard #available(iOS 14, macOS 11.0, tvOS 14.0, watchOS 7.0, *) else { throw XCTSkip() } let view = AnyView(LazyHGrid(rows: [], content: { Text("abc") })) XCTAssertNoThrow(try view.inspect().anyView().lazyHGrid()) } func testExtractionFromMultipleViewContainer() throws { guard #available(iOS 14, macOS 11.0, tvOS 14.0, watchOS 7.0, *) else { throw XCTSkip() } let view = HStack { Text("") LazyHGrid(rows: [], content: { Text("abc") }) Text("") } XCTAssertNoThrow(try view.inspect().hStack().lazyHGrid(1)) } func testSearch() throws { guard #available(iOS 14, macOS 11.0, tvOS 14.0, watchOS 7.0, *) else { throw XCTSkip() } let view = HStack { LazyHGrid(rows: [], content: { Text("abc") }) } XCTAssertEqual(try view.inspect().find(ViewType.LazyHGrid.self).pathToRoot, "hStack().lazyHGrid(0)") XCTAssertEqual(try view.inspect().find(text: "abc").pathToRoot, "hStack().lazyHGrid(0).text(0)") } func testContentViewInspection() throws { guard #available(iOS 14, macOS 11.0, tvOS 14.0, watchOS 7.0, *) else { throw XCTSkip() } let view = LazyHGrid(rows: [], content: { ForEach((0...10), id: \.self) { Text("\($0)") } }) let sut = try view.inspect().lazyHGrid().forEach(0) XCTAssertEqual(try sut.text(3).string(), "3") } func testAlignmentInspection() throws { guard #available(iOS 14, macOS 11.0, tvOS 14.0, watchOS 7.0, *) else { throw XCTSkip() } let view = LazyHGrid(rows: [], alignment: .top) { Text("") } let sut = try view.inspect().lazyHGrid().alignment() XCTAssertEqual(sut, .top) } func testSpacingInspection() throws { guard #available(iOS 14, macOS 11.0, tvOS 14.0, watchOS 7.0, *) else { throw XCTSkip() } let view = LazyHGrid(rows: [], spacing: 5) { Text("") } let sut = try view.inspect().lazyHGrid().spacing() XCTAssertEqual(sut, 5) } func testPinnedViewsInspection() throws { guard #available(iOS 14, macOS 11.0, tvOS 14.0, watchOS 7.0, *) else { throw XCTSkip() } let view = LazyHGrid(rows: [], pinnedViews: .sectionFooters) { Text("") } let sut = try view.inspect().lazyHGrid().pinnedViews() XCTAssertEqual(sut, .sectionFooters) } func testRowsInspection() throws { guard #available(iOS 14, macOS 11.0, tvOS 14.0, watchOS 7.0, *) else { throw XCTSkip() } let view = LazyHGrid(rows: [GridItem(.fixed(10))]) { Text("") } let sut = try view.inspect().lazyHGrid().rows() XCTAssertEqual(sut, [GridItem(.fixed(10))]) } } @available(iOS 13.0, macOS 10.15, tvOS 13.0, *) final class GridItemTests: XCTestCase { func testEquatable() throws { guard #available(iOS 14, macOS 11.0, tvOS 14.0, watchOS 7.0, *) else { throw XCTSkip() } let items = [ GridItem(.fixed(5), spacing: 40, alignment: .bottomLeading), GridItem(.adaptive(minimum: 10, maximum: 20)), GridItem(.flexible(minimum: 10, maximum: 20)) ] XCTAssertEqual(items[0], items[0]) XCTAssertEqual(items[1], items[1]) XCTAssertEqual(items[2], items[2]) XCTAssertNotEqual(items[1], items[2]) } }
mit
140ac5a22becb9c7d0a50b76382fb7f7
38.029703
83
0.577372
3.876106
false
true
false
false
xuzhuoxi/SearchKit
Source/cs/wordscoding/PinyinCodingImpl.swift
1
1943
// // PinyinCodingImpl.swift // SearchKit // // Created by 许灼溪 on 15/12/22. // // import Foundation /** * * @author xuzhuoxi * */ class PinyinCodingImpl : ChineseWordsCoding , ChineseWordsCodingProtocol { /** * 编码过程:<br> * 1.不可编码部分作为编码保留,可编码则求取编码。 * 2.编码数组作自由组合,中间补充空格。<br> */ final func coding(_ wordCache: CharacterLibraryProtocol, words: String) -> [String]? { if words.isEmpty { return nil } let parts = participles(wordCache, words: words) var values = [[String]]() var size = 1 for part in parts { if part.length > 1 || !wordCache.isKey(part) { values.append([part]) }else{ values.append(wordCache.getValues(part.characters.first!)!) size *= values[values.count-1].count } } var rs = [String](repeating: "", count: size) for (i, var sb) in rs.enumerated() { for strAry in values { let index = i % strAry.count sb.append(strAry[index] + " ") } rs[i] = sb.substring(to: sb.characters.index(sb.endIndex, offsetBy: -1)) } return rs } final fileprivate func participles(_ wordCache: CharacterLibraryProtocol, words: String) ->[String] { var temp = [String]() var sb = "" for word in words.characters { if (wordCache.isKey(word)) { if (sb.length > 0) { temp.append(sb) sb.removeAll(keepingCapacity: true) } temp.append(String(word)) } else { sb.append(word) } } if (sb.length > 0) { temp.append(sb) } return temp } }
mit
77c764c159d51987f2657aa8955c267b
25.797101
105
0.49378
3.934043
false
false
false
false
Igor-Palaguta/YoutubeEngine
Example/YoutubeViewController.swift
1
2155
import ReactiveSwift import UIKit import YoutubeEngine extension Engine { #warning("Generate your own API key https://developers.google.com/youtube/v3/getting-started") static let defaultEngine = Engine( authorization: .key("AIzaSyBjLH-61v1oTcb_wQUcGAYIHmWSCj19Ss4"), isLogEnabled: true ) } final class YoutubeViewModel { let keyword = MutableProperty("") } final class YoutubeViewController: UIViewController { @IBOutlet private var searchBar: UISearchBar! private let model = YoutubeViewModel() override func viewDidLoad() { super.viewDidLoad() navigationItem.titleView = searchBar automaticallyAdjustsScrollViewInsets = false } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard let contentController = segue.destination as? ItemsViewController else { return } contentController.model.mutableProvider <~ model.keyword.signal .debounce(0.5, on: QueueScheduler.main) .map { keyword -> AnyItemsProvider<DisplayItem>? in if keyword.isEmpty { return nil } return AnyItemsProvider { token, limit in let request: SearchRequest = .search( withTerm: keyword, requiredVideoParts: [.statistics, .contentDetails], requiredChannelParts: [.statistics], requiredPlaylistParts: [.snippet], limit: limit, pageToken: token ) return Engine.defaultEngine .search(request) .map { page in (page.items.map { $0.displayItem }, page.nextPageToken) } } } } } extension YoutubeViewController: UISearchBarDelegate { func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { model.keyword.value = searchText } func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { searchBar.resignFirstResponder() } }
mit
fd5028103be870666c2db3c6a2382e73
32.153846
98
0.60232
5.455696
false
false
false
false
IngmarStein/swift
test/attr/attr_dynamic.swift
4
2413
// RUN: %target-parse-verify-swift // RUN: %target-swift-ide-test -print-ast-typechecked -source-filename=%s -print-implicit-attrs struct NotObjCAble { var c: Foo } @objc class ObjCClass {} dynamic prefix operator +!+ // expected-error{{'dynamic' modifier cannot be applied to this declaration}} {{1-9=}} class Foo { dynamic init() {} dynamic init(x: NotObjCAble) {} // expected-error{{method cannot be marked dynamic because the type of the parameter cannot be represented in Objective-C}} expected-note{{Swift structs cannot be represented in Objective-C}} dynamic var x: Int dynamic var nonObjcVar: NotObjCAble // expected-error{{property cannot be marked dynamic because its type cannot be represented in Objective-C}} expected-note{{Swift structs cannot be represented in Objective-C}} dynamic func foo(x: Int) {} dynamic func bar(x: Int) {} dynamic func nonObjcFunc(x: NotObjCAble) {} // expected-error{{method cannot be marked dynamic because the type of the parameter cannot be represented in Objective-C}} expected-note{{Swift structs cannot be represented in Objective-C}} dynamic subscript(x: Int) -> ObjCClass { get {} } dynamic subscript(x: Int) -> NotObjCAble { get {} } // expected-error{{subscript cannot be marked dynamic because its type cannot be represented in Objective-C}} expected-note{{Swift structs cannot be represented in Objective-C}} dynamic deinit {} // expected-error{{'dynamic' modifier cannot be applied to this declaration}} {{3-11=}} func notDynamic() {} final dynamic func indecisive() {} // expected-error{{a declaration cannot be both 'final' and 'dynamic'}} {{9-17=}} } struct Bar { dynamic init() {} // expected-error{{only members of classes may be dynamic}} {{3-11=}} dynamic var x: Int // expected-error{{only members of classes may be dynamic}} {{3-11=}} dynamic subscript(x: Int) -> ObjCClass { get {} } // expected-error{{only members of classes may be dynamic}} {{3-11=}} dynamic func foo(x: Int) {} // expected-error{{only members of classes may be dynamic}} {{3-11=}} } // CHECK-LABEL: class InheritsDynamic : Foo { class InheritsDynamic: Foo { // CHECK-LABEL: {{^}} dynamic override func foo(x: Int) override func foo(x: Int) {} // CHECK-LABEL: {{^}} dynamic override func foo(x: Int) dynamic override func bar(x: Int) {} // CHECK: {{^}} override func notDynamic() override func notDynamic() {} }
apache-2.0
b0093ed6f64ca91fcc3257633c075858
42.872727
237
0.707833
3.995033
false
false
false
false
PetroccoCo/Lock.iOS-OSX
Examples/AWS/AWS/AWSInMemoryCredentialProvider.swift
3
2173
// AWSInMemoryCredentialProvider.swift // // Copyright (c) 2014 Auth0 (http://auth0.com) // // 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 class AWSInMemoryCredentialProvider: NSObject, AWSCredentialsProvider { private(set) var accessKey: String private(set) var secretKey: String private(set) var sessionKey: String private(set) var expiration: NSDate init(accessKey: NSString, secretKey: NSString, sessionKey: String, expiration: NSDate) { self.accessKey = accessKey; self.secretKey = secretKey; self.sessionKey = sessionKey; self.expiration = expiration; } convenience init(credentials: [NSString: AnyObject!]) { let accessKey = credentials["AccessKeyId"] as String let secretKey = credentials["SecretAccessKey"] as String let sessionKey = credentials["SessionToken"] as String let expirationISO = credentials["Expiration"] as String let expiration = ISO8601DateFormatter().dateFromString(expirationISO) self.init(accessKey: accessKey, secretKey: secretKey, sessionKey: sessionKey, expiration: expiration) } }
mit
bb57785cf4066f09319a449aaa522bde
45.234043
109
0.741371
4.818182
false
false
false
false
dokun1/firstRuleFireplace
FirstRuleFireplace/FirstRuleFireplace/VolumeController.swift
1
1281
// // VolumeController.swift // FirstRuleFireplace // // Created by David Okun on 11/7/15. // Copyright © 2015 David Okun, LLC. All rights reserved. // import UIKit class VolumeController: NSObject { class func adjustVolume(xMovement: Float, yMovement:Float, musicVolume: Float, rainVolume: Float) -> (musicVolume: Float, rainVolume: Float) { let adjustmentFactor:Float = 5500 let minimumTranslationThreshold:Float = 6.999 // haha lol 69 var newMusicVolume:Float = musicVolume var newRainVolume:Float = rainVolume if fabsf(xMovement) > minimumTranslationThreshold { newMusicVolume = newMusicVolume + (xMovement/adjustmentFactor) if newMusicVolume > 1 { newMusicVolume = 1.00 } if newMusicVolume < 0 { newMusicVolume = 0.00 } } if fabsf(yMovement) > minimumTranslationThreshold { newRainVolume = newRainVolume - (yMovement/adjustmentFactor) if newRainVolume > 1 { newRainVolume = 1.00 } if newRainVolume < 0 { newRainVolume = 0.00 } } return (newMusicVolume, newRainVolume) } }
mit
71b605dfa094c0493d2cde7367d33797
29.5
146
0.5875
4.383562
false
false
false
false
Lightstreamer/Lightstreamer-example-StockList-client-ios
iPad/AppDelegate_iPad.swift
2
2504
// Converted to Swift 5.4 by Swiftify v5.4.24488 - https://swiftify.com/ // // AppDelegate_iPad.swift // StockList Demo for iOS // // Copyright (c) Lightstreamer Srl // // 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 LightstreamerClient //@UIApplicationMain class AppDelegate_iPad: NSObject, UIApplicationDelegate, StockListAppDelegate { var splitController: UISplitViewController? // MARK: - // MARK: Properties @IBOutlet var window: UIWindow? private(set) var stockListController: StockListViewController? private(set) var detailController: DetailViewController? // MARK: - // MARK: Application lifecycle func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool { application.statusBarStyle = .lightContent // Uncomment for detailed logging // LightstreamerClient.setLoggerProvider(ConsoleLoggerProvider(level: .debug)) // Create the user interface stockListController = StockListViewController() var navController1: UINavigationController? = nil if let stockListController = stockListController { navController1 = UINavigationController(rootViewController: stockListController) } navController1?.navigationBar.barStyle = .black detailController = DetailViewController() var navController2: UINavigationController? = nil if let detailController = detailController { navController2 = UINavigationController(rootViewController: detailController) } navController2?.navigationBar.barStyle = .black splitController = UISplitViewController() splitController?.viewControllers = [navController1, navController2].compactMap { $0 } window?.rootViewController = splitController window?.makeKeyAndVisible() return true } // MARK: - // MARK: Properties }
apache-2.0
e9a78cec04db56f65c1fdef2422b4038
32.837838
152
0.719649
5.227557
false
false
false
false
vmanot/swift-package-manager
Tests/UtilityTests/VersionTests.swift
1
11212
/* 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 http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ import struct Utility.Version import XCTest class VersionTests: XCTestCase { func testEquality() { let versions: [Version] = ["1.2.3", "0.0.0", "0.0.0-alpha+yol", "0.0.0-alpha.1+pol", "0.1.2", "10.7.3", ] // Test that each version is equal to itself and not equal to others. for (idx, version) in versions.enumerated() { for (ridx, rversion) in versions.enumerated() { if idx == ridx { XCTAssertEqual(version, rversion) // Construct the object again with different initializer. XCTAssertEqual(version, Version(rversion.major, rversion.minor, rversion.patch, prereleaseIdentifiers: rversion.prereleaseIdentifiers, buildMetadataIdentifiers: rversion.buildMetadataIdentifiers)) } else { XCTAssertNotEqual(version, rversion) } } } } func testHashable() { let versions: [Version] = ["1.2.3", "1.2.3", "1.2.3", "1.0.0-alpha", "1.0.0-alpha", "1.0.0", "1.0.0" ] XCTAssertEqual(Set(versions), Set(["1.0.0-alpha", "1.2.3", "1.0.0"])) XCTAssertEqual(Set([Version(1,2,3)]), Set([Version(1,2,3)])) XCTAssertNotEqual(Set([Version(1,2,3)]), Set([Version(1,2,3, prereleaseIdentifiers: ["alpha"])])) XCTAssertNotEqual(Set([Version(1,2,3)]), Set([Version(1,2,3, buildMetadataIdentifiers: ["1011"])])) } func testDescription() { let v: Version = "123.234.345-alpha.beta+sha1.1011" XCTAssertEqual(v.description, "123.234.345-alpha.beta+sha1.1011") XCTAssertEqual(v.major, 123) XCTAssertEqual(v.minor, 234) XCTAssertEqual(v.patch, 345) XCTAssertEqual(v.prereleaseIdentifiers, ["alpha", "beta"]) XCTAssertEqual(v.buildMetadataIdentifiers, ["sha1", "1011"]) } func testFromString() { let badStrings = [ "", "1", "1.2", "1.2.3.4", "1.2.3.4.5", "a", "1.a", "a.2", "a.2.3", "1.a.3", "1.2.a", "-1.2.3", "1.-2.3", "1.2.-3", ".1.2.3", "v.1.2.3", "1.2..3", "v1.2.3", ] for str in badStrings { XCTAssertNil(Version(string: str)) } XCTAssertEqual(Version(1,2,3), Version(string: "1.2.3")) XCTAssertEqual(Version(1,2,3), Version(string: "01.002.0003")) XCTAssertEqual(Version(0,9,21), Version(string: "0.9.21")) XCTAssertEqual(Version(0,9,21, prereleaseIdentifiers: ["alpha", "beta"], buildMetadataIdentifiers: ["1011"]), Version(string: "0.9.21-alpha.beta+1011")) XCTAssertEqual(Version(0,9,21, prereleaseIdentifiers: [], buildMetadataIdentifiers: ["1011"]), Version(string: "0.9.21+1011")) } func testComparable() { do { let v1 = Version(1,2,3) let v2 = Version(2,1,2) XCTAssertLessThan(v1, v2) XCTAssertLessThanOrEqual(v1, v2) XCTAssertGreaterThan(v2, v1) XCTAssertGreaterThanOrEqual(v2, v1) XCTAssertNotEqual(v1, v2) XCTAssertLessThanOrEqual(v1, v1) XCTAssertGreaterThanOrEqual(v1, v1) XCTAssertLessThanOrEqual(v2, v2) XCTAssertGreaterThanOrEqual(v2, v2) } do { let v3 = Version(2,1,3) let v4 = Version(2,2,2) XCTAssertLessThan(v3, v4) XCTAssertLessThanOrEqual(v3, v4) XCTAssertGreaterThan(v4, v3) XCTAssertGreaterThanOrEqual(v4, v3) XCTAssertNotEqual(v3, v4) XCTAssertLessThanOrEqual(v3, v3) XCTAssertGreaterThanOrEqual(v3, v3) XCTAssertLessThanOrEqual(v4, v4) XCTAssertGreaterThanOrEqual(v4, v4) } do { let v5 = Version(2,1,2) let v6 = Version(2,1,3) XCTAssertLessThan(v5, v6) XCTAssertLessThanOrEqual(v5, v6) XCTAssertGreaterThan(v6, v5) XCTAssertGreaterThanOrEqual(v6, v5) XCTAssertNotEqual(v5, v6) XCTAssertLessThanOrEqual(v5, v5) XCTAssertGreaterThanOrEqual(v5, v5) XCTAssertLessThanOrEqual(v6, v6) XCTAssertGreaterThanOrEqual(v6, v6) } do { let v7 = Version(0,9,21) let v8 = Version(2,0,0) XCTAssert(v7 < v8) XCTAssertLessThan(v7, v8) XCTAssertLessThanOrEqual(v7, v8) XCTAssertGreaterThan(v8, v7) XCTAssertGreaterThanOrEqual(v8, v7) XCTAssertNotEqual(v7, v8) XCTAssertLessThanOrEqual(v7, v7) XCTAssertGreaterThanOrEqual(v7, v7) XCTAssertLessThanOrEqual(v8, v8) XCTAssertGreaterThanOrEqual(v8, v8) } do { // Prerelease precedence tests taken directly from http://semver.org var tests: [Version] = [ "1.0.0-alpha", "1.0.0-alpha.1", "1.0.0-alpha.beta", "1.0.0-beta", "1.0.0-beta.2", "1.0.0-beta.11", "1.0.0-rc.1", "1.0.0" ] var v1 = tests.removeFirst() for v2 in tests { XCTAssertLessThan(v1, v2) XCTAssertLessThanOrEqual(v1, v2) XCTAssertGreaterThan(v2, v1) XCTAssertGreaterThanOrEqual(v2, v1) XCTAssertNotEqual(v1, v2) XCTAssertLessThanOrEqual(v1, v1) XCTAssertGreaterThanOrEqual(v1, v1) XCTAssertLessThanOrEqual(v2, v2) XCTAssertGreaterThanOrEqual(v2, v2) v1 = v2 } } } func testOrder() { XCTAssertLessThan(Version(0,0,0), Version(0,0,1)) XCTAssertLessThan(Version(0,0,1), Version(0,1,0)) XCTAssertLessThan(Version(0,1,0), Version(0,10,0)) XCTAssertLessThan(Version(0,10,0), Version(1,0,0)) XCTAssertLessThan(Version(1,0,0), Version(2,0,0)) XCTAssert(!(Version(1,0,0) < Version(1,0,0))) XCTAssert(!(Version(2,0,0) < Version(1,0,0))) } func testRange() { switch Version(1,2,4) { case Version(1,2,3)..<Version(2,3,4): break default: XCTFail() } switch Version(1,2,4) { case Version(1,2,3)..<Version(2,3,4): break case Version(1,2,5)..<Version(1,2,6): XCTFail() default: XCTFail() } switch Version(1,2,4) { case Version(1,2,3)..<Version(1,2,4): XCTFail() case Version(1,2,5)..<Version(1,2,6): XCTFail() default: break } switch Version(1,2,4) { case Version(1,2,5)..<Version(2,0,0): XCTFail() case Version(2,0,0)..<Version(2,2,6): XCTFail() case Version(0,0,1)..<Version(0,9,6): XCTFail() default: break } } func testContains() { do { let range: Range<Version> = "1.0.0"..<"2.0.0" XCTAssertTrue(range.contains(version: "1.0.0")) XCTAssertTrue(range.contains(version: "1.5.0")) XCTAssertTrue(range.contains(version: "1.9.99999")) XCTAssertTrue(range.contains(version: "1.9.99999+1232")) XCTAssertFalse(range.contains(version: "1.0.0-alpha")) XCTAssertFalse(range.contains(version: "1.5.0-alpha")) XCTAssertFalse(range.contains(version: "2.0.0-alpha")) XCTAssertFalse(range.contains(version: "2.0.0")) } do { let range: Range<Version> = "1.0.0"..<"2.0.0-beta" XCTAssertTrue(range.contains(version: "1.0.0")) XCTAssertTrue(range.contains(version: "1.5.0")) XCTAssertTrue(range.contains(version: "1.9.99999")) XCTAssertTrue(range.contains(version: "1.0.1-alpha")) XCTAssertTrue(range.contains(version: "2.0.0-alpha")) XCTAssertFalse(range.contains(version: "1.0.0-alpha")) XCTAssertFalse(range.contains(version: "2.0.0")) XCTAssertFalse(range.contains(version: "2.0.0-beta")) XCTAssertFalse(range.contains(version: "2.0.0-clpha")) } do { let range: Range<Version> = "1.0.0-alpha"..<"2.0.0" XCTAssertTrue(range.contains(version: "1.0.0")) XCTAssertTrue(range.contains(version: "1.5.0")) XCTAssertTrue(range.contains(version: "1.9.99999")) XCTAssertTrue(range.contains(version: "1.0.0-alpha")) XCTAssertTrue(range.contains(version: "1.0.0-beta")) XCTAssertTrue(range.contains(version: "1.0.1-alpha")) XCTAssertFalse(range.contains(version: "2.0.0-alpha")) XCTAssertFalse(range.contains(version: "2.0.0-beta")) XCTAssertFalse(range.contains(version: "2.0.0-clpha")) XCTAssertFalse(range.contains(version: "2.0.0")) } do { let range: Range<Version> = "1.0.0"..<"1.1.0" XCTAssertTrue(range.contains(version: "1.0.0")) XCTAssertTrue(range.contains(version: "1.0.9")) XCTAssertFalse(range.contains(version: "1.1.0")) XCTAssertFalse(range.contains(version: "1.2.0")) XCTAssertFalse(range.contains(version: "1.5.0")) XCTAssertFalse(range.contains(version: "2.0.0")) XCTAssertFalse(range.contains(version: "1.0.0-beta")) XCTAssertFalse(range.contains(version: "1.0.10-clpha")) XCTAssertFalse(range.contains(version: "1.1.0-alpha")) } do { let range: Range<Version> = "1.0.0"..<"1.1.0-alpha" XCTAssertTrue(range.contains(version: "1.0.0")) XCTAssertTrue(range.contains(version: "1.0.9")) XCTAssertTrue(range.contains(version: "1.0.1-beta")) XCTAssertTrue(range.contains(version: "1.0.10-clpha")) XCTAssertFalse(range.contains(version: "1.1.0")) XCTAssertFalse(range.contains(version: "1.2.0")) XCTAssertFalse(range.contains(version: "1.5.0")) XCTAssertFalse(range.contains(version: "2.0.0")) XCTAssertFalse(range.contains(version: "1.0.0-alpha")) XCTAssertFalse(range.contains(version: "1.1.0-alpha")) XCTAssertFalse(range.contains(version: "1.1.0-beta")) } } static var allTests = [ ("testEquality", testEquality), ("testHashable", testHashable), ("testComparable", testComparable), ("testDescription", testDescription), ("testFromString", testFromString), ("testOrder", testOrder), ("testRange", testRange), ("testContains", testContains), ] }
apache-2.0
d0279ab6358cdcd636cd05e662f9a2ea
36.498328
134
0.555209
3.761154
false
true
false
false
Quick/Nimble
Sources/Nimble/Matchers/HaveCount.swift
2
3305
// The `haveCount` matchers do not print the full string representation of the collection value, // instead they only print the type name and the expected count. This makes it easier to understand // the reason for failed expectations. See: https://github.com/Quick/Nimble/issues/308. // The representation of the collection content is provided in a new line as an `extendedMessage`. /// A Nimble matcher that succeeds when the actual Collection's count equals /// the expected value public func haveCount<T: Collection>(_ expectedValue: Int) -> Predicate<T> { return Predicate.define { actualExpression in if let actualValue = try actualExpression.evaluate() { let message = ExpectationMessage .expectedCustomValueTo( "have \(prettyCollectionType(actualValue)) with count \(stringify(expectedValue))", actual: "\(actualValue.count)" ) .appended(details: "Actual Value: \(stringify(actualValue))") let result = expectedValue == actualValue.count return PredicateResult(bool: result, message: message) } else { return PredicateResult(status: .fail, message: .fail("")) } } } /// A Nimble matcher that succeeds when the actual collection's count equals /// the expected value public func haveCount(_ expectedValue: Int) -> Predicate<NMBCollection> { return Predicate { actualExpression in if let actualValue = try actualExpression.evaluate() { let message = ExpectationMessage .expectedCustomValueTo( "have \(prettyCollectionType(actualValue)) with count \(stringify(expectedValue))", actual: "\(actualValue.count). Actual Value: \(stringify(actualValue))" ) let result = expectedValue == actualValue.count return PredicateResult(bool: result, message: message) } else { return PredicateResult(status: .fail, message: .fail("")) } } } #if canImport(Darwin) import Foundation extension NMBPredicate { @objc public class func haveCountMatcher(_ expected: NSNumber) -> NMBPredicate { return NMBPredicate { actualExpression in let location = actualExpression.location let actualValue = try actualExpression.evaluate() if let value = actualValue as? NMBCollection { let expr = Expression(expression: ({ value as NMBCollection}), location: location) return try haveCount(expected.intValue).satisfies(expr).toObjectiveC() } let message: ExpectationMessage if let actualValue = actualValue { message = ExpectationMessage.expectedCustomValueTo( "get type of NSArray, NSSet, NSDictionary, or NSHashTable", actual: "\(String(describing: type(of: actualValue)))" ) } else { message = ExpectationMessage .expectedActualValueTo("have a collection with count \(stringify(expected.intValue))") .appendedBeNilHint() } return NMBPredicateResult(status: .fail, message: message.toObjectiveC()) } } } #endif
apache-2.0
379d50b4e7298d8a88ea60f1787304e0
44.273973
106
0.632073
5.639932
false
false
false
false
jslim89/maplot-ios
Maplot/Helpers/DBManager.swift
1
3918
// // DBManager.swift // Maplot // // Created by Jeong Sheng Lim on 9/1/15. // Copyright (c) 2015 Js Lim. All rights reserved. // import UIKit import CoreData class DBManager: NSObject { static let sharedInstance = DBManager() // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "uk.co.plymouthsoftware.core_data" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("DataModel", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("DataStore.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) DBManager.fatalCoreDataError(wrappedError) } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { let nserror = error as NSError DBManager.fatalCoreDataError(nserror) } } } func deleteObject(object: NSManagedObject) { self.managedObjectContext.deleteObject(object) self.saveContext() } class func fatalCoreDataError(error: NSError?) { if let error = error { print("*** Fatal error: \(error), \(error.userInfo)") } let alert = UIAlertView(title: "Error", message: "Core data error", delegate: nil, cancelButtonTitle: "Close") alert.show() } }
gpl-3.0
869685b9357b8b778f35fc376870080b
45.094118
290
0.68096
5.736457
false
false
false
false
BanyaKrylov/Learn-Swift
protocol.playground/Contents.swift
1
1255
//: Playground - noun: a place where people can play import UIKit protocol Wheel { func drive() } class Car: Wheel { var model: String var numberOfPassengers: Int init(model: String, numberOfPassengers: Int) { self.model = model self.numberOfPassengers = numberOfPassengers } func drive() { print("Пристегнитесь") print("Держите руль") print("Управляйте педалями") } } let tesla = Car(model: "Tesla", numberOfPassengers: 5) //tesla.drive() class Helicopter: Wheel { var numberOfPassengers: Int var speed: Double init(numberOfPassengers: Int, speed: Double) { self.numberOfPassengers = numberOfPassengers self.speed = speed } func drive() { print("Включить автопилот") print("Не бойтесь") } } let nightShark = Helicopter(numberOfPassengers: 8, speed: 150.8) //nightShark.drive() class SportCar: Car { override func drive() { super.drive() print("Аккуратнее") } } let teslaS = SportCar(model: "TeslaS", numberOfPassengers: 7) let wheels: [Wheel] = [tesla, nightShark, teslaS] wheels[2].drive()
apache-2.0
33845c72702201f46c18af3f1064882e
18.616667
64
0.627867
3.492582
false
false
false
false
yuhao-ios/DouYuTVForSwift
DouYuTVForSwift/DouYuTVForSwift/Home/Controller/HomeVC.swift
1
4169
// // HomeVC.swift // DouYuTVForSwift // // Created by t4 on 17/4/14. // Copyright © 2017年 t4. All rights reserved. // import UIKit class HomeVC: UIViewController { //MARK: 懒加载 let titles = ["推荐","游戏","娱乐","趣玩"] //标题视图 fileprivate lazy var pageTitleView : PageTitleView = { [weak self] in let titleViewFrame = CGRect(x: 0, y:kStatusBarH+kNaviBarH , width: kMainWidth, height: kPageTitleViewH) let titleView = PageTitleView(frame: titleViewFrame, titles: (self?.titles)!) return titleView }() //标题视图对应的内容视图 fileprivate lazy var pageContentView:PageContentView = { [weak self] in //1.确定内容视图的frame let contentViewFrame : CGRect = CGRect(x: 0, y: kStatusBarH+kNaviBarH+kPageTitleViewH, width: kMainWidth, height: kMainHeight-kStatusBarH-kNaviBarH-kPageTitleViewH-kTabBarH) //2.确定内容视图所有的子控制器 var childVcs = [UIViewController]() childVcs.append(RecommendVC()) childVcs.append(GameViewController()) childVcs.append(AmuseVC()) childVcs.append(FunnyViewController()) /* for _ in 0..<((self?.titles.count)!-2){ let vc = UIViewController() vc.view.backgroundColor = UIColor(r: CGFloat(arc4random_uniform(UInt32(255))), g: CGFloat(arc4random_uniform(UInt32(255))), b: CGFloat(arc4random_uniform(UInt32(255))), alpha: 1) childVcs.append(vc) }*/ //3.初始化内容视图 let pageContentView = PageContentView(frame: contentViewFrame, childVcs: childVcs, parentViewController: self) return pageContentView }() override func viewDidLoad() { super.viewDidLoad() setUpUI() } } //MARK: - 布局界面 extension HomeVC { //MARK: - 设置UI fileprivate func setUpUI() { //0.不需要系统调整scrollview类边距 automaticallyAdjustsScrollViewInsets = false //1.设置导航栏 setUpNavigationBar() //2.添加标题视图 view.addSubview(pageTitleView) pageTitleView.delegate = self //3.添加标题视图对应的内容视图 view.addSubview(pageContentView) pageContentView.delegate = self as PageContentViewDelegate? } //MARK: - 设置导航栏 fileprivate func setUpNavigationBar(){ //1.设置导航栏左侧视图 //1.1.通过类扩展 创建UIBarButtonItem navigationItem.leftBarButtonItem = UIBarButtonItem.init(imageName: "logo", heightImageName: nil, size: nil) //2. 设置导航栏右侧视图 //2.1 创建 浏览记录 、扫描 、 搜索三个item let size = CGSize(width: 40, height: 40) let historyItem = UIBarButtonItem.init(imageName: "image_my_history", heightImageName: "Image_my_history_click", size: size) let searchItem = UIBarButtonItem.init(imageName: "btn_search", heightImageName: "btn_search_clicked", size: size) let qrcodeItem = UIBarButtonItem.init(imageName: "Image_scan", heightImageName: "Image_scan_click", size: size) //2.2把item设置为导航栏右侧视图 navigationItem.rightBarButtonItems = [historyItem,searchItem,qrcodeItem] } } //MARK: - 代理协议 extension HomeVC : PageTitleViewDelegate,PageContentViewDelegate{ func pageTitleView(titleView: PageTitleView, selectViewIndex index: Int) { //调用方法 通知内容视图做出相应的改变 pageContentView.selectIndexForTitleMakeContentViewChange(index: index) } func pageContentView(contentView: PageContentView, progress: CGFloat, scrollOfIndex sourceIndex: Int, targetIndex: Int) { //调用方法 通知标题视图做出相应改变 pageTitleView.changeTitleViewSelectIndex(progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex) } }
mit
3322c58a5c4bc2fc01fee7746baf2dfb
25.732394
192
0.629874
4.492308
false
false
false
false
tinrobots/CoreDataPlus
Sources/NSManagedObjectContext+History.swift
1
7847
// CoreDataPlus // // https://mjtsai.com/blog/2020/08/21/persistent-history-tracking-in-core-data/ // https://developer.apple.com/documentation/coredata/consuming_relevant_store_changes // https://developer.apple.com/documentation/coredata/synchronizing_a_local_store_to_the_cloud // WWDC 2020: History requests can be tailored like standard fetch requests (see testInvestigationHistoryFetches) import CoreData import Foundation extension NSManagedObjectContext { // MARK: - Transactions /// Returns all the history transactions (anche their associated changes) given a `NSPersistentHistoryChangeRequest` request. public func historyTransactions(using historyFetchRequest: NSPersistentHistoryChangeRequest) throws -> [NSPersistentHistoryTransaction] { historyFetchRequest.resultType = .transactionsAndChanges return try performAndWaitResult { context ->[NSPersistentHistoryTransaction] in // swiftlint:disable force_cast let history = try context.execute(historyFetchRequest) as! NSPersistentHistoryResult let transactions = history.result as! [NSPersistentHistoryTransaction] // ordered from the oldest to the most recent // swiftlint:enable force_cast return transactions } } // MARK: - Changes /// Returns all the history changes given a `NSPersistentHistoryChangeRequest` request. public func historyChanges(using historyFetchRequest: NSPersistentHistoryChangeRequest) throws -> [NSPersistentHistoryChange] { historyFetchRequest.resultType = .changesOnly return try performAndWaitResult { context ->[NSPersistentHistoryChange] in // swiftlint:disable force_cast let history = try context.execute(historyFetchRequest) as! NSPersistentHistoryResult let changes = history.result as! [NSPersistentHistoryChange] // ordered from the oldest to the most recent // swiftlint:enable force_cast return changes } } /// Merges all the changes contained in the given list of `NSPersistentHistoryTransaction`. /// Returns the last merged transaction's token and timestamp. public func mergeTransactions(_ transactions: [NSPersistentHistoryTransaction]) throws -> (NSPersistentHistoryToken, Date)? { // Do your merging inside a context.performAndWait { … } as shown in WWDC 2017 let result = performAndWaitResult { _ -> (NSPersistentHistoryToken, Date)? in var result: (NSPersistentHistoryToken, Date)? for transaction in transactions { result = (transaction.token, transaction.timestamp) guard transaction.changes != nil else { continue } mergeChanges(fromContextDidSave: transaction.objectIDNotification()) } return result } return result } // MARK: - Delete /// Deletes all history. @discardableResult public func deleteHistory() throws -> Bool { return try deleteHistory(before: .distantFuture) } /// Deletes all history before a given `date`. /// /// - Parameter date: The date before which the history will be deleted. /// - Returns: `true` if the operation succeeds. /// - Throws: It throws an error in cases of failure. /// - Note: Deletions can have tombstones if enabled on single attribues of an entity ( Data Model Inspector > "Preserve After Deletion"). @discardableResult public func deleteHistory(before date: Date) throws -> Bool { let deleteHistoryRequest = NSPersistentHistoryChangeRequest.deleteHistory(before: date) return try deleteHistory(using: deleteHistoryRequest) } /// Deletes all history before a given `token`. /// /// - Parameter token: The token before which the history will be deleted. /// - Returns: `true` if the operation succeeds. /// - Throws: It throws an error in cases of failure. @discardableResult public func deleteHistory(before token: NSPersistentHistoryToken?) throws -> Bool { let deleteHistoryRequest = NSPersistentHistoryChangeRequest.deleteHistory(before: token) return try deleteHistory(using: deleteHistoryRequest) } /// Deletes all history before a given `transaction`. /// /// - Parameter transaction: The transaction before which the history will be deleted. /// - Returns: `true` if the operation succeeds. /// - Throws: It throws an error in cases of failure. @discardableResult public func deleteHistory(before transaction: NSPersistentHistoryTransaction) throws -> Bool { let deleteHistoryRequest = NSPersistentHistoryChangeRequest.deleteHistory(before: transaction) return try deleteHistory(using: deleteHistoryRequest) } /// Deletes all history given a delete `NSPersistentHistoryChangeRequest` instance. private func deleteHistory(using deleteHistoryRequest: NSPersistentHistoryChangeRequest) throws -> Bool { deleteHistoryRequest.resultType = .statusOnly let result = try performAndWaitResult { context -> Bool in // swiftlint:disable force_cast let history = try context.execute(deleteHistoryRequest) as! NSPersistentHistoryResult let status = history.result as! Bool // swiftlint:enable force_cast return status } return result } } extension NSPersistentHistoryChangeRequest { /// Creates a NSPersistentHistoryChangeRequest to query the Transaction entity. /// - Note: context is used as hint to discover the Transaction entity. /// /// The predicate conditions must be applied to these fields (of the "Transaction" entity): /// /// - `author` (`NSString`) /// - `bundleID` (`NSString`) /// - `contextName` (`NSString`) /// - `processID` (`NSString`) /// - `timestamp` (`NSDate`) /// - `token` (`NSNumber` - `NSInteger64`) /// - `transactionNumber` (`NSNumber` - `NSInteger64`) @available(iOS 13.0, iOSApplicationExtension 13.0, macCatalyst 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *) public final class func historyTransactionFetchRequest(with context: NSManagedObjectContext, where predicate: NSPredicate) -> NSPersistentHistoryChangeRequest? { guard let entity = NSPersistentHistoryTransaction.entityDescription(with: context) else { return nil } let transactionFetchRequest = NSFetchRequest<NSFetchRequestResult>() transactionFetchRequest.entity = entity // same as (but for some reasons it's nil during tests): // https://developer.apple.com/videos/play/wwdc2019/230 // let transactionFetchRequest = NSPersistentHistoryTransaction.fetchRequest transactionFetchRequest.predicate = predicate let historyFetchRequest = NSPersistentHistoryChangeRequest.fetchHistory(withFetch: transactionFetchRequest) return historyFetchRequest } /// Creates a NSPersistentHistoryChangeRequest to query the Change entity. /// - Note: context is used as hint to discover the Change entity. /// /// The predicate conditions must be applied to these fields (of the "Change" entity): /// /// - `changedID` (`NSNumber` - `NSInteger64`) /// - `changedEntity` (`NSNumber` - `NSInteger64`) /// - `changeType` (`NSNumber` - `NSInteger64`) @available(iOS 13.0, iOSApplicationExtension 13.0, macCatalyst 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *) public final class func historyChangeFetchRequest(with context: NSManagedObjectContext, where predicate: NSPredicate) -> NSPersistentHistoryChangeRequest? { guard let entity = NSPersistentHistoryChange.entityDescription(with: context) else { return nil } let changeFetchRequest = NSFetchRequest<NSFetchRequestResult>() changeFetchRequest.entity = entity // same as (but for some reasons it's nil during tests): // https://developer.apple.com/videos/play/wwdc2019/230 // let changeFetchRequest = NSPersistentHistoryChange.fetchRequest changeFetchRequest.predicate = predicate let historyFetchRequest = NSPersistentHistoryChangeRequest.fetchHistory(withFetch: changeFetchRequest) return historyFetchRequest } }
mit
7dfd156cea99d1acf025c30fba00226c
47.128834
163
0.746463
4.757429
false
false
false
false
or1onsli/Fou.run-
MusicRun/Pentagramma.swift
1
1854
// // Pentagramma.swift // Fou.run() // // Copyright © 2016 Shock&Awe. All rights reserved. // import UIKit import AudioKit class Pentagramma: UIImageView { let defaultPosition = CGPoint(x: 0, y: 87) let defaultSize = CGSize(width: 750, height: 195) var lastBeatAnimationTime: Int = 0 var nextBeat: Int = 0 init() { super.init(image: UIImage(named: "sky_double")) self.frame.origin = defaultPosition self.frame.size = defaultSize } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func mover() { if self.frame.origin.x > defaultPosition.x-375 { self.frame.origin.x -= 2} else { self.frame.origin.x = defaultPosition.x } } func jumper (withCurrentTime currentTime: Double, withArray songArray: [Int]) { let playerTimeCentsOfSecond = Int((currentTime)*100) if ((songArray[nextBeat] - playerTimeCentsOfSecond + 140) < 10) && (nextBeat < songArray.count-1) { if playerTimeCentsOfSecond - lastBeatAnimationTime > 40 { self.frame.size.height = 240 self.frame.origin.y -= 30 nextBeat += 1 lastBeatAnimationTime = playerTimeCentsOfSecond } else { nextBeat += 1 } } else { if self.frame.origin.y < defaultPosition.y { self.frame.origin.y += 5} if self.frame.size.height > defaultSize.height { self.frame.size.height -= 2 } } } /* // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing code } */ }
mit
51f9acf17d43609b3fc3757836da74b9
27.953125
107
0.577442
4.145414
false
false
false
false
TZLike/GiftShow
GiftShow/GiftShow/Classes/Other/LeeBaseViewController.swift
1
1697
// // LeeBaseViewController.swift // GiftShow // // Created by admin on 16/10/21. // Copyright © 2016年 Mr_LeeKi. All rights reserved. // import UIKit //自定义tabbar class LeeBaseViewController: UITabBarController { override func viewDidLoad() { super.viewDidLoad() tabBar.tintColor = UIColor.red //主页 createChileViewController(LeeHomeViewController(), titleLable: "首页", normalImage:"tab_icon_home_default", seletedImage: "tab_icon_home_Select") //热门 createChileViewController(LeeHotViewController(), titleLable: "榜单", normalImage:"tab_btn_list_default", seletedImage: "tab_btn_list_select") //分类 createChileViewController(LeeCategoryViewController(), titleLable: "分类", normalImage:"tab_btn_sort_default", seletedImage: "tab_btn_sort_select") //我 createChileViewController(LeeMeViewController(), titleLable: "我的", normalImage:"tab_btn_mine_default", seletedImage: "tab_btn_mine_select") } // MARK:创建子控制器 /** 这是创建控制器 - parameter vc: 控制器 - parameter titleLable: 标题 - parameter normalImage: 正常图片 - parameter seletedImage: 选中图片 */ fileprivate func createChileViewController(_ vc:UIViewController,titleLable:String,normalImage:String,seletedImage:String){ vc.tabBarItem.title = titleLable vc.tabBarItem.image = UIImage(named: normalImage) vc.tabBarItem.selectedImage = UIImage(named: seletedImage) let nav = LeeNavgationController(rootViewController: vc) addChildViewController(nav) } }
apache-2.0
4996d0a7f9e884859ddca3bb4756e199
32.458333
154
0.676837
4.248677
false
false
false
false
mbeloded/beaconDemo
PassKitApp/PassKitApp/Classes/UI/MainMenu/MainMenuViewController.swift
1
1941
// // MainMenuViewController.swift // PassKitApp // // Created by Alexandr Chernyy on 10/3/14. // Copyright (c) 2014 Alexandr Chernyy. All rights reserved. // import UIKit class MainMenuViewController: RootViewController { @IBOutlet weak var mainMenuView: MainMenuView! @IBOutlet weak var bannerView: BannerView! override func viewDidLoad() { super.viewDidLoad() mainMenuView.owner = self mainMenuView.setupView() var items:Array<AnyObject> = CoreDataManager.sharedManager.loadData(RequestType.MALL) if(items.count > 0) { var mallModel:MallModel = items[0] as MallModel self.title = mallModel.name bannerView.setupView(mallModel.id) } self.hideLeftButton() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // 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!) { if(segue.identifier == "showCategory") { let viewController:CategoryViewController = segue.destinationViewController as CategoryViewController var items:Array<AnyObject> = CoreDataManager.sharedManager.loadData(RequestType.MALL) if(items.count > 0) { var mallModel:MallModel = items[0] as MallModel viewController.mall_id = mallModel.id viewController.category_id = mainMenuView.category_id } } } @IBAction func rightSwipeAction(sender: AnyObject) { bannerView.update() } @IBAction func leftSwipeAction(sender: AnyObject) { bannerView.updateMinus() } }
gpl-2.0
50177f3d8c3833d66c1456a38086ea4f
28.861538
113
0.632148
5.107895
false
false
false
false
Constructor-io/constructorio-client-swift
UserApplication/Screens/Details/UI/DetailsViewController.swift
1
3367
// // DetailsViewController.swift // UserApplication // // Copyright © Constructor.io. All rights reserved. // http://constructor.io/ // import UIKit class DetailsViewController: UIViewController { @IBOutlet weak var labelTitlePrice: UILabel! @IBOutlet weak var labelDescription: UILabel! @IBOutlet weak var imageViewProduct: UIImageView! @IBOutlet weak var buttonBuy: UIButton! let viewModel: DetailsViewModel let constructorProvider: ConstructorIOProvider var cartButton: CartBarButtonItem! init(viewModel: DetailsViewModel, constructorProvider: ConstructorIOProvider){ self.viewModel = viewModel self.constructorProvider = constructorProvider super.init(nibName: "DetailsViewController", bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() self.setupUI() } func setupUI(){ self.cartButton = CartBarButtonItem.addToViewController(viewController: self, cart: self.viewModel.cart, constructorProvider: self.constructorProvider) self.labelDescription.text = self.viewModel.description self.labelDescription.textColor = UIColor.darkGray if let image = self.viewModel.image{ self.imageViewProduct.image = image }else{ self.imageViewProduct.kf.setImage(with: URL(string: self.viewModel.imageURL)) } self.labelTitlePrice.text = self.viewModel.titlePrice self.labelTitlePrice.font = UIFont.systemFont(ofSize: self.labelDescription.font.pointSize+6, weight: .bold) let colorBrown = UIColor.RGB(183, green: 173, blue: 142) self.buttonBuy.setTitleColor(colorBrown, for: .normal) self.buttonBuy.layer.borderColor = colorBrown.cgColor self.buttonBuy.layer.borderWidth = 1.2 self.buttonBuy.addTarget(self, action: #selector(didTapOnButtonBuy), for: .touchUpInside) } @objc func didTapOnButtonBuy(){ let cartItem = CartItem(title: self.viewModel.title, imageURL: self.viewModel.imageURL, price: self.viewModel.price, quantity: 1) self.viewModel.cart.addItem(cartItem) self.cartButton.update() self.animateBuyProduct() } func animateBuyProduct(){ // initialize animatable image view let imageView = UIImageView(image: self.imageViewProduct.image) imageView.contentMode = self.imageViewProduct.contentMode imageView.translatesAutoresizingMaskIntoConstraints = false // convert frame to window coordinates let animatableImageViewFrame = self.view.convert(self.imageViewProduct.frame, to: nil) imageView.frame = animatableImageViewFrame // add subview to window let window = UIApplication.shared.windows.first! window.addSubview(imageView) let barButtonItemView = self.navigationItem.rightBarButtonItem!.value(forKey: "view") as! UIView let targetFrame = barButtonItemView.superview!.convert(barButtonItemView.frame, to: nil) // animate UIView.animate(withDuration: 0.5, animations: { imageView.frame = targetFrame imageView.alpha = 0 }) { _ in imageView.removeFromSuperview() } } }
mit
0ab70aea73d2c1dbda3de9d48c72f847
35.193548
159
0.693108
4.794872
false
false
false
false
devpunk/cartesian
cartesian/View/DrawProjectShare/VDrawProjectShare.swift
1
5152
import UIKit class VDrawProjectShare:VView { private weak var controller:CDrawProjectShare! private weak var viewSpinner:VSpinner! private weak var viewImage:VDrawProjectShareImage! private weak var shareButtons:VDrawProjectShareButtons! private weak var layoutButtonCloseLeft:NSLayoutConstraint! private weak var layoutButtonsShareLeft:NSLayoutConstraint! private let kButtonCloseWidth:CGFloat = 100 private let kButtonCloseHeight:CGFloat = 32 private let kButtonCloseBottom:CGFloat = -20 private let kButtonsShareHeight:CGFloat = 34 private let kButtonsShareWidth:CGFloat = 300 private let kButtonsShareBottom:CGFloat = -20 private let kImageBottom:CGFloat = -20 override init(controller:CController) { super.init(controller:controller) backgroundColor = UIColor.clear self.controller = controller as? CDrawProjectShare let blur:VBlur = VBlur.extraLight() let buttonClose:UIButton = UIButton() buttonClose.translatesAutoresizingMaskIntoConstraints = false buttonClose.backgroundColor = UIColor.cartesianOrange buttonClose.clipsToBounds = true buttonClose.setTitleColor( UIColor.white, for:UIControlState.normal) buttonClose.setTitleColor( UIColor(white:1, alpha:0.2), for:UIControlState.highlighted) buttonClose.setTitle( NSLocalizedString("VDrawProjectShare_buttonClose", comment:""), for:UIControlState.normal) buttonClose.titleLabel!.font = UIFont.bold(size:15) buttonClose.layer.cornerRadius = kButtonCloseHeight / 2.0 buttonClose.addTarget( self, action:#selector(actionClose(sender:)), for:UIControlEvents.touchUpInside) let shareButtons:VDrawProjectShareButtons = VDrawProjectShareButtons( controller:self.controller) shareButtons.isHidden = true self.shareButtons = shareButtons let viewImage:VDrawProjectShareImage = VDrawProjectShareImage( controller:self.controller) viewImage.isHidden = true self.viewImage = viewImage let viewSpinner:VSpinner = VSpinner() self.viewSpinner = viewSpinner addSubview(blur) addSubview(viewImage) addSubview(shareButtons) addSubview(buttonClose) addSubview(viewSpinner) NSLayoutConstraint.equals( view:viewSpinner, toView:self) NSLayoutConstraint.equals( view:blur, toView:self) NSLayoutConstraint.height( view:buttonClose, constant:kButtonCloseHeight) NSLayoutConstraint.bottomToBottom( view:buttonClose, toView:self, constant:kButtonCloseBottom) NSLayoutConstraint.width( view:buttonClose, constant:kButtonCloseWidth) layoutButtonCloseLeft = NSLayoutConstraint.leftToLeft( view:buttonClose, toView:self) NSLayoutConstraint.topToTop( view:viewImage, toView:self) NSLayoutConstraint.bottomToTop( view:viewImage, toView:shareButtons, constant:kImageBottom) NSLayoutConstraint.equalsHorizontal( view:viewImage, toView:self) NSLayoutConstraint.bottomToTop( view:shareButtons, toView:buttonClose, constant:kButtonsShareBottom) NSLayoutConstraint.height( view:shareButtons, constant:kButtonsShareHeight) layoutButtonsShareLeft = NSLayoutConstraint.leftToLeft( view:shareButtons, toView:self) NSLayoutConstraint.width( view:shareButtons, constant:kButtonsShareWidth) } required init?(coder:NSCoder) { return nil } override func layoutSubviews() { let width:CGFloat = bounds.maxX let remainButtonClose:CGFloat = width - kButtonCloseWidth let remainButtonsShare:CGFloat = width - kButtonsShareWidth let buttonCloseLeft:CGFloat = remainButtonClose / 2.0 let buttonsShareLeft:CGFloat = remainButtonsShare / 2.0 layoutButtonCloseLeft.constant = buttonCloseLeft layoutButtonsShareLeft.constant = buttonsShareLeft super.layoutSubviews() } //MARK: actions func actionClose(sender button:UIButton) { controller.close() } func actionShare(sender button:UIButton) { controller.exportImage() } //MARK: public func startLoading() { viewSpinner.startAnimating() shareButtons.isHidden = true viewImage.isHidden = true } func stopLoading() { viewSpinner.stopAnimating() shareButtons.isHidden = false viewImage.isHidden = false viewImage.refresh() shareButtons.updateButtons() } }
mit
caa7c3d25938dfc17e8dc21caec25e42
31
77
0.638393
5.300412
false
false
false
false
cavalcantedosanjos/ND-OnTheMap
OnTheMap/OnTheMap/Services/ServiceManager.swift
1
3400
// // ServiceManager.swift // OnTheMap // // Created by Joao Anjos on 08/02/17. // Copyright © 2017 Joao Anjos. All rights reserved. // import UIKit class ServiceManager: NSObject { // MARK: Shared Instance class func sharedInstance() -> ServiceManager { struct Singleton { static var sharedInstance = ServiceManager() } return Singleton.sharedInstance } // MARK: HttpMethods enum HttpMethod: String { case GET = "GET" case POST = "POST" case DELETE = "DELETE" case PUT = "PUT" } func request(method: HttpMethod, url: String, parameters: [String: Any]? = nil, headers: [String: String]? = nil, onSuccess: @escaping (_ data: Data) -> Void, onFailure: @escaping (_ error: ErrorResponse) -> Void, onCompleted: @escaping ()-> Void) { let encodeUrl = url.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) let request = NSMutableURLRequest(url: URL(string: encodeUrl!)!) request.httpMethod = method.rawValue request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") request.addValue(Environment.sharedInstance().parseApplicationId, forHTTPHeaderField: "X-Parse-Application-Id") request.addValue(Environment.sharedInstance().parseRestApiKey, forHTTPHeaderField: "X-Parse-REST-API-Key") if let headers = headers{ for header in headers { request.addValue(header.value, forHTTPHeaderField: header.key) } } if let parameters = parameters { do { request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) } catch { let errorResponse = ErrorResponse(code: "", error: "Unexpected error") onFailure(errorResponse) onCompleted() } } let session = URLSession.shared let task = session.dataTask(with: request as URLRequest) { data, response, error in guard (error == nil) else { let errorResponse = ErrorResponse(code: "", error: error.debugDescription) onFailure(errorResponse) return } guard let statusCode = (response as? HTTPURLResponse)?.statusCode, statusCode >= 200 && statusCode <= 299 else { if let data = data { let newData = data.subdata(in: Range(uncheckedBounds: (5, data.count))) let parsedResult = JSON.deserialize(data: newData) as? [String:AnyObject] let errorResponse = ErrorResponse(dictionary: parsedResult!) onFailure(errorResponse) } else { let errorResponse = ErrorResponse(code: "", error: "Unexpected error") onFailure(errorResponse) } return } if let data = data { onSuccess(data) } onCompleted() } task.resume() } }
mit
df447274298e4e906f068971781e2940
34.778947
124
0.549279
5.491115
false
false
false
false
sharkspeed/dororis
languages/swift/guide/14-initialization.swift
1
30913
// 14. Initialzation // - setting an initial value for each stored property on that instance // - performing any other setup or initialization // define initializers --- like a special methods be called to create a new instance // initializers do not RETURN a value // a deinitializer, which performs any custom cleanup just before an instance of that class is deallocated // 14.1 Setting Initial Values for Stored Properties // Classes and structures must set all of their stored properties // 可以在 initializer 中设置 stored property 值或者在 定义时就赋值 // 14.1.1 Initializers // init() { // } struct Fahrenheit { var temperature: Double init() { temperature = 32.0 // 32.0 (the freezing point of water in degrees Fahrenheit) } } var f = Fahrenheit() print("The default temperature is \(f.temperature) Fahrenheit") // 14.1.2 Default Property Values // If a property always takes the same initial value, provide a default value rather than setting a value within an initializer. 如果初始值不怎么变化 应该在定义时设置默认值 而不是通过 initializers struct FahrenheitBetter { var temperature = 32.0 } // 14.2 Customizing Initialization // 14.2.1 Initialization Parameters // 可以提供初始化参数给 initialization struct Celsius { var temperatureInCelsius: Double init(fromFahrenheit fahrenheit: Double) { temperatureInCelsius = (fahrenheit - 32.0) / 1.8 } init(fromKelvin kelvin: Double) { temperatureInCelsius = kelvin - 273.15 } } let boilingPointOfWater = Celsius(fromFahrenheit: 212.0) print("boilingPointOfWater is \(boilingPointOfWater.temperatureInCelsius)") let freezingPointOfWater = Celsius(fromKelvin: 273.15) print("freezingPointOfWater is \(freezingPointOfWater.temperatureInCelsius)") // 14.2.2 Parameter Names and Argument Labels // parameter name for use within the initializer’s body and an argument label for use when calling the initializer // init 函数不像一般的函数和方法那样有个函数名可以调用 因此 初始化函数的参数名和类型用来识别调用哪个初始化函数 struct Color { let red, green, blue: Double init(red: Double, green: Double, blue: Double) { self.red = red self.green = green self.blue = blue } // init(_ white: Double) { init(white: Double) { red = white green = white blue = white } } let magenta = Color(red: 1.0, green: 0.0, blue: 1.0) let haltGray = Color(white: 0.5) // let newGray = Color(0.4) // 必须要提供 参数标签 // 14.2.3 Initializer Parameters Without Argument Labels struct ColorNoLabels { let red, green, blue: Double init(red: Double, green: Double, blue: Double) { self.red = red self.green = green self.blue = blue } // init(_ white: Double) { init(_ white: Double) { red = white green = white blue = white } } // 用 underscore 可以省略标签直接调用初始化函数 // 14.2.4 Optional Property Types // stored property 可以有 no value var response: String? 一般无法在初始化时设置值或者允许没有值 class SurveryQuestion { var text: String var response: String? init(text: String) { self.text = text } func ask() { print(text) } func answer() { if response == nil { print("no ask and no answers") } else { print("\(response!)") } } } // \(convertedNumber!) let cheeseQuestion = SurveryQuestion(text: "Do you like cheese???") cheeseQuestion.answer() cheeseQuestion.ask() cheeseQuestion.response = "No ..." cheeseQuestion.answer() // 14.2.5 Assigning Constant Properties During Initialization class SurveryQuestionWithConstant: SurveryQuestion { let constantText: String init (constantText: String, text: String) { self.constantText = constantText super.init(text: text) } func constantAsk() { print(constantText) } override func ask() { print("new \(constantText)") } } let surveryQuestionWithConstant = SurveryQuestionWithConstant(constantText: "ConstantValue", text: "HHH") print("constant value is \(surveryQuestionWithConstant.constantText)") surveryQuestionWithConstant.constantAsk() surveryQuestionWithConstant.ask() // let surveryQuestionWithConstantNew = SurveryQuestionWithConstant(text: "HHH") // 14.3 Default Initializers // Swift 为 structure 和 class 提供了默认初始化函数 只需要满足以下条件 // 1. 所有属性都已经初始化 2. 未提供 init 函数 class ShoppingListItem { var name: String? var quantity = 1 var purchased = false func isPurchased() -> String { if purchased { return "Yes" } else { return "not purchased" } } } var item = ShoppingListItem() // var testItem = ShoppingListItem(name: "New", quantity: 3, purchased: true) item.purchased = true print("Purchased?\n\(item.isPurchased())") // 14.3.1 Memberwise Initializers for Structure Types 深拷贝 // Structure 类型 自动接收一个 memberwise initializer 可以通过 变量名 初始化 struct Size { var width: Double = 0.0, height = 0.0 // 如果 width 不定义 下边的 Rect 就无法用 zero-initialized 方式 } let twoByTwo = Size(width: 3.5, height: 4.5) print(twoByTwo.width) // 14.4 Initializer Delegation for Value Types // initializer delegation: call other initializer to perform part of an instance's initialization 避免代码重复 // 1. value types : structures enumerations 没有继承 因此只能委托自己内部的其他初始化方法 // 用 self.init() 可以调用其他初始化函数 只能在 init() 内部用 // 如果定义自己的 初始化函数 那么就无法使用 自动初始化函数。如果想用自动初始化函数又要自定义函数,应该使用 extensions struct Point { var x = 0.0, y = 0.0 } struct Rect { var origin = Point() var size = Size() init() {} // default zero-initialized init(origin: Point, size: Size) { // a specific origin point and size self.origin = origin self.size = size } init(center: Point, size: Size) { // a specific center point and size let originX = center.x - (size.width / 2) let originY = center.y - (size.height / 2) self.init(origin: Point(x: originX, y: originY), size: size) // delegation } } let basicRect = Rect() let originRect = Rect(origin: Point(x: 2.0, y: 2.0), size: Size(width: 5.0, height: 5.0)) let centerRect = Rect(center: Point(x: 4.0, y: 4.0), size: Size(width: 3.0, height: 3.0)) // 另外一个选择是用 extension // 2. class types : class // 14.5 Class Inheritance and Initialization // 原则: 类中全部的 stored properities 在初始化后都要被赋值 // 14.5.1 Designated Initializers and Convenience Initializers // 指派初始化函数 初始化自己全部 属性 , 调用父类初始化函数 初始化父类链上的属性 // 一般有一个指派初始化函数 有时可以通过继承一个或多个 Designated initializers 实现 // Convenience initializers 调用一个 designated 初始化函数 其中一些参数有默认值 // 可以用这种函数在一些情况下创建 实例 // 不一定要提供这种初始化函数 但有时可以节省时间 使代码清晰 // 14.5.1 Syntax for Designated and Convenience Initializers // init(parameters) { // statements // } // convenience init(parameters) { // statements // } // Rule 1 // A designated initializer must call a designated initializer from its immediate superclass. // Rule 2 // A convenience initializer must call another initializer from the same class. // Rule 3 // A convenience initializer must ultimately call a designated initializer. // A simple way to remember this is: // Designated initializers must always delegate up. 向上追溯 // Convenience initializers must always delegate across. 必须调用同类中的 designated initializers // 14.5.2 Two-Phase Initialization // each stored property is assigned an initial value by the class that introduced it // each class is given the opportunity to customize its stored properties further before the new instance is considered ready for use // prevents property values from being accessed before they are initialized // prevents property values from being set to a different value by another initializer unexpectedly // Safety check 1 // A designated initializer must ensure that all of the properties introduced by its class are initialized before it delegates up to a superclass initializer. // Safety check 2 // A designated initializer must delegate up to a superclass initializer before assigning a value to an inherited property. If it doesn’t, the new value the designated initializer assigns will be overwritten by the superclass as part of its own initialization. // Safety check 3 // A convenience initializer must delegate to another initializer before assigning a value to any property (including properties defined by the same class). If it doesn’t, the new value the convenience initializer assigns will be overwritten by its own class’s designated initializer // Safety check 4 // An initializer cannot call any instance methods, read the values of any instance properties, or refer to self as a value until after the first phase of initialization is complete. // 14.5.3 Initializer Inheritance and Overriding // Swift 的子类默认不继承父类初始化函数 (Superclass initializers are inherited in certain circumstances) // 子类 override 父类方法要在方法前加 override 在用 convenience initializer 复写 designated initializer 时也要加。 但是复写父类的 convenience initializer 不用加 因为子类无法调用父类的该方法。 class Vehicle { var numberOfWheels = 0 var description: String { return "\(numberOfWheels)" } } // automatically receives a default initializer let vehicle = Vehicle() print("Vehicle: \(vehicle.description)") // a subclass of Vehicle called Bicycle class Bicycle: Vehicle { override init() { super.init() numberOfWheels = 2 } } let bicycle = Bicycle() print("Bicycle: \(bicycle.description)") // 子类可以修改继承的变量值, 无法修改常量的值。 // 14.5.4 Automatic Initializer Inheritance // 在满足一些条件下 子类可以自动继承父类的初始化函数 // Rule 1 子类不定义任何指派初始化函数 自动继承全部的父类指派函数 // Rule 2 子类实现了全部的父类指派函数(继承或自己实现),自动继承父类的 convenience initializers // 14.5.4 Designated and Convenience Initializers in Action // Food RecipeIngredient ShoppingListItem class Food { var name: String init(name: String) { self.name = name } convenience init() { self.init(name: "[Unnamed]") } } let namedMeat = Food(name: "Bacon") print(namedMeat.name) let unnamedMeat = Food() print(unnamedMeat.name) class RecipeIngredient: Food { var quantity: Int init(name: String, quantity: Int) { self.quantity = quantity super.init(name: name) } override convenience init(name: String) { // 重写父类的指派初始化函数为convenience 函数 还需要加 override self.init(name: name, quantity: 1) } // 由于实现了父类的指派初始化函数 因此继承了父类的 convenience 初始化函数 } let oneMysteryItem = RecipeIngredient() let oneBacon = RecipeIngredient(name: "Bacon") let sixEggs = RecipeIngredient(name: "Eggs", quantity: 6) class ShoppingListItem1: RecipeIngredient { var purchased = false var description: String { var output = "\(quantity) x \(name)" output += purchased ? " √" : " x" return output } } // 同时符合两个规则 继承全部的父类初始化方法 // automatically inherits all of the designated and convenience initializers from its superclass var breakfastList = [ ShoppingListItem1(), ShoppingListItem1(name: "Bacon"), ShoppingListItem1(name: "Eggs", quantity: 6), ] breakfastList[0].name = "Orange juice" breakfastList[0].purchased = true for item in breakfastList { print(item.description) } // ingredient 因素; (混合物的) 组成部分; (烹调的) 原料; (构成) 要素; // 14.6 Failable Initializers // 有时候要处理初始化失败的情况 // 初始化参数无效 外部资源缺失 其他阻止初始化成功的条件 // init?() { // } 定义可能失败的初始化方法 // 不能定义签名相同的初始化方法 // Strictly speaking, initializers do not return a value 严格来说 init?() 不返回值 init?() 返回 nil 仅仅为了触发 failure // failable initializers are implemented for numeric type conversions /* let wholeNumber : Double = 12.0 let pi = 3.14 // To ensure conversion between numeric types maintains the value exactly, use the init(exactly:) initializer. if let valueMaintained = Int(exactly: wholeNumber) { print("\(wholeNumber) conversion to Int maintains value") } let valueChanged = Int(exactly: pi) if valueChanged == nil { print("\(pi) conversion to Int does not maintain value") } */ struct Animal { let species: String init?(species: String) { if species.isEmpty { return nil } self.species = species } } // let someCreature = Animal(species: "Giraffe") let someCreature = Animal(species: "") // someCreature is of type Animal?, not Animal if let giraffe = someCreature { print("An animal was initialized with a species of \(giraffe.species)") } // Prints "An animal was initialized with a species of Giraffe" // 14.6.1 Failable Initializers for Enumerations enum TemperatureUnit { case kelvin, celsius, fahrenheit init?(symbol: Character) { switch symbol { case "K": self = .kelvin case "C": self = .celsius case "F": self = .fahrenheit default: return nil } } } let fahrenheitUnit = TemperatureUnit(symbol: "F") if fahrenheitUnit != nil { print("This is a defined temperature unit, initialization succeeded.") } let unknownUnit = TemperatureUnit(symbol: "X") if unknownUnit == nil { print("This is not a defined temperature unit.") } // 14.6.2 Failable Initializers for Enumerations with Raw Values // Enumerations with raw values automatically receive a failable initializer, init?(rawValue:) enum TemperatureUnitRaw: Character { case kelvin = "K", celsius = "C", fahrenheit = "F" } let fRawUnit = TemperatureUnitRaw(rawValue: "F") let unRawUnit = TemperatureUnitRaw(rawValue: "x") // 14.6.3 Propagation of Initialization Failure // 一个可失败的初始化函数可以委托同一个 class structure enumeration 的可失败初始化函数 // 子类的可失败初始化函数可以委托父类的可失败初始化函数 // 一旦有一个导致失败,其他的初始化函数就不执行。 class ProductFail { let name: String init?(name: String) { if name.isEmpty { return nil } self.name = name } } class CartItemFail: ProductFail { let quantity : Int init?(name: String, quantity: Int) { if quantity < 1 { return nil } self.quantity = quantity super.init(name: name) // 调用不用带 ? 号 } } let twoSocks = CartItemFail(name: "sock", quantity: 2) let zeroShirts = CartItemFail(name: "shirt", quantity: 0) let oneUnnamed = CartItemFail(name: "", quantity: 1) // 14.6.4 Overriding a Failable Initializer // 子类可以 override 父类的可失败初始化函数 还可以用 不失败初始化函数 override 可失败初始化函数 // 后者情况下 必须 force-wrap 可失败函数的结果 class Document { var name: String? init() {} init?(name:String) { if name.isEmpty { return nil } self.name = name } } class AutoNamedDocument : Document { override init() { super.init() self.name = "[Untitled]" } override init(name: String) { super.init() // => init() {} if name.isEmpty { self.name = "[Untitled]" } else { self.name = name } } } class UntitledDocument: Document { override init() { super.init(name: "[Untitled]")! } } // 14.6.5 The init! Failable Initializer // implicitly unwrapped optional instance // 14.7 Required Initializers // every subclass of the class must implement that initializer class RequiredInit { required init() { } } // also write the required modifier before every subclass implementation of a required initializer, to indicate that the initializer requirement applies to further subclasses in the chain. class SubRequiredInit : RequiredInit { required init() { } } // 14.8 Setting a Default Property Value with a Closure or Function // 可以用 closure 或 函数 对 stored property 设置 default value /* class SomeClass { let someProperty: SomeType = { // create a default value for someProperty inside this closure // someValue must be of the same type as SomeType return someValue }() } */ struct Chessboard { let boardColors: [Bool] = { var temporaryBoard = [Bool]() var isBlack = false for i in 1...8 { for j in 1...8 { temporaryBoard.append(isBlack) } isBlack = !isBlack } return temporaryBoard }() func squareIsBlackAt(row: Int, column: Int) -> Bool { return boardColors[(row * 8) + column] } } let board = Chessboard() print(board.squareIsBlackAt(row: 0, column: 1)) print(board.squareIsBlackAt(row: 7, column: 7)) // 15. Deinitialization // A deinitializer is called immediately before a class instance is deallocated. // only available in class Types. // 15.1 How Deinitialization Works // 为了 perform some additional cleanup yourself. // 关闭打开的文件 // 子类不提供析构函数的话回继承父类的 // 15.2 Deinitializers in Action class Bank { static var coinsInBank = 10_000 static func distribute(coins numberOfCoinsRequested: Int) -> Int { let numberOfCoinsToVend = min(numberOfCoinsRequested, coinsInBank) coinsInBank -= numberOfCoinsToVend return numberOfCoinsToVend } static func receive(coins: Int) { coinsInBank += coins } } class Player { var coinsInPurse: Int init(coins: Int) { coinsInPurse = Bank.distribute(coins: coins) } func win(coins: Int) { coinsInPurse += Bank.distribute(coins: coins) } deinit { Bank.receive(coins: coinsInPurse) } } var playerOne: Player? = Player(coins: 100) print("A new gamer \(playerOne!.coinsInPurse)") print("There are now \(Bank.coinsInBank)") playerOne!.win(coins: 2_000) print("PlayerOne won 2000 coins") print("The bank now only has \(Bank.coinsInBank)") playerOne = nil print("PlayerOne has left the game") print("The bank now has \(Bank.coinsInBank)") // 16. Automatic Reference Counting // 16.1 How ARC Works // Every time you create a new instance of a class, ARC allocates a chunk of memory to store information about that instance. // 16.2 ARC in Action class Person { let name: String init(name: String) { self.name = name print("\(name) is being initialized") } deinit { print("\(name) is being deinitialized") } } var ref1: Person? var ref2: Person? var ref3: Person? ref1 = Person(name: "John") ref2 = ref1 ref3 = ref1 ref1 = nil ref2 = nil // 解除两个 strong reference ref3 = nil // 16.3 Strong Reference Cycles Between Class Instances class PersonS { let name: String init(name:String){self.name = name} var apartment: ApartmentS? deinit {print("\(name) is being deinitialized")} } class ApartmentS { let unit: String init(unit: String) { self.unit = unit } var tenant: PersonS? deinit { print("Apartment \(unit) is being deinitialized")} } var johnS: PersonS? var unit4A: ApartmentS? // Optional (nil or ApartmentS) johnS = PersonS(name: "John") unit4A = ApartmentS(unit: "4A") johnS!.apartment = unit4A unit4A!.tenant = johnS // an exclamation mark (!) is used to unwrap and access the instances stored inside johnS = nil unit4A = nil // 16.4 Resolving Strong Reference Cycles Between Class Instances // Use a weak reference when the other instance has a shorter lifetime—that is, when the other instance can be deallocated first // use an unowned reference when the other instance has the same lifetime or a longer lifetime. // 16.4.1 Weak References class PersonW { let name: String init(name: String) { self.name = name } var apartment: ApartmentW? deinit { print("\(name) is being deinitialized") } } class ApartmentW { let unit: String init(unit: String) { self.unit = unit } weak var tenant: PersonW? deinit { print("Apartment \(unit) is being deinitialized") } } // ARC 将一个 weak reference 设为 nil 不触发 Property observers // ARC unsuitable for a simple caching mechanism // 16.4.2 Unowned References // An unowned reference is expected to always have a value. As a result, ARC never sets an unowned reference’s value to nil, which means that unowned references are defined using nonoptional types. // 仅仅当你确定引用总是指向没有被 deallocated 的实例 // In this data model, a customer may or may not have a credit card, but a credit card will always be associated with a customer // To represent this, the Customer class has an optional card property, but the CreditCard class has an unowned (and nonoptional) customer property. // 信用卡必须通过数字编号 和 顾客实例初始化 class CustomerU { let name: String var card: CreditCardU? init(name: String) { self.name = name } deinit {print("\(name) is being deinitialized")} } class CreditCardU { let number: UInt64 // ensure that the number property’s capacity is large enough to store a 16-digit card number on both 32-bit and 64-bit systems. unowned let customer: CustomerU init(number: UInt64, customer: CustomerU) { self.number = number self.customer = customer } deinit {print("Card #\(number) is being deinitialized")} } var rabbit: CustomerU? rabbit = CustomerU(name: "rabbit") rabbit!.card = CreditCardU(number:1234_1234_1234_1234, customer: rabbit!) rabbit = nil // 16.4.3 Unowned References and Implicitly Unwrapped Optional Properties // there is a third scenario, in which both properties should always have a value, and neither property should ever be nil once initialization is complete. In this scenario, it’s useful to combine an unowned property on one class with an implicitly unwrapped optional property on the other class. // This enables both properties to be accessed directly (without optional unwrapping) once initialization is complete class CountryUR { let name: String var capitalCity: CityUR! // This means that the capitalCity property has a default value of nil, like any other optional, but can be accessed without the need to unwrap its value init (name:String, capitalName: String) { self.name = name self.capitalCity = CityUR(name: capitalName, country: self) } } class CityUR { let name: String unowned let country: CountryUR init(name: String, country: CountryUR) { self.name = name self.country = country } } var country = CountryUR(name: "Canada", capitalName: "Ottawa") print("\(country.name)'s capital city is called \(country.capitalCity.name)") // 16.5 Strong Reference Cycles for Closures // closures, like classes, are reference types. // Swift provides an elegant solution to this problem, known as a closure capture list class HTMLElement { let name: String let text: String? lazy var asHTML: () -> String = { if let text = self.text { return "<\(self.name)>\(text)</\(self.name)>" } else { return "<\(self.name) />" } } // 导致对 HTMLElement 的强引用 self.text self.name 是一次引用 init(name: String, text: String? = nil) { self.name = name self.text = text } deinit { print("\(name) is being deinitialized") } } // 16.6 Resolving Strong Reference Cycles for Closures // Swift requires you to write self.someProperty or self.someMethod() (rather than just someProperty or someMethod()) 这可以让你记得闭包可能捕获 self // 16.6.1 Defining a Capture List // lazy var someClosure: (Int, String) -> String = { // [unowned self, weak delegate = self.delegate!] (index: Int, stringToProcess: String) -> String in // // closure body goes here // } // 当然 如果闭包可以从函数体推断出类型 可以写做 // lazy var someClosure: () -> String = { // [unowned self, weak delegate = self.delegate!] in // // closure body goes here // } // 16.6.2 Weak and Unowned References // 什么标记为 weak 什么标记为 unowned // unowned : the closure and the instance it captures will always refer to each other, and will always be deallocated at the same time // weak : the captured reference may become nil at some point in the future // If the captured reference will never become nil, it should always be captured as an unowned reference, rather than a weak reference. class HTMLElementSolved { let name: String let text: String? lazy var asHTML: () -> String = { [unowned self] in if let text = self.text { return "<\(self.name)>\(text)</\(self.name)>" } else { return "<\(self.name) />" } } init(name: String, text: String? = nil) { self.name = name self.text = text } deinit { print("\(name) is being deinitialized") } } var paragraph: HTMLElementSolved? = HTMLElementSolved(name: "p", text: "This is Swift") print(paragraph!.asHTML()) paragraph = nil // deallocated // 17. Optional Chaining // Optional Chaining 是对可能为 nil 的 optional 对象进行属性或方法的搜索调用(subscripts)的流程。如果包含值,property method subscript 都可以成功获取,如果为 nil 那么都返回 nil。多层搜索调用可以相互串联,一个出现nil整个链都是 nil // 17.1 Optional Chaining as an Alternative to Forced Unwrapping // optional value 后边的 question mark 表明这是 optional 类型 可能为 nil ; optional value 后边加 exclamation mark 表示强制解包获取值。区别在于当在 optional chaining 上时 ? 导致返回 nil ; ! 导致 runtime error // optional chaining 的返回值也是 optional type 即使返回一个非 optional type. 可用于检查 optional chaining 调用情况 // 预期返回 Int 的 现在返回 Int? class Person17 { var residence: Residence17? } class Residence17 { var numberOfRooms = 1 } let john17 = Person17() // let roomCount = john17.residence!.numberOfRooms john17.residence = Residence17() if let roomCount = john17.residence?.numberOfRooms { print("Residence has \(roomCount) room(s).") } else { print("Unable to retrieve the number of rooms.") } // 17.2 Defining Model Classes for Optional Chaining class PersonRed { var residence: ResidenceRed? } class ResidenceRed { var rooms = [RoomRed] var numberOfRooms: Int { return rooms.count } subscript(i: Int) -> RoomRed { get { return rooms[i] } set { room[i] = newValue } } func printNumberOfRooms() { print("The number of rooms is \(numberOfRooms)") } var address: AddressRed? } class RoomRed { let name: String init(name: String) { self.name = name} } class AddressRed { var buildingNumber: Strings var buildingName: Strings var street: String? func buildingIndentifier() -> String? { if let buildingNumber = buildingNumber, let street = street { return "\(buildingNumber) \(street)" } else if buildingName != nil { return buildngName } else { return nil } } } // 17.3 Accessing Properties Through Optional Chaining let someAddress = Address() someAddress.buildingNumber = "29" someAddress.street = "Acacia Road" john.residence?.address = someAddress // The assignment is part of the optional chaining, which means none of the code on the right hand side of the = operator is evaluated. // 17.4 Calling Methods Through Optional Chaining // use optional chaining to call a method on an optional value.即使这个方法没有返回值也可以,因为没有返回值的函数默认返回 Void 就是返回 () 或者叫 空元组 // 在 optional 值上调用没有返回值的函数会返回 Void? 这可以用来检查是否可以在值上调用方法 if (john.residence?.address = someAddress) != nil { print("It was possible to set the address.") } else { print("It was not possible to set the address.") } // 17.6 Accessing Subscripts Through Optional Chaining // You can use optional chaining to try to retrieve and set a value from a subscript on an optional value, and to check whether that subscript call is successful. if let firstRoomName = john.residence?[0].name { print("The first room name is \(firstRoomName).") } else { print("Unable to retrieve the first room name.") } // 17.7 Accessing Subscripts of Optional Type var testScores = ["Dave": [86, 82, 84], "Bev": [79, 94, 81]] testScores["Dave"]?[0] = 91 testScores["Bev"]?[0] += 1 testScores["Brian"]?[0] = 72 // 17.8 Linking Multiple Levels of Chaining // 1. 非 optional 值只要在 optional 调用链上就会返回 optional // 2. 已经是 optional 的值 一直会返回 optional // 17.9 Chaining on Methods with Optional Return Values // 通过optional链可以获取属性也可以调用函数 返回一个 optional type 还可以继续在这个返回值上继续链式调用 if let beginsWithThe = john.residence?.address?.buildingIdentifier()?.hasPrefix("The") { if beginsWithThe { print("John's building identifier begins with \"The\".") } else { print("John's building identifier does not begin with \"The\".") } } // Prints "John's building identifier begins with "The"." // 上例加 ? 是因为在返回值上调用而不是在函数自身调用。
bsd-2-clause
6b6cfa4777c4f5410ea37bb075ec4e65
25.763083
296
0.685213
3.845113
false
false
false
false
material-motion/motion-interchange-objc
tests/unit/MDMSpringTimingCurve.swift
2
3240
/* Copyright 2017-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 XCTest import MotionInterchange class MDMTimingCurveTests: XCTestCase { func testInitializerValuesWithNoInitialVelocity() { let curve = MDMSpringTimingCurve(mass: 0.1, tension: 0.2, friction: 0.3) XCTAssertEqual(curve.mass, 0.1, accuracy: 0.001) XCTAssertEqual(curve.tension, 0.2, accuracy: 0.001) XCTAssertEqual(curve.friction, 0.3, accuracy: 0.001) XCTAssertEqual(curve.initialVelocity, 0.0, accuracy: 0.001) } func testInitializerValuesWithInitialVelocity() { let curve = MDMSpringTimingCurve(mass: 0.1, tension: 0.2, friction: 0.3, initialVelocity: 0.4) XCTAssertEqual(curve.mass, 0.1, accuracy: 0.001) XCTAssertEqual(curve.tension, 0.2, accuracy: 0.001) XCTAssertEqual(curve.friction, 0.3, accuracy: 0.001) XCTAssertEqual(curve.initialVelocity, 0.4, accuracy: 0.001) } @available(iOS 9.0, *) func testInitializerValuesWithDampingCoefficient() { for duration in stride(from: TimeInterval(0.1), to: TimeInterval(3), by: TimeInterval(0.5)) { for dampingRatio in stride(from: CGFloat(0.1), to: CGFloat(2), by: CGFloat(0.4)) { for initialVel in stride(from: CGFloat(-2), to: CGFloat(2), by: CGFloat(0.8)) { let generator = MDMSpringTimingCurveGenerator(duration: duration, dampingRatio: dampingRatio, initialVelocity: initialVel) let view = UIView() UIView.animate(withDuration: duration, delay: 0, usingSpringWithDamping: dampingRatio, initialSpringVelocity: initialVel, options: [], animations: { view.center = CGPoint(x: initialVel * 5, y: dampingRatio * 10) }, completion: nil) if let animationKey = view.layer.animationKeys()?.first, let animation = view.layer.animation(forKey: animationKey) as? CASpringAnimation { let curve = generator.springTimingCurve() XCTAssertEqual(curve.mass, animation.mass, accuracy: 0.001) XCTAssertEqual(curve.tension, animation.stiffness, accuracy: 0.001) XCTAssertEqual(curve.friction, animation.damping, accuracy: 0.001) if animation.responds(to: #selector(initialVelocity)) { XCTAssertEqual(curve.initialVelocity, animation.initialVelocity, accuracy: 0.001) } } } } } } // Dummy getter for #selector(initialVelocity) reference. func initialVelocity() { } }
apache-2.0
3fa631d13c7ec3deeaef55da0e003c77
41.631579
98
0.651543
4.456671
false
true
false
false
RemyDCF/tpg-offline
tpg offline/Disruptions/DisruptionTableViewCell.swift
1
5428
// // DisruptionTableViewCell.swift // tpgoffline // // Created by Rémy Da Costa Faro on 18/06/2017. // Copyright © 2018 Rémy Da Costa Faro DA COSTA FARO. All rights reserved. // import UIKit class DisruptionTableViewCell: UITableViewCell { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var descriptionLabel: UILabel! @IBOutlet weak var linesCollectionView: UICollectionView! @IBOutlet weak var collectionViewHeight: NSLayoutConstraint! var color: UIColor = .white var loading = true var timer: Timer? var opacity = 0.5 var disruption: Disruption? = nil { didSet { guard let disruption = disruption else { self.backgroundColor = App.cellBackgroundColor self.linesCollectionView.backgroundColor = App.cellBackgroundColor titleLabel.backgroundColor = .gray descriptionLabel.backgroundColor = .gray titleLabel.text = " " descriptionLabel.text = "\n\n\n" titleLabel.cornerRadius = 10 descriptionLabel.cornerRadius = 10 titleLabel.clipsToBounds = true descriptionLabel.clipsToBounds = true timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(self.changeOpacity), userInfo: nil, repeats: true) return } self.color = LineColorManager.color(for: disruption.line) self.linesCollectionView.backgroundColor = App.cellBackgroundColor titleLabel.alpha = 1 descriptionLabel.alpha = 1 titleLabel.backgroundColor = App.cellBackgroundColor descriptionLabel.backgroundColor = App.cellBackgroundColor titleLabel.textColor = App.textColor descriptionLabel.textColor = App.textColor titleLabel.cornerRadius = 0 descriptionLabel.cornerRadius = 0 titleLabel.text = disruption.nature .replacingOccurrences(of: " ", with: " ") .replacingOccurrences(of: "' ", with: "'") if disruption.place != "" { let disruptionPlace = disruption.place .replacingOccurrences(of: " ", with: " ") .replacingOccurrences(of: "' ", with: "'") titleLabel.text = titleLabel.text?.appending(" - \(disruptionPlace)") } self.backgroundColor = App.cellBackgroundColor descriptionLabel.text = disruption.consequence .replacingOccurrences(of: " ", with: " ") .replacingOccurrences(of: "' ", with: "'") self.loading = false } } override func awakeFromNib() { super.awakeFromNib() self.backgroundColor = App.cellBackgroundColor self.linesCollectionView.backgroundColor = App.cellBackgroundColor lines = [] titleLabel.backgroundColor = .gray descriptionLabel.backgroundColor = .gray titleLabel.text = " " descriptionLabel.text = "\n\n\n" titleLabel.cornerRadius = 10 descriptionLabel.cornerRadius = 10 titleLabel.clipsToBounds = true descriptionLabel.clipsToBounds = true timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(self.changeOpacity), userInfo: nil, repeats: true) _ = linesCollectionView.observe(\.contentSize) { (_, _) in self.collectionViewHeight.constant = self.linesCollectionView.contentSize.height } self.linesCollectionView.reloadData() } deinit { linesCollectionView.removeObserver(self, forKeyPath: "contentSize") } @objc func changeOpacity() { if loading == false { timer?.invalidate() titleLabel.alpha = 1 descriptionLabel.alpha = 1 } else { self.opacity += 0.010 if self.opacity >= 0.2 { self.opacity = 0.1 } var opacity = CGFloat(self.opacity) if opacity > 0.5 { opacity -= (0.5 - opacity) } titleLabel.alpha = opacity descriptionLabel.alpha = opacity } } var lines: [String] = [] { didSet { self.linesCollectionView.reloadData() } } } extension DisruptionTableViewCell: UICollectionViewDelegate, UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return lines.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { guard let cell = linesCollectionView .dequeueReusableCell(withReuseIdentifier: "disruptionLineCollectionViewCell", for: indexPath) as? DisruptionLineCollectionViewCell else { return UICollectionViewCell() } cell.label.text = lines[indexPath.row] let color = lines[indexPath.row] == "tpg" ? #colorLiteral(red: 1, green: 0.3411764706, blue: 0.1333333333, alpha: 1) : LineColorManager.color(for: lines[indexPath.row]) cell.backgroundColor = App.darkMode ? UIColor.black.lighten(by: 0.1) : color cell.label.textColor = App.darkMode ? color : color.contrast cell.clipsToBounds = true cell.cornerRadius = cell.bounds.height / 2 return cell } } class DisruptionLineCollectionViewCell: UICollectionViewCell { @IBOutlet weak var label: UILabel! }
mit
21242fe635c4324fdb5493134c4b19ed
33.775641
130
0.641843
5.03714
false
false
false
false
tdscientist/ShelfView-iOS
Example/Pods/Kingfisher/Sources/Cache/ImageCache.swift
1
35602
// // ImageCache.swift // Kingfisher // // Created by Wei Wang on 15/4/6. // // Copyright (c) 2018 Wei Wang <[email protected]> // // 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. #if os(macOS) import AppKit #else import UIKit #endif extension Notification.Name { /// This notification will be sent when the disk cache got cleaned either there are cached files expired or the /// total size exceeding the max allowed size. The manually invoking of `clearDiskCache` method will not trigger /// this notification. /// /// The `object` of this notification is the `ImageCache` object which sends the notification. /// A list of removed hashes (files) could be retrieved by accessing the array under /// `KingfisherDiskCacheCleanedHashKey` key in `userInfo` of the notification object you received. /// By checking the array, you could know the hash codes of files are removed. public static let KingfisherDidCleanDiskCache = Notification.Name("com.onevcat.Kingfisher.KingfisherDidCleanDiskCache") } /// Key for array of cleaned hashes in `userInfo` of `KingfisherDidCleanDiskCacheNotification`. public let KingfisherDiskCacheCleanedHashKey = "com.onevcat.Kingfisher.cleanedHash" /// Cache type of a cached image. /// - none: The image is not cached yet when retrieving it. /// - memory: The image is cached in memory. /// - disk: The image is cached in disk. public enum CacheType { /// The image is not cached yet when retrieving it. case none /// The image is cached in memory. case memory /// The image is cached in disk. case disk /// Whether the cache type represents the image is already cached or not. public var cached: Bool { switch self { case .memory, .disk: return true case .none: return false } } } /// Represents the caching operation result. public struct CacheStoreResult { /// The cache result for memory cache. Caching an image to memory will never fail. public let memoryCacheResult: Result<(), Never> /// The cache result for disk cache. If an error happens during caching operation, /// you can get it from `.failure` case of this `diskCacheResult`. public let diskCacheResult: Result<(), KingfisherError> } extension Image: CacheCostCalculable { /// Cost of an image public var cacheCost: Int { return kf.cost } } extension Data: DataTransformable { public func toData() throws -> Data { return self } public static func fromData(_ data: Data) throws -> Data { return data } public static let empty = Data() } /// Represents the getting image operation from the cache. /// /// - disk: The image can be retrieved from disk cache. /// - memory: The image can be retrieved memory cache. /// - none: The image does not exist in the cache. public enum ImageCacheResult { /// The image can be retrieved from disk cache. case disk(Image) /// The image can be retrieved memory cache. case memory(Image) /// The image does not exist in the cache. case none /// Extracts the image from cache result. It returns the associated `Image` value for /// `.disk` and `.memory` case. For `.none` case, `nil` is returned. public var image: Image? { switch self { case .disk(let image): return image case .memory(let image): return image case .none: return nil } } /// Returns the corresponding `CacheType` value based on the result type of `self`. public var cacheType: CacheType { switch self { case .disk: return .disk case .memory: return .memory case .none: return .none } } } /// Represents a hybrid caching system which is composed by a `MemoryStorage.Backend` and a `DiskStorage.Backend`. /// `ImageCache` is a high level abstract for storing an image as well as its data to disk memory and disk, and /// retrieving them back. /// /// While a default image cache object will be used if you prefer the extension methods of Kingfisher, you can create /// your own cache object and configure its storages as your need. This class also provide an interface for you to set /// the memory and disk storage config. open class ImageCache { // MARK: Singleton /// The default `ImageCache` object. Kingfisher will use this cache for its related methods if there is no /// other cache specified. The `name` of this default cache is "default", and you should not use this name /// for any of your customize cache. public static let `default` = ImageCache(name: "default") // MARK: Public Properties /// The `MemoryStorage.Backend` object used in this cache. This storage holds loaded images in memory with a /// reasonable expire duration and a maximum memory usage. To modify the configuration of a storage, just set /// the storage `config` and its properties. public let memoryStorage: MemoryStorage.Backend<Image> /// The `DiskStorage.Backend` object used in this cache. This storage stores loaded images in disk with a /// reasonable expire duration and a maximum disk usage. To modify the configuration of a storage, just set /// the storage `config` and its properties. public let diskStorage: DiskStorage.Backend<Data> private let ioQueue: DispatchQueue /// Closure that defines the disk cache path from a given path and cacheName. public typealias DiskCachePathClosure = (URL, String) -> URL // MARK: Initializers /// Creates an `ImageCache` from a customized `MemoryStorage` and `DiskStorage`. /// /// - Parameters: /// - memoryStorage: The `MemoryStorage.Backend` object to use in the image cache. /// - diskStorage: The `DiskStorage.Backend` object to use in the image cache. public init( memoryStorage: MemoryStorage.Backend<Image>, diskStorage: DiskStorage.Backend<Data>) { self.memoryStorage = memoryStorage self.diskStorage = diskStorage let ioQueueName = "com.onevcat.Kingfisher.ImageCache.ioQueue.\(UUID().uuidString)" ioQueue = DispatchQueue(label: ioQueueName) #if !os(macOS) && !os(watchOS) #if swift(>=4.2) let notifications: [(Notification.Name, Selector)] = [ (UIApplication.didReceiveMemoryWarningNotification, #selector(clearMemoryCache)), (UIApplication.willTerminateNotification, #selector(cleanExpiredDiskCache)), (UIApplication.didEnterBackgroundNotification, #selector(backgroundCleanExpiredDiskCache)) ] #else let notifications: [(Notification.Name, Selector)] = [ (NSNotification.Name.UIApplicationDidReceiveMemoryWarning, #selector(clearMemoryCache)), (NSNotification.Name.UIApplicationWillTerminate, #selector(cleanExpiredDiskCache)), (NSNotification.Name.UIApplicationDidEnterBackground, #selector(backgroundCleanExpiredDiskCache)) ] #endif notifications.forEach { NotificationCenter.default.addObserver(self, selector: $0.1, name: $0.0, object: nil) } #endif } /// Creates an `ImageCache` with a given `name`. Both `MemoryStorage` and `DiskStorage` will be created /// with a default config based on the `name`. /// /// - Parameter name: The name of cache object. It is used to setup disk cache directories and IO queue. /// You should not use the same `name` for different caches, otherwise, the disk storage would /// be conflicting to each other. The `name` should not be an empty string. public convenience init(name: String) { try! self.init(name: name, path: nil, diskCachePathClosure: nil) } /// Creates an `ImageCache` with a given `name`, cache directory `path` /// and a closure to modify the cache directory. /// /// - Parameters: /// - name: The name of cache object. It is used to setup disk cache directories and IO queue. /// You should not use the same `name` for different caches, otherwise, the disk storage would /// be conflicting to each other. /// - path: Location of cache path on disk. It will be internally pass to the initializer of `DiskStorage` as the /// disk cache directory. /// - diskCachePathClosure: Closure that takes in an optional initial path string and generates /// the final disk cache path. You could use it to fully customize your cache path. /// - Throws: An error that happens during image cache creating, such as unable to create a directory at the given /// path. public convenience init( name: String, path: String?, diskCachePathClosure: DiskCachePathClosure? = nil) throws { if name.isEmpty { fatalError("[Kingfisher] You should specify a name for the cache. A cache with empty name is not permitted.") } let totalMemory = ProcessInfo.processInfo.physicalMemory let costLimit = totalMemory / 4 let memoryStorage = MemoryStorage.Backend<Image>(config: .init(totalCostLimit: (costLimit > Int.max) ? Int.max : Int(costLimit))) var diskConfig = DiskStorage.Config( name: name, sizeLimit: 0, directory: path.flatMap { URL(string: $0) } ) if let closure = diskCachePathClosure { diskConfig.cachePathBlock = closure } let diskStorage = try DiskStorage.Backend<Data>(config: diskConfig) diskConfig.cachePathBlock = nil self.init(memoryStorage: memoryStorage, diskStorage: diskStorage) } deinit { NotificationCenter.default.removeObserver(self) } // MARK: Storing Images open func store(_ image: Image, original: Data? = nil, forKey key: String, options: KingfisherParsedOptionsInfo, toDisk: Bool = true, completionHandler: ((CacheStoreResult) -> Void)? = nil) { let identifier = options.processor.identifier let callbackQueue = options.callbackQueue let computedKey = key.computedKey(with: identifier) // Memory storage should not throw. memoryStorage.storeNoThrow(value: image, forKey: computedKey, expiration: options.memoryCacheExpiration) guard toDisk else { if let completionHandler = completionHandler { let result = CacheStoreResult(memoryCacheResult: .success(()), diskCacheResult: .success(())) callbackQueue.execute { completionHandler(result) } } return } ioQueue.async { let serializer = options.cacheSerializer if let data = serializer.data(with: image, original: original) { self.syncStoreToDisk( data, forKey: key, processorIdentifier: identifier, callbackQueue: callbackQueue, expiration: options.diskCacheExpiration, completionHandler: completionHandler) } else { guard let completionHandler = completionHandler else { return } let diskError = KingfisherError.cacheError( reason: .cannotSerializeImage(image: image, original: original, serializer: serializer)) let result = CacheStoreResult( memoryCacheResult: .success(()), diskCacheResult: .failure(diskError)) callbackQueue.execute { completionHandler(result) } } } } /// Stores an image to the cache. /// /// - Parameters: /// - image: The image to be stored. /// - original: The original data of the image. This value will be forwarded to the provided `serializer` for /// further use. By default, Kingfisher uses a `DefaultCacheSerializer` to serialize the image to /// data for caching in disk, it checks the image format based on `original` data to determine in /// which image format should be used. For other types of `serializer`, it depends on their /// implementation detail on how to use this original data. /// - key: The key used for caching the image. /// - identifier: The identifier of processor being used for caching. If you are using a processor for the /// image, pass the identifier of processor to this parameter. /// - serializer: The `CacheSerializer` /// - toDisk: Whether this image should be cached to disk or not. If `false`, the image is only cached in memory. /// Otherwise, it is cached in both memory storage and disk storage. Default is `true`. /// - callbackQueue: The callback queue on which `completionHandler` is invoked. Default is `.untouch`. For case /// that `toDisk` is `false`, a `.untouch` queue means `callbackQueue` will be invoked from the /// caller queue of this method. If `toDisk` is `true`, the `completionHandler` will be called /// from an internal file IO queue. To change this behavior, specify another `CallbackQueue` /// value. /// - completionHandler: A closure which is invoked when the cache operation finishes. open func store(_ image: Image, original: Data? = nil, forKey key: String, processorIdentifier identifier: String = "", cacheSerializer serializer: CacheSerializer = DefaultCacheSerializer.default, toDisk: Bool = true, callbackQueue: CallbackQueue = .untouch, completionHandler: ((CacheStoreResult) -> Void)? = nil) { struct TempProcessor: ImageProcessor { let identifier: String func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> Image? { return nil } } let options = KingfisherParsedOptionsInfo([ .processor(TempProcessor(identifier: identifier)), .cacheSerializer(serializer), .callbackQueue(callbackQueue) ]) store(image, original: original, forKey: key, options: options, toDisk: toDisk, completionHandler: completionHandler) } open func storeToDisk( _ data: Data, forKey key: String, processorIdentifier identifier: String = "", expiration: StorageExpiration? = nil, callbackQueue: CallbackQueue = .untouch, completionHandler: ((CacheStoreResult) -> Void)? = nil) { ioQueue.async { self.syncStoreToDisk( data, forKey: key, processorIdentifier: identifier, callbackQueue: callbackQueue, expiration: expiration, completionHandler: completionHandler) } } private func syncStoreToDisk( _ data: Data, forKey key: String, processorIdentifier identifier: String = "", callbackQueue: CallbackQueue = .untouch, expiration: StorageExpiration? = nil, completionHandler: ((CacheStoreResult) -> Void)? = nil) { let computedKey = key.computedKey(with: identifier) let result: CacheStoreResult do { try self.diskStorage.store(value: data, forKey: computedKey, expiration: expiration) result = CacheStoreResult(memoryCacheResult: .success(()), diskCacheResult: .success(())) } catch { let diskError: KingfisherError if let error = error as? KingfisherError { diskError = error } else { diskError = .cacheError(reason: .cannotConvertToData(object: data, error: error)) } result = CacheStoreResult( memoryCacheResult: .success(()), diskCacheResult: .failure(diskError) ) } if let completionHandler = completionHandler { callbackQueue.execute { completionHandler(result) } } } // MARK: Removing Images /// Removes the image for the given key from the cache. /// /// - Parameters: /// - key: The key used for caching the image. /// - identifier: The identifier of processor being used for caching. If you are using a processor for the /// image, pass the identifier of processor to this parameter. /// - fromMemory: Whether this image should be removed from memory storage or not. /// If `false`, the image won't be removed from the memory storage. Default is `true`. /// - fromDisk: Whether this image should be removed from disk storage or not. /// If `false`, the image won't be removed from the disk storage. Default is `true`. /// - callbackQueue: The callback queue on which `completionHandler` is invoked. Default is `.untouch`. /// - completionHandler: A closure which is invoked when the cache removing operation finishes. open func removeImage(forKey key: String, processorIdentifier identifier: String = "", fromMemory: Bool = true, fromDisk: Bool = true, callbackQueue: CallbackQueue = .untouch, completionHandler: (() -> Void)? = nil) { let computedKey = key.computedKey(with: identifier) if fromMemory { try? memoryStorage.remove(forKey: computedKey) } if fromDisk { ioQueue.async{ try? self.diskStorage.remove(forKey: computedKey) if let completionHandler = completionHandler { callbackQueue.execute { completionHandler() } } } } else { if let completionHandler = completionHandler { callbackQueue.execute { completionHandler() } } } } func retrieveImage(forKey key: String, options: KingfisherParsedOptionsInfo, callbackQueue: CallbackQueue = .untouch, completionHandler: ((Result<ImageCacheResult, KingfisherError>) -> Void)?) { // No completion handler. No need to start working and early return. guard let completionHandler = completionHandler else { return } let imageModifier = options.imageModifier // Try to check the image from memory cache first. if let image = retrieveImageInMemoryCache(forKey: key, options: options) { let image = imageModifier.modify(image) callbackQueue.execute { completionHandler(.success(.memory(image))) } } else if options.fromMemoryCacheOrRefresh { callbackQueue.execute { completionHandler(.success(.none)) } } else { // Begin to disk search. self.retrieveImageInDiskCache(forKey: key, options: options, callbackQueue: callbackQueue) { result in // The callback queue is already correct in this closure. switch result { case .success(let image): guard let image = imageModifier.modify(image) else { // No image found in disk storage. completionHandler(.success(.none)) return } // Cache the disk image to memory. // We are passing `false` to `toDisk`, the memory cache does not change // callback queue, we can call `completionHandler` without another dispatch. var cacheOptions = options cacheOptions.callbackQueue = .untouch self.store( image, forKey: key, options: cacheOptions, toDisk: false) { _ in completionHandler(.success(.disk(image))) } case .failure(let error): completionHandler(.failure(error)) } } } } // MARK: Getting Images /// Gets an image for a given key from the cache, either from memory storage or disk storage. /// /// - Parameters: /// - key: The key used for caching the image. /// - options: The `KingfisherOptionsInfo` options setting used for retrieving the image. /// - callbackQueue: The callback queue on which `completionHandler` is invoked. Default is `.untouch`. /// - completionHandler: A closure which is invoked when the image getting operation finishes. If the /// image retrieving operation finishes without problem, an `ImageCacheResult` value /// will be sent to this closure as result. Otherwise, a `KingfisherError` result /// with detail failing reason will be sent. open func retrieveImage(forKey key: String, options: KingfisherOptionsInfo? = nil, callbackQueue: CallbackQueue = .untouch, completionHandler: ((Result<ImageCacheResult, KingfisherError>) -> Void)?) { retrieveImage( forKey: key, options: KingfisherParsedOptionsInfo(options), callbackQueue: callbackQueue, completionHandler: completionHandler) } func retrieveImageInMemoryCache( forKey key: String, options: KingfisherParsedOptionsInfo) -> Image? { let computedKey = key.computedKey(with: options.processor.identifier) do { return try memoryStorage.value(forKey: computedKey) } catch { return nil } } /// Gets an image for a given key from the memory storage. /// /// - Parameters: /// - key: The key used for caching the image. /// - options: The `KingfisherOptionsInfo` options setting used for retrieving the image. /// - Returns: The image stored in memory cache, if exists and valid. Otherwise, if the image does not exist or /// has already expired, `nil` is returned. open func retrieveImageInMemoryCache( forKey key: String, options: KingfisherOptionsInfo? = nil) -> Image? { return retrieveImageInMemoryCache(forKey: key, options: KingfisherParsedOptionsInfo(options)) } func retrieveImageInDiskCache( forKey key: String, options: KingfisherParsedOptionsInfo, callbackQueue: CallbackQueue = .untouch, completionHandler: @escaping (Result<Image?, KingfisherError>) -> Void) { let computedKey = key.computedKey(with: options.processor.identifier) let loadingQueue: CallbackQueue = options.loadDiskFileSynchronously ? .untouch : .dispatch(ioQueue) loadingQueue.execute { do { var image: Image? = nil if let data = try self.diskStorage.value(forKey: computedKey) { image = options.cacheSerializer.image(with: data, options: options) } callbackQueue.execute { completionHandler(.success(image)) } } catch { if let error = error as? KingfisherError { callbackQueue.execute { completionHandler(.failure(error)) } } else { assertionFailure("The internal thrown error should be a `KingfisherError`.") } } } } /// Gets an image for a given key from the disk storage. /// /// - Parameters: /// - key: The key used for caching the image. /// - options: The `KingfisherOptionsInfo` options setting used for retrieving the image. /// - callbackQueue: The callback queue on which `completionHandler` is invoked. Default is `.untouch`. /// - completionHandler: A closure which is invoked when the operation finishes. open func retrieveImageInDiskCache( forKey key: String, options: KingfisherOptionsInfo? = nil, callbackQueue: CallbackQueue = .untouch, completionHandler: @escaping (Result<Image?, KingfisherError>) -> Void) { retrieveImageInDiskCache( forKey: key, options: KingfisherParsedOptionsInfo(options), callbackQueue: callbackQueue, completionHandler: completionHandler) } // MARK: Cleaning /// Clears the memory storage of this cache. @objc public func clearMemoryCache() { try? memoryStorage.removeAll() } /// Clears the disk storage of this cache. This is an async operation. /// /// - Parameter handler: A closure which is invoked when the cache clearing operation finishes. /// This `handler` will be called from the main queue. open func clearDiskCache(completion handler: (()->())? = nil) { ioQueue.async { do { try self.diskStorage.removeAll() } catch _ { } if let handler = handler { DispatchQueue.main.async { handler() } } } } /// Clears the expired images from disk storage. This is an async operation. open func cleanExpiredMemoryCache() { memoryStorage.removeExpired() } /// Clears the expired images from disk storage. This is an async operation. @objc func cleanExpiredDiskCache() { cleanExpiredDiskCache(completion: nil) } /// Clears the expired images from disk storage. This is an async operation. /// /// - Parameter handler: A closure which is invoked when the cache clearing operation finishes. /// This `handler` will be called from the main queue. open func cleanExpiredDiskCache(completion handler: (() -> Void)? = nil) { ioQueue.async { do { var removed: [URL] = [] let removedExpired = try self.diskStorage.removeExpiredValues() removed.append(contentsOf: removedExpired) let removedSizeExceeded = try self.diskStorage.removeSizeExceededValues() removed.append(contentsOf: removedSizeExceeded) if !removed.isEmpty { DispatchQueue.main.async { let cleanedHashes = removed.map { $0.lastPathComponent } NotificationCenter.default.post( name: .KingfisherDidCleanDiskCache, object: self, userInfo: [KingfisherDiskCacheCleanedHashKey: cleanedHashes]) } } if let handler = handler { DispatchQueue.main.async { handler() } } } catch {} } } #if !os(macOS) && !os(watchOS) /// Clears the expired images from disk storage when app is in background. This is an async operation. /// In most cases, you should not call this method explicitly. /// It will be called automatically when `UIApplicationDidEnterBackgroundNotification` received. @objc public func backgroundCleanExpiredDiskCache() { // if 'sharedApplication()' is unavailable, then return guard let sharedApplication = KingfisherWrapper<UIApplication>.shared else { return } func endBackgroundTask(_ task: inout UIBackgroundTaskIdentifier) { sharedApplication.endBackgroundTask(task) #if swift(>=4.2) task = UIBackgroundTaskIdentifier.invalid #else task = UIBackgroundTaskInvalid #endif } var backgroundTask: UIBackgroundTaskIdentifier! backgroundTask = sharedApplication.beginBackgroundTask { endBackgroundTask(&backgroundTask!) } cleanExpiredDiskCache { endBackgroundTask(&backgroundTask!) } } #endif // MARK: Image Cache State /// Returns the cache type for a given `key` and `identifier` combination. /// This method is used for checking whether an image is cached in current cache. /// It also provides information on which kind of cache can it be found in the return value. /// /// - Parameters: /// - key: The key used for caching the image. /// - identifier: Processor identifier which used for this image. Default is the `identifier` of /// `DefaultImageProcessor.default`. /// - Returns: A `CacheType` instance which indicates the cache status. /// `.none` means the image is not in cache or it is already expired. open func imageCachedType( forKey key: String, processorIdentifier identifier: String = DefaultImageProcessor.default.identifier) -> CacheType { let computedKey = key.computedKey(with: identifier) if memoryStorage.isCached(forKey: computedKey) { return .memory } if diskStorage.isCached(forKey: computedKey) { return .disk } return .none } /// Returns whether the file exists in cache for a given `key` and `identifier` combination. /// /// - Parameters: /// - key: The key used for caching the image. /// - identifier: Processor identifier which used for this image. Default is the `identifier` of /// `DefaultImageProcessor.default`. /// - Returns: A `Bool` which indicates whether a cache could match the given `key` and `identifier` combination. /// /// - Note: /// The return value does not contain information about from which kind of storage the cache matches. /// To get the information about cache type according `CacheType`, /// use `imageCachedType(forKey:processorIdentifier:)` instead. public func isCached( forKey key: String, processorIdentifier identifier: String = DefaultImageProcessor.default.identifier) -> Bool { return imageCachedType(forKey: key, processorIdentifier: identifier).cached } /// Gets the hash used as cache file name for the key. /// /// - Parameters: /// - key: The key used for caching the image. /// - identifier: Processor identifier which used for this image. Default is the `identifier` of /// `DefaultImageProcessor.default`. /// - Returns: The hash which is used as the cache file name. /// /// - Note: /// By default, for a given combination of `key` and `identifier`, `ImageCache` will use the value /// returned by this method as the cache file name. You can use this value to check and match cache file /// if you need. open func hash( forKey key: String, processorIdentifier identifier: String = DefaultImageProcessor.default.identifier) -> String { let computedKey = key.computedKey(with: identifier) return diskStorage.cacheFileName(forKey: computedKey) } /// Calculates the size taken by the disk storage. /// It is the total file size of all cached files in the `diskStorage` on disk in bytes. /// /// - Parameter handler: Called with the size calculating finishes. This closure is invoked from the main queue. open func calculateDiskStorageSize(completion handler: @escaping ((Result<UInt, KingfisherError>) -> Void)) { ioQueue.async { do { let size = try self.diskStorage.totalSize() DispatchQueue.main.async { handler(.success(size)) } } catch { if let error = error as? KingfisherError { DispatchQueue.main.async { handler(.failure(error)) } } else { assertionFailure("The internal thrown error should be a `KingfisherError`.") } } } } /// Gets the cache path for the key. /// It is useful for projects with web view or anyone that needs access to the local file path. /// /// i.e. Replacing the `<img src='path_for_key'>` tag in your HTML. /// /// - Parameters: /// - key: The key used for caching the image. /// - identifier: Processor identifier which used for this image. Default is the `identifier` of /// `DefaultImageProcessor.default`. /// - Returns: The disk path of cached image under the given `key` and `identifier`. /// /// - Note: /// This method does not guarantee there is an image already cached in the returned path. It just gives your /// the path that the image should be, if it exists in disk storage. /// /// You could use `isCached(forKey:)` method to check whether the image is cached under that key in disk. open func cachePath( forKey key: String, processorIdentifier identifier: String = DefaultImageProcessor.default.identifier) -> String { let computedKey = key.computedKey(with: identifier) return diskStorage.cacheFileURL(forKey: computedKey).path } } extension Dictionary { func keysSortedByValue(_ isOrderedBefore: (Value, Value) -> Bool) -> [Key] { return Array(self).sorted{ isOrderedBefore($0.1, $1.1) }.map{ $0.0 } } } #if !os(macOS) && !os(watchOS) // MARK: - For App Extensions extension UIApplication: KingfisherCompatible { } extension KingfisherWrapper where Base: UIApplication { public static var shared: UIApplication? { let selector = NSSelectorFromString("sharedApplication") guard Base.responds(to: selector) else { return nil } return Base.perform(selector).takeUnretainedValue() as? UIApplication } } #endif extension String { func computedKey(with identifier: String) -> String { if identifier.isEmpty { return self } else { return appending("@\(identifier)") } } }
mit
24c2527a09cde63c52ed69a30cd9d66f
43.116481
121
0.620499
5.217939
false
false
false
false
MainasuK/Bangumi-M
Percolator/Percolator/Staff.swift
1
842
// // Staff.swift // Percolator // // Created by Cirno MainasuK on 2015-8-21. // Copyright (c) 2015年 Cirno MainasuK. All rights reserved. // import Foundation import SwiftyJSON struct Staff { let id: Int let url: String let name: String let nameCN: String let roleName: String let images: Images let jobs: [String] init(from json: JSON) { id = json[BangumiKey.id].intValue url = json[BangumiKey.url].stringValue name = json[BangumiKey.name].stringValue nameCN = json[BangumiKey.nameCN].stringValue roleName = json[BangumiKey.roleName].stringValue let imageDict = json[BangumiKey.imagesDict].dictionaryValue images = Images(json: imageDict) jobs = json[BangumiKey.jobs].arrayValue.flatMap { $0.string } } }
mit
6212c90d1189c19e744afdab2ea606e7
23.705882
69
0.640476
3.766816
false
false
false
false
mercadopago/px-ios
MercadoPagoSDK/MercadoPagoSDK/UI/PXCardSlider/FSPager/FSPageViewTransformer.swift
1
11310
import UIKit @objc public enum FSPagerViewTransformerType: Int { case crossFading case zoomOut case depth case overlap case linear case coverFlow case ferrisWheel case invertedFerrisWheel case cubic } open class FSPagerViewTransformer: NSObject { open internal(set) weak var pagerView: FSPagerView? open internal(set) var type: FSPagerViewTransformerType open var minimumScale: CGFloat = 0.65 open var minimumAlpha: CGFloat = 0.6 @objc public init(type: FSPagerViewTransformerType) { self.type = type switch type { case .zoomOut: self.minimumScale = 0.85 case .depth: self.minimumScale = 0.5 default: break } } // Apply transform to attributes - zIndex: Int, frame: CGRect, alpha: CGFloat, transform: CGAffineTransform or transform3D: CATransform3D. open func applyTransform(to attributes: FSPagerViewLayoutAttributes) { guard let pagerView = self.pagerView else { return } let position = attributes.position let scrollDirection = pagerView.scrollDirection let itemSpacing = (scrollDirection == .horizontal ? attributes.bounds.width : attributes.bounds.height) + self.proposedInteritemSpacing() switch self.type { case .crossFading: var zIndex = 0 var alpha: CGFloat = 0 var transform = CGAffineTransform.identity switch scrollDirection { case .horizontal: transform.tx = -itemSpacing * position case .vertical: transform.ty = -itemSpacing * position } if abs(position) < 1 { // [-1,1] // Use the default slide transition when moving to the left page alpha = 1 - abs(position) zIndex = 1 } else { // (1,+Infinity] // This page is way off-screen to the right. alpha = 0 zIndex = Int.min } attributes.alpha = alpha attributes.transform = transform attributes.zIndex = zIndex case .zoomOut: var alpha: CGFloat = 0 var transform = CGAffineTransform.identity switch position { case -CGFloat.greatestFiniteMagnitude ..< -1 : // [-Infinity,-1) // This page is way off-screen to the left. alpha = 0 case -1 ... 1 : // [-1,1] // Modify the default slide transition to shrink the page as well let scaleFactor = max(self.minimumScale, 1 - abs(position)) transform.a = scaleFactor transform.d = scaleFactor switch scrollDirection { case .horizontal: let vertMargin = attributes.bounds.height * (1 - scaleFactor) / 2 let horzMargin = itemSpacing * (1 - scaleFactor) / 2 transform.tx = position < 0 ? (horzMargin - vertMargin * 2) : (-horzMargin + vertMargin * 2) case .vertical: let horzMargin = attributes.bounds.width * (1 - scaleFactor) / 2 let vertMargin = itemSpacing * (1 - scaleFactor) / 2 transform.ty = position < 0 ? (vertMargin - horzMargin * 2) : (-vertMargin + horzMargin * 2) } // Fade the page relative to its size. alpha = self.minimumAlpha + (scaleFactor - self.minimumScale) / (1 - self.minimumScale) * (1 - self.minimumAlpha) case 1 ... CGFloat.greatestFiniteMagnitude : // (1,+Infinity] // This page is way off-screen to the right. alpha = 0 default: break } attributes.alpha = alpha attributes.transform = transform case .depth: var transform = CGAffineTransform.identity var zIndex = 0 var alpha: CGFloat = 0.0 switch position { case -CGFloat.greatestFiniteMagnitude ..< -1: // [-Infinity,-1) // This page is way off-screen to the left. alpha = 0 zIndex = 0 case -1 ... 0: // [-1,0] // Use the default slide transition when moving to the left page alpha = 1 transform.tx = 0 transform.a = 1 transform.d = 1 zIndex = 1 case 0 ..< 1: // (0,1) // Fade the page out. alpha = CGFloat(1.0) - position // Counteract the default slide transition switch scrollDirection { case .horizontal: transform.tx = itemSpacing * -position case .vertical: transform.ty = itemSpacing * -position } // Scale the page down (between minimumScale and 1) let scaleFactor = self.minimumScale + (1.0 - self.minimumScale) * (1.0 - abs(position)) transform.a = scaleFactor transform.d = scaleFactor zIndex = 0 case 1 ... CGFloat.greatestFiniteMagnitude: // [1,+Infinity) // This page is way off-screen to the right. alpha = 0 zIndex = 0 default: break } attributes.alpha = alpha attributes.transform = transform attributes.zIndex = zIndex case .overlap, .linear: guard scrollDirection == .horizontal else { // This type doesn't support vertical mode return } let scale = max(1 - (1 - self.minimumScale) * abs(position), self.minimumScale) let transform = CGAffineTransform(scaleX: scale, y: scale) attributes.transform = transform let alpha = (self.minimumAlpha + (1 - abs(position)) * (1 - self.minimumAlpha)) attributes.alpha = alpha let zIndex = (1 - abs(position)) * 10 attributes.zIndex = Int(zIndex) case .coverFlow: guard scrollDirection == .horizontal else { // This type doesn't support vertical mode return } let position = min(max(-position, -1), 1) let rotation = sin(position * (.pi) * 0.5) * (.pi) * 0.25 * 1.5 let translationZ = -itemSpacing * 0.5 * abs(position) var transform3D = CATransform3DIdentity transform3D.m34 = -0.002 transform3D = CATransform3DRotate(transform3D, rotation, 0, 1, 0) transform3D = CATransform3DTranslate(transform3D, 0, 0, translationZ) attributes.zIndex = 100 - Int(abs(position)) attributes.transform3D = transform3D case .ferrisWheel, .invertedFerrisWheel: guard scrollDirection == .horizontal else { // This type doesn't support vertical mode return } // http://ronnqvi.st/translate-rotate-translate/ var zIndex = 0 var transform = CGAffineTransform.identity switch position { case -5 ... 5: let itemSpacing = attributes.bounds.width + self.proposedInteritemSpacing() let count: CGFloat = 14 let circle: CGFloat = .pi * 2.0 let radius = itemSpacing * count / circle let ty = radius * (self.type == .ferrisWheel ? 1 : -1) let theta = circle / count let rotation = position * theta * (self.type == .ferrisWheel ? 1 : -1) transform = transform.translatedBy(x: -position * itemSpacing, y: ty) transform = transform.rotated(by: rotation) transform = transform.translatedBy(x: 0, y: -ty) zIndex = Int((4.0 - abs(position) * 10)) default: break } attributes.alpha = abs(position) < 0.5 ? 1 : self.minimumAlpha attributes.transform = transform attributes.zIndex = zIndex case .cubic: switch position { case -CGFloat.greatestFiniteMagnitude ... -1: attributes.alpha = 0 case -1 ..< 1: attributes.alpha = 1 attributes.zIndex = Int((1 - position) * CGFloat(10)) let direction: CGFloat = position < 0 ? 1 : -1 let theta = position * .pi * 0.5 * (scrollDirection == .horizontal ? 1 : -1) let radius = scrollDirection == .horizontal ? attributes.bounds.width : attributes.bounds.height var transform3D = CATransform3DIdentity transform3D.m34 = -0.002 switch scrollDirection { case .horizontal: // ForwardX -> RotateY -> BackwardX attributes.center.x += direction * radius * 0.5 // ForwardX transform3D = CATransform3DRotate(transform3D, theta, 0, 1, 0) // RotateY transform3D = CATransform3DTranslate(transform3D, -direction * radius * 0.5, 0, 0) // BackwardX case .vertical: // ForwardY -> RotateX -> BackwardY attributes.center.y += direction * radius * 0.5 // ForwardY transform3D = CATransform3DRotate(transform3D, theta, 1, 0, 0) // RotateX transform3D = CATransform3DTranslate(transform3D, 0, -direction * radius * 0.5, 0) // BackwardY } attributes.transform3D = transform3D case 1 ... CGFloat.greatestFiniteMagnitude: attributes.alpha = 0 default: attributes.alpha = 0 attributes.zIndex = 0 } } } // An interitem spacing proposed by transformer class. This will override the default interitemSpacing provided by the pager view. open func proposedInteritemSpacing() -> CGFloat { guard let pagerView = self.pagerView else { return 0 } let scrollDirection = pagerView.scrollDirection switch self.type { case .overlap: guard scrollDirection == .horizontal else { return 0 } return pagerView.itemSize.width * -self.minimumScale * 0.6 case .linear: guard scrollDirection == .horizontal else { return 0 } return pagerView.itemSize.width * -self.minimumScale * 0.2 case .coverFlow: guard scrollDirection == .horizontal else { return 0 } return -pagerView.itemSize.width * sin(.pi * 0.25 * 0.25 * 3.0) case .ferrisWheel, .invertedFerrisWheel: guard scrollDirection == .horizontal else { return 0 } return -pagerView.itemSize.width * 0.15 case .cubic: return 0 default: break } return pagerView.interitemSpacing } }
mit
eb76c5861eff7b205c0ef3b45f3987c6
42.167939
145
0.53351
5.110709
false
false
false
false
knutnyg/ios-iou
iou/ExpensesHandler.swift
1
6358
import Foundation import BrightFutures import SwiftyJSON import SwiftHTTP import JSONJoy class ExpensesHandler { static func getExpensesForGroup(token:String, group:Group) -> Future<[Expense],NSError> { let promise = Promise<[Expense], NSError>() let url:String = "\(API.baseUrl)/api/spreadsheets/\(group.id)/receipts" do { let request = try HTTP.GET(url, headers: ["AccessToken":token], requestSerializer:JSONParameterSerializer()) request.start { response in if let err = response.error { print("ExpensesListFetcher: Response contains error: \(err)") promise.failure(err) return } print("Debug: ExpensesListFetcher got response") let expenseList = ExpenseList(JSONDecoder(response.data)) print(response.description) for expense:Expense in expenseList.expenses { self.populateCreatorIfNotSet(expense, members: group.members) } promise.success(expenseList.expenses) } } catch { print("ExpensesListFetcher: got error in getExpensesForGroup") promise.failure(NSError(domain: "SSL", code: 503, userInfo: nil)) } return promise.future } static func updateExpense(token:String, expense:Expense) -> Future<Expense,NSError>{ let updatePromise = Promise<Expense,NSError>() let urlString = "\(API.baseUrl)/api/spreadsheets/\(expense.groupId)/receipts/\(expense.id)" let payload:[String:AnyObject] = expense.toJSONparsableDicitonary() as! [String : AnyObject] do { let request = try HTTP.PUT(urlString, parameters: payload, headers: ["AccessToken":token], requestSerializer: JSONParameterSerializer()) request.start { response in if let err = response.error { print("ExpensesListFetcher-updateExpense: Response contains error: \(err)") updatePromise.failure(NSError(domain: "Update expense", code: response.statusCode!, userInfo: nil)) return } if response.statusCode! != 200 { updatePromise.failure(NSError(domain: "Update expense failed?", code: response.statusCode!, userInfo: nil)) return } print("---- UPDATE EXPENSE RESPONSE ----\n" + response.description) let expense = Expense(JSONDecoder(response.data)) updatePromise.success(expense) } } catch { updatePromise.failure(NSError(domain: "Request Error", code: 500, userInfo: nil)) } return updatePromise.future } static func newExpense(token:String, expense:Expense) -> Future<Expense,NSError>{ let updatePromise = Promise<Expense,NSError>() if expense.participants.count == 0 { return Future(error: NSError(domain: "Participants cannot be 0", code: 500, userInfo: nil)) } let urlString = "\(API.baseUrl)/api/spreadsheets/\(expense.groupId)/receipts" let payload:[String:AnyObject] = expense.toJSONCreate() as! [String : AnyObject] do { let request = try HTTP.POST(urlString, parameters: payload, headers: ["AccessToken":token], requestSerializer: JSONParameterSerializer()) request.start { response in if let err = response.error { print("ExpensesListFetcher-updateExpense: Response contains error: \(err)") updatePromise.failure(NSError(domain: "New expense failed", code: response.statusCode!, userInfo: nil)) return } if response.statusCode! != 201 { updatePromise.failure(NSError(domain: "New expense failed?", code: response.statusCode!, userInfo: nil)) return } print(response.description) let expense = Expense(JSONDecoder(response.data)) updatePromise.success(expense) } } catch { updatePromise.failure(NSError(domain: "Request Error", code: 500, userInfo: nil)) } return updatePromise.future } static func deleteExpense(token:String, expense:Expense) -> Future<Expense, NSError>{ let deletePromise = Promise<Expense,NSError>() let urlString = "\(API.baseUrl)/api/spreadsheets/\(expense.groupId)/receipts/\(expense.id)" print(urlString) do { let request = try HTTP.DELETE(urlString, headers: ["AccessToken":token], requestSerializer: JSONParameterSerializer()) request.start { response in print(response.description) if let err = response.error { print("ExpensesHandler-deleteExpense: Response contains error: \(err)") deletePromise.failure(NSError(domain: "Delete expense failed", code: response.statusCode!, userInfo: nil)) return } if (response.statusCode! == 200 || response.statusCode! == 204) { deletePromise.success(expense) return } deletePromise.failure(NSError(domain: "Delete expense failed", code: response.statusCode!, userInfo: nil)) return } } catch { deletePromise.failure(NSError(domain: "Request Error", code: 500, userInfo: nil)) } return deletePromise.future } static func populateCreatorIfNotSet(expense:Expense, members:[User]){ if expense.creator.name == nil{ if let user = findUserById(expense.creator.id, members: members) { expense.creator = user } } } static func findUserById(id:String, members:[User]) -> User?{ for user in members { if user.id == id { return user } } return nil } }
bsd-2-clause
2ed4f839290cff1cd718572e461060a6
38.490683
149
0.565901
5.224322
false
false
false
false
fedepo/phoneid_iOS
Pod/Classes/ui/customization/ComponentFactory.swift
2
4143
// // ComponentFactory.swift // phoneid_iOS // // Copyright 2015 phone.id - 73 knots, Inc. // // 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 @objc public protocol ComponentFactory: NSObjectProtocol { func loginViewController() -> LoginViewController func countryCodePickerViewController(_ model: NumberInfo) -> CountryCodePickerViewController func editProfileViewController(_ model: UserInfo) -> EditProfileViewController func imageEditViewController(_ image: UIImage) -> ImageEditViewController func editUserNameViewController(_ model: UserInfo) -> UserNameViewController func loginView(_ model: NumberInfo) -> LoginView func countryCodePickerView(_ model: NumberInfo) -> CountryCodePickerView func editProfileView(_ model: UserInfo) -> EditProfileView func userNameView(_ model: String?) -> UserNameView var colorScheme:ColorScheme {get set} var localizationBundle: Bundle {get set} var localizationTableName:String {get set} var defaultBackgroundImage:UIImage? {get set} } @objc open class DefaultComponentFactory: NSObject, ComponentFactory { open func loginViewController() -> LoginViewController { let controller = LoginViewController() return controller } open func loginView(_ model: NumberInfo) -> LoginView { let view = LoginView(model: model, scheme: self.colorScheme, bundle: self.localizationBundle, tableName: localizationTableName) return view } open func countryCodePickerViewController(_ model: NumberInfo) -> CountryCodePickerViewController { let controller = CountryCodePickerViewController(model: model) return controller } open func countryCodePickerView(_ model: NumberInfo) -> CountryCodePickerView { let view = CountryCodePickerView(model: model, scheme: self.colorScheme, bundle: self.localizationBundle, tableName: localizationTableName) return view } open func editProfileViewController(_ model: UserInfo) -> EditProfileViewController { let controller = EditProfileViewController(model: model) return controller } open func imageEditViewController(_ image: UIImage) -> ImageEditViewController { let controller = ImageEditViewController(image: image) return controller } open func editUserNameViewController(_ model: UserInfo) -> UserNameViewController { let controller = UserNameViewController(model: model) return controller } open func userNameView(_ model: String?) -> UserNameView { let view = UserNameView(userName: model, scheme: self.colorScheme, bundle: self.localizationBundle, tableName: localizationTableName) return view } open func editProfileView(_ model: UserInfo) -> EditProfileView { let view = EditProfileView(user: model, scheme: self.colorScheme, bundle: self.localizationBundle, tableName: localizationTableName) return view } open var colorScheme = ColorScheme() open var localizationBundle = Bundle.phoneIdBundle() open var localizationTableName = "Localizable" open var defaultBackgroundImage = UIImage(namedInPhoneId: "background") } public protocol PhoneIdConsumer: NSObjectProtocol { var phoneIdService: PhoneIdService! { get } var phoneIdComponentFactory: ComponentFactory! { get } } public extension PhoneIdConsumer { var phoneIdService: PhoneIdService! { return PhoneIdService.sharedInstance } var phoneIdComponentFactory: ComponentFactory! { return phoneIdService.componentFactory } }
apache-2.0
d71fbdf0ed29cea60cd045aeb45d86f5
32.682927
147
0.732802
5.095941
false
false
false
false
zhixingxi/JJA_Swift
JJA_Swift/JJA_Swift/Utils/Extensions/UIViewExtension.swift
1
1118
// // UIViewExtension.swift // JJA_Swift // // Created by MQL-IT on 2017/8/9. // Copyright © 2017年 MQL-IT. All rights reserved. // UIView布局工具 import UIKit extension UIView { var x: CGFloat { get { return frame.origin.x } set { frame.origin.x = newValue } } var y: CGFloat { get { return frame.origin.y } set { frame.origin.y = newValue } } var width: CGFloat { get { return frame.size.width } set { frame.size.width = newValue } } var height: CGFloat { get { return frame.size.height } set { frame.size.height = newValue } } var centerX: CGFloat { get { return center.x } set { center.x = newValue } } var centerY: CGFloat { get { return center.y } set { center.y = newValue } } }
mit
3becedf22b46daffcc9ea47a8d557e24
15.522388
50
0.418248
4.307393
false
false
false
false
vgorloff/AUHost
Vendor/mc/mcxUIExtensions/Sources/AppKit/NSView.swift
1
6351
// // NSView.swift // MCA-OSS-VSTNS;MCA-OSS-AUH // // Created by Vlad Gorlov on 06.06.2020. // Copyright © 2020 Vlad Gorlov. All rights reserved. // #if canImport(AppKit) && !targetEnvironment(macCatalyst) import AppKit import mcxRuntime import mcxTypes import mcxUI extension NSView { public var accessibilityId: String? { get { return accessibilityIdentifier() } set { setAccessibilityIdentifier(newValue) } } public var isVisible: Bool { get { return !isHidden } set { isHidden = !newValue } } public func convertFromBacking(_ value: CGFloat) -> CGFloat { return convertFromBacking(NSSize(width: value, height: value)).width } public func convertToBacking(_ value: CGFloat) -> CGFloat { return convertToBacking(NSSize(width: value, height: value)).width } public func addSubviews(_ views: NSView...) { for view in views { addSubview(view) } } public func addSubviews(_ views: [NSView]) { for view in views { addSubview(view) } } public func removeSubviews() { subviews.forEach { $0.removeFromSuperview() } } public var recursiveSubviews: [NSView] { var result = subviews for subview in subviews { result += subview.recursiveSubviews } return result } public var controls: [NSControl] { return subviews.compactMap { $0 as? NSControl } } public var recursiveControls: [NSControl] { var result = controls for subview in subviews { result += subview.recursiveControls } return result } public func recursiveSubviews<T: NSView>(for type: T.Type) -> [T] { return recursiveSubviews.compactMap { $0 as? T } } @available(macOS, deprecated: 10.14, message: "To draw, subclass NSView and implement -drawRect:; AppKit's automatic deferred display mechanism will call -drawRect: as necessary to display the view.") public func withFocus(drawingCalls: () -> Void) { lockFocus() drawingCalls() unlockFocus() } } extension NSView { /// - fittingSizeCompression: 50 /// - defaultLow: 250 /// - dragThatCannotResizeWindow: 490 /// - windowSizeStayPut: 500 /// - dragThatCanResizeWindow: 510 /// - defaultHigh: 750 /// - required: 1000 public var verticalContentCompressionResistancePriority: NSLayoutConstraint.Priority { get { return contentCompressionResistancePriority(for: .vertical) } set { setContentCompressionResistancePriority(newValue, for: .vertical) } } /// - fittingSizeCompression: 50 /// - defaultLow: 250 /// - dragThatCannotResizeWindow: 490 /// - windowSizeStayPut: 500 /// - dragThatCanResizeWindow: 510 /// - defaultHigh: 750 /// - required: 1000 public var horizontalContentCompressionResistancePriority: NSLayoutConstraint.Priority { get { return contentCompressionResistancePriority(for: .horizontal) } set { setContentCompressionResistancePriority(newValue, for: .horizontal) } } /// - fittingSizeCompression: 50 /// - defaultLow: 250 /// - dragThatCannotResizeWindow: 490 /// - windowSizeStayPut: 500 /// - dragThatCanResizeWindow: 510 /// - defaultHigh: 750 /// - required: 1000 public var verticalContentHuggingPriority: NSLayoutConstraint.Priority { get { return contentHuggingPriority(for: .vertical) } set { setContentHuggingPriority(newValue, for: .vertical) } } /// - fittingSizeCompression: 50 /// - defaultLow: 250 /// - dragThatCannotResizeWindow: 490 /// - windowSizeStayPut: 500 /// - dragThatCanResizeWindow: 510 /// - defaultHigh: 750 /// - required: 1000 public var horizontalContentHuggingPriority: NSLayoutConstraint.Priority { get { return contentHuggingPriority(for: .horizontal) } set { setContentHuggingPriority(newValue, for: .horizontal) } } // MARK: - public var systemAppearance: SystemAppearance { if #available(OSX 10.14, *) { return effectiveAppearance.systemAppearance } else { // See: https://stackoverflow.com/q/51774587/1418981 if NSWorkspace.shared.accessibilityDisplayShouldIncreaseContrast { return .highContrastLight } else { return .light } } } } extension NSView { public func setBorder(width: CGFloat? = nil, color: NSColor) { wantsLayer = true layer?.setBorder(width: width ?? convertFromBacking(1), color: color) } } extension NSView { public func setNeedsLayout() { needsLayout = true } public func layoutIfNeeded() { if needsLayout { layout() layoutSubtreeIfNeeded() } } public func sizeToFittingSize() { frame = CGRect(origin: frame.origin, size: fittingSize) } public func autolayoutView() -> Self { translatesAutoresizingMaskIntoConstraints = false return self } public func autoresizingView() -> Self { translatesAutoresizingMaskIntoConstraints = true return self } /// Prints results of internal Apple API method `_subtreeDescription` to console. public func dump() { let value = perform(Selector(("_subtreeDescription"))) Swift.print(String(describing: value)) } public func autolayoutTrace() { let value = perform(Selector(("_autolayoutTrace"))) Swift.print(String(describing: value)) } public var ambiguousSubviews: [NSView] { guard BuildInfo.isDebug else { return [] } let result = recursiveSubviews.filter { $0.hasAmbiguousLayout } return result } public func assertOnAmbiguityInSubviewsLayout() { guard BuildInfo.isDebug else { return } DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { let value = self.ambiguousSubviews value.forEach { print("- " + $0.debugDescription) $0.autolayoutTrace() } if RuntimeInfo.shouldAssertOnAmbiguousLayout { assert(value.isEmpty) } } } } extension NSView { public var anchor: LayoutConstraint { return LayoutConstraint() } } #endif
mit
c157902501296b7c9610b17b0f78cae5
25.02459
203
0.638425
4.652015
false
false
false
false
rudkx/swift
test/Interop/Cxx/foreign-reference/singleton-silgen.swift
1
2473
// RUN: %target-swift-emit-silgen %s -I %S/Inputs -enable-cxx-interop | %FileCheck %s import Singleton // CHECK-NOT: borrow // CHECK-NOT: retain // CHECK-NOT: release // CHECK-LABEL: sil [ossa] @$s4main4testyyF : $@convention(thin) () -> () // CHECK: [[BOX:%.*]] = project_box {{.*}} : ${ var DeletedSpecialMembers }, 0 // CHECK: [[CREATE_FN:%.*]] = function_ref @{{_ZN21DeletedSpecialMembers6createEv|\?create\@DeletedSpecialMembers\@\@SAPEAU1\@XZ}} : $@convention(c) () -> DeletedSpecialMembers // CHECK: [[CREATED_PTR:%.*]] = apply [[CREATE_FN]]() : $@convention(c) () -> DeletedSpecialMembers // CHECK: store [[CREATED_PTR]] to [trivial] [[BOX]] : $*DeletedSpecialMembers // CHECK: [[ACCESS_1:%.*]] = begin_access [read] [unknown] [[BOX]] : $*DeletedSpecialMembers // CHECK: [[X_1:%.*]] = load [trivial] [[ACCESS_1]] : $*DeletedSpecialMembers // CHECK: [[TMP:%.*]] = alloc_stack $DeletedSpecialMembers // CHECK: store [[X_1]] to [trivial] [[TMP]] // CHECK: [[TEST_FN:%.*]] = function_ref @{{_ZNK21DeletedSpecialMembers4testEv|\?test\@DeletedSpecialMembers\@\@QEBAHXZ}} : $@convention(cxx_method) (@in_guaranteed DeletedSpecialMembers) -> Int32 // CHECK: apply [[TEST_FN]]([[TMP]]) : $@convention(cxx_method) (@in_guaranteed DeletedSpecialMembers) -> Int32 // CHECK: [[ACCESS_2:%.*]] = begin_access [read] [unknown] [[BOX]] : $*DeletedSpecialMembers // CHECK: [[X_2:%.*]] = load [trivial] [[ACCESS_2]] : $*DeletedSpecialMembers // CHECK: [[MOVE_IN_RES_FN:%.*]] = function_ref @{{_Z8mutateItR21DeletedSpecialMembers|\?mutateIt\@\@YAXAEAUDeletedSpecialMembers\@\@\@Z}} : $@convention(c) (DeletedSpecialMembers) -> () // CHECK: apply [[MOVE_IN_RES_FN]]([[X_2]]) : $@convention(c) (DeletedSpecialMembers) -> () // CHECK: return // CHECK-LABEL: end sil function '$s4main4testyyF' public func test() { var x = DeletedSpecialMembers.create() _ = x.test() mutateIt(x) } // CHECK-LABEL: sil [clang DeletedSpecialMembers.create] @{{_ZN21DeletedSpecialMembers6createEv|\?create\@DeletedSpecialMembers\@\@SAPEAU1\@XZ}} : $@convention(c) () -> DeletedSpecialMembers // CHECK-LABEL: sil [clang DeletedSpecialMembers.test] @{{_ZNK21DeletedSpecialMembers4testEv|\?test\@DeletedSpecialMembers\@\@QEBAHXZ}} : $@convention(cxx_method) (@in_guaranteed DeletedSpecialMembers) -> Int32 // CHECK-LABEL: sil [serialized] [clang mutateIt] @{{_Z8mutateItR21DeletedSpecialMembers|\?mutateIt\@\@YAXAEAUDeletedSpecialMembers\@\@\@Z}} : $@convention(c) (DeletedSpecialMembers) -> ()
apache-2.0
80cdd3a89073af348da02ade9d73fdda
59.317073
210
0.678932
3.30615
false
true
false
false
huangboju/AsyncDisplay_Study
AsyncDisplay/CustomCollectionView/MosaicCollectionViewLayout.swift
1
9708
// // MosaicCollectionViewLayout // Sample // // Created by Rajeev Gupta on 11/9/16. // // Copyright (c) 2014-present, Facebook, Inc. All rights reserved. // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. // // 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 // FACEBOOK 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 AsyncDisplayKit protocol MosaicCollectionViewLayoutDelegate: ASCollectionDelegate { func collectionView(_ collectionView: UICollectionView, layout: MosaicCollectionViewLayout, originalItemSizeAtIndexPath: IndexPath) -> CGSize } class MosaicCollectionViewLayout: UICollectionViewFlowLayout { var numberOfColumns: Int var columnSpacing: CGFloat var _sectionInset: UIEdgeInsets var interItemSpacing: UIEdgeInsets var headerHeight: CGFloat var _columnHeights: [[CGFloat]]? var _itemAttributes = [[UICollectionViewLayoutAttributes]]() var _headerAttributes = [UICollectionViewLayoutAttributes]() var _allAttributes = [UICollectionViewLayoutAttributes]() required override init() { numberOfColumns = 2 columnSpacing = 10.0 headerHeight = 44.0 //viewcontroller _sectionInset = UIEdgeInsets.init(top: 10.0, left: 10.0, bottom: 10.0, right: 10.0) interItemSpacing = UIEdgeInsets.init(top: 10.0, left: 0, bottom: 10.0, right: 0) super.init() scrollDirection = .vertical } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public weak var delegate : MosaicCollectionViewLayoutDelegate? override func prepare() { super.prepare() guard let collectionView = collectionView else { return } _itemAttributes = [] _allAttributes = [] _headerAttributes = [] _columnHeights = [] var top: CGFloat = 0 let numberOfSections = collectionView.numberOfSections for section in 0 ..< numberOfSections { let numberOfItems = collectionView.numberOfItems(inSection: section) top += _sectionInset.top if headerHeight > 0 { let headerSize = _headerSizeForSection(section: section) let attributes = UICollectionViewLayoutAttributes(forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, with: IndexPath(row: 0, section: section)) attributes.frame = CGRect(x: _sectionInset.left, y: top, width: headerSize.width, height: headerSize.height) _headerAttributes.append(attributes) _allAttributes.append(attributes) top = attributes.frame.maxY } _columnHeights?.append([]) // Adding new Section for _ in 0 ..< numberOfColumns { _columnHeights?[section].append(top) } let columnWidth = _columnWidthForSection(section: section) _itemAttributes.append([]) for idx in 0 ..< numberOfItems { let columnIndex = _shortestColumnIndexInSection(section: section) let indexPath = IndexPath(item: idx, section: section) let itemSize = _itemSizeAtIndexPath(indexPath: indexPath); let xOffset = _sectionInset.left + (columnWidth + columnSpacing) * CGFloat(columnIndex) let yOffset = _columnHeights![section][columnIndex] let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath) attributes.frame = CGRect(x: xOffset, y: yOffset, width: itemSize.width, height: itemSize.height) _columnHeights?[section][columnIndex] = attributes.frame.maxY + interItemSpacing.bottom _itemAttributes[section].append(attributes) _allAttributes.append(attributes) } let columnIndex = _tallestColumnIndexInSection(section: section) top = (_columnHeights?[section][columnIndex])! - interItemSpacing.bottom + _sectionInset.bottom for idx in 0 ..< _columnHeights![section].count { _columnHeights![section][idx] = top } } } override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { // Slow search for small batches return _allAttributes.filter { $0.frame.intersects(rect) } } override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { guard indexPath.section < _itemAttributes.count, indexPath.item < _itemAttributes[indexPath.section].count else { return nil } return _itemAttributes[indexPath.section][indexPath.item] } override func layoutAttributesForSupplementaryView(ofKind elementKind: String, at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { if elementKind == UICollectionView.elementKindSectionHeader { return _headerAttributes[indexPath.section] } return nil } override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool { return collectionView?.bounds.size != newBounds.size } func _widthForSection(section: Int) -> CGFloat { return collectionView!.bounds.width - _sectionInset.left - _sectionInset.right } func _columnWidthForSection(section: Int) -> CGFloat { return abs((_widthForSection(section: section) - ((CGFloat(numberOfColumns - 1)) * columnSpacing)) / CGFloat(numberOfColumns)) } func _itemSizeAtIndexPath(indexPath: IndexPath) -> CGSize { var size = CGSize(width: self._columnWidthForSection(section: indexPath.section), height: 0) let originalSize = self.delegate!.collectionView(self.collectionView!, layout:self, originalItemSizeAtIndexPath: indexPath) if originalSize.height > 0 && originalSize.width > 0 { size.height = originalSize.height / originalSize.width * size.width } return size } func _headerSizeForSection(section: Int) -> CGSize { return CGSize(width: _widthForSection(section: section), height: headerHeight) } override var collectionViewContentSize: CGSize { guard let columnHeights = _columnHeights else { return .zero } var height: CGFloat = 0 if columnHeights.count > 0 { if columnHeights[columnHeights.count - 1].count > 0 { height = columnHeights[columnHeights.count - 1][0] } } return CGSize(width: collectionView!.bounds.width, height: height) } func _tallestColumnIndexInSection(section: Int) -> Int { var index = 0 var tallestHeight: CGFloat = 0 _columnHeights?[section].enumerated().forEach { (idx,height) in if height > tallestHeight { index = idx tallestHeight = height } } return index } func _shortestColumnIndexInSection(section: Int) -> Int { var index: Int = 0 var shortestHeight = CGFloat.greatestFiniteMagnitude _columnHeights?[section].enumerated().forEach { (idx,height) in if height < shortestHeight { index = idx shortestHeight = height } } return index } } class MosaicCollectionViewLayoutInspector: NSObject, ASCollectionViewLayoutInspecting { func collectionView(_ collectionView: ASCollectionView, constrainedSizeForNodeAt indexPath: IndexPath) -> ASSizeRange { let layout = collectionView.collectionViewLayout as! MosaicCollectionViewLayout return ASSizeRangeMake(.zero, layout._itemSizeAtIndexPath(indexPath: indexPath)) } func collectionView(_ collectionView: ASCollectionView, constrainedSizeForSupplementaryNodeOfKind: String, at atIndexPath: IndexPath) -> ASSizeRange { let layout = collectionView.collectionViewLayout as! MosaicCollectionViewLayout return ASSizeRange(min: .zero, max: layout._headerSizeForSection(section: atIndexPath.section)) } /** * Asks the inspector for the number of supplementary sections in the collection view for the given kind. */ func collectionView(_ collectionView: ASCollectionView, numberOfSectionsForSupplementaryNodeOfKind kind: String) -> UInt { if kind == UICollectionView.elementKindSectionHeader { return UInt((collectionView.dataSource?.numberOfSections!(in: collectionView))!) } else { return 0 } } /** * Asks the inspector for the number of supplementary views for the given kind in the specified section. */ func collectionView(_ collectionView: ASCollectionView, supplementaryNodesOfKind kind: String, inSection section: UInt) -> UInt { if kind == UICollectionView.elementKindSectionHeader { return 1 } else { return 0 } } func scrollableDirections() -> ASScrollDirection { return ASScrollDirectionVerticalDirections } }
mit
3265ec7ac278aa857d35bb75f66099c3
39.282158
179
0.661104
5.345815
false
false
false
false
dominikoledzki/TextDrawing
TextDrawing/Sequence+ConsecutiveElements.swift
1
2448
// // Sequence+ConsecutiveElements.swift // // Created by Dominik Olędzki on 23/01/2017. // Copyright © 2017 Dominik Olędzki. // This software is published under MIT license https://opensource.org/licenses/mit-license.php // import Foundation extension Sequence { /** You can use this method to access sequence by n consecutive elements, starting from each element. For example, the following code `Array((0..<4).takeElements(by: 2))` will result in array like that: `[[0, 1], [1, 2], [2, 3]]` - Parameter by: number of elements taken from original sequence to form one element of new sequence - Returns: Sequence of arrays, where each array contains `n` elements from original sequence */ func takeElements(by n: Int) -> ConsecutiveElementsSequence<Self> { return ConsecutiveElementsSequence(originSequence: self, takenElementsCount: n) } } struct ConsecutiveElementsSequence<OriginSequence: Sequence>: Sequence { typealias OriginIterator = OriginSequence.Iterator typealias Iterator = ConsecutiveElementsIterator<OriginIterator> let originSequence: OriginSequence let takenElementsCount: Int func makeIterator() -> ConsecutiveElementsIterator<OriginSequence.Iterator> { return ConsecutiveElementsIterator(iterator: originSequence.makeIterator(), takeBy: takenElementsCount) } } struct ConsecutiveElementsIterator<OriginIterator: IteratorProtocol>: IteratorProtocol { typealias OriginElement = OriginIterator.Element typealias Element = [OriginElement] var previousElements: [OriginElement] = [] var originIterator: OriginIterator let takenElementsCount: Int init(iterator: OriginIterator, takeBy n: Int) { takenElementsCount = n originIterator = iterator while previousElements.count < takenElementsCount { if let nextElement = originIterator.next() { previousElements.append(nextElement) } else { break } } } mutating func next() -> Element? { guard previousElements.count == takenElementsCount else { return nil } let current = previousElements previousElements.removeFirst() if let newElement = originIterator.next() { previousElements.append(newElement) } return current } }
mit
4388fb11da0be3e38f14b74ae7f69443
33.43662
111
0.679755
4.822485
false
false
false
false
hetefe/MyNews
MyNews/MyNews/AppDelegate.swift
1
4790
// // AppDelegate.swift // MyNews // // Created by 赫腾飞 on 15/12/23. // Copyright © 2015年 hetefe. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { window = UIWindow(frame: UIScreen.mainScreen().bounds) window?.backgroundColor = UIColor.whiteColor() let leftVC = LeftViewController() let rightVC = RightViewController() let sideMenuViewController: RESideMenu = RESideMenu(contentViewController: MainTabBarController(), leftMenuViewController: leftVC, rightMenuViewController: rightVC) //设置背景的 sideMenuViewController.backgroundImage = UIImage(named: "wood") //设置side和mainView之间的阴影效果 sideMenuViewController.contentViewShadowColor = UIColor.blackColor() sideMenuViewController.contentViewShadowOffset = CGSizeMake(0, 0) sideMenuViewController.contentViewShadowOpacity = 0.6 sideMenuViewController.contentViewShadowRadius = 12 sideMenuViewController.contentViewShadowEnabled = true //在ContentView上滑动抽屉的效果控制 sideMenuViewController.bouncesHorizontally = true //是否缩放ContentView sideMenuViewController.scaleContentView = false // panFromEdge允许拖动界面边界执行 滑动抽屉效果 不仅限于按钮的动作 sideMenuViewController.panFromEdge = false //panGestureEnabled与panFromEdge的是对同一性能的不同设置 但是执行效果是完全不同的 sideMenuViewController.panGestureEnabled = true //背景图片的渐变效果 sideMenuViewController.fadeMenuView = true // 管理 以下 设置是否起作用 sideMenuViewController.parallaxEnabled = false //控制主视图在抽屉中左右分占比例 sideMenuViewController.parallaxContentMaximumRelativeValue = 100 sideMenuViewController.parallaxContentMinimumRelativeValue = 100 //TODO: 未知属性 sideMenuViewController.menuPrefersStatusBarHidden = false sideMenuViewController.menuPreferredStatusBarStyle = .LightContent //TODO: 未找到对应效果 //sideMenuViewController.parallaxMenuMinimumRelativeValue = 100 //sideMenuViewController.parallaxMenuMaximumRelativeValue = 100 //CGAffineTransform: menuViewControllerTransformation; //sideMenuViewController.menuViewControllerTransformation = CGAffineTransform(a: 100, b: 0, c: 0, d: 0, tx: 100, ty: 100) //TODO: 待处理 // sideMenuViewController.panMinimumOpenThreshold = 1 window?.rootViewController = sideMenuViewController//MainTabBarController() print(window?.frame) window?.makeKeyAndVisible() return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
9712418fb116c42de04330c671366b74
42.912621
285
0.718771
5.682161
false
false
false
false
cuzv/Popover
Sample/ArrowView.swift
1
4690
// // ArrowView.swift // PopoverSwift // // Created by Roy Shaw on 3/19/16. // Copyright © 2016 Red Rain. All rights reserved. // import UIKit extension Double { var radian: CGFloat { return CGFloat(self / 180.0 * Double.pi) } } let ArrawWidthHalf: CGFloat = 5 let ArrawHeight: CGFloat = 10 let ArrawCenterX: CGFloat = 50 let CornerRadius: CGFloat = 5 class ArrowView : UIView { override func draw(_ rect: CGRect) { layer.masksToBounds = true clipsToBounds = true let path = UIBezierPath() debugPrint(bounds.width) debugPrint(rect) path.move(to: CGPoint(x: ArrawCenterX, y: 0)) path.addLine(to: CGPoint(x: ArrawCenterX - ArrawWidthHalf, y: ArrawHeight)) path.addLine(to: CGPoint(x: CornerRadius + ArrawHeight, y: ArrawHeight)) path.addArc(withCenter: CGPoint(x: CornerRadius, y: CornerRadius + ArrawHeight), radius: CornerRadius, startAngle: 270.radian, endAngle: 180.radian, clockwise: false) path.addLine(to: CGPoint(x: 0, y: bounds.height - CornerRadius)) path.addArc(withCenter: CGPoint(x: CornerRadius, y: bounds.height - CornerRadius), radius: CornerRadius, startAngle: 180.radian, endAngle: 90.radian, clockwise: false) path.addLine(to: CGPoint(x: bounds.width - CornerRadius, y: bounds.height)) path.addArc(withCenter: CGPoint(x: bounds.width - CornerRadius, y: bounds.height - CornerRadius), radius: CornerRadius, startAngle: 90.radian, endAngle: 0.radian, clockwise: false) path.addLine(to: CGPoint(x: bounds.width, y: CornerRadius + ArrawHeight)) path.addArc(withCenter: CGPoint(x: bounds.width - CornerRadius, y: CornerRadius + ArrawHeight), radius: CornerRadius, startAngle: 0.radian, endAngle: -90.radian, clockwise: false) path.addLine(to: CGPoint(x: ArrawCenterX + ArrawWidthHalf, y: ArrawHeight)) path.close() UIColor.blue.setFill() path.fill() UIColor.red.setStroke() path.stroke() } } internal func drawArrawImageIn( _ rect: CGRect, strokeColor: UIColor, fillColor: UIColor = UIColor.clear, lineWidth: CGFloat = 1, arrawCenterX: CGFloat, arrawWidth: CGFloat = 5, arrawHeight: CGFloat = 10, cornerRadius: CGFloat = 6, handstand: Bool = false ) -> UIImage { UIGraphicsBeginImageContext(rect.size) let context = UIGraphicsGetCurrentContext() if handstand { context!.textMatrix = CGAffineTransform.identity context!.translateBy(x: 0, y: rect.height) context!.scaleBy(x: 1.0, y: -1.0) } // Perform the drawing context!.setLineWidth(lineWidth) context!.setStrokeColor(strokeColor.cgColor) context!.setFillColor(fillColor.cgColor) let path = CGMutablePath() let lineHalfWidth = lineWidth / 2.0 let arrawHalfWidth = arrawWidth / 2.0 path.move(to: CGPoint(x: arrawCenterX, y: lineWidth)) path.addLine(to: CGPoint(x: arrawCenterX - arrawHalfWidth, y: arrawHeight + lineWidth)) path.addLine(to: CGPoint(x: cornerRadius + arrawHeight, y: arrawHeight + lineWidth)) path.addArc(center: CGPoint(x:cornerRadius + lineHalfWidth, y:cornerRadius + arrawHeight + lineWidth), radius: cornerRadius, startAngle: 270.radian, endAngle: 180.radian, clockwise: true) path.addLine(to: CGPoint(x: lineHalfWidth, y: rect.height - cornerRadius - lineHalfWidth)) path.addArc(center: CGPoint(x:cornerRadius + lineHalfWidth, y:rect.height - cornerRadius - lineHalfWidth), radius: cornerRadius, startAngle: 180.radian, endAngle: 90.radian, clockwise: true) path.addLine(to: CGPoint(x: rect.width - cornerRadius - lineHalfWidth, y: rect.height - lineHalfWidth)) path.addArc(center: CGPoint(x:rect.width - cornerRadius - lineHalfWidth, y: rect.height - cornerRadius - lineHalfWidth), radius: cornerRadius, startAngle: 90.radian, endAngle: 0.radian, clockwise: true) path.addLine(to: CGPoint(x: rect.width - lineHalfWidth, y: arrawHeight + cornerRadius + lineWidth / 2)) path.addArc(center: CGPoint(x:rect.width - cornerRadius - lineHalfWidth, y:cornerRadius + arrawHeight + lineWidth), radius: cornerRadius, startAngle: 0.radian, endAngle: -90.radian, clockwise: true) path.addLine(to: CGPoint(x: arrawCenterX + arrawHalfWidth, y: arrawHeight + lineWidth)) path.closeSubpath() context!.addPath(path) context!.drawPath(using: .fillStroke) let output = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return output! }
mit
67b099f49d120b31a2b78bed82ee23cb
39.422414
207
0.676264
4.149558
false
false
false
false
fredrikcollden/LittleMaestro
Bird.swift
1
7021
// // Bird.swift // MaestroLevel // // Created by Fredrik Colldén on 2015-11-20. // Copyright © 2015 Marie. All rights reserved. // import SpriteKit class Bird: SKNode { let birdBody: SKSpriteNode let eyeLeft: SKSpriteNode let eyeRight: SKSpriteNode let pupilLeft: SKSpriteNode let pupilRight: SKSpriteNode let beakTop: SKSpriteNode let beakBottom: SKSpriteNode let footLeft: SKSpriteNode let footRight: SKSpriteNode let wingLeft: SKSpriteNode let wingRight: SKSpriteNode var eyeLeftPosition = CGPoint(x:-16, y:47) var eyeRightPosition = CGPoint(x:16, y:47) var pupilLeftPosition = CGPoint(x:-16, y:47) var pupilRightPosition = CGPoint(x:16, y:47) var beakTopPosition = CGPoint(x:0, y:30) var beakBottomPosition = CGPoint(x:0, y:32) var footLeftPosition = CGPoint(x:-10, y:-3) var footRightPosition = CGPoint(x:10, y:-3) var wingLeftPosition = CGPoint(x:-30, y:20) var wingRightPosition = CGPoint(x:30, y:20) var zOrigin:CGFloat var tintEffect:CGFloat = 0.5 //Animations let beakOpen:SKAction let beakClose:SKAction init(texture: SKTexture, zPos: CGFloat, tintColor: SKColor?=SKColor.clearColor()){ beakOpen = SKAction.scaleXBy(1.00, y: 1.8, duration: 0.2) beakClose = beakOpen.reversedAction() self.zOrigin = zPos birdBody = SKSpriteNode(texture: texture, color: tintColor!, size: texture.size()) eyeLeft = SKSpriteNode(imageNamed: "eye") eyeRight = SKSpriteNode(imageNamed: "eye") pupilLeft = SKSpriteNode(imageNamed: "pupil") pupilRight = SKSpriteNode(imageNamed: "pupil") beakTop = SKSpriteNode(imageNamed: "topbeak") beakBottom = SKSpriteNode(imageNamed: "bottombeak") footLeft = SKSpriteNode(imageNamed: "foot") footRight = SKSpriteNode(imageNamed: "foot") wingLeft = SKSpriteNode(imageNamed: "leftwing") wingRight = SKSpriteNode(imageNamed: "rightwing") super.init() eyeLeft.position = eyeLeftPosition eyeRight.position = eyeRightPosition pupilLeft.position = pupilLeftPosition pupilRight.position = pupilRightPosition beakTop.position = beakTopPosition beakBottom.position = beakBottomPosition footLeft.position = footLeftPosition footRight.position = footRightPosition wingLeft.position = wingLeftPosition wingRight.position = wingRightPosition birdBody.anchorPoint = CGPoint(x: 0.5, y: 0.0) beakBottom.anchorPoint = CGPoint(x: 0.5, y: 1.0) if (tintColor == SKColor.clearColor()) { tintEffect = 0 } else { tint(tintColor!) } setZPos(zPos) self.addChild(wingLeft) self.addChild(wingRight) self.addChild(birdBody) self.addChild(eyeLeft) self.addChild(eyeRight) self.addChild(pupilLeft) self.addChild(pupilRight) self.addChild(beakTop) self.addChild(beakBottom) self.addChild(footLeft) self.addChild(footRight) } func tint(color: SKColor){ birdBody.color = color birdBody.colorBlendFactor = tintEffect eyeLeft.color = color eyeLeft.colorBlendFactor = tintEffect eyeRight.color = color eyeRight.colorBlendFactor = tintEffect pupilLeft.color = color pupilLeft.colorBlendFactor = tintEffect pupilRight.color = color pupilRight.colorBlendFactor = tintEffect beakTop.color = color beakTop.colorBlendFactor = tintEffect beakBottom.color = color beakBottom.colorBlendFactor = tintEffect footLeft.color = color footLeft.colorBlendFactor = tintEffect footRight.color = color footRight.colorBlendFactor = tintEffect wingLeft.color = color wingLeft.colorBlendFactor = tintEffect wingRight.color = color wingRight.colorBlendFactor = tintEffect } func setZPos(zPos: CGFloat) { //print("zpos \(zPos)") self.zOrigin = zPos birdBody.zPosition = zPos + 2 eyeLeft.zPosition = zPos + 3 eyeRight.zPosition = zPos + 3 pupilLeft.zPosition = zPos + 4 pupilRight.zPosition = zPos + 4 beakTop.zPosition = zPos + 4 beakBottom.zPosition = zPos + 3 footLeft.zPosition = zPos + 3 footRight.zPosition = zPos + 3 wingLeft.zPosition = zPos + 1 wingRight.zPosition = zPos + 1 } func actionSing(time: NSTimeInterval){ let beakOpen = SKAction.scaleXBy(1.00, y: 1.8, duration: 0.2) let beakClose = beakOpen.reversedAction() beakBottom.runAction(SKAction.sequence([beakOpen, SKAction.waitForDuration(time), beakClose])) } func actionRun(count: Int){ actionRunStop() let footUp = SKAction.moveByX(0, y: -10, duration: 0.2) let footDown = footUp.reversedAction() footLeft.runAction(SKAction.repeatAction(SKAction.sequence([footUp, footDown]), count: count)) footRight.runAction(SKAction.sequence([SKAction.waitForDuration(0.1), SKAction.repeatAction(SKAction.sequence([footUp, footDown]), count: count)])) } func actionRunFor(time: Double){ actionRunStop() let count = 20 let duration = time/(Double(count*2)) let footUp = SKAction.moveByX(0, y: -10, duration: duration) let footDown = footUp.reversedAction() footLeft.runAction(SKAction.repeatAction(SKAction.sequence([footUp, footDown]), count: count)) footRight.runAction(SKAction.sequence([SKAction.waitForDuration(0.1), SKAction.repeatAction(SKAction.sequence([footUp, footDown]), count: count)])) } func actionRunStop() { footLeft.removeAllActions() footRight.removeAllActions() footLeft.position = footLeftPosition footRight.position = footRightPosition } func actionLookAt(from: CGPoint, to: CGPoint) { let xd = to.x-from.x let yd = to.y-from.y var xdn = CGFloat(0) var ydn = CGFloat(0) let normal = CGFloat(3) let magnitude = sqrt(xd*xd + yd*yd) if (magnitude != 0) { xdn = (xd/magnitude)*normal ydn = (yd/magnitude)*normal } pupilLeft.position.x = pupilLeftPosition.x + xdn pupilLeft.position.y = pupilLeftPosition.y + ydn pupilRight.position.x = pupilRightPosition.x + xdn pupilRight.position.y = pupilRightPosition.y + ydn } func actionLookAtStop() { pupilLeft.position = pupilLeftPosition pupilRight.position = pupilRightPosition } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
lgpl-3.0
73484c1fe1b1cfbb66e314e9f588f439
32.42381
155
0.631002
4.040875
false
false
false
false
pmhicks/Spindle-Player
Spindle Player/StringHelper.swift
1
2124
// Spindle Player // Copyright (C) 2015 Mike Hicks // // 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 //FUGLY hack func int8TupleToString<T>(tuple:T) -> String { let reflection = reflect(tuple) var arr:[UInt8] = [] for i in 0..<reflection.count { if let value = reflection[i].1.value as? Int8 { if value > 0 { arr.append(UInt8(value)) } } } if arr.count > 0 { //return String(bytes: arr, encoding: NSASCIIStringEncoding) ?? "" return String(bytes: arr, encoding: NSISOLatin1StringEncoding) ?? "" } return "" } func md5UInt8ToString<T>(tuple:T) -> String { let reflection = reflect(tuple) var arr:[String] = [] for i in 0..<reflection.count { if let value = reflection[i].1.value as? UInt8 { let hex = NSString(format:"%02x", value) as String //let hex = String(value, radix: 16, uppercase: false) arr.append(hex) } } if arr.count == 16 { return arr.reduce("") { $0 + $1 } } return "" }
mit
c9cf15ffb9aa2e77b1543846365170a6
33.819672
80
0.661488
4.108317
false
false
false
false
khizkhiz/swift
test/Sema/accessibility_multi.swift
2
1154
// RUN: %target-swift-frontend -parse -primary-file %s %S/Inputs/accessibility_multi_other.swift -verify func read(value: Int) {} func reset(value: inout Int) { value = 0 } func testGlobals() { read(privateSetGlobal) privateSetGlobal = 42 // expected-error {{cannot assign to value: 'privateSetGlobal' setter is inaccessible}} reset(&privateSetGlobal) // expected-error {{cannot pass immutable value as inout argument: 'privateSetGlobal' setter is inaccessible}} } func testProperties(instance: Members) { var instance = instance read(instance.privateSetProp) instance.privateSetProp = 42 // expected-error {{cannot assign to property: 'privateSetProp' setter is inaccessible}} reset(&instance.privateSetProp) // expected-error {{cannot pass immutable value as inout argument: 'privateSetProp' setter is inaccessible}} } func testSubscript(instance: Members) { var instance = instance read(instance[]) instance[] = 42 // expected-error {{cannot assign through subscript: subscript setter is inaccessible}} reset(&instance[]) // expected-error {{cannot pass immutable value as inout argument: subscript setter is inaccessible}} }
apache-2.0
9d58c5fe6e65bea95a235a4fc4eff5c5
49.173913
142
0.758232
4.354717
false
true
false
false
benjaminsnorris/CloudKitReactor
Sources/SubscribeToDatabase.swift
1
2732
/* | _ ____ ____ _ | | |‾| ⚈ |-| ⚈ |‾| | | | | ‾‾‾‾| |‾‾‾‾ | | | ‾ ‾ ‾ */ import Foundation import CloudKit import Reactor public struct SubscribeToDatabase<U: State>: Command { public var databaseScope: CKDatabase.Scope public var subscriptionID: String public var notificationInfo: CKSubscription.NotificationInfo public init(databaseScope: CKDatabase.Scope = .private, subscriptionID: String? = nil, notificationInfo: CKSubscription.NotificationInfo? = nil) { self.databaseScope = databaseScope if let subscriptionID = subscriptionID { self.subscriptionID = subscriptionID } else { self.subscriptionID = databaseScope == .private ? CloudKitReactorConstants.privateDatabaseSubscription : CloudKitReactorConstants.sharedDatabaseSubscription } if let notificationInfo = notificationInfo { self.notificationInfo = notificationInfo } else { let notificationInfo = CKSubscription.NotificationInfo() notificationInfo.shouldSendContentAvailable = true self.notificationInfo = notificationInfo } } public func execute(state: U, core: Core<U>) { let subscription = CKDatabaseSubscription(subscriptionID: subscriptionID) subscription.notificationInfo = notificationInfo let operation = CKModifySubscriptionsOperation(subscriptionsToSave: [subscription], subscriptionIDsToDelete: []) operation.qualityOfService = .utility operation.modifySubscriptionsCompletionBlock = { savedSubscriptions, _, error in if let error = error { core.fire(event: CloudKitSubscriptionError(error: error)) } else { let type: CloudKitSubscriptionType switch self.databaseScope { case .private: type = .privateDatabase case .shared: type = .sharedDatabase case .public: type = .publicDatabase @unknown default: fatalError() } core.fire(event: CloudKitSubscriptionSuccessful(type: type, subscriptionID: self.subscriptionID)) } } let container = CKContainer.default() switch databaseScope { case .private: container.privateCloudDatabase.add(operation) case .shared: container.sharedCloudDatabase.add(operation) case .public: container.publicCloudDatabase.add(operation) @unknown default: fatalError() } } }
mit
a7d9b7432b1bb2784b7709980c1d2bc3
37.056338
168
0.609548
5.700422
false
false
false
false
kunsy/DYZB
DYZB/DYZB/Classes/Main/View/PageContentView.swift
1
5426
// // PageContentView.swift // DYZB // // Created by Anyuting on 2017/8/6. // Copyright © 2017年 Anyuting. All rights reserved. // import UIKit protocol PageContentViewDelegate : class { func pageContentView(contentView : PageContentView, progress : CGFloat, sourceIndex : Int, targetIndex : Int) } private let ContentCellID = "ContentCellID" class PageContentView: UIView { //定义属性 fileprivate var childVcs : [UIViewController] fileprivate weak var parentViewController : UIViewController? fileprivate var startOffsetX :CGFloat = 0 weak var delegate : PageContentViewDelegate? fileprivate var isForbidScrollDelegate = false //懒加载属性 fileprivate lazy var collectionView : UICollectionView = { [weak self] in //layout let layout = UICollectionViewFlowLayout() layout.itemSize = (self?.bounds.size)! layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.scrollDirection = .horizontal //Create uicollectionView let collectionView : UICollectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout) collectionView.showsHorizontalScrollIndicator = false collectionView.isPagingEnabled = true collectionView.bounces = false collectionView.dataSource = self! collectionView.delegate = self! //监听代理 collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: ContentCellID) return collectionView }() //自定义构造函数 init(frame: CGRect, childVcs: [UIViewController], parentViewController : UIViewController?) { self.childVcs = childVcs self.parentViewController = parentViewController super.init(frame : frame) //设置UI界面 setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } //设置UI界面 extension PageContentView { fileprivate func setupUI(){ //1.将子控制器放入父控制器中 for childVc in childVcs { parentViewController?.addChildViewController(childVc) } //2.添加collectionView addSubview(collectionView) collectionView.frame = bounds } } //遵守CollecionViewDatasource extension PageContentView : UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return childVcs.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { //1.Create Cell let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ContentCellID, for: indexPath) //2.Add content for view in cell.contentView.subviews{ view.removeFromSuperview() } let childVc = childVcs[indexPath.item] childVc.view.frame = cell.contentView.bounds cell.contentView.addSubview(childVc.view) return cell } } //遵守UICollectionViewDelegate代理 extension PageContentView : UICollectionViewDelegate { func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { isForbidScrollDelegate = false startOffsetX = scrollView.contentOffset.x } func scrollViewDidScroll(_ scrollView: UIScrollView) { //print(".......") // 判断是否是点击事件 if isForbidScrollDelegate { return } //滚动发生的变化 var progress : CGFloat = 0 var sourceIndex : Int = 0 var targetIndex : Int = 0 //判断滑动方向 let currentOffsetX = scrollView.contentOffset.x let scrollViewW = scrollView.bounds.width if currentOffsetX > startOffsetX {//left move progress = currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW) sourceIndex = Int(currentOffsetX / scrollViewW) targetIndex = sourceIndex + 1 if targetIndex >= childVcs.count { targetIndex = childVcs.count - 1 } //如果完全滑过去 if currentOffsetX - startOffsetX == scrollViewW { progress = 1 targetIndex = sourceIndex } } else {//right move progress = 1 - (currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW)) targetIndex = Int(currentOffsetX / scrollViewW) sourceIndex = targetIndex + 1 if sourceIndex >= childVcs.count { sourceIndex = childVcs.count - 1 } } //action //print("progress: \(progress) source: \(sourceIndex) target: \(targetIndex)") delegate?.pageContentView(contentView: self, progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex) } } //对外暴露的方法 extension PageContentView { func setCurrentIndex(currentIndex : Int) { //记录需要禁止执行代理方法 isForbidScrollDelegate = true let offsetX = CGFloat(currentIndex) * collectionView.frame.width collectionView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: false) } }
mit
bd1e7cd09c2c199807e86b26b2e362c8
32.107595
124
0.645192
5.844693
false
false
false
false
alenalen/DYZB
DYZB/DYZB/Classes/Main/View/PageContentView.swift
1
5505
// // PageContentView.swift // DYZB // // Created by Alen on 2017/7/21. // Copyright © 2017年 JingKeCompany. All rights reserved. // import UIKit protocol PageContentViewDelegate:class { func pageContentView(contentView: PageContentView, progress: CGFloat, sourceIndex: Int, targetIndex: Int) } private let ContentCellID = "contentCellID" class PageContentView: UIView { //定义属性 fileprivate var startOffsetX : CGFloat = 0 fileprivate var childVcs : [UIViewController] fileprivate weak var parentViewController : UIViewController? weak var delegate: PageContentViewDelegate? fileprivate var isForbidScorllDelegate : Bool = false //MARK:-懒加载 lazy var collectionView: UICollectionView = { [weak self] in //1创建Layout let layout = UICollectionViewFlowLayout() layout.itemSize = (self?.bounds.size)! layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.scrollDirection = .horizontal //2创建collectionView let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout) collectionView.showsHorizontalScrollIndicator = false collectionView.isPagingEnabled = true collectionView.bounces = false collectionView.dataSource = self collectionView.delegate = self collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: ContentCellID) return collectionView }() //自定义构造函数 init(frame: CGRect,childVcs: [UIViewController],parentViewController: UIViewController?) { self.childVcs = childVcs self.parentViewController = parentViewController super.init(frame: frame) //设置UI setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } //MARK:-设置UI界面 extension PageContentView{ fileprivate func setupUI(){ //1将所有的子控制器添加到父控制器 for childVc in childVcs { parentViewController?.addChildViewController(childVc) } //2布局界面 (uicollectionView) addSubview(collectionView) collectionView.frame = bounds } } //MARK:-遵守UICollectionViewDataSource协议 extension PageContentView:UICollectionViewDataSource{ func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return childVcs.count } func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ContentCellID, for: indexPath) for view in cell.contentView.subviews { view.removeFromSuperview() } let childVc = childVcs[indexPath.item] childVc.view.frame = cell.contentView.bounds cell.contentView.addSubview(childVc.view) return cell } } //MARK:-遵守UICollectionViewDelegate协议 extension PageContentView:UICollectionViewDelegate{ func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { isForbidScorllDelegate = false startOffsetX = scrollView.contentOffset.x } func scrollViewDidScroll(_ scrollView: UIScrollView) { if isForbidScorllDelegate { return } var progress : CGFloat = 0 var sourceIndex : Int = 0 var targentIndex : Int = 0 let scrollViewW = scrollView.frame.width let currentOffsetX = scrollView.contentOffset.x if currentOffsetX > startOffsetX { //左滑 progress = currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW) sourceIndex = Int(currentOffsetX/scrollViewW) targentIndex = sourceIndex + 1; if targentIndex>=childVcs.count { targentIndex = childVcs.count - 1 } if currentOffsetX - startOffsetX == scrollViewW { progress = 1 targentIndex = sourceIndex } }else{ //右滑 progress = 1 - (currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW)) targentIndex = Int(currentOffsetX/scrollViewW) sourceIndex = targentIndex + 1; if sourceIndex>=childVcs.count { sourceIndex = childVcs.count - 1 } if startOffsetX - currentOffsetX == scrollViewW { progress = 1 sourceIndex = targentIndex } } // 传递给titleView //print(progress,sourceIndex,targentIndex) delegate?.pageContentView(contentView: self, progress: progress, sourceIndex: sourceIndex, targetIndex: targentIndex) } } //MARK:-对外暴露的方法 extension PageContentView{ func setCurrentView(currentIndex : Int) { print(#function) isForbidScorllDelegate = true let offsetX = CGFloat(currentIndex) * collectionView.frame.width collectionView.setContentOffset(CGPoint(x: offsetX, y:0), animated: true) } }
mit
9801fda0eaedadd0786cd63bdec98e57
29.674286
125
0.639531
5.70457
false
false
false
false
brodie20j/Reunion-iOS
NSW/ICSParser.swift
1
2879
// // ICSParser.swift // Carleton Reunion // // Created by Grant Terrien on 5/22/15. // Copyright (c) 2015 BTIN. All rights reserved. // // Creates NSWEvent objects for use by NewEventDataSource. // Uses modified MXLCalendar library by Kiran Panesar to parse iCalendar files // https://github.com/KiranPanesar/MXLCalendarManager import Foundation @objc class ICSParser: NSObject { var documentsUrl: NSURL? init(eventDataSource: NewEventDataSource) { super.init() let reunionScheduleUrlString = "https://apps.carleton.edu/reunion/schedule/?start_date=2015-06-07&format=ical" documentsUrl = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first as! NSURL downloadScheduleSynchronously() let path = documentsUrl!.URLByAppendingPathComponent("schedule.ics").pat var err : NSError? var content = String(contentsOfFile: path!, encoding: NSUTF8StringEncoding, error: &err) var calendarManager = MXLCalendarManager() // This is asynchronous. Would have to rewrite much of third party library to not use // callback functions. calendarManager.parseICSString(content, withCompletionHandler: { (calendar: MXLCalendar!, error: NSError!) -> Void in var events = calendar.events var nswEvents = NSMutableArray() for event in events { var theEvent = event as! MXLCalendarEvent var newEvent = NSWEvent(ID: theEvent.eventUniqueID, title: theEvent.eventSummary, description: theEvent.eventDescription, location: theEvent.eventLocation, start: theEvent.eventStartDate, duration: event.eventDuration) nswEvents.addObject(newEvent) } eventDataSource.populateEventList(nswEvents) }) } func downloadScheduleSynchronously() { if let scheduleUrl = NSURL(string: "https://apps.carleton.edu/reunion/schedule/?start_date=2015-06-07&format=ical") { if let scheduleDataFromUrl = NSData(contentsOfURL: scheduleUrl){ // after downloading your data you need to save it to your destination url let destinationUrl = documentsUrl!.URLByAppendingPathComponent("schedule.ics") if scheduleDataFromUrl.writeToURL(destinationUrl, atomically: true) { println("file saved at \(destinationUrl)") } else { println("error saving file") } return } println("Can't download file. Check your internet connection.") } else { println("error") } } }
mit
8f7b173cfb8e16c5dcd0bfe2199e1f72
36.38961
234
0.61827
5.10461
false
false
false
false
danielgindi/Charts
Source/Charts/Renderers/YAxisRendererRadarChart.swift
2
7017
// // YAxisRendererRadarChart.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics open class YAxisRendererRadarChart: YAxisRenderer { private weak var chart: RadarChartView? @objc public init(viewPortHandler: ViewPortHandler, axis: YAxis, chart: RadarChartView) { self.chart = chart super.init(viewPortHandler: viewPortHandler, axis: axis, transformer: nil) } open override func computeAxisValues(min yMin: Double, max yMax: Double) { let labelCount = axis.labelCount let range = abs(yMax - yMin) guard labelCount != 0, range > 0, range.isFinite else { axis.entries = [] axis.centeredEntries = [] return } // Find out how much spacing (in yValue space) between axis values let rawInterval = range / Double(labelCount) var interval = rawInterval.roundedToNextSignificant() // If granularity is enabled, then do not allow the interval to go below specified granularity. // This is used to avoid repeated values when rounding values for display. if axis.isGranularityEnabled { interval = max(interval, axis.granularity) } // Normalize interval let intervalMagnitude = pow(10.0, floor(log10(interval))).roundedToNextSignificant() let intervalSigDigit = Int(interval / intervalMagnitude) if intervalSigDigit > 5 { // Use one order of magnitude higher, to avoid intervals like 0.9 or 90 // if it's 0.0 after floor(), we use the old value interval = floor(10.0 * intervalMagnitude) == 0.0 ? interval : floor(10.0 * intervalMagnitude) } let centeringEnabled = axis.isCenterAxisLabelsEnabled var n = centeringEnabled ? 1 : 0 // force label count if axis.isForceLabelsEnabled { let step = range / Double(labelCount - 1) // Ensure stops contains at least n elements. axis.entries.removeAll(keepingCapacity: true) axis.entries.reserveCapacity(labelCount) let values = stride(from: yMin, to: Double(labelCount) * step + yMin, by: step) axis.entries.append(contentsOf: values) n = labelCount } else { // no forced count var first = interval == 0.0 ? 0.0 : ceil(yMin / interval) * interval if centeringEnabled { first -= interval } let last = interval == 0.0 ? 0.0 : (floor(yMax / interval) * interval).nextUp if interval != 0.0 { stride(from: first, through: last, by: interval).forEach { _ in n += 1 } } n += 1 // Ensure stops contains at least n elements. axis.entries.removeAll(keepingCapacity: true) axis.entries.reserveCapacity(labelCount) // Fix for IEEE negative zero case (Where value == -0.0, and 0.0 == -0.0) let values = stride(from: first, to: Double(n) * interval + first, by: interval).map { $0 == 0.0 ? 0.0 : $0 } axis.entries.append(contentsOf: values) } // set decimals if interval < 1 { axis.decimals = Int(ceil(-log10(interval))) } else { axis.decimals = 0 } if centeringEnabled { let offset = (axis.entries[1] - axis.entries[0]) / 2.0 axis.centeredEntries = axis.entries.map { $0 + offset } } axis._axisMinimum = axis.entries.first! axis._axisMaximum = axis.entries.last! axis.axisRange = abs(axis._axisMaximum - axis._axisMinimum) } open override func renderAxisLabels(context: CGContext) { guard let chart = chart, axis.isEnabled, axis.isDrawLabelsEnabled else { return } let labelFont = axis.labelFont let labelTextColor = axis.labelTextColor let center = chart.centerOffsets let factor = chart.factor let labelLineHeight = axis.labelFont.lineHeight let from = axis.isDrawBottomYLabelEntryEnabled ? 0 : 1 let to = axis.isDrawTopYLabelEntryEnabled ? axis.entryCount : (axis.entryCount - 1) let alignment = axis.labelAlignment let xOffset = axis.labelXOffset let entries = axis.entries[from..<to] entries.indexed().forEach { index, entry in let r = CGFloat(entry - axis._axisMinimum) * factor let p = center.moving(distance: r, atAngle: chart.rotationAngle) let label = axis.getFormattedLabel(index) context.drawText( label, at: CGPoint(x: p.x + xOffset, y: p.y - labelLineHeight), align: alignment, attributes: [.font: labelFont, .foregroundColor: labelTextColor] ) } } open override func renderLimitLines(context: CGContext) { guard let chart = chart, let data = chart.data else { return } let limitLines = axis.limitLines guard !limitLines.isEmpty else { return } context.saveGState() defer { context.restoreGState() } let sliceangle = chart.sliceAngle // calculate the factor that is needed for transforming the value to pixels let factor = chart.factor let center = chart.centerOffsets for l in limitLines where l.isEnabled { context.setStrokeColor(l.lineColor.cgColor) context.setLineWidth(l.lineWidth) if l.lineDashLengths != nil { context.setLineDash(phase: l.lineDashPhase, lengths: l.lineDashLengths!) } else { context.setLineDash(phase: 0.0, lengths: []) } let r = CGFloat(l.limit - chart.chartYMin) * factor context.beginPath() for i in 0 ..< (data.maxEntryCountSet?.entryCount ?? 0) { let p = center.moving( distance: r, atAngle: sliceangle * CGFloat(i) + chart.rotationAngle ) i == 0 ? context.move(to: p) : context.addLine(to: p) } context.closePath() context.strokePath() } } }
apache-2.0
d47effc9cc1724af7da5099d7ddafef8
30.895455
121
0.54254
5.095861
false
false
false
false
suragch/Chimee-iOS
Chimee/FavoriteViewController.swift
1
6693
import UIKit class FavoriteViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var mongolTableView: UIMongolTableView! weak var delegate: MenuDelegate? = nil let renderer = MongolUnicodeRenderer.sharedInstance let mongolFont = "ChimeeWhiteMirrored" let fontSize: CGFloat = 24 // passed in from main view controller var currentMessage = "" // Array of strings to display in table view cells var messages: [Message]? override func viewDidLoad() { super.viewDidLoad() // setup the table view from the IB reference mongolTableView.delegate = self mongolTableView.dataSource = self self.mongolTableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell") self.mongolTableView.tableFooterView = UIView() self.automaticallyAdjustsScrollViewInsets = false // load the favorites from the database loadFavorites() } func loadFavorites() { let qualityOfServiceClass = DispatchQoS.QoSClass.background let backgroundQueue = DispatchQueue.global(qos: qualityOfServiceClass) backgroundQueue.async(execute: { // lookup words in user dictionary that start with word before cursor var favoritesList: [Message]? do { favoritesList = try FavoriteDataHelper.findAll() } catch _ { print("query for favorites failed") } // update TableView with favorite messages DispatchQueue.main.async(execute: { () -> Void in self.messages = favoritesList self.mongolTableView?.reloadData() }) }) } // MARK: - Actions @IBAction func addFavoriteButtonTapped(_ sender: UIBarButtonItem) { guard currentMessage.characters.count > 0 else { // TODO: notify user that they have to write sth return } // add message to database addFavoriteMessageToDatabase(currentMessage) } @IBAction func historyButtonTapped(_ sender: UIBarButtonItem) { } // MARK: - UITableView func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.messages?.count ?? 0; } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // set up the cells for the table view let cell: UITableViewCell = self.mongolTableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell! // TODO: use a custom UIMongolTableViewCell to render and choose font cell.layoutMargins = UIEdgeInsets.zero if let text = self.messages?[indexPath.row].messageText { cell.textLabel?.text = renderer.unicodeToGlyphs(text) cell.textLabel?.font = UIFont(name: mongolFont, size: fontSize) } return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if let text = messages?[indexPath.row].messageText { self.delegate?.insertMessage(text) updateTimeForFavoriteMessage(text) } _ = self.navigationController?.popViewController(animated: true) } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { if let message = messages?[indexPath.row] { deleteFavoriteMessageFromDatabase(message, indexPath: indexPath) } } } func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? { return "|" } // MARK: - Database func addFavoriteMessageToDatabase(_ message: String) { guard message.characters.count > 0 else { return } // do on background thread let qualityOfServiceClass = DispatchQoS.QoSClass.background let backgroundQueue = DispatchQueue.global(qos: qualityOfServiceClass) backgroundQueue.async(execute: { do { _ = try FavoriteDataHelper.insertMessage(message) self.messages = try FavoriteDataHelper.findAll() } catch _ { print("message update failed") } // update TableView with favorite messages DispatchQueue.main.async(execute: { () -> Void in // insert row in table let indexPath = IndexPath(row: 0, section: 0) self.mongolTableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.fade) }) }) } func deleteFavoriteMessageFromDatabase(_ item: Message, indexPath: IndexPath) { // do on background thread let qualityOfServiceClass = DispatchQoS.QoSClass.background let backgroundQueue = DispatchQueue.global(qos: qualityOfServiceClass) backgroundQueue.async(execute: { do { try FavoriteDataHelper.delete(item) self.messages = try FavoriteDataHelper.findAll() } catch _ { print("message update failed") } // update TableView with favorite messages DispatchQueue.main.async(execute: { () -> Void in self.mongolTableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .fade) }) }) } func updateTimeForFavoriteMessage(_ messageText: String) { // do on background thread let qualityOfServiceClass = DispatchQoS.QoSClass.background let backgroundQueue = DispatchQueue.global(qos: qualityOfServiceClass) backgroundQueue.async(execute: { do { try FavoriteDataHelper.updateTimeForFavorite(messageText) } catch _ { print("message update failed") } }) } }
mit
322465aa9021053c2917013a00d03412
30.570755
127
0.57224
6.129121
false
false
false
false
Tomikes/eidolon
Kiosk/Auction Listings/WebViewController.swift
7
1966
import DZNWebViewController let modalHeight: CGFloat = 660 class WebViewController: DZNWebViewController { var showToolbar = true convenience init(url: NSURL) { self.init() self.URL = url } override func viewDidLoad() { super.viewDidLoad() let webView = view as! UIWebView webView.scalesPageToFit = true self.navigationItem.rightBarButtonItem = nil } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) navigationController?.setNavigationBarHidden(true, animated:false) navigationController?.setToolbarHidden(!showToolbar, animated:false) } } class ModalWebViewController: WebViewController { var closeButton: UIButton! override func viewDidLoad() { super.viewDidLoad() closeButton = UIButton() view.addSubview(closeButton) closeButton.titleLabel?.font = UIFont.sansSerifFontWithSize(14) closeButton.setTitleColor(.artsyMediumGrey(), forState:.Normal) closeButton.setTitle("CLOSE", forState:.Normal) closeButton.constrainWidth("140", height: "72") closeButton.alignTop("0", leading:"0", bottom:nil, trailing:nil, toView:view) closeButton.addTarget(self, action:"closeTapped:", forControlEvents:.TouchUpInside) var height = modalHeight if let nav = navigationController { if !nav.navigationBarHidden { height -= CGRectGetHeight(nav.navigationBar.frame) } if !nav.toolbarHidden { height -= CGRectGetHeight(nav.toolbar.frame) } } preferredContentSize = CGSizeMake(815, height) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) navigationController?.view.superview?.layer.cornerRadius = 0; } func closeTapped(sender: AnyObject) { presentingViewController?.dismissViewControllerAnimated(true, completion:nil) } }
mit
2655b81e76248dad3bdb4fd0b97bab45
31.229508
94
0.68413
5.313514
false
false
false
false
nikita-leonov/boss-client
BoSS/Services/CategoriesService.swift
1
1134
// // CategoriesService.swift // BoSS // // Created by Emanuele Rudel on 28/02/15. // Copyright (c) 2015 Bureau of Street Services. All rights reserved. // import Foundation private let categoriesDictionary: [String: String] = [ "POTHOLE" : "Pothole", "DEBRIS" : "Debris on Road", "DAMAGED_SIDEWALK" : "Damaged Sidewalk", "STREET_SWEEPING" : "Street Cleaning", "BROKEN_STREETLIGHTS" : "Broken Streetlight", ] class CategoriesService: CategoriesServiceProtocol { internal class func category(forIdentifier identifier: String) -> Category? { var result: Category? if let name = categoriesDictionary[identifier] { result = Category(name: name, identifier: identifier) } return result } private lazy var fixedCategories: [Category] = { var result = [Category]() for (id, name) in categoriesDictionary { result.append(Category(name: name, identifier: id)) } return result }() func categories() -> [Category] { return fixedCategories } }
mit
176bba1e5f775c21086b09c240867403
24.222222
81
0.609347
4.035587
false
false
false
false
calebkleveter/UIWebKit
Sources/UIWebKit/Components/UILink.swift
1
3020
// The MIT License (MIT) // // Copyright (c) 2017 Caleb Kleveter // // 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. /// `CSSLink` represents a link to a CSS file from the HTML file that is rendered. open class CSSLink { /// The `UILink` used to link to the CSS file. public let link: UILink /// Creates a link to a CSS file from the rendered HTML file. /// /// - Parameter href: The path to the CSS file. This parameter defaults `"css/main.css"` public init(href: String = "css/main.css") { self.link = UILink(href: href, rel: "stylesheet") } } extension CSSLink: ElementRenderable { /// The `link` element contained in the `CSSLink`'s `UILink`. public var topLevelElement: UIElement { return link.link } } /// A wrapper class for a `UIElement` that represents a `link` element. open class UILink { /// The `link` element that the class represents. public let link: UIElement = UIElement(element: .link) /// The `rel` attribute for the `link` tag. public var rel: String = "" { didSet { link.attributes["rel"] = rel } } /// The `href` attribute for the `link` tag. public var href: String = "" { didSet { link.attributes["href"] = href } } /// Creates a instance of `UILink` with an `href` and `rel` properties. /// /// - Parameters: /// - href: The path the the document being linked to. /// - rel: The relationship between the linked document to the current document. View the HTML [documention](http://devdocs.io/html/element/link) for more details. public init(href: String, rel: String) { self.href = href self.rel = rel } } extension UILink: ElementRenderable { /// The `link` tag represented by a `UIElement` object that is controlled by an instance `UILink`. public var topLevelElement: UIElement { return link } }
mit
3fd05d7d124496bfb1dad289753c6062
35.829268
169
0.66457
4.148352
false
false
false
false
alex-alex/S2Geometry
Tests/S2GeometryTests/S2CapTests.swift
1
10416
// // S2CapTests.swift // S2Geometry // // Created by Alex Studnicka on 7/30/16. // Copyright © 2016 Alex Studnicka. MIT License. // #if os(Linux) import Glibc #else import Darwin.C #endif import XCTest @testable import S2Geometry class S2CapTests: XCTestCase { static let eps = 1e-15 func testBasic() { // Test basic properties of empty and full caps. let empty = S2Cap.empty let full = S2Cap.full XCTAssert(empty.isValid) XCTAssert(empty.isEmpty) XCTAssert(empty.complement.isFull) XCTAssert(full.isValid) XCTAssert(full.isFull) XCTAssert(full.complement.isEmpty) XCTAssertEqual(full.height, 2.0) XCTAssertEqualWithAccuracy(full.angle.degrees, 180, accuracy: 1e-9) // Containment and intersection of empty and full caps. XCTAssert(empty.contains(other: empty)) XCTAssert(full.contains(other: empty)) XCTAssert(full.contains(other: full)) XCTAssert(!empty.interiorIntersects(with: empty)) XCTAssert(full.interiorIntersects(with: full)) XCTAssert(!full.interiorIntersects(with: empty)) // Singleton cap containing the x-axis. let xaxis = S2Cap(axis: S2Point(x: 1, y: 0, z: 0), height: 0) XCTAssert(xaxis.contains(point: S2Point(x: 1, y: 0, z: 0))) XCTAssert(!xaxis.contains(point: S2Point(x: 1, y: 1e-20, z: 0))) XCTAssertEqual(xaxis.angle.radians, 0.0) // Singleton cap containing the y-axis. let yaxis = S2Cap(axis: S2Point(x: 0, y: 1, z: 0), angle: S1Angle(radians: 0)) XCTAssert(!yaxis.contains(point: xaxis.axis)) XCTAssertEqual(xaxis.height, 0.0) // Check that the complement of a singleton cap is the full cap. let xcomp = xaxis.complement XCTAssert(xcomp.isValid) XCTAssert(xcomp.isFull) XCTAssert(xcomp.contains(point: xaxis.axis)) // Check that the complement of the complement is *not* the original. XCTAssert(xcomp.complement.isValid) XCTAssert(xcomp.complement.isEmpty) XCTAssert(!xcomp.complement.contains(point: xaxis.axis)) // Check that very small caps can be represented accurately. // Here "kTinyRad" is small enough that unit vectors perturbed by this // amount along a tangent do not need to be renormalized. let kTinyRad = 1e-10 let tiny = S2Cap(axis: S2Point.normalize(point: S2Point(x: 1, y: 2, z: 3)), angle: S1Angle(radians: kTinyRad)) let tangent = S2Point.normalize(point: tiny.axis.crossProd(S2Point(x: 3, y: 2, z: 1))) XCTAssert(tiny.contains(point: tiny.axis + tangent * (0.99 * kTinyRad))) XCTAssert(!tiny.contains(point: tiny.axis + tangent * (1.01 * kTinyRad))) // Basic tests on a hemispherical cap. let hemi = S2Cap(axis: S2Point.normalize(point: S2Point(x: 1, y: 0, z: 1)), height: 1) XCTAssertEqual(hemi.complement.axis, -hemi.axis) XCTAssertEqual(hemi.complement.height, 1.0) XCTAssert(hemi.contains(point: S2Point(x: 1, y: 0, z: 0))) XCTAssert(!hemi.complement.contains(point: S2Point(x: 1, y: 0, z: 0))) XCTAssert(hemi.contains(point: S2Point.normalize(point: S2Point(x: 1, y: 0, z: -(1 - S2CapTests.eps))))) XCTAssert(!hemi.interiorContains(point: S2Point.normalize(point: S2Point(x: 1, y: 0, z: -(1 + S2CapTests.eps))))) // A concave cap. let concave = S2Cap(axis: S2Point(latDegrees: 80, lngDegrees: 10), angle: S1Angle(degrees: 150)); XCTAssert(concave.contains(point: S2Point(latDegrees: -70 * (1 - S2CapTests.eps), lngDegrees: 10))) XCTAssert(!concave.contains(point: S2Point(latDegrees: -70 * (1 + S2CapTests.eps), lngDegrees: 10))) XCTAssert(concave.contains(point: S2Point(latDegrees: -50 * (1 - S2CapTests.eps), lngDegrees: -170))) // FIXME: Wrong result // XCTAssert(!concave.contains(point: S2Point(latDegrees: -50 * (1 + S2CapTests.eps), lngDegrees: -170))) // Cap containment tests. XCTAssert(!empty.contains(other: xaxis)) XCTAssert(!empty.interiorIntersects(with: xaxis)) XCTAssert(full.contains(other: xaxis)) XCTAssert(full.interiorIntersects(with: xaxis)) XCTAssert(!xaxis.contains(other: full)) XCTAssert(!xaxis.interiorIntersects(with: full)) XCTAssert(xaxis.contains(other: xaxis)) XCTAssert(!xaxis.interiorIntersects(with: xaxis)) XCTAssert(xaxis.contains(other: empty)) XCTAssert(!xaxis.interiorIntersects(with: empty)) XCTAssert(hemi.contains(other: tiny)) XCTAssert(hemi.contains(other: S2Cap(axis: S2Point(x: 1, y: 0, z: 0), angle: S1Angle(radians: M_PI_4 - S2CapTests.eps)))) XCTAssert(!hemi.contains(other: S2Cap(axis: S2Point(x: 1, y: 0, z: 0), angle: S1Angle(radians: M_PI_4 + S2CapTests.eps)))) XCTAssert(concave.contains(other: hemi)) XCTAssert(concave.interiorIntersects(with: hemi.complement)) XCTAssert(!concave.contains(other: S2Cap(axis: -concave.axis, height: 0.1))) } public func testRectBound() { // Empty and full caps. XCTAssert(S2Cap.empty.rectBound.isEmpty) XCTAssert(S2Cap.full.rectBound.isFull) let degreeEps = 1e-13 // Maximum allowable error for latitudes and longitudes measured in // degrees. (assertDoubleNear uses a fixed tolerance that is too small.) // Cap that includes the south pole. var rect = S2Cap(axis: S2Point(latDegrees: -45, lngDegrees: 57), angle: S1Angle(degrees: 50)).rectBound XCTAssertEqualWithAccuracy(rect.latLo.degrees, -90, accuracy: degreeEps) XCTAssertEqualWithAccuracy(rect.latHi.degrees, 5, accuracy: degreeEps) XCTAssert(rect.lng.isFull) // Cap that is tangent to the north pole. rect = S2Cap(axis: S2Point.normalize(point: S2Point(x: 1, y: 0, z: 1)), angle: S1Angle(radians: M_PI_4)).rectBound XCTAssertEqualWithAccuracy(rect.lat.lo, 0, accuracy: 1e-9); XCTAssertEqualWithAccuracy(rect.lat.hi, M_PI_2, accuracy: 1e-9); XCTAssert(rect.lng.isFull) rect = S2Cap(axis: S2Point.normalize(point: S2Point(x: 1, y: 0, z: 1)), angle: S1Angle(degrees: 45)).rectBound XCTAssertEqualWithAccuracy(rect.latLo.degrees, 0, accuracy: degreeEps) XCTAssertEqualWithAccuracy(rect.latHi.degrees, 90, accuracy: degreeEps) XCTAssert(rect.lng.isFull) // The eastern hemisphere. rect = S2Cap(axis: S2Point(x: 0, y: 1, z: 0), angle: S1Angle(radians: M_PI_2 + 5e-16)).rectBound XCTAssertEqualWithAccuracy(rect.latLo.degrees, -90, accuracy: degreeEps) XCTAssertEqualWithAccuracy(rect.latHi.degrees, 90, accuracy: degreeEps) XCTAssert(rect.lng.isFull) // A cap centered on the equator. rect = S2Cap(axis: S2Point(latDegrees: 0, lngDegrees: 50), angle: S1Angle(degrees: 20)).rectBound XCTAssertEqualWithAccuracy(rect.latLo.degrees, -20, accuracy: degreeEps) XCTAssertEqualWithAccuracy(rect.latHi.degrees, 20, accuracy: degreeEps) XCTAssertEqualWithAccuracy(rect.lngLo.degrees, 30, accuracy: degreeEps) XCTAssertEqualWithAccuracy(rect.lngHi.degrees, 70, accuracy: degreeEps) // A cap centered on the north pole. rect = S2Cap(axis: S2Point(latDegrees: 90, lngDegrees: 123), angle: S1Angle(degrees: 10)).rectBound XCTAssertEqualWithAccuracy(rect.latLo.degrees, 80, accuracy: degreeEps) XCTAssertEqualWithAccuracy(rect.latHi.degrees, 90, accuracy: degreeEps) XCTAssert(rect.lng.isFull) } public func testCells() { // For each cube face, we construct some cells on // that face and some caps whose positions are relative to that face, // and then check for the expected intersection/containment results. // The distance from the center of a face to one of its vertices. let faceRadius = atan(M_SQRT2) for face in 0 ..< 6 { // The cell consisting of the entire face. let rootCell = S2Cell(face: face, pos: 0, level: 0) // A leaf cell at the midpoint of the v=1 edge. let edgeCell = S2Cell(point: S2Projections.faceUvToXyz(face: face, u: 0, v: 1 - S2CapTests.eps)) // A leaf cell at the u=1, v=1 corner. let cornerCell = S2Cell(point: S2Projections.faceUvToXyz(face: face, u: 1 - S2CapTests.eps, v: 1 - S2CapTests.eps)) // Quick check for full and empty caps. XCTAssert(S2Cap.full.contains(cell: rootCell)) XCTAssert(!S2Cap.empty.mayIntersect(cell: rootCell)) // Check intersections with the bounding caps of the leaf cells that are // adjacent to 'corner_cell' along the Hilbert curve. Because this corner // is at (u=1,v=1), the curve stays locally within the same cube face. let first = cornerCell.cellId.prev().prev().prev() let last = cornerCell.cellId.next().next().next().next() var id = first while id < last { // FIXME: Wrong result // let cell = S2Cell(cellId: id) // XCTAssertEqual(cell.capBound.contains(cell: cornerCell), id == cornerCell.cellId) // XCTAssertEqual(cell.capBound.mayIntersect(cell: cornerCell), id.parent.contains(other: cornerCell.cellId)) id = id.next() } let antiFace = (face + 3) % 6 // Opposite face. for capFace in 0 ..< 6 { // A cap that barely contains all of 'cap_face'. let center = S2Projections.getNorm(face: capFace) let covering = S2Cap(axis: center, angle: S1Angle(radians: faceRadius + S2CapTests.eps)) XCTAssertEqual(covering.contains(cell: rootCell), capFace == face) XCTAssertEqual(covering.mayIntersect(cell: rootCell), capFace != antiFace) XCTAssertEqual(covering.contains(cell: edgeCell), center.dotProd(edgeCell.center) > 0.1) XCTAssertEqual(covering.contains(cell: edgeCell), covering.mayIntersect(cell: edgeCell)) XCTAssertEqual(covering.contains(cell: cornerCell), capFace == face) XCTAssertEqual(covering.mayIntersect(cell: cornerCell), center.dotProd(cornerCell.center) > 0) // A cap that barely intersects the edges of 'cap_face'. let bulging = S2Cap(axis: center, angle: S1Angle(radians: M_PI_4 + S2CapTests.eps)) XCTAssert(!bulging.contains(cell: rootCell)) XCTAssertEqual(bulging.mayIntersect(cell: rootCell), capFace != antiFace) XCTAssertEqual(bulging.contains(cell: edgeCell), capFace == face) XCTAssertEqual(bulging.mayIntersect(cell: edgeCell), center.dotProd(edgeCell.center) > 0.1) XCTAssert(!bulging.contains(cell: cornerCell)) XCTAssert(!bulging.mayIntersect(cell: cornerCell)) // A singleton cap. let singleton = S2Cap(axis: center, angle: S1Angle(radians: 0)) XCTAssertEqual(singleton.mayIntersect(cell: rootCell), capFace == face) XCTAssert(!singleton.mayIntersect(cell: edgeCell)) XCTAssert(!singleton.mayIntersect(cell: cornerCell)) } } } } extension S2CapTests { static var allTests: [(String, (S2CapTests) -> () throws -> Void)] { return [ ("testBasic", testBasic), ("testRectBound", testRectBound), ("testCells", testCells), ] } }
mit
224fb21c8dd3a3267ad30306661192a7
43.892241
124
0.719251
3.122939
false
true
false
false
RyanTech/SwinjectMVVMExample
ExampleViewModel/ImageDetailViewModel.swift
1
4021
// // ImageDetailViewModel.swift // SwinjectMVVMExample // // Created by Yoichi Tagaya on 8/24/15. // Copyright © 2015 Swinject Contributors. All rights reserved. // import ReactiveCocoa import ExampleModel public final class ImageDetailViewModel: ImageDetailViewModeling { public var id: PropertyOf<UInt64?> { return PropertyOf(_id) } public var pageImageSizeText: PropertyOf<String?> { return PropertyOf(_pageImageSizeText) } public var tagText: PropertyOf<String?> { return PropertyOf(_tagText) } public var usernameText: PropertyOf<String?> { return PropertyOf(_usernameText) } public var viewCountText: PropertyOf<String?> { return PropertyOf(_viewCountText) } public var downloadCountText: PropertyOf<String?> { return PropertyOf(_downloadCountText) } public var likeCountText: PropertyOf<String?> { return PropertyOf(_likeCountText) } public var image: PropertyOf<UIImage?> { return PropertyOf(_image) } private let _id = MutableProperty<UInt64?>(nil) private let _pageImageSizeText = MutableProperty<String?>(nil) private let _tagText = MutableProperty<String?>(nil) private let _usernameText = MutableProperty<String?>(nil) private let _viewCountText = MutableProperty<String?>(nil) private let _downloadCountText = MutableProperty<String?>(nil) private let _likeCountText = MutableProperty<String?>(nil) private let _image = MutableProperty<UIImage?>(nil) internal var locale = NSLocale.currentLocale() // For testing. private var imageEntities = [ImageEntity]() private var currentImageIndex = 0 private var (stopSignalProducer, stopSignalObserver) = SignalProducer<(), NoError>.buffer() private let network: Networking private let externalAppChannel: ExternalAppChanneling public init(network: Networking, externalAppChannel: ExternalAppChanneling) { self.network = network self.externalAppChannel = externalAppChannel } public func openImagePage() { if let currentImageEntity = currentImageEntity { externalAppChannel.openURL(currentImageEntity.pageURL) } } private var currentImageEntity: ImageEntity? { return imageEntities.indices.contains(currentImageIndex) ? imageEntities[currentImageIndex] : nil } } extension ImageDetailViewModel: ImageDetailViewModelModifiable { public func update(imageEntities: [ImageEntity], atIndex index: Int) { sendNext(stopSignalObserver, ()) (stopSignalProducer, stopSignalObserver) = SignalProducer<(), NoError>.buffer() self.imageEntities = imageEntities currentImageIndex = index let imageEntity = currentImageEntity self._id.value = imageEntity?.id self._usernameText.value = imageEntity?.username self._pageImageSizeText.value = imageEntity.map { "\($0.pageImageWidth) x \($0.pageImageHeight)" } self._tagText.value = imageEntity.map { $0.tags.joinWithSeparator(", ") } self._viewCountText.value = imageEntity.map { formatInt64($0.viewCount) } self._downloadCountText.value = imageEntity.map { formatInt64($0.downloadCount) } self._likeCountText.value = imageEntity.map { formatInt64($0.likeCount) } _image.value = nil if let imageEntity = imageEntity { _image <~ network.requestImage(imageEntity.imageURL) .takeUntil(stopSignalProducer) .map { $0 as UIImage? } .flatMapError { _ in SignalProducer<UIImage?, NoError>(value: nil) } .observeOn(UIScheduler()) } } private func formatInt64(value: Int64) -> String { return NSNumber(longLong: value).descriptionWithLocale(locale) } // This method can be used if you add next and previsou buttons on image detail view // to display the next or previous image. // public func updateIndex(index: Int) { // update(imageEntities, atIndex: index) // } }
mit
0ed8379202b4f9a9d3a695bf5e4bebd1
43.175824
106
0.695025
4.594286
false
false
false
false
EclipseSoundscapes/EclipseSoundscapes
EclipseSoundscapes/Features/Permissions/LocationPermission.swift
1
2379
// // LocationPermission.swift // EclipseSoundscapes // // Created by Arlindo on 12/26/20. // Copyright © 2020 Eclipse Soundscapes. All rights reserved. // import CoreLocation class LocationPermission: NSObject, Permission, CLLocationManagerDelegate { private let locationManager: CLLocationManager private var authorizationHandler: ((PermissionStatus) -> Void)? static var isLocallyAuthorized: Bool { get { return UserDefaults.standard.bool(forKey: "LocationGranted") } set { UserDefaults.standard.set(newValue, forKey: "LocationGranted") } } var localPermissionAuthorized: Bool { get { return LocationPermission.isLocallyAuthorized } set { LocationPermission.isLocallyAuthorized = newValue } } init(locationManager: CLLocationManager = CLLocationManager()) { self.locationManager = locationManager super.init() locationManager.delegate = self } func isAuthorized(completion: @escaping ((PermissionStatus) -> Void)) { let status = CLLocationManager.authorizationStatus() switch status.permissionStatus { case .authorized where !localPermissionAuthorized: completion(.denied(.localLocationDisabled)) return case .denied where !checkLocationServices(): completion(.denied(.locationServicesDisabled)) return default: break } completion(status.permissionStatus) } func checkLocationServices() -> Bool { return CLLocationManager.locationServicesEnabled() } func request(completion: @escaping ((PermissionStatus) -> Void)) { locationManager.requestWhenInUseAuthorization() authorizationHandler = completion } func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { authorizationHandler?(status.permissionStatus) } } extension CLAuthorizationStatus { var permissionStatus: PermissionStatus { switch self { case .notDetermined: return .notDetermined case .authorizedWhenInUse, .authorizedAlways: return .authorized default: return .denied(.locationDisabled) } } }
gpl-3.0
36c15cfc3c4d92b4a287bc84e5151c44
27.650602
110
0.652649
5.857143
false
false
false
false
apple/swift-nio
Sources/NIOHTTP1/HTTPHeaderValidator.swift
1
3922
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2022 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import NIOCore /// A ChannelHandler to validate that outbound request headers are spec-compliant. /// /// The HTTP RFCs constrain the bytes that are validly present within a HTTP/1.1 header block. /// ``NIOHTTPRequestHeadersValidator`` polices this constraint and ensures that only valid header blocks /// are emitted on the network. If a header block is invalid, then ``NIOHTTPRequestHeadersValidator`` /// will send a ``HTTPParserError/invalidHeaderToken``. /// /// ``NIOHTTPRequestHeadersValidator`` will also valid that the HTTP trailers are within specification, /// if they are present. public final class NIOHTTPRequestHeadersValidator: ChannelOutboundHandler, RemovableChannelHandler { public typealias OutboundIn = HTTPClientRequestPart public typealias OutboundOut = HTTPClientRequestPart public init() { } public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise<Void>?) { switch self.unwrapOutboundIn(data) { case .head(let head): guard head.headers.areValidToSend else { promise?.fail(HTTPParserError.invalidHeaderToken) context.fireErrorCaught(HTTPParserError.invalidHeaderToken) return } case .body, .end(.none): () case .end(.some(let trailers)): guard trailers.areValidToSend else { promise?.fail(HTTPParserError.invalidHeaderToken) context.fireErrorCaught(HTTPParserError.invalidHeaderToken) return } } context.write(data, promise: promise) } } /// A ChannelHandler to validate that outbound response headers are spec-compliant. /// /// The HTTP RFCs constrain the bytes that are validly present within a HTTP/1.1 header block. /// ``NIOHTTPResponseHeadersValidator`` polices this constraint and ensures that only valid header blocks /// are emitted on the network. If a header block is invalid, then ``NIOHTTPResponseHeadersValidator`` /// will send a ``HTTPParserError/invalidHeaderToken``. /// /// ``NIOHTTPResponseHeadersValidator`` will also valid that the HTTP trailers are within specification, /// if they are present. public final class NIOHTTPResponseHeadersValidator: ChannelOutboundHandler, RemovableChannelHandler { public typealias OutboundIn = HTTPServerResponsePart public typealias OutboundOut = HTTPServerResponsePart public init() { } public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise<Void>?) { switch self.unwrapOutboundIn(data) { case .head(let head): guard head.headers.areValidToSend else { promise?.fail(HTTPParserError.invalidHeaderToken) context.fireErrorCaught(HTTPParserError.invalidHeaderToken) return } case .body, .end(.none): () case .end(.some(let trailers)): guard trailers.areValidToSend else { promise?.fail(HTTPParserError.invalidHeaderToken) context.fireErrorCaught(HTTPParserError.invalidHeaderToken) return } } context.write(data, promise: promise) } } #if swift(>=5.6) @available(*, unavailable) extension NIOHTTPRequestHeadersValidator: Sendable {} @available(*, unavailable) extension NIOHTTPResponseHeadersValidator: Sendable {} #endif
apache-2.0
7792be89081a2b84d22a5dbd2930f899
39.43299
105
0.670321
5.160526
false
false
false
false
mountainKaku/Basic-Algorithms
SelectionSort.playground/Contents.swift
1
1022
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" print(str) //SelectionSort: 选择排序法 typealias CRITERIA<T> = (T, T) -> Bool func selectionSortOf<T: Comparable>( _ arr: Array<T>, byCriteria: CRITERIA<T> = { $0 < $1 }) -> Array<T> { // 1. An array with a single element is ordered guard arr.count > 1 else { return arr } var result = arr for i in 0 ..< result.count - 1 { var min = i for j in i+1 ..< result.count { if byCriteria(result[j], result[min]) { min = j } } let temp = result[min] result[min] = result[i] result[i] = temp } return result } var numbersArray = [10,3,17,8,5,2,1,9,5,4] print("选择排序方案: \(selectionSortOf(numbersArray))") print("选择排序方案: \(selectionSortOf(numbersArray, byCriteria: <))") print("选择排序方案: \(selectionSortOf(numbersArray, byCriteria: >))")
mit
e6814ba25350ba23acd7c6970b1ea07a
21.697674
64
0.566598
3.286195
false
false
false
false
269961541/weibo
xinlangweibo/Class/Home/View/Cell/tableTopView.swift
1
3483
// // tableTopView.swift // xinlangweibo // // Created by Mac on 15/10/31. // Copyright © 2015年 Mac. All rights reserved. // import UIKit class tableTopView: UIView { //MARK: 构造方法 required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override init(frame: CGRect) { super.init(frame: frame) prepareUI() } var status:XGWstatus?{ didSet{ ///发布时间 timeLabel.text = status?.created_at /// 微博来源 sourceLabel.text = "来自星星的你发布" /// 用户微博头像 let user = status?.user let url = NSURL(string: (user?.profile_image_url)!) iconView.sd_setImageWithURL(url) ///好友名称 userName.text = user?.name /// 会员等级 memberView.image = user!.mbrankImage ///认证等级 verifiedView.image = user?.verifiedTypeImage } } ///准备UI func prepareUI (){ addSubview(iconView) addSubview(userName) addSubview(timeLabel) addSubview(sourceLabel) addSubview(verifiedView) addSubview(memberView) //约束垂直方向对齐指的是参照控件的X轴对齐 水平方向参照的是Y轴 // 添加约束 /// 头像视图 iconView.ff_AlignInner(type: ff_AlignType.TopLeft, referView: self, size: CGSize(width: 35, height: 35), offset: CGPoint(x: 8, y: 8)) /// 名称 userName.ff_AlignHorizontal(type: ff_AlignType.TopRight, referView: iconView, size: nil, offset: CGPoint(x: 8, y: 0)) /// 时间 timeLabel.ff_AlignHorizontal(type: ff_AlignType.BottomRight, referView: iconView, size: nil, offset: CGPoint(x: 8, y: 0)) /// 来源 sourceLabel.ff_AlignHorizontal(type: ff_AlignType.CenterRight, referView: timeLabel, size: nil, offset: CGPoint(x: 8, y: 0)) /// 会员等级 memberView.ff_AlignHorizontal(type: ff_AlignType.CenterRight, referView: userName, size: CGSize(width: 14, height: 14), offset: CGPoint(x: 8, y: 0)) /// 认证图标 verifiedView.ff_AlignInner(type: ff_AlignType.BottomRight, referView: iconView, size: CGSize(width: 17, height: 17), offset: CGPoint(x: 8.5, y: 8.5)) } //MARK: 属性懒加载 ///头像 private lazy var iconView = UIImageView() ///姓名 private lazy var userName:UILabel = { let leble = UILabel() leble.font = UIFont.systemFontOfSize(14) leble.textColor = UIColor.darkGrayColor(); return leble }() ///发布时间 private lazy var timeLabel:UILabel = { let lable = UILabel() lable.font = UIFont.systemFontOfSize(9) lable.tintColor = UIColor.orangeColor() return lable }() ///来源 private lazy var sourceLabel:UILabel = { let lable = UILabel() lable.font = UIFont.systemFontOfSize(9) lable.tintColor = UIColor.lightGrayColor() return lable }() ///认证图标 private lazy var verifiedView = UIImageView() ///会员等级 private lazy var memberView:UIImageView = { let image = UIImageView() image.image = UIImage(named: "common_icon_membership") return image }() }
apache-2.0
0f9a4ac25dfa422ad014613b3189343d
28.853211
157
0.575907
4.248042
false
false
false
false
kinetic-fit/sensors-swift
Sources/SwiftySensors/DeviceInformationService.swift
1
3511
// // DeviceInformationService.swift // SwiftySensors // // https://github.com/kinetic-fit/sensors-swift // // Copyright © 2017 Kinetic. All rights reserved. // import CoreBluetooth // // https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.service.device_information.xml // /// :nodoc: open class DeviceInformationService: Service, ServiceProtocol { public static var uuid: String { return "180A" } public static var characteristicTypes: Dictionary<String, Characteristic.Type> = [ ManufacturerName.uuid: ManufacturerName.self, ModelNumber.uuid: ModelNumber.self, SerialNumber.uuid: SerialNumber.self, HardwareRevision.uuid: HardwareRevision.self, FirmwareRevision.uuid: FirmwareRevision.self, SoftwareRevision.uuid: SoftwareRevision.self, SystemID.uuid: SystemID.self ] open var manufacturerName: ManufacturerName? { return characteristic() } open var modelNumber: ModelNumber? { return characteristic() } open var serialNumber: SerialNumber? { return characteristic() } open var hardwareRevision: HardwareRevision? { return characteristic() } open var firmwareRevision: FirmwareRevision? { return characteristic() } open var softwareRevision: SoftwareRevision? { return characteristic() } open var systemID: SystemID? { return characteristic() } // // https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.manufacturer_name_string.xml // open class ManufacturerName: UTF8Characteristic { public static let uuid: String = "2A29" } // // https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.model_number_string.xml // open class ModelNumber: UTF8Characteristic { public static let uuid: String = "2A24" } // // https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.serial_number_string.xml // open class SerialNumber: UTF8Characteristic { public static let uuid: String = "2A25" } // // https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.hardware_revision_string.xml // open class HardwareRevision: UTF8Characteristic { public static let uuid: String = "2A27" } // // https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.firmware_revision_string.xml // open class FirmwareRevision: UTF8Characteristic { public static let uuid: String = "2A26" } // // https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.software_revision_string.xml // open class SoftwareRevision: UTF8Characteristic { public static let uuid: String = "2A28" } // // https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.software_revision_string.xml // open class SystemID: Characteristic { public static let uuid: String = "2A23" required public init(service: Service, cbc: CBCharacteristic) { super.init(service: service, cbc: cbc) readValue() } } }
mit
b916109873bc70b6150b937b29b7300c
32.75
134
0.67265
4.437421
false
false
false
false
oarrabi/RangeSliderView
Pod/Classes/SliderBackgroundView.swift
1
2232
// // SliderBackgroundView.swift // DublinBusMenu // // Created by Omar Abdelhafith on 04/02/2016. // Copyright © 2016 Omar Abdelhafith. All rights reserved. // import Foundation protocol SliderBackground { var boundRange: BoundRange { get set } var frame: CGRect { get } var view: SliderBackgroundView { get } #if os(OSX) var emptyColor: NSColor { get set } var fullColor: NSColor { get set } #else var emptyColor: UIColor { get set } var fullColor: UIColor { get set } #endif } class SliderBackgroundViewImpl { static func drawRect(forView view: SliderBackground, dirtyRect: CGRect) { view.emptyColor.set() dirtyRect |> RectUtil.setRectHeight(height: 3) |> RectUtil.centerRectVertically(height: view.frame.height) |> drawCapsule view.fullColor.set() dirtyRect |> RectUtil.applyBoundRange(boundRange: view.boundRange.boundByApplyingInset(-3)) |> RectUtil.setRectHeight(height: 3) |> RectUtil.centerRectVertically(height: view.frame.height) |> drawCapsule } static func drawCapsule(frame frame: CGRect) { let height = CGRectGetHeight(frame) if (frame.width - height) < 4 { return } #if os(OSX) let ovalPath = NSBezierPath(ovalInRect: NSMakeRect(frame.minX, frame.minY, height, frame.height)) #else let ovalPath = UIBezierPath(ovalInRect: CGRectMake(frame.minX, frame.minY, height, frame.height)) #endif ovalPath.fill() #if os(OSX) let oval2Path = NSBezierPath(ovalInRect: NSMakeRect(frame.minX + frame.width - height, frame.minY, height, frame.height)) #else let oval2Path = UIBezierPath(ovalInRect: CGRectMake(frame.minX + frame.width - height, frame.minY, height, frame.height)) #endif oval2Path.fill() #if os(OSX) let rectanglePath = NSBezierPath(rect: NSMakeRect(frame.minX + (height/2), frame.minY, frame.width - height, frame.height)) #else let rectanglePath = UIBezierPath(rect: CGRectMake(frame.minX + (height/2), frame.minY, frame.width - height, frame.height)) #endif rectanglePath.fill() } } extension SliderBackgroundView: SliderBackground { var view: SliderBackgroundView { return self } }
mit
a4ac4f39c78be5168179271a73b8d24f
28.76
129
0.686688
3.866551
false
false
false
false
milseman/swift
validation-test/compiler_crashers_2_fixed/0090-emit-implied-witness-table-ref.swift
56
1317
// RUN: %target-swift-frontend -primary-file %s -emit-ir // From https://twitter.com/Dimillian/status/854436731894018048 class User: Equatable { var id: String = "" var username: String = "" var name: String = "" var avatar: String? var friends: [String]? var followers: [String]? var library: [String]? var libraryCount: Int = 0 var friendsCount: Int = 0 var followersCount: Int = 0 var loadMoreFriends = false var loadMoreFollowers = false var loadMoreLibrary = false } func ==<T: User>(lhs: T?, rhs: T?) -> Bool { guard let lhs = lhs, let rhs = rhs else { return false } return lhs == rhs } func ==<T: User>(lhs: T, rhs: T) -> Bool { return lhs.id == rhs.id && lhs.username == rhs.username && lhs.name == rhs.name && lhs.libraryCount == rhs.libraryCount && lhs.friendsCount == rhs.friendsCount && lhs.followersCount == rhs.followersCount && lhs.friends == rhs.friends && lhs.followers == rhs.followers && lhs.library == rhs.library } func ==<T: Equatable>(lhs: [T]?, rhs: [T]?) -> Bool { switch (lhs, rhs) { case (.some(let lhs), .some(let rhs)): return lhs == rhs case (.none, .none): return true default: return false } }
apache-2.0
e16c04a0fbba5334826859010d5b1e33
25.34
63
0.578588
3.638122
false
false
false
false
superk589/CGSSGuide
DereGuide/Controller/BaseFilterSortController.swift
2
3743
// // BaseFilterSortController.swift // DereGuide // // Created by zzk on 2017/1/12. // Copyright © 2017 zzk. All rights reserved. // import UIKit import SnapKit class BaseFilterSortController: BaseViewController, UITableViewDelegate, UITableViewDataSource { let toolbar = UIToolbar() let tableView = UITableView() override func viewDidLoad() { super.viewDidLoad() tableView.register(FilterTableViewCell.self, forCellReuseIdentifier: "FilterCell") tableView.register(SortTableViewCell.self, forCellReuseIdentifier: "SortCell") tableView.delegate = self tableView.dataSource = self tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 44, right: 0) tableView.tableFooterView = UIView(frame: .zero) tableView.estimatedRowHeight = 50 tableView.cellLayoutMarginsFollowReadableWidth = false view.addSubview(tableView) tableView.snp.makeConstraints { (make) in make.left.right.bottom.equalToSuperview() make.top.equalTo(topLayoutGuide.snp.bottom) } toolbar.tintColor = .parade view.addSubview(toolbar) toolbar.snp.makeConstraints { (make) in if #available(iOS 11.0, *) { make.left.right.equalToSuperview() make.bottom.equalTo(view.safeAreaLayoutGuide) } else { make.bottom.left.right.equalToSuperview() } make.height.equalTo(44) } let leftSpaceItem = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil) leftSpaceItem.width = 0 let doneItem = UIBarButtonItem(title: NSLocalizedString("完成", comment: "导航栏按钮"), style: .done, target: self, action: #selector(doneAction)) let middleSpaceItem = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) let resetItem = UIBarButtonItem(title: NSLocalizedString("重置", comment: "导航栏按钮"), style: .plain, target: self, action: #selector(resetAction)) let rightSpaceItem = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil) rightSpaceItem.width = 0 toolbar.setItems([leftSpaceItem, resetItem, middleSpaceItem, doneItem, rightSpaceItem], animated: false) } @objc func doneAction() { } @objc func resetAction() { } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) coordinator.animate(alongsideTransition: { [weak self] (context) in // since the size changes, update all table cells to fit the new size self?.tableView.beginUpdates() self?.tableView.endUpdates() }, completion: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func numberOfSections(in tableView: UITableView) -> Int { return 2 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { return UITableViewCell() } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if section == 0 { return NSLocalizedString("筛选", comment: "") } else { return NSLocalizedString("排序", comment: "") } } }
mit
3b2664b956f214cdacdd0d3ad588090d
34.634615
150
0.644091
5.175978
false
false
false
false
melsomino/unified-ios
Unified/Library/Ui/Layout/LayoutLayered.swift
1
1427
// // Created by Власов М.Ю. on 07.06.16. // Copyright (c) 2016 Tensor. All rights reserved. // import Foundation import UIKit public class LayoutLayered: LayoutItem { let content: [LayoutItem] init(_ content: [LayoutItem]) { self.content = content } public override var visible: Bool { return content.contains({ $0.visible }) } public override var fixedSize: Bool { return content.contains({ $0.fixedSize }) } public override func createViews(inSuperview superview: UIView) { for item in content { item.createViews(inSuperview: superview) } } public override func collectFrameItems(inout items: [LayoutFrameItem]) { for item in content { item.collectFrameItems(&items) } } public override func measureMaxSize(bounds: CGSize) -> CGSize { var maxSize = CGSizeZero for item in content { let itemSize = item.measureMaxSize(bounds) maxSize.width = max(maxSize.width, itemSize.width) maxSize.height = max(maxSize.height, itemSize.height) } return maxSize } public override func measureSize(bounds: CGSize) -> CGSize { var size = CGSizeZero for item in content { let itemSize = item.measureSize(bounds) size.width = max(size.width, itemSize.width) size.height = max(size.height, itemSize.height) } return size } public override func layout(bounds: CGRect) -> CGRect { for item in content { item.layout(bounds) } return bounds } }
mit
814752985fe8dc155535d1714b3dce1d
20.179104
73
0.707541
3.427536
false
false
false
false
afonsograca/Queryable_Swift
ios-queryable/NSManagedObjectContext+Queryable.swift
1
7945
// // NSManagedObjectContext+Queryable.swift // ios-queryable // // Created by Afonso Graça on 09/03/15. // Copyright (c) 2015 Afonso Graça. All rights reserved. // import Foundation import CoreData class Queryable : NSFastEnumeration { // MARK: - Private Properties private let context : NSManagedObjectContext private let type : String private let skipCount : Int private let fetchCount : Int private var sorts : [AnyObject]? private var whereClauses : [AnyObject]? // MARK: - Initialisers init(type entityType : String, context theContext: NSManagedObjectContext){ self.type = entityType self.context = theContext self.fetchCount = Int.max self.skipCount = 0 } init(type entityType : String, context theContext : NSManagedObjectContext, fetch newFetch: Int, skip newSkip : Int, sorts newSorts : [AnyObject]?, whereClauses newWhereClauses : [AnyObject]?){ self.type = entityType self.context = theContext self.fetchCount = newFetch self.skipCount = newSkip self.sorts = newSorts self.whereClauses = newWhereClauses } // MARK: - Public Methods func toArray() -> [AnyObject]? { if self.fetchCount <= 0 { return [AnyObject]() } var error : NSError? let results = self.context.executeFetchRequest(self.getFetchRequest(), error: &error) if let err = error { NSLog("[\(self) \(__FUNCTION__)] \(err.localizedDescription) (\(err.localizedFailureReason))") } return results } func add(object : AnyObject, array : [AnyObject]?) -> [AnyObject]? { if let array = array { return array + [object] } else { return [object] } } func orderBy(fieldName : String, ascending : Bool) -> Queryable { let descriptor = NSSortDescriptor(key: fieldName, ascending: ascending) let newSorts = self.add(descriptor, array: self.sorts) return Queryable(type: self.type, context: self.context, fetch: self.fetchCount, skip: self.skipCount, sorts: newSorts, whereClauses: self.whereClauses) } func skip(numberToSKip : Int) -> Queryable { return Queryable(type: self.type, context: self.context, fetch: self.fetchCount, skip: numberToSKip, sorts: self.sorts, whereClauses: self.whereClauses) } func fetch(numberToFetch : Int) -> Queryable { return Queryable(type: self.type, context: self.context, fetch: numberToFetch, skip: self.skipCount, sorts: self.sorts, whereClauses: self.whereClauses) } func whereConditions( conditions : [String]) -> Queryable { if conditions.count > 0 { let predicate = NSPredicate(format: conditions[0], conditions) if let pred = predicate { let newWhere = self.add(pred, array: self.whereClauses) return Queryable(type: self.type, context: self.context, fetch: self.fetchCount, skip: self.skipCount, sorts: self.sorts, whereClauses: newWhere) } } return Queryable(type: self.type, context: self.context, fetch: self.fetchCount, skip: self.skipCount, sorts: self.sorts, whereClauses: self.whereClauses) } func countRequest() -> Int { var error : NSError? let theCount = self.context.countForFetchRequest(self.getFetchRequest(), error: &error) if let err = error { NSLog("[\(self) \(__FUNCTION__)] \(err.localizedDescription) (\(err.localizedFailureReason))") } return theCount } func countRequest(conditions : [String]) -> Int { let query = self.whereConditions(conditions) return query.countRequest() } func anyRequest() -> Bool { return self.countRequest() > 0 ? true : false } func anyRequest(conditions : String...) -> Bool { return self.countRequest(conditions) > 0 ? true : false } func allRequest(conditions : String...) -> Bool { return self.countRequest() == self.countRequest(conditions) ? true : false } func first() -> AnyObject? { if let result: AnyObject = self.firstOrDefault() { return result } else { var list : CVaListPointer? NSException.raise("The source sequence is empty", format: "", arguments: list!) return nil } } func firstRequest(conditions : String...) -> AnyObject? { let query = self.whereConditions(conditions) return query.first() } func firstOrDefault() -> AnyObject? { let query = Queryable(type: self.type, context: self.context, fetch: 1, skip: self.skipCount, sorts: self.sorts, whereClauses: self.whereClauses) if let results = query.toArray() { return results[0] } else { return nil } } func firstOrDefaultRequest(conditions : String...) -> AnyObject? { let query = self.whereConditions(conditions) return query.firstOrDefault() } func single() -> AnyObject? { if let result: AnyObject = self.singleOrDefault() { return result } else { var list : CVaListPointer? NSException.raise("The source sequence is empty", format: "", arguments: list!) return nil } } func singleRequest(conditions : String...) -> AnyObject? { let query = self.whereConditions(conditions) return query.single() } func singleOrDefault() -> AnyObject? { var howManyShouldIFetch = min(self.fetchCount < 0 ? 0 : self.fetchCount, 2) let query = Queryable(type: self.type, context: self.context, fetch: howManyShouldIFetch, skip: self.skipCount, sorts: self.sorts, whereClauses: self.whereClauses) if let results = query.toArray() { switch results.count { case 0 : return nil case 1: return results[0] default: var list : CVaListPointer? NSException.raise("The source sequence is empty", format: "", arguments: list!) return nil } } else { return nil } } func singleOrDefaultRequest(conditions : String...) -> AnyObject? { let query = self.whereConditions(conditions) return query.singleOrDefault() } /** * Fetches the value of a function applied to an entity's attribute * property - the attribute to perform the expression on * function - the function to be performed (i.e. average: sum: min: max:) */ func getExpressionValue(property : String, function : String) -> Double { let keyPathExpression = NSExpression(forKeyPath: property) let exp = NSExpression(forFunction: function, arguments: [keyPathExpression]) let expressionDescription = NSExpressionDescription() expressionDescription.name = "expressionValue" expressionDescription.expression = exp expressionDescription.expressionResultType = .DoubleAttributeType let request = self.getFetchRequest() request.resultType = .DictionaryResultType request.propertiesToFetch = [expressionDescription] var error : NSError? let fetchResultArray = self.context.executeFetchRequest(request, error: &error) if let err = error { println("\(err)") } else { if let fra = fetchResultArray { let fetchResultsDictionary: AnyObject = fra[0] return fetchResultsDictionary.objectForKey("expressionValue")! as Double } } return 0 } // MARK: - NSFastEnumeration Protocol Conformance func countByEnumeratingWithState(state: UnsafeMutablePointer<NSFastEnumerationState>, objects buffer: AutoreleasingUnsafeMutablePointer<AnyObject?>, count len: Int) -> Int { let items : AnyObject? = self.toArray() if let nsarray = items as? NSArray { return nsarray.countByEnumeratingWithState(state, objects: buffer, count: len) } return 0 } // MARK: - Private Methods func getFetchRequest() -> NSFetchRequest { let entityDescription = NSEntityDescription.entityForName(self.type, inManagedObjectContext: self.context) let fetchRequest = NSFetchRequest() fetchRequest.entity = entityDescription fetchRequest.sortDescriptors = self.sorts fetchRequest.fetchOffset = max(self.skipCount, 0) fetchRequest.fetchLimit = self.fetchCount if let whereClauses = self.whereClauses { fetchRequest.predicate = NSCompoundPredicate.andPredicateWithSubpredicates(whereClauses) } return fetchRequest } } extension NSManagedObjectContext { //+Queryable func ofType(name : String) -> Queryable { return Queryable(type : name, context : self) } }
mit
956e87df5809b355ca7de681fde426f5
29.436782
194
0.71434
3.816915
false
false
false
false
superk589/DereGuide
DereGuide/Controller/BaseNavigationController.swift
2
4581
// // BaseNavigationController.swift // DereGuide // // Created by zzk on 16/7/30. // Copyright © 2016 zzk. All rights reserved. // import UIKit class BaseNavigationController: UINavigationController, UIGestureRecognizerDelegate, UINavigationControllerDelegate { override func viewDidLoad() { super.viewDidLoad() // 设置导航控制器背景颜色 防止跳转时页面闪烁 self.view.backgroundColor = .white // self.navigationBar.tintColor = UIColor.whiteColor() // 设置右滑手势代理 防止右滑在修改了左侧导航按钮之后失效 self.interactivePopGestureRecognizer?.delegate = self self.interactivePopGestureRecognizer?.isEnabled = true self.delegate = self navigationBar.tintColor = .parade toolbar.tintColor = .parade // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // 解决当视图中存在其他手势时 特别是UIScrollView布满全屏时 导致返回手势失效的问题 func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer) -> Bool { return gestureRecognizer == self.interactivePopGestureRecognizer } // 如果不实现这个方法, 在根视图的左侧向右滑动几下再点击push新页面会卡死 func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { return children.count > 1 } private var showHomeButtonCount = 3 @objc func popToRoot() { // 使用自定义动画效果 let transition = CATransition() transition.type = CATransitionType.fade transition.duration = 0.3 view.layer.add(transition, forKey: kCATransition) popViewController(animated: false) popToRootViewController(animated: false) setToolbarHidden(true, animated: true) } private lazy var flexibleSpaceItem = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) private lazy var homeItem = UIBarButtonItem(image: #imageLiteral(resourceName: "750-home-toolbar"), style: .plain, target: self, action: #selector(popToRoot)) func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) { // if self.viewControllers.count <= showHomeButtonCount { // if let items = viewController.toolbarItems { // if items.count > 0 && items.contains(where: { ![flexibleSpaceItem, homeItem].contains($0) }) { // setToolbarHidden(false, animated: animated) // } else { // setToolbarHidden(true, animated: animated) // } // } else { // setToolbarHidden(true, animated: animated) // } // } else { // setToolbarHidden(false, animated: animated) // if let items = viewController.toolbarItems { // if !items.contains(homeItem) { // if items.count > 0 { // viewController.toolbarItems?.append(flexibleSpaceItem) // } // viewController.toolbarItems?.append(homeItem) // } // } else { // viewController.toolbarItems = [homeItem] // } // } if let items = viewController.toolbarItems { setToolbarHidden(items.count == 0, animated: animated) } else { setToolbarHidden(true, animated: animated) } } func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationController.Operation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? { if let vc = fromVC as? (BannerAnimatorProvider & BannerContainer), toVC is BannerContainer, operation == .push { vc.bannerAnimator.animatorType = .push return vc.bannerAnimator } else if let vc = toVC as? (BannerContainer & BannerAnimatorProvider), let fromVC = fromVC as? BannerContainer, operation == .pop, vc.bannerView != nil, fromVC.bannerView != nil { vc.bannerAnimator.animatorType = .pop return vc.bannerAnimator } return nil } }
mit
e5f0e976fa7d32cb135950078a42ca99
41.174757
247
0.644567
5.080702
false
false
false
false
PopovVadim/PVDSwiftAddOns
PVDSwiftAddOns/Classes/Extensions/Foundation/StringAndCharacterExtension.swift
1
3690
// // StringExtensions.swift // PVDSwiftExtensions // // Created by Вадим Попов on 9/25/17. // import Foundation /** * * */ public extension String { /** */ func capitalizingFirstLetter() -> String { let first = String(self.prefix(1)).capitalized let other = String(self.dropFirst()) return first + other } /** */ mutating func capitalizeFirstLetter() { self = self.capitalizingFirstLetter() } /** */ subscript (i: Int) -> Character { return self[index(startIndex, offsetBy: i)] } /** */ subscript (i: Int) -> String { return String(self[i] as Character) } /** */ subscript (r: Range<Int>) -> String { let start = index(startIndex, offsetBy: r.lowerBound) let end = index(startIndex, offsetBy: r.upperBound) return String(self[start ..< end]) } /** */ func isInteger() -> Bool { return Int(self) != nil } /** */ func isDouble() -> Bool { return Double(self) != nil } /** */ func replacing(with: String, occurences of: String...) -> String { var replaced: String = self for needle in of { replaced = replaced.replacingOccurrences(of: needle, with: with) } return replaced } /** */ static func random(length: Int = 20) -> String { let letters : NSString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" let len = UInt32(letters.length) var randomString = "" for _ in 0 ..< length { let rand = arc4random_uniform(len) var nextChar = letters.character(at: Int(rand)) randomString += NSString(characters: &nextChar, length: 1) as String } return randomString } /** */ func height(withConstrainedWidth width: CGFloat, font: UIFont) -> CGFloat { let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude) let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [.font: font], context: nil) return ceil(boundingBox.height) } /** */ func width(withConstraintedHeight height: CGFloat, font: UIFont) -> CGFloat { let constraintRect = CGSize(width: .greatestFiniteMagnitude, height: height) let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [.font: font], context: nil) return ceil(boundingBox.width) } } /** * * */ public extension NSAttributedString { /** */ func height(withConstrainedWidth width: CGFloat) -> CGFloat { let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude) let boundingBox = boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, context: nil) return ceil(boundingBox.height) } /** */ func width(withConstrainedHeight height: CGFloat) -> CGFloat { let constraintRect = CGSize(width: .greatestFiniteMagnitude, height: height) let boundingBox = boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, context: nil) return ceil(boundingBox.width) } } /** * * */ public extension Character { /** */ func unicodeScalarCodePoint() -> UInt32 { let characterString = String(self) let scalars = characterString.unicodeScalars return scalars[scalars.startIndex].value } }
mit
034970714cf6efb9c5adc5746b3f3623
24.034014
140
0.588859
4.773022
false
false
false
false
andreaperizzato/CoreStore
CoreStore/NSError+CoreStore.swift
2
3138
// // NSError+CoreStore.swift // CoreStore // // Copyright (c) 2014 John Rommel Estropia // // 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 /** The `NSError` error domain for `CoreStore`. */ public let CoreStoreErrorDomain = "com.corestore.error" /** The `NSError` error codes for `CoreStoreErrorDomain`. */ public enum CoreStoreErrorCode: Int { /** A failure occured because of an unknown error. */ case UnknownError /** The `NSPersistentStore` could note be initialized because another store existed at the specified `NSURL`. */ case DifferentPersistentStoreExistsAtURL /** The `NSPersistentStore` specified could not be found. */ case PersistentStoreNotFound /** An `NSMappingModel` could not be found for a specific source and destination model versions. */ case MappingModelNotFound } // MARK: - NSError+CoreStore public extension NSError { /** If the error's domain is equal to `CoreStoreErrorDomain`, returns the associated `CoreStoreErrorCode`. For other domains, returns `nil`. */ public var coreStoreErrorCode: CoreStoreErrorCode? { return (self.domain == CoreStoreErrorDomain ? CoreStoreErrorCode(rawValue: self.code) : nil) } // MARK: Internal internal convenience init(coreStoreErrorCode: CoreStoreErrorCode) { self.init(coreStoreErrorCode: coreStoreErrorCode, userInfo: nil) } internal convenience init(coreStoreErrorCode: CoreStoreErrorCode, userInfo: [NSObject: AnyObject]?) { self.init( domain: CoreStoreErrorDomain, code: coreStoreErrorCode.rawValue, userInfo: userInfo) } internal var isCoreDataMigrationError: Bool { let code = self.code return (code == NSPersistentStoreIncompatibleVersionHashError || code == NSMigrationMissingSourceModelError || code == NSMigrationError) && self.domain == NSCocoaErrorDomain } }
mit
7e02327a525fc1e6427754d4c0784a09
31.020408
140
0.688974
4.865116
false
false
false
false
inaturalist/INaturalistIOS
INaturalistIOS/Controllers/Media Picker/MediaPickerViewController.swift
1
9641
// // MediaPickerViewController.swift // iNaturalist // // Created by Alex Shepard on 5/24/20. // Copyright © 2020 iNaturalist. All rights reserved. // import UIKit import FontAwesomeKit @objc protocol MediaPickerDelegate { func choseMediaPickerItemAtIndex(_ idx: Int) } class MediaPickerViewController: UIViewController { @objc var showsNoPhotoOption = true @objc weak var mediaPickerDelegate: MediaPickerDelegate? var taxon: ExploreTaxonRealm? weak var collectionView: UICollectionView! override func viewDidLoad() { super.viewDidLoad() let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout()) collectionView.delegate = self collectionView.dataSource = self collectionView.register(MediaPickerCell.self, forCellWithReuseIdentifier: "MediaPickerCell") collectionView.backgroundColor = .white collectionView.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(collectionView) NSLayoutConstraint.activate([ collectionView.topAnchor.constraint(equalTo: self.view.topAnchor), collectionView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor), collectionView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor), collectionView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor), ]) self.collectionView = collectionView } } extension MediaPickerViewController: UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if showsNoPhotoOption { return 4 } else { return 3 } } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if showsNoPhotoOption { if indexPath.item == 0 { return noPhotoCellForItemAt(indexPath: indexPath) } else if indexPath.item == 1 { return cameraCellForItemAt(indexPath: indexPath) } else if indexPath.item == 2 { return photoLibraryCellForItemAt(indexPath: indexPath) } else { return recordSoundCellForItemAt(indexPath: indexPath) } } else { if indexPath.item == 0 { return cameraCellForItemAt(indexPath: indexPath) } else if indexPath.item == 1 { return photoLibraryCellForItemAt(indexPath: indexPath) } else { return recordSoundCellForItemAt(indexPath: indexPath) } } } func noPhotoCellForItemAt(indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MediaPickerCell", for: indexPath) as! MediaPickerCell cell.titleLabel.text = NSLocalizedString("No Photo", comment: "Title for No Photo button in media picker") if let composeIcon = FAKIonIcons.composeIcon(withSize: 50), let circleOutline = FAKIonIcons.iosCircleOutlineIcon(withSize: 80) { composeIcon.addAttribute(NSAttributedString.Key.foregroundColor.rawValue, value: UIColor.lightGray) circleOutline.addAttribute(NSAttributedString.Key.foregroundColor.rawValue, value: UIColor.lightGray) cell.iconImageView.image = UIImage(stackedIcons: [composeIcon, circleOutline], imageSize: CGSize(width: 100, height: 100)) } return cell } func cameraCellForItemAt(indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MediaPickerCell", for: indexPath) as! MediaPickerCell cell.titleLabel.text = NSLocalizedString("Camera", comment: "Title for Camera button in media picker") if let cameraIcon = FAKIonIcons.cameraIcon(withSize: 50), let circleOutline = FAKIonIcons.iosCircleOutlineIcon(withSize: 80) { cameraIcon.addAttribute(NSAttributedString.Key.foregroundColor.rawValue, value: UIColor.inatTint()) circleOutline.addAttribute(NSAttributedString.Key.foregroundColor.rawValue, value: UIColor.inatTint()) cell.iconImageView.image = UIImage(stackedIcons: [cameraIcon, circleOutline], imageSize: CGSize(width: 100, height: 100)) } return cell } func photoLibraryCellForItemAt(indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MediaPickerCell", for: indexPath) as! MediaPickerCell cell.titleLabel.text = NSLocalizedString("Photo Library", comment: "Title for Photo Library button in media picker") if let imagesIcon = FAKIonIcons.imagesIcon(withSize: 50), let circleOutline = FAKIonIcons.iosCircleOutlineIcon(withSize: 80) { imagesIcon.addAttribute(NSAttributedString.Key.foregroundColor.rawValue, value: UIColor.inatTint()) circleOutline.addAttribute(NSAttributedString.Key.foregroundColor.rawValue, value: UIColor.inatTint()) cell.iconImageView.image = UIImage(stackedIcons: [imagesIcon, circleOutline], imageSize: CGSize(width: 100, height: 100)) } return cell } func recordSoundCellForItemAt(indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MediaPickerCell", for: indexPath) as! MediaPickerCell cell.titleLabel.text = NSLocalizedString("Record Sound", comment: "Title for Camera button in media picker") if let micIcon = FAKIonIcons.micAIcon(withSize: 50), let circleOutline = FAKIonIcons.iosCircleOutlineIcon(withSize: 80) { micIcon.addAttribute(NSAttributedString.Key.foregroundColor.rawValue, value: UIColor.inatTint()) circleOutline.addAttribute(NSAttributedString.Key.foregroundColor.rawValue, value: UIColor.inatTint()) cell.iconImageView.image = UIImage(stackedIcons: [micIcon, circleOutline], imageSize: CGSize(width: 100, height: 100)) } return cell } } extension MediaPickerViewController: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { self.mediaPickerDelegate?.choseMediaPickerItemAtIndex(indexPath.item) } } extension MediaPickerViewController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: 60, height: 150) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return 1.0 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return 1.0 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { let totalCellWidth = 60 * (showsNoPhotoOption ? 3 : 2) let totalSpacingWidth = 1 * ((showsNoPhotoOption ? 3 : 2) - 1) let leftInset = (collectionView.frame.size.width - CGFloat(totalCellWidth + totalSpacingWidth)) / 2 let rightInset = leftInset print("left inset \(leftInset)") return UIEdgeInsets(top: 10, left: leftInset - 60, bottom: 0, right: rightInset - 60) } } class MediaPickerCell: UICollectionViewCell { weak var iconImageView: UIImageView! weak var titleLabel: UILabel! override init(frame: CGRect) { super.init(frame: frame) let iconImageView = UIImageView(frame: .zero) iconImageView.contentMode = .center let titleLabel = UILabel(frame: .zero) titleLabel.numberOfLines = 2 titleLabel.textAlignment = .center let stack = UIStackView(arrangedSubviews: [iconImageView, titleLabel]) stack.translatesAutoresizingMaskIntoConstraints = false stack.alignment = .center stack.distribution = .fillEqually stack.axis = .vertical stack.spacing = 0 self.contentView.addSubview(stack) NSLayoutConstraint.activate([ stack.topAnchor.constraint(equalTo: self.contentView.topAnchor), stack.bottomAnchor.constraint(equalTo: self.contentView.bottomAnchor), stack.leadingAnchor.constraint(equalTo: self.contentView.leadingAnchor), stack.trailingAnchor.constraint(equalTo: self.contentView.trailingAnchor), ]) self.titleLabel = titleLabel self.iconImageView = iconImageView } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) fatalError("Interface Builder is not supported!") } override func awakeFromNib() { super.awakeFromNib() fatalError("Interface Builder is not supported!") } override func prepareForReuse() { super.prepareForReuse() self.titleLabel.text = nil self.iconImageView.image = nil } }
mit
b6e91b014de18e58c6aa6eebe6d2da11
43.423963
175
0.690768
5.424873
false
false
false
false
zapdroid/RXWeather
Pods/Alamofire/Source/Timeline.swift
1
6908
// // Timeline.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // 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 /// Responsible for computing the timing metrics for the complete lifecycle of a `Request`. public struct Timeline { /// The time the request was initialized. public let requestStartTime: CFAbsoluteTime /// The time the first bytes were received from or sent to the server. public let initialResponseTime: CFAbsoluteTime /// The time when the request was completed. public let requestCompletedTime: CFAbsoluteTime /// The time when the response serialization was completed. public let serializationCompletedTime: CFAbsoluteTime /// The time interval in seconds from the time the request started to the initial response from the server. public let latency: TimeInterval /// The time interval in seconds from the time the request started to the time the request completed. public let requestDuration: TimeInterval /// The time interval in seconds from the time the request completed to the time response serialization completed. public let serializationDuration: TimeInterval /// The time interval in seconds from the time the request started to the time response serialization completed. public let totalDuration: TimeInterval /// Creates a new `Timeline` instance with the specified request times. /// /// - parameter requestStartTime: The time the request was initialized. Defaults to `0.0`. /// - parameter initialResponseTime: The time the first bytes were received from or sent to the server. /// Defaults to `0.0`. /// - parameter requestCompletedTime: The time when the request was completed. Defaults to `0.0`. /// - parameter serializationCompletedTime: The time when the response serialization was completed. Defaults /// to `0.0`. /// /// - returns: The new `Timeline` instance. public init( requestStartTime: CFAbsoluteTime = 0.0, initialResponseTime: CFAbsoluteTime = 0.0, requestCompletedTime: CFAbsoluteTime = 0.0, serializationCompletedTime: CFAbsoluteTime = 0.0) { self.requestStartTime = requestStartTime self.initialResponseTime = initialResponseTime self.requestCompletedTime = requestCompletedTime self.serializationCompletedTime = serializationCompletedTime latency = initialResponseTime - requestStartTime requestDuration = requestCompletedTime - requestStartTime serializationDuration = serializationCompletedTime - requestCompletedTime totalDuration = serializationCompletedTime - requestStartTime } } // MARK: - CustomStringConvertible extension Timeline: CustomStringConvertible { /// The textual representation used when written to an output stream, which includes the latency, the request /// duration and the total duration. public var description: String { let latency = String(format: "%.3f", self.latency) let requestDuration = String(format: "%.3f", self.requestDuration) let serializationDuration = String(format: "%.3f", self.serializationDuration) let totalDuration = String(format: "%.3f", self.totalDuration) // NOTE: Had to move to string concatenation due to memory leak filed as rdar://26761490. Once memory leak is // fixed, we should move back to string interpolation by reverting commit 7d4a43b1. let timings = [ "\"Latency\": " + latency + " secs", "\"Request Duration\": " + requestDuration + " secs", "\"Serialization Duration\": " + serializationDuration + " secs", "\"Total Duration\": " + totalDuration + " secs", ] return "Timeline: { " + timings.joined(separator: ", ") + " }" } } // MARK: - CustomDebugStringConvertible extension Timeline: CustomDebugStringConvertible { /// The textual representation used when written to an output stream, which includes the request start time, the /// initial response time, the request completed time, the serialization completed time, the latency, the request /// duration and the total duration. public var debugDescription: String { let requestStartTime = String(format: "%.3f", self.requestStartTime) let initialResponseTime = String(format: "%.3f", self.initialResponseTime) let requestCompletedTime = String(format: "%.3f", self.requestCompletedTime) let serializationCompletedTime = String(format: "%.3f", self.serializationCompletedTime) let latency = String(format: "%.3f", self.latency) let requestDuration = String(format: "%.3f", self.requestDuration) let serializationDuration = String(format: "%.3f", self.serializationDuration) let totalDuration = String(format: "%.3f", self.totalDuration) // NOTE: Had to move to string concatenation due to memory leak filed as rdar://26761490. Once memory leak is // fixed, we should move back to string interpolation by reverting commit 7d4a43b1. let timings = [ "\"Request Start Time\": " + requestStartTime, "\"Initial Response Time\": " + initialResponseTime, "\"Request Completed Time\": " + requestCompletedTime, "\"Serialization Completed Time\": " + serializationCompletedTime, "\"Latency\": " + latency + " secs", "\"Request Duration\": " + requestDuration + " secs", "\"Serialization Duration\": " + serializationDuration + " secs", "\"Total Duration\": " + totalDuration + " secs", ] return "Timeline: { " + timings.joined(separator: ", ") + " }" } }
mit
7a8bf9281556cf7cfcb9321b2331846a
50.17037
118
0.690359
5.261234
false
false
false
false
huonw/swift
test/SILGen/optional.swift
1
3998
// RUN: %target-swift-emit-silgen -module-name optional -enable-sil-ownership %s | %FileCheck %s func testCall(_ f: (() -> ())?) { f?() } // CHECK: sil hidden @{{.*}}testCall{{.*}} // CHECK: bb0([[T0:%.*]] : @guaranteed $Optional<@callee_guaranteed () -> ()>): // CHECK: [[T0_COPY:%.*]] = copy_value [[T0]] // CHECK-NEXT: switch_enum [[T0_COPY]] : $Optional<@callee_guaranteed () -> ()>, case #Optional.some!enumelt.1: [[SOME:bb[0-9]+]], case #Optional.none!enumelt: [[NONE:bb[0-9]+]] // // CHECK: [[NONE]]: // CHECK: br [[NOTHING_BLOCK_EXIT:bb[0-9]+]] // If it does, project and load the value out of the implicitly unwrapped // optional... // CHECK: [[SOME]]([[FN0:%.*]] : // .... then call it // CHECK-NEXT: [[B:%.*]] = begin_borrow [[FN0]] // CHECK-NEXT: apply [[B]]() // CHECK: destroy_value [[FN0]] // CHECK: br [[EXIT:bb[0-9]+]]( // (first nothing block) // CHECK: [[NOTHING_BLOCK_EXIT]]: // CHECK-NEXT: enum $Optional<()>, #Optional.none!enumelt // CHECK-NEXT: br [[EXIT]] // CHECK: } // end sil function '$S8optional8testCallyyyycSgF' func testAddrOnlyCallResult<T>(_ f: (() -> T)?) { var f = f var x = f?() } // CHECK-LABEL: sil hidden @{{.*}}testAddrOnlyCallResult{{.*}} : $@convention(thin) <T> (@guaranteed Optional<@callee_guaranteed () -> @out T>) -> () // CHECK: bb0([[T0:%.*]] : @guaranteed $Optional<@callee_guaranteed () -> @out T>): // CHECK: [[F:%.*]] = alloc_box $<τ_0_0> { var Optional<@callee_guaranteed () -> @out τ_0_0> } <T>, var, name "f" // CHECK-NEXT: [[PBF:%.*]] = project_box [[F]] // CHECK: [[T0_COPY:%.*]] = copy_value [[T0]] // CHECK: store [[T0_COPY]] to [init] [[PBF]] // CHECK-NEXT: [[X:%.*]] = alloc_box $<τ_0_0> { var Optional<τ_0_0> } <T>, var, name "x" // CHECK-NEXT: [[PBX:%.*]] = project_box [[X]] // CHECK-NEXT: [[TEMP:%.*]] = init_enum_data_addr [[PBX]] // CHECK-NEXT: [[READ:%.*]] = begin_access [read] [unknown] [[PBF]] // Check whether 'f' holds a value. // CHECK: [[HASVALUE:%.*]] = select_enum_addr [[READ]] // CHECK-NEXT: cond_br [[HASVALUE]], bb2, bb1 // If so, pull out the value... // CHECK: bb2: // CHECK-NEXT: [[T1:%.*]] = unchecked_take_enum_data_addr [[READ]] // CHECK-NEXT: [[T0:%.*]] = load [copy] [[T1]] // CHECK-NEXT: end_access [[READ]] // ...evaluate the rest of the suffix... // CHECK: [[B:%.*]] = begin_borrow [[T0]] // CHECK-NEXT: apply [[B]]([[TEMP]]) // ...and coerce to T? // CHECK: inject_enum_addr [[PBX]] {{.*}}some // CHECK: destroy_value [[T0]] // CHECK-NEXT: br bb3 // Continuation block. // CHECK: bb3 // CHECK-NEXT: destroy_value [[X]] // CHECK-NEXT: destroy_value [[F]] // CHECK-NOT: destroy_value %0 // CHECK-NEXT: [[T0:%.*]] = tuple () // CHECK-NEXT: return [[T0]] : $() // Nothing block. // CHECK: bb4: // CHECK-NEXT: inject_enum_addr [[PBX]] {{.*}}none // CHECK-NEXT: br bb3 // <rdar://problem/15180622> func wrap<T>(_ x: T) -> T? { return x } // CHECK-LABEL: sil hidden @$S8optional16wrap_then_unwrap{{[_0-9a-zA-Z]*}}F func wrap_then_unwrap<T>(_ x: T) -> T { // CHECK: switch_enum_addr {{.*}}, case #Optional.some!enumelt.1: [[OK:bb[0-9]+]], case #Optional.none!enumelt: [[FAIL:bb[0-9]+]] // CHECK: [[FAIL]]: // CHECK: unreachable // CHECK: [[OK]]: // CHECK: unchecked_take_enum_data_addr return wrap(x)! } // CHECK-LABEL: sil hidden @$S8optional10tuple_bind{{[_0-9a-zA-Z]*}}F func tuple_bind(_ x: (Int, String)?) -> String? { return x?.1 // CHECK: switch_enum {{%.*}}, case #Optional.some!enumelt.1: [[NONNULL:bb[0-9]+]], case #Optional.none!enumelt: [[NULL:bb[0-9]+]] // CHECK: [[NONNULL]]( // CHECK: [[STRING:%.*]] = tuple_extract {{%.*}} : $(Int, String), 1 // CHECK-NOT: destroy_value [[STRING]] } // rdar://21883752 - We were crashing on this function because the deallocation happened // out of scope. // CHECK-LABEL: sil hidden @$S8optional16crash_on_deallocyys10DictionaryVySiSaySiGGFfA_ func crash_on_dealloc(_ dict : [Int : [Int]] = [:]) { var dict = dict dict[1]?.append(2) }
apache-2.0
69b466ce82b51c3e4a3d098e5fc663a1
37.776699
177
0.57336
2.956329
false
false
false
false
ambientlight/Perfect
Tests/PerfectLibTests/XCTestManifests.swift
3
697
// // XCTestManifests.swift // // Created by Kyle Jessup on 2015-10-19. // Copyright © 2015 PerfectlySoft. All rights reserved. // //===----------------------------------------------------------------------===// // // This source file is part of the Perfect.org open source project // // Copyright (c) 2015 - 2016 PerfectlySoft Inc. and the Perfect project authors // Licensed under Apache License v2.0 // // See http://perfect.org/licensing.html for license information // //===----------------------------------------------------------------------===// // import XCTest #if !os(OSX) public func allTests() -> [XCTestCaseEntry] { return [ testCase(PerfectLibTests.allTests) ] } #endif
apache-2.0
bd1a6e4f6c40f68fabdece018264d8a9
24.777778
80
0.54454
4.519481
false
true
false
false
huonw/swift
test/attr/attr_objc_clang.swift
28
1228
// RUN: %target-typecheck-verify-swift -sdk %S/Inputs -I %S/Inputs/custom-modules -I %S/../Inputs/custom-modules // RUN: %target-swift-ide-test -print-ast-typechecked -source-filename %s -sdk %S/Inputs -I %S/Inputs/custom-modules -I %S/../Inputs/custom-modules -function-definitions=true -prefer-type-repr=false -print-implicit-attrs=true -explode-pattern-binding-decls=true -disable-objc-attr-requires-foundation-module | %FileCheck %s // REQUIRES: objc_interop import AttrObjc_FooClangModule import ObjCRuntimeVisible @objc class infer_instanceVar1 { // CHECK-LABEL: @objc class infer_instanceVar1 { var var_ClangEnum: FooEnum1 var var_ClangStruct: FooStruct1 // CHECK-LABEL: @objc var var_ClangEnum: FooEnum1 // CHECK-LABEL: @objc var var_ClangStruct: FooStruct1 init(fe: FooEnum1, fs: FooStruct1) { var_ClangEnum = fe var_ClangStruct = fs } } class ObjC_Class1 : NSObject, Hashable { var hashValue: Int { return 0 } } func ==(lhs: ObjC_Class1, rhs: ObjC_Class1) -> Bool { return true } @objc class ObjC_Class2 : Hashable { var hashValue: Int { return 0 } } func ==(lhs: ObjC_Class2, rhs: ObjC_Class2) -> Bool { return true } extension A { // CHECK: {{^}} func foo() func foo() { } }
apache-2.0
4e1996099cadc5366cbb1608d0496cea
27.55814
324
0.706026
3.18961
false
false
false
false
WE-St0r/SwiftyVK
Library/Sources/Sharing/ShareContext.swift
2
2488
import Foundation public struct ShareContext: Equatable { var message: String? let images: [ShareImage] let link: ShareLink? let canShowError: Bool var preferences = [ShareContextPreference]() var hasAttachments: Bool { return images.isEmpty || link != nil } public init( text: String? = nil, images: [ShareImage] = [], link: ShareLink? = nil, canShowError: Bool = true ) { self.message = text self.images = images self.link = link self.canShowError = canShowError } public static func == (lhs: ShareContext, rhs: ShareContext) -> Bool { return lhs.message == rhs.message && lhs.images == rhs.images && lhs.link == rhs.link } } public struct ShareLink: Equatable { let title: String let url: URL public init( title: String, url: URL ) { self.title = title self.url = url } public static func == (lhs: ShareLink, rhs: ShareLink) -> Bool { return lhs.title == rhs.title && lhs.url == rhs.url } } public final class ShareImage: Equatable { let data: Data let type: ImageType var id: String? var state: ShareImageUploadState = .initial { didSet { switch state { case .uploaded: onUpload?() case .failed: onFail?() default: break } } } private var onUpload: (() -> ())? private var onFail: (() -> ())? public init(data: Data, type: ImageType) { self.data = data self.type = type } func setOnUpload(_ onUpload: @escaping (() -> ())) { self.onUpload = onUpload } func setOnFail(_ onFail: @escaping (() -> ())) { self.onFail = onFail } public static func == (lhs: ShareImage, rhs: ShareImage) -> Bool { return lhs.data == rhs.data } } enum ShareImageUploadState: Equatable { case initial case uploading case uploaded case failed } final class ShareContextPreference { let key: String let name: String var active: Bool init(key: String, name: String, active: Bool) { self.key = key self.name = name self.active = active } } struct ShareContextPreferencesSet { let twitter: Bool let facebook: Bool let livejournal: Bool }
mit
b4036d43ff0be3653fc9d79e67059d6d
21.214286
93
0.547026
4.34965
false
false
false
false
Cellane/iWeb
Sources/App/Controllers/API/RoleController.swift
1
894
import Vapor import AuthProvider extension Controllers.API { final class RoleController { private let droplet: Droplet init(droplet: Droplet) { self.droplet = droplet } func addRoutes() { let role = droplet.grouped(["api", "role"]) let adminAuthorized = role.grouped(TokenRolesMiddleware(User.self, roles: [Role.admin])) adminAuthorized.get(handler: index) adminAuthorized.post(handler: store) adminAuthorized.delete(Role.parameter, handler: delete) } func index(req: Request) throws -> ResponseRepresentable { return try Role.all().makeJSON() } func store(req: Request) throws -> ResponseRepresentable { let role = try req.role() try role.save() return role } func delete(req: Request) throws -> ResponseRepresentable { let role = try req.parameters.next(Role.self) try role.delete() return Response(status: .ok) } } }
mit
9edb843c8238bf2d6b98a47c00fd55b4
20.804878
91
0.701342
3.590361
false
false
false
false
zmian/xcore.swift
Sources/Xcore/Cocoa/Components/Anchor/Anchor+Attributes.swift
1
5226
// // Xcore // Copyright © 2019 Xcore // MIT license, see LICENSE file for details // import UIKit extension Anchor { struct Attributes: OptionSet { let rawValue: Int init(rawValue: Int) { self.rawValue = rawValue } static let top = Attributes(rawValue: 1 << 0) static let bottom = Attributes(rawValue: 1 << 1) static let leading = Attributes(rawValue: 1 << 2) static let trailing = Attributes(rawValue: 1 << 3) static let width = Attributes(rawValue: 1 << 4) static let height = Attributes(rawValue: 1 << 5) static let centerX = Attributes(rawValue: 1 << 6) static let centerY = Attributes(rawValue: 1 << 7) static let firstBaseline = Attributes(rawValue: 1 << 8) static let lastBaseline = Attributes(rawValue: 1 << 9) static let vertical: Attributes = [top, bottom] static let horizontal: Attributes = [leading, trailing] static let edges: Attributes = [vertical, horizontal] static let size: Attributes = [width, height] static let center: Attributes = [centerX, centerY] static func related(to attribute: Attributes) -> [Attributes] { switch attribute { case .top: return [.top, .bottom, .centerY, .firstBaseline, .lastBaseline] case .bottom: return [.bottom, .top, .centerY, .firstBaseline, .lastBaseline] case .centerY: return [centerY, .top, .bottom, .firstBaseline, .lastBaseline] case .firstBaseline: return [.firstBaseline, .lastBaseline, .top, .bottom, .centerY] case .lastBaseline: return [.lastBaseline, .firstBaseline, .top, .bottom, .centerY] case .centerX: return [centerX, .leading, .trailing] case .leading: return [.leading, .trailing, .centerX] case .trailing: return [.trailing, .leading, .centerX] case .width: return [.width, .height] case .height: return [.height, .width] default: fatalError("Detected unknown attribute: \(attribute).") } } } } extension Anchor.Attributes { func yAxisAnchor( _ view: UIView, safeAreaLayoutGuideOptions: SafeAreaLayoutGuideOptions, preferred: [Anchor.Attributes], file: StaticString = #file, line: UInt = #line ) -> NSLayoutAnchor<NSLayoutYAxisAnchor> { func inner(_ attribute: Anchor.Attributes) -> NSLayoutAnchor<NSLayoutYAxisAnchor> { switch attribute { case .top: return safeAreaLayoutGuideOptions.topAnchor(view) case .bottom: return safeAreaLayoutGuideOptions.bottomAnchor(view) case .centerY: return view.centerYAnchor case .firstBaseline: return view.firstBaselineAnchor case .lastBaseline: return view.lastBaselineAnchor default: fatalError("Unable to find appropriate Y-Axis anchor.", file: file, line: line) } } for attr in preferred where contains(attr) { return inner(attr) } return inner(self) } func xAxisAnchor( _ view: UIView, safeAreaLayoutGuideOptions: SafeAreaLayoutGuideOptions, preferred: [Anchor.Attributes], file: StaticString = #file, line: UInt = #line ) -> NSLayoutAnchor<NSLayoutXAxisAnchor> { func inner(_ attribute: Anchor.Attributes) -> NSLayoutAnchor<NSLayoutXAxisAnchor> { switch attribute { case .leading: return safeAreaLayoutGuideOptions.leadingAnchor(view) case .trailing: return safeAreaLayoutGuideOptions.trailingAnchor(view) case .centerX: return view.centerXAnchor default: fatalError("Unable to find appropriate X-Axis anchor.", file: file, line: line) } } for attr in preferred where contains(attr) { return inner(attr) } return inner(self) } func dimensionAnchor( _ view: UIView, preferred: [Anchor.Attributes], file: StaticString = #file, line: UInt = #line ) -> NSLayoutAnchor<NSLayoutDimension> { func inner(_ attribute: Anchor.Attributes) -> NSLayoutAnchor<NSLayoutDimension> { switch self { case .width: return view.widthAnchor case .height: return view.heightAnchor default: fatalError("Unable to find appropriate dimension anchor.", file: file, line: line) } } for attr in preferred where contains(attr) { return inner(attr) } return inner(self) } }
mit
e4359e1c90f52f9c3b8f21d198b07295
33.375
102
0.547943
5.386598
false
false
false
false
StYaphet/firefox-ios
Client/Frontend/Browser/LocalRequestHelper.swift
6
1469
/* 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 WebKit import Shared class LocalRequestHelper: TabContentScript { func scriptMessageHandlerName() -> String? { return "localRequestHelper" } func userContentController(_ userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) { guard let requestUrl = message.frameInfo.request.url, let internalUrl = InternalURL(requestUrl) else { return } let params = message.body as! [String: String] guard let token = params["securitytoken"], token == UserScriptManager.securityToken else { print("Missing required security token.") return } if params["type"] == "reload" { // If this is triggered by session restore pages, the url to reload is a nested url argument. if let _url = internalUrl.extractedUrlParam, let nested = InternalURL(_url), let url = nested.extractedUrlParam { message.webView?.replaceLocation(with: url) } else { _ = message.webView?.reload() } } else { assertionFailure("Invalid message: \(message.body)") } } class func name() -> String { return "LocalRequestHelper" } }
mpl-2.0
b318fc166c2cecad7dad3e616a37f0b7
36.666667
132
0.650102
4.864238
false
false
false
false
sunfei/realm-cocoa
RealmSwift-swift2.0/RealmCollectionType.swift
16
23977
//////////////////////////////////////////////////////////////////////////// // // Copyright 2014 Realm Inc. // // 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 import Realm /** Encapsulates iteration state and interface for iteration over a `RealmCollectionType`. */ public final class RLMGenerator<T: Object>: GeneratorType { private let generatorBase: NSFastGenerator internal init(collection: RLMCollection) { generatorBase = NSFastGenerator(collection) } /// Advance to the next element and return it, or `nil` if no next element /// exists. public func next() -> T? { let accessor = generatorBase.next() as! T? if let accessor = accessor { RLMInitializeSwiftListAccessor(accessor) } return accessor } } /** A homogenous collection of `Object`s which can be retrieved, filtered, sorted, and operated upon. */ public protocol RealmCollectionType: CollectionType, CustomStringConvertible { /// Element type contained in this collection. typealias Element: Object // MARK: Properties /// The Realm the objects in this collection belong to, or `nil` if the /// collection's owning object does not belong to a realm (the collection is /// standalone). var realm: Realm? { get } /// Returns the number of objects in this collection. var count: Int { get } /// Returns a human-readable description of the objects contained in this collection. var description: String { get } // MARK: Index Retrieval /** Returns the index of the given object, or `nil` if the object is not in the collection. - parameter object: The object whose index is being queried. - returns: The index of the given object, or `nil` if the object is not in the collection. */ func indexOf(object: Element) -> Int? /** Returns the index of the first object matching the given predicate, or `nil` no objects match. - parameter predicate: The `NSPredicate` used to filter the objects. - returns: The index of the given object, or `nil` if no objects match. */ func indexOf(predicate: NSPredicate) -> Int? /** Returns the index of the first object matching the given predicate, or `nil` if no objects match. - parameter predicateFormat: The predicate format string, optionally followed by a variable number of arguments. - returns: The index of the given object, or `nil` if no objects match. */ func indexOf(predicateFormat: String, _ args: AnyObject...) -> Int? // MARK: Filtering /** Returns `Results` containing collection elements that match the given predicate. - parameter predicateFormat: The predicate format string which can accept variable arguments. - returns: `Results` containing collection elements that match the given predicate. */ func filter(predicateFormat: String, _ args: AnyObject...) -> Results<Element> /** Returns `Results` containing collection elements that match the given predicate. - parameter predicate: The predicate to filter the objects. - returns: `Results` containing collection elements that match the given predicate. */ func filter(predicate: NSPredicate) -> Results<Element> // MARK: Sorting /** Returns `Results` containing collection elements sorted by the given property. - parameter property: The property name to sort by. - parameter ascending: The direction to sort by. - returns: `Results` containing collection elements sorted by the given property. */ func sorted(property: String, ascending: Bool) -> Results<Element> /** Returns `Results` with elements sorted by the given sort descriptors. - parameter sortDescriptors: `SortDescriptor`s to sort by. - returns: `Results` with elements sorted by the given sort descriptors. */ func sorted<S: SequenceType where S.Generator.Element == SortDescriptor>(sortDescriptors: S) -> Results<Element> // MARK: Aggregate Operations /** Returns the minimum value of the given property. - warning: Only names of properties of a type conforming to the `MinMaxType` protocol can be used. - parameter property: The name of a property conforming to `MinMaxType` to look for a minimum on. - returns: The minimum value for the property amongst objects in the collection, or `nil` if the collection is empty. */ func min<U: MinMaxType>(property: String) -> U? /** Returns the maximum value of the given property. - warning: Only names of properties of a type conforming to the `MinMaxType` protocol can be used. - parameter property: The name of a property conforming to `MinMaxType` to look for a maximum on. - returns: The maximum value for the property amongst objects in the collection, or `nil` if the collection is empty. */ func max<U: MinMaxType>(property: String) -> U? /** Returns the sum of the given property for objects in the collection. - warning: Only names of properties of a type conforming to the `AddableType` protocol can be used. - parameter property: The name of a property conforming to `AddableType` to calculate sum on. - returns: The sum of the given property over all objects in the collection. */ func sum<U: AddableType>(property: String) -> U /** Returns the average of the given property for objects in the collection. - warning: Only names of properties of a type conforming to the `AddableType` protocol can be used. - parameter property: The name of a property conforming to `AddableType` to calculate average on. - returns: The average of the given property over all objects in the collection, or `nil` if the collection is empty. */ func average<U: AddableType>(property: String) -> U? // MARK: Key-Value Coding /** Returns an Array containing the results of invoking `valueForKey:` using key on each of the collection's objects. - parameter key: The name of the property. - returns: Array containing the results of invoking `valueForKey:` using key on each of the collection's objects. */ func valueForKey(key: String) -> AnyObject? /** Invokes `setValue:forKey:` on each of the collection's objects using the specified value and key. :warning: This method can only be called during a write transaction. - parameter value: The object value. - parameter key: The name of the property. */ func setValue(value: AnyObject?, forKey key: String) } private class _AnyRealmCollectionBase<T: Object>: RealmCollectionType { typealias Element = T var realm: Realm? { fatalError() } var count: Int { fatalError() } var description: String { fatalError() } func indexOf(object: Element) -> Int? { fatalError() } func indexOf(predicate: NSPredicate) -> Int? { fatalError() } func indexOf(predicateFormat: String, _ args: AnyObject...) -> Int? { fatalError() } func filter(predicateFormat: String, _ args: AnyObject...) -> Results<Element> { fatalError() } func filter(predicate: NSPredicate) -> Results<Element> { fatalError() } func sorted(property: String, ascending: Bool) -> Results<Element> { fatalError() } func sorted<S: SequenceType where S.Generator.Element == SortDescriptor>(sortDescriptors: S) -> Results<Element> { fatalError() } func min<U: MinMaxType>(property: String) -> U? { fatalError() } func max<U: MinMaxType>(property: String) -> U? { fatalError() } func sum<U: AddableType>(property: String) -> U { fatalError() } func average<U: AddableType>(property: String) -> U? { fatalError() } subscript(index: Int) -> Element { fatalError() } func generate() -> RLMGenerator<T> { fatalError() } var startIndex: Int { fatalError() } var endIndex: Int { fatalError() } func valueForKey(key: String) -> AnyObject? { fatalError() } func setValue(value: AnyObject?, forKey key: String) { fatalError() } } private final class _AnyRealmCollection<C: RealmCollectionType>: _AnyRealmCollectionBase<C.Element> { let base: C init(base: C) { self.base = base } // MARK: Properties /// The Realm the objects in this collection belong to, or `nil` if the /// collection's owning object does not belong to a realm (the collection is /// standalone). override var realm: Realm? { return base.realm } /// Returns the number of objects in this collection. override var count: Int { return base.count } /// Returns a human-readable description of the objects contained in this collection. override var description: String { return base.description } // MARK: Index Retrieval /** Returns the index of the given object, or `nil` if the object is not in the collection. - parameter object: The object whose index is being queried. - returns: The index of the given object, or `nil` if the object is not in the collection. */ override func indexOf(object: C.Element) -> Int? { return base.indexOf(object) } /** Returns the index of the first object matching the given predicate, or `nil` no objects match. - parameter predicate: The `NSPredicate` used to filter the objects. - returns: The index of the given object, or `nil` if no objects match. */ override func indexOf(predicate: NSPredicate) -> Int? { return base.indexOf(predicate) } /** Returns the index of the first object matching the given predicate, or `nil` if no objects match. - parameter predicateFormat: The predicate format string, optionally followed by a variable number of arguments. - returns: The index of the given object, or `nil` if no objects match. */ override func indexOf(predicateFormat: String, _ args: AnyObject...) -> Int? { return base.indexOf(NSPredicate(format: predicateFormat, argumentArray: args)) } // MARK: Filtering /** Returns `Results` containing collection elements that match the given predicate. - parameter predicateFormat: The predicate format string which can accept variable arguments. - returns: `Results` containing collection elements that match the given predicate. */ override func filter(predicateFormat: String, _ args: AnyObject...) -> Results<C.Element> { return base.filter(NSPredicate(format: predicateFormat, argumentArray: args)) } /** Returns `Results` containing collection elements that match the given predicate. - parameter predicate: The predicate to filter the objects. - returns: `Results` containing collection elements that match the given predicate. */ override func filter(predicate: NSPredicate) -> Results<C.Element> { return base.filter(predicate) } // MARK: Sorting /** Returns `Results` containing collection elements sorted by the given property. - parameter property: The property name to sort by. - parameter ascending: The direction to sort by. - returns: `Results` containing collection elements sorted by the given property. */ override func sorted(property: String, ascending: Bool) -> Results<C.Element> { return base.sorted(property, ascending: ascending) } /** Returns `Results` with elements sorted by the given sort descriptors. - parameter sortDescriptors: `SortDescriptor`s to sort by. - returns: `Results` with elements sorted by the given sort descriptors. */ override func sorted<S: SequenceType where S.Generator.Element == SortDescriptor>(sortDescriptors: S) -> Results<C.Element> { return base.sorted(sortDescriptors) } // MARK: Aggregate Operations /** Returns the minimum value of the given property. - warning: Only names of properties of a type conforming to the `MinMaxType` protocol can be used. - parameter property: The name of a property conforming to `MinMaxType` to look for a minimum on. - returns: The minimum value for the property amongst objects in the collection, or `nil` if the collection is empty. */ override func min<U: MinMaxType>(property: String) -> U? { return base.min(property) } /** Returns the maximum value of the given property. - warning: Only names of properties of a type conforming to the `MinMaxType` protocol can be used. - parameter property: The name of a property conforming to `MinMaxType` to look for a maximum on. - returns: The maximum value for the property amongst objects in the collection, or `nil` if the collection is empty. */ override func max<U: MinMaxType>(property: String) -> U? { return base.max(property) } /** Returns the sum of the given property for objects in the collection. - warning: Only names of properties of a type conforming to the `AddableType` protocol can be used. - parameter property: The name of a property conforming to `AddableType` to calculate sum on. - returns: The sum of the given property over all objects in the collection. */ override func sum<U: AddableType>(property: String) -> U { return base.sum(property) } /** Returns the average of the given property for objects in the collection. - warning: Only names of properties of a type conforming to the `AddableType` protocol can be used. - parameter property: The name of a property conforming to `AddableType` to calculate average on. - returns: The average of the given property over all objects in the collection, or `nil` if the collection is empty. */ override func average<U: AddableType>(property: String) -> U? { return base.average(property) } // MARK: Sequence Support /** Returns the object at the given `index`. - parameter index: The index. - returns: The object at the given `index`. */ override subscript(index: Int) -> C.Element { return unsafeBitCast(base[index as! C.Index], C.Element.self) } // FIXME: it should be possible to avoid this force-casting /// Returns a `GeneratorOf<Element>` that yields successive elements in the collection. override func generate() -> RLMGenerator<Element> { return base.generate() as! RLMGenerator<Element> } // FIXME: it should be possible to avoid this force-casting // MARK: Collection Support /// The position of the first element in a non-empty collection. /// Identical to endIndex in an empty collection. override var startIndex: Int { return base.startIndex as! Int } // FIXME: it should be possible to avoid this force-casting /// The collection's "past the end" position. /// endIndex is not a valid argument to subscript, and is always reachable from startIndex by zero or more applications of successor(). override var endIndex: Int { return base.endIndex as! Int } // FIXME: it should be possible to avoid this force-casting // MARK: Key-Value Coding /** Returns an Array containing the results of invoking `valueForKey:` using key on each of the collection's objects. - parameter key: The name of the property. - returns: Array containing the results of invoking `valueForKey:` using key on each of the collection's objects. */ override func valueForKey(key: String) -> AnyObject? { return base.valueForKey(key) } /** Invokes `setValue:forKey:` on each of the collection's objects using the specified value and key. :warning: This method can only be called during a write transaction. - parameter value: The object value. - parameter key: The name of the property. */ override func setValue(value: AnyObject?, forKey key: String) { base.setValue(value, forKey: key) } } /** A type-erased `RealmCollectionType`. Forwards operations to an arbitrary underlying collection having the same Element type, hiding the specifics of the underlying `RealmCollectionType`. */ public final class AnyRealmCollection<T: Object>: RealmCollectionType { /// Element type contained in this collection. public typealias Element = T private let base: _AnyRealmCollectionBase<T> /// Creates an AnyRealmCollection wrapping `base`. public init<C: RealmCollectionType where C.Element == T>(_ base: C) { self.base = _AnyRealmCollection(base: base) } // MARK: Properties /// The Realm the objects in this collection belong to, or `nil` if the /// collection's owning object does not belong to a realm (the collection is /// standalone). public var realm: Realm? { return base.realm } /// Returns the number of objects in this collection. public var count: Int { return base.count } /// Returns a human-readable description of the objects contained in this collection. public var description: String { return base.description } // MARK: Index Retrieval /** Returns the index of the given object, or `nil` if the object is not in the collection. - parameter object: The object whose index is being queried. - returns: The index of the given object, or `nil` if the object is not in the collection. */ public func indexOf(object: Element) -> Int? { return base.indexOf(object) } /** Returns the index of the first object matching the given predicate, or `nil` no objects match. - parameter predicate: The `NSPredicate` used to filter the objects. - returns: The index of the given object, or `nil` if no objects match. */ public func indexOf(predicate: NSPredicate) -> Int? { return base.indexOf(predicate) } /** Returns the index of the first object matching the given predicate, or `nil` if no objects match. - parameter predicateFormat: The predicate format string, optionally followed by a variable number of arguments. - returns: The index of the given object, or `nil` if no objects match. */ public func indexOf(predicateFormat: String, _ args: AnyObject...) -> Int? { return base.indexOf(NSPredicate(format: predicateFormat, argumentArray: args)) } // MARK: Filtering /** Returns `Results` containing collection elements that match the given predicate. - parameter predicateFormat: The predicate format string which can accept variable arguments. - returns: `Results` containing collection elements that match the given predicate. */ public func filter(predicateFormat: String, _ args: AnyObject...) -> Results<Element> { return base.filter(NSPredicate(format: predicateFormat, argumentArray: args)) } /** Returns `Results` containing collection elements that match the given predicate. - parameter predicate: The predicate to filter the objects. - returns: `Results` containing collection elements that match the given predicate. */ public func filter(predicate: NSPredicate) -> Results<Element> { return base.filter(predicate) } // MARK: Sorting /** Returns `Results` containing collection elements sorted by the given property. - parameter property: The property name to sort by. - parameter ascending: The direction to sort by. - returns: `Results` containing collection elements sorted by the given property. */ public func sorted(property: String, ascending: Bool) -> Results<Element> { return base.sorted(property, ascending: ascending) } /** Returns `Results` with elements sorted by the given sort descriptors. - parameter sortDescriptors: `SortDescriptor`s to sort by. - returns: `Results` with elements sorted by the given sort descriptors. */ public func sorted<S: SequenceType where S.Generator.Element == SortDescriptor>(sortDescriptors: S) -> Results<Element> { return base.sorted(sortDescriptors) } // MARK: Aggregate Operations /** Returns the minimum value of the given property. - warning: Only names of properties of a type conforming to the `MinMaxType` protocol can be used. - parameter property: The name of a property conforming to `MinMaxType` to look for a minimum on. - returns: The minimum value for the property amongst objects in the collection, or `nil` if the collection is empty. */ public func min<U: MinMaxType>(property: String) -> U? { return base.min(property) } /** Returns the maximum value of the given property. - warning: Only names of properties of a type conforming to the `MinMaxType` protocol can be used. - parameter property: The name of a property conforming to `MinMaxType` to look for a maximum on. - returns: The maximum value for the property amongst objects in the collection, or `nil` if the collection is empty. */ public func max<U: MinMaxType>(property: String) -> U? { return base.max(property) } /** Returns the sum of the given property for objects in the collection. - warning: Only names of properties of a type conforming to the `AddableType` protocol can be used. - parameter property: The name of a property conforming to `AddableType` to calculate sum on. - returns: The sum of the given property over all objects in the collection. */ public func sum<U: AddableType>(property: String) -> U { return base.sum(property) } /** Returns the average of the given property for objects in the collection. - warning: Only names of properties of a type conforming to the `AddableType` protocol can be used. - parameter property: The name of a property conforming to `AddableType` to calculate average on. - returns: The average of the given property over all objects in the collection, or `nil` if the collection is empty. */ public func average<U: AddableType>(property: String) -> U? { return base.average(property) } // MARK: Sequence Support /** Returns the object at the given `index`. - parameter index: The index. - returns: The object at the given `index`. */ public subscript(index: Int) -> T { return base[index] } /// Returns a `GeneratorOf<T>` that yields successive elements in the collection. public func generate() -> RLMGenerator<T> { return base.generate() } // MARK: Collection Support /// The position of the first element in a non-empty collection. /// Identical to endIndex in an empty collection. public var startIndex: Int { return base.startIndex } /// The collection's "past the end" position. /// endIndex is not a valid argument to subscript, and is always reachable from startIndex by zero or more applications of successor(). public var endIndex: Int { return base.endIndex } // MARK: Key-Value Coding /** Returns an Array containing the results of invoking `valueForKey:` using key on each of the collection's objects. - parameter key: The name of the property. - returns: Array containing the results of invoking `valueForKey:` using key on each of the collection's objects. */ public func valueForKey(key: String) -> AnyObject? { return base.valueForKey(key) } /** Invokes `setValue:forKey:` on each of the collection's objects using the specified value and key. :warning: This method can only be called during a write transaction. - parameter value: The object value. - parameter key: The name of the property. */ public func setValue(value: AnyObject?, forKey key: String) { base.setValue(value, forKey: key) } }
apache-2.0
9da8ae899f8d883f52973fe414be4d68
37.301917
175
0.697835
4.684838
false
false
false
false
hachinobu/CleanQiitaClient
PresentationLayer/Routing/Auth/AuthScreenRouting.swift
1
1532
// // AuthScreenRouting.swift // CleanQiitaClient // // Created by Takahiro Nishinobu on 2016/09/23. // Copyright © 2016年 hachinobu. All rights reserved. // import Foundation //import DataLayer //import DomainLayer public protocol AuthScreenRouting: Routing { func segueAllItemListScreen() } //public struct AuthScreenRoutingImpl: AuthScreenRouting { // // weak public var viewController: UIViewController? // // public init() { // // } // // public func segueAllItemListScreen() { // // let repository = ItemListRepositoryImpl.shared // let useCase = AllItemListUseCaseImpl(repository: repository) // let presenter = AllItemListPresenterImpl(useCase: useCase) // // let navigationController = UIStoryboard(name: "ItemListScreen", bundle: Bundle(for: ItemListViewController.self)).instantiateInitialViewController() as! UINavigationController // let viewController = navigationController.topViewController as! ItemListViewController // // let routing = AllItemListRoutingImpl() // routing.viewController = viewController // viewController.injection(presenter: presenter, routing: routing) // // UIApplication.shared.delegate?.window!?.rootViewController = navigationController // let appDelegate = UIApplication.shared.delegate // appDelegate?.window??.rootViewController = navigationController // appDelegate?.window??.makeKeyAndVisible() // // } // //}
mit
753d9854cb470ce057fefbd6d75b9a2d
32.977778
185
0.689993
4.647416
false
false
false
false
StevenDXC/SwiftDemo
Carthage/Checkouts/PromiseKit/Categories/UIKit/UIAlertView+Promise.swift
2
1553
import Foundation import UIKit.UIAlertView #if !COCOAPODS import PromiseKit #endif /** To import the `UIActionSheet` category: use_frameworks! pod "PromiseKit/UIKit" Or `UIKit` is one of the categories imported by the umbrella pod: use_frameworks! pod "PromiseKit" And then in your sources: import PromiseKit */ extension UIAlertView { public func promise() -> Promise<Int> { let proxy = PMKAlertViewDelegate() delegate = proxy proxy.retainCycle = proxy show() if numberOfButtons == 1 && cancelButtonIndex == 0 { NSLog("PromiseKit: An alert view is being promised with a single button that is set as the cancelButtonIndex. The promise *will* be cancelled which may result in unexpected behavior. See http://promisekit.org/PromiseKit-2.0-Released/ for cancellation documentation.") } return proxy.promise } } public enum UIAlertViewError: CancellableErrorType { case Cancelled public var cancelled: Bool { switch self { case .Cancelled: return true } } } private class PMKAlertViewDelegate: NSObject, UIAlertViewDelegate { let (promise, fulfill, reject) = Promise<Int>.pendingPromise() var retainCycle: NSObject? @objc func alertView(alertView: UIAlertView, didDismissWithButtonIndex buttonIndex: Int) { if buttonIndex != alertView.cancelButtonIndex { fulfill(buttonIndex) } else { reject(UIAlertViewError.Cancelled) } } }
mit
e51b95dafa08aa66e327f2519457c434
25.775862
279
0.669028
4.977564
false
false
false
false
nmartinson/Bluetooth-Camera-Controller
BLE Test/BLEAppDelegate.swift
1
3559
// // BLEAppDelegate.swift // Adafruit Bluefruit LE Connect // // Created by Collin Cunningham on 10/13/14. // Copyright (c) 2014 Adafruit Industries. All rights reserved. // import Foundation import UIKit @UIApplicationMain class BLEAppDelegate: UIResponder, UIApplicationDelegate { var window:UIWindow? var mainViewController:BLEMainViewController? required override init() { super.init() } func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool { window = UIWindow(frame: UIScreen.mainScreen().bounds) // Load NIB based on current platform var nibName:String nibName = "BLEMainViewController_iPhone" self.mainViewController = BLEMainViewController(nibName: nibName, bundle: NSBundle.mainBundle()) //TODO: check for redundancy window!.rootViewController = mainViewController window!.makeKeyAndVisible() return true } func applicationWillResignActive(application: UIApplication) { // Stop scanning before entering background mainViewController?.stopScan() //TEST NOTIFICATION // let note = UILocalNotification() // note.fireDate = NSDate().dateByAddingTimeInterval(5.0) // note.alertBody = "THIS IS A TEST" // note.soundName = UILocalNotificationDefaultSoundName // application.scheduleLocalNotification(note) } func applicationDidBecomeActive(application: UIApplication) { mainViewController?.didBecomeActive() } func applicationWillTerminate(application: UIApplication) { println("application will terminate") } // // - (void)applicationWillResignActive:(UIApplication*)application // { // // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. // } // // - (void)applicationDidEnterBackground:(UIApplication*)application // { // // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. // } // // - (void)applicationWillEnterForeground:(UIApplication*)application // { // // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. // } // // - (void)applicationDidBecomeActive:(UIApplication*)application // { // // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. // } // // - (void)applicationWillTerminate:(UIApplication*)application // { // // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // } }
bsd-3-clause
6a0513f1cf740bf03bf6002a773a5a14
37.684783
283
0.69261
5.31194
false
false
false
false
cpuu/OTT
OTT/Utils/ProgressView.swift
2
1851
// // ProgressView.swift // BlueCap // // Created by Troy Stribling on 7/20/14. // Copyright (c) 2014 Troy Stribling. The MIT License (MIT). // import UIKit class ProgressView : UIView { let BACKGROUND_ALPHA : CGFloat = 0.6 let DISPLAY_REMOVE_DURATION : NSTimeInterval = 0.5 var activityIndicator : UIActivityIndicatorView! var backgroundView : UIView! var displayed = false required init?(coder aDecoder: NSCoder) { super.init(coder:aDecoder) } override init(frame:CGRect) { super.init(frame:frame) self.activityIndicator = UIActivityIndicatorView(activityIndicatorStyle:UIActivityIndicatorViewStyle.WhiteLarge) self.activityIndicator.center = self.center self.backgroundView = UIView(frame:frame) self.backgroundView.backgroundColor = UIColor.blackColor() self.backgroundView.alpha = BACKGROUND_ALPHA self.addSubview(self.backgroundView) self.addSubview(self.activityIndicator) } convenience init() { self.init(frame:UIScreen.mainScreen().bounds) } func show() { if let keyWindow = UIApplication.sharedApplication().keyWindow { self.show(keyWindow) } } func show(view:UIView) { if !self.displayed { self.displayed = true self.activityIndicator.startAnimating() view.addSubview(self) } } func remove() { if self.displayed { self.displayed = false UIView.animateWithDuration(DISPLAY_REMOVE_DURATION, animations:{ self.alpha = 0.0 }, completion:{(finished) in self.removeFromSuperview() self.alpha = 1.0 }) } } }
mit
0247ead9131614030e9e9fe27cea913b
27.476923
120
0.595894
4.909814
false
false
false
false
darren90/rubbish
Example-Swift/SwiftExample/DelegateAppearanceViewController.swift
1
6306
// // DelegateAppearanceViewController.swift // SwiftExample // // Created by dingwenchao on 30/12/2016. // Copyright © 2016 wenchao. All rights reserved. // import UIKit class DelegateAppearanceViewController: UIViewController, FSCalendarDataSource, FSCalendarDelegate, FSCalendarDelegateAppearance { fileprivate weak var calendar: FSCalendar! fileprivate let gregorian: Calendar = Calendar(identifier: .gregorian) fileprivate lazy var dateFormatter1: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "yyyy/MM/dd" return formatter }() fileprivate lazy var dateFormatter2: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd" return formatter }() let fillSelectionColors = ["2015/10/08": UIColor.green, "2015/10/06": UIColor.purple, "2015/10/17": UIColor.gray, "2015/10/21": UIColor.cyan, "2015/11/08": UIColor.green, "2015/11/06": UIColor.purple, "2015/11/17": UIColor.gray, "2015/11/21": UIColor.cyan, "2015/12/08": UIColor.green, "2015/12/06": UIColor.purple, "2015/12/17": UIColor.gray, "2015/12/21": UIColor.cyan] let fillDefaultColors = ["2015/10/08": UIColor.purple, "2015/10/06": UIColor.green, "2015/10/18": UIColor.cyan, "2015/10/22": UIColor.yellow, "2015/11/08": UIColor.purple, "2015/11/06": UIColor.green, "2015/11/18": UIColor.cyan, "2015/11/22": UIColor.yellow, "2015/12/08": UIColor.purple, "2015/12/06": UIColor.green, "2015/12/18": UIColor.cyan, "2015/12/22": UIColor.magenta] let borderDefaultColors = ["2015/10/08": UIColor.brown, "2015/10/17": UIColor.magenta, "2015/10/21": UIColor.cyan, "2015/10/25": UIColor.black, "2015/11/08": UIColor.brown, "2015/11/17": UIColor.magenta, "2015/11/21": UIColor.cyan, "2015/11/25": UIColor.black, "2015/12/08": UIColor.brown, "2015/12/17": UIColor.magenta, "2015/12/21": UIColor.purple, "2015/12/25": UIColor.black] let borderSelectionColors = ["2015/10/08": UIColor.red, "2015/10/17": UIColor.purple, "2015/10/21": UIColor.cyan, "2015/10/25": UIColor.magenta, "2015/11/08": UIColor.red, "2015/11/17": UIColor.purple, "2015/11/21": UIColor.cyan, "2015/11/25": UIColor.purple, "2015/12/08": UIColor.red, "2015/12/17": UIColor.purple, "2015/12/21": UIColor.cyan, "2015/12/25": UIColor.magenta] var datesWithEvent = ["2015-10-03", "2015-10-06", "2015-10-12", "2015-10-25"] var datesWithMultipleEvents = ["2015-10-08", "2015-10-16", "2015-10-20", "2015-10-28"] override func loadView() { let view = UIView(frame: UIScreen.main.bounds) view.backgroundColor = UIColor.groupTableViewBackground self.view = view let height: CGFloat = UIDevice.current.model.hasPrefix("iPad") ? 450 : 300 let calendar = FSCalendar(frame: CGRect(x:0, y:64, width:self.view.bounds.size.width, height:height)) calendar.dataSource = self calendar.delegate = self calendar.allowsMultipleSelection = true calendar.swipeToChooseGesture.isEnabled = true calendar.backgroundColor = UIColor.white calendar.appearance.caseOptions = [.headerUsesUpperCase,.weekdayUsesSingleUpperCase] self.view.addSubview(calendar) self.calendar = calendar calendar.select(self.dateFormatter1.date(from: "2015/10/03")) let todayItem = UIBarButtonItem(title: "TODAY", style: .plain, target: self, action: #selector(self.todayItemClicked(sender:))) self.navigationItem.rightBarButtonItem = todayItem } deinit { print("\(#function)") } @objc func todayItemClicked(sender: AnyObject) { self.calendar.setCurrentPage(Date(), animated: false) } func calendar(_ calendar: FSCalendar, numberOfEventsFor date: Date) -> Int { let dateString = self.dateFormatter2.string(from: date) if self.datesWithEvent.contains(dateString) { return 1 } if self.datesWithMultipleEvents.contains(dateString) { return 3 } return 0 } func calendar(_ calendar: FSCalendar, appearance: FSCalendarAppearance, eventColorFor date: Date) -> UIColor? { let dateString = self.dateFormatter2.string(from: date) if self.datesWithEvent.contains(dateString) { return UIColor.purple } return nil } func calendar(_ calendar: FSCalendar, appearance: FSCalendarAppearance, eventDefaultColorsFor date: Date) -> [UIColor]? { let key = self.dateFormatter2.string(from: date) if self.datesWithMultipleEvents.contains(key) { return [UIColor.magenta, appearance.eventDefaultColor, UIColor.black] } return nil } func calendar(_ calendar: FSCalendar, appearance: FSCalendarAppearance, fillSelectionColorFor date: Date) -> UIColor? { let key = self.dateFormatter1.string(from: date) if let color = self.fillDefaultColors[key] { return color } return appearance.selectionColor } func calendar(_ calendar: FSCalendar, appearance: FSCalendarAppearance, fillDefaultColorFor date: Date) -> UIColor? { let key = self.dateFormatter1.string(from: date) if let color = self.fillDefaultColors[key] { return color } return nil } func calendar(_ calendar: FSCalendar, appearance: FSCalendarAppearance, borderDefaultColorFor date: Date) -> UIColor? { let key = self.dateFormatter1.string(from: date) if let color = self.borderDefaultColors[key] { return color } return appearance.borderDefaultColor } func calendar(_ calendar: FSCalendar, appearance: FSCalendarAppearance, borderSelectionColorFor date: Date) -> UIColor? { let key = self.dateFormatter1.string(from: date) if let color = self.borderSelectionColors[key] { return color } return appearance.borderSelectionColor } func calendar(_ calendar: FSCalendar, appearance: FSCalendarAppearance, borderRadiusFor date: Date) -> CGFloat { if [8, 17, 21, 25].contains((self.gregorian.component(.day, from: date))) { return 0.0 } return 1.0 } }
apache-2.0
5b7a1d8399efdf5bfec60423afa009e5
45.703704
383
0.662173
3.938164
false
false
false
false
ishkawa/APIKit
Sources/APIKit/BodyParameters/Data+InputStream.swift
1
1000
import Foundation enum InputStreamError: Error { case invalidDataCapacity(Int) case unreadableStream(InputStream) } extension Data { init(inputStream: InputStream, capacity: Int = Int(UInt16.max)) throws { var data = Data(capacity: capacity) let bufferSize = Swift.min(Int(UInt16.max), capacity) let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: bufferSize) var readSize: Int repeat { readSize = inputStream.read(buffer, maxLength: bufferSize) switch readSize { case let x where x > 0: data.append(buffer, count: readSize) case let x where x < 0: throw InputStreamError.unreadableStream(inputStream) default: break } } while readSize > 0 #if swift(>=4.1) buffer.deallocate() #else buffer.deallocate(capacity: bufferSize) #endif self.init(data) } }
mit
be0a885206e4a64eded91ec5baba4b86
24
79
0.589
4.739336
false
false
false
false
wikimedia/wikipedia-ios
Wikipedia/Code/Advanced Settings/InsertMediaAdvancedSettingsViewController.swift
3
7229
import UIKit final class InsertMediaAdvancedSettingsViewController: ViewController { static let title = WMFLocalizedString("advanced-settings-title", value: "Advanced settings", comment: "Title for advanced settings screen") private let tableView = UITableView() typealias AdvancedSettings = InsertMediaSettings.Advanced var advancedSettings: AdvancedSettings { return AdvancedSettings(wrapTextAroundImage: textWrappingSwitch.isOn, imagePosition: imagePositionSettingsViewController.selectedImagePosition(isTextWrappingEnabled: textWrappingSwitch.isOn), imageType: imageTypeSettingsViewController.selectedImageType, imageSize: imageSizeSettingsViewController.selectedImageSize) } struct ViewModel { let title: String let detailText: String? let accessoryView: UIView? let accessoryType: UITableViewCell.AccessoryType let isEnabled: Bool let selectionStyle: UITableViewCell.SelectionStyle let onSelection: (() -> Void)? init(title: String, detailText: String? = nil, accessoryView: UIView? = nil, accessoryType: UITableViewCell.AccessoryType = .disclosureIndicator, isEnabled: Bool = true, selectionStyle: UITableViewCell.SelectionStyle = .default, onSelection: (() -> Void)? = nil) { self.title = title self.detailText = detailText self.accessoryView = accessoryView self.accessoryType = accessoryType self.isEnabled = isEnabled self.selectionStyle = selectionStyle self.onSelection = onSelection } } private lazy var textWrappingSwitch: UISwitch = { let textWrappingSwitch = UISwitch() textWrappingSwitch.isOn = true textWrappingSwitch.addTarget(self, action: #selector(toggleImagePositionEnabledState(_:)), for: .valueChanged) return textWrappingSwitch }() private lazy var imagePositionSettingsViewController = InsertMediaImagePositionSettingsViewController() private lazy var imageTypeSettingsViewController = InsertMediaImageTypeSettingsViewController() private lazy var imageSizeSettingsViewController = InsertMediaImageSizeSettingsViewController() private var viewModels: [ViewModel] { let textWrappingViewModel = ViewModel(title: WMFLocalizedString("insert-media-image-text-wrapping-setting", value: "Wrap text around image", comment: "Title for image setting that wraps text around image"), accessoryView: textWrappingSwitch, accessoryType: .none, selectionStyle: .none) let imagePositionViewModel = ViewModel(title: AdvancedSettings.ImagePosition.displayTitle, detailText: imagePositionSettingsViewController.selectedImagePosition(isTextWrappingEnabled: textWrappingSwitch.isOn).displayTitle, isEnabled: textWrappingSwitch.isOn) { [weak self] in guard let self = self else { return } self.push(self.imagePositionSettingsViewController) } let imageTypeViewModel = ViewModel(title: AdvancedSettings.ImageType.displayTitle, detailText: imageTypeSettingsViewController.selectedImageType.displayTitle) { [weak self] in guard let self = self else { return } self.push(self.imageTypeSettingsViewController) } let imageSizeViewModel = ViewModel(title: AdvancedSettings.ImageSize.displayTitle, detailText: imageSizeSettingsViewController.selectedImageSize.displayTitle) { [weak self] in guard let self = self else { return } self.push(self.imageSizeSettingsViewController) } return [textWrappingViewModel, imagePositionViewModel, imageTypeViewModel, imageSizeViewModel] } private func push(_ viewController: UIViewController & Themeable) { viewController.apply(theme: theme) navigationController?.pushViewController(viewController, animated: true) } @objc private func toggleImagePositionEnabledState(_ sender: UISwitch) { tableView.reloadRows(at: [IndexPath(row: 1, section: 0)], with: .automatic) } override func viewDidLoad() { scrollView = tableView super.viewDidLoad() navigationBar.isBarHidingEnabled = false tableView.dataSource = self tableView.delegate = self view.wmf_addSubviewWithConstraintsToEdges(tableView) tableView.separatorInset = .zero tableView.tableFooterView = UIView() title = InsertMediaAdvancedSettingsViewController.title apply(theme: theme) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) defer { isFirstAppearance = false } guard !isFirstAppearance else { return } tableView.reloadData() } // MARK: - Themeable override func apply(theme: Theme) { super.apply(theme: theme) guard viewIfLoaded != nil else { return } view.backgroundColor = theme.colors.paperBackground tableView.backgroundColor = view.backgroundColor tableView.separatorColor = theme.colors.border tableView.reloadData() } } // MARK: - Table view data source extension InsertMediaAdvancedSettingsViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return viewModels.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: UITableViewCell.identifier) ?? UITableViewCell(style: .value1, reuseIdentifier: UITableViewCell.identifier) let viewModel = viewModels[indexPath.row] cell.textLabel?.text = viewModel.title cell.accessoryView = viewModel.accessoryView cell.accessoryType = viewModel.accessoryType cell.isUserInteractionEnabled = viewModel.isEnabled cell.detailTextLabel?.textAlignment = .right cell.detailTextLabel?.text = viewModel.detailText cell.selectionStyle = cell.isUserInteractionEnabled ? viewModel.selectionStyle : .none apply(theme: theme, to: cell) return cell } private func apply(theme: Theme, to cell: UITableViewCell) { cell.backgroundColor = theme.colors.paperBackground cell.contentView.backgroundColor = theme.colors.paperBackground let selectedBackgroundView = UIView() selectedBackgroundView.backgroundColor = theme.colors.midBackground cell.selectedBackgroundView = selectedBackgroundView cell.textLabel?.textColor = cell.isUserInteractionEnabled ? theme.colors.primaryText : theme.colors.secondaryText cell.detailTextLabel?.textColor = theme.colors.secondaryText } } // MARK: - Table view delegate extension InsertMediaAdvancedSettingsViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let viewModel = viewModels[indexPath.row] viewModel.onSelection?() } }
mit
39d19e57cf7bdb8ac0bc5c27a412de36
45.044586
323
0.714898
5.78783
false
false
false
false
safx/TypetalkApp
TypetalkApp/iOS/ViewControllers/CreateTopicViewController.swift
1
1907
// // CreateTopicViewController.swift // TypetalkApp // // Created by Safx Developer on 2014/11/12. // Copyright (c) 2014年 Safx Developers. All rights reserved. // import UIKit import TypetalkKit import RxSwift class CreateTopicViewController: UITableViewController { let viewModel = CreateTopicViewModel() let disposeBag = DisposeBag() @IBOutlet weak var doneButton: UIBarButtonItem! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. tableView.estimatedRowHeight = 100 tableView.rowHeight = UITableViewAutomaticDimension tableView.dataSource = viewModel viewModel.topicTitle .asObservable() .subscribeNext { self.doneButton.enabled = !($0.isEmpty) } .addDisposableTo(disposeBag) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //MARK action @IBAction func createTopic(sender: AnyObject) { viewModel.createTopicAction() .subscribe( onNext: { res in print("\(res)") }, onError: { err in print("\(err)") }, onCompleted:{ self.dismissViewControllerAnimated(true, completion: nil) }) .addDisposableTo(disposeBag) } //MARK: Segue @IBAction func exitAction(segue: UIStoryboardSegue) { self.dismissViewControllerAnimated(true, completion: nil) } override func canPerformUnwindSegueAction(action: Selector, fromViewController: UIViewController, withSender sender: AnyObject) -> Bool { return true } }
mit
92b7c65462f3548118cc99dac22df978
27.014706
141
0.6
5.772727
false
false
false
false
shadanan/mado
Antlr4Runtime/Sources/Antlr4/misc/ArrayList.swift
1
2188
/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. /// Use of this file is governed by the BSD 3-clause license that /// can be found in the LICENSE.txt file in the project root. // // ArrayList.swift // Antlr4 // // Created by janyou on 16/2/24. // import Foundation public final class ArrayList<T>: ExpressibleByArrayLiteral { private var array: Array<T> public init(slice: ArraySlice<T>) { array = Array<T>() for element in slice { array.append(element) } } public init(_ elements: T...) { array = Array<T>() for element in elements { array.append(element) } } public init(count: Int, repeatedValue: T) { array = Array<T>( repeating: repeatedValue, count: count) } public init(arrayLiteral elements: T...) { array = Array<T>() for element in elements { array.append(element) } } public subscript(index: Int) -> T { get { return array[index] } set { array[index] = newValue } } public subscript(subRange: Range<Int>) -> ArrayList<T> { return ArrayList<T>(slice: array[subRange]) } public var count: Int { return array.count } } public func == <Element: Equatable>(lhs: ArrayList<Element>, rhs: ArrayList<Element>) -> Bool { if lhs === rhs { return true } if lhs.count != rhs.count { return false } let length = lhs.count for i in 0..<length { if lhs[i] != rhs[i] { return false } } return true } public func == <Element: Equatable>(lhs: ArrayList<Element?>, rhs: ArrayList<Element?>) -> Bool { if lhs === rhs { return true } if lhs.count != rhs.count { return false } let length = lhs.count for i in 0..<length { if lhs[i] == nil && rhs[i] != nil { return false } if rhs[i] == nil && lhs[i] != nil { return false } if lhs[i] != nil && rhs[i] != nil && rhs[i]! != rhs[i]! { return false } } return true }
mit
ee24db21abf43885dc803ecdc66c9fee
21.791667
97
0.530622
3.935252
false
false
false
false
jaanussiim/weather-scrape
Sources/NetworkRequest.swift
1
4650
/* * Copyright 2016 JaanusSiim * * 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 enum HTTPMethod: String { case GET = "GET" case POST = "POST" } enum Result: CustomStringConvertible { case Success(Int, Data) case Error(NSError) case Unknown var description: String { switch self { case .Unknown: return "Unknown" case .Error(let error): return "Error \(error)" case .Success(let status, let data): return "Success - status: \(status). data: \(data.count)" } } } class NetworkRequest { private let baseURL: URL var logContent = false init(baseURL: URL) { self.baseURL = baseURL } final func GET(_ path: String, params: [String: AnyObject] = [:]) { executeRequest(method: .GET, path: path, params: params) } final func POST(to path: String, body: Data? = nil) { executeRequest(method: .POST, path: path, params: [:], body: body) } private func executeRequest(method: HTTPMethod, path: String, params: [String: AnyObject], body: Data? = nil) { var components = URLComponents(url: baseURL, resolvingAgainstBaseURL: true)! components.path = components.path?.appending(path) var queryItems = [URLQueryItem]() for (name, value) in params { queryItems.append(URLQueryItem(name: name, value: "\(value)")) } if queryItems.count > 0 { components.queryItems = queryItems } let requestURL = components.url! Log.debug("\(method) to \(requestURL)") var request = URLRequest(url: requestURL) request.httpMethod = method.rawValue request.addValue("www.jaanussiim.com / [email protected]", forHTTPHeaderField: "User-Agent") let additionalHeaders = customHeaders() for (name, value) in additionalHeaders { request.addValue(value, forHTTPHeaderField: name) } if let bodyData = body { Log.debug("Attach body \(bodyData.count)") request.httpBody = bodyData } Log.debug("Headers: \(request.allHTTPHeaderFields)") let completion: (Data?, URLResponse?, NSError?) -> () = { data, response, error in var statusCode = 0 if self.logContent, let httpResponse = response as? HTTPURLResponse { Log.debug("Response code \(httpResponse.statusCode)") Log.debug("Headers: \(httpResponse.allHeaderFields)") statusCode = httpResponse.statusCode } if self.logContent, let data = data, string = String(data: data, encoding: String.Encoding.utf8) { Log.debug("Response body\n\n \(string)") } if let error = error { self.handle(result: .Error(error)) } else if let data = data { self.handle(result: .Success(statusCode, data)) } else { self.handle(result: .Unknown) } } URLSession.shared().synchronousDataWithRequest(request: request, completionHandler: completion) } func execute() { fatalError("Overrie: \(#function)") } func handle(result: Result) { Log.debug("Handle: \(result)") } func customHeaders() -> [String: String] { return [:]; } } extension URLSession { func synchronousDataWithRequest(request: URLRequest, completionHandler: (Data?, URLResponse?, NSError?) -> Void) { var data: Data? var response: URLResponse? var error: NSError? let sem = DispatchSemaphore(value: 0) let task = dataTask(with: request, completionHandler: { data = $0 response = $1 error = $2 sem.signal() }) task.resume() sem.wait(timeout: DispatchTime.distantFuture) completionHandler(data, response, error) } }
apache-2.0
b73c88c8f120eb323ca030b711895705
31.068966
118
0.584946
4.711246
false
false
false
false
YauheniYarotski/APOD
APOD/ApodCell.swift
1
2831
// // ApodCell.swift // APOD // // Created by Yauheni Yarotski on 23.04.16. // Copyright © 2016 Yauheni_Yarotski. All rights reserved. // import UIKit import youtube_ios_player_helper protocol ApodCellDelegate { func prepareCellForReuse(_ row: NSInteger, cell: ApodCell) func apodImageTaped(_ tap: UITapGestureRecognizer, cell: ApodCell) } class ApodCell: UICollectionViewCell { struct constants { static let reuseIdentifier = "ApodCell" } let apodImageView = UIImageView() let activityIndicator = UIActivityIndicatorView() let errorLabel = UILabel() let playerView = YTPlayerView() var delegate: ApodCellDelegate? override func awakeFromNib() { super.awakeFromNib() setupCell() } override init(frame: CGRect) { super.init(frame: frame) setupCell() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setupCell() { playerView.isHidden = true playerView.webView?.backgroundColor = UIColor.red playerView.tintColor = UIColor.red apodImageView.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(apodImageView) apodImageView.snp.makeConstraints { (make) in make.edges.equalToSuperview() } let tap = UITapGestureRecognizer(target: self, action: #selector(ApodCell.apodImagePressed(_:))) tap.numberOfTapsRequired = 1 apodImageView.addGestureRecognizer(tap) apodImageView.isUserInteractionEnabled = true apodImageView.contentMode = .scaleAspectFit playerView.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(playerView) playerView.snp.makeConstraints { (make) in make.edges.equalToSuperview() } errorLabel.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(errorLabel) errorLabel.snp.makeConstraints { (make) in make.leading.top.equalToSuperview().offset(8) make.trailing.equalToSuperview().offset(-8) } activityIndicator.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(activityIndicator) activityIndicator.snp.makeConstraints { (make) in make.center.equalToSuperview() } activityIndicator.activityIndicatorViewStyle = .whiteLarge } func apodImagePressed(_ tap: UITapGestureRecognizer) { delegate?.apodImageTaped(tap, cell: self) } override func prepareForReuse() { super.prepareForReuse() delegate?.prepareCellForReuse(tag, cell: self) apodImageView.image = nil errorLabel.text = nil tag = NSIntegerMax activityIndicator.stopAnimating() if !playerView.isHidden { playerView.stopVideo() } playerView.isHidden = true apodImageView.isHidden = false } }
mit
7efba9e4d5c82959b58af60bfe1dc3ef
25.952381
98
0.714841
4.477848
false
false
false
false
shaps80/InkKit
Example/InkExampleOSX/Grid.swift
1
3622
// // Grid.swift // InkKit // // Created by Shahpour Benkau on 11/05/2017. // Copyright © 2017 CocoaPods. All rights reserved. // import CoreGraphics public struct LayoutMargins { public let start: CGFloat public let end: CGFloat public init(start: CGFloat, end: CGFloat) { self.start = start self.end = end } public static func both(_ margin: CGFloat) -> LayoutMargins { return LayoutMargins(start: margin, end: margin) } } extension LayoutMargins: ExpressibleByIntegerLiteral { public init(integerLiteral value: IntegerLiteralType) { self.init(start: CGFloat(value), end: CGFloat(value)) } } extension LayoutMargins: ExpressibleByFloatLiteral { public init(floatLiteral value: FloatLiteralType) { self.init(start: CGFloat(value), end: CGFloat(value)) } } public protocol Cell { var offset: Int { get } var span: Int { get } var size: CGFloat { get } } public struct GridCell: Cell { public let offset: Int public let span: Int // height for column, width for row public let size: CGFloat public init(offset: Int = 0, span: Int = 0, size: CGFloat) { self.offset = offset self.span = span self.size = size } } public struct Grid: Cell { public enum Layout { case columns(Int) case rows(Int) } fileprivate var count: Int { switch layout { case .columns(let count): return count case .rows(let count): return count } } public var layout: Layout public var margins: LayoutMargins public var gutter: CGFloat public var cells = [Cell]() public let offset: Int public let span: Int // height for column, width for row public let size: CGFloat public init(with layout: Layout, gutter: CGFloat = 16, margins: LayoutMargins = .both(0)) { self.layout = layout self.gutter = gutter self.margins = margins self.offset = 0 self.span = 0 self.size = 0 } } extension Grid { public var flattened: [Cell] { let grids = cells.flatMap { $0 as? Grid } return [self] + grids.flatMap { $0.flattened } } } struct GridCellAttributes { let frame: CGRect let cell: Cell } //extension Cell { // private func frame(for cell: Cell, in frame: CGRect, withColumns count: Int) -> CGRect { // let availableWidth = width - (start + end) - (gutter * CGFloat(count - 1)) // let singleCellWidth = availableWidth / CGFloat(count) // // let cell = cells[index] // var x = bounds.origin.x + margins.start // x += CGFloat(cell.offset) * gutter // x += CGFloat(cell.offset) * singleCellWidth // // var width = CGFloat(cell.span) * singleCellWidth // width += CGFloat(cell.span - 1) * gutter // // return CGRect(x: x, y: 0, width: width, height: cell.size) // } //} // //extension Grid { // // public func layout(in frame: CGRect) -> CGRect { // let count: Int // // switch layout { // case .columns(let c): count = c // case .rows(let c): count = c // } // // let availableSpace = frame.width - (margins.start + margins.end) - (gutter * CGFloat(count - 1)) // let singleCellWidth = availableWidth / CGFloat(count) // } // // func boundsForCell(at index: Int) -> CGRect { // var rect = frameForCell(at: index) // rect.origin = .zero // return rect // } // // //}
mit
d361901a2e503c739ab1c3d60ee281e8
24.145833
106
0.584645
3.893548
false
false
false
false
vchuo/Photoasis
Photoasis/Classes/Views/Views/Buttons/POSavedPhotosNavigationButtonView.swift
1
2611
// // POSavedPhotosNavigationButtonView.swift // 保存したフォトのナビボタンビュー。 // // Created by Vernon Chuo Chian Khye on 2017/02/26. // Copyright © 2017 Vernon Chuo Chian Khye. All rights reserved. // import UIKit import ChuoUtil class POSavedPhotosNavigationButtonView: UIView { // MARK: - Public Properties // ボタンアクション var buttonAction: (() -> Void)? { get { return overlayButton.buttonAction } set(newValue) { overlayButton.buttonAction = newValue } } // MARK: - Views private let imageView = UIImageView() private let overlayButton = CUOverlayButtonView() // MARK: - Init init() { super.init(frame: CGRectZero) setup() } required init?(coder aDecoder: NSCoder) { super.init(frame: CGRectZero) setup() } // MARK: - Public Functions /** フォトが保存する時のアニメーションを実行。 */ func executePhotoSavedAnimation() { CUHelper.animate( 0.5, options: .CurveEaseOut, animations: { self.imageView.transform = CGAffineTransformMakeScale(0.5, 0.5) } ) { _ in CUHelper.animateWithSpringBehavior( 0.5, usingSpringWithDamping: 0.2, initialSpringVelocity: 0.3, animations: { self.imageView.transform = CGAffineTransformMakeScale(1, 1) } ) } } // MARK: - Private Functions /** セットアップ。 */ private func setup() { self.bounds.size = POConstants.NavigationButtonSize self.center = POConstants.SavedPhotosNavigationButtonCenter self.layer.cornerRadius = POConstants.NavigationButtonSize.width / 2 self.clipsToBounds = true self.backgroundColor = POColors.NavigationButtonSelectedStateBackgroundColor // イメージビュー imageView.bounds.size = self.bounds.size imageView.center = CUHelper.centerPointOf(self) if let image = UIImage(named: "saved_photos_navi_button") { imageView.image = image.imageWithRenderingMode(.AlwaysTemplate) imageView.tintColor = UIColor.whiteColor() } self.addSubview(imageView) // オーバーレイボタン overlayButton.bounds.size = self.bounds.size overlayButton.center = imageView.center self.addSubview(overlayButton) } }
mit
842bfa813768967a5c6173f8913165cf
25.580645
91
0.591828
4.594796
false
false
false
false
AlphaJian/LarsonApp
LarsonApp/LarsonApp/Class/JobDetail/WorkOrderViews/WorkOrderStaticView.swift
1
1188
// // WorkOrderStaticView.swift // LarsonApp // // Created by Perry Z Chen on 11/10/16. // Copyright © 2016 Jian Zhang. All rights reserved. // import UIKit class WorkOrderStaticView: UIView { /* // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing code } */ @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var contentLabel: UILabel! private var strTitle = "" private var strContent = "" func initUI(parameter: (String, String), labelWidth: CGFloat) { self.contentLabel.preferredMaxLayoutWidth = labelWidth - 30 self.strTitle = parameter.0 self.strContent = "\(parameter.1)\(parameter.1)\(parameter.1)\(parameter.1)" self.titleLabel.text = self.strTitle self.contentLabel.text = self.strContent // self.titleLabel.text = parameter.0 // self.contentLabel.text = "\(parameter.1)\(parameter.1)\(parameter.1)\(parameter.1)" // self.contentLabel.layoutIfNeeded() // self.layoutIfNeeded() } }
apache-2.0
d75e9cb4837b81eb61d74f8e170f45cc
25.977273
93
0.64027
4.380074
false
false
false
false
kenwilcox/Crypticker
CryptoCurrencyKit/BitCoinService.swift
1
6844
/* * Copyright (c) 2014 Razeware LLC * * 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 typealias StatsCompletionBlock = (stats: BitCoinStats?, error: NSError?) -> () typealias MarketPriceCompletionBlock = (prices: [BitCoinPrice]?, error: NSError?) -> () class BitCoinService { let statsCacheKey = "BitCoinServiceStatsCache" let statsCachedDateKey = "BitCoinServiceStatsCachedDate" let priceHistoryCacheKey = "BitCoinServicePriceHistoryCache" let priceHistoryCachedDateKey = "BitCoinServicePriceHistoryCachedDate" let session: NSURLSession class var sharedInstance: BitCoinService { struct Singleton { static let instance = BitCoinService() } return Singleton.instance } init() { let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() session = NSURLSession(configuration: configuration) } func getStats(completion: StatsCompletionBlock) { if let cachedStats: BitCoinStats = getCachedStats() { completion(stats: cachedStats, error: nil) return } let statsUrl = NSURL(string: "https://blockchain.info/stats?format=json") let request = NSURLRequest(URL: statsUrl!) let task = session.dataTaskWithRequest(request) {[unowned self] data, response, error in if error == nil { var jsonError: NSError? if (jsonError == nil) { let statsDictionary = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.AllowFragments, error: &jsonError) as! NSDictionary let stats: BitCoinStats = BitCoinStats(fromJSON: JSONValue(statsDictionary)) self.cacheStats(stats) completion(stats: stats, error: nil) } else { completion(stats: nil, error: jsonError) } } else { completion(stats: nil, error: error) } } task.resume() } func getMarketPriceInUSDForPast30Days(completion: MarketPriceCompletionBlock) { if let cachedPrices: [BitCoinPrice] = getCachedPriceHistory() { completion(prices: cachedPrices, error: nil) return } let pricesUrl = NSURL(string: "https://blockchain.info/charts/market-price?timespan=30days&format=json") let request = NSURLRequest(URL: pricesUrl!); let task = session.dataTaskWithRequest(request) {[unowned self] data, response, error in if error == nil { var jsonError: NSError? let pricesDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: &jsonError)as! NSDictionary if (jsonError == nil) { let json = JSONValue(pricesDictionary) let priceValues = pricesDictionary["values"] as! Array<NSDictionary> var prices = [BitCoinPrice]() for priceDictionary in priceValues { let price = BitCoinPrice(fromJSON: JSONValue(priceDictionary)) prices.append(price) } self.cachePriceHistory(prices) completion(prices: prices, error: nil) } else { completion(prices: nil, error: jsonError) } } else { completion(prices: nil, error: error) } } task.resume() } func yesterdaysPriceUsingPriceHistory(priceHistory: Array<BitCoinPrice>) -> (BitCoinPrice?) { var yesterdaysPrice: BitCoinPrice? for price in priceHistory.reverse() { if (price.time.isYesterday()) { yesterdaysPrice = price break; } } return yesterdaysPrice } func loadCachedDataForKey(key: String, cachedDateKey: String) -> AnyObject? { var cachedValue: AnyObject? if let cachedDate = NSUserDefaults.standardUserDefaults().valueForKey(cachedDateKey) as? NSDate { let timeInterval = NSDate().timeIntervalSinceDate(cachedDate) if (timeInterval < 60*5) { let cachedData = NSUserDefaults.standardUserDefaults().valueForKey(key) as? NSData if cachedData != nil { cachedValue = NSKeyedUnarchiver.unarchiveObjectWithData(cachedData!) } } } return cachedValue } func getCachedStats() -> BitCoinStats? { let stats = loadCachedDataForKey(statsCacheKey, cachedDateKey: statsCachedDateKey) as? BitCoinStats return stats } func getCachedPriceHistory() -> [BitCoinPrice]? { let prices = loadCachedDataForKey(priceHistoryCacheKey, cachedDateKey: priceHistoryCachedDateKey) as? [BitCoinPrice] return prices } func cacheStats(stats: BitCoinStats) { print(stats) let statsData = NSKeyedArchiver.archivedDataWithRootObject(stats) NSUserDefaults.standardUserDefaults().setValue(statsData, forKey: statsCacheKey) NSUserDefaults.standardUserDefaults().setValue(NSDate(), forKey: statsCachedDateKey) } func cachePriceHistory(history: [BitCoinPrice]) { let priceData = NSKeyedArchiver.archivedDataWithRootObject(history) NSUserDefaults.standardUserDefaults().setValue(priceData, forKey: priceHistoryCacheKey) NSUserDefaults.standardUserDefaults().setValue(NSDate(), forKey: priceHistoryCachedDateKey) } }
mit
5511407b9cfb504633465ae13bb5733c
39.738095
167
0.635009
5.244444
false
false
false
false
brentdax/swift
benchmark/single-source/DropFirst.swift
3
6940
//===--- DropFirst.swift --------------------------------------*- swift -*-===// // // 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 // //===----------------------------------------------------------------------===// //////////////////////////////////////////////////////////////////////////////// // WARNING: This file is manually generated from .gyb template and should not // be directly modified. Instead, make changes to DropFirst.swift.gyb and run // scripts/generate_harness/generate_harness.py to regenerate this file. //////////////////////////////////////////////////////////////////////////////// import TestsUtils let sequenceCount = 4096 let dropCount = 1024 let suffixCount = sequenceCount - dropCount let sumCount = suffixCount * (2 * sequenceCount - suffixCount - 1) / 2 public let DropFirst = [ BenchmarkInfo( name: "DropFirstCountableRange", runFunction: run_DropFirstCountableRange, tags: [.validation, .api]), BenchmarkInfo( name: "DropFirstSequence", runFunction: run_DropFirstSequence, tags: [.validation, .api]), BenchmarkInfo( name: "DropFirstAnySequence", runFunction: run_DropFirstAnySequence, tags: [.validation, .api]), BenchmarkInfo( name: "DropFirstAnySeqCntRange", runFunction: run_DropFirstAnySeqCntRange, tags: [.validation, .api]), BenchmarkInfo( name: "DropFirstAnySeqCRangeIter", runFunction: run_DropFirstAnySeqCRangeIter, tags: [.validation, .api]), BenchmarkInfo( name: "DropFirstAnyCollection", runFunction: run_DropFirstAnyCollection, tags: [.validation, .api]), BenchmarkInfo( name: "DropFirstArray", runFunction: run_DropFirstArray, tags: [.validation, .api, .Array]), BenchmarkInfo( name: "DropFirstCountableRangeLazy", runFunction: run_DropFirstCountableRangeLazy, tags: [.validation, .api]), BenchmarkInfo( name: "DropFirstSequenceLazy", runFunction: run_DropFirstSequenceLazy, tags: [.validation, .api]), BenchmarkInfo( name: "DropFirstAnySequenceLazy", runFunction: run_DropFirstAnySequenceLazy, tags: [.validation, .api]), BenchmarkInfo( name: "DropFirstAnySeqCntRangeLazy", runFunction: run_DropFirstAnySeqCntRangeLazy, tags: [.validation, .api]), BenchmarkInfo( name: "DropFirstAnySeqCRangeIterLazy", runFunction: run_DropFirstAnySeqCRangeIterLazy, tags: [.validation, .api]), BenchmarkInfo( name: "DropFirstAnyCollectionLazy", runFunction: run_DropFirstAnyCollectionLazy, tags: [.validation, .api]), BenchmarkInfo( name: "DropFirstArrayLazy", runFunction: run_DropFirstArrayLazy, tags: [.validation, .api]), ] @inline(never) public func run_DropFirstCountableRange(_ N: Int) { let s = 0..<sequenceCount for _ in 1...20*N { var result = 0 for element in s.dropFirst(dropCount) { result += element } CheckResults(result == sumCount) } } @inline(never) public func run_DropFirstSequence(_ N: Int) { let s = sequence(first: 0) { $0 < sequenceCount - 1 ? $0 &+ 1 : nil } for _ in 1...20*N { var result = 0 for element in s.dropFirst(dropCount) { result += element } CheckResults(result == sumCount) } } @inline(never) public func run_DropFirstAnySequence(_ N: Int) { let s = AnySequence(sequence(first: 0) { $0 < sequenceCount - 1 ? $0 &+ 1 : nil }) for _ in 1...20*N { var result = 0 for element in s.dropFirst(dropCount) { result += element } CheckResults(result == sumCount) } } @inline(never) public func run_DropFirstAnySeqCntRange(_ N: Int) { let s = AnySequence(0..<sequenceCount) for _ in 1...20*N { var result = 0 for element in s.dropFirst(dropCount) { result += element } CheckResults(result == sumCount) } } @inline(never) public func run_DropFirstAnySeqCRangeIter(_ N: Int) { let s = AnySequence((0..<sequenceCount).makeIterator()) for _ in 1...20*N { var result = 0 for element in s.dropFirst(dropCount) { result += element } CheckResults(result == sumCount) } } @inline(never) public func run_DropFirstAnyCollection(_ N: Int) { let s = AnyCollection(0..<sequenceCount) for _ in 1...20*N { var result = 0 for element in s.dropFirst(dropCount) { result += element } CheckResults(result == sumCount) } } @inline(never) public func run_DropFirstArray(_ N: Int) { let s = Array(0..<sequenceCount) for _ in 1...20*N { var result = 0 for element in s.dropFirst(dropCount) { result += element } CheckResults(result == sumCount) } } @inline(never) public func run_DropFirstCountableRangeLazy(_ N: Int) { let s = (0..<sequenceCount).lazy for _ in 1...20*N { var result = 0 for element in s.dropFirst(dropCount) { result += element } CheckResults(result == sumCount) } } @inline(never) public func run_DropFirstSequenceLazy(_ N: Int) { let s = (sequence(first: 0) { $0 < sequenceCount - 1 ? $0 &+ 1 : nil }).lazy for _ in 1...20*N { var result = 0 for element in s.dropFirst(dropCount) { result += element } CheckResults(result == sumCount) } } @inline(never) public func run_DropFirstAnySequenceLazy(_ N: Int) { let s = (AnySequence(sequence(first: 0) { $0 < sequenceCount - 1 ? $0 &+ 1 : nil })).lazy for _ in 1...20*N { var result = 0 for element in s.dropFirst(dropCount) { result += element } CheckResults(result == sumCount) } } @inline(never) public func run_DropFirstAnySeqCntRangeLazy(_ N: Int) { let s = (AnySequence(0..<sequenceCount)).lazy for _ in 1...20*N { var result = 0 for element in s.dropFirst(dropCount) { result += element } CheckResults(result == sumCount) } } @inline(never) public func run_DropFirstAnySeqCRangeIterLazy(_ N: Int) { let s = (AnySequence((0..<sequenceCount).makeIterator())).lazy for _ in 1...20*N { var result = 0 for element in s.dropFirst(dropCount) { result += element } CheckResults(result == sumCount) } } @inline(never) public func run_DropFirstAnyCollectionLazy(_ N: Int) { let s = (AnyCollection(0..<sequenceCount)).lazy for _ in 1...20*N { var result = 0 for element in s.dropFirst(dropCount) { result += element } CheckResults(result == sumCount) } } @inline(never) public func run_DropFirstArrayLazy(_ N: Int) { let s = (Array(0..<sequenceCount)).lazy for _ in 1...20*N { var result = 0 for element in s.dropFirst(dropCount) { result += element } CheckResults(result == sumCount) } } // Local Variables: // eval: (read-only-mode 1) // End:
apache-2.0
a409d2b38beb77e1f93ca15f2b496014
27.559671
91
0.634582
3.905459
false
false
false
false
jverkoey/FigmaKit
Sources/FigmaKit/Effect.swift
1
3765
/// A Figma effect. /// /// "A visual effect such as a shadow or blur." /// https://www.figma.com/developers/api#effect-type public class Effect: PolymorphicDecodable { /// The Type of effect. public let type: EffectType /// Is the effect active? public let visible: Bool /// Radius of the blur effect (applies to shadows as well). public let radius: Double private enum CodingKeys: String, CodingKey { case type case visible case radius } public required init(from decoder: Decoder) throws { let keyedDecoder = try decoder.container(keyedBy: Self.CodingKeys) self.type = try keyedDecoder.decode(EffectType.self, forKey: .type) self.visible = try keyedDecoder.decode(Bool.self, forKey: .visible) self.radius = try keyedDecoder.decode(Double.self, forKey: .radius) } public static func decodePolymorphicArray(from decoder: UnkeyedDecodingContainer) throws -> [Effect] { return try decodePolyType(from: decoder, keyedBy: Effect.CodingKeys.self, key: .type, typeMap: Effect.typeMap) } static let typeMap: [EffectType: Effect.Type] = [ .innerShadow: Shadow.self, .dropShadow: DropShadow.self, .layerBlur: Effect.self, .backgroundBlur: Effect.self, ] public enum EffectType: String, Codable { case innerShadow = "INNER_SHADOW" case dropShadow = "DROP_SHADOW" case layerBlur = "LAYER_BLUR" case backgroundBlur = "BACKGROUND_BLUR" } public var description: String { return """ <\(Swift.type(of: self)) - type: \(type) - visible: \(visible) - radius: \(radius) \(effectDescription.isEmpty ? "" : "\n" + effectDescription) > """ } var effectDescription: String { return "" } } extension Effect { /// A Figma shadow effect. public final class Shadow: Effect { /// The color of the shadow. public let color: Color /// The blend mode of the shadow. public let blendMode: BlendMode /// How far the shadow is projected in the x and y directions. public let offset: Vector /// How far the shadow spreads. public let spread: Double private enum CodingKeys: String, CodingKey { case color case blendMode case offset case spread } public required init(from decoder: Decoder) throws { let keyedDecoder = try decoder.container(keyedBy: Self.CodingKeys) self.color = try keyedDecoder.decode(Color.self, forKey: .color) self.blendMode = try keyedDecoder.decode(BlendMode.self, forKey: .blendMode) self.offset = try keyedDecoder.decode(Vector.self, forKey: .offset) self.spread = try keyedDecoder.decodeIfPresent(Double.self, forKey: .spread) ?? 0 try super.init(from: decoder) } override var effectDescription: String { return """ - color: \(color) - blendMode: \(blendMode) - offset: \(offset) - spread: \(spread) """ } } /// A Figma drop shadow effect. public final class DropShadow: Effect { /// Whether to show the shadow behind translucent or transparent pixels. public let showShadowBehindNode: Bool private enum CodingKeys: String, CodingKey { case showShadowBehindNode } public required init(from decoder: Decoder) throws { let keyedDecoder = try decoder.container(keyedBy: Self.CodingKeys) self.showShadowBehindNode = try keyedDecoder.decode(Bool.self, forKey: .showShadowBehindNode) try super.init(from: decoder) } override var effectDescription: String { return super.effectDescription + """ - showShadowBehindNode: \(showShadowBehindNode) """ } } }
apache-2.0
31c33482e1b588b6b2723ca0dd5b3517
28.880952
114
0.651262
4.278409
false
false
false
false
twtstudio/WePeiYang-iOS
WePeiYang/Tools/Controller/ToolsCollectionViewController.swift
1
13607
// // ToolsCollectionViewController.swift // WePeiYang // // Created by Qin Yubo on 16/3/26. // Copyright © 2016年 Qin Yubo. All rights reserved. // import UIKit import LocalAuthentication import STPopup private let reuseIdentifier = "Cell" class ToolsCollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout { typealias ToolCell = (title: String, image: UIImage) private let toolsData: [ToolCell] = [ (title: "成绩", image: UIImage(named: "gpaBtn")!), (title: "课程表", image: UIImage(named: "classtableBtn")!), // (title: "图书馆", image: UIImage(named: "libBtn")!), (title: "失物招领", image: UIImage(named: "lfBtn")!), (title: "自行车", image: UIImage(named: "bicycleBtn")!), (title: "党建" , image: UIImage(named: "partyBtn")!), (title: "探索", image: UIImage(named: "msBtn")!), (title: "阅读", image: UIImage(named: "readBtn")!), (title: "黄页", image: UIImage(named: "YellowPageBtn")!), // (title: "图书馆", image: UIImage(named: "libBtn")!) ] var microserviceController: STPopupController! override func viewDidLoad() { super.viewDidLoad() //3D Touch if #available(iOS 9.0, *) { if traitCollection.forceTouchCapability == .Available { registerForPreviewingWithDelegate(self, sourceView: self.collectionView!) } } else { // Fallback on earlier versions } self.navigationController?.view.backgroundColor = UIColor.whiteColor() self.collectionView?.backgroundColor = UIColor.whiteColor() self.collectionView?.alwaysBounceVertical = true self.jz_navigationBarBackgroundHidden = false // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Register cell classes self.collectionView!.registerClass(ToolsCollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier) // Do any additional setup after loading the view. } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.navigationController?.navigationBar.tintColor = UIColor(red: 0.0, green: 122.0/255.0, blue: 1.0, alpha: 1.0) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator) self.collectionView?.reloadData() } /* // 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. } */ // MARK: - UICollectionViewDataSource override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return toolsData.count } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { return CGSizeMake(collectionView.bounds.width/4, 119) } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { var nibCellLoaded = false if !nibCellLoaded { let nib = UINib(nibName: "ToolsCollectionViewCell", bundle: nil) collectionView.registerNib(nib, forCellWithReuseIdentifier: reuseIdentifier) nibCellLoaded = true } let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! ToolsCollectionViewCell cell.iconView.image = toolsData[indexPath.row].image cell.titleLabel.text = toolsData[indexPath.row].title return cell } // MARK: - UICollectionViewDelegate override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { switch indexPath.row { case 0: self.showGPAController() case 1: self.showClasstableController() // case 2: // self.showLibraryController() case 2: self.showLostFoundController() case 3: self.showBicycleServiceController() case 4: self.showPartyServiceController() case 5: self.showMicroservicesController() case 6: self.showReadController() case 7: self.showYellowPageController() // case 8: // self.showLibraryController() default: return } } /* // Uncomment this method to specify if the specified item should be highlighted during tracking override func collectionView(collectionView: UICollectionView, shouldHighlightItemAtIndexPath indexPath: NSIndexPath) -> Bool { return true } */ /* // Uncomment this method to specify if the specified item should be selected override func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool { return true } */ /* // Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item override func collectionView(collectionView: UICollectionView, shouldShowMenuForItemAtIndexPath indexPath: NSIndexPath) -> Bool { return false } override func collectionView(collectionView: UICollectionView, canPerformAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) -> Bool { return false } override func collectionView(collectionView: UICollectionView, performAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) { } */ // MARK: - push tools func showGPAController() { let storyboard = UIStoryboard(name: "Main", bundle: nil) let gpaVC = storyboard.instantiateViewControllerWithIdentifier("GPATableViewController") as! GPATableViewController gpaVC.hidesBottomBarWhenPushed = true let userDefaults = NSUserDefaults() let touchIdEnabled = userDefaults.boolForKey("touchIdEnabled") if (touchIdEnabled) { let authContext = LAContext() var error: NSError? guard authContext.canEvaluatePolicy(.DeviceOwnerAuthenticationWithBiometrics, error: &error) else { return } authContext.evaluatePolicy(.DeviceOwnerAuthenticationWithBiometrics, localizedReason: "GPA这种东西才不给你看", reply: {(success, error) in if success { dispatch_async(dispatch_get_main_queue(), { self.navigationController?.showViewController(gpaVC, sender: nil) }) } else { MsgDisplay.showErrorMsg("指纹验证失败") } }) } else { self.navigationController?.showViewController(gpaVC, sender: nil) } } func showClasstableController() { let classtableVC = ClasstableViewController(nibName: "ClasstableViewController", bundle: nil) classtableVC.hidesBottomBarWhenPushed = true self.navigationController?.showViewController(classtableVC, sender: nil) } func showLibraryController() { let libVC = LibraryViewController(nibName: "LibraryViewController", bundle: nil) libVC.hidesBottomBarWhenPushed = true self.navigationController?.showViewController(libVC, sender: nil) } func showLostFoundController() { let lfVC = LostFoundViewController() lfVC.hidesBottomBarWhenPushed = true self.navigationController?.showViewController(lfVC, sender: nil) } func showMicroservicesController() { let msVC = MicroservicesTableViewController(style: .Plain) // msVC.hidesBottomBarWhenPushed = true // self.navigationController?.showViewController(msVC, sender: nil) microserviceController = STPopupController(rootViewController: msVC) microserviceController.backgroundView = UIVisualEffectView(effect: UIBlurEffect(style: .Light)) microserviceController.backgroundView.addGestureRecognizer((UITapGestureRecognizer().bk_initWithHandler({ (recognizer, state, point) in self.microserviceController.dismiss() }) as! UIGestureRecognizer)) microserviceController.containerView.layer.shadowOffset = CGSizeMake(0.0, 0.0) microserviceController.containerView.layer.shadowOpacity = 0.5 microserviceController.containerView.layer.shadowRadius = 20.0 microserviceController.containerView.clipsToBounds = false microserviceController.containerView.layer.cornerRadius = 5.0 microserviceController.presentInViewController(self) } func showBicycleServiceController() { /* guard #available(iOS 9.0, *) else { MsgDisplay.showErrorMsg("你需要 iOS 9 或以上系统才能使用该功能,请更新系统") return } */ let bikeVC = BicycleServiceViewController() //log.word(NSUserDefaults.standardUserDefaults().objectForKey("twtToken") as! String)/ if NSUserDefaults.standardUserDefaults().objectForKey("twtToken") == nil { let loginVC = LoginViewController(nibName: "LoginViewController", bundle: nil) self.presentViewController(loginVC, animated: true, completion: nil) } else { //坑:让后面能自动弹出要求绑定,但是做法不太科学,应改为 Notification BicycleUser.sharedInstance.bindCancel = false /* if NSUserDefaults.standardUserDefaults().valueForKey("BicycleToken") != nil { let BicycleExpire = NSUserDefaults.standardUserDefaults().valueForKey("BicycleExpire") as? Int let now = NSDate() let timeInterval: NSTimeInterval = now.timeIntervalSince1970 let timeStamp = Int(timeInterval) if timeStamp <= BicycleExpire { //隐藏tabbar bikeVC.hidesBottomBarWhenPushed = true; self.navigationController?.showViewController(bikeVC, sender: nil) } else { BicycleUser.sharedInstance.auth({ //隐藏tabbar bikeVC.hidesBottomBarWhenPushed = true; self.navigationController?.showViewController(bikeVC, sender: nil) }) } } else { }*/ BicycleUser.sharedInstance.auth({ //隐藏tabbar bikeVC.hidesBottomBarWhenPushed = true self.navigationController?.showViewController(bikeVC, sender: nil) }) } } func showPartyServiceController() { /* guard #available(iOS 9.0, *) else { MsgDisplay.showErrorMsg("你需要 iOS 9 或以上系统才能使用该功能,请更新系统") return } */ let partyVC = PartyMainViewController() partyVC.hidesBottomBarWhenPushed = true guard NSUserDefaults.standardUserDefaults().objectForKey("studentID") != nil else { Applicant.sharedInstance.getStudentNumber({ self.navigationController?.showViewController(partyVC, sender: nil) }) return } self.navigationController?.showViewController(partyVC, sender: nil) //FIXME: This takes an awful lot of time and makes the main thread laggggggg /*Applicant.sharedInstance.getStudentNumber({ self.navigationController?.showViewController(partyVC, sender: nil) })*/ } func showReadController() { guard let _ = NSUserDefaults.standardUserDefaults().objectForKey("twtToken") else { MsgDisplay.showErrorMsg("你需要登录才能访问") let loginVC = LoginViewController(nibName: "LoginViewController", bundle: nil) UIViewController.currentViewController().presentViewController(loginVC, animated: true, completion: nil) return } let readVC = ReadViewController() readVC.hidesBottomBarWhenPushed = true self.navigationController?.showViewController(readVC, sender: nil) } func showYellowPageController() { let ypVC = YellowPageMainViewController() ypVC.hidesBottomBarWhenPushed = true self.navigationController?.showViewController(ypVC, sender: nil) } }
mit
86d476e1912c1f3e13a05a7a51235a2c
39.222892
185
0.65179
5.490954
false
false
false
false