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
Pluto-Y/SwiftyEcharts
SwiftyEchartsTest_iOS/GeoSepc.swift
1
7648
// // GeoSepc.swift // SwiftyEcharts // // Created by Pluto Y on 15/07/2017. // Copyright © 2017 com.pluto-y. All rights reserved. // import Quick import Nimble @testable import SwiftyEcharts class GeoSepc: QuickSpec { override func spec() { let minScaleLimitValue: Float = 2.552 let maxScaleLimitValue: Float = 100.100 let scaleLimit = Geo.ScaleLimit() scaleLimit.min = minScaleLimitValue scaleLimit.max = maxScaleLimitValue describe("For Geo.ScaleLimit") { it("needs to check the jsonString") { let resultDic: [String: Jsonable] = [ "min": minScaleLimitValue, "max": maxScaleLimitValue ] expect(scaleLimit.jsonString).to(equal(resultDic.jsonString)) } it("needs to check the Enumable") { let scaleLimitByEnums = Geo.ScaleLimit( .min(minScaleLimitValue), .max(maxScaleLimitValue) ) expect(scaleLimitByEnums.jsonString).to(equal(scaleLimit.jsonString)) } } let nameRegionValue = "regionNameValue" let selectedRegionValue = false let itemStyleRegionValue = ItemStyle( .normal(CommonItemStyleContent()), .emphasis(CommonItemStyleContent( .shadowBlur(10), .shadowOffsetX(0), .shadowOffsetY(0), .shadowColor(.rgba(0, 0, 0, 0.5)) )) ) let labelRegionValue = FormattedLabel( .normal(FormattedLabelStyle(.show(true))), .emphasis(FormattedLabelStyle(.show(true))) ) let region = Geo.Region() region.name = nameRegionValue region.selected = selectedRegionValue region.itemStyle = itemStyleRegionValue region.label = labelRegionValue describe("For Geo.Region") { it("needs to check the jsonString") { let resultDic: [String: Jsonable] = [ "name": nameRegionValue, "selected": selectedRegionValue, "itemStyle": itemStyleRegionValue, "label": labelRegionValue ] expect(region.jsonString).to(equal(resultDic.jsonString)) } it("needs to check the Enumable") { let regionByEnums = Geo.Region( .name(nameRegionValue), .selected(selectedRegionValue), .itemStyle(itemStyleRegionValue), .label(labelRegionValue) ) expect(regionByEnums.jsonString).to(equal(region.jsonString)) } } describe("For Geo") { let showValue = true let mapValue = "China" let roamValue = false let centerValue: Point = [1.28521, 4832.273] let aspectScaleValue: Float = 4.245 let zoomValue: Float = 3.245 let scaleLimitValue = scaleLimit let nameMapValue: String = "{'China': '中国'}" let selectedModeValue = SelectedMode.multiple let labelValue = FormattedLabel( .normal(FormattedLabelStyle( .show(true), .position(.outside), .offset([10, 0]), .textStyle(TextStyle( .fontSize(6) )) )) ) let itemStyleValue = ItemStyle( .normal(CommonItemStyleContent( .opacity(0.8), .shadowBlur(10), .shadowOffsetX(0), .shadowOffsetY(0), .shadowColor(.rgba(0, 0, 0, 0.5)) )) ) let zlevelValue: Float = 5.22 let zValue: Float = 2.1023 let leftValue = Position.insideLeft let rightValue = Position.insideRight let bottomValue = Position.insideBottom let topValue = Position.insideTop let layoutCenterValue = "bottom" let layoutSizeValue = "['30%', '30%']" let regionsValue: [Geo.Region] = [region] let silentValue = true let geo = Geo() geo.show = showValue geo.map = mapValue geo.roam = roamValue geo.center = centerValue geo.aspectScale = aspectScaleValue geo.zoom = zoomValue geo.scaleLimit = scaleLimitValue geo.nameMap = nameMapValue geo.selectedMode = selectedModeValue geo.label = labelValue geo.itemStyle = itemStyleValue geo.zlevel = zlevelValue geo.z = zValue geo.left = leftValue geo.top = topValue geo.right = rightValue geo.bottom = bottomValue geo.layoutCenter = layoutCenterValue geo.layoutSize = layoutSizeValue geo.regions = regionsValue geo.silent = silentValue it("needs to check the jsonString") { let resultDic: [String: Jsonable] = [ "show": showValue, "map": mapValue, "roam": roamValue, "center": centerValue, "aspectScale": aspectScaleValue, "zoom": zoomValue, "scaleLimit": scaleLimitValue, "nameMap": nameMapValue, "selectedMode": selectedModeValue, "label": labelValue, "itemStyle": itemStyleValue, "zlevel": zlevelValue, "z": zValue, "left": leftValue, "top": topValue, "right": rightValue, "bottom": bottomValue, "layoutCenter": layoutCenterValue, "layoutSize": layoutSizeValue, "regions": regionsValue, "silent": silentValue ] expect(geo.jsonString).to(equal(resultDic.jsonString)) } it("needs to check the Enumable") { let geoByEnums = Geo( .show(showValue), .map(mapValue), .roam(roamValue), .center(centerValue), .aspectScale(aspectScaleValue), .zoom(zoomValue), .scaleLimit(scaleLimitValue), .nameMap(nameMapValue), .selectedMode(selectedModeValue), .label(labelValue), .itemStyle(itemStyleValue), .zlevel(zlevelValue), .z(zValue), .left(leftValue), .top(topValue), .right(rightValue), .bottom(bottomValue), .layoutCenter(layoutCenterValue), .layoutSize(layoutSizeValue), .regions(regionsValue), .silent(silentValue) ) expect(geoByEnums.jsonString).to(equal(geo.jsonString)) } } } }
mit
11ef0835d77d48781f8536eaa929d2bc
35.745192
85
0.475991
5.506484
false
false
false
false
juliantejera/JTDataStructures
Pods/Nimble/Sources/Nimble/Adapters/NMBExpectation.swift
5
6485
import Foundation #if (os(macOS) || os(iOS) || os(tvOS) || os(watchOS)) && !SWIFT_PACKAGE private func from(objcPredicate: NMBPredicate) -> Predicate<NSObject> { return Predicate { actualExpression in let result = objcPredicate.satisfies(({ try! actualExpression.evaluate() }), location: actualExpression.location) return result.toSwift() } } internal struct ObjCMatcherWrapper: Matcher { let matcher: NMBMatcher func matches(_ actualExpression: Expression<NSObject>, failureMessage: FailureMessage) -> Bool { return matcher.matches( ({ try! actualExpression.evaluate() }), failureMessage: failureMessage, location: actualExpression.location) } func doesNotMatch(_ actualExpression: Expression<NSObject>, failureMessage: FailureMessage) -> Bool { return matcher.doesNotMatch( ({ try! actualExpression.evaluate() }), failureMessage: failureMessage, location: actualExpression.location) } } // Equivalent to Expectation, but for Nimble's Objective-C interface public class NMBExpectation: NSObject { internal let _actualBlock: () -> NSObject? internal var _negative: Bool internal let _file: FileString internal let _line: UInt internal var _timeout: TimeInterval = 1.0 @objc public init(actualBlock: @escaping () -> NSObject?, negative: Bool, file: FileString, line: UInt) { self._actualBlock = actualBlock self._negative = negative self._file = file self._line = line } private var expectValue: Expectation<NSObject> { return expect(_file, line: _line) { self._actualBlock() as NSObject? } } @objc public var withTimeout: (TimeInterval) -> NMBExpectation { return ({ timeout in self._timeout = timeout return self }) } @objc public var to: (NMBMatcher) -> Void { return ({ matcher in if let pred = matcher as? NMBPredicate { self.expectValue.to(from(objcPredicate: pred)) } else { self.expectValue.to(ObjCMatcherWrapper(matcher: matcher)) } }) } @objc public var toWithDescription: (NMBMatcher, String) -> Void { return ({ matcher, description in if let pred = matcher as? NMBPredicate { self.expectValue.to(from(objcPredicate: pred), description: description) } else { self.expectValue.to(ObjCMatcherWrapper(matcher: matcher), description: description) } }) } @objc public var toNot: (NMBMatcher) -> Void { return ({ matcher in if let pred = matcher as? NMBPredicate { self.expectValue.toNot(from(objcPredicate: pred)) } else { self.expectValue.toNot(ObjCMatcherWrapper(matcher: matcher)) } }) } @objc public var toNotWithDescription: (NMBMatcher, String) -> Void { return ({ matcher, description in if let pred = matcher as? NMBPredicate { self.expectValue.toNot(from(objcPredicate: pred), description: description) } else { self.expectValue.toNot(ObjCMatcherWrapper(matcher: matcher), description: description) } }) } @objc public var notTo: (NMBMatcher) -> Void { return toNot } @objc public var notToWithDescription: (NMBMatcher, String) -> Void { return toNotWithDescription } @objc public var toEventually: (NMBMatcher) -> Void { return ({ matcher in if let pred = matcher as? NMBPredicate { self.expectValue.toEventually( from(objcPredicate: pred), timeout: self._timeout, description: nil ) } else { self.expectValue.toEventually( ObjCMatcherWrapper(matcher: matcher), timeout: self._timeout, description: nil ) } }) } @objc public var toEventuallyWithDescription: (NMBMatcher, String) -> Void { return ({ matcher, description in if let pred = matcher as? NMBPredicate { self.expectValue.toEventually( from(objcPredicate: pred), timeout: self._timeout, description: description ) } else { self.expectValue.toEventually( ObjCMatcherWrapper(matcher: matcher), timeout: self._timeout, description: description ) } }) } @objc public var toEventuallyNot: (NMBMatcher) -> Void { return ({ matcher in if let pred = matcher as? NMBPredicate { self.expectValue.toEventuallyNot( from(objcPredicate: pred), timeout: self._timeout, description: nil ) } else { self.expectValue.toEventuallyNot( ObjCMatcherWrapper(matcher: matcher), timeout: self._timeout, description: nil ) } }) } @objc public var toEventuallyNotWithDescription: (NMBMatcher, String) -> Void { return ({ matcher, description in if let pred = matcher as? NMBPredicate { self.expectValue.toEventuallyNot( from(objcPredicate: pred), timeout: self._timeout, description: description ) } else { self.expectValue.toEventuallyNot( ObjCMatcherWrapper(matcher: matcher), timeout: self._timeout, description: description ) } }) } @objc public var toNotEventually: (NMBMatcher) -> Void { return toEventuallyNot } @objc public var toNotEventuallyWithDescription: (NMBMatcher, String) -> Void { return toEventuallyNotWithDescription } @objc public class func failWithMessage(_ message: String, file: FileString, line: UInt) { fail(message, location: SourceLocation(file: file, line: line)) } } #endif
mit
76c11d3f8f90d27cddc6e8fab5e8b685
33.679144
109
0.558828
5.505093
false
false
false
false
josepvaleriano/iOS-practices
NavigationExample/TableViewController.swift
1
4738
// // TableViewController.swift // NavigationExample // // Created by Infraestructura on 24/09/16. // Copyright © 2016 Valeriano Lopez. All rights reserved. // import UIKit class TableViewController: UITableViewController { var elArreglo: NSArray? var elArreglo2: NSArray? override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() self.elArreglo = ["comida", "Bebida","lugar", "Otros"] self.elArreglo2 = [["Margarita", "BBQ Chicken", "Pepperoni","sausage", "meat lovers", "veggie lovers","sausage", "chicken pesto", "prawns", "mushrooms","Agua","Refresco"], ["Limonada","Cerveza","Tequila","Ron"], ["Cancun","Italia","Patagonia"], ["Privacidad"]] //self.elArreglo2 = ["Agua","Refresco","Limonada","Cerveza","Tequila","Ron"] // self.elArreglo2 = ["Cancun","Italia","Patagonia"] } override func viewWillAppear(animated: Bool) { self.navigationItem.title = "Comida" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return self.elArreglo2!.count } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return self.elArreglo2![section].count } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return self.elArreglo![section] as? String } override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 20.0 } override func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 20.0 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("cellForReuse", forIndexPath: indexPath) /* // 2 formas de buscar objeto por la version de xcode y ver del ios let item = self.elArreglo2! [indexPath.section] as! NSArray cell.textLabel!.text = (item [indexPath.row]as! String) */ cell.textLabel!.text = (self.elArreglo2! [indexPath.section] [indexPath.row]as! String) return cell } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
9b3785f9e2b5e70c4fa9e9a4a51f7cd8
35.72093
268
0.667511
4.818922
false
false
false
false
DroidsOnRoids/MazeSpriteKit
Maze/GameScene.swift
1
5058
/* * Copyright (c) 2015 Droids on Roids 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 CoreMotion import SpriteKit struct Collision { static let Ball: UInt32 = 0x1 << 0 // bin(001) = dec(1) static let BlackHole: UInt32 = 0x1 << 1 // bin(010) = dec(2) static let FinishHole: UInt32 = 0x1 << 2 // bin(100) = dec(4) } class GameScene: SKScene { var manager: CMMotionManager? var ball: SKSpriteNode! var timer: NSTimer? var seconds: Double? // MARK: - SpriteKit Methods override func didMoveToView(view: SKView) { timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: "increaseTimer", userInfo: nil, repeats: true) physicsWorld.contactDelegate = self ball = SKSpriteNode(imageNamed: "Ball") ball.position = CGPoint(x: CGRectGetMidX(frame), y: CGRectGetMidY(frame)) ball.physicsBody = SKPhysicsBody(circleOfRadius: CGRectGetHeight(ball.frame) / 2.0) ball.physicsBody?.mass = 4.5 ball.physicsBody?.allowsRotation = false ball.physicsBody?.dynamic = true // necessary to detect collision ball.physicsBody?.categoryBitMask = Collision.Ball ball.physicsBody?.collisionBitMask = Collision.Ball ball.physicsBody?.contactTestBitMask = Collision.BlackHole | Collision.FinishHole ball.physicsBody?.affectedByGravity = false addChild(ball) manager = CMMotionManager() if let manager = manager where manager.deviceMotionAvailable { manager.deviceMotionUpdateInterval = 0.01 manager.startDeviceMotionUpdates() } } override func update(currentTime: CFTimeInterval) { if let gravityX = manager?.deviceMotion?.gravity.x, gravityY = manager?.deviceMotion?.gravity.y where ball != nil { // let newPosition = CGPoint(x: Double(ball.position.x) + gravityX * 35.0, y: Double(ball.position.y) + gravityY * 35.0) // let moveAction = SKAction.moveTo(newPosition, duration: 0.0) // ball.runAction(moveAction) // applyImpulse() is much better than applyForce() // ball.physicsBody?.applyForce(CGVector(dx: CGFloat(gravityX) * 5000.0, dy: CGFloat(gravityY) * 5000.0)) ball.physicsBody?.applyImpulse(CGVector(dx: CGFloat(gravityX) * 200.0, dy: CGFloat(gravityY) * 200.0)) } } // MARK: - Ball Methods func centerBall() { ball.physicsBody?.velocity = CGVector(dx: 0.0, dy: 0.0) let moveAction = SKAction.moveTo(CGPoint(x: CGRectGetMidX(frame), y: CGRectGetMidY(frame)), duration: 0.0) ball.runAction(moveAction) } func alertWon() { let alertController = UIAlertController(title: "You've won", message: String(format: "It took you %.1f seconds", arguments: [seconds!]), preferredStyle: .Alert) let okAction = UIAlertAction(title: "OK", style: .Default) { (action) -> Void in self.resetTimer() self.centerBall() } alertController.addAction(okAction) if let rootViewController = view?.window?.rootViewController { rootViewController.presentViewController(alertController, animated: true, completion: { () -> Void in self.centerBall() }) } } // MARK: - Timer Methods func increaseTimer() { seconds = (seconds ?? 0.0) + 0.01 } func resetTimer() { seconds = 0.0 } } // MARK: - SKPhysicsContact Delegate Methods extension GameScene: SKPhysicsContactDelegate { func didBeginContact(contact: SKPhysicsContact) { if contact.bodyA.categoryBitMask == Collision.BlackHole || contact.bodyB.categoryBitMask == Collision.BlackHole { centerBall() resetTimer() } else if contact.bodyA.categoryBitMask == Collision.FinishHole || contact.bodyB.categoryBitMask == Collision.FinishHole { alertWon() } } }
mit
99b377ce9cea55aeaf983eb576346b6d
40.801653
168
0.663503
4.585675
false
false
false
false
X140Yu/Lemon
Lemon/Library/ViewController/LemonNavigationViewController.swift
1
591
import UIKit class LemonNavigationViewController: UINavigationController { override func viewDidLoad() { super.viewDidLoad() style() } private func style() { navigationBar.isTranslucent = false let color = UIColor.lmDarkGrey guard let font = UIFont(name: "Menlo-Regular", size: 20) else { navigationBar.titleTextAttributes = [ NSAttributedStringKey.foregroundColor: color ] return } navigationBar.titleTextAttributes = [ NSAttributedStringKey.foregroundColor: color, NSAttributedStringKey.font: font ] } }
gpl-3.0
d0b5a7a27d9a928da253426f6841b380
20.107143
67
0.690355
5.230088
false
false
false
false
sergii-frost/weeknum-ios
weeknum/watchWeeknum Extension/InterfaceController.swift
1
1834
// // InterfaceController.swift // watchWeeknum Extension // // Created by Sergii Nezdolii on 02/07/16. // Copyright © 2016 FrostDigital. All rights reserved. // import WatchKit import Foundation class InterfaceController: WKInterfaceController { @IBOutlet var dateDetailsLabel: WKInterfaceLabel! @IBOutlet var weekInfoLabel: WKInterfaceLabel! @IBOutlet var weekNumberLabel: WKInterfaceLabel! var currentDate: Date = Date() override func awake(withContext context: Any?) { super.awake(withContext: context) // Configure interface objects here. } override func willActivate() { // This method is called when watch view controller is about to be visible to user super.willActivate() updateForToday() } override func didDeactivate() { // This method is called when watch view controller is no longer visible super.didDeactivate() } fileprivate func updateUIWithDate(_ date: Date?) { guard let date = date else {return} currentDate = date self.dateDetailsLabel.setText(FormatterUtils.formattedDate(currentDate)) if let weekInfo = FormatterUtils.getWeekInfo(currentDate) { self.weekInfoLabel.setText(weekInfo) } else { self.weekInfoLabel.setText(nil) } if let weekNumber = currentDate.weekNumber() { self.weekNumberLabel.setText(String(weekNumber)) } else { self.weekNumberLabel.setText(nil) } } @IBAction func updateForToday() { updateUIWithDate(Date()) } @IBAction func updateForPreviousWeek() { updateUIWithDate(currentDate.weekBefore()) } @IBAction func updateForNextWeek() { updateUIWithDate(currentDate.weekAfter()) } }
mit
734b4d055f2be8a72498f8303f959185
27.640625
90
0.657392
4.823684
false
false
false
false
iOSDevLog/iOSDevLog
126. Internationalization/AutoLayout/User.swift
1
1627
// // User.swift // Autolayout // // Created by CS193p Instructor. // Copyright (c) 2015 Stanford University. All rights reserved. // import Foundation struct User { let name: String let company: String let login: String let password: String var lastLogin = NSDate.demoRandom() init(name: String, company: String, login: String, password: String) { self.name = name self.company = company self.login = login self.password = password } static func login(login: String, password: String) -> User? { if let user = database[login] { if user.password == password { return user } } return nil } static let database: Dictionary<String, User> = { var theDatabase = Dictionary<String, User>() for user in [ User(name: "John Appleseed", company: "Apple", login: "japple", password: "foo"), User(name: "Madison Bumgarner", company: "World Champion San Francisco Giants", login: "madbum", password: "foo"), User(name: "John Hennessy", company: "Stanford", login: "hennessy", password: "foo"), User(name: "Bad Guy", company: "Criminals, Inc.", login: "baddie", password: "foo") ] { theDatabase[user.login] = user } return theDatabase }() } private extension NSDate { class func demoRandom() -> NSDate { let randomIntervalIntoThePast = -Double(arc4random() % 60*60*24*20) return NSDate(timeIntervalSinceNow: randomIntervalIntoThePast) } }
mit
6798564a0ac024064c83f68aa43548d1
28.6
126
0.590043
4.118987
false
false
false
false
TimurBK/SwiftSampleProject
Pods/ProcedureKit/Sources/Group.swift
1
24360
// // ProcedureKit // // Copyright © 2016 ProcedureKit. All rights reserved. // // swiftlint:disable file_length import Foundation import Dispatch /** A `Procedure` subclass which enables the grouping of other procedures. Use `Group`s to associate related operations together, thereby creating higher levels of abstractions. */ open class GroupProcedure: Procedure, ProcedureQueueDelegate { internal struct GroupErrors { typealias ByOperation = Dictionary<Operation, Array<Error>> var fatal = [Error]() var attemptedRecovery: ByOperation = [:] var attemptedRecoveryErrors: [Error] { return Array(attemptedRecovery.values.flatMap { $0 }) } var all: [Error] { get { var tmp: [Error] = fatal tmp.append(contentsOf: attemptedRecoveryErrors) return tmp } } } internal let queue = ProcedureQueue() fileprivate let finishing = BlockOperation { } fileprivate var groupErrors = Protector(GroupErrors()) fileprivate var groupChildren: Protector<[Operation]> fileprivate var groupIsFinishing = false fileprivate var groupFinishLock = NSRecursiveLock() fileprivate var groupIsSuspended = false fileprivate var groupSuspendLock = NSLock() fileprivate var groupIsAddingOperations = DispatchGroup() fileprivate var groupCanFinish: CanFinishGroup! /// - returns: the operations which have been added to the queue final public var children: [Operation] { get { return groupChildren.read { $0 } } } /** Designated initializer for GroupProcedure. Create a GroupProcedure with an array of Operation instances. Optionally provide the underlying dispatch queue for the group's internal ProcedureQueue. - parameter underlyingQueue: an optional DispatchQueue which defaults to nil, this parameter is set as the underlying queue of the group's own ProcedureQueue. - parameter operations: an array of Operation instances. Note that these do not have to be Procedure instances - you can use `Foundation.Operation` instances from other sources. */ public init(dispatchQueue underlyingQueue: DispatchQueue? = nil, operations: [Operation]) { groupChildren = Protector(operations) /** GroupProcedure is responsible for calling `finish()` on cancellation once all of its childred have cancelled and finished, and its own finishing operation has finished. Therefore we disable `Procedure`'s automatic finishing mechanisms. */ super.init(disableAutomaticFinishing: true) queue.isSuspended = true queue.underlyingQueue = underlyingQueue queue.delegate = self userIntent = operations.userIntent groupCanFinish = CanFinishGroup(group: self) addDidCancelBlockObserver { group, errors in if errors.isEmpty { group.children.forEach { $0.cancel() } } else { let (operations, procedures) = group.children.operationsAndProcedures operations.forEach { $0.cancel() } procedures.forEach { $0.cancel(withError: ProcedureKitError.parent(cancelledWithErrors: errors)) } } } } public convenience init(operations: Operation...) { self.init(operations: operations) } deinit { // To ensure that any remaining operations on the internal queue are released // we must cancelAllOperations and also ensure the queue is not suspended. queue.cancelAllOperations() queue.isSuspended = false // If you find that execution is stuck on the following line, one of the child // Operations/Procedures is likely not handling cancellation and finishing. queue.waitUntilAllOperationsAreFinished() } // MARK: - Execute open override func execute() { add(additional: children.filter { !queue.operations.contains($0) }, toOperationsArray: false) add(canFinishGroup: groupCanFinish) queue.addOperation(finishing) groupSuspendLock.withCriticalScope { if !groupIsSuspended { queue.isSuspended = false } } } // MARK: - Error recovery and child finishing /** This method is called when a child will finish with errors. Often an operation will finish with errors become some of its pre-requisites were not met. Errors of this nature should be recoverable. This can be done by re-trying the original operation, but with another operation which fulfil the pre-requisites as a dependency. If the errors were recovered from, return true from this method, else return false. Errors which are not handled will result in the GroupProcedure finishing with errors. - parameter child: the child operation which is finishing - parameter errors: an [ErrorType], the errors of the child operation - returns: a Boolean, return true if the errors were handled, else return false. */ open func child(_ child: Operation, willAttemptRecoveryFromErrors errors: [Error]) -> Bool { return false } /** This method is only called when a child finishes without any errors. - parameter child: the Operation which will finish without errors */ open func childWillFinishWithoutErrors(_ child: Operation) { /* no-op */ } // MARK - OperationQueueDelegate public func operationQueue(_ queue: OperationQueue, didFinishOperation operation: Operation) { guard queue === self.queue else { return } if operation === finishing { finish(withErrors: errors) queue.isSuspended = true } } // MARK: - ProcedureQueueDelegate private var shouldAddOperation: Bool { return groupFinishLock.withCriticalScope { guard !groupIsFinishing else { assertionFailure("Cannot add new operations to a group after the group has started to finish.") return false } groupIsAddingOperations.enter() return true } } /** The group acts as its own queue's delegate. When an operation is added to the queue, assuming that the group is not yet finishing or finished, then we add the operation as a dependency to an internal "barrier" operation that separates executing from finishing state. The purpose of this is to keep the internal operation as a final child operation that executes when there are no more operations in the group operation, safely handling the transition of group operation state. */ public func procedureQueue(_ queue: ProcedureQueue, willAddOperation operation: Operation) { guard queue === self.queue && operation !== finishing else { return } assert(!finishing.isExecuting, "Cannot add new operations to a group after the group has started to finish.") assert(!finishing.isFinished, "Cannot add new operations to a group after the group has completed.") guard shouldAddOperation else { return } observers.forEach { $0.procedure(self, willAdd: operation) } groupCanFinish.addDependency(operation) groupFinishLock.withCriticalScope { groupIsAddingOperations.leave() } observers.forEach { $0.procedure(self, didAdd: operation) } } public func procedureQueue(_ queue: ProcedureQueue, willProduceOperation operation: Operation) { guard queue === self.queue && operation !== finishing else { return } assert(!finishing.isExecuting, "Cannot add new operations to a group after the group has started to finish.") assert(!finishing.isFinished, "Cannot add new operations to a group after the group has completed.") guard shouldAddOperation else { return } // Ensure that produced operations are added to the Group's // internal array (and cancelled if appropriate) groupChildren.append(operation) if isCancelled && !operation.isCancelled { operation.cancel() } groupFinishLock.withCriticalScope { groupIsAddingOperations.leave() } } /** The group acts as it's own queue's delegate. When an operation finishes, if the operation is the finishing operation, we finish the group operation here. Else, the group is notified that a child operation has finished. */ public func procedureQueue(_ queue: ProcedureQueue, willFinishOperation operation: Operation, withErrors errors: [Error]) { guard queue === self.queue else { return } /// If the group is cancelled, exit early guard !isCancelled else { return } /// If the operation is a Procedure.EvaluateConditions - exit early. if operation is Procedure.EvaluateConditions { return } if !errors.isEmpty { if child(operation, willAttemptRecoveryFromErrors: errors) { child(operation, didAttemptRecoveryFromErrors: errors) } else { child(operation, didEncounterFatalErrors: errors) } } else if operation !== finishing { childWillFinishWithoutErrors(operation) } } public func procedureQueue(_ queue: ProcedureQueue, didFinishOperation operation: Operation, withErrors errors: [Error]) { } } // MARK: - GroupProcedure API public extension GroupProcedure { /** Access the underlying queue of the GroupProcedure. - returns: the DispatchQueue of the groups private ProcedureQueue */ final var dispatchQueue: DispatchQueue? { return queue.underlyingQueue } /** The maximum number of child operations that can execute at the same time. The value in this property affects only the operations that the current GroupProcedure has executing at the same time. Other operation queues and GroupProcedures can also execute their maximum number of operations in parallel. Reducing the number of concurrent operations does not affect any operations that are currently executing. Specifying the value NSOperationQueueDefaultMaxConcurrentOperationCount (which is recommended) causes the system to set the maximum number of operations based on system conditions. The default value of this property is NSOperationQueueDefaultMaxConcurrentOperationCount. */ final var maxConcurrentOperationCount: Int { get { return queue.maxConcurrentOperationCount } set { queue.maxConcurrentOperationCount = newValue } } /** A Boolean value indicating whether the GroupProcedure is actively scheduling operations for execution. When the value of this property is false, the GroupProcedure actively starts child operations that are ready to execute once the GroupProcedure has been executed. Setting this property to true prevents the GroupProcedure from starting any child operations, but already executing child operations continue to execute. You may continue to add operations to a GroupProcedure that is suspended but those operations are not scheduled for execution until you change this property to false. The default value of this property is false. */ final var isSuspended: Bool { get { return groupSuspendLock.withCriticalScope { groupIsSuspended } } set { groupSuspendLock.withCriticalScope { groupIsSuspended = newValue queue.isSuspended = newValue } } } /** The default service level to apply to the GroupProcedure and its child operations. This property specifies the service level applied to the GroupProcedure itself, and to operation objects added to the GroupProcedure. If the added operation object has an explicit service level set, that value is used instead. For more, see the NSOperation and NSOperationQueue documentation for `qualityOfService`. */ @available(OSX 10.10, iOS 8.0, tvOS 8.0, watchOS 2.0, *) final public override var qualityOfService: QualityOfService { get { return queue.qualityOfService } set { super.qualityOfService = newValue queue.qualityOfService = newValue } } /// Override of Procedure.userIntent final public override var userIntent: UserIntent { didSet { let (operations, procedures) = children.operationsAndProcedures operations.forEach { $0.setQualityOfService(fromUserIntent: userIntent) } procedures.forEach { $0.userIntent = userIntent } } } } // MARK: - Add Child API public extension GroupProcedure { /** Add a single child Operation instance to the group - parameter child: an Operation instance */ final func add(child: Operation) { add(children: child) } /** Add children Operation instances to the group - parameter children: a variable number of Operation instances */ final func add(children: Operation...) { add(children: children) } /** Add a sequence of Operation instances to the group - parameter children: a sequence of Operation instances */ final func add<Children: Collection>(children: Children) where Children.Iterator.Element: Operation { add(additional: children, toOperationsArray: true) } private var shouldAddChildren: Bool { return groupFinishLock.withCriticalScope { log.verbose(message: "checking to see if we can add child operations.") guard !groupIsFinishing else { return false } groupIsAddingOperations.enter() return true } } final fileprivate func add<Additional: Collection>(additional: Additional, toOperationsArray shouldAddToProperty: Bool) where Additional.Iterator.Element: Operation { // Exit early if there are no children in the collection guard !additional.isEmpty else { return } // Check to see if should add child operations, depending on finishing state guard shouldAddChildren else { let message = !finishing.isFinished ? "started to finish" : "completed" assertionFailure("Cannot add new children to a group after the group has \(message).") return } log.verbose(message: "is adding child operations to the queue.") // Check for the group being cancelled, and cancel the children var didHandleCancelled = false if isCancelled { additional.forEach { $0.cancel() } didHandleCancelled = true } // Set the log severity on each child procedure let severity = log.severity additional.forEachProcedure { $0.log.severity = severity } // Add the children to the queue queue.add(operations: additional) // Add the children to group property if shouldAddToProperty { let childrenToAdd: [Operation] = Array(additional) groupChildren.append(contentsOf: childrenToAdd) } // Check again for the group being cancelled, and cancel the children if necessary if !didHandleCancelled && isCancelled { // It is possible that the cancellation happened before adding the // additional operations to the operations array. // Thus, ensure that all additional operations are cancelled. additional.forEach { if !$0.isCancelled { $0.cancel() } } } // Leave the is adding operation group groupFinishLock.withCriticalScope { groupIsAddingOperations.leave() log.verbose(message: "finished adding child operations to the queue.") } } } // MARK: - Error Handling & Recovery public extension GroupProcedure { internal var attemptedRecoveryErrors: [Error] { return groupErrors.read { $0.attemptedRecoveryErrors } } public override var errors: [Error] { get { return groupErrors.read { $0.fatal } } set { groupErrors.write { (ward: inout GroupErrors) in ward.fatal = newValue } } } final public func append(fatalError error: Error) { append(fatalErrors: [error]) } final public func child(_ child: Operation, didEncounterFatalError error: Error) { log.warning(message: "\(child.operationName) did encounter fatal error: \(error).") append(fatalError: error) } final public func append(fatalErrors errors: [Error]) { groupErrors.write { (ward: inout GroupErrors) in ward.fatal.append(contentsOf: errors) } } final public func child(_ child: Operation, didEncounterFatalErrors errors: [Error]) { log.warning(message: "\(child.operationName) did encounter \(errors.count) fatal errors.") append(fatalErrors: errors) } public func child(_ child: Operation, didAttemptRecoveryFromErrors errors: [Error]) { groupErrors.write { (ward: inout GroupErrors) in ward.attemptedRecovery[child] = errors } } fileprivate var attemptedRecovery: GroupErrors.ByOperation { return groupErrors.read { $0.attemptedRecovery } } final public func childDidRecoverFromErrors(_ child: Operation) { if let _ = attemptedRecovery[child] { log.notice(message: "successfully recovered from errors in \(child)") groupErrors.write { (ward: inout GroupErrors) in ward.attemptedRecovery.removeValue(forKey: child) } } } final public func childDidNotRecoverFromErrors(_ child: Operation) { log.notice(message: "failed to recover from errors in \(child)") groupErrors.write { (ward: inout GroupErrors) in if let errors = ward.attemptedRecovery.removeValue(forKey: child) { ward.fatal.append(contentsOf: errors) } } } } // MARK: - Finishing fileprivate extension GroupProcedure { fileprivate final class CanFinishGroup: Operation { private weak var group: GroupProcedure? private var _isFinished = false private var _isExecuting = false init(group: GroupProcedure) { self.group = group super.init() } fileprivate override func start() { // Override Operation.start() because this operation may have to // finish asynchronously (if it has to register to be notified when // operations are no longer being added concurrently). // // Since we override start(), it is important to send Operation // isExecuting / isFinished KVO notifications. // // (Otherwise, the operation may not be released, there may be // problems with dependencies, with the queue's handling of // maxConcurrentOperationCount, etc.) isExecuting = true main() } override func main() { execute() } func execute() { if let group = group { group.log.verbose(message: "executing can finish group operation.") // All operations that were added as a side-effect of anything up to // WillFinishObservers of prior operations should have been executed. // // Handle an edge case caused by concurrent calls to Group.add(children:) let isWaiting: Bool = group.groupFinishLock.withCriticalScope { // Is anything currently adding operations? guard group.groupIsAddingOperations.wait(timeout: DispatchTime.now()) == .success else { // Operations are actively being added to the group // Wait for this to complete before proceeding. // // Register to dispatch a new call to execute() in the future, after the // wait completes (i.e. after concurrent calls to Group.add(children:) // have completed), and return from this call to execute() without finishing // the operation. group.log.verbose(message: "cannot finish now, as group is currently adding children.") let dispatchQueue = DispatchQueue.global(qos: group.qualityOfService.qosClass) group.groupIsAddingOperations.notify(queue: dispatchQueue, execute: execute) return true } // Check whether new children were added prior to the lock // by checking for child operations that are not finished. let active = group.children.filter({ !$0.isFinished }) if !active.isEmpty { // Children were added after this CanFinishOperation became // ready, but before it executed or before the lock could be acquired. group.log.verbose(message: "cannot finish now, as there are children still active.") // The GroupProcedure should wait for these children to finish // before finishing. Add the oustanding children as // dependencies to a new CanFinishGroup, and add that as the // Group's new CanFinishGroup. let newCanFinishGroup = GroupProcedure.CanFinishGroup(group: group) active.forEach { newCanFinishGroup.addDependency($0) } group.groupCanFinish = newCanFinishGroup group.add(canFinishGroup: newCanFinishGroup) } else { // There are no additional children to handle. // Ensure that no new operations can be added. group.log.verbose(message: "can now finish.") group.groupIsFinishing = true } return false } // End of isWaiting guard !isWaiting else { return } } isExecuting = false isFinished = true } override private(set) var isExecuting: Bool { get { return _isExecuting } set { willChangeValue(forKey: .executing) _isExecuting = newValue didChangeValue(forKey: .executing) } } override private(set) var isFinished: Bool { get { return _isFinished } set { willChangeValue(forKey: .finished) _isFinished = newValue didChangeValue(forKey: .finished) } } } fileprivate func add(canFinishGroup: CanFinishGroup) { finishing.addDependency(canFinishGroup) queue.add(canFinishGroup: canFinishGroup) } } fileprivate extension ProcedureQueue { func add(canFinishGroup: GroupProcedure.CanFinishGroup) { // Do not add observers (not needed - CanFinishGroup is an implementation detail of Group) // Do not add conditions (CanFinishGroup has none) // Call OperationQueue.addOperation() directly super.addOperation(canFinishGroup) } } // MARK: - Unavailable public extension GroupProcedure { @available(*, unavailable, renamed: "children") var operations: [Operation] { return children } @available(*, unavailable, renamed: "isSuspended") final var suspended: Bool { return isSuspended } @available(*, unavailable, renamed: "add(child:)") func addOperation(operation: Operation) { } @available(*, unavailable, renamed: "add(children:)") func addOperations(operations: Operation...) { } @available(*, unavailable, renamed: "add(children:)") func addOperations(additional: [Operation]) { } }
mit
2dc271f97b653d8b647ce3c895793a5d
35.796073
170
0.642719
5.325536
false
false
false
false
WSDOT/wsdot-ios-app
wsdot/TravelerInfoViewController.swift
1
7370
// // TravelerInfoViewController.swift // WSDOT // // Copyright (c) 2016 Washington State Department of Transportation // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the Licensevarr // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/> // import UIKit import GoogleMobileAds class TravelerInfoViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, GADBannerViewDelegate { let cellIdentifier = "TravelerInfoCell" let SegueTravelTimesViewController = "TravelTimesViewController" let SegueExpressLanesViewController = "ExpressLanesViewController" let SegueBestTimesToTravelRoutesViewController = "BestTimesToTravelRoutesViewController" let SegueNewsViewController = "NewsViewController" let SegueHappeningNowViewController = "HappeningNowTabViewController" let SegueBridgeAlertsViewController = "BridgeAlertsViewController" @IBOutlet weak var tableView: UITableView! @IBOutlet weak var activityIndicator: UIActivityIndicatorView! @IBOutlet weak var bannerView: GAMBannerView! var menu_options: [String] = [] var bestTimesToTravel: BestTimesToTravelItem? = nil override func viewDidLoad() { super.viewDidLoad() // Set Title title = "Traveler Information" menu_options = ["Happening Now", "Travel Times", "Express Lanes", "News Releases", "Bridge Alerts"] setStandardTableLayout(tableView) checkForTravelCharts() tableView.rowHeight = UITableView.automaticDimension // Ad Banner bannerView.adUnitID = ApiKeys.getAdId() bannerView.adSize = getFullWidthAdaptiveAdSize() bannerView.rootViewController = self let request = GAMRequest() request.customTargeting = ["wsdotapp":"traffic"] bannerView.load(request) bannerView.delegate = self } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) MyAnalytics.screenView(screenName: "TravelerInformation") } /* Checks if "best time to travel charts" are available from the data server, if they are, add a new menu option to display the chart information */ func checkForTravelCharts() { self.activityIndicator.isHidden = false self.activityIndicator.startAnimating() DispatchQueue.global(qos: DispatchQoS.QoSClass.userInitiated).async { [weak self] in BestTimesToTravelStore.getBestTimesToTravel({ data, error in if let selfValue = self{ selfValue.activityIndicator.isHidden = true selfValue.activityIndicator.stopAnimating() } if let validData = data { DispatchQueue.main.async { [weak self] in if let selfValue = self{ selfValue.bestTimesToTravel = validData if (validData.available){ self?.menu_options.append(validData.name) selfValue.tableView.reloadData() } } } } }) } } // MARK: TableView methods func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat { return UITableView.automaticDimension } // MARK: Table View Data Source Methods func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return menu_options.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) // Configure Cell cell.textLabel?.lineBreakMode = .byWordWrapping cell.textLabel?.numberOfLines = 0 cell.textLabel?.text = menu_options[indexPath.row] /* switch (indexPath.row) { case 0: // Happening Now cell.imageView?.image = UIImage(named: "icBolt") break case 1: // Travel Times cell.imageView?.image = UIImage(named: "icClock") break case 2: // Express Lanes cell.imageView?.image = UIImage(named: "icRocket") break case 3: // News Releases cell.imageView?.image = UIImage(named: "icNews") break case 4: // Travel Charts cell.imageView?.image = UIImage(named: "icNotice") default: break } */ return cell } // MARK: Table View Delegate Methods func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // Perform Segue switch (indexPath.row) { case 0: // Happening Now performSegue(withIdentifier: SegueHappeningNowViewController, sender: self) tableView.deselectRow(at: indexPath, animated: true) break case 1: // Travel Times performSegue(withIdentifier: SegueTravelTimesViewController, sender: self) tableView.deselectRow(at: indexPath, animated: true) break case 2: // Express Lanes performSegue(withIdentifier: SegueExpressLanesViewController, sender: self) tableView.deselectRow(at: indexPath, animated: true) break case 3: // News Releases performSegue(withIdentifier: SegueNewsViewController, sender: self) tableView.deselectRow(at: indexPath, animated: true) break case 4: performSegue(withIdentifier: SegueBridgeAlertsViewController, sender: self) tableView.deselectRow(at: indexPath, animated: true) break case 5: // Travel Charts performSegue(withIdentifier: SegueBestTimesToTravelRoutesViewController, sender: self) tableView.deselectRow(at: indexPath, animated: true) default: break } } // MARK: Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // If travel charts are available, pass them downloaded data on if segue.identifier == SegueBestTimesToTravelRoutesViewController { let destinationViewController = segue.destination as! BestTimesToTravelRoutesViewController destinationViewController.bestTimesToTravel = self.bestTimesToTravel } } }
gpl-3.0
34002dac02e2d33ffcadd7fabdbb9ac9
35.85
119
0.627815
5.451183
false
false
false
false
dnpp73/SimpleCamera
Sources/View/Parts/FocusIndicatorView.swift
1
2741
#if canImport(UIKit) import UIKit internal final class FocusIndicatorView: UIView { @IBOutlet private weak var indicatorView: UIView! // Circle private let baseAlpha: CGFloat = 0.5 private let movingTime: TimeInterval = 0.25 private let fadeTime: TimeInterval = 0.3 private let afterDelay: TimeInterval = 2.0 private var resetBounds: CGRect { let shortSide = min(bounds.width, bounds.height) / 3.0 * 0.85 return CGRect(x: 0.0, y: 0.0, width: shortSide, height: shortSide) } private var focusBounds: CGRect { let shortSide = min(bounds.width, bounds.height) / 3.0 * 0.7 return CGRect(x: 0.0, y: 0.0, width: shortSide, height: shortSide) } internal func focusResetAnimation(animated: Bool = true) { let selector = #selector(animateIndicatorViewAlpha) NSObject.cancelPreviousPerformRequests(withTarget: self, selector: selector, object: nil) UIView.animate(withDuration: animated ? movingTime : 0.0, delay: 0.0, options: [.beginFromCurrentState, .curveEaseInOut], animations: { self.indicatorView.alpha = self.baseAlpha self.indicatorView.center = self.center self.indicatorView.bounds = self.resetBounds }, completion: { (finished: Bool) -> Void in NSObject.cancelPreviousPerformRequests(withTarget: self, selector: selector, object: nil) self.perform(selector, with: nil, afterDelay: self.afterDelay) }) } internal func focusAnimation(to point: CGPoint) { let selector = #selector(animateIndicatorViewAlpha) NSObject.cancelPreviousPerformRequests(withTarget: self, selector: selector, object: nil) UIView.animate(withDuration: movingTime, delay: 0.0, options: [.beginFromCurrentState, .curveEaseInOut], animations: { self.indicatorView.alpha = self.baseAlpha self.indicatorView.center = point self.indicatorView.bounds = self.focusBounds }, completion: { (finished: Bool) -> Void in NSObject.cancelPreviousPerformRequests(withTarget: self, selector: selector, object: nil) self.perform(selector, with: nil, afterDelay: self.afterDelay) }) } @objc private func animateIndicatorViewAlpha() { NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #function, object: nil) let alpha: CGFloat = indicatorView.center == center ? 0.0 : baseAlpha / 2.0 UIView.animate(withDuration: fadeTime, delay: 0.0, options: [.beginFromCurrentState, .curveEaseInOut], animations: { self.indicatorView.alpha = alpha }, completion: { (finished: Bool) -> Void in // nop }) } } #endif
mit
3bd4b5d3b085661502b30f0099f6531d
43.934426
143
0.672018
4.471452
false
false
false
false
orcudy/archive
ios/apps/speed/Speed!/Controllers/GameplayViewController.swift
1
2586
// // GameplayViewController.swift // Speed! // // Created by Orcudy on 10/1/15. // Copyright © 2015 Chris Orcutt. All rights reserved. // import UIKit class GameplayViewController: UIViewController { @IBOutlet weak var topView: UIView! @IBOutlet weak var bottomView: UIView! @IBOutlet weak var topScoreLabel: UILabel! @IBOutlet weak var bottomScoreLabel: UILabel! @IBOutlet weak var topTimerLabel: UILabel! @IBOutlet weak var bottomTimerLabel: UILabel! // player objects (passed in from the Start Scene) var topPlayer: Player! var bottomPlayer: Player! var isGameOver = false // timer used to update the amount of time remaining var timer: NSTimer! var timeRemaining: NSTimeInterval = 0 { // didSet allows us to run this code whenever the value of timeRemaining changes didSet { topTimerLabel.text = timeRemaining.countDownString() bottomTimerLabel.text = timeRemaining.countDownString() } } // MARK: LifeCycle override func viewDidLoad() { super.viewDidLoad() topScoreLabel.transform.rotate(degrees: 180) topTimerLabel.transform.rotate(degrees: 180) topScoreLabel.text = "0" bottomScoreLabel.text = "0" topView.backgroundColor = UIColor.blue() bottomView.backgroundColor = UIColor.red() timeRemaining = 30 timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "timerTick", userInfo: nil, repeats: true) } // MARK: Timer func timerTick() { timeRemaining-- if timeRemaining == 0 { gameOver() } } // MARK: - GameLogic @IBAction func topBlockTapped(sender: UITapGestureRecognizer) { if !isGameOver { topPlayer.score++ topScoreLabel.text = "\(topPlayer.score)" } else { restartGame() } } @IBAction func bottomBlockTapped(sender: UITapGestureRecognizer) { if !isGameOver { bottomPlayer.score++ bottomScoreLabel.text = "\(bottomPlayer.score)" } else { restartGame() } } func gameOver() { timer.invalidate() isGameOver = true if topPlayer.score > bottomPlayer.score { topScoreLabel.text = "You Win! =]" bottomScoreLabel.text = "You Lose! =[" } else if bottomPlayer.score > topPlayer.score { topScoreLabel.text = "You Lose! =[" bottomScoreLabel.text = "You Win! =]" } else { topScoreLabel.text = "You Tie! =|" bottomScoreLabel.text = "You Tie! =|" } } func restartGame() { self.performSegueWithIdentifier("unwindToStart", sender: self) } }
gpl-3.0
09bdfb47310ac06d647fd0560066c8be
23.855769
122
0.661896
4.279801
false
false
false
false
dobnezmi/EmotionNote
EmotionNote/HourlyChartPresenter.swift
1
1716
// // HourlyChartPresenter.swift // EmotionNote // // Created by Shingo Suzuki on 2016/09/19. // Copyright © 2016年 dobnezmi. All rights reserved. // import UIKit import RxSwift protocol HourlyChartPresenter: class { var rx_happyEmotion: Variable<[Int]> { get } var rx_enjoyEmotin: Variable<[Int]> { get } var rx_sadEmotion: Variable<[Int]> { get } var rx_frustEmotion: Variable<[Int]> { get } } final class HourlyChartPresenterImpl: HourlyChartPresenter { let interactor: HourlyChartInteractor = Injector.container.resolve(HourlyChartInteractor.self)! let rx_happyEmotion: Variable<[Int]> = Variable([]) let rx_enjoyEmotin: Variable<[Int]> = Variable([]) let rx_sadEmotion: Variable<[Int]> = Variable([]) let rx_frustEmotion: Variable<[Int]> = Variable([]) let disposeBag = DisposeBag() init() { bindObject() } private func bindObject() { interactor.rx_emotionsWithPeriodPerHours(period: .All).subscribe(onNext: { [weak self] emotions in var happyCount: [Int] = [] var enjoyCount: [Int] = [] var sadCount: [Int] = [] var frustCount: [Int] = [] for emotion in emotions { happyCount.append(emotion.happyCount) enjoyCount.append(emotion.enjoyCount) sadCount.append(emotion.sadCount) frustCount.append(emotion.frustCount) } self?.rx_happyEmotion.value = happyCount self?.rx_enjoyEmotin.value = enjoyCount self?.rx_sadEmotion.value = sadCount self?.rx_frustEmotion.value = frustCount }).addDisposableTo(disposeBag) } }
apache-2.0
708559e5033e3155aef7b8bdc94275d6
32.588235
106
0.619965
3.919908
false
false
false
false
tidepool-org/nutshell-ios
Nutshell/GraphView/Tidepool Graph/BasalGraphData.swift
1
10820
/* * Copyright (c) 2015, Tidepool Project * * This program is free software; you can redistribute it and/or modify it under * the terms of the associated License, which is identical to the BSD 2-Clause * License as published by the Open Source Initiative at opensource.org. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the License for more details. * * You should have received a copy of the License along with this program; if * not, you can obtain one from Tidepool Project at tidepool.org. */ import UIKit class BasalGraphDataType: GraphDataType { var suppressed: CGFloat? convenience init(value: CGFloat, timeOffset: TimeInterval, suppressed: CGFloat?) { self.init(value: value, timeOffset: timeOffset) self.suppressed = suppressed } //(timeOffset: NSTimeInterval, value: NSNumber, suppressed: NSNumber?) override func typeString() -> String { return "basal" } } class BasalGraphDataLayer: TidepoolGraphDataLayer { // vars for drawing datapoints of this type var pixelsPerValue: CGFloat = 0.0 // config... fileprivate let kBasalLightBlueRectColor = Styles.lightBlueColor fileprivate let kBasalMinScaleValue: CGFloat = 1.0 fileprivate let kBasalDarkBlueRectColor = Styles.blueColor fileprivate let kBasalMaxDuration: TimeInterval = 12*60*60 // Assume maximum basal of 12 hours! // locals... fileprivate var context: CGContext? fileprivate var startValue: CGFloat = 0.0 fileprivate var startTimeOffset: TimeInterval = 0.0 fileprivate var startValueSuppressed: CGFloat? fileprivate var suppressedLine: UIBezierPath? // // MARK: - Loading data // // NOTE: the first BasalGraphDataLayer slice that has loadDataItems called loads the basal data for the entire graph time interval override func loadStartTime() -> Date { return layout.graphStartTime.addingTimeInterval(-kBasalMaxDuration) as Date } override func loadEndTime() -> Date { return layout.graphStartTime.addingTimeInterval(layout.graphTimeInterval) } override func typeString() -> String { return "basal" } override func loadEvent(_ event: CommonData, timeOffset: TimeInterval) { if let event = event as? Basal { let eventTime = event.time! let graphTimeOffset = eventTime.timeIntervalSince(layout.graphStartTime as Date) //NSLog("Adding Basal event: \(event)") var value = event.value if value == nil { if let deliveryType = event.deliveryType { if deliveryType == "suspend" { value = NSNumber(value: 0.0 as Double) } } } if value != nil { if event.duration != nil { let duration = CGFloat(event.duration!) if duration > 0 { let floatValue = CGFloat(value!) var suppressed: CGFloat? = nil if event.suppressedRate != nil { suppressed = CGFloat(event.suppressedRate!) } dataArray.append(BasalGraphDataType(value: floatValue, timeOffset: graphTimeOffset, suppressed: suppressed)) if floatValue > layout.maxBasal { layout.maxBasal = floatValue } } else { // Note: a zero duration event may follow a suspended bolus, and might even have the same time stamp as another basal event with a different rate value! In general, durations should be very long. NSLog("ignoring Basal event with zero duration") } } else { // Note: sometimes suspend events have a nil duration - put in a zero valued record! if event.deliveryType == "suspend" { dataArray.append(BasalGraphDataType(value: 0.0, timeOffset: graphTimeOffset, suppressed: nil)) } else { NSLog("ignoring non-suspend Basal event with nil duration") } } } else { NSLog("ignoring Basal event with nil value") } } } override func loadDataItems() { // Note: since each graph tile needs to know the max basal value for the graph, the first tile to load loads data for the whole graph range... if layout.allBasalData == nil { dataArray = [] super.loadDataItems() layout.allBasalData = dataArray if layout.maxBasal < kBasalMinScaleValue { layout.maxBasal = kBasalMinScaleValue } //NSLog("Prefetched \(dataArray.count) basal items for graph") } dataArray = [] let dataLayerOffset = startTime.timeIntervalSince(layout.graphStartTime as Date) let rangeStart = dataLayerOffset - kBasalMaxDuration let rangeEnd = dataLayerOffset + timeIntervalForView // copy over cached items in the range needed for this tile! for item in layout.allBasalData! { if let basalItem = item as? BasalGraphDataType { if basalItem.timeOffset >= rangeStart && basalItem.timeOffset <= rangeEnd { dataArray.append(BasalGraphDataType(value: basalItem.value, timeOffset: basalItem.timeOffset - dataLayerOffset, suppressed: basalItem.suppressed)) } } } //NSLog("Copied \(dataArray.count) basal items from graph cache for slice at offset \(dataLayerOffset/3600) hours") } // // MARK: - Drawing data points // override func configureForDrawing() { context = UIGraphicsGetCurrentContext() self.pixelsPerValue = layout.yPixelsBasal / CGFloat(layout.maxBasal) startValue = 0.0 startTimeOffset = 0.0 startValueSuppressed = nil suppressedLine = nil } override func drawDataPointAtXOffset(_ xOffset: CGFloat, dataPoint: GraphDataType) { if let basalPoint = dataPoint as? BasalGraphDataType { // skip over values before starting time, but remember last value... let itemTime = basalPoint.timeOffset let itemValue = basalPoint.value let itemSuppressed = basalPoint.suppressed //NSLog("time: \(itemTime) val: \(itemValue) sup: \(itemSuppressed)") if itemTime < 0 { startValue = itemValue startValueSuppressed = itemSuppressed } else if startValue == 0.0 && startValueSuppressed == nil { if (itemValue > 0.0 || itemSuppressed != nil) { // just starting a rect, note the time... startTimeOffset = itemTime startValue = itemValue startValueSuppressed = itemSuppressed } } else { // got another value, draw the rect drawBasalRect(startTimeOffset, endTimeOffset: itemTime, value: startValue, suppressed: startValueSuppressed, layout: layout, finish: itemTime == timeIntervalForView) // and start another rect... startValue = itemValue startTimeOffset = itemTime startValueSuppressed = itemSuppressed } } } override func finishDrawing() { // finish off any rect/supressed line we started, to right edge of graph if (startValue > 0.0 || startValueSuppressed != nil) { drawBasalRect(startTimeOffset, endTimeOffset: timeIntervalForView, value: startValue, suppressed: startValueSuppressed, layout: layout, finish: true) } } fileprivate func drawSuppressedLine() { if let linePath = suppressedLine { kBasalDarkBlueRectColor.setStroke() linePath.lineWidth = 2.0 linePath.lineCapStyle = .square // note this requires pattern change from 2, 2 to 2, 4! let pattern: [CGFloat] = [2.0, 4.0] linePath.setLineDash(pattern, count: 2, phase: 0.0) linePath.stroke() suppressedLine = nil } } fileprivate func drawBasalRect(_ startTimeOffset: TimeInterval, endTimeOffset: TimeInterval, value: CGFloat, suppressed: CGFloat?, layout: TidepoolGraphLayout, finish: Bool) { let rectLeft = floor(CGFloat(startTimeOffset) * viewPixelsPerSec) let rectRight = ceil(CGFloat(endTimeOffset) * viewPixelsPerSec) let rectWidth = rectRight-rectLeft //NSLog(" len: \(rectWidth) bas: \(value), sup: \(suppressed)") let rectHeight = floor(pixelsPerValue * value) let basalRect = CGRect(x: rectLeft, y: layout.yBottomOfBasal - rectHeight, width: rectWidth, height: rectHeight) let basalValueRectPath = UIBezierPath(rect: basalRect) kBasalLightBlueRectColor.setFill() basalValueRectPath.fill() if let suppressed = suppressed { var suppressedStart = CGPoint(x: basalRect.origin.x + 1.0, y:layout.yBottomOfBasal - floor(pixelsPerValue * suppressed) + 1.0) // add 1.0 so suppressed line top is same as basal top let suppressedEnd = CGPoint(x: suppressedStart.x + basalRect.size.width - 2.0, y: suppressedStart.y) if suppressedLine == nil { // start a new line path suppressedLine = UIBezierPath() suppressedLine!.move(to: suppressedStart) //NSLog("suppressed move to \(suppressedStart)") } else { // continue an existing suppressed line path by adding connecting line if it's at a different y let currentEnd = suppressedLine!.currentPoint if abs(currentEnd.y - suppressedStart.y) > 1.0 { suppressedLine!.addLine(to: suppressedStart) //NSLog("suppressed line to \(suppressedStart)") } suppressedStart.y = currentEnd.y } // add current line segment suppressedLine!.addLine(to: suppressedEnd) //NSLog("suppressed line to \(suppressedEnd)") if finish { drawSuppressedLine() //NSLog("suppressed line draw at finish!") } } else if suppressedLine != nil { drawSuppressedLine() //NSLog("suppressed line draw!") } } }
bsd-2-clause
6025659936d860d4c6b081a285b436c9
43.344262
219
0.605176
5.204425
false
false
false
false
superk589/DereGuide
DereGuide/Toolbox/EventInfo/Controller/EventFilterSortController.swift
2
6031
// // EventFilterSortController.swift // DereGuide // // Created by zzk on 2017/1/14. // Copyright © 2017 zzk. All rights reserved. // import UIKit protocol EventFilterSortControllerDelegate: class { func doneAndReturn(filter: CGSSEventFilter, sorter: CGSSSorter) } class EventFilterSortController: BaseFilterSortController { var filter: CGSSEventFilter! var sorter: CGSSSorter! weak var delegate: EventFilterSortControllerDelegate? var eventTypeTitles = [CGSSEventTypes.tradition.description, CGSSEventTypes.kyalapon.description, CGSSEventTypes.groove.description, CGSSEventTypes.party.description, CGSSEventTypes.parade.description, CGSSEventTypes.rail.description, CGSSEventTypes.carnival.description] var sorterTitles = [NSLocalizedString("更新时间", comment: "")] var sorterMethods = ["sortId"] var sorterOrderTitles = [NSLocalizedString("降序", comment: ""), NSLocalizedString("升序", comment: "")] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } func reloadData() { self.tableView.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func doneAction() { delegate?.doneAndReturn(filter: filter, sorter: sorter) drawerController?.hide(animated: true) } override func resetAction() { filter = CGSSSorterFilterManager.DefaultFilter.event sorter = CGSSSorterFilterManager.DefaultSorter.event tableView.reloadData() } // MARK: - TableViewDelegate & DataSource override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if section == 0 { return NSLocalizedString("筛选", comment: "") } else { return NSLocalizedString("排序", comment: "") } } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows if section == 0 { return 1 } else { return 2 } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.section == 0 { let cell = tableView.dequeueReusableCell(withIdentifier: "FilterCell", for: indexPath) as! FilterTableViewCell switch indexPath.row { case 0: cell.setup(titles: eventTypeTitles, index: filter.eventTypes.rawValue, all: CGSSEventTypes.all.rawValue) default: break } cell.delegate = self return cell } else { let cell = tableView.dequeueReusableCell(withIdentifier: "SortCell", for: indexPath) as! SortTableViewCell switch indexPath.row { case 0: cell.setup(titles: sorterOrderTitles) cell.presetIndex(index: sorter.ascending ? 1 : 0) case 1: cell.setup(titles: sorterTitles) if let index = sorterMethods.firstIndex(of: sorter.property) { cell.presetIndex(index: UInt(index)) } default: break } cell.delegate = self return cell } } } extension EventFilterSortController: FilterTableViewCellDelegate { func filterTableViewCell(_ cell: FilterTableViewCell, didSelect index: Int) { if let indexPath = tableView.indexPath(for: cell) { if indexPath.section == 0 { switch indexPath.row { case 0: filter.eventTypes.insert(CGSSEventTypes.init(rawValue: 1 << UInt(index))) default: break } } } } func filterTableViewCell(_ cell: FilterTableViewCell, didDeselect index: Int) { if let indexPath = tableView.indexPath(for: cell) { if indexPath.section == 0 { switch indexPath.row { case 0: filter.eventTypes.remove(CGSSEventTypes.init(rawValue: 1 << UInt(index))) default: break } } } } func didSelectAll(filterTableViewCell cell: FilterTableViewCell) { if let indexPath = tableView.indexPath(for: cell) { if indexPath.section == 0 { switch indexPath.row { case 0: filter.eventTypes = .all default: break } } } } func didDeselectAll(filterTableViewCell cell: FilterTableViewCell) { if let indexPath = tableView.indexPath(for: cell) { if indexPath.section == 0 { switch indexPath.row { case 0: filter.eventTypes = CGSSEventTypes.init(rawValue: 0) default: break } } } } } extension EventFilterSortController: SortTableViewCellDelegate { func sortTableViewCell(_ cell: SortTableViewCell, didSelect index: Int) { if let indexPath = tableView.indexPath(for: cell) { if indexPath.section == 1 { switch indexPath.row { case 0: sorter.ascending = (index == 1) case 1: sorter.property = sorterMethods[index] default: break } } } } }
mit
720a37ec91a1967251afe010ca5ba139
31.290323
122
0.553447
5.505041
false
false
false
false
RomeRock/ios-calculator
Calculator/Calculator/ViewController.swift
1
1583
// // ViewController.swift // iosCalculator // // Created by NDM on 11/23/16. // Copyright © 2016 Rome Rock. All rights reserved. // import UIKit class ViewController: UIViewController, UIGestureRecognizerDelegate { @IBOutlet var menuItem: UIBarButtonItem! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. if self.revealViewController() != nil { menuItem.target = self.revealViewController() menuItem.action = #selector(SWRevealViewController.revealToggle(_:)) self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer()) self.revealViewController().panGestureRecognizer().delegate = self } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func openButtonPressed(_ sender: Any) { let calculatorViewController:UIViewController = UIViewController() let calculatorView = Bundle.main.loadNibNamed("CalculatorView", owner: nil, options: nil)?[0] as! CalculatorView calculatorViewController.view = calculatorView calculatorView.viewController = calculatorViewController calculatorViewController.modalPresentationStyle = .overFullScreen calculatorViewController.modalTransitionStyle = .crossDissolve present(calculatorViewController, animated: true, completion: nil) } }
mit
c43b69ff344a360f8c41f3cc40b9224f
33.391304
120
0.693426
5.794872
false
false
false
false
blochberger/swift-sodium
Examples/OSX/AppDelegate.swift
2
1112
import Cocoa import Sodium @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { @IBOutlet weak var window: NSWindow! func applicationDidFinishLaunching(_ notification: Notification) { let sodium = Sodium() let aliceKeyPair = sodium.box.keyPair()! let bobKeyPair = sodium.box.keyPair()! let message = "My Test Message".bytes print("Original Message:\(message.utf8String!)") let encryptedMessageFromAliceToBob: Bytes = sodium.box.seal( message: message, recipientPublicKey: bobKeyPair.publicKey, senderSecretKey: aliceKeyPair.secretKey)! print("Encrypted Message:\(encryptedMessageFromAliceToBob)") let messageVerifiedAndDecryptedByBob = sodium.box.open( nonceAndAuthenticatedCipherText: encryptedMessageFromAliceToBob, senderPublicKey: bobKeyPair.publicKey, recipientSecretKey: aliceKeyPair.secretKey) print("Decrypted Message:\(messageVerifiedAndDecryptedByBob!.utf8String!)") } }
isc
cf3d469dd2e3865c1c102ba692b8ee02
32.69697
83
0.669964
5.196262
false
false
false
false
taxibeat/ios-conference
iOSConf/ScheduleItem.swift
1
1299
// // ScheduleItem.swift // iOSConf // // Created by Nikos Maounis on 04/02/2017. // Copyright © 2017 Taxibeat Ltd. All rights reserved. // import UIKit import CloudKit public struct ScheduleItem { public var description: String? public var speakerName: String? public var speakerPosition: String? public var timeString: String? public var hasSpeaker: Bool? public var weight: Int? public init?(record: CKRecord) { guard let theDescription = record.object(forKey: "Description") as? String, let itHasSpeaker = record.object(forKey: "hasSpeaker") as? Int, let theTimeString = record.object(forKey: "TimeString") as? String, let theWeight = record.object(forKey: "Weight") as? Int else { return nil } self.description = theDescription if let theSpeakerName = record.object(forKey: "Speaker") as? String { self.speakerName = theSpeakerName } if let theSpeakerPosition = record.object(forKey:"SpeakerPosition") as? String { self.speakerPosition = theSpeakerPosition } self.timeString = theTimeString self.hasSpeaker = Bool(truncating: itHasSpeaker as NSNumber) self.weight = theWeight } }
mit
d68b29e131bb00534011b4d1127c6c8c
31.45
89
0.644838
4.312292
false
false
false
false
jgonfer/JGFLabRoom
JGFLabRoom/Controller/Security/TouchIDViewController.swift
1
4430
// // TouchIDViewController.swift // JGFLabRoom // // Created by Josep González on 27/1/16. // Copyright © 2016 Josep Gonzalez Fernandez. All rights reserved. // import UIKit import LocalAuthentication class TouchIDViewController: UIViewController { @IBOutlet weak var image: UIImageView! @IBOutlet weak var message: UILabel! let kMsgShowFinger = "Show me your finger 👍" let kMsgShowReason = "🌛 Try to dismiss this screen 🌜" let kMsgFingerOK = "Login successful! ✅" var context = LAContext() deinit { Utils.removeObserverForNotifications(self) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) updateUI() } override func viewDidLoad() { super.viewDidLoad() setupController() } private func setupController() { Utils.cleanBackButtonTitle(navigationController) Utils.registerNotificationWillEnterForeground(self, selector: "updateUI") // Add right button in the navigation bar to repeat the login process so many times as we want navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Refresh, target: self, action: "updateUI") } func updateUI() { // Initialize our context object just in this example, in a real app it shouldn't be necessary. In fact, we should avoid this initialization // The reason is because once our LAContext detects that the login was successfully done, it won't let us repeat the login process again context = LAContext() var policy: LAPolicy? // Depending the iOS version we've selected properly policy system that the user is able to do if #available(iOS 9.0, *) { // iOS 9+ users with Biometric and Passcode verification policy = .DeviceOwnerAuthentication } else { // iOS 9+ users with Biometric and Custom (Fallback button) verification context.localizedFallbackTitle = "Fuu!" policy = .DeviceOwnerAuthenticationWithBiometrics } var err: NSError? // Check if the user is able to use the policy we've selected previously guard context.canEvaluatePolicy(policy!, error: &err) else { image.image = UIImage(named: "TouchID_off") // Print the localized message received by the system message.text = err?.localizedDescription return } // Great! The user is able to use his/her Touch ID 👍 image.image = UIImage(named: "TouchID_on") message.text = kMsgShowFinger loginProcess(policy!) } private func loginProcess(policy: LAPolicy) { // Start evaluation process with a callback that is executed when the user ends the process successfully or not context.evaluatePolicy(policy, localizedReason: kMsgShowReason) { (success: Bool, error: NSError?) -> Void in dispatch_async(Utils.GlobalMainQueue, { () -> Void in guard success else { if error != nil { switch(error!.code) { case LAError.AuthenticationFailed.rawValue: self.message.text = "There was a problem verifying your identity." case LAError.UserCancel.rawValue: self.message.text = "You pressed cancel." // Fallback button was pressed and an extra login step should be implemented for iOS 8 users. // By the other hand, iOS 9+ users will use the pasccode verification implemented by the own system. case LAError.UserFallback.rawValue: self.message.text = "You pressed Fuu!." // MARK: IMPORTANT: There are more error states, take a look into the LAError struct default: self.message.text = "Touch ID may not be configured" break } } return } // Good news! Everything went fine 👏 self.message.text = self.kMsgFingerOK }) } } }
mit
3e64e70d58c492bc824e144304cd750e
39.46789
148
0.589436
5.385836
false
false
false
false
jkusnier/WorkoutMerge
WorkoutMerge/SubmitWorkoutViewController.swift
1
29759
// // SubmitWorkoutViewController.swift // WorkoutMerge // // Created by Jason Kusnier on 5/29/15. // Copyright (c) 2015 Jason Kusnier. All rights reserved. // // This will need a refactor once we submit to more than one service. Intentionally coding to RunKeeper for first iteration. import UIKit import CoreData class SubmitWorkoutViewController: UITableViewController, UIPickerViewDelegate, UIPickerViewDataSource { let kSwitchPrefTotalCalories = "kSwitchPrefTotalCalories" let kSwitchPrefTotalDistance = "kSwitchPrefTotalDistance" let kSwitchPrefAverageHeartRate = "kSwitchPrefAverageHeartRate" let defaults = NSUserDefaults.standardUserDefaults() var workoutSyncAPI: WorkoutSyncAPI = WorkoutSyncAPI() var resultWorkoutData: (UUID: NSUUID?, type: String?, startTime: NSDate?, totalDistance: Double?, duration: Double?, averageHeartRate: Int?, totalCalories: Double?, notes: String?, otherType: String?, activityName: String?) var workoutData: (UUID: NSUUID?, type: String?, startTime: NSDate?, totalDistance: Double?, duration: Double?, averageHeartRate: Int?, totalCalories: Double?, notes: String?, otherType: String?, activityName: String?) { didSet { self.resultWorkoutData = self.workoutData // Check defaults for switches if let switchPrefTotalCalories = defaults.valueForKey(kSwitchPrefTotalCalories) as? Bool where !switchPrefTotalCalories { self.resultWorkoutData.totalCalories = nil } if let switchPrefTotalDistance = defaults.valueForKey(kSwitchPrefTotalDistance) as? Bool where !switchPrefTotalDistance { self.resultWorkoutData.totalDistance = nil } if let switchPrefAverageHeartRate = defaults.valueForKey(kSwitchPrefAverageHeartRate) as? Bool where !switchPrefAverageHeartRate { self.resultWorkoutData.averageHeartRate = nil } } } var picker:Int = 0 var pickerSelection:Int = 0 var useMetric = false override func viewDidLoad() { super.viewDidLoad() self.useMetric = self.defaults.stringForKey("distanceUnit") == "meters" if let uuid = self.resultWorkoutData.UUID?.UUIDString, syncLog = self.syncLog(uuid) { if let note = syncLog.valueForKey("note") as? String { self.resultWorkoutData.notes = note } if let activityName = syncLog.valueForKey("name") as? String { self.resultWorkoutData.activityName = activityName } // FIXME find a better way if let _ = self.workoutSyncAPI as? StravaAPI { // Strava Workout Types if let workoutType = syncLog.valueForKey("workoutTypeStrava") as? String { self.resultWorkoutData.type = workoutType } } else { // Default is RunKeeper if let workoutType = syncLog.valueForKey("workoutType") as? String { self.resultWorkoutData.type = workoutType } if let workoutOtherType = syncLog.valueForKey("workoutOtherType") as? String { self.resultWorkoutData.otherType = workoutOtherType } } } self.tableView.contentInset = UIEdgeInsetsMake(20, self.tableView.contentInset.left, self.tableView.contentInset.bottom, self.tableView.contentInset.right) } override func viewDidAppear(animated: Bool) { print("workoutData: \(workoutData)") } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { var rows = 7 if let _ = self.workoutSyncAPI as? StravaAPI { // Add 1 for workout Name rows++ } if resultWorkoutData.type == "Other" { // Select other type return rows++ } return rows } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { switch section { case 0: return "Sync Data" default: return "" } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell:UITableViewCell func staticCell() -> UITableViewCell { return tableView.dequeueReusableCellWithIdentifier("submitStaticCell", forIndexPath: indexPath) } func dynamicCell() -> UITableViewCell { return tableView.dequeueReusableCellWithIdentifier("submitDynamicCell", forIndexPath: indexPath) } func staticInputCell() -> UITableViewCell { return tableView.dequeueReusableCellWithIdentifier("submitStaticInputCell", forIndexPath: indexPath) } func disabledCell() -> UITableViewCell { if let cell = tableView.dequeueReusableCellWithIdentifier("submitStaticInputCell", forIndexPath: indexPath) as? SubmitWorkoutTableViewCell { cell.setDisabled(true) return cell } else { return tableView.dequeueReusableCellWithIdentifier("submitStaticCell", forIndexPath: indexPath) } } func setTitle(title: String?, cell: SubmitWorkoutTableViewCell?) { if let l = cell?.titleLabel, t = title { l.text = t } } func setSubtitle(title: String?, cell: SubmitWorkoutTableViewCell?) { if let l = cell?.subtitleLabel, t = title { l.text = t } } var row = indexPath.row // ugly hack for now to add a conditional cell if resultWorkoutData.type == "Other" { if row > 1 { // reset so our case works row-- } else if row == 1 { cell = staticInputCell() cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator cell.selectionStyle = UITableViewCellSelectionStyle.Default setTitle("Other", cell: cell as? SubmitWorkoutTableViewCell) setSubtitle(self.resultWorkoutData.otherType == nil ? "" : self.resultWorkoutData.otherType, cell: cell as? SubmitWorkoutTableViewCell) return cell } } switch row { case 0: cell = staticInputCell() cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator cell.selectionStyle = UITableViewCellSelectionStyle.Default setTitle("Workout Type", cell: cell as? SubmitWorkoutTableViewCell) setSubtitle(self.resultWorkoutData.type, cell: cell as? SubmitWorkoutTableViewCell) case 1: cell = staticCell() cell.selectionStyle = UITableViewCellSelectionStyle.None setTitle("Duration", cell: cell as? SubmitWorkoutTableViewCell) setSubtitle(stringFromTimeInterval(self.resultWorkoutData.duration), cell: cell as? SubmitWorkoutTableViewCell) case 2: if let _ = self.workoutSyncAPI as? StravaAPI { cell = disabledCell() } else { cell = dynamicCell() } cell.selectionStyle = UITableViewCellSelectionStyle.None setTitle("Calories Burned", cell: cell as? SubmitWorkoutTableViewCell) if let totalCalories = self.workoutData.totalCalories { setSubtitle(totalCalories.intString(), cell: cell as? SubmitWorkoutTableViewCell) } if let cell = cell as? SubmitWorkoutTableViewCell { cell.switchChangedCallback = { isOn in self.resultWorkoutData.totalCalories = isOn ? self.workoutData.totalCalories : nil self.defaults.setBool(isOn, forKey: self.kSwitchPrefTotalCalories) } if !cell.isDisabled { if let switchState = defaults.valueForKey(self.kSwitchPrefTotalCalories) as? Bool { cell.setSwitchState(switchState) } } } case 3: cell = dynamicCell() cell.selectionStyle = UITableViewCellSelectionStyle.None setTitle("Distance", cell: cell as? SubmitWorkoutTableViewCell) if let totalDistance = self.workoutData.totalDistance { if self.useMetric { setSubtitle(totalDistance.intString()! + " meters", cell: cell as? SubmitWorkoutTableViewCell) } else { let miles = totalDistance * 0.00062137 setSubtitle(miles.shortDecimalString()! + " miles", cell: cell as? SubmitWorkoutTableViewCell) } } if let cell = cell as? SubmitWorkoutTableViewCell { cell.switchChangedCallback = { isOn in self.resultWorkoutData.totalDistance = isOn ? self.workoutData.totalDistance : nil self.defaults.setBool(isOn, forKey: self.kSwitchPrefTotalDistance) } if let switchState = defaults.valueForKey(self.kSwitchPrefTotalDistance) as? Bool { cell.setSwitchState(switchState) } } case 4: if let _ = self.workoutSyncAPI as? StravaAPI { cell = disabledCell() } else { cell = dynamicCell() } cell.selectionStyle = UITableViewCellSelectionStyle.None setTitle("Avg Heart Rate", cell: cell as? SubmitWorkoutTableViewCell) if let averageHeartRate = self.workoutData.averageHeartRate { setSubtitle(averageHeartRate.intString()! + " BPM", cell: cell as? SubmitWorkoutTableViewCell) } if let cell = cell as? SubmitWorkoutTableViewCell { cell.switchChangedCallback = { isOn in self.resultWorkoutData.averageHeartRate = isOn ? self.workoutData.averageHeartRate : nil self.defaults.setBool(isOn, forKey: self.kSwitchPrefAverageHeartRate) } if !cell.isDisabled { if let switchState = defaults.valueForKey(self.kSwitchPrefAverageHeartRate) as? Bool { cell.setSwitchState(switchState) } } } case 5: cell = staticCell() cell.selectionStyle = UITableViewCellSelectionStyle.None setTitle("Date", cell: cell as? SubmitWorkoutTableViewCell) if let startTime = self.workoutData.startTime { setSubtitle(startTime.shortDateString(), cell: cell as? SubmitWorkoutTableViewCell) } case 6: cell = staticCell() cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator cell.selectionStyle = UITableViewCellSelectionStyle.Default setTitle("Notes", cell: cell as? SubmitWorkoutTableViewCell) if let notes = self.resultWorkoutData.notes { setSubtitle(notes, cell: cell as? SubmitWorkoutTableViewCell) } else { setSubtitle("", cell: cell as? SubmitWorkoutTableViewCell) } case 7: cell = staticCell() cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator cell.selectionStyle = UITableViewCellSelectionStyle.Default setTitle("Name", cell: cell as? SubmitWorkoutTableViewCell) if let activityName = self.resultWorkoutData.activityName { setSubtitle("\(activityName)", cell: cell as? SubmitWorkoutTableViewCell) } else { if let startTime = self.workoutData.startTime, type = self.resultWorkoutData.type { setSubtitle("\(startTime.dayOfWeek()) - \(type)", cell: cell as? SubmitWorkoutTableViewCell) } } default: cell = dynamicCell() cell.selectionStyle = UITableViewCellSelectionStyle.None } return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { self.tableView.deselectRowAtIndexPath(indexPath, animated: true) var row = indexPath.row if resultWorkoutData.type == "Other" && row > 1 { row-- } switch row { case 0: print("workout selection") self.picker = 0 let workoutPicker = UIPickerView() workoutPicker.delegate = self workoutPicker.dataSource = self let toolBar = UIToolbar() toolBar.sizeToFit() let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Plain, target: self, action: "donePicker") let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil) let cancelButton = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.Plain, target: self, action: "canclePicker") toolBar.setItems([cancelButton, spaceButton, doneButton], animated: false) toolBar.userInteractionEnabled = true if let cell = tableView.cellForRowAtIndexPath(indexPath) as? SubmitWorkoutTableViewCell { if cell.textField != nil { cell.textField.inputView = workoutPicker cell.textField.inputAccessoryView = toolBar if let type = self.resultWorkoutData.type, idx = self.workoutSyncAPI.activityTypes.indexOf(type) { self.pickerSelection = idx workoutPicker.selectRow(idx, inComponent: 0, animated: false) } cell.textField.becomeFirstResponder() } } case 1: if resultWorkoutData.type == "Other" { print("workout other selection") self.picker = 1 let workoutPicker = UIPickerView() workoutPicker.delegate = self workoutPicker.dataSource = self let toolBar = UIToolbar() toolBar.sizeToFit() let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Plain, target: self, action: "donePicker") let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil) let cancelButton = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.Plain, target: self, action: "canclePicker") toolBar.setItems([cancelButton, spaceButton, doneButton], animated: false) toolBar.userInteractionEnabled = true if let cell = tableView.cellForRowAtIndexPath(indexPath) as? SubmitWorkoutTableViewCell { if cell.textField != nil { cell.textField.inputView = workoutPicker cell.textField.inputAccessoryView = toolBar if let otherType = self.resultWorkoutData.otherType, idx = self.workoutSyncAPI.otherTypes.indexOf(otherType) { self.pickerSelection = idx workoutPicker.selectRow(idx, inComponent: 0, animated: false) } else { self.pickerSelection = 0 workoutPicker.selectRow(0, inComponent: 0, animated: false) } cell.textField.becomeFirstResponder() } } } case 6: let alert = UIAlertController(title: "Notes", message: nil, preferredStyle: UIAlertControllerStyle.Alert) let doneAction = UIAlertAction(title: "Done", style: .Default) { (action) in let notesTextField = alert.textFields![0] self.resultWorkoutData.notes = notesTextField.text self.tableView.reloadData() } alert.addAction(doneAction) alert.addTextFieldWithConfigurationHandler({(textField: UITextField) in textField.placeholder = "Enter notes:" textField.autocorrectionType = UITextAutocorrectionType.Default if let notes = self.resultWorkoutData.notes { textField.text = notes } }) self.presentViewController(alert, animated: true, completion: nil) case 7: let alert = UIAlertController(title: "Name", message: nil, preferredStyle: UIAlertControllerStyle.Alert) let doneAction = UIAlertAction(title: "Done", style: .Default) { (action) in let nameTextField = alert.textFields![0] self.resultWorkoutData.activityName = nameTextField.text!.isEmpty ? nil : nameTextField.text self.tableView.reloadData() } alert.addAction(doneAction) alert.addTextFieldWithConfigurationHandler({(textField: UITextField) in textField.placeholder = "Enter name:" textField.autocorrectionType = UITextAutocorrectionType.Default if let activityName = self.resultWorkoutData.activityName { textField.text = activityName } }) self.presentViewController(alert, animated: true, completion: nil) default: break } } func canclePicker() { self.view.endEditing(true) } func donePicker() { if self.picker == 0 { self.resultWorkoutData.type = self.workoutSyncAPI.activityTypes[self.pickerSelection] if resultWorkoutData.type != "Other" { self.resultWorkoutData.otherType = nil } } else if self.picker == 1 { self.resultWorkoutData.otherType = self.workoutSyncAPI.otherTypes[self.pickerSelection] } self.tableView.reloadData() self.view.endEditing(true) } func stringFromTimeInterval(interval:NSTimeInterval?) -> String { if let i = interval { let ti = NSInteger(i) let seconds = ti % 60 let minutes = (ti / 60) % 60 let hours = (ti / 3600) return String(format: "%0.2d:%0.2d:%0.2d",hours,minutes,seconds) } else { return "00:00:00" } } func doSave() { let vcu = ViewControllerUtils() vcu.showActivityIndicator(self.view) if let runKeeper = self.workoutSyncAPI as? RunKeeperAPI { runKeeper.postActivity(self.resultWorkoutData, failure: { (error, msg) in dispatch_async(dispatch_get_main_queue()) { vcu.hideActivityIndicator(self.view) let errorMessage: String if let error = error { errorMessage = "\(error.localizedDescription) - \(msg)" } else { errorMessage = "An error occurred while saving workout. Please verify that WorkoutMerge is still authorized through RunKeeper - \(msg)" } let alert = UIAlertController(title: "Error", message: errorMessage, preferredStyle: .Alert) alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) } }, success: { (savedKey) in if let uuid = self.resultWorkoutData.UUID?.UUIDString { let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let managedContext = appDelegate.managedObjectContext! let note = self.resultWorkoutData.notes if let syncLog = self.syncLog(uuid) { syncLog.setValue(NSDate(), forKey: "syncToRunKeeper") syncLog.setValue(note, forKey: "note") syncLog.setValue(savedKey, forKey: "savedKeyRunKeeper") if let workoutType = self.resultWorkoutData.type { syncLog.setValue(workoutType, forKey: "workoutType") } if let workoutOtherType = self.resultWorkoutData.otherType { syncLog.setValue(workoutOtherType, forKey: "workoutOtherType") } } else { let entity = NSEntityDescription.entityForName("SyncLog", inManagedObjectContext: managedContext) let syncLog = NSManagedObject(entity: entity!, insertIntoManagedObjectContext:managedContext) syncLog.setValue(uuid, forKey: "uuid") syncLog.setValue(NSDate(), forKey: "syncToRunKeeper") syncLog.setValue(note, forKey: "note") syncLog.setValue(savedKey, forKey: "savedKeyRunKeeper") if let workoutType = self.resultWorkoutData.type { syncLog.setValue(workoutType, forKey: "workoutType") } if let workoutOtherType = self.resultWorkoutData.otherType { syncLog.setValue(workoutOtherType, forKey: "workoutOtherType") } } var error: NSError? do { try managedContext.save() } catch let error1 as NSError { error = error1 print("Could not save \(error)") } catch { fatalError() } } dispatch_async(dispatch_get_main_queue()) { vcu.hideActivityIndicator(self.view) self.performSegueWithIdentifier("closeSubmitWorkout", sender: self) } } ) } else if let strava = self.workoutSyncAPI as? StravaAPI { strava.postActivity(self.resultWorkoutData, failure: { (error, msg) in dispatch_async(dispatch_get_main_queue()) { vcu.hideActivityIndicator(self.view) let errorMessage: String if let error = error { errorMessage = "\(error.localizedDescription) - \(msg)" } else { errorMessage = "An error occurred while saving workout. Please verify that WorkoutMerge is still authorized through Strava - \(msg)" } let alert = UIAlertController(title: "Error", message: errorMessage, preferredStyle: .Alert) alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) } }, success: { (savedKey) in if let uuid = self.resultWorkoutData.UUID?.UUIDString { let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let managedContext = appDelegate.managedObjectContext! let note = self.resultWorkoutData.notes if let syncLog = self.syncLog(uuid) { syncLog.setValue(NSDate(), forKey: "syncToStrava") syncLog.setValue(note, forKey: "note") syncLog.setValue(savedKey, forKey: "savedKeyStrava") if let workoutType = self.resultWorkoutData.type { syncLog.setValue(workoutType, forKey: "workoutTypeStrava") } } else { let entity = NSEntityDescription.entityForName("SyncLog", inManagedObjectContext: managedContext) let syncLog = NSManagedObject(entity: entity!, insertIntoManagedObjectContext:managedContext) syncLog.setValue(uuid, forKey: "uuid") syncLog.setValue(NSDate(), forKey: "syncToStrava") syncLog.setValue(note, forKey: "note") syncLog.setValue(savedKey, forKey: "savedKeyStrava") if let workoutType = self.resultWorkoutData.type { syncLog.setValue(workoutType, forKey: "workoutTypeStrava") } } var error: NSError? do { try managedContext.save() } catch let error1 as NSError { error = error1 print("Could not save \(error)") } catch { fatalError() } } dispatch_async(dispatch_get_main_queue()) { vcu.hideActivityIndicator(self.view) self.performSegueWithIdentifier("closeSubmitWorkout", sender: self) } } ) } } @IBAction func saveWorkout(sender: AnyObject) { if let uuid = self.resultWorkoutData.UUID?.UUIDString, syncLog = self.syncLog(uuid) { var showError = false if let _ = self.workoutSyncAPI as? StravaAPI { if let _ = syncLog.valueForKey("savedKeyStrava") as? String { showError = true } } else if let _ = self.workoutSyncAPI as? RunKeeperAPI { if let _ = syncLog.valueForKey("savedKeyRunKeeper") as? String { showError = true } } if showError { let alertController = UIAlertController(title: "Alert", message: "Workout already submitted", preferredStyle: .Alert) alertController.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)) alertController.addAction(UIAlertAction(title: "OK", style: .Default) { (action) in self.doSave() }) self.presentViewController(alertController, animated: true, completion: nil) } else { self.doSave() } } else { self.doSave() } } func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 1 } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { if self.picker == 0 { return self.workoutSyncAPI.activityTypes.count } else if self.picker == 1 { return self.workoutSyncAPI.otherTypes.count } return 0 } func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { if self.picker == 0 { return self.workoutSyncAPI.activityTypes[row] } else if self.picker == 1 { return self.workoutSyncAPI.otherTypes[row] } return nil } func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { self.pickerSelection = row } func syncLog(uuid: String) -> NSManagedObject? { let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let managedContext = appDelegate.managedObjectContext! let fetchRequest = NSFetchRequest(entityName: "SyncLog") let predicate = NSPredicate(format: "uuid = %@", uuid) fetchRequest.predicate = predicate let fetchedEntities = try? managedContext.executeFetchRequest(fetchRequest) if let syncLog = fetchedEntities?.first as? NSManagedObject { return syncLog } return nil } }
mit
9da98bdd440100c3b4dcebe7135bdd4b
45.571205
227
0.557579
5.712997
false
false
false
false
CoolCodeFactory/DynamicWaveCollectionView
DynamicWaveCollectionView/Classes/DynamicWaveCollectionViewFlowLayout.swift
1
14113
// // DynamicWaveCollectionViewFlowLayout.swift // DynamicWaveCollectionView // // Created by Dmitry Utmanov on 10/07/16. // Copyright © 2016 Dmitry Utmanov. All rights reserved. // import UIKit public class DynamicWaveCollectionViewFlowLayout: UICollectionViewFlowLayout { public var length: CGFloat = 0.0 { didSet { dynamicAnimator.removeAllBehaviors() visibleIndexPathsSet = Set<NSIndexPath>() } } public var damping: CGFloat = 0.8 { didSet { dynamicAnimator.removeAllBehaviors() visibleIndexPathsSet = Set<NSIndexPath>() } } public var frequency: CGFloat = 1.0 { didSet { dynamicAnimator.removeAllBehaviors() visibleIndexPathsSet = Set<NSIndexPath>() } } public var resistance: CGFloat = 1000.0 { didSet { dynamicAnimator.removeAllBehaviors() visibleIndexPathsSet = Set<NSIndexPath>() } } public var transformX: CGFloat = 0.4 public var transformY: CGFloat = 0.4 var downscaleIndexPaths: Set<NSIndexPath>? var dynamicAnimator: UIDynamicAnimator! var visibleIndexPathsSet: Set<NSIndexPath>! var latestDelta: CGFloat = 0.0 let kElementKindSectionHeaderItem = Int.max - 1 let kElementKindSectionFooterItem = Int.max - 2 override public init() { super.init() initialize() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initialize() } func initialize() { dynamicAnimator = UIDynamicAnimator(collectionViewLayout: self) visibleIndexPathsSet = Set<NSIndexPath>() } override public func prepareLayout() { super.prepareLayout() let visibleRect = CGRectInset(CGRect(origin: self.collectionView!.bounds.origin, size: self.collectionView!.frame.size), -100, -100) if let itemsInVisibleRectArray = super.layoutAttributesForElementsInRect(visibleRect) { let itemsIndexPathsInVisibleRectSet = Set<NSIndexPath>(itemsInVisibleRectArray.map({ $0.indexPath })) let noLongerVisibleBehaviours = self.dynamicAnimator.behaviors.filter({ (dynamicBehavior) -> Bool in if let attachmentBehavior = dynamicBehavior as? UIAttachmentBehavior { let collectionViewLayoutAttributes = attachmentBehavior.items.last as! UICollectionViewLayoutAttributes return !itemsIndexPathsInVisibleRectSet.contains(collectionViewLayoutAttributes.indexPath) } return false }) for behavior in noLongerVisibleBehaviours { if let attachmentBehavior = behavior as? UIAttachmentBehavior { self.dynamicAnimator.removeBehavior(behavior) let collectionViewLayoutAttributes = attachmentBehavior.items.last as! UICollectionViewLayoutAttributes if let kind = collectionViewLayoutAttributes.representedElementKind { switch kind { case UICollectionElementKindSectionHeader: let indexPath = NSIndexPath(forItem: kElementKindSectionHeaderItem, inSection: collectionViewLayoutAttributes.indexPath.section) self.visibleIndexPathsSet.remove(indexPath) case UICollectionElementKindSectionFooter: let indexPath = NSIndexPath(forItem: kElementKindSectionFooterItem, inSection: collectionViewLayoutAttributes.indexPath.section) self.visibleIndexPathsSet.remove(indexPath) default: fatalError("Unknown kind type") } } else { self.visibleIndexPathsSet.remove(collectionViewLayoutAttributes.indexPath) } } } let newlyVisibleItems = itemsInVisibleRectArray.filter({ (collectionViewLayoutAttributes) -> Bool in if let kind = collectionViewLayoutAttributes.representedElementKind { switch kind { case UICollectionElementKindSectionHeader: let indexPath = NSIndexPath(forItem: kElementKindSectionHeaderItem, inSection: collectionViewLayoutAttributes.indexPath.section) return !visibleIndexPathsSet.contains(indexPath) case UICollectionElementKindSectionFooter: let indexPath = NSIndexPath(forItem: kElementKindSectionFooterItem, inSection: collectionViewLayoutAttributes.indexPath.section) return !visibleIndexPathsSet.contains(indexPath) default: fatalError("Unknown kind type") } } else { return !visibleIndexPathsSet.contains(collectionViewLayoutAttributes.indexPath) } }) let touchLocation = self.collectionView!.panGestureRecognizer.locationInView(self.collectionView) for item in newlyVisibleItems { let center = item.center var fixedCenter: CGPoint switch scrollDirection { case .Horizontal: fixedCenter = CGPoint(x: center.x, y: round(center.y)) case .Vertical: fixedCenter = CGPoint(x: round(center.x), y: center.y) } let springBehaviour = UIAttachmentBehavior(item: item, attachedToAnchor:fixedCenter) if #available(iOS 9.0, *) { springBehaviour.frictionTorque = CGFloat.max } if #available(iOS 9.0, *) { springBehaviour.attachmentRange = UIFloatRangeZero } springBehaviour.length = length springBehaviour.damping = damping springBehaviour.frequency = frequency if (!CGPointEqualToPoint(CGPointZero, touchLocation)) { let distanceFromTouch: CGFloat switch scrollDirection { case .Horizontal: distanceFromTouch = abs(touchLocation.x - springBehaviour.anchorPoint.x) case .Vertical: distanceFromTouch = abs(touchLocation.y - springBehaviour.anchorPoint.y) } let scrollResistance = distanceFromTouch / resistance if (self.latestDelta < 0) { switch scrollDirection { case .Horizontal: fixedCenter.x += max(self.latestDelta, self.latestDelta*scrollResistance) case .Vertical: fixedCenter.y += max(self.latestDelta, self.latestDelta*scrollResistance) } } else { switch scrollDirection { case .Horizontal: fixedCenter.x += min(self.latestDelta, self.latestDelta*scrollResistance) case .Vertical: fixedCenter.y += min(self.latestDelta, self.latestDelta*scrollResistance) } } var _fixedCenter: CGPoint switch scrollDirection { case .Horizontal: _fixedCenter = CGPoint(x: fixedCenter.x, y: round(fixedCenter.y)) case .Vertical: _fixedCenter = CGPoint(x: round(fixedCenter.x), y: fixedCenter.y) } item.center = _fixedCenter } self.dynamicAnimator.addBehavior(springBehaviour) if let kind = item.representedElementKind { switch kind { case UICollectionElementKindSectionHeader: let indexPath = NSIndexPath(forItem: kElementKindSectionHeaderItem, inSection: item.indexPath.section) self.visibleIndexPathsSet.insert(indexPath) case UICollectionElementKindSectionFooter: let indexPath = NSIndexPath(forItem: kElementKindSectionFooterItem, inSection: item.indexPath.section) self.visibleIndexPathsSet.insert(indexPath) default: fatalError("Unknown kind type") } } else { self.visibleIndexPathsSet.insert(item.indexPath) } } } print(visibleIndexPathsSet.count) print(dynamicAnimator.behaviors.count) } override public func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? { let layoutAttributes = dynamicAnimator.itemsInRect(rect) as! [UICollectionViewLayoutAttributes] if let downscaleIndexPaths = downscaleIndexPaths { let scaledLayoutAttributes: [UICollectionViewLayoutAttributes] = layoutAttributes.map({ (collectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes in if downscaleIndexPaths.contains(collectionViewLayoutAttributes.indexPath) { collectionViewLayoutAttributes.transform = CGAffineTransformScale(CGAffineTransformIdentity, transformX, transformY) } else { collectionViewLayoutAttributes.transform = CGAffineTransformIdentity } return collectionViewLayoutAttributes }) return scaledLayoutAttributes } else { return layoutAttributes } } override public func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? { return dynamicAnimator.layoutAttributesForCellAtIndexPath(indexPath) } public override func layoutAttributesForSupplementaryViewOfKind(elementKind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? { return dynamicAnimator.layoutAttributesForSupplementaryViewOfKind(elementKind, atIndexPath: indexPath) } public override func layoutAttributesForDecorationViewOfKind(elementKind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? { return dynamicAnimator.layoutAttributesForDecorationViewOfKind(elementKind, atIndexPath: indexPath) } override public func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool { let scrollView = self.collectionView! let delta: CGFloat switch scrollDirection { case .Horizontal: delta = newBounds.origin.x - scrollView.bounds.origin.x case .Vertical: delta = newBounds.origin.y - scrollView.bounds.origin.y } self.latestDelta = delta let touchLocation = self.collectionView!.panGestureRecognizer.locationInView(self.collectionView) for attachmentBehavior in dynamicAnimator.behaviors as! [UIAttachmentBehavior] { let distanceFromTouch: CGFloat switch scrollDirection { case .Horizontal: distanceFromTouch = abs(touchLocation.x - attachmentBehavior.anchorPoint.x) case .Vertical: distanceFromTouch = abs(touchLocation.y - attachmentBehavior.anchorPoint.y) } let scrollResistance = distanceFromTouch / resistance let item = attachmentBehavior.items.first as! UICollectionViewLayoutAttributes let center = item.center var fixedCenter: CGPoint switch scrollDirection { case .Horizontal: fixedCenter = CGPoint(x: center.x, y: round(center.y)) case .Vertical: fixedCenter = CGPoint(x: round(center.x), y: center.y) } if (delta < 0) { switch scrollDirection { case .Horizontal: fixedCenter.x += max(delta, delta*scrollResistance) case .Vertical: fixedCenter.y += max(delta, delta*scrollResistance) } } else { switch scrollDirection { case .Horizontal: fixedCenter.x += min(delta, delta*scrollResistance) case .Vertical: fixedCenter.y += min(delta, delta*scrollResistance) } } var _fixedCenter: CGPoint switch scrollDirection { case .Horizontal: _fixedCenter = CGPoint(x: fixedCenter.x, y: round(fixedCenter.y)) case .Vertical: _fixedCenter = CGPoint(x: round(fixedCenter.x), y: fixedCenter.y) } item.center = _fixedCenter dynamicAnimator.updateItemUsingCurrentState(item) } let oldBounds = self.collectionView!.frame if newBounds.width != oldBounds.width { dynamicAnimator.removeAllBehaviors() visibleIndexPathsSet = Set<NSIndexPath>() return false } return false } }
mit
2eca9ee29890eb4f7f732a92b520f402
42.555556
171
0.569444
6.591312
false
false
false
false
UPetersen/LibreMonitor
LibreMonitor/ViewControllers/AdjustmentsTableViewController.swift
1
3377
// // AdjustmentsTableViewController.swift // LibreMonitor // // Created by Uwe Petersen on 27.05.16. // Copyright © 2016 Uwe Petersen. All rights reserved. // import Foundation import UIKit class AdjustmentsTableViewController: UITableViewController, UITextFieldDelegate { let numberFormatter = NumberFormatter() @IBOutlet weak var offsetTextField: UITextField! @IBOutlet weak var slopeTextField: UITextField! override func viewDidLoad() { super.viewDidLoad() numberFormatter.numberStyle = .decimal offsetTextField.delegate = self // for handling return key slopeTextField.delegate = self let bloodGlucoseOffset = UserDefaults.standard.double(forKey: "bloodGlucoseOffset") let bloodGlucoseSlope = UserDefaults.standard.double(forKey: "bloodGlucoseSlope") offsetTextField.text = numberFormatter.string(from: NSNumber(value: bloodGlucoseOffset)) slopeTextField.text = numberFormatter.string(from: NSNumber(value: bloodGlucoseSlope)) self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .save, target: self, action: #selector(AdjustmentsTableViewController.didTapSaveButton)) self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .undo, target: self, action: #selector(AdjustmentsTableViewController.didTapUndoButton)) } func textFieldShouldReturn(_ textField: UITextField) -> Bool { checkInputForTextField(textField) return true } func didTapSaveButton() { checkInputForTextField(offsetTextField) checkInputForTextField(slopeTextField) } func checkInputForTextField(_ textField: UITextField) { guard let aNumber = numberFormatter.number(from: textField.text!) else { displayAlertForTextField(textField) return } switch textField { case offsetTextField: let bloodGlucoseOffset = Double(aNumber) UserDefaults.standard.set(bloodGlucoseOffset, forKey: "bloodGlucoseOffset") case slopeTextField: let bloodGlucoseSlope = Double(aNumber) UserDefaults.standard.set(bloodGlucoseSlope, forKey: "bloodGlucoseSlope") default: fatalError("Fatal Error in \(#file): textField not handled in switch case") break } // update table view NotificationCenter.default.post(name: Notification.Name(rawValue: "updateBloodSugarTableViewController"), object: self) resignFirstResponder() navigationController?.dismiss(animated: true, completion: nil) } func didTapUndoButton() { resignFirstResponder() navigationController?.dismiss(animated: true, completion: nil) } func displayAlertForTextField(_ textField: UITextField) { let message = String(format: "\"\(textField.text!)\" ist kein gültiger Wert, bitte korrigieren.", []) let alertController = UIAlertController(title: "Ungültige Eingabe", message: message, preferredStyle: .alert) let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil) alertController.addAction(defaultAction) present(alertController, animated: true, completion: nil) } }
apache-2.0
8f150e2ba37c07c8a5185818d5ae43b2
38.694118
174
0.6885
5.280125
false
false
false
false
alvarorgtr/swift_data_structures
DataStructures/SinglyLinkedList/SinglyLinkedList.swift
1
4055
// // SinglyLinkedList.swift // DataStructures // // Created by Álvaro Rodríguez García on 29/6/16. // Copyright © 2016 DeltaApps. All rights reserved. // import Foundation /** An implementation of a linked list whose nodes only have a pointer to the next node. */ public struct SinglyLinkedList<Element>: Sequence, ExpressibleByArrayLiteral { public typealias Iterator = AnyIterator<Element> fileprivate typealias Node = SinglyLinkedListNode<Element> fileprivate var head: Node? /// The number of elements currently on the list. public fileprivate(set) var count: Int = 0 /// True if the list is empty, false otherwise. public var isEmpty: Bool { return head == nil } // MARK: Initializers /** Creates an empty singly linked list. */ public init() { } /** Creates a list with the elements on the provided sequence. - parameter s: the sequence the elements will be drawn from. - complexity: O(n) where n is the number of elements in the sequence. */ public init<S: Sequence>(_ s: S) where S.Iterator.Element == Element { var iterator = s.makeIterator() var node: Node? if let first = iterator.next() { head = Node(value: first, next: nil) node = head count = 1 } while let next = iterator.next() { node!.next = Node(value: next, next: nil) node = node!.next count += 1 } } public init(arrayLiteral elements: Element...) { for element in elements.reversed() { prepend(element) } } /** Creates a list with the provided element repeated. - parameter count: the number of repetitions. - parameter repeatedValue: the value to be repeated. */ public init(count: Int, repeatedValue: Element) { for _ in 0..<count { prepend(repeatedValue) } } // MARK: Accessors and mutators /** Adds an element to the head of the list. - parameter value: the element to be added. - complexity: O(1) */ public mutating func prepend(_ value: Element) { head = Node(value: value, next: head) count += 1 } /** Delete the element on the head of the list. - returns: the element which was deleted. - complexity: O(1) */ @discardableResult public mutating func deleteFirst() -> Element { if let h = head { head = h.next count -= 1 return h.value } else { fatalError("Cannot delete in an empty list") } } /** Obtain the first element on the list (the head). - returns: the element. - complexity: O(1) */ public var first: Element? { return head?.value } // MARK: Iteration public func makeIterator() -> SinglyLinkedList.Iterator { return AnyIterator(SinglyLinkedListIterator<Element>(node: head)) } } extension SinglyLinkedList: CustomStringConvertible { public var description: String { var desc = "[" let iterator = makeIterator() if let first = iterator.next() { desc += String(describing: first) } while let element = iterator.next() { desc += ", " + String(describing: element) } desc += "]" return desc } } public func ==<T: Equatable>(lhs: SinglyLinkedList<T>, rhs: SinglyLinkedList<T>) -> Bool { if lhs.count != rhs.count { return false } else { if lhs.count == 0 || lhs.head === rhs.head { return true } else { var result = true let leftIterator = lhs.makeIterator() let rightIterator = rhs.makeIterator() while let l = leftIterator.next(), let r = rightIterator.next() { result = result && (l == r) } return result } } } private class SinglyLinkedListNode<Element> { fileprivate var next: SinglyLinkedListNode<Element>? fileprivate var value: Element fileprivate init(value: Element, next: SinglyLinkedListNode<Element>? = nil) { self.value = value self.next = next } } private struct SinglyLinkedListIterator<Element>: IteratorProtocol { fileprivate var node: SinglyLinkedListNode<Element>? fileprivate init(node: SinglyLinkedListNode<Element>?) { self.node = node } fileprivate mutating func next() -> Element? { let value = node?.value node = node?.next return value } }
gpl-3.0
4639ab86d3526e4a4e46766135c10943
20.663102
90
0.673167
3.550394
false
false
false
false
TMTBO/TTARefresher
TTARefresher/Classes/Footer/Back/TTARefresherBackNormalFooter.swift
1
3482
// // TTARefresherBackNormalFooter.swift // Pods // // Created by TobyoTenma on 13/05/2017. // // import UIKit open class TTARefresherBackNormalFooter: TTARefresherBackStateFooter { public var indicatorStyle = UIActivityIndicatorViewStyle.gray { didSet { loadingView = nil setNeedsLayout() } } public lazy var arrowImageView: UIImageView = { let arrowImage = Bundle.TTARefresher.arrowImage() let arrowImageView = UIImageView(image: arrowImage) self.addSubview(arrowImageView) return arrowImageView }() lazy var loadingView: UIActivityIndicatorView? = { let indicator = UIActivityIndicatorView(activityIndicatorStyle: self.indicatorStyle) indicator.hidesWhenStopped = true self.addSubview(indicator) return indicator }() override open var state: TTARefresherState { didSet { if oldValue == state { return } if state == .idle { if oldValue == .refreshing { arrowImageView.transform = CGAffineTransform(rotationAngle: 0.000001 - CGFloat.pi) UIView.animate(withDuration: TTARefresherAnimationDuration.slow, animations: { [weak self] in self?.loadingView?.alpha = 0 }, completion: { [weak self] (isFinished) in guard let `self` = self else { return } self.loadingView?.alpha = 1 self.loadingView?.stopAnimating() self.arrowImageView.isHidden = false }) } else { arrowImageView.isHidden = false loadingView?.stopAnimating() UIView.animate(withDuration: TTARefresherAnimationDuration.fast, animations: { [weak self] in self?.arrowImageView.transform = CGAffineTransform(rotationAngle: 0.000001 - CGFloat.pi) }) } } else if state == .pulling { arrowImageView.isHidden = false loadingView?.stopAnimating() UIView.animate(withDuration: TTARefresherAnimationDuration.fast, animations: { [weak self] in self?.arrowImageView.transform = .identity }) } else if state == .refreshing { arrowImageView.isHidden = true loadingView?.startAnimating() } else if state == .noMoreData { arrowImageView.isHidden = true loadingView?.stopAnimating() } } } } // MARK: - Override Methods extension TTARefresherBackNormalFooter { override open func placeSubviews() { super.placeSubviews() var arrowCenterX = bounds.width * 0.5 if !stateLabel.isHidden { arrowCenterX -= labelLeftInset + stateLabel.ttaRefresher.textWidth() * 0.5 } let arrowCenterY = bounds.height * 0.5 let arrowCenter = CGPoint(x: arrowCenterX, y: arrowCenterY) if arrowImageView.constraints.count == 0, let image = arrowImageView.image { arrowImageView.bounds.size = image.size arrowImageView.center = arrowCenter } if loadingView?.constraints.count == 0 { loadingView?.center = arrowCenter } arrowImageView.tintColor = stateLabel.textColor } }
mit
aebfc094cccc1972989e8f7445496f3a
36.042553
113
0.580988
5.803333
false
false
false
false
Awalz/ark-ios-monitor
ArkMonitor/Settings/Server Selection/Custom Server Selection/SettingsServerNameTableViewCell.swift
1
3607
// Copyright (c) 2016 Ark // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // import UIKit protocol SettingsServerNameTableViewCellDelegate: class { func ipCell(_ cell: SettingsServerNameTableViewCell, didChangeText text: String?) } class SettingsServerNameTableViewCell: UITableViewCell { public weak var delegate: SettingsServerNameTableViewCellDelegate? var nameLabel : UILabel! var nameTextField : ArkServerTextField! init(reuseIdentifier: String) { super.init(style: .default, reuseIdentifier: "servername") backgroundColor = ArkPalette.backgroundColor selectionStyle = .none let nameLabel = UILabel() nameLabel.text = "Server name" nameLabel.textColor = ArkPalette.highlightedTextColor nameLabel.textAlignment = .left nameLabel.font = UIFont.systemFont(ofSize: 16.0, weight: .semibold) addSubview(nameLabel) nameLabel.snp.makeConstraints { (make) in make.top.bottom.equalToSuperview() make.left.equalTo(25.0) make.width.equalToSuperview().multipliedBy(0.35) } nameTextField = ArkServerTextField(settings: true, placeHolder: "Custom Server") nameTextField.delegate = self nameTextField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged) addSubview(nameTextField) nameTextField.snp.makeConstraints { (make) in make.height.equalTo(30.0) make.centerY.equalToSuperview() make.right.equalToSuperview().offset(-25.0) make.width.equalToSuperview().multipliedBy(0.5) } let seperator = UIView() seperator.backgroundColor = ArkPalette.secondaryBackgroundColor addSubview(seperator) seperator.snp.makeConstraints { (make) in make.left.right.bottom.equalToSuperview() make.height.equalTo(1.0) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public func update(_ ipAddress: String?) { nameTextField.text = ipAddress } } // MARK: UITextFieldDelegate extension SettingsServerNameTableViewCell : UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } @objc func textFieldDidChange(_ textField: UITextField) { delegate?.ipCell(self, didChangeText: textField.text) } }
mit
4e887ac5108efeee3770b0acf9909326
39.988636
137
0.690602
5.145506
false
false
false
false
AnRanScheme/magiGlobe
magi/magiGlobe/Pods/SQLite.swift/Sources/SQLite/Typed/CoreFunctions.swift
40
24117
// // SQLite.swift // https://github.com/stephencelis/SQLite.swift // Copyright © 2014-2015 Stephen Celis. // // 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.NSData extension ExpressionType where UnderlyingType : Number { /// Builds a copy of the expression wrapped with the `abs` function. /// /// let x = Expression<Int>("x") /// x.absoluteValue /// // abs("x") /// /// - Returns: A copy of the expression wrapped with the `abs` function. public var absoluteValue : Expression<UnderlyingType> { return "abs".wrap(self) } } extension ExpressionType where UnderlyingType : _OptionalType, UnderlyingType.WrappedType : Number { /// Builds a copy of the expression wrapped with the `abs` function. /// /// let x = Expression<Int?>("x") /// x.absoluteValue /// // abs("x") /// /// - Returns: A copy of the expression wrapped with the `abs` function. public var absoluteValue : Expression<UnderlyingType> { return "abs".wrap(self) } } extension ExpressionType where UnderlyingType == Double { /// Builds a copy of the expression wrapped with the `round` function. /// /// let salary = Expression<Double>("salary") /// salary.round() /// // round("salary") /// salary.round(2) /// // round("salary", 2) /// /// - Returns: A copy of the expression wrapped with the `round` function. public func round(_ precision: Int? = nil) -> Expression<UnderlyingType> { guard let precision = precision else { return wrap([self]) } return wrap([self, Int(precision)]) } } extension ExpressionType where UnderlyingType == Double? { /// Builds a copy of the expression wrapped with the `round` function. /// /// let salary = Expression<Double>("salary") /// salary.round() /// // round("salary") /// salary.round(2) /// // round("salary", 2) /// /// - Returns: A copy of the expression wrapped with the `round` function. public func round(_ precision: Int? = nil) -> Expression<UnderlyingType> { guard let precision = precision else { return wrap(self) } return wrap([self, Int(precision)]) } } extension ExpressionType where UnderlyingType : Value, UnderlyingType.Datatype == Int64 { /// Builds an expression representing the `random` function. /// /// Expression<Int>.random() /// // random() /// /// - Returns: An expression calling the `random` function. public static func random() -> Expression<UnderlyingType> { return "random".wrap([]) } } extension ExpressionType where UnderlyingType == Data { /// Builds an expression representing the `randomblob` function. /// /// Expression<Int>.random(16) /// // randomblob(16) /// /// - Parameter length: Length in bytes. /// /// - Returns: An expression calling the `randomblob` function. public static func random(_ length: Int) -> Expression<UnderlyingType> { return "randomblob".wrap([]) } /// Builds an expression representing the `zeroblob` function. /// /// Expression<Int>.allZeros(16) /// // zeroblob(16) /// /// - Parameter length: Length in bytes. /// /// - Returns: An expression calling the `zeroblob` function. public static func allZeros(_ length: Int) -> Expression<UnderlyingType> { return "zeroblob".wrap([]) } /// Builds a copy of the expression wrapped with the `length` function. /// /// let data = Expression<NSData>("data") /// data.length /// // length("data") /// /// - Returns: A copy of the expression wrapped with the `length` function. public var length: Expression<Int> { return wrap(self) } } extension ExpressionType where UnderlyingType == Data? { /// Builds a copy of the expression wrapped with the `length` function. /// /// let data = Expression<NSData?>("data") /// data.length /// // length("data") /// /// - Returns: A copy of the expression wrapped with the `length` function. public var length: Expression<Int?> { return wrap(self) } } extension ExpressionType where UnderlyingType == String { /// Builds a copy of the expression wrapped with the `length` function. /// /// let name = Expression<String>("name") /// name.length /// // length("name") /// /// - Returns: A copy of the expression wrapped with the `length` function. public var length: Expression<Int> { return wrap(self) } /// Builds a copy of the expression wrapped with the `lower` function. /// /// let name = Expression<String>("name") /// name.lowercaseString /// // lower("name") /// /// - Returns: A copy of the expression wrapped with the `lower` function. public var lowercaseString: Expression<UnderlyingType> { return "lower".wrap(self) } /// Builds a copy of the expression wrapped with the `upper` function. /// /// let name = Expression<String>("name") /// name.uppercaseString /// // lower("name") /// /// - Returns: A copy of the expression wrapped with the `upper` function. public var uppercaseString: Expression<UnderlyingType> { return "upper".wrap(self) } /// Builds a copy of the expression appended with a `LIKE` query against the /// given pattern. /// /// let email = Expression<String>("email") /// email.like("%@example.com") /// // "email" LIKE '%@example.com' /// email.like("99\\%@%", escape: "\\") /// // "email" LIKE '99\%@%' ESCAPE '\' /// /// - Parameters: /// /// - pattern: A pattern to match. /// /// - escape: An (optional) character designated for escaping /// pattern-matching characters (*i.e.*, the `%` and `_` characters). /// /// - Returns: A copy of the expression appended with a `LIKE` query against /// the given pattern. public func like(_ pattern: String, escape character: Character? = nil) -> Expression<Bool> { guard let character = character else { return "LIKE".infix(self, pattern) } return Expression("(\(template) LIKE ? ESCAPE ?)", bindings + [pattern, String(character)]) } /// Builds a copy of the expression appended with a `GLOB` query against the /// given pattern. /// /// let path = Expression<String>("path") /// path.glob("*.png") /// // "path" GLOB '*.png' /// /// - Parameter pattern: A pattern to match. /// /// - Returns: A copy of the expression appended with a `GLOB` query against /// the given pattern. public func glob(_ pattern: String) -> Expression<Bool> { return "GLOB".infix(self, pattern) } /// Builds a copy of the expression appended with a `MATCH` query against /// the given pattern. /// /// let title = Expression<String>("title") /// title.match("swift AND programming") /// // "title" MATCH 'swift AND programming' /// /// - Parameter pattern: A pattern to match. /// /// - Returns: A copy of the expression appended with a `MATCH` query /// against the given pattern. public func match(_ pattern: String) -> Expression<Bool> { return "MATCH".infix(self, pattern) } /// Builds a copy of the expression appended with a `REGEXP` query against /// the given pattern. /// /// - Parameter pattern: A pattern to match. /// /// - Returns: A copy of the expression appended with a `REGEXP` query /// against the given pattern. public func regexp(_ pattern: String) -> Expression<Bool> { return "REGEXP".infix(self, pattern) } /// Builds a copy of the expression appended with a `COLLATE` clause with /// the given sequence. /// /// let name = Expression<String>("name") /// name.collate(.Nocase) /// // "name" COLLATE NOCASE /// /// - Parameter collation: A collating sequence. /// /// - Returns: A copy of the expression appended with a `COLLATE` clause /// with the given sequence. public func collate(_ collation: Collation) -> Expression<UnderlyingType> { return "COLLATE".infix(self, collation) } /// Builds a copy of the expression wrapped with the `ltrim` function. /// /// let name = Expression<String>("name") /// name.ltrim() /// // ltrim("name") /// name.ltrim([" ", "\t"]) /// // ltrim("name", ' \t') /// /// - Parameter characters: A set of characters to trim. /// /// - Returns: A copy of the expression wrapped with the `ltrim` function. public func ltrim(_ characters: Set<Character>? = nil) -> Expression<UnderlyingType> { guard let characters = characters else { return wrap(self) } return wrap([self, String(characters)]) } /// Builds a copy of the expression wrapped with the `rtrim` function. /// /// let name = Expression<String>("name") /// name.rtrim() /// // rtrim("name") /// name.rtrim([" ", "\t"]) /// // rtrim("name", ' \t') /// /// - Parameter characters: A set of characters to trim. /// /// - Returns: A copy of the expression wrapped with the `rtrim` function. public func rtrim(_ characters: Set<Character>? = nil) -> Expression<UnderlyingType> { guard let characters = characters else { return wrap(self) } return wrap([self, String(characters)]) } /// Builds a copy of the expression wrapped with the `trim` function. /// /// let name = Expression<String>("name") /// name.trim() /// // trim("name") /// name.trim([" ", "\t"]) /// // trim("name", ' \t') /// /// - Parameter characters: A set of characters to trim. /// /// - Returns: A copy of the expression wrapped with the `trim` function. public func trim(_ characters: Set<Character>? = nil) -> Expression<UnderlyingType> { guard let characters = characters else { return wrap([self]) } return wrap([self, String(characters)]) } /// Builds a copy of the expression wrapped with the `replace` function. /// /// let email = Expression<String>("email") /// email.replace("@mac.com", with: "@icloud.com") /// // replace("email", '@mac.com', '@icloud.com') /// /// - Parameters: /// /// - pattern: A pattern to match. /// /// - replacement: The replacement string. /// /// - Returns: A copy of the expression wrapped with the `replace` function. public func replace(_ pattern: String, with replacement: String) -> Expression<UnderlyingType> { return "replace".wrap([self, pattern, replacement]) } public func substring(_ location: Int, length: Int? = nil) -> Expression<UnderlyingType> { guard let length = length else { return "substr".wrap([self, location]) } return "substr".wrap([self, location, length]) } public subscript(range: Range<Int>) -> Expression<UnderlyingType> { return substring(range.lowerBound, length: range.upperBound - range.lowerBound) } } extension ExpressionType where UnderlyingType == String? { /// Builds a copy of the expression wrapped with the `length` function. /// /// let name = Expression<String?>("name") /// name.length /// // length("name") /// /// - Returns: A copy of the expression wrapped with the `length` function. public var length: Expression<Int?> { return wrap(self) } /// Builds a copy of the expression wrapped with the `lower` function. /// /// let name = Expression<String?>("name") /// name.lowercaseString /// // lower("name") /// /// - Returns: A copy of the expression wrapped with the `lower` function. public var lowercaseString: Expression<UnderlyingType> { return "lower".wrap(self) } /// Builds a copy of the expression wrapped with the `upper` function. /// /// let name = Expression<String?>("name") /// name.uppercaseString /// // lower("name") /// /// - Returns: A copy of the expression wrapped with the `upper` function. public var uppercaseString: Expression<UnderlyingType> { return "upper".wrap(self) } /// Builds a copy of the expression appended with a `LIKE` query against the /// given pattern. /// /// let email = Expression<String?>("email") /// email.like("%@example.com") /// // "email" LIKE '%@example.com' /// email.like("99\\%@%", escape: "\\") /// // "email" LIKE '99\%@%' ESCAPE '\' /// /// - Parameters: /// /// - pattern: A pattern to match. /// /// - escape: An (optional) character designated for escaping /// pattern-matching characters (*i.e.*, the `%` and `_` characters). /// /// - Returns: A copy of the expression appended with a `LIKE` query against /// the given pattern. public func like(_ pattern: String, escape character: Character? = nil) -> Expression<Bool?> { guard let character = character else { return "LIKE".infix(self, pattern) } return Expression("(\(template) LIKE ? ESCAPE ?)", bindings + [pattern, String(character)]) } /// Builds a copy of the expression appended with a `GLOB` query against the /// given pattern. /// /// let path = Expression<String?>("path") /// path.glob("*.png") /// // "path" GLOB '*.png' /// /// - Parameter pattern: A pattern to match. /// /// - Returns: A copy of the expression appended with a `GLOB` query against /// the given pattern. public func glob(_ pattern: String) -> Expression<Bool?> { return "GLOB".infix(self, pattern) } /// Builds a copy of the expression appended with a `MATCH` query against /// the given pattern. /// /// let title = Expression<String?>("title") /// title.match("swift AND programming") /// // "title" MATCH 'swift AND programming' /// /// - Parameter pattern: A pattern to match. /// /// - Returns: A copy of the expression appended with a `MATCH` query /// against the given pattern. public func match(_ pattern: String) -> Expression<Bool> { return "MATCH".infix(self, pattern) } /// Builds a copy of the expression appended with a `REGEXP` query against /// the given pattern. /// /// - Parameter pattern: A pattern to match. /// /// - Returns: A copy of the expression appended with a `REGEXP` query /// against the given pattern. public func regexp(_ pattern: String) -> Expression<Bool?> { return "REGEXP".infix(self, pattern) } /// Builds a copy of the expression appended with a `COLLATE` clause with /// the given sequence. /// /// let name = Expression<String?>("name") /// name.collate(.Nocase) /// // "name" COLLATE NOCASE /// /// - Parameter collation: A collating sequence. /// /// - Returns: A copy of the expression appended with a `COLLATE` clause /// with the given sequence. public func collate(_ collation: Collation) -> Expression<UnderlyingType> { return "COLLATE".infix(self, collation) } /// Builds a copy of the expression wrapped with the `ltrim` function. /// /// let name = Expression<String?>("name") /// name.ltrim() /// // ltrim("name") /// name.ltrim([" ", "\t"]) /// // ltrim("name", ' \t') /// /// - Parameter characters: A set of characters to trim. /// /// - Returns: A copy of the expression wrapped with the `ltrim` function. public func ltrim(_ characters: Set<Character>? = nil) -> Expression<UnderlyingType> { guard let characters = characters else { return wrap(self) } return wrap([self, String(characters)]) } /// Builds a copy of the expression wrapped with the `rtrim` function. /// /// let name = Expression<String?>("name") /// name.rtrim() /// // rtrim("name") /// name.rtrim([" ", "\t"]) /// // rtrim("name", ' \t') /// /// - Parameter characters: A set of characters to trim. /// /// - Returns: A copy of the expression wrapped with the `rtrim` function. public func rtrim(_ characters: Set<Character>? = nil) -> Expression<UnderlyingType> { guard let characters = characters else { return wrap(self) } return wrap([self, String(characters)]) } /// Builds a copy of the expression wrapped with the `trim` function. /// /// let name = Expression<String?>("name") /// name.trim() /// // trim("name") /// name.trim([" ", "\t"]) /// // trim("name", ' \t') /// /// - Parameter characters: A set of characters to trim. /// /// - Returns: A copy of the expression wrapped with the `trim` function. public func trim(_ characters: Set<Character>? = nil) -> Expression<UnderlyingType> { guard let characters = characters else { return wrap(self) } return wrap([self, String(characters)]) } /// Builds a copy of the expression wrapped with the `replace` function. /// /// let email = Expression<String?>("email") /// email.replace("@mac.com", with: "@icloud.com") /// // replace("email", '@mac.com', '@icloud.com') /// /// - Parameters: /// /// - pattern: A pattern to match. /// /// - replacement: The replacement string. /// /// - Returns: A copy of the expression wrapped with the `replace` function. public func replace(_ pattern: String, with replacement: String) -> Expression<UnderlyingType> { return "replace".wrap([self, pattern, replacement]) } /// Builds a copy of the expression wrapped with the `substr` function. /// /// let title = Expression<String?>("title") /// title.substr(-100) /// // substr("title", -100) /// title.substr(0, length: 100) /// // substr("title", 0, 100) /// /// - Parameters: /// /// - location: The substring’s start index. /// /// - length: An optional substring length. /// /// - Returns: A copy of the expression wrapped with the `substr` function. public func substring(_ location: Int, length: Int? = nil) -> Expression<UnderlyingType> { guard let length = length else { return "substr".wrap([self, location]) } return "substr".wrap([self, location, length]) } /// Builds a copy of the expression wrapped with the `substr` function. /// /// let title = Expression<String?>("title") /// title[0..<100] /// // substr("title", 0, 100) /// /// - Parameter range: The character index range of the substring. /// /// - Returns: A copy of the expression wrapped with the `substr` function. public subscript(range: Range<Int>) -> Expression<UnderlyingType> { return substring(range.lowerBound, length: range.upperBound - range.lowerBound) } } extension Collection where Iterator.Element : Value, IndexDistance == Int { /// Builds a copy of the expression prepended with an `IN` check against the /// collection. /// /// let name = Expression<String>("name") /// ["alice", "betty"].contains(name) /// // "name" IN ('alice', 'betty') /// /// - Parameter pattern: A pattern to match. /// /// - Returns: A copy of the expression prepended with an `IN` check against /// the collection. public func contains(_ expression: Expression<Iterator.Element>) -> Expression<Bool> { let templates = [String](repeating: "?", count: count).joined(separator: ", ") return "IN".infix(expression, Expression<Void>("(\(templates))", map { $0.datatypeValue })) } /// Builds a copy of the expression prepended with an `IN` check against the /// collection. /// /// let name = Expression<String?>("name") /// ["alice", "betty"].contains(name) /// // "name" IN ('alice', 'betty') /// /// - Parameter pattern: A pattern to match. /// /// - Returns: A copy of the expression prepended with an `IN` check against /// the collection. public func contains(_ expression: Expression<Iterator.Element?>) -> Expression<Bool?> { let templates = [String](repeating: "?", count: count).joined(separator: ", ") return "IN".infix(expression, Expression<Void>("(\(templates))", map { $0.datatypeValue })) } } /// Builds a copy of the given expressions wrapped with the `ifnull` function. /// /// let name = Expression<String?>("name") /// name ?? "An Anonymous Coward" /// // ifnull("name", 'An Anonymous Coward') /// /// - Parameters: /// /// - optional: An optional expression. /// /// - defaultValue: A fallback value for when the optional expression is /// `nil`. /// /// - Returns: A copy of the given expressions wrapped with the `ifnull` /// function. public func ??<V : Value>(optional: Expression<V?>, defaultValue: V) -> Expression<V> { return "ifnull".wrap([optional, defaultValue]) } /// Builds a copy of the given expressions wrapped with the `ifnull` function. /// /// let nick = Expression<String?>("nick") /// let name = Expression<String>("name") /// nick ?? name /// // ifnull("nick", "name") /// /// - Parameters: /// /// - optional: An optional expression. /// /// - defaultValue: A fallback expression for when the optional expression is /// `nil`. /// /// - Returns: A copy of the given expressions wrapped with the `ifnull` /// function. public func ??<V : Value>(optional: Expression<V?>, defaultValue: Expression<V>) -> Expression<V> { return "ifnull".wrap([optional, defaultValue]) } /// Builds a copy of the given expressions wrapped with the `ifnull` function. /// /// let nick = Expression<String?>("nick") /// let name = Expression<String?>("name") /// nick ?? name /// // ifnull("nick", "name") /// /// - Parameters: /// /// - optional: An optional expression. /// /// - defaultValue: A fallback expression for when the optional expression is /// `nil`. /// /// - Returns: A copy of the given expressions wrapped with the `ifnull` /// function. public func ??<V : Value>(optional: Expression<V?>, defaultValue: Expression<V?>) -> Expression<V> { return "ifnull".wrap([optional, defaultValue]) }
mit
631409a04d9b500ef1f818ca381e06b8
34.306003
100
0.590819
4.296098
false
false
false
false
youngsoft/TangramKit
TangramKitDemo/FlowLayoutDemo/FLLTest2ViewController.swift
1
7669
// // FLLTest2ViewController.swift // TangramKit // // Created by apple on 16/7/18. // Copyright © 2016年 youngsoft. All rights reserved. // import UIKit /** *2.FlowLayout - Tag cloud */ class FLLTest2ViewController: UIViewController { weak var tagTextField:UITextField! weak var flowLayout:TGFlowLayout! override func loadView() { /* 这个例子用来介绍流式布局中的内容填充流式布局,主要用来实现标签流的功能。内容填充流式布局的每行的数量是不固定的,而是根据其内容的尺寸来自动换行。 */ self.edgesForExtendedLayout = UIRectEdge(rawValue:0) //设置视图控制器中的视图尺寸不延伸到导航条或者工具条下面。您可以注释这句代码看看效果。 let rootLayout = TGFlowLayout(.vert,arrangedCount:2) rootLayout.backgroundColor = .white rootLayout.tg_arrangedGravity = TGGravity.vert.center rootLayout.tg_vspace = 4 rootLayout.tg_hspace = 4 self.view = rootLayout //第一行 let tempTagTextField = UITextField() tempTagTextField.placeholder = "input tag here" tempTagTextField.borderStyle = .roundedRect tempTagTextField.tg_leading.equal(2) tempTagTextField.tg_top.equal(2) tempTagTextField.tg_height.equal(30) tempTagTextField.tg_width.equal(.fill) //宽度占用剩余父视图宽度。 rootLayout.addSubview(tempTagTextField) self.tagTextField = tempTagTextField let addTagButton = UIButton(type: .system) addTagButton.setTitle("Add Tag", for: .normal) addTagButton.addTarget(self, action: #selector(handleAddTag), for: .touchUpInside) addTagButton.tg_trailing.equal(2) addTagButton.sizeToFit() //因为每行2个子视图,这个子视图的宽度是固定的,而上面的兄弟视图占用了剩余的宽度。这样这两个子视图将均分父视图。 rootLayout.addSubview(addTagButton) //第二行 let stretchSpacingLabel = UILabel() stretchSpacingLabel.text = "Stretch Spacing:" stretchSpacingLabel.font = CFTool.font(15) stretchSpacingLabel.tg_leading.equal(2) stretchSpacingLabel.tg_width.equal(140) stretchSpacingLabel.tg_height.equal(.wrap) rootLayout.addSubview(stretchSpacingLabel) let stretchSpacingSwitch = UISwitch() stretchSpacingSwitch.addTarget(self, action: #selector(handleStretchSpace), for: .valueChanged) rootLayout.addSubview(stretchSpacingSwitch) //第三行 let stretchSizeLabel = UILabel() stretchSizeLabel.text = "Stretch Size:" stretchSizeLabel.font = CFTool.font(15) stretchSizeLabel.tg_leading.equal(2) stretchSizeLabel.tg_width.equal(140) stretchSizeLabel.tg_height.equal(.wrap) rootLayout.addSubview(stretchSizeLabel) let stretchSizeSwitch = UISwitch() stretchSizeSwitch.addTarget(self, action: #selector(handleStretchContent), for: .valueChanged) rootLayout.addSubview(stretchSizeSwitch) //第四行 let autoArrangeLabel = UILabel() autoArrangeLabel.text = "Auto Arrange:" autoArrangeLabel.font = CFTool.font(15) autoArrangeLabel.tg_leading.equal(2) autoArrangeLabel.tg_width.equal(140) autoArrangeLabel.tg_height.equal(.wrap) rootLayout.addSubview(autoArrangeLabel) let autoArrangeSwitch = UISwitch() autoArrangeSwitch.addTarget(self, action: #selector(handleAutoArrange), for: .valueChanged) rootLayout.addSubview(autoArrangeSwitch) //最后一行。 let flowLayout = TGFlowLayout() flowLayout.backgroundColor = CFTool.color(0) flowLayout.tg_space = 10 flowLayout.tg_padding = UIEdgeInsets.init(top: 10, left: 10, bottom: 10, right: 10) flowLayout.tg_width.equal(.fill) flowLayout.tg_height.equal(.fill) rootLayout.addSubview(flowLayout) self.flowLayout = flowLayout } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.createTagButton(NSLocalizedString("click to remove tag", comment:"")) self.createTagButton(NSLocalizedString("tag2", comment:"")) self.createTagButton(NSLocalizedString("TGLayout can used in XIB&SB", comment:"")) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension FLLTest2ViewController { func createTagButton(_ text:String) { let tagButton = UIButton() tagButton.setTitle(text,for:.normal) tagButton.titleLabel?.font = CFTool.font(15) tagButton.layer.cornerRadius = 15; tagButton.backgroundColor = UIColor(red: CGFloat(arc4random_uniform(256))/255.0, green: CGFloat(arc4random_uniform(256))/255.0, blue: CGFloat(arc4random_uniform(256))/255.0, alpha: 1) //这里可以看到尺寸宽度等于内容宽度并且再增加10,且最小是40,意思是按钮的宽度是等于自身内容的宽度再加10,但最小的宽度是40 tagButton.tg_width.equal(.wrap, increment:10).min(40) tagButton.tg_height.equal(.wrap, increment:10) //高度等于自身内容的高度加10 tagButton.addTarget(self,action:#selector(handleDelTag), for:.touchUpInside ) self.flowLayout.addSubview(tagButton) } @objc func handleAddTag(sender:Any!) { if let text = self.tagTextField.text { self.createTagButton(text) self.tagTextField.text = "" self.flowLayout.tg_layoutAnimationWithDuration(0.2) } } @objc func handleStretchSpace(sender:UISwitch!) { //间距拉伸 if sender.isOn { self.flowLayout.tg_gravity = TGGravity.horz.between //流式布局的tg_gravity如果设置为TGGravity.horz.between表示子视图的间距会被拉伸,以便填充满整个布局。 } else { self.flowLayout.tg_gravity = .none } self.flowLayout.tg_layoutAnimationWithDuration(0.2) } @objc func handleStretchContent(sender:UISwitch!) { //内容拉伸 if sender.isOn { self.flowLayout.tg_gravity = TGGravity.horz.fill //流式布局的gravity如果设置为TGGravity.horz.fill表示子视图的间距会被拉伸,以便填充满整个布局。 } else { self.flowLayout.tg_gravity = TGGravity.none } self.flowLayout.tg_layoutAnimationWithDuration(0.2) } @objc func handleAutoArrange(sender:UISwitch!) { //自动调整位置。 if (sender.isOn) { self.flowLayout.tg_autoArrange = true //tg_autoArrange属性会根据子视图的内容自动调整,以便以最合适的布局来填充布局。 } else { self.flowLayout.tg_autoArrange = false } self.flowLayout.tg_layoutAnimationWithDuration(0.2) } @objc func handleDelTag(sender:UIButton!) { sender.removeFromSuperview() self.flowLayout.tg_layoutAnimationWithDuration(0.2) } }
mit
a15a2ce90b435b2c424f7d12f98e9be0
31.308411
191
0.634365
4.091124
false
false
false
false
rambler-digital-solutions/rambler-it-ios
Carthage/Checkouts/rides-ios-sdk/source/UberRides/RideRequestViewRequestingBehavior.swift
1
4669
// // RideRequestViewRequestingBehavior.swift // UberRides // // Copyright © 2015 Uber Technologies, Inc. All rights reserved. // // 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. /// A RideRequesting object for requesting a ride via the RideRequestViewController @objc(UBSDKRideRequestViewRequestingBehavior) public class RideRequestViewRequestingBehavior : NSObject { /// The UIViewController to present the RideRequestViewController over @objc unowned public var presentingViewController: UIViewController /** The LoginManager to use with the RideRequestViewController. Uses the accessTokenIdentifier & keychainAccessGroup to get an AccessToken. Will be used to log a user in, if necessary */ @objc public var loginManager: LoginManager { get { return self.modalRideRequestViewController.rideRequestViewController.loginManager } set { self.modalRideRequestViewController.rideRequestViewController.loginManager = newValue } } /// The ModalRideRequestViewController that is created by this behavior, only exists after requestRide() is called @objc public internal(set) var modalRideRequestViewController: ModalRideRequestViewController /** Creates the RideRequestViewRequestingBehavior with the given presenting view controller. This view controller will be used to modally present the ModalRideRequestViewController when this behavior is executed - parameter presentingViewController: The UIViewController to present the ModalRideRequestViewController over - parameter loginManager: The LoginManager to use for managing the AccessToken for the RideRequestView - returns: An initialized RideRequestViewRequestingBehavior object */ @objc public init(presentingViewController: UIViewController, loginManager: LoginManager) { self.presentingViewController = presentingViewController let rideRequestViewController = RideRequestViewController(rideParameters: RideParametersBuilder().build(), loginManager: loginManager) modalRideRequestViewController = ModalRideRequestViewController(rideRequestViewController: rideRequestViewController) } /** Creates the RideRequestViewRequestingBehavior with the given presenting view controller. This view controller will be used to modally present the ModalRideRequestViewController when this behavior is executed Uses a default LoginManager() for login & token management - parameter presentingViewController: The UIViewController to present the ModalRideRequestViewController over - returns: An initialized RideRequestViewRequestingBehavior object */ @objc public convenience init(presentingViewController: UIViewController) { self.init(presentingViewController: presentingViewController, loginManager: LoginManager()) } } extension RideRequestViewRequestingBehavior : RideRequesting { /** Requests a ride by presenting a RideRequestView that is constructed using the provided rideParameters - parameter parameters: The RideParameters to use for building and prefilling the RideRequestView */ public func requestRide(parameters rideParameters: RideParameters?) { if let rideParameters = rideParameters { modalRideRequestViewController.rideRequestViewController.rideRequestView.rideParameters = rideParameters } presentingViewController.present(modalRideRequestViewController, animated: true, completion: nil) } }
mit
d5e2ba6a08052ab32182ddd6a14b6d26
48.136842
142
0.760497
5.91635
false
false
false
false
darkzero/SimplePlayer
SimplePlayer/Player/MusicLibrary.swift
1
4043
// // MusicLibrary.swift // SimplePlayer // // Created by Lihua Hu on 2014/06/16. // Copyright (c) 2014 darkzero. All rights reserved. // import UIKit import MediaPlayer class MusicLibrary: NSObject { required override init() { super.init(); } class func defaultPlayer() -> MusicLibrary { struct Static { static var instance: MusicLibrary? = nil static var onceToken: dispatch_once_t = 0 } dispatch_once(&Static.onceToken) { Static.instance = self(); } return Static.instance! } // get playlist func getiPodPlaylists() -> NSMutableArray { var result:NSMutableArray = NSMutableArray.array(); var playlistQuery:MPMediaQuery = MPMediaQuery.playlistsQuery(); playlistQuery.groupingType = MPMediaGrouping.Playlist; result.addObjectsFromArray(playlistQuery.collections);//MPMediaItemCollection return result; } // get artists list func getiPodArtistList() -> NSMutableArray { var result:NSMutableArray = NSMutableArray.array(); var artistsQuery:MPMediaQuery = MPMediaQuery.artistsQuery(); artistsQuery.groupingType = MPMediaGrouping.AlbumArtist; result.addObjectsFromArray(artistsQuery.collections); result = self.groupArrayByInitial(result, theSelector:"albumArtist"); return result; } // get album list func getiPodAlbumList() -> NSMutableArray { var result:NSMutableArray = NSMutableArray.array(); var artistsQuery:MPMediaQuery = MPMediaQuery.artistsQuery(); artistsQuery.groupingType = MPMediaGrouping.Album; result.addObjectsFromArray(artistsQuery.collections); result = self.groupArrayByInitial(result, theSelector:"albumTitle"); return result; } // get all songs func getiPodAllSongs() -> NSMutableArray { var result:NSMutableArray = NSMutableArray.array(); var playlistQuery:MPMediaQuery = MPMediaQuery.playlistsQuery(); playlistQuery.groupingType = MPMediaGrouping.Title; result.addObjectsFromArray(playlistQuery.collections);//MPMediaItemCollection result = self.groupArrayByInitial(result, theSelector:"title"); return result; } // group by a-z func groupArrayByInitial(inputArray:NSMutableArray, theSelector selector:Selector) -> NSMutableArray { var collation:UILocalizedIndexedCollation = UILocalizedIndexedCollation.currentCollation() as UILocalizedIndexedCollation; var sectionCount = (collation.sectionTitles as NSArray).count; var ret:NSMutableArray = NSMutableArray.array(); for ( var i = 0 ; i < sectionCount ; i++ ) { ret.addObject(NSMutableArray.array()); } // TODO: // for (var item:MPMediaItemCollection) in inputArray as [MPMediaItemCollection] { // var index:NSInteger = collation.sectionForObject(item.representativeItem, collationStringSelector: selector); // ret.objectAtIndex(index).addObject(item); // } return ret; } // get albums list func getiPodAlbums() -> NSMutableArray { var result:NSMutableArray = NSMutableArray.array(); return result; } // func getAlliPodSongs() -> NSMutableArray { var result:NSMutableArray = NSMutableArray.array(); var allSongsQuery:MPMediaQuery = MPMediaQuery.songsQuery(); var tempArray:NSArray = allSongsQuery.items; for item : AnyObject in tempArray { if ( item is MPMediaItem ) { let temp = item as MPMediaItem; if ( temp.mediaType != MPMediaType.Music ) { continue; } result.addObject(item); } } return result; } }
mit
536c17242d349cddf7c5e60b264eeeaf
31.087302
130
0.620084
5.13723
false
false
false
false
tdquang/CarlWrite
CVCalendar/CVCalendarContentViewController.swift
1
6683
// // CVCalendarContentViewController.swift // CVCalendar Demo // // Created by Eugene Mozharovsky on 12/04/15. // Copyright (c) 2015 GameApp. All rights reserved. // import UIKit typealias Identifier = String class CVCalendarContentViewController: UIViewController { // MARK: - Constants let Previous = "Previous" let Presented = "Presented" let Following = "Following" // MARK: - Public Properties let calendarView: CalendarView let scrollView: UIScrollView var presentedMonthView: MonthView var bounds: CGRect { return scrollView.bounds } var currentPage = 1 var pageChanged: Bool { get { return currentPage == 1 ? false : true } } var pageLoadingEnabled = true var presentationEnabled = true var lastContentOffset: CGFloat = 0 var direction: CVScrollDirection = .None init(calendarView: CalendarView, frame: CGRect) { self.calendarView = calendarView scrollView = UIScrollView(frame: frame) presentedMonthView = MonthView(calendarView: calendarView, date: NSDate()) presentedMonthView.updateAppearance(frame) super.init(nibName: nil, bundle: nil) scrollView.contentSize = CGSizeMake(frame.width * 3, frame.height) scrollView.showsHorizontalScrollIndicator = false scrollView.showsVerticalScrollIndicator = false scrollView.layer.masksToBounds = true scrollView.pagingEnabled = true scrollView.delegate = self } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: - UI Refresh extension CVCalendarContentViewController { func updateFrames(frame: CGRect) { if frame != CGRectZero { scrollView.frame = frame scrollView.removeAllSubviews() scrollView.contentSize = CGSizeMake(frame.size.width * 3, frame.size.height) } calendarView.hidden = false } } // MARK: - Abstract methods /// UIScrollViewDelegate extension CVCalendarContentViewController: UIScrollViewDelegate { } /// Convenience API. extension CVCalendarContentViewController { func performedDayViewSelection(dayView: DayView) { } func togglePresentedDate(date: NSDate) { } func presentNextView(view: UIView?) { } func presentPreviousView(view: UIView?) { } func updateDayViews(hidden: Bool) { } } // MARK: - Contsant conversion extension CVCalendarContentViewController { func indexOfIdentifier(identifier: Identifier) -> Int { let index: Int switch identifier { case Previous: index = 0 case Presented: index = 1 case Following: index = 2 default: index = -1 } return index } } // MARK: - Date management extension CVCalendarContentViewController { func dateBeforeDate(date: NSDate) -> NSDate { let components = Manager.componentsForDate(date) let calendar = NSCalendar.currentCalendar() components.month -= 1 let dateBefore = calendar.dateFromComponents(components)! return dateBefore } func dateAfterDate(date: NSDate) -> NSDate { let components = Manager.componentsForDate(date) let calendar = NSCalendar.currentCalendar() components.month += 1 let dateAfter = calendar.dateFromComponents(components)! return dateAfter } func matchedMonths(lhs: Date, _ rhs: Date) -> Bool { return lhs.year == rhs.year && lhs.month == rhs.month } func matchedWeeks(lhs: Date, _ rhs: Date) -> Bool { return (lhs.year == rhs.year && lhs.month == rhs.month && lhs.week == rhs.week) } func matchedDays(lhs: Date, _ rhs: Date) -> Bool { return (lhs.year == rhs.year && lhs.month == rhs.month && lhs.day == rhs.day) } } // MARK: - AutoLayout Management extension CVCalendarContentViewController { private func layoutViews(views: [UIView], toHeight height: CGFloat) { self.scrollView.frame.size.height = height self.calendarView.layoutIfNeeded() for view in views { view.layoutIfNeeded() } } func updateHeight(height: CGFloat, animated: Bool) { var viewsToLayout = [UIView]() if let calendarSuperview = calendarView.superview { for constraintIn in calendarSuperview.constraints { if let constraint = constraintIn as? NSLayoutConstraint { if let firstItem = constraint.firstItem as? UIView, let secondItem = constraint.secondItem as? CalendarView { viewsToLayout.append(firstItem) } } } } for constraintIn in calendarView.constraints { if let constraint = constraintIn as? NSLayoutConstraint where constraint.firstAttribute == NSLayoutAttribute.Height { calendarView.layoutIfNeeded() constraint.constant = height if animated { UIView.animateWithDuration(0.2, delay: 0, options: UIViewAnimationOptions.CurveLinear, animations: { self.layoutViews(viewsToLayout, toHeight: height) }) { _ in self.presentedMonthView.frame.size = self.presentedMonthView.potentialSize self.presentedMonthView.updateInteractiveView() } } else { layoutViews(viewsToLayout, toHeight: height) presentedMonthView.updateInteractiveView() presentedMonthView.frame.size = presentedMonthView.potentialSize presentedMonthView.updateInteractiveView() } break } } } func updateLayoutIfNeeded() { if presentedMonthView.potentialSize.height != scrollView.bounds.height { updateHeight(presentedMonthView.potentialSize.height, animated: true) } else if presentedMonthView.frame.size != scrollView.frame.size { presentedMonthView.frame.size = presentedMonthView.potentialSize presentedMonthView.updateInteractiveView() } } } extension UIView { func removeAllSubviews() { for subview in subviews { if let view = subview as? UIView { view.removeFromSuperview() } } } }
mit
a7f02134483d6c27908cd0e581b89faa
30.233645
129
0.613347
5.592469
false
false
false
false
marko628/Playground
Bridging.playground/Contents.swift
1
1825
// Cocoa Types and Bridging // Bridging // bridging example // edited in Textastic on iPad // importing Foundation (or UIKit) enables automatic bridging import Foundation // a NSString and a Swift String both in all lower-case let myNSString: NSString = "hello world!" let mySwiftString: String = "hey paraguay!" // use type(of:) to get object type String(describing: type(of:mySwiftString)) String(describing: type(of:myNSString)) // Automatic bridging: // capitalized is a NSString property // can use capitalized on a Swift String if you import Foundation or UIKit // this is because String is bridged to NSString myNSString.capitalized mySwiftString.capitalized // another example using hasPrefix(_:) myNSString.hasPrefix("hello") mySwiftString.hasPrefix("hey") // a NSArray and a Swift Array var myNSArray: NSArray = ["this is the end", "?"] var mySwiftArray: [String] = ["my only friend"] String(describing: type(of:mySwiftArray)) String(describing: type(of:myNSArray)) // use Mirror(reflecting:).subjectType to get subject type of object Mirror(reflecting: mySwiftArray).subjectType Mirror(reflecting: myNSArray).subjectType // Swift Arrays and NSArrays are not bridged // need to cast Swift Arrays to NSArrays in order to use NSArray methods func combineArrays(_ a1: NSArray, _ a2: NSArray) -> NSArray { return a1.addingObjects(from: a2 as [AnyObject]) as NSArray } combineArrays(myNSArray, mySwiftArray as NSArray) combineArrays(mySwiftArray as NSArray, mySwiftArray as NSArray) type(of:(mySwiftArray as NSArray)) String(describing: type(of:mySwiftArray)) String(describing: type(of:myNSArray)) // appending NSArrays var myNSArray2 = NSArray() myNSArray2 = myNSArray2.addingObjects(from: myNSArray as [AnyObject]) as NSArray myNSArray2.addingObjects(from: mySwiftArray as [AnyObject]) myNSArray2
mit
08a964ee0f4cf8695c8e8b5450a77a97
29.416667
80
0.772603
3.842105
false
false
false
false
creatubbles/ctb-api-swift
CreatubblesAPIClient/Sources/Requests/CustomStyle/CustomStyleFetchResponseHandler.swift
1
2198
// // CustomStyleFetchResponseHandler.swift // CreatubblesAPIClient // // Copyright (c) 2017 Creatubbles Pte. Ltd. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit import ObjectMapper class CustomStyleFetchResponseHandler: ResponseHandler { fileprivate let completion: CustomStyleClosure? init(completion: CustomStyleClosure?) { self.completion = completion } override func handleResponse(_ response: Dictionary<String, AnyObject>?, error: Error?) { if let response = response, let mapper = Mapper<CustomStyleMapper>().map(JSON: response["data"] as! [String : Any]) { let metadata = MappingUtils.metadataFromResponse(response) let dataMapper = MappingUtils.dataIncludeMapperFromResponse(response, metadata: metadata) let style = CustomStyle(mapper: mapper, dataMapper: dataMapper) executeOnMainQueue { self.completion?(style, ErrorTransformer.errorFromResponse(response, error: error)) } } else { executeOnMainQueue { self.completion?(nil, ErrorTransformer.errorFromResponse(response, error: error)) } } } }
mit
fcbeb2936e4c881654fb183300540996
44.791667
118
0.728389
4.757576
false
false
false
false
Rdxer/SnapKit
Sources/ConstraintMakerRelatable+Extensions.swift
3
2786
// // SnapKit // // Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit // // 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(iOS) || os(tvOS) import UIKit #else import AppKit #endif extension ConstraintMakerRelatable { @discardableResult public func equalToSuperview<T: ConstraintRelatableTarget>(_ closure: (ConstraintView) -> T, _ file: String = #file, line: UInt = #line) -> ConstraintMakerEditable { guard let other = self.description.item.superview else { fatalError("Expected superview but found nil when attempting make constraint `equalToSuperview`.") } return self.relatedTo(closure(other), relation: .equal, file: file, line: line) } @discardableResult public func lessThanOrEqualToSuperview<T: ConstraintRelatableTarget>(_ closure: (ConstraintView) -> T, _ file: String = #file, line: UInt = #line) -> ConstraintMakerEditable { guard let other = self.description.item.superview else { fatalError("Expected superview but found nil when attempting make constraint `lessThanOrEqualToSuperview`.") } return self.relatedTo(closure(other), relation: .lessThanOrEqual, file: file, line: line) } @discardableResult public func greaterThanOrEqualTo<T: ConstraintRelatableTarget>(_ closure: (ConstraintView) -> T, _ file: String = #file, line: UInt = #line) -> ConstraintMakerEditable { guard let other = self.description.item.superview else { fatalError("Expected superview but found nil when attempting make constraint `greaterThanOrEqualToSuperview`.") } return self.relatedTo(closure(other), relation: .greaterThanOrEqual, file: file, line: line) } }
mit
3f31ed58d253a21fe42b8621307dbcb2
47.877193
179
0.71967
4.635607
false
false
false
false
iOS-mamu/SS
P/Potatso/Base/SegmentPageVC.swift
1
1762
// // SegmentPageVC.swift // Potatso // // Created by LEI on 7/15/16. // Copyright © 2016 TouchingApp. All rights reserved. // import Foundation import Cartography class SegmentPageVC: UIViewController { override func viewDidLoad() { super.viewDidLoad() navigationItem.titleView = segmentedControl showPage(0) } func pageViewControllersForSegmentPageVC() -> [UIViewController] { fatalError() } func segmentsForSegmentPageVC() -> [String] { fatalError() } func onSegmentedChanged(_ seg: UISegmentedControl) { showPage(seg.selectedSegmentIndex) } func showPage(_ index: Int) { segmentedControl.selectedSegmentIndex = index let pageViewControllers = pageViewControllersForSegmentPageVC() if index < pageViewControllers.count { pageVC.setViewControllers([pageViewControllers[index]], direction: .forward, animated: false, completion: nil) } } override func loadView() { super.loadView() view.backgroundColor = Color.Background addChildVC(pageVC) setupAutoLayout() } func setupAutoLayout() { constrain(pageVC.view, view) { pageView, superview in pageView.edges == superview.edges } } lazy var pageVC: UIPageViewController = { let p = UIPageViewController(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil) return p }() lazy var segmentedControl: UISegmentedControl = { let v = UISegmentedControl(items: self.segmentsForSegmentPageVC()) v.addTarget(self, action: #selector(CollectionViewController.onSegmentedChanged(_:)), for: .valueChanged) return v }() }
mit
dcc16a7d0147425afe4c694108e8da0e
26.515625
122
0.659284
5.017094
false
false
false
false
CoderXiaoming/Ronaldo
SaleManager/SaleManager/ComOperation/Controller/SAMRankDetailController.swift
1
25409
// // SAMRankDetailController.swift // SaleManager // // Created by apple on 16/12/31. // Copyright © 2016年 YZH. All rights reserved. // import UIKit import MJRefresh class SAMRankDetailController: UIViewController { ///对外提供的类工厂方法 class func instance(customerRankModel: SAMCustomerRankModel?, productRankModel: SAMProductRankModel?) -> SAMRankDetailController { let vc = SAMRankDetailController() if customerRankModel != nil { vc.customerRankModel = customerRankModel vc.productRankModel = nil vc.requestURLStr = "getCustomerProductStatic.ashx" }else { vc.productRankModel = productRankModel vc.customerRankModel = nil vc.requestURLStr = "getSellStaticProductDetail.ashx" } return vc } ///对外提供的加载用户排行数据的方法 func willSearchRankDetailInfo(startDateStr: String, endDateStr: String, success: @escaping ()->(), noData: @escaping ()->(), defeat: @escaping ()->()) { //赋值 beginDate = startDateStr endDate = endDateStr //创建请求参数 if customerRankModel != nil { //客户排行请求 let CGUnitID = customerRankModel!.id let userID = "" requestParameters = ["CGUnitID": CGUnitID, "startDate": startDateStr, "endDate": endDateStr, "userID": userID] }else { //产品排行请求 let productID = productRankModel!.id let pageSize = String(format: "%d", requestPageSize) let pageIndex = String(format: "%d", requestPageIndex) requestParameters = ["productID": productID, "pageSize": pageSize, "pageIndex": pageIndex, "startDate": startDateStr, "endDate": endDateStr] } //发送请求 SAMNetWorker.sharedNetWorker().get(requestURLStr!, parameters: requestParameters, progress: nil, success: {[weak self] (Task, json) in //清空原先数据 self!.rankListModels.removeAllObjects() //获取模型数组 let Json = json as! [String: AnyObject] let dictArr = Json["body"] as? [[String: AnyObject]] let count = dictArr?.count ?? 0 //判断是否有模型数据 if count == 0 { //回主线程调用没有数据闭包 DispatchQueue.main.async(execute: { noData() }) }else { //有数据模型 if self!.customerRankModel != nil { //用户排行 let arr = SAMCustomerRankListModel.mj_objectArray(withKeyValuesArray: dictArr)! self!.rankListModels.addObjects(from: arr as [AnyObject]) }else { //产品排行 let arr = SAMProductRankListModel.mj_objectArray(withKeyValuesArray: dictArr)! self!.rankListModels.addObjects(from: arr as [AnyObject]) if arr.count < self!.requestPageSize { //记录状态,没有更多数据 self!.hasMoreData = false }else { //设置pageIndex,可能还有更多信息 self!.requestPageIndex += 1 //记录状态,可能有更多数据 self!.hasMoreData = true } } //回主线程,调用成功闭包 DispatchQueue.main.async(execute: { success() }) } }) { (Task, Error) in //回主线程,调用成功闭包 DispatchQueue.main.async(execute: { defeat() }) } } //MARK: - viewDidLoad override func viewDidLoad() { super.viewDidLoad() //设置时间按钮控件 setupDateButtonView() ///设置文本 setupTextField() //设置ScrollView setupCollectionView() //设置其他 setupOtherUI() } ///设置时间按钮控件 fileprivate func setupDateButtonView() { //设置dateBtnView的锚点, transform dateBtnView.layer.anchorPoint = CGPoint(x: 1, y: 0) dateBtnView.transform = CGAffineTransform(scaleX: 0.6, y: 0.6) dateBtnView.alpha = 0.00001 //设置时间按钮控件边框 dateBtnContentView.layer.cornerRadius = 5 } ///设置文本框 fileprivate func setupTextField() { let arr = NSArray(array: [beginDateTF, endDateTF]) arr.enumerateObjects({ (obj, _, _) in let textField = obj as! UITextField //设置代理 textField.delegate = self //设置输入控件 textField.inputView = datePicker }) //设置时间选择器最大时间 datePicker!.maximumDate = Date() } ///设置ScrollCollectionView fileprivate func setupCollectionView() { //设置代理数据源 collectionView.delegate = self collectionView.dataSource = self //注册cell collectionView.register(UINib(nibName: "SAMComOperationViewRankCell", bundle: nil), forCellWithReuseIdentifier: "SAMComOperationViewRankCell") //设置上拉 collectionView.mj_header = MJRefreshNormalHeader.init(refreshingTarget: self, refreshingAction: #selector(SAMRankDetailController.loadNewInfo)) if productRankModel != nil { //设置下拉 collectionView.mj_footer = MJRefreshAutoNormalFooter.init(refreshingTarget: self, refreshingAction: #selector(SAMRankDetailController.loadMoreInfo)) //判断是否还有更多数据 if !hasMoreData { collectionView.mj_footer.endRefreshingWithNoMoreData() } } } ///设置其他UI fileprivate func setupOtherUI() { //设置hudView let tapGesture = UITapGestureRecognizer(target: self, action: #selector(SAMComOperationController.hudViewDidClick)) hudView.addGestureRecognizer(tapGesture) //设置文本框文字 beginDateTF.text = beginDate endDateTF.text = endDate //设置搜索框代理 searchBar.delegate = self if customerRankModel != nil { //客户搜索 searchBar.placeholder = String(format: "产品排行(%@)", customerRankModel!.CGUnitName) }else { searchBar.placeholder = String(format: "客户排行(%@)", productRankModel!.productIDName) } } //MARK: - 加载新数据 func loadNewInfo() { //创建请求参数 if customerRankModel != nil { //客户排行搜索 let CGUnitID = customerRankModel!.id let startDate = beginDateTF.text! let endDate = endDateTF.text! let userID = "" requestParameters = ["CGUnitID": CGUnitID, "startDate": startDate, "endDate": endDate, "userID": userID] }else { //产品排行搜索 collectionView.mj_footer.endRefreshing() let productID = productRankModel!.id let pageSize = String(format: "%d", requestPageSize) requestPageIndex = 1 let pageIndex = String(format: "%d", requestPageIndex) let startDate = beginDateTF.text! let endDate = endDateTF.text! requestParameters = ["productID": productID, "pageSize": pageSize, "pageIndex": pageIndex, "startDate": startDate, "endDate": endDate] } //发送请求 SAMNetWorker.sharedNetWorker().get(requestURLStr!, parameters: requestParameters!, progress: nil, success: {[weak self] (Task, json) in //清空原先数据 self!.rankListModels.removeAllObjects() //获取模型数组 let Json = json as! [String: AnyObject] let dictArr = Json["body"] as? [[String: AnyObject]] let count = dictArr?.count ?? 0 //判断是否有模型数据 if count == 0 { //没有模型数据 let _ = SAMHUD.showMessage("暂无数据", superView: self!.view, hideDelay: SAMHUDNormalDuration, animated: true) }else { //有数据模型 if self!.customerRankModel != nil { //用户排行 let arr = SAMCustomerRankListModel.mj_objectArray(withKeyValuesArray: dictArr)! self!.rankListModels.addObjects(from: arr as [AnyObject]) }else { //产品排行 let arr = SAMProductRankListModel.mj_objectArray(withKeyValuesArray: dictArr)! self!.rankListModels.addObjects(from: arr as [AnyObject]) if arr.count < self!.requestPageSize { //改变上拉刷新状态 self!.collectionView.mj_footer.endRefreshingWithNoMoreData() }else { //设置pageIndex,可能还有更多信息 self!.requestPageIndex += 1 } } } //当前是搜索状态 if self!.isSearch { self!.searchBar(self!.searchBar, textDidChange: self!.searchBar.text!) } //回主线程,刷新数据 DispatchQueue.main.async(execute: { self!.collectionView.mj_header.endRefreshing() self!.collectionView.reloadData() }) }) {[weak self] (Task, Error) in //处理上拉 self!.collectionView.mj_header.endRefreshing() let _ = SAMHUD.showMessage("请检查网络", superView: self!.view, hideDelay: SAMHUDNormalDuration, animated: true) } } //MARK: - 加载更多数据 func loadMoreInfo() { //创建请求参数 let pageIndex = String(format: "%d", requestPageIndex) requestParameters!["pageIndex"] = pageIndex //发送请求 SAMNetWorker.sharedNetWorker().get(requestURLStr!, parameters: requestParameters, progress: nil, success: {[weak self] (Task, json) in //获取模型数组 let Json = json as! [String: AnyObject] let dictArr = Json["body"] as? [[String: AnyObject]] let count = dictArr?.count ?? 0 //判断是否有模型数据 if count == 0 { //没有模型数据 let _ = SAMHUD.showMessage("没有更多数据", superView: self!.view, hideDelay: SAMHUDNormalDuration, animated: true) self?.collectionView.mj_footer.endRefreshingWithNoMoreData() }else { //有数据模型 let arr = SAMProductRankListModel.mj_objectArray(withKeyValuesArray: dictArr)! //判断是否还有更过数据 if arr.count < self!.requestPageSize { //没有更多数据 //设置footer状态 self!.collectionView.mj_footer.endRefreshingWithNoMoreData() }else { //可能有更多数据 //设置pageIndex self!.requestPageIndex += 1 //处理下拉 self!.collectionView.mj_footer.endRefreshing() } self!.rankListModels.addObjects(from: arr as [AnyObject]) //当前是搜索状态 if self!.isSearch { self!.searchBar(self!.searchBar, textDidChange: self!.searchBar.text!) } //刷新数据 DispatchQueue.main.async(execute: { self!.collectionView.reloadData() }) } }) {[weak self] (Task, Error) in //处理上拉 self!.collectionView.mj_header.endRefreshing() let _ = SAMHUD.showMessage("请检查网络", superView: self!.view, hideDelay: SAMHUDNormalDuration, animated: true) } } //MARK: - 获取 客户 或者 状态 搜索字符串 fileprivate func searchConIn(textField: UITextField) -> String { let searchStr = textField.text?.lxm_stringByTrimmingWhitespace() if searchStr == "" { //没有内容 return "" } return (searchStr?.components(separatedBy: " ")[0])! } //MARK: - 用户点击事件 @IBAction func dismissBtnClick(_ sender: UIButton) { dismiss(animated: true, completion: nil) } ///时间控件按钮展示 @IBAction func dropDownBtnClick(_ sender: UIButton) { //退出第一相应textField endFirstTextFieldEditing() if !dropDownBtn.isSelected { //显示hudView hudView.isHidden = false //动画展示dateBtnView UIView.animate(withDuration: 0.3, animations: { self.dateBtnView.transform = CGAffineTransform.identity self.dateBtnView.alpha = 1 }, completion: { (_) in self.dropDownBtn.isSelected = !self.dropDownBtn.isSelected }) }else { //动画隐藏dateBtnView UIView.animate(withDuration: 0.3, animations: { self.dateBtnView.transform = CGAffineTransform(scaleX: 0.6, y: 0.6) self.dateBtnView.alpha = 0.00001 }, completion: { (_) in self.dropDownBtn.isSelected = !self.dropDownBtn.isSelected //隐藏HUDView self.hideHUDView() }) } } ///4个时间按钮的点击 @IBAction func todayBtnClick(_ sender: AnyObject) { dateBtnViewdidClick(0.0) } @IBAction func yesterdayBtnClick(_ sender: AnyObject) { dateBtnViewdidClick(1.0) } @IBAction func last7daysBtnClick(_ sender: AnyObject) { dateBtnViewdidClick(7.0) } @IBAction func last30daysBtnClick(_ sender: AnyObject) { dateBtnViewdidClick(30.0) } //MARK: - 4个时间按钮点击时调用 fileprivate func dateBtnViewdidClick(_ days: Double) { //隐藏时间按钮控件 dropDownBtnClick(dropDownBtn) //获取今天日期字符串 let todayDate = Date() let todayStr = todayDate.yyyyMMddStr() //获取目标日期字符串 let disDate = todayDate.beforeOrAfter(days, before: true) let disStr = disDate.yyyyMMddStr() //设置字符串 endDateTF.text = todayStr beginDateTF.text = disStr } //时间选择器 选择时间 func dateChanged(_ datePicker: UIDatePicker) { //设置文本框时间 firstTF?.text = datePicker.date.yyyyMMddStr() } //MARK: - 结束textField编辑状态 fileprivate func endFirstTextFieldEditing() { if firstTF != nil { firstTF?.resignFirstResponder() } } //MARK: - 点击了hudView func hudViewDidClick() { //结束textfield编辑状态 endFirstTextFieldEditing() //关闭dateButtonView if dropDownBtn.isSelected { dropDownBtnClick(dropDownBtn) } } //MARK: - 隐藏HUDView fileprivate func hideHUDView() { if firstTF == nil && dropDownBtn.isSelected == false { hudView.isHidden = true } } //MARK: - 属性 ///接收的用户排名的数据模型 fileprivate var customerRankModel: SAMCustomerRankModel? ///接收的产品排名的数据模型 fileprivate var productRankModel: SAMProductRankModel? ///请求的URL字符串 fileprivate var requestURLStr: String? ///请求参数数组 fileprivate var requestParameters: [String: String]? ///产品请求当前页码 fileprivate var requestPageIndex = 1 ///产品请求一页最多数量 fileprivate var requestPageSize = 20 ///是否有更多数据 fileprivate var hasMoreData = false ///搜索开始时间 fileprivate var beginDate: String? ///搜索停止时间 fileprivate var endDate: String? ///第一响应者 fileprivate var firstTF: UITextField? ///时间选择器 fileprivate lazy var datePicker: UIDatePicker? = { let datePicker = UIDatePicker() datePicker.datePickerMode = UIDatePickerMode.date datePicker.addTarget(self, action: #selector(SAMRankDetailController.dateChanged(_:)), for: .valueChanged) return datePicker }() ///数据模型数组 fileprivate let rankListModels = NSMutableArray() ///符合搜索结果模型数组 fileprivate let searchResultModels = NSMutableArray() ///记录当前是否在搜索 fileprivate var isSearch: Bool = false //MARK: - XIB链接属性 @IBOutlet weak var beginDateTF: SAMLoginTextField! @IBOutlet weak var endDateTF: SAMLoginTextField! @IBOutlet weak var dropDownBtn: UIButton! @IBOutlet weak var dateBtnView: UIView! @IBOutlet weak var dateBtnContentView: UIView! @IBOutlet weak var searchBar: UISearchBar! @IBOutlet weak var countLabel: UILabel! @IBOutlet weak var hudView: UIView! @IBOutlet weak var collectionView: UICollectionView! //MARK: - 其他方法 fileprivate init() { //重写该方法,为单例服务 super.init(nibName: nil, bundle: nil) } fileprivate override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func loadView() { //从xib加载view view = Bundle.main.loadNibNamed("SAMRankDetailController", owner: self, options: nil)![0] as! UIView } } //MARK: - UICollectionViewDelegate extension SAMRankDetailController: UICollectionViewDelegate { func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { endFirstTextFieldEditing() } } //MARK: - UICollectionViewDataSource extension SAMRankDetailController: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { let arr = isSearch ? searchResultModels : rankListModels //统计总米数 var countM = 0.0 if customerRankModel != nil { for obj in arr { let model = obj as! SAMCustomerRankListModel countM += model.countM } }else { for obj in arr { let model = obj as! SAMProductRankListModel countM += model.countM } } countLabel.text = String(format: "%.1f米", countM) return arr.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "SAMComOperationViewRankCell", for: indexPath) as! SAMComOperationViewRankCell if customerRankModel != nil { //客户排行搜索 var model: SAMCustomerRankListModel? if isSearch { model = (searchResultModels[indexPath.row] as! SAMCustomerRankListModel) }else { model = (rankListModels[indexPath.row] as! SAMCustomerRankListModel) } cell.customerRankListModel = model }else { //产品排行搜索 var model: SAMProductRankListModel? if isSearch { model = (searchResultModels[indexPath.row] as! SAMProductRankListModel) }else { model = (rankListModels[indexPath.row] as! SAMProductRankListModel) } cell.productRankListModel = model } return cell } } //MARK: - collectionView布局代理 extension SAMRankDetailController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: ScreenW, height: 55) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return 0 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return 0 } } //MARK: - UITextFieldDelegate extension SAMRankDetailController: UITextFieldDelegate { func textFieldDidBeginEditing(_ textField: UITextField) { //停止滚动 collectionView.setContentOffset(collectionView.contentOffset, animated: true) //展现hudView hudView.isHidden = false //判断dateBtnView是否展现 if dropDownBtn.isSelected { //隐藏界面 dropDownBtnClick(dropDownBtn) } //设置第一响应者 firstTF = textField } func textFieldDidEndEditing(_ textField: UITextField) { //清空firstTF firstTF = nil //隐藏hudView hideHUDView() } func textFieldShouldReturn(_ textField: UITextField) -> Bool { //结束第一响应者编辑状态 endFirstTextFieldEditing() return true } } //MARK: - 搜索框代理UISearchBarDelegate extension SAMRankDetailController: UISearchBarDelegate { func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) { //停止滚动 collectionView!.setContentOffset(collectionView!.contentOffset, animated: true) //调用方法 hudViewDidClick() //显示取消按钮 searchBar.showsCancelButton = true } func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { //清空搜索结果数组,并赋值 searchResultModels.removeAllObjects() searchResultModels.addObjects(from: rankListModels as [AnyObject]) //获取搜索字符串 let searchStr = NSString(string: searchText.lxm_stringByTrimmingWhitespace()!) if searchStr.length > 0 { //记录正在搜索 isSearch = true //获取搜索字符串数组 let searchItems = searchStr.components(separatedBy: " ") var andMatchPredicates = [NSPredicate]() for item in searchItems { let searchString = item as NSString //productIDName搜索谓语 let keyPath = (customerRankModel == nil) ? "CGUnitName" : "productIDName" let lhs = NSExpression(forKeyPath: keyPath) let rhs = NSExpression(forConstantValue: searchString) let firstPredicate = NSComparisonPredicate(leftExpression: lhs, rightExpression: rhs, modifier: .direct, type: .contains, options: .caseInsensitive) let orMatchPredicate = NSCompoundPredicate.init(orPredicateWithSubpredicates: [firstPredicate]) andMatchPredicates.append(orMatchPredicate) } let finalCompoundPredicate = NSCompoundPredicate.init(andPredicateWithSubpredicates: andMatchPredicates) //存储搜索结果 let arr = searchResultModels.filtered(using: finalCompoundPredicate) searchResultModels.removeAllObjects() searchResultModels.addObjects(from: arr) }else { //记录没有搜索 isSearch = false } //刷新tableView collectionView.reloadData() } func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { //结束搜索框编辑状态 searchBar.text = "" searchBar.resignFirstResponder() searchBar.showsCancelButton = false isSearch = false collectionView.reloadData() } //MARK: - 点击键盘搜索按钮调用 func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { searchBar.resignFirstResponder() } }
apache-2.0
3b4fc42d4531f8d015286b6c295f0f19
33.182609
175
0.568473
5.233193
false
false
false
false
kwkhaw/SwiftAnyPic
SwiftAnyPic/PAPHomeViewController.swift
1
3725
import UIKit class PAPHomeViewController: PAPPhotoTimelineViewController { var firstLaunch: Bool = false private var blankTimelineView: UIView? private var _presentingAccountNavController: UINavigationController? private var _presentingFriendNavController: UINavigationController? // MARK:- UIViewController override func viewDidLoad() { super.viewDidLoad() self.navigationItem.titleView = UIImageView(image: UIImage(named: "LogoNavigationBar.png")) self.navigationItem.rightBarButtonItem = PAPSettingsButtonItem(target: self, action: #selector(PAPHomeViewController.settingsButtonAction(_:))) self.blankTimelineView = UIView(frame: self.tableView.bounds) let button = UIButton(type: UIButtonType.Custom) button.frame = CGRectMake(33.0, 96.0, 253.0, 173.0) button.setBackgroundImage(UIImage(named: "HomeTimelineBlank.png"), forState: UIControlState.Normal) button.addTarget(self, action: #selector(PAPHomeViewController.inviteFriendsButtonAction(_:)), forControlEvents: UIControlEvents.TouchUpInside) self.blankTimelineView!.addSubview(button) } // MARK:- PFQueryTableViewController override func objectsDidLoad(error: NSError?) { super.objectsDidLoad(error) if self.objects!.count == 0 && !self.queryForTable().hasCachedResult() && !self.firstLaunch { self.tableView.scrollEnabled = false if self.blankTimelineView!.superview == nil { self.blankTimelineView!.alpha = 0.0 self.tableView.tableHeaderView = self.blankTimelineView UIView.animateWithDuration(0.200, animations: { self.blankTimelineView!.alpha = 1.0 }) } } else { self.tableView.tableHeaderView = nil self.tableView.scrollEnabled = true } } // MARK:- () func settingsButtonAction(sender: AnyObject) { let actionController = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet) let myProfileAction = UIAlertAction(title: NSLocalizedString("My Profile", comment: ""), style: UIAlertActionStyle.Default, handler: { _ in self.navigationController!.pushViewController(PAPAccountViewController(user: PFUser.currentUser()!), animated: true) }) let findFriendsAction = UIAlertAction(title: NSLocalizedString("Find Friends", comment: ""), style: UIAlertActionStyle.Default, handler: { _ in self.navigationController!.pushViewController(PAPFindFriendsViewController(style: UITableViewStyle.Plain), animated: true) }) let logOutAction = UIAlertAction(title: NSLocalizedString("Log Out", comment: ""), style: UIAlertActionStyle.Default, handler: { _ in // Log out user and present the login view controller (UIApplication.sharedApplication().delegate as! AppDelegate).logOut() }) let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil) actionController.addAction(myProfileAction) actionController.addAction(findFriendsAction) actionController.addAction(logOutAction) actionController.addAction(cancelAction) self.presentViewController(actionController, animated: true, completion: nil) } func inviteFriendsButtonAction(sender: AnyObject) { let detailViewController = PAPFindFriendsViewController(style: UITableViewStyle.Plain) self.navigationController!.pushViewController(detailViewController, animated: true) } }
cc0-1.0
d54264e087c4090375a5fd478cf08f32
46.151899
151
0.690201
5.510355
false
false
false
false
tzef/BunbunuCustom
BunbunuCustom/BunbunuCustom/ViewController.swift
1
1410
// // ViewController.swift // BunbunuCustom // // Created by LEE ZHE YU on 2016/5/22. // Copyright © 2016年 LEE ZHE YU. All rights reserved. // import UIKit private let reuseIdentifier = "basicCell" class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var tableView: UITableView! let menu = ["Button", "ImageView"] override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if let index = tableView.indexPathForSelectedRow { tableView.deselectRowAtIndexPath(index, animated: true) } } // MARK: - TableView func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return menu.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier, forIndexPath: indexPath) cell.textLabel?.text = menu[indexPath.row] return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let vcName = menu[indexPath.row] if let vc = storyboard?.instantiateViewControllerWithIdentifier(vcName) { self.showViewController(vc, sender: nil) } } }
mit
4ab12196dfb61332f8202e84c4ec9182
32.5
109
0.693674
5.061151
false
false
false
false
auth0/Lock.iOS-OSX
Lock/PasswordlessRouter.swift
2
5730
// PasswordlessRouter.swift // // Copyright (c) 2016 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 import Auth0 struct PasswordlessRouter: Router { weak var controller: LockViewController? let user = User() let lock: Lock var observerStore: ObserverStore { return self.lock.observerStore } init(lock: Lock, controller: LockViewController) { self.controller = controller self.lock = lock } var root: Presentable? { let connections = self.lock.connections guard !connections.isEmpty else { self.lock.logger.debug("No connections configured. Loading application info from Auth0...") let baseURL = self.lock.options.configurationBaseURL ?? self.lock.authentication.url let interactor = CDNLoaderInteractor(baseURL: baseURL, clientId: self.lock.authentication.clientId) return ConnectionLoadingPresenter(loader: interactor, navigator: self, dispatcher: observerStore, options: self.lock.options) } // Passwordless Email/SMS if let connection = connections.passwordless.filter({ $0.strategy == "email" }).first ?? connections.passwordless.filter({ $0.strategy == "sms" }).first { let passwordlessActivity = PasswordlessActivity.shared passwordlessActivity.dispatcher = self.lock.observerStore passwordlessActivity.messagePresenter = self.controller?.messagePresenter let interactor = PasswordlessInteractor(connection: connection, authentication: self.lock.authentication, dispatcher: observerStore, user: self.user, options: self.lock.options, passwordlessActivity: passwordlessActivity) let presenter = PasswordlessPresenter(interactor: interactor, connection: connection, navigator: self, options: self.lock.options) // +Social if !connections.oauth2.isEmpty { let interactor = Auth0OAuth2Interactor(authentication: self.lock.authentication, dispatcher: observerStore, options: self.lock.options, nativeHandlers: self.lock.nativeHandlers) presenter.authPresenter = AuthPresenter(connections: connections.oauth2, interactor: interactor, customStyle: self.lock.style.oauth2) } return presenter } // Social Only if !connections.oauth2.isEmpty { let interactor = Auth0OAuth2Interactor(authentication: self.lock.authentication, dispatcher: observerStore, options: self.lock.options, nativeHandlers: self.lock.nativeHandlers) let presenter = AuthPresenter(connections: connections.oauth2, interactor: interactor, customStyle: self.lock.style.oauth2) return presenter } return nil } func passwordless(withScreen screen: PasswordlessScreen, connection: PasswordlessConnection) -> Presentable? { let passwordlessActivity = PasswordlessActivity.shared passwordlessActivity.dispatcher = self.lock.observerStore passwordlessActivity.messagePresenter = self.controller?.messagePresenter let interactor = PasswordlessInteractor(connection: connection, authentication: self.lock.authentication, dispatcher: observerStore, user: self.user, options: self.lock.options, passwordlessActivity: passwordlessActivity) let presenter = PasswordlessPresenter(interactor: interactor, connection: connection, navigator: self, options: self.lock.options, screen: screen) return presenter } func onBack() { guard let current = self.controller?.routes.back() else { return } self.user.reset() let style = self.lock.style self.lock.logger.debug("Back pressed. Showing \(current)") switch current { case .root: self.controller?.present(self.root, title: style.hideTitle ? nil : style.title) default: break } } func navigate(_ route: Route) { let presentable: Presentable? switch route { case .root where self.controller?.routes.current != .root: presentable = self.root case .unrecoverableError(let error): presentable = self.unrecoverableError(for: error) case .passwordless(let screen, let connection): presentable = self.passwordless(withScreen: screen, connection: connection) default: self.lock.logger.warn("Ignoring navigation \(route)") return } self.lock.logger.debug("Navigating to \(route)") self.controller?.routes.go(route) self.controller?.present(presentable, title: route.title(withStyle: self.lock.style)) } }
mit
620bf87ce3e52810b0111f3467afde77
48.826087
233
0.705934
4.973958
false
false
false
false
Beaver/BeaverCodeGen
Pods/SourceKittenFramework/Source/SourceKittenFramework/String+SourceKitten.swift
1
25395
// // String+SourceKitten.swift // SourceKitten // // Created by JP Simard on 2015-01-05. // Copyright (c) 2015 SourceKitten. All rights reserved. // import Foundation // swiftlint:disable file_length // This file could easily be split up /// Representation of line in String public struct Line { /// origin = 0 public let index: Int /// Content public let content: String /// UTF16 based range in entire String. Equivalent to Range<UTF16Index> public let range: NSRange /// Byte based range in entire String. Equivalent to Range<UTF8Index> public let byteRange: NSRange } /** * For "wall of asterisk" comment blocks, such as this one. */ private let commentLinePrefixCharacterSet: CharacterSet = { var characterSet = CharacterSet.whitespacesAndNewlines characterSet.insert(charactersIn: "*") return characterSet }() extension NSString { /** CacheContainer caches: - UTF16-based NSRange - UTF8-based NSRange - Line */ private class CacheContainer { let lines: [Line] let utf8View: String.UTF8View init(_ string: NSString) { // Make a copy of the string to avoid holding a circular reference, which would leak // memory. // // If the string is a `Swift.String`, strongly referencing that in `CacheContainer` does // not cause a circular reference, because casting `String` to `NSString` makes a new // `NSString` instance. // // If the string is a native `NSString` instance, a circular reference is created when // assigning `self.utf8View = (string as String).utf8`. // // A reference to `NSString` is held by every cast `String` along with their views and // indices. let string = (string.mutableCopy() as! NSMutableString).bridge() utf8View = string.utf8 var utf16CountSoFar = 0 var bytesSoFar = 0 var lines = [Line]() let lineContents = string.components(separatedBy: .newlines) // Be compatible with `NSString.getLineStart(_:end:contentsEnd:forRange:)` let endsWithNewLineCharacter: Bool if let lastChar = string.utf16.last, let lastCharScalar = UnicodeScalar(lastChar) { endsWithNewLineCharacter = CharacterSet.newlines.contains(lastCharScalar) } else { endsWithNewLineCharacter = false } // if string ends with new line character, no empty line is generated after that. let enumerator = endsWithNewLineCharacter ? AnySequence(lineContents.dropLast().enumerated()) : AnySequence(lineContents.enumerated()) for (index, content) in enumerator { let index = index + 1 let rangeStart = utf16CountSoFar let utf16Count = content.utf16.count utf16CountSoFar += utf16Count let byteRangeStart = bytesSoFar let byteCount = content.lengthOfBytes(using: .utf8) bytesSoFar += byteCount let newlineLength = index != lineContents.count ? 1 : 0 // FIXME: assumes \n let line = Line( index: index, content: content, range: NSRange(location: rangeStart, length: utf16Count + newlineLength), byteRange: NSRange(location: byteRangeStart, length: byteCount + newlineLength) ) lines.append(line) utf16CountSoFar += newlineLength bytesSoFar += newlineLength } self.lines = lines } /** Returns UTF16 offset from UTF8 offset. - parameter byteOffset: UTF8-based offset of string. - returns: UTF16 based offset of string. */ func location(fromByteOffset byteOffset: Int) -> Int { if lines.isEmpty { return 0 } let index = lines.index(where: { NSLocationInRange(byteOffset, $0.byteRange) }) // byteOffset may be out of bounds when sourcekitd points end of string. guard let line = (index.map { lines[$0] } ?? lines.last) else { fatalError() } let diff = byteOffset - line.byteRange.location if diff == 0 { return line.range.location } else if line.byteRange.length == diff { return NSMaxRange(line.range) } let utf8View = line.content.utf8 let endUTF16index = utf8View.index(utf8View.startIndex, offsetBy: diff, limitedBy: utf8View.endIndex)! .samePosition(in: line.content.utf16)! let utf16Diff = line.content.utf16.distance(from: line.content.utf16.startIndex, to: endUTF16index) return line.range.location + utf16Diff } /** Returns UTF8 offset from UTF16 offset. - parameter location: UTF16-based offset of string. - returns: UTF8 based offset of string. */ func byteOffset(fromLocation location: Int) -> Int { if lines.isEmpty { return 0 } let index = lines.index(where: { NSLocationInRange(location, $0.range) }) // location may be out of bounds when NSRegularExpression points end of string. guard let line = (index.map { lines[$0] } ?? lines.last) else { fatalError() } let diff = location - line.range.location if diff == 0 { return line.byteRange.location } else if line.range.length == diff { return NSMaxRange(line.byteRange) } let utf16View = line.content.utf16 let endUTF8index = utf16View.index(utf16View.startIndex, offsetBy: diff, limitedBy: utf16View.endIndex)! .samePosition(in: line.content.utf8)! let byteDiff = line.content.utf8.distance(from: line.content.utf8.startIndex, to: endUTF8index) return line.byteRange.location + byteDiff } func lineAndCharacter(forCharacterOffset offset: Int, expandingTabsToWidth tabWidth: Int) -> (line: Int, character: Int)? { assert(tabWidth > 0) let index = lines.index(where: { NSLocationInRange(offset, $0.range) }) return index.map { let line = lines[$0] let prefixLength = offset - line.range.location let character: Int if tabWidth == 1 { character = prefixLength } else { #if swift(>=3.2) character = line.content.prefix(prefixLength).reduce(0) { sum, character in if character == "\t" { return sum - (sum % tabWidth) + tabWidth } else { return sum + 1 } } #else character = line.content.characters.prefix(prefixLength).reduce(0) { sum, character in if character == "\t" { return sum - (sum % tabWidth) + tabWidth } else { return sum + 1 } } #endif } return (line: line.index, character: character + 1) } } func lineAndCharacter(forByteOffset offset: Int, expandingTabsToWidth tabWidth: Int) -> (line: Int, character: Int)? { let characterOffset = location(fromByteOffset: offset) return lineAndCharacter(forCharacterOffset: characterOffset, expandingTabsToWidth: tabWidth) } } static private var stringCache = [NSString: CacheContainer]() static private var stringCacheLock = NSLock() /** CacheContainer instance is stored to instance of NSString as associated object. */ private var cacheContainer: CacheContainer { NSString.stringCacheLock.lock() defer { NSString.stringCacheLock.unlock() } if let cache = NSString.stringCache[self] { return cache } let cache = CacheContainer(self) NSString.stringCache[self] = cache return cache } /** Returns line number and character for utf16 based offset. - parameter offset: utf16 based index. - parameter tabWidth: the width in spaces to expand tabs to. */ public func lineAndCharacter(forCharacterOffset offset: Int, expandingTabsToWidth tabWidth: Int = 1) -> (line: Int, character: Int)? { return cacheContainer.lineAndCharacter(forCharacterOffset: offset, expandingTabsToWidth: tabWidth) } /** Returns line number and character for byte offset. - parameter offset: byte offset. - parameter tabWidth: the width in spaces to expand tabs to. */ public func lineAndCharacter(forByteOffset offset: Int, expandingTabsToWidth tabWidth: Int = 1) -> (line: Int, character: Int)? { return cacheContainer.lineAndCharacter(forByteOffset: offset, expandingTabsToWidth: tabWidth) } /** Returns a copy of `self` with the trailing contiguous characters belonging to `characterSet` removed. - parameter characterSet: Character set to check for membership. */ public func trimmingTrailingCharacters(in characterSet: CharacterSet) -> String { guard length > 0 else { return "" } var unicodeScalars = self.bridge().unicodeScalars while let scalar = unicodeScalars.last { if !characterSet.contains(scalar) { return String(unicodeScalars) } unicodeScalars.removeLast() } return "" } /** Returns self represented as an absolute path. - parameter rootDirectory: Absolute parent path if not already an absolute path. */ public func absolutePathRepresentation(rootDirectory: String = FileManager.default.currentDirectoryPath) -> String { if isAbsolutePath { return bridge() } #if os(Linux) return NSURL(fileURLWithPath: NSURL.fileURL(withPathComponents: [rootDirectory, bridge()])!.path).standardizingPath!.path #else return NSString.path(withComponents: [rootDirectory, bridge()]).bridge().standardizingPath #endif } /** Converts a range of byte offsets in `self` to an `NSRange` suitable for filtering `self` as an `NSString`. - parameter start: Starting byte offset. - parameter length: Length of bytes to include in range. - returns: An equivalent `NSRange`. */ public func byteRangeToNSRange(start: Int, length: Int) -> NSRange? { if self.length == 0 { return nil } let utf16Start = cacheContainer.location(fromByteOffset: start) if length == 0 { return NSRange(location: utf16Start, length: 0) } let utf16End = cacheContainer.location(fromByteOffset: start + length) return NSRange(location: utf16Start, length: utf16End - utf16Start) } /** Converts an `NSRange` suitable for filtering `self` as an `NSString` to a range of byte offsets in `self`. - parameter start: Starting character index in the string. - parameter length: Number of characters to include in range. - returns: An equivalent `NSRange`. */ public func NSRangeToByteRange(start: Int, length: Int) -> NSRange? { let string = bridge() let utf16View = string.utf16 let startUTF16Index = utf16View.index(utf16View.startIndex, offsetBy: start) let endUTF16Index = utf16View.index(startUTF16Index, offsetBy: length) let utf8View = string.utf8 guard let startUTF8Index = startUTF16Index.samePosition(in: utf8View), let endUTF8Index = endUTF16Index.samePosition(in: utf8View) else { return nil } // Don't using `CacheContainer` if string is short. // There are two reasons for: // 1. Avoid using associatedObject on NSTaggedPointerString (< 7 bytes) because that does // not free associatedObject. // 2. Using cache is overkill for short string. let byteOffset: Int if utf16View.count > 50 { byteOffset = cacheContainer.byteOffset(fromLocation: start) } else { byteOffset = utf8View.distance(from: utf8View.startIndex, to: startUTF8Index) } // `cacheContainer` will hit for below, but that will be calculated from startUTF8Index // in most case. let length = utf8View.distance(from: startUTF8Index, to: endUTF8Index) return NSRange(location: byteOffset, length: length) } /** Returns a substring with the provided byte range. - parameter start: Starting byte offset. - parameter length: Length of bytes to include in range. */ public func substringWithByteRange(start: Int, length: Int) -> String? { return byteRangeToNSRange(start: start, length: length).map(substring) } /** Returns a substring starting at the beginning of `start`'s line and ending at the end of `end`'s line. Returns `start`'s entire line if `end` is nil. - parameter start: Starting byte offset. - parameter length: Length of bytes to include in range. */ public func substringLinesWithByteRange(start: Int, length: Int) -> String? { return byteRangeToNSRange(start: start, length: length).map { range in var lineStart = 0, lineEnd = 0 getLineStart(&lineStart, end: &lineEnd, contentsEnd: nil, for: range) return substring(with: NSRange(location: lineStart, length: lineEnd - lineStart)) } } public func substringStartingLinesWithByteRange(start: Int, length: Int) -> String? { return byteRangeToNSRange(start: start, length: length).map { range in var lineStart = 0, lineEnd = 0 getLineStart(&lineStart, end: &lineEnd, contentsEnd: nil, for: range) return substring(with: NSRange(location: lineStart, length: NSMaxRange(range) - lineStart)) } } /** Returns line numbers containing starting and ending byte offsets. - parameter start: Starting byte offset. - parameter length: Length of bytes to include in range. */ public func lineRangeWithByteRange(start: Int, length: Int) -> (start: Int, end: Int)? { return byteRangeToNSRange(start: start, length: length).flatMap { range in var numberOfLines = 0, index = 0, lineRangeStart = 0 while index < self.length { numberOfLines += 1 if index <= range.location { lineRangeStart = numberOfLines } index = NSMaxRange(lineRange(for: NSRange(location: index, length: 1))) if index > NSMaxRange(range) { return (lineRangeStart, numberOfLines) } } return nil } } /** Returns an array of Lines for each line in the file. */ public func lines() -> [Line] { return cacheContainer.lines } /** Returns true if self is an Objective-C header file. */ public func isObjectiveCHeaderFile() -> Bool { return ["h", "hpp", "hh"].contains(pathExtension) } /** Returns true if self is a Swift file. */ public func isSwiftFile() -> Bool { return pathExtension == "swift" } #if !os(Linux) /** Returns a substring from a start and end SourceLocation. */ public func substringWithSourceRange(start: SourceLocation, end: SourceLocation) -> String? { return substringWithByteRange(start: Int(start.offset), length: Int(end.offset - start.offset)) } #endif } extension String { internal var isFile: Bool { return FileManager.default.fileExists(atPath: self) } internal func capitalizingFirstLetter() -> String { #if swift(>=3.2) return String(prefix(1)).capitalized + String(dropFirst()) #else return String(characters.prefix(1)).capitalized + String(characters.dropFirst()) #endif } #if !os(Linux) /// Returns the `#pragma mark`s in the string. /// Just the content; no leading dashes or leading `#pragma mark`. public func pragmaMarks(filename: String, excludeRanges: [NSRange], limit: NSRange?) -> [SourceDeclaration] { let regex = try! NSRegularExpression(pattern: "(#pragma\\smark|@name)[ -]*([^\\n]+)", options: []) // Safe to force try let range: NSRange if let limit = limit { range = NSRange(location: limit.location, length: min(utf16.count - limit.location, limit.length)) } else { range = NSRange(location: 0, length: utf16.count) } let matches = regex.matches(in: self, options: [], range: range) return matches.flatMap { match in let markRange = match.range(at: 2) for excludedRange in excludeRanges { if NSIntersectionRange(excludedRange, markRange).length > 0 { return nil } } let markString = (self as NSString).substring(with: markRange).trimmingCharacters(in: .whitespaces) if markString.isEmpty { return nil } guard let markByteRange = self.NSRangeToByteRange(start: markRange.location, length: markRange.length) else { return nil } let location = SourceLocation(file: filename, line: UInt32((self as NSString).lineRangeWithByteRange(start: markByteRange.location, length: 0)!.start), column: 1, offset: UInt32(markByteRange.location)) return SourceDeclaration(type: .mark, location: location, extent: (location, location), name: markString, usr: nil, declaration: nil, documentation: nil, commentBody: nil, children: [], swiftDeclaration: nil, availability: nil) } } #endif /** Returns whether or not the `token` can be documented. Either because it is a `SyntaxKind.Identifier` or because it is a function treated as a `SyntaxKind.Keyword`: - `subscript` - `init` - `deinit` - parameter token: Token to process. */ public func isTokenDocumentable(token: SyntaxToken) -> Bool { if token.type == SyntaxKind.keyword.rawValue { let keywordFunctions = ["subscript", "init", "deinit"] return bridge().substringWithByteRange(start: token.offset, length: token.length) .map(keywordFunctions.contains) ?? false } return token.type == SyntaxKind.identifier.rawValue } /** Find integer offsets of documented Swift tokens in self. - parameter syntaxMap: Syntax Map returned from SourceKit editor.open request. - returns: Array of documented token offsets. */ public func documentedTokenOffsets(syntaxMap: SyntaxMap) -> [Int] { let documentableOffsets = syntaxMap.tokens.filter(isTokenDocumentable).map { $0.offset } let regex = try! NSRegularExpression(pattern: "(///.*\\n|\\*/\\n)", options: []) // Safe to force try let range = NSRange(location: 0, length: utf16.count) let matches = regex.matches(in: self, options: [], range: range) return matches.flatMap { match in documentableOffsets.first { $0 >= match.range.location } } } /** Returns the body of the comment if the string is a comment. - parameter range: Range to restrict the search for a comment body. */ public func commentBody(range: NSRange? = nil) -> String? { let nsString = bridge() let patterns: [(pattern: String, options: NSRegularExpression.Options)] = [ ("^\\s*\\/\\*\\*\\s*(.*?)\\*\\/", [.anchorsMatchLines, .dotMatchesLineSeparators]), // multi: ^\s*\/\*\*\s*(.*?)\*\/ ("^\\s*\\/\\/\\/(.+)?", .anchorsMatchLines) // single: ^\s*\/\/\/(.+)? // swiftlint:disable:previous comma ] let range = range ?? NSRange(location: 0, length: nsString.length) for pattern in patterns { let regex = try! NSRegularExpression(pattern: pattern.pattern, options: pattern.options) // Safe to force try let matches = regex.matches(in: self, options: [], range: range) let bodyParts = matches.flatMap { match -> [String] in let numberOfRanges = match.numberOfRanges if numberOfRanges < 1 { return [] } return (1..<numberOfRanges).map { rangeIndex in let range = match.range(at: rangeIndex) if range.location == NSNotFound { return "" // empty capture group, return empty string } var lineStart = 0 var lineEnd = nsString.length let indexRange = NSRange(location: range.location, length: 0) nsString.getLineStart(&lineStart, end: &lineEnd, contentsEnd: nil, for: indexRange) let leadingWhitespaceCountToAdd = nsString.substring(with: NSRange(location: lineStart, length: lineEnd - lineStart)) .countOfLeadingCharacters(in: .whitespacesAndNewlines) let leadingWhitespaceToAdd = String(repeating: " ", count: leadingWhitespaceCountToAdd) let bodySubstring = nsString.substring(with: range) if bodySubstring.contains("@name") { return "" // appledoc directive, return empty string } return leadingWhitespaceToAdd + bodySubstring } } if !bodyParts.isEmpty { return bodyParts.joined(separator: "\n").bridge() .trimmingTrailingCharacters(in: .whitespacesAndNewlines) .removingCommonLeadingWhitespaceFromLines() } } return nil } /// Returns a copy of `self` with the leading whitespace common in each line removed. public func removingCommonLeadingWhitespaceFromLines() -> String { var minLeadingCharacters = Int.max let lineComponents = components(separatedBy: .newlines) for line in lineComponents { let lineLeadingWhitespace = line.countOfLeadingCharacters(in: .whitespacesAndNewlines) let lineLeadingCharacters = line.countOfLeadingCharacters(in: commentLinePrefixCharacterSet) // Is this prefix smaller than our last and not entirely whitespace? #if swift(>=3.2) if lineLeadingCharacters < minLeadingCharacters && lineLeadingWhitespace != line.count { minLeadingCharacters = lineLeadingCharacters } #else if lineLeadingCharacters < minLeadingCharacters && lineLeadingWhitespace != line.characters.count { minLeadingCharacters = lineLeadingCharacters } #endif } return lineComponents.map { line in #if swift(>=3.2) if line.count >= minLeadingCharacters { return String(line[line.index(line.startIndex, offsetBy: minLeadingCharacters)...]) } #else if line.characters.count >= minLeadingCharacters { let range: Range = line.index(line.startIndex, offsetBy: minLeadingCharacters)..<line.endIndex return line.substring(with: range) } #endif return line }.joined(separator: "\n") } /** Returns the number of contiguous characters at the start of `self` belonging to `characterSet`. - parameter characterSet: Character set to check for membership. */ public func countOfLeadingCharacters(in characterSet: CharacterSet) -> Int { let characterSet = characterSet.bridge() var count = 0 for char in utf16 { if !characterSet.characterIsMember(char) { break } count += 1 } return count } /// Returns a copy of the string by trimming whitespace and the opening curly brace (`{`). internal func trimmingWhitespaceAndOpeningCurlyBrace() -> String? { var unwantedSet = CharacterSet.whitespacesAndNewlines unwantedSet.insert(charactersIn: "{") return trimmingCharacters(in: unwantedSet) } /// Returns the byte offset of the section of the string following the last dot ".", or 0 if no dots. internal func byteOffsetOfInnerTypeName() -> Int64 { guard let range = range(of: ".", options: .backwards) else { return 0 } #if swift(>=4.0) let utf8pos = index(after: range.lowerBound).samePosition(in: utf8)! #else let utf8pos = index(after: range.lowerBound).samePosition(in: utf8) #endif return Int64(utf8.distance(from: utf8.startIndex, to: utf8pos)) } }
mit
0a82f48dcfa80861c859ca43db21cc14
39.118483
138
0.603898
4.929154
false
false
false
false
horothesun/ImmutableGraph
Sources/ImmutableGraph/Utils/ImmutableQueue.swift
1
1223
public protocol ImmutableQueueProtocol: Equatable { associatedtype Element: Equatable var isEmpty: Bool { get } func toArray() -> [Element] func enqueue(_ element: Element) -> Self func dequeue() -> (Element?, Self) } public struct ImmutableQueue<T>: ImmutableQueueProtocol where T: Equatable { public typealias Element = T private let elements: [T] public init() { elements = [T]() } public init(_ elements: [T]) { self.elements = elements } public static func ==(lhs: ImmutableQueue<T>, rhs: ImmutableQueue<T>) -> Bool { return (lhs.toArray() == rhs.toArray()) } public var isEmpty: Bool { get { return elements.isEmpty } } public func toArray() -> [T] { return elements } public func enqueue(_ element: T) -> ImmutableQueue<T> { var newElements = elements newElements.append(element) return ImmutableQueue(newElements) } public func dequeue() -> (T?, ImmutableQueue<T>) { let newQueue = (isEmpty ? self : ImmutableQueue(Array(elements.suffix(from: 1)))) return (elements.first, newQueue) } }
mit
ef2b3eab2a945b82671fd322212e0aff
24.479167
83
0.588716
4.580524
false
false
false
false
heshamMassoud/RouteMe
RouteMe/TransitStep.swift
1
1593
// // TransitStep.swift // RouteMe // // Created by Hesham Massoud on 27/05/16. // Copyright © 2016 Hesham Massoud. All rights reserved. // import Foundation class TransitStep { var transportationMode: String var transportationLineHeadSign: String var transportationVehicleShortName: String var transportationLineColorCode: String var startStation: String var endStation: String var duration: String var startTime: String var endTime: String init(transportationMode: String, transportationLineHeadSign: String, transportationVehicleShortName: String, transportationLineColorCode: String, startStation: String, endStation: String, duration: String, startTime: String, endTime: String) { self.transportationMode = transportationMode self.transportationLineHeadSign = transportationLineHeadSign self.transportationVehicleShortName = transportationVehicleShortName self.transportationLineColorCode = transportationLineColorCode self.startStation = startStation self.endStation = endStation self.duration = duration self.startTime = startTime self.endTime = endTime } init() { self.transportationMode = String() self.transportationLineHeadSign = String() self.transportationVehicleShortName = String() self.transportationLineColorCode = String() self.startStation = String() self.endStation = String() self.duration = String() self.startTime = String() self.endTime = String() } }
apache-2.0
6b81c62c3e541689b8c3ad15560ee937
33.630435
247
0.711055
4.724036
false
false
false
false
noppoMan/aws-sdk-swift
Sources/Soto/Services/MediaTailor/MediaTailor_Error.swift
1
1755
//===----------------------------------------------------------------------===// // // 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 MediaTailor public struct MediaTailorErrorType: AWSErrorType { enum Code: String { case badRequestException = "BadRequestException" } private let error: Code public let context: AWSErrorContext? /// initialize MediaTailor 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 } /// One of the parameters in the request is invalid. public static var badRequestException: Self { .init(.badRequestException) } } extension MediaTailorErrorType: Equatable { public static func == (lhs: MediaTailorErrorType, rhs: MediaTailorErrorType) -> Bool { lhs.error == rhs.error } } extension MediaTailorErrorType: CustomStringConvertible { public var description: String { return "\(self.error.rawValue): \(self.message ?? "")" } }
apache-2.0
d0330fefd76d5153f79d8bc42dc44314
29.789474
117
0.62735
4.705094
false
false
false
false
strike65/SwiftyStats
SwiftyStats/CommonSource/ProbDist/ProbDist-ExtremValue.swift
1
5957
// // Created by VT on 20.07.18. // Copyright © 2018 strike65. All rights reserved. /* Copyright (2017-2019) strike65 GNU GPL 3+ This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 3 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ import Foundation #if os(macOS) || os(iOS) import os.log #endif extension SSProbDist { /// Extreme value distribution public enum ExtremeValue { /// Returns a SSProbDistParams struct containing mean, variance, kurtosis and skewness of the Extrem Value distribution. /// - Parameter a: location /// - Parameter b: scale /// - Throws: SSSwiftyStatsError if b <= 0 public static func para<FPT: SSFloatingPoint & Codable>(location a: FPT, scale b: FPT) throws -> SSProbDistParams<FPT> { var result: SSProbDistParams<FPT> = SSProbDistParams<FPT>() if b <= 0 { #if os(macOS) || os(iOS) if #available(macOS 10.12, iOS 13, *) { os_log("scale parameter are expected to be > 0", log: .log_stat, type: .error) } #endif throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function) } let ZETA3: FPT = Helpers.makeFP(1.202056903159594285399738161511449990764986292340498881792271555) result.mean = a + FPT.eulergamma result.variance = (b * b * FPT.pisquared) / 6 result.skewness = (12 * FPT.sqrt6 * ZETA3) / (FPT.pisquared * FPT.pi) result.kurtosis = Helpers.makeFP(5.4) return result } /// Returns the pdf of the Extrem Value distribution. /// - Parameter a: location /// - Parameter b: scale /// - Parameter x: x /// - Throws: SSSwiftyStatsError if b <= 0 public static func pdf<FPT: SSFloatingPoint & Codable>(x: FPT, location a: FPT, scale b: FPT) throws -> FPT { if b <= 0 { #if os(macOS) || os(iOS) if #available(macOS 10.12, iOS 13, *) { os_log("scale parameter are expected to be > 0", log: .log_stat, type: .error) } #endif throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function) } var result: FPT = 0 var ex1: FPT var ex2: FPT var ex3: FPT var ex4: FPT ex1 = x - a ex2 = ex1 / b ex3 = SSMath.exp1(-ex2) ex4 = SSMath.exp1(-ex3) result = SSMath.exp1(-ex2) * ex4 / b return result } /// Returns the cdf of the Extrem Value distribution. /// - Parameter a: location /// - Parameter b: scale /// - Parameter x: x /// - Throws: SSSwiftyStatsError if b <= 0 public static func cdf<FPT: SSFloatingPoint & Codable>(x: FPT, location a: FPT, scale b: FPT) throws -> FPT { if b <= 0 { #if os(macOS) || os(iOS) if #available(macOS 10.12, iOS 13, *) { os_log("scale parameter are expected to be > 0", log: .log_stat, type: .error) } #endif throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function) } var ex1: FPT var ex2: FPT var ex3: FPT var result: FPT = 0 ex1 = -a + x ex2 = ex1 / b ex3 = SSMath.exp1(-ex2) result = SSMath.exp1(-ex3) return result } /// Returns the p-quantile of the Extrem Value distribution. /// - Parameter a: location /// - Parameter b: scale /// - Parameter p: p /// - Throws: SSSwiftyStatsError if b <= 0 public static func quantile<FPT: SSFloatingPoint & Codable>(p: FPT, location a: FPT, scale b: FPT) throws -> FPT { if b <= 0 { #if os(macOS) || os(iOS) if #available(macOS 10.12, iOS 13, *) { os_log("scale parameter are expected to be > 0", log: .log_stat, type: .error) } #endif throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function) } if p < 0 || p > 1 { #if os(macOS) || os(iOS) if #available(macOS 10.12, iOS 13, *) { os_log("p is expected to be >= 0.0 and <= 1.0", log: .log_stat, type: .error) } #endif throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function) } if p <= 0 { return -FPT.infinity } else if (p >= 1) { return FPT.infinity } else { return a - b * SSMath.log1(-SSMath.log1(p)) } } } }
gpl-3.0
296eadaeaf564ca3934f8016cf86cd3e
36.696203
135
0.513096
4.372981
false
false
false
false
voidException/AlamofireImage
Source/UIImage+AlamofireImage.swift
13
10543
// UIImage+AlamofireImage.swift // // Copyright (c) 2015 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 CoreGraphics import Foundation import UIKit #if os(iOS) import CoreImage #endif // MARK: Initialization private let lock = NSLock() extension UIImage { /** Initializes and returns the image object with the specified data in a thread-safe manner. It has been reported that there are thread-safety issues when initializing large amounts of images simultaneously. In the event of these issues occurring, this method can be used in place of the `init?(data:)` method. - parameter data: The data object containing the image data. - returns: An initialized `UIImage` object, or `nil` if the method failed. */ public static func af_threadSafeImageWithData(data: NSData) -> UIImage? { lock.lock() let image = UIImage(data: data) lock.unlock() return image } /** Initializes and returns the image object with the specified data and scale in a thread-safe manner. It has been reported that there are thread-safety issues when initializing large amounts of images simultaneously. In the event of these issues occurring, this method can be used in place of the `init?(data:scale:)` method. - parameter data: The data object containing the image data. - parameter scale: The scale factor to assume when interpreting the image data. Applying a scale factor of 1.0 results in an image whose size matches the pixel-based dimensions of the image. Applying a different scale factor changes the size of the image as reported by the size property. - returns: An initialized `UIImage` object, or `nil` if the method failed. */ public static func af_threadSafeImageWithData(data: NSData, scale: CGFloat) -> UIImage? { lock.lock() let image = UIImage(data: data, scale: scale) lock.unlock() return image } } // MARK: - Inflation extension UIImage { private struct AssociatedKeys { static var InflatedKey = "af_UIImage.Inflated" } /// Returns whether the image is inflated. public var af_inflated: Bool { get { if let inflated = objc_getAssociatedObject(self, &AssociatedKeys.InflatedKey) as? Bool { return inflated } else { return false } } set(inflated) { objc_setAssociatedObject(self, &AssociatedKeys.InflatedKey, inflated, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } /** Inflates the underlying compressed image data to be backed by an uncompressed bitmap representation. Inflating compressed image formats (such as PNG or JPEG) can significantly improve drawing performance as it allows a bitmap representation to be constructed in the background rather than on the main thread. */ public func af_inflate() { guard !af_inflated else { return } af_inflated = true CGDataProviderCopyData(CGImageGetDataProvider(CGImage)) } } // MARK: - Scaling extension UIImage { /** Returns a new version of the image scaled to the specified size. - parameter size: The size to use when scaling the new image. - returns: A new image object. */ public func af_imageScaledToSize(size: CGSize) -> UIImage { UIGraphicsBeginImageContextWithOptions(size, false, 0.0) drawInRect(CGRect(origin: CGPointZero, size: size)) let scaledImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return scaledImage } /** Returns a new version of the image scaled from the center while maintaining the aspect ratio to fit within a specified size. - parameter size: The size to use when scaling the new image. - returns: A new image object. */ public func af_imageAspectScaledToFitSize(size: CGSize) -> UIImage { let imageAspectRatio = self.size.width / self.size.height let canvasAspectRatio = size.width / size.height var resizeFactor: CGFloat if imageAspectRatio > canvasAspectRatio { resizeFactor = size.width / self.size.width } else { resizeFactor = size.height / self.size.height } let scaledSize = CGSize(width: self.size.width * resizeFactor, height: self.size.height * resizeFactor) let origin = CGPoint(x: (size.width - scaledSize.width) / 2.0, y: (size.height - scaledSize.height) / 2.0) UIGraphicsBeginImageContextWithOptions(size, false, 0.0) drawInRect(CGRect(origin: origin, size: scaledSize)) let scaledImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return scaledImage } /** Returns a new version of the image scaled from the center while maintaining the aspect ratio to fill a specified size. Any pixels that fall outside the specified size are clipped. - parameter size: The size to use when scaling the new image. - returns: A new image object. */ public func af_imageAspectScaledToFillSize(size: CGSize) -> UIImage { let imageAspectRatio = self.size.width / self.size.height let canvasAspectRatio = size.width / size.height var resizeFactor: CGFloat if imageAspectRatio > canvasAspectRatio { resizeFactor = size.height / self.size.height } else { resizeFactor = size.width / self.size.width } let scaledSize = CGSize(width: self.size.width * resizeFactor, height: self.size.height * resizeFactor) let origin = CGPoint(x: (size.width - scaledSize.width) / 2.0, y: (size.height - scaledSize.height) / 2.0) UIGraphicsBeginImageContextWithOptions(size, false, 0.0) drawInRect(CGRect(origin: origin, size: scaledSize)) let scaledImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return scaledImage } } // MARK: - Rounded Corners extension UIImage { /** Returns a new version of the image with the corners rounded to the specified radius. - parameter radius: The radius to use when rounding the new image. - returns: A new image object. */ public func af_imageWithRoundedCornerRadius(radius: CGFloat) -> UIImage { UIGraphicsBeginImageContextWithOptions(size, false, 0.0) let scaledRadius = radius / scale let clippingPath = UIBezierPath(roundedRect: CGRect(origin: CGPointZero, size: size), cornerRadius: scaledRadius) clippingPath.addClip() drawInRect(CGRect(origin: CGPointZero, size: size)) let roundedImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return roundedImage } /** Returns a new version of the image rounded into a circle. - returns: A new image object. */ public func af_imageRoundedIntoCircle() -> UIImage { let radius = min(size.width, size.height) / 2.0 var squareImage = self if size.width != size.height { let squareDimension = min(size.width, size.height) let squareSize = CGSize(width: squareDimension, height: squareDimension) squareImage = af_imageAspectScaledToFillSize(squareSize) } UIGraphicsBeginImageContextWithOptions(squareImage.size, false, 0.0) let clippingPath = UIBezierPath( roundedRect: CGRect(origin: CGPointZero, size: squareImage.size), cornerRadius: radius ) clippingPath.addClip() squareImage.drawInRect(CGRect(origin: CGPointZero, size: squareImage.size)) let roundedImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return roundedImage } } #if os(iOS) // MARK: - Core Image Filters extension UIImage { /** Returns a new version of the image using a CoreImage filter with the specified name and parameters. - parameter filterName: The name of the CoreImage filter to use on the new image. - parameter filterParameters: The parameters to apply to the CoreImage filter. - returns: A new image object, or `nil` if the filter failed for any reason. */ public func af_imageWithAppliedCoreImageFilter( filterName: String, filterParameters: [String: AnyObject]? = nil) -> UIImage? { var image: CoreImage.CIImage? = CIImage if image == nil, let CGImage = self.CGImage { image = CoreImage.CIImage(CGImage: CGImage) } guard let coreImage = image else { return nil } let context = CIContext(options: [kCIContextPriorityRequestLow: true]) var parameters: [String: AnyObject] = filterParameters ?? [:] parameters[kCIInputImageKey] = coreImage guard let filter = CIFilter(name: filterName, withInputParameters: parameters) else { return nil } guard let outputImage = filter.outputImage else { return nil } let cgImageRef = context.createCGImage(outputImage, fromRect: coreImage.extent) return UIImage(CGImage: cgImageRef, scale: scale, orientation: imageOrientation) } } #endif
mit
30a3634038ef6ec8981146e2e4f2b418
34.618243
121
0.675045
4.987228
false
false
false
false
CodeDrunkard/Algorithm
Algorithm.playground/Pages/LinkedList.xcplaygroundpage/Contents.swift
1
5536
/*: Linked List Note: Operations are O(1). */ public class ListNode<T> { public var value: T public var next: ListNode? public weak var previous: ListNode? public init(_ value: T) { self.value = value } } final public class List<T> { public typealias Node = ListNode<T> public fileprivate(set) var lead: Node? public fileprivate(set) var tail: Node? public fileprivate(set) var count: Int = 0 public init() {} } extension List { public var isEmpty: Bool { return lead == nil } @discardableResult public func append(value: T) -> Node { let new = Node(value) if isEmpty { lead = new tail = new } else { new.previous = tail tail!.next = new tail = new } count += 1 return tail! } public func node(at index: Int) -> Node { assert(index >= 0 && index < count, "illegal index!") let pivot = (count - 1) / 2 if index > pivot { var i = count - 1 var previous = tail while true { if i == index { return previous! } i -= 1 previous = previous!.previous } } else { var i = 0 var next = lead while true { if i == index { return next! } i += 1 next = next!.next } } } @discardableResult public func insert(value: T, at index: Int) -> Node { if isEmpty { return append(value: value) } else if index == count { let new = Node(value) return new } else { let insertedNode = node(at: index) let new = Node(value) if let pre = insertedNode.previous { pre.next = new new.previous = pre } else { lead = new } new.next = insertedNode insertedNode.previous = new count += 1 return new } } private func remove(_ node: Node) { if let pre = node.previous { pre.next = node.next } else { lead = node.next } if let nex = node.next { nex.previous = node.previous } else { tail = node.previous } count -= 1 node.previous = nil node.next = nil } @discardableResult public func remove(at index: Int) -> Node { let node = self.node(at: index) remove(node) return node } public func removeLead() { guard let lead = lead else { return } remove(lead) } public func removeTail() { guard let tail = tail else { return } remove(tail) } public func removeAll() { lead = nil tail = nil } } extension List { public func reverse() { var node = lead while let currentNode = node { node = currentNode.next swap(&currentNode.next, &currentNode.previous) lead = currentNode } } } extension List { public func map<U>(transform: (T) -> U) -> List<U> { let result = List<U>() var node = lead while node != nil { result.append(value: transform(node!.value)) node = node!.next } return result } public func filter(predicate: (T) -> Bool) -> List<T> { let result = List<T>() var node = lead while node != nil { if predicate(node!.value) { result.append(value: node!.value) } node = node!.next } return result } } extension List { public subscript(_ index: Int) -> T { let n = node(at: index) return n.value } } extension List: CustomStringConvertible { public var description: String { var s = "[" var node = lead while node != nil { s += "\(node!.value)" node = node!.next if node != nil { s += ", " } } return s + "]" } } extension List { convenience init(array: Array<T>) { self.init() for element in array { self.append(value: element) } } } extension List: ExpressibleByArrayLiteral { public convenience init(arrayLiteral elements: T...) { self.init() for element in elements { self.append(value: element) } } } //: TEST var list = List<Int>() list.isEmpty //list.node(at: 0).value //list.remove(at: 0) list.insert(value: -1, at: 0).value list.remove(at: 0).value list.insert(value: -2, at: 0).value list.append(value: 0).next?.value list.append(value: 1).previous?.value list.append(value: 2).previous?.value list.count list.lead?.value list.tail?.value list.node(at: 1).value //list.node(at: 3).value list.insert(value: 3, at: 3) var array: List = ["A", "B", "C", "D"] array.reverse() let map = array.map { $0.characters.count } map let filter = array.filter { $0 > "B" } filter //: [Contents](Contents) | [Previous](@previous) | [Next](@next)
mit
4e7052fc7ac3783c4d6152602e9dbd6e
20.968254
64
0.477962
4.265023
false
false
false
false
WeirdMath/SwiftyHaru
Demo/Demo.playground/Sources/ViewConfiguration.swift
1
1797
import Quartz import PlaygroundSupport import SwiftyHaru public extension SwiftyHaru.PDFDocument { public func display() { let view = PDFView(frame: NSRect(x: 0, y: 0, width: 480, height: 640)) view.document = Quartz.PDFDocument(data: getData()) view.scaleFactor = 0.75 PlaygroundPage.current.liveView = view } } /// Concatenates the sequences. /// /// - parameter lhs: The base sequence. /// - parameter rhs: The sequence to concatenate to the base sequence. /// /// - returns: A new sequence constructed by concatenating the two sequences. public func +<LHS: Sequence, RHS: Sequence>(lhs: LHS, rhs: RHS) -> AnySequence<LHS.Element> where LHS.Element == RHS.Element { var lhsIterator = lhs.makeIterator() var rhsIterator = rhs.makeIterator() return AnySequence { return AnyIterator { lhsIterator.next() ?? rhsIterator.next() } } } extension Sequence { /// Appends the new element to the beginning of the sequence. /// /// - parameter lhs: The element to append. /// - parameter rhs: The base sequence. /// /// - returns: A new sequence constructed by appending the new element to the beginning of the base sequence. public static func + (lhs: Element, rhs: Self) -> AnySequence<Element> { return CollectionOfOne(lhs) + rhs } /// Appends the new element to the end of the sequence. /// /// - parameter lhs: The base sequence. /// - parameter rhs: The element to append. /// /// - returns: A new sequence constructed by appending the new element to the end of the base sequence. public static func + (lhs: Self, rhs: Element) -> AnySequence<Element> { return lhs + CollectionOfOne(rhs) } }
mit
b2e35e7156bb7b861d6b7d75fb93023d
29.457627
113
0.643294
4.393643
false
false
false
false
morbrian/udacity-nano-onthemap
OnTheMap/Logger.swift
1
2063
// // Logger.swift // OnTheMap // // Created by Brian Moriarty on 4/22/15. // Copyright (c) 2015 Brian Moriarty. All rights reserved. // import Foundation // Logger // Helper class for logging during development. // Provides file name and line nuber to provide context to the log messages. public class Logger { // supported log levels // currently only changes the tag in log message. // DEBUG = low-level step-through messages to help troubleshoot during development. // INFO = messages about significant events or transitions during development. // ERROR = unexpected issues or misbehavior to call out during development. enum LogLevel: CustomStringConvertible { case Debug case Info case Error var description: String { switch self { case Debug: return "DEBUG" case Info: return "INFO" case Error: return "ERROR" } } } // output the log information in a predefined format static private func outputMessage(message: String, file: String, line: Int, function: String, level: LogLevel) { print("[\(level)][\((file as NSString).lastPathComponent):\(line)][\(function)][\(message)]") } // print debug level messages static public func debug(message: String, file: String = __FILE__, line: Int = __LINE__, function: String = __FUNCTION__) { outputMessage(message, file: file, line: line, function: function, level: LogLevel.Debug) } //print info level messages static public func info(message: String, file: String = __FILE__, line: Int = __LINE__, function: String = __FUNCTION__) { outputMessage(message, file: file, line: line, function: function, level: LogLevel.Info) } // print error level messages static public func error(message: String, file: String = __FILE__, line: Int = __LINE__, function: String = __FUNCTION__) { outputMessage(message, file: file, line: line, function: function, level: LogLevel.Error) } }
mit
d54e5f4b9071ab0d6a119b39fe1ee2fc
37.943396
127
0.646146
4.494553
false
false
false
false
zhiquan911/SwiftChatKit
Pod/Classes/extention/String+extension.swift
1
1072
// // String+extension.swift // SwiftChatKit // // Created by 麦志泉 on 15/9/4. // Copyright (c) 2015年 CocoaPods. All rights reserved. // import Foundation extension String { /// 字符串长度 var length: Int { return self.characters.count; } // Swift 1.2 /** 计算文字的高度 - parameter font: - parameter size: - returns: */ func textSizeWithFont(font: UIFont, constrainedToSize size:CGSize) -> CGSize { var textSize:CGSize! let newStr = NSString(string: self) if CGSizeEqualToSize(size, CGSizeZero) { let attributes = [NSFontAttributeName: font] textSize = newStr.sizeWithAttributes(attributes) } else { let option = NSStringDrawingOptions.UsesLineFragmentOrigin let attributes = [NSFontAttributeName: font] let stringRect = newStr.boundingRectWithSize(size, options: option, attributes: attributes, context: nil) textSize = stringRect.size } return textSize } }
mit
70068c93a3deb7eaed9931ec974260a8
25.025
117
0.619231
4.663677
false
false
false
false
danielsaidi/Vandelay
VandelayDemo/ViewController+Import.swift
1
4159
// // ViewController+Import.swift // VandelayExample // // Created by Daniel Saidi on 2018-09-16. // Copyright © 2018 Daniel Saidi. All rights reserved. // import UIKit import Vandelay // import VandelayDropbox // import VandelayQr extension ViewController { func importPhotoAlbum() { let title = "Import photo album" let message = "How do you want to import this data?" let alert = UIAlertController(title: title, message: message, preferredStyle: .actionSheet) alert.addAction(importPhotoAlbumAction(for: FileImporter(fileName: photoFile), title: "From a local file")) alert.addAction(importPhotoAlbumAction(for: UrlImporter(url: photoUrl), title: "From a local file URL")) alert.addAction(importWithEmailImporterAction(title: "From an e-mail attachment")) // alert.addAction(importPhotoAlbumAction(for: QrCodeImporter(fromViewController: self), title: "By scanning a QR code")) // alert.addAction(importPhotoAlbumAction(for: DropboxImporter(fromViewController: self, fileName: photoFile), title: "From a Dropbox file")) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) present(alert, animated: true, completion: nil) } func importPhotoAlbum(with importer: DataImporter) { importer.importData { [weak self] result in self?.alertImportResult(result) guard let data = result.data else { return } let photos = try? JSONDecoder().decode([Photo].self, from: data) self?.photoRepository.add(photos ?? []) self?.reloadData() } } func importTodoList() { let title = "Import todo list" let message = "How do you want to import this data?" let alert = UIAlertController(title: title, message: message, preferredStyle: .actionSheet) alert.addAction(importTodoListAction(for: PasteboardImporter(), title: "From the pasteboard")) alert.addAction(importTodoListAction(for: FileImporter(fileName: photoFile), title: "From a local file")) alert.addAction(importTodoListAction(for: UrlImporter(url: photoUrl), title: "From a local file URL")) alert.addAction(importWithEmailImporterAction(title: "From an e-mail attachment")) // alert.addAction(importTodoListAction(for: QrCodeImporter(fromViewController: self), title: "By scanning a QR code")) // alert.addAction(importTodoListAction(for: DropboxImporter(fromViewController: self, fileName: photoFile), title: "From a Dropbox file")) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) present(alert, animated: true, completion: nil) } func importTodoList(with importer: StringImporter) { importer.importString { [weak self] result in self?.alertImportResult(result) guard let string = result.string else { return } guard let data = string.data(using: .utf8) else { return } let items = try? JSONDecoder().decode([TodoItem].self, from: data) self?.todoItemRepository.add(items ?? []) self?.reloadData() } } } // MARK: - Import functions private extension ViewController { func importPhotoAlbumAction(for importer: DataImporter, title: String) -> UIAlertAction { let action = { [weak self] importer in self?.importPhotoAlbum(with: importer)} return UIAlertAction(title: title, style: .default) { _ in action(importer) } } func importTodoListAction(for importer: StringImporter, title: String) -> UIAlertAction { let action = { [weak self] importer in self?.importTodoList(with: importer)} return UIAlertAction(title: title, style: .default) { _ in action(importer) } } func importWithEmailImporterAction(title: String) -> UIAlertAction { UIAlertAction(title: title, style: .default) { _ in self.alert(title: "Import external file", message: "You can try this by exporting data from this app to an e-mail, then tap the attached .vdl file and share it back to this app.") } } }
mit
0b4262031c3050637b7936d861153710
48.5
191
0.678211
4.437567
false
false
false
false
xsin/HiSwift
HiSwift/HiSwift/IconFontViewController.swift
1
1662
// // IconFontController.swift // LVHelloToIOS // // Created by Levin Wong on 9/30/14. // Copyright (c) 2014 Levin Wong. All rights reserved. // import UIKit class IconFontViewController: UIViewController { @IBOutlet weak var sliderFlat: UISlider! @IBOutlet weak var sliderSize: UISlider! @IBOutlet weak var sliderColor: UISlider! @IBOutlet weak var stageIcon: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. stageIcon.font = UIFont(name:"fontello",size:130) stageIcon.text = NSString.stringWithUTF8String("\u{e801}") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func morphChanged(sender: AnyObject) { stageIcon.shadowColor = UIColor.grayColor() stageIcon.shadowOffset = CGSizeMake(1,CGFloat(sliderFlat.value)) } @IBAction func colorChanged(sender: AnyObject) { var val = sliderColor.value if (val == 0.0) { stageIcon.textColor = UIColor.blackColor() } else { //stageIcon.textColor = [UIColor colorWithHue: value saturation: 0.8 brightness: 0.9 alpha: 1.0]; stageIcon.textColor = UIColor(hue: CGFloat(val), saturation: CGFloat(0.8), brightness: CGFloat(0.9), alpha: CGFloat(1.0)) } } @IBAction func sizeChanged(sender: AnyObject) { var size = sliderSize.value stageIcon.font = UIFont(name:"fontello",size:CGFloat(size) ) } }
mit
0369da8b4fece9bd4af2d7fc89e02ea2
32.26
133
0.644404
4.207595
false
false
false
false
clowwindy/firefox-ios
Sync/Bytes.swift
2
1468
/* 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 /** * Utilities for futzing with bytes and such. */ public class Bytes { public class func generateRandomBytes(len: UInt) -> NSData { let len = Int(len) let data: NSMutableData! = NSMutableData(length: len) let bytes = UnsafeMutablePointer<UInt8>(data.mutableBytes) let result: Int32 = SecRandomCopyBytes(kSecRandomDefault, len, bytes) assert(result == 0, "Random byte generation failed."); return data } public class func generateGUID() -> String { return generateRandomBytes(9).base64EncodedStringWithOptions(NSDataBase64EncodingOptions.allZeros) } public class func decodeBase64(b64: String) -> NSData { return NSData(base64EncodedString: b64, options: NSDataBase64DecodingOptions.allZeros)! } /** * Turn a string of base64 characters into an NSData *without decoding*. * This is to allow HMAC to be computed of the raw base64 string. */ public class func dataFromBase64(b64: String) -> NSData? { return b64.dataUsingEncoding(NSASCIIStringEncoding, allowLossyConversion: false) } func fromHex(str: String) -> NSData { // TODO return NSData() } }
mpl-2.0
97114774ed0ddd623a69a7db075821c5
33.97619
106
0.662807
4.573209
false
false
false
false
allenlinli/Wildlife-League
Wildlife League/MaskMaker.swift
1
1374
// // MaskMaker.swift // Wildlife League // // Created by allenlin on 7/17/14. // Copyright (c) 2014 Raccoonism. All rights reserved. // import Foundation class MaskMaker { class func beedCrossMask(beed :Beed) -> Set<Coordinate>{ var coor = Coordinate(beed: beed) return self.coordinateCrossMaskAtCoordinate(coor) } class func coordinateCrossMaskAtCoordinate (coor :Coordinate) -> Set<Coordinate>{ var maskDiffTupleSet = [(0,1),(0,-1),(1,0),(-1,0),(0,0)] var maskSet = Set<Coordinate>() for tuple in maskDiffTupleSet { var (inDiffX, inDiffY) = tuple var tempCoor = Coordinate(x: coor.x + inDiffX, y: coor.y + inDiffY) if (tempCoor.x>=0 && tempCoor.x < NumColumns && tempCoor.y >= 0 && tempCoor.y < NumRows){ maskSet.addElement(tempCoor) } } return maskSet } class func crossMaskSetOfCoordinateSet (set :Set<Coordinate>) -> Set<Coordinate> { var maskSet = Set<Coordinate>() for coor in set { maskSet.union(self.coordinateCrossMaskAtCoordinate(coor)) } return maskSet } class func crossMaskSetOfChain (chain :Chain) -> Set<Coordinate> { return self.crossMaskSetOfCoordinateSet(Coordinate.turnChainToCoordinateSet(chain)) } }
apache-2.0
30fb9642414ac5bfd3d552a73523a000
30.25
101
0.608443
3.693548
false
false
false
false
borjaIgartua/todo
TodoApp/TasksInteractor.swift
1
3033
// // TasksInteractor.swift // TodoApp // // Created by Borja Igartua Pastor on 24/5/17. // Copyright © 2017 Borja Igartua Pastor. All rights reserved. // import DispatchIntrospection import Foundation class TaskInteractor { typealias UpdateClosure = ([Task]?) -> () var updateHandler: UpdateClosure? var tasks: [Task]? init() { /* //To Post a notification NotificationCenter.default.post(name: notificationName, object: nil) extension Notification.Name { static let yourCustomNotificationName = Notification.Name("yourCustomNotificationName") } */ NotificationCenter.default.addObserver(self, selector: #selector(TaskInteractor.storeTaskInPersistance), name: Notification.Name.UIApplicationWillResignActive, object: nil) } deinit { NotificationCenter.default.removeObserver(self, name: Notification.Name.UIApplicationWillResignActive, object: nil); } func retrieveTasks(updateHandler: @escaping UpdateClosure) { self.updateHandler = updateHandler self.getTasksFromServer() self.updateHandler?(getTaskFromPersistence()) } private func getTaskFromPersistence() -> [Task]? { guard let data = UserDefaults.standard.data(forKey: "tasks_key") else { return nil } let tasks = NSKeyedUnarchiver.unarchiveObject(with: data) as? [Task] return tasks } private func getTasksFromServer() { NetworkManager.shared.GET(urlString: NetworkConstants.TASKS_OPERATION, successHandler: { (json) in if let dic = json as? [Any] { let tasks = dic.map({ (taskDic) -> Task? in return Task(taskDic as! [String: Any]) }) DispatchQueue.main.async { self.updateHandler?(tasks as? [Task]) } self.safeTaskInPersistance(tasks: tasks as? [Task]) } }) { (error) in print(error) //TODO: show error } } private func safeTaskInPersistance(tasks: [Task]?) { if let tasks = tasks, tasks.count > 0 { let data = NSKeyedArchiver.archivedData(withRootObject: tasks) UserDefaults.standard.setValue(data, forKey: "tasks_key") UserDefaults.standard.synchronize() } } @objc private func storeTaskInPersistance() { self.safeTaskInPersistance(tasks: self.tasks) } }
apache-2.0
928af531f5af47347dbdef15d9ae5aff
30.915789
124
0.515172
5.635688
false
false
false
false
fluidsonic/JetPack
Sources/UI/ScrollViewController.swift
1
20391
import UIKit @objc(JetPack_ScrollViewController) open class ScrollViewController: ViewController { // TODO rename public typealias ScrollCompletion = (_ cancelled: Bool) -> Void fileprivate lazy var childContainer = View() fileprivate lazy var delegateProxy: DelegateProxy = DelegateProxy(scrollViewController: self) fileprivate var ignoresScrollViewDidScroll = 0 fileprivate var isSettingPrimaryViewControllerInternally = false fileprivate var lastLayoutedScrollViewInsets = UIEdgeInsets.zero fileprivate var lastLayoutedScrollViewInsetsForChildren = UIEdgeInsets.zero fileprivate var lastLayoutedScrollViewSizeForChildren = CGSize.zero fileprivate var lastLayoutedSizeForChildren = CGSize.zero fileprivate var lastLayoutedSize = CGSize.zero fileprivate var reusableChildView: ChildView? fileprivate var scrollCompletion: ScrollCompletion? fileprivate var viewControllersNotYetMovedToParentViewController = [UIViewController]() public fileprivate(set) final var isInScrollingAnimation = false public override init() { super.init() } public required init?(coder: NSCoder) { super.init(coder: coder) } fileprivate func childViewForIndex(_ index: Int) -> ChildView? { guard isViewLoaded else { return nil } for subview in childContainer.subviews { guard let childView = subview as? ChildView, childView.index == index else { continue } return childView } return nil } fileprivate func childViewForViewController(_ viewController: UIViewController) -> ChildView? { guard isViewLoaded else { return nil } for subview in childContainer.subviews { guard let childView = subview as? ChildView, childView.viewController === viewController else { continue } return childView } return nil } fileprivate func createScrollView() -> UIScrollView { let child = SpecialScrollView() child.bounces = false child.canCancelContentTouches = true child.contentInsetAdjustmentBehavior = .automatic child.delaysContentTouches = true child.delegate = self.delegateProxy child.isPagingEnabled = true child.scrollsToTop = false child.showsHorizontalScrollIndicator = false child.showsVerticalScrollIndicator = false return child } open var currentIndex: CGFloat { let scrollViewWidth = scrollView.bounds.width if isViewLoaded && scrollViewWidth > 0 { return scrollView.contentOffset.left / scrollViewWidth } else if let primaryViewController = primaryViewController, let index = viewControllers.indexOfIdentical(primaryViewController) { return CGFloat(index) } else { return 0 } } open func didEndDecelerating() { // override in subclasses } open func didEndDragging(willDecelerate: Bool) { // override in subclasses } open func didScroll() { // override in subclasses } fileprivate var isInTransition: Bool { return appearState == .willAppear || appearState == .willDisappear || isInScrollingAnimation || scrollView.isTracking || scrollView.isDecelerating } fileprivate func layoutChildContainer() { ignoresScrollViewDidScroll += 1 defer { ignoresScrollViewDidScroll -= 1 } let scrollViewFrame = CGRect(size: view.bounds.size).inset(by: scrollViewInsets) let contentSize = CGSize(width: CGFloat(viewControllers.count) * scrollViewFrame.width, height: scrollViewFrame.height) let contentOffset = scrollView.contentOffset scrollView.frame = scrollViewFrame childContainer.frame = CGRect(size: contentSize) scrollView.contentSize = contentSize scrollView.contentOffset = contentOffset } fileprivate func layoutChildView(_ childView: ChildView) { guard childView.index >= 0 else { return } let containerSize = scrollView.bounds.size var childViewFrame = CGRect() childViewFrame.left = CGFloat(childView.index) * containerSize.width childViewFrame.size = containerSize childView.frame = childViewFrame } fileprivate func layoutChildrenForcingLayoutUpdate(_ forcesLayoutUpdate: Bool) { ignoresScrollViewDidScroll += 1 defer { ignoresScrollViewDidScroll -= 1 } let viewControllers = self.viewControllers let viewSize = view.bounds.size let scrollViewInsets = self.scrollViewInsets var scrollViewSize = self.scrollView.bounds.size var contentOffset: CGPoint let layoutsExistingChildren: Bool let previousScrollViewSize = lastLayoutedScrollViewSizeForChildren if forcesLayoutUpdate || scrollViewSize != previousScrollViewSize || scrollViewInsets != lastLayoutedScrollViewInsetsForChildren || viewSize != lastLayoutedSizeForChildren { lastLayoutedScrollViewInsetsForChildren = scrollViewInsets lastLayoutedSizeForChildren = viewSize layoutChildContainer() scrollViewSize = self.scrollView.bounds.size lastLayoutedScrollViewSizeForChildren = scrollViewSize contentOffset = scrollView.contentOffset var newContentOffset = contentOffset if viewControllers.count > 1 { var closestChildIndex: Int? var closestChildOffset = CGFloat(0) var closestDistanceToHorizontalCenter = CGFloat.greatestFiniteMagnitude if !previousScrollViewSize.isEmpty { let previousHorizontalCenter = contentOffset.left + (previousScrollViewSize.width / 2) for subview in childContainer.subviews { guard let childView = subview as? ChildView, childView.index >= 0 else { continue } let childViewFrame = childView.frame let distanceToHorizontalCenter = min((previousHorizontalCenter - childViewFrame.left).absolute, (previousHorizontalCenter - childViewFrame.right).absolute) guard distanceToHorizontalCenter < closestDistanceToHorizontalCenter else { continue } closestChildIndex = childView.index closestChildOffset = (childViewFrame.left - contentOffset.left) / previousScrollViewSize.width closestDistanceToHorizontalCenter = distanceToHorizontalCenter } } if let closestChildIndex = closestChildIndex { newContentOffset = CGPoint(left: (CGFloat(closestChildIndex) - closestChildOffset) * scrollViewSize.width, top: 0) } else if let primaryViewController = primaryViewController, let index = viewControllers.indexOfIdentical(primaryViewController) { newContentOffset = CGPoint(left: (CGFloat(index) * scrollViewSize.width), top: 0) } } newContentOffset = newContentOffset.coerced(atLeast: scrollView.minimumContentOffset, atMost: scrollView.maximumContentOffset) if newContentOffset != contentOffset { scrollView.contentOffset = newContentOffset contentOffset = newContentOffset } layoutsExistingChildren = true } else { contentOffset = scrollView.contentOffset layoutsExistingChildren = false } let visibleIndexes: CountableRange<Int> if viewControllers.isEmpty || scrollViewSize.isEmpty { visibleIndexes = 0 ..< 0 } else { let floatingIndex = contentOffset.left / scrollViewSize.width visibleIndexes = Int(floatingIndex.rounded(.down)).coerced(in: 0 ... (viewControllers.count - 1)) ..< (Int(floatingIndex.rounded(.up)).coerced(in: 0 ... (viewControllers.count - 1)) + 1) } for subview in childContainer.subviews { guard let childView = subview as? ChildView, !visibleIndexes.contains(childView.index) else { continue } updateChildView(childView, withPreferredAppearState: .willDisappear, animated: false) childView.removeFromSuperview() updateChildView(childView, withPreferredAppearState: .didDisappear, animated: false) childView.index = -1 childView.viewController = nil reusableChildView = childView } for index in visibleIndexes { if let childView = childViewForIndex(index) { if layoutsExistingChildren { layoutChildView(childView) } } else { let viewController = viewControllers[index] let childView = reusableChildView ?? ChildView() childView.index = index childView.viewController = viewController reusableChildView = nil layoutChildView(childView) updateChildView(childView, withPreferredAppearState: .willAppear, animated: false) childContainer.addSubview(childView) updateChildView(childView, withPreferredAppearState: .didAppear, animated: false) } } } open var primaryViewController: UIViewController? { didSet { if isSettingPrimaryViewControllerInternally { return } guard let primaryViewController = primaryViewController else { fatalError("Cannot set primaryViewController to nil") } scrollToViewController(primaryViewController, animated: false) } } open func scrollToViewController(_ viewController: UIViewController, animated: Bool = true, completion: ScrollCompletion? = nil) { guard let index = viewControllers.indexOfIdentical(viewController) else { fatalError("Cannot scroll to view controller \(viewController) which is not a child view controller") } if viewController != primaryViewController { isSettingPrimaryViewControllerInternally = true primaryViewController = viewController isSettingPrimaryViewControllerInternally = false } if isViewLoaded { let previousScrollCompletion = self.scrollCompletion scrollCompletion = completion scrollView.setContentOffset(CGPoint(left: CGFloat(index) * scrollView.bounds.width, top: 0), animated: animated) previousScrollCompletion?(true) } } public fileprivate(set) final lazy var scrollView: UIScrollView = self.createScrollView() public var scrollViewInsets = UIEdgeInsets.zero { didSet { guard scrollViewInsets != oldValue else { return } if isViewLoaded { view.setNeedsLayout() } } } open override var shouldAutomaticallyForwardAppearanceMethods : Bool { return false } fileprivate func updateAppearStateForAllChildrenAnimated(_ animated: Bool) { for subview in childContainer.subviews { guard let childView = subview as? ChildView else { continue } updateChildView(childView, withPreferredAppearState: appearState, animated: animated) } } fileprivate func updateChildView(_ childView: ChildView, withPreferredAppearState preferredAppearState: AppearState, animated: Bool) { guard let viewController = childView.viewController else { return } var targetAppearState = min(preferredAppearState, appearState) if isInTransition && targetAppearState != .didDisappear { switch childView.appearState { case .didDisappear: targetAppearState = .willAppear case .willAppear: return case .didAppear: targetAppearState = .willDisappear case .willDisappear: return } } childView.updateAppearState(targetAppearState, animated: animated) if targetAppearState == .didAppear, let index = viewControllersNotYetMovedToParentViewController.indexOfIdentical(viewController) { viewControllersNotYetMovedToParentViewController.remove(at: index) onMainQueue { // perform one cycle later since the child may not yet have completed the transitions in this cycle if viewController.containmentState == .willMoveToParent { viewController.didMove(toParent: self) } } } } fileprivate func updatePrimaryViewController() { guard isViewLoaded else { return } var mostVisibleViewController: UIViewController? var mostVisibleWidth = CGFloat.leastNormalMagnitude let scrollViewFrame = scrollView.frame for subview in childContainer.subviews { guard let childView = subview as? ChildView else { continue } let childFrameInView = childView.convert(childView.bounds, to: view) let intersection = childFrameInView.intersection(scrollViewFrame) guard !intersection.isNull else { continue } if intersection.width > mostVisibleWidth { mostVisibleViewController = childView.viewController mostVisibleWidth = intersection.width } } guard mostVisibleViewController != primaryViewController else { return } isSettingPrimaryViewControllerInternally = true primaryViewController = mostVisibleViewController isSettingPrimaryViewControllerInternally = false } open var viewControllers = [UIViewController]() { didSet { guard viewControllers != oldValue else { return } ignoresScrollViewDidScroll += 1 defer { ignoresScrollViewDidScroll -= 1 } var removedViewControllers = [UIViewController]() for viewController in oldValue where viewController.parent === self && !viewControllers.containsIdentical(viewController) { viewController.willMove(toParent: nil) childViewForViewController(viewController)?.index = -1 removedViewControllers.append(viewController) viewControllersNotYetMovedToParentViewController.removeFirstIdentical(viewController) } for index in 0 ..< viewControllers.count { let viewController = viewControllers[index] if viewController.parent !== self { addChild(viewController) viewControllersNotYetMovedToParentViewController.append(viewController) } else { childViewForViewController(viewController)?.index = index } } if isViewLoaded { layoutChildrenForcingLayoutUpdate(true) updatePrimaryViewController() } else { if let primaryViewController = primaryViewController, viewControllers.containsIdentical(primaryViewController) { // primaryViewController still valid } else { primaryViewController = viewControllers.first } } for viewController in removedViewControllers { viewController.removeFromParent() } } } open override func viewDidLayoutSubviewsWithAnimation(_ animation: Animation?) { super.viewDidLayoutSubviewsWithAnimation(animation) let bounds = view.bounds let scrollViewInsets = self.scrollViewInsets guard bounds.size != lastLayoutedSize || scrollViewInsets != lastLayoutedScrollViewInsets else { return } lastLayoutedSize = bounds.size lastLayoutedScrollViewInsets = scrollViewInsets layoutChildrenForcingLayoutUpdate(false) updatePrimaryViewController() } open override func viewDidLoad() { super.viewDidLoad() scrollView.addSubview(childContainer) view.addSubview(scrollView) } open override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) updateAppearStateForAllChildrenAnimated(animated) } open override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) updateAppearStateForAllChildrenAnimated(animated) } open override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) updateAppearStateForAllChildrenAnimated(animated) } open override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) updateAppearStateForAllChildrenAnimated(animated) } open func willBeginDragging() { // override in subclasses } } private final class DelegateProxy: NSObject { fileprivate unowned let scrollViewController: ScrollViewController fileprivate init(scrollViewController: ScrollViewController) { self.scrollViewController = scrollViewController } } extension DelegateProxy: UIScrollViewDelegate { @objc fileprivate func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { let scrollViewController = self.scrollViewController scrollViewController.updateAppearStateForAllChildrenAnimated(true) scrollViewController.didEndDecelerating() } @objc fileprivate func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) { let scrollViewController = self.scrollViewController scrollViewController.isInScrollingAnimation = false scrollViewController.updateAppearStateForAllChildrenAnimated(true) scrollViewController.updatePrimaryViewController() let scrollCompletion = scrollViewController.scrollCompletion scrollViewController.scrollCompletion = nil // TODO not called when scrolling was not necessary scrollCompletion?(false) } @objc fileprivate func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { let scrollViewController = self.scrollViewController scrollViewController.isInScrollingAnimation = false if decelerate { scrollViewController.didEndDragging(willDecelerate: true) } else { onMainQueue { // loop one cycle because UIScrollView did not yet update .tracking scrollViewController.updateAppearStateForAllChildrenAnimated(true) scrollViewController.updatePrimaryViewController() scrollViewController.didEndDragging(willDecelerate: false) } } } @objc fileprivate func scrollViewDidScroll(_ scrollView: UIScrollView) { let scrollViewController = self.scrollViewController guard scrollViewController.ignoresScrollViewDidScroll == 0 else { return } scrollViewController.layoutChildrenForcingLayoutUpdate(false) if scrollView.isTracking || scrollView.isDecelerating { scrollViewController.updatePrimaryViewController() } scrollViewController.didScroll() } @objc fileprivate func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { let scrollViewController = self.scrollViewController scrollViewController.isInScrollingAnimation = false let scrollCompletion = scrollViewController.scrollCompletion scrollViewController.scrollCompletion = nil scrollViewController.updateAppearStateForAllChildrenAnimated(true) scrollCompletion?(true) scrollViewController.willBeginDragging() } @objc fileprivate func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { scrollViewController.isInScrollingAnimation = false } } private final class ChildView: View { fileprivate var appearState = ViewController.AppearState.didDisappear fileprivate var index = -1 fileprivate override func layoutSubviews() { super.layoutSubviews() guard let viewControllerView = viewController?.view else { return } let bounds = self.bounds viewControllerView.bounds = CGRect(size: bounds.size) viewControllerView.center = bounds.center } fileprivate func updateAppearState(_ appearState: ViewController.AppearState, animated: Bool) { let oldAppearState = self.appearState guard appearState != oldAppearState else { return } self.appearState = appearState guard let viewController = self.viewController else { return } switch appearState { case .didDisappear: switch oldAppearState { case .didDisappear: break case .willAppear, .didAppear: viewController.beginAppearanceTransition(false, animated: animated) fallthrough case .willDisappear: viewController.view.removeFromSuperview() viewController.endAppearanceTransition() } case .willAppear: switch oldAppearState { case .didAppear, .willAppear: break case .willDisappear, .didDisappear: viewController.beginAppearanceTransition(true, animated: animated) addSubview(viewController.view) if window != nil { layoutIfNeeded() } } case .willDisappear: switch oldAppearState { case .didDisappear, .willDisappear: break case .willAppear, .didAppear: viewController.beginAppearanceTransition(false, animated: animated) } case .didAppear: assert(window != nil) switch oldAppearState { case .didAppear: break case .didDisappear, .willDisappear: viewController.beginAppearanceTransition(true, animated: animated) addSubview(viewController.view) fallthrough case .willAppear: layoutIfNeeded() viewController.endAppearanceTransition() } } } fileprivate var viewController: UIViewController? { didSet { precondition((viewController != nil) != (oldValue != nil)) } } } private class SpecialScrollView: ScrollView { fileprivate override func setContentOffset(_ contentOffset: CGPoint, animated: Bool) { let willBeginAnimation = animated && contentOffset != self.contentOffset super.setContentOffset(contentOffset, animated: animated) if willBeginAnimation, let delegate = delegate as? DelegateProxy { delegate.scrollViewController.isInScrollingAnimation = true } } } private func min(_ a: ViewController.AppearState, _ b: ViewController.AppearState) -> ViewController.AppearState { switch a { case .didAppear: return b case .willAppear: switch b { case .didAppear: return a default: return b } case .willDisappear: switch b { case .didAppear, .willAppear: return a default: return b } case .didDisappear: return a } }
mit
db3d35fea89025c9032e40400ae427a6
25.759843
161
0.767103
4.927743
false
false
false
false
skedgo/tripkit-ios
Tests/TripKitUITests/vendor/RxTest/ColdObservable.swift
8
1529
// // ColdObservable.swift // RxTest // // Created by Krunoslav Zaher on 3/14/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import RxSwift /// A representation of cold observable sequence. /// /// Recorded events are replayed after subscription once per subscriber. /// /// Event times represent relative offset to subscription time. final class ColdObservable<Element> : TestableObservable<Element> { override init(testScheduler: TestScheduler, recordedEvents: [Recorded<Event<Element>>]) { super.init(testScheduler: testScheduler, recordedEvents: recordedEvents) } /// Subscribes `observer` to receive events for this sequence. override func subscribe<Observer: ObserverType>(_ observer: Observer) -> Disposable where Observer.Element == Element { self.subscriptions.append(Subscription(self.testScheduler.clock)) let i = self.subscriptions.count - 1 var disposed = false for recordedEvent in self.recordedEvents { _ = self.testScheduler.scheduleRelativeVirtual((), dueTime: recordedEvent.time, action: { _ in if !disposed { observer.on(recordedEvent.value) } return Disposables.create() }) } return Disposables.create { disposed = true let existing = self.subscriptions[i] self.subscriptions[i] = Subscription(existing.subscribe, self.testScheduler.clock) } } }
apache-2.0
0408dc1fff9a199243c0b1fc88d005f1
32.217391
123
0.651832
4.913183
false
true
false
false
ScoutHarris/WordPress-iOS
WordPress/Classes/ViewRelated/Me/GravatarPickerViewController.swift
2
4194
import Foundation import WPMediaPicker import WordPressShared import Photos // Encapsulates all of the interactions required to capture a new Gravatar image, and resize it. // class GravatarPickerViewController: UIViewController, WPMediaPickerViewControllerDelegate { // MARK: - Public Properties var onCompletion: ((UIImage?) -> Void)? // MARK: - Private Properties fileprivate var mediaPickerViewController: WPNavigationMediaPickerViewController! fileprivate lazy var mediaPickerAssetDataSource: WPPHAssetDataSource? = { let collectionsFetchResult = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: .smartAlbumSelfPortraits, options: nil) guard let assetCollection = collectionsFetchResult.firstObject else { return nil } let dataSource = WPPHAssetDataSource() dataSource.setSelectedGroup(PHAssetCollectionForWPMediaGroup(collection: assetCollection, mediaType: .image)) return dataSource }() // MARK: - View Lifecycle Methods override func viewDidLoad() { super.viewDidLoad() setupChildrenViewControllers() } // MARK: - WPMediaPickerViewControllerDelegate func mediaPickerController(_ picker: WPMediaPickerViewController, shouldShow asset: WPMediaAsset) -> Bool { return asset.isKind(of: PHAsset.self) } func mediaPickerController(_ picker: WPMediaPickerViewController, didFinishPicking assets: [WPMediaAsset]) { // Export the UIImage Asset guard let asset = assets.first as? PHAsset else { onCompletion?(nil) return } asset.exportMaximumSizeImage { (image, info) in guard let rawGravatar = image else { self.onCompletion?(nil) return } // Track WPAppAnalytics.track(.gravatarCropped) // Proceed Cropping let imageCropViewController = self.newImageCropViewController(rawGravatar) self.mediaPickerViewController.show(after: imageCropViewController) } } func mediaPickerControllerDidCancel(_ picker: WPMediaPickerViewController) { onCompletion?(nil) } // MARK: - Private Methods // Instantiates a new MediaPickerViewController, and sets it up as a children ViewController. // fileprivate func setupChildrenViewControllers() { let pickerViewController = newMediaPickerViewController() pickerViewController.willMove(toParentViewController: self) pickerViewController.view.bounds = view.bounds view.addSubview(pickerViewController.view) addChildViewController(pickerViewController) pickerViewController.didMove(toParentViewController: self) mediaPickerViewController = pickerViewController } // Returns a new WPMediaPickerViewController instance. // fileprivate func newMediaPickerViewController() -> WPNavigationMediaPickerViewController { let options = WPMediaPickerOptions() options.showMostRecentFirst = true options.filter = [.image] options.preferFrontCamera = true options.allowMultipleSelection = false let pickerViewController = WPNavigationMediaPickerViewController(options: options) pickerViewController.delegate = self pickerViewController.dataSource = mediaPickerAssetDataSource pickerViewController.startOnGroupSelector = false return pickerViewController } // Returns a new ImageCropViewController instance. // fileprivate func newImageCropViewController(_ rawGravatar: UIImage) -> ImageCropViewController { let imageCropViewController = ImageCropViewController(image: rawGravatar) imageCropViewController.onCompletion = { [weak self] image, _ in self?.onCompletion?(image) self?.dismiss(animated: true, completion: nil) } return imageCropViewController } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } override var childViewControllerForStatusBarStyle: UIViewController? { return nil } }
gpl-2.0
260412a7476f2ccdcaa57eced6d63649
33.661157
144
0.707201
6.069465
false
false
false
false
justindarc/firefox-ios
Client/Frontend/Browser/TopTabsViewController.swift
2
10280
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import Storage import WebKit struct TopTabsUX { static let TopTabsViewHeight: CGFloat = 44 static let TopTabsBackgroundShadowWidth: CGFloat = 12 static let TabWidth: CGFloat = 190 static let FaderPading: CGFloat = 8 static let SeparatorWidth: CGFloat = 1 static let HighlightLineWidth: CGFloat = 3 static let TabNudge: CGFloat = 1 // Nudge the favicon and close button by 1px static let TabTitlePadding: CGFloat = 10 static let AnimationSpeed: TimeInterval = 0.1 static let SeparatorYOffset: CGFloat = 7 static let SeparatorHeight: CGFloat = 32 } protocol TopTabsDelegate: AnyObject { func topTabsDidPressTabs() func topTabsDidPressNewTab(_ isPrivate: Bool) func topTabsDidTogglePrivateMode() func topTabsDidChangeTab() } class TopTabsViewController: UIViewController { let tabManager: TabManager weak var delegate: TopTabsDelegate? fileprivate var tabDisplayManager: TabDisplayManager! var tabCellIdentifer: TabDisplayer.TabCellIdentifer = TopTabCell.Identifier lazy var collectionView: UICollectionView = { let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: TopTabsViewLayout()) collectionView.register(TopTabCell.self, forCellWithReuseIdentifier: TopTabCell.Identifier) collectionView.showsVerticalScrollIndicator = false collectionView.showsHorizontalScrollIndicator = false collectionView.bounces = false collectionView.clipsToBounds = false collectionView.accessibilityIdentifier = "Top Tabs View" collectionView.semanticContentAttribute = .forceLeftToRight return collectionView }() fileprivate lazy var tabsButton: TabsButton = { let tabsButton = TabsButton.tabTrayButton() tabsButton.semanticContentAttribute = .forceLeftToRight tabsButton.addTarget(self, action: #selector(TopTabsViewController.tabsTrayTapped), for: .touchUpInside) tabsButton.accessibilityIdentifier = "TopTabsViewController.tabsButton" return tabsButton }() fileprivate lazy var newTab: UIButton = { let newTab = UIButton.newTabButton() newTab.semanticContentAttribute = .forceLeftToRight newTab.addTarget(self, action: #selector(TopTabsViewController.newTabTapped), for: .touchUpInside) newTab.accessibilityIdentifier = "TopTabsViewController.newTabButton" return newTab }() lazy var privateModeButton: PrivateModeButton = { let privateModeButton = PrivateModeButton() privateModeButton.semanticContentAttribute = .forceLeftToRight privateModeButton.accessibilityIdentifier = "TopTabsViewController.privateModeButton" privateModeButton.addTarget(self, action: #selector(TopTabsViewController.togglePrivateModeTapped), for: .touchUpInside) return privateModeButton }() fileprivate lazy var tabLayoutDelegate: TopTabsLayoutDelegate = { let delegate = TopTabsLayoutDelegate() delegate.tabSelectionDelegate = tabDisplayManager return delegate }() init(tabManager: TabManager) { self.tabManager = tabManager super.init(nibName: nil, bundle: nil) tabDisplayManager = TabDisplayManager(collectionView: self.collectionView, tabManager: self.tabManager, tabDisplayer: self, reuseID: TopTabCell.Identifier) collectionView.dataSource = tabDisplayManager collectionView.delegate = tabLayoutDelegate [UICollectionView.elementKindSectionHeader, UICollectionView.elementKindSectionFooter].forEach { collectionView.register(TopTabsHeaderFooter.self, forSupplementaryViewOfKind: $0, withReuseIdentifier: "HeaderFooter") } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) view.setNeedsLayout() view.layoutIfNeeded() tabDisplayManager.refreshStore(evenIfHidden: true) } deinit { tabManager.removeDelegate(self.tabDisplayManager) } override func viewDidLoad() { super.viewDidLoad() collectionView.dragDelegate = tabDisplayManager collectionView.dropDelegate = tabDisplayManager let topTabFader = TopTabFader() topTabFader.semanticContentAttribute = .forceLeftToRight view.addSubview(topTabFader) topTabFader.addSubview(collectionView) view.addSubview(tabsButton) view.addSubview(newTab) view.addSubview(privateModeButton) // Setup UIDropInteraction to handle dragging and dropping // links onto the "New Tab" button. let dropInteraction = UIDropInteraction(delegate: tabDisplayManager) newTab.addInteraction(dropInteraction) newTab.snp.makeConstraints { make in make.centerY.equalTo(view) make.trailing.equalTo(tabsButton.snp.leading) make.size.equalTo(view.snp.height) } tabsButton.snp.makeConstraints { make in make.centerY.equalTo(view) make.trailing.equalTo(view).offset(-10) make.size.equalTo(view.snp.height) } privateModeButton.snp.makeConstraints { make in make.centerY.equalTo(view) make.leading.equalTo(view).offset(10) make.size.equalTo(view.snp.height) } topTabFader.snp.makeConstraints { make in make.top.bottom.equalTo(view) make.leading.equalTo(privateModeButton.snp.trailing) make.trailing.equalTo(newTab.snp.leading) } collectionView.snp.makeConstraints { make in make.edges.equalTo(topTabFader) } tabsButton.applyTheme() applyUIMode(isPrivate: tabManager.selectedTab?.isPrivate ?? false) updateTabCount(tabDisplayManager.dataStore.count, animated: false) } func switchForegroundStatus(isInForeground reveal: Bool) { // Called when the app leaves the foreground to make sure no information is inadvertently revealed if let cells = self.collectionView.visibleCells as? [TopTabCell] { let alpha: CGFloat = reveal ? 1 : 0 for cell in cells { cell.titleText.alpha = alpha cell.favicon.alpha = alpha } } } func updateTabCount(_ count: Int, animated: Bool = true) { self.tabsButton.updateTabCount(count, animated: animated) } @objc func tabsTrayTapped() { delegate?.topTabsDidPressTabs() } @objc func newTabTapped() { self.delegate?.topTabsDidPressNewTab(self.tabDisplayManager.isPrivate) LeanPlumClient.shared.track(event: .openedNewTab, withParameters: ["Source": "Add tab button in the URL Bar on iPad"]) } @objc func togglePrivateModeTapped() { tabDisplayManager.togglePrivateMode(isOn: !tabDisplayManager.isPrivate, createTabOnEmptyPrivateMode: true) delegate?.topTabsDidTogglePrivateMode() self.privateModeButton.setSelected(tabDisplayManager.isPrivate, animated: true) } func scrollToCurrentTab(_ animated: Bool = true, centerCell: Bool = false) { assertIsMainThread("Only animate on the main thread") guard let currentTab = tabManager.selectedTab, let index = tabDisplayManager.dataStore.index(of: currentTab), !collectionView.frame.isEmpty else { return } if let frame = collectionView.layoutAttributesForItem(at: IndexPath(row: index, section: 0))?.frame { if centerCell { collectionView.scrollToItem(at: IndexPath(item: index, section: 0), at: .centeredHorizontally, animated: false) } else { // Padding is added to ensure the tab is completely visible (none of the tab is under the fader) let padFrame = frame.insetBy(dx: -(TopTabsUX.TopTabsBackgroundShadowWidth+TopTabsUX.FaderPading), dy: 0) if animated { UIView.animate(withDuration: TopTabsUX.AnimationSpeed, animations: { self.collectionView.scrollRectToVisible(padFrame, animated: true) }) } else { collectionView.scrollRectToVisible(padFrame, animated: false) } } } } } extension TopTabsViewController: TabDisplayer { func focusSelectedTab() { self.scrollToCurrentTab(true) } func cellFactory(for cell: UICollectionViewCell, using tab: Tab) -> UICollectionViewCell { guard let tabCell = cell as? TopTabCell else { return UICollectionViewCell() } tabCell.delegate = self let isSelected = (tab == tabManager.selectedTab) tabCell.configureWith(tab: tab, isSelected: isSelected) return tabCell } } extension TopTabsViewController: TopTabCellDelegate { func tabCellDidClose(_ cell: UICollectionViewCell) { tabDisplayManager.closeActionPerformed(forCell: cell) } } extension TopTabsViewController: Themeable, PrivateModeUI { func applyUIMode(isPrivate: Bool) { tabDisplayManager.togglePrivateMode(isOn: isPrivate, createTabOnEmptyPrivateMode: true) privateModeButton.onTint = UIColor.theme.topTabs.privateModeButtonOnTint privateModeButton.offTint = UIColor.theme.topTabs.privateModeButtonOffTint privateModeButton.applyUIMode(isPrivate: tabDisplayManager.isPrivate) } func applyTheme() { tabsButton.applyTheme() newTab.tintColor = UIColor.theme.topTabs.buttonTint view.backgroundColor = UIColor.theme.topTabs.background collectionView.backgroundColor = view.backgroundColor tabDisplayManager.refreshStore() } } // Functions for testing extension TopTabsViewController { func test_getDisplayManager() -> TabDisplayManager { assert(AppConstants.IsRunningTest) return tabDisplayManager } }
mpl-2.0
cb1e5eede5a8e87586c4e7dc4e209e3a
39
163
0.697763
5.427666
false
false
false
false
shajrawi/swift
test/IDE/print_property_wrappers.swift
1
951
// RUN: %empty-directory(%t) // Directly printing the type-checked AST // RUN: %target-swift-ide-test -print-ast-typechecked -source-filename %s | %FileCheck %s @_propertyWrapper struct Wrapper<Value> { var _stored: Value? var value: Value { get { return _stored! } set { _stored = newValue } } init() { self._stored = nil } init(initialValue: Value) { self._stored = initialValue } init(closure: () -> Value) { self._stored = closure() } } func foo() -> Int { return 17 } // CHECK: struct HasWrappers { struct HasWrappers { // CHECK: @Wrapper var x: Int { // CHECK-NEXT: get // CHECK: var $x: Wrapper<Int> @Wrapper(closure: foo) var x: Int @Wrapper var y = true @Wrapper var z: String // Memberwise initializer. // CHECK: init(x: Wrapper<Int> = Wrapper(closure: foo), y: Bool = true, z: String = Wrapper()) } func trigger() { _ = HasWrappers(y: false) }
apache-2.0
1b67179e50a76253fa9b4119bd16308d
16.290909
96
0.602524
3.325175
false
false
false
false
HabitRPG/habitrpg-ios
HabitRPG/UI/General/HallOfContributorsViewController.swift
1
1228
// // HallOfContributorsViewController.swift // Habitica // // Created by Phillip Thelen on 11.08.20. // Copyright © 2020 HabitRPG Inc. All rights reserved. // import Foundation import Habitica_Models class HallOfContributorsViewController: BaseTableViewController { private let dataSource = HallOfContributorsDataSource() private var selectedIndex: Int? override func viewDidLoad() { super.viewDidLoad() topHeaderCoordinator.hideHeader = true topHeaderCoordinator.followScrollView = false navigationItem.title = L10n.Titles.hallOfContributors dataSource.tableView = tableView } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let member = dataSource.item(at: indexPath) let navController = StoryboardScene.Social.userProfileNavController.instantiate() let profileViewControler = navController.topViewController as? UserProfileViewController profileViewControler?.username = member?.username profileViewControler?.userID = member?.id profileViewControler?.needsDoneButton = true present(navController, animated: true, completion: nil) } }
gpl-3.0
ba6b0bd02086304ff5e247c8dfa1e689
33.083333
96
0.728606
5.311688
false
false
false
false
advaita13/YouTubeFloatingPlayer
Source/YouTubeFloatingPlayer/Classes/CustomProgressSlider.swift
1
1347
// // CustomSlider.swift // YTDraggablePlayer // // Created by Ana Paula on 5/25/16. // Copyright © 2016 Ana Paula. All rights reserved. // import UIKit class CustomSlider: UISlider { override init (frame : CGRect) { super.init(frame : frame) } convenience init () { self.init(frame:CGRect.zero) setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } override func draw(_ rect: CGRect) { super.draw(rect) } func setup() { self.maximumTrackTintColor = UIColor.clear self.isContinuous = true } override func trackRect(forBounds bounds: CGRect) -> CGRect { var newBounds = super.trackRect(forBounds: bounds) newBounds.size.height = 6 return newBounds } } class CustomProgress: UIProgressView { override init (frame : CGRect) { super.init(frame : frame) } convenience init () { self.init(frame:CGRect.zero) setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } func setup() { self.layer.cornerRadius = 2.0 self.clipsToBounds = true self.transform = self.transform.scaledBy(x: 1, y: 3) } }
gpl-3.0
61df337f7dbcd42e750ef338e6a90798
19.707692
65
0.574294
4.116208
false
false
false
false
rymcol/Linux-Server-Side-Swift-Benchmarking
ZewoPress/Sources/BlogHandler.swift
2
1000
#if os(Linux) import Glibc #else import Darwin #endif struct BlogHandler { func loadPageContent() -> String { var finalContent = "<section id=\"content\"><div class=\"container\">" let randomContent = ContentGenerator().generate() for _ in 1...5 { let index: Int = Int(arc4random_uniform(UInt32(randomContent.count))) let value = Array(randomContent.values)[index] let imageNumber = Int(arc4random_uniform(25) + 1) finalContent += "<div class=\"row blog-post\"><div class=\"col-xs-12\"><h1>" finalContent += "Test Post \(index)" finalContent += "</h1><img src=\"" finalContent += "/img/random/random-\(imageNumber).jpg\" alt=\"Random Image \(imageNumber)\" class=\"alignleft feature-image img-responsive\" />" finalContent += "<div class=\"content\">\(value)</div>" } finalContent += "</div></div</div></section>" return finalContent } }
apache-2.0
a56b842c89a9f4f134d50a1cafa470d3
29.30303
157
0.586
4.366812
false
false
false
false
ryanspillsbury90/OmahaTutorial
ios/OmahaPokerTutorial/OmahaPokerTutorial/NavController.swift
1
1748
// // NavController.swift // OmahaPokerTutorial // // Created by Ryan Pillsbury on 6/19/15. // Copyright (c) 2015 koait. All rights reserved. // import UIKit class NavController: ENSideMenuNavigationController, ENSideMenuDelegate { var _sideMenu: ENSideMenu? override func viewDidLoad() { super.viewDidLoad() let whiteOverlay = UIView(frame: CGRectMake( self.navigationBar.frame.origin.x, self.navigationBar.frame.size.height, self.view.frame.size.width, 1) ); whiteOverlay.backgroundColor = UIColor.whiteColor() self.navigationBar.addSubview(whiteOverlay); // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func getOrCreateSideMenu() -> ENSideMenu? { if (_sideMenu == nil) { _sideMenu = ENSideMenu(sourceView: self.view, menuViewController: MenuTableViewController(), menuPosition:.Left) _sideMenu?.menuWidth = 180.0 // optional, default is 160 _sideMenu?.bouncingEnabled = false; view.bringSubviewToFront(navigationBar) _sideMenu?.hideSideMenu(); } return _sideMenu; } /* // 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
b9d50f407621d485ee1cdb2ef2a9312f
30.214286
124
0.646453
5.022989
false
false
false
false
JustasL/mapbox-navigation-ios
MapboxNavigation/RouteTableViewController.swift
1
4075
import UIKit import Pulley import MapboxCoreNavigation class RouteTableViewController: UIViewController { let RouteTableViewCellIdentifier = "RouteTableViewCellId" let dateFormatter = DateFormatter() let dateComponentsFormatter = DateComponentsFormatter() let distanceFormatter = DistanceFormatter(approximate: true) let routeStepFormatter = RouteStepFormatter() weak var routeController: RouteController! @IBOutlet var headerView: RouteTableViewHeaderView! @IBOutlet weak var tableView: UITableView! override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) setupTableView() dateFormatter.timeStyle = .short dateComponentsFormatter.maximumUnitCount = 2 dateComponentsFormatter.allowedUnits = [.day, .hour, .minute] dateComponentsFormatter.unitsStyle = .short distanceFormatter.numberFormatter.locale = .nationalizedCurrent headerView.progress = CGFloat(routeController.routeProgress.fractionTraveled) } func setupTableView() { tableView.tableHeaderView = headerView tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 80 } func showETA(routeProgress: RouteProgress) { let arrivalDate = NSCalendar.current.date(byAdding: .second, value: Int(routeProgress.durationRemaining), to: Date()) headerView.etaLabel.text = dateFormatter.string(from: arrivalDate!) if routeProgress.durationRemaining < 5 { headerView.distanceRemaining.text = nil } else { headerView.distanceRemaining.text = distanceFormatter.string(from: routeProgress.distanceRemaining) } if routeProgress.durationRemaining < 60 { headerView.timeRemaining.text = String.localizedStringWithFormat(NSLocalizedString("LESS_THAN", value: "<%@", comment: "Format string for less than; 1 = duration remaining"), dateComponentsFormatter.string(from: 61)!) } else { headerView.timeRemaining.text = dateComponentsFormatter.string(from: routeProgress.durationRemaining) } } func notifyDidChange(routeProgress: RouteProgress) { headerView.progress = routeProgress.currentLegProgress.alertUserLevel == .arrive ? 1 : CGFloat(routeProgress.fractionTraveled) showETA(routeProgress: routeProgress) } func notifyDidReroute() { tableView.reloadData() } func notifyAlertLevelDidChange() { if let visibleIndexPaths = tableView.indexPathsForVisibleRows { tableView.reloadRows(at: visibleIndexPaths, with: .fade) } } } extension RouteTableViewController: UITableViewDelegate, UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return routeController.routeProgress.currentLeg.steps.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: RouteTableViewCellIdentifier, for: indexPath) as! RouteTableViewCell let leg = routeController.routeProgress.currentLeg cell.step = leg.steps[indexPath.row] if routeController.routeProgress.currentLegProgress.stepIndex + 1 > indexPath.row { cell.contentView.alpha = 0.4 } return cell } } extension RouteTableViewController: PulleyDrawerViewControllerDelegate { public func supportedDrawerPositions() -> [PulleyPosition] { return [ .collapsed, .partiallyRevealed, .open, .closed ] } func collapsedDrawerHeight() -> CGFloat { return headerView.intrinsicContentSize.height } func partialRevealDrawerHeight() -> CGFloat { return UIScreen.main.bounds.height * 0.75 } }
isc
de42d9eb2fd99c2b4356fb79407dfccd
36.045455
229
0.69227
5.469799
false
false
false
false
shahmishal/swift
test/SILGen/c_function_pointers.swift
3
4104
// RUN: %target-swift-emit-silgen -verify %s | %FileCheck %s if true { var x = 0 func local() -> Int { return 0 } func localWithContext() -> Int { return x } func transitiveWithoutContext() -> Int { return local() } // Can't convert a closure with context to a C function pointer let _: @convention(c) () -> Int = { x } // expected-error{{cannot be formed from a closure that captures context}} let _: @convention(c) () -> Int = { [x] in x } // expected-error{{cannot be formed from a closure that captures context}} let _: @convention(c) () -> Int = localWithContext // expected-error{{cannot be formed from a local function that captures context}} let _: @convention(c) () -> Int = local let _: @convention(c) () -> Int = transitiveWithoutContext } class C { static func staticMethod() -> Int { return 0 } class func classMethod() -> Int { return 0 } } class Generic<X : C> { func f<Y : C>(_ y: Y) { let _: @convention(c) () -> Int = { return 0 } let _: @convention(c) () -> Int = { return X.staticMethod() } // expected-error{{cannot be formed from a closure that captures generic parameters}} let _: @convention(c) () -> Int = { return Y.staticMethod() } // expected-error{{cannot be formed from a closure that captures generic parameters}} } } func values(_ arg: @escaping @convention(c) (Int) -> Int) -> @convention(c) (Int) -> Int { return arg } // CHECK-LABEL: sil hidden [ossa] @$s19c_function_pointers6valuesyS2iXCS2iXCF // CHECK: bb0(%0 : $@convention(c) (Int) -> Int): // CHECK: return %0 : $@convention(c) (Int) -> Int @discardableResult func calls(_ arg: @convention(c) (Int) -> Int, _ x: Int) -> Int { return arg(x) } // CHECK-LABEL: sil hidden [ossa] @$s19c_function_pointers5callsyS3iXC_SitF // CHECK: bb0(%0 : $@convention(c) @noescape (Int) -> Int, %1 : $Int): // CHECK: [[RESULT:%.*]] = apply %0(%1) // CHECK: return [[RESULT]] @discardableResult func calls_no_args(_ arg: @convention(c) () -> Int) -> Int { return arg() } func global(_ x: Int) -> Int { return x } func no_args() -> Int { return 42 } // CHECK-LABEL: sil hidden [ossa] @$s19c_function_pointers0B19_to_swift_functionsyySiF func pointers_to_swift_functions(_ x: Int) { // CHECK: bb0([[X:%.*]] : $Int): func local(_ y: Int) -> Int { return y } // CHECK: [[GLOBAL_C:%.*]] = function_ref @$s19c_function_pointers6globalyS2iFTo // CHECK: [[CVT:%.*]] = convert_function [[GLOBAL_C]] // CHECK: apply {{.*}}([[CVT]], [[X]]) calls(global, x) // CHECK: [[LOCAL_C:%.*]] = function_ref @$s19c_function_pointers0B19_to_swift_functionsyySiF5localL_yS2iFTo // CHECK: [[CVT:%.*]] = convert_function [[LOCAL_C]] // CHECK: apply {{.*}}([[CVT]], [[X]]) calls(local, x) // CHECK: [[CLOSURE_C:%.*]] = function_ref @$s19c_function_pointers0B19_to_swift_functionsyySiFS2iXEfU_To // CHECK: [[CVT:%.*]] = convert_function [[CLOSURE_C]] // CHECK: apply {{.*}}([[CVT]], [[X]]) calls({ $0 + 1 }, x) calls_no_args(no_args) // CHECK: [[NO_ARGS_C:%.*]] = function_ref @$s19c_function_pointers7no_argsSiyFTo // CHECK: [[CVT:%.*]] = convert_function [[NO_ARGS_C]] // CHECK: apply {{.*}}([[CVT]]) } func unsupported(_ a: Any) -> Int { return 0 } func pointers_to_bad_swift_functions(_ x: Int) { calls(unsupported, x) // expected-error{{C function pointer signature '(Any) -> Int' is not compatible with expected type '@convention(c) (Int) -> Int'}} } // CHECK-LABEL: sil private [ossa] @$s19c_function_pointers22StructWithInitializersV3fn1yyXCvpfiyycfU_ : $@convention(thin) () -> () { // CHECK-LABEL: sil private [thunk] [ossa] @$s19c_function_pointers22StructWithInitializersV3fn1yyXCvpfiyycfU_To : $@convention(c) () -> () { struct StructWithInitializers { let fn1: @convention(c) () -> () = {} init(a: ()) {} init(b: ()) {} } func pointers_to_nested_local_functions_in_generics<T>(x: T) -> Int{ func foo(y: Int) -> Int { return y } return calls(foo, 0) } func capture_list_no_captures(x: Int) { calls({ [x] in $0 }, 0) // expected-warning {{capture 'x' was never used}} }
apache-2.0
f764448872bc3775d110421798246c92
37.364486
155
0.617446
3.213782
false
false
false
false
huang1988519/WechatArticles
WechatArticles/WechatArticles/Library/Sqlite/SQLiteDB.swift
1
12374
// // SQLiteDB.swift // TasksGalore // // Created by Fahim Farook on 12/6/14. // Copyright (c) 2014 RookSoft Pte. Ltd. All rights reserved. // import Foundation #if os(iOS) import UIKit #else import AppKit #endif let SQLITE_DATE = SQLITE_NULL + 1 private let SQLITE_STATIC = unsafeBitCast(0, sqlite3_destructor_type.self) private let SQLITE_TRANSIENT = unsafeBitCast(-1, sqlite3_destructor_type.self) // MARK:- SQLiteDB Class - Does all the work class SQLiteDB { let DB_NAME = "wechatArticle.sqlite3" let QUEUE_LABEL = "SQLiteDB" private var db:COpaquePointer = nil private var queue:dispatch_queue_t private var fmt = NSDateFormatter() private var GROUP = "" struct Static { static var instance:SQLiteDB? = nil static var token:dispatch_once_t = 0 } class func sharedInstance() -> SQLiteDB! { dispatch_once(&Static.token) { Static.instance = self.init(gid:"") } return Static.instance! } class func sharedInstance(gid:String) -> SQLiteDB! { dispatch_once(&Static.token) { Static.instance = self.init(gid:gid) } return Static.instance! } required init(gid:String) { assert(Static.instance == nil, "Singleton already initialized!") GROUP = gid // Set queue queue = dispatch_queue_create(QUEUE_LABEL, nil) fmt.timeZone = NSTimeZone(forSecondsFromGMT:0) // Set up for file operations let fm = NSFileManager.defaultManager() let dbName:String = String.fromCString(DB_NAME)! var docDir = "" // Is this for an app group? if GROUP.isEmpty { // Get path to DB in Documents directory docDir = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] } else { // Get path to shared group folder if let url = fm.containerURLForSecurityApplicationGroupIdentifier(GROUP) { docDir = url.path! } else { assert(false, "Error getting container URL for group: \(GROUP)") } } let path = (docDir as NSString).stringByAppendingPathComponent(dbName) print("Database path: \(path)") // Check if copy of DB is there in Documents directory if !(fm.fileExistsAtPath(path)) { // The database does not exist, so copy to Documents directory guard let rp = NSBundle.mainBundle().resourcePath else { return } let from = (rp as NSString).stringByAppendingPathComponent(dbName) do { try fm.copyItemAtPath(from, toPath:path) } catch let error as NSError { print("SQLiteDB - failed to copy writable version of DB!") print("Error - \(error.localizedDescription)") return } } // Open the DB let cpath = path.cStringUsingEncoding(NSUTF8StringEncoding) let error = sqlite3_open(cpath!, &db) if error != SQLITE_OK { // Open failed, close DB and fail print("SQLiteDB - failed to open DB!") sqlite3_close(db) } fmt.dateFormat = "YYYY-MM-dd HH:mm:ss" } deinit { closeDatabase() } private func closeDatabase() { if db != nil { // Get launch count value let ud = NSUserDefaults.standardUserDefaults() var launchCount = ud.integerForKey("LaunchCount") launchCount-- print("SQLiteDB - Launch count \(launchCount)") var clean = false if launchCount < 0 { clean = true launchCount = 500 } ud.setInteger(launchCount, forKey: "LaunchCount") ud.synchronize() // Do we clean DB? if !clean { sqlite3_close(db) return } // Clean DB print("SQLiteDB - Optimize DB") let sql = "VACUUM; ANALYZE" if execute(sql) != SQLITE_OK { print("SQLiteDB - Error cleaning DB") } sqlite3_close(db) } } // Execute SQL with parameters and return result code func execute(sql:String, parameters:[AnyObject]?=nil)->CInt { var result:CInt = 0 dispatch_sync(queue) { let stmt = self.prepare(sql, params:parameters) if stmt != nil { result = self.execute(stmt, sql:sql) } } return result } // Run SQL query with parameters func query(sql:String, parameters:[AnyObject]?=nil)->[[String:AnyObject]] { var rows = [[String:AnyObject]]() dispatch_sync(queue) { let stmt = self.prepare(sql, params:parameters) if stmt != nil { rows = self.query(stmt, sql:sql) } } return rows } // Show alert with either supplied message or last error func alert(msg:String) { dispatch_async(dispatch_get_main_queue()) { #if os(iOS) let alert = UIAlertView(title: "SQLiteDB", message:msg, delegate: nil, cancelButtonTitle: "OK") alert.show() #else let alert = NSAlert() alert.addButtonWithTitle("OK") alert.messageText = "SQLiteDB" alert.informativeText = msg alert.alertStyle = NSAlertStyle.WarningAlertStyle alert.runModal() #endif } } // Private method which prepares the SQL private func prepare(sql:String, params:[AnyObject]?)->COpaquePointer { var stmt:COpaquePointer = nil let cSql = sql.cStringUsingEncoding(NSUTF8StringEncoding) // Prepare let result = sqlite3_prepare_v2(self.db, cSql!, -1, &stmt, nil) if result != SQLITE_OK { sqlite3_finalize(stmt) if let error = String.fromCString(sqlite3_errmsg(self.db)) { let msg = "SQLiteDB - failed to prepare SQL: \(sql), Error: \(error)" print(msg) } return nil } // Bind parameters, if any if params != nil { // Validate parameters let cntParams = sqlite3_bind_parameter_count(stmt) let cnt = CInt(params!.count) if cntParams != cnt { let msg = "SQLiteDB - failed to bind parameters, counts did not match. SQL: \(sql), Parameters: \(params)" print(msg) return nil } var flag:CInt = 0 // Text & BLOB values passed to a C-API do not work correctly if they are not marked as transient. for ndx in 1...cnt { // println("Binding: \(params![ndx-1]) at Index: \(ndx)") // Check for data types if let txt = params![ndx-1] as? String { flag = sqlite3_bind_text(stmt, CInt(ndx), txt, -1, SQLITE_TRANSIENT) } else if let data = params![ndx-1] as? NSData { flag = sqlite3_bind_blob(stmt, CInt(ndx), data.bytes, CInt(data.length), SQLITE_TRANSIENT) } else if let date = params![ndx-1] as? NSDate { let txt = fmt.stringFromDate(date) flag = sqlite3_bind_text(stmt, CInt(ndx), txt, -1, SQLITE_TRANSIENT) } else if let val = params![ndx-1] as? Double { flag = sqlite3_bind_double(stmt, CInt(ndx), CDouble(val)) } else if let val = params![ndx-1] as? Int { flag = sqlite3_bind_int(stmt, CInt(ndx), CInt(val)) } else { flag = sqlite3_bind_null(stmt, CInt(ndx)) } // Check for errors if flag != SQLITE_OK { sqlite3_finalize(stmt) if let error = String.fromCString(sqlite3_errmsg(self.db)) { let msg = "SQLiteDB - failed to bind for SQL: \(sql), Parameters: \(params), Index: \(ndx) Error: \(error)" print(msg) } return nil } } } return stmt } // Private method which handles the actual execution of an SQL statement private func execute(stmt:COpaquePointer, sql:String)->CInt { // Step var result = sqlite3_step(stmt) if result != SQLITE_OK && result != SQLITE_DONE { sqlite3_finalize(stmt) if let err = String.fromCString(sqlite3_errmsg(self.db)) { let msg = "SQLiteDB - failed to execute SQL: \(sql), Error: \(err)" print(msg) } return 0 } // Is this an insert let upp = sql.uppercaseString if upp.hasPrefix("INSERT ") { // Known limitations: http://www.sqlite.org/c3ref/last_insert_rowid.html let rid = sqlite3_last_insert_rowid(self.db) result = CInt(rid) } else if upp.hasPrefix("DELETE") || upp.hasPrefix("UPDATE") { var cnt = sqlite3_changes(self.db) if cnt == 0 { cnt++ } result = CInt(cnt) } else { result = 1 } // Finalize sqlite3_finalize(stmt) return result } // Private method which handles the actual execution of an SQL query private func query(stmt:COpaquePointer, sql:String)->[[String:AnyObject]] { var rows = [[String:AnyObject]]() var fetchColumnInfo = true var columnCount:CInt = 0 var columnNames = [String]() var columnTypes = [CInt]() var result = sqlite3_step(stmt) while result == SQLITE_ROW { // Should we get column info? if fetchColumnInfo { columnCount = sqlite3_column_count(stmt) for index in 0..<columnCount { // Get column name let name = sqlite3_column_name(stmt, index) columnNames.append(String.fromCString(name)!) // Get column type columnTypes.append(self.getColumnType(index, stmt:stmt)) } fetchColumnInfo = false } // Get row data for each column var row = [String:AnyObject]() for index in 0..<columnCount { let key = columnNames[Int(index)] let type = columnTypes[Int(index)] if let val = getColumnValue(index, type:type, stmt:stmt) { // println("Column type:\(type) with value:\(val)") row[key] = val } } rows.append(row) // Next row result = sqlite3_step(stmt) } sqlite3_finalize(stmt) return rows } // Get column type private func getColumnType(index:CInt, stmt:COpaquePointer)->CInt { var type:CInt = 0 // Column types - http://www.sqlite.org/datatype3.html (section 2.2 table column 1) let blobTypes = ["BINARY", "BLOB", "VARBINARY"] let charTypes = ["CHAR", "CHARACTER", "CLOB", "NATIONAL VARYING CHARACTER", "NATIVE CHARACTER", "NCHAR", "NVARCHAR", "TEXT", "VARCHAR", "VARIANT", "VARYING CHARACTER"] let dateTypes = ["DATE", "DATETIME", "TIME", "TIMESTAMP"] let intTypes = ["BIGINT", "BIT", "BOOL", "BOOLEAN", "INT", "INT2", "INT8", "INTEGER", "MEDIUMINT", "SMALLINT", "TINYINT"] let nullTypes = ["NULL"] let realTypes = ["DECIMAL", "DOUBLE", "DOUBLE PRECISION", "FLOAT", "NUMERIC", "REAL"] // Determine type of column - http://www.sqlite.org/c3ref/c_blob.html let buf = sqlite3_column_decltype(stmt, index) // println("SQLiteDB - Got column type: \(buf)") if buf != nil { var tmp = String.fromCString(buf)!.uppercaseString // Remove brackets let pos = tmp.positionOf("(") if pos > 0 { tmp = tmp.subStringTo(pos) } // Remove unsigned? // Remove spaces // Is the data type in any of the pre-set values? // println("SQLiteDB - Cleaned up column type: \(tmp)") if intTypes.contains(tmp) { return SQLITE_INTEGER } if realTypes.contains(tmp) { return SQLITE_FLOAT } if charTypes.contains(tmp) { return SQLITE_TEXT } if blobTypes.contains(tmp) { return SQLITE_BLOB } if nullTypes.contains(tmp) { return SQLITE_NULL } if dateTypes.contains(tmp) { return SQLITE_DATE } return SQLITE_TEXT } else { // For expressions and sub-queries type = sqlite3_column_type(stmt, index) } return type } // Get column value private func getColumnValue(index:CInt, type:CInt, stmt:COpaquePointer)->AnyObject? { // Integer if type == SQLITE_INTEGER { let val = sqlite3_column_int(stmt, index) return Int(val) } // Float if type == SQLITE_FLOAT { let val = sqlite3_column_double(stmt, index) return Double(val) } // Text - handled by default handler at end // Blob if type == SQLITE_BLOB { let data = sqlite3_column_blob(stmt, index) let size = sqlite3_column_bytes(stmt, index) let val = NSData(bytes:data, length: Int(size)) return val } // Null if type == SQLITE_NULL { return nil } // Date if type == SQLITE_DATE { // Is this a text date let txt = UnsafePointer<Int8>(sqlite3_column_text(stmt, index)) if txt != nil { if let buf = NSString(CString:txt, encoding:NSUTF8StringEncoding) { let set = NSCharacterSet(charactersInString: "-:") let range = buf.rangeOfCharacterFromSet(set) if range.location != NSNotFound { // Convert to time var time:tm = tm(tm_sec: 0, tm_min: 0, tm_hour: 0, tm_mday: 0, tm_mon: 0, tm_year: 0, tm_wday: 0, tm_yday: 0, tm_isdst: 0, tm_gmtoff: 0, tm_zone:nil) strptime(txt, "%Y-%m-%d %H:%M:%S", &time) time.tm_isdst = -1 let diff = NSTimeZone.localTimeZone().secondsFromGMT let t = mktime(&time) + diff let ti = NSTimeInterval(t) let val = NSDate(timeIntervalSince1970:ti) return val } } } // If not a text date, then it's a time interval let val = sqlite3_column_double(stmt, index) let dt = NSDate(timeIntervalSince1970: val) return dt } // If nothing works, return a string representation let buf = UnsafePointer<Int8>(sqlite3_column_text(stmt, index)) let val = String.fromCString(buf) return val } }
apache-2.0
13b1f750ae02846684b96b403f635c6d
29.628713
169
0.65977
3.233342
false
false
false
false
practicalswift/swift
test/IRGen/unexploded-calls.swift
10
1726
// RUN: %swift -disable-legacy-type-info -target thumbv7-unknown-windows-msvc -parse-stdlib -parse-as-library -I %S/Inputs/usr/include -module-name Swift -S -emit-ir -o - %s | %FileCheck %s // RUN: %swift -disable-legacy-type-info -target thumbv7-unknown-linux-gnueabihf -parse-stdlib -parse-as-library -I %S/Inputs/usr/include -module-name Swift -S -emit-ir -o - %s | %FileCheck %s // RUN: %swift -disable-legacy-type-info -target thumbv7-unknown-linux-gnueabi -Xcc -mfloat-abi=hard -parse-stdlib -parse-as-library -I %S/Inputs/usr/include -module-name Swift -S -emit-ir -o - %s | %FileCheck %s // REQUIRES: CODEGENERATOR=ARM struct Float { let _value: Builtin.FPIEEE32 } typealias CFloat = Float typealias Void = () import SRoA public func g(_ s : S) { return f(s) } // CHECK: define {{.*}}swiftcc void @"$ss1gyySo1SVF"(float, float) {{.*}}{ // CHECK: entry: // CHECK: alloca // CHECK: [[ALLOCA:%[-._0-9a-zA-Z]+]] = alloca %TSo1SV, align 4 // CHECK: %{{.*}} = bitcast %TSo1SV* [[ALLOCA]] to i8* // CHECK: [[ALLOCA]].f = getelementptr inbounds %TSo1SV, %TSo1SV* [[ALLOCA]], i32 0, i32 0 // CHECK: [[ALLOCA]].f._value = getelementptr inbounds %TSf, %TSf* [[ALLOCA]].f, i32 0, i32 0 // CHECK: store float %0, float* [[ALLOCA]].f._value, align 4 // CHECK: [[ALLOCA]].g = getelementptr inbounds %TSo1SV, %TSo1SV* [[ALLOCA]], i32 0, i32 1 // CHECK: [[ALLOCA]].g._value = getelementptr inbounds %TSf, %TSf* [[ALLOCA]].g, i32 0, i32 0 // CHECK: store float %1, float* [[ALLOCA]].g._value, align 4 // CHECK: %[[BITCAST:.*]] = bitcast %TSo1SV* [[ALLOCA]] to %struct.S* // CHECK: %[[LOAD:.*]] = load %struct.S, %struct.S* %[[BITCAST]], align 4 // CHECK: call void @f(%struct.S %[[LOAD]]) // CHECK: }
apache-2.0
5b54223e095700d90a9aa4d7d940ea99
48.314286
212
0.640209
2.910624
false
false
false
false
PekanMmd/Pokemon-XD-Code
GoDToolOSX/Objects/GoDDesign.swift
1
3114
// // GoDDesign.swift // GoD Tool // // Created by StarsMmd on 29/06/2016. // Copyright © 2016 StarsMmd. All rights reserved. // #if GUI import AppKit #endif import Foundation class GoDDesign { #if GUI static var isDarkModeEnabled: Bool { let mode = UserDefaults.standard.string(forKey: "AppleInterfaceStyle") return mode == "Dark" } //MARK: - Fonts class func fontOfSize(_ size: CGFloat) -> NSFont { return NSFont(name: "Helvetica", size: size)! } class func fontBoldOfSize(_ size: CGFloat) -> NSFont { return NSFont(name: "Helvetica Bold", size: size)! } //MARK: - Sizes class func sizeCornerRadius() -> CGFloat { return 12.0 } class func sizeBottomButton() -> CGFloat { return 60.0 } #endif //MARK: - Colours class func colourClear() -> XGColour { return XGColour(raw:0x00000000) } class func colourBlack() -> XGColour { return XGColour(raw:0x000000FF) } class func colourWhite() -> XGColour { return XGColour(raw:0xFFFFFFFF) } class func colourRed() -> XGColour { return XGColour(raw:0xFC6848FF) } class func colourLightOrange() -> XGColour { return XGColour(raw: 0xFFD080FF) } class func colourOrange() -> XGColour { return XGColour(raw: 0xF7B409FF) } class func colourYellow() -> XGColour { return XGColour(raw: 0xF8F888FF) } class func colourLightGreen() -> XGColour { return XGColour(raw: 0xD0FFD0FF) } class func colourGreen() -> XGColour { return XGColour(raw: 0xA8E79CFF) } class func colourLightBlue() -> XGColour { return XGColour(raw: 0xB8F0FFFF) } class func colourBlue() -> XGColour { return XGColour(raw: 0x80ACFFFF) } class func colourLightPurple() -> XGColour { return XGColour(raw: 0xE0C0FFFF) } class func colourPurple() -> XGColour { return XGColour(raw: 0xA070FFFF) } class func colourPeach() -> XGColour { return XGColour(raw: 0xFFE8D0FF) } class func colourBabyPink() -> XGColour { return XGColour(raw: 0xFFE0E8FF) } class func colourPink() -> XGColour { return XGColour(raw: 0xFC80F6FF) } class func colourNavy() -> XGColour { return XGColour(raw: 0x28276BFF) } class func colourBrown() -> XGColour { return XGColour(raw: 0xC0A078FF) } class func colourLightBlack() -> XGColour { return XGColour(raw: 0x282828FF) } class func colourGrey() -> XGColour { return XGColour(raw: 0xC0C0C8FF) } class func colourDarkGrey() -> XGColour { return XGColour(raw: 0xA0A0A8FF) } class func colourLightGrey() -> XGColour { return XGColour(raw: 0xF0F0FCFF) } class func colourMainTheme() -> XGColour { return colourWhite() } class func colourBackground() -> XGColour { return colourLightGrey() } class func colourBlur() -> XGColour { return XGColour(raw: 0x70ACFF80) } #if GUI //MARK: - Dates class func dateFormatter() -> DateFormatter { let formatter = DateFormatter() formatter.dateStyle = .medium formatter.timeStyle = .short return formatter } //MARK: - Photos class func photoDefault() -> NSImage { let image = NSImage(named: "PhotoDefault")! return image } #endif }
gpl-2.0
59f9ea616265c559b6a59f2a91240103
17.529762
72
0.683906
3.010638
false
false
false
false
lukevanin/OCRAI
CardScanner/DataDetectorTextAnnotationService.swift
1
5845
// // DataDetectorTextAnnotationService.swift // CardScanner // // Created by Luke Van In on 2017/02/09. // Copyright © 2017 Luke Van In. All rights reserved. // // FIXME: Detect dates // import Foundation import Contacts import CoreLocation private class DataDetectorTextAnnotationOperation: AsyncOperation { private let content: Document private let completion: TextAnnotationServiceCompletion init(content: Document, completion: @escaping TextAnnotationServiceCompletion) { self.content = content self.completion = completion } fileprivate override func execute(completion: @escaping AsyncOperation.Completion) { DispatchQueue.main.async { [content] in if let content = content.text { let types: NSTextCheckingResult.CheckingType = [.phoneNumber, .link, .address] let detector = try! NSDataDetector(types: types.rawValue) let range = NSRange( location: 0, length: content.characters.count ) let matches = detector.matches( in: content, options: [], range: range ) self.annotatePhoneNumbers(matches) self.annotateUrlAddresses(matches) self.annotateEmailAddresses(matches) self.annotatePostalAddresses(matches) } if !self.isCancelled { self.completion(true, nil) } completion() } } private func annotatePhoneNumbers(_ matches: [NSTextCheckingResult]) { annotate(type: .phoneNumber, matches: matches) { guard let phoneNumber = $0.phoneNumber else { return nil } return self.sanitize(phoneNumber: phoneNumber) } } private func sanitize(phoneNumber: String) -> String { let characterSet = NSCharacterSet(charactersIn: "+()0123456789").inverted let components = phoneNumber.components(separatedBy: characterSet) return components.joined(separator: "") } private func annotateUrlAddresses(_ matches: [NSTextCheckingResult]) { annotate(type: .url, matches: matches) { guard let url = $0.url else { return nil } if let scheme = url.scheme, scheme == "mailto" { return nil } return url.absoluteString } } private func annotateEmailAddresses(_ matches: [NSTextCheckingResult]) { annotate(type: .email, matches: matches) { guard let url = $0.url, let scheme = url.scheme, scheme == "mailto" else { return nil } let raw = url.absoluteString let output: String if let s = raw.range(of: "mailto:") { output = raw.substring(from: s.upperBound) } else { output = raw } return output } } private func annotatePostalAddresses(_ matches: [NSTextCheckingResult]) { annotate(matches: matches) { match in guard let components = match.addressComponents else { return nil } return makeAddress(components) } } private func makeAddress(_ entities: [String: String]) -> CNPostalAddress { let address = CNMutablePostalAddress() if let street = entities[NSTextCheckingStreetKey] { address.street = street } if let city = entities[NSTextCheckingCityKey] { address.city = city } if let postalCode = entities[NSTextCheckingZIPKey] { address.postalCode = postalCode } if let country = entities[NSTextCheckingCountryKey] { address.country = country } return address } private func annotate(type: FieldType, matches: [NSTextCheckingResult], normalize: (NSTextCheckingResult) -> String?) { for match in matches { guard let normalizedText = normalize(match) else { continue } if match.numberOfRanges > 1 { // FIXME: Handle multiple ranges in response fatalError("unsupported multiple ranges") } content.annotate( type: type, text: normalizedText, at: match.range ) } } private func annotate(matches: [NSTextCheckingResult], normalize: (NSTextCheckingResult) -> CNPostalAddress?) { for match in matches { guard let address = normalize(match) else { continue } if match.numberOfRanges > 1 { // FIXME: Handle multiple ranges in response fatalError("unsupported multiple ranges") } content.annotate( address: address, at: match.range ) } } } struct DataDetectorTextAnnotationService: TextAnnotationService { let operationQueue: OperationQueue init(queue: OperationQueue? = nil) { self.operationQueue = queue ?? OperationQueue() } func annotate(content: Document, completion: @escaping TextAnnotationServiceCompletion) { let operation = DataDetectorTextAnnotationOperation( content: content, completion: completion ) operationQueue.addOperation(operation) } }
mit
c7e7e61600803b200069eca363da2825
30.251337
123
0.548768
5.701463
false
false
false
false
jzucker2/AwakeBrowser
AwakeBrowser/AwakeBrowser/JSZBrowserToolbar.swift
1
9361
// // JSZBrowserToolbar.swift // AwakeBrowser // // Created by Jordan Zucker on 3/20/16. // Copyright © 2016 Jordan Zucker. All rights reserved. // import UIKit enum JSZBrowserNavigationItem: String { case Reload case Back case Forward case Cancel case BackHistory case ForwardHistory } enum JSZBrowserNavigationState: String { case NotLoading case Loading } class JSZBrowserToolbar: UIView, UITextFieldDelegate { var inputField: UITextField! var backButton: UIButton! var forwardButton: UIButton! var awakeSwitch: UISwitch! var rightButton: UIButton! var navigationState = JSZBrowserNavigationState.NotLoading var shareButton: UIButton! weak var delegate: JSZBrowserToolbarDelegate? override init(frame: CGRect) { self.inputField = UITextField(frame: CGRectZero) self.inputField.borderStyle = .Line self.inputField.clearButtonMode = .WhileEditing self.inputField.autocapitalizationType = .None self.inputField.autocorrectionType = .No self.inputField.spellCheckingType = .No self.forwardButton = UIButton(type: .System) self.backButton = UIButton(type: .System) self.forwardButton.setTitle("F", forState: .Normal) self.backButton.setTitle("B", forState: .Normal) self.awakeSwitch = UISwitch() self.rightButton = UIButton(type: .System) self.shareButton = UIButton(type: .System) self.shareButton.setTitle("S", forState: .Normal) super.init(frame: frame) self.addSubview(inputField) self.addSubview(forwardButton) self.addSubview(backButton) self.addSubview(awakeSwitch) self.addSubview(shareButton) inputField.rightViewMode = .UnlessEditing inputField.rightView = rightButton inputField.delegate = self inputField.autoresizingMask = .None inputField.adjustsFontSizeToFitWidth = false self.backgroundColor = UIColor.purpleColor(); awakeSwitch.addTarget(self, action: #selector(JSZBrowserToolbar.awakeSwitchValueChanged(_:)), forControlEvents: .ValueChanged) backButton.addTarget(self, action: #selector(JSZBrowserToolbar.didTapBackButton(_:)), forControlEvents: .TouchUpInside) forwardButton.addTarget(self, action: #selector(JSZBrowserToolbar.didTapForwardButton(_:)), forControlEvents: .TouchUpInside) rightButton.addTarget(self, action: #selector(JSZBrowserToolbar.didTapRightButton(_:)), forControlEvents: .TouchUpInside) shareButton.addTarget(self, action: #selector(JSZBrowserToolbar.didTapShareButton(_:)), forControlEvents: .TouchUpInside) backButton.addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: #selector(JSZBrowserToolbar.didLongPressNavigationButton(_:)))) forwardButton.addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: #selector(JSZBrowserToolbar.didLongPressNavigationButton(_:)))) applyLayoutConstraints() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } func applyLayoutConstraints() { inputField.translatesAutoresizingMaskIntoConstraints = false forwardButton.translatesAutoresizingMaskIntoConstraints = false backButton.translatesAutoresizingMaskIntoConstraints = false awakeSwitch.translatesAutoresizingMaskIntoConstraints = false shareButton.translatesAutoresizingMaskIntoConstraints = false let views = ["inputField": inputField, "forwardButton": forwardButton, "backButton": backButton, "awakeSwitch": awakeSwitch, "shareButton": shareButton] let metrics = ["inputFieldTopPadding": 5.0, "inputFieldBottomPadding": 5.0, "inputFieldLeftPadding": 5.0, "inputFieldRightPadding": 5.0, "navigationButtonsWidth": 10.0, "navigationButtonsHeight": 20.0, "navigationButtonsTopPadding": 10.0] let inputFieldHorizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|-5-[backButton(navigationButtonsWidth)]-2-[forwardButton(navigationButtonsWidth)]-inputFieldLeftPadding-[inputField]-inputFieldRightPadding-[shareButton(10)]-5-[awakeSwitch]-5-|", options: [], metrics: metrics, views: views) let inputFieldVerticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|-inputFieldTopPadding-[inputField]-inputFieldBottomPadding-|", options: [], metrics: metrics, views: views) let forwardButtonVerticalConstraint = NSLayoutConstraint(item: forwardButton, attribute: .Height, relatedBy: .Equal, toItem: self, attribute: .Height, multiplier: 0.5, constant: 0.0) let backButtonVerticalConstraint = NSLayoutConstraint(item: backButton, attribute: .Height, relatedBy: .Equal, toItem: self, attribute: .Height, multiplier: 0.5, constant: 0.0) let forwardButtonVerticalCenterConstraints = NSLayoutConstraint(item: forwardButton, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1.0, constant: 0.0) let backButtonVerticalCenterConstraints = NSLayoutConstraint(item: backButton, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1.0, constant: 0.0) let awakeSwitchVerticalCenterConstraint = NSLayoutConstraint(item: awakeSwitch, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1.0, constant: 0.0) let shareButtonVerticalCenterConstraint = NSLayoutConstraint(item: shareButton, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1.0, constant: 0.0) let shareButtonVerticalConstraint = NSLayoutConstraint(item: shareButton, attribute: .Height, relatedBy: .Equal, toItem: self, attribute: .Height, multiplier: 0.5, constant: 0.0) self.addConstraints(inputFieldHorizontalConstraints) self.addConstraints(inputFieldVerticalConstraints) self.addConstraints([forwardButtonVerticalConstraint, backButtonVerticalConstraint]) self.addConstraints([forwardButtonVerticalCenterConstraints, backButtonVerticalCenterConstraints]) self.addConstraint(awakeSwitchVerticalCenterConstraint) self.addConstraints([shareButtonVerticalConstraint, shareButtonVerticalCenterConstraint]) } func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() delegate?.toolbarDidReturnWithText(textField.text) return true } var forwardButtonEnabled: Bool { get { return forwardButton.enabled } set { forwardButton.enabled = newValue } } var backButtonEnabled: Bool { get { return backButton.enabled } set { backButton.enabled = newValue } } func setLoading(loading: Bool) { let rightButtonTitle: String if (loading) { navigationState = .Loading rightButtonTitle = "C" } else { navigationState = .NotLoading rightButtonTitle = "R" } rightButton.setTitle(rightButtonTitle, forState: .Normal) rightButton.sizeToFit() } var awakeSwitchOn: Bool { get { return awakeSwitch.on } set { awakeSwitch.setOn(newValue, animated: false) delegate?.toolbarAwakeSwitchValueChanged(newValue) } } func awakeSwitchValueChanged(sender: UISwitch) { delegate?.toolbarAwakeSwitchValueChanged(sender.on) } func didTapForwardButton(sender: UIButton) { delegate?.toolbarDidReceiveNavigationAction(sender, action: .Forward) } func didTapBackButton(sender: UIButton) { delegate?.toolbarDidReceiveNavigationAction(sender, action: .Back) } func didTapShareButton(sender: UIButton) { delegate?.toolbarDidTapShareButton(sender) } func updateTextFieldWithURL(URL: NSURL?) { if let aURL = URL { inputField.text = aURL.absoluteString } else { inputField.text = "" } } func didTapRightButton(sender: UIButton) { switch navigationState { case .NotLoading: delegate?.toolbarDidReceiveNavigationAction(sender, action: .Reload) case .Loading: delegate?.toolbarDidReceiveNavigationAction(sender, action: .Cancel) } } func didLongPressNavigationButton(recognizer: UITapGestureRecognizer) { var longPressItem: JSZBrowserNavigationItem? if let button = recognizer.view as? UIButton { if button == backButton { longPressItem = .BackHistory } else if button == forwardButton { longPressItem = .ForwardHistory } } if let item = longPressItem { delegate?.toolbarDidReceiveNavigationAction(recognizer.view, action: item) } } } protocol JSZBrowserToolbarDelegate: class { func toolbarDidReturnWithText(text: String?) func toolbarDidReceiveNavigationAction(sourceView: UIView!, action: JSZBrowserNavigationItem) func toolbarAwakeSwitchValueChanged(awakeSwitchValue: Bool) func toolbarDidTapShareButton(sourceView: UIView!) }
mit
f83d626537406a27691298362829f76f
44.217391
321
0.701709
5.282167
false
false
false
false
orta/Agrume
Agrume/AgrumeCell.swift
2
16587
// // AgrumeCell.swift // Agrume // import UIKit class AgrumeCell: UICollectionViewCell { private static let TargetZoomForDoubleTap: CGFloat = 3 private static let MinFlickDismissalVelocity: CGFloat = 800 private static let HighScrollVelocity: CGFloat = 1600 private lazy var scrollView: UIScrollView = { let scrollView = UIScrollView(frame: self.contentView.bounds) scrollView.delegate = self scrollView.zoomScale = 1 scrollView.maximumZoomScale = 8 scrollView.scrollEnabled = false scrollView.showsHorizontalScrollIndicator = false scrollView.showsVerticalScrollIndicator = false return scrollView }() private lazy var imageView: UIImageView = { let imageView = UIImageView(frame: self.contentView.bounds) imageView.contentMode = .ScaleAspectFit imageView.userInteractionEnabled = true imageView.clipsToBounds = true imageView.layer.allowsEdgeAntialiasing = true return imageView }() private var animator: UIDynamicAnimator! var image: UIImage? { didSet { imageView.image = image updateScrollViewAndImageViewForCurrentMetrics() } } var dismissAfterFlick: (() -> Void)! var dismissByExpanding: (() -> Void)! override init(frame: CGRect) { super.init(frame: frame) backgroundColor = UIColor.clearColor() contentView.addSubview(scrollView) scrollView.addSubview(imageView) setupGestureRecognizers() animator = UIDynamicAnimator(referenceView: scrollView) } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func prepareForReuse() { imageView.image = nil scrollView.zoomScale = 1 updateScrollViewAndImageViewForCurrentMetrics() } private lazy var singleTapGesture: UITapGestureRecognizer = { let singleTapGesture = UITapGestureRecognizer(target: self, action: Selector("singleTap:")) singleTapGesture.requireGestureRecognizerToFail(self.doubleTapGesture) singleTapGesture.delegate = self return singleTapGesture }() private lazy var doubleTapGesture: UITapGestureRecognizer = { let doubleTapGesture = UITapGestureRecognizer(target: self, action: Selector("doubleTap:")) doubleTapGesture.numberOfTapsRequired = 2 return doubleTapGesture }() private lazy var panGesture: UIPanGestureRecognizer = { let panGesture = UIPanGestureRecognizer(target: self, action: Selector("dismissPan:")) panGesture.maximumNumberOfTouches = 1 panGesture.delegate = self return panGesture }() lazy var swipeGesture: UISwipeGestureRecognizer = { let swipeGesture = UISwipeGestureRecognizer(target: self, action: nil) swipeGesture.direction = .Left | .Right swipeGesture.delegate = self return swipeGesture }() private var flickedToDismiss: Bool = false private var isDraggingImage: Bool = false private var imageDragStartingPoint: CGPoint! private var imageDragOffsetFromActualTranslation: UIOffset! private var imageDragOffsetFromImageCenter: UIOffset! private var attachmentBehavior: UIAttachmentBehavior? private func setupGestureRecognizers() { contentView.addGestureRecognizer(singleTapGesture) contentView.addGestureRecognizer(doubleTapGesture) scrollView.addGestureRecognizer(panGesture) contentView.addGestureRecognizer(swipeGesture) } } extension AgrumeCell: UIGestureRecognizerDelegate { // MARK: UIGestureRecognizerDelegate func notZoomed() -> Bool { return scrollView.zoomScale == 1 } override func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool { if let pan = gestureRecognizer as? UIPanGestureRecognizer where notZoomed() { let velocity = pan.velocityInView(scrollView) return abs(velocity.y) > abs(velocity.x) } else if let _ = gestureRecognizer as? UISwipeGestureRecognizer where notZoomed() { return false } else if let tap = gestureRecognizer as? UITapGestureRecognizer where tap == singleTapGesture && !notZoomed() { return false } return true } func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool { if let _ = gestureRecognizer as? UIPanGestureRecognizer { return notZoomed() } return true } func doubleTap(sender: UITapGestureRecognizer) { let point = scrollView.convertPoint(sender.locationInView(sender.view), fromView: sender.view) let targetZoom: CGRect let targetInsets: UIEdgeInsets if notZoomed() { let zoomWidth = CGRectGetWidth(contentView.bounds) / AgrumeCell.TargetZoomForDoubleTap let zoomHeight = CGRectGetHeight(contentView.bounds) / AgrumeCell.TargetZoomForDoubleTap targetZoom = CGRect(x: point.x - zoomWidth / 2, y: point.y / zoomWidth / 2, width: zoomWidth, height: zoomHeight) targetInsets = contentInsetForScrollView(atScale: AgrumeCell.TargetZoomForDoubleTap) } else { let zoomWidth = CGRectGetWidth(contentView.bounds) * scrollView.zoomScale let zoomHeight = CGRectGetHeight(contentView.bounds) * scrollView.zoomScale targetZoom = CGRect(x: point.x - zoomWidth / 2, y: point.y / zoomWidth / 2, width: zoomWidth, height: zoomHeight) targetInsets = contentInsetForScrollView(atScale: 1) } contentView.userInteractionEnabled = false CATransaction.begin() CATransaction.setCompletionBlock { [weak self] in self?.scrollView.contentInset = targetInsets self?.contentView.userInteractionEnabled = true } scrollView.zoomToRect(targetZoom, animated: true) CATransaction.commit() } private func contentInsetForScrollView(#atScale: CGFloat) -> UIEdgeInsets { let boundsWidth = CGRectGetWidth(scrollView.bounds) let boundsHeight = CGRectGetHeight(scrollView.bounds) let contentWidth = max(image?.size.width ?? 0, boundsWidth) let contentHeight = max(image?.size.height ?? 0, boundsHeight) var minContentWidth: CGFloat var minContentHeight: CGFloat if contentHeight > contentWidth { if boundsHeight / boundsWidth < contentHeight / contentWidth { minContentHeight = boundsHeight minContentWidth = contentWidth * (minContentHeight / contentHeight) } else { minContentWidth = boundsWidth minContentHeight = contentHeight * (minContentWidth / contentWidth) } } else { if boundsWidth / boundsHeight < contentWidth / contentHeight { minContentWidth = boundsWidth minContentHeight = contentHeight * (minContentWidth / contentWidth) } else { minContentHeight = boundsHeight minContentWidth = contentWidth * (minContentHeight / contentHeight) } } minContentWidth *= atScale minContentHeight *= atScale let inset: UIEdgeInsets if minContentWidth > CGRectGetWidth(contentView.bounds) && minContentHeight > CGRectGetHeight(contentView.bounds) { inset = UIEdgeInsetsZero } else { let verticalDiff = max(boundsHeight - minContentHeight, 0) let horizontalDiff = max(boundsWidth - minContentWidth, 0) inset = UIEdgeInsets(top: verticalDiff / 2, left: horizontalDiff / 2, bottom: verticalDiff / 2, right: horizontalDiff / 2) } return inset } func singleTap(gesture: UITapGestureRecognizer) { dismiss() } private func dismiss() { if flickedToDismiss { dismissAfterFlick() } else { dismissByExpanding() } } func dismissPan(gesture: UIPanGestureRecognizer) { var translation = gesture.translationInView(gesture.view!) let locationInView = gesture.locationInView(gesture.view) let velocity = gesture.velocityInView(gesture.view) let vectorDistance = sqrt(pow(velocity.x, 2) + pow(velocity.y, 2)) if gesture.state == .Began { isDraggingImage = CGRectContainsPoint(imageView.frame, locationInView) if isDraggingImage { startImageDragging(locationInView, translationOffset: UIOffsetZero) } } else if gesture.state == .Changed { if isDraggingImage { var newAnchor = imageDragStartingPoint newAnchor.x += translation.x + imageDragOffsetFromActualTranslation.horizontal newAnchor.y += translation.y + imageDragOffsetFromActualTranslation.vertical attachmentBehavior?.anchorPoint = newAnchor } else { isDraggingImage = CGRectContainsPoint(imageView.frame, locationInView) if isDraggingImage { let translationOffset = UIOffset(horizontal: -1 * translation.x, vertical: -1 * translation.y) startImageDragging(locationInView, translationOffset: translationOffset) } } } else { if vectorDistance > AgrumeCell.MinFlickDismissalVelocity { if isDraggingImage { dismissWithFlick(velocity) } else { dismiss() } } else { cancelCurrentImageDrag(true) } } } private func dismissWithFlick(velocity: CGPoint) { flickedToDismiss = true let push = UIPushBehavior(items: [imageView], mode: .Instantaneous) push.pushDirection = CGVector(dx: velocity.x * 0.1, dy: velocity.y * 0.1) push.setTargetOffsetFromCenter(imageDragOffsetFromImageCenter, forItem: imageView) push.action = { [unowned self] in if self.isImageViewOffscreen() { self.animator.removeAllBehaviors() self.attachmentBehavior = nil self.imageView.removeFromSuperview() self.dismiss() } } animator.removeBehavior(attachmentBehavior) animator.addBehavior(push) } func isImageViewOffscreen() -> Bool { let visibleRect = scrollView.convertRect(contentView.bounds, fromView: contentView) return animator.itemsInRect(visibleRect).count == 0 } private func cancelCurrentImageDrag(animated: Bool) { animator.removeAllBehaviors() attachmentBehavior = nil isDraggingImage = false if !animated { imageView.transform = CGAffineTransformIdentity imageView.center = CGPoint(x: scrollView.contentSize.width / 2, y: scrollView.contentSize.height / 2) } else { UIView.animateWithDuration(0.7, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0, options: .AllowUserInteraction | .BeginFromCurrentState, animations: { if !self.isDraggingImage { self.imageView.transform = CGAffineTransformIdentity if !self.scrollView.dragging && !self.scrollView.decelerating { self.imageView.center = CGPoint(x: self.scrollView.contentSize.width / 2, y: self.scrollView.contentSize.height / 2) self.updateScrollViewAndImageViewForCurrentMetrics() } } }, completion: nil) } } func updateScrollViewAndImageViewForCurrentMetrics() { scrollView.frame = contentView.bounds if let image = self.imageView.image { imageView.frame = resizedFrameForSize(image.size) } scrollView.contentSize = imageView.frame.size scrollView.contentInset = contentInsetForScrollView(atScale: scrollView.zoomScale) } private func resizedFrameForSize(imageSize: CGSize) -> CGRect { var frame = contentView.bounds let screenWidth = CGRectGetWidth(frame) * scrollView.zoomScale let screenHeight = CGRectGetHeight(frame) * scrollView.zoomScale var targetWidth = screenWidth var targetHeight = screenHeight let nativeWidth = max(imageSize.width, screenWidth) let nativeHeight = max(imageSize.height, screenHeight) if nativeHeight > nativeWidth { if screenHeight / screenWidth < nativeHeight / nativeWidth { targetWidth = screenHeight / (nativeHeight / nativeWidth) } else { targetHeight = screenWidth / (nativeWidth / nativeHeight) } } else { if screenWidth / screenHeight < nativeWidth / nativeHeight { targetHeight = screenWidth / (nativeWidth / nativeHeight) } else { targetWidth = screenHeight / (nativeHeight / nativeWidth) } } frame.size = CGSize(width: targetWidth, height: targetHeight) frame.origin = CGPointZero return frame } private func startImageDragging(locationInView: CGPoint, translationOffset: UIOffset) { imageDragStartingPoint = locationInView imageDragOffsetFromActualTranslation = translationOffset let anchor = imageDragStartingPoint let imageCenter = imageView.center let offset = UIOffset(horizontal: locationInView.x - imageCenter.x, vertical: locationInView.y - imageCenter.y) imageDragOffsetFromImageCenter = offset attachmentBehavior = UIAttachmentBehavior(item: imageView, offsetFromCenter: offset, attachedToAnchor: anchor) animator.addBehavior(attachmentBehavior) let modifier = UIDynamicItemBehavior(items: [imageView]) modifier.angularResistance = angularResistance(view: imageView) modifier.density = density(view: imageView) animator.addBehavior(modifier) } private func angularResistance(#view: UIView) -> CGFloat { let defaultResistance: CGFloat = 4 return appropriateValue(defaultValue: defaultResistance) * factor(forView: view) } private func density(#view: UIView) -> CGFloat { let defaultDensity: CGFloat = 0.5 return appropriateValue(defaultValue: defaultDensity) * factor(forView: view) } private func appropriateValue(#defaultValue: CGFloat) -> CGFloat { let screenWidth = CGRectGetWidth(UIScreen.mainScreen().bounds) let screenHeight = CGRectGetHeight(UIScreen.mainScreen().bounds) // Default value that works well for the screenSize adjusted for the actual size of the device return defaultValue * ((320 * 480) / (screenWidth * screenHeight)) } private func factor(forView view: UIView) -> CGFloat { let actualArea = CGRectGetHeight(contentView.bounds) * CGRectGetWidth(view.bounds) let referenceArea = CGRectGetHeight(contentView.bounds) * CGRectGetWidth(contentView.bounds) return referenceArea / actualArea } } extension AgrumeCell: UIScrollViewDelegate { // MARK: UIScrollViewDelegate func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? { return imageView } func scrollViewDidZoom(scrollView: UIScrollView) { scrollView.contentInset = contentInsetForScrollView(atScale: scrollView.zoomScale) if !scrollView.scrollEnabled { scrollView.scrollEnabled = true } } func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView!, atScale scale: CGFloat) { scrollView.scrollEnabled = scale > 1 scrollView.contentInset = contentInsetForScrollView(atScale: scale) } func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) { let highVelocity = AgrumeCell.HighScrollVelocity let velocity = scrollView.panGestureRecognizer.velocityInView(scrollView.panGestureRecognizer.view) if notZoomed() && (fabs(velocity.x) > highVelocity || fabs(velocity.y) > highVelocity) { dismiss() } } }
mit
2f53e320fb54117573a25b6c6465c455
39.456098
134
0.653464
5.698042
false
false
false
false
johnfairh/TMLPersistentContainer
Sources/Helpers.swift
1
7340
// // Helpers.swift // TMLPersistentContainer // // Distributed under the ISC license, see LICENSE. // import Foundation import CoreData // MARK: Additions to Foundation.FileManager @available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) extension FileManager { /// Get a new temporary directory. Caller must delete. func newTemporaryDirectoryURL() throws -> URL { let directoryURL = temporaryDirectory.appendingPathComponent(UUID().uuidString) try createDirectory(at: directoryURL, withIntermediateDirectories: false) return directoryURL } /// Get a new temporary file. Caller must delete. func temporaryFileURL(inDirectory directory: URL? = nil) -> URL { let filename = UUID().uuidString let directoryURL = directory ?? temporaryDirectory return directoryURL.appendingPathComponent(filename) } } /// More wrappers for temp file patterns @available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) class TemporaryDirectory { private(set) var directoryURL: URL? var exists: Bool { return directoryURL != nil } func createNewFile() throws -> URL { if directoryURL == nil { directoryURL = try FileManager.default.newTemporaryDirectoryURL() } return FileManager.default.temporaryFileURL(inDirectory: directoryURL) } func deleteAll() { if let directoryURL = directoryURL { try? FileManager.default.removeItem(at: directoryURL) self.directoryURL = nil } } } // MARK: Additions to Swift.String extension String { /// Does the string precede `other` using `NSString.CompareOptions.numeric`? func precedesByNumericComparison(_ other: String) -> Bool { let selfNsString = self as NSString return selfNsString.compare(other, options: .numeric) == .orderedAscending } /// Return an NSRange corresponding to the entire string var nsRange: NSRange { return NSMakeRange(0, utf16.count) } /// Return the string corresponding to an NSRange, or empty if none internal subscript(nsRange: NSRange) -> String { guard let range = Range(nsRange, in: self) else { return "" } return String(self[range]) } } // MARK: Additions to Swift.Collection extension Collection where Iterator.Element: Hashable { /// Does the collection consist of unique elements? /// - Complexity: O(n) with some squinting.... var hasUniqueElements: Bool { var dict: [Iterator.Element:Bool] = [:] for s in self { if dict[s] != nil { return false } dict[s] = true } return true } } extension Collection where Iterator.Element: Equatable { func commonPrefix(with: Self) -> Int { var prefix = 0 for (a, b) in zip(self, with) { guard a == b else { break } prefix += 1 } return prefix } } // MARK: Additions to Swift.Dictionary extension Dictionary { /// Initialize a dictionary from a sequence of (Key,Value) tuples init<S>(_ seq: S) where S: Sequence, S.Iterator.Element == (Key, Value) { self.init() seq.forEach { self[$0.0] = $0.1 } } /// Return a new dictionary including just those (Key,Value) pairs included by the filter function func filtered(_ isIncluded: (Key, Value) throws -> Bool) rethrows -> Dictionary<Key, Value> { let filteredTuples: [(Key, Value)] = try filter(isIncluded) return Dictionary(filteredTuples) } } // MARK: Additions to Foundation.Bundle extension Bundle { /// Return URLs for all files and directories optionally matching an extension within the bundle. func urlsRecursively(forResourcesWithExtension ext: String) -> [URL] { var urls: [URL] = [] guard let enumerator = FileManager.default.enumerator(at: bundleURL, includingPropertiesForKeys: nil) else { // hmm return urls } for case let fileURL as URL in enumerator { let filename = fileURL.lastPathComponent if filename.hasSuffix(ext) { urls.append(fileURL) } } return urls } } // this allows mocking Bundle for the tests protocol BundleProtocol { func url(forResource name: String?, withExtension ext: String?) -> URL? } extension Bundle: BundleProtocol {} extension Sequence where Iterator.Element: BundleProtocol { /// this looks through all bundles of the sequence and returns all `NSManagedObjectModel` with the supplied `name` /// - Parameters: /// - name: The name of the managed object model to use with the container. /// This name is used as the default name for the first persistent store. func managedObjectModels(with name: String) -> [NSManagedObjectModel] { return self.compactMap { (bundle) -> URL? in // Investigation does show that NSPC.init(string) searches for .momds and NOT .moms. bundle.url(forResource: name, withExtension: "momd") }.compactMap { (url) -> NSManagedObjectModel? in NSManagedObjectModel(contentsOf: url) } } } // MARK: Additions to Foundation.NSRegularExpression extension NSRegularExpression { /// Check if the pattern matches + return the matched string, either whole thing or 1st c.grp func matchesString(_ str: String) -> String? { let results = matches(in: str, range: str.nsRange) guard results.count == 1 else { return nil } let matchRange: NSRange if results[0].numberOfRanges == 1 { // entire match matchRange = results[0].range(at: 0) } else { // first capture group matchRange = results[0].range(at: 1) } return str[matchRange] } } // MARK: Additions to CoreData.NSManagedObjectModel private extension NSEntityDescription { var reliableName: String { return name ?? "(unnamed)" // gee thanks } } // NSData prints its bytes out, Data does not. When debugging core data we want the bytes. // See SR-2514. extension NSManagedObjectModel { /// Return a string of the entity version hashes. var entityHashDescription: String { var str = "" var first = true entityVersionHashesByName.sorted(by: { $0.0 > $1.0 }) .forEach { name, data in if !first { str = str + ", " } str = str + "(\(name): \(data as NSData))" first = false } return "[\(str)]" } /// Return a string of the entity version hashes for a particular config func entityHashDescription(forConfigurationName configuration: String?) -> String { guard let entities = entities(forConfigurationName: configuration) else { return "[]" } var str = "" var first = true entities.sorted(by: { $0.reliableName > $1.reliableName}) .forEach { ent in if !first { str = str + ", " } str = str + "(\(ent.reliableName): \(ent.versionHash as NSData))" first = false } return "[\(str)]" } }
isc
24d2dcdcdff9bf9119bcee4bc20aed07
29.330579
118
0.617847
4.578915
false
false
false
false
soyabi/wearableD
WearableD/BLEPeripheral.swift
2
8920
// // BLEPeripheral.swift // WearableD // // Created by Zhang, Modesty on 1/9/15. // Copyright (c) 2015 Intuit. All rights reserved. // import Foundation import CoreBluetooth protocol BLEPeripheralDelegate { func blePeripheralMsgUpdate(textMsg:String!) func blePeripheralIsReady() func blePeripheralDidSendData(dataSequence: BLESequence) func blePeripheralDidStop() } class BLEPeripheral: NSObject, CBPeripheralManagerDelegate { var wctPeripheral: CBPeripheralManager? var wctService: CBMutableService? var wctCharacteristic: CBMutableCharacteristic? var wctSequence: BLESequence var wctConnectedCentral: CBCentral? var delegate: BLEPeripheralDelegate? // oAuth error or cancel var data_error: String // oAuth access token private var data_token: [String] // token chunk idx private var chunk_idx = 0 private var _raw_token: String var raw_token: String { get { return _raw_token } set (rawValue) { _raw_token = rawValue println("AUTH TOEKEN LENGTH: \(count(_raw_token))") var str = rawValue //MQZ.2/3/2015 max-chunk-length is 150 var chunkLength = 120 var chunks = [String]() var startIndex = str.startIndex var chunkAmount = Int(count(_raw_token) / chunkLength) + 1 while chunkAmount > 0 { var oneLength = chunkLength if chunkAmount == 1 { oneLength = count(str) - Int(count(_raw_token) / chunkLength) * chunkLength } var endIndex = advance(startIndex, oneLength) var chunk = str.substringWithRange(Range(start: startIndex, end: endIndex)) chunks.append(chunk) startIndex = endIndex chunkAmount-- } data_token = chunks } } var is_all_chunk_sent: Bool { get { return (self.chunk_idx == self.data_token.count) ? true : false } } override init() { self.wctPeripheral = nil self.wctService = nil self.wctCharacteristic = nil self.wctSequence = .None self.wctConnectedCentral = nil self.data_error = "" self.data_token = [String]() self.delegate = nil self._raw_token = "" super.init() } func openPeripheral(delegate: BLEPeripheralDelegate!) { self.delegate = delegate self.wctPeripheral = CBPeripheralManager(delegate: self, queue: nil) } func startPeripheral() { // start advertising with specific service uuid self.wctPeripheral?.startAdvertising([CBAdvertisementDataServiceUUIDsKey: [BLEIDs.wctService] ]) } func closePeripheral() { self.wctConnectedCentral = nil self.wctPeripheral?.stopAdvertising() self.delegate?.blePeripheralDidStop() self.delegate = nil } func openService() { // Start with the CBMutableCharacteristic self.wctCharacteristic = CBMutableCharacteristic( type: BLEIDs.wctCharacteristic, properties: CBCharacteristicProperties.Notify, value: nil, permissions: CBAttributePermissions.Readable) // Then the service self.wctService = CBMutableService(type: BLEIDs.wctService, primary: true) // Add the characteristic to the service self.wctService?.characteristics = [self.wctCharacteristic!] // finally, add the service to peripheral manager self.wctPeripheral!.addService(self.wctService) println(self.wctService?.peripheral?.name) println("BLE service is set up.") } func sendDataSequence() -> Bool { if self.wctSequence == .None { println("no data to sent, return") return false } if self.wctConnectedCentral == nil { println("connection already closed, return") return false } var rawValue = self.wctSequence.rawValue if self.wctSequence == .Init { self.chunk_idx = 0 } else if self.wctSequence == .Ready { rawValue += ":\(self.data_token.count)" println("ready for token: \(self.data_token.count) chunks") } else if self.wctSequence == .Token { rawValue += ":\(self.data_token[self.chunk_idx])" println("sending token: \(self.data_token[self.chunk_idx]) - \(self.chunk_idx) of \(self.data_token.count)") } else if self.wctSequence == .Error { rawValue += ":\(self.data_error)" println("sending error:\(self.data_error)") } var didSend = self.wctPeripheral?.updateValue(BLEIDs.getSequenceData(rawValue), forCharacteristic: self.wctCharacteristic, onSubscribedCentrals: [self.wctConnectedCentral!]) if didSend! { println("sent Data ok: \(rawValue)") if self.wctSequence == .Token { self.chunk_idx++ } self.delegate!.blePeripheralDidSendData(self.wctSequence) } else { println("sent data failed: \(rawValue). will send again") } return didSend! } /** Required protocol method. A full app should take care of all the possible states, * but we're just waiting for to know when the CBPeripheralManager is ready */ func peripheralManagerDidStartAdvertising(peripheral: CBPeripheralManager!, error: NSError!) { if let err = error { println("peripheralManagerDidStartAdvertising error: " + err.localizedFailureReason!) self.delegate?.blePeripheralMsgUpdate("Bluetooth LE error of advertising...\(err.localizedFailureReason!)") } else { println("peripheralManagerDidStartAdvertising ok") self.delegate?.blePeripheralMsgUpdate("Bluetooth LE is waiting to connect...") } } func peripheralManagerDidUpdateState(peripheral: CBPeripheralManager!) { // opt out from any other state var statusMsg = "Bluetooth LE error..." switch peripheral.state { case .Unknown: statusMsg = "Bluetoothe LE state is unknown" case .Unsupported: statusMsg = "Bluetooth LE is not supported on this device" case .Unauthorized: statusMsg = "Needs your approval to use Bluetooth LE on this device" case .Resetting: statusMsg = "Bluetooth LE is resetting, please wait..." case .PoweredOff: statusMsg = "Please turn on Bluetooth from settings and come back" default: statusMsg = "Bluetooth LE is ready..." } self.delegate?.blePeripheralMsgUpdate(statusMsg) if (peripheral.state != CBPeripheralManagerState.PoweredOn) { println("needs state: CBPeripheralManagerState.PoweredOn, but got \(peripheral.state.rawValue). quit.") } else { // we're in CBPeripheralManagerState.PoweredOn state now println("BLE powered on") self.openService() self.delegate?.blePeripheralIsReady() } } func peripheralManager(peripheral: CBPeripheralManager!, central: CBCentral!, didSubscribeToCharacteristic characteristic: CBCharacteristic!) { println("Central subscribed to characteristic") self.wctConnectedCentral = central self.wctSequence = .Init self.sendDataSequence() self.delegate?.blePeripheralMsgUpdate("Data requester is connected...") } func peripheralManager(peripheral: CBPeripheralManager!, central: CBCentral!, didUnsubscribeFromCharacteristic characteristic: CBCharacteristic!) { self.wctConnectedCentral = nil println("Central unsubscribed from characteristic") } func peripheralManagerIsReadyToUpdateSubscribers(peripheral: CBPeripheralManager!) { println("Underlining transmit queue is ready, ready to update central again") self.sendDataSequence() } func peripheralManager(peripheral: CBPeripheralManager!, didReceiveReadRequest request: CBATTRequest!) { println("Central read request") self.sendDataSequence() } func peripheralManager(peripheral: CBPeripheralManager!, willRestoreState dict: [NSObject : AnyObject]!) { println("willRestoreState") } func peripheralManager(peripheral: CBPeripheralManager!, didReceiveWriteRequests requests: [AnyObject]!) { println("didReceiveWriteRequests") } }
apache-2.0
5e3151a230fd608ab319a1c761f8f0bc
33.980392
181
0.611883
5.117613
false
false
false
false
jovito-royeca/Decktracker
ios/Pods/Eureka/Source/Core/HeaderFooterView.swift
4
5328
// HeaderFooterView.swift // Eureka ( https://github.com/xmartlabs/Eureka ) // // Copyright (c) 2016 Xmartlabs ( http://xmartlabs.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 /** Enumeration used to generate views for the header and footer of a section. - Class: Will generate a view of the specified class. - Callback->ViewType: Will generate the view as a result of the given closure. - NibFile: Will load the view from a nib file. */ public enum HeaderFooterProvider<ViewType: UIView> { /** * Will generate a view of the specified class. */ case Class /** * Will generate the view as a result of the given closure. */ case Callback(()->ViewType) /** * Will load the view from a nib file. */ case NibFile(name: String, bundle: NSBundle?) internal func createView() -> ViewType { switch self { case .Class: return ViewType.init() case .Callback(let builder): return builder() case .NibFile(let nibName, let bundle): return (bundle ?? NSBundle(forClass: ViewType.self)).loadNibNamed(nibName, owner: nil, options: nil)[0] as! ViewType } } } /** * Represents headers and footers of sections */ public enum HeaderFooterType { case Header, Footer } /** * Struct used to generate headers and footers either from a view or a String. */ public struct HeaderFooterView<ViewType: UIView> : StringLiteralConvertible, HeaderFooterViewRepresentable { /// Holds the title of the view if it was set up with a String. public var title: String? /// Generates the view. public var viewProvider: HeaderFooterProvider<ViewType>? /// Closure called when the view is created. Useful to customize its appearance. public var onSetupView: ((view: ViewType, section: Section) -> ())? /// A closure that returns the height for the header or footer view. public var height: (()->CGFloat)? /** This method can be called to get the view corresponding to the header or footer of a section in a specific controller. - parameter section: The section from which to get the view. - parameter type: Either header or footer. - parameter controller: The controller from which to get that view. - returns: The header or footer of the specified section. */ public func viewForSection(section: Section, type: HeaderFooterType) -> UIView? { var view: ViewType? if type == .Header { view = section.headerView as? ViewType ?? { let result = viewProvider?.createView() section.headerView = result return result }() } else { view = section.footerView as? ViewType ?? { let result = viewProvider?.createView() section.footerView = result return result }() } guard let v = view else { return nil } onSetupView?(view: v, section: section) return v } /** Initiates the view with a String as title */ public init?(title: String?){ guard let t = title else { return nil } self.init(stringLiteral: t) } /** Initiates the view with a view provider, ideal for customized headers or footers */ public init(_ provider: HeaderFooterProvider<ViewType>){ viewProvider = provider } /** Initiates the view with a String as title */ public init(unicodeScalarLiteral value: String) { self.title = value } /** Initiates the view with a String as title */ public init(extendedGraphemeClusterLiteral value: String) { self.title = value } /** Initiates the view with a String as title */ public init(stringLiteral value: String) { self.title = value } } extension UIView { func eurekaInvalidate() { setNeedsUpdateConstraints() updateConstraintsIfNeeded() setNeedsLayout() } }
apache-2.0
36598a0b90f42cee673f0d8c327d3b00
31.487805
128
0.628941
4.960894
false
false
false
false
zhenghuadong11/firstGitHub
旅游app_useSwift/旅游app_useSwift/MYScenicSpotEvaluetionCell1.swift
1
4095
// // MYScenicSpotEvaluetionCell.swift // 旅游app_useSwift // // Created by zhenghuadong on 16/4/18. // Copyright © 2016年 zhenghuadong. All rights reserved. // import Foundation import UIKit class MYScenicSpotEvaluetionCell: UITableViewCell { let headLabel = UILabel() let headLabelView = UIView() var height:CGFloat = 30 var _num:String{ set{ _numTmp = newValue createAndSetUpScenicSpotEvaluetionModels(newValue) createAndSetUpEvalutionViews() } get { return _numTmp! } } var _numTmp:String? var evalutionViews:Array<MYScenicSpotEvaluetionView> = Array<MYScenicSpotEvaluetionView>() var _scenicSpotEvaluetionModels:Array<MYScenicSpotEvaluetionModel> = Array<MYScenicSpotEvaluetionModel>() func createAndSetUpEvalutionViews() -> Void { self.height = 30 for var i1 in 0..<evalutionViews.count { evalutionViews[i1]._evalution = _scenicSpotEvaluetionModels[i1] self.height += self.evalutionViews[i1].height! } for var i2 in evalutionViews.count..<_scenicSpotEvaluetionModels.count{ let evalutionView = MYScenicSpotEvaluetionView() evalutionView._evalution = _scenicSpotEvaluetionModels[i2] print(evalutionView._evalution) self.height += evalutionView.height! evalutionViews.append(evalutionView) self.addSubview(evalutionView) } print(self.height) } func createAndSetUpScenicSpotEvaluetionModels(num:String) -> Void { var array = getArrayFromPlist("evaluetion.plist") var mArrayTmp = Array<MYScenicSpotEvaluetionModel>() for var dict in array { if dict["num"] as! String == num { let scenicSpotEvaluetionModel:MYScenicSpotEvaluetionModel = MYScenicSpotEvaluetionModel.scenicSpotEvaluetionModelWithDict(dict) mArrayTmp.append(scenicSpotEvaluetionModel) } } _scenicSpotEvaluetionModels = mArrayTmp } static func scenicSpotEvaluetionCellWithTableView(tableView:UITableView) -> MYScenicSpotEvaluetionCell{ let cellID = "MYScenicSpotEvaluetionCell" var cell:MYScenicSpotEvaluetionCell? = tableView.dequeueReusableCellWithIdentifier(cellID) as? MYScenicSpotEvaluetionCell if cell == nil { cell = MYScenicSpotEvaluetionCell.init(style: UITableViewCellStyle.Default, reuseIdentifier: cellID) } return cell! } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { self.headLabel.snp_makeConstraints { (make) in make.left.right.top.equalTo(self) make.height.equalTo(30) } var totalHeight:CGFloat = 30 for var i1 in 0..<self.subviews.count { if !self.subviews[i1].isKindOfClass(MYScenicSpotEvaluetionView) { continue; } let evaluetionView = self.subviews[i1] as! MYScenicSpotEvaluetionView self.subviews[i1].frame = CGRectMake(0,totalHeight , self.frame.width, 200) totalHeight += evaluetionView.height! } } override func didMoveToSuperview() { self.addSubview(headLabel) let attributes = [NSFontAttributeName:UIFont.init(name: "Bodoni 72", size: 15)!,NSForegroundColorAttributeName:UIColor.redColor()] let attributeString = NSAttributedString.init(string: "评价", attributes: attributes) self.headLabel.attributedText = attributeString } }
apache-2.0
75cf8d1f2deab53a73fbf36123662274
30.90625
143
0.621205
4.219008
false
false
false
false
PFei-He/PFKit-Swift
PFKit-Swift/Foundation/PFFile.swift
1
3872
// // PFFile.swift // PFKit-Swift // // Created by PFei_He on 15/11/12. // Copyright © 2015年 PF-Lib. All rights reserved. // // https://github.com/PFei-He/PFKit-Swift // // vesion: 0.1.2 // // 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 public class PFFile: NSObject { /** 创建文件 - Note: 文件存放于沙盒中的Documents文件夹中 - Parameter fileName: 文件名 - Returns: 无 */ public class func createFile(fileName: String) { let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true) let path = NSURL(fileURLWithPath: paths[0]).URLByAppendingPathComponent(fileName) let manager = NSFileManager.defaultManager() if (!manager.fileExistsAtPath(path.path!)) {//如果文件不存在则创建文件 manager.createFileAtPath(path.path!, contents:nil, attributes:nil) } } /** 读取文件 - Note: 文件存放于沙盒中的Documents文件夹中 - Parameter fileName: 文件名 - Returns: 文件中的数据 */ public class func readFile(fileName: String) -> Dictionary<String, AnyObject> { let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true) let path = NSURL(fileURLWithPath: paths[0]).URLByAppendingPathComponent(fileName) return NSDictionary(contentsOfFile: path.path!) as! Dictionary<String, AnyObject> } /** 读取JSON文件 - Note: 文件存放于main bundle中 - Parameter fileName: 文件名 - Returns: 文件中的数据 */ public class func readJSON(fileName: String) -> Dictionary<String, AnyObject> { let path = NSBundle.mainBundle().pathForResource(fileName, ofType: "json") let string = try? String(contentsOfFile: path!, encoding: NSUTF8StringEncoding) let data = string?.dataUsingEncoding(NSUTF8StringEncoding) return try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableLeaves) as! Dictionary<String, AnyObject> } /** 写入文件 - Note: 文件存放于沙盒中的Documents文件夹中 - Parameter fileName: 文件名 - Parameter params: 写入文件的参数 - Returns: 写入结果 */ public class func writeToFile(fileName: String, params: Dictionary<String, AnyObject>) -> Bool { let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true) let path = NSURL(fileURLWithPath: paths[0]).URLByAppendingPathComponent(fileName) return (params as NSDictionary).writeToFile(path.path!, atomically: true) } }
mit
832e2384476bda42c59d9203ca4bdf63
40.965517
144
0.714325
4.541045
false
false
false
false
ello/ello-ios
Sources/Controllers/Stream/Presenters/StreamFooterCellPresenter.swift
1
5615
//// /// StreamFooterCellPresenter.swift // enum InteractionVisibility { case enabled case selectedAndEnabled case selectedAndDisabled case disabled case hidden var isVisible: Bool { return self != .hidden } var isEnabled: Bool { return self == .enabled || self == .selectedAndEnabled } var isSelected: Bool { return self == .selectedAndDisabled || self == .selectedAndEnabled } } struct StreamFooterCellPresenter { static func configure( _ cell: UICollectionViewCell, streamCellItem: StreamCellItem, streamKind: StreamKind, indexPath: IndexPath, currentUser: User? ) { guard let cell = cell as? StreamFooterCell, let post = streamCellItem.jsonable as? Post else { return } let isGridView = streamCellItem.isGridView(streamKind: streamKind) configureDisplayCounts(cell, post: post, isGridView: isGridView) configureToolBarItems(cell, post: post, currentUser: currentUser, isGridView: isGridView) configureCommentControl( cell, post: post, streamCellItem: streamCellItem, streamKind: streamKind, currentUser: currentUser ) } private static func configureDisplayCounts( _ cell: StreamFooterCell, post: Post, isGridView: Bool ) { let rounding = isGridView ? 0 : 1 if cell.frame.width < 155 { cell.views.title = "" cell.reposts.title = "" cell.loves.title = "" } else { cell.views.title = post.viewsCount?.numberToHuman(rounding: rounding) cell.reposts.title = post.repostsCount?.numberToHuman(rounding: rounding) cell.loves.title = post.lovesCount?.numberToHuman(rounding: rounding) } cell.comments.title = post.commentsCount?.numberToHuman(rounding: rounding) } private static func configureToolBarItems( _ cell: StreamFooterCell, post: Post, currentUser: User?, isGridView: Bool ) { let (commentVisibility, loveVisibility, repostVisibility, shareVisibility) = toolbarItemVisibility(post: post, currentUser: currentUser, isGridView: isGridView) cell.updateToolbarItems( isGridView: isGridView, commentVisibility: commentVisibility, loveVisibility: loveVisibility, repostVisibility: repostVisibility, shareVisibility: shareVisibility ) } static func toolbarItemVisibility( post: Post, currentUser: User?, isGridView: Bool ) -> ( commentVisibility: InteractionVisibility, loveVisibility: InteractionVisibility, repostVisibility: InteractionVisibility, shareVisibility: InteractionVisibility ) { let ownPost = ( currentUser?.id == post.authorId || (post.repostAuthor?.id != nil && currentUser?.id == post.repostAuthor?.id) ) let commentingEnabled = post.author?.hasCommentingEnabled ?? true let commentVisibility: InteractionVisibility = commentingEnabled ? .enabled : .hidden let lovingEnabled = post.author?.hasLovesEnabled ?? true var loveVisibility: InteractionVisibility = .enabled if post.isLoved { loveVisibility = .selectedAndEnabled } if !lovingEnabled { loveVisibility = .hidden } let repostingEnabled = post.author?.hasRepostingEnabled ?? true var repostVisibility: InteractionVisibility = .enabled if post.isReposted { repostVisibility = .disabled } else if !repostingEnabled { repostVisibility = .hidden } else if ownPost { repostVisibility = .disabled } let sharingEnabled = post.author?.hasSharingEnabled ?? true let shareVisibility: InteractionVisibility = sharingEnabled ? .enabled : .hidden return ( commentVisibility: commentVisibility, loveVisibility: loveVisibility, repostVisibility: repostVisibility, shareVisibility: shareVisibility ) } private static func configureCommentControl( _ cell: StreamFooterCell, post: Post, streamCellItem: StreamCellItem, streamKind: StreamKind, currentUser: User? ) { if streamKind.isDetail(post: post) && currentUser == nil { let count = post.commentsCount ?? 0 let open = count > 0 cell.commentsOpened = open cell.comments.isSelected = open } else if streamKind.isDetail(post: post) { cell.commentsOpened = true cell.comments.isSelected = true } else { let isLoading = streamCellItem.state == .loading let isExpanded = streamCellItem.state == .expanded if isLoading { // this should be set via a custom accessor or method, // me thinks. // `StreamFooterCell.state = streamCellItem.state` ?? cell.commentsAnimate() cell.comments.isSelected = true } else { cell.commentsFinishAnimation() if isExpanded { cell.comments.isSelected = true cell.commentsOpened = true } else { cell.comments.isSelected = false cell.commentsOpened = false streamCellItem.state = .collapsed } } } } }
mit
976c7644cc3fd48d69d9ea5c2bded559
33.875776
97
0.608905
5.127854
false
false
false
false
ktmswzw/FeelClient
FeelingClient/AppDelegate.swift
1
12489
// // AppDelegate.swift // FeelingClient // // Created by vincent on 11/2/16. // Copyright © 2016 xecoder. All rights reserved. // import UIKit import CoreData import SwiftyDB import SwiftyJSON import Alamofire var jwt = JWTTools() var loader:PhotoUpLoader = PhotoUpLoader() @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, RCIMConnectionStatusDelegate, RCIMUserInfoDataSource, RCIMGroupInfoDataSource, RCIMReceiveMessageDelegate{ var window: UIWindow? let cacheDirectory: NSURL = { let urls = NSFileManager.defaultManager().URLsForDirectory(.CachesDirectory, inDomains: .UserDomainMask) return urls[urls.endIndex-1] }() func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. //初始化SMS-SDK ,在MOB后台注册应用并获得AppKey 和AppSecret SMSSDK.registerApp("f7b6d783cb00", withSecret: "164aabea58f5eb4723f366eafb0eadf0") RCIM.sharedRCIM().initWithAppKey("25wehl3uwkppw") //设置监听连接状态 RCIM.sharedRCIM().connectionStatusDelegate = self //设置消息接收的监听 RCIM.sharedRCIM().receiveMessageDelegate = self //设置用户信息提供者,需要提供正确的用户信息,否则SDK无法显示用户头像、用户名和本地通知 RCIM.sharedRCIM().userInfoDataSource = self //设置群组信息提供者,需要提供正确的群组信息,否则SDK无法显示群组头像、群名称和本地通知 RCIM.sharedRCIM().groupInfoDataSource = self RCIM.sharedRCIM().enableReadReceipt = true RCIM.sharedRCIM().enableTypingStatus = true //推送处理1 //注册推送,用于iOS8以上系统 application.registerUserNotificationSettings( UIUserNotificationSettings(forTypes:[.Alert, .Badge, .Sound], categories: nil)) //点击远程推送的launchOptions内容格式请参考官网文档 //http://www.rongcloud.cn/docs/ios.html#App_接收的消息推送格式 return true } //推送处理2 @available(iOS 8.0, *) func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) { //注册推送,用于iOS8以上系统 application.registerForRemoteNotifications() } //推送处理3 func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) { var rcDevicetoken = deviceToken.description rcDevicetoken = rcDevicetoken.stringByReplacingOccurrencesOfString("<", withString: "") rcDevicetoken = rcDevicetoken.stringByReplacingOccurrencesOfString(">", withString: "") rcDevicetoken = rcDevicetoken.stringByReplacingOccurrencesOfString(" ", withString: "") RCIMClient.sharedRCIMClient().setDeviceToken(rcDevicetoken) } //推送处理4 func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) { //远程推送的userInfo内容格式请参考官网文档 //http://www.rongcloud.cn/docs/ios.html#App_接收的消息推送格式 } func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) { //本地通知 } //监听连接状态变化 func onRCIMConnectionStatusChanged(status: RCConnectionStatus) { print("RCConnectionStatus = \(status.rawValue)") } //用户信息提供者。您需要在completion中返回userId对应的用户信息,SDK将根据您提供的信息显示头像和用户名 func getUserInfoWithUserId(userId: String!, completion: ((RCUserInfo!) -> Void)!) { print("用户信息提供者,getUserInfoWithUserId:\(userId)") let database = SwiftyDB(databaseName: "UserInfo") let list = database.objectsForType(UserInfo.self, matchingFilter: ["id": userId]).value! if list.count > 0 { let userinfo = list[0] completion(RCUserInfo(userId: userId, name: userinfo.nickname, portrait: userinfo.avatar)) } else{ let params = [:] let headers = jwt.getHeader(jwt.token, myDictionary: Dictionary<String,String>()) NetApi().makeCallBean(Alamofire.Method.GET, section: "user/\(userId)", headers: headers, params: (params as! [String : AnyObject])) { (res:Response<UserInfo, NSError>) in switch (res.result) { case .Success(let userInfo): database.addObject(userInfo, update: true) completion(RCUserInfo(userId: userId, name: userInfo.nickname, portrait: userInfo.avatar)) break case .Failure(let error): completion(RCUserInfo(userId: userId, name: "新用户", portrait: "")) print(error) break } } } } //群组信息提供者。您需要在Block中返回groupId对应的群组信息,SDK将根据您提供的信息显示头像和群组名 func getGroupInfoWithGroupId(groupId: String!, completion: ((RCGroup!) -> Void)!) { print("群组信息提供者,getGroupInfoWithGroupId:\(groupId)") //简单的示例,根据groupId获取对应的群组信息并返回 //建议您在本地做一个缓存,只有缓存没有该群组信息的情况下,才去您的服务器获取,以提高用户体验 if (groupId == "group01") { //如果您提供的头像地址是http连接,在iOS9以上的系统中,请设置使用http,否则无法正常显示 //具体可以参考Info.plist中"App Transport Security Settings->Allow Arbitrary Loads" completion(RCGroup(groupId: groupId, groupName: "第一个群", portraitUri: "http://www.rongcloud.cn/images/newVersion/logo/aipai.png")) } else { completion(RCGroup(groupId: groupId, groupName: "unknown", portraitUri: "http://www.rongcloud.cn/images/newVersion/logo/qiugongl.png")) } } //监听消息接收 func onRCIMReceiveMessage(message: RCMessage!, left: Int32) { if (left != 0) { print("收到一条消息,当前的接收队列中还剩余\(left)条消息未接收,您可以等待left为0时再刷新UI以提高性能") } else { print("收到一条消息") } } 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:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // 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 "com.xecoder.FeelingClient" 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("FeelingClient", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns 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("SingleViewCoreData.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) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } 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 { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
mit
46fb5e9c77383909be09de57de675e84
46.858921
291
0.68077
4.9974
false
false
false
false
niilohlin/Fuzi
Sources/Helpers.swift
6
3715
// Helpers.swift // Copyright (c) 2015 Ce Zheng // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import libxml2 // Public Helpers /// For printing an `XMLNode` extension XMLNode: CustomStringConvertible, CustomDebugStringConvertible { /// String printed by `print` function public var description: String { return self.rawXML } /// String printed by `debugPrint` function public var debugDescription: String { return self.rawXML } } /// For printing an `XMLDocument` extension XMLDocument: CustomStringConvertible, CustomDebugStringConvertible { /// String printed by `print` function public var description: String { return self.root?.rawXML ?? "" } /// String printed by `debugPrint` function public var debugDescription: String { return self.root?.rawXML ?? "" } } // Internal Helpers internal extension String { subscript (nsrange: NSRange) -> String { let start = utf16.index(utf16.startIndex, offsetBy: nsrange.location) let end = utf16.index(start, offsetBy: nsrange.length) return String(utf16[start..<end])! } } // Just a smiling helper operator making frequent UnsafePointer -> String cast prefix operator ^-^ internal prefix func ^-^ <T> (ptr: UnsafePointer<T>?) -> String? { if let ptr = ptr { return String(validatingUTF8: UnsafeRawPointer(ptr).assumingMemoryBound(to: CChar.self)) } return nil } internal prefix func ^-^ <T> (ptr: UnsafeMutablePointer<T>?) -> String? { if let ptr = ptr { return String(validatingUTF8: UnsafeMutableRawPointer(ptr).assumingMemoryBound(to: CChar.self)) } return nil } internal struct LinkedCNodes: Sequence, IteratorProtocol { internal let head: xmlNodePtr? internal let types: [xmlElementType] fileprivate var cursor: xmlNodePtr? mutating func next() -> xmlNodePtr? { defer { if let ptr = cursor { cursor = ptr.pointee.next } } while let ptr = cursor, !types.contains(where: { $0 == ptr.pointee.type }) { cursor = ptr.pointee.next } return cursor } init(head: xmlNodePtr?, types: [xmlElementType] = [XML_ELEMENT_NODE]) { self.head = head self.cursor = head self.types = types } } internal func cXMLNode(_ node: xmlNodePtr?, matchesTag tag: String, inNamespace ns: String?) -> Bool { guard let name = ^-^node?.pointee.name else { return false } var matches = name.compare(tag, options: .caseInsensitive) == .orderedSame if let ns = ns { guard let prefix = ^-^node?.pointee.ns.pointee.prefix else { return false } matches = matches && (prefix.compare(ns, options: .caseInsensitive) == .orderedSame) } return matches }
mit
fbfb4b30a5e61a5290a00952a9a55c6c
30.752137
102
0.708748
4.216799
false
false
false
false
hffmnn/Swiftz
Swiftz/DictionaryExt.swift
2
1625
// // DictionaryExt.swift // swiftz // // Created by Maxwell Swadling on 5/06/2014. // Copyright (c) 2014 Maxwell Swadling. All rights reserved. // /// Maps a function taking key-value pairs to key-value pairs over a dictionary. public func map<K, V, T, U>(#dict : Dictionary<K, V>) -> ((K, V) -> (T, U)) -> Dictionary<T, U> { return { transform in var d = Dictionary<T, U>(minimumCapacity: dict.count) for (key, value) in dict { switch transform(key, value) { case let (k, v): d.updateValue(v, forKey: k) } } return d } } /// Returns a dictionary consisting of all the key-value pairs satisfying a predicate. public func filter<K, V>(#dict : Dictionary<K, V>) -> ((K, V) -> Bool) -> Dictionary<K, V> { return { pred in var f = Dictionary<K, V>() for (k, v) in dict { if pred(k, v) { f[k] = v } } return f } } /// Folds a reducing function over all the key-value pairs in a dictionary. public func reduce<K, V, A>(#dict : Dictionary<K, V>) -> A -> ((key : K, val : V, start : A) -> A) -> A { return { start in { reduce in var reduced:A? for (k,v) in dict { reduced = reduce(key:k, val:v, start:start) } switch reduced { case let .Some(a): return a case .None: return start } } } } /// Maps key-value pairs to new values for each key. public func mapValues<KeyType, ElementType, V>(#dict: Dictionary<KeyType, ElementType>, transform: (KeyType, ElementType) -> V) -> Dictionary<KeyType, V> { var d = Dictionary<KeyType, V>(minimumCapacity: dict.count) for (key, value) in dict { d.updateValue(transform(key, value), forKey: key) } return d }
bsd-3-clause
48ec051fe1cb9b23b3b5c76b66411531
26.542373
155
0.628923
2.927928
false
false
false
false
zero2launch/z2l-ios-social-network
InstagramClone/Post.swift
1
1226
// // Post.swift // InstagramClone // // Created by The Zero2Launch Team on 12/26/16. // Copyright © 2016 The Zero2Launch Team. All rights reserved. // import Foundation import FirebaseAuth class Post { var caption: String? var photoUrl: String? var uid: String? var id: String? var likeCount: Int? var likes: Dictionary<String, Any>? var isLiked: Bool? var ratio: CGFloat? var videoUrl: String? } extension Post { static func transformPostPhoto(dict: [String: Any], key: String) -> Post { let post = Post() post.id = key post.caption = dict["caption"] as? String post.photoUrl = dict["photoUrl"] as? String post.videoUrl = dict["videoUrl"] as? String post.uid = dict["uid"] as? String post.likeCount = dict["likeCount"] as? Int post.likes = dict["likes"] as? Dictionary<String, Any> post.ratio = dict["ratio"] as? CGFloat if let currentUserId = FIRAuth.auth()?.currentUser?.uid { if post.likes != nil { post.isLiked = post.likes![currentUserId] != nil } } return post } static func transformPostVideo() { } }
mit
8dab32d492cc1c5550a13a4112319597
25.630435
78
0.59102
4.029605
false
false
false
false
JJJayway/ReactiveSwift
Reactive/SinkOperations.swift
1
7432
// // SinkOperations.swift // Reactive // // Created by Jens Jakob Jensen on 25/08/14. // Copyright (c) 2014 Jayway. All rights reserved. // import Dispatch.queue import Foundation.NSDate // To get NSTimeInterval import class Foundation.NSError public func map<I,O>(block: I -> O) (sink: TypesIO<I,O>.OutputSink) -> TypesIO<I,O>.InputSink { return SinkOf { event in if let value = event.value { sink.put(Event.fromValue(block(value))) } else { sink.put(event.convertNonValue()) } } } public func filter<T>(block: T -> Bool) (sink: Types<T>.Sink) -> Types<T>.Sink { return SinkOf { event in if let value = event.value { if block(value) { sink.put(event) } } else { sink.put(event) } } } /// Also see merge() public func flattenMap<I,O>(block: I -> TypesIO<I,O>.OutputEmitter) (sink: TypesIO<I,O>.OutputSink) -> TypesIO<I,O>.InputSink { return map(block) .. merge .. sink } /// Actually fold(), but the Swift standard library calls this `reduce`, hence the naming. public func reduce<T, U>(#initial: U, combine: (U, T) -> U) (sink: Types<U>.Sink) -> Types<T>.Sink { var runningValue = initial return SinkOf { event in if let value = event.value { runningValue = combine(runningValue, value) } else if event.isCompleted { sink.put(Event.fromValue(runningValue)) sink.put(.Completed) } else { sink.put(event.convertNonValue()) } } } // MARK: - /// Concatenates a series of emitters, first forwarding the values from the first emitter, /// then, when that emitter ends, forwards values from the next, and so on. /// /// If some emitter (including the emitter of emitters) sends the .Error event, or the .Stopped event, that event will be forwarded and event processing ends. /// Other than that, event processing continues until all emitters (including the emitter of emitters) have completed. public func concat<T>(var sink: Types<T>.Sink) -> Types<T>.SinkOfEmitters { let queue = dispatch_queue_create("Reactive.concat", DISPATCH_QUEUE_SERIAL) // Serialize incoming emitters var emitterCount = 0 var mainEmitterHasEnded = false var valid = true // Becomes false if some emitter fails or stops sink = eventIntercept { if $0.isError || $0.isStopped { valid = false } } .. eventFilter { // Only send last .Completed // NOTE: This is run on `queue` if !$0.isCompleted { return true // Forward all non-.Completed events } return mainEmitterHasEnded && emitterCount == 0 // Only forward .Completed if all emitters have ended } .. sink return SinkOf { event in if !valid { return // Some emitter failed or stopped. We have ended. } dispatch_sync(queue) { dispatch_suspend(queue) // Do not accept more emitters until this has ended if let emitter = event.value { emitterCount++ emitter .. eventFilter { _ in valid } // Ignore remaining events if we got an .Error or .Stopped event .. eventIntercept { if $0.isEnd { emitterCount--; dispatch_resume(queue) } } // Accept next emitter .. sink } else { // The emitter of emitters has ended mainEmitterHasEnded = true sink.put(event.convertNonValue()) dispatch_resume(queue) } } } } /// Merge a series of emitters, forwarding their values as they come in. /// /// If some emitter (including the emitter of emitters) sends the .Error event, or the .Stopped event, that event will be forwarded and event processing ends. /// Other than that, event processing continues until all emitters (including the emitter of emitters) have completed. public func merge<T>(var sink: Types<T>.Sink) -> Types<T>.SinkOfEmitters { let queue = dispatch_queue_create("Reactive.merge", DISPATCH_QUEUE_SERIAL) // Serialize emits to the sink var emitterCount = 0 var mainEmitterHasEnded = false var valid = true // Becomes false if some emitter fails or stops sink = eventIntercept { if $0.isError || $0.isStopped { valid = false } } .. eventFilter { // Only send last .Completed // NOTE: This is run on `queue` if !$0.isCompleted { return true // Forward all non-.Completed events } return mainEmitterHasEnded && emitterCount == 0 // Only forward .Completed if all emitters have ended } .. sink return SinkOf { event in if !valid { return // Some emitter failed or stopped. We have ended. } if let emitter = event.value { dispatch_async(queue) { emitterCount++ return } emitter .. eventFilter { _ in valid } // Ignore remaining events if we got an .Error or .Stopped event .. onQueue (queue) .. eventIntercept { if $0.isCompleted { emitterCount-- } } .. sink } else { // No more emitters dispatch_async(queue) { mainEmitterHasEnded = true sink.put(event.convertNonValue()) } } } } // MARK: - /// Forward events on the given queue (asynchronously) public func onQueue<T>(queue: dispatch_queue_t) (sink: Types<T>.Sink) -> Types<T>.Sink { return SinkOf { event in dispatch_async(queue) { sink.put(event) } } } public func onMain<T>(sink: Types<T>.Sink) -> Types<T>.Sink { return onQueue(dispatch_get_main_queue())(sink: sink) } public func throttle<T>(minInterval: NSTimeInterval) (sink: Types<T>.Sink) -> Types<T>.Sink { var nextAcceptTime = NSDate() return SinkOf { event in NSThread.sleepUntilDate(nextAcceptTime) nextAcceptTime = NSDate(timeIntervalSinceNow: minInterval) sink.put(event) } } // MARK: - public func intercept<T>(onValue: T -> () = {_ in}, onCompleted: () -> () = {}, onError: (NSError) -> () = {_ in}, onStopped: () -> () = {}, onEnd: () -> () = {}) -> (sink: Types<T>.Sink) -> Types<T>.Sink { return eventIntercept { event in switch event { case .Value(let valueBox): onValue(valueBox.unbox()) case .Completed: onCompleted() onEnd() case .Error(let error): onError(error) onEnd() case .Stopped: onStopped() onEnd() } } } public func valueIntercept<T>(onValue: T -> ()) -> (sink: Types<T>.Sink) -> Types<T>.Sink { return eventIntercept { event in if let value = event.value { onValue(value) } } } public func eventFilter<T>(block: Event<T> -> Bool) (sink: Types<T>.Sink) -> Types<T>.Sink { return SinkOf { event in if block(event) { sink.put(event) } } } public func eventIntercept<T>(block: Event<T> -> ()) (sink: Types<T>.Sink) -> Types<T>.Sink { return SinkOf { event in block(event) sink.put(event) } }
mit
b64561853e71de5293635abb54966819
32.628959
206
0.57683
4.142698
false
false
false
false
dcunited001/SwiftState
SwiftState/StateRoute.swift
1
2206
// // StateRoute.swift // SwiftState // // Created by Yasuhiro Inami on 2014/08/04. // Copyright (c) 2014年 Yasuhiro Inami. All rights reserved. // public struct StateRoute<S: StateType> { internal typealias Condition = ((transition: Transition) -> Bool) private typealias State = S private typealias Transition = StateTransition<State> public let transition: Transition public let condition: Condition? public init(transition: Transition, condition: Condition?) { self.transition = transition self.condition = condition } public init(transition: Transition, @autoclosure(escaping) condition: () -> Bool) { self.init(transition: transition, condition: { t in condition() }) } public func toTransition() -> Transition { return self.transition } public func toRouteChain() -> StateRouteChain<State> { var routes: [StateRoute<State>] = [] routes += [self] return StateRouteChain(routes: routes) } } //-------------------------------------------------- // MARK: - Custom Operators //-------------------------------------------------- /// e.g. [.State0, .State1] => .State2, allowing [0 => 2, 1 => 2] public func => <S: StateType>(leftStates: [S], right: S) -> StateRoute<S> { // NOTE: don't reuse "nil => nil + condition" for efficiency return StateRoute(transition: nil => right, condition: { transition -> Bool in return leftStates.contains(transition.fromState) }) } /// e.g. .State0 => [.State1, .State2], allowing [0 => 1, 0 => 2] public func => <S: StateType>(left: S, rightStates: [S]) -> StateRoute<S> { return StateRoute(transition: left => nil, condition: { transition -> Bool in return rightStates.contains(transition.toState) }) } /// e.g. [.State0, .State1] => [.State2, .State3], allowing [0 => 2, 0 => 3, 1 => 2, 1 => 3] public func => <S: StateType>(leftStates: [S], rightStates: [S]) -> StateRoute<S> { return StateRoute(transition: nil => nil, condition: { transition -> Bool in return leftStates.contains(transition.fromState) && rightStates.contains(transition.toState) }) }
mit
ee73651f3f6cd60028f66bbb5af669d8
30.5
100
0.602541
3.971171
false
false
false
false
airbnb/lottie-ios
Sources/Private/MainThread/NodeRenderSystem/Extensions/ItemsExtension.swift
2
4219
// // ItemsExtension.swift // lottie-swift // // Created by Brandon Withrow on 1/18/19. // import Foundation // MARK: - NodeTree final class NodeTree { var rootNode: AnimatorNode? = nil var transform: ShapeTransform? = nil var renderContainers: [ShapeContainerLayer] = [] var paths: [PathOutputNode] = [] var childrenNodes: [AnimatorNode] = [] } extension Array where Element == ShapeItem { func initializeNodeTree() -> NodeTree { let nodeTree = NodeTree() for item in self { guard item.hidden == false, item.type != .unknown else { continue } if let fill = item as? Fill { let node = FillNode(parentNode: nodeTree.rootNode, fill: fill) nodeTree.rootNode = node nodeTree.childrenNodes.append(node) } else if let stroke = item as? Stroke { let node = StrokeNode(parentNode: nodeTree.rootNode, stroke: stroke) nodeTree.rootNode = node nodeTree.childrenNodes.append(node) } else if let gradientFill = item as? GradientFill { let node = GradientFillNode(parentNode: nodeTree.rootNode, gradientFill: gradientFill) nodeTree.rootNode = node nodeTree.childrenNodes.append(node) } else if let gradientStroke = item as? GradientStroke { let node = GradientStrokeNode(parentNode: nodeTree.rootNode, gradientStroke: gradientStroke) nodeTree.rootNode = node nodeTree.childrenNodes.append(node) } else if let ellipse = item as? Ellipse { let node = EllipseNode(parentNode: nodeTree.rootNode, ellipse: ellipse) nodeTree.rootNode = node nodeTree.childrenNodes.append(node) } else if let rect = item as? Rectangle { let node = RectangleNode(parentNode: nodeTree.rootNode, rectangle: rect) nodeTree.rootNode = node nodeTree.childrenNodes.append(node) } else if let star = item as? Star { switch star.starType { case .none: continue case .polygon: let node = PolygonNode(parentNode: nodeTree.rootNode, star: star) nodeTree.rootNode = node nodeTree.childrenNodes.append(node) case .star: let node = StarNode(parentNode: nodeTree.rootNode, star: star) nodeTree.rootNode = node nodeTree.childrenNodes.append(node) } } else if let shape = item as? Shape { let node = ShapeNode(parentNode: nodeTree.rootNode, shape: shape) nodeTree.rootNode = node nodeTree.childrenNodes.append(node) } else if let trim = item as? Trim { let node = TrimPathNode(parentNode: nodeTree.rootNode, trim: trim, upstreamPaths: nodeTree.paths) nodeTree.rootNode = node nodeTree.childrenNodes.append(node) } else if let roundedCorners = item as? RoundedCorners { let node = RoundedCornersNode( parentNode: nodeTree.rootNode, roundedCorners: roundedCorners, upstreamPaths: nodeTree.paths) nodeTree.rootNode = node nodeTree.childrenNodes.append(node) } else if let xform = item as? ShapeTransform { nodeTree.transform = xform continue } else if let group = item as? Group { let tree = group.items.initializeNodeTree() let node = GroupNode(name: group.name, parentNode: nodeTree.rootNode, tree: tree) nodeTree.rootNode = node nodeTree.childrenNodes.append(node) /// Now add all child paths to current tree nodeTree.paths.append(contentsOf: tree.paths) nodeTree.renderContainers.append(node.container) } else if item is Repeater { LottieLogger.shared.warn(""" The Main Thread rendering engine doesn't currently support repeaters. To play an animation with repeaters, you can use the Core Animation rendering engine instead. """) } if let pathNode = nodeTree.rootNode as? PathNode { //// Add path container to the node tree nodeTree.paths.append(pathNode.pathOutput) } if let renderNode = nodeTree.rootNode as? RenderNode { nodeTree.renderContainers.append(ShapeRenderLayer(renderer: renderNode.renderer)) } } return nodeTree } }
apache-2.0
936994d0bf542e8286eeff50af8e480b
38.429907
105
0.658687
4.265925
false
false
false
false
Mazy-ma/DemoBySwift
FaceDetectionByCoreImage/FaceDetectionByCoreImage/ViewController.swift
1
3744
// // ViewController.swift // FaceDetectionByCoreImage // // Created by Mazy on 2017/4/28. // Copyright © 2017年 Mazy. All rights reserved. // import UIKit import CoreImage class ViewController: UIViewController { @IBOutlet weak var personPicView: UIImageView! let imagePicker = UIImagePickerController() var faceBox: UIView? override func viewDidLoad() { super.viewDidLoad() imagePicker.delegate = self detect() } func detect() { faceBox?.removeFromSuperview() guard let personciImage = CIImage(image: personPicView.image!) else { return } let accuracy = [CIDetectorAccuracy: CIDetectorAccuracyLow] let faceDetector = CIDetector(ofType: CIDetectorTypeFace, context: nil, options: accuracy) let faces = faceDetector?.features(in: personciImage) // issue let ciImageSize = personciImage.extent.size var transform = CGAffineTransform(scaleX: 1, y: -1) transform = transform.translatedBy(x: 0, y: -ciImageSize.height) if (faces?.count)! > 0 { let face = faces?.first as! CIFaceFeature var faceViewBounds = face.bounds.applying(transform) let viewSize = personPicView.bounds.size let scale = min(viewSize.width/ciImageSize.width,viewSize.height/ciImageSize.height) let offsetX = (viewSize.width - ciImageSize.width*scale)/2 let offsetY = (viewSize.height - ciImageSize.height*scale)/2 faceViewBounds = faceViewBounds.applying(CGAffineTransform(scaleX: scale, y: scale)) faceViewBounds.origin.x += offsetX faceViewBounds.origin.y += offsetY faceBox = UIView(frame: faceViewBounds) faceBox?.layer.borderWidth = 3 faceBox?.layer.borderColor = UIColor.red.cgColor faceBox?.backgroundColor = .clear personPicView.addSubview(faceBox!) if face.hasLeftEyePosition { print("Left eye bounds are \(face.leftEyePosition)") } if face.hasRightEyePosition { print("Right eye bounds are \(face.rightEyePosition)") } } else { let alertVC = UIAlertController(title: "Alert", message: "\n Not Detect Face", preferredStyle: .alert) let cancel = UIAlertAction(title: "OK", style: .cancel, handler: nil) alertVC.addAction(cancel) present(alertVC, animated: true, completion: nil) } } @IBAction func pickerImageAction() { // 检查是否有访问权限 if !UIImagePickerController.isSourceTypeAvailable(.photoLibrary) { return } imagePicker.allowsEditing = false imagePicker.sourceType = .photoLibrary present(imagePicker, animated: true, completion: nil) } @IBAction func startDetec() { detect() } } extension ViewController: UIImagePickerControllerDelegate,UINavigationControllerDelegate { func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { if let pickerImage = info[UIImagePickerControllerOriginalImage] as? UIImage { personPicView.image = pickerImage } dismiss(animated: true, completion: nil) detect() } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { dismiss(animated: true, completion: nil) } }
apache-2.0
803461c82f96573b006c25619f4c0676
30.285714
119
0.603008
5.280851
false
false
false
false
guerrero/mocha
Mocha/CustomTableViewCell.swift
1
1143
// // CustomTableViewCell.swift // Mocha // // Created by AG on 20/1/15. // Copyright (c) 2015 AG. All rights reserved. // import UIKit class CustomTableViewCell: UITableViewCell { @IBOutlet weak var classNameLabel: UILabel! @IBOutlet weak var widthLabel: UILabel! @IBOutlet weak var heightLabel: UILabel! @IBOutlet weak var colorView: UIView! // Set colorView as rounded view with border color and inner layer func setIdColor(color: UIColor) { colorView.layer.borderColor = UIColor.blackColor().CGColor colorView.layer.borderWidth = 2 colorView.layer.cornerRadius = colorView.frame.size.height / 2 var innerElement: CALayer = CALayer() innerElement.frame = CGRectMake(2, 2, colorView.frame.size.width - 4, colorView.frame.size.height - 4) innerElement.cornerRadius = (colorView.frame.size.width - 2) / 2 innerElement.borderColor = UIColor.whiteColor().CGColor innerElement.borderWidth = 2 innerElement.backgroundColor = color.CGColor colorView.layer.addSublayer(innerElement) } }
mit
722e060aee93b5d24085d1a4918ba56a
33.636364
114
0.672791
4.517787
false
false
false
false
hejunbinlan/swiftmi-app
swiftmi/swiftmi/MyController.swift
4
4192
// // MyController.swift // swiftmi // // Created by yangyin on 15/4/14. // Copyright (c) 2015年 swiftmi. All rights reserved. // import UIKit import Kingfisher import Alamofire import SwiftyJSON class MyController: UITableViewController { var profileHeaderView:ProfileHeaderView? var currentUser:Users? @IBOutlet weak var logoutCell: UITableViewCell! @IBOutlet weak var signatureLabel: UILabel! @IBOutlet weak var emailLabel: UILabel! override func viewDidAppear(animated: Bool) { loadCurrentUser() self.clearAllNotice() } private func loadCurrentUser() { if currentUser == nil { var token = KeychainWrapper.stringForKey("token") if token != nil { var dalUser = UsersDal() currentUser = dalUser.getCurrentUser() } if currentUser != nil { self.profileHeaderView?.setData(self.currentUser!) self.emailLabel.text = self.currentUser?.email self.signatureLabel.text = self.currentUser?.signature self.logoutCell.hidden = false }else { self.logoutCell.hidden = true } } } override func viewDidLoad() { super.viewDidLoad() self.setView() } func setView() { self.profileHeaderView = ProfileHeaderView.viewFromNib()! self.profileHeaderView?.frame = CGRectMake(0,0,self.view.frame.width,280); self.tableView.tableHeaderView = self.profileHeaderView! self.profileHeaderView?.tapLoginCallBack = { let toViewController:LoginController = Utility.GetViewController("loginController") self.navigationController?.pushViewController(toViewController, animated: true) return true } } private func logout() { if KeychainWrapper.hasValueForKey("token") { KeychainWrapper.removeObjectForKey("token") self.currentUser = nil Router.token = "" } self.emailLabel.text = "" self.signatureLabel.text = "" self.profileHeaderView?.resetData() self.tableView.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func scrollViewDidScroll(scrollView: UIScrollView) { self.profileHeaderView?.scrollViewDidScroll(scrollView) } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if indexPath.section == 2 && indexPath.row == 0 { self.logout() } else if indexPath.section == 1 && indexPath.row == 0 { var url = NSURL(string: "itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=993402332") UIApplication.sharedApplication().openURL(url!) //self.logout() /* var webViewController:WebViewController = Utility.GetViewController("webViewController") webViewController.webUrl = "http://www.swiftmi.com/timeline" webViewController.title = " 关于Swift迷 " webViewController.isPop = true self.navigationController?.pushViewController(webViewController, animated: true)*/ } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
92f693b0cfdf1274b0ac3b00a284ff1c
26.708609
151
0.578394
5.700272
false
false
false
false
watson-developer-cloud/ios-sdk
Sources/AssistantV1/Models/RuntimeResponseGenericRuntimeResponseTypeUserDefined.swift
1
2773
/** * (C) Copyright IBM Corp. 2021. * * 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 IBMSwiftSDKCore /** RuntimeResponseGenericRuntimeResponseTypeUserDefined. Enums with an associated value of RuntimeResponseGenericRuntimeResponseTypeUserDefined: RuntimeResponseGeneric */ public struct RuntimeResponseGenericRuntimeResponseTypeUserDefined: Codable, Equatable { /** The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. */ public var responseType: String /** An object containing any properties for the user-defined response type. */ public var userDefined: [String: JSON] /** An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. */ public var channels: [ResponseGenericChannel]? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case responseType = "response_type" case userDefined = "user_defined" case channels = "channels" } /** Initialize a `RuntimeResponseGenericRuntimeResponseTypeUserDefined` with member variables. - parameter responseType: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - parameter userDefined: An object containing any properties for the user-defined response type. - parameter channels: An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. - returns: An initialized `RuntimeResponseGenericRuntimeResponseTypeUserDefined`. */ public init( responseType: String, userDefined: [String: JSON], channels: [ResponseGenericChannel]? = nil ) { self.responseType = responseType self.userDefined = userDefined self.channels = channels } }
apache-2.0
048abf1e337065c8e9200a6f402ba061
35.973333
120
0.721601
5.005415
false
false
false
false
gcba/hermes
sdks/swift/Pods/SwifterSwift/Sources/Extensions/Foundation/OptionalExtensions.swift
1
1259
// // OptionalExtensions.swift // SwifterSwift // // Created by Omar Albeik on 3/3/17. // Copyright © 2017 omaralbeik. All rights reserved. // import Foundation public extension Optional { /// SwifterSwift: Get self of default value (if self is nil). /// /// let foo: String? = nil /// print(foo.unwrapped(or: "bar")) -> "bar" /// /// let bar: String? = "bar" /// print(bar.unwrapped(or: "foo")) -> "bar" /// /// - Parameter defaultValue: default value to return if self is nil. /// - Returns: self if not nil or default value if nil. public func unwrapped(or defaultValue: Wrapped) -> Wrapped { // http://www.russbishop.net/improving-optionals return self ?? defaultValue } /// SwifterSwift: Runs a block to Wrapped if not nil /// /// let foo: String? = nil /// foo.run { unwrappedFoo in /// // block will never run sice foo is nill /// print(unwrappedFoo) /// } /// /// let bar: String? = "bar" /// bar.run { unwrappedBar in /// // block will run sice bar is not nill /// print(unwrappedBar) -> "bar" /// } /// /// - Parameter block: a block to run if self is not nil. public func run(_ block: (Wrapped) -> Void) { // http://www.russbishop.net/improving-optionals _ = self.map(block) } }
mit
87281e8e4fcbdc49d0960de94be1ba55
24.673469
70
0.621622
2.995238
false
false
false
false
jianwoo/WordPress-iOS
WordPress/Classes/ViewRelated/Reader/WPContentSyncHelper.swift
2
2618
import UIKit @objc protocol WPContentSyncHelperDelegate: NSObjectProtocol { func syncHelper(syncHelper:WPContentSyncHelper, syncContentWithUserInteraction userInteraction: Bool, success: ((count: Int, hasMore: Bool) -> Void)?, failure: ((error: NSError) -> Void)?) func syncHelper(syncHelper:WPContentSyncHelper, syncMoreWithSuccess success: ((count: Int, hasMore: Bool) -> Void)?, failure: ((error: NSError) -> Void)?) optional func syncContentEnded() optional func hasNoMoreContent() } class WPContentSyncHelper: NSObject { weak var delegate: WPContentSyncHelperDelegate? var isSyncing:Bool = false var isLoadingMore:Bool = false var hasMoreContent:Bool = true { didSet { if hasMoreContent == oldValue { return } if hasMoreContent == false { delegate?.hasNoMoreContent?() } } } // MARK: - Syncing func syncContent() -> Bool { return syncContentWithUserInteraction(false) } func syncContentWithUserInteraction() -> Bool { return syncContentWithUserInteraction(true) } func syncContentWithUserInteraction(userInteraction:Bool) -> Bool { if isSyncing { return false } isSyncing = true delegate?.syncHelper(self, syncContentWithUserInteraction: userInteraction, success: { [weak self] (count: Int, hasMore: Bool) -> Void in if let weakSelf = self { weakSelf.hasMoreContent = hasMore weakSelf.syncContentEnded() } }, failure: { [weak self] (error: NSError) -> Void in if let weakSelf = self { weakSelf.syncContentEnded() } }) return true } func syncMoreContent() -> Bool { if isSyncing { return false } isSyncing = true isLoadingMore = true delegate?.syncHelper(self, syncMoreWithSuccess: { [weak self] (count: Int, hasMore: Bool) -> Void in if let weakSelf = self { weakSelf.hasMoreContent = hasMore weakSelf.syncContentEnded() } }, failure: { [weak self] (error: NSError) -> Void in if let weakSelf = self { weakSelf.syncContentEnded() } }) return true } // MARK: - Private Methods private func syncContentEnded() { isSyncing = false isLoadingMore = false delegate?.syncContentEnded?() } }
gpl-2.0
74f0063858f315e0515bb2f0a320936e
25.444444
192
0.578304
5.257028
false
false
false
false
klundberg/swift-corelibs-foundation
Foundation/NSXMLDTD.swift
1
6410
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 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 the list of Swift project authors // import CoreFoundation /*! @class NSXMLDTD @abstract Defines the order, repetition, and allowable values for a document */ public class XMLDTD : XMLNode { internal var _xmlDTD: _CFXMLDTDPtr { return _CFXMLDTDPtr(_xmlNode) } public convenience init(contentsOf url: URL, options mask: Int) throws { let urlString = url.absoluteString guard let node = _CFXMLParseDTD(urlString!) else { //TODO: throw error fatalError("parsing dtd string failed") } self.init(ptr: node) } public convenience init(data: Data, options mask: Int) throws { var unmanagedError: Unmanaged<CFError>? = nil guard let node = _CFXMLParseDTDFromData(data._cfObject, &unmanagedError) else { if let error = unmanagedError?.takeRetainedValue()._nsObject { throw error } //TODO: throw a generic error? fatalError("parsing dtd from data failed") } self.init(ptr: node) } //primitive /*! @method publicID @abstract Sets the public id. This identifier should be in the default catalog in /etc/xml/catalog or in a path specified by the environment variable XML_CATALOG_FILES. When the public id is set the system id must also be set. */ public var publicID: String? { get { return _CFXMLDTDExternalID(_xmlDTD)?._swiftObject } set { if let value = newValue { _CFXMLDTDSetExternalID(_xmlDTD, value) } else { _CFXMLDTDSetExternalID(_xmlDTD, nil) } } } /*! @method systemID @abstract Sets the system id. This should be a URL that points to a valid DTD. */ public var systemID: String? { get { return _CFXMLDTDSystemID(_xmlDTD)?._swiftObject } set { if let value = newValue { _CFXMLDTDSetSystemID(_xmlDTD, value) } else { _CFXMLDTDSetSystemID(_xmlDTD, nil) } } } /*! @method insertChild:atIndex: @abstract Inserts a child at a particular index. */ public func insertChild(_ child: XMLNode, at index: Int) { _insertChild(child, atIndex: index) } //primitive /*! @method insertChildren:atIndex: @abstract Insert several children at a particular index. */ public func insertChildren(_ children: [XMLNode], at index: Int) { _insertChildren(children, atIndex: index) } /*! @method removeChildAtIndex: @abstract Removes a child at a particular index. */ public func removeChild(at index: Int) { _removeChildAtIndex(index) } //primitive /*! @method setChildren: @abstract Removes all existing children and replaces them with the new children. Set children to nil to simply remove all children. */ public func setChildren(_ children: [XMLNode]?) { _setChildren(children) } //primitive /*! @method addChild: @abstract Adds a child to the end of the existing children. */ public func addChild(_ child: XMLNode) { _addChild(child) } /*! @method replaceChildAtIndex:withNode: @abstract Replaces a child at a particular index with another child. */ public func replaceChild(at index: Int, with node: XMLNode) { _replaceChildAtIndex(index, withNode: node) } /*! @method entityDeclarationForName: @abstract Returns the entity declaration matching this name. */ public func entityDeclaration(forName name: String) -> XMLDTDNode? { guard let node = _CFXMLDTDGetEntityDesc(_xmlDTD, name) else { return nil } return XMLDTDNode._objectNodeForNode(node) } //primitive /*! @method notationDeclarationForName: @abstract Returns the notation declaration matching this name. */ public func notationDeclaration(forName name: String) -> XMLDTDNode? { guard let node = _CFXMLDTDGetNotationDesc(_xmlDTD, name) else { return nil } return XMLDTDNode._objectNodeForNode(node) } //primitive /*! @method elementDeclarationForName: @abstract Returns the element declaration matching this name. */ public func elementDeclaration(forName name: String) -> XMLDTDNode? { guard let node = _CFXMLDTDGetElementDesc(_xmlDTD, name) else { return nil } return XMLDTDNode._objectNodeForNode(node) } //primitive /*! @method attributeDeclarationForName: @abstract Returns the attribute declaration matching this name. */ public func attributeDeclaration(forName name: String, elementName: String) -> XMLDTDNode? { guard let node = _CFXMLDTDGetAttributeDesc(_xmlDTD, elementName, name) else { return nil } return XMLDTDNode._objectNodeForNode(node) } //primitive /*! @method predefinedEntityDeclarationForName: @abstract Returns the predefined entity declaration matching this name. @discussion The five predefined entities are <ul><li>&amp;lt; - &lt;</li><li>&amp;gt; - &gt;</li><li>&amp;amp; - &amp;</li><li>&amp;quot; - &quot;</li><li>&amp;apos; - &amp;</li></ul> */ public class func predefinedEntityDeclaration(forName name: String) -> XMLDTDNode? { guard let node = _CFXMLDTDGetPredefinedEntity(name) else { return nil } return XMLDTDNode._objectNodeForNode(node) } internal override class func _objectNodeForNode(_ node: _CFXMLNodePtr) -> XMLDTD { precondition(_CFXMLNodeGetType(node) == _kCFXMLTypeDTD) if let privateData = _CFXMLNodeGetPrivateData(node) { return XMLDTD.unretainedReference(privateData) } return XMLDTD(ptr: node) } internal override init(ptr: _CFXMLNodePtr) { super.init(ptr: ptr) } }
apache-2.0
f27a7c25ff2b39b3e034e8f14a58c7c8
32.560209
234
0.624181
4.482517
false
false
false
false
BSDStudios/parity
mac/Parity/AppDelegate.swift
1
7077
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. import Cocoa @NSApplicationMain @available(macOS, deprecated: 10.11) class AppDelegate: NSObject, NSApplicationDelegate { @IBOutlet weak var statusMenu: NSMenu! @IBOutlet weak var startAtLogonMenuItem: NSMenuItem! let statusItem = NSStatusBar.system().statusItem(withLength: NSVariableStatusItemLength) var parityPid: Int32? = nil var commandLine: [String] = [] let defaultConfig = "[network]\nwarp = true" let defaultDefaults = "{\"fat_db\":false,\"mode\":\"passive\",\"mode.alarm\":3600,\"mode.timeout\":300,\"pruning\":\"fast\",\"tracing\":false}" func menuAppPath() -> String { return Bundle.main.executablePath! } func parityPath() -> String { return Bundle.main.bundlePath + "/Contents/MacOS/parity" } func isAlreadyRunning() -> Bool { return NSRunningApplication.runningApplications(withBundleIdentifier: Bundle.main.bundleIdentifier!).count > 1 } func isParityRunning() -> Bool { if let pid = self.parityPid { return kill(pid, 0) == 0 } return false } func killParity() { if let pid = self.parityPid { kill(pid, SIGINT) } } func openUI() { let parity = Process() parity.launchPath = self.parityPath() parity.arguments = self.commandLine parity.arguments!.append("ui") parity.launch() } func writeConfigFiles() { let basePath = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first? .appendingPathComponent(Bundle.main.bundleIdentifier!, isDirectory: true) if FileManager.default.fileExists(atPath: basePath!.path) { return } do { let defaultsFileDir = basePath?.appendingPathComponent("chains").appendingPathComponent("ethereum") let defaultsFile = defaultsFileDir?.appendingPathComponent("user_defaults") try FileManager.default.createDirectory(atPath: (defaultsFileDir?.path)!, withIntermediateDirectories: true, attributes: nil) if !FileManager.default.fileExists(atPath: defaultsFile!.path) { try defaultDefaults.write(to: defaultsFile!, atomically: false, encoding: String.Encoding.utf8) } let configFile = basePath?.appendingPathComponent("config.toml") if !FileManager.default.fileExists(atPath: configFile!.path) { try defaultConfig.write(to: configFile!, atomically: false, encoding: String.Encoding.utf8) } } catch {} } func autostartEnabled() -> Bool { return itemReferencesInLoginItems().existingReference != nil } func itemReferencesInLoginItems() -> (existingReference: LSSharedFileListItem?, lastReference: LSSharedFileListItem?) { let itemUrl: UnsafeMutablePointer<Unmanaged<CFURL>?> = UnsafeMutablePointer<Unmanaged<CFURL>?>.allocate(capacity: 1) if let appUrl: NSURL = NSURL.fileURL(withPath: Bundle.main.bundlePath) as NSURL? { let loginItemsRef = LSSharedFileListCreate( nil, kLSSharedFileListSessionLoginItems.takeRetainedValue(), nil ).takeRetainedValue() as LSSharedFileList? if loginItemsRef != nil { let loginItems: NSArray = LSSharedFileListCopySnapshot(loginItemsRef, nil).takeRetainedValue() as NSArray if(loginItems.count > 0) { let lastItemRef: LSSharedFileListItem = loginItems.lastObject as! LSSharedFileListItem for i in 0 ..< loginItems.count { let currentItemRef: LSSharedFileListItem = loginItems.object(at: i) as! LSSharedFileListItem if LSSharedFileListItemResolve(currentItemRef, 0, itemUrl, nil) == noErr { if let urlRef: NSURL = itemUrl.pointee?.takeRetainedValue() { if urlRef.isEqual(appUrl) { return (currentItemRef, lastItemRef) } } } } //The application was not found in the startup list return (nil, lastItemRef) } else { let addAtStart: LSSharedFileListItem = kLSSharedFileListItemBeforeFirst.takeRetainedValue() return(nil, addAtStart) } } } return (nil, nil) } func toggleLaunchAtStartup() { let itemReferences = itemReferencesInLoginItems() let shouldBeToggled = (itemReferences.existingReference == nil) let loginItemsRef = LSSharedFileListCreate( nil, kLSSharedFileListSessionLoginItems.takeRetainedValue(), nil ).takeRetainedValue() as LSSharedFileList? if loginItemsRef != nil { if shouldBeToggled { if let appUrl : CFURL = NSURL.fileURL(withPath: Bundle.main.bundlePath) as CFURL? { LSSharedFileListInsertItemURL( loginItemsRef, itemReferences.lastReference, nil, nil, appUrl, nil, nil ) } } else { if let itemRef = itemReferences.existingReference { LSSharedFileListItemRemove(loginItemsRef,itemRef) } } } } func launchParity() { self.commandLine = CommandLine.arguments.dropFirst().filter({ $0 != "ui"}) let processes = GetBSDProcessList()! let parityProcess = processes.index(where: { var name = $0.kp_proc.p_comm let str = withUnsafePointer(to: &name) { $0.withMemoryRebound(to: UInt8.self, capacity: MemoryLayout.size(ofValue: name)) { String(cString: $0) } } return str == "parity" }) if parityProcess == nil { let parity = Process() let p = self.parityPath() parity.launchPath = p//self.parityPath() parity.arguments = self.commandLine parity.launch() self.parityPid = parity.processIdentifier } else { self.parityPid = processes[parityProcess!].kp_proc.p_pid } } func applicationDidFinishLaunching(_ aNotification: Notification) { if self.isAlreadyRunning() { openUI() NSApplication.shared().terminate(self) return } self.writeConfigFiles() self.launchParity() Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true, block: {_ in if !self.isParityRunning() { NSApplication.shared().terminate(self) } }) let icon = NSImage(named: "statusIcon") icon?.isTemplate = true // best for dark mode statusItem.image = icon statusItem.menu = statusMenu } override func validateMenuItem(_ menuItem: NSMenuItem) -> Bool { if menuItem == self.startAtLogonMenuItem! { menuItem.state = self.autostartEnabled() ? NSOnState : NSOffState } return true } @IBAction func quitClicked(_ sender: NSMenuItem) { self.killParity() NSApplication.shared().terminate(self) } @IBAction func openClicked(_ sender: NSMenuItem) { self.openUI() } @IBAction func startAtLogonClicked(_ sender: NSMenuItem) { self.toggleLaunchAtStartup() } }
gpl-3.0
382c745727374da5d620a885b2d81a3e
30.039474
144
0.713579
3.844106
false
false
false
false
szk-atmosphere/URLEmbeddedView
URLEmbeddedView/UI/URLEmbeddedView.swift
1
18692
// // URLEmbeddedView.swift // URLEmbeddedView // // Created by Taiki Suzuki on 2016/03/06. // // import UIKit protocol URLEmbeddedViewProtocol: class { func layoutIfNeeded() func prepareViewsForReuse() func updateActivityView(isHidden: Bool) func updateViewAsEmpty(with url: URL, faciconURLString: String) func updateLinkIconView(isHidden: Bool) func updateTitleLabel(pageTitle: String) func updateDescriptionLabel(pageDescription: String?) func updateImageView(urlString: String?) func updateDomainLabel(host: String) func updateDomainImageView(urlString: String) } @objc open class URLEmbeddedView: UIView { //MARK: - Properties private let alphaView = UIView() let imageView = URLImageView() private var imageViewWidthConstraint: NSLayoutConstraint? private let titleLabel = UILabel() private var titleLabelHeightConstraint: NSLayoutConstraint? private let descriptionLabel = UILabel() private let domainConainter = UIView() private var domainContainerHeightConstraint: NSLayoutConstraint? private let domainLabel = UILabel() private let domainImageView = URLImageView() private var domainImageViewToDomainLabelConstraint: NSLayoutConstraint? private var domainImageViewWidthConstraint: NSLayoutConstraint? #if os(iOS) #if swift(>=4.2) private let activityView = UIActivityIndicatorView(style: .gray) #else private let activityView = UIActivityIndicatorView(activityIndicatorStyle: .gray) #endif #elseif os(tvOS) #if swift(>=4.2) private let activityView = UIActivityIndicatorView(style: .white) #else private let activityView = UIActivityIndicatorView(activityIndicatorStyle: .white) #endif #endif private lazy var linkIconView = LinkIconView(frame: self.bounds) private lazy var presenter: URLEmbeddedViewPresenterProtocol = URLEmbeddedViewPresenter(view: self) @objc public let textProvider: AttributedTextProvider = .shared @objc open var didTapHandler: ((URLEmbeddedView, URL?) -> Void)? @objc open var shouldContinueDownloadingWhenCancel: Bool { get { return presenter.shouldContinueDownloadingWhenCancel } set { presenter.shouldContinueDownloadingWhenCancel = newValue domainImageView.shouldContinueDownloadingWhenCancel = newValue imageView.shouldContinueDownloadingWhenCancel = newValue } } convenience init(presenter: URLEmbeddedViewPresenterProtocol?) { self.init(frame: .zero) if let presenter = presenter { self.presenter = presenter } } @objc public convenience init() { self.init(frame: .zero) } @objc public override init(frame: CGRect) { super.init(frame: frame) setInitialiValues() configureViews() } @objc public convenience init(url: String) { self.init(url: url, frame: .zero) } @objc public init(url: String, frame: CGRect) { super.init(frame: frame) presenter.setURLString(url) setInitialiValues() configureViews() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setInitialiValues() } open override func awakeFromNib() { super.awakeFromNib() configureViews() } open func prepareViewsForReuse() { cancelLoading() imageView.image = nil titleLabel.attributedText = nil descriptionLabel.attributedText = nil domainLabel.attributedText = nil domainImageView.image = nil linkIconView.isHidden = true } fileprivate func setInitialiValues() { borderColor = .lightGray borderWidth = 1 cornerRaidus = 8 } fileprivate func configureViews() { setNeedsDisplay() layoutIfNeeded() textProvider.didChangeValue = { [weak self] style, attribute, value in self?.handleTextProviderChanged(style, attribute: attribute, value: value) } addSubview(linkIconView) addConstraints(with: linkIconView, edges: .init(top: 0, left: 0, bottom: 0)) addConstraint(.init(item: linkIconView, attribute: .width, relatedBy: .equal, toItem: linkIconView, attribute: .height, multiplier: 1, constant: 0)) linkIconView.clipsToBounds = true linkIconView.isHidden = true imageView.contentMode = .scaleAspectFill imageView.clipsToBounds = true addSubview(imageView) addConstraints(with: imageView, edges: .init(top: 0, left: 0, bottom: 0)) changeImageViewWidthConstrain(nil) titleLabel.numberOfLines = textProvider[.title].numberOfLines addSubview(titleLabel) addConstraints(with: titleLabel, edges: .init(top: 8, right: -12)) addConstraint(.init(item: titleLabel, attribute: .left, relatedBy: .equal, toItem: imageView, attribute: .right, multiplier: 1, constant: 12)) changeTitleLabelHeightConstraint() addSubview(domainConainter) addConstraints(with: domainConainter, edges: .init(right: -12, bottom: -10)) addConstraint(.init(item: domainConainter, attribute: .left, relatedBy: .equal, toItem: imageView, attribute: .right, multiplier: 1, constant: 12)) changeDomainContainerHeightConstraint() descriptionLabel.numberOfLines = textProvider[.description].numberOfLines addSubview(descriptionLabel) addConstraints(with: descriptionLabel, edges: .init(right: -12)) addConstraints(with: descriptionLabel, size: .init(height: 0), relatedBy: .greaterThanOrEqual) addConstraints([ .init(item: descriptionLabel, attribute: .top, relatedBy: .equal, toItem: titleLabel, attribute: .bottom, multiplier: 1, constant: 2), .init(item: descriptionLabel, attribute: .bottom, relatedBy: .lessThanOrEqual, toItem: domainConainter, attribute: .top, multiplier: 1, constant: 4), .init(item: descriptionLabel, attribute: .left, relatedBy: .equal, toItem: imageView, attribute: .right, multiplier: 1, constant: 12) ]) domainImageView.activityViewHidden = true domainConainter.addSubview(domainImageView) domainConainter.addConstraints(with: domainImageView, edges: .init(top: 0, left: 0, bottom: 0)) changeDomainImageViewWidthConstraint(nil) domainLabel.numberOfLines = textProvider[.domain].numberOfLines domainConainter.addSubview(domainLabel) domainConainter.addConstraints(with: domainLabel, edges: .init(top: 0, right: 0, bottom: 0)) changeDomainImageViewToDomainLabelConstraint(nil) activityView.hidesWhenStopped = true addSubview(activityView) addConstraints(with: activityView, center: .zero) addConstraints(with: activityView, size: .init(width: 30, height: 30)) alphaView.backgroundColor = UIColor.black.withAlphaComponent(0.2) alphaView.alpha = 0 addSubview(alphaView) addConstraints(with: alphaView, edges: .zero) } open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { alphaView.alpha = 1 } open override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { alphaView.alpha = 0 } open override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { alphaView.alpha = 0 didTapHandler?(self, presenter.url) } //MARK: - Image layout private func changeImageViewWidthConstrain(_ constant: CGFloat?) { if let constraint = imageViewWidthConstraint { removeConstraint(constraint) } let constraint: NSLayoutConstraint if let constant = constant { constraint = NSLayoutConstraint(item: imageView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: constant) } else { constraint = NSLayoutConstraint(item: imageView, attribute: .width, relatedBy: .equal, toItem: imageView, attribute: .height, multiplier: 1, constant: 0) } addConstraint(constraint) imageViewWidthConstraint = constraint } private func changeDomainImageViewWidthConstraint(_ constant: CGFloat?) { if let constraint = domainImageViewWidthConstraint { removeConstraint(constraint) } let constraint: NSLayoutConstraint if let constant = constant { constraint = NSLayoutConstraint(item: domainImageView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: constant) } else { constraint = NSLayoutConstraint(item: domainImageView, attribute: .width, relatedBy: .equal, toItem: domainConainter, attribute: .height, multiplier: 1, constant: 0) } addConstraint(constraint) domainImageViewWidthConstraint = constraint } private func changeDomainImageViewToDomainLabelConstraint(_ constant: CGFloat?) { let constant = constant ?? (textProvider[.domain].font.lineHeight / 5) if let constraint = domainImageViewToDomainLabelConstraint { if constant == constraint.constant { return } removeConstraint(constraint) } let constraint = NSLayoutConstraint(item: domainLabel, attribute: .left, relatedBy: .equal, toItem: domainImageView, attribute: .right, multiplier: 1, constant: constant) addConstraint(constraint) domainImageViewToDomainLabelConstraint = constraint } private func changeTitleLabelHeightConstraint() { let constant = textProvider[.title].font.lineHeight if let constraint = titleLabelHeightConstraint { if constant == constraint.constant { return } removeConstraint(constraint) } let constraint = NSLayoutConstraint(item: titleLabel, attribute: .height, relatedBy: .greaterThanOrEqual, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: constant) addConstraint(constraint) titleLabelHeightConstraint = constraint } private func changeDomainContainerHeightConstraint() { let constant = textProvider[.domain].font.lineHeight if let constraint = domainContainerHeightConstraint { if constant == constraint.constant { return } removeConstraint(constraint) } let constraint = NSLayoutConstraint(item: domainConainter, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: constant) addConstraint(constraint) domainContainerHeightConstraint = constraint } //MARK: - Attributes private func handleTextProviderChanged(_ style: AttributeManager.Style, attribute: AttributeManager.Attribute, value: Any) { switch style { case .title: didChangeTitleAttirbute(attribute, value: value) case .domain: didChangeDomainAttirbute(attribute, value: value) case .description: didChangeDescriptionAttirbute(attribute, value: value) case .noDataTitle: didChangeNoDataTitleAttirbute(attribute, value: value) } } private func didChangeTitleAttirbute(_ attribute: AttributeManager.Attribute, value: Any) { switch attribute { case .font: changeDomainContainerHeightConstraint() case .fontColor: break case .numberOfLines: break } } private func didChangeDomainAttirbute(_ attribute: AttributeManager.Attribute, value: Any) { switch attribute { case .font: changeDomainContainerHeightConstraint() case .fontColor: break case .numberOfLines: break } } private func didChangeDescriptionAttirbute(_ attribute: AttributeManager.Attribute, value: Any) { switch attribute { case .font: break case .fontColor: break case .numberOfLines: break } } private func didChangeNoDataTitleAttirbute(_ attribute: AttributeManager.Attribute, value: Any) { switch attribute { case .font: changeTitleLabelHeightConstraint() case .fontColor: break case .numberOfLines: break } } //MARK: - Load @objc public func load(withURLString urlString: String, completion: ((Error?) -> Void)? = nil) { load(urlString: urlString) { completion?($0.error) } } @nonobjc public func load(urlString: String, completion: ((Result<Void>) -> Void)? = nil) { presenter.load(urlString: urlString, completion: completion) } @objc public func load(_ completion: ((Error?) -> Void)? = nil) { load { completion?($0.error) } } @nonobjc public func load(_ completion: ((Result<Void>) -> Void)? = nil) { presenter.load(completion) } @objc public func cancelLoading() { domainImageView.cancelLoadingImage() imageView.cancelLoadingImage() presenter.cancelLoading() } } extension URLEmbeddedView: URLEmbeddedViewProtocol { func updateActivityView(isHidden: Bool) { activityView.isHidden = isHidden if isHidden { activityView.stopAnimating() } else { activityView.startAnimating() } } func updateViewAsEmpty(with url: URL, faciconURLString: String) { imageView.image = nil titleLabel.attributedText = textProvider[.noDataTitle].attributedText(url.absoluteString) descriptionLabel.attributedText = nil domainLabel.attributedText = textProvider[.domain].attributedText(url.host ?? "") changeDomainImageViewWidthConstraint(0) updateDomainImageView(urlString: faciconURLString) linkIconView.isHidden = false } func updateLinkIconView(isHidden: Bool) { linkIconView.isHidden = isHidden } func updateTitleLabel(pageTitle: String) { titleLabel.attributedText = textProvider[.title].attributedText(pageTitle) } func updateDescriptionLabel(pageDescription: String?) { if let pageDescription = pageDescription { descriptionLabel.attributedText = textProvider[.description].attributedText(pageDescription) } else { descriptionLabel.attributedText = nil } } func updateImageView(urlString: String?) { if let urlString = urlString { imageView.loadImage(urlString: urlString) { [weak self] in switch $0 { case .success: self?.changeImageViewWidthConstrain(nil) case .failure: self?.changeImageViewWidthConstrain(0) } self?.layoutIfNeeded() } } else { changeImageViewWidthConstrain(0) imageView.image = nil } } func updateDomainLabel(host: String) { domainLabel.attributedText = textProvider[.domain].attributedText(host) } func updateDomainImageView(urlString: String) { domainImageView.loadImage(urlString: urlString) { [weak self] in switch $0 { case .success: self?.changeDomainImageViewWidthConstraint(nil) self?.changeDomainImageViewToDomainLabelConstraint(nil) case .failure: self?.changeDomainImageViewWidthConstraint(0) self?.changeDomainImageViewToDomainLabelConstraint(0) } self?.layoutIfNeeded() } } }
mit
625f93a67ea275d57ccb97cf7e6258a3
37.540206
128
0.562701
5.90398
false
false
false
false
adrfer/swift
validation-test/stdlib/Assert.swift
2
6281
// RUN: rm -rf %t // RUN: mkdir -p %t // RUN: %target-build-swift %s -Xfrontend -disable-access-control -o %t/Assert_Debug // RUN: %target-build-swift %s -Xfrontend -disable-access-control -o %t/Assert_Release -O // RUN: %target-build-swift %s -Xfrontend -disable-access-control -o %t/Assert_Unchecked -Ounchecked // // RUN: %target-run %t/Assert_Debug // RUN: %target-run %t/Assert_Release // RUN: %target-run %t/Assert_Unchecked // REQUIRES: executable_test import StdlibUnittest // Also import modules which are used by StdlibUnittest internally. This // workaround is needed to link all required libraries in case we compile // StdlibUnittest with -sil-serialize-all. import SwiftPrivate import SwiftPrivatePthreadExtras #if _runtime(_ObjC) import ObjectiveC #endif //===--- // Tests. //===--- func testTrapsAreNoreturn(i: Int) -> Int { // Don't need a return statement in 'case' statements because these functions // are @noreturn. switch i { case 2: preconditionFailure("cannot happen") case 3: _preconditionFailure("cannot happen") case 4: _debugPreconditionFailure("cannot happen") case 5: _sanityCheckFailure("cannot happen") default: return 0 } } var Assert = TestSuite("Assert") Assert.test("assert") .xfail(.Custom( { !_isDebugAssertConfiguration() }, reason: "assertions are disabled in Release and Unchecked mode")) .crashOutputMatches("this should fail") .code { var x = 2 assert(x * 21 == 42, "should not fail") expectCrashLater() assert(x == 42, "this should fail") } Assert.test("assert/StringInterpolation") .xfail(.Custom( { !_isDebugAssertConfiguration() }, reason: "assertions are disabled in Release and Unchecked mode")) .crashOutputMatches("this should fail") .code { var should = "should" var x = 2 assert(x * 21 == 42, "\(should) not fail") expectCrashLater() assert(x == 42, "this \(should) fail") } Assert.test("assertionFailure") .skip(.Custom( { !_isDebugAssertConfiguration() }, reason: "optimizer assumes that the code path is unreachable")) .crashOutputMatches("this should fail") .code { expectCrashLater() assertionFailure("this should fail") } Assert.test("assertionFailure/StringInterpolation") .skip(.Custom( { !_isDebugAssertConfiguration() }, reason: "optimizer assumes that the code path is unreachable")) .crashOutputMatches("this should fail") .code { var should = "should" expectCrashLater() assertionFailure("this \(should) fail") } Assert.test("precondition") .xfail(.Custom( { _isFastAssertConfiguration() }, reason: "preconditions are disabled in Unchecked mode")) .crashOutputMatches(_isDebugAssertConfiguration() ? "this should fail" : "") .code { var x = 2 precondition(x * 21 == 42, "should not fail") expectCrashLater() precondition(x == 42, "this should fail") } Assert.test("precondition/StringInterpolation") .xfail(.Custom( { _isFastAssertConfiguration() }, reason: "preconditions are disabled in Unchecked mode")) .crashOutputMatches(_isDebugAssertConfiguration() ? "this should fail" : "") .code { var should = "should" var x = 2 precondition(x * 21 == 42, "\(should) not fail") expectCrashLater() precondition(x == 42, "this \(should) fail") } Assert.test("preconditionFailure") .skip(.Custom( { _isFastAssertConfiguration() }, reason: "optimizer assumes that the code path is unreachable")) .crashOutputMatches(_isDebugAssertConfiguration() ? "this should fail" : "") .code { expectCrashLater() preconditionFailure("this should fail") } Assert.test("preconditionFailure/StringInterpolation") .skip(.Custom( { _isFastAssertConfiguration() }, reason: "optimizer assumes that the code path is unreachable")) .crashOutputMatches(_isDebugAssertConfiguration() ? "this should fail" : "") .code { var should = "should" expectCrashLater() preconditionFailure("this \(should) fail") } Assert.test("fatalError") .crashOutputMatches("this should fail") .code { expectCrashLater() fatalError("this should fail") } Assert.test("fatalError/StringInterpolation") .crashOutputMatches("this should fail") .code { var should = "should" expectCrashLater() fatalError("this \(should) fail") } Assert.test("_precondition") .xfail(.Custom( { _isFastAssertConfiguration() }, reason: "preconditions are disabled in Unchecked mode")) .crashOutputMatches(_isDebugAssertConfiguration() ? "this should fail" : "") .code { var x = 2 _precondition(x * 21 == 42, "should not fail") expectCrashLater() _precondition(x == 42, "this should fail") } Assert.test("_preconditionFailure") .skip(.Custom( { _isFastAssertConfiguration() }, reason: "optimizer assumes that the code path is unreachable")) .crashOutputMatches(_isDebugAssertConfiguration() ? "this should fail" : "") .code { expectCrashLater() _preconditionFailure("this should fail") } Assert.test("_debugPrecondition") .xfail(.Custom( { !_isDebugAssertConfiguration() }, reason: "debug preconditions are disabled in Release and Unchecked mode")) .crashOutputMatches(_isDebugAssertConfiguration() ? "this should fail" : "") .code { var x = 2 _debugPrecondition(x * 21 == 42, "should not fail") expectCrashLater() _debugPrecondition(x == 42, "this should fail") } Assert.test("_debugPreconditionFailure") .skip(.Custom( { !_isDebugAssertConfiguration() }, reason: "optimizer assumes that the code path is unreachable")) .crashOutputMatches("this should fail") .code { expectCrashLater() _debugPreconditionFailure("this should fail") } Assert.test("_sanityCheck") .xfail(.Custom( { !_isStdlibInternalChecksEnabled() }, reason: "sanity checks are disabled in this build of stdlib")) .crashOutputMatches("this should fail") .code { var x = 2 _sanityCheck(x * 21 == 42, "should not fail") expectCrashLater() _sanityCheck(x == 42, "this should fail") } Assert.test("_sanityCheckFailure") .skip(.Custom( { !_isStdlibInternalChecksEnabled() }, reason: "optimizer assumes that the code path is unreachable")) .crashOutputMatches("this should fail") .code { expectCrashLater() _sanityCheckFailure("this should fail") } runAllTests()
apache-2.0
1eeb415af878fa10177d8c4421c5d810
27.040179
100
0.696545
4.212609
false
true
false
false
mrdepth/Neocom
Neocom/Neocom/Utility/DataLoaders/CorpWalletJournalData.swift
2
2670
// // CorpWalletJournalData.swift // Neocom // // Created by Artem Shimanski on 7/2/20. // Copyright © 2020 Artem Shimanski. All rights reserved. // import Foundation import EVEAPI import Combine import Alamofire import CoreData class CorpWalletJournalData: ObservableObject { @Published var isLoading = false @Published var result: Result<[(ESI.Wallet, ESI.WalletJournal)], AFError>? private var esi: ESI private var characterID: Int64 private var subscription: AnyCancellable? init(esi: ESI, characterID: Int64) { self.esi = esi self.characterID = characterID update(cachePolicy: .useProtocolCachePolicy) } func update(cachePolicy: URLRequest.CachePolicy) { isLoading = true let esi = self.esi let characterID = self.characterID subscription = esi.characters.characterID(Int(characterID)).get().map{esi.corporations.corporationID($0.value.corporationID)} .flatMap { corporation in corporation.wallets().get().map{$0.value} .flatMap { divisions in Publishers.Sequence(sequence: divisions).flatMap { division in corporation.wallets().division(division.division).journal().get().map{$0.value.map{$0 as WalletJournalProtocol}}.map{(division, $0)} }.collect() } } .asResult() .receive(on: RunLoop.main) .sink { [weak self] (result) in self?.result = result } // // // subscription = esi.characters.characterID(Int(characterID)).wallet().transactions().get(fromID: nil, cachePolicy: cachePolicy).flatMap { transactions -> AnyPublisher<(ESI.WalletTransactions, [Int64: Contact], [Int64: EVELocation]), AFError> in // let clientIDs = transactions.value.map{Int64($0.clientID)} // let locationIDs = transactions.value.map{$0.locationID} // let contacts = Contact.contacts(with: Set(clientIDs), esi: esi, characterID: characterID, options: [.universe], managedObjectContext: managedObjectContext).replaceError(with: [:]) // let locations = EVELocation.locations(with: Set(locationIDs), esi: esi, managedObjectContext: managedObjectContext).replaceError(with: [:]) // return Publishers.Zip3(Just(transactions.value), contacts, locations).setFailureType(to: AFError.self).eraseToAnyPublisher() // }.asResult() // .receive(on: RunLoop.main) // .sink { [weak self] result in // self?.result = result.map{(transactions: $0.0, contacts: $0.1, locations: $0.2)} // self?.isLoading = false // } } }
lgpl-2.1
5842545eeda6198277bc36c6fe5025af
41.365079
253
0.647433
4.440932
false
false
false
false
CrazyZhangSanFeng/BanTang
BanTang/BanTang/Classes/Home/ScrollPageView/ScrollSegmentView.swift
1
21137
// // TopScrollView.swift // ScrollViewController // // Created by jasnig on 16/4/6. // Copyright © 2016年 ZeroJ. All rights reserved. // github: https://github.com/jasnig // 简书: http://www.jianshu.com/users/fb31a3d1ec30/latest_articles // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit public class ScrollSegmentView: UIView { // 1. 实现颜色填充效果 /// 所有的title设置 public var segmentStyle: SegmentStyle /// 点击响应的closure public var titleBtnOnClick:((label: UILabel, index: Int) -> Void)? /// 附加按钮点击响应 public var extraBtnOnClick: ((extraBtn: UIButton) -> Void)? /// self.bounds.size.width private var currentWidth: CGFloat = 0 /// 遮盖x和文字x的间隙 private var xGap = 5 /// 遮盖宽度比文字宽度多的部分 private var wGap: Int { return 2 * xGap } /// 缓存标题labels private var labelsArray: [UILabel] = [] /// 记录当前选中的下标 private var currentIndex = 0 /// 记录上一个下标 private var oldIndex = 0 /// 用来缓存所有标题的宽度, 达到根据文字的字数和font自适应控件的宽度 private var titlesWidthArray: [CGFloat] = [] /// 所有的标题 private var titles:[String] private lazy var scrollView: UIScrollView = { let scrollV = UIScrollView() scrollV.showsHorizontalScrollIndicator = false scrollV.bounces = true scrollV.pagingEnabled = false scrollV.scrollsToTop = false return scrollV }() /// 滚动条 private lazy var scrollLine: UIView? = {[unowned self] in let line = UIView() return self.segmentStyle.showLine ? line : nil }() /// 遮盖 private lazy var coverLayer: UIView? = {[unowned self] in if !self.segmentStyle.showCover { return nil } let cover = UIView() cover.layer.cornerRadius = CGFloat(self.segmentStyle.coverCornerRadius) // 这里只有一个cover 需要设置圆角, 故不用考虑离屏渲染的消耗, 直接设置 masksToBounds 来设置圆角 cover.layer.masksToBounds = true return cover }() /// 附加的按钮 private lazy var extraButton: UIButton? = {[unowned self] in if !self.segmentStyle.showExtraButton { return nil } let btn = UIButton() btn.addTarget(self, action: #selector(self.extraBtnOnClick(_:)), forControlEvents: .TouchUpInside) // 默认 图片名字 let imageName = self.segmentStyle.extraBtnBackgroundImageName ?? "" btn.setImage(UIImage(named:imageName), forState: .Normal) btn.backgroundColor = UIColor.whiteColor() // 设置边缘的阴影效果 btn.layer.shadowColor = UIColor.whiteColor().CGColor btn.layer.shadowOffset = CGSize(width: -5, height: 0) btn.layer.shadowOpacity = 1 return btn }() /// 懒加载颜色的rgb变化值, 不要每次滚动时都计算 private lazy var rgbDelta: (deltaR: CGFloat, deltaG: CGFloat, deltaB: CGFloat) = {[unowned self] in let normalColorRgb = self.normalColorRgb let selectedTitleColorRgb = self.selectedTitleColorRgb let deltaR = normalColorRgb.r - selectedTitleColorRgb.r let deltaG = normalColorRgb.g - selectedTitleColorRgb.g let deltaB = normalColorRgb.b - selectedTitleColorRgb.b return (deltaR: deltaR, deltaG: deltaG, deltaB: deltaB) }() /// 懒加载颜色的rgb变化值, 不要每次滚动时都计算 private lazy var normalColorRgb: (r: CGFloat, g: CGFloat, b: CGFloat) = { if let normalRgb = self.getColorRGB(self.segmentStyle.normalTitleColor) { return normalRgb } else { fatalError("设置普通状态的文字颜色时 请使用RGB空间的颜色值") } }() private lazy var selectedTitleColorRgb: (r: CGFloat, g: CGFloat, b: CGFloat) = { if let selectedRgb = self.getColorRGB(self.segmentStyle.selectedTitleColor) { return selectedRgb } else { fatalError("设置选中状态的文字颜色时 请使用RGB空间的颜色值") } }() //FIXME: 如果提供的不是RGB空间的颜色值就可能crash private func getColorRGB(color: UIColor) -> (r: CGFloat, g: CGFloat, b: CGFloat)? { // let colorString = String(color) // let colorArr = colorString.componentsSeparatedByString(" ") // print(colorString) // guard let r = Int(colorArr[1]), let g = Int(colorArr[2]), let b = Int(colorArr[3]) else { // return nil // } let numOfComponents = CGColorGetNumberOfComponents(color.CGColor) if numOfComponents == 4 { let componemts = CGColorGetComponents(color.CGColor) // print("\(componemts[0]) --- \(componemts[1]) ---- \(componemts[2]) --- \(componemts[3])") return (r: componemts[0], g: componemts[1], b: componemts[2]) } return nil } /// 背景图片 public var backgroundImage: UIImage? = nil { didSet { // 在设置了背景图片的时候才添加imageView if let image = backgroundImage { backgroundImageView.image = image insertSubview(backgroundImageView, atIndex: 0) } } } private lazy var backgroundImageView: UIImageView = {[unowned self] in let imageView = UIImageView(frame: self.bounds) return imageView }() //MARK:- life cycle /// 初始化的过程中做了太多的事了 !!!!!! public init(frame: CGRect, segmentStyle: SegmentStyle, titles: [String]) { self.segmentStyle = segmentStyle self.titles = titles super.init(frame: frame) if !self.segmentStyle.scrollTitle { // 不能滚动的时候就不要把缩放和遮盖或者滚动条同时使用, 否则显示效果不好 self.segmentStyle.scaleTitle = !(self.segmentStyle.showCover || self.segmentStyle.showLine) } addSubview(scrollView) // 添加附加按钮 if let extraBtn = extraButton { addSubview(extraBtn) } // 设置了frame之后可以直接设置其他的控件的frame了, 不需要在layoutsubView()里面设置 setupTitles() setupUI() } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func titleLabelOnClick(tapGes: UITapGestureRecognizer) { guard let currentLabel = tapGes.view as? CustomLabel else { return } currentIndex = currentLabel.tag adjustUIWhenBtnOnClickWithAnimate(true) } func extraBtnOnClick(btn: UIButton) { extraBtnOnClick?(extraBtn: btn) } deinit { print("\(self.debugDescription) --- 销毁") } } //MARK: - public helper extension ScrollSegmentView { /// 对外界暴露设置选中的下标的方法 可以改变设置下标滚动后是否有动画切换效果 public func selectedIndex(selectedIndex: Int, animated: Bool) { assert(!(selectedIndex < 0 || selectedIndex >= titles.count), "设置的下标不合法!!") if selectedIndex < 0 || selectedIndex >= titles.count { return } // 自动调整到相应的位置 currentIndex = selectedIndex // print("\(oldIndex) ------- \(currentIndex)") // 可以改变设置下标滚动后是否有动画切换效果 adjustUIWhenBtnOnClickWithAnimate(animated) } // 暴露给外界来刷新标题的显示 public func reloadTitlesWithNewTitles(titles: [String]) { // 移除所有的scrollView子视图 scrollView.subviews.forEach { (subview) in subview.removeFromSuperview() } // 移除所有的label相关 titlesWidthArray.removeAll() labelsArray.removeAll() // 重新设置UI self.titles = titles setupTitles() setupUI() // default selecte the first tag selectedIndex(0, animated: true) } } //MARK: - private helper extension ScrollSegmentView { private func setupTitles() { for (index, title) in titles.enumerate() { let label = CustomLabel(frame: CGRectZero) label.tag = index label.text = title label.textColor = segmentStyle.normalTitleColor label.font = segmentStyle.titleFont label.textAlignment = .Center label.userInteractionEnabled = true let tapGes = UITapGestureRecognizer(target: self, action: #selector(self.titleLabelOnClick(_:))) label.addGestureRecognizer(tapGes) let size = (title as NSString).boundingRectWithSize(CGSizeMake(CGFloat(MAXFLOAT), 0.0), options: .UsesLineFragmentOrigin, attributes: [NSFontAttributeName: label.font], context: nil) titlesWidthArray.append(size.width) labelsArray.append(label) scrollView.addSubview(label) } } private func setupUI() { // 设置extra按钮 setupScrollViewAndExtraBtn() // 先设置label的位置 setUpLabelsPosition() // 再设置滚动条和cover的位置 setupScrollLineAndCover() if segmentStyle.scrollTitle { // 设置滚动区域 if let lastLabel = labelsArray.last { scrollView.contentSize = CGSize(width: CGRectGetMaxX(lastLabel.frame) + segmentStyle.titleMargin, height: 0) } } } private func setupScrollViewAndExtraBtn() { currentWidth = bounds.size.width let extraBtnW: CGFloat = 44.0 let extraBtnY: CGFloat = 5.0 let scrollW = extraButton == nil ? currentWidth : currentWidth - extraBtnW scrollView.frame = CGRect(x: 0.0, y: 0.0, width: scrollW, height: bounds.size.height) extraButton?.frame = CGRect(x: scrollW, y: extraBtnY, width: extraBtnW, height: bounds.size.height - 2*extraBtnY) } // 先设置label的位置 private func setUpLabelsPosition() { var titleX: CGFloat = 0.0 let titleY: CGFloat = 0.0 var titleW: CGFloat = 0.0 let titleH = bounds.size.height - segmentStyle.scrollLineHeight if !segmentStyle.scrollTitle {// 标题不能滚动, 平分宽度 titleW = currentWidth / CGFloat(titles.count) for (index, label) in labelsArray.enumerate() { titleX = CGFloat(index) * titleW label.frame = CGRect(x: titleX, y: titleY, width: titleW, height: titleH) } } else { for (index, label) in labelsArray.enumerate() { titleW = titlesWidthArray[index] titleX = segmentStyle.titleMargin if index != 0 { let lastLabel = labelsArray[index - 1] titleX = CGRectGetMaxX(lastLabel.frame) + segmentStyle.titleMargin } label.frame = CGRect(x: titleX, y: titleY, width: titleW, height: titleH) } } if let firstLabel = labelsArray[0] as? CustomLabel { // 缩放, 设置初始的label的transform if segmentStyle.scaleTitle { firstLabel.currentTransformSx = segmentStyle.titleBigScale } // 设置初始状态文字的颜色 firstLabel.textColor = segmentStyle.selectedTitleColor } } // 再设置滚动条和cover的位置 private func setupScrollLineAndCover() { if let line = scrollLine { line.backgroundColor = segmentStyle.scrollLineColor scrollView.addSubview(line) } if let cover = coverLayer { cover.backgroundColor = segmentStyle.coverBackgroundColor scrollView.insertSubview(cover, atIndex: 0) } let coverX = labelsArray[0].frame.origin.x let coverW = labelsArray[0].frame.size.width let coverH: CGFloat = segmentStyle.coverHeight let coverY = (bounds.size.height - coverH) / 2 if segmentStyle.scrollTitle { // 这里x-xGap width+wGap 是为了让遮盖的左右边缘和文字有一定的距离 coverLayer?.frame = CGRect(x: coverX - CGFloat(xGap), y: coverY, width: coverW + CGFloat(wGap), height: coverH) } else { coverLayer?.frame = CGRect(x: coverX, y: coverY, width: coverW, height: coverH) } scrollLine?.frame = CGRect(x: coverX, y: bounds.size.height - segmentStyle.scrollLineHeight, width: coverW, height: segmentStyle.scrollLineHeight) // scrollLine?.center.x = labelsArray[0].center.x // scrollLine?.frame.origin.y = bounds.size.height - segmentStyle.scrollLineHeight // scrollLine?.frame.size.width = 30 // scrollLine?.frame.size.height = segmentStyle.scrollLineHeight } } extension ScrollSegmentView { // 自动或者手动点击按钮的时候调整UI public func adjustUIWhenBtnOnClickWithAnimate(animated: Bool) { // 重复点击时的相应, 这里没有处理, 可以传递给外界来处理 if currentIndex == oldIndex { return } let oldLabel = labelsArray[oldIndex] as! CustomLabel let currentLabel = labelsArray[currentIndex] as! CustomLabel adjustTitleOffSetToCurrentIndex(currentIndex) let animatedTime = animated ? 0.3 : 0.0 UIView.animateWithDuration(animatedTime) {[unowned self] in // 设置文字颜色 oldLabel.textColor = self.segmentStyle.normalTitleColor currentLabel.textColor = self.segmentStyle.selectedTitleColor // 缩放文字 if self.segmentStyle.scaleTitle { oldLabel.currentTransformSx = self.segmentStyle.titleOriginalScale currentLabel.currentTransformSx = self.segmentStyle.titleBigScale } // 设置滚动条的位置 self.scrollLine?.frame.origin.x = currentLabel.frame.origin.x // self.scrollLine?.center.x = currentLabel.center.x // 注意, 通过bounds 获取到的width 是没有进行transform之前的 所以使用frame self.scrollLine?.frame.size.width = currentLabel.frame.size.width // 设置遮盖位置 if self.segmentStyle.scrollTitle { self.coverLayer?.frame.origin.x = currentLabel.frame.origin.x - CGFloat(self.xGap) self.coverLayer?.frame.size.width = currentLabel.frame.size.width + CGFloat(self.wGap) } else { self.coverLayer?.frame.origin.x = currentLabel.frame.origin.x self.coverLayer?.frame.size.width = currentLabel.frame.size.width } } oldIndex = currentIndex titleBtnOnClick?(label: currentLabel, index: currentIndex) } // 手动滚动时需要提供动画效果 public func adjustUIWithProgress(progress: CGFloat, oldIndex: Int, currentIndex: Int) { // 记录当前的currentIndex以便于在点击的时候处理 self.oldIndex = currentIndex // print("\(currentIndex)------------currentIndex") let oldLabel = labelsArray[oldIndex] as! CustomLabel let currentLabel = labelsArray[currentIndex] as! CustomLabel // 需要改变的距离 和 宽度 let xDistance = currentLabel.frame.origin.x - oldLabel.frame.origin.x let wDistance = currentLabel.frame.size.width - oldLabel.frame.size.width // 设置滚动条位置 scrollLine?.frame.origin.x = oldLabel.frame.origin.x + xDistance * progress scrollLine?.frame.size.width = oldLabel.frame.size.width + wDistance * progress // 设置 cover位置 if segmentStyle.scrollTitle { coverLayer?.frame.origin.x = oldLabel.frame.origin.x + xDistance * progress - CGFloat(xGap) coverLayer?.frame.size.width = oldLabel.frame.size.width + wDistance * progress + CGFloat(wGap) } else { coverLayer?.frame.origin.x = oldLabel.frame.origin.x + xDistance * progress coverLayer?.frame.size.width = oldLabel.frame.size.width + wDistance * progress } // print(progress) // 文字颜色渐变 if segmentStyle.gradualChangeTitleColor { oldLabel.textColor = UIColor(red:selectedTitleColorRgb.r + rgbDelta.deltaR * progress, green: selectedTitleColorRgb.g + rgbDelta.deltaG * progress, blue: selectedTitleColorRgb.b + rgbDelta.deltaB * progress, alpha: 1.0) currentLabel.textColor = UIColor(red: normalColorRgb.r - rgbDelta.deltaR * progress, green: normalColorRgb.g - rgbDelta.deltaG * progress, blue: normalColorRgb.b - rgbDelta.deltaB * progress, alpha: 1.0) } // 缩放文字 if !segmentStyle.scaleTitle { return } // 注意左右间的比例是相关连的, 加减相同 // 设置文字缩放 let deltaScale = (segmentStyle.titleBigScale - segmentStyle.titleOriginalScale) oldLabel.currentTransformSx = segmentStyle.titleBigScale - deltaScale * progress currentLabel.currentTransformSx = segmentStyle.titleOriginalScale + deltaScale * progress } // 居中显示title public func adjustTitleOffSetToCurrentIndex(currentIndex: Int) { let currentLabel = labelsArray[currentIndex] labelsArray.enumerate().forEach {[unowned self] in if $0.index != currentIndex { $0.element.textColor = self.segmentStyle.normalTitleColor } } var offSetX = currentLabel.center.x - currentWidth / 2 if offSetX < 0 { offSetX = 0 } // considering the exist of extraButton let extraBtnW = extraButton?.frame.size.width ?? 0.0 var maxOffSetX = scrollView.contentSize.width - (currentWidth - extraBtnW) // 可以滚动的区域小余屏幕宽度 if maxOffSetX < 0 { maxOffSetX = 0 } if offSetX > maxOffSetX { offSetX = maxOffSetX } scrollView.setContentOffset(CGPoint(x:offSetX, y: 0), animated: true) // 没有渐变效果的时候设置切换title时的颜色 if !segmentStyle.gradualChangeTitleColor { for (index, label) in labelsArray.enumerate() { if index == currentIndex { label.textColor = segmentStyle.selectedTitleColor } else { label.textColor = segmentStyle.normalTitleColor } } } // print("\(oldIndex) ------- \(currentIndex)") } } public class CustomLabel: UILabel { /// 用来记录当前label的缩放比例 public var currentTransformSx:CGFloat = 1.0 { didSet { transform = CGAffineTransformMakeScale(currentTransformSx, currentTransformSx) } } }
apache-2.0
4e0d372ea78924c3461cafa28a28fc7e
33.820604
231
0.599112
4.55166
false
false
false
false
PiXeL16/BudgetShare
BudgetShareTests/Services/Mocks/Firebase/MockFirebaseBudgetService.swift
1
2243
// // Created by Chris Jimenez on 8/26/18. // Copyright (c) 2018 Chris Jimenez. All rights reserved. // import Foundation import FirebaseDatabase import RxSwift @testable import BudgetShare internal class MockFirebaseBudgetService: FirebaseBudgetService { var invokedObserveBudget = false var invokedObserveBudgetCount = 0 var invokedObserveBudgetParameters: (budgetId: String, Void)? var invokedObserveBudgetParametersList = [(budgetId: String, Void)]() var stubbedObserveBudgetResult: Observable<DataSnapshot>! func observeBudget(budgetId: String) -> Observable<DataSnapshot> { invokedObserveBudget = true invokedObserveBudgetCount += 1 invokedObserveBudgetParameters = (budgetId, ()) invokedObserveBudgetParametersList.append((budgetId, ())) return stubbedObserveBudgetResult } var invokedCreateBudget = false var invokedCreateBudgetCount = 0 var invokedCreateBudgetParameters: (data: BudgetServiceCreateData, Void)? var invokedCreateBudgetParametersList = [(data: BudgetServiceCreateData, Void)]() var stubbedCreateBudgetCallbackResult: BudgetServiceResult? func createBudget(data: BudgetServiceCreateData, callback: ((BudgetServiceResult) -> Void)?) { invokedCreateBudget = true invokedCreateBudgetCount += 1 invokedCreateBudgetParameters = (data, ()) invokedCreateBudgetParametersList.append((data, ())) if let result = stubbedCreateBudgetCallbackResult { callback?(result) } } var invokedFetchBudgetInfo = false var invokedFetchBudgetInfoCount = 0 var invokedFetchBudgetInfoParameters: (budgetId: String, Void)? var invokedFetchBudgetInfoParametersList = [(budgetId: String, Void)]() var stubbedFetchBudgetInfoCallbackResult: BudgetServiceResult? func fetchBudgetInfo(budgetId: String, callback: ((BudgetServiceResult) -> Void)?) { invokedFetchBudgetInfo = true invokedFetchBudgetInfoCount += 1 invokedFetchBudgetInfoParameters = (budgetId, ()) invokedFetchBudgetInfoParametersList.append((budgetId, ())) if let result = stubbedFetchBudgetInfoCallbackResult { callback?(result) } } }
mit
4e97d14fc2d1b6b7729e69797dd05b00
37.672414
98
0.728934
4.77234
false
false
false
false
valleyman86/ReactiveCocoa
ReactiveCocoa/Swift/ObjectiveCBridging.swift
13
6073
// // ObjectiveCBridging.swift // ReactiveCocoa // // Created by Justin Spahr-Summers on 2014-07-02. // Copyright (c) 2014 GitHub, Inc. All rights reserved. // import Result extension RACDisposable: Disposable {} extension RACScheduler: DateSchedulerType { public var currentDate: NSDate { return NSDate() } public func schedule(action: () -> ()) -> Disposable? { return self.schedule(action) } public func scheduleAfter(date: NSDate, action: () -> ()) -> Disposable? { return self.after(date, schedule: action) } public func scheduleAfter(date: NSDate, repeatingEvery: NSTimeInterval, withLeeway: NSTimeInterval, action: () -> ()) -> Disposable? { return self.after(date, repeatingEvery: repeatingEvery, withLeeway: withLeeway, schedule: action) } } extension ImmediateScheduler { public func toRACScheduler() -> RACScheduler { return RACScheduler.immediateScheduler() } } extension UIScheduler { public func toRACScheduler() -> RACScheduler { return RACScheduler.mainThreadScheduler() } } extension QueueScheduler { public func toRACScheduler() -> RACScheduler { return RACTargetQueueScheduler(name: "org.reactivecocoa.ReactiveCocoa.QueueScheduler.toRACScheduler()", targetQueue: queue) } } private func defaultNSError(message: String, #file: String, #line: Int) -> NSError { let error = Result<(), NSError>.error(file: file, line: line) var userInfo = error.userInfo userInfo?[NSLocalizedDescriptionKey] = message return NSError(domain: error.domain, code: error.code, userInfo: userInfo) } extension RACSignal { /// Creates a SignalProducer which will subscribe to the receiver once for /// each invocation of start(). public func toSignalProducer(file: String = __FILE__, line: Int = __LINE__) -> SignalProducer<AnyObject?, NSError> { return SignalProducer { observer, disposable in let next = { (obj: AnyObject?) -> () in sendNext(observer, obj) } let error = { (nsError: NSError?) -> () in sendError(observer, nsError ?? defaultNSError("Nil RACSignal error", file: file, line: line)) } let completed = { sendCompleted(observer) } let selfDisposable: RACDisposable? = self.subscribeNext(next, error: error, completed: completed) disposable.addDisposable(selfDisposable) } } } /// Turns each value into an Optional. private func optionalize<T, E>(signal: Signal<T, E>) -> Signal<T?, E> { return signal |> map { Optional($0) } } /// Creates a RACSignal that will start() the producer once for each /// subscription. /// /// Any `Interrupted` events will be silently discarded. public func toRACSignal<T: AnyObject, E>(producer: SignalProducer<T, E>) -> RACSignal { return toRACSignal(producer |> optionalize) } /// Creates a RACSignal that will start() the producer once for each /// subscription. /// /// Any `Interrupted` events will be silently discarded. public func toRACSignal<T: AnyObject, E>(producer: SignalProducer<T?, E>) -> RACSignal { return RACSignal.createSignal { subscriber in let selfDisposable = producer.start(next: { value in subscriber.sendNext(value) }, error: { error in subscriber.sendError(error.nsError) }, completed: { subscriber.sendCompleted() }) return RACDisposable { selfDisposable.dispose() } } } /// Creates a RACSignal that will observe the given signal. /// /// Any `Interrupted` event will be silently discarded. public func toRACSignal<T: AnyObject, E>(signal: Signal<T, E>) -> RACSignal { return toRACSignal(signal |> optionalize) } /// Creates a RACSignal that will observe the given signal. /// /// Any `Interrupted` event will be silently discarded. public func toRACSignal<T: AnyObject, E>(signal: Signal<T?, E>) -> RACSignal { return RACSignal.createSignal { subscriber in let selfDisposable = signal.observe(next: { value in subscriber.sendNext(value) }, error: { error in subscriber.sendError(error.nsError) }, completed: { subscriber.sendCompleted() }) return RACDisposable { selfDisposable?.dispose() } } } extension RACCommand { /// Creates an Action that will execute the receiver. /// /// Note that the returned Action will not necessarily be marked as /// executing when the command is. However, the reverse is always true: /// the RACCommand will always be marked as executing when the action is. public func toAction(file: String = __FILE__, line: Int = __LINE__) -> Action<AnyObject?, AnyObject?, NSError> { let enabledProperty = MutableProperty(true) enabledProperty <~ self.enabled.toSignalProducer() |> map { $0 as! Bool } |> catch { _ in SignalProducer<Bool, NoError>(value: false) } return Action(enabledIf: enabledProperty) { (input: AnyObject?) -> SignalProducer<AnyObject?, NSError> in let executionSignal = RACSignal.defer { return self.execute(input) } return executionSignal.toSignalProducer(file: file, line: line) } } } extension Action { private var commandEnabled: RACSignal { let enabled = self.enabled.producer |> map { $0 as NSNumber } return toRACSignal(enabled) } } /// Creates a RACCommand that will execute the action. /// /// Note that the returned command will not necessarily be marked as /// executing when the action is. However, the reverse is always true: /// the Action will always be marked as executing when the RACCommand is. public func toRACCommand<Output: AnyObject, E>(action: Action<AnyObject?, Output, E>) -> RACCommand { return RACCommand(enabled: action.commandEnabled) { (input: AnyObject?) -> RACSignal in return toRACSignal(action.apply(input)) } } /// Creates a RACCommand that will execute the action. /// /// Note that the returned command will not necessarily be marked as /// executing when the action is. However, the reverse is always true: /// the Action will always be marked as executing when the RACCommand is. public func toRACCommand<Output: AnyObject, E>(action: Action<AnyObject?, Output?, E>) -> RACCommand { return RACCommand(enabled: action.commandEnabled) { (input: AnyObject?) -> RACSignal in return toRACSignal(action.apply(input)) } }
mit
c262cfea259d421aad6a4849b1c4c230
31.132275
135
0.720566
3.918065
false
false
false
false
El-Arnault/Snake-Game-Project
Snake/MenuScene.swift
1
1550
// // MenuScene.swift // Snake // // Created by Max Zhuravsky on 3/20/17. // Copyright © 2017 Moscow State University. All rights reserved. // import SpriteKit class MenuScene : SKScene { let background = SKVideoNode(fileNamed: "Gameplay.mov") override func didMove(to view: SKView) { setupScene() background.run(SKAction.repeatForever(SKAction.sequence([ SKAction.rotate(byAngle: CGFloat(2 * M_PI), duration: 8), SKAction.rotate(byAngle: CGFloat(-2 * M_PI), duration: 8) ]))) } private func setupScene() { backgroundColor = SKColor.white background.anchorPoint = CGPoint(x: 0.5, y: 0.5) background.position = CGPoint(x: 300, y: 300) background.size = CGSize(width: 600, height: 600) background.play() addChild(background) } override func keyDown(with event: NSEvent) { switch (event.keyCode) { case 36: leaveScene() default: print("Unknown key pressed: \(event.keyCode)\n") } } private func leaveScene() { let transition = SKTransition.reveal(with: SKTransitionDirection.up, duration: 1.0) let nextScene = GameScene(size: self.size) nextScene.scaleMode = SKSceneScaleMode.fill background.pause() background.removeAllChildren() self.view?.presentScene(nextScene, transition: transition) } }
mit
c1256c02b22e31dad0e3d91bf3c10bca
26.660714
91
0.579083
4.413105
false
false
false
false
daher-alfawares/Chart
Chart/Circle.swift
1
2772
// // CircleChartView.swift // Circle // // Created by Daher Alfawares on 1/12/16. // Copyright © 2016 Daher Alfawares. All rights reserved. // import Foundation import UIKit @IBDesignable class Circle : UIView { let π = CGFloat(M_PI) var userColors : Array<UIColor>! var userData : Array<Double>! { didSet { setNeedsDisplay() } } override func draw(_ rect: CGRect) { let data = getData() let colors = getColors() let calculator = CircleCalculator( Data: data, StartAngle:Double(startAngle), SpaceAngle:Double(spaceAngle) ) let center = CGPoint(x:bounds.width/2, y: bounds.height/2) let radius : CGFloat = min(bounds.width, bounds.height)/2 for arc in calculator.arcs() { let path = UIBezierPath( arcCenter: center, radius: radius - (arcWidth/2), startAngle: CGFloat(arc.start()), endAngle: CGFloat(arc.end()), clockwise: true) path.lineWidth = arcWidth colors[arc.index()%colors.count].setStroke() path.stroke() } } func getData()->Array<Double> { if let _ = userData { return userData } return [ Double(data_1), Double(data_2), Double(data_3), Double(data_4), Double(data_5), Double(data_6)] } func getColors()->Array<UIColor> { if let _ = userColors { return userColors } return [ color_1, color_2, color_3, color_4, color_5, color_6] } @IBInspectable var arcWidth : CGFloat = 20 @IBInspectable var startAngle : CGFloat = 0 @IBInspectable var spaceAngle : CGFloat = 2 @IBInspectable var color_1 : UIColor = UIColor.red @IBInspectable var color_2 : UIColor = UIColor.green @IBInspectable var color_3 : UIColor = UIColor.blue @IBInspectable var color_4 : UIColor = UIColor.purple @IBInspectable var color_5 : UIColor = UIColor.cyan @IBInspectable var color_6 : UIColor = UIColor.orange @IBInspectable var data_1 : CGFloat = 100 @IBInspectable var data_2 : CGFloat = 200 @IBInspectable var data_3 : CGFloat = 150 @IBInspectable var data_4 : CGFloat = 100 @IBInspectable var data_5 : CGFloat = 200 @IBInspectable var data_6 : CGFloat = 150 }
apache-2.0
bbc240c5630fd42fe09dfaa44ea11834
25.634615
66
0.513357
4.608985
false
false
false
false
WestlakeAPC/game-off-2016
external/Fiber2D/Fiber2D/ResponderManager.swift
1
18612
// // ResponderManager.swift // // Created by Andrey Volodin on 07.06.16. // Copyright © 2016. All rights reserved. // import SwiftMath import Cocoa public enum MouseButton: Int { case left case right case other } /** * Defines a running iOS/OSX responder. */ internal final class RunningResponder { /** * Holdes the target of the touch. This is the node which accepted the touch. */ var target: Node! #if os(iOS) /** * Holds the current touch. Note that touches must not be retained. */ weak var touch: CCTouch! /** * Holdes the current event. Note that events must not be retained. */ weak var event: CCTouchEvent! #endif #if os(OSX) /** * Button in the currently ongoing event. */ var button: MouseButton! #endif } let RESPONDER_MANAGER_BUFFER_SIZE = 128 /** * The responder manager handles touches. */ internal final class ResponderManager : NSObject { /** * Enables the responder manager. * When the responder manager is disabled, all current touches will be cancelled and no further touch handling registered. */ var enabled = true { didSet { guard oldValue != enabled else { return } // cancel ongoing touches, if disabled if !enabled { self.cancelAllResponders() } } } internal var responderList = [Node]() // list of active responders internal var dirty = true// list of responders should be rebuild internal var currentEventProcessed: Bool = false // current event was processed internal var exclusiveMode = false // manager only responds to current exclusive responder internal var director: Director! internal var runningResponderList = [RunningResponder]() init(director: Director) { super.init() self.director = director // reset touch handling self.removeAllResponders() } func discardCurrentEvent() { self.currentEventProcessed = false } func buildResponderList() { // rebuild responder list self.removeAllResponders() assert(director != nil, "Missing current director. Probably not bound.") assert(director.runningScene != nil, "Missing current running scene.") self.buildResponderList(director.runningScene!) self.dirty = false } func buildResponderList(_ node: Node) { // dont add invisible nodes if !node.visible { return } var shouldAddNode: Bool = node.userInteractionEnabled defer { // if eligible, add the current node to the responder list if shouldAddNode { self.addResponder(node) } } // scan through children, and build responder list for child: Node in node.children { if shouldAddNode && child.zOrder >= 0 { self.addResponder(node) shouldAddNode = false } self.buildResponderList(child) } } func addResponder(_ responder: Node!) { guard responder != nil else { assertionFailure("Trying to add a nil responder") return } self.responderList.append(responder) assert(responderList.count < RESPONDER_MANAGER_BUFFER_SIZE, "Number of touchable nodes pr. scene can not exceed \(RESPONDER_MANAGER_BUFFER_SIZE)") } func removeAllResponders() { responderList = [] } func cancelAllResponders() { runningResponderList.forEach { (r: RunningResponder) in self.cancelResponder(r) } runningResponderList = [] self.exclusiveMode = false } func markAsDirty() { self.dirty = true } func nodeAtPoint(_ pos: Point) -> Node? { if dirty { self.buildResponderList() } // scan backwards through touch responders for node in responderList.reversed() { // check for hit test if node.hitTestWithWorldPos(pos) { return (node) } } // nothing found return nil } func nodesAtPoint(_ pos: Point) -> [AnyObject] { if dirty { self.buildResponderList() } return responderList.filter { $0.hitTestWithWorldPos(pos) } } #if os(iOS) func touchesBegan(touches: Set<AnyObject>, withEvent event: CCTouchEvent) { if !enabled { return } if exclusiveMode { return } // End editing any text fields director.view!.endEditing(true) var responderCanAcceptTouch: Bool if dirty { self.buildResponderList() } // go through all touches for touch: CCTouch in touches { var worldTouchLocation: Point = director.convertToGL(touch.locationInView((director.view as! CCView))) // scan backwards through touch responders for var index = responderListCount - 1; index >= 0; index-- { var node: Node = responderList[index] // check for hit test if node.clippedHitTestWithWorldPos(worldTouchLocation) { // check if node has exclusive touch if node.isExclusiveTouch { self.cancelAllResponders() self.exclusiveMode = true } // if not a multi touch node, check if node already is being touched responderCanAcceptTouch = true if !node.isMultipleTouchEnabled { // scan current touch objects, and break if object already has a touch for responderEntry: RunningResponder in runningResponderList { if responderEntry.target == node { responderCanAcceptTouch = false } } } if !responderCanAcceptTouch { } // begin the touch self.currentEventProcessed = true if node.respondsToSelector("touchBegan:withEvent:") { node.touchBegan(touch, withEvent: event) } // if touch was processed, add it and break if currentEventProcessed { self.addResponder(node, withTouch: touch, andEvent: event) } } } } } func touchesMoved(touches: Set<AnyObject>, withEvent event: CCTouchEvent) { if !enabled { return } if dirty { self.buildResponderList() } // go through all touches for touch: CCTouch in touches { // get touch object var touchEntry: RunningResponder = self.responderForTouch(touch) // if a touch object was found if touchEntry != nil { var node: Node = (touchEntry.target as! Node) // check if it locks touches if node.claimsUserInteraction { // move the touch if node.respondsToSelector("touchMoved:withEvent:") { node.touchMoved(touch, withEvent: event) } } else { // as node does not lock touch, check if it was moved outside if !node.clippedHitTestWithWorldPos(director.convertToGL(touch.locationInView(director.view!))) { // cancel the touch if node.respondsToSelector("touchCancelled:withEvent:") { node.touchCancelled(touch, withEvent: event) } // remove from list runningResponderList.removeObject(touchEntry) // always end exclusive mode self.exclusiveMode = false } else { // move the touch if node.respondsToSelector("touchMoved:withEvent:") { node.touchMoved(touch, withEvent: event) } } } } else { if !exclusiveMode { // scan backwards through touch responders for var index = responderListCount - 1; index >= 0; index-- { var node: Node = responderList[index] // if the touch responder does not lock touch, it will receive a touchBegan if a touch is moved inside if !node.claimsUserInteraction && node.clippedHitTestWithWorldPos(director.convertToGL(touch.locationInView(director.view!))) { // check if node has exclusive touch if node.isExclusiveTouch { self.cancelAllResponders() self.exclusiveMode = true } // begin the touch self.currentEventProcessed = true if node.respondsToSelector("touchBegan:withEvent:") { node.touchBegan(touch, withEvent: event) } // if touch was accepted, add it and break if currentEventProcessed { self.addResponder(node, withTouch: touch, andEvent: event) } } } } } } } func touchesEnded(touches: Set<AnyObject>, withEvent event: CCTouchEvent) { if !enabled { return } if dirty { self.buildResponderList() } // go through all touches for touch: CCTouch in touches { // get touch object var touchEntry: RunningResponder = self.responderForTouch(touch) if touchEntry != nil { var node: Node = (touchEntry.target as! Node) // end the touch if node.respondsToSelector("touchEnded:withEvent:") { node.touchEnded(touch, withEvent: event) } // remove from list runningResponderList.removeObject(touchEntry) // always end exclusive mode self.exclusiveMode = false } } } func touchesCancelled(touches: Set<AnyObject>, withEvent event: CCTouchEvent) { if !enabled { return } if dirty { self.buildResponderList() } // go through all touches for touch: CCTouch in touches { // get touch object var touchEntry: RunningResponder = self.responderForTouch(touch) if touchEntry != nil { self.cancelResponder(touchEntry) // always end exclusive mode self.exclusiveMode = false } } } // finds a responder object for a touch func responderForTouch(touch: CCTouch) -> RunningResponder { for touchEntry: RunningResponder in runningResponderList { if touchEntry.touch == touch { return touchEntry } } return (nil) } // adds a responder object ( running responder ) to the responder object list func addResponder(node: Node, withTouch touch: CCTouch, andEvent event: CCTouchEvent) { var touchEntry: RunningResponder // create a new touch object touchEntry = RunningResponder() touchEntry.target = node touchEntry.touch = touch touchEntry.event = event runningResponderList.append(touchEntry) } // cancels a running responder func cancelResponder(responder: RunningResponder) { var node: Node = (responder.target as! Node) // cancel the touch if node.respondsToSelector("touchCancelled:withEvent:") { node.touchCancelled(responder.touch, withEvent: responder.event) } // remove from list runningResponderList.removeObject(responder) } #endif #if os(OSX) func mouseDown(_ theEvent: NSEvent, button: MouseButton) { if !enabled { return } if dirty { self.buildResponderList() } self.executeOnEachResponder({(node: Node) -> Void in node.mouseDown(theEvent, button: button) if self.currentEventProcessed { self.addResponder(node, withButton: button) } }, withEvent: theEvent) } func mouseDragged(_ theEvent: NSEvent, button: MouseButton) { if !enabled { return } if dirty { self.buildResponderList() } if let responder: RunningResponder = self.responderForButton(button) { // This drag event is already associated with a specific target. // Items that claim user interaction receive events even if they occur outside of the bounds of the object. if responder.target.claimsUserInteraction || responder.target.clippedHitTestWithWorldPos(director.convertEventToGL(theEvent)) { Director.pushCurrentDirector(director) responder.target.mouseDragged(theEvent, button: button) Director.popCurrentDirector() } else { runningResponderList.removeObject(responder) } } else { self.executeOnEachResponder({(node: Node) -> Void in node.mouseDragged(theEvent, button: button) if self.currentEventProcessed { self.addResponder(node, withButton: button) } }, withEvent: theEvent) } } func mouseUp(_ theEvent: NSEvent, button: MouseButton) { if dirty { self.buildResponderList() } if let responder = self.responderForButton(button) { Director.pushCurrentDirector(director) responder.target.mouseUp(theEvent, button: button) Director.popCurrentDirector() runningResponderList.removeObject(responder) } } func scrollWheel(_ theEvent: NSEvent) { if !enabled { return } if dirty { self.buildResponderList() } // if otherMouse is active, scrollWheel goes to that node // otherwise, scrollWheel goes to the node under the cursor if let responder: RunningResponder = self.responderForButton(.other) { self.currentEventProcessed = true Director.pushCurrentDirector(director) responder.target.scrollWheel(theEvent) Director.popCurrentDirector() // if mouse was accepted, return if currentEventProcessed { return } } self.executeOnEachResponder({(node: Node) -> Void in node.scrollWheel(theEvent) }, withEvent: theEvent) } func mouseMoved(_ theEvent: NSEvent) { if !enabled { return } if dirty { self.buildResponderList() } self.executeOnEachResponder({(node: Node) -> Void in node.mouseMoved(theEvent) }, withEvent: theEvent) } func executeOnEachResponder(_ block: (Node) -> Void, withEvent theEvent: NSEvent) { Director.pushCurrentDirector(director) // scan through responders, and find first one for node in responderList.reversed() { // check for hit test if node.clippedHitTestWithWorldPos(director.convertEventToGL(theEvent)) { self.currentEventProcessed = true block(node) // if mouse was accepted, break if currentEventProcessed { } } } Director.popCurrentDirector() } func keyDown(_ theEvent: NSEvent) { if !enabled { return } if dirty { self.buildResponderList() } Director.pushCurrentDirector(director) responderList.reversed().forEach { $0.keyDown(theEvent) } Director.popCurrentDirector() } func keyUp(_ theEvent: NSEvent) { if !enabled { return } if dirty { self.buildResponderList() } Director.pushCurrentDirector(director) responderList.reversed().forEach { $0.keyUp(theEvent) } Director.popCurrentDirector() } func flagsChanged(_ theEvent: NSEvent) { if !enabled { return } if dirty { self.buildResponderList() } Director.pushCurrentDirector(director) responderList.reversed().forEach { $0.flagsChanged(theEvent) } Director.popCurrentDirector() } // finds a responder object for an event func responderForButton(_ button: MouseButton) -> RunningResponder? { for touchEntry: RunningResponder in runningResponderList { if touchEntry.button == button { return touchEntry } } return nil } // adds a responder object ( running responder ) to the responder object list func addResponder(_ node: Node, withButton button: MouseButton) { var touchEntry: RunningResponder // create a new touch object touchEntry = RunningResponder() touchEntry.target = node touchEntry.button = button runningResponderList.append(touchEntry) } func cancelResponder(_ responder: RunningResponder) { runningResponderList.removeObject(responder) } #endif }
apache-2.0
89291ee1a4a37ef6cace7304c9b97524
32.838182
151
0.53909
5.357225
false
false
false
false
Amazing-Team/GlobeCheckr
TinderSwipeCardsSwift/SettingsView.swift
1
6593
// // SettingsView.swift // TinderSwipeCardsSwift // // Created by Andrei Nevar on 31/10/15. // Copyright © 2015 gcweb. All rights reserved. // import UIKit import Foundation class SettingsView: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate, UITextFieldDelegate { @IBAction func callAPIandGo(sender: UIButton) { /* API Structure // Origin airport based from user's location (e.x. ams,bcn) // Date of departure yyyyMMdd(e.x 20150606) // Date of return yyyyMMdd(e.x 20150606) // Price range (e.x. 50-100) // Number of people */ let url = NSURL(string: "http://opendutchhackathon.w3ibm.mybluemix.net/ams/20151101/20151110/100-2000/2") let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in //Table with the destiantions available var destinations = [String]() //Table with the prices of the aller var pricesAller = [Int]() //Table with the prices of the return var pricesRetur = [Int]() //Table with the total prices of the trips //var pricesTotal = [Int]() //Table with the departure times of the aller var departureTimeAller = [String]() //Table with the arrival times of the aller var arrivalTimeAller = [String]() //Table with the departure times of the return var departureTimeRetur = [String]() //Table with the arrival times of the return var arrivalTimeRetur = [String]() do { let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary destinations = jsonResult!.valueForKeyPath("flightOffer.inboundFlight.departureAirport.locationCode") as! [String]; pricesAller = jsonResult!.valueForKeyPath("flightOffer.inboundFlight.pricingInfo.totalPriceAllPassengers") as! [Int]; pricesRetur = jsonResult!.valueForKeyPath("flightOffer.outboundFlight.pricingInfo.totalPriceAllPassengers") as! [Int]; departureTimeAller = jsonResult!.valueForKeyPath("flightOffer.inboundFlight.departureDateTime") as! [String]; arrivalTimeAller = jsonResult!.valueForKeyPath("flightOffer.inboundFlight.arrivalDateTime") as! [String]; departureTimeRetur = jsonResult!.valueForKeyPath("flightOffer.outboundFlight.departureDateTime") as! [String]; arrivalTimeRetur = jsonResult!.valueForKeyPath("flightOffer.outboundFlight.arrivalDateTime") as! [String]; print(destinations) for (var i = 0; i < pricesAller.count; i++ ){ pricesTotal.append(pricesAller[i] + pricesRetur[i]) } print(pricesTotal) print(departureTimeAller) print(arrivalTimeAller) print(departureTimeRetur) print(arrivalTimeRetur) } catch let error as NSError { print(error) } } task.resume() } @IBAction func tempSlider(sender: UISlider) { let currentValue = Int(sender.value) var plus = "" if(currentValue > 0){plus = "+"} else {plus = ""} temperatureLabel.text = "\(plus)\(currentValue)°C" } @IBAction func costSlider(sender: UISlider) { let currentValue = Int(sender.value) costLabel.text = "\(currentValue)€" if(currentValue == 5000){costLabel.text = "∞"} } @IBOutlet weak var tempSlider: UISlider! @IBOutlet weak var costSlider: UISlider! @IBOutlet weak var temperatureLabel: UILabel! @IBOutlet weak var costLabel: UILabel! @IBOutlet weak var justPicker: UIPickerView! @IBOutlet weak var justPicker2: UIPickerView! // @IBOutlet var txtTest : UITextField = nil @IBOutlet weak var txtTest: UITextField! = nil let monthsData = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sept","Oct", "Nov", "Dec"] var daysArray = [Int] () var yearsArray = [Int] () func populateArray (start:Int, end:Int) -> [Int]{ var daysData = [Int]() for index in start...end { daysData.append(index) } return daysData } override func viewDidLoad() { super.viewDidLoad() daysArray = populateArray (1, end: 31) yearsArray = populateArray (2015, end: 2040) justPicker.setValue(UIColor.whiteColor(), forKeyPath: "textColor") justPicker.dataSource = self justPicker.delegate = self justPicker2.setValue(UIColor.whiteColor(), forKeyPath: "textColor") justPicker2.dataSource = self justPicker2.delegate = self } func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 3 } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { if (component == 0) { return daysArray.count } else if (component == 1){ return monthsData.count } else if (component == 2){ return yearsArray.count } return 0 } func pickerView(pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusingView view: UIView?) -> UIView { let pickerLabel = UILabel() var titleData: String = "" if (component == 0) { titleData = String(daysArray[row]) } else if (component == 1){ titleData = monthsData[row] } else if (component == 2){ titleData = String(yearsArray[row]) } let myTitle = NSAttributedString(string: titleData, attributes: [NSFontAttributeName:UIFont(name: "Georgia", size: 26.0)!,NSForegroundColorAttributeName:UIColor.whiteColor()]) pickerLabel.attributedText = myTitle return pickerLabel } }
mit
22b5787016c14b0cd44822b10ce2dc04
34.605405
183
0.571429
5.066923
false
false
false
false