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
inaka/Otec
Otec/NewsDataSource.swift
1
2002
// // NewsDataSource.swift // Otec // // Copyright (c) 2016 Inaka - http://inaka.net/ // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit class NewsDataSource: NSObject, UITableViewDataSource { let news: [News] init(news: [News]) { self.news = news } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.news.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if let cell = tableView.dequeueReusableCellWithIdentifier(Constants.NewsFeedCellIdentifier) as? NewsTableViewCell { cell.news = self.news[indexPath.row] return cell } let cell = NSBundle.mainBundle().loadNibNamed(Constants.NewsFeedCellClassName, owner: self, options: nil).first as! NewsTableViewCell cell.news = self.news[indexPath.row] return cell } }
apache-2.0
6c5687bd88328353aa74c11f192208a3
39.04
141
0.717283
4.699531
false
false
false
false
LeeShiYoung/RxSwiftXinWen
XW/XW/Classes/News/ViewController/HomeViewController.swift
1
2558
// // HomeViewController.swift // XW // // Created by 李世洋 on 2017/10/13. // Copyright © 2017年 浙江聚有财金融服务外包有限公司. All rights reserved. // import UIKit class HomeViewController: BaseViewController { @IBOutlet weak var titleView: PageTitleView! lazy var viewModel = HomeViewModel() override func viewDidLoad() { super.viewDidLoad() titleView.titles.value = titles } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let pageVC = segue.destination if pageVC is UIPageViewController { let page = pageVC as! UIPageViewController page.dataSource = self page.setViewControllers([viewControllers.first!], direction: .forward, animated: true, completion: nil) for subview in page.view.subviews { if subview is UIScrollView { (subview as! UIScrollView).rx.contentOffset.subscribe(onNext: {[weak self] point in self?.viewModel.offsetObservable.value = point }) .disposed(by: disposebag) } } } } fileprivate lazy var viewControllers: [UIViewController] = { var controllers = [NewsViewController]() for title in titles { let newVc = R.storyboard.main.newsViewController()! newVc.newsTtile = title.value controllers.append(newVc) } return controllers }() fileprivate lazy var titles: [PageModel] = Array<PageModel>.mapPlist(path: R.file.titlesPlist.path()) } extension HomeViewController: UIPageViewControllerDataSource { func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { let index = viewControllers.index(of: viewController) guard var idx = index, idx > 0 else { return nil } idx-=1 return viewControllers[idx] } func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { let index = viewControllers.index(of: viewController) guard var idx = index, idx < viewControllers.count - 1 else { return nil } idx+=1 return viewControllers[idx] } func presentationCount(for pageViewController: UIPageViewController) -> Int { return viewControllers.count } }
apache-2.0
2f5d904bef1510d31fc4b3b6302475ee
33.040541
149
0.637158
5.280922
false
false
false
false
kylef/CommandKit
Sources/Commander/ArgumentParser.swift
1
6571
private enum Arg : CustomStringConvertible, Equatable { /// A positional argument case argument(String) /// A boolean like option, `--version`, `--help`, `--no-clean`. case option(String) /// A flag case flag(Set<Character>) var description:String { switch self { case .argument(let value): return value case .option(let key): return "--\(key)" case .flag(let flags): return "-\(String(flags))" } } var type:String { switch self { case .argument: return "argument" case .option: return "option" case .flag: return "flag" } } } private func == (lhs: Arg, rhs: Arg) -> Bool { return lhs.description == rhs.description } public struct ArgumentParserError : Error, Equatable, CustomStringConvertible { public let description: String public init(_ description: String) { self.description = description } } public func ==(lhs: ArgumentParserError, rhs: ArgumentParserError) -> Bool { return lhs.description == rhs.description } public final class ArgumentParser : ArgumentConvertible, CustomStringConvertible { fileprivate var arguments:[Arg] public typealias Option = String public typealias Flag = Character /// Initialises the ArgumentParser with an array of arguments public init(arguments: [String]) { self.arguments = arguments.map { argument in if argument.first == "-" { let flags = argument[argument.index(after: argument.startIndex)..<argument.endIndex] if flags.first == "-" { let option = flags[flags.index(after: flags.startIndex)..<flags.endIndex] return .option(String(option)) } return .flag(Set(flags)) } return .argument(argument) } } public init(parser: ArgumentParser) throws { arguments = parser.arguments } public var description:String { return arguments.map { $0.description }.joined(separator: " ") } public var isEmpty: Bool { return arguments.first { $0 != .argument("") } == nil } public var remainder:[String] { return arguments.map { $0.description } } /// Returns the first positional argument in the remaining arguments. /// This will remove the argument from the remaining arguments. public func shift() -> String? { for (index, argument) in arguments.enumerated() { switch argument { case .argument(let value): arguments.remove(at: index) return value default: continue } } return nil } /// Returns the value for an option (--name Kyle, --name=Kyle) public func shiftValue(for name: Option) throws -> String? { return try shiftValues(for: name)?.first } /// Returns the value for an option (--name Kyle, --name=Kyle) public func shiftValues(for name: Option, count: Int = 1) throws -> [String]? { var index = 0 var hasOption = false for argument in arguments { switch argument { case .option(let option): if option == name { hasOption = true break } fallthrough default: index += 1 } if hasOption { break } } if hasOption { arguments.remove(at: index) // Pop option return try (0..<count).map { i in if arguments.count > index { let argument = arguments.remove(at: index) switch argument { case .argument(let value): return value default: throw ArgumentParserError("Unexpected \(argument.type) `\(argument)` as a value for `--\(name)`") } } throw ArgumentError.missingValue(argument: "--\(name)") } } return nil } /// Returns whether an option was specified in the arguments public func hasOption(_ name: Option) -> Bool { var index = 0 for argument in arguments { switch argument { case .option(let option): if option == name { arguments.remove(at: index) return true } default: break } index += 1 } return false } /// Returns whether a flag was specified in the arguments public func hasFlag(_ flag: Flag) -> Bool { var index = 0 for argument in arguments { switch argument { case .flag(let option): var options = option if options.contains(flag) { options.remove(flag) arguments.remove(at: index) if !options.isEmpty { arguments.insert(.flag(options), at: index) } return true } default: break } index += 1 } return false } /// Returns the value for a flag (-n Kyle) public func shiftValue(for flag: Flag) throws -> String? { return try shiftValues(for: flag)?.first } /// Returns the value for a flag (-n Kyle) public func shiftValues(for flag: Flag, count: Int = 1) throws -> [String]? { var index = 0 var hasFlag = false for argument in arguments { switch argument { case .flag(let flags): if flags.contains(flag) { hasFlag = true break } fallthrough default: index += 1 } if hasFlag { break } } if hasFlag { arguments.remove(at: index) return try (0..<count).map { i in if arguments.count > index { let argument = arguments.remove(at: index) switch argument { case .argument(let value): return value default: throw ArgumentParserError("Unexpected \(argument.type) `\(argument)` as a value for `-\(flag)`") } } throw ArgumentError.missingValue(argument: "-\(flag)") } } return nil } /// Returns the value for an option (--name Kyle, --name=Kyle) or flag (-n Kyle) public func shiftValue(for name: Option, or flag: Flag?) throws -> String? { if let value = try shiftValue(for: name) { return value } else if let flag = flag, let value = try shiftValue(for: flag) { return value } return nil } /// Returns the values for an option (--name Kyle, --name=Kyle) or flag (-n Kyle) public func shiftValues(for name: Option, or flag: Flag?, count: Int = 1) throws -> [String]? { if let value = try shiftValues(for: name, count: count) { return value } else if let flag = flag, let value = try shiftValues(for: flag, count: count) { return value } return nil } }
bsd-3-clause
9d793626f465499911b12f5710a40fd1
23.247232
109
0.591234
4.351656
false
false
false
false
danielallsopp/Charts
ChartsDemo-OSX/ChartsDemo-OSX/Demos/BarDemoViewController.swift
7
2087
// // BarDemoViewController.swift // ChartsDemo-OSX // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts import Foundation import Cocoa import Charts public class BarDemoViewController: NSViewController { @IBOutlet var barChartView: BarChartView! override public func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. let xs = Array(1..<10).map { return Double($0) } let ys1 = xs.map { i in return sin(Double(i / 2.0 / 3.141 * 1.5)) } let ys2 = xs.map { i in return cos(Double(i / 2.0 / 3.141)) } let yse1 = ys1.enumerate().map { idx, i in return BarChartDataEntry(value: i, xIndex: idx) } let yse2 = ys2.enumerate().map { idx, i in return BarChartDataEntry(value: i, xIndex: idx) } let data = BarChartData(xVals: xs) let ds1 = BarChartDataSet(yVals: yse1, label: "Hello") ds1.colors = [NSUIColor.redColor()] data.addDataSet(ds1) let ds2 = BarChartDataSet(yVals: yse2, label: "World") ds2.colors = [NSUIColor.blueColor()] data.addDataSet(ds2) self.barChartView.data = data self.barChartView.gridBackgroundColor = NSUIColor.whiteColor() self.barChartView.descriptionText = "Barchart Demo" } @IBAction func save(sender: AnyObject) { let panel = NSSavePanel() panel.allowedFileTypes = ["png"] panel.beginSheetModalForWindow(self.view.window!) { (result) -> Void in if result == NSFileHandlingPanelOKButton { if let path = panel.URL?.path { self.barChartView.saveToPath(path, format: .PNG, compressionQuality: 1.0) } } } } override public func viewWillAppear() { self.barChartView.animate(xAxisDuration: 1.0, yAxisDuration: 1.0) } }
apache-2.0
a44aeddf47b03a50f3570f1041bb2338
31.123077
100
0.600862
4.303093
false
false
false
false
Roommate-App/roomy
roomy/Pods/IBAnimatable/Sources/Enums/MaskType.swift
2
2239
// // Created by Jake Lin on 12/13/15. // Copyright © 2015 IBAnimatable. All rights reserved. // import UIKit public typealias CustomMaskProvider = (CGSize) -> UIBezierPath /** Mask type for masking an IBAnimatable UI element. */ public enum MaskType: IBEnum { /// For circle shape with diameter equals to min(width, height). case circle /// For ellipse shape. case ellipse /// For polygon shape with `n` sides. (min: 3, the default: 6). case polygon(sides: Int) /// For star shape with n points (min: 3, default: 5) case star(points: Int) /// For isosceles triangle shape. The triangle's height is equal to the view's frame height. If the view is a square, the triangle is equilateral. case triangle /// For wave shape with `direction` (up or down, default: up), width (default: 40) and offset (default: 0) case wave(direction: WaveDirection, width: Double, offset: Double) /// For parallelogram shape with an angle (default: 60). If `angle == 90` then it is a rectangular mask. If `angle < 90` then is a left-oriented parallelogram\-\ case parallelogram(angle: Double) /// Custom shape case custom(pathProvider: CustomMaskProvider) case none /** Wave direction for `wave` shape. */ public enum WaveDirection: String { /// For the wave facing up. case up /// For the wave facing down. case down } } public extension MaskType { init(string: String?) { guard let string = string else { self = .none return } let (name, params) = MaskType.extractNameAndParams(from: string) switch name { case "circle": self = .circle case "ellipse": self = .ellipse case "polygon": self = .polygon(sides: params[safe: 0]?.toInt() ?? 6) case "star": self = .star(points: params[safe: 0]?.toInt() ?? 5) case "triangle": self = .triangle case "wave": self = .wave(direction: WaveDirection(raw: params[safe: 0], defaultValue: .up), width: params[safe: 1]?.toDouble() ?? 40, offset: params[safe: 2]?.toDouble() ?? 0) case "parallelogram": self = .parallelogram(angle: params[safe: 0]?.toDouble() ?? 60) default: self = .none } } }
mit
8a8673ed346be408e28556067331ffca
28.447368
164
0.637623
3.851979
false
false
false
false
veue/ClockClassroom-swift
ClockClassroom/YYPRequestManager.swift
1
2006
// // YYPRequestManager.swift // ClockClassroom // // Created by YUYUNPENG on 2017/6/2. // Copyright © 2017年 YUYUNPENG. All rights reserved. // import UIKit import Foundation import Alamofire let BaseUrl = "https://api.51shizhong.com/api_v9/" let H5BaseUrl = "http://api.51shizhong.com" let BasePicUrl = "http://i.upload.file.dc.cric.com/" let JavaUrl = "https://api2.51shizhong.com" let KVersion = "api_v9" let KVersionH = "h5_v12" let CCAppVersion = "v2.6" private let YYPRequestShareInstance = YYPRequestManager() class YYPRequestManager: NSObject { class var sharedInstance : YYPRequestManager { return YYPRequestShareInstance } } extension YYPRequestManager { func getRequest(urlString : String, parameters : [String : Any], success : @escaping (_ response : [String : AnyObject])->(), failture : @escaping (_ error : Error)->()) { Alamofire.request(urlString, method: .get, parameters: [:], encoding: JSONEncoding.default).responseJSON { response in debugPrint(response) switch response.result { case .success: if let value = response.result.value { success(value as! [String : AnyObject]) } case .failure: failture(response.result.error!) } } } func postRequest(urlString : String, parameters : [String : Any], success : @escaping (_ response : [String : AnyObject])->(), failture : @escaping (_ error : Error)->()) { Alamofire.request(urlString, method: .post, parameters: [:], encoding: JSONEncoding.default).responseJSON { response in debugPrint(response) switch response.result { case .success: if let value = response.result.value { success(value as! [String : AnyObject]) } case .failure: failture(response.result.error!) } } } }
mit
1d9da495759962e03f21c56b21ceaad7
31.836066
176
0.603095
4.164241
false
false
false
false
kickstarter/ios-oss
Kickstarter-iOS/Features/Discovery/Views/Cells/ActivitySampleFollowCell.swift
1
2633
import KsApi import Library import Prelude import UIKit internal protocol ActivitySampleFollowCellDelegate: AnyObject { /// Call when should go to activity screen. func goToActivity() } internal final class ActivitySampleFollowCell: UITableViewCell, ValueCell { fileprivate let viewModel: ActivitySampleFollowCellViewModelType = ActivitySampleFollowCellViewModel() internal weak var delegate: ActivitySampleFollowCellDelegate? @IBOutlet fileprivate var activityStackView: UIStackView! @IBOutlet fileprivate var activityTitleLabel: UILabel! @IBOutlet fileprivate var cardView: UIView! @IBOutlet fileprivate var friendFollowLabel: UILabel! @IBOutlet fileprivate var friendImageAndFollowStackView: UIStackView! @IBOutlet fileprivate var friendImageView: CircleAvatarImageView! @IBOutlet fileprivate var seeAllActivityButton: UIButton! internal override func awakeFromNib() { super.awakeFromNib() self.seeAllActivityButton.addTarget( self, action: #selector(self.seeAllActivityButtonTapped), for: .touchUpInside ) } internal override func bindStyles() { super.bindStyles() _ = self |> activitySampleCellStyle |> \.backgroundColor .~ discoveryPageBackgroundColor() _ = self.activityStackView |> activitySampleStackViewStyle _ = self.activityTitleLabel |> activitySampleTitleLabelStyle _ = self.cardView |> dropShadowStyleMedium() _ = self.friendFollowLabel |> activitySampleFriendFollowLabelStyle _ = self.friendImageAndFollowStackView |> UIStackView.lens.spacing .~ Styles.grid(2) _ = self.friendImageView |> ignoresInvertColorsImageViewStyle _ = self.seeAllActivityButton |> activitySampleSeeAllActivityButtonStyle } internal override func bindViewModel() { super.bindViewModel() self.friendFollowLabel.rac.text = self.viewModel.outputs.friendFollowText self.viewModel.outputs.friendImageURL .observeForUI() .on(event: { [weak self] _ in self?.friendImageView.af.cancelImageRequest() self?.friendImageView.image = nil }) .skipNil() .observeValues { [weak self] url in self?.friendImageView.af.setImage(withURL: url) } self.viewModel.outputs.goToActivity .observeForUI() .observeValues { [weak self] _ in self?.delegate?.goToActivity() } } internal func configureWith(value: Activity) { self.viewModel.inputs.configureWith(activity: value) } @objc fileprivate func seeAllActivityButtonTapped() { self.viewModel.inputs.seeAllActivityTapped() } }
apache-2.0
93f5f8b29eb42054322b2eb6a8be1e58
27.619565
104
0.729966
4.894052
false
false
false
false
bmichotte/HSTracker
HSTracker/HSReplay/HSReplayPreferences.swift
1
7151
// // HSReplayPreferences.swift // HSTracker // // Created by Benjamin Michotte on 13/08/16. // Copyright © 2016 Benjamin Michotte. All rights reserved. // import Foundation import MASPreferences import CleanroomLogger class HSReplayPreferences: NSViewController { @IBOutlet weak var synchronizeMatches: NSButton! @IBOutlet weak var gameTypeSelector: NSView! @IBOutlet weak var uploadRankedGames: NSButton! @IBOutlet weak var uploadCasualGames: NSButton! @IBOutlet weak var uploadArenaGames: NSButton! @IBOutlet weak var uploadBrawlGames: NSButton! @IBOutlet weak var uploadFriendlyGames: NSButton! @IBOutlet weak var uploadAdventureGames: NSButton! @IBOutlet weak var uploadSpectatorGames: NSButton! @IBOutlet weak var hsReplayAccountStatus: NSTextField! @IBOutlet weak var claimAccountButton: NSButtonCell! @IBOutlet weak var claimAccountInfo: NSTextField! @IBOutlet weak var disconnectButton: NSButton! @IBOutlet weak var showPushNotification: NSButton! private var getAccountTimer: Timer? private var requests = 0 private let maxRequests = 10 override func viewDidLoad() { super.viewDidLoad() showPushNotification.state = Settings.showHSReplayPushNotification ? NSOnState : NSOffState synchronizeMatches.state = Settings.hsReplaySynchronizeMatches ? NSOnState : NSOffState // swiftlint:disable line_length uploadRankedGames.state = Settings.hsReplayUploadRankedMatches ? NSOnState : NSOffState uploadCasualGames.state = Settings.hsReplayUploadCasualMatches ? NSOnState : NSOffState uploadArenaGames.state = Settings.hsReplayUploadArenaMatches ? NSOnState : NSOffState uploadBrawlGames.state = Settings.hsReplayUploadBrawlMatches ? NSOnState : NSOffState uploadFriendlyGames.state = Settings.hsReplayUploadFriendlyMatches ? NSOnState : NSOffState uploadAdventureGames.state = Settings.hsReplayUploadAdventureMatches ? NSOnState : NSOffState uploadSpectatorGames.state = Settings.hsReplayUploadSpectatorMatches ? NSOnState : NSOffState // swiftlint:enable line_length updateUploadGameTypeView() updateStatus() } override func viewDidDisappear() { getAccountTimer?.invalidate() } @IBAction func checkboxClicked(_ sender: NSButton) { if sender == synchronizeMatches { Settings.hsReplaySynchronizeMatches = synchronizeMatches.state == NSOnState } else if sender == showPushNotification { Settings.showHSReplayPushNotification = showPushNotification.state == NSOnState } else if sender == uploadRankedGames { Settings.hsReplayUploadRankedMatches = uploadRankedGames.state == NSOnState } else if sender == uploadCasualGames { Settings.hsReplayUploadCasualMatches = uploadCasualGames.state == NSOnState } else if sender == uploadArenaGames { Settings.hsReplayUploadArenaMatches = uploadArenaGames.state == NSOnState } else if sender == uploadBrawlGames { Settings.hsReplayUploadBrawlMatches = uploadBrawlGames.state == NSOnState } else if sender == uploadFriendlyGames { Settings.hsReplayUploadFriendlyMatches = uploadFriendlyGames.state == NSOnState } else if sender == uploadAdventureGames { Settings.hsReplayUploadAdventureMatches = uploadAdventureGames.state == NSOnState } else if sender == uploadSpectatorGames { Settings.hsReplayUploadSpectatorMatches = uploadSpectatorGames.state == NSOnState } updateUploadGameTypeView() } fileprivate func updateUploadGameTypeView() { if synchronizeMatches.state == NSOffState { uploadRankedGames.isEnabled = false uploadCasualGames.isEnabled = false uploadArenaGames.isEnabled = false uploadBrawlGames.isEnabled = false uploadFriendlyGames.isEnabled = false uploadAdventureGames.isEnabled = false uploadSpectatorGames.isEnabled = false } else { uploadRankedGames.isEnabled = true uploadCasualGames.isEnabled = true uploadArenaGames.isEnabled = true uploadBrawlGames.isEnabled = true uploadFriendlyGames.isEnabled = true uploadAdventureGames.isEnabled = true uploadSpectatorGames.isEnabled = true } } @IBAction func disconnectAccount(_ sender: AnyObject) { Settings.hsReplayUsername = nil Settings.hsReplayId = nil updateStatus() } @IBAction func resetAccount(_ sender: Any) { Settings.hsReplayUsername = nil Settings.hsReplayId = nil Settings.hsReplayUploadToken = nil updateStatus() } @IBAction func claimAccount(_ sender: AnyObject) { claimAccountButton.isEnabled = false requests = 0 HSReplayAPI.getUploadToken { _ in HSReplayAPI.claimAccount() self.getAccountTimer?.invalidate() self.getAccountTimer = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(self.checkAccountInfo), userInfo: nil, repeats: true) } } @objc private func checkAccountInfo() { guard requests < maxRequests else { Log.warning?.message("max request for checking account info") return } HSReplayAPI.updateAccountStatus { (status) in self.requests += 1 if status { self.getAccountTimer?.invalidate() } self.updateStatus() } } private func updateStatus() { if Settings.hsReplayId != nil { var information = NSLocalizedString("Connected", comment: "") if let username = Settings.hsReplayUsername { information = String(format: NSLocalizedString("Connected as %@", comment: ""), username) } hsReplayAccountStatus.stringValue = information claimAccountInfo.isEnabled = false claimAccountButton.isEnabled = false disconnectButton.isEnabled = true } else { claimAccountInfo.isEnabled = true claimAccountButton.isEnabled = true disconnectButton.isEnabled = false hsReplayAccountStatus.stringValue = NSLocalizedString("Account status : Anonymous", comment: "") } } } // MARK: - MASPreferencesViewController extension HSReplayPreferences: MASPreferencesViewController { override var identifier: String? { get { return "hsreplay" } set { super.identifier = newValue } } var toolbarItemImage: NSImage? { return NSImage(named: "hsreplay_icon") } var toolbarItemLabel: String? { return "HSReplay" } }
mit
4377ab677f476da588fee1c77f4625d9
38.285714
101
0.654126
5.585938
false
false
false
false
anzfactory/QiitaCollection
QiitaCollection/SimpleListViewController.swift
1
4413
// // SimpleListViewController.swift // QiitaCollection // // Created by ANZ on 2015/02/21. // Copyright (c) 2015年 anz. All rights reserved. // import UIKit class SimpleListViewController: BaseViewController, UITableViewDataSource, UITableViewDelegate, SWTableViewCellDelegate { typealias ItemTapCallback = (SimpleListViewController, Int) -> Void typealias SwipeCellCallback = (SimpleListViewController, SlideTableViewCell, Int) -> Void // MARK: UI @IBOutlet weak var tableView: UITableView! @IBOutlet weak var navigationBar: UINavigationBar! @IBOutlet weak var navigationTitleItem: UINavigationItem! // MARK: プロパティ var items: [String] = [String]() var swipableCell: Bool = true var tapCallback: ItemTapCallback? = nil var swipeCellCallback: SwipeCellCallback? = nil var removeNavigationBar: Bool = false var cellGuide: GuideManager.GuideType = .None // MARK: ライフサイクル override func viewDidLoad() { super.viewDidLoad() self.setupForPresentedVC(self.navigationBar) let dummy: UIView = UIView(frame: CGRect.zeroRect) self.tableView.tableFooterView = dummy self.tableView.separatorColor = UIColor.borderTableView() self.tableView.dataSource = self self.tableView.delegate = self } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if self.removeNavigationBar { if let navBar = self.navigationBar { navBar.removeFromSuperview() self.tableView.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height) self.tableView.addConstraintFromTop(0.0) } } else { self.navigationTitleItem.title = self.title } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: Actions @IBAction func tapClose(sender: AnyObject) { self.dismissViewControllerAnimated(true, completion: { () -> Void in }) } // MARK: メソッド func refresh(items: [String]) { self.items = items self.tableView.reloadData() } func removeItem(index: Int) { if index >= self.items.count { return; } self.items.removeAtIndex(index) self.tableView.reloadData() } // MARK: UITableViewDataSource func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 44.0 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.items.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell: SlideTableViewCell = self.tableView.dequeueReusableCellWithIdentifier("CELL") as! SlideTableViewCell if !cell.isReused { cell.delegate = self } cell.textLabel?.text = self.items[indexPath.row] cell.tag = indexPath.row return cell } // MARK: UITableViewDelegate func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if let callback = self.tapCallback { if let cell = self.tableView.cellForRowAtIndexPath(indexPath) { self.transitionSenderPoint = cell.superview!.convertPoint(cell.center, toView: self.view) } callback(self, indexPath.row) } } func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { if indexPath.row == 0 && self.cellGuide != .None { cell.showGuide(self.cellGuide, inView: self.view) } } // MARK: SWTableViewCellDelegate func swipeableTableViewCell(cell: SWTableViewCell!, didTriggerRightUtilityButtonWithIndex index: Int) { self.transitionSenderPoint = cell.superview!.convertPoint(cell.center, toView: self.view) self.swipeCellCallback?(self, cell as! SlideTableViewCell, cell.tag) } func swipeableTableViewCell(cell: SWTableViewCell!, canSwipeToState state: SWCellState) -> Bool { return self.swipableCell } }
mit
1d77577cdb717fbda07bc0fe1732de44
32.945736
129
0.652889
4.925759
false
false
false
false
goldenplan/Pattern-on-Swift
StateMachine/StateMachine/ParkingState.swift
1
821
// // ParkingState.swift // StateMachine // // Created by Snake on 15.07.17. // Copyright © 2017 Stanislav Belsky. All rights reserved. // import UIKit class ParkingState: State { static let sharedInstance: ParkingState = { let instance = ParkingState() // setup code return instance }() var id = 0 var name = "Parking" var minFuelValue = 0 func next(for car: Car){ car.state = FillingState.sharedInstance } func availableState(for car: Car) -> [State]{ if car.fuelValue > 0{ return [ParkingState.sharedInstance, FillingState.sharedInstance, RidingState.sharedInstance] }else{ return [ParkingState.sharedInstance, FillingState.sharedInstance] } } }
mit
fafaab4fa4b555440ffbd98515f8b1fe
20.025641
105
0.596341
4.338624
false
false
false
false
kjantzer/FolioReaderKit
Source/FolioReaderHighlightList.swift
1
6982
// // FolioReaderHighlightList.swift // FolioReaderKit // // Created by Heberti Almeida on 01/09/15. // Copyright (c) 2015 Folio Reader. All rights reserved. // import UIKit class FolioReaderHighlightList: UITableViewController { var highlights: [Highlight]! override func viewDidLoad() { super.viewDidLoad() tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: reuseIdentifier) tableView.separatorInset = UIEdgeInsetsZero tableView.backgroundColor = isNight(readerConfig.nightModeMenuBackground, readerConfig.menuBackgroundColor) tableView.separatorColor = isNight(readerConfig.nightModeSeparatorColor, readerConfig.menuSeparatorColor) highlights = Highlight.allByBookId((kBookId as NSString).stringByDeletingPathExtension) } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return highlights.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier, forIndexPath: indexPath) cell.backgroundColor = UIColor.clearColor() let highlight = highlights[indexPath.row] // Format date let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = readerConfig.localizedHighlightsDateFormat let dateString = dateFormatter.stringFromDate(highlight.date) // Date var dateLabel: UILabel! if cell.contentView.viewWithTag(456) == nil { dateLabel = UILabel(frame: CGRect(x: 0, y: 0, width: view.frame.width-40, height: 16)) dateLabel.tag = 456 dateLabel.autoresizingMask = UIViewAutoresizing.FlexibleWidth dateLabel.font = UIFont(name: "Avenir-Medium", size: 12) cell.contentView.addSubview(dateLabel) } else { dateLabel = cell.contentView.viewWithTag(456) as! UILabel } dateLabel.text = dateString.uppercaseString dateLabel.textColor = isNight(UIColor(white: 5, alpha: 0.3), UIColor.lightGrayColor()) dateLabel.frame = CGRect(x: 20, y: 20, width: view.frame.width-40, height: dateLabel.frame.height) // Text let cleanString = highlight.content.stripHtml().truncate(250, trailing: "...").stripLineBreaks() let text = NSMutableAttributedString(string: cleanString) let range = NSRange(location: 0, length: text.length) let paragraph = NSMutableParagraphStyle() paragraph.lineSpacing = 3 let textColor = isNight(readerConfig.menuTextColor, UIColor.blackColor()) text.addAttribute(NSParagraphStyleAttributeName, value: paragraph, range: range) text.addAttribute(NSFontAttributeName, value: UIFont(name: "Avenir-Light", size: 16)!, range: range) text.addAttribute(NSForegroundColorAttributeName, value: textColor, range: range) if highlight.type == HighlightStyle.Underline.rawValue { text.addAttribute(NSBackgroundColorAttributeName, value: UIColor.clearColor(), range: range) text.addAttribute(NSUnderlineColorAttributeName, value: HighlightStyle.colorForStyle(highlight.type, nightMode: FolioReader.nightMode), range: range) text.addAttribute(NSUnderlineStyleAttributeName, value: NSNumber(integer: NSUnderlineStyle.StyleSingle.rawValue), range: range) } else { text.addAttribute(NSBackgroundColorAttributeName, value: HighlightStyle.colorForStyle(highlight.type, nightMode: FolioReader.nightMode), range: range) } // Text var highlightLabel: UILabel! if cell.contentView.viewWithTag(123) == nil { highlightLabel = UILabel(frame: CGRect(x: 0, y: 0, width: view.frame.width-40, height: 0)) highlightLabel.tag = 123 highlightLabel.autoresizingMask = UIViewAutoresizing.FlexibleWidth highlightLabel.numberOfLines = 0 highlightLabel.textColor = UIColor.blackColor() cell.contentView.addSubview(highlightLabel) } else { highlightLabel = cell.contentView.viewWithTag(123) as! UILabel } highlightLabel.attributedText = text highlightLabel.sizeToFit() highlightLabel.frame = CGRect(x: 20, y: 46, width: view.frame.width-40, height: highlightLabel.frame.height) cell.layoutMargins = UIEdgeInsetsZero cell.preservesSuperviewLayoutMargins = false return cell } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { let highlight = highlights[indexPath.row] let cleanString = highlight.content.stripHtml().truncate(250, trailing: "...").stripLineBreaks() let text = NSMutableAttributedString(string: cleanString) let range = NSRange(location: 0, length: text.length) let paragraph = NSMutableParagraphStyle() paragraph.lineSpacing = 3 text.addAttribute(NSParagraphStyleAttributeName, value: paragraph, range: range) text.addAttribute(NSFontAttributeName, value: UIFont(name: "Avenir-Light", size: 16)!, range: range) let s = text.boundingRectWithSize(CGSize(width: view.frame.width-40, height: CGFloat.max), options: [NSStringDrawingOptions.UsesLineFragmentOrigin, NSStringDrawingOptions.UsesFontLeading], context: nil) return s.size.height + 66 } // MARK: - Table view delegate override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let highlight = highlights[indexPath.row] FolioReader.sharedInstance.readerCenter.changePageWith(page: highlight.page, andFragment: highlight.highlightId) dismiss() } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { let highlight = highlights[indexPath.row] if highlight.page == currentPageNumber { Highlight.removeFromHTMLById(highlight.highlightId) // Remove from HTML } highlight.remove() // Remove from Database highlights.removeAtIndex(indexPath.row) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } } // MARK: - Handle rotation transition override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { tableView.reloadData() } }
bsd-3-clause
e85d3dcf971d1f5a3bfe6e3a5fedacb5
45.238411
162
0.687052
5.532488
false
false
false
false
milseman/swift
stdlib/public/SDK/Foundation/NSArray.swift
25
5064
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_exported import Foundation // Clang module //===----------------------------------------------------------------------===// // Arrays //===----------------------------------------------------------------------===// extension NSArray : ExpressibleByArrayLiteral { /// Create an instance initialized with `elements`. public required convenience init(arrayLiteral elements: Any...) { // Let bridging take care of it. self.init(array: elements) } } extension Array : _ObjectiveCBridgeable { /// Private initializer used for bridging. /// /// The provided `NSArray` will be copied to ensure that the copy can /// not be mutated by other code. internal init(_cocoaArray: NSArray) { _sanityCheck(_isBridgedVerbatimToObjectiveC(Element.self), "Array can be backed by NSArray only when the element type can be bridged verbatim to Objective-C") // FIXME: We would like to call CFArrayCreateCopy() to avoid doing an // objc_msgSend() for instances of CoreFoundation types. We can't do that // today because CFArrayCreateCopy() copies array contents unconditionally, // resulting in O(n) copies even for immutable arrays. // // <rdar://problem/19773555> CFArrayCreateCopy() is >10x slower than // -[NSArray copyWithZone:] // // The bug is fixed in: OS X 10.11.0, iOS 9.0, all versions of tvOS // and watchOS. self = Array( _immutableCocoaArray: unsafeBitCast(_cocoaArray.copy() as AnyObject, to: _NSArrayCore.self)) } @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> NSArray { return unsafeBitCast(self._bridgeToObjectiveCImpl(), to: NSArray.self) } public static func _forceBridgeFromObjectiveC( _ source: NSArray, result: inout Array? ) { // If we have the appropriate native storage already, just adopt it. if let native = Array._bridgeFromObjectiveCAdoptingNativeStorageOf(source) { result = native return } if _fastPath(_isBridgedVerbatimToObjectiveC(Element.self)) { // Forced down-cast (possible deferred type-checking) result = Array(_cocoaArray: source) return } result = _arrayForceCast([AnyObject](_cocoaArray: source)) } public static func _conditionallyBridgeFromObjectiveC( _ source: NSArray, result: inout Array? ) -> Bool { // Construct the result array by conditionally bridging each element. let anyObjectArr = [AnyObject](_cocoaArray: source) result = _arrayConditionalCast(anyObjectArr) return result != nil } public static func _unconditionallyBridgeFromObjectiveC( _ source: NSArray? ) -> Array { // `nil` has historically been used as a stand-in for an empty // array; map it to an empty array instead of failing. if _slowPath(source == nil) { return Array() } // If we have the appropriate native storage already, just adopt it. if let native = Array._bridgeFromObjectiveCAdoptingNativeStorageOf(source!) { return native } if _fastPath(_isBridgedVerbatimToObjectiveC(Element.self)) { // Forced down-cast (possible deferred type-checking) return Array(_cocoaArray: source!) } return _arrayForceCast([AnyObject](_cocoaArray: source!)) } } extension NSArray : Sequence { /// Return an *iterator* over the elements of this *sequence*. /// /// - Complexity: O(1). final public func makeIterator() -> NSFastEnumerationIterator { return NSFastEnumerationIterator(self) } } /* TODO: API review extension NSArray : Swift.Collection { final public var startIndex: Int { return 0 } final public var endIndex: Int { return count } } */ extension NSArray { // Overlay: - (instancetype)initWithObjects:(id)firstObj, ... public convenience init(objects elements: Any...) { self.init(array: elements) } } extension NSArray { /// Initializes a newly allocated array by placing in it the objects /// contained in a given array. /// /// - Returns: An array initialized to contain the objects in /// `anArray``. The returned object might be different than the /// original receiver. /// /// Discussion: After an immutable array has been initialized in /// this way, it cannot be modified. @nonobjc public convenience init(array anArray: NSArray) { self.init(array: anArray as Array) } } extension NSArray : CustomReflectable { public var customMirror: Mirror { return Mirror(reflecting: self as [AnyObject]) } } extension Array: CVarArg {}
apache-2.0
25e275973db63bffa46cb516333d4cc8
30.849057
105
0.648499
4.75493
false
false
false
false
rivetlogic/liferay-mobile-directory-ios
Liferay-Screens/Themes/Flat7/Auth/ForgotPasswordScreenlet/ForgotPasswordView_flat7.swift
1
2062
/** * Copyright (c) 2000-present Liferay, Inc. All rights reserved. * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. */ import UIKit public class ForgotPasswordView_flat7: ForgotPasswordView_default { @IBOutlet private var titleLabel: UILabel? @IBOutlet private var subtitleLabel: UILabel? @IBOutlet private var userNamePlaceholder: UILabel? //MARK: ForgotPasswordView override internal func onCreated() { super.onCreated() setFlat7ButtonBackground(requestPasswordButton) BaseScreenlet.setHUDCustomColor(Flat7ThemeBasicGreen) } override internal func onSetTranslations() { let bundle = NSBundle(forClass: self.dynamicType) titleLabel!.text = LocalizedString("flat7", "forgotpassword-title", self) subtitleLabel!.text = LocalizedString("flat7", "forgotpassword-subtitle", self) userNamePlaceholder!.text = LocalizedString("flat7", "forgotpassword-email", self) requestPasswordButton!.replaceAttributedTitle( LocalizedString("flat7", "forgotpassword-request", self), forState: .Normal) userNameField!.placeholder = ""; } //MARK: ForgotPasswordView override public var userName: String? { didSet { userNamePlaceholder!.changeVisibility(visible: userName != "") } } //MARK: UITextFieldDelegate internal func textField(textField: UITextField!, shouldChangeCharactersInRange range: NSRange, replacementString string: String!) -> Bool { let newText = (textField.text as NSString).stringByReplacingCharactersInRange(range, withString:string) userNamePlaceholder!.changeVisibility(visible: newText != "") return true } }
gpl-3.0
35e9f96426b6a55f8c63c128205b3708
27.246575
86
0.763337
4.278008
false
false
false
false
victorchee/DynamicAnimator
DynamicAnimator/DynamicAnimator/AttachmentViewController.swift
1
1617
// // AttachmentsViewController.swift // DynamicAnimator // // Created by qihaijun on 12/23/15. // Copyright © 2015 VictorChee. All rights reserved. // import UIKit class AttachmentViewController: UIViewController { @IBOutlet weak var attachmentView: UIView! @IBOutlet weak var itemView: UIView! @IBOutlet weak var itemAttachmentView: UIView! var animator: UIDynamicAnimator! var attachmentBehavior: UIAttachmentBehavior! override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) animator = UIDynamicAnimator(referenceView: view) let collisionBehavior = UICollisionBehavior(items: [itemView]) collisionBehavior.translatesReferenceBoundsIntoBoundary = true let anchor = CGPoint(x: itemView.center.x, y: itemView.center.y - 100) let offset = UIOffset(horizontal: -22, vertical: -22) attachmentBehavior = UIAttachmentBehavior(item: itemView, offsetFromCenter: offset, attachedToAnchor: anchor) // attachmentBehavior.damping = 0.5 // attachmentBehavior.frequency = 0.5 // attachmentBehavior.frictionTorque = 0.5 attachmentView.center = attachmentBehavior.anchorPoint itemAttachmentView.center = CGPoint(x: 22, y: 22) animator.addBehavior(collisionBehavior) animator.addBehavior(attachmentBehavior) } @IBAction func pan(_ sender: UIPanGestureRecognizer) { attachmentBehavior.anchorPoint = sender.location(in: view) attachmentView.center = attachmentBehavior.anchorPoint } }
mit
b387623dc8e5e800b825d7a42b729f9c
34.911111
117
0.697401
5.146497
false
false
false
false
daviwiki/Gourmet_Swift
Gourmet/Gourmet/Support/Mappers/MapBalanceToBalanceVM.swift
1
952
// // MapBalanceToBalanceVM.swift // Gourmet // // Created by David Martinez on 14/12/2016. // Copyright © 2016 Atenea. All rights reserved. // import UIKit import GourmetModel class MapBalanceToBalanceVM: NSObject { func map(source: Balance) -> BalanceVM? { let balanceVM = BalanceVM() balanceVM.quantity = source.quantity balanceVM.requestDate = source.requestDate balanceVM.lastPurchases = [] for purchase in source.lastPurchases { let purchaseVM = PurchaseVM() purchaseVM.commerce = purchase.commerce purchaseVM.date = purchase.date purchaseVM.location = purchase.location purchaseVM.quantity = purchase.quantity purchaseVM.type = PurchaseVM.PurchaseType(rawValue: purchase.type.rawValue) ?? .spend balanceVM.lastPurchases.append(purchaseVM) } return balanceVM } }
mit
975568275d69ea279b7fab7d503828a8
27.818182
97
0.640379
4.362385
false
false
false
false
rahuliyer95/iShowcase
Source/iShowcase.swift
1
19186
// // iShowcase.swift // iShowcase // // Created by Rahul Iyer on 12/10/15. // Copyright © 2015 rahuliyer. All rights reserved. // import UIKit import Foundation @objc public protocol iShowcaseDelegate: NSObjectProtocol { /** Called when the showcase is displayed - showcase: The instance of the showcase displayed */ @objc optional func iShowcaseShown(_ showcase: iShowcase) /** Called when the showcase is removed from the view - showcase: The instance of the showcase removed */ @objc optional func iShowcaseDismissed(_ showcase: iShowcase) } @objc open class iShowcase: UIView { // MARK: Properties /** Type of the highlight for the showcase - CIRCLE: Creates a circular highlight around the view - RECTANGLE: Creates a rectangular highligh around the view */ @objc public enum TYPE: Int { case circle = 0 case rectangle = 1 } fileprivate enum REGION: Int { case top = 0 case left = 1 case bottom = 2 case right = 3 static func regionFromInt(_ region: Int) -> REGION { switch region { case 0: return .top case 1: return .left case 2: return .bottom case 3: return .right default: return .top } } } fileprivate var containerView: UIView! fileprivate var showcaseRect: CGRect! fileprivate var region: REGION! fileprivate var targetView: UIView? fileprivate var showcaseImageView: UIImageView! /// Label to show the title of the showcase open var titleLabel: UILabel! /// Label to show the description of the showcase open var detailsLabel: UILabel! /// Color of the background for the showcase. Default is black open var coverColor: UIColor! /// Alpha of the background of the showcase. Default is 0.75 open var coverAlpha: CGFloat! /// Color of the showcase highlight. Default is #1397C5 open var highlightColor: UIColor! /// Type of the showcase to be created. Default is Rectangle open var type: TYPE! /// Radius of the circle with iShowcase type Circle. Default radius is 25 open var radius: Float! /// Single Shot ID for iShowcase open var singleShotId: Int64! /// Hide on tapped outside the showcase spot open var hideOnTouchOutside = true /// Delegate for handling iShowcase callbacks open var delegate: iShowcaseDelegate? // MARK: Initialize /** Initialize an instance of iShowcae */ public init() { super.init(frame: CGRect( x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)) setup() } /** This method is not supported */ required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: Public /** Position the views on the screen for display */ open override func layoutSubviews() { super.layoutSubviews() if showcaseImageView != nil { recycleViews() } if let view = targetView { showcaseRect = view.convert(view.bounds, to: containerView) } draw() addSubview(showcaseImageView) addSubview(titleLabel) addSubview(detailsLabel) addGestureRecognizer(getGestureRecgonizer()) } /** Setup the showcase for a view - parameter view: The view to be highlighted */ open func setupShowcaseForView(_ view: UIView) { targetView = view setupShowcaseForLocation(view.convert(view.bounds, to: containerView)) } /** Setup showcase for the item at 1st position (0th index) of the table - parameter tableView: Table whose item is to be highlighted */ open func setupShowcaseForTableView(_ tableView: UITableView) { setupShowcaseForTableView(tableView, withIndexOfItem: 0, andSectionOfItem: 0) } /** Setup showcase for the item at the given indexpath - parameter tableView: Table whose item is to be highlighted - parameter indexPath: IndexPath of the item to be highlighted */ open func setupShowcaseForTableView(_ tableView: UITableView, withIndexPath indexPath: IndexPath) { setupShowcaseForTableView(tableView, withIndexOfItem: (indexPath as NSIndexPath).row, andSectionOfItem: (indexPath as NSIndexPath).section) } /** Setup showcase for the item at the given index in the given section of the table - parameter tableView: Table whose item is to be highlighted - parameter row: Index of the item to be highlighted - parameter section: Section of the item to be highlighted */ open func setupShowcaseForTableView(_ tableView: UITableView, withIndexOfItem row: Int, andSectionOfItem section: Int) { let indexPath = IndexPath(row: row, section: section) targetView = tableView.cellForRow(at: indexPath) setupShowcaseForLocation(tableView.convert( tableView.rectForRow(at: indexPath), to: containerView)) } /** Setup showcase for the Bar Button in the Navigation Bar - parameter barButtonItem: Bar button to be highlighted */ open func setupShowcaseForBarButtonItem(_ barButtonItem: UIBarButtonItem) { setupShowcaseForView(barButtonItem.value(forKey: "view") as! UIView) } /** Setup showcase to highlight a particular location on the screen - parameter location: Location to be highlighted */ open func setupShowcaseForLocation(_ location: CGRect) { showcaseRect = location } /** Display the iShowcase */ open func show() { if singleShotId != -1 && UserDefaults.standard.bool(forKey: String( format: "iShowcase-%ld", singleShotId)) { return } self.alpha = 1 for view in containerView.subviews { view.isUserInteractionEnabled = false } UIView.transition( with: containerView, duration: 0.5, options: UIViewAnimationOptions.transitionCrossDissolve, animations: { () -> Void in self.containerView.addSubview(self) }) { (_) -> Void in if let delegate = self.delegate { if delegate.responds(to: #selector(iShowcaseDelegate.iShowcaseShown)) { delegate.iShowcaseShown!(self) } } } } // MARK: Private fileprivate func setup() { self.backgroundColor = UIColor.clear containerView = UIApplication.shared.delegate!.window! coverColor = UIColor.black highlightColor = UIColor.colorFromHexString("#1397C5") coverAlpha = 0.75 type = .rectangle radius = 25 singleShotId = -1 // Setup title label defaults titleLabel = UILabel() titleLabel.font = UIFont.boldSystemFont(ofSize: 24) titleLabel.textColor = UIColor.white titleLabel.textAlignment = .center titleLabel.lineBreakMode = NSLineBreakMode.byWordWrapping titleLabel.numberOfLines = 0 // Setup details label defaults detailsLabel = UILabel() detailsLabel.font = UIFont.systemFont(ofSize: 16) detailsLabel.textColor = UIColor.white detailsLabel.textAlignment = .center detailsLabel.lineBreakMode = NSLineBreakMode.byWordWrapping detailsLabel.numberOfLines = 0 } fileprivate func draw() { setupBackground() calculateRegion() setupText() } fileprivate func setupBackground() { UIGraphicsBeginImageContextWithOptions(UIScreen.main.bounds.size, false, UIScreen.main.scale) var context: CGContext? = UIGraphicsGetCurrentContext() context?.setFillColor(coverColor.cgColor) context?.fill(containerView.bounds) if type == .rectangle { if let showcaseRect = showcaseRect { // Outer highlight let highlightRect = CGRect( x: showcaseRect.origin.x - 15, y: showcaseRect.origin.y - 15, width: showcaseRect.size.width + 30, height: showcaseRect.size.height + 30) context?.setShadow(offset: CGSize.zero, blur: 30, color: highlightColor.cgColor) context?.setFillColor(coverColor.cgColor) context?.setStrokeColor(highlightColor.cgColor) context?.addPath(UIBezierPath(rect: highlightRect).cgPath) context?.drawPath(using: .fillStroke) // Inner highlight context?.setLineWidth(3) context?.addPath(UIBezierPath(rect: showcaseRect).cgPath) context?.drawPath(using: .fillStroke) let showcase = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() // Clear region UIGraphicsBeginImageContext((showcase?.size)!) showcase?.draw(at: CGPoint.zero) context = UIGraphicsGetCurrentContext() context?.clear(showcaseRect) } } else { if let showcaseRect = showcaseRect { let center = CGPoint( x: showcaseRect.origin.x + showcaseRect.size.width / 2.0, y: showcaseRect.origin.y + showcaseRect.size.height / 2.0) // Draw highlight context?.setLineWidth(2.54) context?.setShadow(offset: CGSize.zero, blur: 30, color: highlightColor.cgColor) context?.setFillColor(coverColor.cgColor) context?.setStrokeColor(highlightColor.cgColor) context?.addArc(center: center, radius: CGFloat(radius * 2), startAngle: 0, endAngle: CGFloat(2 * Double.pi), clockwise: false) context?.drawPath(using: .fillStroke) context?.addArc(center: center, radius: CGFloat(radius), startAngle: 0, endAngle: CGFloat(2 * Double.pi), clockwise: false) context?.drawPath(using: .fillStroke) // Clear circle context?.setFillColor(UIColor.clear.cgColor) context?.setBlendMode(.clear) context?.addArc(center: center, radius: CGFloat(radius - 0.54), startAngle: 0, endAngle: CGFloat(2 * Double.pi), clockwise: false) context?.drawPath(using: .fill) context?.setBlendMode(.normal) } } showcaseImageView = UIImageView(image: UIGraphicsGetImageFromCurrentImageContext()) showcaseImageView.alpha = coverAlpha UIGraphicsEndImageContext() } fileprivate func calculateRegion() { let left = showcaseRect.origin.x, right = showcaseRect.origin.x + showcaseRect.size.width, top = showcaseRect.origin.y, bottom = showcaseRect.origin.y + showcaseRect.size.height let areas = [ top * UIScreen.main.bounds.size.width, // Top region left * UIScreen.main.bounds.size.height, // Left region (UIScreen.main.bounds.size.height - bottom) * UIScreen.main.bounds.size.width, // Bottom region (UIScreen.main.bounds.size.width - right) - UIScreen.main.bounds.size.height // Right region ] var largestIndex = 0 for i in 0..<areas.count { if areas[i] > areas[largestIndex] { largestIndex = i } } region = REGION.regionFromInt(largestIndex) } fileprivate func setupText() { titleLabel.frame = containerView.frame detailsLabel.frame = containerView.frame titleLabel.sizeToFit() detailsLabel.sizeToFit() let textPosition = getBestPositionOfTitle( withTitleSize: titleLabel.bounds.size, withDetailsSize: detailsLabel.bounds.size) if region == .bottom { detailsLabel.frame = textPosition.0 titleLabel.frame = textPosition.1 } else { titleLabel.frame = textPosition.0 detailsLabel.frame = textPosition.1 } titleLabel.frame = CGRect( x: containerView.bounds.size.width / 2.0 - titleLabel.frame.size.width / 2.0, y: titleLabel.frame.origin.y, width: titleLabel.frame.size.width - (region == .left || region == .right ? showcaseRect.size.width : 0), height: titleLabel.frame.size.height) titleLabel.sizeToFit() detailsLabel.frame = CGRect( x: containerView.bounds.size.width / 2.0 - detailsLabel.frame.size.width / 2.0, y: detailsLabel.frame.origin.y + titleLabel.frame.size.height / 2, width: detailsLabel.frame.size.width - (region == .left || region == .right ? showcaseRect.size.width : 0), height: detailsLabel.frame.size.height) detailsLabel.sizeToFit() } fileprivate func getBestPositionOfTitle(withTitleSize titleSize: CGSize, withDetailsSize detailsSize: CGSize) -> (CGRect, CGRect) { var rect0 = CGRect(), rect1 = CGRect() if let region = self.region { switch region { case .top: rect0 = CGRect( x: containerView.bounds.size.width / 2.0 - titleSize.width / 2.0, y: titleSize.height + 20, width: titleSize.width, height: titleSize.height) rect1 = CGRect( x: containerView.bounds.size.width / 2.0 - detailsSize.width / 2.0, y: rect0.origin.y + rect0.size.height + detailsSize.height / 2.0, width: detailsSize.width, height: detailsSize.height) break case .left: rect0 = CGRect( x: 0, y: containerView.bounds.size.height / 2.0, width: titleSize.width, height: titleSize.height) rect1 = CGRect( x: 0, y: rect0.origin.y + rect0.size.height + detailsSize.height / 2.0, width: detailsSize.width, height: detailsSize.height) break case .bottom: rect0 = CGRect( x: containerView.bounds.size.width / 2.0 - detailsSize.width / 2.0, y: containerView.bounds.size.height - detailsSize.height * 2.0, width: detailsSize.width, height: detailsSize.height) rect1 = CGRect( x: containerView.bounds.size.width / 2.0 - titleSize.width / 2.0, y: rect0.origin.y - rect0.size.height - titleSize.height / 2.0, width: titleSize.width, height: titleSize.height) break case .right: rect0 = CGRect( x: containerView.bounds.size.width - titleSize.width, y: containerView.bounds.size.height / 2.0, width: titleSize.width, height: titleSize.height) rect1 = CGRect( x: containerView.bounds.size.width - detailsSize.width, y: rect0.origin.y + rect0.size.height + detailsSize.height / 2.0, width: detailsSize.width, height: detailsSize.height) break } } return (rect0, rect1) } fileprivate func getGestureRecgonizer() -> UIGestureRecognizer { let singleTap = UITapGestureRecognizer(target: self, action: #selector(showcaseTapped)) singleTap.numberOfTapsRequired = 1 singleTap.numberOfTouchesRequired = 1 return singleTap } @objc internal func showcaseTapped(_ gestureRecognizer: UIGestureRecognizer) { if !hideOnTouchOutside { // only dismiss if touch is inside spot area let point = gestureRecognizer.location(in: self) if !showcaseRect.contains(point) { return } } UIView.animate( withDuration: 0.5, animations: { () -> Void in self.alpha = 0 }, completion: { (_) -> Void in self.onAnimationComplete() }) } fileprivate func onAnimationComplete() { if singleShotId != -1 { UserDefaults.standard.set(true, forKey: String( format: "iShowcase-%ld", singleShotId)) singleShotId = -1 } for view in self.containerView.subviews { view.isUserInteractionEnabled = true } recycleViews() self.removeFromSuperview() if let delegate = delegate { if delegate.responds(to: #selector(iShowcaseDelegate.iShowcaseDismissed)) { delegate.iShowcaseDismissed!(self) } } } fileprivate func recycleViews() { showcaseImageView.removeFromSuperview() titleLabel.removeFromSuperview() detailsLabel.removeFromSuperview() } } // MARK: UIColor extension public extension UIColor { /** Parse a hex string for its `ARGB` components and return a `UIColor` instance - parameter colorString: A string representing the color hex to be parsed - returns: A UIColor instance containing the parsed color */ public static func colorFromHexString(_ colorString: String) -> UIColor { let hex = colorString.trimmingCharacters( in: CharacterSet.alphanumerics.inverted) var int = UInt32() Scanner(string: hex).scanHexInt32(&int) let a, r, g, b: UInt32 switch hex.characters.count { case 3: // RGB (12-bit) (a, r, g, b) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17) case 6: // RGB (24-bit) (a, r, g, b) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF) case 8: // ARGB (32-bit) (a, r, g, b) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF) default: return UIColor.clear } return UIColor( red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: CGFloat(a) / 255) } }
mit
a153798cb22af4cbb686963ba8bdbb15
35.06203
146
0.574772
4.983117
false
false
false
false
maxim-pervushin/simplenotes
SimpleNotes/SimpleNotes/Src/Screens/Note List/NoteCell.swift
1
464
// // Created by Maxim Pervushin on 11/08/15. // Copyright (c) 2015 Maxim Pervushin. All rights reserved. // import UIKit class NoteCell: UITableViewCell { var note: Note? { didSet { if let note = note { textLabel?.text = note.text detailTextLabel?.text = note.identifier } else { textLabel?.text = "" detailTextLabel?.text = "" } } } }
mit
bc9dfcf5636a4b85f81f87aa179693cc
21.095238
59
0.506466
4.64
false
false
false
false
lieven/fietsknelpunten-ios
App/Report/ReportTagsViewController.swift
1
2403
// // ReportTagsViewController.swift // Fietsknelpunten // // Created by Lieven Dekeyser on 13/11/16. // Copyright © 2016 Fietsknelpunten. All rights reserved. // import UIKit import FietsknelpuntenAPI class ReportTagsViewController: UITableViewController { let tagGroups: [TagGroup] var report: Report init(report: Report, tagGroups: [TagGroup]) { self.report = report self.tagGroups = tagGroups super.init(style: .grouped) self.title = NSLocalizedString("REPORT_SELECT_TAGS_TITLE", value: "Select Type", comment: "Title for the tags/type view. Should be short.") self.hidesBottomBarWhenPushed = true } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func numberOfSections(in tableView: UITableView) -> Int { return self.tagGroups.count } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.tagGroups[safe: section]?.tags.count ?? 0 } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return self.tagGroups[safe: section]?.name } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let reuseIdentifier = "TagsReuseIdentifier" let cell: UITableViewCell if let dequeuedCell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier) { cell = dequeuedCell } else { cell = UITableViewCell(style: .subtitle, reuseIdentifier: reuseIdentifier) } if let tag = self.tagGroups[safe: indexPath.section]?.tags[safe: indexPath.row] { cell.textLabel?.text = tag.name cell.detailTextLabel?.text = tag.info cell.accessoryType = self.report.tags.contains(tag) ? .checkmark : .none } else { cell.textLabel?.text = "" cell.detailTextLabel?.text = "" cell.accessoryType = .none } return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if let tag = tagGroups[safe: indexPath.section]?.tags[safe: indexPath.row] { if let index = self.report.tags.firstIndex(of: tag) { self.report.tags.remove(at: index) } else { self.report.tags.append(tag) } tableView.reloadRows(at: [indexPath], with: .automatic) } else { tableView.deselectRow(at: indexPath, animated: true) } } }
mit
53b116297f7b6000b49ad5e8f88ff42d
22.782178
141
0.710241
3.633888
false
false
false
false
slimane-swift/WS
Sources/SHA1.swift
1
6984
// Originally based on CryptoSwift by Marcin Krzyżanowski <[email protected]> // Copyright (C) 2014 Marcin Krzyżanowski <[email protected]> // This software is provided 'as-is', without any express or implied warranty. // // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: // // - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. // - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. // - This notice may not be removed or altered from any source or binary distribution. func rotateLeft(_ value: UInt8, count: UInt8) -> UInt8 { return ((value << count) & 0xFF) | (value >> (8 - count)) } func rotateLeft(_ value: UInt16, count: UInt16) -> UInt16 { return ((value << count) & 0xFFFF) | (value >> (16 - count)) } func rotateLeft(_ value: UInt32, count: UInt32) -> UInt32 { return ((value << count) & 0xFFFFFFFF) | (value >> (32 - count)) } func rotateLeft(_ value: UInt64, count: UInt64) -> UInt64 { return (value << count) | (value >> (64 - count)) } func rotateRight(_ value: UInt16, count: UInt16) -> UInt16 { return (value >> count) | (value << (16 - count)) } func rotateRight(_ value: UInt32, count: UInt32) -> UInt32 { return (value >> count) | (value << (32 - count)) } func rotateRight(_ value: UInt64, count: UInt64) -> UInt64 { return ((value >> count) | (value << (64 - count))) } func reverseBytes(_ value: UInt32) -> UInt32 { return ((value & 0x000000FF) << 24) | ((value & 0x0000FF00) << 8) | ((value & 0x00FF0000) >> 8) | ((value & 0xFF000000) >> 24); } func arrayOfBytes<T>(_ value: T, length: Int? = nil) -> [UInt8] { let totalBytes = length ?? sizeof(T.self) let valuePointer = UnsafeMutablePointer<T>.allocate(capacity: 1) valuePointer.pointee = value let bytesPointer = unsafeBitCast(valuePointer, to: UnsafeMutablePointer<UInt8>.self) var bytes = [UInt8](repeating: 0, count: totalBytes) for j in 0..<min(sizeof(T.self),totalBytes) { bytes[totalBytes - 1 - j] = (bytesPointer + j).pointee } valuePointer.deinitialize(count: 1) valuePointer.deallocate(capacity: 1) return bytes } func toUInt32Array(_ slice: ArraySlice<UInt8>) -> Array<UInt32> { var result = Array<UInt32>() result.reserveCapacity(16) for idx in stride(from: slice.startIndex, to: slice.endIndex, by: sizeof(UInt32.self)) { let val1:UInt32 = (UInt32(slice[idx.advanced(by: 3)]) << 24) let val2:UInt32 = (UInt32(slice[idx.advanced(by: 2)]) << 16) let val3:UInt32 = (UInt32(slice[idx.advanced(by: 1)]) << 8) let val4:UInt32 = UInt32(slice[idx]) let val:UInt32 = val1 | val2 | val3 | val4 result.append(val) } return result } let size: Int = 20 // 160 / 8 let h: [UInt32] = [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0] func sha1(_ data: Data) -> Data { let len = 64 let originalMessage = data.bytes var tmpMessage = data.bytes // Step 1. Append Padding Bits tmpMessage.append(0x80) // append one bit (UInt8 with one bit) to message // append "0" bit until message length in bits ≡ 448 (mod 512) var msgLength = tmpMessage.count var counter = 0 while msgLength % len != (len - 8) { counter += 1 msgLength += 1 } tmpMessage += Array<UInt8>(repeating: 0, count: counter) // hash values var hh = h // append message length, in a 64-bit big-endian integer. So now the message length is a multiple of 512 bits. tmpMessage += arrayOfBytes(originalMessage.count * 8, length: 64 / 8) // Process the message in successive 512-bit chunks: let chunkSizeBytes = 512 / 8 // 64 for chunk in BytesSequence(chunkSize: chunkSizeBytes, data: tmpMessage) { // break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15, big-endian // Extend the sixteen 32-bit words into eighty 32-bit words: var M:[UInt32] = [UInt32](repeating: 0, count: 80) for x in 0..<M.count { switch (x) { case 0...15: let start = chunk.startIndex + (x * sizeofValue(M[x])) let end = start + sizeofValue(M[x]) let le = toUInt32Array(chunk[start..<end])[0] M[x] = le.bigEndian break default: M[x] = rotateLeft(M[x-3] ^ M[x-8] ^ M[x-14] ^ M[x-16], count: 1) break } } var A = hh[0] var B = hh[1] var C = hh[2] var D = hh[3] var E = hh[4] // Main loop for j in 0...79 { var f: UInt32 = 0; var k: UInt32 = 0 switch (j) { case 0...19: f = (B & C) | ((~B) & D) k = 0x5A827999 break case 20...39: f = B ^ C ^ D k = 0x6ED9EBA1 break case 40...59: f = (B & C) | (B & D) | (C & D) k = 0x8F1BBCDC break case 60...79: f = B ^ C ^ D k = 0xCA62C1D6 break default: break } let temp = (rotateLeft(A, count:5) &+ f &+ E &+ M[j] &+ k) & 0xffffffff E = D D = C C = rotateLeft(B, count: 30) B = A A = temp } hh[0] = (hh[0] &+ A) & 0xffffffff hh[1] = (hh[1] &+ B) & 0xffffffff hh[2] = (hh[2] &+ C) & 0xffffffff hh[3] = (hh[3] &+ D) & 0xffffffff hh[4] = (hh[4] &+ E) & 0xffffffff } // Produce the final hash value (big-endian) as a 160 bit number: var result = [UInt8]() result.reserveCapacity(hh.count / 4) hh.forEach { let item = $0.bigEndian result += [UInt8(item & 0xff), UInt8((item >> 8) & 0xff), UInt8((item >> 16) & 0xff), UInt8((item >> 24) & 0xff)] } return Data(result) } struct BytesSequence: Sequence { let chunkSize: Int let data: [UInt8] func makeIterator() -> AnyIterator<ArraySlice<UInt8>> { var offset: Int = 0 return AnyIterator { var end: Int if self.chunkSize < self.data.count - offset { end = self.chunkSize } else { end = self.data.count - offset } let result = self.data[offset ..< offset + end] offset += result.count return result.count > 0 ? result : nil } } }
mit
8d787cb3043608ba2fd83c68230ed1f2
33.364532
216
0.5668
3.64282
false
false
false
false
lieonCX/TodayHeadline
TodayHealine/View/Find/FindViewController.swift
1
3528
// // FindViewController.swift // TodayHealine // // Created by lieon on 2017/1/26. // Copyright © 2017年 ChangHongCloudTechService. All rights reserved. // import UIKit import PromiseKit class FindViewController: BaseViewController { fileprivate lazy var finVM: FindViewModel = FindViewModel() fileprivate lazy var tableView: UITableView = {[unowned self] in let tableView = UITableView(frame: CGRect(x: 0.0, y: 0, width: UIScreen.width, height: UIScreen.height), style: UITableViewStyle.plain) tableView.dataSource = self tableView.delegate = self tableView.tableHeaderView = self.bannerView tableView.separatorStyle = .none return tableView }() fileprivate lazy var bannerView: CycleView = { let bannerView = CycleView.cycleView() bannerView.backgroundColor = UIColor.yellow bannerView.frame = CGRect(x: 0, y: 0, width: Int(UIScreen.width), height: Int(self.finVM.bannerHeight)) return bannerView }() override func viewDidLoad() { super.viewDidLoad() setupUI() loadData() } } extension FindViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return finVM.numberOfSections() } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return finVM.numberOfRows(in: section) } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch indexPath.section { case 0: let cell: RecHotTableViewCell = tableView.dequeueReuseableCell(for: indexPath) cell.finVM = finVM return cell case 1: let cell: TopicPostTableViewCell = tableView.dequeueReuseableCell(for: indexPath) cell.getModel(data: finVM.findlist[indexPath.row]) return cell default: break } return UITableViewCell() } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let titleView = SegmentView(frame: CGRect(x: 0, y: 0, width: Int(UIScreen.width), height: Int(finVM.segmenTitleViewHeight)), titles: ["最新", "热门", "关注"]) titleView.tapAction = { index in } return titleView } } extension FindViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return finVM.heightForRow(at: indexPath) } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return finVM.heightForHeader(in: section) } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { } } extension FindViewController { fileprivate func setupUI() { view.addSubview(tableView) automaticallyAdjustsScrollViewInsets = false tableView.register(R.nib.topicPostTableViewCell) tableView.register(R.nib.recHotTableViewCell) } fileprivate func loadData() { finVM.loadbannerAndActivity { [unowned self] in self.bannerView.banners = self.finVM.banners self.tableView.reloadData() } finVM.loadlistByNew { [unowned self] in self.tableView.reloadData() } finVM.loadlistByRec { } } } extension FindViewController { }
mit
9a2088d5cad2804143330825c7ecbbdf
30.366071
160
0.653288
4.81893
false
false
false
false
piscoTech/MBLibrary
Shared/TimeInterval.swift
1
2464
// // TimeInterval.swift // Workout // // Created by Marco Boschi on 19/07/16. // Copyright © 2016 Marco Boschi. All rights reserved. // import Foundation extension TimeInterval { private static let durationF: DateComponentsFormatter = { let formatter = DateComponentsFormatter() formatter.unitsStyle = .abbreviated formatter.zeroFormattingBehavior = .default return formatter }() public var formattedDuration: String { Self.durationF.string(from: self)! } public func rawDuration(hidingHours shouldHide: Bool = false) -> String { var s = self let neg = s < 0 if neg { s *= -1 } let m = floor(s / 60) let sec = Int(fmod(s, 60)) let h = floor(m / 60) let min = Int(fmod(m, 60)) let doHide = shouldHide && h == 0 var res = (sec < 10 ? "0" : "") + "\(sec)" res = (min < 10 && !doHide ? "0" : "") + "\(min):" + res res = (doHide ? "" : "\(h.toString()):") + res return (neg ? "-" : "") + res } /// The representation in the local time zone in the format `YYYY-MM-DD HH:mm` of the date created by interpreting the receiver as the number of seconds from January 1, 1970 00:00:00 UTC. public var unixDateTime: String { let date = Date(timeIntervalSince1970: self) return date.unixDateTime } /// The representation in the local time zone in the format `YYYY-MM-DD HH:mm:ss.sss` of the date created by interpreting the receiver as the number of seconds from January 1, 1970 00:00:00 UTC. public var unixTimestamp: String { let date = Date(timeIntervalSince1970: self) return date.unixTimestamp } /// The representation in the local time zone and current locale of the date and time created by interpreting the receiver as the number of seconds from January 1, 1970 00:00:00 UTC. public var formattedDateTime: String { let date = Date(timeIntervalSince1970: self) return date.formattedDate } /// The representation in the local time zone and current locale of the date created by interpreting the receiver as the number of seconds from January 1, 1970 00:00:00 UTC. public var formattedDate: String { let date = Date(timeIntervalSince1970: self) return date.formattedDate } /// The representation in the local time zone and current locale of the time created by interpreting the receiver as the number of seconds from January 1, 1970 00:00:00 UTC. public var formattedTime: String { let date = Date(timeIntervalSince1970: self) return date.formattedTime } }
mit
cb3f87ad981ffbd779e37b27aa12a685
29.407407
195
0.701989
3.676119
false
false
false
false
itssofluffy/NanoMessage
Sources/NanoMessage/Core/NanoSocketIO.swift
1
7936
/* NanoSocketIO.swift Copyright (c) 2016, 2017 Stephen Whittle 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 CNanoMessage import Foundation import ISFLibrary private let NN_MSG: size_t = -1 /// Is it valid to send or receive on the socket. /// /// - Parameters: /// - nanoSocket: The nano socket to use. /// /// - Throws: `NanoMessageError.SocketIsADevice` /// `NanoMessageError.NoEndPoint` internal func validateNanoSocket(_ nanoSocket: NanoSocket) throws { guard (!nanoSocket.isDevice) else { throw NanoMessageError.SocketIsADevice(socket: nanoSocket) } guard (nanoSocket.endPoints.count > 0) else { throw NanoMessageError.NoEndPoint(socket: nanoSocket) } } /// The low-level send function. /// /// - Parameters: /// - nanoSocket: The nano socket to use. /// - message: The message to send. /// - blockingMode: Specifies that the send should be performed in non-blocking mode. /// If the message cannot be sent straight away, the function will throw /// `NanoMessageError.MessageNotSent` /// /// - Throws: `NanoMessageError.SocketIsADevice` /// `NanoMessageError.NoEndPoint` /// `NanoMessageError.sendMessage` there was a problem sending the message. /// `NanoMessageError.MessageNotSent` the send has beem performed in non-blocking mode and the message cannot be sent straight away. /// `NanoMessageError.SendTimedOut` the send timedout. /// /// - Returns: The number of bytes sent. internal func sendToSocket(_ nanoSocket: NanoSocket, _ payload: Data, _ blockingMode: BlockingMode) throws -> RawSentData { try validateNanoSocket(nanoSocket) let bytesSent = Int(nn_send(nanoSocket.fileDescriptor, payload.bytes, payload.count, blockingMode.rawValue)) let timestamp = Date().timeIntervalSinceReferenceDate guard (bytesSent >= 0) else { let errno = nn_errno() if (blockingMode == .NonBlocking && errno == EAGAIN) { throw NanoMessageError.MessageNotSent } else if (errno == ETIMEDOUT) { let timeout = wrapper(do: { () -> TimeInterval in try getSocketOption(nanoSocket, .SendTimeout) }, catch: { failure in nanoMessageErrorLogger(failure) }) throw NanoMessageError.SendTimedOut(timeout: timeout!) } throw NanoMessageError.SendMessage(code: errno) } return RawSentData(bytes: bytesSent, timestamp: timestamp) } /// The low-level receive function. /// /// - Parameters: /// - nanoSocket: The nano socket to use. /// - blockingMode: Specifies if the socket should operate in blocking or non-blocking mode. /// if in non-blocking mode and there is no message to receive the function /// will throw `NanoMessageError.MessageNotReceived`. /// /// - Throws: `NanoMessageError.SocketIsADevice` /// `NanoMessageError.NoEndPoint` /// `NanoMessageError.ReceiveMessage` there was an issue when receiving the message. /// `NanoMessageError.MessageNotAvailable` in non-blocking mode there was no message to receive. /// `NanoMessageError.ReceiveTimedOut` the receive timedout. /// `NanoMessageError.FreeMessage` deallocation of the message has failed. /// /// - Returns: The number of bytes received and the received message internal func receiveFromSocket(_ nanoSocket: NanoSocket, _ blockingMode: BlockingMode) throws -> MessagePayload { try validateNanoSocket(nanoSocket) // A raw null pointer, we allocate nothing. In C this would be a void* var buffer = UnsafeMutableRawPointer(bitPattern: 0) // We pass a pointer to the above null pointer, in C this would be a void** // nn_recv() will do the actual memory allocation, and change raw to point to the new memory. let bytesReceived = Int(nn_recv(nanoSocket.fileDescriptor, &buffer, NN_MSG, blockingMode.rawValue)) let timestamp = Date().timeIntervalSinceReferenceDate guard (bytesReceived >= 0) else { let errno = nn_errno() if (blockingMode == .NonBlocking && errno == EAGAIN) { throw NanoMessageError.MessageNotAvailable } else if (errno == ETIMEDOUT) { let timeout = wrapper(do: { () -> TimeInterval in try getSocketOption(nanoSocket, .ReceiveTimeout) }, catch: { failure in nanoMessageErrorLogger(failure) }) throw NanoMessageError.ReceiveTimedOut(timeout: timeout!) } throw NanoMessageError.ReceiveMessage(code: errno) } // Swift doesn't like going between UnsafeMutableRawPointer and UnsafeMutableBufferPointer, so we create a // OpaquePointer out of our UnsafeMutableRawPointer, just to create an UnsafeMutablePointer which we can use to // create an UnsafeMutableBufferPointer. Thanks Apple. let p = UnsafeMutablePointer<Byte>(OpaquePointer(buffer)) let message = Message(buffer: UnsafeMutableBufferPointer(start: p, count: bytesReceived)) // finally call nn_freemsg() to free the memory that nn_recv() allocated for us guard (nn_freemsg(buffer) >= 0) else { throw NanoMessageError.FreeMessage(code: nn_errno()) } return MessagePayload(bytes: bytesReceived, message: message, direction: .Received, timestamp: timestamp) } /// Asynchrounous execute a passed operation closure. /// /// - Parameters: /// - nanoSocket: The socket to perform the operation on. /// - closure: The closure to use to perform the send /// - success: The closure to use when `closure()` is succesful. /// - capture: The closure to use to pass any objects required when an error occurs. internal func asyncOperationOnSocket(nanoSocket: NanoSocket, closure: @escaping () throws -> MessagePayload, success: @escaping (MessagePayload) -> Void, capture: @escaping () -> Array<Any>) { nanoSocket.aioQueue.async(group: nanoSocket.aioGroup) { wrapper(do: { try nanoSocket.mutex.lock { try success(closure()) } }, catch: { failure in nanoMessageErrorLogger(failure) }, capture: capture) } }
mit
fd991f7f73c49a0dc43f8b617f4b5568
43.088889
143
0.631174
4.907854
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureQRCodeScanner/Sources/FeatureQRCodeScannerUIMock/MockCaptureSession.swift
1
1284
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import AVKit @testable import FeatureQRCodeScannerUI final class CaptureSessionMock: CaptureSessionProtocol { var sessionPreset = AVCaptureSession.Preset.high var current: AVCaptureSession? = AVCaptureSession() var startRunningCallback: () -> Void = {} var startRunningCallCount: Int = 0 func startRunning() { startRunningCallCount += 1 startRunningCallback() } var stopRunningCallback: () -> Void = {} var stopRunningCallCount: Int = 0 func stopRunning() { stopRunningCallCount += 1 stopRunningCallback() } var addInputCallback: (CaptureInputProtocol) -> Void = { _ in } var inputsAdded: [CaptureInputProtocol] = [] func add(input: CaptureInputProtocol) { inputsAdded.append(input) addInputCallback(input) } var addOutputCallback: (CaptureOutputProtocol) -> Void = { _ in } var outputsAdded: [CaptureOutputProtocol] = [] func add(output: CaptureOutputProtocol) { outputsAdded.append(output) addOutputCallback(output) } func canAdd(input: CaptureInputProtocol) -> Bool { true } func canAdd(output: CaptureOutputProtocol) -> Bool { true } }
lgpl-3.0
a5775dd93c86d496de625b88c3f398d6
25.183673
69
0.667186
4.615108
false
false
false
false
harlanhaskins/Swifter-1
Sources/SwifterSuggested.swift
2
2997
// // SwifterSuggested.swift // Swifter // // Copyright (c) 2014 Matt Donnelly. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation public extension Swifter { /** GET users/suggestions/:slug Access the users in a given category of the Twitter suggested user list. It is recommended that applications cache this data for no more than one hour. */ public func getUserSuggestions(slug: String, lang: String? = nil, success: SuccessHandler? = nil, failure: FailureHandler? = nil) { let path = "users/suggestions/\(slug).json" var parameters = Dictionary<String, Any>() parameters["lang"] ??= lang self.getJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in success?(json) }, failure: failure) } /** GET users/suggestions Access to Twitter's suggested user list. This returns the list of suggested user categories. The category can be used in GET users/suggestions/:slug to get the users in that category. */ public func getUsersSuggestions(lang: String? = nil, success: SuccessHandler? = nil, failure: FailureHandler? = nil) { let path = "users/suggestions.json" var parameters = Dictionary<String, Any>() parameters["lang"] ??= lang self.getJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in success?(json) }, failure: failure) } /** GET users/suggestions/:slug/members Access the users in a given category of the Twitter suggested user list and return their most recent status if they are not a protected user. */ public func getUsersSuggestions(for slug: String, success: SuccessHandler? = nil, failure: FailureHandler? = nil) { let path = "users/suggestions/\(slug)/members.json" self.getJSON(path: path, baseURL: .api, parameters: [:], success: { json, _ in success?(json) }, failure: failure) } }
mit
db35d60b7b8d441b131f06fb9228d4d8
41.814286
187
0.701368
4.381579
false
false
false
false
ozgur/AutoLayoutAnimation
autolayoutanimation/AlamofirePostViewController.swift
1
4128
// // AlamofirePostViewController.swift // AutoLayoutAnimation // // Created by Ozgur Vatansever on 10/19/15. // Copyright © 2015 Techshed. All rights reserved. // import UIKit import Alamofire class AlamofirePostViewController: UIViewController { convenience init() { self.init(nibName: "AlamofirePostViewController", bundle: nil) } @IBOutlet fileprivate weak var activityIndicatorView: UIActivityIndicatorView! @IBOutlet fileprivate weak var responseLabel: UILabel! @IBOutlet fileprivate weak var progressView: UIProgressView! fileprivate func url(_ url: String) -> String { return "http://httpbin.org" + url } fileprivate var imagePath: URL! { return Bundle.main.url(forResource: "image", withExtension: "jpg") } fileprivate let credentials = URLCredential(user: "ozgur", password: "rbrocks", persistence: .forSession) override func loadView() { super.loadView() view.backgroundColor = UIColor.white } override func viewDidLoad() { super.viewDidLoad() self.edgesForExtendedLayout = UIRectEdge() title = "Alamofire POST" } @IBAction func uploadButtonTapped(_ sender: UIButton) { activityIndicatorView.stopAnimating() progressView.progress = 0.0 progressView.isHidden = false responseLabel.text = "Sending \(imagePath.absoluteString) ..." Alamofire.upload(.POST, url("/post"), file: imagePath) .progress { bytesSent, totalBytesSent, totalBytesExpectedToSend in let progress = Float(totalBytesSent) / Float(totalBytesExpectedToSend) DispatchQueue.main.async(execute: { self.progressView.setProgress(progress, animated: true) self.responseLabel.text = "Sending %\(progress * 100)" }) } .response { request, response, data, error -> Void in self.responseLabel.text = "Sent image.jpg" } } func login(_ userName: String, password: String, completionHandler: ([String: AnyObject]) -> Void) { let device = UIDevice().identifierForVendor! let parameters = ["login": userName, "password": password, "deviceid": device] Alamofire.request(.POST, "http://www.google.com", parameters: parameters).responseJSON { response in if response.result.isSuccess { completionHandler(response.result.value as! [String: AnyObject]) } else { print("Error: \(response.result.error!.description)") } } } @IBAction func headersButtonTapped(_ sender: UIButton) { progressView.isHidden = true activityIndicatorView.startAnimating() responseLabel.text = nil let absoluteURL: URL! = URL(string: url("/headers")) var request = NSMutableURLRequest(url: absoluteURL) request.httpMethod = "GET" request = Alamofire.ParameterEncoding.url.encode(request, parameters: ["foo": "bar"]).0 Alamofire.request(request).responseJSON { response in self.activityIndicatorView.stopAnimating() if response.result.isSuccess { let result = response.result.value as! [String: [String: String]] let headers = result["headers"]!.map { (key, value) -> String in return "\(key) -> \(value)" } self.responseLabel.text = headers.joined(separator: "\n") } else { self.responseLabel.text = response.result.error!.description } } } @IBAction func basicAuthButtonTapped(_ sender: UIButton) { progressView.isHidden = true activityIndicatorView.startAnimating() responseLabel.text = nil Alamofire.request(.GET, url("/basic-auth/\(credentials.user!)/\(credentials.password!)")) .authenticate(usingCredential: credentials) .responseJSON { response in self.activityIndicatorView.stopAnimating() if response.result.isSuccess { let result = response.result.value as! [String: AnyObject] let headers = result.map { (key, value) -> String in return "\(key) -> \(String(value))" } self.responseLabel.text = headers.joined(separator: "\n") } } } }
mit
885f3324573932fb725c1bfe7d1112ef
30.992248
107
0.663436
4.716571
false
false
false
false
barisarsan/ScreenSceneController
ScreenSceneController/ScreenSceneController/ScreenSceneContainerView.swift
2
3057
// // ScreenSceneContainerView.swift // ScreenSceneController // // Copyright (c) 2014 Ruslan Shevchuk // // 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 @objc public class ScreenSceneContainerView: UIScrollView { // MARK: - Initial Screen Container Setup override public func willMoveToSuperview(newSuperview: UIView?) { super.willMoveToSuperview(newSuperview) alwaysBounceHorizontal = true alwaysBounceVertical = false canCancelContentTouches = true clipsToBounds = false showsHorizontalScrollIndicator = false showsVerticalScrollIndicator = false delaysContentTouches = false } // MARK: - // Possibility to disable scroll when container touch intersect some special view that not allow containers moves during interaction with it. override public func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? { if let view = super.hitTest(point, withEvent: event) { let scrollEnabled = hitTest(view) self.scrollEnabled = scrollEnabled return view } else { return nil } } func hitTest(view: UIView) -> Bool { var enableScroll = true for anyClass in ScreenSceneSettings.defaultSettings.classesThatDisableScrolling { if shouldDisableScroll(view, classToCheck: anyClass) { enableScroll = false break } } return enableScroll } func shouldDisableScroll(view: UIView, classToCheck: AnyClass) -> Bool { if (view.isKindOfClass(classToCheck)) { return true } else if let superview = view.superview { return shouldDisableScroll(superview, classToCheck: classToCheck) } else { return false } } }
mit
f8fce8ed6ad310b435561889d92a6eb9
34.137931
145
0.650311
5.325784
false
false
false
false
kazuhiro4949/PagingKit
Sources/PagingMenuView.swift
1
31524
// // PagingMenuView.swift // PagingKit // // Copyright (c) 2017 Kazuhiro Hayashi // // 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 /** A PagingMenuViewCell object presents the content for a single menu item when that item is within the paging menu view's visible bounds. You can use this class as-is or subclass it to add additional properties and methods. The layout and presentation of cells is managed by the paging menu view. */ open class PagingMenuViewCell: UIView { /** The selection state of the cell. It is not managed by this class and paging menu view now. You can use this property as an utility to manage selected state. */ open var isSelected: Bool = false /** A string that identifies the purpose of the view. The paging menu view identifies and queues reusable views using their reuse identifiers. The paging menu view sets this value when it first creates the view, and the value cannot be changed later. When your data source is prompted to provide a given view, it can use the reuse identifier to dequeue a view of the appropriate type. */ public internal(set) var identifier: String! /** A index that identifier where the view locate on. The paging menu view identifiers and queues reusable views using their reuse identifiers. The index specify current state for the view's position. */ public internal(set) var index: Int! } /// A set of methods that provides support for animations associated with a focus view transition. /// You can use a coordinator object to perform tasks that are related to a transition but that are separate from what the animator objects are doing. open class PagingMenuFocusViewAnimationCoordinator { /// A frame at the start position public let beginFrame: CGRect /// A frame at the end position public let endFrame: CGRect fileprivate var animationHandler: ((PagingMenuFocusViewAnimationCoordinator) -> Void)? fileprivate var completionHandler: ((Bool) -> Void)? init(beginFrame: CGRect, endFrame: CGRect) { self.beginFrame = beginFrame self.endFrame = endFrame } /// Runs the specified animations at the same time as the focus view animations. /// /// - Parameters: /// - animation: A block containing the animations you want to perform. These animations run in the same context as the focus view animations and therefore have the same default attributes. /// - completion: The block of code to execute after the animation finishes. You may specify nil for this open func animateFocusView(alongside animation: @escaping (PagingMenuFocusViewAnimationCoordinator) -> Void, completion: ((Bool) -> Void)?) { animationHandler = animation completionHandler = completion } } /// A view that focus menu corresponding to current page. open class PagingMenuFocusView: UIView { open var selectedIndex: Int? public override init(frame: CGRect) { super.init(frame: frame) backgroundColor = .clear } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } } /** An object that adopts the PagingMenuViewDataSource protocol is responsible for providing the data and views required by a paging menu view. A data source object represents your app’s data model and vends information to the collection view as needed. It also handles the creation and configuration of cells and supplementary views used by the collection view to display your data. */ public protocol PagingMenuViewDataSource: AnyObject { /// Asks your data source object for the number of sections in the paging menu view. /// /// - Returns: The number of items in paging menu view. func numberOfItemForPagingMenuView() -> Int /// Asks your data source object for the cell that corresponds to the specified item in the paging menu view. /// You can use this delegate methid like UITableView or UICollectionVew. /// /// - Parameters: /// - pagingMenuView: The paging menu view requesting this information. /// - index: The index that specifies the location of the item. /// - Returns: A configured cell object. You must not return nil from this method. func pagingMenuView(pagingMenuView: PagingMenuView, cellForItemAt index: Int) -> PagingMenuViewCell /// Asks the delegate for the width to use for a row in a specified location. /// /// - Parameters: /// - pagingMenuView: The paging menu view requesting this information. /// - index: The index that specifies the location of the item. /// - Returns: A nonnegative floating-point value that specifies the width (in points) that row should be. func pagingMenuView(pagingMenuView: PagingMenuView, widthForItemAt index: Int) -> CGFloat } /** The PagingMenuViewDelegate protocol defines methods that allow you to manage the selection of items in a paging menu view and to perform actions on those items. */ public protocol PagingMenuViewDelegate: AnyObject { /// Tells the delegate that the specified row is now selected. /// /// - Parameters: /// - pagingMenuView: The paging menu view requesting this information. /// - index: The index that specifies the location of the item. func pagingMenuView(pagingMenuView: PagingMenuView, didSelectItemAt index: Int) /// Notifies the menu view that the frame of its focus view is about to change. /// The menu view calls this method before adding a cell to its content. Use this method to detect cell additions, as opposed to monitoring the cell itself to see when it appears. /// /// - Parameters: /// - pagingMenuView: a menu view object informing the delegate. /// - index: end index /// - coordinator: animator coordinator func pagingMenuView(pagingMenuView: PagingMenuView, willAnimateFocusViewTo index: Int, with coordinator: PagingMenuFocusViewAnimationCoordinator) /// Tells the delegate that the specified cell is about to be displayed in the menu view. /// /// - Parameters: /// - pagingMenuView: a menu view object informing the delegate. /// - cell: The cell object being added. /// - index: The index path of the data item that the cell represents. func pagingMenuView(pagingMenuView: PagingMenuView, willDisplay cell: PagingMenuViewCell, forItemAt index: Int) } public extension PagingMenuViewDelegate { func pagingMenuView(pagingMenuView: PagingMenuView, didSelectItemAt index: Int) {} func pagingMenuView(pagingMenuView: PagingMenuView, willAnimateFocusViewTo index: Int, with coordinator: PagingMenuFocusViewAnimationCoordinator) {} func pagingMenuView(pagingMenuView: PagingMenuView, willDisplay cell: PagingMenuViewCell, forItemAt index: Int) {} } /// Displays menu lists of information and supports selection and paging of the information. open class PagingMenuView: UIScrollView { enum RegisteredCell { case nib(nib: UINib) case type(type: PagingMenuViewCell.Type) } /// If contentSize.width is not over safe area, paging menu view applys this value to each thecells. /// /// - center: centering each PagingMenuViewCell object. /// - left: aligning each PagingMenuViewCell object on the left side. /// - right: aligning each PagingMenuViewCell object on the right side. public enum Alignment { case center case left case right /// calculation origin.x from max offset.x /// /// - Parameter maxOffsetX: maximum offset.x on scroll view /// - Returns: container view's origin.x func calculateOriginX(from maxOffsetX: CGFloat) -> CGFloat { switch self { case .center: return maxOffsetX/2 case .left: return 0 case .right: return maxOffsetX } } } //MARK:- open /// The object that acts as the indicator to focus current menu. public let focusView = PagingMenuFocusView(frame: .zero) /// Returns an array of visible cells currently displayed by the menu view. open fileprivate(set) var visibleCells = [PagingMenuViewCell]() fileprivate var queue = [String: [PagingMenuViewCell]]() fileprivate var registeredCells = [String: RegisteredCell]() fileprivate var widths = [CGFloat]() fileprivate(set) var containerView = UIView() fileprivate var touchingIndex: Int? /// If contentSize.width is not over safe area, paging menu view applys cellAlignment to each the cells. (default: .left) open var cellAlignment: Alignment = .left /// space setting between cells open var cellSpacing: CGFloat = 0 /// total space between cells open var totalSpacing: CGFloat { return cellSpacing * numberOfCellSpacing } /// The object that acts as the data source of the paging menu view. open weak var dataSource: PagingMenuViewDataSource? /// The object that acts as the delegate of the paging menu view. open weak var menuDelegate: PagingMenuViewDelegate? public override init(frame: CGRect) { super.init(frame: frame) configureContainerView() configureFocusView() configureView() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) configureContainerView() configureFocusView() configureView() } /// The number of items in the paging menu view. open var numberOfItem: Int = 0 /// Returns an index identifying the row and section at the given point. /// /// - Parameter point: A point in the local coordinate system of the paging menu view (the paging menu view’€™s bounds). /// - Returns: An index path representing the item associated with point, or nil if the point is out of the bounds of any item. open func indexForItem(at point: CGPoint) -> Int? { var currentOffsetX: CGFloat = 0 var resultIndex: Int? = nil for (idx, width) in widths.enumerated() { let nextOffsetX = currentOffsetX + width if (currentOffsetX..<nextOffsetX) ~= point.x { resultIndex = idx break } currentOffsetX = nextOffsetX } return resultIndex } /// Returns the paging menu cell at the specified index . /// /// - Parameter index: The index locating the item in the paging menu view. /// - Returns: An object representing a cell of the menu, or nil if the cell is not visible or index is out of range. open func cellForItem(at index: Int) -> PagingMenuViewCell? { return visibleCells.filter { $0.index == index }.first } /// Reloads the rows and sections of the menu view. /// /// - Parameters: /// - index: focusing index /// - completion: completion handler open func reloadData(with index: Int = 0, completion: ((Bool) -> Void)? = nil) { focusView.selectedIndex = index contentOffset = .zero _reloadData() UIView.pk.catchLayoutCompletion( layout: { [weak self] in self?.scroll(index: index) }, completion: { finish in completion?(finish) } ) } /// Registers a nib object containing a cell with the paging menu view under a specified identifier. /// /// - Parameters: /// - nib: A nib object that specifies the nib file to use to create the cell. /// - identifier: The reuse identifier for the cell. This parameter must not be nil and must not be an empty string. open func register(nib: UINib?, with identifier: String) { registeredCells[identifier] = nib.flatMap { .nib(nib: $0) } } /// Registers a cell type under a specified identifier. /// /// - Parameters: /// - type: A type that specifies the cell to use to create it. /// - identifier: The reuse identifier for the cell. This parameter must not be nil and must not be an empty string. open func register(type: PagingMenuViewCell.Type, with identifier: String) { registeredCells[identifier] = .type(type: type) } open func registerFocusView(view: UIView, isBehindCell: Bool = false) { view.autoresizingMask = [ .flexibleWidth, .flexibleHeight ] view.translatesAutoresizingMaskIntoConstraints = true view.frame = CGRect( origin: .zero, size: focusView.bounds.size ) focusView.addSubview(view) focusView.layer.zPosition = isBehindCell ? -1 : 0 } open func registerFocusView(nib: UINib, isBehindCell: Bool = false) { let view = nib.instantiate(withOwner: self, options: nil).first as! UIView registerFocusView(view: view, isBehindCell: isBehindCell) } /// Returns a reusable paging menu view cell object for the specified reuse identifier and adds it to the menu. /// /// - Parameter identifier: A string identifying the cell object to be reused. This parameter must not be nil. /// - Returns: The index specifying the location of the cell. open func dequeue(with identifier: String) -> PagingMenuViewCell { if var cells = queue[identifier], !cells.isEmpty { let cell = cells.removeFirst() queue[identifier] = cells cell.identifier = identifier return cell } switch registeredCells[identifier] { case .nib(let nib)?: let cell = nib.instantiate(withOwner: self, options: nil).first as! PagingMenuViewCell cell.identifier = identifier return cell case .type(let type)?: let cell = type.init() cell.identifier = identifier return cell default: fatalError() } } /// Returns the drawing area for a row identified by index. /// /// - Parameter index: An index that identifies a item by its index. /// - Returns: A rectangle defining the area in which the table view draws the row or right edge rect if index is over the number of items. open func rectForItem(at index: Int) -> CGRect { guard 0 < widths.count else { return CGRect(x: 0, y: 0, width: 0, height: bounds.height) } guard index < widths.count else { let rightEdge = widths.reduce(CGFloat(0)) { (sum, width) in sum + width } + totalSpacing let mostRightWidth = widths[widths.endIndex - 1] return CGRect(x: rightEdge, y: 0, width: mostRightWidth, height: bounds.height) } guard 0 <= index else { let leftEdge = -widths[0] let mostLeftWidth = widths[0] return CGRect(x: leftEdge, y: 0, width: mostLeftWidth, height: bounds.height) } var x = (0..<index).reduce(0) { (sum, idx) in return sum + widths[idx] } x += cellSpacing * CGFloat(index) return CGRect(x: x, y: 0, width: widths[index], height: bounds.height) } open func invalidateLayout() { guard let dataSource = dataSource else { return } widths = [] var containerWidth: CGFloat = 0 (0..<numberOfItem).forEach { (index) in let width = dataSource.pagingMenuView(pagingMenuView: self, widthForItemAt: index) widths.append(width) containerWidth += width } containerWidth += totalSpacing contentSize = CGSize(width: containerWidth, height: bounds.height) containerView.frame = CGRect(origin: .zero, size: contentSize) alignEachVisibleCell() } open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if keyPath == #keyPath(UIView.bounds), let newFrame = change?[.newKey] as? CGRect, let oldFrame = change?[.oldKey] as? CGRect, newFrame.height != oldFrame.height { adjustComponentHeights(from: newFrame.height) } } /// Scrolls a specific index of the menu so that it is visible in the receiver. /// /// - Parameters: /// - index: A index defining an menu of the menu view. /// - percent: A rate that transit from the index. (percent ranges from -0.5 to 0.5.) open func scroll(index: Int, percent: CGFloat = 0) { // Specification in this method is difference from the interface specification. let (index, percent) = correctScrollIndexAndPercent(index: index, percent: percent) let rightIndex = index + 1 let leftFrame = rectForItem(at: index) let rightFrame = rectForItem(at: rightIndex) let width = (rightFrame.width - leftFrame.width) * percent + leftFrame.width focusView.frame.size = CGSize(width: width, height: bounds.height) let centerPointX = leftFrame.midX + (rightFrame.midX - leftFrame.midX) * percent let offsetX = centerPointX - bounds.width / 2 let normaizedOffsetX = min(max(minContentOffsetX, offsetX), maxContentOffsetX) focusView.center = CGPoint(x: centerPointX, y: center.y) let expectedIndex = (focusView.center.x < leftFrame.maxX) ? index : rightIndex focusView.selectedIndex = max(0, min(expectedIndex, numberOfItem - 1)) contentOffset = CGPoint(x: normaizedOffsetX, y:0) if let index = focusView.selectedIndex { visibleCells.selectCell(with: index) } } /// Scrolls a specific index of the menu so that it is visible in the receiver and calls handler when finishing scroll. /// /// - Parameters: /// - index: A index defining an menu of the menu view. /// - completeHandler: handler called after completion open func scroll(index: Int, completeHandler: @escaping (Bool) -> Void) { let itemFrame = rectForItem(at: index) let offsetX = itemFrame.midX - bounds.width / 2 let offset = CGPoint(x: min(max(minContentOffsetX, offsetX), maxContentOffsetX), y: 0) focusView.selectedIndex = index visibleCells.selectCell(with: index) let coordinator = PagingMenuFocusViewAnimationCoordinator(beginFrame: focusView.frame, endFrame: itemFrame) menuDelegate?.pagingMenuView(pagingMenuView: self, willAnimateFocusViewTo: index, with: coordinator) UIView.perform(.delete, on: [], options: UIView.AnimationOptions(rawValue: 0), animations: { [weak self] in guard let _self = self else { return } _self.contentOffset = offset _self.focusView.frame = itemFrame _self.focusView.layoutIfNeeded() coordinator.animationHandler?(coordinator) }, completion: { (finished) in coordinator.completionHandler?(finished) completeHandler(finished) }) } // MARK:- Internal var contentSafeAreaInsets: UIEdgeInsets { if #available(iOS 11.0, *) { return safeAreaInsets } else { return .zero } } var safedViewWidth: CGFloat { return bounds.width - contentSafeAreaInsets.horizontal } var hasScrollableArea: Bool { return safedViewWidth < contentSize.width } var maxContentOffsetX: CGFloat { return max(bounds.width, contentSize.width + contentSafeAreaInsets.right + contentInset.right) - bounds.width } var minContentOffsetX: CGFloat { return -(contentSafeAreaInsets.left + contentInset.left) } // max offset inside safe area var maxSafedOffset: CGFloat { return safedViewWidth - containerView.frame.width } // MARK:- Private /// Reloads the rows and sections of the menu view. private func _reloadData() { guard let dataSource = dataSource else { return } visibleCells.forEach { $0.removeFromSuperview() } visibleCells = [] numberOfItem = dataSource.numberOfItemForPagingMenuView() invalidateLayout() setNeedsLayout() layoutIfNeeded() } private func configureContainerView() { containerView.frame = bounds containerView.center = center addSubview(containerView) } private func configureFocusView() { focusView.frame = CGRect(x: 0, y: 0, width: 1, height: 1) // to avoid ignoring focus view's layout containerView.addSubview(focusView) } private func configureView() { backgroundColor = .clear addObserver(self, forKeyPath: #keyPath(UIView.bounds), options: [.old, .new], context: nil) } private var numberOfCellSpacing: CGFloat { return max(CGFloat(numberOfItem - 1), 0) } private func recenterIfNeeded() { let currentOffset = contentOffset let contentWidth = contentSize.width let centerOffsetX = (contentWidth - bounds.size.width) / 2 let distanceFromCenter = abs(currentOffset.x - centerOffsetX) if distanceFromCenter > (contentWidth - bounds.size.width) / 4 { contentOffset = CGPoint(x: centerOffsetX, y: currentOffset.y) for cell in visibleCells { var center = containerView.convert(cell.center, to: self) center.x += centerOffsetX - currentOffset.x cell.center = convert(center, to: containerView) } } } private func alignEachVisibleCell() { visibleCells.forEach { (cell) in let leftEdge = (0..<cell.index).reduce(CGFloat(0)) { (sum, idx) in sum + widths[idx] + cellSpacing } cell.frame.origin = CGPoint(x: leftEdge, y: 0) cell.frame.size = CGSize(width: widths[cell.index], height: containerView.bounds.height) } } private func adjustComponentHeights(from newHeight: CGFloat) { contentSize.height = newHeight containerView.frame.size.height = newHeight visibleCells.forEach { $0.frame.size.height = newHeight } focusView.frame.size.height = newHeight } @discardableResult private func placeNewCellOnRight(with rightEdge: CGFloat, index: Int, dataSource: PagingMenuViewDataSource) -> CGFloat { let nextIndex = (index + 1) % numberOfItem let cell = dataSource.pagingMenuView(pagingMenuView: self, cellForItemAt: nextIndex) cell.isSelected = (focusView.selectedIndex == nextIndex) cell.index = nextIndex containerView.insertSubview(cell, at: 0) visibleCells.append(cell) cell.frame.origin = CGPoint(x: rightEdge, y: 0) cell.frame.size = CGSize(width: widths[nextIndex], height: containerView.bounds.height) menuDelegate?.pagingMenuView(pagingMenuView: self, willDisplay: cell, forItemAt: nextIndex) return cell.frame.maxX } private func placeNewCellOnLeft(with leftEdge: CGFloat, index: Int, dataSource: PagingMenuViewDataSource) -> CGFloat { let nextIndex: Int if index == 0 { nextIndex = numberOfItem - 1 } else { nextIndex = (index - 1) % numberOfItem } let cell = dataSource.pagingMenuView(pagingMenuView: self, cellForItemAt: nextIndex) cell.isSelected = (focusView.selectedIndex == nextIndex) cell.index = nextIndex containerView.insertSubview(cell, at: 0) visibleCells.insert(cell, at: 0) cell.frame.size = CGSize(width: widths[nextIndex], height: containerView.bounds.height) cell.frame.origin = CGPoint(x: leftEdge - widths[nextIndex] - cellSpacing, y: 0) menuDelegate?.pagingMenuView(pagingMenuView: self, willDisplay: cell, forItemAt: nextIndex) return cell.frame.minX } private func tileCell(from minX: CGFloat, to maxX: CGFloat) { guard let dataSource = dataSource, 0 < numberOfItem else { return } if visibleCells.isEmpty { placeNewCellOnRight(with: minX, index: numberOfItem - 1, dataSource: dataSource) } var lastCell = visibleCells.last var rightEdge = lastCell.flatMap { $0.frame.maxX + cellSpacing } while let _lastCell = lastCell, let _rightEdge = rightEdge, _rightEdge < maxX, (0..<numberOfItem) ~= _lastCell.index + 1 { rightEdge = placeNewCellOnRight(with: _rightEdge, index: _lastCell.index, dataSource: dataSource) + cellSpacing lastCell = visibleCells.last } var firstCell = visibleCells.first var leftEdge = firstCell?.frame.minX while let _firstCell = firstCell, let _leftEdge = leftEdge, _leftEdge > minX, (0..<numberOfItem) ~= _firstCell.index - 1 { leftEdge = placeNewCellOnLeft(with: _leftEdge, index: _firstCell.index, dataSource: dataSource) firstCell = visibleCells.first } while let lastCell = visibleCells.last, lastCell.frame.minX > maxX { lastCell.removeFromSuperview() let recycleCell = visibleCells.removeLast() if let cells = queue[recycleCell.identifier] { queue[recycleCell.identifier] = cells + [recycleCell] } else { queue[recycleCell.identifier] = [recycleCell] } } while let firstCell = visibleCells.first, firstCell.frame.maxX < minX { firstCell.removeFromSuperview() let recycleCell = visibleCells.removeFirst() if let cells = queue[recycleCell.identifier] { queue[recycleCell.identifier] = cells + [recycleCell] } else { queue[recycleCell.identifier] = [recycleCell] } } } /// If contentSize.width is not over safe area, paging menu view applys cellAlignment to each the cells. private func alignContainerViewIfNeeded() { guard let expectedOriginX = getExpectedAlignmentPositionXIfNeeded() else { return } if expectedOriginX != containerView.frame.origin.x { containerView.frame.origin.x = expectedOriginX } } /// get correct origin X of menu view's container view, If menu view is scrollable. func getExpectedAlignmentPositionXIfNeeded() -> CGFloat? { let expectedOriginX = cellAlignment.calculateOriginX(from: maxSafedOffset) guard !hasScrollableArea else { return nil } return expectedOriginX } /// correct a page index as starting index is always left side. /// /// - Parameters: /// - index: current page index defined in PagingKit /// - percent: current percent defined in PagingKit /// - Returns: index and percent private func correctScrollIndexAndPercent(index: Int, percent: CGFloat) -> (index: Int, percent: CGFloat) { let pagingPositionIsLeftSide = (percent < 0) if pagingPositionIsLeftSide { if index == 0 { return (index: index, percent: percent) } else { return (index: max(index - 1, 0), percent: percent + 1) } } else { return (index: index, percent: percent) } } //MARK:- Life Cycle open override func layoutSubviews() { super.layoutSubviews() if numberOfItem != 0 { let visibleBounds = convert(bounds, to: containerView) let extraOffset = visibleBounds.width / 2 tileCell( from: max(0, visibleBounds.minX - extraOffset), to: min(contentSize.width, visibleBounds.maxX + extraOffset) ) } alignContainerViewIfNeeded() } @available(iOS 11.0, *) open override func safeAreaInsetsDidChange() { super.safeAreaInsetsDidChange() alignEachVisibleCell() } deinit { removeObserver(self, forKeyPath: #keyPath(UIView.bounds)) } } //MARK:- Touch Event extension PagingMenuView { open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesBegan(touches, with: event) guard let touchPoint = touches.first.flatMap({ $0.location(in: containerView) }) else { return } touchingIndex = visibleCells.filter { cell in cell.frame.contains(touchPoint) }.first?.index } open override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesEnded(touches, with: event) defer { touchingIndex = nil } guard let touchingIndex = self.touchingIndex, let touchPoint = touches.first.flatMap({ $0.location(in: containerView) }), let touchEndedIndex = visibleCells.filter({ $0.frame.contains(touchPoint) }).first?.index else { return } if touchingIndex == touchEndedIndex { menuDelegate?.pagingMenuView(pagingMenuView: self, didSelectItemAt: touchingIndex) } } open override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesCancelled(touches, with: event) touchingIndex = nil } } // MARK: - UIEdgeInsets private extension UIEdgeInsets { /// only horizontal insets var horizontal: CGFloat { return left + right } } // MARK:- CGRect private extension CGRect { var center: CGPoint { return CGPoint(x: midX, y: midY) } } // MARK:- Array private extension Array where Element == PagingMenuViewCell { func resetSelected() { forEach { $0.isSelected = false } } @discardableResult func selectCell(with index: Int) -> Int? { resetSelected() let selectedCell = filter { $0.index == index }.first selectedCell?.isSelected = true return selectedCell?.index } }
mit
bb60e3669a67e574cfaa4bd2bc432021
38.946768
335
0.646044
4.843707
false
false
false
false
mendesbarreto/IOS
UICollectionInUITableViewCell/UICollectionInUITableViewCell/DateSliderMenuView.swift
1
896
// // ButtomView.swift // DatebuttonsScrolls // // Created by Douglas Barreto on 2/20/16. // Copyright © 2016 Douglas. All rights reserved. // import UIKit public class DateSliderMenuView: UICollectionView { // public var view: UIView? // // public var collectionView:UICollectionView! // override public init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) { super.init(frame: frame, collectionViewLayout: layout) initWithNib() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initWithNib() } public func initWithNib() { //view = self.loadFromNib() self.userInteractionEnabled = true let nib = UINib(nibName: "DateCollectionViewCell", bundle:nil) self.registerNib(nib, forCellWithReuseIdentifier: "DateCollectionViewCell") self.backgroundColor = UIColor.whiteColor() self.pagingEnabled = true } }
mit
f09a2e7240323a2fe4aecf9f258df178
22.578947
91
0.73743
3.925439
false
false
false
false
lyp1992/douyu-Swift
YPTV/YPTV/Classes/Home/Other/YPWaterFallLayout.swift
1
2796
// // YPWaterFallLayout.swift // YPWaterFallLayout // // Created by 赖永鹏 on 2018/12/3. // Copyright © 2018年 LYP. All rights reserved. // import UIKit @objc protocol YPWaterFallLayoutDataSource : class{ func waterFallLayout(_ layout : YPWaterFallLayout , indexPath : IndexPath) -> CGFloat @objc optional func waterFallLayout(_ layout : YPWaterFallLayout) -> Int } class YPWaterFallLayout: UICollectionViewFlowLayout { weak var dataSource : YPWaterFallLayoutDataSource? fileprivate lazy var cols : Int = Int(self.dataSource?.waterFallLayout?(self) ?? 2) fileprivate lazy var cellAttrs : [UICollectionViewLayoutAttributes] = [UICollectionViewLayoutAttributes]() fileprivate lazy var colHeights : [CGFloat] = Array(repeating: self.sectionInset.top, count: self.cols) } //准备布局 extension YPWaterFallLayout { override func prepare() { super.prepare() // 1. 检验collectionview是否有值 guard let collectionView = collectionView else { return } // 2. 获取cell的个数 let count = collectionView.numberOfItems(inSection: 0) // 3. 遍历所有的cell,计算出frame let itemW = (collectionView.bounds.width - sectionInset.left - sectionInset.right - (CGFloat(cols) - 1)*minimumInteritemSpacing) / CGFloat(cols) for i in cellAttrs.count..<count { // 3.1 创建attribute let indexPath = IndexPath(item: i, section: 0) let attr = UICollectionViewLayoutAttributes(forCellWith: indexPath) // 3.2 计算高度 let itemH = dataSource?.waterFallLayout(self, indexPath: indexPath) ?? 0 // 3.3 计算x值 let minH = colHeights.min()! let minIndex = colHeights.index(of: minH)! let itemX = sectionInset.left + CGFloat(minIndex) * (itemW + minimumInteritemSpacing) // 3.4 计算Y值 let itemY = minH // 3.5 设置frame attr.frame = CGRect(x: itemX, y: itemY, width: itemW, height: itemH) // 3.6 给minIndex附上新值 colHeights[minIndex] = attr.frame.maxY + minimumLineSpacing // 将attr添加到attrs中 cellAttrs.append(attr) } } } // 返回准备好的布局 extension YPWaterFallLayout { override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { return cellAttrs } } //设置可滚动区域 extension YPWaterFallLayout { override var collectionViewContentSize : CGSize { return CGSize(width: 0, height: colHeights.max()! + sectionInset.bottom - minimumLineSpacing) } }
mit
bd25ee22aab1dd7b99ae74f0a2664130
30.305882
152
0.632093
4.479798
false
false
false
false
LearningSwift2/LearningApps
SimpleAPIClient/SimpleAPIClient/Photo.swift
1
1390
// // Photo.swift // WebServicesApp // // Created by Phil Wright on 2/22/16. // Copyright © 2016 The Iron Yard. All rights reserved. // import UIKit class Photo { var photoID: String = "" var title: String = "" var urlString: String = "" var dateTaken = NSDate() private let dateFormatter: NSDateFormatter = { let formatter = NSDateFormatter() formatter.dateFormat = "yyyy-MM-dd HH:mm:ss" return formatter }() init(jsonDict: JSONDictionary) { if let photoID = jsonDict["id"] as? String { self.photoID = photoID } else { print("Could not parse photoID") } if let title = jsonDict["title"] as? String { self.title = title } else { print("Could not parse title") } if let photoURLString = jsonDict["url_h"] as? String { self.urlString = photoURLString if let dateString = jsonDict["datetaken"] as? String { if let dateTaken = dateFormatter.dateFromString(dateString) { self.dateTaken = dateTaken } else { print("Could not parse dateTaken") } } else { debugPrint("Could not parse datetaken") } } } }
apache-2.0
12daa045670652c67c3c34d51e36d429
25.226415
77
0.512599
4.839721
false
false
false
false
OatmealCode/Oatmeal
Pod/Classes/Extensions/Swift/Dollar.swift
1
55199
// // ___ ___ __ ___ ________ _________ // _|\ \__|\ \ |\ \|\ \|\ _____\\___ ___\ // |\ ____\ \ \ \ \ \ \ \ \ \__/\|___ \ \_| // \ \ \___|\ \ \ __\ \ \ \ \ \ __\ \ \ \ // \ \_____ \ \ \|\__\_\ \ \ \ \ \_| \ \ \ // \|____|\ \ \____________\ \__\ \__\ \ \__\ // ____\_\ \|____________|\|__|\|__| \|__| // |\___ __\ // \|___|\__\_| // \|__| // // Dollar.swift // $ - A functional tool-belt for Swift Language // // Created by Ankur Patel on 6/3/14. // Copyright (c) 2014 Encore Dev Labs LLC. All rights reserved. // import Foundation public class $ { /// Creates a function that executes passed function only after being called n times. /// /// :param n Number of times after which to call function. /// :param function Function to be called that takes params. /// :return Function that can be called n times after which the callback function is called. public class func after<T, E>(n: Int, function: (T...) -> E) -> ((T...) -> E?) { var counter = n return { (params: T...) -> E? in typealias Function = [T] -> E if --counter <= 0 { let f = unsafeBitCast(function, Function.self) return f(params) } return .None } } /// Creates a function that executes passed function only after being called n times. /// /// :param n Number of times after which to call function. /// :param function Function to be called that does not take any params. /// :return Function that can be called n times after which the callback function is called. public class func after<T>(n: Int, function: () -> T) -> (() -> T?) { let f = self.after(n) { (params: Any?...) -> T in return function() } return { f() } } /// Creates an array of elements from the specified indexes, or keys, of the collection. /// Indexes may be specified as individual arguments or as arrays of indexes. /// /// :param array The array to source from /// :param indexes Get elements from these indexes /// :return New array with elements from the indexes specified. public class func at<T>(array: [T], indexes: Int...) -> [T] { return self.at(array, indexes: indexes) } /// Creates an array of elements from the specified indexes, or keys, of the collection. /// Indexes may be specified as individual arguments or as arrays of indexes. /// /// :param array The array to source from /// :param indexes Get elements from these indexes /// :return New array with elements from the indexes specified. public class func at<T>(array: [T], indexes: [Int]) -> [T] { var result: [T] = [] for index in indexes { result.append(array[index]) } return result } /// Creates a function that, when called, invokes func with the binding of arguments provided. /// /// :param function Function to be bound. /// :param parameters Parameters to be passed into the function when being invoked. /// :return A new function that when called will invoked the passed function with the parameters specified. public class func bind<T, E>(function: (T...) -> E, _ parameters: T...) -> (() -> E) { return { () -> E in typealias Function = [T] -> E let f = unsafeBitCast(function, Function.self) return f(parameters) } } /// Creates an array of elements split into groups the length of size. /// If array can’t be split evenly, the final chunk will be the remaining elements. /// /// :param array to chunk /// :param size size of each chunk /// :return array elements chunked public class func chunk<T>(array: [T], size: Int = 1) -> [[T]] { var result = [[T]]() var chunk = -1 for (index, elem) in array.enumerate() { if index % size == 0 { result.append([T]()) chunk += 1 } result[chunk].append(elem) } return result } /// Creates an array with all nil values removed. /// /// :param array Array to be compacted. /// :return A new array that doesnt have any nil values. public class func compact<T>(array: [T?]) -> [T] { var result: [T] = [] for elem in array { if let val = elem { result.append(val) } } return result } /// Compose two or more functions passing result of the first function /// into the next function until all the functions have been evaluated /// /// :param functions - list of functions /// :return A function that can be called with variadic parameters of values public class func compose<T>(functions: ((T...) -> [T])...) -> ((T...) -> [T]) { typealias Function = [T] -> [T] return { var result = $0 for fun in functions { let f = unsafeBitCast(fun, Function.self) result = f(result) } return result } } /// Compose two or more functions passing result of the first function /// into the next function until all the functions have been evaluated /// /// :param functions - list of functions /// :return A function that can be called with array of values public class func compose<T>(functions: ([T] -> [T])...) -> ([T] -> [T]) { return { var result = $0 for fun in functions { result = fun(result) } return result } } /// Checks if a given value is present in the array. /// /// :param array The array to check against. /// :param value The value to check. /// :return Whether value is in the array. public class func contains<T : Equatable>(array: [T], value: T) -> Bool { return array.contains(value) } /// Create a copy of an array /// /// :param array The array to copy /// :return New copy of array public class func copy<T>(array: [T]) -> [T] { var newArr : [T] = [] for elem in array { newArr.append(elem) } return newArr } /// Cycles through the array indefinetly passing each element into the callback function /// /// :param array to cycle through /// :param callback function to call with the element public class func cycle<T, U>(array: [T], callback: (T) -> (U)) { while true { for elem in array { callback(elem) } } } /// Cycles through the array n times passing each element into the callback function /// /// :param array to cycle through /// :param times Number of times to cycle through the array /// :param callback function to call with the element public class func cycle<T, U>(array: [T], _ times: Int, callback: (T) -> (U)) { var i = 0 while i++ < times { for elem in array { callback(elem) } } } /// Creates an array excluding all values of the provided arrays in order /// /// :param arrays The arrays to difference between. /// :return The difference between the first array and all the remaining arrays from the arrays params. public class func differenceInOrder<T: Equatable>(arrays: [[T]]) -> [T] { return $.reduce(self.rest(arrays), initial: self.first(arrays)!) { (result, arr) -> [T] in return result.filter() { !arr.contains($0) } } } /// Creates an array excluding all values of the provided arrays with or without order /// Without order difference is much faster and at times 100% than difference with order /// /// :param arrays The arrays to difference between. /// :param inOrder Optional Paramter which is true by default /// :return The difference between the first array and all the remaining arrays from the arrays params. public class func difference<T: Hashable>(arrays: [T]..., inOrder: Bool = true) -> [T] { if inOrder { return self.differenceInOrder(arrays) } else { var result : [T] = [] var map : [T: Int] = [T: Int]() let firstArr : [T] = self.first(arrays)! let restArr : [[T]] = self.rest(arrays) as [[T]] for elem in firstArr { if let val = map[elem] { map[elem] = val + 1 } else { map[elem] = 1 } } for arr in restArr { for elem in arr { map.removeValueForKey(elem) } } for (key, count) in map { for _ in 0..<count { result.append(key) } } return result } } /// Call the callback passing each element in the array /// /// :param array The array to iterate over /// :param callback function that gets called with each item in the array /// :return The array passed public class func each<T>(array: [T], callback: (T) -> ()) -> [T] { for elem in array { callback(elem) } return array } /// Call the callback passing index of the element and each element in the array /// /// :param array The array to iterate over /// :param callback function that gets called with each item in the array with its index /// :return The array passed public class func each<T>(array: [T], callback: (Int, T) -> ()) -> [T] { for (index, elem): (Int, T) in array.enumerate() { callback(index, elem) } return array } /// Call the callback on all elements that meet the when condition /// /// :param array The array to check. /// :param when Condition to check before performing callback /// :param callback Check whether element value is true or false. /// :return The array passed public class func each<T>(array: [T], when: (T) -> Bool, callback: (T) -> ()) ->[T] { for elem in array where when(elem) { callback(elem); } return array; } /// Checks if two optionals containing Equatable types are equal. /// /// :param value The first optional to check. /// :param other The second optional to check. /// :return: true if the optionals contain two equal values, or both are nil; false otherwise. public class func equal<T: Equatable>(value: T?, _ other: T?) -> Bool { switch (value, other) { case (.None, .None): return true case (.None, .Some(_)): return false case (.Some(_), .None): return false case (.Some(let unwrappedValue), .Some(let otherUnwrappedValue)): return unwrappedValue == otherUnwrappedValue } } /// Checks if the given callback returns true value for all items in the array. /// /// :param array The array to check. /// :param callback Check whether element value is true or false. /// :return First element from the array. public class func every<T>(array: [T], callback: (T) -> Bool) -> Bool { for elem in array { if !callback(elem) { return false } } return true } /// Returns Factorial of integer /// /// :param num number whose factorial needs to be calculated /// :return factorial public class func factorial(num: Int) -> Int { guard num > 0 else { return 1 } return num * $.factorial(num - 1) } /// Get element from an array at the given index which can be negative /// to find elements from the end of the array /// /// :param array The array to fetch from /// :param index Can be positive or negative to find from end of the array /// :param orElse Default value to use if index is out of bounds /// :return Element fetched from the array or the default value passed in orElse public class func fetch<T>(array: [T], _ index: Int, orElse: T? = .None) -> T! { if index < 0 && -index < array.count { return array[array.count + index] } else if index < array.count { return array[index] } else { return orElse } } /// Fills elements of array with value from start up to, but not including, end. /// /// :param array to fill /// :param elem the element to replace /// :return array elements chunked public class func fill<T>(inout array: [T], withElem elem: T, startIndex: Int = 0, endIndex: Int? = .None) -> [T] { let endIndex = endIndex ?? array.count for (index, _) in array.enumerate() { if index > endIndex { break } if index >= startIndex && index <= endIndex { array[index] = elem } } return array } /// Iterates over elements of an array and returning the first element /// that the callback returns true for. /// /// :param array The array to search for the element in. /// :param callback The callback function to tell whether element is found. /// :return Optional containing either found element or nil. public class func find<T>(array: [T], callback: (T) -> Bool) -> T? { for elem in array { let result = callback(elem) if result { return elem } } return .None } /// This method is like find except that it returns the index of the first element /// that passes the callback check. /// /// :param array The array to search for the element in. /// :param callback Function used to figure out whether element is the same. /// :return First element's index from the array found using the callback. public class func findIndex<T>(array: [T], callback: (T) -> Bool) -> Int? { for (index, elem): (Int, T) in array.enumerate() { if callback(elem) { return index } } return .None } /// This method is like findIndex except that it iterates over elements of the array /// from right to left. /// /// :param array The array to search for the element in. /// :param callback Function used to figure out whether element is the same. /// :return Last element's index from the array found using the callback. public class func findLastIndex<T>(array: [T], callback: (T) -> Bool) -> Int? { let count = array.count for (index, _) in array.enumerate() { let reverseIndex = count - (index + 1) let elem : T = array[reverseIndex] if callback(elem) { return reverseIndex } } return .None } /// Gets the first element in the array. /// /// :param array The array to wrap. /// :return First element from the array. public class func first<T>(array: [T]) -> T? { if array.isEmpty { return .None } else { return array[0] } } /// Gets the second element in the array. /// /// :param array The array to wrap. /// :return Second element from the array. public class func second<T>(array: [T]) -> T? { if array.count < 2 { return .None } else { return array[1] } } /// Gets the third element in the array. /// /// :param array The array to wrap. /// :return Third element from the array. public class func third<T>(array: [T]) -> T? { if array.count < 3 { return .None } else { return array[2] } } /// Flattens a nested array of any depth. /// /// :param array The array to flatten. /// :return Flattened array. public class func flatten<T>(array: [T]) -> [T] { var resultArr: [T] = [] for elem : T in array { if let val = elem as? [T] { resultArr += self.flatten(val) } else { resultArr.append(elem) } } return resultArr } /// Maps a function that converts elements to a list and then concatenates them. /// /// :param array The array to map. /// :return The array with the transformed values concatenated together. public class func flatMap<T, U>(array: [T], f: (T) -> ([U])) -> [U] { return array.map(f).reduce([], combine: +) } /// Maps a function that converts a type to an Optional over an Optional, and then returns a single-level Optional. /// /// :param array The array to map. /// :return The array with the transformed values concatenated together. public class func flatMap<T, U>(value: T?, f: (T) -> (U?)) -> U? { if let unwrapped = value.map(f) { return unwrapped } else { return .None } } /// Returns size of the array /// /// :param array The array to size. /// :return size of the array public class func size<T>(array: [T]) -> Int { return array.count } /// Randomly shuffles the elements of an array. /// /// :param array The array to shuffle. /// :return Shuffled array public class func shuffle<T>(array: [T]) -> [T] { var newArr = self.copy(array) // Implementation of Fisher-Yates shuffle // http://en.wikipedia.org/wiki/Fisher-Yates_Shuffle for index in 0..<array.count { let randIndex = self.random(index) if index != randIndex { Swift.swap(&newArr[index], &newArr[randIndex]) } } return newArr } /// This method returns a dictionary of values in an array mapping to the /// total number of occurrences in the array. /// /// :param array The array to source from. /// :return Dictionary that contains the key generated from the element passed in the function. public class func frequencies<T>(array: [T]) -> [T: Int] { return self.frequencies(array) { $0 } } /// This method returns a dictionary of values in an array mapping to the /// total number of occurrences in the array. If passed a function it returns /// a frequency table of the results of the given function on the arrays elements. /// /// :param array The array to source from. /// :param function The function to get value of the key for each element to group by. /// :return Dictionary that contains the key generated from the element passed in the function. public class func frequencies<T, U: Equatable>(array: [T], function: (T) -> U) -> [U: Int] { var result = [U: Int]() for elem in array { let key = function(elem) if let freq = result[key] { result[key] = freq + 1 } else { result[key] = 1 } } return result } /// GCD function return greatest common denominator /// /// :param first number /// :param second number /// :return Greatest common denominator public class func gcd(var first: Int, var _ second: Int) -> Int { while second != 0 { (first, second) = (second, first % second) } return Swift.abs(first) } /// LCM function return least common multiple /// /// :param first number /// :param second number /// :return Least common multiple public class func lcm(first: Int, _ second: Int) -> Int { return (first / $.gcd(first, second)) * second } /// The identity function. Returns the argument it is given. /// /// :param arg Value to return /// :return Argument that was passed public class func id<T>(arg: T) -> T { return arg } /// Gets the index at which the first occurrence of value is found. /// /// :param array The array to source from. /// :param value Value whose index needs to be found. /// :return Index of the element otherwise returns nil if not found. public class func indexOf<T: Equatable>(array: [T], value: T) -> Int? { return self.findIndex(array) { $0 == value } } /// Gets all but the last element or last n elements of an array. /// /// :param array The array to source from. /// :param numElements The number of elements to ignore in the end. /// :return Array of initial values. public class func initial<T>(array: [T], numElements: Int = 1) -> [T] { var result: [T] = [] if (array.count > numElements && numElements >= 0) { for index in 0..<(array.count - numElements) { result.append(array[index]) } } return result } /// Creates an array of unique values present in all provided arrays. /// /// :param arrays The arrays to perform an intersection on. /// :return Intersection of all arrays passed. public class func intersection<T : Hashable>(arrays: [T]...) -> [T] { var map : [T: Int] = [T: Int]() for arr in arrays { for elem in arr { if let val : Int = map[elem] { map[elem] = val + 1 } else { map[elem] = 1 } } } var result : [T] = [] let count = arrays.count for (key, value) in map { if value == count { result.append(key) } } return result } /// Returns true if i is in range /// /// :param i to check if it is in range /// :param range to check in /// :return true if it is in range otherwise false public class func it<T: Comparable>(i: T, isIn range: Range<T>) -> Bool { return i >= range.startIndex && i < range.endIndex } /// Returns true if i is in interval /// /// :param i to check if it is in interval /// :param interval to check in /// :return true if it is in interval otherwise false public class func it<I : IntervalType>(i: I.Bound, isIn interval: I) -> Bool { return interval.contains(i) } /// Joins the elements in the array to create a concatenated element of the same type. /// /// :param array The array to join the elements of. /// :param separator The separator to join the elements with. /// :return Joined element from the array of elements. public class func join(array: [String], separator: String) -> String { return array.joinWithSeparator(separator) } /// Creates an array of keys given a dictionary. /// /// :param dictionary The dictionary to source from. /// :return Array of keys from dictionary. public class func keys<T, U>(dictionary: [T: U]) -> [T] { var result : [T] = [] for key in dictionary.keys { result.append(key) } return result } /// Gets the last element from the array. /// /// :param array The array to source from. /// :return Last element from the array. public class func last<T>(array: [T]) -> T? { if array.isEmpty { return .None } else { return array[array.count - 1] } } /// Gets the index at which the last occurrence of value is found. /// /// param: array:: The array to source from. /// :param value The value whose last index needs to be found. /// :return Last index of element if found otherwise returns nil. public class func lastIndexOf<T: Equatable>(array: [T], value: T) -> Int? { return self.findLastIndex(array) { $0 == value } } /// Maps each element to new value based on the map function passed /// /// :param collection The collection to source from /// :param transform The mapping function /// :return Array of elements mapped using the map function public class func map<T : CollectionType, E>(collection: T, transform: (T.Generator.Element) -> E) -> [E] { return collection.map(transform) } /// Maps each element to new value based on the map function passed /// /// :param sequence The sequence to source from /// :param transform The mapping function /// :return Array of elements mapped using the map function public class func map<T : SequenceType, E>(sequence: T, transform: (T.Generator.Element) -> E) -> [E] { return sequence.map(transform) } /// Retrieves the maximum value in an array. /// /// :param array The array to source from. /// :return Maximum element in array. public class func max<T : Comparable>(array: [T]) -> T? { if var maxVal = array.first { for elem in array { if maxVal < elem { maxVal = elem } } return maxVal } return .None } /// Get memoized function to improve performance /// /// :param function The function to memoize. /// :return Memoized function public class func memoize<T: Hashable, U>(function: ((T -> U), T) -> U) -> (T -> U) { var cache = [T: U]() var funcRef: (T -> U)! funcRef = { (param : T) -> U in if let cacheVal = cache[param] { return cacheVal } else { cache[param] = function(funcRef, param) return cache[param]! } } return funcRef } /// Merge dictionaries together, later dictionaries overiding earlier values of keys. /// /// :param dictionaries The dictionaries to source from. /// :return Merged dictionary with all of its keys and values. public class func merge<T, U>(dictionaries: [T: U]...) -> [T: U] { var result = [T: U]() for dict in dictionaries { for (key, value) in dict { result[key] = value } } return result } /// Merge arrays together in the supplied order. /// /// :param arrays The arrays to source from. /// :return Array with all values merged, including duplicates. public class func merge<T>(arrays: [T]...) -> [T] { var result = [T]() for arr in arrays { result += arr } return result } /// Retrieves the minimum value in an array. /// /// :param array The array to source from. /// :return Minimum value from array. public class func min<T : Comparable>(array: [T]) -> T? { if var minVal = array.first { for elem in array { if minVal > elem { minVal = elem } } return minVal } return .None } /// A no-operation function. /// /// :return nil. public class func noop() -> () { } /// Gets the number of seconds that have elapsed since the Unix epoch (1 January 1970 00:00:00 UTC). /// /// :return number of seconds as double public class func now() -> NSTimeInterval { return NSDate().timeIntervalSince1970 } /// Creates a shallow clone of a dictionary excluding the specified keys. /// /// :param dictionary The dictionary to source from. /// :param keys The keys to omit from returning dictionary. /// :return Dictionary with the keys specified omitted. public class func omit<T, U>(dictionary: [T: U], keys: T...) -> [T: U] { var result : [T: U] = [T: U]() for (key, value) in dictionary { if !self.contains(keys, value: key) { result[key] = value } } return result } /// Get a wrapper function that executes the passed function only once /// /// :param function That takes variadic arguments and return nil or some value /// :return Wrapper function that executes the passed function only once /// Consecutive calls will return the value returned when calling the function first time public class func once<T, U>(function: (T...) -> U) -> (T...) -> U { var result: U? let onceFunc = { (params: T...) -> U in typealias Function = [T] -> U if let returnVal = result { return returnVal } else { let f = unsafeBitCast(function, Function.self) result = f(params) return result! } } return onceFunc } /// Get a wrapper function that executes the passed function only once /// /// :param function That takes variadic arguments and return nil or some value /// :return Wrapper function that executes the passed function only once /// Consecutive calls will return the value returned when calling the function first time public class func once<U>(function: () -> U) -> () -> U { var result: U? let onceFunc = { () -> U in if let returnVal = result { return returnVal } else { result = function() return result! } } return onceFunc } /// Get the first object in the wrapper object. /// /// :param array The array to wrap. /// :return First element from the array. public class func partial<T, E> (function: (T...) -> E, _ parameters: T...) -> ((T...) -> E) { return { (params: T...) -> E in typealias Function = [T] -> E let f = unsafeBitCast(function, Function.self) return f(parameters + params) } } /// Produces an array of arrays, each containing n elements, each offset by step. /// If the final partition is not n elements long it is dropped. /// /// :param array The array to partition. /// :param n The number of elements in each partition. /// :param step The number of elements to progress between each partition. Set to n if not supplied. /// :return Array partitioned into n element arrays, starting step elements apart. public class func partition<T>(array: [T], var n: Int, var step: Int? = .None) -> [[T]] { var result = [[T]]() if step == .None { step = n } // If no step is supplied move n each step. if step < 1 { step = 1 } // Less than 1 results in an infinite loop. if n < 1 { n = 0 } // Allow 0 if user wants [[],[],[]] for some reason. if n > array.count { return [[]] } for i in self.range(from: 0, through: array.count - n, incrementBy: step!) { result.append(Array(array[i..<(i+n)] as ArraySlice<T>)) } return result } /// Produces an array of arrays, each containing n elements, each offset by step. /// /// :param array The array to partition. /// :param n The number of elements in each partition. /// :param step The number of elements to progress between each partition. Set to n if not supplied. /// :param pad An array of elements to pad the last partition if it is not long enough to /// contain n elements. If nil is passed or there are not enough pad elements /// the last partition may less than n elements long. /// :return Array partitioned into n element arrays, starting step elements apart. public class func partition<T>(var array: [T], var n: Int, var step: Int? = .None, pad: [T]?) -> [[T]] { var result : [[T]] = [] if step == .None { step = n } // If no step is supplied move n each step. if step < 1 { step = 1 } // Less than 1 results in an infinite loop. if n < 1 { n = 0 } // Allow 0 if user wants [[],[],[]] for some reason. for i in self.range(from: 0, to: array.count, incrementBy: step!) { var end = i + n if end > array.count { end = array.count } result.append(Array(array[i..<end] as ArraySlice<T>)) if end != i+n { break } } if let padding = pad { let remain = array.count % n let end = padding.count > remain ? remain : padding.count result[result.count - 1] += Array(padding[0..<end] as ArraySlice<T>) } return result } /// Produces an array of arrays, each containing n elements, each offset by step. /// /// :param array The array to partition. /// :param n The number of elements in each partition. /// :param step The number of elements to progress between each partition. Set to n if not supplied. /// :return Array partitioned into n element arrays, starting step elements apart. public class func partitionAll<T>(array: [T], var n: Int, var step: Int? = .None) -> [[T]] { var result = [[T]]() if step == .None { step = n } // If no step is supplied move n each step. if step < 1 { step = 1 } // Less than 1 results in an infinite loop. if n < 1 { n = 0 } // Allow 0 if user wants [[],[],[]] for some reason. for i in self.range(from: 0, to: array.count, incrementBy: step!) { var end = i + n if end > array.count { end = array.count } result.append(Array(array[i..<end] as ArraySlice<T>)) } return result } /// Applies function to each element in array, splitting it each time function returns a new value. /// /// :param array The array to partition. /// :param function Function which takes an element and produces an equatable result. /// :return Array partitioned in order, splitting via results of function. public class func partitionBy<T, U: Equatable>(array: [T], function: (T) -> U) -> [[T]] { var result = [[T]]() var lastValue: U? = .None for item in array { let value = function(item) if let lastValue = lastValue where value == lastValue { result[result.count-1].append(item) } else { result.append([item]) lastValue = value } } return result } /// Creates a shallow clone of a dictionary composed of the specified keys. /// /// :param dictionary The dictionary to source from. /// :param keys The keys to pick values from. /// :return Dictionary with the key and values picked from the keys specified. public class func pick<T, U>(dictionary: [T: U], keys: T...) -> [T: U] { var result : [T: U] = [T: U]() for key in keys { result[key] = dictionary[key] } return result } /// Retrieves the value of a specified property from all elements in the array. /// /// :param array The array to source from. /// :param value The property on object to pull out value from. /// :return Array of values from array of objects with property of value. public class func pluck<T, E>(array: [[T: E]], value: T) -> [E] { var result : [E] = [] for obj in array { if let val = obj[value] { result.append(val) } } return result } /// Removes all provided values from the given array. /// /// :param array The array to source from. /// :return Array with values pulled out. public class func pull<T : Equatable>(array: [T], values: T...) -> [T] { return self.pull(array, values: values) } /// Removes all provided values from the given array. /// /// :param array The array to source from. /// :param values The values to remove. /// :return Array with values pulled out. public class func pull<T : Equatable>(array: [T], values: [T]) -> [T] { return array.filter { !self.contains(values, value: $0) } } /// Removes all provided values from the given array at the given indices /// /// :param array The array to source from. /// :param values The indices to remove from. /// :return Array with values pulled out. public class func pullAt<T : Equatable>(array: [T], indices: Int...) -> [T] { var elemToRemove = [T]() for index in indices { elemToRemove.append(array[index]) } return $.pull(array, values: elemToRemove) } /// Returns random number from 0 upto but not including upperBound /// /// :return Random number public class func random(upperBound: Int) -> Int { return Int(arc4random_uniform(UInt32(upperBound))) } /// Creates an array of numbers (positive and/or negative) progressing from start up to but not including end. /// /// :param endVal End value of range. /// :return Array of elements based on the sequence starting from 0 to endVal and incremented by 1. public class func range<T : Strideable where T : IntegerLiteralConvertible>(endVal: T) -> [T] { return self.range(from: 0, to: endVal) } /// Creates an array of numbers (positive and/or negative) progressing from start up to but not including end. /// /// :param from Start value of range /// :param to End value of range /// :return Array of elements based on the sequence that is incremented by 1 public class func range<T : Strideable where T.Stride : IntegerLiteralConvertible>(from startVal: T, to endVal: T) -> [T] { return self.range(from: startVal, to: endVal, incrementBy: 1) } /// Creates an array of numbers (positive and/or negative) progressing from start up to but not including end. /// /// :param from Start value of range. /// :param to End value of range. /// :param incrementBy Increment sequence by. /// :return Array of elements based on the sequence. public class func range<T : Strideable>(from startVal: T, to endVal: T, incrementBy: T.Stride) -> [T] { let range = startVal.stride(to: endVal, by: incrementBy) return self.sequence(range) } /// Creates an array of numbers (positive and/or negative) progressing from start up to but not including end. /// /// :param from Start value of range /// :param through End value of range /// :return Array of elements based on the sequence that is incremented by 1 public class func range<T : Strideable where T.Stride : IntegerLiteralConvertible>(from startVal: T, through endVal: T) -> [T] { return self.range(from: startVal, to: endVal + 1, incrementBy: 1) } /// Creates an array of numbers (positive and/or negative) progressing from start up to but not including end. /// /// :param from Start value of range. /// :param through End value of range. /// :param incrementBy Increment sequence by. /// :return Array of elements based on the sequence. public class func range<T : Strideable>(from startVal: T, through endVal: T, incrementBy: T.Stride) -> [T] { return self.range(from: startVal, to: endVal + 1, incrementBy: incrementBy) } /// Reduce function that will resolve to one value after performing combine function on all elements /// /// :param array The array to source from. /// :param initial Initial value to seed the reduce function with /// :param combine Function that will combine the passed value with element in the array /// :return The result of reducing all of the elements in the array into one value public class func reduce<U, T>(array: [T], initial: U, combine: (U, T) -> U) -> U { return array.reduce(initial, combine: combine) } /// Creates an array of an arbitrary sequence. Especially useful with builtin ranges. /// /// :param seq The sequence to generate from. /// :return Array of elements generated from the sequence. public class func sequence<S : SequenceType>(seq: S) -> [S.Generator.Element] { return Array<S.Generator.Element>(seq) } /// Removes all elements from an array that the callback returns true. /// /// :param array The array to wrap. /// :param callback Remove elements for which callback returns true. /// :return Array with elements filtered out. public class func remove<T>(array: [T], callback: (T) -> Bool) -> [T] { return array.filter { !callback($0) } } /// Removes an element from an array. /// /// :param array The array to source from. /// :param element Element that is to be removed /// :return Array with element removed. public class func remove<T: Equatable>(array: [T], value: T) -> [T] { return self.remove(array, callback: {$0 == value}) } /// The opposite of initial this method gets all but the first element or first n elements of an array. /// /// :param array The array to source from. /// :param numElements The number of elements to exclude from the beginning. /// :return The rest of the elements. public class func rest<T>(array: [T], numElements: Int = 1) -> [T] { var result : [T] = [] if (numElements < array.count && numElements >= 0) { for index in numElements..<array.count { result.append(array[index]) } } return result } /// Returns a sample from the array. /// /// :param array The array to sample from. /// :return Random element from array. public class func sample<T>(array: [T]) -> T { return array[self.random(array.count)] } /// Slices the array based on the start and end position. If an end position is not specified it will slice till the end of the array. /// /// :param array The array to slice. /// :param start Start index. /// :param end End index. /// :return First element from the array. public class func slice<T>(array: [T], start: Int, end: Int = 0) -> [T] { var uend = end; if (uend == 0) { uend = array.count; } if end > array.count || start > array.count || uend < start { return []; } else { return Array(array[start..<uend]); } } /// Gives the smallest index at which a value should be inserted into a given the array is sorted. /// /// :param array The array to source from. /// :param value Find sorted index of this value. /// :return Index of where the elemnt should be inserted. public class func sortedIndex<T : Comparable>(array: [T], value: T) -> Int { for (index, elem) in array.enumerate() { if elem > value { return index } } return array.count } /// Invokes interceptor with the object and then returns object. /// /// :param object Object to tap into. /// :param function Callback function to invoke. /// :return Returns the object back. public class func tap<T>(object: T, function: (T) -> ()) -> T { function(object) return object } /// Call a function n times and also passes the index. If a value is returned /// in the function then the times method will return an array of those values. /// /// :param n Number of times to call function. /// :param function The function to be called every time. /// :return Values returned from callback function. public class func times<T>(n: Int, function: () -> T) -> [T] { return self.times(n) { (index: Int) -> T in return function() } } /// Call a function n times and also passes the index. If a value is returned /// in the function then the times method will return an array of those values. /// /// :param n Number of times to call function. /// :param function The function to be called every time. public class func times(n: Int, function: () -> ()) { self.times(n) { (index: Int) -> () in function() } } /// Call a function n times and also passes the index. If a value is returned /// in the function then the times method will return an array of those values. /// /// :param n Number of times to call function. /// :param function The function to be called every time that takes index. /// :return Values returned from callback function. public class func times<T>(n: Int, function: (Int) -> T) -> [T] { var result : [T] = [] for index in (0..<n) { result.append(function(index)) } return result } /// Creates an array of unique values, in order, of the provided arrays. /// /// :param arrays The arrays to perform union on. /// :return Resulting array after union. public class func union<T : Hashable>(arrays: [T]...) -> [T] { var result : [T] = [] for arr in arrays { result += arr } return self.uniq(result) } /// Creates a duplicate-value-free version of an array. /// /// :param array The array to source from. /// :return An array with unique values. public class func uniq<T : Hashable>(array: [T]) -> [T] { var result: [T] = [] var map: [T: Bool] = [T: Bool]() for elem in array { if map[elem] == .None { result.append(elem) } map[elem] = true } return result } /// Create a duplicate-value-free version of an array based on the condition. /// Uses the last value generated by the condition function /// /// :param array The array to source from. /// :param condition Called per iteration /// :return An array with unique values. public class func uniq<T: Hashable, U: Hashable>(array: [T], by condition: (T) -> U) -> [T] { var result: [T] = [] var map : [U: Bool] = [U: Bool]() for elem in array { let val = condition(elem) if map[val] == .None { result.append(elem) } map[val] = true } return result } /// Creates an array of values of a given dictionary. /// /// :param dictionary The dictionary to source from. /// :return An array of values from the dictionary. public class func values<T, U>(dictionary: [T: U]) -> [U] { var result : [U] = [] for value in dictionary.values { result.append(value) } return result } /// Creates an array excluding all provided values. /// /// :param array The array to source from. /// :param values Values to exclude. /// :return Array excluding provided values. public class func without<T : Equatable>(array: [T], values: T...) -> [T] { return self.pull(array, values: values) } /// Creates an array that is the symmetric difference of the provided arrays. /// /// :param arrays The arrays to perform xor on in order. /// :return Resulting array after performing xor. public class func xor<T : Hashable>(arrays: [T]...) -> [T] { var map : [T: Bool] = [T: Bool]() for arr in arrays { for elem in arr { map[elem] = !(map[elem] ?? false) } } var result : [T] = [] for (key, value) in map { if value { result.append(key) } } return result } /// Creates an array of grouped elements, the first of which contains the first elements /// of the given arrays. /// /// :param arrays The arrays to be grouped. /// :return An array of grouped elements. public class func zip<T>(arrays: [T]...) -> [[T]] { var result: [[T]] = [] for _ in self.first(arrays)! as [T] { result.append([] as [T]) } for (_, array) in arrays.enumerate() { for (elemIndex, elem): (Int, T) in array.enumerate() { result[elemIndex].append(elem) } } return result } /// Creates an object composed from arrays of keys and values. /// /// :param keys The array of keys. /// :param values The array of values. /// :return Dictionary based on the keys and values passed in order. public class func zipObject<T, E>(keys: [T], values: [E]) -> [T: E] { var result = [T: E]() for (index, key) in keys.enumerate() { result[key] = values[index] } return result } /// Returns the collection wrapped in the chain object /// /// :param collection of elements /// :return Chain object public class func chain<T>(collection: [T]) -> Chain<T> { return Chain(collection) } } // ________ ___ ___ ________ ___ ________ // |\ ____\|\ \|\ \|\ __ \|\ \|\ ___ \ // \ \ \___|\ \ \\\ \ \ \|\ \ \ \ \ \\ \ \ // \ \ \ \ \ __ \ \ __ \ \ \ \ \\ \ \ // \ \ \____\ \ \ \ \ \ \ \ \ \ \ \ \\ \ \ // \ \_______\ \__\ \__\ \__\ \__\ \__\ \__\\ \__\ // \|_______|\|__|\|__|\|__|\|__|\|__|\|__| \|__| // public class Chain<C> { private var result: Wrapper<[C]> private var funcQueue: [Wrapper<[C]> -> Wrapper<[C]>] = [] public var value: [C] { get { var result: Wrapper<[C]> = self.result for function in self.funcQueue { result = function(result) } return result.value } } /// Initializer of the wrapper object for chaining. /// /// :param array The array to wrap. public init(_ collection: [C]) { self.result = Wrapper(collection) } /// Get the first object in the wrapper object. /// /// :return First element from the array. public func first() -> C? { return $.first(self.value) } /// Get the second object in the wrapper object. /// /// :return Second element from the array. public func second() -> C? { return $.first(self.value) } /// Get the third object in the wrapper object. /// /// :return Third element from the array. public func third() -> C? { return $.first(self.value) } /// Flattens nested array. /// /// :return The wrapper object. public func flatten() -> Chain { return self.queue { return Wrapper($.flatten($0.value)) } } /// Keeps all the elements except last one. /// /// :return The wrapper object. public func initial() -> Chain { return self.initial(1) } /// Keeps all the elements except last n elements. /// /// :param numElements Number of items to remove from the end of the array. /// :return The wrapper object. public func initial(numElements: Int) -> Chain { return self.queue { return Wrapper($.initial($0.value, numElements: numElements)) } } /// Maps elements to new elements. /// /// :param function Function to map. /// :return The wrapper object. public func map(function: C -> C) -> Chain { return self.queue { var result: [C] = [] for elem: C in $0.value { result.append(function(elem)) } return Wrapper(result) } } /// Get the first object in the wrapper object. /// /// :param array The array to wrap. /// :return The wrapper object. public func map(function: (Int, C) -> C) -> Chain { return self.queue { var result: [C] = [] for (index, elem) in $0.value.enumerate() { result.append(function(index, elem)) } return Wrapper(result) } } /// Get the first object in the wrapper object. /// /// :param array The array to wrap. /// :return The wrapper object. public func each(function: (C) -> ()) -> Chain { return self.queue { for elem in $0.value { function(elem) } return $0 } } /// Get the first object in the wrapper object. /// /// :param array The array to wrap. /// :return The wrapper object. public func each(function: (Int, C) -> ()) -> Chain { return self.queue { for (index, elem) in $0.value.enumerate() { function(index, elem) } return $0 } } /// Filter elements based on the function passed. /// /// :param function Function to tell whether to keep an element or remove. /// :return The wrapper object. public func filter(function: (C) -> Bool) -> Chain { return self.queue { return Wrapper(($0.value).filter(function)) } } /// Returns if all elements in array are true based on the passed function. /// /// :param function Function to tell whether element value is true or false. /// :return Whether all elements are true according to func function. public func all(function: (C) -> Bool) -> Bool { return $.every(self.value, callback: function) } /// Returns if any element in array is true based on the passed function. /// /// :param function Function to tell whether element value is true or false. /// :return Whether any one element is true according to func function in the array. public func any(function: (C) -> Bool) -> Bool { let resultArr = self.value for elem in resultArr { if function(elem) { return true } } return false } /// Returns size of the array /// /// :return The wrapper object. public func size() -> Int { return self.value.count } /// Slice the array into smaller size based on start and end value. /// /// :param start Start index to start slicing from. /// :param end End index to stop slicing to and not including element at that index. /// :return The wrapper object. public func slice(start: Int, end: Int = 0) -> Chain { return self.queue { return Wrapper($.slice($0.value, start: start, end: end)) } } private func queue(function: Wrapper<[C]> -> Wrapper<[C]>) -> Chain { funcQueue.append(function) return self } } private struct Wrapper<V> { let value: V init(_ value: V) { self.value = value } }
mit
90c3ae8d3ff1e2edbd5249f9f951f7fb
35.627074
138
0.558309
4.309909
false
false
false
false
zach-freeman/swift-localview
localview/FlickrApiUtils.swift
1
4152
// // FlickrApiUtils.swift // localview // // Created by Zach Freeman on 10/7/15. // Copyright © 2021 sparkwing. All rights reserved. // import UIKit import SwiftyJSON open class FlickrApiUtils { public enum PhotoFetchState: Int { case photoListNotFetched case photoListFetched case photosNotFetched case photosFetched } public enum FlickrPhotoSize: Int { case photoSizeUnknown case photoSizeCollectionIconLarge case photoSizeBuddyIcon case photoSizeSmallSquare75 case photoSizeLargeSquare150 case photoSizeThumbnail100 case photoSizeSmall240 case photoSizeSmall320 case photoSizeMedium500 case photoSizeMedium640 case photoSizeMedium800 case photoSizeLarge1024 case photoSizeLarge1600 case photoSizeLarge2048 case photoSizeOriginal case photoSizeVideoOriginal case photoSizeVideoHDMP4 case photoSizeVideoSiteMP4 case photoSizeVideoMobileMP4 case photoSizeVideoPlayer } class func setupPhotoListWithJSON(_ json: JSON) -> [FlickrPhoto] { var flickrPhotos: [FlickrPhoto] = [] let thePhotoArray: JSON! = json["photos"]["photo"] if thePhotoArray.count > 0 { for (_, flickrPhotoDictionary) in thePhotoArray { let flickrPhoto: FlickrPhoto = FlickrPhoto() flickrPhoto.title = flickrPhotoDictionary["title"].string flickrPhoto.bigImageUrl = FlickrApiUtils .photoUrlForSize(FlickrConstants.kBigImageSize, photoDictionary: flickrPhotoDictionary) flickrPhoto.smallImageUrl = FlickrApiUtils .photoUrlForSize(FlickrConstants.kSmallImageSize, photoDictionary: flickrPhotoDictionary) flickrPhoto.photoSetId = flickrPhotoDictionary["id"].string flickrPhotos.append(flickrPhoto) } } return flickrPhotos } class func photoUrlForSize(_ size: FlickrPhotoSize, photoDictionary: JSON!) -> URL { let photoId = photoDictionary["id"].string! let server = photoDictionary["server"].string! let farm: String? = photoDictionary["farm"].string let secret = photoDictionary["secret"].string! let photoUrl = photoUrlForSize(size, photoId: photoId, server: server, secret: secret, farm: farm) return photoUrl } class func photoUrlForSize(_ size: FlickrPhotoSize, photoId: String, server: String, secret: String, farm: String?) -> URL { // https://farm{farm-id}.static.flickr.com/{server-id}/{id}_{secret}_[mstb].jpg // https://farm{farm-id}.static.flickr.com/{server-id}/{id}_{secret}.jpg var photoUrlString = "https://" if farm != nil { photoUrlString += "farm\(farm!)." } let sizeSuffix = suffixForSize(size) assert(server.utf8.count > 0, "Server attribute is required") assert(secret.utf8.count > 0, "Secret attribute is required") assert(photoId.utf8.count > 0, "Id attribute is required") photoUrlString += FlickrConstants.kFlickrPhotoSourceHost + "/\(server)/\(photoId)_\(secret)_\(sizeSuffix).jpg" return URL(string: photoUrlString)! } class func suffixForSize(_ size: FlickrPhotoSize) -> String { let suffixArray: [String] = ["", "collectionIconLarge", "buddyIcon", "s", "q", "t", "m", "n", "", "z", "c", "b", "h", "k", "o", "", "", "", "", ""] return suffixArray[size.rawValue] } }
mit
28daf430d68c334e1ac1dfd5aa9db3a9
35.734513
118
0.553842
5.22796
false
false
false
false
RocketChat/Rocket.Chat.iOS
Rocket.Chat/Controllers/Preferences/Notifications/NotificationsPreferencesViewModel.swift
1
11648
// // NotificationsPreferencesViewModel.swift // Rocket.Chat // // Created by Artur Rymarz on 05.03.2018. // Copyright © 2018 Rocket.Chat. All rights reserved. // import Foundation enum NotificationCellType: String { case `switch` = "NotificationsSwitchCell" case list = "NotificationsChooseCell" } protocol NotificationSettingModel { var type: NotificationCellType { get } } final class NotificationsPreferencesViewModel { var isModelBinded = false var currentPreferences: NotificationPreferences? { didSet { guard !isModelBinded else { checkIfSaveButtonShouldBeEnabled() return } isModelBinded = true enableModel.value.bind { [weak self] _ in self?.checkIfSaveButtonShouldBeEnabled() } counterModel.value.bind { [weak self] _ in self?.checkIfSaveButtonShouldBeEnabled() } desktopAlertsModel.value.bind { [weak self] _ in self?.checkIfSaveButtonShouldBeEnabled() } desktopAudioModel.value.bind { [weak self] _ in self?.checkIfSaveButtonShouldBeEnabled() } desktopSoundModel.value.bind { [weak self] _ in self?.checkIfSaveButtonShouldBeEnabled() } desktopDurationModel.value.bind { [weak self] _ in self?.checkIfSaveButtonShouldBeEnabled() } mobileAlertsModel.value.bind { [weak self] _ in self?.checkIfSaveButtonShouldBeEnabled() } mailAlertsModel.value.bind { [weak self] _ in self?.checkIfSaveButtonShouldBeEnabled() } } } internal var title: String { return localized("myaccount.settings.notifications.title") } internal var saveSuccessTitle: String { return localized("alert.update_notifications_preferences_success.title") } internal var saveButtonTitle: String { return localized("myaccount.settings.notifications.save") } internal var notificationPreferences: NotificationPreferences { return NotificationPreferences( desktopNotifications: desktopAlertsModel.value.value, disableNotifications: !enableModel.value.value, emailNotifications: mailAlertsModel.value.value, audioNotificationValue: desktopSoundModel.value.value, desktopNotificationDuration: desktopDurationModel.value.value, audioNotifications: desktopAudioModel.value.value, hideUnreadStatus: !counterModel.value.value, mobilePushNotifications: mobileAlertsModel.value.value ) } internal var isSaveButtonEnabled = Dynamic(false) internal var channelName = "channel" internal let enableModel = NotificationsSwitchCell.SettingModel( value: Dynamic(false), type: .switch, title: localized("myaccount.settings.notifications.receive.title") ) internal let counterModel = NotificationsSwitchCell.SettingModel( value: Dynamic(false), type: .switch, title: localized("myaccount.settings.notifications.show.title") ) internal let desktopAlertsModel = NotificationsChooseCell.SettingModel( value: Dynamic(SubscriptionNotificationsStatus.default), options: SubscriptionNotificationsStatus.allCases, type: .list, title: localized("myaccount.settings.notifications.inapp.alerts"), pickerVisible: Dynamic(false) ) internal let desktopAudioModel = NotificationsChooseCell.SettingModel( value: Dynamic(SubscriptionNotificationsStatus.default), options: SubscriptionNotificationsStatus.allCases, type: .list, title: localized("myaccount.settings.notifications.desktop.audio"), pickerVisible: Dynamic(false) ) internal let desktopSoundModel = NotificationsChooseCell.SettingModel( value: Dynamic(SubscriptionNotificationsAudioValue.default), options: SubscriptionNotificationsAudioValue.allCases, type: .list, title: localized("myaccount.settings.notifications.desktop.sound"), pickerVisible: Dynamic(false) ) internal let desktopDurationModel = NotificationsChooseCell.SettingModel( value: Dynamic(0), options: [0, 1, 2, 3, 4, 5], type: .list, title: localized("myaccount.settings.notifications.desktop.duration"), pickerVisible: Dynamic(false) ) internal let mobileAlertsModel = NotificationsChooseCell.SettingModel( value: Dynamic(SubscriptionNotificationsStatus.default), options: SubscriptionNotificationsStatus.allCases, type: .list, title: localized("myaccount.settings.notifications.mobile.alerts"), pickerVisible: Dynamic(false) ) internal let mailAlertsModel = NotificationsChooseCell.SettingModel( value: Dynamic(SubscriptionNotificationsStatus.default), options: SubscriptionNotificationsStatus.allCases, type: .list, title: localized("myaccount.settings.notifications.email.alerts"), pickerVisible: Dynamic(false) ) private typealias TableSection = (header: String?, footer: String?, elements: [NotificationSettingModel]) private lazy var alwaysActiveSections: [TableSection] = [ (header: nil, footer: String(format: localized("myaccount.settings.notifications.receive.footer"), channelName), [enableModel]), (header: nil, footer: localized("myaccount.settings.notifications.show.footer"), [counterModel]) ] private lazy var conditionallyActiveSections: [TableSection] = [ (header: localized("myaccount.settings.notifications.inapp"), footer: localized("myaccount.settings.notifications.inapp.footer"), [desktopAlertsModel]), (header: localized("myaccount.settings.notifications.mobile"), footer: localized("myaccount.settings.notifications.mobile.footer"), [mobileAlertsModel]), (header: localized("myaccount.settings.notifications.desktop"), footer: nil, [desktopAudioModel, desktopSoundModel, desktopDurationModel]), (header: localized("myaccount.settings.notifications.mail"), footer: nil, [mailAlertsModel]) ] // These variables help in row animation private var lastEnableState = false private var currentEnableState: Bool { return enableModel.value.value } private var settingsCells: [TableSection] { lastEnableState = currentEnableState if !enableModel.value.value { return alwaysActiveSections } else { return alwaysActiveSections + conditionallyActiveSections } } internal func numberOfSections() -> Int { return settingsCells.count } internal func numberOfRows(in section: Int) -> Int { return settingsCells[section].elements.count } internal func titleForHeader(in section: Int) -> String? { return settingsCells[section].header } internal func titleForFooter(in section: Int) -> String? { return settingsCells[section].footer } internal func settingModel(for indexPath: IndexPath) -> NotificationSettingModel { return settingsCells[indexPath.section].elements[indexPath.row] } internal func openPicker(for indexPath: IndexPath) { for section in 0..<settingsCells.count { let elements = settingsCells[section].elements for row in 0..<elements.count { setPickerVisible(indexPath.section == section && indexPath.row == row, for: elements[row]) } } } internal func checkIfSaveButtonShouldBeEnabled() { guard let currentPreferences = currentPreferences else { isSaveButtonEnabled.value = false return } isSaveButtonEnabled.value = enableModel.value.value == currentPreferences.disableNotifications || counterModel.value.value == currentPreferences.hideUnreadStatus || desktopAlertsModel.value.value != currentPreferences.desktopNotifications || desktopAudioModel.value.value != currentPreferences.audioNotifications || desktopSoundModel.value.value != currentPreferences.audioNotificationValue || desktopDurationModel.value.value != currentPreferences.desktopNotificationDuration || mobileAlertsModel.value.value != currentPreferences.mobilePushNotifications || mailAlertsModel.value.value != currentPreferences.emailNotifications } internal func updateModel(subscription: Subscription?) { guard let subscription = subscription else { return } channelName = AuthSettingsManager.settings?.useUserRealName ?? false ? subscription.fname : subscription.name lastEnableState = !subscription.disableNotifications enableModel.value.value = !subscription.disableNotifications counterModel.value.value = !subscription.hideUnreadStatus desktopAlertsModel.value.value = subscription.desktopNotifications desktopAudioModel.value.value = subscription.audioNotifications desktopSoundModel.value.value = subscription.audioNotificationValue desktopDurationModel.value.value = subscription.desktopNotificationDuration mobileAlertsModel.value.value = subscription.mobilePushNotifications mailAlertsModel.value.value = subscription.emailNotifications } internal func updateCurrentPreferences() { currentPreferences = NotificationPreferences( desktopNotifications: desktopAlertsModel.value.value, disableNotifications: !enableModel.value.value, emailNotifications: mailAlertsModel.value.value, audioNotificationValue: desktopSoundModel.value.value, desktopNotificationDuration: desktopDurationModel.value.value, audioNotifications: desktopAudioModel.value.value, hideUnreadStatus: !counterModel.value.value, mobilePushNotifications: mobileAlertsModel.value.value ) } private func setPickerVisible(_ visible: Bool, for cellModel: NotificationSettingModel) { if let model = cellModel as? NotificationsChooseCell.SettingModel<SubscriptionNotificationsStatus> { model.pickerVisible.value = visible ? !model.pickerVisible.value : false } else if let model = cellModel as? NotificationsChooseCell.SettingModel<SubscriptionNotificationsAudioValue> { model.pickerVisible.value = visible ? !model.pickerVisible.value : false } else if let model = cellModel as? NotificationsChooseCell.SettingModel<Int> { model.pickerVisible.value = visible ? !model.pickerVisible.value : false } } internal func tableUpdatesAfterStateChange() -> (insertions: IndexSet, deletions: IndexSet) { guard lastEnableState != currentEnableState else { return (insertions: IndexSet(), deletions: IndexSet()) } var indexSetForConditionallyActiveSections = IndexSet() for section in conditionallyActiveSections.startIndex..<conditionallyActiveSections.endIndex { indexSetForConditionallyActiveSections.insert(section + alwaysActiveSections.count) } if currentEnableState { return (insertions: indexSetForConditionallyActiveSections, deletions: IndexSet()) } else { return (insertions: IndexSet(), deletions: indexSetForConditionallyActiveSections) } } }
mit
67280d8483f8f4d8ddaa8e446d2d3b8b
40.010563
161
0.692796
5.130837
false
false
false
false
rsmoz/swift-corelibs-foundation
Foundation/NSCFString.swift
1
8067
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // import CoreFoundation internal class _NSCFString : NSMutableString { required init(characters: UnsafePointer<unichar>, length: Int) { fatalError() } required init?(coder aDecoder: NSCoder) { fatalError() } required init(extendedGraphemeClusterLiteral value: StaticString) { fatalError() } required init(stringLiteral value: StaticString) { fatalError() } required init(capacity: Int) { fatalError() } required init(string aString: String) { fatalError() } deinit { _CFDeinit(self) _CFZeroUnsafeIvars(&_storage) } override var length: Int { return CFStringGetLength(unsafeBitCast(self, CFStringRef.self)) } override func characterAtIndex(index: Int) -> unichar { return CFStringGetCharacterAtIndex(unsafeBitCast(self, CFStringRef.self), index) } override func replaceCharactersInRange(range: NSRange, withString aString: String) { CFStringReplace(unsafeBitCast(self, CFMutableStringRef.self), CFRangeMake(range.location, range.length), aString._cfObject) } } internal final class _NSCFConstantString : _NSCFString { internal var _ptr : UnsafePointer<UInt8> { get { let ptr = unsafeAddressOf(self) + sizeof(COpaquePointer) + sizeof(Int32) + sizeof(Int32) + sizeof(_CFInfo) return UnsafePointer<UnsafePointer<UInt8>>(ptr).memory } } internal var _length : UInt32 { get { let offset = sizeof(COpaquePointer) + sizeof(Int32) + sizeof(Int32) + sizeof(_CFInfo) + sizeof(UnsafePointer<UInt8>) let ptr = unsafeAddressOf(self) + offset return UnsafePointer<UInt32>(ptr).memory } } required init(characters: UnsafePointer<unichar>, length: Int) { fatalError() } required init?(coder aDecoder: NSCoder) { fatalError() } required init(extendedGraphemeClusterLiteral value: StaticString) { fatalError() } required init(stringLiteral value: StaticString) { fatalError() } required init(capacity: Int) { fatalError() } required init(string aString: String) { fatalError("Constant strings cannot be constructed in code") } deinit { fatalError("Constant strings cannot be deallocated") } override var length: Int { return Int(_length) } override func characterAtIndex(index: Int) -> unichar { return unichar(_ptr[index]) } override func replaceCharactersInRange(range: NSRange, withString aString: String) { fatalError() } } internal func _CFSwiftStringGetLength(string: AnyObject) -> CFIndex { return (string as! NSString).length } internal func _CFSwiftStringGetCharacterAtIndex(str: AnyObject, index: CFIndex) -> UniChar { return (str as! NSString).characterAtIndex(index) } internal func _CFSwiftStringGetCharacters(str: AnyObject, range: CFRange, buffer: UnsafeMutablePointer<UniChar>) { (str as! NSString).getCharacters(buffer, range: NSMakeRange(range.location, range.length)) } internal func _CFSwiftStringGetBytes(str: AnyObject, encoding: CFStringEncoding, range: CFRange, buffer: UnsafeMutablePointer<UInt8>, maxBufLen: CFIndex, usedBufLen: UnsafeMutablePointer<CFIndex>) -> CFIndex { switch encoding { // TODO: Don't treat many encodings like they are UTF8 case CFStringEncoding(kCFStringEncodingUTF8), CFStringEncoding(kCFStringEncodingISOLatin1), CFStringEncoding(kCFStringEncodingMacRoman), CFStringEncoding(kCFStringEncodingASCII), CFStringEncoding(kCFStringEncodingNonLossyASCII): let encodingView = (str as! NSString)._swiftObject.utf8 let start = encodingView.startIndex if buffer != nil { for idx in 0..<range.length { let character = encodingView[start.advancedBy(idx + range.location)] buffer.advancedBy(idx).initialize(character) } } if usedBufLen != nil { usedBufLen.memory = range.length } case CFStringEncoding(kCFStringEncodingUTF16): let encodingView = (str as! NSString)._swiftObject.utf16 let start = encodingView.startIndex if buffer != nil { for idx in 0..<range.length { // Since character is 2 bytes but the buffer is in term of 1 byte values, we have to split it up let character = encodingView[start.advancedBy(idx + range.location)] let byte0 = UInt8(character & 0x00ff) let byte1 = UInt8((character >> 8) & 0x00ff) buffer.advancedBy(idx * 2).initialize(byte0) buffer.advancedBy((idx * 2) + 1).initialize(byte1) } } if usedBufLen != nil { // Every character was 2 bytes usedBufLen.memory = range.length * 2 } default: fatalError("Attempted to get bytes of a Swift string using an unsupported encoding") } return range.length } internal func _CFSwiftStringCreateWithSubstring(str: AnyObject, range: CFRange) -> Unmanaged<AnyObject> { return Unmanaged<AnyObject>.passRetained((str as! NSString).substringWithRange(NSMakeRange(range.location, range.length))._nsObject) } internal func _CFSwiftStringCreateCopy(str: AnyObject) -> Unmanaged<AnyObject> { return Unmanaged<AnyObject>.passRetained((str as! NSString).copyWithZone(nil)) } internal func _CFSwiftStringCreateMutableCopy(str: AnyObject) -> Unmanaged<AnyObject> { return Unmanaged<AnyObject>.passRetained((str as! NSString).mutableCopyWithZone(nil)) } internal func _CFSwiftStringFastCStringContents(str: AnyObject) -> UnsafePointer<Int8> { return (str as! NSString)._fastCStringContents } internal func _CFSwiftStringFastContents(str: AnyObject) -> UnsafePointer<UniChar> { return (str as! NSString)._fastContents } internal func _CFSwiftStringGetCString(str: AnyObject, buffer: UnsafeMutablePointer<Int8>, maxLength: Int, encoding: CFStringEncoding) -> Bool { return (str as! NSString).getCString(buffer, maxLength: maxLength, encoding: CFStringConvertEncodingToNSStringEncoding(encoding)) } internal func _CFSwiftStringIsUnicode(str: AnyObject) -> Bool { return (str as! NSString)._encodingCantBeStoredInEightBitCFString } internal func _CFSwiftStringInsert(str: AnyObject, index: CFIndex, inserted: AnyObject) { (str as! NSMutableString).insertString((inserted as! NSString)._swiftObject, atIndex: index) } internal func _CFSwiftStringDelete(str: AnyObject, range: CFRange) { (str as! NSMutableString).deleteCharactersInRange(NSMakeRange(range.location, range.length)) } internal func _CFSwiftStringReplace(str: AnyObject, range: CFRange, replacement: AnyObject) { (str as! NSMutableString).replaceCharactersInRange(NSMakeRange(range.location, range.length), withString: (replacement as! NSString)._swiftObject) } internal func _CFSwiftStringReplaceAll(str: AnyObject, replacement: AnyObject) { (str as! NSMutableString).setString((replacement as! NSString)._swiftObject) } internal func _CFSwiftStringAppend(str: AnyObject, appended: AnyObject) { (str as! NSMutableString).appendString((appended as! NSString)._swiftObject) } internal func _CFSwiftStringAppendCharacters(str: AnyObject, chars: UnsafePointer<UniChar>, length: CFIndex) { (str as! NSMutableString).appendCharacters(chars, length: length) } internal func _CFSwiftStringAppendCString(str: AnyObject, chars: UnsafePointer<Int8>, length: CFIndex) { (str as! NSMutableString)._cfAppendCString(chars, length: length) }
apache-2.0
aff1624122ab48843e6c38c925f6a28b
35.337838
232
0.69369
4.750883
false
false
false
false
regwez/Bezr
Sources/ArraySorting.swift
1
2274
/* This source file is part of the Bezr open source project Copyright (c) 2014 - 2017 Regwez, Inc. Licensed under Apache License v2.0 with Runtime Library Exception Created by Ragy Eleish on 8/6/14. */ import Foundation public func insertionSort<T: Comparable>(_ array:inout [T], offset:Int, end:Int) { var y = offset for x in offset..<end { y = x while(y>offset && array[y-1]>array[y]) { let temp = array[y] array[y] = array[y-1] array[y-1] = temp y -= 1 } } } public func radixSortUInt16(_ array:inout [UInt16]) { internalRadixSortUInt16(&array, offset:0, end:array.count,shift:8) } func internalRadixSortUInt16(_ array:inout [UInt16], offset:Int, end:Int, shift:UInt16) { var y:UInt16 = 0 var temp:UInt16 = 0 var value: UInt16 = 0 var last = [Int](repeating: 0, count: 256) var pointer = [Int](repeating: 0, count: 256) var localShift:UInt16 = shift for x1:UInt16 in UInt16(offset)..<UInt16(end) { let index:UInt16 = (array[Int(x1)] >> shift) & 0xFF last[Int(index)] += 1 } last[0] += offset; pointer[0] = offset; for x in 1..<256 { let previousX = Int(x - 1) pointer[Int(x)] = last[previousX] last[Int(x)] += last[previousX] } for x in 0..<256 { while (pointer[x] != last[x]) { value = array[pointer[x]] y = (value >> shift) & 0xFF while UInt16(x) != y { temp = array[pointer[Int(y)]] array[pointer[Int(y)]] = value pointer[Int(y)] += 1 value = temp y = (value >> shift) & 0xFF } array[pointer[x]] = value pointer[x] += 1 } } if localShift > 0 { localShift -= 8; for x in 0..<256 { let temp = x > 0 ? pointer[Int(x)] - pointer[Int(x-1)] : pointer[0] - offset if (temp > 64) { internalRadixSortUInt16(&array, offset:pointer[Int(x)] - temp, end:pointer[Int(x)], shift:localShift) } else if (temp > 1) { insertionSort(&array, offset: pointer[Int(x)] - temp, end: pointer[Int(x)]) } } } }
apache-2.0
f991d78ef756ee1059564691ddf3a280
26.731707
117
0.524626
3.414414
false
false
false
false
121372288/Refresh
Refresh/Custom/Header/RefreshStateHeader.swift
1
4812
// // RefreshStateHeader.swift // Refresh // // Created by 马磊 on 2019/1/14. // Copyright © 2019 MLCode.com. All rights reserved. // import UIKit open class RefreshStateHeader: RefreshHeader { /** 显示上一次刷新时间的label */ public let lastUpdatedTimeLabel = UILabel.mlLabel() public var lastUpdatedTimeText: ((Date?)->(String?))? /** 文字距离圈圈、箭头的距离 */ var labelLeftInset: CGFloat = 15 /** 显示刷新状态的label */ public let stateLabel = UILabel.mlLabel() public fileprivate(set) var stateTitles: [RefreshState: String] = [:] /** 设置state状态下的文字 */ public func set(_ title: String, state: RefreshState) { if title.isEmpty { return } stateTitles[state] = title stateLabel.text = stateTitles[self.state] } //MARK: - 日历获取在9.x之后的系统使用currentCalendar会出异常。在8.0之后使用系统新API。 var currentCalendar: Calendar { if #available(iOS 8.0, *) { return Calendar(identifier: Calendar.Identifier.gregorian) } return Calendar.current } open override var lastUpdatedTimeKey: String { didSet { // 如果label隐藏了,就不用再处理 if lastUpdatedTimeLabel.isHidden { return } lastUpdatedTimeLabel.text = lastUpdatedTimeText?(lastUpdatedTime) if let lastUpdatedTime = lastUpdatedTime { let calendar = currentCalendar let componentunits: Set<Calendar.Component> = [.year, .month, .day, .hour, .minute, .second] let lastCmp = calendar.dateComponents(componentunits, from: lastUpdatedTime) let currnetCmp = calendar.dateComponents(componentunits, from: Date()) let formatter = DateFormatter() if lastCmp.day == currnetCmp.day { formatter.dateFormat = " HH:mm" } else if lastCmp.month == currnetCmp.month { formatter.dateFormat = " MM-dd HH:mm" } else { formatter.dateFormat = " yyyy-MM-dd HH:mm" } let time = formatter.string(from: lastUpdatedTime) lastUpdatedTimeLabel.text = Bundle.localizedString(for: RefreshText.Time.HeaderLastTime) + time } else { lastUpdatedTimeLabel.text = Bundle.localizedString(for: RefreshText.Time.HeaderNoneLastDate) } } } //MARK: - 覆盖父类的方法 open override func prepare() { super.prepare() labelLeftInset = RefreshLabelLeftInset addSubview(stateLabel) addSubview(lastUpdatedTimeLabel) set(Bundle.localizedString(for: RefreshText.Header.idle), state: .idle) set(Bundle.localizedString(for: RefreshText.Header.pulling), state: .pulling) set(Bundle.localizedString(for: RefreshText.Header.refreshing), state: .refreshing) layoutIfNeeded() } open override func placeSubViews() { super.placeSubViews() if self.stateLabel.isHidden { return } let noConstrainsOnStatusLabel = stateLabel.constraints.isEmpty if lastUpdatedTimeLabel.isHidden { // 状态 if noConstrainsOnStatusLabel { stateLabel.frame = bounds } } else { let stateLabelH = self.frame.size.height * 0.5 // 状态 if noConstrainsOnStatusLabel { stateLabel.frame.origin.x = 0 stateLabel.frame.origin.y = 0 stateLabel.frame.size.width = self.frame.size.width stateLabel.frame.size.height = stateLabelH } // 更新时间 if lastUpdatedTimeLabel.constraints.isEmpty { lastUpdatedTimeLabel.frame.origin.x = 0 lastUpdatedTimeLabel.frame.origin.y = stateLabelH lastUpdatedTimeLabel.frame.size.width = self.frame.size.width lastUpdatedTimeLabel.frame.size.height = self.frame.size.height - self.lastUpdatedTimeLabel.frame.origin.y } } } public override var state: RefreshState { didSet { if oldValue == state { return } // 设置状态文字 stateLabel.text = stateTitles[state] // 重新设置key(重新显示时间) let lastUpdatedTimeKey = self.lastUpdatedTimeKey self.lastUpdatedTimeKey = lastUpdatedTimeKey } } }
mit
eb7409fedeaea4b181ab1f6619ea7162
33.518797
122
0.573949
5.039517
false
false
false
false
srn214/Floral
Floral/Pods/CLImagePickerTool/CLImagePickerTool/CLImagePickerTool/views/CLPreviewVideoCell.swift
2
5735
// // CLPreviewVideoCell.swift // CLImagePickerTool // // Created by darren on 2017/8/8. // Copyright © 2017年 陈亮陈亮. All rights reserved. // import UIKit import PhotosUI import Photos class CLPreviewVideoCell: UICollectionViewCell { @objc var previewClouse: CLPreviewCellClouse? var imageRequestID: PHImageRequestID? @objc let manager = PHImageManager.default() @objc var playerItem: AVPlayerItem? @objc var player: AVPlayer? @objc lazy var iconView: UIImageView = { let img = UIImageView.init(frame: CGRect(x: 0, y: 0, width: self.cl_width, height: self.cl_height)) img.isUserInteractionEnabled = true img.contentMode = .scaleAspectFit return img }() @objc lazy var playBtn: UIButton = { let btn = UIButton.init(frame: CGRect(x: 0.5*(self.cl_width-80), y: 0.5*(self.cl_height-80), width: 80, height: 80)) btn.setBackgroundImage(UIImage(named: "clvedioplaybtn", in: BundleUtil.getCurrentBundle(), compatibleWith: nil), for: .normal) return btn }() override init(frame: CGRect) { super.init(frame: frame) self.addSubview(self.iconView) self.iconView.addGestureRecognizer(UITapGestureRecognizer.init(target: self, action: #selector(clickImage))) self.addSubview(self.playBtn) self.playBtn.addTarget(self, action: #selector(self.clickPlayBtn), for: .touchUpInside) } @objc var model: PreviewModel! { didSet{ CLPickersTools.instence.getAssetThumbnail(targetSize: CGSize(width:cellH, height: cellH), asset: model.phAsset!) { (image, info) in self.iconView.image = image } } } @objc func clickImage() { self.removeObserver() if self.previewClouse != nil { self.previewClouse!() } } override func layoutSubviews() { super.layoutSubviews() self.iconView.frame = CGRect(x: 0, y: 0, width: self.cl_width, height: self.cl_height) self.playBtn.frame = CGRect(x: 0.5*(self.cl_width-80), y: 0.5*(self.cl_height-80), width: 80, height: 80) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @objc func clickPlayBtn() { self.playBtn.isHidden = true if self.model.phAsset == nil { return } let manager = PHImageManager.default() let videoRequestOptions = PHVideoRequestOptions() videoRequestOptions.deliveryMode = .automatic videoRequestOptions.version = .current videoRequestOptions.isNetworkAccessAllowed = true videoRequestOptions.progressHandler = { (progress, error, stop, info) in DispatchQueue.main.async(execute: { print(progress, info ?? "0000") }) } PopViewUtil.share.showLoading() manager.requestPlayerItem(forVideo: self.model.phAsset!, options: videoRequestOptions) { (playItem, info) in DispatchQueue.main.async(execute: { self.removeObserver() self.playerItem = playItem self.player = AVPlayer(playerItem: self.playerItem) let playerLayer = AVPlayerLayer(player: self.player) playerLayer.frame = self.bounds playerLayer.videoGravity = AVLayerVideoGravity.resizeAspect //视频填充模式 self.iconView.layer.addSublayer(playerLayer) self.addObserver() }) } } @objc func addObserver(){ //为AVPlayerItem添加status属性观察,得到资源准备好,开始播放视频 playerItem?.addObserver(self, forKeyPath: "status", options: .new, context: nil) NotificationCenter.default.addObserver(self, selector: #selector(CLVideoPlayView.playerItemDidReachEnd(notification:)), name: Notification.Name.AVPlayerItemDidPlayToEndTime, object: playerItem) } @objc func removeObserver() { if self.playerItem != nil { self.playerItem?.removeObserver(self, forKeyPath: "status") NotificationCenter.default.removeObserver(self, name: Notification.Name.AVPlayerItemDidPlayToEndTime, object: self.playerItem) self.player = nil self.playerItem = nil } } @objc func playerItemDidReachEnd(notification:Notification) { self.playBtn.isHidden = false self.removeObserver() } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { guard let object = object as? AVPlayerItem else { return } guard let keyPath = keyPath else { return } if keyPath == "status"{ if object.status == .readyToPlay{ //当资源准备好播放,那么开始播放视频 self.player?.play() DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+1, execute: { PopViewUtil.share.stopLoading() }) }else if object.status == .failed || object.status == .unknown{ print("播放出错") PopViewUtil.alert(message: playErrorStr, leftTitle: "", rightTitle: sureStr, leftHandler: { }, rightHandler: { }) PopViewUtil.share.stopLoading() } } } deinit { self.removeObserver() } }
mit
016cdc11f97776d50bc9f968d1cb94c7
33.728395
201
0.599538
4.866782
false
false
false
false
galv/reddift
reddiftSample/MessageViewController.swift
1
1743
// // MessageViewController.swift // reddift // // Created by sonson on 2015/04/21. // Copyright (c) 2015年 sonson. All rights reserved. // import Foundation import reddift class MessageViewController: UITableViewController { var session:Session? = nil var messageWhere = MessageWhere.Inbox var messages:[Thing] = [] override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.title = messageWhere.description session?.getMessage(messageWhere, completion: { (result) -> Void in switch result { case .Failure(let error): print(error) case .Success(let listing): self.messages += listing.children dispatch_async(dispatch_get_main_queue(), { () -> Void in self.tableView.reloadData() }) } }) } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.messages.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell if messages.indices ~= indexPath.row { let child = messages[indexPath.row] if let message = child as? Message { cell.textLabel?.text = message.subject } else if let link = child as? Link { cell.textLabel?.text = link.title } else if let comment = child as? Comment { cell.textLabel?.text = comment.body } } return cell } }
mit
c77ef6c8037eca472af5032fa8cccf23
28.016667
118
0.646755
4.522078
false
false
false
false
tomvlk/MPFormatter_swift
Sources/MPFormatter/MPColor.swift
1
1517
// // MPColor.swift // MPFormatter // // MIT Licensed, 2017, Tom Valk // import Foundation import UIKit class MPColor:MPStyles { fileprivate var color:UIColor init(color:UIColor, startIndex:Int){ self.color = color super.init(start: startIndex) } func apply(_ attr:inout NSMutableAttributedString) { if(self.end != 0){ attr.addAttribute(NSAttributedString.Key.foregroundColor, value: self.color, range: NSRange(location: self.start, length: self.end - self.start)) } } class func isColor(_ input:String, startIndex:Int) -> MPColor? { if(input.count == 3){ return MPColor.init(color: UIColor(rgbaSmall: input), startIndex: startIndex) } return nil } } extension UIColor { convenience init(rgbaSmall: String) { var red: CGFloat = 0.0 var green: CGFloat = 0.0 var blue: CGFloat = 0.0 let alpha: CGFloat = 1.0 if rgbaSmall.count == 3 { let hex = rgbaSmall let scanner = Scanner(string: hex) var hexValue: CUnsignedLongLong = 0 if scanner.scanHexInt64(&hexValue) { red = CGFloat((hexValue & 0xF00) >> 8) / 15.0 green = CGFloat((hexValue & 0x0F0) >> 4) / 15.0 blue = CGFloat(hexValue & 0x00F) / 15.0 } } self.init(red:red, green:green, blue:blue, alpha:alpha) } }
mit
e4f5ea1354b892807176d78f00181709
27.092593
157
0.553065
4.002639
false
false
false
false
Raizlabs/Geode
Example/Common/LocationAnnotationView.swift
1
4145
// // LocationAnnotationView.swift // Example // // Created by John Watson on 1/31/16. // // Copyright © 2016 Raizlabs. All rights reserved. // http://raizlabs.com // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import MapKit import UIKit final class LocationAnnotationView: MKAnnotationView { static let reuseIdentifier = "com.raizlabs.Geode.Example.location-annotation-view" fileprivate let blueCircle = CAShapeLayer() override class var layerClass: AnyClass { return CAShapeLayer.self } override init(annotation: MKAnnotation?, reuseIdentifier: String?) { precondition(reuseIdentifier == LocationAnnotationView.reuseIdentifier, "Incorrect reuse identifier specified") super.init(annotation: annotation, reuseIdentifier: reuseIdentifier) layer.addSublayer(blueCircle) configureLayerProperties() attachAnimations() } @available(*, unavailable) required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: - Private private extension LocationAnnotationView { struct LayoutConstants { static let annotationFrame = CGRect(x: 0.0, y: 0.0, width: 24.0, height: 24.0) static let blueCircleFrame = LayoutConstants.annotationFrame.insetBy(dx: 4.0, dy: 4.0) static let blueCirclePulseInset = CGFloat(1.5) } func configureLayerProperties() { guard let shapeLayer = layer as? CAShapeLayer else { fatalError("View's backing layer is not a CAShapeLayer!") } shapeLayer.path = UIBezierPath(ovalIn: bounds).cgPath shapeLayer.fillColor = UIColor.white.cgColor shapeLayer.shadowColor = UIColor(named: .black).cgColor shapeLayer.shadowOpacity = 0.3 shapeLayer.shadowRadius = 5.0 shapeLayer.shadowOffset = CGSize(width: 0.0, height: 0.0) blueCircle.path = UIBezierPath(ovalIn: LayoutConstants.blueCircleFrame).cgPath blueCircle.fillColor = UIColor(named: .blue).cgColor } func attachAnimations() { attachPathAnimation() attachColorAnimation() } func attachPathAnimation() { let animation = animationWithKeyPath("path") let rect = LayoutConstants.blueCircleFrame.insetBy(dx: LayoutConstants.blueCirclePulseInset, dy: LayoutConstants.blueCirclePulseInset) animation.toValue = UIBezierPath(ovalIn: rect).cgPath animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) blueCircle.add(animation, forKey: animation.keyPath) } func attachColorAnimation() { let animation = animationWithKeyPath("fillColor") animation.toValue = UIColor(named: .lightBlue) blueCircle.add(animation, forKey: animation.keyPath) } func animationWithKeyPath(_ keyPath: String) -> CABasicAnimation { let animation = CABasicAnimation(keyPath: keyPath) animation.autoreverses = true animation.repeatCount = HUGE animation.duration = 2.0 return animation } }
mit
bac1374a0c882e23160670bdb2ffa761
35.672566
142
0.710425
4.7252
false
false
false
false
oarrabi/RangeSliderView
Pod/Classes/SliderBackgroundViewiOS.swift
1
841
// // SliderBackgroundViewiOS.swift // Pods // // Created by Omar Abdelhafith on 07/02/2016. // // #if os(iOS) import UIKit class SliderBackgroundView: UIView { var emptyColor = UIColor(red: 0.722, green: 0.722, blue: 0.722, alpha: 1) var fullColor = UIColor(red: 0.231, green: 0.6, blue: 0.988, alpha: 1) var boundRange: BoundRange = BoundRange.emptyRange { didSet { setNeedsDisplay() } } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) backgroundColor = UIColor.clearColor() } init () { super.init(frame: CGRectZero) backgroundColor = UIColor.clearColor() } override func drawRect(dirtyRect: CGRect) { SliderBackgroundViewImpl.drawRect(forView: self, dirtyRect: dirtyRect) } } #endif
mit
99922b67a6ff507c326e1abe22d4ffc8
20.589744
77
0.621879
3.840183
false
false
false
false
colbylwilliams/bugtrap
iOS/Code/Swift/bugTrap/bugTrapKit/Controllers/BtNavigationController.swift
1
1924
// // BtNavigationController.swift // bugTrap // // Created by Colby L Williams on 11/20/14. // Copyright (c) 2014 bugTrap. All rights reserved. // import UIKit class BtNavigationController: UINavigationController { override func viewDidLoad() { super.viewDidLoad() if TrapState.Shared.inActionExtension { navigationBar.barTintColor = nil navigationBar.tintColor = Colors.Theme.uiColor navigationBar.titleTextAttributes?.updateValue(Colors.Black.uiColor, forKey: NSForegroundColorAttributeName) } } // func presentSettingsNavController (animate: Bool, block: (() -> Void)?) { // let kitStoryboard = UIStoryboard(name: "bugTrapKit", bundle: nil) // // if let settingsNavController = kitStoryboard.instantiateViewControllerWithIdentifier("BtSettingsNavigationController") as? UINavigationController { // presentViewController(settingsNavController, animated: animate, completion: block) // } // } func presentNewBugDetailsNavController (animate: Bool, block: (() -> Void)?) { let kitStoryboard = UIStoryboard(name: "bugTrapKit", bundle: nil) if let newBugDetailsNavController = kitStoryboard.instantiateViewControllerWithIdentifier("BtNewBugDetailsNavigationController") as? UINavigationController { presentViewController(newBugDetailsNavController, animated: animate, completion: block) } } func presentAnnotateImageNavController (animate: Bool, block: (() -> Void)?) { let kitStoryboard = UIStoryboard(name: "bugTrapKit", bundle: nil) if let annotateImageNavController = kitStoryboard.instantiateViewControllerWithIdentifier("BtAnnotateImageNavigationController") as? BtAnnotateImageNavigationController { presentViewController(annotateImageNavController, animated: animate, completion: block) } } override func prefersStatusBarHidden() -> Bool { return true } override func preferredStatusBarStyle() -> UIStatusBarStyle { return .LightContent } }
mit
f4599d2ab860d648dc05c9e5687b40c5
34.648148
172
0.775468
4.715686
false
false
false
false
ekinakyurek/KusisLite
KuGpa/programView.swift
1
26911
// // programView.swift // // // Created by Ekin Akyürek and Ali Mert Türker on 1.10.2015. // // import UIKit import Foundation import Parse var LectureViews = [[UILabel]]() var updated = false; var isPlanned = false; var becauseRotation = false; var statusBarHeight = CGFloat () var oocolor = mainStoryBoardColo class programView: UIViewController{ var ActivityIndicator = UIActivityIndicatorView() override func viewDidLoad() { super.viewDidLoad() if(LectureViews.capacity == 0){ for _ in 0...7 { LectureViews.append(Array(repeating: UILabel(), count: 8)) } } if UIDevice.current.orientation.isLandscape { createMyTableLandscape() }else{ createMyTablePortrait() } if(!updated && isPlanned){ getPlannedProgram(); }else if(!updated && !isPlanned){ getConfirmedProgram() } } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { if isPlanned && updated { becauseRotation = true putCoursesToTable(planned) LectureViews[0][0].text = "Planned" self.ActivityIndicator.stopAnimating() LectureViews[0][0].isUserInteractionEnabled = true }else if !isPlanned && updated { becauseRotation = true putCoursesToTable(confirmed) LectureViews[0][0].text = "Confirm." self.ActivityIndicator.stopAnimating() LectureViews[0][0].isUserInteractionEnabled = true } } func createMyTableLandscape(){ ActivityIndicator.startAnimating() self.navigationController?.isNavigationBarHidden = true var size = get_visible_size() size.height += self.tabBarController!.tabBar.frame.size.height + UIApplication.shared.statusBarFrame.height size.width -= self.tabBarController!.tabBar.frame.size.height let firstRow = (size.width / 6.0) * 0.8 let firstColumn = (size.height / 8.0) * 0.7 let rowStep = (size.width - firstRow) / 5.0 let columnStep = (size.height - firstColumn) / 7.0 var cells = [[ CGRect ]]() cells.append(Array(repeating: CGRect(), count: 8)) cells[0][0] = CGRect(x: 0.0,y: 0.0,width: firstColumn,height: firstRow); let label = UILabel(frame: cells[0][0]); label.textAlignment = NSTextAlignment.center if isPlanned { label.backgroundColor = navigationControllerColor }else{ label.backgroundColor = oocolor } label.textColor = UIColor.white label.numberOfLines = 0 label.font = UIFont(name: "Roboto-Regular", size: 13) let tap = UITapGestureRecognizer(target: self, action: #selector(programView.myMethodToHandleTap(_:))) tap.numberOfTapsRequired = 1 LectureViews[0][0] = label; ActivityIndicator.center = CGPoint(x: firstColumn/2, y: firstRow/2) LectureViews[0][0].addSubview(ActivityIndicator) LectureViews[0][0].addGestureRecognizer(tap) for time in 1...7 { cells[0][time] = CGRect(x: CGFloat(time-1)*columnStep + firstColumn,y: 0.0,width: columnStep,height: firstRow); let label = UILabel(frame: cells[0][time]); label.textAlignment = NSTextAlignment.center; label.backgroundColor = greenButtonColor label.numberOfLines = 1 var start = 8.50 + 1.50 * Double((time-1)) let intstart = Double(Int(floor(start))) let left = start-intstart if left == 0.00 { }else{ start = intstart + 0.30 } let finish = start + 1.15 label.text = String(format: "%.2f", start) + " - " + String(format: "%.2f", finish ) label.textColor = UIColor.white label.font = UIFont(name: "Roboto-Regular", size: 13) label.adjustsFontSizeToFitWidth = true LectureViews[0][time] = label self.view.addSubview(LectureViews[0][time]) } for i in 1...5 { cells.append(Array(repeating: CGRect(), count: 8)) for j in 1...7{ cells[i][j] = CGRect(x: CGFloat(j-1)*columnStep + firstColumn,y: firstRow + CGFloat(i-1)*rowStep,width: columnStep,height: rowStep); let label = UILabel(frame: cells[i][j]); label.textAlignment = NSTextAlignment.center; label.backgroundColor = colorPicker(i, column: j) label.attributedText = LectureViews[i][j].attributedText label.numberOfLines = 0 LectureViews[i][j] = label self.view.addSubview( LectureViews[i][j] ) } } for day in 1...5{ cells[day][0] = CGRect(x: 0,y: CGFloat(day-1)*rowStep + firstRow,width: firstColumn,height: rowStep); let label = UILabel(frame: cells[day][0]); label.textAlignment = NSTextAlignment.center; label.backgroundColor = greenButtonColor label.numberOfLines = 0 var Sday = "" switch day { case 1 : Sday = "Mon" case 2 : Sday = "Tue" case 3 : Sday = "Wed" case 4 : Sday = "Thu" case 5: Sday = "Fri" default: Sday = "" } label.font = UIFont(name: "Roboto-Regular", size: 14) label.text = Sday label.textColor = UIColor.white LectureViews[day][0] = label self.view.addSubview(LectureViews[day][0]) } LectureViews[0][0].layer.shadowOffset = CGSize(width: 2, height: 2) LectureViews[0][0].layer.shadowOpacity = 0.4 LectureViews[0][0].layer.shadowRadius = 4 LectureViews[0][0].layer.shadowColor = UIColor.white.cgColor self.view.addSubview(LectureViews[0][0]) } func createMyTablePortrait(){ ActivityIndicator.startAnimating() self.navigationController?.isNavigationBarHidden = true var size = get_visible_size() if(becauseRotation) { size.height -= statusBarHeight } becauseRotation = false let firstRow = (size.height / 8.0) * 0.8 let firstColumn = (size.width / 6.0) * 0.8 let rowStep = (size.height-firstRow)/7.0 let columnStep = (size.width-firstColumn)/5.0 var cells = [[ CGRect ]]() cells.append(Array(repeating: CGRect(), count: 6)) cells[0][0] = CGRect(x: 0,y: statusBarHeight,width: firstColumn,height: firstRow); let label = UILabel(frame: cells[0][0]); label.textAlignment = NSTextAlignment.center if isPlanned { label.backgroundColor = navigationControllerColor }else{ label.backgroundColor = oocolor } label.textColor = UIColor.white label.numberOfLines = 1 label.adjustsFontSizeToFitWidth = true label.font = UIFont(name: "Roboto-Regular", size: 13) let tap = UITapGestureRecognizer(target: self, action: #selector(programView.myMethodToHandleTap(_:))) tap.numberOfTapsRequired = 1 LectureViews[0][0] = label; ActivityIndicator.center = CGPoint(x: firstColumn/2, y: firstRow/2) LectureViews[0][0].addSubview(ActivityIndicator) LectureViews[0][0].addGestureRecognizer(tap) self.view.addSubview(LectureViews[0][0]) for time in 1...7 { cells.append(Array(repeating: CGRect(), count: 6)) cells[time][0] = CGRect(x: 0.0,y: statusBarHeight + CGFloat(time-1) * rowStep + firstRow ,width: firstColumn,height: rowStep); let label = UILabel(frame: cells[time][0]); label.textAlignment = NSTextAlignment.center; label.backgroundColor = greenButtonColor label.numberOfLines = 0 var start = 8.50 + 1.50 * Double((time-1)) let intstart = Double(Int(floor(start))) let left = start-intstart if left == 0.00 { }else{ start = intstart + 0.30 } let finish = start + 1.15 label.text = String(format: "%.2f", start) + "\n" + String(format: "%.2f", finish ) label.textColor = UIColor.white label.font = UIFont(name: "Roboto-Regular", size: 12) LectureViews[0][time] = label self.view.addSubview(LectureViews[0][time]) } for i in 1...7 { for j in 1...5{ cells[i][j] = CGRect(x: CGFloat(j-1)*columnStep + firstColumn,y: statusBarHeight + CGFloat(i-1)*rowStep + firstRow, width: columnStep,height: rowStep); let label = UILabel(frame: cells[i][j]); label.textAlignment = NSTextAlignment.center; label.backgroundColor = colorPicker(j, column: i) label.attributedText = LectureViews[j][i].attributedText label.numberOfLines = 0 LectureViews[j][i] = label self.view.addSubview( LectureViews[j][i] ) } } for day in 1...5{ cells[0][day] = CGRect(x: CGFloat(day-1)*columnStep + firstColumn,y: statusBarHeight,width: columnStep,height: firstRow); let label = UILabel(frame: cells[0][day]); label.textAlignment = NSTextAlignment.center; label.backgroundColor = greenButtonColor label.numberOfLines = 0 var Sday = "" switch day { case 1 : Sday = "Mo" case 2 : Sday = "Tue" case 3 : Sday = "Wed" case 4 : Sday = "Thu" case 5: Sday = "Fri" default: Sday = "" } label.font = UIFont(name: "Roboto-Regular", size: 14) label.text = Sday label.textColor = UIColor.white LectureViews[day][0] = label self.view.addSubview(LectureViews[day][0]) } LectureViews[0][0].layer.shadowOffset = CGSize(width: 10, height: 10) LectureViews[0][0].layer.shadowOpacity = 0.5 LectureViews[0][0].layer.shadowRadius = 20 LectureViews[0][0].layer.shadowColor = UIColor.white.cgColor } func myMethodToHandleTap(_ sender: UITapGestureRecognizer) { ActivityIndicator.startAnimating() LectureViews[0][0].isUserInteractionEnabled = false LectureViews[0][0].text = "" LectureViews[0][0].layer.shadowOffset = CGSize(width: 2, height: 2) LectureViews[0][0].layer.shadowOpacity = 0.4 LectureViews[0][0].layer.shadowRadius = 7 LectureViews[0][0].layer.shadowColor = UIColor.gray.cgColor if sender.view?.backgroundColor == navigationControllerColor { getConfirmedProgram() sender.view?.backgroundColor = oocolor isPlanned = false; }else{ getPlannedProgram() sender.view?.backgroundColor = navigationControllerColor isPlanned = true; } } func get_visible_size() -> CGSize { var result = UIScreen.main.bounds.size; var size = UIScreen.main.bounds.size; if size.height < size.width { result.height = size.width; result.width = size.height; } size = UIApplication.shared.statusBarFrame.size; result.height -= min(size.width, size.height); if (self.navigationController?.isNavigationBarHidden != true) { size = self.navigationController!.navigationBar.frame.size; result.height -= min(size.width, size.height); } if (self.tabBarController != nil) { size = self.tabBarController!.tabBar.frame.size; result.height -= min(size.width, size.height); } return result; } func colorPicker(_ row: Int, column: Int) -> UIColor { if row % 2 == 0 { return firstCellColor }else{ return UIColor.white } } func getPlannedProgram() { if Reachability.isConnectedToNetwork(){ let request = Reachability.PrepareLoginRequest() let session = URLSession.shared let task = session.dataTask(with: request, completionHandler: { (data, response, error) -> Void in DispatchQueue.main.async(execute: { let newrequest = Reachability.PreparePlannedProgramRequest() let newtask = session.dataTask(with: newrequest, completionHandler: { (data, repsonse, error) -> Void in DispatchQueue.main.async(execute: { planned.removeAll() // var mytext = NSData() // var path = NSURL() // // do { // path = NSBundle.mainBundle().bundleURL // // // path = path.URLByAppendingPathComponent("pelin") // // mytext = try NSData(contentsOfURL: path)! // // // } catch let error as NSError { // print("error loading from url") // print(error.localizedDescription) // } Reachability.dataParsingForProgram( data! ) let USER = PFUser.current() if(USER != nil ) { let currentuser = PFUser.current()?.username if currentuser != "" && planned.count != 0 { USER!.setObject( Reachability.ToJson(planned), forKey: "planned" ) USER?.saveInBackground() } } self.putCoursesToTable(planned) LectureViews[0][0].text = "Planned" self.ActivityIndicator.stopAnimating() LectureViews[0][0].isUserInteractionEnabled = true }) }) newtask.resume() }) }) task.resume() }else{ self.putCoursesToTable(confirmed) LectureViews[0][0].text = "confirmed" self.ActivityIndicator.stopAnimating() LectureViews[0][0].isUserInteractionEnabled = true } } func getConfirmedProgram() { if Reachability.isConnectedToNetwork(){ let request = Reachability.PrepareLoginRequest() let session = URLSession.shared let task = session.dataTask(with: request, completionHandler: { (data, response, error) -> Void in DispatchQueue.main.async(execute: { let newrequest = Reachability.PrepareConfirmedProgramRequest() let newtask = session.dataTask(with: newrequest, completionHandler: { (data, repsonse, error) -> Void in DispatchQueue.main.async(execute: { confirmed.removeAll() Reachability.dataParsingForConfirmed(data!) let USER = PFUser.current() if(USER != nil && USER?.username != "" && confirmed.count != 0 ) { USER!.setObject( Reachability.ToJson(confirmed) , forKey: "confirmed" ) USER!.saveInBackground(); } self.putCoursesToTable(confirmed) if UIDevice.current.orientation.isLandscape { LectureViews[0][0].text = "Confirm." }else{ LectureViews[0][0].text = "Conf." } self.ActivityIndicator.stopAnimating() LectureViews[0][0].isUserInteractionEnabled = true }) }) newtask.resume() }) }) task.resume() }else{ self.putCoursesToTable(planned) LectureViews[0][0].text = "planned" self.ActivityIndicator.stopAnimating() LectureViews[0][0].isUserInteractionEnabled = true } } func putCoursesToTable(_ listOfProgram: [Lecture]){ for lectures in LectureViews{ for lecture in lectures { lecture.text = " " } } for lecture in listOfProgram { var index = [0,0,0,0] var firstLine = NSMutableAttributedString(string: "") let smallerFontSize = [NSFontAttributeName: UIFont(name: "Roboto-Light", size: 10)!] let biggerFontSize = [NSFontAttributeName: UIFont(name: "Roboto-Regular", size: 12)!] var secondLine = NSMutableAttributedString(string: "") let yildiz = NSMutableAttributedString(string: "*", attributes: smallerFontSize) if(lecture.lecStart != 0.0 ){ index = dateToIndex(lecture.lecStart,end: lecture.lecEnd , days: lecture.lecDays) firstLine = NSMutableAttributedString(string: lecture.name, attributes: biggerFontSize) secondLine = NSMutableAttributedString(string: "\n" + lecture.location, attributes: smallerFontSize) if index[4]==1 { secondLine.append(yildiz) } firstLine.append(secondLine) LectureViews[index[2]][index[0]].font = nil LectureViews[index[2]][index[0]].textColor = nil LectureViews[index[2]][index[0]].attributedText = firstLine if index[3] != 0 { LectureViews[index[3]][index[0]].attributedText = firstLine } if index[1] == 1 { LectureViews[index[3]][index[0]+1].attributedText = firstLine } if index[1] == 2 { LectureViews[index[3]][index[0]+1].attributedText = firstLine LectureViews[index[3]][index[0]+2].attributedText = firstLine } } if(lecture.psStart != 0.0 ){ index = dateToIndex(lecture.psStart,end: lecture.psEnd , days: lecture.psDays) firstLine = NSMutableAttributedString(string: "PS-\(lecture.name)\n", attributes: biggerFontSize) secondLine = NSMutableAttributedString(string: "\(lecture.psLocation)", attributes: smallerFontSize) if index[4]==1 { secondLine.append(yildiz) } firstLine.append(secondLine) LectureViews[index[2]][index[0]].attributedText = firstLine if index[3] != 0 { LectureViews[index[3]][index[0]].attributedText = firstLine } if index[1] == 1 { LectureViews[index[3]][index[0]+1].attributedText = firstLine } if index[1] == 2 { LectureViews[index[3]][index[0]+1].attributedText = firstLine LectureViews[index[3]][index[0]+2].attributedText = firstLine } } if(lecture.dsStart != 0.0 ){ index = dateToIndex(lecture.dsStart,end: lecture.dsEnd , days: lecture.dsDays) firstLine = NSMutableAttributedString(string: "DS-\(lecture.name)\n", attributes: biggerFontSize) secondLine = NSMutableAttributedString(string: "\(lecture.dsLocation)", attributes: smallerFontSize) if index[4]==1 { secondLine.append(yildiz) } firstLine.append(secondLine) LectureViews[index[2]][index[0]].attributedText = firstLine if index[3] != 0 { LectureViews[index[3]][index[0]].attributedText = firstLine } if index[1] == 1 { LectureViews[index[3]][index[0]+1].attributedText = firstLine } if index[1] == 2 { LectureViews[index[3]][index[0]+1].attributedText = firstLine LectureViews[index[3]][index[0]+2].attributedText = firstLine } } if(lecture.labStart != 0.0 ){ index = dateToIndex(lecture.labStart,end: lecture.labEnd , days: lecture.labDays) firstLine = NSMutableAttributedString(string: "LAB-\(lecture.name)\n", attributes: biggerFontSize) secondLine = NSMutableAttributedString(string: "\(lecture.labLocation)", attributes: smallerFontSize) if index[4]==1 { secondLine.append(yildiz) } firstLine.append(secondLine) LectureViews[index[2]][index[0]].attributedText = firstLine if index[3] != 0 { LectureViews[index[3]][index[0]].attributedText = firstLine } if index[1] == 1 { LectureViews[index[2]][1 + index[0]].attributedText = firstLine } if index[1] == 2 { LectureViews[index[2]][index[0]+1].attributedText = firstLine LectureViews[index[2]][index[0]+2].attributedText = firstLine } } } updated = true let parent: UIView = self.view.superview! self.view.removeFromSuperview() self.view = nil; // unloads the view parent.addSubview(self.view) } func dateToIndex(_ start: Double, end: Double, days: String) -> [Int]{ var i,j : Int var t,z: Int var yildiz : Int yildiz = 0 switch start { case 8.3 : j = 1 case 10.0 : j = 2 case 11.3 : j = 3 case 13.0 : j = 4 case 14.3 : j = 5 case 16.0 : j = 6 case 17.3 : j = 7 case 12.3 : j = 4 yildiz = 1 default: j = 0 } switch end { case 9.45 : z = 1 - j case 11.15 : z = 2 - j case 12.45 : z = 3 - j case 14.15 : z = 4 - j case 15.45 : z = 5 - j case 17.15 : z = 6 - j case 16.45 : z = 7 - j case 12.20 : z = 3 - j yildiz = 1 default: z = 0 } switch days { case "MoWe" : i = 1 t = 3 case "TuTh" : i = 2 t = 4 case "Mo" : i = 1 t = 0 case "Tu" : i = 2 t = 0 case "We" : i = 3 t = 0 case "Th" : i = 4 t = 0 case "Fr" : i = 5 t = 0 default : i=0 t=0 } return [j,z,i,t,yildiz] } override func viewWillAppear(_ animated: Bool) { navigationController?.hidesBarsOnSwipe = false self.navigationController?.interactivePopGestureRecognizer!.isEnabled = true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
lgpl-3.0
eddee448f08f05cd0367c0da1fbbd477
32.933165
167
0.468245
5.205843
false
false
false
false
gkye/DribbbleSwift
Source/Source/LclJSONSerialization.swift
2
8735
/** * Copyright IBM Corporation 2016 * * 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. **/ #if os(Linux) import Foundation public let LclErrorDomain = "Lcl.Error.Domain" public class LclJSONSerialization { private static let JSON_WRITE_ERROR = "JSON Write failure." private static let FALSE = "false" private static let TRUE = "true" private static let NULL = "null" public class func isValidJSONObject(_ obj: Any) -> Bool { // TODO: - revisit this once bridging story gets fully figured out func isValidJSONObjectInternal(_ obj: Any) -> Bool { // object is Swift.String or NSNull if obj is String || obj is Int || obj is Bool || obj is NSNull || obj is UInt { return true } // object is a Double and is not NaN or infinity if let number = obj as? Double { let invalid = number.isInfinite || number.isNaN return !invalid } // object is a Float and is not NaN or infinity if let number = obj as? Float { let invalid = number.isInfinite || number.isNaN return !invalid } // object is NSNumber and is not NaN or infinity if let number = obj as? NSNumber { let invalid = number.doubleValue.isInfinite || number.doubleValue.isNaN return !invalid } let mirror = Mirror(reflecting: obj) if mirror.displayStyle == .collection { // object is Swift.Array for element in mirror.children { guard isValidJSONObjectInternal(element.value) else { return false } } return true } else if mirror.displayStyle == .dictionary { // object is Swift.Dictionary for pair in mirror.children { let pairMirror = Mirror(reflecting: pair.value) if pairMirror.displayStyle == .tuple && pairMirror.children.count == 2 { let generator = pairMirror.children.makeIterator() if generator.next()!.value is String { guard isValidJSONObjectInternal(generator.next()!.value) else { return false } } else { // Invalid JSON Object, Key not a String return false } } else { // Invalid Dictionary return false } } return true } else { // invalid object return false } } // top level object must be an Swift.Array or Swift.Dictionary let mirror = Mirror(reflecting: obj) guard mirror.displayStyle == .collection || mirror.displayStyle == .dictionary else { return false } return isValidJSONObjectInternal(obj) } public class func dataWithJSONObject(_ obj: Any, options: JSONSerialization.WritingOptions) throws -> Data { var result = Data() try writeJson(obj, options: options) { (str: String?) in if let str = str { result.append(str.data(using: String.Encoding.utf8) ?? Data()) } } return result } /* Helper function to enable writing to NSData as well as NSStream */ private static func writeJson(_ obj: Any, options opt: JSONSerialization.WritingOptions, writer: (String?) -> Void) throws { let prettyPrint = opt.rawValue & JSONSerialization.WritingOptions.prettyPrinted.rawValue != 0 let padding: String? = prettyPrint ? "" : nil try writeJsonValue(obj, padding: padding, writer: writer) } /* Write out a JSON value (simple value, object, or array) */ private static func writeJsonValue(_ obj: Any, padding: String?, writer: (String?) -> Void) throws { if obj is String { writer("\"") writer((obj as! String)) writer("\"") } else if obj is Bool { writer(obj as! Bool ? TRUE : FALSE) } else if obj is Int || obj is Float || obj is Double || obj is UInt { writer(String(describing: obj)) } else if obj is NSNumber { writer(JSON.stringFromNumber(obj as! NSNumber)) } else if obj is NSNull { writer(NULL) } else { let mirror = Mirror(reflecting: obj) if mirror.displayStyle == .collection { try writeJsonArray(mirror.children.map { $0.value as Any }, padding: padding, writer: writer) } else if mirror.displayStyle == .dictionary { try writeJsonObject(mirror.children.map { $0.value }, padding: padding, writer: writer) } else { print("writeJsonValue: Unsupported type \(type(of: obj))") throw createWriteError("Unsupported data type to be written out as JSON") } } } /* Write out a dictionary as a JSON object */ private static func writeJsonObject(_ pairs: Array<Any>, padding: String?, writer: (String?) -> Void) throws { let (nestedPadding, startOfLine, endOfLine) = setupPadding(padding) let nameValueSeparator = padding != nil ? ": " : ":" writer("{") var comma = "" let realComma = "," for pair in pairs { let pairMirror = Mirror(reflecting: pair) if pairMirror.displayStyle == .tuple && pairMirror.children.count == 2 { let generator = pairMirror.children.makeIterator() if let key = generator.next()!.value as? String { let value = generator.next()!.value writer(comma) comma = realComma writer(endOfLine) writer(nestedPadding) writer("\"") writer(key) writer("\"") writer(nameValueSeparator) try writeJsonValue(value, padding: nestedPadding, writer: writer) } } } writer(endOfLine) writer(startOfLine) writer("}") } /* Write out an array as a JSON Array */ private static func writeJsonArray(_ obj: Array<Any>, padding: String?, writer: (String?) -> Void) throws { let (nestedPadding, startOfLine, endOfLine) = setupPadding(padding) writer("[") var comma = "" let realComma = "," for value in obj { writer(comma) comma = realComma writer(endOfLine) writer(nestedPadding) try writeJsonValue(value, padding: nestedPadding, writer: writer) } writer(endOfLine) writer(startOfLine) writer("]") } /* Setup "padding" to be used in objects and arrays. Note: if padding is nil, then all padding, newlines etc., are suppressed */ private static func setupPadding(_ padding: String?) -> (String?, String?, String?) { var nestedPadding: String? var startOfLine: String? var endOfLine: String? if let padding = padding { nestedPadding = padding + " " startOfLine = padding endOfLine = "\n" } else { nestedPadding = nil startOfLine = nil endOfLine = nil } return (nestedPadding, startOfLine, endOfLine) } private static func createWriteError(_ reason: String) -> NSError { let userInfo: [String: Any] = [NSLocalizedDescriptionKey: JSON_WRITE_ERROR, NSLocalizedFailureReasonErrorKey: reason] return NSError(domain: LclErrorDomain, code: 1, userInfo: userInfo) } } #endif
mit
30c92cde059b7559a238ba8e4d5b8b4b
35.244813
128
0.542988
5.040392
false
false
false
false
arnaudbenard/my-npm
Pods/Charts/Charts/Classes/Renderers/BubbleChartRenderer.swift
54
11776
// // BubbleChartRenderer.swift // Charts // // Bubble chart implementation: // Copyright 2015 Pierre-Marc Airoldi // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics import UIKit @objc public protocol BubbleChartRendererDelegate { func bubbleChartRendererData(renderer: BubbleChartRenderer) -> BubbleChartData! func bubbleChartRenderer(renderer: BubbleChartRenderer, transformerForAxis which: ChartYAxis.AxisDependency) -> ChartTransformer! func bubbleChartDefaultRendererValueFormatter(renderer: BubbleChartRenderer) -> NSNumberFormatter! func bubbleChartRendererChartYMax(renderer: BubbleChartRenderer) -> Double func bubbleChartRendererChartYMin(renderer: BubbleChartRenderer) -> Double func bubbleChartRendererChartXMax(renderer: BubbleChartRenderer) -> Double func bubbleChartRendererChartXMin(renderer: BubbleChartRenderer) -> Double func bubbleChartRendererMaxVisibleValueCount(renderer: BubbleChartRenderer) -> Int func bubbleChartRendererXValCount(renderer: BubbleChartRenderer) -> Int } public class BubbleChartRenderer: ChartDataRendererBase { public weak var delegate: BubbleChartRendererDelegate? public init(delegate: BubbleChartRendererDelegate?, animator: ChartAnimator?, viewPortHandler: ChartViewPortHandler) { super.init(animator: animator, viewPortHandler: viewPortHandler) self.delegate = delegate } public override func drawData(#context: CGContext) { let bubbleData = delegate!.bubbleChartRendererData(self) for set in bubbleData.dataSets as! [BubbleChartDataSet] { if (set.isVisible) { drawDataSet(context: context, dataSet: set) } } } private func getShapeSize(#entrySize: CGFloat, maxSize: CGFloat, reference: CGFloat) -> CGFloat { let factor: CGFloat = (maxSize == 0.0) ? 1.0 : sqrt(entrySize / maxSize) let shapeSize: CGFloat = reference * factor return shapeSize } private var _pointBuffer = CGPoint() private var _sizeBuffer = [CGPoint](count: 2, repeatedValue: CGPoint()) internal func drawDataSet(#context: CGContext, dataSet: BubbleChartDataSet) { let trans = delegate!.bubbleChartRenderer(self, transformerForAxis: dataSet.axisDependency) let phaseX = _animator.phaseX let phaseY = _animator.phaseY let entries = dataSet.yVals as! [BubbleChartDataEntry] let valueToPixelMatrix = trans.valueToPixelMatrix CGContextSaveGState(context) var entryFrom = dataSet.entryForXIndex(_minX) var entryTo = dataSet.entryForXIndex(_maxX) var minx = max(dataSet.entryIndex(entry: entryFrom!, isEqual: true), 0) var maxx = min(dataSet.entryIndex(entry: entryTo!, isEqual: true) + 1, entries.count) _sizeBuffer[0].x = 0.0 _sizeBuffer[0].y = 0.0 _sizeBuffer[1].x = 1.0 _sizeBuffer[1].y = 0.0 trans.pointValuesToPixel(&_sizeBuffer) // calcualte the full width of 1 step on the x-axis let maxBubbleWidth: CGFloat = abs(_sizeBuffer[1].x - _sizeBuffer[0].x) let maxBubbleHeight: CGFloat = abs(viewPortHandler.contentBottom - viewPortHandler.contentTop) let referenceSize: CGFloat = min(maxBubbleHeight, maxBubbleWidth) for (var j = minx; j < maxx; j++) { var entry = entries[j] _pointBuffer.x = CGFloat(entry.xIndex - minx) * phaseX + CGFloat(minx) _pointBuffer.y = CGFloat(entry.value) * phaseY _pointBuffer = CGPointApplyAffineTransform(_pointBuffer, valueToPixelMatrix) let shapeSize = getShapeSize(entrySize: entry.size, maxSize: dataSet.maxSize, reference: referenceSize) let shapeHalf = shapeSize / 2.0 if (!viewPortHandler.isInBoundsTop(_pointBuffer.y + shapeHalf) || !viewPortHandler.isInBoundsBottom(_pointBuffer.y - shapeHalf)) { continue } if (!viewPortHandler.isInBoundsLeft(_pointBuffer.x + shapeHalf)) { continue } if (!viewPortHandler.isInBoundsRight(_pointBuffer.x - shapeHalf)) { break } let color = dataSet.colorAt(entry.xIndex) let rect = CGRect( x: _pointBuffer.x - shapeHalf, y: _pointBuffer.y - shapeHalf, width: shapeSize, height: shapeSize ) CGContextSetFillColorWithColor(context, color.CGColor) CGContextFillEllipseInRect(context, rect) } CGContextRestoreGState(context) } public override func drawValues(#context: CGContext) { let bubbleData = delegate!.bubbleChartRendererData(self) if (bubbleData === nil) { return } let defaultValueFormatter = delegate!.bubbleChartDefaultRendererValueFormatter(self) // if values are drawn if (bubbleData.yValCount < Int(ceil(CGFloat(delegate!.bubbleChartRendererMaxVisibleValueCount(self)) * viewPortHandler.scaleX))) { let dataSets = bubbleData.dataSets as! [BubbleChartDataSet] for dataSet in dataSets { if (!dataSet.isDrawValuesEnabled) { continue } let phaseX = _animator.phaseX let phaseY = _animator.phaseY let alpha = phaseX == 1 ? phaseY : phaseX let valueTextColor = dataSet.valueTextColor.colorWithAlphaComponent(alpha) let formatter = dataSet.valueFormatter === nil ? defaultValueFormatter : dataSet.valueFormatter let entries = dataSet.yVals var entryFrom = dataSet.entryForXIndex(_minX) var entryTo = dataSet.entryForXIndex(_maxX) var minx = max(dataSet.entryIndex(entry: entryFrom!, isEqual: true), 0) var maxx = min(dataSet.entryIndex(entry: entryTo!, isEqual: true) + 1, entries.count) let positions = delegate!.bubbleChartRenderer(self, transformerForAxis: dataSet.axisDependency).generateTransformedValuesBubble(entries, phaseX: phaseX, phaseY: phaseY, from: minx, to: maxx) for (var j = 0, count = positions.count; j < count; j++) { if (!viewPortHandler.isInBoundsRight(positions[j].x)) { break } if ((!viewPortHandler.isInBoundsLeft(positions[j].x) || !viewPortHandler.isInBoundsY(positions[j].y))) { continue } let entry = entries[j + minx] as! BubbleChartDataEntry let val = entry.size let text = formatter!.stringFromNumber(val) // Larger font for larger bubbles? let valueFont = dataSet.valueFont let lineHeight = valueFont.lineHeight ChartUtils.drawText(context: context, text: text!, point: CGPoint(x: positions[j].x, y: positions[j].y - ( 0.5 * lineHeight)), align: .Center, attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: valueTextColor]) } } } } public override func drawExtras(#context: CGContext) { } public override func drawHighlighted(#context: CGContext, indices: [ChartHighlight]) { let bubbleData = delegate!.bubbleChartRendererData(self) CGContextSaveGState(context) let phaseX = _animator.phaseX let phaseY = _animator.phaseY for indice in indices { let dataSet = bubbleData.getDataSetByIndex(indice.dataSetIndex) as! BubbleChartDataSet! if (dataSet === nil || !dataSet.isHighlightEnabled) { continue } var entryFrom = dataSet.entryForXIndex(_minX) var entryTo = dataSet.entryForXIndex(_maxX) var minx = max(dataSet.entryIndex(entry: entryFrom!, isEqual: true), 0) var maxx = min(dataSet.entryIndex(entry: entryTo!, isEqual: true) + 1, dataSet.entryCount) let entry: BubbleChartDataEntry! = bubbleData.getEntryForHighlight(indice) as! BubbleChartDataEntry if (entry === nil || entry.xIndex != indice.xIndex) { continue } let trans = delegate!.bubbleChartRenderer(self, transformerForAxis: dataSet.axisDependency) _sizeBuffer[0].x = 0.0 _sizeBuffer[0].y = 0.0 _sizeBuffer[1].x = 1.0 _sizeBuffer[1].y = 0.0 trans.pointValuesToPixel(&_sizeBuffer) // calcualte the full width of 1 step on the x-axis let maxBubbleWidth: CGFloat = abs(_sizeBuffer[1].x - _sizeBuffer[0].x) let maxBubbleHeight: CGFloat = abs(viewPortHandler.contentBottom - viewPortHandler.contentTop) let referenceSize: CGFloat = min(maxBubbleHeight, maxBubbleWidth) _pointBuffer.x = CGFloat(entry.xIndex - minx) * phaseX + CGFloat(minx) _pointBuffer.y = CGFloat(entry.value) * phaseY trans.pointValueToPixel(&_pointBuffer) let shapeSize = getShapeSize(entrySize: entry.size, maxSize: dataSet.maxSize, reference: referenceSize) let shapeHalf = shapeSize / 2.0 if (!viewPortHandler.isInBoundsTop(_pointBuffer.y + shapeHalf) || !viewPortHandler.isInBoundsBottom(_pointBuffer.y - shapeHalf)) { continue } if (!viewPortHandler.isInBoundsLeft(_pointBuffer.x + shapeHalf)) { continue } if (!viewPortHandler.isInBoundsRight(_pointBuffer.x - shapeHalf)) { break } if (indice.xIndex < minx || indice.xIndex >= maxx) { continue } let originalColor = dataSet.colorAt(entry.xIndex) var h: CGFloat = 0.0 var s: CGFloat = 0.0 var b: CGFloat = 0.0 var a: CGFloat = 0.0 originalColor.getHue(&h, saturation: &s, brightness: &b, alpha: &a) let color = UIColor(hue: h, saturation: s, brightness: b * 0.5, alpha: a) let rect = CGRect( x: _pointBuffer.x - shapeHalf, y: _pointBuffer.y - shapeHalf, width: shapeSize, height: shapeSize) CGContextSetLineWidth(context, dataSet.highlightCircleWidth) CGContextSetStrokeColorWithColor(context, color.CGColor) CGContextStrokeEllipseInRect(context, rect) } CGContextRestoreGState(context) } }
mit
c754b225728fce867e4db3919204dc3b
37.486928
256
0.572181
5.586338
false
false
false
false
DimensionSrl/Desman
Desman/Core/Managers/UploadManager.swift
1
14050
// // UploadManager.swift // Desman // // Created by Matteo Gavagnin on 19/10/15. // Copyright © 2015 DIMENSION S.r.l. All rights reserved. // import Foundation open class UploadManager { /** A shared instance of `UploadManager`. */ static open let sharedInstance = UploadManager() open var baseURL: URL? open var session: URLSession? var uploading = false /** Configures `NetworkManager` with the specified base URL and app key used to authenticate with the remote service. - parameter baseURL: The base URL to be used to construct requests; - parameter appKey: The Authorization token that will be used authenticate the application with the remote serive. */ func takeOff(_ baseURL: URL, appKey: String) { self.baseURL = baseURL let sessionConfiguration = URLSessionConfiguration.default sessionConfiguration.httpAdditionalHeaders = ["Authorization": "Token \(appKey)"] self.session = URLSession(configuration: sessionConfiguration) } func sendEventWithAttachment(_ event: Event) { // TODO: use a separate queue guard (self.session != nil) else { return } guard event.sent == false else { print("Desman: event already sent, won't upload it again") return } guard event.uploading == false else { return } event.uploading = true guard let attachment = event.attachment else { return } let url = URL(string: "/events.json", relativeTo: baseURL)! var request = forgeRequest(url: url, contentTypes: []) let boundary = "Boundary-\(UUID().uuidString)" request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type") request.httpMethod = "POST" request.httpBody = createBodyWithParameters(event.dictionary, filePathKey: "attachment", attachment: attachment as Data, boundary: boundary) guard let session = self.session else { return } let task = session.dataTask(with: request, completionHandler: { (data, response, error) -> Void in if let error = error { event.uploading = false print("Desman: cannot send event - \(error.localizedDescription)") } else { // We should receive an identifier from the server to confirm save operation, we are going to overwrite the local one if let data = data { do { let eventDictionary = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions(rawValue: 0)) as! [String: Any] if let id = eventDictionary["id"] as? String { event.id = id event.sent = true event.uploading = false if EventManager.shared.type == .coreData { event.saveCDEvent() } DispatchQueue.main.async { EventManager.shared.sentEvents.append(event) } } else if let id = eventDictionary["id"] as? Int { event.id = "\(id)" event.sent = true event.uploading = false if EventManager.shared.type == .coreData { event.saveCDEvent() } DispatchQueue.main.async { EventManager.shared.sentEvents.append(event) } } } catch let parseError as NSError { event.uploading = false // TODO: Should mark the event as sent, but with failure print("Desman: cannot parse event response \(parseError.description) - \(String(data: data, encoding: String.Encoding.utf8))") } } else { event.uploading = false } } DispatchQueue.main.async { EventManager.shared.serializeEvents() } }) task.resume() } func createBodyWithParameters(_ parameters: [String : Any]?, filePathKey: String?, attachment: Data, boundary: String) -> Data { let body = NSMutableData(); if parameters != nil { for (key, value) in parameters! { if key != "payload" { body.appendString("--\(boundary)\r\n") body.appendString("Content-Disposition: form-data; name=\"event[\(key)]\"\r\n\r\n") body.appendString("\(value)\r\n") } else { do { let payloadJson = try JSONSerialization.data(withJSONObject: value, options: JSONSerialization.WritingOptions(rawValue: 0)) if let stringPayload = String(data: payloadJson, encoding: String.Encoding.utf8) { body.appendString("--\(boundary)\r\n") body.appendString("Content-Disposition: form-data; name=\"event[\(key)]\"\r\n\r\n") body.appendString("\(stringPayload)\r\n") } } catch _ { } } } } let filename = "attachment" let mimetype = "image/png" body.appendString("--\(boundary)\r\n") body.appendString("Content-Disposition: form-data; name=\"event[\(filePathKey!)]\"; filename=\"\(filename)\"\r\n") body.appendString("Content-Type: \(mimetype)\r\n\r\n") body.append(attachment) body.appendString("\r\n") body.appendString("--\(boundary)--\r\n") return body as Data } func sendEvent(_ event: Event) { guard !uploading else { return } guard event.attachment == nil else { self.sendEventWithAttachment(event) return } guard (self.session != nil) else { return } guard event.sent == false else { print("Desman: event already sent, won't upload it again") return } guard let data = event.data else { print("Desman: event cannot be converted to json, cannot send it") return } let url = URL(string: "/events", relativeTo: baseURL)! var request = forgeRequest(url: url, contentTypes: ["application/json"]) request.httpMethod = "POST" request.httpBody = data as Data let task = self.session!.dataTask(with: request, completionHandler: { (data, response, error) -> Void in self.uploading = false if let error = error { print("Desman: cannot send event \(error.localizedDescription)") } else { // We should receive an identifier from the server to confirm save operation, we are going to overwrite the local one if let data = data { do { let eventDictionary = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions(rawValue: 0)) as! [String: Any] if let id = eventDictionary["id"] as? String { event.id = id } else if let id = eventDictionary["id"] as? Int { event.id = "\(id)" } } catch let parseError as NSError { // TODO: Should mark the event as sent, but with failure print("Desman: cannot parse event response \(parseError.description) - \(String(data: data, encoding: String.Encoding.utf8))") } } event.sent = true if EventManager.shared.type == .coreData { event.saveCDEvent() } DispatchQueue.main.async { EventManager.shared.sentEvents.append(event) } } DispatchQueue.main.async { EventManager.shared.serializeEvents() } }) task.resume() uploading = true } func sendEvents(_ events: [Event]) { guard !uploading else { return } guard (self.session != nil) else { return } var pendingEvents = events.filter{ $0.sent == false } let eventsWithAttachments = pendingEvents.filter{ $0.attachment != nil } for event in eventsWithAttachments { sendEventWithAttachment(event) } pendingEvents = pendingEvents.filter{ $0.attachment == nil } guard pendingEvents.count > 0 else { return } let url = URL(string: "/batch", relativeTo: baseURL)! var request = forgeRequest(url: url, contentTypes: ["application/json"]) request.httpMethod = "POST" let operations = pendingEvents.map{forgeSendEventOperation($0)} let dictionary = ["ops": operations, "sequential": true] as [String : Any] do { let data = try JSONSerialization.data(withJSONObject: dictionary, options: .prettyPrinted) request.httpBody = data let task = self.session!.dataTask(with: request, completionHandler: { (data, response, error) -> Void in self.uploading = false if let error = error { print("Desman: cannot send event - \(error.localizedDescription)") } else { // We should receive an identifier from the server to confirm save operation, we are going to overwrite the local one if let data = data { do { let parsedData = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions(rawValue: 0)) as! [String: Any] if let results = parsedData["results"] as? [[String : AnyObject]] { for result in results { if let bodyJson = result["body"] as? String, let body = bodyJson.data(using: String.Encoding.utf8) { do { let body = try JSONSerialization.jsonObject(with: body, options: JSONSerialization.ReadingOptions(rawValue: 0)) as! [String: Any] if let id = body["id"] as? Int, let uuidString = body["uuid"] as? String, let uuid = UUID(uuidString: uuidString) { let filteredEvents = events.filter{$0.uuid == uuid} if let event = filteredEvents.first { event.id = "\(id)" event.sent = true if EventManager.shared.type == .coreData { event.saveCDEvent() } DispatchQueue.main.async { EventManager.shared.sentEvents.append(event) } } } else { print("Desman: cannot find id in body \(body)") } } catch let parseBodyError as NSError { print("Desman: cannot parse body event response \(parseBodyError.description)") } } else { print("Desman: cannot parse result \(result)") } } } else { print("Desman: cannot find and parse *results* data \(parsedData)") } } catch let parseError as NSError { print("Desman: cannot parse event response \(parseError.description)") } } } DispatchQueue.main.async { EventManager.shared.serializeEvents() } }) task.resume() uploading = true } catch let error { print("Desman: cannot serialize events \(error)") } } func forgeSendEventOperation(_ event: Event) -> [String : AnyObject] { let operation : [String : AnyObject] = ["method": "post" as AnyObject, "url": "/events" as AnyObject, "params": event.dictionary as AnyObject] return operation } open func forgeRequest(url: URL, contentTypes: [String]) -> URLRequest { // TODO: use cache in production // UseProtocolCachePolicy var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 30) for type in contentTypes { request.addValue(type, forHTTPHeaderField: "Content-Type") request.addValue(type, forHTTPHeaderField: "Accept") } return request } } extension NSMutableData { func appendString(_ string: String) { let data = string.data(using: String.Encoding.utf8, allowLossyConversion: true) append(data!) } }
mit
12f8927a469f9cd203fbd15beef3884f
47.113014
173
0.500676
5.583863
false
false
false
false
practicalswift/swift
stdlib/public/core/StringProtocol.swift
1
6665
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// A type that can represent a string as a collection of characters. /// /// Do not declare new conformances to `StringProtocol`. Only the `String` and /// `Substring` types in the standard library are valid conforming types. public protocol StringProtocol : BidirectionalCollection, TextOutputStream, TextOutputStreamable, LosslessStringConvertible, ExpressibleByStringInterpolation, Hashable, Comparable where Iterator.Element == Character, Index == String.Index, SubSequence : StringProtocol, StringInterpolation == DefaultStringInterpolation { associatedtype UTF8View : /*Bidirectional*/Collection where UTF8View.Element == UInt8, // Unicode.UTF8.CodeUnit UTF8View.Index == Index associatedtype UTF16View : BidirectionalCollection where UTF16View.Element == UInt16, // Unicode.UTF16.CodeUnit UTF16View.Index == Index associatedtype UnicodeScalarView : BidirectionalCollection where UnicodeScalarView.Element == Unicode.Scalar, UnicodeScalarView.Index == Index associatedtype SubSequence = Substring var utf8: UTF8View { get } var utf16: UTF16View { get } var unicodeScalars: UnicodeScalarView { get } func hasPrefix(_ prefix: String) -> Bool func hasSuffix(_ prefix: String) -> Bool func lowercased() -> String func uppercased() -> String /// Creates a string from the given Unicode code units in the specified /// encoding. /// /// - Parameters: /// - codeUnits: A collection of code units encoded in the encoding /// specified in `sourceEncoding`. /// - sourceEncoding: The encoding in which `codeUnits` should be /// interpreted. init<C: Collection, Encoding: Unicode.Encoding>( decoding codeUnits: C, as sourceEncoding: Encoding.Type ) where C.Iterator.Element == Encoding.CodeUnit /// Creates a string from the null-terminated, UTF-8 encoded sequence of /// bytes at the given pointer. /// /// - Parameter nullTerminatedUTF8: A pointer to a sequence of contiguous, /// UTF-8 encoded bytes ending just before the first zero byte. init(cString nullTerminatedUTF8: UnsafePointer<CChar>) /// Creates a string from the null-terminated sequence of bytes at the given /// pointer. /// /// - Parameters: /// - nullTerminatedCodeUnits: A pointer to a sequence of contiguous code /// units in the encoding specified in `sourceEncoding`, ending just /// before the first zero code unit. /// - sourceEncoding: The encoding in which the code units should be /// interpreted. init<Encoding: Unicode.Encoding>( decodingCString nullTerminatedCodeUnits: UnsafePointer<Encoding.CodeUnit>, as sourceEncoding: Encoding.Type) /// Calls the given closure with a pointer to the contents of the string, /// represented as a null-terminated sequence of UTF-8 code units. /// /// The pointer passed as an argument to `body` is valid only during the /// execution of `withCString(_:)`. Do not store or return the pointer for /// later use. /// /// - Parameter body: A closure with a pointer parameter that points to a /// null-terminated sequence of UTF-8 code units. If `body` has a return /// value, that value is also used as the return value for the /// `withCString(_:)` method. The pointer argument is valid only for the /// duration of the method's execution. /// - Returns: The return value, if any, of the `body` closure parameter. func withCString<Result>( _ body: (UnsafePointer<CChar>) throws -> Result) rethrows -> Result /// Calls the given closure with a pointer to the contents of the string, /// represented as a null-terminated sequence of code units. /// /// The pointer passed as an argument to `body` is valid only during the /// execution of `withCString(encodedAs:_:)`. Do not store or return the /// pointer for later use. /// /// - Parameters: /// - body: A closure with a pointer parameter that points to a /// null-terminated sequence of code units. If `body` has a return /// value, that value is also used as the return value for the /// `withCString(encodedAs:_:)` method. The pointer argument is valid /// only for the duration of the method's execution. /// - targetEncoding: The encoding in which the code units should be /// interpreted. /// - Returns: The return value, if any, of the `body` closure parameter. func withCString<Result, Encoding: Unicode.Encoding>( encodedAs targetEncoding: Encoding.Type, _ body: (UnsafePointer<Encoding.CodeUnit>) throws -> Result ) rethrows -> Result } extension StringProtocol { // TODO(String performance): Make a _SharedString for non-smol Substrings // // TODO(String performance): Provide a closure-based call with stack-allocated // _SharedString for non-smol Substrings // public // @SPI(NSStringAPI.swift) var _ephemeralString: String { @_specialize(where Self == String) @_specialize(where Self == Substring) get { return String(self) } } internal var _gutsSlice: _StringGutsSlice { @_specialize(where Self == String) @_specialize(where Self == Substring) @inline(__always) get { if let str = self as? String { return _StringGutsSlice(str._guts) } if let subStr = self as? Substring { return _StringGutsSlice(subStr._wholeGuts, subStr._offsetRange) } return _StringGutsSlice(String(self)._guts) } } @inlinable internal var _offsetRange: Range<Int> { @inline(__always) get { let start = startIndex let end = endIndex _internalInvariant( start.transcodedOffset == 0 && end.transcodedOffset == 0) return Range(uncheckedBounds: (start._encodedOffset, end._encodedOffset)) } } @inlinable internal var _wholeGuts: _StringGuts { @_specialize(where Self == String) @_specialize(where Self == Substring) @inline(__always) get { if let str = self as? String { return str._guts } if let subStr = self as? Substring { return subStr._wholeGuts } return String(self)._guts } } }
apache-2.0
d7afc3c3cf2eea8e7bb33d35a0d0cd4d
36.869318
80
0.674119
4.68706
false
false
false
false
alessandrostone/RIABrowser
RIABrowser/RealmInAppBrowser.swift
1
3681
// // RealmInAppBrowser.swift // RIABrowser // // Created by Yoshiyuki Tanaka on 2015/04/04. // Copyright (c) 2015 Yoshiyuki Tanaka. All rights reserved. // import UIKit import RealmSwift public enum Position { case LeftTop case LeftBottom case RightTop case RightBottom } public class RealmInAppBrowser : NSObject { private let topMargin:CGFloat = 10 private let leftMargin:CGFloat = 10 private let bottomMargin:CGFloat = -10 private let rightMargin:CGFloat = -10 private var targetViewController:UIViewController? private var launchButton = LaunchBrowserButton() override init() { super.init() launchButton.addTarget(self, action: "pressLaunchButton:", forControlEvents: UIControlEvents.TouchUpInside) } //MARK: Public Method class var sharedInstance : RealmInAppBrowser { struct Static { static let instance : RealmInAppBrowser = RealmInAppBrowser() } return Static.instance } public class func registerClass<T:Object>(type:T.Type) { ObjectExtractor.sharedInstance.registerClass(T) } public class func unregisterClass<T:Object>(type:T.Type) { ObjectExtractor.sharedInstance.unregisterClass(T) } public func setup(realmPath: String) { ObjectExtractor.sharedInstance.realmPath = realmPath } public func showLaunchButton(toViewController: UIViewController) { showLaunchButton(toViewController, position: Position.RightBottom) } public func showLaunchButton(toViewController: UIViewController, position: Position) { launchButton.removeFromSuperview() targetViewController = nil toViewController.view.addSubview(launchButton) targetViewController = toViewController applyConstraints(position) } //MARK:Internal Method func pressLaunchButton(sender: UIButton) { let storyboard = UIStoryboard(name: "RIABrowser", bundle: nil) let viewController = storyboard.instantiateInitialViewController() as! UIViewController targetViewController?.presentViewController(viewController, animated: true, completion: nil) } //MARK:Private Method private func applyConstraints(position: Position) { let horizonalAttribute:NSLayoutAttribute; let horizonalMargin:CGFloat let verticalAttribute:NSLayoutAttribute; let verticalMargin:CGFloat switch position { case .LeftTop: horizonalAttribute = .Left verticalAttribute = .Top horizonalMargin = leftMargin verticalMargin = topMargin case .LeftBottom: horizonalAttribute = .Left verticalAttribute = .Bottom horizonalMargin = leftMargin verticalMargin = bottomMargin case .RightTop: horizonalAttribute = .Right verticalAttribute = .Top horizonalMargin = rightMargin verticalMargin = topMargin case .RightBottom: horizonalAttribute = .Right verticalAttribute = .Bottom horizonalMargin = rightMargin verticalMargin = bottomMargin } targetViewController?.view.addConstraints([ NSLayoutConstraint( item: launchButton, attribute: horizonalAttribute, relatedBy: .Equal, toItem: targetViewController?.view, attribute: horizonalAttribute, multiplier: 1.0, constant: horizonalMargin ), NSLayoutConstraint( item: launchButton, attribute: verticalAttribute, relatedBy: .Equal, toItem: targetViewController?.view, attribute: verticalAttribute, multiplier: 1.0, constant: verticalMargin )] ) targetViewController?.view.updateConstraints() } }
mit
0fbf36eb0df479aaa52b4cef1e8997f8
27.10687
111
0.705515
5.1125
false
false
false
false
itsnauman/RoadToSwift
Project 09 - Search Bar In Table View/Project 09 - Search Bar In Table View/ViewController.swift
1
2130
// // ViewController.swift // Project 09 - Search Bar In Table View // // Created by Nauman Ahmad on 6/24/16. // Copyright © 2016 Nauman Ahmad. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDataSource, UISearchResultsUpdating { @IBOutlet weak var tableview: UITableView! var data = ["Google", "Facebook", "Snapchat", "Yahoo", "Github"] var searchResults: [String]! var searchController: UISearchController! override func viewDidLoad() { super.viewDidLoad() searchController = UISearchController(searchResultsController: nil) searchController.searchResultsUpdater = self searchController.dimsBackgroundDuringPresentation = false // Ensure that the search bar does not remain on the screen if the user navigates to another view controller definesPresentationContext = true let bar = searchController.searchBar bar.searchBarStyle = .Minimal tableview.tableHeaderView = bar } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if self.searchController.active && self.searchController.searchBar.text != "" { return searchResults.count } return data.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) if self.searchController.active && self.searchController.searchBar.text != "" { cell.textLabel?.text = searchResults[indexPath.row] } else { cell.textLabel?.text = data[indexPath.row] } return cell } func updateSearchResultsForSearchController(searchController: UISearchController) { self.searchResults = data.filter({ (item) -> Bool in return item.lowercaseString.containsString(searchController.searchBar.text!.lowercaseString) }) tableview.reloadData() } }
mit
23a55186f19a897c5774c77bd6215319
33.33871
116
0.669798
5.707775
false
false
false
false
ernestopino/SLPagingViewSwift
SLPagingViewSwift/SLPagingViewSwift.swift
3
12666
// // PagingView.swift // TestSwift // // Created by Stefan Lage on 09/01/15. // Copyright (c) 2015 Stefan Lage. All rights reserved. // import UIKit public enum SLNavigationSideItemsStyle: Int { case SLNavigationSideItemsStyleOnBounds = 40 case SLNavigationSideItemsStyleClose = 30 case SLNavigationSideItemsStyleNormal = 20 case SLNavigationSideItemsStyleFar = 10 case SLNavigationSideItemsStyleDefault = 0 case SLNavigationSideItemsStyleCloseToEachOne = -40 } public typealias SLPagingViewMoving = ((subviews: [UIView])-> ()) public typealias SLPagingViewMovingRedefine = ((scrollView: UIScrollView, subviews: NSArray)-> ()) public typealias SLPagingViewDidChanged = ((currentPage: Int)-> ()) public class SLPagingViewSwift: UIViewController, UIScrollViewDelegate { // MARK: - Public properties var views = [Int : UIView]() public var currentPageControlColor: UIColor? public var tintPageControlColor: UIColor? public var pagingViewMoving: SLPagingViewMoving? public var pagingViewMovingRedefine: SLPagingViewMovingRedefine? public var didChangedPage: SLPagingViewDidChanged? public var navigationSideItemsStyle: SLNavigationSideItemsStyle = .SLNavigationSideItemsStyleDefault // MARK: - Private properties private var SCREENSIZE: CGSize { return UIScreen.mainScreen().bounds.size } private var scrollView: UIScrollView! private var pageControl: UIPageControl! private var navigationBarView: UIView = UIView() private var navItems: [UIView] = [] private var needToShowPageControl: Bool = false private var isUserInteraction: Bool = false private var indexSelected: Int = 0 // MARK: - Constructors public required init(coder decoder: NSCoder) { super.init(coder: decoder) } public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) // Here you can init your properties } // MARK: - Constructors with items & views public convenience init(items: [UIView], views: [UIView]) { self.init(items: items, views: views, showPageControl:false, navBarBackground:UIColor.whiteColor()) } public convenience init(items: [UIView], views: [UIView], showPageControl: Bool){ self.init(items: items, views: views, showPageControl:showPageControl, navBarBackground:UIColor.whiteColor()) } /* * SLPagingViewController's constructor * * @param items should contain all subviews of the navigation bar * @param navBarBackground navigation bar's background color * @param views all subviews corresponding to each page * @param showPageControl inform if we need to display the page control in the navigation bar * * @return Instance of SLPagingViewController */ public init(items: [UIView], views: [UIView], showPageControl: Bool, navBarBackground: UIColor) { super.init(nibName: nil, bundle: nil) needToShowPageControl = showPageControl navigationBarView.backgroundColor = navBarBackground isUserInteraction = true for (i, v) in enumerate(items) { let vSize: CGSize = (v as? UILabel)?._slpGetSize() ?? v.frame.size let originX = (self.SCREENSIZE.width/2.0 - vSize.width/2.0) + CGFloat(i * 100) v.frame = CGRectMake(originX, 8, vSize.width, vSize.height) v.tag = i let tap = UITapGestureRecognizer(target: self, action: "tapOnHeader:") v.addGestureRecognizer(tap) v.userInteractionEnabled = true self.navigationBarView.addSubview(v) self.navItems.append(v) } for (i, view) in enumerate(views) { view.tag = i self.views[i] = view } } // MARK: - Constructors with controllers public convenience init(controllers: [UIViewController]){ self.init(controllers: controllers, showPageControl: true, navBarBackground: UIColor.whiteColor()) } public convenience init(controllers: [UIViewController], showPageControl: Bool){ self.init(controllers: controllers, showPageControl: true, navBarBackground: UIColor.whiteColor()) } /* * SLPagingViewController's constructor * * Use controller's title as a navigation item * * @param controllers view controllers containing sall subviews corresponding to each page * @param navBarBackground navigation bar's background color * @param showPageControl inform if we need to display the page control in the navigation bar * * @return Instance of SLPagingViewController */ public convenience init(controllers: [UIViewController], showPageControl: Bool, navBarBackground: UIColor){ var views = [UIView]() var items = [UILabel]() for ctr in controllers { let item = UILabel() item.text = ctr.title views.append(ctr.view) items.append(item) } self.init(items: items, views: views, showPageControl:showPageControl, navBarBackground:navBarBackground) } // MARK: - Constructors with items & controllers public convenience init(items: [UIView], controllers: [UIViewController]){ self.init(items: items, controllers: controllers, showPageControl: true, navBarBackground: UIColor.whiteColor()) } public convenience init(items: [UIView], controllers: [UIViewController], showPageControl: Bool){ self.init(items: items, controllers: controllers, showPageControl: showPageControl, navBarBackground: UIColor.whiteColor()) } /* * SLPagingViewController's constructor * * @param items should contain all subviews of the navigation bar * @param navBarBackground navigation bar's background color * @param controllers view controllers containing sall subviews corresponding to each page * @param showPageControl inform if we need to display the page control in the navigation bar * * @return Instance of SLPagingViewController */ public convenience init(items: [UIView], controllers: [UIViewController], showPageControl: Bool, navBarBackground: UIColor){ var views = [UIView]() for ctr in controllers { views.append(ctr.view) } self.init(items: items, views: views, showPageControl:showPageControl, navBarBackground:navBarBackground) } // MARK: - Life cycle public override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.setupPagingProcess() self.setCurrentIndex(self.indexSelected, animated: false) } public override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() self.navigationBarView.frame = CGRectMake(0, 0, self.SCREENSIZE.width, 44) } // MARK: - Public methods /* * Update the state of the UserInteraction on the navigation bar * * @param activate state you want to set to UserInteraction */ public func updateUserInteractionOnNavigation(active: Bool){ self.isUserInteraction = active } /* * Set the current index page and scroll to its position * * @param index of the wanted page * @param animated animate the moving */ public func setCurrentIndex(index: Int, animated: Bool){ // Be sure we got an existing index if(index < 0 || index > self.navigationBarView.subviews.count-1){ var exc = NSException(name: "Index out of range", reason: "The index is out of range of subviews's countsd!", userInfo: nil) exc.raise() } self.indexSelected = index // Get the right position and update it let xOffset = CGFloat(index) * self.SCREENSIZE.width self.scrollView.setContentOffset(CGPointMake(xOffset, self.scrollView.contentOffset.y), animated: animated) } // MARK: - Internal methods private func setupPagingProcess() { var frame: CGRect = CGRectMake(0, 0, SCREENSIZE.width, self.view.frame.height) self.scrollView = UIScrollView(frame: frame) self.scrollView.backgroundColor = UIColor.clearColor() self.scrollView.pagingEnabled = true self.scrollView.showsHorizontalScrollIndicator = false self.scrollView.showsVerticalScrollIndicator = false self.scrollView.delegate = self self.scrollView.bounces = false self.scrollView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: -80, right: 0) self.view.addSubview(self.scrollView) // Adds all views self.addViews() if(self.needToShowPageControl){ // Make the page control self.pageControl = UIPageControl(frame: CGRectMake(0, 35, 0, 0)) self.pageControl.numberOfPages = self.navigationBarView.subviews.count self.pageControl.currentPage = 0 if self.currentPageControlColor != nil { self.pageControl.currentPageIndicatorTintColor = self.currentPageControlColor } if self.tintPageControlColor != nil { self.pageControl.pageIndicatorTintColor = self.tintPageControlColor } self.navigationBarView.addSubview(self.pageControl) } self.navigationController?.navigationBar.addSubview(self.navigationBarView) } // Loads all views private func addViews() { if self.views.count > 0 { let width = SCREENSIZE.width * CGFloat(self.views.count) let height = self.view.frame.height self.scrollView.contentSize = CGSize(width: width, height: height) var i: Int = 0 while let v = views[i] { v.frame = CGRectMake(self.SCREENSIZE.width * CGFloat(i), 0, self.SCREENSIZE.width, self.SCREENSIZE.height) self.scrollView.addSubview(v) i++ } } } private func sendNewIndex(scrollView: UIScrollView){ let xOffset = Float(scrollView.contentOffset.x) var currentIndex = (Int(roundf(xOffset)) % (self.navigationBarView.subviews.count * Int(self.SCREENSIZE.width))) / Int(self.SCREENSIZE.width) if self.needToShowPageControl && self.pageControl.currentPage != currentIndex { self.pageControl.currentPage = currentIndex self.didChangedPage?(currentPage: currentIndex) } } func getOriginX(vSize: CGSize, idx: CGFloat, distance: CGFloat, xOffset: CGFloat) -> CGFloat{ var result = self.SCREENSIZE.width / 2.0 - vSize.width/2.0 result += (idx * distance) result -= xOffset / (self.SCREENSIZE.width / distance) return result } // Scroll to the view tapped func tapOnHeader(recognizer: UITapGestureRecognizer){ if let key = recognizer.view?.tag, view = self.views[key] where self.isUserInteraction { self.scrollView.scrollRectToVisible(view.frame, animated: true) } } // MARK: - UIScrollViewDelegate public func scrollViewDidScroll(scrollView: UIScrollView) { let xOffset = scrollView.contentOffset.x let distance = CGFloat(100 + self.navigationSideItemsStyle.rawValue) for (i, v) in enumerate(self.navItems) { let vSize = v.frame.size let originX = self.getOriginX(vSize, idx: CGFloat(i), distance: CGFloat(distance), xOffset: xOffset) v.frame = CGRectMake(originX, 8, vSize.width, vSize.height) } self.pagingViewMovingRedefine?(scrollView: scrollView, subviews: self.navItems) self.pagingViewMoving?(subviews: self.navItems) } public func scrollViewDidEndDecelerating(scrollView: UIScrollView) { self.sendNewIndex(scrollView) } public func scrollViewDidEndScrollingAnimation(scrollView: UIScrollView) { self.sendNewIndex(scrollView) } } extension UILabel { func _slpGetSize() -> CGSize? { return (text as NSString?)?.sizeWithAttributes([NSFontAttributeName: font]) } }
mit
14cea7224301427eb70488e283a3d151
41.083056
149
0.650482
4.786848
false
false
false
false
amraboelela/SwiftLevelDB
Sources/SwiftLevelDB/Extensions/Array.swift
1
1258
// // Array.swift // SwiftLevelDB // // Created by Amr Aboelela on 4/25/18. // Copyright © 2018 Amr Aboelela. // import Foundation extension Array where Element: Equatable { // Remove first collection element that is equal to the given `object`: mutating public func remove(object: Element) { if let index = firstIndex(of: object) { remove(at: index) } } public func asyncFilter(closure: (Element) async -> Bool) async -> Array { var result = [Element]() for item in self { if await closure(item) { result.append(item) } } return result } public func asyncCompactMap<Element2>(closure: (Element) async -> Element2?) async -> [Element2] { var result = [Element2]() for item in self { if let item2 = await closure(item) { result.append(item2) } } return result } public mutating func asyncRemoveAll(closure: (Element) async -> Bool) async { var result = [Element]() for item in self { if await !closure(item) { result.append(item) } } self = result } }
mit
095ab0ad2804a67967b3bb032365eb20
24.653061
102
0.538584
4.246622
false
false
false
false
RideBeeline/GpxKit
GpxKit/Gpx+Parser.swift
1
2147
// // Copyright © 2017 Beeline. All rights reserved. // import CoreLocation import SWXMLHash public extension Gpx { init(data: Data) throws { let gpx = SWXMLHash.parse(data)["gpx"] self.creator = gpx["creator"].element?.text ?? "" self.metadata = gpx["metadata"].metadata() self.waypoints = try gpx["wpt"].all.map { waypoint in try waypoint.point() } self.route = try gpx["rte"]["rtept"].all.map { routePoint in try routePoint.point() } self.tracks = try gpx["trk"].all.map { track in Track(segments: try track["trkseg"].all.map { trackSegment in try trackSegment["trkpt"].all.map { trackPoint in try trackPoint.point() } } ) } } } fileprivate extension XMLIndexer { func metadata() -> Metadata? { guard element != nil else { return nil } let name = self["name"].element?.text let description = self["description"].element?.text return Metadata(name: name, description: description) } func point() throws -> Point { guard let element = element else { throw IndexingError.error } let latitude = try element.attributeValue(by: "lat") let longitude = try element.attributeValue(by: "lon") let elevation = self["ele"].element?.text let time = self["time"].element?.text return Point( CLLocationCoordinate2D(latitude: latitude, longitude: longitude), elevation: elevation != nil ? Double(elevation!) : nil, time: time != nil ? DateFormatter.iso8601.date(from: time!) : nil ) } } fileprivate extension XMLElement { func attributeValue(by name: String) throws -> Double { guard let attribute = attribute(by: name) else { throw IndexingError.attribute(attr: name) } guard let value = Double(attribute.text) else { throw IndexingError.attributeValue(attr: name, value: attribute.text) } return value } }
mit
da2b0fcb01b8d802c67e451c705227a6
28.805556
81
0.576887
4.54661
false
false
false
false
brentdax/swift
test/SILGen/protocol_with_superclass.swift
1
10740
// RUN: %target-swift-emit-silgen -enable-sil-ownership %s | %FileCheck %s // RUN: %target-swift-frontend -emit-ir -enable-sil-ownership %s // Protocols with superclass-constrained Self. class Concrete { typealias ConcreteAlias = String func concreteMethod(_: ConcreteAlias) {} } class Generic<T> : Concrete { typealias GenericAlias = (T, T) func genericMethod(_: GenericAlias) {} } protocol BaseProto {} protocol ProtoRefinesClass : Generic<Int>, BaseProto { func requirementUsesClassTypes(_: ConcreteAlias, _: GenericAlias) } extension ProtoRefinesClass { // CHECK-LABEL: sil hidden @$s24protocol_with_superclass17ProtoRefinesClassPAAE019extensionMethodUsesF5TypesyySS_Si_SittF : $@convention(method) <Self where Self : ProtoRefinesClass> (@guaranteed String, Int, Int, @guaranteed Self) -> () func extensionMethodUsesClassTypes(_ x: ConcreteAlias, _ y: GenericAlias) { _ = ConcreteAlias.self _ = GenericAlias.self // CHECK: [[SELF:%.*]] = copy_value %3 : $Self // CHECK-NEXT: [[UPCAST:%.*]] = upcast [[SELF]] : $Self to $Generic<Int> // CHECK-NEXT: [[UPCAST2:%.*]] = upcast [[UPCAST]] : $Generic<Int> to $Concrete // CHECK-NEXT: [[BORROW:%.*]] = begin_borrow [[UPCAST2]] : $Concrete // CHECK-NEXT: [[METHOD:%.*]] = class_method [[BORROW:%.*]] : $Concrete, #Concrete.concreteMethod!1 : (Concrete) -> (String) -> (), $@convention(method) (@guaranteed String, @guaranteed Concrete) -> () // CHECK-NEXT: apply [[METHOD]](%0, [[BORROW]]) // CHECK-NEXT: end_borrow [[BORROW]] // CHECK-NEXT: destroy_value [[UPCAST2]] concreteMethod(x) // CHECK: [[SELF:%.*]] = copy_value %3 : $Self // CHECK-NEXT: [[UPCAST:%.*]] = upcast [[SELF]] : $Self to $Generic<Int> // CHECK-NEXT: [[BORROW:%.*]] = begin_borrow [[UPCAST]] : $Generic<Int> // CHECK: [[METHOD:%.*]] = class_method [[BORROW:%.*]] : $Generic<Int>, #Generic.genericMethod!1 : <T> (Generic<T>) -> ((T, T)) -> (), $@convention(method) <τ_0_0> (@in_guaranteed τ_0_0, @in_guaranteed τ_0_0, @guaranteed Generic<τ_0_0>) -> () // CHECK-NEXT: apply [[METHOD]]<Int>({{.*}}, [[BORROW]]) // CHECK: end_borrow [[BORROW]] // CHECK-NEXT: destroy_value [[UPCAST]] genericMethod(y) // CHECK: [[SELF:%.*]] = copy_value %3 : $Self // CHECK-NEXT: [[UPCAST:%.*]] = upcast [[SELF]] : $Self to $Generic<Int> // CHECK-NEXT: destroy_value [[UPCAST]] : $Generic<Int> let _: Generic<Int> = self // CHECK: [[SELF:%.*]] = copy_value %3 : $Self // CHECK-NEXT: [[UPCAST:%.*]] = upcast [[SELF]] : $Self to $Generic<Int> // CHECK-NEXT: [[UPCAST2:%.*]] = upcast [[UPCAST]] : $Generic<Int> to $Concrete // CHECK-NEXT: destroy_value [[UPCAST2]] : $Concrete let _: Concrete = self // CHECK: [[BOX:%.*]] = alloc_stack $BaseProto // CHECK-NEXT: [[SELF:%.*]] = copy_value %3 : $Self // CHECK-NEXT: [[ADDR:%.*]] = init_existential_addr [[BOX]] : $*BaseProto, $Self // CHECK-NEXT: store [[SELF]] to [init] [[ADDR]] : $*Self // CHECK-NEXT: destroy_addr [[BOX]] : $*BaseProto // CHECK-NEXT: dealloc_stack [[BOX]] : $*BaseProto let _: BaseProto = self // CHECK: [[SELF:%.*]] = copy_value %3 : $Self // CHECK-NEXT: [[EXISTENTIAL:%.*]] = init_existential_ref [[SELF]] : $Self : $Self, $Generic<Int> & BaseProto let _: BaseProto & Generic<Int> = self // CHECK: [[SELF:%.*]] = copy_value %3 : $Self // CHECK-NEXT: [[EXISTENTIAL:%.*]] = init_existential_ref [[SELF]] : $Self : $Self, $Concrete & BaseProto let _: BaseProto & Concrete = self // CHECK: return } } // CHECK-LABEL: sil hidden @$s24protocol_with_superclass22usesProtoRefinesClass1yyAA0eF5Class_pF : $@convention(thin) (@guaranteed ProtoRefinesClass) -> () func usesProtoRefinesClass1(_ t: ProtoRefinesClass) { let x: ProtoRefinesClass.ConcreteAlias = "hi" _ = ProtoRefinesClass.ConcreteAlias.self t.concreteMethod(x) let y: ProtoRefinesClass.GenericAlias = (1, 2) _ = ProtoRefinesClass.GenericAlias.self t.genericMethod(y) t.requirementUsesClassTypes(x, y) let _: Generic<Int> = t let _: Concrete = t let _: BaseProto = t let _: BaseProto & Generic<Int> = t let _: BaseProto & Concrete = t } // CHECK-LABEL: sil hidden @$s24protocol_with_superclass22usesProtoRefinesClass2yyxAA0eF5ClassRzlF : $@convention(thin) <T where T : ProtoRefinesClass> (@guaranteed T) -> () func usesProtoRefinesClass2<T : ProtoRefinesClass>(_ t: T) { let x: T.ConcreteAlias = "hi" _ = T.ConcreteAlias.self t.concreteMethod(x) let y: T.GenericAlias = (1, 2) _ = T.GenericAlias.self t.genericMethod(y) t.requirementUsesClassTypes(x, y) let _: Generic<Int> = t let _: Concrete = t let _: BaseProto = t let _: BaseProto & Generic<Int> = t let _: BaseProto & Concrete = t } class GoodConformingClass : Generic<Int>, ProtoRefinesClass { // CHECK-LABEL: sil hidden @$s24protocol_with_superclass19GoodConformingClassC015requirementUsesF5TypesyySS_Si_SittF : $@convention(method) (@guaranteed String, Int, Int, @guaranteed GoodConformingClass) -> () func requirementUsesClassTypes(_ x: ConcreteAlias, _ y: GenericAlias) { _ = ConcreteAlias.self _ = GenericAlias.self concreteMethod(x) genericMethod(y) } } protocol ProtoRefinesProtoWithClass : ProtoRefinesClass {} extension ProtoRefinesProtoWithClass { // CHECK-LABEL: sil hidden @$s24protocol_with_superclass012ProtoRefinesD9WithClassPAAE026anotherExtensionMethodUsesG5TypesyySS_Si_SittF : $@convention(method) <Self where Self : ProtoRefinesProtoWithClass> (@guaranteed String, Int, Int, @guaranteed Self) -> () func anotherExtensionMethodUsesClassTypes(_ x: ConcreteAlias, _ y: GenericAlias) { _ = ConcreteAlias.self _ = GenericAlias.self concreteMethod(x) genericMethod(y) let _: Generic<Int> = self let _: Concrete = self let _: BaseProto = self let _: BaseProto & Generic<Int> = self let _: BaseProto & Concrete = self } } // CHECK-LABEL: sil hidden @$s24protocol_with_superclass016usesProtoRefinesE10WithClass1yyAA0efeG5Class_pF : $@convention(thin) (@guaranteed ProtoRefinesProtoWithClass) -> () func usesProtoRefinesProtoWithClass1(_ t: ProtoRefinesProtoWithClass) { let x: ProtoRefinesProtoWithClass.ConcreteAlias = "hi" _ = ProtoRefinesProtoWithClass.ConcreteAlias.self t.concreteMethod(x) let y: ProtoRefinesProtoWithClass.GenericAlias = (1, 2) _ = ProtoRefinesProtoWithClass.GenericAlias.self t.genericMethod(y) t.requirementUsesClassTypes(x, y) let _: Generic<Int> = t let _: Concrete = t let _: BaseProto = t let _: BaseProto & Generic<Int> = t let _: BaseProto & Concrete = t } // CHECK-LABEL: sil hidden @$s24protocol_with_superclass016usesProtoRefinesE10WithClass2yyxAA0efeG5ClassRzlF : $@convention(thin) <T where T : ProtoRefinesProtoWithClass> (@guaranteed T) -> () func usesProtoRefinesProtoWithClass2<T : ProtoRefinesProtoWithClass>(_ t: T) { let x: T.ConcreteAlias = "hi" _ = T.ConcreteAlias.self t.concreteMethod(x) let y: T.GenericAlias = (1, 2) _ = T.GenericAlias.self t.genericMethod(y) t.requirementUsesClassTypes(x, y) let _: Generic<Int> = t let _: Concrete = t let _: BaseProto = t let _: BaseProto & Generic<Int> = t let _: BaseProto & Concrete = t } class ClassWithInits<T> { init(notRequiredInit: ()) {} required init(requiredInit: ()) {} } protocol ProtocolWithClassInits : ClassWithInits<Int> {} // CHECK-LABEL: sil hidden @$s24protocol_with_superclass26useProtocolWithClassInits1yyAA0efG5Inits_pXpF : $@convention(thin) (@thick ProtocolWithClassInits.Type) -> () func useProtocolWithClassInits1(_ t: ProtocolWithClassInits.Type) { // CHECK: [[OPENED:%.*]] = open_existential_metatype %0 : $@thick ProtocolWithClassInits.Type // CHECK-NEXT: [[UPCAST:%.*]] = upcast [[OPENED]] : $@thick (@opened("{{.*}}") ProtocolWithClassInits).Type to $@thick ClassWithInits<Int>.Type // CHECK-NEXT: [[METHOD:%.*]] = class_method [[UPCAST]] : $@thick ClassWithInits<Int>.Type, #ClassWithInits.init!allocator.1 : <T> (ClassWithInits<T>.Type) -> (()) -> ClassWithInits<T>, $@convention(method) <τ_0_0> (@thick ClassWithInits<τ_0_0>.Type) -> @owned ClassWithInits<τ_0_0> // CHECK-NEXT: [[RESULT:%.*]] = apply [[METHOD]]<Int>([[UPCAST]]) // CHECK-NEXT: [[CAST:%.*]] = unchecked_ref_cast [[RESULT]] : $ClassWithInits<Int> to $@opened("{{.*}}") ProtocolWithClassInits // CHECK-NEXT: [[EXISTENTIAL:%.*]] = init_existential_ref [[CAST]] : $@opened("{{.*}}") ProtocolWithClassInits : $@opened("{{.*}}") ProtocolWithClassInits, $ProtocolWithClassInits // CHECK-NEXT: destroy_value [[EXISTENTIAL]] let _: ProtocolWithClassInits = t.init(requiredInit: ()) } // CHECK-LABEL: sil hidden @$s24protocol_with_superclass26useProtocolWithClassInits2yyxmAA0efG5InitsRzlF : $@convention(thin) <T where T : ProtocolWithClassInits> (@thick T.Type) -> () func useProtocolWithClassInits2<T : ProtocolWithClassInits>(_ t: T.Type) { let _: T = T(requiredInit: ()) let _: T = t.init(requiredInit: ()) } protocol ProtocolRefinesClassInits : ProtocolWithClassInits {} // CHECK-LABEL: sil hidden @$s24protocol_with_superclass29useProtocolRefinesClassInits1yyAA0efG5Inits_pXpF : $@convention(thin) (@thick ProtocolRefinesClassInits.Type) -> () func useProtocolRefinesClassInits1(_ t: ProtocolRefinesClassInits.Type) { let _: ProtocolRefinesClassInits = t.init(requiredInit: ()) } // CHECK-LABEL: sil hidden @$s24protocol_with_superclass29useProtocolRefinesClassInits2yyxmAA0efG5InitsRzlF : $@convention(thin) <T where T : ProtocolRefinesClassInits> (@thick T.Type) -> () func useProtocolRefinesClassInits2<T : ProtocolRefinesClassInits>(_ t: T.Type) { let _: T = T(requiredInit: ()) let _: T = t.init(requiredInit: ()) } class ClassWithDefault<T> { func makeT() -> T { while true {} } } protocol SillyDefault : ClassWithDefault<Int> { func makeT() -> Int } class ConformsToSillyDefault : ClassWithDefault<Int>, SillyDefault {} // CHECK-LABEL: sil private [transparent] [thunk] @$s24protocol_with_superclass22ConformsToSillyDefaultCAA0fG0A2aDP5makeTSiyFTW : $@convention(witness_method: SillyDefault) (@guaranteed ConformsToSillyDefault) -> Int // CHECK: class_method %1 : $ClassWithDefault<Int>, #ClassWithDefault.makeT!1 : <T> (ClassWithDefault<T>) -> () -> T, $@convention(method) <τ_0_0> (@guaranteed ClassWithDefault<τ_0_0>) -> @out τ_0_0 // CHECK: return // CHECK-LABEL: sil_witness_table hidden ConformsToSillyDefault: SillyDefault module protocol_with_superclass { // CHECK-NEXT: method #SillyDefault.makeT!1: <Self where Self : SillyDefault> (Self) -> () -> Int : @$s24protocol_with_superclass22ConformsToSillyDefaultCAA0fG0A2aDP5makeTSiyFTW // CHECK-NEXT: }
apache-2.0
ccbf279931adc4a7173ca3f25d99099d
41.579365
284
0.679124
3.582638
false
false
false
false
domenicosolazzo/practice-swift
CoreData/Deleting data from CoreData/Deleting data from CoreData/AppDelegate.swift
1
9022
// // AppDelegate.swift // Deleting data from CoreData // // Created by Domenico Solazzo on 17/05/15. // License MIT // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? //- MARK: Helper methods func createNewPerson(firstName: String, lastName: String, age:Int) -> Bool{ let entityName = NSStringFromClass(Person.classForCoder()) let newPerson = NSEntityDescription.insertNewObjectForEntityForName(entityName, inManagedObjectContext: managedObjectContext!) as! Person (newPerson.firstName, newPerson.lastName, newPerson.age) = (firstName, lastName, age) var savingError: NSError? do { try managedObjectContext!.save() print("Successfully saved...") } catch let error1 as NSError { savingError = error1 if let error = savingError{ print("Failed to save the new person. Error = \(error)") } } return false } //- MARK: Application Delegate func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. /* Create the entities first */ createNewPerson("Anthony", lastName: "Robbins", age: 52) createNewPerson("Richard", lastName: "Branson", age: 62) /* Tell the request that we want to read the contents of the Person entity */ /* Create the fetch request first */ let fetchRequest = NSFetchRequest(entityName: "Person") var requestError: NSError? /* And execute the fetch request on the context */ let persons = (try! managedObjectContext!.executeFetchRequest(fetchRequest)) as! [Person] if persons.count > 0{ /* Delete the last person in the array */ let lastPerson = (persons as NSArray).lastObject as! Person managedObjectContext!.deleteObject(lastPerson) // .deleted check if an entity has been deleted in the context if lastPerson.deleted{ print("Successfully deleted the last person...") var savingError: NSError? do { try managedObjectContext!.save() print("Successfully saved the context") } catch let error1 as NSError { savingError = error1 if let error = savingError{ print("Failed to save the context. Error = \(error)") } } } else { print("Failed to delete the last person") } }else{ print("Could not find any Person entity in the context") } return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "com.domenicosolazzo.swift.Deleting_data_from_CoreData" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("Deleting_data_from_CoreData", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("Deleting_data_from_CoreData.sqlite") var error: NSError? = nil var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch var error1 as NSError { error = error1 coordinator = nil // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } catch { fatalError() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext? = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator if coordinator == nil { return nil } var managedObjectContext = NSManagedObjectContext() managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if let moc = self.managedObjectContext { var error: NSError? = nil if moc.hasChanges { do { try moc.save() } catch let error1 as NSError { error = error1 // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } } } } }
mit
72cf9b5a8116c9bbc51b390c4889ff5a
46.235602
290
0.652073
5.873698
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/InstantPageTableItem.swift
1
26399
import Foundation import TelegramCore import Postbox import TGUIKit private struct TableSide: OptionSet { var rawValue: Int32 = 0 static let top = TableSide(rawValue: 1 << 0) static let left = TableSide(rawValue: 1 << 1) static let right = TableSide(rawValue: 1 << 2) static let bottom = TableSide(rawValue: 1 << 3) var uiRectCorner: NSRectCorner { var corners: NSRectCorner = [] if self.contains(.top) && self.contains(.left) { corners.insert(.topLeft) } if self.contains(.top) && self.contains(.right) { corners.insert(.topRight) } if self.contains(.bottom) && self.contains(.left) { corners.insert(.bottomLeft) } if self.contains(.bottom) && self.contains(.right) { corners.insert(.bottomRight) } return corners } } private extension TableHorizontalAlignment { var textAlignment: NSTextAlignment { switch self { case .left: return .left case .center: return .center case .right: return .right } } } private struct TableCellPosition { let row: Int let column: Int } private struct InstantPageTableCellItem { let position: TableCellPosition let cell: InstantPageTableCell let frame: CGRect let filled: Bool let textItem: InstantPageTextItem? let additionalItems: [InstantPageItem] let adjacentSides: TableSide func withRowHeight(_ height: CGFloat) -> InstantPageTableCellItem { var frame = self.frame frame = CGRect(x: frame.minX, y: frame.minY, width: frame.width, height: height) return InstantPageTableCellItem(position: position, cell: self.cell, frame: frame, filled: self.filled, textItem: self.textItem, additionalItems: self.additionalItems, adjacentSides: self.adjacentSides) } func withRTL(_ totalWidth: CGFloat) -> InstantPageTableCellItem { var frame = self.frame frame = CGRect(x: totalWidth - frame.minX - frame.width, y: frame.minY, width: frame.width, height: frame.height) var adjacentSides = self.adjacentSides if adjacentSides.contains(.left) && !adjacentSides.contains(.right) { adjacentSides.remove(.left) adjacentSides.insert(.right) } else if adjacentSides.contains(.right) && !adjacentSides.contains(.left) { adjacentSides.remove(.right) adjacentSides.insert(.left) } return InstantPageTableCellItem(position: position, cell: self.cell, frame: frame, filled: self.filled, textItem: self.textItem, additionalItems: self.additionalItems, adjacentSides: adjacentSides) } var verticalAlignment: TableVerticalAlignment { return self.cell.verticalAlignment } var colspan: Int { return self.cell.colspan > 1 ? Int(clamping: self.cell.colspan) : 1 } var rowspan: Int { return self.cell.rowspan > 1 ? Int(clamping: self.cell.rowspan) : 1 } } private let tableCellInsets = NSEdgeInsetsMake(14.0, 12.0, 14.0, 12.0) private let tableBorderWidth: CGFloat = 1.0 private let tableCornerRadius: CGFloat = 5.0 final class InstantPageTableItem: InstantPageScrollableItem { var hasLinks: Bool = false var isInteractive: Bool = false func linkSelectionViews() -> [InstantPageLinkSelectionView] { return [] } var frame: CGRect let totalWidth: CGFloat let horizontalInset: CGFloat let medias: [InstantPageMedia] = [] let wantsView: Bool = true let separatesTiles: Bool = false let theme: InstantPageTheme let isRTL: Bool fileprivate let cells: [InstantPageTableCellItem] private let borderWidth: CGFloat let anchors: [String: (CGFloat, Bool)] fileprivate init(frame: CGRect, totalWidth: CGFloat, horizontalInset: CGFloat, borderWidth: CGFloat, theme: InstantPageTheme, cells: [InstantPageTableCellItem], rtl: Bool) { self.frame = frame self.totalWidth = totalWidth self.horizontalInset = horizontalInset self.borderWidth = borderWidth self.theme = theme self.cells = cells self.isRTL = rtl var anchors: [String: (CGFloat, Bool)] = [:] for cell in cells { if let textItem = cell.textItem { for (anchor, (lineIndex, empty)) in textItem.anchors { if anchors[anchor] == nil { let textItemFrame = textItem.frame.offsetBy(dx: cell.frame.minX, dy: cell.frame.minY) let offset = textItemFrame.minY + textItem.lines[lineIndex].frame.minY anchors[anchor] = (offset, empty) } } } } self.anchors = anchors } func itemsIn( _ rect: NSRect, items: [InstantPageItem] = []) -> [InstantPageItem] { var items: [InstantPageItem] = items for cell in cells { if let textItem = cell.textItem, cell.frame.intersects(rect) { items.append(textItem) } } return items } func itemFrameSkipCells(_ item: InstantPageTextItem, effectiveRect: NSRect) -> NSRect { for cell in cells { if let textItem = cell.textItem, textItem === item { return item.frame.offsetBy(dx: cell.frame.minX, dy: cell.frame.minY).offsetBy(dx: effectiveRect.minX + horizontalInset, dy: effectiveRect.minY) } } return item.frame } var contentSize: CGSize { return CGSize(width: self.totalWidth, height: self.frame.height) } func drawInTile(context: CGContext) { for cell in self.cells { if cell.textItem == nil && cell.additionalItems.isEmpty { continue } context.saveGState() context.translateBy(x: cell.frame.minX, y: cell.frame.minY) let hasBorder = self.borderWidth > 0.0 let bounds = CGRect(origin: CGPoint(), size: cell.frame.size) var path: CGPath? if !cell.adjacentSides.isEmpty { path = CGContext.round(frame: bounds, cornerRadius: tableCornerRadius, rectCorner: cell.adjacentSides.uiRectCorner) // path = NSBezierPath(roundedRect: bounds, byRoundingCorners: cell.adjacentSides.uiRectCorner, cornerRadius: CGSize(width: tableCornerRadius, height: tableCornerRadius)) } if cell.filled { context.setFillColor(self.theme.tableHeaderColor.cgColor) } if self.borderWidth > 0.0 { context.setStrokeColor(self.theme.tableBorderColor.cgColor) context.setLineWidth(borderWidth) } if let path = path { context.addPath(path) var drawMode: CGPathDrawingMode? switch (cell.filled, hasBorder) { case (true, false): drawMode = .fill case (true, true): drawMode = .fillStroke case (false, true): drawMode = .stroke default: break } if let drawMode = drawMode { context.drawPath(using: drawMode) } } else { if cell.filled { context.fill(bounds) } if hasBorder { context.stroke(bounds) } } if let textItem = cell.textItem { textItem.drawInTile(context: context) } context.restoreGState() } } func matchesAnchor(_ anchor: String) -> Bool { return false } func view(arguments: InstantPageItemArguments, currentExpandedDetails: [Int : Bool]?) -> (InstantPageView & NSView)? { var additionalViews: [InstantPageView] = [] for cell in self.cells { for item in cell.additionalItems { if item.wantsView { if let view = item.view(arguments: arguments, currentExpandedDetails: nil) { view.frame = item.frame.offsetBy(dx: cell.frame.minX, dy: cell.frame.minY) additionalViews.append(view) } } } } return InstantPageScrollableView(item: self, arguments: arguments, additionalViews: additionalViews) } func matchesView(_ node: InstantPageView) -> Bool { if let node = node as? InstantPageScrollableView { return node.item === self } return false } func distanceThresholdGroup() -> Int? { return nil } func distanceThresholdWithGroupCount(_ count: Int) -> CGFloat { return 0.0 } // func linkSelectionRects(at point: CGPoint) -> [CGRect] { // for cell in self.cells { // if let item = cell.textItem, item.selectable, item.frame.insetBy(dx: -tableCellInsets.left, dy: -tableCellInsets.top).contains(point.offsetBy(dx: -cell.frame.minX - self.horizontalInset, dy: -cell.frame.minY)) { // let rects = item.linkSelectionRects(at: point.offsetBy(dx: -cell.frame.minX - self.horizontalInset - item.frame.minX, dy: -cell.frame.minY - item.frame.minY)) // return rects.map { $0.offsetBy(dx: cell.frame.minX + item.frame.minX + self.horizontalInset, dy: cell.frame.minY + item.frame.minY) } // } // } // return [] // } func textItemAtLocation(_ location: CGPoint) -> (InstantPageTextItem, CGPoint)? { for cell in self.cells { if let item = cell.textItem, item.selectable, item.frame.insetBy(dx: -tableCellInsets.left, dy: -tableCellInsets.top).contains(location.offsetBy(dx: -cell.frame.minX - self.horizontalInset, dy: -cell.frame.minY)) { return (item, cell.frame.origin.offsetBy(dx: self.horizontalInset, dy: 0.0)) } } return nil } } private struct TableRow { var minColumnWidths: [Int : CGFloat] var maxColumnWidths: [Int : CGFloat] } private func offsetForHorizontalAlignment(_ alignment: TableHorizontalAlignment, width: CGFloat, boundingWidth: CGFloat, insets: NSEdgeInsets) -> CGFloat { switch alignment { case .left: return insets.left case .center: return (boundingWidth - width) / 2.0 case .right: return boundingWidth - width - insets.right } } private func offestForVerticalAlignment(_ verticalAlignment: TableVerticalAlignment, height: CGFloat, boundingHeight: CGFloat, insets: NSEdgeInsets) -> CGFloat { switch verticalAlignment { case .top: return insets.top case .middle: return (boundingHeight - height) / 2.0 case .bottom: return boundingHeight - height - insets.bottom } } func layoutTableItem(rtl: Bool, rows: [InstantPageTableRow], styleStack: InstantPageTextStyleStack, theme: InstantPageTheme, bordered: Bool, striped: Bool, boundingWidth: CGFloat, horizontalInset: CGFloat, media: [MediaId: Media], webpage: TelegramMediaWebpage) -> InstantPageTableItem { if rows.count == 0 { return InstantPageTableItem(frame: CGRect(), totalWidth: 0.0, horizontalInset: 0.0, borderWidth: 0.0, theme: theme, cells: [], rtl: rtl) } let borderWidth = bordered ? tableBorderWidth : 0.0 let totalCellPadding = tableCellInsets.left + tableCellInsets.right let cellWidthLimit = boundingWidth - totalCellPadding var tableRows: [TableRow] = [] var columnCount: Int = 0 var columnSpans: [Range<Int> : (CGFloat, CGFloat)] = [:] var rowSpans: [Int : [(Int, Int)]] = [:] var r: Int = 0 for row in rows { var minColumnWidths: [Int : CGFloat] = [:] var maxColumnWidths: [Int : CGFloat] = [:] var i: Int = 0 for cell in row.cells { if let rowSpan = rowSpans[r] { for columnAndSpan in rowSpan { if columnAndSpan.0 == i { i += columnAndSpan.1 } else { break } } } var minCellWidth: CGFloat = 1.0 var maxCellWidth: CGFloat = 1.0 if let text = cell.text { if let shortestTextItem = layoutTextItemWithString(attributedStringForRichText(text, styleStack: styleStack, boundingWidth: cellWidthLimit - totalCellPadding), boundingWidth: cellWidthLimit, offset: CGPoint(), media: media, webpage: webpage, minimizeWidth: true).0 { minCellWidth = shortestTextItem.effectiveWidth() + totalCellPadding } if let longestTextItem = layoutTextItemWithString(attributedStringForRichText(text, styleStack: styleStack, boundingWidth: cellWidthLimit - totalCellPadding), boundingWidth: cellWidthLimit, offset: CGPoint(), media: media, webpage: webpage).0 { maxCellWidth = max(minCellWidth, longestTextItem.effectiveWidth() + totalCellPadding) } } if cell.colspan > 1 { minColumnWidths[i] = 1.0 maxColumnWidths[i] = 1.0 let spanRange = i ..< i + Int(cell.colspan) if let (minSpanWidth, maxSpanWidth) = columnSpans[spanRange] { columnSpans[spanRange] = (max(minSpanWidth, minCellWidth), max(maxSpanWidth, maxCellWidth)) } else { columnSpans[spanRange] = (minCellWidth, maxCellWidth) } } else { minColumnWidths[i] = minCellWidth maxColumnWidths[i] = maxCellWidth } let colspan = cell.colspan > 1 ? Int(clamping: cell.colspan) : 1 if cell.rowspan > 1 { for j in r ..< r + Int(cell.rowspan) { if rowSpans[j] == nil { rowSpans[j] = [(i, colspan)] } else { rowSpans[j]!.append((i, colspan)) } } } i += colspan } tableRows.append(TableRow(minColumnWidths: minColumnWidths, maxColumnWidths: maxColumnWidths)) columnCount = max(columnCount, row.cells.count) r += 1 } let maxContentWidth = boundingWidth - borderWidth var availableWidth = maxContentWidth var minColumnWidths: [Int : CGFloat] = [:] var maxColumnWidths: [Int : CGFloat] = [:] var maxTotalWidth: CGFloat = 0.0 for i in 0 ..< columnCount { var minWidth: CGFloat = 1.0 var maxWidth: CGFloat = 1.0 for row in tableRows { if let columnWidth = row.minColumnWidths[i] { minWidth = max(minWidth, columnWidth) } if let columnWidth = row.maxColumnWidths[i] { maxWidth = max(maxWidth, columnWidth) } } minColumnWidths[i] = minWidth maxColumnWidths[i] = maxWidth availableWidth -= minWidth maxTotalWidth += maxWidth } for (range, span) in columnSpans { let (minSpanWidth, maxSpanWidth) = span var minWidth: CGFloat = 0.0 var maxWidth: CGFloat = 0.0 for i in range { if let columnWidth = minColumnWidths[i] { minWidth += columnWidth } if let columnWidth = maxColumnWidths[i] { maxWidth += columnWidth } } if minWidth < minSpanWidth { let delta = minSpanWidth - minWidth for i in range { if let columnWidth = minColumnWidths[i] { let growth = floor(delta / CGFloat(range.count)) minColumnWidths[i] = columnWidth + growth availableWidth -= growth } } } if maxWidth < maxSpanWidth { let delta = maxSpanWidth - maxWidth for i in range { if let columnWidth = maxColumnWidths[i] { let growth = round(delta / CGFloat(range.count)) maxColumnWidths[i] = columnWidth + growth maxTotalWidth += growth } } } } var totalWidth = maxTotalWidth var finalColumnWidths: [Int : CGFloat] = [:] let widthToDistribute: CGFloat if availableWidth > 0 { widthToDistribute = availableWidth finalColumnWidths = minColumnWidths } else { widthToDistribute = maxContentWidth - maxTotalWidth finalColumnWidths = maxColumnWidths } if widthToDistribute > 0.0 { var distributedWidth = widthToDistribute for i in 0 ..< finalColumnWidths.count { var width = finalColumnWidths[i]! let maxWidth = maxColumnWidths[i]! let growth = min(round(widthToDistribute * maxWidth / maxTotalWidth), distributedWidth) width += growth distributedWidth -= growth finalColumnWidths[i] = width } totalWidth = boundingWidth } else { totalWidth += borderWidth } var finalizedCells: [InstantPageTableCellItem] = [] var origin: CGPoint = CGPoint(x: borderWidth / 2.0, y: borderWidth / 2.0) var totalHeight: CGFloat = 0.0 var rowHeights: [Int : CGFloat] = [:] var awaitingSpanCells: [Int : [(Int, InstantPageTableCellItem)]] = [:] for i in 0 ..< rows.count { let row = rows[i] var maxRowHeight: CGFloat = 0.0 var isEmptyRow = true origin.x = borderWidth / 2.0 var k: Int = 0 var rowCells: [InstantPageTableCellItem] = [] for cell in row.cells { if let cells = awaitingSpanCells[i] { isEmptyRow = false for colAndCell in cells { let cell = colAndCell.1 if cell.position.column == k { for j in 0 ..< cell.colspan { if let width = finalColumnWidths[k + j] { origin.x += width } } k += cell.colspan } else { break } } } var cellWidth: CGFloat = 0.0 let colspan: Int = cell.colspan > 1 ? Int(clamping: cell.colspan) : 1 let rowspan: Int = cell.rowspan > 1 ? Int(clamping: cell.rowspan) : 1 for j in 0 ..< colspan { if let width = finalColumnWidths[k + j] { cellWidth += width } } var item: InstantPageTextItem? var additionalItems: [InstantPageItem] = [] var cellHeight: CGFloat? if let text = cell.text { let (textItem, items, _) = layoutTextItemWithString(attributedStringForRichText(text, styleStack: styleStack, boundingWidth: cellWidth - totalCellPadding), boundingWidth: cellWidth - totalCellPadding, alignment: cell.alignment.textAlignment, offset: CGPoint(), media: media, webpage: webpage) if let textItem = textItem { isEmptyRow = false textItem.frame = textItem.frame.offsetBy(dx: tableCellInsets.left, dy: 0.0) cellHeight = ceil(textItem.frame.height) + tableCellInsets.top + tableCellInsets.bottom item = textItem } for var item in items where !(item is InstantPageTextItem) { isEmptyRow = false if textItem == nil { let offset = offsetForHorizontalAlignment(cell.alignment, width: item.frame.width, boundingWidth: cellWidth, insets: tableCellInsets) item.frame = item.frame.offsetBy(dx: offset, dy: 0.0) } else { item.frame = item.frame.offsetBy(dx: tableCellInsets.left, dy: 0.0) } let height = ceil(item.frame.height) + tableCellInsets.top + tableCellInsets.bottom - 10.0 if let currentCellHeight = cellHeight { cellHeight = max(currentCellHeight, height) } else { cellHeight = height } additionalItems.append(item) } } var filled = cell.header if !filled && striped { filled = i % 2 == 0 } var adjacentSides: TableSide = [] if i == 0 { adjacentSides.insert(.top) } if i == rows.count - 1 { adjacentSides.insert(.bottom) } if k == 0 { adjacentSides.insert(.left) } if k + colspan == columnCount { adjacentSides.insert(.right) } let rowCell = InstantPageTableCellItem(position: TableCellPosition(row: i, column: k), cell: cell, frame: CGRect(x: origin.x, y: origin.y, width: cellWidth, height: cellHeight ?? 20.0), filled: filled, textItem: item, additionalItems: additionalItems, adjacentSides: adjacentSides) if rowspan == 1 { rowCells.append(rowCell) if let cellHeight = cellHeight { maxRowHeight = max(maxRowHeight, cellHeight) } } else { for j in i ..< i + rowspan { if awaitingSpanCells[j] == nil { awaitingSpanCells[j] = [(k, rowCell)] } else { awaitingSpanCells[j]!.append((k, rowCell)) } } } k += colspan origin.x += cellWidth } let finalizeCell: (InstantPageTableCellItem, inout [InstantPageTableCellItem], CGFloat) -> Void = { cell, cells, height in let updatedCell = cell.withRowHeight(height) if let textItem = updatedCell.textItem { let offset = offestForVerticalAlignment(cell.verticalAlignment, height: textItem.frame.height, boundingHeight: height, insets: tableCellInsets) updatedCell.textItem!.frame = textItem.frame.offsetBy(dx: 0.0, dy: offset) for var item in updatedCell.additionalItems { item.frame = item.frame.offsetBy(dx: 0.0, dy: offset) } } else { for var item in updatedCell.additionalItems { let offset = offestForVerticalAlignment(cell.verticalAlignment, height: item.frame.height, boundingHeight: height, insets: tableCellInsets) item.frame = item.frame.offsetBy(dx: 0.0, dy: offset) } } cells.append(updatedCell) } if !isEmptyRow { rowHeights[i] = maxRowHeight } else { rowHeights[i] = 0.0 maxRowHeight = 0.0 } var completedSpans = [Int : Set<Int>]() if let cells = awaitingSpanCells[i] { for colAndCell in cells { let cell = colAndCell.1 let utmostRow = cell.position.row + cell.rowspan - 1 if rowHeights[utmostRow] == nil { continue } var cellHeight: CGFloat = 0.0 for k in cell.position.row ..< utmostRow + 1 { if let height = rowHeights[k] { cellHeight += height } if completedSpans[k] == nil { var set = Set<Int>() set.insert(colAndCell.0) completedSpans[k] = set } else { completedSpans[k]!.insert(colAndCell.0) } } if cell.frame.height > cellHeight { let delta = cell.frame.height - cellHeight cellHeight = cell.frame.height maxRowHeight += delta rowHeights[i] = maxRowHeight } finalizeCell(cell, &finalizedCells, cellHeight) } } for cell in rowCells { finalizeCell(cell, &finalizedCells, maxRowHeight) } if !completedSpans.isEmpty { awaitingSpanCells = awaitingSpanCells.reduce([Int : [(Int, InstantPageTableCellItem)]]()) { (current, rowAndValue) in var result = current let cells = rowAndValue.value.filter({ column, cell in if let completedSpansInRow = completedSpans[rowAndValue.key] { return !completedSpansInRow.contains(column) } else { return true } }) if !cells.isEmpty { result[rowAndValue.key] = cells } return result } } if !isEmptyRow { totalHeight += maxRowHeight origin.y += maxRowHeight } } totalHeight += borderWidth if rtl { finalizedCells = finalizedCells.map { $0.withRTL(totalWidth) } } return InstantPageTableItem(frame: CGRect(x: 0.0, y: 0.0, width: boundingWidth + horizontalInset * 2.0, height: totalHeight), totalWidth: totalWidth, horizontalInset: horizontalInset, borderWidth: borderWidth, theme: theme, cells: finalizedCells, rtl: rtl) }
gpl-2.0
fc40fac3c109f7866cd51903a596c63d
37.994092
308
0.547445
4.864382
false
false
false
false
sadawi/ModelKit
ModelKit/Fields/CountRule.swift
1
560
// // CountRule.swift // ModelKit // // Created by Sam Williams on 3/22/17. // Copyright © 2017 Sam Williams. All rights reserved. // import Foundation open class CountRule<T>: TransformerRule<Array<T>, Int> { public convenience init(length: Int?) { self.init(minimum: length, maximum: length) } public init(minimum:Int?=nil, maximum:Int?=nil) { super.init() self.transform = { $0.count } self.rule = RangeRule(minimum: minimum, maximum: maximum) self.transformationDescription = "count" } }
mit
eda15513589d1232a586fe14c60ebb37
24.409091
65
0.636852
3.606452
false
false
false
false
hamzamuhammad/iChan
iChan/iChan/PageTableViewController.swift
1
5999
// // PageTableViewController.swift // iChan // // Created by Hamza Muhammad on 12/17/16. // Copyright © 2016 Hamza Muhammad. All rights reserved. // import UIKit class PageTableViewController: UITableViewController, UIPopoverPresentationControllerDelegate, PreviewLoadDelegate { var page: Page? var currentIndex: Int? var currentLabel: UILabel? 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() page!.previewLoadDelegate = self tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 140 } 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 return page!.numPreviewThreads() } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "ThreadCell", for: indexPath) as! ThreadTableViewCell // Configure the cell... let post = page!.getPost(index: indexPath.row) cell.titleLabel.text = post.title let dateFormatter = DateFormatter() dateFormatter.dateFormat = "EEE, dd MMM yyy hh:mm:ss +zzzz" cell.dateLabel.text = dateFormatter.string(from: post.date) cell.userIDLabel.text = post.userID cell.postTextLabel.text = post.text cell.postImageView.image = post.image currentIndex = indexPath.row // create tap gesture recognizer let tapGesture = UILongPressGestureRecognizer(target: self, action: #selector(self.textTapped(_:))) // add it to the image view; cell.postTextLabel.addGestureRecognizer(tapGesture) // make sure label can be interacted with by user cell.postTextLabel.isUserInteractionEnabled = true return cell } func textTapped(_ sender: UITapGestureRecognizer) { // if the tapped view is a UIImageView then set it to imageview if let textLabel = sender.view as? UILabel { print("text tapped") currentLabel = textLabel page!.getPreviewPosts(index: currentIndex!) } } func didLoadPreviews(posts: [String]) { let popoverContent = self.storyboard?.instantiateViewController(withIdentifier: "PreviewTableViewController") as! PreviewTableViewController popoverContent.previews = posts popoverContent.modalPresentationStyle = .popover if let popover = popoverContent.popoverPresentationController { popoverContent.preferredContentSize = CGSize(width: 200,height: 250) popover.sourceView = currentLabel popover.delegate = self } self.present(popoverContent, animated: true, completion: nil) } func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle { return .none } /* // 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. if segue.identifier == "ThreadSegue" { if let row = tableView.indexPathForSelectedRow?.row { let threadTableViewController = segue.destination as! ThreadTableViewController let newThread = Thread(pagePostIndex: row, threadID: page!.getPost(index: row).threadID, threadLen: page!.getPost(index: row).threadLen, mainPostID: page!.getPost(index: row).userID, currentPageView: self) threadTableViewController.thread = newThread } } } }
apache-2.0
203b232d2f5d9865076949811276f5da
37.448718
221
0.667723
5.477626
false
false
false
false
krzysztofzablocki/Sourcery
Sourcery/Generating/Templates/JavaScript/JavaScriptTemplate.swift
1
2100
import SourceryFramework import SourceryJS import SourceryRuntime import JavaScriptCore class JavaScriptTemplate: EJSTemplate, Template { override var context: [String: Any] { didSet { jsContext.catchTypesAccessErrors() jsContext.catchTemplateContextTypesUnknownProperties() } } func render(_ context: TemplateContext) throws -> String { return try render(context.jsContext) } } private extension JSContext { // this will catch errors accessing types through wrong collections (i.e. using `implementing` instead of `based`) func catchTypesAccessErrors() { let valueForKey: @convention(block) (TypesCollection, String) -> Any? = { target, key in do { return try target.types(forKey: key) } catch { JSContext.current().evaluateScript("throw \"\(error)\"") return nil } } setObject(valueForKey, forKeyedSubscript: "valueForKey" as NSString) evaluateScript("templateContext.types.implementing = new Proxy(templateContext.types.implementing, { get: valueForKey })") evaluateScript("templateContext.types.inheriting = new Proxy(templateContext.types.inheriting, { get: valueForKey })") evaluateScript("templateContext.types.based = new Proxy(templateContext.types.based, { get: valueForKey })") } // this will catch errors when accessing context types properties (i.e. using `implements` instead of `implementing`) func catchTemplateContextTypesUnknownProperties() { evaluateScript(""" templateContext.types = new Proxy(templateContext.types, { get(target, propertyKey, receiver) { if (!(propertyKey in target)) { throw new TypeError('Unknown property `'+propertyKey+'`'); } // Make sure we don’t block access to Object.prototype return Reflect.get(target, propertyKey, receiver); } }); """) } }
mit
91ca8285dbbe078bcc6e70a4475482f8
37.851852
130
0.627264
5.019139
false
false
false
false
josepvaleriano/iOS-practices
testSql2/testSql2/MasterViewController.swift
1
9173
// // MasterViewController.swift // testSql2 // // Created by Infraestructura on 01/10/16. // Copyright © 2016 Valeriano Lopez. All rights reserved. // import UIKit import CoreData class MasterViewController: UITableViewController, NSFetchedResultsControllerDelegate { var detailViewController: DetailViewController? = nil var managedObjectContext: NSManagedObjectContext? = nil override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.navigationItem.leftBarButtonItem = self.editButtonItem() let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: #selector(insertNewObject(_:))) self.navigationItem.rightBarButtonItem = addButton if let split = self.splitViewController { let controllers = split.viewControllers self.detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController } } override func viewWillAppear(animated: Bool) { self.clearsSelectionOnViewWillAppear = self.splitViewController!.collapsed super.viewWillAppear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func insertNewObject(sender: AnyObject) { let context = self.fetchedResultsController.managedObjectContext let entity = self.fetchedResultsController.fetchRequest.entity! let newManagedObject = NSEntityDescription.insertNewObjectForEntityForName(entity.name!, inManagedObjectContext: context) // If appropriate, configure the new managed object. // Normally you should use accessor methods, but using KVC here avoids the need to add a custom class to the template. newManagedObject.setValue(NSDate(), forKey: "timeStamp") // Save the context. do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. //print("Unresolved error \(error), \(error.userInfo)") abort() } } // MARK: - Segues override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showDetail" { if let indexPath = self.tableView.indexPathForSelectedRow { let object = self.fetchedResultsController.objectAtIndexPath(indexPath) let controller = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController controller.detailItem = object controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem() controller.navigationItem.leftItemsSupplementBackButton = true } } } // MARK: - Table View override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return self.fetchedResultsController.sections?.count ?? 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let sectionInfo = self.fetchedResultsController.sections![section] return sectionInfo.numberOfObjects } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) let object = self.fetchedResultsController.objectAtIndexPath(indexPath) as! NSManagedObject self.configureCell(cell, withObject: object) return cell } override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { let context = self.fetchedResultsController.managedObjectContext context.deleteObject(self.fetchedResultsController.objectAtIndexPath(indexPath) as! NSManagedObject) do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. //print("Unresolved error \(error), \(error.userInfo)") abort() } } } func configureCell(cell: UITableViewCell, withObject object: NSManagedObject) { cell.textLabel!.text = object.valueForKey("timeStamp")!.description } // MARK: - Fetched results controller var fetchedResultsController: NSFetchedResultsController { if _fetchedResultsController != nil { return _fetchedResultsController! } let fetchRequest = NSFetchRequest() // Edit the entity name as appropriate. let entity = NSEntityDescription.entityForName("Event", inManagedObjectContext: self.managedObjectContext!) fetchRequest.entity = entity // Set the batch size to a suitable number. fetchRequest.fetchBatchSize = 20 // Edit the sort key as appropriate. let sortDescriptor = NSSortDescriptor(key: "timeStamp", ascending: false) fetchRequest.sortDescriptors = [sortDescriptor] // Edit the section name key path and cache name if appropriate. // nil for section name key path means "no sections". let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.managedObjectContext!, sectionNameKeyPath: nil, cacheName: "Master") aFetchedResultsController.delegate = self _fetchedResultsController = aFetchedResultsController do { try _fetchedResultsController!.performFetch() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. //print("Unresolved error \(error), \(error.userInfo)") abort() } return _fetchedResultsController! } var _fetchedResultsController: NSFetchedResultsController? = nil func controllerWillChangeContent(controller: NSFetchedResultsController) { self.tableView.beginUpdates() } func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) { switch type { case .Insert: self.tableView.insertSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade) case .Delete: self.tableView.deleteSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade) default: return } } func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) { switch type { case .Insert: tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade) case .Delete: tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade) case .Update: self.configureCell(tableView.cellForRowAtIndexPath(indexPath!)!, withObject: anObject as! NSManagedObject) case .Move: tableView.moveRowAtIndexPath(indexPath!, toIndexPath: newIndexPath!) } } func controllerDidChangeContent(controller: NSFetchedResultsController) { self.tableView.endUpdates() } /* // Implementing the above methods to update the table view in response to individual changes may have performance implications if a large number of changes are made simultaneously. If this proves to be an issue, you can instead just implement controllerDidChangeContent: which notifies the delegate that all section and object changes have been processed. func controllerDidChangeContent(controller: NSFetchedResultsController) { // In the simplest, most efficient, case, reload the table view. self.tableView.reloadData() } */ }
mit
24790cfeac433c58df8edc6bebb418bb
45.090452
360
0.689708
6.26931
false
false
false
false
taher-mosbah/firefox-ios
StorageTests/TestFaviconsTable.swift
17
3417
/* 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 XCTest class TestFaviconsTable : XCTestCase { var db: SwiftData! private func addIcon(favicons: FaviconsTable<Favicon>, url: String, s: Bool = true) -> Favicon { var inserted = -1; var icon: Favicon! db.withConnection(.ReadWrite) { connection -> NSError? in icon = Favicon(url: url, type: IconType.Icon) var err: NSError? = nil inserted = favicons.insert(connection, item: icon, err: &err) return err } if s { XCTAssert(inserted >= 0, "Inserted succeeded") } else { XCTAssert(inserted == -1, "Inserted failed") } return icon } private func checkIcons(favicons: FaviconsTable<Favicon>, options: QueryOptions?, urls: [String], s: Bool = true) { db.withConnection(.ReadOnly) { connection -> NSError? in var cursor = favicons.query(connection, options: options) XCTAssertEqual(cursor.status, CursorStatus.Success, "returned success \(cursor.statusMessage)") XCTAssertEqual(cursor.count, urls.count, "cursor has right num of entries") for index in 0..<cursor.count { if let s = cursor[index] { XCTAssertNotNil(s, "cursor has an icon for entry") let index = find(urls, s.url) XCTAssert(index > -1, "Found right url") } else { XCTAssertFalse(true, "Should not be nil...") } } return nil } } private func clear(favicons: FaviconsTable<Favicon>, icon: Favicon? = nil, s: Bool = true) { var deleted = -1; db.withConnection(.ReadWrite) { connection -> NSError? in var err: NSError? = nil deleted = favicons.delete(connection, item: icon, err: &err) return nil } if s { XCTAssert(deleted >= 0, "Delete worked") } else { XCTAssert(deleted == -1, "Delete failed") } } // This is a very basic test. Adds an entry. Retrieves it, and then clears the database func testFaviconsTable() { let files = MockFiles() self.db = SwiftData(filename: files.getAndEnsureDirectory()!.stringByAppendingPathComponent("test.db")) let f = FaviconsTable<Favicon>() self.db.withConnection(SwiftData.Flags.ReadWriteCreate, cb: { (db) -> NSError? in f.create(db, version: 1) return nil }) let icon = self.addIcon(f, url: "url1") self.addIcon(f, url: "url1", s: false) self.addIcon(f, url: "url2") self.addIcon(f, url: "url2", s: false) self.checkIcons(f, options: nil, urls: ["url1", "url2"]) let options = QueryOptions() options.filter = "url2" self.checkIcons(f, options: options, urls: ["url2"]) var site = Favicon(url: "url1", type: IconType.Icon) self.clear(f, icon: icon, s: true) self.checkIcons(f, options: nil, urls: ["url2"]) self.clear(f) self.checkIcons(f, options: nil, urls: [String]()) files.remove("test.db") } }
mpl-2.0
33eb719b935f642e02ddff347f698c93
36.56044
119
0.572139
4.202952
false
true
false
false
crashoverride777/SwiftyAds
Sources/Internal/SwiftyAdsConsentManager.swift
1
5986
// The MIT License (MIT) // // Copyright (c) 2015-2022 Dominik Ringler // // 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 UserMessagingPlatform /* The SDK is designed to be used in a linear fashion. The steps for using the SDK are: Request the latest consent information. Check if consent is required. Check if a form is available and if so load a form. Present the form. Provide a way for users to change their consent. */ protocol SwiftyAdsConsentManagerType: AnyObject { var consentStatus: SwiftyAdsConsentStatus { get } func requestUpdate(completion: @escaping SwiftyAdsConsentResultHandler) func showForm(from viewController: UIViewController, completion: @escaping SwiftyAdsConsentResultHandler) } final class SwiftyAdsConsentManager { // MARK: - Properties private let consentInformation: UMPConsentInformation private let environment: SwiftyAdsEnvironment private let isTaggedForUnderAgeOfConsent: Bool private let consentStatusDidChange: (SwiftyAdsConsentStatus) -> Void private var form: UMPConsentForm? // MARK: - Initialization init(consentInformation: UMPConsentInformation, environment: SwiftyAdsEnvironment, isTaggedForUnderAgeOfConsent: Bool, consentStatusDidChange: @escaping (SwiftyAdsConsentStatus) -> Void) { self.consentInformation = consentInformation self.environment = environment self.isTaggedForUnderAgeOfConsent = isTaggedForUnderAgeOfConsent self.consentStatusDidChange = consentStatusDidChange } } // MARK: - SwiftyAdsConsentManagerType extension SwiftyAdsConsentManager: SwiftyAdsConsentManagerType { var consentStatus: SwiftyAdsConsentStatus { consentInformation.consentStatus } func requestUpdate(completion: @escaping SwiftyAdsConsentResultHandler) { // Create a UMPRequestParameters object. let parameters = UMPRequestParameters() // Set UMPDebugSettings if in development environment. switch environment { case .production: break case .development(let testDeviceIdentifiers, let consentConfiguration): let debugSettings = UMPDebugSettings() debugSettings.testDeviceIdentifiers = testDeviceIdentifiers debugSettings.geography = consentConfiguration.geography parameters.debugSettings = debugSettings if case .resetOnLaunch = consentConfiguration { consentInformation.reset() } } // Update parameters for under age of consent. parameters.tagForUnderAgeOfConsent = isTaggedForUnderAgeOfConsent // Request an update to the consent information. // The first time we request consent information, even if outside of EEA, the status // may return `.required` as the ATT alert has not yet been displayed and we are using // Google Choices ATT message. consentInformation.requestConsentInfoUpdate(with: parameters) { [weak self] error in guard let self = self else { return } if let error = error { completion(.failure(error)) return } // The consent information state was updated and we can now check if a form is available. switch self.consentInformation.formStatus { case .available: DispatchQueue.main.async { UMPConsentForm.load { [weak self ] (form, error) in guard let self = self else { return } if let error = error { completion(.failure(error)) return } self.form = form completion(.success(self.consentStatus)) } } case .unavailable: completion(.success(self.consentStatus)) case .unknown: completion(.success(self.consentStatus)) @unknown default: completion(.success(self.consentStatus)) } } } func showForm(from viewController: UIViewController, completion: @escaping SwiftyAdsConsentResultHandler) { // Ensure form is loaded guard let form = form else { completion(.failure(SwiftyAdsError.consentFormNotAvailable)) return } // Present the form form.present(from: viewController) { [weak self] error in guard let self = self else { return } if let error = error { completion(.failure(error)) return } let consentStatus = self.consentStatus self.consentStatusDidChange(consentStatus) completion(.success(consentStatus)) } } }
mit
5753c95c90aac0dbaf8e7d45ec461b28
38.124183
111
0.656699
5.412297
false
false
false
false
crisisGriega/swift-simple-tree-drawer
TreeStructure/NodeView.swift
1
4465
// // Node.swift // TreeStructure // // Created by Gerardo Garrido on 13/07/16. // import UIKit class NodeView: UIView { static let nodeSize = CGSizeMake(50, 25); static let separatorSize = CGSizeMake(10, 25); var name: String { get { if let text = self.lbName.text { return text; } return ""; } set { self.lbName.text = newValue; } } var node: Node?; @IBOutlet weak var lbName: UILabel!; @IBOutlet weak var connectorsView: UIView! @IBOutlet weak var childrenView: UIView! @IBOutlet weak var vertexView: UIView! // MARK: Lifecycle methods class func initFromXib(with node: Node) -> NodeView { let nodeView = NSBundle.mainBundle().loadNibNamed(String(NodeView), owner: self, options: nil)[0] as! NodeView nodeView.node = node; nodeView.name = node.name; nodeView.frame.size = node.neededSize(); return nodeView; } // MARK: Actions @IBAction func onVisibilityTap(sender: UIButton) { self.childrenView.hidden = !self.childrenView.hidden; self.connectorsView.hidden = !self.connectorsView.hidden; } // MARK: Public func drawChildrenNodes() { self.clearChildrenView(); guard let node = self.node else { return; } let size = node.neededSize(); self.frame.size = size; self.childrenView.frame.size = size; self.connectorsView.frame.size = size; var origin = CGPointMake(0, NodeView.nodeSize.height + NodeView.separatorSize.height); for child in node.children { let childView = NodeView.initFromXib(with: child); self.childrenView.addSubview(childView); childView.drawChildrenNodes(); childView.frame.origin = origin; origin.x += childView.frame.width + NodeView.separatorSize.width; } self.vertexView.frame.origin.x = (size.width - NodeView.nodeSize.width) / 2; self.drawConnectors(); } // MARK: Private private func clearChildrenView() { for view in self.childrenView.subviews { view.removeFromSuperview(); } for connector in self.connectorsView.subviews { connector.removeFromSuperview(); } } private func drawConnectors() { guard let node = self.node where node.numberOfChildren() > 0 else { return; } UIGraphicsBeginImageContext(self.frame.size); guard let context = UIGraphicsGetCurrentContext() else { return; } CGContextSetLineWidth(context, 1); CGContextSetStrokeColorWithColor(context, UIColor.blackColor().CGColor); let firstChildView = self.childrenView.subviews.first!; if (node.children.count == 1) { CGContextMoveToPoint(context, firstChildView.center.x, self.vertexView.center.y); CGContextAddLineToPoint(context, firstChildView.center.x, firstChildView.frame.origin.y); CGContextStrokePath(context); } else if (node.children.count > 1) { let linePosY = NodeView.nodeSize.height/2 + NodeView.separatorSize.height; let lastChildView = self.childrenView.subviews.last!; CGContextMoveToPoint(context, firstChildView.center.x, linePosY); CGContextAddLineToPoint(context, lastChildView.center.x, linePosY); CGContextStrokePath(context); for childView in self.childrenView.subviews { self.drawLine(fromNode: childView, toLineAt: linePosY, in: context); } self.drawLine(fromNode: self.vertexView, toLineAt: linePosY, in: context); } let img = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); self.connectorsView.addSubview(UIImageView(image: img)); } private func drawLine(fromNode node: UIView, toLineAt posY: CGFloat, in context: CGContext) { CGContextMoveToPoint(context, node.center.x, node.frame.origin.y); CGContextAddLineToPoint(context, node.center.x, posY); CGContextStrokePath(context); } }
mit
fcda9af9b243547e525cd38f23fdf0f2
29.793103
118
0.597536
4.806243
false
false
false
false
soapyigu/LeetCode_Swift
String/FizzBuzz.swift
1
716
/** * Question Link: https://leetcode.com/problems/fizz-buzz/ * Primary idea: Iterate the array and handle multiples of 3 or 5 separately. * * Time Complexity: O(n), Space Complexity: O(1) * */ class FizzBuzz { func fizzBuzz(_ n: Int) -> [String] { var res = [String]() if n < 0 { return res } for i in 1...n { if i % 3 == 0 && i % 5 == 0 { res.append("FizzBuzz") } else if i % 3 == 0 { res.append("Fizz") } else if i % 5 == 0 { res.append("Buzz") } else { res.append("\(i)") } } return res } }
mit
cc88a01ef205b135ed48f76e843730ad
22.129032
77
0.414804
4
false
false
false
false
WaterReporter/WaterReporter-iOS
WaterReporter/WaterReporter/Endpoints.swift
1
2689
// // Endpoints.swift // WaterReporter // // Created by Viable Industries on 7/25/16. // Copyright © 2016 Viable Industries, L.L.C. All rights reserved. // import Foundation struct Endpoints { static let GET_MANY_REPORTS = "https://api.waterreporter.org/v2/data/report" static let POST_REPORT = "https://api.waterreporter.org/v2/data/report" static let GET_MANY_REPORT_LIKES = "https://api.waterreporter.org/v2/data/like" static let POST_LIKE = "https://api.waterreporter.org/v2/data/like" static let DELETE_LIKE = "https://api.waterreporter.org/v2/data/like" static let GET_MANY_USER = "https://api.waterreporter.org/v2/data/user" static let POST_AUTH_REMOTE = "https://api.waterreporter.org/v2/auth/remote" static let GET_AUTH_AUTHORIZE = "https://www.waterreporter.org/authorize" static let GET_USER_ME = "https://api.waterreporter.org/v2/data/me" static let POST_USER_REGISTER = "https://api.waterreporter.org/v2/user/register" static let GET_USER_PROFILE = "https://api.waterreporter.org/v2/data/user/" static let GET_USER_SNAPSHOT = "https://api.waterreporter.org/v2/data/snapshot/user/" static let POST_USER_PROFILE = "https://api.waterreporter.org/v2/data/user/" static let POST_PASSWORD_RESET = "https://api.waterreporter.org/v2/reset" static let POST_IMAGE = "https://api.waterreporter.org/v2/media/image" static let GET_MANY_ORGANIZATIONS = "https://api.waterreporter.org/v2/data/organization" static let GET_MANY_REPORT_COMMENTS = "https://api.waterreporter.org/v2/data/comment" static let POST_COMMENT = "https://api.waterreporter.org/v2/data/comment" static let GET_MANY_HASHTAGS = "https://api.waterreporter.org/v2/data/hashtag" static let GET_MANY_TERRITORY = "https://api.waterreporter.org/v2/data/territory" static let GET_MANY_HUC8WATERSHEDS = "https://api.waterreporter.org/v2/data/huc-8" static let TRENDING_GROUP = "https://api.waterreporter.org/v2/data/trending/group" static let TRENDING_HASHTAG = "https://api.waterreporter.org/v2/data/trending/hashtag" static let TRENDING_PEOPLE = "https://api.waterreporter.org/v2/data/trending/people" static let TRENDING_TERRITORY = "https://api.waterreporter.org/v2/data/trending/territory" static let TERRITORY = "https://huc.waterreporter.org/8/" // // // var apiUrl: String! = "https://api.waterreporter.org/v2/data" func getManyReportComments(reportId: AnyObject) -> String { let _endpoint = apiUrl, _reportId = String(reportId) return _endpoint + "/report/" + _reportId + "/comments" } }
agpl-3.0
32a88113581c2c89616effe93fda7fa3
41
94
0.69308
3.15493
false
false
false
false
guipanizzon/ioscreator
SpriteKitSwiftParticleTutorial/SpriteKitSwiftParticleTutorial/GameScene.swift
39
898
// // GameScene.swift // SpriteKitSwiftParticleTutorial // // Created by Arthur Knopper on 26/05/15. // Copyright (c) 2015 Arthur Knopper. All rights reserved. // import SpriteKit class GameScene: SKScene { override func didMoveToView(view: SKView) { /* Setup your scene here */ self.backgroundColor = UIColor.blackColor() var path = NSBundle.mainBundle().pathForResource("Rain", ofType: "sks") var rainParticle = NSKeyedUnarchiver.unarchiveObjectWithFile(path!) as! SKEmitterNode rainParticle.position = CGPointMake(self.size.width/2, self.size.height) rainParticle.name = "rainParticle" rainParticle.targetNode = self.scene self.addChild(rainParticle) } /*override func update(currentTime: CFTimeInterval) { /* Called before each frame is rendered */ }*/ }
mit
72ade14af46c38a930e7c4fdc5ee9dc1
27.967742
93
0.652561
4.701571
false
false
false
false
dvlproad/CommonLibrary
UITestDemo/Finished-3/BullsEye/BullsEye/ViewController.swift
2
4437
/** * Copyright (c) 2016 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import UIKit class ViewController: UIViewController { var defaults = UserDefaults.standard @IBOutlet weak var targetGuessLabel: UILabel! @IBOutlet weak var targetGuessField: UITextField! @IBOutlet weak var roundLabel: UILabel! @IBOutlet weak var scoreLabel: UILabel! @IBOutlet weak var slider: UISlider! @IBOutlet weak var segmentedControl: UISegmentedControl! let game = BullsEyeGame() enum GameStyle: Int { case moveSlider, guessPosition } let gameStyleRange = 0..<2 var gameStyle: GameStyle = .guessPosition override func viewDidLoad() { super.viewDidLoad() let defaultGameStyle = defaults.integer(forKey: "gameStyle") print(defaultGameStyle) if gameStyleRange.contains(defaultGameStyle) { gameStyle = GameStyle(rawValue: defaultGameStyle)! segmentedControl.selectedSegmentIndex = defaultGameStyle } else { gameStyle = .moveSlider defaults.set(0, forKey: "gameStyle") } updateView() } @IBAction func chooseGameStyle(_ sender: UISegmentedControl) { if gameStyleRange.contains(sender.selectedSegmentIndex) { gameStyle = GameStyle(rawValue: sender.selectedSegmentIndex)! updateView() } defaults.set(sender.selectedSegmentIndex, forKey: "gameStyle") } func updateView() { switch gameStyle { case .moveSlider: targetGuessLabel.text = "Get as close as you can to: " targetGuessField.text = "\(game.targetValue)" targetGuessField.isEnabled = false slider.value = Float(game.startValue) slider.isEnabled = true case .guessPosition: targetGuessLabel.text = "Guess where the slider is: " targetGuessField.text = "" targetGuessField.placeholder = "1-100" targetGuessField.isEnabled = true slider.value = Float(game.targetValue) slider.isEnabled = false } roundLabel.text = "Round: \(game.round)" scoreLabel.text = "Score: \(game.scoreTotal)" } @IBAction func checkGuess(_ sender: Any) { var guess: Int? switch gameStyle { case .moveSlider: guess = Int(lroundf(slider.value)) case .guessPosition: targetGuessField.resignFirstResponder() guess = Int(targetGuessField.text!) } if let guess = guess { showScoreAlert(difference: game.check(guess: guess)) } else { showNaNAlert() } } func showScoreAlert(difference: Int) { let title = "you scored \(game.scoreRound) points" let message = "target value \(game.targetValue)" let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) let action = UIAlertAction(title: "OK", style: .default, handler: { action in self.game.startNewRound() self.updateView() }) alert.addAction(action) present(alert, animated: true, completion: nil) } func showNaNAlert() { let alert = UIAlertController(title: "Not A Number", message: "Please enter a positive number", preferredStyle: .alert) let action = UIAlertAction(title: "OK", style: .default, handler: nil) alert.addAction(action) present(alert, animated: true, completion: nil) } @IBAction func startOver(_ sender: Any) { game.startNewGame() updateView() } }
mit
74165404b8ab26c324e07c44bbe238e8
33.395349
89
0.69281
4.388724
false
false
false
false
ygorshenin/omim
iphone/Maps/UI/Welcome/WhatsNewController.swift
1
2561
final class WhatsNewController: WelcomeViewController { private struct WhatsNewConfig: WelcomeConfig { let image: UIImage let title: String let text: String let buttonTitle: String let ctaButtonTitle: String? let ctaButtonUrl: String? } static var welcomeConfigs: [WelcomeConfig] { return [ WhatsNewConfig(image: #imageLiteral(resourceName: "img_whats_new_catalog"), title: "whats_new_bookmarks_catalog_title", text: "whats_new_bookmarks_catalog_message", buttonTitle: "whats_new_next_button", ctaButtonTitle: nil, ctaButtonUrl: nil), WhatsNewConfig(image: #imageLiteral(resourceName: "img_whats_new_popular"), title: "whats_new_popularity_label_title", text: "whats_new_popularity_label_message", buttonTitle: "whats_new_next_button", ctaButtonTitle: nil, ctaButtonUrl: nil), WhatsNewConfig(image: #imageLiteral(resourceName: "img_whats_hot_offers"), title: "whats_new_hot_offers_title", text: "whats_new_hot_offers_message", buttonTitle: "done", ctaButtonTitle: nil, ctaButtonUrl: nil) ] } override class var key: String { return welcomeConfigs.reduce("\(self)", { return "\($0)_\($1.title)" }) } static var shouldShowWhatsNew: Bool { get { return !UserDefaults.standard.bool(forKey: key) } set { UserDefaults.standard.set(!newValue, forKey: key) } } static func controllers() -> [WelcomeViewController] { var result = [WelcomeViewController]() let sb = UIStoryboard.instance(.welcome) WhatsNewController.welcomeConfigs.forEach { (config) in let vc = sb.instantiateViewController(withIdentifier: toString(self)) as! WelcomeViewController vc.pageConfig = config result.append(vc) } return result } @IBOutlet weak var ctaButton: UIButton! override func viewDidLoad() { super.viewDidLoad() let config = pageConfig as! WhatsNewConfig if let ctaTitleKey = config.ctaButtonTitle { ctaButton.setTitle(L(ctaTitleKey), for: .normal) } else { ctaButton.isHidden = true } } @IBAction func onCta() { let config = pageConfig as! WhatsNewConfig if let url = URL(string: config.ctaButtonUrl!) { UIApplication.shared.openURL(url) } else { assertionFailure() } close() } }
apache-2.0
c2a217782693a37c7790dde115b51e0c
31.833333
108
0.618899
4.54078
false
true
false
false
ByteriX/BxInputController
BxInputController/Sources/Common/View/BxInputBaseFieldRowBinder.swift
1
1629
/** * @file BxInputBaseFieldRowBinder.swift * @namespace BxInputController * * @details Base class for binding row data model with base field cell * @date 25.04.2017 * @author Sergey Balalaev * * @version last in https://github.com/ByteriX/BxInputController.git * @copyright The MIT License (MIT) https://opensource.org/licenses/MIT * Copyright (c) 2017 ByteriX. See http://byterix.com */ import UIKit /// Base class for binding row data model with base field cell open class BxInputBaseFieldRowBinder<Row: BxInputRow, Cell> : BxInputBaseTitleRowBinder<Row, Cell> where Cell : UITableViewCell, Cell : BxInputFieldCell { /// update cell from model data override open func update() { super.update() cell?.valueTextField.font = owner?.settings.valueFont cell?.valueTextField.textColor = owner?.settings.valueColor cell?.valueTextField.setPlaceholder(row.placeholder, with: owner?.settings.placeholderColor) } /// event of change isEnabled override open func didSetEnabled(_ value: Bool) { super.didSetEnabled(value) guard let cell = cell else { return } cell.valueTextField.isEnabled = value // UI part if needChangeDisabledCell { if let changeViewEnableHandler = owner?.settings.changeViewEnableHandler { changeViewEnableHandler(cell.valueTextField, isEnabled) } else { cell.valueTextField.alpha = value ? 1 : alphaForDisabledView } } else { cell.valueTextField.alpha = 1 } } }
mit
fae0e5eea366eb692a8dc15b16d022f4
31.58
100
0.6593
4.367292
false
false
false
false
vigneshuvi/SwiftLoggly
SwiftLoggly/Sources/Loggly.swift
2
32022
// // Loggly.swift // SwiftLoggly // // Created by Vignesh on 30/01/17. // Copyright © 2017 vigneshuvi. All rights reserved. // import Foundation //MARK: - Extension for String to find length extension String { var length: Int { return self.count } func trim() -> String { return components(separatedBy: .whitespaces).joined() } } //MARK: - Extension for convert Dictionary to String extension Dictionary { var jsonString: String { let invalidJson = "Not a valid JSON" do { let jsonData = try JSONSerialization.data(withJSONObject: self, options: .prettyPrinted) return String(bytes: jsonData, encoding: String.Encoding.utf8) ?? invalidJson } catch { return invalidJson } } func printJson() { print(jsonString) } } //MARK: - Extension for convert NSDictionary to String extension NSDictionary { var jsonString: String { let invalidJson = "Not a valid JSON" do { let jsonData = try JSONSerialization.data(withJSONObject: self, options: .prettyPrinted) return String(bytes: jsonData, encoding: String.Encoding.utf8) ?? invalidJson } catch { return invalidJson } } func printJson() { print(jsonString) } } //MARK: - Struct for Color Log struct ColorLog { static let ESCAPE = "\u{001B}[" static let RESET_FG = ESCAPE + "fg;" // Clear any foreground color static let RESET_BG = ESCAPE + "bg;" // Clear any background color static let RESET = ESCAPE + "0m" // Clear any foreground or background color static func red<T>(object: T) { print("\(ESCAPE)31m\(object)\(RESET)") } static func green<T>(object: T) { print("\(ESCAPE)32m\(object)\(RESET)") } static func blue<T>(object: T) { print("\(ESCAPE)34m\(object)\(RESET)") } static func yellow<T>(object: T) { print("\(ESCAPE)33m\(object)\(RESET)") } static func purple<T>(object: T) { print("\(ESCAPE)35m\(object)\(RESET)") } } //MARK: - Enumaration for log type public enum LogType { case Info case Verbose case Warnings case Debug case Error } //MARK: - Enumaration for log type public enum LogFormatType { case Normal case JSON } //MARK: - Loggly Class @objc open class Loggly:NSObject { //MARK: - Log Report Properties //The name of swift loggly report. var logReportName = "SwiftLogglyReport"; //The field of loggly report. var logReportFields:NSArray = ["Info", "Verbose", "Warnings", "Debug", "Error"] //The field of Info Count var logInfoCount:NSInteger = 0 //The field of Verbose Count var logVerboseCount:NSInteger = 0 //The field of Warnings Count var logWarnCount:NSInteger = 0 //The field of Debug Count var logDebugCount:NSInteger = 0 //The field of Error Count var logErrorCount:NSInteger = 0 //MARK: - Log Properties //The log encodeing format open var logEncodingType:String.Encoding = String.Encoding.utf8; //Log items saved format . open var logFormatType = LogFormatType.Normal; ///The max size a log file can be in Kilobytes. Default is 1024 (1 MB) open var maxFileSize: UInt64 = 1024; ///The max number of log file that will be stored. Once this point is reached, the oldest file is deleted. open var maxFileCount = 4; ///The directory in which the log files will be written open var directory : String = Loggly.defaultDirectory() { didSet { guard directory.count > 0 else { print("Error changing logger directory. The value \(directory) is not valid. Using default value instead") directory = Loggly.defaultDirectory() return } let fileManager = FileManager.default if !fileManager.fileExists(atPath: directory) { do { try fileManager.createDirectory(atPath: directory, withIntermediateDirectories: false, attributes: nil) } catch _ { print("Error changing logger directory. The value \(directory) is not valid. Using default value instead") directory = Loggly.defaultDirectory() } } } } ///The reportDirectory in which the report files will be written var reportDirectory = Loggly.defaultReportDirectory(); //The name of the log files. open var name = "logglyfile"; //The date format of the log time. open var logDateFormat = ""; // Help to enble Emojis open var enableEmojis = false; // Log file extension open var logFileExtension = ".log" func getExtension() -> String { return logFileExtension.trim().length > 0 ? logFileExtension : ".log" } ///logging singleton open class var logger: Loggly { struct Static { static let instance: Loggly = Loggly() } Static.instance.loadLogCounts() return Static.instance } //MARK: - Reports Util Methods ///gets the CSV name func getReportFileName() -> String { return "\(logReportName).csv" } // Set the Loggly Reports Name open func setLogglyReportsName(_ name: String){ logReportName = name; } // Get the Loggly Reports Name open func getLogglyReportsName() -> String{ return logReportName; } func loadLogCounts() { if logInfoCount == 0 && logVerboseCount == 0 && logWarnCount == 0 && logDebugCount == 0 && logErrorCount == 0 { self.loadLogDetails() } } func loadLogDetails() { let path = "\(reportDirectory)/\(self.getReportFileName())" let fileManager = FileManager.default if fileManager.fileExists(atPath: path) { let logDict:NSMutableDictionary = self.readReports(); if logDict.allKeys.count > 0 { let rows:NSArray = logDict.object(forKey: "rows") as! NSArray; if rows.count > 0 { for dict in rows { let row = dict as! NSDictionary for key in row.allKeys { switch (key as! String) { case "Info": logInfoCount = (row.object(forKey: key) as! NSString).integerValue; break case "Verbose": logVerboseCount = (row.object(forKey: key) as! NSString).integerValue; break case "Warnings": logWarnCount = (row.object(forKey: key) as! NSString).integerValue; break case "Debug": logDebugCount = (row.object(forKey: key) as! NSString).integerValue; break case "Error": logErrorCount = (row.object(forKey: key) as! NSString).integerValue; break default : break } } } } } } } // Set the Loggly Reports Name func increaseLogCount(_ type: LogType){ switch type { case .Info: logInfoCount += 1; break; case .Verbose: logVerboseCount += 1; break; case .Warnings: logWarnCount += 1; break; case .Debug: logDebugCount += 1; break; case .Error: logErrorCount += 1; break; } _ = self.createCSVReport(self.generateReportArray()) } func generateReportArray() -> NSMutableArray { // Create Dictionary object for storing log count let logDictforCount:NSMutableDictionary = self.getReportsOutput() // CSV rows Array let data:NSMutableArray = NSMutableArray() data.add(logDictforCount); return data; } open func getReportsOutput() -> NSMutableDictionary { // Create Dictionary object for storing log count let logDictforCount:NSMutableDictionary = NSMutableDictionary() logDictforCount.setValue(self.logInfoCount, forKey: "Info"); logDictforCount.setValue(self.logVerboseCount, forKey: "Verbose" ); logDictforCount.setValue(self.logWarnCount, forKey: "Warnings"); logDictforCount.setValue(self.logDebugCount, forKey: "Debug"); logDictforCount.setValue(self.logErrorCount, forKey: "Error"); return logDictforCount; } // Get the Loggly Info Count open func getCountBasedonLogType(_ type: LogType) -> NSInteger{ var count:NSInteger = 0; switch type { case .Info: count = self.getLogInfoCount(); break; case .Verbose: count = self.getLogVerboseCount(); break; case .Warnings: count = self.getLogWarningsCount(); break; case .Debug: count = self.getLogDebugCount(); break; case .Error: count = self.getLogErrorCount(); break; } return count; } // Get the Loggly Info Count open func getLogInfoCount() -> NSInteger{ return self.logInfoCount; } // Get the Loggly Verbose Count open func getLogVerboseCount() -> NSInteger{ return self.logVerboseCount; } // Get the Loggly Warnings Count open func getLogWarningsCount() -> NSInteger{ return self.logWarnCount; } // Get the Loggly Debug Count open func getLogDebugCount() -> NSInteger{ return self.logDebugCount; } // Get the Loggly Error Count open func getLogErrorCount() -> NSInteger{ return self.logErrorCount; } ///write content to the current csv file. open func getReportsFilePath() -> String{ let path = "\(reportDirectory)/\(self.getReportFileName())" let fileManager = FileManager.default if fileManager.fileExists(atPath: path) { return path; } return ""; } func createCSVReport(_ values: NSArray) -> String { if logReportFields.count > 0 && values.count > 0 { let path = "\(reportDirectory)/\(self.getReportFileName())" let fileManager = FileManager.default if !fileManager.fileExists(atPath: path) { do { try "".write(toFile: path, atomically: true, encoding: String.Encoding.utf8) } catch _ { } } else { do { try "".write(toFile: path, atomically: true, encoding: String.Encoding.utf8) } catch _ { } } let result:String = logReportFields.componentsJoined(by: ","); Loggly.logger.writeReports( text: result) for dict in values { let values = (dict as! NSDictionary).allValues as NSArray; let result:String = values.componentsJoined(by: ","); Loggly.logger.writeReports( text: result) } return Loggly.logger.getReportsFilePath(); } return ""; } ///write content to the current csv file. open func writeReports(text: String) { let path = "\(reportDirectory)/\(self.getReportFileName())" let fileManager = FileManager.default if !fileManager.fileExists(atPath: path) { do { try "".write(toFile: path, atomically: true, encoding: String.Encoding.utf8) } catch _ { } } if let fileHandle = FileHandle(forWritingAtPath: path) { let writeText = "\(text)\n" fileHandle.seekToEndOfFile() fileHandle.write(writeText.data(using: String.Encoding.utf8)!) fileHandle.closeFile() } } open func readReports() -> NSMutableDictionary { let path = "\(reportDirectory)/\(self.getReportFileName())" return self.readFromPath(filePath:path); } /// read content to the current csv file. open func readFromPath(filePath: String) -> NSMutableDictionary{ let fileManager = FileManager.default let output:NSMutableDictionary = NSMutableDictionary() // Find the CSV file path is available if fileManager.fileExists(atPath: filePath) { do { // Generate the Local file path URL let localPathURL: URL = NSURL.fileURL(withPath: filePath); // Read the content from Local Path let csvText = try String(contentsOf: localPathURL, encoding: String.Encoding.utf8); // Check the csv count if csvText.count > 0 { // Split based on Newline delimiter let csvArray = self.splitUsingDelimiter(csvText, separatedBy: "\n") as NSArray if csvArray.count >= 2 { var fieldsArray:NSArray = []; let rowsArray:NSMutableArray = NSMutableArray() for row in csvArray { // Get the CSV headers if((row as! String).contains(csvArray[0] as! String)) { fieldsArray = self.splitUsingDelimiter(row as! String, separatedBy: ",") as NSArray; } else { // Get the CSV values let valuesArray = self.splitUsingDelimiter(row as! String, separatedBy: ",") as NSArray; if valuesArray.count == fieldsArray.count && valuesArray.count > 0{ let rowJson:NSMutableDictionary = self.generateDict(fieldsArray, valuesArray: valuesArray) if rowJson.allKeys.count > 0 && valuesArray.count == rowJson.allKeys.count && rowJson.allKeys.count == fieldsArray.count { rowsArray.add(rowJson) } } } } // Set the CSV headers & Values and name in the dict. if fieldsArray.count > 0 && rowsArray.count > 0 { output.setObject(fieldsArray, forKey: "fields" as NSCopying) output.setObject(rowsArray, forKey: "rows" as NSCopying) output.setObject(localPathURL.lastPathComponent, forKey: "name" as NSCopying) } } } } catch { /* error handling here */ print("Error while read csv: \(error)", terminator: "") } } return output; } func generateDict(_ fieldsArray: NSArray, valuesArray: NSArray ) -> NSMutableDictionary { let rowsDictionary:NSMutableDictionary = NSMutableDictionary() for i in 0..<valuesArray.count { let key = fieldsArray[i]; let value = valuesArray[i]; rowsDictionary.setObject(value, forKey: key as! NSCopying); } return rowsDictionary; } func splitUsingDelimiter(_ string: String, separatedBy: String) -> NSArray { if string.count > 0 { return string.components(separatedBy: separatedBy) as NSArray; } return []; } ///do the checks and cleanup open func cleanupReports() { let path = "\(reportDirectory)/\(self.getReportFileName())" let size = fileSize(path) if size > 0 { //delete the oldest file let deletePath = "\(directory)/\(self.getReportFileName())" let fileManager = FileManager.default do { try fileManager.removeItem(atPath: deletePath) } catch _ { } } } //MARK: - Loggly Util Methods //the date formatter var dateFormatter: DateFormatter { let formatter = DateFormatter() if !logDateFormat.isEmpty && logDateFormat.length > 0 { formatter.dateFormat = logDateFormat } else { formatter.timeStyle = .medium formatter.dateStyle = .medium } return formatter } ///gets the log type with String // use colored Emojis for better visual distinction // of log level for Xcode 8 func logTypeName(_ type: LogType, isEmojis:Bool) -> String { var logTypeStr = ""; switch type { case .Info: logTypeStr = isEmojis ? "💙 Info - " : "Info - "; break; case .Verbose: logTypeStr = isEmojis ? "💜 Verbose - " : "Verbose - "; break; case .Warnings: logTypeStr = isEmojis ? "💛 Warnings - " : "Warnings - "; break; case .Debug: logTypeStr = isEmojis ? "💚 Debug - " : "Debug - "; break; case .Error: logTypeStr = isEmojis ? "❤️ Error - " : "Error - "; break; } return logTypeStr; } // Gets the log type with String func logJSONTypeName(_ type: LogType) -> String { var logTypeStr = ""; switch type { case .Info: logTypeStr = "Info" break; case .Verbose: logTypeStr = "Verbose" ; break; case .Warnings: logTypeStr = "Warnings" ; break; case .Debug: logTypeStr = "Debug" ; break; case .Error: logTypeStr = "Error"; break; } return logTypeStr; } /// Prints the log type with String and type color code. func printLog(_ type: LogType, text:String) { switch type { case .Info: ColorLog.blue(object: text) break; case .Verbose: ColorLog.purple(object: text) break; case .Warnings: ColorLog.yellow(object: text) break; case .Debug: ColorLog.green(object: text) break; case .Error: ColorLog.red(object: text) break; } } // Generate log text base on Log Format type. func getWriteTextBasedOnType(_ type: LogType, text: String, isDelimiter: Bool) -> String { let dateStr = dateFormatter.string(from: Date()) if(logFormatType == LogFormatType.JSON) { let logJson = NSMutableDictionary(); logJson.setValue(logJSONTypeName(type), forKey: "LogType") logJson.setValue(dateStr, forKey: "LogDate") logJson.setValue(text, forKey: "LogMessage") return "\(logJson.jsonString.replacingOccurrences(of: "\n", with: ""))\(isDelimiter ?"\n":"")" } return "[\(logTypeName(type, isEmojis: enableEmojis)) \(dateStr)]: \(text)\(isDelimiter ?"\n":"")" } ///write content to the current log file. open func write(_ type: LogType, text: String) { let path = "\(directory)/\(logName(0))" let fileManager = FileManager.default if !fileManager.fileExists(atPath: path) { do { try "".write(toFile: path, atomically: true, encoding: logEncodingType) } catch { print("error getting wriet string: \(error)") } } if let fileHandle = FileHandle(forWritingAtPath: path) { var writeText = getWriteTextBasedOnType(type, text: text, isDelimiter: true) fileHandle.seekToEndOfFile() fileHandle.write(writeText.data(using: logEncodingType)!) fileHandle.closeFile() writeText = getWriteTextBasedOnType(type, text: text, isDelimiter: false) #if os(iOS) print(writeText) #elseif os(OSX) printLog(type, text:writeText) #else printLog(type, text:writeText) #endif cleanup() } self.increaseLogCount(type); } ///do the checks and cleanup open func cleanup() { let path = "\(directory)/\(logName(0))" let size = fileSize(path) let maxSize: UInt64 = maxFileSize*1024 if size > 0 && size >= maxSize && maxSize > 0 && maxFileCount > 0 { rename(0) //delete the oldest file let deletePath = "\(directory)/\(logName(maxFileCount))" let fileManager = FileManager.default do { try fileManager.removeItem(atPath: deletePath) } catch _ { } } } ///check the size of a file open func fileSize(_ path: String) -> UInt64 { let fileManager = FileManager.default if fileManager.fileExists(atPath: path) { let attrs: NSDictionary? = try! fileManager.attributesOfItem(atPath: path) as NSDictionary? if let dict = attrs { return dict.fileSize() } } return 0 } ///Recursive method call to rename log files func rename(_ index: Int) { let fileManager = FileManager.default let path = "\(directory)/\(logName(index))" let newPath = "\(directory)/\(logName(index+1))" if fileManager.fileExists(atPath: newPath) { rename(index+1) } do { try fileManager.moveItem(atPath: path, toPath: newPath) } catch _ { } } ///gets the log name func logName(_ num :Int) -> String { return "\(name)-\(num)\(getExtension())" } ///get the default log directory class func defaultReportDirectory() -> String { var path = "" let fileManager = FileManager.default #if os(iOS) let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) path = "\(paths[0])/Report" #elseif os(OSX) let urls = fileManager.urls(for: .libraryDirectory, in: .userDomainMask) if let url = urls.last?.path { path = "\(url)/Report" } #endif if !fileManager.fileExists(atPath: path) && path != "" { do { try fileManager.createDirectory(atPath: path, withIntermediateDirectories: false, attributes: nil) } catch _ { } } return path } ///get the default log directory class func defaultDirectory() -> String { var path = "" let fileManager = FileManager.default #if os(iOS) let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) path = "\(paths[0])/Logs" #elseif os(OSX) let urls = fileManager.urls(for: .libraryDirectory, in: .userDomainMask) if let url = urls.last?.path { path = "\(url)/Logs" } #endif if !fileManager.fileExists(atPath: path) && path != "" { do { try fileManager.createDirectory(atPath: path, withIntermediateDirectories: false, attributes: nil) } catch _ { } } return path } //MARK: - Loggly Util Methods ///a free function to make writing to the log with Log type open func getLogglyReportsOutput() -> NSDictionary { return Loggly.logger.getReportsOutput() } // Before logging details it return empty path. Once logging is done. Method return exact report path open func getLogglyReportCSVfilPath() -> String { return Loggly.logger.getReportsFilePath() } // Get the Loggly Info Count open func getLogCountBasedonType(_ type: LogType) -> NSInteger{ return Loggly.logger.getCountBasedonLogType(type); } //MARK: - Loggly Info Methods ///a free function to make writing to the log open func logglyInfo(text: String) { Loggly.logger.write(LogType.Info, text: text) } ///a free function to make writing to the log with Log type open func logglyInfo(dictionary: NSDictionary) { Loggly.logger.write(LogType.Info, text: dictionary.jsonString) } //MARK: - Loggly Warning Methods ///a free function to make writing to the log open func logglyWarnings(text: String) { Loggly.logger.write(LogType.Warnings, text: text) } ///a free function to make writing to the log with Log type open func logglyWarnings(dictionary: NSDictionary) { Loggly.logger.write(LogType.Warnings, text: dictionary.jsonString) } //MARK: - Loggly Verbose Methods ///a free function to make writing to the log open func logglyVerbose(text: String) { Loggly.logger.write(LogType.Debug, text: text) } ///a free function to make writing to the log with Log type open func logglyVerbose(dictionary: Dictionary<AnyHashable, Any>) { Loggly.logger.write(LogType.Debug, text: dictionary.jsonString) } //MARK: - Loggly Debug Methods ///a free function to make writing to the log open func logglyDebug(text: String) { Loggly.logger.write(LogType.Debug, text: text) } ///a free function to make writing to the log with Log type open func logglyDebug(dictionary: NSDictionary) { Loggly.logger.write(LogType.Debug, text: dictionary.jsonString) } //MARK: - Loggly Error Methods ///a free function to make writing to the log open func logglyError(text: String) { Loggly.logger.write(LogType.Error, text: text) } ///a free function to make writing to the log with Log type open func logglyError(dictionary: NSDictionary) { Loggly.logger.write(LogType.Error, text: dictionary.jsonString) } ///a free function to make writing to the log with Log type open func logglyError(error: NSError) { Loggly.logger.write(LogType.Error, text: error.localizedDescription) } //MARK: - Loggly Methods with Log type ///a free function to make writing to the log with Log type open func loggly(_ type: LogType, text: String) { Loggly.logger.write(type, text: text) } ///a free function to make writing to the log with Log type open func loggly(_ type: LogType, dictionary: Dictionary<AnyHashable, Any>) { Loggly.logger.write(type, text: dictionary.jsonString) } ///a free function to make writing to the log with Log type open func loggly(_ type: LogType, dictionary: NSDictionary) { Loggly.logger.write(type, text: dictionary.jsonString) } } //MARK: - Loggly Util Methods ///a free function to make writing to the log with Log type public func getLogglyReportsOutput() -> NSDictionary { return Loggly.logger.getReportsOutput() } // Before logging details it return empty path. Once logging is done. Method return exact report path public func getLogglyReportCSVfilPath() -> String { return Loggly.logger.getReportsFilePath() } // Get the Loggly Info Count public func getLogCountBasedonType(_ type: LogType) -> NSInteger{ return Loggly.logger.getCountBasedonLogType(type); } //MARK: - Loggly Info Methods ///a free function to make writing to the log public func logglyInfo(text: String) { Loggly.logger.write(LogType.Info, text: text) } ///a free function to make writing to the log with Log type public func logglyInfo(_ dictionary: Dictionary<AnyHashable, Any>) { Loggly.logger.write(LogType.Info, text: dictionary.jsonString) } ///a free function to make writing to the log with Log type public func logglyInfo(_ dictionary: NSDictionary) { Loggly.logger.write(LogType.Info, text: dictionary.jsonString) } //MARK: - Loggly Warning Methods ///a free function to make writing to the log public func logglyWarnings(text: String) { Loggly.logger.write(LogType.Warnings, text: text) } ///a free function to make writing to the log with Log type public func logglyWarnings(_ dictionary: Dictionary<AnyHashable, Any>) { Loggly.logger.write(LogType.Warnings, text: dictionary.jsonString) } ///a free function to make writing to the log with Log type public func logglyWarnings(_ dictionary: NSDictionary) { Loggly.logger.write(LogType.Warnings, text: dictionary.jsonString) } //MARK: - Loggly Verbose Methods ///a free function to make writing to the log public func logglyVerbose(text: String) { Loggly.logger.write(LogType.Debug, text: text) } ///a free function to make writing to the log with Log type public func logglyVerbose(_ dictionary: Dictionary<AnyHashable, Any>) { Loggly.logger.write(LogType.Debug, text: dictionary.jsonString) } ///a free function to make writing to the log with Log type public func logglyVerbose(_ dictionary: NSDictionary) { Loggly.logger.write(LogType.Debug, text: dictionary.jsonString) } //MARK: - Loggly Debug Methods ///a free function to make writing to the log public func logglyDebug(text: String) { Loggly.logger.write(LogType.Debug, text: text) } ///a free function to make writing to the log with Log type public func logglyDebug(_ dictionary: Dictionary<AnyHashable, Any>) { Loggly.logger.write(LogType.Debug, text: dictionary.jsonString) } ///a free function to make writing to the log with Log type public func logglyDebug(_ dictionary: NSDictionary) { Loggly.logger.write(LogType.Debug, text: dictionary.jsonString) } //MARK: - Loggly Error Methods ///a free function to make writing to the log public func logglyError(text: String) { Loggly.logger.write(LogType.Error, text: text) } ///a free function to make writing to the log with Log type public func logglyError(_ dictionary: Dictionary<AnyHashable, Any>) { Loggly.logger.write(LogType.Error, text: dictionary.jsonString) } ///a free function to make writing to the log with Log type public func logglyError(_ dictionary: NSDictionary) { Loggly.logger.write(LogType.Error, text: dictionary.jsonString) } ///a free function to make writing to the log with Log type public func logglyError(_ error: NSError) { Loggly.logger.write(LogType.Error, text: error.localizedDescription) } ///a free function to make writing to the log with Log type public func logglyError(_ error: Error) { Loggly.logger.write(LogType.Error, text: error.localizedDescription) } //MARK: - Loggly Methods with Log type ///a free function to make writing to the log with Log type public func loggly(_ type: LogType, text: String) { Loggly.logger.write(type, text: text) } ///a free function to make writing to the log with Log type public func loggly(_ type: LogType, dictionary: Dictionary<AnyHashable, Any>) { Loggly.logger.write(type, text: dictionary.jsonString) } ///a free function to make writing to the log with Log type public func loggly(_ type: LogType, dictionary: NSDictionary) { Loggly.logger.write(type, text: dictionary.jsonString) }
mit
faa3707b9c8acd73144f436bf152480b
32.975584
158
0.57866
4.676359
false
false
false
false
gongmingqm10/DriftBook
DriftReading/DriftReading/LoginViewController.swift
1
1516
// // LoginViewController.swift // DriftReading // // Created by Ming Gong on 7/6/15. // Copyright © 2015 gongmingqm10. All rights reserved. // import UIKit class LoginViewController: ViewController, UITextFieldDelegate { let driftAPI = DriftAPI() @IBOutlet weak var emailTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! override func viewDidLoad() { if let _ = NSUserDefaults.standardUserDefaults().valueForKey(Constants.UserKey) { self.performSegueWithIdentifier("HomeSegue", sender: self) } self.passwordTextField.delegate = self } @IBAction func loginAction(sender: AnyObject) { let email = emailTextField.text! let password = passwordTextField.text! driftAPI.loginWith(email, password: password, success: { () in self.performSegueWithIdentifier("HomeSegue", sender: self) }) { (error: APIError) -> Void in let alertController = UIAlertController(title: "提示", message: "用户名或密码错误", preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: "确定", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(alertController, animated: true, completion: nil) } } func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return true } }
mit
3efe07d50fa75c743d61f2252a9dace8
33.674419
135
0.662643
5.106164
false
false
false
false
alecgorge/gapless-audio-bass-ios
BASS Audio Test/ViewController.swift
1
3489
// // ViewController.swift // BASS Audio Test // // Created by Alec Gorge on 10/20/16. // Copyright © 2016 Alec Gorge. All rights reserved. // import UIKit class ViewController: UIViewController { var bass: ObjectiveBASS? = nil let urls = ["http://phish.in/audio/000/025/507/25507.mp3", "http://phish.in/audio/000/025/508/25508.mp3", "http://phish.in/audio/000/025/509/25509.mp3", "http://phish.in/audio/000/025/510/25510.mp3"] var idx = 0 override func viewDidLoad() { super.viewDidLoad() /* bass = ObjectiveBASS() bass?.delegate = self bass?.dataSource = self bass?.play(URL(string: urls[idx])!, withIdentifier: 100) */ } func stringFromTimeInterval(_ interval: TimeInterval) -> String { let ti = NSInteger(interval) let seconds = ti % 60 let minutes = (ti / 60) % 60 return NSString(format: "%0.2d:%0.2d", minutes,seconds) as String } @IBOutlet weak var uiLabelElapsed: UILabel! @IBOutlet weak var uiLabelDuration: UILabel! @IBOutlet weak var uiSliderProgress: UISlider! @IBOutlet weak var uiProgressDownload: UIProgressView! @IBOutlet weak var uiLabelState: UILabel! @IBAction func uiSeek(_ sender: AnyObject) { bass?.seek(toPercent: 0.97) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } /* extension ViewController : ObjectiveBASSDelegate { func bassDownloadProgressChanged(_ forActiveTrack: Bool, downloadedBytes: UInt64, totalBytes: UInt64) { uiProgressDownload.progress = Float(downloadedBytes) / Float(totalBytes); } func textForState(_ state: BassPlaybackState) -> String { switch state { case .paused: return "Paused" case .playing: return "Playing" case .stalled: return "Stalled" case .stopped: return "Stopped" } } func bassDownloadPlaybackStateChanged(_ state: BassPlaybackState) { uiLabelState.text = textForState(state); } func bassErrorStartingStream(_ error: Error, for url: URL, withIdentifier identifier: Int) { print(error); } func bassPlaybackProgressChanged(_ elapsed: TimeInterval, withTotalDuration totalDuration: TimeInterval) { uiLabelElapsed.text = stringFromTimeInterval(elapsed) uiLabelDuration.text = stringFromTimeInterval(totalDuration) uiSliderProgress.value = Float(elapsed / totalDuration) } } extension ViewController : ObjectiveBASSDataSource { func identifierToIdx(_ ident: Int) -> Int { return ident - 100 } func indexToIdentifier(_ idx: Int) -> Int { return idx + 100 } func bassisPlayingLastTrack(_ bass: ObjectiveBASS, with url: URL, andIdentifier identifier: Int) -> Bool { return identifierToIdx(identifier) == urls.count - 1 } func bassNextTrackIdentifier(_ bass: ObjectiveBASS, after url: URL, withIdentifier identifier: Int) -> Int { return identifierToIdx(indexToIdentifier(identifier) + 1) } func bassLoadNextTrackURL(_ bass: ObjectiveBASS, forIdentifier identifier: Int) { bass.nextTrackURLLoaded(URL(string: urls[identifierToIdx(identifier)])!) } } */
mit
eeee5c49e6be0da6a939a2e55853665e
29.867257
112
0.634461
4.392947
false
false
false
false
vimeo/VimeoUpload
VimeoUpload/Upload/Controllers/VideoDeletionManager.swift
1
9688
// // RetryManager.swift // VimeoUpload // // Created by Alfred Hanssen on 11/23/15. // Copyright © 2015 Vimeo. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation import VimeoNetworking @objc public class VideoDeletionManager: NSObject { @objc public static let DeletionDefaultRetryCount = 3 private static let DeletionsArchiveKey = "deletions" // MARK: private let sessionManager: VimeoSessionManager private let retryCount: Int private let reachabilityChangedNotificaton = Notification.Name( rawValue: NetworkingNotification.reachabilityDidChange.rawValue ) // MARK: private var deletions: [VideoUri: Int] = [:] private let operationQueue: OperationQueue private let archiver: KeyedArchiver // MARK: - Initialization deinit { self.operationQueue.cancelAllOperations() self.removeObservers() } /// Initializes a video deletion manager object. Upon creation, the /// object will attempt to create a folder to save deletion information /// if needed. If the folder already exists, it will attempt to load /// that information into memory, then perform deletion. /// /// The folder is created with the following scheme: /// /// ``` /// Documents/deletions /// ``` /// /// - Parameters: /// - sessionManager: A session manager object capable of deleting /// uploads. /// - archivePrefix: The prefix of the archive file. You pass in the /// prefix if you want to keep track of multiple archive files. By /// default, it has the value of `nil`. /// - documentsFolderURL: The Documents folder's URL in which the folder /// is located. /// - retryCount: The number of retries. The default value is `3`. /// - Returns: `nil` if the keyed archiver cannot load deletions' archive. @objc public init?(sessionManager: VimeoSessionManager, archivePrefix: String? = nil, documentsFolderURL: URL, retryCount: Int = VideoDeletionManager.DeletionDefaultRetryCount) { guard let archiver = VideoDeletionManager.setupArchiver(name: VideoDeletionManager.DeletionsArchiveKey, archivePrefix: archivePrefix, documentsFolderURL: documentsFolderURL) else { return nil } self.archiver = archiver self.sessionManager = sessionManager self.retryCount = retryCount self.operationQueue = OperationQueue() self.operationQueue.maxConcurrentOperationCount = OperationQueue.defaultMaxConcurrentOperationCount super.init() self.addObservers() self.reachabilityDidChange(nil) // Set suspended state let migrator = ArchiveMigrator(fileManager: FileManager.default) self.deletions = self.loadDeletions(withMigrator: migrator) self.startDeletions() } // MARK: Setup private static func setupArchiver(name: String, archivePrefix: String?, documentsFolderURL: URL) -> KeyedArchiver? { let deletionsFolder = documentsFolderURL.appendingPathComponent(name) let deletionsArchiveDirectory = deletionsFolder.appendingPathComponent(VideoDeletionManager.DeletionsArchiveKey) if FileManager.default.fileExists(atPath: deletionsArchiveDirectory.path) == false { do { try FileManager.default.createDirectory(at: deletionsArchiveDirectory, withIntermediateDirectories: true, attributes: nil) } catch { return nil } } return KeyedArchiver(basePath: deletionsArchiveDirectory.path, archivePrefix: archivePrefix) } // MARK: Archiving private func loadDeletions(withMigrator migrator: ArchiveMigrating?) -> [VideoUri: Int] { let relativeFolderURL = URL(string: VideoDeletionManager.DeletionsArchiveKey)?.appendingPathComponent(VideoDeletionManager.DeletionsArchiveKey) guard let retries = ArchiveDataLoader.loadData(relativeFolderURL: relativeFolderURL, archiver: self.archiver, key: VideoDeletionManager.DeletionsArchiveKey) as? [VideoUri: Int] else { return [:] } return retries } private func startDeletions() { for (key, value) in deletions { self.deleteVideo(withURI: key, retryCount: value) } } private func save() { self.archiver.save(object: deletions, key: type(of: self).DeletionsArchiveKey) } // MARK: Public API @objc public func deleteVideo(withURI uri: String) { self.deleteVideo(withURI: uri, retryCount: self.retryCount) } // MARK: Private API private func deleteVideo(withURI uri: String, retryCount: Int) { self.deletions[uri] = retryCount self.save() let operation = DeleteVideoOperation(sessionManager: self.sessionManager, videoUri: uri) operation.completionBlock = { [weak self] () -> Void in DispatchQueue.main.async(execute: { [weak self] () -> Void in guard let strongSelf = self else { return } if operation.isCancelled == true { return } if let error = operation.error { if error.is404NotFoundError { strongSelf.deletions.removeValue(forKey: uri) // The video has already been deleted strongSelf.save() return } if let retryCount = strongSelf.deletions[uri], retryCount > 0 { let newRetryCount = retryCount - 1 strongSelf.deleteVideo(withURI: uri, retryCount: newRetryCount) // Decrement the retryCount and try again } else { strongSelf.deletions.removeValue(forKey: uri) // We retried the required number of times, nothing more to do strongSelf.save() } } else { strongSelf.deletions.removeValue(forKey: uri) strongSelf.save() } }) } self.operationQueue.addOperation(operation) } // MARK: Notifications private func addObservers() { NotificationCenter.default.addObserver(self, selector: .applicationWillEnterForeground, name: UIApplication.willEnterForegroundNotification, object: nil) NotificationCenter.default.addObserver(self, selector: .applicationDidEnterBackground, name: UIApplication.didEnterBackgroundNotification, object: nil) NotificationCenter.default.addObserver(self, selector: .reachabilityDidChange, name: reachabilityChangedNotificaton, object: nil) } private func removeObservers() { NotificationCenter.default.removeObserver(self, name: UIApplication.willEnterForegroundNotification, object: nil) NotificationCenter.default.removeObserver(self, name: UIApplication.didEnterBackgroundNotification, object: nil) NotificationCenter.default.removeObserver(self, name: reachabilityChangedNotificaton, object: nil) } @objc func applicationWillEnterForeground(_ notification: Notification) { self.operationQueue.isSuspended = false } @objc func applicationDidEnterBackground(_ notification: Notification) { self.operationQueue.isSuspended = true } @objc func reachabilityDidChange(_ notification: Notification?) { self.operationQueue.isSuspended = !VimeoReachabilityProvider.isReachable } } private extension Selector { static let applicationWillEnterForeground = #selector(UIApplicationDelegate.applicationWillEnterForeground(_:)) static let applicationDidEnterBackground = #selector(UIApplicationDelegate.applicationDidEnterBackground(_:)) static let reachabilityDidChange = #selector(VideoDeletionManager.reachabilityDidChange(_:)) }
mit
987819592c4e866bc3bf4b21f45b9965
36.988235
186
0.633633
5.589729
false
false
false
false
ChaselAn/CodeLibrary
codeLibrary/codeLibrary/Extension/Dictionary+Extension.swift
1
1385
// // Dictionary+Extension.swift // codeLibrary // // Created by ancheng on 2017/2/9. // Copyright © 2017年 ac. All rights reserved. // import Foundation extension Dictionary { /// 合并两个字典,键相同的会被后者覆盖 /// /// - Parameter other: 要合并的字典 mutating func merge<S>(_ other: S) where S: Sequence, S.Iterator.Element == (key: Key, value: Value) { for (k, v) in other { self[k] = v } } /// 通过元祖数组初始化一个字典 /// /// 例: /// let defaultAlarms = (1..<5).map { (key: "Alarm \($0)", value: false) } /// let alarmsDictionary = Dictionary(defaultAlarms) /// /// - Parameter sequence: 元祖数组 init<S: Sequence>(_ sequence: S) where S.Iterator.Element == (key: Key, value: Value) { self = [:] self.merge(sequence) } /// 保留字典结构的前提下,只对value进行map操作 /// /// 例: /// let dict: [String : Any] = ["name": "123", "num": 123] /// let strDict = dict.mapValues(transform: {"\($0)"}) //["name":"123","num":"123"] /// /// - Parameter transform: map条件 /// - Returns: 保持原来key不变的数组 func mapValues<NewValue>(transform: (Value) -> NewValue) -> [Key:NewValue] { return Dictionary<Key, NewValue>(map { (key, value) in return (key, transform(value)) }) } }
mit
e0efb2841d641a627eb86e84a91fe1d1
23.27451
85
0.571082
3.215584
false
false
false
false
seguemodev/Meducated-Ninja
iOS/Zippy/Medication.swift
1
47812
// // Medication.swift // Zippy // // Created by Geoffrey Bender on 6/19/15. // Copyright (c) 2015 Segue Technologies, Inc. All rights reserved. // import UIKit class Medication: NSObject, NSCoding { // MARK: - Properties // The name of the medicine cabinet this medication is saved in var medicineCabinet: String? // ID and version var set_id: String? var document_id: String? var version: String? var effective_time: String? // Abuse and overdosage var drug_abuse_and_dependence: [String]? var controlled_substance: [String]? var abuse: [String]? var dependence: [String]? var overdosage: [String]? // Adverse effects and interactions var adverse_reactions: [String]? var drug_interactions: [String]? var drug_and_or_laboratory_test_interactions: [String]? // Clinical pharmacology var clinical_pharmacology: [String]? var mechanism_of_action: [String]? var pharmacodynamics: [String]? var pharmacokinetics: [String]? // Indications, usage, and dosage var indications_and_usage: [String]? var contraindications: [String]? var dosage_and_administration: [String]? var dosage_forms_and_strengths: [String]? var purpose: [String]? var product_description: [String]? var active_ingredient: [String]? var inactive_ingredient: [String]? var spl_product_data_elements: [String]? // Patient information var spl_patient_package_insert: [String]? var information_for_patients: [String]? var information_for_owners_or_caregivers: [String]? var instructions_for_use: [String]? var ask_doctor: [String]? var ask_doctor_or_pharmacist: [String]? var do_not_use: [String]? var keep_out_of_reach_of_children: [String]? var other_safety_information: [String]? var questions: [String]? var stop_use: [String]? var when_using: [String]? var patient_medication_information: [String]? var spl_medguide: [String]? // Special Populations var use_in_specific_populations: [String]? var pregnancy: [String]? var teratogenic_effects: [String]? var nonteratogenic_effects: [String]? var labor_and_delivery: [String]? var nursing_mothers: [String]? var pregnancy_or_breast_feeding: [String]? var pediatric_use: [String]? var geriatric_use: [String]? // Nonclinical toxicology var nonclinical_toxicology: [String]? var carcinogenesis_and_mutagenesis_and_impairment_of_fertility: [String]? var animal_pharmacology_and_or_toxicology: [String]? // References var clinical_studies: [String]? var references: [String]? // Supply, storage, and handling var how_supplied: [String]? var storage_and_handling: [String]? var safe_handling_warning: [String]? // Warnings and precautions var boxed_warning: [String]? var warnings_and_precautions: [String]? var user_safety_warnings: [String]? var precautions: [String]? var warnings: [String]? var general_precautions: [String]? // Other fields var laboratory_tests: [String]? var recent_major_changes: [String]? var microbiology: [String]? var package_label_principal_display_panel: [String]? var spl_unclassified_section: [String]? // Open FDA var openfda: NSDictionary? // MARK: - Methods required init(coder aDecoder: NSCoder) { // Saved medicine cabinet self.medicineCabinet = aDecoder.decodeObjectForKey("medicineCabinet") as? String // ID and version self.set_id = aDecoder.decodeObjectForKey("set_id") as? String self.document_id = aDecoder.decodeObjectForKey("document_id") as? String self.version = aDecoder.decodeObjectForKey("version") as? String self.effective_time = aDecoder.decodeObjectForKey("effective_time") as? String // Abuse and overdosage self.drug_abuse_and_dependence = aDecoder.decodeObjectForKey("drug_abuse_and_dependence") as? [String] self.controlled_substance = aDecoder.decodeObjectForKey("controlled_substance") as? [String] self.abuse = aDecoder.decodeObjectForKey("abuse") as? [String] self.dependence = aDecoder.decodeObjectForKey("dependence") as? [String] self.overdosage = aDecoder.decodeObjectForKey("overdosage") as? [String] // Adverse effects and interactions self.adverse_reactions = aDecoder.decodeObjectForKey("adverse_reactions") as? [String] self.drug_interactions = aDecoder.decodeObjectForKey("drug_interactions") as? [String] self.drug_and_or_laboratory_test_interactions = aDecoder.decodeObjectForKey("drug_and_or_laboratory_test_interactions") as? [String] // Clinical pharmacology self.clinical_pharmacology = aDecoder.decodeObjectForKey("clinical_pharmacology") as? [String] self.mechanism_of_action = aDecoder.decodeObjectForKey("mechanism_of_action") as? [String] self.pharmacodynamics = aDecoder.decodeObjectForKey("pharmacodynamics") as? [String] self.pharmacokinetics = aDecoder.decodeObjectForKey("pharmacokinetics") as? [String] // Indications, usage, and dosage self.indications_and_usage = aDecoder.decodeObjectForKey("indications_and_usage") as? [String] self.contraindications = aDecoder.decodeObjectForKey("contraindications") as? [String] self.dosage_and_administration = aDecoder.decodeObjectForKey("dosage_and_administration") as? [String] self.dosage_forms_and_strengths = aDecoder.decodeObjectForKey("dosage_forms_and_strengths") as? [String] self.purpose = aDecoder.decodeObjectForKey("purpose") as? [String] self.product_description = aDecoder.decodeObjectForKey("product_description") as? [String] self.active_ingredient = aDecoder.decodeObjectForKey("active_ingredient") as? [String] self.inactive_ingredient = aDecoder.decodeObjectForKey("inactive_ingredient") as? [String] self.spl_product_data_elements = aDecoder.decodeObjectForKey("spl_product_data_elements") as? [String] // Patient information self.spl_patient_package_insert = aDecoder.decodeObjectForKey("spl_patient_package_insert") as? [String] self.information_for_patients = aDecoder.decodeObjectForKey("information_for_patients") as? [String] self.information_for_owners_or_caregivers = aDecoder.decodeObjectForKey("information_for_owners_or_caregivers") as? [String] self.instructions_for_use = aDecoder.decodeObjectForKey("instructions_for_use") as? [String] self.ask_doctor = aDecoder.decodeObjectForKey("ask_doctor") as? [String] self.ask_doctor_or_pharmacist = aDecoder.decodeObjectForKey("ask_doctor_or_pharmacist") as? [String] self.do_not_use = aDecoder.decodeObjectForKey("do_not_use") as? [String] self.keep_out_of_reach_of_children = aDecoder.decodeObjectForKey("keep_out_of_reach_of_children") as? [String] self.other_safety_information = aDecoder.decodeObjectForKey("other_safety_information") as? [String] self.questions = aDecoder.decodeObjectForKey("questions") as? [String] self.stop_use = aDecoder.decodeObjectForKey("stop_use") as? [String] self.when_using = aDecoder.decodeObjectForKey("when_using") as? [String] self.patient_medication_information = aDecoder.decodeObjectForKey("patient_medication_information") as? [String] self.spl_medguide = aDecoder.decodeObjectForKey("spl_medguide") as? [String] // Special Populations self.use_in_specific_populations = aDecoder.decodeObjectForKey("use_in_specific_populations") as? [String] self.pregnancy = aDecoder.decodeObjectForKey("pregnancy") as? [String] self.teratogenic_effects = aDecoder.decodeObjectForKey("teratogenic_effects") as? [String] self.nonteratogenic_effects = aDecoder.decodeObjectForKey("nonteratogenic_effects") as? [String] self.labor_and_delivery = aDecoder.decodeObjectForKey("labor_and_delivery") as? [String] self.nursing_mothers = aDecoder.decodeObjectForKey("nursing_mothers") as? [String] self.pregnancy_or_breast_feeding = aDecoder.decodeObjectForKey("pregnancy_or_breast_feeding") as? [String] self.pediatric_use = aDecoder.decodeObjectForKey("pediatric_use") as? [String] self.geriatric_use = aDecoder.decodeObjectForKey("geriatric_use") as? [String] // Nonclinical toxicology self.nonclinical_toxicology = aDecoder.decodeObjectForKey("nonclinical_toxicology") as? [String] self.carcinogenesis_and_mutagenesis_and_impairment_of_fertility = aDecoder.decodeObjectForKey("carcinogenesis_and_mutagenesis_and_impairment_of_fertility") as? [String] self.animal_pharmacology_and_or_toxicology = aDecoder.decodeObjectForKey("animal_pharmacology_and_or_toxicology") as? [String] // References self.clinical_studies = aDecoder.decodeObjectForKey("clinical_studies") as? [String] self.references = aDecoder.decodeObjectForKey("references") as? [String] // Supply, storage, and handling self.how_supplied = aDecoder.decodeObjectForKey("how_supplied") as? [String] self.storage_and_handling = aDecoder.decodeObjectForKey("storage_and_handling") as? [String] self.safe_handling_warning = aDecoder.decodeObjectForKey("safe_handling_warning") as? [String] // Warnings and precautions self.boxed_warning = aDecoder.decodeObjectForKey("boxed_warning") as? [String] self.warnings_and_precautions = aDecoder.decodeObjectForKey("warnings_and_precautions") as? [String] self.user_safety_warnings = aDecoder.decodeObjectForKey("user_safety_warnings") as? [String] self.precautions = aDecoder.decodeObjectForKey("precautions") as? [String] self.warnings = aDecoder.decodeObjectForKey("warnings") as? [String] self.general_precautions = aDecoder.decodeObjectForKey("general_precautions") as? [String] // Other fields self.laboratory_tests = aDecoder.decodeObjectForKey("laboratory_tests") as? [String] self.recent_major_changes = aDecoder.decodeObjectForKey("recent_major_changes") as? [String] self.microbiology = aDecoder.decodeObjectForKey("microbiology") as? [String] self.package_label_principal_display_panel = aDecoder.decodeObjectForKey("package_label_principal_display_panel") as? [String] self.spl_unclassified_section = aDecoder.decodeObjectForKey("spl_unclassified_section") as? [String] // OpenFDA self.openfda = aDecoder.decodeObjectForKey("openfda") as? NSDictionary } override init() { // Saved medicine cabinet self.medicineCabinet = "" // ID and version self.set_id = "" self.document_id = "" self.version = "" self.effective_time = "" // Abuse and overdosage self.drug_abuse_and_dependence = [String]() self.controlled_substance = [String]() self.abuse = [String]() self.dependence = [String]() self.overdosage = [String]() // Adverse effects and interactions self.adverse_reactions = [String]() self.drug_interactions = [String]() self.drug_and_or_laboratory_test_interactions = [String]() // Clinical pharmacology self.clinical_pharmacology = [String]() self.mechanism_of_action = [String]() self.pharmacodynamics = [String]() self.pharmacokinetics = [String]() // Indications, usage, and dosage self.indications_and_usage = [String]() self.contraindications = [String]() self.dosage_and_administration = [String]() self.dosage_forms_and_strengths = [String]() self.purpose = [String]() self.product_description = [String]() self.active_ingredient = [String]() self.inactive_ingredient = [String]() self.spl_product_data_elements = [String]() // Patient information self.spl_patient_package_insert = [String]() self.information_for_patients = [String]() self.information_for_owners_or_caregivers = [String]() self.instructions_for_use = [String]() self.ask_doctor = [String]() self.ask_doctor_or_pharmacist = [String]() self.do_not_use = [String]() self.keep_out_of_reach_of_children = [String]() self.other_safety_information = [String]() self.questions = [String]() self.stop_use = [String]() self.when_using = [String]() self.patient_medication_information = [String]() self.spl_medguide = [String]() // Special Populations self.use_in_specific_populations = [String]() self.pregnancy = [String]() self.teratogenic_effects = [String]() self.nonteratogenic_effects = [String]() self.labor_and_delivery = [String]() self.nursing_mothers = [String]() self.pregnancy_or_breast_feeding = [String]() self.pediatric_use = [String]() self.geriatric_use = [String]() // Nonclinical toxicology self.nonclinical_toxicology = [String]() self.carcinogenesis_and_mutagenesis_and_impairment_of_fertility = [String]() self.animal_pharmacology_and_or_toxicology = [String]() // References self.clinical_studies = [String]() self.references = [String]() // Supply, storage, and handling self.how_supplied = [String]() self.storage_and_handling = [String]() self.safe_handling_warning = [String]() // Warnings and precautions self.boxed_warning = [String]() self.warnings_and_precautions = [String]() self.user_safety_warnings = [String]() self.precautions = [String]() self.warnings = [String]() self.general_precautions = [String]() // Other fields self.laboratory_tests = [String]() self.recent_major_changes = [String]() self.microbiology = [String]() self.package_label_principal_display_panel = [String]() self.spl_unclassified_section = [String]() // Open FDA self.openfda = NSDictionary() super.init() } func encodeWithCoder(aCoder: NSCoder) { // Saved medicine cabinet aCoder.encodeObject(self.medicineCabinet, forKey: "medicineCabinet") // ID and version aCoder.encodeObject(self.set_id, forKey: "set_id") aCoder.encodeObject(self.document_id, forKey: "document_id") aCoder.encodeObject(self.version, forKey: "version") aCoder.encodeObject(self.effective_time, forKey: "effective_time") // Abuse and overdosage aCoder.encodeObject(self.drug_abuse_and_dependence, forKey: "drug_abuse_and_dependence") aCoder.encodeObject(self.controlled_substance, forKey: "controlled_substance") aCoder.encodeObject(self.abuse, forKey: "abuse") aCoder.encodeObject(self.dependence, forKey: "dependence") aCoder.encodeObject(self.overdosage, forKey: "overdosage") // Adverse effects and interactions aCoder.encodeObject(self.adverse_reactions, forKey: "adverse_reactions") aCoder.encodeObject(self.drug_interactions, forKey: "drug_interactions") aCoder.encodeObject(self.drug_and_or_laboratory_test_interactions, forKey: "drug_and_or_laboratory_test_interactions") // Clinical pharmacology aCoder.encodeObject(self.clinical_pharmacology, forKey: "clinical_pharmacology") aCoder.encodeObject(self.mechanism_of_action, forKey: "mechanism_of_action") aCoder.encodeObject(self.pharmacodynamics, forKey: "pharmacodynamics") aCoder.encodeObject(self.pharmacokinetics, forKey: "pharmacokinetics") // Indications, usage, and dosage aCoder.encodeObject(self.indications_and_usage, forKey: "indications_and_usage") aCoder.encodeObject(self.contraindications, forKey: "contraindications") aCoder.encodeObject(self.dosage_and_administration, forKey: "dosage_and_administration") aCoder.encodeObject(self.dosage_forms_and_strengths, forKey: "dosage_forms_and_strengths") aCoder.encodeObject(self.purpose, forKey: "purpose") aCoder.encodeObject(self.product_description, forKey: "product_description") aCoder.encodeObject(self.active_ingredient, forKey: "active_ingredient") aCoder.encodeObject(self.inactive_ingredient, forKey: "inactive_ingredient") aCoder.encodeObject(self.spl_product_data_elements, forKey: "spl_product_data_elements") // Patient information aCoder.encodeObject(self.spl_patient_package_insert, forKey: "spl_patient_package_insert") aCoder.encodeObject(self.information_for_patients, forKey: "information_for_patients") aCoder.encodeObject(self.information_for_owners_or_caregivers, forKey: "information_for_owners_or_caregivers") aCoder.encodeObject(self.instructions_for_use, forKey: "instructions_for_use") aCoder.encodeObject(self.ask_doctor, forKey: "ask_doctor") aCoder.encodeObject(self.ask_doctor_or_pharmacist, forKey: "ask_doctor_or_pharmacist") aCoder.encodeObject(self.do_not_use, forKey: "do_not_use") aCoder.encodeObject(self.keep_out_of_reach_of_children, forKey: "keep_out_of_reach_of_children") aCoder.encodeObject(self.other_safety_information, forKey: "other_safety_information") aCoder.encodeObject(self.questions, forKey: "questions") aCoder.encodeObject(self.stop_use, forKey: "stop_use") aCoder.encodeObject(self.when_using, forKey: "when_using") aCoder.encodeObject(self.patient_medication_information, forKey: "patient_medication_information") aCoder.encodeObject(self.spl_medguide, forKey: "spl_medguide") // Special Populations aCoder.encodeObject(self.use_in_specific_populations, forKey: "use_in_specific_populations") aCoder.encodeObject(self.pregnancy, forKey: "pregnancy") aCoder.encodeObject(self.teratogenic_effects, forKey: "teratogenic_effects") aCoder.encodeObject(self.nonteratogenic_effects, forKey: "nonteratogenic_effects") aCoder.encodeObject(self.labor_and_delivery, forKey: "labor_and_delivery") aCoder.encodeObject(self.nursing_mothers, forKey: "nursing_mothers") aCoder.encodeObject(self.pregnancy_or_breast_feeding, forKey: "pregnancy_or_breast_feeding") aCoder.encodeObject(self.pediatric_use, forKey: "pediatric_use") aCoder.encodeObject(self.geriatric_use, forKey: "geriatric_use") // Nonclinical toxicology aCoder.encodeObject(self.nonclinical_toxicology, forKey: "nonclinical_toxicology") aCoder.encodeObject(self.carcinogenesis_and_mutagenesis_and_impairment_of_fertility, forKey: "carcinogenesis_and_mutagenesis_and_impairment_of_fertility") aCoder.encodeObject(self.animal_pharmacology_and_or_toxicology, forKey: "animal_pharmacology_and_or_toxicology") // References aCoder.encodeObject(self.clinical_studies, forKey: "clinical_studies") aCoder.encodeObject(self.references, forKey: "references") // Supply, storage, and handling aCoder.encodeObject(self.how_supplied, forKey: "how_supplied") aCoder.encodeObject(self.storage_and_handling, forKey: "storage_and_handling") aCoder.encodeObject(self.safe_handling_warning, forKey: "safe_handling_warning") // Warnings and precautions aCoder.encodeObject(self.boxed_warning, forKey: "boxed_warning") aCoder.encodeObject(self.warnings_and_precautions, forKey: "warnings_and_precautions") aCoder.encodeObject(self.user_safety_warnings, forKey: "user_safety_warnings") aCoder.encodeObject(self.precautions, forKey: "precautions") aCoder.encodeObject(self.warnings, forKey: "warnings") aCoder.encodeObject(self.general_precautions, forKey: "general_precautions") // Other fields aCoder.encodeObject(self.laboratory_tests, forKey: "laboratory_tests") aCoder.encodeObject(self.recent_major_changes, forKey: "recent_major_changes") aCoder.encodeObject(self.microbiology, forKey: "microbiology") aCoder.encodeObject(self.package_label_principal_display_panel, forKey: "package_label_principal_display_panel") aCoder.encodeObject(self.spl_unclassified_section, forKey: "spl_unclassified_section") // Open FDA aCoder.encodeObject(self.openfda, forKey: "openfda") } // Initializes object from JSON dict init (result: NSDictionary) { // If we have a medicine cabinet self.medicineCabinet = "" // ID and version if let set_id = result["set_id"] as? String{ self.set_id = set_id } if let document_id = result["document_id"] as? String{ self.document_id = document_id } if let version = result["version"] as? String{ self.version = version } if let effective_time = result["effective_time"] as? String{ self.effective_time = effective_time } // Abuse and overdosage if let drug_abuse_and_dependence = result["drug_abuse_and_dependence"] as? [String]{ self.drug_abuse_and_dependence = drug_abuse_and_dependence } if let controlled_substance = result["controlled_substance"] as? [String]{ self.controlled_substance = controlled_substance } if let abuse = result["abuse"] as? [String]{ self.abuse = abuse } if let dependence = result["dependence"] as? [String]{ self.dependence = dependence } if let overdosage = result["overdosage"] as? [String]{ self.overdosage = overdosage } // Adverse effects and interactions if let adverse_reactions = result["adverse_reactions"] as? [String]{ self.adverse_reactions = adverse_reactions } if let drug_interactions = result["drug_interactions"] as? [String]{ self.drug_interactions = drug_interactions } if let drug_and_or_laboratory_test_interactions = result["drug_and_or_laboratory_test_interactions"] as? [String]{ self.drug_and_or_laboratory_test_interactions = drug_and_or_laboratory_test_interactions } // Clinical pharmacology if let clinical_pharmacology = result["clinical_pharmacology"] as? [String]{ self.clinical_pharmacology = clinical_pharmacology } if let mechanism_of_action = result["mechanism_of_action"] as? [String]{ self.mechanism_of_action = mechanism_of_action } if let pharmacodynamics = result["pharmacodynamics"] as? [String]{ self.pharmacodynamics = pharmacodynamics } if let pharmacokinetics = result["pharmacokinetics"] as? [String]{ self.pharmacokinetics = pharmacokinetics } // Indications, usage, and dosage if let indications_and_usage = result["indications_and_usage"] as? [String]{ self.indications_and_usage = indications_and_usage } if let contraindications = result["contraindications"] as? [String]{ self.contraindications = contraindications } if let dosage_and_administration = result["dosage_and_administration"] as? [String]{ self.dosage_and_administration = dosage_and_administration } if let dosage_forms_and_strengths = result["dosage_forms_and_strengths"] as? [String]{ self.dosage_forms_and_strengths = dosage_forms_and_strengths } if let purpose = result["purpose"] as? [String]{ self.purpose = purpose } if let product_description = result["product_description"] as? [String]{ self.product_description = product_description } if let active_ingredient = result["active_ingredient"] as? [String]{ self.active_ingredient = active_ingredient } if let inactive_ingredient = result["inactive_ingredient"] as? [String]{ self.inactive_ingredient = inactive_ingredient } if let spl_product_data_elements = result["spl_product_data_elements"] as? [String]{ self.spl_product_data_elements = spl_product_data_elements } // Patient information if let spl_patient_package_insert = result["spl_patient_package_insert"] as? [String]{ self.spl_patient_package_insert = spl_patient_package_insert } if let information_for_patients = result["information_for_patients"] as? [String]{ self.information_for_patients = information_for_patients } if let information_for_owners_or_caregivers = result["information_for_owners_or_caregivers"] as? [String]{ self.information_for_owners_or_caregivers = information_for_owners_or_caregivers } if let instructions_for_use = result["instructions_for_use"] as? [String]{ self.instructions_for_use = instructions_for_use } if let ask_doctor = result["ask_doctor"] as? [String]{ self.ask_doctor = ask_doctor } if let ask_doctor_or_pharmacist = result["ask_doctor_or_pharmacist"] as? [String]{ self.ask_doctor_or_pharmacist = ask_doctor_or_pharmacist } if let do_not_use = result["do_not_use"] as? [String]{ self.do_not_use = do_not_use } if let keep_out_of_reach_of_children = result["keep_out_of_reach_of_children"] as? [String]{ self.keep_out_of_reach_of_children = keep_out_of_reach_of_children } if let other_safety_information = result["other_safety_information"] as? [String]{ self.other_safety_information = other_safety_information } if let questions = result["questions"] as? [String]{ self.questions = questions } if let stop_use = result["stop_use"] as? [String]{ self.stop_use = stop_use } if let when_using = result["when_using"] as? [String]{ self.when_using = when_using } if let patient_medication_information = result["patient_medication_information"] as? [String]{ self.patient_medication_information = patient_medication_information } if let spl_medguide = result["spl_medguide"] as? [String]{ self.spl_medguide = spl_medguide } // Special Populations if let use_in_specific_populations = result["use_in_specific_populations"] as? [String]{ self.use_in_specific_populations = use_in_specific_populations } if let pregnancy = result["pregnancy"] as? [String]{ self.pregnancy = pregnancy } if let teratogenic_effects = result["teratogenic_effects"] as? [String]{ self.teratogenic_effects = teratogenic_effects } if let nonteratogenic_effects = result["nonteratogenic_effects"] as? [String]{ self.nonteratogenic_effects = nonteratogenic_effects } if let labor_and_delivery = result["labor_and_delivery"] as? [String]{ self.labor_and_delivery = labor_and_delivery } if let nursing_mothers = result["nursing_mothers"] as? [String]{ self.nursing_mothers = nursing_mothers } if let pregnancy_or_breast_feeding = result["pregnancy_or_breast_feeding"] as? [String]{ self.pregnancy_or_breast_feeding = pregnancy_or_breast_feeding } if let pediatric_use = result["pediatric_use"] as? [String]{ self.pediatric_use = pediatric_use } if let geriatric_use = result["geriatric_use"] as? [String]{ self.geriatric_use = geriatric_use } // Nonclinical toxicology if let nonclinical_toxicology = result["nonclinical_toxicology"] as? [String]{ self.nonclinical_toxicology = nonclinical_toxicology } if let carcinogenesis_and_mutagenesis_and_impairment_of_fertility = result["carcinogenesis_and_mutagenesis_and_impairment_of_fertility"] as? [String]{ self.carcinogenesis_and_mutagenesis_and_impairment_of_fertility = carcinogenesis_and_mutagenesis_and_impairment_of_fertility } if let animal_pharmacology_and_or_toxicology = result["animal_pharmacology_and_or_toxicology"] as? [String]{ self.animal_pharmacology_and_or_toxicology = animal_pharmacology_and_or_toxicology } // References if let clinical_studies = result["clinical_studies"] as? [String]{ self.clinical_studies = clinical_studies } if let references = result["references"] as? [String]{ self.references = references } // Supply, storage, and handling if let how_supplied = result["how_supplied"] as? [String]{ self.how_supplied = how_supplied } if let storage_and_handling = result["storage_and_handling"] as? [String]{ self.storage_and_handling = storage_and_handling } if let safe_handling_warning = result["safe_handling_warning"] as? [String]{ self.safe_handling_warning = safe_handling_warning } // Warnings and precautions if let boxed_warning = result["boxed_warning"] as? [String]{ self.boxed_warning = boxed_warning } if let warnings_and_precautions = result["warnings_and_precautions"] as? [String]{ self.warnings_and_precautions = warnings_and_precautions } if let user_safety_warnings = result["user_safety_warnings"] as? [String]{ self.user_safety_warnings = user_safety_warnings } if let precautions = result["precautions"] as? [String]{ self.precautions = precautions } if let warnings = result["warnings"] as? [String]{ self.warnings = warnings } if let general_precautions = result["general_precautions"] as? [String]{ self.general_precautions = general_precautions } // Other fields if let laboratory_tests = result["laboratory_tests"] as? [String]{ self.laboratory_tests = laboratory_tests } if let recent_major_changes = result["recent_major_changes"] as? [String]{ self.recent_major_changes = recent_major_changes } if let microbiology = result["microbiology"] as? [String]{ self.microbiology = microbiology } if let package_label_principal_display_panel = result["package_label_principal_display_panel"] as? [String]{ self.package_label_principal_display_panel = package_label_principal_display_panel } if let spl_unclassified_section = result["spl_unclassified_section"] as? [String]{ self.spl_unclassified_section = spl_unclassified_section } // Open FDA if let openfda = result["openfda"] as? NSDictionary{ self.openfda = openfda } } // Returns list of properties in original format func getDefinedProperties() -> [String] { var properties = [String]() // ID and version // if self.set_id != nil{ // properties.append("set_id") // } // if self.document_id != nil{ // properties.append("document_id") // } // if self.version != nil{ // properties.append("version") // } // if self.effective_time != nil{ // properties.append("effective_time") // } // Abuse and overdosage if self.drug_abuse_and_dependence != nil{ properties.append("drug_abuse_and_dependence") } if self.controlled_substance != nil{ properties.append("controlled_substance") } if self.abuse != nil{ properties.append("abuse") } if self.dependence != nil{ properties.append("dependence") } if self.overdosage != nil{ properties.append("overdosage") } // Adverse effects and interactions if self.adverse_reactions != nil{ properties.append("adverse_reactions") } if self.drug_interactions != nil{ properties.append("drug_interactions") } if self.drug_and_or_laboratory_test_interactions != nil{ properties.append("drug_and_or_laboratory_test_interactions") } // Clinical pharmacology if self.clinical_pharmacology != nil{ properties.append("clinical_pharmacology") } if self.mechanism_of_action != nil{ properties.append("mechanism_of_action") } if self.pharmacodynamics != nil{ properties.append("pharmacodynamics") } if self.pharmacokinetics != nil{ properties.append("pharmacokinetics") } // Indications, usage, and dosage if self.indications_and_usage != nil{ properties.append("indications_and_usage") } if self.contraindications != nil{ properties.append("contraindications") } if self.dosage_and_administration != nil{ properties.append("dosage_and_administration") } if self.dosage_forms_and_strengths != nil{ properties.append("dosage_forms_and_strengths") } if self.purpose != nil{ properties.append("purpose") } if self.product_description != nil{ properties.append("product_description") } if self.active_ingredient != nil{ properties.append("active_ingredient") } if self.inactive_ingredient != nil{ properties.append("inactive_ingredient") } if self.spl_product_data_elements != nil{ properties.append("spl_product_data_elements") } // Patient information if self.spl_patient_package_insert != nil{ properties.append("spl_patient_package_insert") } if self.information_for_patients != nil{ properties.append("information_for_patients") } if self.information_for_owners_or_caregivers != nil{ properties.append("information_for_owners_or_caregivers") } if self.instructions_for_use != nil{ properties.append("instructions_for_use") } if self.ask_doctor != nil{ properties.append("ask_doctor") } if self.ask_doctor_or_pharmacist != nil{ properties.append("ask_doctor_or_pharmacist") } if self.do_not_use != nil{ properties.append("do_not_use") } if self.keep_out_of_reach_of_children != nil{ properties.append("keep_out_of_reach_of_children") } if self.other_safety_information != nil{ properties.append("other_safety_information") } if self.questions != nil{ properties.append("questions") } if self.stop_use != nil{ properties.append("stop_use") } if self.when_using != nil{ properties.append("when_using") } if self.patient_medication_information != nil{ properties.append("patient_medication_information") } if self.spl_medguide != nil{ properties.append("spl_medguide") } // Special Populations if self.use_in_specific_populations != nil{ properties.append("use_in_specific_populations") } if self.pregnancy != nil{ properties.append("pregnancy") } if self.teratogenic_effects != nil{ properties.append("teratogenic_effects") } if self.nonteratogenic_effects != nil{ properties.append("nonteratogenic_effects") } if self.labor_and_delivery != nil{ properties.append("labor_and_delivery") } if self.nursing_mothers != nil{ properties.append("nursing_mothers") } if self.pregnancy_or_breast_feeding != nil{ properties.append("pregnancy_or_breast_feeding") } if self.pediatric_use != nil{ properties.append("pediatric_use") } if self.geriatric_use != nil{ properties.append("geriatric_use") } // Nonclinical toxicology if self.nonclinical_toxicology != nil{ properties.append("nonclinical_toxicology") } if self.carcinogenesis_and_mutagenesis_and_impairment_of_fertility != nil{ properties.append("carcinogenesis_and_mutagenesis_and_impairment_of_fertility") } if self.animal_pharmacology_and_or_toxicology != nil{ properties.append("animal_pharmacology_and_or_toxicology") } // References if self.clinical_studies != nil{ properties.append("clinical_studies") } if self.references != nil{ properties.append("references") } // Supply, storage, and handling if self.how_supplied != nil{ properties.append("how_supplied") } if self.storage_and_handling != nil{ properties.append("storage_and_handling") } if self.safe_handling_warning != nil{ properties.append("safe_handling_warning") } // Warnings and precautions if self.boxed_warning != nil{ properties.append("boxed_warning") } if self.warnings_and_precautions != nil{ properties.append("warnings_and_precautions") } if self.user_safety_warnings != nil{ properties.append("user_safety_warnings") } if self.precautions != nil{ properties.append("precautions") } if self.warnings != nil{ properties.append("warnings") } if self.general_precautions != nil{ properties.append("general_precautions") } // Other fields if self.laboratory_tests != nil{ properties.append("laboratory_tests") } if self.recent_major_changes != nil{ properties.append("recent_major_changes") } if self.microbiology != nil{ properties.append("microbiology") } if self.package_label_principal_display_panel != nil{ properties.append("package_label_principal_display_panel") } if self.spl_unclassified_section != nil{ properties.append("spl_unclassified_section") } // Open FDA if self.openfda != nil{ properties.append("openfda") } return properties } // Returns a list of properties in human readable format func getPropertyTitles() -> [String] { var properties = [String]() // ID and version // if self.set_id != nil{ // properties.append("Set ID") // } // if self.document_id != nil{ // properties.append("Document ID") // } // if self.version != nil{ // properties.append("Version") // } // if self.effective_time != nil{ // properties.append("Effective Time") // } // Abuse and overdosage if self.drug_abuse_and_dependence != nil{ properties.append("Drug Abuse and Dependence") } if self.controlled_substance != nil{ properties.append("Controlled Substance") } if self.abuse != nil{ properties.append("Abuse") } if self.dependence != nil{ properties.append("Dependence") } if self.overdosage != nil{ properties.append("Overdosage") } // Adverse effects and interactions if self.adverse_reactions != nil{ properties.append("Adverse Reactions") } if self.drug_interactions != nil{ properties.append("Drug Interactions") } if self.drug_and_or_laboratory_test_interactions != nil{ properties.append("Drug and/or Laboratory Test Interactions") } // Clinical pharmacology if self.clinical_pharmacology != nil{ properties.append("Clinical Pharmacology") } if self.mechanism_of_action != nil{ properties.append("Mechanism of Action") } if self.pharmacodynamics != nil{ properties.append("Pharmacodynamics") } if self.pharmacokinetics != nil{ properties.append("Pharmacokinetics") } // Indications, usage, and dosage if self.indications_and_usage != nil{ properties.append("Indications and Usage") } if self.contraindications != nil{ properties.append("Contraindications") } if self.dosage_and_administration != nil{ properties.append("Dosage and Administration") } if self.dosage_forms_and_strengths != nil{ properties.append("Dosage Forms and Strengths") } if self.purpose != nil{ properties.append("Purpose") } if self.product_description != nil{ properties.append("Product Description") } if self.active_ingredient != nil{ properties.append("Active Ingredient") } if self.inactive_ingredient != nil{ properties.append("Inactive Ingredient") } if self.spl_product_data_elements != nil{ properties.append("SPL Product Data Elements") } // Patient information if self.spl_patient_package_insert != nil{ properties.append("SPL Patient Package Insert") } if self.information_for_patients != nil{ properties.append("Information For Patients") } if self.information_for_owners_or_caregivers != nil{ properties.append("Information For Owners or Caregivers") } if self.instructions_for_use != nil{ properties.append("Instructions for use") } if self.ask_doctor != nil{ properties.append("Ask doctor") } if self.ask_doctor_or_pharmacist != nil{ properties.append("Ask doctor or pharmacist") } if self.do_not_use != nil{ properties.append("Do not use") } if self.keep_out_of_reach_of_children != nil{ properties.append("Keep out of reach of children") } if self.other_safety_information != nil{ properties.append("Other safety information") } if self.questions != nil{ properties.append("Questions") } if self.stop_use != nil{ properties.append("Stop use") } if self.when_using != nil{ properties.append("When using") } if self.patient_medication_information != nil{ properties.append("Patient medication information") } if self.spl_medguide != nil{ properties.append("SPL Medguide") } // Special Populations if self.use_in_specific_populations != nil{ properties.append("Use in specific populations") } if self.pregnancy != nil{ properties.append("Pregnancy") } if self.teratogenic_effects != nil{ properties.append("Teratogenic Effects") } if self.nonteratogenic_effects != nil{ properties.append("Nonteratogenic Effects") } if self.labor_and_delivery != nil{ properties.append("Labor and delivery") } if self.nursing_mothers != nil{ properties.append("Nursing mothers") } if self.pregnancy_or_breast_feeding != nil{ properties.append("Pregnancy or breast feeding") } if self.pediatric_use != nil{ properties.append("Pediatric use") } if self.geriatric_use != nil{ properties.append("Geriatric use") } // Nonclinical toxicology if self.nonclinical_toxicology != nil{ properties.append("Nonclinical toxicology") } if self.carcinogenesis_and_mutagenesis_and_impairment_of_fertility != nil{ properties.append("Carcinogenesis and Mutagenesis and Impairment of Fertility") } if self.animal_pharmacology_and_or_toxicology != nil{ properties.append("Animal pharmacology and or toxicology") } // References if self.clinical_studies != nil{ properties.append("Clinical studies") } if self.references != nil{ properties.append("References") } // Supply, storage, and handling if self.how_supplied != nil{ properties.append("How supplied") } if self.storage_and_handling != nil{ properties.append("Storage and handling") } if self.safe_handling_warning != nil{ properties.append("Safe handling warning") } // Warnings and precautions if self.boxed_warning != nil{ properties.append("Boxed warning") } if self.warnings_and_precautions != nil{ properties.append("Warnings and precautions") } if self.user_safety_warnings != nil{ properties.append("User safety warnings") } if self.precautions != nil{ properties.append("Precautions") } if self.warnings != nil{ properties.append("Warnings") } if self.general_precautions != nil{ properties.append("General precautions") } // Other fields if self.laboratory_tests != nil{ properties.append("Laboratory tests") } if self.recent_major_changes != nil{ properties.append("Recent major changes") } if self.microbiology != nil{ properties.append("Microbiology") } if self.package_label_principal_display_panel != nil{ properties.append("Package label principal display panel") } if self.spl_unclassified_section != nil{ properties.append("spl unclassified section") } // Open FDA if self.openfda != nil{ properties.append("Open FDA") } return properties } }
cc0-1.0
17015927aa3a7c3da47a923fbc9a40b0
41.348981
176
0.618631
3.990985
false
false
false
false
SoneeJohn/WWDC
WWDC/Preferences.swift
1
3817
// // Preferences.swift // WWDC // // Created by Guilherme Rambo on 13/05/17. // Copyright © 2017 Guilherme Rambo. All rights reserved. // import Foundation import ThrowBack import SwiftyJSON extension Notification.Name { static let LocalVideoStoragePathPreferenceDidChange = Notification.Name("LocalVideoStoragePathPreferenceDidChange") static let RefreshPeriodicallyPreferenceDidChange = Notification.Name("RefreshPeriodicallyPreferenceDidChange") static let SkipBackAndForwardBy30SecondsPreferenceDidChange = Notification.Name("SkipBackAndForwardBy30SecondsPreferenceDidChange") } final class Preferences { static let shared: Preferences = Preferences() private let defaults = UserDefaults.standard /// The URL for the folder where downloaded videos will be saved var localVideoStorageURL: URL { get { return URL(fileURLWithPath: TBPreferences.shared.localVideoStoragePath) } set { TBPreferences.shared.localVideoStoragePath = newValue.path defaults.set(newValue.path, forKey: #function) defaults.synchronize() NotificationCenter.default.post(name: .LocalVideoStoragePathPreferenceDidChange, object: nil) } } var activeTab: MainWindowTab { get { let rawValue = defaults.integer(forKey: #function) return MainWindowTab(rawValue: rawValue) ?? .schedule } set { defaults.set(newValue.rawValue, forKey: #function) } } var selectedScheduleItemIdentifier: String? { get { return defaults.object(forKey: #function) as? String } set { defaults.set(newValue, forKey: #function) } } var selectedVideoItemIdentifier: String? { get { return defaults.object(forKey: #function) as? String } set { defaults.set(newValue, forKey: #function) } } var filtersState: JSON? { get { if let string = defaults.object(forKey: #function) as? String { return JSON(parseJSON: string) } else { return nil } } set { if let myString = newValue?.rawString() { defaults.set(myString, forKey: #function) } } } var showedAccountPromptAtStartup: Bool { get { return defaults.bool(forKey: #function) } set { defaults.set(newValue, forKey: #function) } } var userOptedOutOfCrashReporting: Bool { get { return defaults.bool(forKey: #function) } set { defaults.set(newValue, forKey: #function) } } var searchInTranscripts: Bool { get { return defaults.bool(forKey: #function) } set { defaults.set(newValue, forKey: #function) } } var searchInBookmarks: Bool { get { return defaults.bool(forKey: #function) } set { defaults.set(newValue, forKey: #function) } } var refreshPeriodically: Bool { get { return defaults.bool(forKey: #function) } set { defaults.set(newValue, forKey: #function) NotificationCenter.default.post(name: .RefreshPeriodicallyPreferenceDidChange, object: nil) } } var skipBackAndForwardBy30Seconds: Bool { get { return defaults.bool(forKey: #function) } set { defaults.set(newValue, forKey: #function) NotificationCenter.default.post(name: .SkipBackAndForwardBy30SecondsPreferenceDidChange, object: nil) } } }
bsd-2-clause
dcbe3711105b7e63c2462c4ef2ccf1e2
25.685315
135
0.594602
4.886044
false
false
false
false
KaushalElsewhere/AllHandsOn
SwaggerAPiConnect/SwaggerAPiConnect/ViewController.swift
1
1279
// // ViewController.swift // SwaggerAPiConnect // // Created by Kaushal Elsewhere on 15/11/2016. // Copyright © 2016 Kaushal Elsewhere. All rights reserved. // import UIKit import Alamofire class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() login() } let url = "https://api.stage.totsamour.com/auth/login" // let headers: HTTPHeaders = [ // "Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", // "Accept": "application/json" // ] let header: HTTPHeaders = [ "x-socket-api-key" : "7b16afe1aaa3ec502e074ed15c0c020d079a4f9f" ] func login() { Alamofire.request(.POST, url).responseJSON { (response) in print(response) } // Alamofire.request(url).responseJSON { response in // print(response.request) // original URL request // print(response.response) // HTTP URL response // print(response.data) // server data // print(response.result) // result of response serialization // // if let JSON = response.result.value { // print("JSON: \(JSON)") // } // } } }
mit
a4c6cceedf5d49dfcfc6a7e8a08c5ecd
23.576923
74
0.562598
3.908257
false
false
false
false
yonaskolb/SwagGen
Templates/Swift/Sources/Coding.swift
1
10627
{% include "Includes/Header.stencil" %} import Foundation {% if options.modelProtocol %} public protocol {{ options.modelProtocol }}: Codable, Equatable { } {% endif %} {% for type, typealias in options.typeAliases %} public typealias {{ type }} = {{ typealias }} {% endfor %} public protocol ResponseDecoder { func decode<T: Decodable>(_ type: T.Type, from: Data) throws -> T } extension JSONDecoder: ResponseDecoder {} public protocol RequestEncoder { func encode<T: Encodable>(_ value: T) throws -> Data } extension JSONEncoder: RequestEncoder {} extension {{ options.modelProtocol }} { func encode() -> [String: Any] { guard let jsonData = try? JSONEncoder().encode(self), let jsonValue = try? JSONSerialization.jsonObject(with: jsonData), let jsonDictionary = jsonValue as? [String: Any] else { return [:] } return jsonDictionary } } struct StringCodingKey: CodingKey, ExpressibleByStringLiteral { private let string: String private let int: Int? var stringValue: String { return string } init(string: String) { self.string = string int = nil } init?(stringValue: String) { string = stringValue int = nil } var intValue: Int? { return int } init?(intValue: Int) { string = String(describing: intValue) int = intValue } init(stringLiteral value: String) { string = value int = nil } } // any json decoding extension ResponseDecoder { func decodeAny<T>(_ type: T.Type, from data: Data) throws -> T { guard let decoded = try decode(AnyCodable.self, from: data) as? T else { throw DecodingError.typeMismatch(T.self, DecodingError.Context(codingPath: [StringCodingKey(string: "")], debugDescription: "Decoding of \(T.self) failed")) } return decoded } } // any decoding extension KeyedDecodingContainer { func decodeAny<T>(_ type: T.Type, forKey key: K) throws -> T { guard let value = try decode(AnyCodable.self, forKey: key).value as? T else { throw DecodingError.typeMismatch(T.self, DecodingError.Context(codingPath: codingPath, debugDescription: "Decoding of \(T.self) failed")) } return value } func decodeAnyIfPresent<T>(_ type: T.Type, forKey key: K) throws -> T? { return try decodeOptional { guard let value = try decodeIfPresent(AnyCodable.self, forKey: key)?.value else { return nil } if let typedValue = value as? T { return typedValue } else { throw DecodingError.typeMismatch(T.self, DecodingError.Context(codingPath: codingPath, debugDescription: "Decoding of \(T.self) failed")) } } } func toDictionary() throws -> [String: Any] { var dictionary: [String: Any] = [:] for key in allKeys { dictionary[key.stringValue] = try decodeAny(key) } return dictionary } func decode<T>(_ key: KeyedDecodingContainer.Key) throws -> T where T: Decodable { return try decode(T.self, forKey: key) } func decodeIfPresent<T>(_ key: KeyedDecodingContainer.Key) throws -> T? where T: Decodable { return try decodeOptional { try decodeIfPresent(T.self, forKey: key) } } func decodeAny<T>(_ key: K) throws -> T { return try decodeAny(T.self, forKey: key) } func decodeAnyIfPresent<T>(_ key: K) throws -> T? { return try decodeAnyIfPresent(T.self, forKey: key) } public func decodeArray<T: Decodable>(_ key: K) throws -> [T] { var container: UnkeyedDecodingContainer var array: [T] = [] do { container = try nestedUnkeyedContainer(forKey: key) } catch { if {{ options.name }}.safeArrayDecoding { return array } else { throw error } } while !container.isAtEnd { do { let element = try container.decode(T.self) array.append(element) } catch { if {{ options.name }}.safeArrayDecoding { // hack to advance the current index _ = try? container.decode(AnyCodable.self) } else { throw error } } } return array } public func decodeArrayIfPresent<T: Decodable>(_ key: K) throws -> [T]? { return try decodeOptional { if contains(key) { return try decodeArray(key) } else { return nil } } } fileprivate func decodeOptional<T>(_ closure: () throws -> T? ) throws -> T? { if {{ options.name }}.safeOptionalDecoding { do { return try closure() } catch { return nil } } else { return try closure() } } } // any encoding extension KeyedEncodingContainer { mutating func encodeAnyIfPresent<T>(_ value: T?, forKey key: K) throws { guard let value = value else { return } try encodeIfPresent(AnyCodable(value), forKey: key) } mutating func encodeAny<T>(_ value: T, forKey key: K) throws { try encode(AnyCodable(value), forKey: key) } } // Date structs for date and date-time formats extension DateFormatter { convenience init(formatString: String, locale: Locale? = nil, timeZone: TimeZone? = nil, calendar: Calendar? = nil) { self.init() dateFormat = formatString if let locale = locale { self.locale = locale } if let timeZone = timeZone { self.timeZone = timeZone } if let calendar = calendar { self.calendar = calendar } } convenience init(dateStyle: DateFormatter.Style, timeStyle: DateFormatter.Style) { self.init() self.dateStyle = dateStyle self.timeStyle = timeStyle } } let dateDecoder: (Decoder) throws -> Date = { decoder in let container = try decoder.singleValueContainer() let string = try container.decode(String.self) let formatterWithMilliseconds = DateFormatter() formatterWithMilliseconds.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" formatterWithMilliseconds.locale = Locale(identifier: "en_US_POSIX") formatterWithMilliseconds.timeZone = TimeZone(identifier: "UTC") formatterWithMilliseconds.calendar = Calendar(identifier: .gregorian) let formatterWithoutMilliseconds = DateFormatter() formatterWithoutMilliseconds.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ" formatterWithoutMilliseconds.locale = Locale(identifier: "en_US_POSIX") formatterWithoutMilliseconds.timeZone = TimeZone(identifier: "UTC") formatterWithoutMilliseconds.calendar = Calendar(identifier: .gregorian) guard let date = formatterWithMilliseconds.date(from: string) ?? formatterWithoutMilliseconds.date(from: string) else { throw DecodingError.dataCorruptedError(in: container, debugDescription: "Could not decode date") } return date } public struct DateDay: Codable, Comparable { /// The date formatter used for encoding and decoding public static let dateFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd" formatter.calendar = .current return formatter }() public let date: Date public let year: Int public let month: Int public let day: Int public init(date: Date = Date()) { self.date = date let dateComponents = Calendar.current.dateComponents([.day, .month, .year], from: date) guard let year = dateComponents.year, let month = dateComponents.month, let day = dateComponents.day else { fatalError("Date does not contain correct components") } self.year = year self.month = month self.day = day } public init(year: Int, month: Int, day: Int) { let dateComponents = DateComponents(calendar: .current, year: year, month: month, day: day) guard let date = dateComponents.date else { fatalError("Could not create date in current calendar") } self.date = date self.year = year self.month = month self.day = day } public init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() let string = try container.decode(String.self) guard let date = DateDay.dateFormatter.date(from: string) else { throw DecodingError.dataCorruptedError(in: container, debugDescription: "Date not in correct format of \(DateDay.dateFormatter.dateFormat ?? "")") } self.init(date: date) } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() let string = DateDay.dateFormatter.string(from: date) try container.encode(string) } public static func == (lhs: DateDay, rhs: DateDay) -> Bool { return lhs.year == rhs.year && lhs.month == rhs.month && lhs.day == rhs.day } public static func < (lhs: DateDay, rhs: DateDay) -> Bool { return lhs.date < rhs.date } } extension DateFormatter { public func string(from dateDay: DateDay) -> String { return string(from: dateDay.date) } } // for parameter encoding extension DateDay { func encode() -> Any { return DateDay.dateFormatter.string(from: date) } } extension Date { func encode() -> Any { return {{ options.name }}.dateEncodingFormatter.string(from: self) } } extension URL { func encode() -> Any { return absoluteString } } extension RawRepresentable { func encode() -> Any { return rawValue } } extension Array where Element: RawRepresentable { func encode() -> [Any] { return map { $0.rawValue } } } extension Dictionary where Key == String, Value: RawRepresentable { func encode() -> [String: Any] { return mapValues { $0.rawValue } } } extension UUID { func encode() -> Any { return uuidString } } extension String { func encode() -> Any { return self } } extension Data { func encode() -> Any { return self } }
mit
c9e43560c5506e7fdcfbec7ae23e1381
28.035519
168
0.60111
4.65484
false
false
false
false
penniooi/TestKichen
TestKitchen/TestKitchen/classes/cookbook/foodMaterial/view/CBMaterialView.swift
1
2111
// // CBMaterialView.swift // TestKitchen // // Created by aloha on 16/8/23. // Copyright © 2016年 胡颉禹. All rights reserved. // import UIKit class CBMaterialView: UIView { //表格 private var tbView:UITableView? //数据 var model:CBMaterialModel?{ didSet{ tbView?.reloadData() } } //初始化的方法 init(){ super.init(frame:CGRectZero) tbView = UITableView(frame: CGRectZero, style: .Plain) tbView?.delegate = self tbView?.dataSource = self addSubview(tbView!) //添加约束 tbView?.snp_makeConstraints(closure: { [weak self] (make) in make.edges.equalTo(self!) }) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } //MARK:UITableView extension CBMaterialView:UITableViewDelegate,UITableViewDataSource{ func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { var rowNum = 0 if model?.data?.data?.count>0{ rowNum = (model?.data?.data?.count)! } return rowNum } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { var h:CGFloat = 0 //获取模型对象 if model?.data?.data?.count>0{ let typeModel = model?.data?.data![indexPath.row] h = CBMaterialCell.heightWithModel(typeModel!) } return h } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cellId = "materialCellId" var cell = tableView.dequeueReusableCellWithIdentifier(cellId) as? CBMaterialCell if cell == nil{ cell = CBMaterialCell(style: .Default, reuseIdentifier: cellId) } let typmodel = model?.data?.data![indexPath.row] cell?.model = typmodel return cell! } }
mit
110abac303996b8dba108366270aec3e
24.158537
109
0.577595
4.633708
false
false
false
false
fengxinsen/ReadX
ReadX/BookWindowController.swift
1
3983
// // BookWindowController.swift // ReadX // // Created by video on 2017/3/17. // Copyright © 2017年 Von. All rights reserved. // import Cocoa class BookWindowController: BaseWindowController { override var windowNibName: String? { return "BookWindowController" } override func windowDidLoad() { super.windowDidLoad() self.window?.styleMask = [.unifiedTitleAndToolbar, .closable, .miniaturizable, .titled] hiddenZoomButton() hiddenTitleVisibility() titleBackgroundColor(color: NSColor.brown) center() setUpToolbar() } } extension BookWindowController: NSToolbarDelegate { func setUpToolbar(){ let toolbar = NSToolbar(identifier: "AppToolbar") toolbar.allowsUserCustomization = false toolbar.autosavesConfiguration = false toolbar.displayMode = .iconOnly toolbar.delegate = self self.window?.toolbar = toolbar } //实际显示的item 标识 func toolbarAllowedItemIdentifiers(_ toolbar: NSToolbar) -> [String] { return ["refresh_chapters", NSToolbarFlexibleSpaceItemIdentifier, "add"] } //所有的item 标识,在编辑模式下会显示出所有的item func toolbarDefaultItemIdentifiers(_ toolbar: NSToolbar) -> [String] { return ["refresh_chapters", NSToolbarFlexibleSpaceItemIdentifier, "add"] } //根据item 标识 返回每个具体的NSToolbarItem对象实例 func toolbar(_ toolbar: NSToolbar, itemForItemIdentifier itemIdentifier: String, willBeInsertedIntoToolbar flag: Bool) -> NSToolbarItem? { let toolbarItem = NSToolbarItem(itemIdentifier: itemIdentifier) if itemIdentifier == "refresh_chapters" { toolbarItem.tag = 1 let size = NSSize(width: 66, height: 22) let refresh = NSButton.init(frame: NSRect.init(x: 0, y: 0, width: size.width, height: size.height)) refresh.bezelStyle = .roundRect refresh.title = "刷新目录" toolbarItem.view = refresh toolbarItem.minSize = size toolbarItem.maxSize = size refresh.target = self refresh.action = #selector(refreshBookRoomAction(_:)) } if itemIdentifier == NSToolbarFlexibleSpaceItemIdentifier { toolbarItem.tag = 2 } if itemIdentifier == "add" { toolbarItem.tag = 3 let size = NSSize(width: 33, height: 22) let add = NSButton.init(frame: NSRect.init(x: 0, y: 0, width: size.width, height: size.height)) add.bezelStyle = .roundRect add.title = "+" toolbarItem.view = add toolbarItem.minSize = size toolbarItem.maxSize = size add.target = self add.action = #selector(addBookAction(_:)) } return toolbarItem } func refreshBookRoomAction(_ sender: NSButton) { NotificationCenter.default.post(name: Book_RoomChaptersRefresh_Notification, object: nil) } func addBookAction(_ sender: NSButton) { let bookAdd = BookAddViewController() let pop = NSPopover.init() pop.behavior = .semitransient pop.delegate = self bookAdd.popover = pop pop.contentViewController = bookAdd pop.show(relativeTo: sender.bounds, of: sender, preferredEdge: .maxY) } func toolbarItemClicked(_ sender:NSToolbarItem) { let tag = sender.tag switch tag { case 0: print("0") case 1: print("1") default: print("1000") } } } extension BookWindowController: NSPopoverDelegate { func popoverDidClose(_ notification: Notification) { let pop = notification.object as! NSPopover let add = pop.contentViewController as! BookAddViewController add.popover = nil } }
mit
0bb5e02943a1cf960ef6792bc7fbb422
30.901639
142
0.616906
4.672269
false
false
false
false
blstream/mEatUp
mEatUp/mEatUp/Subscriptions.swift
1
4012
// // Subscriptions.swift // mEatUp // // Created by Paweł Knuth on 26.04.2016. // Copyright © 2016 BLStream. All rights reserved. // import Foundation import CloudKit class Subscriptions { var cloudKitHelper = CloudKitHelper() func deleteSubscriptions() { cloudKitHelper.publicDB.fetchAllSubscriptionsWithCompletionHandler({subscriptions, error in if let subscriptions = subscriptions where error == nil { for subscription in subscriptions { self.cloudKitHelper.publicDB.deleteSubscriptionWithID(subscription.subscriptionID, completionHandler: { (str, error) -> Void in if error != nil { print(error!.localizedDescription) } }) } } }) } func createSubscription(predicate: NSPredicate, recordType: String, option: CKSubscriptionOptions, desiredKeys: [String]?) { let subscription = CKSubscription(recordType: recordType, predicate: predicate, options: option) let notificationInfo = CKNotificationInfo() notificationInfo.shouldSendContentAvailable = true notificationInfo.desiredKeys = desiredKeys notificationInfo.shouldBadge = false subscription.notificationInfo = notificationInfo cloudKitHelper.publicDB.saveSubscription(subscription, completionHandler: { returnRecord, error in if let error = error { print("Subscription faild \(error)") } else { dispatch_async(dispatch_get_main_queue(), { print("Subscription succeed") }) } }) } func createSubscriptions() { createUpdateRoomSubscription() createDeleteRoomSubscription() createCreateRoomSubscription() createCreateUserInRoomSubscription() createDeleteUserInRoomSubscription() createUpdateUserInRoomSubscription() createCreateChatMessageSubscription() } func createUpdateRoomSubscription() { let predicate = NSPredicate(format: "TRUEPREDICATE") createSubscription(predicate, recordType: Room.entityName, option: .FiresOnRecordUpdate, desiredKeys: nil) } func createDeleteRoomSubscription() { let predicate = NSPredicate(format: "TRUEPREDICATE") createSubscription(predicate, recordType: Room.entityName, option: .FiresOnRecordDeletion, desiredKeys: nil) } func createCreateRoomSubscription() { let predicate = NSPredicate(format: "accessType == 2") createSubscription(predicate, recordType: Room.entityName, option: .FiresOnRecordCreation, desiredKeys: nil) } func createCreateUserInRoomSubscription() { let predicate = NSPredicate(format: "TRUEPREDICATE") createSubscription(predicate, recordType: UserInRoom.entityName, option: .FiresOnRecordCreation, desiredKeys: ["userRecordID", "roomRecordID", "confirmationStatus"]) } func createDeleteUserInRoomSubscription() { let predicate = NSPredicate(format: "TRUEPREDICATE") createSubscription(predicate, recordType: UserInRoom.entityName, option: .FiresOnRecordDeletion, desiredKeys: ["userRecordID", "roomRecordID", "confirmationStatus"]) } func createUpdateUserInRoomSubscription() { let predicate = NSPredicate(format: "confirmationStatus == 2") createSubscription(predicate, recordType: UserInRoom.entityName, option: .FiresOnRecordUpdate, desiredKeys: ["userRecordID", "roomRecordID", "confirmationStatus"]) } func createCreateChatMessageSubscription() { let predicate = NSPredicate(format: "TRUEPREDICATE") createSubscription(predicate, recordType: ChatMessage.entityName, option: .FiresOnRecordCreation, desiredKeys: ["message"]) } }
apache-2.0
b88ec6724b9a354c5014e61550539e67
38.313725
173
0.659102
5.647887
false
false
false
false
djq993452611/YiYuDaoJia_Swift
YiYuDaoJia/YiYuDaoJia/Classes/Home/Controller/MessageViewController.swift
1
2584
// // MessageViewController.swift // YiYuDaoJia // // Created by 蓝海天网Djq on 2017/4/28. // Copyright © 2017年 蓝海天网Djq. All rights reserved. // import UIKit class MessageViewController: BaseTableViewController { } extension MessageViewController{ override func setupUI() { // tableStyle = UITableViewStyle.plain navigationItem.title = "plan" super.setupUI() navigationItem.rightBarButtonItem = UIBarButtonItem(normalImage: #imageLiteral(resourceName: "daifukuan"), parentVc: self, action: #selector(self.messagePressed)) } func messagePressed(){ navigationController?.pushViewController(WaitPayViewController(), animated: true) } } extension MessageViewController{ override func loadData() { for item in 0..<15 { let content = "message 初始数据 : \(item)" dataList.append(content) } DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .seconds(3)) { self.tableView.reloadData() self.loadDataFinished() } } override func loadNewData() { var dataArray = Array<Any>() for item in 0..<15 { let content = "message 初始数据 : \(item)" dataArray.append(content) } DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .seconds(3)) { self.dataList = dataArray self.tableView.reloadData() self.tableView.headerSetState(CoreHeaderViewRefreshStateSuccessedResultDataShowing) self.tableView.footerSetState(CoreFooterViewRefreshStateNormalForContinueDragUp) } } override func loadMoreData() { let count = dataList.count var dataArray = Array<Any>() if count < 32 { for item in count..<count+15 { let content = "message 初始数据 : \(item)" dataArray.append(content) } DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .seconds(3)) { self.dataList += dataArray self.tableView.reloadData() self.tableView.footerSetState(CoreFooterViewRefreshStateSuccessedResultDataShowing) } } else{ self.tableView.footerSetState(CoreFooterViewRefreshStateSuccessedResultNoMoreData) } } }
mit
2850834762d64ade88900ea5a5b605f6
25.46875
170
0.578906
5.154158
false
false
false
false
luanlzsn/pos
pos/Classes/pos/Payment/Controller/ChangeTableController.swift
1
6044
// // ChangeTableController.swift // pos // // Created by luan on 2017/5/30. // Copyright © 2017年 luan. All rights reserved. // import UIKit class ChangeTableController: AntController,UICollectionViewDelegate,UICollectionViewDataSource,UIGestureRecognizerDelegate { @IBOutlet weak var changeView: UIView! @IBOutlet weak var changeHeight: NSLayoutConstraint! @IBOutlet weak var changeCollection: UICollectionView! var changeTable: ConfirmBlock? var changeArray = [[String : [NSNumber]]]()//可以被换桌的信息 deinit { changeTable = nil } override func viewDidLoad() { super.viewDidLoad() checkChangeTableData() } @IBAction func cancelClick() { if changeTable != nil { changeTable = nil } dismiss(animated: true, completion: nil) } func checkChangeTableData() { var height = 0.0 let home = ((UIApplication.shared.delegate as! AppDelegate).window!.rootViewController as! UINavigationController).viewControllers.first as! HomeController var dineSet = Set<NSNumber>() for i in 1...home.dineNum { dineSet.insert(NSNumber(integerLiteral: i)) } let dineArray = [NSNumber](dineSet.subtracting(Set((home.dineDic as NSDictionary).allKeys as! [NSNumber]))).sorted { (num1, num2) -> Bool in num1.intValue < num2.intValue } if dineArray.count > 0 { changeArray.append([NSLocalizedString("堂食", comment: "") : dineArray]) height += 45.0 * (ceil(Double(dineArray.count) / 3.0) + 1) } var takeoutSet = Set<NSNumber>() for i in 1...home.takeoutNum { takeoutSet.insert(NSNumber(integerLiteral: i)) } let takeoutArray = [NSNumber](takeoutSet.subtracting(Set((home.takeoutDic as NSDictionary).allKeys as! [NSNumber]))).sorted { (num1, num2) -> Bool in num1.intValue < num2.intValue } if takeoutArray.count > 0 { changeArray.append([NSLocalizedString("外卖", comment: "") : takeoutArray]) height += 45.0 * (ceil(Double(takeoutArray.count) / 3.0) + 1) } var deliverySet = Set<NSNumber>() for i in 1...home.deliveryNum { deliverySet.insert(NSNumber(integerLiteral: i)) } let deliveryArray = [NSNumber](deliverySet.subtracting(Set((home.deliveryDic as NSDictionary).allKeys as! [NSNumber]))).sorted { (num1, num2) -> Bool in num1.intValue < num2.intValue } if deliveryArray.count > 0 { changeArray.append([NSLocalizedString("送餐", comment: "") : deliveryArray]) height += 45.0 * (ceil(Double(deliveryArray.count) / 3.0) + 1) } if height > Double(kScreenHeight - 75) { height = Double(kScreenHeight - 75) } changeHeight.constant = CGFloat(35.0 + height) changeCollection.reloadData() } // MARK: UIGestureRecognizerDelegate func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { if touch.view == changeView || touch.view?.className() == "UIButton" { return false } return true } // MARK: UICollectionViewDelegate,UICollectionViewDataSource func numberOfSections(in collectionView: UICollectionView) -> Int { return changeArray.count } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return ((changeArray[section].values.first != nil) ? changeArray[section].values.first!.count : 0) } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { if kind == UICollectionElementKindSectionHeader { let header: ChangeTableHeaderView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "ChangeTableHeaderView", for: indexPath) as! ChangeTableHeaderView header.headerTitle.text = changeArray[indexPath.section].keys.first return header } else { return UICollectionReusableView() } } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell: ChangeTableCell = collectionView.dequeueReusableCell(withReuseIdentifier: "ChangeTableCell", for: indexPath) as! ChangeTableCell cell.changeNumBtn.setTitle("\(changeArray[indexPath.section].values.first![indexPath.row])", for: .normal) weak var weakSelf = self cell.changeTable = {(_) -> () in let tableNo = (weakSelf?.changeArray[indexPath.section].values.first![indexPath.row])! let tableType: String! if weakSelf?.changeArray[indexPath.section].keys.first == NSLocalizedString("堂食", comment: "") { tableType = "D" } else if weakSelf?.changeArray[indexPath.section].keys.first == NSLocalizedString("外卖", comment: "") { tableType = "T" } else { tableType = "W" } if weakSelf!.changeTable != nil { weakSelf!.changeTable!(["TableNo":tableNo, "TableType":tableType]) } weakSelf?.cancelClick() } return cell } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
0cc65b945908236ba46934a475a3e36d
39.302013
197
0.633472
4.82717
false
false
false
false
sydvicious/firefox-ios
Storage/Bookmarks.swift
2
11471
/* 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 UIKit import Shared public struct ShareItem { public let url: String public let title: String? public let favicon: Favicon? public init(url: String, title: String?, favicon: Favicon?) { self.url = url self.title = title self.favicon = favicon } } public protocol ShareToDestination { func shareItem(item: ShareItem) } public protocol SearchableBookmarks { func bookmarksByURL(url: NSURL) -> Deferred<Result<Cursor<BookmarkItem>>> } public struct BookmarkRoots { // These match Places on desktop. public static let RootGUID = "root________" public static let MobileFolderGUID = "mobile______" public static let MenuFolderGUID = "menu________" public static let ToolbarFolderGUID = "toolbar_____" public static let UnfiledFolderGUID = "unfiled_____" /* public static let TagsFolderGUID = "tags________" public static let PinnedFolderGUID = "pinned______" public static let FakeDesktopFolderGUID = "desktop_____" */ static let RootID = 0 static let MobileID = 1 static let MenuID = 2 static let ToolbarID = 3 static let UnfiledID = 4 } /** * This matches Places's nsINavBookmarksService, just for sanity. * These are only used at the DB layer. */ public enum BookmarkNodeType: Int { case Bookmark = 1 case Folder = 2 case Separator = 3 case DynamicContainer = 4 } /** * The immutable base interface for bookmarks and folders. */ public class BookmarkNode { public var id: Int? = nil public var guid: String public var title: String public var favicon: Favicon? = nil init(guid: String, title: String) { self.guid = guid self.title = title } } /** * An immutable item representing a bookmark. * * To modify this, issue changes against the backing store and get an updated model. */ public class BookmarkItem: BookmarkNode { public let url: String! public init(guid: String, title: String, url: String) { self.url = url super.init(guid: guid, title: title) } } /** * A folder is an immutable abstraction over a named * thing that can return its child nodes by index. */ public class BookmarkFolder: BookmarkNode { public var count: Int { return 0 } public subscript(index: Int) -> BookmarkNode? { return nil } public func itemIsEditableAtIndex(index: Int) -> Bool { return false } } /** * A model is a snapshot of the bookmarks store, suitable for backing a table view. * * Navigation through the folder hierarchy produces a sequence of models. * * Changes to the backing store implicitly invalidates a subset of models. * * 'Refresh' means requesting a new model from the store. */ public class BookmarksModel { let modelFactory: BookmarksModelFactory public let current: BookmarkFolder public init(modelFactory: BookmarksModelFactory, root: BookmarkFolder) { self.modelFactory = modelFactory self.current = root } /** * Produce a new model rooted at the appropriate folder. Fails if the folder doesn't exist. */ public func selectFolder(folder: BookmarkFolder, success: BookmarksModel -> (), failure: Any -> ()) { modelFactory.modelForFolder(folder, success: success, failure: failure) } /** * Produce a new model rooted at the appropriate folder. Fails if the folder doesn't exist. */ public func selectFolder(guid: String, success: BookmarksModel -> (), failure: Any -> ()) { modelFactory.modelForFolder(guid, success: success, failure: failure) } /** * Produce a new model rooted at the base of the hierarchy. Should never fail. */ public func selectRoot(success: BookmarksModel -> (), failure: Any -> ()) { modelFactory.modelForRoot(success, failure: failure) } /** * Produce a new model rooted at the same place as this model. Can fail if * the folder has been deleted from the backing store. */ public func reloadData(success: BookmarksModel -> (), failure: Any -> ()) { modelFactory.modelForFolder(current, success: success, failure: failure) } } public protocol BookmarksModelFactory { func modelForFolder(folder: BookmarkFolder, success: BookmarksModel -> (), failure: Any -> ()) func modelForFolder(guid: String, success: BookmarksModel -> (), failure: Any -> ()) func modelForRoot(success: BookmarksModel -> (), failure: Any -> ()) // Whenever async construction is necessary, we fall into a pattern of needing // a placeholder that behaves correctly for the period between kickoff and set. var nullModel: BookmarksModel { get } func isBookmarked(url: String, success: Bool -> (), failure: Any -> ()) func remove(bookmark: BookmarkNode) -> Success func removeByURL(url: String) -> Success func clearBookmarks() -> Success } /* * A folder that contains an array of children. */ public class MemoryBookmarkFolder: BookmarkFolder, SequenceType { let children: [BookmarkNode] public init(guid: String, title: String, children: [BookmarkNode]) { self.children = children super.init(guid: guid, title: title) } public struct BookmarkNodeGenerator: GeneratorType { typealias Element = BookmarkNode let children: [BookmarkNode] var index: Int = 0 init(children: [BookmarkNode]) { self.children = children } public mutating func next() -> BookmarkNode? { return index < children.count ? children[index++] : nil } } override public var favicon: Favicon? { get { if let path = NSBundle.mainBundle().pathForResource("bookmark_folder_closed", ofType: "png") { if let url = NSURL(fileURLWithPath: path) { return Favicon(url: url.absoluteString!, date: NSDate(), type: IconType.Local) } } return nil } set { } } override public var count: Int { return children.count } override public subscript(index: Int) -> BookmarkNode { get { return children[index] } } override public func itemIsEditableAtIndex(index: Int) -> Bool { return true } public func generate() -> BookmarkNodeGenerator { return BookmarkNodeGenerator(children: self.children) } /** * Return a new immutable folder that's just like this one, * but also contains the new items. */ func append(items: [BookmarkNode]) -> MemoryBookmarkFolder { if (items.isEmpty) { return self } return MemoryBookmarkFolder(guid: self.guid, title: self.title, children: self.children + items) } } public class MemoryBookmarksSink: ShareToDestination { var queue: [BookmarkNode] = [] public init() { } public func shareItem(item: ShareItem) { let title = item.title == nil ? "Untitled" : item.title! func exists(e: BookmarkNode) -> Bool { if let bookmark = e as? BookmarkItem { return bookmark.url == item.url; } return false; } // Don't create duplicates. if (!contains(queue, exists)) { queue.append(BookmarkItem(guid: Bytes.generateGUID(), title: title, url: item.url)) } } } private extension SuggestedSite { func asBookmark() -> BookmarkNode { let b = BookmarkItem(guid: self.guid ?? Bytes.generateGUID(), title: self.title, url: self.url) b.favicon = self.icon return b } } public class BookmarkFolderWithDefaults: BookmarkFolder { private let folder: BookmarkFolder private let sites: SuggestedSitesData<SuggestedSite> init(folder: BookmarkFolder, sites: SuggestedSitesData<SuggestedSite>) { self.folder = folder self.sites = sites super.init(guid: folder.guid, title: folder.title) } override public var count: Int { return self.folder.count + self.sites.count } override public subscript(index: Int) -> BookmarkNode? { if index < self.folder.count { return self.folder[index] } if let site = self.sites[index - self.folder.count] { return site.asBookmark() } return nil } override public func itemIsEditableAtIndex(index: Int) -> Bool { return index < self.folder.count } } /** * A trivial offline model factory that represents a simple hierarchy. */ public class MockMemoryBookmarksStore: BookmarksModelFactory, ShareToDestination { let mobile: MemoryBookmarkFolder let root: MemoryBookmarkFolder var unsorted: MemoryBookmarkFolder let sink: MemoryBookmarksSink public init() { var res = [BookmarkItem]() mobile = MemoryBookmarkFolder(guid: BookmarkRoots.MobileFolderGUID, title: "Mobile Bookmarks", children: res) unsorted = MemoryBookmarkFolder(guid: BookmarkRoots.UnfiledFolderGUID, title: "Unsorted Bookmarks", children: []) sink = MemoryBookmarksSink() root = MemoryBookmarkFolder(guid: BookmarkRoots.RootGUID, title: "Root", children: [mobile, unsorted]) } public func modelForFolder(folder: BookmarkFolder, success: (BookmarksModel) -> (), failure: (Any) -> ()) { self.modelForFolder(folder.guid, success: success, failure: failure) } public func modelForFolder(guid: String, success: (BookmarksModel) -> (), failure: (Any) -> ()) { var m: BookmarkFolder switch (guid) { case BookmarkRoots.MobileFolderGUID: // Transparently merges in any queued items. m = self.mobile.append(self.sink.queue) break; case BookmarkRoots.RootGUID: m = self.root break; case BookmarkRoots.UnfiledFolderGUID: m = self.unsorted break; default: failure("No such folder.") return } success(BookmarksModel(modelFactory: self, root: m)) } public func modelForRoot(success: (BookmarksModel) -> (), failure: (Any) -> ()) { success(BookmarksModel(modelFactory: self, root: self.root)) } /** * This class could return the full data immediately. We don't, because real DB-backed code won't. */ public var nullModel: BookmarksModel { let f = MemoryBookmarkFolder(guid: BookmarkRoots.RootGUID, title: "Root", children: []) return BookmarksModel(modelFactory: self, root: f) } public func shareItem(item: ShareItem) { self.sink.shareItem(item) } public func isBookmarked(url: String, success: (Bool) -> (), failure: (Any) -> ()) { failure("Not implemented") } public func remove(bookmark: BookmarkNode) -> Success { return deferResult(DatabaseError(description: "Not implemented")) } public func removeByURL(url: String) -> Success { return deferResult(DatabaseError(description: "Not implemented")) } public func clearBookmarks() -> Success { return succeed() } }
mpl-2.0
0a4c7dcff1d577a517e0479291791d46
29.83871
121
0.640136
4.561034
false
false
false
false
devpunk/punknote
punknote/View/Basic/VGradient.swift
2
2262
import UIKit class VGradient:UIView { private static let kLocationStart:NSNumber = 0 private static let kLocationEnd:NSNumber = 1 class func diagonal(colorLeftBottom:UIColor, colorTopRight:UIColor) -> VGradient { let colors:[CGColor] = [ colorLeftBottom.cgColor, colorTopRight.cgColor] let locations:[NSNumber] = [ kLocationStart, kLocationEnd] let startPoint:CGPoint = CGPoint(x:0, y:1) let endPoint:CGPoint = CGPoint(x:1, y:0) let gradient:VGradient = VGradient( colors:colors, locations:locations, startPoint:startPoint, endPoint:endPoint) return gradient } class func horizontal(colorLeft:UIColor, colorRight:UIColor) -> VGradient { let colors:[CGColor] = [ colorLeft.cgColor, colorRight.cgColor] let locations:[NSNumber] = [ kLocationStart, kLocationEnd] let startPoint:CGPoint = CGPoint(x:0, y:0.5) let endPoint:CGPoint = CGPoint(x:1, y:0.5) let gradient:VGradient = VGradient( colors:colors, locations:locations, startPoint:startPoint, endPoint:endPoint) return gradient } private init( colors:[CGColor], locations:[NSNumber], startPoint:CGPoint, endPoint:CGPoint) { super.init(frame:CGRect.zero) clipsToBounds = true backgroundColor = UIColor.clear translatesAutoresizingMaskIntoConstraints = false isUserInteractionEnabled = false guard let gradientLayer:CAGradientLayer = self.layer as? CAGradientLayer else { return } gradientLayer.startPoint = startPoint gradientLayer.endPoint = endPoint gradientLayer.locations = locations gradientLayer.colors = colors } required init?(coder:NSCoder) { return nil } override open class var layerClass:AnyClass { get { return CAGradientLayer.self } } }
mit
491d0ecb7d289ae5872dc96145492cd9
25
84
0.565871
5.24826
false
false
false
false
VojtaStavik/ProtocolUI
ProtocolUITests/ShadowOffsetProtocolTest.swift
1
4842
// // ShadowOffsetProtocolTest.swift // ProtocolUI // // Created by STRV on 19/08/15. // Copyright © 2015 Vojta Stavik. All rights reserved. // import XCTest @testable import ProtocolUI extension ShadowOffset { var pShadowOffset : CGSize { return ShadowOffsetProtocolTest.testValue } } class ShadowOffsetProtocolTest: XCTestCase { typealias CurrentTestProtocol = ShadowOffset typealias CurrentTestValueType = CGSize static let testValue : CurrentTestValueType = CGSize(width: 50.0, height: 15.0) func performTestWithClass(classType : UIView.Type, shouldTestIBDesignable: Bool = false) { let testView = classType.init() if shouldTestIBDesignable { testView.prepareForInterfaceBuilder() } else { testView.applyProtocolUIAppearance() } XCTAssert(testView is CurrentTestProtocol) XCTAssert(testView.layer.shadowOffset == self.dynamicType.testValue) } // DO NOT EDIT HERE // The following code is copied to every test case file from the SharedTestCode.swift file. // If needed, do your changes there. //~~~**~~~ func testUIButton() { class TestView : UIButton, CurrentTestProtocol { } performTestWithClass(TestView) performTestWithClass(TestView.self, shouldTestIBDesignable: true) } func testUIControl() { class TestView : UIControl, CurrentTestProtocol { } performTestWithClass(TestView) performTestWithClass(TestView.self, shouldTestIBDesignable: true) } func testUILabel() { class TestView : UILabel, CurrentTestProtocol { } performTestWithClass(TestView) performTestWithClass(TestView.self, shouldTestIBDesignable: true) } func testUINavigationBar() { class TestView : UINavigationBar, CurrentTestProtocol { } performTestWithClass(TestView) performTestWithClass(TestView.self, shouldTestIBDesignable: true) } func testUIPageControl() { class TestView : UIPageControl, CurrentTestProtocol { } performTestWithClass(TestView) performTestWithClass(TestView.self, shouldTestIBDesignable: true) } func testUIProgressView() { class TestView : UIProgressView, CurrentTestProtocol { } performTestWithClass(TestView) performTestWithClass(TestView.self, shouldTestIBDesignable: true) } func testUISearchBar() { class TestView : UISearchBar, CurrentTestProtocol { } performTestWithClass(TestView) performTestWithClass(TestView.self, shouldTestIBDesignable: true) } func testUISegmentedControl() { class TestView : UISegmentedControl, CurrentTestProtocol { } performTestWithClass(TestView) performTestWithClass(TestView.self, shouldTestIBDesignable: true) } func testUISlider() { class TestView : UISlider, CurrentTestProtocol { } performTestWithClass(TestView) performTestWithClass(TestView.self, shouldTestIBDesignable: true) } func testUISwitch() { class TestView : UISwitch, CurrentTestProtocol { } performTestWithClass(TestView) performTestWithClass(TestView.self, shouldTestIBDesignable: true) } func testUITabBar() { class TestView : UITabBar, CurrentTestProtocol { } performTestWithClass(TestView) performTestWithClass(TestView.self, shouldTestIBDesignable: true) } func testUITextField() { class TestView : UITextField, CurrentTestProtocol { } performTestWithClass(TestView) performTestWithClass(TestView.self, shouldTestIBDesignable: true) } func testUITextView() { class TestView : UITextView, CurrentTestProtocol { } performTestWithClass(TestView) performTestWithClass(TestView.self, shouldTestIBDesignable: true) } func testUIToolbar() { class TestView : UIToolbar, CurrentTestProtocol { } performTestWithClass(TestView) performTestWithClass(TestView.self, shouldTestIBDesignable: true) } func testUIView() { class TestView : UIView, CurrentTestProtocol { } performTestWithClass(TestView) performTestWithClass(TestView.self, shouldTestIBDesignable: true) } //~~~**~~~ }
mit
ab09e61cb6f4d88f0c08208273a61d45
31.496644
402
0.618674
5.932598
false
true
false
false
radazzouz/firefox-ios
Client/Frontend/Settings/SettingsTableViewController.swift
1
28575
/* 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 Account import Shared import UIKit import XCGLogger import SwiftyJSON // The following are only here because we use master for L10N and otherwise these strings would disappear from the v1.0 release private let Bug1204635_S1 = NSLocalizedString("Clear Everything", tableName: "ClearPrivateData", comment: "Title of the Clear private data dialog.") private let Bug1204635_S2 = NSLocalizedString("Are you sure you want to clear all of your data? This will also close all open tabs.", tableName: "ClearPrivateData", comment: "Message shown in the dialog prompting users if they want to clear everything") private let Bug1204635_S3 = NSLocalizedString("Clear", tableName: "ClearPrivateData", comment: "Used as a button label in the dialog to Clear private data dialog") private let Bug1204635_S4 = NSLocalizedString("Cancel", tableName: "ClearPrivateData", comment: "Used as a button label in the dialog to cancel clear private data dialog") // A base setting class that shows a title. You probably want to subclass this, not use it directly. class Setting: NSObject { fileprivate var _title: NSAttributedString? fileprivate var _footerTitle: NSAttributedString? fileprivate var _cellHeight: CGFloat? weak var delegate: SettingsDelegate? // The url the SettingsContentViewController will show, e.g. Licenses and Privacy Policy. var url: URL? { return nil } // The title shown on the pref. var title: NSAttributedString? { return _title } var footerTitle: NSAttributedString? { return _footerTitle } var cellHeight: CGFloat? { return _cellHeight} fileprivate(set) var accessibilityIdentifier: String? // An optional second line of text shown on the pref. var status: NSAttributedString? { return nil } // Whether or not to show this pref. var hidden: Bool { return false } var style: UITableViewCellStyle { return .subtitle } var accessoryType: UITableViewCellAccessoryType { return .none } var textAlignment: NSTextAlignment { return .natural } fileprivate(set) var enabled: Bool = true // Called when the cell is setup. Call if you need the default behaviour. func onConfigureCell(_ cell: UITableViewCell) { cell.detailTextLabel?.attributedText = status cell.detailTextLabel?.numberOfLines = 0 cell.textLabel?.attributedText = title cell.textLabel?.textAlignment = textAlignment cell.textLabel?.numberOfLines = 0 cell.accessoryType = accessoryType cell.accessoryView = nil cell.selectionStyle = enabled ? .default : .none cell.accessibilityIdentifier = accessibilityIdentifier if let title = title?.string { if let detailText = cell.detailTextLabel?.text { cell.accessibilityLabel = "\(title), \(detailText)" } else if let status = status?.string { cell.accessibilityLabel = "\(title), \(status)" } else { cell.accessibilityLabel = title } } cell.accessibilityTraits = UIAccessibilityTraitButton cell.indentationWidth = 0 cell.layoutMargins = UIEdgeInsets.zero // So that the separator line goes all the way to the left edge. cell.separatorInset = UIEdgeInsets.zero } // Called when the pref is tapped. func onClick(_ navigationController: UINavigationController?) { return } // Helper method to set up and push a SettingsContentViewController func setUpAndPushSettingsContentViewController(_ navigationController: UINavigationController?) { if let url = self.url { let viewController = SettingsContentViewController() viewController.settingsTitle = self.title viewController.url = url navigationController?.pushViewController(viewController, animated: true) } } init(title: NSAttributedString? = nil, footerTitle: NSAttributedString? = nil, cellHeight: CGFloat? = nil, delegate: SettingsDelegate? = nil, enabled: Bool? = nil) { self._title = title self._footerTitle = footerTitle self._cellHeight = cellHeight self.delegate = delegate self.enabled = enabled ?? true } } // A setting in the sections panel. Contains a sublist of Settings class SettingSection: Setting { fileprivate let children: [Setting] init(title: NSAttributedString? = nil, footerTitle: NSAttributedString? = nil, cellHeight: CGFloat? = nil, children: [Setting]) { self.children = children super.init(title: title, footerTitle: footerTitle, cellHeight: cellHeight) } var count: Int { var count = 0 for setting in children { if !setting.hidden { count += 1 } } return count } subscript(val: Int) -> Setting? { var i = 0 for setting in children { if !setting.hidden { if i == val { return setting } i += 1 } } return nil } } private class PaddedSwitch: UIView { fileprivate static let Padding: CGFloat = 8 init(switchView: UISwitch) { super.init(frame: CGRect.zero) addSubview(switchView) frame.size = CGSize(width: switchView.frame.width + PaddedSwitch.Padding, height: switchView.frame.height) switchView.frame.origin = CGPoint(x: PaddedSwitch.Padding, y: 0) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // A helper class for settings with a UISwitch. // Takes and optional settingsDidChange callback and status text. class BoolSetting: Setting { let prefKey: String fileprivate let prefs: Prefs fileprivate let defaultValue: Bool fileprivate let settingDidChange: ((Bool) -> Void)? fileprivate let statusText: NSAttributedString? init(prefs: Prefs, prefKey: String, defaultValue: Bool, attributedTitleText: NSAttributedString, attributedStatusText: NSAttributedString? = nil, settingDidChange: ((Bool) -> Void)? = nil) { self.prefs = prefs self.prefKey = prefKey self.defaultValue = defaultValue self.settingDidChange = settingDidChange self.statusText = attributedStatusText super.init(title: attributedTitleText) } convenience init(prefs: Prefs, prefKey: String, defaultValue: Bool, titleText: String, statusText: String? = nil, settingDidChange: ((Bool) -> Void)? = nil) { var statusTextAttributedString: NSAttributedString? if let statusTextString = statusText { statusTextAttributedString = NSAttributedString(string: statusTextString, attributes: [NSForegroundColorAttributeName: UIConstants.TableViewHeaderTextColor]) } self.init(prefs: prefs, prefKey: prefKey, defaultValue: defaultValue, attributedTitleText: NSAttributedString(string: titleText, attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]), attributedStatusText: statusTextAttributedString, settingDidChange: settingDidChange) } override var status: NSAttributedString? { return statusText } override func onConfigureCell(_ cell: UITableViewCell) { super.onConfigureCell(cell) let control = UISwitch() control.onTintColor = UIConstants.ControlTintColor control.addTarget(self, action: #selector(BoolSetting.switchValueChanged(_:)), for: UIControlEvents.valueChanged) control.isOn = prefs.boolForKey(prefKey) ?? defaultValue if let title = title { if let status = status { control.accessibilityLabel = "\(title.string), \(status.string)" } else { control.accessibilityLabel = title.string } cell.accessibilityLabel = nil } cell.accessoryView = PaddedSwitch(switchView: control) cell.selectionStyle = .none } @objc func switchValueChanged(_ control: UISwitch) { prefs.setBool(control.isOn, forKey: prefKey) settingDidChange?(control.isOn) } } /// A helper class for a setting backed by a UITextField. /// This takes an optional settingIsValid and settingDidChange callback /// If settingIsValid returns false, the Setting will not change and the text remains red. class StringSetting: Setting, UITextFieldDelegate { let prefKey: String fileprivate let Padding: CGFloat = 8 fileprivate let prefs: Prefs fileprivate let defaultValue: String? fileprivate let placeholder: String fileprivate let settingDidChange: ((String?) -> Void)? fileprivate let settingIsValid: ((String?) -> Bool)? let textField = UITextField() init(prefs: Prefs, prefKey: String, defaultValue: String? = nil, placeholder: String, accessibilityIdentifier: String, settingIsValid isValueValid: ((String?) -> Bool)? = nil, settingDidChange: ((String?) -> Void)? = nil) { self.prefs = prefs self.prefKey = prefKey self.defaultValue = defaultValue self.settingDidChange = settingDidChange self.settingIsValid = isValueValid self.placeholder = placeholder super.init() self.accessibilityIdentifier = accessibilityIdentifier } override func onConfigureCell(_ cell: UITableViewCell) { super.onConfigureCell(cell) if let id = accessibilityIdentifier { textField.accessibilityIdentifier = id + "TextField" } textField.placeholder = placeholder textField.textAlignment = .center textField.delegate = self textField.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged) cell.isUserInteractionEnabled = true cell.accessibilityTraits = UIAccessibilityTraitNone cell.contentView.addSubview(textField) textField.snp.makeConstraints { make in make.height.equalTo(44) make.trailing.equalTo(cell.contentView).offset(-Padding) make.leading.equalTo(cell.contentView).offset(Padding) } textField.text = prefs.stringForKey(prefKey) ?? defaultValue textFieldDidChange(textField) } override func onClick(_ navigationController: UINavigationController?) { textField.becomeFirstResponder() } fileprivate func isValid(_ value: String?) -> Bool { guard let test = settingIsValid else { return true } return test(prepareValidValue(userInput: value)) } /// This gives subclasses an opportunity to treat the user input string /// before it is saved or tested. /// Default implementation does nothing. func prepareValidValue(userInput value: String?) -> String? { return value } @objc func textFieldDidChange(_ textField: UITextField) { let color = isValid(textField.text) ? UIConstants.TableViewRowTextColor : UIConstants.DestructiveRed textField.textColor = color } @objc func textFieldShouldReturn(_ textField: UITextField) -> Bool { return isValid(textField.text) } @objc func textFieldDidEndEditing(_ textField: UITextField) { let text = textField.text if !isValid(text) { return } if let text = prepareValidValue(userInput: text) { prefs.setString(text, forKey: prefKey) } else { prefs.removeObjectForKey(prefKey) } // Call settingDidChange with text or nil. settingDidChange?(text) } } /// A helper class for a setting backed by a UITextField. /// This takes an optional isEnabled and mandatory onClick callback /// isEnabled is called on each tableview.reloadData. If it returns /// false then the 'button' appears disabled. class ButtonSetting: Setting { let onButtonClick: (UINavigationController?) -> Void let destructive: Bool let isEnabled: (() -> Bool)? init(title: NSAttributedString?, destructive: Bool = false, accessibilityIdentifier: String, isEnabled: (() -> Bool)? = nil, onClick: @escaping (UINavigationController?) -> Void) { self.onButtonClick = onClick self.destructive = destructive self.isEnabled = isEnabled super.init(title: title) self.accessibilityIdentifier = accessibilityIdentifier } override func onConfigureCell(_ cell: UITableViewCell) { super.onConfigureCell(cell) if isEnabled?() ?? true { cell.textLabel?.textColor = destructive ? UIConstants.DestructiveRed : UIConstants.HighlightBlue } else { cell.textLabel?.textColor = UIConstants.TableViewDisabledRowTextColor } cell.textLabel?.textAlignment = NSTextAlignment.center cell.accessibilityTraits = UIAccessibilityTraitButton cell.selectionStyle = .none } override func onClick(_ navigationController: UINavigationController?) { if isEnabled?() ?? true { onButtonClick(navigationController) } } } // A helper class for prefs that deal with sync. Handles reloading the tableView data if changes to // the fxAccount happen. class AccountSetting: Setting, FxAContentViewControllerDelegate { unowned var settings: SettingsTableViewController var profile: Profile { return settings.profile } override var title: NSAttributedString? { return nil } init(settings: SettingsTableViewController) { self.settings = settings super.init(title: nil) } override func onConfigureCell(_ cell: UITableViewCell) { super.onConfigureCell(cell) if settings.profile.getAccount() != nil { cell.selectionStyle = .none } } override var accessoryType: UITableViewCellAccessoryType { return .none } func contentViewControllerDidSignIn(_ viewController: FxAContentViewController, data: JSON) { if data["keyFetchToken"].string == nil || data["unwrapBKey"].string == nil { // The /settings endpoint sends a partial "login"; ignore it entirely. NSLog("Ignoring didSignIn with keyFetchToken or unwrapBKey missing.") return } // TODO: Error handling. let account = FirefoxAccount.from(profile.accountConfiguration, andJSON: data)! profile.setAccount(account) // Reload the data to reflect the new Account immediately. settings.tableView.reloadData() // And start advancing the Account state in the background as well. settings.SELrefresh() // Dismiss the FxA content view if the account is verified. if let verified = data["verified"].bool, verified { let _ = settings.navigationController?.popToRootViewController(animated: true) } } func contentViewControllerDidCancel(_ viewController: FxAContentViewController) { NSLog("didCancel") let _ = settings.navigationController?.popToRootViewController(animated: true) } } class WithAccountSetting: AccountSetting { override var hidden: Bool { return !profile.hasAccount() } } class WithoutAccountSetting: AccountSetting { override var hidden: Bool { return profile.hasAccount() } } @objc protocol SettingsDelegate: class { func settingsOpenURLInNewTab(_ url: URL) } // The base settings view controller. class SettingsTableViewController: UITableViewController { typealias SettingsGenerator = (SettingsTableViewController, SettingsDelegate?) -> [SettingSection] fileprivate let Identifier = "CellIdentifier" fileprivate let SectionHeaderIdentifier = "SectionHeaderIdentifier" var settings = [SettingSection]() weak var settingsDelegate: SettingsDelegate? var profile: Profile! var tabManager: TabManager! /// Used to calculate cell heights. fileprivate lazy var dummyToggleCell: UITableViewCell = { let cell = UITableViewCell(style: .subtitle, reuseIdentifier: "dummyCell") cell.accessoryView = UISwitch() return cell }() override func viewDidLoad() { super.viewDidLoad() tableView.register(UITableViewCell.self, forCellReuseIdentifier: Identifier) tableView.register(SettingsTableSectionHeaderFooterView.self, forHeaderFooterViewReuseIdentifier: SectionHeaderIdentifier) let tableFooter = SettingsTableFooterView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 128)) tableFooter.showTopBorder = false tableView.tableFooterView = tableFooter tableView.separatorColor = UIConstants.TableViewSeparatorColor tableView.backgroundColor = UIConstants.TableViewHeaderBackgroundColor tableView.estimatedRowHeight = 44 tableView.estimatedSectionHeaderHeight = 44 } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) settings = generateSettings() NotificationCenter.default.addObserver(self, selector: #selector(SettingsTableViewController.SELsyncDidChangeState), name: NotificationProfileDidStartSyncing, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(SettingsTableViewController.SELsyncDidChangeState), name: NotificationProfileDidFinishSyncing, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(SettingsTableViewController.SELfirefoxAccountDidChange), name: NotificationFirefoxAccountChanged, object: nil) tableView.reloadData() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) SELrefresh() } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) NotificationCenter.default.removeObserver(self, name: NotificationProfileDidStartSyncing, object: nil) NotificationCenter.default.removeObserver(self, name: NotificationProfileDidFinishSyncing, object: nil) NotificationCenter.default.removeObserver(self, name: NotificationFirefoxAccountChanged, object: nil) } // Override to provide settings in subclasses func generateSettings() -> [SettingSection] { return [] } @objc fileprivate func SELsyncDidChangeState() { DispatchQueue.main.async { self.tableView.reloadData() } } @objc fileprivate func SELrefresh() { // Through-out, be aware that modifying the control while a refresh is in progress is /not/ supported and will likely crash the app. if let account = self.profile.getAccount() { account.advance().upon { state in DispatchQueue.main.async { () -> Void in self.tableView.reloadData() } } } else { self.tableView.reloadData() } } @objc func SELfirefoxAccountDidChange() { self.tableView.reloadData() } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let section = settings[indexPath.section] if let setting = section[indexPath.row] { var cell: UITableViewCell! if let _ = setting.status { // Work around http://stackoverflow.com/a/9999821 and http://stackoverflow.com/a/25901083 by using a new cell. // I could not make any setNeedsLayout solution work in the case where we disconnect and then connect a new account. // Be aware that dequeing and then ignoring a cell appears to cause issues; only deque a cell if you're going to return it. cell = UITableViewCell(style: setting.style, reuseIdentifier: nil) } else { cell = tableView.dequeueReusableCell(withIdentifier: Identifier, for: indexPath) } setting.onConfigureCell(cell) return cell } return tableView.dequeueReusableCell(withIdentifier: Identifier, for: indexPath) } override func numberOfSections(in tableView: UITableView) -> Int { return settings.count } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let section = settings[section] return section.count } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: SectionHeaderIdentifier) as! SettingsTableSectionHeaderFooterView let sectionSetting = settings[section] if let sectionTitle = sectionSetting.title?.string { headerView.titleLabel.text = sectionTitle } // Hide the top border for the top section to avoid having a double line at the top if section == 0 { headerView.showTopBorder = false } else { headerView.showTopBorder = true } return headerView } override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { let footerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: SectionHeaderIdentifier) as! SettingsTableSectionHeaderFooterView let sectionSetting = settings[section] if let sectionFooter = sectionSetting.footerTitle?.string { footerView.titleLabel.text = sectionFooter } footerView.titleAlignment = .top footerView.showBottomBorder = false return footerView } //is this needed? override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { let sectionSetting = settings[section] if let _ = sectionSetting.footerTitle?.string { return 44 } return 0 } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { let section = settings[indexPath.section] // Workaround for calculating the height of default UITableViewCell cells with a subtitle under // the title text label. if let setting = section[indexPath.row], setting is BoolSetting && setting.status != nil { return calculateStatusCellHeightForSetting(setting) } if let setting = section[indexPath.row], let height = setting.cellHeight { return height } return UITableViewAutomaticDimension } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let section = settings[indexPath.section] if let setting = section[indexPath.row], setting.enabled { setting.onClick(navigationController) } } fileprivate func calculateStatusCellHeightForSetting(_ setting: Setting) -> CGFloat { dummyToggleCell.layoutSubviews() let topBottomMargin: CGFloat = 10 let width = dummyToggleCell.contentView.frame.width - 2 * dummyToggleCell.separatorInset.left return heightForLabel(dummyToggleCell.textLabel!, width: width, text: setting.title?.string) + heightForLabel(dummyToggleCell.detailTextLabel!, width: width, text: setting.status?.string) + 2 * topBottomMargin } fileprivate func heightForLabel(_ label: UILabel, width: CGFloat, text: String?) -> CGFloat { guard let text = text else { return 0 } let size = CGSize(width: width, height: CGFloat.greatestFiniteMagnitude) let attrs = [NSFontAttributeName: label.font as Any] let boundingRect = NSString(string: text).boundingRect(with: size, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: attrs, context: nil) return boundingRect.height } } class SettingsTableFooterView: UIView { var logo: UIImageView = { var image = UIImageView(image: UIImage(named: "settingsFlatfox")) image.contentMode = UIViewContentMode.center image.accessibilityIdentifier = "SettingsTableFooterView.logo" return image }() fileprivate lazy var topBorder: CALayer = { let topBorder = CALayer() topBorder.backgroundColor = UIConstants.SeparatorColor.cgColor return topBorder }() override init(frame: CGRect) { super.init(frame: frame) backgroundColor = UIConstants.TableViewHeaderBackgroundColor layer.addSublayer(topBorder) addSubview(logo) } var showTopBorder: Bool = true { didSet { topBorder.isHidden = !showTopBorder } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() topBorder.frame = CGRect(x: 0.0, y: 0.0, width: frame.size.width, height: 0.5) logo.center = CGPoint(x: frame.size.width / 2, y: frame.size.height / 2) } } struct SettingsTableSectionHeaderFooterViewUX { static let titleHorizontalPadding: CGFloat = 15 static let titleVerticalPadding: CGFloat = 6 static let titleVerticalLongPadding: CGFloat = 20 } class SettingsTableSectionHeaderFooterView: UITableViewHeaderFooterView { enum TitleAlignment { case top case bottom } var titleAlignment: TitleAlignment = .bottom { didSet { remakeTitleAlignmentConstraints() } } var showTopBorder: Bool = true { didSet { topBorder.isHidden = !showTopBorder } } var showBottomBorder: Bool = true { didSet { bottomBorder.isHidden = !showBottomBorder } } lazy var titleLabel: UILabel = { var headerLabel = UILabel() headerLabel.textColor = UIConstants.TableViewHeaderTextColor headerLabel.font = UIFont.systemFont(ofSize: 12.0, weight: UIFontWeightRegular) headerLabel.numberOfLines = 0 return headerLabel }() fileprivate lazy var topBorder: UIView = { let topBorder = UIView() topBorder.backgroundColor = UIConstants.SeparatorColor return topBorder }() fileprivate lazy var bottomBorder: UIView = { let bottomBorder = UIView() bottomBorder.backgroundColor = UIConstants.SeparatorColor return bottomBorder }() override init(reuseIdentifier: String?) { super.init(reuseIdentifier: reuseIdentifier) contentView.backgroundColor = UIConstants.TableViewHeaderBackgroundColor addSubview(titleLabel) addSubview(topBorder) addSubview(bottomBorder) setupInitialConstraints() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setupInitialConstraints() { bottomBorder.snp.makeConstraints { make in make.bottom.left.right.equalTo(self) make.height.equalTo(0.5) } topBorder.snp.makeConstraints { make in make.top.left.right.equalTo(self) make.height.equalTo(0.5) } remakeTitleAlignmentConstraints() } override func prepareForReuse() { super.prepareForReuse() showTopBorder = true showBottomBorder = true titleLabel.text = nil titleAlignment = .bottom } fileprivate func remakeTitleAlignmentConstraints() { switch titleAlignment { case .top: titleLabel.snp.remakeConstraints { make in make.left.right.equalTo(self).inset(SettingsTableSectionHeaderFooterViewUX.titleHorizontalPadding) make.top.equalTo(self).offset(SettingsTableSectionHeaderFooterViewUX.titleVerticalPadding) make.bottom.equalTo(self).offset(-SettingsTableSectionHeaderFooterViewUX.titleVerticalLongPadding) } case .bottom: titleLabel.snp.remakeConstraints { make in make.left.right.equalTo(self).inset(SettingsTableSectionHeaderFooterViewUX.titleHorizontalPadding) make.bottom.equalTo(self).offset(-SettingsTableSectionHeaderFooterViewUX.titleVerticalPadding) make.top.equalTo(self).offset(SettingsTableSectionHeaderFooterViewUX.titleVerticalLongPadding) } } } }
mpl-2.0
3aa4da99a44f609ca75d878150f98b7b
37.877551
304
0.679615
5.462627
false
false
false
false
nktn/MalKit
MalKit/MalKitUtil.swift
1
8912
// // MalKitUtil.swift // MalKit // // Created by nktn on 2017/08/14. // Copyright © 2017年 nktn. All rights reserved. // import Foundation class MalKitUtil { var minValueS: Int var maxValueS: Int var minValueE: Int var maxValueE: Int init(){ //1/reading, 2/completed, 3/onhold, 4/dropped, 6/plantoread minValueS = 1 maxValueS = 6 //int. 1=enable, 0=disable minValueE = 0 maxValueE = 1 } //MARK: - dateparamseter from https://myanimelist.net/modules.php?go=api private func dateString(date: Date) -> String { let formatter = DateFormatter() formatter.dateFormat = "MMddyyyy" let dateString = formatter.string(from: date) return dateString } //MARK: - Add and Update Anime Query func makeAnimeQuerty(params: Dictionary<String, Any>, type: Int) -> String? { let query :Array<Any?> = parseAnimeParam(params:params) var str = "<entry>" if query[0] as? Int != nil { str += "<episode>" str += String(query[0] as! Int) str += "</episode>" } if type == MalKitGlobalVar.requestUpdate { if query[1] as? Int != nil { str += "<status>" str += String(min(max(query[1] as! Int, minValueS), maxValueS)) str += "</status>" } } else { if query[1] as? Int != nil { str += "<status>" str += String(min(max(query[1] as! Int, minValueS), maxValueS)) str += "</status>" } } if query[2] as? Int != nil { str += "<score>" str += String(query[2] as! Int) str += "</score>" } if query[3] as? Int != nil { str += "<storage_type>" str += String(query[3] as! Int) str += "</storage_type>" } if query[4] as? Float != nil { str += "<storage_value>" str += String(query[4] as! Float) str += "</storage_value>" } if query[5] as? Int != nil { str += "<times_rewatched>" str += String(query[5] as! Int) str += "</times_rewatched>" } if query[6] as? Int != nil { str += "<rewatch_value>" str += String(query[6] as! Int) str += "</rewatch_value>" } if query[7] as? Date != nil{ str += "<date_start>" str += self.dateString(date: query[7] as! Date) str += "</date_start>" } else if query[7] as? String == "" { str += "<date_start>" str += "</date_start>" } if query[8] as? Date != nil{ str += "<date_finish>" str += self.dateString(date: query[8] as! Date) str += "</date_finish>" } else if query[8] as? String == "" { str += "<date_finish>" str += "</date_finish>" } if query[9] as? Int != nil { str += "<priority>" str += String(query[9] as! Int) str += "</priority>" } if query[10] as? Int != nil { str += "<enable_discussion>" str += String(min(max(query[10] as! Int, minValueE), maxValueE)) str += "</enable_discussion>" } if query[11] as? Int != nil { str += "<enable_rewatching>" str += String(min(max(query[11] as! Int, minValueE), maxValueE)) str += "</enable_rewatching>" } if query[12] as? String != nil { str += "<comments>" str += query[12] as! String str += "</comments>" } if query[13] as? String != nil { str += "<tags>" str += query[13] as! String str += "</tags>" } str += "</entry>" return str } //MARK: - Add and Update Manga Query func makeMangaQuerty(params: Dictionary<String, Any>, type: Int) -> String? { let query :Array<Any?> = parseMangaParam(params:params) //let query_check = query.flatMap{$0} //if query_check.count == 0{ // return nil //} var str = "<entry>" if query[0] as? Int != nil { str += "<chapter>" str += String(query[0] as! Int) str += "</chapter>" } if query[1] as? Int != nil { str += "<volume>" str += String(query[1] as! Int) str += "</volume>" } if type == MalKitGlobalVar.requestUpdate { if query[2] as? Int != nil { str += "<status>" str += String(min(max(query[2] as! Int, minValueS), maxValueS)) str += "</status>" } }else{ if query[2] as? Int != nil { str += "<status>" str += String(min(max(query[2] as! Int, minValueS), maxValueS)) str += "</status>" } } if query[3] as? Int != nil { str += "<score>" str += String(query[3] as! Int) str += "</score>" } if query[4] as? Int != nil { str += "<times_reread>" str += String(query[4] as! Int) str += "</times_reread>" } if query[5] as? Int != nil { str += "<reread_value>" str += String(query[5] as! Int) str += "</reread_value>" } if query[6] as? Date != nil { str += "<date_start>" str += self.dateString(date: query[6] as! Date) str += "</date_start>" }else if query[6] as? String == ""{ str += "<date_start>" str += "</date_start>" } if query[7] as? Date != nil { str += "<date_finish>" str += self.dateString(date: query[7] as! Date) str += "</date_finish>" }else if query[7] as? String == "" { str += "<date_finish>" str += "</date_finish>" } if query[8] as? Int != nil { str += "<priority>" str += String(query[8] as! Int) str += "</priority>" } if query[9] as? Int != nil { str += "<enable_discussion>" str += String(min(max(query[9] as! Int, minValueE), maxValueE)) str += "</enable_discussion>" } if query[10] as? Int != nil { str += "<enable_rereading>" str += String(min(max(query[10] as! Int, minValueE), maxValueE)) str += "</enable_rereading>" } if query[11] as? String != nil { str += "<comments>" str += query[11] as! String str += "</comments>" } if query[12] as? String != nil { str += "<scan_group>" str += query[12] as! String str += "</scan_group>" } if query[13] as? String != nil { str += "<tags>" str += query[13] as! String str += "</tags>" } if query[14] as? Int != nil { str += "<retail_volumes>" str += String(query[14] as! Int) str += "</retail_volumes>" } str += "</entry>" return str } //MARK: - parse anime param private func parseAnimeParam(params: Dictionary<String, Any>) -> Array<Any?>{ let parsedParams = [params["episode"],params["status"],params["score"],params["storage_type"],params["storage_value"],params["times_rewatched"], params["rewatch_value"],params["date_start"],params["date_finish"], params["priority"],params["enable_discussion"],params["enable_rewatching"], params["comments"],params["tags"]] return parsedParams } //MARK: - parse manga param private func parseMangaParam(params: Dictionary<String, Any>) -> Array<Any?>{ let parsedParams = [params["chapter"],params["volume"],params["status"],params["score"],params["times_reread"],params["reread_value"], params["date_start"], params["date_finish"],params["priority"], params["enable_discussion"],params["enable_rereading"],params["comments"], params["scan_group"],params["tags"],params["retail_volumes"]] return parsedParams } //MARK: - debug log func debugLog(_ obj: Any?, function: String = #function, line: Int = #line) { #if DEBUG if let obj = obj { print("[Function:\(function) Line:\(line)] : \(obj)") } else { print("[Function:\(function) Line:\(line)]") } #endif } }
mit
d219d3c8a5f677c7a93f5dd43bf16bfc
34.353175
152
0.455607
3.980786
false
false
false
false
devpunk/velvet_room
Source/View/SaveData/VSaveDataBar.swift
1
1995
import UIKit final class VSaveDataBar:View<ArchSaveData> { weak var layoutHeight:NSLayoutConstraint! private weak var viewThumbnail:VSaveDataBarThumbnail! private let kThumbnailSize:CGFloat = 134 required init(controller:CSaveData) { super.init(controller:controller) factoryViews() } required init?(coder:NSCoder) { return nil } override func layoutSubviews() { let width:CGFloat = bounds.width let height:CGFloat = bounds.height let thumbnailRemainWidth:CGFloat = width - kThumbnailSize let thumbnailRemainHeight:CGFloat = height - kThumbnailSize let thumbnailMarginLeft:CGFloat = thumbnailRemainWidth / 2.0 let thumbnailMarginTop:CGFloat = thumbnailRemainHeight / 2.0 viewThumbnail.layoutLeft.constant = thumbnailMarginLeft viewThumbnail.layoutTop.constant = thumbnailMarginTop super.layoutSubviews() } //MARK: private private func factoryViews() { let cornerRadius:CGFloat = kThumbnailSize / 2.0 let viewBackground:VSaveDataBarBackground = VSaveDataBarBackground( controller:controller) let viewThumbnail:VSaveDataBarThumbnail = VSaveDataBarThumbnail( controller:controller) viewThumbnail.layer.cornerRadius = cornerRadius self.viewThumbnail = viewThumbnail addSubview(viewBackground) addSubview(viewThumbnail) NSLayoutConstraint.equals( view:viewBackground, toView:self) viewThumbnail.layoutTop = NSLayoutConstraint.topToTop( view:viewThumbnail, toView:self) viewThumbnail.layoutLeft = NSLayoutConstraint.leftToLeft( view:viewThumbnail, toView:self) NSLayoutConstraint.size( view:viewThumbnail, constant:kThumbnailSize) } }
mit
a02fb6344219df997304c5a1312d9e1b
28.776119
75
0.645614
5.377358
false
false
false
false
dunkelstern/FastString
src/split.swift
1
5377
// Copyright (c) 2016 Johannes Schriewer. // // 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. /// String splitting and joining public extension FastString { /// Join array of strings by using a delimiter string /// /// - parameter parts: parts to join /// - parameter delimiter: delimiter to insert /// - returns: combined string public static func join(parts: [FastString], delimiter: FastString) -> FastString { let result = FastString() if parts.count == 0 { // Nothing to join here return result } // calculate final length to reserve space var len = 0 for part in parts { len += part.byteCount } len += delimiter.byteCount * (parts.count - 1) // reserve space let memory = UnsafeMutablePointer<UInt8>(allocatingCapacity: len + 1) memory[len] = 0 // join string parts var index = 0 for (idx, part) in parts.enumerated() { for c in part.makeByteIterator() { memory[index] = c index += 1 } if idx < parts.count - 1 { for c in delimiter.makeByteIterator() { memory[index] = c index += 1 } } } result.buffer.baseAddress!.deallocateCapacity(result.buffer.count + 1) result.buffer = UnsafeMutableBufferPointer(start: memory, count: len) return result } public static func join(parts: [String], delimiter: String) -> FastString { let fastParts = parts.map { part in return FastString(part) } return self.join(parts: fastParts, delimiter: FastString(delimiter)) } /// Join array of strings by using a delimiter character /// /// - parameter parts: parts to join /// - parameter delimiter: delimiter to insert /// - returns: combined string public static func join(parts: [FastString], delimiter: Character) -> FastString { return self.join(parts: parts, delimiter: FastString(String(delimiter))) } public static func join(parts: [String], delimiter: Character) -> FastString { let fastParts = parts.map { part in return FastString(part) } return self.join(parts: fastParts, delimiter: delimiter) } /// Join array of strings /// /// - parameter parts: parts to join /// - returns: combined string public static func join(parts: [FastString]) -> FastString { // calculate final length to reserve space var len = 0 for part in parts { len += part.byteCount } // reserve space var result = [UInt8]() result.reserveCapacity(len) // join string parts for part in parts { for c in part.makeByteIterator() { result.append(c) } } return FastString(array: result) } public static func join(parts: [String]) -> FastString { let fastParts = parts.map { part in return FastString(part) } return self.join(parts: fastParts) } /// Split string into array by using delimiter character /// /// - parameter character: delimiter to use /// - parameter maxSplits: (optional) maximum number of splits, set to 0 to allow unlimited splits /// - returns: array with string components public func split(character: UInt8, maxSplits: Int = 0) -> [FastString] { return self.buffer.split(separator: character, maxSplits: maxSplits).map { slice in return FastString(slice: slice) } } public func split(character: Character, maxSplits: Int = 0) -> [FastString] { return self.split(string: String(character), maxSplits: maxSplits) } /// Split string into array by using delimiter string /// /// - parameter string: delimiter to use /// - parameter maxSplits: (optional) maximum number of splits, set to 0 to allow unlimited splits /// - returns: array with string components public func split(string: FastString, maxSplits: Int = 0) -> [FastString] { var result = [FastString]() let positions = self.positions(string: string) var start = 0 for idx in positions { let subString = self.subString(range: start..<idx) result.append(subString) start += subString.byteCount + string.byteCount if result.count == maxSplits { break } } result.append(self.subString(range: start..<self.byteCount)) return result } public func split(string: String, maxSplits: Int = 0) -> [FastString] { return self.split(string: FastString(string), maxSplits: maxSplits) } }
apache-2.0
92ad214a7190d7684b78fef989d64143
33.037975
102
0.604426
4.720808
false
false
false
false
jum/Charts
Source/Charts/Utils/ChartColorTemplates.swift
8
7888
// // ChartColorTemplates.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics open class ChartColorTemplates: NSObject { @objc open class func liberty () -> [NSUIColor] { return [ NSUIColor(red: 207/255.0, green: 248/255.0, blue: 246/255.0, alpha: 1.0), NSUIColor(red: 148/255.0, green: 212/255.0, blue: 212/255.0, alpha: 1.0), NSUIColor(red: 136/255.0, green: 180/255.0, blue: 187/255.0, alpha: 1.0), NSUIColor(red: 118/255.0, green: 174/255.0, blue: 175/255.0, alpha: 1.0), NSUIColor(red: 42/255.0, green: 109/255.0, blue: 130/255.0, alpha: 1.0) ] } @objc open class func joyful () -> [NSUIColor] { return [ NSUIColor(red: 217/255.0, green: 80/255.0, blue: 138/255.0, alpha: 1.0), NSUIColor(red: 254/255.0, green: 149/255.0, blue: 7/255.0, alpha: 1.0), NSUIColor(red: 254/255.0, green: 247/255.0, blue: 120/255.0, alpha: 1.0), NSUIColor(red: 106/255.0, green: 167/255.0, blue: 134/255.0, alpha: 1.0), NSUIColor(red: 53/255.0, green: 194/255.0, blue: 209/255.0, alpha: 1.0) ] } @objc open class func pastel () -> [NSUIColor] { return [ NSUIColor(red: 64/255.0, green: 89/255.0, blue: 128/255.0, alpha: 1.0), NSUIColor(red: 149/255.0, green: 165/255.0, blue: 124/255.0, alpha: 1.0), NSUIColor(red: 217/255.0, green: 184/255.0, blue: 162/255.0, alpha: 1.0), NSUIColor(red: 191/255.0, green: 134/255.0, blue: 134/255.0, alpha: 1.0), NSUIColor(red: 179/255.0, green: 48/255.0, blue: 80/255.0, alpha: 1.0) ] } @objc open class func colorful () -> [NSUIColor] { return [ NSUIColor(red: 193/255.0, green: 37/255.0, blue: 82/255.0, alpha: 1.0), NSUIColor(red: 255/255.0, green: 102/255.0, blue: 0/255.0, alpha: 1.0), NSUIColor(red: 245/255.0, green: 199/255.0, blue: 0/255.0, alpha: 1.0), NSUIColor(red: 106/255.0, green: 150/255.0, blue: 31/255.0, alpha: 1.0), NSUIColor(red: 179/255.0, green: 100/255.0, blue: 53/255.0, alpha: 1.0) ] } @objc open class func vordiplom () -> [NSUIColor] { return [ NSUIColor(red: 192/255.0, green: 255/255.0, blue: 140/255.0, alpha: 1.0), NSUIColor(red: 255/255.0, green: 247/255.0, blue: 140/255.0, alpha: 1.0), NSUIColor(red: 255/255.0, green: 208/255.0, blue: 140/255.0, alpha: 1.0), NSUIColor(red: 140/255.0, green: 234/255.0, blue: 255/255.0, alpha: 1.0), NSUIColor(red: 255/255.0, green: 140/255.0, blue: 157/255.0, alpha: 1.0) ] } @objc open class func material () -> [NSUIColor] { return [ NSUIColor(red: 46/255.0, green: 204/255.0, blue: 113/255.0, alpha: 1.0), NSUIColor(red: 241/255.0, green: 196/255.0, blue: 15/255.0, alpha: 1.0), NSUIColor(red: 231/255.0, green: 76/255.0, blue: 60/255.0, alpha: 1.0), NSUIColor(red: 52/255.0, green: 152/255.0, blue: 219/255.0, alpha: 1.0) ] } @objc open class func colorFromString(_ colorString: String) -> NSUIColor { let leftParenCharset: CharacterSet = CharacterSet(charactersIn: "( ") let commaCharset: CharacterSet = CharacterSet(charactersIn: ", ") let colorString = colorString.lowercased() if colorString.hasPrefix("#") { var argb: [UInt] = [255, 0, 0, 0] let colorString = colorString.unicodeScalars var length = colorString.count var index = colorString.startIndex let endIndex = colorString.endIndex index = colorString.index(after: index) length = length - 1 if length == 3 || length == 6 || length == 8 { var i = length == 8 ? 0 : 1 while index < endIndex { var c = colorString[index] index = colorString.index(after: index) var val = (c.value >= 0x61 && c.value <= 0x66) ? (c.value - 0x61 + 10) : c.value - 0x30 argb[i] = UInt(val) * 16 if length == 3 { argb[i] = argb[i] + UInt(val) } else { c = colorString[index] index = colorString.index(after: index) val = (c.value >= 0x61 && c.value <= 0x66) ? (c.value - 0x61 + 10) : c.value - 0x30 argb[i] = argb[i] + UInt(val) } i += 1 } } return NSUIColor(red: CGFloat(argb[1]) / 255.0, green: CGFloat(argb[2]) / 255.0, blue: CGFloat(argb[3]) / 255.0, alpha: CGFloat(argb[0]) / 255.0) } else if colorString.hasPrefix("rgba") { var a: Float = 1.0 var r: Int32 = 0 var g: Int32 = 0 var b: Int32 = 0 let scanner: Scanner = Scanner(string: colorString) scanner.scanString("rgba", into: nil) scanner.scanCharacters(from: leftParenCharset, into: nil) scanner.scanInt32(&r) scanner.scanCharacters(from: commaCharset, into: nil) scanner.scanInt32(&g) scanner.scanCharacters(from: commaCharset, into: nil) scanner.scanInt32(&b) scanner.scanCharacters(from: commaCharset, into: nil) scanner.scanFloat(&a) return NSUIColor( red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: CGFloat(a) ) } else if colorString.hasPrefix("argb") { var a: Float = 1.0 var r: Int32 = 0 var g: Int32 = 0 var b: Int32 = 0 let scanner: Scanner = Scanner(string: colorString) scanner.scanString("argb", into: nil) scanner.scanCharacters(from: leftParenCharset, into: nil) scanner.scanFloat(&a) scanner.scanCharacters(from: commaCharset, into: nil) scanner.scanInt32(&r) scanner.scanCharacters(from: commaCharset, into: nil) scanner.scanInt32(&g) scanner.scanCharacters(from: commaCharset, into: nil) scanner.scanInt32(&b) return NSUIColor( red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: CGFloat(a) ) } else if colorString.hasPrefix("rgb") { var r: Int32 = 0 var g: Int32 = 0 var b: Int32 = 0 let scanner: Scanner = Scanner(string: colorString) scanner.scanString("rgb", into: nil) scanner.scanCharacters(from: leftParenCharset, into: nil) scanner.scanInt32(&r) scanner.scanCharacters(from: commaCharset, into: nil) scanner.scanInt32(&g) scanner.scanCharacters(from: commaCharset, into: nil) scanner.scanInt32(&b) return NSUIColor( red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: 1.0 ) } return NSUIColor.clear } }
apache-2.0
6638d39adf878b8531bed87eaa015fc9
38.838384
157
0.507733
3.630005
false
false
false
false
WalterCreazyBear/Swifter30
ArtList/ArtList/ViewController.swift
1
2091
// // ViewController.swift // ArtList // // Created by Bear on 2017/6/26. // Copyright © 2017年 Bear. All rights reserved. // import UIKit class ViewController: UIViewController { let artlistDataSource = Artist.artistsFromBundle() let cellID = "CELLID" lazy var table:UITableView = { let table = UITableView.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)) table.backgroundColor = UIColor.white table.delegate = self table.dataSource = self table.register(ArtistTableViewCell.self, forCellReuseIdentifier: self.cellID) return table }() override func viewDidLoad() { super.viewDidLoad() title = "ArtList" view.backgroundColor = UIColor.white view.addSubview(self.table) } } extension ViewController:UITableViewDelegate,UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return artlistDataSource.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) cell.selectionStyle = .none let artist = artlistDataSource[indexPath.row] if cell.isKind(of: ArtistTableViewCell.self) { (cell as! ArtistTableViewCell).bindData(model: artist) } return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 160 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard indexPath.row<artlistDataSource.count else { return } let artist = artlistDataSource[indexPath.row] let workVC = WorksViewController.init(model: artist) navigationController?.pushViewController(workVC, animated: true) } }
mit
b411995a4b3d395ab7db6488a252ada6
31.123077
140
0.670498
4.778032
false
false
false
false
spire-inc/Bond
Sources/AppKit/NSControl.swift
4
3136
// // The MIT License (MIT) // // Copyright (c) 2016 Tony Arnold (@tonyarnold) // // 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 ReactiveKit import AppKit @objc class RKNSControlHelper: NSObject { weak var control: NSControl? let subject = PublishSubject<AnyObject?, NoError>() init(control: NSControl) { self.control = control super.init() control.target = self control.action = #selector(eventHandler) } func eventHandler(_ sender: NSControl?) { subject.next(sender!.objectValue as AnyObject?) } deinit { control?.target = nil control?.action = nil subject.completed() } } extension NSControl { private struct AssociatedKeys { static var ControlHelperKey = "bnd_ControlHelperKey" } public var rControlEvent: Signal1<AnyObject?> { if let controlHelper = objc_getAssociatedObject(self, &AssociatedKeys.ControlHelperKey) as AnyObject? { return (controlHelper as! RKNSControlHelper).subject.toSignal() } else { let controlHelper = RKNSControlHelper(control: self) objc_setAssociatedObject(self, &AssociatedKeys.ControlHelperKey, controlHelper, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) return controlHelper.subject.toSignal() } } public var bnd_isEnabled: Bond<NSControl, Bool> { return Bond(target: self) { $0.isEnabled = $1 } } public var bnd_objectValue: Bond<NSControl, AnyObject?> { return Bond(target: self) { $0.objectValue = $1 } } public var bnd_stringValue: Bond<NSControl, String> { return Bond(target: self) { $0.stringValue = $1 } } public var bnd_attributedStringleValue: Bond<NSControl, NSAttributedString> { return Bond(target: self) { $0.attributedStringValue = $1 } } public var bnd_integerValue: Bond<NSControl, Int> { return Bond(target: self) { $0.integerValue = $1 } } public var bnd_floatValue: Bond<NSControl, Float> { return Bond(target: self) { $0.floatValue = $1 } } public var bnd_doubleValue: Bond<NSControl, Double> { return Bond(target: self) { $0.doubleValue = $1 } } }
mit
6b281d26d5794230153fe1a347ea9216
32.010526
143
0.715561
4.093995
false
false
false
false
apple/swift-nio
Tests/NIOPosixTests/UniversalBootstrapSupportTest.swift
1
9302
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2020-2021 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import XCTest import NIOCore import NIOEmbedded import NIOPosix import NIOTestUtils class UniversalBootstrapSupportTest: XCTestCase { func testBootstrappingWorks() { let group = MultiThreadedEventLoopGroup(numberOfThreads: 1) defer { XCTAssertNoThrow(try group.syncShutdownGracefully()) } final class DropChannelReadsHandler: ChannelInboundHandler { typealias InboundIn = Any func channelRead(context: ChannelHandlerContext, data: NIOAny) { // drop } } final class DummyTLSProvider: NIOClientTLSProvider { typealias Bootstrap = ClientBootstrap final class DropInboundEventsHandler: ChannelInboundHandler { typealias InboundIn = Any func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) { // drop } } func enableTLS(_ bootstrap: ClientBootstrap) -> ClientBootstrap { return bootstrap.protocolHandlers { [DropInboundEventsHandler()] } } } final class FishOutChannelHandler: ChannelInboundHandler { typealias InboundIn = Channel var acceptedChannels: [Channel] = [] let firstArrived: EventLoopPromise<Void> init(firstArrived: EventLoopPromise<Void>) { self.firstArrived = firstArrived } func channelRead(context: ChannelHandlerContext, data: NIOAny) { let channel = self.unwrapInboundIn(data) self.acceptedChannels.append(channel) if self.acceptedChannels.count == 1 { self.firstArrived.succeed(()) } context.fireChannelRead(data) } } XCTAssertNoThrow(try withTCPServerChannel(group: group) { server in let firstArrived = group.next().makePromise(of: Void.self) let counter1 = EventCounterHandler() let counter2 = EventCounterHandler() let channelFisher = FishOutChannelHandler(firstArrived: firstArrived) XCTAssertNoThrow(try server.pipeline.addHandler(channelFisher).wait()) let client = try NIOClientTCPBootstrap(ClientBootstrap(group: group), tls: DummyTLSProvider()) .channelInitializer { channel in channel.pipeline.addHandlers(counter1, DropChannelReadsHandler(), counter2) } .channelOption(ChannelOptions.autoRead, value: false) .connectTimeout(.hours(1)) .enableTLS() .connect(to: server.localAddress!) .wait() defer { XCTAssertNoThrow(try client.close().wait()) } var buffer = client.allocator.buffer(capacity: 16) buffer.writeString("hello") var maybeAcceptedChannel: Channel? = nil XCTAssertNoThrow(try firstArrived.futureResult.wait()) XCTAssertNoThrow(maybeAcceptedChannel = try server.eventLoop.submit { XCTAssertEqual(1, channelFisher.acceptedChannels.count) return channelFisher.acceptedChannels.first }.wait()) guard let acceptedChannel = maybeAcceptedChannel else { XCTFail("couldn't fish out the accepted channel") return } XCTAssertNoThrow(try acceptedChannel.writeAndFlush(buffer).wait()) // auto-read is off, so we shouldn't see any reads/channelReads XCTAssertEqual(0, counter1.readCalls) XCTAssertEqual(0, counter2.readCalls) XCTAssertEqual(0, counter1.channelReadCalls) XCTAssertEqual(0, counter2.channelReadCalls) // let's do a read XCTAssertNoThrow(try client.eventLoop.submit { client.read() }.wait()) XCTAssertEqual(1, counter1.readCalls) XCTAssertEqual(1, counter2.readCalls) // let's check that the order is right XCTAssertNoThrow(try client.eventLoop.submit { client.pipeline.fireChannelRead(NIOAny(buffer)) client.pipeline.fireUserInboundEventTriggered(buffer) }.wait()) // the protocol handler which was added by the "TLS" implementation should be first, it however drops // inbound events so we shouldn't see them XCTAssertEqual(0, counter1.userInboundEventTriggeredCalls) XCTAssertEqual(0, counter2.userInboundEventTriggeredCalls) // the channelReads so have gone through but only to counter1 XCTAssertGreaterThanOrEqual(counter1.channelReadCalls, 1) XCTAssertEqual(0, counter2.channelReadCalls) }) } func testBootstrapOverrideOfShortcutOptions() { final class FakeBootstrap : NIOClientTCPBootstrapProtocol { func channelInitializer(_ handler: @escaping (Channel) -> EventLoopFuture<Void>) -> Self { fatalError("Not implemented") } func protocolHandlers(_ handlers: @escaping () -> [ChannelHandler]) -> Self { fatalError("Not implemented") } var regularOptionsSeen = false func channelOption<Option>(_ option: Option, value: Option.Value) -> Self where Option : ChannelOption { regularOptionsSeen = true return self } var convenienceOptionConsumed = false func _applyChannelConvenienceOptions(_ options: inout ChannelOptions.TCPConvenienceOptions) -> FakeBootstrap { if options.consumeAllowLocalEndpointReuse().isSet { convenienceOptionConsumed = true } return self } func connectTimeout(_ timeout: TimeAmount) -> Self { fatalError("Not implemented") } func connect(host: String, port: Int) -> EventLoopFuture<Channel> { fatalError("Not implemented") } func connect(to address: SocketAddress) -> EventLoopFuture<Channel> { fatalError("Not implemented") } func connect(unixDomainSocketPath: String) -> EventLoopFuture<Channel> { fatalError("Not implemented") } } // Check consumption works. let consumingFake = FakeBootstrap() _ = NIOClientTCPBootstrap(consumingFake, tls: NIOInsecureNoTLS()) .channelConvenienceOptions([.allowLocalEndpointReuse]) XCTAssertTrue(consumingFake.convenienceOptionConsumed) XCTAssertFalse(consumingFake.regularOptionsSeen) // Check default behaviour works. let nonConsumingFake = FakeBootstrap() _ = NIOClientTCPBootstrap(nonConsumingFake, tls: NIOInsecureNoTLS()) .channelConvenienceOptions([.allowRemoteHalfClosure]) XCTAssertFalse(nonConsumingFake.convenienceOptionConsumed) XCTAssertTrue(nonConsumingFake.regularOptionsSeen) // Both at once. let bothFake = FakeBootstrap() _ = NIOClientTCPBootstrap(bothFake, tls: NIOInsecureNoTLS()) .channelConvenienceOptions([.allowRemoteHalfClosure, .allowLocalEndpointReuse]) XCTAssertTrue(bothFake.convenienceOptionConsumed) XCTAssertTrue(bothFake.regularOptionsSeen) } } // Prove we've not broken implementors of NIOClientTCPBootstrapProtocol by adding a new method. private class UniversalWithoutNewMethods : NIOClientTCPBootstrapProtocol { func channelInitializer(_ handler: @escaping (Channel) -> EventLoopFuture<Void>) -> Self { return self } func protocolHandlers(_ handlers: @escaping () -> [ChannelHandler]) -> Self { return self } func channelOption<Option>(_ option: Option, value: Option.Value) -> Self where Option : ChannelOption { return self } func connectTimeout(_ timeout: TimeAmount) -> Self { return self } func connect(host: String, port: Int) -> EventLoopFuture<Channel> { return EmbeddedEventLoop().makePromise(of: Channel.self).futureResult } func connect(to address: SocketAddress) -> EventLoopFuture<Channel> { return EmbeddedEventLoop().makePromise(of: Channel.self).futureResult } func connect(unixDomainSocketPath: String) -> EventLoopFuture<Channel> { return EmbeddedEventLoop().makePromise(of: Channel.self).futureResult } }
apache-2.0
50b82ba6161efa4f7c42db5939078ae8
38.922747
122
0.608041
5.596871
false
false
false
false
apple/swift-nio
IntegrationTests/tests_04_performance/test_01_resources/test_1000_udpbootstraps.swift
1
1075
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2020-2021 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import NIOCore import NIOPosix fileprivate final class DoNothingHandler: ChannelInboundHandler { public typealias InboundIn = ByteBuffer public typealias OutboundOut = ByteBuffer } func run(identifier: String) { measure(identifier: identifier) { let numberOfIterations = 1000 for _ in 0 ..< numberOfIterations { _ = DatagramBootstrap(group: group) .channelInitializer { channel in channel.pipeline.addHandler(DoNothingHandler()) } } return numberOfIterations } }
apache-2.0
7b5ba1bb73c1a1082ee33a48444ecf5f
30.617647
80
0.577674
5.512821
false
false
false
false
dasdom/AllergyDiary
AllergyDiary/AddEntry/EntryInputDataSource.swift
1
1209
// // EntryInputDataSource.swift // AllergyDiary // // Created by dasdom on 07.06.15. // Copyright (c) 2015 Dominik Hauser. All rights reserved. // import UIKit public class EntryInputDataSource: NSObject, UITableViewDataSource { public let entry: DayEntry public init(entry: DayEntry = DayEntry()) { self.entry = entry } public func numberOfSectionsInTableView(tableView: UITableView) -> Int { return EntryInputSectionTypes.NumberOfSections.rawValue } public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { var numberOfRows = 0 let sectionType = EntryInputSectionTypes(rawValue: section)! switch sectionType { case .Date: numberOfRows = 1 case .Afflictions: numberOfRows = 5 case .Times: numberOfRows = 2 default: break } return numberOfRows } public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { return UITableViewCell() } } enum EntryInputSectionTypes: Int { case Date = 0 case Afflictions case Times case Medicine case Provision case PollenContamination case NumberOfSections }
mit
8e2f2bb12540240d4593a1c6b1d67260
21.811321
114
0.709677
4.52809
false
false
false
false
pauldardeau/tataille-swift
tataille-swift/CocoaDisplayEngineWindow.swift
1
59439
// // CocoaDisplayEngineWindow.swift // tataille-swift // // Created by Paul Dardeau on 8/1/14. // Copyright (c) 2014 SwampBits. All rights reserved. // BSD license import Foundation import Cocoa import WebKit // Enhancements // ============ // status bar at bottom of window: // [theWindow setContentBorderThickness:24.0 forEdge:NSMinYEdge]; // Don't forget to set autorecalculatesContentBorderThickness to NO // developer.apple.com/releasenotes/Cocoa/AppKit.html class CocoaDisplayEngineWindow: NSObject, DisplayEngineWindow, NSComboBoxDelegate, NSTableViewDataSource, NSTableViewDelegate { var window: NSWindow! var windowView: NSView! var windowId: Int var mapControlIdToControl: Dictionary<Int, NSView> var mapControlToControlId: Dictionary<Int, Int> // <Hash(NSView), Int> var mapGroupControls: Dictionary<String, Array<NSView>> var mapListBoxDataSources: Dictionary<Int, Array<String>> // <Hash(NSView), [String]> var mapListViewDataSources: Dictionary<Int, Array<Array<String>>> // <Hash(NSView), [[String]]> var mapListViewColumns: Dictionary<Int, Array<Int>> // Hash(NSView), Array<Hash(NSTableColumn)> var mapCheckBoxHandlers: Dictionary<Int, CheckBoxHandler> var mapComboBoxHandlers: Dictionary<Int, ComboBoxHandler> var mapListBoxHandlers: Dictionary<Int, ListBoxHandler> var mapListViewHandlers: Dictionary<Int, ListViewHandler> var mapPushButtonHandlers: Dictionary<Int, PushButtonHandler> var mapSliderHandlers: Dictionary<Int, SliderHandler> var mapTabViewHandlers: Dictionary<Int, TabViewHandler> var _translateYValues = true var logger = Logger(logLevel:Logger.LogLevel.Debug) //************************************************************************** init(window: NSWindow, windowId: Int) { self.window = window if let contentView = window.contentView as? NSView { self.windowView = contentView } self.windowId = windowId self.mapControlIdToControl = Dictionary<Int, NSView>() self.mapControlToControlId = Dictionary<Int, Int>() self.mapGroupControls = Dictionary<String, [NSView]>() self.mapListBoxDataSources = Dictionary<Int, [String]>() self.mapListViewDataSources = Dictionary<Int, [[String]]>() self.mapListViewColumns = Dictionary<Int, [Int]>() self.mapCheckBoxHandlers = Dictionary<Int, CheckBoxHandler>() self.mapComboBoxHandlers = Dictionary<Int, ComboBoxHandler>() self.mapListBoxHandlers = Dictionary<Int, ListBoxHandler>() self.mapListViewHandlers = Dictionary<Int, ListViewHandler>() self.mapPushButtonHandlers = Dictionary<Int, PushButtonHandler>() self.mapSliderHandlers = Dictionary<Int, SliderHandler>() self.mapTabViewHandlers = Dictionary<Int, TabViewHandler>() } //************************************************************************** func tableViewSelectionDidChange(notification: NSNotification!) { self.logger.debug("tableViewSelectionDidChange: combo box selection did change") if let aNotification = notification { if let obj: AnyObject = aNotification.object { if let tableView = obj as? NSTableView { if let controlId = self.mapControlToControlId[tableView.hashValue] { let selectedRowIndex = tableView.selectedRow if let listBoxHandler = self.mapListBoxHandlers[controlId] { listBoxHandler.listBoxItemSelected(selectedRowIndex) } else { if let listViewHandler = self.mapListViewHandlers[controlId] { listViewHandler.listViewRowSelected(selectedRowIndex) } else { self.logger.debug("tableViewSelectionDidChange: no handler registered for table view") } } } else { self.logger.error("tableViewSelectionDidChange: unable to find control id for table view") } } else { self.logger.error("tableViewSelectionDidChange: control is not a NSTableView") } } else { self.logger.error("tableViewSelectionDidChange: no object available in notification") } } else { self.logger.error("tableViewSelectionDidChange: no notification object available") } } //************************************************************************** func comboBoxSelectionDidChange(notification: NSNotification!) { self.logger.debug("comboBoxSelectionDidChange: combo box selection did change") if let aNotification = notification { if let obj: AnyObject = aNotification.object { if let comboBox = obj as? NSComboBox { if let controlId = self.mapControlToControlId[comboBox.hashValue] { if let handler = self.mapComboBoxHandlers[controlId] { handler.combBoxItemSelected(comboBox.indexOfSelectedItem) } else { self.logger.debug("comboBoxSelectionDidChange: no handler registered for combobox") } } else { self.logger.error("comboBoxSelectionDidChange: unable to find control id for combo box") } } else { self.logger.error("comboBoxSelectionDidChange: control is not a NSComboBox") } } else { self.logger.error("comboBoxSelectionDidChange: no object available in notification") } } else { self.logger.error("comboBoxSelectionDidChange: no notification object available") } } //************************************************************************** func comboBoxSelectionIsChanging(notification: NSNotification!) { //println("combo box selection is changing") } //************************************************************************** func comboBoxWillDismiss(notification: NSNotification!) { //println("combo box will dismiss") } //************************************************************************** func comboBoxWillPopUp(notification: NSNotification!) { //println("combo box will popup") } //************************************************************************** func setTranslateYValues(translateYValues: Bool) { self._translateYValues = translateYValues } //************************************************************************** func translateYValues() -> Bool { return self._translateYValues } //************************************************************************** func controlsForGroup(groupName: String) -> [NSView]? { return self.mapGroupControls[groupName] } //************************************************************************** func controlFromControlId(controlId: Int) -> NSView? { var control: NSView? if controlId > -1 { control = self.mapControlIdToControl[controlId] } return control } //************************************************************************** func controlFromCid(cid: ControlId) -> NSView? { return self.controlFromControlId(cid.controlId) } //************************************************************************** func valuesFromCi(ci: ControlInfo) -> [String]? { var listValues: [String]? if ci.haveValues() { listValues = ci.getValues(",") } return listValues } //************************************************************************** func populateControl(view: NSView, ci:ControlInfo) { //view.tag = ci.cid.controlId; if let helpCaption = ci.helpCaption { view.toolTip = helpCaption } if !ci.isVisible { view.hidden = !ci.isVisible } if ci.haveForegroundColor() { let fgColor = self.colorFromString(ci.foregroundColor! as NSString) //TODO: set foreground color } if ci.haveBackgroundColor() { let bgColor = self.colorFromString(ci.backgroundColor! as NSString) //TODO: set background color } if !ci.isEnabled || ci.isSelected { if let control = view as? NSControl { if !ci.isEnabled { control.enabled = false } //TODO: if isSelected only applies to checkbox, take it out // of ControlInfo if ci.isSelected { //TODO: } } } self.windowView!.addSubview(view) } //************************************************************************** func registerControl(control: NSView, ci:ControlInfo) { self.mapControlIdToControl[ci.cid.controlId] = control self.mapControlToControlId[control.hashValue] = ci.cid.controlId if let groupName = ci.groupName { var optListControls = self.mapGroupControls[groupName] if optListControls != nil { var listControls = optListControls! listControls.append(control) } else { var listControls = [NSView]() listControls.append(control) self.mapGroupControls[groupName] = listControls } } } //************************************************************************** func numberOfRowsInTableView(aTableView: NSTableView!) -> Int { if let tv = aTableView { // is it a listbox? let hash = tv.hashValue if let listValues = self.mapListBoxDataSources[hash] { return listValues.count } else { if let listViewValues = self.mapListViewDataSources[hash] { return listViewValues.count } else { self.logger.error("numberOfRowsInTableView: no datasource available for listview") return 0 } } } else { self.logger.error("numberOfRowsInTableView: no tableview provided") return 0 } } //************************************************************************** func tableView(aTableView: NSTableView!, objectValueForTableColumn tableColumn: NSTableColumn!, row: Int) -> AnyObject! { //self.logger.debug("tableView objectValueForTableColumn") if let tv = aTableView { let hash = tv.hashValue // is it a listbox? if let listValues = self.mapListBoxDataSources[hash] { return listValues[row] } else { if let listRowValues = self.mapListViewDataSources[hash] { if row < listRowValues.count { //self.logger.debug("non-empty list of values found") let rowValues = listRowValues[row] if !rowValues.isEmpty { if var listColumns = self.mapListViewColumns[hash] { var colIndex = 0 let hashTargetColumn = tableColumn!.hashValue for hashColumn in listColumns { if hashColumn == hashTargetColumn { break } else { ++colIndex } } if colIndex < rowValues.count { return rowValues[colIndex] } else { // log error self.logger.error("objectValueForTableColumn: column index beyond max values index") return "" } } else { // log error self.logger.error("objectValueForTableColumn: no table columns registered for NSTableView") return "" } } else { self.logger.error("objectValueForTableColumn: no column data available") return "" } } else { self.logger.debug("no value available in list") return "xvalue" } } else { self.logger.debug("no data source found") return "" } } } else { self.logger.error("objectValueForTableColumn: aTableView is nil") return "" } } //************************************************************************** func tableView(aTableView: NSTableView!, viewForTableColumn tableColumn: NSTableColumn!, row rowIndex: Int) -> NSView! { //self.logger.debug("tableView viewForTableColumn") var view: NSView! if let tv = aTableView { var tf: NSTextField! var optView: AnyObject! = tv.makeViewWithIdentifier("TVCTF", owner: self) if let aTextField = optView as? NSTextField { tf = aTextField } else { tf = NSTextField(frame:CGRectZero) tf.bezeled = false tf.drawsBackground = false tf.editable = false tf.selectable = false } if let textField = tf { let hash = tv.hashValue // is it a listbox? if let listValues = self.mapListBoxDataSources[hash] { textField.stringValue = listValues[rowIndex] } else { if let listRowValues = self.mapListViewDataSources[hash] { if rowIndex < listRowValues.count { let rowValues = listRowValues[rowIndex] if !rowValues.isEmpty { if var listColumns = self.mapListViewColumns[hash] { var colIndex = 0 let hashTargetColumn = tableColumn!.hashValue for hashColumn in listColumns { if hashColumn == hashTargetColumn { break } else { ++colIndex } } if colIndex < rowValues.count { textField.stringValue = rowValues[colIndex] } else { // log error self.logger.error("viewForTableColumn: column index beyond max values index") } } else { // log error self.logger.error("viewForTableColumn: no table columns registered for NSTableView") } } else { self.logger.error("viewForTableColumn: no column data available") textField.stringValue = "" } } else { self.logger.error("viewForTableColumn: no row data available") textField.stringValue = "" } } else { self.logger.error("viewForTableColumn: no data source for listview") textField.stringValue = "" } } view = tf } else { self.logger.error("viewForTableColumn: view is not a textfield") } } else { self.logger.error("viewForTableColumn: no tableview provided") } return view } //************************************************************************** func isControlInfoValid(ci: ControlInfo) -> Bool { return ci.isValid() } //************************************************************************** func setWindowRect(rect: NSRect) -> Bool { if let theWindow = self.window { theWindow.setFrame(rect, display: true) return true } return false } //************************************************************************** func setWindowSize(windowSize: NSSize) -> Bool { //TODO: return false } //************************************************************************** func setWindowPos(point: NSPoint) -> Bool { //TODO: return false } //************************************************************************** func hideWindow() -> Bool { return self.setWindowVisible(false) } //************************************************************************** func showWindow() -> Bool { return self.setWindowVisible(true) } //************************************************************************** func setWindowVisible(isVisible: Bool) -> Bool { if let theWindow = self.window { if isVisible { theWindow.makeKeyAndOrderFront(self) } else { theWindow.orderOut(self) } return true } return false } //************************************************************************** func setWindowTitle(windowTitle: String) -> Bool { if let theWindow = self.window { theWindow.title = windowTitle return true } return false } //************************************************************************** func closeWindow() -> Bool { if self.window { var theWindow = self.window! theWindow.close() self.window = nil self.windowView = nil return true } return false } //************************************************************************** func translateRectYValues(rect: NSRect) -> NSRect { let windowRect = self.windowView!.frame var translatedRect = NSMakeRect(0, 0, 0, 0) translatedRect.origin.x = rect.origin.x translatedRect.origin.y = windowRect.size.height - rect.origin.y - rect.size.height translatedRect.size.width = rect.size.width translatedRect.size.height = rect.size.height return translatedRect } //************************************************************************** func translateYValues(ci: ControlInfo) -> NSRect { // do we have a parent? if ci.haveParent() { //TODO: implement translation for control with a parent return ci.rect; } else { return self.translateRectYValues(ci.rect) } } //************************************************************************** func rectForCi(ci: ControlInfo) -> NSRect { if self.translateYValues() { return self.translateYValues(ci) } else { return ci.rect } } //************************************************************************** class func hexDigitToInt(hexDigit: NSString) -> Int { let digits: NSString = "0123456789" let rangeDigit = digits.rangeOfString(hexDigit) if rangeDigit.location != NSNotFound { return rangeDigit.location } else { let lowerHexDigit: NSString = hexDigit.lowercaseString let hexDigits: NSString = "abcdef" let rangeHexDigit = hexDigits.rangeOfString(lowerHexDigit) if rangeHexDigit.location != NSNotFound { return 10 + rangeHexDigit.location } else { return -1 } } } //************************************************************************** class func hexStringToInt(hexString: NSString) -> Int { var intValue = 0 let firstDigitValue = CocoaDisplayEngineWindow.hexDigitToInt(hexString.substringToIndex(1)) if firstDigitValue > -1 { intValue = firstDigitValue * 16 let secondDigitValue = CocoaDisplayEngineWindow.hexDigitToInt(hexString.substringWithRange(NSMakeRange(1,1))) if secondDigitValue > -1 { intValue += secondDigitValue } else { intValue = -1 } } else { intValue = -1 } return intValue } //************************************************************************** func colorFromString(colorString: String) -> NSColor { var color = NSColor.blackColor() if colorString.hasPrefix("color:") { let colorName: String = (colorString as NSString).substringFromIndex(6) if colorName == "black" { color = NSColor.blackColor() } else if colorName == "blue" { color = NSColor.blueColor() } else if colorName == "brown" { color = NSColor.brownColor() } else if colorName == "clear" { color = NSColor.clearColor() } else if colorName == "cyan" { color = NSColor.cyanColor() } else if colorName == "darkGray" { color = NSColor.darkGrayColor() } else if colorName == "gray" { color = NSColor.grayColor() } else if colorName == "green" { color = NSColor.greenColor() } else if colorName == "lightGray" { color = NSColor.lightGrayColor() } else if colorName == "magenta" { color = NSColor.magentaColor() } else if colorName == "orange" { color = NSColor.orangeColor() } else if colorName == "purple" { color = NSColor.purpleColor() } else if colorName == "red" { color = NSColor.redColor() } else if colorName == "white" { color = NSColor.whiteColor() } else if colorName == "yellow" { color = NSColor.yellowColor() } else { self.logger.error("colorFromString: unrecognized color value ' \(colorName)'") } } else if colorString.hasPrefix("rgb:") { let colorValues = colorString.componentsSeparatedByString(",") if colorValues.count > 2 { let redIntValue: Int? = colorValues[0].toInt() let greenIntValue: Int? = colorValues[1].toInt() let blueIntValue: Int? = colorValues[2].toInt() if redIntValue != nil && greenIntValue != nil && blueIntValue != nil { //TODO: check that values are between 0-255 let red = redIntValue! let green = greenIntValue! let blue = blueIntValue! if red >= 0 && red <= 255 && green >= 0 && green <= 255 && blue >= 0 && blue <= 255 { let redValue: CGFloat = CGFloat(red) / 255.0 let greenValue: CGFloat = CGFloat(green) / 255.0 let blueValue: CGFloat = CGFloat(blue) / 255.0 color = NSColor(red:redValue, green: greenValue, blue: blueValue, alpha: 1.0) } else { // log error } } else { // log error } } else { // log error } } else if colorString.hasPrefix("hexRGB:") { let colorValues: NSString = (colorString as NSString).substringFromIndex(7) if colorValues.length == 6 { let redString = colorValues.substringToIndex(2) let greenString = colorValues.substringWithRange(NSMakeRange(2,2)) let blueString = colorValues.substringFromIndex(4) let red = CocoaDisplayEngineWindow.hexStringToInt(redString) let green = CocoaDisplayEngineWindow.hexStringToInt(greenString) let blue = CocoaDisplayEngineWindow.hexStringToInt(blueString) if red > -1 && green > -1 && blue > -1 { let redValue: CGFloat = CGFloat(red) / 255.0 let greenValue: CGFloat = CGFloat(green) / 255.0 let blueValue: CGFloat = CGFloat(blue) / 255.0 color = NSColor(red:redValue, green: greenValue, blue: blueValue, alpha: 1.0) } else { // log error } } else { // log error } } else { self.logger.error("colorFromString: unrecognized color value ' \(colorString)'") } return color } //************************************************************************** func checkBoxToggled(obj:NSButton) { self.logger.debug("checkBoxToggled: check box toggled") if let controlId = self.mapControlToControlId[obj.hashValue] { if let handler = self.mapCheckBoxHandlers[controlId] { handler.checkBoxToggled(true) } else { self.logger.debug("checkBoxToggled: no handler registered for checkbox") } } else { self.logger.error("checkBoxToggled: unable to find control id for checkbox") } } //************************************************************************** func createCheckBox(ci: ControlInfo) -> Bool { var controlCreated = false if self.isControlInfoValid(ci) { var checkBox = NSButton(frame:self.rectForCi(ci)) if ci.haveText() { checkBox.title = ci.text } checkBox.setButtonType(NSButtonType.SwitchButton) if (ci.isSelected) { checkBox.state = NSOnState } checkBox.target = self checkBox.action = "checkBoxToggled:" ci.controlType = CocoaDisplayEngine.ControlType.CheckBox; self.populateControl(checkBox, ci:ci) self.registerControl(checkBox, ci:ci) controlCreated = true } return controlCreated } //************************************************************************** func comboBoxSelectionChange(obj: NSComboBox) { } //************************************************************************** func createColorWell(ci: ControlInfo) -> Bool { var controlCreated = false if self.isControlInfoValid(ci) { var colorWell = NSColorWell(frame:self.rectForCi(ci)) if ci.haveValues() { colorWell.color = self.colorFromString(ci.values!) } //TODO: respond to changes in color selection ci.controlType = CocoaDisplayEngine.ControlType.ColorWell self.populateControl(colorWell, ci:ci) self.registerControl(colorWell, ci:ci) controlCreated = true } return controlCreated } //************************************************************************** func createComboBox(ci: ControlInfo) -> Bool { var controlCreated = false if self.isControlInfoValid(ci) { var comboBox = NSComboBox(frame:self.rectForCi(ci)) if ci.haveValues() { var listValues = self.valuesFromCi(ci) comboBox.addItemsWithObjectValues(listValues) comboBox.selectItemAtIndex(0) } comboBox.editable = false comboBox.setDelegate(self) ci.controlType = CocoaDisplayEngine.ControlType.ComboBox self.populateControl(comboBox, ci:ci) self.registerControl(comboBox, ci:ci) controlCreated = true } return controlCreated } //************************************************************************** func createDatePicker(ci: ControlInfo) -> Bool { var controlCreated = false if self.isControlInfoValid(ci) { var datePicker = NSDatePicker(frame:self.rectForCi(ci)) if ci.haveText() { //TODO: //textField.stringValue = ci.text! } ci.controlType = CocoaDisplayEngine.ControlType.DatePicker self.populateControl(datePicker, ci:ci) self.registerControl(datePicker, ci:ci) controlCreated = true } return controlCreated } //************************************************************************** func createEntryField(ci: ControlInfo) -> Bool { var controlCreated = false if self.isControlInfoValid(ci) { var textField = NSTextField(frame:self.rectForCi(ci)) if ci.haveText() { textField.stringValue = ci.text! } ci.controlType = CocoaDisplayEngine.ControlType.EntryField self.populateControl(textField, ci:ci) self.registerControl(textField, ci:ci) controlCreated = true } return controlCreated } //************************************************************************** func createGroupBox(ci: ControlInfo) -> Bool { var controlCreated = false if self.isControlInfoValid(ci) { var box = NSBox(frame:self.rectForCi(ci)) box.borderType = NSBorderType.BezelBorder // GrooveBorder, LineBorder if ci.haveText() { box.title = ci.text! } ci.controlType = CocoaDisplayEngine.ControlType.GroupBox self.populateControl(box, ci:ci) self.registerControl(box, ci:ci) controlCreated = true } return controlCreated } //************************************************************************** func createHtmlBrowser(ci: ControlInfo) -> Bool { var controlCreated = false if self.isControlInfoValid(ci) { var webView = WebView(frame:self.rectForCi(ci)) if ci.haveValues() { let value = ci.values! // does it look like a URL? if value.hasPrefix("http") { let url = NSURL(string:value) let urlRequest = NSURLRequest(URL: url) webView.mainFrame.loadRequest(urlRequest) } else { // treat the value as HTML content and set it in the browser webView.mainFrame.loadHTMLString(value, baseURL: nil) } } ci.controlType = CocoaDisplayEngine.ControlType.HtmlBrowser self.populateControl(webView, ci:ci) self.registerControl(webView, ci:ci) controlCreated = true } return controlCreated } //************************************************************************** func createImageView(ci: ControlInfo) -> Bool { var controlCreated = false if self.isControlInfoValid(ci) { var imageView = NSImageView(frame:self.rectForCi(ci)) if ci.haveValues() { //TODO: // attempt to load image // support local file path and URL } ci.controlType = CocoaDisplayEngine.ControlType.ImageView self.populateControl(imageView, ci:ci) self.registerControl(imageView, ci:ci) controlCreated = true } return controlCreated } //************************************************************************** func createLevelIndicator(ci: ControlInfo) -> Bool { var controlCreated = false if self.isControlInfoValid(ci) { var levelIndicator = NSLevelIndicator(frame:self.rectForCi(ci)) levelIndicator.minValue = 0.0 levelIndicator.maxValue = 0.0 if ci.haveValues() { //TODO: } ci.controlType = CocoaDisplayEngine.ControlType.LevelIndicator self.populateControl(levelIndicator, ci:ci) self.registerControl(levelIndicator, ci:ci) controlCreated = true } return controlCreated } //************************************************************************** func createListBox(ci: ControlInfo) -> Bool { var controlCreated = false if self.isControlInfoValid(ci) { var tableView = NSTableView(frame:self.rectForCi(ci)) var tableColumn = NSTableColumn(identifier:"listColumn") tableView.addTableColumn(tableColumn) let hash = tableView.hashValue if ci.haveValues() { var listValues = self.valuesFromCi(ci)! self.mapListBoxDataSources[hash] = listValues } else { self.mapListBoxDataSources[hash] = Array<String>() } tableView.setDataSource(self) tableView.setDelegate(self) ci.controlType = CocoaDisplayEngine.ControlType.ListBox self.populateControl(tableView, ci:ci) self.registerControl(tableView, ci:ci) controlCreated = true } return controlCreated } //************************************************************************** func createListView(ci: ControlInfo) -> Bool { var controlCreated = false if self.isControlInfoValid(ci) { let viewRect = self.rectForCi(ci) var scrollView = NSScrollView(frame: viewRect) var tableView = NSTableView(frame: viewRect) let hash = tableView.hashValue scrollView.hasVerticalScroller = true scrollView.hasHorizontalScroller = true scrollView.documentView = tableView //scrollView.autoresizesSubviews = true tableView.usesAlternatingRowBackgroundColors = true tableView.columnAutoresizingStyle = NSTableViewColumnAutoresizingStyle.UniformColumnAutoresizingStyle tableView.rowHeight = 17.0 //tableView.autoresizesSubviews = true self.mapListViewDataSources[hash] = Array<Array<String>>() var listColumns = Array<Int>() if ci.haveValues() { var listValues = self.valuesFromCi(ci)! let tableHeaderViewRect = NSMakeRect(0.0, 0.0, NSWidth(ci.rect), 22.0) var tableHeaderView = NSTableHeaderView(frame:tableHeaderViewRect) //tableHeaderView.autoresizesSubviews = true tableView.headerView = tableHeaderView tableView.addSubview(tableHeaderView) for colText in listValues { var tableColumn = NSTableColumn(identifier:colText) let hashTableColumn = tableColumn.hashValue listColumns.append(hashTableColumn) let colIndex = listColumns.count - 1 //println("registering column '\(colText)' at index \(colIndex)") //NSTableCellView //var headerCell = tableColumn.headerCell! //headerCell.setStringValue(colText, resolvingEntities: false) tableView.addTableColumn(tableColumn) } } self.mapListViewColumns[hash] = listColumns tableView.setDataSource(self) tableView.setDelegate(self) tableView.setNeedsDisplay() ci.controlType = CocoaDisplayEngine.ControlType.ListView self.populateControl(tableView, ci:ci) self.registerControl(tableView, ci:ci) controlCreated = true } return controlCreated } //************************************************************************** func createPanel(ci: ControlInfo) -> Bool { var controlCreated = false if self.isControlInfoValid(ci) { var view = NSView(frame:self.rectForCi(ci)) ci.controlType = CocoaDisplayEngine.ControlType.Panel self.populateControl(view, ci:ci) self.registerControl(view, ci:ci) controlCreated = true } return controlCreated } //************************************************************************** func createPasswordField(ci: ControlInfo) -> Bool { var controlCreated = false if self.isControlInfoValid(ci) { var secureTextField = NSSecureTextField(frame:self.rectForCi(ci)) ci.controlType = CocoaDisplayEngine.ControlType.PasswordField self.populateControl(secureTextField, ci:ci) self.registerControl(secureTextField, ci:ci) controlCreated = true } return controlCreated } //************************************************************************** func createProgressBar(ci: ControlInfo) -> Bool { var controlCreated = false if self.isControlInfoValid(ci) { var progressIndicator = NSProgressIndicator(frame:self.rectForCi(ci)) progressIndicator.style = NSProgressIndicatorStyle.BarStyle progressIndicator.indeterminate = false progressIndicator.minValue = 0.0 progressIndicator.maxValue = 0.0 ci.controlType = CocoaDisplayEngine.ControlType.ProgressBar self.populateControl(progressIndicator, ci:ci) self.registerControl(progressIndicator, ci:ci) controlCreated = true } return controlCreated } //************************************************************************** func pushButtonClicked(obj:NSButton) { self.logger.debug("pushButtonClicked: push button clicked") if let controlId = self.mapControlToControlId[obj.hashValue] { if let handler = self.mapPushButtonHandlers[controlId] { handler.pushButtonClicked() } else { self.logger.debug("pushButtonClicked: no handler registered for push button") } } else { self.logger.error("pushButtonClicked: can't map push button to cid") } } //************************************************************************** func createPushButton(ci: ControlInfo) -> Bool { var controlCreated = false if self.isControlInfoValid(ci) { var pushButton = NSButton(frame:self.rectForCi(ci)) if ci.haveText() { pushButton.title = ci.text! } pushButton.bezelStyle = NSBezelStyle.RoundRectBezelStyle pushButton.target = self pushButton.action = "pushButtonClicked:" ci.controlType = CocoaDisplayEngine.ControlType.PushButton self.populateControl(pushButton, ci:ci) self.registerControl(pushButton, ci:ci) controlCreated = true } return controlCreated } //************************************************************************** func createSegmentedControl(ci: ControlInfo) -> Bool { var controlCreated = false if self.isControlInfoValid(ci) { var segmentedControl = NSSegmentedControl(frame:self.rectForCi(ci)) if ci.haveValues() { var listValues = self.valuesFromCi(ci)! segmentedControl.segmentCount = listValues.count var i = 0 for segmentText in listValues { segmentedControl.setLabel(segmentText, forSegment: i) ++i } } // TexturedRounded, RoundedRect, Capsule, SmallSqure let style = NSSegmentStyle.Rounded segmentedControl.segmentStyle = style //segmentedControl.target = self //segmentedControl.action = "pushButtonClicked:" ci.controlType = CocoaDisplayEngine.ControlType.SegmentedControl self.populateControl(segmentedControl, ci:ci) self.registerControl(segmentedControl, ci:ci) controlCreated = true } return controlCreated } //************************************************************************** func createSlider(ci: ControlInfo) -> Bool { var controlCreated = false if self.isControlInfoValid(ci) { var slider = NSSlider(frame:self.rectForCi(ci)) slider.minValue = 0.0 slider.maxValue = 100.0 ci.controlType = CocoaDisplayEngine.ControlType.Slider self.populateControl(slider, ci:ci) self.registerControl(slider, ci:ci) controlCreated = true } return controlCreated } //************************************************************************** func createStaticText(ci: ControlInfo) -> Bool { var controlCreated = false if self.isControlInfoValid(ci) { var textField = NSTextField(frame:self.rectForCi(ci)) if ci.haveText() { textField.stringValue = ci.text! } textField.bezeled = false textField.drawsBackground = false textField.editable = false textField.selectable = false ci.controlType = CocoaDisplayEngine.ControlType.StaticText self.populateControl(textField, ci:ci) self.registerControl(textField, ci:ci) controlCreated = true } return controlCreated } //************************************************************************** func createTabView(ci: ControlInfo) -> Bool { var controlCreated = false if self.isControlInfoValid(ci) { var tabView = NSTabView(frame:self.rectForCi(ci)) if ci.haveValues() { var listValues = self.valuesFromCi(ci)! for value in listValues { var tabViewItem = NSTabViewItem() tabViewItem.label = value tabView.addTabViewItem(tabViewItem) } } ci.controlType = CocoaDisplayEngine.ControlType.TabView self.populateControl(tabView, ci:ci) self.registerControl(tabView, ci:ci) controlCreated = true } return controlCreated } //************************************************************************** func createTextView(ci: ControlInfo) -> Bool { var controlCreated = false if self.isControlInfoValid(ci) { var textView = NSTextView(frame:self.rectForCi(ci)) if ci.haveText() { textView.string = ci.text! } ci.controlType = CocoaDisplayEngine.ControlType.TextView self.populateControl(textView, ci:ci) self.registerControl(textView, ci:ci) controlCreated = true } return controlCreated } //************************************************************************** func createTree(ci: ControlInfo) -> Bool { var controlCreated = false if self.isControlInfoValid(ci) { var outlineView = NSOutlineView(frame:self.rectForCi(ci)) ci.controlType = CocoaDisplayEngine.ControlType.Tree self.populateControl(outlineView, ci:ci) self.registerControl(outlineView, ci:ci) controlCreated = true } return controlCreated } //************************************************************************** func hideControl(cid: ControlId) -> Bool { return self.setVisible(false, cid:cid) } //************************************************************************** func showControl(cid: ControlId) -> Bool { return self.setVisible(true, cid:cid) } //************************************************************************** func hideGroup(groupName: String) -> Bool { return setVisible(false, groupName:groupName) } //************************************************************************** func showGroup(groupName: String) -> Bool { return setVisible(true, groupName:groupName) } //************************************************************************** func setVisible(isVisible: Bool, cid: ControlId) -> Bool { if let view = self.controlFromCid(cid) { view.hidden = !isVisible return true } return false } //************************************************************************** func setVisible(isVisible: Bool, groupName: String) -> Bool { var optGroupControls = self.controlsForGroup(groupName) if optGroupControls != nil { let isHidden = !isVisible for view in optGroupControls! { view.hidden = isHidden } return true } return false } //************************************************************************** func setFocus(cid: ControlId) -> Bool { if let view = self.controlFromCid(cid) { self.window.makeFirstResponder(view) return true } return false } //************************************************************************** func enableControl(cid: ControlId) -> Bool { return setEnabled(true, cid:cid) } //************************************************************************** func disableControl(cid: ControlId) -> Bool { return setEnabled(false, cid:cid) } //************************************************************************** func enableGroup(groupName: String) -> Bool { return self.setEnabled(true, groupName:groupName) } //************************************************************************** func disableGroup(groupName: String) -> Bool { return self.setEnabled(false, groupName:groupName) } //************************************************************************** func setEnabled(isEnabled: Bool, cid: ControlId) -> Bool { if let view = self.controlFromCid(cid) { if let control = view as? NSControl { control.enabled = isEnabled } return true } return false } //************************************************************************** func setEnabled(isEnabled: Bool, groupName: String) -> Bool { if var optGroupControls = self.controlsForGroup(groupName) { for view in optGroupControls { if let control = view as? NSControl { control.enabled = isEnabled } } return true } return false } //************************************************************************** func setSize(controlSize: NSSize, cid: ControlId) -> Bool { if let view = self.controlFromCid(cid) { var frame = view.frame frame.size = controlSize view.frame = frame return true } return false } //************************************************************************** func setPos(point: NSPoint, cid: ControlId) -> Bool { if let view = self.controlFromCid(cid) { var frame = view.frame frame.origin = point view.frame = frame return true } return false } //************************************************************************** func setRect(rect: NSRect, cid: ControlId) -> Bool { if let view = self.controlFromCid(cid) { view.frame = rect return true } return false } //************************************************************************** func showListViewDataSource(ds:[[String]]) { var i = 0 for row in ds { print("row \(i): ") var j = 0 for col in row { if j > 0 { print(",") } print("\(col)") ++j } println("") ++i } if i == 0 { println("<no data>") } } //************************************************************************** func addRow(rowText: String, cid: ControlId) -> Bool { if let view = self.controlFromCid(cid) { if let listView = view as? NSTableView { let hash = listView.hashValue //println("adding row to view: \(hash)") if var ds = self.mapListViewDataSources[hash] { let parsedValues: [String] = rowText.componentsSeparatedByString(",") //let beforeLen = ds.count //println("======== before appending row ==========") //println("len(dataSource) = \(beforeLen)") //self.showListViewDataSource(ds) ds.append(parsedValues) //let afterLen = ds.count //println("-------- after appending row ----------") //println("len(dataSource) = \(afterLen)") //self.showListViewDataSource(ds) // IMPORTANT: swift passes arrays by VALUE, so we have to // update what's stored! self.mapListViewDataSources[hash] = ds listView.reloadData() listView.needsDisplay = true return true } else { self.logger.error("addRow: no data source exists for ListView") } } else { self.logger.error("addRow: control is not a NSTableView") } } else { self.logger.error("addRow: invalid ControlId") } return false } //************************************************************************** func removeRow(rowIndex: Int, cid: ControlId) -> Bool { if let view = self.controlFromCid(cid) { if let listView = view as? NSTableView { let hash = listView.hashValue //println("removing row from view: \(hash)") if var ds = self.mapListViewDataSources[hash] { //let beforeLen = ds.count //println("======== before removing row ==========") //println("len(dataSource) = \(beforeLen)") //self.showListViewDataSource(ds) ds.removeAtIndex(rowIndex) //let afterLen = ds.count //println("-------- after removing row ----------") //println("len(dataSource) = \(afterLen)") //self.showListViewDataSource(ds) // IMPORTANT: swift passes arrays by VALUE, so we have to // update what's stored! self.mapListViewDataSources[hash] = ds listView.reloadData() listView.needsDisplay = true return true } else { self.logger.error("removeRow: no data source exists for ListView") } } else { self.logger.error("removeRow: control is not a NSTableView") } } else { self.logger.error("removeRow: invalid ControlId") } return false } //************************************************************************** func removeAllRows(cid: ControlId) -> Bool { if let view = self.controlFromCid(cid) { if let listView = view as? NSTableView { let hash = listView.hashValue if var ds = self.mapListViewDataSources[hash] { ds.removeAll(keepCapacity: true) // IMPORTANT: swift passes arrays by VALUE, so we have to // update what's stored! self.mapListViewDataSources[hash] = ds listView.reloadData() listView.needsDisplay = true return true } else { self.logger.error("removeAllRows: no data source exists for ListView") } } else { self.logger.error("removeAllRows: control is not a NSTableView") } } else { self.logger.error("removeAllRows: invalid ControlId") } return false } //************************************************************************** func setStaticText(text: NSString, cid: ControlId) -> Bool { if var view = self.controlFromCid(cid) { if var textField = view as? NSTextField { textField.stringValue = text } } return false } //************************************************************************** func setCheckBoxHandler(handler: CheckBoxHandler, cid: ControlId) -> Bool { let controlId = cid.controlId if controlId > -1 { self.mapCheckBoxHandlers[controlId] = handler return true } return false } //************************************************************************** func setComboBoxHandler(handler: ComboBoxHandler, cid: ControlId) -> Bool { let controlId = cid.controlId if controlId > -1 { self.mapComboBoxHandlers[controlId] = handler return true } return false } //************************************************************************** func setListBoxHandler(handler: ListBoxHandler, cid: ControlId) -> Bool { let controlId = cid.controlId if controlId > -1 { self.mapListBoxHandlers[controlId] = handler return true } return false } //************************************************************************** func setListViewHandler(handler: ListViewHandler, cid: ControlId) -> Bool { let controlId = cid.controlId if controlId > -1 { self.mapListViewHandlers[controlId] = handler return true } return false } //************************************************************************** func setPushButtonHandler(handler: PushButtonHandler, cid: ControlId) -> Bool { let controlId = cid.controlId if controlId > -1 { self.mapPushButtonHandlers[controlId] = handler return true } return false } //************************************************************************** func setTabViewHandler(handler: TabViewHandler, cid: ControlId) -> Bool { let controlId = cid.controlId if controlId > -1 { self.mapTabViewHandlers[controlId] = handler return true } return false } //************************************************************************** func setSliderHandler(handler: SliderHandler, cid: ControlId) -> Bool { let controlId = cid.controlId if controlId > -1 { self.mapSliderHandlers[controlId] = handler return true } return false } //************************************************************************** }
bsd-3-clause
4afeccfe1e90396e281789c5fe644251
34.82821
123
0.459328
5.939149
false
false
false
false
pkc456/Roastbook
Roastbook/Roastbook/Model/Mirror Model/MirrorRoot.swift
1
2669
// // MirrorRoot.swift // Roastbook // // Created by Pardeep on 27/04/17. // Copyright © 2017 Programming crew. All rights reserved. // // -- auto-generated by JSON2Swift -- // import Foundation struct MirrorRoot { var content: [MirrorContentItem] var totalPages: Int var sort: Any? var number: Int var size: Int var numberOfElements: Int var totalElements: Int var first: Bool var last: Bool init?(json: [String: Any]?) { guard let json = json else {return nil} content = (json["content"] as? [[String: Any]] ?? []).flatMap{MirrorContentItem(json: $0)} totalPages = json["totalPages"] as? Int ?? 0 sort = json["sort"] number = json["number"] as? Int ?? 0 size = json["size"] as? Int ?? 0 numberOfElements = json["numberOfElements"] as? Int ?? 0 totalElements = json["totalElements"] as? Int ?? 0 first = json["first"] as? Bool ?? false last = json["last"] as? Bool ?? false } init() { self.init(json: [:])! } init?(data: Data?) { guard let data = data else {return nil} guard let json = (try? JSONSerialization.jsonObject(with: data, options: [])) as? [String: Any] else {return nil} self.init(json: json) } init(content: [MirrorContentItem], totalPages: Int, sort: Any?, number: Int, size: Int, numberOfElements: Int, totalElements: Int, first: Bool, last: Bool) { self.content = content self.totalPages = totalPages self.sort = sort self.number = number self.size = size self.numberOfElements = numberOfElements self.totalElements = totalElements self.first = first self.last = last } /// This function generate a json dictionary from the model. /// /// - Parameter useOriginalJsonKey: This parameter take effect only when you have modified a property's name making it different to the original json key. If true, the original json key will be used when generate json dictionary, otherwise, the modified property name will be used as key in the dictionary. func jsonDictionary(useOriginalJsonKey: Bool) -> [String: Any] { var dict: [String: Any] = [:] dict["content"] = content.map{$0.jsonDictionary(useOriginalJsonKey: useOriginalJsonKey)} dict["totalPages"] = totalPages dict["sort"] = sort dict["number"] = number dict["size"] = size dict["numberOfElements"] = numberOfElements dict["totalElements"] = totalElements dict["first"] = first dict["last"] = last return dict } }
mit
ca612621d8372bef93981c846f6931c4
28.318681
310
0.615067
4.194969
false
false
false
false
mohsinalimat/LocationPicker
LocationPicker/Location.swift
2
1402
// // Location.swift // LocationPicker // // Created by Almas Sapargali on 7/29/15. // Copyright (c) 2015 almassapargali. All rights reserved. // import Foundation import CoreLocation import AddressBookUI import Contacts // class because protocol public class Location: NSObject { public let name: String? // difference from placemark location is that if location was reverse geocoded, // then location point to user selected location public let location: CLLocation public let placemark: CLPlacemark public var address: String { // try to build full address first if let addressDic = placemark.addressDictionary, let lines = addressDic["FormattedAddressLines"] as? [String] { return lines.joined(separator: ", ") } if #available(iOS 11.0, *), let postalAddress = placemark.postalAddress { return CNPostalAddressFormatter().string(from: postalAddress) } return "\(coordinate.latitude), \(coordinate.longitude)" } public init(name: String?, location: CLLocation? = nil, placemark: CLPlacemark) { self.name = name self.location = location ?? placemark.location! self.placemark = placemark } } import MapKit extension Location: MKAnnotation { @objc public var coordinate: CLLocationCoordinate2D { return location.coordinate } public var title: String? { return name ?? address } }
mit
7ace2e4251e5e43928085099261ec015
25.961538
119
0.703994
4.27439
false
false
false
false
nerdishbynature/TrashCanKit
TrashCanKit/OAuthConfiguration.swift
1
3183
import Foundation import RequestKit public struct OAuthConfiguration: Configuration { public var apiEndpoint: String public var accessToken: String? public let token: String public let secret: String public let scopes: [String] public let webEndpoint: String public let errorDomain = TrashCanKitErrorDomain public init(_ url: String = bitbucketBaseURL, webURL: String = bitbucketWebURL, token: String, secret: String, scopes: [String]) { apiEndpoint = url webEndpoint = webURL self.token = token self.secret = secret self.scopes = [] } public func authenticate() -> URL? { return OAuthRouter.authorize(self).URLRequest?.url } fileprivate func basicAuthenticationString() -> String { let clientIDSecretString = [token, secret].joined(separator: ":") let clientIDSecretData = clientIDSecretString.data(using: String.Encoding.utf8) let base64 = clientIDSecretData?.base64EncodedString(options: Data.Base64EncodingOptions(rawValue: 0)) return "Basic \(base64 ?? "")" } public func basicAuthConfig() -> URLSessionConfiguration { let config = URLSessionConfiguration.default config.httpAdditionalHeaders = ["Authorization" : basicAuthenticationString()] return config } public func authorize(_ session: RequestKitURLSession, code: String, completion: @escaping (_ config: TokenConfiguration) -> Void) { let request = OAuthRouter.accessToken(self, code).URLRequest if let request = request { let task = session.dataTask(with: request) { data, response, err in if let response = response as? HTTPURLResponse { if response.statusCode != 200 { return } else { if let config = self.configFromData(data) { completion(config) } } } } task.resume() } } private func configFromData(_ data: Data?) -> TokenConfiguration? { guard let data = data else { return nil } do { guard let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: AnyObject] else { return nil } let config = TokenConfiguration(json: json) return config } catch { return nil } } public func handleOpenURL(_ session: RequestKitURLSession = URLSession.shared, url: URL, completion: @escaping (_ config: TokenConfiguration) -> Void) { let params = url.URLParameters() if let code = params["code"] { authorize(session, code: code) { config in completion(config) } } } public func accessTokenFromResponse(_ response: String) -> String? { let accessTokenParam = response.components(separatedBy: "&").first if let accessTokenParam = accessTokenParam { return accessTokenParam.components(separatedBy: "=").last } return nil } }
mit
d6a8375e01335022ae89bb7e86d7e9d5
36.892857
156
0.605718
5.261157
false
true
false
false
devmynd/harbor
Harbor/AppDelegate.swift
1
1598
import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate, StatusMenuDelegate { // // MARK: Dependencies fileprivate lazy var settings: SettingsType = Settings.instance fileprivate lazy var projectsInteractor: ProjectsInteractor = ProjectsProvider.instance fileprivate lazy var timerCoordinator: TimerCoordinatorType = TimerCoordinator.instance // // MARK: Interface Elements @IBOutlet weak var statusItemMenu: StatusMenu! var preferencesWindowController: PreferencesPaneWindowController! // // MARK: NSApplicationDelegate func applicationDidFinishLaunching(_ aNotification: Notification) { if Environment.active == .testing { return } preferencesWindowController = PreferencesPaneWindowController(windowNibName: "PreferencesPaneWindowController") statusItemMenu.statusMenuDelegate = self // run startup logic startup() } // // MARK: Startup fileprivate func startup() { settings.startup() timerCoordinator.startup() refreshProjects() } fileprivate func refreshProjects() { if !settings.apiKey.isEmpty { projectsInteractor.refreshProjects() } else { showPreferencesPane() } } // // MARK: StatusMenuDelegate func statusMenuDidSelectPreferences(_ statusMenu: StatusMenu) { showPreferencesPane() } fileprivate func showPreferencesPane() { preferencesWindowController.window?.center() preferencesWindowController.window?.orderFront(self) // Show your window in front of all other apps NSApp.activate(ignoringOtherApps: true) } }
mit
83d6350e69e431224a62bd77af72aa6e
25.196721
115
0.745932
5.398649
false
false
false
false