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
yq616775291/DiliDili-Fun
Pods/Kingfisher/Sources/KingfisherOptionsInfo.swift
5
6570
// // KingfisherOptionsInfo.swift // Kingfisher // // Created by Wei Wang on 15/4/23. // // Copyright (c) 2016 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if os(OSX) import AppKit #else import UIKit #endif /** * KingfisherOptionsInfo is a typealias for [KingfisherOptionsInfoItem]. You can use the enum of option item with value to control some behaviors of Kingfisher. */ public typealias KingfisherOptionsInfo = [KingfisherOptionsInfoItem] let KingfisherEmptyOptionsInfo = [KingfisherOptionsInfoItem]() /** Items could be added into KingfisherOptionsInfo. - TargetCache: The associated value of this member should be an ImageCache object. Kingfisher will use the specified cache object when handling related operations, including trying to retrieve the cached images and store the downloaded image to it. - Downloader: The associated value of this member should be an ImageDownloader object. Kingfisher will use this downloader to download the images. - Transition: Member for animation transition when using UIImageView. Kingfisher will use the `ImageTransition` of this enum to animate the image in if it is downloaded from web. The transition will not happen when the image is retrieved from either memory or disk cache. - DownloadPriority: Associated `Float` value will be set as the priority of image download task. The value for it should be between 0.0~1.0. If this option not set, the default value (`NSURLSessionTaskPriorityDefault`) will be used. - ForceRefresh: If set, `Kingfisher` will ignore the cache and try to fire a download task for the resource. - CacheMemoryOnly: If set, `Kingfisher` will only cache the value in memory but not in disk. - BackgroundDecode: Decode the image in background thread before using. - CallbackDispatchQueue: The associated value of this member will be used as the target queue of dispatch callbacks when retrieving images from cache. If not set, `Kingfisher` will use main quese for callbacks. - ScaleFactor: The associated value of this member will be used as the scale factor when converting retrieved data to an image. */ public enum KingfisherOptionsInfoItem { case TargetCache(ImageCache?) case Downloader(ImageDownloader?) case Transition(ImageTransition) case DownloadPriority(Float) case ForceRefresh case CacheMemoryOnly case BackgroundDecode case CallbackDispatchQueue(dispatch_queue_t?) case ScaleFactor(CGFloat) } infix operator <== { associativity none precedence 160 } // This operator returns true if two `KingfisherOptionsInfoItem` enum is the same, without considering the associated values. func <== (lhs: KingfisherOptionsInfoItem, rhs: KingfisherOptionsInfoItem) -> Bool { switch (lhs, rhs) { case (.TargetCache(_), .TargetCache(_)): return true case (.Downloader(_), .Downloader(_)): return true case (.Transition(_), .Transition(_)): return true case (.DownloadPriority(_), .DownloadPriority(_)): return true case (.ForceRefresh, .ForceRefresh): return true case (.CacheMemoryOnly, .CacheMemoryOnly): return true case (.BackgroundDecode, .BackgroundDecode): return true case (.CallbackDispatchQueue(_), .CallbackDispatchQueue(_)): return true case (.ScaleFactor(_), .ScaleFactor(_)): return true default: return false } } extension CollectionType where Generator.Element == KingfisherOptionsInfoItem { func kf_firstMatchIgnoringAssociatedValue(target: Generator.Element) -> Generator.Element? { return indexOf { $0 <== target }.flatMap { self[$0] } } } extension CollectionType where Generator.Element == KingfisherOptionsInfoItem { var targetCache: ImageCache? { if let item = kf_firstMatchIgnoringAssociatedValue(.TargetCache(nil)), case .TargetCache(let cache) = item { return cache } return nil } var downloader: ImageDownloader? { if let item = kf_firstMatchIgnoringAssociatedValue(.Downloader(nil)), case .Downloader(let downloader) = item { return downloader } return nil } var transition: ImageTransition { if let item = kf_firstMatchIgnoringAssociatedValue(.Transition(.None)), case .Transition(let transition) = item { return transition } return ImageTransition.None } var downloadPriority: Float { if let item = kf_firstMatchIgnoringAssociatedValue(.DownloadPriority(0)), case .DownloadPriority(let priority) = item { return priority } return NSURLSessionTaskPriorityDefault } var forceRefresh: Bool { return contains{ $0 <== .ForceRefresh } } var cacheMemoryOnly: Bool { return contains{ $0 <== .CacheMemoryOnly } } var backgroundDecode: Bool { return contains{ $0 <== .BackgroundDecode } } var callbackDispatchQueue: dispatch_queue_t { if let item = kf_firstMatchIgnoringAssociatedValue(.CallbackDispatchQueue(nil)), case .CallbackDispatchQueue(let queue) = item { return queue ?? dispatch_get_main_queue() } return dispatch_get_main_queue() } var scaleFactor: CGFloat { if let item = kf_firstMatchIgnoringAssociatedValue(.ScaleFactor(0)), case .ScaleFactor(let scale) = item { return scale } return 1.0 } }
mit
fe139a73196b4adbd3e619de3f179700
40.0625
272
0.70898
4.992401
false
false
false
false
Erin-Mounts/BridgeAppSDK
BridgeAppSDK/SBASurveyNavigationStep.swift
1
9121
// // SBAQuizStep.swift // BridgeAppSDK // // Copyright © 2016 Sage Bionetworks. All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // 3. Neither the name of the copyright holder(s) nor the names of any contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. No license is granted to the trademarks of // the copyright holders even if such marks are included in this software. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // import ResearchKit public protocol SBASurveyNavigationStep: SBANavigationRule { // Step identifier to go to if the quiz passed var skipToStepIdentifier: String { get set } // Should the rule skip if results match expected var skipIfPassed: Bool { get set } // Predicate to use for getting the matching step results var surveyStepResultFilterPredicate: NSPredicate { get } // Form step that matches with the given result func matchingSurveyStep(stepResult: ORKStepResult) -> ORKFormStep? } public final class SBASurveyFormStep: ORKFormStep, SBASurveyNavigationStep { public var surveyStepResultFilterPredicate: NSPredicate { return NSPredicate(format: "identifier = %@", self.identifier) } public func matchingSurveyStep(stepResult: ORKStepResult) -> ORKFormStep? { guard (stepResult.identifier == self.identifier) else { return nil } return self } // MARK: Stuff you can't extend on a protocol public var skipToStepIdentifier: String = ORKNullStepIdentifier public var skipIfPassed: Bool = false override public init(identifier: String) { super.init(identifier: identifier) } init(surveyItem: SBASurveyItem) { super.init(identifier: surveyItem.identifier) self.sharedCopyFromSurveyItem(surveyItem) } // MARK: NSCopying override public func copyWithZone(zone: NSZone) -> AnyObject { let copy = super.copyWithZone(zone) return self.sharedCopying(copy) } // MARK: NSSecureCoding required public init(coder aDecoder: NSCoder) { super.init(coder: aDecoder); self.sharedDecoding(coder: aDecoder) } override public func encodeWithCoder(aCoder: NSCoder) { super.encodeWithCoder(aCoder) self.sharedEncoding(aCoder) } } public final class SBASurveySubtaskStep: SBASubtaskStep, SBASurveyNavigationStep { public var surveyStepResultFilterPredicate: NSPredicate { return NSPredicate(format: "identifier BEGINSWITH %@", "\(self.identifier).") } public func matchingSurveyStep(stepResult: ORKStepResult) -> ORKFormStep? { return self.stepWithIdentifier(stepResult.identifier) as? ORKFormStep } // MARK: Stuff you can't extend on a protocol public var skipToStepIdentifier: String = ORKNullStepIdentifier public var skipIfPassed: Bool = false override public init(identifier: String, steps: [ORKStep]?) { super.init(identifier: identifier, steps: steps) } init(surveyItem: SBASurveyItem, steps: [ORKStep]?) { super.init(identifier: surveyItem.identifier, steps: steps) self.sharedCopyFromSurveyItem(surveyItem) } // MARK: NSCopying override public func copyWithZone(zone: NSZone) -> AnyObject { let copy = super.copyWithZone(zone) return self.sharedCopying(copy) } // MARK: NSSecureCoding required public init(coder aDecoder: NSCoder) { super.init(coder: aDecoder); self.sharedDecoding(coder: aDecoder) } override public func encodeWithCoder(aCoder: NSCoder) { super.encodeWithCoder(aCoder) self.sharedEncoding(aCoder) } } public final class SBASurveyFormItem : ORKFormItem { public var rulePredicate: NSPredicate? override public init(identifier: String, text: String?, answerFormat: ORKAnswerFormat?) { super.init(identifier: identifier, text: text, answerFormat: answerFormat) } override public init(identifier:String, text:String?, answerFormat:ORKAnswerFormat?, optional:Bool) { super.init(identifier:identifier, text: text, answerFormat: answerFormat, optional:optional); } // MARK: NSCopying override public func copyWithZone(zone: NSZone) -> AnyObject { let copy = super.copyWithZone(zone) guard let formItem = copy as? SBASurveyFormItem else { return copy } formItem.rulePredicate = self.rulePredicate return formItem } // MARK: NSSecureCoding required public init?(coder aDecoder: NSCoder) { rulePredicate = aDecoder.decodeObjectForKey("rulePredicate") as? NSPredicate super.init(coder: aDecoder); } override public func encodeWithCoder(aCoder: NSCoder) { super.encodeWithCoder(aCoder) if let rulePredicate = self.rulePredicate { aCoder.encodeObject(rulePredicate, forKey: "rulePredicate") } } } public extension SBASurveyNavigationStep { public func nextStepIdentifier(taskResult: ORKTaskResult, additionalTaskResults:[ORKTaskResult]?) -> String? { guard let results = taskResult.results else { return nil } let predicate = self.surveyStepResultFilterPredicate let passed = results.filter({ predicate.evaluateWithObject($0) && !matchesExpectedResult($0)}).count == 0 if (passed && self.skipIfPassed) || (!passed && !self.skipIfPassed) { return self.skipToStepIdentifier } return nil; } func matchesRulePredicate(item: AnyObject, result: ORKResult?) -> Bool? { if let rule = item as? SBASurveyFormItem, let predicate = rule.rulePredicate { // If the result is nil then it fails guard let result = result else { return false } // Otherwise, evaluate against the predicate return predicate.evaluateWithObject(result) } return nil } func matchesExpectedResult(result: ORKResult) -> Bool { if let stepResult = result as? ORKStepResult, let step = self.matchingSurveyStep(stepResult) { // evaluate each form item if let formItems = step.formItems { for formItem in formItems { let formResult = stepResult.resultForIdentifier(formItem.identifier) if let matchingRule = matchesRulePredicate(formItem, result:formResult) where !matchingRule { // If a form item does not match the expected result then exit, otherwise keep going return false } } } } return true; } func sharedCopying(copy: AnyObject) -> AnyObject { guard let step = copy as? SBASurveyNavigationStep else { return copy } step.skipToStepIdentifier = self.skipToStepIdentifier return step } func sharedDecoding(coder aDecoder: NSCoder) { self.skipToStepIdentifier = aDecoder.decodeObjectForKey("skipToStepIdentifier") as! String self.skipIfPassed = aDecoder.decodeBoolForKey("skipIfPassed") } func sharedEncoding(aCoder: NSCoder) { aCoder.encodeObject(self.skipToStepIdentifier, forKey: "skipToStepIdentifier") aCoder.encodeBool(self.skipIfPassed, forKey: "skipIfPassed") } func sharedCopyFromSurveyItem(surveyItem: AnyObject) { guard let surveyItem = surveyItem as? SBASurveyItem else { return } if let skipIdentifier = surveyItem.skipIdentifier { self.skipToStepIdentifier = skipIdentifier } self.skipIfPassed = surveyItem.skipIfPassed } }
bsd-3-clause
c47d969fb86fc20917e890a92bb9d3c7
37.158996
117
0.679167
5.033113
false
false
false
false
rsyncOSX/RsyncOSX
RsyncOSX/Configuration.swift
1
6495
// // ConfigurationsJSON.swift // RsyncOSX // // Created by Thomas Evensen on 26/05/2021. // Copyright © 2021 Thomas Evensen. All rights reserved. // // // Created by Thomas Evensen on 08/02/16. // Copyright © 2016 Thomas Evensen. All rights reserved. // import Foundation enum NumDayofweek: Int { case Monday = 2 case Tuesday = 3 case Wednesday = 4 case Thursday = 5 case Friday = 6 case Saturday = 7 case Sunday = 1 } enum StringDayofweek: String, CaseIterable, Identifiable, CustomStringConvertible { case Monday case Tuesday case Wednesday case Thursday case Friday case Saturday case Sunday var id: String { rawValue } var description: String { rawValue.localizedLowercase } } struct Configuration: Codable { var hiddenID: Int var task: String var localCatalog: String var offsiteCatalog: String var offsiteUsername: String var parameter1: String var parameter2: String var parameter3: String var parameter4: String var parameter5: String var parameter6: String var offsiteServer: String var backupID: String var dateRun: String? var snapshotnum: Int? // parameters choosed by user var parameter8: String? var parameter9: String? var parameter10: String? var parameter11: String? var parameter12: String? var parameter13: String? var parameter14: String? var rsyncdaemon: Int? // SSH parameters var sshport: Int? var sshkeypathandidentityfile: String? // Calculated days since last backup var dayssincelastbackup: String? var markdays: Bool = false var profile: String? // Snapshots, day to save and last = 1 or every last=0 var snapdayoffweek: String? var snaplast: Int? // Pre and post tasks var executepretask: Int? var pretask: String? var executeposttask: Int? var posttask: String? var haltshelltasksonerror: Int? var lastruninseconds: Double? { if let date = dateRun { let lastbackup = date.en_us_date_from_string() let seconds: TimeInterval = lastbackup.timeIntervalSinceNow return seconds * -1 } else { return nil } } // Used when reading JSON data from store // see in ReadConfigurationJSON init(_ data: DecodeConfiguration) { backupID = data.backupID ?? "" hiddenID = data.hiddenID ?? -1 localCatalog = data.localCatalog ?? "" offsiteCatalog = data.offsiteCatalog ?? "" offsiteServer = data.offsiteServer ?? "" offsiteUsername = data.offsiteUsername ?? "" parameter1 = data.parameter1 ?? "" parameter10 = data.parameter10 parameter11 = data.parameter11 parameter12 = data.parameter12 parameter13 = data.parameter13 parameter14 = data.parameter14 parameter2 = data.parameter2 ?? "" parameter3 = data.parameter3 ?? "" parameter4 = data.parameter4 ?? "" parameter5 = data.parameter5 ?? "" parameter6 = data.parameter6 ?? "" parameter8 = data.parameter8 parameter9 = data.parameter9 rsyncdaemon = data.rsyncdaemon sshkeypathandidentityfile = data.sshkeypathandidentityfile sshport = data.sshport task = data.task ?? "" executepretask = data.executepretask pretask = data.pretask executeposttask = data.executeposttask posttask = data.posttask snapshotnum = data.snapshotnum haltshelltasksonerror = data.haltshelltasksonerror // For snapshots if let snapshotnum = data.snapshotnum { self.snapshotnum = snapshotnum snapdayoffweek = data.snapdayoffweek ?? StringDayofweek.Sunday.rawValue snaplast = data.snaplast ?? 1 } // Last run of task if let dateRun = data.dateRun { self.dateRun = dateRun if let secondssince = lastruninseconds { dayssincelastbackup = String(format: "%.2f", secondssince / (60 * 60 * 24)) if secondssince / (60 * 60 * 24) > SharedReference.shared.marknumberofdayssince { markdays = true } } } } // Create an empty record with no values init() { hiddenID = -1 task = "" localCatalog = "" offsiteCatalog = "" offsiteUsername = "" parameter1 = "" parameter2 = "" parameter3 = "" parameter4 = "" parameter5 = "" parameter6 = "" offsiteServer = "" backupID = "" } } extension Configuration: Hashable, Equatable { static func == (lhs: Configuration, rhs: Configuration) -> Bool { return lhs.localCatalog == rhs.localCatalog && lhs.offsiteCatalog == rhs.offsiteCatalog && lhs.offsiteUsername == rhs.offsiteUsername && lhs.offsiteServer == rhs.offsiteServer && lhs.hiddenID == rhs.hiddenID && lhs.task == rhs.task && lhs.parameter1 == rhs.parameter1 && lhs.parameter2 == rhs.parameter2 && lhs.parameter3 == rhs.parameter3 && lhs.parameter4 == rhs.parameter4 && lhs.parameter5 == rhs.parameter5 && lhs.parameter6 == rhs.parameter6 && lhs.parameter8 == rhs.parameter8 && lhs.parameter9 == rhs.parameter9 && lhs.parameter10 == rhs.parameter10 && lhs.parameter11 == rhs.parameter11 && lhs.parameter12 == rhs.parameter12 && lhs.parameter13 == rhs.parameter13 && lhs.parameter14 == rhs.parameter14 && lhs.dateRun == rhs.dateRun } func hash(into hasher: inout Hasher) { hasher.combine(localCatalog) hasher.combine(offsiteUsername) hasher.combine(offsiteServer) hasher.combine(String(hiddenID)) hasher.combine(task) hasher.combine(parameter1) hasher.combine(parameter2) hasher.combine(parameter3) hasher.combine(parameter4) hasher.combine(parameter5) hasher.combine(parameter6) hasher.combine(parameter8) hasher.combine(parameter9) hasher.combine(parameter10) hasher.combine(parameter11) hasher.combine(parameter12) hasher.combine(parameter13) hasher.combine(parameter14) hasher.combine(dateRun) } }
mit
f1e5383f29852de7ac091a0839a4c56d
30.828431
97
0.614816
4.462543
false
false
false
false
teambox/RealmResultsController
Source/RealmLogger.swift
2
3269
// // RealmLogger.swift // RealmResultsController // // Created by Pol Quintana on 6/8/15. // Copyright © 2015 Redbooth. // import Foundation import RealmSwift /** Internal RealmResultsController class In charge of listen to Realm notifications and notify the RRCs when finished A logger is associated with one and only one Realm. */ class RealmLogger { weak var realm: Realm? var temporary: [RealmChange] = [] var notificationToken: NotificationToken? init(realm: Realm) { self.realm = realm if Thread.isMainThread { registerNotificationBlock() } else { CFRunLoopPerformBlock(CFRunLoopGetCurrent(), CFRunLoopMode.defaultMode.rawValue) { self.registerNotificationBlock() CFRunLoopStop(CFRunLoopGetCurrent()) } CFRunLoopRun() } } @objc func registerNotificationBlock() { notificationToken = realm?.addNotificationBlock { [weak self] notification, realm in if notification == .didChange { self?.finishRealmTransaction() } } } /** When a Realm finish a write transaction, notify any active RRC via NSNotificaion Then clean the current state. */ func finishRealmTransaction() { guard let realmIdentifier = realm?.realmIdentifier else { return } var notificationName = "realmChanges" //For testing if realmIdentifier == "testingRealm" { notificationName = "realmChangesTest" } NotificationCenter.default.post(name: Notification.Name(rawValue: notificationName), object: [realmIdentifier : temporary]) postIndividualNotifications() cleanAll() } /** Posts a notification for every change occurred in Realm */ func postIndividualNotifications() { for change: RealmChange in temporary { guard let object = change.mirror else { continue } guard let name = object.objectIdentifier() else { continue } NotificationCenter.default.post(name: Notification.Name(rawValue: name), object: change) } } func didAdd<T: RealmSwift.Object>(_ object: T) { add(object, action: .add) } func didUpdate<T: RealmSwift.Object>(_ object: T) { add(object, action: .update) } func didDelete<T: RealmSwift.Object>(_ object: T) { add(object, action: .delete) } /** When there is an operation in a Realm, instead of keeping a reference to the original object we create a mirror that is thread safe and can be passed to RRC to operate with it safely. :warning: the relationships of the Mirror are not thread safe. - parameter object Object that is involed in the transaction - parameter action Action that was performed on that object */ func add<T: RealmSwift.Object>(_ object: T, action: RealmAction) { let realmChange = RealmChange(type: type(of: (object as Object)), action: action, mirror: object.getMirror()) temporary.append(realmChange) } func cleanAll() { temporary.removeAll() } }
mit
4942ab9b993025494b5f7396a2f7762a
30.728155
117
0.626683
5.019969
false
false
false
false
laszlokorte/reform-swift
ReformExpression/ReformExpression/Colors.swift
1
1782
// // Colors.swift // ExpressionEngine // // Created by Laszlo Korte on 07.08.15. // Copyright © 2015 Laszlo Korte. All rights reserved. // private func clamp<T:Comparable>(_ value: T, minimum: T, maximum: T) -> T { return min(maximum, max(minimum, value)) } private func component(_ value: Value) -> UInt8 { switch value { case .stringValue(_): return UInt8(0) case .intValue(let int): return UInt8(clamp(int, minimum: 0, maximum: 255)) case .doubleValue(let double): return UInt8(clamp(double, minimum: 0, maximum: 1) * 255) case .colorValue(_): return UInt8(0) case .boolValue(let bool): return UInt8(bool ? 255 : 0) } } struct RGBConstructor : Function { static let arity = FunctionArity.fix(3) func apply(_ params: [Value]) -> Result<Value, EvaluationError> { guard params.count == 3 else { return .fail(.parameterCountMismatch(message: "expected three arguments")) } let r : UInt8 = component(params[0]) let g : UInt8 = component(params[1]) let b : UInt8 = component(params[2]) let a : UInt8 = 255 return .success(.colorValue(r:r,g:g,b:b,a:a)) } } struct RGBAConstructor : Function { static let arity = FunctionArity.fix(4) func apply(_ params: [Value]) -> Result<Value, EvaluationError> { guard params.count == 4 else { return .fail(.parameterCountMismatch(message: "expected four arguments")) } let r : UInt8 = component(params[0]) let g : UInt8 = component(params[1]) let b : UInt8 = component(params[2]) let a : UInt8 = component(params[3]) return .success(.colorValue(r:r,g:g,b:b,a:a)) } }
mit
a5853b2d6ae74f568e52841cd748bd7c
27.725806
86
0.594048
3.679752
false
false
false
false
erikfloresq/weriklandia
Weriklandia/Tools/Please.swift
1
1817
// // Utils.swift // Weriklandia // // Created by Erik Flores on 11/12/17. // Copyright © 2017 Erik Flores. All rights reserved. // import UIKit struct Please { func getDataFromJSON(_ file:String) -> NSData { guard let jsonFile: String = Bundle.main.path(forResource: file, ofType: "json") else { fatalError("JSON not found") } guard let data = NSData(contentsOfFile:jsonFile) else { fatalError("Error data from JSON") } return data } static func makeFeedback(type: UINotificationFeedbackType) { var feedbackGenerator: UINotificationFeedbackGenerator? = nil feedbackGenerator = UINotificationFeedbackGenerator() feedbackGenerator?.prepare() feedbackGenerator?.notificationOccurred(type) feedbackGenerator = nil } static func showAlert(withMessage message: String, in view: UIViewController) { let alert = UIAlertController(title: "Weriklandia", message: message, preferredStyle: .alert) let btnOk = UIAlertAction(title: "OK", style: .default) alert.addAction(btnOk) view.present(alert, animated: true) } static func showActivityButton(in view: UIView) -> UIActivityIndicatorView { let activityView = UIActivityIndicatorView() activityView.startAnimating() activityView.hidesWhenStopped = true let positionX = view.frame.size.width - 30 let positionY = view.frame.size.height / 2 activityView.frame = CGRect(x: positionX, y: positionY, width: 25, height: 0) view.addSubview(activityView) return activityView } static func addCornerRadiusTo(button: UIButton...) { for btn in button { btn.layer.cornerRadius = 5 } } }
mit
cce0b8d5692a83a8d88ec7a07d2b94eb
32.018182
101
0.649229
4.766404
false
false
false
false
tardieu/swift
stdlib/public/Platform/TiocConstants.swift
21
6240
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // Tty ioctl request constants, needed only on Darwin and FreeBSD. // Constants available on all platforms, also available on Linux. #if os(OSX) || os(iOS) || os(tvOS) || os(watchOS) || os(FreeBSD) /// Set exclusive use of tty. public var TIOCEXCL: UInt { return 0x2000740d } /// Reset exclusive use of tty. public var TIOCNXCL: UInt { return 0x2000740e } /// Flush buffers. public var TIOCFLUSH: UInt { return 0x80047410 } /// Get line discipline. public var TIOCGETD: UInt { return 0x4004741a } /// Set line discipline. public var TIOCSETD: UInt { return 0x8004741b } /// Set break bit. public var TIOCSBRK: UInt { return 0x2000747b } /// Clear break bit. public var TIOCCBRK: UInt { return 0x2000747a } /// Set data terminal ready. public var TIOCSDTR: UInt { return 0x20007479 } /// Clear data terminal ready. public var TIOCCDTR: UInt { return 0x20007478 } /// Get pgrp of tty. public var TIOCGPGRP: UInt { return 0x40047477 } /// Set pgrp of tty. public var TIOCSPGRP: UInt { return 0x80047476 } /// Output queue size. public var TIOCOUTQ: UInt { return 0x40047473 } /// Simulate terminal input. public var TIOCSTI: UInt { return 0x80017472 } /// Void tty association. public var TIOCNOTTY: UInt { return 0x20007471 } /// Pty: set/clear packet mode. public var TIOCPKT: UInt { return 0x80047470 } /// Stop output, like `^S`. public var TIOCSTOP: UInt { return 0x2000746f } /// Start output, like `^Q`. public var TIOCSTART: UInt { return 0x2000746e } /// Set all modem bits. public var TIOCMSET: UInt { return 0x8004746d } /// Bis modem bits. public var TIOCMBIS: UInt { return 0x8004746c } /// Bic modem bits. public var TIOCMBIC: UInt { return 0x8004746b } /// Get all modem bits. public var TIOCMGET: UInt { return 0x4004746a } /// Get window size. public var TIOCGWINSZ: UInt { return 0x40087468 } /// Set window size. public var TIOCSWINSZ: UInt { return 0x80087467 } /// Pty: set/clr usr cntl mode. public var TIOCUCNTL: UInt { return 0x80047466 } /// Simulate `^T` status message. public var TIOCSTAT: UInt { return 0x20007465 } /// Become virtual console. public var TIOCCONS: UInt { return 0x80047462 } /// Become controlling tty. public var TIOCSCTTY: UInt { return 0x20007461 } /// Pty: external processing. public var TIOCEXT: UInt { return 0x80047460 } /// Wait till output drained. public var TIOCDRAIN: UInt { return 0x2000745e } /// Modem: set wait on close. public var TIOCMSDTRWAIT: UInt { return 0x8004745b } /// Modem: get wait on close. public var TIOCMGDTRWAIT: UInt { return 0x4004745a } /// Enable/get timestamp of last input event. public var TIOCTIMESTAMP: UInt { return 0x40107459 } /// Set ttywait timeout. public var TIOCSDRAINWAIT: UInt { return 0x80047457 } /// Get ttywait timeout. public var TIOCGDRAINWAIT: UInt { return 0x40047456 } // From ioctl_compat.h. /// Hang up on last close. public var TIOCHPCL: UInt { return 0x20007402 } /// Get parameters -- gtty. public var TIOCGETP: UInt { return 0x40067408 } /// Set parameters -- stty. public var TIOCSETP: UInt { return 0x80067409 } /// As above, but no flushtty. public var TIOCSETN: UInt { return 0x8006740a } /// Set special characters. public var TIOCSETC: UInt { return 0x80067411 } /// Get special characters. public var TIOCGETC: UInt { return 0x40067412 } /// Bis local mode bits. public var TIOCLBIS: UInt { return 0x8004747f } /// Bic local mode bits. public var TIOCLBIC: UInt { return 0x8004747e } /// Set entire local mode word. public var TIOCLSET: UInt { return 0x8004747d } /// Get local modes. public var TIOCLGET: UInt { return 0x4004747c } /// Set local special chars. public var TIOCSLTC: UInt { return 0x80067475 } /// Get local special chars. public var TIOCGLTC: UInt { return 0x40067474 } #endif // Darwin only constants, also available on Linux. #if os(OSX) || os(iOS) || os(tvOS) || os(watchOS) /// Get termios struct. public var TIOCGETA: UInt { return 0x40487413 } /// Set termios struct. public var TIOCSETA: UInt { return 0x80487414 } /// Drain output, set. public var TIOCSETAW: UInt { return 0x80487415 } /// Drn out, fls in, set. public var TIOCSETAF: UInt { return 0x80487416 } /// Pty: generate signal. public var TIOCSIG: UInt { return 0x2000745f } /// Get modem control state. public var TIOCMODG: UInt { return 0x40047403 } /// Set modem control state. public var TIOCMODS: UInt { return 0x80047404 } /// Internal input VSTART. public var TIOCIXON: UInt { return 0x20007481 } /// Internal input VSTOP. public var TIOCIXOFF: UInt { return 0x20007480 } /// Remote input editing. public var TIOCREMOTE: UInt { return 0x80047469 } /// 4.2 compatibility. public var TIOCSCONS: UInt { return 0x20007463 } /// Enable/get timestamp of last DCd rise. public var TIOCDCDTIMESTAMP: UInt { return 0x40107458 } /// Download microcode to DSI Softmodem. public var TIOCDSIMICROCODE: UInt { return 0x20007455 } /// Grantpt(3). public var TIOCPTYGRANT: UInt { return 0x20007454 } /// Ptsname(3). public var TIOCPTYGNAME: UInt { return 0x40807453 } /// Unlockpt(3). public var TIOCPTYUNLK: UInt { return 0x20007452 } #endif // FreeBSD specific values and constants available only on FreeBSD. #if os(FreeBSD) /// Get termios struct. public var TIOCGETA: UInt { return 0x402c7413 } /// Set termios struct. public var TIOCSETA: UInt { return 0x802c7414 } /// Drain output, set. public var TIOCSETAW: UInt { return 0x802c7415 } /// Drn out, fls in, set. public var TIOCSETAF: UInt { return 0x802c7416 } /// Pty: generate signal. public var TIOCSIG: UInt { return 0x2004745f } /// Get pts number. public var TIOCGPTN: UInt { return 0x4004740f } /// Pts master validation. public var TIOCPTMASTER: UInt { return 0x2000741c } /// Get session id. public var TIOCGSID: UInt { return 0x40047463 } #endif
apache-2.0
8cdced045fe2bf312f1e23423c54768b
34.254237
80
0.711218
3.072378
false
false
false
false
whyefa/RCSwitch
RCSwitch/RCSwitch.swift
1
11469
// // RCSwitch.swift // RCSwitch // // Created by Developer on 2016/11/7. // Copyright © 2016年 Beijing Haitao International Travel Service Co., Ltd. All rights reserved. // a swich for password security enter import UIKit let rcSwitchFontSize: CGFloat = 12 public class RCSwitch: UIControl, CAAnimationDelegate { // the text showing when isOn == true public var onText: String = "" { didSet { setNeedsLayout() } } // the text showing when isOn == false, default show ... public var offText: String = "" { didSet { setNeedsLayout() } } // shadowLayer show on superview or not, default is false public var isShadowShowing: Bool = false // onText background color public var onColor: UIColor = UIColor(red:243/255.0, green: 68/255.0, blue:107/255.0, alpha: 1) { didSet { onLayer.fillColor = onColor.cgColor setNeedsLayout() } } // offText background color public var offColor: UIColor = UIColor.white { didSet { offLayer.fillColor = offColor.cgColor setNeedsLayout() } } // textlayer show onText string private var onTextLayer: CATextLayer! // textlayer show offText string private var offTextLayer: CATextLayer? // switch max length private let maxLength: CGFloat = 60 // thumb offset the border private let margin: CGFloat = 2 // leftcorner / right corner radius private let minRadius:CGFloat = 3 // thumb radius # private var thumbRadius: CGFloat = 0 // animation duration private let rcswitchAnimationDuration: CFTimeInterval = 0.2 // on backgound layer fill with onColor private var onLayer: CAShapeLayer! // off background layer fill with offColor private var offLayer: CAShapeLayer! // round thumb layer private var thumbLayer: CAShapeLayer! // switch shadow color private var shadowLayer: CAShapeLayer! // if offText is not nil, offLayer show three dot private var dots = [CAShapeLayer]() // path of whole bounds private var fullPath: CGPath! // left thumb center when isOn == true private var leftArcCenter: CGPoint! // right thumb center when isOn == false private var rightArcCenter: CGPoint! public var isOn: Bool = false { didSet { self.isUserInteractionEnabled = false let leftPath = UIBezierPath(arcCenter: leftArcCenter, radius: thumbRadius, startAngle: 0, endAngle: CGFloat(M_PI*2), clockwise: true).cgPath let rightPath = UIBezierPath(arcCenter: rightArcCenter, radius: thumbRadius, startAngle: 0, endAngle: CGFloat(M_PI*2), clockwise: true).cgPath let lightMinPath = UIBezierPath(arcCenter: leftArcCenter, radius: minRadius , startAngle: 0, endAngle: CGFloat(M_PI*2), clockwise: true).cgPath let rightMinPath = UIBezierPath(arcCenter: rightArcCenter, radius: minRadius , startAngle: 0, endAngle: CGFloat(M_PI*2), clockwise: true).cgPath if self.isOn { let thumbAnimation = pathAnimation(from: leftPath, to: rightPath) thumbAnimation.delegate = self thumbLayer.add(thumbAnimation, forKey: "thumb") let onAnimation = pathAnimation(from: lightMinPath, to: fullPath) onLayer.add(onAnimation, forKey: "light") let offAnimation = pathAnimation(from: fullPath, to: rightMinPath) offLayer.add(offAnimation, forKey: "white") onTextLayer.isHidden = false offTextLayer?.isHidden = true } else { let thumbAnimation = pathAnimation(from: rightPath, to: leftPath) thumbAnimation.delegate = self thumbLayer.add(thumbAnimation, forKey: "thumb") let onAnimation = pathAnimation(from: fullPath, to: lightMinPath) onLayer.add(onAnimation, forKey: "light") let offAnimation = pathAnimation(from: rightMinPath, to: fullPath) offLayer.add(offAnimation, forKey: "white") onTextLayer.isHidden = true offTextLayer?.isHidden = false } } } override public func layoutSubviews() { super.layoutSubviews() let height: CGFloat = self.frame.height let width: CGFloat = self.frame.width leftArcCenter = CGPoint(x: height/2, y: height/2) rightArcCenter = CGPoint(x: width-height/2, y: height/2) thumbRadius = frame.height/2-margin onTextLayer.frame = onTextFrame() onTextLayer.string = onText fullPath = UIBezierPath(roundedRect: self.bounds, cornerRadius: frame.height/2).cgPath thumbLayer.path = UIBezierPath(arcCenter: leftArcCenter, radius: thumbRadius, startAngle: 0, endAngle: CGFloat(M_PI*2), clockwise: true).cgPath onLayer.path = UIBezierPath(arcCenter: leftArcCenter, radius: minRadius, startAngle: 0, endAngle: CGFloat(M_PI*2), clockwise: true).cgPath offLayer.path = UIBezierPath(arcCenter: rightArcCenter, radius: minRadius, startAngle: 0, endAngle: CGFloat(M_PI*2), clockwise: true).cgPath if offText != "" { if offTextLayer == nil { offTextLayer = textLayer() offTextLayer!.foregroundColor = UIColor.lightGray.cgColor offTextLayer!.isHidden = isOn offLayer.addSublayer(offTextLayer!) } offTextLayer?.frame = offTextFrame() offTextLayer?.string = offText removeDots() } else { offTextLayer?.removeFromSuperlayer() setDots() } shadowLayer.frame = self.frame shadowLayer.path = fullPath self.superview!.layer.insertSublayer(shadowLayer, below: layer) } // MARK: - init override public init(frame: CGRect) { var rect = frame rect.size.width = min(frame.width, maxLength) super.init(frame: rect) self.frame = rect self.backgroundColor = .white layer.masksToBounds = true layer.cornerRadius = frame.height/2 thumbLayer = CAShapeLayer() thumbLayer.fillColor = UIColor.white.cgColor thumbLayer.shadowOffset = .zero thumbLayer.shadowRadius = 1 thumbLayer.shadowColor = UIColor.lightGray.cgColor thumbLayer.shadowOpacity = 0.9 layer.addSublayer(thumbLayer) onLayer = CAShapeLayer() onLayer.fillColor = onColor.cgColor layer.insertSublayer(onLayer, below: thumbLayer) onTextLayer = textLayer() onTextLayer.isHidden = true layer.insertSublayer(onTextLayer, above: offLayer) offLayer = CAShapeLayer() offLayer.fillColor = UIColor.white.cgColor self.layer.insertSublayer(offLayer, below: thumbLayer) shadowLayer = CAShapeLayer() shadowLayer.fillColor = UIColor.lightGray.cgColor shadowLayer.frame = self.frame shadowLayer.shadowRadius = 1.5 shadowLayer.shadowColor = UIColor.lightGray.cgColor shadowLayer.shadowOffset = .zero shadowLayer.shadowOpacity = 1 // tap gesture let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap)) self.addGestureRecognizer(tapGesture) } private func setDots() { let width = self.frame.width let height = self.frame.height var dotStartX = width/2 + width/2/3 let radius: CGFloat = 2 let dot1 = CAShapeLayer() dot1.fillColor = UIColor.lightGray.cgColor let dot1Path = UIBezierPath(arcCenter: CGPoint(x: dotStartX, y: height/2), radius: radius, startAngle: 0, endAngle: CGFloat(M_PI*2), clockwise: true) dot1.path = dot1Path.cgPath offLayer.addSublayer(dot1) dotStartX += radius*2 + 1 let dot2 = CAShapeLayer() dot2.fillColor = UIColor.lightGray.cgColor let dot2Path = UIBezierPath(arcCenter: CGPoint(x: dotStartX, y: height/2), radius: radius, startAngle: 0, endAngle: CGFloat(M_PI*2), clockwise: true) dot2.path = dot2Path.cgPath offLayer.addSublayer(dot2) dotStartX += radius*2 + 1 let dot3 = CAShapeLayer() dot3.fillColor = UIColor.lightGray.cgColor let dot3Path = UIBezierPath(arcCenter: CGPoint(x: dotStartX, y: height/2), radius: radius, startAngle: 0, endAngle: CGFloat(M_PI*2), clockwise: true) dot3.path = dot3Path.cgPath offLayer.addSublayer(dot3) dots.append(dot1) dots.append(dot2) dots.append(dot3) } private func removeDots() { for dot in dots { dot.removeFromSuperlayer() } dots.removeAll() } // MARK: - animate private func pathAnimation(from: CGPath, to: CGPath) -> CABasicAnimation { let animation = CABasicAnimation(keyPath: "path") animation.duration = rcswitchAnimationDuration animation.fromValue = from animation.toValue = to return animation } public func animationDidStart(_ anim: CAAnimation) { if self.isOn { thumbLayer.path = UIBezierPath(arcCenter: rightArcCenter, radius: thumbRadius, startAngle: 0, endAngle: CGFloat(M_PI*2), clockwise: true).cgPath onLayer.path = fullPath offLayer.path = UIBezierPath(arcCenter: rightArcCenter, radius: minRadius , startAngle: 0, endAngle: CGFloat(M_PI*2), clockwise: true).cgPath } else { thumbLayer.path = UIBezierPath(arcCenter: leftArcCenter, radius: thumbRadius, startAngle: 0, endAngle: CGFloat(M_PI*2), clockwise: true).cgPath onLayer.path = UIBezierPath(arcCenter: leftArcCenter, radius: minRadius , startAngle: 0, endAngle: CGFloat(M_PI*2), clockwise: true).cgPath offLayer.path = fullPath } } public func animationDidStop(_ anim: CAAnimation, finished flag: Bool) { self.isUserInteractionEnabled = true } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } // MARK: - private @objc private func handleTap() { self.isOn = !isOn } // MARK: - text layer private func textLayer() -> CATextLayer { let textlayer = CATextLayer() textlayer.foregroundColor = UIColor.white.cgColor textlayer.fontSize = rcSwitchFontSize textlayer.font = "PingFangSC-Light" as CFTypeRef? textlayer.contentsScale = 2 return textlayer } private func onTextFrame() -> CGRect { let size = textSize(str: onText) return CGRect(origin: CGPoint(x: thumbRadius, y: (self.frame.height-size.height)/2), size: size) } private func offTextFrame() -> CGRect{ let size = textSize(str: offText) let x:CGFloat = self.frame.width - CGFloat(10) - size.width return CGRect(origin: CGPoint(x: x, y: (self.frame.height-size.height)/2), size: size) } private func textSize(str: String) -> CGSize { let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.alignment = .center let size = str.size(attributes: [NSFontAttributeName: UIFont(name: "PingFangSC-Light", size: rcSwitchFontSize)!, NSForegroundColorAttributeName: UIColor.black, NSParagraphStyleAttributeName: paragraphStyle]) return size } }
mit
440392467270c848fb2d77a79591f860
37.093023
215
0.643032
4.579073
false
false
false
false
iewam/GBook
GBook/GBook/MENewCommentViewController.swift
1
9667
// // MENewCommentViewController.swift // GBook // // Created by 马伟 on 2017/6/6. // Copyright © 2017年 马伟. All rights reserved. // import UIKit let topViewHeight : CGFloat = 180.0 let topView_topMargin : CGFloat = 60.0 let reuseIdentifier = "cell" class MENewCommentViewController: MEBaseViewController { lazy var topView = MENewCommentTopView(frame: CGRect(x: 0, y: topView_topMargin, width: SCREEN_WIDTH, height: topViewHeight)) lazy var imgPicker = UIImagePickerController() lazy var tableView = UITableView(frame: CGRect(x: 0, y: topViewHeight + topView_topMargin + 20, width: SCREEN_WIDTH, height: SCREEN_HEIGHT - topView_topMargin - topViewHeight - 20), style: .grouped) var titleArr : [String]? var commentTitle : String?// 书评标题 var score : LDXScore { let score = LDXScore(frame: CGRect(x: 10, y: 10, width: SCREEN_WIDTH - 20, height: 22)) score.normalImg = UIImage(named: "btn_star_evaluation_normal") score.highlightImg = UIImage(named: "btn_star_evaluation_press") score.isSelect = true score.max_star = 5 score.show_star = 5 return score } //评分控件 var showScore = false var segmentDetailText : String? var bookCommentText : String? override func viewDidLoad() { super.viewDidLoad() titleArr = ["标题", "评分", "分类", "书评"] setupUI() } private func setupUI() { self.topView.delegate = self view.addSubview(self.topView) self.tableView.backgroundColor = UIColor.groupTableViewBackground self.tableView.tableFooterView = UIView() self.tableView.delegate = self self.tableView.dataSource = self self.tableView.register(UITableViewCell.classForCoder(), forCellReuseIdentifier: reuseIdentifier) view.addSubview(self.tableView) } @objc func rightButtonClick() { print("publish") } deinit { print("MENewCommentViewController deinit") } } //MARK:------ UITableViewDelegate ------ extension MENewCommentViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return (titleArr?.count)! } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell(style: .value1, reuseIdentifier: reuseIdentifier) cell.selectionStyle = .none cell.textLabel?.text = titleArr?[indexPath.row] cell.textLabel?.font = UIFont(name: My_Font_Name, size: 15) cell.detailTextLabel?.font = UIFont(name: My_Font_Name, size: 13) if indexPath.row != 1 { cell.accessoryType = .disclosureIndicator } guard let cellText = cell.textLabel?.text else {return cell} switch cellText { case "标题": cell.detailTextLabel?.text = commentTitle break case "":// 空字符串 if self.showScore { cell.contentView.addSubview(self.score) cell.accessoryType = .none } break case "分类": cell.detailTextLabel?.text = self.segmentDetailText break case " ":// 空格 cell.accessoryType = .none let commentView = UITextView(frame: CGRect(x: 4, y: 4, width: SCREEN_WIDTH - 8, height: 80)) commentView.text = self.bookCommentText commentView.font = UIFont(name: My_Font_Name, size: 15) commentView.isEditable = false cell.contentView.addSubview(commentView) break default: break } return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if showScore && indexPath.row >= 5 { return 88 } else if !showScore && indexPath.row >= 4 { return 88 } return 44 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let cell = tableView.cellForRow(at: indexPath) guard let cellText = cell?.textLabel?.text else { return } switch cellText { case "标题": setCommentTitle() break case "评分": setScore() break case "分类": setSegment() break case "书评": addBookComment() break default: break } } //MARK: 设置书评标题 private func setCommentTitle() { let setCommenttitleVC = MENewCommentSetTitleViewController() MEGeneralFactory.setupNormalFunctionalButton(setCommenttitleVC) setCommenttitleVC.callback = {(title) in self.commentTitle = title self.tableView.reloadData() } present(setCommenttitleVC, animated: true, completion: nil) } //MARK: 设置评分 private func setScore() { self.tableView.beginUpdates() if self.showScore { self.showScore = false self.titleArr?.remove(at: 2) let insertIndexPaths = [IndexPath(row: 2, section: 0)] self.tableView.deleteRows(at: insertIndexPaths, with: .right) } else { self.showScore = true self.titleArr?.insert("", at: 2) let insertIndexPaths = [IndexPath(row: 2, section: 0)] self.tableView.insertRows(at: insertIndexPaths, with: .left) } self.tableView.endUpdates() } //MARK: 选择分类 private func setSegment() { let segmentVC = MESetSegmentViewController() MEGeneralFactory.setupNormalFunctionalButton(segmentVC) segmentVC.segmentCallback = {(segmentText) in self.segmentDetailText = segmentText self.tableView.reloadData() } present(segmentVC, animated: true, completion: nil) } //MARK: 添加书评 private func addBookComment() { let addBookCommentVC = MEAddBookCommentViewController() MEGeneralFactory.setupNormalFunctionalButton(addBookCommentVC) addBookCommentVC.textView.text = self.bookCommentText addBookCommentVC.bookCommentCallback = {(bookCommet) in self.bookCommentText = bookCommet if self.titleArr?.last == " " { self.titleArr?.removeLast() } if self.bookCommentText != "" { self.titleArr?.append(" ") } self.tableView.reloadData() } present(addBookCommentVC, animated: true, completion: nil) } } //MARK:------ MENewCommentTopViewDelegate ------ extension MENewCommentViewController : MENewCommentTopViewDelegate { func bookCoverBtnDidClick() { print("chose book") self.imgPicker.delegate = self let alert = UIAlertController(title: "选择图片", message: nil, preferredStyle: .actionSheet) alert.addAction(UIAlertAction(title: "拍摄", style: .default, handler: { (_) in self.takePhoto() })) alert.addAction(UIAlertAction(title: "从相册选择", style: .default, handler: { (_) in self.choosePhotoFromPhotoLibrary() })) alert.addAction(UIAlertAction(title: "取消", style: .cancel, handler: { (_) in })) present(alert, animated: true, completion: nil) } private func choosePhotoFromPhotoLibrary() { self.imgPicker.sourceType = .photoLibrary self.present(self.imgPicker, animated: true, completion: nil) } private func takePhoto() { if (UIImagePickerController.isSourceTypeAvailable(.camera)) { print("camera") self.imgPicker.sourceType = .camera self.present(self.imgPicker, animated: true, completion: nil) } else { let tipAlert = UIAlertController(title: "tip", message: "no camera", preferredStyle: .alert) tipAlert.addAction(UIAlertAction(title: "sure", style: .default, handler: { (_) in })) self.present(tipAlert, animated: true, completion: nil) } } } //MARK:------ UIImagePickerControllerDelegate ------ extension MENewCommentViewController : UIImagePickerControllerDelegate, UINavigationControllerDelegate { func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { self.imgPicker.dismiss(animated: true, completion: nil) } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { self.imgPicker.dismiss(animated: true) { let image = info["UIImagePickerControllerOriginalImage"] as! UIImage self.topView.bookCoverBtn.setImage(image, for: .normal) } } }
apache-2.0
c10204666b89a9dc0584b96402b71b51
27.779456
202
0.572433
5.04288
false
false
false
false
Dimentar/SwiftGen
swiftgen-cli/ArgumentsUtils.swift
1
3243
// // SwiftGen // Copyright (c) 2015 Olivier Halligon // MIT Licence // import Commander import PathKit // MARK: Validators func checkPath(type: String, assertion: Path -> Bool) -> (Path throws -> Path) { return { (path: Path) throws -> Path in guard assertion(path) else { throw ArgumentError.InvalidType(value: path.description, type: type, argument: nil) } return path } } let pathExists = checkPath("path") { $0.exists } let fileExists = checkPath("file") { $0.isFile } let dirExists = checkPath("directory") { $0.isDirectory } // MARK: Path as Input Argument extension Path : ArgumentConvertible { public init(parser: ArgumentParser) throws { guard let path = parser.shift() else { throw ArgumentError.MissingValue(argument: nil) } self = Path(path) } } // MARK: Output (Path or Console) Argument enum OutputDestination: ArgumentConvertible { case Console case File(Path) init(parser: ArgumentParser) throws { guard let path = parser.shift() else { throw ArgumentError.MissingValue(argument: nil) } self = .File(Path(path)) } var description: String { switch self { case .Console: return "(stdout)" case .File(let path): return path.description } } func write(content: String, onlyIfChanged: Bool = false) { switch self { case .Console: print(content) case .File(let path): do { if try onlyIfChanged && path.exists && path.read(NSUTF8StringEncoding) == content { return print("Not writing the file as content is unchanged") } try path.write(content) print("File written: \(path)") } catch let e as NSError { print("Error: \(e)") } } } } // MARK: Template Arguments enum TemplateError: ErrorType, CustomStringConvertible { case NamedTemplateNotFound(name: String) case TemplatePathNotFound(path: Path) var description: String { switch self { case .NamedTemplateNotFound(let name): return "Template named \(name) not found. Use `swiftgen template` to list available named templates " + "or use --templatePath to specify a template by its full path." case .TemplatePathNotFound(let path): return "Template not found at path \(path.description)." } } } extension Path { static let applicationSupport = Path( NSSearchPathForDirectoriesInDomains(.ApplicationSupportDirectory, .UserDomainMask, true).first! ) } let appSupportTemplatesPath = Path.applicationSupport + "SwiftGen/templates" let bundledTemplatesPath = Path(NSProcessInfo.processInfo().arguments[0]).parent() + templatesRelativePath func findTemplate(prefix: String, templateShortName: String, templateFullPath: String) throws -> Path { guard templateFullPath.isEmpty else { let fullPath = Path(templateFullPath) guard fullPath.isFile else { throw TemplateError.TemplatePathNotFound(path: fullPath) } return fullPath } var path = appSupportTemplatesPath + "\(prefix)-\(templateShortName).stencil" if !path.isFile { path = bundledTemplatesPath + "\(prefix)-\(templateShortName).stencil" } guard path.isFile else { throw TemplateError.NamedTemplateNotFound(name: templateShortName) } return path }
mit
7afdfb264e7c339a2c774d7b18f4fcc2
27.699115
118
0.693185
4.267105
false
false
false
false
hooman/swift
test/stdlib/ArrayBuffer_CopyContents.swift
3
2127
//===--- ArrayBuffer_CopyContents.swift -----------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2021 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // RUN: %target-run-simple-swift // REQUIRES: executable_test // REQUIRES: swift_stdlib_asserts // REQUIRES: foundation import Foundation import StdlibUnittest let suite = TestSuite("ArrayBuffer_CopyContents") defer { runAllTests() } var trackedCount = 0 var nextBaseSerialNumber = 0 /// A type that will be bridged verbatim to Objective-C class Thing: NSObject { var value: Int var serialNumber: Int func foo() { } required init(_ value: Int) { trackedCount += 1 nextBaseSerialNumber += 1 serialNumber = nextBaseSerialNumber self.value = value } deinit { assert(serialNumber > 0, "double destruction!") trackedCount -= 1 serialNumber = -serialNumber } override func isEqual(_ other: Any?) -> Bool { return (other as? Thing)?.value == self.value } override var hash: Int { value } } suite.test("nativeArray/_copyContents") { let array = [Thing(0), Thing(1), Thing(2), Thing(3)] expectEqualSequence(array._copyToNewArray(), array) } suite.test("nativeArraySlice/_copyContents") { let array = (0 ..< 100).map { Thing($0) } expectEqualSequence( array[20 ..< 30]._copyToNewArray(), (20 ..< 30).map { Thing($0) }) } suite.test("bridgedArray/_copyContents") { let array = NSArray(array: (0 ..< 5).map { Thing($0) }) as! [Thing] expectEqualSequence( array._copyToNewArray(), (0 ..< 5).map { Thing($0) }) } suite.test("bridgedArraySlice/_copyContents") { let array = NSArray(array: (0 ..< 100).map { Thing($0) }) as! [Thing] expectEqualSequence( array[20 ..< 30]._copyToNewArray(), (20 ..< 30).map { Thing($0) }) }
apache-2.0
fff90500872b4777e5483c858adf6c36
25.5875
80
0.632346
3.968284
false
true
false
false
chrisbudro/GrowlerHour
growlers/MapViewController.swift
1
1222
// // MapViewController.swift // GrowlerHour // // Created by Chris Budro on 11/1/15. // Copyright © 2015 chrisbudro. All rights reserved. // import UIKit class MapViewController: UIViewController { //MARK: Constants let mapPadding: CGFloat = 10 //MARK: Properties private var mapView: GMSMapView! var markers = [GMSMarker]() //MARK: Life Cycle Methods override func loadView() { super.loadView() mapView = GMSMapView(frame: view.frame) view.addSubview(mapView) } override func viewDidLoad() { super.viewDidLoad() mapView.delegate = self addMarkersToMap() centerCameraOnMarkers() } //MARK: Helper Methods func addMarkersToMap() { for marker in markers { marker.map = mapView } } func centerCameraOnMarkers() { let path = GMSMutablePath() for marker in markers { path.addCoordinate(marker.position) } let bounds = GMSCoordinateBounds(path: path) let camera = mapView.cameraForBounds(bounds, insets: UIEdgeInsets(top: mapPadding, left: mapPadding, bottom: mapPadding, right: mapPadding)) mapView.animateToCameraPosition(camera) } } extension MapViewController: GMSMapViewDelegate { }
mit
4df213e0ebeabc4cdd46aaa90231a4f3
20.421053
144
0.684685
4.210345
false
false
false
false
HeartOfCarefreeHeavens/TestKitchen_pww
TestKitchen/TestKitchen/classes/cookbook/recommend/view/CBSubjectCell.swift
1
2489
// // CBSubjectCell.swift // TestKitchen // // Created by qianfeng on 16/8/23. // Copyright © 2016年 qianfeng. All rights reserved. // import UIKit class CBSubjectCell: UITableViewCell { @IBOutlet weak var subjectImageView: UIImageView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var descLabel: UILabel! var dataArray:Array<CBRecommendWidgetdataModel>?{ didSet{ showData() } } func showData(){ //显示图片 if dataArray?.count>0{ let imageModel = dataArray![0] if imageModel.type == "image" { let url = NSURL(string: imageModel.content!) subjectImageView.kf_setImageWithURL(url, placeholderImage: UIImage(named: "sdefaultImage"), optionsInfo: nil, progressBlock: nil, completionHandler: nil) } } //描述标题 if dataArray?.count>1{ let titleModel = dataArray![1] if titleModel.type == "text" { titleLabel.text = titleModel.content } } //描述文字 if dataArray?.count>2{ let descModel = dataArray![2] if descModel.type == "text" { titleLabel.text = descModel.content } } } class func createSubjectCellFor(tableView:UITableView,atIndexPath indexPath:NSIndexPath,withListModel listModel:CBRecommendWidgetListModel)->CBSubjectCell{ let cellId = "subjectCellId" var cell = tableView.dequeueReusableCellWithIdentifier(cellId) as? CBSubjectCell if cell == nil { cell = NSBundle.mainBundle().loadNibNamed("CBSubjectCell", owner: nil, options: nil).last as? CBSubjectCell } if listModel.widget_data?.count>indexPath.row*3+2{ //if 判断防止数组越界,其他地方同样 let array = NSArray(array: listModel.widget_data!) cell?.dataArray = array.subarrayWithRange(NSMakeRange(indexPath.row*3, 3)) as? Array<CBRecommendWidgetdataModel> } return cell! } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
mit
0566bd4200d786c289e603b0cb2d8e1c
26.977011
169
0.586689
4.88755
false
false
false
false
AlexRamey/mbird-iOS
Pods/CVCalendar/CVCalendar/CVCalendarView.swift
1
13384
// // CVCalendarView.swift // CVCalendar // // Created by E. Mozharovsky on 12/26/14. // Copyright (c) 2014 GameApp. All rights reserved. // import UIKit public typealias WeekView = CVCalendarWeekView public typealias CalendarView = CVCalendarView public typealias MonthView = CVCalendarMonthView public typealias Manager = CVCalendarManager public typealias DayView = CVCalendarDayView public typealias ContentController = CVCalendarContentViewController public typealias Appearance = CVCalendarViewAppearance public typealias Coordinator = CVCalendarDayViewControlCoordinator public typealias CalendarMode = CVCalendarViewPresentationMode public typealias Weekday = CVCalendarWeekday public typealias Animator = CVCalendarViewAnimator public typealias Delegate = CVCalendarViewDelegate public typealias AppearanceDelegate = CVCalendarViewAppearanceDelegate public typealias AnimatorDelegate = CVCalendarViewAnimatorDelegate public typealias ContentViewController = CVCalendarContentViewController public typealias MonthContentViewController = CVCalendarMonthContentViewController public typealias WeekContentViewController = CVCalendarWeekContentViewController public typealias MenuViewDelegate = CVCalendarMenuViewDelegate public typealias TouchController = CVCalendarTouchController public typealias SelectionType = CVSelectionType public final class CVCalendarView: UIView { // MARK: - Public properties public var manager: Manager! public var appearance: Appearance! public var touchController: TouchController! public var coordinator: Coordinator! public var animator: Animator! public var contentController: ContentViewController! public var calendarMode: CalendarMode! public var (weekViewSize, dayViewSize): (CGSize?, CGSize?) fileprivate var validated = false fileprivate var currentOrientation: UIDeviceOrientation fileprivate var maxHeight: CGFloat = 0 public var firstWeekday: Weekday { if let delegate = delegate { return delegate.firstWeekday() } else { return .sunday } } public var shouldShowWeekdaysOut: Bool! { if let delegate = delegate, let shouldShow = delegate.shouldShowWeekdaysOut?() { return shouldShow } else { return false } } public var presentedDate: CVDate! { didSet { let calendar = self.delegate?.calendar?() ?? Calendar.current if oldValue != nil && presentedDate.convertedDate(calendar: calendar) != oldValue.convertedDate(calendar: calendar) { delegate?.presentedDateUpdated?(presentedDate) } } } public var shouldAnimateResizing: Bool { if let delegate = delegate, let should = delegate.shouldAnimateResizing?() { return should } return true } public var shouldAutoSelectDayOnMonthChange: Bool { if let delegate = delegate, let should = delegate.shouldAutoSelectDayOnMonthChange?() { return should } return true } public var shouldAutoSelectDayOnWeekChange: Bool { if let delegate = delegate, let should = delegate.shouldAutoSelectDayOnWeekChange?() { return should } return true } public var shouldScrollOnOutDayViewSelection: Bool { if let delegate = delegate, let should = delegate.shouldScrollOnOutDayViewSelection?() { return should } return true } public var shouldSelectRange: Bool { get { if let delegate = delegate, let should = delegate.shouldSelectRange?() { return should } return false } } public var disableScrollingBeforeDate: Date? { get { if let delegate = delegate, let date = delegate.disableScrollingBeforeDate?() { return date } return nil } } public var disableScrollingBeyondDate: Date? { get { if let delegate = delegate, let date = delegate.disableScrollingBeyondDate?() { return date } return nil } } public var maxSelectableRange: Int { get { if let delegate = delegate, let range = delegate.maxSelectableRange?() { return range } return 0 } } public var earliestSelectableDate: Date? { get { if let delegate = delegate, let date = delegate.earliestSelectableDate?() { return date } return nil } } public var latestSelectableDate: Date? { get { if let delegate = delegate, let date = delegate.latestSelectableDate?() { return date } return nil } } // MARK: - Calendar View Delegate @IBOutlet public weak var calendarDelegate: AnyObject? { set { if let calendarDelegate = newValue as? Delegate { delegate = calendarDelegate } } get { return delegate } } public weak var delegate: CVCalendarViewDelegate? { didSet { if manager == nil { manager = Manager(calendarView: self) } if appearance == nil { appearance = Appearance() } if touchController == nil { touchController = TouchController(calendarView: self) } if coordinator == nil { coordinator = Coordinator(calendarView: self) } if animator == nil { animator = Animator(calendarView: self) } if calendarMode == nil { loadCalendarMode() } } } // MARK: - Calendar Appearance Delegate @IBOutlet public weak var calendarAppearanceDelegate: AnyObject? { set { if let calendarAppearanceDelegate = newValue as? AppearanceDelegate { if appearance == nil { appearance = Appearance() } appearance.delegate = calendarAppearanceDelegate } } get { return appearance } } // MARK: - Calendar Animator Delegate @IBOutlet public weak var animatorDelegate: AnyObject? { set { if let animatorDelegate = newValue as? AnimatorDelegate { animator.delegate = animatorDelegate } } get { return animator } } // MARK: - Initialization public init() { currentOrientation = UIDevice.current.orientation super.init(frame: CGRect.zero) isHidden = true } public override init(frame: CGRect) { currentOrientation = UIDevice.current.orientation super.init(frame: frame) isHidden = true } // IB Initialization public required init?(coder aDecoder: NSCoder) { currentOrientation = UIDevice.current.orientation super.init(coder: aDecoder) isHidden = true } } // MARK: - Frames update extension CVCalendarView { public func commitCalendarViewUpdate() { if currentOrientation != UIDevice.current.orientation { validated = false currentOrientation = UIDevice.current.orientation } setNeedsLayout() layoutIfNeeded() if let _ = delegate, let contentController = contentController { let contentViewSize = contentController.bounds.size let selfSize = bounds.size let screenSize = UIScreen.main.bounds.size let allowed = selfSize.width <= screenSize.width && selfSize.height <= screenSize.height if !validated && allowed { let width = selfSize.width let height: CGFloat let countOfWeeks = CGFloat(6) let vSpace = appearance.spaceBetweenWeekViews! let hSpace = appearance.spaceBetweenDayViews! if selfSize.height > maxHeight { maxHeight = selfSize.height } if let mode = calendarMode { switch mode { case .weekView: height = contentViewSize.height contentController.updateHeight(height, animated: false) case .monthView : height = (maxHeight / countOfWeeks) - (vSpace * countOfWeeks) } // If no height constraint found we set it manually. var found = false for constraint in constraints { if constraint.firstAttribute == .height { found = true } } if !found { addConstraint(NSLayoutConstraint(item: self, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: frame.height)) } weekViewSize = CGSize(width: width, height: height) dayViewSize = CGSize(width: (width / 7.0) - hSpace, height: height) validated = true contentController .updateFrames(selfSize != contentViewSize ? bounds : CGRect.zero) } } } } } // MARK: - Coordinator callback extension CVCalendarView { public func didSelectDayView(_ dayView: CVCalendarDayView) { presentedDate = dayView.date delegate?.didSelectDayView?(dayView, animationDidFinish: false) if let controller = contentController { controller.performedDayViewSelection(dayView) // TODO: Update to range selection } } } // MARK: - Convenience API extension CVCalendarView { public func changeDaysOutShowingState(shouldShow: Bool) { contentController.updateDayViews(shouldShow: shouldShow) } public func toggleViewWithDate(_ date: Foundation.Date) { contentController.togglePresentedDate(date) } public func toggleCurrentDayView() { contentController.togglePresentedDate(Foundation.Date()) } public func loadNextView() { contentController.presentNextView(nil) } public func loadPreviousView() { contentController.presentPreviousView(nil) } public func changeMode(_ mode: CalendarMode, completion: @escaping () -> () = {}) { let calendar = self.delegate?.calendar?() ?? Calendar.current let shouldSelectRange = self.delegate?.shouldSelectRange?() ?? false guard calendarMode != mode else { return } var selectedDate:Date? if !shouldSelectRange { selectedDate = coordinator.selectedDayView?.date.convertedDate(calendar: calendar) } else { selectedDate = coordinator.selectedStartDayView?.date.convertedDate(calendar: calendar) } calendarMode = mode let newController: ContentController switch mode { case .weekView: contentController.updateHeight(dayViewSize!.height, animated: true) newController = WeekContentViewController(calendarView: self, frame: bounds, presentedDate: selectedDate ?? Date()) case .monthView: contentController.updateHeight( contentController.presentedMonthView.potentialSize.height, animated: true) newController = MonthContentViewController(calendarView: self, frame: bounds, presentedDate: selectedDate ?? Date()) } newController.updateFrames(bounds) newController.scrollView.alpha = 0 addSubview(newController.scrollView) UIView.animate(withDuration: 0.5, delay: 0, options: UIViewAnimationOptions(), animations: { [weak self] in self?.contentController.scrollView.alpha = 0 newController.scrollView.alpha = 1 }) { [weak self] _ in self?.contentController.scrollView.removeAllSubviews() self?.contentController.scrollView.removeFromSuperview() self?.contentController = newController completion() } } } // MARK: - Mode load private extension CVCalendarView { func loadCalendarMode() { if let delegate = delegate { calendarMode = delegate.presentationMode() switch delegate.presentationMode() { case .monthView: contentController = MonthContentViewController(calendarView: self, frame: bounds) case .weekView: contentController = WeekContentViewController(calendarView: self, frame: bounds) } addSubview(contentController.scrollView) } } }
mit
d4946a4e80a29995e309364d48ee3a6f
30.866667
129
0.594815
5.948444
false
false
false
false
liamdkane/GetGreen-HipHopHacktivist
GetGreen/GetGreen/MapViewController.swift
1
8231
// // MapViewController.swift // GetGreen // // Created by C4Q on 6/24/17. // Copyright © 2017 Liam Kane. All rights reserved. // import UIKit import MapKit import CoreLocation class MapViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate, UISearchBarDelegate { @IBOutlet weak var greenMapView: MKMapView! @IBOutlet weak var greenSearchBar: UISearchBar! let notificationCenter = NotificationCenter.default var communityGardens: [CommunityGardens]? { didSet { loadAnnotations() } } let locationManager: CLLocationManager = { let locMan: CLLocationManager = CLLocationManager() locMan.desiredAccuracy = 100.0 locMan.distanceFilter = 500.0 return locMan }() override func viewDidLoad() { super.viewDidLoad() locationManager.delegate = self greenMapView.delegate = self greenSearchBar.delegate = self } @IBAction func refreshMap(_ sender: UIButton) { loadAnnotations() } override func viewDidAppear(_ animated: Bool) { if let appDelegate = UIApplication.shared.delegate as? AppDelegate, let gardens = appDelegate.communityGardens { self.communityGardens = gardens } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) NotificationCenter.default.addObserver(self, selector: #selector(parseNotification(_:)), name: kGardensNotificationName, object: nil) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) NotificationCenter.default.removeObserver(self) } func parseNotification(_ notification: Notification) { if let gardens = notification.object as? [CommunityGardens] { self.communityGardens = gardens } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - CLLocationManager Delegate func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { switch status { case .authorizedAlways, .authorizedWhenInUse: print("All good") manager.startUpdatingLocation() // manager.startMonitoringSignificantLocationChanges() case .denied, .restricted: print("NOPE") case .notDetermined: print("IDK") locationManager.requestWhenInUseAuthorization() } } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { guard let validLocation: CLLocation = locations.last else { return } greenMapView.setRegion(MKCoordinateRegionMakeWithDistance(validLocation.coordinate, 500.0, 500.0), animated: true) let circleOverlay: MKCircle = MKCircle(center: validLocation.coordinate, radius: 50.0) greenMapView.add(circleOverlay) } func loadAnnotations() { if let validGardens = self.communityGardens { var annotations = [MKAnnotation]() for garden in validGardens { print(garden.address) let geocoder: CLGeocoder = CLGeocoder() geocoder.geocodeAddressString(garden.address, completionHandler: { (placemarks, error) in print(error.debugDescription) if let validPlacemarks = placemarks, let location = validPlacemarks.first?.location{ let annotation = GetGreenAnnotation(location: location, garden: garden) annotations.append(annotation) DispatchQueue.main.async { self.greenMapView.addAnnotation(annotation) } } }) } validGardens.forEach({ (garden) in }) // print(annotations.count) // greenMapView.addAnnotations(annotations) } } func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { if annotation is MKUserLocation { return nil } else { let annotationIdentifier = "AnnotationIdentifier" let mapAnnotationView = mapView.dequeueReusableAnnotationView(withIdentifier: annotationIdentifier) as? AnnotationView ?? AnnotationView(annotation: annotation, reuseIdentifier: annotationIdentifier) mapAnnotationView.canShowCallout = false mapAnnotationView.annotation = annotation let btn = UIButton(type: .detailDisclosure) mapAnnotationView.rightCalloutAccessoryView = btn mapAnnotationView.image = UIImage(named: "getgreenlogo") return mapAnnotationView } } func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) { let annotation = view.annotation as! GetGreenAnnotation let garden = annotation.garden let placeName = garden.name let placeInfo = garden.address + "\n" + garden.neighborhood let ac = UIAlertController(title: placeName, message: placeInfo, preferredStyle: .alert) ac.addAction(UIAlertAction(title: "OK", style: .default)) present(ac, animated: true) } func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) { let annotation = view.annotation as! GetGreenAnnotation let garden = annotation.garden let placeName = garden.name let placeInfo = garden.address + "\n" + garden.neighborhood let ac = UIAlertController(title: placeName, message: placeInfo, preferredStyle: .alert) ac.addAction(UIAlertAction(title: "OK", style: .default)) present(ac, animated: true) } @IBAction func cancelButtonPressed(_ sender: UIButton) { self.dismiss(animated: true, completion: nil) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } class GetGreenAnnotation: NSObject, MKAnnotation{ var title: String? var coordinate: CLLocationCoordinate2D let image = #imageLiteral(resourceName: "getgreenlogo") let garden: CommunityGardens init(location: CLLocation, garden: CommunityGardens) { self.coordinate = location.coordinate self.garden = garden } } class AnnotationView: MKAnnotationView { // override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { // let hitView = super.hitTest(point, with: event) // if (hitView != nil) // { // //self.superview?.bringSubview(toFront: self) // } // // return hitView // } // override func point(inside point: CGPoint, with event: UIEvent?) -> Bool { // let rect = self.bounds; // var isInside: Bool = rect.contains(point); // // if(!isInside) // { // for view in self.subviews // { // isInside = view.frame.contains(point); // if isInside // { // break; // } // } // } // return isInside; // } }
mit
af567d4c364e3c6a1db70cc5537424f0
34.782609
211
0.588943
5.505017
false
false
false
false
leuski/Coiffeur
Coiffeur/src/util/String+al.swift
1
6988
// // String+al.swift // Coiffeur // // Created by Anton Leuski on 4/5/15. // Copyright (c) 2015 Anton Leuski. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // import Foundation /** Adds string processing utilities */ extension String { var commandLineComponents: [String] { let nullChar: Character = "\0" var result = [String]() var isArg = false var isBackslash = false var curQuote: Character = nullChar var currentToken: String = "" for character in self { let isSpace = character == " " || character == "\t" || character == "\n" || character == "\r" if !isArg { if isSpace { continue } isArg = true currentToken = "" } if isBackslash { isBackslash = false currentToken.append(character) } else if character == "\\" { isBackslash = true } else if character == curQuote { curQuote = nullChar } else if (character == "'") || (character == "\"") || (character == "`") { curQuote = character } else if curQuote != nullChar { currentToken.append(character) } else if isSpace { isArg = false result.append(currentToken) } else { currentToken.append(character) } } if isArg { result.append(currentToken) } return result } var words: [String] { var result = [String]() self.enumerateLinguisticTags( in: self.startIndex..<self.endIndex, scheme: NSLinguisticTagScheme.tokenType.rawValue, options: NSLinguisticTagger.Options.omitWhitespace, orthography: nil) { (_, tokenRange: Range<String.Index>, _, _) in result.append(String(self[tokenRange])) } return result } var stringByCapitalizingFirstWord: String { if self.isEmpty { return self } let nextIndex = self.index(after: self.startIndex) return self[self.startIndex..<nextIndex].capitalized + self[nextIndex...] } private func _stringByQuoting(_ quote: Character) -> String { let backSpace: Character = "\\" var result = "" result.append(quote) for character in self { switch character { case quote, "\\", "\"", "'", "`", " ", "\t", "\r", "\n": result.append(backSpace) result.append(character) default: result.append(character) } } result.append(quote) return result } func stringByQuoting(_ quote: Character = "\"") -> String { let set = NSMutableCharacterSet(charactersIn: String(quote)) set.addCharacters(in: "\\\"'` \t\r\n") if self.isEmpty { return _stringByQuoting(quote) } else if nil != self.rangeOfCharacter(from: set as CharacterSet) { return _stringByQuoting(quote) } else { return self } } func stringByAppendingString(_ string: String, separatedBy delimiter: String) -> String { var result = self if !result.isEmpty { result += delimiter } return result + string } func trim() -> String { return self.trimmingCharacters( in: CharacterSet.whitespacesAndNewlines) } func stringByTrimmingPrefix(_ prefix: String) -> String { var result = self.trim() if prefix.isEmpty { return result } let length = prefix.distance(from: prefix.startIndex, to: prefix.endIndex) while result.hasPrefix(prefix) { let nextIndex = result.index(result.startIndex, offsetBy: length) result = String(result[nextIndex...]).trim() } return result } func stringByTrimmingSuffix(_ suffix: String) -> String { var result = self.trim() if suffix.isEmpty { return result } let length = suffix.distance(from: suffix.startIndex, to: suffix.endIndex) while result.hasSuffix(suffix) { let resultLength = result.distance(from: result.startIndex, to: result.endIndex) let nextIndex = result.index(result.startIndex, offsetBy: resultLength-length) result = String(result[result.startIndex..<nextIndex]).trim() } return result } func lineRangeForCharacterRange(_ range: Range<String.Index>) -> CountableClosedRange<Int> { var numberOfLines = 0 var index = self.startIndex let lastCharacter = self.index(before: range.upperBound) var start: Int = 0 var end: Int = 0 while index < self.endIndex { let nextIndex = self.lineRange(for: index..<index).upperBound if index <= range.lowerBound && range.lowerBound < nextIndex { start = numberOfLines end = numberOfLines if lastCharacter < range.lowerBound { break } } if index <= lastCharacter && lastCharacter < nextIndex { end = numberOfLines break } index = nextIndex numberOfLines += 1 } return start...end } func lineCountForCharacterRange(_ range: Range<String.Index>) -> Int { if range.upperBound == range.lowerBound { return 0 } let lastCharacter = self.index(before: range.upperBound) var numberOfLines: Int = 0 var index = range.lowerBound while index < self.endIndex { let nextIndex = self.lineRange(for: index..<index).upperBound if index <= lastCharacter && lastCharacter < nextIndex { return numberOfLines } index = nextIndex numberOfLines += 1 } return 0 } func lineCount() -> Int { return lineCountForCharacterRange(self.startIndex..<self.endIndex) } var nsRange: NSRange { return NSRange(location: 0, length: (self as NSString).length) } func substringWithRange(_ range: NSRange) -> String { let start = self.index(self.startIndex, offsetBy: range.location) let end = self.index(start, offsetBy: range.length) return String(self[start..<end]) } func stringByReplacingCharactersInRange(_ range: NSRange, withString replacement: String) -> String { let start = self.index(self.startIndex, offsetBy: range.location) let end = self.index(start, offsetBy: range.length) return self.replacingCharacters(in: start..<end, with: replacement) } init?(data: Data, encoding: String.Encoding) { var buffer = [UInt8](repeating: 0, count: data.count) (data as NSData).getBytes(&buffer, length: data.count) self.init(bytes: buffer, encoding: encoding) } }
apache-2.0
55180789ee07f76640d452ade02e3a13
25.270677
92
0.628649
4.345771
false
false
false
false
zeroc-ice/ice-demos
swift/Ice/latency/Sources/Client/main.swift
1
1263
// // Copyright (c) ZeroC, Inc. All rights reserved. // import Dispatch import Ice import PromiseKit // Automatically flush stdout setbuf(__stdoutp, nil) func run() -> Int32 { do { var args = CommandLine.arguments let communicator = try Ice.initialize(args: &args, configFile: "config.client") defer { communicator.destroy() } guard args.count == 1 else { print("too many arguments") return 1 } guard let ping = try checkedCast(prx: communicator.propertyToProxy("Ping.Proxy")!, type: PingPrx.self) else { print("invalid proxy") return 1 } let start = DispatchTime.now() let repetitions = 100_000 print("pinging server \(repetitions) times (this may take a while)") for _ in 0 ..< repetitions { try ping.ice_ping() } let total = Double(DispatchTime.now().uptimeNanoseconds - start.uptimeNanoseconds) / 1_000_000 let perPing = total / Double(repetitions) print("time for \(repetitions) pings: \(total)ms") print("time per ping: \(perPing)ms") return 0 } catch { print("Error: \(error)") return 1 } } exit(run())
gpl-2.0
289ceeb942ba899c7bca6ca8cd0f5a3d
24.77551
117
0.576405
4.31058
false
false
false
false
OpenSourceContributions/SwiftOCR
framework/SwiftOCR/GPUImage2-master/framework/Source/Operations/GaussianBlur.swift
4
11025
#if os(Linux) import Glibc let M_PI = 3.14159265359 // TODO: remove this once Foundation pulls this in on Linux #endif import Foundation public class GaussianBlur: TwoStageOperation { public var blurRadiusInPixels:Float { didSet { let (sigma, downsamplingFactor) = sigmaAndDownsamplingForBlurRadius(blurRadiusInPixels, limit:8.0, override:overrideDownsamplingOptimization) sharedImageProcessingContext.runOperationAsynchronously { self.downsamplingFactor = downsamplingFactor let pixelRadius = pixelRadiusForBlurSigma(Double(sigma)) self.shader = crashOnShaderCompileFailure("GaussianBlur"){try sharedImageProcessingContext.programForVertexShader(vertexShaderForOptimizedGaussianBlurOfRadius(pixelRadius, sigma:Double(sigma)), fragmentShader:fragmentShaderForOptimizedGaussianBlurOfRadius(pixelRadius, sigma:Double(sigma)))} } } } public init() { blurRadiusInPixels = 2.0 let pixelRadius = pixelRadiusForBlurSigma(round(Double(blurRadiusInPixels))) let initialShader = crashOnShaderCompileFailure("GaussianBlur"){try sharedImageProcessingContext.programForVertexShader(vertexShaderForOptimizedGaussianBlurOfRadius(pixelRadius, sigma:2.0), fragmentShader:fragmentShaderForOptimizedGaussianBlurOfRadius(pixelRadius, sigma:2.0))} super.init(shader:initialShader, numberOfInputs:1) } } // MARK: - // MARK: Blur sizing calculations func sigmaAndDownsamplingForBlurRadius(_ radius:Float, limit:Float, override:Bool = false) -> (sigma:Float, downsamplingFactor:Float?) { // For now, only do integral sigmas let startingRadius = Float(round(Double(radius))) guard ((startingRadius > limit) && (!override)) else { return (sigma:startingRadius, downsamplingFactor:nil) } return (sigma:limit, downsamplingFactor:startingRadius / limit) } // inputRadius for Core Image's CIGaussianBlur is really sigma in the Gaussian equation, so I'm using that for my blur radius, to be consistent func pixelRadiusForBlurSigma(_ sigma:Double) -> UInt { // 7.0 is the limit for blur size for hardcoded varying offsets let minimumWeightToFindEdgeOfSamplingArea = 1.0 / 256.0 var calculatedSampleRadius:UInt = 0 if (sigma >= 1.0) { // Avoid a divide-by-zero error here // Calculate the number of pixels to sample from by setting a bottom limit for the contribution of the outermost pixel calculatedSampleRadius = UInt(floor(sqrt(-2.0 * pow(sigma, 2.0) * log(minimumWeightToFindEdgeOfSamplingArea * sqrt(2.0 * .pi * pow(sigma, 2.0))) ))) calculatedSampleRadius += calculatedSampleRadius % 2 // There's nothing to gain from handling odd radius sizes, due to the optimizations I use } return calculatedSampleRadius } // MARK: - // MARK: Standard Gaussian blur shaders func standardGaussianWeightsForRadius(_ blurRadius:UInt, sigma:Double) -> [Double] { var gaussianWeights = [Double]() var sumOfWeights = 0.0 for gaussianWeightIndex in 0...blurRadius { let weight = (1.0 / sqrt(2.0 * .pi * pow(sigma, 2.0))) * exp(-pow(Double(gaussianWeightIndex), 2.0) / (2.0 * pow(sigma, 2.0))) gaussianWeights.append(weight) if (gaussianWeightIndex == 0) { sumOfWeights += weight } else { sumOfWeights += (weight * 2.0) } } return gaussianWeights.map{$0 / sumOfWeights} } func vertexShaderForStandardGaussianBlurOfRadius(_ radius:UInt, sigma:Double) -> String { guard (radius > 0) else { return OneInputVertexShader } let numberOfBlurCoordinates = radius * 2 + 1 var shaderString = "attribute vec4 position;\n attribute vec4 inputTextureCoordinate;\n \n uniform float texelWidth;\n uniform float texelHeight;\n \n varying vec2 blurCoordinates[\(numberOfBlurCoordinates)];\n \n void main()\n {\n gl_Position = position;\n \n vec2 singleStepOffset = vec2(texelWidth, texelHeight);\n" for currentBlurCoordinateIndex in 0..<numberOfBlurCoordinates { let offsetFromCenter = Int(currentBlurCoordinateIndex) - Int(radius) if (offsetFromCenter < 0) { shaderString += "blurCoordinates[\(currentBlurCoordinateIndex)] = inputTextureCoordinate.xy - singleStepOffset * \(Float(-offsetFromCenter));\n" } else if (offsetFromCenter > 0) { shaderString += "blurCoordinates[\(currentBlurCoordinateIndex)] = inputTextureCoordinate.xy + singleStepOffset * \(Float(offsetFromCenter));\n" } else { shaderString += "blurCoordinates[\(currentBlurCoordinateIndex)] = inputTextureCoordinate.xy;\n" } } shaderString += "}\n" return shaderString } func fragmentShaderForStandardGaussianBlurOfRadius(_ radius:UInt, sigma:Double) -> String { guard (radius > 0) else { return PassthroughFragmentShader } let gaussianWeights = standardGaussianWeightsForRadius(radius, sigma:sigma) let numberOfBlurCoordinates = radius * 2 + 1 #if GLES var shaderString = "uniform sampler2D inputImageTexture;\n \n varying highp vec2 blurCoordinates[\(numberOfBlurCoordinates)];\n \n void main()\n {\n lowp vec4 sum = vec4(0.0);\n" #else var shaderString = "uniform sampler2D inputImageTexture;\n \n varying vec2 blurCoordinates[\(numberOfBlurCoordinates)];\n \n void main()\n {\n vec4 sum = vec4(0.0);\n" #endif for currentBlurCoordinateIndex in 0..<numberOfBlurCoordinates { let offsetFromCenter = Int(currentBlurCoordinateIndex) - Int(radius) if (offsetFromCenter < 0) { shaderString += "sum += texture2D(inputImageTexture, blurCoordinates[\(currentBlurCoordinateIndex)]) * \(gaussianWeights[-offsetFromCenter]);\n" } else { shaderString += "sum += texture2D(inputImageTexture, blurCoordinates[\(currentBlurCoordinateIndex)]) * \(gaussianWeights[offsetFromCenter]);\n" } } shaderString += "gl_FragColor = sum;\n }\n" return shaderString } // MARK: - // MARK: Optimized Gaussian blur shaders func optimizedGaussianOffsetsForRadius(_ blurRadius:UInt, sigma:Double) -> [Double] { let standardWeights = standardGaussianWeightsForRadius(blurRadius, sigma:sigma) let numberOfOptimizedOffsets = min(blurRadius / 2 + (blurRadius % 2), 7) var optimizedOffsets = [Double]() for currentOptimizedOffset in 0..<numberOfOptimizedOffsets { let firstWeight = Double(standardWeights[Int(currentOptimizedOffset * 2 + 1)]) let secondWeight = Double(standardWeights[Int(currentOptimizedOffset * 2 + 2)]) let optimizedWeight = firstWeight + secondWeight optimizedOffsets.append((firstWeight * (Double(currentOptimizedOffset) * 2.0 + 1.0) + secondWeight * (Double(currentOptimizedOffset) * 2.0 + 2.0)) / optimizedWeight) } return optimizedOffsets } func vertexShaderForOptimizedGaussianBlurOfRadius(_ radius:UInt, sigma:Double) -> String { guard (radius > 0) else { return OneInputVertexShader } let optimizedOffsets = optimizedGaussianOffsetsForRadius(radius, sigma:sigma) let numberOfOptimizedOffsets = optimizedOffsets.count // Header var shaderString = "attribute vec4 position;\n attribute vec4 inputTextureCoordinate;\n \n uniform float texelWidth;\n uniform float texelHeight;\n \n varying vec2 blurCoordinates[\((1 + (numberOfOptimizedOffsets * 2)))];\n \n void main()\n {\n gl_Position = position;\n \n vec2 singleStepOffset = vec2(texelWidth, texelHeight);\n" shaderString += "blurCoordinates[0] = inputTextureCoordinate.xy;\n" for currentOptimizedOffset in 0..<numberOfOptimizedOffsets { shaderString += "blurCoordinates[\(((currentOptimizedOffset * 2) + 1))] = inputTextureCoordinate.xy + singleStepOffset * \(optimizedOffsets[currentOptimizedOffset]);\n" shaderString += "blurCoordinates[\(((currentOptimizedOffset * 2) + 2))] = inputTextureCoordinate.xy - singleStepOffset * \(optimizedOffsets[currentOptimizedOffset]);\n" } shaderString += "}\n" return shaderString } func fragmentShaderForOptimizedGaussianBlurOfRadius(_ radius:UInt, sigma:Double) -> String { guard (radius > 0) else { return PassthroughFragmentShader } let standardWeights = standardGaussianWeightsForRadius(radius, sigma:sigma) let numberOfOptimizedOffsets = min(radius / 2 + (radius % 2), 7) let trueNumberOfOptimizedOffsets = radius / 2 + (radius % 2) #if GLES var shaderString = "uniform sampler2D inputImageTexture;\n uniform highp float texelWidth;\n uniform highp float texelHeight;\n \n varying highp vec2 blurCoordinates[\(1 + (numberOfOptimizedOffsets * 2))];\n \n void main()\n {\n lowp vec4 sum = vec4(0.0);\n" #else var shaderString = "uniform sampler2D inputImageTexture;\n uniform float texelWidth;\n uniform float texelHeight;\n \n varying vec2 blurCoordinates[\(1 + (numberOfOptimizedOffsets * 2))];\n \n void main()\n {\n vec4 sum = vec4(0.0);\n" #endif // Inner texture loop shaderString += "sum += texture2D(inputImageTexture, blurCoordinates[0]) * \(standardWeights[0]);\n" for currentBlurCoordinateIndex in 0..<numberOfOptimizedOffsets { let firstWeight = standardWeights[Int(currentBlurCoordinateIndex * 2 + 1)] let secondWeight = standardWeights[Int(currentBlurCoordinateIndex * 2 + 2)] let optimizedWeight = firstWeight + secondWeight shaderString += "sum += texture2D(inputImageTexture, blurCoordinates[\((currentBlurCoordinateIndex * 2) + 1)]) * \(optimizedWeight);\n" shaderString += "sum += texture2D(inputImageTexture, blurCoordinates[\((currentBlurCoordinateIndex * 2) + 2)]) * \(optimizedWeight);\n" } // If the number of required samples exceeds the amount we can pass in via varyings, we have to do dependent texture reads in the fragment shader if (trueNumberOfOptimizedOffsets > numberOfOptimizedOffsets) { #if GLES shaderString += "highp vec2 singleStepOffset = vec2(texelWidth, texelHeight);\n" #else shaderString += "vec2 singleStepOffset = vec2(texelWidth, texelHeight);\n" #endif } for currentOverlowTextureRead in numberOfOptimizedOffsets..<trueNumberOfOptimizedOffsets { let firstWeight = standardWeights[Int(currentOverlowTextureRead * 2 + 1)]; let secondWeight = standardWeights[Int(currentOverlowTextureRead * 2 + 2)]; let optimizedWeight = firstWeight + secondWeight let optimizedOffset = (firstWeight * (Double(currentOverlowTextureRead) * 2.0 + 1.0) + secondWeight * (Double(currentOverlowTextureRead) * 2.0 + 2.0)) / optimizedWeight shaderString += "sum += texture2D(inputImageTexture, blurCoordinates[0] + singleStepOffset * \(optimizedOffset)) * \(optimizedWeight);\n" shaderString += "sum += texture2D(inputImageTexture, blurCoordinates[0] - singleStepOffset * \(optimizedOffset)) * \(optimizedWeight);\n" } shaderString += "gl_FragColor = sum;\n }\n" return shaderString }
apache-2.0
87fb4730a589e35ce7f992d9abde813e
53.044118
335
0.714739
4.299922
false
false
false
false
ioscreator/ioscreator
IOSCustomCollectionViewCellTutorial/IOSCustomCollectionViewCellTutorial/CollectionViewController.swift
1
3031
// // CollectionViewController.swift // IOSCustomCollectionViewCellTutorial // // Created by Arthur Knopper on 28/11/2018. // Copyright © 2018 Arthur Knopper. All rights reserved. // import UIKit private let reuseIdentifier = "Cell" class CollectionViewController: UICollectionViewController { let myImage = UIImage(named: "Apple_Swift_Logo") override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Register cell classes //self.collectionView!.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier) // Do any additional setup after loading the view. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ // MARK: UICollectionViewDataSource override func numberOfSections(in collectionView: UICollectionView) -> Int { // 1 return 1 } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { // 2 return 100 } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { // 3 let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! CollectionViewCell cell.imageView.image = myImage return cell } // MARK: UICollectionViewDelegate /* // Uncomment this method to specify if the specified item should be highlighted during tracking override func collectionView(_ collectionView: UICollectionView, shouldHighlightItemAt indexPath: IndexPath) -> Bool { return true } */ /* // Uncomment this method to specify if the specified item should be selected override func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool { return true } */ /* // Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item override func collectionView(_ collectionView: UICollectionView, shouldShowMenuForItemAt indexPath: IndexPath) -> Bool { return false } override func collectionView(_ collectionView: UICollectionView, canPerformAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) -> Bool { return false } override func collectionView(_ collectionView: UICollectionView, performAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) { } */ }
mit
512a6be5d7b90665d429900305ab8046
32.296703
170
0.706271
5.804598
false
false
false
false
LYM-mg/DemoTest
其他功能/MGImagePickerControllerDemo/MGImagePickerControllerDemo/MGPhotosBrowseCell.swift
1
4626
// // MGPhotosBrowseCell.swift // MGImagePickerControllerDemo // // Created by newunion on 2019/7/8. // Copyright © 2019 MG. All rights reserved. // import UIKit class MGPhotosBrowseCell: UICollectionViewCell { // MARK: public /// 显示图片的imageView lazy var mg_imageView : UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFit return imageView }() /// 单击执行的闭包 var mg_photoBrowerSimpleTapHandle:((Any)-> Void)? // MARK: private /// 是否已经缩放 fileprivate var isScale = false /// 底部负责缩放的滚动视图 lazy fileprivate var mg_scrollView : UIScrollView = { let scrollView = UIScrollView() scrollView.backgroundColor = .black scrollView.minimumZoomScale = CGFloat(self.minScaleZoome) scrollView.maximumZoomScale = CGFloat(self.maxScaleZoome) scrollView.delegate = self return scrollView }() /// 单击手势 lazy fileprivate var mg_simpleTap : UITapGestureRecognizer = { let simpleTap = UITapGestureRecognizer() simpleTap.numberOfTapsRequired = 1 simpleTap.require(toFail: self.mg_doubleTap) //设置响应 simpleTap.action({ [weak self](sender) in if let strongSelf = self { if strongSelf.mg_photoBrowerSimpleTapHandle != nil { //执行闭包 strongSelf.mg_photoBrowerSimpleTapHandle?(strongSelf) } } /********** 此处不再返回原始比例,如需此功能,请清除此处注释 2019/7/8 ***********/ /* if strongSelf!.mg_scrollView.zoomScale != 1.0 { strongSelf!.mg_scrollView.setZoomScale(1.0, animated: true) } */ /*************************************************************************/ }) return simpleTap }() /// 双击手势 lazy fileprivate var mg_doubleTap : UITapGestureRecognizer = { let doubleTap = UITapGestureRecognizer() doubleTap.numberOfTapsRequired = 2 doubleTap.action({ [weak self](sender) in let strongSelf = self //表示需要缩放成1.0 guard strongSelf!.mg_scrollView.zoomScale == 1.0 else { strongSelf!.mg_scrollView.setZoomScale(1.0, animated: true); return } //进行放大 let width = strongSelf!.frame.width let scale = width / CGFloat(strongSelf!.maxScaleZoome) let point = sender.location(in: strongSelf!.mg_imageView) //对点进行处理 let originX = max(0, point.x - width / scale) let originY = max(0, point.y - width / scale) //进行位置的计算 let rect = CGRect(x: originX, y: originY, width: width / scale, height: width / scale) //进行缩放 strongSelf!.mg_scrollView.zoom(to: rect, animated: true) }) return doubleTap }() /// 最小缩放比例 fileprivate let minScaleZoome = 1.0 /// 最大缩放比例 fileprivate let maxScaleZoome = 2.0 override init(frame: CGRect) { super.init(frame: frame) addAndLayoutSubViews() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func awakeFromNib() { super.awakeFromNib() addAndLayoutSubViews() } fileprivate func addAndLayoutSubViews() { contentView.addSubview(mg_scrollView) mg_scrollView.addSubview(mg_imageView) mg_scrollView.addGestureRecognizer(mg_simpleTap) mg_scrollView.addGestureRecognizer(mg_doubleTap) //layout mg_scrollView.snp.makeConstraints { (make) in make.edges.equalToSuperview().inset(UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)) } mg_imageView.snp.makeConstraints { [weak self](make) in let strongSelf = self make.edges.equalToSuperview() make.width.equalTo(strongSelf!.mg_scrollView.snp.width) make.height.equalTo(strongSelf!.mg_scrollView.snp.height) } } } extension MGPhotosBrowseCell : UIScrollViewDelegate { func viewForZooming(in scrollView: UIScrollView) -> UIView? { return mg_imageView } func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) { scrollView.setZoomScale(scale, animated: true) } }
mit
52bf8b9e1030d8260d4eb29d4666a183
23.348066
106
0.587928
4.698294
false
false
false
false
Inspirato/SwiftPhotoGallery
Example/SwiftPhotoGallery/DismissingAnimator.swift
1
2658
// // DismissingAnimator.swift // Inspirato // // Created by Justin Vallely on 6/12/17. // Copyright © 2017 Inspirato. All rights reserved. // import Foundation import UIKit import SwiftPhotoGallery class DismissingAnimator: NSObject, UIViewControllerAnimatedTransitioning { private let indexPath: IndexPath private let finalFrame: CGRect private let duration: TimeInterval = 0.5 init(pageIndex: Int, finalFrame: CGRect) { self.indexPath = IndexPath(item: pageIndex, section: 0) self.finalFrame = finalFrame super.init() } func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return duration } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { guard let toVC = transitionContext.viewController(forKey: .to) as? MainCollectionViewController, let fromVC = transitionContext.viewController(forKey: .from) as? SwiftPhotoGallery, let swiftPhotoGalleryCell = fromVC.imageCollectionView.cellForItem(at: indexPath) as? SwiftPhotoGalleryCell else { transitionContext.completeTransition(true) return } let containerView = transitionContext.containerView // Determine our original and final frames let size = swiftPhotoGalleryCell.imageView.frame.size let convertedRect = swiftPhotoGalleryCell.imageView.convert(swiftPhotoGalleryCell.imageView.bounds, to: containerView) let originFrame = CGRect(origin: convertedRect.origin, size: size) let viewToAnimate = UIImageView(frame: originFrame) viewToAnimate.center = CGPoint(x: convertedRect.midX, y: convertedRect.midY) viewToAnimate.image = swiftPhotoGalleryCell.imageView.image viewToAnimate.contentMode = .scaleAspectFill viewToAnimate.clipsToBounds = true containerView.addSubview(viewToAnimate) toVC.collectionView?.cellForItem(at: self.indexPath)?.isHidden = true fromVC.view.isHidden = true // Animate size and position UIView.animate(withDuration: duration, animations: { viewToAnimate.frame.size.width = self.finalFrame.width viewToAnimate.frame.size.height = self.finalFrame.height viewToAnimate.center = CGPoint(x: self.finalFrame.midX, y: self.finalFrame.midY) }, completion: { _ in toVC.collectionView?.cellForItem(at: self.indexPath)?.isHidden = false viewToAnimate.removeFromSuperview() transitionContext.completeTransition(true) }) } }
apache-2.0
3869499cc41896c4b6ff35c3a477dce8
37.507246
126
0.706436
5.271825
false
false
false
false
devincoughlin/swift
test/decl/init/nil.swift
1
1255
// RUN: %target-typecheck-verify-swift var a: Int = nil // expected-error@-1 {{'nil' cannot initialize specified type 'Int'}} // expected-note@-2 {{add '?' to form the optional type 'Int?'}} {{11-11=?}} var b: () -> Void = nil // expected-error@-1 {{'nil' cannot initialize specified type '() -> Void'}} // expected-note@-2 {{add '?' to form the optional type '(() -> Void)?'}} {{8-8=(}} {{18-18=)?}} var c, d: Int = nil // expected-error@-1 {{type annotation missing in pattern}} var (e, f): (Int, Int) = nil // expected-error@-1 {{'nil' cannot initialize specified type '(Int, Int)'}} var g: Int = nil, h: Int = nil // expected-error@-1 {{'nil' cannot initialize specified type 'Int'}} // expected-note@-2 {{add '?' to form the optional type 'Int?'}} {{11-11=?}} // expected-error@-3 {{'nil' cannot initialize specified type 'Int'}} // expected-note@-4 {{add '?' to form the optional type 'Int?'}} {{25-25=?}} var _: Int = nil // expected-error@-1 {{'nil' cannot initialize specified type 'Int'}} // expected-note@-2 {{add '?' to form the optional type 'Int?'}} {{11-11=?}} // 'nil' can initialize the specified type, if its generic parameters are bound var _: Array? = nil // expected-error {{generic parameter 'Element' could not be inferred}}
apache-2.0
e7aa8eedb7aa4fd439837027956cda17
43.821429
96
0.631873
3.515406
false
false
false
false
ryanbaldwin/Restivus
Tests/NotificationCenterPublishableSpec.swift
1
5369
// // NotificationCenterPublishableSpec.swift // Restivus // // Created by Ryan Baldwin on 2017-09-30. // Copyright © 2017 bunnyhug.me. All rights reserved. // import Quick import Nimble @testable import Restivus /// A NotificationCenterPublishable Restable, suitable for testing, which always return true for `shouldPublish` private struct PublishingRestable: Gettable, NotificationCenterPublishable { typealias ResponseType = Person func shouldPublish(_: HTTPURLResponse) -> Bool { return true } } /// A NotificationCenterPublishable Restable, suitable for testing, which always return false for `shouldPublish` private struct NonPublishingRestable: Gettable, NotificationCenterPublishable { typealias ResponseType = Person func shouldPublish(_: HTTPURLResponse) -> Bool { return false } } func makeURLResponse(_ statusCode: Int) -> HTTPURLResponse { return HTTPURLResponse(url: URL(string: "https://some.com")!, statusCode: statusCode, httpVersion: nil, headerFields: nil)! } class NotificationCenterPublishableSpec: QuickSpec { override func spec() { describe("A NotificationCenterPublishable Restable") { var observer: NSObjectProtocol! var data: Data! var receivedNotification = false beforeEach { receivedNotification = false observer = NotificationCenter.default.addObserver(forName: .RestivusReceivedNon200, object: nil, queue: nil) { _ in receivedNotification = true } data = try? JSONEncoder().encode(Person(firstName: "Ryan", lastName: "Baldwin", age: 38)) } afterEach { NotificationCenter.default.removeObserver(observer) receivedNotification = false } context("when its shouldPublish returns true") { let request = PublishingRestable() it("publishes a notification for 1xx responses") { request.dataTaskCompletionHandler(data: data, response: makeURLResponse(100), error: nil, completion: nil) expect(receivedNotification).toEventually(beTrue()) } it("does not publish a notification for 2xx responses") { request.dataTaskCompletionHandler(data: data, response: makeURLResponse(204), error: nil, completion: nil) expect(receivedNotification).toEventually(beFalse()) } it("publishes a notification for 3xx responses") { request.dataTaskCompletionHandler(data: data, response: makeURLResponse(302), error: nil, completion: nil) expect(receivedNotification).toEventually(beTrue()) } it("publishes a notification for 4xx responses") { request.dataTaskCompletionHandler(data: data, response: makeURLResponse(404), error: nil, completion: nil) expect(receivedNotification).toEventually(beTrue()) } it("publishes a notification for 5xx responses") { request.dataTaskCompletionHandler(data: data, response: makeURLResponse(500), error: nil, completion: nil) expect(receivedNotification).toEventually(beTrue()) } } context("when its shouldPublish returns false") { let request = NonPublishingRestable() it("does not publish a notification for 1xx responses") { request.dataTaskCompletionHandler(data: data, response: makeURLResponse(100), error: nil, completion: nil) expect(receivedNotification).toEventually(beFalse(), timeout: 1) } it("does not publish a notification for 2xx responses") { request.dataTaskCompletionHandler(data: data, response: makeURLResponse(204), error: nil, completion: nil) expect(receivedNotification).toEventually(beFalse(), timeout: 1) } it("does not publish a notification for 3xx responses") { request.dataTaskCompletionHandler(data: data, response: makeURLResponse(302), error: nil, completion: nil) expect(receivedNotification).toEventually(beFalse(), timeout: 1) } it("does not publish a notification for 4xx responses") { request.dataTaskCompletionHandler(data: data, response: makeURLResponse(404), error: nil, completion: nil) expect(receivedNotification).toEventually(beFalse(), timeout: 1) } it("does not publish a notification for 5xx responses") { request.dataTaskCompletionHandler(data: data, response: makeURLResponse(500), error: nil, completion: nil) expect(receivedNotification).toEventually(beFalse(), timeout: 1) } } } } }
apache-2.0
daa4bd1a2483659057efd86cc3cc0087
46.087719
126
0.588115
5.710638
false
false
false
false
DonMag/ScratchPad
Swift3/scratchy/XC8.playground/Pages/Image Scale.xcplaygroundpage/Contents.swift
1
2720
//: [Previous](@previous) import Foundation import UIKit import PlaygroundSupport var screenSize = CGSize(width: 600, height: 600) let containerView = UIView(frame: CGRect(x: 0, y: 0, width: screenSize.width, height: screenSize.height)) containerView.backgroundColor = UIColor.orange class MyImage: UIImage { // Resize image func resized(withPercentage percentage: CGFloat) -> UIImage? { let canvasSize = CGSize(width: size.width * percentage, height: size.height * percentage) UIGraphicsBeginImageContextWithOptions(canvasSize, false, scale) defer { UIGraphicsEndImageContext() } draw(in: CGRect(origin: .zero, size: canvasSize)) return UIGraphicsGetImageFromCurrentImageContext() } func resized(toWidth width: CGFloat) -> UIImage? { let canvasSize = CGSize(width: width, height: size.height * width / size.width) UIGraphicsBeginImageContextWithOptions(canvasSize, false, scale) defer { UIGraphicsEndImageContext() } draw(in: CGRect(origin: .zero, size: canvasSize)) return UIGraphicsGetImageFromCurrentImageContext() } func resized(toHeight height: CGFloat) -> UIImage? { let canvasSize = CGSize(width: size.width * height / size.height, height: height) UIGraphicsBeginImageContextWithOptions(canvasSize, false, scale) defer { UIGraphicsEndImageContext() } draw(in: CGRect(origin: .zero, size: canvasSize)) return UIGraphicsGetImageFromCurrentImageContext() } } var finalImage = UIImage() var img = UIImage(named: "car.png") var myImg = MyImage(cgImage: (img?.cgImage)!) var finalImageSize: CGFloat = 200.0 var w = myImg.size.width var h = myImg.size.height if w > h { finalImage = myImg.resized(toHeight: finalImageSize)! } else { finalImage = myImg.resized(toWidth: finalImageSize)! } let imgView = UIImageView(frame: CGRect(x: 40, y: 280, width: 200, height: 200)) imgView.backgroundColor = UIColor.red imgView.contentMode = .center imgView.clipsToBounds = true imgView.image = finalImage containerView.addSubview(imgView) let v = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200)) v.backgroundColor = UIColor.black containerView.addSubview(v) let newImage = UIImage(named: "car.png") let newImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 200, height: 200)) newImageView.image = newImage newImageView.contentMode = .scaleAspectFill newImageView.layer.cornerRadius = newImageView.frame.width / 2 newImageView.layer.masksToBounds = true //let maskView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200)) //maskView.layer.cornerRadius = maskView.frame.width / 2 //iv.mask = maskView containerView.addSubview(newImageView) PlaygroundPage.current.liveView = containerView PlaygroundPage.current.needsIndefiniteExecution = true
mit
595a6de9b11adfba15f6538dd54f725f
30.264368
105
0.759559
3.913669
false
false
false
false
anilmanukonda/Watson
Watson/Watson/Watson.swift
1
2453
// // Watson.swift // Watson // // Copyright © 2017 Anil. All rights reserved. // import Foundation import UIKit protocol WatsonInfo {} extension Bool: WatsonInfo {} public struct Watson { private static let isSimulator: Bool = { var isSim = false #if arch(i386) || arch(x86_64) isSim = true #endif return isSim }() private static var deviceInfo: DeviceInfo? public static var batteryStats: BatteryStats? public static var isBeaconsSupported = false public static var is3DTouchSupported = false public static var isLocationEnabled = false public static var isProximityEnabled = false public static var hasTouchId = false private init() {} public static func scan(_ properties: DeviceProperties...) { debugPrint("Watson is starting investigation...🕵🏻") guard isSimulator else { debugPrint("Sorry..too busy playing crime tycoon on iOS simulator") return } for property in properties { switch property { case .battery: debugPrint("Recharging your battery...🔋") batteryStats = property.details() case .beacons: debugPrint("Checking for wireless bugs...🔌🔉") isBeaconsSupported = property.details() ?? false case .deviceInfo: debugPrint("Gathering device details... easy there... not your passwords📱") deviceInfo = property.details() case .forceTouch: debugPrint("Force touch or 3D touch...fat fingers📲") is3DTouchSupported = property.details() ?? false case .location: debugPrint("Locating you...just kidding🗺") isLocationEnabled = property.details() ?? false case .proximityMonitoring: isProximityEnabled = property.details() ?? false case .touchId: debugPrint("Gathering finger prints🖕🏼") hasTouchId = property.details() ?? false } } debugPrint("Case closed...🕵🏻") } public static func operatingSystem() -> DeviceInfo.DeviceOS { return deviceInfo?.operatingSystem ?? .iOSUnknown } public static func deviceModel() -> DeviceModel { return deviceInfo?.deviceModel ?? .other } }
mit
15e34edb1f26fefeb6f9c7609ce0a80c
32.09589
91
0.590232
5.118644
false
false
false
false
netguru/inbbbox-ios
Inbbbox/Source Files/Managers/Shots State Handlers/ShotsOnboardingStateHandler.swift
1
6852
// // Copyright (c) 2016 Netguru Sp. z o.o. All rights reserved. // import Foundation import SwiftyUserDefaults import PromiseKit class ShotsOnboardingStateHandler: NSObject, ShotsStateHandler { fileprivate let connectionsRequester = APIConnectionsRequester() fileprivate let userProvider = APIUsersProvider() fileprivate let netguruIdentifier = "netguru" weak var shotsCollectionViewController: ShotsCollectionViewController? weak var delegate: ShotsStateHandlerDelegate? weak var skipDelegate: OnboardingSkipButtonHandlerDelegate? let onboardingSteps: [(image: UIImage?, action: ShotCollectionViewCell.Action)] var scrollViewAnimationsCompletion: (() -> Void)? var state: ShotsCollectionViewController.State { return .onboarding } var nextState: ShotsCollectionViewController.State? { return .normal } var tabBarInteractionEnabled: Bool { return false } var tabBarAlpha: CGFloat { return 0.3 } var collectionViewLayout: UICollectionViewLayout { return ShotsCollectionViewFlowLayout() } var collectionViewInteractionEnabled: Bool { return true } var collectionViewScrollEnabled: Bool { return false } var shouldShowNoShotsView: Bool { return false } func prepareForPresentingData() { self.disablePrefetching() } func presentData() { shotsCollectionViewController?.collectionView?.reloadData() } override init() { let step1 = Localized("ShotsOnboardingStateHandler.Onboarding-Step1", comment: "") let step2 = Localized("ShotsOnboardingStateHandler.Onboarding-Step2", comment: "") let step3 = Localized("ShotsOnboardingStateHandler.Onboarding-Step3", comment: "") let step4 = Localized("ShotsOnboardingStateHandler.Onboarding-Step4", comment: "") let step5 = Localized("ShotsOnboardingStateHandler.Onboarding-Step5", comment: "") onboardingSteps = [ (image: UIImage(named: step1), action: ShotCollectionViewCell.Action.like), (image: UIImage(named: step2), action: ShotCollectionViewCell.Action.bucket), (image: UIImage(named: step3), action: ShotCollectionViewCell.Action.comment), (image: UIImage(named: step4), action: ShotCollectionViewCell.Action.follow), (image: UIImage(named: step5), action: ShotCollectionViewCell.Action.doNothing), ] } func skipOnboardingStep() { guard let collectionView = shotsCollectionViewController?.collectionView else { return } collectionView.animateToNextCell() } } // MARK: UICollectionViewDataSource extension ShotsOnboardingStateHandler { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { guard let shotsCollectionViewController = shotsCollectionViewController else { return onboardingSteps.count } return onboardingSteps.count + shotsCollectionViewController.shots.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if indexPath.row < onboardingSteps.count { return cellForOnboardingShot(collectionView, indexPath: indexPath) } else { return cellForShot(collectionView, indexPath: indexPath) } } } // MARK: UICollectionViewDelegate extension ShotsOnboardingStateHandler { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { guard indexPath.row == onboardingSteps.count - 1 else { return } scrollViewAnimationsCompletion = { Defaults[.onboardingPassed] = true self.enablePrefetching() self.delegate?.shotsStateHandlerDidInvalidate(self) } skipOnboardingStep() } } // MARK: UIScrollViewDelegate extension ShotsOnboardingStateHandler { func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) { scrollViewAnimationsCompletion?() scrollViewAnimationsCompletion = nil } } // MARK: Private methods private extension ShotsOnboardingStateHandler { func cellForShot(_ collectionView: UICollectionView, indexPath: IndexPath) -> ShotCollectionViewCell { guard let shotsCollectionViewController = shotsCollectionViewController else { return ShotCollectionViewCell() } let shot = shotsCollectionViewController.shots[0] let cell = collectionView.dequeueReusableClass(ShotCollectionViewCell.self, forIndexPath: indexPath, type: .cell) cell.shotImageView.loadShotImageFromURL(shot.shotImage.normalURL) cell.displayAuthor(Settings.Customization.ShowAuthor, animated: false) cell.gifLabel.isHidden = !shot.animated return cell } func cellForOnboardingShot(_ collectionView: UICollectionView, indexPath: IndexPath) -> ShotCollectionViewCell { let cell = collectionView.dequeueReusableClass(ShotCollectionViewCell.self, forIndexPath: indexPath, type: .cell) let stepImage = onboardingSteps[indexPath.row].image cell.shotImageView.image = stepImage cell.gifLabel.isHidden = true cell.enabledActions = [self.onboardingSteps[indexPath.row].action] cell.swipeCompletion = { [weak self] action in guard let certainSelf = self, action == certainSelf.onboardingSteps[indexPath.row].action else { return } collectionView.animateToNextCell() if action == .follow { certainSelf.followNetguru() } } let currentStep = onboardingSteps[indexPath.row].action switch currentStep { case .follow: skipDelegate?.shouldSkipButtonAppear() default: skipDelegate?.shouldSkipButtonDisappear() } return cell } func followNetguru() { firstly { userProvider.provideUser(netguruIdentifier) }.then { user in self.connectionsRequester.followUser(user) }.catch { _ in } } func enablePrefetching() { if #available(iOS 10.0, *) { self.shotsCollectionViewController?.collectionView?.isPrefetchingEnabled = true } } func disablePrefetching() { if #available(iOS 10.0, *) { self.shotsCollectionViewController?.collectionView?.isPrefetchingEnabled = false } } } private extension UICollectionView { func animateToNextCell() { var newContentOffset = contentOffset newContentOffset.y += bounds.height setContentOffset(newContentOffset, animated: true) } }
gpl-3.0
1c63cbf87134a93ea6c9fb947dc33314
33.606061
116
0.682574
5.468476
false
false
false
false
mspvirajpatel/SwiftyBase
Example/SwiftyBase/Model/AllContry.swift
1
2021
// // AllContry.swift // SwiftyBase // // Created by MacMini-2 on 05/09/17. // Copyright © 2017 CocoaPods. All rights reserved. // import UIKit class AllContry: NSObject, NSCoding { var code : Int! var result : [Result]! /** * Instantiate the instance using the passed dictionary values to set the properties values */ init(fromDictionary dictionary: [String:Any]){ code = dictionary["code"] as? Int result = [Result]() if let resultArray = dictionary["result"] as? [[String:Any]]{ for dic in resultArray{ let value = Result(fromDictionary: dic) result.append(value) } } } /** * Returns all the available property values in the form of [String:Any] object where the key is the approperiate json key and the value is the value of the corresponding property */ func toDictionary() -> [String:Any] { var dictionary = [String:Any]() if code != nil{ dictionary["code"] = code } if result != nil{ var dictionaryElements = [[String:Any]]() for resultElement in result { dictionaryElements.append(resultElement.toDictionary()) } dictionary["result"] = dictionaryElements } return dictionary } /** * NSCoding required initializer. * Fills the data from the passed decoder */ @objc required init(coder aDecoder: NSCoder) { code = aDecoder.decodeObject(forKey: "code") as? Int result = aDecoder.decodeObject(forKey :"result") as? [Result] } /** * NSCoding required method. * Encodes mode properties into the decoder */ @objc func encode(with aCoder: NSCoder) { if code != nil{ aCoder.encode(code, forKey: "code") } if result != nil{ aCoder.encode(result, forKey: "result") } } }
mit
bc5300b8bacf0368cd868c63d42ad48a
25.933333
183
0.563366
4.654378
false
false
false
false
KTMarc/Marvel-Heroes
Marvel Heroes/AppDelegate.swift
1
3573
// // AppDelegate.swift // Marvel Heroes // // Created by Marc Humet on 10/4/16. // Copyright © 2016 SPM. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate/*, UISplitViewControllerDelegate */{ var window: UIWindow? private func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { BuddyBuildSDK.setup() // Override point for customization after application launch. // let splitViewController = self.window!.rootViewController as! UISplitViewController // let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController // navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem() // splitViewController.delegate = self UINavigationBar.appearance().titleTextAttributes = [ NSAttributedStringKey.font.rawValue: UIFont(name: "GothamLight", size: 15)! ] return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } // MARK: - Split view // func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController, ontoPrimaryViewController primaryViewController:UIViewController) -> Bool { // guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false } // guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false } // if topAsDetailController.detailItem == nil { // // Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded. // return true // } // return false // } }
mit
4b15d64a916dcd4645893158ab60a459
53.121212
285
0.74748
5.913907
false
false
false
false
pawan007/SmartZip
SmartZip/Controllers/SideMenu/LeftMenuViewController.swift
1
10155
// // LeftMenuViewController.swift // SmartZip // // Created by Pawan Kumar on 16/06/16. // Copyright © 2016 Modi. All rights reserved. // import UIKit import MMDrawerController import MessageUI class LeftMenuViewController: UIViewController ,MFMailComposeViewControllerDelegate{ @IBOutlet weak var topTableView: UITableView! // private var topTableIDs = ["HomeCell","TutorialCell","BuyProCell","RestoreCell","ShareAppCell","RateAppCell","AboutCompany","AboutProduct","EmailCell"] private var topTableIDs = ["HomeCell","TutorialCell","ShareAppCell","RateAppCell","AboutCompany","AboutProduct","EmailCell"] override func viewDidLoad() { super.viewDidLoad() } override internal func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.topTableView.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension LeftMenuViewController: UITableViewDataSource { func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return topTableIDs.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(topTableIDs[indexPath.row]) return cell! } } // MARK: - UITableViewDelegate extension LeftMenuViewController: UITableViewDelegate { func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { self.topTableViewSelected(tableView, didSelectRowAtIndexPath: indexPath) } func topTableViewSelected(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let container = SideMenuManager.sharedManager().container let identifier = topTableIDs[indexPath.row] switch identifier { case "HomeCell" : let center = (self.storyboard?.instantiateViewControllerWithIdentifier("HomeVCNew"))! container!.centerViewController = UINavigationController(rootViewController: center) container!.closeDrawerAnimated(true, completion: { (Bool) in }) break case "TutorialCell" : //TODO let center = (self.storyboard?.instantiateViewControllerWithIdentifier("WLCTutorialVC"))! container!.centerViewController = UINavigationController(rootViewController: center) container!.closeDrawerAnimated(true, completion: { (Bool) in }) break case "BuyProCell" : let center = (self.storyboard?.instantiateViewControllerWithIdentifier("BuyProVC"))! container!.centerViewController = UINavigationController(rootViewController: center) container!.closeDrawerAnimated(true, completion: { (Bool) in }) break case "RestoreCell" : let center = self.storyboard?.instantiateViewControllerWithIdentifier("BuyProVC") as? BuyProVC container!.centerViewController = UINavigationController(rootViewController: center!) center!.isShowRestoreBtn = true container!.closeDrawerAnimated(true, completion: { (Bool) in }) break //TODO case "PasswordCell" : container!.closeDrawerAnimated(true, completion: { (Bool) in let passcodeVC : PasscodeVC = UIStoryboard.mainStoryboard().instantiateViewControllerWithIdentifier("PasscodeVC") as! PasscodeVC self.presentViewController(passcodeVC, animated: true, completion: nil) //self.navigationController?.pushViewController(passcodeVC, animated: true) }) break //TODO case "ShareAppCell" : container!.closeDrawerAnimated(true, completion: { (Bool) in }) self.shareApp() break case "RateAppCell" : container!.closeDrawerAnimated(true, completion: { (Bool) in }) iRate.sharedInstance().openRatingsPageInAppStore() break case "AboutCompany" : self.openAboutCompanyVC(); break case "AboutProduct" : self.openAboutProductVC(); break case "EmailCell" : self.sendEmail(); break case "HistoryCell" : let center = (self.storyboard?.instantiateViewControllerWithIdentifier("HistoryVC"))! container!.centerViewController = UINavigationController(rootViewController: center) container!.closeDrawerAnimated(true, completion: { (Bool) in }) break default: break } } func openAboutCompanyVC() { let container = SideMenuManager.sharedManager().container let center = (self.storyboard?.instantiateViewControllerWithIdentifier("AboutCompany"))! container!.centerViewController = UINavigationController(rootViewController: center) container!.closeDrawerAnimated(true, completion: { (Bool) in }) } func openAboutProductVC() { let container = SideMenuManager.sharedManager().container let center = (self.storyboard?.instantiateViewControllerWithIdentifier("AboutProduct"))! container!.centerViewController = UINavigationController(rootViewController: center) container!.closeDrawerAnimated(true, completion: { (Bool) in }) } func shareApp() { let textToShare = "Quick and smart way for zip file management. SmartZip is user friendly app for iPhone. It can easily zip our files and upload/share it on cloud and social media. Its a most useful and fast Zip utility for professional and business persons. It has very interesting features : 1) It can compress files, photos, videos, music into Zip file. 2) You can send zip file by email, messenger, Gmail. 3) Open and extract files from Zip format. 4) Save your zipped files in MyFiles section for future use. 5) Upload your zip files on cloud like Dropbox, Google drive, iCloud drive. So friends what are you waiting for! Use SmartZip be smart !!" if let myWebsite = NSURL(string: "https://itunes.apple.com/us/app/smartzip/id1141913794?ls=1&mt=8") { let objectsToShare = [textToShare, myWebsite] let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil) //New Excluded Activities Code // activityVC.excludedActivityTypes = [UIActivityTypeAirDrop, UIActivityTypeAddToReadingList] // if let popoverPresentationController = activityVC.popoverPresentationController { popoverPresentationController.sourceView = self.view var rect=self.view.frame rect.origin.y = rect.height popoverPresentationController.sourceRect = rect } self.presentViewController(activityVC, animated: true, completion: nil) } } func sendEmail() { if MFMailComposeViewController.canSendMail() { let mail = MFMailComposeViewController() mail.mailComposeDelegate = self mail.setToRecipients(["[email protected]"]) mail.setSubject("SmartZip - Feedback to Admin") mail.setMessageBody("<p>Dear Admin</p>", isHTML: true) presentViewController(mail, animated: true, completion: nil) } else { // show failure alert self.showAlertViewWithMessage("Error", message: Constants.UserMessages.missingEmail) } } func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) { controller.dismissViewControllerAnimated(true, completion: nil) } func contactAdmin() { let actionSheetController: UIAlertController = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet) actionSheetController.view.tintColor = UIColor.blackColor() let cancelActionButton: UIAlertAction = UIAlertAction(title: "Cancel", style: .Cancel) { action -> Void in } actionSheetController.addAction(cancelActionButton) let webActionButton: UIAlertAction = UIAlertAction(title: "View Website", style: .Default) { action -> Void in let url:NSURL? = NSURL(string: "http://www.SmartZip.com.au/") UIApplication.sharedApplication().openURL(url!) } actionSheetController.addAction(webActionButton) let feedbackActionButton: UIAlertAction = UIAlertAction(title: "Give Feedback", style: .Default) { action -> Void in self.sendEmail() } actionSheetController.addAction(feedbackActionButton) let callActionButton: UIAlertAction = UIAlertAction(title: " Call Admin", style: .Default) { action -> Void in self.callNumber("0450 663 654") } actionSheetController.addAction(callActionButton) if let popoverPresentationController = actionSheetController.popoverPresentationController { popoverPresentationController.sourceView = self.view popoverPresentationController.sourceRect = self.topTableView.frame } self.presentViewController(actionSheetController, animated: true, completion: nil) } private func callNumber(phoneNumber:String) { if let phoneCallURL:NSURL = NSURL(string:"tel://"+"\(phoneNumber)") { let application:UIApplication = UIApplication.sharedApplication() if (application.canOpenURL(phoneCallURL)) { application.openURL(phoneCallURL); } } } }
mit
5230bcf07daa51a40d84bf84493a6853
41.13278
660
0.652551
5.672626
false
false
false
false
mrommel/TreasureDungeons
TreasureDungeons/Source/OpenGL/Model.swift
1
5388
// // Model.swift // Model // // Created by burt on 2016. 2. 27.. // Copyright © 2016년 BurtK. All rights reserved. // import GLKit class Model { var shader: BaseEffect! var name: String! var vertices: [Vertex]! var vertexCount: GLuint! var indices: [GLuint]! var indexCount: GLuint! var vao: GLuint = 0 var vertexBuffer: GLuint = 0 var indexBuffer: GLuint = 0 var texture: GLuint = 0 // ModelView Transformation var position : GLKVector3 = GLKVector3(v: (0.0, 0.0, 0.0)) var rotationX : Float = 0.0 var rotationY : Float = 0.0 var rotationZ : Float = 0.0 var scale : Float = 1.0 init(name: String, shader: BaseEffect, vertices: [Vertex], indices: [GLuint]) { self.name = name self.shader = shader self.updateBuffers(vertices: vertices, indices: indices) } func updateBuffers(vertices: [Vertex], indices: [GLuint]) { self.vertices = vertices self.vertexCount = GLuint(vertices.count) self.indices = indices self.indexCount = GLuint(indices.count) glGenVertexArraysOES(1, &vao) // GPU에 VertexArrayObject를 생성해서 미리 정점과 인덱스를 CPU에서 GPU로 모두 복사한다 glBindVertexArrayOES(vao) glGenBuffers(GLsizei(1), &vertexBuffer) glBindBuffer(GLenum(GL_ARRAY_BUFFER), vertexBuffer) let count = vertices.count let size = MemoryLayout<Vertex>.size glBufferData(GLenum(GL_ARRAY_BUFFER), count * size, vertices, GLenum(GL_STATIC_DRAW)) glGenBuffers(GLsizei(1), &indexBuffer) glBindBuffer(GLenum(GL_ELEMENT_ARRAY_BUFFER), indexBuffer) glBufferData(GLenum(GL_ELEMENT_ARRAY_BUFFER), indices.count * MemoryLayout<GLuint>.size, indices, GLenum(GL_STATIC_DRAW)) // 현재 vao가 바인딩 되어 있어서 아래 함수를 실행하면 정점과 인덱스 데이터가 모두 vao에 저장된다. glEnableVertexAttribArray(VertexAttributes.position.rawValue) glVertexAttribPointer( VertexAttributes.position.rawValue, 3, GLenum(GL_FLOAT), GLboolean(GL_FALSE), GLsizei(MemoryLayout<Vertex>.size), BUFFER_OFFSET(0)) glEnableVertexAttribArray(VertexAttributes.color.rawValue) glVertexAttribPointer( VertexAttributes.color.rawValue, 4, GLenum(GL_FLOAT), GLboolean(GL_FALSE), GLsizei(MemoryLayout<Vertex>.size), BUFFER_OFFSET(3 * MemoryLayout<GLfloat>.size)) // x, y, z | r, g, b, a :: offset is 3*sizeof(GLfloat) glEnableVertexAttribArray(VertexAttributes.texCoord.rawValue) glVertexAttribPointer( VertexAttributes.texCoord.rawValue, 2, GLenum(GL_FLOAT), GLboolean(GL_FALSE), GLsizei(MemoryLayout<Vertex>.size), BUFFER_OFFSET((3+4) * MemoryLayout<GLfloat>.size)) // x, y, z | r, g, b, a | u, v :: offset is (3+4)*sizeof(GLfloat) glEnableVertexAttribArray(VertexAttributes.normal.rawValue) glVertexAttribPointer( VertexAttributes.normal.rawValue, 3, GLenum(GL_FLOAT), GLboolean(GL_FALSE), GLsizei(MemoryLayout<Vertex>.size), BUFFER_OFFSET((3+4+2) * MemoryLayout<GLfloat>.size)) // x, y, z | r, g, b, a | u, v | nx, ny, nz :: offset is (3+4+2)*sizeof(GLfloat) // 바인딩을 끈다 glBindVertexArrayOES(0) glBindBuffer(GLenum(GL_ARRAY_BUFFER), 0) glBindBuffer(GLenum(GL_ELEMENT_ARRAY_BUFFER), 0) } func modelMatrix() -> GLKMatrix4 { var modelMatrix : GLKMatrix4 = GLKMatrix4Identity modelMatrix = GLKMatrix4Translate(modelMatrix, self.position.x, self.position.y, self.position.z) modelMatrix = GLKMatrix4Rotate(modelMatrix, self.rotationX, 1, 0, 0) modelMatrix = GLKMatrix4Rotate(modelMatrix, self.rotationY, 0, 1, 0) modelMatrix = GLKMatrix4Rotate(modelMatrix, self.rotationZ, 0, 0, 1) modelMatrix = GLKMatrix4Scale(modelMatrix, self.scale, self.scale, self.scale) return modelMatrix } func render(withParentModelViewMatrix parentModelViewMatrix: GLKMatrix4) { let modelViewMatrix : GLKMatrix4 = GLKMatrix4Multiply(parentModelViewMatrix, modelMatrix()) shader.modelViewMatrix = modelViewMatrix shader.texture = self.texture shader.prepareToDraw() glBindVertexArrayOES(vao) glDrawElements(GLenum(GL_TRIANGLES), GLsizei(indices.count), GLenum(GL_UNSIGNED_INT), nil) glBindVertexArrayOES(0) } func updateWithDelta(_ dt: TimeInterval) { } func loadTexture(_ filename: String) { let path = Bundle.main.path(forResource: filename, ofType: nil)! let option = [ GLKTextureLoaderOriginBottomLeft: true] do { let info = try GLKTextureLoader.texture(withContentsOfFile: path, options: option as [String : NSNumber]?) self.texture = info.name } catch { } } func BUFFER_OFFSET(_ n: Int) -> UnsafeRawPointer? { return UnsafeRawPointer(bitPattern: n) } }
apache-2.0
7bedd80999ed468b0f3d48fb1bf5082b
35.213793
181
0.617787
4.045455
false
false
false
false
vasilyjp/tech_salon_ios_twitter_client
TwitterClient/TweetsRequest.swift
1
3504
// // TweetsRequest.swift // TwitterClient // // Created by Nicholas Maccharoli on 2016/09/26. // Copyright © 2016 Vasily inc. All rights reserved. // import Social import Accounts final class TweetsRequest { enum TwitterError: Error { case noAccount } static let requestMaxTweetCount: Int = 50 private static let backgroundQueue = DispatchQueue(label: "com.twitterClient.background", qos: .default) fileprivate static let accountStore: ACAccountStore = ACAccountStore() fileprivate static let accountType: ACAccountType = { return accountStore.accountType(withAccountTypeIdentifier: ACAccountTypeIdentifierTwitter)! }() // MARK: Request fileprivate static func performRequest(url: URL, parameters: [String: String]?, account: ACAccount, completion: @escaping ((Data?, Error?) -> Void)) { guard let request = SLRequest(forServiceType: SLServiceTypeTwitter, requestMethod: .GET, url: url, parameters: parameters) else { return } request.account = account backgroundQueue.async { request.perform { data, _, error in DispatchQueue.main.async { completion(data, error) } } } } fileprivate static func tweets(withData data: Data?) -> [Tweet]? { guard let data = data else { return nil } guard let jsonResponse = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) else { return nil } guard let response = jsonResponse as? [AnyObject] else { return nil } let tweets = response.flatMap { $0 as? [String: AnyObject] } .flatMap { Tweet(dictionary: $0) } return tweets } } // MARK: public extension TweetsRequest { static func firstAccount() -> ACAccount? { guard let accounts = accountStore.accounts(with: accountType) else { return nil } guard let account = accounts.first as? ACAccount else { return nil } return account } static func requestPermission(withCompletion completion: @escaping ((Bool, Error?) -> Void)) { accountStore.requestAccessToAccounts(with: accountType, options: nil, completion: completion) } static func timeline(maxId: Int64?, withCompletion completion: @escaping (([Tweet]?, Error?) -> Void)) { guard let account = firstAccount() else { completion(nil, TwitterError.noAccount) return } let twitterTimeLineURL: URL = URL(string: "https://api.twitter.com/1.1/statuses/user_timeline.json")! var parameters: [String: String] = [ "screen_name": account.username, "count": "\(requestMaxTweetCount)", "exclude_replies": "true", "include_rts": "false", ] if let maxId = maxId { parameters["max_id"] = "\(maxId)" } performRequest(url: twitterTimeLineURL, parameters: parameters, account: account) { data, error in if let error = error { completion(nil, error) return } guard let tweets = tweets(withData: data) else { completion(nil, nil) return } completion(tweets, nil) } } }
mit
010dc31c6bb0064eb52aceee535c011c
32.04717
124
0.581787
5.004286
false
false
false
false
jedlewison/ObservableProperty
ObservableProperty/ObservationEvent.swift
1
1365
// // Observation.swift // ObservableProperty // // Created by Jed Lewison on 2/28/16. // Copyright © 2016 Jed Lewison. All rights reserved. // import Foundation final public class Observation<Value> { public let event: ObservationEvent<Value> weak var observerBox: WeakObserverBox<Value>? init(event: ObservationEvent<Value>, observerBox: WeakObserverBox<Value>) { self.event = event self.observerBox = observerBox } public var value: Value { return event.value } public var error: ErrorType? { return event.error } public func unobserve() { observerBox?.boxedObserver = nil } } public enum ObservationEvent<Value> { case Next(Value) case Error(ErrorType, Value) public var value: Value { switch self { case .Next(let value): return value case .Error(_, let value): return value } } public var error: ErrorType? { switch self { case .Next(_): return nil case .Error(let error, _): return error } } public init(change: Value, error: ErrorType?) { switch (change, error) { case (_, .Some(let error)): self = .Error(error, change) case _: self = .Next(change) } } }
mit
c67bf1080caa5bf3eb731304e53c2476
19.681818
79
0.569648
4.2625
false
false
false
false
ZhaoBingDong/CYPhotosLibrary
CYPhotoKit/View/CYPhotoPreviewCollectionViewCell.swift
1
1026
// // CYPhotoPreviewCollectionViewCell.swift // CYPhotosKit // // Created by 董招兵 on 2017/8/10. // Copyright © 2017年 大兵布莱恩特. All rights reserved. // import UIKit public class CYPhotoPreviewCollectionViewCell: UICollectionViewCell { public var imageView : UIImageView? public var asset : CYPhotosAsset? { didSet { imageView?.image = asset?.originalImg } } override public init(frame: CGRect) { super.init(frame: frame) contentView.backgroundColor = .black imageView = UIImageView() imageView?.contentMode = .scaleAspectFit contentView.addSubview(imageView!) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public override func layoutSubviews() { super.layoutSubviews() self.imageView?.frame = CGRect(x: 10.0, y: 0.0, width: self.contentView.bounds.size.width-20.0, height: self.contentView.bounds.size.height) } }
apache-2.0
8d95af20a801a228508e0f7f32e0f7b6
28.558824
148
0.666667
4.240506
false
false
false
false
sora0077/DribbbleKit
DribbbleKit/Sources/Error.swift
1
2024
// // Error.swift // DribbbleKit // // Created by 林 達也 on 2017/04/26. // Copyright © 2017年 jp.sora0077. All rights reserved. // import Foundation import APIKit import Alter public enum DribbbleError: Swift.Error { public struct Error { public let attribute: String public let message: String } case invalidJSON(message: String) case invalidFields(message: String, errors: [Error]) case invalidScope(current: [OAuth.Scope], require: OAuth.Scope) case invalidOAuth(error: String, description: String) case rateLimit(message: String, meta: Meta) case notFound case unexpected } extension DribbbleError.Error: Decodable { public static func decode(_ decoder: Decoder) throws -> DribbbleError.Error { return try self.init( attribute: decoder.decode(forKeyPath: "attribute"), message: decoder.decode(forKeyPath: "message")) } } private struct BaseError: Decodable { let message: String let errors: [DribbbleError.Error]? func actualError(_ meta: Meta) -> Error { if let errors = errors { return DribbbleError.invalidFields(message: message, errors: errors) } else if meta.status == 429 { return DribbbleError.rateLimit(message: message, meta: meta) } else { return DribbbleError.invalidJSON(message: message) } } static func decode(_ decoder: Decoder) throws -> BaseError { return try self.init( message: decoder.decode(forKeyPath: "message"), errors: decoder.decode(forKeyPath: "errors", optional: true)) } } extension Request { func throwIfErrorOccurred(from object: Any, meta: Meta) throws { let code = meta.status if (400..<500).contains(code) && code != 404 { do { throw (try decode(object) as BaseError).actualError(meta) } catch let error as DribbbleError { throw error } catch {} } } }
mit
2665b52d4a25040ad112d81a4cae04c3
29.074627
81
0.632754
4.370933
false
false
false
false
LoganHollins/SuperStudent
SuperStudent/EditProfileViewController.swift
1
1803
// // EditProfileViewController.swift // SuperStudent // // Created by Logan Hollins on 2015-11-28. // Copyright © 2015 Logan Hollins. All rights reserved. // import UIKit import Alamofire class EditProfileViewController: UIViewController { @IBOutlet weak var aboutField: UITextView! @IBAction func updateProfile(sender: AnyObject) { var path = "https://api.mongolab.com/api/1/databases/rhythmictracks/collections/Users?apiKey=L4HrujTTG-XOamCKvRJp5RwYMpoJ6xCZ&q={'studentId':'\(StudentInfo.StudentId)'}" path = path.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())! Alamofire.request(.PUT, path, parameters: ["$set": ["about":aboutField.text]], encoding: .JSON) StudentInfo.About = aboutField.text navigationController?.popViewControllerAnimated(true) } override func viewDidLoad() { super.viewDidLoad() aboutField.text = StudentInfo.About // Do any additional setup after loading the view. self.aboutField.layer.borderWidth = 1 self.aboutField.layer.borderColor = UIColor(red: 0.9, green: 0.9, blue: 0.9, alpha: 1.0).CGColor self.aboutField.layer.cornerRadius = 5 } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
gpl-2.0
1c8c46816698c2cd7d176496561eb722
33.653846
177
0.692009
4.493766
false
false
false
false
yhyuan/WeatherMap
WeatherAroundUs/WeatherAroundUs/CardView.swift
5
17261
// // CardView.swift // WeatherAroundUs // // Created by Kedan Li on 15/4/4. // Copyright (c) 2015年 Kedan Li. All rights reserved. // import UIKit import Spring class CardView: DesignableView, ImageCacheDelegate, InternetConnectionDelegate, AMapSearchDelegate{ var icon: UIImageView! var temperature: UILabel! var city: UILabel! var smallImage: UIImageView! var weatherDescription: UILabel! var parentViewController: ViewController! var iconBack: DesignableView! var temperatureBack: DesignableView! var cityBack: DesignableView! var weatherDescriptionBack: DesignableView! var smallImageBack: DesignableView! var iconBackCenter: CGPoint! var temperatureBackCenter: CGPoint! var cityBackCenter: CGPoint! var weatherDescriptionBackCenter: CGPoint! var smallImageEntered = false var imageUrlReady = false var hide = false var currentIcon = "" required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } let sideWidth:CGFloat = 6 var search: AMapSearchAPI? // get small city image from google func gotImageUrls(btUrl: String, imageURL: String, cityID: String) { var cache = ImageCache() cache.delegate = self cache.getSmallImageFromCache(btUrl, cityID: cityID) } func setup(){ search = AMapSearchAPI(searchKey: APIKey, delegate: self) hide = false iconBack = DesignableView(frame: CGRectMake(sideWidth, sideWidth, self.frame.height * 0.75 - sideWidth * 2, self.frame.height * 0.75 - sideWidth * 2)) self.addSubview(iconBack) addShadow(iconBack) addVisualEffectView(iconBack) icon = UIImageView(frame: CGRectMake(3, 3, iconBack.frame.width - 6, iconBack.frame.height - 6)) iconBack.addSubview(icon) iconBackCenter = iconBack.center temperatureBack = DesignableView(frame: CGRectMake(sideWidth * 2 + iconBack.frame.width, iconBack.frame.width - self.frame.height * 0.2 + sideWidth, self.frame.height * 0.6, self.frame.height * 0.2)) self.addSubview(temperatureBack) addShadow(temperatureBack) addVisualEffectView(temperatureBack) temperature = UILabel(frame: CGRectMake(5, 2, temperatureBack.frame.width - 8, temperatureBack.frame.height - 6)) temperature.font = UIFont(name: "AvenirNext-Medium", size: 24) temperature.adjustsFontSizeToFitWidth = true temperature.textAlignment = NSTextAlignment.Left temperature.textColor = UIColor.darkGrayColor() temperatureBack.addSubview(temperature) temperatureBackCenter = temperatureBack.center cityBack = DesignableView(frame: CGRectMake(sideWidth, iconBack.frame.height + sideWidth * 2, iconBack.frame.width * 1.8, self.frame.height - iconBack.frame.height - 3 * sideWidth)) self.addSubview(cityBack) addShadow(cityBack) addVisualEffectView(cityBack) city = UILabel(frame: CGRectMake(3, 3, cityBack.frame.width - 6, cityBack.frame.height - 6)) city.font = UIFont(name: "AvenirNext-Medium", size: 22) city.textAlignment = NSTextAlignment.Center city.adjustsFontSizeToFitWidth = true city.textColor = UIColor.darkGrayColor() cityBack.addSubview(city) cityBackCenter = cityBack.center weatherDescriptionBack = DesignableView(frame: CGRectMake(sideWidth * 2 + cityBack.frame.width, cityBack.frame.origin.y, self.frame.width - sideWidth * 3 - cityBack.frame.width, cityBack.frame.height)) self.addSubview(weatherDescriptionBack) addShadow(weatherDescriptionBack) addVisualEffectView(weatherDescriptionBack) weatherDescription = UILabel(frame: CGRectMake(3, 3, weatherDescriptionBack.frame.width - 6, weatherDescriptionBack.frame.height - 6)) weatherDescription.font = UIFont(name: "AvenirNext-Regular", size: 18) weatherDescription.textColor = UIColor.darkGrayColor() weatherDescription.textAlignment = NSTextAlignment.Center weatherDescriptionBack.addSubview(weatherDescription) weatherDescriptionBackCenter = weatherDescriptionBack.center smallImageBack = DesignableView(frame: CGRectMake(sideWidth + temperatureBack.frame.origin.x + temperatureBack.frame.width, temperatureBack.frame.origin.y, self.frame.width - sideWidth * 2 - temperatureBack.frame.origin.x - temperatureBack.frame.width, temperatureBack.frame.height)) self.addSubview(smallImageBack) addShadow(smallImageBack) addVisualEffectView(smallImageBack) smallImage = UIImageView(frame: CGRectMake(3, 3, smallImageBack.frame.width - 6, smallImageBack.frame.height - 6)) smallImage.alpha = 0.6 smallImageBack.addSubview(smallImage) // move the image away at the beginning smallImageBack.center = CGPointMake(smallImageBack.center.x + temperatureBack.frame.width * 1.5, smallImageBack.center.y) hideSelf() } func onReGeocodeSearchDone(request: AMapReGeocodeSearchRequest!, response: AMapReGeocodeSearchResponse!) { if response.regeocode.addressComponent.district != nil{ self.city.text = response.regeocode.addressComponent.district }else{ self.city.text = response.regeocode.addressComponent.city } } func displayCity(cityID: String){ if WeatherInfo.citiesAroundDict[cityID] != nil { // set image to invalid imageUrlReady = false var location = CLLocationCoordinate2DMake(((WeatherInfo.citiesAroundDict[cityID] as! [String : AnyObject]) ["coord"] as! [String: AnyObject])["lat"]! as! Double, ((WeatherInfo.citiesAroundDict[cityID] as! [String : AnyObject]) ["coord"] as! [String: AnyObject])["lon"]! as! Double) var connection = InternetConnection() connection.delegate = self //get image url connection.searchForCityPhotos(location, name: ((WeatherInfo.citiesAroundDict[cityID] as! [String: AnyObject])["name"] as? String)!, cityID: cityID) if UserLocation.inChina{ var regeoRequest = AMapReGeocodeSearchRequest() regeoRequest.location = AMapGeoPoint.locationWithLatitude(CGFloat(location.latitude), longitude: CGFloat(location.longitude)) search!.AMapReGoecodeSearch(regeoRequest) } //发起逆地理编码 if hide { parentViewController.returnCurrentPositionButton.animation = "fadeOut" parentViewController.returnCurrentPositionButton.animate() hide = false self.userInteractionEnabled = true let info: AnyObject? = WeatherInfo.citiesAroundDict[cityID] var temp = Int(((info as! [String: AnyObject])["main"] as! [String: AnyObject])["temp"] as! Double) if WeatherInfo.forcastMode { temp = Int((((WeatherInfo.citiesForcast[cityID] as! [AnyObject])[self.parentViewController.clockButton.futureDay] as! [String: AnyObject])["temp"] as! [String: AnyObject])["day"] as! Double) currentIcon = ((((WeatherInfo.citiesForcast[cityID] as! [AnyObject])[self.parentViewController.clockButton.futureDay] as! [String: AnyObject])["weather"] as! [AnyObject])[0] as! [String : AnyObject])["icon"] as! String self.icon.image = UIImage(named: currentIcon)! }else{ currentIcon = (((info as! [String : AnyObject])["weather"] as! [AnyObject])[0] as! [String : AnyObject])["icon"] as! String self.icon.image = UIImage(named: currentIcon)! } self.temperature.text = "\(temp)°C / \(WeatherMapCalculations.degreeToF(temp))°F" if !UserLocation.inChina{ self.city.text = (info as! [String: AnyObject])["name"] as? String } if UserLocation.inChina{ self.weatherDescription.text = IconImage.getWeatherInChinese(currentIcon) }else{ self.weatherDescription.text = (((info as! [String: AnyObject])["weather"] as! [AnyObject])[0] as! [String: AnyObject])["main"]?.capitalizedString if WeatherInfo.forcastMode { self.weatherDescription.text = ((((WeatherInfo.citiesForcast[cityID] as! [AnyObject])[self.parentViewController.clockButton.futureDay] as! [String: AnyObject])["weather"] as! [AnyObject])[0] as! [String: AnyObject])["main"]?.capitalizedString } } weatherDescriptionBack.center = weatherDescriptionBackCenter weatherDescriptionBack.animation = "slideLeft" weatherDescriptionBack.animate() cityBack.center = cityBackCenter cityBack.animation = "slideUp" cityBack.animate() iconBack.center = iconBackCenter iconBack.animation = "slideRight" iconBack.animate() temperatureBack.center = temperatureBackCenter temperatureBack.animation = "slideLeft" temperatureBack.animate() }else{ iconBack.animation = "swing" iconBack.animate() UIView.animateWithDuration(0.4, animations: { () -> Void in self.icon.alpha = 0 self.temperature.alpha = 0 self.city.alpha = 0 self.weatherDescription.alpha = 0 }) { (done) -> Void in let info: AnyObject? = WeatherInfo.citiesAroundDict[cityID] var temp = Int(((info as! [String: AnyObject])["main"] as! [String: AnyObject])["temp"] as! Double) if WeatherInfo.forcastMode { temp = Int((((WeatherInfo.citiesForcast[cityID] as! [AnyObject])[self.parentViewController.clockButton.futureDay] as! [String: AnyObject])["temp"] as! [String: AnyObject])["day"] as! Double) } if WeatherInfo.forcastMode { self.currentIcon = ((((WeatherInfo.citiesForcast[cityID] as! [AnyObject])[self.parentViewController.clockButton.futureDay] as! [String: AnyObject])["weather"] as! [AnyObject])[0] as! [String : AnyObject])["icon"] as! String self.icon.image = UIImage(named: self.currentIcon)! self.temperature.text = "\(WeatherMapCalculations.kelvinConvert(temp, unit: TUnit.Celcius))°C / \(WeatherMapCalculations.kelvinConvert(temp, unit: TUnit.Fahrenheit))°F" }else{ self.currentIcon = (((info as! [String : AnyObject])["weather"] as! [AnyObject])[0] as! [String : AnyObject])["icon"] as! String self.icon.image = UIImage(named: self.currentIcon)! self.temperature.text = "\(temp)°C / \(WeatherMapCalculations.degreeToF(temp))°F" } if !UserLocation.inChina{ self.city.text = (info as! [String: AnyObject])["name"] as? String } if UserLocation.inChina{ self.weatherDescription.text = IconImage.getWeatherInChinese(self.currentIcon) }else{ self.weatherDescription.text = (((info as! [String: AnyObject])["weather"] as! [AnyObject])[0] as! [String: AnyObject])["main"]?.capitalizedString if WeatherInfo.forcastMode { self.weatherDescription.text = ((((WeatherInfo.citiesForcast[cityID] as! [AnyObject])[self.parentViewController.clockButton.futureDay] as! [String: AnyObject])["weather"] as! [AnyObject])[0] as! [String: AnyObject])["main"]?.capitalizedString } } UIView.animateWithDuration(0.4, animations: { () -> Void in self.icon.alpha = 1 self.temperature.alpha = 1 self.city.alpha = 1 self.weatherDescription.alpha = 1 }) { (done) -> Void in } } } } } func gotSmallImageFromCache(image: UIImage, cityID: String){ imageUrlReady = true if !hide{ if !smallImageEntered{ //not on screen yet smallImageEntered = true let theWidth = smallImageBack.frame.width let theHeight:CGFloat = image.size.height / image.size.width * theWidth smallImageBack.frame = CGRectMake(sideWidth + temperatureBack.frame.origin.x + temperatureBack.frame.width, weatherDescriptionBack.frame.origin.y - sideWidth - theHeight, theWidth, theHeight) (smallImageBack.subviews[0] as! UIView).frame = smallImageBack.bounds smallImageBack.animation = "slideLeft" smallImageBack.animate() smallImage.image = image smallImage.frame = CGRectMake(3, 3, smallImageBack.frame.width - 6, smallImageBack.frame.height - 6) }else{ let theWidth = smallImageBack.frame.width let theHeight:CGFloat = image.size.height / image.size.width * theWidth let theFrame = CGRectMake(sideWidth + temperatureBack.frame.origin.x + temperatureBack.frame.width, weatherDescriptionBack.frame.origin.y - sideWidth - theHeight, theWidth, theHeight) UIView.animateWithDuration(0.5, animations: { () -> Void in self.smallImageBack.frame = theFrame (self.smallImageBack.subviews[0] as! UIView).frame = self.smallImageBack.bounds self.smallImage.frame = CGRectMake(3, 3, self.smallImageBack.frame.width - 6, self.smallImageBack.frame.height - 6) }) UIView.animateWithDuration(0.25, animations: { () -> Void in self.smallImage.alpha = 0.3 }) { (finish) -> Void in self.smallImage.image = image UIView.animateWithDuration(0.25, animations: { () -> Void in self.smallImage.alpha = 0.6 }) } } } } func addVisualEffectView(view: UIView){ var effectView = UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffectStyle.Light)) effectView.frame = view.bounds view.addSubview(effectView) } func addShadow(view: UIView){ view.layer.shadowOffset = CGSizeMake(0, 1); view.layer.shadowRadius = 0.5; view.layer.shadowOpacity = 0.3; } func hideSelf(){ if !hide { parentViewController.returnCurrentPositionButton.animation = "fadeIn" parentViewController.returnCurrentPositionButton.animate() hide = true self.userInteractionEnabled = false weatherDescriptionBack.center = CGPointMake(weatherDescriptionBack.center.x + weatherDescriptionBack.frame.width * 1.5, weatherDescriptionBack.center.y) weatherDescriptionBack.animation = "slideLeft" weatherDescriptionBack.animate() cityBack.center = CGPointMake(cityBack.center.x, cityBack.center.y + cityBack.frame.height * 1.5) cityBack.animation = "slideUp" cityBack.animate() iconBack.center = CGPointMake(iconBack.center.x - iconBack.frame.width * 1.5 , iconBack.center.y) iconBack.animation = "slideRight" iconBack.animate() temperatureBack.center = CGPointMake(temperatureBack.center.x, temperatureBack.center.y + temperatureBack.frame.height * 3.5) temperatureBack.animation = "slideUp" temperatureBack.animate() smallImageBack.center = CGPointMake(smallImageBack.center.x + temperatureBack.frame.width * 1.5, smallImageBack.center.y) smallImageBack.animation = "slideLeft" smallImageBack.animate() smallImageEntered = false } } func removeAllViews(){ iconBack.removeFromSuperview() temperatureBack.removeFromSuperview() cityBack.removeFromSuperview() weatherDescriptionBack.removeFromSuperview() smallImageBack.removeFromSuperview() } }
apache-2.0
f45bc5cc9cacfff02b03e5f6d99500dd
49.554252
293
0.601137
4.936712
false
false
false
false
wikimedia/wikipedia-ios
Wikipedia/Code/EmptyViewController.swift
1
3948
import Foundation import WMF protocol EmptyViewControllerDelegate: AnyObject { func triggeredRefresh(refreshCompletion: @escaping () -> Void) func emptyViewScrollViewDidScroll(_ scrollView: UIScrollView) } class EmptyViewController: UIViewController { private let refreshControl = UIRefreshControl() @IBOutlet var scrollView: UIScrollView! @IBOutlet var emptyContainerView: UIView! private var emptyView: WMFEmptyView? = nil var canRefresh: Bool = false weak var delegate: EmptyViewControllerDelegate? var theme: Theme = .standard @IBOutlet var emptyContainerViewTopConstraint: NSLayoutConstraint! var type: WMFEmptyViewType? { didSet { if oldValue != type { emptyView?.removeFromSuperview() emptyView = nil if let newType = type, let emptyView = EmptyViewController.emptyView(of: newType, theme: self.theme, frame: .zero) { emptyView.delegate = self emptyContainerView.wmf_addSubviewWithConstraintsToEdges(emptyView) self.emptyView = emptyView apply(theme: theme) } } } } override func viewDidLoad() { super.viewDidLoad() scrollView.delegate = self scrollView.alwaysBounceVertical = true scrollView.contentInsetAdjustmentBehavior = .never if canRefresh { refreshControl.layer.zPosition = -100 refreshControl.addTarget(self, action: #selector(refreshControlActivated), for: .valueChanged) scrollView.addSubview(refreshControl) scrollView.refreshControl = refreshControl } apply(theme: theme) } @objc private func refreshControlActivated() { delegate?.triggeredRefresh(refreshCompletion: { [weak self] in self?.refreshControl.endRefreshing() }) } func centerEmptyView(topInset: CGFloat, topEmptyViewSpacing: CGFloat) { guard viewIfLoaded != nil else { return } scrollView.contentInset = UIEdgeInsets(top: topInset, left: 0, bottom: 0, right: 0) emptyContainerViewTopConstraint.constant = topEmptyViewSpacing } func centerEmptyView(within targetRect: CGRect) { scrollView.contentInset = UIEdgeInsets(top: targetRect.minY, left: 0, bottom: 0, right: 0) } private func determineTopOffset(emptyViewHeight: CGFloat) { let availableHeight = view.bounds.height - scrollView.contentInset.top let middle = availableHeight/2 let heightMiddle = emptyViewHeight / 2 let targetY = middle - heightMiddle emptyContainerViewTopConstraint.constant = max(0, ceil(targetY)) } } extension EmptyViewController: Themeable { func apply(theme: Theme) { self.theme = theme guard viewIfLoaded != nil else { return } if let emptyView = emptyView, let bgKeyPath = theme.value(forKeyPath: emptyView.backgroundColorKeyPath) as? UIColor { view.backgroundColor = bgKeyPath scrollView.backgroundColor = bgKeyPath (emptyView as Themeable).apply(theme: theme) } else { view.backgroundColor = theme.colors.paperBackground scrollView.backgroundColor = theme.colors.paperBackground } refreshControl.tintColor = theme.colors.refreshControlTint } } extension EmptyViewController: UIScrollViewDelegate { func scrollViewDidScroll(_ scrollView: UIScrollView) { delegate?.emptyViewScrollViewDidScroll(scrollView) } } extension EmptyViewController: WMFEmptyViewDelegate { func heightChanged(_ height: CGFloat) { determineTopOffset(emptyViewHeight: height) } }
mit
4cc58dd263123eed8569c3af7343292b
33.034483
113
0.640324
5.65616
false
false
false
false
mownier/photostream
Photostream/UI/Shared/PostListCollectionCell/PostListCollectionCell.swift
1
9050
// // PostListCollectionCell.swift // Photostream // // Created by Mounir Ybanez on 07/12/2016. // Copyright © 2016 Mounir Ybanez. All rights reserved. // import Spring protocol PostListCollectionCellDelegate: class { func didTapPhoto(cell: PostListCollectionCell) func didTapHeart(cell: PostListCollectionCell) func didTapComment(cell: PostListCollectionCell) func didTapCommentCount(cell: PostListCollectionCell) func didTapLikeCount(cell: PostListCollectionCell) } @objc protocol PostListCollectionCellAction: class { func didTapHeart() func didTapComment() func didTapPhoto() func didTapCommentCount() func didTapLikeCount() } class PostListCollectionCell: UICollectionViewCell { weak var delegate: PostListCollectionCellDelegate? var photoImageView: UIImageView! var heartButton: UIButton! var commentButton: UIButton! var stripView: UIView! var likeCountLabel: UILabel! var messageLabel: UILabel! var commentCountLabel: UILabel! var timeLabel: UILabel! override init(frame: CGRect) { super.init(frame: frame) initSetup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initSetup() } func initSetup() { photoImageView = UIImageView() photoImageView.contentMode = .scaleAspectFit photoImageView.clipsToBounds = true photoImageView.backgroundColor = UIColor.white photoImageView.isUserInteractionEnabled = true heartButton = UIButton() heartButton.addTarget(self, action: #selector(self.didTapHeart), for: .touchUpInside) heartButton.setImage(#imageLiteral(resourceName: "heart"), for: .normal) commentButton = UIButton() commentButton.addTarget(self, action: #selector(self.didTapComment), for: .touchUpInside) commentButton.setImage(#imageLiteral(resourceName: "comment"), for: .normal) stripView = UIView() stripView.backgroundColor = UIColor(red: 223/255, green: 223/255, blue: 223/255, alpha: 1) likeCountLabel = UILabel() likeCountLabel.numberOfLines = 0 likeCountLabel.font = UIFont.boldSystemFont(ofSize: 12) likeCountLabel.textColor = primaryColor likeCountLabel.isUserInteractionEnabled = true messageLabel = UILabel() messageLabel.numberOfLines = 0 messageLabel.font = UIFont.systemFont(ofSize: 12) messageLabel.textColor = primaryColor commentCountLabel = UILabel() commentCountLabel.numberOfLines = 0 commentCountLabel.font = UIFont.systemFont(ofSize: 12) commentCountLabel.textColor = secondaryColor commentCountLabel.isUserInteractionEnabled = true timeLabel = UILabel() timeLabel.numberOfLines = 0 timeLabel.font = UIFont.systemFont(ofSize: 8) timeLabel.textColor = secondaryColor var tap = UITapGestureRecognizer(target: self, action: #selector(self.didTapPhoto)) tap.numberOfTapsRequired = 2 photoImageView.addGestureRecognizer(tap) tap = UITapGestureRecognizer(target: self, action: #selector(self.didTapCommentCount)) tap.numberOfTapsRequired = 1 commentCountLabel.addGestureRecognizer(tap) tap = UITapGestureRecognizer(target: self, action: #selector(self.didTapLikeCount)) tap.numberOfTapsRequired = 1 likeCountLabel.addGestureRecognizer(tap) addSubview(photoImageView) addSubview(heartButton) addSubview(commentButton) addSubview(stripView) addSubview(likeCountLabel) addSubview(messageLabel) addSubview(commentCountLabel) addSubview(timeLabel) } override func layoutSubviews() { var rect = photoImageView.frame let ratio = bounds.width / rect.size.width rect.size.width = bounds.width rect.size.height = min(rect.size.width, rect.size.height * ratio) photoImageView.frame = rect rect.origin.x = spacing * 2 rect.origin.y = rect.size.height + (spacing * 2) rect.size = CGSize(width: buttonDimension, height: buttonDimension) heartButton.frame = rect rect.origin.x += rect.size.width + (spacing * 4) commentButton.frame = rect rect.origin.x = spacing * 2 rect.origin.y += (spacing * 2) rect.origin.y += rect.size.height rect.size.height = 1 rect.size.width = bounds.width - (spacing * 4) stripView.frame = rect if let text = likeCountLabel.text, !text.isEmpty { rect.origin.y += (spacing * 2) + rect.size.height rect.size.height = likeCountLabel.sizeThatFits(rect.size).height likeCountLabel.frame = rect } else { likeCountLabel.frame = .zero } if let text = messageLabel.text, !text.isEmpty { rect.origin.y += (spacing * 2) + rect.size.height rect.size.height = messageLabel.sizeThatFits(rect.size).height messageLabel.frame = rect } else { messageLabel.frame = .zero } if let text = commentCountLabel.text, !text.isEmpty { rect.origin.y += (spacing * 2) + rect.size.height rect.size.height = commentCountLabel.sizeThatFits(rect.size).height commentCountLabel.frame = rect } else { commentCountLabel.frame = .zero } rect.origin.y += (spacing * 2) + rect.size.height rect.size.height = timeLabel.sizeThatFits(rect.size).height timeLabel.frame = rect } } extension PostListCollectionCell: PostListCollectionCellAction { func didTapHeart() { delegate?.didTapHeart(cell: self) } func didTapComment() { delegate?.didTapComment(cell: self) } func didTapPhoto() { animateHeartButton { } showAnimatedHeart { self.delegate?.didTapPhoto(cell: self) } } func didTapCommentCount() { delegate?.didTapCommentCount(cell: self) } func didTapLikeCount() { delegate?.didTapLikeCount(cell: self) } } extension PostListCollectionCell { func showAnimatedHeart(completion: @escaping () -> Void) { let heart = SpringImageView(image: #imageLiteral(resourceName: "heart_pink")) heart.frame = CGRect(x: 0, y: 0, width: 48, height: 48) photoImageView.addSubviewAtCenter(heart) heart.autohide = true heart.autostart = false heart.animation = "pop" heart.duration = 1.0 heart.animateToNext { heart.animation = "fadeOut" heart.duration = 0.5 heart.animateToNext { heart.removeFromSuperview() completion() } } } func animateHeartButton(completion: @escaping () -> Void) { heartButton.isHidden = true let heart = SpringImageView(image: #imageLiteral(resourceName: "heart_pink")) heart.frame = heartButton.frame addSubview(heart) heart.autohide = true heart.autostart = false heart.animation = "pop" heart.duration = 1.0 heart.animateToNext { [weak self] in heart.removeFromSuperview() self?.heartButton.setImage(#imageLiteral(resourceName: "heart_pink"), for: .normal) self?.heartButton.isHidden = false completion() } } } extension PostListCollectionCell { func toggleHeart(liked: Bool, completion: @escaping() -> Void) { if liked { heartButton.setImage(#imageLiteral(resourceName: "heart"), for: .normal) completion() } else { animateHeartButton { } showAnimatedHeart { completion() } } } } extension PostListCollectionCell { var spacing: CGFloat { return 4 } var buttonDimension: CGFloat { return 24 } var secondaryColor: UIColor { return UIColor(red: 157/255, green: 157/255, blue: 157/255, alpha: 1) } var primaryColor: UIColor { return UIColor(red: 10/255, green: 10/255, blue: 10/255, alpha: 1) } } extension PostListCollectionCell { static var reuseId: String { return "PostListColllectionCell" } class func register(in view: UICollectionView) { view.register(self, forCellWithReuseIdentifier: self.reuseId) } class func dequeue(from view: UICollectionView, for indexPath: IndexPath) -> PostListCollectionCell? { let cell = view.dequeueReusableCell(withReuseIdentifier: self.reuseId, for: indexPath) return cell as? PostListCollectionCell } }
mit
28944acc22b3792dbefb94e8fcb71277
30.63986
106
0.624378
4.93941
false
false
false
false
MillmanY/MMTabBarAnimation
MMTabBarAnimation/Classes/AnimateItem.swift
1
4138
// // AnimateItem.swift // TabBarDemo // // Created by Millman YANG on 2016/12/17. // Copyright © 2016年 Millman YANG. All rights reserved. // import UIKit public enum AnimateType { case scale(rate:Float) case jump case rotation(type:RotationType) case shake case none } public enum ItemAnimateType { case content(type:AnimateType) case icon(type:AnimateType) case label(type:AnimateType) case iconExpand(image:UIImage) } class MMAnimateItem: NSObject { var label:UILabel? var badgeAnimateType:AnimateType = .none var animateType:ItemAnimateType = .content(type: .none) var duration:TimeInterval = 0.3 var badge:UIView? var imgAnimateLayer:ImageAnimateLayer = { let layer = ImageAnimateLayer() return layer }() var item:UITabBarItem? { didSet { self.observerBadge() } } var icon:UIImageView? { didSet { if let i = icon { imgAnimateLayer.frame = i.bounds } } } var tabBarView:UIView? { didSet { self.setItem() } } fileprivate func setItem() { if let contentImageClass = NSClassFromString("UITabBarSwappableImageView"), let contentLabelClass = NSClassFromString("UITabBarButtonLabel") { tabBarView?.subviews.forEach({ (view) in if let v = view as? UIImageView , view.isKind(of: contentImageClass) { icon = v icon?.layer.addSublayer(imgAnimateLayer) } else if let v = view as? UILabel, view.isKind(of: contentLabelClass) { label = v } else if let _ = NSClassFromString("_UIBadgeView") { badge = view } }) } } fileprivate func observerBadge() { if let barItem = self.item , barItem.observationInfo == nil{ barItem.addObserver(self, forKeyPath: "badgeValue", options: .new, context: nil) } } func animateBadge(type:AnimateType) { var delay = 0.0 if badge == nil { self.setItem() delay = 0.1 } DispatchQueue.main.asyncAfter(deadline: .now() + delay) { if let badge = self.badge { self.animateItem(item: badge, type: type) } } } func animate(isSelect:Bool) { self.imgAnimateLayer.selectImage = nil switch animateType { case .content(let type): if let view = tabBarView { self.animateItem(item: view, type: type) } case .icon(let type): if let i = icon { self.animateItem(item: i, type: type) } case .label(let type): if let l = label { self.animateItem(item: l, type: type) } case .iconExpand(let image): self.imgAnimateLayer.selectImage = image self.imgAnimateLayer.animate(show: isSelect, duration: duration) break } } fileprivate func animateItem(item:UIView,type:AnimateType) { item.animate.duration = duration switch type { case .scale(let rate): item.animate.scaleBounce(rate: rate) case .jump: item.animate.jumpY() case .rotation(let type): item.animate.rotation(type: type) case .shake: item.animate.shake() case .none: break } } } extension MMAnimateItem { override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if keyPath == "badgeValue" { self.animateBadge(type: badgeAnimateType) } else { super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context) } } }
mit
aefc9b4e79764f9d453fe883e9f2de8e
27.916084
151
0.540024
4.630459
false
false
false
false
dcunited001/Spectra
Example/Spectra/MetalViewController.swift
1
3306
// // File.swift // Spectra // // Created by David Conner on 10/3/15. // Copyright © 2015 CocoaPods. All rights reserved. // import Foundation import UIKit import MetalKit import Spectra class MetalViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() print("view loaded") } // @IBOutlet weak var spectraView: Spectra.BaseView! //TODO: weak? // var scene: Spectra.Scene? // var descMan: Spectra.SpectraDescriptorManager! // var stateMan: Spectra.SpectraStateManager! // // let cubeKey = "spectra_cube" // var pipelineStateMap: Spectra.RenderPipelineStateMap = [:] // var encodableDataMap: Spectra.SceneEncodableDataMap = [:] // // override func viewDidLoad() { // super.viewDidLoad() // stateMan = Spectra.SpectraStateManager() // loadDescriptorManager() // loadRenderPipelineStates() // // scene = Spectra.Scene() // setupPerspective() // setupSceneGraph() // setupNodeGeneratorMap() // setupNodeMap() // setupObjects() // setupScene() // } // // func loadDescriptorManager() { // let bundle = NSBundle(forClass: CubeViewController.self) // let xmlData: NSData = S3DXML.readXML(bundle, filename: "Spectra3D") // let xml = S3DXML(data: xmlData) // // descMan = Spectra.SpectraDescriptorManager(library: spectraView.defaultLibrary) // descMan = xml.parse(descMan) // } // // // add descriptorConfigBlock? // func loadRenderPipelineStates() { // let pipeGen = RenderPipelineGenerator(library: spectraView.defaultLibrary) // stateMan.renderPipelineStates = descMan.renderPipelineDescriptors.reduce(Spectra.RenderPipelineStateMap()) { (var hash, kv) in // let k = kv.0 // var desc = kv.1.copy() as! MTLRenderPipelineDescriptor // desc.colorAttachments[0].pixelFormat = .BGRA8Unorm // let state = pipeGen.generateFromDescriptor(spectraView.device!, pipelineStateDescriptor: desc) // hash[k] = state! // return hash // } // } // // func setupPerspective() { // //create encodable inputs for camera/etc // } // // func setupSceneGraph() { // let bundle = NSBundle(forClass: CubeViewController.self) // let path = bundle.pathForResource("Cube", ofType: "xml") // let data = NSData(contentsOfFile: path!) // let sceneGraph = SceneGraph(xmlData: data!) // scene!.sceneGraph = sceneGraph // } // // func setupNodeGeneratorMap() { // scene!.nodeGeneratorMap["cube"] = Spectra.CubeGenerator() // } // // func setupNodeMap() { // scene!.sceneGraph!.createGeneratedNodes(scene!.nodeGeneratorMap, nodeMap: scene!.nodeMap) // scene!.sceneGraph!.createRefNodes(scene!.nodeMap) // } // // func setupObjects() { // // parse Cube.XML // // let cubeXml = try! xml["root"]["mesh"].withAttr("id", cubeKey) // // setupCube(cubeKey, xml: cubeXml) // } // // func setupScene() { // scene!.pipelineStateMap = pipelineStateMap // // // renderer strategy // // updater strategy // } }
mit
5e94670206def638e26e7cc7c2061acd
31.087379
136
0.604539
3.870023
false
false
false
false
happylance/MacKey
MacKey/ViewControllers/UpgradeViewController.swift
1
7509
// // UpgradeViewController.swift // MacKey // // Created by Liu Liang on 19/02/2017. // Copyright © 2017 Liu Liang. All rights reserved. // import UIKit import RxSwift import RxCocoa import SwiftyStoreKit private let buttonCornerRadius: CGFloat = 5 extension ProductIdType { var productType: ProductType { if productId == Config.sleepModeProductID { return .sleepMode } else if productId == Config.skipTouchIDProductID { return .skipTouchID } return .unknown } } extension Purchase: ProductIdType {} extension PurchaseDetails: ProductIdType {} private extension ProductType { var productId: String { switch self { case .sleepMode: return Config.sleepModeProductID case .skipTouchID: return Config.skipTouchIDProductID case .unknown: return "" } } } enum PurchaseState { case purchased, cancelled } class UpgradeViewController: UIViewController{ @IBOutlet weak var activityIndicatorOutlet: UIActivityIndicatorView! @IBOutlet weak var cancelOutlet: UIBarButtonItem! @IBOutlet weak var productDetailsOutlet: UILabel! @IBOutlet weak var purchaseOutlet: UIButton! @IBOutlet weak var restorePurchaseOutlet: UIButton! private let disposeBag = DisposeBag() private let productType$ = Variable<ProductType>(.sleepMode) private let purchaseState$ = PublishSubject<PurchaseState>() func getPurchaseState$() -> Observable<PurchaseState> { return purchaseState$.asObservable() } override func viewDidLoad() { super.viewDidLoad() purchaseOutlet.layer.cornerRadius = buttonCornerRadius restorePurchaseOutlet.layer.cornerRadius = buttonCornerRadius cancelOutlet.rx.tap .subscribe(onNext: { [unowned self] _ in self.purchaseState$.onNext(.cancelled) self.purchaseState$.onCompleted() self.dismiss(animated: true, completion: nil) }) .disposed(by: disposeBag) productType$.asObservable() .map { $0.productId } .do(onNext: { [unowned self] _ in self.activityIndicatorOutlet.isHidden = false }) .flatMapLatest { UpgradeService.getProductInfo(by: $0) } .subscribe(onNext: { [unowned self] result in self.activityIndicatorOutlet.isHidden = true if let product = result.retrievedProducts.first { let priceString = product.localizedPrice! dlog("Product: \(product.localizedDescription), price: \(priceString)") self.productDetailsOutlet.isHidden = false self.productDetailsOutlet.text = product.localizedDescription self.purchaseOutlet.isHidden = false self.purchaseOutlet.setTitle(priceString, for: .normal) } else if let invalidProductId = result.invalidProductIDs.first { return self.alertWithTitle( "Could not retrieve product info", message: String(format:"Invalid product identifier: %@".localized(), invalidProductId)) } else { dlog("Error: \(String(describing: result.error))") if let error = result.error as NSError? { self.alertWithTitle("Error", message: error.localizedDescription) } } }) .disposed(by: disposeBag) purchaseOutlet.rx.tap .withLatestFrom(productType$.asObservable()) { $1.productId } .do(onNext: { [unowned self] _ in self.activityIndicatorOutlet.isHidden = false }) .flatMapLatest { UpgradeService.purchase(by: $0) } .subscribe(onNext: { [unowned self] result in self.activityIndicatorOutlet.isHidden = true switch result { case .success(let product): dlog("Purchase Success: \(product.productId)") store.dispatch(Upgrade(productType: product.productType)) self.purchaseState$.onNext(.purchased) self.purchaseState$.onCompleted() self.dismiss(animated: true, completion: nil) case .error(let error): dlog("Purchase Failed: \(error)") self.alertWithTitle("Purchase Failed", message: { switch(error.code) { case .storeProductNotAvailable: return String(format:"Store product not available") case .paymentNotAllowed: return "Payment not allowed" default: return error._nsError.localizedDescription } }()) } }) .disposed(by: disposeBag) restorePurchaseOutlet.rx.tap .do(onNext: { [unowned self] _ in self.activityIndicatorOutlet.isHidden = false }) .flatMapLatest {_ in UpgradeService.restorePurchase() } .withLatestFrom(productType$.asObservable()) { ($0, $1) } .subscribe(onNext: { [unowned self] (results, productType) in self.activityIndicatorOutlet.isHidden = true if results.restoreFailedPurchases.count > 0 { dlog("Restore Failed: \(results.restoreFailedPurchases)") let message = { () -> String in if let error = results.restoreFailedPurchases.first?.0._nsError { return error.localizedDescription } return "" }() self.alertWithTitle("Restore Unsuccessful", message: message) } else if results.restoredPurchases.count > 0 { dlog("Restore Success: \(results.restoredPurchases)") if (results.restoredPurchases.contains { $0.productId == productType.productId }) { store.dispatch(Upgrade(productType: productType)) self.purchaseState$.onNext(.purchased) self.purchaseState$.onCompleted() self.dismiss(animated: true, completion: nil) return } else { self.alertWithTitle("Restore Unsuccessful", message: "You purchased another product but not this one") return } } else { dlog("Nothing to Restore") self.alertWithTitle("Restore Unsuccessful", message: "Nothing to restore") } }) .disposed(by: disposeBag) } func setProductType(_ type: ProductType) { productType$.value = type } private func alertWithTitle(_ title: String, message: String) { let alertView = UIAlertController(title: title.localized(), message: message.localized(), preferredStyle: .alert) alertView.addAction(UIAlertAction(title: "OK".localized(), style: .cancel) { _ in }) self.present(alertView, animated: true, completion: nil) } }
mit
5a2be3334a488e317744dfe1f767a2e5
40.944134
126
0.563532
5.520588
false
false
false
false
joshua-d-miller/macOSLAPS
macOSLAPS/Extensions/TimeConversion.swift
1
821
/// /// TimeConversion.swift /// macOSLAPS /// /// Created by Joshua D. Miller on 6/13/17. /// /// import Foundation class TimeConversion: NSObject { // Windows to Epoch time converter and vice versa class func epoch(exp_time: String) -> Date? { let converted_time = Double((Int(exp_time)! / 10000000 - 11644473600)) let pw_expires_date = Date(timeIntervalSince1970: converted_time) return(pw_expires_date) } class func windows() -> String? { let new_expiration_time = Calendar.current.date(byAdding: .day, value: Constants.days_till_expiration, to: Date())! let new_conv_time = Int(new_expiration_time.timeIntervalSince1970) let new_ad_expiration_time = String((new_conv_time + 11644473600) * 10000000) return(new_ad_expiration_time) } }
mit
1175f56b80dae99a6877f73a10f849f7
31.84
123
0.660171
3.766055
false
false
false
false
square/Valet
Scripts/build.swift
1
6750
#!/usr/bin/env swift import Foundation // Usage: build.swift platforms [spm|xcode] func execute(commandPath: String, arguments: [String]) throws { let task = Process() task.launchPath = commandPath task.arguments = arguments print("Launching command: \(commandPath) \(arguments.joined(separator: " "))") task.launch() task.waitUntilExit() guard task.terminationStatus == 0 else { throw TaskError.code(task.terminationStatus) } } enum TaskError: Error { case code(Int32) } enum Platform: String, CustomStringConvertible { case iOS_13 case iOS_14 case iOS_15 case tvOS_13 case tvOS_14 case tvOS_15 case macOS_10_15 case macOS_11 case macOS_12 case watchOS_6 case watchOS_7 case watchOS_8 var destination: String { switch self { case .iOS_13: return "platform=iOS Simulator,OS=13.7,name=iPad Pro (12.9-inch) (4th generation)" case .iOS_14: return "platform=iOS Simulator,OS=14.4,name=iPad Pro (12.9-inch) (4th generation)" case .iOS_15: return "platform=iOS Simulator,OS=15.5,name=iPad Pro (12.9-inch) (5th generation)" case .tvOS_13: return "platform=tvOS Simulator,OS=13.4,name=Apple TV" case .tvOS_14: return "platform=tvOS Simulator,OS=14.3,name=Apple TV" case .tvOS_15: return "platform=tvOS Simulator,OS=15.4,name=Apple TV" case .macOS_10_15, .macOS_11, .macOS_12: return "platform=OS X" case .watchOS_6: return "OS=6.2.1,name=Apple Watch Series 4 - 44mm" case .watchOS_7: return "OS=7.2,name=Apple Watch Series 6 - 44mm" case .watchOS_8: return "OS=8.5,name=Apple Watch Series 6 - 44mm" } } var sdk: String { switch self { case .iOS_13, .iOS_14, .iOS_15: return "iphonesimulator" case .tvOS_13, .tvOS_14, .tvOS_15: return "appletvsimulator" case .macOS_10_15: return "macosx10.15" case .macOS_11: return "macosx11.1" case .macOS_12: return "macosx12.3" case .watchOS_6, .watchOS_7, .watchOS_8: return "watchsimulator" } } var shouldTest: Bool { switch self { case .iOS_13, .iOS_14, .iOS_15, .tvOS_13, .tvOS_14, .tvOS_15, .macOS_10_15, .macOS_11, .macOS_12: return true case .watchOS_6, .watchOS_7, .watchOS_8: // watchOS does not support unit testing (yet?). return false } } var derivedDataPath: String { ".build/derivedData/" + description } var scheme: String { switch self { case .iOS_13, .iOS_14, .iOS_15: return "Valet iOS" case .tvOS_13, .tvOS_14, .tvOS_15: return "Valet tvOS" case .macOS_10_15, .macOS_11, .macOS_12: return "Valet Mac" case .watchOS_6, .watchOS_7, .watchOS_8: return "Valet watchOS" } } var description: String { rawValue } } enum Task: String, CustomStringConvertible { case spm case xcode var description: String { rawValue } var project: String { switch self { case .spm: return "generated/Valet.xcodeproj" case .xcode: return "Valet.xcodeproj" } } var shouldGenerateXcodeProject: Bool { switch self { case .spm: return true case .xcode: return false } } var shouldUseLegacyBuildSystem: Bool { switch self { case .spm: return false case .xcode: // The new build system choked on our XCTest framework. // Once this project compiles with the new build system, // we can change this to false. return true } } var configuration: String { switch self { case .spm: return "Release" case .xcode: return "Debug" } } func scheme(for platform: Platform) -> String { switch self { case .spm: return "Valet-Package" case .xcode: return platform.scheme } } func shouldTest(on platform: Platform) -> Bool { switch self { case .spm: // Our Package isn't set up with unit test targets, becuase SPM can't run unit tests in a codesigned environment. return false case .xcode: return platform.shouldTest } } } guard CommandLine.arguments.count > 2 else { print("Usage: build.swift platforms [spm|xcode]") throw TaskError.code(1) } let rawPlatforms = CommandLine.arguments[1].components(separatedBy: ",") let rawTask = CommandLine.arguments[2] guard let task = Task(rawValue: rawTask) else { print("Received unknown task \(rawTask)") throw TaskError.code(1) } if task.shouldGenerateXcodeProject { try execute(commandPath: "/usr/bin/xcrun", arguments: ["/usr/bin/swift", "package", "generate-xcodeproj", "--output=generated/"]) } for rawPlatform in rawPlatforms { guard let platform = Platform(rawValue: rawPlatform) else { print("Received unknown platform type \(rawPlatform)") throw TaskError.code(1) } var xcodeBuildArguments = [ "-project", task.project, "-scheme", task.scheme(for: platform), "-sdk", platform.sdk, "-configuration", task.configuration, "-PBXBuildsContinueAfterErrors=0", ] if !platform.destination.isEmpty { xcodeBuildArguments.append("-destination") xcodeBuildArguments.append(platform.destination) } if task.shouldUseLegacyBuildSystem { xcodeBuildArguments.append("-UseModernBuildSystem=0") } let shouldTest = task.shouldTest(on: platform) if shouldTest { xcodeBuildArguments.append("-enableCodeCoverage") xcodeBuildArguments.append("YES") xcodeBuildArguments.append("-derivedDataPath") xcodeBuildArguments.append(platform.derivedDataPath) } xcodeBuildArguments.append("build") if shouldTest { xcodeBuildArguments.append("test") } try execute(commandPath: "/usr/bin/xcodebuild", arguments: xcodeBuildArguments) }
apache-2.0
c05aa4bc7b7041483cf09946fdfb34f3
24.665399
133
0.558667
4.192547
false
false
false
false
DSanzh/GuideMe-iOS
GuideMe/Controller/MainTabBarVC.swift
1
1984
// // MainTabBarVC.swift // GuideMe // // Created by Sanzhar on 7/29/17. // Copyright © 2017 Sanzhar Dauylov. All rights reserved. // import UIKit import Sugar struct TabBar { var icon: UIImage? var name: String? var controller: UIViewController } final class MainTabBarVC: UITabBarController { override func viewDidLoad() { super.viewDidLoad() setupTabBar() } // SETUP TABBARController func setupTabBar() { let tabBarItems = [ TabBar(icon: UIImage(named: "Map"), name: "Места", controller: UINavigationController(rootViewController: PlaceVC())), TabBar(icon: UIImage(named: "Hiking"), name: "Туры", controller: UINavigationController(rootViewController: TourVC())), TabBar(icon: UIImage(named: "Shop"), name: "Продукты", controller: UINavigationController(rootViewController: ProductsVC())), TabBar(icon: UIImage(named: "Profile"), name: "Профиль", controller: UINavigationController(rootViewController: ProfileVC())) ] viewControllers = tabBarItems.flatMap { $0.controller.then{ _ in } } tabBar.isTranslucent = false tabBar.barTintColor = .white tabBar.shadowImage = UIImage() tabBar.tintColor = ColorConstants.tabBarActive tabBar.backgroundImage = UIImage() tabBar.layer.shadowOffset = CGSize(width: 0, height: 0) tabBar.layer.shadowRadius = 8 tabBar.layer.shadowColor = UIColor.black.cgColor tabBar.layer.shadowOpacity = 0.1 for (index, item) in tabBarItems.enumerated() { setUpTabBarItem(tabBar.items?[index], image: item.icon, title: item.name) } } func setUpTabBarItem(_ tabBarItem: UITabBarItem?, image: UIImage?, title: String?) { tabBarItem?.image = image tabBarItem?.title = title } }
mit
de35bd02c44f783b0f4ce8368fc165e4
32.775862
137
0.622767
4.675418
false
false
false
false
rechsteiner/Parchment
Parchment/Classes/PagingCollectionViewLayout.swift
1
22398
import UIKit /// A custom `UICollectionViewLayout` subclass responsible for /// defining the layout for all the `PagingItem` cells. You can /// subclass this type if you need further customization outside what /// is provided by customization properties on `PagingViewController`. /// /// To create your own `PagingViewControllerLayout` you need to /// override the `menuLayoutClass` property on `PagingViewController`. /// Then you can override the methods you normally would to update the /// layout attributes for each cell. /// /// The layout has two decoration views; one for the border at the /// bottom and one for the view that indicates the currently selected /// `PagingItem`. You can customize their layout attributes by /// updating the `indicatorLayoutAttributes` and /// `borderLayoutAttributes` properties. open class PagingCollectionViewLayout: UICollectionViewLayout, PagingLayout { // MARK: Public Properties /// An instance that stores all the customization that is applied /// to the `PagingViewController`. public var options = PagingOptions() { didSet { optionsChanged(oldValue: oldValue) } } /// The current state of the menu items. Indicates whether an item /// is currently selected or is scrolling to another item. Can be /// used to get the distance and progress of any ongoing transition. public var state: PagingState = .empty /// The `PagingItem`'s that are currently visible in the collection /// view. The items in this array are not necessarily the same as /// the `visibleCells` property on `UICollectionView`. public var visibleItems = PagingItems(items: []) /// A dictionary containing all the layout attributes for a given /// `IndexPath`. This will be generated in the `prepare()` call when /// the layout is invalidated with the correct invalidation context. public private(set) var layoutAttributes: [IndexPath: PagingCellLayoutAttributes] = [:] /// The layout attributes for the selected item indicator. This is /// updated whenever the layout is invalidated. public private(set) var indicatorLayoutAttributes: PagingIndicatorLayoutAttributes? /// The layout attributes for the bottom border view. This is /// updated whenever the layout is invalidated. public private(set) var borderLayoutAttributes: PagingBorderLayoutAttributes? /// The `InvalidatedState` is used to represent what to invalidate /// in a collection view layout based on the invalidation context. public var invalidationState: InvalidationState = .everything open override var collectionViewContentSize: CGSize { return contentSize } open override class var layoutAttributesClass: AnyClass { return PagingCellLayoutAttributes.self } open override var flipsHorizontallyInOppositeLayoutDirection: Bool { return true } // MARK: Initializers public required override init() { super.init() configure() } public required init?(coder: NSCoder) { super.init(coder: coder) configure() } // MARK: Internal Properties internal var sizeCache: PagingSizeCache? // MARK: Private Properties private var view: UICollectionView { return collectionView! } private var range: Range<Int> { return 0 ..< view.numberOfItems(inSection: 0) } private var adjustedMenuInsets: UIEdgeInsets { return UIEdgeInsets( top: options.menuInsets.top, left: options.menuInsets.left + safeAreaInsets.left, bottom: options.menuInsets.bottom, right: options.menuInsets.right + safeAreaInsets.right ) } private var safeAreaInsets: UIEdgeInsets { if options.includeSafeAreaInsets, #available(iOS 11.0, *) { return view.safeAreaInsets } else { return .zero } } /// Cache used to store the preferred item size for each self-sizing /// cell. PagingItem identifier is used as the key. private var preferredSizeCache: [Int: CGFloat] = [:] private(set) var contentInsets: UIEdgeInsets = .zero private var contentSize: CGSize = .zero private let PagingIndicatorKind = "PagingIndicatorKind" private let PagingBorderKind = "PagingBorderKind" // MARK: Public Methods open override func prepare() { super.prepare() switch invalidationState { case .everything: layoutAttributes = [:] borderLayoutAttributes = nil indicatorLayoutAttributes = nil createLayoutAttributes() createDecorationLayoutAttributes() case .sizes: layoutAttributes = [:] createLayoutAttributes() case .nothing: break } updateBorderLayoutAttributes() updateIndicatorLayoutAttributes() invalidationState = .nothing } open override func invalidateLayout() { super.invalidateLayout() invalidationState = .everything } open override func invalidateLayout(with context: UICollectionViewLayoutInvalidationContext) { super.invalidateLayout(with: context) invalidationState = invalidationState + InvalidationState(context) } open override func invalidationContext(forPreferredLayoutAttributes _: UICollectionViewLayoutAttributes, withOriginalAttributes _: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutInvalidationContext { let context = PagingInvalidationContext() context.invalidateSizes = true return context } open override func shouldInvalidateLayout(forPreferredLayoutAttributes preferredAttributes: UICollectionViewLayoutAttributes, withOriginalAttributes originalAttributes: UICollectionViewLayoutAttributes) -> Bool { switch options.menuItemSize { // Invalidate the layout and update the layout attributes with the // preferred width for each cell. The preferred size is based on // the layout constraints in each cell. case .selfSizing where originalAttributes is PagingCellLayoutAttributes: if preferredAttributes.frame.width != originalAttributes.frame.width { let pagingItem = visibleItems.pagingItem(for: originalAttributes.indexPath) preferredSizeCache[pagingItem.identifier] = preferredAttributes.frame.width return true } return false default: return false } } open override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { guard let layoutAttributes = self.layoutAttributes[indexPath] else { return nil } layoutAttributes.progress = progressForItem(at: layoutAttributes.indexPath) return layoutAttributes } open override func layoutAttributesForDecorationView(ofKind elementKind: String, at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { switch elementKind { case PagingIndicatorKind: return indicatorLayoutAttributes case PagingBorderKind: return borderLayoutAttributes default: return super.layoutAttributesForDecorationView(ofKind: elementKind, at: indexPath) } } open override func layoutAttributesForElements(in _: CGRect) -> [UICollectionViewLayoutAttributes]? { var layoutAttributes: [UICollectionViewLayoutAttributes] = Array(self.layoutAttributes.values) for attributes in layoutAttributes { if let pagingAttributes = attributes as? PagingCellLayoutAttributes { pagingAttributes.progress = progressForItem(at: attributes.indexPath) } } let indicatorAttributes = layoutAttributesForDecorationView( ofKind: PagingIndicatorKind, at: IndexPath(item: 0, section: 0) ) let borderAttributes = layoutAttributesForDecorationView( ofKind: PagingBorderKind, at: IndexPath(item: 1, section: 0) ) if let indicatorAttributes = indicatorAttributes { layoutAttributes.append(indicatorAttributes) } if let borderAttributes = borderAttributes { layoutAttributes.append(borderAttributes) } return layoutAttributes } // MARK: Private Methods private func optionsChanged(oldValue: PagingOptions) { var shouldInvalidateLayout: Bool = false if options.borderClass != oldValue.borderClass { registerBorderClass() shouldInvalidateLayout = true } if options.indicatorClass != oldValue.indicatorClass { registerIndicatorClass() shouldInvalidateLayout = true } if options.borderColor != oldValue.borderColor { shouldInvalidateLayout = true } if options.indicatorColor != oldValue.indicatorColor { shouldInvalidateLayout = true } if shouldInvalidateLayout { invalidateLayout() } } private func configure() { registerBorderClass() registerIndicatorClass() } private func registerIndicatorClass() { register(options.indicatorClass, forDecorationViewOfKind: PagingIndicatorKind) } private func registerBorderClass() { register(options.borderClass, forDecorationViewOfKind: PagingBorderKind) } private func createLayoutAttributes() { guard let sizeCache = sizeCache else { return } var layoutAttributes: [IndexPath: PagingCellLayoutAttributes] = [:] var previousFrame: CGRect = .zero previousFrame.origin.x = adjustedMenuInsets.left - options.menuItemSpacing for index in 0 ..< view.numberOfItems(inSection: 0) { let indexPath = IndexPath(item: index, section: 0) let attributes = PagingCellLayoutAttributes(forCellWith: indexPath) let x = previousFrame.maxX + options.menuItemSpacing let y = adjustedMenuInsets.top let pagingItem = visibleItems.pagingItem(for: indexPath) if sizeCache.implementsSizeDelegate { var width = sizeCache.itemSize(for: pagingItem) let selectedWidth = sizeCache.itemWidthSelected(for: pagingItem) if let currentPagingItem = state.currentPagingItem, currentPagingItem.isEqual(to: pagingItem) { width = tween(from: selectedWidth, to: width, progress: abs(state.progress)) } else if let upcomingPagingItem = state.upcomingPagingItem, upcomingPagingItem.isEqual(to: pagingItem) { width = tween(from: width, to: selectedWidth, progress: abs(state.progress)) } attributes.frame = CGRect(x: x, y: y, width: width, height: options.menuItemSize.height) } else { switch options.menuItemSize { case let .fixed(width, height): attributes.frame = CGRect(x: x, y: y, width: width, height: height) case let .sizeToFit(minWidth, height): attributes.frame = CGRect(x: x, y: y, width: minWidth, height: height) case let .selfSizing(estimatedWidth, height): if let actualWidth = preferredSizeCache[pagingItem.identifier] { attributes.frame = CGRect(x: x, y: y, width: actualWidth, height: height) } else { attributes.frame = CGRect(x: x, y: y, width: estimatedWidth, height: height) } } } previousFrame = attributes.frame layoutAttributes[indexPath] = attributes } // When the menu items all can fit inside the bounds we need to // reposition the items based on the current options if previousFrame.maxX - adjustedMenuInsets.left < view.bounds.width { switch options.menuItemSize { case let .sizeToFit(_, height) where sizeCache.implementsSizeDelegate == false: let insets = adjustedMenuInsets.left + adjustedMenuInsets.right let spacing = (options.menuItemSpacing * CGFloat(range.upperBound - 1)) let width = (view.bounds.width - insets - spacing) / CGFloat(range.upperBound) previousFrame = .zero previousFrame.origin.x = adjustedMenuInsets.left - options.menuItemSpacing for attributes in layoutAttributes.values.sorted(by: { $0.indexPath < $1.indexPath }) { let x = previousFrame.maxX + options.menuItemSpacing let y = adjustedMenuInsets.top attributes.frame = CGRect(x: x, y: y, width: width, height: height) previousFrame = attributes.frame } // When using sizeToFit the content will always be as wide as // the bounds so there is not possible to center the items. In // all the other cases we want to center them if the menu // alignment is set to .center default: if case .center = options.menuHorizontalAlignment { // Subtract the menu insets as they should not have an effect on // whether or not we should center the items. let offset = (view.bounds.width - previousFrame.maxX - adjustedMenuInsets.left) / 2 for attributes in layoutAttributes.values { attributes.frame = attributes.frame.offsetBy(dx: offset, dy: 0) } } } } if case .center = options.selectedScrollPosition { let attributes = layoutAttributes.values.sorted(by: { $0.indexPath < $1.indexPath }) if let first = attributes.first, let last = attributes.last { let insetLeft = (view.bounds.width / 2) - (first.bounds.width / 2) let insetRight = (view.bounds.width / 2) - (last.bounds.width / 2) for attributes in layoutAttributes.values { attributes.frame = attributes.frame.offsetBy(dx: insetLeft, dy: 0) } contentInsets = UIEdgeInsets( top: 0, left: insetLeft + adjustedMenuInsets.left, bottom: 0, right: insetRight + adjustedMenuInsets.right ) contentSize = CGSize( width: previousFrame.maxX + insetLeft + insetRight + adjustedMenuInsets.right, height: view.bounds.height ) } } else { contentInsets = adjustedMenuInsets contentSize = CGSize( width: previousFrame.maxX + adjustedMenuInsets.right, height: view.bounds.height ) } self.layoutAttributes = layoutAttributes } private func createDecorationLayoutAttributes() { if case .visible = options.indicatorOptions { indicatorLayoutAttributes = PagingIndicatorLayoutAttributes( forDecorationViewOfKind: PagingIndicatorKind, with: IndexPath(item: 0, section: 0) ) } if case .visible = options.borderOptions { borderLayoutAttributes = PagingBorderLayoutAttributes( forDecorationViewOfKind: PagingBorderKind, with: IndexPath(item: 1, section: 0) ) } } private func updateBorderLayoutAttributes() { borderLayoutAttributes?.configure(options) borderLayoutAttributes?.update( contentSize: collectionViewContentSize, bounds: collectionView?.bounds ?? .zero, safeAreaInsets: safeAreaInsets ) } private func updateIndicatorLayoutAttributes() { guard let currentPagingItem = state.currentPagingItem else { return } indicatorLayoutAttributes?.configure(options) let currentIndexPath = visibleItems.indexPath(for: currentPagingItem) let upcomingIndexPath = upcomingIndexPathForIndexPath(currentIndexPath) if let upcomingIndexPath = upcomingIndexPath { let progress = abs(state.progress) let to = PagingIndicatorMetric( frame: indicatorFrameForIndex(upcomingIndexPath.item), insets: indicatorInsetsForIndex(upcomingIndexPath.item), spacing: indicatorSpacingForIndex(upcomingIndexPath.item) ) if let currentIndexPath = currentIndexPath { let from = PagingIndicatorMetric( frame: indicatorFrameForIndex(currentIndexPath.item), insets: indicatorInsetsForIndex(currentIndexPath.item), spacing: indicatorSpacingForIndex(currentIndexPath.item) ) indicatorLayoutAttributes?.update(from: from, to: to, progress: progress) } else if let from = indicatorMetricForFirstItem() { indicatorLayoutAttributes?.update(from: from, to: to, progress: progress) } else if let from = indicatorMetricForLastItem() { indicatorLayoutAttributes?.update(from: from, to: to, progress: progress) } } else if let metric = indicatorMetricForFirstItem() { indicatorLayoutAttributes?.update(to: metric) } else if let metric = indicatorMetricForLastItem() { indicatorLayoutAttributes?.update(to: metric) } } private func indicatorMetricForFirstItem() -> PagingIndicatorMetric? { guard let currentPagingItem = state.currentPagingItem else { return nil } if let first = visibleItems.items.first { if currentPagingItem.isBefore(item: first) { return PagingIndicatorMetric( frame: indicatorFrameForIndex(-1), insets: indicatorInsetsForIndex(-1), spacing: indicatorSpacingForIndex(-1) ) } } return nil } private func indicatorMetricForLastItem() -> PagingIndicatorMetric? { guard let currentPagingItem = state.currentPagingItem else { return nil } if let last = visibleItems.items.last { if last.isBefore(item: currentPagingItem) { return PagingIndicatorMetric( frame: indicatorFrameForIndex(visibleItems.items.count), insets: indicatorInsetsForIndex(visibleItems.items.count), spacing: indicatorSpacingForIndex(visibleItems.items.count) ) } } return nil } private func progressForItem(at indexPath: IndexPath) -> CGFloat { guard let currentPagingItem = state.currentPagingItem else { return 0 } let currentIndexPath = visibleItems.indexPath(for: currentPagingItem) if let currentIndexPath = currentIndexPath { if indexPath.item == currentIndexPath.item { return 1 - abs(state.progress) } } if let upcomingIndexPath = upcomingIndexPathForIndexPath(currentIndexPath) { if indexPath.item == upcomingIndexPath.item { return abs(state.progress) } } return 0 } private func upcomingIndexPathForIndexPath(_ indexPath: IndexPath?) -> IndexPath? { if let upcomingPagingItem = state.upcomingPagingItem, let upcomingIndexPath = visibleItems.indexPath(for: upcomingPagingItem) { return upcomingIndexPath } else if let indexPath = indexPath { if indexPath.item == range.lowerBound { return IndexPath(item: indexPath.item - 1, section: 0) } else if indexPath.item == range.upperBound - 1 { return IndexPath(item: indexPath.item + 1, section: 0) } } return indexPath } private func indicatorSpacingForIndex(_: Int) -> UIEdgeInsets { if case let .visible(_, _, insets, _) = options.indicatorOptions { return insets } return UIEdgeInsets.zero } private func indicatorInsetsForIndex(_ index: Int) -> PagingIndicatorMetric.Inset { if case let .visible(_, _, _, insets) = options.indicatorOptions { if index == 0, range.upperBound == 1 { return .both(insets.left, insets.right) } else if index == range.lowerBound { return .left(insets.left) } else if index >= range.upperBound - 1 { return .right(insets.right) } } return .none } private func indicatorFrameForIndex(_ index: Int) -> CGRect { if index < range.lowerBound { let frame = frameForIndex(0) return frame.offsetBy(dx: -frame.width, dy: 0) } else if index > range.upperBound - 1 { let frame = frameForIndex(visibleItems.items.count - 1) return frame.offsetBy(dx: frame.width, dy: 0) } return frameForIndex(index) } private func frameForIndex(_ index: Int) -> CGRect { guard let sizeCache = sizeCache, let attributes = layoutAttributes[IndexPath(item: index, section: 0)] else { return .zero } var frame = CGRect( x: attributes.center.x - attributes.bounds.midX, y: attributes.center.y - attributes.bounds.midY, width: attributes.bounds.width, height: attributes.bounds.height ) if sizeCache.implementsSizeDelegate { let indexPath = IndexPath(item: index, section: 0) let pagingItem = visibleItems.pagingItem(for: indexPath) if let upcomingPagingItem = state.upcomingPagingItem, let currentPagingItem = state.currentPagingItem { if upcomingPagingItem.isEqual(to: pagingItem) || currentPagingItem.isEqual(to: pagingItem) { frame.size.width = sizeCache.itemWidthSelected(for: pagingItem) } } } return frame } }
mit
8b317e9044582fa3d5f4de989c6e7058
39.284173
216
0.634208
5.489706
false
false
false
false
wireapp/wire-ios
Wire-iOS/Sources/UserInterface/ConversationList/ZMConversation+Status.swift
1
29966
// // Wire // Copyright (C) 2017 Wire Swiss GmbH // // 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 License, or // (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 Foundation import WireDataModel import WireSyncEngine import WireCommonComponents // Describes the icon to be shown for the conversation in the list. enum ConversationStatusIcon: Equatable { case pendingConnection case typing case unreadMessages(count: Int) case unreadPing case missedCall case mention case reply case silenced case playingMedia case activeCall(showJoin: Bool) } // Describes the status of the conversation. struct ConversationStatus { let isGroup: Bool let hasMessages: Bool let hasUnsentMessages: Bool let messagesRequiringAttention: [ZMConversationMessage] let messagesRequiringAttentionByType: [StatusMessageType: UInt] let isTyping: Bool let mutedMessageTypes: MutedMessageTypes let isOngoingCall: Bool let isBlocked: Bool let isSelfAnActiveMember: Bool let hasSelfMention: Bool let hasSelfReply: Bool } // Describes the conversation message. enum StatusMessageType: Int, CaseIterable { case mention case reply case missedCall case knock case text case link case image case location case audio case video case file case addParticipants case removeParticipants case newConversation private var localizationSilencedRootPath: String { return "conversation.silenced.status.message" } private var localizationKeySuffix: String? { switch self { case .mention: return "mention" case .reply: return "reply" case .missedCall: return "missedcall" case .knock: return "knock" case .text: return "generic_message" default: return nil } } var localizationKey: String? { guard let localizationKey = localizationKeySuffix else { return nil } return (localizationSilencedRootPath + "." + localizationKey) } func localizedString(with count: UInt) -> String? { guard let localizationKey = localizationKey else { return nil } return String(format: localizationKey.localized, count) } } extension StatusMessageType { /// Types of statuses that can be included in a status summary. static let summaryTypes: [StatusMessageType] = [.mention, .reply, .missedCall, .knock, .text, .link, .image, .location, .audio, .video, .file] var parentSummaryType: StatusMessageType? { switch self { case .link, .image, .location, .audio, .video, .file: return .text default: return nil } } private static let conversationSystemMessageTypeToStatusMessageType: [ZMSystemMessageType: StatusMessageType] = [ .participantsAdded: .addParticipants, .participantsRemoved: .removeParticipants, .missedCall: .missedCall, .newConversation: .newConversation ] init?(message: ZMConversationMessage) { if message.isText, let textMessage = message.textMessageData { if textMessage.isMentioningSelf { self = .mention } else if textMessage.isQuotingSelf { self = .reply } else if textMessage.linkPreview != nil { self = .link } else { self = .text } } else if message.isImage { self = .image } else if message.isLocation { self = .location } else if message.isAudio { self = .audio } else if message.isVideo { self = .video } else if message.isFile { self = .file } else if message.isKnock { self = .knock } else if message.isSystem, let system = message.systemMessageData { if let statusMessageType = StatusMessageType.conversationSystemMessageTypeToStatusMessageType[system.systemMessageType] { self = statusMessageType } else { return nil } } else { return nil } } } // Describes object that is able to match and describe the conversation. // Provides rich description and status icon. protocol ConversationStatusMatcher { func isMatching(with status: ConversationStatus) -> Bool func description(with status: ConversationStatus, conversation: MatcherConversation) -> NSAttributedString? func icon(with status: ConversationStatus, conversation: MatcherConversation) -> ConversationStatusIcon? // An array of matchers that are compatible with the current one. Leads to display the description of all matching // in one row, like "description1 | description2" var combinesWith: [ConversationStatusMatcher] { get } } protocol TypedConversationStatusMatcher: ConversationStatusMatcher { var matchedTypes: [StatusMessageType] { get } } extension TypedConversationStatusMatcher { func isMatching(with status: ConversationStatus) -> Bool { let matches: [UInt] = matchedTypes.compactMap { status.messagesRequiringAttentionByType[$0] } return matches.reduce(0, +) > 0 } } extension ConversationStatusMatcher { func icon(with status: ConversationStatus, conversation: MatcherConversation) -> ConversationStatusIcon? { return nil } func addEmphasis(to string: NSAttributedString, for substring: String) -> NSAttributedString { return string.setAttributes(type(of: self).emphasisStyle, toSubstring: substring) } } final class ContentSizeCategoryUpdater { private let callback: () -> Void private var observer: NSObjectProtocol! deinit { if let observer = observer { NotificationCenter.default.removeObserver(observer) } } init(callback: @escaping () -> Void) { self.callback = callback callback() self.observer = NotificationCenter.default.addObserver(forName: UIContentSizeCategory.didChangeNotification, object: nil, queue: nil) { [weak self] _ in self?.callback() } } } final class ConversationStatusStyle { private(set) var regularStyle: [NSAttributedString.Key: AnyObject] = [:] private(set) var emphasisStyle: [NSAttributedString.Key: AnyObject] = [:] private var contentSizeStyleUpdater: ContentSizeCategoryUpdater! init() { contentSizeStyleUpdater = ContentSizeCategoryUpdater { [weak self] in guard let `self` = self else { return } self.regularStyle = [.font: FontSpec(.medium, .none).font!, .foregroundColor: UIColor(white: 1.0, alpha: 0.64)] self.emphasisStyle = [.font: FontSpec(.medium, .medium).font!, .foregroundColor: UIColor(white: 1.0, alpha: 0.64)] } } } private let statusStyle = ConversationStatusStyle() extension ConversationStatusMatcher { static var regularStyle: [NSAttributedString.Key: AnyObject] { return statusStyle.regularStyle } static var emphasisStyle: [NSAttributedString.Key: AnyObject] { return statusStyle.emphasisStyle } } // Accessors for ObjC extension ZMConversation { static func statusRegularStyle() -> [NSAttributedString.Key: AnyObject] { return statusStyle.regularStyle } static func statusEmphasisStyle() -> [NSAttributedString.Key: AnyObject] { return statusStyle.emphasisStyle } } // "You left" final class SelfUserLeftMatcher: ConversationStatusMatcher { func isMatching(with status: ConversationStatus) -> Bool { return !status.hasMessages && status.isGroup && !status.isSelfAnActiveMember } func description(with status: ConversationStatus, conversation: MatcherConversation) -> NSAttributedString? { return "conversation.status.you_left".localized && type(of: self).regularStyle } func icon(with status: ConversationStatus, conversation: MatcherConversation) -> ConversationStatusIcon? { return nil } var combinesWith: [ConversationStatusMatcher] = [] } // "Blocked" final class BlockedMatcher: ConversationStatusMatcher { func isMatching(with status: ConversationStatus) -> Bool { return status.isBlocked } func description(with status: ConversationStatus, conversation: MatcherConversation) -> NSAttributedString? { return "conversation.status.blocked".localized && type(of: self).regularStyle } var combinesWith: [ConversationStatusMatcher] = [] } // "Active Call" final class CallingMatcher: ConversationStatusMatcher { func isMatching(with status: ConversationStatus) -> Bool { return status.isOngoingCall } func description(with status: ConversationStatus, conversation: MatcherConversation) -> NSAttributedString? { if conversation.voiceChannel?.state.canJoinCall == true { if let callerDisplayName = conversation.voiceChannel?.initiator?.name { return "conversation.status.incoming_call".localized(args: callerDisplayName) && type(of: self).regularStyle } else { return "conversation.status.incoming_call.someone".localized && type(of: self).regularStyle } } return .none } func icon(with status: ConversationStatus, conversation: MatcherConversation) -> ConversationStatusIcon? { return CallingMatcher.icon(for: conversation.voiceChannel?.state, conversation: conversation) } public static func icon(for state: CallState?, conversation: ConversationStatusProvider?) -> ConversationStatusIcon? { guard let state = state else { return nil } if state.canJoinCall { return .activeCall(showJoin: true) } else if state.isCallOngoing { return .activeCall(showJoin: false) } return nil } var combinesWith: [ConversationStatusMatcher] = [] } final class SecurityAlertMatcher: ConversationStatusMatcher { func isMatching(with status: ConversationStatus) -> Bool { return status.messagesRequiringAttention.contains(where: { $0.isComposite }) } func description(with status: ConversationStatus, conversation: MatcherConversation) -> NSAttributedString? { guard let message = status.messagesRequiringAttention.reversed().first(where: { $0.isComposite }) else { return nil } let textItem = (message as? ConversationCompositeMessage)?.compositeMessageData?.items.first(where: { if case .text = $0 { return true } return false }) let text: String if let textItem = textItem, case let .text(data) = textItem, let messageText = data.messageText { text = messageText } else { text = "conversation.status.poll.default".localized } return text && Swift.type(of: self).regularStyle } func icon(with status: ConversationStatus, conversation: MatcherConversation) -> ConversationStatusIcon? { return nil /// TODO: icon for poll message } var combinesWith: [ConversationStatusMatcher] = [] } // "A, B, C: typing a message..." final class TypingMatcher: ConversationStatusMatcher { func isMatching(with status: ConversationStatus) -> Bool { return status.isTyping && status.showingAllMessages } func description(with status: ConversationStatus, conversation: MatcherConversation) -> NSAttributedString? { let statusString: NSAttributedString if status.isGroup { let typingUsersString = conversation.typingUsers.compactMap(\.name).joined(separator: ", ") let resultString = String(format: "conversation.status.typing.group".localized, typingUsersString) let intermediateString = NSAttributedString(string: resultString, attributes: type(of: self).regularStyle) statusString = self.addEmphasis(to: intermediateString, for: typingUsersString) } else { statusString = "conversation.status.typing".localized && type(of: self).regularStyle } return statusString } func icon(with status: ConversationStatus, conversation: MatcherConversation) -> ConversationStatusIcon? { return .typing } var combinesWith: [ConversationStatusMatcher] = [] } // "Silenced" final class SilencedMatcher: ConversationStatusMatcher { func isMatching(with status: ConversationStatus) -> Bool { return !status.showingAllMessages } func description(with status: ConversationStatus, conversation: MatcherConversation) -> NSAttributedString? { return .none } func icon(with status: ConversationStatus, conversation: MatcherConversation) -> ConversationStatusIcon? { if status.showingOnlyMentionsAndReplies { if status.hasSelfMention { return .mention } else if status.hasSelfReply { return .reply } } return .silenced } var combinesWith: [ConversationStatusMatcher] = [] } extension ConversationStatus { var showingAllMessages: Bool { return mutedMessageTypes == .none } var showingOnlyMentionsAndReplies: Bool { return mutedMessageTypes == .regular } var completelyMuted: Bool { return mutedMessageTypes == .all } var shouldSummarizeMessages: Bool { if completelyMuted { // Always summarize for completely muted conversation return true } else if showingOnlyMentionsAndReplies && !hasSelfMention && !hasSelfReply { // Summarize when there is no mention return true } else if hasSelfMention { // Summarize if there is at least one mention and another activity that can be inside a summary return StatusMessageType.summaryTypes.reduce(into: UInt(0)) { $0 += (messagesRequiringAttentionByType[$1] ?? 0) } > 1 } else if hasSelfReply { // Summarize if there is at least one reply and another activity that can be inside a summary let count = StatusMessageType.summaryTypes.reduce(into: UInt(0)) { $0 += (messagesRequiringAttentionByType[$1] ?? 0) } // if all activities are replies, do not summarize if messagesRequiringAttentionByType[.reply] == count { return false } else { return count > 1 } } else { // Never summarize in other cases return false } } } // In silenced "N (text|image|link|...) message, ..." // In not silenced: "[Sender:] <message text>" // Ephemeral: "Ephemeral message" final class NewMessagesMatcher: TypedConversationStatusMatcher { var matchedTypes: [StatusMessageType] { return StatusMessageType.summaryTypes } let localizationRootPath = "conversation.status.message" let matchedTypesDescriptions: [StatusMessageType: String] = [ .mention: "mention", .reply: "reply", .missedCall: "missedcall", .knock: "knock", .text: "text", .link: "link", .image: "image", .location: "location", .audio: "audio", .video: "video", .file: "file" ] func description(with status: ConversationStatus, conversation: MatcherConversation) -> NSAttributedString? { if status.shouldSummarizeMessages { // Get the count of each category we can summarize, and group them under their parent type let flattenedCount: [StatusMessageType: UInt] = matchedTypes .reduce(into: [StatusMessageType: UInt]()) { guard let count = status.messagesRequiringAttentionByType[$1], count > 0 else { return } if let parentType = $1.parentSummaryType { $0[parentType, default: 0] += count } else { $0[$1, default: 0] += count } } // For each top-level summary type, generate the subtitle fragment let localizedMatchedItems: [String] = flattenedCount.keys.lazy .sorted { $0.rawValue < $1.rawValue } .reduce(into: []) { guard let count = flattenedCount[$1], let string = $1.localizedString(with: count) else { return } $0.append(string) } let resultString = localizedMatchedItems.joined(separator: ", ") return resultString.capitalizingFirstLetter() && type(of: self).regularStyle } else { guard let message = status.messagesRequiringAttention.reversed().first(where: { if $0.senderUser != nil, let type = StatusMessageType(message: $0), matchedTypesDescriptions[type] != nil { return true } else { return false } }), let sender = message.senderUser, let type = StatusMessageType(message: message), let localizationKey = matchedTypesDescriptions[type] else { return "" && Swift.type(of: self).regularStyle } let messageDescription: String if message.isEphemeral { var typeSuffix = ".ephemeral" if type == .mention { typeSuffix += status.isGroup ? ".mention.group" : ".mention" } else if type == .reply { typeSuffix += status.isGroup ? ".reply.group" : ".reply" } else if type == .knock { typeSuffix += status.isGroup ? ".knock.group" : ".knock" } else if status.isGroup { typeSuffix += ".group" } messageDescription = (localizationRootPath + typeSuffix).localized } else { var format = localizationRootPath + "." + localizationKey if status.isGroup && type == .missedCall { format += ".groups" return format.localized(args: sender.name ?? "") && Swift.type(of: self).regularStyle } messageDescription = String(format: format.localized, message.textMessageData?.messageText ?? "") } if status.isGroup && !message.isEphemeral { return (((sender.name ?? "") + ": ") && Swift.type(of: self).emphasisStyle) + (messageDescription && Swift.type(of: self).regularStyle) } else { return messageDescription && Swift.type(of: self).regularStyle } } } func icon(with status: ConversationStatus, conversation: MatcherConversation) -> ConversationStatusIcon? { if status.hasSelfMention { return .mention } else if status.hasSelfReply { return .reply } guard let message = status.messagesRequiringAttention.reversed().first(where: { if $0.senderUser != nil, let type = StatusMessageType(message: $0), matchedTypesDescriptions[type] != nil { return true } else { return false } }), let type = StatusMessageType(message: message) else { return nil } switch type { case .knock: return .unreadPing case .missedCall: return .missedCall default: return .unreadMessages(count: status.messagesRequiringAttention.compactMap { StatusMessageType(message: $0) }.filter { matchedTypes.firstIndex(of: $0) != .none }.count) } } var combinesWith: [ConversationStatusMatcher] = [] } // ! Failed to send final class FailedSendMatcher: ConversationStatusMatcher { func isMatching(with status: ConversationStatus) -> Bool { return status.hasUnsentMessages } func description(with status: ConversationStatus, conversation: MatcherConversation) -> NSAttributedString? { return "conversation.status.unsent".localized && type(of: self).regularStyle } var combinesWith: [ConversationStatusMatcher] = [] } // "[You|User] [added|removed|left] [_|users|you]" final class GroupActivityMatcher: TypedConversationStatusMatcher { let matchedTypes: [StatusMessageType] = [.addParticipants, .removeParticipants] private func addedString(for messages: [ZMConversationMessage], in conversation: MatcherConversation) -> NSAttributedString? { if let message = messages.last, let systemMessage = message.systemMessageData, let sender = message.senderUser, !sender.isSelfUser { if systemMessage.userTypes.contains(where: { ($0 as? UserType)?.isSelfUser == true }) { let fullName = sender.name ?? "" let result = String(format: "conversation.status.you_was_added".localized, fullName) && type(of: self).regularStyle return self.addEmphasis(to: result, for: fullName) } } return .none } private func removedString(for messages: [ZMConversationMessage], in conversation: MatcherConversation) -> NSAttributedString? { if let message = messages.last, let systemMessage = message.systemMessageData, let sender = message.senderUser, !sender.isSelfUser { if systemMessage.userTypes.contains(where: { ($0 as? UserType)?.isSelfUser == true }) { return "conversation.status.you_were_removed".localized && type(of: self).regularStyle } } return .none } func description(with status: ConversationStatus, conversation: MatcherConversation) -> NSAttributedString? { var allStatusMessagesByType: [StatusMessageType: [ZMConversationMessage]] = [:] self.matchedTypes.forEach { type in allStatusMessagesByType[type] = status.messagesRequiringAttention.filter { StatusMessageType(message: $0) == type } } let resultString = [addedString(for: allStatusMessagesByType[.addParticipants] ?? [], in: conversation), removedString(for: allStatusMessagesByType[.removeParticipants] ?? [], in: conversation)].compactMap { $0 }.joined(separator: "; " && type(of: self).regularStyle) return resultString } var combinesWith: [ConversationStatusMatcher] = [] func icon(with status: ConversationStatus, conversation: MatcherConversation) -> ConversationStatusIcon? { return .unreadMessages(count: status.messagesRequiringAttention .compactMap { StatusMessageType(message: $0) } .filter { matchedTypes.contains($0) } .count) } } // [Someone] started a conversation final class StartConversationMatcher: TypedConversationStatusMatcher { let matchedTypes: [StatusMessageType] = [.newConversation] func description(with status: ConversationStatus, conversation: MatcherConversation) -> NSAttributedString? { guard let message = status.messagesRequiringAttention.first(where: { StatusMessageType(message: $0) == .newConversation }), let sender = message.senderUser, !sender.isSelfUser else { return .none } let senderString = sender.name ?? "" let resultString = String(format: "conversation.status.started_conversation".localized, senderString) return (resultString && type(of: self).regularStyle).addAttributes(type(of: self).emphasisStyle, toSubstring: senderString) } func icon(with status: ConversationStatus, conversation: MatcherConversation) -> ConversationStatusIcon? { return ConversationStatusIcon.unreadMessages(count: 1) } var combinesWith: [ConversationStatusMatcher] = [] } // Fallback for empty conversations: showing the handle. final class UsernameMatcher: ConversationStatusMatcher { func isMatching(with status: ConversationStatus) -> Bool { return !status.hasMessages } func description(with status: ConversationStatus, conversation: MatcherConversation) -> NSAttributedString? { guard let user = conversation.connectedUserType, let handle = user.handleDisplayString(withDomain: user.isFederated) else { return .none } return handle && type(of: self).regularStyle } var combinesWith: [ConversationStatusMatcher] = [] } /* Matchers priorities (highest first): (SecurityAlert) (SelfUserLeftMatcher) (Blocked) (Calling) (Typing) (Silenced) (New message / call) (Unsent message combines with (Group activity), (New message / call), (Silenced)) (Group activity) (Started conversation) (Username) */ private var allMatchers: [ConversationStatusMatcher] = { let silencedMatcher = SilencedMatcher() let newMessageMatcher = NewMessagesMatcher() let groupActivityMatcher = GroupActivityMatcher() let failedSendMatcher = FailedSendMatcher() failedSendMatcher.combinesWith = [silencedMatcher, newMessageMatcher, groupActivityMatcher] return [SecurityAlertMatcher(), SelfUserLeftMatcher(), BlockedMatcher(), CallingMatcher(), silencedMatcher, TypingMatcher(), newMessageMatcher, failedSendMatcher, groupActivityMatcher, StartConversationMatcher(), UsernameMatcher()] }() extension ConversationStatus { func appliedMatchersForDescription(for conversation: MatcherConversation) -> [ConversationStatusMatcher] { guard let topMatcher = allMatchers.first(where: { $0.isMatching(with: self) && $0.description(with: self, conversation: conversation) != .none }) else { return [] } return [topMatcher] + topMatcher.combinesWith.filter { $0.isMatching(with: self) && $0.description(with: self, conversation: conversation) != .none } } func appliedMatcherForIcon(for conversation: MatcherConversation) -> ConversationStatusMatcher? { for matcher in allMatchers.filter({ $0.isMatching(with: self) }) { let icon = matcher.icon(with: self, conversation: conversation) switch icon { case .none: break default: return matcher } } return .none } func description(for conversation: MatcherConversation) -> NSAttributedString { let allMatchers = appliedMatchersForDescription(for: conversation) guard !allMatchers.isEmpty else { return "" && [:] } let allStrings = allMatchers.compactMap { $0.description(with: self, conversation: conversation) } return allStrings.joined(separator: " | " && CallingMatcher.regularStyle) } func icon(for conversation: MatcherConversation) -> ConversationStatusIcon? { guard let topMatcher = appliedMatcherForIcon(for: conversation) else { return nil } return topMatcher.icon(with: self, conversation: conversation) } } extension ZMConversation { var status: ConversationStatus { let messagesRequiringAttention = estimatedUnreadCount > 0 ? unreadMessages : [] let messagesRequiringAttentionByType: [StatusMessageType: UInt] = messagesRequiringAttention.reduce(into: [:]) { histogram, element in guard let messageType = StatusMessageType(message: element) else { return } histogram[messageType, default: 0] += 1 } let isOngoingCall: Bool = { guard let state = voiceChannel?.state else { return false } switch state { case .none, .terminating: return false case .incoming: return true default: return true } }() return ConversationStatus( isGroup: conversationType == .group, hasMessages: estimatedHasMessages, hasUnsentMessages: hasUnreadUnsentMessage, messagesRequiringAttention: messagesRequiringAttention, messagesRequiringAttentionByType: messagesRequiringAttentionByType, isTyping: typingUsers.count > 0, mutedMessageTypes: mutedMessageTypes, isOngoingCall: isOngoingCall, isBlocked: connectedUser?.isBlocked ?? false, isSelfAnActiveMember: isSelfAnActiveMember, hasSelfMention: estimatedUnreadSelfMentionCount > 0, hasSelfReply: estimatedUnreadSelfReplyCount > 0 ) } }
gpl-3.0
7f8a35bc441c3bbf701f2b50fb74f79a
35.060168
190
0.632917
5.001836
false
false
false
false
djtone/VIPER
VIPER-SWIFT/Classes/Modules/Add/User Interface/Transition/AddDismissalTransition.swift
2
1340
// // AddDismissalTransition.swift // VIPER-SWIFT // // Created by Conrad Stoll on 6/4/14. // Copyright (c) 2014 Mutual Mobile. All rights reserved. // import Foundation import UIKit class AddDismissalTransition : NSObject, UIViewControllerAnimatedTransitioning { func transitionDuration(transitionContext: UIViewControllerContextTransitioning) -> NSTimeInterval { return 0.72 } func animateTransition(transitionContext: UIViewControllerContextTransitioning) { let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) as! AddViewController let finalCenter = CGPointMake(160.0, (fromVC.view.bounds.size.height / 2) - 1000.0) let options = UIViewAnimationOptions.CurveEaseIn UIView.animateWithDuration(self.transitionDuration(transitionContext), delay: 0.0, usingSpringWithDamping: 0.64, initialSpringVelocity: 0.22, options: options, animations: { fromVC.view.center = finalCenter fromVC.transitioningBackgroundView.alpha = 0.0 }, completion: { finished in fromVC.view.removeFromSuperview() transitionContext.completeTransition(true) } ) } }
mit
7424dab65ab9e13c5200f57bc557d054
32.525
123
0.660448
5.726496
false
false
false
false
macc704/iKF
iKF/KFNote.swift
1
3945
// // KFNote.swift // iKF // // Created by Yoshiaki Matsuzawa on 2014-06-06. // Copyright (c) 2014 Yoshiaki Matsuzawa. All rights reserved. // import UIKit var idCounter = 0; class KFNote: KFPost { var title = ""; var content = ""; override func marge(another: KFPost) { super.marge(another); let anotherNote = another as KFNote; title = anotherNote.title; content = anotherNote.content; } func getReadHtml() -> String{ let template = KFResource.loadReadTemplate(); var html = template; html = html.stringByReplacingOccurrencesOfString("%YOURCONTENT%", withString:content); var systemVersion = UIDevice.currentDevice().systemVersion; if(systemVersion.hasPrefix("7.") == false){ html = html.stringByReplacingOccurrencesOfString("../kforum_uploads/", withString: KFService.getInstance().getHostURLString() + "kforum_uploads/"); } return html; } func getBaseURL() -> NSURL{ return KFResource.getWebResourceURL(); } func initWithoutAuthor() -> KFNote{ self.guid = "temporary-\(idCounter)"; idCounter++; return self; } func initWithAuthor(author:KFUser) -> KFNote{ self.guid = "temporary-\(idCounter)"; idCounter++; self.primaryAuthor = author; self.title = "New Note"; self.content = "Test"; return self; } override func toString() -> String { var text = ""; text += "\"\(title)\""; if(self.primaryAuthor != nil){ text = text + " by " + self.primaryAuthor.firstName; } if(self.modified != nil){ text = text + " at " + self.modified; } return text; } class func createInitialContent() -> String{ return "<html><body></body></html>"; } class func createReferenceNoteTag(guid:String, title:String) -> String{ return "<kf-post-reference class=\"mceNonEditable\" postid=\"\(guid)\">\(title)</kf-post-reference>"; } class func createReferenceContentTag(guid:String, title:String) -> String{ return "<kf-content-reference class=\"mceNonEditable\" postid=\"\(guid)\">\(title)</kf-content-reference>"; } class func createSupportTag(support:KFSupport) -> String{ let uniqueId = String(Int(NSDate().timeIntervalSince1970)); let template = KFResource.loadScaffoldTagTemplate(); var tagString = template; tagString = tagString.stringByReplacingOccurrencesOfString("%SUPPORTID%", withString: support.guid, options: nil, range: nil); tagString = tagString.stringByReplacingOccurrencesOfString("%UNIQUEID%", withString: uniqueId, options: nil, range: nil); tagString = tagString.stringByReplacingOccurrencesOfString("%TITLE%", withString: support.title, options: nil, range: nil); return tagString; } //temporary implementation func addReference(refNote:KFNote){ if(self.content.isEmpty){ self.content = KFNote.createInitialContent(); } let tag = "<ul><li>\(KFNote.createReferenceNoteTag(refNote.guid, title: refNote.title))</li></ul>"; self.content = self.content.stringByReplacingOccurrencesOfString("</body>", withString: "\(tag)</body>"); self.notify(); } func updateToServer(){ KFAppUtils.executeInBackThread({ let res = KFService.getInstance().updateNote(self); if(res == false){ KFAppUtils.showDialog("Saving Failed", msg: "Would you like to save contents to clipboard?", okHandler: {(UIAlertAction) in let pasteboard = UIPasteboard.generalPasteboard(); pasteboard.string = self.content; return; }); } }); } }
gpl-2.0
d2ce592917dc77311a94938c8e5deb42
33.304348
159
0.600253
4.560694
false
false
false
false
PaulWoodIII/tipski
TipskyiOS/Tipski/TaxiDriversViewController.swift
1
2481
// // TaxiDriversViewController.swift // Tipski // // Created by Paul Wood on 10/19/16. // Copyright © 2016 Paul Wood. All rights reserved. // import Foundation import UIKit class TaxiDriversViewController : TipViewController { @IBOutlet weak var amountTextField: UITextField! @IBOutlet weak var tipLabel: UILabel! @IBOutlet weak var totalLabel: UILabel! @IBOutlet weak var stackView: UIStackView! override var emojiList : Array<TipEmoji>! { get { return Datastore.shared.taxiTipEmojis } set { Datastore.shared.tipEmojis = newValue Datastore.shared.persist() } } override func viewDidLoad() { super.viewDidLoad() Appearance.createInput(textField: amountTextField) amountTextField.inputAccessoryView = self.doneToolbar updateViews() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction override func keyboardDonePressed(_ sender: AnyObject) { amountTextField.resignFirstResponder() } override func updateViews(){ let sat = Double(satisfactionSlider.value) let increment = 1.0 / Double(Datastore.shared.tipEmojis.count) var minBounds = 0.0 var foundSat : TipEmoji = Datastore.shared.tipEmojis[0] for i in 0..<Datastore.shared.tipEmojis.count { if(minBounds > sat){ break } minBounds = minBounds + increment; foundSat = Datastore.shared.tipEmojis[i] } let satisfactionText = foundSat.emoji let tip : Double! = foundSat.tipAmount satisfactionLabel.text = satisfactionText if let amount = Double(amountTextField.text!){ tipLabel.text = "\(prettyPrintMoney(amount * tip))" totalLabel.text = "\(prettyPrintMoney((amount * tip) + amount ))" } else { displayError() } } override func displayError(){ super.displayError() tipLabel.text = "...?" totalLabel.text = "...?" //hideTipLabels() } @IBAction func textFieldDidChange(_ sender: UITextField) { updateViews() } }
mit
7066e860face399a1d7dc8361b5d445f
26.555556
80
0.595968
4.920635
false
false
false
false
tuanphung/ATSwiftKit
Source/Extensions/UIKit/UIAlertView+ATS.swift
1
3499
// // UIAlertView+ATS.swift // // Copyright (c) 2015 PHUNG ANH TUAN. 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. import UIKit var UIAlertViewClosureKey = "UIAlertViewClosureKey" public typealias UIAlertViewClosure = (selectedOption: String) -> () public extension UIAlertView { private var handler: UIAlertViewClosure? { set(value) { let closure = ATSClosureWrapper(closure: value) objc_setAssociatedObject(self, &UIAlertViewClosureKey, closure, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN)) } get { if let wrapper = objc_getAssociatedObject(self, &UIAlertViewClosureKey) as? ATSClosureWrapper<UIAlertViewClosure>{ return wrapper.closure } return nil } } public class func show(title: String?, message: String?, cancelButtonTitle: String?, otherButtonTitles: [String]?, handler: UIAlertViewClosure?) -> UIAlertView { return self.show(title, message: message, accessoryView: nil, cancelButtonTitle: cancelButtonTitle, otherButtonTitles: otherButtonTitles, handler: handler) } public class func show(title: String?, message: String?, accessoryView: UIView?, cancelButtonTitle: String?, otherButtonTitles: [String]?, handler: UIAlertViewClosure?) -> UIAlertView { var alertView = UIAlertView(title: title, message: message, delegate: nil, cancelButtonTitle: nil) alertView.delegate = alertView if let _accessoryView = accessoryView { alertView.setValue(_accessoryView, forKey: "accessoryView") } if let _otherButtonTitles = otherButtonTitles { for buttonTitle in _otherButtonTitles { alertView.addButtonWithTitle(buttonTitle) } } if let _cancelButtonTitle = cancelButtonTitle { alertView.cancelButtonIndex = alertView.addButtonWithTitle(cancelButtonTitle!) } alertView.handler = handler dispatch_async(dispatch_get_main_queue(), { alertView.show() }) return alertView } } extension UIAlertView: UIAlertViewDelegate { public func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) { alertView.setValue(nil, forKey: "accessoryView") alertView.handler?(selectedOption: alertView.buttonTitleAtIndex(buttonIndex)) } }
mit
a283ae1c744a028995ace6dd6c6822c4
42.209877
189
0.696485
5.245877
false
false
false
false
wildthink/BagOfTricks
BagOfTricks/Array+Extensions.swift
1
597
// // Array+Extensions.swift // Pods // // Created by Jason Jobe on 10/5/16. // Copyright © 2016 WildThink. All rights reserved. // import Foundation public struct Segment <T>: Sequence, IteratorProtocol { var items: [T] var index: Int var last: Int public mutating func next() -> T? { guard index <= last else { return nil } defer { index += 1 } return items[index] } public init (_ items: [T], start: Int = 0, end: Int? = nil) { self.items = items self.index = start self.last = end ?? items.count - 1 } }
mit
e14c74d9794aaf8fb8398261bc5df540
20.285714
65
0.568792
3.547619
false
false
false
false
Pluto-tv/RxSwift
RxSwift/Observables/Implementations/Zip.swift
1
3521
// // Zip.swift // RxSwift // // Created by Krunoslav Zaher on 5/23/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation protocol ZipSinkProtocol : class { func next(index: Int) func fail(error: ErrorType) func done(index: Int) } class ZipSink<O: ObserverType> : Sink<O>, ZipSinkProtocol { typealias Element = O.E let arity: Int let lock = NSRecursiveLock() // state var isDone: [Bool] init(arity: Int, observer: O, cancel: Disposable) { self.isDone = [Bool](count: arity, repeatedValue: false) self.arity = arity super.init(observer: observer, cancel: cancel) } func getResult() throws -> Element { abstractMethod() } func hasElements(index: Int) -> Bool { abstractMethod() } func next(index: Int) { var hasValueAll = true for i in 0 ..< arity { if !hasElements(i) { hasValueAll = false; break; } } if hasValueAll { do { let result = try getResult() self.observer?.on(.Next(result)) } catch let e { self.observer?.on(.Error(e)) dispose() } } else { var allOthersDone = true let arity = self.isDone.count for var i = 0; i < arity; ++i { if i != index && !isDone[i] { allOthersDone = false break } } if allOthersDone { observer?.on(.Completed) self.dispose() } } } func fail(error: ErrorType) { observer?.on(.Error(error)) dispose() } func done(index: Int) { isDone[index] = true var allDone = true for done in self.isDone { if !done { allDone = false break } } if allDone { observer?.on(.Completed) dispose() } } } class ZipObserver<ElementType> : ObserverType { typealias E = ElementType typealias ValueSetter = (ElementType) -> () var parent: ZipSinkProtocol? let lock: NSRecursiveLock // state let index: Int let this: Disposable let setNextValue: ValueSetter init(lock: NSRecursiveLock, parent: ZipSinkProtocol, index: Int, setNextValue: ValueSetter, this: Disposable) { self.lock = lock self.parent = parent self.index = index self.this = this self.setNextValue = setNextValue } func on(event: Event<E>) { if let _ = parent { switch event { case .Next(_): break case .Error(_): this.dispose() case .Completed: this.dispose() } } lock.performLocked { if let parent = parent { switch event { case .Next(let value): setNextValue(value) parent.next(index) case .Error(let error): parent.fail(error) case .Completed: parent.done(index) } } } } }
mit
7f67a6c674d294ce2ee2b4a242c38f3d
22.013072
115
0.460665
4.917598
false
false
false
false
dulingkang/Capture
Capture/Capture/SeniorBeauty/FilterAjust/FilterListViewController.swift
1
2582
// // FilterListViewController.swift // Core Image Explorer // // Created by Warren Moore on 1/6/15. // Copyright (c) 2015 objc.io. All rights reserved. // import UIKit class FilterListViewController: UITableViewController{ let filters: [(filterName: String, filterDisplayName: String)] = [ ("CIBloom", "Bloom"), ("CIColorControls", "Color Controls"), ("CIColorInvert", "Color Invert"), ("CIColorPosterize", "Color Posterize"), ("CIExposureAdjust", "Exposure Adjust"), ("CIGammaAdjust", "Gamma Adjust"), ("CIGaussianBlur", "Gaussian Blur"), ("CIGloom", "Gloom"), ("CIHighlightShadowAdjust", "Highlights and Shadows"), ("CIHueAdjust", "Hue Adjust"), ("CILanczosScaleTransform", "Lanczos Scale Transform"), ("CIMaximumComponent", "Maximum Component"), ("CIMinimumComponent", "Minimum Component"), ("CISepiaTone", "Sepia Tone"), ("CISharpenLuminance", "Sharpen Luminance"), ("CIStraightenFilter", "Straighten"), ("CIUnsharpMask", "Unsharp Mask"), ("CIVibrance", "Vibrance"), ("CIVignette", "Vignette") ] override func viewWillAppear(animated: Bool) { self.navigationController?.setNavigationBarHidden(false, animated: true) } override func viewDidLoad() { self.tableView.delegate = self self.tableView.dataSource = self } // MARK: - Table View override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return filters.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let identifier = "SystemFilterCell" let filterProperties: (filterName: String, filterDisplayName: String) = filters[indexPath.row] tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: identifier) let cell = tableView.dequeueReusableCellWithIdentifier(identifier, forIndexPath: indexPath) as UITableViewCell cell.textLabel!.text = filterProperties.filterDisplayName return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let controller = FilterDetailViewController.init() controller.filterName = filters[indexPath.row].filterName self.navigationController?.pushViewController(controller, animated: true) } }
mit
d5888089e6851c2a9d1a0bdee6c39a3d
36.42029
118
0.67622
4.853383
false
false
false
false
jozsef-vesza/Swift-practice
Learning/Learning/View elements/GalleryCell.swift
1
1191
// // GalleryCell.swift // Learning // // Created by Jozsef Vesza on 04/06/14. // Copyright (c) 2014 Jozsef Vesza. All rights reserved. // import UIKit let startAnimNotification = "startanim" let stopAnimNotification = "stopanim" class GalleryCell: UICollectionViewCell, DownloaderCell { @IBOutlet var mealImage : UIImageView @IBOutlet var downloadIndicator : UIActivityIndicatorView var mealName: String? init(coder aDecoder: NSCoder!) { super.init(coder: aDecoder) NSNotificationCenter.defaultCenter().addObserver(self, selector: "startAnimating:", name: startAnimNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "stopAnimating:", name: stopAnimNotification, object: nil) } func startAnimating(notification: NSNotification) { if notification.userInfo["meal"] as NSString == self.mealName { self.downloadIndicator.startAnimating() } } func stopAnimating(notification: NSNotification) { if notification.userInfo["meal"] as NSString == self.mealName { self.downloadIndicator.stopAnimating() } } }
mit
1d5a34151cbdd93e76811c030447a411
30.342105
133
0.690176
4.74502
false
false
false
false
VBVMI/VerseByVerse-iOS
Pods/VimeoNetworking/VimeoNetworking/Sources/ErrorCode.swift
1
6239
// // ErrorCode.swift // VimeoNetworking // // Created by Huebner, Rob on 4/25/16. // Copyright © 2016 Vimeo. 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. // import Foundation /// `VimeoErrorCode` contains all api error codes that are currently recognized by our client applications public enum VimeoErrorCode: Int { // Upload case uploadStorageQuotaExceeded = 4101 case uploadDailyQuotaExceeded = 4102 case invalidRequestInput = 2204 // root error code for all invalid parameters errors below // Password-protected video playback case videoPasswordIncorrect = 2222 case noVideoPasswordProvided = 2223 // Authentication case emailTooLong = 2216 case passwordTooShort = 2210 case passwordTooSimple = 2211 case nameInPassword = 2212 case emailNotRecognized = 2217 case passwordEmailMismatch = 2218 case noPasswordProvided = 2209 case noEmailProvided = 2214 case invalidEmail = 2215 case noNameProvided = 2213 case nameTooLong = 2208 case facebookJoinInvalidToken = 2303 case facebookJoinNoToken = 2306 case facebookJoinMissingProperty = 2304 case facebookJoinMalformedToken = 2305 case facebookJoinDecryptFail = 2307 case facebookJoinTokenTooLong = 2308 case facebookLoginNoToken = 2312 case facebookLoginMissingProperty = 2310 case facebookLoginMalformedToken = 2311 case facebookLoginDecryptFail = 2313 case facebookLoginTokenTooLong = 2314 case facebookInvalidInputGrantType = 2221 case facebookJoinValidateTokenFail = 2315 case facebookInvalidNoInput = 2207 case facebookInvalidToken = 2300 case facebookMissingProperty = 2301 case facebookMalformedToken = 2302 case googleUnableToCreateUserMissingEmail = 2325 case googleUnableToCreateUserTokenTooLong = 2326 case googleUnableToLoginNoToken = 2327 case googleUnableToLoginNonExistentProperty = 2328 case googleUnableToLoginEmailNotFoundViaToken = 2329 case googleUnableToCreateUserInsufficientPermissions = 2330 case googleUnableToCreateUserCannotValidateToken = 2331 case googleUnableToCreateUserDailyLimit = 2332 case googleUnableToLoginInsufficientPermissions = 2333 case googleUnableToLoginCannotValidateToken = 2334 case googleUnableToLoginDailyLimit = 2335 case googleUnableToLoginCouldNotVerifyToken = 2336 case googleUnableToCreateUserCouldNotVerifyToken = 2337 case emailAlreadyRegistered = 2400 case emailBlocked = 2401 case emailSpammer = 2402 case emailPurgatory = 2403 case urlUnavailable = 2404 case timeout = 5000 case tokenNotGenerated = 5001 case drmStreamLimitHit = 3420 case drmDeviceLimitHit = 3421 case unverifiedUser = 3411 // Batch follow case batchUserDoesNotExist = 2900 case batchFollowUserRequestExceeded = 2901 case batchSubscribeChannelRequestExceeded = 2902 case batchChannelDoesNotExist = 2903 case userNotAllowedToFollowUsers = 3417 case userNotAllowedToFollowChannels = 3418 case batchFollowUserRequestFailed = 4005 case batchSubscribeChannelRequestFailed = 4006 // Live Streaming case userNotAllowedToLiveStream = 3422 case userHitSimultaneousLiveStreamingLimit = 3423 case userHitMonthlyLiveStreamingMinutesQuota = 3424 } /// `HTTPStatusCode` contains HTTP status code constants used to inspect response status public enum HTTPStatusCode: Int { case serviceUnavailable = 503 case badRequest = 400 case unauthorized = 401 case forbidden = 403 case notFound = 404 } /// `LocalErrorCode` contains codes for all error conditions that can be generated from within the library public enum LocalErrorCode: Int { // MARK: VimeoClient /// A response failed but returned no error object case undefined = 9000 /// A response returned successfully, but the response dictionary was not valid case invalidResponseDictionary = 9001 /// A request was not able to be initiated with the specified values case requestMalformed = 9002 /// A cache-only request found no cached response case cachedResponseNotFound = 9003 // MARK: VIMObjectMapper /// No model object class was specified for deserialization case noMappingClass = 9010 /// Model object mapping was not successful case mappingFailed = 9011 // MARK: AuthenticationController /// No access token was returned with a successful authentication response case authToken = 9004 /// Could not retrieve parameters from code grant response case codeGrant = 9005 /// Code grant returned state did not match existing state case codeGrantState = 9006 /// No response was returned for an authenticationo request case noResponse = 9007 /// Pin code authentication did not return an activate link or pin code case pinCodeInfo = 9008 /// The currently active pin code has expired case pinCodeExpired = 9009 // MARK: AccountStore /// An account object could not be decoded from keychain data case accountCorrupted = 9012 }
mit
63b9785e9950d799f690261cfa91532f
35.694118
106
0.745431
4.831913
false
false
false
false
davidrauch/mds
mds/UI/UI.swift
1
4913
import Foundation import Darwin.ncurses /** The possible terminal signals - INT: Interrupt - WINCH: Window size change */ enum Signal: Int32 { case INT = 2 case WINCH = 28 } /** The supported keys - Quit: The "q" key, to quit the application - Esc: The escape key - Up: The up arrow key - Down: The down arrow key - Enter: The enter key */ enum Key: UInt32 { case Quit = 113 case Esc = 27 case Up = 65 case Down = 66 case Enter = 10 } /** The possible modes for the UI - Text: Display the text of the document - Structure: Display the structure of the document */ enum Mode { case Text case Structure } // A struct to represent the size of elements struct Size { // The width of the element var width: Int // The height of the element var height: Int } // A struct to represent the location of elements struct Location { // The x location of the element var x: Int // The y location of the element var y: Int } /** Traps a signal - Parameters: - signum: The signal to trap - action: The action to perform */ func trap(signum:Signal, action:@escaping @convention(c) (Int32) -> ()) { signal(signum.rawValue, action) } // The UI class UI { // The document to display let document: Document // The current mode var mode: Mode = .Structure // The status Bar let statusBar: StatusBarView // The view to display the document structure let structureView: StructureView // The view to display the document text let textView: TextView /** Initializes the UI - Parameters: - withDocument: The document to display - Returns: A new UI object */ init(withDocument: Document) { // React to SIGINT trap(signum:.INT) { signal in endwin() exit(0) } // Store the document self.document = withDocument // Initialize UI components statusBar = StatusBarView() structureView = StructureView(document: document) textView = TextView(document: document) } /** Starts displaying the UI */ func start() { reset() update() getInput() } /** Resets the screen */ private func reset() { endwin() refresh() initscr() clear() noecho() curs_set(0) } /** Reads keyboard input and reacts accordingly */ private func getInput() { while true { // Get the key pressed let rawKey = UInt32(getch()) // addstr(String(rawKey)) // Try to process the key if let key: Key = Key(rawValue: rawKey) { switch key { // Quit on "q" key case .Quit: endwin() exit(0) // Esc is an escape char which can be followed by other keycodes case .Esc: // Throw away next char _ = getch() // Try to parse next key if let nextKey: Key = Key(rawValue: UInt32(getch())) { switch nextKey { case .Up: goUp() case .Down: goDown() default: () } } // Enter key switches mode case .Enter: switch self.mode { case .Structure: textView.line = structureView.selectedHeader.line mode = .Text case .Text: mode = .Structure } update() default: () } } } } /** Navigates up in the displayed data */ func goUp() { switch mode { case .Text: textView.goUp() case .Structure: structureView.goUp() } update() } /** Navigates down in the displayed data */ func goDown() { switch mode { case .Text: textView.goDown() case .Structure: structureView.goDown() } update() } /** Updates the UI */ func update() { clear() layout() render() refresh() } /** Lays out all UI components */ private func layout() { // Get current size let screenSize = getScreenSize() // Set the status bar statusBar.mode = mode statusBar.location = Location(x: 0, y: screenSize.height - 1) statusBar.size = Size(width: screenSize.width, height: 1) switch mode { case .Structure: structureView.location = Location(x: 0, y: 0) structureView.size = Size(width: screenSize.width, height: screenSize.height - 2) case .Text: textView.location = Location(x: 0, y: 0) textView.size = Size(width: screenSize.width, height: screenSize.height - 2) } } /** Renders the UI */ private func render() { // Render components switch mode { case .Text: textView.render() case .Structure: structureView.render() } statusBar.render() // Render divider lines move(Int32(statusBar.location.y - 1), Int32(statusBar.location.x)) hline(UInt32(UInt8(ascii:"-")), Int32(statusBar.size.width)) } /** Gets the current screen size - Returns: A tuple representing the screen size (width, height) */ private func getScreenSize() -> Size { let maxx = getmaxx(stdscr) let maxy = getmaxy(stdscr) return Size(width: Int(maxx), height: Int(maxy)) } }
mit
d878b39b6779a38f7d20e59c325c5cde
16.059028
84
0.623652
3.215314
false
false
false
false
TurfDb/Turf
Turf/Observable/MiniRx/MapObservable.swift
1
1079
import Foundation extension Observable { public func map<Mapped>(_ map: @escaping (Value) -> Mapped) -> Observable<Mapped> { return AnyObservable<Mapped>.create { (observer) -> Disposable in let mappedObserver = AnyObserver<Value>() { (value) in observer.handle(next: map(value)) } return self.subscribe(mappedObserver) } } public func flatMap<Mapped>(_ map: @escaping (Value) -> Observable<Mapped>) -> Observable<Mapped> { return AnyObservable<Mapped>.create { (observer) -> Disposable in let disposeBag = DisposeBag() let flatMappedObserver = AnyObserver<Mapped>() { (value) in observer.handle(next: value) } let mappedObserver = AnyObserver<Value>() { (value) in let mappedValue = map(value) mappedValue.subscribe(flatMappedObserver).addTo(bag: disposeBag) } self.subscribe(mappedObserver).addTo(bag: disposeBag) return disposeBag } } }
mit
ca2912e9b7b874f591dec70d37556420
32.71875
103
0.587581
4.926941
false
false
false
false
trvslhlt/games-for-impact-final
projects/WinkWink_11/WinkWink/Nodes/TapThePartChallengeNode.swift
1
1653
// // TapThePartChallengeNode.swift // WinkWink // // Created by trvslhlt on 4/21/17. // Copyright © 2017 travis holt. All rights reserved. // import UIKit class TapTheVulvaPartChallengeNode: ChallengeNode { let challengeInstructions: String let correctTapRects: [CGRect] let totalNode = AppSpriteNode(imageNamed: "vulva_composite") let correctNodes = [AppSpriteNode]() var instructionsNode: AppLabelNode! init( challengeInstructions: String, correctTapRects: [CGRect]) { self.challengeInstructions = challengeInstructions self.correctTapRects = correctTapRects super.init() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func commonInit() { super.commonInit() let totalNodeOffset = CGPoint(x: 0, y: -50) totalNode.position = totalNodeOffset totalNode.didTap = { self.didSubmitAnswer(correct: false) } for rect in correctTapRects { let node = AppSpriteNode(color: .clear, size: rect.size) node.position = rect.origin node.didTap = { self.didSubmitAnswer(correct: true) } totalNode.addChild(node) } instructionsNode = AppLabelNode(text: challengeInstructions) instructionsNode.position = totalNodeOffset.offset(point: CGPoint(x: 0, y: 240)) addChild(instructionsNode) addChild(totalNode) } override func start() {} override func stop() {} }
mit
89fd10c4caba88dc4d1f1b51259fbbf0
26.533333
88
0.615012
4.464865
false
false
false
false
306244907/Weibo
JLSina/JLSina/Classes/View(视图和控制器)/Home/StatusCell/JLStatusCell.swift
1
3805
// // JLStatusCell.swift // JLSina // // Created by 盘赢 on 2017/11/14. // Copyright © 2017年 JinLong. All rights reserved. // import UIKit //微博cell的协议 //如果需要设置可选协议方法, // - 需要遵守 NSObjectProtocol 协议 // - 协议需要 @objc // - 方法 @objc optional @objc protocol JLStatusCellDelegate: NSObjectProtocol { //微博cell选中URL字符串 @objc optional func statusCellDidSelectedURLString(cell: JLStatusCell , urlString: String) } //微博cell class JLStatusCell: UITableViewCell { //代理属性 weak var delegate: JLStatusCellDelegate? var viewModel: JLStatusViewModel? { didSet { //微博正文文本 statusLabel?.attributedText = viewModel?.statusAttrText //设置被转发微博的文字 retweetedLabel?.attributedText = viewModel?.retweetedAttrText //姓名 nameLabel.text = viewModel?.status.user?.screen_name //设置会员图标 - 直接获取属性,不需要计算 memberIconView.image = viewModel?.memberIcon //认证图标 vipIconView.image = viewModel?.vipIcon //用户头像 iconView.cz_setImage(urlString: viewModel?.status.user?.profile_image_url, placeholderImage: UIImage.init(named: "avatar_default_big") , isAvatar: true) //底部工具栏 toolBar.viewModel = viewModel //配图视图视图模型 pictureView.viewModel = viewModel //设置来源 // print("来源\(String(describing: viewModel?.status.source))") sourceLabel.text = viewModel?.status.source // sourceLabel.text = viewModel?.sourceStr } } //头像 @IBOutlet weak var iconView: UIImageView! //姓名 @IBOutlet weak var nameLabel: UILabel! //会员图标 @IBOutlet weak var memberIconView: UIImageView! //时间 @IBOutlet weak var timeLabel: UILabel! //来源 @IBOutlet weak var sourceLabel: UILabel! //认证图标 @IBOutlet weak var vipIconView: UIImageView! //微博正文 @IBOutlet weak var statusLabel: FFLabel! //底部工具栏 @IBOutlet weak var toolBar: JLStatusToolBar! //配图视图 @IBOutlet weak var pictureView: JLStatusPictureView! //被转发微博标签 - 原创微博没有此控件,一定要用? @IBOutlet weak var retweetedLabel: FFLabel? override func awakeFromNib() { super.awakeFromNib() //离屏渲染 - 异步绘制 self.layer.drawsAsynchronously = true //栅格化 - 异步绘制之后,会生成一张独立的图像,cell在屏幕上滚动的时候。本质上滚动的是这张图片 //cell 优化,要尽量减少图层的数量,相当于就只有一层 //停止滚动之后可以接收监听 self.layer.shouldRasterize = true //使用栅格化必须注意指定分辨率 self.layer.rasterizationScale = UIScreen.main.scale //设置微博文本代理 statusLabel.delegate = self retweetedLabel?.delegate = self } } extension JLStatusCell: FFLabelDelegate { func labelDidSelectedLinkText(label: FFLabel, text: String) { //判断是否是URL if !text.hasPrefix("http://") { return } //URLString? 插入问号,如果代理没有实现方法,就什么都不做 //URLString! 如果使用 !。代理没有实现方法,仍然强行执行,会崩溃 delegate?.statusCellDidSelectedURLString?(cell: self, urlString: text) } }
mit
b6335e7b9755e63f962fd9e4bf00fd46
26.293103
164
0.605496
4.278378
false
false
false
false
DuCalixte/iTunesSearchPattern
iTunesSearchPattern/AppDelegate.swift
1
6196
// // AppDelegate.swift // iTunesSearchPattern // // Created by STANLEY CALIXTE on 10/25/14. // Copyright (c) 2014 STANLEY CALIXTE. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // 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.anouvo.projects.core.patterns.iTunesSearchPattern" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] as NSURL }() 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("iTunesSearchPattern", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("iTunesSearchPattern.sqlite") var error: NSError? = nil var failureReason = "There was an error creating or loading the application's saved data." if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil { coordinator = nil // Report any error we got. let dict = NSMutableDictionary() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error error = 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 \(error), \(error!.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 if coordinator == nil { return nil } var managedObjectContext = NSManagedObjectContext() managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if let moc = self.managedObjectContext { var error: NSError? = nil if moc.hasChanges && !moc.save(&error) { // 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. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } } } }
mit
8bc16662f3df4c9398515da04e89420b
54.81982
290
0.719012
5.715867
false
false
false
false
306244907/Weibo
JLSina/JLSina/Classes/View(视图和控制器)/Home/StatusCell/JLStatusPictureView.swift
1
3760
// // JLStatusPictureView.swift // JLSina // // Created by 盘赢 on 2017/11/16. // Copyright © 2017年 JinLong. All rights reserved. // import UIKit class JLStatusPictureView: UIView { var viewModel: JLStatusViewModel? { didSet { calcViewSize() //设置url urls = viewModel?.picURLs } } //根据视图模型的配图视图大小,调整显示内容 private func calcViewSize() { //处理宽度 //1>单图,根据配图视图的大小,修改 subViews[0]的宽高 if viewModel?.picURLs?.count == 1 { let viewSize = viewModel?.pictureViewSize ?? CGSize() //a))获取第0个图像视图 let v = subviews[0] v.frame = CGRect(x: 0, y: JLStatusPictureViewOutterMargin, width: viewSize.width, height: viewSize.height - JLStatusPictureViewOutterMargin) } else { //2>多图,恢复subViews[0]的宽高 let v = subviews[0] v.frame = CGRect(x: 0, y: JLStatusPictureViewOutterMargin, width: JLStatusPictureItemWidth, height: JLStatusPictureItemWidth) } //修改高度约束 heightCons.constant = viewModel?.pictureViewSize.height ?? 0 } //配图视图的数组 private var urls: [JLStatusPicture]? { didSet { //1,隐藏所有的imageView for v in subviews { v.isHidden = true } //2,遍历urls数组,顺序设置图像 var index = 0 for url in urls ?? [] { //获得对应索引的imageView let iv = subviews[index] as! UIImageView //4张图像处理 if index == 1 && urls?.count == 4 { index += 1 } //设置图像 iv.cz_setImage(urlString: url.thumbnail_pic, placeholderImage: nil) //显示图像 iv.isHidden = false index += 1 } } } @IBOutlet weak var heightCons: NSLayoutConstraint! override func awakeFromNib() { setupUI() } } //MARK: - 设置界面 extension JLStatusPictureView { //1,cell中所有的控件都提前设置好 //2,设置的时候,根据数据决定是否显示 //3,不要动态创建控件 private func setupUI(){ //设置背景颜色 backgroundColor = superview?.backgroundColor //超出边界的内容不显示 clipsToBounds = true let count = 3 let rect = CGRect(x: 0, y: JLStatusPictureViewOutterMargin, width: JLStatusPictureItemWidth, height: JLStatusPictureItemWidth) for i in 0..<count * count { let iv = UIImageView() //设置contentMode iv.contentMode = .scaleAspectFill iv.clipsToBounds = true //行 - Y let row = CGFloat(i / count) //列 - X let col = CGFloat(i % count) let xOffset = col * (JLStatusPictureItemWidth + JLStatusPictureViewInnerMargin) let yOffset = row * (JLStatusPictureItemWidth + JLStatusPictureViewInnerMargin) iv.frame = rect.offsetBy(dx: xOffset, dy: yOffset) addSubview(iv) } } }
mit
763f6b6a34debf1bb47373e16bd9b420
26.103175
134
0.476428
4.803094
false
false
false
false
JoeLago/MHGDB-iOS
MHGDB/Common/Cells/ImageLabelCell.swift
1
3957
// // MIT License // Copyright (c) Gathering Hall Studios // import UIKit protocol ImageLabelCellProtocol { var label: String? { get } var values: [ImageLabelModel] { get } } struct ImageLabelModel { let imageName: String let value: Int? let doShowValue: Bool init(_ imageName: String, _ value: Int? = nil, doShowValue: Bool = true) { self.imageName = imageName self.value = value self.doShowValue = doShowValue } } class ImageLabelCellModel: ImageLabelCellProtocol { var label: String? var values: [ImageLabelModel] init(values: [ImageLabelModel], label: String? = nil) { self.label = label self.values = values } } class ImageLabelCell<T: ImageLabelCellProtocol>: CustomCell<T> { let imgDim: CGFloat = 15 let stateFontSize: CGFloat = 16 let valueFontSize: CGFloat = 12 var labelText: String? var attributedText = NSMutableAttributedString() var stateLabel = UILabel() var valuesLabel = UILabel() var doIncludeState = true var imageLabelCellModel: T? { didSet { populateCell() } } override var model: T? { set { imageLabelCellModel = newValue } get { return imageLabelCellModel } } init(model: T?) { super.init(style: .default, reuseIdentifier: String(describing: ImageLabelCell.self)) imageLabelCellModel = model selectionStyle = .none populateCell() } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: .default, reuseIdentifier: String(describing: ImageLabelCell.self)) selectionStyle = .none } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func initializeViews() { let rows = UIStackView(axis: .vertical, spacing: 8) contentView.addSubview(rows) if (doIncludeState) { rows.addArrangedSubview(stateLabel) } rows.addArrangedSubview(valuesLabel) stateLabel.font = UIFont.systemFont(ofSize: stateFontSize) stateLabel.textColor = Color.Text.primary rows.matchParent(top: 8, left: 25, bottom: 8, right: 25) valuesLabel.numberOfLines = 0 valuesLabel.font = UIFont.systemFont(ofSize: valueFontSize) contentView.useConstraintsOnly() } func populateCell() { if let imageLabelCellModel = imageLabelCellModel { doIncludeState = (imageLabelCellModel.label != nil) } initializeViews() if let imageLabelCellModel = imageLabelCellModel { stateLabel.text = imageLabelCellModel.label imageLabelCellModel.values.forEach { (model: ImageLabelModel) in if model.doShowValue { addNonZeroImageValue(imageName: model.imageName, value: model.value) } else { addImageValue(imageName: model.imageName) } } } } func addNonZeroImageValue(imageName: String, value: Int?) { if let value = value, value != 0 { addImageValue(imageName: imageName, value: value) } else if value == nil { addImageValue(imageName: imageName) } } func addImageValue(imageName: String, value: Int? = nil) { let attachment = NSTextAttachment() attachment.image = UIImage(named: imageName) attachment.bounds = CGRect(x: 0, y: -(imgDim/4), width: imgDim, height: imgDim) attributedText.append(NSAttributedString(attachment: attachment)) if let value = value { attributedText.append(string: "\(value)") } attributedText.append(string: " ") valuesLabel.attributedText = attributedText } }
mit
845d51237a59b2c7ec970452578a8a13
28.529851
93
0.609047
4.738922
false
false
false
false
SwiftCamp/SwiftPathToMastery
1. Novice/Swift-Novice-101.playground/Pages/7Optionals.xcplaygroundpage/Contents.swift
1
1012
/*: ### Optionals Handle optionals from APIs and unwrap them safely More info [Here](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Types.html#//apple_ref/swift/grammar/optional-type) and [Here](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/OptionalChaining.html#//apple_ref/doc/uid/TP40014097-CH21-ID245) **** */ let optionalWrapped : Int? = 0 //Force unwrap print(optionalWrapped!) // Optional binding if let optionalUnWrapped = optionalWrapped { print(optionalUnWrapped) } // Nil coalescence print(optionalWrapped ?? 0) class App { var name: String = "FeedReader" } class Source { var feeds:Int = 100 var reader: App? = nil } var source = Source() print("There are \(source.feeds) feeds.") print("The reader for this source is \(source.reader?.name).") /*: [Table of Contents](Table%20of%20Contents) | [Previous](@previous) | [Next](@next) */
mit
85f0a9143da94e36493afe93e200746c
19.24
351
0.713439
3.50173
false
false
false
false
reactive-swift/UV
UV/Handle.swift
1
11894
//===--- Handle.swift ------------------------------------------------------===// //Copyright (c) 2016 Daniel Leping (dileping) // //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 Boilerplate import CUV public protocol uv_handle_type { func cast<T>() -> UnsafeMutablePointer<T> func cast<T>() -> UnsafePointer<T> var isNil:Bool {get} func testNil() throws #if swift(>=3.0) #else mutating func nullify() #endif static func alloc() -> Self mutating func dealloc() } //extension UnsafePointer : uv_handle_type { // public func cast<T>() -> UnsafeMutablePointer<T> { // return self.withMemoryRebound(to: T.self, capacity: 1) { pointer in // UnsafeMutablePointer(mutating: pointer) // } // } // // public func cast<T>() -> UnsafePointer<T> { // return self.withMemoryRebound(to: T.self, capacity: 1) { pointer in // pointer // } // } // // public var isNil:Bool { // return self == .null // } //// // public func testNil() throws { // if isNil { // throw Error.handleClosed // } // } // // public static func alloc() -> UnsafeMutablePointer<Pointee> { // return UnsafeMutablePointer.allocate(capacity: 1) // } //// //// mutating public func dealloc() { //// self.deinitialize(count: 1) //// self.deallocate(capacity: 1) //// } //} extension UnsafeMutablePointer : uv_handle_type { public func cast<T>() -> UnsafeMutablePointer<T> { return self.withMemoryRebound(to: T.self, capacity: 1) { pointer in pointer } } public func cast<T>() -> UnsafePointer<T> { return self.withMemoryRebound(to: T.self, capacity: 1) { pointer in UnsafePointer(pointer) } } public var isNil:Bool { return self == .null } public func testNil() throws { if isNil { throw Error.handleClosed } } public static func alloc() -> UnsafeMutablePointer { return UnsafeMutablePointer.allocate(capacity: 1) } mutating public func dealloc() { self.deinitialize(count: 1) self.deallocate(capacity: 1) } } extension Optional where Wrapped : uv_handle_type { public mutating func nullify() { self = nil } public var isNil:Bool { return self?.isNil ?? true } public func testNil() throws { if isNil { throw Error.handleClosed } } public var portable:Wrapped? { return self } } public typealias uv_handle_p = UnsafeMutablePointer<uv_handle_t> protocol PropertyType { associatedtype Object associatedtype `Type` static var name: String {get} static var getterValue:`Type` {get} static var function:(Object, UnsafeMutablePointer<`Type`>) -> Int32 {get} static func read(from object:Object) throws -> `Type` static func write(to object:Object, value:`Type`) throws } extension PropertyType { static func read(from object:Object) throws -> Type { return try ccall(Error.self) { code in var value:Type = getterValue code = function(object, &value) return value } } static func write(to object:Object, value:Type) throws { var value:Type = value try ccall(Error.self) { function(object, &value) } } } extension PropertyType { static func readNoThrow(from object:Object) -> Type? { return try? read(from: object) } static func writeNoThrow(to object:Object, value:Type?) { if let value = value { do { try write(to: object, value: value) } catch let e as Error { print(e.description) } catch { print("Unknown error occured while setting ", name) } } } } private protocol BufferPropertyType : PropertyType { } private extension BufferPropertyType where Type == Int32 { static var getterValue:Type { return 0 } } private class SendBufferSizeProperty : BufferPropertyType { typealias Object = uv_handle_p typealias `Type` = Int32 static var name: String { return "send buffer size" } static var function:(Object, UnsafeMutablePointer<Type>) -> Int32 { return uv_send_buffer_size } } private class RecvBufferSizeProperty : BufferPropertyType { typealias Object = uv_handle_p typealias `Type` = Int32 static var name: String { return "recv buffer size" } static var function:(Object, UnsafeMutablePointer<Type>) -> Int32 { return uv_recv_buffer_size } } public protocol HandleType : AnyObject { var baseHandle:uv_handle_p? {get} var loop:Loop? {get} var active:Bool {get} var closing:Bool {get} func close() func ref() throws func unref() throws var referenced:Bool {get} //present, because properties can not throw. So both ways func getSendBufferSize() throws -> Int32 func setSendBufferSize(_ size:Int32) throws var sendBufferSize:Int32? {get set} //present, because properties can not throw. So both ways func getRecvBufferSize() throws -> Int32 func setRecvBufferSize(_ size:Int32) throws var recvBufferSize:Int32? {get set} //present, because properties can not throw. So both ways func getFileno() throws -> uv_os_fd_t var fileno:uv_os_fd_t? {get} } open class HandleBase { fileprivate var _baseHandle:uv_handle_p? open var baseHandle:uv_handle_p? { get { if _baseHandle == .null { _baseHandle = getBaseHandle() } return _baseHandle } set { _baseHandle = newValue } } func getBaseHandle() -> uv_handle_p? { return nil } func clearHandle() { baseHandle.nullify() } } open class Handle<Type : uv_handle_type> : HandleBase, HandleType { open var handle:Type? override func getBaseHandle() -> uv_handle_p? { return self.handle.map({$0.cast()}) } override func clearHandle() { super.clearHandle() handle.nullify() } init(_ initializer:@escaping (Type?)->Int32) throws { self.handle = Type.alloc() super.init() do { try ccall(Error.self) { initializer(self.handle) } baseHandle?.pointee.data = Unmanaged.passRetained(self).toOpaque() } catch let e { //cleanum if not created handle?.dealloc() throw e } } fileprivate static func doWith<Handle: uv_handle_type, Ret>(handle: Handle?, fun:(Handle) throws -> Ret) throws -> Ret { try handle.testNil() return try fun(handle!) } fileprivate func doWithBaseHandle<Ret>(_ fun:(uv_handle_p) throws -> Ret) throws -> Ret { return try Handle.doWith(handle: baseHandle, fun: fun) } func doWithHandle<Ret>(_ fun:(Type) throws -> Ret) throws -> Ret { return try Handle.doWith(handle: handle, fun: fun) } open var loop:Loop? { get { return try? doWithBaseHandle { handle in Loop(loop: handle.pointee.loop) } } } open var active:Bool { get { return !baseHandle.isNil && uv_is_active(baseHandle!) != 0 } } open var closing:Bool { get { return baseHandle.isNil || uv_is_closing(baseHandle!) != 0 } } //uv_close open func close() { if !baseHandle.isNil { uv_close(baseHandle!, handle_close_cb) } } open func ref() throws { try doWithBaseHandle { _ in uv_ref(self.baseHandle.portable) } } open func unref() throws { try doWithBaseHandle { _ in uv_unref(self.baseHandle.portable) } } open var referenced:Bool { get { return !baseHandle.isNil && uv_has_ref(baseHandle.portable) != 0 } } //uv_handle_size //present, because properties can not throw. So both ways open func getSendBufferSize() throws -> Int32 { return try doWithBaseHandle { handle in try SendBufferSizeProperty.read(from: handle) } } open func setSendBufferSize(_ size:Int32) throws { try doWithBaseHandle { handle in try SendBufferSizeProperty.write(to: handle, value: size) } } open var sendBufferSize:Int32? { get { return try? doWithBaseHandle { handle in return try SendBufferSizeProperty.read(from: handle) } } set { do { try doWithBaseHandle { handle in SendBufferSizeProperty.writeNoThrow(to: handle, value: newValue) } } catch { } } } //present, because properties can not throw. So both ways open func getRecvBufferSize() throws -> Int32 { return try doWithBaseHandle { handle in try RecvBufferSizeProperty.read(from: handle) } } open func setRecvBufferSize(_ size:Int32) throws { try doWithBaseHandle { handle in try RecvBufferSizeProperty.write(to: handle, value: size) } } open var recvBufferSize:Int32? { get { return try? doWithBaseHandle { handle in return try RecvBufferSizeProperty.read(from: handle) } } set { do { try doWithBaseHandle { handle in RecvBufferSizeProperty.writeNoThrow(to: handle, value: newValue) } } catch { } } } //present, because properties can not throw. So both ways open func getFileno() throws -> uv_os_fd_t { return try doWithBaseHandle { handle in try ccall(Error.self) { code in var fileno = uv_os_fd_t() code = uv_fileno(handle, &fileno) return fileno } } } open var fileno:uv_os_fd_t? { get { return try? getFileno() } } } extension HandleType { static func from(handle:uv_handle_type!) -> Self { let handle:uv_handle_p = handle.cast() return Unmanaged.fromOpaque(UnsafeRawPointer(handle.pointee.data)).takeUnretainedValue() } } private func _handle_close_cb(_ handle:uv_handle_p?) { guard let handle = handle , handle != .null else { return } if handle.pointee.data != .null { let object = Unmanaged<HandleBase>.fromOpaque(UnsafeRawPointer(handle.pointee.data)).takeRetainedValue() handle.pointee.data = nil object.clearHandle() } handle.deinitialize(count: 1) handle.deallocate(capacity: 1) } private func handle_close_cb(handle:uv_handle_p?) { _handle_close_cb(handle) }
apache-2.0
e11b9c2f95236e309e2e3d88f4c8fa1e
25.431111
124
0.568102
4.426498
false
false
false
false
steverab/WWDC-2015
Stephan Rabanser/DataLoader.swift
1
1518
// // EntriesLoader.swift // Stephan Rabanser // // Created by Stephan Rabanser on 23/04/15. // Copyright (c) 2015 Stephan Rabanser. All rights reserved. // import UIKit import MapKit class DataLoader: NSObject { class func loadTimelineEntries() -> [Entry] { var entries = [Entry]() let loadedEntries = NSArray(contentsOfFile: NSBundle.mainBundle().pathForResource("Entries", ofType: "plist")!) for dict in loadedEntries ?? [] { let buttonDict = dict["button"] as! [String : String] let buttonTitle = buttonDict["title"]! let entry = Entry(title: dict["title"] as! String, shortDescription: dict["shortDescription"] as! String, description: dict["description"] as! String, date: dict["date"] as! String, type: TimelineEntryType(rawValue: dict["type"] as! Int)!, imageString: dict["image"] as! String, buttonTitle: buttonDict["title"]!, buttonURL: buttonDict["link"]!) entries.append(entry) } return entries } class func loadMe() -> Me { let meDict = NSDictionary(contentsOfFile: NSBundle.mainBundle().pathForResource("Me", ofType: "plist")!)! return Me(name: meDict["name"] as! String, shortDescription: meDict["description"] as! String, email: meDict["email"] as! String, twitter: meDict["twitter"] as! String, website: meDict["website"] as! String, locationLatitude: meDict["latitude"] as! CLLocationDegrees, locationLongitude: meDict["longitude"] as! CLLocationDegrees) } }
mit
2c82deb7c1dc4cba9ab8c65e4b722203
47.967742
357
0.667325
4.240223
false
false
false
false
ixx1232/swiftStudy
swiftStudy/swiftStudyTests/05-数组和字典.playground/Contents.swift
1
2525
//: Playground - noun: a place where people can play import UIKit /** 数组-NSArray 非常像 字典 同样使用 [] 定义, 只是格式 是 key:value, key2:value2 */ let array1 = [1, 3, 4, 5, 6] let array2 = ["zhangsan", "lisi"] for num in array1 { print(num) } for str in array2 { print(str) } let dict1 = ["name":"zhangsan","age":18] // 遍历字典的循环中 (key, value)具体的变量名可以随便写 for (k, v) in dict1 { print("\(k)---\(v)") } // 指定数组中只保存某一类的对象, 例如: String // 只能保存字符串, 同时实例化 var arr1 = [String]() // 只是定义了一个数组, 但是没有实例化 var arr2:[String] arr1.append("18") arr1.append("zhangsan") // 数组的合并 -> 在之前的 swift 中, + 是和 append 等价的 // 目前的语法中, + 能够直接合并两个 "内容一样" 的数组 arr2 = ["1", "2", "3"] arr1 += arr2 // 如果数组中的类型不一致, 是不允许合并的! // 再次提醒, 在 Swift 中, 类型要求异常严格 //arr1 += array1 // 定义字典的时候, 同样可以指定 key & value 的类型 // 通常字典中, key 是字符串, value 是任意的类型 // AnyObject 类似于 OC 中的 id // 但是, 在 Swift 中, 真得时万物皆对象, 数值型的不需要任何的转换 var dict = Dictionary<String, AnyObject>() // OC 中 setValue dict["name"] = "zhangsan" dict dict["age"] = 18 dict // 如果设置同样地 key 会出现什么结果 -> 会替换之前存在的内容 dict["name"] = "lisi" dict // 字典的合并 var dict2 = Dictionary<String, AnyObject>() dict2["title"] = "BOSS" dict2 dict2["name"] = "wangwu" dict2 // 要合并字典 for (k, v) in dict2 { // updateValue 可以直接更新字典中存在的值, 如果不存在会新建 dict.updateValue(v, forKey: k) } dict2 //---------------------------------------- // 使用方括号[]来创建数组和字典,并使用下标或者键(key)来访问元素 var shoppingList = ["catfish", "water","tulips", "blue paint"] shoppingList[1] = "bottle of water" var occupations = [ "Malcolm":"Captain", "Kaylee":"Mechanic", ] occupations["Jayne"] = "Public Relations" // 要创建一个空数组或者字典, 使用初始化语法 let emptyArray = [String]() let emptyDictionary = [String: Float]() // 如果类型信息可以被推断出来,你可以用[]和[:]来创建空数组和空字典 --就像你声明变量或者给函数穿参数的时候一样 shoppingList = [] occupations = [:]
mit
fab1979a686f43183d6d39e618677fe5
16.910891
62
0.62576
2.555085
false
false
false
false
parkera/swift-corelibs-foundation
Foundation/NSObjCRuntime.swift
1
16738
// 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 #if os(macOS) || os(iOS) internal let kCFCompareLessThan = CFComparisonResult.compareLessThan internal let kCFCompareEqualTo = CFComparisonResult.compareEqualTo internal let kCFCompareGreaterThan = CFComparisonResult.compareGreaterThan #endif internal enum _NSSimpleObjCType : UnicodeScalar { case ID = "@" case Class = "#" case Sel = ":" case Char = "c" case UChar = "C" case Short = "s" case UShort = "S" case Int = "i" case UInt = "I" case Long = "l" case ULong = "L" case LongLong = "q" case ULongLong = "Q" case Float = "f" case Double = "d" case Bitfield = "b" case Bool = "B" case Void = "v" case Undef = "?" case Ptr = "^" case CharPtr = "*" case Atom = "%" case ArrayBegin = "[" case ArrayEnd = "]" case UnionBegin = "(" case UnionEnd = ")" case StructBegin = "{" case StructEnd = "}" case Vector = "!" case Const = "r" } extension Int { init(_ v: _NSSimpleObjCType) { self.init(UInt8(ascii: v.rawValue)) } } extension Int8 { init(_ v: _NSSimpleObjCType) { self.init(Int(v)) } } extension String { init(_ v: _NSSimpleObjCType) { self.init(v.rawValue) } } extension _NSSimpleObjCType { init?(_ v: UInt8) { self.init(rawValue: UnicodeScalar(v)) } init?(_ v: String?) { if let rawValue = v?.unicodeScalars.first { self.init(rawValue: rawValue) } else { return nil } } } // mapping of ObjC types to sizes and alignments (note that .Int is 32-bit) // FIXME use a generic function, unfortunately this seems to promote the size to 8 private let _NSObjCSizesAndAlignments : Dictionary<_NSSimpleObjCType, (Int, Int)> = [ .ID : ( MemoryLayout<AnyObject>.size, MemoryLayout<AnyObject>.alignment ), .Class : ( MemoryLayout<AnyClass>.size, MemoryLayout<AnyClass>.alignment ), .Char : ( MemoryLayout<CChar>.size, MemoryLayout<CChar>.alignment ), .UChar : ( MemoryLayout<UInt8>.size, MemoryLayout<UInt8>.alignment ), .Short : ( MemoryLayout<Int16>.size, MemoryLayout<Int16>.alignment ), .UShort : ( MemoryLayout<UInt16>.size, MemoryLayout<UInt16>.alignment ), .Int : ( MemoryLayout<Int32>.size, MemoryLayout<Int32>.alignment ), .UInt : ( MemoryLayout<UInt32>.size, MemoryLayout<UInt32>.alignment ), .Long : ( MemoryLayout<Int32>.size, MemoryLayout<Int32>.alignment ), .ULong : ( MemoryLayout<UInt32>.size, MemoryLayout<UInt32>.alignment ), .LongLong : ( MemoryLayout<Int64>.size, MemoryLayout<Int64>.alignment ), .ULongLong : ( MemoryLayout<UInt64>.size, MemoryLayout<UInt64>.alignment ), .Float : ( MemoryLayout<Float>.size, MemoryLayout<Float>.alignment ), .Double : ( MemoryLayout<Double>.size, MemoryLayout<Double>.alignment ), .Bool : ( MemoryLayout<Bool>.size, MemoryLayout<Bool>.alignment ), .CharPtr : ( MemoryLayout<UnsafePointer<CChar>>.size, MemoryLayout<UnsafePointer<CChar>>.alignment) ] internal func _NSGetSizeAndAlignment(_ type: _NSSimpleObjCType, _ size : inout Int, _ align : inout Int) -> Bool { guard let sizeAndAlignment = _NSObjCSizesAndAlignments[type] else { return false } size = sizeAndAlignment.0 align = sizeAndAlignment.1 return true } public func NSGetSizeAndAlignment(_ typePtr: UnsafePointer<Int8>, _ sizep: UnsafeMutablePointer<Int>?, _ alignp: UnsafeMutablePointer<Int>?) -> UnsafePointer<Int8> { let type = _NSSimpleObjCType(UInt8(typePtr.pointee))! var size : Int = 0 var align : Int = 0 if !_NSGetSizeAndAlignment(type, &size, &align) { // FIXME: This used to return nil, but the corresponding Darwin // implementation is defined as returning a non-optional value. fatalError("invalid type encoding") } sizep?.pointee = size alignp?.pointee = align return typePtr.advanced(by: 1) } public enum ComparisonResult : Int { case orderedAscending = -1 case orderedSame case orderedDescending internal static func _fromCF(_ val: CFComparisonResult) -> ComparisonResult { if val == kCFCompareLessThan { return .orderedAscending } else if val == kCFCompareGreaterThan { return .orderedDescending } else { return .orderedSame } } } /* Note: QualityOfService enum is available on all platforms, but it may not be implemented on all platforms. */ public enum QualityOfService : Int { /* UserInteractive QoS is used for work directly involved in providing an interactive UI such as processing events or drawing to the screen. */ case userInteractive /* UserInitiated QoS is used for performing work that has been explicitly requested by the user and for which results must be immediately presented in order to allow for further user interaction. For example, loading an email after a user has selected it in a message list. */ case userInitiated /* Utility QoS is used for performing work which the user is unlikely to be immediately waiting for the results. This work may have been requested by the user or initiated automatically, does not prevent the user from further interaction, often operates at user-visible timescales and may have its progress indicated to the user by a non-modal progress indicator. This work will run in an energy-efficient manner, in deference to higher QoS work when resources are constrained. For example, periodic content updates or bulk file operations such as media import. */ case utility /* Background QoS is used for work that is not user initiated or visible. In general, a user is unaware that this work is even happening and it will run in the most efficient manner while giving the most deference to higher QoS work. For example, pre-fetching content, search indexing, backups, and syncing of data with external systems. */ case background /* Default QoS indicates the absence of QoS information. Whenever possible QoS information will be inferred from other sources. If such inference is not possible, a QoS between UserInitiated and Utility will be used. */ case `default` } public struct NSSortOptions: OptionSet { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let concurrent = NSSortOptions(rawValue: UInt(1 << 0)) public static let stable = NSSortOptions(rawValue: UInt(1 << 4)) } public struct NSEnumerationOptions: OptionSet { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let concurrent = NSEnumerationOptions(rawValue: UInt(1 << 0)) public static let reverse = NSEnumerationOptions(rawValue: UInt(1 << 1)) } public typealias Comparator = (Any, Any) -> ComparisonResult public let NSNotFound: Int = Int.max internal func NSRequiresConcreteImplementation(_ fn: String = #function, file: StaticString = #file, line: UInt = #line) -> Never { fatalError("\(fn) must be overriden in subclass implementations", file: file, line: line) } internal func NSUnimplemented(_ fn: String = #function, file: StaticString = #file, line: UInt = #line) -> Never { #if os(Android) NSLog("\(fn) is not yet implemented. \(file):\(line)") #endif fatalError("\(fn) is not yet implemented", file: file, line: line) } internal func NSUnsupported(_ fn: String = #function, file: StaticString = #file, line: UInt = #line) -> Never { #if os(Android) NSLog("\(fn) is not supported on this platform. \(file):\(line)") #endif fatalError("\(fn) is not supported on this platform", file: file, line: line) } internal func NSInvalidArgument(_ message: String, method: String = #function, file: StaticString = #file, line: UInt = #line) -> Never { fatalError("\(method): \(message)", file: file, line: line) } internal struct _CFInfo { // This must match _CFRuntimeBase var info: UInt32 var pad : UInt32 init(typeID: CFTypeID) { // This matches what _CFRuntimeCreateInstance does to initialize the info value info = UInt32((UInt32(typeID) << 8) | (UInt32(0x80))) pad = 0 } init(typeID: CFTypeID, extra: UInt32) { info = UInt32((UInt32(typeID) << 8) | (UInt32(0x80))) pad = extra } } // MARK: Classes to strings // These must remain in sync with Foundation.apinotes as shipped on Apple OSes. // NSStringFromClass(_:) will return the ObjC name when passed one of these classes, and NSClassFromString(_:) will return the class when passed the ObjC name. // This is important for NSCoding archives created on Apple OSes to decode with swift-corelibs-foundation and for general source and data format compatibility. internal let _NSClassesRenamedByObjCAPINotes: [(class: AnyClass, objCName: String)] = [ (CachedURLResponse.self, "NSCachedURLResponse"), (HTTPCookie.self, "NSHTTPCookie"), (HTTPCookieStorage.self, "NSHTTPCookieStorage"), (HTTPURLResponse.self, "NSHTTPURLResponse"), (ProcessInfo.self, "NSProcessInfo"), (URLResponse.self, "NSURLResponse"), (URLSession.self, "NSURLSession"), (URLSessionConfiguration.self, "NSURLSessionConfiguration"), (URLSessionDataTask.self, "NSURLSessionDataTask"), (URLSessionDownloadTask.self, "NSURLSessionDownloadTask"), (URLSessionStreamTask.self, "NSURLSessionStreamTask"), (URLSessionTask.self, "NSURLSessionTask"), (URLSessionUploadTask.self, "NSURLSessionUploadTask"), (MessagePort.self, "NSMessagePort"), (Port.self, "NSPort"), (PortMessage.self, "NSPortMessage"), (SocketPort.self, "NSSocketPort"), (Process.self, "NSTask"), (XMLDTD.self, "NSXMLDTD"), (XMLDTDNode.self, "NSXMLDTDNode"), (XMLDocument.self, "NSXMLDocument"), (XMLElement.self, "NSXMLElement"), (XMLNode.self, "NSXMLNode"), (XMLParser.self, "NSXMLParser"), (Bundle.self, "NSBundle"), (ByteCountFormatter.self, "NSByteCountFormatter"), (Host.self, "NSHost"), (DateComponentsFormatter.self, "NSDateComponentsFormatter"), (DateFormatter.self, "NSDateFormatter"), (DateIntervalFormatter.self, "NSDateIntervalFormatter"), (EnergyFormatter.self, "NSEnergyFormatter"), (FileHandle.self, "NSFileHandle"), (FileManager.self, "NSFileManager"), (Formatter.self, "NSFormatter"), (InputStream.self, "NSInputStream"), (ISO8601DateFormatter.self, "NSISO8601DateFormatter"), (JSONSerialization.self, "NSJSONSerialization"), (LengthFormatter.self, "NSLengthFormatter"), (MassFormatter.self, "NSMassFormatter"), (MeasurementFormatter.self, "NSMeasurementFormatter"), (NotificationQueue.self, "NSNotificationQueue"), (NumberFormatter.self, "NSNumberFormatter"), (Operation.self, "NSOperation"), (OperationQueue.self, "NSOperationQueue"), (OutputStream.self, "NSOutputStream"), (PersonNameComponentsFormatter.self, "NSPersonNameComponentsFormatter"), (Pipe.self, "NSPipe"), (Progress.self, "NSProgress"), (PropertyListSerialization.self, "NSPropertyListSerialization"), (RunLoop.self, "NSRunLoop"), (Scanner.self, "NSScanner"), (Stream.self, "NSStream"), (Thread.self, "NSThread"), (Timer.self, "NSTimer"), (URLAuthenticationChallenge.self, "NSURLAuthenticationChallenge"), (URLCache.self, "NSURLCache"), (URLCredential.self, "NSURLCredential"), (URLCredentialStorage.self, "NSURLCredentialStorage"), (URLProtectionSpace.self, "NSURLProtectionSpace"), (URLProtocol.self, "NSURLProtocol"), (UserDefaults.self, "NSUserDefaults"), (FileManager.DirectoryEnumerator.self, "NSDirectoryEnumerator"), (Dimension.self, "NSDimension"), (Unit.self, "NSUnit"), (UnitAcceleration.self, "NSUnitAcceleration"), (UnitAngle.self, "NSUnitAngle"), (UnitArea.self, "NSUnitArea"), (UnitConcentrationMass.self, "UnitConcentrationMass"), (UnitConverter.self, "NSUnitConverter"), (UnitConverterLinear.self, "NSUnitConverterLinear"), (UnitDispersion.self, "NSUnitDispersion"), (UnitDuration.self, "NSUnitDuration"), (UnitElectricCharge.self, "NSUnitElectricCharge"), (UnitElectricCurrent.self, "NSUnitElectricCurrent"), (UnitElectricPotentialDifference.self, "NSUnitElectricPotentialDifference"), (UnitElectricResistance.self, "NSUnitElectricResistance"), (UnitEnergy.self, "NSUnitEnergy"), (UnitFrequency.self, "NSUnitFrequency"), (UnitFuelEfficiency.self, "NSUnitFuelEfficiency"), (UnitIlluminance.self, "NSUnitIlluminance"), (UnitLength.self, "NSUnitLength"), (UnitMass.self, "NSUnitMass"), (UnitPower.self, "NSUnitPower"), (UnitPressure.self, "NSUnitPressure"), (UnitSpeed.self, "NSUnitSpeed"), (UnitVolume.self, "NSUnitVolume"), (UnitTemperature.self, "NSUnitTemperature"), ] fileprivate var mapFromObjCNameToClass: [String: AnyClass] = { var map: [String: AnyClass] = [:] for entry in _NSClassesRenamedByObjCAPINotes { map[entry.objCName] = entry.class } return map }() fileprivate var mapFromSwiftClassNameToObjCName: [String: String] = { var map: [String: String] = [:] for entry in _NSClassesRenamedByObjCAPINotes { map[String(reflecting: entry.class)] = entry.objCName } return map }() #if os(macOS) || os(iOS) private let _SwiftFoundationModuleName = "SwiftFoundation" #else private let _SwiftFoundationModuleName = "Foundation" #endif /** Returns the class name for a class. For compatibility with Foundation on Darwin, Foundation classes are returned as unqualified names. Only top-level Swift classes (Foo.bar) are supported at present. There is no canonical encoding for other types yet, except for the mangled name, which is neither stable nor human-readable. */ public func NSStringFromClass(_ aClass: AnyClass) -> String { let classNameString = String(reflecting: aClass) if let renamed = mapFromSwiftClassNameToObjCName[classNameString] { return renamed } let aClassName = classNameString._bridgeToObjectiveC() let components = aClassName.components(separatedBy: ".") guard components.count == 2 else { fatalError("NSStringFromClass: \(String(reflecting: aClass)) is not a top-level class") } if components[0] == _SwiftFoundationModuleName { return components[1] } else { return String(describing: aClassName) } } /** Returns the class metadata given a string. For compatibility with Foundation on Darwin, unqualified names are looked up in the Foundation module. Only top-level Swift classes (Foo.bar) are supported at present. There is no canonical encoding for other types yet, except for the mangled name, which is neither stable nor human-readable. */ public func NSClassFromString(_ aClassName: String) -> AnyClass? { if let renamedClass = mapFromObjCNameToClass[aClassName] { return renamedClass } let aClassNameWithPrefix : String let components = aClassName._bridgeToObjectiveC().components(separatedBy: ".") switch components.count { case 1: guard !aClassName.hasPrefix("_Tt") else { NSLog("*** NSClassFromString(\(aClassName)): cannot yet decode mangled class names") return nil } aClassNameWithPrefix = _SwiftFoundationModuleName + "." + aClassName case 2: aClassNameWithPrefix = aClassName default: NSLog("*** NSClassFromString(\(aClassName)): nested class names not yet supported") return nil } return _typeByName(aClassNameWithPrefix) as? AnyClass }
apache-2.0
6709c1c352bdac4f676cf40690aa1c53
40.02451
571
0.667762
4.501883
false
false
false
false
ruslanskorb/CoreStore
CoreStoreTests/ListObserverTests.swift
1
27610
// // ListObserverTests.swift // CoreStore // // Copyright © 2018 John Rommel Estropia // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import XCTest @testable import CoreStore // MARK: - ListObserverTests @available(macOS 10.12, *) class ListObserverTests: BaseTestDataTestCase { @objc dynamic func test_ThatListObservers_CanReceiveInsertNotifications() { self.prepareStack { (stack) in let observer = TestListObserver() let monitor = stack.monitorSectionedList( From<TestEntity1>(), SectionBy(#keyPath(TestEntity1.testBoolean)), OrderBy<TestEntity1>(.ascending(#keyPath(TestEntity1.testBoolean)), .ascending(#keyPath(TestEntity1.testEntityID))) ) monitor.addObserver(observer) XCTAssertFalse(monitor.hasSections()) XCTAssertFalse(monitor.hasObjects()) XCTAssertTrue(monitor.objectsInAllSections().isEmpty) var events = 0 let willChangeExpectation = self.expectation( forNotification: NSNotification.Name(rawValue: "listMonitorWillChange:"), object: observer, handler: { (note) -> Bool in XCTAssertEqual(events, 0) XCTAssertEqual((note.userInfo as NSDictionary?) ?? [:], NSDictionary()) defer { events += 1 } return events == 0 } ) let didInsertSectionExpectation = self.expectation( forNotification: NSNotification.Name(rawValue: "listMonitor:didInsertSection:toSectionIndex:"), object: observer, handler: { (note) -> Bool in XCTAssertEqual(events, 1) XCTAssertEqual( ((note.userInfo as NSDictionary?) ?? [:]), [ "sectionInfo": monitor.sectionInfo(at: 0), "sectionIndex": 0 ] as NSDictionary ) defer { events += 1 } return events == 1 } ) let didInsertObjectExpectation = self.expectation( forNotification: NSNotification.Name(rawValue: "listMonitor:didInsertObject:toIndexPath:"), object: observer, handler: { (note) -> Bool in XCTAssertEqual(events, 2) let userInfo = note.userInfo XCTAssertNotNil(userInfo) XCTAssertEqual( Set(userInfo?.keys.map({ $0 as! String }) ?? []), ["indexPath", "object"] ) let indexPath = userInfo?["indexPath"] as? NSIndexPath XCTAssertEqual(indexPath?.index(atPosition: 0), 0) XCTAssertEqual(indexPath?.index(atPosition: 1), 0) let object = userInfo?["object"] as? TestEntity1 XCTAssertEqual(object?.testBoolean, NSNumber(value: true)) XCTAssertEqual(object?.testNumber, NSNumber(value: 1)) XCTAssertEqual(object?.testDecimal, NSDecimalNumber(string: "1")) XCTAssertEqual(object?.testString, "nil:TestEntity1:1") XCTAssertEqual(object?.testData, ("nil:TestEntity1:1" as NSString).data(using: String.Encoding.utf8.rawValue)!) XCTAssertEqual(object?.testDate, self.dateFormatter.date(from: "2000-01-01T00:00:00Z")!) defer { events += 1 } return events == 2 } ) let didChangeExpectation = self.expectation( forNotification: NSNotification.Name(rawValue: "listMonitorDidChange:"), object: observer, handler: { (note) -> Bool in XCTAssertEqual((note.userInfo as NSDictionary?) ?? [:], NSDictionary()) defer { events += 1 } return events == 3 } ) let saveExpectation = self.expectation(description: "save") stack.perform( asynchronous: { (transaction) -> Bool in let object = transaction.create(Into<TestEntity1>()) object.testBoolean = NSNumber(value: true) object.testNumber = NSNumber(value: 1) object.testDecimal = NSDecimalNumber(string: "1") object.testString = "nil:TestEntity1:1" object.testData = ("nil:TestEntity1:1" as NSString).data(using: String.Encoding.utf8.rawValue)! object.testDate = self.dateFormatter.date(from: "2000-01-01T00:00:00Z")! return transaction.hasChanges }, success: { (hasChanges) in XCTAssertTrue(hasChanges) saveExpectation.fulfill() }, failure: { _ in XCTFail() } ) self.waitAndCheckExpectations() } } @objc dynamic func test_ThatListObservers_CanReceiveUpdateNotifications() { self.prepareStack { (stack) in self.prepareTestDataForStack(stack) let observer = TestListObserver() let monitor = stack.monitorSectionedList( From<TestEntity1>(), SectionBy(#keyPath(TestEntity1.testBoolean)), OrderBy<TestEntity1>(.ascending(#keyPath(TestEntity1.testBoolean)), .ascending(#keyPath(TestEntity1.testEntityID))) ) monitor.addObserver(observer) XCTAssertTrue(monitor.hasSections()) XCTAssertEqual(monitor.numberOfSections(), 2) XCTAssertTrue(monitor.hasObjects()) XCTAssertTrue(monitor.hasObjects(in: 0)) XCTAssertEqual(monitor.numberOfObjects(in: 0), 2) XCTAssertEqual(monitor.numberOfObjects(in: 1), 3) var events = 0 let willChangeExpectation = self.expectation( forNotification: NSNotification.Name(rawValue: "listMonitorWillChange:"), object: observer, handler: { (note) -> Bool in XCTAssertEqual(events, 0) XCTAssertEqual((note.userInfo as NSDictionary?) ?? [:], NSDictionary()) defer { events += 1 } return events == 0 } ) let didUpdateObjectExpectation = self.expectation( forNotification: NSNotification.Name(rawValue: "listMonitor:didUpdateObject:atIndexPath:"), object: observer, handler: { (note) -> Bool in XCTAssert(events == 1 || events == 2) let userInfo = note.userInfo XCTAssertNotNil(userInfo) XCTAssertEqual( Set(userInfo?.keys.map({ $0 as! String }) ?? []), ["indexPath", "object"] ) let indexPath = userInfo?["indexPath"] as? NSIndexPath let object = userInfo?["object"] as? TestEntity1 switch object?.testEntityID { case NSNumber(value: 101)?: XCTAssertEqual(indexPath?.index(atPosition: 0), 1) XCTAssertEqual(indexPath?.index(atPosition: 1), 0) XCTAssertEqual(object?.testBoolean, NSNumber(value: true)) XCTAssertEqual(object?.testNumber, NSNumber(value: 11)) XCTAssertEqual(object?.testDecimal, NSDecimalNumber(string: "11")) XCTAssertEqual(object?.testString, "nil:TestEntity1:11") XCTAssertEqual(object?.testData, ("nil:TestEntity1:11" as NSString).data(using: String.Encoding.utf8.rawValue)!) XCTAssertEqual(object?.testDate, self.dateFormatter.date(from: "2000-01-11T00:00:00Z")!) case NSNumber(value: 102)?: XCTAssertEqual(indexPath?.index(atPosition: 0), 0) XCTAssertEqual(indexPath?.index(atPosition: 1), 0) XCTAssertEqual(object?.testBoolean, NSNumber(value: false)) XCTAssertEqual(object?.testNumber, NSNumber(value: 22)) XCTAssertEqual(object?.testDecimal, NSDecimalNumber(string: "22")) XCTAssertEqual(object?.testString, "nil:TestEntity1:22") XCTAssertEqual(object?.testData, ("nil:TestEntity1:22" as NSString).data(using: String.Encoding.utf8.rawValue)!) XCTAssertEqual(object?.testDate, self.dateFormatter.date(from: "2000-01-22T00:00:00Z")!) default: XCTFail() } defer { events += 1 } return events == 1 || events == 2 } ) let didChangeExpectation = self.expectation( forNotification: NSNotification.Name(rawValue: "listMonitorDidChange:"), object: observer, handler: { (note) -> Bool in XCTAssertEqual(events, 3) XCTAssertEqual((note.userInfo as NSDictionary?) ?? [:], NSDictionary()) defer { events += 1 } return events == 3 } ) let saveExpectation = self.expectation(description: "save") stack.perform( asynchronous: { (transaction) -> Bool in if let object = try transaction.fetchOne( From<TestEntity1>(), Where<TestEntity1>(#keyPath(TestEntity1.testEntityID), isEqualTo: 101)) { object.testNumber = NSNumber(value: 11) object.testDecimal = NSDecimalNumber(string: "11") object.testString = "nil:TestEntity1:11" object.testData = ("nil:TestEntity1:11" as NSString).data(using: String.Encoding.utf8.rawValue)! object.testDate = self.dateFormatter.date(from: "2000-01-11T00:00:00Z")! } else { XCTFail() } if let object = try transaction.fetchOne( From<TestEntity1>(), Where<TestEntity1>(#keyPath(TestEntity1.testEntityID), isEqualTo: 102)) { object.testNumber = NSNumber(value: 22) object.testDecimal = NSDecimalNumber(string: "22") object.testString = "nil:TestEntity1:22" object.testData = ("nil:TestEntity1:22" as NSString).data(using: String.Encoding.utf8.rawValue)! object.testDate = self.dateFormatter.date(from: "2000-01-22T00:00:00Z")! } else { XCTFail() } return transaction.hasChanges }, success: { (hasChanges) in XCTAssertTrue(hasChanges) saveExpectation.fulfill() }, failure: { _ in XCTFail() } ) self.waitAndCheckExpectations() } } @objc dynamic func test_ThatListObservers_CanReceiveMoveNotifications() { self.prepareStack { (stack) in self.prepareTestDataForStack(stack) let observer = TestListObserver() let monitor = stack.monitorSectionedList( From<TestEntity1>(), SectionBy(#keyPath(TestEntity1.testBoolean)), OrderBy<TestEntity1>(.ascending(#keyPath(TestEntity1.testBoolean)), .ascending(#keyPath(TestEntity1.testEntityID))) ) monitor.addObserver(observer) var events = 0 let willChangeExpectation = self.expectation( forNotification: NSNotification.Name(rawValue: "listMonitorWillChange:"), object: observer, handler: { (note) -> Bool in XCTAssertEqual(events, 0) XCTAssertEqual((note.userInfo as NSDictionary?) ?? [:], NSDictionary()) defer { events += 1 } return events == 0 } ) let didMoveObjectExpectation = self.expectation( forNotification: NSNotification.Name(rawValue: "listMonitor:didMoveObject:fromIndexPath:toIndexPath:"), object: observer, handler: { (note) -> Bool in XCTAssertEqual(events, 1) let userInfo = note.userInfo XCTAssertNotNil(userInfo) XCTAssertEqual( Set(userInfo?.keys.map({ $0 as! String }) ?? []), ["fromIndexPath", "toIndexPath", "object"] ) let fromIndexPath = userInfo?["fromIndexPath"] as? NSIndexPath XCTAssertEqual(fromIndexPath?.index(atPosition: 0), 0) XCTAssertEqual(fromIndexPath?.index(atPosition: 1), 0) let toIndexPath = userInfo?["toIndexPath"] as? NSIndexPath XCTAssertEqual(toIndexPath?.index(atPosition: 0), 1) XCTAssertEqual(toIndexPath?.index(atPosition: 1), 1) let object = userInfo?["object"] as? TestEntity1 XCTAssertEqual(object?.testEntityID, NSNumber(value: 102)) XCTAssertEqual(object?.testBoolean, NSNumber(value: true)) defer { events += 1 } return events == 1 } ) let didChangeExpectation = self.expectation( forNotification: NSNotification.Name(rawValue: "listMonitorDidChange:"), object: observer, handler: { (note) -> Bool in XCTAssertEqual(events, 2) XCTAssertEqual((note.userInfo as NSDictionary?) ?? [:], NSDictionary()) defer { events += 1 } return events == 2 } ) let saveExpectation = self.expectation(description: "save") stack.perform( asynchronous: { (transaction) -> Bool in if let object = try transaction.fetchOne( From<TestEntity1>(), Where<TestEntity1>(#keyPath(TestEntity1.testEntityID), isEqualTo: 102)) { object.testBoolean = NSNumber(value: true) } else { XCTFail() } return transaction.hasChanges }, success: { (hasChanges) in XCTAssertTrue(hasChanges) saveExpectation.fulfill() }, failure: { _ in XCTFail() } ) self.waitAndCheckExpectations() } } @objc dynamic func test_ThatListObservers_CanReceiveDeleteNotifications() { self.prepareStack { (stack) in self.prepareTestDataForStack(stack) let observer = TestListObserver() let monitor = stack.monitorSectionedList( From<TestEntity1>(), SectionBy(#keyPath(TestEntity1.testBoolean)), OrderBy<TestEntity1>(.ascending(#keyPath(TestEntity1.testBoolean)), .ascending(#keyPath(TestEntity1.testEntityID))) ) monitor.addObserver(observer) var events = 0 let willChangeExpectation = self.expectation( forNotification: NSNotification.Name(rawValue: "listMonitorWillChange:"), object: observer, handler: { (note) -> Bool in XCTAssertEqual(events, 0) XCTAssertEqual((note.userInfo as NSDictionary?) ?? [:], NSDictionary()) defer { events += 1 } return events == 0 } ) let didUpdateObjectExpectation = self.expectation( forNotification: NSNotification.Name(rawValue: "listMonitor:didDeleteObject:fromIndexPath:"), object: observer, handler: { (note) -> Bool in XCTAssert(events == 1 || events == 2) let userInfo = note.userInfo XCTAssertNotNil(userInfo) XCTAssertEqual( Set(userInfo?.keys.map({ $0 as! String }) ?? []), ["indexPath", "object"] ) let indexPath = userInfo?["indexPath"] as? NSIndexPath XCTAssertEqual(indexPath?.section, 0) XCTAssert(indexPath?.index(atPosition: 1) == 0 || indexPath?.index(atPosition: 1) == 1) let object = userInfo?["object"] as? TestEntity1 XCTAssertEqual(object?.isDeleted, true) defer { events += 1 } return events == 1 || events == 2 } ) let didDeleteSectionExpectation = self.expectation( forNotification: NSNotification.Name(rawValue: "listMonitor:didDeleteSection:fromSectionIndex:"), object: observer, handler: { (note) -> Bool in XCTAssertEqual(events, 3) let userInfo = note.userInfo XCTAssertNotNil(userInfo) XCTAssertEqual( Set(userInfo?.keys.map({ $0 as! String }) ?? []), ["sectionInfo", "sectionIndex"] ) let sectionInfo = userInfo?["sectionInfo"] as? NSFetchedResultsSectionInfo XCTAssertNotNil(sectionInfo) XCTAssertEqual(sectionInfo?.name, "0") let sectionIndex = userInfo?["sectionIndex"] XCTAssertEqual(sectionIndex as? NSNumber, NSNumber(value: 0)) defer { events += 1 } return events == 3 } ) let didChangeExpectation = self.expectation( forNotification: NSNotification.Name(rawValue: "listMonitorDidChange:"), object: observer, handler: { (note) -> Bool in XCTAssertEqual(events, 4) XCTAssertEqual((note.userInfo as NSDictionary?) ?? [:], NSDictionary()) defer { events += 1 } return events == 4 } ) let saveExpectation = self.expectation(description: "save") stack.perform( asynchronous: { (transaction) -> Bool in let count = try transaction.deleteAll( From<TestEntity1>(), Where<TestEntity1>(#keyPath(TestEntity1.testBoolean), isEqualTo: false) ) XCTAssertEqual(count, 2) return transaction.hasChanges }, success: { (hasChanges) in XCTAssertTrue(hasChanges) saveExpectation.fulfill() }, failure: { _ in XCTFail() } ) self.waitAndCheckExpectations() } } } // MARK: TestListObserver @available(macOS 10.12, *) class TestListObserver: ListSectionObserver { // MARK: ListObserver typealias ListEntityType = TestEntity1 func listMonitorWillChange(_ monitor: ListMonitor<TestEntity1>) { NotificationCenter.default.post( name: Notification.Name(rawValue: "listMonitorWillChange:"), object: self, userInfo: [:] ) } func listMonitorDidChange(_ monitor: ListMonitor<TestEntity1>) { NotificationCenter.default.post( name: Notification.Name(rawValue: "listMonitorDidChange:"), object: self, userInfo: [:] ) } func listMonitorWillRefetch(_ monitor: ListMonitor<TestEntity1>) { NotificationCenter.default.post( name: Notification.Name(rawValue: "listMonitorWillRefetch:"), object: self, userInfo: [:] ) } func listMonitorDidRefetch(_ monitor: ListMonitor<TestEntity1>) { NotificationCenter.default.post( name: Notification.Name(rawValue: "listMonitorDidRefetch:"), object: self, userInfo: [:] ) } // MARK: ListObjectObserver func listMonitor(_ monitor: ListMonitor<TestEntity1>, didInsertObject object: TestEntity1, toIndexPath indexPath: IndexPath) { NotificationCenter.default.post( name: Notification.Name(rawValue: "listMonitor:didInsertObject:toIndexPath:"), object: self, userInfo: [ "object": object, "indexPath": indexPath ] ) } func listMonitor(_ monitor: ListMonitor<TestEntity1>, didDeleteObject object: TestEntity1, fromIndexPath indexPath: IndexPath) { NotificationCenter.default.post( name: Notification.Name(rawValue: "listMonitor:didDeleteObject:fromIndexPath:"), object: self, userInfo: [ "object": object, "indexPath": indexPath ] ) } func listMonitor(_ monitor: ListMonitor<TestEntity1>, didUpdateObject object: TestEntity1, atIndexPath indexPath: IndexPath) { NotificationCenter.default.post( name: Notification.Name(rawValue: "listMonitor:didUpdateObject:atIndexPath:"), object: self, userInfo: [ "object": object, "indexPath": indexPath ] ) } func listMonitor(_ monitor: ListMonitor<TestEntity1>, didMoveObject object: TestEntity1, fromIndexPath: IndexPath, toIndexPath: IndexPath) { NotificationCenter.default.post( name: Notification.Name(rawValue: "listMonitor:didMoveObject:fromIndexPath:toIndexPath:"), object: self, userInfo: [ "object": object, "fromIndexPath": fromIndexPath, "toIndexPath": toIndexPath ] ) } // MARK: ListSectionObserver func listMonitor(_ monitor: ListMonitor<TestEntity1>, didInsertSection sectionInfo: NSFetchedResultsSectionInfo, toSectionIndex sectionIndex: Int) { NotificationCenter.default.post( name: Notification.Name(rawValue: "listMonitor:didInsertSection:toSectionIndex:"), object: self, userInfo: [ "sectionInfo": sectionInfo, "sectionIndex": sectionIndex ] ) } func listMonitor(_ monitor: ListMonitor<TestEntity1>, didDeleteSection sectionInfo: NSFetchedResultsSectionInfo, fromSectionIndex sectionIndex: Int) { NotificationCenter.default.post( name: Notification.Name(rawValue: "listMonitor:didDeleteSection:fromSectionIndex:"), object: self, userInfo: [ "sectionInfo": sectionInfo, "sectionIndex": sectionIndex ] ) } }
mit
34d30950d4b4bf2fde88ef6ad0689c03
39.841716
154
0.48314
6.279054
false
true
false
false
VladasZ/iOSTools
Sources/iOS/Views/HorisontalPanel/HorisontalPanel.swift
1
3069
// // HorisontalPanel.swift // iOSTools // // Created by Vladas Zakrevskis on 25/12/2017. // Copyright © 2017 Vladas Zakrevskis. All rights reserved. // import UIKit public protocol HorisontalPanelDelegate : AnyObject { func horisontalPanelDidSelectIndex(_ index: Int) } public class HorisontalPanel : UIView { public var delegate: HorisontalPanelDelegate? public var titles: [String] = [] { didSet { setup() } } public var margin: CGFloat = 10 public var font: UIFont = UIFont.systemFont(ofSize: 15) public var color: UIColor = UIColor.gray public var selectedColor: UIColor = UIColor.black public var selectedIndex: Int = 0 { didSet { setupIndex() } } private var scrollView: UIScrollView! private var labels: [UILabel] = [] private var lastX: CGFloat { if let label = labels.last { return label.maxX } return 0 } private var contentWidth: CGFloat { var width: CGFloat = 0 for title in titles { width += title.sizeFor(font: font).width width += margin } width -= margin return width } public override init(frame: CGRect) { super.init(frame: frame) initialSetup() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initialSetup() } private func initialSetup() { scrollView = UIScrollView(frame: frame.withZeroOrigin) scrollView.autoresizingMask = [.flexibleHeight, .flexibleWidth] scrollView.showsVerticalScrollIndicator = false scrollView.showsHorizontalScrollIndicator = false addSubview(scrollView) setup() } private func setup() { scrollView.removeAllSubviews() scrollView.contentSize = CGSize(contentWidth, height) if titles.count == 0 { return } for i in 0...titles.count - 1 { let title = titles[i] let label = UILabel(frame: CGRect(lastX, 0, title.sizeFor(font: font).width + margin / 2, height)) label.textAlignment = .center label.text = title label.font = font label.tag = i label.isUserInteractionEnabled = true label.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.didTap(_:)))) label.textColor = color scrollView.addSubview(label) labels.append(label) } selectedIndex = 0 } private func setupIndex() { let index = selectedIndex labels.forEach { $0.textColor = self.color } labels[index].textColor = selectedColor delegate?.horisontalPanelDidSelectIndex(index) } @objc private func didTap(_ sender: UITapGestureRecognizer) { selectedIndex = sender.view?.tag ?? 0 } }
mit
4e3c96e93eade04971a440dff931bfa3
29.078431
112
0.583116
4.924559
false
false
false
false
dfsilva/actor-platform
actor-sdk/sdk-core-ios/ActorSDK/Sources/Controllers/Managed Runtime/AANavigationController.swift
1
2428
// // Copyright (c) 2014-2016 Actor LLC. <https://actor.im> // import UIKit open class AANavigationController: UINavigationController { fileprivate let binder = AABinder() public init() { super.init(nibName: nil, bundle: nil) } public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } public override init(rootViewController: UIViewController) { super.init(rootViewController: rootViewController) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } open override func viewDidLoad() { super.viewDidLoad() styleNavBar() // Enabling app state sync progress // self.setPrimaryColor(MainAppTheme.navigation.progressPrimary) // self.setSecondaryColor(MainAppTheme.navigation.progressSecondary) // // binder.bind(Actor.getAppState().isSyncing, valueModel2: Actor.getAppState().isConnecting) { (value1: JavaLangBoolean?, value2: JavaLangBoolean?) -> () in // if value1!.booleanValue() || value2!.booleanValue() { // self.showProgress() // self.setIndeterminate(true) // } else { // self.finishProgress() // } // } } open override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) styleNavBar() UIApplication.shared.setStatusBarStyle(ActorSDK.sharedActor().style.vcStatusBarStyle, animated: true) } open override var preferredStatusBarStyle : UIStatusBarStyle { return ActorSDK.sharedActor().style.vcStatusBarStyle } fileprivate func styleNavBar() { navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: ActorSDK.sharedActor().style.navigationTitleColor] navigationBar.tintColor = ActorSDK.sharedActor().style.navigationTintColor navigationBar.barTintColor = ActorSDK.sharedActor().style.navigationBgColor navigationBar.isTranslucent = ActorSDK.sharedActor().style.navigationIsTransluent navigationBar.hairlineHidden = ActorSDK.sharedActor().style.navigationHairlineHidden view.backgroundColor = ActorSDK.sharedActor().style.vcBgColor } }
agpl-3.0
1a121812c2ec6f0bb6a3b1831dd0d9f2
34.188406
163
0.66145
5.31291
false
false
false
false
aschwaighofer/swift
test/AutoDiff/SILOptimizer/differentiation_sil.swift
2
2707
// RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s --check-prefix=CHECK-SILGEN // RUN: %target-swift-frontend -enable-experimental-forward-mode-differentiation -emit-sil %s | %FileCheck %s --check-prefix=CHECK-SIL // Simple differentiation transform test: check SIL before and after the transform. import _Differentiation @_silgen_name("basic") @differentiable func basic(_ x: Float) -> Float { x } // Test differentiability witnesses. // CHECK-SILGEN-LABEL: sil_differentiability_witness hidden [parameters 0] [results 0] @basic : $@convention(thin) (Float) -> Float { // CHECK-SILGEN-NEXT: } // CHECK-SIL-LABEL: sil_differentiability_witness hidden [parameters 0] [results 0] @basic : $@convention(thin) (Float) -> Float { // CHECK-SIL-NEXT: jvp: @AD__basic__jvp_src_0_wrt_0 : $@convention(thin) (Float) -> (Float, @owned @callee_guaranteed (Float) -> Float) // CHECK-SIL-NEXT: vjp: @AD__basic__vjp_src_0_wrt_0 : $@convention(thin) (Float) -> (Float, @owned @callee_guaranteed (Float) -> Float) // CHECK-SIL-NEXT: } // Test `differentiable_function` instructions. @_silgen_name("test_differentiable_function") func testDifferentiableFunction() { let _: @differentiable (Float) -> Float = basic } // CHECK-SILGEN-LABEL: sil hidden [ossa] @test_differentiable_function : $@convention(thin) () -> () { // CHECK-SILGEN: [[ORIG_FN_REF:%.*]] = function_ref @basic : $@convention(thin) (Float) -> Float // CHECK-SILGEN: [[ORIG_FN:%.*]] = thin_to_thick_function [[ORIG_FN_REF]] : $@convention(thin) (Float) -> Float to $@callee_guaranteed (Float) -> Float // CHECK-SILGEN: [[DIFF_FN:%.*]] = differentiable_function [parameters 0] [[ORIG_FN]] : $@callee_guaranteed (Float) -> Float // CHECK-SILGEN: } // CHECK-SIL-LABEL: sil hidden @test_differentiable_function : $@convention(thin) () -> () { // CHECK-SIL: [[ORIG_FN_REF:%.*]] = function_ref @basic : $@convention(thin) (Float) -> Float // CHECK-SIL: [[ORIG_FN:%.*]] = thin_to_thick_function [[ORIG_FN_REF]] // CHECK-SIL: [[JVP_FN_REF:%.*]] = differentiability_witness_function [jvp] [parameters 0] [results 0] @basic // CHECK-SIL: [[JVP_FN:%.*]] = thin_to_thick_function [[JVP_FN_REF]] // CHECK-SIL: [[VJP_FN_REF:%.*]] = differentiability_witness_function [vjp] [parameters 0] [results 0] @basic // CHECK-SIL: [[VJP_FN:%.*]] = thin_to_thick_function [[VJP_FN_REF]] // CHECK-SIL: [[DIFF_FN:%.*]] = differentiable_function [parameters 0] [[ORIG_FN]] : $@callee_guaranteed (Float) -> Float with_derivative {[[JVP_FN]] : $@callee_guaranteed (Float) -> (Float, @owned @callee_guaranteed (Float) -> Float), [[VJP_FN]] : $@callee_guaranteed (Float) -> (Float, @owned @callee_guaranteed (Float) -> Float)} // CHECK-SIL: }
apache-2.0
a07c5d5f8fb75e8739a596040c7eb039
61.953488
334
0.665682
3.297199
false
true
false
false
aidenluo177/Weather-Swift
Weather/Weather/Models/City.swift
1
417
// // City.swift // Weather // // Created by aidenluo on 15/7/22. // Copyright (c) 2015年 36kr. All rights reserved. // import Foundation import RealmSwift class City: Object { dynamic var id = 0 dynamic var name = "" dynamic var temperature = 0.0 dynamic var pressure = 0.0 dynamic var humidity = 0.0 override static func primaryKey() -> String? { return "id" } }
mit
1c5eb3d6a7c0af2945542fdd3e4df851
17.086957
50
0.614458
3.547009
false
false
false
false
iPrysyazhnyuk/SwiftNetworker
SwiftNetworker/Classes/SwiftNetworker/NetworkerFile.swift
1
1469
// // NetworkerFile.swift // Pods // // Created by Igor on 10/15/17. // // import Foundation public struct NetworkerFile { let data: Data let key: String let fileName: String let mimeType: String public enum ImageFormat { case jpg(compressionQuality: Float) case png func getFileName(name: String) -> String { let fileExtension: String switch self { case .jpg: fileExtension = "jpg" case .png: fileExtension = "png" } return "\(name).\(fileExtension)" } var mimeType: String { switch self { case .jpg: return "image/jpeg" case .png: return "image/png" } } } public init(data: Data, key: String, fileName: String, mimeType: String) { self.data = data self.key = key self.fileName = fileName self.mimeType = mimeType } public init(image: UIImage, key: String, name: String, imageFormat: ImageFormat) { switch imageFormat { case .jpg(let compressionQuality): self.data = UIImageJPEGRepresentation(image, CGFloat(compressionQuality))! case .png: self.data = UIImagePNGRepresentation(image)! } self.key = key self.fileName = imageFormat.getFileName(name: name) self.mimeType = imageFormat.mimeType } }
mit
8fd29992a08f226aed0577d9d25079a6
24.327586
86
0.55548
4.708333
false
false
false
false
prebid/prebid-mobile-ios
InternalTestApp/PrebidMobileDemoRenderingUITests/UITests/RepeatedUITestCase.swift
1
3544
/*   Copyright 2018-2021 Prebid.org, Inc.  Licensed under the Apache License, Version 2.0 (the "License");  you may not use this file except in compliance with the License.  You may obtain a copy of the License at  http://www.apache.org/licenses/LICENSE-2.0  Unless required by applicable law or agreed to in writing, software  distributed under the License is distributed on an "AS IS" BASIS,  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the License for the specific language governing permissions and  limitations under the License.  */ import XCTest class RepeatedUITestCase: BaseUITestCase, Failable { private var iterationFailed = false private var iterationFailures: [[(String, String, UInt)]] = [] private var isIterating = false private var noThrowCount = 0 override func setUp() { super.setUp() iterationFailed = false iterationFailures = [] isIterating = false } // MARK: Failable @objc func failTest(withMessage message: String, file: String, line: UInt, error errorPtr: NSErrorPointer) { failWithMessage(message, file: file, line: line, nothrow: false) } func failWithMessage(_ message: String, file: String, line: UInt, nothrow: Bool) { func performFailure() { if isIterating, iterationFailures.count > 0 { continueAfterFailure = true defer { continueAfterFailure = false } iterationFailed = true iterationFailures[iterationFailures.count - 1].append((message, file, line)) if noThrowCount == 0 { failIterationRunning() } } else { record(XCTIssue(type: .assertionFailure, compactDescription: message)) } } if nothrow { doNotThrowing { performFailure() } } else { performFailure() } } private func doNotThrowing(operation: () -> ()) { noThrowCount += 1 defer { noThrowCount -= 1 } operation() } // MARK: Iterative testing func failUnless(_ condition: @autoclosure () -> Bool, message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) { if !condition() { failWithMessage(message(), file: "\(file)", line: line, nothrow: false) } } func repeatTesting(times: Int, file: StaticString = #file, line: UInt = #line, testClosure: () -> ()) { XCTAssertFalse(isIterating) isIterating = true defer { isIterating = false } for _ in 0..<times { iterationFailed = false iterationFailures.append([]) iterationFailed = attemptRunningIteration(testClosure) == false Thread.sleep(forTimeInterval: 1) guard iterationFailed else { return } } continueAfterFailure = true for failureArray in iterationFailures { for failure in failureArray { record(XCTIssue(type: .assertionFailure, compactDescription: failure.0)) } } continueAfterFailure = false XCTFail("Failed to get successful iteration after \(times) time(s)", file: file, line: line) } }
apache-2.0
491bfa2b378495bccbb4bf185f545980
31.118182
148
0.574299
5.018466
false
true
false
false
hoseking/Peak
Source/Audio/Graph.swift
1
10085
// Copyright © 2015 Venture Media Labs. All rights reserved. // // This file is part of Peak. The full Peak copyright notice, including // terms governing use, modification, and redistribution, is contained in the // file LICENSE at the root of the source code distribution tree. import AudioToolbox func checkStatus(_ status: OSStatus) { guard status == noErr else { fatalError("Status: \(status)") } } open class Graph { enum Bus: AudioUnitScope { case input = 1 // 1 = I = Input case output = 0 // 0 = O = Output } var graph: AUGraph? = nil var ioNode = IONode() var mixerNode = MixerNode() var channels = [Channel]() fileprivate let queue = DispatchQueue(label: "Peak.Graph", attributes: []) fileprivate let sampleSize = UInt32(MemoryLayout<Buffer.Element>.size) fileprivate let inputCallback: AURenderCallback = { (inRefCon, ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData) -> OSStatus in let controller = unsafeBitCast(inRefCon, to: Graph.self) if !controller.deiniting { controller.queue.sync { controller.preloadInput(ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames) } } return noErr } fileprivate var buffer: Buffer! fileprivate var deiniting = false open var running: Bool { var isRunning = DarwinBoolean(false) checkStatus(AUGraphIsRunning(graph!, &isRunning)) return isRunning.boolValue } open var initialized: Bool { var isInitialized = DarwinBoolean(false) checkStatus(AUGraphIsInitialized(graph!, &isInitialized)) return isInitialized.boolValue } open var open: Bool { var isOpen = DarwinBoolean(false) checkStatus(AUGraphIsOpen(graph!, &isOpen)) return isOpen.boolValue } open var sampleRate = 44100 { didSet { performUpdate(setup) } } open var inputEnabled: Bool { didSet { performUpdate(setup) } } open var inputAvailable: ((Int) -> ())? public init(inputEnabled: Bool) { self.inputEnabled = inputEnabled self.buffer = Buffer(capacity: 8192) checkStatus(NewAUGraph(&graph)) checkStatus(AUGraphOpen(graph!)) checkStatus(AUGraphAddNode(graph!, &mixerNode.cd, &mixerNode.audioNode)) checkStatus(AUGraphNodeInfo(graph!, mixerNode.audioNode, nil, &mixerNode.audioUnit)) performUpdate(setup) checkStatus(AUGraphInitialize(graph!)) } deinit { deiniting = true stop() checkStatus(DisposeAUGraph(graph!)) } func setup() { checkStatus(AUGraphStop(graph!)) // Remove and add io node if ioNode.audioNode != 0 { checkStatus(AUGraphRemoveNode(graph!, ioNode.audioNode)) } checkStatus(AUGraphAddNode(graph!, &ioNode.cd, &ioNode.audioNode)) checkStatus(AUGraphNodeInfo(graph!, ioNode.audioNode, nil, &ioNode.audioUnit)) var enableFlag: UInt32 = 1 var disableFlag: UInt32 = 0 // Enable output on io node checkStatus(AudioUnitSetProperty(ioNode.audioUnit!, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Output, Bus.output.rawValue, &enableFlag, UInt32(MemoryLayout<UInt32>.size))) // Set the stream format var streamFormat = AudioStreamBasicDescription() streamFormat.mBitsPerChannel = 8 * sampleSize streamFormat.mBytesPerFrame = sampleSize streamFormat.mBytesPerPacket = sampleSize streamFormat.mChannelsPerFrame = 1 streamFormat.mFormatFlags = kAudioFormatFlagIsFloat | kAudioFormatFlagIsNonInterleaved streamFormat.mFormatID = kAudioFormatLinearPCM streamFormat.mFramesPerPacket = 1 streamFormat.mSampleRate = Float64(sampleRate) // Set the stream format for input of the audio output bus checkStatus(AudioUnitSetProperty(ioNode.audioUnit!, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, Bus.output.rawValue, &streamFormat, UInt32(MemoryLayout<AudioStreamBasicDescription>.size))) // Set buffer size var maxFrames = UInt32(buffer.capacity) checkStatus(AudioUnitSetProperty(ioNode.audioUnit!, kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global, 0, &maxFrames, UInt32(MemoryLayout<UInt32>.size))) if inputEnabled { // Enable input on io node checkStatus(AudioUnitSetProperty(ioNode.audioUnit!, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, Bus.input.rawValue, &enableFlag, UInt32(MemoryLayout<UInt32>.size))) // Set the stream format for output of the audio input bus checkStatus(AudioUnitSetProperty(ioNode.audioUnit!, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, Bus.input.rawValue, &streamFormat, UInt32(MemoryLayout<AudioStreamBasicDescription>.size))) // Disable buffer allocation for the recorder checkStatus(AudioUnitSetProperty(ioNode.audioUnit!, kAudioUnitProperty_ShouldAllocateBuffer, kAudioUnitScope_Output, Bus.input.rawValue, &disableFlag, UInt32(MemoryLayout<UInt32>.size))) // Setup input callback let context = UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque()) var callbackStruct = AURenderCallbackStruct(inputProc: inputCallback, inputProcRefCon: context) checkStatus(AudioUnitSetProperty(ioNode.audioUnit!, kAudioOutputUnitProperty_SetInputCallback, kAudioUnitScope_Global, 0, &callbackStruct, UInt32(MemoryLayout<AURenderCallbackStruct>.size))) } // Connect the io node checkStatus(AUGraphConnectNodeInput(graph!, mixerNode.audioNode, 0, ioNode.audioNode, 0)) } open func start() { guard !running else { return } checkStatus(AUGraphStart(graph!)) } open func stop() { guard running else { return } checkStatus(AUGraphStop(graph!)) } func performUpdate(_ block: () -> ()) { let wasRunning = running stop() block() if wasRunning { start() } } } // MARK: Connections extension Graph { public func add(_ channel: Channel) { guard !channels.contains(where: { $0.mixer.audioNode == channel.mixer.audioNode }) else { return } performUpdate { addFromBlock(channel) } } func addFromBlock(_ channel: Channel) { // Add nodes for i in 0..<channel.nodes.count { guard var node = channel.nodes.at(i) else { fatalError("Could not create channel node") } checkStatus(AUGraphAddNode(graph!, &node.cd, &node.audioNode)) checkStatus(AUGraphNodeInfo(graph!, node.audioNode, nil, &node.audioUnit)) } // Connect nodes for i in 0..<channel.nodes.count { guard let sourceNode = channel.nodes.at(i) else { fatalError("Could not create connect node") } if var targetNode = channel.nodes.at(i+1) { checkStatus(AUGraphConnectNodeInput(graph!, sourceNode.audioNode, 0, targetNode.audioNode, 0)) } else { let bus: UInt32 = mixerNode.addInput(sourceNode) checkStatus(AUGraphConnectNodeInput(graph!, sourceNode.audioNode, 0, mixerNode.audioNode, bus)) } } channels.append(channel) } public func remove(_ channel: Channel) { guard channels.contains(where: { $0.mixer.audioNode == channel.mixer.audioNode }) else { return } performUpdate { removeFromBlock(channel) } } func removeFromBlock(_ channel: Channel) { // Remove nodes for i in 0..<channel.nodes.count { guard var node = channel.nodes.at(i) else { fatalError("Could not remove channel node") } mixerNode.removeInput(node) checkStatus(AUGraphRemoveNode(graph!, node.audioNode)) node.audioNode = 0 node.audioUnit = nil } guard let index = channels.index(where: { $0.mixer.audioNode == channel.mixer.audioNode }) else { fatalError("Could not remove channel") } channels.remove(at: index) } } // MARK: Input extension Graph { fileprivate func preloadInput(_ ioActionFlags: UnsafeMutablePointer<AudioUnitRenderActionFlags>, _ inTimeStamp: UnsafePointer<AudioTimeStamp>, _ inOutputBusNumber: UInt32, _ inNumberFrames: UInt32) { let numSamples = Int(inNumberFrames) assert(numSamples <= buffer.capacity) // Discard old data if there is no room if (buffer.count + numSamples > buffer.capacity) { buffer.removeRange(0..<(buffer.count + numSamples - buffer.capacity)) } // Get new data var bufferList = AudioBufferList() bufferList.mNumberBuffers = 1 bufferList.mBuffers.mNumberChannels = 1 bufferList.mBuffers.mDataByteSize = inNumberFrames * sampleSize bufferList.mBuffers.mData = UnsafeMutableRawPointer(buffer.pointer + buffer.count) checkStatus(AudioUnitRender(ioNode.audioUnit!, ioActionFlags, inTimeStamp, inOutputBusNumber, inNumberFrames, &bufferList)) let numSamplesRendered = Int(bufferList.mBuffers.mDataByteSize / sampleSize) buffer.count += numSamplesRendered; // Notify new data DispatchQueue.main.async { self.inputAvailable?(self.buffer.count) } } public func renderInput(_ data: UnsafeMutablePointer<Double>, count: Int) -> Int { var renderCount = 0 queue.sync { renderCount = self.renderInQueue(data, count: count) } return renderCount } fileprivate func renderInQueue(_ data: UnsafeMutablePointer<Double>, count: Int) -> Int { let renderCount = min(count, self.buffer.count) guard renderCount > 0 else { return 0 } data.assign(from: buffer.pointer, count: renderCount) buffer.removeRange(0..<renderCount) return renderCount } }
mit
e6b897f7036d346d712da98280c06587
37.05283
212
0.662039
4.589895
false
false
false
false
DaRkD0G/EasyHelper
EasyHelperTests/TestSequenceType.swift
1
1329
// // TestSequenceType.swift // EasyHelper // // Created by DaRk-_-D0G on 02/10/2015. // Copyright © 2015 DaRk-_-D0G. All rights reserved. // import XCTest import EasyHelper class TestSequenceType: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { func add(n:String) -> Bool { return n == "jj" } let a = ["jj","jj"] //XCTAssert(a.forEachBySorts(add)) XCTAssert(a.forEachByReject(add).count == 0) // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testSubscript() { let arrayTest = [11,22,33,44,55,66,77,88,99,0] XCTAssertEqual(arrayTest[1,2,0],[22,33,11]) } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock { // Put the code you want to measure the time of here. } } }
mit
bafcba4468035799bd16b03f7668cad2
25.039216
111
0.59488
4.07362
false
true
false
false
kevin-zqw/play-swift
swift-lang/15. Deinitialization.playground/section-1.swift
1
2131
// ------------------------------------------------------------------------------------------------ // Things to know: // // * Deinitializers are called automatically before a class instance is // deallocated,so you can access all properties in the deinitializer. // // * You cannot call them directly. // // * The superclass' deinitializer is called before the subclass'. // // * Swift uses ARC to manage memory, so deinitializers shouldn't always // be necessary. However, you might open a file and need to close it // when a class is deallocated. // ------------------------------------------------------------------------------------------------ // Superclass's deinitializer is called before the subclass'. // Swift uses ARC to manage memory for you, so you don't have to free memory manually, // Deinitializer was used to free other types of resources. // Let's create a couple classes to work with... struct Bank { static var coinsInBank = 10_000 static func vendCoins(var numberOfCoinsToVend: Int) -> Int { numberOfCoinsToVend = min(numberOfCoinsToVend, coinsInBank) coinsInBank -= numberOfCoinsToVend return numberOfCoinsToVend } static func receiveCoins(coins: Int) { coinsInBank += coins } } class Player { var coinsInPurse: Int init(coins: Int) { coinsInPurse = Bank.vendCoins(coins) } func winCoins(coins: Int) { coinsInPurse += coins } deinit { Bank.receiveCoins(coinsInPurse) } } // Let's exercise the Player class a bit and create a new player with 100 // coins in his purse (pulled from the Bank.) var playerOne: Player? = Player(coins: 100) playerOne!.coinsInPurse Bank.coinsInBank // The Player now wins 2000 coins! playerOne!.winCoins(2_000) playerOne!.coinsInPurse Bank.coinsInBank // When we cause playerOne to be deallocated, the deinitializer is called playerOne = nil // This should print 12000 coins, but the playgrounds don't appear to do // this correctly. If you put this code into a project and compile/run // it (with minor changes to print variables using println) then you // will see that the bank does indeed have 12000 coins. Bank.coinsInBank
apache-2.0
9917415e69fb20d6fbae6e2cb17658f4
27.413333
99
0.672454
4.105973
false
false
false
false
finder39/Swimgur
Swimgur/Extensions/UITextViewExt.swift
1
868
// // UITextViewExt.swift // Swimgur // // Created by Joseph Neuman on 10/5/14. // Copyright (c) 2014 Joseph Neuman. All rights reserved. // import Foundation import UIKit public extension UITextView { public func getTextHeight() -> CGFloat { let fixedWidth = self.frame.size.width let newSize = self.sizeThatFits(CGSizeMake(fixedWidth, CGFloat.max)) return newSize.height } public func getTextHeight(#width:CGFloat) -> CGFloat { let newSize = self.sizeThatFits(CGSizeMake(width, CGFloat.max)) return newSize.height } public func autoHeight() { let fixedWidth = self.frame.size.width let newSize = self.sizeThatFits(CGSizeMake(fixedWidth, CGFloat.max)) var newFrame = self.frame newFrame.size = CGSizeMake(CGFloat(fmaxf(Float(newSize.width), Float(fixedWidth))), newSize.height) self.frame = newFrame } }
mit
482ebd13f294041f45385352ba125abb
27.032258
103
0.713134
3.945455
false
false
false
false
rpowelll/ReactiveAPIClient
Nirvash/Nirvash.swift
2
5961
// // Nirvash.swift // Nirvash // // Created by Rhys Powell on 9/08/2015. // Copyright © 2015 Rhys Powell. All rights reserved. // import Foundation import Alamofire import ReactiveCocoa /// Solely used for namespacing public struct Nirvash { /// HTTP Methods public enum Method { case GET, POST, PUT, DELETE, OPTIONS, HEAD, PATCH, TRACE, CONNECT func method() -> Alamofire.Method { switch self { case .GET: return .GET case .POST: return .POST case .PUT: return .PUT case .DELETE: return .DELETE case .HEAD: return .HEAD case .OPTIONS: return .OPTIONS case PATCH: return .PATCH case TRACE: return .TRACE case .CONNECT: return .CONNECT } } } /// Choice of parameter encoding. public enum ParameterEncoding { case URL case JSON case PropertyList(NSPropertyListFormat, NSPropertyListWriteOptions) case Custom((URLRequestConvertible, [String: AnyObject]?) -> (NSMutableURLRequest, NSError?)) func parameterEncoding() -> Alamofire.ParameterEncoding { switch self { case .URL: return .URL case .JSON: return .JSON case .PropertyList(let format, let options): return .PropertyList(format, options) case .Custom(let closure): return .Custom(closure) } } } public enum StubbingBehaviour { case Never case Immediately case Delayed(seconds: Int) } } public protocol APITarget { var baseURL: NSURL { get } var path: String { get } var method: Nirvash.Method { get } var parameters: [String: AnyObject]? { get } var sampleData: NSData { get } } public struct APIEndpoint { public let URL: String public let method: Nirvash.Method public let parameters: [String: AnyObject]? public let parameterEncoding: Nirvash.ParameterEncoding public let httpHeaderFields: [String: String]? public var urlRequest: NSURLRequest { let request = NSMutableURLRequest(URL: NSURL(string: URL)!) request.HTTPMethod = method.method().rawValue request.allHTTPHeaderFields = httpHeaderFields return parameterEncoding.parameterEncoding().encode(request, parameters: parameters).0 } } public class APIProvider { public typealias EndpointClosure = (APITarget) -> (APIEndpoint) public typealias RequestClosure = (endpoint: APIEndpoint) -> (NSURLRequest) public typealias StubClosure = (APITarget) -> (Nirvash.StubbingBehaviour) public let endpointClosure: EndpointClosure public let requestClosure: RequestClosure public let stubClosure: StubClosure public let stubScheduler: DateSchedulerType public init(endpointClosure: EndpointClosure = APIProvider.DefaultEndpointMapping, requestClosure: RequestClosure = APIProvider.DefaultEndpointResolution, stubClosure: StubClosure = APIProvider.NeverStub, stubScheduler: DateSchedulerType = QueueScheduler()) { self.endpointClosure = endpointClosure self.requestClosure = requestClosure self.stubClosure = stubClosure self.stubScheduler = stubScheduler } @warn_unused_result(message="Did you forget to call `start` om the producer?") public func request(target: APITarget) -> SignalProducer<(NSData, NSURLResponse?), NSError> { switch stubClosure(target) { case .Never: return sendRequest(target) case .Immediately, .Delayed(seconds: _): return stubRequest(target ) } } public func sendRequest(target: APITarget) -> SignalProducer<(NSData, NSURLResponse?), NSError> { return SignalProducer<APITarget, NSError>(value: target) .map(endpointClosure) .map(requestClosure) .flatMap(.Latest) { request in return NSURLSession.sharedSession().rac_dataWithRequest(request) } .map { data, response in return (data, response) } } public func stubRequest(target: APITarget) -> SignalProducer<(NSData, NSURLResponse?), NSError> { let producer: SignalProducer<(NSData, NSURLResponse?), NSError> = SignalProducer(value: target) .map { ($0.sampleData, nil) } switch stubClosure(target) { case .Never: fatalError("Tried to stub target that should never be stubbed") case .Immediately: return producer case .Delayed(seconds: let seconds): return producer.delay(NSTimeInterval(seconds), onScheduler: stubScheduler) } } } // MARK: - Defaults extension APIProvider { public class func DefaultEndpointMapping(target: APITarget) -> APIEndpoint { let url = target.baseURL.URLByAppendingPathComponent(target.path).absoluteString return APIEndpoint(URL: url, method: target.method, parameters: target.parameters, parameterEncoding: Nirvash.ParameterEncoding.URL, httpHeaderFields: nil) } public class func DefaultEndpointResolution(endpoint: APIEndpoint) -> NSURLRequest { return endpoint.urlRequest } } // MARK: - Stubbing extension APIProvider { public class func NeverStub(_: APITarget) -> Nirvash.StubbingBehaviour { return .Never } public class func ImmediatelyStub(_: APITarget) -> Nirvash.StubbingBehaviour { return .Immediately } public class func DelayedStub(seconds: Int) -> (_: APITarget) -> Nirvash.StubbingBehaviour { return { _ in .Delayed(seconds: seconds) } } }
mit
f6b056f8d3aed3fbab227a582dd9700c
32.111111
163
0.624832
5.169124
false
false
false
false
meteochu/Alamofire
Source/Manager.swift
1
38205
// // Manager.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /** Responsible for creating and managing `Request` objects, as well as their underlying `URLSession`. */ public class Manager { // MARK: - Properties /** A shared instance of `Manager`, used by top-level Alamofire request methods, and suitable for use directly for any ad hoc requests. */ public static let sharedInstance: Manager = { let configuration = URLSessionConfiguration.default() configuration.httpAdditionalHeaders = Manager.defaultHTTPHeaders return Manager(configuration: configuration) }() /** Creates default values for the "Accept-Encoding", "Accept-Language" and "User-Agent" headers. */ public static let defaultHTTPHeaders: [String: String] = { // Accept-Encoding HTTP Header; see https://tools.ietf.org/html/rfc7230#section-4.2.3 let acceptEncoding: String = "gzip;q=1.0, compress;q=0.5" // Accept-Language HTTP Header; see https://tools.ietf.org/html/rfc7231#section-5.3.5 let acceptLanguage = Locale.preferredLanguages().prefix(6).enumerated().map { index, languageCode in let quality = 1.0 - (Double(index) * 0.1) return "\(languageCode);q=\(quality)" }.joined(separator: ", ") // User-Agent Header; see https://tools.ietf.org/html/rfc7231#section-5.5.3 let userAgent: String = { if let info = Bundle.main().infoDictionary { let executable = info[kCFBundleExecutableKey as String] as? String ?? "Unknown" let bundle = info[kCFBundleIdentifierKey as String] as? String ?? "Unknown" let version = info[kCFBundleVersionKey as String] as? String ?? "Unknown" let os = ProcessInfo.processInfo().operatingSystemVersionString var mutableUserAgent = NSMutableString(string: "\(executable)/\(bundle) (\(version); OS \(os))") as CFMutableString let transform = NSString(string: "Any-Latin; Latin-ASCII; [:^ASCII:] Remove") as CFString if CFStringTransform(mutableUserAgent, UnsafeMutablePointer<CFRange>(nil), transform, false) { return mutableUserAgent as String } } return "Alamofire" }() return [ "Accept-Encoding": acceptEncoding, "Accept-Language": acceptLanguage, "User-Agent": userAgent ] }() let queue = DispatchQueue(label: "", attributes: .serial, target: nil)//dispatch_queue_create(nil, DISPATCH_QUEUE_SERIAL) /// The underlying session. public let session: URLSession /// The session delegate handling all the task and session delegate callbacks. public let delegate: SessionDelegate /// Whether to start requests immediately after being constructed. `true` by default. public var startRequestsImmediately: Bool = true /** The background completion handler closure provided by the UIApplicationDelegate `application:handleEventsForBackgroundURLSession:completionHandler:` method. By setting the background completion handler, the SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` closure implementation will automatically call the handler. If you need to handle your own events before the handler is called, then you need to override the SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` and manually call the handler when finished. `nil` by default. */ public var backgroundCompletionHandler: (() -> Void)? // MARK: - Lifecycle /** Initializes the `Manager` instance with the specified configuration, delegate and server trust policy. - parameter configuration: The configuration used to construct the managed session. `URLSessionConfiguration.defaultSessionConfiguration()` by default. - parameter delegate: The delegate used when initializing the session. `SessionDelegate()` by default. - parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust challenges. `nil` by default. - returns: The new `Manager` instance. */ public init( configuration: URLSessionConfiguration = URLSessionConfiguration.default(), delegate: SessionDelegate = SessionDelegate(), serverTrustPolicyManager: ServerTrustPolicyManager? = nil) { self.delegate = delegate self.session = URLSession(configuration: configuration, delegate: delegate, delegateQueue: nil) commonInit(serverTrustPolicyManager: serverTrustPolicyManager) } /** Initializes the `Manager` instance with the specified session, delegate and server trust policy. - parameter session: The URL session. - parameter delegate: The delegate of the URL session. Must equal the URL session's delegate. - parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust challenges. `nil` by default. - returns: The new `Manager` instance if the URL session's delegate matches the delegate parameter. */ public init?( session: URLSession, delegate: SessionDelegate, serverTrustPolicyManager: ServerTrustPolicyManager? = nil) { guard delegate === session.delegate else { return nil } self.delegate = delegate self.session = session commonInit(serverTrustPolicyManager: serverTrustPolicyManager) } private func commonInit(serverTrustPolicyManager: ServerTrustPolicyManager?) { session.serverTrustPolicyManager = serverTrustPolicyManager delegate.sessionDidFinishEventsForBackgroundURLSession = { [weak self] session in guard let strongSelf = self else { return } DispatchQueue.main.async { strongSelf.backgroundCompletionHandler?() } } } deinit { session.invalidateAndCancel() } // MARK: - Request /** Creates a request for the specified method, URL string, parameters, parameter encoding and headers. - parameter method: The HTTP method. - parameter URLString: The URL string. - parameter parameters: The parameters. `nil` by default. - parameter encoding: The parameter encoding. `.URL` by default. - parameter headers: The HTTP headers. `nil` by default. - returns: The created request. */ public func request( method: Method, _ URLString: URLStringConvertible, parameters: [String: AnyObject]? = nil, encoding: ParameterEncoding = .URL, headers: [String: String]? = nil) -> Request { let mutableURLRequest = urlRequest(method: method, URLString, headers: headers) let encodedURLRequest = encoding.encode(urlRequest: mutableURLRequest, parameters: parameters).0 return request(urlRequest: encodedURLRequest) } /** Creates a request for the specified URL request. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - parameter URLRequest: The URL request - returns: The created request. */ public func request(urlRequest: URLRequestConvertible) -> Request { var dataTask: URLSessionDataTask! queue.sync { dataTask = self.session.dataTask(with: urlRequest.urlRequest) } let request = Request(session: session, task: dataTask) delegate[request.delegate.task] = request.delegate if startRequestsImmediately { request.resume() } return request } // MARK: - SessionDelegate /** Responsible for handling all delegate callbacks for the underlying session. */ public class SessionDelegate: NSObject, URLSessionDelegate, URLSessionTaskDelegate, URLSessionDataDelegate, URLSessionDownloadDelegate { private var subdelegates: [Int: Request.TaskDelegate] = [:] private let subdelegateQueue = DispatchQueue(label: "", attributes: .concurrent, target: nil)//dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT) /// Access the task delegate for the specified task in a thread-safe manner. public subscript(task: URLSessionTask) -> Request.TaskDelegate? { get { var subdelegate: Request.TaskDelegate? subdelegateQueue.sync() { subdelegate = self.subdelegates[task.taskIdentifier] } return subdelegate } set { if #available(OSXApplicationExtension 10.10, *) { subdelegateQueue.async(group: nil, qos: DispatchQoS.default, flags: DispatchWorkItemFlags.barrier) { self.subdelegates[task.taskIdentifier] = newValue } } else { // ??? // Fallback on earlier versions } } } /** Initializes the `SessionDelegate` instance. - returns: The new `SessionDelegate` instance. */ public override init() { super.init() } // MARK: - URLSessionDelegate // MARK: Override Closures /// Overrides default behavior for URLSessionDelegate method `urlSession:didBecomeInvalidWithError:`. public var sessionDidBecomeInvalidWithError: ((URLSession, NSError?) -> Void)? /// Overrides default behavior for URLSessionDelegate method `urlSession:didReceiveChallenge:completionHandler:`. public var sessionDidReceiveChallenge: ((URLSession, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))? /// Overrides all behavior for URLSessionDelegate method `urlSession:didReceiveChallenge:completionHandler:` and requires the caller to call the `completionHandler`. public var sessionDidReceiveChallengeWithCompletion: ((URLSession, URLAuthenticationChallenge, (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) -> Void)? /// Overrides default behavior for URLSessionDelegate method `URLSessionDidFinishEventsForBackgroundURLSession:`. public var sessionDidFinishEventsForBackgroundURLSession: ((URLSession) -> Void)? // MARK: Delegate Methods /** Tells the delegate that the session has been invalidated. - parameter session: The session object that was invalidated. - parameter error: The error that caused invalidation, or nil if the invalidation was explicit. */ public func urlSession(_ session: URLSession, didBecomeInvalidWithError error: NSError?) { sessionDidBecomeInvalidWithError?(session, error) } /** Requests credentials from the delegate in response to a session-level authentication request from the remote server. - parameter session: The session containing the task that requested authentication. - parameter challenge: An object that contains the request for authentication. - parameter completionHandler: A handler that your delegate method must call providing the disposition and credential. */ public func urlSession( _ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: ((URLSession.AuthChallengeDisposition, URLCredential?) -> Void)) { guard sessionDidReceiveChallengeWithCompletion == nil else { sessionDidReceiveChallengeWithCompletion?(session, challenge, completionHandler) return } var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling var credential: URLCredential? if let sessionDidReceiveChallenge = sessionDidReceiveChallenge { (disposition, credential) = sessionDidReceiveChallenge(session, challenge) } else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { let host = challenge.protectionSpace.host if let serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicyForHost(host: host), serverTrust = challenge.protectionSpace.serverTrust { if serverTrustPolicy.evaluateServerTrust(serverTrust: serverTrust, isValidForHost: host) { disposition = .useCredential credential = URLCredential(trust: serverTrust) } else { disposition = .cancelAuthenticationChallenge } } } completionHandler(disposition, credential) } /** Tells the delegate that all messages enqueued for a session have been delivered. - parameter session: The session that no longer has any outstanding requests. */ public func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) { sessionDidFinishEventsForBackgroundURLSession?(session) } // MARK: - URLSessionTaskDelegate // MARK: Override Closures /// Overrides default behavior for URLSessionTaskDelegate method `urlSession:task:willPerformHTTPRedirection:newRequest:completionHandler:`. public var taskWillPerformHTTPRedirection: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> URLRequest?)? /// Overrides all behavior for URLSessionTaskDelegate method `urlSession:task:willPerformHTTPRedirection:newRequest:completionHandler:` and /// requires the caller to call the `completionHandler`. public var taskWillPerformHTTPRedirectionWithCompletion: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest, (URLRequest?) -> Void) -> Void)? /// Overrides default behavior for URLSessionTaskDelegate method `urlSession:task:didReceiveChallenge:completionHandler:`. public var taskDidReceiveChallenge: ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))? /// Overrides all behavior for URLSessionTaskDelegate method `urlSession:task:didReceiveChallenge:completionHandler:` and /// requires the caller to call the `completionHandler`. public var taskDidReceiveChallengeWithCompletion: ((URLSession, URLSessionTask, URLAuthenticationChallenge, (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) -> Void)? /// Overrides default behavior for URLSessionTaskDelegate method `urlSession:session:task:needNewBodyStream:`. public var taskNeedNewBodyStream: ((URLSession, URLSessionTask) -> InputStream?)? /// Overrides all behavior for URLSessionTaskDelegate method `urlSession:session:task:needNewBodyStream:` and /// requires the caller to call the `completionHandler`. public var taskNeedNewBodyStreamWithCompletion: ((URLSession, URLSessionTask, (InputStream?) -> Void) -> Void)? /// Overrides default behavior for URLSessionTaskDelegate method `urlSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:`. public var taskDidSendBodyData: ((URLSession, URLSessionTask, Int64, Int64, Int64) -> Void)? /// Overrides default behavior for URLSessionTaskDelegate method `urlSession:task:didCompleteWithError:`. public var taskDidComplete: ((URLSession, URLSessionTask, NSError?) -> Void)? // MARK: Delegate Methods /** Tells the delegate that the remote server requested an HTTP redirect. - parameter session: The session containing the task whose request resulted in a redirect. - parameter task: The task whose request resulted in a redirect. - parameter response: An object containing the server’s response to the original request. - parameter request: A URL request object filled out with the new location. - parameter completionHandler: A closure that your handler should call with either the value of the request parameter, a modified URL request object, or NULL to refuse the redirect and return the body of the redirect response. */ public func urlSession( _ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: (URLRequest?) -> Void) { guard taskWillPerformHTTPRedirectionWithCompletion == nil else { taskWillPerformHTTPRedirectionWithCompletion?(session, task, response, request, completionHandler) return } var redirectRequest: URLRequest? = request if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection { redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request) } completionHandler(redirectRequest) } /** Requests credentials from the delegate in response to an authentication request from the remote server. - parameter session: The session containing the task whose request requires authentication. - parameter task: The task whose request requires authentication. - parameter challenge: An object that contains the request for authentication. - parameter completionHandler: A handler that your delegate method must call providing the disposition and credential. */ public func urlSession( _ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { guard taskDidReceiveChallengeWithCompletion == nil else { taskDidReceiveChallengeWithCompletion?(session, task, challenge, completionHandler) return } if let taskDidReceiveChallenge = taskDidReceiveChallenge { let result = taskDidReceiveChallenge(session, task, challenge) completionHandler(result.0, result.1) } else if let delegate = self[task] { delegate.urlSession( session, task: task, didReceiveChallenge: challenge, completionHandler: completionHandler ) } else { urlSession(session, didReceive: challenge, completionHandler: completionHandler) } } /** Tells the delegate when a task requires a new request body stream to send to the remote server. - parameter session: The session containing the task that needs a new body stream. - parameter task: The task that needs a new body stream. - parameter completionHandler: A completion handler that your delegate method should call with the new body stream. */ public func urlSession( _ session: URLSession, task: URLSessionTask, needNewBodyStream completionHandler: (InputStream?) -> Void) { guard taskNeedNewBodyStreamWithCompletion == nil else { taskNeedNewBodyStreamWithCompletion?(session, task, completionHandler) return } if let taskNeedNewBodyStream = taskNeedNewBodyStream { completionHandler(taskNeedNewBodyStream(session, task)) } else if let delegate = self[task] { delegate.urlSession(session, task: task, needNewBodyStream: completionHandler) } } /** Periodically informs the delegate of the progress of sending body content to the server. - parameter session: The session containing the data task. - parameter task: The data task. - parameter bytesSent: The number of bytes sent since the last time this delegate method was called. - parameter totalBytesSent: The total number of bytes sent so far. - parameter totalBytesExpectedToSend: The expected length of the body data. */ public func urlSession( _ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) { if let taskDidSendBodyData = taskDidSendBodyData { taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend) } else if let delegate = self[task] as? Request.UploadTaskDelegate { delegate.urlSession( session: session, task: task, didSendBodyData: bytesSent, totalBytesSent: totalBytesSent, totalBytesExpectedToSend: totalBytesExpectedToSend ) } } /** Tells the delegate that the task finished transferring data. - parameter session: The session containing the task whose request finished transferring data. - parameter task: The task whose request finished transferring data. - parameter error: If an error occurred, an error object indicating how the transfer failed, otherwise nil. */ public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: NSError?) { if let taskDidComplete = taskDidComplete { taskDidComplete(session, task, error) } else if let delegate = self[task] { delegate.urlSession(session, task: task, didCompleteWithError: error) } NotificationCenter.default().post(name: Notifications.Task.DidComplete, object: task) self[task] = nil } // MARK: - URLSessionDataDelegate // MARK: Override Closures /// Overrides default behavior for URLSessionDataDelegate method `urlSession:dataTask:didReceiveResponse:completionHandler:`. public var dataTaskDidReceiveResponse: ((URLSession, URLSessionDataTask, URLResponse) -> URLSession.ResponseDisposition)? /// Overrides all behavior for URLSessionDataDelegate method `urlSession:dataTask:didReceiveResponse:completionHandler:` and /// requires caller to call the `completionHandler`. public var dataTaskDidReceiveResponseWithCompletion: ((URLSession, URLSessionDataTask, URLResponse, (URLSession.ResponseDisposition) -> Void) -> Void)? /// Overrides default behavior for URLSessionDataDelegate method `urlSession:dataTask:didBecomeDownloadTask:`. public var dataTaskDidBecomeDownloadTask: ((URLSession, URLSessionDataTask, URLSessionDownloadTask) -> Void)? /// Overrides default behavior for URLSessionDataDelegate method `urlSession:dataTask:didReceiveData:`. public var dataTaskDidReceiveData: ((URLSession, URLSessionDataTask, NSData) -> Void)? /// Overrides default behavior for URLSessionDataDelegate method `urlSession:dataTask:willCacheResponse:completionHandler:`. public var dataTaskWillCacheResponse: ((URLSession, URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)? /// Overrides all behavior for URLSessionDataDelegate method `urlSession:dataTask:willCacheResponse:completionHandler:` and /// requires caller to call the `completionHandler`. public var dataTaskWillCacheResponseWithCompletion: ((URLSession, URLSessionDataTask, CachedURLResponse, (CachedURLResponse?) -> Void) -> Void)? // MARK: Delegate Methods /** Tells the delegate that the data task received the initial reply (headers) from the server. - parameter session: The session containing the data task that received an initial reply. - parameter dataTask: The data task that received an initial reply. - parameter response: A URL response object populated with headers. - parameter completionHandler: A completion handler that your code calls to continue the transfer, passing a constant to indicate whether the transfer should continue as a data task or should become a download task. */ public func urlSession( _ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: (URLSession.ResponseDisposition) -> Void) { guard dataTaskDidReceiveResponseWithCompletion == nil else { dataTaskDidReceiveResponseWithCompletion?(session, dataTask, response, completionHandler) return } var disposition: URLSession.ResponseDisposition = .allow if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse { disposition = dataTaskDidReceiveResponse(session, dataTask, response) } completionHandler(disposition) } /** Tells the delegate that the data task was changed to a download task. - parameter session: The session containing the task that was replaced by a download task. - parameter dataTask: The data task that was replaced by a download task. - parameter downloadTask: The new download task that replaced the data task. */ public func urlSession( _ session: URLSession, dataTask: URLSessionDataTask, didBecome downloadTask: URLSessionDownloadTask) { if let dataTaskDidBecomeDownloadTask = dataTaskDidBecomeDownloadTask { dataTaskDidBecomeDownloadTask(session, dataTask, downloadTask) } else { let downloadDelegate = Request.DownloadTaskDelegate(task: downloadTask) self[downloadTask] = downloadDelegate } } /** Tells the delegate that the data task has received some of the expected data. - parameter session: The session containing the data task that provided data. - parameter dataTask: The data task that provided data. - parameter data: A data object containing the transferred data. */ public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { if let dataTaskDidReceiveData = dataTaskDidReceiveData { dataTaskDidReceiveData(session, dataTask, data) } else if let delegate = self[dataTask] as? Request.DataTaskDelegate { delegate.urlSession(session, dataTask: dataTask, didReceive: data as Data) } } /** Asks the delegate whether the data (or upload) task should store the response in the cache. - parameter session: The session containing the data (or upload) task. - parameter dataTask: The data (or upload) task. - parameter proposedResponse: The default caching behavior. This behavior is determined based on the current caching policy and the values of certain received headers, such as the Pragma and Cache-Control headers. - parameter completionHandler: A block that your handler must call, providing either the original proposed response, a modified version of that response, or NULL to prevent caching the response. If your delegate implements this method, it must call this completion handler; otherwise, your app leaks memory. */ public func urlSession( _ session: URLSession, dataTask: URLSessionDataTask, willCacheResponse proposedResponse: CachedURLResponse, completionHandler: (CachedURLResponse?) -> Void) { guard dataTaskWillCacheResponseWithCompletion == nil else { dataTaskWillCacheResponseWithCompletion?(session, dataTask, proposedResponse, completionHandler) return } if let dataTaskWillCacheResponse = dataTaskWillCacheResponse { completionHandler(dataTaskWillCacheResponse(session, dataTask, proposedResponse)) } else if let delegate = self[dataTask] as? Request.DataTaskDelegate { delegate.urlSession( session, dataTask: dataTask, willCacheResponse: proposedResponse, completionHandler: completionHandler ) } else { completionHandler(proposedResponse) } } // MARK: - URLSessionDownloadDelegate // MARK: Override Closures /// Overrides default behavior for URLSessionDownloadDelegate method `urlSession:downloadTask:didFinishDownloadingToURL:`. public var downloadTaskDidFinishDownloadingToURL: ((URLSession, URLSessionDownloadTask, URL) -> Void)? /// Overrides default behavior for URLSessionDownloadDelegate method `urlSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:`. public var downloadTaskDidWriteData: ((URLSession, URLSessionDownloadTask, Int64, Int64, Int64) -> Void)? /// Overrides default behavior for URLSessionDownloadDelegate method `urlSession:downloadTask:didResumeAtOffset:expectedTotalBytes:`. public var downloadTaskDidResumeAtOffset: ((URLSession, URLSessionDownloadTask, Int64, Int64) -> Void)? // MARK: Delegate Methods /** Tells the delegate that a download task has finished downloading. - parameter session: The session containing the download task that finished. - parameter downloadTask: The download task that finished. - parameter location: A file URL for the temporary file. Because the file is temporary, you must either open the file for reading or move it to a permanent location in your app’s sandbox container directory before returning from this delegate method. */ public func urlSession( _ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { if let downloadTaskDidFinishDownloadingToURL = downloadTaskDidFinishDownloadingToURL { downloadTaskDidFinishDownloadingToURL(session, downloadTask, location) } else if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate { delegate.urlSession(session, downloadTask: downloadTask, didFinishDownloadingTo: location) } } /** Periodically informs the delegate about the download’s progress. - parameter session: The session containing the download task. - parameter downloadTask: The download task. - parameter bytesWritten: The number of bytes transferred since the last time this delegate method was called. - parameter totalBytesWritten: The total number of bytes transferred so far. - parameter totalBytesExpectedToWrite: The expected length of the file, as provided by the Content-Length header. If this header was not provided, the value is `URLSessionTransferSizeUnknown`. */ public func urlSession( _ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { if let downloadTaskDidWriteData = downloadTaskDidWriteData { downloadTaskDidWriteData(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) } else if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate { delegate.urlSession( session, downloadTask: downloadTask, didWriteData: bytesWritten, totalBytesWritten: totalBytesWritten, totalBytesExpectedToWrite: totalBytesExpectedToWrite ) } } /** Tells the delegate that the download task has resumed downloading. - parameter session: The session containing the download task that finished. - parameter downloadTask: The download task that resumed. See explanation in the discussion. - parameter fileOffset: If the file's cache policy or last modified date prevents reuse of the existing content, then this value is zero. Otherwise, this value is an integer representing the number of bytes on disk that do not need to be retrieved again. - parameter expectedTotalBytes: The expected length of the file, as provided by the Content-Length header. If this header was not provided, the value is URLSessionTransferSizeUnknown. */ public func urlSession( _ session: URLSession, downloadTask: URLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) { if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset { downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes) } else if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate { delegate.urlSession( session, downloadTask: downloadTask, didResumeAtOffset: fileOffset, expectedTotalBytes: expectedTotalBytes ) } } // MARK: - URLSessionStreamDelegate var _streamTaskReadClosed: Any? var _streamTaskWriteClosed: Any? var _streamTaskBetterRouteDiscovered: Any? var _streamTaskDidBecomeInputStream: Any? // MARK: - NSObject public override func responds(to selector: Selector) -> Bool { #if !os(OSX) if selector == #selector(URLSessionDelegate.urlSessionDidFinishEvents(forBackgroundURLSession:)) { return sessionDidFinishEventsForBackgroundURLSession != nil } #endif switch selector { case #selector(URLSessionDelegate.urlSession(_:didBecomeInvalidWithError:)): return sessionDidBecomeInvalidWithError != nil case #selector(URLSessionDelegate.urlSession(_:didReceive:completionHandler:)): return (sessionDidReceiveChallenge != nil || sessionDidReceiveChallengeWithCompletion != nil) case #selector(URLSessionTaskDelegate.urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)): return (taskWillPerformHTTPRedirection != nil || taskWillPerformHTTPRedirectionWithCompletion != nil) case #selector(URLSessionDataDelegate.urlSession(_:dataTask:didReceive:completionHandler:)): return (dataTaskDidReceiveResponse != nil || dataTaskDidReceiveResponseWithCompletion != nil) default: return self.dynamicType.instancesRespond(to: selector) } } } }
mit
f56ac2fe5fb1e342734b52841eb7e039
49.06422
188
0.644546
6.605395
false
false
false
false
larryhou/swift
SpriteKit/SpriteKit/NinjaPresenter.swift
1
2157
// // NinjaPresenter.swift // SpriteKit // // Created by larryhou on 25/5/15. // Copyright (c) 2015 larryhou. All rights reserved. // import Foundation import UIKit import SpriteKit class NinjaPresenter: SKSpriteNode { var atlas: SKTextureAtlas! var actionInfos: [NinjaActionInfo]! var data: NinjaActionInfo! var frameIndex: Int = 0 var frameCount: Int = 0 var layers: [SKSpriteNode]! convenience init(atlas: SKTextureAtlas, actionInfos: [NinjaActionInfo]) { self.init(color: UIColor.clearColor(), size: CGSize(width: 1, height: 1)) self.actionInfos = actionInfos self.atlas = atlas } func playNextAction() { let index = (data.index + 1) % actionInfos.count play(actionInfos[index].name) } func play(name: String) -> Bool { removeAllChildren() data = nil for i in 0 ..< actionInfos.count { if name == actionInfos[i].name { data = actionInfos[i] break } } if data == nil { return false } layers = [] for i in 0..<data.layers.count { var list: [SKAction] = [] var sprite = SKSpriteNode() addChild(sprite) var index: Int = 0 let layerInfo = data.layers[i] for j in 0 ..< layerInfo.length { if j >= layerInfo.frames[index].position { index++ } let frame = layerInfo.frames[index] if frame.texture != "" { list.append(SKAction.setTexture(atlas.textureNamed(frame.texture), resize: true)) list.append(SKAction.runBlock({ sprite.position.x = CGFloat(frame.x) sprite.position.y = CGFloat(frame.y) })) } else { list.append(SKAction.waitForDuration(1/30)) } } list.append(SKAction.removeFromParent()) sprite.runAction(SKAction.sequence(list)) } return true } }
mit
0ba3895d18ea5ab68cbd7a8930cc073d
25.9625
101
0.52573
4.512552
false
false
false
false
USAssignmentWarehouse/EnglishNow
EnglishNow/Controller/Conversation/MyConversationVC.swift
1
3389
// // MyConversationVC.swift // EnglishNow // // Created by Nha T.Tran on 5/21/17. // Copyright © 2017 IceTeaViet. All rights reserved. // import UIKit import Cosmos class MyConversationVC: UIViewController { @IBOutlet weak var table: UITableView! @IBOutlet var btnMenu: UIBarButtonItem! override func viewDidLoad() { super.viewDidLoad() initShow() if revealViewController() != nil { btnMenu.target = self.revealViewController() btnMenu.action = "revealToggle:" self.view.addGestureRecognizer(revealViewController().panGestureRecognizer()) Singleton.sharedInstance.conversationViewController = self } // Do any additional setup after loading the view. } func initShow(){ table.delegate = self table.dataSource = self table.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. let backItem = UIBarButtonItem() backItem.title = "Back" navigationItem.backBarButtonItem = backItem let nc = segue.destination as! UINavigationController let vc = nc.topViewController as! DetailViewController let index = table.indexPathForSelectedRow?.row vc.review = User.current.reviews[index!] } } extension MyConversationVC: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: CellIdentifier.HistoryCell, for: indexPath ) as! HistoryCell cell.layer.borderWidth = 1 cell.layer.borderColor = UIColor(red: 213/255,green: 216/255,blue: 220/255,alpha: 1.0).cgColor cell.layer.cornerRadius = 15 var rating: Double = User.current.reviews[indexPath.row].rating if rating == 0 { rating = Double(arc4random_uniform(5) + 1) User.current.reviews[indexPath.row].rating = rating } cell.cosmos.rating = rating cell.nameLabel?.text = User.current.reviews[indexPath.row].partner var profileImg: String = User.current.reviews[indexPath.row].photoPartner if profileImg.isEmpty { cell.profileImageView?.image = UIImage(named: ResourceName.coverPlaceholder) } else { cell.profileImageView.setImageWith(URL(string: profileImg)!) } return cell } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return User.current.reviews.count } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { performSegue(withIdentifier: SegueIdentifier.SegueDetail, sender: self) } }
apache-2.0
76cdfd03df529aa2743d0d6e5c30ba3b
33.222222
125
0.656139
5.110106
false
false
false
false
sashohadz/swift
photoStories/photoStories/photoStories/StoriesTableViewController.swift
1
3715
// // StoriesTableViewController.swift // photoStories // // Created by Sasho Hadzhiev on 2/21/17. // Copyright © 2017 Sasho Hadzhiev. All rights reserved. // import UIKit import Leanplum class StoriesTableViewController: UITableViewController, StoryTableViewCellDelegate { @IBOutlet weak var logoutButton: UIBarButtonItem! let storiesData:[[StoryDataType:String]] = [ [.storyImage:"moon", .storyName:"stays", .storyShortDetail:"stays"], [.storyImage:"places", .storyName:"places", .storyShortDetail:"places"], [.storyImage:"rewards", .storyName:"rewards", .storyShortDetail:"rewards"], [.storyImage:"card", .storyName:"Payment", .storyShortDetail:"Payment"], [.storyImage:"star", .storyName:"Favourites", .storyShortDetail:"Favourites"] ] override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(_ animated: Bool) { var userLoggedIn:Bool! if let autoUserLoginEnabled = UserDefaults.standard.object(forKey: UserDefaultKeys.autoLoginEnabled.rawValue) { userLoggedIn = autoUserLoginEnabled as? Bool } else { userLoggedIn = false } if (!userLoggedIn) { self.logoutButton.title = "Login" } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.storiesData.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "StoryCellIdentifier", for: indexPath) as! StoryTableViewCell let data = self.storiesData[indexPath.row] cell.storyImageView.image = UIImage(named: data[.storyImage]!) cell.storyDetailLabel.text = data[.storyName] return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let selectedCell = tableView.cellForRow(at: indexPath) as! StoryTableViewCell let storyShortText = selectedCell.storyDetailLabel.text print("Track Selected item with item: \(storyShortText ?? "")") Leanplum.track("Selected item", withValue: Double(selectedCell.isBookmarked.hashValue), andParameters: ["item":storyShortText!]) self.performSegue(withIdentifier: "ToStoryDetailsSegue", sender: nil) tableView.deselectRow(at: indexPath, animated: true) } @IBAction func logoutButtonPressed(_ sender: UIBarButtonItem) { UserDefaults.standard.set(false, forKey: UserDefaultKeys.autoLoginEnabled.rawValue) self.modalTransitionStyle = .crossDissolve self.present(UIStoryboard.init(name: "Main", bundle: nil).instantiateInitialViewController()!, animated: true, completion: nil) } func didPressBookmarkButton(inCell:StoryTableViewCell) { inCell.isBookmarked = !inCell.isBookmarked } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.destination is DetailViewController { let destination = segue.destination as! DetailViewController let imageName = self.storiesData[self.tableView.indexPathForSelectedRow!.row][.storyImage] destination.loadViewIfNeeded() destination.largerImageView.image = UIImage(named: imageName!) } } }
mit
45324cd2996532f97004acd4ebcd0447
35.772277
136
0.667474
5.07377
false
false
false
false
dadalar/DDSpiderChart
DDSpiderChart/Classes/DrawableString.swift
1
1501
// // DrawableString.swift // Pods // // Created by Deniz Adalar on 01/05/2017. // // import Foundation public protocol DrawableString { func size() -> CGSize func drawDrawable(with rect: CGRect) } extension NSString: DrawableString { public func drawDrawable(with rect: CGRect) { let style = NSMutableParagraphStyle() style.lineBreakMode = .byClipping style.alignment = .center #if swift(>=4.2) draw(with: rect, options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.paragraphStyle: style], context: nil) #elseif swift(>=4.0) draw(with: rect, options: .usesLineFragmentOrigin, attributes: [NSAttributedStringKey.paragraphStyle: style], context: nil) #else draw(with: rect, options: .usesLineFragmentOrigin, attributes: [NSParagraphStyleAttributeName: style], context: nil) #endif } public func size() -> CGSize { #if swift(>=4.0) return size(withAttributes: nil) #else return size(attributes: nil) #endif } } extension String: DrawableString { public func drawDrawable(with rect: CGRect) { (self as NSString).drawDrawable(with: rect) } public func size() -> CGSize { return (self as NSString).size() } } extension NSAttributedString: DrawableString { public func drawDrawable(with rect: CGRect) { draw(with: rect, options: .usesLineFragmentOrigin, context: nil) } }
mit
3065e42be5b48cc0142a2a5c57c6d59f
23.209677
132
0.648901
4.313218
false
false
false
false
jonesgithub/MLSwiftBasic
MLSwiftBasic/Classes/Refresh/ZLSwiftHeadView.swift
8
11283
// // ZLSwiftHeadView.swift // ZLSwiftRefresh // // Created by 张磊 on 15-3-6. // Copyright (c) 2015年 com.zixue101.www. All rights reserved. // import UIKit var KVOContext = "" let imageViewW:CGFloat = 50 let labelTextW:CGFloat = 150 public class ZLSwiftHeadView: UIView { private var headLabel: UILabel = UILabel() var headImageView : UIImageView = UIImageView() var scrollView:UIScrollView = UIScrollView() var customAnimation:Bool = false var pullImages:[UIImage] = [UIImage]() var animationStatus:HeaderViewRefreshAnimationStatus? var activityView: UIActivityIndicatorView? var nowLoading:Bool = false{ willSet { if (newValue == true){ self.nowLoading = newValue self.scrollView.contentOffset = CGPointMake(0, -ZLSwithRefreshHeadViewHeight)//UIEdgeInsetsMake(ZLSwithRefreshHeadViewHeight, 0, self.scrollView.contentInset.bottom, 0) } } } var action: (() -> ()) = {} var nowAction: (() -> ()) = {} private var refreshTempAction:(() -> Void) = {} convenience init(action :(() -> ()), frame: CGRect) { self.init(frame: frame) self.action = action self.nowAction = action } override init(frame: CGRect) { super.init(frame: frame) self.setupUI() } public required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } var imgName:String { set { if(!self.customAnimation){ // 默认动画 if (self.animationStatus != .headerViewRefreshArrowAnimation){ self.headImageView.image = self.imageBundleWithNamed(named: "dropdown_anim__000\(newValue)") }else{ // 箭头动画 self.headImageView.image = self.imageBundleWithNamed(named: "arrow") } }else{ var image = self.pullImages[newValue.toInt()!] self.headImageView.image = image } } get { return self.imgName } } func setupUI(){ var headImageView:UIImageView = UIImageView(frame: CGRectZero) headImageView.contentMode = .Center headImageView.clipsToBounds = true; self.addSubview(headImageView) self.headImageView = headImageView var headLabel:UILabel = UILabel(frame: self.frame) headLabel.text = ZLSwithRefreshHeadViewText headLabel.textAlignment = .Center headLabel.clipsToBounds = true; self.addSubview(headLabel) self.headLabel = headLabel var activityView = UIActivityIndicatorView(activityIndicatorStyle: .Gray) self.addSubview(activityView) self.activityView = activityView } func startAnimation(){ if (self.activityView?.isAnimating() == true){ return ; } if (!self.customAnimation){ if (self.animationStatus != .headerViewRefreshArrowAnimation){ var results:[AnyObject] = [] for i in 1..<4{ var image:UIImage = self.imageBundleWithNamed(named: "dropdown_loading_0\(i)") if image.size.height > 0 && image.size.width > 0 { results.append(image) } } self.headImageView.animationImages = results as [AnyObject]? self.headImageView.animationDuration = 0.6 self.activityView?.alpha = 0.0 }else{ self.activityView?.alpha = 1.0 self.headImageView.hidden = true } self.activityView?.startAnimating() }else{ var duration:Double = Double(self.pullImages.count) * 0.1 self.headImageView.animationDuration = duration } self.headLabel.text = ZLSwithRefreshLoadingText if (self.animationStatus != .headerViewRefreshArrowAnimation){ self.headImageView.animationRepeatCount = 0 self.headImageView.startAnimating() } } func stopAnimation(){ self.nowLoading = false self.headLabel.text = ZLSwithRefreshHeadViewText UIView.animateWithDuration(0.25, animations: { () -> Void in if (abs(self.scrollView.contentOffset.y) >= self.getNavigationHeight() + ZLSwithRefreshHeadViewHeight){ self.scrollView.contentInset = UIEdgeInsetsMake(self.getNavigationHeight(), 0, self.scrollView.contentInset.bottom, 0) }else{ self.scrollView.contentInset = UIEdgeInsetsMake(self.getNavigationHeight(), 0, self.scrollView.contentInset.bottom, 0) } }) if (self.animationStatus == .headerViewRefreshArrowAnimation){ self.headImageView.hidden = false self.activityView?.alpha = 0.0 }else{ self.activityView?.alpha = 1.0 self.headImageView.stopAnimating() } self.activityView?.stopAnimating() } public override func layoutSubviews() { super.layoutSubviews() headLabel.sizeToFit() headLabel.frame = CGRectMake((self.frame.size.width - labelTextW) / 2, -self.scrollView.frame.origin.y, labelTextW, self.frame.size.height) headImageView.frame = CGRectMake(headLabel.frame.origin.x - imageViewW - 5, headLabel.frame.origin.y, imageViewW, self.frame.size.height) self.activityView?.frame = headImageView.frame } public override func willMoveToSuperview(newSuperview: UIView!) { superview?.removeObserver(self, forKeyPath: contentOffsetKeyPath, context: &KVOContext) if (newSuperview != nil && newSuperview.isKindOfClass(UIScrollView)) { self.scrollView = newSuperview as! UIScrollView newSuperview.addObserver(self, forKeyPath: contentOffsetKeyPath, options: .Initial, context: &KVOContext) } } //MARK: KVO methods public override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<()>) { if (self.action == nil) { return; } if (self.activityView?.isAnimating() == true){ return ; } var scrollView:UIScrollView = self.scrollView // change contentOffset var scrollViewContentOffsetY:CGFloat = scrollView.contentOffset.y var height = ZLSwithRefreshHeadViewHeight if (ZLSwithRefreshHeadViewHeight > animations){ height = animations } if (scrollViewContentOffsetY + self.getNavigationHeight() != 0 && scrollViewContentOffsetY <= -height - scrollView.contentInset.top + 20) { if (self.animationStatus == .headerViewRefreshArrowAnimation){ UIView.animateWithDuration(0.15, animations: { () -> Void in self.headImageView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI)) }) } // 上拉刷新 self.headLabel.text = ZLSwithRefreshRecoderText if scrollView.dragging == false && self.headImageView.isAnimating() == false{ if refreshTempAction != nil { refreshStatus = .Refresh self.startAnimation() UIView.animateWithDuration(0.25, animations: { () -> Void in if scrollView.contentInset.top == 0 { scrollView.contentInset = UIEdgeInsetsMake(self.getNavigationHeight(), 0, scrollView.contentInset.bottom, 0) }else{ scrollView.contentInset = UIEdgeInsetsMake(ZLSwithRefreshHeadViewHeight + scrollView.contentInset.top, 0, scrollView.contentInset.bottom, 0) } }) if (nowLoading == true){ nowAction() nowAction = {} nowLoading = false }else{ refreshTempAction() refreshTempAction = {} } } } }else{ // 上拉刷新 if (nowLoading == true){ self.headLabel.text = ZLSwithRefreshLoadingText }else if(scrollView.dragging == true){ self.headLabel.text = ZLSwithRefreshHeadViewText } if (self.animationStatus == .headerViewRefreshArrowAnimation){ UIView.animateWithDuration(0.15, animations: { () -> Void in self.headImageView.transform = CGAffineTransformIdentity }) } refreshTempAction = self.action } // 上拉刷新 if (nowLoading == true){ self.headLabel.text = ZLSwithRefreshLoadingText } if (scrollViewContentOffsetY <= 0){ var v:CGFloat = scrollViewContentOffsetY + scrollView.contentInset.top if ((!self.customAnimation) && (v < -animations || v > animations)){ v = animations } if (self.customAnimation){ v *= CGFloat(CGFloat(self.pullImages.count) / ZLSwithRefreshHeadViewHeight) if (Int(abs(v)) > self.pullImages.count - 1){ v = CGFloat(self.pullImages.count - 1); } } if ((Int)(abs(v)) > 0){ self.imgName = "\((Int)(abs(v)))" } } } //MARK: getNavigaition Height -> delete func getNavigationHeight() -> CGFloat{ var vc = UIViewController() if self.getViewControllerWithView(self).isKindOfClass(UIViewController) == true { vc = self.getViewControllerWithView(self) as! UIViewController } var top = vc.navigationController?.navigationBar.frame.height if top == nil{ top = 0 } // iOS7 var offset:CGFloat = 20 if((UIDevice.currentDevice().systemVersion as NSString).floatValue < 7.0){ offset = 0 } return offset + top! } func getViewControllerWithView(vcView:UIView) -> AnyObject{ if( (vcView.nextResponder()?.isKindOfClass(UIViewController) ) == true){ return vcView.nextResponder() as! UIViewController } if(vcView.superview == nil){ return vcView } return self.getViewControllerWithView(vcView.superview!) } func imageBundleWithNamed(#named: String!) -> UIImage{ return UIImage(named: ZLSwiftRefreshBundleName.stringByAppendingPathComponent(named))! } deinit{ var scrollView = superview as? UIScrollView scrollView?.removeObserver(self, forKeyPath: contentOffsetKeyPath, context: &KVOContext) } }
mit
51ab965fba57694a32ca87ce92525d49
36.332226
184
0.568301
5.535468
false
false
false
false
varshylmobile/VMXMLParser
XMLParserTest/XMLParserTest/DetailView.swift
1
820
// // DetailView.swift // XMLParserTest // // Created by Jimmy Jose on 29/08/14. // Copyright (c) 2014 Varshyl Mobile Pvt. Ltd. All rights reserved. // import UIKit class DetailView : UIViewController{ @IBOutlet var textView:UITextView? = UITextView() var urlString:NSString! var text:NSString! override func viewDidLoad() { super.viewDidLoad() textView?.text = text as String } @IBAction func showInBrowser() { self.performSegueWithIdentifier("Webview", sender: nil) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) { let webViewController = segue.destinationViewController as! WebView webViewController.title = "WebView" webViewController.urlString = urlString! } }
mit
56166bfee5c8693dac4ef324fe5fd53a
23.878788
81
0.659756
4.852071
false
false
false
false
dwcares/GarageOS
iOS/GarageOS/DeepPressableButton.swift
1
1291
// // DeepPressableButton.swift // GarageOS // // Created by David Washington on 4/15/16. // Copyright © 2016 David Washington. All rights reserved. // import Foundation class DeepPressableButton: UIButton, DeepPressable { override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { for touch in touches{ print("% Touch pressure: \(touch.force/touch.maximumPossibleForce)") print("% shadow: \(3 - 3*(touch.force/touch.maximumPossibleForce))") self.layer.shadowOffset = CGSize(width: 0, height: 3 - 3*(touch.force/touch.maximumPossibleForce)) self.layer.shadowOpacity = 1 - 0.8*Float(touch.force/touch.maximumPossibleForce) } } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { print("Touches End") self.layer.shadowOffset = CGSize(width: 0, height: 3) self.layer.shadowOpacity = 0.8 super.touchesEnded(touches, with: event) } override internal func layoutSubviews() { super.layoutSubviews() self.layer.shadowOpacity = 0.8 self.layer.shadowRadius = 2.0 self.layer.shadowOffset = CGSize(width: 0, height: 3) } }
mit
94a5e32bf91bb8a915b363f2689b42a8
27.666667
110
0.615504
4.285714
false
false
false
false
melvitax/AFViewHelper
ViewHelperDemo tvOS/ViewController.swift
1
12001
// // ViewController.swift // ViewHelperDemo tvOS // // Created by Melvin Rivera on 9/16/16. // Copyright © 2016 All Forces. All rights reserved. // import UIKit let selectedAnimationKey = "selectedAnimation" let selectedEasingCurveKey = "selectedEasingCurve" class ViewController: UIViewController { var selectedAnimation: Int = 0 var selectedEasingCurve: Int = 0 @IBOutlet weak var mainBox: InspectableView! @IBOutlet weak var bigCircle: InspectableView! @IBOutlet weak var smallCircle: InspectableView! @IBOutlet weak var forceLabel: UILabel! @IBOutlet weak var durationLabel: UILabel! @IBOutlet weak var delayLabel: UILabel! @IBOutlet weak var scaleLabel: UILabel! @IBOutlet weak var rotateLabel: UILabel! @IBOutlet weak var dampingLabel: UILabel! @IBOutlet weak var velocityLabel: UILabel! @IBOutlet weak var xPointLabel: UILabel! @IBOutlet weak var yPointLabel: UILabel! @IBOutlet weak var animation: UIButton! @IBOutlet weak var curve: UIButton! struct AnimationProperty { var minValue:Float var maxValue:Float var defaultValue:Float var stepValue:Float init (min:Float, max:Float, defaultValue:Float, step:Float) { minValue = min maxValue = max self.defaultValue = defaultValue currentValue = defaultValue stepValue = step } var currentValue:Float { didSet { currentValue = max(min(currentValue, maxValue), minValue) } } var percentageValue:Float { get { return (currentValue - minValue) / (maxValue - minValue) } } } var force = AnimationProperty(min: 1, max: 5, defaultValue: 1, step: 1) var duration = AnimationProperty(min: 0.5, max: 5, defaultValue: 0.5, step: 0.5) var delay = AnimationProperty(min: 0, max: 5, defaultValue: 0, step: 0.5) var scale = AnimationProperty(min: 1, max: 5, defaultValue: 1, step: 1) var rotate = AnimationProperty(min: 0, max: 5, defaultValue: 0, step: 1) var damping = AnimationProperty(min: 0, max: 1, defaultValue: 0.7, step: 0.1) var velocity = AnimationProperty(min: 0, max: 1, defaultValue: 0.7, step: 0.1) var xPoint = AnimationProperty(min: -1000, max: 1000, defaultValue: 0, step: 50) var yPoint = AnimationProperty(min: -1000, max: 1000, defaultValue: 0, step: 50) override func viewDidLoad() { super.viewDidLoad() /* Setting up some views by code to demnstrate how to add a view with constraints. */ // Top Left Square let topLeftSquare = UIView(autoLayout:true) bigCircle.addSubview(topLeftSquare) topLeftSquare.backgroundColor = UIColor(white: 0.1, alpha: 1) topLeftSquare .left(to: bigCircle) .top(to: bigCircle) .width(to: bigCircle, attribute: .width, constant: 0, multiplier: 0.48) .height(to: topLeftSquare, attribute: .width) .layoutIfNeeded() // Top Right Square let topRightSquare = UIView(autoLayout:true) bigCircle.addSubview(topRightSquare) topRightSquare.backgroundColor = UIColor(white: 0.1, alpha: 1) topRightSquare .right(to: bigCircle) .top(to: bigCircle) .size(to: topLeftSquare) .layoutIfNeeded() // Bottom Left Square let bottomLeftSquare = UIView(autoLayout:true) bigCircle.addSubview(bottomLeftSquare) bottomLeftSquare.backgroundColor = UIColor(white: 0.1, alpha: 1) bottomLeftSquare .left(to: bigCircle) .bottom(to: bigCircle) .size(to: topLeftSquare) .layoutIfNeeded() // Bottom Right Square let bottomRightSquare = UIView(autoLayout:true) bigCircle.addSubview(bottomRightSquare) bottomRightSquare.backgroundColor = UIColor(white:0.1, alpha: 1) bottomRightSquare .right(to: bigCircle) .bottom(to: bigCircle) .size(to: topLeftSquare) .layoutIfNeeded() UserDefaults.standard.addObserver(self, forKeyPath: selectedAnimationKey, options: NSKeyValueObservingOptions.new, context: nil) UserDefaults.standard.addObserver(self, forKeyPath: selectedEasingCurveKey, options: NSKeyValueObservingOptions.new, context: nil) resetValues() } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if keyPath == selectedAnimationKey { updateAnimationUI() } else { updateEasingCurveUI() } animateView() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) layoutView() } func layoutView() { view.layoutIfNeeded() bigCircle.cornerRadius = bigCircle.width()/2 smallCircle.cornerRadius = smallCircle.width()/2 } @IBAction func resetValues(_ sender: AnyObject? = nil) { force.currentValue = force.defaultValue updateForceUI() duration.currentValue = duration.defaultValue updateDurationUI() delay.currentValue = delay.defaultValue updateDelayUI() scale.currentValue = scale.defaultValue updateScaleUI() rotate.currentValue = rotate.defaultValue updateRotateUI() damping.currentValue = damping.defaultValue updateDampingUI() velocity.currentValue = velocity.defaultValue updateVelocityUI() xPoint.currentValue = xPoint.defaultValue updateXPointUI() yPoint.currentValue = yPoint.defaultValue updateYPointUI() selectedAnimation = 0 selectedEasingCurve = 0 UserDefaults.standard.set(selectedAnimation, forKey: selectedAnimationKey) UserDefaults.standard.set(selectedEasingCurve, forKey: selectedAnimationKey) UserDefaults.standard.synchronize() updateAnimationUI() updateEasingCurveUI() } @IBAction func animateView(_ sender: AnyObject? = nil) { bigCircle.animate(AnimationType.allValues[selectedAnimation], curve: AnimationEasingCurve.allValues[selectedEasingCurve], duration: CGFloat(duration.currentValue), delay: CGFloat(delay.currentValue), force: CGFloat(force.currentValue), damping: CGFloat(damping.currentValue), velocity: CGFloat(velocity.currentValue), fromRotation: CGFloat(rotate.currentValue), fromScale: CGFloat(scale.currentValue), fromX: CGFloat(xPoint.currentValue), fromY: CGFloat(yPoint.currentValue)) } @IBAction func forceAction(sender: UIButton) { force.currentValue = sender.titleLabel!.text == "+" ? force.currentValue + force.stepValue : force.currentValue - force.stepValue updateForceUI() animateView() } func updateForceUI() { forceLabel.text = String(format: "%.1f", force.currentValue) } @IBAction func durationAction(sender: UIButton) { duration.currentValue = sender.titleLabel!.text == "+" ? duration.currentValue + duration.stepValue : duration.currentValue - duration.stepValue updateDurationUI() animateView() } func updateDurationUI() { durationLabel.text = String(format: "%.1f", duration.currentValue) } @IBAction func delayAction(sender: UIButton) { delay.currentValue = sender.titleLabel!.text == "+" ? delay.currentValue + delay.stepValue : delay.currentValue - delay.stepValue updateDelayUI() animateView() } func updateDelayUI() { delayLabel.text = String(format: "%.1f", delay.currentValue) } @IBAction func scaleAction(sender: UIButton) { scale.currentValue = sender.titleLabel!.text == "+" ? scale.currentValue + scale.stepValue : scale.currentValue - scale.stepValue updateScaleUI() animateView() } func updateScaleUI() { scaleLabel.text = String(format: "%.1f", scale.currentValue) } @IBAction func rotateAction(sender: UIButton) { rotate.currentValue = sender.titleLabel!.text == "+" ? rotate.currentValue + rotate.stepValue : rotate.currentValue - rotate.stepValue updateRotateUI() animateView() } func updateRotateUI() { rotateLabel.text = String(format: "%.1f", rotate.currentValue) } @IBAction func dampingAction(sender: UIButton) { damping.currentValue = sender.titleLabel!.text == "+" ? damping.currentValue + damping.stepValue : damping.currentValue - damping.stepValue updateDampingUI() animateView() } func updateDampingUI() { dampingLabel.text = String(format: "%.1f", damping.currentValue) } @IBAction func velocityAction(sender: UIButton) { velocity.currentValue = sender.titleLabel!.text == "+" ? velocity.currentValue + velocity.stepValue : velocity.currentValue - velocity.stepValue updateVelocityUI() animateView() } func updateVelocityUI() { velocityLabel.text = String(format: "%.1f", velocity.currentValue) } @IBAction func xAction(sender: UIButton) { xPoint.currentValue = sender.titleLabel!.text == "+" ? xPoint.currentValue + xPoint.stepValue : xPoint.currentValue - xPoint.stepValue updateXPointUI() animateView() } func updateXPointUI() { xPointLabel.text = String(format: "%.1f", xPoint.currentValue) } @IBAction func yAction(sender: UIButton) { yPoint.currentValue = sender.titleLabel!.text == "+" ? yPoint.currentValue + yPoint.stepValue : yPoint.currentValue - yPoint.stepValue updateYPointUI() animateView() } func updateYPointUI() { yPointLabel.text = String(format: "%.1f", yPoint.currentValue) } func updateAnimationUI() { selectedAnimation = UserDefaults.standard.integer(forKey: selectedAnimationKey) animation.setTitle("Animation: \(AnimationType.allValues[selectedAnimation]) ⋯", for: .normal) } func updateEasingCurveUI() { selectedEasingCurve = UserDefaults.standard.integer(forKey: selectedEasingCurveKey) curve.setTitle("Curve: \(AnimationEasingCurve.allValues[selectedEasingCurve]) ⋯", for: .normal) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let controller = segue.destination as! TableViewController if segue.identifier == "Animation" { controller.items = AnimationType.allValues.map { $0.description } controller.selected = selectedAnimation controller.title = selectedAnimationKey } else { controller.items = AnimationEasingCurve.allValues.map { $0.description } controller.selected = selectedEasingCurve controller.title = selectedEasingCurveKey } } func updateUIFromTableViewControllerAction(){ } @IBAction func unwindToThisViewController(segue: UIStoryboardSegue) { print("here") let controller = segue.source as! TableViewController if controller.title == selectedAnimationKey { selectedAnimation = controller.selected updateAnimationUI() } else { selectedEasingCurve = controller.selected updateEasingCurveUI() } } }
mit
7865a274d756f29f7145f3b82fc0d977
35.573171
152
0.630794
4.888346
false
false
false
false
justindarc/firefox-ios
Client/Frontend/Browser/BrowserViewController/BrowserViewController+KeyCommands.swift
1
7907
/* 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 Shared // Naming functions: use the suffix 'KeyCommand' for an additional level of namespacing (bug 1415830) extension BrowserViewController { @objc private func reloadTabKeyCommand() { UnifiedTelemetry.recordEvent(category: .action, method: .press, object: .keyCommand, extras: ["action": "reload"]) if let tab = tabManager.selectedTab, firefoxHomeViewController == nil { tab.reload() } } @objc private func goBackKeyCommand() { UnifiedTelemetry.recordEvent(category: .action, method: .press, object: .keyCommand, extras: ["action": "go-back"]) if let tab = tabManager.selectedTab, tab.canGoBack, firefoxHomeViewController == nil { tab.goBack() } } @objc private func goForwardKeyCommand() { UnifiedTelemetry.recordEvent(category: .action, method: .press, object: .keyCommand, extras: ["action": "go-forward"]) if let tab = tabManager.selectedTab, tab.canGoForward { tab.goForward() } } @objc private func findInPageKeyCommand() { UnifiedTelemetry.recordEvent(category: .action, method: .press, object: .keyCommand, extras: ["action": "find-in-page"]) if let tab = tabManager.selectedTab, firefoxHomeViewController == nil { self.tab(tab, didSelectFindInPageForSelection: "") } } @objc private func selectLocationBarKeyCommand() { UnifiedTelemetry.recordEvent(category: .action, method: .press, object: .keyCommand, extras: ["action": "select-location-bar"]) scrollController.showToolbars(animated: true) urlBar.tabLocationViewDidTapLocation(urlBar.locationView) } @objc private func newTabKeyCommand() { UnifiedTelemetry.recordEvent(category: .action, method: .press, object: .keyCommand, extras: ["action": "new-tab"]) openBlankNewTab(focusLocationField: true, isPrivate: false) } @objc private func newPrivateTabKeyCommand() { // NOTE: We cannot and should not distinguish between "new-tab" and "new-private-tab" // when recording telemetry for key commands. UnifiedTelemetry.recordEvent(category: .action, method: .press, object: .keyCommand, extras: ["action": "new-tab"]) openBlankNewTab(focusLocationField: true, isPrivate: true) } @objc private func closeTabKeyCommand() { UnifiedTelemetry.recordEvent(category: .action, method: .press, object: .keyCommand, extras: ["action": "close-tab"]) guard let currentTab = tabManager.selectedTab else { return } tabManager.removeTabAndUpdateSelectedIndex(currentTab) } @objc private func nextTabKeyCommand() { UnifiedTelemetry.recordEvent(category: .action, method: .press, object: .keyCommand, extras: ["action": "next-tab"]) guard let currentTab = tabManager.selectedTab else { return } let tabs = currentTab.isPrivate ? tabManager.privateTabs : tabManager.normalTabs if let index = tabs.firstIndex(of: currentTab), index + 1 < tabs.count { tabManager.selectTab(tabs[index + 1]) } else if let firstTab = tabs.first { tabManager.selectTab(firstTab) } } @objc private func previousTabKeyCommand() { UnifiedTelemetry.recordEvent(category: .action, method: .press, object: .keyCommand, extras: ["action": "previous-tab"]) guard let currentTab = tabManager.selectedTab else { return } let tabs = currentTab.isPrivate ? tabManager.privateTabs : tabManager.normalTabs if let index = tabs.firstIndex(of: currentTab), index - 1 < tabs.count && index != 0 { tabManager.selectTab(tabs[index - 1]) } else if let lastTab = tabs.last { tabManager.selectTab(lastTab) } } @objc private func showTabTrayKeyCommand() { UnifiedTelemetry.recordEvent(category: .action, method: .press, object: .keyCommand, extras: ["action": "show-tab-tray"]) showTabTray() } @objc private func moveURLCompletionKeyCommand(sender: UIKeyCommand) { guard let searchController = self.searchController else { return } searchController.handleKeyCommands(sender: sender) } override var keyCommands: [UIKeyCommand]? { let searchLocationCommands = [ UIKeyCommand(input: UIKeyCommand.inputDownArrow, modifierFlags: [], action: #selector(moveURLCompletionKeyCommand(sender:))), UIKeyCommand(input: UIKeyCommand.inputUpArrow, modifierFlags: [], action: #selector(moveURLCompletionKeyCommand(sender:))), ] let overidesTextEditing = [ UIKeyCommand(input: UIKeyCommand.inputRightArrow, modifierFlags: [.command, .shift], action: #selector(nextTabKeyCommand)), UIKeyCommand(input: UIKeyCommand.inputLeftArrow, modifierFlags: [.command, .shift], action: #selector(previousTabKeyCommand)), UIKeyCommand(input: UIKeyCommand.inputLeftArrow, modifierFlags: .command, action: #selector(goBackKeyCommand)), UIKeyCommand(input: UIKeyCommand.inputRightArrow, modifierFlags: .command, action: #selector(goForwardKeyCommand)), ] let tabNavigation = [ UIKeyCommand(input: "r", modifierFlags: .command, action: #selector(reloadTabKeyCommand), discoverabilityTitle: Strings.ReloadPageTitle), UIKeyCommand(input: "[", modifierFlags: .command, action: #selector(goBackKeyCommand), discoverabilityTitle: Strings.BackTitle), UIKeyCommand(input: "]", modifierFlags: .command, action: #selector(goForwardKeyCommand), discoverabilityTitle: Strings.ForwardTitle), UIKeyCommand(input: "f", modifierFlags: .command, action: #selector(findInPageKeyCommand), discoverabilityTitle: Strings.FindTitle), UIKeyCommand(input: "l", modifierFlags: .command, action: #selector(selectLocationBarKeyCommand), discoverabilityTitle: Strings.SelectLocationBarTitle), UIKeyCommand(input: "t", modifierFlags: .command, action: #selector(newTabKeyCommand), discoverabilityTitle: Strings.NewTabTitle), UIKeyCommand(input: "p", modifierFlags: [.command, .shift], action: #selector(newPrivateTabKeyCommand), discoverabilityTitle: Strings.NewPrivateTabTitle), UIKeyCommand(input: "w", modifierFlags: .command, action: #selector(closeTabKeyCommand), discoverabilityTitle: Strings.CloseTabTitle), UIKeyCommand(input: "\t", modifierFlags: .control, action: #selector(nextTabKeyCommand), discoverabilityTitle: Strings.ShowNextTabTitle), UIKeyCommand(input: "\t", modifierFlags: [.control, .shift], action: #selector(previousTabKeyCommand), discoverabilityTitle: Strings.ShowPreviousTabTitle), // Switch tab to match Safari on iOS. UIKeyCommand(input: "]", modifierFlags: [.command, .shift], action: #selector(nextTabKeyCommand)), UIKeyCommand(input: "[", modifierFlags: [.command, .shift], action: #selector(previousTabKeyCommand)), UIKeyCommand(input: "\\", modifierFlags: [.command, .shift], action: #selector(showTabTrayKeyCommand)), // Safari on macOS UIKeyCommand(input: "\t", modifierFlags: [.command, .alternate], action: #selector(showTabTrayKeyCommand), discoverabilityTitle: Strings.ShowTabTrayFromTabKeyCodeTitle) ] let isEditingText = tabManager.selectedTab?.isEditing ?? false if urlBar.inOverlayMode { return tabNavigation + searchLocationCommands } else if !isEditingText { return tabNavigation + overidesTextEditing } return tabNavigation } }
mpl-2.0
820966a1d48e791740c12c2eb14a3aef
53.157534
180
0.685089
4.920348
false
false
false
false
reesemclean/rm-project-euler
in_progress/swifty-euler/problem-22.playground/Contents.swift
1
1548
//Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score. // //For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 × 53 = 49714. // //What is the total of all the name scores in the file? import Foundation let nameString = try! NSString(contentsOfFile: "/Users/reesemclean/Desktop/rm-project-euler/in_progress/swifty-euler/problem-22.playground/Resources/p022_names.txt", encoding:NSUTF8StringEncoding) let namesWithoutParenthesis = nameString.stringByReplacingOccurrencesOfString("\"", withString: "") let names = namesWithoutParenthesis.componentsSeparatedByString(",") let sortedNames = names.sort(<) func letterScore(letter: Character) -> Int { let alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" let index = alphabet.characters.indexOf(letter)! let position = alphabet.startIndex.distanceTo(index) return position + 1 } func nameScore(name: String, indexInList: Int) -> Int { let letterTotalScore: Int = name.characters.reduce(0) { $0 + letterScore($1) } return letterTotalScore * (indexInList + 1) } var total = 0 for (index, name) in sortedNames.enumerate() { total = total + nameScore(name, indexInList: index) } print(total)
mit
5535c7973d304a2d98d1be8944532cf7
43.228571
305
0.744021
3.976864
false
false
false
false
xedin/swift
test/decl/protocol/conforms/self.swift
2
2798
// RUN: %target-typecheck-verify-swift protocol P { associatedtype T = Int func hasDefault() func returnsSelf() -> Self func hasDefaultTakesT(_: T) func returnsSelfTakesT(_: T) -> Self } extension P { func hasDefault() {} func returnsSelf() -> Self { return self } func hasDefaultTakesT(_: T) {} func returnsSelfTakesT(_: T) -> Self { // expected-note {{'returnsSelfTakesT' declared here}} return self } } // This fails class Class : P {} // expected-error {{method 'returnsSelfTakesT' in non-final class 'Class' cannot be implemented in a protocol extension because it returns 'Self' and has associated type requirements}} // This succeeds, because the class is final final class FinalClass : P {} // This succeeds, because we're not using the default implementation class NonFinalClass : P { func returnsSelfTakesT(_: T) -> Self { return self } } // Test for default implementation that comes from a constrained extension // - https://bugs.swift.org/browse/SR-7422 // FIXME: Better error message here? class SillyClass {} protocol HasDefault { func foo() // expected-note@-1 {{protocol requires function 'foo()' with type '() -> ()'; do you want to add a stub?}} } extension HasDefault where Self == SillyClass { func foo() {} // expected-note@-1 {{candidate would match if 'SillyClass' conformed to 'HasDefault'}} } extension SillyClass : HasDefault {} // expected-error@-1 {{type 'SillyClass' does not conform to protocol 'HasDefault'}} // This is OK, though class SeriousClass {} extension HasDefault where Self : SeriousClass { func foo() {} // expected-note@-1 {{candidate would match if 'SillyClass' subclassed 'SeriousClass'}} } extension SeriousClass : HasDefault {} // https://bugs.swift.org/browse/SR-7428 protocol Node { associatedtype ValueType = Int func addChild<ChildType>(_ child: ChildType) where ChildType: Node, ChildType.ValueType == Self.ValueType } extension Node { func addChild<ChildType>(_ child: ChildType) where ChildType: Node, ChildType.ValueType == Self.ValueType {} } class IntNode: Node {} // SR-8902 protocol P8902 { associatedtype A // expected-note {{protocol requires nested type 'A'; do you want to add it?}} func f(_ x: A) -> Self } struct S : P8902 { func f(_ x: Bool) -> S { fatalError() } } class C8902 : P8902 { // expected-error {{type 'C8902' does not conform to protocol 'P8902'}} func f(_ x: Bool) -> C8902 { fatalError() } } final class C8902b : P8902 { func f(_ x: Bool) -> C8902b { fatalError() } } class C8902c : P8902 { func f(_ x: Bool) -> Self { fatalError() } } protocol P8902complex { associatedtype A func f() -> (A, Self?) } final class C8902complex : P8902complex { func f() -> (Bool, C8902complex?) { fatalError() } }
apache-2.0
155a638cfdb443b7ec3caa7b226e7073
24.669725
203
0.680843
3.806803
false
false
false
false
february29/Learning
swift/ReactiveCocoaDemo/Pods/RxSwift/RxSwift/Observables/Buffer.swift
132
4320
// // Buffer.swift // RxSwift // // Created by Krunoslav Zaher on 9/13/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // extension ObservableType { /** Projects each element of an observable sequence into a buffer that's sent out when either it's full or a given amount of time has elapsed, using the specified scheduler to run timers. A useful real-world analogy of this overload is the behavior of a ferry leaving the dock when all seats are taken, or at the scheduled time of departure, whichever event occurs first. - seealso: [buffer operator on reactivex.io](http://reactivex.io/documentation/operators/buffer.html) - parameter timeSpan: Maximum time length of a buffer. - parameter count: Maximum element count of a buffer. - parameter scheduler: Scheduler to run buffering timers on. - returns: An observable sequence of buffers. */ public func buffer(timeSpan: RxTimeInterval, count: Int, scheduler: SchedulerType) -> Observable<[E]> { return BufferTimeCount(source: self.asObservable(), timeSpan: timeSpan, count: count, scheduler: scheduler) } } final fileprivate class BufferTimeCount<Element> : Producer<[Element]> { fileprivate let _timeSpan: RxTimeInterval fileprivate let _count: Int fileprivate let _scheduler: SchedulerType fileprivate let _source: Observable<Element> init(source: Observable<Element>, timeSpan: RxTimeInterval, count: Int, scheduler: SchedulerType) { _source = source _timeSpan = timeSpan _count = count _scheduler = scheduler } override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == [Element] { let sink = BufferTimeCountSink(parent: self, observer: observer, cancel: cancel) let subscription = sink.run() return (sink: sink, subscription: subscription) } } final fileprivate class BufferTimeCountSink<Element, O: ObserverType> : Sink<O> , LockOwnerType , ObserverType , SynchronizedOnType where O.E == [Element] { typealias Parent = BufferTimeCount<Element> typealias E = Element private let _parent: Parent let _lock = RecursiveLock() // state private let _timerD = SerialDisposable() private var _buffer = [Element]() private var _windowID = 0 init(parent: Parent, observer: O, cancel: Cancelable) { _parent = parent super.init(observer: observer, cancel: cancel) } func run() -> Disposable { createTimer(_windowID) return Disposables.create(_timerD, _parent._source.subscribe(self)) } func startNewWindowAndSendCurrentOne() { _windowID = _windowID &+ 1 let windowID = _windowID let buffer = _buffer _buffer = [] forwardOn(.next(buffer)) createTimer(windowID) } func on(_ event: Event<E>) { synchronizedOn(event) } func _synchronized_on(_ event: Event<E>) { switch event { case .next(let element): _buffer.append(element) if _buffer.count == _parent._count { startNewWindowAndSendCurrentOne() } case .error(let error): _buffer = [] forwardOn(.error(error)) dispose() case .completed: forwardOn(.next(_buffer)) forwardOn(.completed) dispose() } } func createTimer(_ windowID: Int) { if _timerD.isDisposed { return } if _windowID != windowID { return } let nextTimer = SingleAssignmentDisposable() _timerD.disposable = nextTimer let disposable = _parent._scheduler.scheduleRelative(windowID, dueTime: _parent._timeSpan) { previousWindowID in self._lock.performLocked { if previousWindowID != self._windowID { return } self.startNewWindowAndSendCurrentOne() } return Disposables.create() } nextTimer.setDisposable(disposable) } }
mit
bd56327b5e4a6c56943b4435e069d37d
30.071942
188
0.610095
4.89128
false
false
false
false
4taras4/totp-auth
TOTP/ViperModules/AddItemManualy/Module/Assembly/AddItemManualyAssemblyContainer.swift
1
1310
// // AddItemManualyAddItemManualyAssemblyContainer.swift // TOTP // // Created by Tarik on 10/10/2020. // Copyright © 2020 Taras Markevych. All rights reserved. // import Swinject final class AddItemManualyAssemblyContainer: Assembly { func assemble(container: Container) { container.register(AddItemManualyInteractor.self) { (_, presenter: AddItemManualyPresenter) in let interactor = AddItemManualyInteractor() interactor.output = presenter return interactor } container.register(AddItemManualyRouter.self) { (_, viewController: AddItemManualyViewController) in let router = AddItemManualyRouter() router.transitionHandler = viewController return router } container.register(AddItemManualyPresenter.self) { (r, viewController: AddItemManualyViewController) in let presenter = AddItemManualyPresenter() presenter.view = viewController presenter.interactor = r.resolve(AddItemManualyInteractor.self, argument: presenter) presenter.router = r.resolve(AddItemManualyRouter.self, argument: viewController) return presenter } container.storyboardInitCompleted(AddItemManualyViewController.self) { r, viewController in viewController.output = r.resolve(AddItemManualyPresenter.self, argument: viewController) } } }
mit
a408a6a21f8b694b397992b0d8539865
29.44186
105
0.763942
4.467577
false
false
false
false
Yoloabdo/CS-193P
SmashTag/SmashTag/TweetTableViewController.swift
1
6164
// // TweetTableViewController.swift // Smashtag // // Created by abdelrahman mohamed on 2/25/16. // Copyright © 2016 Abdulrhman dev. All rights reserved. // import UIKit class TweetTableViewController: UITableViewController, UITextFieldDelegate { // MARK: - Public API var tweets = [[Tweet]]() var searchText: String? { didSet { UIApplication.sharedApplication().networkActivityIndicatorVisible = true lastSuccessfulRequest = nil searchTextField?.text = searchText tweets.removeAll() tableView.reloadData() // clear out the table view refresh() } } // MARK: - View Controller Lifecycle override func viewDidLoad() { super.viewDidLoad() tableView.estimatedRowHeight = tableView.rowHeight tableView.rowHeight = UITableViewAutomaticDimension refresh() } // MARK: - Refreshing private var lastSuccessfulRequest: TwitterRequest? private var nextRequestToAttempt: TwitterRequest? { if lastSuccessfulRequest == nil { if let searchText = searchText { history.addWord(searchText) return TwitterRequest(search: searchText, count: 100) } else { return nil } } else { return lastSuccessfulRequest!.requestForNewer } } var numRows = true @IBAction private func refresh(sender: UIRefreshControl?) { if Reachability.isConnectedToNetwork(){ numRows = true if let request = nextRequestToAttempt { request.fetchTweets { (newTweets) -> Void in dispatch_async(dispatch_get_main_queue()) { () -> Void in if newTweets.count > 0 { self.lastSuccessfulRequest = request self.tweets.insert(newTweets, atIndex: 0) self.tableView.reloadData() } sender?.endRefreshing() UIApplication.sharedApplication().networkActivityIndicatorVisible = false } } } else { sender?.endRefreshing() } }else{ let alert = UIAlertController(title: "Connection failed", message: "check your internet connection", preferredStyle: .Alert) alert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: { _ in sender?.endRefreshing()})) alert.addAction(UIAlertAction(title: "Try again", style: .Default, handler: { _ in self.refresh() })) presentViewController(alert, animated: true, completion: nil) numRows = false } } func refresh() { refreshControl?.beginRefreshing() refresh(refreshControl) } // MARK: - Rresistance let history = PrestingHistory() // MARK: - Storyboard Connectivity @IBOutlet private weak var searchTextField: UITextField! { didSet { searchTextField.delegate = self searchTextField.text = searchText } } func textFieldShouldReturn(textField: UITextField) -> Bool { if textField == searchTextField { textField.resignFirstResponder() searchText = textField.text } return true } private struct Storyboard { static let CellReuseIdentifier = "Tweet" static let segue = "cellDetail" } // MARK: - UITableViewDataSource override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return tweets.count } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if numRows { return tweets[section].count } return 0 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(Storyboard.CellReuseIdentifier, forIndexPath: indexPath) as! TweetTableViewCell let tweet = tweets[indexPath.section][indexPath.row] if Reachability.isConnectedToNetwork() { UIApplication.sharedApplication().networkActivityIndicatorVisible = true if let url = tweet.user.profileImageURL { let request = NSURLRequest(URL: url) let urlSession = NSURLSession.sharedSession() cell.dataTask = urlSession.dataTaskWithRequest(request) { (data, response, error) -> Void in NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in if error == nil && data != nil { let image = UIImage(data: data!) cell.profileImage = image UIApplication.sharedApplication().networkActivityIndicatorVisible = false } }) } cell.dataTask?.resume() } } cell.tweet = tweet return cell } override func tableView(tableView: UITableView, didEndDisplayingCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { if let cell = cell as? TweetTableViewCell { cell.dataTask?.cancel() cell.dataTask = nil } } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == Storyboard.segue{ let tvc = segue.destinationViewController as! TweetDetailsTableViewController let cell = sender as! TweetTableViewCell if let indexPath = tableView.indexPathForCell(cell){ tvc.tweet = tweets[indexPath.section][indexPath.row] } } } @IBAction func goBackToSearch(segue: UIStoryboardSegue){ } }
mit
827264167a1bf03e4006c2a02ef9febf
31.957219
142
0.575045
6.048086
false
false
false
false
JaSpa/swift
stdlib/public/SDK/Foundation/NSDictionary.swift
4
9375
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_exported import Foundation // Clang module //===----------------------------------------------------------------------===// // Dictionaries //===----------------------------------------------------------------------===// extension NSDictionary : ExpressibleByDictionaryLiteral { public required convenience init( dictionaryLiteral elements: (Any, Any)... ) { // FIXME: Unfortunate that the `NSCopying` check has to be done at runtime. self.init( objects: elements.map { $0.1 as AnyObject }, forKeys: elements.map { $0.0 as AnyObject as! NSCopying }, count: elements.count) } } extension Dictionary { /// Private initializer used for bridging. /// /// The provided `NSDictionary` will be copied to ensure that the copy can /// not be mutated by other code. public init(_cocoaDictionary: _NSDictionary) { _sanityCheck( _isBridgedVerbatimToObjectiveC(Key.self) && _isBridgedVerbatimToObjectiveC(Value.self), "Dictionary can be backed by NSDictionary storage only when both key and value are bridged verbatim to Objective-C") // FIXME: We would like to call CFDictionaryCreateCopy() to avoid doing an // objc_msgSend() for instances of CoreFoundation types. We can't do that // today because CFDictionaryCreateCopy() copies dictionary contents // unconditionally, resulting in O(n) copies even for immutable dictionaries. // // <rdar://problem/20690755> CFDictionaryCreateCopy() does not call copyWithZone: // // The bug is fixed in: OS X 10.11.0, iOS 9.0, all versions of tvOS // and watchOS. self = Dictionary( _immutableCocoaDictionary: unsafeBitCast(_cocoaDictionary.copy(with: nil) as AnyObject, to: _NSDictionary.self)) } } // Dictionary<Key, Value> is conditionally bridged to NSDictionary extension Dictionary : _ObjectiveCBridgeable { @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> NSDictionary { return unsafeBitCast(_bridgeToObjectiveCImpl() as AnyObject, to: NSDictionary.self) } public static func _forceBridgeFromObjectiveC( _ d: NSDictionary, result: inout Dictionary? ) { if let native = [Key : Value]._bridgeFromObjectiveCAdoptingNativeStorageOf( d as AnyObject) { result = native return } if _isBridgedVerbatimToObjectiveC(Key.self) && _isBridgedVerbatimToObjectiveC(Value.self) { result = [Key : Value]( _cocoaDictionary: unsafeBitCast(d as AnyObject, to: _NSDictionary.self)) return } // `Dictionary<Key, Value>` where either `Key` or `Value` is a value type // may not be backed by an NSDictionary. var builder = _DictionaryBuilder<Key, Value>(count: d.count) d.enumerateKeysAndObjects({ (anyKey: Any, anyValue: Any, _) in let anyObjectKey = anyKey as AnyObject let anyObjectValue = anyValue as AnyObject builder.add( key: Swift._forceBridgeFromObjectiveC(anyObjectKey, Key.self), value: Swift._forceBridgeFromObjectiveC(anyObjectValue, Value.self)) }) result = builder.take() } public static func _conditionallyBridgeFromObjectiveC( _ x: NSDictionary, result: inout Dictionary? ) -> Bool { let anyDict = x as [NSObject : AnyObject] if _isBridgedVerbatimToObjectiveC(Key.self) && _isBridgedVerbatimToObjectiveC(Value.self) { result = Swift._dictionaryDownCastConditional(anyDict) return result != nil } result = Swift._dictionaryBridgeFromObjectiveCConditional(anyDict) return result != nil } public static func _unconditionallyBridgeFromObjectiveC( _ d: NSDictionary? ) -> Dictionary { // `nil` has historically been used as a stand-in for an empty // dictionary; map it to an empty dictionary. if _slowPath(d == nil) { return Dictionary() } if let native = [Key : Value]._bridgeFromObjectiveCAdoptingNativeStorageOf( d! as AnyObject) { return native } if _isBridgedVerbatimToObjectiveC(Key.self) && _isBridgedVerbatimToObjectiveC(Value.self) { return [Key : Value]( _cocoaDictionary: unsafeBitCast(d! as AnyObject, to: _NSDictionary.self)) } // `Dictionary<Key, Value>` where either `Key` or `Value` is a value type // may not be backed by an NSDictionary. var builder = _DictionaryBuilder<Key, Value>(count: d!.count) d!.enumerateKeysAndObjects({ (anyKey: Any, anyValue: Any, _) in builder.add( key: Swift._forceBridgeFromObjectiveC(anyKey as AnyObject, Key.self), value: Swift._forceBridgeFromObjectiveC(anyValue as AnyObject, Value.self)) }) return builder.take() } } extension NSDictionary : Sequence { // FIXME: A class because we can't pass a struct with class fields through an // [objc] interface without prematurely destroying the references. final public class Iterator : IteratorProtocol { var _fastIterator: NSFastEnumerationIterator var _dictionary: NSDictionary { return _fastIterator.enumerable as! NSDictionary } public func next() -> (key: Any, value: Any)? { if let key = _fastIterator.next() { // Deliberately avoid the subscript operator in case the dictionary // contains non-copyable keys. This is rare since NSMutableDictionary // requires them, but we don't want to paint ourselves into a corner. return (key: key, value: _dictionary.object(forKey: key)!) } return nil } internal init(_ _dict: NSDictionary) { _fastIterator = NSFastEnumerationIterator(_dict) } } // Bridging subscript. @objc public subscript(key: Any) -> Any? { @objc(_swift_objectForKeyedSubscript:) get { // Deliberately avoid the subscript operator in case the dictionary // contains non-copyable keys. This is rare since NSMutableDictionary // requires them, but we don't want to paint ourselves into a corner. return self.object(forKey: key) } } /// Return an *iterator* over the elements of this *sequence*. /// /// - Complexity: O(1). public func makeIterator() -> Iterator { return Iterator(self) } } extension NSMutableDictionary { // Bridging subscript. override public subscript(key: Any) -> Any? { get { return self.object(forKey: key) } @objc(_swift_setObject:forKeyedSubscript:) set { // FIXME: Unfortunate that the `NSCopying` check has to be done at // runtime. let copyingKey = key as AnyObject as! NSCopying if let newValue = newValue { self.setObject(newValue, forKey: copyingKey) } else { self.removeObject(forKey: copyingKey) } } } } extension NSDictionary { /// Initializes a newly allocated dictionary and adds to it objects from /// another given dictionary. /// /// - Returns: An initialized dictionary--which might be different /// than the original receiver--containing the keys and values /// found in `otherDictionary`. @objc(_swiftInitWithDictionary_NSDictionary:) public convenience init(dictionary otherDictionary: NSDictionary) { // FIXME(performance)(compiler limitation): we actually want to do just // `self = otherDictionary.copy()`, but Swift does not have factory // initializers right now. let numElems = otherDictionary.count let stride = MemoryLayout<AnyObject>.stride let alignment = MemoryLayout<AnyObject>.alignment let singleSize = stride * numElems let totalSize = singleSize * 2 _sanityCheck(stride == MemoryLayout<NSCopying>.stride) _sanityCheck(alignment == MemoryLayout<NSCopying>.alignment) // Allocate a buffer containing both the keys and values. let buffer = UnsafeMutableRawPointer.allocate( bytes: totalSize, alignedTo: alignment) defer { buffer.deallocate(bytes: totalSize, alignedTo: alignment) _fixLifetime(otherDictionary) } let valueBuffer = buffer.bindMemory(to: AnyObject.self, capacity: numElems) let buffer2 = buffer + singleSize let keyBuffer = buffer2.bindMemory(to: AnyObject.self, capacity: numElems) _stdlib_NSDictionary_getObjects( nsDictionary: otherDictionary, objects: valueBuffer, andKeys: keyBuffer) let keyBufferCopying = buffer2.assumingMemoryBound(to: NSCopying.self) self.init(objects: valueBuffer, forKeys: keyBufferCopying, count: numElems) } } @_silgen_name("__NSDictionaryGetObjects") func _stdlib_NSDictionary_getObjects( nsDictionary: NSDictionary, objects: UnsafeMutablePointer<AnyObject>?, andKeys keys: UnsafeMutablePointer<AnyObject>? ) extension NSDictionary : CustomReflectable { public var customMirror: Mirror { return Mirror(reflecting: self as [NSObject : AnyObject]) } } extension Dictionary: CVarArg {}
apache-2.0
01f8568f1990f6458b8264005e02cddd
35.196911
122
0.6688
4.832474
false
false
false
false
Jnosh/swift
test/SILGen/address_only_types.swift
5
9566
// RUN: %target-swift-frontend -parse-as-library -parse-stdlib -emit-silgen %s | %FileCheck %s precedencegroup AssignmentPrecedence { assignment: true } typealias Int = Builtin.Int64 enum Bool { case true_, false_ } protocol Unloadable { func foo() -> Int var address_only_prop : Unloadable { get } var loadable_prop : Int { get } } // CHECK-LABEL: sil hidden @_T018address_only_types0a1_B9_argument{{[_0-9a-zA-Z]*}}F func address_only_argument(_ x: Unloadable) { // CHECK: bb0([[XARG:%[0-9]+]] : $*Unloadable): // CHECK: debug_value_addr [[XARG]] // CHECK-NEXT: destroy_addr [[XARG]] // CHECK-NEXT: tuple // CHECK-NEXT: return } // CHECK-LABEL: sil hidden @_T018address_only_types0a1_B17_ignored_argument{{[_0-9a-zA-Z]*}}F func address_only_ignored_argument(_: Unloadable) { // CHECK: bb0([[XARG:%[0-9]+]] : $*Unloadable): // CHECK: destroy_addr [[XARG]] // CHECK-NOT: dealloc_stack {{.*}} [[XARG]] // CHECK: return } // CHECK-LABEL: sil hidden @_T018address_only_types0a1_B7_return{{[_0-9a-zA-Z]*}}F func address_only_return(_ x: Unloadable, y: Int) -> Unloadable { // CHECK: bb0([[RET:%[0-9]+]] : $*Unloadable, [[XARG:%[0-9]+]] : $*Unloadable, [[YARG:%[0-9]+]] : $Builtin.Int64): // CHECK-NEXT: debug_value_addr [[XARG]] : $*Unloadable, let, name "x" // CHECK-NEXT: debug_value [[YARG]] : $Builtin.Int64, let, name "y" // CHECK-NEXT: copy_addr [[XARG]] to [initialization] [[RET]] // CHECK-NEXT: destroy_addr [[XARG]] // CHECK-NEXT: [[VOID:%[0-9]+]] = tuple () // CHECK-NEXT: return [[VOID]] return x } // CHECK-LABEL: sil hidden @_T018address_only_types0a1_B15_missing_return{{[_0-9a-zA-Z]*}}F func address_only_missing_return() -> Unloadable { // CHECK: unreachable } // CHECK-LABEL: sil hidden @_T018address_only_types0a1_B27_conditional_missing_return{{[_0-9a-zA-Z]*}}F func address_only_conditional_missing_return(_ x: Unloadable) -> Unloadable { // CHECK: bb0({{%.*}} : $*Unloadable, {{%.*}} : $*Unloadable): // CHECK: switch_enum {{%.*}}, case #Bool.true_!enumelt: [[TRUE:bb[0-9]+]], case #Bool.false_!enumelt: [[FALSE:bb[0-9]+]] switch Bool.true_ { case .true_: // CHECK: [[TRUE]]: // CHECK: copy_addr %1 to [initialization] %0 : $*Unloadable // CHECK: destroy_addr %1 // CHECK: return return x case .false_: () } // CHECK: [[FALSE]]: // CHECK: unreachable } // CHECK-LABEL: sil hidden @_T018address_only_types0a1_B29_conditional_missing_return_2 func address_only_conditional_missing_return_2(_ x: Unloadable) -> Unloadable { // CHECK: bb0({{%.*}} : $*Unloadable, {{%.*}} : $*Unloadable): // CHECK: switch_enum {{%.*}}, case #Bool.true_!enumelt: [[TRUE1:bb[0-9]+]], case #Bool.false_!enumelt: [[FALSE1:bb[0-9]+]] switch Bool.true_ { case .true_: return x case .false_: () } // CHECK: [[FALSE1]]: // CHECK: switch_enum {{%.*}}, case #Bool.true_!enumelt: [[TRUE2:bb[0-9]+]], case #Bool.false_!enumelt: [[FALSE2:bb[0-9]+]] switch Bool.true_ { case .true_: return x case .false_: () } // CHECK: [[FALSE2]]: // CHECK: unreachable // CHECK: bb{{.*}}: // CHECK: return } var crap : Unloadable = some_address_only_function_1() func some_address_only_function_1() -> Unloadable { return crap } func some_address_only_function_2(_ x: Unloadable) -> () {} // CHECK-LABEL: sil hidden @_T018address_only_types0a1_B7_call_1 func address_only_call_1() -> Unloadable { // CHECK: bb0([[RET:%[0-9]+]] : $*Unloadable): return some_address_only_function_1() // FIXME emit into // CHECK: [[FUNC:%[0-9]+]] = function_ref @_T018address_only_types05some_a1_B11_function_1AA10Unloadable_pyF // CHECK: apply [[FUNC]]([[RET]]) // CHECK: return } // CHECK-LABEL: sil hidden @_T018address_only_types0a1_B21_call_1_ignore_returnyyF func address_only_call_1_ignore_return() { // CHECK: bb0: some_address_only_function_1() // CHECK: [[FUNC:%[0-9]+]] = function_ref @_T018address_only_types05some_a1_B11_function_1AA10Unloadable_pyF // CHECK: [[TEMP:%[0-9]+]] = alloc_stack $Unloadable // CHECK: apply [[FUNC]]([[TEMP]]) // CHECK: destroy_addr [[TEMP]] // CHECK: dealloc_stack [[TEMP]] // CHECK: return } // CHECK-LABEL: sil hidden @_T018address_only_types0a1_B7_call_2{{[_0-9a-zA-Z]*}}F func address_only_call_2(_ x: Unloadable) { // CHECK: bb0([[XARG:%[0-9]+]] : $*Unloadable): // CHECK: debug_value_addr [[XARG]] : $*Unloadable some_address_only_function_2(x) // CHECK: [[FUNC:%[0-9]+]] = function_ref @_T018address_only_types05some_a1_B11_function_2{{[_0-9a-zA-Z]*}}F // CHECK: [[X_CALL_ARG:%[0-9]+]] = alloc_stack $Unloadable // CHECK: copy_addr [[XARG]] to [initialization] [[X_CALL_ARG]] // CHECK: apply [[FUNC]]([[X_CALL_ARG]]) // CHECK: dealloc_stack [[X_CALL_ARG]] // CHECK: return } // CHECK-LABEL: sil hidden @_T018address_only_types0a1_B12_call_1_in_2{{[_0-9a-zA-Z]*}}F func address_only_call_1_in_2() { // CHECK: bb0: some_address_only_function_2(some_address_only_function_1()) // CHECK: [[FUNC2:%[0-9]+]] = function_ref @_T018address_only_types05some_a1_B11_function_2{{[_0-9a-zA-Z]*}}F // CHECK: [[FUNC1:%[0-9]+]] = function_ref @_T018address_only_types05some_a1_B11_function_1{{[_0-9a-zA-Z]*}}F // CHECK: [[TEMP:%[0-9]+]] = alloc_stack $Unloadable // CHECK: apply [[FUNC1]]([[TEMP]]) // CHECK: apply [[FUNC2]]([[TEMP]]) // CHECK: dealloc_stack [[TEMP]] // CHECK: return } // CHECK-LABEL: sil hidden @_T018address_only_types0a1_B12_materialize{{[_0-9a-zA-Z]*}}F func address_only_materialize() -> Int { // CHECK: bb0: return some_address_only_function_1().foo() // CHECK: [[FUNC:%[0-9]+]] = function_ref @_T018address_only_types05some_a1_B11_function_1{{[_0-9a-zA-Z]*}}F // CHECK: [[TEMP:%[0-9]+]] = alloc_stack $Unloadable // CHECK: apply [[FUNC]]([[TEMP]]) // CHECK: [[TEMP_PROJ:%[0-9]+]] = open_existential_addr immutable_access [[TEMP]] : $*Unloadable to $*[[OPENED:@opened(.*) Unloadable]] // CHECK: [[FOO_METHOD:%[0-9]+]] = witness_method $[[OPENED]], #Unloadable.foo!1 // CHECK: [[RET:%[0-9]+]] = apply [[FOO_METHOD]]<[[OPENED]]>([[TEMP_PROJ]]) // CHECK: destroy_addr [[TEMP]] // CHECK: dealloc_stack [[TEMP]] // CHECK: return [[RET]] } // CHECK-LABEL: sil hidden @_T018address_only_types0a1_B21_assignment_from_temp{{[_0-9a-zA-Z]*}}F func address_only_assignment_from_temp(_ dest: inout Unloadable) { // CHECK: bb0([[DEST:%[0-9]+]] : $*Unloadable): dest = some_address_only_function_1() // CHECK: [[TEMP:%[0-9]+]] = alloc_stack $Unloadable // CHECK: %[[ACCESS:.*]] = begin_access [modify] [unknown] %0 : // CHECK: copy_addr [take] [[TEMP]] to %[[ACCESS]] : // CHECK-NOT: destroy_addr [[TEMP]] // CHECK: dealloc_stack [[TEMP]] } // CHECK-LABEL: sil hidden @_T018address_only_types0a1_B19_assignment_from_lv{{[_0-9a-zA-Z]*}}F func address_only_assignment_from_lv(_ dest: inout Unloadable, v: Unloadable) { var v = v // CHECK: bb0([[DEST:%[0-9]+]] : $*Unloadable, [[VARG:%[0-9]+]] : $*Unloadable): // CHECK: [[VBOX:%.*]] = alloc_box ${ var Unloadable } // CHECK: [[PBOX:%[0-9]+]] = project_box [[VBOX]] // CHECK: copy_addr [[VARG]] to [initialization] [[PBOX]] : $*Unloadable dest = v // CHECK: [[READBOX:%.*]] = begin_access [read] [unknown] [[PBOX]] : // CHECK: [[TEMP:%[0-9]+]] = alloc_stack $Unloadable // CHECK: copy_addr [[READBOX]] to [initialization] [[TEMP]] : // CHECK: [[RET:%.*]] = begin_access [modify] [unknown] %0 : // CHECK: copy_addr [take] [[TEMP]] to [[RET]] : // CHECK: destroy_value [[VBOX]] } var global_prop : Unloadable { get { return crap } set {} } // CHECK-LABEL: sil hidden @_T018address_only_types0a1_B33_assignment_from_temp_to_property{{[_0-9a-zA-Z]*}}F func address_only_assignment_from_temp_to_property() { // CHECK: bb0: global_prop = some_address_only_function_1() // CHECK: [[TEMP:%[0-9]+]] = alloc_stack $Unloadable // CHECK: [[SETTER:%[0-9]+]] = function_ref @_T018address_only_types11global_propAA10Unloadable_pfs // CHECK: apply [[SETTER]]([[TEMP]]) // CHECK: dealloc_stack [[TEMP]] } // CHECK-LABEL: sil hidden @_T018address_only_types0a1_B31_assignment_from_lv_to_property{{[_0-9a-zA-Z]*}}F func address_only_assignment_from_lv_to_property(_ v: Unloadable) { // CHECK: bb0([[VARG:%[0-9]+]] : $*Unloadable): // CHECK: debug_value_addr [[VARG]] : $*Unloadable // CHECK: [[TEMP:%[0-9]+]] = alloc_stack $Unloadable // CHECK: copy_addr [[VARG]] to [initialization] [[TEMP]] // CHECK: [[SETTER:%[0-9]+]] = function_ref @_T018address_only_types11global_propAA10Unloadable_pfs // CHECK: apply [[SETTER]]([[TEMP]]) // CHECK: dealloc_stack [[TEMP]] global_prop = v } // CHECK-LABEL: sil hidden @_T018address_only_types0a1_B4_varAA10Unloadable_pyF func address_only_var() -> Unloadable { // CHECK: bb0([[RET:%[0-9]+]] : $*Unloadable): var x = some_address_only_function_1() // CHECK: [[XBOX:%[0-9]+]] = alloc_box ${ var Unloadable } // CHECK: [[XPB:%.*]] = project_box [[XBOX]] // CHECK: apply {{%.*}}([[XPB]]) return x // CHECK: [[ACCESS:%.*]] = begin_access [read] [unknown] [[XPB]] : // CHECK: copy_addr [[ACCESS]] to [initialization] %0 // CHECK: destroy_value [[XBOX]] // CHECK: return } func unloadable_to_unloadable(_ x: Unloadable) -> Unloadable { return x } var some_address_only_nontuple_arg_function : (Unloadable) -> Unloadable = unloadable_to_unloadable // CHECK-LABEL: sil hidden @_T018address_only_types05call_a1_B22_nontuple_arg_function{{[_0-9a-zA-Z]*}}F func call_address_only_nontuple_arg_function(_ x: Unloadable) { some_address_only_nontuple_arg_function(x) }
apache-2.0
f81a756c92c936acc21650c3d69fecbf
39.706383
137
0.62304
2.94067
false
false
false
false
coach-plus/ios
CoachPlus/helperclasses/DropdownAlert.swift
1
827
// // DropdownAlert.swift // CoachPlus // // Created by Breit, Maurice on 26.03.17. // Copyright © 2017 Mathandoro GbR. All rights reserved. // import Foundation import NotificationBannerSwift class DropdownAlert { static let errorBgColor = UIColor.red static let errorTextColor = UIColor.white static let errorTitle = L10n.error static let errorTime = 3 static let successTitle = L10n.success static func error(message: String) { let msg = message.localize() let banner = NotificationBanner(title: self.errorTitle, subtitle: msg, style: .danger) banner.show() } static func success(message: String) { let banner = NotificationBanner(title: self.successTitle, subtitle: message, style: .success) banner.show() } }
mit
693113f2a95dce3c8d116e7dc597da1e
24.030303
101
0.664649
4.324607
false
false
false
false
chrisjmendez/swift-exercises
Transitions/Razzle/Pods/RazzleDazzle/Source/RotationAnimation.swift
25
1079
// // RotationAnimation.swift // RazzleDazzle // // Created by Laura Skelton on 6/13/15. // Copyright (c) 2015 IFTTT. All rights reserved. // import UIKit /** Animates the rotation of the `transform` of a `UIView`. */ public class RotationAnimation : Animation<CGFloat>, Animatable { private let view : UIView public init(view: UIView) { self.view = view } public func animate(time: CGFloat) { if !hasKeyframes() {return} let degrees = self[time] let radians = degrees * CGFloat(M_PI / -180.0) let rotationTransform = CGAffineTransformMakeRotation(radians) view.rotationTransform = rotationTransform var newTransform = rotationTransform if let scaleTransform = view.scaleTransform { newTransform = CGAffineTransformConcat(newTransform, scaleTransform) } if let translationTransform = view.translationTransform { newTransform = CGAffineTransformConcat(newTransform, translationTransform) } view.transform = newTransform } }
mit
f629687091b4bebe2a4fb90d7975b670
28.972222
86
0.666358
4.670996
false
false
false
false
silence0201/Swift-Study
Learn/06.原生集合类型/Set声明和初始化.playground/section-1.swift
1
588
let studentList1: Set<String> = ["张三","李四","王五","董六"] var studentList2 = Set<String>() let studentList3 = ["张三","李四","王五","董六"] let studentList4: [String] = ["董六", "张三","李四","王五"] let studentList5: Set<String> = ["董六", "张三", "李四", "王五"] if studentList1 == studentList5 { print("studentList1 等于 studentList5") } else { print("studentList1 不等于 studentList5") } if studentList3 == studentList4 { print("studentList3 等于 studentList4") } else { print("studentList3 不等于 studentList4") }
mit
ddecb62b7c9064cd8516c50ca833202b
21.909091
56
0.646825
2.597938
false
false
false
false
lucaslouca/swipe-away-views
swipe/ViewController.swift
1
952
// // ViewController.swift // swipe // // Created by Lucas Louca on 22/03/15. // Copyright (c) 2015 Lucas Louca. All rights reserved. // import UIKit class ViewController: UIViewController { var items:[Item]! var swipeViews:[SwipeView]! override func viewDidLoad() { super.viewDidLoad() items = Item.allItems() self.loadDraggableCustomViews() } func loadDraggableCustomViews(){ swipeViews = [] var swipeView:SwipeView! var imageView:UIImageView! for item in items { swipeView = SwipeView(frame:CGRectMake(35, 35, 250, 250)) imageView = UIImageView(image: item.image) imageView.frame = CGRect(x: 0, y: 0, width: swipeView.frame.width, height: swipeView.frame.height) swipeView.addSubview(imageView) swipeViews.append(swipeView) self.view.addSubview(swipeView) } } }
mit
ba38eff8bcaf235945321cc73e2d87d0
24.72973
110
0.612395
4.387097
false
false
false
false