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
abaca100/Nest
iOS-NestDK/TimeConditionViewController.swift
1
13526
/* Copyright (C) 2015 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: The `TimeConditionViewController` allows the user to create a new time condition. */ import UIKit import HomeKit /// Represents a section in the `TimeConditionViewController`. enum TimeConditionTableViewSection: Int { /** This section contains the segmented control to choose a time condition type. */ case TimeOrSun /** This section contains cells to allow the selection of 'before', 'after', or 'at'. 'At' is only available when the exact time is specified. */ case BeforeOrAfter /** If the condition type is exact time, this section will only have one cell, the date picker cell. If the condition type is relative to a solar event, this section will have two cells, one for 'sunrise' and one for 'sunset. */ case Value static let count = 3 } /** Represents the type of time condition. The condition can be an exact time, or relative to a solar event. */ enum TimeConditionType: Int { case Time, Sun } /** Represents the type of solar event. This can be sunrise or sunset. */ enum TimeConditionSunState: Int { case Sunrise, Sunset } /** Represents the condition order. Conditions can be before, after, or exactly at a given time. */ enum TimeConditionOrder: Int { case Before, After, At } /// A view controller that facilitates the creation of time conditions for triggers. class TimeConditionViewController: HMCatalogViewController { // MARK: Types struct Identifiers { static let selectionCell = "SelectionCell" static let timePickerCell = "TimePickerCell" static let segmentedTimeCell = "SegmentedTimeCell" } static let timeOrSunTitles = [ NSLocalizedString("Relative to time", comment: "Relative to time"), NSLocalizedString("Relative to sun", comment: "Relative to sun") ] static let beforeOrAfterTitles = [ NSLocalizedString("Before", comment: "Before"), NSLocalizedString("After", comment: "After"), NSLocalizedString("At", comment: "At") ] static let sunriseSunsetTitles = [ NSLocalizedString("Sunrise", comment: "Sunrise"), NSLocalizedString("Sunset", comment: "Sunset") ] // MARK: Properties private var timeType: TimeConditionType = .Time private var order: TimeConditionOrder = .Before private var sunState: TimeConditionSunState = .Sunrise private var datePicker: UIDatePicker? var triggerCreator: EventTriggerCreator? // MARK: View Methods /// Configures the table view. override func viewDidLoad() { super.viewDidLoad() tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 44.0 } // MARK: Table View Methods /// - returns: The number of `TimeConditionTableViewSection`s. override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return TimeConditionTableViewSection.count } /** - returns: The number rows based on the `TimeConditionTableViewSection` and the `timeType`. */ override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch TimeConditionTableViewSection(rawValue: section) { case .TimeOrSun?: return 1 case .BeforeOrAfter?: // If we're choosing an exact time, we add the 'At' row. return (timeType == .Time) ? 3 : 2 case .Value?: // Date picker cell or sunrise/sunset selection cells return (timeType == .Time) ? 1 : 2 case nil: fatalError("Unexpected `TimeConditionTableViewSection` raw value.") } } /// Switches based on the section to generate a cell. override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { switch TimeConditionTableViewSection(rawValue: indexPath.section) { case .TimeOrSun?: return self.tableView(tableView, segmentedCellForRowAtIndexPath: indexPath) case .BeforeOrAfter?: return self.tableView(tableView, selectionCellForRowAtIndexPath: indexPath) case .Value?: switch timeType { case .Time: return self.tableView(tableView, datePickerCellForRowAtIndexPath: indexPath) case .Sun: return self.tableView(tableView, selectionCellForRowAtIndexPath: indexPath) } case nil: fatalError("Unexpected `TimeConditionTableViewSection` raw value.") } } /// - returns: A localized string describing the section. override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { switch TimeConditionTableViewSection(rawValue: section) { case .TimeOrSun?: return NSLocalizedString("Condition Type", comment: "Condition Type") case .BeforeOrAfter?: return nil case .Value?: if timeType == .Time { return NSLocalizedString("Time", comment: "Time") } else { return NSLocalizedString("Event", comment: "Event") } case nil: fatalError("Unexpected `TimeConditionTableViewSection` raw value.") } } /// - returns: A localized description for condition type section; `nil` otherwise. override func tableView(tableView: UITableView, titleForFooterInSection section: Int) -> String? { switch TimeConditionTableViewSection(rawValue: section) { case .TimeOrSun?: return NSLocalizedString("Time conditions can relate to specific times or special events, like sunrise and sunset.", comment: "Condition Type Description") case .BeforeOrAfter?: return nil case .Value?: return nil case nil: fatalError("Unexpected `TimeConditionTableViewSection` raw value.") } } /// Updates internal values based on row selection. override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let cell = tableView.cellForRowAtIndexPath(indexPath)! if cell.selectionStyle == .None { return } tableView.deselectRowAtIndexPath(indexPath, animated: true) switch TimeConditionTableViewSection(rawValue: indexPath.section) { case .TimeOrSun?: timeType = TimeConditionType(rawValue: indexPath.row)! reloadDynamicSections() return case .BeforeOrAfter?: order = TimeConditionOrder(rawValue: indexPath.row)! tableView.reloadSections(NSIndexSet(index: indexPath.section), withRowAnimation: .Automatic) case .Value?: if timeType == .Sun { sunState = TimeConditionSunState(rawValue: indexPath.row)! } tableView.reloadSections(NSIndexSet(index: indexPath.section), withRowAnimation: .Automatic) case nil: fatalError("Unexpected `TimeConditionTableViewSection` raw value.") } } // MARK: Helper Methods /** Generates a selection cell based on the section. Ordering and sun-state sections have selections. */ private func tableView(tableView: UITableView, selectionCellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(Identifiers.selectionCell, forIndexPath: indexPath) switch TimeConditionTableViewSection(rawValue: indexPath.section) { case .BeforeOrAfter?: cell.textLabel?.text = TimeConditionViewController.beforeOrAfterTitles[indexPath.row] cell.accessoryType = (order.rawValue == indexPath.row) ? .Checkmark : .None case .Value?: if timeType == .Sun { cell.textLabel?.text = TimeConditionViewController.sunriseSunsetTitles[indexPath.row] cell.accessoryType = (sunState.rawValue == indexPath.row) ? .Checkmark : .None } case nil: fatalError("Unexpected `TimeConditionTableViewSection` raw value.") default: break } return cell } /// Generates a date picker cell and sets the internal date picker when created. private func tableView(tableView: UITableView, datePickerCellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(Identifiers.timePickerCell, forIndexPath: indexPath) as! TimePickerCell // Save the date picker so we can get the result later. datePicker = cell.datePicker return cell } /// Generates a segmented cell and sets its target when created. private func tableView(tableView: UITableView, segmentedCellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(Identifiers.segmentedTimeCell, forIndexPath: indexPath) as! SegmentedTimeCell cell.segmentedControl.selectedSegmentIndex = timeType.rawValue cell.segmentedControl.removeTarget(nil, action: nil, forControlEvents: .AllEvents) cell.segmentedControl.addTarget(self, action: "segmentedControlDidChange:", forControlEvents: .ValueChanged) return cell } /// Creates date components from the date picker's date. var dateComponents: NSDateComponents? { guard let datePicker = datePicker else { return nil } let flags: NSCalendarUnit = [.Hour, .Minute] return NSCalendar.currentCalendar().components(flags, fromDate: datePicker.date) } /** Updates the time type and reloads dynamic sections. - parameter segmentedControl: The segmented control that changed. */ func segmentedControlDidChange(segmentedControl: UISegmentedControl) { if let segmentedControlType = TimeConditionType(rawValue: segmentedControl.selectedSegmentIndex) { timeType = segmentedControlType } reloadDynamicSections() } /// Reloads the BeforeOrAfter and Value section. private func reloadDynamicSections() { if timeType == .Sun && order == .At { order = .Before } let reloadIndexSet = NSIndexSet(indexesInRange: NSMakeRange(TimeConditionTableViewSection.BeforeOrAfter.rawValue, 2)) tableView.reloadSections(reloadIndexSet, withRowAnimation: .Automatic) } // MARK: IBAction Methods /** Generates a predicate based on the stored values, adds the condition to the trigger, then dismisses the view. */ @IBAction func saveAndDismiss(sender: UIBarButtonItem) { var predicate: NSPredicate? switch timeType { case .Time: switch order { case .Before: predicate = HMEventTrigger.predicateForEvaluatingTriggerOccurringBeforeDateWithComponents(dateComponents!) case .After: predicate = HMEventTrigger.predicateForEvaluatingTriggerOccurringAfterDateWithComponents(dateComponents!) case .At: predicate = HMEventTrigger.predicateForEvaluatingTriggerOccurringOnDateWithComponents(dateComponents!) } case .Sun: let significantEventString = (sunState == .Sunrise) ? HMSignificantEventSunrise : HMSignificantEventSunset switch order { case .Before: predicate = HMEventTrigger.predicateForEvaluatingTriggerOccurringBeforeSignificantEvent(significantEventString, applyingOffset: nil) case .After: predicate = HMEventTrigger.predicateForEvaluatingTriggerOccurringAfterSignificantEvent(significantEventString, applyingOffset: nil) case .At: // Significant events must be specified 'before' or 'after'. break } } if let predicate = predicate { triggerCreator?.addCondition(predicate) } dismissViewControllerAnimated(true, completion: nil) } /// Cancels the creation of the conditions and exits. @IBAction func dismiss(sender: UIBarButtonItem) { dismissViewControllerAnimated(true, completion: nil) } }
apache-2.0
9fc5ffaf1ba19f950c7cacb8fa7989d6
37.642857
171
0.618086
6.075472
false
false
false
false
iWeslie/Ant
Ant/Ant/Me/LoginTableViewCell.swift
2
1631
// // LoginTableViewCell.swift // AntProfileDemo // // Created by Weslie on 2017/7/7. // Copyright © 2017年 Weslie. All rights reserved. // import UIKit class LoginTableViewCell: UITableViewCell { @IBOutlet weak var avaImage: UIImageView! @IBOutlet weak var loginHint: UILabel! @IBOutlet weak var detialHint: UILabel! override func awakeFromNib() { super.awakeFromNib() let profileNumber = UserInfoModel.shareInstance.account?.phoneNumber loginHint.text = profileNumber != nil ? profileNumber : "点击登录账号" detialHint.text = profileNumber != nil ? "查看个人资料" : "登陆享用同步数据等完整功能" //接受通知 NotificationCenter.default.addObserver(self, selector: #selector(didLogin), name: isLoginNotification, object: nil) //登录后点击头像跳转个人界面 // let avatarTap = UITapGestureRecognizer(target: self, action: #selector(loadSelfProfileVC)) // avaImage.addGestureRecognizer(avatarTap) } deinit { NotificationCenter.default.removeObserver(self) } func didLogin() { if isLogin == true { loginHint.text = UserInfoModel.shareInstance.account?.phoneNumber detialHint.text = "查看个人资料" } else { loginHint.text = "点击登录账号" detialHint.text = "登陆享用同步数据等完整功能" } } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } }
apache-2.0
874179efeb4b67e649c974e0888f3bf1
28.88
123
0.638554
4.446429
false
false
false
false
rxwei/dlvm-tensor
Sources/RankedTensor/Rank.swift
2
12134
// // Rank.swift // RankedTensor // // Copyright 2016-2018 The DLVM Team. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import struct CoreTensor.TensorShape import struct CoreTensor.TensorSlice public protocol StaticRank { associatedtype UnitType associatedtype Shape associatedtype ElementTensor associatedtype ArrayLiteralElement static var rank: UInt { get } static func makeTensor(from literal: [ArrayLiteralElement]) -> Tensor<Self> static func element(of tensor: Tensor<Self>, at index: Int) -> ElementTensor static func element(of tensor: TensorSlice<Self>, at index: Int) -> ElementTensor static func updateElement(_ newElement: ElementTensor, at index: Int, in tensor: inout Tensor<Self>) static func updateElement(_ newElement: ElementTensor, at index: Int, in tensor: inout TensorSlice<Self>) } public typealias Shape1D = (UInt) public typealias Shape2D = (UInt, UInt) public typealias Shape3D = (UInt, UInt, UInt) public typealias Shape4D = (UInt, UInt, UInt, UInt) extension StaticRank { static func staticShape(from shape: TensorShape) -> Shape { var elements = shape.map(UInt.init) return withUnsafePointer(to: &elements[0]) { ptr in ptr.withMemoryRebound(to: Shape.self, capacity: 1) { ptr in return ptr.pointee } } } static func dynamicShape(from shape: Shape) -> TensorShape { var shape = shape return withUnsafePointer(to: &shape) { ptr in ptr.withMemoryRebound(to: UInt.self, capacity: 1) { ptr in let buf = UnsafeBufferPointer(start: ptr, count: Int(rank)) return TensorShape(buf.lazy.map {Int($0)}) } } } } public struct Rank1<T> : StaticRank { public typealias UnitType = T public typealias Shape = Shape1D public typealias ElementTensor = T public typealias ArrayLiteralElement = T public static var rank: UInt { return 1 } public static func makeTensor(from literal: [T]) -> Tensor<Rank1<T>> { return Tensor<Rank1<T>>(shape: (UInt(literal.count)), units: ContiguousArray(literal)) } public static func makeTensor(with elements: [T]) -> Tensor<Rank1<T>> { return makeTensor(from: elements) } public static func element(of tensor: Tensor<Rank1<T>>, at index: Int) -> T { return tensor.units[index] } public static func element(of tensor: TensorSlice<Rank1<T>>, at index: Int) -> T { let unitIndex = index.advanced(by: tensor.units.startIndex) return tensor.units[unitIndex] } public static func updateElement(_ newElement: T, at index: Int, in tensor: inout Tensor<Rank1<T>>) { tensor.base[index] = CoreTensor.TensorSlice(scalar: newElement) } public static func updateElement(_ newElement: T, at index: Int, in tensor: inout TensorSlice<Rank1<T>>) { tensor.base[index] = CoreTensor.TensorSlice(scalar: newElement) } } public struct Rank2<T> : StaticRank { public typealias UnitType = T public typealias Shape = Shape2D public typealias ElementTensor = TensorSlice1D<T> public typealias ArrayLiteralElement = [T] public static var rank: UInt { return 2 } public static func makeTensor(from literal: [[T]]) -> Tensor<Rank2<T>> { let dim0 = UInt(literal.count) guard dim0 > 0 else { fatalError("Array literal cannot be empty") } let dim1 = UInt(literal[0].count) guard dim1 > 0 else { fatalError("The 2nd dimension cannot be empty") } let contSize = dim0 * dim1 var units: ContiguousArray<T> = [] units.reserveCapacity(Int(contSize)) for subArray in literal { guard subArray.count == dim1 else { fatalError(""" Element tensors in the 2nd dimension have mismatching shapes """) } units.append(contentsOf: subArray) } return Tensor<Rank2<T>>(shape: (dim0, dim1), units: units) } public static func makeTensor( with elements: [Tensor<Rank1<T>>]) -> Tensor<Rank2<T>> { return makeTensor(from: elements.map { Array($0.units) }) } public static func makeTensor( with elements: [TensorSlice<Rank1<T>>]) -> Tensor<Rank2<T>> { return makeTensor(from: elements.map { Array($0.units) }) } public static func element( of tensor: Tensor<Rank2<T>>, at index: Int) -> TensorSlice<Rank1<T>> { return TensorSlice1D(base: tensor, index: index) } public static func element( of tensor: TensorSlice<Rank2<T>>, at index: Int ) -> TensorSlice<Rank1<T>> { return TensorSlice1D(base: tensor, index: index) } public static func updateElement(_ newElement: TensorSlice<Rank1<T>>, at index: Int, in tensor: inout Tensor<Rank2<T>>) { tensor.base[index] = newElement.base } public static func updateElement(_ newElement: TensorSlice<Rank1<T>>, at index: Int, in tensor: inout TensorSlice<Rank2<T>>) { tensor.base[index] = newElement.base } } public struct Rank3<T> : StaticRank { public typealias UnitType = T public typealias Shape = Shape3D public typealias ElementTensor = TensorSlice2D<T> public typealias ArrayLiteralElement = [[T]] public static var rank: UInt { return 3 } public static func makeTensor(from literal: [[[T]]]) -> Tensor<Rank3<T>> { let dim0 = UInt(literal.count) guard dim0 > 0 else { fatalError("Array literal cannot be empty") } let dim1 = UInt(literal[0].count) guard dim1 > 0 else { fatalError("The 2nd dimension cannot be empty") } let dim2 = UInt(literal[0][0].count) guard dim2 > 0 else { fatalError("The 3rd dimension cannot be empty") } let contSize = dim0 * dim1 * dim2 var units: ContiguousArray<T> = [] units.reserveCapacity(Int(contSize)) for subArray in literal { guard subArray.count == dim1 else { fatalError(""" Element tensors in the 2nd dimension have mismatching shapes """) } for subSubArray in subArray { guard subSubArray.count == dim2 else { fatalError(""" Element tensors in the 3nd dimension have mismatching \ shapes """) } units.append(contentsOf: subSubArray) } } return Tensor<Rank3<T>>(shape: (dim0, dim1, dim2), units: units) } public static func makeTensor( with elements: [Tensor<Rank2<T>>]) -> Tensor<Rank3<T>> { return makeTensor(from: elements.map { $0.map { Array($0.units) } }) } public static func makeTensor( with elements: [TensorSlice<Rank2<T>>]) -> Tensor<Rank3<T>> { return makeTensor(from: elements.map { $0.map { Array($0.units) } }) } public static func element( of tensor: Tensor<Rank3<T>>, at index: Int) -> TensorSlice<Rank2<T>> { return TensorSlice2D(base: tensor, index: index) } public static func element(of tensor: TensorSlice<Rank3<T>>, at index: Int) -> TensorSlice<Rank2<T>> { return TensorSlice2D(base: tensor, index: index) } public static func updateElement( _ newElement: TensorSlice<Rank2<T>>, at index: Int, in tensor: inout Tensor<Rank3<T>> ) { tensor.base[index] = newElement.base } public static func updateElement( _ newElement: TensorSlice<Rank2<T>>, at index: Int, in tensor: inout TensorSlice<Rank3<T>> ) { tensor.base[index] = newElement.base } } public struct Rank4<T> : StaticRank { public typealias UnitType = T public typealias Shape = Shape4D public typealias ElementTensor = TensorSlice3D<T> public typealias ArrayLiteralElement = [[[T]]] public static var rank: UInt { return 4 } public static func makeTensor(from literal: [[[[T]]]]) -> Tensor<Rank4<T>> { let dim0 = UInt(literal.count) guard dim0 > 0 else { fatalError("Array literal cannot be empty") } let dim1 = UInt(literal[0].count) guard dim1 > 0 else { fatalError("The 2nd dimension cannot be empty") } let dim2 = UInt(literal[0][0].count) guard dim2 > 0 else { fatalError("The 3rd dimension cannot be empty") } let dim3 = UInt(literal[0][0][0].count) guard dim3 > 0 else { fatalError("The 3rd dimension cannot be empty") } let contSize = dim0 * dim1 * dim2 * dim3 var units: ContiguousArray<T> = [] units.reserveCapacity(Int(contSize)) for subArray in literal { guard subArray.count == dim1 else { fatalError(""" Element tensors in the 2nd dimension have mismatching shapes """) } for subSubArray in subArray { guard subSubArray.count == dim2 else { fatalError(""" Element tensors in the 3nd dimension have mismatching \ shapes """) } for subSubSubArray in subSubArray { guard subSubSubArray.count == dim3 else { fatalError(""" Element tensors in the 4nd dimension have \ mismatching shapes """) } units.append(contentsOf: subSubSubArray) } } } return Tensor<Rank4<T>>(shape: (dim0, dim1, dim2, dim3), units: units) } public static func makeTensor( with elements: [Tensor<Rank3<T>>]) -> Tensor<Rank4<T>> { return makeTensor(from: elements.map { $0.map { $0.map { Array($0.units) } } }) } public static func makeTensor( with elements: [TensorSlice<Rank3<T>>]) -> Tensor<Rank4<T>> { return makeTensor(from: elements.map { $0.map { $0.map { Array($0.units) } } }) } public static func element(of tensor: Tensor<Rank4<T>>, at index: Int) -> TensorSlice<Rank3<T>> { return TensorSlice3D(base: tensor, index: index) } public static func element(of tensor: TensorSlice<Rank4<T>>, at index: Int) -> TensorSlice<Rank3<T>> { return TensorSlice3D(base: tensor, index: index) } public static func updateElement( _ newElement: TensorSlice<Rank3<T>>, at index: Int, in tensor: inout Tensor<Rank4<T>> ) { tensor.base[index] = newElement.base } public static func updateElement( _ newElement: TensorSlice<Rank3<T>>, at index: Int, in tensor: inout TensorSlice<Rank4<T>> ) { tensor.base[index] = newElement.base } }
apache-2.0
eae2d836d42ee7ee68744915e4ea0deb
35.113095
80
0.575655
4.482453
false
false
false
false
SoneeJohn/WWDC
WWDC/VideoPlayerWindowController.swift
1
7028
// // VideoPlayerWindowController.swift // WWDC // // Created by Guilherme Rambo on 04/06/16. // Copyright © 2016 Guilherme Rambo. All rights reserved. // import Cocoa import PlayerUI public enum PUIPlayerWindowSizePreset: CGFloat { case quarter = 0.25 case half = 0.50 case max = 1.0 } final class VideoPlayerWindowController: NSWindowController, NSWindowDelegate { fileprivate let fullscreenOnly: Bool fileprivate let originalContainer: NSView! var actionOnWindowClosed = {} init(playerViewController: VideoPlayerViewController, fullscreenOnly: Bool = false, originalContainer: NSView? = nil) { self.fullscreenOnly = fullscreenOnly self.originalContainer = originalContainer let styleMask: NSWindow.StyleMask = [NSWindow.StyleMask.titled, NSWindow.StyleMask.closable, NSWindow.StyleMask.miniaturizable, NSWindow.StyleMask.resizable, NSWindow.StyleMask.fullSizeContentView] var rect = PUIPlayerWindow.bestScreenRectFromDetachingContainer(playerViewController.view.superview) if rect == NSZeroRect { rect = PUIPlayerWindow.centerRectForProposedContentRect(playerViewController.view.bounds) } let window = PUIPlayerWindow(contentRect: rect, styleMask: styleMask, backing: .buffered, defer: false) window.isReleasedWhenClosed = true if #available(OSX 10.11, *) { // ¯\_(ツ)_/¯ } else { window.collectionBehavior = NSWindow.CollectionBehavior.fullScreenPrimary } super.init(window: window) window.delegate = self contentViewController = playerViewController window.title = playerViewController.title ?? "" if let aspect = playerViewController.player.currentItem?.presentationSize, aspect != NSZeroSize { window.aspectRatio = aspect } } required public init?(coder: NSCoder) { fatalError("VideoPlayerWindowController can't be initialized with a coder") } override func showWindow(_ sender: Any?) { super.showWindow(sender) if !fullscreenOnly { (window as! PUIPlayerWindow).applySizePreset(.half) } else { window?.toggleFullScreen(sender) } } // MARK: - Reattachment and fullscreen support func windowWillClose(_ notification: Notification) { (contentViewController as? VideoPlayerViewController)?.player.cancelPendingPrerolls() (contentViewController as? VideoPlayerViewController)?.player.pause() actionOnWindowClosed() guard fullscreenOnly && contentViewController is VideoPlayerViewController else { return } reattachContentViewController() } func windowWillExitFullScreen(_ notification: Notification) { guard fullscreenOnly && contentViewController is VideoPlayerViewController else { return } window?.resizeIncrements = NSSize(width: 1.0, height: 1.0) } func windowDidExitFullScreen(_ notification: Notification) { guard fullscreenOnly && contentViewController is VideoPlayerViewController else { return } reattachContentViewController() } fileprivate func reattachContentViewController() { contentViewController!.view.frame = originalContainer.bounds originalContainer.addSubview(contentViewController!.view) originalContainer.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "|-(0)-[playerView]-(0)-|", options: [], metrics: nil, views: ["playerView": contentViewController!.view])) originalContainer.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-(0)-[playerView]-(0)-|", options: [], metrics: nil, views: ["playerView": contentViewController!.view])) contentViewController = nil close() } func customWindowsToExitFullScreen(for window: NSWindow) -> [NSWindow]? { guard fullscreenOnly else { return nil } return [window] } func window(_ window: NSWindow, startCustomAnimationToExitFullScreenWithDuration duration: TimeInterval) { NSAnimationContext.runAnimationGroup({ ctx in ctx.duration = duration let frame = PUIPlayerWindow.bestScreenRectFromDetachingContainer(originalContainer) window.animator().setFrame(frame, display: false) }, completionHandler: nil) } @IBAction func sizeWindowToHalfSize(_ sender: AnyObject?) { (window as! PUIPlayerWindow).applySizePreset(.half) } @IBAction func sizeWindowToQuarterSize(_ sender: AnyObject?) { (window as! PUIPlayerWindow).applySizePreset(.quarter) } @IBAction func sizeWindowToFill(_ sender: AnyObject?) { (window as! PUIPlayerWindow).applySizePreset(.max) } @IBAction func floatOnTop(_ sender: NSMenuItem) { if sender.state == .on { toggleFloatOnTop(false) sender.state = .off } else { toggleFloatOnTop(true) sender.state = .on } } fileprivate func toggleFloatOnTop(_ enable: Bool) { let level = enable ? Int(CGWindowLevelForKey(CGWindowLevelKey.floatingWindow)) : Int(CGWindowLevelForKey(CGWindowLevelKey.normalWindow)) window?.level = NSWindow.Level(rawValue: level) } deinit { #if DEBUG Swift.print("VideoPlayerWindowController is gone") #endif } } private extension PUIPlayerWindow { class func centerRectForProposedContentRect(_ rect: NSRect) -> NSRect { guard let screen = NSScreen.main else { return NSZeroRect } return NSRect(x: screen.frame.width / 2.0 - rect.width / 2.0, y: screen.frame.height / 2.0 - rect.height / 2.0, width: rect.width, height: rect.height) } class func bestScreenRectFromDetachingContainer(_ containerView: NSView?) -> NSRect { guard let view = containerView, let superview = view.superview else { return NSZeroRect } return view.window?.convertToScreen(superview.convert(view.frame, to: nil)) ?? NSZeroRect } func applySizePreset(_ preset: PUIPlayerWindowSizePreset, center: Bool = true, animated: Bool = true) { guard let screen = screen else { return } let proportion = frame.size.width / screen.visibleFrame.size.width let idealSize: NSSize if proportion != preset.rawValue { let rect = NSRect(origin: CGPoint.zero, size: NSSize(width: screen.frame.size.width * preset.rawValue, height: screen.frame.size.height * preset.rawValue)) idealSize = constrainFrameRect(rect, to: screen).size } else { idealSize = constrainFrameRect(frame, to: screen).size } let origin: NSPoint if center { origin = NSPoint(x: screen.frame.width / 2.0 - idealSize.width / 2.0, y: screen.frame.height / 2.0 - idealSize.height / 2.0) } else { origin = frame.origin } setFrame(NSRect(origin: origin, size: idealSize), display: true, animate: animated) } }
bsd-2-clause
ba817f557095823c9952025e45f256fb
35.388601
205
0.682614
5.041637
false
false
false
false
vgorloff/AUHost
Vendor/mc/mcxUIExtensions/Sources/AppKit/NSControl.swift
1
1563
// // NSControl.swift // MCA-OSS-VSTNS;MCA-OSS-AUH // // Created by Vlad Gorlov on 06.06.2020. // Copyright © 2020 Vlad Gorlov. All rights reserved. // #if canImport(AppKit) && !targetEnvironment(macCatalyst) import AppKit import mcxTypes extension NSControl { // Stub for iOS public func setEditingChangedHandler(_ handler: (() -> Void)?) { setHandler(handler) } public func setHandler(_ handler: (() -> Void)?) { target = self action = #selector(appActionHandler(_:)) if let handler = handler { ObjCAssociation.setCopyNonAtomic(value: handler, to: self, forKey: &OBJCAssociationKeys.actionHandler) } } public func setHandler<T: AnyObject>(_ caller: T, _ handler: @escaping (T) -> Void) { setHandler { [weak caller] in guard let caller = caller else { return } handler(caller) } } } extension NSControl { private enum OBJCAssociationKeys { static var actionHandler = "app.ui.actionHandler" } @objc private func appActionHandler(_ sender: NSControl) { guard sender == self else { return } if let handler: (() -> Void) = ObjCAssociation.value(from: self, forKey: &OBJCAssociationKeys.actionHandler) { handler() } } } extension Array where Element == NSControl { public func enable() { forEach { $0.isEnabled = true } } public func disable() { forEach { $0.isEnabled = false } } public func setEnabled(_ isEnabled: Bool) { forEach { $0.isEnabled = isEnabled } } } #endif
mit
0bc732ff7238f619db034b7f2c8c5229
23.030769
116
0.631242
4.057143
false
false
false
false
tzhenghao/Psychologist
Psychologist/EmotionViewController.swift
1
1605
// // EmotionViewController.swift // Emotions // // Created by Zheng Hao Tan on 6/20/15. // Copyright (c) 2015 Zheng Hao Tan. All rights reserved. // import UIKit class EmotionViewController: UIViewController, FaceViewDataSource { private struct Constants { static let HappinessGestureScale: CGFloat = 4 } @IBAction func changeHappiness(gesture: UIPanGestureRecognizer) { switch gesture.state { case .Ended: fallthrough case .Changed: let translation = gesture.translationInView(faceView) let happinessChange = Int(translation.y/Constants.HappinessGestureScale) if happinessChange != 0 { happiness += happinessChange gesture.setTranslation(CGPointZero, inView: faceView) } default: break } } @IBOutlet weak var faceView: FaceView! { didSet { faceView.dataSource = self faceView.addGestureRecognizer(UIPinchGestureRecognizer(target: faceView, action: "scale:")) } } var happiness : Int = 75 { // 0 = very sad, 100 = happiest didSet { // Bound it to have range between 0 and 100 happiness = min(max(happiness, 0), 100) println("happiness = \(happiness)") updateUI(); } } func updateUI() { faceView?.setNeedsDisplay() title = "\(happiness)" } func smilinessForFaceView(sender: FaceView) -> Double? { return Double(happiness-50)/50 // Convert from 0 to 100 scale -> -1 to 1 range. } }
mit
263b79cfe442d980eacbf9d4ad01c710
28.181818
103
0.603115
4.938462
false
false
false
false
saidmarouf/SMZoomTransition
Example/SMNavigationController.swift
1
3302
// // SMNavigationController.swift // ZoomTransition // // Created by Said Marouf on 8/13/15. // Copyright © 2015 Said Marouf. All rights reserved. // import Foundation import UIKit /// Naivgation controller which uses the SMZoomNavigationTransition. /// Also combines that with a UIPercentDrivenInteractiveTransition interactive transition. class SMNavigationController: UINavigationController, UINavigationControllerDelegate { private var percentDrivenInteraction: UIPercentDrivenInteractiveTransition? private var edgeGestureRecognizer: UIScreenEdgePanGestureRecognizer! override init(rootViewController: UIViewController) { super.init(rootViewController: rootViewController) commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } func commonInit() { self.delegate = self } override func viewDidLoad() { super.viewDidLoad() //self.view.backgroundColor = UIColor.whiteColor() edgeGestureRecognizer = UIScreenEdgePanGestureRecognizer(target: self, action: "handleScreenEdgePan:") edgeGestureRecognizer.edges = UIRectEdge.Left view.addGestureRecognizer(edgeGestureRecognizer) } func handleScreenEdgePan(gestureRecognizer: UIScreenEdgePanGestureRecognizer) { if let vc = topViewController { let location = gestureRecognizer.translationInView(vc.view) let percentage = location.x / CGRectGetWidth(vc.view.bounds) let velocity_x = gestureRecognizer.velocityInView(vc.view).x switch gestureRecognizer.state { case .Began: popViewControllerAnimated(true) case .Changed: percentDrivenInteraction?.updateInteractiveTransition(percentage) case .Ended: if percentage > 0.3 || velocity_x > 1000 { percentDrivenInteraction?.finishInteractiveTransition() } else { percentDrivenInteraction?.cancelInteractiveTransition() } case .Cancelled: percentDrivenInteraction?.cancelInteractiveTransition() default: break } } } // MARK: - UINavigationControllerDelegate func navigationController(navigationController: UINavigationController, animationControllerForOperation operation: UINavigationControllerOperation, fromViewController fromVC: UIViewController, toViewController toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? { return SMZoomNavigationAnimator(navigationOperation: operation) } func navigationController(navigationController: UINavigationController, interactionControllerForAnimationController animationController: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { if edgeGestureRecognizer.state == .Began { percentDrivenInteraction = UIPercentDrivenInteractiveTransition() percentDrivenInteraction!.completionCurve = .EaseOut } else { percentDrivenInteraction = nil } return percentDrivenInteraction } }
mit
04bd12addc344ff3d003e14d577f638e
35.677778
281
0.689791
6.934874
false
false
false
false
raulriera/TextFieldEffects
TextFieldEffects/TextFieldEffects/AkiraTextField.swift
1
4486
// // AkiraTextField.swift // TextFieldEffects // // Created by Mihaela Miches on 5/31/15. // Copyright (c) 2015 Raul Riera. All rights reserved. // import UIKit /** An AkiraTextField is a subclass of the TextFieldEffects object, is a control that displays an UITextField with a customizable visual effect around the edges of the control. */ @IBDesignable open class AkiraTextField : TextFieldEffects { private let borderSize: (active: CGFloat, inactive: CGFloat) = (1, 2) private let borderLayer = CALayer() private let textFieldInsets = CGPoint(x: 6, y: 0) private let placeholderInsets = CGPoint(x: 6, y: 0) /** The color of the border. This property applies a color to the bounds of the control. The default value for this property is a clear color. */ @IBInspectable dynamic open var borderColor: UIColor? { didSet { updateBorder() } } /** The color of the placeholder text. This property applies a color to the complete placeholder string. The default value for this property is a black color. */ @IBInspectable dynamic open var placeholderColor: UIColor = .black { didSet { updatePlaceholder() } } /** The scale of the placeholder font. This property determines the size of the placeholder label relative to the font size of the text field. */ @IBInspectable dynamic open var placeholderFontScale: CGFloat = 0.7 { didSet { updatePlaceholder() } } override open var placeholder: String? { didSet { updatePlaceholder() } } override open var bounds: CGRect { didSet { updateBorder() } } // MARK: TextFieldEffects override open func drawViewsForRect(_ rect: CGRect) { updateBorder() updatePlaceholder() addSubview(placeholderLabel) layer.addSublayer(borderLayer) } override open func animateViewsForTextEntry() { UIView.animate(withDuration: 0.3, animations: { self.updateBorder() self.updatePlaceholder() }, completion: { _ in self.animationCompletionHandler?(.textEntry) }) } override open func animateViewsForTextDisplay() { UIView.animate(withDuration: 0.3, animations: { self.updateBorder() self.updatePlaceholder() }, completion: { _ in self.animationCompletionHandler?(.textDisplay) }) } // MARK: Private private func updatePlaceholder() { placeholderLabel.frame = placeholderRect(forBounds: bounds) placeholderLabel.text = placeholder placeholderLabel.font = placeholderFontFromFont(font!) placeholderLabel.textColor = placeholderColor placeholderLabel.textAlignment = textAlignment } private func updateBorder() { borderLayer.frame = rectForBounds(bounds) borderLayer.borderWidth = (isFirstResponder || text!.isNotEmpty) ? borderSize.active : borderSize.inactive borderLayer.borderColor = borderColor?.cgColor } private func placeholderFontFromFont(_ font: UIFont) -> UIFont! { let smallerFont = UIFont(descriptor: font.fontDescriptor, size: font.pointSize * placeholderFontScale) return smallerFont } private var placeholderHeight : CGFloat { return placeholderInsets.y + placeholderFontFromFont(font!).lineHeight } private func rectForBounds(_ bounds: CGRect) -> CGRect { return CGRect(x: bounds.origin.x, y: bounds.origin.y + placeholderHeight, width: bounds.size.width, height: bounds.size.height - placeholderHeight) } // MARK: - Overrides open override func placeholderRect(forBounds bounds: CGRect) -> CGRect { if isFirstResponder || text!.isNotEmpty { return CGRect(x: placeholderInsets.x, y: placeholderInsets.y, width: bounds.width, height: placeholderHeight) } else { return textRect(forBounds: bounds) } } open override func editingRect(forBounds bounds: CGRect) -> CGRect { return textRect(forBounds: bounds) } override open func textRect(forBounds bounds: CGRect) -> CGRect { return bounds.offsetBy(dx: textFieldInsets.x, dy: textFieldInsets.y + placeholderHeight/2) } }
mit
05b1565b78789bbdc09635f6041f8dd9
31.042857
173
0.642443
5.277647
false
false
false
false
lady12/firefox-ios
Extensions/ShareTo/ShareViewController.swift
7
11135
/* 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 UIKit import Storage struct ShareDestination { let code: String let name: String let image: String } // TODO: See if we can do this with an Enum instead. Previous attempts failed because for example NSSet does not take (string) enum values. let ShareDestinationBookmarks: String = "Bookmarks" let ShareDestinationReadingList: String = "ReadingList" let ShareDestinations = [ ShareDestination(code: ShareDestinationReadingList, name: NSLocalizedString("Add to Reading List", tableName: "ShareTo", comment: "On/off toggle to select adding this url to your reading list"), image: "AddToReadingList"), ShareDestination(code: ShareDestinationBookmarks, name: NSLocalizedString("Add to Bookmarks", tableName: "ShareTo", comment: "On/off toggle to select adding this url to your bookmarks"), image: "AddToBookmarks") ] protocol ShareControllerDelegate { func shareControllerDidCancel(shareController: ShareDialogController) -> Void func shareController(shareController: ShareDialogController, didShareItem item: ShareItem, toDestinations destinations: NSSet) -> Void } private struct ShareDialogControllerUX { static let CornerRadius: CGFloat = 4 // Corner radius of the dialog static let NavigationBarTintColor = UIColor(rgb: 0xf37c00) // Tint color changes the text color in the navigation bar static let NavigationBarCancelButtonFont = UIFont.systemFontOfSize(UIFont.buttonFontSize()) // System default static let NavigationBarAddButtonFont = UIFont.boldSystemFontOfSize(UIFont.buttonFontSize()) // System default static let NavigationBarIconSize = 38 // Width and height of the icon static let NavigationBarBottomPadding = 12 @available(iOSApplicationExtension 8.2, *) static let ItemTitleFontMedium = UIFont.systemFontOfSize(15, weight: UIFontWeightMedium) static let ItemTitleFont = UIFont.systemFontOfSize(15) static let ItemTitleMaxNumberOfLines = 2 static let ItemTitleLeftPadding = 44 static let ItemTitleRightPadding = 44 static let ItemTitleBottomPadding = 12 static let ItemLinkFont = UIFont.systemFontOfSize(12) static let ItemLinkMaxNumberOfLines = 3 static let ItemLinkLeftPadding = 44 static let ItemLinkRightPadding = 44 static let ItemLinkBottomPadding = 14 static let DividerColor = UIColor.lightGrayColor() // Divider between the item and the table with destinations static let DividerHeight = 0.5 static let TableRowHeight: CGFloat = 44 // System default static let TableRowFont = UIFont.systemFontOfSize(UIFont.labelFontSize()) static let TableRowTintColor = UIColor(red:0.427, green:0.800, blue:0.102, alpha:1.0) // Green tint for the checkmark static let TableRowTextColor = UIColor(rgb: 0x555555) static let TableHeight = 88 // Height of 2 standard 44px cells } class ShareDialogController: UIViewController, UITableViewDataSource, UITableViewDelegate { var delegate: ShareControllerDelegate! var item: ShareItem! var initialShareDestinations: NSSet = NSSet(object: ShareDestinationBookmarks) var selectedShareDestinations: NSMutableSet = NSMutableSet() var navBar: UINavigationBar! var navItem: UINavigationItem! override func viewDidLoad() { super.viewDidLoad() selectedShareDestinations = NSMutableSet(set: initialShareDestinations) self.view.backgroundColor = UIColor.whiteColor() self.view.layer.cornerRadius = ShareDialogControllerUX.CornerRadius self.view.clipsToBounds = true // Setup the NavigationBar navBar = UINavigationBar() navBar.translatesAutoresizingMaskIntoConstraints = false navBar.tintColor = ShareDialogControllerUX.NavigationBarTintColor navBar.translucent = false self.view.addSubview(navBar) // Setup the NavigationItem navItem = UINavigationItem() navItem.leftBarButtonItem = UIBarButtonItem(title: NSLocalizedString("Cancel", comment: "Cancel button title in share dialog"), style: .Plain, target: self, action: "cancel") navItem.leftBarButtonItem?.setTitleTextAttributes([NSFontAttributeName: ShareDialogControllerUX.NavigationBarCancelButtonFont], forState: UIControlState.Normal) navItem.rightBarButtonItem = UIBarButtonItem(title: NSLocalizedString("Add", tableName: "ShareTo", comment: "Add button in the share dialog"), style: UIBarButtonItemStyle.Done, target: self, action: "add") navItem.rightBarButtonItem?.setTitleTextAttributes([NSFontAttributeName: ShareDialogControllerUX.NavigationBarAddButtonFont], forState: UIControlState.Normal) let logo = UIImageView(frame: CGRect(x: 0, y: 0, width: ShareDialogControllerUX.NavigationBarIconSize, height: ShareDialogControllerUX.NavigationBarIconSize)) logo.image = UIImage(named: "Icon-Small") logo.contentMode = UIViewContentMode.ScaleAspectFit // TODO Can go away if icon is provided in correct size navItem.titleView = logo navBar.pushNavigationItem(navItem, animated: false) // Setup the title view let titleView = UILabel() titleView.translatesAutoresizingMaskIntoConstraints = false titleView.numberOfLines = ShareDialogControllerUX.ItemTitleMaxNumberOfLines titleView.lineBreakMode = NSLineBreakMode.ByTruncatingTail titleView.text = item.title if #available(iOSApplicationExtension 8.2, *) { titleView.font = ShareDialogControllerUX.ItemTitleFontMedium } else { // Fallback on earlier versions titleView.font = ShareDialogControllerUX.ItemTitleFont } view.addSubview(titleView) // Setup the link view let linkView = UILabel() linkView.translatesAutoresizingMaskIntoConstraints = false linkView.numberOfLines = ShareDialogControllerUX.ItemLinkMaxNumberOfLines linkView.lineBreakMode = NSLineBreakMode.ByTruncatingTail linkView.text = item.url linkView.font = ShareDialogControllerUX.ItemLinkFont view.addSubview(linkView) // Setup the icon let iconView = UIImageView() iconView.translatesAutoresizingMaskIntoConstraints = false iconView.image = UIImage(named: "defaultFavicon") view.addSubview(iconView) // Setup the divider let dividerView = UIView() dividerView.translatesAutoresizingMaskIntoConstraints = false dividerView.backgroundColor = ShareDialogControllerUX.DividerColor view.addSubview(dividerView) // Setup the table with destinations let tableView = UITableView() tableView.translatesAutoresizingMaskIntoConstraints = false tableView.separatorInset = UIEdgeInsetsZero tableView.layoutMargins = UIEdgeInsetsZero tableView.userInteractionEnabled = true tableView.delegate = self tableView.allowsSelection = true tableView.dataSource = self tableView.scrollEnabled = false view.addSubview(tableView) // Setup constraints let views = [ "nav": navBar, "title": titleView, "link": linkView, "icon": iconView, "divider": dividerView, "table": tableView ] // TODO See Bug 1102516 - Use Snappy to define share extension layout constraints let constraints = [ "H:|[nav]|", "V:|[nav]", "H:|-\(ShareDialogControllerUX.ItemTitleLeftPadding)-[title]-\(ShareDialogControllerUX.ItemTitleRightPadding)-|", "V:[nav]-\(ShareDialogControllerUX.NavigationBarBottomPadding)-[title]", "H:|-\(ShareDialogControllerUX.ItemLinkLeftPadding)-[link]-\(ShareDialogControllerUX.ItemLinkLeftPadding)-|", "V:[title]-\(ShareDialogControllerUX.ItemTitleBottomPadding)-[link]", "H:|[divider]|", "V:[divider(\(ShareDialogControllerUX.DividerHeight))]", "V:[link]-\(ShareDialogControllerUX.ItemLinkBottomPadding)-[divider]", "H:|[table]|", "V:[divider][table]", "V:[table(\(ShareDialogControllerUX.TableHeight))]|" ] for constraint in constraints { view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(constraint, options: NSLayoutFormatOptions(), metrics: nil, views: views)) } } // UITabBarItem Actions that map to our delegate methods func cancel() { delegate?.shareControllerDidCancel(self) } func add() { delegate?.shareController(self, didShareItem: item, toDestinations: NSSet(set: selectedShareDestinations)) } // UITableView Delegate and DataSource func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return ShareDestinations.count } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return ShareDialogControllerUX.TableRowHeight } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = UITableViewCell() cell.textLabel?.textColor = UIAccessibilityDarkerSystemColorsEnabled() ? UIColor.darkGrayColor() : ShareDialogControllerUX.TableRowTextColor cell.textLabel?.font = ShareDialogControllerUX.TableRowFont cell.accessoryType = selectedShareDestinations.containsObject(ShareDestinations[indexPath.row].code) ? UITableViewCellAccessoryType.Checkmark : UITableViewCellAccessoryType.None cell.tintColor = ShareDialogControllerUX.TableRowTintColor cell.layoutMargins = UIEdgeInsetsZero cell.textLabel?.text = ShareDestinations[indexPath.row].name cell.imageView?.image = UIImage(named: ShareDestinations[indexPath.row].image) return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: false) let code = ShareDestinations[indexPath.row].code if selectedShareDestinations.containsObject(code) { selectedShareDestinations.removeObject(code) } else { selectedShareDestinations.addObject(code) } tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic) navItem.rightBarButtonItem?.enabled = (selectedShareDestinations.count != 0) } }
mpl-2.0
43f5e03d240f7455f0b2bc27d5bae6bf
45.012397
226
0.700494
6.015667
false
false
false
false
nathanlea/CS4153MobileAppDev
WIA/WIA9_Lea_Nathan/WIA9_Lea_Nathan/AppDelegate.swift
1
6105
// // AppDelegate.swift // WIA9_Lea_Nathan // // Created by Nathan on 10/19/15. // Copyright © 2015 Okstate. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "CS4153AppDev.WIA9_Lea_Nathan" 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("WIA9_Lea_Nathan", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
mit
63f1b7c678e31eb1c071fc6d8df98bfd
53.990991
291
0.719528
5.813333
false
false
false
false
haskellswift/swift-package-manager
Sources/Basic/StringConversions.swift
2
2530
/* This source file is part of the Swift.org open source project Copyright 2015 - 2016 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ /// Check if the given code unit needs shell escaping. // /// - Parameters: /// - codeUnit: The code unit to be checked. /// /// - Returns: True if shell escaping is not needed. private func inShellWhitelist(_ codeUnit: UInt8) -> Bool { switch codeUnit { case UInt8(ascii: "a")...UInt8(ascii: "z"), UInt8(ascii: "A")...UInt8(ascii: "Z"), UInt8(ascii: "0")...UInt8(ascii: "9"), UInt8(ascii: "-"), UInt8(ascii: "_"), UInt8(ascii: "/"), UInt8(ascii: ":"), UInt8(ascii: "@"), UInt8(ascii: "%"), UInt8(ascii: "+"), UInt8(ascii: "="), UInt8(ascii: "."), UInt8(ascii: ","): return true default: return false } } public extension String { /// Creates a shell escaped string. If the string does not need escaping, returns the original string. /// Otherwise escapes using single quotes. For eg: hello -> hello, hello$world -> 'hello$world', input A -> 'input A' /// /// - Returns: Shell escaped string. public func shellEscaped() -> String { // If all the characters in the string are in whitelist then no need to escape. guard let pos = utf8.index(where: { !inShellWhitelist($0) }) else { return self } // If there are no single quotes then we can just wrap the string around single quotes. guard let singleQuotePos = utf8[pos..<utf8.endIndex].index(of: UInt8(ascii: "'")) else { return "'" + self + "'" } // Otherwise iterate and escape all the single quotes. var newString = "'" + String(utf8[utf8.startIndex..<singleQuotePos])! for char in utf8[singleQuotePos..<utf8.endIndex] { if char == UInt8(ascii: "'") { newString += "'\\''" } else { newString += String(UnicodeScalar(char)) } } newString += "'" return newString } /// Shell escapes the current string. This method is mutating version of shellEscaped(). public mutating func shellEscape() { self = shellEscaped() } }
apache-2.0
e36773f3da7a9f087e7234b0e89fc09f
32.289474
121
0.573123
4.288136
false
false
false
false
ftxbird/NetEaseMoive
NetEaseMoive/NetEaseMoive/Helper/YSSegmentedControl.swift
1
7449
// // YSSegmentedControl.swift // yemeksepeti // // Created by Cem Olcay on 22/04/15. // Copyright (c) 2015 yemeksepeti. All rights reserved. // import UIKit // MARK: - 主题 public struct YSSegmentedControlAppearance { //背景色 public var backgroundColor: UIColor //高亮背景色 public var selectedBackgroundColor: UIColor //文本颜色 public var textColor: UIColor //字体 public var font: UIFont //高亮字体颜色 public var selectedTextColor: UIColor //高亮字体 public var selectedFont: UIFont //底部指示线颜色 public var bottomLineColor: UIColor public var selectorColor: UIColor //底部指示线高 public var bottomLineHeight: CGFloat public var selectorHeight: CGFloat //文本上部间距 public var labelTopPadding: CGFloat } // MARK: - Control Item typealias YSSegmentedControlItemAction = (item: YSSegmentedControlItem) -> Void class YSSegmentedControlItem: UIControl { // MARK: Properties private var willPress: YSSegmentedControlItemAction? private var didPressed: YSSegmentedControlItemAction? var label: UILabel! // MARK: Init init ( frame: CGRect, text: String, appearance: YSSegmentedControlAppearance, willPress: YSSegmentedControlItemAction?, didPressed: YSSegmentedControlItemAction?) { super.init(frame: frame) self.willPress = willPress self.didPressed = didPressed label = UILabel(frame: CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height)) label.textColor = appearance.textColor label.font = appearance.font label.textAlignment = .Center label.text = text addSubview(label) } required init?(coder aDecoder: NSCoder) { super.init (coder: aDecoder) } // MARK: Events override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { willPress?(item: self) } override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { didPressed?(item: self) } } // MARK: - Control @objc public protocol YSSegmentedControlDelegate { optional func segmentedControlWillPressItemAtIndex (segmentedControl: YSSegmentedControl, index: Int) optional func segmentedControlDidPressedItemAtIndex (segmentedControl: YSSegmentedControl, index: Int) } public typealias YSSegmentedControlAction = (segmentedControl: YSSegmentedControl, index: Int) -> Void public class YSSegmentedControl: UIView { // MARK: Properties weak var delegate: YSSegmentedControlDelegate? var action: YSSegmentedControlAction? public var appearance: YSSegmentedControlAppearance! { didSet { self.draw() } } var titles: [String]! var items: [YSSegmentedControlItem]! var selector: UIView! // MARK: Init public init (frame: CGRect, titles: [String], action: YSSegmentedControlAction? = nil) { super.init (frame: frame) self.action = action self.titles = titles defaultAppearance() } required public init? (coder aDecoder: NSCoder) { super.init (coder: aDecoder) } // MARK: Draw private func reset () { for sub in subviews { let v = sub v.removeFromSuperview() } items = [] } private func draw () { reset() backgroundColor = appearance.backgroundColor let width = frame.size.width / CGFloat(titles.count) var currentX: CGFloat = 0 for title in titles { let item = YSSegmentedControlItem( frame: CGRect( x: currentX, y: appearance.labelTopPadding, width: width, height: frame.size.height - appearance.labelTopPadding), text: title, appearance: appearance, willPress: { segmentedControlItem in let index = self.items.indexOf(segmentedControlItem)! self.delegate?.segmentedControlWillPressItemAtIndex?(self, index: index) }, didPressed: { segmentedControlItem in let index = self.items.indexOf(segmentedControlItem)! self.selectItemAtIndex(index, withAnimation: true) self.action?(segmentedControl: self, index: index) self.delegate?.segmentedControlDidPressedItemAtIndex?(self, index: index) }) addSubview(item) items.append(item) currentX += width } // bottom line let bottomLine = CALayer () bottomLine.frame = CGRect( x: 0, y: frame.size.height - appearance.bottomLineHeight, width: frame.size.width, height: appearance.bottomLineHeight) bottomLine.backgroundColor = appearance.bottomLineColor.CGColor layer.addSublayer(bottomLine) // selector selector = UIView (frame: CGRect ( x: 0, y: frame.size.height - appearance.selectorHeight, width: width, height: appearance.selectorHeight)) selector.backgroundColor = appearance.selectorColor addSubview(selector) selectItemAtIndex(0, withAnimation: true) } private func defaultAppearance () { appearance = YSSegmentedControlAppearance( backgroundColor: UIColor.clearColor(), selectedBackgroundColor: UIColor.clearColor(), textColor: UIColor.grayColor(), font: UIFont.systemFontOfSize(15), selectedTextColor: SEUIConfigCenter.sharedCenter.appColor, selectedFont: UIFont.systemFontOfSize(15), bottomLineColor: UIColor.blackColor(), selectorColor: SEUIConfigCenter.sharedCenter.appColor, bottomLineHeight: 0.5, selectorHeight: 2, labelTopPadding: 0) } // MARK: Select public func selectItemAtIndex (index: Int, withAnimation: Bool) { moveSelectorAtIndex(index, withAnimation: withAnimation) for item in items { if item == items[index] { item.label.textColor = appearance.selectedTextColor item.label.font = appearance.selectedFont item.backgroundColor = appearance.selectedBackgroundColor } else { item.label.textColor = appearance.textColor item.label.font = appearance.font item.backgroundColor = appearance.backgroundColor } } } private func moveSelectorAtIndex (index: Int, withAnimation: Bool) { let width = frame.size.width / CGFloat(items.count) let target = width * CGFloat(index) UIView.animateWithDuration(withAnimation ? 0.3 : 0, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: [], animations: { [unowned self] in self.selector.frame.origin.x = target }, completion: nil) } }
mit
7f67c498ee736ae44c3cb443a35b7d83
29.790795
106
0.603343
5.336476
false
false
false
false
creatubbles/ctb-api-swift
CreatubblesAPIClient/Sources/Requests/Bubble/UpdateBubbleRequest.swift
1
1894
// // UpdateBubbleRequest.swift // CreatubblesAPIClient // // Copyright (c) 2017 Creatubbles Pte. Ltd. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit class UpdateBubbleRequest: Request { override var method: RequestMethod { return .put } override var parameters: Dictionary<String, AnyObject> { return prepareParameters() } override var endpoint: String { return "bubbles/\(data.identifier)" } fileprivate let data: UpdateBubbleData init(data: UpdateBubbleData) { self.data = data } fileprivate func prepareParameters() -> Dictionary<String, AnyObject> { var params = Dictionary<String, AnyObject>() params["id"] = data.identifier as AnyObject? if let color = data.colorName { params["color"] = color as AnyObject? } return params } }
mit
afb41b88786a49a8574acff6b87c1476
39.297872
89
0.717529
4.5311
false
false
false
false
RocketChat/Rocket.Chat.iOS
Rocket.Chat/Controllers/User/UserDetail/UserDetailViewModel.swift
1
1540
// // UserDetailViewModel.swift // Rocket.Chat // // Created by Matheus Cardoso on 6/26/18. // Copyright © 2018 Rocket.Chat. All rights reserved. // import Foundation struct UserDetailViewModel { let name: String let username: String let avatarUrl: URL? let cells: [UserDetailFieldCellModel] let messageButtonText = localized("user_details.message_button") let voiceCallButtonText = localized("user_details.voice_call_button") let videoCallButtonText = localized("user_details.video_call_button") } // MARK: Empty State extension UserDetailViewModel { static var emptyState: UserDetailViewModel { return UserDetailViewModel(name: "", username: "", avatarUrl: nil, cells: []) } } // MARK: User extension UserDetailViewModel { static func forUser(_ user: User) -> UserDetailViewModel { return UserDetailViewModel( name: user.name ?? user.username ?? "", username: user.username ?? "", avatarUrl: user.avatarURL(), cells: UserDetailFieldCellModel.cellsForUser(user) ) } } // MARK: Table View extension UserDetailViewModel { var numberOfSections: Int { return 1 } func numberOfRowsForSection(_ section: Int) -> Int { return section == 0 ? cells.count : 0 } func cellForRowAtIndexPath(_ indexPath: IndexPath) -> UserDetailFieldCellModel { return indexPath.section == 0 && indexPath.row < cells.count ? cells[indexPath.row] : .emptyState } }
mit
5485d511edeba6993d2d9d3e93089010
25.084746
85
0.65757
4.580357
false
false
false
false
thatseeyou/iOSSDKExamples
Pages/[UITableViewController] UIRefreshControl.xcplaygroundpage/Contents.swift
1
2466
/*: # UIRefreshControl * UITableView가 아닌 UITableViewController에서 지원한다. * refreshControl 속성을 지정하면 된다. */ import Foundation import UIKit class TableViewController: UITableViewController { let cellIdentifier = "Cell" let cellImage = [#Image(imageLiteral: "people.user_simple 64.png")#] /*: ## override UIViewController method */ override func viewDidLoad() { print ("viewDidLoad") super.viewDidLoad() self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: cellIdentifier) // 줄의 좌우 여백을 준다. self.tableView.separatorInset = UIEdgeInsetsMake(0, 15, 0, 15) self.tableView.backgroundColor = [#Color(colorLiteralRed: 0, green: 1, blue: 0, alpha: 1)#] // UIRefreshControl self.refreshControl = UIRefreshControl() self.refreshControl!.addTarget(self, action: "doRefresh", forControlEvents: .ValueChanged) } /*: ## UITableViewDelegate protocol */ /*: ## UITableViewDataSource protocol */ override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 4 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell : UITableViewCell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) // one-time configuration cell.imageView?.image = cellImage cell.textLabel?.text = "textLabel \(indexPath.section)-\(indexPath.row)" cell.detailTextLabel?.text = "detailTextLabel" return cell } func doRefresh(sender: UIRefreshControl) { print("doRefresh") } func simulateUserInput() { self.tableView.setContentOffset(CGPointMake(0, -self.refreshControl!.bounds.height), animated: true) // 실제 환경에서는 아래의 코드는 자동으로 호출된다. self.refreshControl!.beginRefreshing() self.doRefresh(self.refreshControl!) } } let viewController = TableViewController(style: .Plain) PlaygroundHelper.showViewController(viewController) Utility.runActionAfterTime(1.0) { viewController.simulateUserInput() } Utility.runActionAfterTime(5.0) { viewController.refreshControl!.endRefreshing() }
mit
04c75aba709540d481243ce44a80c5cc
27.554217
121
0.694937
4.749499
false
false
false
false
RxSwiftCommunity/RxWebKit
Example/RedirectViewController.swift
1
1501
// // RedirectViewController.swift // Example // // Created by Bob Godwin Obi on 10/25/17. // Copyright © 2017 RxSwift Community. All rights reserved. // import UIKit import WebKit import RxWebKit import RxSwift import RxCocoa class RedirectViewController: UIViewController { let bag = DisposeBag() let wkWebView = WKWebView() override func viewDidLoad() { super.viewDidLoad() view.addSubview(wkWebView) wkWebView.load(URLRequest(url: URL(string: "http://www.webconfs.com/http-header-check.php")!)) wkWebView.rx .didReceiveServerRedirectForProvisionalNavigation .observe(on: MainScheduler.instance) .debug("didReceiveServerRedirectForProvisionalNavigation") .subscribe(onNext: { [weak self] webView, navigation in guard let self = self else { return } let alert = UIAlertController(title: "Redirect Navigation", message: "you have bene redirected", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) self.present(alert, animated: true, completion: nil) }) .disposed(by: bag) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() let originY = UIApplication.shared.statusBarFrame.maxY wkWebView.frame = CGRect(x: 0, y: originY, width: view.bounds.width, height: view.bounds.height) } }
mit
94b3b1e6d0364976748e1cfb4d1a6d32
33.883721
136
0.654
4.77707
false
false
false
false
kusl/swift
test/Serialization/function.swift
12
5300
// RUN: rm -rf %t // RUN: mkdir %t // RUN: %target-swift-frontend -emit-module -o %t %S/Inputs/def_func.swift // RUN: llvm-bcanalyzer %t/def_func.swiftmodule | FileCheck %s // RUN: %target-swift-frontend -emit-silgen -I %t %s | FileCheck %s -check-prefix=SIL // CHECK-NOT: FALL_BACK_TO_TRANSLATION_UNIT // CHECK-NOT: UnknownCode import def_func func useEq<T: EqualOperator>(x: T, y: T) -> Bool { return x == y } // SIL: sil @main // SIL: [[RAW:%.+]] = global_addr @_Tv8function3rawSi : $*Int // SIL: [[ZERO:%.+]] = function_ref @_TF8def_func7getZeroFT_Si : $@convention(thin) () -> Int // SIL: [[RESULT:%.+]] = apply [[ZERO]]() : $@convention(thin) () -> Int // SIL: store [[RESULT]] to [[RAW]] : $*Int var raw = getZero() // Check that 'raw' is an Int var cooked : Int = raw // SIL: [[GET_INPUT:%.+]] = function_ref @_TF8def_func8getInputFT1xSi_Si : $@convention(thin) (Int) -> Int // SIL: {{%.+}} = apply [[GET_INPUT]]({{%.+}}) : $@convention(thin) (Int) -> Int var raw2 = getInput(x: raw) // SIL: [[GET_SECOND:%.+]] = function_ref @_TF8def_func9getSecondFTSi1ySi_Si : $@convention(thin) (Int, Int) -> Int // SIL: {{%.+}} = apply [[GET_SECOND]]({{%.+}}, {{%.+}}) : $@convention(thin) (Int, Int) -> Int var raw3 = getSecond(raw, y: raw2) // SIL: [[USE_NESTED:%.+]] = function_ref @_TF8def_func9useNestedFTT1xSi1ySi_1nSi_T_ : $@convention(thin) (Int, Int, Int) -> () // SIL: {{%.+}} = apply [[USE_NESTED]]({{%.+}}, {{%.+}}, {{%.+}}) : $@convention(thin) (Int, Int, Int) -> () useNested((raw, raw2), n: raw3) // SIL: [[VARIADIC:%.+]] = function_ref @_TF8def_func8variadicFt1xSdGSaSi__T_ : $@convention(thin) (Double, @owned Array<Int>) -> () // SIL: [[VA_SIZE:%.+]] = integer_literal $Builtin.Word, 2 // SIL: {{%.+}} = apply {{%.*}}<Int>([[VA_SIZE]]) // SIL: {{%.+}} = apply [[VARIADIC]]({{%.+}}, {{%.+}}) : $@convention(thin) (Double, @owned Array<Int>) -> () variadic(x: 2.5, 4, 5) // SIL: [[VARIADIC:%.+]] = function_ref @_TF8def_func9variadic2FTGSaSi_1xSd_T_ : $@convention(thin) (@owned Array<Int>, Double) -> () variadic2(1, 2, 3, x: 5.0) // SIL: [[SLICE:%.+]] = function_ref @_TF8def_func5sliceFT1xGSaSi__T_ : $@convention(thin) (@owned Array<Int>) -> () // SIL: [[SLICE_SIZE:%.+]] = integer_literal $Builtin.Word, 3 // SIL: {{%.+}} = apply {{%.*}}<Int>([[SLICE_SIZE]]) // SIL: {{%.+}} = apply [[SLICE]]({{%.+}}) : $@convention(thin) (@owned Array<Int>) -> () slice(x: [2, 4, 5]) optional(x: .Some(23)) optional(x: .None) // SIL: [[MAKE_PAIR:%.+]] = function_ref @_TF8def_func8makePair{{.*}} : $@convention(thin) <τ_0_0, τ_0_1> (@out (τ_0_0, τ_0_1), @in τ_0_0, @in τ_0_1) -> () // SIL: {{%.+}} = apply [[MAKE_PAIR]]<Int, Double>({{%.+}}, {{%.+}}) var pair : (Int, Double) = makePair(a: 1, b: 2.5) // SIL: [[DIFFERENT_A:%.+]] = function_ref @_TF8def_func9different{{.*}} : $@convention(thin) <τ_0_0 where τ_0_0 : Equatable> (@in τ_0_0, @in τ_0_0) -> Bool // SIL: [[DIFFERENT_B:%.+]] = function_ref @_TF8def_func9different{{.*}} : $@convention(thin) <τ_0_0 where τ_0_0 : Equatable> (@in τ_0_0, @in τ_0_0) -> Bool different(a: 1, b: 2) different(a: false, b: false) // SIL: [[DIFFERENT2_A:%.+]] = function_ref @_TF8def_func10different2{{.*}} : $@convention(thin) <τ_0_0 where τ_0_0 : Equatable> (@in τ_0_0, @in τ_0_0) -> Bool // SIL: [[DIFFERENT2_B:%.+]] = function_ref @_TF8def_func10different2{{.*}} : $@convention(thin) <τ_0_0 where τ_0_0 : Equatable> (@in τ_0_0, @in τ_0_0) -> Bool different2(a: 1, b: 2) different2(a: false, b: false) struct IntWrapper1 : Wrapped { typealias Value = Int func getValue() -> Int { return 1 } } struct IntWrapper2 : Wrapped { typealias Value = Int func getValue() -> Int { return 2 } } // SIL: [[DIFFERENT_WRAPPED:%.+]] = function_ref @_TF8def_func16differentWrapped{{.*}} : $@convention(thin) <τ_0_0, τ_0_1 where τ_0_0 : Wrapped, τ_0_1 : Wrapped, τ_0_0.Value : Equatable, τ_0_0.Value == τ_0_1.Value> (@in τ_0_0, @in τ_0_1) -> Bool differentWrapped(a: IntWrapper1(), b: IntWrapper2()) // SIL: {{%.+}} = function_ref @_TF8def_func10overloadedFT1xSi_T_ : $@convention(thin) (Int) -> () // SIL: {{%.+}} = function_ref @_TF8def_func10overloadedFT1xSb_T_ : $@convention(thin) (Bool) -> () overloaded(x: 1) overloaded(x: false) // SIL: {{%.+}} = function_ref @primitive : $@convention(thin) () -> () primitive() if raw == 5 { testNoReturnAttr() testNoReturnAttrPoly(x: 5) } // SIL: {{%.+}} = function_ref @_TF8def_func16testNoReturnAttrFT_T_ : $@convention(thin) @noreturn () -> () // SIL: {{%.+}} = function_ref @_TF8def_func20testNoReturnAttrPoly{{.*}} : $@convention(thin) @noreturn <τ_0_0> (@in τ_0_0) -> () // SIL: sil @_TF8def_func16testNoReturnAttrFT_T_ : $@convention(thin) @noreturn () -> () // SIL: sil @_TF8def_func20testNoReturnAttrPoly{{.*}} : $@convention(thin) @noreturn <τ_0_0> (@in τ_0_0) -> () do { try throws1() try throws2(1) } catch _ {} // SIL: sil @_TF8def_func7throws1FzT_T_ : $@convention(thin) () -> @error ErrorType // SIL: sil @_TF8def_func7throws2{{.*}} : $@convention(thin) <τ_0_0> (@out τ_0_0, @in τ_0_0) -> @error ErrorType // LLVM: } mineGold() // expected-warning{{you might want to keep it}} var foo = Foo() foo.reverse() // expected-warning{{reverseInPlace}}{{5-12=reverseInPlace}}
apache-2.0
d65afbe20e0daa4540fbcbe6b92a31c6
42.131148
247
0.582858
2.822961
false
false
false
false
xibe/WordPress-iOS
WordPress/Classes/ViewRelated/Notifications/Controllers/NotificationSettingDetailsViewController.swift
3
11022
import Foundation /** * @class NotificationSettingDetailsViewController * @brief The purpose of this class is to render a collection of NotificationSettings for a given * Stream, encapsulated in the class NotificationSettings.Stream, and to provide the user * a simple interface to update those settings, as needed. */ public class NotificationSettingDetailsViewController : UITableViewController { // MARK: - Initializers public convenience init(settings: NotificationSettings) { self.init(settings: settings, stream: settings.streams.first!) } public convenience init(settings: NotificationSettings, stream: NotificationSettings.Stream) { self.init(style: .Grouped) self.settings = settings self.stream = stream } // MARK: - View Lifecycle public override func viewDidLoad() { super.viewDidLoad() setupTitle() setupNotifications() setupTableView() reloadTable() } public override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) WPAnalytics.track(.OpenedNotificationSettingDetails) } public override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) saveSettingsIfNeeded() } // MARK: - Setup Helpers private func setupTitle() { switch settings!.channel { case .WordPressCom: title = NSLocalizedString("WordPress.com Updates", comment: "WordPress.com Notification Settings Title") default: title = stream!.kind.description() } } private func setupNotifications() { // Reload whenever the app becomes active again since Push Settings may have changed in the meantime! let notificationCenter = NSNotificationCenter.defaultCenter() notificationCenter.addObserver(self, selector: "reloadTable", name: UIApplicationDidBecomeActiveNotification, object: nil) } private func setupTableView() { // Register the cells tableView.registerClass(SwitchTableViewCell.self, forCellReuseIdentifier: Row.Kind.Setting.rawValue) tableView.registerClass(WPTableViewCell.self, forCellReuseIdentifier: Row.Kind.Text.rawValue) // Hide the separators, whenever the table is empty tableView.tableFooterView = UIView() // Style! WPStyleGuide.configureColorsForView(view, andTableView: tableView) } @IBAction private func reloadTable() { sections = isDeviceStreamDisabled() ? sectionsForDisabledDeviceStream() : sectionsForSettings(settings!, stream: stream!) tableView.reloadData() } // MARK: - Private Helpers private func sectionsForSettings(settings: NotificationSettings, stream: NotificationSettings.Stream) -> [Section] { // WordPress.com Channel requires a brief description per row. // For that reason, we'll render each row in its own section, with it's very own footer let singleSectionMode = settings.channel != .WordPressCom // Parse the Rows var rows = [Row]() for key in settings.sortedPreferenceKeys(stream) { let description = settings.localizedDescription(key) let value = stream.preferences?[key] ?? true let row = Row(kind: .Setting, description: description, key: key, value: value) rows.append(row) } // Single Section Mode: A single section will contain all of the rows if singleSectionMode { return [Section(rows: rows)] } // Multi Section Mode: We'll have one Section per Row var sections = [Section]() for row in rows { let unwrappedKey = row.key ?? String() let details = settings.localizedDetails(unwrappedKey) let section = Section(rows: [row], footerText: details) sections.append(section) } return sections } private func sectionsForDisabledDeviceStream() -> [Section] { let description = NSLocalizedString("Go to iPhone Settings", comment: "Opens WPiOS Settings.app Section") let row = Row(kind: .Text, description: description, key: nil, value: nil) let footerText = NSLocalizedString("Push Notifications have been turned off in iOS Settings App. " + "Toggle \"Allow Notifications\" to turn them back on.", comment: "Suggests to enable Push Notification Settings in Settings.app") let section = Section(rows: [row], footerText: footerText) return [section] } // MARK: - UITableView Delegate Methods public override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return sections.count } public override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return sections[section].rows.count } public override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let section = sections[indexPath.section] let row = section.rows[indexPath.row] let cell = tableView.dequeueReusableCellWithIdentifier(row.kind.rawValue) as! UITableViewCell switch row.kind { case .Text: configureTextCell(cell as! WPTableViewCell, row: row) case .Setting: configureSwitchCell(cell as! SwitchTableViewCell, row: row) } return cell } public override func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { if let footerText = sections[section].footerText { return WPTableViewSectionHeaderFooterView.heightForFooter(footerText, width: view.bounds.width) } return CGFloat.min } public override func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { if let footerText = sections[section].footerText { let footerView = WPTableViewSectionHeaderFooterView(reuseIdentifier: nil, style: .Footer) footerView.title = footerText return footerView } return nil } public override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectSelectedRowWithAnimation(true) if isDeviceStreamDisabled() { openApplicationSettings() } } // MARK: - UITableView Helpers private func configureTextCell(cell: WPTableViewCell, row: Row) { cell.textLabel?.text = row.description WPStyleGuide.configureTableViewCell(cell) } private func configureSwitchCell(cell: SwitchTableViewCell, row: Row) { let settingKey = row.key ?? String() cell.name = row.description cell.on = newValues[settingKey] ?? (row.value ?? true) cell.onChange = { [weak self] (newValue: Bool) in self?.newValues[settingKey] = newValue } } // MARK: - Disabled Push Notifications Handling private func isDeviceStreamDisabled() -> Bool { return stream?.kind == .Device && !NotificationsManager.pushNotificationsEnabledInDeviceSettings() } private func openApplicationSettings() { if !UIDevice.isOS8() { return } let targetURL = NSURL(string: UIApplicationOpenSettingsURLString) UIApplication.sharedApplication().openURL(targetURL!) } // MARK: - Service Helpers private func saveSettingsIfNeeded() { if newValues.count == 0 || settings == nil { return } let context = ContextManager.sharedInstance().mainContext let service = NotificationsService(managedObjectContext: context) service.updateSettings(settings!, stream : stream!, newValues : newValues, success : { WPAnalytics.track(.NotificationsSettingsUpdated, withProperties: ["success" : true]) }, failure : { (error: NSError!) in WPAnalytics.track(.NotificationsSettingsUpdated, withProperties: ["success" : false]) self.handleUpdateError() }) } private func handleUpdateError() { UIAlertView.showWithTitle(NSLocalizedString("Oops!", comment: ""), message : NSLocalizedString("There has been an unexpected error while updating " + "your Notification Settings", comment: "Displayed after a failed Notification Settings call"), style : .Default, cancelButtonTitle : NSLocalizedString("Cancel", comment: "Cancel. Action."), otherButtonTitles : [ NSLocalizedString("Retry", comment: "Retry. Action") ], tapBlock : { (alertView: UIAlertView!, buttonIndex: Int) -> Void in if alertView.cancelButtonIndex == buttonIndex { return } self.saveSettingsIfNeeded() }) } // MARK: - Private Nested Class'ess private class Section { var rows : [Row] var footerText : String? init(rows: [Row], footerText: String? = nil) { self.rows = rows self.footerText = footerText } } private class Row { let description : String let kind : Kind let key : String? let value : Bool? init(kind: Kind, description: String, key: String? = nil, value: Bool? = nil) { self.description = description self.kind = kind self.key = key self.value = value } enum Kind : String { case Setting = "SwitchCell" case Text = "TextCell" } } // MARK: - Private Properties private var settings : NotificationSettings? private var stream : NotificationSettings.Stream? // MARK: - Helpers private var sections = [Section]() private var newValues = [String: Bool]() }
gpl-2.0
180d54d9efaafe433cb2b743227ed93b
35.862876
129
0.587643
5.764644
false
false
false
false
danielgindi/Charts
Source/Charts/Renderers/RadarChartRenderer.swift
1
18066
// // RadarChartRenderer.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 RadarChartRenderer: LineRadarRenderer { private lazy var accessibilityXLabels: [String] = { guard let chart = chart else { return [] } guard let formatter = chart.xAxis.valueFormatter else { return [] } let maxEntryCount = chart.data?.maxEntryCountSet?.entryCount ?? 0 return stride(from: 0, to: maxEntryCount, by: 1).map { formatter.stringForValue(Double($0), axis: chart.xAxis) } }() @objc open weak var chart: RadarChartView? @objc public init(chart: RadarChartView, animator: Animator, viewPortHandler: ViewPortHandler) { super.init(animator: animator, viewPortHandler: viewPortHandler) self.chart = chart } open override func drawData(context: CGContext) { guard let chart = chart, let radarData = chart.data as? RadarChartData else { return } let mostEntries = radarData.maxEntryCountSet?.entryCount ?? 0 // If we redraw the data, remove and repopulate accessible elements to update label values and frames self.accessibleChartElements.removeAll() // Make the chart header the first element in the accessible elements array let element = createAccessibleHeader(usingChart: chart, andData: radarData, withDefaultDescription: "Radar Chart") self.accessibleChartElements.append(element) for case let set as RadarChartDataSetProtocol in (radarData as ChartData) where set.isVisible { drawDataSet(context: context, dataSet: set, mostEntries: mostEntries) } } /// Draws the RadarDataSet /// /// - Parameters: /// - context: /// - dataSet: /// - mostEntries: the entry count of the dataset with the most entries internal func drawDataSet(context: CGContext, dataSet: RadarChartDataSetProtocol, mostEntries: Int) { guard let chart = chart else { return } context.saveGState() let phaseX = animator.phaseX let phaseY = animator.phaseY let sliceangle = chart.sliceAngle // calculate the factor that is needed for transforming the value to pixels let factor = chart.factor let center = chart.centerOffsets let entryCount = dataSet.entryCount let path = CGMutablePath() var hasMovedToPoint = false let prefix: String = chart.data?.accessibilityEntryLabelPrefix ?? "Item" let description = dataSet.label ?? "" // Make a tuple of (xLabels, value, originalIndex) then sort it // This is done, so that the labels are narrated in decreasing order of their corresponding value // Otherwise, there is no non-visual logic to the data presented let accessibilityEntryValues = Array(0 ..< entryCount).map { (dataSet.entryForIndex($0)?.y ?? 0, $0) } let accessibilityAxisLabelValueTuples = zip(accessibilityXLabels, accessibilityEntryValues).map { ($0, $1.0, $1.1) }.sorted { $0.1 > $1.1 } let accessibilityDataSetDescription: String = description + ". \(entryCount) \(prefix + (entryCount == 1 ? "" : "s")). " let accessibilityFrameWidth: CGFloat = 22.0 // To allow a tap target of 44x44 var accessibilityEntryElements: [NSUIAccessibilityElement] = [] for j in 0 ..< entryCount { guard let e = dataSet.entryForIndex(j) else { continue } let p = center.moving(distance: CGFloat((e.y - chart.chartYMin) * Double(factor) * phaseY), atAngle: sliceangle * CGFloat(j) * CGFloat(phaseX) + chart.rotationAngle) if p.x.isNaN { continue } if !hasMovedToPoint { path.move(to: p) hasMovedToPoint = true } else { path.addLine(to: p) } let accessibilityLabel = accessibilityAxisLabelValueTuples[j].0 let accessibilityValue = accessibilityAxisLabelValueTuples[j].1 let accessibilityValueIndex = accessibilityAxisLabelValueTuples[j].2 let axp = center.moving(distance: CGFloat((accessibilityValue - chart.chartYMin) * Double(factor) * phaseY), atAngle: sliceangle * CGFloat(accessibilityValueIndex) * CGFloat(phaseX) + chart.rotationAngle) let axDescription = description + " - " + accessibilityLabel + ": \(accessibilityValue) \(chart.data?.accessibilityEntryLabelSuffix ?? "")" let axElement = createAccessibleElement(withDescription: axDescription, container: chart, dataSet: dataSet) { (element) in element.accessibilityFrame = CGRect(x: axp.x - accessibilityFrameWidth, y: axp.y - accessibilityFrameWidth, width: 2 * accessibilityFrameWidth, height: 2 * accessibilityFrameWidth) } accessibilityEntryElements.append(axElement) } // if this is the largest set, close it if dataSet.entryCount < mostEntries { // if this is not the largest set, draw a line to the center before closing path.addLine(to: center) } path.closeSubpath() // draw filled if dataSet.isDrawFilledEnabled { if dataSet.fill != nil { drawFilledPath(context: context, path: path, fill: dataSet.fill!, fillAlpha: dataSet.fillAlpha) } else { drawFilledPath(context: context, path: path, fillColor: dataSet.fillColor, fillAlpha: dataSet.fillAlpha) } } // draw the line (only if filled is disabled or alpha is below 255) if !dataSet.isDrawFilledEnabled || dataSet.fillAlpha < 1.0 { context.setStrokeColor(dataSet.color(atIndex: 0).cgColor) context.setLineWidth(dataSet.lineWidth) context.setAlpha(1.0) context.beginPath() context.addPath(path) context.strokePath() let axElement = createAccessibleElement(withDescription: accessibilityDataSetDescription, container: chart, dataSet: dataSet) { (element) in element.isHeader = true element.accessibilityFrame = path.boundingBoxOfPath } accessibleChartElements.append(axElement) accessibleChartElements.append(contentsOf: accessibilityEntryElements) } accessibilityPostLayoutChangedNotification() context.restoreGState() } open override func drawValues(context: CGContext) { guard let chart = chart, let data = chart.data else { return } let phaseX = animator.phaseX let phaseY = animator.phaseY let sliceangle = chart.sliceAngle // calculate the factor that is needed for transforming the value to pixels let factor = chart.factor let center = chart.centerOffsets let yoffset = CGFloat(5.0) for i in data.indices { guard let dataSet = data[i] as? RadarChartDataSetProtocol, shouldDrawValues(forDataSet: dataSet) else { continue } let angleRadians = dataSet.valueLabelAngle.DEG2RAD let entryCount = dataSet.entryCount let iconsOffset = dataSet.iconsOffset for j in 0 ..< entryCount { guard let e = dataSet.entryForIndex(j) else { continue } let p = center.moving(distance: CGFloat(e.y - chart.chartYMin) * factor * CGFloat(phaseY), atAngle: sliceangle * CGFloat(j) * CGFloat(phaseX) + chart.rotationAngle) let valueFont = dataSet.valueFont let formatter = dataSet.valueFormatter if dataSet.isDrawValuesEnabled { context.drawText(formatter.stringForValue(e.y, entry: e, dataSetIndex: i, viewPortHandler: viewPortHandler), at: CGPoint(x: p.x, y: p.y - yoffset - valueFont.lineHeight), align: .center, angleRadians: angleRadians, attributes: [.font: valueFont, .foregroundColor: dataSet.valueTextColorAt(j)]) } if let icon = e.icon, dataSet.isDrawIconsEnabled { var pIcon = center.moving(distance: CGFloat(e.y) * factor * CGFloat(phaseY) + iconsOffset.y, atAngle: sliceangle * CGFloat(j) * CGFloat(phaseX) + chart.rotationAngle) pIcon.y += iconsOffset.x context.drawImage(icon, atCenter: CGPoint(x: pIcon.x, y: pIcon.y), size: icon.size) } } } } open override func drawExtras(context: CGContext) { drawWeb(context: context) } private var _webLineSegmentsBuffer = [CGPoint](repeating: CGPoint(), count: 2) @objc open func drawWeb(context: CGContext) { guard let chart = chart, let data = chart.data else { return } let sliceangle = chart.sliceAngle context.saveGState() // calculate the factor that is needed for transforming the value to // pixels let factor = chart.factor let rotationangle = chart.rotationAngle let center = chart.centerOffsets // draw the web lines that come from the center context.setLineWidth(chart.webLineWidth) context.setStrokeColor(chart.webColor.cgColor) context.setAlpha(chart.webAlpha) let xIncrements = 1 + chart.skipWebLineCount let maxEntryCount = chart.data?.maxEntryCountSet?.entryCount ?? 0 for i in stride(from: 0, to: maxEntryCount, by: xIncrements) { let p = center.moving(distance: CGFloat(chart.yRange) * factor, atAngle: sliceangle * CGFloat(i) + rotationangle) _webLineSegmentsBuffer[0].x = center.x _webLineSegmentsBuffer[0].y = center.y _webLineSegmentsBuffer[1].x = p.x _webLineSegmentsBuffer[1].y = p.y context.strokeLineSegments(between: _webLineSegmentsBuffer) } // draw the inner-web context.setLineWidth(chart.innerWebLineWidth) context.setStrokeColor(chart.innerWebColor.cgColor) context.setAlpha(chart.webAlpha) let labelCount = chart.yAxis.entryCount for j in 0 ..< labelCount { for i in 0 ..< data.entryCount { let r = CGFloat(chart.yAxis.entries[j] - chart.chartYMin) * factor let p1 = center.moving(distance: r, atAngle: sliceangle * CGFloat(i) + rotationangle) let p2 = center.moving(distance: r, atAngle: sliceangle * CGFloat(i + 1) + rotationangle) _webLineSegmentsBuffer[0].x = p1.x _webLineSegmentsBuffer[0].y = p1.y _webLineSegmentsBuffer[1].x = p2.x _webLineSegmentsBuffer[1].y = p2.y context.strokeLineSegments(between: _webLineSegmentsBuffer) } } context.restoreGState() } private var _highlightPointBuffer = CGPoint() open override func drawHighlighted(context: CGContext, indices: [Highlight]) { guard let chart = chart, let radarData = chart.data as? RadarChartData else { return } context.saveGState() let sliceangle = chart.sliceAngle // calculate the factor that is needed for transforming the value pixels let factor = chart.factor let center = chart.centerOffsets for high in indices { guard let set = chart.data?[high.dataSetIndex] as? RadarChartDataSetProtocol, set.isHighlightEnabled else { continue } guard let e = set.entryForIndex(Int(high.x)) as? RadarChartDataEntry else { continue } if !isInBoundsX(entry: e, dataSet: set) { continue } context.setLineWidth(radarData.highlightLineWidth) if radarData.highlightLineDashLengths != nil { context.setLineDash(phase: radarData.highlightLineDashPhase, lengths: radarData.highlightLineDashLengths!) } else { context.setLineDash(phase: 0.0, lengths: []) } context.setStrokeColor(set.highlightColor.cgColor) let y = e.y - chart.chartYMin _highlightPointBuffer = center.moving(distance: CGFloat(y) * factor * CGFloat(animator.phaseY), atAngle: sliceangle * CGFloat(high.x) * CGFloat(animator.phaseX) + chart.rotationAngle) high.setDraw(pt: _highlightPointBuffer) // draw the lines drawHighlightLines(context: context, point: _highlightPointBuffer, set: set) if set.isDrawHighlightCircleEnabled { if !_highlightPointBuffer.x.isNaN && !_highlightPointBuffer.y.isNaN { var strokeColor = set.highlightCircleStrokeColor if strokeColor == nil { strokeColor = set.color(atIndex: 0) } if set.highlightCircleStrokeAlpha < 1.0 { strokeColor = strokeColor?.withAlphaComponent(set.highlightCircleStrokeAlpha) } drawHighlightCircle( context: context, atPoint: _highlightPointBuffer, innerRadius: set.highlightCircleInnerRadius, outerRadius: set.highlightCircleOuterRadius, fillColor: set.highlightCircleFillColor, strokeColor: strokeColor, strokeWidth: set.highlightCircleStrokeWidth) } } } context.restoreGState() } internal func drawHighlightCircle( context: CGContext, atPoint point: CGPoint, innerRadius: CGFloat, outerRadius: CGFloat, fillColor: NSUIColor?, strokeColor: NSUIColor?, strokeWidth: CGFloat) { context.saveGState() if let fillColor = fillColor { context.beginPath() context.addEllipse(in: CGRect(x: point.x - outerRadius, y: point.y - outerRadius, width: outerRadius * 2.0, height: outerRadius * 2.0)) if innerRadius > 0.0 { context.addEllipse(in: CGRect(x: point.x - innerRadius, y: point.y - innerRadius, width: innerRadius * 2.0, height: innerRadius * 2.0)) } context.setFillColor(fillColor.cgColor) context.fillPath(using: .evenOdd) } if let strokeColor = strokeColor { context.beginPath() context.addEllipse(in: CGRect(x: point.x - outerRadius, y: point.y - outerRadius, width: outerRadius * 2.0, height: outerRadius * 2.0)) context.setStrokeColor(strokeColor.cgColor) context.setLineWidth(strokeWidth) context.strokePath() } context.restoreGState() } private func createAccessibleElement(withDescription description: String, container: RadarChartView, dataSet: RadarChartDataSetProtocol, modifier: (NSUIAccessibilityElement) -> ()) -> NSUIAccessibilityElement { let element = NSUIAccessibilityElement(accessibilityContainer: container) element.accessibilityLabel = description // The modifier allows changing of traits and frame depending on highlight, rotation, etc modifier(element) return element } }
apache-2.0
2ee164ff5604c0e434fa001e06a70abd
37.520256
151
0.5393
5.814612
false
false
false
false
cailingyun2010/swift-weibo
微博-S/Classes/Home/PhotoBrowserController.swift
1
4958
// // PhotoBrowserController.swift // 微博-S // // Created by nimingM on 16/3/30. // Copyright © 2016年 蔡凌云. All rights reserved. // import UIKit import SVProgressHUD private let photoBrowserCellReuseIdentifier = "pictureCell" class PhotoBrowserController: UIViewController { // MARK: - propety var currentIndex: Int? var pictureURLs: [NSURL]? // MARK: - private method init(index: Int, urls: [NSURL]) { // swift 语法规定,必须先调用本类的初始化,在调用父类的 currentIndex = index pictureURLs = urls // 并且调用设计的构造方法 super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.whiteColor() setupUI() } // MARK: - 初始化 private func setupUI() { // 1.添加子控件 view.addSubview(collectionView) view.addSubview(closeBtn) view.addSubview(saveBtn) // 布局子控件 closeBtn.xmg_AlignInner(type: XMG_AlignType.BottomLeft, referView: view, size: CGSize(width: 100, height: 35), offset: CGPoint(x: 10, y: -10)) saveBtn.xmg_AlignInner(type: XMG_AlignType.BottomRight, referView: view, size: CGSize(width: 100, height: 35), offset: CGPoint(x: -10, y: -10)) collectionView.frame = UIScreen.mainScreen().bounds // 3.设置数据源 collectionView.dataSource = self collectionView.registerClass(PhotoBrowserCell.self, forCellWithReuseIdentifier: photoBrowserCellReuseIdentifier) } // MARK: - 懒加载 private lazy var closeBtn:UIButton = { let btn = UIButton() btn.setTitle("关闭", forState: UIControlState.Normal) btn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal) btn.backgroundColor = UIColor.darkGrayColor() btn.addTarget(self, action: "close", forControlEvents: UIControlEvents.TouchUpInside) return btn }() private lazy var saveBtn: UIButton = { let btn = UIButton() btn.setTitle("保存", forState: UIControlState.Normal) btn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal) btn.backgroundColor = UIColor.darkGrayColor() btn.addTarget(self, action: "save", forControlEvents: UIControlEvents.TouchUpInside) return btn }() private lazy var collectionView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: PhotoBrowserLayout()) // MARK: - actions func close() { dismissViewControllerAnimated(true, completion: nil) } func save() { // 获得当前正在显示cell的索引 let index = collectionView.indexPathsForVisibleItems().last! let cell = collectionView.cellForItemAtIndexPath(index) as! PhotoBrowserCell // 保存图片 let image = cell.iconView.image UIImageWriteToSavedPhotosAlbum(image!, self, "image:didFinishSavingWithError:contextInfo:", nil) } func image(image:UIImage, didFinishSavingWithError error:NSError?, contextInfo:AnyObject) { if error != nil { SVProgressHUD.showErrorWithStatus("保存失败", maskType: SVProgressHUDMaskType.Black) }else { SVProgressHUD.showSuccessWithStatus("保存成功", maskType: SVProgressHUDMaskType.Black) } } } extension PhotoBrowserController : UICollectionViewDataSource,PhotoBrowserCellDelegate { func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return pictureURLs?.count ?? 0 } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(photoBrowserCellReuseIdentifier, forIndexPath: indexPath) as! PhotoBrowserCell cell.backgroundColor = UIColor.whiteColor() cell.imageURL = pictureURLs![indexPath.item] cell.photoDelegate = self return cell } func photoBrowserCellDidClose(cell: PhotoBrowserCell) { dismissViewControllerAnimated(true, completion: nil) } } class PhotoBrowserLayout : UICollectionViewFlowLayout { override func prepareLayout() { itemSize = UIScreen.mainScreen().bounds.size minimumInteritemSpacing = 0 minimumLineSpacing = 0 scrollDirection = UICollectionViewScrollDirection.Horizontal collectionView?.showsHorizontalScrollIndicator = false collectionView?.pagingEnabled = true collectionView?.bounces = false } }
apache-2.0
f8c4483e3f1449852e849169a299596f
32.433566
151
0.665342
5.318131
false
false
false
false
garygriswold/Bible.js
SafeBible2/SafeBible_ios/SafeBible/ToolBars/SettingsSearchController.swift
1
2602
// // SettingsSearchController.swift // Settings // // Created by Gary Griswold on 9/9/18. // Copyright © 2018 ShortSands. All rights reserved. // import UIKit class SettingsSearchController: NSObject, UISearchResultsUpdating { private weak var controller: AppTableViewController? private let availableSection: Int private let searchController: UISearchController private var dataModel: SettingsModel? init(controller: AppTableViewController, selectionViewSection: Int) { self.controller = controller self.availableSection = selectionViewSection + 1 self.searchController = UISearchController(searchResultsController: nil) self.searchController.searchBar.placeholder = NSLocalizedString("Find Languages", comment: "Languages search bar") super.init() self.searchController.searchResultsUpdater = self self.searchController.obscuresBackgroundDuringPresentation = false self.searchController.hidesNavigationBarDuringPresentation = false self.controller?.navigationItem.hidesSearchBarWhenScrolling = false //self.searchController.searchBar.setShowsCancelButton(false, animated: true) } deinit { print("**** deinit SettingsSearchController ******") } func viewAppears(dataModel: SettingsModel?) { if let data = dataModel { self.dataModel = data self.controller?.navigationItem.searchController = self.searchController } else { self.dataModel = nil self.controller?.navigationItem.searchController = nil } } func isSearching() -> Bool { let searchBarEmpty: Bool = self.searchController.searchBar.text?.isEmpty ?? true return self.searchController.isActive && !searchBarEmpty } func updateSearchResults() { if isSearching() { updateSearchResults(for: self.searchController) } } // MARK: - UISearchResultsUpdating Delegate func updateSearchResults(for searchController: UISearchController) { print("****** INSIDE update Search Results ********") if let text = self.searchController.searchBar.text { if text.count > 0 { self.dataModel?.filterForSearch(searchText: text) } let sections = IndexSet(integer: self.availableSection) self.controller?.tableView.reloadSections(sections, with: UITableView.RowAnimation.automatic) } } }
mit
c4f1f40afd91c28df335f92c15840b73
37.25
105
0.658208
5.858108
false
false
false
false
wibosco/ASOS-Consumer
ASOSConsumer/Networking/CategoryProducts/Operations/Retrieval/CategoryProductsRetrievalOperation.swift
1
1845
// // CategoryProductsRetrievalOperation.swift // ASOSConsumer // // Created by William Boles on 02/03/2016. // Copyright © 2016 Boles. All rights reserved. // import UIKit class CategoryProductsRetrievalOperation: NSOperation { //MARK: - Accessors var category : Category var data : NSData var completion : ((category: Category, categoryProducts: Array<CategoryProduct>?) -> (Void))? var callBackQueue : NSOperationQueue //MARK: - Init init(category: Category, data: NSData, completion: ((category: Category, categoryProducts: Array<CategoryProduct>?) -> Void)?) { self.category = category self.data = data self.completion = completion self.callBackQueue = NSOperationQueue.currentQueue()! super.init() } //MARK: - Main override func main() { super.main() do { let jsonResponse = try NSJSONSerialization.JSONObjectWithData(self.data, options: NSJSONReadingOptions.MutableContainers) as! Dictionary<String, AnyObject> let parser = CategoryProductParser() let categoryProducts = parser.parseCategoryProducts(jsonResponse) self.callBackQueue.addOperationWithBlock({ () -> Void in if (self.completion != nil) { self.completion!(category: self.category, categoryProducts: categoryProducts) } }) } catch let error as NSError { print("Failed to load \(error.localizedDescription)") self.callBackQueue.addOperationWithBlock({ () -> Void in if (self.completion != nil) { self.completion!(category: self.category, categoryProducts: nil) } }) } } }
mit
b8a5a62dc69de367958f2206ce604bc5
31.350877
167
0.598698
5.344928
false
false
false
false
rokuz/omim
iphone/Maps/Bookmarks/Catalog/Subscription/BookmarksSubscriptionViewController.swift
1
2646
import SafariServices @objc class BookmarksSubscriptionViewController: BaseSubscriptionViewController { //MARK: outlets @IBOutlet private var annualSubscriptionButton: BookmarksSubscriptionButton! @IBOutlet private var annualDiscountLabel: BookmarksSubscriptionDiscountLabel! @IBOutlet private var monthlySubscriptionButton: BookmarksSubscriptionButton! override var subscriptionManager: ISubscriptionManager? { get { return InAppPurchase.bookmarksSubscriptionManager } } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { get { return [.portrait] } } override var preferredStatusBarStyle: UIStatusBarStyle { get { return UIColor.isNightMode() ? .lightContent : .default } } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() annualSubscriptionButton.config(title: L("annual_subscription_title"), price: "...", enabled: false) monthlySubscriptionButton.config(title: L("montly_subscription_title"), price: "...", enabled: false) if !UIColor.isNightMode() { annualDiscountLabel.layer.shadowRadius = 4 annualDiscountLabel.layer.shadowOffset = CGSize(width: 0, height: 2) annualDiscountLabel.layer.shadowColor = UIColor.blackHintText().cgColor annualDiscountLabel.layer.shadowOpacity = 0.62 } annualDiscountLabel.layer.cornerRadius = 6 annualDiscountLabel.isHidden = true self.configure(buttons: [ .year: annualSubscriptionButton, .month: monthlySubscriptionButton], discountLabels:[ .year: annualDiscountLabel]) Statistics.logEvent(kStatInappShow, withParameters: [kStatVendor: MWMPurchaseManager.bookmarksSubscriptionVendorId(), kStatPurchase: MWMPurchaseManager.bookmarksSubscriptionServerId(), kStatProduct: BOOKMARKS_SUBSCRIPTION_YEARLY_PRODUCT_ID, kStatFrom: source], with: .realtime) } @IBAction func onAnnualButtonTap(_ sender: UIButton) { purchase(sender: sender, period: .year) } @IBAction func onMonthlyButtonTap(_ sender: UIButton) { purchase(sender: sender, period: .month) } }
apache-2.0
486c58ec626e5619e3bc1a42c258c3f2
38.492537
123
0.662887
5.828194
false
false
false
false
sschiau/swift-package-manager
Sources/Basic/JSON.swift
2
11348
/* This source file is part of the Swift.org open source project Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors ------------------------------------------------------------------------- This file defines JSON support infrastructure. It is not designed to be general purpose JSON utilities, but rather just the infrastructure which SwiftPM needs to manage serialization of data through JSON. */ // MARK: JSON Item Definition /// A JSON value. /// /// This type uses container wrappers in order to allow for mutable elements. public enum JSON { /// The null value. case null /// A boolean value. case bool(Bool) /// An integer value. /// /// While not strictly present in JSON, we use this as a convenience to /// parsing code. case int(Int) /// A floating-point value. case double(Double) /// A string. case string(String) /// An array. case array([JSON]) /// A dictionary. case dictionary([String: JSON]) /// An ordered dictionary. case orderedDictionary(DictionaryLiteral<String, JSON>) } /// A JSON representation of an element. public protocol JSONSerializable { /// Return a JSON representation. func toJSON() -> JSON } extension JSON: CustomStringConvertible { public var description: Swift.String { switch self { case .null: return "null" case .bool(let value): return value.description case .int(let value): return value.description case .double(let value): return value.description case .string(let value): return value.debugDescription case .array(let values): return values.description case .dictionary(let values): return values.description case .orderedDictionary(let values): return values.description } } } /// Equatable conformance. extension JSON: Equatable { public static func == (lhs: JSON, rhs: JSON) -> Bool { switch (lhs, rhs) { case (.null, .null): return true case (.null, _): return false case (.bool(let a), .bool(let b)): return a == b case (.bool, _): return false case (.int(let a), .int(let b)): return a == b case (.int, _): return false case (.double(let a), .double(let b)): return a == b case (.double, _): return false case (.string(let a), .string(let b)): return a == b case (.string, _): return false case (.array(let a), .array(let b)): return a == b case (.array, _): return false case (.dictionary(let a), .dictionary(let b)): return a == b case (.dictionary, _): return false case (.orderedDictionary(let a), .orderedDictionary(let b)): return a == b case (.orderedDictionary, _): return false } } } // MARK: JSON Encoding extension JSON { /// Encode a JSON item into a string of bytes. public func toBytes(prettyPrint: Bool = false) -> ByteString { let stream = BufferedOutputByteStream() write(to: stream, indent: prettyPrint ? 0 : nil) if prettyPrint { stream.write("\n") } return stream.bytes } /// Encode a JSON item into a JSON string public func toString(prettyPrint: Bool = false) -> String { guard let contents = self.toBytes(prettyPrint: prettyPrint).asString else { fatalError("Failed to serialize JSON: \(self)") } return contents } } /// Support writing to a byte stream. extension JSON: ByteStreamable { public func write(to stream: OutputByteStream) { write(to: stream, indent: nil) } public func write(to stream: OutputByteStream, indent: Int?) { func indentStreamable(offset: Int? = nil) -> ByteStreamable { return Format.asRepeating(string: " ", count: indent.flatMap({ $0 + (offset ?? 0) }) ?? 0) } let shouldIndent = indent != nil switch self { case .null: stream <<< "null" case .bool(let value): stream <<< Format.asJSON(value) case .int(let value): stream <<< Format.asJSON(value) case .double(let value): // FIXME: What happens for NaN, etc.? stream <<< Format.asJSON(value) case .string(let value): stream <<< Format.asJSON(value) case .array(let contents): stream <<< "[" <<< (shouldIndent ? "\n" : "") for (i, item) in contents.enumerated() { if i != 0 { stream <<< "," <<< (shouldIndent ? "\n" : " ") } stream <<< indentStreamable(offset: 2) item.write(to: stream, indent: indent.flatMap({ $0 + 2 })) } stream <<< (shouldIndent ? "\n" : "") <<< indentStreamable() <<< "]" case .dictionary(let contents): // We always output in a deterministic order. stream <<< "{" <<< (shouldIndent ? "\n" : "") for (i, key) in contents.keys.sorted().enumerated() { if i != 0 { stream <<< "," <<< (shouldIndent ? "\n" : " ") } stream <<< indentStreamable(offset: 2) <<< Format.asJSON(key) <<< ": " contents[key]!.write(to: stream, indent: indent.flatMap({ $0 + 2 })) } stream <<< (shouldIndent ? "\n" : "") <<< indentStreamable() <<< "}" case .orderedDictionary(let contents): stream <<< "{" <<< (shouldIndent ? "\n" : "") for (i, item) in contents.enumerated() { if i != 0 { stream <<< "," <<< (shouldIndent ? "\n" : " ") } stream <<< indentStreamable(offset: 2) <<< Format.asJSON(item.key) <<< ": " item.value.write(to: stream, indent: indent.flatMap({ $0 + 2 })) } stream <<< (shouldIndent ? "\n" : "") <<< indentStreamable() <<< "}" } } } // MARK: JSON Decoding import Foundation enum JSONDecodingError: Swift.Error { /// The input byte string is malformed. case malformed } // NOTE: This implementation is carefully crafted to work correctly on both // Linux and OS X while still compiling for both. Thus, the implementation takes // Any even though it could take AnyObject on OS X, and it uses converts to // direct Swift types (for Linux) even though those don't apply on OS X. // // This allows the code to be portable, and expose a portable API, but it is not // very efficient. private let nsBooleanType = type(of: NSNumber(value: false)) extension JSON { private static func convertToJSON(_ object: Any) -> JSON { switch object { case is NSNull: return .null case let value as String: return .string(value) case let value as NSNumber: // Check if this is a boolean. // // FIXME: This is all rather unfortunate and expensive. if type(of: value) === nsBooleanType { return .bool(value != 0) } // Check if this is an exact integer. // // FIXME: This is highly questionable. Aside from the performance of // decoding in this fashion, it means clients which truly have // arrays of real numbers will need to be prepared to see either an // .int or a .double. However, for our specific use case we usually // want to get integers out of JSON, and so it seems an ok tradeoff // versus forcing all clients to cast out of a double. let asInt = value.intValue if NSNumber(value: asInt) == value { return .int(asInt) } // Otherwise, we have a floating point number. return .double(value.doubleValue) case let value as NSArray: return .array(value.map(convertToJSON)) case let value as NSDictionary: var result = [String: JSON]() for (key, val) in value { result[key as! String] = convertToJSON(val) } return .dictionary(result) // On Linux, the JSON deserialization handles this. case let asBool as Bool: // This is true on Linux. return .bool(asBool) case let asInt as Int: // This is true on Linux. return .int(asInt) case let asDouble as Double: // This is true on Linux. return .double(asDouble) case let value as [Any]: return .array(value.map(convertToJSON)) case let value as [String: Any]: var result = [String: JSON]() for (key, val) in value { result[key] = convertToJSON(val) } return .dictionary(result) default: fatalError("unexpected object: \(object) \(type(of: object))") } } /// Load a JSON item from a Data object. public init(data: Data) throws { do { let result = try JSONSerialization.jsonObject(with: data, options: [.allowFragments]) // Convert to a native representation. // // FIXME: This is inefficient; eventually, we want a way to do the // loading and not need to copy / traverse all of the data multiple // times. self = JSON.convertToJSON(result) } catch { throw JSONDecodingError.malformed } } /// Load a JSON item from a byte string. public init(bytes: ByteString) throws { try self.init(data: Data(bytes: bytes.contents)) } /// Convenience initalizer for UTF8 encoded strings. /// /// - Throws: JSONDecodingError public init(string: String) throws { let bytes = ByteString(encodingAsUTF8: string) try self.init(bytes: bytes) } } // MARK: - JSONSerializable helpers. extension JSON { public init(_ dict: [String: JSONSerializable]) { self = .dictionary(Dictionary(items: dict.map({ ($0.0, $0.1.toJSON()) }))) } } extension Int: JSONSerializable { public func toJSON() -> JSON { return .int(self) } } extension Double: JSONSerializable { public func toJSON() -> JSON { return .double(self) } } extension String: JSONSerializable { public func toJSON() -> JSON { return .string(self) } } extension Bool: JSONSerializable { public func toJSON() -> JSON { return .bool(self) } } extension AbsolutePath: JSONSerializable { public func toJSON() -> JSON { return .string(asString) } } extension RelativePath: JSONSerializable { public func toJSON() -> JSON { return .string(asString) } } extension Optional where Wrapped: JSONSerializable { public func toJSON() -> JSON { switch self { case .some(let wrapped): return wrapped.toJSON() case .none: return .null } } } extension Sequence where Iterator.Element: JSONSerializable { public func toJSON() -> JSON { return .array(map({ $0.toJSON() })) } } extension JSON: JSONSerializable { public func toJSON() -> JSON { return self } }
apache-2.0
9cc70ac56f10b8421605fce4ef3eca61
32.084548
102
0.579133
4.513922
false
false
false
false
apple/swift-nio
Tests/NIOPosixTests/SystemTest+XCTest.swift
1
1391
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2017-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 // //===----------------------------------------------------------------------===// // // SystemTest+XCTest.swift // import XCTest /// /// NOTE: This file was generated by generate_linux_tests.rb /// /// Do NOT edit this file directly as it will be regenerated automatically when needed. /// extension SystemTest { @available(*, deprecated, message: "not actually deprecated. Just deprecated to allow deprecated tests (which test deprecated functionality) without warnings") static var allTests : [(String, (SystemTest) -> () throws -> Void)] { return [ ("testSystemCallWrapperPerformance", testSystemCallWrapperPerformance), ("testErrorsWorkCorrectly", testErrorsWorkCorrectly), ("testCmsgFirstHeader", testCmsgFirstHeader), ("testCMsgNextHeader", testCMsgNextHeader), ("testCMsgData", testCMsgData), ("testCMsgCollection", testCMsgCollection), ] } }
apache-2.0
1c27ef7193221dc7b0a21287e11e4a9a
34.666667
162
0.602444
5.076642
false
true
false
false
27629678/web_dev
client/Pods/FileBrowser/FileBrowser/WebviewPreviewViewContoller.swift
3
3865
// // WebviewPreviewViewContoller.swift // FileBrowser // // Created by Roy Marmelstein on 16/02/2016. // Copyright © 2016 Roy Marmelstein. All rights reserved. // import UIKit import WebKit /// Webview for rendering items QuickLook will struggle with. class WebviewPreviewViewContoller: UIViewController { var webView = WKWebView() var file: FBFile? { didSet { self.title = file?.displayName self.processForDisplay() } } //MARK: Lifecycle override func viewDidLoad() { super.viewDidLoad() self.view.addSubview(webView) // Add share button let shareButton = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(WebviewPreviewViewContoller.shareFile)) self.navigationItem.rightBarButtonItem = shareButton } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() webView.frame = self.view.bounds } //MARK: Share func shareFile() { guard let file = file else { return } let activityViewController = UIActivityViewController(activityItems: [file.filePath], applicationActivities: nil) self.present(activityViewController, animated: true, completion: nil) } //MARK: Processing func processForDisplay() { guard let file = file, let data = try? Data(contentsOf: file.filePath as URL) else { return } var rawString: String? // Prepare plist for display if file.type == .PLIST { do { if let plistDescription = try (PropertyListSerialization.propertyList(from: data, options: [], format: nil) as AnyObject).description { rawString = plistDescription } } catch {} } // Prepare json file for display else if file.type == .JSON { do { let jsonObject = try JSONSerialization.jsonObject(with: data, options: []) if JSONSerialization.isValidJSONObject(jsonObject) { let prettyJSON = try JSONSerialization.data(withJSONObject: jsonObject, options: .prettyPrinted) var jsonString = String(data: prettyJSON, encoding: String.Encoding.utf8) // Unescape forward slashes jsonString = jsonString?.replacingOccurrences(of: "\\/", with: "/") rawString = jsonString } } catch {} } // Default prepare for display if rawString == nil { rawString = String(data: data, encoding: String.Encoding.utf8) } // Convert and display string if let convertedString = convertSpecialCharacters(rawString) { let htmlString = "<html><head><meta name='viewport' content='initial-scale=1.0, user-scalable=no'></head><body><pre>\(convertedString)</pre></body></html>" webView.loadHTMLString(htmlString, baseURL: nil) } } // Make sure we convert HTML special characters // Code from https://gist.github.com/mikesteele/70ae98d04fdc35cb1d5f func convertSpecialCharacters(_ string: String?) -> String? { guard let string = string else { return nil } var newString = string let char_dictionary = [ "&amp;": "&", "&lt;": "<", "&gt;": ">", "&quot;": "\"", "&apos;": "'" ]; for (escaped_char, unescaped_char) in char_dictionary { newString = newString.replacingOccurrences(of: escaped_char, with: unescaped_char, options: NSString.CompareOptions.regularExpression, range: nil) } return newString } }
mit
5e4e85f6a4eb9f5bdffc2382a5e7c11a
32.6
167
0.584627
5.172691
false
false
false
false
realm/SwiftLint
Source/SwiftLintFramework/Rules/Idiomatic/PreferZeroOverExplicitInitRule.swift
1
5296
import SwiftSyntax struct PreferZeroOverExplicitInitRule: SwiftSyntaxCorrectableRule, OptInRule, ConfigurationProviderRule { var configuration = SeverityConfiguration(.warning) static let description = RuleDescription( identifier: "prefer_zero_over_explicit_init", name: "Prefer Zero Over Explicit Init", description: "Prefer `.zero` over explicit init with zero parameters (e.g. `CGPoint(x: 0, y: 0)`)", kind: .idiomatic, nonTriggeringExamples: [ Example("CGRect(x: 0, y: 0, width: 0, height: 1)"), Example("CGPoint(x: 0, y: -1)"), Example("CGSize(width: 2, height: 4)"), Example("CGVector(dx: -5, dy: 0)"), Example("UIEdgeInsets(top: 0, left: 1, bottom: 0, right: 1)") ], triggeringExamples: [ Example("↓CGPoint(x: 0, y: 0)"), Example("↓CGPoint(x: 0.000000, y: 0)"), Example("↓CGPoint(x: 0.000000, y: 0.000)"), Example("↓CGRect(x: 0, y: 0, width: 0, height: 0)"), Example("↓CGSize(width: 0, height: 0)"), Example("↓CGVector(dx: 0, dy: 0)"), Example("↓UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)") ], corrections: [ Example("↓CGPoint(x: 0, y: 0)"): Example("CGPoint.zero"), Example("(↓CGPoint(x: 0, y: 0))"): Example("(CGPoint.zero)"), Example("↓CGRect(x: 0, y: 0, width: 0, height: 0)"): Example("CGRect.zero"), Example("↓CGSize(width: 0, height: 0.000)"): Example("CGSize.zero"), Example("↓CGVector(dx: 0, dy: 0)"): Example("CGVector.zero"), Example("↓UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)"): Example("UIEdgeInsets.zero") ] ) init() {} func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor { Visitor(viewMode: .sourceAccurate) } func makeRewriter(file: SwiftLintFile) -> ViolationsSyntaxRewriter? { Rewriter( locationConverter: file.locationConverter, disabledRegions: disabledRegions(file: file) ) } } private extension PreferZeroOverExplicitInitRule { final class Visitor: ViolationsSyntaxVisitor { override func visitPost(_ node: FunctionCallExprSyntax) { if node.hasViolation { violations.append(node.positionAfterSkippingLeadingTrivia) } } } private final class Rewriter: SyntaxRewriter, ViolationsSyntaxRewriter { private(set) var correctionPositions: [AbsolutePosition] = [] let locationConverter: SourceLocationConverter let disabledRegions: [SourceRange] init(locationConverter: SourceLocationConverter, disabledRegions: [SourceRange]) { self.locationConverter = locationConverter self.disabledRegions = disabledRegions } override func visit(_ node: FunctionCallExprSyntax) -> ExprSyntax { guard node.hasViolation, let name = node.name, !node.isContainedIn(regions: disabledRegions, locationConverter: locationConverter) else { return super.visit(node) } correctionPositions.append(node.positionAfterSkippingLeadingTrivia) let newNode: MemberAccessExprSyntax = "\(name).zero" return super.visit( newNode .withLeadingTrivia(node.leadingTrivia ?? .zero) .withTrailingTrivia(node.trailingTrivia ?? .zero) ) } } } private extension FunctionCallExprSyntax { var hasViolation: Bool { isCGPointZeroCall || isCGSizeCall || isCGRectCall || isCGVectorCall || isUIEdgeInsetsCall } var isCGPointZeroCall: Bool { return name == "CGPoint" && argumentNames == ["x", "y"] && argumentsAreAllZero } var isCGSizeCall: Bool { return name == "CGSize" && argumentNames == ["width", "height"] && argumentsAreAllZero } var isCGRectCall: Bool { return name == "CGRect" && argumentNames == ["x", "y", "width", "height"] && argumentsAreAllZero } var isCGVectorCall: Bool { return name == "CGVector" && argumentNames == ["dx", "dy"] && argumentsAreAllZero } var isUIEdgeInsetsCall: Bool { return name == "UIEdgeInsets" && argumentNames == ["top", "left", "bottom", "right"] && argumentsAreAllZero } var name: String? { guard let expr = calledExpression.as(IdentifierExprSyntax.self) else { return nil } return expr.identifier.text } var argumentNames: [String?] { argumentList.map(\.label?.text) } var argumentsAreAllZero: Bool { argumentList.allSatisfy { arg in if let intExpr = arg.expression.as(IntegerLiteralExprSyntax.self) { return intExpr.isZero } else if let floatExpr = arg.expression.as(FloatLiteralExprSyntax.self) { return floatExpr.isZero } else { return false } } } }
mit
7d83872c87a0d200bdc9a0a561f2b37b
33.900662
108
0.576281
4.87963
false
false
false
false
keshavvishwkarma/KVConstraintKit
KVConstraintKit/NSLayoutConstraintExtension.swift
1
6082
// // NSLayoutConstraintExtension.swift // https://github.com/keshavvishwkarma/KVConstraintKit.git // // Distributed under the MIT License. // // Copyright © 2016-2017 Keshav Vishwkarma <[email protected]>. 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. // #if os(iOS) || os(tvOS) import UIKit #else import AppKit #endif public enum SelfAttribute: Int { case width = 7, height, aspectRatio = 64 func attribute()-> (LayoutAttribute,LayoutAttribute){ if self == .aspectRatio { return (.width, .height) }else{ return (LayoutAttribute(rawValue: self.rawValue)!, .notAnAttribute ) } } } extension NSLayoutConstraint { public struct Defualt { #if os(iOS) || os(tvOS) public static let iPadRatio = CGFloat(3.0/4.0) #endif public static let lessMaxPriority = CGFloat(999.99996) } /// :name: prepareConstraint public final class func prepareConstraint(_ item: Any, attribute attr1: LayoutAttribute, relation: LayoutRelation = .equal, toItem: Any?=nil, attribute attr2: LayoutAttribute = .notAnAttribute, multiplier: CGFloat = 1.0, constant: CGFloat = 0) -> NSLayoutConstraint { return NSLayoutConstraint(item: item, attribute: attr1, relatedBy: relation, toItem: toItem, attribute: attr2, multiplier: multiplier, constant: constant) } } extension NSLayoutConstraint { public final func isEqualTo(constraint c:NSLayoutConstraint, shouldIgnoreMutiplier m:Bool = true, shouldIgnoreRelation r:Bool = true)-> Bool { var isEqualExceptMultiplier = firstItem === c.firstItem && firstAttribute == c.firstAttribute && secondItem === c.secondItem && secondAttribute == c.secondAttribute if !isEqualExceptMultiplier { isEqualExceptMultiplier = firstItem === c.secondItem && firstAttribute == c.secondAttribute && secondItem === c.firstItem && secondAttribute == c.firstAttribute } log(isEqualExceptMultiplier) if m && r { return isEqualExceptMultiplier } else if m { return isEqualExceptMultiplier && multiplier == c.multiplier } else if r { return isEqualExceptMultiplier && relation == c.relation } return isEqualExceptMultiplier && multiplier == c.multiplier && relation == c.relation } public final func reversed() -> NSLayoutConstraint { if let secondItemObj = secondItem { return NSLayoutConstraint(item: secondItemObj, attribute: secondAttribute, relatedBy: relation, toItem: firstItem, attribute: firstAttribute, multiplier: multiplier, constant: constant) } else { return self } } public final func modified(relation r: LayoutRelation) -> NSLayoutConstraint? { if relation == r { return self } #if swift(>=4.0) || (!swift(>=4.0) && os(OSX)) guard let firstItem = self.firstItem else { return nil } #endif return NSLayoutConstraint(item: firstItem, attribute: firstAttribute, relatedBy: r, toItem: secondItem, attribute: secondAttribute, multiplier: multiplier, constant: constant) } public final func modified(multiplier m: CGFloat) -> NSLayoutConstraint? { if multiplier == m { return self } #if swift(>=4.0) || (!swift(>=4.0) && os(OSX)) guard let firstItem = self.firstItem else { return nil } #endif return NSLayoutConstraint(item: firstItem, attribute: firstAttribute, relatedBy: relation, toItem: secondItem, attribute: secondAttribute, multiplier: m, constant: constant) } internal final func isSelfConstraint() -> Bool { // For aspect Ratio if firstItem === secondItem && ( firstAttribute == .width && secondAttribute == .height || firstAttribute == .height && secondAttribute == .width){ return true } if (secondItem == nil && secondAttribute == .notAnAttribute) && (firstAttribute == .width || firstAttribute == .height) { return true } return false } } extension Array where Element: NSLayoutConstraint { internal func containsApplied(constraint c: Element, shouldIgnoreMutiplier m:Bool = true) -> Element? { #if os(iOS) || os(tvOS) let reverseConstraints = reversed().filter { !( $0.firstItem is UILayoutSupport || $0.secondItem is UILayoutSupport) } #else let reverseConstraints = reversed() #endif return reverseConstraints.filter { $0.isEqualTo(constraint: c, shouldIgnoreMutiplier: m) }.first } } internal func log( disable: Bool = true, _ args: Any...) { if !disable { var messageFormat = "" args.forEach { messageFormat.append( " " + String(describing: $0) ) } print( "👀 KVConstraintKit :", messageFormat ) } }
mit
b6ba395eab9be79ed20e15d27924b395
38.467532
271
0.654163
4.819984
false
false
false
false
cnbin/WordPress-iOS
WordPress/Classes/ViewRelated/Notifications/Views/NoteTableHeaderView.swift
6
2731
import Foundation /** * @class NoteTableHeaderView * @brief This class renders a view with top and bottom separators, meant to be used as UITableView * section header in NotificationsViewController. */ @objc public class NoteTableHeaderView : UIView { // MARK: - Public Properties public var title: String? { set { // For layout reasons, we need to ensure that the titleLabel uses an exact Paragraph Height! let unwrappedTitle = newValue?.uppercaseStringWithLocale(NSLocale.currentLocale()) ?? String() let attributes = Style.sectionHeaderRegularStyle titleLabel.attributedText = NSAttributedString(string: unwrappedTitle, attributes: attributes) setNeedsLayout() } get { return titleLabel.text } } public var separatorColor: UIColor? { set { layoutView.bottomColor = newValue ?? UIColor.clearColor() layoutView.topColor = newValue ?? UIColor.clearColor() } get { return layoutView.bottomColor } } // MARK: - Convenience Initializers public convenience init() { self.init(frame: CGRectZero) } required override public init(frame: CGRect) { super.init(frame: frame) setupView() } required public init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! setupView() } // MARK - Private Helpers private func setupView() { NSBundle.mainBundle().loadNibNamed("NoteTableHeaderView", owner: self, options: nil) addSubview(contentView) // Make sure the Outlets are loaded assert(contentView != nil) assert(layoutView != nil) assert(imageView != nil) assert(titleLabel != nil) // Layout contentView.translatesAutoresizingMaskIntoConstraints = false pinSubviewToAllEdges(contentView) // Background + Separators backgroundColor = UIColor.clearColor() layoutView.backgroundColor = Style.sectionHeaderBackgroundColor layoutView.bottomVisible = true layoutView.topVisible = true } // MARK: - Aliases typealias Style = WPStyleGuide.Notifications // MARK: - Static Properties public static let headerHeight = CGFloat(26) // MARK: - Outlets @IBOutlet private var contentView: UIView! @IBOutlet private var layoutView: SeparatorsView! @IBOutlet private var imageView: UIImageView! @IBOutlet private var titleLabel: UILabel! }
gpl-2.0
0a982cec090b298dac436b3e65da4bdf
28.684783
106
0.609301
5.539554
false
false
false
false
yunfeng1299/XQ_IDYLive
Imitate_DY/Imitate_DY/Classes/Main/View/ChannelContentView.swift
1
5379
// // ChannelContentView.swift // Imitate_DY // // Created by 夏琪 on 2017/5/4. // Copyright © 2017年 yunfeng. All rights reserved. // import UIKit //自定义代理(联动) protocol ChanelContentViewDelegate : class { func channelContentView(_ contentView : ChannelContentView, progress : CGFloat, sourceIndex : Int, targetIndex : Int) } private let ContentCellID = "channelContentCell" class ChannelContentView: UIView { //定义属性: fileprivate var childVcs : [UIViewController] fileprivate weak var parentViewController : UIViewController? fileprivate var startOffsetX : CGFloat = 0 fileprivate var isForbidScrollDelegate : Bool = false weak var delegate : ChanelContentViewDelegate? //懒加载控件: fileprivate lazy var collectionView:UICollectionView = {[weak self] in let layout = UICollectionViewFlowLayout() layout.itemSize = (self?.bounds.size)! layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.scrollDirection = .horizontal let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout) collectionView.showsHorizontalScrollIndicator = false collectionView.isPagingEnabled = true collectionView.bounces = false collectionView.dataSource = self collectionView.delegate = self collectionView.scrollsToTop = false //注册cell collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: ContentCellID) return collectionView }() init(frame:CGRect,childVcs:[UIViewController],parentViewController:UIViewController?) { self.childVcs = childVcs self.parentViewController = parentViewController super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } //搭建界面: extension ChannelContentView { fileprivate func setupUI() { for childVc in childVcs { parentViewController?.addChildViewController(childVc) } addSubview(collectionView) collectionView.frame = bounds } } //MARK: - colectionView代理方法: extension ChannelContentView:UICollectionViewDelegate { func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { isForbidScrollDelegate = false startOffsetX = scrollView.contentOffset.x } func scrollViewDidScroll(_ scrollView: UIScrollView) { if isForbidScrollDelegate { return } var progress : CGFloat = 0 var sourceIndex : Int = 0 var targetIndex : Int = 0 let currentOffsetX = scrollView.contentOffset.x let scrollViewW = scrollView.bounds.width if currentOffsetX > startOffsetX { progress = currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW) sourceIndex = Int(currentOffsetX / scrollViewW) targetIndex = sourceIndex + 1 if targetIndex >= childVcs.count { targetIndex = childVcs.count - 1 } if currentOffsetX - startOffsetX == scrollViewW { progress = 1 targetIndex = sourceIndex } } else { progress = 1 - (currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW)) targetIndex = Int(currentOffsetX / scrollViewW) sourceIndex = targetIndex + 1 if sourceIndex >= childVcs.count { sourceIndex = childVcs.count - 1 } } //将数值传给代理属性 delegate?.channelContentView(self, progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex) } } //MARK: - collectionView数据源方法 extension ChannelContentView:UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return childVcs.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ContentCellID, for: indexPath) //给每一个cell设置内容: for view in cell.contentView.subviews { view.removeFromSuperview() } let childVc = childVcs[indexPath.item] childVc.view.frame = bounds cell.contentView.addSubview(childVc.view) return cell } } //MARK: - 外界获取到的方法: extension ChannelContentView { func setCurrentIndex(_ currentIndex:Int) { isForbidScrollDelegate = true let offsetX = CGFloat(currentIndex) * collectionView.frame.width collectionView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: false) } }
mit
bd43f559d0250e2001b0efeb4d3c4686
24.960396
121
0.611937
6.15493
false
false
false
false
vishw3/IOSChart-IOS-7.0-Support
VisChart/Classes/Utils/ChartTransformer.swift
2
9442
// // ChartTransformer.swift // Charts // // Created by Daniel Cohen Gindi on 6/3/15. // // 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 UIKit /// Transformer class that contains all matrices and is responsible for transforming values into pixels on the screen and backwards. public class ChartTransformer: NSObject { /// matrix to map the values to the screen pixels internal var _matrixValueToPx = CGAffineTransformIdentity /// matrix for handling the different offsets of the chart internal var _matrixOffset = CGAffineTransformIdentity internal var _viewPortHandler: ChartViewPortHandler public init(viewPortHandler: ChartViewPortHandler) { _viewPortHandler = viewPortHandler; } /// Prepares the matrix that transforms values to pixels. Calculates the scale factors from the charts size and offsets. public func prepareMatrixValuePx(#chartXMin: Float, deltaX: CGFloat, deltaY: CGFloat, chartYMin: Float) { var scaleX = (_viewPortHandler.contentWidth / deltaX); var scaleY = (_viewPortHandler.contentHeight / deltaY); // setup all matrices _matrixValueToPx = CGAffineTransformIdentity; _matrixValueToPx = CGAffineTransformScale(_matrixValueToPx, scaleX, -scaleY); _matrixValueToPx = CGAffineTransformTranslate(_matrixValueToPx, CGFloat(-chartXMin), CGFloat(-chartYMin)); } /// Prepares the matrix that contains all offsets. public func prepareMatrixOffset(inverted: Bool) { if (!inverted) { _matrixOffset = CGAffineTransformMakeTranslation(_viewPortHandler.offsetLeft, _viewPortHandler.chartHeight - _viewPortHandler.offsetBottom); } else { _matrixOffset = CGAffineTransformMakeScale(1.0, -1.0); _matrixOffset = CGAffineTransformTranslate(_matrixOffset, _viewPortHandler.offsetLeft, -_viewPortHandler.offsetTop); } } /// Transforms an arraylist of Entry into a float array containing the x and y values transformed with all matrices for the SCATTERCHART. public func generateTransformedValuesScatter(entries: [ChartDataEntry], phaseY: CGFloat) -> [CGPoint] { var valuePoints = [CGPoint](); valuePoints.reserveCapacity(entries.count); for (var j = 0; j < entries.count; j++) { var e = entries[j]; valuePoints.append(CGPoint(x: CGFloat(e.xIndex), y: CGFloat(e.value) * phaseY)); } pointValuesToPixel(&valuePoints); return valuePoints; } /// Transforms an arraylist of Entry into a float array containing the x and y values transformed with all matrices for the LINECHART. public func generateTransformedValuesLine(entries: [ChartDataEntry], phaseX: CGFloat, phaseY: CGFloat, from: Int, to: Int) -> [CGPoint] { let count = Int(ceil(CGFloat(to - from) * phaseX)); var valuePoints = [CGPoint](); valuePoints.reserveCapacity(count); for (var j = 0; j < count; j++) { var e = entries[j + from]; valuePoints.append(CGPoint(x: CGFloat(e.xIndex), y: CGFloat(e.value) * phaseY)); } pointValuesToPixel(&valuePoints); return valuePoints; } /// Transforms an arraylist of Entry into a float array containing the x and y values transformed with all matrices for the CANDLESTICKCHART. public func generateTransformedValuesCandle(entries: [CandleChartDataEntry], phaseY: CGFloat) -> [CGPoint] { var valuePoints = [CGPoint](); valuePoints.reserveCapacity(entries.count); for (var j = 0; j < entries.count; j++) { var e = entries[j]; valuePoints.append(CGPoint(x: CGFloat(e.xIndex), y: CGFloat(e.high) * phaseY)); } pointValuesToPixel(&valuePoints); return valuePoints; } /// Transforms an arraylist of Entry into a float array containing the x and y values transformed with all matrices for the BARCHART. public func generateTransformedValuesBarChart(entries: [BarChartDataEntry], dataSet: Int, barData: BarChartData, phaseY: CGFloat) -> [CGPoint] { var valuePoints = [CGPoint](); valuePoints.reserveCapacity(entries.count); var setCount = barData.dataSetCount; var space = barData.groupSpace; for (var j = 0; j < entries.count; j++) { var e = entries[j]; // calculate the x-position, depending on datasetcount var x = CGFloat(e.xIndex + (j * (setCount - 1)) + dataSet) + space * CGFloat(j) + space / 2.0; var y = e.value; valuePoints.append(CGPoint(x: x, y: CGFloat(y) * phaseY)); } pointValuesToPixel(&valuePoints); return valuePoints; } /// Transforms an arraylist of Entry into a float array containing the x and y values transformed with all matrices for the BARCHART. public func generateTransformedValuesHorizontalBarChart(entries: [ChartDataEntry], dataSet: Int, barData: BarChartData, phaseY: CGFloat) -> [CGPoint] { var valuePoints = [CGPoint](); valuePoints.reserveCapacity(entries.count); var setCount = barData.dataSetCount; var space = barData.groupSpace; for (var j = 0; j < entries.count; j++) { var e = entries[j]; // calculate the x-position, depending on datasetcount var x = CGFloat(e.xIndex + (j * (setCount - 1)) + dataSet) + space * CGFloat(j) + space / 2.0; var y = e.value; valuePoints.append(CGPoint(x: CGFloat(y) * phaseY, y: x)); } pointValuesToPixel(&valuePoints); return valuePoints; } /// Transform an array of points with all matrices. // VERY IMPORTANT: Keep matrix order "value-touch-offset" when transforming. public func pointValuesToPixel(inout pts: [CGPoint]) { var trans = valueToPixelMatrix; for (var i = 0, count = pts.count; i < count; i++) { pts[i] = CGPointApplyAffineTransform(pts[i], trans); } } public func pointValueToPixel(inout point: CGPoint) { point = CGPointApplyAffineTransform(point, valueToPixelMatrix); } /// Transform a rectangle with all matrices. public func rectValueToPixel(inout r: CGRect) { r = CGRectApplyAffineTransform(r, valueToPixelMatrix); } /// Transform a rectangle with all matrices with potential animation phases. public func rectValueToPixel(inout r: CGRect, phaseY: CGFloat) { // multiply the height of the rect with the phase if (r.origin.y > 0.0) { r.origin.y *= phaseY; } else { var bottom = r.origin.y + r.size.height; bottom *= phaseY; r.size.height = bottom - r.origin.y; } r = CGRectApplyAffineTransform(r, valueToPixelMatrix); } /// Transform a rectangle with all matrices with potential animation phases. public func rectValueToPixelHorizontal(inout r: CGRect, phaseY: CGFloat) { // multiply the height of the rect with the phase if (r.origin.x > 0.0) { r.origin.x *= phaseY; } else { var right = r.origin.x + r.size.width; right *= phaseY; r.size.width = right - r.origin.x; } r = CGRectApplyAffineTransform(r, valueToPixelMatrix); } /// transforms multiple rects with all matrices public func rectValuesToPixel(inout rects: [CGRect]) { var trans = valueToPixelMatrix; for (var i = 0; i < rects.count; i++) { rects[i] = CGRectApplyAffineTransform(rects[i], trans); } } /// Transforms the given array of touch points (pixels) into values on the chart. public func pixelsToValue(inout pixels: [CGPoint]) { var trans = pixelToValueMatrix; for (var i = 0; i < pixels.count; i++) { pixels[i] = CGPointApplyAffineTransform(pixels[i], trans); } } /// Transforms the given touch point (pixels) into a value on the chart. public func pixelToValue(inout pixel: CGPoint) { pixel = CGPointApplyAffineTransform(pixel, pixelToValueMatrix); } /// Returns the x and y values in the chart at the given touch point /// (encapsulated in a PointD). This method transforms pixel coordinates to /// coordinates / values in the chart. public func getValueByTouchPoint(point: CGPoint) -> CGPoint { return CGPointApplyAffineTransform(point, pixelToValueMatrix); } public var valueToPixelMatrix: CGAffineTransform { return CGAffineTransformConcat( CGAffineTransformConcat( _matrixValueToPx, _viewPortHandler.touchMatrix ), _matrixOffset ); } public var pixelToValueMatrix: CGAffineTransform { return CGAffineTransformInvert(valueToPixelMatrix); } }
mit
9da0d091d4c15ac9ccad30605a692f7c
33.716912
153
0.624868
5.025013
false
false
false
false
Bluthwort/Bluthwort
Sources/Classes/UI/ButtonTableViewCell.swift
1
2197
// // ButtonTableViewCell.swift // // Copyright (c) 2018 Bluthwort // // 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. // private let kDefaultButtonHeight: CGFloat = 44.0 open class ButtonTableViewCell: UITableViewCell { // MARK: Properties open let button = UIButton() // MARK: Lifecycle public override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setup() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } private func setup() { backgroundColor = .clear separatorInset = .init(top: 0.0, left: 0.0, bottom: 0.0, right: kScreenWidth) selectionStyle = .none setupSubviews() } // MARK: Subviews Configuration private func setupSubviews() { button.bw.backgroundColor(UIColor.bw.init(hex: 0x007AFF)).add(to: self) { $0.top.leading.equalToSuperview().offset(kMargin12) $0.trailing.bottom.equalToSuperview().offset(-kMargin12) $0.height.equalTo(kDefaultButtonHeight) } } }
mit
1b82d268fea27134cf1c37b6a2544cf7
34.435484
85
0.69868
4.438384
false
false
false
false
matthewpurcell/firefox-ios
ThirdParty/SQLite.swift/Source/Core/Connection.swift
5
23944
// // SQLite.swift // https://github.com/stephencelis/SQLite.swift // Copyright © 2014-2015 Stephen Celis. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Dispatch /// A connection to SQLite. public final class Connection { /// The location of a SQLite database. public enum Location { /// An in-memory database (equivalent to `.URI(":memory:")`). /// /// See: <https://www.sqlite.org/inmemorydb.html#sharedmemdb> case InMemory /// A temporary, file-backed database (equivalent to `.URI("")`). /// /// See: <https://www.sqlite.org/inmemorydb.html#temp_db> case Temporary /// A database located at the given URI filename (or path). /// /// See: <https://www.sqlite.org/uri.html> /// /// - Parameter filename: A URI filename case URI(String) } public var handle: COpaquePointer { return _handle } private var _handle: COpaquePointer = nil /// Initializes a new SQLite connection. /// /// - Parameters: /// /// - location: The location of the database. Creates a new database if it /// doesn’t already exist (unless in read-only mode). /// /// Default: `.InMemory`. /// /// - readonly: Whether or not to open the database in a read-only state. /// /// Default: `false`. /// /// - Returns: A new database connection. public init(_ location: Location = .InMemory, readonly: Bool = false) throws { let flags = readonly ? SQLITE_OPEN_READONLY : SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE try check(sqlite3_open_v2(location.description, &_handle, flags | SQLITE_OPEN_FULLMUTEX, nil)) dispatch_queue_set_specific(queue, Connection.queueKey, queueContext, nil) } /// Initializes a new connection to a database. /// /// - Parameters: /// /// - filename: The location of the database. Creates a new database if /// it doesn’t already exist (unless in read-only mode). /// /// - readonly: Whether or not to open the database in a read-only state. /// /// Default: `false`. /// /// - Throws: `Result.Error` iff a connection cannot be established. /// /// - Returns: A new database connection. public convenience init(_ filename: String, readonly: Bool = false) throws { try self.init(.URI(filename), readonly: readonly) } deinit { sqlite3_close_v2(handle) } // MARK: - /// Whether or not the database was opened in a read-only state. public var readonly: Bool { return sqlite3_db_readonly(handle, nil) == 1 } /// The last rowid inserted into the database via this connection. public var lastInsertRowid: Int64? { let rowid = sqlite3_last_insert_rowid(handle) return rowid > 0 ? rowid : nil } /// The last number of changes (inserts, updates, or deletes) made to the /// database via this connection. public var changes: Int { return Int(sqlite3_changes(handle)) } /// The total number of changes (inserts, updates, or deletes) made to the /// database via this connection. public var totalChanges: Int { return Int(sqlite3_total_changes(handle)) } // MARK: - Execute /// Executes a batch of SQL statements. /// /// - Parameter SQL: A batch of zero or more semicolon-separated SQL /// statements. /// /// - Throws: `Result.Error` if query execution fails. public func execute(SQL: String) throws { try sync { try check(sqlite3_exec(self.handle, SQL, nil, nil, nil)) } } // MARK: - Prepare /// Prepares a single SQL statement (with optional parameter bindings). /// /// - Parameters: /// /// - statement: A single SQL statement. /// /// - bindings: A list of parameters to bind to the statement. /// /// - Returns: A prepared statement. @warn_unused_result public func prepare(statement: String, _ bindings: Binding?...) -> Statement { if !bindings.isEmpty { return prepare(statement, bindings) } return Statement(self, statement) } /// Prepares a single SQL statement and binds parameters to it. /// /// - Parameters: /// /// - statement: A single SQL statement. /// /// - bindings: A list of parameters to bind to the statement. /// /// - Returns: A prepared statement. @warn_unused_result public func prepare(statement: String, _ bindings: [Binding?]) -> Statement { return prepare(statement).bind(bindings) } /// Prepares a single SQL statement and binds parameters to it. /// /// - Parameters: /// /// - statement: A single SQL statement. /// /// - bindings: A dictionary of named parameters to bind to the statement. /// /// - Returns: A prepared statement. @warn_unused_result public func prepare(statement: String, _ bindings: [String: Binding?]) -> Statement { return prepare(statement).bind(bindings) } // MARK: - Run /// Runs a single SQL statement (with optional parameter bindings). /// /// - Parameters: /// /// - statement: A single SQL statement. /// /// - bindings: A list of parameters to bind to the statement. /// /// - Throws: `Result.Error` if query execution fails. /// /// - Returns: The statement. public func run(statement: String, _ bindings: Binding?...) throws -> Statement { return try run(statement, bindings) } /// Prepares, binds, and runs a single SQL statement. /// /// - Parameters: /// /// - statement: A single SQL statement. /// /// - bindings: A list of parameters to bind to the statement. /// /// - Throws: `Result.Error` if query execution fails. /// /// - Returns: The statement. public func run(statement: String, _ bindings: [Binding?]) throws -> Statement { return try prepare(statement).run(bindings) } /// Prepares, binds, and runs a single SQL statement. /// /// - Parameters: /// /// - statement: A single SQL statement. /// /// - bindings: A dictionary of named parameters to bind to the statement. /// /// - Throws: `Result.Error` if query execution fails. /// /// - Returns: The statement. public func run(statement: String, _ bindings: [String: Binding?]) throws -> Statement { return try prepare(statement).run(bindings) } // MARK: - Scalar /// Runs a single SQL statement (with optional parameter bindings), /// returning the first value of the first row. /// /// - Parameters: /// /// - statement: A single SQL statement. /// /// - bindings: A list of parameters to bind to the statement. /// /// - Returns: The first value of the first row returned. @warn_unused_result public func scalar(statement: String, _ bindings: Binding?...) -> Binding? { return scalar(statement, bindings) } /// Runs a single SQL statement (with optional parameter bindings), /// returning the first value of the first row. /// /// - Parameters: /// /// - statement: A single SQL statement. /// /// - bindings: A list of parameters to bind to the statement. /// /// - Returns: The first value of the first row returned. @warn_unused_result public func scalar(statement: String, _ bindings: [Binding?]) -> Binding? { return prepare(statement).scalar(bindings) } /// Runs a single SQL statement (with optional parameter bindings), /// returning the first value of the first row. /// /// - Parameters: /// /// - statement: A single SQL statement. /// /// - bindings: A dictionary of named parameters to bind to the statement. /// /// - Returns: The first value of the first row returned. @warn_unused_result public func scalar(statement: String, _ bindings: [String: Binding?]) -> Binding? { return prepare(statement).scalar(bindings) } // MARK: - Transactions /// The mode in which a transaction acquires a lock. public enum TransactionMode : String { /// Defers locking the database till the first read/write executes. case Deferred = "DEFERRED" /// Immediately acquires a reserved lock on the database. case Immediate = "IMMEDIATE" /// Immediately acquires an exclusive lock on all databases. case Exclusive = "EXCLUSIVE" } // TODO: Consider not requiring a throw to roll back? /// Runs a transaction with the given mode. /// /// - Note: Transactions cannot be nested. To nest transactions, see /// `savepoint()`, instead. /// /// - Parameters: /// /// - mode: The mode in which a transaction acquires a lock. /// /// Default: `.Deferred` /// /// - block: A closure to run SQL statements within the transaction. /// The transaction will be committed when the block returns. The block /// must throw to roll the transaction back. /// /// - Throws: `Result.Error`, and rethrows. public func transaction(mode: TransactionMode = .Deferred, block: () throws -> Void) throws { try transaction("BEGIN \(mode.rawValue) TRANSACTION", block, "COMMIT TRANSACTION", or: "ROLLBACK TRANSACTION") } // TODO: Consider not requiring a throw to roll back? // TODO: Consider removing ability to set a name? /// Runs a transaction with the given savepoint name (if omitted, it will /// generate a UUID). /// /// - SeeAlso: `transaction()`. /// /// - Parameters: /// /// - savepointName: A unique identifier for the savepoint (optional). /// /// - block: A closure to run SQL statements within the transaction. /// The savepoint will be released (committed) when the block returns. /// The block must throw to roll the savepoint back. /// /// - Throws: `SQLite.Result.Error`, and rethrows. public func savepoint(name: String = NSUUID().UUIDString, block: () throws -> Void) throws { let name = name.quote("'") let savepoint = "SAVEPOINT \(name)" try transaction(savepoint, block, "RELEASE \(savepoint)", or: "ROLLBACK TO \(savepoint)") } private func transaction(begin: String, _ block: () throws -> Void, _ commit: String, or rollback: String) throws { return try sync { try self.run(begin) do { try block() } catch { try self.run(rollback) throw error } try self.run(commit) } } /// Interrupts any long-running queries. public func interrupt() { sqlite3_interrupt(handle) } // MARK: - Handlers /// The number of seconds a connection will attempt to retry a statement /// after encountering a busy signal (lock). public var busyTimeout: Double = 0 { didSet { sqlite3_busy_timeout(handle, Int32(busyTimeout * 1_000)) } } /// Sets a handler to call after encountering a busy signal (lock). /// /// - Parameter callback: This block is executed during a lock in which a /// busy error would otherwise be returned. It’s passed the number of /// times it’s been called for this lock. If it returns `true`, it will /// try again. If it returns `false`, no further attempts will be made. public func busyHandler(callback: ((tries: Int) -> Bool)?) { guard let callback = callback else { sqlite3_busy_handler(handle, nil, nil) busyHandler = nil return } let box: BusyHandler = { callback(tries: Int($0)) ? 1 : 0 } sqlite3_busy_handler(handle, { callback, tries in unsafeBitCast(callback, BusyHandler.self)(tries) }, unsafeBitCast(box, UnsafeMutablePointer<Void>.self)) busyHandler = box } private typealias BusyHandler = @convention(block) Int32 -> Int32 private var busyHandler: BusyHandler? /// Sets a handler to call when a statement is executed with the compiled /// SQL. /// /// - Parameter callback: This block is invoked when a statement is executed /// with the compiled SQL as its argument. /// /// db.trace { SQL in print(SQL) } public func trace(callback: (String -> Void)?) { guard let callback = callback else { sqlite3_trace(handle, nil, nil) trace = nil return } let box: Trace = { callback(String.fromCString($0)!) } sqlite3_trace(handle, { callback, SQL in unsafeBitCast(callback, Trace.self)(SQL) }, unsafeBitCast(box, UnsafeMutablePointer<Void>.self)) trace = box } private typealias Trace = @convention(block) UnsafePointer<Int8> -> Void private var trace: Trace? /// Registers a callback to be invoked whenever a row is inserted, updated, /// or deleted in a rowid table. /// /// - Parameter callback: A callback invoked with the `Operation` (one of /// `.Insert`, `.Update`, or `.Delete`), database name, table name, and /// rowid. public func updateHook(callback: ((operation: Operation, db: String, table: String, rowid: Int64) -> Void)?) { guard let callback = callback else { sqlite3_update_hook(handle, nil, nil) updateHook = nil return } let box: UpdateHook = { callback( operation: Operation(rawValue: $0), db: String.fromCString($1)!, table: String.fromCString($2)!, rowid: $3 ) } sqlite3_update_hook(handle, { callback, operation, db, table, rowid in unsafeBitCast(callback, UpdateHook.self)(operation, db, table, rowid) }, unsafeBitCast(box, UnsafeMutablePointer<Void>.self)) updateHook = box } private typealias UpdateHook = @convention(block) (Int32, UnsafePointer<Int8>, UnsafePointer<Int8>, Int64) -> Void private var updateHook: UpdateHook? /// Registers a callback to be invoked whenever a transaction is committed. /// /// - Parameter callback: A callback invoked whenever a transaction is /// committed. If this callback throws, the transaction will be rolled /// back. public func commitHook(callback: (() throws -> Void)?) { guard let callback = callback else { sqlite3_commit_hook(handle, nil, nil) commitHook = nil return } let box: CommitHook = { do { try callback() } catch { return 1 } return 0 } sqlite3_commit_hook(handle, { callback in unsafeBitCast(callback, CommitHook.self)() }, unsafeBitCast(box, UnsafeMutablePointer<Void>.self)) commitHook = box } private typealias CommitHook = @convention(block) () -> Int32 private var commitHook: CommitHook? /// Registers a callback to be invoked whenever a transaction rolls back. /// /// - Parameter callback: A callback invoked when a transaction is rolled /// back. public func rollbackHook(callback: (() -> Void)?) { guard let callback = callback else { sqlite3_rollback_hook(handle, nil, nil) rollbackHook = nil return } let box: RollbackHook = { callback() } sqlite3_rollback_hook(handle, { callback in unsafeBitCast(callback, RollbackHook.self)() }, unsafeBitCast(box, UnsafeMutablePointer<Void>.self)) rollbackHook = box } private typealias RollbackHook = @convention(block) () -> Void private var rollbackHook: RollbackHook? /// Creates or redefines a custom SQL function. /// /// - Parameters: /// /// - function: The name of the function to create or redefine. /// /// - argumentCount: The number of arguments that the function takes. If /// `nil`, the function may take any number of arguments. /// /// Default: `nil` /// /// - deterministic: Whether or not the function is deterministic (_i.e._ /// the function always returns the same result for a given input). /// /// Default: `false` /// /// - block: A block of code to run when the function is called. The block /// is called with an array of raw SQL values mapped to the function’s /// parameters and should return a raw SQL value (or nil). public func createFunction(function: String, argumentCount: UInt? = nil, deterministic: Bool = false, _ block: (args: [Binding?]) -> Binding?) { let argc = argumentCount.map { Int($0) } ?? -1 let box: Function = { context, argc, argv in let arguments: [Binding?] = (0..<Int(argc)).map { idx in let value = argv[idx] switch sqlite3_value_type(value) { case SQLITE_BLOB: return Blob(bytes: sqlite3_value_blob(value), length: Int(sqlite3_value_bytes(value))) case SQLITE_FLOAT: return sqlite3_value_double(value) case SQLITE_INTEGER: return sqlite3_value_int64(value) case SQLITE_NULL: return nil case SQLITE_TEXT: return String.fromCString(UnsafePointer(sqlite3_value_text(value)))! case let type: fatalError("unsupported value type: \(type)") } } let result = block(args: arguments) if let result = result as? Blob { sqlite3_result_blob(context, result.bytes, Int32(result.bytes.count), nil) } else if let result = result as? Double { sqlite3_result_double(context, result) } else if let result = result as? Int64 { sqlite3_result_int64(context, result) } else if let result = result as? String { sqlite3_result_text(context, result, Int32(result.characters.count), SQLITE_TRANSIENT) } else if result == nil { sqlite3_result_null(context) } else { fatalError("unsupported result type: \(result)") } } var flags = SQLITE_UTF8 if deterministic { flags |= SQLITE_DETERMINISTIC } sqlite3_create_function_v2(handle, function, Int32(argc), flags, unsafeBitCast(box, UnsafeMutablePointer<Void>.self), { context, argc, value in unsafeBitCast(sqlite3_user_data(context), Function.self)(context, argc, value) }, nil, nil, nil) if functions[function] == nil { self.functions[function] = [:] } functions[function]?[argc] = box } private typealias Function = @convention(block) (COpaquePointer, Int32, UnsafeMutablePointer<COpaquePointer>) -> Void private var functions = [String: [Int: Function]]() /// The return type of a collation comparison function. public typealias ComparisonResult = NSComparisonResult /// Defines a new collating sequence. /// /// - Parameters: /// /// - collation: The name of the collation added. /// /// - block: A collation function that takes two strings and returns the /// comparison result. public func createCollation(collation: String, _ block: (lhs: String, rhs: String) -> ComparisonResult) { let box: Collation = { lhs, rhs in Int32(block(lhs: String.fromCString(UnsafePointer<Int8>(lhs))!, rhs: String.fromCString(UnsafePointer<Int8>(rhs))!).rawValue) } try! check(sqlite3_create_collation_v2(handle, collation, SQLITE_UTF8, unsafeBitCast(box, UnsafeMutablePointer<Void>.self), { callback, _, lhs, _, rhs in unsafeBitCast(callback, Collation.self)(lhs, rhs) }, nil)) collations[collation] = box } private typealias Collation = @convention(block) (UnsafePointer<Void>, UnsafePointer<Void>) -> Int32 private var collations = [String: Collation]() // MARK: - Error Handling func sync<T>(block: () throws -> T) rethrows -> T { var success: T? var failure: ErrorType? let box: () -> Void = { do { success = try block() } catch { failure = error } } if dispatch_get_specific(Connection.queueKey) == queueContext { box() } else { dispatch_sync(queue, box) // FIXME: rdar://problem/21389236 } if let failure = failure { try { () -> Void in throw failure }() } return success! } private var queue = dispatch_queue_create("SQLite.Database", DISPATCH_QUEUE_SERIAL) private static let queueKey = unsafeBitCast(Connection.self, UnsafePointer<Void>.self) private lazy var queueContext: UnsafeMutablePointer<Void> = unsafeBitCast(self, UnsafeMutablePointer<Void>.self) } extension Connection : CustomStringConvertible { public var description: String { return String.fromCString(sqlite3_db_filename(handle, nil))! } } extension Connection.Location : CustomStringConvertible { public var description: String { switch self { case .InMemory: return ":memory:" case .Temporary: return "" case .URI(let URI): return URI } } } /// An SQL operation passed to update callbacks. public enum Operation { /// An INSERT operation. case Insert /// An UPDATE operation. case Update /// A DELETE operation. case Delete private init(rawValue: Int32) { switch rawValue { case SQLITE_INSERT: self = .Insert case SQLITE_UPDATE: self = .Update case SQLITE_DELETE: self = .Delete default: fatalError("unhandled operation code: \(rawValue)") } } } public enum Result : ErrorType { private static let successCodes: Set = [SQLITE_OK, SQLITE_ROW, SQLITE_DONE] case Error(code: Int32, statement: Statement?) init?(errorCode: Int32, statement: Statement? = nil) { guard !Result.successCodes.contains(errorCode) else { return nil } self = Error(code: errorCode, statement: statement) } } extension Result : CustomStringConvertible { public var description: String { switch self { case .Error(let code, _): return String.fromCString(sqlite3_errstr(code))! } } }
mpl-2.0
6317d906af46b642a5daab0c004bd403
34.403846
161
0.603435
4.495304
false
false
false
false
Prodisky/LASS-Dial
StyleKitDial.swift
1
10766
// // StyleKitDial.swift // LASS Dial // // Created by Paul Wu on 2016/2/4. // Copyright (c) 2016 Prodisky Inc. All rights reserved. // // Generated by PaintCode (www.paintcodeapp.com) // import UIKit public class StyleKitDial : NSObject { //// Drawing Methods public class func drawRing(value value: CGFloat = 0.14, colorR: CGFloat = 1, colorG: CGFloat = 1, colorB: CGFloat = 1, colorA: CGFloat = 1) { //// General Declarations let context = UIGraphicsGetCurrentContext() //// Color Declarations let colorRingBack = UIColor(red: 1.000, green: 1.000, blue: 1.000, alpha: 0.200) //// Variable Declarations let expressionAngle: CGFloat = -value * 360 let expressionColor = UIColor(red: colorR, green: colorG, blue: colorB, alpha: colorA) //// Oval Line Back Drawing CGContextSaveGState(context) CGContextTranslateCTM(context, 100, 100) CGContextRotateCTM(context, -90 * CGFloat(M_PI) / 180) let ovalLineBackPath = UIBezierPath(ovalInRect: CGRectMake(-91, -91, 182, 182)) colorRingBack.setStroke() ovalLineBackPath.lineWidth = 16 ovalLineBackPath.stroke() CGContextRestoreGState(context) //// Oval Line Drawing CGContextSaveGState(context) CGContextTranslateCTM(context, 100, 100) CGContextRotateCTM(context, -90 * CGFloat(M_PI) / 180) let ovalLineRect = CGRectMake(-91, -91, 182, 182) let ovalLinePath = UIBezierPath() ovalLinePath.addArcWithCenter(CGPointMake(ovalLineRect.midX, ovalLineRect.midY), radius: ovalLineRect.width / 2, startAngle: 0 * CGFloat(M_PI)/180, endAngle: -expressionAngle * CGFloat(M_PI)/180, clockwise: true) expressionColor.setStroke() ovalLinePath.lineWidth = 16 ovalLinePath.stroke() CGContextRestoreGState(context) //// Oval Line Back 2 Drawing CGContextSaveGState(context) CGContextTranslateCTM(context, 100, 100) CGContextRotateCTM(context, -90 * CGFloat(M_PI) / 180) let ovalLineBack2Path = UIBezierPath(ovalInRect: CGRectMake(-78, -78, 156, 156)) colorRingBack.setFill() ovalLineBack2Path.fill() CGContextRestoreGState(context) } public class func drawDataItem(frame frame: CGRect = CGRectMake(0, 0, 240, 320), name: String = "PM 2.5", data: String = "35", unit: String = "μg/m3", value: CGFloat = 0.14, station: String = "臺東 1.4KM", time: String = "2016/01/23 14:31", colorR: CGFloat = 1, colorG: CGFloat = 1, colorB: CGFloat = 1, colorA: CGFloat = 1) { //// General Declarations let context = UIGraphicsGetCurrentContext() //// Symbol Time Drawing let symbolTimeRect = CGRectMake(frame.minX + floor(frame.width * 0.08333 + 0.5), frame.minY + floor(frame.height * 0.90000 + 0.5), floor(frame.width * 0.91667 + 0.5) - floor(frame.width * 0.08333 + 0.5), floor(frame.height * 0.97500 + 0.5) - floor(frame.height * 0.90000 + 0.5)) CGContextSaveGState(context) UIRectClip(symbolTimeRect) CGContextTranslateCTM(context, symbolTimeRect.origin.x, symbolTimeRect.origin.y) CGContextScaleCTM(context, symbolTimeRect.size.width / 200, symbolTimeRect.size.height / 24) StyleKitDial.drawCenterText(label: time, colorR: colorR, colorG: colorG, colorB: colorB, colorA: colorA) CGContextRestoreGState(context) //// Symbol Station Drawing let symbolStationRect = CGRectMake(frame.minX + floor(frame.width * -0.12500 + 0.5), frame.minY + floor(frame.height * 0.78750 + 0.5), floor(frame.width * 1.12500 + 0.5) - floor(frame.width * -0.12500 + 0.5), floor(frame.height * 0.90000 + 0.5) - floor(frame.height * 0.78750 + 0.5)) CGContextSaveGState(context) UIRectClip(symbolStationRect) CGContextTranslateCTM(context, symbolStationRect.origin.x, symbolStationRect.origin.y) CGContextScaleCTM(context, symbolStationRect.size.width / 200, symbolStationRect.size.height / 24) StyleKitDial.drawCenterText(label: station, colorR: colorR, colorG: colorG, colorB: colorB, colorA: colorA) CGContextRestoreGState(context) //// Symbol Name Drawing let symbolNameRect = CGRectMake(frame.minX + floor(frame.width * -0.33333 + 0.5), frame.minY + floor(frame.height * 0.01875 + 0.5), floor(frame.width * 1.33333 + 0.5) - floor(frame.width * -0.33333 + 0.5), floor(frame.height * 0.16875 + 0.5) - floor(frame.height * 0.01875 + 0.5)) CGContextSaveGState(context) UIRectClip(symbolNameRect) CGContextTranslateCTM(context, symbolNameRect.origin.x, symbolNameRect.origin.y) CGContextScaleCTM(context, symbolNameRect.size.width / 200, symbolNameRect.size.height / 24) StyleKitDial.drawCenterText(label: name, colorR: colorR, colorG: colorG, colorB: colorB, colorA: colorA) CGContextRestoreGState(context) //// Symbol Ring Drawing let symbolRingRect = CGRectMake(frame.minX + floor(frame.width * 0.08333 + 0.5), frame.minY + floor(frame.height * 0.15625 + 0.5), floor(frame.width * 0.91667 + 0.5) - floor(frame.width * 0.08333 + 0.5), floor(frame.height * 0.78125 + 0.5) - floor(frame.height * 0.15625 + 0.5)) CGContextSaveGState(context) UIRectClip(symbolRingRect) CGContextTranslateCTM(context, symbolRingRect.origin.x, symbolRingRect.origin.y) StyleKitDial.drawDataRing(frame: CGRectMake(0, 0, symbolRingRect.size.width, symbolRingRect.size.height), data: data, unit: unit, value: value, colorR: colorR, colorG: colorG, colorB: colorB, colorA: colorA) CGContextRestoreGState(context) } public class func drawCenterText(label label: String = "PM 2.5", colorR: CGFloat = 1, colorG: CGFloat = 1, colorB: CGFloat = 1, colorA: CGFloat = 1) { //// General Declarations let context = UIGraphicsGetCurrentContext() //// Variable Declarations let expressionColor = UIColor(red: colorR, green: colorG, blue: colorB, alpha: colorA) //// Text Drawing let textRect = CGRectMake(0, 0, 200, 24) let textStyle = NSParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle textStyle.alignment = .Center let textFontAttributes = [NSFontAttributeName: UIFont.systemFontOfSize(19), NSForegroundColorAttributeName: expressionColor, NSParagraphStyleAttributeName: textStyle] let textTextHeight: CGFloat = NSString(string: label).boundingRectWithSize(CGSizeMake(textRect.width, CGFloat.infinity), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: textFontAttributes, context: nil).size.height CGContextSaveGState(context) CGContextClipToRect(context, textRect); NSString(string: label).drawInRect(CGRectMake(textRect.minX, textRect.minY + (textRect.height - textTextHeight) / 2, textRect.width, textTextHeight), withAttributes: textFontAttributes) CGContextRestoreGState(context) } public class func drawDataRing(frame frame: CGRect = CGRectMake(0, 0, 200, 200), data: String = "35", unit: String = "μg/m3", value: CGFloat = 0.14, colorR: CGFloat = 1, colorG: CGFloat = 1, colorB: CGFloat = 1, colorA: CGFloat = 1) { //// General Declarations let context = UIGraphicsGetCurrentContext() //// Symbol Ring Drawing let symbolRingRect = CGRectMake(frame.minX + floor(frame.width * 0.00000 + 0.5), frame.minY + floor(frame.height * 0.00000 + 0.5), floor(frame.width * 1.00000 + 0.5) - floor(frame.width * 0.00000 + 0.5), floor(frame.height * 1.00000 + 0.5) - floor(frame.height * 0.00000 + 0.5)) CGContextSaveGState(context) UIRectClip(symbolRingRect) CGContextTranslateCTM(context, symbolRingRect.origin.x, symbolRingRect.origin.y) CGContextScaleCTM(context, symbolRingRect.size.width / 200, symbolRingRect.size.height / 200) StyleKitDial.drawRing(value: value, colorR: colorR, colorG: colorG, colorB: colorB, colorA: colorA) CGContextRestoreGState(context) //// Symbol Data Drawing let symbolDataRect = CGRectMake(frame.minX + floor(frame.width * -1.50000 + 0.5), frame.minY + floor(frame.height * 0.26000 + 0.5), floor(frame.width * 2.50000 + 0.5) - floor(frame.width * -1.50000 + 0.5), floor(frame.height * 0.74000 + 0.5) - floor(frame.height * 0.26000 + 0.5)) CGContextSaveGState(context) UIRectClip(symbolDataRect) CGContextTranslateCTM(context, symbolDataRect.origin.x, symbolDataRect.origin.y) CGContextScaleCTM(context, symbolDataRect.size.width / 200, symbolDataRect.size.height / 24) StyleKitDial.drawCenterText(label: data, colorR: colorR, colorG: colorG, colorB: colorB, colorA: colorA) CGContextRestoreGState(context) //// Symbol Unit Drawing let symbolUnitRect = CGRectMake(frame.minX + floor(frame.width * 0.00000 + 0.5), frame.minY + floor(frame.height * 0.68000 + 0.5), floor(frame.width * 1.00000 + 0.5) - floor(frame.width * 0.00000 + 0.5), floor(frame.height * 0.80000 + 0.5) - floor(frame.height * 0.68000 + 0.5)) CGContextSaveGState(context) UIRectClip(symbolUnitRect) CGContextTranslateCTM(context, symbolUnitRect.origin.x, symbolUnitRect.origin.y) CGContextScaleCTM(context, symbolUnitRect.size.width / 200, symbolUnitRect.size.height / 24) StyleKitDial.drawCenterText(label: unit, colorR: colorR, colorG: colorG, colorB: colorB, colorA: colorA) CGContextRestoreGState(context) } //// Generated Images public class func imageOfRing(value value: CGFloat = 0.14, colorR: CGFloat = 1, colorG: CGFloat = 1, colorB: CGFloat = 1, colorA: CGFloat = 1) -> UIImage { UIGraphicsBeginImageContextWithOptions(CGSizeMake(200, 200), false, 0) StyleKitDial.drawRing(value: value, colorR: colorR, colorG: colorG, colorB: colorB, colorA: colorA) let imageOfRing = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return imageOfRing } public class func imageOfDataRing(frame frame: CGRect = CGRectMake(0, 0, 200, 200), data: String = "35", unit: String = "μg/m3", value: CGFloat = 0.14, colorR: CGFloat = 1, colorG: CGFloat = 1, colorB: CGFloat = 1, colorA: CGFloat = 1) -> UIImage { UIGraphicsBeginImageContextWithOptions(frame.size, false, 0) StyleKitDial.drawDataRing(frame: CGRectMake(0, 0, frame.size.width, frame.size.height), data: data, unit: unit, value: value, colorR: colorR, colorG: colorG, colorB: colorB, colorA: colorA) let imageOfDataRing = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return imageOfDataRing } }
mit
265fda3c8e49310349303a3b64cb8f82
53.065327
328
0.687424
4.210959
false
false
false
false
samodom/TestableUIKit
TestableUIKitTests/Tests/UIViewControllerIndirectSpiesTests.swift
1
44118
// // UIViewControllerIndirectSpiesTests.swift // TestableUIKit // // Created by Sam Odom on 2/25/17. // Copyright © 2017 Swagger Soft. All rights reserved. // import XCTest import SampleTypes import TestableUIKit class UIViewControllerIndirectSpiesTests: XCTestCase { let plainController = PlainController() let compliantController = CompliantController() let subCompliantController = CompliantControllerSubclass() let nonCompliantController = NonCompliantController() var compliantControllers: [UIViewController]! let sourceController = UIViewController() let destinationController = UIViewController() let duration = 0.111 let options = UIViewAnimationOptions.curveEaseIn var animationsClosureInvoked = false var animations: UIViewAnimations! var completionHandlerInvoked = false var completion: UIViewAnimationsCompletion! override func setUp() { super.setUp() compliantControllers = [ plainController, compliantController, subCompliantController ] animations = { [weak self] in self?.animationsClosureInvoked = true } completion = { [weak self] _ in self?.completionHandlerInvoked = true } } // MARK: - `loadView` func testLoadViewControllerForwardingBehavior() { XCTAssertTrue(UIViewController.LoadViewSpyController.forwardsInvocations, "Spies on `loadView` should always forward their method invocations") } func testLoadViewSpyWithCompliantControllers() { subCompliantController.compliantControllerSubclassLoadViewCalled = false [compliantController, subCompliantController].forEach { controller in XCTAssertFalse(controller.superclassLoadViewCalled, "By default the controller should not indicate having asked its superclass to load its view") let spy = UIViewController.LoadViewSpyController.createSpy(on: controller)! spy.beginSpying() controller.loadView() XCTAssertFalse(controller.superclassLoadViewCalled, "A `UIViewController` subclass that does not call its superclass's implementation of `loadView` should not indicate having called that method when being spied upon") if controller === subCompliantController { XCTAssertTrue(subCompliantController.compliantControllerSubclassLoadViewCalled, "The spy method should always forward the method call to the original implementation") } spy.endSpying() XCTAssertFalse(controller.superclassLoadViewCalled, "The flag should be cleared after spying is complete") } } func testLoadViewSpyWithNonCompliantController() { let spy = UIViewController.LoadViewSpyController.createSpy(on: nonCompliantController)! spy.beginSpying() nonCompliantController.loadView() XCTAssertTrue(nonCompliantController.superclassLoadViewCalled, "A `UIViewController` subclass that calls its superclass implementation of `loadView` should indicate having called that method when being spied upon") spy.endSpying() } // MARK: - `viewDidLoad` func testViewDidLoadControllerForwardingBehavior() { XCTAssertTrue(UIViewController.ViewDidLoadSpyController.forwardsInvocations, "Spies on `viewDidLoad` should always forward their method invocations") } func testViewDidLoadSpyWithCompliantControllers() { subCompliantController.compliantControllerViewDidLoadCalled = false compliantControllers.forEach { controller in XCTAssertFalse(controller.superclassViewDidLoadCalled, "By default the controller should not indicate having invoked its superclass's implementation of `viewDidLoad`") let spy = UIViewController.ViewDidLoadSpyController.createSpy(on: controller)! spy.beginSpying() controller.viewDidLoad() XCTAssertTrue(controller.superclassViewDidLoadCalled, "A `UIViewController` subclass that calls its superclass's implementation of `viewDidLoad` should indicate having called that method when being spied upon") if controller === subCompliantController { XCTAssertTrue(subCompliantController.compliantControllerViewDidLoadCalled, "The spy method should always forward the method call to the original implementation") } spy.endSpying() XCTAssertFalse(controller.superclassViewDidLoadCalled, "The flag should be cleared after spying is complete") } } func testViewDidLoadSpyWithNonCompliantController() { let spy = UIViewController.ViewDidLoadSpyController.createSpy(on: nonCompliantController)! spy.beginSpying() nonCompliantController.viewDidLoad() XCTAssertFalse(nonCompliantController.superclassViewDidLoadCalled, "A `UIViewController` subclass that does not call its superclass implementation of `viewDidLoad` should not indicate having called that method when being spied upon") spy.endSpying() } // MARK: - `viewWillAppear(_:)` func testViewWillAppearControllerForwardingBehavior() { XCTAssertTrue(UIViewController.ViewWillAppearSpyController.forwardsInvocations, "Spies on `viewWillAppear(_:)` should always forward their method invocations") } func testViewWillAppearSpyWithCompliantControllers() { subCompliantController.compliantControllerViewWillAppearCalled = false compliantControllers.forEach { controller in XCTAssertFalse(controller.superclassViewWillAppearCalled, "By default the controller should not indicate having invoked its superclass's implementation of `viewWillAppear(_:)`") XCTAssertNil(controller.superclassViewWillAppearAnimated, "By default the animation flag should be clear") let spy = UIViewController.ViewWillAppearSpyController.createSpy(on: controller)! spy.beginSpying() controller.viewWillAppear(true) XCTAssertTrue(controller.superclassViewWillAppearCalled, "A `UIViewController` subclass that calls its superclass's implementation of `viewWillAppear(_:)` should indicate having called that method when being spied upon") XCTAssertTrue(controller.superclassViewWillAppearAnimated!, "The animation flag should be captured") if controller === subCompliantController { XCTAssertTrue(subCompliantController.compliantControllerViewWillAppearCalled, "The spy method should always forward the method call to the original implementation") } spy.endSpying() XCTAssertFalse(controller.superclassViewWillAppearCalled, "The flag should be cleared after spying is complete") XCTAssertNil(controller.superclassViewWillAppearAnimated, "The flag should be cleared after spying is complete") } } func testViewWillAppearSpyWithNonCompliantController() { let spy = UIViewController.ViewWillAppearSpyController.createSpy(on: nonCompliantController)! spy.beginSpying() nonCompliantController.viewWillAppear(true) XCTAssertFalse(nonCompliantController.superclassViewWillAppearCalled, "A `UIViewController` subclass that does not call its superclass implementation of `viewWillAppear(_:)` should not indicate having called that method when being spied upon") spy.endSpying() } // MARK: - `viewDidAppear(_:)` func testViewDidAppearControllerForwardingBehavior() { XCTAssertTrue(UIViewController.ViewDidAppearSpyController.forwardsInvocations, "Spies on `viewDidAppear(_:)` should always forward their method invocations") } func testViewDidAppearSpyWithCompliantControllers() { subCompliantController.compliantControllerViewDidAppearCalled = false compliantControllers.forEach { controller in XCTAssertFalse(controller.superclassViewDidAppearCalled, "By default the controller should not indicate having invoked its superclass's implementation of `viewDidAppear(_:)`") XCTAssertNil(controller.superclassViewDidAppearAnimated, "By default the animation flag should be clear") let spy = UIViewController.ViewDidAppearSpyController.createSpy(on: controller)! spy.beginSpying() controller.viewDidAppear(true) XCTAssertTrue(controller.superclassViewDidAppearCalled, "A `UIViewController` subclass that calls its superclass's implementation of `viewDidAppear(_:)` should indicate having called that method when being spied upon") XCTAssertTrue(controller.superclassViewDidAppearAnimated!, "The animation flag should be captured") if controller === subCompliantController { XCTAssertTrue(subCompliantController.compliantControllerViewDidAppearCalled, "The spy method should always forward the method call to the original implementation") } spy.endSpying() XCTAssertFalse(controller.superclassViewDidAppearCalled, "The flag should be cleared after spying is complete") XCTAssertNil(controller.superclassViewDidAppearAnimated, "The flag should be cleared after spying is complete") } } func testViewDidAppearSpyWithNonCompliantController() { let spy = UIViewController.ViewDidAppearSpyController.createSpy(on: nonCompliantController)! spy.beginSpying() nonCompliantController.viewDidAppear(true) XCTAssertFalse(nonCompliantController.superclassViewDidAppearCalled, "A `UIViewController` subclass that does not call its superclass implementation of `viewDidAppear(_:)` should not indicate having called that method when being spied upon") spy.endSpying() } // MARK: - `viewWillDisappear(_:)` func testViewWillDisappearControllerForwardingBehavior() { XCTAssertTrue(UIViewController.ViewWillDisappearSpyController.forwardsInvocations, "Spies on `viewWillDisappear(_:)` should always forward their method invocations") } func testViewWillDisappearSpyWithCompliantControllers() { subCompliantController.compliantControllerViewWillDisappearCalled = false compliantControllers.forEach { controller in XCTAssertFalse(controller.superclassViewWillDisappearCalled, "By default the controller should not indicate having invoked its superclass's implementation of `viewWillDisappear(_:)`") XCTAssertNil(controller.superclassViewWillDisappearAnimated, "By default the animation flag should be clear") let spy = UIViewController.ViewWillDisappearSpyController.createSpy(on: controller)! spy.beginSpying() controller.viewWillDisappear(true) XCTAssertTrue(controller.superclassViewWillDisappearCalled, "A `UIViewController` subclass that calls its superclass's implementation of `viewWillDisappear(_:)` should indicate having called that method when being spied upon") XCTAssertTrue(controller.superclassViewWillDisappearAnimated!, "The animation flag should be captured") if controller === subCompliantController { XCTAssertTrue(subCompliantController.compliantControllerViewWillDisappearCalled, "The spy method should always forward the method call to the original implementation") } spy.endSpying() XCTAssertFalse(controller.superclassViewWillDisappearCalled, "The flag should be cleared after spying is complete") XCTAssertNil(controller.superclassViewWillDisappearAnimated, "The flag should be cleared after spying is complete") } } func testViewWillDisappearSpyWithNonCompliantController() { let spy = UIViewController.ViewWillDisappearSpyController.createSpy(on: nonCompliantController)! spy.beginSpying() nonCompliantController.viewWillDisappear(true) XCTAssertFalse(nonCompliantController.superclassViewWillDisappearCalled, "A `UIViewController` subclass that does not call its superclass implementation of `viewWillDisappear(_:)` should not indicate having called that method when being spied upon") spy.endSpying() } // MARK: - `viewDidDisappear(_:)` func testViewDidDisappearControllerForwardingBehavior() { XCTAssertTrue(UIViewController.ViewDidDisappearSpyController.forwardsInvocations, "Spies on `viewDidDisappear(_:)` should always forward their method invocations") } func testViewDidDisappearSpyWithCompliantControllers() { subCompliantController.compliantControllerViewDidDisappearCalled = false compliantControllers.forEach { controller in XCTAssertFalse(controller.superclassViewDidDisappearCalled, "By default the controller should not indicate having invoked its superclass's implementation of `viewDidDisappear(_:)`") XCTAssertNil(controller.superclassViewDidDisappearAnimated, "By default the animation flag should be clear") let spy = UIViewController.ViewDidDisappearSpyController.createSpy(on: controller)! spy.beginSpying() controller.viewDidDisappear(true) XCTAssertTrue(controller.superclassViewDidDisappearCalled, "A `UIViewController` subclass that calls its superclass's implementation of `viewDidDisappear(_:)` should indicate having called that method when being spied upon") XCTAssertTrue(controller.superclassViewDidDisappearAnimated!, "The animation flag should be captured") if controller === subCompliantController { XCTAssertTrue(subCompliantController.compliantControllerViewDidDisappearCalled, "The spy method should always forward the method call to the original implementation") } spy.endSpying() XCTAssertFalse(controller.superclassViewDidDisappearCalled, "The flag should be cleared after spying is complete") XCTAssertNil(controller.superclassViewDidDisappearAnimated, "The flag should be cleared after spying is complete") } } func testViewDidDisappearSpyWithNonCompliantController() { let spy = UIViewController.ViewDidDisappearSpyController.createSpy(on: nonCompliantController)! spy.beginSpying() nonCompliantController.viewDidDisappear(true) XCTAssertFalse(nonCompliantController.superclassViewDidDisappearCalled, "A `UIViewController` subclass that does not call its superclass implementation of `viewDidDisappear(_:)` should not indicate having called that method when being spied upon") spy.endSpying() } // MARK: - `didReceiveMemoryWarning` func testDidReceiveMemoryWarningControllerForwardingBehavior() { XCTAssertTrue(UIViewController.DidReceiveMemoryWarningSpyController.forwardsInvocations, "Spies on `didReceiveMemoryWarning` should always forward their method invocations") } func testDidReceiveMemoryWarningSpyWithCompliantControllers() { subCompliantController.compliantControllerDidReceiveMemoryWarningCalled = false compliantControllers.forEach { controller in XCTAssertFalse(controller.superclassDidReceiveMemoryWarningCalled, "By default the controller should not indicate having invoked its superclass's implementation of `didReceiveMemoryWarning`") let spy = UIViewController.DidReceiveMemoryWarningSpyController.createSpy(on: controller)! spy.beginSpying() controller.didReceiveMemoryWarning() XCTAssertTrue(controller.superclassDidReceiveMemoryWarningCalled, "A `UIViewController` subclass that calls its superclass's implementation of `didReceiveMemoryWarning` should indicate having called that method when being spied upon") if controller === subCompliantController { XCTAssertTrue(subCompliantController.compliantControllerDidReceiveMemoryWarningCalled, "The spy method should always forward the method call to the original implementation") } spy.endSpying() XCTAssertFalse(controller.superclassDidReceiveMemoryWarningCalled, "The flag should be cleared after spying is complete") } } func testDidReceiveMemoryWarningSpyWithNonCompliantController() { let spy = UIViewController.DidReceiveMemoryWarningSpyController.createSpy(on: nonCompliantController)! spy.beginSpying() nonCompliantController.didReceiveMemoryWarning() XCTAssertFalse(nonCompliantController.superclassDidReceiveMemoryWarningCalled, "A `UIViewController` subclass that does not call its superclass implementation of `didReceiveMemoryWarning` should not indicate having called that method when being spied upon") spy.endSpying() } // MARK: - `updateViewConstraints` func testUpdateViewConstraintsControllerForwardingBehavior() { XCTAssertTrue(UIViewController.UpdateViewConstraintsSpyController.forwardsInvocations, "Spies on `updateViewConstraints` should always forward their method invocations") } func testUpdateViewConstraintsSpyWithCompliantControllers() { subCompliantController.compliantControllerUpdateViewConstraintsCalled = false compliantControllers.forEach { controller in XCTAssertFalse(controller.superclassUpdateViewConstraintsCalled, "By default the controller should not indicate having invoked its superclass's implementation of `updateViewConstraints`") let spy = UIViewController.UpdateViewConstraintsSpyController.createSpy(on: controller)! spy.beginSpying() controller.updateViewConstraints() XCTAssertTrue(controller.superclassUpdateViewConstraintsCalled, "A `UIViewController` subclass that calls its superclass's implementation of `updateViewConstraints` should indicate having called that method when being spied upon") if controller === subCompliantController { XCTAssertTrue(subCompliantController.compliantControllerUpdateViewConstraintsCalled, "The spy method should always forward the method call to the original implementation") } spy.endSpying() XCTAssertFalse(controller.superclassUpdateViewConstraintsCalled, "The flag should be cleared after spying is complete") } } func testUpdateViewConstraintsSpyWithNonCompliantController() { let spy = UIViewController.UpdateViewConstraintsSpyController.createSpy(on: nonCompliantController)! spy.beginSpying() nonCompliantController.updateViewConstraints() XCTAssertFalse(nonCompliantController.superclassUpdateViewConstraintsCalled, "A `UIViewController` subclass that does not call its superclass implementation of `updateViewConstraints` should not indicate having called that method when being spied upon") spy.endSpying() } // MARK: - `addChildViewController(_:)` func testAddChildViewControllerControllerForwardingBehavior() { XCTAssertTrue(UIViewController.AddChildViewControllerSpyController.forwardsInvocations, "Spies on `addChildViewController(_:)` should always forward their method invocations") } func testAddChildViewControllerSpyWithCompliantControllers() { compliantControllers.forEach { controller in XCTAssertFalse(controller.superclassAddChildViewControllerCalled, "By default the controller should not indicate having invoked its superclass's implementation of `addChildViewController(_:)`") XCTAssertNil(controller.superclassAddChildViewControllerChild, "By default the child controller should be clear") let spy = UIViewController.AddChildViewControllerSpyController.createSpy(on: controller)! spy.beginSpying() let child = UIViewController() controller.addChildViewController(child) XCTAssertTrue(controller.superclassAddChildViewControllerCalled, "A `UIViewController` subclass that calls its superclass's implementation of `addChildViewController(_:)` should indicate having called that method when being spied upon") XCTAssertEqual(controller.superclassAddChildViewControllerChild!, child, "The child controller should be captured") XCTAssertTrue(controller.childViewControllers.contains(child), "The spy method should always forward the method call to the original implementation") spy.endSpying() XCTAssertFalse(controller.superclassAddChildViewControllerCalled, "The flag should be cleared after spying is complete") XCTAssertNil(controller.superclassAddChildViewControllerChild, "The child should be cleared after spying is complete") } } func testAddChildViewControllerSpyWithNonCompliantController() { let child = UIViewController() let spy = UIViewController.AddChildViewControllerSpyController.createSpy(on: nonCompliantController)! spy.beginSpying() nonCompliantController.addChildViewController(child) XCTAssertFalse(nonCompliantController.superclassAddChildViewControllerCalled, "A `UIViewController` subclass that does not call its superclass implementation of `addChildViewController(_:)` should not indicate having called that method when being spied upon") spy.endSpying() } // MARK: - `removeFromParentViewController` func testRemoveFromParentViewControllerControllerForwardingBehavior() { XCTAssertTrue(UIViewController.RemoveFromParentViewControllerSpyController.forwardsInvocations, "Spies on `removeFromParentViewController` should always forward their method invocations") } func testRemoveFromParentViewControllerSpyWithCompliantControllers() { compliantControllers.forEach { controller in XCTAssertFalse(controller.superclassRemoveFromParentViewControllerCalled, "By default the controller should not indicate having invoked its superclass's implementation of `removeFromParentViewController`") let spy = UIViewController.RemoveFromParentViewControllerSpyController.createSpy(on: controller)! spy.beginSpying() let child = UIViewController() controller.addChildViewController(child) assert(controller.childViewControllers.contains(child)) controller.removeFromParentViewController() XCTAssertTrue(controller.superclassRemoveFromParentViewControllerCalled, "A `UIViewController` subclass that calls its superclass's implementation of `removeFromParentViewController` should indicate having called that method when being spied upon") XCTAssertFalse(!controller.childViewControllers.contains(child), "The spy method should always forward the method call to the original implementation") spy.endSpying() XCTAssertFalse(controller.superclassRemoveFromParentViewControllerCalled, "The flag should be cleared after spying is complete") } } func testRemoveFromParentViewControllerSpyWithNonCompliantController() { let spy = UIViewController.RemoveFromParentViewControllerSpyController.createSpy(on: nonCompliantController)! spy.beginSpying() nonCompliantController.removeFromParentViewController() XCTAssertFalse(nonCompliantController.superclassRemoveFromParentViewControllerCalled, "A `UIViewController` subclass that does not call its superclass implementation of `removeFromParentViewController` should not indicate having called that method when being spied upon") spy.endSpying() } // MARK: - `transition(from:to:duration:options:animations:completion:)` func testTransitionSpyWithCompliantControllersWithoutForwarding() { compliantControllers.forEach { controller in controller.addChildViewController(sourceController) controller.addChildViewController(destinationController) XCTAssertFalse(controller.superclassTransitionCalled, "By default the controller should not indicate having invoked its superclass's implementation of `transition(from:to:duration:options:animations:completion:)`") XCTAssertNil(controller.superclassTransitionFromController, "By default the source controller should be clear") XCTAssertNil(controller.superclassTransitionToController, "By default the destination controller should be clear") XCTAssertNil(controller.superclassTransitionDuration, "By default the duration should be clear") XCTAssertNil(controller.superclassTransitionOptions, "By default the options should be clear") XCTAssertNil(controller.superclassTransitionAnimations, "By default the animations closure should be clear") XCTAssertNil(controller.superclassTransitionCompletion, "By default the completion handler should be clear") animationsClosureInvoked = false completionHandlerInvoked = false UIViewController.TransitionIndirectSpyController.forwardsInvocations = false let spy = UIViewController.TransitionIndirectSpyController.createSpy(on: controller)! spy.beginSpying() controller.transition( from: sourceController, to: destinationController, duration: duration, options: options, animations: animations, completion: completion ) XCTAssertTrue(controller.superclassTransitionCalled, "A `UIViewController` subclass that calls its superclass's implementation of `transition(from:to:duration:options:animations:completion:)` should indicate having called that method when being spied upon") XCTAssertEqual(controller.superclassTransitionFromController!, sourceController, "The source controller should be captured") XCTAssertEqual(controller.superclassTransitionToController!, destinationController, "The destination controller should be captured") XCTAssertEqual(controller.superclassTransitionDuration!, duration, "The duration should be captured") XCTAssertEqual(controller.superclassTransitionOptions!, options, "The options should be captured") XCTAssertFalse(animationsClosureInvoked, "The spy method should not forward the method call to the original implementation") let capturedAnimations = controller.superclassTransitionAnimations capturedAnimations!() XCTAssertTrue(animationsClosureInvoked, "The animations closure should be captured") XCTAssertFalse(completionHandlerInvoked, "The spy method should not forward the method call to the original implementation") let capturedCompletion = controller.superclassTransitionCompletion capturedCompletion!(true) XCTAssertTrue(completionHandlerInvoked, "The completion handler should be captured") spy.endSpying() UIViewController.TransitionIndirectSpyController.forwardsInvocations = true XCTAssertFalse(controller.superclassTransitionCalled, "The flag should be cleared after spying is complete") XCTAssertNil(controller.superclassTransitionFromController, "The source controller should be cleared after spying is complete") XCTAssertNil(controller.superclassTransitionToController, "The destination controller should be cleared after spying is complete") XCTAssertNil(controller.superclassTransitionDuration, "The duration should be cleared after spying is complete") XCTAssertNil(controller.superclassTransitionOptions, "The options should be cleared after spying is complete") XCTAssertNil(controller.superclassTransitionAnimations, "The animations closure should be cleared after spying is complete") XCTAssertNil(controller.superclassTransitionCompletion, "The completion handler should be cleared after spying is complete") } } func testTransitionSpyWithCompliantControllersWithForwarding() { compliantControllers.forEach { controller in controller.addChildViewController(sourceController) controller.addChildViewController(destinationController) XCTAssertFalse(controller.superclassTransitionCalled, "By default the controller should not indicate having invoked its superclass's implementation of `transition(from:to:duration:options:animations:completion:)`") XCTAssertNil(controller.superclassTransitionFromController, "By default the source controller should be clear") XCTAssertNil(controller.superclassTransitionToController, "By default the destination controller should be clear") XCTAssertNil(controller.superclassTransitionDuration, "By default the duration should be clear") XCTAssertNil(controller.superclassTransitionOptions, "By default the options should be clear") XCTAssertNil(controller.superclassTransitionAnimations, "By default the animations closure should be clear") XCTAssertNil(controller.superclassTransitionCompletion, "By default the completion handler should be clear") animationsClosureInvoked = false completionHandlerInvoked = false let spy = UIViewController.TransitionIndirectSpyController.createSpy(on: controller)! spy.beginSpying() controller.transition( from: sourceController, to: destinationController, duration: duration, options: options, animations: animations, completion: completion ) XCTAssertTrue(controller.superclassTransitionCalled, "A `UIViewController` subclass that calls its superclass's implementation of `transition(from:to:duration:options:animations:completion:)` should indicate having called that method when being spied upon") XCTAssertEqual(controller.superclassTransitionFromController!, sourceController, "The source controller should be captured") XCTAssertEqual(controller.superclassTransitionToController!, destinationController, "The destination controller should be captured") XCTAssertEqual(controller.superclassTransitionDuration!, duration, "The duration should be captured") XCTAssertEqual(controller.superclassTransitionOptions!, options, "The options should be captured") XCTAssertNil(controller.superclassTransitionAnimations, "The animations closure should not be captured when forwarding to the original implementation") XCTAssertNil(controller.superclassTransitionCompletion, "The completion handler should not be captured when forwarding to the original implementation") if controller == subCompliantController { XCTAssertTrue(subCompliantController.compliantControllerTransitionCalled, "The spy method should not forward the method call to the original implementation") } spy.endSpying() XCTAssertFalse(controller.superclassTransitionCalled, "The flag should be cleared after spying is complete") XCTAssertNil(controller.superclassTransitionFromController, "The source controller should be cleared after spying is complete") XCTAssertNil(controller.superclassTransitionToController, "The destination controller should be cleared after spying is complete") XCTAssertNil(controller.superclassTransitionDuration, "The duration should be cleared after spying is complete") XCTAssertNil(controller.superclassTransitionOptions, "The options should be cleared after spying is complete") } } func testTransitionSpyWithNonCompliantController() { let spy = UIViewController.TransitionIndirectSpyController.createSpy(on: nonCompliantController)! spy.beginSpying() nonCompliantController.transition( from: sourceController, to: destinationController, duration: duration, options: options, animations: animations, completion: completion ) XCTAssertFalse(nonCompliantController.superclassTransitionCalled, "A `UIViewController` subclass that does not call its superclass implementation of `transition(from:to:duration:options:animations:completion:)` should not indicate having called that method when being spied upon") spy.endSpying() } // MARK: - `setEditing(_:animated:)` func testSetEditingControllerForwardingBehavior() { XCTAssertTrue(UIViewController.SetEditingSpyController.forwardsInvocations, "Spies on `setEditing(_:animated:)` should always forward their method invocations") } func testSetEditingSpyWithCompliantControllers() { compliantControllers.forEach { controller in XCTAssertFalse(controller.superclassSetEditingCalled, "By default the controller should not indicate having invoked its superclass's implementation of `setEditing(_:animated:)`") XCTAssertNil(controller.superclassSetEditingEditing, "By default the editing flag should be clear") XCTAssertNil(controller.superclassSetEditingAnimated, "By default the animation flag should be clear") let spy = UIViewController.SetEditingSpyController.createSpy(on: controller)! spy.beginSpying() controller.setEditing(true, animated: true) XCTAssertTrue(controller.superclassSetEditingCalled, "A `UIViewController` subclass that calls its superclass's implementation of `setEditing(_:animated:)` should indicate having called that method when being spied upon") XCTAssertTrue(controller.superclassSetEditingEditing!, "The editing flag should be captured") XCTAssertTrue(controller.superclassSetEditingAnimated!, "The animation flag should be captured") XCTAssertTrue(controller.isEditing, "The spy method should always forward the method call to the original implementation") spy.endSpying() XCTAssertFalse(controller.superclassSetEditingCalled, "The flag should be cleared after spying is complete") XCTAssertNil(controller.superclassSetEditingEditing, "The editing flag should be cleared after spying is complete") XCTAssertNil(controller.superclassSetEditingAnimated, "The animation flag should be cleared after spying is complete") controller.setEditing(false, animated: true) } } func testSetEditingSpyWithNonCompliantController() { let spy = UIViewController.SetEditingSpyController.createSpy(on: nonCompliantController)! spy.beginSpying() nonCompliantController.setEditing(true, animated: true) XCTAssertFalse(nonCompliantController.superclassSetEditingCalled, "A `UIViewController` subclass that does not call its superclass implementation of `setEditing(_:animated:)` should not indicate having called that method when being spied upon") spy.endSpying() nonCompliantController.setEditing(false, animated: true) } // MARK: - `encodeRestorableState(with:)` func testEncodeRestorableStateControllerForwardingBehavior() { XCTAssertTrue(UIViewController.EncodeRestorableStateSpyController.forwardsInvocations, "Spies on `encodeRestorableState(with:)` should always forward their method invocations") } func testEncodeRestorableStateSpyWithCompliantControllers() { subCompliantController.compliantControllerEncodeRestorableStateCalled = false compliantControllers.forEach { controller in XCTAssertFalse(controller.superclassEncodeRestorableStateCalled, "By default the controller should not indicate having invoked its superclass's implementation of `encodeRestorableState(with:)`") XCTAssertNil(controller.superclassEncodeRestorableStateCoder, "By default the coder should be clear") let spy = UIViewController.EncodeRestorableStateSpyController.createSpy(on: controller)! spy.beginSpying() let coder = NSCoder() controller.encodeRestorableState(with: coder) XCTAssertTrue(controller.superclassEncodeRestorableStateCalled, "A `UIViewController` subclass that calls its superclass's implementation of `encodeRestorableState(with:)` should indicate having called that method when being spied upon") XCTAssertEqual(controller.superclassEncodeRestorableStateCoder!, coder, "The coder should be captured") if controller == subCompliantController { XCTAssertTrue(subCompliantController.compliantControllerEncodeRestorableStateCalled, "The spy method should always forward the method call to the original implementation") } spy.endSpying() XCTAssertFalse(controller.superclassEncodeRestorableStateCalled, "The flag should be cleared after spying is complete") XCTAssertNil(controller.superclassEncodeRestorableStateCoder, "The coder should be cleared after spying is complete") } } func testEncodeRestorableStateSpyWithNonCompliantController() { let spy = UIViewController.EncodeRestorableStateSpyController.createSpy(on: nonCompliantController)! spy.beginSpying() nonCompliantController.encodeRestorableState(with: NSCoder()) XCTAssertFalse(nonCompliantController.superclassEncodeRestorableStateCalled, "A `UIViewController` subclass that does not call its superclass implementation of `encodeRestorableState(with:)` should not indicate having called that method when being spied upon") spy.endSpying() } // MARK: - `decodeRestorableState(with:)` func testDecodeRestorableStateControllerForwardingBehavior() { XCTAssertTrue(UIViewController.DecodeRestorableStateSpyController.forwardsInvocations, "Spies on `decodeRestorableState(with:)` should always forward their method invocations") } func testDecodeRestorableStateSpyWithCompliantControllers() { subCompliantController.compliantControllerDecodeRestorableStateCalled = false compliantControllers.forEach { controller in XCTAssertFalse(controller.superclassDecodeRestorableStateCalled, "By default the controller should not indicate having invoked its superclass's implementation of `decodeRestorableState(with:)`") XCTAssertNil(controller.superclassDecodeRestorableStateCoder, "By default the coder should be clear") let spy = UIViewController.DecodeRestorableStateSpyController.createSpy(on: controller)! spy.beginSpying() let coder = NSCoder() controller.decodeRestorableState(with: coder) XCTAssertTrue(controller.superclassDecodeRestorableStateCalled, "A `UIViewController` subclass that calls its superclass's implementation of `decodeRestorableState(with:)` should indicate having called that method when being spied upon") XCTAssertEqual(controller.superclassDecodeRestorableStateCoder!, coder, "The coder should be captured") if controller == subCompliantController { XCTAssertTrue(subCompliantController.compliantControllerDecodeRestorableStateCalled, "The spy method should always forward the method call to the original implementation") } spy.endSpying() XCTAssertFalse(controller.superclassDecodeRestorableStateCalled, "The flag should be cleared after spying is complete") XCTAssertNil(controller.superclassDecodeRestorableStateCoder, "The coder should be cleared after spying is complete") } } func testDecodeRestorableStateSpyWithNonCompliantController() { let spy = UIViewController.DecodeRestorableStateSpyController.createSpy(on: nonCompliantController)! spy.beginSpying() nonCompliantController.decodeRestorableState(with: NSCoder()) XCTAssertFalse(nonCompliantController.superclassDecodeRestorableStateCalled, "A `UIViewController` subclass that does not call its superclass implementation of `decodeRestorableState(with:)` should not indicate having called that method when being spied upon") spy.endSpying() } }
mit
5434f3bbf9b4dd810baec6d68ab4a3c6
50.59883
237
0.68749
7.469861
false
true
false
false
Davidde94/StemCode_iOS
StemCode/StemKit/AppVersion.swift
1
2640
// // AppVersion.swift // StemCode // // Created by David Evans on 07/09/2018. // Copyright © 2018 BlackPoint LTD. All rights reserved. // import Foundation public struct AppVersion: Codable { public let majorVersion: UInt public let minorVersion: UInt public let patchVersion: UInt public var isOutdated: Bool { return self < AppVersion.current } public static let current: AppVersion = { guard let infoDictionary = Bundle.main.infoDictionary, let versionString = infoDictionary["CFBundleShortVersionString"] as? String else { return AppVersion(1, 0, 0) } return AppVersion(versionString) ?? AppVersion(1, 0, 0) }() public init?(_ string: String) { let components = string.split(separator: Character(".")) guard components.count == 3 else { return nil } guard let majorVersion = UInt(components[0]), let minorVersion = UInt(components[1]), let patchVersion = UInt(components[2]) else { return nil } self.majorVersion = majorVersion self.minorVersion = minorVersion self.patchVersion = patchVersion } public init(_ majorVersion: UInt, _ minorVersion: UInt, _ patchVersion: UInt) { self.init(majorVersion: majorVersion, minorVersion: minorVersion, patchVersion: patchVersion) } public init(majorVersion: UInt, minorVersion: UInt, patchVersion: UInt) { self.majorVersion = majorVersion self.minorVersion = minorVersion self.patchVersion = patchVersion } } extension AppVersion: Equatable { } extension AppVersion: Comparable { public static func < (lhs: AppVersion, rhs: AppVersion) -> Bool { if lhs.majorVersion < rhs.majorVersion { return true } else if lhs.minorVersion < rhs.minorVersion { return true } else if lhs.patchVersion < rhs.patchVersion { return true } return false } public static func > (lhs: AppVersion, rhs: AppVersion) -> Bool { if lhs.majorVersion > rhs.majorVersion { return true } else if lhs.minorVersion > rhs.minorVersion { return true } else if lhs.patchVersion > rhs.patchVersion { return true } return false } public static func >= (lhs: AppVersion, rhs: AppVersion) -> Bool { if lhs.majorVersion < rhs.majorVersion { return false } else if lhs.minorVersion < rhs.minorVersion { return false } else if lhs.patchVersion < rhs.patchVersion { return false } return true } public static func <= (lhs: AppVersion, rhs: AppVersion) -> Bool { if lhs.majorVersion > rhs.majorVersion { return false } else if lhs.minorVersion > rhs.minorVersion { return false } else if lhs.patchVersion > rhs.patchVersion { return false } return true } }
mit
c02dc6a0c13f9f1401a9a4b1edad2551
22.149123
95
0.707465
3.791667
false
false
false
false
azac/swift-faker
Faker/ViewController.swift
1
1449
import UIKit class ViewController: UIViewController { @IBOutlet var avatarImage: UIImageView! @IBOutlet var label: UILabel! @IBAction func klik(sender: AnyObject) { var fakeGuy = Faker() label.text=fakeGuy.fullDescription avatarImage.image = UIImage(named:"") dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { let imgURL = NSURL.URLWithString(fakeGuy.photo); var request: NSURLRequest = NSURLRequest(URL: imgURL) var urlConnection: NSURLConnection = NSURLConnection(request: request, delegate: self) NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response: NSURLResponse!,data: NSData!,error: NSError!) -> Void in if !error? { var downloadedImage = UIImage(data: data) self.avatarImage.image = downloadedImage } else { println("Error: \(error.localizedDescription)") } }) }) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
apache-2.0
4785c7b9457090352388dcfccd72a428
20.626866
185
0.606625
5.426966
false
false
false
false
Driftt/drift-sdk-ios
Drift/Birdsong/Presence.swift
2
3858
// // Presence.swift // Pods // // Created by Simon Manning on 6/07/2016. // // import Foundation internal final class Presence { // MARK: - Convenience typealiases public typealias PresenceState = [String: [Meta]] public typealias Diff = [String: [String: Any]] public typealias Meta = [String: Any] // MARK: - Properties fileprivate(set) public var state: PresenceState // MARK: - Callbacks public var onJoin: ((_ id: String, _ meta: Meta) -> ())? public var onLeave: ((_ id: String, _ meta: Meta) -> ())? public var onStateChange: ((_ state: PresenceState) -> ())? // MARK: - Initialisation init(state: PresenceState = Presence.PresenceState()) { self.state = state } // MARK: - Syncing func sync(_ diff: Response) { // Initial state event if diff.event == "presence_state" { diff.payload.forEach{ id, entry in if let entry = entry as? [String: Any] { if let metas = entry["metas"] as? [Meta] { state[id] = metas } } } } else if diff.event == "presence_diff" { if let leaves = diff.payload["leaves"] as? Diff { syncLeaves(leaves) } if let joins = diff.payload["joins"] as? Diff { syncJoins(joins) } } onStateChange?(state) } func syncLeaves(_ diff: Diff) { defer { diff.forEach { id, entry in if let metas = entry["metas"] as? [Meta] { metas.forEach { onLeave?(id, $0) } } } } for (id, entry) in diff where state[id] != nil { guard var existing = state[id] else { continue } // If there's only one entry for the id, just remove it. if existing.count == 1 { state.removeValue(forKey: id) continue } // Otherwise, we need to find the phx_ref keys to delete. let metas = entry["metas"] as? [Meta] if let refsToDelete = metas?.compactMap({ $0["phx_ref"] as? String }) { existing = existing.filter { if let phxRef = $0["phx_ref"] as? String { return !refsToDelete.contains(phxRef) } return true } state[id] = existing } } } func syncJoins(_ diff: Diff) { diff.forEach { id, entry in if let metas = entry["metas"] as? [Meta] { if var existing = state[id] { existing += metas } else { state[id] = metas } metas.forEach { onJoin?(id, $0) } } } } // MARK: - Presence access convenience func metas(id: String) -> [Meta]? { return state[id] } func firstMeta(id: String) -> Meta? { return state[id]?.first } func firstMetas() -> [String: Meta] { var result = [String: Meta]() state.forEach { id, metas in result[id] = metas.first } return result } func firstMetaValue<T>(id: String, key: String) -> T? { guard let meta = state[id]?.first, let value = meta[key] as? T else { return nil } return value } func firstMetaValues<T>(key: String) -> [T] { var result = [T]() state.forEach { id, metas in if let meta = metas.first, let value = meta[key] as? T { result.append(value) } } return result } }
mit
0d1a9027d5cbc2d86bba9dbba12da415
25.424658
83
0.466304
4.369196
false
false
false
false
AutomationStation/BouncerBuddy
BouncerBuddyV6/BouncerBuddy/MainViewController.swift
1
1369
// // ViewController.swift // BouncerBuddy // // Created by Sha Wu on 16/3/2. // Copyright © 2016年 Sheryl Hong. All rights reserved. // import UIKit class MainViewController: UIViewController { @IBOutlet weak var usernameLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidAppear(animated: Bool) { // comment out the next lines if you want to go to homepage without sign in let prefs:NSUserDefaults = NSUserDefaults.standardUserDefaults() let isLoggedIn:Int = prefs.integerForKey("ISLOGGEDIN") as Int if (isLoggedIn != 1){ self.performSegueWithIdentifier("SignInView", sender: self) }else{ self.usernameLabel.text = prefs.valueForKey("USERNAME") as? String } } @IBAction func LogoutTapped(sender: AnyObject) { let appDomain = NSBundle.mainBundle().bundleIdentifier NSUserDefaults.standardUserDefaults().removePersistentDomainForName(appDomain!) self.performSegueWithIdentifier("SignInView", sender: self) } }
apache-2.0
38e0fbb0be54ed02c03a0e61d1b54ef7
28.695652
87
0.65959
5.116105
false
false
false
false
nathawes/swift
test/IDE/print_synthesized_extensions.swift
6
12899
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -emit-module-path %t/print_synthesized_extensions.swiftmodule -emit-module-doc -emit-module-doc-path %t/print_synthesized_extensions.swiftdoc %s // RUN: %target-swift-ide-test -print-module -annotate-print -synthesize-extension -print-interface -no-empty-line-between-members -module-to-print=print_synthesized_extensions -I %t -source-filename=%s > %t.syn.txt // RUN: %FileCheck %s -check-prefix=CHECK1 < %t.syn.txt // RUN: %FileCheck %s -check-prefix=CHECK2 < %t.syn.txt // RUN: %FileCheck %s -check-prefix=CHECK3 < %t.syn.txt // RUN: %FileCheck %s -check-prefix=CHECK4 < %t.syn.txt // RUN: %FileCheck %s -check-prefix=CHECK5 < %t.syn.txt // RUN: %FileCheck %s -check-prefix=CHECK6 < %t.syn.txt // RUN: %FileCheck %s -check-prefix=CHECK7 < %t.syn.txt // RUN: %FileCheck %s -check-prefix=CHECK8 < %t.syn.txt // RUN: %FileCheck %s -check-prefix=CHECK9 < %t.syn.txt // RUN: %FileCheck %s -check-prefix=CHECK10 < %t.syn.txt // RUN: %FileCheck %s -check-prefix=CHECK11 < %t.syn.txt // RUN: %FileCheck %s -check-prefix=CHECK12 < %t.syn.txt // RUN: %FileCheck %s -check-prefix=CHECK13 < %t.syn.txt // RUN: %FileCheck %s -check-prefix=CHECK14 < %t.syn.txt public protocol P1 { associatedtype T1 associatedtype T2 func f1(t : T1) -> T1 func f2(t : T2) -> T2 } public extension P1 where T1 == Int { func p1IntFunc(i : Int) -> Int {return 0} } public extension P1 where T1 : P3 { func p3Func(i : Int) -> Int {return 0} } public protocol P2 { associatedtype P2T1 } public extension P2 where P2T1 : P2{ public func p2member() {} } public protocol P3 {} public extension P1 where T1 : P2 { public func ef1(t : T1) {} public func ef2(t : T2) {} } public extension P1 where T1 == P3, T2 : P3 { public func ef3(t : T1) {} public func ef4(t : T1) {} } public extension P1 where T2 : P3 { public func ef5(t : T2) {} } public struct S2 {} public struct S1<T> : P1, P2 { public typealias T1 = T public typealias T2 = S2 public typealias P2T1 = T public func f1(t : T1) -> T1 { return t } public func f2(t : T2) -> T2 { return t } } public struct S3<T> : P1 { public typealias T1 = (T, T) public typealias T2 = (T, T) public func f1(t : T1) -> T1 { return t } public func f2(t : T2) -> T2 { return t } } public struct S4<T> : P1 { public typealias T1 = Int public typealias T2 = Int public func f1(t : T1) -> T1 { return t } public func f2(t : T2) -> T2 { return t } } public struct S5 : P3 {} public struct S6<T> : P1 { public typealias T1 = S5 public typealias T2 = S5 public func f1(t : T1) -> T1 { return t } public func f2(t : T2) -> T2 { return t } } public extension S6 { public func f3() {} } public struct S7 { public struct S8 : P1 { public typealias T1 = S5 public typealias T2 = S5 public func f1(t : T1) -> T1 { return t } public func f2(t : T2) -> T2 { return t } } } public extension P1 where T1 == S9<Int> { public func S9IntFunc() {} } public struct S9<T> : P3 {} public struct S10 : P1 { public typealias T1 = S9<Int> public typealias T2 = S9<Int> public func f1(t : T1) -> T1 { return t } public func f2(t : T2) -> T2 { return t } } public protocol P4 {} /// Extension on P4Func1 public extension P4 { func P4Func1() {} } /// Extension on P4Func2 public extension P4 { func P4Func2() {} } public struct S11 : P4 {} public extension S6 { public func fromActualExtension() {} } public protocol P5 { associatedtype T1 /// This is picked func foo1() } public extension P5 { /// This is not picked public func foo1() {} } public extension P5 where T1 == Int { /// This is picked public func foo2() {} } public extension P5 { /// This is not picked public func foo2() {} } public extension P5 { /// This is not picked public func foo3() {} } public extension P5 where T1 : Comparable{ /// This is picked public func foo3() {} } public extension P5 where T1 : Comparable { /// This is picked public func foo4() {} } public extension P5 where T1 : AnyObject { /// This should not crash public func foo5() {} } public extension P5 { /// This is not picked public func foo4() {} } public struct S12 : P5{ public typealias T1 = Int public func foo1() {} } public protocol P6 { func foo1() func foo2() } public extension P6 { public func foo1() {} } public protocol P7 { associatedtype T1 func f1(t: T1) } public extension P7 { public func nomergeFunc(t: T1) -> T1 { return t } public func f1(t: T1) -> T1 { return t } } public struct S13 {} extension S13 : P5 { public typealias T1 = Int public func foo1() {} } // CHECK1: <synthesized>extension <ref:Struct>S1</ref> where T : <ref:Protocol>P2</ref> { // CHECK1-NEXT: <decl:Func>public func <loc>p2member()</loc></decl> // CHECK1-NEXT: <decl:Func>public func <loc>ef1(<decl:Param>t: T</decl>)</loc></decl> // CHECK1-NEXT: <decl:Func>public func <loc>ef2(<decl:Param>t: <ref:Struct>S2</ref></decl>)</loc></decl> // CHECK1-NEXT: }</synthesized> // CHECK2: <synthesized>extension <ref:Struct>S1</ref> where T : <ref:Protocol>P3</ref> { // CHECK2-NEXT: <decl:Func>public func <loc>p3Func(<decl:Param>i: <ref:Struct>Int</ref></decl>)</loc> -> <ref:Struct>Int</ref></decl> // CHECK2-NEXT: }</synthesized> // CHECK3: <synthesized>extension <ref:Struct>S1</ref> where T == <ref:Struct>Int</ref> { // CHECK3-NEXT: <decl:Func>public func <loc>p1IntFunc(<decl:Param>i: <ref:Struct>Int</ref></decl>)</loc> -> <ref:Struct>Int</ref></decl> // CHECK3-NEXT: }</synthesized> // CHECK4: <synthesized>extension <ref:Struct>S1</ref> where T == <ref:Struct>S9</ref><<ref:Struct>Int</ref>> { // CHECK4-NEXT: <decl:Func>public func <loc>S9IntFunc()</loc></decl> // CHECK4-NEXT: }</synthesized> // CHECK5: <decl:Struct>public struct <loc>S10</loc> : <ref:module>print_synthesized_extensions</ref>.<ref:Protocol>P1</ref> { // CHECK5-NEXT: <decl:TypeAlias>public typealias <loc>T1</loc> = <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S9</ref><<ref:Struct>Int</ref>></decl> // CHECK5-NEXT: <decl:TypeAlias>public typealias <loc>T2</loc> = <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S9</ref><<ref:Struct>Int</ref>></decl> // CHECK5-NEXT: <decl:Func>public func <loc>f1(<decl:Param>t: <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S10</ref>.<ref:TypeAlias>T1</ref></decl>)</loc> -> <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S10</ref>.<ref:TypeAlias>T1</ref></decl> // CHECK5-NEXT: <decl:Func>public func <loc>f2(<decl:Param>t: <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S10</ref>.<ref:TypeAlias>T2</ref></decl>)</loc> -> <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S10</ref>.<ref:TypeAlias>T2</ref></decl></decl> // CHECK5-NEXT: <decl:Func>public func <loc>p3Func(<decl:Param>i: <ref:Struct>Int</ref></decl>)</loc> -> <ref:Struct>Int</ref></decl> // CHECK5-NEXT: <decl:Func>public func <loc>ef5(<decl:Param>t: <ref:Struct>S9</ref><<ref:Struct>Int</ref>></decl>)</loc></decl> // CHECK5-NEXT: <decl:Func>public func <loc>S9IntFunc()</loc></decl> // CHECK5-NEXT: }</synthesized> // CHECK6: <synthesized>/// Extension on P4Func1 // CHECK6-NEXT: extension <ref:Struct>S11</ref> { // CHECK6-NEXT: <decl:Func>public func <loc>P4Func1()</loc></decl> // CHECK6-NEXT: }</synthesized> // CHECK7: <synthesized>/// Extension on P4Func2 // CHECK7-NEXT: extension <ref:Struct>S11</ref> { // CHECK7-NEXT: <decl:Func>public func <loc>P4Func2()</loc></decl> // CHECK7-NEXT: }</synthesized> // CHECK8: <decl:Struct>public struct <loc>S4<<decl:GenericTypeParam>T</decl>></loc> : <ref:module>print_synthesized_extensions</ref>.<ref:Protocol>P1</ref> { // CHECK8-NEXT: <decl:TypeAlias>public typealias <loc>T1</loc> = <ref:Struct>Int</ref></decl> // CHECK8-NEXT: <decl:TypeAlias>public typealias <loc>T2</loc> = <ref:Struct>Int</ref></decl> // CHECK8-NEXT: <decl:Func>public func <loc>f1(<decl:Param>t: <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S4</ref><T>.<ref:TypeAlias>T1</ref></decl>)</loc> -> <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S4</ref><T>.<ref:TypeAlias>T1</ref></decl> // CHECK8-NEXT: <decl:Func>public func <loc>f2(<decl:Param>t: <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S4</ref><T>.<ref:TypeAlias>T2</ref></decl>)</loc> -> <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S4</ref><T>.<ref:TypeAlias>T2</ref></decl></decl> // CHECK8-NEXT: <decl:Func>public func <loc>p1IntFunc(<decl:Param>i: <ref:Struct>Int</ref></decl>)</loc> -> <ref:Struct>Int</ref></decl> // CHECK8-NEXT: }</synthesized> // CHECK9: <decl:Struct>public struct <loc>S6<<decl:GenericTypeParam>T</decl>></loc> : <ref:module>print_synthesized_extensions</ref>.<ref:Protocol>P1</ref> { // CHECK9-NEXT: <decl:TypeAlias>public typealias <loc>T1</loc> = <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S5</ref></decl> // CHECK9-NEXT: <decl:TypeAlias>public typealias <loc>T2</loc> = <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S5</ref></decl> // CHECK9-NEXT: <decl:Func>public func <loc>f1(<decl:Param>t: <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S6</ref><T>.<ref:TypeAlias>T1</ref></decl>)</loc> -> <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S6</ref><T>.<ref:TypeAlias>T1</ref></decl> // CHECK9-NEXT: <decl:Func>public func <loc>f2(<decl:Param>t: <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S6</ref><T>.<ref:TypeAlias>T2</ref></decl>)</loc> -> <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S6</ref><T>.<ref:TypeAlias>T2</ref></decl></decl> // CHECK9-NEXT: <decl:Extension><decl:Func>public func <loc>f3()</loc></decl></decl> // CHECK9-NEXT: <decl:Extension><decl:Func>public func <loc>fromActualExtension()</loc></decl></decl> // CHECK9-NEXT: <decl:Func>public func <loc>p3Func(<decl:Param>i: <ref:Struct>Int</ref></decl>)</loc> -> <ref:Struct>Int</ref></decl> // CHECK9-NEXT: <decl:Func>public func <loc>ef5(<decl:Param>t: <ref:Struct>S5</ref></decl>)</loc></decl> // CHECK9-NEXT: }</synthesized> // CHECK10: <synthesized>extension <ref:Struct>S7</ref>.<ref:Struct>S8</ref> { // CHECK10-NEXT: <decl:Func>public func <loc>p3Func(<decl:Param>i: <ref:Struct>Int</ref></decl>)</loc> -> <ref:Struct>Int</ref></decl> // CHECK10-NEXT: <decl:Func>public func <loc>ef5(<decl:Param>t: <ref:Struct>S5</ref></decl>)</loc></decl> // CHECK10-NEXT: }</synthesized> // CHECK11: <decl:Struct>public struct <loc>S12</loc> : <ref:module>print_synthesized_extensions</ref>.<ref:Protocol>P5</ref> { // CHECK11-NEXT: <decl:TypeAlias>public typealias <loc>T1</loc> = <ref:Struct>Int</ref></decl> // CHECK11-NEXT: <decl:Func>/// This is picked // CHECK11-NEXT: public func <loc>foo1()</loc></decl></decl> // CHECK11-NEXT: <decl:Func>/// This is picked // CHECK11-NEXT: public func <loc>foo2()</loc></decl> // CHECK11-NEXT: <decl:Func>/// This is picked // CHECK11-NEXT: public func <loc>foo3()</loc></decl> // CHECK11-NEXT: <decl:Func>/// This is picked // CHECK11-NEXT: public func <loc>foo4()</loc></decl> // CHECK11-NEXT: <decl:Func>/// This should not crash // CHECK11-NEXT: public func <loc>foo5()</loc></decl> // CHECK11-NEXT: }</synthesized> // CHECK12: <decl:Protocol>public protocol <loc>P6</loc> { // CHECK12-NEXT: <decl:Func(HasDefault)>func <loc>foo1()</loc></decl> // CHECK12-NEXT: <decl:Func>func <loc>foo2()</loc></decl> // CHECK12-NEXT: }</decl> // CHECK13: <decl:Protocol>public protocol <loc>P7</loc> { // CHECK13-NEXT: <decl:AssociatedType>associatedtype <loc>T1</loc></decl> // CHECK13-NEXT: <decl:Func(HasDefault)>func <loc>f1(<decl:Param>t: <ref:GenericTypeParam>Self</ref>.T1</decl>)</loc></decl> // CHECK13-NEXT: }</decl> // CHECK13: <decl:Extension>extension <loc><ref:Protocol>P7</ref></loc> { // CHECK13-NEXT: <decl:Func>public func <loc>nomergeFunc(<decl:Param>t: <ref:GenericTypeParam>Self</ref>.T1</decl>)</loc> -> <ref:GenericTypeParam>Self</ref>.T1</decl> // CHECK13-NEXT: <decl:Func>public func <loc>f1(<decl:Param>t: <ref:GenericTypeParam>Self</ref>.T1</decl>)</loc> -> <ref:GenericTypeParam>Self</ref>.T1</decl> // CHECK13-NEXT: }</decl> // CHECK14: <decl:Struct>public struct <loc>S13</loc> {</decl> // CHECK14-NEXT: <decl:Func>/// This is picked // CHECK14-NEXT: public func <loc>foo2()</loc></decl> // CHECK14-NEXT: <decl:Func>/// This is picked // CHECK14-NEXT: public func <loc>foo3()</loc></decl> // CHECK14-NEXT: <decl:Func>/// This is picked // CHECK14-NEXT: public func <loc>foo4()</loc></decl> // CHECK14-NEXT: <decl:Func>/// This should not crash // CHECK14-NEXT: public func <loc>foo5()</loc></decl> // CHECK14-NEXT: }</synthesized>
apache-2.0
77fd0103b48ed6e886bffa859dd8955c
36.826979
285
0.65602
2.812691
false
false
false
false
roambotics/swift
test/SILOptimizer/static_arrays.swift
2
9332
// RUN: %target-swift-frontend -primary-file %s -O -sil-verify-all -Xllvm -sil-disable-pass=FunctionSignatureOpts -module-name=test -emit-sil | %FileCheck %s // RUN: %target-swift-frontend -primary-file %s -O -sil-verify-all -Xllvm -sil-disable-pass=FunctionSignatureOpts -module-name=test -emit-ir | %FileCheck %s -check-prefix=CHECK-LLVM // Also do an end-to-end test to check all components, including IRGen. // RUN: %empty-directory(%t) // RUN: %target-build-swift -O -Xllvm -sil-disable-pass=FunctionSignatureOpts -module-name=test %s -o %t/a.out // RUN: %target-run %t/a.out | %FileCheck %s -check-prefix=CHECK-OUTPUT // REQUIRES: executable_test,swift_stdlib_no_asserts,optimized_stdlib // REQUIRES: CPU=arm64 || CPU=x86_64 // REQUIRES: swift_in_compiler // Check if the optimizer is able to convert array literals to statically initialized arrays. // CHECK-LABEL: sil_global @$s4test4FStrV10globalFuncyS2icvpZ : $@callee_guaranteed (Int) -> Int = { // CHECK: %0 = function_ref @$s4test3fooyS2iF : $@convention(thin) (Int) -> Int // CHECK-NEXT: %initval = thin_to_thick_function %0 // CHECK-NEXT: } // CHECK-LABEL: outlined variable #0 of arrayLookup(_:) // CHECK-NEXT: sil_global private @{{.*}}arrayLookup{{.*}} = { // CHECK-DAG: integer_literal $Builtin.Int{{[0-9]+}}, 10 // CHECK-DAG: integer_literal $Builtin.Int{{[0-9]+}}, 11 // CHECK-DAG: integer_literal $Builtin.Int{{[0-9]+}}, 12 // CHECK: object {{.*}} ({{[^,]*}}, [tail_elems] {{[^,]*}}, {{[^,]*}}, {{[^,]*}}) // CHECK-NEXT: } // CHECK-LABEL: outlined variable #0 of returnArray() // CHECK-NEXT: sil_global private @{{.*}}returnArray{{.*}} = { // CHECK-DAG: integer_literal $Builtin.Int{{[0-9]+}}, 20 // CHECK-DAG: integer_literal $Builtin.Int{{[0-9]+}}, 21 // CHECK: object {{.*}} ({{[^,]*}}, [tail_elems] {{[^,]*}}, {{[^,]*}}) // CHECK-NEXT: } // CHECK-LABEL: outlined variable #0 of returnStaticStringArray() // CHECK-NEXT: sil_global private @{{.*}}returnStaticStringArray{{.*}} = { // CHECK-DAG: string_literal utf8 "a" // CHECK-DAG: string_literal utf8 "b" // CHECK: object {{.*}} ({{[^,]*}}, [tail_elems] {{[^,]*}}, {{[^,]*}}) // CHECK-NEXT: } // CHECK-LABEL: outlined variable #0 of passArray() // CHECK-NEXT: sil_global private @{{.*}}passArray{{.*}} = { // CHECK-DAG: integer_literal $Builtin.Int{{[0-9]+}}, 27 // CHECK-DAG: integer_literal $Builtin.Int{{[0-9]+}}, 28 // CHECK: object {{.*}} ({{[^,]*}}, [tail_elems] {{[^,]*}}, {{[^,]*}}) // CHECK-NEXT: } // CHECK-LABEL: outlined variable #1 of passArray() // CHECK-NEXT: sil_global private @{{.*}}passArray{{.*}} = { // CHECK: integer_literal $Builtin.Int{{[0-9]+}}, 29 // CHECK: object {{.*}} ({{[^,]*}}, [tail_elems] {{[^,]*}}) // CHECK-NEXT: } // CHECK-LABEL: outlined variable #0 of storeArray() // CHECK-NEXT: sil_global private @{{.*}}storeArray{{.*}} = { // CHECK-DAG: integer_literal $Builtin.Int{{[0-9]+}}, 227 // CHECK-DAG: integer_literal $Builtin.Int{{[0-9]+}}, 228 // CHECK: object {{.*}} ({{[^,]*}}, [tail_elems] {{[^,]*}}, {{[^,]*}}) // CHECK-NEXT: } // CHECK-LABEL: outlined variable #0 of functionArray() // CHECK-NEXT: sil_global private @{{.*functionArray.*}} = { // CHECK: function_ref // CHECK: thin_to_thick_function // CHECK: convert_function // CHECK: function_ref // CHECK: thin_to_thick_function // CHECK: convert_function // CHECK: object {{.*}} ({{[^,]*}}, [tail_elems] // CHECK-NEXT: } // CHECK-LABEL: outlined variable #0 of returnDictionary() // CHECK-NEXT: sil_global private @{{.*}}returnDictionary{{.*}} = { // CHECK-DAG: integer_literal $Builtin.Int{{[0-9]+}}, 5 // CHECK-DAG: integer_literal $Builtin.Int{{[0-9]+}}, 4 // CHECK-DAG: integer_literal $Builtin.Int{{[0-9]+}}, 2 // CHECK-DAG: integer_literal $Builtin.Int{{[0-9]+}}, 1 // CHECK-DAG: integer_literal $Builtin.Int{{[0-9]+}}, 6 // CHECK-DAG: integer_literal $Builtin.Int{{[0-9]+}}, 3 // CHECK: object {{.*}} ({{[^,]*}}, [tail_elems] // CHECK-NEXT: } // CHECK-LABEL: outlined variable #0 of returnStringDictionary() // CHECK-NEXT: sil_global private @{{.*}}returnStringDictionary{{.*}} = { // CHECK: object {{.*}} ({{[^,]*}}, [tail_elems] // CHECK-NEXT: } // CHECK-LABEL: sil_global private @{{.*}}main{{.*}} = { // CHECK-DAG: integer_literal $Builtin.Int{{[0-9]+}}, 100 // CHECK-DAG: integer_literal $Builtin.Int{{[0-9]+}}, 101 // CHECK-DAG: integer_literal $Builtin.Int{{[0-9]+}}, 102 // CHECK: object {{.*}} ({{[^,]*}}, [tail_elems] {{[^,]*}}, {{[^,]*}}, {{[^,]*}}) // CHECK-NEXT: } // CHECK-LABEL: sil {{.*}}@main // CHECK: global_value @{{.*}}main{{.*}} // CHECK: return public let globalVariable = [ 100, 101, 102 ] // CHECK-LABEL: sil [noinline] @$s4test11arrayLookupyS2iF // CHECK: global_value @$s4test11arrayLookupyS2iFTv_ // CHECK-NOT: retain // CHECK-NOT: release // CHECK: } // end sil function '$s4test11arrayLookupyS2iF' // CHECK-LLVM-LABEL: define {{.*}} @"$s4test11arrayLookupyS2iF" // CHECK-LLVM-NOT: call // CHECK-LLVM: [[E:%[0-9]+]] = getelementptr {{.*}} @"$s4test11arrayLookupyS2iFTv_" // CHECK-LLVM-NEXT: [[L:%[0-9]+]] = load {{.*}} [[E]] // CHECK-LLVM-NEXT: ret {{.*}} [[L]] // CHECK-LLVM: } @inline(never) public func arrayLookup(_ i: Int) -> Int { let lookupTable = [10, 11, 12] return lookupTable[i] } // CHECK-LABEL: sil {{.*}}returnArray{{.*}} : $@convention(thin) () -> @owned Array<Int> { // CHECK: global_value @{{.*}}returnArray{{.*}} // CHECK: return @inline(never) public func returnArray() -> [Int] { return [20, 21] } // CHECK-LABEL: sil {{.*}}returnStaticStringArray{{.*}} : $@convention(thin) () -> @owned Array<StaticString> { // CHECK: global_value @{{.*}}returnStaticStringArray{{.*}} // CHECK: return @inline(never) public func returnStaticStringArray() -> [StaticString] { return ["a", "b"] } public var gg: [Int]? @inline(never) public func receiveArray(_ a: [Int]) { gg = a } // CHECK-LABEL: sil {{.*}}passArray{{.*}} : $@convention(thin) () -> () { // CHECK: global_value @{{.*}}passArray{{.*}} // CHECK: global_value @{{.*}}passArray{{.*}} // CHECK: return @inline(never) public func passArray() { receiveArray([27, 28]) receiveArray([29]) } // CHECK-LABEL: sil {{.*}}storeArray{{.*}} : $@convention(thin) () -> () { // CHECK: global_value @{{.*}}storeArray{{.*}} // CHECK: return @inline(never) public func storeArray() { gg = [227, 228] } struct Empty { } // CHECK-LABEL: sil {{.*}}arrayWithEmptyElements{{.*}} : $@convention(thin) () -> @owned Array<Empty> { func arrayWithEmptyElements() -> [Empty] { // CHECK: global_value @{{.*}}arrayWithEmptyElements{{.*}} // CHECK: return return [Empty()] } // CHECK-LABEL: sil {{.*}}returnDictionary{{.*}} : $@convention(thin) () -> @owned Dictionary<Int, Int> { // CHECK: global_value @{{.*}}returnDictionary{{.*}} // CHECK: return @inline(never) public func returnDictionary() -> [Int:Int] { return [1:2, 3:4, 5:6] } // CHECK-LABEL: sil {{.*}}returnStringDictionary{{.*}} : $@convention(thin) () -> @owned Dictionary<String, String> { // CHECK: global_value @{{.*}}returnStringDictionary{{.*}} // CHECK: return @inline(never) public func returnStringDictionary() -> [String:String] { return ["1":"2", "3":"4", "5":"6"] } func foo(_ i: Int) -> Int { return i } // CHECK-LABEL: sil {{.*functionArray.*}} : $@convention(thin) () -> @owned Array<(Int) -> Int> { // CHECK: global_value @{{.*functionArray.*}} // CHECK: } // end sil function '{{.*functionArray.*}}' @inline(never) func functionArray() -> [(Int) -> Int] { func bar(_ i: Int) -> Int { return i + 1 } return [foo, bar, { $0 + 10 }] } public struct FStr { // Not an array, but also tested here. public static var globalFunc = foo } // CHECK-OUTPUT: [100, 101, 102] print(globalVariable) // CHECK-OUTPUT-NEXT: 11 print(arrayLookup(1)) // CHECK-OUTPUT-NEXT: [20, 21] print(returnArray()) // CHECK-OUTPUT-NEXT: ["a", "b"] print(returnStaticStringArray()) passArray() // CHECK-OUTPUT-NEXT: [29] print(gg!) storeArray() // CHECK-OUTPUT-NEXT: [227, 228] print(gg!) // CHECK-OUTPUT-NEXT: 311 print(functionArray()[0](100) + functionArray()[1](100) + functionArray()[2](100)) // CHECK-OUTPUT-NEXT: 27 print(FStr.globalFunc(27)) let dict = returnDictionary() // CHECK-OUTPUT-NEXT: dict 3: 2, 4, 6 print("dict \(dict.count): \(dict[1]!), \(dict[3]!), \(dict[5]!)") let sdict = returnStringDictionary() // CHECK-OUTPUT-NEXT: sdict 3: 2, 4, 6 print("sdict \(sdict.count): \(sdict["1"]!), \(sdict["3"]!), \(sdict["5"]!)") public class SwiftClass {} @inline(never) func takeUnsafePointer(ptr : UnsafePointer<SwiftClass>, len: Int) { print(ptr, len) // Use the arguments somehow so they don't get removed. } // This should be a single basic block, and the array should end up being stack // allocated. // // CHECK-LABEL: sil @{{.*}}passArrayOfClasses // CHECK: bb0(%0 : $SwiftClass, %1 : $SwiftClass, %2 : $SwiftClass): // CHECK-NOT: bb1( // CHECK: alloc_ref{{(_dynamic)?}} {{.*}}[tail_elems $SwiftClass * // CHECK-NOT: bb1( // CHECK: return public func passArrayOfClasses(a: SwiftClass, b: SwiftClass, c: SwiftClass) { let arr = [a, b, c] takeUnsafePointer(ptr: arr, len: arr.count) }
apache-2.0
a32446d9275bf555832fbdc2bd1f0e0f
36.179283
182
0.599443
3.361671
false
true
false
false
MooYoo/UINavigationBarStyle
Example/UINavigationBarStyle/TableViewController.swift
1
2270
// // TableViewController.swift // UINavigationBarStyle // // Created by Alan on 17/4/6. // Copyright © 2017年 CocoaPods. All rights reserved. // import UIKit import UINavigationBarExtension var aindex: Int = 1 class TableViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() automaticallyAdjustsScrollViewInsets = false navigationBarBackgroundAlpha = 0 navigationBarTintColor = UIColor.red statusBarStyle = .lightContent navigationBarTitleTextAttributes = [NSForegroundColorAttributeName: UIColor.white] statusBarStyle = .lightContent navigationBarShadowImageHidden = true title = String(describing: aindex) aindex = aindex + 1 } override func scrollViewDidScroll(_ scrollView: UIScrollView) { let alpha = min(max(scrollView.contentOffset.y / 80, 0), 1) navigationBarBackgroundAlpha = alpha if alpha > 0.9 { navigationBarTintColor = nil statusBarStyle = .default navigationBarTitleTextAttributes = nil } else { navigationBarTintColor = UIColor.red statusBarStyle = .lightContent navigationBarTitleTextAttributes = [NSForegroundColorAttributeName: UIColor.white] } } @IBAction func clickBarButtonItem(_ sender: AnyObject) { let controller = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "TableViewController") navigationController?.pushViewController(controller, animated: true) } @IBAction func clickPopToButton(_ sender: AnyObject) { let count = navigationController!.viewControllers.count - 3 guard count < navigationController!.viewControllers.count else {return} let controller = navigationController!.viewControllers[count] navigationController?.popToViewController(controller, animated: true) } @IBAction func clickPopRootButton(_ sender: AnyObject) { navigationController?.popToRootViewController(animated: true) } // override func preferredStatusBarStyle() -> UIStatusBarStyle { // return statusBarStyle // } }
mit
10afdc61639bb73b3eca6fb3c453bc36
32.338235
129
0.678871
5.950131
false
false
false
false
kamleshgk/iOSStarterTemplate
foodcolors/ThirdParty/Dodo/DodoDistrib.swift
1
80269
// // Dodo // // A message bar for iOS. // // https://github.com/marketplacer/Dodo // // This file was automatically generated by combining multiple Swift source files. // // ---------------------------- // // DodoAnimation.swift // // ---------------------------- import UIKit /// A closure that is called for animation of the bar when it is being shown or hidden. public typealias DodoAnimation = (UIView, _ duration: TimeInterval?, _ locationTop: Bool, _ completed: @escaping DodoAnimationCompleted)->() /// A closure that is called by the animator when animation has finished. public typealias DodoAnimationCompleted = ()->() // ---------------------------- // // DodoAnimations.swift // // ---------------------------- import UIKit /// Collection of animation effects use for showing and hiding the notification bar. public enum DodoAnimations: String { /// Animation that fades the bar in/out. case fade = "Fade" /// Used for showing notification without animation. case noAnimation = "No animation" /// Animation that rotates the bar around X axis in perspective with spring effect. case rotate = "Rotate" /// Animation that swipes the bar to/from the left with fade effect. case slideLeft = "Slide left" /// Animation that swipes the bar to/from the right with fade effect. case slideRight = "Slide right" /// Animation that slides the bar in/out vertically. case slideVertically = "Slide vertically" /** Get animation function that can be used for showing notification bar. - returns: Animation function. */ public var show: DodoAnimation { switch self { case .fade: return DodoAnimationsShow.fade case .noAnimation: return DodoAnimations.doNoAnimation case .rotate: return DodoAnimationsShow.rotate case .slideLeft: return DodoAnimationsShow.slideLeft case .slideRight: return DodoAnimationsShow.slideRight case .slideVertically: return DodoAnimationsShow.slideVertically } } /** Get animation function that can be used for hiding notification bar. - returns: Animation function. */ public var hide: DodoAnimation { switch self { case .fade: return DodoAnimationsHide.fade case .noAnimation: return DodoAnimations.doNoAnimation case .rotate: return DodoAnimationsHide.rotate case .slideLeft: return DodoAnimationsHide.slideLeft case .slideRight: return DodoAnimationsHide.slideRight case .slideVertically: return DodoAnimationsHide.slideVertically } } /** A empty animator which is used when no animation is supplied. It simply calls the completion closure. - parameter view: View supplied for animation. - parameter completed: A closure to be called after animation completes. */ static func doNoAnimation(_ view: UIView, duration: TimeInterval?, locationTop: Bool, completed: DodoAnimationCompleted) { completed() } /// Helper function for fading the view in and out. static func doFade(_ duration: TimeInterval?, showView: Bool, view: UIView, completed: @escaping DodoAnimationCompleted) { let actualDuration = duration ?? 0.5 let startAlpha: CGFloat = showView ? 0 : 1 let endAlpha: CGFloat = showView ? 1 : 0 view.alpha = startAlpha UIView.animate(withDuration: actualDuration, animations: { view.alpha = endAlpha }, completion: { finished in completed() } ) } /// Helper function for sliding the view vertically static func doSlideVertically(_ duration: TimeInterval?, showView: Bool, view: UIView, locationTop: Bool, completed: @escaping DodoAnimationCompleted) { let actualDuration = duration ?? 0.5 view.layoutIfNeeded() var distance: CGFloat = 0 if locationTop { distance = view.frame.height + view.frame.origin.y } else { distance = UIScreen.main.bounds.height - view.frame.origin.y } let transform = CGAffineTransform(translationX: 0, y: locationTop ? -distance : distance) let start: CGAffineTransform = showView ? transform : CGAffineTransform.identity let end: CGAffineTransform = showView ? CGAffineTransform.identity : transform view.transform = start UIView.animate(withDuration: actualDuration, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: [], animations: { view.transform = end }, completion: { finished in completed() } ) } static weak var timer: MoaTimer? /// Animation that rotates the bar around X axis in perspective with spring effect. static func doRotate(_ duration: TimeInterval?, showView: Bool, view: UIView, completed: @escaping DodoAnimationCompleted) { let actualDuration = duration ?? 2.0 let start: Double = showView ? Double(M_PI / 2) : 0 let end: Double = showView ? 0 : Double(M_PI / 2) let damping = showView ? 0.85 : 3 let myCALayer = view.layer var transform = CATransform3DIdentity transform.m34 = -1.0/200.0 myCALayer.transform = CATransform3DRotate(transform, CGFloat(end), 1, 0, 0) myCALayer.zPosition = 300 SpringAnimationCALayer.animate(myCALayer, keypath: "transform.rotation.x", duration: actualDuration, usingSpringWithDamping: damping, initialSpringVelocity: 1, fromValue: start, toValue: end, onFinished: showView ? completed : nil) // Hide the bar prematurely for better looks timer?.cancel() if !showView { timer = MoaTimer.runAfter(0.3) { timer in completed() } } } /// Animation that swipes the bar to the right with fade-out effect. static func doSlide(_ duration: TimeInterval?, right: Bool, showView: Bool, view: UIView, completed: @escaping DodoAnimationCompleted) { let actualDuration = duration ?? 0.4 let distance = UIScreen.main.bounds.width let transform = CGAffineTransform(translationX: right ? distance : -distance, y: 0) let start: CGAffineTransform = showView ? transform : CGAffineTransform.identity let end: CGAffineTransform = showView ? CGAffineTransform.identity : transform let alphaStart: CGFloat = showView ? 0.2 : 1 let alphaEnd: CGFloat = showView ? 1 : 0.2 view.transform = start view.alpha = alphaStart UIView.animate(withDuration: actualDuration, delay: 0, options: UIViewAnimationOptions.curveEaseOut, animations: { view.transform = end view.alpha = alphaEnd }, completion: { finished in completed() } ) } } // ---------------------------- // // DodoAnimationsHide.swift // // ---------------------------- import UIKit /// Collection of animation effects use for hiding the notification bar. struct DodoAnimationsHide { /** Animation that rotates the bar around X axis in perspective with spring effect. - parameter view: View supplied for animation. - parameter completed: A closure to be called after animation completes. */ static func rotate(_ view: UIView, duration: TimeInterval?, locationTop: Bool, completed: @escaping DodoAnimationCompleted) { DodoAnimations.doRotate(duration, showView: false, view: view, completed: completed) } /** Animation that swipes the bar from to the left with fade-in effect. - parameter view: View supplied for animation. - parameter completed: A closure to be called after animation completes. */ static func slideLeft(_ view: UIView, duration: TimeInterval?, locationTop: Bool, completed: @escaping DodoAnimationCompleted) { DodoAnimations.doSlide(duration, right: false, showView: false, view: view, completed: completed) } /** Animation that swipes the bar to the right with fade-out effect. - parameter view: View supplied for animation. - parameter completed: A closure to be called after animation completes. */ static func slideRight(_ view: UIView, duration: TimeInterval?, locationTop: Bool, completed: @escaping DodoAnimationCompleted) { DodoAnimations.doSlide(duration, right: true, showView: false, view: view, completed: completed) } /** Animation that fades the bar out. - parameter view: View supplied for animation. - parameter completed: A closure to be called after animation completes. */ static func fade(_ view: UIView, duration: TimeInterval?, locationTop: Bool, completed: @escaping DodoAnimationCompleted) { DodoAnimations.doFade(duration, showView: false, view: view, completed: completed) } /** Animation that slides the bar vertically out of view. - parameter view: View supplied for animation. - parameter completed: A closure to be called after animation completes. */ static func slideVertically(_ view: UIView, duration: TimeInterval?, locationTop: Bool, completed: @escaping DodoAnimationCompleted) { DodoAnimations.doSlideVertically(duration, showView: false, view: view, locationTop: locationTop, completed: completed) } } // ---------------------------- // // DodoAnimationsShow.swift // // ---------------------------- import UIKit /// Collection of animation effects use for showing the notification bar. struct DodoAnimationsShow { /** Animation that rotates the bar around X axis in perspective with spring effect. - parameter view: View supplied for animation. - parameter completed: A closure to be called after animation completes. */ static func rotate(_ view: UIView, duration: TimeInterval?, locationTop: Bool, completed: @escaping DodoAnimationCompleted) { DodoAnimations.doRotate(duration, showView: true, view: view, completed: completed) } /** Animation that swipes the bar from the left with fade-in effect. - parameter view: View supplied for animation. - parameter completed: A closure to be called after animation completes. */ static func slideLeft(_ view: UIView, duration: TimeInterval?, locationTop: Bool, completed: @escaping DodoAnimationCompleted) { DodoAnimations.doSlide(duration, right: false, showView: true, view: view, completed: completed) } /** Animation that swipes the bar from the right with fade-in effect. - parameter view: View supplied for animation. - parameter completed: A closure to be called after animation completes. */ static func slideRight(_ view: UIView, duration: TimeInterval?, locationTop: Bool, completed: @escaping DodoAnimationCompleted) { DodoAnimations.doSlide(duration, right: true, showView: true, view: view, completed: completed) } /** Animation that fades the bar in. - parameter view: View supplied for animation. - parameter completed: A closure to be called after animation completes. */ static func fade(_ view: UIView, duration: TimeInterval?, locationTop: Bool, completed: @escaping DodoAnimationCompleted) { DodoAnimations.doFade(duration, showView: true, view: view, completed: completed) } /** Animation that slides the bar in/out vertically. - parameter view: View supplied for animation. - parameter completed: A closure to be called after animation completes. */ static func slideVertically(_ view: UIView, duration: TimeInterval?, locationTop: Bool, completed: @escaping DodoAnimationCompleted) { DodoAnimations.doSlideVertically(duration, showView: true, view: view, locationTop: locationTop,completed: completed) } } // ---------------------------- // // DodoButtonOnTap.swift // // ---------------------------- /// A closure that is called when a bar button is tapped public typealias DodoButtonOnTap = ()->() // ---------------------------- // // DodoButtonView.swift // // ---------------------------- import UIKit class DodoButtonView: UIImageView { private let style: DodoButtonStyle weak var delegate: DodoButtonViewDelegate? var onTap: OnTap? init(style: DodoButtonStyle) { self.style = style super.init(frame: CGRect()) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // Create button views for given button styles. static func createMany(_ styles: [DodoButtonStyle]) -> [DodoButtonView] { if !haveButtons(styles) { return [] } return styles.map { style in let view = DodoButtonView(style: style) view.setup() return view } } static func haveButtons(_ styles: [DodoButtonStyle]) -> Bool { let hasImages = styles.filter({ $0.image != nil }).count > 0 let hasIcons = styles.filter({ $0.icon != nil }).count > 0 return hasImages || hasIcons } func doLayout(onLeftSide: Bool) { precondition(delegate != nil, "Button view delegate can not be nil") translatesAutoresizingMaskIntoConstraints = false // Set button's size TegAutolayoutConstraints.width(self, value: style.size.width) TegAutolayoutConstraints.height(self, value: style.size.height) if let superview = superview { let alignAttribute = onLeftSide ? NSLayoutAttribute.left : NSLayoutAttribute.right let marginHorizontal = onLeftSide ? style.horizontalMarginToBar : -style.horizontalMarginToBar // Align the button to the left/right of the view TegAutolayoutConstraints.alignSameAttributes(self, toItem: superview, constraintContainer: superview, attribute: alignAttribute, margin: marginHorizontal) // Center the button verticaly TegAutolayoutConstraints.centerY(self, viewTwo: superview, constraintContainer: superview) } } func setup() { if let image = DodoButtonView.image(style) { applyStyle(image) } setupTap() } /// Increase the hitsize of the image view if it's less than 44px for easier tapping. override func point(inside point: CGPoint, with event: UIEvent?) -> Bool { let oprimizedBounds = DodoTouchTarget.optimize(bounds) return oprimizedBounds.contains(point) } /// Returns the image supplied by user or create one from the icon class func image(_ style: DodoButtonStyle) -> UIImage? { if style.image != nil { return style.image } if let icon = style.icon { let bundle = Bundle(for: self) let imageName = icon.rawValue return UIImage(named: imageName, in: bundle, compatibleWith: nil) } return nil } private func applyStyle(_ imageIn: UIImage) { var imageToShow = imageIn if let tintColorToShow = style.tintColor { // Replace image colors with the specified tint color imageToShow = imageToShow.withRenderingMode(UIImageRenderingMode.alwaysTemplate) tintColor = tintColorToShow } layer.minificationFilter = kCAFilterTrilinear // make the image crisp image = imageToShow contentMode = UIViewContentMode.scaleAspectFit // Make button accessible if let accessibilityLabelToShow = style.accessibilityLabel { isAccessibilityElement = true accessibilityLabel = accessibilityLabelToShow accessibilityTraits = UIAccessibilityTraitButton } } private func setupTap() { onTap = OnTap(view: self, gesture: UITapGestureRecognizer()) { [weak self] in self?.didTap() } } private func didTap() { self.delegate?.buttonDelegateDidTap(self.style) style.onTap?() } } // ---------------------------- // // DodoButtonViewDelegate.swift // // ---------------------------- protocol DodoButtonViewDelegate: class { func buttonDelegateDidTap(_ buttonStyle: DodoButtonStyle) } // ---------------------------- // // Dodo.swift // // ---------------------------- import UIKit /** Main class that coordinates the process of showing and hiding of the message bar. Instance of this class is created automatically in the `dodo` property of any UIView instance. It is not expected to be instantiated manually anywhere except unit tests. For example: let view = UIView() view.dodo.info("Horses are blue?") */ final class Dodo: DodoInterface, DodoButtonViewDelegate { private weak var superview: UIView! private var hideTimer: MoaTimer? // Gesture handler that hides the bar when it is tapped var onTap: OnTap? /// Specify optional layout guide for positioning the bar view. var topLayoutGuide: UILayoutSupport? /// Specify optional layout guide for positioning the bar view. var bottomLayoutGuide: UILayoutSupport? /// Defines styles for the bar. var style = DodoStyle(parentStyle: DodoPresets.defaultPreset.style) /// Creates an instance of Dodo class init(superview: UIView) { self.superview = superview DodoKeyboardListener.startListening() } /// Changes the style preset for the bar widget. var preset: DodoPresets = DodoPresets.defaultPreset { didSet { if preset != oldValue { style.parent = preset.style } } } /** Shows the message bar with *.success* preset. It can be used to indicate successful completion of an operation. - parameter message: The text message to be shown. */ func success(_ message: String) { preset = .success show(message) } /** Shows the message bar with *.Info* preset. It can be used for showing information messages that have neutral emotional value. - parameter message: The text message to be shown. */ func info(_ message: String) { preset = .info show(message) } /** Shows the message bar with *.warning* preset. It can be used for for showing warning messages. - parameter message: The text message to be shown. */ func warning(_ message: String) { preset = .warning show(message) } /** Shows the message bar with *.warning* preset. It can be used for showing critical error messages - parameter message: The text message to be shown. */ func error(_ message: String) { preset = .error show(message) } /** Shows the message bar. Set `preset` property to change the appearance of the message bar, or use the shortcut methods: `success`, `info`, `warning` and `error`. - parameter message: The text message to be shown. */ func show(_ message: String) { removeExistingBars() setupHideTimer() let bar = DodoToolbar(witStyle: style) setupHideOnTap(bar) bar.layoutGuide = style.bar.locationTop ? topLayoutGuide : bottomLayoutGuide bar.buttonViewDelegate = self bar.show(inSuperview: superview, withMessage: message) } /// Hide the message bar if it's currently shown. func hide() { hideTimer?.cancel() toolbar?.hide({}) } func listenForKeyboard() { } private var toolbar: DodoToolbar? { get { return superview.subviews.filter { $0 is DodoToolbar }.map { $0 as! DodoToolbar }.first } } private func removeExistingBars() { for view in superview.subviews { if let existingToolbar = view as? DodoToolbar { existingToolbar.removeFromSuperview() } } } // MARK: - Hiding after delay private func setupHideTimer() { hideTimer?.cancel() if style.bar.hideAfterDelaySeconds > 0 { hideTimer = MoaTimer.runAfter(style.bar.hideAfterDelaySeconds) { [weak self] timer in DispatchQueue.main.async { self?.hide() } } } } // MARK: - Reacting to tap private func setupHideOnTap(_ toolbar: UIView) { onTap = OnTap(view: toolbar, gesture: UITapGestureRecognizer()) { [weak self] in self?.didTapTheBar() } } /// The bar has been tapped private func didTapTheBar() { style.bar.onTap?() if style.bar.hideOnTap { hide() } } // MARK: - DodoButtonViewDelegate func buttonDelegateDidTap(_ buttonStyle: DodoButtonStyle) { if buttonStyle.hideOnTap { hide() } } } // ---------------------------- // // DodoBarOnTap.swift // // ---------------------------- /// A closure that is called when a bar is tapped public typealias DodoBarOnTap = ()->() // ---------------------------- // // DodoInterface.swift // // ---------------------------- import UIKit /** Coordinates the process of showing and hiding of the message bar. The instance is created automatically in the `dodo` property of any UIView instance. It is not expected to be instantiated manually anywhere except unit tests. For example: let view = UIView() view.dodo.info("Horses are blue?") */ public protocol DodoInterface: class { /// Specify optional layout guide for positioning the bar view. var topLayoutGuide: UILayoutSupport? { get set } /// Specify optional layout guide for positioning the bar view. var bottomLayoutGuide: UILayoutSupport? { get set } /// Defines styles for the bar. var style: DodoStyle { get set } /// Changes the style preset for the bar widget. var preset: DodoPresets { get set } /** Shows the message bar with *.success* preset. It can be used to indicate successful completion of an operation. - parameter message: The text message to be shown. */ func success(_ message: String) /** Shows the message bar with *.Info* preset. It can be used for showing information messages that have neutral emotional value. - parameter message: The text message to be shown. */ func info(_ message: String) /** Shows the message bar with *.warning* preset. It can be used for for showing warning messages. - parameter message: The text message to be shown. */ func warning(_ message: String) /** Shows the message bar with *.warning* preset. It can be used for showing critical error messages - parameter message: The text message to be shown. */ func error(_ message: String) /** Shows the message bar. Set `preset` property to change the appearance of the message bar, or use the shortcut methods: `success`, `info`, `warning` and `error`. - parameter message: The text message to be shown. */ func show(_ message: String) /// Hide the message bar if it's currently shown. func hide() } // ---------------------------- // // DodoKeyboardListener.swift // // ---------------------------- /** Start listening for keyboard events. Used for moving the message bar from under the keyboard when the bar is shown at the bottom of the screen. */ struct DodoKeyboardListener { static let underKeyboardLayoutConstraint = UnderKeyboardLayoutConstraint() static func startListening() { // Just access the static property to make it initialize itself lazily if it hasn't been already. underKeyboardLayoutConstraint.isAccessibilityElement = false } } // ---------------------------- // // DodoToolbar.swift // // ---------------------------- import UIKit class DodoToolbar: UIView { var layoutGuide: UILayoutSupport? var style: DodoStyle weak var buttonViewDelegate: DodoButtonViewDelegate? private var didCallHide = false convenience init(witStyle style: DodoStyle) { self.init(frame: CGRect()) self.style = style } override init(frame: CGRect) { style = DodoStyle() super.init(frame: frame) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func show(inSuperview parentView: UIView, withMessage message: String) { if superview != nil { return } // already being shown parentView.addSubview(self) applyStyle() layoutBarInSuperview() let buttons = createButtons() createLabel(message, withButtons: buttons) style.bar.animationShow(self, style.bar.animationShowDuration, style.bar.locationTop, {}) } func hide(_ onAnimationCompleted: @escaping ()->()) { // Respond only to the first hide() call if didCallHide { return } didCallHide = true style.bar.animationHide(self, style.bar.animationHideDuration, style.bar.locationTop, { [weak self] in self?.removeFromSuperview() onAnimationCompleted() }) } // MARK: - Label private func createLabel(_ message: String, withButtons buttons: [UIView]) { let label = UILabel() label.font = style.label.font label.text = message label.textColor = style.label.color label.textAlignment = NSTextAlignment.center label.numberOfLines = style.label.numberOfLines if style.bar.debugMode { label.backgroundColor = UIColor.red } if let shadowColor = style.label.shadowColor { label.shadowColor = shadowColor label.shadowOffset = style.label.shadowOffset } addSubview(label) layoutLabel(label, withButtons: buttons) } private func layoutLabel(_ label: UILabel, withButtons buttons: [UIView]) { label.translatesAutoresizingMaskIntoConstraints = false // Stretch the label vertically TegAutolayoutConstraints.fillParent(label, parentView: self, margin: style.label.horizontalMargin, vertically: true) if buttons.count == 0 { if let superview = superview { // If there are no buttons - stretch the label to the entire width of the view TegAutolayoutConstraints.fillParent(label, parentView: superview, margin: style.label.horizontalMargin, vertically: false) } } else { layoutLabelWithButtons(label, withButtons: buttons) } } private func layoutLabelWithButtons(_ label: UILabel, withButtons buttons: [UIView]) { if buttons.count != 2 { return } let views = [buttons[0], label, buttons[1]] if let superview = superview { TegAutolayoutConstraints.viewsNextToEachOther(views, constraintContainer: superview, margin: style.label.horizontalMargin, vertically: false) } } // MARK: - Buttons private func createButtons() -> [DodoButtonView] { precondition(buttonViewDelegate != nil, "Button view delegate can not be nil") let buttonStyles = [style.leftButton, style.rightButton] let buttonViews = DodoButtonView.createMany(buttonStyles) for (index, button) in buttonViews.enumerated() { addSubview(button) button.delegate = buttonViewDelegate button.doLayout(onLeftSide: index == 0) if style.bar.debugMode { button.backgroundColor = UIColor.yellow } } return buttonViews } // MARK: - Style the bar private func applyStyle() { backgroundColor = style.bar.backgroundColor layer.cornerRadius = style.bar.cornerRadius layer.masksToBounds = true if let borderColor = style.bar.borderColor , style.bar.borderWidth > 0 { layer.borderColor = borderColor.cgColor layer.borderWidth = style.bar.borderWidth } } private func layoutBarInSuperview() { translatesAutoresizingMaskIntoConstraints = false if let superview = superview { // Stretch the toobar horizontally to the width if its superview TegAutolayoutConstraints.fillParent(self, parentView: superview, margin: style.bar.marginToSuperview.width, vertically: false) let vMargin = style.bar.marginToSuperview.height let verticalMargin = style.bar.locationTop ? -vMargin : vMargin var verticalConstraints = [NSLayoutConstraint]() if let layoutGuide = layoutGuide { // Align the top/bottom edge of the toolbar with the top/bottom layout guide // (a tab bar, for example) verticalConstraints = TegAutolayoutConstraints.alignVerticallyToLayoutGuide(self, onTop: style.bar.locationTop, layoutGuide: layoutGuide, constraintContainer: superview, margin: verticalMargin) } else { // Align the top/bottom of the toolbar with the top/bottom of its superview verticalConstraints = TegAutolayoutConstraints.alignSameAttributes(superview, toItem: self, constraintContainer: superview, attribute: style.bar.locationTop ? NSLayoutAttribute.top : NSLayoutAttribute.bottom, margin: verticalMargin) } setupKeyboardEvader(verticalConstraints) } } // Moves the message bar from under the keyboard private func setupKeyboardEvader(_ verticalConstraints: [NSLayoutConstraint]) { if let bottomConstraint = verticalConstraints.first, let superview = superview , !style.bar.locationTop { DodoKeyboardListener.underKeyboardLayoutConstraint.setup(bottomConstraint, view: superview, bottomLayoutGuide: layoutGuide) } } } // ---------------------------- // // DodoTouchTarget.swift // // ---------------------------- import UIKit /** Helper function to make sure bounds are big enought to be used as touch target. The function is used in pointInside(point: CGPoint, withEvent event: UIEvent?) of UIImageView. */ struct DodoTouchTarget { static func optimize(_ bounds: CGRect) -> CGRect { let recommendedHitSize: CGFloat = 44 var hitWidthIncrease:CGFloat = recommendedHitSize - bounds.width var hitHeightIncrease:CGFloat = recommendedHitSize - bounds.height if hitWidthIncrease < 0 { hitWidthIncrease = 0 } if hitHeightIncrease < 0 { hitHeightIncrease = 0 } let extendedBounds: CGRect = bounds.insetBy(dx: -hitWidthIncrease / 2, dy: -hitHeightIncrease / 2) return extendedBounds } } // ---------------------------- // // DodoIcons.swift // // ---------------------------- /** Collection of icons included with Dodo library. */ public enum DodoIcons: String { /// Icon for closing the bar. case close = "Close" /// Icon for reloading. case reload = "Reload" } // ---------------------------- // // DodoMock.swift // // ---------------------------- import UIKit /** This class is for testing the code that uses Dodo. It helps verifying the messages that were shown in the message bar without actually showing them. Here is how to use it in your unit test. 1. Create an instance of DodoMock. 2. Set it to the `view.dodo` property of the view. 3. Run the code that you are testing. 4. Finally, verify which messages were shown in the message bar. Example: // Supply mock to the view let dodoMock = DodoMock() view.dodo = dodoMock // Run the code from the app runSomeAppCode() // Verify the message is visible XCTAssert(dodoMock.results.visible) // Check total number of messages shown XCTAssertEqual(1, dodoMock.results.total) // Verify the text of the success message XCTAssertEqual("To be prepared is half the victory.", dodoMock.results.success[0]) */ public class DodoMock: DodoInterface { /// This property is used in unit tests to verify which messages were displayed in the message bar. public var results = DodoMockResults() /// Specify optional layout guide for positioning the bar view. public var topLayoutGuide: UILayoutSupport? /// Specify optional layout guide for positioning the bar view. public var bottomLayoutGuide: UILayoutSupport? /// Defines styles for the bar. public var style = DodoStyle(parentStyle: DodoPresets.defaultPreset.style) /// Creates an instance of DodoMock class public init() { } /// Changes the style preset for the bar widget. public var preset: DodoPresets = DodoPresets.defaultPreset { didSet { if preset != oldValue { style.parent = preset.style } } } /** Shows the message bar with *.success* preset. It can be used to indicate successful completion of an operation. - parameter message: The text message to be shown. */ public func success(_ message: String) { preset = .success show(message) } /** Shows the message bar with *.Info* preset. It can be used for showing information messages that have neutral emotional value. - parameter message: The text message to be shown. */ public func info(_ message: String) { preset = .info show(message) } /** Shows the message bar with *.warning* preset. It can be used for for showing warning messages. - parameter message: The text message to be shown. */ public func warning(_ message: String) { preset = .warning show(message) } /** Shows the message bar with *.warning* preset. It can be used for showing critical error messages - parameter message: The text message to be shown. */ public func error(_ message: String) { preset = .error show(message) } /** Shows the message bar. Set `preset` property to change the appearance of the message bar, or use the shortcut methods: `success`, `info`, `warning` and `error`. - parameter message: The text message to be shown. */ public func show(_ message: String) { let mockMessage = DodoMockMessage(preset: preset, message: message) results.messages.append(mockMessage) results.visible = true } /// Hide the message bar if it's currently shown. public func hide() { results.visible = false } } // ---------------------------- // // DodoMockMessage.swift // // ---------------------------- /** Contains information about the message that was displayed in message bar. Used in unit tests. */ struct DodoMockMessage { let preset: DodoPresets let message: String } // ---------------------------- // // DodoMockResults.swift // // ---------------------------- /** Used in unit tests to verify the messages that were shown in the message bar. */ public struct DodoMockResults { /// An array of success messages displayed in the message bar. public var success: [String] { return messages.filter({ $0.preset == DodoPresets.success }).map({ $0.message }) } /// An array of information messages displayed in the message bar. public var info: [String] { return messages.filter({ $0.preset == DodoPresets.info }).map({ $0.message }) } /// An array of warning messages displayed in the message bar. public var warning: [String] { return messages.filter({ $0.preset == DodoPresets.warning }).map({ $0.message }) } /// An array of error messages displayed in the message bar. public var errors: [String] { return messages.filter({ $0.preset == DodoPresets.error }).map({ $0.message }) } /// Total number of messages shown. public var total: Int { return messages.count } /// Indicates whether the message is visible public var visible = false var messages = [DodoMockMessage]() } // ---------------------------- // // DodoBarDefaultStyles.swift // // ---------------------------- import UIKit /** Default styles for the bar view. Default styles are used when individual element styles are not set. */ public struct DodoBarDefaultStyles { /// Revert the property values to their defaults public static func resetToDefaults() { animationHide = _animationHide animationHideDuration = _animationHideDuration animationShow = _animationShow animationShowDuration = _animationShowDuration backgroundColor = _backgroundColor borderColor = _borderColor borderWidth = _borderWidth cornerRadius = _cornerRadius debugMode = _debugMode hideAfterDelaySeconds = _hideAfterDelaySeconds hideOnTap = _hideOnTap locationTop = _locationTop marginToSuperview = _marginToSuperview onTap = _onTap } // --------------------------- private static let _animationHide: DodoAnimation = DodoAnimationsHide.rotate /// Specify a function for animating the bar when it is hidden. public static var animationHide: DodoAnimation = _animationHide // --------------------------- private static let _animationHideDuration: TimeInterval? = nil /// Duration of hide animation. When nil it uses default duration for selected animation function. public static var animationHideDuration: TimeInterval? = _animationHideDuration // --------------------------- private static let _animationShow: DodoAnimation = DodoAnimationsShow.rotate /// Specify a function for animating the bar when it is shown. public static var animationShow: DodoAnimation = _animationShow // --------------------------- private static let _animationShowDuration: TimeInterval? = nil /// Duration of show animation. When nil it uses default duration for selected animation function. public static var animationShowDuration: TimeInterval? = _animationShowDuration // --------------------------- private static let _backgroundColor: UIColor? = nil /// Background color of the bar. public static var backgroundColor = _backgroundColor // --------------------------- private static let _borderColor: UIColor? = nil /// Color of the bar's border. public static var borderColor = _borderColor // --------------------------- private static let _borderWidth: CGFloat = 1 / UIScreen.main.scale /// Border width of the bar. public static var borderWidth = _borderWidth // --------------------------- private static let _cornerRadius: CGFloat = 20 /// Corner radius of the bar view. public static var cornerRadius = _cornerRadius // --------------------------- private static let _debugMode = false /// When true it highlights the view background for spotting layout issues. public static var debugMode = _debugMode // --------------------------- private static let _hideAfterDelaySeconds: TimeInterval = 0 /** Hides the bar automatically after the specified number of seconds. The bar is kept on screen indefinitely if the value is zero. */ public static var hideAfterDelaySeconds = _hideAfterDelaySeconds // --------------------------- private static let _hideOnTap = false /// When true the bar is hidden when user taps on it. public static var hideOnTap = _hideOnTap // --------------------------- private static let _locationTop = true /// Position of the bar. When true the bar is shown on top of the screen. public static var locationTop = _locationTop // --------------------------- private static let _marginToSuperview = CGSize(width: 5, height: 5) /// Margin between the bar edge and its superview. public static var marginToSuperview = _marginToSuperview // --------------------------- private static let _onTap: DodoBarOnTap? = nil /// Supply a function that will be called when user taps the bar. public static var onTap = _onTap // --------------------------- } // ---------------------------- // // DodoBarStyle.swift // // ---------------------------- import UIKit /// Defines styles related to the bar view in general. public class DodoBarStyle { /// The parent style is used to get the property value if the object is missing one. var parent: DodoBarStyle? init(parentStyle: DodoBarStyle? = nil) { self.parent = parentStyle } /// Clears the styles for all properties for this style object. The styles will be taken from parent and default properties. public func clear() { _animationHide = nil _animationHideDuration = nil _animationShow = nil _animationShowDuration = nil _backgroundColor = nil _borderColor = nil _borderWidth = nil _cornerRadius = nil _debugMode = nil _hideAfterDelaySeconds = nil _hideOnTap = nil _locationTop = nil _marginToSuperview = nil _onTap = nil } // ----------------------------- private var _animationHide: DodoAnimation? /// Specify a function for animating the bar when it is hidden. public var animationHide: DodoAnimation { get { return (_animationHide ?? parent?.animationHide) ?? DodoBarDefaultStyles.animationHide } set { _animationHide = newValue } } // --------------------------- private var _animationHideDuration: TimeInterval? /// Duration of hide animation. When nil it uses default duration for selected animation function. public var animationHideDuration: TimeInterval? { get { return (_animationHideDuration ?? parent?.animationHideDuration) ?? DodoBarDefaultStyles.animationHideDuration } set { _animationHideDuration = newValue } } // --------------------------- private var _animationShow: DodoAnimation? /// Specify a function for animating the bar when it is shown. public var animationShow: DodoAnimation { get { return (_animationShow ?? parent?.animationShow) ?? DodoBarDefaultStyles.animationShow } set { _animationShow = newValue } } // --------------------------- private var _animationShowDuration: TimeInterval? /// Duration of show animation. When nil it uses default duration for selected animation function. public var animationShowDuration: TimeInterval? { get { return (_animationShowDuration ?? parent?.animationShowDuration) ?? DodoBarDefaultStyles.animationShowDuration } set { _animationShowDuration = newValue } } // --------------------------- private var _backgroundColor: UIColor? /// Background color of the bar. public var backgroundColor: UIColor? { get { return _backgroundColor ?? parent?.backgroundColor ?? DodoBarDefaultStyles.backgroundColor } set { _backgroundColor = newValue } } // ----------------------------- private var _borderColor: UIColor? /// Color of the bar's border. public var borderColor: UIColor? { get { return _borderColor ?? parent?.borderColor ?? DodoBarDefaultStyles.borderColor } set { _borderColor = newValue } } // ----------------------------- private var _borderWidth: CGFloat? /// Border width of the bar. public var borderWidth: CGFloat { get { return _borderWidth ?? parent?.borderWidth ?? DodoBarDefaultStyles.borderWidth } set { _borderWidth = newValue } } // ----------------------------- private var _cornerRadius: CGFloat? /// Corner radius of the bar view. public var cornerRadius: CGFloat { get { return _cornerRadius ?? parent?.cornerRadius ?? DodoBarDefaultStyles.cornerRadius } set { _cornerRadius = newValue } } // ----------------------------- private var _debugMode: Bool? /// When true it highlights the view background for spotting layout issues. public var debugMode: Bool { get { return _debugMode ?? parent?.debugMode ?? DodoBarDefaultStyles.debugMode } set { _debugMode = newValue } } // --------------------------- private var _hideAfterDelaySeconds: TimeInterval? /** Hides the bar automatically after the specified number of seconds. If nil the bar is kept on screen. */ public var hideAfterDelaySeconds: TimeInterval { get { return _hideAfterDelaySeconds ?? parent?.hideAfterDelaySeconds ?? DodoBarDefaultStyles.hideAfterDelaySeconds } set { _hideAfterDelaySeconds = newValue } } // ----------------------------- private var _hideOnTap: Bool? /// When true the bar is hidden when user taps on it. public var hideOnTap: Bool { get { return _hideOnTap ?? parent?.hideOnTap ?? DodoBarDefaultStyles.hideOnTap } set { _hideOnTap = newValue } } // ----------------------------- private var _locationTop: Bool? /// Position of the bar. When true the bar is shown on top of the screen. public var locationTop: Bool { get { return _locationTop ?? parent?.locationTop ?? DodoBarDefaultStyles.locationTop } set { _locationTop = newValue } } // ----------------------------- private var _marginToSuperview: CGSize? /// Margin between the bar edge and its superview. public var marginToSuperview: CGSize { get { return _marginToSuperview ?? parent?.marginToSuperview ?? DodoBarDefaultStyles.marginToSuperview } set { _marginToSuperview = newValue } } // --------------------------- private var _onTap: DodoBarOnTap? /// Supply a function that will be called when user taps the bar. public var onTap: DodoBarOnTap? { get { return _onTap ?? parent?.onTap ?? DodoBarDefaultStyles.onTap } set { _onTap = newValue } } // ----------------------------- } // ---------------------------- // // DodoButtonDefaultStyles.swift // // ---------------------------- import UIKit /** Default styles for the bar button. Default styles are used when individual element styles are not set. */ public struct DodoButtonDefaultStyles { /// Revert the property values to their defaults public static func resetToDefaults() { accessibilityLabel = _accessibilityLabel hideOnTap = _hideOnTap horizontalMarginToBar = _horizontalMarginToBar icon = _icon image = _image onTap = _onTap size = _size tintColor = _tintColor } // --------------------------- private static let _accessibilityLabel: String? = nil /** This text is spoken by the device when it is in accessibility mode. It is recommended to always set the accessibility label for your button. The text can be a short localized description of the button function, for example: "Close the message", "Reload" etc. */ public static var accessibilityLabel = _accessibilityLabel // --------------------------- private static let _hideOnTap = false /// When true it hides the bar when the button is tapped. public static var hideOnTap = _hideOnTap // --------------------------- private static let _horizontalMarginToBar: CGFloat = 10 /// Margin between the bar edge and the button public static var horizontalMarginToBar = _horizontalMarginToBar // --------------------------- private static let _icon: DodoIcons? = nil /// When set it shows one of the default Dodo icons. Use `image` property to supply a custom image. The color of the image can be changed with `tintColor` property. public static var icon = _icon // --------------------------- private static let _image: UIImage? = nil /// Custom image for the button. One can also use the `icon` property to show one of the default Dodo icons. The color of the image can be changed with `tintColor` property. public static var image = _image // --------------------------- private static let _onTap: DodoButtonOnTap? = nil /// Supply a function that will be called when user taps the button. public static var onTap = _onTap // --------------------------- private static let _size = CGSize(width: 25, height: 25) /// Size of the button. public static var size = _size // --------------------------- private static let _tintColor: UIColor? = nil /// Replaces the color of the image or icon. The original colors are used when nil. public static var tintColor = _tintColor // --------------------------- } // ---------------------------- // // DodoButtonStyle.swift // // ---------------------------- import UIKit /// Defines styles for the bar button. public class DodoButtonStyle { /// The parent style is used to get the property value if the object is missing one. var parent: DodoButtonStyle? init(parentStyle: DodoButtonStyle? = nil) { self.parent = parentStyle } /// Clears the styles for all properties for this style object. The styles will be taken from parent and default properties. public func clear() { _accessibilityLabel = nil _hideOnTap = nil _horizontalMarginToBar = nil _icon = nil _image = nil _onTap = nil _size = nil _tintColor = nil } // ----------------------------- private var _accessibilityLabel: String? /** This text is spoken by the device when it is in accessibility mode. It is recommended to always set the accessibility label for your button. The text can be a short localized description of the button function, for example: "Close the message", "Reload" etc. */ public var accessibilityLabel: String? { get { return _accessibilityLabel ?? parent?.accessibilityLabel ?? DodoButtonDefaultStyles.accessibilityLabel } set { _accessibilityLabel = newValue } } // ----------------------------- private var _hideOnTap: Bool? /// When true it hides the bar when the button is tapped. public var hideOnTap: Bool { get { return _hideOnTap ?? parent?.hideOnTap ?? DodoButtonDefaultStyles.hideOnTap } set { _hideOnTap = newValue } } // ----------------------------- private var _horizontalMarginToBar: CGFloat? /// Horizontal margin between the bar edge and the button. public var horizontalMarginToBar: CGFloat { get { return _horizontalMarginToBar ?? parent?.horizontalMarginToBar ?? DodoButtonDefaultStyles.horizontalMarginToBar } set { _horizontalMarginToBar = newValue } } // ----------------------------- private var _icon: DodoIcons? /// When set it shows one of the default Dodo icons. Use `image` property to supply a custom image. The color of the image can be changed with `tintColor` property. public var icon: DodoIcons? { get { return _icon ?? parent?.icon ?? DodoButtonDefaultStyles.icon } set { _icon = newValue } } // ----------------------------- private var _image: UIImage? /// Custom image for the button. One can also use the `icon` property to show one of the default Dodo icons. The color of the image can be changed with `tintColor` property. public var image: UIImage? { get { return _image ?? parent?.image ?? DodoButtonDefaultStyles.image } set { _image = newValue } } // --------------------------- private var _onTap: DodoButtonOnTap? /// Supply a function that will be called when user taps the button. public var onTap: DodoButtonOnTap? { get { return _onTap ?? parent?.onTap ?? DodoButtonDefaultStyles.onTap } set { _onTap = newValue } } // ----------------------------- private var _size: CGSize? /// Size of the button. public var size: CGSize { get { return _size ?? parent?.size ?? DodoButtonDefaultStyles.size } set { _size = newValue } } // ----------------------------- private var _tintColor: UIColor? /// Replaces the color of the image or icon. The original colors are used when nil. public var tintColor: UIColor? { get { return _tintColor ?? parent?.tintColor ?? DodoButtonDefaultStyles.tintColor } set { _tintColor = newValue } } // ----------------------------- } // ---------------------------- // // DodoLabelDefaultStyles.swift // // ---------------------------- import UIKit /** Default styles for the text label. Default styles are used when individual element styles are not set. */ public struct DodoLabelDefaultStyles { /// Revert the property values to their defaults public static func resetToDefaults() { color = _color font = _font horizontalMargin = _horizontalMargin numberOfLines = _numberOfLines shadowColor = _shadowColor shadowOffset = _shadowOffset } // --------------------------- private static let _color = UIColor.white /// Color of the label text. public static var color = _color // --------------------------- private static let _font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.headline) /// Font of the label text. public static var font = _font // --------------------------- private static let _horizontalMargin: CGFloat = 10 /// Margin between the bar/button edge and the label. public static var horizontalMargin = _horizontalMargin // --------------------------- private static let _numberOfLines: Int = 3 /// The maximum number of lines in the label. public static var numberOfLines = _numberOfLines // --------------------------- private static let _shadowColor: UIColor? = nil /// Color of text shadow. public static var shadowColor = _shadowColor // --------------------------- private static let _shadowOffset = CGSize(width: 0, height: 1) /// Text shadow offset. public static var shadowOffset = _shadowOffset // --------------------------- } // ---------------------------- // // DodoLabelStyle.swift // // ---------------------------- import UIKit /// Defines styles related to the text label. public class DodoLabelStyle { /// The parent style is used to get the property value if the object is missing one. var parent: DodoLabelStyle? init(parentStyle: DodoLabelStyle? = nil) { self.parent = parentStyle } /// Clears the styles for all properties for this style object. The styles will be taken from parent and default properties. public func clear() { _color = nil _font = nil _horizontalMargin = nil _numberOfLines = nil _shadowColor = nil _shadowOffset = nil } // ----------------------------- private var _color: UIColor? /// Color of the label text. public var color: UIColor { get { return _color ?? parent?.color ?? DodoLabelDefaultStyles.color } set { _color = newValue } } // ----------------------------- private var _font: UIFont? /// Color of the label text. public var font: UIFont { get { return _font ?? parent?.font ?? DodoLabelDefaultStyles.font } set { _font = newValue } } // ----------------------------- private var _horizontalMargin: CGFloat? /// Margin between the bar/button edge and the label. public var horizontalMargin: CGFloat { get { return _horizontalMargin ?? parent?.horizontalMargin ?? DodoLabelDefaultStyles.horizontalMargin } set { _horizontalMargin = newValue } } // ----------------------------- private var _numberOfLines: Int? /// The maximum number of lines in the label. public var numberOfLines: Int { get { return _numberOfLines ?? parent?.numberOfLines ?? DodoLabelDefaultStyles.numberOfLines } set { _numberOfLines = newValue } } // ----------------------------- private var _shadowColor: UIColor? /// Color of text shadow. public var shadowColor: UIColor? { get { return _shadowColor ?? parent?.shadowColor ?? DodoLabelDefaultStyles.shadowColor } set { _shadowColor = newValue } } // ----------------------------- private var _shadowOffset: CGSize? /// Text shadow offset. public var shadowOffset: CGSize { get { return _shadowOffset ?? parent?.shadowOffset ?? DodoLabelDefaultStyles.shadowOffset } set { _shadowOffset = newValue } } // ----------------------------- } // ---------------------------- // // DodoPresets.swift // // ---------------------------- /** Defines the style presets for the bar. */ public enum DodoPresets { /// A styling preset used for indicating successful completion of an operation. Usually styled with green color. case success /// A styling preset for showing information messages, neutral in color. case info /// A styling preset for showing warning messages. Can be styled with yellow/orange colors. case warning /// A styling preset for showing critical error messages. Usually styled with red color. case error /// The preset is used by default for the bar if it's not set by the user. static let defaultPreset = DodoPresets.success /// The preset cache. private static var styles = [DodoPresets: DodoStyle]() /// Returns the style for the preset public var style: DodoStyle { var style = DodoPresets.styles[self] if style == nil { style = DodoPresets.makeStyle(forPreset: self) DodoPresets.styles[self] = style } precondition(style != nil, "Failed to create style") return style ?? DodoStyle() } /// Reset alls preset styles to their initial states. public static func resetAll() { styles = [:] } /// Reset the preset style to its initial state. public func reset() { DodoPresets.styles.removeValue(forKey: self) } private static func makeStyle(forPreset preset: DodoPresets) -> DodoStyle{ let style = DodoStyle() switch preset { case .success: style.bar.backgroundColor = DodoColor.fromHexString("#00CC03C9") case .info: style.bar.backgroundColor = DodoColor.fromHexString("#0057FF96") case .warning: style.bar.backgroundColor = DodoColor.fromHexString("#CEC411DD") case .error: style.bar.backgroundColor = DodoColor.fromHexString("#FF0B0BCC") } return style } } // ---------------------------- // // DodoStyle.swift // // ---------------------------- import UIKit /// Combines various styles for the toolbar element. public class DodoStyle { /// The parent style is used to get the property value if the object is missing one. var parent: DodoStyle? { didSet { changeParent() } } init(parentStyle: DodoStyle? = nil) { self.parent = parentStyle } private func changeParent() { bar.parent = parent?.bar label.parent = parent?.label leftButton.parent = parent?.leftButton rightButton.parent = parent?.rightButton } /** Reverts all the default styles to their initial values. Usually used in setUp() function in the unit tests. */ public static func resetDefaultStyles() { DodoBarDefaultStyles.resetToDefaults() DodoLabelDefaultStyles.resetToDefaults() DodoButtonDefaultStyles.resetToDefaults() } /// Clears the styles for all properties for this style object. The styles will be taken from parent and default properties. public func clear() { bar.clear() label.clear() leftButton.clear() rightButton.clear() } /** Styles for the bar view. */ public lazy var bar: DodoBarStyle = self.initBarStyle() private func initBarStyle() -> DodoBarStyle { return DodoBarStyle(parentStyle: parent?.bar) } /** Styles for the text label. */ public lazy var label: DodoLabelStyle = self.initLabelStyle() private func initLabelStyle() -> DodoLabelStyle { return DodoLabelStyle(parentStyle: parent?.label) } /** Styles for the left button. */ public lazy var leftButton: DodoButtonStyle = self.initLeftButtonStyle() private func initLeftButtonStyle() -> DodoButtonStyle { return DodoButtonStyle(parentStyle: parent?.leftButton) } /** Styles for the right button. */ public lazy var rightButton: DodoButtonStyle = self.initRightButtonStyle() private func initRightButtonStyle() -> DodoButtonStyle { return DodoButtonStyle(parentStyle: parent?.rightButton) } } // ---------------------------- // // UIView+SwiftAlertBar.swift // // ---------------------------- import UIKit private var sabAssociationKey: UInt8 = 0 /** UIView extension for showing a notification widget. let view = UIView() view.dodo.show("Hello World!") */ public extension UIView { /** Message bar extension. Call `dodo.show`, `dodo.success`, dodo.error` functions to show a notification widget in the view. let view = UIView() view.dodo.show("Hello World!") */ public var dodo: DodoInterface { get { if let value = objc_getAssociatedObject(self, &sabAssociationKey) as? DodoInterface { return value } else { let dodo = Dodo(superview: self) objc_setAssociatedObject(self, &sabAssociationKey, dodo, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) return dodo } } set { objc_setAssociatedObject(self, &sabAssociationKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) } } } // ---------------------------- // // DodoColor.swift // // ---------------------------- import UIKit /** Creates a UIColor object from a string. Examples: DodoColor.fromHexString('#340f9a') // With alpha channel DodoColor.fromHexString('#f1a2b3a6') */ public class DodoColor { /** Creates a UIColor object from a string. - parameter rgba: a RGB/RGBA string representation of color. It can include optional alpha value. Example: "#cca213" or "#cca21312" (with alpha value). - returns: UIColor object. */ public class func fromHexString(_ rgba: String) -> UIColor { var red: CGFloat = 0.0 var green: CGFloat = 0.0 var blue: CGFloat = 0.0 var alpha: CGFloat = 1.0 if !rgba.hasPrefix("#") { print("Warning: DodoColor.fromHexString, # character missing") return UIColor() } let index = rgba.characters.index(rgba.startIndex, offsetBy: 1) let hex = rgba.substring(from: index) let scanner = Scanner(string: hex) var hexValue: CUnsignedLongLong = 0 if !scanner.scanHexInt64(&hexValue) { print("Warning: DodoColor.fromHexString, error scanning hex value") return UIColor() } if hex.characters.count == 6 { red = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0 green = CGFloat((hexValue & 0x00FF00) >> 8) / 255.0 blue = CGFloat(hexValue & 0x0000FF) / 255.0 } else if hex.characters.count == 8 { red = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0 green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0 blue = CGFloat((hexValue & 0x0000FF00) >> 8) / 255.0 alpha = CGFloat(hexValue & 0x000000FF) / 255.0 } else { print("Warning: DodoColor.fromHexString, invalid rgb string, length should be 7 or 9") return UIColor() } return UIColor(red: red, green: green, blue: blue, alpha: alpha) } } // ---------------------------- // // MoaTimer.swift // // ---------------------------- import UIKit /** Creates a timer that executes code after delay. Usage var timer: MoaTimer.runAfter? ... func myFunc() { timer = MoaTimer.runAfter(0.010) { timer in ... code to run } } Canceling the timer Timer is Canceling automatically when it is deallocated. You can also cancel it manually: let timer = MoaTimer.runAfter(0.010) { timer in ... } timer.cancel() */ final class MoaTimer: NSObject { private let repeats: Bool private var timer: Timer? private var callback: ((MoaTimer)->())? private init(interval: TimeInterval, repeats: Bool = false, callback: @escaping (MoaTimer)->()) { self.repeats = repeats super.init() self.callback = callback timer = Timer.scheduledTimer(timeInterval: interval, target: self, selector: #selector(MoaTimer.timerFired(_:)), userInfo: nil, repeats: repeats) } /// Timer is cancelled automatically when it is deallocated. deinit { cancel() } /** Cancels the timer and prevents it from firing in the future. Note that timer is cancelled automatically whe it is deallocated. */ func cancel() { timer?.invalidate() timer = nil } /** Runs the closure after specified time interval. - parameter interval: Time interval in milliseconds. :repeats: repeats When true, the code is run repeatedly. - returns: callback A closure to be run by the timer. */ @discardableResult class func runAfter(_ interval: TimeInterval, repeats: Bool = false, callback: @escaping (MoaTimer)->()) -> MoaTimer { return MoaTimer(interval: interval, repeats: repeats, callback: callback) } func timerFired(_ timer: Timer) { self.callback?(self) if !repeats { cancel() } } } // ---------------------------- // // OnTap.swift // // ---------------------------- import UIKit /** Calling tap with closure. */ class OnTap: NSObject { var closure: ()->() init(view: UIView, gesture: UIGestureRecognizer, closure: @escaping ()->()) { self.closure = closure super.init() view.addGestureRecognizer(gesture) view.isUserInteractionEnabled = true gesture.addTarget(self, action: #selector(OnTap.didTap(_:))) } func didTap(_ gesture: UIGestureRecognizer) { closure() } } // ---------------------------- // // SpringAnimationCALayer.swift // // ---------------------------- import UIKit /** Animating CALayer with spring effect in iOS with Swift https://github.com/evgenyneu/SpringAnimationCALayer */ class SpringAnimationCALayer { // Animates layer with spring effect. class func animate(_ layer: CALayer, keypath: String, duration: CFTimeInterval, usingSpringWithDamping: Double, initialSpringVelocity: Double, fromValue: Double, toValue: Double, onFinished: (()->())?) { CATransaction.begin() CATransaction.setCompletionBlock(onFinished) let animation = create(keypath, duration: duration, usingSpringWithDamping: usingSpringWithDamping, initialSpringVelocity: initialSpringVelocity, fromValue: fromValue, toValue: toValue) layer.add(animation, forKey: keypath + " spring animation") CATransaction.commit() } // Creates CAKeyframeAnimation object class func create(_ keypath: String, duration: CFTimeInterval, usingSpringWithDamping: Double, initialSpringVelocity: Double, fromValue: Double, toValue: Double) -> CAKeyframeAnimation { let dampingMultiplier = Double(10) let velocityMultiplier = Double(10) let values = animationValues(fromValue, toValue: toValue, usingSpringWithDamping: dampingMultiplier * usingSpringWithDamping, initialSpringVelocity: velocityMultiplier * initialSpringVelocity) let animation = CAKeyframeAnimation(keyPath: keypath) animation.values = values animation.duration = duration return animation } class func animationValues(_ fromValue: Double, toValue: Double, usingSpringWithDamping: Double, initialSpringVelocity: Double) -> [Double]{ let numOfPoints = 1000 var values = [Double](repeating: 0.0, count: numOfPoints) let distanceBetweenValues = toValue - fromValue for point in (0..<numOfPoints) { let x = Double(point) / Double(numOfPoints) let valueNormalized = animationValuesNormalized(x, usingSpringWithDamping: usingSpringWithDamping, initialSpringVelocity: initialSpringVelocity) let value = toValue - distanceBetweenValues * valueNormalized values[point] = value } return values } private class func animationValuesNormalized(_ x: Double, usingSpringWithDamping: Double, initialSpringVelocity: Double) -> Double { return pow(M_E, -usingSpringWithDamping * x) * cos(initialSpringVelocity * x) } } // ---------------------------- // // TegAutolayoutConstraints.swift // // ---------------------------- // // TegAlign.swift // // Collection of shortcuts to create autolayout constraints. // import UIKit class TegAutolayoutConstraints { class func centerX(_ viewOne: UIView, viewTwo: UIView, constraintContainer: UIView) -> [NSLayoutConstraint] { return center(viewOne, viewTwo: viewTwo, constraintContainer: constraintContainer, vertically: false) } @discardableResult class func centerY(_ viewOne: UIView, viewTwo: UIView, constraintContainer: UIView) -> [NSLayoutConstraint] { return center(viewOne, viewTwo: viewTwo, constraintContainer: constraintContainer, vertically: true) } private class func center(_ viewOne: UIView, viewTwo: UIView, constraintContainer: UIView, vertically: Bool = false) -> [NSLayoutConstraint] { let attribute = vertically ? NSLayoutAttribute.centerY : NSLayoutAttribute.centerX let constraint = NSLayoutConstraint( item: viewOne, attribute: attribute, relatedBy: NSLayoutRelation.equal, toItem: viewTwo, attribute: attribute, multiplier: 1, constant: 0) constraintContainer.addConstraint(constraint) return [constraint] } @discardableResult class func alignSameAttributes(_ item: AnyObject, toItem: AnyObject, constraintContainer: UIView, attribute: NSLayoutAttribute, margin: CGFloat = 0) -> [NSLayoutConstraint] { let constraint = NSLayoutConstraint( item: item, attribute: attribute, relatedBy: NSLayoutRelation.equal, toItem: toItem, attribute: attribute, multiplier: 1, constant: margin) constraintContainer.addConstraint(constraint) return [constraint] } class func alignVerticallyToLayoutGuide(_ item: AnyObject, onTop: Bool, layoutGuide: UILayoutSupport, constraintContainer: UIView, margin: CGFloat = 0) -> [NSLayoutConstraint] { let constraint = NSLayoutConstraint( item: layoutGuide, attribute: onTop ? NSLayoutAttribute.bottom : NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: item, attribute: onTop ? NSLayoutAttribute.top : NSLayoutAttribute.bottom, multiplier: 1, constant: margin) constraintContainer.addConstraint(constraint) return [constraint] } class func aspectRatio(_ view: UIView, ratio: CGFloat) { let constraint = NSLayoutConstraint( item: view, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.height, multiplier: ratio, constant: 0) view.addConstraint(constraint) } class func fillParent(_ view: UIView, parentView: UIView, margin: CGFloat = 0, vertically: Bool = false) { var marginFormat = "" if margin != 0 { marginFormat = "-\(margin)-" } var format = "|\(marginFormat)[view]\(marginFormat)|" if vertically { format = "V:" + format } let constraints = NSLayoutConstraint.constraints(withVisualFormat: format, options: [], metrics: nil, views: ["view": view]) parentView.addConstraints(constraints) } @discardableResult class func viewsNextToEachOther(_ views: [UIView], constraintContainer: UIView, margin: CGFloat = 0, vertically: Bool = false) -> [NSLayoutConstraint] { if views.count < 2 { return [] } var constraints = [NSLayoutConstraint]() for (index, view) in views.enumerated() { if index >= views.count - 1 { break } let viewTwo = views[index + 1] constraints += twoViewsNextToEachOther(view, viewTwo: viewTwo, constraintContainer: constraintContainer, margin: margin, vertically: vertically) } return constraints } class func twoViewsNextToEachOther(_ viewOne: UIView, viewTwo: UIView, constraintContainer: UIView, margin: CGFloat = 0, vertically: Bool = false) -> [NSLayoutConstraint] { var marginFormat = "" if margin != 0 { marginFormat = "-\(margin)-" } var format = "[viewOne]\(marginFormat)[viewTwo]" if vertically { format = "V:" + format } let constraints = NSLayoutConstraint.constraints(withVisualFormat: format, options: [], metrics: nil, views: [ "viewOne": viewOne, "viewTwo": viewTwo ]) constraintContainer.addConstraints(constraints) return constraints } class func equalWidth(_ viewOne: UIView, viewTwo: UIView, constraintContainer: UIView) -> [NSLayoutConstraint] { let constraints = NSLayoutConstraint.constraints(withVisualFormat: "[viewOne(==viewTwo)]", options: [], metrics: nil, views: ["viewOne": viewOne, "viewTwo": viewTwo]) constraintContainer.addConstraints(constraints) return constraints } @discardableResult class func height(_ view: UIView, value: CGFloat) -> [NSLayoutConstraint] { return widthOrHeight(view, value: value, isWidth: false) } @discardableResult class func width(_ view: UIView, value: CGFloat) -> [NSLayoutConstraint] { return widthOrHeight(view, value: value, isWidth: true) } private class func widthOrHeight(_ view: UIView, value: CGFloat, isWidth: Bool) -> [NSLayoutConstraint] { let attribute = isWidth ? NSLayoutAttribute.width : NSLayoutAttribute.height let constraint = NSLayoutConstraint( item: view, attribute: attribute, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: value) view.addConstraint(constraint) return [constraint] } } // ---------------------------- // // UnderKeyboardDistrib.swift // // ---------------------------- // // An iOS libary for moving content from under the keyboard. // // https://github.com/marketplacer/UnderKeyboard // // This file was automatically generated by combining multiple Swift source files. // // ---------------------------- // // UnderKeyboardLayoutConstraint.swift // // ---------------------------- import UIKit /** Adjusts the length (constant value) of the bottom layout constraint when keyboard shows and hides. */ @objc public class UnderKeyboardLayoutConstraint: NSObject { private weak var bottomLayoutConstraint: NSLayoutConstraint? private weak var bottomLayoutGuide: UILayoutSupport? private var keyboardObserver = UnderKeyboardObserver() private var initialConstraintConstant: CGFloat = 0 private var minMargin: CGFloat = 10 private var viewToAnimate: UIView? /// Creates an instance of the class public override init() { super.init() keyboardObserver.willAnimateKeyboard = keyboardWillAnimate keyboardObserver.animateKeyboard = animateKeyboard keyboardObserver.start() } deinit { stop() } /// Stop listening for keyboard notifications. public func stop() { keyboardObserver.stop() } /** Supply a bottom Auto Layout constraint. Its constant value will be adjusted by the height of the keyboard when it appears and hides. - parameter bottomLayoutConstraint: Supply a bottom layout constraint. Its constant value will be adjusted when keyboard is shown and hidden. - parameter view: Supply a view that will be used to animate the constraint. It is usually the superview containing the view with the constraint. - parameter minMargin: Specify the minimum margin between the keyboard and the bottom of the view the constraint is attached to. Default: 10. - parameter bottomLayoutGuide: Supply an optional bottom layout guide (like a tab bar) that will be taken into account during height calculations. */ public func setup(_ bottomLayoutConstraint: NSLayoutConstraint, view: UIView, minMargin: CGFloat = 10, bottomLayoutGuide: UILayoutSupport? = nil) { initialConstraintConstant = bottomLayoutConstraint.constant self.bottomLayoutConstraint = bottomLayoutConstraint self.minMargin = minMargin self.bottomLayoutGuide = bottomLayoutGuide self.viewToAnimate = view // Keyboard is already open when setup is called if let currentKeyboardHeight = keyboardObserver.currentKeyboardHeight , currentKeyboardHeight > 0 { keyboardWillAnimate(currentKeyboardHeight) } } func keyboardWillAnimate(_ height: CGFloat) { guard let bottomLayoutConstraint = bottomLayoutConstraint else { return } let layoutGuideHeight = bottomLayoutGuide?.length ?? 0 let correctedHeight = height - layoutGuideHeight if height > 0 { let newConstantValue = correctedHeight + minMargin if newConstantValue > initialConstraintConstant { // Keyboard height is bigger than the initial constraint length. // Increase constraint length. bottomLayoutConstraint.constant = newConstantValue } else { // Keyboard height is NOT bigger than the initial constraint length. // Show the initial constraint length. bottomLayoutConstraint.constant = initialConstraintConstant } } else { bottomLayoutConstraint.constant = initialConstraintConstant } } func animateKeyboard(_ height: CGFloat) { viewToAnimate?.layoutIfNeeded() } } // ---------------------------- // // UnderKeyboardObserver.swift // // ---------------------------- import UIKit /** Detects appearance of software keyboard and calls the supplied closures that can be used for changing the layout and moving view from under the keyboard. */ public final class UnderKeyboardObserver: NSObject { public typealias AnimationCallback = (_ height: CGFloat) -> () let notificationCenter: NotificationCenter /// Function that will be called before the keyboard is shown and before animation is started. public var willAnimateKeyboard: AnimationCallback? /// Function that will be called inside the animation block. This can be used to call `layoutIfNeeded` on the view. public var animateKeyboard: AnimationCallback? /// Current height of the keyboard. Has value `nil` if unknown. public var currentKeyboardHeight: CGFloat? /// Creates an instance of the class public override init() { notificationCenter = NotificationCenter.default super.init() } deinit { stop() } /// Start listening for keyboard notifications. public func start() { stop() notificationCenter.addObserver(self, selector: #selector(UnderKeyboardObserver.keyboardNotification(_:)), name:NSNotification.Name.UIKeyboardWillShow, object: nil); notificationCenter.addObserver(self, selector: #selector(UnderKeyboardObserver.keyboardNotification(_:)), name:NSNotification.Name.UIKeyboardWillHide, object: nil); } /// Stop listening for keyboard notifications. public func stop() { notificationCenter.removeObserver(self) } // MARK: - Notification func keyboardNotification(_ notification: Notification) { let isShowing = notification.name == NSNotification.Name.UIKeyboardWillShow if let userInfo = (notification as NSNotification).userInfo, let height = (userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue.height, let duration: TimeInterval = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue, let animationCurveRawNSN = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber { let correctedHeight = isShowing ? height : 0 willAnimateKeyboard?(correctedHeight) UIView.animate(withDuration: duration, delay: TimeInterval(0), options: UIViewAnimationOptions(rawValue: animationCurveRawNSN.uintValue), animations: { [weak self] in self?.animateKeyboard?(correctedHeight) }, completion: nil ) currentKeyboardHeight = correctedHeight } } }
mit
c7cda69ca9bab5b4f542c5e0269465c7
24.876531
260
0.640858
5.133274
false
false
false
false
sdhzwm/WMMatchbox
WMMatchbox/WMMatchbox/Classes/Topic(话题)/Controller/WMTopController.swift
1
3713
// // WMTopController.swift // WMMatchbox // // Created by 王蒙 on 15/7/21. // Copyright © 2015年 wm. All rights reserved. // import UIKit extension UIImage{ class func imageWithOriRenderingImage(imageName:String) -> UIImage{ let image = UIImage(named: imageName) return (image?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal))! } } class WMTopController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() //设置leftBarButtonItem self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: (UIImage.imageWithOriRenderingImage("Social_GoToGift")), style: UIBarButtonItemStyle.Done, target: self, action: "leftBtnClick") //设置rightBarButtonItem self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: (UIImage.imageWithOriRenderingImage("creatTopic")), style: UIBarButtonItemStyle.Done, target: self, action: "rightBtnClick") } func leftBtnClick(){ print("这是左边") } func rightBtnClick(){ print("这是右边") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 0 } /* override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
apache-2.0
cfde1db8dd9216e00d2721613a99369d
32.472727
199
0.687127
5.351744
false
false
false
false
AlexeyGolovenkov/DevHelper
DevHelper/Ext/SwtExtensionCommand.swift
1
1163
// // SwiftExtensionCommand.swift // DevHelperContainer // // Created by Alex Golovenkov on 05/02/2019. // Copyright © 2019 Alexey Golovenkov. All rights reserved. // import Cocoa import XcodeKit class SwtExtensionCommand: NSObject, XCSourceEditorCommand { func perform(with invocation: XCSourceEditorCommandInvocation, completionHandler: @escaping (Error?) -> Void ) { guard invocation.buffer.selections.count > 0 else { completionHandler(nil) return } let selection = invocation.buffer.selections[0] as? XCSourceTextRange guard let range = DHTextRange(textRange: selection) else { completionHandler(nil) return } let newSelection = invocation.buffer.lines.addSwiftExtension(for: range.start) if let textSelection = selection { textSelection.start.column = newSelection.start.column textSelection.start.line = newSelection.start.line textSelection.end.column = newSelection.end.column textSelection.end.line = newSelection.end.line } completionHandler(nil) } }
mit
02713f235a7a8038b6c9d130d06f7487
33.176471
116
0.665232
4.861925
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureInterest/Sources/FeatureInterestUI/Dashboard/InterestDashboardAnnouncementViewController.swift
1
4105
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import PlatformUIKit public final class InterestDashboardAnnouncementViewController: UIViewController { private let tableView = SelfSizingTableView() private let presenter: InterestDashboardAnnouncementPresenting public init(presenter: InterestDashboardAnnouncementPresenting) { self.presenter = presenter super.init(nibName: nil, bundle: nil) } @available(*, unavailable) required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Lifecycle override public func loadView() { view = UIView() view.backgroundColor = .white } override public func viewDidLoad() { super.viewDidLoad() setupTableView() tableView.reloadData() } private func setupTableView() { view.addSubview(tableView) tableView.layoutToSuperview(axis: .horizontal, usesSafeAreaLayoutGuide: true) tableView.layoutToSuperview(axis: .vertical, usesSafeAreaLayoutGuide: true) tableView.tableFooterView = UIView() tableView.estimatedRowHeight = 100 tableView.rowHeight = UITableView.automaticDimension tableView.register(AnnouncementTableViewCell.self) tableView.register(BadgeNumberedTableViewCell.self) tableView.registerNibCell(ButtonsTableViewCell.self, in: .platformUIKit) tableView.register(LineItemTableViewCell.self) tableView.register(FooterTableViewCell.self) tableView.separatorColor = .clear tableView.delegate = self tableView.dataSource = self } } // MARK: - UITableViewDelegate, UITableViewDataSource extension InterestDashboardAnnouncementViewController: UITableViewDelegate, UITableViewDataSource { public func tableView( _ tableView: UITableView, numberOfRowsInSection section: Int ) -> Int { presenter.cellCount } public func tableView( _ tableView: UITableView, cellForRowAt indexPath: IndexPath ) -> UITableViewCell { let cell: UITableViewCell let type = presenter.cellArrangement[indexPath.row] switch type { case .announcement(let viewModel): cell = announcement(for: indexPath, viewModel: viewModel) case .numberedItem(let viewModel): cell = numberedCell(for: indexPath, viewModel: viewModel) case .buttons(let buttons): cell = buttonsCell(for: indexPath, buttons: buttons) case .item(let presenter): cell = lineItemCell(for: indexPath, presenter: presenter) case .footer(let presenter): cell = footerCell(for: indexPath, presenter: presenter) } return cell } // MARK: - Accessors private func announcement(for indexPath: IndexPath, viewModel: AnnouncementCardViewModel) -> UITableViewCell { let cell = tableView.dequeue(AnnouncementTableViewCell.self, for: indexPath) cell.viewModel = viewModel return cell } private func numberedCell(for indexPath: IndexPath, viewModel: BadgeNumberedItemViewModel) -> UITableViewCell { let cell = tableView.dequeue(BadgeNumberedTableViewCell.self, for: indexPath) cell.viewModel = viewModel return cell } private func lineItemCell(for indexPath: IndexPath, presenter: LineItemCellPresenting) -> UITableViewCell { let cell = tableView.dequeue(LineItemTableViewCell.self, for: indexPath) cell.presenter = presenter return cell } private func footerCell(for indexPath: IndexPath, presenter: FooterTableViewCellPresenter) -> FooterTableViewCell { let cell = tableView.dequeue(FooterTableViewCell.self, for: indexPath) cell.presenter = presenter return cell } private func buttonsCell(for indexPath: IndexPath, buttons: [ButtonViewModel]) -> UITableViewCell { let cell = tableView.dequeue(ButtonsTableViewCell.self, for: indexPath) cell.models = buttons return cell } }
lgpl-3.0
003e347ad2e1e5384ac4689b24fbdd43
35.318584
119
0.693226
5.4214
false
false
false
false
lukevanin/OCRAI
CardScanner/UICollectionView+Photos.swift
1
1603
// // UICollectionView+Photos.swift // CardScanner // // Created by Luke Van In on 2017/03/07. // Copyright © 2017 Luke Van In. All rights reserved. // import UIKit import Photos extension UICollectionView { func applyChanges(_ changes: PHFetchResultChangeDetails<PHAsset>, inSection section: Int, completion: ((Bool) -> Void)? = nil) { if changes.hasIncrementalChanges { performBatchUpdates({ [weak self] in if let indexSet = changes.removedIndexes { let indexPaths = indexSet.map { IndexPath(item: $0, section: section) } self?.deleteItems(at: indexPaths) } if let indexSet = changes.insertedIndexes { let indexPaths = indexSet.map { IndexPath(item: $0, section: section) } self?.insertItems(at: indexPaths) } if let indexSet = changes.changedIndexes { let indexPaths = indexSet.map { IndexPath(item: $0, section: section) } self?.reloadItems(at: indexPaths) } if changes.hasMoves { changes.enumerateMoves { self?.moveItem( at: IndexPath(item: $0, section: 0), to: IndexPath(item: $1, section: 0) ) } } }, completion: completion) } else { reloadData() } } }
mit
9ecb9de34752efd4b68695a61016b56f
33.826087
132
0.486891
5.430508
false
false
false
false
HarukaMa/iina
iina/UpdateChecker.swift
1
4706
// // UpdateChecker.swift // iina // // Created by lhc on 12/1/2017. // Copyright © 2017 lhc. All rights reserved. // import Foundation import Just class UpdateChecker { enum State { case updateDetected, noUpdate, error, networkError } struct GithubTag { var name: String var numericName: [Int] var commitSHA: String var commitUrl: String var zipUrl: String var tarUrl: String } static let githubTagApiPath = "https://api.github.com/repos/lhc70000/iina/tags" static func checkUpdate(alertIfOfflineOrNoUpdate: Bool = true) { var tagList: [GithubTag] = [] Just.get(githubTagApiPath) { response in // network error guard response.ok else { if response.statusCode == nil { // if network not available if alertIfOfflineOrNoUpdate { showUpdateAlert(.networkError, message: response.reason) } } else { // if network error showUpdateAlert(.error, message: response.reason) } return } guard let tags = response.json as? [[String: Any]] else { showUpdateAlert(.error, message: "Wrong response format") return } // parse tags tags.forEach { tag in guard let name = tag["name"] as? String else { return } // discard tags like "v0.0.1-build2" guard Regex.tagVersion.matches(name) else { return } let numericName = Regex.tagVersion.captures(in: name)[1].components(separatedBy: ".").map { str -> Int in return Int(str) ?? 0 } guard let commitInfo = tag["commit"] as? [String: String] else { return } tagList.append(GithubTag(name: name, numericName: numericName, commitSHA: commitInfo["sha"] ?? "", commitUrl: commitInfo["url"] ?? "", zipUrl: tag["zipball_url"] as! String, tarUrl: tag["tarball_url"] as! String)) } // tagList should not be empty guard tagList.count > 0 else { showUpdateAlert(.error, message: "Wrong response format") return } // get latest let latest = tagList.sorted { $1.numericName.lexicographicallyPrecedes($0.numericName) }.first!.numericName // get current let currentVer = Bundle.main.infoDictionary!["CFBundleShortVersionString"] as! String let current = currentVer.components(separatedBy: ".").map { str -> Int in return Int(str) ?? 0 } // compare let hasUpdate = current.lexicographicallyPrecedes(latest) if hasUpdate { showUpdateAlert(.updateDetected) } else if alertIfOfflineOrNoUpdate { showUpdateAlert(.noUpdate) } } } private static func showUpdateAlert(_ state: State, message: String? = nil) { DispatchQueue.main.sync { let alert = NSAlert() let isError = state == .error || state == .networkError let title: String var mainMessage: String switch state { case .updateDetected: title = NSLocalizedString("update.title_update_found", comment: "Title") mainMessage = NSLocalizedString("update.update_found", comment: "Update found") case .noUpdate: title = NSLocalizedString("update.title_no_update", comment: "Title") mainMessage = NSLocalizedString("update.no_update", comment: "No update") case .error, .networkError: title = NSLocalizedString("update.title_error", comment: "Title") mainMessage = NSLocalizedString("update.check_failed", comment: "Error") alert.alertStyle = .warning } if let message = message { mainMessage.append("\n\n\(message)") } alert.alertStyle = isError ? .warning : .informational alert.messageText = title alert.informativeText = mainMessage if state == .noUpdate { // if no update alert.addButton(withTitle: "OK") alert.runModal() } else { // if require user action alert.addButton(withTitle: NSLocalizedString("update.dl_from_website", comment: "Website")) alert.addButton(withTitle: NSLocalizedString("update.dl_from_github", comment: "Github")) alert.addButton(withTitle: "Cancel") let result = alert.runModal() if result == NSAlertFirstButtonReturn { // website NSWorkspace.shared().open(URL(string: AppData.websiteLink)!) } else if result == NSAlertSecondButtonReturn { // github NSWorkspace.shared().open(URL(string: AppData.githubReleaseLink)!) } } } } }
gpl-3.0
eaad9b03e4233fdb0be159ad64056d9f
30.15894
113
0.606164
4.608227
false
false
false
false
JerrySir/YCOA
YCOA/Main/My/View/MyInfoDescriptionTableViewCell.swift
1
2230
// // MyInfoDescriptionTableViewCell.swift // YCOA // // Created by Jerry on 2016/12/14. // Copyright © 2016年 com.baochunsteel. All rights reserved. // import UIKit import ReactiveCocoa class MyInfoDescriptionTableViewCell: UITableViewCell { @IBOutlet weak var headIconImageView: UIImageView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var departmentLabel: UILabel! @IBOutlet weak var positionLabel: UILabel! @IBOutlet weak var accountLabel: UILabel! @IBOutlet weak var companyLabel: UILabel! @IBOutlet weak var uidLabel: UILabel! @IBOutlet weak var logoutButton: UIButton! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } func configure(headIconURL: String?, name: String?, department: String?, position: String?, account: String?, company: String?, uid: String?) { self.nameLabel.text = name self.departmentLabel.text = department self.positionLabel.text = position self.accountLabel.text = account self.companyLabel.text = company self.uidLabel.text = uid guard headIconURL != nil && headIconURL!.utf8.count > 0 else { self.headIconImageView.image = #imageLiteral(resourceName: "contact_place_holder_icon") return } self.headIconImageView.sd_setImage(with: URL(string: headIconURL!), placeholderImage: #imageLiteral(resourceName: "contact_place_holder_icon"), options: .lowPriority) //样式 self.headIconImageView.layer.masksToBounds = true self.headIconImageView.layer.cornerRadius = JRSCREEN_WIDTH / 3.0 / 2.0 self.headIconImageView.layer.borderWidth = 2.0 self.headIconImageView.layer.borderColor = UIColor.white.cgColor } func configureLogout(action: @escaping () -> Void) { self.logoutButton.rac_signal(for: .touchUpInside).take(until: self.rac_prepareForReuseSignal).subscribeNext { (sender) in action() } } }
mit
e2405291924056972f2415b19020e8a0
34.854839
174
0.676563
4.63125
false
false
false
false
ncsrobin/Fuber
SplashScreenUI/Constants.swift
1
1603
/** * 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 Foundation /// The total animation duration of the splash animation let kAnimationDuration: TimeInterval = 3.0 /// The length of the second part of the duration let kAnimationDurationDelay: TimeInterval = 0.5 /// The offset between the AnimatedULogoView and the background Grid let kAnimationTimeOffset: CFTimeInterval = 0.35 * kAnimationDuration /// The ripple magnitude. Increase by small amounts for amusement ( <= .2) :] let kRippleMagnitudeMultiplier: CGFloat = 0.025
apache-2.0
da6ba6a8f42d24070c7579d1f40d7a82
44.8
80
0.767935
4.606322
false
false
false
false
sjf0213/DingShan
DingshanSwift/DingshanSwift/StageMenuView.swift
1
7959
// // StageMenuView.swift // DingshanSwift // // Created by song jufeng on 15/11/30. // Copyright © 2015年 song jufeng. All rights reserved. // import Foundation class StageMenuView : UIView{ var tapItemHandler : ((index:Int) -> Void)?// 用户点击处理 var userSelectIndex:Int = 0 var mainBtn = GalleryMenuButtton() var subItemContainer = UIView()// 按钮容器 var mask:UIView?// 黑色半透明背景,相应点击收起 var container_h:CGFloat = 0.0 // 菜单内容的配置 var menuConfig = [AnyObject](){ didSet{ if menuConfig.count > 0{ if let one = menuConfig[0] as? [NSObject:AnyObject]{ if let title = one["title"] as? String{ self.mainBtn.btnText = title } } } self.mainBtn.curSelected = false } } // 菜单的展开与收起 var isExpanded:Bool = false { didSet{ if isExpanded{ // UIView.animateWithDuration(0.2, delay: 0.0, options: UIViewAnimationOptions.CurveEaseIn, animations: { () -> Void in // // // }, completion: { (finished) -> Void in // self.subItemContainer.layer.position = CGPoint(x: 160, y: 20) // }) self.frame = CGRectMake(0, 20, UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.height-20) self.mainBtn.frame = CGRect(x: 50, y: 0, width: UIScreen.mainScreen().bounds.width - 100, height: TopBar_H - 21) print("- - - ****2222 self.mainBtn.frame = \(self.mainBtn.frame)") self.mainBtn.curSelected = true // 点击菜单覆盖的黑色半透明区域,收起菜单 self.mask = UIView(frame: CGRect(x: 0, y: TopBar_H-20, width: UIScreen.mainScreen().bounds.width, height: UIScreen.mainScreen().bounds.height-TopBar_H+20)) self.mask?.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.5) self.mask?.alpha = 0.0 let tapRec = UITapGestureRecognizer(target: self, action: Selector("resetMenu")) self.mask?.addGestureRecognizer(tapRec) self.insertSubview(self.mask!, belowSubview: self.subItemContainer) UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.3, options:UIViewAnimationOptions([.AllowUserInteraction, .BeginFromCurrentState]), animations: { () -> Void in self.subItemContainer.frame = CGRectMake(0, TopBar_H-20, UIScreen.mainScreen().bounds.width, self.container_h) self.mask?.alpha = 1.0 }, completion: { (finished) -> Void in print("self.mainBtn.frame = \(self.mainBtn.frame)") }) }else{ // UIView.animateWithDuration(0.2, delay: 0.0, options: UIViewAnimationOptions.CurveEaseIn, animations: { () -> Void in // // // }, completion: { (finished) -> Void in // self.subItemContainer.layer.position = CGPoint(x: 160, y: 160) // }) self.frame = CGRectMake(50, 20, UIScreen.mainScreen().bounds.width - 100, TopBar_H - 20) self.mainBtn.frame = CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width - 100, height: TopBar_H - 21) UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.3, options:UIViewAnimationOptions([.AllowUserInteraction, .BeginFromCurrentState]), animations: { () -> Void in self.subItemContainer.frame = CGRect(x: 0, y: TopBar_H-20, width: UIScreen.mainScreen().bounds.width, height: 0) }, completion: { (finished) -> Void in self.mainBtn.curSelected = false self.mask?.removeFromSuperview() self.mask = nil }) } } } // MARK: init required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(frame aRect: CGRect) { super.init(frame: aRect); self.backgroundColor = UIColor.clearColor() self.clipsToBounds = true self.subItemContainer = UIView(frame: CGRect(x: 0, y: TopBar_H-20, width: UIScreen.mainScreen().bounds.width, height: 0)) self.subItemContainer.backgroundColor = UIColor.whiteColor() self.subItemContainer.clipsToBounds = true self.addSubview(self.subItemContainer) self.mainBtn = GalleryMenuButtton(frame: CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width - 100, height: TopBar_H - 21)) self.mainBtn.backgroundColor = NAVI_COLOR self.mainBtn.setTitleColor(UIColor.blackColor(), forState:.Normal) self.mainBtn.addTarget(self, action: Selector("onTapMainBtn:"), forControlEvents: UIControlEvents.TouchUpInside) self.addSubview(self.mainBtn) self.isExpanded = false } override func layoutSubviews() { // self.btnBgContainer?.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: GalleryMenuBar_H) } // 复位所有菜单状态 func resetMenu(){ // 收起菜单 self.isExpanded = false // 清空二级项 for v in self.subItemContainer.subviews{ v.removeFromSuperview() } } // 点击按钮 func onTapMainBtn(sender:UIButton) { if(self.isExpanded){ self.resetMenu() return; } print(sender, terminator: "") // 生成所有菜单项 let w:CGFloat = UIScreen.mainScreen().bounds.width / 2 let h:CGFloat = 58 for (var i = 0; i < self.menuConfig.count; i++){ if let one = self.menuConfig[i] as? [NSObject:AnyObject]{ let row:Int = i/2 let col:Int = i%2 let rect = CGRect(x: w * CGFloat(col), y: h * CGFloat(row), width: w, height: h) let btn = StageMenuItem(frame: rect) btn.tag = i if let t = one["title"] as? String{ btn.setTitle(t, forState: UIControlState.Normal) } // 显示当前正在选中的项目 if userSelectIndex == i{ btn.curSelected = true } btn.addTarget(self, action: Selector("onTapItem:"), forControlEvents: UIControlEvents.TouchUpInside) self.subItemContainer.addSubview(btn) } } let rowCount:Int = (self.menuConfig.count-1)/2 + 1 self.container_h = h*CGFloat(rowCount) + 10 self.isExpanded = true } // 点击二级菜单项 func onTapItem(item:GalleryMenuItem) { print("----------sub menu items title:\(item.titleLabel?.text), tagIndex:\(item.tag)") // 低亮其他 for v in self.subItemContainer.subviews{ if let i = v as? GalleryMenuItem{ if i != item{ i.curSelected = false } } } // 高亮所选 item.curSelected = true // 更新设置 userSelectIndex = item.tag // 更新Btn显示 mainBtn.btnText = item.titleForState(UIControlState.Normal)! // 点击动作,进入下一个页面 // dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.0 * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), { self.resetMenu() if (self.tapItemHandler != nil) { self.tapItemHandler?(index:self.userSelectIndex) } // }) } }
mit
280756e1472908f416561f5e4f3509ee
41.977654
223
0.553302
4.446243
false
false
false
false
mitchtreece/Bulletin
Example/Pods/Espresso/Espresso/Classes/Core/UIKit/UIViewController/UIStyledNavigationController.swift
1
8662
// // UIStyledNavigationController.swift // Espresso // // Created by Mitch Treece on 12/18/17. // import UIKit /** A `UINavigationController` subclass that implements common appearance properties. */ public class UIStyledNavigationController: UINavigationController, UINavigationControllerDelegate { private var statusBarStyle: UIStatusBarStyle = .default private var statusBarHidden: Bool = false private var statusBarAnimation: UIStatusBarAnimation = .fade public override var preferredStatusBarStyle: UIStatusBarStyle { return statusBarStyle } public override var prefersStatusBarHidden: Bool { return statusBarHidden } public override var preferredStatusBarUpdateAnimation: UIStatusBarAnimation { return statusBarAnimation } public override init(rootViewController: UIViewController) { super.init(rootViewController: rootViewController) self.delegate = self } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.delegate = self } public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } public override func viewDidLoad() { super.viewDidLoad() // Style initial view controller if let vc = viewControllers.first, vc is UINavigationBarAppearanceProvider, viewControllers.count > 0 { update(with: vc, sourceVC: nil, animated: false) } } private func update(with vc: UIViewController, sourceVC: UIViewController?, animated: Bool) { let sbAppearance = (vc as? UIStatusBarAppearanceProvider)?.preferredStatusBarAppearance let lastSbAppearance = (sourceVC as? UIStatusBarAppearanceProvider)?.preferredStatusBarAppearance let defaultSbAppearance = UIStatusBarAppearance() statusBarStyle = sbAppearance?.style ?? lastSbAppearance?.style ?? defaultSbAppearance.style statusBarHidden = sbAppearance?.hidden ?? lastSbAppearance?.hidden ?? defaultSbAppearance.hidden statusBarAnimation = sbAppearance?.animation ?? lastSbAppearance?.animation ?? defaultSbAppearance.animation setNeedsStatusBarAppearanceUpdate() let nbAppearance = (vc as? UINavigationBarAppearanceProvider)?.preferredNavigationBarAppearance let lastNbAppearance = (sourceVC as? UINavigationBarAppearanceProvider)?.preferredNavigationBarAppearance let defaultNbAppearance = UINavigationBarAppearance() navigationBar.barTintColor = nbAppearance?.barColor ?? lastNbAppearance?.barColor ?? defaultNbAppearance.barColor navigationBar.tintColor = nbAppearance?.itemColor ?? lastNbAppearance?.itemColor ?? defaultNbAppearance.itemColor navigationBar.titleTextAttributes = [ .font: nbAppearance?.titleFont ?? lastNbAppearance?.titleFont ?? defaultNbAppearance.titleFont, .foregroundColor: nbAppearance?.titleColor ?? lastNbAppearance?.titleColor ?? defaultNbAppearance.titleColor ] if #available(iOS 11, *) { let displayMode = nbAppearance?.largeTitleDisplayMode ?? lastNbAppearance?.largeTitleDisplayMode ?? .automatic vc.navigationItem.largeTitleDisplayMode = displayMode navigationBar.prefersLargeTitles = (displayMode != .never) let titleColor = nbAppearance?.largeTitleColor ?? lastNbAppearance?.largeTitleColor ?? nbAppearance?.titleColor ?? lastNbAppearance?.titleColor ?? defaultNbAppearance.largeTitleColor navigationBar.largeTitleTextAttributes = [ .font: (nbAppearance?.largeTitleFont ?? lastNbAppearance?.largeTitleFont ?? defaultNbAppearance.largeTitleFont) as Any, .foregroundColor: titleColor ] } let hidden = (nbAppearance?.hidden ?? lastNbAppearance?.hidden ?? defaultNbAppearance.hidden) setNavigationBarHidden(hidden, animated: animated) if nbAppearance?.transparent ?? lastNbAppearance?.transparent ?? false { navigationBar.setBackgroundImage(UIImage(), for: .default) navigationBar.shadowImage = UIImage() } else { navigationBar.setBackgroundImage(nil, for: .default) navigationBar.shadowImage = nil } if nbAppearance?.backButtonHidden ?? defaultNbAppearance.backButtonHidden { navigationBar.backIndicatorImage = UIImage() navigationBar.backIndicatorTransitionMaskImage = UIImage() let backItem = UIBarButtonItem(title: nil, style: UIBarButtonItem.Style.plain, target: nil, action: nil) vc.navigationItem.backBarButtonItem = backItem sourceVC?.navigationItem.backBarButtonItem = backItem } else { if var image = nbAppearance?.backButtonImage ?? lastNbAppearance?.backButtonImage { image = image.withRenderingMode(.alwaysTemplate) navigationBar.backIndicatorImage = image navigationBar.backIndicatorTransitionMaskImage = image } if let title = nbAppearance?.backButtonTitle { let backItem = UIBarButtonItem(title: title, style: UIBarButtonItem.Style.plain, target: nil, action: nil) vc.navigationItem.backBarButtonItem = backItem sourceVC?.navigationItem.backBarButtonItem = backItem } } } /** Tells the navigation controller to re-draw it's navigation bar. */ public func setNeedsNavigationBarAppearanceUpdate() { guard let vc = self.topViewController else { return } let sourceIndex = (viewControllers.count - 2) let sourceVC = viewControllers[safe: sourceIndex] update(with: vc, sourceVC: sourceVC, animated: true) } public override func setViewControllers(_ viewControllers: [UIViewController], animated: Bool) { if let vc = viewControllers.last, viewControllers.count > 0 { guard let _ = vc as? UINavigationBarAppearanceProvider else { super.setViewControllers(viewControllers, animated: animated) return } let sourceIndex = (viewControllers.count - 2) let sourceVC = (sourceIndex >= 0) ? viewControllers[sourceIndex] : nil update(with: vc, sourceVC: sourceVC, animated: false) } super.setViewControllers(viewControllers, animated: animated) } public override func pushViewController(_ viewController: UIViewController, animated: Bool) { if viewController is UINavigationBarAppearanceProvider { update(with: viewController, sourceVC: self.topViewController, animated: animated) } super.pushViewController(viewController, animated: animated) } public override func popViewController(animated: Bool) -> UIViewController? { if let topVC = topViewController, let index = viewControllers.firstIndex(of: topVC) { guard (index - 1) >= 0 else { return super.popViewController(animated: animated) } let vc = viewControllers[index - 1] update(with: vc, sourceVC: topVC, animated: animated) } return super.popViewController(animated: animated) } public override func popToRootViewController(animated: Bool) -> [UIViewController]? { guard viewControllers.count > 0 else { return super.popToRootViewController(animated: animated) } let viewController = viewControllers[0] update(with: viewController, sourceVC: self.topViewController, animated: animated) return super.popToRootViewController(animated: animated) } public override func popToViewController(_ viewController: UIViewController, animated: Bool) -> [UIViewController]? { update(with: viewController, sourceVC: self.topViewController, animated: animated) return super.popToViewController(viewController, animated: animated) } }
mit
b8bd80b70169a56622434b7ff4788e5c
38.917051
135
0.648349
6.582067
false
false
false
false
perrywky/CCFlexbox
Source/AppDelegate.swift
1
2504
// // AppDelegate.swift // CCFlexbox // // Created by Perry on 15/12/28. // Copyright © 2015年 Perry. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { let storyboard = UIStoryboard(name: "Demo", bundle: nil) let vc = storyboard.instantiateViewControllerWithIdentifier("DemoViewController") as! DemoViewController // let nav = UINavigationController.init(rootViewController: MasterViewController.init()) window = UIWindow.init() window!.rootViewController = vc window!.makeKeyAndVisible() window!.backgroundColor = UIColor.whiteColor() return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
5f5c47f1f77310aad0ad1ab018f081af
49.02
285
0.747301
5.582589
false
false
false
false
EvgenyKarkan/Feeds4U
iFeed/Sources/Data/Workers/Common/EVKParser.swift
1
2253
// // EVKParser.swift // iFeed // // Created by Evgeny Karkan on 8/16/15. // Copyright (c) 2015 Evgeny Karkan. All rights reserved. // import FeedKit // MARK: - EVKParserDelegate protocol EVKParserDelegate: AnyObject { func didStartParsingFeed() func didEndParsingFeed(_ feed: Feed) func didFailParsingFeed() } final class EVKParser: NSObject { // MARK: - properties weak var delegate: EVKParserDelegate? private var feed : Feed! // MARK: - public API func beginParseURL(_ rssURL: URL) { self.delegate?.didStartParsingFeed() let parser = FeedParser(URL: rssURL) parser.parseAsync { (result) in DispatchQueue.main.async { switch result { case .success(let feed): guard let rssFeed = feed.rssFeed else { self.delegate?.didFailParsingFeed() return } // Create Feed self.feed = EVKBrain.brain.createEntity(name: kFeed) as? Feed self.feed.title = rssFeed.title self.feed.rssURL = rssURL.absoluteString self.feed.summary = rssFeed.description // Create Feeds rssFeed.items?.forEach({ rrsFeedItem in if let feedItem: FeedItem = EVKBrain.brain.createEntity(name: kFeedItem) as? FeedItem { feedItem.title = rrsFeedItem.title ?? "" feedItem.link = rrsFeedItem.link ?? "" feedItem.publishDate = rrsFeedItem.pubDate ?? Date() //relationship feedItem.feed = self.feed } }) self.delegate?.didEndParsingFeed(self.feed) case .failure( _): self.delegate?.didFailParsingFeed() } } } } }
mit
db9ff2880084d574933684ec25371676
33.136364
115
0.458056
5.562963
false
false
false
false
Vadimkomis/Myclok
Pods/Auth0/Auth0/UserPatchAttributes.swift
2
5648
// UserPatchAttributes.swift // // Copyright (c) 2016 Auth0 (http://auth0.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation /// Atributes of the user allowed to update using `patch()` method of `Users` public class UserPatchAttributes { private(set) var dictionary: [String: Any] /** Creates a new attributes - parameter dictionary: default attribute values - returns: new attributes */ public init(dictionary: [String: Any] = [:]) { self.dictionary = dictionary } /** Mark/Unmark a user as blocked - parameter blocked: if the user is blocked - returns: itself */ public func blocked(_ blocked: Bool) -> UserPatchAttributes { dictionary["blocked"] = blocked return self } /** Changes the email of the user - parameter email: new email for the user - parameter verified: if the email is verified - parameter verify: if the user should verify the email - parameter connection: name of the connection - parameter clientId: Auth0 clientId - returns: itself */ public func email(_ email: String, verified: Bool? = nil, verify: Bool? = nil, connection: String, clientId: String) -> UserPatchAttributes { dictionary["email"] = email dictionary["verify_email"] = verify dictionary["email_verified"] = verified dictionary["connection"] = connection dictionary["client_id"] = clientId return self } /** Sets the verified status of the email - parameter verified: if the email is verified or not - parameter connection: connection name - returns: itself */ public func emailVerified(_ verified: Bool, connection: String) -> UserPatchAttributes { dictionary["email_verified"] = verified dictionary["connection"] = connection return self } /** Changes the phone number of the user (SMS connection only) - parameter phoneNumber: new phone number for the user - parameter verified: if the phone number is verified - parameter verify: if the user should verify the phone number - parameter connection: name of the connection - parameter clientId: Auth0 clientId - returns: itself */ public func phoneNumber(_ phoneNumber: String, verified: Bool? = nil, verify: Bool? = nil, connection: String, clientId: String) -> UserPatchAttributes { dictionary["phone_number"] = phoneNumber dictionary["verify_phone_number"] = verify dictionary["phone_verified"] = verified dictionary["connection"] = connection dictionary["client_id"] = clientId return self } /** Sets the verified status of the phone number - parameter verified: if the phone number is verified or not - parameter connection: connection name - returns: itself */ public func phoneVerified(_ verified: Bool, connection: String) -> UserPatchAttributes { dictionary["phone_verified"] = verified dictionary["connection"] = connection return self } /** Changes the user's password - parameter password: new password for the user - parameter verify: if the password should be verified by the user - parameter connection: name of the connection - returns: itself */ public func password(_ password: String, verify: Bool? = nil, connection: String) -> UserPatchAttributes { dictionary["password"] = password dictionary["connection"] = connection dictionary["verify_password"] = verify return self } /** Changes the username - parameter username: new username - parameter connection: name of the connection - returns: itself */ public func username(_ username: String, connection: String) -> UserPatchAttributes { dictionary["username"] = username dictionary["connection"] = connection return self } /** Updates user metadata - parameter metadata: new user metadata values - returns: itself */ public func userMetadata(_ metadata: [String: Any]) -> UserPatchAttributes { dictionary["user_metadata"] = metadata return self } /** Updates app metadata - parameter metadata: new app metadata values - returns: itself */ public func appMetadata(_ metadata: [String: Any]) -> UserPatchAttributes { dictionary["app_metadata"] = metadata return self } }
mit
c85cafabc089a7d31e20b24cf3ba3d36
31.45977
157
0.66289
5.007092
false
false
false
false
stripe/stripe-ios
StripePayments/StripePayments/Internal/Categories/NSDictionary+Stripe.swift
1
4160
// // NSDictionary+Stripe.swift // StripePayments // // Created by Jack Flintermann on 10/15/15. // Copyright © 2015 Stripe, Inc. All rights reserved. // import Foundation extension Dictionary where Key == AnyHashable, Value: Any { @_spi(STP) public func stp_dictionaryByRemovingNulls() -> [AnyHashable: Any] { var result = [AnyHashable: Any]() (self as NSDictionary).enumerateKeysAndObjects({ key, obj, _ in guard let key = key as? AnyHashable else { assertionFailure() return } if let obj = obj as? [Any] { // Save array after removing any null values let stp = obj.stp_arrayByRemovingNulls() result[key] = stp } else if let obj = obj as? [AnyHashable: Any] { // Save dictionary after removing any null values let stp = obj.stp_dictionaryByRemovingNulls() result[key] = stp } else if obj is NSNull { // Skip null value } else { // Save other value result[key] = obj } }) // Make immutable copy return result } func stp_dictionaryByRemovingNonStrings() -> [String: String] { var result: [String: String] = [:] (self as NSDictionary).enumerateKeysAndObjects({ key, obj, _ in if let key = key as? String, let obj = obj as? String { // Save valid key/value pair result[key] = obj } }) // Make immutable copy return result } // Getters @_spi(STP) public func stp_array(forKey key: String) -> [Any]? { let value = self[key] if value != nil { return value as? [Any] } return nil } @_spi(STP) public func stp_bool(forKey key: String, or defaultValue: Bool) -> Bool { let value = self[key] if value != nil { if let value = value as? NSNumber { return value.boolValue } if value is NSString { let string = (value as? String)?.lowercased() // boolValue on NSString is true for "Y", "y", "T", "t", or 1-9 if (string == "true") || (string as NSString?)?.boolValue ?? false { return true } else { return false } } } return defaultValue } @_spi(STP) public func stp_date(forKey key: String) -> Date? { let value = self[key] if let value = value as? NSNumber { let timeInterval = value.doubleValue return Date(timeIntervalSince1970: TimeInterval(timeInterval)) } else if let value = value as? NSString { let timeInterval = value.doubleValue return Date(timeIntervalSince1970: TimeInterval(timeInterval)) } return nil } @_spi(STP) public func stp_dictionary(forKey key: String) -> [AnyHashable: Any]? { let value = self[key] if value != nil && (value is [AnyHashable: Any]) { return value as? [AnyHashable: Any] } return nil } func stp_int(forKey key: String, or defaultValue: Int) -> Int { let value = self[key] if let value = value as? NSNumber { return value.intValue } else if let value = value as? NSString { return Int(value.intValue) } return defaultValue } func stp_number(forKey key: String) -> NSNumber? { return self[key] as? NSNumber } @_spi(STP) public func stp_string(forKey key: String) -> String? { let value = self[key] if value != nil && (value is NSString) { return value as? String } return nil } func stp_url(forKey key: String) -> URL? { let value = self[key] if value != nil && (value is NSString) && ((value as? String)?.count ?? 0) > 0 { return URL(string: value as? String ?? "") } return nil } }
mit
190473ad840e2cad91c6ceb03ec74cc2
30.748092
88
0.523203
4.57033
false
false
false
false
lojals/curiosity_reader
curiosity_reader/curiosity_reader/Charts/Classes/Charts/BarLineChartViewBase.swift
1
52722
// // BarLineChartViewBase.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/15. // // 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 CoreGraphics.CGBase import UIKit.UIGestureRecognizer /// Base-class of LineChart, BarChart, ScatterChart and CandleStickChart. public class BarLineChartViewBase: ChartViewBase, UIGestureRecognizerDelegate { /// the maximum number of entried to which values will be drawn internal var _maxVisibleValueCount = 100 private var _pinchZoomEnabled = false private var _doubleTapToZoomEnabled = true private var _dragEnabled = true private var _scaleXEnabled = true private var _scaleYEnabled = true /// the color for the background of the chart-drawing area (everything behind the grid lines). public var gridBackgroundColor = UIColor(red: 240/255.0, green: 240/255.0, blue: 240/255.0, alpha: 1.0) public var borderColor = UIColor.blackColor() public var borderLineWidth: CGFloat = 1.0 /// flag indicating if the grid background should be drawn or not public var drawGridBackgroundEnabled = true /// Sets drawing the borders rectangle to true. If this is enabled, there is no point drawing the axis-lines of x- and y-axis. public var drawBordersEnabled = false /// the object representing the labels on the y-axis, this object is prepared /// in the pepareYLabels() method internal var _leftAxis: ChartYAxis! internal var _rightAxis: ChartYAxis! /// the object representing the labels on the x-axis internal var _xAxis: ChartXAxis! internal var _leftYAxisRenderer: ChartYAxisRenderer! internal var _rightYAxisRenderer: ChartYAxisRenderer! internal var _leftAxisTransformer: ChartTransformer! internal var _rightAxisTransformer: ChartTransformer! internal var _xAxisRenderer: ChartXAxisRenderer! private var _tapGestureRecognizer: UITapGestureRecognizer! private var _doubleTapGestureRecognizer: UITapGestureRecognizer! private var _pinchGestureRecognizer: UIPinchGestureRecognizer! private var _panGestureRecognizer: UIPanGestureRecognizer! /// flag that indicates if a custom viewport offset has been set private var _customViewPortEnabled = false public override init(frame: CGRect) { super.init(frame: frame); } public required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder); } deinit { stopDeceleration(); } internal override func initialize() { super.initialize(); _leftAxis = ChartYAxis(position: .Left); _rightAxis = ChartYAxis(position: .Right); _xAxis = ChartXAxis(); _leftAxisTransformer = ChartTransformer(viewPortHandler: _viewPortHandler); _rightAxisTransformer = ChartTransformer(viewPortHandler: _viewPortHandler); _leftYAxisRenderer = ChartYAxisRenderer(viewPortHandler: _viewPortHandler, yAxis: _leftAxis, transformer: _leftAxisTransformer); _rightYAxisRenderer = ChartYAxisRenderer(viewPortHandler: _viewPortHandler, yAxis: _rightAxis, transformer: _rightAxisTransformer); _xAxisRenderer = ChartXAxisRenderer(viewPortHandler: _viewPortHandler, xAxis: _xAxis, transformer: _leftAxisTransformer); _tapGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("tapGestureRecognized:")); _doubleTapGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("doubleTapGestureRecognized:")); _doubleTapGestureRecognizer.numberOfTapsRequired = 2; _pinchGestureRecognizer = UIPinchGestureRecognizer(target: self, action: Selector("pinchGestureRecognized:")); _panGestureRecognizer = UIPanGestureRecognizer(target: self, action: Selector("panGestureRecognized:")); _pinchGestureRecognizer.delegate = self; _panGestureRecognizer.delegate = self; self.addGestureRecognizer(_tapGestureRecognizer); self.addGestureRecognizer(_doubleTapGestureRecognizer); self.addGestureRecognizer(_pinchGestureRecognizer); self.addGestureRecognizer(_panGestureRecognizer); _doubleTapGestureRecognizer.enabled = _doubleTapToZoomEnabled; _pinchGestureRecognizer.enabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled; _panGestureRecognizer.enabled = _dragEnabled; } public override func drawRect(rect: CGRect) { super.drawRect(rect); if (_dataNotSet) { return; } let context = UIGraphicsGetCurrentContext(); calcModulus(); if (_xAxisRenderer !== nil) { _xAxisRenderer!.calcXBounds(chart: self, xAxisModulus: _xAxis.axisLabelModulus); } if (renderer !== nil) { renderer!.calcXBounds(chart: self, xAxisModulus: _xAxis.axisLabelModulus); } // execute all drawing commands drawGridBackground(context: context); if (_leftAxis.isEnabled) { _leftYAxisRenderer?.computeAxis(yMin: _leftAxis.axisMinimum, yMax: _leftAxis.axisMaximum); } if (_rightAxis.isEnabled) { _rightYAxisRenderer?.computeAxis(yMin: _rightAxis.axisMinimum, yMax: _rightAxis.axisMaximum); } _xAxisRenderer?.renderAxisLine(context: context); _leftYAxisRenderer?.renderAxisLine(context: context); _rightYAxisRenderer?.renderAxisLine(context: context); // make sure the graph values and grid cannot be drawn outside the content-rect CGContextSaveGState(context); CGContextClipToRect(context, _viewPortHandler.contentRect); if (_xAxis.isDrawLimitLinesBehindDataEnabled) { _xAxisRenderer?.renderLimitLines(context: context); } if (_leftAxis.isDrawLimitLinesBehindDataEnabled) { _leftYAxisRenderer?.renderLimitLines(context: context); } if (_rightAxis.isDrawLimitLinesBehindDataEnabled) { _rightYAxisRenderer?.renderLimitLines(context: context); } _xAxisRenderer?.renderGridLines(context: context); _leftYAxisRenderer?.renderGridLines(context: context); _rightYAxisRenderer?.renderGridLines(context: context); renderer?.drawData(context: context); if (!_xAxis.isDrawLimitLinesBehindDataEnabled) { _xAxisRenderer?.renderLimitLines(context: context); } if (!_leftAxis.isDrawLimitLinesBehindDataEnabled) { _leftYAxisRenderer?.renderLimitLines(context: context); } if (!_rightAxis.isDrawLimitLinesBehindDataEnabled) { _rightYAxisRenderer?.renderLimitLines(context: context); } // if highlighting is enabled if (highlightEnabled && highlightIndicatorEnabled && valuesToHighlight()) { renderer?.drawHighlighted(context: context, indices: _indicesToHightlight); } // Removes clipping rectangle CGContextRestoreGState(context); renderer!.drawExtras(context: context); _xAxisRenderer.renderAxisLabels(context: context); _leftYAxisRenderer.renderAxisLabels(context: context); _rightYAxisRenderer.renderAxisLabels(context: context); renderer!.drawValues(context: context); _legendRenderer.renderLegend(context: context); // drawLegend(); drawMarkers(context: context); drawDescription(context: context); } internal func prepareValuePxMatrix() { _rightAxisTransformer.prepareMatrixValuePx(chartXMin: _chartXMin, deltaX: _deltaX, deltaY: CGFloat(_rightAxis.axisRange), chartYMin: _rightAxis.axisMinimum); _leftAxisTransformer.prepareMatrixValuePx(chartXMin: _chartXMin, deltaX: _deltaX, deltaY: CGFloat(_leftAxis.axisRange), chartYMin: _leftAxis.axisMinimum); } internal func prepareOffsetMatrix() { _rightAxisTransformer.prepareMatrixOffset(_rightAxis.isInverted); _leftAxisTransformer.prepareMatrixOffset(_leftAxis.isInverted); } public override func notifyDataSetChanged() { if (_dataNotSet) { return; } calcMinMax(); _leftAxis?._defaultValueFormatter = _defaultValueFormatter; _rightAxis?._defaultValueFormatter = _defaultValueFormatter; _leftYAxisRenderer?.computeAxis(yMin: _leftAxis.axisMinimum, yMax: _leftAxis.axisMaximum); _rightYAxisRenderer?.computeAxis(yMin: _rightAxis.axisMinimum, yMax: _rightAxis.axisMaximum); _xAxisRenderer?.computeAxis(xValAverageLength: _data.xValAverageLength, xValues: _data.xVals); _legendRenderer?.computeLegend(_data); calculateOffsets(); setNeedsDisplay(); } internal override func calcMinMax() { var minLeft = _data.getYMin(.Left); var maxLeft = _data.getYMax(.Left); var minRight = _data.getYMin(.Right); var maxRight = _data.getYMax(.Right); var leftRange = abs(maxLeft - (_leftAxis.isStartAtZeroEnabled ? 0.0 : minLeft)); var rightRange = abs(maxRight - (_rightAxis.isStartAtZeroEnabled ? 0.0 : minRight)); // in case all values are equal if (leftRange == 0.0) { maxLeft = maxLeft + 1.0; if (!_leftAxis.isStartAtZeroEnabled) { minLeft = minLeft - 1.0; } } if (rightRange == 0.0) { maxRight = maxRight + 1.0; if (!_rightAxis.isStartAtZeroEnabled) { minRight = minRight - 1.0; } } var topSpaceLeft = leftRange * Float(_leftAxis.spaceTop); var topSpaceRight = rightRange * Float(_rightAxis.spaceTop); var bottomSpaceLeft = leftRange * Float(_leftAxis.spaceBottom); var bottomSpaceRight = rightRange * Float(_rightAxis.spaceBottom); _chartXMax = Float(_data.xVals.count - 1); _deltaX = CGFloat(abs(_chartXMax - _chartXMin)); _leftAxis.axisMaximum = !isnan(_leftAxis.customAxisMax) ? _leftAxis.customAxisMax : (maxLeft + topSpaceLeft); _rightAxis.axisMaximum = !isnan(_rightAxis.customAxisMax) ? _rightAxis.customAxisMax : (maxRight + topSpaceRight); _leftAxis.axisMinimum = !isnan(_leftAxis.customAxisMin) ? _leftAxis.customAxisMin : (minLeft - bottomSpaceLeft); _rightAxis.axisMinimum = !isnan(_rightAxis.customAxisMin) ? _rightAxis.customAxisMin : (minRight - bottomSpaceRight); // consider starting at zero (0) if (_leftAxis.isStartAtZeroEnabled) { _leftAxis.axisMinimum = 0.0; } if (_rightAxis.isStartAtZeroEnabled) { _rightAxis.axisMinimum = 0.0; } _leftAxis.axisRange = abs(_leftAxis.axisMaximum - _leftAxis.axisMinimum); _rightAxis.axisRange = abs(_rightAxis.axisMaximum - _rightAxis.axisMinimum); } internal override func calculateOffsets() { if (!_customViewPortEnabled) { var offsetLeft = CGFloat(0.0); var offsetRight = CGFloat(0.0); var offsetTop = CGFloat(0.0); var offsetBottom = CGFloat(0.0); // setup offsets for legend if (_legend !== nil && _legend.isEnabled) { if (_legend.position == .RightOfChart || _legend.position == .RightOfChartCenter) { offsetRight += _legend.textWidthMax + _legend.xOffset * 2.0; } if (_legend.position == .LeftOfChart || _legend.position == .LeftOfChartCenter) { offsetLeft += _legend.textWidthMax + _legend.xOffset * 2.0; } else if (_legend.position == .BelowChartLeft || _legend.position == .BelowChartRight || _legend.position == .BelowChartCenter) { offsetBottom += _legend.textHeightMax * 3.0; } } // offsets for y-labels if (leftAxis.needsOffset) { offsetLeft += leftAxis.requiredSize().width; } if (rightAxis.needsOffset) { offsetRight += rightAxis.requiredSize().width; } var xlabelheight = xAxis.labelHeight * 2.0; if (xAxis.isEnabled) { // offsets for x-labels if (xAxis.labelPosition == .Bottom) { offsetBottom += xlabelheight; } else if (xAxis.labelPosition == .Top) { offsetTop += xlabelheight; } else if (xAxis.labelPosition == .BothSided) { offsetBottom += xlabelheight; offsetTop += xlabelheight; } } var min = CGFloat(10.0); _viewPortHandler.restrainViewPort( offsetLeft: max(min, offsetLeft), offsetTop: max(min, offsetTop), offsetRight: max(min, offsetRight), offsetBottom: max(min, offsetBottom)); } prepareOffsetMatrix(); prepareValuePxMatrix(); } /// calculates the modulus for x-labels and grid internal func calcModulus() { if (_xAxis === nil || !_xAxis.isEnabled) { return; } if (!_xAxis.isAxisModulusCustom) { _xAxis.axisLabelModulus = Int(ceil((CGFloat(_data.xValCount) * _xAxis.labelWidth) / (_viewPortHandler.contentWidth * _viewPortHandler.touchMatrix.a))); } if (_xAxis.axisLabelModulus < 1) { _xAxis.axisLabelModulus = 1; } } public override func getMarkerPosition(#entry: ChartDataEntry, dataSetIndex: Int) -> CGPoint { var xPos = CGFloat(entry.xIndex); if (self.isKindOfClass(BarChartView)) { var bd = _data as! BarChartData; var space = bd.groupSpace; var j = _data.getDataSetByIndex(dataSetIndex)!.entryIndex(entry: entry, isEqual: true); var x = CGFloat(j * (_data.dataSetCount - 1) + dataSetIndex) + space * CGFloat(j) + space / 2.0; xPos += x; } // position of the marker depends on selected value index and value var pt = CGPoint(x: xPos, y: CGFloat(entry.value) * _animator.phaseY); getTransformer(_data.getDataSetByIndex(dataSetIndex)!.axisDependency).pointValueToPixel(&pt); return pt; } /// draws the grid background internal func drawGridBackground(#context: CGContext) { if (drawGridBackgroundEnabled || drawBordersEnabled) { CGContextSaveGState(context); } if (drawGridBackgroundEnabled) { // draw the grid background CGContextSetFillColorWithColor(context, gridBackgroundColor.CGColor); CGContextFillRect(context, _viewPortHandler.contentRect); } if (drawBordersEnabled) { CGContextSetLineWidth(context, borderLineWidth); CGContextSetStrokeColorWithColor(context, borderColor.CGColor); CGContextStrokeRect(context, _viewPortHandler.contentRect); } if (drawGridBackgroundEnabled || drawBordersEnabled) { CGContextRestoreGState(context); } } /// Returns the Transformer class that contains all matrices and is /// responsible for transforming values into pixels on the screen and /// backwards. public func getTransformer(which: ChartYAxis.AxisDependency) -> ChartTransformer { if (which == .Left) { return _leftAxisTransformer; } else { return _rightAxisTransformer; } } // MARK: - Gestures private enum GestureScaleAxis { case Both case X case Y } private var _isDragging = false; private var _isScaling = false; private var _gestureScaleAxis = GestureScaleAxis.Both; private var _closestDataSetToTouch: ChartDataSet!; private var _panGestureReachedEdge: Bool = false; private weak var _outerScrollView: UIScrollView?; /// the last highlighted object private var _lastHighlighted: ChartHighlight!; private var _lastPanPoint = CGPoint() /// This is to prevent using setTranslation which resets velocity private var _decelerationLastTime: NSTimeInterval = 0.0 private var _decelerationDisplayLink: CADisplayLink! private var _decelerationVelocity = CGPoint() @objc private func tapGestureRecognized(recognizer: UITapGestureRecognizer) { if (_dataNotSet) { return; } if (recognizer.state == UIGestureRecognizerState.Ended) { var h = getHighlightByTouchPoint(recognizer.locationInView(self)); if (h === nil || h!.isEqual(_lastHighlighted)) { self.highlightValue(highlight: nil, callDelegate: true); _lastHighlighted = nil; } else { _lastHighlighted = h; self.highlightValue(highlight: h, callDelegate: true); } } } @objc private func doubleTapGestureRecognized(recognizer: UITapGestureRecognizer) { if (_dataNotSet) { return; } if (recognizer.state == UIGestureRecognizerState.Ended) { if (!_dataNotSet && _doubleTapToZoomEnabled) { var location = recognizer.locationInView(self); location.x = location.x - _viewPortHandler.offsetLeft; if (isAnyAxisInverted && _closestDataSetToTouch !== nil && getAxis(_closestDataSetToTouch.axisDependency).isInverted) { location.y = -(location.y - _viewPortHandler.offsetTop); } else { location.y = -(self.bounds.size.height - location.y - _viewPortHandler.offsetBottom); } self.zoom(1.4, scaleY: 1.4, x: location.x, y: location.y); } } } @objc private func pinchGestureRecognized(recognizer: UIPinchGestureRecognizer) { if (recognizer.state == UIGestureRecognizerState.Began) { stopDeceleration(); if (!_dataNotSet && (_pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled)) { _isScaling = true; if (_pinchZoomEnabled) { _gestureScaleAxis = .Both; } else { var x = abs(recognizer.locationInView(self).x - recognizer.locationOfTouch(1, inView: self).x); var y = abs(recognizer.locationInView(self).y - recognizer.locationOfTouch(1, inView: self).y); if (x > y) { _gestureScaleAxis = .X; } else { _gestureScaleAxis = .Y; } } } } else if (recognizer.state == UIGestureRecognizerState.Ended || recognizer.state == UIGestureRecognizerState.Cancelled) { if (_isScaling) { _isScaling = false; } } else if (recognizer.state == UIGestureRecognizerState.Changed) { if (_isScaling) { var location = recognizer.locationInView(self); location.x = location.x - _viewPortHandler.offsetLeft; if (isAnyAxisInverted && _closestDataSetToTouch !== nil && getAxis(_closestDataSetToTouch.axisDependency).isInverted) { location.y = -(location.y - _viewPortHandler.offsetTop); } else { location.y = -(_viewPortHandler.chartHeight - location.y - _viewPortHandler.offsetBottom); } var scaleX = (_gestureScaleAxis == .Both || _gestureScaleAxis == .X) && _scaleXEnabled ? recognizer.scale : 1.0; var scaleY = (_gestureScaleAxis == .Both || _gestureScaleAxis == .Y) && _scaleYEnabled ? recognizer.scale : 1.0; var matrix = CGAffineTransformMakeTranslation(location.x, location.y); matrix = CGAffineTransformScale(matrix, scaleX, scaleY); matrix = CGAffineTransformTranslate(matrix, -location.x, -location.y); matrix = CGAffineTransformConcat(_viewPortHandler.touchMatrix, matrix); _viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true); recognizer.scale = 1.0; } } } @objc private func panGestureRecognized(recognizer: UIPanGestureRecognizer) { if (recognizer.state == UIGestureRecognizerState.Began) { stopDeceleration(); if ((!_dataNotSet && _dragEnabled && !self.hasNoDragOffset) || !self.isFullyZoomedOut) { _isDragging = true; _closestDataSetToTouch = getDataSetByTouchPoint(recognizer.locationOfTouch(0, inView: self)); var translation = recognizer.translationInView(self); if (!performPanChange(translation: translation)) { if (_outerScrollView !== nil) { // We can stop dragging right now, and let the scroll view take control _outerScrollView = nil; _isDragging = false; } } else { if (_outerScrollView !== nil) { // Prevent the parent scroll view from scrolling _outerScrollView?.scrollEnabled = false; } } _lastPanPoint = recognizer.translationInView(self); } } else if (recognizer.state == UIGestureRecognizerState.Changed) { if (_isDragging) { var originalTranslation = recognizer.translationInView(self); var translation = CGPoint(x: originalTranslation.x - _lastPanPoint.x, y: originalTranslation.y - _lastPanPoint.y); performPanChange(translation: translation); _lastPanPoint = originalTranslation; } else if (isHighlightPerDragEnabled) { var h = getHighlightByTouchPoint(recognizer.locationInView(self)); if ((h === nil && _lastHighlighted !== nil) || (h !== nil && _lastHighlighted === nil) || (h !== nil && _lastHighlighted !== nil && !h!.isEqual(_lastHighlighted))) { _lastHighlighted = h; self.highlightValue(highlight: h, callDelegate: true); } } } else if (recognizer.state == UIGestureRecognizerState.Ended || recognizer.state == UIGestureRecognizerState.Cancelled) { if (_isDragging) { if (recognizer.state == UIGestureRecognizerState.Ended && isDragDecelerationEnabled) { stopDeceleration(); _decelerationLastTime = CACurrentMediaTime(); _decelerationVelocity = recognizer.velocityInView(self); _decelerationDisplayLink = CADisplayLink(target: self, selector: Selector("decelerationLoop")); _decelerationDisplayLink.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes); } _isDragging = false; } if (_outerScrollView !== nil) { _outerScrollView?.scrollEnabled = true; _outerScrollView = nil; } } } private func performPanChange(var #translation: CGPoint) -> Bool { if (isAnyAxisInverted && _closestDataSetToTouch !== nil && getAxis(_closestDataSetToTouch.axisDependency).isInverted) { if (self is HorizontalBarChartView) { translation.x = -translation.x; } else { translation.y = -translation.y; } } var originalMatrix = _viewPortHandler.touchMatrix; var matrix = CGAffineTransformMakeTranslation(translation.x, translation.y); matrix = CGAffineTransformConcat(originalMatrix, matrix); matrix = _viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true); // Did we managed to actually drag or did we reach the edge? return matrix.tx != originalMatrix.tx || matrix.ty != originalMatrix.ty; } public func stopDeceleration() { if (_decelerationDisplayLink !== nil) { _decelerationDisplayLink.removeFromRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes); _decelerationDisplayLink = nil; } } @objc private func decelerationLoop() { var currentTime = CACurrentMediaTime(); _decelerationVelocity.x *= self.dragDecelerationFrictionCoef; _decelerationVelocity.y *= self.dragDecelerationFrictionCoef; var timeInterval = CGFloat(currentTime - _decelerationLastTime); var distance = CGPoint( x: _decelerationVelocity.x * timeInterval, y: _decelerationVelocity.y * timeInterval ); if (!performPanChange(translation: distance)) { // We reached the edge, stop _decelerationVelocity.x = 0.0; _decelerationVelocity.y = 0.0; } _decelerationLastTime = currentTime; if (abs(_decelerationVelocity.x) < 0.001 && abs(_decelerationVelocity.y) < 0.001) { stopDeceleration(); } } public override func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool { if (!super.gestureRecognizerShouldBegin(gestureRecognizer)) { return false; } if (gestureRecognizer == _panGestureRecognizer) { if (_dataNotSet || !_dragEnabled || !self.hasNoDragOffset || (self.isFullyZoomedOut && !self.isHighlightPerDragEnabled)) { return false; } } else if (gestureRecognizer == _pinchGestureRecognizer) { if (_dataNotSet || (!_pinchZoomEnabled && !_scaleXEnabled && !_scaleYEnabled)) { return false; } } return true; } public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool { if ((gestureRecognizer.isKindOfClass(UIPinchGestureRecognizer) && otherGestureRecognizer.isKindOfClass(UIPanGestureRecognizer)) || (gestureRecognizer.isKindOfClass(UIPanGestureRecognizer) && otherGestureRecognizer.isKindOfClass(UIPinchGestureRecognizer))) { return true; } if (gestureRecognizer.isKindOfClass(UIPanGestureRecognizer) && otherGestureRecognizer.isKindOfClass(UIPanGestureRecognizer) && ( gestureRecognizer == _panGestureRecognizer )) { var scrollView = self.superview; while (scrollView !== nil && !scrollView!.isKindOfClass(UIScrollView)) { scrollView = scrollView?.superview; } var foundScrollView = scrollView as? UIScrollView; if (foundScrollView !== nil && !foundScrollView!.scrollEnabled) { foundScrollView = nil; } var scrollViewPanGestureRecognizer: UIGestureRecognizer!; if (foundScrollView !== nil) { for scrollRecognizer in foundScrollView!.gestureRecognizers as! [UIGestureRecognizer] { if (scrollRecognizer.isKindOfClass(UIPanGestureRecognizer)) { scrollViewPanGestureRecognizer = scrollRecognizer as! UIPanGestureRecognizer; break; } } } if (otherGestureRecognizer === scrollViewPanGestureRecognizer) { _outerScrollView = foundScrollView; return true; } } return false; } /// MARK: Viewport modifiers /// Zooms in by 1.4f, into the charts center. center. public func zoomIn() { var matrix = _viewPortHandler.zoomIn(x: self.bounds.size.width / 2.0, y: -(self.bounds.size.height / 2.0)); _viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true); } /// Zooms out by 0.7f, from the charts center. center. public func zoomOut() { var matrix = _viewPortHandler.zoomOut(x: self.bounds.size.width / 2.0, y: -(self.bounds.size.height / 2.0)); _viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true); } /// Zooms in or out by the given scale factor. x and y are the coordinates /// (in pixels) of the zoom center. /// /// :param: scaleX if < 1f --> zoom out, if > 1f --> zoom in /// :param: scaleY if < 1f --> zoom out, if > 1f --> zoom in /// :param: x /// :param: y public func zoom(scaleX: CGFloat, scaleY: CGFloat, x: CGFloat, y: CGFloat) { var matrix = _viewPortHandler.zoom(scaleX: scaleX, scaleY: scaleY, x: x, y: -y); _viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true); } /// Resets all zooming and dragging and makes the chart fit exactly it's bounds. public func fitScreen() { var matrix = _viewPortHandler.fitScreen(); _viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true); } /// Sets the minimum scale value to which can be zoomed out. 1f = fitScreen public func setScaleMinima(scaleX: CGFloat, scaleY: CGFloat) { _viewPortHandler.setMinimumScaleX(scaleX); _viewPortHandler.setMinimumScaleY(scaleY); } /// Sets the size of the area (range on the x-axis) that should be maximum /// visible at once. If this is e.g. set to 10, no more than 10 values on the /// x-axis can be viewed at once without scrolling. public func setVisibleXRange(xRange: CGFloat) { var xScale = _deltaX / (xRange); _viewPortHandler.setMinimumScaleX(xScale); } /// Sets the size of the area (range on the y-axis) that should be maximum visible at once. /// /// :param: yRange /// :param: axis - the axis for which this limit should apply public func setVisibleYRange(yRange: CGFloat, axis: ChartYAxis.AxisDependency) { var yScale = getDeltaY(axis) / yRange; _viewPortHandler.setMinimumScaleY(yScale); } /// Moves the left side of the current viewport to the specified x-index. public func moveViewToX(xIndex: Int) { if (_viewPortHandler.hasChartDimens) { var pt = CGPoint(x: CGFloat(xIndex), y: 0.0); getTransformer(.Left).pointValueToPixel(&pt); _viewPortHandler.centerViewPort(pt: pt, chart: self); } else { _sizeChangeEventActions.append({[weak self] () in self?.moveViewToX(xIndex); }); } } /// Centers the viewport to the specified y-value on the y-axis. /// /// :param: yValue /// :param: axis - which axis should be used as a reference for the y-axis public func moveViewToY(yValue: CGFloat, axis: ChartYAxis.AxisDependency) { if (_viewPortHandler.hasChartDimens) { var valsInView = getDeltaY(axis) / _viewPortHandler.scaleY; var pt = CGPoint(x: 0.0, y: yValue + valsInView / 2.0); getTransformer(axis).pointValueToPixel(&pt); _viewPortHandler.centerViewPort(pt: pt, chart: self); } else { _sizeChangeEventActions.append({[weak self] () in self?.moveViewToY(yValue, axis: axis); }); } } /// This will move the left side of the current viewport to the specified x-index on the x-axis, and center the viewport to the specified y-value on the y-axis. /// /// :param: xIndex /// :param: yValue /// :param: axis - which axis should be used as a reference for the y-axis public func moveViewTo(#xIndex: Int, yValue: CGFloat, axis: ChartYAxis.AxisDependency) { if (_viewPortHandler.hasChartDimens) { var valsInView = getDeltaY(axis) / _viewPortHandler.scaleY; var pt = CGPoint(x: CGFloat(xIndex), y: yValue + valsInView / 2.0); getTransformer(axis).pointValueToPixel(&pt); _viewPortHandler.centerViewPort(pt: pt, chart: self); } else { _sizeChangeEventActions.append({[weak self] () in self?.moveViewTo(xIndex: xIndex, yValue: yValue, axis: axis); }); } } /// This will move the center of the current viewport to the specified x-index and y-value. /// /// :param: xIndex /// :param: yValue /// :param: axis - which axis should be used as a reference for the y-axis public func centerViewTo(#xIndex: Int, yValue: CGFloat, axis: ChartYAxis.AxisDependency) { if (_viewPortHandler.hasChartDimens) { var valsInView = getDeltaY(axis) / _viewPortHandler.scaleY; var xsInView = CGFloat(xAxis.values.count) / _viewPortHandler.scaleX; var pt = CGPoint(x: CGFloat(xIndex) - xsInView / 2.0, y: yValue + valsInView / 2.0); getTransformer(axis).pointValueToPixel(&pt); _viewPortHandler.centerViewPort(pt: pt, chart: self); } else { _sizeChangeEventActions.append({[weak self] () in self?.centerViewTo(xIndex: xIndex, yValue: yValue, axis: axis); }); } } /// Sets custom offsets for the current ViewPort (the offsets on the sides of the actual chart window). Setting this will prevent the chart from automatically calculating it's offsets. Use resetViewPortOffsets() to undo this. public func setViewPortOffsets(#left: CGFloat, top: CGFloat, right: CGFloat, bottom: CGFloat) { _customViewPortEnabled = true; if (NSThread.isMainThread()) { self._viewPortHandler.restrainViewPort(offsetLeft: left, offsetTop: top, offsetRight: right, offsetBottom: bottom); prepareOffsetMatrix(); prepareValuePxMatrix(); } else { dispatch_async(dispatch_get_main_queue(), { self.setViewPortOffsets(left: left, top: top, right: right, bottom: bottom); }); } } /// Resets all custom offsets set via setViewPortOffsets(...) method. Allows the chart to again calculate all offsets automatically. public func resetViewPortOffsets() { _customViewPortEnabled = false; calculateOffsets(); } // MARK: - Accessors /// Returns the delta-y value (y-value range) of the specified axis. public func getDeltaY(axis: ChartYAxis.AxisDependency) -> CGFloat { if (axis == .Left) { return CGFloat(leftAxis.axisRange); } else { return CGFloat(rightAxis.axisRange); } } /// Returns the position (in pixels) the provided Entry has inside the chart view public func getPosition(e: ChartDataEntry, axis: ChartYAxis.AxisDependency) -> CGPoint { var vals = CGPoint(x: CGFloat(e.xIndex), y: CGFloat(e.value)); getTransformer(axis).pointValueToPixel(&vals); return vals; } /// the number of maximum visible drawn values on the chart /// only active when setDrawValues() is enabled public var maxVisibleValueCount: Int { get { return _maxVisibleValueCount; } set { _maxVisibleValueCount = newValue; } } /// is dragging enabled? (moving the chart with the finger) for the chart (this does not affect scaling). public var dragEnabled: Bool { get { return _dragEnabled; } set { if (_dragEnabled != newValue) { _dragEnabled = newValue; } } } /// is dragging enabled? (moving the chart with the finger) for the chart (this does not affect scaling). public var isDragEnabled: Bool { return dragEnabled; } /// is scaling enabled? (zooming in and out by gesture) for the chart (this does not affect dragging). public func setScaleEnabled(enabled: Bool) { if (_scaleXEnabled != enabled || _scaleYEnabled != enabled) { _scaleXEnabled = enabled; _scaleYEnabled = enabled; _pinchGestureRecognizer.enabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled; } } public var scaleXEnabled: Bool { get { return _scaleXEnabled } set { if (_scaleXEnabled != newValue) { _scaleXEnabled = newValue; _pinchGestureRecognizer.enabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled; } } } public var scaleYEnabled: Bool { get { return _scaleYEnabled } set { if (_scaleYEnabled != newValue) { _scaleYEnabled = newValue; _pinchGestureRecognizer.enabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled; } } } public var isScaleXEnabled: Bool { return scaleXEnabled; } public var isScaleYEnabled: Bool { return scaleYEnabled; } /// flag that indicates if double tap zoom is enabled or not public var doubleTapToZoomEnabled: Bool { get { return _doubleTapToZoomEnabled; } set { if (_doubleTapToZoomEnabled != newValue) { _doubleTapToZoomEnabled = newValue; _doubleTapGestureRecognizer.enabled = _doubleTapToZoomEnabled; } } } /// :returns: true if zooming via double-tap is enabled false if not. /// :default: true public var isDoubleTapToZoomEnabled: Bool { return doubleTapToZoomEnabled; } /// flag that indicates if highlighting per dragging over a fully zoomed out chart is enabled public var highlightPerDragEnabled = true /// If set to true, highlighting per dragging over a fully zoomed out chart is enabled /// You might want to disable this when using inside a UIScrollView /// :default: true public var isHighlightPerDragEnabled: Bool { return highlightPerDragEnabled; } /// if set to true, the highlight indicator (lines for linechart, dark bar for barchart) will be drawn upon selecting values. public var highlightIndicatorEnabled = true /// If set to true, the highlight indicator (vertical line for LineChart and /// ScatterChart, dark bar overlay for BarChart) that gives visual indication /// that an Entry has been selected will be drawn upon selecting values. This /// does not depend on the MarkerView. /// :default: true public var isHighlightIndicatorEnabled: Bool { return highlightIndicatorEnabled; } /// :returns: true if drawing the grid background is enabled, false if not. /// :default: true public var isDrawGridBackgroundEnabled: Bool { return drawGridBackgroundEnabled; } /// :returns: true if drawing the borders rectangle is enabled, false if not. /// :default: false public var isDrawBordersEnabled: Bool { return drawBordersEnabled; } /// Returns the Highlight object (contains x-index and DataSet index) of the selected value at the given touch point inside the Line-, Scatter-, or CandleStick-Chart. public func getHighlightByTouchPoint(var pt: CGPoint) -> ChartHighlight! { if (_dataNotSet || _data === nil) { println("Can't select by touch. No data set."); return nil; } var valPt = CGPoint(); valPt.x = pt.x; valPt.y = 0.0; // take any transformer to determine the x-axis value _leftAxisTransformer.pixelToValue(&valPt); var xTouchVal = valPt.x; var base = floor(xTouchVal); var touchOffset = _deltaX * 0.025; // touch out of chart if (xTouchVal < -touchOffset || xTouchVal > _deltaX + touchOffset) { return nil; } if (base < 0.0) { base = 0.0; } if (base >= _deltaX) { base = _deltaX - 1.0; } var xIndex = Int(base); // check if we are more than half of a x-value or not if (xTouchVal - base > 0.5) { xIndex = Int(base + 1.0); } var valsAtIndex = getYValsAtIndex(xIndex); var leftdist = ChartUtils.getMinimumDistance(valsAtIndex, val: Float(pt.y), axis: .Left); var rightdist = ChartUtils.getMinimumDistance(valsAtIndex, val: Float(pt.y), axis: .Right); if (_data!.getFirstRight() === nil) { rightdist = FLT_MAX; } if (_data!.getFirstLeft() === nil) { leftdist = FLT_MAX; } var axis: ChartYAxis.AxisDependency = leftdist < rightdist ? .Left : .Right; var dataSetIndex = ChartUtils.closestDataSetIndex(valsAtIndex, value: Float(pt.y), axis: axis); if (dataSetIndex == -1) { return nil; } return ChartHighlight(xIndex: xIndex, dataSetIndex: dataSetIndex); } /// Returns an array of SelInfo objects for the given x-index. The SelInfo /// objects give information about the value at the selected index and the /// DataSet it belongs to. public func getYValsAtIndex(xIndex: Int) -> [ChartSelInfo] { var vals = [ChartSelInfo](); var pt = CGPoint(); for (var i = 0, count = _data.dataSetCount; i < count; i++) { var dataSet = _data.getDataSetByIndex(i); if (dataSet === nil) { continue; } // extract all y-values from all DataSets at the given x-index var yVal = dataSet!.yValForXIndex(xIndex); pt.y = CGFloat(yVal); getTransformer(dataSet!.axisDependency).pointValueToPixel(&pt); if (!isnan(pt.y)) { vals.append(ChartSelInfo(value: Float(pt.y), dataSetIndex: i, dataSet: dataSet!)); } } return vals; } /// Returns the x and y values in the chart at the given touch point /// (encapsulated in a PointD). This method transforms pixel coordinates to /// coordinates / values in the chart. This is the opposite method to /// getPixelsForValues(...). public func getValueByTouchPoint(var #pt: CGPoint, axis: ChartYAxis.AxisDependency) -> CGPoint { getTransformer(axis).pixelToValue(&pt); return pt; } /// Transforms the given chart values into pixels. This is the opposite /// method to getValueByTouchPoint(...). public func getPixelForValue(x: Float, y: Float, axis: ChartYAxis.AxisDependency) -> CGPoint { var pt = CGPoint(x: CGFloat(x), y: CGFloat(y)); getTransformer(axis).pointValueToPixel(&pt); return pt; } /// returns the y-value at the given touch position (must not necessarily be /// a value contained in one of the datasets) public func getYValueByTouchPoint(#pt: CGPoint, axis: ChartYAxis.AxisDependency) -> CGFloat { return getValueByTouchPoint(pt: pt, axis: axis).y; } /// returns the Entry object displayed at the touched position of the chart public func getEntryByTouchPoint(pt: CGPoint) -> ChartDataEntry! { var h = getHighlightByTouchPoint(pt); if (h !== nil) { return _data!.getEntryForHighlight(h!); } return nil; } ///returns the DataSet object displayed at the touched position of the chart public func getDataSetByTouchPoint(pt: CGPoint) -> BarLineScatterCandleChartDataSet! { var h = getHighlightByTouchPoint(pt); if (h !== nil) { return _data.getDataSetByIndex(h.dataSetIndex) as! BarLineScatterCandleChartDataSet!; } return nil; } /// Returns the lowest x-index (value on the x-axis) that is still visible on he chart. public var lowestVisibleXIndex: Int { var pt = CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentBottom); getTransformer(.Left).pixelToValue(&pt); return (pt.x <= 0.0) ? 0 : Int(pt.x + 1.0); } /// Returns the highest x-index (value on the x-axis) that is still visible on the chart. public var highestVisibleXIndex: Int { var pt = CGPoint(x: viewPortHandler.contentRight, y: viewPortHandler.contentBottom); getTransformer(.Left).pixelToValue(&pt); return (Int(pt.x) >= _data.xValCount) ? _data.xValCount - 1 : Int(pt.x); } /// returns the current x-scale factor public var scaleX: CGFloat { if (_viewPortHandler === nil) { return 1.0; } return _viewPortHandler.scaleX; } /// returns the current y-scale factor public var scaleY: CGFloat { if (_viewPortHandler === nil) { return 1.0; } return _viewPortHandler.scaleY; } /// if the chart is fully zoomed out, return true public var isFullyZoomedOut: Bool { return _viewPortHandler.isFullyZoomedOut; } /// Returns the left y-axis object. In the horizontal bar-chart, this is the /// top axis. public var leftAxis: ChartYAxis { return _leftAxis; } /// Returns the right y-axis object. In the horizontal bar-chart, this is the /// bottom axis. public var rightAxis: ChartYAxis { return _rightAxis; } /// Returns the y-axis object to the corresponding AxisDependency. In the /// horizontal bar-chart, LEFT == top, RIGHT == BOTTOM public func getAxis(axis: ChartYAxis.AxisDependency) -> ChartYAxis { if (axis == .Left) { return _leftAxis; } else { return _rightAxis; } } /// Returns the object representing all x-labels, this method can be used to /// acquire the XAxis object and modify it (e.g. change the position of the /// labels) public var xAxis: ChartXAxis { return _xAxis; } /// flag that indicates if pinch-zoom is enabled. if true, both x and y axis can be scaled with 2 fingers, if false, x and y axis can be scaled separately public var pinchZoomEnabled: Bool { get { return _pinchZoomEnabled; } set { if (_pinchZoomEnabled != newValue) { _pinchZoomEnabled = newValue; _pinchGestureRecognizer.enabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled; } } } /// returns true if pinch-zoom is enabled, false if not /// :default: false public var isPinchZoomEnabled: Bool { return pinchZoomEnabled; } /// Set an offset in dp that allows the user to drag the chart over it's /// bounds on the x-axis. public func setDragOffsetX(offset: CGFloat) { _viewPortHandler.setDragOffsetX(offset); } /// Set an offset in dp that allows the user to drag the chart over it's /// bounds on the y-axis. public func setDragOffsetY(offset: CGFloat) { _viewPortHandler.setDragOffsetY(offset); } /// :returns: true if both drag offsets (x and y) are zero or smaller. public var hasNoDragOffset: Bool { return _viewPortHandler.hasNoDragOffset; } public var xAxisRenderer: ChartXAxisRenderer { return _xAxisRenderer; } public var leftYAxisRenderer: ChartYAxisRenderer { return _leftYAxisRenderer; } public var rightYAxisRenderer: ChartYAxisRenderer { return _rightYAxisRenderer; } public override var chartYMax: Float { return max(leftAxis.axisMaximum, rightAxis.axisMaximum); } public override var chartYMin: Float { return min(leftAxis.axisMinimum, rightAxis.axisMinimum); } /// Returns true if either the left or the right or both axes are inverted. public var isAnyAxisInverted: Bool { return _leftAxis.isInverted || _rightAxis.isInverted; } } /// Default formatter that calculates the position of the filled line. internal class BarLineChartFillFormatter: NSObject, ChartFillFormatter { private weak var _chart: BarLineChartViewBase!; internal init(chart: BarLineChartViewBase) { _chart = chart; } internal func getFillLinePosition(#dataSet: LineChartDataSet, data: LineChartData, chartMaxY: Float, chartMinY: Float) -> CGFloat { var fillMin = CGFloat(0.0); if (dataSet.yMax > 0.0 && dataSet.yMin < 0.0) { fillMin = 0.0; } else { if (!_chart.getAxis(dataSet.axisDependency).isStartAtZeroEnabled) { var max: Float, min: Float; if (data.yMax > 0.0) { max = 0.0; } else { max = chartMaxY; } if (data.yMin < 0.0) { min = 0.0; } else { min = chartMinY; } fillMin = CGFloat(dataSet.yMin >= 0.0 ? min : max); } else { fillMin = 0.0; } } return fillMin; } }
gpl-2.0
f48a8f3240ae87e075cfa3715bc41ea3
33.594488
229
0.576932
5.573739
false
false
false
false
Fenrikur/ef-app_ios
Domain Model/EurofurenceModelTests/Events/Favourites/WhenLaunchingApplicationWithPreexistingFavourites.swift
1
1660
import EurofurenceModel import EurofurenceModelTestDoubles import XCTest class WhenLaunchingApplicationWithPreexistingFavourites: XCTestCase { func testTheObserversAreToldAboutTheFavouritedEvents() { let characteristics = ModelCharacteristics.randomWithoutDeletions let expected = characteristics.events.changed.map({ EventIdentifier($0.identifier) }) let dataStore = InMemoryDataStore(response: characteristics) dataStore.performTransaction { (transaction) in expected.forEach(transaction.saveFavouriteEventIdentifier) } let context = EurofurenceSessionTestBuilder().with(dataStore).build() let observer = CapturingEventsServiceObserver() context.eventsService.add(observer) XCTAssertTrue(expected.contains(elementsFrom: observer.capturedFavouriteEventIdentifiers)) } func testTheFavouritesAreSortedByEventStartTime() { let response = ModelCharacteristics.randomWithoutDeletions let events = response.events.changed let dataStore = InMemoryDataStore(response: response) dataStore.performTransaction { (transaction) in events.map({ EventIdentifier($0.identifier) }).forEach(transaction.saveFavouriteEventIdentifier) } let context = EurofurenceSessionTestBuilder().with(dataStore).build() let observer = CapturingEventsServiceObserver() context.eventsService.add(observer) let expected = events.sorted(by: { $0.startDateTime < $1.startDateTime }).map({ EventIdentifier($0.identifier) }) XCTAssertEqual(expected, observer.capturedFavouriteEventIdentifiers) } }
mit
a220778e026c0e8017baec7851320363
41.564103
121
0.744578
5.99278
false
true
false
false
arnoappenzeller/PiPifier
PiPifier iOS/PiPifier iOS/RoundRectButton.swift
1
921
// // RoundRectButton.swift // PiPifier iOS // // Created by Arno Appenzeller on 18.05.17. // Copyright © 2017 APPenzeller. All rights reserved. // import UIKit @IBDesignable class RoundRectButton: UIButton { @IBInspectable public var cornerRadius: CGFloat = 2.0 { didSet { self.layer.cornerRadius = self.cornerRadius } } @IBInspectable public var borderWidth: CGFloat = 1.0 { didSet{ self.layer.borderWidth = self.borderWidth } } @IBInspectable public var borderColor: UIColor = UIColor.blue { didSet{ self.layer.borderColor = self.borderColor.cgColor } } /* // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing code } */ }
mit
045c55a4ee1c1dd9a443e9fe58e38922
20.904762
78
0.613043
4.423077
false
false
false
false
NoryCao/zhuishushenqi
zhuishushenqi/Root/Views/ZSLeftViewCell.swift
1
1700
// // ZSLeftViewCell.swift // zhuishushenqi // // Created by caony on 2018/10/22. // Copyright © 2018 QS. All rights reserved. // import UIKit class ZSLeftViewCell: UITableViewCell { lazy var iconView:UIImageView = { let imageView = UIImageView(frame: CGRect(x: SideVC.maximumLeftOffsetWidth/2 - 12.5, y: 10, width: 25, height: 25)) return imageView }() lazy var selectedView:UIView = { let view = UIView(frame: CGRect(x: 0,y: 0,width: 5,height: 44)) view.backgroundColor = UIColor ( red: 0.7235, green: 0.0, blue: 0.1146, alpha: 1.0 ) view.isHidden = true return view }() lazy var nameLabel:UILabel = { let label = UILabel(frame: CGRect(x: SideVC.maximumLeftOffsetWidth/2 - 20,y: 35,width: 40,height: 10)) label.font = UIFont.systemFont(ofSize: 9) label.textAlignment = .center label.textColor = UIColor(white: 1.0, alpha: 0.5) return label }() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) contentView.addSubview(self.iconView) contentView.addSubview(self.selectedView) contentView.addSubview(self.nameLabel) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
mit
069885b6e8a0ad2647e1effc95c17411
29.339286
123
0.634491
4.164216
false
false
false
false
manavgabhawala/swift
test/SILGen/if_while_binding.swift
1
14686
// RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -Xllvm -sil-full-demangle -emit-silgen %s | %FileCheck %s func foo() -> String? { return "" } func bar() -> String? { return "" } func a(_ x: String) {} func b(_ x: String) {} func c(_ x: String) {} func marker_1() {} func marker_2() {} func marker_3() {} // CHECK-LABEL: sil hidden @_T016if_while_binding0A8_no_else{{[_0-9a-zA-Z]*}}F func if_no_else() { // CHECK: [[FOO:%.*]] = function_ref @_T016if_while_binding3fooSSSgyF // CHECK: [[OPT_RES:%.*]] = apply [[FOO]]() // CHECK: switch_enum [[OPT_RES]] : $Optional<String>, case #Optional.some!enumelt.1: [[YES:bb[0-9]+]], default [[CONT:bb[0-9]+]] if let x = foo() { // CHECK: [[YES]]([[VAL:%[0-9]+]] : $String): // CHECK: [[A:%.*]] = function_ref @_T016if_while_binding1a // CHECK: [[BORROWED_VAL:%.*]] = begin_borrow [[VAL]] // CHECK: [[VAL_COPY:%.*]] = copy_value [[BORROWED_VAL]] // CHECK: apply [[A]]([[VAL_COPY]]) // CHECK: end_borrow [[BORROWED_VAL]] from [[VAL]] // CHECK: destroy_value [[VAL]] // CHECK: br [[CONT]] a(x) } // CHECK: [[CONT]]: // CHECK-NEXT: tuple () } // CHECK: } // end sil function '_T016if_while_binding0A8_no_else{{[_0-9a-zA-Z]*}}F' // CHECK-LABEL: sil hidden @_T016if_while_binding0A11_else_chainyyF : $@convention(thin) () -> () { func if_else_chain() { // CHECK: [[FOO:%.*]] = function_ref @_T016if_while_binding3foo{{[_0-9a-zA-Z]*}}F // CHECK-NEXT: [[OPT_RES:%.*]] = apply [[FOO]]() // CHECK-NEXT: switch_enum [[OPT_RES]] : $Optional<String>, case #Optional.some!enumelt.1: [[YESX:bb[0-9]+]], default [[NOX:bb[0-9]+]] if let x = foo() { // CHECK: [[YESX]]([[VAL:%[0-9]+]] : $String): // CHECK: debug_value [[VAL]] : $String, let, name "x" // CHECK: [[A:%.*]] = function_ref @_T016if_while_binding1a // CHECK: [[BORROWED_VAL:%.*]] = begin_borrow [[VAL]] // CHECK: [[VAL_COPY:%.*]] = copy_value [[BORROWED_VAL]] // CHECK: apply [[A]]([[VAL_COPY]]) // CHECK: end_borrow [[BORROWED_VAL]] from [[VAL]] // CHECK: destroy_value [[VAL]] // CHECK: br [[CONT_X:bb[0-9]+]] a(x) // CHECK: [[NOX]]: // CHECK: alloc_box ${ var String }, var, name "y" // CHECK: switch_enum {{.*}} : $Optional<String>, case #Optional.some!enumelt.1: [[YESY:bb[0-9]+]], default [[ELSE1:bb[0-9]+]] // CHECK: [[ELSE1]]: // CHECK: dealloc_box {{.*}} ${ var String } // CHECK: br [[ELSE:bb[0-9]+]] } else if var y = bar() { // CHECK: [[YESY]]([[VAL:%[0-9]+]] : $String): // CHECK: br [[CONT_Y:bb[0-9]+]] b(y) } else { // CHECK: [[ELSE]]: // CHECK: function_ref if_while_binding.c c("") // CHECK: br [[CONT_Y]] } // CHECK: [[CONT_Y]]: // br [[CONT_X]] // CHECK: [[CONT_X]]: } // CHECK-LABEL: sil hidden @_T016if_while_binding0B5_loopyyF : $@convention(thin) () -> () { func while_loop() { // CHECK: br [[LOOP_ENTRY:bb[0-9]+]] // CHECK: [[LOOP_ENTRY]]: // CHECK: switch_enum {{.*}} : $Optional<String>, case #Optional.some!enumelt.1: [[LOOP_BODY:bb[0-9]+]], default [[LOOP_EXIT:bb[0-9]+]] while let x = foo() { // CHECK: [[LOOP_BODY]]([[X:%[0-9]+]] : $String): // CHECK: switch_enum {{.*}} : $Optional<String>, case #Optional.some!enumelt.1: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]] if let y = bar() { // CHECK: [[YES]]([[Y:%[0-9]+]] : $String): a(y) break // CHECK: destroy_value [[Y]] // CHECK: destroy_value [[X]] // CHECK: br [[LOOP_EXIT]] } // CHECK: [[NO]]: // CHECK: destroy_value [[X]] // CHECK: br [[LOOP_ENTRY]] } // CHECK: [[LOOP_EXIT]]: // CHECK-NEXT: tuple () // CHECK-NEXT: return } // Don't leak alloc_stacks for address-only conditional bindings in 'while'. // <rdar://problem/16202294> // CHECK-LABEL: sil hidden @_T016if_while_binding0B13_loop_generic{{[_0-9a-zA-Z]*}}F // CHECK: br [[COND:bb[0-9]+]] // CHECK: [[COND]]: // CHECK: [[X:%.*]] = alloc_stack $T, let, name "x" // CHECK: [[OPTBUF:%[0-9]+]] = alloc_stack $Optional<T> // CHECK: switch_enum_addr {{.*}}, case #Optional.some!enumelt.1: [[LOOPBODY:bb.*]], default [[OUT:bb[0-9]+]] // CHECK: [[OUT]]: // CHECK: dealloc_stack [[OPTBUF]] // CHECK: dealloc_stack [[X]] // CHECK: br [[DONE:bb[0-9]+]] // CHECK: [[LOOPBODY]]: // CHECK: [[ENUMVAL:%.*]] = unchecked_take_enum_data_addr // CHECK: copy_addr [take] [[ENUMVAL]] to [initialization] [[X]] // CHECK: destroy_addr [[X]] // CHECK: dealloc_stack [[X]] // CHECK: br [[COND]] // CHECK: [[DONE]]: // CHECK: destroy_value %0 func while_loop_generic<T>(_ source: () -> T?) { while let x = source() { } } // <rdar://problem/19382942> Improve 'if let' to avoid optional pyramid of doom // CHECK-LABEL: sil hidden @_T016if_while_binding0B11_loop_multiyyF func while_loop_multi() { // CHECK: br [[LOOP_ENTRY:bb[0-9]+]] // CHECK: [[LOOP_ENTRY]]: // CHECK: switch_enum {{.*}}, case #Optional.some!enumelt.1: [[CHECKBUF2:bb.*]], default [[LOOP_EXIT0:bb[0-9]+]] // CHECK: [[CHECKBUF2]]([[A:%[0-9]+]] : $String): // CHECK: debug_value [[A]] : $String, let, name "a" // CHECK: switch_enum {{.*}}, case #Optional.some!enumelt.1: [[LOOP_BODY:bb.*]], default [[LOOP_EXIT2a:bb[0-9]+]] // CHECK: [[LOOP_EXIT2a]]: // CHECK: destroy_value [[A]] // CHECK: br [[LOOP_EXIT0]] // CHECK: [[LOOP_BODY]]([[B:%[0-9]+]] : $String): while let a = foo(), let b = bar() { // CHECK: debug_value [[B]] : $String, let, name "b" // CHECK: [[BORROWED_A:%.*]] = begin_borrow [[A]] // CHECK: [[A_COPY:%.*]] = copy_value [[BORROWED_A]] // CHECK: debug_value [[A_COPY]] : $String, let, name "c" // CHECK: end_borrow [[BORROWED_A]] from [[A]] // CHECK: destroy_value [[A_COPY]] // CHECK: destroy_value [[B]] // CHECK: destroy_value [[A]] // CHECK: br [[LOOP_ENTRY]] let c = a } // CHECK: [[LOOP_EXIT0]]: // CHECK-NEXT: tuple () // CHECK-NEXT: return } // CHECK-LABEL: sil hidden @_T016if_while_binding0A6_multiyyF func if_multi() { // CHECK: switch_enum {{.*}}, case #Optional.some!enumelt.1: [[CHECKBUF2:bb.*]], default [[IF_DONE:bb[0-9]+]] // CHECK: [[CHECKBUF2]]([[A:%[0-9]+]] : $String): // CHECK: debug_value [[A]] : $String, let, name "a" // CHECK: [[B:%[0-9]+]] = alloc_box ${ var String }, var, name "b" // CHECK: [[PB:%[0-9]+]] = project_box [[B]] // CHECK: switch_enum {{.*}}, case #Optional.some!enumelt.1: [[IF_BODY:bb.*]], default [[IF_EXIT1a:bb[0-9]+]] // CHECK: [[IF_EXIT1a]]: // CHECK: dealloc_box {{.*}} ${ var String } // CHECK: destroy_value [[A]] // CHECK: br [[IF_DONE]] // CHECK: [[IF_BODY]]([[BVAL:%[0-9]+]] : $String): if let a = foo(), var b = bar() { // CHECK: store [[BVAL]] to [init] [[PB]] : $*String // CHECK: debug_value {{.*}} : $String, let, name "c" // CHECK: destroy_value [[B]] // CHECK: destroy_value [[A]] // CHECK: br [[IF_DONE]] let c = a } // CHECK: [[IF_DONE]]: // CHECK-NEXT: tuple () // CHECK-NEXT: return } // CHECK-LABEL: sil hidden @_T016if_while_binding0A11_multi_elseyyF func if_multi_else() { // CHECK: switch_enum {{.*}}, case #Optional.some!enumelt.1: [[CHECKBUF2:bb.*]], default [[ELSE:bb[0-9]+]] // CHECK: [[CHECKBUF2]]([[A:%[0-9]+]] : $String): // CHECK: debug_value [[A]] : $String, let, name "a" // CHECK: [[B:%[0-9]+]] = alloc_box ${ var String }, var, name "b" // CHECK: [[PB:%[0-9]+]] = project_box [[B]] // CHECK: switch_enum {{.*}}, case #Optional.some!enumelt.1: [[IF_BODY:bb.*]], default [[IF_EXIT1a:bb[0-9]+]] // CHECK: [[IF_EXIT1a]]: // CHECK: dealloc_box {{.*}} ${ var String } // CHECK: destroy_value [[A]] // CHECK: br [[ELSE]] // CHECK: [[IF_BODY]]([[BVAL:%[0-9]+]] : $String): if let a = foo(), var b = bar() { // CHECK: store [[BVAL]] to [init] [[PB]] : $*String // CHECK: debug_value {{.*}} : $String, let, name "c" // CHECK: destroy_value [[B]] // CHECK: destroy_value [[A]] // CHECK: br [[IF_DONE:bb[0-9]+]] let c = a } else { let d = 0 // CHECK: [[ELSE]]: // CHECK: debug_value {{.*}} : $Int, let, name "d" // CHECK: br [[IF_DONE]] } // CHECK: [[IF_DONE]]: // CHECK-NEXT: tuple () // CHECK-NEXT: return } // CHECK-LABEL: sil hidden @_T016if_while_binding0A12_multi_whereyyF func if_multi_where() { // CHECK: switch_enum {{.*}}, case #Optional.some!enumelt.1: [[CHECKBUF2:bb.*]], default [[ELSE:bb[0-9]+]] // CHECK: [[CHECKBUF2]]([[A:%[0-9]+]] : $String): // CHECK: debug_value [[A]] : $String, let, name "a" // CHECK: [[BBOX:%[0-9]+]] = alloc_box ${ var String }, var, name "b" // CHECK: [[PB:%[0-9]+]] = project_box [[BBOX]] // CHECK: switch_enum {{.*}}, case #Optional.some!enumelt.1: [[CHECK_WHERE:bb.*]], default [[IF_EXIT1a:bb[0-9]+]] // CHECK: [[IF_EXIT1a]]: // CHECK: dealloc_box {{.*}} ${ var String } // CHECK: destroy_value [[A]] // CHECK: br [[ELSE]] // CHECK: [[CHECK_WHERE]]([[B:%[0-9]+]] : $String): // CHECK: function_ref Swift.Bool._getBuiltinLogicValue () -> Builtin.Int1 // CHECK: cond_br {{.*}}, [[IF_BODY:bb[0-9]+]], [[IF_EXIT3:bb[0-9]+]] // CHECK: [[IF_EXIT3]]: // CHECK: destroy_value [[BBOX]] // CHECK: destroy_value [[A]] // CHECK: br [[IF_DONE:bb[0-9]+]] if let a = foo(), var b = bar(), a == b { // CHECK: [[IF_BODY]]: // CHECK: destroy_value [[BBOX]] // CHECK: destroy_value [[A]] // CHECK: br [[IF_DONE]] let c = a } // CHECK: [[IF_DONE]]: // CHECK-NEXT: tuple () // CHECK-NEXT: return } // <rdar://problem/19797158> Swift 1.2's "if" has 2 behaviors. They could be unified. // CHECK-LABEL: sil hidden @_T016if_while_binding0A16_leading_booleanySiF func if_leading_boolean(_ a : Int) { // Test the boolean condition. // CHECK: debug_value %0 : $Int, let, name "a" // CHECK: [[EQRESULT:%[0-9]+]] = apply {{.*}}(%0, %0{{.*}}) : $@convention({{.*}}) (Int, Int{{.*}}) -> Bool // CHECK-NEXT: [[EQRESULTI1:%[0-9]+]] = apply %2([[EQRESULT]]) : $@convention(method) (Bool) -> Builtin.Int1 // CHECK-NEXT: cond_br [[EQRESULTI1]], [[CHECKFOO:bb[0-9]+]], [[IFDONE:bb[0-9]+]] // Call Foo and test for the optional being present. // CHECK: [[CHECKFOO]]: // CHECK: [[OPTRESULT:%[0-9]+]] = apply {{.*}}() : $@convention(thin) () -> @owned Optional<String> // CHECK: switch_enum [[OPTRESULT]] : $Optional<String>, case #Optional.some!enumelt.1: [[SUCCESS:bb.*]], default [[IF_DONE:bb[0-9]+]] // CHECK: [[SUCCESS]]([[B:%[0-9]+]] : $String): // CHECK: debug_value [[B]] : $String, let, name "b" // CHECK: [[BORROWED_B:%.*]] = begin_borrow [[B]] // CHECK: [[B_COPY:%.*]] = copy_value [[BORROWED_B]] // CHECK: debug_value [[B_COPY]] : $String, let, name "c" // CHECK: end_borrow [[BORROWED_B]] from [[B]] // CHECK: destroy_value [[B_COPY]] // CHECK: destroy_value [[B]] // CHECK: br [[IFDONE]] if a == a, let b = foo() { let c = b } // CHECK: [[IFDONE]]: // CHECK-NEXT: tuple () } /// <rdar://problem/20364869> Assertion failure when using 'as' pattern in 'if let' class BaseClass {} class DerivedClass : BaseClass {} // CHECK-LABEL: sil hidden @_T016if_while_binding20testAsPatternInIfLetyAA9BaseClassCSgF func testAsPatternInIfLet(_ a : BaseClass?) { // CHECK: bb0([[ARG:%.*]] : $Optional<BaseClass>): // CHECK: debug_value [[ARG]] : $Optional<BaseClass>, let, name "a" // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]] : $Optional<BaseClass> // CHECK: switch_enum [[ARG_COPY]] : $Optional<BaseClass>, case #Optional.some!enumelt.1: [[OPTPRESENTBB:bb[0-9]+]], default [[NILBB:bb[0-9]+]] // CHECK: [[NILBB]]: // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: br [[EXITBB:bb[0-9]+]] // CHECK: [[OPTPRESENTBB]]([[CLS:%.*]] : $BaseClass): // CHECK: checked_cast_br [[CLS]] : $BaseClass to $DerivedClass, [[ISDERIVEDBB:bb[0-9]+]], [[ISBASEBB:bb[0-9]+]] // CHECK: [[ISDERIVEDBB]]([[DERIVED_CLS:%.*]] : $DerivedClass): // CHECK: [[DERIVED_CLS_SOME:%.*]] = enum $Optional<DerivedClass>, #Optional.some!enumelt.1, [[DERIVED_CLS]] : $DerivedClass // CHECK: br [[MERGE:bb[0-9]+]]([[DERIVED_CLS_SOME]] : $Optional<DerivedClass>) // CHECK: [[ISBASEBB]]([[BASECLASS:%.*]] : $BaseClass): // CHECK: destroy_value [[BASECLASS]] : $BaseClass // CHECK: = enum $Optional<DerivedClass>, #Optional.none!enumelt // CHECK: br [[MERGE]]( // CHECK: [[MERGE]]([[OPTVAL:%[0-9]+]] : $Optional<DerivedClass>): // CHECK: switch_enum [[OPTVAL]] : $Optional<DerivedClass>, case #Optional.some!enumelt.1: [[ISDERIVEDBB:bb[0-9]+]], default [[NILBB:bb[0-9]+]] // CHECK: [[ISDERIVEDBB]]([[DERIVEDVAL:%[0-9]+]] : $DerivedClass): // CHECK: debug_value [[DERIVEDVAL]] : $DerivedClass // => SEMANTIC SIL TODO: This is benign, but scoping wise, this end borrow should be after derived val. // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[DERIVEDVAL]] : $DerivedClass // CHECK: br [[EXITBB]] // CHECK: [[EXITBB]]: // CHECK: destroy_value [[ARG]] : $Optional<BaseClass> // CHECK: tuple () // CHECK: return if case let b as DerivedClass = a { } } // <rdar://problem/22312114> if case crashes swift - bools not supported in let/else yet // CHECK-LABEL: sil hidden @_T016if_while_binding12testCaseBoolySbSgF func testCaseBool(_ value : Bool?) { // CHECK: bb0(%0 : $Optional<Bool>): // CHECK: switch_enum %0 : $Optional<Bool>, case #Optional.some!enumelt.1: bb1, default bb3 // CHECK: bb1(%3 : $Bool): // CHECK: [[ISTRUE:%[0-9]+]] = struct_extract %3 : $Bool, #Bool._value // CHECK: cond_br [[ISTRUE]], bb2, bb3 // CHECK: bb2: // CHECK: function_ref @_T016if_while_binding8marker_1yyF // CHECK: br bb3{{.*}} // id: %8 if case true? = value { marker_1() } // CHECK: bb3: // Preds: bb2 bb1 bb0 // CHECK: switch_enum %0 : $Optional<Bool>, case #Optional.some!enumelt.1: bb4, default bb6 // CHECK: bb4( // CHECK: [[ISTRUE:%[0-9]+]] = struct_extract %10 : $Bool, #Bool._value{{.*}}// user: %12 // CHECK: cond_br [[ISTRUE]], bb6, bb5 // CHECK: bb5: // CHECK: function_ref @_T016if_while_binding8marker_2yyF // CHECK: br bb6{{.*}} // id: %15 // CHECK: bb6: // Preds: bb5 bb4 bb3 if case false? = value { marker_2() } }
apache-2.0
111eee252618f97ccedbad0f957eb894
39.125683
148
0.540583
3.034298
false
false
false
false
ohadh123/MuscleUp-
Pods/GTProgressBar/GTProgressBar/Classes/GTProgressBar.swift
1
7715
// // GTProgressBar.swift // Pods // // Created by Grzegorz Tatarzyn on 19/09/2016. import UIKit @IBDesignable public class GTProgressBar: UIView { private let minimumProgressBarWidth: CGFloat = 20 private let minimumProgressBarFillHeight: CGFloat = 1 private let backgroundView = UIView() private let fillView = UIView() private let progressLabel = UILabel() private var _progress: CGFloat = 1 public var font: UIFont = UIFont.systemFont(ofSize: 12) { didSet { progressLabel.font = font self.setNeedsLayout() } } public var progressLabelInsets: UIEdgeInsets = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5) { didSet { self.setNeedsLayout() } } @IBInspectable public var progressLabelInsetLeft: CGFloat = 0.0 { didSet { self.progressLabelInsets.left = max(0.0, progressLabelInsetLeft) self.setNeedsLayout() } } @IBInspectable public var progressLabelInsetRight: CGFloat = 0.0 { didSet { self.progressLabelInsets.right = max(0.0, progressLabelInsetRight) self.setNeedsLayout() } } @IBInspectable public var progressLabelInsetTop: CGFloat = 0.0 { didSet { self.progressLabelInsets.top = max(0.0, progressLabelInsetTop) self.setNeedsLayout() } } @IBInspectable public var progressLabelInsetBottom: CGFloat = 0.0 { didSet { self.progressLabelInsets.bottom = max(0.0, progressLabelInsetBottom) self.setNeedsLayout() } } public var barMaxHeight: CGFloat? { didSet { self.setNeedsLayout() } } @IBInspectable public var barBorderColor: UIColor = UIColor.black { didSet { backgroundView.layer.borderColor = barBorderColor.cgColor self.setNeedsLayout() } } @IBInspectable public var barBackgroundColor: UIColor = UIColor.white { didSet { backgroundView.backgroundColor = barBackgroundColor self.setNeedsLayout() } } @IBInspectable public var barFillColor: UIColor = UIColor.black { didSet { fillView.backgroundColor = barFillColor self.setNeedsLayout() } } @IBInspectable public var barBorderWidth: CGFloat = 2 { didSet { backgroundView.layer.borderWidth = barBorderWidth self.setNeedsLayout() } } @IBInspectable public var barFillInset: CGFloat = 2 { didSet { self.setNeedsLayout() } } @IBInspectable public var progress: CGFloat { get { return self._progress } set { self._progress = min(max(newValue,0), 1) self.setNeedsLayout() } } @IBInspectable public var labelTextColor: UIColor = UIColor.black { didSet { progressLabel.textColor = labelTextColor self.setNeedsLayout() } } @IBInspectable public var displayLabel: Bool = true { didSet { self.progressLabel.isHidden = !self.displayLabel self.setNeedsLayout() } } @IBInspectable public var cornerRadius: CGFloat = 0.0 { didSet { self.layer.masksToBounds = cornerRadius != 0.0 self.layer.cornerRadius = cornerRadius self.setNeedsLayout() } } public var labelPosition: GTProgressBarLabelPosition = GTProgressBarLabelPosition.left { didSet { self.setNeedsLayout() } } @IBInspectable public var labelPositionInt: Int = 0 { didSet { let enumPosition = GTProgressBarLabelPosition(rawValue: labelPositionInt) if let position = enumPosition { self.labelPosition = position } } } public override init(frame: CGRect) { super.init(frame: frame) prepareSubviews() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) prepareSubviews() } private func prepareSubviews() { progressLabel.textAlignment = NSTextAlignment.center progressLabel.font = font progressLabel.textColor = labelTextColor addSubview(progressLabel) backgroundView.backgroundColor = barBackgroundColor backgroundView.layer.borderWidth = barBorderWidth backgroundView.layer.borderColor = barBorderColor.cgColor addSubview(backgroundView) fillView.backgroundColor = barFillColor addSubview(fillView) } public override func layoutSubviews() { updateProgressLabelText() updateViewsLocation() } public override func sizeThatFits(_ size: CGSize) -> CGSize { return createFrameCalculator().sizeThatFits(size) } private func updateViewsLocation() { let frameCalculator: FrameCalculator = createFrameCalculator() progressLabel.frame = frameCalculator.labelFrame() frameCalculator.center(view: progressLabel, parent: self) backgroundView.frame = frameCalculator.backgroundViewFrame() backgroundView.layer.cornerRadius = cornerRadiusFor(view: backgroundView) if (barMaxHeight != nil) { frameCalculator.center(view: backgroundView, parent: self) } fillView.frame = fillViewFrameFor(progress: _progress) fillView.layer.cornerRadius = cornerRadiusFor(view: fillView) } private func createFrameCalculator() -> FrameCalculator { switch labelPosition { case .right: return LabelRightFrameCalculator(progressBar: self) case .top: return LabelTopFrameCalculator(progressBar: self) case .bottom: return LabelBottomFrameCalculator(progressBar: self) default: return LabelLeftFrameCalculator(progressBar: self) } } private func updateProgressLabelText() { progressLabel.text = "\(Int(_progress * 100))%" } public func animateTo(progress: CGFloat) { let newProgress = min(max(progress,0), 1) let fillViewFrame = fillViewFrameFor(progress: newProgress) let frameChange: () -> () = { self.fillView.frame.size.width = fillViewFrame.size.width self._progress = newProgress } if #available(iOS 10.0, *) { UIViewPropertyAnimator(duration: 0.8, curve: .easeInOut, animations: frameChange) .startAnimation() } else { UIView.animate(withDuration: 0.8, delay: 0, options: [UIViewAnimationOptions.curveEaseInOut], animations: frameChange, completion: nil); } } private func fillViewFrameFor(progress: CGFloat) -> CGRect { let offset = barBorderWidth + barFillInset let fillFrame = backgroundView.frame.insetBy(dx: offset, dy: offset) let fillFrameAdjustedSize = CGSize(width: fillFrame.width * progress, height: fillFrame.height) return CGRect(origin: fillFrame.origin, size: fillFrameAdjustedSize) } private func cornerRadiusFor(view: UIView) -> CGFloat { if cornerRadius != 0.0 { return cornerRadius } return view.frame.height / 2 * 0.7 } }
apache-2.0
f37479762ebbfb1cd6a6141f4103ec36
28.003759
103
0.598315
5.463881
false
false
false
false
ChristianKienle/highway
Sources/HighwayCore/Features/Swift/SwiftRunTool.swift
1
1823
import Foundation import ZFile import Url import Task import Arguments import POSIX public enum SwiftRun { } public extension SwiftRun { public final class Tool { public let context: Context public init(context: Context) { self.context = context } public func run(with options: Options) throws -> Result { let arguments = options.taskArguments let task = try Task(commandName: "swift", arguments: arguments, provider: context.executableProvider) task.currentDirectoryUrl = options.currentWorkingDirectory task.enableReadableOutputDataCapturing() try context.executor.execute(task: task) try task.throwIfNotSuccess("🛣🔥 \(SwiftRun.Tool.self) failed running task\n\(task).") let output = task.capturedOutputString return Result(output: output ?? "") } } } public extension SwiftRun { public struct Result { public let output: String } public struct Options { public var executable: String? = nil // swift run $executable public var arguments: Arguments = .empty public var packageUrl: FolderProtocol? = nil // --package-path public var currentWorkingDirectory: FolderProtocol = FileSystem().currentFolder public init() {} var taskArguments: Arguments { var result = Arguments() result.append("run") if let packageUrl = packageUrl { result.append("--package-path") result.append(packageUrl.path) } if let executable = executable { result.append(executable) } result += arguments return result } } }
mit
ab3fb3efa40fb8264266d30b75c62fc9
31.446429
113
0.598239
5.251445
false
false
false
false
Elm-Tree-Island/Shower
Shower/Carthage/Checkouts/ReactiveCocoa/ReactiveCocoaTests/AppKit/NSPopUpButtonSpec.swift
5
3720
import Quick import Nimble import ReactiveCocoa import ReactiveSwift import Result import AppKit final class NSPopUpButtonSpec: QuickSpec { override func spec() { describe("NSPopUpButton") { var button: NSPopUpButton! var window: NSWindow! weak var _button: NSButton? let testTitles = (0..<100).map { $0.description } beforeEach { window = NSWindow() button = NSPopUpButton(frame: .zero) _button = button for (i, title) in testTitles.enumerated() { let item = NSMenuItem(title: title, action: nil, keyEquivalent: "") item.tag = 1000 + i button.menu?.addItem(item) } window.contentView?.addSubview(button) } afterEach { autoreleasepool { button.removeFromSuperview() button = nil } expect(_button).to(beNil()) } it("should emit selected index changes") { var values = [Int]() button.reactive.selectedIndexes.observeValues { values.append($0) } button.menu?.performActionForItem(at: 1) button.menu?.performActionForItem(at: 99) expect(values) == [1, 99] } it("should emit selected title changes") { var values = [String]() button.reactive.selectedTitles.observeValues { values.append($0) } button.menu?.performActionForItem(at: 1) button.menu?.performActionForItem(at: 99) expect(values) == ["1", "99"] } it("should accept changes from its bindings to its index values") { let (signal, observer) = Signal<Int?, NoError>.pipe() button.reactive.selectedIndex <~ SignalProducer(signal) observer.send(value: 1) expect(button.indexOfSelectedItem) == 1 observer.send(value: 99) expect(button.indexOfSelectedItem) == 99 observer.send(value: nil) expect(button.indexOfSelectedItem) == -1 expect(button.selectedItem?.title).to(beNil()) } it("should accept changes from its bindings to its title values") { let (signal, observer) = Signal<String?, NoError>.pipe() button.reactive.selectedTitle <~ SignalProducer(signal) observer.send(value: "1") expect(button.selectedItem?.title) == "1" observer.send(value: "99") expect(button.selectedItem?.title) == "99" observer.send(value: nil) expect(button.selectedItem?.title).to(beNil()) expect(button.indexOfSelectedItem) == -1 } it("should emit selected item changes") { var values = [NSMenuItem]() button.reactive.selectedItems.observeValues { values.append($0) } button.menu?.performActionForItem(at: 1) button.menu?.performActionForItem(at: 99) let titles = values.map { $0.title } expect(titles) == ["1", "99"] } it("should emit selected tag changes") { var values = [Int]() button.reactive.selectedTags.observeValues { values.append($0) } button.menu?.performActionForItem(at: 1) button.menu?.performActionForItem(at: 99) expect(values) == [1001, 1099] } it("should accept changes from its bindings to its tag values") { let (signal, observer) = Signal<Int, NoError>.pipe() button.reactive.selectedTag <~ SignalProducer(signal) observer.send(value: 1001) expect(button.selectedItem?.tag) == 1001 expect(button.indexOfSelectedItem) == 1 observer.send(value: 1099) expect(button.selectedItem?.tag) == 1099 expect(button.indexOfSelectedItem) == 99 observer.send(value: 1042) expect(button.selectedItem?.tag) == 1042 expect(button.indexOfSelectedItem) == 42 // Sending an invalid tag number doesn't change the selection observer.send(value: testTitles.count + 1) expect(button.selectedItem?.tag) == 1042 expect(button.indexOfSelectedItem) == 42 } } } }
gpl-3.0
e752d1ea6631925664228c4b309cb112
27.181818
72
0.665054
3.75
false
false
false
false
AxziplinLib/TabNavigations
Sources/_ScrollViewDelegates.swift
1
5811
// // _ScrollViewDelegates.swift // AxReminder // // Created by devedbox on 2017/9/19. // Copyright © 2017年 devedbox. All rights reserved. // import UIKit // MARK: - _ScrollViewDelegateQueue. /// A type representing the managing queue of the delegates of one UIScrollView. /// The delegates is managed with the NSHashTable as the storage. internal class _ScrollViewDelegatesQueue: NSObject { /// Delegates storage. fileprivate let _hashTable = NSHashTable<UIScrollViewDelegate>.weakObjects() /// A closure to get the view for scroll view's zooming. var viewForZooming: ((UIScrollView) -> UIView?)? = nil /// A closure decides whether the scroll view should scroll to top. var scrollViewShouldScrollToTop: ((UIScrollView) -> Bool)? = nil } // Confirming to UIScrollViewDelegate. extension _ScrollViewDelegatesQueue: UIScrollViewDelegate { func scrollViewDidScroll(_ scrollView: UIScrollView) { _hashTable.allObjects.forEach{ $0.scrollViewDidScroll?(scrollView) } } func scrollViewDidZoom(_ scrollView: UIScrollView) { _hashTable.allObjects.forEach{ $0.scrollViewDidZoom?(scrollView) } } func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { _hashTable.allObjects.forEach{ $0.scrollViewWillBeginDragging?(scrollView) } } func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { _hashTable.allObjects.forEach{ $0.scrollViewWillEndDragging?(scrollView, withVelocity: velocity, targetContentOffset: targetContentOffset) } } func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { _hashTable.allObjects.forEach{ $0.scrollViewDidEndDragging?(scrollView, willDecelerate: decelerate) } } func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) { _hashTable.allObjects.forEach{ $0.scrollViewWillBeginDecelerating?(scrollView) } } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { _hashTable.allObjects.forEach{ $0.scrollViewDidEndDecelerating?(scrollView) } } func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) { _hashTable.allObjects.forEach{ $0.scrollViewDidEndScrollingAnimation?(scrollView) } } func scrollViewWillBeginZooming(_ scrollView: UIScrollView, with view: UIView?) { _hashTable.allObjects.forEach{ $0.scrollViewWillBeginZooming?(scrollView, with: view) } } func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) { _hashTable.allObjects.forEach{ $0.scrollViewDidEndZooming?(scrollView, with: view, atScale: scale) } } @available(iOS 11.0, *) func scrollViewDidChangeAdjustedContentInset(_ scrollView: UIScrollView) { _hashTable.allObjects.forEach{ $0.scrollViewDidChangeAdjustedContentInset?(scrollView) } } } extension _ScrollViewDelegatesQueue { func viewForZooming(in scrollView: UIScrollView) -> UIView? { return viewForZooming?(scrollView) } func scrollViewShouldScrollToTop(_ scrollView: UIScrollView) -> Bool { return scrollViewShouldScrollToTop?(scrollView) ?? false } } extension _ScrollViewDelegatesQueue { /// Add a new UIScrollViewDelegate object to the managed queue. /// - Parameter delegate: A UIScrollViewDelegate to be added and managed. func add(_ delegate: UIScrollViewDelegate?) { _hashTable.add(delegate) } /// Remove a existing UIScrollViewDelegate object from the managed queue. /// - Parameter delegate: The existing delegate the be removed. func remove(_ delegate: UIScrollViewDelegate?) { _hashTable.remove(delegate) } /// Remove all the managed UIScrollViewDelegate objects. func removeAll() { _hashTable.removeAllObjects() } } // MARK: - _ScrollViewDidEndScrollingAnimation. /// A type reresenting the a hook of UIScrollViewDelegate to set as the temporary /// delegate and to get the call back of the `setContentOffset(:animated:)` if the /// transition is animated. internal class _ScrollViewDidEndScrollingAnimation: NSObject { fileprivate var _completion: ((UIScrollView)->Void) /// Creates a _ScrollViewDidEndScrollingAnimation object with the call back closure. /// /// - Parameter completion: A closure will be triggered when the `scrollViewDidEndScrollingAnimation(:)` is called. /// - Returns: A _ScrollViewDidEndScrollingAnimation with the call back closure. internal init(_ completion: @escaping (UIScrollView)->Void) { _completion = completion super.init() } } // Confirming of UIScrollViewDelegate. extension _ScrollViewDidEndScrollingAnimation: UIScrollViewDelegate { func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) { _completion(scrollView) } } // MARK: - _ScrollViewDidScroll. /// A type reresenting the a hook of UIScrollViewDelegate to set as the temporary /// delegate and to get the call back when scroll view did scroll. internal class _ScrollViewDidScroll: NSObject { fileprivate var _didScroll: ((UIScrollView) -> Void) /// Creates a _ScrollViewDidScroll object with the call back closure. /// /// - Parameter completion: A closure will be triggered when the `scrollViewDidScroll(:)` is called. /// - Returns: A _ScrollViewDidScroll with the call back closure. internal init(_ didScroll: @escaping ((UIScrollView) -> Void)) { _didScroll = didScroll } } // Confirming of UIScrollViewDelegate. extension _ScrollViewDidScroll: UIScrollViewDelegate { func scrollViewDidScroll(_ scrollView: UIScrollView) { _didScroll(scrollView) } }
apache-2.0
6860408b09aaaf4c2c756d04a26f6950
42.343284
148
0.726067
5.428037
false
false
false
false
raulriera/UpvoteControl
UpvoteControl/UpvoteControl.swift
1
3990
// // UpvoteControl.swift // Raúl Riera // // Created by Raúl Riera on 26/04/2015. // Copyright (c) 2015 Raul Riera. All rights reserved. // import UIKit @IBDesignable open class UpvoteControl: UIControl { /** The current count value The default value for this property is 0. It will increment and decrement internally depending of the `selected` property */ @IBInspectable open var count: Int = 0 { didSet { updateCountLabel() } } @IBInspectable open var borderRadius: CGFloat = 0 { didSet { updateLayer() } } @IBInspectable open var shadow: Bool = false { didSet { updateLayer() } } @IBInspectable open var vertical: Bool = true { didSet { updateCountLabel() } } /** The font of the text Until Xcode supports @IBInspectable for UIFonts, this is the only way to change the font of the inner label */ @IBInspectable open var font: UIFont? { didSet { countLabel.font = font } } /** The color of text The default value for this property is a black color (set through the blackColor class method of UIColor). */ @IBInspectable open var textColor: UIColor = .black { didSet { countLabel.textColor = textColor } } private var countLabel: UILabel = UILabel() override open var isSelected: Bool { didSet { if isSelected { countLabel.textColor = tintColor } else { countLabel.textColor = textColor } } } // MARK: Overrides open override func endTracking(_ touch: UITouch?, with event: UIEvent?) { super.endTracking(touch, with:event) if let touch = touch , touch.tapCount > 0 { if isSelected { count -= 1 } else { count += 1 } isSelected = !isSelected super.sendActions(for: .valueChanged) } } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) configureView() } override init(frame: CGRect) { super.init(frame: frame) configureView() } // MARK: Private private func configureView() { // Allow this method to only run once guard countLabel.superview == .none else { return } updateLayer() countLabel = UILabel(frame: bounds) countLabel.font = UIFont(name: "AppleSDGothicNeo-Medium", size: 12) countLabel.numberOfLines = 0 countLabel.lineBreakMode = .byWordWrapping countLabel.textAlignment = .center countLabel.isUserInteractionEnabled = false countLabel.translatesAutoresizingMaskIntoConstraints = false addSubview(countLabel) let centerXConstraint = NSLayoutConstraint(item: countLabel, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0) let centerYConstraint = NSLayoutConstraint(item: countLabel, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0) NSLayoutConstraint.activate([centerXConstraint, centerYConstraint]) countLabel.setNeedsDisplay() } private func updateLayer() { layer.cornerRadius = borderRadius if shadow { layer.shadowColor = UIColor.darkGray.cgColor layer.shadowRadius = 0.5 layer.shadowOffset = CGSize(width: 0, height: 1) layer.shadowOpacity = 0.5 } } private func updateCountLabel() { if vertical { countLabel.text = "▲\n\(count)" } else { countLabel.text = "▲ \(count)" } } }
mit
4a4e45c52083770266065c55f24fad96
26.102041
171
0.573293
5.21466
false
false
false
false
muhlenXi/SwiftEx
projects/TodoList/TodoList/TodoModel.swift
1
572
// // TodoModel.swift // TodoList // // Created by 席银军 on 2017/8/20. // Copyright © 2017年 muhlenXi. All rights reserved. // import Foundation class TodoModel { var id: String var image: String var title: String var date: Date // MARK: - init method init(id: String, image: String, title: String, date: Date) { self.id = id self.image = image self.title = title self.date = date } init() { id = "" image = "" title = "" date = Date() } }
mit
6da64c0d9e63114ecbc806014b785ead
16.060606
64
0.515098
3.563291
false
false
false
false
laszlokorte/reform-swift
ReformCore/ReformCore/TranslateInstruction.swift
1
1807
// // TranslateInstruction.swift // ReformCore // // Created by Laszlo Korte on 14.08.15. // Copyright © 2015 Laszlo Korte. All rights reserved. // public struct TranslateInstruction : Instruction { public typealias DistanceType = RuntimeDistance & Labeled public var target : FormIdentifier? { return formId } public let formId : FormIdentifier public let distance : DistanceType public init(formId: FormIdentifier, distance: DistanceType) { self.formId = formId self.distance = distance } public func evaluate<T:Runtime>(_ runtime: T) { guard let form = runtime.get(formId) as? Translatable else { runtime.reportError(.unknownForm) return } guard let delta = distance.getDeltaFor(runtime) else { runtime.reportError(.invalidDistance) return } form.translator.translate(runtime, delta: delta) } public func getDescription(_ stringifier: Stringifier) -> String { let formName = stringifier.labelFor(formId) ?? "???" return "Move \(formName) \(distance.getDescription(stringifier))" } public func analyze<T:Analyzer>(_ analyzer: T) { } public var isDegenerated : Bool { return distance.isDegenerated } } extension TranslateInstruction : Mergeable { public func mergeWith(_ other: TranslateInstruction, force: Bool) -> TranslateInstruction? { guard formId == other.formId else { return nil } guard let newDistance = merge(distance: distance, distance: other.distance, force: force) else { return nil } return TranslateInstruction(formId: formId, distance: newDistance) } }
mit
75e9c6eb18a6363f46b91fcaf71e1b05
26.784615
130
0.6268
4.920981
false
false
false
false
iHunterX/SocketIODemo
DemoSocketIO/Utils/UIViewExtensions/UIViewBorder.swift
1
6453
// // UIViewExtensions.swift // DemoSocketIO // // Created by Loc.dx-KeizuDev on 10/28/16. // Copyright © 2016 Loc Dinh Xuan. All rights reserved. // import UIKit //class UIViewBorder: UIView { class BorderView: UIView { var lineColor = UIColor.clear @IBInspectable var lineBorderColor: UIColor = .clear { didSet{ updateColor() } } func updateColor(){ lineColor = lineBorderColor } @IBInspectable var leftBorderWidth: CGFloat { get { return 0.0 // Just to satisfy property } set { let line = UIView(frame: CGRect(x: 0.0, y: 0.0, width: newValue, height: bounds.height)) line.translatesAutoresizingMaskIntoConstraints = false line.backgroundColor = lineColor self.addSubview(line) let views = ["line": line] let metrics = ["lineWidth": newValue] addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "|[line(==lineWidth)]", options: [], metrics: metrics, views: views)) addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[line]|", options: [], metrics: nil, views: views)) } } @IBInspectable var topBorderWidth: CGFloat { get { return 0.0 // Just to satisfy property } set { let line = UIView(frame: CGRect(x: 0.0, y: 0.0, width: bounds.width, height: newValue)) line.translatesAutoresizingMaskIntoConstraints = false line.backgroundColor = lineColor self.addSubview(line) let views = ["line": line] let metrics = ["lineWidth": newValue] addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "|[line]|", options: [], metrics: nil, views: views)) addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[line(==lineWidth)]", options: [], metrics: metrics, views: views)) } } @IBInspectable var rightBorderWidth: CGFloat { get { return 0.0 // Just to satisfy property } set { let line = UIView(frame: CGRect(x: bounds.width, y: 0.0, width: newValue, height: bounds.height)) line.translatesAutoresizingMaskIntoConstraints = false line.backgroundColor = lineColor self.addSubview(line) let views = ["line": line] let metrics = ["lineWidth": newValue] addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "[line(==lineWidth)]|", options: [], metrics: metrics, views: views)) addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[line]|", options: [], metrics: nil, views: views)) } } @IBInspectable var bottomBorderWidth: CGFloat { get { return 0.0 // Just to satisfy property } set { let line = UIView(frame: CGRect(x: 0.0, y: bounds.height, width: bounds.width, height: newValue)) line.translatesAutoresizingMaskIntoConstraints = false line.backgroundColor = lineColor self.addSubview(line) let views = ["line": line] let metrics = ["lineWidth": newValue] addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "|[line]|", options: [], metrics: nil, views: views)) addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[line(==lineWidth)]|", options: [], metrics: metrics, views: views)) } } // @IBInspectable dynamic open var borderColor: UIColor = .lightGray // @IBInspectable dynamic open var thickness: CGFloat = 1 // // @IBInspectable dynamic open var topBorder: Bool = false { // didSet { // addBorder(edge: .top) // } // } // @IBInspectable dynamic open var bottomBorder: Bool = false { // didSet { // addBorder(edge: .bottom) // } // } // @IBInspectable dynamic open var rightBorder: Bool = false { // didSet { // addBorder(edge: .right) // } // } // @IBInspectable dynamic open var leftBorder: Bool = false { // didSet { // addBorder(edge: .left) // } // } // enum // //decalare a private topBorder // func addTopBorderWithColor(color: UIColor, thickness: CGFloat) { // let border = CALayer() // border.backgroundColor = color.cgColor // border.frame = CGRect(x:0,y: 0,width: self.frame.size.width,height: thickness) // self.layer.addSublayer(border) // } // func addTopBorderWithColor(color: UIColor, thickness: CGFloat) { // let border = CALayer() // border.backgroundColor = color.cgColor // border.frame = CGRect(x:0,y: 0,width: self.frame.size.width,height: thickness) // self.layer.addSublayer(border) // } // // func addRightBorderWithColor(color: UIColor, thickness: CGFloat) { // let border = CALayer() // border.backgroundColor = color.cgColor // border.frame = CGRect(x:self.frame.size.width - thickness,y: 0,width: width,height: self.frame.size.height) // self.layer.addSublayer(border) // } // // func addBottomBorderWithColor(color: UIColor, thickness: CGFloat) { // let border = CALayer() // border.backgroundColor = color.cgColor // border.frame = CGRect(x:0,y: self.frame.size.height - thickness,width: self.frame.size.width,height: thickness) // self.layer.addSublayer(border) // } // // func addLeftBorderWithColor(color: UIColor, thickness: CGFloat) { // let border = CALayer() // border.backgroundColor = color.cgColor // border.frame = CGRect(x:0,y: 0,width: thickness,height: self.frame.size.height) // self.layer.addSublayer(border) // } } extension UIViewController { func hideKeyboardWhenTappedAround() { let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard)) view.addGestureRecognizer(tap) } func dismissKeyboard() { view.endEditing(true) } }
gpl-3.0
157c7f6ae88e49082d9dafe1d3e8776d
39.325
147
0.588035
4.63839
false
false
false
false
ccrama/Slide-iOS
Slide for Reddit/Fonts/FontGenerator.swift
1
5057
// // FontGenerator.swift // Slide for Reddit // // Created by Carlos Crane on 1/28/17. // Copyright © 2017 Haptic Apps. All rights reserved. // import DTCoreText import UIKit class FontGenerator { public static func fontOfSize(size: CGFloat, submission: Bool) -> UIFont { let fontName = UserDefaults.standard.string(forKey: submission ? "postfont" : "commentfont") ?? ( submission ? "AvenirNext-DemiBold" : "AvenirNext-Medium") let adjustedSize = size + CGFloat(submission ? SettingValues.postFontOffset : SettingValues.commentFontOffset) return FontMapping.fromStoredName(name: fontName).font(ofSize: adjustedSize) ?? UIFont.systemFont(ofSize: adjustedSize) } public static func boldFontOfSize(size: CGFloat, submission: Bool) -> UIFont { let normalFont = fontOfSize(size: size, submission: submission) if normalFont.fontName == UIFont.systemFont(ofSize: 10).fontName { return UIFont.boldSystemFont(ofSize: size) } return normalFont.makeBold() } public static var postFont = Font.SYSTEM public static var commentFont = Font.SYSTEM public static func initialize() { if let name = UserDefaults.standard.string(forKey: "postfont") { if let t = Font(rawValue: name) { postFont = t } } if let name = UserDefaults.standard.string(forKey: "commentfont") { if let t = Font(rawValue: name) { commentFont = t } } } enum Font: String { case HELVETICA = "helvetica" case AVENIR = "avenirnext-regular" case AVENIR_MEDIUM = "avenirnext-medium" case ROBOTOCONDENSED_REGULAR = "rcreg" case ROBOTOCONDENSED_BOLD = "rcbold" case ROBOTO_LIGHT = "rlight" case ROBOTO_BOLD = "rbold" case ROBOTO_MEDIUM = "rmed" case SYSTEM = "system" case PAPYRUS = "papyrus" case CHALKBOARD = "chalkboard" public static var cases: [Font] { return [.HELVETICA, .AVENIR, .AVENIR_MEDIUM, .ROBOTOCONDENSED_REGULAR, .ROBOTOCONDENSED_BOLD, .ROBOTO_LIGHT, .ROBOTO_BOLD, .ROBOTO_MEDIUM, .SYSTEM] } public func bold() -> UIFont { switch self { case .HELVETICA: return UIFont.init(name: "HelveticaNeue-Bold", size: 16)! case .AVENIR: return UIFont.init(name: "AvenirNext-DemiBold", size: 16)! case .AVENIR_MEDIUM: return UIFont.init(name: "AvenirNext-Bold", size: 16)! case .ROBOTOCONDENSED_REGULAR: return UIFont.init(name: "RobotoCondensed-Bold", size: 16)! case .ROBOTOCONDENSED_BOLD: return UIFont.init(name: "RobotoCondensed-Bold", size: 16)! case .ROBOTO_LIGHT: return UIFont.init(name: "Roboto-Medium", size: 16)! case .ROBOTO_BOLD: return UIFont.init(name: "Roboto-Bold", size: 16)! case .ROBOTO_MEDIUM: return UIFont.init(name: "Roboto-Bold", size: 16)! case .PAPYRUS: return UIFont.init(name: "Papyrus", size: 16)! case .CHALKBOARD: return UIFont.init(name: "ChalkboardSE-Bold", size: 16)! case .SYSTEM: return UIFont.boldSystemFont(ofSize: 16) } } public var font: UIFont { switch self { case .HELVETICA: return UIFont.init(name: "HelveticaNeue", size: 16)! case .AVENIR: return UIFont.init(name: "AvenirNext-Regular", size: 16)! case .AVENIR_MEDIUM: return UIFont.init(name: "AvenirNext-DemiBold", size: 16)! case .ROBOTOCONDENSED_REGULAR: return UIFont.init(name: "RobotoCondensed-Regular", size: 16)! case .ROBOTOCONDENSED_BOLD: return UIFont.init(name: "RobotoCondensed-Bold", size: 16)! case .ROBOTO_LIGHT: return UIFont.init(name: "Roboto-Light", size: 16)! case .ROBOTO_BOLD: return UIFont.init(name: "Roboto-Bold", size: 16)! case .ROBOTO_MEDIUM: return UIFont.init(name: "Roboto-Medium", size: 16)! case .PAPYRUS: return UIFont.init(name: "Papyrus", size: 16)! case .CHALKBOARD: return UIFont.init(name: "ChalkboardSE-Regular", size: 16)! case .SYSTEM: return UIFont.systemFont(ofSize: 16) } } } } extension UIFont { func withTraits(traits: UIFontDescriptor.SymbolicTraits...) -> UIFont { let descriptor = self.fontDescriptor .withSymbolicTraits(UIFontDescriptor.SymbolicTraits(traits)) ?? self.fontDescriptor return UIFont(descriptor: descriptor, size: 0) } func makeBold() -> UIFont { return withTraits(traits: .traitBold) } }
apache-2.0
91556b7d668a4b954d48efa578ab038d
37.892308
163
0.580103
4.47038
false
false
false
false
qingtianbuyu/Mono
Moon/Classes/Explore/Model/MNTea.swift
1
1020
// // MNTea.swift // Moon // // Created by YKing on 16/5/25. // Copyright © 2016年 YKing. All rights reserved. // import UIKit class MNTea: NSObject { var start: Int = 0 var entity_list: [MNExploreEntity]? var kind: Int = 2 var share_text: String? var push_msg: String? var title: String? var sub_title: String? var bg_img_url: String? var release_date: Date? var intro: String? var read_time: String? var share_time: String? var share_image: String? var id: Int = 0 init(dict: [String: AnyObject]) { super.init() setValuesForKeys(dict) } override func setValue(_ value: Any?, forKey key: String) { if key == "entity_list" { guard let array = (value as?[[String : AnyObject]]) else { return } var tmpArray = [MNExploreEntity]() for dict in array { tmpArray.append(MNExploreEntity(dict:dict)) } entity_list = tmpArray return } super.setValue(value, forKey: key) } }
mit
54a9bf52e275a79d1b21b06efc19ef4a
18.188679
66
0.600787
3.459184
false
false
false
false
LondonSwift/OnTrack
OnTrack/OnTrack/AppDelegate.swift
1
3392
// // AppDelegate.swift // OnTrack // // Created by Daren David Taylor on 01/09/2015. // Copyright (c) 2015 LondonSwift. All rights reserved. // import UIKit import LSRepeater import Fabric import Crashlytics @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func setupDefaults() { let defaults = NSUserDefaults.standardUserDefaults() if defaults.objectForKey("file") == nil { defaults.setObject("PennineBridleway.gpx", forKey:"file"); defaults.synchronize(); } if defaults.objectForKey("OffTrackAudioOn") == nil { defaults.setBool(true, forKey:"OffTrackAudioOn"); defaults.synchronize(); } if defaults.objectForKey("WeatherAudioOn") == nil { defaults.setBool(true, forKey:"WeatherAudioOn"); defaults.synchronize(); } if defaults.objectForKey("RSSAudioOn") == nil { defaults.setBool(true, forKey:"RSSAudioOn"); defaults.synchronize(); } if defaults.objectForKey("TimeAudioOn") == nil { defaults.setBool(true, forKey:"TimeAudioOn"); defaults.synchronize(); } if defaults.objectForKey("OffTrackDistance") == nil { defaults.setDouble(10.0, forKey:"OffTrackDistance"); defaults.synchronize(); } if defaults.objectForKey("hasCopiedFiles") == nil { // add this back in when we go live // defaults.setBool(true, forKey:"hasCopiedFiles"); // defaults.synchronize(); self.copyFiles() } } func copyFiles() { let fileManager = NSFileManager.defaultManager() do { for path in ["PennineBridleway"] { if let fullSourcePath = NSBundle.mainBundle().pathForResource(path, ofType:"gpx") { if fileManager.fileExistsAtPath(fullSourcePath) { try fileManager.copyItemAtPath(fullSourcePath, toPath: NSURL.applicationDocumentsDirectory().URLByAppendingPathComponent(path+".gpx").path!) } } } } catch { print("error copying") } } func application(app: UIApplication, openURL url: NSURL, options: [String : AnyObject]) -> Bool { self.setupDefaults() let data = NSData(contentsOfURL: url) if let path = url.lastPathComponent { data?.writeToURL(NSURL.applicationDocumentsDirectory().URLByAppendingPathComponent(path), atomically: true) let defaults = NSUserDefaults.standardUserDefaults() defaults.setObject(path, forKey:"file"); defaults.synchronize(); let vc = self.window?.rootViewController as! MapViewController vc.loadRoute(path) } return true } func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { Fabric.with([Crashlytics.self()]) self.setupDefaults() return true } }
gpl-3.0
1069e57115516a0d30da54830b422d4a
27.991453
160
0.561321
5.615894
false
false
false
false
bhajian/raspi-remote
Carthage/Checkouts/ios-sdk/Source/RelationshipExtractionV1Beta/Models/Sentence.swift
1
3217
/** * 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. **/ import Foundation import Freddy /** Contains the analysis of an input sentence. Produced by the Relationship Extraction service. */ public struct Sentence: JSONDecodable { /// The numeric identifier of the sentence. public let sentenceID: Int /// The index of the first token in the sentence. public let begin: Int /// The index of the last token in the sentence. public let end: Int /// The complete text of the analyzed sentence. public let text: String /// The serialized constituent parse tree for the sentence. See the following link for more /// information: http://en.wikipedia.org/wiki/Parse_tree public let parse: String /// The dependency parse tree for the sentence. See the following link for more information: /// http://www.cis.upenn.edu/~treebank/ public let dependencyParse: String /// The universal Stanford dependency parse tree for the sentence. See the following link for /// more information: http://nlp.stanford.edu/software/stanford-dependencies.shtml public let usdDependencyParse: String /// A list of Token objects for each token in the sentence. Tokens are the individual words and /// punctuation in the sentence. public let tokens: [Token] /// Used internally to initialize a `Sentence` model from JSON. public init(json: JSON) throws { sentenceID = try json.int("sid") begin = try json.int("begin") end = try json.int("end") text = try json.string("text") parse = try json.string("parse", "text") dependencyParse = try json.string("dependency_parse") usdDependencyParse = try json.string("usd_dependency_parse") tokens = try json.arrayOf("tokens", "token", type: Token.self) } } /** A Token object provides more information about a specific token (word or punctuation) in the sentence. */ public struct Token: JSONDecodable { /// The beginning character offset of the token among all tokens of the input text. public let begin: Int /// The ending character offset of the token among all tokens of the input text. public let end: Int /// The token to which this object pertains. public let text: String /// The numeric identifier of the token. public let tokenID: Int /// Used internally to initialize a `Token` model from JSON. public init(json: JSON) throws { begin = try json.int("begin") end = try json.int("end") text = try json.string("text") tokenID = try json.int("tid") } }
mit
4a9eda0c1f921a14f499caa6d280d01a
35.146067
99
0.679515
4.511921
false
false
false
false
quickthyme/PUTcat
PUTcat/Application/Data/Parser/DataStore/PCParserDataStoreLocal.swift
1
1800
import Foundation class PCParserDataStoreLocal : PCParserDataStore { private static let StorageFile_Pfx = "PCParserList_" private static let StorageFile_Sfx = ".json" private static let StorageKey = "parsers" private static func StorageFileName(_ parentID: String) -> String { return "\(StorageFile_Pfx)\(parentID)\(StorageFile_Sfx)" } static func fetch(transactionID: String, asCopy: Bool) -> Composed.Action<Any, PCList<PCParser>> { return Composed.Action<Any, PCList<PCParser>> { _, completion in guard let path = DocumentsDirectory.existingFilePathWithName(StorageFileName(transactionID)), let dict = xJSON.parse(file: path) as? [String:Any], let items = dict[StorageKey] as? [[String:Any]] else { return completion(.success(PCList<PCParser>())) } let list = PCList<PCParser>(fromLocal: items) completion( .success( (asCopy) ? list.copy() : list ) ) } } static func store(transactionID: String) -> Composed.Action<PCList<PCParser>, PCList<PCParser>> { return Composed.Action<PCList<PCParser>, PCList<PCParser>> { list, completion in guard let list = list else { return completion(.failure(PCError(code: 404, text: "No list to store \(StorageKey)"))) } let path = DocumentsDirectory.filePathWithName(StorageFileName(transactionID)) let dict = [ StorageKey : list.toLocal() ] if xJSON.write(dict, toFile: path) { completion(.success(list)) } else { completion(.failure(PCError(code: 404, text: "Error writing \(StorageKey)"))) } } } }
apache-2.0
0e0d9ab93aa45576aa01804706288f3f
39.909091
103
0.598889
4.675325
false
false
false
false
luoziyong/firefox-ios
Client/Frontend/Home/HistoryPanel.swift
1
25397
/* 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 UIKit import Shared import Storage import XCGLogger import Deferred private let log = Logger.browserLogger private typealias SectionNumber = Int private typealias CategoryNumber = Int private typealias CategorySpec = (section: SectionNumber?, rows: Int, offset: Int) private struct HistoryPanelUX { static let WelcomeScreenItemTextColor = UIColor.gray static let WelcomeScreenItemWidth = 170 static let IconSize = 23 static let IconBorderColor = UIColor(white: 0, alpha: 0.1) static let IconBorderWidth: CGFloat = 0.5 } private func getDate(_ dayOffset: Int) -> Date { let calendar = Calendar(identifier: Calendar.Identifier.gregorian) let nowComponents = (calendar as NSCalendar).components([.year, .month, .day], from: Date()) let today = calendar.date(from: nowComponents)! return (calendar as NSCalendar).date(byAdding: NSCalendar.Unit.day, value: dayOffset, to: today, options: [])! } class HistoryPanel: SiteTableViewController, HomePanel { weak var homePanelDelegate: HomePanelDelegate? private var currentSyncedDevicesCount: Int? var events = [NotificationFirefoxAccountChanged, NotificationPrivateDataClearedHistory, NotificationDynamicFontChanged] var refreshControl: UIRefreshControl? fileprivate lazy var longPressRecognizer: UILongPressGestureRecognizer = { return UILongPressGestureRecognizer(target: self, action: #selector(HistoryPanel.longPress(_:))) }() private lazy var emptyStateOverlayView: UIView = self.createEmptyStateOverlayView() private let QueryLimit = 100 private let NumSections = 5 private let Today = getDate(0) private let Yesterday = getDate(-1) private let ThisWeek = getDate(-7) private var categories: [CategorySpec] = [CategorySpec]() // Category number (index) -> (UI section, row count, cursor offset). private var sectionLookup = [SectionNumber: CategoryNumber]() // Reverse lookup from UI section to data category. var syncDetailText = "" var hasRecentlyClosed: Bool { return self.profile.recentlyClosedTabs.tabs.count > 0 } // MARK: - Lifecycle init() { super.init(nibName: nil, bundle: nil) events.forEach { NotificationCenter.default.addObserver(self, selector: #selector(HistoryPanel.notificationReceived(_:)), name: $0, object: nil) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { events.forEach { NotificationCenter.default.removeObserver(self, name: $0, object: nil) } } override func viewDidLoad() { super.viewDidLoad() tableView.addGestureRecognizer(longPressRecognizer) tableView.accessibilityIdentifier = "History List" updateSyncedDevicesCount().uponQueue(DispatchQueue.main) { result in self.updateNumberOfSyncedDevices(self.currentSyncedDevicesCount) } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Add a refresh control if the user is logged in and the control was not added before. If the user is not // logged in, remove any existing control but only when it is not currently refreshing. Otherwise, wait for // the refresh to finish before removing the control. if profile.hasSyncableAccount() && refreshControl == nil { addRefreshControl() } else if refreshControl?.isRefreshing == false { removeRefreshControl() } updateSyncedDevicesCount().uponQueue(DispatchQueue.main) { result in self.updateNumberOfSyncedDevices(self.currentSyncedDevicesCount) } } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { coordinator.animate(alongsideTransition: { context in self.presentedViewController?.dismiss(animated: true, completion: nil) }, completion: nil) } @objc fileprivate func longPress(_ longPressGestureRecognizer: UILongPressGestureRecognizer) { guard longPressGestureRecognizer.state == UIGestureRecognizerState.began else { return } let touchPoint = longPressGestureRecognizer.location(in: tableView) guard let indexPath = tableView.indexPathForRow(at: touchPoint) else { return } if indexPath.section != 0 { presentContextMenu(for: indexPath) } } // MARK: - History Data Store func updateNumberOfSyncedDevices(_ count: Int?) { if let count = count, count > 0 { syncDetailText = String.localizedStringWithFormat(Strings.SyncedTabsTableViewCellDescription, count) } else { syncDetailText = "" } self.tableView.reloadRows(at: [IndexPath(row: 1, section: 0)], with: .automatic) } func updateSyncedDevicesCount() -> Success { return chainDeferred(self.profile.getCachedClientsAndTabs()) { tabsAndClients in self.currentSyncedDevicesCount = tabsAndClients.count return succeed() } } func notificationReceived(_ notification: Notification) { switch notification.name { case NotificationFirefoxAccountChanged, NotificationPrivateDataClearedHistory: if self.profile.hasSyncableAccount() { resyncHistory() } break case NotificationDynamicFontChanged: if emptyStateOverlayView.superview != nil { emptyStateOverlayView.removeFromSuperview() } emptyStateOverlayView = createEmptyStateOverlayView() resyncHistory() break default: // no need to do anything at all log.warning("Received unexpected notification \(notification.name)") break } } private func fetchData() -> Deferred<Maybe<Cursor<Site>>> { return profile.history.getSitesByLastVisit(QueryLimit) } private func setData(_ data: Cursor<Site>) { self.data = data self.computeSectionOffsets() } func resyncHistory() { profile.syncManager.syncHistory().uponQueue(DispatchQueue.main) { result in if result.isSuccess { self.reloadData() } else { self.endRefreshing() } self.updateSyncedDevicesCount().uponQueue(DispatchQueue.main) { result in self.updateNumberOfSyncedDevices(self.currentSyncedDevicesCount) } } } // MARK: - Refreshing TableView func addRefreshControl() { let refresh = UIRefreshControl() refresh.addTarget(self, action: #selector(HistoryPanel.refresh), for: UIControlEvents.valueChanged) self.refreshControl = refresh self.tableView.addSubview(refresh) } func removeRefreshControl() { self.refreshControl?.removeFromSuperview() self.refreshControl = nil } func endRefreshing() { // Always end refreshing, even if we failed! self.refreshControl?.endRefreshing() // Remove the refresh control if the user has logged out in the meantime if !self.profile.hasSyncableAccount() { self.removeRefreshControl() } } @objc func refresh() { self.refreshControl?.beginRefreshing() resyncHistory() } override func reloadData() { self.fetchData().uponQueue(DispatchQueue.main) { result in if let data = result.successValue { self.setData(data) self.tableView.reloadData() self.updateEmptyPanelState() } self.endRefreshing() } } // MARK: - Empty State private func updateEmptyPanelState() { if data.count == 0 { if self.emptyStateOverlayView.superview == nil { self.tableView.addSubview(self.emptyStateOverlayView) self.emptyStateOverlayView.snp.makeConstraints { make -> Void in make.left.right.bottom.equalTo(self.view) make.top.equalTo(self.view).offset(100) } } } else { self.tableView.alwaysBounceVertical = true self.emptyStateOverlayView.removeFromSuperview() } } private func createEmptyStateOverlayView() -> UIView { let overlayView = UIView() overlayView.backgroundColor = UIColor.white let welcomeLabel = UILabel() overlayView.addSubview(welcomeLabel) welcomeLabel.text = Strings.HistoryPanelEmptyStateTitle welcomeLabel.textAlignment = NSTextAlignment.center welcomeLabel.font = DynamicFontHelper.defaultHelper.DeviceFontLight welcomeLabel.textColor = HistoryPanelUX.WelcomeScreenItemTextColor welcomeLabel.numberOfLines = 0 welcomeLabel.adjustsFontSizeToFitWidth = true welcomeLabel.snp.makeConstraints { make in make.centerX.equalTo(overlayView) // Sets proper top constraint for iPhone 6 in portait and for iPad. make.centerY.equalTo(overlayView).offset(HomePanelUX.EmptyTabContentOffset).priority(100) // Sets proper top constraint for iPhone 4, 5 in portrait. make.top.greaterThanOrEqualTo(overlayView).offset(50) make.width.equalTo(HistoryPanelUX.WelcomeScreenItemWidth) } return overlayView } // MARK: - TableView Row Helpers func computeSectionOffsets() { var counts = [Int](repeating: 0, count: NumSections) // Loop over all the data. Record the start of each "section" of our list. for i in 0..<data.count { if let site = data[i] { counts[categoryForDate(site.latestVisit!.date) + 1] += 1 } } var section = 0 var offset = 0 self.categories = [CategorySpec]() for i in 0..<NumSections { let count = counts[i] if i == 0 { sectionLookup[section] = i section += 1 } if count > 0 { log.debug("Category \(i) has \(count) rows, and thus is section \(section).") self.categories.append((section: section, rows: count, offset: offset)) sectionLookup[section] = i offset += count section += 1 } else { log.debug("Category \(i) has 0 rows, and thus has no section.") self.categories.append((section: nil, rows: 0, offset: offset)) } } } fileprivate func siteForIndexPath(_ indexPath: IndexPath) -> Site? { let offset = self.categories[sectionLookup[indexPath.section]!].offset return data[indexPath.row + offset] } private func categoryForDate(_ date: MicrosecondTimestamp) -> Int { let date = Double(date) if date > (1000000 * Today.timeIntervalSince1970) { return 0 } if date > (1000000 * Yesterday.timeIntervalSince1970) { return 1 } if date > (1000000 * ThisWeek.timeIntervalSince1970) { return 2 } return 3 } private func isInCategory(_ date: MicrosecondTimestamp, category: Int) -> Bool { return self.categoryForDate(date) == category } // UI sections disappear as categories empty. We need to translate back and forth. private func uiSectionToCategory(_ section: SectionNumber) -> CategoryNumber { for i in 0..<self.categories.count { if let s = self.categories[i].section, s == section { return i } } return 0 } private func categoryToUISection(_ category: CategoryNumber) -> SectionNumber? { return self.categories[category].section } // MARK: - TableView Delegate / DataSource override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = super.tableView(tableView, cellForRowAt: indexPath) cell.accessoryType = UITableViewCellAccessoryType.none if indexPath.section == 0 { cell.imageView!.layer.borderWidth = 0 return indexPath.row == 0 ? configureRecentlyClosed(cell, for: indexPath) : configureSyncedTabs(cell, for: indexPath) } else { return configureSite(cell, for: indexPath) } } func configureRecentlyClosed(_ cell: UITableViewCell, for indexPath: IndexPath) -> UITableViewCell { cell.accessoryType = UITableViewCellAccessoryType.disclosureIndicator cell.textLabel!.text = Strings.RecentlyClosedTabsButtonTitle cell.detailTextLabel!.text = "" cell.imageView!.image = UIImage(named: "recently_closed") cell.imageView?.backgroundColor = UIColor.white if !hasRecentlyClosed { cell.textLabel?.alpha = 0.5 cell.imageView!.alpha = 0.5 cell.selectionStyle = .none } cell.accessibilityIdentifier = "HistoryPanel.recentlyClosedCell" return cell } func configureSyncedTabs(_ cell: UITableViewCell, for indexPath: IndexPath) -> UITableViewCell { cell.accessoryType = UITableViewCellAccessoryType.disclosureIndicator cell.textLabel!.text = Strings.SyncedTabsTableViewCellTitle cell.detailTextLabel!.text = self.syncDetailText cell.imageView!.image = UIImage(named: "synced_devices") cell.imageView?.backgroundColor = UIColor.white cell.accessibilityIdentifier = "HistoryPanel.syncedDevicesCell" return cell } func configureSite(_ cell: UITableViewCell, for indexPath: IndexPath) -> UITableViewCell { if let site = siteForIndexPath(indexPath), let cell = cell as? TwoLineTableViewCell { cell.setLines(site.title, detailText: site.url) cell.imageView!.layer.borderColor = HistoryPanelUX.IconBorderColor.cgColor cell.imageView!.layer.borderWidth = HistoryPanelUX.IconBorderWidth cell.imageView?.setIcon(site.icon, forURL: site.tileURL, completed: { (color, url) in if site.tileURL == url { cell.imageView?.image = cell.imageView?.image?.createScaled(CGSize(width: HistoryPanelUX.IconSize, height: HistoryPanelUX.IconSize)) cell.imageView?.backgroundColor = color cell.imageView?.contentMode = .center } }) } return cell } func numberOfSectionsInTableView(_ tableView: UITableView) -> Int { var count = 1 for category in self.categories where category.rows > 0 { count += 1 } return count } func tableView(_ tableView: UITableView, didSelectRowAtIndexPath indexPath: IndexPath) { if indexPath.section == 0 { self.tableView.deselectRow(at: indexPath, animated: true) return indexPath.row == 0 ? self.showRecentlyClosed() : self.showSyncedTabs() } if let site = self.siteForIndexPath(indexPath), let url = URL(string: site.url) { let visitType = VisitType.typed // Means History, too. if let homePanelDelegate = homePanelDelegate { homePanelDelegate.homePanel(self, didSelectURL: url, visitType: visitType) } return } log.warning("No site or no URL when selecting row.") } func pinTopSite(_ site: Site) { _ = profile.history.addPinnedTopSite(site).value } func showSyncedTabs() { let nextController = RemoteTabsPanel() nextController.homePanelDelegate = self.homePanelDelegate nextController.profile = self.profile self.refreshControl?.endRefreshing() self.navigationController?.pushViewController(nextController, animated: true) } func showRecentlyClosed() { guard hasRecentlyClosed else { return } let nextController = RecentlyClosedTabsPanel() nextController.homePanelDelegate = self.homePanelDelegate nextController.profile = self.profile self.refreshControl?.endRefreshing() self.navigationController?.pushViewController(nextController, animated: true) } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { var title = String() switch sectionLookup[section]! { case 0: return nil case 1: title = NSLocalizedString("Today", comment: "History tableview section header") case 2: title = NSLocalizedString("Yesterday", comment: "History tableview section header") case 3: title = NSLocalizedString("Last week", comment: "History tableview section header") case 4: title = NSLocalizedString("Last month", comment: "History tableview section header") default: assertionFailure("Invalid history section \(section)") } return title } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { if section == 0 { return nil } return super.tableView(tableView, viewForHeaderInSection: section) } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if section == 0 { return 0 } return super.tableView(tableView, heightForHeaderInSection: section) } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 0 { return 2 } return self.categories[uiSectionToCategory(section)].rows } func tableView(_ tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: IndexPath) { // Intentionally blank. Required to use UITableViewRowActions } fileprivate func removeHistoryForURLAtIndexPath(indexPath: IndexPath) { if let site = self.siteForIndexPath(indexPath) { // Why the dispatches? Because we call success and failure on the DB // queue, and so calling anything else that calls through to the DB will // deadlock. This problem will go away when the history API switches to // Deferred instead of using callbacks. self.profile.history.removeHistoryForURL(site.url) .upon { res in self.fetchData().uponQueue(DispatchQueue.main) { result in // If a section will be empty after removal, we must remove the section itself. if let data = result.successValue { let oldCategories = self.categories self.data = data self.computeSectionOffsets() let sectionsToDelete = NSMutableIndexSet() var rowsToDelete = [IndexPath]() let sectionsToAdd = NSMutableIndexSet() var rowsToAdd = [IndexPath]() for (index, category) in self.categories.enumerated() { let oldCategory = oldCategories[index] // don't bother if we're not displaying this category if oldCategory.section == nil && category.section == nil { continue } // 1. add a new section if the section didn't previously exist if oldCategory.section == nil && category.section != oldCategory.section { log.debug("adding section \(category.section ?? 0)") sectionsToAdd.add(category.section!) } // 2. add a new row if there are more rows now than there were before if oldCategory.rows < category.rows { log.debug("adding row to \(category.section ?? 0) at \(category.rows-1)") rowsToAdd.append(IndexPath(row: category.rows-1, section: category.section!)) } // if we're dealing with the section where the row was deleted: // 1. if the category no longer has a section, then we need to delete the entire section // 2. delete a row if the number of rows has been reduced // 3. delete the selected row and add a new one on the bottom of the section if the number of rows has stayed the same if oldCategory.section == indexPath.section { if category.section == nil { log.debug("deleting section \(indexPath.section)") sectionsToDelete.add(indexPath.section) } else if oldCategory.section == category.section { if oldCategory.rows > category.rows { log.debug("deleting row from \(category.section ?? 0) at \(indexPath.row)") rowsToDelete.append(indexPath) } else if category.rows == oldCategory.rows { log.debug("in section \(category.section ?? 0), removing row at \(indexPath.row) and inserting row at \(category.rows-1)") rowsToDelete.append(indexPath) rowsToAdd.append(IndexPath(row: category.rows-1, section: indexPath.section)) } } } } self.tableView.beginUpdates() if sectionsToAdd.count > 0 { self.tableView.insertSections(sectionsToAdd as IndexSet, with: UITableViewRowAnimation.left) } if sectionsToDelete.count > 0 { self.tableView.deleteSections(sectionsToDelete as IndexSet, with: UITableViewRowAnimation.right) } if !rowsToDelete.isEmpty { self.tableView.deleteRows(at: rowsToDelete, with: UITableViewRowAnimation.right) } if !rowsToAdd.isEmpty { self.tableView.insertRows(at: rowsToAdd, with: UITableViewRowAnimation.right) } self.tableView.endUpdates() self.updateEmptyPanelState() } } } } } func tableView(_ tableView: UITableView, editActionsForRowAtIndexPath indexPath: IndexPath) -> [AnyObject]? { if indexPath.section == 0 { return [] } let title = NSLocalizedString("Delete", tableName: "HistoryPanel", comment: "Action button for deleting history entries in the history panel.") let delete = UITableViewRowAction(style: UITableViewRowActionStyle.default, title: title, handler: { (action, indexPath) in self.removeHistoryForURLAtIndexPath(indexPath: indexPath) }) return [delete] } } extension HistoryPanel: HomePanelContextMenu { func presentContextMenu(for site: Site, with indexPath: IndexPath, completionHandler: @escaping () -> ActionOverlayTableViewController?) { guard let contextMenu = completionHandler() else { return } self.present(contextMenu, animated: true, completion: nil) } func getSiteDetails(for indexPath: IndexPath) -> Site? { return siteForIndexPath(indexPath) } func getContextMenuActions(for site: Site, with indexPath: IndexPath) -> [ActionOverlayTableViewAction]? { guard var actions = getDefaultContextMenuActions(for: site, homePanelDelegate: homePanelDelegate) else { return nil } let removeAction = ActionOverlayTableViewAction(title: Strings.DeleteFromHistoryContextMenuTitle, iconString: "action_delete", handler: { action in self.removeHistoryForURLAtIndexPath(indexPath: indexPath) }) let pinTopSite = ActionOverlayTableViewAction(title: Strings.PinTopsiteActionTitle, iconString: "action_pin", handler: { action in self.pinTopSite(site) }) if FeatureSwitches.activityStream.isMember(profile.prefs) { actions.append(pinTopSite) } actions.append(removeAction) return actions } }
mpl-2.0
dbc600951384e2fec837768fc7d3c8f8
42.118846
166
0.61271
5.716183
false
false
false
false
eduresende/ios-nd-swift-syntax-swift-3
Lesson6/L6_Classes_Properties_Methods.playground/Sources/SupportCode.swift
1
887
// // This file (and all other Swift source files in the Sources directory of this playground) will be precompiled into a framework which is automatically made available to Classes_Properties_Methods.playground. // import UIKit class Movie { let title: String let director: String let releaseYear: Int init(title: String, director:String, releaseYear: Int) { self.title = title self.director = director self.releaseYear = releaseYear } } class MovieArchive { var movies:[Movie] func filterByYear(_ year:Int, movies: [Movie]) -> [Movie] { var filteredArray = [Movie]() for movie in movies { if movie.releaseYear == year { filteredArray.append(movie) } } return filteredArray } init(movies:[Movie]) { self.movies = movies } }
mit
f963d92e52e5095705dbe97686d37c9a
23.638889
208
0.616685
4.595855
false
false
false
false
niunaruto/DeDaoAppSwift
testSwift/Pods/RxSwift/RxSwift/Observables/GroupBy.swift
20
4742
// // GroupBy.swift // RxSwift // // Created by Tomi Koskinen on 01/12/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // extension ObservableType { /* Groups the elements of an observable sequence according to a specified key selector function. - seealso: [groupBy operator on reactivex.io](http://reactivex.io/documentation/operators/groupby.html) - parameter keySelector: A function to extract the key for each element. - returns: A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. */ public func groupBy<Key: Hashable>(keySelector: @escaping (Element) throws -> Key) -> Observable<GroupedObservable<Key, Element>> { return GroupBy(source: self.asObservable(), selector: keySelector) } } final private class GroupedObservableImpl<Element>: Observable<Element> { private var _subject: PublishSubject<Element> private var _refCount: RefCountDisposable init(subject: PublishSubject<Element>, refCount: RefCountDisposable) { self._subject = subject self._refCount = refCount } override public func subscribe<Observer: ObserverType>(_ observer: Observer) -> Disposable where Observer.Element == Element { let release = self._refCount.retain() let subscription = self._subject.subscribe(observer) return Disposables.create(release, subscription) } } final private class GroupBySink<Key: Hashable, Element, Observer: ObserverType> : Sink<Observer> , ObserverType where Observer.Element == GroupedObservable<Key, Element> { typealias ResultType = Observer.Element typealias Parent = GroupBy<Key, Element> private let _parent: Parent private let _subscription = SingleAssignmentDisposable() private var _refCountDisposable: RefCountDisposable! private var _groupedSubjectTable: [Key: PublishSubject<Element>] init(parent: Parent, observer: Observer, cancel: Cancelable) { self._parent = parent self._groupedSubjectTable = [Key: PublishSubject<Element>]() super.init(observer: observer, cancel: cancel) } func run() -> Disposable { self._refCountDisposable = RefCountDisposable(disposable: self._subscription) self._subscription.setDisposable(self._parent._source.subscribe(self)) return self._refCountDisposable } private func onGroupEvent(key: Key, value: Element) { if let writer = self._groupedSubjectTable[key] { writer.on(.next(value)) } else { let writer = PublishSubject<Element>() self._groupedSubjectTable[key] = writer let group = GroupedObservable( key: key, source: GroupedObservableImpl(subject: writer, refCount: _refCountDisposable) ) self.forwardOn(.next(group)) writer.on(.next(value)) } } final func on(_ event: Event<Element>) { switch event { case let .next(value): do { let groupKey = try self._parent._selector(value) self.onGroupEvent(key: groupKey, value: value) } catch let e { self.error(e) return } case let .error(e): self.error(e) case .completed: self.forwardOnGroups(event: .completed) self.forwardOn(.completed) self._subscription.dispose() self.dispose() } } final func error(_ error: Swift.Error) { self.forwardOnGroups(event: .error(error)) self.forwardOn(.error(error)) self._subscription.dispose() self.dispose() } final func forwardOnGroups(event: Event<Element>) { for writer in self._groupedSubjectTable.values { writer.on(event) } } } final private class GroupBy<Key: Hashable, Element>: Producer<GroupedObservable<Key,Element>> { typealias KeySelector = (Element) throws -> Key fileprivate let _source: Observable<Element> fileprivate let _selector: KeySelector init(source: Observable<Element>, selector: @escaping KeySelector) { self._source = source self._selector = selector } override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == GroupedObservable<Key,Element> { let sink = GroupBySink(parent: self, observer: observer, cancel: cancel) return (sink: sink, subscription: sink.run()) } }
mit
88e987468f766ce5c02aafec3c22bba3
34.646617
194
0.64248
4.882595
false
false
false
false
mrdepth/EVEUniverse
Legacy/Neocom/Neocom/NCTableViewBackgroundLabel.swift
2
940
// // File.swift // Neocom // // Created by Artem Shimanski on 08.12.16. // Copyright © 2016 Artem Shimanski. All rights reserved. // import UIKit class NCTableViewBackgroundLabel: NCLabel { override init(frame: CGRect) { super.init(frame: frame) numberOfLines = 0 pointSize = 15 font = UIFont.systemFont(ofSize: fontSize(contentSizeCategory: UIApplication.shared.preferredContentSizeCategory)) textColor = UIColor.lightText } convenience init(text: String) { self.init(frame: CGRect.zero) let paragraph = NSParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle paragraph.firstLineHeadIndent = 20 paragraph.headIndent = 20 paragraph.tailIndent = -20 paragraph.alignment = NSTextAlignment.center attributedText = NSAttributedString(string: text, attributes: [NSAttributedStringKey.paragraphStyle: paragraph]) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } }
lgpl-2.1
080efcf27c4e06cfd9861cde1ab063e3
26.617647
116
0.757188
4.030043
false
false
false
false
niunaruto/DeDaoAppSwift
testSwift/Pods/RxCocoa/RxCocoa/iOS/UIScrollView+Rx.swift
33
6592
// // UIScrollView+Rx.swift // RxCocoa // // Created by Krunoslav Zaher on 4/3/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if os(iOS) || os(tvOS) import RxSwift import UIKit extension Reactive where Base: UIScrollView { public typealias EndZoomEvent = (view: UIView?, scale: CGFloat) public typealias WillEndDraggingEvent = (velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) /// Reactive wrapper for `delegate`. /// /// For more information take a look at `DelegateProxyType` protocol documentation. public var delegate: DelegateProxy<UIScrollView, UIScrollViewDelegate> { return RxScrollViewDelegateProxy.proxy(for: base) } /// Reactive wrapper for `contentOffset`. public var contentOffset: ControlProperty<CGPoint> { let proxy = RxScrollViewDelegateProxy.proxy(for: base) let bindingObserver = Binder(self.base) { scrollView, contentOffset in scrollView.contentOffset = contentOffset } return ControlProperty(values: proxy.contentOffsetBehaviorSubject, valueSink: bindingObserver) } /// Bindable sink for `scrollEnabled` property. public var isScrollEnabled: Binder<Bool> { return Binder(self.base) { scrollView, scrollEnabled in scrollView.isScrollEnabled = scrollEnabled } } /// Reactive wrapper for delegate method `scrollViewDidScroll` public var didScroll: ControlEvent<Void> { let source = RxScrollViewDelegateProxy.proxy(for: base).contentOffsetPublishSubject return ControlEvent(events: source) } /// Reactive wrapper for delegate method `scrollViewWillBeginDecelerating` public var willBeginDecelerating: ControlEvent<Void> { let source = delegate.methodInvoked(#selector(UIScrollViewDelegate.scrollViewWillBeginDecelerating(_:))).map { _ in } return ControlEvent(events: source) } /// Reactive wrapper for delegate method `scrollViewDidEndDecelerating` public var didEndDecelerating: ControlEvent<Void> { let source = delegate.methodInvoked(#selector(UIScrollViewDelegate.scrollViewDidEndDecelerating(_:))).map { _ in } return ControlEvent(events: source) } /// Reactive wrapper for delegate method `scrollViewWillBeginDragging` public var willBeginDragging: ControlEvent<Void> { let source = delegate.methodInvoked(#selector(UIScrollViewDelegate.scrollViewWillBeginDragging(_:))).map { _ in } return ControlEvent(events: source) } /// Reactive wrapper for delegate method `scrollViewWillEndDragging(_:withVelocity:targetContentOffset:)` public var willEndDragging: ControlEvent<WillEndDraggingEvent> { let source = delegate.methodInvoked(#selector(UIScrollViewDelegate.scrollViewWillEndDragging(_:withVelocity:targetContentOffset:))) .map { value -> WillEndDraggingEvent in let velocity = try castOrThrow(CGPoint.self, value[1]) let targetContentOffsetValue = try castOrThrow(NSValue.self, value[2]) guard let rawPointer = targetContentOffsetValue.pointerValue else { throw RxCocoaError.unknown } let typedPointer = rawPointer.bindMemory(to: CGPoint.self, capacity: MemoryLayout<CGPoint>.size) return (velocity, typedPointer) } return ControlEvent(events: source) } /// Reactive wrapper for delegate method `scrollViewDidEndDragging(_:willDecelerate:)` public var didEndDragging: ControlEvent<Bool> { let source = delegate.methodInvoked(#selector(UIScrollViewDelegate.scrollViewDidEndDragging(_:willDecelerate:))).map { value -> Bool in return try castOrThrow(Bool.self, value[1]) } return ControlEvent(events: source) } /// Reactive wrapper for delegate method `scrollViewDidZoom` public var didZoom: ControlEvent<Void> { let source = delegate.methodInvoked(#selector(UIScrollViewDelegate.scrollViewDidZoom)).map { _ in } return ControlEvent(events: source) } /// Reactive wrapper for delegate method `scrollViewDidScrollToTop` public var didScrollToTop: ControlEvent<Void> { let source = delegate.methodInvoked(#selector(UIScrollViewDelegate.scrollViewDidScrollToTop(_:))).map { _ in } return ControlEvent(events: source) } /// Reactive wrapper for delegate method `scrollViewDidEndScrollingAnimation` public var didEndScrollingAnimation: ControlEvent<Void> { let source = delegate.methodInvoked(#selector(UIScrollViewDelegate.scrollViewDidEndScrollingAnimation(_:))).map { _ in } return ControlEvent(events: source) } /// Reactive wrapper for delegate method `scrollViewWillBeginZooming(_:with:)` public var willBeginZooming: ControlEvent<UIView?> { let source = delegate.methodInvoked(#selector(UIScrollViewDelegate.scrollViewWillBeginZooming(_:with:))).map { value -> UIView? in return try castOptionalOrThrow(UIView.self, value[1] as AnyObject) } return ControlEvent(events: source) } /// Reactive wrapper for delegate method `scrollViewDidEndZooming(_:with:atScale:)` public var didEndZooming: ControlEvent<EndZoomEvent> { let source = delegate.methodInvoked(#selector(UIScrollViewDelegate.scrollViewDidEndZooming(_:with:atScale:))).map { value -> EndZoomEvent in return (try castOptionalOrThrow(UIView.self, value[1] as AnyObject), try castOrThrow(CGFloat.self, value[2])) } return ControlEvent(events: source) } /// Installs delegate as forwarding delegate on `delegate`. /// Delegate won't be retained. /// /// It enables using normal delegate mechanism with reactive delegate mechanism. /// /// - parameter delegate: Delegate object. /// - returns: Disposable object that can be used to unbind the delegate. public func setDelegate(_ delegate: UIScrollViewDelegate) -> Disposable { return RxScrollViewDelegateProxy.installForwardDelegate(delegate, retainDelegate: false, onProxyForObject: self.base) } } #endif
mit
ffa645ec5754dacbf7cd4ad8c506ad18
46.76087
152
0.66606
5.916517
false
false
false
false
hooman/swift
test/IRGen/unmanaged_objc_throw_func.swift
4
4399
// RUN: %target-swift-frontend -emit-ir -enable-copy-propagation %s | %FileCheck %s // REQUIRES: objc_interop // REQUIRES: optimized_stdlib import Foundation @objc protocol SR_9035_P { func returnUnmanagedCFArray() throws -> Unmanaged<CFArray> } // CHECK-LABEL: define hidden swiftcc %TSo10CFArrayRefa* @"$s25unmanaged_objc_throw_func9SR_9035_CC22returnUnmanagedCFArrays0G0VySo0H3RefaGyKF" @objc class SR_9035_C: NSObject, SR_9035_P { func returnUnmanagedCFArray() throws -> Unmanaged<CFArray> { // CHECK: %[[T0:.+]] = call swiftcc { %swift.bridge*, i8* } @"$ss27_allocateUninitializedArrayySayxG_BptBwlF"(i{{32|64}} 1, %swift.type* @"$sSiN") // CHECK-NEXT: %[[T1:.+]] = extractvalue { %swift.bridge*, i8* } %[[T0]], 0 // CHECK-NEXT: %[[T2:.+]] = extractvalue { %swift.bridge*, i8* } %[[T0]], 1 // CHECK-NEXT: %[[T3:.+]] = bitcast i8* %[[T2]] to %TSi* // CHECK-NEXT: %._value = getelementptr inbounds %TSi, %TSi* %[[T3]], i32 0, i32 0 // CHECK: %[[T7:.+]] = call swiftcc %swift.bridge* @"$ss27_finalizeUninitializedArrayySayxGABnlF"(%swift.bridge* %[[T1]], %swift.type* @"$sSiN") // CHECK: %[[T4:.+]] = call swiftcc %TSo7NSArrayC* @"$sSa10FoundationE19_bridgeToObjectiveCSo7NSArrayCyF"(%swift.bridge* %[[T7]], %swift.type* @"$sSiN") // CHECK-NEXT: %[[T5:.+]] = bitcast %TSo7NSArrayC* %[[T4]] to %TSo10CFArrayRefa* // CHECK-NEXT: store %TSo10CFArrayRefa* %[[T5]] // CHECK-NEXT: call void @swift_bridgeObjectRelease(%swift.bridge* %{{[0-9]+}}) #{{[0-9]+}} // CHECK-NEXT: %[[T6:.+]] = bitcast %TSo10CFArrayRefa* %[[T5]] to i8* // CHECK-NEXT: call void @llvm.objc.release(i8* %[[T6]]) // CHECK-NEXT: ret %TSo10CFArrayRefa* %[[T5]] let arr = [1] as CFArray return Unmanaged.passUnretained(arr) } } // CHECK: %[[T0:.+]] = call swiftcc %TSo10CFArrayRefa* @"$s25unmanaged_objc_throw_func9SR_9035_CC22returnUnmanagedCFArrays0G0VySo0H3RefaGyKF" // CHECK-NEXT: %[[T2:.+]] = load %swift.error*, %swift.error** %swifterror, align {{[0-9]+}} // CHECK-NEXT: %[[T3:.+]] = icmp ne %swift.error* %[[T2]], null // CHECK-NEXT: br i1 %[[T3]], label %[[L1:.+]], label %[[L2:.+]] // CHECK: [[L2]]: ; preds = %entry // CHECK-NEXT: %[[T4:.+]] = phi %TSo10CFArrayRefa* [ %[[T0]], %entry ] // CHECK-NEXT: %[[T4a:.+]] = bitcast %T25unmanaged_objc_throw_func9SR_9035_CC* %{{.+}} to i8* // CHECK-NEXT: call void @llvm.objc.release(i8* %[[T4a]]) // CHECK-NEXT: %[[T5:.+]] = ptrtoint %TSo10CFArrayRefa* %[[T4]] to i{{32|64}} // CHECK-NEXT: br label %[[L3:.+]] // CHECK: [[L1]]: ; preds = %entry // CHECK-NEXT: %[[T6:.+]] = phi %swift.error* [ %[[T2]], %entry ] // CHECK-NEXT: store %swift.error* null, %swift.error** %swifterror, align {{[0-9]+}} // CHECK-NEXT: %[[T6a:.+]] = bitcast %T25unmanaged_objc_throw_func9SR_9035_CC* %{{.+}} to i8* // CHECK-NEXT: call void @llvm.objc.release(i8* %[[T6a]]) // CHECK-NEXT: %[[T7:.+]] = icmp eq i{{32|64}} %{{.+}}, 0 // CHECK-NEXT: br i1 %[[T7]], label %[[L4:.+]], label %[[L5:.+]] // CHECK: [[L5]]: ; preds = %[[L1]] // CHECK-NEXT: %[[T8:.+]] = inttoptr i{{32|64}} %{{.+}} to i8* // CHECK-NEXT: br label %[[L6:.+]] // CHECK: [[L6]]: ; preds = %[[L5]] // CHECK-NEXT: %[[T9:.+]] = phi i8* [ %[[T8]], %[[L5]] ] // CHECK-NEXT: %[[T10:.+]] = call swiftcc %TSo7NSErrorC* @"$s10Foundation22_convertErrorToNSErrorySo0E0Cs0C0_pF"(%swift.error* %[[T6]]) #{{[0-9]+}} // CHECK: call swiftcc void @"$sSA7pointeexvs"(%swift.opaque* noalias nocapture %{{.+}}, i8* %[[T9]], %swift.type* %{{.+}}) #{{[0-9]+}} // CHECK-NEXT: %[[T11:.+]] = bitcast %TSo7NSErrorCSg* %{{.+}} to i8* // CHECK: call void @swift_errorRelease(%swift.error* %[[T6]]) #{{[0-9]+}} // CHECK-NEXT: br label %[[L7:.+]] // CHECK: [[L4]]: ; preds = %[[L1]] // CHECK-NEXT: call void @swift_errorRelease(%swift.error* %[[T6]]) #{{[0-9]+}} // CHECK-NEXT: br label %[[L7]] // CHECK: [[L7]]: ; preds = %[[L6]], %[[L4]] // CHECK-NEXT: br label %[[L3]] // CHECK: [[L3]]: ; preds = %[[L2]], %[[L7]] // CHECK-NEXT: %[[T12:.+]] = phi i{{32|64}} [ 0, %[[L7]] ], [ %[[T5]], %[[L2]] ] // CHECK-NEXT: %[[T14:.+]] = inttoptr i{{32|64}} %[[T12]] to %struct.__CFArray* // CHECK-NEXT: ret %struct.__CFArray* %[[T14]]
apache-2.0
f2531f66699bb71bbe2d57ba3c5b2f05
58.445946
161
0.54717
3.10007
false
false
false
false
Miridescen/M_365key
365KEY_swift/365KEY_swift/MainController/Class/UserCenter/controller/SKMyFocusController.swift
1
4764
// // SKMyFocusController.swift // 365KEY_swift // // Created by 牟松 on 2016/12/1. // Copyright © 2016年 DoNews. All rights reserved. // import UIKit class SKMyFocusController: UIViewController { var navBar: UINavigationBar? var navItem: UINavigationItem? var bgView: UIView? var headBtnView: UIView? var productBtn: UIButton? var peopleBtn: UIButton? lazy var NoInfoView = SKNoInfoView(frame: CGRect(x: 0, y: 72, width: SKScreenWidth, height: SKScreenHeight-64-72)) lazy var focusProductView = SKMyfocusProductTV(frame: CGRect(x: 0, y: 72, width: SKScreenWidth, height: SKScreenHeight-64-72), style: UITableViewStyle.init(rawValue: 0)!) override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.white addSubView() loadData() } func loadData() { NSURLConnection.connection.userCenterMyFocusDataRqeuest { (bool, jsonData) in if bool { self.focusProductView.dataSourceArray = jsonData! self.bgView?.addSubview(self.focusProductView) } else { self.bgView?.insertSubview(self.NoInfoView, at: (self.bgView?.subviews.count)!) } } } } extension SKMyFocusController{ func addSubView() { navBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: SKScreenWidth, height: 64)) navBar?.isTranslucent = false navBar?.barTintColor = UIColor().mainColor navBar?.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white] view.addSubview(navBar!) navItem = UINavigationItem() navItem?.leftBarButtonItem = UIBarButtonItem(SK_barButtonItem: UIImage(named:"icon_back"), selectorImage: UIImage(named:"icon_back"), tragtic: self, action: #selector(backBtnDidClick)) navItem?.title = "我的关注" navBar?.items = [navItem!] bgView = UIView(frame: CGRect(x: 0, y: 64, width: SKScreenWidth, height: SKScreenHeight-64)) view.addSubview(bgView!) headBtnView = UIView(frame: CGRect(x: 0, y: 0, width: SKScreenWidth, height: 72)) bgView?.addSubview(headBtnView!) let topLineLayer = CALayer() topLineLayer.frame = CGRect(x: 16, y: 12, width: SKScreenWidth-32, height: 1) topLineLayer.backgroundColor = UIColor(white: 225/255.0, alpha: 1).cgColor headBtnView?.layer.addSublayer(topLineLayer) let bottemLineLayer = CALayer() bottemLineLayer.frame = CGRect(x: 16, y: 60, width: SKScreenWidth-32, height: 1) bottemLineLayer.backgroundColor = UIColor(white: 225/255.0, alpha: 1).cgColor headBtnView?.layer.addSublayer(bottemLineLayer) let verticalLineLayer = CALayer() verticalLineLayer.frame = CGRect(x: SKScreenWidth/2, y: 27, width: 2, height: 20) verticalLineLayer.backgroundColor = UIColor(white: 225/255.0, alpha: 1).cgColor headBtnView?.layer.addSublayer(verticalLineLayer) productBtn = UIButton(frame: CGRect(x: ((SKScreenWidth/2-16)-126)/2+16, y: 23, width: 126, height: 28)) productBtn?.setBackgroundImage(UIImage(named: "bg_guanzhu_nav"), for: .selected) productBtn?.setTitle("产品", for: .normal) productBtn?.setTitleColor(UIColor.white, for: .selected) productBtn?.setTitleColor(UIColor.black, for: .normal) productBtn?.isSelected = true productBtn?.addTarget(self, action: #selector(productBtnDidClick), for: .touchUpInside) headBtnView?.addSubview(productBtn!) peopleBtn = UIButton(frame: CGRect(x: ((SKScreenWidth/2-16)-126)/2+SKScreenWidth/2, y: 23, width: 126, height: 28)) peopleBtn?.setBackgroundImage(UIImage(named: "bg_guanzhu_nav"), for: .selected) peopleBtn?.setTitle("人脉", for: .normal) peopleBtn?.setTitleColor(UIColor.white, for: .selected) peopleBtn?.setTitleColor(UIColor.black, for: .normal) peopleBtn?.addTarget(self, action: #selector(peopleBtnDidClick), for: .touchUpInside) headBtnView?.addSubview(peopleBtn!) } @objc private func backBtnDidClick(){ _ = navigationController?.popViewController(animated: true) } @objc private func productBtnDidClick(btn: UIButton){ btn.isSelected = true peopleBtn?.isSelected = false bgView?.insertSubview(focusProductView, at: (bgView?.subviews.count)!) } @objc private func peopleBtnDidClick(btn: UIButton){ btn.isSelected = true productBtn?.isSelected = false bgView?.insertSubview(NoInfoView, at: (bgView?.subviews.count)!) } }
apache-2.0
b181fccd0bba1b893b5d87e875807a38
38.840336
192
0.65155
4.443299
false
false
false
false
firebase/firebase-ios-sdk
Example/tvOSSample/tvOSSample/EmailLoginViewController.swift
2
3029
// Copyright 2017 Google // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import UIKit import FirebaseAuth protocol EmailLoginDelegate { func emailLogin(_ controller: EmailLoginViewController, signedInAs user: User) func emailLogin(_ controller: EmailLoginViewController, failedWithError error: Error) } class EmailLoginViewController: UIViewController { // MARK: - Public Properties var delegate: EmailLoginDelegate? // MARK: - User Interface @IBOutlet private var emailAddress: UITextField! @IBOutlet private var password: UITextField! // MARK: - User Actions @IBAction func logInButtonHit(_ sender: UIButton) { guard let (email, password) = validatedInputs() else { return } Auth.auth().signIn(withEmail: email, password: password) { [unowned self] result, error in guard let result = result else { print("Error signing in: \(error!)") self.delegate?.emailLogin(self, failedWithError: error!) return } print("Signed in as user: \(result.user.uid)") self.delegate?.emailLogin(self, signedInAs: result.user) } } @IBAction func signUpButtonHit(_ sender: UIButton) { guard let (email, password) = validatedInputs() else { return } Auth.auth().createUser(withEmail: email, password: password) { [unowned self] result, error in guard let result = result else { print("Error signing up: \(error!)") self.delegate?.emailLogin(self, failedWithError: error!) return } print("Created new user: \(result.user.uid)!") self.delegate?.emailLogin(self, signedInAs: result.user) } } // MARK: - View Controller Lifecycle override func viewDidLoad() {} // MARK: - Helper Methods /// Validate the inputs for user email and password, returning the username and password if valid, /// otherwise nil. private func validatedInputs() -> (email: String, password: String)? { guard let userEmail = emailAddress.text, userEmail.count >= 6 else { presentError(with: "Email address isn't long enough.") return nil } guard let userPassword = password.text, userPassword.count >= 6 else { presentError(with: "Password is not long enough!") return nil } return (userEmail, userPassword) } func presentError(with text: String) { let alert = UIAlertController(title: "Error", message: text, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Okay", style: .default)) present(alert, animated: true) } }
apache-2.0
8f384a18b68b8333fc7c9cb7a4ed3094
31.923913
100
0.696269
4.454412
false
false
false
false
mozilla-mobile/firefox-ios
CredentialProvider/Cells/NoSearchResultCell.swift
2
1712
// 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 UIKit class NoSearchResultCell: UITableViewCell { static let identifier = "noSearchResultCell" lazy private var titleLabel: UILabel = .build { label in label.textColor = UIColor.CredentialProvider.titleColor label.text = .LoginsListNoMatchingResultTitle label.font = UIFont.systemFont(ofSize: 15) } lazy private var descriptionLabel: UILabel = .build { label in label.text = .LoginsListNoMatchingResultSubtitle label.textColor = .systemGray label.font = UIFont.systemFont(ofSize: 13) label.textAlignment = .center label.numberOfLines = 0 } override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) selectionStyle = .none backgroundColor = UIColor.CredentialProvider.tableViewBackgroundColor contentView.addSubviews(titleLabel, descriptionLabel) NSLayoutConstraint.activate([ titleLabel.centerXAnchor.constraint(equalTo: contentView.centerXAnchor), titleLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 55), descriptionLabel.centerXAnchor.constraint(equalTo: contentView.centerXAnchor), descriptionLabel.topAnchor.constraint(equalTo: titleLabel.layoutMarginsGuide.bottomAnchor, constant: 15), ]) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mpl-2.0
28a504988a2c486404a06b47c21571ea
38.813953
117
0.712033
5.110448
false
false
false
false
klundberg/swift-corelibs-foundation
TestFoundation/TestNSURLResponse.swift
1
15023
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // #if DEPLOYMENT_RUNTIME_OBJC || os(Linux) import Foundation import XCTest #else import SwiftFoundation import SwiftXCTest #endif class TestNSURLResponse : XCTestCase { static var allTests: [(String, (TestNSURLResponse) -> () throws -> Void)] { return [ ("test_URL", test_URL), ("test_MIMEType_1", test_MIMEType_1), ("test_MIMEType_2", test_MIMEType_2), ("test_ExpectedContentLength", test_ExpectedContentLength), ("test_TextEncodingName", test_TextEncodingName), ("test_suggestedFilename", test_suggestedFilename), ("test_suggestedFilename_2", test_suggestedFilename_2), ("test_suggestedFilename_3", test_suggestedFilename_3), ("test_copywithzone", test_copyWithZone), ] } func test_URL() { let url = URL(string: "a/test/path")! let res = URLResponse(url: url, mimeType: "txt", expectedContentLength: 0, textEncodingName: nil) XCTAssertEqual(res.url, url, "should be the expected url") } func test_MIMEType_1() { let mimetype = "text/plain" let res = URLResponse(url: URL(string: "test")!, mimeType: mimetype, expectedContentLength: 0, textEncodingName: nil) XCTAssertEqual(res.mimeType, mimetype, "should be the passed in mimetype") } func test_MIMEType_2() { let mimetype = "APPlication/wordperFECT" let res = URLResponse(url: URL(string: "test")!, mimeType: mimetype, expectedContentLength: 0, textEncodingName: nil) XCTAssertEqual(res.mimeType, mimetype, "should be the other mimetype") } func test_ExpectedContentLength() { let zeroContentLength = 0 let positiveContentLength = 100 let url = URL(string: "test")! let res1 = URLResponse(url: url, mimeType: "text/plain", expectedContentLength: zeroContentLength, textEncodingName: nil) XCTAssertEqual(res1.expectedContentLength, Int64(zeroContentLength), "should be Int65 of the zero length") let res2 = URLResponse(url: url, mimeType: "text/plain", expectedContentLength: positiveContentLength, textEncodingName: nil) XCTAssertEqual(res2.expectedContentLength, Int64(positiveContentLength), "should be Int64 of the positive content length") } func test_TextEncodingName() { let encoding = "utf8" let url = URL(string: "test")! let res1 = URLResponse(url: url, mimeType: nil, expectedContentLength: 0, textEncodingName: encoding) XCTAssertEqual(res1.textEncodingName, encoding, "should be the utf8 encoding") let res2 = URLResponse(url: url, mimeType: nil, expectedContentLength: 0, textEncodingName: nil) XCTAssertNil(res2.textEncodingName) } func test_suggestedFilename() { let url = URL(string: "a/test/name.extension")! let res = URLResponse(url: url, mimeType: "txt", expectedContentLength: 0, textEncodingName: nil) XCTAssertEqual(res.suggestedFilename, "name.extension") } func test_suggestedFilename_2() { let url = URL(string: "a/test/name.extension?foo=bar")! let res = URLResponse(url: url, mimeType: "txt", expectedContentLength: 0, textEncodingName: nil) XCTAssertEqual(res.suggestedFilename, "name.extension") } func test_suggestedFilename_3() { let url = URL(string: "a://bar")! let res = URLResponse(url: url, mimeType: "txt", expectedContentLength: 0, textEncodingName: nil) XCTAssertEqual(res.suggestedFilename, "Unknown") } func test_copyWithZone() { let url = URL(string: "a/test/path")! let res = URLResponse(url: url, mimeType: "txt", expectedContentLength: 0, textEncodingName: nil) XCTAssertTrue(res.isEqual(res.copy())) } } class TestNSHTTPURLResponse : XCTestCase { static var allTests: [(String, (TestNSHTTPURLResponse) -> () throws -> Void)] { return [ ("test_URL_and_status_1", test_URL_and_status_1), ("test_URL_and_status_2", test_URL_and_status_2), ("test_headerFields_1", test_headerFields_1), ("test_headerFields_2", test_headerFields_2), ("test_headerFields_3", test_headerFields_3), ("test_contentLength_available_1", test_contentLength_available_1), ("test_contentLength_available_2", test_contentLength_available_2), ("test_contentLength_available_3", test_contentLength_available_3), ("test_contentLength_available_4", test_contentLength_available_4), ("test_contentLength_notAvailable", test_contentLength_notAvailable), ("test_contentLength_withTransferEncoding", test_contentLength_withTransferEncoding), ("test_contentLength_withContentEncoding", test_contentLength_withContentEncoding), ("test_contentLength_withContentEncodingAndTransferEncoding", test_contentLength_withContentEncodingAndTransferEncoding), ("test_contentLength_withContentEncodingAndTransferEncoding_2", test_contentLength_withContentEncodingAndTransferEncoding_2), ("test_suggestedFilename_notAvailable_1", test_suggestedFilename_notAvailable_1), ("test_suggestedFilename_notAvailable_2", test_suggestedFilename_notAvailable_2), ("test_suggestedFilename_1", test_suggestedFilename_1), ("test_suggestedFilename_2", test_suggestedFilename_2), ("test_suggestedFilename_3", test_suggestedFilename_3), ("test_suggestedFilename_4", test_suggestedFilename_4), ("test_suggestedFilename_removeSlashes_1", test_suggestedFilename_removeSlashes_1), ("test_suggestedFilename_removeSlashes_2", test_suggestedFilename_removeSlashes_2), ("test_MIMETypeAndCharacterEncoding_1", test_MIMETypeAndCharacterEncoding_1), ("test_MIMETypeAndCharacterEncoding_2", test_MIMETypeAndCharacterEncoding_2), ("test_MIMETypeAndCharacterEncoding_3", test_MIMETypeAndCharacterEncoding_3), ] } let url = URL(string: "https://www.swift.org")! func test_URL_and_status_1() { let sut = NSHTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: ["Content-Length": "5299"]) XCTAssertEqual(sut?.url, url) XCTAssertEqual(sut?.statusCode, 200) } func test_URL_and_status_2() { let url = URL(string: "http://www.apple.com")! let sut = NSHTTPURLResponse(url: url, statusCode: 302, httpVersion: "HTTP/1.1", headerFields: ["Content-Length": "5299"]) XCTAssertEqual(sut?.url, url) XCTAssertEqual(sut?.statusCode, 302) } func test_headerFields_1() { let sut = NSHTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: nil) XCTAssertEqual(sut?.allHeaderFields.count, 0) } func test_headerFields_2() { let sut = NSHTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: [:]) XCTAssertEqual(sut?.allHeaderFields.count, 0) } func test_headerFields_3() { let f = ["A": "1", "B": "2"] let sut = NSHTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: f) XCTAssertEqual(sut?.allHeaderFields.count, 2) XCTAssertEqual(sut?.allHeaderFields["A"], "1") XCTAssertEqual(sut?.allHeaderFields["B"], "2") } // Note that the message content length is different from the message // transfer length. // The transfer length can only be derived when the Transfer-Encoding is identity (default). // For compressed content (Content-Encoding other than identity), there is not way to derive the // content length from the transfer length. // // C.f. <https://tools.ietf.org/html/rfc2616#section-4.4> func test_contentLength_available_1() { let f = ["Content-Length": "997"] let sut = NSHTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: f) XCTAssertEqual(sut?.expectedContentLength, 997) } func test_contentLength_available_2() { let f = ["Content-Length": "997", "Transfer-Encoding": "identity"] let sut = NSHTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: f) XCTAssertEqual(sut?.expectedContentLength, 997) } func test_contentLength_available_3() { let f = ["Content-Length": "997", "Content-Encoding": "identity"] let sut = NSHTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: f) XCTAssertEqual(sut?.expectedContentLength, 997) } func test_contentLength_available_4() { let f = ["Content-Length": "997", "Content-Encoding": "identity", "Transfer-Encoding": "identity"] let sut = NSHTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: f) XCTAssertEqual(sut?.expectedContentLength, 997) } func test_contentLength_notAvailable() { let f = ["Server": "Apache"] let sut = NSHTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: f) XCTAssertEqual(sut?.expectedContentLength, -1) } func test_contentLength_withTransferEncoding() { let f = ["Content-Length": "997", "Transfer-Encoding": "chunked"] let sut = NSHTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: f) XCTAssertEqual(sut?.expectedContentLength, 997) } func test_contentLength_withContentEncoding() { let f = ["Content-Length": "997", "Content-Encoding": "deflate"] let sut = NSHTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: f) XCTAssertEqual(sut?.expectedContentLength, 997) } func test_contentLength_withContentEncodingAndTransferEncoding() { let f = ["Content-Length": "997", "Content-Encoding": "deflate", "Transfer-Encoding": "identity"] let sut = NSHTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: f) XCTAssertEqual(sut?.expectedContentLength, 997) } func test_contentLength_withContentEncodingAndTransferEncoding_2() { let f = ["Content-Length": "997", "Content-Encoding": "identity", "Transfer-Encoding": "chunked"] let sut = NSHTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: f) XCTAssertEqual(sut?.expectedContentLength, 997) } // The `suggestedFilename` can be derived from the "Content-Disposition" // header as defined in RFC 1806 and more recently RFC 2183 // https://tools.ietf.org/html/rfc1806 // https://tools.ietf.org/html/rfc2183 // // Typical use looks like this: // Content-Disposition: attachment; filename="fname.ext" // // As noted in https://tools.ietf.org/html/rfc2616#section-19.5.1 the // receiving user agent SHOULD NOT respect any directory path information // present in the filename-parm parameter. // func test_suggestedFilename_notAvailable_1() { let f: [String: String] = [:] let sut = NSHTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: f) XCTAssertEqual(sut?.suggestedFilename, "Unknown") } func test_suggestedFilename_notAvailable_2() { let f = ["Content-Disposition": "inline"] let sut = NSHTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: f) XCTAssertEqual(sut?.suggestedFilename, "Unknown") } func test_suggestedFilename_1() { let f = ["Content-Disposition": "attachment; filename=\"fname.ext\""] let sut = NSHTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: f) XCTAssertEqual(sut?.suggestedFilename, "fname.ext") } func test_suggestedFilename_2() { let f = ["Content-Disposition": "attachment; filename=genome.jpeg; modification-date=\"Wed, 12 Feb 1997 16:29:51 -0500\";"] let sut = NSHTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: f) XCTAssertEqual(sut?.suggestedFilename, "genome.jpeg") } func test_suggestedFilename_3() { let f = ["Content-Disposition": "attachment; filename=\";.ext\""] let sut = NSHTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: f) XCTAssertEqual(sut?.suggestedFilename, ";.ext") } func test_suggestedFilename_4() { let f = ["Content-Disposition": "attachment; aa=bb\\; filename=\"wrong.ext\"; filename=\"fname.ext\"; cc=dd"] let sut = NSHTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: f) XCTAssertEqual(sut?.suggestedFilename, "fname.ext") } func test_suggestedFilename_removeSlashes_1() { let f = ["Content-Disposition": "attachment; filename=\"/a/b/name\""] let sut = NSHTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: f) XCTAssertEqual(sut?.suggestedFilename, "_a_b_name") } func test_suggestedFilename_removeSlashes_2() { let f = ["Content-Disposition": "attachment; filename=\"a/../b/name\""] let sut = NSHTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: f) XCTAssertEqual(sut?.suggestedFilename, "a_.._b_name") } // The MIME type / character encoding func test_MIMETypeAndCharacterEncoding_1() { let f = ["Server": "Apache"] let sut = NSHTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: f) XCTAssertNil(sut?.mimeType) XCTAssertNil(sut?.textEncodingName) } func test_MIMETypeAndCharacterEncoding_2() { let f = ["Content-Type": "text/html"] let sut = NSHTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: f) XCTAssertEqual(sut?.mimeType, "text/html") XCTAssertNil(sut?.textEncodingName) } func test_MIMETypeAndCharacterEncoding_3() { let f = ["Content-Type": "text/HTML; charset=ISO-8859-4"] let sut = NSHTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: f) XCTAssertEqual(sut?.mimeType, "text/html") XCTAssertEqual(sut?.textEncodingName, "iso-8859-4") } }
apache-2.0
69ea49565dd02930f9228cff40d4b67a
49.925424
144
0.653598
4.432871
false
true
false
false
KrishMunot/swift
stdlib/public/core/Zip.swift
4
3519
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// A sequence of pairs built out of two underlying sequences, where /// the elements of the `i`th pair are the `i`th elements of each /// underlying sequence. public func zip<Sequence1 : Sequence, Sequence2 : Sequence>( _ sequence1: Sequence1, _ sequence2: Sequence2 ) -> Zip2Sequence<Sequence1, Sequence2> { return Zip2Sequence(_sequence1: sequence1, _sequence2: sequence2) } /// An iterator for `Zip2Sequence`. public struct Zip2Iterator< Iterator1 : IteratorProtocol, Iterator2 : IteratorProtocol > : IteratorProtocol { /// The type of element returned by `next()`. public typealias Element = (Iterator1.Element, Iterator2.Element) /// Construct around a pair of underlying iterators. internal init(_ iterator1: Iterator1, _ iterator2: Iterator2) { (_baseStream1, _baseStream2) = (iterator1, iterator2) } /// Advance to the next element and return it, or `nil` if no next /// element exists. /// /// - Precondition: `next()` has not been applied to a copy of `self` /// since the copy was made, and no preceding call to `self.next()` /// has returned `nil`. public mutating func next() -> Element? { // The next() function needs to track if it has reached the end. If we // didn't, and the first sequence is longer than the second, then when we // have already exhausted the second sequence, on every subsequent call to // next() we would consume and discard one additional element from the // first sequence, even though next() had already returned nil. if _reachedEnd { return nil } guard let element1 = _baseStream1.next(), element2 = _baseStream2.next() else { _reachedEnd = true return nil } return (element1, element2) } internal var _baseStream1: Iterator1 internal var _baseStream2: Iterator2 internal var _reachedEnd: Bool = false } /// A sequence of pairs built out of two underlying sequences, where /// the elements of the `i`th pair are the `i`th elements of each /// underlying sequence. public struct Zip2Sequence<Sequence1 : Sequence, Sequence2 : Sequence> : Sequence { public typealias Stream1 = Sequence1.Iterator public typealias Stream2 = Sequence2.Iterator /// A type whose instances can produce the elements of this /// sequence, in order. public typealias Iterator = Zip2Iterator<Stream1, Stream2> @available(*, unavailable, renamed: "Iterator") public typealias Generator = Iterator /// Construct an instance that makes pairs of elements from `sequence1` and /// `sequence2`. public // @testable init(_sequence1 sequence1: Sequence1, _sequence2 sequence2: Sequence2) { (_sequence1, _sequence2) = (sequence1, sequence2) } /// Returns an iterator over the elements of this sequence. /// /// - Complexity: O(1). public func makeIterator() -> Iterator { return Iterator( _sequence1.makeIterator(), _sequence2.makeIterator()) } internal let _sequence1: Sequence1 internal let _sequence2: Sequence2 }
apache-2.0
a73e60c27a450f6a8eec0a55ea6574e9
34.908163
83
0.674339
4.317791
false
false
false
false
ericvergnaud/antlr4
runtime/Swift/Sources/Antlr4/atn/LexerTypeAction.swift
7
1905
/// /// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. /// Use of this file is governed by the BSD 3-clause license that /// can be found in the LICENSE.txt file in the project root. /// /// /// Implements the `type` lexer action by calling _org.antlr.v4.runtime.Lexer#setType_ /// with the assigned type. /// /// - Sam Harwell /// - 4.2 /// public class LexerTypeAction: LexerAction, CustomStringConvertible { fileprivate let type: Int /// /// Constructs a new `type` action with the specified token type value. /// - parameter type: The type to assign to the token using _org.antlr.v4.runtime.Lexer#setType_. /// public init(_ type: Int) { self.type = type } /// /// Gets the type to assign to a token created by the lexer. /// - returns: The type to assign to a token created by the lexer. /// public func getType() -> Int { return type } /// /// /// - returns: This method returns _org.antlr.v4.runtime.atn.LexerActionType#TYPE_. /// public override func getActionType() -> LexerActionType { return LexerActionType.type } /// /// /// - returns: This method returns `false`. /// override public func isPositionDependent() -> Bool { return false } /// /// /// /// This action is implemented by calling _org.antlr.v4.runtime.Lexer#setType_ with the /// value provided by _#getType_. /// public override func execute(_ lexer: Lexer) { lexer.setType(type) } public override func hash(into hasher: inout Hasher) { hasher.combine(type) } public var description: String { return "type(\(type))" } } public func ==(lhs: LexerTypeAction, rhs: LexerTypeAction) -> Bool { if lhs === rhs { return true } return lhs.type == rhs.type }
bsd-3-clause
81740d8d437bcdbba403aa8066f9b68d
23.113924
101
0.599475
4.070513
false
false
false
false
chicio/RangeUISlider
Source/UI/RangeSlider.swift
1
2396
// // RangeSlider.swift // RangeUISlider // // Created by Fabrizio Duroni on 06.01.21. // 2021 Fabrizio Duroni. // #if canImport(SwiftUI) import SwiftUI /** RangeUISlider SwiftUI implementation using UIViewRepresentable. It exposes all the RangeUIslider properties. */ @available(iOS 14.0, *) public struct RangeSlider: UIViewRepresentable { /// Min value selected binding value. /// In this property the min value selected will be exposed. It will be updated during dragging. @Binding public var minValueSelected: CGFloat /// Max value selected binding value. /// In this property the max value selected will be exposed. It will be updated during dragging. @Binding public var maxValueSelected: CGFloat let settings: RangeSliderSettings private let rangeUISliderCreator: RangeUISliderCreator /** Init RangeSlider. - parameter minValueSelected: the binding value to get the min value selected. - parameter maxValueSelected: the binding value to get the max value selected. */ public init(minValueSelected: Binding<CGFloat>, maxValueSelected: Binding<CGFloat>) { self._minValueSelected = minValueSelected self._maxValueSelected = maxValueSelected self.settings = RangeSliderSettings() self.rangeUISliderCreator = RangeUISliderCreator() } // MARK: lifecycle /** Implementation of `UIViewRepresentable.makeUIView(context: Context)` method. - parameter content: the SwiftUI context. - returns: an instance of RangeUISlider */ public func makeUIView(context: Context) -> RangeUISlider { let rangeSlider = rangeUISliderCreator.createFrom(settings: settings) rangeSlider.delegate = context.coordinator return rangeSlider } /** Implementation of `UIViewRepresentable.updateUIView(_ uiView: RangeUISlider, context: Context)` method. - parameter uiView: the `RangeUISlider` instance. - parameter content: the SwiftUI context. */ public func updateUIView(_ uiView: RangeUISlider, context: Context) { } /** Implementation of `UIViewRepresentable.makeCoordinator()` method. - returns: an instance of `RangeSliderCoordinator` */ public func makeCoordinator() -> RangeSliderCoordinator { return RangeSliderCoordinator(rangeSlider: self) } } #endif
mit
633b41eea34edc9525cb2ad1046cd287
32.746479
109
0.707429
5.174946
false
false
false
false
blue42u/swift-t
stc/tests/513-strings-14.swift
4
1219
import assert; import string; main { string x = "hello world\n"; string y = "banana nana\n"; trace(x); assertEqual(x, "hello world\n",""); // Success cases string s = replace("hello world", "world", "folks", 0); assertEqual("hello folks", s, "s"); string s1 = replace("banana", "an", "ah", 0); assertEqual("bahana", s1, "s1"); string s1a = replaceAll("banana", "an", "..", 0, 4); assertEqual(s1a, "b..ana", "s1a"); string s2 = replace(y, "ana", "i", 0); assertEqual("bina nana\n", s2, "s2"); string s3 = replaceAll("banana", "an", "ah"); assertEqual("bahaha", s3, "s3"); string s4 = replace_all(y, "ana", "i", 0); assertEqual("bina ni\n", s4, "s4"); string s4a = replace_all(y, "ana", "i", 2); assertEqual("bani ni\n", s4a, "s4a"); // Failure cases string s5 = replace("hello world", "", "folks", 0); assertEqual("hello world", s5, "s5"); string s6 = replace("banana", "an", "ah", 5); assertEqual("banana", s6, "s6"); string s7 = replace("banana", "", "ah", 5); assertEqual("banana", s7, "s7"); string s8 = replace_all("banana", "an", "anana", 0); assertEqual("bananaananaa", s8, "s8"); }
apache-2.0
f2543fa262c50d002a4318ab784efdee
25.5
59
0.54799
2.958738
false
false
false
false
ahoppen/swift
stdlib/public/core/Sequence.swift
4
46221
//===----------------------------------------------------------------------===// // // 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 supplies the values of a sequence one at a time. /// /// The `IteratorProtocol` protocol is tightly linked with the `Sequence` /// protocol. Sequences provide access to their elements by creating an /// iterator, which keeps track of its iteration process and returns one /// element at a time as it advances through the sequence. /// /// Whenever you use a `for`-`in` loop with an array, set, or any other /// collection or sequence, you're using that type's iterator. Swift uses a /// sequence's or collection's iterator internally to enable the `for`-`in` /// loop language construct. /// /// Using a sequence's iterator directly gives you access to the same elements /// in the same order as iterating over that sequence using a `for`-`in` loop. /// For example, you might typically use a `for`-`in` loop to print each of /// the elements in an array. /// /// let animals = ["Antelope", "Butterfly", "Camel", "Dolphin"] /// for animal in animals { /// print(animal) /// } /// // Prints "Antelope" /// // Prints "Butterfly" /// // Prints "Camel" /// // Prints "Dolphin" /// /// Behind the scenes, Swift uses the `animals` array's iterator to loop over /// the contents of the array. /// /// var animalIterator = animals.makeIterator() /// while let animal = animalIterator.next() { /// print(animal) /// } /// // Prints "Antelope" /// // Prints "Butterfly" /// // Prints "Camel" /// // Prints "Dolphin" /// /// The call to `animals.makeIterator()` returns an instance of the array's /// iterator. Next, the `while` loop calls the iterator's `next()` method /// repeatedly, binding each element that is returned to `animal` and exiting /// when the `next()` method returns `nil`. /// /// Using Iterators Directly /// ======================== /// /// You rarely need to use iterators directly, because a `for`-`in` loop is the /// more idiomatic approach to traversing a sequence in Swift. Some /// algorithms, however, may call for direct iterator use. /// /// One example is the `reduce1(_:)` method. Similar to the `reduce(_:_:)` /// method defined in the standard library, which takes an initial value and a /// combining closure, `reduce1(_:)` uses the first element of the sequence as /// the initial value. /// /// Here's an implementation of the `reduce1(_:)` method. The sequence's /// iterator is used directly to retrieve the initial value before looping /// over the rest of the sequence. /// /// extension Sequence { /// func reduce1( /// _ nextPartialResult: (Element, Element) -> Element /// ) -> Element? /// { /// var i = makeIterator() /// guard var accumulated = i.next() else { /// return nil /// } /// /// while let element = i.next() { /// accumulated = nextPartialResult(accumulated, element) /// } /// return accumulated /// } /// } /// /// The `reduce1(_:)` method makes certain kinds of sequence operations /// simpler. Here's how to find the longest string in a sequence, using the /// `animals` array introduced earlier as an example: /// /// let longestAnimal = animals.reduce1 { current, element in /// if current.count > element.count { /// return current /// } else { /// return element /// } /// } /// print(longestAnimal) /// // Prints Optional("Butterfly") /// /// Using Multiple Iterators /// ======================== /// /// Whenever you use multiple iterators (or `for`-`in` loops) over a single /// sequence, be sure you know that the specific sequence supports repeated /// iteration, either because you know its concrete type or because the /// sequence is also constrained to the `Collection` protocol. /// /// Obtain each separate iterator from separate calls to the sequence's /// `makeIterator()` method rather than by copying. Copying an iterator is /// safe, but advancing one copy of an iterator by calling its `next()` method /// may invalidate other copies of that iterator. `for`-`in` loops are safe in /// this regard. /// /// Adding IteratorProtocol Conformance to Your Type /// ================================================ /// /// Implementing an iterator that conforms to `IteratorProtocol` is simple. /// Declare a `next()` method that advances one step in the related sequence /// and returns the current element. When the sequence has been exhausted, the /// `next()` method returns `nil`. /// /// For example, consider a custom `Countdown` sequence. You can initialize the /// `Countdown` sequence with a starting integer and then iterate over the /// count down to zero. The `Countdown` structure's definition is short: It /// contains only the starting count and the `makeIterator()` method required /// by the `Sequence` protocol. /// /// struct Countdown: Sequence { /// let start: Int /// /// func makeIterator() -> CountdownIterator { /// return CountdownIterator(self) /// } /// } /// /// The `makeIterator()` method returns another custom type, an iterator named /// `CountdownIterator`. The `CountdownIterator` type keeps track of both the /// `Countdown` sequence that it's iterating and the number of times it has /// returned a value. /// /// struct CountdownIterator: IteratorProtocol { /// let countdown: Countdown /// var times = 0 /// /// init(_ countdown: Countdown) { /// self.countdown = countdown /// } /// /// mutating func next() -> Int? { /// let nextNumber = countdown.start - times /// guard nextNumber > 0 /// else { return nil } /// /// times += 1 /// return nextNumber /// } /// } /// /// Each time the `next()` method is called on a `CountdownIterator` instance, /// it calculates the new next value, checks to see whether it has reached /// zero, and then returns either the number, or `nil` if the iterator is /// finished returning elements of the sequence. /// /// Creating and iterating over a `Countdown` sequence uses a /// `CountdownIterator` to handle the iteration. /// /// let threeTwoOne = Countdown(start: 3) /// for count in threeTwoOne { /// print("\(count)...") /// } /// // Prints "3..." /// // Prints "2..." /// // Prints "1..." public protocol IteratorProtocol { /// The type of element traversed by the iterator. associatedtype Element /// Advances to the next element and returns it, or `nil` if no next element /// exists. /// /// Repeatedly calling this method returns, in order, all the elements of the /// underlying sequence. As soon as the sequence has run out of elements, all /// subsequent calls return `nil`. /// /// You must not call this method if any other copy of this iterator has been /// advanced with a call to its `next()` method. /// /// The following example shows how an iterator can be used explicitly to /// emulate a `for`-`in` loop. First, retrieve a sequence's iterator, and /// then call the iterator's `next()` method until it returns `nil`. /// /// let numbers = [2, 3, 5, 7] /// var numbersIterator = numbers.makeIterator() /// /// while let num = numbersIterator.next() { /// print(num) /// } /// // Prints "2" /// // Prints "3" /// // Prints "5" /// // Prints "7" /// /// - Returns: The next element in the underlying sequence, if a next element /// exists; otherwise, `nil`. mutating func next() -> Element? } /// A type that provides sequential, iterated access to its elements. /// /// A sequence is a list of values that you can step through one at a time. The /// most common way to iterate over the elements of a sequence is to use a /// `for`-`in` loop: /// /// let oneTwoThree = 1...3 /// for number in oneTwoThree { /// print(number) /// } /// // Prints "1" /// // Prints "2" /// // Prints "3" /// /// While seemingly simple, this capability gives you access to a large number /// of operations that you can perform on any sequence. As an example, to /// check whether a sequence includes a particular value, you can test each /// value sequentially until you've found a match or reached the end of the /// sequence. This example checks to see whether a particular insect is in an /// array. /// /// let bugs = ["Aphid", "Bumblebee", "Cicada", "Damselfly", "Earwig"] /// var hasMosquito = false /// for bug in bugs { /// if bug == "Mosquito" { /// hasMosquito = true /// break /// } /// } /// print("'bugs' has a mosquito: \(hasMosquito)") /// // Prints "'bugs' has a mosquito: false" /// /// The `Sequence` protocol provides default implementations for many common /// operations that depend on sequential access to a sequence's values. For /// clearer, more concise code, the example above could use the array's /// `contains(_:)` method, which every sequence inherits from `Sequence`, /// instead of iterating manually: /// /// if bugs.contains("Mosquito") { /// print("Break out the bug spray.") /// } else { /// print("Whew, no mosquitos!") /// } /// // Prints "Whew, no mosquitos!" /// /// Repeated Access /// =============== /// /// The `Sequence` protocol makes no requirement on conforming types regarding /// whether they will be destructively consumed by iteration. As a /// consequence, don't assume that multiple `for`-`in` loops on a sequence /// will either resume iteration or restart from the beginning: /// /// for element in sequence { /// if ... some condition { break } /// } /// /// for element in sequence { /// // No defined behavior /// } /// /// In this case, you cannot assume either that a sequence will be consumable /// and will resume iteration, or that a sequence is a collection and will /// restart iteration from the first element. A conforming sequence that is /// not a collection is allowed to produce an arbitrary sequence of elements /// in the second `for`-`in` loop. /// /// To establish that a type you've created supports nondestructive iteration, /// add conformance to the `Collection` protocol. /// /// Conforming to the Sequence Protocol /// =================================== /// /// Making your own custom types conform to `Sequence` enables many useful /// operations, like `for`-`in` looping and the `contains` method, without /// much effort. To add `Sequence` conformance to your own custom type, add a /// `makeIterator()` method that returns an iterator. /// /// Alternatively, if your type can act as its own iterator, implementing the /// requirements of the `IteratorProtocol` protocol and declaring conformance /// to both `Sequence` and `IteratorProtocol` are sufficient. /// /// Here's a definition of a `Countdown` sequence that serves as its own /// iterator. The `makeIterator()` method is provided as a default /// implementation. /// /// struct Countdown: Sequence, IteratorProtocol { /// var count: Int /// /// mutating func next() -> Int? { /// if count == 0 { /// return nil /// } else { /// defer { count -= 1 } /// return count /// } /// } /// } /// /// let threeToGo = Countdown(count: 3) /// for i in threeToGo { /// print(i) /// } /// // Prints "3" /// // Prints "2" /// // Prints "1" /// /// Expected Performance /// ==================== /// /// A sequence should provide its iterator in O(1). The `Sequence` protocol /// makes no other requirements about element access, so routines that /// traverse a sequence should be considered O(*n*) unless documented /// otherwise. public protocol Sequence { /// A type representing the sequence's elements. associatedtype Element /// A type that provides the sequence's iteration interface and /// encapsulates its iteration state. associatedtype Iterator: IteratorProtocol where Iterator.Element == Element // FIXME: <rdar://problem/34142121> // This typealias should be removed as it predates the source compatibility // guarantees of Swift 3, but it cannot due to a bug. @available(*, unavailable, renamed: "Iterator") typealias Generator = Iterator /// A type that represents a subsequence of some of the sequence's elements. // associatedtype SubSequence: Sequence = AnySequence<Element> // where Element == SubSequence.Element, // SubSequence.SubSequence == SubSequence // typealias SubSequence = AnySequence<Element> /// Returns an iterator over the elements of this sequence. __consuming func makeIterator() -> Iterator /// A value less than or equal to the number of elements in the sequence, /// calculated nondestructively. /// /// The default implementation returns 0. If you provide your own /// implementation, make sure to compute the value nondestructively. /// /// - Complexity: O(1), except if the sequence also conforms to `Collection`. /// In this case, see the documentation of `Collection.underestimatedCount`. var underestimatedCount: Int { get } func _customContainsEquatableElement( _ element: Element ) -> Bool? /// Create a native array buffer containing the elements of `self`, /// in the same order. __consuming func _copyToContiguousArray() -> ContiguousArray<Element> /// Copy `self` into an unsafe buffer, initializing its memory. /// /// The default implementation simply iterates over the elements of the /// sequence, initializing the buffer one item at a time. /// /// For sequences whose elements are stored in contiguous chunks of memory, /// it may be more efficient to copy them in bulk, using the /// `UnsafeMutablePointer.initialize(from:count:)` method. /// /// - Parameter ptr: An unsafe buffer addressing uninitialized memory. The /// buffer must be of sufficient size to accommodate /// `source.underestimatedCount` elements. (Some implementations trap /// if given a buffer that's smaller than this.) /// /// - Returns: `(it, c)`, where `c` is the number of elements copied into the /// buffer, and `it` is a partially consumed iterator that can be used to /// retrieve elements that did not fit into the buffer (if any). (This can /// only happen if `underestimatedCount` turned out to be an actual /// underestimate, and the buffer did not contain enough space to hold the /// entire sequence.) /// /// On return, the memory region in `buffer[0 ..< c]` is initialized to /// the first `c` elements in the sequence. __consuming func _copyContents( initializing ptr: UnsafeMutableBufferPointer<Element> ) -> (Iterator,UnsafeMutableBufferPointer<Element>.Index) /// Executes a closure on the sequence’s contiguous storage. /// /// This method calls `body(buffer)`, where `buffer` is a pointer to the /// collection’s contiguous storage. If the contiguous storage doesn't exist, /// the collection creates it. If the collection doesn’t support an internal /// representation in a form of contiguous storage, the method doesn’t call /// `body` --- it immediately returns `nil`. /// /// The optimizer can often eliminate bounds- and uniqueness-checking /// within an algorithm. When that fails, however, invoking the same /// algorithm on the `buffer` argument may let you trade safety for speed. /// /// Successive calls to this method may provide a different pointer on each /// call. Don't store `buffer` outside of this method. /// /// A `Collection` that provides its own implementation of this method /// must provide contiguous storage to its elements in the same order /// as they appear in the collection. This guarantees that it's possible to /// generate contiguous mutable storage to any of its subsequences by slicing /// `buffer` with a range formed from the distances to the subsequence's /// `startIndex` and `endIndex`, respectively. /// /// - Parameters: /// - body: A closure that receives an `UnsafeBufferPointer` to the /// sequence's contiguous storage. /// - Returns: The value returned from `body`, unless the sequence doesn't /// support contiguous storage, in which case the method ignores `body` and /// returns `nil`. func withContiguousStorageIfAvailable<R>( _ body: (_ buffer: UnsafeBufferPointer<Element>) throws -> R ) rethrows -> R? } // Provides a default associated type witness for Iterator when the // Self type is both a Sequence and an Iterator. extension Sequence where Self: IteratorProtocol { // @_implements(Sequence, Iterator) public typealias _Default_Iterator = Self } /// A default makeIterator() function for `IteratorProtocol` instances that /// are declared to conform to `Sequence` extension Sequence where Self.Iterator == Self { /// Returns an iterator over the elements of this sequence. @inlinable public __consuming func makeIterator() -> Self { return self } } /// A sequence that lazily consumes and drops `n` elements from an underlying /// `Base` iterator before possibly returning the first available element. /// /// The underlying iterator's sequence may be infinite. @frozen public struct DropFirstSequence<Base: Sequence> { @usableFromInline internal let _base: Base @usableFromInline internal let _limit: Int @inlinable public init(_ base: Base, dropping limit: Int) { _precondition(limit >= 0, "Can't drop a negative number of elements from a sequence") _base = base _limit = limit } } extension DropFirstSequence: Sequence { public typealias Element = Base.Element public typealias Iterator = Base.Iterator public typealias SubSequence = AnySequence<Element> @inlinable public __consuming func makeIterator() -> Iterator { var it = _base.makeIterator() var dropped = 0 while dropped < _limit, it.next() != nil { dropped &+= 1 } return it } @inlinable public __consuming func dropFirst(_ k: Int) -> DropFirstSequence<Base> { // If this is already a _DropFirstSequence, we need to fold in // the current drop count and drop limit so no data is lost. // // i.e. [1,2,3,4].dropFirst(1).dropFirst(1) should be equivalent to // [1,2,3,4].dropFirst(2). return DropFirstSequence(_base, dropping: _limit + k) } } /// A sequence that only consumes up to `n` elements from an underlying /// `Base` iterator. /// /// The underlying iterator's sequence may be infinite. @frozen public struct PrefixSequence<Base: Sequence> { @usableFromInline internal var _base: Base @usableFromInline internal let _maxLength: Int @inlinable public init(_ base: Base, maxLength: Int) { _precondition(maxLength >= 0, "Can't take a prefix of negative length") _base = base _maxLength = maxLength } } extension PrefixSequence { @frozen public struct Iterator { @usableFromInline internal var _base: Base.Iterator @usableFromInline internal var _remaining: Int @inlinable internal init(_ base: Base.Iterator, maxLength: Int) { _base = base _remaining = maxLength } } } extension PrefixSequence.Iterator: IteratorProtocol { public typealias Element = Base.Element @inlinable public mutating func next() -> Element? { if _remaining != 0 { _remaining &-= 1 return _base.next() } else { return nil } } } extension PrefixSequence: Sequence { @inlinable public __consuming func makeIterator() -> Iterator { return Iterator(_base.makeIterator(), maxLength: _maxLength) } @inlinable public __consuming func prefix(_ maxLength: Int) -> PrefixSequence<Base> { let length = Swift.min(maxLength, self._maxLength) return PrefixSequence(_base, maxLength: length) } } /// A sequence that lazily consumes and drops `n` elements from an underlying /// `Base` iterator before possibly returning the first available element. /// /// The underlying iterator's sequence may be infinite. @frozen public struct DropWhileSequence<Base: Sequence> { public typealias Element = Base.Element @usableFromInline internal var _iterator: Base.Iterator @usableFromInline internal var _nextElement: Element? @inlinable internal init(iterator: Base.Iterator, predicate: (Element) throws -> Bool) rethrows { _iterator = iterator _nextElement = _iterator.next() while let x = _nextElement, try predicate(x) { _nextElement = _iterator.next() } } @inlinable internal init(_ base: Base, predicate: (Element) throws -> Bool) rethrows { self = try DropWhileSequence(iterator: base.makeIterator(), predicate: predicate) } } extension DropWhileSequence { @frozen public struct Iterator { @usableFromInline internal var _iterator: Base.Iterator @usableFromInline internal var _nextElement: Element? @inlinable internal init(_ iterator: Base.Iterator, nextElement: Element?) { _iterator = iterator _nextElement = nextElement } } } extension DropWhileSequence.Iterator: IteratorProtocol { public typealias Element = Base.Element @inlinable public mutating func next() -> Element? { guard let next = _nextElement else { return nil } _nextElement = _iterator.next() return next } } extension DropWhileSequence: Sequence { @inlinable public func makeIterator() -> Iterator { return Iterator(_iterator, nextElement: _nextElement) } @inlinable public __consuming func drop( while predicate: (Element) throws -> Bool ) rethrows -> DropWhileSequence<Base> { guard let x = _nextElement, try predicate(x) else { return self } return try DropWhileSequence(iterator: _iterator, predicate: predicate) } } //===----------------------------------------------------------------------===// // Default implementations for Sequence //===----------------------------------------------------------------------===// extension Sequence { /// Returns an array containing the results of mapping the given closure /// over the sequence's elements. /// /// In this example, `map` is used first to convert the names in the array /// to lowercase strings and then to count their characters. /// /// let cast = ["Vivien", "Marlon", "Kim", "Karl"] /// let lowercaseNames = cast.map { $0.lowercased() } /// // 'lowercaseNames' == ["vivien", "marlon", "kim", "karl"] /// let letterCounts = cast.map { $0.count } /// // 'letterCounts' == [6, 6, 3, 4] /// /// - Parameter transform: A mapping closure. `transform` accepts an /// element of this sequence as its parameter and returns a transformed /// value of the same or of a different type. /// - Returns: An array containing the transformed elements of this /// sequence. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @inlinable public func map<T>( _ transform: (Element) throws -> T ) rethrows -> [T] { let initialCapacity = underestimatedCount var result = ContiguousArray<T>() result.reserveCapacity(initialCapacity) var iterator = self.makeIterator() // Add elements up to the initial capacity without checking for regrowth. for _ in 0..<initialCapacity { result.append(try transform(iterator.next()!)) } // Add remaining elements, if any. while let element = iterator.next() { result.append(try transform(element)) } return Array(result) } /// Returns an array containing, in order, the elements of the sequence /// that satisfy the given predicate. /// /// In this example, `filter(_:)` is used to include only names shorter than /// five characters. /// /// let cast = ["Vivien", "Marlon", "Kim", "Karl"] /// let shortNames = cast.filter { $0.count < 5 } /// print(shortNames) /// // Prints "["Kim", "Karl"]" /// /// - Parameter isIncluded: A closure that takes an element of the /// sequence as its argument and returns a Boolean value indicating /// whether the element should be included in the returned array. /// - Returns: An array of the elements that `isIncluded` allowed. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @inlinable public __consuming func filter( _ isIncluded: (Element) throws -> Bool ) rethrows -> [Element] { return try _filter(isIncluded) } @_transparent public func _filter( _ isIncluded: (Element) throws -> Bool ) rethrows -> [Element] { var result = ContiguousArray<Element>() var iterator = self.makeIterator() while let element = iterator.next() { if try isIncluded(element) { result.append(element) } } return Array(result) } /// A value less than or equal to the number of elements in the sequence, /// calculated nondestructively. /// /// The default implementation returns 0. If you provide your own /// implementation, make sure to compute the value nondestructively. /// /// - Complexity: O(1), except if the sequence also conforms to `Collection`. /// In this case, see the documentation of `Collection.underestimatedCount`. @inlinable public var underestimatedCount: Int { return 0 } @inlinable @inline(__always) public func _customContainsEquatableElement( _ element: Iterator.Element ) -> Bool? { return nil } /// Calls the given closure on each element in the sequence in the same order /// as a `for`-`in` loop. /// /// The two loops in the following example produce the same output: /// /// let numberWords = ["one", "two", "three"] /// for word in numberWords { /// print(word) /// } /// // Prints "one" /// // Prints "two" /// // Prints "three" /// /// numberWords.forEach { word in /// print(word) /// } /// // Same as above /// /// Using the `forEach` method is distinct from a `for`-`in` loop in two /// important ways: /// /// 1. You cannot use a `break` or `continue` statement to exit the current /// call of the `body` closure or skip subsequent calls. /// 2. Using the `return` statement in the `body` closure will exit only from /// the current call to `body`, not from any outer scope, and won't skip /// subsequent calls. /// /// - Parameter body: A closure that takes an element of the sequence as a /// parameter. @_semantics("sequence.forEach") @inlinable public func forEach( _ body: (Element) throws -> Void ) rethrows { for element in self { try body(element) } } } extension Sequence { /// Returns the first element of the sequence that satisfies the given /// predicate. /// /// The following example uses the `first(where:)` method to find the first /// negative number in an array of integers: /// /// let numbers = [3, 7, 4, -2, 9, -6, 10, 1] /// if let firstNegative = numbers.first(where: { $0 < 0 }) { /// print("The first negative number is \(firstNegative).") /// } /// // Prints "The first negative number is -2." /// /// - Parameter predicate: A closure that takes an element of the sequence as /// its argument and returns a Boolean value indicating whether the /// element is a match. /// - Returns: The first element of the sequence that satisfies `predicate`, /// or `nil` if there is no element that satisfies `predicate`. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @inlinable public func first( where predicate: (Element) throws -> Bool ) rethrows -> Element? { for element in self { if try predicate(element) { return element } } return nil } } extension Sequence where Element: Equatable { /// Returns the longest possible subsequences of the sequence, in order, /// around elements equal to the given element. /// /// The resulting array consists of at most `maxSplits + 1` subsequences. /// Elements that are used to split the sequence are not returned as part of /// any subsequence. /// /// The following examples show the effects of the `maxSplits` and /// `omittingEmptySubsequences` parameters when splitting a string at each /// space character (" "). The first use of `split` returns each word that /// was originally separated by one or more spaces. /// /// let line = "BLANCHE: I don't want realism. I want magic!" /// print(line.split(separator: " ") /// .map(String.init)) /// // Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]" /// /// The second example passes `1` for the `maxSplits` parameter, so the /// original string is split just once, into two new strings. /// /// print(line.split(separator: " ", maxSplits: 1) /// .map(String.init)) /// // Prints "["BLANCHE:", " I don\'t want realism. I want magic!"]" /// /// The final example passes `false` for the `omittingEmptySubsequences` /// parameter, so the returned array contains empty strings where spaces /// were repeated. /// /// print(line.split(separator: " ", omittingEmptySubsequences: false) /// .map(String.init)) /// // Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]" /// /// - Parameters: /// - separator: The element that should be split upon. /// - maxSplits: The maximum number of times to split the sequence, or one /// less than the number of subsequences to return. If `maxSplits + 1` /// subsequences are returned, the last one is a suffix of the original /// sequence containing the remaining elements. `maxSplits` must be /// greater than or equal to zero. The default value is `Int.max`. /// - omittingEmptySubsequences: If `false`, an empty subsequence is /// returned in the result for each consecutive pair of `separator` /// elements in the sequence and for each instance of `separator` at the /// start or end of the sequence. If `true`, only nonempty subsequences /// are returned. The default value is `true`. /// - Returns: An array of subsequences, split from this sequence's elements. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @inlinable public __consuming func split( separator: Element, maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true ) -> [ArraySlice<Element>] { return split( maxSplits: maxSplits, omittingEmptySubsequences: omittingEmptySubsequences, whereSeparator: { $0 == separator }) } } extension Sequence { /// Returns the longest possible subsequences of the sequence, in order, that /// don't contain elements satisfying the given predicate. Elements that are /// used to split the sequence are not returned as part of any subsequence. /// /// The following examples show the effects of the `maxSplits` and /// `omittingEmptySubsequences` parameters when splitting a string using a /// closure that matches spaces. The first use of `split` returns each word /// that was originally separated by one or more spaces. /// /// let line = "BLANCHE: I don't want realism. I want magic!" /// print(line.split(whereSeparator: { $0 == " " }) /// .map(String.init)) /// // Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]" /// /// The second example passes `1` for the `maxSplits` parameter, so the /// original string is split just once, into two new strings. /// /// print( /// line.split(maxSplits: 1, whereSeparator: { $0 == " " }) /// .map(String.init)) /// // Prints "["BLANCHE:", " I don\'t want realism. I want magic!"]" /// /// The final example passes `true` for the `allowEmptySlices` parameter, so /// the returned array contains empty strings where spaces were repeated. /// /// print( /// line.split( /// omittingEmptySubsequences: false, /// whereSeparator: { $0 == " " } /// ).map(String.init)) /// // Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]" /// /// - Parameters: /// - maxSplits: The maximum number of times to split the sequence, or one /// less than the number of subsequences to return. If `maxSplits + 1` /// subsequences are returned, the last one is a suffix of the original /// sequence containing the remaining elements. `maxSplits` must be /// greater than or equal to zero. The default value is `Int.max`. /// - omittingEmptySubsequences: If `false`, an empty subsequence is /// returned in the result for each pair of consecutive elements /// satisfying the `isSeparator` predicate and for each element at the /// start or end of the sequence satisfying the `isSeparator` predicate. /// If `true`, only nonempty subsequences are returned. The default /// value is `true`. /// - isSeparator: A closure that returns `true` if its argument should be /// used to split the sequence; otherwise, `false`. /// - Returns: An array of subsequences, split from this sequence's elements. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @inlinable public __consuming func split( maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true, whereSeparator isSeparator: (Element) throws -> Bool ) rethrows -> [ArraySlice<Element>] { _precondition(maxSplits >= 0, "Must take zero or more splits") let whole = Array(self) return try whole.split( maxSplits: maxSplits, omittingEmptySubsequences: omittingEmptySubsequences, whereSeparator: isSeparator) } /// Returns a subsequence, up to the given maximum length, containing the /// final elements of the sequence. /// /// The sequence must be finite. If the maximum length exceeds the number of /// elements in the sequence, the result contains all the elements in the /// sequence. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.suffix(2)) /// // Prints "[4, 5]" /// print(numbers.suffix(10)) /// // Prints "[1, 2, 3, 4, 5]" /// /// - Parameter maxLength: The maximum number of elements to return. The /// value of `maxLength` must be greater than or equal to zero. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @inlinable public __consuming func suffix(_ maxLength: Int) -> [Element] { _precondition(maxLength >= 0, "Can't take a suffix of negative length from a sequence") guard maxLength != 0 else { return [] } // FIXME: <rdar://problem/21885650> Create reusable RingBuffer<T> // Put incoming elements into a ring buffer to save space. Once all // elements are consumed, reorder the ring buffer into a copy and return it. // This saves memory for sequences particularly longer than `maxLength`. var ringBuffer = ContiguousArray<Element>() ringBuffer.reserveCapacity(Swift.min(maxLength, underestimatedCount)) var i = 0 for element in self { if ringBuffer.count < maxLength { ringBuffer.append(element) } else { ringBuffer[i] = element i = (i + 1) % maxLength } } if i != ringBuffer.startIndex { var rotated = ContiguousArray<Element>() rotated.reserveCapacity(ringBuffer.count) rotated += ringBuffer[i..<ringBuffer.endIndex] rotated += ringBuffer[0..<i] return Array(rotated) } else { return Array(ringBuffer) } } /// Returns a sequence containing all but the given number of initial /// elements. /// /// If the number of elements to drop exceeds the number of elements in /// the sequence, the result is an empty sequence. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.dropFirst(2)) /// // Prints "[3, 4, 5]" /// print(numbers.dropFirst(10)) /// // Prints "[]" /// /// - Parameter k: The number of elements to drop from the beginning of /// the sequence. `k` must be greater than or equal to zero. /// - Returns: A sequence starting after the specified number of /// elements. /// /// - Complexity: O(1), with O(*k*) deferred to each iteration of the result, /// where *k* is the number of elements to drop from the beginning of /// the sequence. @inlinable public __consuming func dropFirst(_ k: Int = 1) -> DropFirstSequence<Self> { return DropFirstSequence(self, dropping: k) } /// Returns a sequence containing all but the given number of final /// elements. /// /// The sequence must be finite. If the number of elements to drop exceeds /// the number of elements in the sequence, the result is an empty /// sequence. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.dropLast(2)) /// // Prints "[1, 2, 3]" /// print(numbers.dropLast(10)) /// // Prints "[]" /// /// - Parameter n: The number of elements to drop off the end of the /// sequence. `n` must be greater than or equal to zero. /// - Returns: A sequence leaving off the specified number of elements. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @inlinable public __consuming func dropLast(_ k: Int = 1) -> [Element] { _precondition(k >= 0, "Can't drop a negative number of elements from a sequence") guard k != 0 else { return Array(self) } // FIXME: <rdar://problem/21885650> Create reusable RingBuffer<T> // Put incoming elements from this sequence in a holding tank, a ring buffer // of size <= k. If more elements keep coming in, pull them out of the // holding tank into the result, an `Array`. This saves // `k` * sizeof(Element) of memory, because slices keep the entire // memory of an `Array` alive. var result = ContiguousArray<Element>() var ringBuffer = ContiguousArray<Element>() var i = ringBuffer.startIndex for element in self { if ringBuffer.count < k { ringBuffer.append(element) } else { result.append(ringBuffer[i]) ringBuffer[i] = element i = (i + 1) % k } } return Array(result) } /// Returns a sequence by skipping the initial, consecutive elements that /// satisfy the given predicate. /// /// The following example uses the `drop(while:)` method to skip over the /// positive numbers at the beginning of the `numbers` array. The result /// begins with the first element of `numbers` that does not satisfy /// `predicate`. /// /// let numbers = [3, 7, 4, -2, 9, -6, 10, 1] /// let startingWithNegative = numbers.drop(while: { $0 > 0 }) /// // startingWithNegative == [-2, 9, -6, 10, 1] /// /// If `predicate` matches every element in the sequence, the result is an /// empty sequence. /// /// - Parameter predicate: A closure that takes an element of the sequence as /// its argument and returns a Boolean value indicating whether the /// element should be included in the result. /// - Returns: A sequence starting after the initial, consecutive elements /// that satisfy `predicate`. /// /// - Complexity: O(*k*), where *k* is the number of elements to drop from /// the beginning of the sequence. @inlinable public __consuming func drop( while predicate: (Element) throws -> Bool ) rethrows -> DropWhileSequence<Self> { return try DropWhileSequence(self, predicate: predicate) } /// Returns a sequence, up to the specified maximum length, containing the /// initial elements of the sequence. /// /// If the maximum length exceeds the number of elements in the sequence, /// the result contains all the elements in the sequence. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.prefix(2)) /// // Prints "[1, 2]" /// print(numbers.prefix(10)) /// // Prints "[1, 2, 3, 4, 5]" /// /// - Parameter maxLength: The maximum number of elements to return. The /// value of `maxLength` must be greater than or equal to zero. /// - Returns: A sequence starting at the beginning of this sequence /// with at most `maxLength` elements. /// /// - Complexity: O(1) @inlinable public __consuming func prefix(_ maxLength: Int) -> PrefixSequence<Self> { return PrefixSequence(self, maxLength: maxLength) } /// Returns a sequence containing the initial, consecutive elements that /// satisfy the given predicate. /// /// The following example uses the `prefix(while:)` method to find the /// positive numbers at the beginning of the `numbers` array. Every element /// of `numbers` up to, but not including, the first negative value is /// included in the result. /// /// let numbers = [3, 7, 4, -2, 9, -6, 10, 1] /// let positivePrefix = numbers.prefix(while: { $0 > 0 }) /// // positivePrefix == [3, 7, 4] /// /// If `predicate` matches every element in the sequence, the resulting /// sequence contains every element of the sequence. /// /// - Parameter predicate: A closure that takes an element of the sequence as /// its argument and returns a Boolean value indicating whether the /// element should be included in the result. /// - Returns: A sequence of the initial, consecutive elements that /// satisfy `predicate`. /// /// - Complexity: O(*k*), where *k* is the length of the result. @inlinable public __consuming func prefix( while predicate: (Element) throws -> Bool ) rethrows -> [Element] { var result = ContiguousArray<Element>() for element in self { guard try predicate(element) else { break } result.append(element) } return Array(result) } } extension Sequence { /// Copy `self` into an unsafe buffer, initializing its memory. /// /// The default implementation simply iterates over the elements of the /// sequence, initializing the buffer one item at a time. /// /// For sequences whose elements are stored in contiguous chunks of memory, /// it may be more efficient to copy them in bulk, using the /// `UnsafeMutablePointer.initialize(from:count:)` method. /// /// - Parameter ptr: An unsafe buffer addressing uninitialized memory. The /// buffer must be of sufficient size to accommodate /// `source.underestimatedCount` elements. (Some implementations trap /// if given a buffer that's smaller than this.) /// /// - Returns: `(it, c)`, where `c` is the number of elements copied into the /// buffer, and `it` is a partially consumed iterator that can be used to /// retrieve elements that did not fit into the buffer (if any). (This can /// only happen if `underestimatedCount` turned out to be an actual /// underestimate, and the buffer did not contain enough space to hold the /// entire sequence.) /// /// On return, the memory region in `buffer[0 ..< c]` is initialized to /// the first `c` elements in the sequence. @inlinable public __consuming func _copyContents( initializing buffer: UnsafeMutableBufferPointer<Element> ) -> (Iterator,UnsafeMutableBufferPointer<Element>.Index) { return _copySequenceContents(initializing: buffer) } @_alwaysEmitIntoClient internal __consuming func _copySequenceContents( initializing buffer: UnsafeMutableBufferPointer<Element> ) -> (Iterator,UnsafeMutableBufferPointer<Element>.Index) { var it = self.makeIterator() guard var ptr = buffer.baseAddress else { return (it,buffer.startIndex) } for idx in buffer.startIndex..<buffer.count { guard let x = it.next() else { return (it, idx) } ptr.initialize(to: x) ptr += 1 } return (it,buffer.endIndex) } @inlinable public func withContiguousStorageIfAvailable<R>( _ body: (UnsafeBufferPointer<Element>) throws -> R ) rethrows -> R? { return nil } } // FIXME(ABI)#182 // Pending <rdar://problem/14011860> and <rdar://problem/14396120>, // pass an IteratorProtocol through IteratorSequence to give it "Sequence-ness" /// A sequence built around an iterator of type `Base`. /// /// Useful mostly to recover the ability to use `for`...`in`, /// given just an iterator `i`: /// /// for x in IteratorSequence(i) { ... } @frozen public struct IteratorSequence<Base: IteratorProtocol> { @usableFromInline internal var _base: Base /// Creates an instance whose iterator is a copy of `base`. @inlinable public init(_ base: Base) { _base = base } } extension IteratorSequence: IteratorProtocol, Sequence { /// Advances to the next element and returns it, or `nil` if no next element /// exists. /// /// Once `nil` has been returned, all subsequent calls return `nil`. /// /// - Precondition: `next()` has not been applied to a copy of `self` /// since the copy was made. @inlinable public mutating func next() -> Base.Element? { return _base.next() } } extension IteratorSequence: Sendable where Base: Sendable { } /* FIXME: ideally for compatibility we would declare extension Sequence { @available(swift, deprecated: 5, message: "") public typealias SubSequence = AnySequence<Element> } */
apache-2.0
ab295d45713cb16a8ef3511ee097dad7
36.358933
100
0.642936
4.350687
false
false
false
false
StanZabroda/Hydra
Hydra/AuthController.swift
1
3274
import UIKit class AuthController: UIViewController,VKSdkDelegate { var motionView:UIImageView! var authButton: UIButton! var authLogo:UIImageView! override func loadView() { super.loadView() VKSdk.initializeWithDelegate(self, andAppId: "4689635") if VKSdk.wakeUpSession() == true { self.startWorking() } } override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.blackColor() self.setNeedsStatusBarAppearanceUpdate() } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) self.motionView = UIImageView(frame: CGRectMake(0, 0, screenSizeWidth, screenSizeHeight)) self.motionView.image = UIImage(named: "placeholderBackground") self.view.addSubview(self.motionView) self.motionView.frame = CGRectMake(0, 0, screenSizeWidth, screenSizeHeight) self.authButton = UIButton(frame: CGRectMake(screenSizeWidth/2 - 100, screenSizeHeight-150, 200, 50)) self.authButton.setTitle("Авторизация", forState: UIControlState.Normal) self.authButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal) self.authButton.setTitleColor(UIColor.grayColor(), forState: UIControlState.Highlighted) self.authButton.setBackgroundImage(UIImage(named: "authButton"), forState: UIControlState.Normal) self.authButton.addTarget(self, action: "authButtonAction", forControlEvents: UIControlEvents.TouchUpInside) self.view.addSubview(self.authButton) self.authLogo = UIImageView(frame: CGRectMake(screenSizeWidth/2 - 100, 100, 200, 200)) self.authLogo.image = UIImage(named: "authLogo") self.view.addSubview(self.authLogo) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() } func authButtonAction() { log.debug("auth button action") VKSdk.authorize(["audio","status"], revokeAccess: true, forceOAuth: true, inApp: true) } func startWorking() { dispatch.async.main { () -> Void in HRInterfaceManager.sharedInstance.openDrawer() self.presentViewController(HRInterfaceManager.sharedInstance.mainNav, animated: false, completion: nil) } } func vkSdkNeedCaptchaEnter(captchaError: VKError!) { // } func vkSdkTokenHasExpired(expiredToken: VKAccessToken!) { // } func vkSdkReceivedNewToken(newToken: VKAccessToken!) { self.startWorking() } func vkSdkShouldPresentViewController(controller: UIViewController!) { self.presentViewController(controller, animated: true, completion: nil) } func vkSdkAcceptedUserToken(token: VKAccessToken!) { self.startWorking() } func vkSdkUserDeniedAccess(authorizationError: VKError!) { // } override func preferredStatusBarStyle() -> UIStatusBarStyle { return UIStatusBarStyle.LightContent } }
mit
b58247694e5289fb1b3a381aeaec1efe
29.783019
116
0.638063
5.130503
false
false
false
false
arvedviehweger/swift
test/Parse/ConditionalCompilation/identifierName.swift
1
1928
// RUN: %target-typecheck-verify-swift // Ensure that the identifiers in compilation conditions don't reference // any decls in the scope. func f2( FOO: Int, swift: Int, _compiler_version: Int, os: Int, arch: Int, _endian: Int, _runtime: Int, arm: Int, i386: Int, macOS: Int, OSX: Int, Linux: Int, big: Int, little: Int, _ObjC: Int, _Native: Int ) { #if FOO _ = FOO #elseif os(macOS) && os(OSX) && os(Linux) _ = os + macOS + OSX + Linux #elseif arch(i386) && arch(arm) _ = arch + i386 + arm #elseif _endian(big) && _endian(little) _ = _endian + big + little #elseif _runtime(_ObjC) && _runtime(_Native) _ = _runtime + _ObjC + _Native #elseif swift(>=1.0) && _compiler_version("3.*.0") _ = swift + _compiler_version #endif } func f2() { let FOO = 1, swift = 1, _compiler_version = 1, os = 1, arch = 1, _endian = 1, _runtime = 1, arm = 1, i386 = 1, macOS = 1, OSX = 1, Linux = 1, big = 1, little = 1, _ObjC = 1, _Native = 1 #if FOO _ = FOO #elseif os(macOS) && os(OSX) && os(Linux) _ = os + macOS + OSX + Linux #elseif arch(i386) && arch(arm) _ = arch + i386 + arm #elseif _endian(big) && _endian(little) _ = _endian + big + little #elseif _runtime(_ObjC) && _runtime(_Native) _ = _runtime + _ObjC + _Native #elseif swift(>=1.0) && _compiler_version("3.*.0") _ = swift + _compiler_version #endif } struct S { let FOO = 1, swift = 1, _compiler_version = 1, os = 1, arch = 1, _endian = 1, _runtime = 1, arm = 1, i386 = 1, macOS = 1, OSX = 1, Linux = 1, big = 1, little = 1, _ObjC = 1, _Native = 1 #if FOO #elseif os(macOS) && os(OSX) && os(Linux) #elseif arch(i386) && arch(arm) #elseif _endian(big) && _endian(little) #elseif _runtime(_ObjC) && _runtime(_Native) #elseif swift(>=1.0) && _compiler_version("3.*.0") #endif } /// Ensure 'variable used within its own initial value' not to be emitted. let BAR = { () -> Void in #if BAR #endif }
apache-2.0
448d1a9631172f3484aba53699f98628
24.368421
74
0.582988
2.782107
false
false
false
false
iabudiab/HTMLKit
HTMLKit.playground/Pages/Parsing Fragments.xcplaygroundpage/Contents.swift
1
717
//: [Previous](@previous) /*: # Parsing Document Fragments */ import HTMLKit /*: Given some HTML content */ let htmlString = "<div><p>Hello HTMLKit</p></div><td>some table data" /*: You can prase it as a document fragment in a specified context element: */ let parser = HTMLParser(string: htmlString) let tableContext = HTMLElement(tagName: "table") var elements = parser.parseFragment(withContextElement: tableContext) for element in elements { print(element.outerHTML) } /*: The same parser instance can be reusued: */ let bodyContext = HTMLElement(tagName: "body") elements = parser.parseFragment(withContextElement: bodyContext) for element in elements { print(element.outerHTML) } //: [Next](@next)
mit
dc26a7794fa2eb88a7d9c7bf6b56946f
17.868421
71
0.735007
3.585
false
false
false
false
danielrcardenas/ac-course-2017
frameworks/SwarmChemistry-Swif/Demo_ScreenSaver/Defaults.swift
1
1059
// // Defaults.swift // SwarmChemistry // // Created by mitsuyoshi.yamazaki on 2017/09/07. // Copyright © 2017 Mitsuyoshi Yamazaki. All rights reserved. // import Foundation import ScreenSaver import SwarmChemistry internal class Defaults { fileprivate static var moduleName: String { let bundle = Bundle.init(for: self) return bundle.bundleIdentifier! } fileprivate static var defaults: ScreenSaverDefaults { return ScreenSaverDefaults.init(forModuleWithName: moduleName)! } fileprivate static func fullKey(of key: String) -> String { return moduleName + "." + key } } extension Defaults { static var selectedRecipe: Recipe? { get { guard let recipeName = defaults.object(forKey: fullKey(of: "selectedRecipeName")) as? String else { return nil } return Recipe.presetRecipes.filter { $0.name == recipeName }.first } set { let defaults = self.defaults defaults.set(newValue?.name, forKey: fullKey(of: "selectedRecipeName")) defaults.synchronize() } } }
apache-2.0
94fa288240d6cbf03eac2b5ccea82efa
23.604651
105
0.689981
4.266129
false
false
false
false
alokc83/rayW-SwiftSeries
RW-SwiftSeries-controlStatment-challenge6.playground/Contents.swift
1
769
//: Playground - noun: a place where people can play import UIKit for var i=0; i<10; i++ { println(i) } for j in 1..<10{ println(j) } for k in 1...10{ println(k) } var counter = 10 while(counter > 0){ counter -= 1 } var c = 10 do { println(c) c -= 1 }while (c>0) var movieList = [1:"Jurrassic World", 2:"Spy", 3:"Terminator"] for (_,value) in movieList{ println("\(value)") } // challenge 6 for i in 1...100{ let multipleOf3 = i%3 == 0 let multipleOf5 = i%5 == 0 if multipleOf3 && multipleOf5{ println("fizzBuzz") } else if multipleOf3{ println("Fizz") } else if multipleOf5{ println("Buzz") } else{ println("No fizz, no Buzz, no fizzBuzz") } }
mit
6a74ab0d2cad098c2ab1218b41380772
13.259259
62
0.540962
3.088353
false
false
false
false
chayelheinsen/GamingStreams-tvOS-App
StreamCenter/HitboxAPI.swift
3
10750
// // HitboxAPI.swift // GamingStreamsTVApp // // Created by Brendan Kirchner on 10/12/15. // Copyright © 2015 Rivus Media Inc. All rights reserved. // import UIKit import Alamofire class HitboxAPI { enum HitboxError: ErrorType { case URLError case JSONError case AuthError case NoAuthTokenError case OtherError var errorDescription: String { get { switch self { case .URLError: return "There was an error with the request." case .JSONError: return "There was an error parsing the JSON." case .AuthError: return "The user is not authenticated." case .NoAuthTokenError: return "There was no auth token provided in the response data." case .OtherError: return "An unidentified error occured." } } } var recoverySuggestion: String { get { switch self { case .URLError: return "Please make sure that the url is formatted correctly." case .JSONError: return "Please check the request information and response." case .AuthError: return "Please make sure to authenticate with Twitch before attempting to load this data." case .NoAuthTokenError: return "Please check the server logs and response." case .OtherError: return "Sorry, there's no provided solution for this error." } } } } ///This is a method to retrieve the most popular Hitbox games and we filter it to only games that have streams with content that is live at the moment /// /// - parameters: /// - offset: An integer offset to load content after the primary results (useful when you reach the end of a scrolling list) /// - limit: The number of games to return /// - searchTerm: An optional search term /// - completionHandler: A closure providing results and an error (both optionals) to be executed once the request completes static func getGames(offset: Int, limit: Int, searchTerm: String? = nil, completionHandler: (games: [HitboxGame]?, error: HitboxError?) -> ()) { let urlString = "https://api.hitbox.tv/games" var parameters: [String : AnyObject] = ["limit" : limit, "liveonly" : "true", "offset" : offset] if let term = searchTerm { parameters["q"] = term } Alamofire.request(.GET, urlString, parameters: parameters) .responseJSON { (response) -> Void in //do the stuff if(response.result.isSuccess) { if let baseDict = response.result.value as? [String : AnyObject] { if let gamesDict = baseDict["categories"] as? [[String : AnyObject]] { var games = [HitboxGame]() for gameRaw in gamesDict { if let game = HitboxGame(dict: gameRaw) { games.append(game) } } Logger.Debug("Returned \(games.count) results") completionHandler(games: games, error: nil) return } } Logger.Error("Could not parse the response as JSON") completionHandler(games: nil, error: .JSONError) return } else { Logger.Error("Could not request top games") completionHandler(games: nil, error: .URLError) return } } } ///This is a method to retrieve the Hitbox streams for a specific game /// /// - parameters: /// - forGame: An integer gameID for given HitboxGame. This is called the category_id in the Hitbox API /// - offset: An integer offset to load content after the primary results (useful when you reach the end of a scrolling list) /// - limit: The number of games to return /// - completionHandler: A closure providing results and an error (both optionals) to be executed once the request completes static func getLiveStreams(forGame gameid: Int, offset: Int, limit: Int, completionHandler: (streams: [HitboxMedia]?, error: HitboxError?) -> ()) { let urlString = "https://api.hitbox.tv/media/live/list" Alamofire.request(.GET, urlString, parameters: [ "game" : gameid, "limit" : limit, "start" : offset, "publicOnly" : true ]) .responseJSON { (response) -> Void in //do the stuff if(response.result.isSuccess) { if let baseDict = response.result.value as? [String : AnyObject] { if let streamsDicts = baseDict["livestream"] as? [[String : AnyObject]] { var streams = [HitboxMedia]() for streamRaw in streamsDicts { if let stream = HitboxMedia(dict: streamRaw) { streams.append(stream) } } Logger.Debug("Returned \(streams.count) results") completionHandler(streams: streams, error: nil) return } } Logger.Error("Could not parse the response as JSON") completionHandler(streams: nil, error: .JSONError) return } else { Logger.Error("Could not request top streams") completionHandler(streams: nil, error: .URLError) return } } } ///This is a method to retrieve the stream links and information for a given Hitbox Stream /// /// - parameters: /// - forMediaID: A media ID for a given stream. In the Hitbox API they call it the user_media_id /// - completionHandler: A closure providing results and an error (both optionals) to be executed once the request completes static func getStreamInfo(forMediaId mediaId: String, completionHandler: (streamVideos: [HitboxStreamVideo]?, error: HitboxError?) -> ()) { let urlString = "http://www.hitbox.tv/api/player/config/live/\(mediaId)" Logger.Debug("getting stream info for: \(urlString)") Alamofire.request(.GET, urlString) .responseJSON { (response) -> Void in if(response.result.isSuccess) { if let baseDict = response.result.value as? [String : AnyObject] { if let playlist = baseDict["playlist"] as? [[String : AnyObject]], bitrates = playlist.first?["bitrates"] as? [[String : AnyObject]] { var streamVideos = [HitboxStreamVideo]() for bitrate in bitrates { if let video = HitboxStreamVideo(dict: bitrate) { streamVideos.append(video) } } // //this is no longer necessary, it was to try and get a rtmp stream but AVPlayer doesn't support that // if streamVideos.count == 0 { // //rtmp://edge.live.hitbox.tv/live/youplay // streamVideos += HitboxStreamVideo.alternativeCreation(playlist.first) // } Logger.Debug("Returned \(streamVideos.count) results") completionHandler(streamVideos: streamVideos, error: nil) return } } Logger.Error("Could not parse the response as JSON") completionHandler(streamVideos: nil, error: .JSONError) return } else { Logger.Error("Could not request stream info") completionHandler(streamVideos: nil, error: .URLError) return } } } ///This is a method to authenticate with the HitboxAPI. It takes a username and password and if it's successful it will store the token in the User's Keychain /// /// - parameters: /// - username: A username /// - password: A password /// - completionHandler: A closure providing a boolean indicating if the authentication was successful and an optional error if it was not successful static func authenticate(withUserName username: String, password: String, completionHandler: (success: Bool, error: HitboxError?) -> ()) { let urlString = "https://www.hitbox.tv/api/auth/login" Alamofire.request(.POST, urlString, parameters: [ "login" : username, "pass" : password, "rememberme" : "" ]) .responseJSON { (response) -> Void in if response.result.isSuccess { if let baseDict = response.result.value as? [String : AnyObject] { if let dataDict = baseDict["data"] as? [String : AnyObject], token = dataDict["authToken"] as? String { if let username = dataDict["user_name"] as? String { TokenHelper.storeHitboxUsername(username) } TokenHelper.storeHitboxToken(token) Mixpanel.tracker()?.trackEvents([Event.ServiceAuthenticationEvent("Hitbox")]) Logger.Debug("Successfully authenticated") completionHandler(success: true, error: nil) return } } Logger.Error("Could not parse the response as JSON") completionHandler(success: false, error: .NoAuthTokenError) } else { Logger.Error("Could not request for authentication") completionHandler(success: false, error: .URLError) } } } }
mit
a1901b335dee60219ff9078ec4421b04
46.352423
162
0.516141
5.509482
false
false
false
false
SmallElephant/FEAlgorithm-Swift
7-String/7-String/ReverseString.swift
1
1628
// // ReverseString.swift // 7-String // // Created by keso on 2017/1/8. // Copyright © 2017年 FlyElephant. All rights reserved. // import Foundation class ReverseString { func reversePosition(strArr:inout [Character],begin:Int,end:Int) { var low:Int = begin var high:Int = end while low < high { swap(&strArr[low], &strArr[high]) low += 1 high -= 1 } } func leftRoateString(str:String,len:Int) -> String { var strArr:[Character] = [Character]() for c in str.characters { strArr.append(c) } reversePosition(strArr: &strArr, begin: 0, end: len - 1) reversePosition(strArr: &strArr, begin: len, end: strArr.count - 1) reversePosition(strArr: &strArr, begin: 0, end: strArr.count - 1) return String(strArr) } func reverseSentence(str:String) -> String { var strArr:[Character] = [Character]() for c in str.characters { strArr.append(c) } reversePosition(strArr: &strArr, begin: 0, end: str.characters.count - 1) var start:Int = 0 var end:Int = 0 while end < strArr.count { if String(strArr[start]) == " " { start += 1 end += 1 } else if String(strArr[end]) == " " { reversePosition(strArr: &strArr, begin: start, end: end-1) start = end } else { end += 1 } } return String(strArr) } }
mit
5dcb7b878183c7067e2c4a058b0f6e7d
24.793651
81
0.503385
4.145408
false
false
false
false
DonMag/ScratchPad
Swift3/scratchy/fbb/FBEdgeCrossing.swift
3
5001
// // FBEdgeCrossing.swift // Swift VectorBoolean for iOS // // Based on FBEdgeCrossing - Created by Andrew Finnell on 6/15/11. // Copyright 2011 Fortunate Bear, LLC. All rights reserved. // // Created by Leslie Titze on 2015-07-02. // Copyright (c) 2015 Leslie Titze. All rights reserved. // import UIKit /// FBEdgeCrossing is used by the boolean operations code to hold data about /// where two edges actually cross (as opposed to just intersect). /// /// The main piece of data is the intersection, but it also holds a pointer to the /// crossing's counterpart in the other FBBezierGraph class FBEdgeCrossing { fileprivate var _intersection: FBBezierIntersection var edge: FBBezierCurve? var counterpart: FBEdgeCrossing? var fromCrossingOverlap = false var entry = false var processed = false var selfCrossing = false var index: Int = 0 //+ (id) crossingWithIntersection:(FBBezierIntersection *)intersection init(intersection: FBBezierIntersection) { _intersection = intersection } var isProcessed : Bool { return processed } var isSelfCrossing : Bool { return selfCrossing } var isEntry : Bool { return entry } //@synthesize edge=_edge; //@synthesize counterpart=_counterpart; //@synthesize entry=_entry; //@synthesize processed=_processed; //@synthesize selfCrossing=_selfCrossing; //@synthesize index=_index; //@synthesize fromCrossingOverlap=_fromCrossingOverlap; //@property (assign) FBBezierCurve *edge; //@property (assign) FBEdgeCrossing *counterpart; //@property (readonly) CGFloat order; //@property (getter = isEntry) BOOL entry; //@property (getter = isProcessed) BOOL processed; //@property (getter = isSelfCrossing) BOOL selfCrossing; //@property BOOL fromCrossingOverlap; //@property NSUInteger index; // An easy way to iterate crossings. It doesn't wrap when it reaches the end. //@property (readonly) FBEdgeCrossing *next; //@property (readonly) FBEdgeCrossing *previous; //@property (readonly) FBEdgeCrossing *nextNonself; //@property (readonly) FBEdgeCrossing *previousNonself; // These properties pass through to the underlying intersection //@property (readonly) CGFloat parameter; ///@property (readonly) FBBezierCurve *curve; //@property (readonly) FBBezierCurve *leftCurve; //@property (readonly) FBBezierCurve *rightCurve; //@property (readonly, getter = isAtStart) BOOL atStart; //@property (readonly, getter = isAtEnd) BOOL atEnd; //@property (readonly) NSPoint location; //- (void) removeFromEdge func removeFromEdge() { if let edge = edge { edge.removeCrossing(self) } } //- (CGFloat) order var order : Double { return parameter } //- (FBEdgeCrossing *) next var next : FBEdgeCrossing? { if let edge = edge { return edge.nextCrossing(self) } else { return nil } } //- (FBEdgeCrossing *) previous var previous : FBEdgeCrossing? { if let edge = edge { return edge.previousCrossing(self) } else { return nil } } //- (FBEdgeCrossing *) nextNonself var nextNonself : FBEdgeCrossing? { var nextNon : FBEdgeCrossing? = next while nextNon != nil && nextNon!.isSelfCrossing { nextNon = nextNon!.next } return nextNon } //- (FBEdgeCrossing *) previousNonself var previousNonself : FBEdgeCrossing? { var prevNon : FBEdgeCrossing? = previous while prevNon != nil && prevNon!.isSelfCrossing { prevNon = prevNon!.previous } return prevNon } // MARK: Underlying Intersection Access // These properties pass through to the underlying intersection //- (CGFloat) parameter var parameter : Double { // TODO: Is this actually working? Check equality operator here! if edge == _intersection.curve1 { return _intersection.parameter1 } else { return _intersection.parameter2 } } //- (NSPoint) location var location : CGPoint { return _intersection.location } //- (FBBezierCurve *) curve var curve : FBBezierCurve? { return edge } //- (FBBezierCurve *) leftCurve var leftCurve : FBBezierCurve? { if isAtStart { return nil } if edge == _intersection.curve1 { return _intersection.curve1LeftBezier } else { return _intersection.curve2LeftBezier } } //- (FBBezierCurve *) rightCurve var rightCurve : FBBezierCurve? { if isAtEnd { return nil } if edge == _intersection.curve1 { return _intersection.curve1RightBezier } else { return _intersection.curve2RightBezier } } //- (BOOL) isAtStart var isAtStart : Bool { if edge == _intersection.curve1 { return _intersection.isAtStartOfCurve1 } else { return _intersection.isAtStartOfCurve2 } } //- (BOOL) isAtEnd var isAtEnd : Bool { if edge == _intersection.curve1 { return _intersection.isAtStopOfCurve1 } else { return _intersection.isAtStopOfCurve2 } } }
mit
8349ab782748dc75ebdaec43f34724f4
24.515306
82
0.679264
4.433511
false
false
false
false
material-motion/motion-animator-objc
tests/unit/UIKitBehavioralTests.swift
2
14413
/* Copyright 2017-present The Material Motion Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import XCTest #if IS_BAZEL_BUILD import MotionAnimator #else import MotionAnimator #endif class ShapeLayerBackedView: UIView { override static var layerClass: AnyClass { return CAShapeLayer.self } override init(frame: CGRect) { super.init(frame: frame) let shapeLayer = self.layer as! CAShapeLayer shapeLayer.path = UIBezierPath(rect: CGRect(x: 0, y: 0, width: 100, height: 100)).cgPath } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class UIKitBehavioralTests: XCTestCase { var view: UIView! var window: UIWindow! override func setUp() { super.setUp() window = getTestHarnessKeyWindow() rebuildView() } override func tearDown() { view = nil window = nil super.tearDown() } private func rebuildView() { window.subviews.forEach { $0.removeFromSuperview() } view = ShapeLayerBackedView() // Need to animate a view's layer to get implicit animations. view.layer.anchorPoint = .zero window.addSubview(view) // Connect our layers to the render server. CATransaction.flush() } // MARK: Each animatable property needs to be added to exactly one of the following three tests func testSomePropertiesImplicitlyAnimateAdditively() { let baselineProperties: [AnimatableKeyPath: Any] = [ .bounds: CGRect(x: 0, y: 0, width: 123, height: 456), .height: 100, .position: CGPoint(x: 50, y: 20), .rotation: 42, .scale: 2.5, // Note: prior to iOS 14 this used to work as a CGAffineTransform. iOS 14 now only accepts // CATransform3D instances when using KVO. .transform: CATransform3DMakeScale(1.5, 1.5, 1.5), .width: 25, .x: 12, .y: 23, ] let properties: [AnimatableKeyPath: Any] if #available(iOS 11.0, *) { // Corner radius became implicitly animatable in iOS 11. var baselineWithCornerRadiusProperties = baselineProperties baselineWithCornerRadiusProperties[.cornerRadius] = 3 properties = baselineWithCornerRadiusProperties } else { properties = baselineProperties } for (keyPath, value) in properties { rebuildView() UIView.animate(withDuration: 0.01) { self.view.layer.setValue(value, forKeyPath: keyPath.rawValue) } XCTAssertNotNil(view.layer.animationKeys(), "Expected \(keyPath.rawValue) to generate at least one animation.") if let animationKeys = view.layer.animationKeys() { for key in animationKeys { let animation = view.layer.animation(forKey: key) as! CABasicAnimation XCTAssertTrue(animation.isAdditive, "Expected \(key) to be additive as a result of animating " + "\(keyPath.rawValue), but it was not: \(animation.debugDescription).") } } } } func testSomePropertiesImplicitlyAnimateButNotAdditively() { let baselineProperties: [AnimatableKeyPath: Any] = [ .backgroundColor: UIColor.blue, .opacity: 0.5, ] let properties: [AnimatableKeyPath: Any] if #available(iOS 11.0, *) { // Anchor point became implicitly animatable in iOS 11. var baselineWithCornerRadiusProperties = baselineProperties baselineWithCornerRadiusProperties[.anchorPoint] = CGPoint(x: 0.2, y: 0.4) properties = baselineWithCornerRadiusProperties } else { properties = baselineProperties } for (keyPath, value) in properties { rebuildView() UIView.animate(withDuration: 0.01) { self.view.layer.setValue(value, forKeyPath: keyPath.rawValue) } XCTAssertNotNil(view.layer.animationKeys(), "Expected \(keyPath.rawValue) to generate at least one animation.") if let animationKeys = view.layer.animationKeys() { for key in animationKeys { let animation = view.layer.animation(forKey: key) as! CABasicAnimation XCTAssertFalse(animation.isAdditive, "Expected \(key) not to be additive as a result of animating " + "\(keyPath.rawValue), but it was: \(animation.debugDescription).") } } } } func testSomePropertiesDoNotImplicitlyAnimate() { let baselineProperties: [AnimatableKeyPath: Any] = [ .anchorPoint: CGPoint(x: 0.2, y: 0.4), .borderWidth: 5, .borderColor: UIColor.red, .cornerRadius: 3, .shadowColor: UIColor.blue, .shadowOffset: CGSize(width: 1, height: 1), .shadowOpacity: 0.3, .shadowRadius: 5, .strokeStart: 0.2, .strokeEnd: 0.5, .z: 3, ] let properties: [AnimatableKeyPath: Any] if #available(iOS 13, *) { // Shadow opacity became implicitly animatable in iOS 13. var baselineWithModernSupport = baselineProperties baselineWithModernSupport.removeValue(forKey: .shadowOpacity) baselineWithModernSupport.removeValue(forKey: .anchorPoint) baselineWithModernSupport.removeValue(forKey: .cornerRadius) properties = baselineWithModernSupport } else if #available(iOS 11.0, *) { // Corner radius became implicitly animatable in iOS 11. var baselineWithModernSupport = baselineProperties baselineWithModernSupport.removeValue(forKey: .anchorPoint) baselineWithModernSupport.removeValue(forKey: .cornerRadius) properties = baselineWithModernSupport } else { properties = baselineProperties } for (keyPath, value) in properties { rebuildView() UIView.animate(withDuration: 0.01) { self.view.layer.setValue(value, forKeyPath: keyPath.rawValue) } XCTAssertNil(view.layer.animationKeys(), "Expected \(keyPath.rawValue) not to generate any animations.") } } // MARK: Every animatable layer property must be added to the following test func testNoPropertiesImplicitlyAnimateOutsideOfAnAnimationBlock() { let properties: [AnimatableKeyPath: Any] = [ .backgroundColor: UIColor.blue, .bounds: CGRect(x: 0, y: 0, width: 123, height: 456), .cornerRadius: 3, .height: 100, .opacity: 0.5, .position: CGPoint(x: 50, y: 20), .rotation: 42, .scale: 2.5, .shadowColor: UIColor.blue, .shadowOffset: CGSize(width: 1, height: 1), .shadowOpacity: 0.3, .shadowRadius: 5, .strokeStart: 0.2, .strokeEnd: 0.5, .transform: CGAffineTransform(scaleX: 1.5, y: 1.5), .width: 25, .x: 12, .y: 23, ] for (keyPath, value) in properties { rebuildView() self.view.layer.setValue(value, forKeyPath: keyPath.rawValue) XCTAssertNil(view.layer.animationKeys(), "Expected \(keyPath.rawValue) not to generate any animations.") } } // MARK: .beginFromCurrentState option behavior // // The following tests indicate that UIKit treats .beginFromCurrentState differently depending // on the key path being animated. This difference is in line with whether or not a key path is // animated additively or not. // // > See testSomePropertiesImplicitlyAnimateAdditively and // > testSomePropertiesImplicitlyAnimateButNotAdditively for a list of which key paths are // > animated which way. // // Notably, ONLY non-additive key paths are affected by the beginFromCurrentState option. This // likely became the case starting in iOS 8 when additive animations were enabled by default. // Additive animations will always animate additively regardless of whether or not you provide // this flag. func testDefaultsAnimatesOpacityNonAdditivelyFromItsModelLayerState() { UIView.animate(withDuration: 0.1) { self.view.alpha = 0.5 } RunLoop.main.run(until: .init(timeIntervalSinceNow: 0.01)) let initialValue = self.view.layer.opacity UIView.animate(withDuration: 0.1) { self.view.alpha = 0.2 } XCTAssertNotNil(view.layer.animationKeys(), "Expected an animation to be added, but none were found.") guard let animationKeys = view.layer.animationKeys() else { return } XCTAssertEqual(animationKeys.count, 1, "Expected only one animation to be added, but the following were found: " + "\(animationKeys).") guard let key = animationKeys.first, let animation = view.layer.animation(forKey: key) as? CABasicAnimation else { return } XCTAssertFalse(animation.isAdditive, "Expected the animation not to be additive, but it was.") XCTAssertTrue(animation.fromValue is Float, "The animation's from value was not a number type: " + String(describing: animation.fromValue)) guard let fromValue = animation.fromValue as? Float else { return } XCTAssertEqual(fromValue, initialValue, accuracy: 0.0001, "Expected the animation to start from \(initialValue), but it did not.") } func testBeginFromCurrentStateAnimatesOpacityNonAdditivelyFromItsPresentationLayerState() { UIView.animate(withDuration: 0.1) { self.view.alpha = 0.5 } RunLoop.main.run(until: .init(timeIntervalSinceNow: 0.01)) let initialValue = self.view.layer.presentation()!.opacity UIView.animate(withDuration: 0.1, delay: 0, options: .beginFromCurrentState, animations: { self.view.alpha = 0.2 }, completion: nil) XCTAssertNotNil(view.layer.animationKeys(), "Expected an animation to be added, but none were found.") guard let animationKeys = view.layer.animationKeys() else { return } XCTAssertEqual(animationKeys.count, 1, "Expected only one animation to be added, but the following were found: " + "\(animationKeys).") guard let key = animationKeys.first, let animation = view.layer.animation(forKey: key) as? CABasicAnimation else { return } XCTAssertFalse(animation.isAdditive, "Expected the animation not to be additive, but it was.") XCTAssertTrue(animation.fromValue is Float, "The animation's from value was not a number type: " + String(describing: animation.fromValue)) guard let fromValue = animation.fromValue as? Float else { return } XCTAssertEqual(fromValue, initialValue, accuracy: 0.0001, "Expected the animation to start from \(initialValue), but it did not.") } func testDefaultsAnimatesPositionAdditivelyFromItsModelLayerState() { UIView.animate(withDuration: 0.1) { self.view.layer.position = CGPoint(x: 100, y: self.view.layer.position.y) } RunLoop.main.run(until: .init(timeIntervalSinceNow: 0.01)) let initialValue = self.view.layer.position UIView.animate(withDuration: 0.1) { self.view.layer.position = CGPoint(x: 20, y: self.view.layer.position.y) } let displacement = initialValue.x - self.view.layer.position.x XCTAssertNotNil(view.layer.animationKeys(), "Expected an animation to be added, but none were found.") guard let animationKeys = view.layer.animationKeys() else { return } XCTAssertEqual(animationKeys.count, 2, "Expected two animations to be added, but the following were found: " + "\(animationKeys).") guard let key = animationKeys.first(where: { $0 != "position" }), let animation = view.layer.animation(forKey: key) as? CABasicAnimation else { return } XCTAssertTrue(animation.isAdditive, "Expected the animation to be additive, but it wasn't.") XCTAssertTrue(animation.fromValue is CGPoint, "The animation's from value was not a point type: " + String(describing: animation.fromValue)) guard let fromValue = animation.fromValue as? CGPoint else { return } XCTAssertEqual(fromValue.x, displacement, accuracy: 0.0001, "Expected the animation to have a delta of \(displacement), but it did not.") } func testBeginFromCurrentStateAnimatesPositionAdditivelyFromItsModelLayerState() { UIView.animate(withDuration: 0.1) { self.view.layer.position = CGPoint(x: 100, y: self.view.layer.position.y) } RunLoop.main.run(until: .init(timeIntervalSinceNow: 0.01)) let initialValue = self.view.layer.position UIView.animate(withDuration: 0.1, delay: 0, options: .beginFromCurrentState, animations: { self.view.layer.position = CGPoint(x: 20, y: self.view.layer.position.y) }, completion: nil) let displacement = initialValue.x - self.view.layer.position.x XCTAssertNotNil(view.layer.animationKeys(), "Expected an animation to be added, but none were found.") guard let animationKeys = view.layer.animationKeys() else { return } XCTAssertEqual(animationKeys.count, 2, "Expected two animations to be added, but the following were found: " + "\(animationKeys).") guard let key = animationKeys.first(where: { $0 != "position" }), let animation = view.layer.animation(forKey: key) as? CABasicAnimation else { return } XCTAssertTrue(animation.isAdditive, "Expected the animation to be additive, but it wasn't.") XCTAssertTrue(animation.fromValue is CGPoint, "The animation's from value was not a point type: " + String(describing: animation.fromValue)) guard let fromValue = animation.fromValue as? CGPoint else { return } XCTAssertEqual(fromValue.x, displacement, accuracy: 0.0001, "Expected the animation to have a delta of \(displacement), but it did not.") } }
apache-2.0
aea569100fc595dfd073405e886c4902
34.853234
98
0.666967
4.643363
false
false
false
false
eduresende/ios-nd-swift-syntax-swift-3
Lesson8/L8_CalmTheCompiler.playground/Contents.swift
1
887
//: ### Calm the compiler // Problem 1 protocol DirtyDeeds { func cheat() func steal() } class Minion: DirtyDeeds { var name: String init(name:String) { self.name = name } } // Problem 2 class DinnerCrew { var members: [Souschef] init(members: [Souschef]) { self.members = members } } protocol Souschef { func chop(_ vegetable: String) -> String func rinse(_ vegetable:String) -> String } var deviousDinnerCrew = DinnerCrew(members: [Minion]()) // Problem 3 protocol DogWalker { func throwBall(_ numberOfTimes:Int) -> Int func rubBelly() } class Neighbor: DogWalker { func throwBall(_ numberOfTimes:Int) { var count = 0 while count < numberOfTimes { print("Go get it!") count += 1 } } func rubBelly() { print("Rub rub") } }
mit
b174c1b825d5eacd715a920670599224
16.392157
55
0.572717
3.650206
false
false
false
false
i-miss-you/Nuke
Pod/Classes/Core/ImageManagerLoader.swift
1
10794
// The MIT License (MIT) // // Copyright (c) 2015 Alexander Grebenyuk (github.com/kean). import UIKit internal protocol ImageManagerLoaderDelegate: class { func imageLoader(imageLoader: ImageManagerLoader, imageTask: ImageTask, didUpdateProgressWithCompletedUnitCount completedUnitCount: Int64, totalUnitCount: Int64) func imageLoader(imageLoader: ImageManagerLoader, imageTask: ImageTask, didCompleteWithImage image: UIImage?, error: ErrorType?) } internal class ImageManagerLoader { internal weak var delegate: ImageManagerLoaderDelegate? private let conf: ImageManagerConfiguration private var executingTasks = [ImageTask : ImageLoaderTask]() private var sessionTasks = [ImageRequestKey : ImageLoaderSessionTask]() private let queue = dispatch_queue_create("ImageManagerLoader-InternalSerialQueue", DISPATCH_QUEUE_SERIAL) private let decodingQueue: NSOperationQueue = { let queue = NSOperationQueue() queue.maxConcurrentOperationCount = 1 return queue }() private let processingQueue: NSOperationQueue = { let queue = NSOperationQueue() queue.maxConcurrentOperationCount = 2 return queue }() internal init(configuration: ImageManagerConfiguration) { self.conf = configuration } internal func startLoadingForTask(task: ImageTask) { dispatch_async(self.queue) { let loaderTask = ImageLoaderTask(imageTask: task) self.executingTasks[task] = loaderTask self.startSessionTaskForTask(loaderTask) } } private func startSessionTaskForTask(task: ImageLoaderTask) { let key = ImageRequestKey(task.request, type: .Load, owner: self) var sessionTask: ImageLoaderSessionTask! = self.sessionTasks[key] if sessionTask == nil { sessionTask = ImageLoaderSessionTask(key: key) let dataTask = self.conf.dataLoader.imageDataTaskWithURL(task.request.URL, progressHandler: { [weak self] completedUnits, totalUnits in self?.sessionTask(sessionTask, didUpdateProgressWithCompletedUnitCount: completedUnits, totalUnitCount: totalUnits) }, completionHandler: { [weak self] data, _, error in self?.sessionTask(sessionTask, didCompleteWithData: data, error: error) }) dataTask.resume() sessionTask.dataTask = dataTask self.sessionTasks[key] = sessionTask } else { self.delegate?.imageLoader(self, imageTask: task.imageTask, didUpdateProgressWithCompletedUnitCount: sessionTask.completedUnitCount, totalUnitCount: sessionTask.completedUnitCount) } task.sessionTask = sessionTask sessionTask.tasks.append(task) } private func sessionTask(sessionTask: ImageLoaderSessionTask, didUpdateProgressWithCompletedUnitCount completedUnitCount: Int64, totalUnitCount: Int64) { dispatch_async(self.queue) { sessionTask.totalUnitCount = totalUnitCount sessionTask.completedUnitCount = completedUnitCount for loaderTask in sessionTask.tasks { self.delegate?.imageLoader(self, imageTask: loaderTask.imageTask, didUpdateProgressWithCompletedUnitCount: completedUnitCount, totalUnitCount: totalUnitCount) } } } private func sessionTask(sessionTask: ImageLoaderSessionTask, didCompleteWithData data: NSData?, error: ErrorType?) { if let unwrappedData = data { self.decodingQueue.addOperationWithBlock { [weak self] in let image = self?.conf.decoder.imageWithData(unwrappedData) self?.sessionTask(sessionTask, didCompleteWithImage: image, error: error) } } else { self.sessionTask(sessionTask, didCompleteWithImage: nil, error: error) } } private func sessionTask(sessionTask: ImageLoaderSessionTask, didCompleteWithImage image: UIImage?, error: ErrorType?) { dispatch_async(self.queue) { for loaderTask in sessionTask.tasks { self.processImage(image, error: error, forLoaderTask: loaderTask) } sessionTask.tasks.removeAll() sessionTask.dataTask = nil self.removeSessionTask(sessionTask) } } private func processImage(image: UIImage?, error: ErrorType?, forLoaderTask task: ImageLoaderTask) { if let unwrappedImage = image, processor = self.processorForRequest(task.request) { let operation = NSBlockOperation { [weak self] in let processedImage = processor.processImage(unwrappedImage) self?.storeImage(processedImage, forRequest: task.request) self?.loaderTask(task, didCompleteWithImage: processedImage, error: error) } self.processingQueue.addOperation(operation) task.processingOperation = operation } else { self.storeImage(image, forRequest: task.request) self.loaderTask(task, didCompleteWithImage: image, error: error) } } private func processorForRequest(request: ImageRequest) -> ImageProcessing? { var processors = [ImageProcessing]() if request.shouldDecompressImage { processors.append(ImageDecompressor(targetSize: request.targetSize, contentMode: request.contentMode)) } if let processor = request.processor { processors.append(processor) } return processors.isEmpty ? nil : ImageProcessorComposition(processors: processors) } private func loaderTask(task: ImageLoaderTask, didCompleteWithImage image: UIImage?, error: ErrorType?) { dispatch_async(self.queue) { self.delegate?.imageLoader(self, imageTask: task.imageTask, didCompleteWithImage: image, error: error) self.executingTasks[task.imageTask] = nil } } internal func stopLoadingForTask(imageTask: ImageTask) { dispatch_async(self.queue) { if let loaderTask = self.executingTasks[imageTask], sessionTask = loaderTask.sessionTask { if let index = (sessionTask.tasks.indexOf { $0 === loaderTask }) { sessionTask.tasks.removeAtIndex(index) } if sessionTask.tasks.isEmpty { sessionTask.dataTask?.cancel() sessionTask.dataTask = nil self.removeSessionTask(sessionTask) } loaderTask.processingOperation?.cancel() self.executingTasks[imageTask] = nil } } } // MARK: Misc internal func cachedResponseForRequest(request: ImageRequest) -> ImageCachedResponse? { return self.conf.cache?.cachedResponseForKey(ImageRequestKey(request, type: .Cache, owner: self)) } private func storeImage(image: UIImage?, forRequest request: ImageRequest) { if image != nil { let cachedResponse = ImageCachedResponse(image: image!, userInfo: nil) self.conf.cache?.storeResponse(cachedResponse, forKey: ImageRequestKey(request, type: .Cache, owner: self)) } } internal func preheatingKeyForRequest(request: ImageRequest) -> ImageRequestKey { return ImageRequestKey(request, type: .Cache, owner: self) } private func removeSessionTask(task: ImageLoaderSessionTask) { if self.sessionTasks[task.key] === task { self.sessionTasks[task.key] = nil } } } // MARK: ImageManagerLoader: ImageRequestKeyOwner extension ImageManagerLoader: ImageRequestKeyOwner { internal func isImageRequestKey(lhs: ImageRequestKey, equalToKey rhs: ImageRequestKey) -> Bool { switch lhs.type { case .Cache: if !(self.conf.dataLoader.isRequestCacheEquivalent(lhs.request, toRequest: rhs.request)) { return false } let lhsProcessor: ImageProcessing! = self.processorForRequest(lhs.request) let rhsProcessor: ImageProcessing! = self.processorForRequest(rhs.request) if lhsProcessor != nil && rhsProcessor != nil { return lhsProcessor.isEquivalentToProcessor(rhsProcessor) } else if lhsProcessor != nil || rhsProcessor != nil { return false } return true case .Load: return self.conf.dataLoader.isRequestLoadEquivalent(lhs.request, toRequest: rhs.request) } } } // MARK: - ImageLoaderTask private class ImageLoaderTask { let imageTask: ImageTask var request: ImageRequest { get { return self.imageTask.request } } var sessionTask: ImageLoaderSessionTask? var processingOperation: NSOperation? private init(imageTask: ImageTask) { self.imageTask = imageTask } } // MARK: - ImageLoaderSessionTask private class ImageLoaderSessionTask { let key: ImageRequestKey var dataTask: NSURLSessionTask? var tasks = [ImageLoaderTask]() var totalUnitCount: Int64 = 0 var completedUnitCount: Int64 = 0 init(key: ImageRequestKey) { self.key = key } } // MARK: - ImageRequestKey internal protocol ImageRequestKeyOwner: class { func isImageRequestKey(key: ImageRequestKey, equalToKey: ImageRequestKey) -> Bool } internal enum ImageRequestKeyType { case Load case Cache } /** Makes it possible to use ImageRequest as a key in dictionaries (and dictionary-like structures). This should be a nested class inside ImageManager but it's impossible because of the Equatable protocol. */ internal class ImageRequestKey: NSObject { let request: ImageRequest let type: ImageRequestKeyType weak var owner: ImageRequestKeyOwner? override var hashValue: Int { return self.request.URL.hashValue } init(_ request: ImageRequest, type: ImageRequestKeyType, owner: ImageRequestKeyOwner) { self.request = request self.type = type self.owner = owner } // Make it possible to use ImageRequesKey as key in NSCache override var hash: Int { return self.hashValue } override func isEqual(object: AnyObject?) -> Bool { if object === self { return true } if let object = object as? ImageRequestKey { return self == object } return false } } private func ==(lhs: ImageRequestKey, rhs: ImageRequestKey) -> Bool { if let owner = lhs.owner where lhs.owner === rhs.owner && lhs.type == rhs.type { return owner.isImageRequestKey(lhs, equalToKey: rhs) } return false }
mit
81d5cf1b979ae765db8f2b7315661609
38.250909
205
0.661386
5.484756
false
false
false
false