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
SeptAi/Cooperate
Cooperate/Cooperate/Class/Model/Project.swift
1
1362
// // Project.swift // Cooperate // // Created by J on 2017/1/3. // Copyright © 2017年 J. All rights reserved. // import UIKit import YYModel // 项目模型 class Project: NSObject { // 编号 var projectid:Int = 0 // 标题 var title:String? // 内容 var content:String? // 成员 var co_worker:String? // 状态 var state:Int = 0 // 启动 var isuse:Int = 0 // 创建者ID var uid:Int = 0 // 时间 var updatedAt:String?{ didSet{ time = Date.init() } } var time:Date? // 转发、评论、点赞 - 预留 var reposts_count:Int = 0 var comments_count:Int = 0 var attitudes_count:Int = 0 // 图片链接 // 配图模型数组 - 后期详细处理,通过自定义类 var pic_urls:[ProjectPicture]? // 用户 var user:User? override var description: String{ return yy_modelDescription() } // 类函数:告知第三方框架,遇到数组类型属性,数组中存放的数据是什么类 ---- 针对数组。自定义对象不需要 /// 字典转模型,嵌套问题处理 /// /// - Returns: 子模型定义 class func modelContainerPropertyGenericClass() -> [String:AnyClass]{ return ["pic_urls":ProjectPicture.self,"user":User.self] } }
mit
273cd5b1945c48e7e97c6ca8e69c5e18
18.327586
73
0.55843
3.277778
false
false
false
false
mokumoku/SwiftWebViewProgress
SwiftWebViewProgress/SwiftWebViewProgress/SwiftWebViewProgressView.swift
1
2938
// // SwiftWebViewProgressView.swift // SwiftWebViewProgress // // Created by Daichi Ichihara on 2014/12/04. // Copyright (c) 2014年 MokuMokuCloud. All rights reserved. // import UIKit public class WebViewProgressView: UIView { var progress: Float = 0.0 var progressBarView: UIView? var barAnimationDuration: TimeInterval? var fadeAnimationDuration: TimeInterval? var fadeOutDelay: TimeInterval? // MARK: Initializer override public init(frame: CGRect) { super.init(frame: frame) configureViews() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override public func awakeFromNib() { super.awakeFromNib() configureViews() } // MARK: Private Method private func configureViews() { self.isUserInteractionEnabled = false self.autoresizingMask = .flexibleWidth progressBarView = UIView(frame: self.bounds) progressBarView?.autoresizingMask = [.flexibleWidth, .flexibleHeight] var tintColor = UIColor(red: 22/255, green: 126/255, blue: 251/255, alpha: 1.0) if let color = UIApplication.shared.delegate?.window??.tintColor { tintColor = color } progressBarView?.backgroundColor = tintColor self.addSubview(progressBarView ?? UIView()) barAnimationDuration = 0.1 fadeAnimationDuration = 0.27 fadeOutDelay = 0.1 } // MARK: Public Method public func setProgress(_ progress: Float, animated: Bool = false) { let isGrowing = progress > 0.0 if let barAnimationDuration = barAnimationDuration { UIView.animate(withDuration: (isGrowing && animated) ? barAnimationDuration : 0.0, delay: 0.0, options: UIViewAnimationOptions(), animations: { var frame = self.progressBarView?.frame frame?.size.width = CGFloat(progress) * self.bounds.size.width self.progressBarView?.frame = frame ?? .zero }, completion: nil) } guard let fadeAnimationDuration = fadeAnimationDuration else { return } if progress >= 1.0 { guard let fadeOutDelay = fadeOutDelay else { return } UIView.animate(withDuration: animated ? fadeAnimationDuration : 0.0, delay: fadeOutDelay, options: UIViewAnimationOptions(), animations: { self.progressBarView?.alpha = 0.0 }, completion: { completed in var frame = self.progressBarView?.frame frame?.size.width = 0 self.progressBarView?.frame = frame ?? .zero }) } else { UIView.animate(withDuration: animated ? fadeAnimationDuration : 0.0, delay: 0.0, options: UIViewAnimationOptions(), animations: { self.progressBarView?.alpha = 1.0 }, completion: nil) } } }
mit
7162e1ff4401e64fa45c7eb14eac00e4
35.7
155
0.625681
4.893333
false
false
false
false
qutheory/vapor
Sources/Vapor/Content/PlaintextEncoder.swift
2
3539
/// Encodes data as plaintext, utf8. public struct PlaintextEncoder: ContentEncoder { /// Private encoder. private let encoder: _PlaintextEncoder /// The specific plaintext `MediaType` to use. private let contentType: HTTPMediaType /// Creates a new `PlaintextEncoder`. /// /// - parameters: /// - contentType: Plaintext `MediaType` to use. /// Usually `.plainText` or `.html`. public init(_ contentType: HTTPMediaType = .plainText) { encoder = .init() self.contentType = contentType } /// `ContentEncoder` conformance. public func encode<E>(_ encodable: E, to body: inout ByteBuffer, headers: inout HTTPHeaders) throws where E: Encodable { try encodable.encode(to: encoder) guard let string = self.encoder.plaintext else { fatalError() } headers.contentType = self.contentType body.writeString(string) } } // MARK: Private private final class _PlaintextEncoder: Encoder { public var codingPath: [CodingKey] public var userInfo: [CodingUserInfoKey: Any] public var plaintext: String? public init() { self.codingPath = [] self.userInfo = [:] self.plaintext = nil } public func container<Key: CodingKey>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> { fatalError("Plaintext encoding does not support dictionaries.") } public func unkeyedContainer() -> UnkeyedEncodingContainer { fatalError("Plaintext encoding does not support arrays.") } public func singleValueContainer() -> SingleValueEncodingContainer { return DataEncodingContainer(encoder: self) } } private final class DataEncodingContainer: SingleValueEncodingContainer { var codingPath: [CodingKey] { return encoder.codingPath } let encoder: _PlaintextEncoder init(encoder: _PlaintextEncoder) { self.encoder = encoder } func encodeNil() throws { encoder.plaintext = nil } func encode(_ value: Bool) throws { encoder.plaintext = value.description } func encode(_ value: Int) throws { encoder.plaintext = value.description } func encode(_ value: Double) throws { encoder.plaintext = value.description } func encode(_ value: String) throws { encoder.plaintext = value } func encode(_ value: Int8) throws { try encode(Int(value)) } func encode(_ value: Int16) throws { try encode(Int(value)) } func encode(_ value: Int32) throws { try encode(Int(value)) } func encode(_ value: Int64) throws { try encode(Int(value)) } func encode(_ value: UInt) throws { try encode(Int(value)) } func encode(_ value: UInt8) throws { try encode(UInt(value)) } func encode(_ value: UInt16) throws { try encode(UInt(value)) } func encode(_ value: UInt32) throws { try encode(UInt(value)) } func encode(_ value: UInt64) throws { try encode(UInt(value)) } func encode(_ value: Float) throws { try encode(Double(value)) } func encode<T>(_ value: T) throws where T: Encodable { if let data = value as? Data { // special case for data if let utf8 = String(data: data, encoding: .utf8) { encoder.plaintext = utf8 } else { encoder.plaintext = data.base64EncodedString() } } else { try value.encode(to: encoder) } } }
mit
f48c18c07e29542017658178247b1fc8
32.074766
103
0.619667
4.620104
false
false
false
false
ElSquash/weavr-team
CustomStuff/DataControl.swift
1
1595
// // DataControl.swift // Weavr // // Created by Joshua Peeling on 6/16/16. // Copyright © 2016 Evan Dekhayser. All rights reserved. // import Foundation class DataControl { static var instance : DataControl? // Keys for userDefaults // Holds data that must be carried accross instances of the app let TOKEN = "currentToken" let ID = "_id" let userDefaults = NSUserDefaults.standardUserDefaults() // Data that can be deleted accross instances of the app var needLocationUpdate = false var currentLatitude = 0.0 var currentLongitude = 0.0 var mapRegionSet = false private init(){ } static func getInstance()-> DataControl { if(instance == nil){ instance = DataControl() } return instance! } func tokenExists() -> Bool{ if userDefaults.stringForKey(TOKEN) != nil{ return true } return false } func getToken() -> String { return userDefaults.stringForKey(TOKEN)! } func getID() -> String { return userDefaults.stringForKey(ID)! } func setUserPersistingData(token token: String, _id: String){ userDefaults.setObject(token, forKey:TOKEN) userDefaults.setObject(_id, forKey:ID) } func clearUserPersistingData(){ userDefaults.removeObjectForKey(TOKEN) userDefaults.removeObjectForKey(ID) } }
mit
1e4b43e9c9dc0ec84ab37055673330f1
19.701299
67
0.566499
5.108974
false
false
false
false
diwu/LeetCode-Solutions-in-Swift
Solutions/Solutions/Easy/Easy_067_Add_Binary.swift
1
1384
/* https://leetcode.com/problems/add-binary/ #67 Add Binary Given two binary strings, return their sum (also a binary string). For example, a = "11" b = "1" Return "100". Inspired by @makuiyu at https://leetcode.com/discuss/25593/short-code-by-c */ import Foundation private extension String { subscript (index: Int) -> Character { return self[self.index(self.startIndex, offsetBy: index)] } } struct Easy_067_Add_Binary { static func addBinary(a: String, b: String) -> String { var s = "" var c: Int = 0 var i = a.count - 1 var j = b.count - 1 let characterDict: [Character: Int] = [ "0": 0, "1": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9, ] let intDict: [Int: String] = [ 0: "0", 1: "1", 2: "2", 3: "3", 4: "4", 5: "5", 6: "6", 7: "7", 8: "8", 9: "9", ] while i >= 0 || j >= 0 || c == 1 { c += i >= 0 ? characterDict[a[i]]! : 0 i -= 1 c += j >= 0 ? characterDict[b[j]]! : 0 j -= 1 s = intDict[c%2]! + s c /= 2 } return s } }
mit
2c598b76a45036b619db3902e56ed6ba
19.969697
74
0.393064
3.33494
false
false
false
false
looopTools/irisPause
break_window.swift
1
2466
// // break_window.swift // irisPause // // Created by Lars Nielsen on 18/01/16. // Copyright © 2016 Lars Nielsen. All rights reserved. // import Cocoa class break_window: NSWindowController { @IBOutlet weak var break_image: NSImageView! @IBOutlet weak var counter_label: NSTextField! var timeout_timer: Timer! var count_down_timer: Timer! var settings_handler = settings_handling.settings_handler var counter = 0 override func windowDidLoad() { super.windowDidLoad() self.window!.orderFront(self) self.window!.level = Int(CGWindowLevelForKey(.floatingWindow)) self.window!.title = "irisPause" let icon:NSImage = NSImage(named: "pause_icon")! break_image.image = icon } @IBAction func cancel_break(_ sender: NSButton) { // cancle break } @IBAction func add_five_minuts(_ sender: NSButton) { // Temp add five minuts to work period } func show_window() { self.showWindow(nil) counter = settings_handler.get_timeout_time() timeout_timer = intialise_timeout_timer() count_down_timer = initialise_count_down_timer() } func update_label() { //counter_label.setStringValue = counter; counter_label.stringValue = String(counter) counter = counter - 1 } func disable_window() { if(self.window!.isVisible) { print("Went into disable window") // Disable and resetting timers timeout_timer.invalidate() timeout_timer = nil count_down_timer.invalidate() count_down_timer = nil window?.close() print("disable completed") } else { print("demo") } } func intialise_timeout_timer() -> Timer { return Timer.scheduledTimer(timeInterval: Double(settings_handler.get_timeout_time()), target: self, selector: #selector(break_window.disable_window), userInfo: nil, repeats: true) } func initialise_count_down_timer() -> Timer { print("you got to be kidding") return Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(break_window.update_label), userInfo: nil, repeats: true) } @IBAction func close_window(_ sender: NSButton) { disable_window() } }
gpl-3.0
8ea3b48997f94624d6dfa787ad838058
27.011364
188
0.593509
4.417563
false
false
false
false
codingforentrepreneurs/Django-to-iOS
Source/ios/srvup/Project.swift
1
5627
// // Project.swift // srvup // // Created by Justin Mitchel on 6/15/15. // Copyright (c) 2015 Coding for Entrepreneurs. All rights reserved. // import UIKit import Foundation import Alamofire import KeychainAccess import SwiftyJSON class Project:NSObject { var title:String var url:String var id:Int var slug:String var projectDescription: String? var imageUrlString: String? // var videoSet = [JSON]() var lectureSet = [Lecture]() init(title:String, url:String, id:Int, slug:String) { self.title = title self.url = url self.id = id self.slug = slug } func image() -> UIImage? { if self.imageUrlString != nil { let url = NSURL(string: self.imageUrlString!)! let imageData = NSData(contentsOfURL: url)! let image = UIImage(data: imageData) return image } return nil } func createLectures(theArray:[JSON]) { if self.lectureSet.count == 0 && theArray.count > 0 { for i in theArray { var lecture = Lecture(title: i["title"].string!, url: i["url"].string!, id: i["id"].int!, slug: i["slug"].string!, order: i["order"].int!, embedCode: i["embed_code"].string!) lecture.shareMessage = i["share_message"].string lecture.timestamp = i["timestamp"].string if i["comment_set"].array != nil { lecture.commentSet = i["comment_set"].array! } if i["free_preview"].bool != nil { lecture.freePreview = i["free_preview"].bool! } self.lectureSet.append(lecture) } } } } class Lecture: NSObject { var title: String var url: String var id: Int var slug: String var order: Int var embedCode: String var freePreview = false var shareMessage: String? var timestamp: String? var commentSet = [JSON]() init(title:String, url:String, id:Int, slug:String, order:Int, embedCode:String) { self.title = title self.url = url self.id = id self.slug = slug self.order = order self.embedCode = embedCode } func updateLectureComments(completion:(success:Bool)->Void){ let keychain = Keychain(service: "com.codingforentrepreneurs.srvup") let token = keychain["token"] if token != nil { var manager = Alamofire.Manager.sharedInstance manager.session.configuration.HTTPAdditionalHeaders = [ "Authorization": "JWT \(token!)" ] let getCommentsRequest = manager.request(Method.GET, self.url, parameters:nil, encoding: ParameterEncoding.JSON) getCommentsRequest.responseJSON(options: nil, completionHandler: { (request, response, data, error) -> Void in let statusCode = response?.statusCode if (200 ... 299 ~= statusCode!) && (data != nil) { let jsonData = JSON(data!) let commentSet = jsonData["comment_set"].array if commentSet != nil { self.commentSet = commentSet! } completion(success: true) } else { completion(success: false) } }) } else { println("No token") } } func addComment(commentText:String, parent:Int?, completion:(success:Bool, dataSent:JSON?)->Void){ let commentCreateUrlString = "http://127.0.0.1:8000/api2/comment/create/" let keychain = Keychain(service: "com.codingforentrepreneurs.srvup") let token = keychain["token"] let user = keychain["user"] let userid = keychain["userid"] if token != nil && userid != nil { var manager = Alamofire.Manager.sharedInstance manager.session.configuration.HTTPAdditionalHeaders = [ "Authorization": "JWT \(token!)" ] var params = ["text" : commentText, "video": "\(self.id)", "user": "\(userid!)"] if parent != nil { params = ["text" : commentText, "video": "\(self.id)", "user": "\(userid!)", "parent": "\(parent!)"] } let addCommentRequest = manager.request(Method.POST, commentCreateUrlString, parameters:params, encoding: ParameterEncoding.JSON) println(self.commentSet.count) addCommentRequest.responseJSON(options: nil, completionHandler: { (request, response, data, error) -> Void in let statusCode = response?.statusCode // 201 println(response) println(data) println(error) if (200 ... 299 ~= statusCode!) && (data != nil) { let jsonData = JSON(data!) self.commentSet.insert(jsonData, atIndex: 0) // self.commentSet.append(jsonData) let newData = ["text": "\(commentText)", "user":"\(user!)"] completion(success: true, dataSent:JSON(newData)) } else { completion(success: false, dataSent:nil) } }) } else { println("No token") } } }
apache-2.0
609a5021dec6504fc12622384871e510
33.317073
190
0.522125
4.685262
false
false
false
false
rohan1989/FacebookOauth2Swift
HanekeSwift-feature-swift-3/HanekeTests/XCTestCase+Test.swift
3
840
// // XCTestCase+Test.swift // Haneke // // Created by Hermes Pique on 9/15/14. // Copyright (c) 2014 Haneke. All rights reserved. // import XCTest extension XCTestCase { func waitFor(_ interval : TimeInterval) { let date = Date(timeIntervalSinceNow: interval) RunLoop.current.run(mode: .defaultRunLoopMode, before: date) } func wait(_ timeout : TimeInterval, condition: () -> Bool) { let timeoutDate = Date(timeIntervalSinceNow: timeout) var success = false while !success && (NSDate().laterDate(timeoutDate) == timeoutDate) { success = condition() if !success { RunLoop.current.run(mode: .defaultRunLoopMode, before: timeoutDate) } } if !success { XCTFail("Wait timed out.") } } }
mit
4355f91d2c2b9ed6960fbf537f2fc29c
25.25
83
0.591667
4.397906
false
true
false
false
my-mail-ru/swiftperl
Sources/Perl/Embed.swift
1
1439
import CPerl #if os(Linux) || os(FreeBSD) || os(PS4) || os(Android) || CYGWIN import func Glibc.atexit #elseif os(macOS) || os(iOS) || os(watchOS) || os(tvOS) import func Darwin.atexit #endif private var perlInitialized: Bool = { PerlInterpreter.sysInit() atexit { PerlInterpreter.sysTerm() } return true }() extension PerlInterpreter { static func sysInit() { var argc = CommandLine.argc var argv = CommandLine.unsafeArgv var env = environ! PERL_SYS_INIT3(&argc, &argv, &env) } static func sysTerm() { PERL_SYS_TERM() } /// Creates a new embedded Perl interpreter. public static func new() -> PerlInterpreter { _ = perlInitialized let perl = PerlInterpreter(Pointee.alloc()!) perl.pointee.construct() perl.embed() return perl } /// Shuts down the Perl interpreter. public func destroy() { pointee.destruct() pointee.free() } func embed() { pointee.Iorigalen = 1 pointee.Iperl_destruct_level = 2 pointee.Iexit_flags |= UInt8(PERL_EXIT_DESTRUCT_END) let args: StaticString = "\0-e\00\0" args.withUTF8Buffer { $0.baseAddress!.withMemoryRebound(to: CChar.self, capacity: $0.count) { let start = UnsafeMutablePointer<CChar>(mutating: $0) var cargs: [UnsafeMutablePointer<CChar>?] = [start, start + 1, start + 4] let status = cargs.withUnsafeMutableBufferPointer { pointee.parse(xs_init, Int32($0.count), $0.baseAddress, nil) } assert(status == 0) } } } }
mit
0e082fb1436554aabaeb4b7534c90435
24.245614
77
0.682418
3.01046
false
false
false
false
johnno1962/eidolon
Kiosk/Bid Fulfillment/ConfirmYourBidPINViewController.swift
1
5972
import UIKit import Moya import RxSwift import Action class ConfirmYourBidPINViewController: UIViewController { private var _pin = Variable("") @IBOutlet var keypadContainer: KeypadContainerView! @IBOutlet var pinTextField: TextField! @IBOutlet var confirmButton: Button! @IBOutlet var bidDetailsPreviewView: BidDetailsPreviewView! lazy var pin: Observable<String> = { self.keypadContainer.stringValue }() var provider: Networking! class func instantiateFromStoryboard(storyboard: UIStoryboard) -> ConfirmYourBidPINViewController { return storyboard.viewControllerWithID(.ConfirmYourBidPIN) as! ConfirmYourBidPINViewController } override func viewDidLoad() { super.viewDidLoad() pin .bindTo(_pin) .addDisposableTo(rx_disposeBag) pin .bindTo(pinTextField.rx_text) .addDisposableTo(rx_disposeBag) pin .mapToOptional() .bindTo(fulfillmentNav().bidDetails.bidderPIN) .addDisposableTo(rx_disposeBag) let pinExists = pin.map { $0.isNotEmpty } let bidDetails = fulfillmentNav().bidDetails let provider = self.provider bidDetailsPreviewView.bidDetails = bidDetails /// verify if we can connect with number & pin confirmButton.rx_action = CocoaAction(enabledIf: pinExists) { [weak self] _ in guard let me = self else { return .empty() } var loggedInProvider: AuthorizedNetworking! return bidDetails.authenticatedNetworking(provider) .doOnNext { provider in loggedInProvider = provider } .flatMap { provider -> Observable<AuthorizedNetworking> in return provider .request(ArtsyAuthenticatedAPI.Me) .filterSuccessfulStatusCodes() .mapReplace(provider) } .flatMap { provider -> Observable<AuthorizedNetworking> in return me .fulfillmentNav() .updateUserCredentials(loggedInProvider) .mapReplace(provider) } .flatMap { provider -> Observable<AuthorizedNetworking> in return me .fulfillmentNav() .updateUserCredentials(loggedInProvider) .mapReplace(provider) } .flatMap { provider -> Observable<AuthorizedNetworking> in return me .checkForCreditCard(loggedInProvider) .doOnNext { cards in // If the cards list doesn't exist, or its .empty, then perform the segue to collect one. // Otherwise, proceed directly to the loading view controller to place the bid. if cards.isEmpty { me.performSegue(.ArtsyUserviaPINHasNotRegisteredCard) } else { me.performSegue(.PINConfirmedhasCard) } } .mapReplace(provider) } .map(void) .doOnError { error in if let response = (error as NSError).userInfo["data"] as? Response { let responseBody = NSString(data: response.data, encoding: NSUTF8StringEncoding) print("Error authenticating(\(response.statusCode)): \(responseBody)") } me.showAuthenticationError() } } } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { super.prepareForSegue(segue, sender: sender) if segue == .ArtsyUserviaPINHasNotRegisteredCard { let viewController = segue.destinationViewController as! RegisterViewController viewController.provider = provider } else if segue == .PINConfirmedhasCard { let viewController = segue.destinationViewController as! LoadingViewController viewController.provider = provider } } @IBAction func forgotPINTapped(sender: AnyObject) { let auctionID = fulfillmentNav().auctionID let number = fulfillmentNav().bidDetails.newUser.phoneNumber.value ?? "" let endpoint: ArtsyAPI = ArtsyAPI.BidderDetailsNotification(auctionID: auctionID, identifier: number) let alertController = UIAlertController(title: "Forgot PIN", message: "We have sent your bidder details to your device.", preferredStyle: .Alert) let cancelAction = UIAlertAction(title: "Back", style: .Cancel) { (_) in } alertController.addAction(cancelAction) self.presentViewController(alertController, animated: true) {} provider.request(endpoint) .filterSuccessfulStatusCodes() .subscribeNext { _ in // Necessary to subscribe to the actual observable. This should be in a CocoaAction of the button, instead. logger.log("Sent forgot PIN request") } .addDisposableTo(rx_disposeBag) } func showAuthenticationError() { confirmButton.flashError("Wrong PIN") pinTextField.flashForError() keypadContainer.resetAction.execute() } func checkForCreditCard(loggedInProvider: AuthorizedNetworking) -> Observable<[Card]> { let endpoint = ArtsyAuthenticatedAPI.MyCreditCards return loggedInProvider.request(endpoint).filterSuccessfulStatusCodes().mapJSON().mapToObjectArray(Card.self) } } private extension ConfirmYourBidPINViewController { @IBAction func dev_loggedInTapped(sender: AnyObject) { self.performSegue(.PINConfirmedhasCard) } }
mit
a17a69bdc2efc17de717b7482490efc3
38.82
153
0.599632
5.995984
false
false
false
false
BrunoMazzo/CocoaHeadsApp
CocoaHeadsApp/Classes/Events/Controllers/EventsListDataSource.swift
3
948
import UIKit class EventsListTableDataSource: NSObject, UITableViewDataSource { let viewModel :EventsListViewModel init(viewModel : EventsListViewModel) { self.viewModel = viewModel super.init() } // MARK: - Table view data source func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.viewModel.items.value.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let reuseIdentifier = R.nib.eventsListTableViewCell.name let cell = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier, forIndexPath: indexPath) guard let eventsCell = cell as? EventsListTableViewCell else { return cell } //eventsCell.events.value = viewModel.items.value[indexPath.item] return eventsCell } }
mit
f0d9d2cd3f768bc70d0e34ea5522b4b6
29.580645
109
0.67616
5.576471
false
false
false
false
apple/swift-argument-parser
Examples/count-lines/CountLines.swift
1
2243
//===----------------------------------------------------------*- swift -*-===// // // This source file is part of the Swift Argument Parser open source project // // Copyright (c) 2020 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 // //===----------------------------------------------------------------------===// import ArgumentParser import Foundation @main @available(macOS 10.15, *) struct CountLines: AsyncParsableCommand { @Argument( help: "A file to count lines in. If omitted, counts the lines of stdin.", completion: .file(), transform: URL.init(fileURLWithPath:)) var inputFile: URL? = nil @Option(help: "Only count lines with this prefix.") var prefix: String? = nil @Flag(help: "Include extra information in the output.") var verbose = false } @available(macOS 10.15, *) extension CountLines { var fileHandle: FileHandle { get throws { guard let inputFile = inputFile else { return .standardInput } return try FileHandle(forReadingFrom: inputFile) } } func printCount(_ count: Int) { guard verbose else { print(count) return } if let filename = inputFile?.lastPathComponent { print("Lines in '\(filename)'", terminator: "") } else { print("Lines from stdin", terminator: "") } if let prefix = prefix { print(", prefixed by '\(prefix)'", terminator: "") } print(": \(count)") } mutating func run() async throws { guard #available(macOS 12, *) else { print("'count-lines' isn't supported on this platform.") return } let countAllLines = prefix == nil let lineCount = try await fileHandle.bytes.lines.reduce(0) { count, line in if countAllLines || line.starts(with: prefix!) { return count + 1 } else { return count } } printCount(lineCount) } }
apache-2.0
3c8b2c680dbe7f96c28c0f862e77db59
28.12987
83
0.527864
5.086168
false
false
false
false
blg-andreasbraun/ProcedureKit
Sources/Identity.swift
3
806
// // ProcedureKit // // Copyright © 2016 ProcedureKit. All rights reserved. // import Foundation public protocol Identifiable { var identifier: UUID { get } } public func ==<T: Identifiable> (lhs: T, rhs: T) -> Bool { return lhs.identifier == rhs.identifier } public extension Procedure { struct Identity: Identifiable, Equatable { public static func == (lhs: Identity, rhs: Identity) -> Bool { return lhs.identifier == rhs.identifier } public let identifier: UUID public let name: String? public var description: String { return name.map { "\($0) #\(identifier)" } ?? "Unnamed Procedure #\(identifier)" } } var identity: Identity { return Identity(identifier: identifier, name: name) } }
mit
f1e6fc64b11b17461ce827fa1b680e1a
21.361111
92
0.614907
4.423077
false
false
false
false
monyschuk/JSON
JSON/JSON.swift
1
9027
// // JSON.swift // JSON // // Created by Mark Onyschuk on 2016-10-16. // Copyright © 2016 Mark Onyschuk. All rights reserved. // import Foundation public enum JSONError: Error { case invalidURL(URL) } public enum JSON { case null case bool(Bool) case string(String) case number(Double) case array([JSON]) case object([String:JSON]) public init() { self = .null } } extension JSON:Equatable { public static func ==(lhs: JSON, rhs: JSON) -> Bool { switch (lhs, rhs) { case (.null, .null): return true case let (.bool(v1), .bool(v2)): return v1 == v2 case let (.string(v1), .string(v2)): return v1 == v2 case let (.number(v1), .number(v2)): return v1 == v2 case let (.array(v1), .array(v2)): return v1 == v2 case let (.object(v1), .object(v2)): return v1 == v2 default: return false } } } extension JSON: RawRepresentable { private struct ObjCEncodings { static let bool = NSNumber(value: true).objCType } public var rawValue: Any { switch self { case .null: return NSNull() case let .bool(value): return value case let .string(value): return value case let .number(value): return value case let .array(value): return value.map { $0.rawValue } case let .object(value): var raw = [String:Any]() for (k, v) in value { raw[k] = v.rawValue } return raw } } public init?(rawValue: Any) { switch rawValue { case is NSNull: self = .null case let value as NSNumber: // NOTE: under the hood, JSONSerialization instantiates // NSNumber objects to represent all numerics including booleans. // // The underlying type of the numeric can be identified using its // associated ObjC type encoding. Bool is the only type we're // interested in differentiating. switch value.objCType { case JSON.ObjCEncodings.bool: self = .bool(value.boolValue) default: self = .number(value.doubleValue) } case let value as NSString: self = .string(value as String) case let value as [Any]: self = .array(value.flatMap { JSON(rawValue: $0) }) case let value as [String:Any]: var unraw = [String:JSON]() for (k, v) in value { if let v = JSON(rawValue: v) { unraw[k] = v } } self = .object(unraw) default: return nil } } } extension JSON { public enum PrintOptions { case pretty case compact } public func print(options: PrintOptions = .compact) -> String { switch self { case .null: return "null" case let .bool(value): return "\(value)" case let .number(value): return "\(value)" case let .string(value): return "\(value)" default: let writingOptions: JSONSerialization.WritingOptions = (options == .pretty) ? [.prettyPrinted] : [] if let data = try? JSON.write(self, options: writingOptions), let text = String(data: data, encoding: String.Encoding.utf8) { return text } else { return "" } } } } //extension JSON: CustomStringConvertible { //public var description: String { // return print(options: .pretty) //} //} extension JSON { public var isNull: Bool { switch self { case .null: return true default: return false } } public var asBool: Bool? { switch self { case let .bool(value): return value default: return nil } } public var asInt: Int? { switch self { case let .number(value): return Int(value) default: return nil } } public var asUInt: UInt? { switch self { case let .number(value): return UInt(value) default: return nil } } public var asInt64: Int64? { switch self { case let .number(value): return Int64(value) default: return nil } } public var asUInt64: UInt64? { switch self { case let .number(value): return UInt64(value) default: return nil } } public var asFloat: Float? { switch self { case let .number(value): return Float(value) default: return nil } } public var asCGFloat: CGFloat? { switch self { case let .number(value): return CGFloat(value) default: return nil } } public var asDouble: Double? { switch self { case let .number(value): return Double(value) default: return nil } } public var asString: String? { switch self { case let .string(value): return value default: return nil } } public var asArray: [JSON]? { switch self { case let .array(values): return values default: return nil } } public var asObject: [String:JSON]? { switch self { case let .object(values): return values default: return nil } } } // dictionary interface extension JSON { public subscript(key: String) -> JSON { get { switch self { case let .object(value): return value[key] ?? .null default: return .null } } mutating set(newValue) { switch self { case let .object(value): var value = value value[key] = newValue self = .object(value) default: self = .object([key: newValue]) } } } public var keys: [String] { switch self { case let .object(value): return value.map { $0.key } default: return [] } } public var values: [JSON] { switch self { case let .object(value): return value.map { $0.value } default: return [] } } } // array interface extension JSON { public subscript(index: Int) -> JSON { get { switch self { case let .array(value): return (0..<value.count).contains(index) ? value[index] : .null default: return .null } } mutating set(newValue) { switch self { case let .array(value): var value = value if index < value.startIndex { value.insert(newValue, at: 0) } else if index >= value.count { value.append(newValue) } else { value[index] = newValue } self = .array(value) default: self = .array([newValue]) } } } public var count: Int { switch self { case let .array(value): return value.count default: return 0 } } public mutating func append(_ value: JSON) { self[count] = value } } extension JSON { public static func read(data: Data) throws -> JSON { return JSON(rawValue: try JSONSerialization.jsonObject(with: data, options: []))! } public static func read(url: URL) throws -> JSON { guard let stream = InputStream(url: url) else { throw JSONError.invalidURL(url) } stream.open() defer { stream.close() } return JSON(rawValue: try JSONSerialization.jsonObject(with: stream, options: []))! } public static func write(_ json: JSON, options: JSONSerialization.WritingOptions = []) throws -> Data { return try JSONSerialization.data(withJSONObject: json.rawValue, options: options) } }
mit
2b88e6d2f545d253dc14ae3e8adc5a8b
25.086705
107
0.470308
4.79087
false
false
false
false
ngageoint/mage-ios
Mage/StraightLineNav/StraightLineNavigationView.swift
1
13112
// // StraightLineNavigationView.swift // MAGE // // Created by Daniel Barela on 4/12/21. // Copyright © 2021 National Geospatial Intelligence Agency. All rights reserved. // import Foundation import PureLayout import UIKit import Kingfisher class StraightLineNavigationView: UIView { var didSetupConstraints = false; var delegate: StraightLineNavigationDelegate?; var scheme: MDCContainerScheming?; var locationManager: CLLocationManager?; var destinationCoordinate: CLLocationCoordinate2D?; var destinationMarker: UIImage?; var relativeBearingColor: UIColor = .systemGreen; var headingColor: UIColor = .systemRed; var headingLabel: UILabel = UILabel(forAutoLayout: ()); var speedLabel: UILabel = UILabel(forAutoLayout: ()); var distanceToTargetLabel: UILabel = UILabel(forAutoLayout: ()); var relativeBearingToTargetLabel: UILabel = UILabel(forAutoLayout: ()); var compassView: CompassView?; let navigation = UIImageView(image: UIImage(systemName: "location.north.fill")) var destinationMarkerUrl: URL? { get { return nil } set { guard let newValue = newValue else { return } let processor = DownsamplingImageProcessor(size: CGSize(width: 40, height: 40)) destinationMarkerView.kf.indicatorType = .activity destinationMarkerView.kf.setImage( with: newValue, options: [ .requestModifier(ImageCacheProvider.shared.accessTokenModifier), .processor(processor), .scaleFactor(UIScreen.main.scale), .transition(.fade(1)), .cacheOriginalImage ]) { result in switch result { case .success(_): self.setNeedsLayout() case .failure(let error): print("Job failed: \(error.localizedDescription)") } } } } private lazy var directionArrow: UIView = { let view = UIView.newAutoLayout(); view.addSubview(navigation); navigation.autoPinEdge(toSuperviewEdge: .top); navigation.autoAlignAxis(toSuperviewAxis: .vertical) return view; }() private lazy var cancelButton: UIButton = { let cancelButton = UIButton(type: .custom); cancelButton.accessibilityLabel = "cancel"; cancelButton.setImage(UIImage(systemName: "xmark.circle.fill"), for: .normal); cancelButton.addTarget(self, action: #selector(cancelButtonPressed), for: .touchUpInside) return cancelButton; }(); private lazy var myInformationContainer: UIView = { let view = UIView.newAutoLayout(); view.addSubview(headingLabel); view.addSubview(speedLabel); return view; }() private lazy var targetInformationContainer: UIView = { let view = UIView.newAutoLayout(); view.addSubview(relativeBearingToTargetLabel); view.addSubview(distanceToTargetLabel); return view; }() private lazy var targetMarkerView: UIImageView = { let view = UIImageView(image: UIImage(named: "location_tracking_on")); view.contentMode = .scaleAspectFit; return view; }(); private lazy var speedMarkerView: UIImageView = { let view = UIImageView(image: UIImage(named: "speed")); view.contentMode = .scaleAspectFit; return view; }(); private lazy var destinationMarkerView: UIImageView = { let view = UIImageView(image: destinationMarker); view.contentMode = .scaleAspectFit; return view; }(); private lazy var destinationContainer: UIView = { let view = UIView(forAutoLayout: ()); view.addSubview(destinationMarkerView); view.addSubview(distanceToTargetLabel); distanceToTargetLabel.textAlignment = .center; return view; }(); private lazy var ipadView: UIView = { let view = UIView(forAutoLayout: ()); view.autoSetDimension(.width, toSize: 400, relation: .lessThanOrEqual); view.layer.cornerRadius = 20.0; return view; }(); private lazy var rootView: UIView = { if UIDevice.current.userInterfaceIdiom == .pad { addSubview(ipadView); self.backgroundColor = .clear; return ipadView; } return self; }() func applyTheme(withScheme scheme: MDCContainerScheming?) { rootView.backgroundColor = scheme?.colorScheme.surfaceColor; headingLabel.textColor = scheme?.colorScheme.onSurfaceColor.withAlphaComponent(0.87); speedLabel.textColor = scheme?.colorScheme.onSurfaceColor.withAlphaComponent(0.87); speedMarkerView.tintColor = scheme?.colorScheme.onSurfaceColor.withAlphaComponent(0.87); targetMarkerView.tintColor = scheme?.colorScheme.onSurfaceColor.withAlphaComponent(0.87); distanceToTargetLabel.textColor = scheme?.colorScheme.onSurfaceColor.withAlphaComponent(0.87); relativeBearingToTargetLabel.textColor = scheme?.colorScheme.onSurfaceColor.withAlphaComponent(0.87); cancelButton.tintColor = scheme?.colorScheme.onSurfaceColor.withAlphaComponent(0.87); headingLabel.font = scheme?.typographyScheme.overline; speedLabel.font = scheme?.typographyScheme.overline; distanceToTargetLabel.font = scheme?.typographyScheme.headline6; relativeBearingToTargetLabel.font = scheme?.typographyScheme.headline6; headingLabel.textColor = self.headingColor; navigation.tintColor = self.relativeBearingColor compassView?.applyTheme(withScheme: scheme); } convenience init(locationManager: CLLocationManager?, destinationMarker: UIImage?, destinationCoordinate: CLLocationCoordinate2D, delegate: StraightLineNavigationDelegate?, scheme: MDCContainerScheming? = nil, targetColor: UIColor = .systemGreen, bearingColor: UIColor = .systemRed) { self.init(frame: .zero); self.locationManager = locationManager; self.destinationCoordinate = destinationCoordinate; self.destinationMarker = destinationMarker; self.scheme = scheme; self.relativeBearingColor = targetColor; self.headingColor = bearingColor; self.delegate = delegate; layoutView(); applyTheme(withScheme: scheme); } override func removeFromSuperview() { super.removeFromSuperview() for subview in subviews { subview.removeFromSuperview() } self.compassView = nil } override func updateConstraints() { if (!didSetupConstraints) { compassView?.autoSetDimensions(to: CGSize(width: 350, height: 350)) compassView?.autoAlignAxis(toSuperviewAxis: .vertical); compassView?.autoAlignAxis(.horizontal, toSameAxisOf: self, withOffset: 50); cancelButton.autoPinEdge(toSuperviewEdge: .top, withInset: 4); cancelButton.autoPinEdge(toSuperviewEdge: .right, withInset: 4); destinationMarkerView.autoSetDimensions(to: CGSize(width: 18, height: 18)); destinationMarkerView.autoAlignAxis(toSuperviewAxis: .vertical); targetInformationContainer.autoPinEdge(.top, to: .bottom, of: destinationMarkerView, withOffset: 16); distanceToTargetLabel.autoPinEdgesToSuperviewEdges(with: .zero, excludingEdge: .right); relativeBearingToTargetLabel.autoPinEdgesToSuperviewEdges(with: .zero, excludingEdge: .left); relativeBearingToTargetLabel.autoPinEdge(.left, to: .right, of: distanceToTargetLabel, withOffset: 8); targetInformationContainer.autoAlignAxis(toSuperviewAxis: .vertical); speedLabel.autoPinEdgesToSuperviewEdges(with: .zero, excludingEdge: .right); headingLabel.autoPinEdgesToSuperviewEdges(with: .zero, excludingEdge: .left); headingLabel.autoPinEdge(.left, to: .right, of: speedLabel, withOffset: 8); myInformationContainer.autoPinEdge(.top, to: .bottom, of: targetInformationContainer, withOffset: 2); myInformationContainer.autoPinEdge(toSuperviewEdge: .bottom, withInset: 4); myInformationContainer.autoAlignAxis(toSuperviewAxis: .vertical); directionArrow.autoAlignAxis(.horizontal, toSameAxisOf: destinationMarkerView); directionArrow.autoAlignAxis(.vertical, toSameAxisOf: destinationMarkerView); directionArrow.autoSetDimensions(to: CGSize(width: 51, height: 51)); if UIDevice.current.userInterfaceIdiom == .pad { NSLayoutConstraint.autoSetPriority(.defaultLow) { ipadView.autoPinEdgesToSuperviewEdges() } ipadView.autoAlignAxis(toSuperviewAxis: .vertical) } self.autoSetDimension(.height, toSize: 75); didSetupConstraints = true; } super.updateConstraints(); } func populate(relativeBearingColor: UIColor = .systemGreen, headingColor: UIColor = .systemRed, destinationCoordinate: CLLocationCoordinate2D? = nil) { if let destinationCoordinate = destinationCoordinate { self.destinationCoordinate = destinationCoordinate } self.relativeBearingColor = relativeBearingColor; self.headingColor = headingColor; let measurementFormatter = MeasurementFormatter(); measurementFormatter.unitOptions = .providedUnit; measurementFormatter.unitStyle = .short; measurementFormatter.numberFormatter.maximumFractionDigits = 2; guard let userLocation = locationManager?.location else { return; } var bearing = userLocation.course; let speed = userLocation.speed; // if the user is moving, use their direction of movement if (bearing < 0 || speed <= 0) { // if the user is not moving, use the heading of the phone if let trueHeading = locationManager?.heading?.trueHeading { bearing = trueHeading; } } if bearing >= 0, let destinationCoordinate = self.destinationCoordinate { let bearingTo = userLocation.coordinate.bearing(to: destinationCoordinate); compassView?.updateHeading(heading: bearing, destinationBearing: bearingTo, targetColor: self.relativeBearingColor, bearingColor: self.headingColor); let headingMeasurement = Measurement(value: bearing, unit: UnitAngle.degrees); let bearingToMeasurement = Measurement(value: bearingTo, unit: UnitAngle.degrees); headingLabel.text = "\(measurementFormatter.string(from: headingMeasurement))"; relativeBearingToTargetLabel.text = "@ \(measurementFormatter.string(from: bearingToMeasurement))"; let degreeMeasurement = Measurement(value: 360 - (headingMeasurement.value - bearingToMeasurement.value) , unit: UnitAngle.degrees); directionArrow.transform = CGAffineTransform(rotationAngle: CGFloat(degreeMeasurement.converted(to: .radians).value)); relativeBearingToTargetLabel.textColor = self.relativeBearingColor; headingLabel.textColor = self.headingColor; navigation.tintColor = self.relativeBearingColor let destinationLocation = CLLocation(latitude: destinationCoordinate.latitude, longitude: destinationCoordinate.longitude); let metersMeasurement = NSMeasurement(doubleValue: destinationLocation.distance(from: userLocation), unit: UnitLength.meters); let convertedMeasurement = metersMeasurement.converting(to: UnitLength.nauticalMiles); distanceToTargetLabel.text = "\(measurementFormatter.string(from: convertedMeasurement))" } if let speed = locationManager?.location?.speed { let metersPerSecondMeasurement = Measurement(value: speed, unit: UnitSpeed.metersPerSecond); speedLabel.text = "\(measurementFormatter.string(from: metersPerSecondMeasurement.converted(to: .knots)))"; } } func layoutView() { compassView = CompassView(scheme: self.scheme, targetColor: self.relativeBearingColor, headingColor: self.headingColor); compassView?.clipsToBounds = true; compassView?.layer.cornerRadius = 175 rootView.addSubview(compassView!); rootView.addSubview(destinationMarkerView); rootView.addSubview(myInformationContainer); rootView.addSubview(targetInformationContainer); rootView.addSubview(directionArrow); rootView.addSubview(cancelButton); } @objc func cancelButtonPressed() { delegate?.cancelStraightLineNavigation(); } }
apache-2.0
4bf37291e16065a252e15013f13d8e25
44.524306
288
0.663107
5.534403
false
false
false
false
nathawes/swift
test/SourceKit/Misc/mixed_completion_sequence.swift
5
1128
protocol Target1 {} protocol Target2 {} protocol Target3 {} struct ConcreteTarget1 : Target1 {} struct ConcreteTarget2 : Target2 {} struct ConcreteTarget3 : Target3 {} protocol P { associatedtype Assoc func protocolMethod(asc: Assoc) -> Self } extension P { func protocolMethod(asc: Assoc) -> Self { return self } } enum MyEnum { case foo, bar } class C : P { typealias Assoc = String static func staticMethod() -> Self {} func instanceMethod(x: MyEnum) -> C {} func methodForTarget1() -> ConcreteTarget1 {} func methodForTarget2() -> ConcreteTarget2 {} } func testing(obj: C) { let _ = obj. } func testing(obj: C) { let _ = obj.instanceMethod(x: ) } // RUN: %sourcekitd-test \ // RUN: -req=complete -pos=29:14 %s -- %s -module-name MyModule == \ // RUN: -req=conformingmethods -pos=29:14 -req-opts=expectedtypes='$s8MyModule7Target2PD;$s8MyModule7Target1PD' %s -- %s -module-name MyModule == \ // RUN: -req=typecontextinfo -pos=32:33 %s -- %s -module-name MyModule == \ // RUN: -req=complete -pos=29:14 %s -- %s -module-name MyModule > %t.response // RUN: %diff -u %s.response %t.response
apache-2.0
84247a5fbd0c705425929d5699cf2f32
26.512195
149
0.669326
3.222857
false
true
false
false
vbudhram/firefox-ios
Client/Frontend/Browser/DefaultSearchPrefs.swift
2
2944
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import SwiftyJSON /* This only makes sense if you look at the structure of List.json */ class DefaultSearchPrefs { fileprivate let defaultSearchList: [String] fileprivate let locales: JSON fileprivate let regionOverrides: JSON fileprivate let globalDefaultEngine: String public init?(with filePath: URL) { guard let searchManifest = try? String(contentsOf: filePath) else { assertionFailure("Search list not found. Check bundle") return nil } let json = JSON(parseJSON: searchManifest) // Split up the JSON into useful parts locales = json["locales"] regionOverrides = json["regionOverrides"] // These are the fallback defaults guard let searchList = json["default"]["visibleDefaultEngines"].array?.flatMap({ $0.string }), let engine = json["default"]["searchDefault"].string else { assertionFailure("Defaults are not set up correctly in List.json") return nil } defaultSearchList = searchList globalDefaultEngine = engine } /* Returns an array of the visibile engines. It overrides any of the returned engines from the regionOverrides list Each langauge in the locales list has a default list of engines and then a region override list. */ open func visibleDefaultEngines(for possibileLocales: [String], and region: String) -> [String] { let engineList = possibileLocales.flatMap({ locales[$0].dictionary }).flatMap({ (localDict) -> [JSON]? in return localDict[region]?["visibleDefaultEngines"].array ?? localDict["default"]?["visibleDefaultEngines"].array }).last?.flatMap({ $0.string }) // If the engineList is empty then go ahead and use the default var usersEngineList = engineList ?? defaultSearchList // Overrides for specfic regions. if let overrides = regionOverrides[region].dictionary { usersEngineList = usersEngineList.map({ overrides[$0]?.string ?? $0 }) } return usersEngineList } /* Returns the default search given the possible locales and region The list.json locales list contains searchDefaults for a few locales. Create a list of these and return the last one. The globalDefault acts as the fallback in case the list is empty. */ open func searchDefault(for possibileLocales: [String], and region: String) -> String { return possibileLocales.flatMap({ locales[$0].dictionary }).reduce(globalDefaultEngine) { (defaultEngine, localeJSON) -> String in return localeJSON[region]?["searchDefault"].string ?? defaultEngine } } }
mpl-2.0
982252cb52effaafa40f0c8637a7db14
43.606061
138
0.676291
4.779221
false
false
false
false
SBero/SBSwiftRevealView
SBSwiftRevealView/AppDelegate.swift
1
2671
// // AppDelegate.swift // RevealView // // Created by Stephen Bero on 9/12/14. // Copyright (c) 2014 qws. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. self.window = UIWindow(frame: UIScreen.mainScreen().bounds) let viewController = ViewController() let navWidth: CGFloat = 220 let rearNavigationViewController = RearNavigationViewController(frontViewCtrl: viewController, navWidth: navWidth); // Instantiate and set to the initial view and how wide the navigation width should be self.window!.rootViewController = rearNavigationViewController; self.window!.makeKeyAndVisible() return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
bsd-2-clause
6939a27464bb5468b02e9ec669a3d51e
45.051724
285
0.735305
5.658898
false
false
false
false
tgu/HAP
Sources/HAP/Base/Constants.swift
1
10118
import Foundation public enum CharacteristicType: Codable, Equatable { case appleDefined(UInt32) case custom(UUID) init(_ hex: UInt32) { self = .appleDefined(hex) } public init(_ uuid: UUID) { self = .custom(uuid) } var rawValue: String { switch self { case let .appleDefined(value): return String(value, radix: 16) case let .custom(uuid): return uuid.uuidString } } public static func == (lhs: CharacteristicType, rhs: CharacteristicType) -> Bool { switch (lhs, rhs) { case (let .appleDefined(left), let .appleDefined(right)): return left == right case (let .custom(left), let .custom(right)): return left == right default: return false } } enum DecodeError: Error { case unsupportedValueType case malformedUUIDString } public init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() if let string = try? container.decode(String.self) { if let int = UInt32(string) { self = .appleDefined(int) } else if let uuid = UUID(uuidString: string) { self = .custom(uuid) } else { throw DecodeError.malformedUUIDString } } else { throw DecodeError.unsupportedValueType } } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(rawValue) } } // swiftlint:disable no_grouping_extension public extension CharacteristicType { static let administratorOnlyAccess = CharacteristicType(0x1) static let audioFeedback = CharacteristicType(0x5) static let brightness = CharacteristicType(0x8) static let coolingThresholdTemperature = CharacteristicType(0xD) static let currentDoorState = CharacteristicType(0xE) static let currentHeatingCoolingState = CharacteristicType(0xF) static let currentRelativeHumidity = CharacteristicType(0x10) static let currentTemperature = CharacteristicType(0x11) static let heatingThresholdTemperature = CharacteristicType(0x12) static let hue = CharacteristicType(0x13) static let identify = CharacteristicType(0x14) static let lockControlPoint = CharacteristicType(0x19) static let lockManagementAutoSecurityTimeout = CharacteristicType(0x1A) static let lockLastKnownAction = CharacteristicType(0x1C) static let lockCurrentState = CharacteristicType(0x1D) static let lockTargetState = CharacteristicType(0x1E) static let logs = CharacteristicType(0x1F) static let manufacturer = CharacteristicType(0x20) static let model = CharacteristicType(0x21) static let motionDetected = CharacteristicType(0x22) static let name = CharacteristicType(0x23) static let obstructionDetected = CharacteristicType(0x24) static let on = CharacteristicType(0x25) static let outletInUse = CharacteristicType(0x26) static let rotationDirection = CharacteristicType(0x28) static let rotationSpeed = CharacteristicType(0x29) static let saturation = CharacteristicType(0x2F) static let serialNumber = CharacteristicType(0x30) static let targetDoorState = CharacteristicType(0x32) static let targetHeatingCoolingState = CharacteristicType(0x33) static let targetRelativeHumidity = CharacteristicType(0x34) static let targetTemperature = CharacteristicType(0x35) static let temperatureDisplayUnits = CharacteristicType(0x36) static let version = CharacteristicType(0x37) static let firmwareRevision = CharacteristicType(0x52) static let hardwareRevision = CharacteristicType(0x53) static let accessoryIdentifier = CharacteristicType(0x57) static let reachable = CharacteristicType(0x63) static let airParticulateDensity = CharacteristicType(0x64) static let airParticulateSize = CharacteristicType(0x65) static let securitySystemCurrentState = CharacteristicType(0x66) static let securitySystemTargetState = CharacteristicType(0x67) static let batteryLevel = CharacteristicType(0x68) static let carbonMonoxideDetected = CharacteristicType(0x69) static let contactSensorState = CharacteristicType(0x6A) static let currentAmbientLightLevel = CharacteristicType(0x6B) static let currentHorizontalTiltAngle = CharacteristicType(0x6C) static let currentPosition = CharacteristicType(0x6D) static let currentVerticalTiltAngle = CharacteristicType(0x6E) static let holdPosition = CharacteristicType(0x6F) static let leakDetected = CharacteristicType(0x70) static let occupancyDetected = CharacteristicType(0x71) static let positionState = CharacteristicType(0x72) static let programmableSwitchEvent = CharacteristicType(0x73) static let statusActive = CharacteristicType(0x75) static let smokeDetected = CharacteristicType(0x76) static let statusFault = CharacteristicType(0x77) static let statusJammed = CharacteristicType(0x78) static let statusLowBattery = CharacteristicType(0x79) static let statusTampered = CharacteristicType(0x7A) static let targetHorizontalTiltAngle = CharacteristicType(0x7B) static let targetPosition = CharacteristicType(0x7C) static let targetVerticalTiltAngle = CharacteristicType(0x7D) static let securitySystemAlarmType = CharacteristicType(0x8E) static let chargingState = CharacteristicType(0x8F) static let carbonMonoxideLevel = CharacteristicType(0x90) static let carbonMonoxidePeakLevel = CharacteristicType(0x91) static let carbonDixideDetected = CharacteristicType(0x92) static let carbonDixideLevel = CharacteristicType(0x93) static let carbonDixidePeakLevel = CharacteristicType(0x94) static let airQuality = CharacteristicType(0x95) static let linkQuality = CharacteristicType(0x9C) static let configureBridgedAccessoryStatus = CharacteristicType(0x9D) static let discoverBridgedAccessories = CharacteristicType(0x9E) static let discoveredBridgedAccessories = CharacteristicType(0x9F) static let configureBridgedAccessory = CharacteristicType(0xA0) static let category = CharacteristicType(0xA3) static let accessoryFlags = CharacteristicType(0xA6) static let lockPhysicalControl = CharacteristicType(0xA7) static let targetAirPurifierState = CharacteristicType(0xA8) static let currentAirPurifierState = CharacteristicType(0xA9) static let currentSlatState = CharacteristicType(0xAA) static let filterLifeLevel = CharacteristicType(0xAB) static let filterChangeIndication = CharacteristicType(0xAC) static let resetFilterIndication = CharacteristicType(0xAD) static let currentFanState = CharacteristicType(0xAF) static let active = CharacteristicType(0xB0) static let swingMode = CharacteristicType(0xB6) static let targetFanState = CharacteristicType(0xBF) static let slatType = CharacteristicType(0xC0) static let currentTiltAngle = CharacteristicType(0xC1) static let targetTiltAngle = CharacteristicType(0xC2) static let ozoneDensity = CharacteristicType(0xC3) static let nitrogenDioxideDensity = CharacteristicType(0xC4) static let sulphurDioxideDensity = CharacteristicType(0xC5) static let PM25Density = CharacteristicType(0xC6) static let PM10Density = CharacteristicType(0xC7) static let VOCDensity = CharacteristicType(0xC8) static let serviceLabelIndex = CharacteristicType(0xCB) static let serviceLabelNamespace = CharacteristicType(0xCD) static let colorTemperature = CharacteristicType(0xCE) static let supportedVideoStreamConfiguration = CharacteristicType(0x114) static let supportedAudioStreamConfiguration = CharacteristicType(0x115) static let supportedRTPConfiguration = CharacteristicType(0x116) static let selectedRTPStreamConfiguration = CharacteristicType(0x117) static let setupEndpoints = CharacteristicType(0x118) static let volume = CharacteristicType(0x119) static let mute = CharacteristicType(0x11A) static let nightVision = CharacteristicType(0x11B) static let opticalZoom = CharacteristicType(0x11C) static let digitalZoom = CharacteristicType(0x11D) static let imageRotation = CharacteristicType(0x11E) static let imageMirroring = CharacteristicType(0x11F) static let streamingStatus = CharacteristicType(0x120) } public enum CharacteristicPermission: String, Codable { // This characteristic can only be read by paired controllers. case read = "pr" // paired read // This characteristic can only be written by paired controllers. case write = "pw" // paired write // This characteristic supports events. case events = "ev" // The following properties are not implemented and included for completeness. // This characteristic supports additional authorization data case additionalAuthorization = "aa" // This characteristic supports timed write procedure case timedWrite = "tw" // This characteristic is hidden from the user case hidden = "hd" // Short-hand for "all" permissions. static let ReadWrite: [CharacteristicPermission] = [.read, .write, .events] } public enum CharacteristicFormat: String, Codable { case string case bool case float case uint8 case uint16 case uint32 case int32 case uint64 case data case tlv8 } public enum CharacteristicUnit: String, Codable { case percentage case arcdegrees case celcius case lux case seconds } enum HAPStatusCodes: Int, Codable { case success = 0 case insufficientPrivileges = -70401 case unableToCommunicate = -70402 case busy = -70403 case readOnly = -70404 case writeOnly = -70405 case notificationNotSupported = -70406 case outOfResources = -70407 case operationTimedOut = -70408 case resourceDoesNotExist = -70409 case invalidValue = -70410 case insufficientAuthorization = -70411 }
mit
c0e3fe61caa06e078232758327c8b79d
41.334728
86
0.746393
4.389588
false
false
false
false
ludoded/ReceiptBot
Pods/Material/Sources/iOS/SearchBarController.swift
2
3873
/* * Copyright (C) 2015 - 2017, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of CosmicMind nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import UIKit extension UIViewController { /** A convenience property that provides access to the SearchBarController. This is the recommended method of accessing the SearchBarController through child UIViewControllers. */ public var searchBarController: SearchBarController? { var viewController: UIViewController? = self while nil != viewController { if viewController is SearchBarController { return viewController as? SearchBarController } viewController = viewController?.parent } return nil } } open class SearchBarController: StatusBarController { /** A Display value to indicate whether or not to display the rootViewController to the full view bounds, or up to the searchBar height. */ open var searchBarDisplay = Display.partial { didSet { layoutSubviews() } } /// Reference to the SearchBar. @IBInspectable open let searchBar = SearchBar() open override func layoutSubviews() { super.layoutSubviews() let y = Application.shouldStatusBarBeHidden || statusBar.isHidden ? 0 : statusBar.height searchBar.y = y searchBar.width = view.width switch searchBarDisplay { case .partial: let h = y + searchBar.height rootViewController.view.y = h rootViewController.view.height = view.height - h case .full: rootViewController.view.frame = view.bounds } } /** Prepares the view instance when intialized. When subclassing, it is recommended to override the prepare method to initialize property values and other setup operations. The super.prepare method should always be called immediately when subclassing. */ open override func prepare() { super.prepare() prepareStatusBar() prepareSearchBar() } } extension SearchBarController { /// Prepares the statusBar. fileprivate func prepareStatusBar() { shouldHideStatusBarOnRotation = false } /// Prepares the searchBar. fileprivate func prepareSearchBar() { searchBar.depthPreset = .depth1 searchBar.zPosition = 1000 view.addSubview(searchBar) } }
lgpl-3.0
7402c87f8b322de77249e0046190227b
33.891892
96
0.710044
4.908745
false
false
false
false
sahandnayebaziz/Hypertext
Tests/HypertextTests/HypertextTests.swift
1
8215
import XCTest @testable import Hypertext //MARK: Test Tags class materialButton: tag {} class camelButton: tag { override public var name: String { return String(describing: type(of: self)) } } //MARK: Test Cases class HypertextTests: XCTestCase { func testCanRenderString() { let expected = "hello world." let actual = "hello world.".render() XCTAssertEqual(expected, actual) } func testCanRenderIntRenderable() { let expected = "<div>2</div>" let actual = div { 2 }.render() XCTAssertEqual(expected, actual) } func testCanRenderDoubleRenderable() { let expected = "<div>2.0</div>" let actual = div { 2.0 }.render() XCTAssertEqual(expected, actual) } func testCanRenderFloatRenderable() { let expected = "<div>2.0</div>" let actual = div { Float(2.0) }.render() XCTAssertEqual(expected, actual) } func testCanRenderTag() { let expected = "<title></title>" let actual = title().render() XCTAssertEqual(expected, actual) } func testCanRenderSelfClosingTag() { let expected = "<img/>" let actual = img().render() XCTAssertEqual(expected, actual) } func testCanRenderTagWithStringChild() { let expected = "<title>hello world.</title>" let actual = title { "hello world." }.render() XCTAssertEqual(expected, actual) } func testCanRenderSelfClosingTagWithoutRenderingChild() { let expected = "<img/>" let actual = img { "hello world." }.render() XCTAssertEqual(expected, actual) } func testCanRenderTagWithChildTag() { let expected = "<div><img/></div>" let actual = div { img() }.render() XCTAssertEqual(expected, actual) } func testCanRenderTagWithMultipleChildTags() { let expected = "<div><img/><img/><img/></div>" let actual = div { [img(), img(), img()] }.render() XCTAssertEqual(expected, actual) } func testCanRenderTagWithChildWithNestedChild() { let expected = "<div><div><img/></div></div>" let actual = div { div { img() } }.render() XCTAssertEqual(expected, actual) } func testCanRenderTagWithChildWithNestedChildAbusingRender() { let expected = "<div><div><img/></div></div>" let actual = div { div { img().render() }.render() }.render() XCTAssertEqual(expected, actual) } func testCanRenderTagWithManyNestedChildren() { let expected = "<div><div><div><div><div><div><div><div></div></div></div></div></div></div></div></div>" let actual = div { div { div { div { div { div { div { div() } } } } } } }.render() XCTAssertEqual(expected, actual) } func testCanRenderAttributeOnTag() { let expected = "<link href=\"./style.css\"/>" let actual = link(["href":"./style.css"]).render() XCTAssertEqual(expected, actual) } func testCanRenderAttributeOnNestedTag() { let expected = "<head><link href=\"./style.css\"/></head>" let actual = head { link(["href":"./style.css"]) }.render() XCTAssertEqual(expected, actual) } func testCanRenderTagWithAttributesAndChildren() { let expected = "<div class=\"container\"><p>Well hello there...</p></div>" let actual = div(["class":"container"]) { p { "Well hello there..." } }.render() XCTAssertEqual(expected, actual) } func testCanRenderTagsWithFormatting() { let expected = "<head>\n <title>\n hello world.\n </title>\n</head>" let actual = head { title { "hello world." } }.render(startingWithSpaces: 0, indentingWithSpaces: 2) XCTAssertEqual(expected, actual) let expectedFourSpaces = "<head>\n <title>\n hello world.\n </title>\n</head>" let actualFourSpaces = head { title { "hello world." } }.render(startingWithSpaces: 0, indentingWithSpaces: 4) XCTAssertEqual(expectedFourSpaces, actualFourSpaces) } func testCanRenderTagsWithFormattingWithMultipleSiblings() { let expected = "<div>\n <img/>\n <img/>\n <img/>\n <h1></h1>\n</div>" let actual = div { [ img(), img(), img(), h1() ] }.render(startingWithSpaces: 0, indentingWithSpaces: 2) XCTAssertEqual(expected, actual) } func testCanCreateCustomTagWithOverridenName() { let expected = "<mycustomtagname></mycustomtagname>" class mycustomtag : tag { override public var name: String { return "mycustomtagname" } } let actual = mycustomtag().render() XCTAssertEqual(expected, actual) } func testCanDescribeTagAsCustomStringConvertible() { let expected = "<div>hello world.</div>" let actual = "\(div { "hello world." })" XCTAssertEqual(expected, actual) } func testCanRenderDoctype() { let expected = "<!DOCTYPE html>" let actual = doctype(.html5).render() XCTAssertEqual(expected, actual) let expectedHtml4 = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">" let actualHtml4 = doctype(.html4Strict).render() XCTAssertEqual(expectedHtml4, actualHtml4) } func testSnakeDelimiter() { let expected = "material_button" let actual = TagFormatter.snaked("materialButton") XCTAssertEqual(expected, actual) let expectedNoOp = "materialbutton" let actualNoOp = TagFormatter.snaked("materialbutton") XCTAssertEqual(expectedNoOp, actualNoOp) } func testDashDelimiter() { let expected = "material-button" let actual = TagFormatter.dashed("materialButton") XCTAssertEqual(expected, actual) let expectedNoOp = "materialbutton" let actualNoOp = TagFormatter.dashed("materialbutton") XCTAssertEqual(expectedNoOp, actualNoOp) } func testDefaultTagFormatIsDashed() { let expected = "<material-button></material-button>" let actual = materialButton().render() XCTAssertEqual(expected, actual) } func testCanOverrideDefaultTagFormat() { let expected = "<camelButton></camelButton>" let actual = camelButton().render() XCTAssertEqual(expected, actual) } static var allTests : [(String, (HypertextTests) -> () throws -> Void)] { return [ ("testCanRenderString", testCanRenderString), ("testCanRenderIntRenderable", testCanRenderIntRenderable), ("testCanRenderDoubleRenderable", testCanRenderDoubleRenderable), ("testCanRenderFloatRenderable", testCanRenderFloatRenderable), ("testCanRenderTag", testCanRenderTag), ("testCanRenderSelfClosingTag", testCanRenderSelfClosingTag), ("testCanRenderTagWithStringChild", testCanRenderTagWithStringChild), ("testCanRenderSelfClosingTagWithoutRenderingChild", testCanRenderSelfClosingTagWithoutRenderingChild), ("testCanRenderTagWithChildTag", testCanRenderTagWithChildTag), ("testCanRenderTagWithMultipleChildTags", testCanRenderTagWithMultipleChildTags), ("testCanRenderTagWithChildWithNestedChild", testCanRenderTagWithChildWithNestedChild), ("testCanRenderTagWithChildWithNestedChildAbusingRender", testCanRenderTagWithChildWithNestedChildAbusingRender), ("testCanRenderTagWithManyNestedChildren", testCanRenderTagWithManyNestedChildren), ("testCanRenderAttributeOnTag", testCanRenderAttributeOnTag), ("testCanRenderAttributeOnNestedTag", testCanRenderAttributeOnNestedTag), ("testCanRenderTagsWithFormatting", testCanRenderTagsWithFormatting), ("testCanRenderTagsWithFormattingWithMultipleSiblings", testCanRenderTagsWithFormattingWithMultipleSiblings), ("testCanCreateCustomTagWithOverridenName", testCanCreateCustomTagWithOverridenName), ("testCanRenderTagWithAttributesAndChildren", testCanRenderTagWithAttributesAndChildren), ("testCanDescribeTagAsCustomStringConvertible", testCanDescribeTagAsCustomStringConvertible), ("testCanRenderDoctype", testCanRenderDoctype), ("testSnakeDelimiter", testSnakeDelimiter), ("testDashDelimiter", testDashDelimiter), ("testDefaultTagFormatIsDashed", testDefaultTagFormatIsDashed), ("testCanOverrideDefaultTagFormat", testCanOverrideDefaultTagFormat) ] } }
mit
f5335209175466983da78235619aa2e6
32.946281
122
0.678393
4.292059
false
true
false
false
tktsubota/CareKit
Sample/OCKSample/QueryActivityEventsOperation.swift
1
5032
/* Copyright (c) 2016, Apple Inc. 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 CareKit class QueryActivityEventsOperation: Operation { // MARK: Properties fileprivate let store: OCKCarePlanStore fileprivate let activityIdentifier: String fileprivate let startDate: DateComponents fileprivate let endDate: DateComponents fileprivate(set) var dailyEvents: DailyEvents? // MARK: Initialization init(store: OCKCarePlanStore, activityIdentifier: String, startDate: DateComponents, endDate: DateComponents) { self.store = store self.activityIdentifier = activityIdentifier self.startDate = startDate self.endDate = endDate } // MARK: NSOperation override func main() { // Do nothing if the operation has been cancelled. guard !isCancelled else { return } // Find the activity with the specified identifier in the store. guard let activity = findActivity() else { return } /* Create a semaphore to wait for the asynchronous call to `enumerateEventsOfActivity` to complete. */ let semaphore = DispatchSemaphore(value: 0) // Query for events for the activity between the requested dates. self.dailyEvents = DailyEvents() store.enumerateEvents(of: activity, startDate: startDate as DateComponents, endDate: endDate as DateComponents, handler: { event, _ in if let event = event { self.dailyEvents?[event.date].append(event) } }, completion: { _, _ in // Use the semaphore to signal that the query is complete. semaphore.signal() }) // Wait for the semaphore to be signalled. _ = semaphore.wait(timeout: DispatchTime.distantFuture) } // MARK: Convenience fileprivate func findActivity() -> OCKCarePlanActivity? { /* Create a semaphore to wait for the asynchronous call to `activityForIdentifier` to complete. */ let semaphore = DispatchSemaphore(value: 0) var activity: OCKCarePlanActivity? store.activity(forIdentifier: activityIdentifier) { success, foundActivity, error in activity = foundActivity if !success { print(error?.localizedDescription as Any) } // Use the semaphore to signal that the query is complete. semaphore.signal() } // Wait for the semaphore to be signalled. _ = semaphore.wait(timeout: DispatchTime.distantFuture) return activity } } struct DailyEvents { // MARK: Properties fileprivate var mappedEvents: [DateComponents: [OCKCarePlanEvent]] var allEvents: [OCKCarePlanEvent] { return Array(mappedEvents.values.joined()) } var allDays: [DateComponents] { return Array(mappedEvents.keys) } subscript(day: DateComponents) -> [OCKCarePlanEvent] { get { if let events = mappedEvents[day] { return events } else { return [] } } set(newValue) { mappedEvents[day] = newValue } } // MARK: Initialization init() { mappedEvents = [:] } }
bsd-3-clause
5e681b9f2b866e2a4d802a08bcdbf3e2
32.771812
142
0.655604
5.25261
false
false
false
false
seyton/2048
NumberTiles/NumberTileGameViewController.swift
1
7229
// // NumberTileGameViewController.swift // NumberTiles // // Created by Wesley Matlock on 11/24/15. // Copyright © 2015 insoc.net. All rights reserved. // import UIKit class NumberTileGameViewController: UIViewController { var dimension: Int var threshold: Int var board: GameBoardView? var gameModel: GameModel? var scoreView: ScoreViewDelegate? let boardWidth = CGFloat(230) let narrowPadding = CGFloat(3) let thickPadding = CGFloat(6) let viewPadding = CGFloat(10) let verticalViewOffset = CGFloat(0) init(dimension d: Int, threshold t: Int) { dimension = d > 2 ? d : 2 threshold = t > 8 ? t : 8 super.init(nibName: nil, bundle: nil) gameModel = GameModel(dimension: dimension, threshold: threshold, delegate: self) view.backgroundColor = UIColor.whiteColor() setupSwipeControls() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() setupGame() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func setupSwipeControls() { let swipeUp = UISwipeGestureRecognizer(target: self, action: Selector("swipeUp:")) swipeUp.numberOfTouchesRequired = 1 swipeUp.direction = .Up view.addGestureRecognizer(swipeUp) let swipeDown = UISwipeGestureRecognizer(target: self, action: Selector("swipeDown:")) swipeDown.numberOfTouchesRequired = 1 swipeDown.direction = .Down view.addGestureRecognizer(swipeDown) let swipeLeft = UISwipeGestureRecognizer(target: self, action: Selector("swipeLeft:")) swipeLeft.numberOfTouchesRequired = 1 swipeLeft.direction = .Left view.addGestureRecognizer(swipeLeft) let swipeRight = UISwipeGestureRecognizer(target: self, action: Selector("swipeRight:")) swipeRight.numberOfTouchesRequired = 1 swipeRight.direction = .Right view.addGestureRecognizer(swipeRight) } func setupGame() { let scoreView = ScoreView(background: .blackColor(), textColor: .whiteColor(), font: UIFont.systemFontOfSize(16.0), radius: 6) scoreView.score = 0 let padding: CGFloat = dimension > 5 ? narrowPadding : thickPadding let v1 = boardWidth - padding*(CGFloat(dimension + 1)) let width: CGFloat = CGFloat(floorf(CFloat(v1)))/CGFloat(dimension) let gameboard = GameBoardView(dimension: dimension, tileWidth: width, tilePadding: padding, cornerRadius: 6, backgroundColor: .blackColor(), foregroundColor: .darkGrayColor()) let views = [scoreView, gameboard] var scoreViewFrame = scoreView.frame scoreViewFrame.origin.x = xPositionToCenterView(scoreView) scoreViewFrame.origin.y = yPositionForViewAtPosition(0, views: views) scoreView.frame = scoreViewFrame var gameViewFrame = gameboard.frame gameViewFrame.origin.x = xPositionToCenterView(gameboard) gameViewFrame.origin.y = yPositionForViewAtPosition(1, views: views) gameboard.frame = gameViewFrame // Add to game state view.addSubview(gameboard) board = gameboard view.addSubview(scoreView) self.scoreView = scoreView assert(gameModel != nil) gameModel!.insertRandomTileLocation(2) gameModel!.insertRandomTileLocation(2) } } //MARK: - Utility Methods extension NumberTileGameViewController { func xPositionToCenterView(aView: UIView) -> CGFloat { let width = aView.bounds.size.width let posX = 0.5 * ( view.bounds.size.width - width) return posX >= 0 ? posX : 0 } func yPositionForViewAtPosition(order: Int, views: [UIView]) -> CGFloat { assert(views.count > 0) assert(order >= 0 && order < views.count) let totalHeight = CGFloat(views.count - 1)*viewPadding + views.map({ $0.bounds.size.height }).reduce(verticalViewOffset, combine: { $0 + $1 }) let viewsTop = 0.5 * (view.bounds.size.height - totalHeight) >= 0 ? 0.5 * (view.bounds.size.height - totalHeight) : 0 var newHeight = CGFloat(0) for i in 0..<order { newHeight += viewPadding + views[i].bounds.size.height } return viewsTop + newHeight } func gameCheck() { assert(gameModel != nil) let (win, _) = gameModel!.gameWon() if win { //TODO: Replace and add restart let alertView = UIAlertView() alertView.title = "Champion" alertView.message = "Winner! Winner! Chicken Dinner!" alertView.addButtonWithTitle("Cancel") alertView.show() return } let randomVal = Int(arc4random_uniform(10)) gameModel?.insertRandomTileLocation(randomVal == 1 ? 4 : 2) if gameModel!.gameOver() { //TODO: need to delegate the lose and update let alertView = UIAlertView() alertView.title = "LOSER!!" alertView.message = "Ouch that didn't work out well." alertView.addButtonWithTitle("Cancel") alertView.show() } } } //MARK: - Gesture Controls extension NumberTileGameViewController { func swipeUp(recognizer: UIGestureRecognizer) { assert(gameModel != nil) gameModel!.queueMove(.Up) { (changed: Bool) -> () in if changed { self.gameCheck() } } } func swipeDown(recognizer: UIGestureRecognizer) { assert(gameModel != nil) gameModel!.queueMove(.Down) { (changed: Bool) -> () in if changed { self.gameCheck() } } } func swipeLeft(recognizer: UIGestureRecognizer) { assert(gameModel != nil) gameModel!.queueMove(.Left) { (changed: Bool) -> () in if changed { self.gameCheck() } } } func swipeRight(recognizer: UIGestureRecognizer) { assert(gameModel != nil) gameModel!.queueMove(.Right) { (changed: Bool) -> () in if changed { self.gameCheck() } } } } extension NumberTileGameViewController: GameModelDelegate { func scoreChanged(score: Int) { scoreView?.scoreChanged(score) } func moveOneTile(from: (Int, Int), to:(Int, Int), value: Int) { board?.moveOneTile(from, to: to, value: value) } func moreTwoTiles(from: ((Int, Int), (Int, Int)), to:(Int, Int), value: Int) { board?.moveTwoTiles(from, to: to, value: value) } func insertTile(location: (Int, Int), value: Int) { board?.insertTile(location, value: value) } }
mit
71675b5d737b80f18846eaef5fb5e4ee
30.567686
183
0.594632
4.802658
false
false
false
false
capnslipp/SwiftBitmask
Source/OptionSetView.swift
1
1615
// // OptionSetView.swift // SwiftBitmask // // Created by bryn austin bellomy on 2015 Feb 1. // Copyright (c) 2015 bryn austin bellomy. All rights reserved. // import Foundation /// /// Curried version of the `OptionSetView` constructor. /// /// For example: `bitmask |> asOptionSet([.First, .Second, .Third])` /// public func asOptionSet <T: IBitmaskRepresentable> (_ possibleOptions:Set<T>, _ bitmask:Bitmask<T>) -> OptionSetView<T> where T: Hashable { return OptionSetView(bitmask:bitmask, possibleOptions:possibleOptions) } /** A representation of a finite set of options (or flags), some of which are set (flagged). A `Bitmask<T>` can be converted to an `OptionSetView<T>`. */ public struct OptionSetView <T: IBitmaskRepresentable> where T: Hashable { let bitmask: Bitmask<T> let possibleOptions: Set<T> let options: Set<T> public init(bitmask b: Bitmask<T>, possibleOptions po:Set<T>) { bitmask = b possibleOptions = po options = Set(possibleOptions.filter { b.isSet($0) }) } public func isSet(_ option:T) -> Bool { return (bitmask & option).bitmaskValue == option.bitmaskValue } public func areSet(_ options:T...) -> Bool { let otherBitmask = Bitmask(options) return (bitmask & otherBitmask).bitmaskValue == otherBitmask.bitmaskValue } } // // MARK: - OptionSetView: SequenceType // extension OptionSetView: Sequence { public func makeIterator() -> AnyIterator<T> { var generator = options.makeIterator() return AnyIterator { generator.next() } } }
mit
12e59d68ef6015f31284efeff106a268
25.048387
92
0.659443
3.773364
false
false
false
false
leo150/Pelican
Sources/Pelican/API/Types/Message/Message.swift
1
8714
// // Message.swift // Pelican // // Created by Takanu Kyriako on 31/08/2017. // import Foundation import Vapor import FluentProvider /** Defines a message type, and in most cases also contains the contents of that message. */ public enum MessageType { case audio(Audio) case contact(Contact) case document(Document) case game(Game) case photo([Photo]) case location(Location) case sticker(Sticker) case venue(Venue) case video(Video) case voice(Voice) case text /// Returns the name of the type as a string. func name() -> String { switch self { case .audio(_): return "audio" case .contact(_): return "contact" case .document(_): return "document" case .game(_): return "game" case .photo(_): return "photo" case .location(_): return "location" case .sticker(_): return "sticker" case .venue(_): return "venue" case .video(_): return "video" case .voice(_): return "voice" case .text: return "text" } } } /** I'll deal with this once I find a foolproof way to group this stuff... */ /* public enum MessageStatus { } */ public enum MessageParseMode: String { case html = "HTML" case markdown = "Markdown" case none = "" } final public class Message: TelegramType, UpdateModel { public var storage = Storage() // Unique message identifier for the database public var tgID: Int // Unique identifier for the Telegram message. public var from: User? // Sender, can be empty for messages sent to channels public var date: Int // Date the message was sent, in UNIX time. public var chat: Chat // Conversation the message belongs to. // Message Metadata public var forwardFrom: User? // The sender of the original message, if forwarded public var forwardFromChat: Chat? // For messages forwarded from a channel, info about the original channel. public var forwardedFromMessageID: Int? // For forwarded channel posts, identifier of the original message. public var forwardDate: Int? // For forwarded messages, date of the original message sent in UNIX time. public var replyToMessage: Message? // For replies, the original message. Note that this object will not contain further fields of this type. public var editDate: Int? // Date the message was last edited in UNIX time. // Message Body public var type: MessageType // The type of the message, can be anything that matches the protocol public var text: String? public var entities: [MessageEntity]? // For text messages, special entities like usernames that appear in the text. public var caption: String? // Caption for the document, photo or video, 0-200 characters. // Status Message Info // This should be condensed into a single entity using an enumerator, as a status message can only represent one of these things, right? public var newChatMembers: [User]? // A status message specifying information about new users added to the group. public var leftChatMember: User? // A status message specifying information about a user who left the group. public var newChatTitle: String? // A status message specifying the new title for the chat. public var newChatPhoto: [Photo]? // A status message showing the new chat public photo. public var deleteChatPhoto: Bool = false // Service Message: the chat photo was deleted. public var groupChatCreated: Bool = false // Service Message: the group has been created. public var supergroupChatCreated: Bool = false // I dont get this field... public var channelChatCreated: Bool = false // I DONT GET THIS EITHER public var migrateToChatID: Int? // The group has been migrated to a supergroup with the specified identifier. This can be greater than 32-bits so you have been warned... public var migrateFromChatID: Int? // The supergroup has been migrated from a group with the specified identifier. public var pinnedMessage: Message? // Specified message was pinned? public init(id: Int, date: Int, chat:Chat) { self.tgID = id self.date = date self.chat = chat self.type = .text } // NodeRepresentable conforming methods public required init(row: Row) throws { self.tgID = try row.get("message_id") // Used to extract the type in a way thats consistent with the context given. if let subFrom = row["from"] { self.from = try .init(row: Row(subFrom)) as User } self.date = try row.get("date") guard let subChat = row["chat"] else { throw TypeError.ExtractFailed } self.chat = try .init(row: Row(subChat)) as Chat // Forward if let subForwardFrom = row["forward_from"] { self.forwardFrom = try .init(row: Row(subForwardFrom)) as User } if let subForwardFromChat = row["forward_from_chat"] { self.forwardFromChat = try .init(row: Row(subForwardFromChat)) as Chat } self.forwardedFromMessageID = try row.get("forward_from_message_id") self.forwardDate = try row.get("forward_date") // Reply/Edit if let subReplyToMessage = row["reply_to_message"] { self.replyToMessage = try .init(row: Row(subReplyToMessage)) as Message } self.editDate = try row.get("edit_date") // Body if let type = row["audio"] { self.type = .audio(try .init(row: Row(type)) as Audio) } else if let type = row["contact"] { self.type = .contact(try .init(row: Row(type)) as Contact) } else if let type = row["document"] { self.type = .document(try .init(row: Row(type)) as Document) } else if let type = row["game"] { self.type = .game(try .init(row: Row(type)) as Game) } else if let type = row["photo"] { self.type = .photo(try type.array?.map( { try Photo(row: $0) } ) ?? []) //self.type = .photo(try .init(row: Row(type)) as Photo) } } else if let type = row["location"] { self.type = .location(try .init(row: Row(type)) as Location) } else if let type = row["sticker"] { self.type = .sticker(try .init(row: Row(type)) as Sticker) } else if let type = row["venue"] { self.type = .venue(try .init(row: Row(type)) as Venue) } else if let type = row["video"] { self.type = .video(try .init(row: Row(type)) as Video) } else if let type = row["voice"] { self.type = .voice(try .init(row: Row(type)) as Voice) } else { self.type = .text } self.text = try row.get("text") if let subEntities = row["entities"] { self.entities = try subEntities.array?.map( { try MessageEntity(row: $0) } ) } self.caption = try row.get("caption") // Status Messages if let subNewChatMembers = row["new_chat_member"] { self.newChatMembers = try subNewChatMembers.array?.map( { try User(row: $0) } ) } if let subLeftChatMember = row["left_chat_member"] { self.leftChatMember = try .init(row: Row(subLeftChatMember)) as User } self.newChatTitle = try row.get("new_chat_title") if let photoRow = row["new_chat_photo"] { self.newChatPhoto = try photoRow.array?.map( { try Photo(row: $0) } ) } self.deleteChatPhoto = try row.get("delete_chat_photo") ?? false self.groupChatCreated = try row.get("group_chat_created") ?? false self.supergroupChatCreated = try row.get("supergroup_chat_created") ?? false self.channelChatCreated = try row.get("channel_chat_created") ?? false self.migrateToChatID = try row.get("migrate_to_chat_id") self.migrateFromChatID = try row.get("migrate_from_chat_id") if let subPinnedMessage = row["pinned_message"] { self.pinnedMessage = try .init(row: Row(subPinnedMessage)) as Message } } public func makeRow() throws -> Row { var row = Row() try row.set("message_id", tgID) try row.set("from", from) try row.set("date", date) try row.set("chat", chat) try row.set("forward_from", forwardFrom) try row.set("forward_from_chat", forwardFromChat) try row.set("forward_from_message_id", forwardedFromMessageID) try row.set("forward_date", forwardDate) try row.set("reply_to_message", forwardFrom) try row.set("edit_date", forwardFromChat) try row.set("text", text) try row.set("entities", entities) try row.set("caption", caption) try row.set("new_chat_member", newChatMembers) try row.set("left_chat_member", leftChatMember) try row.set("new_chat_title", newChatTitle) try row.set("new_chat_photo", newChatPhoto) try row.set("delete_chat_photo", deleteChatPhoto) try row.set("group_chat_created", groupChatCreated) try row.set("supergroup_chat_created", supergroupChatCreated) try row.set("channel_chat_created", channelChatCreated) try row.set("migrate_to_chat_id", migrateToChatID) try row.set("migrate_from_chat_id", migrateFromChatID) try row.set("pinned_message", pinnedMessage) return row } }
mit
43bc0a8ec28b55f1be3771759405e7f2
34.279352
186
0.686252
3.418596
false
false
false
false
ello/ello-ios
Sources/Controllers/App/AppViewController.swift
1
37641
//// /// AppViewController.swift // import SwiftyUserDefaults import PromiseKit import AudioToolbox struct HapticFeedbackNotifications { static let successfulUserEvent = TypedNotification<(Void)>( name: "co.ello.HapticFeedbackNotifications.successfulUserEvent" ) } struct StatusBarNotifications { static let statusBarVisibility = TypedNotification<(Bool)>( name: "co.ello.StatusBarNotifications.statusBarVisibility" ) static let alertStatusBarVisibility = TypedNotification<(Bool)>( name: "co.ello.StatusBarNotifications.alertStatusBarVisibility" ) } enum LoggedOutAction { case relationshipChange case postTool case artistInviteSubmit } struct LoggedOutNotifications { static let userActionAttempted = TypedNotification<LoggedOutAction>( name: "co.ello.LoggedOutNotifications.userActionAttempted" ) } @objc protocol HasAppController { var appViewController: AppViewController? { get } } class AppViewController: BaseElloViewController { override func trackerName() -> String? { return nil } private var _mockScreen: AppScreenProtocol? var screen: AppScreenProtocol { set(screen) { _mockScreen = screen } get { return fetchScreen(_mockScreen) } } var visibleViewController: UIViewController? var statusBarShouldBeVisible: Bool { return alertStatusBarIsVisible ?? statusBarIsVisible } override var preferredStatusBarStyle: UIStatusBarStyle { return visibleViewController?.preferredStatusBarStyle ?? .lightContent } private var statusBarIsVisible = true { didSet { if oldValue != statusBarIsVisible { updateStatusBar() } } } private var alertStatusBarIsVisible: Bool? { didSet { if oldValue != alertStatusBarIsVisible { updateStatusBar() } } } private var statusBarVisibilityObserver: NotificationObserver? private var alertStatusBarVisibilityObserver: NotificationObserver? private var userLoggedOutObserver: NotificationObserver? private var successfulUserEventObserver: NotificationObserver? private var receivedPushNotificationObserver: NotificationObserver? private var externalWebObserver: NotificationObserver? private var internalWebObserver: NotificationObserver? private var apiOutOfDateObserver: NotificationObserver? private var pushPayload: PushPayload? private var deepLinkPath: String? private var didJoinHandler: Block? override func loadView() { self.view = AppScreen() } override func viewDidLoad() { super.viewDidLoad() setupNotificationObservers() } deinit { removeNotificationObservers() } var isStartup = true override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if isStartup { isStartup = false checkIfLoggedIn() } } override func viewWillTransition( to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator ) { super.viewWillTransition(to: size, with: coordinator) postNotification(Application.Notifications.WindowSizeWillChange, value: size) } override func didSetCurrentUser() { super.didSetCurrentUser() ElloWebBrowserViewController.currentUser = currentUser if let vc = visibleViewController as? ControllerThatMightHaveTheCurrentUser { vc.currentUser = currentUser } } private func updateStatusBar() { animate { self.setNeedsStatusBarAppearanceUpdate() } } private func checkIfLoggedIn() { let authToken = AuthToken() if authToken.isPasswordBased { loadCurrentUser(animateLogo: true) } else { showStartupScreen() } } @discardableResult func loadCurrentUser(animateLogo: Bool = false) -> Promise<User> { if animateLogo { screen.animateLogo() } return ProfileService().loadCurrentUser() .map { user -> User in self.logInNewUser() JWT.refresh() self.screen.stopAnimatingLogo() self.currentUser = user let shouldShowOnboarding = Onboarding.shared.shouldShowOnboarding(user) let shouldShowCreatorType = Onboarding.shared.shouldShowCreatorType(user) if shouldShowOnboarding || shouldShowCreatorType { self.showOnboardingScreen(user) } else { self.showMainScreen(user) } return user } .recover { error -> Promise<User> in if animateLogo { self.showStartupScreen() self.screen.stopAnimatingLogo() } throw error } } private func setupNotificationObservers() { statusBarVisibilityObserver = NotificationObserver( notification: StatusBarNotifications.statusBarVisibility ) { [weak self] visible in self?.statusBarIsVisible = visible } alertStatusBarVisibilityObserver = NotificationObserver( notification: StatusBarNotifications.alertStatusBarVisibility ) { [weak self] visible in if !visible { self?.alertStatusBarIsVisible = false } else { self?.alertStatusBarIsVisible = nil } } userLoggedOutObserver = NotificationObserver( notification: AuthenticationNotifications.userLoggedOut ) { [weak self] in self?.userLoggedOut() } successfulUserEventObserver = NotificationObserver( notification: HapticFeedbackNotifications.successfulUserEvent ) { _ in AudioServicesPlaySystemSound(1520) } receivedPushNotificationObserver = NotificationObserver( notification: PushNotificationNotifications.interactedWithPushNotification ) { [weak self] payload in self?.receivedPushNotification(payload) } externalWebObserver = NotificationObserver(notification: ExternalWebNotification) { [weak self] url in self?.showExternalWebView(url) } internalWebObserver = NotificationObserver(notification: InternalWebNotification) { [weak self] url in self?.navigateToDeepLink(url) } apiOutOfDateObserver = NotificationObserver( notification: AuthenticationNotifications.outOfDateAPI ) { [weak self] _ in guard let `self` = self else { return } let message = InterfaceString.App.OldVersion let alertController = AlertViewController(confirmation: message) self.present(alertController, animated: true, completion: nil) self.apiOutOfDateObserver?.removeObserver() self.userLoggedOut() } } private func removeNotificationObservers() { statusBarVisibilityObserver?.removeObserver() alertStatusBarVisibilityObserver?.removeObserver() userLoggedOutObserver?.removeObserver() successfulUserEventObserver?.removeObserver() receivedPushNotificationObserver?.removeObserver() externalWebObserver?.removeObserver() internalWebObserver?.removeObserver() apiOutOfDateObserver?.removeObserver() } } // MARK: Screens extension AppViewController { private func showStartupScreen(_ completion: @escaping Block = {}) { let initialController = HomeViewController(usage: .loggedOut) let childNavController = ElloNavigationController(rootViewController: initialController) let loggedOutController = LoggedOutViewController() childNavController.willMove(toParent: self) loggedOutController.addChild(childNavController) childNavController.didMove(toParent: loggedOutController) let parentNavController = ElloNavigationController(rootViewController: loggedOutController) swapViewController(parentNavController).done { guard let deepLinkPath = self.deepLinkPath else { return } self.navigateToDeepLink(deepLinkPath) self.deepLinkPath = nil } } func showJoinScreen(invitationCode: String? = nil) { pushPayload = nil let joinController = JoinViewController() joinController.invitationCode = invitationCode showLoggedOutControllers(joinController) } func showJoinScreen(artistInvite: ArtistInvite) { pushPayload = nil didJoinHandler = { guard let navigationController = self.pushDeepNavigationController() else { return } Tracker.shared.artistInviteOpened(slug: artistInvite.slug) let vc = ArtistInviteDetailController(artistInvite: artistInvite) vc.currentUser = self.currentUser vc.submitOnLoad = true ArtistInviteDetailController.open(vc, in: navigationController) } let joinController = JoinViewController( prompt: InterfaceString.ArtistInvites.SubmissionJoinPrompt ) showLoggedOutControllers(joinController) } func cancelledJoin() { deepLinkPath = nil didJoinHandler = nil } func showLoginScreen() { pushPayload = nil let loginController = LoginViewController() showLoggedOutControllers(loginController) } func showForgotPasswordResetScreen(authToken: String) { pushPayload = nil let forgotPasswordResetController = ForgotPasswordResetViewController(authToken: authToken) showLoggedOutControllers(forgotPasswordResetController) } func showForgotPasswordEmailScreen() { pushPayload = nil let loginController = LoginViewController() let forgotPasswordEmailController = ForgotPasswordEmailViewController() showLoggedOutControllers(loginController, forgotPasswordEmailController) } private func showLoggedOutControllers(_ loggedOutControllers: BaseElloViewController...) { guard let nav = visibleViewController as? UINavigationController, let loggedOutController = nav.children.first as? LoggedOutViewController else { return } if !(nav.visibleViewController is LoggedOutViewController) { _ = nav.popToRootViewController(animated: false) } if let loggedOutNav = loggedOutController.navigationController, let bottomBarController = loggedOutNav.children.first as? BottomBarController, let navigationBarsVisible = bottomBarController.navigationBarsVisible { for loggedOutController in loggedOutControllers { if navigationBarsVisible { loggedOutController.showNavBars(animated: true) } else { loggedOutController.hideNavBars(animated: true) } } } let allControllers = [loggedOutController] + loggedOutControllers nav.setViewControllers(allControllers, animated: true) } func showOnboardingScreen(_ user: User) { currentUser = user let vc = OnboardingViewController() vc.currentUser = user swapViewController(vc) } func doneOnboarding() { Onboarding.shared.updateVersionToLatest() self.showMainScreen(currentUser!).done { guard let didJoinHandler = self.didJoinHandler else { return } didJoinHandler() } } @discardableResult func showMainScreen(_ user: User) -> Guarantee<Void> { Tracker.shared.identify(user: user) let vc = ElloTabBarController() ElloWebBrowserViewController.elloTabBarController = vc vc.currentUser = user return swapViewController(vc).done { if let payload = self.pushPayload { self.navigateToDeepLink(payload.applicationTarget) self.pushPayload = nil } if let deepLinkPath = self.deepLinkPath { self.navigateToDeepLink(deepLinkPath) self.deepLinkPath = nil } vc.activateTabBar() PushNotificationController.shared.requestPushAccessIfNeeded(vc) } } } extension AppViewController { func showExternalWebView(_ url: String) { if let externalURL = URL(string: url), ElloWebViewHelper.bypassInAppBrowser(externalURL) { UIApplication.shared.open(externalURL, options: [:], completionHandler: nil) } else { let externalWebController = ElloWebBrowserViewController.navigationControllerWithWebBrowser() present(externalWebController, animated: true, completion: nil) if let externalWebView = externalWebController.rootWebBrowser() { externalWebView.tintColor = UIColor.greyA externalWebView.loadURLString(url) } } Tracker.shared.webViewAppeared(url) } override func present( _ viewControllerToPresent: UIViewController, animated flag: Bool, completion: Block? ) { // Unsure why WKWebView calls this controller - instead of it's own parent controller if let vc = presentedViewController { vc.present(viewControllerToPresent, animated: flag, completion: completion) } else { super.present(viewControllerToPresent, animated: flag, completion: completion) } } } // MARK: Screen transitions extension AppViewController { @discardableResult func swapViewController(_ newViewController: UIViewController) -> Guarantee<Void> { let (promise, fulfill) = Guarantee<Void>.pending() newViewController.view.alpha = 0 visibleViewController?.willMove(toParent: nil) newViewController.willMove(toParent: self) prepareToShowViewController(newViewController) if let tabBarController = visibleViewController as? ElloTabBarController { tabBarController.deactivateTabBar() } animate { self.visibleViewController?.view.alpha = 0 newViewController.view.alpha = 1 self.screen.hide() }.done { self.visibleViewController?.view.removeFromSuperview() self.visibleViewController?.removeFromParent() self.addChild(newViewController) self.visibleViewController?.didMove(toParent: nil) newViewController.didMove(toParent: self) self.visibleViewController = newViewController fulfill(Void()) } return promise } func removeViewController(_ completion: @escaping Block = {}) { if presentingViewController != nil { dismiss(animated: false, completion: nil) } statusBarIsVisible = true if let visibleViewController = visibleViewController { visibleViewController.willMove(toParent: nil) if let tabBarController = visibleViewController as? ElloTabBarController { tabBarController.deactivateTabBar() } UIView.animate( withDuration: 0.2, animations: { visibleViewController.view.alpha = 0 }, completion: { _ in self.showStartupScreen() visibleViewController.view.removeFromSuperview() visibleViewController.removeFromParent() self.visibleViewController = nil completion() } ) } else { showStartupScreen() completion() } } private func prepareToShowViewController(_ newViewController: UIViewController) { newViewController.view.frame = self.view.bounds newViewController.view.autoresizingMask = [.flexibleHeight, .flexibleWidth] newViewController.view.layoutIfNeeded() view.addSubview(newViewController.view) } } // MARK: Logout events extension AppViewController { func userLoggedOut() { logOutCurrentUser() if isLoggedIn() { removeViewController() } } func forceLogOut() { logOutCurrentUser() if isLoggedIn() { removeViewController { let message = InterfaceString.App.LoggedOut let alertController = AlertViewController(confirmation: message) self.present(alertController, animated: true, completion: nil) } } } func isLoggedIn() -> Bool { if let visibleViewController = visibleViewController, visibleViewController is ElloTabBarController { return true } return false } private func logInNewUser() { URLCache.shared.removeAllCachedResponses() TemporaryCache.clear() } private func logOutCurrentUser() { PushNotificationController.shared.deregisterStoredToken() AuthenticationManager.shared.logout() GroupDefaults.resetOnLogout() UIApplication.shared.applicationIconBadgeNumber = 0 URLCache.shared.removeAllCachedResponses() TemporaryCache.clear() ElloLinkedStore.clearDB() var cache = InviteCache() cache.clear() Tracker.shared.identify(user: nil) currentUser = nil } } extension AppViewController: InviteResponder { func onInviteFriends() { guard currentUser != nil else { postNotification(LoggedOutNotifications.userActionAttempted, value: .postTool) return } Tracker.shared.inviteFriendsTapped() AddressBookController.promptForAddressBookAccess( fromController: self, completion: { result in nextTick { switch result { case let .success(addressBook): Tracker.shared.contactAccessPreferenceChanged(true) let vc = OnboardingInviteViewController(addressBook: addressBook) vc.currentUser = self.currentUser if let navigationController = self.navigationController { navigationController.pushViewController(vc, animated: true) } else { self.present(vc, animated: true, completion: nil) } case let .failure(addressBookError): guard addressBookError != .cancelled else { return } Tracker.shared.contactAccessPreferenceChanged(false) let message = addressBookError.rawValue let alertController = AlertViewController( confirmation: InterfaceString.Friends.ImportError(message) ) self.present(alertController, animated: true, completion: nil) } } } ) } func sendInvite(person: LocalPerson, isOnboarding: Bool, completion: @escaping Block) { guard let email = person.emails.first else { return } if isOnboarding { Tracker.shared.onboardingFriendInvited() } else { Tracker.shared.friendInvited() } ElloHUD.showLoadingHudInView(view) InviteService().invite(email) .ensure { [weak self] in guard let `self` = self else { return } ElloHUD.hideLoadingHudInView(self.view) completion() } .ignoreErrors() } } // MARK: Push Notification Handling extension AppViewController { func receivedPushNotification(_ payload: PushPayload) { if self.visibleViewController is ElloTabBarController { navigateToDeepLink(payload.applicationTarget) } else { self.pushPayload = payload } } } // MARK: URL Handling extension AppViewController { func navigateToDeepLink(_ path: String) { let (type, data) = ElloURI.match(path) navigateToURI(path: path, type: type, data: data) } func navigateToURI(path: String, type: ElloURI, data: String?) { guard type.shouldLoadInApp else { showExternalWebView(path) return } guard !stillLoggingIn() && !stillSettingUpLoggedOut() else { self.deepLinkPath = path return } guard isLoggedIn() || !type.requiresLogin else { presentLoginOrSafariAlert(path) return } switch type { case .invite, .join, .signup, .login: guard !isLoggedIn() else { return } switch type { case .invite: showJoinScreen(invitationCode: data) case .join, .signup: showJoinScreen() case .login: showLoginScreen() default: break } case .artistInvitesBrowse: showArtistInvitesScreen() case .artistInvitesDetail, .pushNotificationArtistInvite: showArtistInvitesScreen(slug: data) case .exploreRecommended, .exploreRecent, .exploreTrending, .discover: showCategoryScreen() case .discoverRandom, .discoverRecent, .discoverRelated, .discoverTrending, .category: guard let slug = data else { return } showCategoryScreen(slug: slug) case .invitations: showInvitationScreen() case .forgotMyPassword: showForgotPasswordEmailScreen() case .resetMyPassword: guard let token = data else { return } showForgotPasswordResetScreen(authToken: token) case .enter: showLoginScreen() case .exit, .root, .explore: break case .friends, .following, .noise, .starred: showFollowingScreen() case .notifications: guard let category = data else { return } showNotificationsScreen(category: category) case .onboarding: guard let user = currentUser else { return } showOnboardingScreen(user) case .post: guard let postId = data else { return } showPostDetailScreen(postParam: postId, isSlug: true, path: path) case .pushNotificationComment, .pushNotificationPost: guard let postId = data else { return } showPostDetailScreen(postParam: postId, isSlug: false, path: path) case .profile: guard let userId = data else { return } showProfileScreen(userParam: userId, isSlug: true, path: path) case .pushNotificationURL: guard let path = data else { return } showExternalWebView("\(ElloURI.baseURL)/\(path)") case .pushNotificationUser: guard let userId = data else { return } showProfileScreen(userParam: userId, isSlug: false, path: path) case .profileFollowers, .profileFollowing: guard let username = data else { return } showProfileFollowersScreen(username: username) case .profileLoves: guard let username = data else { return } showProfileLovesScreen(username: username) case .search, .searchPeople, .searchPosts: showSearchScreen(terms: data) case .settings: showSettingsScreen() case .wtf: showExternalWebView(path) default: guard let pathURL = URL(string: path) else { return } UIApplication.shared.open(pathURL, options: [:], completionHandler: nil) } } private func stillLoggingIn() -> Bool { let authToken = AuthToken() return !isLoggedIn() && authToken.isPasswordBased } private func stillSettingUpLoggedOut() -> Bool { let authToken = AuthToken() let isLoggedOut = !isLoggedIn() && authToken.isAnonymous let nav = self.visibleViewController as? UINavigationController let loggedOutVC = nav?.viewControllers.first as? LoggedOutViewController let childNav = loggedOutVC?.children.first as? UINavigationController return childNav == nil && isLoggedOut } private func presentLoginOrSafariAlert(_ path: String) { guard !isLoggedIn() else { return } let alertController = AlertViewController(message: path) let yes = AlertAction(title: InterfaceString.App.LoginAndView, style: .dark) { _ in self.deepLinkPath = path self.showLoginScreen() } alertController.addAction(yes) let viewBrowser = AlertAction(title: InterfaceString.App.OpenInSafari, style: .light) { _ in guard let pathURL = URL(string: path) else { return } UIApplication.shared.open(pathURL, options: [:], completionHandler: nil) } alertController.addAction(viewBrowser) self.present(alertController, animated: true, completion: nil) } private func showInvitationScreen() { guard let vc = self.visibleViewController as? ElloTabBarController else { return } vc.selectedTab = .discover onInviteFriends() } private func showArtistInvitesScreen(slug: String? = nil) { if let slug = slug { guard let navigationController = pushDeepNavigationController(), !DeepLinking.alreadyOnArtistInvites( navVC: pushDeepNavigationController(), slug: slug ) else { return } Tracker.shared.artistInviteOpened(slug: slug) let vc = ArtistInviteDetailController(slug: slug) vc.currentUser = currentUser ArtistInviteDetailController.open(vc, in: navigationController) } else if let vc = self.visibleViewController as? ElloTabBarController { vc.selectedTab = .home let navVC = vc.selectedViewController as? ElloNavigationController let homeVC = navVC?.viewControllers.first as? HomeViewController homeVC?.showArtistInvitesViewController() navVC?.popToRootViewController(animated: true) } } private func showCategoryScreen(slug: String? = nil) { var catVC: CategoryViewController? if let vc = self.visibleViewController as? ElloTabBarController { if let slug = slug { Tracker.shared.categoryOpened(slug) } vc.selectedTab = .discover let navVC = vc.selectedViewController as? ElloNavigationController catVC = navVC?.viewControllers.first as? CategoryViewController navVC?.popToRootViewController(animated: true) } else if let topNav = self.visibleViewController as? UINavigationController, let loggedOutController = topNav.viewControllers.first as? LoggedOutViewController, let childNav = loggedOutController.children.first as? UINavigationController, let categoryViewController = childNav.viewControllers.first as? CategoryViewController { childNav.popToRootViewController(animated: true) catVC = categoryViewController } if let slug = slug { catVC?.selectCategoryFor(slug: slug) } else { catVC?.allCategoriesTapped() } } private func showFollowingScreen() { guard let vc = self.visibleViewController as? ElloTabBarController else { return } vc.selectedTab = .home guard let navVC = vc.selectedViewController as? ElloNavigationController, let homeVC = navVC.visibleViewController as? HomeViewController else { return } homeVC.showFollowingViewController() } private func showNotificationsScreen(category: String) { guard let vc = self.visibleViewController as? ElloTabBarController else { return } vc.selectedTab = .notifications guard let navVC = vc.selectedViewController as? ElloNavigationController, let notificationsVC = navVC.visibleViewController as? NotificationsViewController else { return } let notificationFilterType = NotificationFilterType.fromCategory(category) notificationsVC.categoryFilterType = notificationFilterType notificationsVC.activatedCategory(notificationFilterType) } func showProfileScreen(userParam: String, isSlug: Bool, path: String? = nil) { let param = isSlug ? "~\(userParam)" : userParam let profileVC = ProfileViewController(userParam: param) profileVC.deeplinkPath = path profileVC.currentUser = currentUser pushDeepLinkViewController(profileVC) } func showPostDetailScreen(postParam: String, isSlug: Bool, path: String? = nil) { let param = isSlug ? "~\(postParam)" : postParam let postDetailVC = PostDetailViewController(postParam: param) postDetailVC.deeplinkPath = path postDetailVC.currentUser = currentUser pushDeepLinkViewController(postDetailVC) } private func showProfileFollowersScreen(username: String) { let endpoint = ElloAPI.userStreamFollowers(userId: "~\(username)") let followersVC = SimpleStreamViewController( endpoint: endpoint, title: "@" + username + "'s " + InterfaceString.Followers.Title ) followersVC.currentUser = currentUser pushDeepLinkViewController(followersVC) } private func showProfileFollowingScreen(_ username: String) { let endpoint = ElloAPI.userStreamFollowing(userId: "~\(username)") let vc = SimpleStreamViewController( endpoint: endpoint, title: "@" + username + "'s " + InterfaceString.Following.Title ) vc.currentUser = currentUser pushDeepLinkViewController(vc) } private func showProfileLovesScreen(username: String) { let vc = LovesViewController(username: username) vc.currentUser = currentUser pushDeepLinkViewController(vc) } private func showSearchScreen(terms: String?) { let search = SearchViewController() search.currentUser = currentUser if let terms = terms, !terms.isEmpty { search.searchForPosts( terms.urlDecoded().replacingOccurrences( of: "+", with: " ", options: NSString.CompareOptions.literal, range: nil ) ) } pushDeepLinkViewController(search) } private func showSettingsScreen() { guard let currentUser = currentUser else { return } let settings = SettingsViewController(currentUser: currentUser) pushDeepLinkViewController(settings) } private func pushDeepNavigationController() -> UINavigationController? { var navController: UINavigationController? if let tabController = self.visibleViewController as? ElloTabBarController, let tabNavController = tabController.selectedViewController as? UINavigationController { let topNavVC = topViewController(self)?.navigationController navController = topNavVC ?? tabNavController } else if let nav = self.visibleViewController as? UINavigationController, let loggedOutVC = nav.viewControllers.first as? LoggedOutViewController, let childNav = loggedOutVC.children.first as? UINavigationController { navController = childNav } return navController } private func pushDeepLinkViewController(_ vc: UIViewController) { pushDeepNavigationController()?.pushViewController(vc, animated: true) } private func selectTab(_ tab: ElloTab) { ElloWebBrowserViewController.elloTabBarController?.selectedTab = tab } } extension AppViewController { func topViewController(_ base: UIViewController?) -> UIViewController? { if let nav = base as? UINavigationController { return topViewController(nav.visibleViewController) } if let tab = base as? UITabBarController { if let selected = tab.selectedViewController { return topViewController(selected) } } if let presented = base?.presentedViewController { return topViewController(presented) } return base } } private var isShowingDebug = false private var tabKeys: [String: ElloTab] = [ "1": .home, "2": .discover, "3": .omnibar, "4": .notifications, "5": .profile, ] extension AppViewController { override var canBecomeFirstResponder: Bool { return true } override var keyCommands: [UIKeyCommand]? { guard isFirstResponder else { return nil } return [ UIKeyCommand( input: UIKeyCommand.inputEscape, modifierFlags: [], action: #selector(escapeKeyPressed), discoverabilityTitle: "Back" ), UIKeyCommand( input: "1", modifierFlags: [], action: #selector(tabKeyPressed(_:)), discoverabilityTitle: "Home" ), UIKeyCommand( input: "2", modifierFlags: [], action: #selector(tabKeyPressed(_:)), discoverabilityTitle: "Discover" ), UIKeyCommand( input: "3", modifierFlags: [], action: #selector(tabKeyPressed(_:)), discoverabilityTitle: "Omnibar" ), UIKeyCommand( input: "4", modifierFlags: [], action: #selector(tabKeyPressed(_:)), discoverabilityTitle: "Notifications" ), UIKeyCommand( input: "5", modifierFlags: [], action: #selector(tabKeyPressed(_:)), discoverabilityTitle: "Profile" ), UIKeyCommand( input: " ", modifierFlags: [], action: #selector(scrollDownOnePage), discoverabilityTitle: "Scroll one page" ), ] } @objc func escapeKeyPressed() { guard let navigationController:UINavigationController = findChildController() else { return } navigationController.popViewController(animated: true) } @objc func tabKeyPressed(_ event: UIKeyCommand) { guard let tabBarController:ElloTabBarController = findChildController(), let tab = event.input.flatMap({ input in return tabKeys[input] }) else { return } tabBarController.selectedTab = tab } @objc func scrollDownOnePage() { guard let streamViewController:StreamViewController = findChildController() else { return } streamViewController.scrollDownOnePage() } private var debugAllowed: Bool { #if DEBUG return true #else return AuthToken().isStaff || DebugServer.fromDefaults != nil #endif } override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) { guard debugAllowed, motion == .motionShake else { return } if isShowingDebug { closeDebugController() } else { showDebugController() } } func showDebugController() { guard !isShowingDebug else { return } isShowingDebug = true let ctlr = DebugController() ctlr.title = "Debugging" let nav = UINavigationController(rootViewController: ctlr) let bar = UIView(frame: CGRect(x: 0, y: -20, width: view.frame.width, height: 20)) bar.autoresizingMask = [.flexibleWidth, .flexibleBottomMargin] bar.backgroundColor = .black nav.navigationBar.addSubview(bar) let closeItem = UIBarButtonItem.closeButton( target: self, action: #selector(AppViewController.closeDebugControllerTapped) ) ctlr.navigationItem.leftBarButtonItem = closeItem present(nav, animated: true, completion: nil) } @objc func closeDebugControllerTapped() { closeDebugController() } func closeDebugController(completion: Block? = nil) { guard isShowingDebug else { return } isShowingDebug = false dismiss(animated: true, completion: completion) } }
mit
534ba5030951980dd8e8aafb09be3700
32.63807
100
0.619936
5.719647
false
false
false
false
leo150/Pelican
Sources/Pelican/Pelican/Pelican+Moderator.swift
1
5547
import Foundation import Vapor /** Manages user access to the bot through a permanent blacklist feature (that works in conjunction with FloodLimit), while enabling the creation of custom user lists for flexible permission and other custom user and chat grouping systems. */ public class Moderator { /// Holds the main bot class to ensure access to Chat and User Session lists. var chatTitles: [String:[Int]] = [:] var userTitles: [String:[Int]] = [:] var chatBlacklist: [Int] = [] var userBlacklist: [Int] = [] var getChats: [String:[Int]] { return chatTitles } var getUsers: [String:[Int]] { return userTitles } public init() { } /** An internal function to do the heavy lifting for tag changes. */ func switchTitle(type: SessionIDType, title: String, ids: [Int], remove: Bool) { func editList(ids: [Int], list: [Int], remove: Bool) -> [Int] { var mutableList: [Int] = list if remove == true { ids.forEach( { if let index = mutableList.index(of: $0) { mutableList.remove(at: index) } }) } else { ids.forEach( { if mutableList.contains($0) == false { mutableList.append($0) } }) } return mutableList } switch type { case .chat: if chatTitles[title] == nil { chatTitles[title] = [] } let list = chatTitles[title]! chatTitles[title] = editList(ids: ids, list: list, remove: remove) if chatTitles[title]!.count == 0 { chatTitles.removeValue(forKey: title) } case .user: if userTitles[title] == nil { userTitles[title] = [] } let list = userTitles[title]! userTitles[title] = editList(ids: ids, list: list, remove: remove) if userTitles[title]!.count == 0 { userTitles.removeValue(forKey: title) } default: return } } /** Returns the currently used titles. */ public func getTitles(forType type: SessionIDType) -> [String]? { switch type { case .chat: return chatTitles.keys.array case .user: return userTitles.keys.array default: return nil } } /** Returns the titles associated to a specific ID. */ public func getTitles(forID id: Int, type: SessionIDType) -> [String] { var titles: [String] = [] switch type { case .chat: chatTitles.forEach( { if $0.value.contains(id) == true { titles.append($0.key) } } ) case .user: userTitles.forEach( { if $0.value.contains(id) == true { titles.append($0.key) } } ) default: return [] } return titles } /** Returns the IDs associated to a specific title. */ public func getIDs(forTitle title: String, type: SessionIDType) -> [Int]? { switch type { case .chat: if let ids = chatTitles[title] { return ids } case .user: if let ids = userTitles[title] { return ids } default: return nil } return nil } /** Adds a given set of IDs to a specific title. */ public func addIDs(forTitle title: String, type: SessionIDType, ids: Int...) { switchTitle(type: type, title: title, ids: ids, remove: false) } /** Removes a given set of IDs from a specific title. */ public func removeIDs(forTitle title: String, type: SessionIDType, ids: Int...) { switchTitle(type: type, title: title, ids: ids, remove: true) } // BLACKLIST /** Adds the given users to the blacklist, preventing their updates from being received by or propogating any sessions. As this function does not remove and close the Session, this is an internal type only. */ func addToBlacklist(userIDs: Int...) { // Add the users to the blacklist if they aren't already there for id in userIDs { if userBlacklist.contains(id) == false { userBlacklist.append(id) } } } /** Adds the given chats to the blacklist, preventing their updates from being received by or propogating any sessions. As this function does not remove and close the Session, this is an internal type only. */ func addToBlacklist(chatIDs: Int...) { // Add the chats to the blacklist if they aren't already there for id in chatIDs { if chatBlacklist.contains(id) == false { chatBlacklist.append(id) print("ADDED TO BLACKLIST - \(id)") } } } /** Removes the given users from the blacklist, allowing updates they make to be received by the bot. */ public func removeFromBlacklist(userIDs: Int...) { // Remove the users from the blacklist if they ended up there for id in userIDs { if let index = userBlacklist.index(of: id) { userBlacklist.remove(at: index) } } } /** Removes the given chat from the blacklist, allowing updates they make to be received by the bot. */ public func removeFromBlacklist(chatIDs: Int...) { // Remove the chats from the blacklist if they ended up there for id in chatIDs { if let index = chatBlacklist.index(of: id) { chatBlacklist.remove(at: index) } } } /** Checks to see if the given user ID is in the blacklist. - returns: True if they are in the blacklist, false if not. */ public func checkBlacklist(userID: Int) -> Bool { if userBlacklist.contains(userID) == true { return true } return false } /** Checks to see if the given chat ID is in the blacklist. - returns: True if they are in the blacklist, false if not. */ public func checkBlacklist(chatID: Int) -> Bool { if chatBlacklist.contains(chatID) == true { return true } return false } }
mit
24cca8ce675bd72aee40db2306099193
19.853383
119
0.639986
3.411439
false
false
false
false
CatchChat/Yep
YepKit/Extensions/UIImage+Yep.swift
1
18297
// // UIImage+Yep.swift // Yep // // Created by NIX on 15/3/16. // Copyright (c) 2015年 Catch Inc. All rights reserved. // import UIKit import ImageIO import MobileCoreServices.UTType import Ruler public extension UIImage { public var yep_fixedSize: CGSize { let imageWidth = self.size.width let imageHeight = self.size.height let fixedImageWidth: CGFloat let fixedImageHeight: CGFloat if imageWidth > imageHeight { fixedImageHeight = min(imageHeight, Config.Media.imageHeight) fixedImageWidth = imageWidth * (fixedImageHeight / imageHeight) } else { fixedImageWidth = min(imageWidth, Config.Media.imageWidth) fixedImageHeight = imageHeight * (fixedImageWidth / imageWidth) } return CGSize(width: fixedImageWidth, height: fixedImageHeight) } } public extension UIImage { public func largestCenteredSquareImage() -> UIImage { let scale = self.scale let originalWidth = self.size.width * scale let originalHeight = self.size.height * scale let edge: CGFloat if originalWidth > originalHeight { edge = originalHeight } else { edge = originalWidth } let posX = (originalWidth - edge) / 2.0 let posY = (originalHeight - edge) / 2.0 let cropSquare = CGRectMake(posX, posY, edge, edge) let imageRef = CGImageCreateWithImageInRect(self.CGImage, cropSquare)! return UIImage(CGImage: imageRef, scale: scale, orientation: self.imageOrientation) } public func resizeToTargetSize(targetSize: CGSize) -> UIImage { let size = self.size let widthRatio = targetSize.width / self.size.width let heightRatio = targetSize.height / self.size.height let scale = UIScreen.mainScreen().scale let newSize: CGSize if(widthRatio > heightRatio) { newSize = CGSizeMake(scale * floor(size.width * heightRatio), scale * floor(size.height * heightRatio)) } else { newSize = CGSizeMake(scale * floor(size.width * widthRatio), scale * floor(size.height * widthRatio)) } let rect = CGRectMake(0, 0, floor(newSize.width), floor(newSize.height)) //println("size: \(size), newSize: \(newSize), rect: \(rect)") UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0) self.drawInRect(rect) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage } public func scaleToMinSideLength(sideLength: CGFloat) -> UIImage { let pixelSideLength = sideLength * UIScreen.mainScreen().scale //println("pixelSideLength: \(pixelSideLength)") //println("size: \(size)") let pixelWidth = size.width * scale let pixelHeight = size.height * scale //println("pixelWidth: \(pixelWidth)") //println("pixelHeight: \(pixelHeight)") let newSize: CGSize if pixelWidth > pixelHeight { guard pixelHeight > pixelSideLength else { return self } let newHeight = pixelSideLength let newWidth = (pixelSideLength / pixelHeight) * pixelWidth newSize = CGSize(width: floor(newWidth), height: floor(newHeight)) } else { guard pixelWidth > pixelSideLength else { return self } let newWidth = pixelSideLength let newHeight = (pixelSideLength / pixelWidth) * pixelHeight newSize = CGSize(width: floor(newWidth), height: floor(newHeight)) } if scale == UIScreen.mainScreen().scale { let newSize = CGSize(width: floor(newSize.width / scale), height: floor(newSize.height / scale)) //println("A scaleToMinSideLength newSize: \(newSize)") UIGraphicsBeginImageContextWithOptions(newSize, false, scale) let rect = CGRectMake(0, 0, newSize.width, newSize.height) self.drawInRect(rect) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() if let image = newImage { return image } return self } else { //println("B scaleToMinSideLength newSize: \(newSize)") UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0) let rect = CGRectMake(0, 0, newSize.width, newSize.height) self.drawInRect(rect) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() if let image = newImage { return image } return self } } public func fixRotation() -> UIImage { if self.imageOrientation == .Up { return self } let width = self.size.width let height = self.size.height var transform = CGAffineTransformIdentity switch self.imageOrientation { case .Down, .DownMirrored: transform = CGAffineTransformTranslate(transform, width, height) transform = CGAffineTransformRotate(transform, CGFloat(M_PI)) case .Left, .LeftMirrored: transform = CGAffineTransformTranslate(transform, width, 0) transform = CGAffineTransformRotate(transform, CGFloat(M_PI_2)) case .Right, .RightMirrored: transform = CGAffineTransformTranslate(transform, 0, height) transform = CGAffineTransformRotate(transform, CGFloat(-M_PI_2)) default: break } switch self.imageOrientation { case .UpMirrored, .DownMirrored: transform = CGAffineTransformTranslate(transform, width, 0); transform = CGAffineTransformScale(transform, -1, 1); case .LeftMirrored, .RightMirrored: transform = CGAffineTransformTranslate(transform, height, 0); transform = CGAffineTransformScale(transform, -1, 1); default: break } let selfCGImage = self.CGImage let context = CGBitmapContextCreate(nil, Int(width), Int(height), CGImageGetBitsPerComponent(selfCGImage), 0, CGImageGetColorSpace(selfCGImage), CGImageGetBitmapInfo(selfCGImage).rawValue); CGContextConcatCTM(context, transform) switch self.imageOrientation { case .Left, .LeftMirrored, .Right, .RightMirrored: CGContextDrawImage(context, CGRectMake(0,0, height, width), selfCGImage) default: CGContextDrawImage(context, CGRectMake(0,0, width, height), selfCGImage) } let cgImage = CGBitmapContextCreateImage(context)! return UIImage(CGImage: cgImage) } } // MARK: Message Image public enum MessageImageTailDirection { case Left case Right } public extension UIImage { public func cropToAspectRatio(aspectRatio: CGFloat) -> UIImage { let size = self.size let originalAspectRatio = size.width / size.height var rect = CGRectZero if originalAspectRatio > aspectRatio { let width = size.height * aspectRatio rect = CGRect(x: (size.width - width) * 0.5, y: 0, width: width, height: size.height) } else if originalAspectRatio < aspectRatio { let height = size.width / aspectRatio rect = CGRect(x: 0, y: (size.height - height) * 0.5, width: size.width, height: height) } else { return self } let cgImage = CGImageCreateWithImageInRect(self.CGImage, rect)! return UIImage(CGImage: cgImage) } } public extension UIImage { public func imageWithGradientTintColor(tintColor: UIColor) -> UIImage { return imageWithTintColor(tintColor, blendMode: CGBlendMode.Overlay) } public func imageWithTintColor(tintColor: UIColor, blendMode: CGBlendMode) -> UIImage { UIGraphicsBeginImageContextWithOptions(size, false, 0) tintColor.setFill() let bounds = CGRect(origin: CGPointZero, size: size) UIRectFill(bounds) self.drawInRect(bounds, blendMode: blendMode, alpha: 1) if blendMode != CGBlendMode.DestinationIn { self.drawInRect(bounds, blendMode: CGBlendMode.DestinationIn, alpha: 1) } let tintedImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return tintedImage } } public extension UIImage { public func renderAtSize(size: CGSize) -> UIImage { // 确保 size 为整数,防止 mask 里出现白线 let size = CGSize(width: ceil(size.width), height: ceil(size.height)) UIGraphicsBeginImageContextWithOptions(size, false, 0) // key let context = UIGraphicsGetCurrentContext() drawInRect(CGRect(origin: CGPointZero, size: size)) let cgImage = CGBitmapContextCreateImage(context)! let image = UIImage(CGImage: cgImage) UIGraphicsEndImageContext() return image } public func maskWithImage(maskImage: UIImage) -> UIImage { let scale = UIScreen.mainScreen().scale UIGraphicsBeginImageContextWithOptions(self.size, false, scale) let context = UIGraphicsGetCurrentContext() var transform = CGAffineTransformConcat(CGAffineTransformIdentity, CGAffineTransformMakeScale(1.0, -1.0)) transform = CGAffineTransformConcat(transform, CGAffineTransformMakeTranslation(0.0, self.size.height)) CGContextConcatCTM(context, transform) let drawRect = CGRect(origin: CGPointZero, size: self.size) CGContextClipToMask(context, drawRect, maskImage.CGImage) CGContextDrawImage(context, drawRect, self.CGImage) let roundImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return roundImage } public struct BubbleMaskImage { public static let leftTail: UIImage = { let scale = UIScreen.mainScreen().scale let orientation: UIImageOrientation = .Up var maskImage = UIImage(CGImage: UIImage(named: "left_tail_image_bubble")!.CGImage!, scale: scale, orientation: orientation) maskImage = maskImage.resizableImageWithCapInsets(UIEdgeInsets(top: 25, left: 27, bottom: 20, right: 20), resizingMode: UIImageResizingMode.Stretch) return maskImage }() public static let rightTail: UIImage = { let scale = UIScreen.mainScreen().scale let orientation: UIImageOrientation = .Up var maskImage = UIImage(CGImage: UIImage(named: "right_tail_image_bubble")!.CGImage!, scale: scale, orientation: orientation) maskImage = maskImage.resizableImageWithCapInsets(UIEdgeInsets(top: 24, left: 20, bottom: 20, right: 27), resizingMode: UIImageResizingMode.Stretch) return maskImage }() } public func bubbleImageWithTailDirection(tailDirection: MessageImageTailDirection, size: CGSize, forMap: Bool = false) -> UIImage { //let orientation: UIImageOrientation = tailDirection == .Left ? .Up : .UpMirrored let maskImage: UIImage if tailDirection == .Left { maskImage = BubbleMaskImage.leftTail.renderAtSize(size) } else { maskImage = BubbleMaskImage.rightTail.renderAtSize(size) } if forMap { let image = cropToAspectRatio(size.width / size.height).resizeToTargetSize(size) UIGraphicsBeginImageContextWithOptions(image.size, true, image.scale) image.drawAtPoint(CGPointZero) let bottomShadowImage = UIImage(named: "location_bottom_shadow")! let bottomShadowHeightRatio: CGFloat = 0.185 // 20 / 108 bottomShadowImage.drawInRect(CGRect(x: 0, y: floor(image.size.height * (1 - bottomShadowHeightRatio)), width: image.size.width, height: ceil(image.size.height * bottomShadowHeightRatio))) let finalImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() let bubbleImage = finalImage.maskWithImage(maskImage) return bubbleImage } // fixRotation 会消耗大量内存,改在发送前做 let bubbleImage = /*self.fixRotation().*/cropToAspectRatio(size.width / size.height).resizeToTargetSize(size).maskWithImage(maskImage) return bubbleImage } } // MARK: - Decode public extension UIImage { public func decodedImage() -> UIImage { return decodedImage(scale: scale) } public func decodedImage(scale scale: CGFloat) -> UIImage { let imageRef = CGImage let colorSpace = CGColorSpaceCreateDeviceRGB() let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedLast.rawValue) let context = CGBitmapContextCreate(nil, CGImageGetWidth(imageRef), CGImageGetHeight(imageRef), 8, 0, colorSpace, bitmapInfo.rawValue) if let context = context { let rect = CGRectMake(0, 0, CGFloat(CGImageGetWidth(imageRef)), CGFloat(CGImageGetHeight(imageRef))) CGContextDrawImage(context, rect, imageRef) let decompressedImageRef = CGBitmapContextCreateImage(context)! return UIImage(CGImage: decompressedImageRef, scale: scale, orientation: imageOrientation) ?? self } return self } } // MARK: Resize public extension UIImage { public func resizeToSize(size: CGSize, withTransform transform: CGAffineTransform, drawTransposed: Bool, interpolationQuality: CGInterpolationQuality) -> UIImage? { let newRect = CGRectIntegral(CGRect(origin: CGPointZero, size: size)) let transposedRect = CGRect(origin: CGPointZero, size: CGSize(width: size.height, height: size.width)) let bitmapContext = CGBitmapContextCreate(nil, Int(newRect.width), Int(newRect.height), CGImageGetBitsPerComponent(CGImage), 0, CGImageGetColorSpace(CGImage), CGImageGetBitmapInfo(CGImage).rawValue) CGContextConcatCTM(bitmapContext, transform) CGContextSetInterpolationQuality(bitmapContext, interpolationQuality) CGContextDrawImage(bitmapContext, drawTransposed ? transposedRect : newRect, CGImage) if let newCGImage = CGBitmapContextCreateImage(bitmapContext) { let newImage = UIImage(CGImage: newCGImage) return newImage } return nil } public func transformForOrientationWithSize(size: CGSize) -> CGAffineTransform { var transform = CGAffineTransformIdentity switch imageOrientation { case .Down, .DownMirrored: transform = CGAffineTransformTranslate(transform, size.width, size.height) transform = CGAffineTransformRotate(transform, CGFloat(M_PI)) case .Left, .LeftMirrored: transform = CGAffineTransformTranslate(transform, size.width, 0) transform = CGAffineTransformRotate(transform, CGFloat(M_PI_2)) case .Right, .RightMirrored: transform = CGAffineTransformTranslate(transform, 0, size.height) transform = CGAffineTransformRotate(transform, CGFloat(-M_PI_2)) default: break } switch imageOrientation { case .UpMirrored, .DownMirrored: transform = CGAffineTransformTranslate(transform, size.width, 0) transform = CGAffineTransformScale(transform, -1, 1) case .LeftMirrored, .RightMirrored: transform = CGAffineTransformTranslate(transform, size.height, 0) transform = CGAffineTransformScale(transform, -1, 1) default: break } return transform } public func resizeToSize(size: CGSize, withInterpolationQuality interpolationQuality: CGInterpolationQuality) -> UIImage? { let drawTransposed: Bool switch imageOrientation { case .Left, .LeftMirrored, .Right, .RightMirrored: drawTransposed = true default: drawTransposed = false } return resizeToSize(size, withTransform: transformForOrientationWithSize(size), drawTransposed: drawTransposed, interpolationQuality: interpolationQuality) } } public extension UIImage { public var yep_avarageColor: UIColor { let rgba = UnsafeMutablePointer<CUnsignedChar>.alloc(4) let colorSpace: CGColorSpaceRef = CGColorSpaceCreateDeviceRGB()! let info = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedLast.rawValue) let context: CGContextRef = CGBitmapContextCreate(rgba, 1, 1, 8, 4, colorSpace, info.rawValue)! CGContextDrawImage(context, CGRectMake(0, 0, 1, 1), CGImage) let alpha: CGFloat = (rgba[3] > 0) ? (CGFloat(rgba[3]) / 255.0) : 1 let multiplier = alpha / 255.0 return UIColor(red: CGFloat(rgba[0]) * multiplier, green: CGFloat(rgba[1]) * multiplier, blue: CGFloat(rgba[2]) * multiplier, alpha: alpha) } } // MARK: Progressive public extension UIImage { public var yep_progressiveImage: UIImage? { guard let cgImage = CGImage else { return nil } let data = NSMutableData() guard let distination = CGImageDestinationCreateWithData(data, kUTTypeJPEG, 1, nil) else { return nil } let jfifProperties = [ kCGImagePropertyJFIFIsProgressive as String: kCFBooleanTrue as Bool, kCGImagePropertyJFIFXDensity as String: 72, kCGImagePropertyJFIFYDensity as String: 72, kCGImagePropertyJFIFDensityUnit as String: 1, ] let properties = [ kCGImageDestinationLossyCompressionQuality as String: 0.9, kCGImagePropertyJFIFDictionary as String: jfifProperties, ] CGImageDestinationAddImage(distination, cgImage, properties) guard CGImageDestinationFinalize(distination) else { return nil } guard data.length > 0 else { return nil } guard let progressiveImage = UIImage(data: data) else { return nil } return progressiveImage } }
mit
eb9d39731762e25f69926d7706ae10dc
32.469725
206
0.653418
5.199829
false
false
false
false
NghiaTranUIT/Titan
TitanCore/TitanCore/SelectedTableWorker.swift
2
1280
// // SelectedTableWorker.swift // TitanCore // // Created by Nghia Tran on 4/20/17. // Copyright © 2017 nghiatran. All rights reserved. // import Foundation import SwiftyPostgreSQL import RxSwift struct ReplaceTableAction: Action { var selectedTable: Table! var storeType: StoreType {return .detailDatabaseStore} } struct SelectedIndexInStackViewAction: Action { var selectedIndex: Int! var storeType: StoreType {return .detailDatabaseStore} } struct AddTableToStackAction: Action { var selectedTable: Table! var storeType: StoreType {return .detailDatabaseStore} } class ReplaceTableInCurrentTabWorker: SyncWorker { typealias T = Void var seletedTable: Table! init(seletedTable: Table) { self.seletedTable = seletedTable } func execute() { // If no selection -> add to stack if MainStore.globalStore.detailDatabaseStore.stackTables.value.count == 0 { let addStackAction = AddTableToStackAction(selectedTable: self.seletedTable) MainStore.dispatch(addStackAction) } else { // REplace table let action = ReplaceTableAction(selectedTable: self.seletedTable) MainStore.dispatch(action) } } }
mit
4453f1deb0b4ffd7ef841b05f91022c9
24.58
88
0.680219
4.249169
false
false
false
false
andanylo/THE-Plane
PlaneShopScene.swift
1
4677
import SpriteKit import GameKit class PlaneShopScene: SKScene { var textureAtlas = SKTextureAtlas(named: "Gamesprite") var PlaneSpriteA = SKSpriteNode() var PlaneSpriteB = SKSpriteNode() var PlaneSpriteC = SKSpriteNode() var PlaneSpriteD = SKSpriteNode() var planeA = PlaneA() var planeB = PlaneB() var drawscene = DrawScene() var plusLabel = SKLabelNode() var CostB = SKLabelNode() var CostC = SKLabelNode() var CostD = SKLabelNode() var shopscene = ShopScene() override func didMove(to view: SKView){ shops cene.CreateBackButton() self.anchorPoint = CGPoint(x: 0.5, y: 0.5) //shopscene.CreateBackButton() PlaneSpriteA = SKSpriteNode(texture: textureAtlas.textureNamed("plane1")) PlaneSpriteA.size = CGSize(width: 200, height: 151) PlaneSpriteA.position = CGPoint(x: -self.size.width / 3.5, self.size.height / 2 - 200) PlaneSpriteA.name = "planeA" PlaneSpriteA.zPosition = 2 PlaneSpriteB = SKSpriteNode(texture: textureAtlas.textureNamed("plane2")) PlaneSpriteB.size = CGSize(width:200, height: 151) PlaneSpriteB.position = CGPoint(x: PlaneA.position.x + 400, y: PlaneA.position.y) PlaneSpriteB.name = "planeB" PlaneSpriteB.zPosition = 2 if planeB.isBuyed == false{ CostB = SKLabelNode(text: "500") CostB.position = CGPoint(x: PlaneB.position.x, y: PlaneB.position.y - 45) CostB.fontSize = 25 CostB.fontName = "Arial" CostB.zPosition = 2 } PlaneSpriteC = SKSpriteNode(texture: textureAtlas.textureNamed("plane3")) PlaneSpriteC.position = CGPoint(x: PlaneB.position.x + 400, y: PlaneB.position.y) PlaneSpriteC.size = CGSize(width: 200, height: 151) PlaneSpriteC.zPosition = 2 PlaneSpriteC.name = "planeC" if planeC.isBuyed == false{ CostC = SKLabelNode(text: "1000") CostC.position = CGPoint(x: PlaneC.position.x, y: PlaneC.position.y - 45) CostC.fontSize = 25 CostC.fontName = "Arial" CostC.zPosition = 2 } PlaneSpriteD = SKSpriteNode(texture: textureAtlas.textureNamed("plane4")) PlaneSpriteD.position = CGPoint(x: PlaneA.position.x, y: PlaneA.position.y - 400) PlaneSpriteD.size = CGSize(width: 200, height: 151) PlaneSpriteD.zPosition = 2 PlaneSpriteD.name = "planeD" if planeD.isBuyed == false{ CostD = SKLabelNode(text: "1500") CostD.position = CGPoint(x:PlaneD.position.x, y: PlaneD.position.y - 45) CostD.fontName = "Arial" CostD.fontSize = 25 CostD.zPosition = 2 } if DrawScene.isBuyed == 0 { DrawSprite = SKSpriteNode(imageNamed: "шаблон") DrawSprite.position = CGPoint(x: 0, y: 0) DrawSprite.zPosition = 2 DrawSprite.size = CGSize(width: 200, height: 151) DrawSprite.name = "Draw" self.addChild(DrawSprite) plusLabel = SKLabelNode(fontNamed: "Chulkduster")] plusLabel.text = "+" plusLabel.position = CGPoint(x: 0, y: 0) plusLabel.zPosition = 4 plusLabel.fontColor = //fiolet plusLabel.fontSize = 25 DrawSprite.addChild(plusLabel) } self.addChild(PlaneSpriteA) self.addChild(PlaneSpriteB) self.addChild(PlaneSpriteC) self.addChild(PlaneSpriteD) self.addChild(CostB) self.addChild(CostC) self.addChild(CostD) CreateActions() } func CreateActions(){ let PlaneActionA = SKAction.sequence{[ SKAction.scale(to: 1, duration: 1) SKAction.fadeAlpha(to:1, duration: 1) ]} PlaneSpriteA.run(PlaneActionA) let PlaneActionB = SKAction.sequence{[ SKAction.wait(forDuration: 0.5) SKAction.scale(to: 1, duration: 1) SKAction.fadeAlpha(to:1, duration: 1) ]} PlaneSpriteB.run(PlaneActionB) let PlaneActionC = SKAction.sequence{[ SKAction.wait(forDuration: 1) SKAction.scale(to: 1, duration: 1) SKAction.fadeAlpha(to:1, duration: 1) ]} PlaneSpriteC.run(PlaneActionC) let PlaneActionD = SKAction.sequence{[ SKAction.wait(forDuration: 1.5) SKAction.scale(to: 1, duration: 1) SKAction.fadeAlpha(to:1, duration: 1) ]} PlaneSpriteD.run(PlaneActionD) } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { for touch in (touches) { let location = touch.location(in: self) let node = atPoint(location) if node.name == "planeA"{ self.view?.presentScene(PlaneA(size: self.size)) } else if node.name == "planeB"{ self.view?.presentScene(PlaneB(size: self.size)) } else if node.name == "planeC"{ } else if node.name == "planeD"{ } else if node.name == "Draw"{ //blabla presentview controller blabla self.DrawView.presentScene(DrawScene(size: self.size), transition: .crossFade(withDuraition: 1) } } }
apache-2.0
4f4575c76c93f825c92c932888d41ef8
31.664336
97
0.682081
3.37013
false
false
false
false
alobanov/ALFormBuilder
Sources/FormBuilder/ALFormBuilder.swift
1
8987
// // ALFormBuilder.swift // ALFormBuilder // // Created by Lobanov Aleksey on 25/10/2017. // Copyright © 2017 Lobanov Aleksey. All rights reserved. // import Foundation import ObjectMapper public protocol ALFormBuilderProtocol { var didDatasource: ALFormBuilder.DidDatasource? {set get} var didChangeFormModel: ALFormBuilder.DidChangeFormModel? {set get} var didChangeCompletelyValidation: ALFormBuilder.DidChangeCompletelyValidation? {set get} var didChangeFormState: ALFormBuilder.DidChangeFormState? {set get} // Подготовить билдер данные для отображения, после вызова форма отрисуется func prepareDatasource() // Динамически сформированый словарь с введенными данными func object(withoutNull: Bool) -> [String: Any] // Запросить модель по уникальному идентификатору func model(by identifier: String) -> FormItemCompositeProtocol? // Конфигурируем func configure(compositeFormData: FormItemCompositeProtocol) func apply(errors: [String: String]) -> Bool //маппинг динамического словаря в модель func mappedObject<T: Mappable>(parameters: [String: Any]?) -> T? } public class ALFormBuilder: ALFormBuilderProtocol { public typealias DidDatasource = (FormItemCompositeProtocol) -> Void public typealias DidChangeFormModel = (FormItemCompositeProtocol) -> Void public typealias DidChangeCompletelyValidation = (Bool) -> Void public typealias DidChangeFormState = (Bool) -> Void public var didDatasource: ALFormBuilder.DidDatasource? public var didChangeFormModel: ALFormBuilder.DidChangeFormModel? public var didChangeCompletelyValidation: ALFormBuilder.DidChangeCompletelyValidation? public var didChangeFormState: ALFormBuilder.DidChangeFormState? private var jsonBuilder: ALFormJSONBuilderProtocol private var compositeFormData: FormItemCompositeProtocol? // Состояния private var completelyValidation: Bool = false private var formWasModify: Bool = false // Инициализация с подготовленой структурой данных для таблицы // и зависимость в виде билдера для JSON public init(compositeFormData: FormItemCompositeProtocol, jsonBuilder: ALFormJSONBuilderProtocol) { self.jsonBuilder = jsonBuilder if compositeFormData.level == .root { configure(compositeFormData: compositeFormData) } } // Ручная конфигурация с новой структурой // Метод перезапускает инициализацию FormJSONBuilder // Также выполняется подписка на изменение всех полей в форме public func configure(compositeFormData: FormItemCompositeProtocol) { self.compositeFormData = compositeFormData self.jsonBuilder.prepareObject(tree: compositeFormData) guard let rows = compositeFormData.leaves .filter({ $0 is RowCompositeValueTransformable }) as? [RowCompositeValueTransformable] else { return } for row in rows { row.didChangeData = { [weak self] model, isSilent in self?.updateChanged(item: model, isSilent: isSilent) } } } // Подготовка данных и формирование данных для таблицы public func prepareDatasource() { guard let item = self.compositeFormData else { return } // Проверка всех состоянийв полях (обязательность, видимость и блокировка) checkAllStates(in: item) // Проверка состояний всей таблицы (изменение, полная валидация) checkCommonFormState(in: item) // Установка значения по умолчанию для полей которые требуют полной валидации itemsWithFullValidation(in: item, isFullValidState: completelyValidation) // Формирование всех элементов для таблицы reloadDataSource() } // Проверка всех состояний в моделях таблицы и пересозлание private func rebuildFields(item1: FormItemCompositeProtocol) { guard let item = self.compositeFormData else { return } // reload table if needed let isChanged = checkAllStates(in: item) let isChangedInCommonState = checkCommonFormState(in: item) if isChanged || isChangedInCommonState { reloadDataSource() } } // Проврка всех состояний во всех полях таблицы, возвращает значение нужна ли перезагрузка таблицы или нет @discardableResult private func checkAllStates(in compositeFormData: FormItemCompositeProtocol) -> Bool { var needReload = false let obj = jsonBuilder.object(withoutNull: false) guard let rows = compositeFormData.leaves .filter({ $0 is RowCompositeVisibleSetting & FormItemCompositeProtocol }) as? [RowCompositeVisibleSetting & FormItemCompositeProtocol] else { return needReload } for row in rows { if row.checkStates(by: obj) { row.base.needReloadModel() needReload = true } } for row in rows where row is RowCompositeValidationSetting { guard let validatebleRow = row as? RowCompositeValidationSetting else { continue } let prew = validatebleRow.validation.state let new = validatebleRow.validate(value: validatebleRow.value) if !(prew == new) { validatebleRow.validation.change(state: new) if let block = validatebleRow.didChangeValidation[row.identifier] { block?() } } } return needReload } // Получить словарь со сформированной структурой по данным таблицы public func object(withoutNull: Bool) -> [String: Any] { return jsonBuilder.object(withoutNull: withoutNull) } // Обновить значение в JOSN передав просто композит модели ячейки private func updateChanged(item: FormItemCompositeProtocol, isSilent: Bool) { jsonBuilder.updateValue(item: item) if !isSilent { didChangeFormModel?(item) } rebuildFields(item1: item) } // Получить модель по уникальному идентификатору public func model(by identifier: String) -> FormItemCompositeProtocol? { guard let rows = self.compositeFormData?.leaves else { return nil } for row in rows where row.identifier == identifier { return row } return nil } @discardableResult private func checkCommonFormState(in item: FormItemCompositeProtocol) -> Bool { var needReload = false if item.wasChanged() != formWasModify { formWasModify = !formWasModify didChangeFormState?(formWasModify) } if item.isValid() != completelyValidation { completelyValidation = !completelyValidation didChangeCompletelyValidation?(completelyValidation) needReload = itemsWithFullValidation(in: item, isFullValidState: completelyValidation) } return needReload } // Формирование нового datasource для перерисовки (упрощенный вызов) private func reloadDataSource() { if let composite = self.compositeFormData { didDatasource?(composite) } } @discardableResult private func itemsWithFullValidation(in item: FormItemCompositeProtocol, isFullValidState: Bool) -> Bool { guard let fullValidationItems = item.leaves.filter({$0 is RowCompositeVisibleSetting}) as? [RowCompositeVisibleSetting] else { return false } for field in fullValidationItems where field.visible.disabledExp == ALFB.Condition.fullValidation { field.base.needReloadModel() field.visible.changeDisabled(state: !completelyValidation) } return true } public func mappedObject<T: Mappable>(parameters: [String: Any]?) -> T? { return jsonBuilder.mappedObject(parameters: parameters) } public func apply(errors: [String: String]) -> Bool { var isContainError = false for (formItentifier, message) in errors { guard let model = model(by: formItentifier) as? RowCompositeValidationSetting else { continue } model.validation.change(state: .failed(message: message)) isContainError = true } if isContainError { didChangeCompletelyValidation?(!isContainError) } return isContainError } deinit { print("FormBuilder are dead") } }
mit
07c9b0b6e37d75e69ac04290b64744c0
32.579832
147
0.722472
4.071319
false
false
false
false
1457792186/JWSwift
熊猫TV2/XMTV/Classes/SmallShow/Controller/SmallShowVC.swift
2
2009
// // SmallShowVC.swift // XMTV // // Created by Mac on 2017/1/3. // Copyright © 2017年 Mac. All rights reserved. // import UIKit class SmallShowVC: UIViewController { // MARK: - 由于用青花瓷没有抓取到请求,就用webView直接加载熊猫TV官网 小葱秀地址。显示效果差不多 /// 注意: 控制台打印跟 webView.loadRequest(request)这句代码有关,只要loadRequest就会出现个打印,这个可能是应为ios10 SDK的问题,这个虽然看起来不爽,但是不影响程序正常运行。暂时没有找到解决方法。 /* objc[22562]: Class PLBuildVersion is implemented in both /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk/System/Library/PrivateFrameworks/AssetsLibraryServices.framework/AssetsLibraryServices (0x127e44910) and /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk/System/Library/PrivateFrameworks/PhotoLibraryServices.framework/PhotoLibraryServices (0x127c6e210). One of the two will be used. Which one is undefined. */ override func viewDidLoad() { super.viewDidLoad() automaticallyAdjustsScrollViewInsets = false let webView = UIWebView(frame: CGRect(x: 0, y: 20, width: kScreenW, height: kScreenH-49)) webView.delegate = self view.addSubview(webView) webView.scrollView.bounces = false let request = URLRequest(url: URL(string: "http://cong.panda.tv")!) webView.loadRequest(request) } } extension SmallShowVC: UIWebViewDelegate{ // 因为点击WebView上的播放按钮,会跳转其他页面, 这里禁止跳转 func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool { if request.description.contains("https://m.panda.tv/room.html") { return false } else { return true } } }
apache-2.0
00213a33d6e11aa92e84f39748277fac
41.536585
547
0.730505
3.726496
false
false
false
false
svanimpe/around-the-table
Sources/AroundTheTable/Persistence/GameRepository.swift
1
5470
import Foundation import LoggerAPI import SwiftyRequest /** Persistence methods related to games. */ extension Persistence { /** Queries BoardGameGeek for games that match a query. - Returns: IDs of games that match the query. */ func games(forQuery query: String, exactMatchesOnly: Bool, callback: @escaping ([Int]) -> Void) { let request = RestRequest(url: "https://boardgamegeek.com/xmlapi2/search") request.responseData(queryItems: [ URLQueryItem(name: "type", value: "boardgame"), URLQueryItem(name: "exact", value: exactMatchesOnly ? "1" : "0"), URLQueryItem(name: "query", value: query) ]) { response in guard case .success(let data) = response.result, let xml = try? XMLDocument(data: data, options: []) else { Log.warning("No valid XML data returned for query \(query).") return callback([]) } do { guard let totalString = try xml.nodes(forXPath: "/items/@total").first?.stringValue, let total = Int(totalString), total > 0 else { return callback([]) } let results: [Int] = try xml.nodes(forXPath: "/items/item/@id").compactMap { guard let id = $0.stringValue else { return nil } return Int(id) } callback(results) } catch { Log.warning("Failed to parse XML for query \(query).") callback([]) } } } /** Looks up game data on BoardGameGeek. Performs an aggregate request and offers better performance compared to multiple `game(forID:)` calls. - Returns: Games for the given IDs. Cached results are returned when available. Games that have missing or invalid data are excluded. */ func games(forIDs ids: [Int], callback: @escaping ([Game]) -> Void) throws { guard !ids.isEmpty else { return callback([]) } // First check which games are in the cache. let cachedIDs = try ids.filter { try games.count(["_id": $0], limitedTo: 1) == 1 } let cachedGames = try games.find(["_id": ["$in": cachedIDs]]).compactMap(Game.init) // Then fetch the remaining ones. let newIDs = ids.filter { !cachedIDs.contains($0) } let joinedIDs = newIDs.map { String($0) }.joined(separator: ",") let request = RestRequest(url: "https://boardgamegeek.com/xmlapi2/thing") request.responseData(queryItems: [URLQueryItem(name: "id", value: joinedIDs)]) { response in guard case .success(let data) = response.result, let xml = try? XMLDocument(data: data, options: []) else { Log.warning("No valid XML data returned for IDs \(joinedIDs).") return callback(cachedGames) } do { // Note that the try? in the following statement is important. // We don't want to throw an error if a node has missing or invalid data. // Instead, we simply exlude it from the results. let results = try xml.nodes(forXPath: "/items/item").compactMap { try? Game(xml: $0) } // Cache the new games. try self.games.insert(contentsOf: results.map { $0.document }) callback(cachedGames + results) } catch { Log.warning("Failed to parse XML for IDs \(joinedIDs).") callback(cachedGames) } } } /** Looks up game data on BoardGameGeek. - Returns: The game with the given ID. A cached result is returned when available. Returns `nil` if there is no game with this ID or if the game has missing or invalid data. */ func game(forID id: Int, callback: @escaping (Game?) -> Void) throws { // First check if the game is in the cache. if let game = try games.findOne(["_id": id]).map(Game.init) { return callback(game) } // If not, fetch it. let request = RestRequest(url: "https://boardgamegeek.com/xmlapi2/thing") request.responseData(queryItems: [URLQueryItem(name: "id", value: "\(id)")]) { response in guard case .success(let data) = response.result, let xml = try? XMLDocument(data: data, options: []) else { Log.warning("No valid XML data returned for ID \(id).") return callback(nil) } do { // Note that the try? in the following statement is important. // We don't want to throw an error if the node has missing or invalid data. // Instead, we simply return nil. guard let node = try xml.nodes(forXPath: "/items/item[@id='\(id)']").first, let game = try? Game(xml: node) else { return callback(nil) } // Cache the new game. try self.games.insert(game.document) callback(game) } catch { Log.warning("Failed to parse XML for ID \(id).") callback(nil) } } } }
bsd-2-clause
79dd17599036a7b63985c88b6ee360c1
42.412698
107
0.537477
4.671221
false
false
false
false
mirego/PinLayout
Tests/Common/WrapContentSpec.swift
1
22083
// Copyright (c) 2018 Luc Dion // 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 Quick import Nimble import PinLayout class WrapContentSpec: QuickSpec { override func spec() { var viewController: PViewController! var rootView: BasicView! /* root | - aView | | | |- aViewChild |- aViewChild2 |- aViewChild3 */ var aView: BasicView! var aViewChild: BasicView! var aViewChild2: BasicView! var aViewChild3: BasicView! beforeEach { _pinlayoutSetUnitTest(scale: 2) Pin.lastWarningText = nil viewController = PViewController() viewController.view = BasicView() rootView = BasicView() viewController.view.addSubview(rootView) aView = BasicView() aView.sizeThatFitsExpectedArea = 40 * 40 rootView.addSubview(aView) aViewChild = BasicView() aView.addSubview(aViewChild) aViewChild2 = BasicView() aView.addSubview(aViewChild2) aViewChild3 = BasicView() aView.addSubview(aViewChild3) rootView.frame = CGRect(x: 0, y: 100, width: 400, height: 400) } afterEach { _pinlayoutSetUnitTest(scale: nil) } describe("wrapContent") { it("wrap and update subviews position") { aView.frame = CGRect(x: 20, y: 10, width: 200, height: 100) aViewChild.frame = CGRect(x: 160, y: 120, width: 100, height: 40) aViewChild2.frame = CGRect(x: 260, y: 120, width: 60, height: 60) aViewChild3.frame = CGRect(x: 360, y: 120, width: 60, height: 60) aView.pin.wrapContent() expect(aView.frame).to(equal(CGRect(x: 20.0, y: 10.0, width: 260.0, height: 60.0))) expect(aViewChild.frame).to(equal(CGRect(x: 0.0, y: 0.0, width: 100.0, height: 40.0))) expect(aViewChild2.frame).to(equal(CGRect(x: 100.0, y: 0.0, width: 60.0, height: 60.0))) expect(aViewChild3.frame).to(equal(CGRect(x: 200.0, y: 0.0, width: 60.0, height: 60.0))) } it("wrapContent(.all) should have the same result") { aView.frame = CGRect(x: 20, y: 10, width: 200, height: 100) aViewChild.frame = CGRect(x: 160, y: 120, width: 100, height: 40) aViewChild2.frame = CGRect(x: 260, y: 120, width: 60, height: 60) aViewChild3.frame = CGRect(x: 360, y: 120, width: 60, height: 60) aView.pin.wrapContent(.all) expect(aView.frame).to(equal(CGRect(x: 20.0, y: 10.0, width: 260.0, height: 60.0))) expect(aViewChild.frame).to(equal(CGRect(x: 0.0, y: 0.0, width: 100.0, height: 40.0))) expect(aViewChild2.frame).to(equal(CGRect(x: 100.0, y: 0.0, width: 60.0, height: 60.0))) expect(aViewChild3.frame).to(equal(CGRect(x: 200.0, y: 0.0, width: 60.0, height: 60.0))) } it("wrapContent(.width) + wrapContent(.height) should have the same result") { aView.frame = CGRect(x: 20, y: 10, width: 200, height: 100) aViewChild.frame = CGRect(x: 160, y: 120, width: 100, height: 40) aViewChild2.frame = CGRect(x: 260, y: 120, width: 60, height: 60) aViewChild3.frame = CGRect(x: 360, y: 120, width: 60, height: 60) aView.pin.wrapContent(.horizontally) aView.pin.wrapContent(.vertically) expect(aView.frame).to(equal(CGRect(x: 20.0, y: 10.0, width: 260.0, height: 60.0))) expect(aViewChild.frame).to(equal(CGRect(x: 0.0, y: 0.0, width: 100.0, height: 40.0))) expect(aViewChild2.frame).to(equal(CGRect(x: 100.0, y: 0.0, width: 60.0, height: 60.0))) expect(aViewChild3.frame).to(equal(CGRect(x: 200.0, y: 0.0, width: 60.0, height: 60.0))) } it("wrapContent(.all) and update subviews position") { aView.frame = CGRect(x: 20, y: 10, width: 200, height: 100) aViewChild.frame = CGRect(x: 160, y: 120, width: 100, height: 40) aViewChild2.frame = CGRect(x: 260, y: 120, width: 60, height: 60) aViewChild3.frame = CGRect(x: 360, y: 120, width: 60, height: 60) aView.pin.wrapContent(.all) expect(aView.frame).to(equal(CGRect(x: 20.0, y: 10.0, width: 260.0, height: 60.0))) expect(aViewChild.frame).to(equal(CGRect(x: 0.0, y: 0.0, width: 100.0, height: 40.0))) expect(aViewChild2.frame).to(equal(CGRect(x: 100.0, y: 0.0, width: 60.0, height: 60.0))) expect(aViewChild3.frame).to(equal(CGRect(x: 200.0, y: 0.0, width: 60.0, height: 60.0))) } it("wrapContent(.width) and update subviews position") { aView.frame = CGRect(x: 20, y: 10, width: 200, height: 100) aViewChild.frame = CGRect(x: 160, y: 120, width: 100, height: 40) aViewChild2.frame = CGRect(x: 260, y: 120, width: 60, height: 60) aViewChild3.frame = CGRect(x: 360, y: 120, width: 60, height: 60) aView.pin.wrapContent(.horizontally) expect(aView.frame).to(equal(CGRect(x: 20.0, y: 10.0, width: 260.0, height: 100.0))) expect(aViewChild.frame).to(equal(CGRect(x: 0.0, y: 120.0, width: 100.0, height: 40.0))) expect(aViewChild2.frame).to(equal(CGRect(x: 100.0, y: 120.0, width: 60.0, height: 60.0))) expect(aViewChild3.frame).to(equal(CGRect(x: 200.0, y: 120.0, width: 60.0, height: 60.0))) } it("wrapContent(.height) and update subviews position") { aView.frame = CGRect(x: 20, y: 10, width: 200, height: 100) aViewChild.frame = CGRect(x: 160, y: 120, width: 100, height: 40) aViewChild2.frame = CGRect(x: 260, y: 120, width: 60, height: 60) aViewChild3.frame = CGRect(x: 360, y: 120, width: 60, height: 60) aView.pin.wrapContent(.vertically) expect(aView.frame).to(equal(CGRect(x: 20.0, y: 10.0, width: 200.0, height: 60.0))) expect(aViewChild.frame).to(equal(CGRect(x: 160.0, y: 0.0, width: 100.0, height: 40.0))) expect(aViewChild2.frame).to(equal(CGRect(x: 260.0, y: 0.0, width: 60.0, height: 60.0))) expect(aViewChild3.frame).to(equal(CGRect(x: 360.0, y: 0.0, width: 60.0, height: 60.0))) } it("wrap and update subviews position") { aView.frame = CGRect(x: 20, y: 10, width: 200, height: 100) aViewChild.frame = CGRect(x: 160, y: 120, width: 100, height: 40) aViewChild2.frame = CGRect(x: 180, y: 140, width: 60, height: 60) aViewChild3.frame = CGRect(x: 220, y: 180, width: 60, height: 60) aView.pin.wrapContent() expect(aView.frame).to(equal(CGRect(x: 20.0, y: 10.0, width: 120.0, height: 120.0))) expect(aViewChild.frame).to(equal(CGRect(x: 0.0, y: 0.0, width: 100.0, height: 40.0))) expect(aViewChild2.frame).to(equal(CGRect(x: 20.0, y: 20.0, width: 60.0, height: 60.0))) expect(aViewChild3.frame).to(equal(CGRect(x: 60.0, y: 60.0, width: 60.0, height: 60.0))) } it("wrap when views are of size zero") { aView.frame = CGRect(x: 20, y: 10, width: 200, height: 100) aViewChild.frame = CGRect(x: 160, y: 120, width: 0, height: 0) aViewChild2.frame = CGRect(x: 180, y: 140, width: 0, height: 0) aViewChild3.frame = CGRect(x: 220, y: 180, width: 0, height: 0) aView.pin.wrapContent() expect(aView.frame).to(equal(CGRect(x: 20.0, y: 10.0, width: 60.0, height: 60.0))) expect(aViewChild.frame).to(equal(CGRect(x: 0.0, y: 0.0, width: 0.0, height: 0.0))) expect(aViewChild2.frame).to(equal(CGRect(x: 20.0, y: 20.0, width: 0.0, height: 0.0))) expect(aViewChild3.frame).to(equal(CGRect(x: 60.0, y: 60.0, width: 0.0, height: 0.0))) } it("wrap with subviews with negative position") { aView.frame = CGRect(x: 20, y: 10, width: 200, height: 100) aViewChild.frame = CGRect(x: -40, y: -40, width: 100, height: 40) aViewChild2.frame = CGRect(x: 350, y: 120, width: 60, height: 60) aViewChild3.frame = CGRect(x: 350, y: -100, width: 60, height: 60) aView.pin.wrapContent() expect(aView.frame).to(equal(CGRect(x: 20.0, y: 10.0, width: 450.0, height: 280.0))) expect(aViewChild.frame).to(equal(CGRect(x: 0.0, y: 60.0, width: 100.0, height: 40.0))) expect(aViewChild2.frame).to(equal(CGRect(x: 390.0, y: 220.0, width: 60.0, height: 60.0))) expect(aViewChild3.frame).to(equal(CGRect(x: 390.0, y: 0.0, width: 60.0, height: 60.0))) } } describe("wrapContent with padding") { it("wrap and update subviews position") { aView.frame = CGRect(x: 20, y: 10, width: 200, height: 100) aViewChild.frame = CGRect(x: 160, y: 120, width: 100, height: 40) aViewChild2.frame = CGRect(x: 260, y: 120, width: 60, height: 60) aViewChild3.frame = CGRect(x: 360, y: 120, width: 60, height: 60) aView.pin.wrapContent(padding: 10) expect(aView.frame).to(equal(CGRect(x: 20.0, y: 10.0, width: 280.0, height: 80.0))) expect(aViewChild.frame).to(equal(CGRect(x: 10.0, y: 10.0, width: 100.0, height: 40.0))) expect(aViewChild2.frame).to(equal(CGRect(x: 110.0, y: 10.0, width: 60.0, height: 60.0))) expect(aViewChild3.frame).to(equal(CGRect(x: 210.0, y: 10.0, width: 60.0, height: 60.0))) } it("wrap and update subviews position + center") { aView.frame = CGRect(x: 20, y: 10, width: 200, height: 100) aViewChild.frame = CGRect(x: 160, y: 120, width: 100, height: 40) aViewChild2.frame = CGRect(x: 260, y: 120, width: 60, height: 60) aViewChild3.frame = CGRect(x: 360, y: 120, width: 60, height: 60) aView.pin.wrapContent(padding: 10).center() expect(aView.frame).to(equal(CGRect(x: 60.0, y: 160.0, width: 280.0, height: 80.0))) expect(aViewChild.frame).to(equal(CGRect(x: 10.0, y: 10.0, width: 100.0, height: 40.0))) expect(aViewChild2.frame).to(equal(CGRect(x: 110.0, y: 10.0, width: 60.0, height: 60.0))) expect(aViewChild3.frame).to(equal(CGRect(x: 210.0, y: 10.0, width: 60.0, height: 60.0))) } it("wrap horizontally + padding") { aView.frame = CGRect(x: 20, y: 10, width: 200, height: 100) aViewChild.frame = CGRect(x: 160, y: 120, width: 100, height: 40) aViewChild2.frame = CGRect(x: 260, y: 120, width: 60, height: 60) aViewChild3.frame = CGRect(x: 360, y: 120, width: 60, height: 60) aView.pin.wrapContent(.horizontally, padding: 10) expect(aView.frame).to(equal(CGRect(x: 20.0, y: 10.0, width: 280.0, height: 100.0))) expect(aViewChild.frame).to(equal(CGRect(x: 10.0, y: 120.0, width: 100.0, height: 40.0))) expect(aViewChild2.frame).to(equal(CGRect(x: 110.0, y: 120.0, width: 60.0, height: 60.0))) expect(aViewChild3.frame).to(equal(CGRect(x: 210.0, y: 120.0, width: 60.0, height: 60.0))) } it("wrap vertically + padding") { aView.frame = CGRect(x: 20, y: 10, width: 200, height: 100) aViewChild.frame = CGRect(x: 160, y: 120, width: 100, height: 40) aViewChild2.frame = CGRect(x: 260, y: 120, width: 60, height: 60) aViewChild3.frame = CGRect(x: 360, y: 140, width: 60, height: 60) aView.pin.wrapContent(.vertically, padding: 10) expect(aView.frame).to(equal(CGRect(x: 20.0, y: 10.0, width: 200.0, height: 100.0))) expect(aViewChild.frame).to(equal(CGRect(x: 160.0, y: 10.0, width: 100.0, height: 40.0))) expect(aViewChild2.frame).to(equal(CGRect(x: 260.0, y: 10.0, width: 60.0, height: 60.0))) expect(aViewChild3.frame).to(equal(CGRect(x: 360.0, y: 30.0, width: 60.0, height: 60.0))) } it("wrap horizontally + negative padding") { aView.frame = CGRect(x: 20, y: 10, width: 200, height: 100) aViewChild.frame = CGRect(x: 160, y: 120, width: 100, height: 40) aViewChild2.frame = CGRect(x: 260, y: 120, width: 60, height: 60) aViewChild3.frame = CGRect(x: 360, y: 160, width: 60, height: 60) aView.pin.wrapContent(.horizontally, padding: -10) expect(aView.frame).to(equal(CGRect(x: 20.0, y: 10.0, width: 240.0, height: 100.0))) expect(aViewChild.frame).to(equal(CGRect(x: -10.0, y: 120.0, width: 100.0, height: 40.0))) expect(aViewChild2.frame).to(equal(CGRect(x: 90.0, y: 120.0, width: 60.0, height: 60.0))) expect(aViewChild3.frame).to(equal(CGRect(x: 190.0, y: 160.0, width: 60.0, height: 60.0))) } it("wrap vertically + negative padding") { aView.frame = CGRect(x: 20, y: 10, width: 200, height: 100) aViewChild.frame = CGRect(x: 160, y: 120, width: 100, height: 40) aViewChild2.frame = CGRect(x: 260, y: 120, width: 60, height: 60) aViewChild3.frame = CGRect(x: 360, y: 160, width: 60, height: 60) aView.pin.wrapContent(.vertically, padding: -10) expect(aView.frame).to(equal(CGRect(x: 20.0, y: 10.0, width: 200.0, height: 80.0))) expect(aViewChild.frame).to(equal(CGRect(x: 160.0, y: -10.0, width: 100.0, height: 40.0))) expect(aViewChild2.frame).to(equal(CGRect(x: 260.0, y: -10.0, width: 60.0, height: 60.0))) expect(aViewChild3.frame).to(equal(CGRect(x: 360.0, y: 30.0, width: 60.0, height: 60.0))) } it("wrap all + padding UIEdgeInsets") { aView.frame = CGRect(x: 20, y: 10, width: 200, height: 100) aViewChild.frame = CGRect(x: 160, y: 120, width: 100, height: 40) aViewChild2.frame = CGRect(x: 260, y: 120, width: 60, height: 60) aViewChild3.frame = CGRect(x: 360, y: 140, width: 60, height: 60) aView.pin.wrapContent(padding: PEdgeInsets(top: 10, left: 20, bottom: 30, right: 40)) expect(aView.frame).to(equal(CGRect(x: 20.0, y: 10.0, width: 320.0, height: 120.0))) expect(aViewChild.frame).to(equal(CGRect(x: 20.0, y: 10.0, width: 100.0, height: 40.0))) expect(aViewChild2.frame).to(equal(CGRect(x: 120.0, y: 10.0, width: 60.0, height: 60.0))) expect(aViewChild3.frame).to(equal(CGRect(x: 220.0, y: 30.0, width: 60.0, height: 60.0))) } it("wrap all + padding UIEdgeInsets") { aView.frame = CGRect(x: 20, y: 10, width: 200, height: 100) aViewChild.frame = CGRect(x: 160, y: 120, width: 100, height: 40) aViewChild2.frame = CGRect(x: 260, y: 120, width: 60, height: 60) aViewChild3.frame = CGRect(x: 360, y: 140, width: 60, height: 60) aView.pin.wrapContent(.all, padding: PEdgeInsets(top: 10, left: 20, bottom: 30, right: 40)) expect(aView.frame).to(equal(CGRect(x: 20.0, y: 10.0, width: 320.0, height: 120.0))) expect(aViewChild.frame).to(equal(CGRect(x: 20.0, y: 10.0, width: 100.0, height: 40.0))) expect(aViewChild2.frame).to(equal(CGRect(x: 120.0, y: 10.0, width: 60.0, height: 60.0))) expect(aViewChild3.frame).to(equal(CGRect(x: 220.0, y: 30.0, width: 60.0, height: 60.0))) } it("wrap horizontally + padding PEdgeInsets") { aView.frame = CGRect(x: 20, y: 10, width: 200, height: 100) aViewChild.frame = CGRect(x: 160, y: 120, width: 100, height: 40) aViewChild2.frame = CGRect(x: 260, y: 120, width: 60, height: 60) aViewChild3.frame = CGRect(x: 360, y: 140, width: 60, height: 60) aView.pin.wrapContent(.horizontally, padding: PEdgeInsets(top: 10, left: 20, bottom: 30, right: 40)) expect(aView.frame).to(equal(CGRect(x: 20.0, y: 10.0, width: 320.0, height: 100.0))) expect(aViewChild.frame).to(equal(CGRect(x: 20.0, y: 120.0, width: 100.0, height: 40.0))) expect(aViewChild2.frame).to(equal(CGRect(x: 120.0, y: 120.0, width: 60.0, height: 60.0))) expect(aViewChild3.frame).to(equal(CGRect(x: 220.0, y: 140.0, width: 60.0, height: 60.0))) } it("wrap vertically + padding PEdgeInsets") { aView.frame = CGRect(x: 20, y: 10, width: 200, height: 100) aViewChild.frame = CGRect(x: 160, y: 120, width: 100, height: 40) aViewChild2.frame = CGRect(x: 260, y: 120, width: 60, height: 60) aViewChild3.frame = CGRect(x: 360, y: 140, width: 60, height: 60) aView.pin.wrapContent(.vertically, padding: PEdgeInsets(top: 10, left: 20, bottom: 30, right: 40)) expect(aView.frame).to(equal(CGRect(x: 20.0, y: 10.0, width: 200.0, height: 120.0))) expect(aViewChild.frame).to(equal(CGRect(x: 160.0, y: 10.0, width: 100.0, height: 40.0))) expect(aViewChild2.frame).to(equal(CGRect(x: 260.0, y: 10.0, width: 60.0, height: 60.0))) expect(aViewChild3.frame).to(equal(CGRect(x: 360.0, y: 30.0, width: 60.0, height: 60.0))) } it("wrap all + negative padding PEdgeInsets") { aView.frame = CGRect(x: 20, y: 10, width: 200, height: 100) aViewChild.frame = CGRect(x: 160, y: 120, width: 100, height: 40) aViewChild2.frame = CGRect(x: 260, y: 120, width: 60, height: 60) aViewChild3.frame = CGRect(x: 360, y: 140, width: 60, height: 60) aView.pin.wrapContent(.all, padding: PEdgeInsets(top: -10, left: -20, bottom: -30, right: -40)) expect(aView.frame).to(equal(CGRect(x: 20.0, y: 10.0, width: 200.0, height: 40.0))) expect(aViewChild.frame).to(equal(CGRect(x: -20.0, y: -10.0, width: 100.0, height: 40.0))) expect(aViewChild2.frame).to(equal(CGRect(x: 80.0, y: -10.0, width: 60.0, height: 60.0))) expect(aViewChild3.frame).to(equal(CGRect(x: 180.0, y: 10.0, width: 60.0, height: 60.0))) } } describe("wrapContent + min/max") { it("wrap all + maxWidth + maxHeight") { aView.frame = CGRect(x: 20, y: 10, width: 200, height: 100) aViewChild.frame = CGRect(x: 160, y: 120, width: 100, height: 40) aViewChild2.frame = CGRect(x: 260, y: 130, width: 60, height: 60) aViewChild3.frame = CGRect(x: 360, y: 140, width: 60, height: 60) aView.pin.wrapContent().maxWidth(200).maxHeight(50) expect(aView.frame).to(equal(CGRect(x: 20.0, y: 10.0, width: 200.0, height: 50.0))) expect(aViewChild.frame).to(equal(CGRect(x: 0.0, y: 0.0, width: 100.0, height: 40.0))) expect(aViewChild2.frame).to(equal(CGRect(x: 100.0, y: 10.0, width: 60.0, height: 60.0))) expect(aViewChild3.frame).to(equal(CGRect(x: 200.0, y: 20.0, width: 60.0, height: 60.0))) } it("wrap all + minWidth + minHeight") { aView.frame = CGRect(x: 20, y: 10, width: 200, height: 100) aViewChild.frame = CGRect(x: 160, y: 120, width: 100, height: 40) aViewChild2.frame = CGRect(x: 260, y: 130, width: 60, height: 60) aViewChild3.frame = CGRect(x: 360, y: 140, width: 60, height: 60) aView.pin.wrapContent().minWidth(300).minHeight(100) expect(aView.frame).to(equal(CGRect(x: 20.0, y: 10.0, width: 300.0, height: 100.0))) expect(aViewChild.frame).to(equal(CGRect(x: 0.0, y: 0.0, width: 100.0, height: 40.0))) expect(aViewChild2.frame).to(equal(CGRect(x: 100.0, y: 10.0, width: 60.0, height: 60.0))) expect(aViewChild3.frame).to(equal(CGRect(x: 200.0, y: 20.0, width: 60.0, height: 60.0))) } } } }
mit
7000e494969f6c3cadda3b40d642a492
57.575597
116
0.556129
3.286161
false
false
false
false
noremac/Layout
Sources/Layout/Constraints/ConstrainableItem.swift
1
3897
import UIKit /// This protocol defines an item that constraints can be applied to. /// - Note: Only `UIView` and `UILayoutGuide` should implement this protocol. public protocol ConstrainableItem: AnyObject { /// - Returns: The `UIView`'s `superview` or the `UILayoutGuide`'s /// `owningView`. var parentView: UIView? { get } /// Sets `translatesAutoresizingMaskIntoConstraints` to `false` for /// `UIView`s. It does nothing for `UILayoutGuide`s. func setTranslatesAutoresizingMaskIntoConstraintsFalseIfNecessary() } public extension ConstrainableItem { @inlinable func makeConstraints(groups: [MultipleConstraintGenerator]) -> [NSLayoutConstraint] { setTranslatesAutoresizingMaskIntoConstraintsFalseIfNecessary() let constraints = groups.reduce(into: [NSLayoutConstraint]()) { acc, generator in generator.insertConstraints(withItem: self, into: &acc) } if let container = _globalConstraintContainer { container.addConstraints(constraints) } return constraints } /// Creates and returns an array of `NSLayoutConstraint`s corresponding to /// the given groups. /// /// - Parameter groups: The groups of constraints you'd like. /// - Returns: The `NSLayoutConstraint`s corresponding to the given /// `ConstraintGroup`s. /// /// - Note: This method will call /// `setTranslatesAutoresizingMaskIntoConstraintsFalseIfNecessary()` on /// the receiver automatically. @inlinable @discardableResult func makeConstraints(@ArrayBuilder <MultipleConstraintGenerator> _ groups: () -> [MultipleConstraintGenerator]) -> [NSLayoutConstraint] { makeConstraints(groups: groups()) } /// Creates, immediately activates, and returns an array of /// `NSLayoutConstraint`s corresponding to the given groups. /// /// - Parameter groups: The groups of constraints you'd like. /// - Returns: The `NSLayoutConstraint`s corresponding to the given /// `ConstraintGroup`s. /// /// - Note: This method will call /// `setTranslatesAutoresizingMaskIntoConstraintsFalseIfNecessary()` on /// the receiver automatically. @inlinable @discardableResult func applyConstraints(file: StaticString = #file, line: UInt = #line, @ArrayBuilder <MultipleConstraintGenerator> _ groups: () -> [MultipleConstraintGenerator]) -> [NSLayoutConstraint] { guard _globalConstraintContainer == nil else { FatalError.crash("Call makeConstraints, not applyConstraints, when configurationg a DynamicLayout.", file: file, line: line) return [] } let constraints = makeConstraints(groups: groups()) constraints.activate() return constraints } } // MARK: - Implementations extension UIView: ConstrainableItem { /// Returns the receiver's `superview`. public var parentView: UIView? { superview } /// Sets `translatesAutoresizingMaskIntoConstraints` to `false` on the /// receiver. public func setTranslatesAutoresizingMaskIntoConstraintsFalseIfNecessary() { translatesAutoresizingMaskIntoConstraints = false } } extension UILayoutGuide: ConstrainableItem { /// Returns the receiver's `owningView`. public var parentView: UIView? { owningView } /// This does nothing on `UILayoutGuide`s. public func setTranslatesAutoresizingMaskIntoConstraintsFalseIfNecessary() {} } // MARK: Internal private var constrainableItemToItemKey: UInt8 = 0 extension ConstrainableItem { var toItem: ConstrainableItem? { get { objc_getAssociatedObject(self, &constrainableItemToItemKey) as? ConstrainableItem } set { objc_setAssociatedObject(self, &constrainableItemToItemKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } }
mit
293dcef6782340ff452db5cabedf63e2
36.114286
190
0.692071
5.259109
false
false
false
false
DenHeadless/DTTableViewManager
Sources/DTTableViewManager/DTTableViewDragDelegate.swift
1
5355
// // DTTableViewDragDelegate.swift // DTTableViewManager // // Created by Denys Telezhkin on 20.08.17. // Copyright © 2017 Denys Telezhkin. 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 import DTModelStorage #if os(iOS) /// Object, that implements `UITableViewDragDelegate` methods for `DTTableViewManager`. open class DTTableViewDragDelegate: DTTableViewDelegateWrapper, UITableViewDragDelegate { /// Implementation for `UITableViewDragDelegate` protocol open func tableView(_ tableView: UITableView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] { if let items = perform4ArgumentCellReaction(.itemsForBeginningDragSession, argument: session, location: indexPath, provideCell: true) as? [UIDragItem] { return items } return (delegate as? UITableViewDragDelegate)?.tableView(tableView, itemsForBeginning: session, at:indexPath) ?? [] } /// Implementation for `UITableViewDragDelegate` protocol open func tableView(_ tableView: UITableView, itemsForAddingTo session: UIDragSession, at indexPath: IndexPath, point: CGPoint) -> [UIDragItem] { if let items = perform5ArgumentCellReaction(.itemsForAddingToDragSession, argumentOne: session, argumentTwo: point, location: indexPath, provideCell: true) as? [UIDragItem] { return items } return (delegate as? UITableViewDragDelegate)?.tableView?(tableView, itemsForAddingTo: session, at: indexPath, point: point) ?? [] } /// Implementation for `UITableViewDragDelegate` protocol open func tableView(_ tableView: UITableView, dragPreviewParametersForRowAt indexPath: IndexPath) -> UIDragPreviewParameters? { if let reaction = cellReaction(.dragPreviewParametersForRowAtIndexPath, location: indexPath) { return performNillableCellReaction(reaction, location: indexPath, provideCell: true) as? UIDragPreviewParameters } return (delegate as? UITableViewDragDelegate)?.tableView?(tableView, dragPreviewParametersForRowAt: indexPath) } /// Implementation for `UITableViewDragDelegate` protocol open func tableView(_ tableView: UITableView, dragSessionWillBegin session: UIDragSession) { _ = performNonCellReaction(.dragSessionWillBegin, argument: session) (delegate as? UITableViewDragDelegate)?.tableView?(tableView, dragSessionWillBegin: session) } /// Implementation for `UITableViewDragDelegate` protocol open func tableView(_ tableView: UITableView, dragSessionDidEnd session: UIDragSession) { _ = performNonCellReaction(.dragSessionDidEnd, argument: session) (delegate as? UITableViewDragDelegate)?.tableView?(tableView, dragSessionDidEnd: session) } /// Implementation for `UITableViewDragDelegate` protocol open func tableView(_ tableView: UITableView, dragSessionAllowsMoveOperation session: UIDragSession) -> Bool { if let allows = performNonCellReaction(.dragSessionAllowsMoveOperation, argument: session) as? Bool { return allows } return (delegate as? UITableViewDragDelegate)?.tableView?(tableView, dragSessionAllowsMoveOperation: session) ?? true } /// Implementation for `UITableViewDragDelegate` protocol open func tableView(_ tableView: UITableView, dragSessionIsRestrictedToDraggingApplication session: UIDragSession) -> Bool { if let allows = performNonCellReaction(.dragSessionIsRestrictedToDraggingApplication, argument: session) as? Bool { return allows } return (delegate as? UITableViewDragDelegate)?.tableView?(tableView, dragSessionIsRestrictedToDraggingApplication: session) ?? false } override func delegateWasReset() { tableView?.dragDelegate = nil tableView?.dragDelegate = self } } #endif
mit
19eb675a2b87c97944b956bdda2761b7
50.480769
140
0.684535
5.67161
false
false
false
false
crewshin/GasLog
GasLogger/Controllers/EntriesViewController.swift
1
18999
// // EntriesViewController.swift // GasLogger // // Created by Gene Crucean on 1/3/16. // Copyright © 2016 Dagger Dev. All rights reserved. // import UIKit import RealmSwift import CoreLocation import Material import DZNEmptyDataSet class EntriesViewController: BaseViewController, CLLocationManagerDelegate, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate, TextFieldDelegate, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var dateTextField: TextField! @IBOutlet weak var odometerTextField: TextField! @IBOutlet weak var gallonsTextField: TextField! @IBOutlet weak var priceTextField: TextField! @IBOutlet weak var currentVehicleLabel: UILabel! let locationManager = CLLocationManager() var date = NSDate() var lat = 0.0 var lon = 0.0 var gpsQueryLimit = 0 var entries = [Entry]() override func viewDidLoad() { super.viewDidLoad() NSNotificationCenter.defaultCenter().addObserver(self, selector: "loadVehicleData", name: CONSTANTS.NOTI.ENTRY_ADDED, object: nil) tableView.estimatedRowHeight = 23.0 tableView.rowHeight = UITableViewAutomaticDimension // Set current date into UI. This is just a starting point... which is... now. dateTextField.text = updateDateInUI(NSDate()) // Get rid of cell separators. tableView.tableFooterView = UIView() // Basic ui settings. setupTextFields() // Test if any vehicles exist in DB. If not, prompt user to enter one. // if !vehiclesExist() // { // let noti = UIAlertController(title: nil, message: "You haven't added any vehicles yet. Please tap the menu button in the top left to add your whip.", preferredStyle: .Alert) // let okAction = UIAlertAction(title: "Ok", style: .Default, handler: { (action) -> Void in // // }) // // noti.addAction(okAction) // // self.presentViewController(noti, animated: true, completion: nil) // } if CLLocationManager.locationServicesEnabled() { // Ask for GPS Auth. locationManager.requestAlwaysAuthorization() // For use in foreground. locationManager.requestWhenInUseAuthorization() } } override func viewWillAppear(animated: Bool) { super.viewWillAppear(true) self.navigationController?.hidesBarsOnTap = false loadVehicleData() reloadTable() if CLLocationManager.locationServicesEnabled() { locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.startUpdatingLocation() } if let vehicleName = NSUserDefaults.standardUserDefaults().objectForKey(CONSTANTS.NSUSERDEFAULTS.CURRENTLY_SELECTED_VEHICLE_NAME) as? String { currentVehicleLabel.text = vehicleName } } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(true) if CLLocationManager.locationServicesEnabled() { locationManager.stopUpdatingLocation() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ // MARK: - Methods @IBAction func addNewEntryButton(sender: AnyObject) { addNewEntry() } func addNewEntry() { if let currentVehicleName = NSUserDefaults.standardUserDefaults().objectForKey(CONSTANTS.NSUSERDEFAULTS.CURRENTLY_SELECTED_VEHICLE_NAME) as? String { if let vehicle = try! Realm().objects(Vehicle).filter("name == '\(currentVehicleName)'").first { if let mileage = odometerTextField.text, gallons = gallonsTextField.text, price = priceTextField.text { if mileage != "" && gallons != "" && price != "" { RealmManager.addEntryToVehicle(vehicle, date: date, mileage: Int(mileage)!, gallons: Double(gallons)!, price: Double(price)!, lat: lat, lon: lon) dateTextField.text = updateDateInUI(NSDate()) odometerTextField.text = "" gallonsTextField.text = "" priceTextField.text = "" } } else { warnUserNoti() } } else // Initial setup of vehicle. { if let mileage = odometerTextField.text, gallons = gallonsTextField.text, price = priceTextField.text { if mileage != "" && gallons != "" && price != "" { // Create vehicle first. let vehicle = Vehicle() vehicle.uuid = NSUUID().UUIDString vehicle.name = "Placeholder" RealmManager.addVehicleToDB(vehicle) RealmManager.addEntryToVehicle(vehicle, date: date, mileage: Int(mileage)!, gallons: Double(gallons)!, price: Double(price)!, lat: lat, lon: lon) dateTextField.text = updateDateInUI(NSDate()) odometerTextField.text = "" gallonsTextField.text = "" priceTextField.text = "" } } else { warnUserNoti() } } } else { let noti = UIAlertController(title: nil, message: "Please add or select a vehicle before adding an entry.", preferredStyle: .Alert) let okAction = UIAlertAction(title: "Ok", style: .Default, handler: { (action) -> Void in }) noti.addAction(okAction) self.presentViewController(noti, animated: true, completion: nil) } dateTextField.resignFirstResponder() odometerTextField.resignFirstResponder() gallonsTextField.resignFirstResponder() priceTextField.resignFirstResponder() } func vehiclesExist() -> Bool { if let vehicles = RealmManager.getAllVehicles() { if vehicles.count > 0 { return true } } return false } func warnUserNoti() { print("Please fill in all text fields.") // Notify user. let noti = UIAlertController(title: nil, message: "All fields are required before adding a new entry.", preferredStyle: .Alert) let okAction = UIAlertAction(title: "Ok", style: .Default, handler: { (action) -> Void in }) noti.addAction(okAction) self.presentViewController(noti, animated: true, completion: nil) } func reloadTable() { tableView.reloadData() } func loadVehicleData() { // Load vehicle from db. if let currentVehicleName = NSUserDefaults.standardUserDefaults().objectForKey(CONSTANTS.NSUSERDEFAULTS.CURRENTLY_SELECTED_VEHICLE_NAME) as? String { self.entries.removeAll() if let vehicle = try! Realm().objects(Vehicle).filter("name == '\(currentVehicleName)'").first { for entry in vehicle.entries.sorted("mileage", ascending: false) // Maybe change to date? { self.entries.append(entry) } } reloadTable() } } func loadVehicle(name: String) -> Vehicle? { // Load vehicle from db. if let vehicle = try! Realm().objects(Vehicle).filter("name == '\(name)'").first { return vehicle } return nil } func setupTextFields() { // Date TextField dateTextField.clearButtonMode = .WhileEditing dateTextField.font = UIFont(name: (dateTextField.font?.fontName)!, size: 16) dateTextField.textColor = StyleKit.red dateTextField.backgroundColor = UIColor.clearColor() dateTextField.titleLabel = UILabel() dateTextField.titleLabel!.font = UIFont(name: (dateTextField.font?.fontName)!, size: 12) dateTextField.titleLabelColor = UIColor.darkGrayColor() dateTextField.titleLabelActiveColor = StyleKit.white dateTextField.attributedPlaceholder = NSAttributedString(string:"Date", attributes:[NSForegroundColorAttributeName: UIColor.lightGrayColor()]) dateTextField.layer.borderWidth = 0.0 dateTextField.layer.borderColor = UIColor.clearColor().CGColor // Mileage TextField odometerTextField.clearButtonMode = .WhileEditing odometerTextField.font = UIFont(name: (odometerTextField.font?.fontName)!, size: 16) odometerTextField.textColor = StyleKit.red odometerTextField.backgroundColor = UIColor.clearColor() odometerTextField.titleLabel = UILabel() odometerTextField.titleLabel!.font = UIFont(name: (odometerTextField.font?.fontName)!, size: 12) odometerTextField.titleLabelColor = UIColor.darkGrayColor() odometerTextField.titleLabelActiveColor = StyleKit.white odometerTextField.attributedPlaceholder = NSAttributedString(string:"Mileage", attributes:[NSForegroundColorAttributeName: UIColor.lightGrayColor()]) odometerTextField.layer.borderWidth = 0.0 odometerTextField.layer.borderColor = UIColor.clearColor().CGColor // Gallons TextField gallonsTextField.clearButtonMode = .WhileEditing gallonsTextField.font = UIFont(name: (gallonsTextField.font?.fontName)!, size: 16) gallonsTextField.textColor = StyleKit.red gallonsTextField.backgroundColor = UIColor.clearColor() gallonsTextField.titleLabel = UILabel() gallonsTextField.titleLabel!.font = UIFont(name: (gallonsTextField.font?.fontName)!, size: 12) gallonsTextField.titleLabelColor = UIColor.darkGrayColor() gallonsTextField.titleLabelActiveColor = StyleKit.white gallonsTextField.attributedPlaceholder = NSAttributedString(string:"Gallons", attributes:[NSForegroundColorAttributeName: UIColor.lightGrayColor()]) gallonsTextField.layer.borderWidth = 0.0 gallonsTextField.layer.borderColor = UIColor.clearColor().CGColor // Price TextField priceTextField.clearButtonMode = .WhileEditing priceTextField.font = UIFont(name: (priceTextField.font?.fontName)!, size: 16) priceTextField.textColor = StyleKit.red priceTextField.backgroundColor = UIColor.clearColor() priceTextField.titleLabel = UILabel() priceTextField.titleLabel!.font = UIFont(name: (priceTextField.font?.fontName)!, size: 12) priceTextField.titleLabelColor = UIColor.darkGrayColor() priceTextField.titleLabelActiveColor = StyleKit.white priceTextField.attributedPlaceholder = NSAttributedString(string:"Price", attributes:[NSForegroundColorAttributeName: UIColor.lightGrayColor()]) priceTextField.layer.borderWidth = 0.0 priceTextField.layer.borderColor = UIColor.clearColor().CGColor } // MARK: - CLLocationManagerDelegate - Refactor code into LocationManager.swift asap. // Get GPS coords. func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let locValue:CLLocationCoordinate2D = manager.location!.coordinate print("locations = \(locValue.latitude) \(locValue.longitude)") if gpsQueryLimit < 5 { gpsQueryLimit = gpsQueryLimit + 1 } else { // Stop collecting gps data when all we need is a quick sample. if CLLocationManager.locationServicesEnabled() { locationManager.stopUpdatingLocation() } // Reset query. gpsQueryLimit = 0 } lat = Double(locValue.latitude) lon = Double(locValue.longitude) } // MARK: - Table view data source func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return entries.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("entryCell", forIndexPath: indexPath) as! EntryTableViewCell // Date. cell.dateLabel.text = updateDateInUI(entries[indexPath.row].date) // MPG. cell.mpgLabel.text = "\(entries[indexPath.row].mpg)" // Gallons. cell.gallonsLabel.text = "\(entries[indexPath.row].gallons.roundToPlaces(1))" // Mileage. let formatter = NSNumberFormatter() formatter.numberStyle = NSNumberFormatterStyle.DecimalStyle cell.mileageLabel.text = "\(formatter.stringFromNumber(entries[indexPath.row].mileage)!)" // Price. formatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle cell.priceLabel.text = "\(formatter.stringFromNumber(entries[indexPath.row].price)!)" // format $0.0 return cell } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 23 } // Override to support conditional editing of the table view. // func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // // Return false if you do not want the specified item to be editable. // return true // } // Delete entry from db. func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete entry from db. RealmManager.deleteEntry(entries[indexPath.row]) // Reload data in memory for display. loadVehicleData() // Remove visible row. // tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) tableView.reloadData() } } /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ // MARK: - UITextFieldDelegate func textFieldDidBeginEditing(textField: UITextField) { if textField.tag == 0 // Date. { let datePicker = UIDatePicker() datePicker.datePickerMode = .Date textField.inputView = datePicker datePicker.addTarget(self, action: "datePickerValueChanged:", forControlEvents: UIControlEvents.ValueChanged) } } func textFieldShouldReturn(textField: UITextField) -> Bool { if textField.tag == 1 { odometerTextField.becomeFirstResponder() } else if textField.tag == 2 { gallonsTextField.becomeFirstResponder() } else if textField.tag == 3 { priceTextField.becomeFirstResponder() } else if textField.tag == 4 { addNewEntry() priceTextField.resignFirstResponder() } else { textField.resignFirstResponder() } return false } func datePickerValueChanged(sender: UIDatePicker) { let formatter = NSDateFormatter() formatter.dateStyle = .ShortStyle formatter.timeStyle = .NoStyle dateTextField.text = formatter.stringFromDate(sender.date) date = sender.date } func updateDateInUI(date: NSDate) -> String { let formatter = NSDateFormatter() formatter.dateStyle = .ShortStyle formatter.timeStyle = .NoStyle return formatter.stringFromDate(date) } // MARK: - DZNEmptyTableView Delegate & DataSource. func imageForEmptyDataSet(scrollView: UIScrollView!) -> UIImage! { return StyleKit.imageOfFuelIcon } func titleForEmptyDataSet(scrollView: UIScrollView!) -> NSAttributedString! { let text = "Zero, Zip, Zilch, Nada Entries" let attribs = [ NSFontAttributeName: UIFont.boldSystemFontOfSize(18), NSForegroundColorAttributeName: UIColor.darkGrayColor() ] return NSAttributedString(string: text, attributes: attribs) } func descriptionForEmptyDataSet(scrollView: UIScrollView!) -> NSAttributedString! { let text = "There are no fuel entries added to the current vehicle. If you just installed this app, please tap the menu icon top left and add a vehicle." let para = NSMutableParagraphStyle() para.lineBreakMode = NSLineBreakMode.ByWordWrapping para.alignment = NSTextAlignment.Center let attribs = [ NSFontAttributeName: UIFont.systemFontOfSize(14), NSForegroundColorAttributeName: UIColor.lightGrayColor(), NSParagraphStyleAttributeName: para ] return NSAttributedString(string: text, attributes: attribs) } } // MARK: - Extensions. extension Double { /// Rounds the double to decimal places value func roundToPlaces(places:Int) -> Double { let divisor = pow(10.0, Double(places)) return round(self * divisor) / divisor } }
mit
45b5ca9383c0b98912fd702ce8a36119
35.746615
208
0.611696
5.530713
false
false
false
false
cocoaheadsru/server
Sources/App/Models/Place/Place.swift
1
1476
import Vapor import FluentProvider // sourcery: AutoModelGeneratable // sourcery: toJSON, Preparation final class Place: Model { let storage = Storage() // sourcery: ignoreInJSON var cityId: Identifier var title: String var address: String var description: String var latitude: Double var longitude: Double init(title: String, address: String, description: String, latitude: Double, longitude: Double, cityId: Identifier) { self.title = title self.address = address self.description = description self.latitude = latitude self.longitude = longitude self.cityId = cityId } // sourcery:inline:auto:Place.AutoModelGeneratable init(row: Row) throws { cityId = try row.get(Keys.cityId) title = try row.get(Keys.title) address = try row.get(Keys.address) description = try row.get(Keys.description) latitude = try row.get(Keys.latitude) longitude = try row.get(Keys.longitude) } func makeRow() throws -> Row { var row = Row() try row.set(Keys.cityId, cityId) try row.set(Keys.title, title) try row.set(Keys.address, address) try row.set(Keys.description, description) try row.set(Keys.latitude, latitude) try row.set(Keys.longitude, longitude) return row } // sourcery:end } extension Place { // sourcery: nestedJSONRepresentableField func city() throws -> City? { return try parent(id: cityId).get() } }
mit
070c9f17803b5b92c29861e43ea17771
23.196721
52
0.672764
3.904762
false
false
false
false
developerY/Swift2_Playgrounds
Swift2LangRef.playground/Pages/Extensions.xcplaygroundpage/Contents.swift
1
5795
//: [Previous](@previous) //: ------------------------------------------------------------------------------------------------ //: Things to know: //: //: * Similar to Objective-C categories, extensions allow you to add functionality to an existing //: type (class, struct, enumeration.) //: //: * You do not need access to the original source code to extend a type. //: //: * Extensions can be applied to built-in types as well, including String, Int, Double, etc. //: //: * With extensions, you can: //: //: o Add computed properties (including static) //: o Define instance methods and type methods //: o Provide new convenience initializers //: o Define subscripts //: o Define and use new nested types //: o Make an existing type conform to a protocol //: //: * Extensions do not support adding stored properties or property observers to a type. //: //: * Extensions apply all instances of a type, even if they were created before the extension was //: defined. //: ------------------------------------------------------------------------------------------------ //: Let's take a look at how extensions are declared. Note that, unlike Objective-C categories, //: extensions are not named: extension Int { // ... code here } //: ------------------------------------------------------------------------------------------------ //: Computed properties //: //: Computed properties are a poweful use of extensions. Below, we'll add native conversion from //: various measurements (Km, mm, feet, etc.) to the Double class. extension Double { var kmToMeters: Double { return self * 1_000.0 } var cmToMeters: Double { return self / 100.0 } var mmToMeters: Double { return self / 1_000.0 } var inchToMeters: Double { return self / 39.3701 } var ftToMeters: Double { return self / 3.28084 } } //: We can call upon Double's new computed property to convert inches to meters let oneInchInMeters = 1.inchToMeters //: Similarly, we'll convert three feet to meters let threeFeetInMeters = 3.ftToMeters //: ------------------------------------------------------------------------------------------------ //: Initializers //: //: Extensions can be used to add new convenience initializers to a class, but they cannot add //: new designated initializers. //: //: Let's see this in action: struct Size { var width = 0.0 var height = 0.0 } struct Point { var x = 0.0 var y = 0.0 } struct Rect { var origin = Point() var size = Size() } //: Since we didn't provide any initializers, we can use Swift's default memberwise initializer for //: the Rect. var memberwiseRect = Rect(origin: Point(x: 2.0, y: 2.0), size: Size(width: 5.0, height: 5.0)) //: Let's extend Rect to add a new convenience initializer. Note that we're still responsible for //: ensuring that the instance is fully initialized. extension Rect { init (center: Point, size: Size) { let originX = center.x - (size.width / 2) let originY = center.y - (size.height / 2) self.init(origin: Point(x: originX, y: originY), size: size) } } //: Let's try out our new initializer: let centerRect = Rect(center: Point(x: 4.0, y: 4.0), size: Size(width: 3.0, height: 3.0)) //: Remember that if a class has an initializer, Swift will not provide the default memberwise //: initializer. However, since we added an initializer via an Extension, we still have access //: to Swift's memberwise initializer: var anotherRect = Rect(origin: Point(x: 1.0, y: 1.0), size: Size(width: 3.0, height: 2.0)) //: ------------------------------------------------------------------------------------------------ //: Methods //: //: As you might expect, we can add methods to an existing type as well. Here's a clever little //: extention to perform a task (a closure) multiple times, equal to the value stored in the Int. //: //: Note that the integer value is stored in 'self'. extension Int { func repititions(task: () -> ()) { for i in 0..<self { task() } } } //: Let's call our new member using the shorthand syntax for trailing closures: 3.repititions { print("hello") } //: Instance methods can mutate the instance itself. //: //: Note the use of the 'mutating' keyword. extension Int { mutating func square() { self = self * self } } var someInt = 3 someInt.square() //: someInt is now 9 //: ------------------------------------------------------------------------------------------------ //: Subscripts //: //: Let's add a subscript to Int: extension Int { subscript(digitIndex: Int) -> Int { var decimalBase = 1 for _ in 0 ..< digitIndex { decimalBase *= 10 } return self / decimalBase % 10 } } //: And we can call our subscript directly on an Int, including a literal Int type: 123456789[0] 123456789[1] 123456789[2] 123456789[3] 123456789[4] 123456789[5] 123456789[6] //: ------------------------------------------------------------------------------------------------ //: Nested types //: //: We can also add nested types to an existing type: extension Character { enum Kind { case Vowel, Consonant, Other } var kind: Kind { switch String(self) { case "a", "e", "i", "o", "u": return .Vowel case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z": return .Consonant default: return .Other } } } //: Let's test out our new extension with nested types: Character("a").kind == .Vowel Character("h").kind == .Consonant Character("+").kind == .Other //: [Next](@next)
mit
b2cae99205c5dbaf81f22ef2948dbbeb
29.025907
100
0.553063
4.163075
false
false
false
false
vishalvshekkar/LineGraph
Line Chart/Line Chart/LineChart.swift
1
8596
// // LineChart.swift // Line Chart // // Created by Vishal on 10/7/15. // Copyright © 2015 Vishal. All rights reserved. // import UIKit @IBDesignable class LineChart: UIView { //MARK:- Color Properties @IBInspectable var graphBackgroundColor: UIColor = UIColor.clearColor() { didSet { self.backgroundColor = graphBackgroundColor } } @IBInspectable var startColor: UIColor = UIColor(red:25/255, green:214/255, blue:189/255, alpha:1.0) @IBInspectable var endColor: UIColor = UIColor(red:0.33, green:0.33, blue:0.33, alpha:0.3) @IBInspectable var graphLineColor: UIColor = UIColor.whiteColor() @IBInspectable var gridColor: UIColor = UIColor(red:0.24, green:0.24, blue:0.24, alpha:1) @IBInspectable var gridFontColor: UIColor = UIColor(red:0.36, green:0.36, blue:0.36, alpha:1) @IBInspectable var xLabelFontColor: UIColor = UIColor(white: 1.0, alpha: 1.0) //MARK: - Margins and Borders @IBInspectable var horizontalPadding: CGFloat = 0 @IBInspectable var leftGraphMargin: CGFloat = 20 @IBInspectable var rightGraphMargin: CGFloat { return graphPointDiameter/2 } @IBInspectable var topGraphMargin: CGFloat { return (self.frame.height - bottomGraphMargin)/10 } @IBInspectable var bottomGraphMargin: CGFloat = 40 //MARK: - Thickness and Line Widths @IBInspectable var graphPointDiameter: CGFloat = 8.0 @IBInspectable var graphLineWidth: CGFloat = 1.5 @IBInspectable var gridLineWidth: CGFloat = 1.0 @IBInspectable var graphIndicatorFont: UIFont = UIFont.systemFontOfSize(10.0) @IBInspectable var graphXLabelFont: UIFont = UIFont.systemFontOfSize(12) var dataPoints: [LineGraphDataPoint] = defaultDataPoints let maxValue: CGFloat = 100.0 var maxDataPoint: CGFloat { var maxData: CGFloat = 0 for items in dataPoints { if items.value >= maxData { maxData = items.value } } return maxData } //MARK: - Initializers override init(frame: CGRect) { super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } //MARK: - Graphics and drawings override func drawRect(rect: CGRect) { let width = rect.width let height = rect.height let graphWidth = rect.width - 2 * horizontalPadding - rightGraphMargin - leftGraphMargin let graphHeight = rect.height - topGraphMargin - bottomGraphMargin let linePath = UIBezierPath() //top line let lineSpacing = graphHeight/10.0 for count in 0...10 { linePath.moveToPoint(CGPoint(x: horizontalPadding, y: topGraphMargin + (CGFloat(count) * lineSpacing))) linePath.addLineToPoint(CGPoint(x: width - horizontalPadding, y: topGraphMargin + (CGFloat(count) * lineSpacing))) if count == 0 || count == 5 || count == 10 { let label = UILabel(frame: CGRect(x: horizontalPadding, y: topGraphMargin + (CGFloat(count - 1) * lineSpacing), width: leftGraphMargin, height: lineSpacing)) self.addSubview(label) label.textColor = gridFontColor label.font = graphIndicatorFont label.minimumScaleFactor = 0.9 label.adjustsFontSizeToFitWidth = true if count == 0 { label.text = "100" } else if count == 5 { label.text = "50 " } else { label.text = "0 " } } } let color = gridColor color.setStroke() linePath.lineWidth = gridLineWidth linePath.stroke() let context = UIGraphicsGetCurrentContext() let colors = [startColor.CGColor, endColor.CGColor] let colorSpace = CGColorSpaceCreateDeviceRGB() let colorLocations:[CGFloat] = [0.05, 0.8] let gradient = CGGradientCreateWithColors(colorSpace, colors, colorLocations) var startPoint = CGPoint.zero var endPoint = CGPoint(x:0, y:self.bounds.height) // CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, []) let margin: CGFloat = 10.0 let columnXPoint = { (column: Int) -> CGFloat in let spacer = (graphWidth - self.graphPointDiameter)/CGFloat((self.dataPoints.count - 1)) var x: CGFloat = 0 if column == 0 { x = 0 } else { x = CGFloat(column) * spacer } x += self.horizontalPadding + self.leftGraphMargin + self.graphPointDiameter/2 return x } let columnYPoint = { (graphPoint: CGFloat) -> CGFloat in var y:CGFloat = CGFloat(graphPoint) / CGFloat(self.maxValue) * graphHeight y = graphHeight + self.topGraphMargin - y // Flip the graph return y } //Adding Graph lines based on graph data graphLineColor.setFill() graphLineColor.setStroke() let graphPath = UIBezierPath() graphPath.moveToPoint(CGPoint(x:columnXPoint(0), y:columnYPoint(dataPoints[0].value))) for i in 1..<dataPoints.count { let nextPoint = CGPoint(x: columnXPoint(i), y: columnYPoint(dataPoints[i].value)) graphPath.addLineToPoint(nextPoint) } //save the state of the context (commented out for now) CGContextSaveGState(context) //making a copy of the path let clippingPath = graphPath.copy() as! UIBezierPath //add lines to the copied path to complete the clip area clippingPath.addLineToPoint(CGPoint( x: columnXPoint(dataPoints.count - 1), y:height)) clippingPath.addLineToPoint(CGPoint( x:columnXPoint(0), y:height)) clippingPath.closePath() clippingPath.addClip() let highestYPoint = columnYPoint(maxDataPoint) startPoint = CGPoint(x:margin, y: highestYPoint) endPoint = CGPoint(x:margin, y: self.bounds.height - bottomGraphMargin) CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, []) CGContextRestoreGState(context) graphPath.lineWidth = graphLineWidth graphPath.stroke() for i in 0..<dataPoints.count { var point = CGPoint(x: columnXPoint(i), y: columnYPoint(dataPoints[i].value)) let xLabelWidth: CGFloat = (graphWidth - self.graphPointDiameter)/CGFloat((self.dataPoints.count - 1)) //(horizontalPadding + rightGraphMargin)*2 let xLabelHeight: CGFloat = bottomGraphMargin/2 let xLabel = UILabel() xLabel.font = graphXLabelFont xLabel.minimumScaleFactor = 0.1 xLabel.adjustsFontSizeToFitWidth = true xLabel.text = dataPoints[i].xLabel if i == dataPoints.count - 1 { let temporaryWidth = width - (point.x - xLabelWidth/2) if temporaryWidth <= xLabelWidth { xLabel.frame = CGRect(x: (point.x - xLabelWidth/2), y: height - (bottomGraphMargin + xLabelHeight)/2, width: width - (point.x - xLabelWidth/2), height: xLabelHeight) } else { xLabel.frame = CGRect(x: (point.x - xLabelWidth/2), y: height - (bottomGraphMargin + xLabelHeight)/2, width: xLabelWidth, height: xLabelHeight) } xLabel.textAlignment = .Center } else { xLabel.frame = CGRect(x: (point.x - xLabelWidth/2), y: height - (bottomGraphMargin + xLabelHeight)/2, width: xLabelWidth, height: xLabelHeight) xLabel.textAlignment = .Center } xLabel.textColor = xLabelFontColor point.x -= graphPointDiameter/2 point.y -= graphPointDiameter/2 self.addSubview(xLabel) let circle = UIBezierPath(ovalInRect: CGRect(origin: point, size: CGSize(width: graphPointDiameter, height: graphPointDiameter))) circle.fill() } } //MARK: - Awake from Nib override func awakeFromNib() { self.backgroundColor = graphBackgroundColor } }
mit
2081a1c5bf2b5ccd89334041072c19cd
37.370536
185
0.593252
4.79097
false
false
false
false
uphold/uphold-sdk-ios
Source/Paginator/Paginator.swift
1
2605
import Foundation import ObjectMapper import PromiseKit /// Paginator model. open class Paginator<T>: PaginatorProtocol { /// Default offset page. static var DEFAULT_OFFSET: Int { return 50 } /// Default start page. static var DEFAULT_START: Int { return 0 } /// The current page. private var currentPage: Int /// A promise with the first list of elements. open let elements: Promise<[T]> /// Closure to get a promise with the total number of elements. let countClosure: () -> Promise<Int> /// Closure to get a promise with a bolean indicating if exists a next page of elements. let hasNextPageClosure: (_ currentPage: Int) -> Promise<Bool> /// Closure to get a promise with the next page of elements. let nextPageClosure: (_ range: String) -> Promise<[T]> /** Constructor - parameter countClosure: A closure to get the total number of elements. - parameter elements: A promise with the first page of elements. - parameter hasNextPageClosure: A closure to check if there are more pages. - parameter nextPageClosure: A closure to get the next page of elements. */ init(countClosure: @escaping () -> Promise<Int>, elements: Promise<[T]>, hasNextPageClosure: @escaping (_ currentPage: Int) -> Promise<Bool>, nextPageClosure: @escaping (_ range: String) -> Promise<[T]>) { self.countClosure = countClosure self.currentPage = 1 self.elements = elements self.hasNextPageClosure = hasNextPageClosure self.nextPageClosure = nextPageClosure } /** Gets the total number of elements. - returns: A promise with the total number of elements. */ open func count() -> Promise<Int> { return countClosure() } /** Gets the next page of elements. - returns: A promise with the array of elements. */ open func getNext() -> Promise<[T]> { defer { currentPage += 1 objc_sync_exit(self.currentPage) } objc_sync_enter(self.currentPage) let promise: Promise<[T]> = self.nextPageClosure(Header.buildRangeHeader(start: (Paginator.DEFAULT_OFFSET * currentPage), end: ((Paginator.DEFAULT_OFFSET * currentPage) + Paginator.DEFAULT_OFFSET) - 1)) return promise } /** Gets a promise with a bolean indicating if exists a next page of elements. - returns: A promise with the bolean indicator. */ open func hasNext() -> Promise<Bool> { return self.hasNextPageClosure(self.currentPage) } }
mit
a621650586118d3d6604dd9465935682
29.290698
210
0.646833
4.594356
false
false
false
false
kentaiwami/FiNote
ios/FiNote/FiNote/Movie/MovieAddSearch/MovieAddSearchDetailViewController.swift
1
6875
// // MovieAddSearchDetailViewController.swift // FiNote // // Created by 岩見建汰 on 2018/01/28. // Copyright © 2018年 Kenta. All rights reserved. // import UIKit import NVActivityIndicatorView import SwiftyJSON import Alamofire import AlamofireImage import KeychainAccess import TinyConstraints class MovieAddSearchDetailViewController: UIViewController { var user_id = "" var username = "" var password = "" var searched_movie = MovieAddSearchResult.Data() var contentView = UIView() var latestView = UIView() var posterImageView = UIImageView() fileprivate let utility = Utility() override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.white self.navigationItem.title = "Movie Detail" let keychain = Keychain() user_id = (try! keychain.getString("id"))! username = (try! keychain.getString("username"))! password = (try! keychain.getString("password"))! DrawViews() } func DrawViews() { InitScrollView() InitPosterView() InitFloaty() InitTitleView() InitOverView() InitReleaseInfoView() } func SetMovieID(searched_movie: MovieAddSearchResult.Data) { self.searched_movie = searched_movie } func InitScrollView() { let scrollView = UIScrollView() scrollView.frame = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: self.view.bounds.height) self.view.addSubview(scrollView) scrollView.top(to: self.view) scrollView.leading(to: self.view) scrollView.trailing(to: self.view) scrollView.bottom(to: self.view) contentView = UIView() scrollView.addSubview(contentView) contentView.top(to: scrollView) contentView.leading(to: scrollView) contentView.trailing(to: scrollView) contentView.bottom(to: scrollView) contentView.width(to: scrollView) } func InitPosterView() { let urlRequest = URL(string: API.poster_base.rawValue+searched_movie.poster)! posterImageView = UIImageView() posterImageView.af_setImage( withURL: urlRequest, placeholderImage: UIImage(named: "no_image") ) posterImageView.layer.shadowOpacity = 0.5 posterImageView.layer.shadowColor = UIColor.black.cgColor posterImageView.layer.shadowOffset = CGSize(width: 1, height: 1) posterImageView.layer.shadowRadius = 3 posterImageView.layer.masksToBounds = false contentView.addSubview(posterImageView) posterImageView.top(to: contentView, offset: 50) posterImageView.centerX(to: contentView) posterImageView.width(200) posterImageView.height(300) latestView = posterImageView } func InitFloaty() { let floaty = UIButton(frame: CGRect.zero) floaty.backgroundColor = UIColor.hex(Color.main.rawValue, alpha: 1.0) floaty.tintColor = UIColor.white floaty.setBackgroundImage(utility.uiColorToUIImage(hex: "#FFFFFF", alpha: 0.2), for: .highlighted) floaty.setImage(UIImage(named: "icon_edit"), for: .normal) floaty.setImage(UIImage(named: "icon_edit"), for: .highlighted) floaty.layer.masksToBounds = true floaty.layer.cornerRadius = 56/2 floaty.addTarget(self, action: #selector(TapFloatyButton), for: .touchUpInside) self.view.addSubview(floaty) floaty.trailing(to: self.view, offset: -10) floaty.bottom(to: self.view, offset: -10) floaty.width(56) floaty.height(56) } @objc func TapFloatyButton() { let movie_search_info_VC = MovieAddSearchUserInfoViewController() movie_search_info_VC.SetMovie(movie: self.searched_movie) movie_search_info_VC.SetPoster(poster: self.posterImageView.image!) let nav = UINavigationController() nav.viewControllers = [movie_search_info_VC] self.present(nav, animated: true, completion: nil) } func InitTitleView() { let titleView = UILabel() let offset = 28 as CGFloat titleView.textAlignment = .center titleView.lineBreakMode = .byWordWrapping titleView.numberOfLines = 0 titleView.font = UIFont(name: Font.helveticaneue_B.rawValue, size: 22) titleView.text = searched_movie.title contentView.addSubview(titleView) titleView.topToBottom(of: latestView, offset: 50) titleView.leading(to: contentView, offset: offset) titleView.centerX(to: contentView) titleView.trailing(to: contentView, offset: -offset) latestView = titleView } func InitOverView() { let overviewView = UILabel() let offset = 28 as CGFloat overviewView.textAlignment = .center overviewView.lineBreakMode = .byWordWrapping overviewView.numberOfLines = 0 overviewView.font = UIFont(name: Font.helveticaneue.rawValue, size: 16) overviewView.attributedText = utility.addAttributedTextLineHeight(height: 22, text: NSMutableAttributedString(string: searched_movie.overview)) contentView.addSubview(overviewView) overviewView.topToBottom(of: latestView, offset: 10) overviewView.leading(to: contentView, offset: offset) overviewView.centerX(to: contentView) overviewView.trailing(to: contentView, offset: -offset) latestView = overviewView } func InitReleaseInfoView() { let icon_wh = 25 as CGFloat let release_icon = UIImageView(image: UIImage(named: "tab_movies")) release_icon.image = release_icon.image!.withRenderingMode(.alwaysTemplate) release_icon.tintColor = UIColor.hex(Color.gray.rawValue, alpha: 1.0) contentView.addSubview(release_icon) release_icon.topToBottom(of: latestView, offset: 10) release_icon.centerX(to: contentView, offset: -50) release_icon.width(icon_wh) release_icon.height(icon_wh) let release_date = UILabel() release_date.font = UIFont(name: Font.helveticaneue.rawValue, size: 16) release_date.textColor = UIColor.hex(Color.gray.rawValue, alpha: 1.0) release_date.text = searched_movie.release_date contentView.addSubview(release_date) release_date.centerY(to: release_icon, offset: 0) release_date.leadingToTrailing(of: release_icon, offset: 10) latestView = release_date contentView.bottom(to: latestView, offset: 200) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
mit
876f7e408d7495a150e5cc852b2cfb17
34.75
151
0.649621
4.462939
false
false
false
false
hevertonrodrigues/HRSkills
HRSkills/HRSkill.swift
1
1683
// // HRSkill.swift // HRSkills // // Created by Heverton Rodrigues on 20/09/14. // Copyright (c) 2014 Heverton Rodrigues. All rights reserved. // import SystemConfiguration import Foundation /** * HRSkill * * @package HRSkills/Util * @author Heverton Rodrigues * @since 2014-09-20 * @version 1.0 */ class HRSkill { /** * Static Function to check if iOS is 8 * * @param nil * @return Bool */ class func ios8() -> Bool { if ( NSFoundationVersionNumber <= NSFoundationVersionNumber_iOS_7_1 ) { return false } else { return true } } /** * Static Function to check if has network * * @param nil * @return Bool */ class func hasNetwork() -> Bool { var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0)) zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress)) zeroAddress.sin_family = sa_family_t(AF_INET) let defaultRouteReachability = withUnsafePointer(&zeroAddress) { SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)).takeRetainedValue() } var flags: SCNetworkReachabilityFlags = 0 if SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) == 0 { return false } let isReachable = (flags & UInt32(kSCNetworkFlagsReachable)) != 0 let needsConnection = (flags & UInt32(kSCNetworkFlagsConnectionRequired)) != 0 return (isReachable && !needsConnection) ? true : false } }
mit
504d8e97d78cfe3e21d6fdacfd3bea83
24.515152
143
0.5918
4.282443
false
false
false
false
agvaldezc/MedicaT
InformacionPersonalTableViewController.swift
1
7674
// // InformacionPersonalTableViewController.swift // MedicaT // // Created by Alan Valdez on 10/19/16. // Copyright © 2016 ITESM. All rights reserved. // import UIKit class InformacionPersonalTableViewController: UITableViewController { @IBOutlet weak var profileImage: UIImageView! var rol : String! @IBOutlet weak var nombreField: UITextField! @IBOutlet weak var telefonoField: UITextField! @IBOutlet weak var emailField: UITextField! let userPrefs = UserDefaults.standard override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() // navigationItem.title = rol navigationItem.titleView?.tintColor = UIColor.white prepareAccesoryViews() profileImage.layer.cornerRadius = profileImage.frame.width / 2 switch rol { case "Paciente": let paciente = userPrefs.value(forKey: "paciente") as? [String:String] if paciente != nil { nombreField.text = paciente?["nombre"] telefonoField.text = paciente?["telefono"] } break case "Médico": let medico = userPrefs.value(forKey: "medico") as? [String:String] if medico != nil { nombreField.text = medico?["nombre"] telefonoField.text = medico?["telefono"] emailField.text = medico?["email"] } break case "Responsable": let responsable = userPrefs.value(forKey: "responsable") as? [String:String] if responsable != nil { nombreField.text = responsable?["nombre"] telefonoField.text = responsable?["telefono"] emailField.text = responsable?["email"] } break default: break } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows if rol == "Paciente" { return 3 } else { return 4 } } @IBAction func saveInformation(_ sender: UIBarButtonItem) { let nombre = nombreField.text! let telefono = telefonoField.text! let email = emailField.text! if nombre != "" && telefono != "" && rol == "Paciente" { let paciente : Dictionary = ["nombre" : nombre, "telefono" : telefono] userPrefs.set(paciente, forKey: "paciente") _ = navigationController?.popViewController(animated: true) } else if nombre != "" && telefono != "" && email != "" { switch rol { case "Médico": let medico : Dictionary = ["nombre" : nombre, "telefono" : telefono, "email" : email] userPrefs.set(medico, forKey: "medico") break case "Responsable": let responsable : Dictionary = ["nombre" : nombre, "telefono" : telefono, "email" : email] userPrefs.set(responsable, forKey: "responsable") break default: break } _ = navigationController?.popViewController(animated: true) } else { let alert = UIAlertController(title: "Error", message: "Información no válida. Favor de ingresar la información necesaria.", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil)) present(alert, animated: true, completion: nil) } } func prepareAccesoryViews() { let accessoryView = UIToolbar() let accessoryButton = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(dismissKeyboard)) let accessorySpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil) let items = [accessorySpace, accessoryButton] accessoryButton.tintColor = UIColor.white accessoryView.barStyle = .default accessoryView.backgroundColor = UIColor(red: (110/255.0) as CGFloat, green: (171/255) as CGFloat, blue: (247/255) as CGFloat, alpha: 1.0 as CGFloat) accessoryView.items = items accessoryView.isTranslucent = false accessoryView.barTintColor = UIColor(red: (110/255.0) as CGFloat, green: (171/255) as CGFloat, blue: (247/255) as CGFloat, alpha: 1.0 as CGFloat) accessoryView.isUserInteractionEnabled = true accessoryView.sizeToFit() nombreField.inputAccessoryView = accessoryView telefonoField.inputAccessoryView = accessoryView emailField.inputAccessoryView = accessoryView } func dismissKeyboard() { view.endEditing(true) } /* override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
c217421bc1cd43cea0ef0b5095b31f19
33.38565
160
0.603678
5.044737
false
false
false
false
hongsign/swift-customUI
SudokuBoard.swift
1
1717
// // SudokuBoard.swift // Dev // // Created by YU HONG on 2016-12-01. // Copyright © 2016 homesoft. All rights reserved. // import Foundation class SudokuBoard { /** * Sudoku board size. */ static let BOARD_SIZE: Int = 9; /** * Sudoku board sub-square size. */ static let BOARD_SUB_SQURE_SIZE: Int = 3; /** * Number of 9x3 column segments or 3x9 row segments. */ static let BOARD_SEGMENTS_NUMBER: Int = 3; /** * We will use array indexes from 1.,.n, instead 0...n-1 */ static let BOARD_MAX_INDEX: Int = BOARD_SIZE + 1; /** * Number of cells on the Sudoku board. */ static let BOARD_CELLS_NUMBER: Int = BOARD_SIZE * BOARD_SIZE; /** * Sudoku board was successfully loaded. */ static let BOARD_STATE_EMPTY: Int = 1; /** * Sudoku board was successfully loaded. */ static let BOARD_STATE_LOADED: Int = 2; /** * Sudoku board is ready to start solving process. */ static let BOARD_STATE_READY: Int = 3; /** * Sudoku board is ready to start solving process. */ static let BOARD_STATE_ERROR: Int = SudokuErrorCodes.SUDOKUSOLVER_BOARD_ERROR; /** * Path number gives the information on how many routes * were verified until solutions was found. */ var pathNumber: Int! /** * Sudoku board array. */ var board: [[Int]]! /** * Default constructor. */ init() { board = [[Int]]() for i in 0..<SudokuBoard.BOARD_SIZE { board.append([Int]()) for _ in 0..<SudokuBoard.BOARD_SIZE { board[i].append(SudokuBoardCell.EMPTY) } } pathNumber = -1; } }
mit
0b454f5cec13d814d6a4503d755d6a03
23.528571
82
0.56993
3.635593
false
false
false
false
cristov26/moviesApp
MoviesApp/MoviesApp/Views/MoviesCellViewController.swift
1
1464
// // MoviesCellViewController.swift // MoviesApp // // Created by Cristian Tovar on 11/16/17. // Copyright © 2017 Cristian Tovar. All rights reserved. // import UIKit import Alamofire import AlamofireImage class MoviesCellViewController: UITableViewCell { @IBOutlet weak var MoviesImage: UIImageView! @IBOutlet weak var MoviesTitle: UILabel! @IBOutlet weak var MoviesDescription: UILabel! @IBOutlet weak var MoviesYear: UILabel! let urlImage = "https://image.tmdb.org/t/p/w342" 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 } func setContent(movie: MovieData) { //TODO: Get this info when it comes from server let filter = AspectScaledToFillSizeWithRoundedCornersFilter( size: self.MoviesImage.frame.size, radius: 5.0 ) let url = urlImage + movie.posterPath! self.MoviesImage.af.setImage( withURL: URL(string: url)!, placeholderImage: UIImage(named: "icon - Movie"), filter: filter ) MoviesTitle.text = "\(movie.title)" MoviesDescription.text = movie.overview MoviesYear.text = movie.releaseDateString } }
mit
87387b2c7f732c924f880b0746f956df
27.134615
68
0.634997
4.734628
false
false
false
false
mparrish91/gifRecipes
application/ImageViewController.swift
1
14171
// // ImageViewController.swift // UZImageCollectionView // // Created by sonson on 2015/06/05. // Copyright (c) 2015年 sonson. All rights reserved. // import UIKit import FLAnimatedImage let ImageViewControllerDidChangeCurrentImageName = Notification.Name(rawValue: "ImageViewControllerDidChangeCurrentImage") class ImageViewController: UIViewController, Page, ImageDownloadable, ImageViewDestination { var thumbnails: [Thumbnail] = [] let index: Int let scrollView = UIScrollView(frame: CGRect.zero) let mainImageView = FLAnimatedImageView(frame: CGRect.zero) var indicator = UIActivityIndicatorView(activityIndicatorStyle:.gray) var maximumZoomScale: CGFloat = 0 var minimumZoomScale: CGFloat = 0 var imageURL = URL(string: "https://api.sonson.jp")! var task: URLSessionDataTask? var isOpenedBy3DTouch = false private var _alphaWithoutMainContent: CGFloat = 1 var initialiContentOffsetY = CGFloat(0) var alphaWithoutMainContent: CGFloat { get { return _alphaWithoutMainContent } set { _alphaWithoutMainContent = newValue scrollView.backgroundColor = scrollView.backgroundColor?.withAlphaComponent(_alphaWithoutMainContent) view.backgroundColor = view.backgroundColor?.withAlphaComponent(_alphaWithoutMainContent) } } func thumbnailImageView() -> UIImageView { return mainImageView } deinit { print("deinit ImageViewController") NotificationCenter.default.removeObserver(self) } required init?(coder aDecoder: NSCoder) { self.index = 0 // self.imageCollectionViewController = ImageCollectionViewController(collection: ImageCollection(newList: [])) super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() setupSubviews() view.backgroundColor = UIColor.white scrollView.backgroundColor = UIColor.white scrollView.alwaysBounceVertical = true let rec = UITapGestureRecognizer(target: self, action: #selector(ImageViewController.didTapGesture(recognizer:))) self.scrollView.addGestureRecognizer(rec) } func didTapGesture(recognizer: UITapGestureRecognizer) { if let imageViewPageController = self.parentImageViewPageController { imageViewPageController.navigationBar.isHidden = !imageViewPageController.navigationBar.isHidden } } override func willMove(toParentViewController parent: UIViewController?) { super.willMove(toParentViewController: parent) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } override func viewDidAppear(_ animated: Bool) { print("viewDidAppear") super.viewDidAppear(animated) } override func viewDidDisappear(_ animated: Bool) { print("viewDidDisappear") super.viewDidDisappear(animated) } func toggleDarkMode(isDark: Bool) { UIView.animate(withDuration: 0.2, animations: { () -> Void in self.scrollView.backgroundColor = isDark ? UIColor.black : UIColor.white }, completion: { (_) -> Void in }) } init(index: Int, thumbnails: [Thumbnail], isOpenedBy3DTouch: Bool = false) { self.index = index scrollView.addSubview(mainImageView) super.init(nibName: nil, bundle: nil) self.thumbnails = thumbnails self.imageURL = thumbnails[index].thumbnailURL self.isOpenedBy3DTouch = isOpenedBy3DTouch NotificationCenter.default.addObserver(self, selector: #selector(ImageViewController.didFinishDownloading(notification:)), name: ImageDownloadableDidFinishDownloadingName, object: nil) download(imageURLs: [self.imageURL], sender: self) } class func controllerWithIndex(index: Int, isDark: Bool, thumbnails: [Thumbnail]) -> ImageViewController { let con = ImageViewController(index:index, thumbnails:thumbnails) return con } } extension ImageViewController { func setupScrollViewScale(imageSize: CGSize) { scrollView.frame = self.view.bounds let boundsSize = self.view.bounds // calculate min/max zoomscale let xScale = boundsSize.width / imageSize.width; // the scale needed to perfectly fit the image width-wise let yScale = boundsSize.height / imageSize.height; // the scale needed to perfectly fit the image height-wise // fill width if the image and phone are both portrait or both landscape; otherwise take smaller scale let imagePortrait = imageSize.height > imageSize.width let phonePortrait = boundsSize.height > imageSize.width var minScale = imagePortrait == phonePortrait ? xScale : (xScale < yScale ? xScale : yScale) // on high resolution screens we have double the pixel density, so we will be seeing every pixel if we limit the // maximum zoom scale to 0.5. let maxScale = 10.0 / UIScreen.main.scale // don't let minScale exceed maxScale. (If the image is smaller than the screen, we don't want to force it to be zoomed.) if minScale > maxScale { minScale = maxScale } scrollView.maximumZoomScale = maxScale scrollView.minimumZoomScale = minScale scrollView.contentSize = mainImageView.image!.size scrollView.zoomScale = scrollView.minimumZoomScale } func updateImageCenter() { let boundsSize = self.view.bounds var frameToCenter = mainImageView.frame if frameToCenter.size.width < boundsSize.width { frameToCenter.origin.x = (boundsSize.width - frameToCenter.size.width) / 2 } else { frameToCenter.origin.x = 0 } if frameToCenter.size.height < boundsSize.height { frameToCenter.origin.y = (boundsSize.height - frameToCenter.size.height) / 2 } else { frameToCenter.origin.y = 0 } mainImageView.frame = frameToCenter } func setIndicator() { self.view.addSubview(indicator) indicator.translatesAutoresizingMaskIntoConstraints = false self.view.addConstraint(NSLayoutConstraint(item: indicator, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0)) self.view.addConstraint(NSLayoutConstraint(item: indicator, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0)) } func setScrollView() { scrollView.showsVerticalScrollIndicator = false scrollView.showsHorizontalScrollIndicator = false scrollView.bouncesZoom = true scrollView.decelerationRate = UIScrollViewDecelerationRateFast scrollView.delegate = self scrollView.isMultipleTouchEnabled = true self.view.addSubview(scrollView) scrollView.translatesAutoresizingMaskIntoConstraints = false self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[scrollView]-0-|", options: NSLayoutFormatOptions(), metrics: [:], views: ["scrollView": scrollView])) self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[scrollView]-1-|", options: NSLayoutFormatOptions(), metrics: [:], views: ["scrollView": scrollView])) } func setupSubviews() { self.view.isMultipleTouchEnabled = true self.navigationController?.view.isMultipleTouchEnabled = true setScrollView() setIndicator() indicator.startAnimating() indicator.isHidden = false setImage(of: self.imageURL) } func close() { if let imageViewPageController = parentImageViewPageController { imageViewPageController.close(sender: self) } } var parentImageViewPageController: ImageViewPageController? { if let vc1 = self.parent as? ImageViewPageController { return vc1 } return nil } } // MARK: UIScrollViewDelegate extension ImageViewController : UIScrollViewDelegate { func scrollViewDidZoom(_ scrollView: UIScrollView) { print("scrollViewDidZoom") let ratio = scrollView.zoomScale / scrollView.minimumZoomScale let threshold = CGFloat(0.6) var alpha = CGFloat(1) print(ratio) if ratio > 1 { alpha = 1 } else if ratio > threshold { // alpha = (ratio - threshold / 2) * (ratio - threshold / 2) + 1 - (1 - threshold / 2) * (1 - threshold / 2) alpha = (ratio - 1) * (ratio - 1) * (-1) / ((threshold - 1) * (threshold - 1)) + 1 } else { alpha = 0 } print(alpha) parentImageViewPageController?.alphaWithoutMainContent = alpha self.updateImageCenter() if ratio < threshold { close() } } func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { print("scrollViewDidEndDragging") } func scrollViewDidScroll(_ scrollView: UIScrollView) { print("scrollViewDidScroll") if scrollView.contentOffset.y < initialiContentOffsetY { let threshold = CGFloat(-150) let s = CGFloat(-50) let x = scrollView.contentOffset.y - initialiContentOffsetY if x < s { let param = (x - s) * (x - s) * (-1) / ((threshold - s) * (threshold - s)) + 1 parentImageViewPageController?.alphaWithoutMainContent = param } else { parentImageViewPageController?.alphaWithoutMainContent = 1 } if x < threshold { close() } } } func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) { print("scrollViewWillBeginDecelerating") } func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) { print("scrollViewDidEndScrollingAnimation") } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { print("scrollViewDidEndDecelerating") } func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) { print("scrollViewDidEndZooming") self.updateImageCenter() } func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { print("scrollViewWillBeginDragging") let userInfo: [String: Any] = ["index": self.index, "thumbnail": self.thumbnails[self.index]] NotificationCenter.default.post(name: ImageViewPageControllerDidChangePageName, object: nil, userInfo: userInfo) NotificationCenter.default.post(name: ImageViewPageControllerDidStartDraggingThumbnailName, object: nil, userInfo: ["thumbnail": thumbnails[index]]) } func scrollViewWillBeginZooming(_ scrollView: UIScrollView, with view: UIView?) { print("scrollViewWillBeginZooming") let userInfo: [String: Any] = ["index": self.index, "thumbnail": self.thumbnails[self.index]] NotificationCenter.default.post(name: ImageViewPageControllerDidChangePageName, object: nil, userInfo: userInfo) NotificationCenter.default.post(name: ImageViewPageControllerDidStartDraggingThumbnailName, object: nil, userInfo: ["thumbnail": thumbnails[index]]) } func viewForZooming(in scrollView: UIScrollView) -> UIView? { print("viewForZooming") return mainImageView } } // MARK: ImageDownloadable extension ImageViewController { func setImage(of url: URL) { do { let data = try cachedDataInCache(of: url) guard let animatedImage: FLAnimatedImage = FLAnimatedImage(animatedGIFData: data as Data!) else { if let image = UIImage(data: data as Data) { mainImageView.isHidden = false mainImageView.image = image mainImageView.frame = CGRect(origin: CGPoint(x: 0, y: 0), size: image.size) setupScrollViewScale(imageSize: image.size) updateImageCenter() initialiContentOffsetY = scrollView.contentOffset.y indicator.stopAnimating() indicator.isHidden = true } else { indicator.startAnimating() indicator.isHidden = false } return } mainImageView.animatedImage = animatedImage mainImageView.frame = CGRect(origin: CGPoint(x: 0, y: 0), size: animatedImage.size) setupScrollViewScale(imageSize: animatedImage.size) updateImageCenter() initialiContentOffsetY = scrollView.contentOffset.y indicator.stopAnimating() indicator.isHidden = true } catch { print(error) } } func didFinishDownloading(notification: NSNotification) { if let userInfo = notification.userInfo, let obj = userInfo[ImageDownloadableSenderKey] as? ImageViewController, let url = userInfo[ImageDownloadableUrlKey] as? URL { if obj == self { if let _ = userInfo[ImageDownloadableErrorKey] as? NSError { mainImageView.isHidden = false mainImageView.image = UIImage(named: "error") mainImageView.frame = self.view.bounds updateImageCenter() mainImageView.contentMode = .center mainImageView.isUserInteractionEnabled = false indicator.stopAnimating() indicator.isHidden = true } else { setImage(of: url) } } } } }
mit
3063cc5e42d347245ef76d6acca8c125
39.367521
226
0.646129
5.487607
false
false
false
false
ptangen/equityStatus
EquityStatus/APIClient.swift
1
10978
// // apiClient.swift // EquityStatus // // Created by Paul Tangen on 12/19/16. // Copyright © 2016 Paul Tangen. All rights reserved. // import Foundation import UIKit class APIClient { // Use the "Core US Fundamentals Data" at quandl. $50/mo class func requestHistoricalMeasures(tickers: String, completion: @escaping ([String: Any]) -> Void) { let urlString = "https://www.quandl.com/api/v3/datatables/SHARADAR/SF1.json" let urlWithParameters = "\(urlString)?dimension=MRY&qopts.columns=ticker,datekey,eps,sharesbas,de,pe1,roe,bvps&api_key=\(Secrets.quandlKey)&ticker=\(tickers)" let url = URL(string: urlWithParameters) if let url = url { var request = URLRequest(url: url) request.httpMethod = "GET" request.setValue("application/json", forHTTPHeaderField: "Accept") request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in if let data = data { DispatchQueue.main.async { do { let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] if let message = (json?["message"]) { completion(["error": message as! String]) } else if let datatable = json?["datatable"] { //dump(datatable) if let datatableArr = datatable as? Dictionary<String, [AnyObject]>{ if let data = datatableArr["data"] { //print(data) let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd" var historicalMeasures = [HistoricalMeasure]() for tickersData in data { let historicalMeasure = HistoricalMeasure(ticker: "inital value", date: Date()) // ticker if let ticker = tickersData.allObjects?[0] as? String { historicalMeasure.ticker = ticker } else { historicalMeasure.ticker = "unable to unwrap" } // date if let dateString = tickersData.allObjects?[1] as? String { if let date = formatter.date(from: dateString) { historicalMeasure.date = date } } // eps if let eps = tickersData.allObjects?[2] as? Double { historicalMeasure.eps = eps } // so if let so = tickersData.allObjects?[3] as? Int { historicalMeasure.so = so } // dr if let dr = tickersData.allObjects?[4] as? Double { historicalMeasure.dr = dr } // pe if let pe = tickersData.allObjects?[5] as? Double { historicalMeasure.pe = pe } // roe if let roe = tickersData.allObjects?[6] as? Double { historicalMeasure.roe = roe } // bv if let bv = tickersData.allObjects?[7] as? Double { historicalMeasure.bv = bv } // print("ticker: \(historicalMeasure.ticker)") // print("date: \(historicalMeasure.date)") // print("eps: \(historicalMeasure.eps)") // print("so: \(historicalMeasure.so)") // print("dr: \(historicalMeasure.dr)") // print("pe: \(historicalMeasure.pe)") // print("roe: \(historicalMeasure.roe)") // print("bv: \(historicalMeasure.bv)") historicalMeasures.append(historicalMeasure) } completion(["results": historicalMeasures]) } } else { completion(["error": "No values found for tickers. 6" as String]) } } else { completion(["error": "No values found for tickers. 3" as String]) } } catch { completion(["error": "The request for measures failed. 4"]) } } } if let error = error { dump(error) completion(["error": "error"]) } }).resume() } else { print("error: unable to unwrap url") } } class func getStockPrices(tickers: [String], tenYrsAgo: Bool, completion: @escaping ([String: Any]) -> Void) { let stringOfTickers = tickers.joined(separator: ",") var endDate = Date() if tenYrsAgo { endDate = endDate.advanced(by: -60*60*24*365*10) // move end date back 10 yrs // for 12.1 iOS: endDate = Calendar.current.date(byAdding: .month, value: -120, to: Date())! } // had to comment out for iOS 12 TODO: remove setting endDateLessSevenDays below let endDateLessSevenDays = endDate.advanced(by: -60*60*24*7) // get the date 7 days earlier to make sure we get a day with a ticker price // for 12.1 iOS: var endDateLessSevenDays = Date() // for 12.1 iOS: endDateLessSevenDays = Calendar.current.date(byAdding: .month, value: -121, to: Date())! let endDateString = endDate.description.prefix(10) // get day 10 yrs ago as string let endDateLessSevenDaysString = endDateLessSevenDays.description.prefix(10) // get day 10 yrs ago as string let urlString = "https://api.unibit.ai/v2/stock/historical/?" let urlParametersTickers = "tickers=\(stringOfTickers)" let urlParametersDate = "&startDate=\(endDateLessSevenDaysString)&endDate=\(endDateString)" let urlParamtersKey = "&interval=1&dataType=json&accessKey=\(Secrets.unibitKey)" let url = URL(string: urlString + urlParametersTickers + urlParametersDate + urlParamtersKey) //print(url) if let url = url { var request = URLRequest(url: url) request.httpMethod = "GET" request.setValue("application/json", forHTTPHeaderField: "Accept") request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in if let data = data { var tickersPricesDict:[String: Double] = [:] DispatchQueue.main.async { do { // on error, the data has a different structure, so must unwrap is differently let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] if let status = json?["status"] as! Int? { if status != 200 { // error due to exceeding quota or price does not exist for at time period provided if let message = json?["message"] as! String? { completion(["error": message]) } } } else { // status is not return on successful requests if let resultsDict = json?["result_data"] as! [String: Any]? { // resultsDict has tickers for keys and lots of data as value for ticker in tickers { if let tickerDict = resultsDict[ticker] { let tickerDictArr = tickerDict as! [Any] if let priceDict = tickerDictArr.last as? [String: Any]{ if let adj_close = priceDict["adj_close"] as! Double? { tickersPricesDict[ticker] = adj_close } } } } completion(["results": tickersPricesDict]) } } } catch { print("server not found") completion(["error": ["server not found"]]) } } } if let error = error { completion(["message": error]) } }).resume() } else { print("error: unable to unwrap url") } } }
apache-2.0
eb04b75436b7de2d831476222a8256c1
55.005102
166
0.400656
6.177265
false
false
false
false
vadymmarkov/Tuner
Source/Library/Buffer.swift
3
375
struct Buffer { var elements: [Float] var realElements: [Float]? var imagElements: [Float]? var count: Int { return elements.count } // MARK: - Initialization init(elements: [Float], realElements: [Float]? = nil, imagElements: [Float]? = nil) { self.elements = elements self.realElements = realElements self.imagElements = imagElements } }
mit
2919b7ad8d3fc2d11c4b422218b0ae51
21.058824
87
0.664
3.787879
false
false
false
false
SafeCar/iOS
Pods/TextFieldEffects/TextFieldEffects/TextFieldEffects/YokoTextField.swift
2
8200
// // YokoTextField.swift // TextFieldEffects // // Created by Raúl Riera on 30/01/2015. // Copyright (c) 2015 Raul Riera. All rights reserved. // import UIKit /** A YokoTextField is a subclass of the TextFieldEffects object, is a control that displays an UITextField with a customizable 3D visual effect on the background of the control. */ @IBDesignable public class YokoTextField: TextFieldEffects { /** The color of the placeholder text. This property applies a color to the complete placeholder string. The default value for this property is a black color. */ @IBInspectable dynamic public var placeholderColor: UIColor? { didSet { updatePlaceholder() } } /** The scale of the placeholder font. This property determines the size of the placeholder label relative to the font size of the text field. */ @IBInspectable dynamic public var placeholderFontScale: CGFloat = 0.7 { didSet { updatePlaceholder() } } /** The view’s foreground color. The default value for this property is a clear color. */ @IBInspectable dynamic public var foregroundColor: UIColor = UIColor.blackColor() { didSet { updateForeground() } } override public var placeholder: String? { didSet { updatePlaceholder() } } override public var bounds: CGRect { didSet { updateForeground() updatePlaceholder() } } private let foregroundView = UIView() private let foregroundLayer = CALayer() private let borderThickness: CGFloat = 3 private let placeholderInsets = CGPoint(x: 6, y: 6) private let textFieldInsets = CGPoint(x: 6, y: 6) // MARK: - TextFieldsEffects override public func drawViewsForRect(rect: CGRect) { updateForeground() updatePlaceholder() addSubview(foregroundView) addSubview(placeholderLabel) layer.addSublayer(foregroundLayer) } override public func animateViewsForTextEntry() { UIView.animateWithDuration(0.4, delay: 0, usingSpringWithDamping: 1.0, initialSpringVelocity: 0.6, options: .BeginFromCurrentState, animations: { self.foregroundView.layer.transform = CATransform3DIdentity }, completion: { _ in self.animationCompletionHandler?(type: .TextEntry) }) foregroundLayer.frame = rectForBorder(foregroundView.frame, isFilled: false) } override public func animateViewsForTextDisplay() { if text!.isEmpty { UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 1.0, initialSpringVelocity: 0.6, options: .BeginFromCurrentState, animations: { self.foregroundLayer.frame = self.rectForBorder(self.foregroundView.frame, isFilled: true) self.foregroundView.layer.transform = self.rotationAndPerspectiveTransformForView(self.foregroundView) }, completion: { _ in self.animationCompletionHandler?(type: .TextDisplay) }) } } // MARK: - Private private func updateForeground() { foregroundView.frame = rectForForeground(frame) foregroundView.userInteractionEnabled = false foregroundView.layer.transform = rotationAndPerspectiveTransformForView(foregroundView) foregroundView.backgroundColor = foregroundColor foregroundLayer.borderWidth = borderThickness foregroundLayer.borderColor = colorWithBrightnessFactor(foregroundColor, factor: 0.8).CGColor foregroundLayer.frame = rectForBorder(foregroundView.frame, isFilled: true) } private func updatePlaceholder() { placeholderLabel.font = placeholderFontFromFont(font!) placeholderLabel.text = placeholder placeholderLabel.textColor = placeholderColor placeholderLabel.sizeToFit() layoutPlaceholderInTextRect() if isFirstResponder() || text!.isNotEmpty { animateViewsForTextEntry() } } private func placeholderFontFromFont(font: UIFont) -> UIFont! { let smallerFont = UIFont(name: font.fontName, size: font.pointSize * placeholderFontScale) return smallerFont } private func rectForForeground(bounds: CGRect) -> CGRect { let newRect = CGRect(x: 0, y: 0, width: bounds.size.width, height: bounds.size.height - font!.lineHeight + textFieldInsets.y - borderThickness) return newRect } private func rectForBorder(bounds: CGRect, isFilled: Bool) -> CGRect { var newRect = CGRect(x: 0, y: bounds.size.height, width: bounds.size.width, height: isFilled ? borderThickness : 0) if !CATransform3DIsIdentity(foregroundView.layer.transform) { newRect.origin = CGPoint(x: 0, y: bounds.origin.y) } return newRect } private func layoutPlaceholderInTextRect() { let textRect = textRectForBounds(bounds) var originX = textRect.origin.x switch textAlignment { case .Center: originX += textRect.size.width/2 - placeholderLabel.bounds.width/2 case .Right: originX += textRect.size.width - placeholderLabel.bounds.width default: break } placeholderLabel.frame = CGRect(x: originX, y: bounds.height - placeholderLabel.frame.height, width: placeholderLabel.frame.size.width, height: placeholderLabel.frame.size.height) } // MARK: - private func setAnchorPoint(anchorPoint:CGPoint, forView view:UIView) { var newPoint:CGPoint = CGPoint(x: view.bounds.size.width * anchorPoint.x, y: view.bounds.size.height * anchorPoint.y) var oldPoint:CGPoint = CGPoint(x: view.bounds.size.width * view.layer.anchorPoint.x, y: view.bounds.size.height * view.layer.anchorPoint.y) newPoint = CGPointApplyAffineTransform(newPoint, view.transform) oldPoint = CGPointApplyAffineTransform(oldPoint, view.transform) var position = view.layer.position position.x -= oldPoint.x position.x += newPoint.x position.y -= oldPoint.y position.y += newPoint.y view.layer.position = position view.layer.anchorPoint = anchorPoint } private func colorWithBrightnessFactor(color: UIColor, factor: CGFloat) -> UIColor { var hue : CGFloat = 0 var saturation : CGFloat = 0 var brightness : CGFloat = 0 var alpha : CGFloat = 0 if color.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) { return UIColor(hue: hue, saturation: saturation, brightness: brightness * factor, alpha: alpha) } else { return color; } } private func rotationAndPerspectiveTransformForView(view: UIView) -> CATransform3D { setAnchorPoint(CGPoint(x: 0.5, y: 1.0), forView:view) var rotationAndPerspectiveTransform = CATransform3DIdentity rotationAndPerspectiveTransform.m34 = 1.0/800 let radians = ((-90) / 180.0 * CGFloat(M_PI)) rotationAndPerspectiveTransform = CATransform3DRotate(rotationAndPerspectiveTransform, radians, 1.0, 0.0, 0.0) return rotationAndPerspectiveTransform } // MARK: - Overrides override public func editingRectForBounds(bounds: CGRect) -> CGRect { let newBounds = CGRect(x: 0, y: 0, width: bounds.size.width, height: bounds.size.height - font!.lineHeight + textFieldInsets.y) return CGRectInset(newBounds, textFieldInsets.x, 0) } override public func textRectForBounds(bounds: CGRect) -> CGRect { let newBounds = CGRect(x: 0, y: 0, width: bounds.size.width, height: bounds.size.height - font!.lineHeight + textFieldInsets.y) return CGRectInset(newBounds, textFieldInsets.x, 0) } }
mit
f0fc4d9e3ebc13346227c98e2dc21db0
36.090498
175
0.644138
5.15859
false
false
false
false
DenHeadless/DTTableViewManager
Example/Controllers/CoreDataSearchViewController.swift
1
2663
// // CoreDataSearchViewController.swift // DTTableViewManager // // Created by Denys Telezhkin on 20.08.15. // Copyright (c) 2015 Denys Telezhkin. All rights reserved. // import UIKit import DTTableViewManager import CoreData class CoreDataSearchViewController: UIViewController, DTTableViewManageable { var tableView: UITableView! var noContentLabel: UILabel! let searchController = UISearchController(searchResultsController: nil) let fetchResultsController = CoreDataManager.sharedInstance.banksFetchController() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white configureSubviews() manager = DTTableViewManager(storage: CoreDataStorage(fetchedResultsController: fetchResultsController)) manager.register(BankCell.self) manager.tableViewUpdater?.didUpdateContent = { [weak self] _ in // In some cases it makes sense to show no content view underneath tableView self?.tableView.isHidden = self?.tableView.numberOfSections == 0 self?.noContentLabel.isHidden = self?.tableView.numberOfSections != 0 } searchController.searchResultsUpdater = self navigationItem.searchController = searchController navigationItem.hidesSearchBarWhenScrolling = false } func configureSubviews() { noContentLabel = UILabel() noContentLabel.translatesAutoresizingMaskIntoConstraints = false noContentLabel.text = "No banks found" noContentLabel.isHidden = true tableView = UITableView(frame: view.bounds, style: .plain) tableView.autoresizingMask = [.flexibleWidth, .flexibleHeight] view.addSubview(tableView) view.addSubview(noContentLabel) noContentLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true noContentLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true } } extension CoreDataSearchViewController : UISearchResultsUpdating { func updateSearchResults(for searchController: UISearchController) { let searchString = searchController.searchBar.text ?? "" if searchString == "" { self.fetchResultsController.fetchRequest.predicate = nil } else { let predicate = NSPredicate(format: "name contains[c] %@ OR city contains[c] %@ OR state contains[c] %@",searchString,searchString,searchString) self.fetchResultsController.fetchRequest.predicate = predicate } try! fetchResultsController.performFetch() manager.tableViewUpdater?.storageNeedsReloading() } }
mit
77e4137cde26bde2187a9ea7d1062539
39.969231
156
0.716861
5.653928
false
false
false
false
Azoy/Sword
Sources/Sword/Rest/Bucket.swift
1
2126
// // Bucket.swift // Sword // // Created by Alejandro Alonso // Copyright © 2018 Alejandro Alonso. All rights reserved. // /* import Foundation import Dispatch /// Rate Limit Thing class Bucket { /// Dispatch Queue to handle requests let worker: DispatchQueue /// Array of DispatchWorkItems to execute var queue = [() -> ()]() /// Limit on token count var limit: Int /// Token reset var reset: Int /// Current token count var tokens: Int /// Last reset in terms of Date var lastReset = Date() /// Used for Dispatch, but is basically ^ var lastResetDispatch = DispatchTime.now() /// Creates a bucket /// - parameter name: Name of bucket /// - parameter limit: Token limit /// - parameter interval: Interval at which tokens reset init(name: String, limit: Int, reset: Int) { self.worker = DispatchQueue(label: name, qos: .userInitiated) self.limit = limit self.tokens = limit - 1 self.reset = reset } /// Check for token renewal and amount of tokens in bucket. /// If there are no more tokens then tell Dispatch to execute this function /// after deadline. func check() { let now = Date() if now.timeIntervalSince1970 > Double(reset) { tokens = limit lastReset = now lastResetDispatch = .now() } guard tokens > 0 else { let interval: DispatchTimeInterval = .seconds(Double(reset) - lastReset.timeIntervalSince1970) worker.asyncAfter( deadline: lastResetDispatch + DispatchTimeInterval.seconds(Double(reset) - lastReset.timeIntervalSince1970) ) { [unowned self] in self.check() } return } execute() } /// Executes the first DispatchWorkItem in self.queue and removes /// a token from the bucket. func execute() { let item = queue.removeFirst() tokens -= 1 worker.async(execute: item) } /// Queues the given item /// /// - parameter item: Code block to execute func queue(_ item: @escaping () -> ()) { queue.append(item) check() } } */
mit
daafa7d6899c39414400d5b3bda4c282
22.876404
115
0.621176
4.390496
false
false
false
false
BenziAhamed/Nevergrid
NeverGrid/Source/MenuBar.swift
1
2081
// // MenuBar.swift // MrGreen // // Created by Benzi on 09/08/14. // Copyright (c) 2014 Benzi Ahamed. All rights reserved. // import Foundation import SpriteKit import UIKit class MenuBar : SKNode { required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } var leftNode = SKNode() var rightNode = SKNode() override init() { super.init() addChild(leftNode) addChild(rightNode) } func addLeft(node:SKNode) { var minX = node.position.x minX += FactoredSizes.MenuBar.paddingLeft.x for c in leftNode.children as [SKNode] { minX += c.calculateAccumulatedFrame().width minX += FactoredSizes.MenuBar.paddingLeft.x minX += FactoredSizes.MenuBar.paddingLeft.x // add it twice for extra spacing } minX += node.calculateAccumulatedFrame().width / 2.0 node.position = CGPointMake( minX, node.position.y ) leftNode.addChild(node) } func addRight(node:SKNode) { var maxX = node.position.x // println("maxX -> \(maxX)") if rightNode.children.count == 0 { maxX -= FactoredSizes.MenuBar.paddingRight.x // println("no children, so maxX -> \(maxX)") } for c in rightNode.children as [SKNode] { maxX -= c.calculateAccumulatedFrame().width maxX -= FactoredSizes.MenuBar.paddingRight.x // println("child bounds: \(c.calculateAccumulatedFrame())") // println("child found, so maxX -> \(maxX)") } let position = node.position let x = maxX - node.calculateAccumulatedFrame().width / 2.0 // println("current node bounds: \(node.calculateAccumulatedFrame())") // println("final x -> \(x)") // println("--------") node.position = CGPointMake(x, position.y) rightNode.addChild(node) } }
isc
69f48d74f82ed70d643668bd33957e20
25.025
89
0.547814
4.446581
false
false
false
false
danielrcardenas/ac-course-2017
frameworks/SwarmChemistry-Swif/Demo/CommonUtility.swift
1
2226
// // CommonUtility.swift // SwarmChemistry // // Created by Yamazaki Mitsuyoshi on 2017/08/16. // Copyright © 2017 Mitsuyoshi Yamazaki. All rights reserved. // #if os(iOS) || os(watchOS) || os(tvOS) import UIKit #elseif os(macOS) import Cocoa #endif import SwarmChemistry extension Vector2.Rect { init(_ rect: CGRect) { self.init(x: Value(rect.origin.x), y: Value(rect.origin.y), width: Value(rect.size.width), height: Value(rect.size.height)) } } extension Bundle { var appVersion: String { return object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String } var buildNumber: String { return object(forInfoDictionaryKey: "CFBundleVersion") as! String } var appVersionFullString: String { return "ver. \(appVersion)(\(buildNumber))" } } protocol IBInstantiatable: class { static var ibFileName: String { get } static var nib: Nib { get } static func instantiate() -> Self } extension IBInstantiatable { static var ibFileName: String { return String.init(describing: self) } } #if os(iOS) || os(watchOS) || os(tvOS) #elseif os(macOS) extension IBInstantiatable where Self: View { static var nib: Nib { let bundle = Bundle.init(for: self) return Nib.init(nibNamed: ibFileName, bundle: bundle)! } static func instantiate() -> Self { var topLevelObjects = NSArray() let bundle = Bundle.init(for: self) bundle.loadNibNamed(ibFileName, owner: self, topLevelObjects: &topLevelObjects) return topLevelObjects.filter { $0 is Self }.first as! Self } } // The codes are completely same as `extension IBInstantiatable where Self: View` // But NSWindow does not inherit NSView and `where` clause does not support `where Self: NSView or NSWindow` extension IBInstantiatable where Self: Window { static var nib: Nib { let bundle = Bundle.init(for: self) return Nib.init(nibNamed: ibFileName, bundle: bundle)! } static func instantiate() -> Self { var topLevelObjects = NSArray() let bundle = Bundle.init(for: self) bundle.loadNibNamed(ibFileName, owner: self, topLevelObjects: &topLevelObjects) return topLevelObjects.filter { $0 is Self }.first as! Self } } #endif
apache-2.0
3d9dd17fe65b24705fdd22ac47fbd41f
25.176471
127
0.69573
3.938053
false
false
false
false
megavolt605/CNLFoundationTools
CNLFoundationTools/CNLFT+Dictionary.swift
1
8042
// // CNLFT+Dictionary.swift // CNLFoundationTools // // Created by Igor Smirnov on 11/11/2016. // Copyright © 2016 Complex Numbers. All rights reserved. // import Foundation /// Common dictionary public typealias CNLDictionary = [String: Any] /// Array of CNLDictionary public typealias CNLArray = [CNLDictionary] /// Common dictionary key value public protocol CNLDictionaryKey: Hashable { } /// Common dictionary value public protocol CNLDictionaryValue: Hashable { } // MARK: - CNLDictionaryValue extension Bool: CNLDictionaryValue { } extension Int: CNLDictionaryValue { } extension String: CNLDictionaryValue { } extension Float: CNLDictionaryValue { } extension Double: CNLDictionaryValue { } extension String: CNLDictionaryKey { } // MARK: - Extenstion for Dictionary for CNLDictionary purposes public extension Dictionary { /// Get value for key with type check, returns default value when key doeas not exist either type check was failed /// /// - Parameters: /// - name: Key value /// - defaultValue: Default value /// - Returns: Value for the key (or defaultValue) public func value<T>(_ name: Key, _ defaultValue: T) -> T! where Key: CNLDictionaryKey, T: CNLDictionaryValue { let data = self[name] if let res = data as? T { return res } return defaultValue } /// Returns value for key with type check /// /// - Parameter name: Key value /// - Returns: Value for the key (or nil when type check was failed) public func value<T>(_ name: Key) -> T? where Key: CNLDictionaryKey, T: CNLDictionaryValue { return self[name] as? T } /// Calls closure with sub-dictionary for key with type check /// /// - Parameters: /// - name: Key value for dictionary container /// - closure: Closure to be called if type check successed public func dictionary(_ name: Key, closure: (_ data: Dictionary) -> Void) { if let possibleData = self[name] as? Dictionary { closure(possibleData) } } /// Calls closure for each element of the array in the dictionary array value /// /// - Parameters: /// - name: Key value for the array container /// - closure: Closure to be called if type check successed public func array<T>(_ name: Key, closure: (_ data: T) -> Void) where Key: CNLDictionaryKey { if let possibleData = self[name] as? [T] { for item in possibleData { closure(item) } } } /// Converts values of the key to an array /// /// - Parameter name: Key value /// - Returns: Result array public func array<T>(_ name: Key) -> [T] where Key: CNLDictionaryKey { return self[name] as? [T] ?? [] } /// Special implementation `value<T>` function for Date class /// /// - Parameters: /// - name: Key value /// - defaultValue: Default value /// - Returns: Date struct with value of unix timestamp from the key, nil if type check was failed public func date(_ name: Key, _ defaultValue: Date? = nil) -> Date? { if let data = self[name] as? TimeInterval { return Date(timeIntervalSince1970: data) } else { return defaultValue } } /// Special implementation `value<T>` function for URL class /// /// - Parameters: /// - name: Key value /// - defaultValue: Default value /// - Returns: URL with string, nil if type check was failed public func url(_ name: Key, _ defaultValue: URL? = nil) -> URL? { if let data = self[name] as? String { return URL(string: data) } else { return defaultValue } } /// Maps dictionary values to the another dictionary with same keys, using transform closure for values /// /// - Parameter f: Transform closure /// - Returns: Dictionary with the same keys and transformed values public func map(_ transform: (Key, Value) -> Value) -> [Key: Value] { var ret = [Key: Value]() for (key, value) in self { ret[key] = transform(key, value) } return ret } /// Maps dictionary to the array, using transform function for values. It skips nil results /// /// - Parameter transform: Transform closure /// - Returns: Array with non-nil results of transform closure public func mapSkipNil<V>(_ transform: ((Key, Value)) -> V?) -> [V] { var result: [V] = [] for item in self { if let entry = transform(item) { result.append(entry) } } return result } /// Maps dictionary to another dictionary /// /// - Parameter transform: Transform closure (it mapped source pair of key-value to result pair) /// - Returns: Dictionary with transformed pairs key-value from the source, exluding nil transform results public func mapSkipNil<K, V>(_ transform: ((Key, Value)) -> (K, V)?) -> [K: V] { var result: [K: V] = [:] for item in self { if let entry = transform(item) { result[entry.0] = entry.1 } } return result } /// Filter the dictionary using closure /// /// - Parameter f: <#f description#> /// - Returns: <#return value description#> public func filter(_ check: (Key, Value) -> Bool) -> [Key: Value] { var result = [Key: Value]() for (key, value) in self { if check(key, value) { result[key] = value } } return result } /// Merge dictionary with another dictionary and returns result. When key values has intersections, values from the source dictionary will override existing values /// /// - Parameter with: Source dictionary /// - Returns: New dictionary with self and source elemenct public func merged(with source: [Key: Value]?) -> [Key: Value] { guard let source = source else { return self } var res = self res.merge(with: source) return res } /// Merge the dictionary with another dictionary. When key values has intersections, values from the source dictionary will override existing values /// /// - Parameter with: Source dictionary /// - Returns: New dictionary with self and source elemenct public mutating func merge(with source: [Key: Value]?) { guard let source = source else { return } for (key, value) in source { self[key] = value } } private func _check(_ list: CNLArray, _ path: String = "") { list.forEach { item in for (k, v) in item { if v is Bool || v is String || v is Int || v is Double || v is [Int] || v is [String] { return } if let d = v as? CNLDictionary { _check([d], "\(path).\(k)") return } if let a = v as? CNLArray { _check(a, "\(path).\(k)") return } let t = type(of: v) fatalError("Invalid value: \(path)\(k) = \(v) of type \(t)") } } } /// Checks dictionary conformity NSDictionary.write(to:atomically). Calls fatalError() if not public func check() { if let dictionry = self as? CNLDictionary { _check([dictionry]) return } fatalError("Check failed") } /// Stores plist representation of the dictionary to the url /// /// - Parameters: /// - url: <#url description#> /// - atomically: <#atomically description#> public func write(to url: URL, atomically: Bool = true) { check() let dictionary = NSDictionary(dictionary: self) dictionary.write(to: url, atomically: atomically) } }
mit
05f5a42f86b5ecfa0236db648047f788
33.51073
167
0.576048
4.517416
false
false
false
false
peaks-cc/iOS11_samplecode
chapter_12/HomeKitSample/App/Code/Controller/CharacteristicViewController.swift
1
8453
// // CharacteristicViewController.swift // // Created by ToKoRo on 2017-08-21. // import UIKit import HomeKit class CharacteristicViewController: UITableViewController, ContextHandler { typealias ContextType = HMCharacteristic @IBOutlet weak var valueLabel: UILabel? @IBOutlet weak var valueTypeLabel: UILabel? @IBOutlet weak var uniqueIdentifierLabel: UILabel? @IBOutlet weak var characteristicTypeLabel: UILabel? @IBOutlet weak var localizedDescriptionLabel: UILabel? @IBOutlet weak var propertyIsReadableLabel: UILabel? @IBOutlet weak var propertyIsWriteableLabel: UILabel? @IBOutlet weak var propertyIsHiddenLabel: UILabel? @IBOutlet weak var propertySupportsEventLabel: UILabel? @IBOutlet weak var formatLabel: UILabel? @IBOutlet weak var unitsLabel: UILabel? @IBOutlet weak var validValuesLabel: UILabel? @IBOutlet weak var minimumValueLabel: UILabel? @IBOutlet weak var maximumValueLabel: UILabel? @IBOutlet weak var stepValueLabel: UILabel? @IBOutlet weak var maxLengthLabel: UILabel? @IBOutlet weak var manufacturerDescriptionLabel: UILabel? @IBOutlet weak var isNotificationEnabledLabel: UILabel? @IBInspectable var isCreateMode: Bool = false var characteristic: HMCharacteristic { return context! } var targetValue: NSCopying? override func viewDidLoad() { super.viewDidLoad() refresh() } private func refresh() { if let value = targetValue { valueLabel?.text = String(describing: value) valueTypeLabel?.text = String(describing: type(of: value)) } else if let value = characteristic.value { valueLabel?.text = String(describing: value) valueTypeLabel?.text = String(describing: type(of: value)) } else { valueLabel?.text = "nil" valueTypeLabel?.text = "nil" } uniqueIdentifierLabel?.text = characteristic.uniqueIdentifier.uuidString characteristicTypeLabel?.text = String(describing: CharacteristicType(typeString: characteristic.characteristicType)) print("# characteristicType: \(characteristic.characteristicType)") localizedDescriptionLabel?.text = characteristic.localizedDescription propertyIsReadableLabel?.text = String(characteristic.properties.contains(HMCharacteristicPropertyReadable)) propertyIsWriteableLabel?.text = String(characteristic.properties.contains(HMCharacteristicPropertyWritable)) propertyIsHiddenLabel?.text = String(characteristic.properties.contains(HMCharacteristicPropertyHidden)) propertySupportsEventLabel?.text = String(characteristic.properties.contains(Notification.Name.HMCharacteristicPropertySupportsEvent.rawValue)) if let metadata = characteristic.metadata { formatLabel?.text = metadata.format unitsLabel?.text = metadata.units validValuesLabel?.text = metadata.validValues?.map { $0.stringValue }.joined(separator: ",") minimumValueLabel?.text = metadata.minimumValue?.stringValue maximumValueLabel?.text = metadata.maximumValue?.stringValue stepValueLabel?.text = metadata.stepValue?.stringValue maxLengthLabel?.text = metadata.maxLength?.stringValue manufacturerDescriptionLabel?.text = metadata.manufacturerDescription } else { formatLabel?.text = nil unitsLabel?.text = nil validValuesLabel?.text = nil minimumValueLabel?.text = nil maximumValueLabel?.text = nil stepValueLabel?.text = nil maxLengthLabel?.text = nil manufacturerDescriptionLabel?.text = nil } isNotificationEnabledLabel?.text = String(characteristic.isNotificationEnabled) } private func displayValueAction() { let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) if characteristic.properties.contains(HMCharacteristicPropertyReadable) { alert.addAction(UIAlertAction(title: "現在のvalueを取得", style: .default) { [weak self] _ in self?.updateValue() }) } if characteristic.properties.contains(HMCharacteristicPropertyWritable) { alert.addAction(UIAlertAction(title: "valueを上書き", style: .default) { [weak self] _ in self?.displayWriteValueAlert() }) } alert.addAction(UIAlertAction(title: "キャンセル", style: .cancel)) present(alert, animated: true) } private func updateValue() { characteristic.readValue { [weak self] error in if let error = error { print("# error: \(error)") } self?.refresh() } } private func displayWriteValueAlert() { let characteristic = self.characteristic let alert = UIAlertController(title: nil, message: "設定するvalueを入力してください", preferredStyle: .alert) alert.addTextField { textField in if let value = characteristic.value { textField.text = String(describing: value) } } alert.addAction(UIAlertAction(title: "OK", style: .default) { [weak self] _ in guard let value = alert.textFields?.first?.text, value.count > 0 else { return } self?.handleNewValue(value) }) alert.addAction(UIAlertAction(title: "キャンセル", style: .cancel)) present(alert, animated: true) } private func handleNewValue(_ stringValue: String) { let value = stringValue.characteristicValue(for: characteristic.metadata?.format) if isCreateMode { self.targetValue = value as? NSCopying refresh() } else { writeValue(value) } } private func writeValue(_ value: Any?) { characteristic.writeValue(value) { [weak self] error in if let error = error { print("# error: \(error)") } self?.refresh() } } private func displayEnableNotificationAction() { let message = "Enables/disables notifications or indications for the value of the characteristic" let alert = UIAlertController(title: nil, message: message, preferredStyle: .actionSheet) alert.addAction(UIAlertAction(title: "Enable", style: .default) { [weak self] _ in self?.enableNotification(true) }) alert.addAction(UIAlertAction(title: "Disable", style: .default) { [weak self] _ in self?.enableNotification(false) }) alert.addAction(UIAlertAction(title: "キャンセル", style: .cancel)) present(alert, animated: true) } private func enableNotification(_ enable: Bool) { characteristic.enableNotification(enable) { [weak self] error in if let error = error { print("# error: \(error)") } self?.refresh() } } @IBAction func doneButtonDidTap(sender: AnyObject) { let value: NSCopying? = { if let value = targetValue { return value } else if let value = characteristic.value as? NSCopying { return value } else { return nil } }() guard let validValue = value else { return } let action = HMCharacteristicWriteAction(characteristic: characteristic, targetValue: validValue) ResponderChain(from: self).send(action, protocol: ActionSelector.self) { action, handler in handler.selectAction(action) } dismiss(animated: true) } } // MARK: - UITableViewDelegate extension CharacteristicViewController { override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { defer { tableView.deselectRow(at: indexPath, animated: true) } switch (indexPath.section, indexPath.row) { case (0, 0): if isCreateMode { displayWriteValueAlert() } else { displayValueAction() } case (3, 0): displayEnableNotificationAction() default: break } } }
mit
2fdd4de1f22a15f155b764daec122736
37.077273
125
0.637102
5.170988
false
false
false
false
muhasturk/smart-citizen-ios
Smart Citizen/Core/Contants.swift
1
2131
/** * Copyright (c) 2016 Mustafa Hastürk * * 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 var AppReadOnlyUser: User { let userData = UserDefaults.standard.object(forKey: AppConstants.DefaultKeys.APP_USER) as! Data let user = NSKeyedUnarchiver.unarchiveObject(with: userData) as! User return user } struct AppSegues { static let doLoginSegue = "doLogin" static let doSignUpSegue = "doSignUp" static let doLogoutSegue = "doLogout" static let pushReportCategory = "pushReportCategory" static let mapReportDetail = "mapReportDetail" static let dashboardReportDetail = "dashboardReportDetail" static let profileReportDetail = "profileReportDetail" } struct AppReuseIdentifier { static let mapCustomAnnotationView = "SmartAnnotationView" } struct AppColors { } struct AppCell { static let categoryCell = "categoryCell" static let reportCell = "profileCell" } struct AppConstants { struct DefaultKeys { static let DEVICE_TOKEN = "KEY_DEVICE_TOKEN" static let APP_ALIVE = "KEY_APP_ALIVE" static let APP_USER = "KEY_APP_USER" } }
mit
46ec5350a5609d19a03379da001b3f83
33.354839
97
0.756808
4.243028
false
false
false
false
yuppielabel/YPDrawSignatureView
SignatureTest/SignatureTestTests/SignatureViewTest.swift
2
4444
// YPDrawSignatureView is open source // Version 1.2.1 // // Copyright (c) 2014 - 2019 The YPDrawSignatureView Project Contributors // Available under the MIT license // // https://github.com/GJNilsen/YPDrawSignatureView/blob/master/LICENSE License Information // https://github.com/GJNilsen/YPDrawSignatureView/blob/master/README.md Project Contributors import XCTest @testable import SignatureTest class SignatureViewTest: XCTestCase { var signatureView: YPDrawSignatureView! override func setUp() { super.setUp() signatureView = YPDrawSignatureView(frame: CGRect(x: 0, y: 0, width: 10, height: 10)) } func testFrame() { let frame = CGRect(x: 0, y: 0, width: 10, height: 10) XCTAssertEqual(signatureView.frame, frame) } func testClearSignature() { signatureView.clear() signatureView.strokeColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0) signatureView.injectBezierPath(doodle()) signatureView.draw(signatureView.frame) signatureView.clear() XCTAssertEqual(UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.0), getPixelColor(view2Image(signatureView), at: CGPoint(x: 4, y: 4))) } func testDrawSignature() { signatureView.clear() signatureView.strokeColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0) signatureView.injectBezierPath(doodle()) signatureView.draw(signatureView.frame) XCTAssertNotEqual(signatureView.backgroundColor, getPixelColor(view2Image(signatureView), at: CGPoint(x: 4, y: 4))) } func testGetSignature() { signatureView.clear() signatureView.strokeColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0) signatureView.injectBezierPath(doodle()) signatureView.draw(signatureView.frame) let signature = signatureView.getSignature() XCTAssertNotEqual(signatureView.backgroundColor, getPixelColor(signature!, at: CGPoint(x: 4, y: 4))) } } // Helper Methods extension SignatureViewTest { // Sample signature func doodle() -> UIBezierPath { let bezierPath = UIBezierPath() bezierPath.move(to: CGPoint(x: 4, y: 4)) bezierPath.addCurve(to: CGPoint(x: 4.1, y: 4.1), controlPoint1: CGPoint(x: 7.57, y: 3.33), controlPoint2: CGPoint(x: 1.12, y: 3.43)) bezierPath.addCurve(to: CGPoint(x: 4, y: 4.1), controlPoint1: CGPoint(x: 7.08, y: 4.77), controlPoint2: CGPoint(x: 11.14, y: 0.05)) bezierPath.addCurve(to: CGPoint(x: 4, y: 5), controlPoint1: CGPoint(x: -3.14, y: 8.15), controlPoint2: CGPoint(x: 4, y: 5)) bezierPath.addCurve(to: CGPoint(x: 4.1, y: 4), controlPoint1: CGPoint(x: 4, y: 5), controlPoint2: CGPoint(x: 1.72, y: 3.33)) bezierPath.addCurve(to: CGPoint(x: 4.2, y: 4.2), controlPoint1: CGPoint(x: 6.48, y: 4.67), controlPoint2: CGPoint(x: -3.54, y: 7.57)) bezierPath.addCurve(to: CGPoint(x: 4, y: 4.2), controlPoint1: CGPoint(x: 11.94, y: 0.83), controlPoint2: CGPoint(x: 4, y: 11.62)) bezierPath.addCurve(to: CGPoint(x: 4.2, y: 4), controlPoint1: CGPoint(x: 4, y: -3.22), controlPoint2: CGPoint(x: 7.18, y: 4)) bezierPath.addCurve(to: CGPoint(x: 4.2, y: 4.2), controlPoint1: CGPoint(x: 1.22, y: 4), controlPoint2: CGPoint(x: 4.2, y: 4.2)) return bezierPath } // Creates an UIImage of a provided view func view2Image(_ view: UIView) -> UIImage { UIGraphicsBeginImageContext(view.frame.size) view.layer.render(in: UIGraphicsGetCurrentContext()!) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image! } // Gets the color at a specific location in a provided view func getPixelColor(_ image: UIImage, at pos: CGPoint) -> UIColor { let pixelData = image.cgImage!.dataProvider!.data let data: UnsafePointer<UInt8> = CFDataGetBytePtr(pixelData) let pixelInfo: Int = ((Int(image.size.width) * Int(pos.y)) + Int(pos.x)) * 4 let r = CGFloat(data[pixelInfo]) / CGFloat(255.0) let g = CGFloat(data[pixelInfo+1]) / CGFloat(255.0) let b = CGFloat(data[pixelInfo+2]) / CGFloat(255.0) let a = CGFloat(data[pixelInfo+3]) / CGFloat(255.0) return UIColor(red: r, green: g, blue: b, alpha: a) } }
mit
0c7b527de496063b31ba2841bc7a6bc8
41.730769
143
0.641764
3.580983
false
true
false
false
kousun12/RxSwift
RxSwift/Observables/Observable+Creation.swift
4
6438
// // Observable+Creation.swift // Rx // // Created by Krunoslav Zaher on 3/21/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation // MARK: create /** Creates an observable sequence from a specified subscribe method implementation. - parameter subscribe: Implementation of the resulting observable sequence's `subscribe` method. - returns: The observable sequence with the specified implementation for the `subscribe` method. */ @warn_unused_result(message="http://git.io/rxs.uo") public func create<E>(subscribe: (AnyObserver<E>) -> Disposable) -> Observable<E> { return AnonymousObservable(subscribe) } // MARK: empty /** Returns an empty observable sequence, using the specified scheduler to send out the single `Completed` message. - returns: An observable sequence with no elements. */ @warn_unused_result(message="http://git.io/rxs.uo") public func empty<E>() -> Observable<E> { return Empty<E>() } // MARK: never /** Returns a non-terminating observable sequence, which can be used to denote an infinite duration. - returns: An observable sequence whose observers will never get called. */ @warn_unused_result(message="http://git.io/rxs.uo") public func never<E>() -> Observable<E> { return Never() } // MARK: just /** Returns an observable sequence that contains a single element. - parameter element: Single element in the resulting observable sequence. - returns: An observable sequence containing the single specified element. */ @warn_unused_result(message="http://git.io/rxs.uo") public func just<E>(element: E) -> Observable<E> { return Just(element: element) } // MARK: of /** This method creates a new Observable instance with a variable number of elements. - returns: The observable sequence whose elements are pulled from the given arguments. */ @warn_unused_result(message="http://git.io/rxs.uo") public func sequenceOf<E>(elements: E ...) -> Observable<E> { return AnonymousObservable { observer in for element in elements { observer.on(.Next(element)) } observer.on(.Completed) return NopDisposable.instance } } extension SequenceType { /** Converts a sequence to an observable sequence. - returns: The observable sequence whose elements are pulled from the given enumerable sequence. */ @warn_unused_result(message="http://git.io/rxs.uo") public func asObservable() -> Observable<Generator.Element> { return AnonymousObservable { observer in for element in self { observer.on(.Next(element)) } observer.on(.Completed) return NopDisposable.instance } } } // MARK: fail /** Returns an observable sequence that terminates with an `error`. - returns: The observable sequence that terminates with specified error. */ @warn_unused_result(message="http://git.io/rxs.uo") public func failWith<E>(error: ErrorType) -> Observable<E> { return FailWith(error: error) } // MARK: defer /** Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. - parameter observableFactory: Observable factory function to invoke for each observer that subscribes to the resulting sequence. - returns: An observable sequence whose observers trigger an invocation of the given observable factory function. */ @warn_unused_result(message="http://git.io/rxs.uo") public func deferred<E>(observableFactory: () throws -> Observable<E>) -> Observable<E> { return Deferred(observableFactory: observableFactory) } /** Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to run the loop send out observer messages. - parameter initialState: Initial state. - parameter condition: Condition to terminate generation (upon returning `false`). - parameter iterate: Iteration step function. - parameter scheduler: Scheduler on which to run the generator loop. - returns: The generated sequence. */ @warn_unused_result(message="http://git.io/rxs.uo") public func generate<E>(initialState: E, condition: E throws -> Bool, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance, iterate: E throws -> E) -> Observable<E> { return Generate(initialState: initialState, condition: condition, iterate: iterate, resultSelector: { $0 }, scheduler: scheduler) } /** Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to generate and send out observer messages. - parameter start: The value of the first integer in the sequence. - parameter count: The number of sequential integers to generate. - parameter scheduler: Scheduler to run the generator loop on. - returns: An observable sequence that contains a range of sequential integral numbers. */ @warn_unused_result(message="http://git.io/rxs.uo") public func range(start: Int, _ count: Int, _ scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable<Int> { return RangeProducer<Int>(start: start, count: count, scheduler: scheduler) } /** Generates an observable sequence that repeats the given element infinitely, using the specified scheduler to send out observer messages. - parameter element: Element to repeat. - parameter scheduler: Scheduler to run the producer loop on. - returns: An observable sequence that repeats the given element infinitely. */ @warn_unused_result(message="http://git.io/rxs.uo") public func repeatElement<E>(element: E, _ scheduler: ImmediateSchedulerType) -> Observable<E> { return RepeatElement(element: element, scheduler: scheduler) } /** Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime. - parameter resourceFactory: Factory function to obtain a resource object. - parameter observableFactory: Factory function to obtain an observable sequence that depends on the obtained resource. - returns: An observable sequence whose lifetime controls the lifetime of the dependent resource object. */ @warn_unused_result(message="http://git.io/rxs.uo") public func using<S, R: Disposable>(resourceFactory: () throws -> R, observableFactory: R throws -> Observable<S>) -> Observable<S> { return Using(resourceFactory: resourceFactory, observableFactory: observableFactory) }
mit
731f5b3c2ea31fe75de46741a92b5d25
35.579545
181
0.741069
4.361789
false
false
false
false
talk2junior/iOSND-Beginning-iOS-Swift-3.0
Playground Collection/Part 1 - Pirate Fleet 1/Writing Structs with Properties/Writing Structs with Properties Exercises.playground/Contents.swift
1
2791
//: ## Writing Structs with Properties Exercises //: In these exercises, you work with structs and their properties. //### Exercise 1 //Create a struct called Author that contains the following properties: struct Author { let firstName: String let lastName: String var living: Bool } //### Exercise 2 //Create a struct called Book that contains the following properties: struct Book { let title: String let author: Author let pages: Int var numberOfStars: Double var description: String var genre: String } //### Exercise 3 //Create instances of authors and books based on the following statements: //- Wilson Rawls was born on September 24, 1913 and passed away on December 16, 1984. He wrote the children's book "Where the Red Fern Grows". This book is about a young boy and his hunting dogs. It is 245 pages and has a 4/5 rating by Common Sense Media. let rawls = Author(firstName: "Wilson", lastName: "Rawls", living: false) let whereTheRedFernGrows = Book(title: "Where the Red Fern Grows", author: rawls, pages: 245, numberOfStars: 4, description: "This book is about a young boy and his hunting does.", genre: "Children's Book") whereTheRedFernGrows.title whereTheRedFernGrows.author whereTheRedFernGrows.pages whereTheRedFernGrows.numberOfStars whereTheRedFernGrows.description whereTheRedFernGrows.genre //- John Ronald Reuel (J. R. R.) Tolkien was born on January 3, 1892 and passed away on September 2, 1973. He wrote the fantasy book "The Hobbit". "The Hobbit" follows the treasure-seeking quest of hobbit Bilbo Baggins and it is about 300 pages long. It has a 4.5/5 rating by Barnes & Noble. let tolkien = Author(firstName: "J.R.R.", lastName: "Tolkien", living: false) let theHobbit = Book(title: "The Hobbit", author: tolkien, pages: 300, numberOfStars: 4.5, description: "\"The Hobbit\" follows the treasure-seeking quest of hobbit Bilbo Baggin.", genre: "Fantasy Book") theHobbit.title theHobbit.author theHobbit.description theHobbit.genre //- Mary Shelley was born on August 30, 1797 and passed away on February 1, 1851. She wrote the Gothic novel "Frankenstein". "Frankenstein" is about a young science student named Victor Frankenstein who creates a sentient creature in an unorthodox scientific experiment. It is 280 pages long and has a 4.7/5 rating from Google user reviews. let shelley = Author(firstName: "Mary", lastName: "Shelley", living: false) let frankenstein = Book(title: "Frankenstein", author: shelley, pages: 280, numberOfStars: 4.7, description: "\"Frankenstein\" is about a young science student named Victor Frankenstein who creates a sentient creature in an unorthodox scientific experiment.", genre: "Gothic") frankenstein.author frankenstein.genre frankenstein.description frankenstein.pages
mit
7e3a557591692e19ed58426991d5e5eb
42.609375
340
0.761734
3.569054
false
false
false
false
ArtisOracle/SATextField
source/SATextField/SATextField.swift
1
9623
// // SATextField.swift // SATextField // // Created by Stefan Arambasich on 9/3/2015. // Copyright (c) 2015 Stefan Arambasich. All rights reserved. // import UIKit /// Custom `UITextField` featuring a material design-like placeholder label. When unfocused, the /// placeholder acts the same. When focused, the placeholder label slides above the field so the user /// can still enter her values without losing a sense of what field she was on. @IBDesignable open class SATextField: UITextField { // MARK: - // MARK: Public Properties // MARK: UI // MARK: `IBInspectable`s /// Set the custom placeholder text using this propery. @IBInspectable open var placeholderText: String = "" { didSet { configurePlaceholder(usingText: placeholderText) } } /// Use this to change the text color of the placeholder for the default state. Defaults to /// gray. @IBInspectable open var placeholderTextColor: UIColor = .gray { didSet { configurePlaceholder(usingText: placeholderText) } } /// Use this to change the text color of the placeholder for the slid state. Defaults to white. @IBInspectable open var placeholderTextColorFocused: UIColor = .white { didSet { configurePlaceholder(usingText: placeholderText) } } /// Whether to slide the placeholder text from inside the text field /// to the top of the text field. @IBInspectable open var slidesPlaceholder: Bool = true /// How long to animate the placeholder slide. open var slideAnimationDuration: TimeInterval = 0.15 // MARK: - // MARK: Private Properties /// An X-offset for the placeholder text from its bounds. private var placeholderOffsetXDefault: CGFloat = 0.0 /// An X-offset for the placeholder while slid upward. private var placeholderOffsetXSlid: CGFloat = 0.0 /// An Y-offset for the placeholder text from its bounds. private var placeholderOffsetYDefault: CGFloat = 0.0 /// An Y-offset for the placeholder while slid upward. private var placeholderOffsetYSlid: CGFloat = 0.0 /// Leading constraint of the `UILabel` of the sliding placeholder. private var slidingPlaceholderLeadingConstraint: NSLayoutConstraint? /// Center-Y constraint of the `UILabel` of the sliding placeholder. private var slidingPlaceholderCenterYConstraint: NSLayoutConstraint? /// The placeholder label. private var placeholderLabel: UILabel? // MARK: - // MARK: Initialization public override init(frame: CGRect) { super.init(frame: frame) commonInit() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } /// Single point of initialization logic for `self`. private func commonInit() { addTarget( self, action: #selector(textFieldDidBeginEditing(_:)), for: .editingDidBegin ) addTarget( self, action: #selector(textFieldDidEndEditing(_:)), for: .editingDidEnd ) addTarget( self, action: #selector(textFieldDidChange(_:)), for: .editingChanged ) } // MARK: - // MARK: Overrides open override func layoutSubviews() { super.layoutSubviews() configurePlaceholder(usingText: placeholderText) setSlidingPlaceholder(false) } } // MARK: - // MARK: Text field delegation / handlers extension SATextField { @objc open func textFieldDidChange(_ textField: UITextField) { setSlidingPlaceholder() } @objc open func textFieldDidBeginEditing(_ textField: UITextField) { setSlidingPlaceholder() } @objc open func textFieldDidEndEditing(_ textField: UITextField) { setSlidingPlaceholder() } } // MARK: - // MARK: Placeholder Adjustment private extension SATextField { /// Moves and sets the sldiing holder into the position it should be given the text field's state. /// /// - Parameter animated: Whether to animate the transition. True by default. func setSlidingPlaceholder(_ animated: Bool = true) { if isFirstResponder || !(text?.isEmpty ?? true) { expandPlaceholder(animated: animated) } else { collapsePlaceholder(animated: animated) } } /// Configures the placeholder label's text and position. If the text is empty, removes the /// label from the view. /// /// - Parameter text: The text of the placeholder. func configurePlaceholder(usingText text: String) { if text.isEmpty == false { let label = placeholderLabel ?? UILabel(frame: placeholderRect(forBounds: bounds)) label.translatesAutoresizingMaskIntoConstraints = false label.text = placeholderText label.textColor = placeholderTextColor label.textAlignment = .left label.font = font if label.superview == nil { addSubview(label) addConstraints(makePlaceholderConstraints(for: label)) } placeholderOffsetYSlid = placeholderOffsetYDefault - label.frame.height - 3.0 label.isHidden = false placeholderLabel = label } else { placeholderLabel?.removeFromSuperview() } } func makePlaceholderConstraints(for label: UILabel) -> [NSLayoutConstraint] { let width, height: NSLayoutConstraint if #available(iOS 11, *) { slidingPlaceholderLeadingConstraint = label.leadingAnchor.constraint(equalTo: leadingAnchor) slidingPlaceholderCenterYConstraint = label.centerYAnchor.constraint(equalTo: centerYAnchor) width = label.widthAnchor.constraint(equalTo: widthAnchor) height = label.heightAnchor.constraint(equalTo: heightAnchor, constant: 2.0) } else { slidingPlaceholderLeadingConstraint = NSLayoutConstraint( item: label, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1.0, constant: placeholderOffsetXDefault) slidingPlaceholderCenterYConstraint = NSLayoutConstraint( item: label, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1.0, constant: placeholderOffsetYDefault) width = NSLayoutConstraint(item: label, attribute: .width, relatedBy: .equal, toItem: self, attribute: .width, multiplier: 1.0, constant: 0.0) height = NSLayoutConstraint(item: label, attribute: .height, relatedBy: .equal, toItem: self, attribute: .height, multiplier: 1.0, constant: 2.0) } return [slidingPlaceholderLeadingConstraint!, slidingPlaceholderCenterYConstraint!, width, height ] } func collapsePlaceholder(animated: Bool = true) { let changes = { guard let placeholderLabel = self.placeholderLabel else { return } self.slidingPlaceholderLeadingConstraint?.constant = self.placeholderOffsetXDefault self.slidingPlaceholderCenterYConstraint?.constant = self.placeholderOffsetYDefault placeholderLabel.setAnchorPoint(CGPoint(x: 0.5, y: 0.5)) placeholderLabel.transform = CGAffineTransform.identity.scaledBy(x: 1.0, y: 1.0) placeholderLabel.textColor = self.isFirstResponder ? self.placeholderTextColorFocused : self.placeholderTextColor self.layoutIfNeeded() } animated ? UIView.animate(withDuration: slideAnimationDuration, animations: changes) : changes() } func expandPlaceholder(animated: Bool = true) { let changes = { self.slidingPlaceholderLeadingConstraint?.constant = self.placeholderOffsetXSlid self.slidingPlaceholderCenterYConstraint?.constant = self.placeholderOffsetYSlid self.placeholderLabel?.setAnchorPoint(CGPoint(x: 0.625, y: 0.5)) self.placeholderLabel?.transform = CGAffineTransform.identity.scaledBy(x: 0.8, y: 0.8) self.placeholderLabel?.textColor = self.isFirstResponder ? self.placeholderTextColorFocused : self.placeholderTextColor self.layoutIfNeeded() } animated ? UIView.animate(withDuration: slideAnimationDuration, animations: changes) : changes() } } // MARK: - // MARK: `UIView` Extensions private extension UIView { /// Sets the anchor point. Used for performing animations around points other than the center. /// /// - Parameter anchorPoint: The desired anchor point of the view. func setAnchorPoint(_ anchorPoint: CGPoint) { var newPoint = CGPoint( x: bounds.size.width * anchorPoint.x, y: bounds.size.height * anchorPoint.y), oldPoint = CGPoint( x: bounds.size.width * layer.anchorPoint.x, y: bounds.size.height * layer.anchorPoint.y) newPoint = newPoint.applying(transform) oldPoint = oldPoint.applying(transform) var position = layer.position position.x -= oldPoint.x position.x += newPoint.x position.y -= oldPoint.y position.y += newPoint.y layer.position = position layer.anchorPoint = anchorPoint } }
mit
048d34e69f19f9761c9ffd563c64cd04
33.992727
104
0.644601
5.154258
false
false
false
false
Coderian/SwiftedKML
SwiftedKML/Elements/MinFadeExtent.swift
1
1132
// // MinFadeExtent.swift // SwiftedKML // // Created by 佐々木 均 on 2016/02/02. // Copyright © 2016年 S-Parts. All rights reserved. // import Foundation /// KML MinFadeExtent /// /// [KML 2.2 shcema](http://schemas.opengis.net/kml/2.2.0/ogckml22.xsd) /// /// <element name="minFadeExtent" type="double" default="0.0"/> public class MinFadeExtent:SPXMLElement,HasXMLElementValue,HasXMLElementSimpleValue { public static var elementName: String = "minFadeExtent" public override var parent:SPXMLElement! { didSet { // 複数回呼ばれたて同じものがある場合は追加しない if self.parent.childs.contains(self) == false { self.parent.childs.insert(self) switch parent { case let v as Lod: v.value.minFadeExtent = self default: break } } } } public var value: Double = 0.0 public func makeRelation(contents:String, parent:SPXMLElement) -> SPXMLElement{ self.value = Double(contents)! self.parent = parent return parent } }
mit
ebcaa4befaa3ac14f7c2448ccf52e8e2
28.861111
85
0.613023
3.812057
false
false
false
false
nalexn/ViewInspector
Sources/ViewInspector/SwiftUI/DelayedPreferenceView.swift
1
2977
import SwiftUI @available(iOS 13.0, macOS 10.15, tvOS 13.0, *) public extension InspectableView { func overlayPreferenceValue(_ index: Int? = nil) throws -> InspectableView<ViewType.Overlay> { return try contentForModifierLookup .overlay(parent: self, api: .overlayPreferenceValue, index: index) } func backgroundPreferenceValue(_ index: Int? = nil) throws -> InspectableView<ViewType.Overlay> { return try contentForModifierLookup .overlay(parent: self, api: .backgroundPreferenceValue, index: index) } } @available(iOS 13.0, macOS 10.15, tvOS 13.0, *) internal extension ViewType { struct DelayedPreferenceView { } struct PreferenceReadingView { } } // MARK: - DelayedPreferenceView @available(iOS 13.0, macOS 10.15, tvOS 13.0, *) extension ViewType.DelayedPreferenceView: SingleViewContent { static func child(_ content: Content) throws -> Content { let provider = try Inspector.cast(value: content.view, type: SingleViewProvider.self) let view = try provider.view() return try Inspector.unwrap(content: Content(view, medium: content.medium)) } } // MARK: - PreferenceReadingView @available(iOS 13.0, macOS 10.15, tvOS 13.0, *) extension ViewType.PreferenceReadingView: SingleViewContent { static func child(_ content: Content) throws -> Content { let provider = try Inspector.cast( value: content.view, type: SingleViewProvider.self) let view = try provider.view() let medium = content.medium.resettingViewModifiers() return try Inspector.unwrap(content: Content(view, medium: medium)) } } @available(iOS 13.0, macOS 10.15, tvOS 13.0, *) extension _DelayedPreferenceView: SingleViewProvider { func view() throws -> Any { typealias Builder = (_PreferenceValue<Key>) -> Content let readingViewBuilder = try Inspector.attribute(label: "transform", value: self, type: Builder.self) let prefValue = _PreferenceValue<Key>() return readingViewBuilder(prefValue) } } @available(iOS 13.0, macOS 10.15, tvOS 13.0, *) private extension _PreferenceValue { struct Allocator4 { let data: Int32 = 0 } struct Allocator8 { let data: Int64 = 0 } init() { switch MemoryLayout<Self>.size { case 4: self = unsafeBitCast(Allocator4(), to: _PreferenceValue<Key>.self) case 8: self = unsafeBitCast(Allocator8(), to: _PreferenceValue<Key>.self) default: fatalError(MemoryLayout<Self>.actualSize()) } } } @available(iOS 13.0, macOS 10.15, tvOS 13.0, *) extension _PreferenceReadingView: SingleViewProvider { func view() throws -> Any { typealias Builder = (Key.Value) -> Content let builder = try Inspector.attribute(label: "transform", value: self, type: Builder.self) let value = Key.defaultValue return builder(value) } }
mit
abad0d871f2c6b8ab3f60f121e1cdf97
32.829545
109
0.66342
4.106207
false
false
false
false
ErusaevAP/DStack
Sources/DSExtensions/UIView+Utils.swift
1
914
// // UIView+Utils.swift // Pods // // Created by Andrei Erusaev on 8/2/17. // // public extension UIView { func add(subviews: UIView...) { add(subviews: subviews) } func add(subviews: [UIView?]) { subviews.compactMap { $0 }.forEach { add(subviews: $0) } } @discardableResult func add(inRootView rootView: UIView) -> Self { translatesAutoresizingMaskIntoConstraints = false rootView.addSubview(self) return self } } public extension Array where Element == UIView { func stack( axis: NSLayoutConstraint.Axis? = nil, spacing: CGFloat? = nil, alignment: UIStackView.Alignment? = nil, distribution: UIStackView.Distribution? = nil ) -> UIStackView { UIStackView(arrangedSubviews: self) .set(axis: axis, spacing: spacing, alignment: alignment, distribution: distribution) } }
mit
adb4b115248aee68db2cb404e18f03d0
20.761905
96
0.623632
4.251163
false
false
false
false
Byjuanamn/AzureStorageMobileiOS
Azure/Storage/MyVideoBlog/MyVideoBlog/MyTimelineController.swift
1
4573
import UIKit class MyTimelineController: UITableViewController { let client = MSClient(applicationURL: NSURL(string: "https://myvideoblogjuanamn.azure-mobile.net/"), applicationKey: "CGrpsXnMMsSQgDmjLVpetVqHuoDtlz11") var model : [AnyObject]? override func viewDidLoad() { super.viewDidLoad() self.title = "Mis videos blog" let plusButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "addNewVideoPost:") self.navigationItem.rightBarButtonItem = plusButton // modelo publicar populateModel() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows var rows = 0 if model != nil { rows = (model?.count)! } return rows } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("videos", forIndexPath: indexPath) cell.textLabel?.text = model![indexPath.row]["titulo"] as? String return cell } // MARK: - Popular el modelo func populateModel(){ let tablaVideos = client?.tableWithName("videoblogs") // prueba 1: obtener datos via MSTable // tablaVideos?.readWithCompletion({ (result:MSQueryResult?, error:NSError?) -> Void in // // if error == nil { // self.model = result?.items // self.tableView.reloadData() // } // // }) // prueba 2: Obtener datos via MSQuery let query = MSQuery(table: tablaVideos) // Incluir predicados, constrains para filtrar, para limitar el numero de filas o delimitar el numero de columnas query.orderByAscending("titulo") query.readWithCompletion { (result:MSQueryResult?, error:NSError?) -> Void in if error == nil { self.model = result?.items self.tableView.reloadData() } } } // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.beginUpdates() tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) model!.removeAtIndex(indexPath.row) tableView.endUpdates() } } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { performSegueWithIdentifier("detailPost", sender:indexPath) } // MARK: - Añadir un nuevo post func addNewVideoPost(sender : AnyObject){ performSegueWithIdentifier("addNewItem", sender: sender) } // 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. guard let identifier = segue.identifier else{ print("no tenemos identifier") return } switch identifier{ case "addNewItem": let vc = segue.destinationViewController as! ViewPostController // desde aqui podemos pasar alguna property vc.client = client break case "detailPost": let index = sender as? NSIndexPath let vc = segue.destinationViewController as! DetailPostController vc.client = client vc.record = model![(index?.row)!] break default: break } } }
mit
225c499b6b78b78430de6f9b443f8873
28.688312
157
0.597769
5.397875
false
false
false
false
HC1058503505/HCCardView
HCCardView/EmojiView/HCEmojiView.swift
1
3012
// // HCEmojiView.swift // HCCardView // // Created by UltraPower on 2017/5/31. // Copyright © 2017年 UltraPower. All rights reserved. // import UIKit class HCEmojiView: UIView { fileprivate let titles: [String] fileprivate let emojiViewStyle: HCCardViewStyle fileprivate var originOffsetX:CGFloat = 0 fileprivate let sectionsNumber:[Int] = [13, 15, 17, 20] fileprivate lazy var headerView: HCCardHeaderView = { let headerV = HCCardHeaderView(frame: CGRect(x: 0, y: 0, width: self.bounds.width, height: self.emojiViewStyle.headerViewHeight), titles: self.titles, headerViewStyle: self.emojiViewStyle) return headerV }() lazy var emojiContentView: HCEmojiViewContentView = { let emojiView = HCEmojiViewContentView(frame: CGRect(x: 0, y: self.emojiViewStyle.headerViewHeight, width: self.bounds.width, height: self.bounds.height - self.emojiViewStyle.headerViewHeight - 20), contentStyle: self.emojiViewStyle, titles: self.titles, sectionsNumber: self.sectionsNumber) return emojiView }() fileprivate lazy var pageControl: UIPageControl = { let pageCtr = UIPageControl(frame: CGRect(x: 0, y: self.emojiContentView.frame.maxY, width: self.bounds.width, height: 20)) pageCtr.backgroundColor = UIColor.orange pageCtr.currentPageIndicatorTintColor = UIColor.white pageCtr.tintColor = UIColor.cyan pageCtr.numberOfPages = self.sectionsNumber[0] / (self.emojiViewStyle.emojiMinimumRows * self.emojiViewStyle.emojiMinimumColumns) + 1; return pageCtr }() init(frame: CGRect, titles: [String], emojiViewStyle: HCCardViewStyle) { self.titles = titles self.emojiViewStyle = emojiViewStyle super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension HCEmojiView { func setupUI(){ addSubview(headerView) addSubview(emojiContentView) addSubview(pageControl) weak var weakSelf = self emojiContentView.emojiScroll = { section, numberOfRows, currentRow in weakSelf?.headerView.changeItem = {() -> Int in return section } weakSelf?.pageControl.numberOfPages = numberOfRows weakSelf?.pageControl.currentPage = currentRow } // emojiContentView.emojiViewDidScroll = self headerView.cardHeaderViewDelegate = emojiContentView } } //extension HCEmojiView: HCEmojiViewContentViewDelegate { // func emojiViewContentViewDidScroll(contentView: HCEmojiViewContentView, section: Int, numberOfRows: Int, currentRow: Int) { // headerView.changeItem = {() -> Int in // return section // } // // pageControl.numberOfPages = numberOfRows // pageControl.currentPage = currentRow // } //}
mit
9c2fbb5c97c901f6bdda827b75f8db35
32.808989
299
0.66434
4.552194
false
false
false
false
spweau/Test_DYZB
Test_DYZB/Test_DYZB/Classes/Main/Model/AnchorGroup.swift
1
1581
// // AnchorGroup.swift // Test_DYZB // // Created by Spweau on 2017/2/24. // Copyright © 2017年 sp. All rights reserved. // import UIKit class AnchorGroup: NSObject { /// 该组中对应的房间信息 var room_list : [[String : NSObject]]? { didSet { guard let room_list = room_list else { return } for dict in room_list { anchors.append(AnchorModel(dict: dict)) } } } /// 显示的标题 var tag_name : String = "" /// 组显示的图标 var icon_url : String = "home_header_normal" /// 定义主播的模型对象数组 lazy var anchors : [AnchorModel] = [AnchorModel]() // MARK:- 重写父类的构造函数 用来保存颜值主播的model override init() { } init(dict : [String : NSObject]) { super.init() setValuesForKeys(dict) } override func setValue(_ value: Any?, forUndefinedKey key: String) {} // 重写此方法 --> 是为了 定义主播的模型对象数组 // override func setValue(_ value: Any?, forKey key: String) { // // if key == "room_list" { // // if let dataArr = value as? [String : NSObject] { // // for dict in dataArr { // // 注意 : 这里有警告 ? 未知原因 // anchors.append(AnchorModel(dict: (dict as! [String : NSObject]))) // } // } // // } // // } }
mit
8b912bd01120f92b4cdc0b0117cdf60c
20.753846
87
0.47454
3.873973
false
false
false
false
nathawes/swift
test/attr/asynchandler.swift
2
1382
// RUN: %target-swift-frontend -typecheck -verify %s -enable-experimental-concurrency func globalAsyncFunction() async -> Int { 0 } @asyncHandler func asyncHandler1() { // okay, it's an async context let _ = await globalAsyncFunction() } @asyncHandler func asyncHandler2(fn: @autoclosure () async -> Int ) { // okay, it's an async context } @asyncHandler func asyncHandlerBad1() -> Int { 0 } // expected-error@-1{{'@asyncHandler' function can only return 'Void'}} @asyncHandler func asyncHandlerBad2() async { } // expected-error@-1{{'@asyncHandler' function cannot be 'async' itself}}{{25-31=}} @asyncHandler func asyncHandlerBad3() throws { } // expected-error@-1{{'@asyncHandler' function cannot throw}}{{25-32=}} @asyncHandler func asyncHandlerBad4(result: inout Int) { } // expected-error@-1{{'inout' parameter is not allowed in '@asyncHandler' function}} struct X { @asyncHandler func asyncHandlerMethod() { } @asyncHandler mutating func asyncHandlerMethodBad1() { } // expected-error@-1{{'@asyncHandler' function cannot be 'mutating'}}{{3-12=}} @asyncHandler init() { } // expected-error@-1{{@asyncHandler may only be used on 'func' declarations}} } // Inference of @asyncHandler protocol P { @asyncHandler func callback() } extension X: P { func callback() { // okay, it's an async context let _ = await globalAsyncFunction() } }
apache-2.0
b93210134ebbf1000a185e2aa00a1de1
25.576923
85
0.696816
3.656085
false
false
false
false
pablogsIO/MadridShops
MadridShops/Model/Mappers/MapShop.swift
1
2983
// // MapShop.swift // MadridShops // // Created by Pablo García on 29/09/2017. // Copyright © 2017 KC. All rights reserved. // import Foundation func mapShopIntoCityDataInformation(shop: Shop)-> CityDataInformation{ let cdi = CityDataInformation(name: shop.name!) cdi.latitude = shop.latitude cdi.longitude = shop.longitude if let image = shop.image{ cdi.image = image } if let logo = shop.logo{ cdi.logo = logo } if let telephone = shop.telephone{ cdi.telephone = telephone } if let shopURL = shop.shopURL{ cdi.shopUrl = shopURL } cdi.specialOffer = shop.specialOffer if let address = shop.address{ cdi.address = address } if let openingHours = shop.openingHours{ cdi.openingHours = openingHours } if let keywords = shop.keywords{ cdi.keywords = keywords } if let desc = shop.desc{ cdi.description = desc } if let bookingOperation = shop.bookingOperation{ cdi.bookingOperation = bookingOperation } if let bookingData = shop.bookingData{ cdi.bookingData = bookingData } return cdi } func mapActivityIntoCityDataInformation(activity: Activity)-> CityDataInformation{ let cdi = CityDataInformation(name: activity.name!) cdi.latitude = activity.latitude cdi.longitude = activity.longitude if let image = activity.image{ cdi.image = image } if let logo = activity.logo{ cdi.logo = logo } if let telephone = activity.telephone{ cdi.telephone = telephone } if let shopURL = activity.shopURL{ cdi.shopUrl = shopURL } cdi.specialOffer = activity.specialOffer if let address = activity.address{ cdi.address = address } if let openingHours = activity.openingHours{ cdi.openingHours = openingHours } if let keywords = activity.keywords{ cdi.keywords = keywords } if let desc = activity.desc{ cdi.description = desc } if let bookingOperation = activity.bookingOperation{ cdi.bookingOperation = bookingOperation } if let bookingData = activity.bookingData{ cdi.bookingData = bookingData } return cdi } func mapServiceIntoCityDataInformation(service: Service)-> CityDataInformation{ let cdi = CityDataInformation(name: service.name!) cdi.latitude = service.latitude cdi.longitude = service.longitude if let image = service.image{ cdi.image = image } if let logo = service.logo{ cdi.logo = logo } if let telephone = service.telephone{ cdi.telephone = telephone } if let shopURL = service.shopURL{ cdi.shopUrl = shopURL } cdi.specialOffer = service.specialOffer if let address = service.address{ cdi.address = address } if let openingHours = service.openingHours{ cdi.openingHours = openingHours } if let keywords = service.keywords{ cdi.keywords = keywords } if let desc = service.desc{ cdi.description = desc } if let bookingOperation = service.bookingOperation{ cdi.bookingOperation = bookingOperation } if let bookingData = service.bookingData{ cdi.bookingData = bookingData } return cdi }
mit
e112928aa4367aa1e07f4cc0bf56460a
18.48366
82
0.722912
3.157839
false
false
false
false
shajrawi/swift
stdlib/public/Darwin/Accelerate/vDSP_FFT_DFT_Common.swift
2
1206
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2019 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 // //===----------------------------------------------------------------------===// extension vDSP { @available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *) public enum FourierTransformDirection { case forward case inverse public var dftDirection: vDSP_DFT_Direction { switch self { case .forward: return .FORWARD case .inverse: return .INVERSE } } public var fftDirection: FFTDirection { switch self { case .forward: return FFTDirection(kFFTDirection_Forward) case .inverse: return FFTDirection(kFFTDirection_Inverse) } } } }
apache-2.0
1556198dcc403c3e9af2b3057ee1be5e
31.594595
80
0.510779
5.635514
false
false
false
false
cbrentharris/swift
validation-test/compiler_crashers/28087-swift-genericsignature-profile.swift
1
2494
// RUN: not --crash %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class a = { { protocol P{ va d: A? unit(2){{} class b class b<T where k.C(x: P extension NSData { func g:A{ }} " { va d} let a { func g: e where k.C(x class A{ class a { class b }}}}}class S<T{func a<h{func b<T where h.g=a{}}class d { }} println(2){ let t: A { func g: B{ println(2).B : T.B :{ class A { typealias e where B<f: Array<T where g: Array<T where h class b class b<T where h.B :P protocol c, { var d = e protocol P class b{ func f<T:b protocol c, class b<T where f: T.h : T:T? unit(object1: P { } var A { let a = f { private let t: A? nil private let t: Array<I : Array<I : T) { class func a {{ struct A {{ class A, b }{ class A : a = e? enum S<T where I.E == { enum S: { { var A : P {{{struct B<I : a = " func g: P class b<T where k.E == e? }} class a { " Void{class e?? unit(" if true{ println(object1: a { case c println(x func f<T where g: a = d:A<T where f<T where k.g =b<I : T) { class a<T where g<d = " var b } {class func f: d {} struct B<d : T.h : T.C() ? }}} private let d{ class B<T>() -> String { { func g: Array<T where f=b<T where h.h : P {} return x: A{ { }} class B<T.g == d<T A {struct B<I : d = e typealias e where I.E == e{ class b struct A { struct A, b }}}{{ class func unit<T where h.E == e: e?? { Void{ var b<d : Any { class b ( {func a<T where B:Any).E == e : P }} }}}}}class S<T{func a<h{func b<T where h.g=a{}}class d func a{} var d { class b(key: a = d} protocol e == e?? { return unit(object1: a {{ func g: e, d : Array<T where k.E == Int class A { enum S:P{ { class A, b = set { a = d} } protocol P { { class b<T where g: a { {class A : e, d = [Void{ va d> : e, b } {{var d = e, b : Array<I : Array<T where k.g =b class A, AnyObject, d = { protocol c, func a<I : Array<T where g: B<T where g: e:T let a = d<T where h.E == { var d = e:P struct A : A<T where f<T) { class e struct B<T where B<T:d{ struct B<T where g: T.map { b } extension NSData { struct Q<T class A : e: A<T where g: e where k.E == d:b() { { class A : A, d = " ( { protocol P { class b: A{{ let t: A{ ( " "" class B : Array<I : e where g<T where I.C(" println(key: Array<T) -> String { }}}}}class S<T{func a<h{func b<T where h.g=a{}}class d let t: A func a<T where g: Array<T where g: A<T where I.C(" class B let a {{ protocol P typealias e where g: e {{{ { class
apache-2.0
50099937e000b136b7e89765e0b7fb70
16.440559
87
0.592622
2.313544
false
false
false
false
LeeMZC/MZCWB
MZCWB/MZCWB/Classes/Message-消息/View/MZCEditMessageCustomContentTextView.swift
1
1533
// // MZCMessageTextView.swift // MZCWB // // Created by 马纵驰 on 16/8/12. // Copyright © 2016年 马纵驰. All rights reserved. // import UIKit class MZCEditMessageCustomContentTextView: UITextView { //MARK:- lazy private lazy var placeholderLabel : UILabel = { let label = UILabel() label.text = "分享新鲜事..." label.tintColor = UIColor.grayColor() label.font = self.font label.sizeToFit() return label }() //MARK:- 生命周期 override func awakeFromNib() { setupUI() } /** 布局子控件 */ override func layoutSubviews() { placeholderLabel.snp_makeConstraints { (make) in make.left.equalTo(self).offset(4) make.top.equalTo(self).offset(8) } } /** 销毁通知 */ deinit{ NSNotificationCenter.defaultCenter().removeObserver(self) } } //MARK:- private extension MZCEditMessageCustomContentTextView { /** setupUI */ private func setupUI(){ setupNotf() addSubview(placeholderLabel) } /** 通知内容改变 */ private func setupNotf(){ NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(MZCEditMessageCustomContentTextView.textViewDidChange), name: UITextViewTextDidChangeNotification, object: nil) } } //MARK:- event extension MZCEditMessageCustomContentTextView { @objc private func textViewDidChange(){ placeholderLabel.hidden = self.hasText() } }
artistic-2.0
30c063fe2cafb3445da65e8a90f4862b
23.516667
194
0.634694
4.31085
false
false
false
false
soapyigu/LeetCode_Swift
Tree/UniqueBinarySearchTrees.swift
1
901
/** * Question Link: https://leetcode.com/problems/unique-binary-search-trees/ * Primary idea: Dynamic programming, for each node as root, dp[i] += dp[j] * dp[i - j - 1] * * Time Complexity: O(n^2), Space Complexity: O(n) * * Definition for a binary tree node. * public class TreeNode { * public var val: Int * public var left: TreeNode? * public var right: TreeNode? * public init(_ val: Int) { * self.val = val * self.left = nil * self.right = nil * } * } */ class UniqueBinarySearchTrees { func numTrees(_ n: Int) -> Int { guard n > 1 else { return 1 } var dp = Array(repeating: 0, count: n + 1) dp[0] = 1 for i in 1...n { for j in 0..<i { dp[i] += dp[j] * dp[i - j - 1] } } return dp[n] } }
mit
4cd2a8f439f805c65b03cf0e2fa2ce35
23.351351
91
0.483907
3.387218
false
false
false
false
luosheng/OpenSim
OpenSim/ActionMenu.swift
1
2800
// // ActionMenu.swift // OpenSim // // Created by Luo Sheng on 07/05/2017. // Copyright © 2017 Luo Sheng. All rights reserved. // import Cocoa final class ActionMenu: NSMenu { private weak var application: Application! private static let standardActions: [ApplicationActionable.Type] = [ RevealInFinderAction.self, CopyToPasteboardAction.self, OpenInTerminalAction.self, LaunchAction.self, UninstallAction.self ] private static let extraActions: [ApplicationActionable.Type] = [ OpenInItermAction.self, OpenRealmAction.self ] private var appInfoItem: NSMenuItem { let item = NSMenuItem() item.view = AppInfoView(application: application) return item } init(device: Device, application: Application) { self.application = application super.init(title: "") buildMenuItems() } required init(coder decoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func buildMenuItems() { let createAction: (ApplicationActionable.Type) -> ApplicationActionable = { $0.init(application: self.application) } self.buildMenuSection(title: UIConstants.strings.menuHeaderActions, actions: ActionMenu.standardActions.map(createAction)) self.buildMenuSection(title: UIConstants.strings.menuHeaderExtensions, actions: ActionMenu.extraActions.map(createAction)) self.addItem(self.buildSectionTitle(title: UIConstants.strings.menuHeaderAppInformation)) self.addItem(appInfoItem) } private func buildMenuSection(title: String, actions: [ApplicationActionable]) { self.addItem(self.buildSectionTitle(title: title)) actions.forEach { (action) in if let item = buildMenuItem(for: action) { self.addItem(item) } } self.addItem(NSMenuItem.separator()) } private func buildSectionTitle(title: String) -> NSMenuItem { let titleItem = NSMenuItem(title: title, action: nil, keyEquivalent: "") titleItem.isEnabled = false return titleItem } private func buildMenuItem(`for` action: ApplicationActionable) -> NSMenuItem? { if !action.isAvailable { return nil } let item = NSMenuItem(title: action.title, action: #selector(actionMenuItemClicked(_:)), keyEquivalent: "") item.representedObject = action item.image = action.icon item.target = self return item } @objc private func actionMenuItemClicked(_ sender: NSMenuItem) { (sender.representedObject as? ApplicationActionable)?.perform() } }
mit
ce3253ad58328757fb6e971c3042405e
30.806818
130
0.645588
4.792808
false
false
false
false
jonreiling/Rockbox-Framework-Swift
Source/Model/RBAlbum.swift
1
1348
// // RBAlbum.swift // AKQARockboxController // // Created by Jon Reiling on 9/7/14. // Copyright (c) 2014 AKQA. All rights reserved. // import Foundation import SwiftyJSON public class RBAlbum : RBBase { public var albumArtworkURL:String! public var albumArtworkThumbnailURL:String! public var tracks:[RBTrack]? init( json: JSON ) { super.init() albumArtworkURL = "" albumArtworkThumbnailURL = "" type = "album" populateFromJSON(json) } override public func populateFromJSON( json : JSON ) { super.populateFromJSON(json) if let jsonAlbumURI = json["images"][0]["url"].string { self.albumArtworkURL = jsonAlbumURI } if let jsonAlbumThumbnailURI = json["images"][2]["url"].string { self.albumArtworkThumbnailURL = jsonAlbumThumbnailURI } if let jsonTracks = json["tracks"]["items"].array { var tracks:[RBTrack] = [] for jsonTrack in jsonTracks { let track:RBTrack = RBTrack(json:jsonTrack); track.album = self tracks.append(track) } self.tracks = tracks } } }
mit
01591cf75421fddf7e0c70a96ba3ceb4
22.666667
72
0.531157
4.763251
false
false
false
false
MaTriXy/androidtool-mac
AndroidTool/Constants.swift
1
2154
// // Constants.swift // AndroidTool // // Created by Morten Just Petersen on 11/13/15. // Copyright © 2015 Morten Just Petersen. All rights reserved. // import Cocoa class Constants { static let NOTIF_NEWDATA = "mj.newData" static let NOTIF_NEWDATAVERBOSE = "mj.newDataVerbose" static let NOTIF_NEWSESSION = "mj.newSession" static let NOTIF_ALLOUTPUT = "mj.newAllOutput" static let NOTIF_COMMAND = "mj.command" static let NOTIF_COMMANDVERBOSE = "mj.commandVerbose" static let DROP_INVITE = "Drop a ZIP or APK prototype" static let PREF_SCREENSHOTFOLDER = "screenshotsFolder" static let PREF_SCREENRECORDINGSFOLDER = "screenRecordingsFolder" static let PREF_USEACTIVITYINFILENAME = "useActivityInFilename" static let PREF_LAUNCHINSTALLEDAPP = "launchInstalledApp" static let PREF_FLASHIMAGESINZIPFILES = "flashImagesInZipFiles" static let PREF_GENERATEGIF = "generateGif" static let defaultPrefValues = [ "timeValue":"10:09" ,"mobileDatatype":"No data type" ,"batteryLevel": "100%" ,"mobileLevel" : "4 bars" ,"verboseOutput" : false ,"screenRecordingsFolder": "" ,"screenshotsFolder": "" ,"createGIF": true ,"useActivityInFilename":true ,"launchInstalledApp":true ,"flashImagesInZipFiles":false ,"generateGif":false ] static let tweakProperties = ["bluetooth", "clock", "alarm", "sync", "wifi", "location", "volume", "mute", "notifications", "mobile", "mobileDatatype", "mobileLevel", "batteryLevel", "batteryCharging", "airplane", "nosim", "speakerphone"] static let WIFI = "wifi" static let NOTIFICATIONS = "notifications" static let TIME = "time" static let TIMEVALUE = "timeValue" static let BLUETOOTH = "bluetooth" static let ALARM = "alarm" static let SYNC = "sync" static let LOCATION = "location" static let VOLUME = "volume" static let MUTE = "mute" static let DATATYPE = "datatype" static let BATTERYLEVEL = "batteryLevel" static let CHARGING = "charging" static let VERBOSEOUTPUT = "verboseOutput" }
apache-2.0
62ccd5322775c6049fceb25759b55524
36.12069
242
0.673479
3.886282
false
false
false
false
iAugux/Zoom-Contacts
Phonetic/ViewController.swift
1
7037
// // ViewController.swift // Phonetic // // Created by Augus on 1/27/16. // Copyright © 2016 iAugus. All rights reserved. // import UIKit import AVFoundation import AVKit import KDCircularProgress let kVCWillDisappearNotification = "kVCWillDisappearNotification" let GLOBAL_CUSTOM_COLOR = UIColor(red: 0.0, green: 1.0, blue: 1.0, alpha: 1.0) class ViewController: UIViewController { @IBOutlet weak var executeButton: UIButton! @IBOutlet weak var blurView: UIVisualEffectView! @IBOutlet weak var outputView: UITextView! @IBOutlet weak var percentageLabel: UILabel! @IBOutlet weak var avPlayerPlaceholderView: UIImageView! @IBOutlet weak var settingButton: UIButton! @IBOutlet weak var infoButton: UIButton! @IBOutlet weak var progress: KDCircularProgress! private var singleTap: UITapGestureRecognizer! private var multiTap: UITapGestureRecognizer! private var longPress: UILongPressGestureRecognizer! private var swipeUp: UISwipeGestureRecognizer! private var abortingAlertController: UIAlertController! var avPlayerController: AVPlayerViewController! var avPlayer: AVPlayer! var isProcessing = false { didSet { settingButton?.enabled = !isProcessing infoButton?.enabled = !isProcessing executeButton?.enabled = !isProcessing enableExecuteButtonGestures(!isProcessing) // dismiss alert controller if it's already done. if !isProcessing { abortingAlertController?.dismissViewController() abortingAlertController = nil } } } override func viewDidLoad() { super.viewDidLoad() configureSubViews() NSTimer.scheduledTimerWithTimeInterval(3.0, target: self, selector: #selector(rateMeInTheSecondTime), userInfo: nil, repeats: false) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(showLabels), name: kVCWillDisappearNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(popoverSettingViewController), name: kDismissedAdditionalSettingsVCNotification, object: nil) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) // I modified the style while presenting a SFSafariViewController, so here should reset it. UIApplication.sharedApplication().statusBarStyle = .LightContent } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) displayWalkthroughIfNeeded() } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) pauseVideo() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() avPlayer?.pause() avPlayerPlaceholderView.subviews.first?.removeFromSuperview() avPlayerController = nil if isProcessing { let message = NSLocalizedString("Animation Stopped...", comment: "") Toast.make(message, delay: 0, interval: 5) } } private func configureSubViews() { // execute button executeButton?.tintColor = GLOBAL_CUSTOM_COLOR executeButton?.setImage(UIImage(named: "touch")?.imageWithRenderingMode(.AlwaysTemplate), forState: .Normal) singleTap = UITapGestureRecognizer(target: self, action: #selector(execute)) multiTap = UITapGestureRecognizer(target: self, action: #selector(clean(_:))) longPress = UILongPressGestureRecognizer(target: self, action: #selector(clean(_:))) multiTap.numberOfTapsRequired = 2 swipeUp = UISwipeGestureRecognizer(target: self, action: #selector(abortActions)) swipeUp.direction = .Up executeButton.addGestureRecognizer(singleTap) executeButton.addGestureRecognizer(multiTap) executeButton.addGestureRecognizer(longPress) singleTap.requireGestureRecognizerToFail(multiTap) singleTap.requireGestureRecognizerToFail(longPress) // setting button settingButton.addTarget(self, action: #selector(popoverSettingViewController), forControlEvents: .TouchUpInside) // info button infoButton.addTarget(self, action: #selector(popoverInfoViewController), forControlEvents: .TouchUpInside) // Preventing multiple buttons from being touched at the same time // settingButton.exclusiveTouch = true // infoButton.exclusiveTouch = true if !UIDevice.currentDevice().isBlurSupported() || UIAccessibilityIsReduceTransparencyEnabled() { blurView.effect = nil blurView.backgroundColor = UIColor(red: 0.498, green: 0.498, blue: 0.498, alpha: 0.926) } } private func enableExecuteButtonGestures(enable: Bool) { if !enable { executeButton?.gestureRecognizers?.removeAll() executeButton?.addGestureRecognizer(swipeUp) } else { executeButton?.removeGestureRecognizer(swipeUp) executeButton?.addGestureRecognizer(singleTap) executeButton?.addGestureRecognizer(multiTap) executeButton?.addGestureRecognizer(longPress) } } internal func abortActions() { UIView.animateWithDuration(0.45, delay: 0, options: .TransitionNone, animations: { () -> Void in self.executeButton?.frame.origin.y -= 25 }) { (_) -> Void in UIView.animateWithDuration(0.35, delay: 0.2, options: .TransitionNone, animations: { () -> Void in self.executeButton?.frame.origin.y += 25 }, completion: { _ -> Void in self.abortingAlert() }) } } private func abortingAlert() { guard isProcessing else { return } let title = NSLocalizedString("Abort", comment: "UIAlertController - title") let message = NSLocalizedString("Processing... Are you sure to abort?", comment: "UIAlertController - message") let cancelActionTitle = NSLocalizedString("Cancel", comment: "") let okActionTitle = NSLocalizedString("Abort", comment: "") let cancelAction = UIAlertAction(title: cancelActionTitle, style: .Cancel, handler: nil) let okAction = UIAlertAction(title: okActionTitle, style: .Default) { (_) -> Void in PhoneticContacts.sharedInstance.isProcessing = false } abortingAlertController = UIAlertController(title: title, message: message, preferredStyle: .Alert) abortingAlertController.addAction(cancelAction) abortingAlertController.addAction(okAction) UIApplication.topMostViewController?.presentViewController(abortingAlertController, animated: true, completion: nil) } }
mit
30b969a933d69484a99c74c6032c63b2
38.751412
176
0.66643
5.566456
false
false
false
false
mleiv/MEGameTracker
MEGameTracker/Views/Shepard Tab/Shepard Reputation/ShepardReputationController.swift
1
2678
// // ShepardReputationController.swift // MEGameTracker // // Created by Emily Ivie on 7/29/15. // Copyright © 2015 urdnot. All rights reserved. // import UIKit final public class ShepardReputationController: UIViewController, SideEffectsable { @IBOutlet weak var ruthlessRadio: RadioOptionRowView? @IBOutlet weak var ruthlessSideEffectsView: SideEffectsView? @IBOutlet weak var warHeroRadio: RadioOptionRowView? @IBOutlet weak var warHeroSideEffectsView: SideEffectsView? @IBOutlet weak var soleSurvivorRadio: RadioOptionRowView? @IBOutlet weak var soleSurvivorSideEffectsView: SideEffectsView? public var sideEffects: [String]? private var shepard: Shepard? override public func viewDidLoad() { super.viewDidLoad() guard !UIWindow.isInterfaceBuilder else { return } setup() startListeners() } func setup() { fetchData() if !UIWindow.isInterfaceBuilder { ruthlessSideEffectsView?.controller = self warHeroSideEffectsView?.controller = self soleSurvivorSideEffectsView?.controller = self ruthlessRadio?.onChange = { [weak self] _ in self?.handleChange(reputation: .ruthless) } warHeroRadio?.onChange = { [weak self] _ in self?.handleChange(reputation: .warHero) } soleSurvivorRadio?.onChange = { [weak self] _ in self?.handleChange(reputation: .soleSurvivor) } } if let shepard = self.shepard { setupRadios(shepard: shepard) } view.layoutIfNeeded() } func fetchData() { if UIWindow.isInterfaceBuilder { shepard = Shepard.getDummy() } else { shepard = App.current.game?.shepard } } func setupRadios(shepard: Shepard) { ruthlessRadio?.isOn = shepard.reputation == .ruthless warHeroRadio?.isOn = shepard.reputation == .warHero soleSurvivorRadio?.isOn = shepard.reputation == .soleSurvivor } func handleChange(reputation: Shepard.Reputation) { if let shepard = self.shepard?.changed(reputation: reputation) { setupRadios(shepard: shepard) } } func reloadDataOnChange() { fetchData() if let shepard = self.shepard { setupRadios(shepard: shepard) } } func reloadOnShepardChange(_ x: Bool = false) { if shepard?.uuid != App.current.game?.shepard?.uuid { shepard = App.current.game?.shepard reloadDataOnChange() } } func startListeners() { guard !UIWindow.isInterfaceBuilder else { return } // listen for gameVersion changes only App.onCurrentShepardChange.cancelSubscription(for: self) _ = App.onCurrentShepardChange.subscribe(with: self) { [weak self] _ in DispatchQueue.main.async { self?.reloadOnShepardChange() } } } }
mit
0fde6c6c5357a367f534999478fe366c
25.77
83
0.704894
3.718056
false
false
false
false
uber/RIBs
ios/RIBsTests/ComponentizedBuilderTests.swift
1
2323
// // Copyright (c) 2017. Uber Technologies // // 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. // @testable import RIBs import XCTest class ComponentizedBuilderTests: XCTestCase { func test_componentForCurrentPass_builderReturnsSameInstance_verifyAssertion() { let component = MockComponent() let sameInstanceBuilder = MockComponentizedBuilder { return component } sameInstanceBuilder.buildHandler = { component, _ in return MockSimpleRouter() } let _: MockSimpleRouter = sameInstanceBuilder.build(withDynamicBuildDependency: (), dynamicComponentDependency: ()) expectAssertionFailure { let _: MockSimpleRouter = sameInstanceBuilder.build(withDynamicBuildDependency: (), dynamicComponentDependency: ()) } } func test_componentForCurrentPass_builderReturnsNewInstance_verifyNoAssertion() { let sameInstanceBuilder = MockComponentizedBuilder { return MockComponent() } sameInstanceBuilder.buildHandler = { component, _ in return MockSimpleRouter() } let _: MockSimpleRouter = sameInstanceBuilder.build(withDynamicBuildDependency: (), dynamicComponentDependency: ()) let _: MockSimpleRouter = sameInstanceBuilder.build(withDynamicBuildDependency: (), dynamicComponentDependency: ()) } } private class MockComponent {} private class MockSimpleRouter {} private class MockComponentizedBuilder: ComponentizedBuilder<MockComponent, MockSimpleRouter, (), ()> { fileprivate var buildHandler: ((MockComponent, ()) -> MockSimpleRouter)? override func build(with component: MockComponent, _ dynamicBuildDependency: ()) -> MockSimpleRouter { return buildHandler!(component, dynamicBuildDependency) } }
apache-2.0
a6a30392904cf74da432986a682530a1
35.873016
127
0.716746
4.750511
false
true
false
false
superk589/DereGuide
DereGuide/Live/Model/CGSSBeatmapNote.swift
2
2846
// // CGSSBeatmapNote.swift // DereGuide // // Created by zzk on 21/10/2017. // Copyright © 2017 zzk. All rights reserved. // import Foundation import UIKit class CGSSBeatmapNote { // 判定范围类型(用于计算得分, 并非按键类型) enum RangeType: Int { case click case flick case slide static let hold = RangeType.click } // note 类型 enum Style { enum FlickDirection { case left case right } case click case flick(FlickDirection) case slide case hold case wideClick case wideFlick(FlickDirection) case wideSlide var isWide: Bool { switch self { case .click, .flick, .hold, .slide: return false default: return true } } } var width: Int { switch style { case .click, .flick, .hold, .slide: return 1 default: return status } } var id: Int! var sec: Float! var type: Int! var startPos: Int! var finishPos: Int! var status: Int! var sync: Int! var groupId: Int! // 0 no press, 1 start, 2 end var longPressType = 0 // used in shifting bpm var offset: Float = 0 // from 1 to max combo var comboIndex: Int = 1 // context free note information, so each long press slide and filck note need to know the related note weak var previous: CGSSBeatmapNote? weak var next: CGSSBeatmapNote? weak var along: CGSSBeatmapNote? } extension CGSSBeatmapNote { func append(_ anotherNote: CGSSBeatmapNote) { self.next = anotherNote anotherNote.previous = self } func intervalTo(_ anotherNote: CGSSBeatmapNote) -> Float { return anotherNote.sec - sec } var offsetSecond: Float { return sec + offset } } extension CGSSBeatmapNote { var rangeType: RangeType { switch (status, type) { case (1, _), (2, _): return .flick case (_, 3): return .slide case (_, 2): return .hold default: return .click } } var style: Style { switch (status, type) { case (1, 1): return .flick(.left) case (2, 1): return .flick(.right) case (_, 2): return .hold case (_, 3): return .slide case (_, 4): return .wideClick case (_, 5): return .wideSlide case (_, 6): return .wideFlick(.left) case (_, 7): return .wideFlick(.right) default: return .click } } }
mit
73c3ac209eac914113e4c8a4522fb161
20.412214
107
0.504456
4.546191
false
false
false
false
MostafaTaghipour/mtpFontManager
mtpFontManager/Classes/AppFont.swift
1
2740
// // FontName.swift // mtpFontManager // // Created by Mostafa Taghipour on 2/5/19. // import Foundation /// Font name struct public struct AppFont { public let id: Int public let familyName: String public let defaultFont: String public var ultraLight: String? public var thin: String? public var light: String? public var regular: String? public var medium: String? public var semibold: String? public var bold: String? public var heavy: String? public var black: String? public init(id: Int, familyName: String, defaultFont: String) { self.id = id self.familyName = familyName self.defaultFont = defaultFont } public init(id: Int, familyName: String, defaultFont: String, ultraLight: String?, thin: String?, light: String?, regular: String?, medium: String?, semibold: String?, bold: String?, heavy: String?, black: String?) { self.id = id self.familyName = familyName self.defaultFont = defaultFont self.ultraLight = ultraLight self.thin = thin self.light = light self.regular = regular self.medium = medium self.semibold = semibold self.bold = bold self.heavy = heavy self.black = black } public init(plist: String) { guard let path = Bundle.main.path(forResource: plist, ofType: Constants.plistType), let dict = NSDictionary(contentsOfFile: path) as? [String: Any], let id = dict[ci: Constants.fontIdFiled] as? Int, let name = dict[ci: Constants.fontFamilyNameFiled] as? String, let defaultFont = dict[ci: Constants.fontDefaultFiled] as? String else { fatalError("plist is not correct") } self.id = id self.familyName = name self.defaultFont = defaultFont self.ultraLight = dict[ci: UIFont.Weight.ultraLight.title] as? String self.thin = dict[ci: UIFont.Weight.thin.title] as? String self.light = dict[ci: UIFont.Weight.light.title] as? String self.regular = dict[ci: UIFont.Weight.regular.title] as? String self.medium = dict[ci: UIFont.Weight.medium.title] as? String self.semibold = dict[ci: UIFont.Weight.semibold.title] as? String self.bold = dict[ci: UIFont.Weight.bold.title] as? String self.heavy = dict[ci: UIFont.Weight.heavy.title] as? String self.black = dict[ci: UIFont.Weight.black.title] as? String } }
mit
cc45134f984afe26adbaaeb13f9f2c5f
32.012048
91
0.585401
4.301413
false
false
false
false
russbishop/swift
stdlib/public/core/Process.swift
1
2852
//===----------------------------------------------------------------------===// // // 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 SwiftShims internal class _Box<Wrapped> { internal var _value: Wrapped internal init(_ value: Wrapped) { self._value = value } } /// Command-line arguments for the current process. public enum Process { /// Return an array of string containing the list of command-line arguments /// with which the current process was invoked. internal static func _computeArguments() -> [String] { var result: [String] = [] let argv = unsafeArgv for i in 0..<Int(argc) { let arg = argv[i]! let converted = String(cString: arg) result.append(converted) } return result } @_versioned internal static var _argc: Int32 = Int32() @_versioned internal static var _unsafeArgv: UnsafeMutablePointer<UnsafeMutablePointer<Int8>?>? = nil /// Access to the raw argc value from C. public static var argc: Int32 { return _argc } /// Access to the raw argv value from C. Accessing the argument vector /// through this pointer is unsafe. public static var unsafeArgv: UnsafeMutablePointer<UnsafeMutablePointer<Int8>?> { return _unsafeArgv! } /// Access to the swift arguments, also use lazy initialization of static /// properties to safely initialize the swift arguments. /// /// NOTE: we can not use static lazy let initializer as they can be moved /// around by the optimizer which will break the data dependence on argc /// and argv. public static var arguments: [String] { let argumentsPtr = UnsafeMutablePointer<AnyObject?>( Builtin.addressof(&_swift_stdlib_ProcessArguments)) // Check whether argument has been initialized. if let arguments = _stdlib_atomicLoadARCRef(object: argumentsPtr) { return (arguments as! _Box<[String]>)._value } let arguments = _Box<[String]>(_computeArguments()) _stdlib_atomicInitializeARCRef(object: argumentsPtr, desired: arguments) return arguments._value } } /// Intrinsic entry point invoked on entry to a standalone program's "main". @_transparent public // COMPILER_INTRINSIC func _stdlib_didEnterMain( argc: Int32, argv: UnsafeMutablePointer<UnsafeMutablePointer<Int8>?> ) { // Initialize the Process.argc and Process.unsafeArgv variables with the // values that were passed in to main. Process._argc = Int32(argc) Process._unsafeArgv = argv }
apache-2.0
a00c3b410c46bfb35cf46d88b5988af0
31.781609
80
0.668303
4.577849
false
false
false
false
maxadamski/SwiftyRegex
Source/Flags.swift
1
907
import Darwin public extension Regex { public struct Flags: OptionSetType { public let rawValue: Int32 public init(rawValue: Int32) { self.rawValue = rawValue } /// Do not differentiate case. public static let IgnoreCase = Flags(rawValue: REG_ICASE) /// Use POSIX Extended Regular Expression syntax. public static let Extended = Flags(rawValue: REG_EXTENDED) /// Treat a newline in string as dividing string into multiple lines, so that `$` can match before the newline and `^` can match after. Also, don't permit `.` to match a newline, and don't permit `[^...]` to match a newline. public static let Newline = Flags(rawValue: REG_NEWLINE) /// Do not report position of matches. public static let NoRanges = Flags(rawValue: REG_NOSUB) } }
mit
e7d28173d63c6c6945bebdbd63d87cba
32.592593
232
0.611907
4.748691
false
false
false
false
sarvex/SwiftRecepies
Health/Reading and Modifying the User’s Total Calories Burned/Reading and Modifying the User’s Total Calories Burned/ListCaloriesBurnedTableViewController.swift
1
9909
// // ViewController.swift // Reading and Modifying the User’s Total Calories Burned // // Created by vandad on 237//14. // Copyright (c) 2014 Pixolity Ltd. All rights reserved. // // These example codes are written for O'Reilly's iOS 8 Swift Programming Cookbook // If you use these solutions in your apps, you can give attribution to // Vandad Nahavandipoor for his work. Feel free to visit my blog // at http://vandadnp.wordpress.com for daily tips and tricks in Swift // and Objective-C and various other programming languages. // // You can purchase "iOS 8 Swift Programming Cookbook" from // the following URL: // http://shop.oreilly.com/product/0636920034254.do // // If you have any questions, you can contact me directly // at [email protected] // Similarly, if you find an error in these sample codes, simply // report them to O'Reilly at the following URL: // http://www.oreilly.com/catalog/errata.csp?isbn=0636920034254 import UIKit import HealthKit /* We will store this as metadata for the exercise in the health store */ let HKMetadataKeyExerciseName = "ExerciseName" extension NSDate{ func beginningOfDay() -> NSDate{ return NSCalendar.currentCalendar().dateBySettingHour(0, minute: 0, second: 0, ofDate: self, options: .WrapComponents)! } } class ListCaloriesBurnedTableViewController: UITableViewController, AddBurnedCaloriesToDietViewControllerDelegate { /* The array of all the exercises that the user has performed today */ var allCaloriesBurned = [CalorieBurner]() /* To format the calorie values */ lazy var formatter: NSEnergyFormatter = { let theFormatter = NSEnergyFormatter() theFormatter.forFoodEnergyUse = true return theFormatter }() /* Find out when the user wants to add a new calorie burner to the list and set our view controller as the delegate of the second view controller */ let segueIdentifier = "burnCalories" var isObservingBurnedCalories = false /* When people say calories, they are actually talking about kilocalories but I guess because Kilocalories is difficult to say, we have opted to say calories instead over the years */ lazy var unit = HKUnit.kilocalorieUnit() struct TableViewValues{ static let identifier = "Cell" } let burnedEnergyQuantityType = HKQuantityType.quantityTypeForIdentifier( HKQuantityTypeIdentifierActiveEnergyBurned) lazy var types: Set<NSObject>! = { return Set([self.burnedEnergyQuantityType]) }() lazy var query: HKObserverQuery = {[weak self] in let strongSelf = self! return HKObserverQuery(sampleType: strongSelf.burnedEnergyQuantityType, predicate: strongSelf.predicate, updateHandler: strongSelf.burnedCaloriesChangedHandler) }() lazy var healthStore = HKHealthStore() lazy var predicate: NSPredicate = { let options: NSCalendarOptions = .WrapComponents let nowDate = NSDate() let beginningOfToday = nowDate.beginningOfDay() let tomorrowDate = NSCalendar.currentCalendar().dateByAddingUnit(.DayCalendarUnit, value: 1, toDate: NSDate(), options: options) let beginningOfTomorrow = tomorrowDate!.beginningOfDay() return HKQuery.predicateForSamplesWithStartDate(beginningOfToday, endDate: beginningOfTomorrow, options: .StrictEndDate) }() func burnedCaloriesChangedHandler(query: HKObserverQuery!, completionHandler: HKObserverQueryCompletionHandler!, error: NSError!){ println("The burned calories has changed...") /* Be careful, we are not on the UI thread */ fetchBurnedCaloriesInLastDay() } func addBurnedCaloriesToDietViewController( sender: AddBurnedCaloriesToDietViewController, addedCalorieBurnerWithName: String, calories: Double, startDate: NSDate, endDate: NSDate) { let quantity = HKQuantity(unit: unit, doubleValue: calories) let metadata = [ HKMetadataKeyExerciseName: addedCalorieBurnerWithName ] let sample = HKQuantitySample(type: burnedEnergyQuantityType, quantity: quantity, startDate: startDate, endDate: endDate, metadata: metadata) healthStore.saveObject(sample, withCompletion: {[weak self] (succeeded: Bool, error: NSError!) in let strongSelf = self! if succeeded{ println("Successfully saved the calories...") strongSelf.tableView.reloadData() } else { println("Failed to save the calories") if let theError = error{ println("Error = \(theError)") } } }) } func fetchBurnedCaloriesInLastDay(){ let sortDescriptor = NSSortDescriptor( key: HKSampleSortIdentifierStartDate, ascending: false) let query = HKSampleQuery(sampleType: burnedEnergyQuantityType, predicate: predicate, limit: Int(HKObjectQueryNoLimit), sortDescriptors: [sortDescriptor], resultsHandler: {[weak self] (query: HKSampleQuery!, results: [AnyObject]!, error: NSError!) in println("Received new data from the query. Processing...") let strongSelf = self! if results.count > 0{ strongSelf.allCaloriesBurned = [CalorieBurner]() for sample in results as! [HKQuantitySample]{ let burnerName = sample.metadata[HKMetadataKeyExerciseName] as? NSString let calories = sample.quantity.doubleValueForUnit(strongSelf.unit) let caloriesAsString = strongSelf.formatter.stringFromValue(calories, unit: .Kilocalorie) let burner = CalorieBurner(name: String(burnerName!), calories: calories, startDate: sample.startDate, endDate: sample.endDate) strongSelf.allCaloriesBurned.append(burner) } dispatch_async(dispatch_get_main_queue(), { strongSelf.tableView.reloadData() }) } else { print("Could not read the burned calories ") println("or no burned calories data was available") } }) healthStore.executeQuery(query) } func startObservingBurnedCaloriesChanges(){ if isObservingBurnedCalories{ return } healthStore.executeQuery(query) healthStore.enableBackgroundDeliveryForType(burnedEnergyQuantityType, frequency: .Immediate, withCompletion: {[weak self] (succeeded: Bool, error: NSError!) in if succeeded{ self!.isObservingBurnedCalories = true println("Enabled background delivery of burned energy changes") } else { if let theError = error{ print("Failed to enable background delivery " + "of burned energy changes. ") println("Error = \(theError)") } } }) } deinit{ stopObservingBurnedCaloriesChanges() } func stopObservingBurnedCaloriesChanges(){ if isObservingBurnedCalories == false{ return } healthStore.stopQuery(query) healthStore.disableAllBackgroundDeliveryWithCompletion{[weak self] (succeeded: Bool, error: NSError!) in if succeeded{ self!.isObservingBurnedCalories = false println("Disabled background delivery of burned energy changes") } else { if let theError = error{ print("Failed to disable background delivery of " + "burned energy changes. ") println("Error = \(theError)") } } } } /* Ask for permission to access the health store */ override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) if HKHealthStore.isHealthDataAvailable(){ healthStore.requestAuthorizationToShareTypes(types, readTypes: types, completion: {[weak self] (succeeded: Bool, error: NSError!) in let strongSelf = self! if succeeded && error == nil{ dispatch_async(dispatch_get_main_queue(), strongSelf.startObservingBurnedCaloriesChanges) } else { if let theError = error{ println("Error occurred = \(theError)") } } }) } else { println("Health data is not available") } if allCaloriesBurned.count > 0{ let firstCell = NSIndexPath(forRow: 0, inSection: 0) tableView.selectRowAtIndexPath(firstCell, animated: true, scrollPosition: UITableViewScrollPosition.Top) } } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) { if segue.identifier == segueIdentifier{ let controller = segue.destinationViewController as! AddBurnedCaloriesToDietViewController controller.delegate = self } } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return allCaloriesBurned.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier( TableViewValues.identifier, forIndexPath: indexPath) as! UITableViewCell let burner = allCaloriesBurned[indexPath.row] let caloriesAsString = formatter.stringFromValue(burner.calories, unit: .Kilocalorie) cell.textLabel!.text = burner.name cell.detailTextLabel!.text = caloriesAsString return cell } }
isc
68954fb6c4f6e8043f0793adb8133580
29.112462
83
0.64843
5.162585
false
false
false
false
sarvex/SwiftRecepies
Basics/Loading Web Pages with UIWebView/Loading Web Pages with UIWebView/ViewController.swift
1
2972
// // ViewController.swift // Loading Web Pages with UIWebView // // Created by Vandad Nahavandipoor on 6/30/14. // Copyright (c) 2014 Pixolity Ltd. All rights reserved. // // These example codes are written for O'Reilly's iOS 8 Swift Programming Cookbook // If you use these solutions in your apps, you can give attribution to // Vandad Nahavandipoor for his work. Feel free to visit my blog // at http://vandadnp.wordpress.com for daily tips and tricks in Swift // and Objective-C and various other programming languages. // // You can purchase "iOS 8 Swift Programming Cookbook" from // the following URL: // http://shop.oreilly.com/product/0636920034254.do // // If you have any questions, you can contact me directly // at [email protected] // Similarly, if you find an error in these sample codes, simply // report them to O'Reilly at the following URL: // http://www.oreilly.com/catalog/errata.csp?isbn=0636920034254 /* 1 */ //import UIKit // //class ViewController: UIViewController { // // override func viewDidLoad() { // super.viewDidLoad() // // let webView = UIWebView(frame: view.bounds) // let htmlString = "<br/>iOS <strong>Programming</strong>" // webView.loadHTMLString(htmlString, baseURL: nil) // view.addSubview(webView) // // } // //} /* 2 */ //import UIKit // //class ViewController: UIViewController { // // /* Hide the status bar to give all the screen real estate */ // override func prefersStatusBarHidden() -> Bool { // return true // } // // override func viewDidLoad() { // super.viewDidLoad() // // let webView = UIWebView(frame: view.bounds) // webView.scalesPageToFit = true // view.addSubview(webView) // // let url = NSURL(string: "http://www.apple.com") // let request = NSURLRequest(URL: url!) // // webView.loadRequest(request) // // view.addSubview(webView) // // } // //} /* 3 */ import UIKit class ViewController: UIViewController, UIWebViewDelegate { func webViewDidStartLoad(webView: UIWebView){ UIApplication.sharedApplication().networkActivityIndicatorVisible = true } func webViewDidFinishLoad(webView: UIWebView){ UIApplication.sharedApplication().networkActivityIndicatorVisible = false } func webView(webView: UIWebView, didFailLoadWithError error: NSError){ UIApplication.sharedApplication().networkActivityIndicatorVisible = false } override func viewDidLoad() { super.viewDidLoad() /* Render the web view under the status bar */ var frame = view.bounds frame.origin.y = UIApplication.sharedApplication().statusBarFrame.height frame.size.height -= frame.origin.y let webView = UIWebView(frame: frame) webView.delegate = self webView.scalesPageToFit = true view.addSubview(webView) let url = NSURL(string: "http://www.apple.com") let request = NSURLRequest(URL: url!) webView.loadRequest(request) view.addSubview(webView) } }
isc
c4eda1c76266f6bc4409b16fcffd596c
26.527778
83
0.693809
4.116343
false
false
false
false
dzenbot/Iconic
Vendor/SwiftGen/SwiftGen.playground/Pages/Storyboards-Demo.xcplaygroundpage/Contents.swift
1
3934
//: #### Other pages //: //: * [Demo for `swiftgen strings`](Strings-Demo) //: * [Demo for `swiftgen images`](Images-Demo) //: * Demo for `swiftgen storyboards` //: * [Demo for `swiftgen colors`](Colors-Demo) import UIKit class CreateAccViewController: UIViewController {} //: #### Example of code generated by swiftgen-storyboard // Generated using SwiftGen — https://github.com/SwiftGen/SwiftGen import Foundation import UIKit protocol StoryboardSceneType { static var storyboardName: String { get } } extension StoryboardSceneType { static func storyboard() -> UIStoryboard { return UIStoryboard(name: self.storyboardName, bundle: nil) } static func initialViewController() -> UIViewController { return storyboard().instantiateInitialViewController()! } } extension StoryboardSceneType where Self: RawRepresentable, Self.RawValue == String { func viewController() -> UIViewController { return Self.storyboard().instantiateViewControllerWithIdentifier(self.rawValue) } static func viewController(identifier: Self) -> UIViewController { return identifier.viewController() } } protocol StoryboardSegueType: RawRepresentable { } extension UIViewController { func performSegue<S: StoryboardSegueType where S.RawValue == String>(segue: S, sender: AnyObject? = nil) { performSegueWithIdentifier(segue.rawValue, sender: sender) } } struct StoryboardScene { enum Wizard: String, StoryboardSceneType { static let storyboardName = "Wizard" case CreateAccount = "CreateAccount" static func createAccountViewController() -> CreateAccViewController { return Wizard.CreateAccount.viewController() as! CreateAccViewController } case AcceptCGU = "Accept-CGU" static func acceptCGUViewController() -> UIViewController { return Wizard.AcceptCGU.viewController() } case ValidatePassword = "Validate_Password" static func validatePasswordViewController() -> UIViewController { return Wizard.ValidatePassword.viewController() } case Preferences = "Preferences" static func preferencesViewController() -> UIViewController { return Wizard.Preferences.viewController() } } } struct StoryboardSegue { enum Wizard: String, StoryboardSegueType { case Custom = "Custom" case Back = "Back" case NonCustom = "NonCustom" case ShowPassword = "ShowPassword" } } //: #### Usage Example let initialVC = StoryboardScene.Wizard.initialViewController() initialVC.title let validateVC = StoryboardScene.Wizard.ValidatePassword.viewController() validateVC.title /* Note: the following line would crash when run in playground, because the storyboard file was not compiled alongside the playground code, so the CreateAccViewController class was not known by the storyboard. But it should work correctly in a real project. */ // let cgu = UIStoryboard.Scene.Wizard.createAccountViewController() let segue = StoryboardSegue.Wizard.ShowPassword initialVC.performSegue(segue) switch segue { case .ShowPassword: print("Working! 🎉") default: print("Not working! 😱") } /******************************************************************************* This is a «real world» example of how you can benefit from the generated enum; you can easily switch or directly compare the passed in `segue` with the corresponding segues for a specific storyboard. *******************************************************************************/ //override func prepareForSegue(_ segue: UIStoryboardSegue, sender sender: AnyObject?) { // switch UIStoryboard.Segue.Message(rawValue: segue.identifier)! { // case .Custom: // // Prepare for your custom segue transition // case .NonCustom: // // Pass in information to the destination View Controller // } //}
mit
2f8498c2a4ae7b3d2a45a149d6730599
31.429752
108
0.687309
5.043702
false
false
false
false
hlprmnky/tree-hugger-ios
TreeHuggerMichiana/TreeModel.swift
1
2888
// // Model.swift // TreeHuggerMichiana // // Created by Chris Johnson Bidler on 5/16/15. // Copyright (c) 2015 Helper Monkey Software LLC. All rights reserved. // import Foundation struct Tree { var latitude, longitude : Double? var id : Int var condition, diameter, height: String? var images : [AnyObject]? } protocol TreeModelDelegate { func modelStateUpdated(modelState: [Tree]) } struct TreeModel { let endpoint: String var delegate:TreeModelDelegate? = nil lazy var trees: [Tree] = [] init(restEndpoint endpoint: String) { self.endpoint = endpoint } mutating func didReceieveMemoryWarning() { self.trees.removeAll(keepCapacity: false) } mutating func fetchTrees() { let urlRequest : NSURLRequest = NSURLRequest(URL: NSURL(string: self.endpoint)!) NSURLConnection.sendAsynchronousRequest(urlRequest, queue: NSOperationQueue(), completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in if let anError = error { println("Got an error: \(anError)") } else { var jsonError: NSError? let post = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &jsonError) as! NSDictionary if let aJSONError = jsonError { // got an error while parsing the data, need to handle it println("error parsing result from \(self.endpoint): \(aJSONError)") } else { if let objects : NSArray = post["objects"] as? NSArray { for object in objects { if let jsonTree : NSDictionary = object as? NSDictionary { let tree: Tree = Tree(latitude: jsonTree["latitude"] as? Double, longitude: jsonTree["longitude"] as? Double, id: jsonTree["id"] as! Int, condition: jsonTree["condition"] as? String, diameter: jsonTree["diameter"] as? String, height: jsonTree["height"] as? String, images: jsonTree["images"] as? [AnyObject]) if(self.trees.filter({tree.id == $0.id}).isEmpty) { // println("Adding tree \(tree.id) at lat \(tree.latitude), long \(tree.longitude)") self.trees.append(tree) } else { println("Not adding tree, we already have a tree for ID \(tree.id)") } } else { println("Object \(object.description) is not an NSDictionary, can't make a Tree() from it") } } } self.delegate!.modelStateUpdated(self.trees) } } }) } }
mit
f223f00bfe62aae031e9f1f605eec139
32.195402
113
0.54536
4.765677
false
false
false
false
royratcliffe/NetworkReachability
Sources/NetworkReachability+Notifications.swift
1
2885
// NetworkReachability NetworkReachability+Notifications.swift // // Copyright © 2016, Roy Ratcliffe, Pioneering Software, United Kingdom // // 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, EITHER // EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO // EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES // OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // //------------------------------------------------------------------------------ import Foundation public let FlagsDidChangeNotification = "NetworkReachabilityFlagsDidChange" public let FlagsKey = "NetworkReachabilityFlags" extension NetworkReachability { /// It is common to have a network reachability object to post notifications, /// rather than invoke a call-back capture. This method supplies a capture /// that converts the call-back to a notification. public func beginGeneratingFlagsDidChangeNotifications() { onFlagsDidChange { [weak self] (networkReachability) -> Void in guard let strongSelf = self else { return } strongSelf.postFlagsDidChangeNotification() } } /// Posts a flags-did-change notification. This method exists separately in /// order that applications can trigger an initial notification, if required, /// and also supply a call-back that performs custom handling _as well as_ /// posting notifications. For example, applications may wish to post /// different notifications for different types of reachability: one for local /// link, another for Internet. /// /// Posts to the default notification centre. The network reachability wrapper /// becomes the notification object. The notification's user information /// contains the changed flag type-converted to an unsigned 32-bit integer. public func postFlagsDidChangeNotification() { let userInfo = [FlagsKey: NSNumber(value: flags.rawValue)] let center = NotificationCenter.default center.post(name: Notification.Name(rawValue: FlagsDidChangeNotification), object: self, userInfo: userInfo) } }
mit
61f316f8a2b9f2cdfb084f5805bb0de3
48.586207
112
0.743741
5.06338
false
false
false
false
burla69/PayDay
PayDay/KeypadViewController.swift
1
9411
// // KeypadViewController.swift // PayDay // // Created by Oleksandr Burla on 3/15/16. // Copyright © 2016 Oleksandr Burla. All rights reserved. // import UIKit class KeypadViewController: UIViewController, QRScanningViewControllerDelegate { var JSONFromLogin = [String: AnyObject]() var location = "" var token = "" var firstName = "" var lastName = "" var time = "" var date = "" var tmsIDtemp = "" var userOption = 0 let baseURL = "http://ec2-52-34-242-50.us-west-2.compute.amazonaws.com" var isSuperUser = 0 @IBOutlet weak var whiteView: UIView! @IBOutlet weak var keyPadButton1: UIButton! @IBOutlet weak var timeLabel: UILabel! @IBOutlet weak var dateLabel: UILabel! @IBOutlet weak var locationLabel: UILabel! @IBOutlet weak var myNavigationItem: UINavigationItem! @IBOutlet weak var TmsID: UITextField! @IBOutlet weak var ampmLabel: UILabel! var isFirstDigit = true @IBAction func numberButtonPressed(sender: UIButton) { let digit = sender.currentTitle! TmsID.text = isFirstDigit ? digit : TmsID.text! + digit isFirstDigit = false } @IBAction func deleteButtonPressed(sender: UIButton) { let tempString = TmsID.text TmsID.text = String(tempString!.characters.dropLast()) } @IBAction func qrButtonPressed(sender: UIButton) { let vc: QRScanningViewController = self.storyboard?.instantiateViewControllerWithIdentifier("scanController") as! QRScanningViewController vc.delegate = self self.presentViewController(vc, animated: true, completion: nil) } @IBAction func okButton(sender: UIButton) { goFromQRCode() } func goFromQRCode() { let params = ["token": self.token, "user_identifier": TmsID.text!] self.postRequest("/api/v1/users/identify/", params: params) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. showTime() NSTimer.scheduledTimerWithTimeInterval(59, target: self, selector: #selector(showTime), userInfo: nil, repeats: true) updateDataFrom(JSONFromLogin) self.locationLabel.text = location self.dateLabel.text = date } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) //keyPadButton1.layoutSubviews() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() } func showTime() { let date = NSDate() let outputFormat = NSDateFormatter() //outputFormat.locale = NSLocale(localeIdentifier:"en_US") outputFormat.dateFormat = "hh:mm" timeLabel.text = outputFormat.stringFromDate(date) outputFormat.dateFormat = "a" ampmLabel.text = outputFormat.stringFromDate(date) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func updateDataFrom(json: [String : AnyObject]) { self.location = (json["location"] as? String)! self.token = (json["token"] as? String)! self.time = (json["time"] as? String)! self.date = (json["date"] as? String)! } @IBAction func unwindToKeypad(segue: UIStoryboardSegue) { self.TmsID.text = "" } func qrCodeFromQRViewController(string: String) { tmsIDtemp = string self.TmsID.text = self.tmsIDtemp } //MARK: POST func func postRequest(path: String, params: [String: AnyObject]) { let fullURL = "\(baseURL)\(path)" let request = NSMutableURLRequest(URL: NSURL(string: fullURL)!) let session = NSURLSession.sharedSession() request.HTTPMethod = "POST" request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") // or if you think the conversion might actually fail (which is unlikely if you built `params` yourself) do { request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(params, options: []) } catch { print(error) } let task = session.dataTaskWithRequest(request) { data, response, error in guard data != nil else { print("no data found: \(error)") dispatch_async(dispatch_get_main_queue(), { let alert = UIAlertController(title: "Authentication error", message: "Can not load data from web. Please check your Internet conection and try again later.", preferredStyle: UIAlertControllerStyle.Alert) let cancel = UIAlertAction(title: "OK", style: UIAlertActionStyle.Cancel, handler: nil) alert.addAction(cancel) self.presentViewController(alert, animated: false, completion: nil) }) return } // this, on the other hand, can quite easily fail if there's a server error, so you definitely // want to wrap this in `do`-`try`-`catch`: do { if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary { if let success = json["status"] as? Int { print(success) //print(json) dispatch_async(dispatch_get_main_queue(), { if success == 0 { self.performSegueWithIdentifier("showClock", sender: json) } else { print(self.switchCode(success)) let alert = UIAlertController(title: "Login fail", message: self.switchCode(success), preferredStyle: UIAlertControllerStyle.Alert) let ok = UIAlertAction(title: "Yes", style: .Default) { (action) -> Void in print("Ok pressed") } alert.addAction(ok) self.presentViewController(alert, animated: true, completion: nil) } }) } else { print("Program should crash here") } } else { let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding) // No error thrown, but not NSDictionary print("Error could not parse JSON: \(jsonStr)") } } catch let parseError { print(parseError) // Log the error thrown by `JSONObjectWithData` let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding) print("Error could not parse JSON: '\(jsonStr)'") } } task.resume() } func switchCode(success: Int?) -> String { let status = success! switch (status) { case 0: return "Success action"; case 1: return"Company with this name doesn`t exist"; case 2: return"Incorrect password"; case 3: return "You are not near by with office"; case 4: return "Incorrect IP for this company"; case 5: return "Incorrect data"; case 6: return "Token doesn't exist"; case 7: return "Incorrect identifier"; case 8: return "You aren't member of this company!"; case 9: return "There is not users in this company!"; case 13: return "Company doesn't allow employee device login"; default: return "======="; } } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showClock" { let viewController:ClockViewController = segue.destinationViewController as! ClockViewController viewController.JSONFromKeypad = sender as! [String : AnyObject] viewController.isSuperUser = self.isSuperUser viewController.userOption = self.userOption } } }
mit
f30c6984ff191f2f3326d89dc72060f1
30.577181
224
0.518385
5.614558
false
false
false
false
thombles/Flyweight
Flyweight/XML/AuthorParser.swift
1
3480
// Flyweight - iOS client for GNU social // Copyright 2017 Thomas Karpiniec // // 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 class AuthorParser: NSObject, XMLParserDelegate { let completion: (ASAuthor?) -> Void let author = ASAuthor() var currentTag: String? var tagText = FeedParser.Attrs() var childParser: NSObject? init(attrs: FeedParser.Attrs, completion: @escaping (ASAuthor?) -> Void) { self.completion = completion // No attrs in <author> } public func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) { if namespaceURI == FeedParser.AtomNS && elementName == "author" { author.objectType = tagText["objectType"] author.uri = tagText["uri"] author.username = tagText["username"] author.displayName = tagText["displayName"] author.bio = tagText["bio"] completion(author) } else { currentTag = nil } } func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) { if let tag = processTag(namespace: namespaceURI, element: elementName, attrs: attributeDict) { currentTag = tag } } func processTag(namespace: String?, element: String, attrs: FeedParser.Attrs) -> String? { guard let namespace = namespace else { return nil } if namespace == FeedParser.ActivityStreamNS && element == "object-type" { return "objectType" } if namespace == FeedParser.AtomNS && element == "uri" { return "uri" } if namespace == FeedParser.AtomNS && element == "name" { return "username" } if namespace == FeedParser.PoCoNS && element == "displayName" { return "displayName" } if namespace == FeedParser.AtomNS && element == "summary" { return "bio" } if namespace == FeedParser.AtomNS && element == "link" && attrs["rel"] == "alternate" && attrs["type"] == "text/html" { author.userPage = attrs["href"] } if namespace == FeedParser.AtomNS && element == "link" && attrs["rel"] == "avatar" { let av = ASAvatar() av.mimeType = attrs["type"] av.width = Int64(attrs["media:width"] ?? "") av.height = Int64(attrs["media:height"] ?? "") av.url = attrs["href"] author.avatars.append(av) } if namespace == FeedParser.StatusNetNS && element == "profile_info" { author.statusNetUserId = Int64(attrs["local_id"] ?? "") } return nil } public func parser(_ parser: XMLParser, foundCharacters string: String) { if let tag = currentTag { tagText[tag] = (tagText[tag] ?? "") + string } } }
apache-2.0
e98e774dbbb834542ec5b22d114c4a27
39.941176
179
0.611782
4.496124
false
false
false
false
chicio/Exploring-SceneKit
ExploringSceneKit/Model/Scenes/Collada/MoveAnimationFactory.swift
1
495
// // MoveAnimationFactory.swift // ExploringSceneKit // // Created by Fabrizio Duroni on 28.08.17. // import SceneKit class MoveAnimationFactory { static func makeMoveTo(position: SCNVector3, time: CFTimeInterval) -> CABasicAnimation { let move = CABasicAnimation(keyPath: "position") move.duration = time move.toValue = position move.isRemovedOnCompletion = false move.fillMode = CAMediaTimingFillMode.forwards return move } }
mit
69f68337540e325d177c867768ad90e0
23.75
92
0.682828
4.626168
false
false
false
false
grandiere/box
box/View/GridVirus/VGridVirusReleased.swift
1
3804
import UIKit class VGridVirusReleased:UIView { private weak var controller:CGridVirus! private weak var layoutButtonLeft:NSLayoutConstraint! private(set) weak var label:UILabel! private let kImageTop:CGFloat = 100 private let kImageHeight:CGFloat = 110 private let kLabelMarginHorizontal:CGFloat = 10 private let kLabelHeight:CGFloat = 200 private let kButtonWidth:CGFloat = 120 private let kButtonHeight:CGFloat = 34 init(controller:CGridVirus) { super.init(frame:CGRect.zero) clipsToBounds = true translatesAutoresizingMaskIntoConstraints = false backgroundColor = UIColor.clear self.controller = controller let imageView:UIImageView = UIImageView() imageView.isUserInteractionEnabled = false imageView.translatesAutoresizingMaskIntoConstraints = false imageView.contentMode = UIViewContentMode.center imageView.image = #imageLiteral(resourceName: "assetGenericVirusReleased") imageView.clipsToBounds = true let label:UILabel = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.isUserInteractionEnabled = false label.backgroundColor = UIColor.clear label.textAlignment = NSTextAlignment.center label.numberOfLines = 0 self.label = label let button:UIButton = UIButton() button.translatesAutoresizingMaskIntoConstraints = false button.clipsToBounds = true button.backgroundColor = UIColor.gridBlue button.setTitle( NSLocalizedString("VGridVirusReleased_button", comment:""), for:UIControlState.normal) button.setTitleColor( UIColor.white, for:UIControlState.normal) button.setTitleColor( UIColor(white:1, alpha:0.2), for:UIControlState.highlighted) button.titleLabel!.font = UIFont.bold(size:14) button.layer.cornerRadius = kButtonHeight / 2.0 button.addTarget( self, action:#selector(actionButton(sender:)), for:UIControlEvents.touchUpInside) addSubview(imageView) addSubview(label) addSubview(button) NSLayoutConstraint.topToTop( view:imageView, toView:self, constant:kImageTop) NSLayoutConstraint.height( view:imageView, constant:kImageHeight) NSLayoutConstraint.equalsHorizontal( view:imageView, toView:self) NSLayoutConstraint.topToBottom( view:label, toView:imageView) NSLayoutConstraint.height( view:label, constant:kLabelHeight) NSLayoutConstraint.equalsHorizontal( view:label, toView:self, margin:kLabelMarginHorizontal) NSLayoutConstraint.topToBottom( view:button, toView:label) NSLayoutConstraint.height( view:button, constant:kButtonHeight) layoutButtonLeft = NSLayoutConstraint.leftToLeft( view:button, toView:self) NSLayoutConstraint.width( view:button, constant:kButtonWidth) } required init?(coder:NSCoder) { return nil } override func layoutSubviews() { let width:CGFloat = bounds.width let remainWidth:CGFloat = width - kButtonWidth let marginLeft:CGFloat = remainWidth / 2.0 layoutButtonLeft.constant = marginLeft super.layoutSubviews() } //MARK: action func actionButton(sender button:UIButton) { controller.back() } }
mit
7a3ac961c36f48a8740058be1af2a2c9
30.966387
82
0.627497
5.728916
false
false
false
false
ryanipete/AmericanChronicle
AmericanChronicle/Code/Modules/AppInfo/AppInfoViewController.swift
1
7240
import MessageUI final class AppInfoViewController: UIViewController { // MARK: Properties var dismissHandler: (() -> Void)? private let bodyLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.textColor = AMCColor.darkGray label.textAlignment = .center label.numberOfLines = 0 label.font = AMCFont.mediumRegular let text = """ American Chronicle gets its data from the 'Chronicling America' website. 'Chronicling America' is a project funded by the National Endowment for \ the Humanities and maintained by the Library of Congress. """ label.text = text return label }() private let websiteButton: TitleButton = { let btn = TitleButton(title: "Visit chroniclingamerica.gov.loc".localized()) btn.translatesAutoresizingMaskIntoConstraints = false btn.heightAnchor.constraint(equalToConstant: Dimension.buttonHeight).isActive = true return btn }() private let separator: UIImageView = { let subview = UIImageView(image: .imageWithFillColor(AMCColor.brightBlue)) subview.translatesAutoresizingMaskIntoConstraints = false subview.heightAnchor.constraint(equalToConstant: 1.0 / UIScreen.main.nativeScale).isActive = true return subview }() private let suggestionsLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.textColor = AMCColor.darkGray label.textAlignment = .center label.numberOfLines = 0 label.font = AMCFont.mediumRegular label.text = "Do you have a question, suggestion or complaint about the app?".localized() return label }() private let suggestionsButton: TitleButton = { let btn = TitleButton(title: "Send us a message".localized()) btn.translatesAutoresizingMaskIntoConstraints = false btn.heightAnchor.constraint(equalToConstant: Dimension.buttonHeight).isActive = true return btn }() // MARK: Init methods func commonInit() { navigationItem.title = "About this app".localized() navigationItem.setLeftButtonTitle("Dismiss".localized(), target: self, action: #selector(didTapDismissButton)) } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } // MARK: Internal methods @objc func didTapDismissButton() { dismissHandler?() } private let messageSubject = "American Chronicle v\(Bundle.main.versionNumber) (Build \(Bundle.main.buildNumber))" private let supportEmail = "[email protected]" private lazy var mailtoURL: URL? = { let str = "mailto://\(supportEmail)?subject=\(messageSubject)" guard let encodedStr = str.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else { assertionFailure() return nil } return URL(string: encodedStr) }() private lazy var gmailURL: URL? = { let str = "googlegmail://co?to=\(supportEmail)&subject=\(messageSubject)" guard let encodedStr = str.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else { assertionFailure() return nil } return URL(string: encodedStr) }() @objc func didTapSuggestionsButton() { if let gmailURL = gmailURL, UIApplication.shared.canOpenURL(gmailURL) { // If the Gmail app is installed, favor it. UIApplication.shared.open(gmailURL, options: [:], completionHandler: nil) } else if let mailtoURL = mailtoURL { // Else, show an alert asking the user to re-install the Mail app. UIApplication.shared.open(mailtoURL, options: [:], completionHandler: nil) } } @objc func didTapWebsiteButton() { let vc = ChroniclingAmericaWebsiteViewController() vc.dismissHandler = { self.dismiss(animated: true, completion: nil) } as (() -> Void) let nvc = UINavigationController(rootViewController: vc) present(nvc, animated: true, completion: nil) } // MARK: UIViewController overrides override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = AMCColor.offWhite websiteButton.addTarget( self, action: #selector(didTapWebsiteButton), for: .touchUpInside) suggestionsButton.addTarget( self, action: #selector(didTapSuggestionsButton), for: .touchUpInside) view.addSubview(bodyLabel) NSLayoutConstraint.activate([ bodyLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: Dimension.horizontalMargin), bodyLabel.topAnchor.constraint(equalTo: view.topAnchor, constant: Dimension.verticalMargin), bodyLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -Dimension.horizontalMargin) ]) view.addSubview(websiteButton) NSLayoutConstraint.activate([ websiteButton.topAnchor.constraint(equalTo: bodyLabel.bottomAnchor, constant: Dimension.verticalSiblingSpacing * 2), websiteButton.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: Dimension.horizontalMargin), websiteButton.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -Dimension.horizontalMargin) ]) view.addSubview(separator) NSLayoutConstraint.activate([ separator.topAnchor.constraint(equalTo: websiteButton.bottomAnchor, constant: Dimension.verticalMargin * 2), separator.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: Dimension.horizontalMargin * 2), separator.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -Dimension.horizontalMargin * 2) ]) view.addSubview(suggestionsLabel) NSLayoutConstraint.activate([ suggestionsLabel.topAnchor.constraint(equalTo: separator.bottomAnchor, constant: Dimension.verticalMargin), suggestionsLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: Dimension.horizontalMargin), suggestionsLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -Dimension.horizontalMargin) ]) view.addSubview(suggestionsButton) NSLayoutConstraint.activate([ suggestionsButton.topAnchor.constraint(equalTo: suggestionsLabel.bottomAnchor, constant: Dimension.verticalSiblingSpacing * 2), suggestionsButton.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: Dimension.horizontalMargin), suggestionsButton.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -Dimension.horizontalMargin) ]) } }
mit
02a546ec8f4952860eef9903dcf12605
41.339181
139
0.673066
5.362963
false
false
false
false
alecthomas/EVReflection
EVReflection/pod/EVObject.swift
1
5713
// // EVObject.swift // // Created by Edwin Vermeer on 5/2/15. // Copyright (c) 2015 evict. All rights reserved. // import Foundation /** Object that will support NSCoding, Printable, Hashable and Equeatable for all properties. Use this object as your base class instead of NSObject and you wil automatically have support for all these protocols. */ public class EVObject: NSObject, NSCoding, Printable, Hashable, Equatable { /** Basic init override is needed so we can use EVObject as a base class. */ public override init(){ super.init() } /** Decode any object :param: theObject The object that we want to decode. :param: aDecoder The NSCoder that will be used for decoding the object. */ public convenience required init(coder: NSCoder) { self.init() EVReflection.decodeObjectWithCoder(self, aDecoder: coder) } /** Convenience init for creating an object whith the property values of a dictionary. */ public convenience required init(dictionary:NSDictionary) { self.init() EVReflection.setPropertiesfromDictionary(dictionary, anyObject: self) } /** Convenience init for creating an object whith the contents of a json string. */ public convenience required init(json:String?) { self.init() var jsonDict = EVReflection.dictionaryFromJson(json) EVReflection.setPropertiesfromDictionary(jsonDict, anyObject: self) } /** Returns the dictionary representation of this object. */ final public func toDictionary() -> NSDictionary { let (reflected, types) = EVReflection.toDictionary(self) return reflected } final public func toJsonString() -> String { return EVReflection.toJsonString(self) } /** Encode this object using a NSCoder :param: aCoder The NSCoder that will be used for encoding the object */ final public func encodeWithCoder(aCoder: NSCoder) { EVReflection.encodeWithCoder(self, aCoder: aCoder) } /** Returns the pritty description of this object :return: The pritty description */ final public override var description: String { get { return EVReflection.description(self) } } /** Returns the hashvalue of this object :return: The hashvalue of this object */ public override var hashValue: Int { get { return EVReflection.hashValue(self) } } /** Function for returning the hash for the NSObject based functionality :return: The hashvalue of this object */ final public override var hash: Int { get { return self.hashValue } } /** Implementation of the NSObject isEqual comparisson method :param: object The object where you want to compare with :return: Returns true if the object is the same otherwise false */ final public override func isEqual(object: AnyObject?) -> Bool { // for isEqual: if let dataObject = object as? EVObject { return dataObject == self // just use our "==" function } else { return false } } /** Implementation of the setValue forUndefinedKey so that we can catch exceptions for when we use an optional Type like Int? in our object. Instead of using Int? you should use NSNumber? :param: value The value that you wanted to set :param: key The name of the property that you wanted to set */ public override func setValue(value: AnyObject!, forUndefinedKey key: String) { if let genericSelf = self as? EVGenericsKVC { genericSelf.setValue(value, forUndefinedKey: key) return } NSLog("\nWARNING: The class '\(EVReflection.swiftStringFromClass(self))' is not key value coding-compliant for the key '\(key)'\n There is no support for optional type, array of optionals or enum properties.\nAs a workaround you can implement the function 'setValue forUndefinedKey' for this. See the unit tests for more information\n") } public func propertyMapping() -> [(String?, String?)] { return [] } } /** Protocol for the workaround when using generics. See WorkaroundSwiftGenericsTests.swift */ public protocol EVGenericsKVC { func setValue(value: AnyObject!, forUndefinedKey key: String) } /** Protocol for the workaround when using an enum with a rawValue of type Int */ public protocol EVRawInt { var rawValue: Int { get } } /** Protocol for the workaround when using an enum with a rawValue of type String */ public protocol EVRawString { var rawValue: String { get } } /** Protocol for the workaround when using an enum with a rawValue of an undefined type */ public protocol EVRaw { var anyRawValue: AnyObject { get } } /** Protocol for the workaround when using an array with nullable values */ public protocol EVArrayConvertable { func convertArray(key: String, array: Any) -> NSArray } /** Implementation for Equatable == :param: lhs The object at the left side of the == :param: rhs The object at the right side of the == :return: True if the objects are the same, otherwise false. */ public func ==(lhs: EVObject, rhs: EVObject) -> Bool { return EVReflection.areEqual(lhs, rhs: rhs) } /** Implementation for Equatable != :param: lhs The object at the left side of the == :param: rhs The object at the right side of the == :return: False if the objects are the the same, otherwise true. */ public func !=(lhs: EVObject, rhs: EVObject) -> Bool { return !EVReflection.areEqual(lhs, rhs: rhs) }
mit
a291a97488442994a9f72b721eec6b26
28.448454
344
0.669526
4.637175
false
false
false
false
augmify/Neon
Source/Neon.swift
6
55644
// // Neon.swift // Neon // // Created by Mike on 9/16/15. // Copyright © 2015 Mike Amaral. All rights reserved. // import UIKit extension UIView { // MARK: Frame shortcuts // /// Get the x origin of a view. /// /// - returns: The minimum x value of the view's frame. /// /// Example /// ------- /// let frame = CGRectMake(10.0, 20.0, 5.0, 7.0) /// frame.x() // returns 10.0 /// func x() -> CGFloat { return CGRectGetMinX(frame) } /// Get the mid x of a view. /// /// - returns: The middle x value of the view's frame /// /// Example /// ------- /// let frame = CGRectMake(10.0, 20.0, 5.0, 7.0) /// frame.midX() // returns 7.5 /// func xMid() -> CGFloat { return CGRectGetMinX(frame) + (CGRectGetWidth(frame) / 2.0) } /// Get the max x of a view. /// /// - returns: The maximum x value of the view's frame /// /// Example /// ------- /// let frame = CGRectMake(10.0, 20.0, 5.0, 7.0) /// frame.maxX() // returns 15.0 /// func xMax() -> CGFloat { return CGRectGetMaxX(frame) } /// Get the y origin of a view. /// /// - returns: The minimum y value of the view's frame. /// /// Example /// ------- /// let frame = CGRectMake(10.0, 20.0, 5.0, 7.0) /// frame.y() // returns 20.0 /// func y() -> CGFloat { return CGRectGetMinY(frame) } /// Get the mid y of a view. /// /// - returns: The middle y value of the view's frame /// /// Example /// ------- /// let frame = CGRectMake(10.0, 20.0, 5.0, 7.0) /// frame.midY() // returns 13.5 /// func yMid() -> CGFloat { return CGRectGetMinY(frame) + (CGRectGetHeight(frame) / 2.0) } /// Get the max y of a view. /// /// - returns: The maximum y value of the view's frame. /// /// Example /// ------- /// let frame = CGRectMake(10.0, 20.0, 5.0, 7.0) /// frame.maxY() // returns 27.0 /// func yMax() -> CGFloat { return CGRectGetMaxY(frame) } /// Get the width of a view. /// /// - returns: The width of the view's frame. /// /// Example /// ------- /// let frame = CGRectMake(10.0, 20.0, 5.0, 7.0) /// frame.width() // returns 5.0 /// func width() -> CGFloat { return CGRectGetWidth(frame) } /// Get the height of a view. /// /// - returns: The height of the view's frame. /// /// Example /// ------- /// let frame = CGRectMake(10.0, 20.0, 5.0, 7.0) /// frame.height() // returns 7.0 /// func height() -> CGFloat { return CGRectGetHeight(frame) } // MARK: Corner // /// /// Specifies a corner of a frame. /// /// **TopLeft**: The upper-left corner of the frame. /// /// **TopRight**: The upper-right corner of the frame. /// /// **BottomLeft**: The bottom-left corner of the frame. /// /// **BottomRight**: The upper-right corner of the frame. /// enum Corner { case TopLeft case TopRight case BottomLeft case BottomRight } // MARK: Edge // /// /// Specifies an edge, or face, of a frame. /// /// **Top**: The top edge of the frame. /// /// **Left**: The left edge of the frame. /// /// **Bottom**: The bottom edge of the frame. /// /// **Right**: The right edge of the frame. /// enum Edge { case Top case Left case Bottom case Right } // MARK: Align Type // /// /// Specifies how a view will be aligned relative to the sibling view. /// /// **ToTheRightMatchingTop**: Specifies that the view should be aligned to the right of a sibling, matching the /// top, or y origin, of the sibling's frame. /// /// **ToTheRightMatchingBottom**: Specifies that the view should be aligned to the right of a sibling, matching /// the bottom, or max y value, of the sibling's frame. /// /// **ToTheRightCentered**: Specifies that the view should be aligned to the right of a sibling, and will be centered /// to either match the vertical center of the sibling's frame or centered vertically within the superview, depending /// on the context. /// /// **ToTheLeftMatchingTop**: Specifies that the view should be aligned to the left of a sibling, matching the top, /// or y origin, of the sibling's frame. /// /// **ToTheLeftMatchingBottom**: Specifies that the view should be aligned to the left of a sibling, matching the /// bottom, or max y value, of the sibling's frame. /// /// **ToTheLeftCentered**: Specifies that the view should be aligned to the left of a sibling, and will be centered /// to either match the vertical center of the sibling's frame or centered vertically within the superview, depending /// on the context. /// /// **UnderMatchingLeft**: Specifies that the view should be aligned under a sibling, matching the left, or x origin, /// of the sibling's frame. /// /// **UnderMatchingRight**: Specifies that the view should be aligned under a sibling, matching the right, or max y /// of the sibling's frame. /// /// **UnderCentered**: Specifies that the view should be aligned under a sibling, and will be centered to either match /// the horizontal center of the sibling's frame or centered horizontally within the superview, depending on the context. /// /// **AboveMatchingLeft**: Specifies that the view should be aligned above a sibling, matching the left, or x origin /// of the sibling's frame. /// /// **AboveMatchingRight**: Specifies that the view should be aligned above a sibling, matching the right, or max x /// of the sibling's frame. /// /// **AboveCentered**: Specifies that the view should be aligned above a sibling, and will be centered to either match /// the horizontal center of the sibling's frame or centered horizontally within the superview, depending on the context. /// enum Align { case ToTheRightMatchingTop case ToTheRightMatchingBottom case ToTheRightCentered case ToTheLeftMatchingTop case ToTheLeftMatchingBottom case ToTheLeftCentered case UnderMatchingLeft case UnderMatchingRight case UnderCentered case AboveMatchingLeft case AboveMatchingRight case AboveCentered } // MARK: Group Type // /// /// Specifies how a group will be laid out. /// /// **Horizontal**: Specifies that the views should be aligned relative to eachother horizontally. /// /// **Vertical**: Specifies that the views should be aligned relative to eachother vertically. /// enum Group { case Horizontal case Vertical } // MARK: Filling superview // /// Fill the superview, with optional padding values. /// /// - note: If you don't want padding, simply call `fillSuperview()` with no parameters. /// /// - parameters: /// - left: The padding between the left side of the view and the superview. /// /// - right: The padding between the right side of the view and the superview. /// /// - top: The padding between the top of the view and the superview. /// /// - bottom: The padding between the bottom of the view and the superview. /// func fillSuperview(left left: CGFloat = 0, right: CGFloat = 0, top: CGFloat = 0, bottom: CGFloat = 0) { if superview == nil { print("[NEON] Warning: Can't anchor view without superview!") return } let width : CGFloat = superview!.width() - (left + right) let height : CGFloat = superview!.height() - (top + bottom) frame = CGRectMake(left, top, width, height) } // MARK: Anchoring in superview // /// Anchor a view in the center of its superview. /// /// - parameters: /// - width: The width of the view. /// /// - height: The height of the view. /// func anchorInCenter(width width: CGFloat, height: CGFloat) { if superview == nil { print("[NEON] Warning: Can't anchor view without superview!") return } let xOrigin : CGFloat = (superview!.width() / 2.0) - (width / 2.0) let yOrigin : CGFloat = (superview!.height() / 2.0) - (height / 2.0) frame = CGRectMake(xOrigin, yOrigin, width, height) } /// Anchor a view in one of the four corners of its superview. /// /// - parameters: /// - corner: The `CornerType` value used to specify in which corner the view will be anchored. /// /// - xPad: The *horizontal* padding applied to the view inside its superview, which can be applied /// to the left or right side of the view, depending upon the `CornerType` specified. /// /// - yPad: The *vertical* padding applied to the view inside its supeview, which will either be on /// the top or bottom of the view, depending upon the `CornerType` specified. /// /// - width: The width of the view. /// /// - height: The height of the view. /// func anchorInCorner(corner: Corner, xPad: CGFloat, yPad: CGFloat, width: CGFloat, height: CGFloat) { if superview == nil { print("[NEON] Warning: Can't anchor view without superview!") return } var xOrigin : CGFloat = 0.0 var yOrigin : CGFloat = 0.0 switch corner { case .TopLeft: xOrigin = xPad yOrigin = yPad case .BottomLeft: xOrigin = xPad yOrigin = superview!.height() - height - yPad case .TopRight: xOrigin = superview!.width() - width - xPad yOrigin = yPad case .BottomRight: xOrigin = superview!.width() - width - xPad yOrigin = superview!.height() - height - yPad } frame = CGRectMake(xOrigin, yOrigin, width, height) } /// Anchor a view in its superview, centered on a given edge. /// /// - parameters: /// - edge: The `Edge` used to specify which face of the superview the view /// will be anchored against and centered relative to. /// /// - padding: The padding applied to the view inside its superview. How this padding is applied /// will vary depending on the `Edge` provided. Views centered against the top or bottom of /// their superview will have the padding applied above or below them respectively, whereas views /// centered against the left or right side of their superview will have the padding applied to the /// right and left sides respectively. /// /// - width: The width of the view. /// /// - height: The height of the view. /// func anchorToEdge(edge: Edge, padding: CGFloat, width: CGFloat, height: CGFloat) { if superview == nil { print("[NEON] Warning: Can't anchor view without superview!") return } var xOrigin : CGFloat = 0.0 var yOrigin : CGFloat = 0.0 switch edge { case .Top: xOrigin = (superview!.width() / 2.0) - (width / 2.0) yOrigin = padding case .Left: xOrigin = padding yOrigin = (superview!.height() / 2.0) - (height / 2.0) case .Bottom: xOrigin = (superview!.width() / 2.0) - (width / 2.0) yOrigin = superview!.height() - height - padding case .Right: xOrigin = superview!.width() - width - padding yOrigin = (superview!.height() / 2.0) - (height / 2.0) } frame = CGRectMake(xOrigin, yOrigin, width, height) } /// Anchor a view in its superview, centered on a given edge and filling either the width or /// height of that edge. For example, views anchored to the `.Top` or `.Bottom` will have /// their widths automatically sized to fill their superview, with the xPad applied to both /// the left and right sides of the view. /// /// - parameters: /// - edge: The `Edge` used to specify which face of the superview the view /// will be anchored against, centered relative to, and expanded to fill. /// /// - xPad: The horizontal padding applied to the view inside its superview. If the `Edge` /// specified is `.Top` or `.Bottom`, this padding will be applied to the left and right sides /// of the view when it fills the width superview. /// /// - yPad: The vertical padding applied to the view inside its superview. If the `Edge` /// specified is `.Left` or `.Right`, this padding will be applied to the top and bottom sides /// of the view when it fills the height of the superview. /// /// - otherSize: The size parameter that is *not automatically calculated* based on the provided /// edge. For example, views anchored to the `.Top` or `.Bottom` will have their widths automatically /// calculated, so `otherSize` will be applied to their height, and subsequently views anchored to /// the `.Left` and `.Right` will have `otherSize` applied to their width as their heights are /// automatically calculated. /// func anchorAndFillEdge(edge: Edge, xPad: CGFloat, yPad: CGFloat, otherSize: CGFloat) { if superview == nil { print("[NEON] Warning: Can't anchor view without superview!") return } var xOrigin : CGFloat = 0.0 var yOrigin : CGFloat = 0.0 var width : CGFloat = 0.0 var height : CGFloat = 0.0 switch edge { case .Top: xOrigin = xPad yOrigin = yPad width = superview!.width() - (2 * xPad) height = otherSize case .Left: xOrigin = xPad yOrigin = yPad width = otherSize height = superview!.height() - (2 * yPad) case .Bottom: xOrigin = xPad yOrigin = superview!.height() - otherSize - yPad width = superview!.width() - (2 * xPad) height = otherSize case .Right: xOrigin = superview!.width() - otherSize - xPad yOrigin = yPad width = otherSize height = superview!.height() - (2 * yPad) } frame = CGRectMake(xOrigin, yOrigin, width, height) } // MARK: Align relative to sibling views // /// Align a view relative to a sibling view in the same superview. /// /// - parameters: /// - align: The `Align` type used to specify where and how this view is aligned with its sibling. /// /// - relativeTo: The sibling view this view will be aligned relative to. **NOTE:** Ensure this sibling view shares /// the same superview as this view, and that the sibling view is not the same as this view, otherwise a /// `fatalError` is thrown. /// /// - padding: The padding to be applied between this view and the sibling view, which is applied differently /// depending on the `Align` specified. For example, if aligning `.ToTheRightOfMatchingTop` the padding is used /// to adjust the x origin of this view so it sits to the right of the sibling view, while the y origin is /// automatically calculated to match the sibling view. /// /// - width: The width of the view. /// /// - height: The height of the view. /// func align(align: Align, relativeTo sibling: UIView, padding: CGFloat, width: CGFloat, height: CGFloat) { if superview == nil { print("[NEON] Warning: Can't align view without superview!") return } if self == sibling { fatalError("[NEON] Can't align view relative to itself!") } if superview != sibling.superview { fatalError("[NEON] Can't align view relative to another view in a different superview!") } var xOrigin : CGFloat = 0.0 var yOrigin : CGFloat = 0.0 switch align { case .ToTheRightMatchingTop: xOrigin = sibling.xMax() + padding yOrigin = sibling.y() break case .ToTheRightMatchingBottom: xOrigin = sibling.xMax() + padding yOrigin = sibling.yMax() - height break case .ToTheRightCentered: xOrigin = sibling.xMax() + padding yOrigin = sibling.yMid() - (height / 2.0) break case .ToTheLeftMatchingTop: xOrigin = sibling.x() - width - padding yOrigin = sibling.y() break case .ToTheLeftMatchingBottom: xOrigin = sibling.x() - width - padding yOrigin = sibling.yMax() - height break case .ToTheLeftCentered: xOrigin = sibling.x() - width - padding yOrigin = sibling.yMid() - (height / 2.0) break case .UnderMatchingLeft: xOrigin = sibling.x() yOrigin = sibling.yMax() + padding break case .UnderMatchingRight: xOrigin = sibling.xMax() - width yOrigin = sibling.yMax() + padding break case .UnderCentered: xOrigin = sibling.xMid() - (width / 2.0) yOrigin = sibling.yMax() + padding break case .AboveMatchingLeft: xOrigin = sibling.x() yOrigin = sibling.y() - padding - height break case .AboveMatchingRight: xOrigin = sibling.xMax() - width yOrigin = sibling.y() - padding - height break case .AboveCentered: xOrigin = sibling.xMid() - (width / 2.0) yOrigin = sibling.y() - padding - height break } frame = CGRectMake(xOrigin, yOrigin, width, height) } /// Align a view relative to a sibling view in the same superview, and automatically expand the width to fill /// the superview with equal padding between the superview and sibling view. /// /// - parameters: /// - align: The `Align` type used to specify where and how this view is aligned with its sibling. /// /// - relativeTo: The sibling view this view will be aligned relative to. **NOTE:** Ensure this sibling view shares /// the same superview as this view, and that the sibling view is not the same as this view, otherwise a /// `fatalError` is thrown. /// /// - padding: The padding to be applied between this view, the sibling view and the superview. /// /// - height: The height of the view. /// func alignAndFillWidth(align align: Align, relativeTo sibling: UIView, padding: CGFloat, height: CGFloat) { if superview == nil { print("[NEON] Warning: Can't align view without superview!") return } if self == sibling { fatalError("[NEON] Can't align view relative to itself!") } if superview != sibling.superview { fatalError("[NEON] Can't align view relative to another view in a different superview!") } let superviewWidth = superview!.width() var xOrigin : CGFloat = 0.0 var yOrigin : CGFloat = 0.0 var width : CGFloat = 0.0 switch align { case .ToTheRightMatchingTop: xOrigin = sibling.xMax() + padding yOrigin = sibling.y() width = superviewWidth - xOrigin - padding break case .ToTheRightMatchingBottom: xOrigin = sibling.xMax() + padding yOrigin = sibling.yMax() - height width = superviewWidth - xOrigin - padding break case .ToTheRightCentered: xOrigin = sibling.xMax() + padding yOrigin = sibling.yMid() - (height / 2.0) width = superviewWidth - xOrigin - padding break case .ToTheLeftMatchingTop: xOrigin = padding yOrigin = sibling.y() width = sibling.x() - (2 * padding) break case .ToTheLeftMatchingBottom: xOrigin = padding yOrigin = sibling.yMax() - height width = sibling.x() - (2 * padding) break case .ToTheLeftCentered: xOrigin = padding yOrigin = sibling.yMid() - (height / 2.0) width = sibling.x() - (2 * padding) break case .UnderMatchingLeft: xOrigin = sibling.x() yOrigin = sibling.yMax() + padding width = superviewWidth - xOrigin - padding break case .UnderMatchingRight: xOrigin = padding yOrigin = sibling.yMax() + padding width = superviewWidth - (superviewWidth - sibling.xMax()) - padding break case .UnderCentered: xOrigin = padding yOrigin = sibling.yMax() + padding width = superviewWidth - (2 * padding) break case .AboveMatchingLeft: xOrigin = sibling.x() yOrigin = sibling.y() - padding - height width = superviewWidth - xOrigin - padding break case .AboveMatchingRight: xOrigin = padding yOrigin = sibling.y() - padding - height width = superviewWidth - (superviewWidth - sibling.xMax()) - padding break case .AboveCentered: xOrigin = padding yOrigin = sibling.y() - padding - height width = superviewWidth - (2 * padding) break } if width < 0.0 { width = 0.0 } frame = CGRectMake(xOrigin, yOrigin, width, height) } /// Align a view relative to a sibling view in the same superview, and automatically expand the height to fill /// the superview with equal padding between the superview and sibling view. /// /// - parameters: /// - align: The `Align` type used to specify where and how this view is aligned with its sibling. /// /// - relativeTo: The sibling view this view will be aligned relative to. **NOTE:** Ensure this sibling view shares /// the same superview as this view, and that the sibling view is not the same as this view, otherwise a /// `fatalError` is thrown. /// /// - padding: The padding to be applied between this view, the sibling view and the superview. /// /// - width: The width of the view. /// func alignAndFillHeight(align align: Align, relativeTo sibling: UIView, padding: CGFloat, width: CGFloat) { if superview == nil { print("[NEON] Warning: Can't align view without superview!") return } if self == sibling { fatalError("[NEON] Can't align view relative to itself!") } if superview != sibling.superview { fatalError("[NEON] Can't align view relative to another view in a different superview!") } let superviewHeight = superview!.height() var xOrigin : CGFloat = 0.0 var yOrigin : CGFloat = 0.0 var height : CGFloat = 0.0 switch align { case .ToTheRightMatchingTop: xOrigin = sibling.xMax() + padding yOrigin = sibling.y() height = superviewHeight - sibling.y() - padding break case .ToTheRightMatchingBottom: xOrigin = sibling.xMax() + padding yOrigin = padding height = superviewHeight - (superviewHeight - sibling.yMax()) - padding break case .ToTheRightCentered: xOrigin = sibling.xMax() + padding yOrigin = padding height = superviewHeight - (2 * padding) break case .ToTheLeftMatchingTop: xOrigin = sibling.x() - width - padding yOrigin = sibling.y() height = superviewHeight - sibling.y() - padding break case .ToTheLeftMatchingBottom: xOrigin = sibling.x() - width - padding yOrigin = padding height = superviewHeight - (superviewHeight - sibling.yMax()) - padding break case .ToTheLeftCentered: xOrigin = sibling.x() - width - padding yOrigin = padding height = superviewHeight - (2 * padding) break case .UnderMatchingLeft: xOrigin = sibling.x() yOrigin = sibling.yMax() + padding height = superviewHeight - yOrigin - padding break case .UnderMatchingRight: xOrigin = sibling.xMax() - width yOrigin = sibling.yMax() + padding height = superviewHeight - yOrigin - padding break case .UnderCentered: xOrigin = sibling.xMid() - (width / 2.0) yOrigin = sibling.yMax() + padding height = superviewHeight - yOrigin - padding break case .AboveMatchingLeft: xOrigin = sibling.x() yOrigin = padding height = sibling.y() - (2 * padding) break case .AboveMatchingRight: xOrigin = sibling.xMax() - width yOrigin = padding height = sibling.y() - (2 * padding) break case .AboveCentered: xOrigin = sibling.xMid() - (width / 2.0) yOrigin = padding height = sibling.y() - (2 * padding) break } if height < 0.0 { height = 0.0 } frame = CGRectMake(xOrigin, yOrigin, width, height) } /// Align a view relative to a sibling view in the same superview, and automatically expand the width AND height /// to fill the superview with equal padding between the superview and sibling view. /// /// - parameters: /// - align: The `Align` type used to specify where and how this view is aligned with its sibling. /// /// - relativeTo: The sibling view this view will be aligned relative to. **NOTE:** Ensure this sibling view shares /// the same superview as this view, and that the sibling view is not the same as this view, otherwise a /// `fatalError` is thrown. /// /// - padding: The padding to be applied between this view, the sibling view and the superview. /// func alignAndFill(align align: Align, relativeTo sibling: UIView, padding: CGFloat) { if superview == nil { print("[NEON] Warning: Can't align view without superview!") return } if self == sibling { fatalError("[NEON] Can't align view relative to itself!") } if superview != sibling.superview { fatalError("[NEON] Can't align view relative to another view in a different superview!") } let superviewWidth = superview!.width() let superviewHeight = superview!.height() var xOrigin : CGFloat = 0.0 var yOrigin : CGFloat = 0.0 var width : CGFloat = 0.0 var height : CGFloat = 0.0 switch align { case .ToTheRightMatchingTop: xOrigin = sibling.xMax() + padding yOrigin = sibling.y() width = superviewWidth - xOrigin - padding height = superviewHeight - yOrigin - padding break case .ToTheRightMatchingBottom: xOrigin = sibling.xMax() + padding yOrigin = padding width = superviewWidth - xOrigin - padding height = superviewHeight - (superviewHeight - sibling.yMax()) - padding break case .ToTheRightCentered: xOrigin = sibling.xMax() + padding yOrigin = padding width = superviewWidth - xOrigin - padding height = superviewHeight - (2 * padding) break case .ToTheLeftMatchingTop: xOrigin = padding yOrigin = sibling.y() width = superviewWidth - (superviewWidth - sibling.x()) - (2 * padding) height = superviewHeight - yOrigin - padding break case .ToTheLeftMatchingBottom: xOrigin = padding yOrigin = padding width = superviewWidth - (superviewWidth - sibling.x()) - (2 * padding) height = superviewHeight - (superviewHeight - sibling.yMax()) - padding break case .ToTheLeftCentered: xOrigin = padding yOrigin = padding width = superviewWidth - (superviewWidth - sibling.x()) - (2 * padding) height = superviewHeight - (2 * padding) break case .UnderMatchingLeft: xOrigin = sibling.x() yOrigin = sibling.yMax() + padding width = superviewWidth - xOrigin - padding height = superviewHeight - yOrigin - padding break case .UnderMatchingRight: xOrigin = padding yOrigin = sibling.yMax() + padding width = superviewWidth - (superviewWidth - sibling.xMax()) - padding height = superviewHeight - yOrigin - padding break case .UnderCentered: xOrigin = padding yOrigin = sibling.yMax() + padding width = superviewWidth - (2 * padding) height = superviewHeight - yOrigin - padding break case .AboveMatchingLeft: xOrigin = sibling.x() yOrigin = padding width = superviewWidth - xOrigin - padding height = superviewHeight - (superviewHeight - sibling.y()) - (2 * padding) break case .AboveMatchingRight: xOrigin = padding yOrigin = padding width = superviewWidth - (superviewWidth - sibling.xMax()) - padding height = superviewHeight - (superviewHeight - sibling.y()) - (2 * padding) break case .AboveCentered: xOrigin = padding yOrigin = padding width = superviewWidth - (2 * padding) height = superviewHeight - (superviewHeight - sibling.y()) - (2 * padding) break } if width < 0.0 { width = 0.0 } if height < 0.0 { height = 0.0 } frame = CGRectMake(xOrigin, yOrigin, width, height) } // MARK: Align between siblings // /// Align a view between two sibling views horizontally, automatically expanding the width to extend the full /// horizontal span between the `primaryView` and the `secondaryView`, with equal padding on both sides. /// /// - parameters: /// - align: The `Align` type used to specify where and how this view is aligned with the primary view. /// /// - primaryView: The primary sibling view this view will be aligned relative to. /// /// - secondaryView: The secondary sibling view this view will be automatically sized to fill the space between. /// /// - padding: The horizontal padding to be applied between this view and both sibling views. /// /// - height: The height of the view. /// func alignBetweenHorizontal(align align: Align, primaryView: UIView, secondaryView: UIView, padding: CGFloat, height: CGFloat) { if superview == nil { print("[NEON] Warning: Can't align view without superview!") return } if self == primaryView || self == secondaryView { fatalError("[NEON] Can't align view relative to itself!") } if superview != primaryView.superview || superview != secondaryView.superview { fatalError("[NEON] Can't align view relative to another view in a different superview!") } let superviewWidth : CGFloat = superview!.width() var xOrigin : CGFloat = 0.0 var yOrigin : CGFloat = 0.0 var width : CGFloat = 0.0 switch align { case .ToTheRightMatchingTop: xOrigin = primaryView.xMax() + padding yOrigin = primaryView.y() width = superviewWidth - primaryView.xMax() - (superviewWidth - secondaryView.x()) - (2 * padding) break case .ToTheRightMatchingBottom: xOrigin = primaryView.xMax() + padding yOrigin = primaryView.yMax() - height width = superviewWidth - primaryView.xMax() - (superviewWidth - secondaryView.x()) - (2 * padding) break case .ToTheRightCentered: xOrigin = primaryView.xMax() + padding yOrigin = primaryView.yMid() - (height / 2.0) width = superviewWidth - primaryView.xMax() - (superviewWidth - secondaryView.x()) - (2 * padding) break case .ToTheLeftMatchingTop: xOrigin = secondaryView.xMax() + padding yOrigin = primaryView.y() width = superviewWidth - secondaryView.xMax() - (superviewWidth - primaryView.x()) - (2 * padding) break case .ToTheLeftMatchingBottom: xOrigin = secondaryView.xMax() + padding yOrigin = primaryView.yMax() - height width = superviewWidth - secondaryView.xMax() - (superviewWidth - primaryView.x()) - (2 * padding) break case .ToTheLeftCentered: xOrigin = secondaryView.xMax() + padding yOrigin = primaryView.yMid() - (height / 2.0) width = superviewWidth - secondaryView.xMax() - (superviewWidth - primaryView.x()) - (2 * padding) break case .UnderMatchingLeft, .UnderMatchingRight, .UnderCentered, .AboveMatchingLeft, .AboveMatchingRight, .AboveCentered: fatalError("[NEON] Invalid Align specified for alignBetweenHorizonal().") } if width < 0.0 { width = 0.0 } frame = CGRectMake(xOrigin, yOrigin, width, height) } /// Align a view between two sibling views vertically, automatically expanding the height to extend the full /// vertical span between the `primaryView` and the `secondaryView`, with equal padding above and below. /// /// - parameters: /// - align: The `Align` type used to specify where and how this view is aligned with the primary view. /// /// - primaryView: The primary sibling view this view will be aligned relative to. /// /// - secondaryView: The secondary sibling view this view will be automatically sized to fill the space between. /// /// - padding: The horizontal padding to be applied between this view and both sibling views. /// /// - width: The width of the view. /// func alignBetweenVertical(align align: Align, primaryView: UIView, secondaryView: UIView, padding: CGFloat, width: CGFloat) { if superview == nil { print("[NEON] Warning: Can't align view without superview!") return } if self == primaryView || self == secondaryView { fatalError("[NEON] Can't align view relative to itself!") } if superview != primaryView.superview || superview != secondaryView.superview { fatalError("[NEON] Can't align view relative to another view in a different superview!") } let superviewHeight : CGFloat = superview!.height() var xOrigin : CGFloat = 0.0 var yOrigin : CGFloat = 0.0 var height : CGFloat = 0.0 switch align { case .UnderMatchingLeft: xOrigin = primaryView.x() yOrigin = primaryView.yMax() + padding height = superviewHeight - primaryView.yMax() - (superviewHeight - secondaryView.y()) - (2 * padding) break case .UnderMatchingRight: xOrigin = primaryView.xMax() - width yOrigin = primaryView.yMax() + padding height = superviewHeight - primaryView.yMax() - (superviewHeight - secondaryView.y()) - (2 * padding) break case .UnderCentered: xOrigin = primaryView.xMid() - (width / 2.0) yOrigin = primaryView.yMax() + padding height = superviewHeight - primaryView.yMax() - (superviewHeight - secondaryView.y()) - (2 * padding) break case .AboveMatchingLeft: xOrigin = primaryView.x() yOrigin = secondaryView.yMax() + padding height = superviewHeight - secondaryView.yMax() - (superviewHeight - primaryView.y()) - (2 * padding) break case .AboveMatchingRight: xOrigin = primaryView.xMax() - width yOrigin = secondaryView.yMax() + padding height = superviewHeight - secondaryView.yMax() - (superviewHeight - primaryView.y()) - (2 * padding) break case .AboveCentered: xOrigin = primaryView.xMid() - (width / 2.0) yOrigin = secondaryView.yMax() + padding height = superviewHeight - secondaryView.yMax() - (superviewHeight - primaryView.y()) - (2 * padding) break case .ToTheLeftMatchingTop, .ToTheLeftMatchingBottom, .ToTheLeftCentered, .ToTheRightMatchingTop, .ToTheRightMatchingBottom, .ToTheRightCentered: fatalError("[NEON] Invalid Align specified for alignBetweenVertical().") } if height < 0 { height = 0 } frame = CGRectMake(xOrigin, yOrigin, width, height) } // MARK: Grouping siblings // /// Tell a view to group an array of its subviews centered, specifying the padding between each subview, /// as well as the size of each. /// /// - parameters: /// - group: The `Group` type specifying if the subviews will be laid out horizontally or vertically in the center. /// /// - views: The array of views to grouped in the center. Depending on if the views are gouped horizontally /// or vertically, they will be positioned in order from left-to-right and top-to-bottom, respectively. /// /// - padding: The padding to be applied between the subviews. /// /// - width: The width of each subview. /// /// - height: The height of each subview. /// func groupInCenter(group group: Group, views: [UIView], padding: CGFloat, width: CGFloat, height: CGFloat) { if superview == nil { print("[NEON] Warning: Attempted to group subviews but view doesn't have a superview of its own.") return } if views.count == 0 { print("[NEON] Warning: No subviews provided to groupInCenter().") return } var xOrigin : CGFloat = 0.0 var yOrigin : CGFloat = 0.0 var xAdjust : CGFloat = 0.0 var yAdjust : CGFloat = 0.0 switch group { case .Horizontal: xOrigin = (self.width() - (CGFloat(views.count) * width) - (CGFloat(views.count - 1) * padding)) / 2.0 yOrigin = (self.height() / 2.0) - (height / 2.0) xAdjust = width + padding break case .Vertical: xOrigin = (self.width() / 2.0) - (width / 2.0) yOrigin = (self.height() - (CGFloat(views.count) * height) - (CGFloat(views.count - 1) * padding)) / 2.0 yAdjust = height + padding break } for view in views { if view.superview != self { fatalError("[NEON] Can't group view that is a subview of another view!") } view.frame = CGRectMake(xOrigin, yOrigin, width, height) xOrigin += xAdjust yOrigin += yAdjust } } /// Tell a view to group an array of its subviews in one of its corners, specifying the padding between each subview, /// as well as the size of each. /// /// - parameters: /// - group: The `Group` type specifying if the subviews will be laid out horizontally or vertically in the corner. /// /// - views: The array of views to grouped in the specified corner. Depending on if the views are gouped horizontally /// or vertically, they will be positioned in order from left-to-right and top-to-bottom, respectively. /// /// - inCorner: The specified corner the views will be grouped in. /// /// - padding: The padding to be applied between the subviews and their superview. /// /// - width: The width of each subview. /// /// - height: The height of each subview. /// func groupInCorner(group group: Group, views: [UIView], inCorner corner: Corner, padding: CGFloat, width: CGFloat, height: CGFloat) { switch group { case .Horizontal: groupInCornerHorizontally(views, inCorner: corner, padding: padding, width: width, height: height) break case .Vertical: groupInCornerVertically(views, inCorner: corner, padding: padding, width: width, height: height) break } } /// Tell a view to group an array of its subviews against one of its edges, specifying the padding between each subview /// and their superview, as well as the size of each. /// /// - parameters: /// - group: The `Group` type specifying if the subviews will be laid out horizontally or vertically against the specified /// edge. /// /// - views: The array of views to grouped against the spcified edge. Depending on if the views are gouped horizontally /// or vertically, they will be positioned in-order from left-to-right and top-to-bottom, respectively. /// /// - againstEdge: The specified edge the views will be grouped against. /// /// - padding: The padding to be applied between each of the subviews and their superview. /// /// - width: The width of each subview. /// /// - height: The height of each subview. /// func groupAgainstEdge(group group: Group, views: [UIView], againstEdge edge: Edge, padding: CGFloat, width: CGFloat, height: CGFloat) { if superview == nil { print("[NEON] Warning: Attempted to group subviews but view doesn't have a superview of its own.") return } if views.count == 0 { print("[NEON] Warning: No subviews provided to groupAgainstEdge().") return } var xOrigin : CGFloat = 0.0 var yOrigin : CGFloat = 0.0 var xAdjust : CGFloat = 0.0 var yAdjust : CGFloat = 0.0 switch edge { case .Top: if group == .Horizontal { xOrigin = (self.width() - (CGFloat(views.count) * width) - (CGFloat(views.count - 1) * padding)) / 2.0 xAdjust = width + padding } else { xOrigin = (self.width() / 2.0) - (width / 2.0) yAdjust = height + padding } yOrigin = padding break case .Left: if group == .Horizontal { yOrigin = (self.height() / 2.0) - (height / 2.0) xAdjust = width + padding } else { yOrigin = (self.height() - (CGFloat(views.count) * height) - (CGFloat(views.count - 1) * padding)) / 2.0 yAdjust = height + padding } xOrigin = padding break case .Bottom: if group == .Horizontal { xOrigin = (self.width() - (CGFloat(views.count) * width) - (CGFloat(views.count - 1) * padding)) / 2.0 xAdjust = width + padding } else { xOrigin = (self.width() / 2.0) - (width / 2.0) yAdjust = -(height + padding) } yOrigin = self.height() - height - padding break case .Right: if group == .Horizontal { yOrigin = (self.height() / 2.0) - (height / 2.0) xAdjust = -(width + padding) } else { yOrigin = (self.height() - (CGFloat(views.count) * height) - (CGFloat(views.count - 1) * padding)) / 2.0 yAdjust = height + padding } xOrigin = self.width() - width - padding break } for view in views { if view.superview != self { fatalError("[NEON] Can't group view that is a subview of another view!") } view.frame = CGRectMake(xOrigin, yOrigin, width, height) xOrigin += xAdjust yOrigin += yAdjust } } /// Tell a view to group an array of its subviews relative to another of that view's subview, specifying the padding between /// each. /// /// - parameters: /// - group: The `Group` type specifying if the subviews will be laid out horizontally or vertically against the specified /// sibling. /// /// - andAlign: the `Align` type specifying how the views will be aligned relative to the sibling. /// /// - views: The array of views to grouped against the sibling. Depending on if the views are gouped horizontally /// or vertically, they will be positioned in-order from left-to-right and top-to-bottom, respectively. /// /// - relativeTo: The sibling view that the views will be aligned relative to. /// /// - padding: The padding to be applied between each of the subviews and the sibling. /// /// - width: The width of each subview. /// /// - height: The height of each subview. /// func groupAndAlign(group group: Group, andAlign align: Align, views: [UIView], relativeTo sibling: UIView, padding: CGFloat, width: CGFloat, height: CGFloat) { switch group { case .Horizontal: groupAndAlignHorizontal(align, views: views, relativeTo: sibling, padding: padding, width: width, height: height) break case .Vertical: groupAndAlignVertical(align, views: views, relativeTo: sibling, padding: padding, width: width, height: height) break } } // MARK: Private utils // private func groupInCornerHorizontally(views: [UIView], inCorner corner: Corner, padding: CGFloat, width: CGFloat, height: CGFloat) { if superview == nil { print("[NEON] Warning: Attempted to group subviews but view doesn't have a superview of its own.") return } if views.count == 0 { print("[NEON] Warning: No subviews provided to groupInCorner().") return } var xOrigin : CGFloat = 0.0 var yOrigin : CGFloat = 0.0 let xAdjust : CGFloat = width + padding switch corner { case .TopLeft: xOrigin = padding yOrigin = padding break case .TopRight: xOrigin = self.width() - ((CGFloat(views.count) * width) + (CGFloat(views.count) * padding)) yOrigin = padding break case .BottomLeft: xOrigin = padding yOrigin = self.height() - height - padding break case .BottomRight: xOrigin = self.width() - ((CGFloat(views.count) * width) + (CGFloat(views.count) * padding)) yOrigin = self.height() - height - padding break } for view in views { if view.superview != self { fatalError("[NEON] Can't group view that is a subview of another view!") } view.frame = CGRectMake(xOrigin, yOrigin, width, height) xOrigin += xAdjust } } private func groupInCornerVertically(views: [UIView], inCorner corner: Corner, padding: CGFloat, width: CGFloat, height: CGFloat) { if superview == nil { print("[NEON] Warning: Attempted to group subviews but view doesn't have a superview of its own.") return } if views.count == 0 { print("[NEON] Warning: No subviews provided to groupInCorner().") return } var xOrigin : CGFloat = 0.0 var yOrigin : CGFloat = 0.0 let yAdjust : CGFloat = height + padding switch corner { case .TopLeft: xOrigin = padding yOrigin = padding break case .TopRight: xOrigin = self.width() - width - padding yOrigin = padding break case .BottomLeft: xOrigin = padding yOrigin = self.height() - ((CGFloat(views.count) * height) + (CGFloat(views.count) * padding)) break case .BottomRight: xOrigin = self.width() - width - padding yOrigin = self.height() - ((CGFloat(views.count) * height) + (CGFloat(views.count) * padding)) break } for view in views { if view.superview != self { fatalError("[NEON] Can't group view that is a subview of another view!") } view.frame = CGRectMake(xOrigin, yOrigin, width, height) yOrigin += yAdjust } } private func groupAndAlignHorizontal(align: Align, views: [UIView], relativeTo sibling: UIView, padding: CGFloat, width: CGFloat, height: CGFloat) { if superview == nil { print("[NEON] Warning: Attempted to group subviews but view doesn't have a superview of its own.") return } if views.count == 0 { print("[NEON] Warning: No subviews provided to groupAgainstEdge().") return } var xOrigin : CGFloat = 0.0 var yOrigin : CGFloat = 0.0 var xAdjust : CGFloat = width + padding switch align { case .ToTheRightMatchingTop: xOrigin = sibling.xMax() + padding yOrigin = sibling.y() break case .ToTheRightMatchingBottom: xOrigin = sibling.xMax() + padding yOrigin = sibling.yMax() - height break case .ToTheRightCentered: xOrigin = sibling.xMax() + padding yOrigin = sibling.yMid() - (height / 2.0) break case .ToTheLeftMatchingTop: xOrigin = sibling.x() - width - padding yOrigin = sibling.y() xAdjust = -xAdjust break case .ToTheLeftMatchingBottom: xOrigin = sibling.x() - width - padding yOrigin = sibling.yMax() - height xAdjust = -xAdjust break case .ToTheLeftCentered: xOrigin = sibling.x() - width - padding yOrigin = sibling.yMid() - (height / 2.0) xAdjust = -xAdjust break case .UnderMatchingLeft: xOrigin = sibling.x() yOrigin = sibling.yMax() + padding break case .UnderMatchingRight: xOrigin = sibling.xMax() - (CGFloat(views.count) * width) - (CGFloat(views.count - 1) * padding) yOrigin = sibling.yMax() + padding break case .UnderCentered: xOrigin = sibling.xMid() - ((CGFloat(views.count) * width) + (CGFloat(views.count - 1) * padding)) / 2.0 yOrigin = sibling.yMax() + padding break case .AboveMatchingLeft: xOrigin = sibling.x() yOrigin = sibling.y() - height - padding break case .AboveMatchingRight: xOrigin = sibling.xMax() - (CGFloat(views.count) * width) - (CGFloat(views.count - 1) * padding) yOrigin = sibling.y() - height - padding break case .AboveCentered: xOrigin = sibling.xMid() - ((CGFloat(views.count) * width) + (CGFloat(views.count - 1) * padding)) / 2.0 yOrigin = sibling.y() - height - padding break } for view in views { if view.superview != self { fatalError("[NEON] Can't group view that is a subview of another view!") } view.frame = CGRectMake(xOrigin, yOrigin, width, height) xOrigin += xAdjust } } private func groupAndAlignVertical(align: Align, views: [UIView], relativeTo sibling: UIView, padding: CGFloat, width: CGFloat, height: CGFloat) { if superview == nil { print("[NEON] Warning: Attempted to group subviews but view doesn't have a superview of its own.") return } if views.count == 0 { print("[NEON] Warning: No subviews provided to groupAgainstEdge().") return } var xOrigin : CGFloat = 0.0 var yOrigin : CGFloat = 0.0 var yAdjust : CGFloat = height + padding switch align { case .ToTheRightMatchingTop: xOrigin = sibling.xMax() + padding yOrigin = sibling.y() break case .ToTheRightMatchingBottom: xOrigin = sibling.xMax() + padding yOrigin = sibling.yMax() - (CGFloat(views.count) * height) - (CGFloat(views.count - 1) * padding) break case .ToTheRightCentered: xOrigin = sibling.xMax() + padding yOrigin = sibling.yMid() - ((CGFloat(views.count) * height) + CGFloat(views.count - 1) * padding) / 2.0 break case .ToTheLeftMatchingTop: xOrigin = sibling.x() - width - padding yOrigin = sibling.y() break case .ToTheLeftMatchingBottom: xOrigin = sibling.x() - width - padding yOrigin = sibling.yMax() - (CGFloat(views.count) * height) - (CGFloat(views.count - 1) * padding) break case .ToTheLeftCentered: xOrigin = sibling.x() - width - padding yOrigin = sibling.yMid() - ((CGFloat(views.count) * height) + CGFloat(views.count - 1) * padding) / 2.0 break case .UnderMatchingLeft: xOrigin = sibling.x() yOrigin = sibling.yMax() + padding break case .UnderMatchingRight: xOrigin = sibling.xMax() - width yOrigin = sibling.yMax() + padding break case .UnderCentered: xOrigin = sibling.xMid() - (width / 2.0) yOrigin = sibling.yMax() + padding break case .AboveMatchingLeft: xOrigin = sibling.x() yOrigin = sibling.y() - height - padding yAdjust = -yAdjust break case .AboveMatchingRight: xOrigin = sibling.xMax() - width yOrigin = sibling.y() - height - padding yAdjust = -yAdjust break case .AboveCentered: xOrigin = sibling.xMid() - (width / 2.0) yOrigin = sibling.y() - height - padding yAdjust = -yAdjust break } for view in views { if view.superview != self { fatalError("[NEON] Can't group view that is a subview of another view!") } view.frame = CGRectMake(xOrigin, yOrigin, width, height) yOrigin += yAdjust } } }
mit
b6c76d476e5f03817dd7cf71b5826ac5
34.040302
163
0.567277
4.655928
false
false
false
false
ceecer1/open-muvr
ios/Lift/LiftServer/ExerciseModel.swift
3
4045
import Foundation struct Exercise { /// /// MSG alias /// typealias MuscleGroupKey = String /// /// Exercise intensity value /// typealias ExerciseIntensityKey = Double /// /// Default exercise intensities /// static let defaultIntensities = [ ExerciseIntensity.veryLight, ExerciseIntensity.light, ExerciseIntensity.moderate, ExerciseIntensity.hard, ExerciseIntensity.veryHard, ExerciseIntensity.brutal ] /// /// Single muscle group cell holding the key, which is the communication key with the server /// together with the (localisable) title and set of exercises /// struct MuscleGroup { /// the key that identifies the muscle group to the server var key: MuscleGroupKey /// the title—in the future received from the server (localised) var title: String /// the sample/suggested exercises—in the future received from the server (localised) var exercises: [String] } /// /// Session properties /// struct SessionProps { /// the start date var startDate: NSDate /// the targeted muscle groups var muscleGroupKeys: [String] /// the intended intensity var intendedIntensity: ExerciseIntensityKey } /// Metric struct Metric { // value // metricUnit var value: Double var metricUnit: String //Mass or Distance } /// /// Sigle exercise /// struct Exercise { var name: String var intensity: ExerciseIntensityKey? var metric: Metric? } /// /// Exercise set /// struct ExerciseSet { var exercises: [Exercise] } /// /// Exercise intensity /// struct ExerciseIntensity { var intensity: ExerciseIntensityKey var title: String var userNotes: String /// Default intensities static let veryLight = ExerciseIntensity(intensity: 0.30, title: "VeryLight".localized(), userNotes: "VeryLightUserNotes".localized()) static let light = ExerciseIntensity(intensity: 0.45, title: "Light".localized(), userNotes: "LightUserNotes".localized()) static let moderate = ExerciseIntensity(intensity: 0.65, title: "Moderate".localized(), userNotes: "ModerateUserNotes".localized()) static let hard = ExerciseIntensity(intensity: 0.75, title: "Hard".localized(), userNotes: "HardUserNotes".localized()) static let veryHard = ExerciseIntensity(intensity: 0.87, title: "VeryHard".localized(), userNotes: "VeryHardUserNotes".localized()) static let brutal = ExerciseIntensity(intensity: 0.95, title: "Brutal".localized(), userNotes: "BrutalUserNotes".localized()) } /// /// Classification model metadata /// struct ModelMetadata { var version: Int } /// /// Session intensity /// struct SessionIntensity { var intended: ExerciseIntensityKey var actual: ExerciseIntensityKey } /// /// Session date summary /// struct SessionDate { var date: NSDate var sessionIntensities: [SessionIntensity] } /// /// Session summary model /// struct SessionSummary { var id: NSUUID var sessionProps: SessionProps var setIntensities: [ExerciseIntensityKey] } /// /// Session suggestions /// struct SessionSuggestion { /// the date associated with the suggestion var date: NSDate /// the target muscle groups var muscleGroupKeys: [String] /// the intended intensity var intendedIntensity: ExerciseIntensityKey } /// /// Association of list of exercise with a particular session props /// struct ExerciseSession { var sessionProps: SessionProps var sets: [ExerciseSet] } }
apache-2.0
33cf3f3e6f60db87620c89d4c48594da
26.678082
142
0.604553
5.019876
false
false
false
false
tripleCC/GanHuoCode
GanHuoShareExtension/TPCShareItem.swift
1
761
// // TPCShareItem.swift // TPCShareextension // // Created by tripleCC on 16/4/12. // Copyright © 2016年 tripleCC. All rights reserved. // import UIKit public enum TPCShareItemType: Int { case Input case Display } public class TPCShareItem { var placeholder: String! var content: String! var contentImage: UIImage! var clickAction: ((String) -> Void)? var type: TPCShareItemType! init(placeholder: String = "", content: String? = "", contentImage: UIImage, type: TPCShareItemType = .Input, clickAction: ((String) -> Void)? = nil) { self.placeholder = placeholder self.content = content self.contentImage = contentImage self.type = type self.clickAction = clickAction } }
mit
c4ab7dad8f50821ec82ee4a99a50ed14
24.3
155
0.655673
4.010582
false
false
false
false
groschovskiy/firebase-for-banking-app
Demo/Banking/BBTransactionView.swift
1
1848
// // BBTransactionView.swift // Barclays // // Created by Dmitriy Groschovskiy on 25/09/2016. // Copyright © 2016 Barclays Bank, PLC. All rights reserved. // import UIKit import Firebase class BBTransactionView: UIViewController { var paymentIdent : String! @IBOutlet weak var backgroundViewLayout: UIView! @IBOutlet weak var paidReferenceLabel: UILabel! @IBOutlet weak var paidToAccountLabel: UILabel! @IBOutlet weak var paidFromAccountLabel: UILabel! @IBOutlet weak var paymentAmountLabel: UILabel! @IBOutlet weak var paymentDateLabel: UILabel! var transactionTicket: [BBPurchaseModel] = [] override func viewDidLoad() { super.viewDidLoad() self.backgroundViewLayout.layer.cornerRadius = 10 self.backgroundViewLayout.layer.masksToBounds = true let userRef = FIRAuth.auth()?.currentUser?.uid let purchaseRef = FIRDatabase.database().reference(withPath: "History/\(userRef!)/\(paymentIdent!)") purchaseRef.queryOrdered(byChild: "purchaseValue").observe(.value, with: { snapshot in let dataSnapshot = snapshot.value as! [String: AnyObject] self.paidReferenceLabel.text = "Reference #\(dataSnapshot["purchaseReference"] as! Int)" self.paidFromAccountLabel.text = dataSnapshot["purchaseCard"] as? String self.paidToAccountLabel.text = dataSnapshot["purchaseStore"] as? String self.paymentAmountLabel.text = String(format: "%.2f", dataSnapshot["purchaseAmount"] as! Double) self.paymentDateLabel.text = dataSnapshot["purchaseDate"] as? String }) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func closeController(sender: UIBarButtonItem) { self.dismiss(animated: true, completion: nil) } }
apache-2.0
fa53ceea9f4d5a8b0c35fd4801c30f43
35.94
108
0.698971
4.605985
false
false
false
false
dreamsxin/swift
test/Constraints/casts.swift
3
4762
// RUN: %target-parse-verify-swift class B { init() {} } class D : B { override init() { super.init() } } var seven : Double = 7 var pair : (Int, Double) = (1, 2) var closure : (Int, Int) -> Int = { $0 + $1 } var d_as_b : B = D() var b_as_d = B() as! D var bad_b_as_d : D = B() // expected-error{{cannot convert value of type 'B' to specified type 'D'}} var d = D() var b = B() var d_as_b_2 : B = d var b_as_d_2 = b as! D var b_is_d:Bool = B() is D // FIXME: Poor diagnostic below. var bad_d_is_b:Bool = D() is B // expected-warning{{always true}} func base_class_archetype_casts<T : B>(_ t: T) { var _ : B = t _ = B() as! T var _ : T = B() // expected-error{{cannot convert value of type 'B' to specified type 'T'}} let b = B() _ = b as! T var _:Bool = B() is T var _:Bool = b is T var _:Bool = t is B // expected-warning{{always true}} _ = t as! D } protocol P1 { func p1() } protocol P2 { func p2() } struct S1 : P1 { func p1() {} } class C1 : P1 { func p1() {} } class D1 : C1 {} struct S2 : P2 { func p2() {} } struct S3 {} struct S12 : P1, P2 { func p1() {} func p2() {} } func protocol_archetype_casts<T : P1>(_ t: T, p1: P1, p2: P2, p12: protocol<P1, P2>) { // Coercions. var _ : P1 = t var _ : P2 = t // expected-error{{value of type 'T' does not conform to specified type 'P2'}} // Checked unconditional casts. _ = p1 as! T _ = p2 as! T _ = p12 as! T _ = t as! S1 _ = t as! S12 _ = t as! C1 _ = t as! D1 _ = t as! S2 _ = S1() as! T _ = S12() as! T _ = C1() as! T _ = D1() as! T _ = S2() as! T // Type queries. var _:Bool = p1 is T var _:Bool = p2 is T var _:Bool = p12 is T var _:Bool = t is S1 var _:Bool = t is S12 var _:Bool = t is C1 var _:Bool = t is D1 var _:Bool = t is S2 } func protocol_concrete_casts(_ p1: P1, p2: P2, p12: protocol<P1, P2>) { // Checked unconditional casts. _ = p1 as! S1 _ = p1 as! C1 _ = p1 as! D1 _ = p1 as! S12 _ = p1 as! protocol<P1, P2> _ = p2 as! S1 _ = p12 as! S1 _ = p12 as! S2 _ = p12 as! S12 _ = p12 as! S3 // Type queries. var _:Bool = p1 is S1 var _:Bool = p1 is C1 var _:Bool = p1 is D1 var _:Bool = p1 is S12 var _:Bool = p1 is protocol<P1, P2> var _:Bool = p2 is S1 var _:Bool = p12 is S1 var _:Bool = p12 is S2 var _:Bool = p12 is S12 var _:Bool = p12 is S3 } func conditional_cast(_ b: B) -> D? { return b as? D } @objc protocol ObjCProto1 {} @objc protocol ObjCProto2 {} protocol NonObjCProto : class {} @objc class ObjCClass {} class NonObjCClass {} func objc_protocol_casts(_ op1: ObjCProto1, opn: NonObjCProto) { _ = ObjCClass() as! ObjCProto1 _ = ObjCClass() as! ObjCProto2 _ = ObjCClass() as! protocol<ObjCProto1, ObjCProto2> _ = ObjCClass() as! NonObjCProto _ = ObjCClass() as! protocol<ObjCProto1, NonObjCProto> _ = op1 as! protocol<ObjCProto1, ObjCProto2> _ = op1 as! protocol<ObjCProto2> _ = op1 as! protocol<ObjCProto1, NonObjCProto> _ = opn as! ObjCProto1 _ = NonObjCClass() as! ObjCProto1 } func dynamic_lookup_cast(_ dl: AnyObject) { _ = dl as! ObjCProto1 _ = dl as! ObjCProto2 _ = dl as! protocol<ObjCProto1, ObjCProto2> } // Cast to subclass with generic parameter inference class C2<T> : B { } class C3<T> : C2<[T]> { func f(_ x: T) { } } var c2i : C2<[Int]> = C3() var c3iOpt = c2i as? C3 c3iOpt?.f(5) var b1 = c2i is C3 var c2f: C2<Float>? = b as? C2 var c2f2: C2<[Float]>? = b as! C3 // <rdar://problem/15633178> var f: (Float) -> Float = { $0 as Float } var f2: (B) -> Bool = { $0 is D } func metatype_casts<T, U>(_ b: B.Type, t:T.Type, u: U.Type) { _ = b is D.Type _ = T.self is U.Type _ = T.self.dynamicType is U.Type.Type _ = b.dynamicType is D.Type // expected-warning{{always fails}} _ = b is D.Type.Type // expected-warning{{always fails}} } // <rdar://problem/17017851> func forcedDowncastToOptional(_ b: B) { var dOpt: D? = b as! D // expected-warning{{treating a forced downcast to 'D' as optional will never produce 'nil'}} // expected-note@-1{{use 'as?' to perform a conditional downcast to 'D'}}{{22-23=?}} // expected-note@-2{{add parentheses around the cast to silence this warning}}{{18-18=(}}{{25-25=)}} dOpt = b as! D // expected-warning{{treating a forced downcast to 'D' as optional will never produce 'nil'}} // expected-note@-1{{use 'as?' to perform a conditional downcast to 'D'}}{{14-15=?}} // expected-note@-2{{add parentheses around the cast to silence this warning}}{{10-10=(}}{{17-17=)}} dOpt = (b as! D) _ = dOpt } _ = b1 as Int // expected-error {{cannot convert value of type 'Bool' to type 'Int' in coercion}} _ = seven as Int // expected-error {{cannot convert value of type 'Double' to type 'Int' in coercion}}
apache-2.0
4d676254cd086256dbdfd58d87413649
21.894231
118
0.583998
2.693439
false
false
false
false
wookay/AppConsole
AppConsole/Base/ConsoleRouter.swift
1
19947
// // ConsoleRouter.swift // ConsoleApp // // Created by wookyoung on 3/13/16. // Copyright © 2016 factorcat. All rights reserved. // import UIKit import Swifter enum ChainType { case Go case Stop } enum TypeMatchType { case Match case None } typealias ChainResult = (ChainType, AnyObject?) typealias TypeMatchResult = (TypeMatchType, AnyObject?) public class ConsoleRouter { let type_handler = TypeHandler() var env = [String: AnyObject]() // MARK: ConsoleRouter - route func route(server: HttpServer, initial: AnyObject) { server["/"] = { req in return .OK(.Html("<html><head><title>iOS REPL with Swifter.jl + AppConsole</title></head><body>iOS REPL with <a href=\"https://github.com/wookay/Swifter.jl\">Swifter.jl</a> + <a href=\"https://github.com/wookay/AppConsole\">AppConsole</a></body></html>")) } server["/initial"] = { req in return self.result(initial) } server["/image"] = { req in for (name, value) in req.queryParams { if "path" == name { var lhs = [TypePair]() do { if let data = value.dataUsingEncoding(NSUTF8StringEncoding), let json = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) as? [AnyObject] { lhs = self.typepairs(json) } } catch { } let (_,object) = self.chain(nil, lhs, full: true) if let view = object as? UIView { return self.result_image(view.to_data()) } else if let screen = object as? UIScreen { return self.result_image(screen.to_data()) } } else if "address" == name { if let view = self.from_address(value) as? UIView { return self.result_image(view.to_data()) } } } return self.result_failed() } server["/query"] = { req in var query = [String: AnyObject]() do { let data = NSData(bytes: req.body, length: req.body.count) query = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) as! [String: AnyObject] } catch { } if let type = query["type"] as? String, lhs = query["lhs"] as? [AnyObject] { switch type { case "Getter": let (success,object) = self.chain_getter(lhs) if case .Go = success { if let obj = object { return self.result(obj) } else { return self.result_nil() } } else { return self.result_failed(object) } case "Setter": if let rhs = query["rhs"] as? [AnyObject] { let (success, left) = self.chain(nil, self.typepairs(lhs), full: false) let (_, value) = self.chain_getter(rhs) if case .Go = success { if let obj = left { dispatch_async(dispatch_get_main_queue(), { self.chain_setter(obj, lhs: lhs, value: value) }) if let val = value { return self.result(val) } else { return self.result_nil() } } else { return self.result_nil() } } else { return self.result_failed() } } default: break } } return self.result_failed() } } } // MARK: ConsoleRouter - chains extension ConsoleRouter { func chain_getter(lhs: [AnyObject]) -> ChainResult { let vec: [TypePair] = typepairs(lhs) return chain(nil, vec, full: true) } func chain_setter(obj: AnyObject, lhs: [AnyObject], value: AnyObject?) -> AnyObject? { let vec: [TypePair] = typepairs(lhs) if let pair = vec.last { var val = value let method = pair.second as! String if let str = value as? String { if "@" == ns_return_types(obj, method) { if str.hasPrefix("<UICTFont: 0x") { if let font = UIFontFromString(str) { val = font } } else if str.hasPrefix("UIDevice") { if let color = UIColorFromString(str) { val = color } } } } self.type_handler.setter_handle(obj, "set" + method.uppercase_first() + ":", value: val, second: nil) } return nil } func typepair_chain(obj: AnyObject?, pair: TypePair) -> ChainResult { switch pair.first { case "string": return (.Stop, pair.second) case "int": return (.Go, pair.second) case "float": return (.Go, ValueObject(type: "f", value: pair.second)) case "bool": return (.Go, ValueObject(type: "B", value: pair.second)) case "address": return (.Go, from_address(String(pair.second))) case "symbol": if let str = pair.second as? String { switch str { case "nil": return (.Stop, nil) default: if let o = obj { let sel = NSSelectorFromString(str) if swift_property_names(o).contains(str) { let (match, val) = type_handler.getter_handle(o, str) if case .Match = match { return (.Go, val) } else { return (.Go, swift_property_for_key(o, str)) } } else if o.respondsToSelector(sel) { let (match, val) = type_handler.getter_handle(o, str) if case .Match = match { return (.Go, val) } else if nil == val { return (.Stop, ValueObject(type: "nil", value: "")) } } } } } return (.Stop, nil) case "call": if let nameargs = pair.second as? [AnyObject] { let (match, val) = typepair_callargs(obj, nameargs: nameargs) switch match { case .Match: return (.Go, val) case .None: return (.Stop, nil) } } else if let name = pair.second as? String { if let o = obj { let (match, val) = type_handler.typepair_method(o, name: name, []) switch match { case .Match: return (.Go, val) case .None: return (.Stop, nil) } } } default: break } return (.Stop, nil) } func typepair_callargs(object: AnyObject?, nameargs: [AnyObject]) -> TypeMatchResult { if let name = nameargs.first as? String, let arguments = nameargs.last { if let obj = object { if let args = arguments as? [AnyObject] { if 1 == args.count { if let strargs = args[0] as? [String] { if strargs == ["symbol", "nil"] { return type_handler.typepair_method(obj, name: name, [ValueObject(type: "nil", value: "")]) } } } return type_handler.typepair_method(obj, name: name, args) } else { return type_handler.typepair_method(obj, name: name, []) } } else { switch arguments { case is [Float]: return type_handler.typepair_function(name, arguments as! [Float]) case is [AnyObject]: if let args = arguments as? [[AnyObject]] { return type_handler.typepair_constructor(name, args) } default: break } } } return (.None, nil) } func chain_dictionary(dict: [String: AnyObject], _ key: String, _ nth: Int, _ vec: [TypePair], full: Bool) -> ChainResult { if let obj = dict[key] { return chain(obj, vec.slice_to_end(nth), full: full) } else { switch key { case "keys": return chain([String](dict.keys), vec.slice_to_end(nth), full: full) case "values": return chain([AnyObject](dict.values), vec.slice_to_end(nth), full: full) default: break } } return (.Stop, dict) } func chain_array(arr: [AnyObject], _ method: String, _ nth: Int, _ vec: [TypePair], full: Bool) -> ChainResult { switch method { case "sort": if let a = arr as? [String] { return chain(a.sort(<), vec.slice_to_end(nth), full: full) } case "first": return chain(arr.first, vec.slice_to_end(nth), full: full) case "last": return chain(arr.last, vec.slice_to_end(nth), full: full) default: break } return (.Stop, arr) } func chain(object: AnyObject?, _ vec: [TypePair], full: Bool) -> ChainResult { if let obj = object { let cnt = vec.count for (idx,pair) in vec.enumerate() { if !full && idx == cnt-1 { continue } let (match, val) = typepair_chain(obj, pair: pair) if case .Go = match { if let method = self.var_or_method(pair) { switch method { case is Int: if let arr = obj as? NSArray, let idx = method as? Int { if arr.count > idx { return chain(arr[idx], vec.slice_to_end(1), full: full) } } default: break } } return chain(val, vec.slice_to_end(1), full: full) } else { if let method = self.var_or_method(pair) { switch method { case is String: let meth = method as! String let (mat,ob) = type_handler.getter_handle(obj, meth) if case .Match = mat { if let o = ob { return chain(o, vec.slice_to_end(1), full: full) } else { return (.Go, val) } } else if let dict = obj as? [String: AnyObject] { return chain_dictionary(dict, meth, 1, vec, full: full) } else if let arr = obj as? [AnyObject] { return chain_array(arr, meth, 1, vec, full: full) } else { return (.Stop, val) } default: break } } return chain(val, vec.slice_to_end(1), full: full) } } return (.Go, obj) } else { if let pair = vec.first { let (cont, obj) = typepair_chain(nil, pair: pair) if case .Go = cont { return chain(obj, vec.slice_to_end(1), full: full) } else { if let one = pair.second as? String { if let c: AnyClass = NSClassFromString(one) { return chain(c, vec.slice_to_end(1), full: full) } else if env.keys.contains(one) { return chain(env[one], vec.slice_to_end(1), full: full) } else { let (mat,constant) = type_handler.typepair_constant(one) if case .Match = mat { return (.Go, constant) } else { return (.Stop, obj) } } } } } return (.Stop, nil) } } } struct TypePair: CustomStringConvertible { var first: String var second: AnyObject var description: String { get { return "TypePair(\(first), \(second))" } } } // MARK: ConsoleRouter - utils extension ConsoleRouter { public func register(name: String, object: AnyObject) { env[name] = object } func from_address(address: String) -> AnyObject? { var u: UInt64 = 0 NSScanner(string: address).scanHexLongLong(&u) let ptr = UnsafeMutablePointer<UInt>(bitPattern: UInt(u)) let obj = unsafeBitCast(ptr, AnyObject.self) return obj } func addressof(obj: AnyObject) -> String { return NSString(format: "%p", unsafeBitCast(obj, Int.self)) as String } func var_or_method(pair: TypePair) -> AnyObject? { switch pair.second { case is String: if let str = pair.second as? String { if str.hasSuffix("()") { let method = str.slice(0, to: str.characters.count - 2) return method } else if let num = Int(str) { return num } else { return str } } case is Int: if let num = pair.second as? Int { return num } default: break } return nil } func typepairs(syms: [AnyObject]) -> [TypePair] { var list = [TypePair]() for sym in syms { switch sym { case is Float: if String(sym).containsString(".") { list.append(TypePair(first: "float", second: sym)) } else { list.append(TypePair(first: "int", second: sym)) } case let n as Bool: list.append(TypePair(first: "bool", second: n)) case let array as [AnyObject]: if array.count > 2 { Log.info("array ", array) } list.append(TypePair(first: array[0] as! String, second: array[1])) case let str as String: list.append(TypePair(first: "string", second: str)) case let any: Log.info("any", any) list.append(TypePair(first: "any", second: any)) } } return list } } // MARK: ConsoleRouter - result extension ConsoleRouter { func result(value: AnyObject) -> HttpResponse { switch value { case is ValueObject: if let val = value as? ValueObject { switch val.type { case "v": return result_void() case "B": return result_bool(val.value) case "{CGRect={CGPoint=dd}{CGSize=dd}}", "{CGRect={CGPoint=ff}{CGSize=ff}}": return result_string(val.value) default: if let num = val.value as? NSNumber { if num.stringValue.containsString("e+") { return result_any(String(num)) } else { return result_any(num.floatValue) } } else { return result_any(val.value) } } } case is Int: return result_int(value) case is String: return result_string(value) case is UIView, is UIScreen: return .OK(.Json(["typ": "view", "address": addressof(value), "value": String(value)])) case is [String: AnyObject]: var d = [String: String]() for (k,v) in (value as! [String: AnyObject]) { d[k] = String(v) } return result_any(d) case is [AnyObject]: let a = (value as! [AnyObject]).map { x in String(x) } return result_any(a) default: break } return .OK(.Json(["typ": "any", "address": addressof(value), "value": String(value)])) } func result_any_with_address(value: AnyObject) -> HttpResponse { return .OK(.Json(["typ": "any", "address": addressof(value), "value": value])) } func result_any(value: AnyObject) -> HttpResponse { return .OK(.Json(["typ": "any", "value": value])) } func result_int(value: AnyObject) -> HttpResponse { return .OK(.Json(["typ": "any", "value": value])) } func result_string(value: AnyObject) -> HttpResponse { return .OK(.Json(["typ": "string", "value": value])) } func result_bool(value: AnyObject) -> HttpResponse { return .OK(.Json(["typ": "bool", "value": value])) } func result_void() -> HttpResponse { return .OK(.Json(["typ": "symbol", "value": "nothing"])) } func result_image(imagedata: NSData?) -> HttpResponse { let headers = ["Content-Type": "image/png"] if let data = imagedata { let writer: (HttpResponseBodyWriter -> Void) = { writer in writer.write(Array(UnsafeBufferPointer(start: UnsafePointer<UInt8>(data.bytes), count: data.length))) } return .RAW(200, "OK", headers, writer) } return result_failed() } func result_nil() -> HttpResponse { return .OK(.Json(["typ": "symbol", "value": "nothing"])) } func result_failed(obj: AnyObject? = nil) -> HttpResponse { if let val = obj as? ValueObject { return .OK(.Json(["typ": val.type, "value": val.value])) } else { return .OK(.Json(["typ": "symbol", "value": "Failed"])) } } } // MARK: Swifter.HttpResponse - Equatable public func ==(lhs: HttpResponse, rhs: HttpResponse) -> Bool { switch (lhs,rhs) { case let (.OK(.Json(lok)), .OK(.Json(rok))): return String(lok) == String(rok) default: break } return false }
mit
f86b3bec8ccbef2d78cc3e149f67a31a
35.201452
268
0.432117
4.749048
false
false
false
false