repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
zachwaugh/GIFKit
refs/heads/master
GIFKit/DataStream.swift
mit
1
// // DataStream.swift // GIFKit // // Created by Zach Waugh on 11/5/15. // Copyright © 2015 Zach Waugh. All rights reserved. // import Foundation struct DataStream { let data: NSData var position: Int = 0 var bytesRemaining: Int { return data.length - position } var atEndOfStream: Bool { return position == data.length } init(data: NSData) { self.data = data } mutating func takeBool() -> Bool? { guard hasAvailableBytes(1) else { return nil } var value: Bool = false let length = sizeof(Bool) data.getBytes(&value, range: NSRange(location: position, length: length)) position += length return value } mutating func takeUInt8() -> UInt8? { guard hasAvailableBytes(1) else { return nil } var value: UInt8 = 0 let length = sizeof(UInt8) data.getBytes(&value, range: NSRange(location: position, length: length)) position += length return value } mutating func takeUInt16() -> UInt16? { guard hasAvailableBytes(2) else { return nil } var value: UInt16 = 0 let length = sizeof(UInt16) data.getBytes(&value, range: NSRange(location: position, length: length)) position += length return value } mutating func takeByte() -> Byte? { return takeUInt8() } mutating func takeBytes(length: Int) -> NSData? { guard let bytes = peekBytes(length) else { print("[gif decoder] invalid number of bytes!") return nil } position += length return bytes } mutating func takeBytes(length: Int) -> [Byte]? { guard hasAvailableBytes(length) else { print("[gif decoder] invalid number of bytes!") return nil } let bytes = nextBytes(length) position += length return bytes } // MARK: - Peek func peekBytes(length: Int) -> NSData? { return peekBytesWithRange(NSRange(location: position, length: length)) } func peekBytesWithRange(range: NSRange) -> NSData? { guard range.location + range.length <= data.length else { print("[gif decoder] invalid range! \(range), bytes: \(data.length)") return nil } return data.subdataWithRange(range) } func nextBytes(count: Int) -> [Byte] { return nextBytes(NSRange(location: position, length: count)) } func nextBytes(range: NSRange) -> [Byte] { var bytes = [Byte](count: range.length, repeatedValue: 0) data.getBytes(&bytes, range: range) return bytes } func hasAvailableBytes(count: Int) -> Bool { return bytesRemaining >= count } }
f33906fbfb1cce47dadf44c97654ae9d
23.801653
81
0.545667
false
false
false
false
OBJCC/Flying-Swift
refs/heads/master
test-swift/JLToast/JLToast.swift
apache-2.0
3
/* * JLToast.swift * * DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE * Version 2, December 2004 * * Copyright (C) 2013-2014 Su Yeol Jeon * * Everyone is permitted to copy and distribute verbatim or modified * copies of this license document, and changing it is allowed as long * as the name is changed. * * DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE * TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION * * 0. You just DO WHAT THE FUCK YOU WANT TO. * */ import UIKit public struct JLToastDelay { public static let ShortDelay: NSTimeInterval = 2.0 public static let LongDelay: NSTimeInterval = 3.5 } public struct JLToastViewValue { static var FontSize: CGFloat { return UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Phone ? 12 : 16 } static var PortraitOffsetY: CGFloat { return UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Phone ? 30 : 60 } static var LandscapeOffsetY: CGFloat { return UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Phone ? 20 : 40 } } @objc public class JLToast: NSOperation { public var view: JLToastView = JLToastView() public var text: String? { get { return self.view.textLabel.text? } set { self.view.textLabel.text = newValue } } public var delay: NSTimeInterval = 0 public var duration: NSTimeInterval = JLToastDelay.ShortDelay private var _executing = false override public var executing: Bool { get { return self._executing } set { self.willChangeValueForKey("isExecuting") self._executing = newValue self.didChangeValueForKey("isExecuting") } } private var _finished = false override public var finished: Bool { get { return self._finished } set { self.willChangeValueForKey("isFinished") self._finished = newValue self.didChangeValueForKey("isFinished") } } public class func makeText(text: String) -> JLToast { return JLToast.makeText(text, delay: 0, duration: JLToastDelay.ShortDelay) } public class func makeText(text: String, duration: NSTimeInterval) -> JLToast { return JLToast.makeText(text, delay: 0, duration: duration) } public class func makeText(text: String, delay: NSTimeInterval, duration: NSTimeInterval) -> JLToast { var toast = JLToast() toast.text = text toast.delay = delay toast.duration = duration return toast } public func show() { JLToastCenter.defaultCenter().addToast(self) } override public func start() { if !NSThread.isMainThread() { dispatch_async(dispatch_get_main_queue(), { self.start() }) } else { super.start() } } override public func main() { executing = true dispatch_async(dispatch_get_main_queue(), { self.view.updateView() self.view.alpha = 0 UIApplication.sharedApplication().keyWindow?.subviews.first?.addSubview(self.view) UIView.animateWithDuration(0.5, delay: self.delay, options: UIViewAnimationOptions.BeginFromCurrentState, animations: { self.view.alpha = 1 }, completion: { completed in UIView.animateWithDuration(self.duration, animations: { self.view.alpha = 1.0001 }, completion: { completed in self.finish() UIView.animateWithDuration(0.5, animations: { self.view.alpha = 0 }) } ) } ) }) } public func finish() { executing = false finished = true } }
57b9b1530624f6a4dcd072a09f968f0d
28.068493
106
0.560453
false
false
false
false
dn-m/Collections
refs/heads/master
Collections/SortedArray.swift
mit
1
// // SortedArray.swift // Collections // // Created by James Bean on 12/10/16. // // import Algebra /// `Array` that keeps itself sorted. public struct SortedArray <Element: Comparable>: RandomAccessCollectionWrapping, SortedCollectionWrapping { public var base: [Element] = [] // MARK: - Initializers /// Create an empty `SortedArray`. public init() { } /// Create a `SortedArray` with the given sequence of `elements`. public init <S> (_ elements: S) where S: Sequence, S.Iterator.Element == Element { self.base = Array(elements).sorted() } // MARK: - Instance Methods /// Remove the given `element`, if it is contained herein. /// /// - TODO: Make `throws` instead of returning silently. public mutating func remove(_ element: Element) { guard let index = base.index(of: element) else { return } base.remove(at: index) } /// Insert the given `element`. /// /// - Complexity: O(_n_) public mutating func insert(_ element: Element) { let index = self.index(for: element) base.insert(element, at: index) } /// Insert the contents of another sequence of `T`. public mutating func insert <S: Sequence> (contentsOf elements: S) where S.Iterator.Element == Element { elements.forEach { insert($0) } } /// - Returns: Index for the given `element`, if it exists. Otherwise, `nil`. public func index(of element: Element) -> Int? { let index = self.index(for: element) guard index < count, base[index] == element else { return nil } return index } /// Binary search to find insertion point /// // FIXME: Move to extension on `BidirectionCollection where Element: Comparable`. // FIXME: Add to `SortedCollection` private func index(for element: Element) -> Int { var start = 0 var end = base.count while start < end { let middle = start + (end - start) / 2 if element > base[middle] { start = middle + 1 } else { end = middle } } return start } } extension SortedArray: Equatable { // MARK: - Equatable /// - returns: `true` if all elements in both arrays are equivalent. Otherwise, `false`. public static func == <T> (lhs: SortedArray<T>, rhs: SortedArray<T>) -> Bool { return lhs.base == rhs.base } } extension SortedArray: Additive { // MARK: - Additive /// - Returns: Empty `SortedArray`. public static var zero: SortedArray<Element> { return SortedArray() } /// - returns: `SortedArray` with the contents of two `SortedArray` values. public static func + <T> (lhs: SortedArray<T>, rhs: SortedArray<T>) -> SortedArray<T> { var result = lhs result.insert(contentsOf: rhs) return result } } extension SortedArray: Monoid { // MARK: - Monoid /// - Returns: Empty `SortedArray`. public static var identity: SortedArray<Element> { return .zero } /// - Returns: Composition of two of the same `Semigroup` type values. public static func <> (lhs: SortedArray<Element>, rhs: SortedArray<Element>) -> SortedArray<Element> { return lhs + rhs } } extension SortedArray: ExpressibleByArrayLiteral { // MARK: - ExpressibleByArrayLiteral /// - returns: Create a `SortedArray` with an array literal. public init(arrayLiteral elements: Element...) { self.init(elements) } }
8418a1df11ffec8ed9d193685943a56a
26.113636
92
0.604359
false
false
false
false
narner/AudioKit
refs/heads/master
AudioKit/Common/Operations/Generators/Oscillators/sawtooth.swift
mit
1
// // sawtooth.swift // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Copyright © 2017 Aurelius Prochazka. All rights reserved. // extension AKOperation { /// Simple sawtooth oscillator, not-band limited, can be used for LFO or wave, /// but sawtoothWave is probably better for audio. /// /// - Parameters: /// - frequency: In cycles per second, or Hz. (Default: 440, Minimum: 0.0, Maximum: 20000.0) /// - amplitude: Output Amplitude. (Default: 0.5, Minimum: 0.0, Maximum: 1.0) /// public static func sawtooth( frequency: AKParameter = 440, amplitude: AKParameter = 0.5, phase: AKParameter = 0 ) -> AKOperation { return AKOperation(module: "\"sawtooth\" osc", setup: "\"sawtooth\" 4096 \"0 -1 4095 1\" gen_line", inputs: frequency, amplitude, phase) } /// Simple reverse sawtooth oscillator, not-band limited, can be used for LFO or wave. /// /// - Parameters: /// - frequency: In cycles per second, or Hz. (Default: 440, Minimum: 0.0, Maximum: 20000.0) /// - amplitude: Output Amplitude. (Default: 0.5, Minimum: 0.0, Maximum: 1.0) /// public static func reverseSawtooth( frequency: AKParameter = 440, amplitude: AKParameter = 0.5, phase: AKParameter = 0 ) -> AKOperation { return AKOperation(module: "\"revsaw\" osc", setup: "\"revsaw\" 4096 \"0 1 4095 -1\" gen_line", inputs: frequency, amplitude, phase) } }
42fd4b81de4767c0389e5c551408bd8e
36.511628
98
0.577805
false
false
false
false
Caiflower/SwiftWeiBo
refs/heads/master
花菜微博/花菜微博/Classes/Tools(工具)/CFAddition(Swift)/UIKit/UIView-Layer.swift
apache-2.0
1
// // UIView-Layer.swift // 花菜微博 // // Created by 花菜ChrisCai on 2016/12/20. // Copyright © 2016年 花菜ChrisCai. All rights reserved. // import UIKit // MARK: - layer相关属性 extension UIView { @IBInspectable var borderColor: UIColor { get { return UIColor(cgColor: self.layer.borderColor ?? UIColor.white.cgColor) } set { self.layer.borderColor = newValue.cgColor } } @IBInspectable var cornerRadius: CGFloat { get { return self.layer.cornerRadius } set { self.layer.masksToBounds = true; // 栅格化优化性能 self.layer.rasterizationScale = UIScreen.main.scale; self.layer.shouldRasterize = true; self.layer.cornerRadius = newValue } } @IBInspectable var borderWidth: CGFloat { get { return self.layer.borderWidth } set { self.layer.borderWidth = newValue } } } extension UIView { }
15e9aaa0ba1ee53e7ec946b9d00961be
19.64
84
0.556202
false
false
false
false
krevis/MIDIApps
refs/heads/main
Frameworks/SnoizeMIDI/Endpoint.swift
bsd-3-clause
1
/* Copyright (c) 2021, Kurt Revis. All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. */ import Foundation import CoreMIDI public class Endpoint: MIDIObject { required init(context: CoreMIDIContext, objectRef: MIDIObjectRef) { super.init(context: context, objectRef: objectRef) } private lazy var cachedManufacturer = cacheProperty(kMIDIPropertyManufacturer, String.self) public var manufacturer: String? { get { self[cachedManufacturer] } set { self[cachedManufacturer] = newValue } } private lazy var cachedModel = cacheProperty(kMIDIPropertyModel, String.self) public var model: String? { get { self[cachedModel] } set { self[cachedModel] = newValue } } private lazy var cachedDisplayName = cacheProperty(kMIDIPropertyDisplayName, String.self) public var displayName: String? { get { self[cachedDisplayName] } set { self[cachedDisplayName] = newValue } } public var device: Device? { midiContext.findObject(midiObjectRef: deviceRef) } public var isVirtual: Bool { deviceRef == 0 } public var isOwnedByThisProcess: Bool { isVirtual && ownerPID == getpid() } public var connectedExternalDevices: [ExternalDevice] { uniqueIDsOfConnectedThings.compactMap { uniqueID -> ExternalDevice? in if let deviceRef = deviceRefFromConnectedUniqueID(uniqueID) { return midiContext.findObject(midiObjectRef: deviceRef) } else { return nil } } } public var endpointRef: MIDIEndpointRef { midiObjectRef } // MARK: Internal func setPrivateToThisProcess() { self[kMIDIPropertyPrivate as CFString] = Int32(1) } func setOwnedByThisProcess() { // We have a chicken-egg problem. When setting values of properties, we want // to make sure that the endpoint is owned by this process. However, there's // no way to tell if the endpoint is owned by this process until it gets a // property set on it. So we'll say that this property should be set first, // before any other setters are called. guard isVirtual else { fatalError("Endpoint is not virtual, so it can't be owned by this process") } ownerPID = getpid() } // MARK: Private // We set this property on the virtual endpoints that we create, // so we can query them to see if they're ours. private static let propertyOwnerPID = "SMEndpointPropertyOwnerPID" private var ownerPID: Int32 { get { self[Endpoint.propertyOwnerPID as CFString] ?? 0 } set { self[Endpoint.propertyOwnerPID as CFString] = newValue } } private var cachedDeviceRef: MIDIDeviceRef? private var deviceRef: MIDIDeviceRef { switch cachedDeviceRef { case .none: let value: MIDIDeviceRef = { var entityRef: MIDIEntityRef = 0 var deviceRef: MIDIDeviceRef = 0 if midiContext.interface.endpointGetEntity(endpointRef, &entityRef) == noErr, midiContext.interface.entityGetDevice(entityRef, &deviceRef) == noErr { return deviceRef } else { return 0 } }() cachedDeviceRef = .some(value) return value case .some(let value): return value } } var uniqueIDsOfConnectedThings: [MIDIUniqueID] { // Connected things may be external devices, endpoints, or who knows what. // The property for kMIDIPropertyConnectionUniqueID may be an integer or a data object. // Try getting it as data first. (The data is an array of big-endian MIDIUniqueIDs, aka Int32s.) if let data: Data = self[kMIDIPropertyConnectionUniqueID] { // Make sure the data size makes sense guard data.count > 0, data.count % MemoryLayout<Int32>.size == 0 else { return [] } return data.withUnsafeBytes { $0.bindMemory(to: Int32.self).map { MIDIUniqueID(bigEndian: $0) } } } // Now try getting the property as an integer. (It is only valid if nonzero.) if let oneUniqueID: MIDIUniqueID = self[kMIDIPropertyConnectionUniqueID], oneUniqueID != 0 { return [oneUniqueID] } // Give up return [] } private func deviceRefFromConnectedUniqueID(_ connectedUniqueID: MIDIUniqueID) -> MIDIDeviceRef? { var foundDeviceRef: MIDIDeviceRef? var connectedObjectRef: MIDIObjectRef = 0 var connectedObjectType: MIDIObjectType = .other var status = midiContext.interface.objectFindByUniqueID(connectedUniqueID, &connectedObjectRef, &connectedObjectType) var done = false while status == noErr && !done { switch connectedObjectType { case .device, .externalDevice: // We've got the device foundDeviceRef = connectedObjectRef as MIDIDeviceRef done = true case .entity, .externalEntity: // Get the entity's device status = midiContext.interface.entityGetDevice(connectedObjectRef as MIDIEntityRef, &connectedObjectRef) connectedObjectType = .device case .source, .destination, .externalSource, .externalDestination: // Get the endpoint's entity status = midiContext.interface.endpointGetEntity(connectedObjectRef as MIDIEndpointRef, &connectedObjectRef) connectedObjectType = .entity default: // Give up done = true } } return foundDeviceRef } }
82ef4f94e9b9bfc604908826b20c00b9
34.622754
125
0.626156
false
false
false
false
123kyky/SteamReader
refs/heads/master
SteamReader/SteamReader/CoreData/NewsItem.swift
mit
1
import Foundation import SwiftyJSON @objc(NewsItem) public class NewsItem: _NewsItem, JSONImportNSManagedObjectProtocol { // MARK: - JSONImportNSManagedObjectProtocol class func importDictionaryFromJSON(json: JSON, app: App?) -> [NSObject: AnyObject] { return [ "appId" : app!.appId!, "gId" : json["gid"].stringValue, "title" : json["title"].stringValue, "author" : json["author"].stringValue, "contents" : json["contents"].stringValue, "url" : json["url"].stringValue, "isExternalURL" : json["is_external_url"].boolValue, "feedLabel" : json["feedlabel"].stringValue, "feedName" : json["feedname"].stringValue, "date" : NSDate(timeIntervalSince1970: json["date"].doubleValue) ] } class func importDictionaryMatches(dictionary: [NSObject : AnyObject], app: App?) -> ImportDictionaryMatchingState { let newsItem: NewsItem? = CoreDataInterface.singleton.newsItemForId(dictionary["gId"] as! String) if newsItem == nil { return .NewObject } else if newsItem!.app?.appId == (dictionary["appId"] as! String) && newsItem!.gId == (dictionary["gId"] as! String) && newsItem!.title == (dictionary["title"] as! String) && newsItem!.author == (dictionary["author"] as! String) && newsItem!.contents == (dictionary["contents"] as! String) && newsItem!.url == (dictionary["url"] as! String) && newsItem!.isExternalURL == dictionary["isExternalURL"] as! Bool && newsItem!.feedLabel == (dictionary["feedLabel"] as! String) && newsItem!.feedName == (dictionary["feedName"] as! String) && newsItem!.date?.compare((dictionary["date"] as? NSDate)!) == .OrderedSame { return .Matches } else if dictionary["appId"] != nil && dictionary["gId"] != nil && dictionary["title"] != nil && dictionary["author"] != nil && dictionary["contents"] != nil && dictionary["url"] != nil && dictionary["isExternalURL"] != nil && dictionary["feedLabel"] != nil && dictionary["feedName"] != nil && dictionary["date"] != nil { return .Updated } else { return .Invalid } } }
511ac4577a2ab1d58e7c75d3d5346c37
43.740741
120
0.5625
false
false
false
false
polok/UICheckbox.Swift
refs/heads/master
UICheckbox/Classes/UICheckbox.swift
mit
1
// // UICheckbox.swift // UICheckbox // // The MIT License (MIT) // // Copyright (c) 2016 Marcin Polak. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit @IBDesignable open class UICheckbox: UIButton { /* * Variable describes UICheckbox padding */ @IBInspectable open var padding: CGFloat = CGFloat(15) /* * Variable describes UICheckbox border width */ @IBInspectable open var borderWidth: CGFloat = 2.0 { didSet { layer.borderWidth = borderWidth } } /* * Variable stores UICheckbox border color */ @IBInspectable open var borderColor: UIColor = UIColor.lightGray { didSet { layer.borderColor = borderColor.cgColor } } /* * Variable stores UICheckbox border radius */ @IBInspectable open var cornerRadius: CGFloat = 5.0 { didSet { layer.cornerRadius = cornerRadius } } /* * Variable to store current UICheckbox select status */ override open var isSelected: Bool { didSet { super.isSelected = isSelected onSelectStateChanged?(self, isSelected) } } /* * Callback for handling checkbox status change */ open var onSelectStateChanged: ((_ checkbox: UICheckbox, _ selected: Bool) -> Void)? // MARK: Init /* * Create a new instance of a UICheckbox */ required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initDefaultParams() } /* * Create a new instance of a UICheckbox */ override init(frame: CGRect) { super.init(frame: frame) initDefaultParams() } /* * Increase UICheckbox 'clickability' area for better UX */ override open func point(inside point: CGPoint, with event: UIEvent?) -> Bool { let newBound = CGRect( x: self.bounds.origin.x - padding, y: self.bounds.origin.y - padding, width: self.bounds.width + 2 * padding, height: self.bounds.width + 2 * padding ) return newBound.contains(point) } override open func prepareForInterfaceBuilder() { setTitle("", for: UIControlState()) } } // MARK: Private methods public extension UICheckbox { fileprivate func initDefaultParams() { addTarget(self, action: #selector(UICheckbox.checkboxTapped), for: .touchUpInside) setTitle(nil, for: UIControlState()) clipsToBounds = true setCheckboxImage() } fileprivate func setCheckboxImage() { let frameworkBundle = Bundle(for: UICheckbox.self) let bundleURL = frameworkBundle.resourceURL?.appendingPathComponent("UICheckbox.bundle") let resourceBundle = Bundle(url: bundleURL!) let image = UIImage(named: "ic_check_3x", in: resourceBundle, compatibleWith: nil) imageView?.contentMode = .scaleAspectFit setImage(nil, for: UIControlState()) setImage(image, for: .selected) setImage(image, for: .highlighted) } @objc fileprivate func checkboxTapped(_ sender: UICheckbox) { isSelected = !isSelected } }
5f84e85a6a82b6a9a5046a3dc6b9a586
28.190476
96
0.6488
false
false
false
false
byu-oit-appdev/ios-byuSuite
refs/heads/dev
byuSuite/Apps/YTime/controller/YTimeRootViewController.swift
apache-2.0
1
// // YTimeRootViewController.swift // byuSuite // // Created by Eric Romrell on 5/18/17. // Copyright © 2017 Brigham Young University. All rights reserved. // import CoreLocation private let TIMESHEETS_SEGUE_ID = "showTimesheets" private let CALENDAR_SEGUE_ID = "showCalendar" class YTimeRootViewController: ByuViewController2, UITableViewDataSource, CLLocationManagerDelegate, YTimePunchDelegate { private struct UI { static var fadeDuration = 0.25 } //MARK: Outlets @IBOutlet private weak var tableView: UITableView! @IBOutlet private weak var spinner: UIActivityIndicatorView! @IBOutlet private weak var viewTimesheetButton: UIBarButtonItem! //MARK: Properties private var refreshControl = UIRefreshControl() private var timesheet: YTimeTimesheet? private var punch: YTimePunch? private var readyToPunch = false private var punchLocation: CLLocation? private var locationManager: CLLocationManager? private var loadingView: LoadingView? override func viewDidLoad() { super.viewDidLoad() tableView.hideEmptyCells() refreshControl = tableView.addDefaultRefreshControl(target: self, action: #selector(loadData)) loadData() } override func viewWillAppear(_ animated: Bool) { NotificationCenter.default.addObserver(self, selector: #selector(hideAndLoadTable), name: .UIApplicationWillEnterForeground, object: nil) } override func viewWillDisappear(_ animated: Bool) { NotificationCenter.default.removeObserver(self) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == TIMESHEETS_SEGUE_ID, let vc = segue.destination.childViewControllers.first as? YTimeJobsViewController, let jobs = timesheet?.jobs { vc.jobs = jobs } else if segue.identifier == CALENDAR_SEGUE_ID, let vc = segue.destination.childViewControllers.first as? YTimeCalendarViewController, let job = timesheet?.jobs.first { //Use the first job, as this segue will only ever happen when the user only has one job vc.job = job } } deinit { locationManager?.delegate = nil } //MARK: UITableViewDataSource/Delegate callbacks func numberOfSections(in tableView: UITableView) -> Int { //The first section contains all of the jobs, the second contains the hour summaries return 2 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { //Return 2 for the weekly and period summaries return section == 0 ? timesheet?.jobs.count ?? 0 : 2 } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if indexPath.section == 0 { tableView.estimatedRowHeight = 100 return UITableViewAutomaticDimension } else { return 45 } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.section == 0, let cell = tableView.dequeueReusableCell(for: indexPath, identifier: "jobCell") as? YTimeJobTableViewCell { cell.delegate = self //We added the delegate so that we could allow the view controller to handle the punch logic rather than each cell cell.job = timesheet?.jobs[indexPath.row] return cell } else { let cell = tableView.dequeueReusableCell(for: indexPath, identifier: "paySummary") if indexPath.row == 0 { cell.textLabel?.text = "Week Total:" cell.detailTextLabel?.text = timesheet?.weeklyTotal } else { cell.textLabel?.text = "Pay Period Total:" cell.detailTextLabel?.text = timesheet?.periodTotal } return cell } } //MARK: CLLocationMangerDelegate callbacks func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { YTimeRootViewController.yTimeLocationManager(manager, didChangeAuthorization: status, for: self, deniedCompletionHandler: { self.loadData() //If attempted to punch without location services, remove the loadingView and enable interaction again on table. self.loadingView?.removeFromSuperview() self.tableView.isUserInteractionEnabled = true //Remove any saved punches to prevent them being used without location services enabled. self.punch = nil }) } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { punchLocation = locations.last manager.stopUpdatingLocation() loadingView?.setMessage("Processing Punch...") punchIfReady() } //MARK: YTimePunchDelegate callback func createPunch(punchIn: Bool, job: YTimeJob, sender: Any) { if let employeeRecord = job.employeeRecord { punch = YTimePunch(employeeRecord: employeeRecord, clockingIn: punchIn) if punchIn == job.clockedIn { //Verify that they want to double punch let status = punchIn ? "in" : "out" displayActionSheet(from: sender, title: "You are already clocked \(status). Please confirm that you would like to clock \(status) again.", actions: [ UIAlertAction(title: "Confirm", style: .default, handler: { (_) in self.startRequest() }) ]) } else { startRequest() } } } //MARK: Listeners @objc func hideAndLoadTable() { spinner.startAnimating() tableView.isUserInteractionEnabled = false tableView.alpha = 0 loadData() } @objc func loadData() { YTimeClient.getTimesheet { (sheet, error) in //If refreshing the table, end the refresh control. If loading view for first time, stop the spinner and make the table visible. self.refreshControl.endRefreshing() self.spinner.stopAnimating() UIView.animate(withDuration: UI.fadeDuration) { self.tableView.isUserInteractionEnabled = true self.tableView.alpha = 1 } if let sheet = sheet { self.timesheet = sheet if sheet.jobs.count == 0 { super.displayAlert(title: "No Jobs", message: "You are not listed as a BYU employee in the Y-Time system. Contact your supervisor if you believe this notice is in error.") } self.viewTimesheetButton.isEnabled = true } else { super.displayAlert(error: error, alertHandler: nil) } self.tableView.reloadData() } } @IBAction func didTapTimesheetButton(_ sender: Any) { if timesheet?.jobs.count ?? 0 > 1 { performSegue(withIdentifier: TIMESHEETS_SEGUE_ID, sender: sender) } else { performSegue(withIdentifier: CALENDAR_SEGUE_ID, sender: sender) } } //MARK: Private functions private func startRequest() { loadingView = self.displayLoadingView(message: "Determining Location...") //Disable the table to prevent inadvertent multiple taps tableView.isUserInteractionEnabled = false //Request a location locationManager = CLLocationManager() locationManager?.delegate = self locationManager?.requestWhenInUseAuthorization() //We are now ready to punch whenever a location has been found readyToPunch = true punchIfReady() } private func punchIfReady() { if readyToPunch, let location = punchLocation, let punch = punch { readyToPunch = false punch.location = location YTimeClient.createPunch(punch) { (sheet, error) in self.loadingView?.removeFromSuperview() self.tableView.isUserInteractionEnabled = true //Clear punchLocation after we pass it to the method, to prevent it being saved and sending later. Set to nil here, because LocationManager still resets location right after we stop it updating. self.punchLocation = nil if let sheet = sheet { self.timesheet = sheet self.showToast(message: "Your punch was submitted successfully.\nIt may take a few minutes for these changes to reflect in your timesheet.", dismissDelay: 5) self.viewTimesheetButton.isEnabled = true } else { super.displayAlert(error: error, alertHandler: nil) } self.tableView.reloadData() } } } //MARK: Static Methods static func yTimeLocationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus, for viewController: ByuViewController2, deniedCompletionHandler: (() -> Void)? = nil ) { if status == .denied || status == .restricted { manager.stopUpdatingLocation() let alert = UIAlertController(title: "Location Services Required", message: "In order to create punches, location services must be enabled. Please change your settings to allow for this.", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .cancel)) alert.addAction(UIAlertAction(title: "Settings", style: .default, handler: { (_) in if let url = URL(string: UIApplicationOpenSettingsURLString) { UIApplication.open(url: url) } })) viewController.present(alert, animated: true, completion: deniedCompletionHandler) } else { manager.startUpdatingLocation() } } }
763e78e08dfac3dcdc1ad15630be098e
36.479839
215
0.686498
false
false
false
false
devpunk/velvet_room
refs/heads/master
Source/View/SaveData/VSaveData.swift
mit
1
import UIKit final class VSaveData:ViewMain { private(set) weak var viewBar:VSaveDataBar! private weak var viewList:VSaveDataList! private weak var viewBack:VSaveDataBarBack! override var panBack:Bool { get { return true } } required init(controller:UIViewController) { super.init(controller:controller) guard let controller:CSaveData = controller as? CSaveData else { return } factoryViews(controller:controller) } required init?(coder:NSCoder) { return nil } override func layoutSubviews() { super.layoutSubviews() let barHeight:CGFloat = viewBar.bounds.height let backRemainHeight:CGFloat = barHeight - viewBack.kHeight let backMarginBottom:CGFloat = backRemainHeight / -2.0 viewBack.layoutBottom.constant = backMarginBottom } //MARK: private private func factoryViews(controller:CSaveData) { let viewList:VSaveDataList = VSaveDataList( controller:controller) self.viewList = viewList let viewBar:VSaveDataBar = VSaveDataBar( controller:controller) self.viewBar = viewBar let viewBack:VSaveDataBarBack = VSaveDataBarBack( controller:controller) self.viewBack = viewBack addSubview(viewBar) addSubview(viewList) addSubview(viewBack) NSLayoutConstraint.topToTop( view:viewBar, toView:self) viewBar.layoutHeight = NSLayoutConstraint.height( view:viewBar, constant:viewList.kMinBarHeight) NSLayoutConstraint.equalsHorizontal( view:viewBar, toView:self) NSLayoutConstraint.equals( view:viewList, toView:self) viewBack.layoutBottom = NSLayoutConstraint.bottomToBottom( view:viewBack, toView:viewBar) NSLayoutConstraint.height( view:viewBack, constant:viewBack.kHeight) NSLayoutConstraint.width( view:viewBack, constant:viewBack.kWidth) NSLayoutConstraint.leftToLeft( view:viewBack, toView:self) } }
06e93858e548c2f445eae94f640efb28
24.494737
67
0.580099
false
false
false
false
dfsilva/actor-platform
refs/heads/master
actor-sdk/sdk-core-ios/ActorSDK/Sources/Controllers/Conversation/ConversationViewController.swift
agpl-3.0
1
// // Copyright (c) 2014-2016 Actor LLC. <https://actor.im> // import Foundation import UIKit import MobileCoreServices import AddressBook import AddressBookUI import AVFoundation //import AGEmojiKeyboard final public class ConversationViewController: AAConversationContentController, UIDocumentMenuDelegate, UIDocumentPickerDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate, AALocationPickerControllerDelegate, ABPeoplePickerNavigationControllerDelegate, AAAudioRecorderDelegate, AAConvActionSheetDelegate, AAStickersKeyboardDelegate //, //AGEmojiKeyboardViewDataSource, // AGEmojiKeyboardViewDelegate { // Data binder fileprivate let binder = AABinder() // Internal state // Members for autocomplete var filteredMembers = [ACMentionFilterResult]() let content: ACPage! var appStyle: ActorStyle { get { return ActorSDK.sharedActor().style } } // // Views // fileprivate let titleView: UILabel = UILabel() open let subtitleView: UILabel = UILabel() fileprivate let navigationView: UIView = UIView() fileprivate let avatarView = AABarAvatarView() fileprivate let backgroundView = UIImageView() fileprivate var audioButton: UIButton = UIButton() fileprivate var voiceRecorderView : AAVoiceRecorderView! fileprivate let inputOverlay = UIView() fileprivate let inputOverlayLabel = UILabel() // // Stickers // fileprivate var stickersView: AAStickersKeyboard! open var stickersButton : UIButton! fileprivate var stickersOpen = false //fileprivate var emojiKeyboar: AGEmojiKeyboardView! // // Audio Recorder // open var audioRecorder: AAAudioRecorder! // // Mode // fileprivate var textMode:Bool! fileprivate var micOn: Bool! = true open var removeExcedentControllers = true //////////////////////////////////////////////////////////// // MARK: - Init //////////////////////////////////////////////////////////// required override public init(peer: ACPeer) { // Data self.content = ACAllEvents_Chat_viewWithACPeer_(peer) // Create controller super.init(peer: peer) // // Background // backgroundView.clipsToBounds = true backgroundView.contentMode = .scaleAspectFill backgroundView.backgroundColor = appStyle.chatBgColor // Custom background if available if let bg = Actor.getSelectedWallpaper(){ if bg != "default" { if bg.startsWith("local:") { backgroundView.image = UIImage.bundled(bg.skip(6)) } else { let path = CocoaFiles.pathFromDescriptor(bg.skip(5)) backgroundView.image = UIImage(contentsOfFile:path) } } } view.insertSubview(backgroundView, at: 0) // // slk settings // self.bounces = false self.isKeyboardPanningEnabled = true self.registerPrefixes(forAutoCompletion: ["@"]) // // Text Input // self.textInputbar.backgroundColor = appStyle.chatInputFieldBgColor self.textInputbar.autoHideRightButton = false; self.textInputbar.isTranslucent = false // // Text view // self.textView.placeholder = AALocalized("ChatPlaceholder") self.textView.keyboardAppearance = ActorSDK.sharedActor().style.isDarkApp ? .dark : .light // // Overlay // self.inputOverlay.addSubview(inputOverlayLabel) self.inputOverlayLabel.textAlignment = .center self.inputOverlayLabel.font = UIFont.systemFont(ofSize: 18) self.inputOverlayLabel.textColor = ActorSDK.sharedActor().style.vcTintColor self.inputOverlay.viewDidTap = { self.onOverlayTap() } // // Add stickers button // self.stickersButton = UIButton(type: UIButtonType.system) self.stickersButton.tintColor = UIColor.lightGray.withAlphaComponent(0.5) self.stickersButton.setImage(UIImage.bundled("sticker_button"), for: UIControlState()) self.stickersButton.addTarget(self, action: #selector(ConversationViewController.changeKeyboard), for: UIControlEvents.touchUpInside) if(ActorSDK.sharedActor().delegate.showStickersButton()){ self.textInputbar.addSubview(stickersButton) } // // Check text for set right button // let checkText = Actor.loadDraft(with: peer)!.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) if (checkText.isEmpty) { self.textMode = false self.rightButton.tintColor = appStyle.chatSendColor self.rightButton.setImage(UIImage.tinted("aa_micbutton", color: appStyle.chatAttachColor), for: UIControlState()) self.rightButton.setTitle("", for: UIControlState()) self.rightButton.isEnabled = true self.rightButton.layoutIfNeeded() self.rightButton.addTarget(self, action: #selector(ConversationViewController.beginRecord(_:event:)), for: UIControlEvents.touchDown) self.rightButton.addTarget(self, action: #selector(ConversationViewController.mayCancelRecord(_:event:)), for: UIControlEvents.touchDragInside.union(UIControlEvents.touchDragOutside)) self.rightButton.addTarget(self, action: #selector(ConversationViewController.finishRecord(_:event:)), for: UIControlEvents.touchUpInside.union(UIControlEvents.touchCancel).union(UIControlEvents.touchUpOutside)) } else { self.textMode = true self.stickersButton.isHidden = true self.rightButton.setTitle(AALocalized("ChatSend"), for: UIControlState()) self.rightButton.setTitleColor(appStyle.chatSendColor, for: UIControlState()) self.rightButton.setTitleColor(appStyle.chatSendDisabledColor, for: UIControlState.disabled) self.rightButton.setImage(nil, for: UIControlState()) self.rightButton.isEnabled = true self.rightButton.layoutIfNeeded() } // // Voice Recorder // self.audioRecorder = AAAudioRecorder() self.audioRecorder.delegate = self self.leftButton.setImage(UIImage.tinted("conv_attach", color: appStyle.chatAttachColor), for: UIControlState()) // // Navigation Title // navigationView.frame = CGRect(x: 0, y: 0, width: 200, height: 44) navigationView.autoresizingMask = UIViewAutoresizing.flexibleWidth titleView.font = UIFont.mediumSystemFontOfSize(17) titleView.adjustsFontSizeToFitWidth = false titleView.textAlignment = NSTextAlignment.center titleView.lineBreakMode = NSLineBreakMode.byTruncatingTail titleView.autoresizingMask = UIViewAutoresizing.flexibleWidth titleView.textColor = appStyle.navigationTitleColor subtitleView.font = UIFont.systemFont(ofSize: 13) subtitleView.adjustsFontSizeToFitWidth = true subtitleView.textAlignment = NSTextAlignment.center subtitleView.lineBreakMode = NSLineBreakMode.byTruncatingTail subtitleView.autoresizingMask = UIViewAutoresizing.flexibleWidth navigationView.addSubview(titleView) navigationView.addSubview(subtitleView) self.navigationItem.titleView = navigationView // // Navigation Avatar // avatarView.frame = CGRect(x: 0, y: 0, width: 40, height: 40) avatarView.viewDidTap = onAvatarTap let barItem = UIBarButtonItem(customView: avatarView) let isBot: Bool if (peer.isPrivate) { isBot = Bool(Actor.getUserWithUid(peer.peerId).isBot()) } else { isBot = false } if (ActorSDK.sharedActor().enableCalls && !isBot && peer.isPrivate) { if ActorSDK.sharedActor().enableVideoCalls { let callButtonView = AACallButton(image: UIImage.bundled("ic_call_outline_22")?.tintImage(ActorSDK.sharedActor().style.navigationTintColor)) callButtonView.viewDidTap = onCallTap let callButtonItem = UIBarButtonItem(customView: callButtonView) let videoCallButtonView = AACallButton(image: UIImage.bundled("ic_video_outline_22")?.tintImage(ActorSDK.sharedActor().style.navigationTintColor)) videoCallButtonView.viewDidTap = onVideoCallTap let callVideoButtonItem = UIBarButtonItem(customView: videoCallButtonView) self.navigationItem.rightBarButtonItems = [barItem, callVideoButtonItem, callButtonItem] } else { let callButtonView = AACallButton(image: UIImage.bundled("ic_call_outline_22")?.tintImage(ActorSDK.sharedActor().style.navigationTintColor)) callButtonView.viewDidTap = onCallTap let callButtonItem = UIBarButtonItem(customView: callButtonView) self.navigationItem.rightBarButtonItems = [barItem, callButtonItem] } } else { self.navigationItem.rightBarButtonItems = [barItem] } } required public init(coder aDecoder: NSCoder!) { fatalError("init(coder:) has not been implemented") } override open func viewDidLoad() { super.viewDidLoad() self.voiceRecorderView = AAVoiceRecorderView(frame: CGRect(x: 0, y: 0, width: view.width - 30, height: 44)) self.voiceRecorderView.isHidden = true self.voiceRecorderView.binedController = self self.textInputbar.addSubview(self.voiceRecorderView) self.inputOverlay.backgroundColor = UIColor.white self.inputOverlay.isHidden = false self.textInputbar.addSubview(self.inputOverlay) navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: UIBarButtonItemStyle.plain, target: nil, action: nil) let frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 216) self.stickersView = AAStickersKeyboard(frame: frame) self.stickersView.delegate = self //emojiKeyboar.frame = frame NotificationCenter.default.addObserver( self, selector: #selector(ConversationViewController.updateStickersStateOnCloseKeyboard), name: NSNotification.Name.SLKKeyboardWillHide, object: nil) } open override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() self.stickersButton.frame = CGRect(x: self.view.frame.size.width-67, y: 12, width: 20, height: 20) self.voiceRecorderView.frame = CGRect(x: 0, y: 0, width: view.width - 30, height: 44) self.inputOverlay.frame = CGRect(x: 0, y: 0, width: view.width, height: 44) self.inputOverlayLabel.frame = CGRect(x: 0, y: 0, width: view.width, height: 44) } //////////////////////////////////////////////////////////// // MARK: - Lifecycle //////////////////////////////////////////////////////////// override open func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Installing bindings if (peer.peerType.ordinal() == ACPeerType.private().ordinal()) { let user = Actor.getUserWithUid(peer.peerId) let nameModel = user.getNameModel() let blockStatus = user.isBlockedModel().get().booleanValue() binder.bind(nameModel, closure: { (value: NSString?) -> () in self.titleView.text = String(value!) self.navigationView.sizeToFit() }) binder.bind(user.getAvatarModel(), closure: { (value: ACAvatar?) -> () in self.avatarView.bind(user.getNameModel().get(), id: Int(user.getId()), avatar: value) }) binder.bind(Actor.getTypingWithUid(peer.peerId), valueModel2: user.getPresenceModel(), closure:{ (typing:JavaLangBoolean?, presence:ACUserPresence?) -> () in if (typing != nil && typing!.booleanValue()) { self.subtitleView.text = Actor.getFormatter().formatTyping() self.subtitleView.textColor = self.appStyle.navigationSubtitleActiveColor } else { if (user.isBot()) { self.subtitleView.text = "bot" self.subtitleView.textColor = self.appStyle.userOnlineNavigationColor } else { let stateText = Actor.getFormatter().formatPresence(presence, with: user.getSex()) self.subtitleView.text = stateText; let state = presence!.state.ordinal() if (state == ACUserPresence_State.online().ordinal()) { self.subtitleView.textColor = self.appStyle.userOnlineNavigationColor } else { self.subtitleView.textColor = self.appStyle.userOfflineNavigationColor } } } }) self.inputOverlay.isHidden = true } else if (peer.peerType.ordinal() == ACPeerType.group().ordinal()) { let group = Actor.getGroupWithGid(peer.peerId) let nameModel = group.getNameModel() binder.bind(nameModel, closure: { (value: NSString?) -> () in self.titleView.text = String(value!); self.navigationView.sizeToFit(); }) binder.bind(group.getAvatarModel(), closure: { (value: ACAvatar?) -> () in self.avatarView.bind(group.getNameModel().get(), id: Int(group.getId()), avatar: value) }) binder.bind(Actor.getGroupTyping(withGid: group.getId()), valueModel2: group.membersCount, valueModel3: group.getPresenceModel(), closure: { (typingValue:IOSIntArray?, membersCount: JavaLangInteger?, onlineCount:JavaLangInteger?) -> () in if (!group.isMemberModel().get().booleanValue()) { self.subtitleView.text = AALocalized("ChatNoGroupAccess") self.subtitleView.textColor = self.appStyle.navigationSubtitleColor return } if (typingValue != nil && typingValue!.length() > 0) { self.subtitleView.textColor = self.appStyle.navigationSubtitleActiveColor if (typingValue!.length() == 1) { let uid = typingValue!.int(at: 0); let user = Actor.getUserWithUid(uid) self.subtitleView.text = Actor.getFormatter().formatTyping(withName: user.getNameModel().get()) } else { self.subtitleView.text = Actor.getFormatter().formatTyping(withCount: typingValue!.length()); } } else { var membersString = Actor.getFormatter().formatGroupMembers(membersCount!.intValue()) self.subtitleView.textColor = self.appStyle.navigationSubtitleColor if (onlineCount == nil || onlineCount!.intValue == 0) { self.subtitleView.text = membersString; } else { membersString = membersString! + ", "; let onlineString = Actor.getFormatter().formatGroupOnline(onlineCount!.intValue()); let attributedString = NSMutableAttributedString(string: (membersString! + onlineString!)) attributedString.addAttribute(NSForegroundColorAttributeName, value: self.appStyle.userOnlineNavigationColor, range: NSMakeRange(membersString!.length, onlineString!.length)) self.subtitleView.attributedText = attributedString } } }) binder.bind(group.isMember, valueModel2: group.isCanWriteMessage, valueModel3: group.isCanJoin, closure: { (isMember: JavaLangBoolean?, canWriteMessage: JavaLangBoolean?, canJoin: JavaLangBoolean?) in if canWriteMessage!.booleanValue() { self.stickersButton.isHidden = false self.inputOverlay.isHidden = true } else { if !isMember!.booleanValue() { if canJoin!.booleanValue() { self.inputOverlayLabel.text = AALocalized("ChatJoin") } else { self.inputOverlayLabel.text = AALocalized("ChatNoGroupAccess") } } else { if Actor.isNotificationsEnabled(with: self.peer) { self.inputOverlayLabel.text = AALocalized("ActionMute") } else { self.inputOverlayLabel.text = AALocalized("ActionUnmute") } } self.stickersButton.isHidden = true self.stopAudioRecording() self.textInputbar.textView.text = "" self.inputOverlay.isHidden = false } }) binder.bind(group.isDeleted) { (isDeleted: JavaLangBoolean?) in if isDeleted!.booleanValue() { self.alertUser(AALocalized("ChatDeleted")) { self.execute(Actor.deleteChatCommand(with: self.peer), successBlock: { (r) in self.navigateBack() }) } } } } Actor.onConversationOpen(with: peer) ActorSDK.sharedActor().trackPageVisible(content) if textView.isFirstResponder == false { textView.resignFirstResponder() } textView.text = Actor.loadDraft(with: peer) } open func onOverlayTap() { if peer.isGroup { let group = Actor.getGroupWithGid(peer.peerId) if !group.isMember.get().booleanValue() { if group.isCanJoin.get().booleanValue() { executePromise(Actor.joinGroup(withGid: peer.peerId)) } else { // DO NOTHING } } else if !group.isCanWriteMessage.get().booleanValue() { if Actor.isNotificationsEnabled(with: peer) { Actor.changeNotificationsEnabled(with: peer, withValue: false) inputOverlayLabel.text = AALocalized("ActionUnmute") } else { Actor.changeNotificationsEnabled(with: peer, withValue: true) inputOverlayLabel.text = AALocalized("ActionMute") } } } else if peer.isPrivate { } } override open func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() backgroundView.frame = view.bounds titleView.frame = CGRect(x: 0, y: 4, width: (navigationView.frame.width - 0), height: 20) subtitleView.frame = CGRect(x: 0, y: 22, width: (navigationView.frame.width - 0), height: 20) stickersView.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 216) //emojiKeyboar.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 216) } override open func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if self.removeExcedentControllers { if navigationController!.viewControllers.count > 2 { let firstController = navigationController!.viewControllers[0] let currentController = navigationController!.viewControllers[navigationController!.viewControllers.count - 1] navigationController!.setViewControllers([firstController, currentController], animated: false) } } if !AADevice.isiPad { AANavigationBadge.showBadge() } } override open func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) Actor.onConversationClosed(with: peer) ActorSDK.sharedActor().trackPageHidden(content) if !AADevice.isiPad { AANavigationBadge.hideBadge() } // Closing keyboard self.textView.resignFirstResponder() } override open func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) Actor.saveDraft(with: peer, withDraft: textView.text) // Releasing bindings binder.unbindAll() } //////////////////////////////////////////////////////////// // MARK: - Chat avatar tap //////////////////////////////////////////////////////////// func onAvatarTap() { let id = Int(peer.peerId) var controller: AAViewController! if (peer.peerType.ordinal() == ACPeerType.private().ordinal()) { controller = ActorSDK.sharedActor().delegate.actorControllerForUser(id) if controller == nil { controller = AAUserViewController(uid: id) } } else if (peer.peerType.ordinal() == ACPeerType.group().ordinal()) { controller = ActorSDK.sharedActor().delegate.actorControllerForGroup(id) if controller == nil { controller = AAGroupViewController(gid: id) } } else { return } if (AADevice.isiPad) { let navigation = AANavigationController() navigation.viewControllers = [controller] let popover = UIPopoverController(contentViewController: navigation) controller.popover = popover popover.present(from: navigationItem.rightBarButtonItem!, permittedArrowDirections: UIPopoverArrowDirection.up, animated: true) } else { navigateNext(controller, removeCurrent: false) } } func onCallTap() { if (self.peer.isGroup) { execute(ActorSDK.sharedActor().messenger.doCall(withGid: self.peer.peerId)) } else if (self.peer.isPrivate) { execute(ActorSDK.sharedActor().messenger.doCall(withUid: self.peer.peerId)) } } func onVideoCallTap() { if (self.peer.isPrivate) { execute(ActorSDK.sharedActor().messenger.doVideoCall(withUid: self.peer.peerId)) } } //////////////////////////////////////////////////////////// // MARK: - Text bar actions //////////////////////////////////////////////////////////// override open func textDidUpdate(_ animated: Bool) { super.textDidUpdate(animated) Actor.onTyping(with: peer) checkTextInTextView() } func checkTextInTextView() { let text = self.textView.text.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) self.rightButton.isEnabled = true //change button's if !text.isEmpty && textMode == false { self.rightButton.removeTarget(self, action: #selector(ConversationViewController.beginRecord(_:event:)), for: UIControlEvents.touchDown) self.rightButton.removeTarget(self, action: #selector(ConversationViewController.mayCancelRecord(_:event:)), for: UIControlEvents.touchDragInside.union(UIControlEvents.touchDragOutside)) self.rightButton.removeTarget(self, action: #selector(ConversationViewController.finishRecord(_:event:)), for: UIControlEvents.touchUpInside.union(UIControlEvents.touchCancel).union(UIControlEvents.touchUpOutside)) self.rebindRightButton() self.stickersButton.isHidden = true self.rightButton.setTitle(AALocalized("ChatSend"), for: UIControlState()) self.rightButton.setTitleColor(appStyle.chatSendColor, for: UIControlState()) self.rightButton.setTitleColor(appStyle.chatSendDisabledColor, for: UIControlState.disabled) self.rightButton.setImage(nil, for: UIControlState()) self.rightButton.layoutIfNeeded() self.textInputbar.layoutIfNeeded() self.textMode = true } else if (text.isEmpty && textMode == true) { self.rightButton.addTarget(self, action: #selector(ConversationViewController.beginRecord(_:event:)), for: UIControlEvents.touchDown) self.rightButton.addTarget(self, action: #selector(ConversationViewController.mayCancelRecord(_:event:)), for: UIControlEvents.touchDragInside.union(UIControlEvents.touchDragOutside)) self.rightButton.addTarget(self, action: #selector(ConversationViewController.finishRecord(_:event:)), for: UIControlEvents.touchUpInside.union(UIControlEvents.touchCancel).union(UIControlEvents.touchUpOutside)) self.stickersButton.isHidden = false self.rightButton.tintColor = appStyle.chatAttachColor self.rightButton.setImage(UIImage.bundled("aa_micbutton"), for: UIControlState()) self.rightButton.setTitle("", for: UIControlState()) self.rightButton.isEnabled = true self.rightButton.layoutIfNeeded() self.textInputbar.layoutIfNeeded() self.textMode = false } } //////////////////////////////////////////////////////////// // MARK: - Right/Left button pressed //////////////////////////////////////////////////////////// override open func didPressRightButton(_ sender: Any!) { if !self.textView.text.isEmpty { Actor.sendMessage(withMentionsDetect: peer, withText: textView.text) super.didPressRightButton(sender) } } override open func didPressLeftButton(_ sender: Any!) { super.didPressLeftButton(sender) self.textInputbar.textView.resignFirstResponder() self.rightButton.layoutIfNeeded() if !ActorSDK.sharedActor().delegate.actorConversationCustomAttachMenu(self) { let actionSheet = AAConvActionSheet() actionSheet.addCustomButton("SendDocument") actionSheet.addCustomButton("ShareLocation") actionSheet.addCustomButton("ShareContact") actionSheet.delegate = self actionSheet.presentInController(self) } } //////////////////////////////////////////////////////////// // MARK: - Completition //////////////////////////////////////////////////////////// override open func didChangeAutoCompletionPrefix(_ prefix: String!, andWord word: String!) { if self.peer.peerType.ordinal() == ACPeerType.group().ordinal() { if prefix == "@" { let oldCount = filteredMembers.count filteredMembers.removeAll(keepingCapacity: true) let res = Actor.findMentions(withGid: self.peer.peerId, withQuery: word)! for index in 0..<res.size() { filteredMembers.append(res.getWith(index) as! ACMentionFilterResult) } if oldCount == filteredMembers.count { self.autoCompletionView.reloadData() } dispatchOnUi { () -> Void in self.showAutoCompletionView(self.filteredMembers.count > 0) } return } } dispatchOnUi { () -> Void in self.showAutoCompletionView(false) } } //////////////////////////////////////////////////////////// // MARK: - TableView for completition //////////////////////////////////////////////////////////// override open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return filteredMembers.count } override open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let res = AAAutoCompleteCell(style: UITableViewCellStyle.default, reuseIdentifier: "user_name") res.bindData(filteredMembers[(indexPath as NSIndexPath).row], highlightWord: foundWord) return res } override open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let user = filteredMembers[(indexPath as NSIndexPath).row] var postfix = " " if foundPrefixRange.location == 0 { postfix = ": " } acceptAutoCompletion(with: user.mentionString + postfix, keepPrefix: !user.isNickname) } override open func heightForAutoCompletionView() -> CGFloat { let cellHeight: CGFloat = 44.0; return cellHeight * CGFloat(filteredMembers.count) } override open func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { cell.separatorInset = UIEdgeInsets.zero cell.preservesSuperviewLayoutMargins = false cell.layoutMargins = UIEdgeInsets.zero } //////////////////////////////////////////////////////////// // MARK: - Picker //////////////////////////////////////////////////////////// open func actionSheetPickedImages(_ images:[(Data,Bool)]) { for (i,j) in images { Actor.sendUIImage(i, peer: peer, animated:j) } } open func actionSheetPickCamera() { pickImage(.camera) } open func actionSheetPickGallery() { pickImage(.photoLibrary) } open func actionSheetCustomButton(_ index: Int) { if index == 0 { pickDocument() } else if index == 1 { pickLocation() } else if index == 2 { pickContact() } } open func pickContact() { let pickerController = ABPeoplePickerNavigationController() pickerController.peoplePickerDelegate = self self.present(pickerController, animated: true, completion: nil) } open func pickLocation() { let pickerController = AALocationPickerController() pickerController.delegate = self self.present(AANavigationController(rootViewController:pickerController), animated: true, completion: nil) } open func pickDocument() { let documentPicker = UIDocumentMenuViewController(documentTypes: UTTAll as [String], in: UIDocumentPickerMode.import) documentPicker.view.backgroundColor = UIColor.clear documentPicker.delegate = self self.present(documentPicker, animated: true, completion: nil) } //////////////////////////////////////////////////////////// // MARK: - Document picking //////////////////////////////////////////////////////////// open func documentMenu(_ documentMenu: UIDocumentMenuViewController, didPickDocumentPicker documentPicker: UIDocumentPickerViewController) { documentPicker.delegate = self self.present(documentPicker, animated: true, completion: nil) } open func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) { // Loading path and file name let path = url.path let fileName = url.lastPathComponent // Check if file valid or directory var isDir : ObjCBool = false if !FileManager.default.fileExists(atPath: path, isDirectory: &isDir) { // Not exists return } // Destination file let descriptor = "/tmp/\(UUID().uuidString)" let destPath = CocoaFiles.pathFromDescriptor(descriptor) if isDir.boolValue { // Zipping contents and sending execute(AATools.zipDirectoryCommand(path, to: destPath)) { (val) -> Void in Actor.sendDocument(with: self.peer, withName: fileName, withMime: "application/zip", withDescriptor: descriptor) } } else { // Sending file itself execute(AATools.copyFileCommand(path, to: destPath)) { (val) -> Void in Actor.sendDocument(with: self.peer, withName: fileName, withMime: "application/octet-stream", withDescriptor: descriptor) } } } //////////////////////////////////////////////////////////// // MARK: - Image picking //////////////////////////////////////////////////////////// func pickImage(_ source: UIImagePickerControllerSourceType) { if(source == .camera && (AVAudioSession.sharedInstance().recordPermission() == AVAudioSessionRecordPermission.undetermined || AVAudioSession.sharedInstance().recordPermission() == AVAudioSessionRecordPermission.denied)){ AVAudioSession.sharedInstance().requestRecordPermission({_ in (Bool).self}) } let pickerController = AAImagePickerController() pickerController.sourceType = source pickerController.mediaTypes = [kUTTypeImage as String,kUTTypeMovie as String] pickerController.delegate = self self.present(pickerController, animated: true, completion: nil) } open func imagePickerController(_ picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) { picker.dismiss(animated: true, completion: nil) let imageData = UIImageJPEGRepresentation(image, 0.8) Actor.sendUIImage(imageData!, peer: peer, animated:false) } open func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { picker.dismiss(animated: true, completion: nil) if let image = info[UIImagePickerControllerOriginalImage] as? UIImage { let imageData = UIImageJPEGRepresentation(image, 0.8) //TODO: Need implement assert fetching here to get images Actor.sendUIImage(imageData!, peer: peer, animated:false) } else { Actor.sendVideo(info[UIImagePickerControllerMediaURL] as! URL, peer: peer) } } open func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { picker.dismiss(animated: true, completion: nil) } //////////////////////////////////////////////////////////// // MARK: - Location picking //////////////////////////////////////////////////////////// open func locationPickerDidCancelled(_ controller: AALocationPickerController) { controller.dismiss(animated: true, completion: nil) } open func locationPickerDidPicked(_ controller: AALocationPickerController, latitude: Double, longitude: Double) { Actor.sendLocation(with: self.peer, withLongitude: JavaLangDouble(value: longitude), withLatitude: JavaLangDouble(value: latitude), withStreet: nil, withPlace: nil) controller.dismiss(animated: true, completion: nil) } //////////////////////////////////////////////////////////// // MARK: - Contact picking //////////////////////////////////////////////////////////// open func peoplePickerNavigationController(_ peoplePicker: ABPeoplePickerNavigationController, didSelectPerson person: ABRecord) { // Dismissing picker peoplePicker.dismiss(animated: true, completion: nil) // Names let name = ABRecordCopyCompositeName(person)?.takeRetainedValue() as String? // Avatar var jAvatarImage: String? = nil let hasAvatarImage = ABPersonHasImageData(person) if (hasAvatarImage) { let imgData = ABPersonCopyImageDataWithFormat(person, kABPersonImageFormatOriginalSize).takeRetainedValue() let image = UIImage(data: imgData as Data)?.resizeSquare(90, maxH: 90) if (image != nil) { let thumbData = UIImageJPEGRepresentation(image!, 0.55) jAvatarImage = thumbData?.base64EncodedString(options: NSData.Base64EncodingOptions()) } } // Phones let jPhones = JavaUtilArrayList() let phoneNumbers: ABMultiValue = ABRecordCopyValue(person, kABPersonPhoneProperty).takeRetainedValue() let phoneCount = ABMultiValueGetCount(phoneNumbers) for i in 0 ..< phoneCount { let phone = (ABMultiValueCopyValueAtIndex(phoneNumbers, i).takeRetainedValue() as! String).trim() jPhones?.add(withId: phone) } // Email let jEmails = JavaUtilArrayList() let emails: ABMultiValue = ABRecordCopyValue(person, kABPersonEmailProperty).takeRetainedValue() let emailsCount = ABMultiValueGetCount(emails) for i in 0 ..< emailsCount { let email = (ABMultiValueCopyValueAtIndex(emails, i).takeRetainedValue() as! String).trim() if (email.length > 0) { jEmails?.add(withId: email) } } // Sending Actor.sendContact(with: self.peer, withName: name!, withPhones: jPhones!, withEmails: jEmails!, withPhoto: jAvatarImage) } //////////////////////////////////////////////////////////// // MARK: - // MARK: Audio recording statments + send //////////////////////////////////////////////////////////// func onAudioRecordingStarted() { print("onAudioRecordingStarted\n") stopAudioRecording() // stop voice player when start recording if (self.voicePlayer?.playbackPosition() != 0.0) { self.voicePlayer?.audioPlayerStopAndFinish() } audioRecorder.delegate = self audioRecorder.start() } func onAudioRecordingFinished() { print("onAudioRecordingFinished\n") audioRecorder.finish { (path: String?, duration: TimeInterval) -> Void in if (nil == path) { print("onAudioRecordingFinished: empty path") return } NSLog("onAudioRecordingFinished: %@ [%lfs]", path!, duration) let range = path!.range(of: "/tmp", options: NSString.CompareOptions(), range: nil, locale: nil) let descriptor = path!.substring(from: range!.lowerBound) NSLog("Audio Recording file: \(descriptor)") Actor.sendAudio(with: self.peer, withName: NSString.localizedStringWithFormat("%@.ogg", UUID().uuidString) as String, withDuration: jint(duration*1000), withDescriptor: descriptor) } audioRecorder.cancel() } open func audioRecorderDidStartRecording() { self.voiceRecorderView.recordingStarted() } func onAudioRecordingCancelled() { stopAudioRecording() } func stopAudioRecording() { if (audioRecorder != nil) { audioRecorder.delegate = nil audioRecorder.cancel() } } func beginRecord(_ button:UIButton,event:UIEvent) { self.voiceRecorderView.startAnimation() self.voiceRecorderView.isHidden = false self.stickersButton.isHidden = true let touches : Set<UITouch> = event.touches(for: button)! let touch = touches.first! let location = touch.location(in: button) self.voiceRecorderView.trackTouchPoint = location self.voiceRecorderView.firstTouchPoint = location self.onAudioRecordingStarted() } func mayCancelRecord(_ button:UIButton,event:UIEvent) { let touches : Set<UITouch> = event.touches(for: button)! let touch = touches.first! let currentLocation = touch.location(in: button) if (currentLocation.x < self.rightButton.frame.origin.x) { if (self.voiceRecorderView.trackTouchPoint.x > currentLocation.x) { self.voiceRecorderView.updateLocation(currentLocation.x - self.voiceRecorderView.trackTouchPoint.x,slideToRight: false) } else { self.voiceRecorderView.updateLocation(currentLocation.x - self.voiceRecorderView.trackTouchPoint.x,slideToRight: true) } } self.voiceRecorderView.trackTouchPoint = currentLocation if ((self.voiceRecorderView.firstTouchPoint.x - self.voiceRecorderView.trackTouchPoint.x) > 120) { //cancel self.voiceRecorderView.isHidden = true self.stickersButton.isHidden = false self.stopAudioRecording() self.voiceRecorderView.recordingStoped() button.cancelTracking(with: event) closeRecorderAnimation() } } func closeRecorderAnimation() { let leftButtonFrame = self.leftButton.frame leftButton.frame.origin.x = -100 let textViewFrame = self.textView.frame textView.frame.origin.x = textView.frame.origin.x + 500 let stickerViewFrame = self.stickersButton.frame stickersButton.frame.origin.x = self.stickersButton.frame.origin.x + 500 UIView.animate(withDuration: 1.5, delay: 0.0, usingSpringWithDamping: 0.5, initialSpringVelocity: 1.0, options: UIViewAnimationOptions.curveLinear, animations: { () -> Void in self.leftButton.frame = leftButtonFrame self.textView.frame = textViewFrame self.stickersButton.frame = stickerViewFrame }, completion: { (complite) -> Void in // animation complite }) } func finishRecord(_ button:UIButton,event:UIEvent) { closeRecorderAnimation() self.voiceRecorderView.isHidden = true self.stickersButton.isHidden = false self.onAudioRecordingFinished() self.voiceRecorderView.recordingStoped() } //////////////////////////////////////////////////////////// // MARK: - Stickers actions //////////////////////////////////////////////////////////// open func updateStickersStateOnCloseKeyboard() { self.stickersOpen = false self.stickersButton.setImage(UIImage.bundled("sticker_button"), for: UIControlState()) self.textInputbar.textView.inputView = nil } open func changeKeyboard() { if self.stickersOpen == false { //self.stickersView.loadStickers() self.textInputbar.textView.inputView = self.stickersView //self.textInputbar.textView.inputView = self.emojiKeyboar self.textInputbar.textView.inputView?.isOpaque = false self.textInputbar.textView.inputView?.backgroundColor = UIColor.clear self.textInputbar.textView.refreshFirstResponder() self.textInputbar.textView.refreshInputViews() self.textInputbar.textView.becomeFirstResponder() self.stickersButton.setImage(UIImage.bundled("keyboard_button"), for: UIControlState()) self.stickersOpen = true } else { self.textInputbar.textView.inputView = nil self.textInputbar.textView.refreshFirstResponder() self.textInputbar.textView.refreshInputViews() self.textInputbar.textView.becomeFirstResponder() self.stickersButton.setImage(UIImage.bundled("sticker_button"), for: UIControlState()) self.stickersOpen = false } self.textInputbar.layoutIfNeeded() self.view.layoutIfNeeded() } open func stickerDidSelected(_ keyboard: AAStickersKeyboard, sticker: ACSticker) { Actor.sendSticker(with: self.peer, with: sticker) } /* public func emojiKeyboardView(_ emojiKeyboardView: AGEmojiKeyboardView!, imageForSelectedCategory category: AGEmojiKeyboardViewCategoryImage) -> UIImage{ switch category { case .recent: return UIImage.bundled("ic_smiles_recent")! case .face: return UIImage.bundled("ic_smiles_smile")! case .car: return UIImage.bundled("ic_smiles_car")! case .bell: return UIImage.bundled("ic_smiles_bell")! case .flower: return UIImage.bundled("ic_smiles_flower")! case .characters: return UIImage.bundled("ic_smiles_grid")! } } public func emojiKeyboardView(_ emojiKeyboardView: AGEmojiKeyboardView!, imageForNonSelectedCategory category: AGEmojiKeyboardViewCategoryImage) -> UIImage!{ switch category { case .recent: return UIImage.bundled("ic_smiles_recent")! case .face: return UIImage.bundled("ic_smiles_smile")! case .car: return UIImage.bundled("ic_smiles_car")! case .bell: return UIImage.bundled("ic_smiles_bell")! case .flower: return UIImage.bundled("ic_smiles_flower")! case .characters: return UIImage.bundled("ic_smiles_grid")! } } public func backSpaceButtonImage(for emojiKeyboardView: AGEmojiKeyboardView!) -> UIImage!{ return UIImage.bundled("ic_smiles_backspace")! } public func emojiKeyBoardView(_ emojiKeyBoardView: AGEmojiKeyboardView!, didUseEmoji emoji: String!){ self.textView.text = self.textView.text.appending(emoji) } public func emojiKeyBoardViewDidPressBackSpace(_ emojiKeyBoardView: AGEmojiKeyboardView!){ self.textView.deleteBackward() } */ } class AABarAvatarView : AAAvatarView { // override init(frameSize: Int, type: AAAvatarType) { // super.init(frameSize: frameSize, type: type) // } // // required init(coder aDecoder: NSCoder) { // fatalError("init(coder:) has not been implemented") // } override var alignmentRectInsets : UIEdgeInsets { return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 8) } } class AACallButton: UIImageView { override init(image: UIImage?) { super.init(image: image) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override var alignmentRectInsets : UIEdgeInsets { return UIEdgeInsets(top: 0, left: -2, bottom: 0, right: 0) } }
0e47913d62b594aedea3d3dbdaacb738
39.32519
250
0.585614
false
false
false
false
kickstarter/ios-oss
refs/heads/main
KsApi/models/graphql/adapters/Project+FetchProjectFriendsQueryDataTests.swift
apache-2.0
1
import Apollo @testable import KsApi import XCTest final class Project_FetchProjectFriendsQueryDataTests: XCTestCase { /// `FetchProjectFriendsQueryBySlug` returns identical data. func testFetchProjectFriendsQueryData_Success() { let producer = Project.projectFriendsProducer(from: FetchProjectFriendsQueryTemplate.valid.data) guard let projectFriendsById = MockGraphQLClient.shared.client.data(from: producer) else { XCTFail() return } self.testProjectFriendsProperties_Success(projectFriends: projectFriendsById) } private func testProjectFriendsProperties_Success(projectFriends: [User]) { XCTAssertEqual(projectFriends.count, 2) XCTAssertEqual(projectFriends[0].id, decompose(id: "VXNlci0xNzA1MzA0MDA2")) XCTAssertEqual( projectFriends[0].avatar.large, "https://ksr-qa-ugc.imgix.net/assets/033/090/101/8667751e512228a62d426c77f6eb8a0b_original.jpg?ixlib=rb-4.0.2&blur=false&w=1024&h=1024&fit=crop&v=1618227451&auto=format&frame=1&q=92&s=36de925b6797139e096d7b6219f743d0" ) } }
9a5bb51f7a2c7c051ea585c1ecd42574
39.423077
223
0.778306
false
true
false
false
SPECURE/rmbt-ios-client
refs/heads/main
Sources/AbstractBasicRequestBuilder.swift
apache-2.0
1
/***************************************************************************************************** * Copyright 2016 SPECURE GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************************************/ import Foundation /// class AbstractBasicRequestBuilder { /// class func addBasicRequestValues(_ basicRequest: BasicRequest) { let infoDictionary = Bundle.main.infoDictionary! // ! if RMBTConfig.sharedInstance.RMBT_USE_MAIN_LANGUAGE == true { basicRequest.language = RMBTConfig.sharedInstance.RMBT_MAIN_LANGUAGE } else { basicRequest.language = PREFFERED_LANGUAGE } basicRequest.product = "" // always null on iOS... Log.logger.debug("ADDING PREVIOUS TEST STATUS: \(String(describing: RMBTSettings.sharedSettings.previousTestStatus))") basicRequest.previousTestStatus = RMBTSettings.sharedSettings.previousTestStatus basicRequest.softwareRevision = RMBTBuildInfoString() basicRequest.softwareVersion = infoDictionary["CFBundleShortVersionString"] as? String basicRequest.softwareVersionCode = infoDictionary["CFBundleVersion"] as? Int basicRequest.softwareVersionName = "0.3" // ?? basicRequest.clientVersion = "0.3" // TODO: fix this on server side basicRequest.timezone = TimeZone.current.identifier } }
ed8e38f0958a7160a71997d21d442ee0
41.369565
126
0.643407
false
true
false
false
i-miss-you/Nuke
refs/heads/master
Pod/Classes/Core/ImageRequest.swift
mit
1
// The MIT License (MIT) // // Copyright (c) 2015 Alexander Grebenyuk (github.com/kean). import UIKit public struct ImageRequest { public var URL: NSURL /** Image target size in pixels. */ public var targetSize: CGSize = ImageMaximumSize public var contentMode: ImageContentMode = .AspectFill public var shouldDecompressImage = true /** Filters to be applied to image. Use ImageProcessorComposition to compose multiple filters. */ public var processor: ImageProcessing? public var userInfo: Any? public init(URL: NSURL, targetSize: CGSize, contentMode: ImageContentMode) { self.URL = URL self.targetSize = targetSize self.contentMode = contentMode } public init(URL: NSURL) { self.URL = URL } }
b561083bb2e501583faaa21dc80293d7
25.833333
98
0.665839
false
false
false
false
Za1006/TIY-Assignments
refs/heads/master
The Grail Diary/The Grail Diary/FamousSitesTableViewController.swift
cc0-1.0
1
// // FamousSitesTableViewController.swift // The Grail Diary // // Created by Elizabeth Yeh on 10/19/15. // Copyright © 2015 The Iron Yard. All rights reserved. // import UIKit class FamousSitesTableViewController: UITableViewController { var place = Array<FamousPlaces>() var name: String = "" var location: String = "" var history: String = "" var attribute: String = "" override func viewDidLoad() { super.viewDidLoad() title = "Famouse Places" loadSITEList() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } 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 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return place.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("SiteNameCell", forIndexPath: indexPath) as! SiteNameCell let placeSite = place[indexPath.row] cell.nameOfSite.text = placeSite.siteName cell.locationOfSite.text = "location: " + placeSite.siteLocation cell.historyOfSite.text = "history: " + placeSite.siteHistory cell.attributeOfSite.text = "attribute: " + placeSite.siteAttribute return cell } func loadSITEList() { do { let filePath = NSBundle.mainBundle().pathForResource("SITE", ofType: "json") let dataFromFile = NSData(contentsOfFile: filePath!) let placeData: NSArray! = try NSJSONSerialization.JSONObjectWithData(dataFromFile!, options: []) as! NSArray for placeDictionay in placeData { let placeSite = FamousPlaces(dictionary: placeDictionay as! NSDictionary) place.append(placeSite) } // catch let error as NSError // { // print(error) // } /* // 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. } */ } } }
ad1d02eb7720a3df9468258c09b5133f
32.733333
157
0.645147
false
false
false
false
uwunmn/JSBridgeX
refs/heads/master
iOS/lib/WKWebViewEx.swift
mit
1
// // WKWebViewEx.swift // JSBridgeX // // Created by Xiaohui on 2017/1/20. // Copyright © 2017年 TLX. All rights reserved. // import WebKit open class WKWebViewEx: WKWebView, WebViewProtocol, WKNavigationDelegate { fileprivate let kEstimatedProgress = "estimatedProgress" //替代WKNavigationDelegate,用于获取页面加载的生命周期 open weak var webViewNavigationDelegate: WebViewNavigationDelegate? fileprivate lazy var bridge: JSBridgeX = { return JSBridgeX(webView: self) { (eventName, data, callback) in print("undefined eventName: \(eventName)") callback?(JSBridgeX.CODE_NOT_FOUND, nil) } }() public override init(frame: CGRect, configuration: WKWebViewConfiguration) { super.init(frame: frame, configuration: configuration) self.navigationDelegate = self self.addObserver(self, forKeyPath: self.kEstimatedProgress, options: .new, context: nil) } required public init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { self.navigationDelegate = nil self.removeObserver(self, forKeyPath: self.kEstimatedProgress, context: nil) } open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if keyPath == self.kEstimatedProgress { self.webViewNavigationDelegate?.webViewLoadingWithProgress(webView: self, progress: self.estimatedProgress) } } open func setDeaultEventHandler(handler: JSBridgeX.DefaultEventHandler?) { self.bridge.defaultEventHandler = handler } //MARK: - WKNavigationDelegate public func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { let request = navigationAction.request if self.bridge.interceptRequest(request: request) { decisionHandler(.cancel) return } if let result = self.webViewNavigationDelegate?.webView(webView: self, shouldStartLoadWithRequest: request, navigationType: WebViewNavigationType.from(navigationType: navigationAction.navigationType)) { decisionHandler(result ? .allow : .cancel) return } decisionHandler(.allow) } // public func webView(webView: WKWebView, decidePolicyForNavigationResponse navigationResponse: WKNavigationResponse, decisionHandler: (WKNavigationResponsePolicy) -> Void) { // decisionHandler(.Allow) // } public func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) { self.webViewNavigationDelegate?.webViewDidStartLoad(webView: self) } // // public func webView(webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) { // // } public func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { self.webViewNavigationDelegate?.webViewLoadingWithProgress(webView: self, progress: 1) self.webViewNavigationDelegate?.webView(webView: self, didFailLoadWithError: error) } public func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) { self.bridge.injectBridgeToJS() } public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { self.webViewNavigationDelegate?.webViewLoadingWithProgress(webView: self, progress: 1) self.webViewNavigationDelegate?.webViewDidFinishLoad(webView: self) } public func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { self.webViewNavigationDelegate?.webViewLoadingWithProgress(webView: self, progress: 1) self.webViewNavigationDelegate?.webView(webView: self, didFailLoadWithError: error) } //MARK: - WebViewProtocol open var canBack: Bool { return self.canGoBack } open var canForward: Bool { return self.canGoForward } open func back() { self.goBack() } open func forward() { self.goForward() } open func load(url: URL) { self.load(URLRequest(url: url)) } open func executeJavaScript(js: String, completionHandler: ((Any?, Error?) -> Void)?) { self.evaluateJavaScript(js, completionHandler: completionHandler) } open func send(eventName: String, data: Any?, callback: JSBridgeX.EventCallback?) { self.bridge.send(eventName: eventName, data: data, callback: callback) } open func registerEvent(eventName: String, handler: @escaping JSBridgeX.EventHandler) { self.bridge.registerEvent(eventName: eventName, handler: handler) } open func unregisterEvent(eventName: String) { self.bridge.unregisterEvent(eventName: eventName) } }
9c7f227272568c72a4f20bbb630082a0
36.88806
210
0.685247
false
false
false
false
editfmah/AeonAPI
refs/heads/master
Sources/Mutex.swift
mit
1
// // Mutex.swift // scale // // Created by Adrian Herridge on 06/02/2017. // // import Foundation import Dispatch import SWSQLite class Mutex { private var thread: Thread? = nil; private var lock: DispatchQueue init() { lock = DispatchQueue(label: uuid()) } func mutex(_ closure: ()->()) { if thread != Thread.current { lock.sync { thread = Thread.current closure() thread = nil } } else { closure() } } }
6d89d3514de1d14756d552870e532619
15.823529
45
0.480769
false
false
false
false
onmyway133/Github.swift
refs/heads/master
Carthage/Checkouts/Tailor/Sources/Shared/Protocols/PathAccessible.swift
mit
1
import Sugar public protocol PathAccessible { /** - Parameter name: The array of path, can be index or key - Returns: A child dictionary for that path, otherwise it returns nil */ func path(path: [SubscriptKind]) -> JSONDictionary? /** - Parameter name: The key path, separated by dot - Returns: A child dictionary for that path, otherwise it returns nil */ func path(keyPath: String) -> JSONDictionary? } public extension PathAccessible { func path(path: [SubscriptKind]) -> JSONDictionary? { var castedPath = path.dropFirst() castedPath.append(.Key("")) let pairs = zip(path, Array(castedPath)) var result: Any = self for (kind, castedKind) in pairs { switch (kind, castedKind) { case (let .Key(name), .Key): result = (result as? JSONDictionary)?.dictionary(name) case (let .Key(name), .Index): result = (result as? JSONDictionary)?.array(name) case (let .Index(index), .Key): result = (result as? JSONArray)?.dictionary(index) case (let .Index(index), .Index): result = (result as? JSONArray)?.array(index) } } return result as? JSONDictionary } func path(keyPath: String) -> JSONDictionary? { let kinds: [SubscriptKind] = keyPath.componentsSeparatedByString(".").map { if let index = Int($0) { return .Index(index) } else { return .Key($0) } } return path(kinds) } } extension Dictionary: PathAccessible {} extension Array: PathAccessible {}
194a607a8827f284a3e5897a2f66d4f3
26.357143
79
0.63577
false
false
false
false
morbrian/udacity-nano-virtualtourist
refs/heads/master
VirtualTourist/WebClient.swift
mit
1
// // AuthenticationService.swift // OnTheMap // // Created by Brian Moriarty on 4/19/15. // Copyright (c) 2015 Brian Moriarty. All rights reserved. // import Foundation // MARK: - Class WebClient // WebClient // Base Class for general interactions with any Web Service API that produces JSON data. public class WebClient { // optional data maniupation function // if set will modify the data before handing it off to the parser. // Common Use Case: some web services include extraneous content // before or after the desired JSON content in response data. public var prepareData: ((NSData) -> NSData?)? // encodeParameters // convert dictionary to parameterized String appropriate for use in an HTTP URL public static func encodeParameters(params: [String: AnyObject]) -> String { var queryItems = map(params) { NSURLQueryItem(name:$0, value:"\($1)")} var components = NSURLComponents() components.queryItems = queryItems return components.percentEncodedQuery ?? "" } // createHttpRequestUsingMethod // Creates fuly configured NSURLRequest for making HTTP POST requests. // urlString: properly formatted URL string // withBody: body of the post request, not necessarily JSON or any particular format. // includeHeaders: field-name / value pairs for request headers. public func createHttpRequestUsingMethod(method: String, var forUrlString urlString: String, withBody body: NSData? = nil, includeHeaders requestHeaders: [String:String]? = nil, includeParameters requestParameters: [String:AnyObject]? = nil) -> NSURLRequest? { if (method == WebClient.HttpGet && body != nil) { Logger.error("Programmer Error: Http GET request created with non nil body.") } if ((method == WebClient.HttpPost || method == WebClient.HttpPut) && body == nil) { Logger.error("Programmer Error: Http \(method) request created but no content body specified") } if let requestParameters = requestParameters { urlString = "\(urlString)?\(WebClient.encodeParameters(requestParameters))" } if let requestUrl = NSURL(string: urlString) { var request = NSMutableURLRequest(URL: requestUrl) request.HTTPMethod = method if let requestHeaders = requestHeaders { request = addRequestHeaders(requestHeaders, toRequest: request) } if let body = body { request.HTTPBody = body } return request } else { return nil } } // executeRequest // Execute the request in a background thread, and call completionHandler when done. // Performs the work of checking for general errors and then // turning raw data into JSON data to feed to completionHandler. public func executeRequest(request: NSURLRequest, completionHandler: (jsonData: AnyObject?, error: NSError?) -> Void) { let session = NSURLSession.sharedSession() let task = session.dataTaskWithRequest(request) { data, response, error in // this is a general communication error if error != nil { Logger.debug(error.description) completionHandler(jsonData: nil, error: error) return } let (jsonData: AnyObject?, parsingError: NSError?) = self.parseJsonFromData(data) if let parsingError = parsingError { Logger.debug(parsingError.description) Logger.debug("\(data)") completionHandler(jsonData: nil, error: parsingError) return } completionHandler(jsonData: jsonData, error: nil) } task.resume() } // quick check to see if URL is valid and responsive public func pingUrl(urlString: String, completionHandler: (reply: Bool, error: NSError?) -> Void) { if let request = createHttpRequestUsingMethod(WebClient.HttpHead, forUrlString: urlString) { let session = NSURLSession.sharedSession() let task = session.dataTaskWithRequest(request) { data, response, error in if let error = error { Logger.debug(error.description) } completionHandler(reply: error == nil, error: error) } task.resume() } else { completionHandler(reply: false, error: WebClient.errorForCode(.UnableToCreateRequest)) } } // MARK: Private Helpers // Produces usable JSON object from the raw data. private func parseJsonFromData(data: NSData) -> (jsonData: AnyObject?, error: NSError?) { var mutableData = data var parsingError: NSError? = nil if let prepareData = prepareData, modifiedData = prepareData(data) { mutableData = modifiedData } let jsonData: AnyObject? = NSJSONSerialization.JSONObjectWithData(mutableData, options: NSJSONReadingOptions.AllowFragments, error: &parsingError) return (jsonData, parsingError) } // helper function adds request headers to request private func addRequestHeaders(requestHeaders: [String:String], toRequest request: NSMutableURLRequest) -> NSMutableURLRequest { var request = request for (field, value) in requestHeaders { request.addValue(value, forHTTPHeaderField: field) } return request } } // MARK: - Constants extension WebClient { static let JsonContentType = "application/json" static let HttpHeaderAccept = "Accept" static let HttpHeaderContentType = "Content-Type" static let HttpScheme = "http" static let HttpsScheme = "https" static let HttpHead = "HEAD" static let HttpPost = "POST" static let HttpGet = "GET" static let HttpPut = "PUT" static let HttpDelete = "DELETE" } // MARK: - Error Handling extension WebClient { private static let ErrorDomain = "WebClient" enum ErrorCode: Int, Printable { case UnableToCreateRequest var description: String { switch self { case UnableToCreateRequest: return "Could Not Create Request" default: return "Unknown Error" } } } // createErrorWithCode // helper function to simplify creation of error object static func errorForCode(code: ErrorCode) -> NSError { let userInfo = [NSLocalizedDescriptionKey : code.description] return NSError(domain: WebClient.ErrorDomain, code: code.rawValue, userInfo: userInfo) } static func errorWithMessage(message: String, code: Int) -> NSError { let userInfo = [NSLocalizedDescriptionKey : message] return NSError(domain: WebClient.ErrorDomain, code: code, userInfo: userInfo) } }
8f499eeb90f1a50da414b5a04d67e06f
38.346154
154
0.62617
false
false
false
false
OscarSwanros/swift
refs/heads/master
test/refactoring/SyntacticRename/textual.swift
apache-2.0
5
/* /*foo:unknown*/foo() is not /*foo:unknown*/foo(first:) */ /// This describes /*foo:unknown*/foo and /*foo:unknown*/foo func /*foo:def*/foo() { let /*foo:def*/foo = "Here is /*foo:unknown*/foo" // /*foo:unknown*/foo's return #selector(Struct . /*foo:unknown*/foo(_:aboveSubview:)) #selector(/*foo:unknown*/foo(_:)) #selector(#selector(/*foo:unknown*/foo)) #if true /*foo*/foo = 2 /*foo*/foo() /*foo:call*/foo() /*foo:unknown*/foo = 3 /*foo:unknown*/foo() #if false /*foo:unknown*/foo += 2 /*foo:unknown*/foo() #endif #else /*foo:unknown*/foo = 4 #endif return 1 } #if false class /*MyClass:unknown*/MyClass {} _ = /*MyClass:unknown*/Mismatch() _ = /*MyClass:unknown*/MyClass() #else class /*MyClass:unknown*/MyClass {} _ = /*MyClass:unknown*/Mismatch() _ = /*MyClass:unknown*/MyClass() #endif // RUN: rm -rf %t.result && mkdir -p %t.result // RUN: %refactor -syntactic-rename -source-filename %s -pos="foo" -is-function-like -old-name "foo" -new-name "bar" >> %t.result/textual_foo.swift // RUN: diff -u %S/Outputs/textual/foo.swift.expected %t.result/textual_foo.swift // RUN: %refactor -syntactic-rename -source-filename %s -pos="MyClass" -is-non-protocol-type -old-name "MyClass" -new-name "YourClass" >> %t.result/textual_MyClass.swift // RUN: diff -u %S/Outputs/textual/MyClass.swift.expected %t.result/textual_MyClass.swift // RUN: rm -rf %t.ranges && mkdir -p %t.ranges // RUN: %refactor -find-rename-ranges -source-filename %s -pos="foo" -is-function-like -old-name "foo" >> %t.ranges/textual_foo.swift // RUN: diff -u %S/FindRangeOutputs/textual/foo.swift.expected %t.ranges/textual_foo.swift
9625cd8541cc95ec963f35f823f4bca6
36.73913
169
0.625
false
false
false
false
insidegui/AppleEvents
refs/heads/master
Dependencies/swift-protobuf/Sources/SwiftProtobuf/AnyMessageStorage.swift
bsd-2-clause
1
// Sources/SwiftProtobuf/AnyMessageStorage.swift - Custom stroage for Any WKT // // Copyright (c) 2014 - 2017 Apple Inc. and the project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See LICENSE.txt for license information: // https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt // // ----------------------------------------------------------------------------- /// /// Hand written storage class for Google_Protobuf_Any to support on demand /// transforms between the formats. /// // ----------------------------------------------------------------------------- import Foundation private let i_2166136261 = Int(bitPattern: 2166136261) private let i_16777619 = Int(16777619) fileprivate func serializeAnyJSON(for message: Message, typeURL: String) throws -> String { var visitor = try JSONEncodingVisitor(message: message) visitor.startObject() visitor.encodeField(name: "@type", stringValue: typeURL) if let m = message as? _CustomJSONCodable { let value = try m.encodedJSONString() visitor.encodeField(name: "value", jsonText: value) } else { try message.traverse(visitor: &visitor) } visitor.endObject() return visitor.stringResult } fileprivate func emitVerboseTextForm(visitor: inout TextFormatEncodingVisitor, message: Message, typeURL: String) { let url: String if typeURL.isEmpty { url = buildTypeURL(forMessage: message, typePrefix: defaultAnyTypeURLPrefix) } else { url = typeURL } visitor.visitAnyVerbose(value: message, typeURL: url) } fileprivate func asJSONObject(body: Data) -> Data { let asciiOpenCurlyBracket = UInt8(ascii: "{") let asciiCloseCurlyBracket = UInt8(ascii: "}") var result = Data(bytes: [asciiOpenCurlyBracket]) result.append(body) result.append(asciiCloseCurlyBracket) return result } fileprivate func unpack(contentJSON: Data, options: JSONDecodingOptions, as messageType: Message.Type) throws -> Message { guard messageType is _CustomJSONCodable.Type else { let contentJSONAsObject = asJSONObject(body: contentJSON) return try messageType.init(jsonUTF8Data: contentJSONAsObject, options: options) } var value = String() try contentJSON.withUnsafeBytes { (bytes:UnsafePointer<UInt8>) in let buffer = UnsafeBufferPointer(start: bytes, count: contentJSON.count) var scanner = JSONScanner(source: buffer, messageDepthLimit: options.messageDepthLimit, ignoreUnknownFields: options.ignoreUnknownFields) let key = try scanner.nextQuotedString() if key != "value" { // The only thing within a WKT should be "value". throw AnyUnpackError.malformedWellKnownTypeJSON } try scanner.skipRequiredColon() // Can't fail value = try scanner.skip() if !scanner.complete { // If that wasn't the end, then there was another key, // and WKTs should only have the one. throw AnyUnpackError.malformedWellKnownTypeJSON } } return try messageType.init(jsonString: value, options: options) } internal class AnyMessageStorage { // The two properties generated Google_Protobuf_Any will reference. var _typeURL = String() var _value: Data { // Remapped to the internal `state`. get { switch state { case .binary(let value): return value case .message(let message): do { return try message.serializedData(partial: true) } catch { return Internal.emptyData } case .contentJSON(let contentJSON, let options): guard let messageType = Google_Protobuf_Any.messageType(forTypeURL: _typeURL) else { return Internal.emptyData } do { let m = try unpack(contentJSON: contentJSON, options: options, as: messageType) return try m.serializedData(partial: true) } catch { return Internal.emptyData } } } set { state = .binary(newValue) } } enum InternalState { // a serialized binary // Note: Unlike contentJSON below, binary does not bother to capture the // decoding options. This is because the actual binary format is the binary // blob, i.e. - when decoding from binary, the spec doesn't include decoding // the binary blob, it is pass through. Instead there is a public api for // unpacking that takes new options when a developer decides to decode it. case binary(Data) // a message case message(Message) // parsed JSON with the @type removed and the decoding options. case contentJSON(Data, JSONDecodingOptions) } var state: InternalState = .binary(Internal.emptyData) static let defaultInstance = AnyMessageStorage() private init() {} init(copying source: AnyMessageStorage) { _typeURL = source._typeURL state = source.state } func isA<M: Message>(_ type: M.Type) -> Bool { if _typeURL.isEmpty { return false } let encodedType = typeName(fromURL: _typeURL) return encodedType == M.protoMessageName } // This is only ever called with the expactation that target will be fully // replaced during the unpacking and never as a merge. func unpackTo<M: Message>( target: inout M, extensions: ExtensionMap?, options: BinaryDecodingOptions ) throws { guard isA(M.self) else { throw AnyUnpackError.typeMismatch } switch state { case .binary(let data): target = try M(serializedData: data, extensions: extensions, partial: true, options: options) case .message(let msg): if let message = msg as? M { // Already right type, copy it over. target = message } else { // Different type, serialize and parse. let data = try msg.serializedData(partial: true) target = try M(serializedData: data, extensions: extensions, partial: true) } case .contentJSON(let contentJSON, let options): target = try unpack(contentJSON: contentJSON, options: options, as: M.self) as! M } } // Called before the message is traversed to do any error preflights. // Since traverse() will use _value, this is our chance to throw // when _value can't. func preTraverse() throws { switch state { case .binary: // Nothing to be checked. break case .message: // When set from a developer provided message, partial support // is done. Any message that comes in from another format isn't // checked, and transcoding the isInitialized requirement is // never inserted. break case .contentJSON: // contentJSON requires a good URL and our ability to look up // the message type to transcode. if Google_Protobuf_Any.messageType(forTypeURL: _typeURL) == nil { // Isn't registered, we can't transform it for binary. throw BinaryEncodingError.anyTranscodeFailure } } } } /// Custom handling for Text format. extension AnyMessageStorage { func decodeTextFormat(typeURL url: String, decoder: inout TextFormatDecoder) throws { // Decoding the verbose form requires knowing the type. _typeURL = url guard let messageType = Google_Protobuf_Any.messageType(forTypeURL: url) else { // The type wasn't registered, can't parse it. throw TextFormatDecodingError.malformedText } let terminator = try decoder.scanner.skipObjectStart() var subDecoder = try TextFormatDecoder(messageType: messageType, scanner: decoder.scanner, terminator: terminator) if messageType == Google_Protobuf_Any.self { var any = Google_Protobuf_Any() try any.decodeTextFormat(decoder: &subDecoder) state = .message(any) } else { var m = messageType.init() try m.decodeMessage(decoder: &subDecoder) state = .message(m) } decoder.scanner = subDecoder.scanner if try decoder.nextFieldNumber() != nil { // Verbose any can never have additional keys. throw TextFormatDecodingError.malformedText } } // Specialized traverse for writing out a Text form of the Any. // This prefers the more-legible "verbose" format if it can // use it, otherwise will fall back to simpler forms. internal func textTraverse(visitor: inout TextFormatEncodingVisitor) { switch state { case .binary(let valueData): if let messageType = Google_Protobuf_Any.messageType(forTypeURL: _typeURL) { // If we can decode it, we can write the readable verbose form: do { let m = try messageType.init(serializedData: valueData, partial: true) emitVerboseTextForm(visitor: &visitor, message: m, typeURL: _typeURL) return } catch { // Fall through to just print the type and raw binary data } } if !_typeURL.isEmpty { try! visitor.visitSingularStringField(value: _typeURL, fieldNumber: 1) } if !valueData.isEmpty { try! visitor.visitSingularBytesField(value: valueData, fieldNumber: 2) } case .message(let msg): emitVerboseTextForm(visitor: &visitor, message: msg, typeURL: _typeURL) case .contentJSON(let contentJSON, let options): // If we can decode it, we can write the readable verbose form: if let messageType = Google_Protobuf_Any.messageType(forTypeURL: _typeURL) { do { let m = try unpack(contentJSON: contentJSON, options: options, as: messageType) emitVerboseTextForm(visitor: &visitor, message: m, typeURL: _typeURL) return } catch { // Fall through to just print the raw JSON data } } if !_typeURL.isEmpty { try! visitor.visitSingularStringField(value: _typeURL, fieldNumber: 1) } // Build a readable form of the JSON: let contentJSONAsObject = asJSONObject(body: contentJSON) visitor.visitAnyJSONDataField(value: contentJSONAsObject) } } } /// The obvious goal for Hashable/Equatable conformance would be for /// hash and equality to behave as if we always decoded the inner /// object and hashed or compared that. Unfortunately, Any typically /// stores serialized contents and we don't always have the ability to /// deserialize it. Since none of our supported serializations are /// fully deterministic, we can't even ensure that equality will /// behave this way when the Any contents are in the same /// serialization. /// /// As a result, we can only really perform a "best effort" equality /// test. Of course, regardless of the above, we must guarantee that /// hashValue is compatible with equality. extension AnyMessageStorage { var hashValue: Int { var hash: Int = i_2166136261 if !_typeURL.isEmpty { hash = (hash &* i_16777619) ^ _typeURL.hashValue } // Can't use _valueData for a few reasons: // 1. Since decode is done on demand, two objects could be equal // but created differently (one from JSON, one for Message, etc.), // and the hashes have to be equal even if we don't have data yet. // 2. map<> serialization order is undefined. At the time of writing // the Swift, Objective-C, and Go runtimes all tend to have random // orders, so the messages could be identical, but in binary form // they could differ. return hash } func isEqualTo(other: AnyMessageStorage) -> Bool { if (_typeURL != other._typeURL) { return false } // Since the library does lazy Any decode, equality is a very hard problem. // It things exactly match, that's pretty easy, otherwise, one ends up having // to error on saying they aren't equal. // // The best option would be to have Message forms and compare those, as that // removes issues like map<> serialization order, some other protocol buffer // implementation details/bugs around serialized form order, etc.; but that // would also greatly slow down equality tests. // // Do our best to compare what is present have... // If both have messages, check if they are the same. if case .message(let myMsg) = state, case .message(let otherMsg) = other.state, type(of: myMsg) == type(of: otherMsg) { // Since the messages are known to be same type, we can claim both equal and // not equal based on the equality comparison. return myMsg.isEqualTo(message: otherMsg) } // If both have serialized data, and they exactly match; the messages are equal. // Because there could be map in the message, the fact that the data isn't the // same doesn't always mean the messages aren't equal. Likewise, the binary could // have been created by a library that doesn't order the fields, or the binary was // created using the appending ability in of the binary format. if case .binary(let myValue) = state, case .binary(let otherValue) = other.state, myValue == otherValue { return true } // If both have contentJSON, and they exactly match; the messages are equal. // Because there could be map in the message (or the JSON could just be in a different // order), the fact that the JSON isn't the same doesn't always mean the messages // aren't equal. if case .contentJSON(let myJSON, _) = state, case .contentJSON(let otherJSON, _) = other.state, myJSON == otherJSON { return true } // Out of options. To do more compares, the states conversions would have to be // done to do comparisions; and since equality can be used somewhat removed from // a developer (if they put protos in a Set, use them as keys to a Dictionary, etc), // the conversion cost might be to high for those uses. Give up and say they aren't equal. return false } } // _CustomJSONCodable support for Google_Protobuf_Any extension AnyMessageStorage { // Override the traversal-based JSON encoding // This builds an Any JSON representation from one of: // * The message we were initialized with, // * The JSON fields we last deserialized, or // * The protobuf field we were deserialized from. // The last case requires locating the type, deserializing // into an object, then reserializing back to JSON. func encodedJSONString() throws -> String { switch state { case .binary(let valueData): // Transcode by decoding the binary data to a message object // and then recode back into JSON. guard let messageType = Google_Protobuf_Any.messageType(forTypeURL: _typeURL) else { // If we don't have the type available, we can't decode the // binary value, so we're stuck. (The Google spec does not // provide a way to just package the binary value for someone // else to decode later.) throw JSONEncodingError.anyTranscodeFailure } let m = try messageType.init(serializedData: valueData, partial: true) return try serializeAnyJSON(for: m, typeURL: _typeURL) case .message(let msg): // We should have been initialized with a typeURL, but // ensure it wasn't cleared. let url = !_typeURL.isEmpty ? _typeURL : buildTypeURL(forMessage: msg, typePrefix: defaultAnyTypeURLPrefix) return try serializeAnyJSON(for: msg, typeURL: url) case .contentJSON(let contentJSON, _): var jsonEncoder = JSONEncoder() jsonEncoder.startObject() jsonEncoder.startField(name: "@type") jsonEncoder.putStringValue(value: _typeURL) if !contentJSON.isEmpty { jsonEncoder.append(staticText: ",") jsonEncoder.append(utf8Data: contentJSON) } jsonEncoder.endObject() return jsonEncoder.stringResult } } // TODO: If the type is well-known or has already been registered, // we should consider decoding eagerly. Eager decoding would // catch certain errors earlier (good) but would probably be // a performance hit if the Any contents were never accessed (bad). // Of course, we can't always decode eagerly (we don't always have the // message type available), so the deferred logic here is still needed. func decodeJSON(from decoder: inout JSONDecoder) throws { try decoder.scanner.skipRequiredObjectStart() // Reset state _typeURL = String() state = .binary(Internal.emptyData) if decoder.scanner.skipOptionalObjectEnd() { return } var jsonEncoder = JSONEncoder() while true { let key = try decoder.scanner.nextQuotedString() try decoder.scanner.skipRequiredColon() if key == "@type" { _typeURL = try decoder.scanner.nextQuotedString() } else { jsonEncoder.startField(name: key) let keyValueJSON = try decoder.scanner.skip() jsonEncoder.append(text: keyValueJSON) } if decoder.scanner.skipOptionalObjectEnd() { // Capture the options, but set the messageDepthLimit to be what // was left right now, as that is the limit when the JSON is finally // parsed. var updatedOptions = decoder.options updatedOptions.messageDepthLimit = decoder.scanner.recursionBudget state = .contentJSON(jsonEncoder.dataResult, updatedOptions) return } try decoder.scanner.skipRequiredComma() } } }
3614f75f6ed6f2ff2c167b1de913962d
38.047085
123
0.668964
false
false
false
false
iosClassForBeginner/VacationPlanner_en
refs/heads/master
Vacation Planner Complete/Vacation Planner/ViewController.swift
mit
1
// // ViewController.swift // Vacation Planner // // Created by Sam on 2017-03-13. // Copyright © 2017 Sam. All rights reserved. // import UIKit class ViewController: UIViewController { // MARK: IB outlets @IBOutlet weak var usernameButton: UITextField! @IBOutlet weak var passwordButton: UITextField! @IBOutlet weak var loginButton: UIButton! // MARK: further UI let spinner = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.white) // MARK: IB actions @IBAction func login(_ sender: Any) { spinner.isHidden = !spinner.isHidden } // MARK: view controller methods // Gets called once during loading of the view override func viewDidLoad() { super.viewDidLoad() //set up the UI loginButton.layer.cornerRadius = 8.0 loginButton.layer.masksToBounds = true spinner.frame = CGRect(x: -20.0, y: 6.0, width: 20.0, height: 20.0) spinner.startAnimating() spinner.center = CGPoint(x: spinner.bounds.midX + 5.0, y: loginButton.bounds.midY) loginButton.addSubview(spinner) } // Gets called every time before view appears override func viewWillAppear(_ animated: Bool) { usernameButton.center.x -= view.bounds.width passwordButton.center.x -= view.bounds.width loginButton.center.x -= view.bounds.width } // Gets called right after the view apears override func viewDidAppear(_ animated: Bool) { spinner.isHidden = true UIView.animate(withDuration: 0.5, animations: { self.usernameButton.center.x += self.view.bounds.width }) UIView.animate(withDuration: 0.5, delay: 0.3, options: [], animations: { self.passwordButton.center.x += self.view.bounds.width }, completion: nil) UIView.animate(withDuration: 0.5, delay: 0.4, options: [], animations: { self.loginButton.center.x += self.view.bounds.width }, completion: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
8a2a5d62b9bae2c94d0f5593ca21727b
26.255814
101
0.606655
false
false
false
false
noahemmet/FingerPaint
refs/heads/master
FingerPaint/Shape.swift
apache-2.0
1
// // Shapes.swift // FingerPaint // // Created by Noah Emmet on 4/21/16. // Copyright © 2016 Sticks. All rights reserved. // import Foundation public enum Border { case None case SingleLine } public enum Fill { case Empty case Solid case Checkered case Stripes(rows: Int, columns: Int, offset: Int) } public struct Shape { public let points: [CGPoint] public let border: Border public let fill: Fill public init(points: [CGPoint], border: Border = .SingleLine, fill: Fill = .Empty) { self.points = points self.border = border self.fill = fill } }
e4b623de392aa332478406e22fdf0bcc
16.90625
84
0.69459
false
false
false
false
AckeeCZ/ACKategories
refs/heads/master
ACKategories-iOS/Base/ViewController.swift
mit
1
// // ViewController.swift // ACKategories // // Created by Jan Misar on 02/04/2019. // Copyright © 2019 Ackee, s.r.o. All rights reserved. // import UIKit import os.log extension Base { /// Turn on/off logging of init/deinit of all VCs /// ⚠️ Has no effect when Base.memoryLoggingEnabled is true public static var viewControllerMemoryLoggingEnabled: Bool = true /// Base class for all view controllers open class ViewController: UIViewController { /// Navigation bar is shown/hidden in viewWillAppear according to this flag open var hasNavigationBar: Bool = true public init() { super.init(nibName: nil, bundle: nil) if Base.memoryLoggingEnabled && Base.viewControllerMemoryLoggingEnabled { if #available(iOS 10.0, *) { os_log("📱 👶 %@", log: Logger.lifecycleLog(), type: .info, self) } else { NSLog("📱 👶 \(self)") } } } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private var firstWillAppearOccurred = false override open func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if !firstWillAppearOccurred { viewWillFirstAppear(animated) firstWillAppearOccurred = true } navigationController?.setNavigationBarHidden(!hasNavigationBar, animated: animated) } private var firstDidAppearOccurred = false override open func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if !firstDidAppearOccurred { viewDidFirstAppear(animated) firstDidAppearOccurred = true } } /// Method is called when `viewWillAppear(_:)` is called for the first time open func viewWillFirstAppear(_ animated: Bool) { // to be overridden } /// Method is called when `viewDidAppear(_:)` is called for the first time open func viewDidFirstAppear(_ animated: Bool) { // to be overridden } deinit { if Base.memoryLoggingEnabled && Base.viewControllerMemoryLoggingEnabled { if #available(iOS 10.0, *) { os_log("📱 ⚰️ %@", log: Logger.lifecycleLog(), type: .info, self) } else { NSLog("📱 ⚰️ \(self)") } } } } }
f381daf973563574695744eef7490b5d
29.809524
95
0.568006
false
false
false
false
corchwll/amos-ss15-proj5_ios
refs/heads/master
MobileTimeAccounting/UserInterface/Dashboard/DashboardTableViewController.swift
agpl-3.0
1
/* Mobile Time Accounting Copyright (C) 2015 This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ import UIKit import MessageUI class DashboardTableViewController: UITableViewController { @IBOutlet weak var overtimeLabel: UILabel! @IBOutlet weak var vacationDaysLabel: UILabel! @IBOutlet weak var vacationExpiringWarningLabel: UILabel! /* iOS life-cycle function, called when view did appear. Sets up labels. @methodtype Hook @pre - @post Labels are set up */ override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) setUpOvertimeLabel() setUpVacationDaysLabel() } /* Sets up overtime label. @methodtype Command @pre OvertimeHelper is initialized @post Overtime label is set up */ func setUpOvertimeLabel() { let currentDate = NSDate() overtimeLabel.text = overtimeHelper.getCurrentOvertime(currentDate).description } /* Sets up vacation days label, displaying vacation days left and total vacation days. @methodtype Command @pre VacationTimeHelper is initialized @post Vacation days label is set up */ func setUpVacationDaysLabel() { let currentDate = NSDate() let vacationDaysLeft = vacationTimeHelper.getCurrentVacationDaysLeft(currentDate).description let totalVacationDays = profileDAO.getProfile()!.totalVacationTime if vacationTimeHelper.isExpiring(currentDate) { vacationExpiringWarningLabel.hidden = false vacationDaysLabel.textColor = UIColor.redColor() } else { vacationExpiringWarningLabel.hidden = true vacationDaysLabel.textColor = UIColor.blackColor() } vacationDaysLabel.text = "\(vacationDaysLeft) / \(totalVacationDays)" } }
857bf7dc8a02e47f75b43853e5f2ddb1
29.588235
101
0.666923
false
false
false
false
miracl/amcl
refs/heads/master
version22/swift/BenchtestEC.swift
apache-2.0
3
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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. */ // // TestECDH.swift // // Created by Michael Scott on 02/07/2015. // Copyright (c) 2015 Michael Scott. All rights reserved. // import Foundation //import amcl // comment out for Xcode public func BenchtestEC() { let pub=rsa_public_key(Int(ROM.FFLEN)) let priv=rsa_private_key(Int(ROM.HFLEN)) var C=[UInt8](repeating: 0,count: RSA.RFS) var P=[UInt8](repeating: 0,count: RSA.RFS) var M=[UInt8](repeating: 0,count: RSA.RFS) let MIN_TIME=10.0 let MIN_ITERS=10 var fail=false; var RAW=[UInt8](repeating: 0,count: 100) let rng=RAND() rng.clean(); for i in 0 ..< 100 {RAW[i]=UInt8(i&0xff)} rng.seed(100,RAW) if ROM.CURVETYPE==ROM.WEIERSTRASS { print("Weierstrass parameterisation") } if ROM.CURVETYPE==ROM.EDWARDS { print("Edwards parameterisation") } if ROM.CURVETYPE==ROM.MONTGOMERY { print("Montgomery representation") } if ROM.MODTYPE==ROM.PSEUDO_MERSENNE { print("Pseudo-Mersenne Modulus") } if ROM.MODTYPE==ROM.MONTGOMERY_FRIENDLY { print("Montgomery Friendly Modulus") } if ROM.MODTYPE==ROM.GENERALISED_MERSENNE { print("Generalised-Mersenne Modulus") } if ROM.MODTYPE==ROM.NOT_SPECIAL { print("Not special Modulus") } print("Modulus size \(ROM.MODBITS) bits") print("\(ROM.CHUNK) bit build") let gx=BIG(ROM.CURVE_Gx); var s:BIG var G:ECP if ROM.CURVETYPE != ROM.MONTGOMERY { let gy=BIG(ROM.CURVE_Gy) G=ECP(gx,gy) } else {G=ECP(gx)} let r=BIG(ROM.CURVE_Order) s=BIG.randomnum(r,rng) var W=G.mul(r) if !W.is_infinity() { print("FAILURE - rG!=O") fail=true; } var start=Date() var iterations=0 var elapsed=0.0 while elapsed<MIN_TIME || iterations<MIN_ITERS { W=G.mul(s) iterations+=1 elapsed = -start.timeIntervalSinceNow } elapsed=1000.0*elapsed/Double(iterations) print(String(format: "EC mul - %d iterations",iterations),terminator: ""); print(String(format: " %.2f ms per iteration",elapsed)) print("Generating \(ROM.FFLEN*ROM.BIGBITS) RSA public/private key pair") start=Date() iterations=0 elapsed=0.0 while elapsed<MIN_TIME || iterations<MIN_ITERS { RSA.KEY_PAIR(rng,65537,priv,pub) iterations+=1 elapsed = -start.timeIntervalSinceNow } elapsed=1000.0*elapsed/Double(iterations) print(String(format: "RSA gen - %d iterations",iterations),terminator: ""); print(String(format: " %.2f ms per iteration",elapsed)) for i in 0..<RSA.RFS {M[i]=UInt8(i%128)} start=Date() iterations=0 elapsed=0.0 while elapsed<MIN_TIME || iterations<MIN_ITERS { RSA.ENCRYPT(pub,M,&C) iterations+=1 elapsed = -start.timeIntervalSinceNow } elapsed=1000.0*elapsed/Double(iterations) print(String(format: "RSA enc - %d iterations",iterations),terminator: ""); print(String(format: " %.2f ms per iteration",elapsed)) start=Date() iterations=0 elapsed=0.0 while elapsed<MIN_TIME || iterations<MIN_ITERS { RSA.DECRYPT(priv,C,&P) iterations+=1 elapsed = -start.timeIntervalSinceNow } elapsed=1000.0*elapsed/Double(iterations) print(String(format: "RSA dec - %d iterations",iterations),terminator: ""); print(String(format: " %.2f ms per iteration",elapsed)) var cmp=true for i in 0..<RSA.RFS { if P[i] != M[i] {cmp=false} } if !cmp { print("FAILURE - RSA decryption") fail=true; } if !fail { print("All tests pass") } } //BenchtestEC()
afcaa2c62bacea1915813908618ccf94
27.10559
79
0.633812
false
false
false
false
pawel-sp/PSZCircularPicker
refs/heads/master
iOS-Example/DragAndDropViewController.swift
mit
1
// // DragAndDropViewController.swift // PSZCircularPickerFramework // // Created by Paweł Sporysz on 28.10.2014. // Copyright (c) 2014 Paweł Sporysz. All rights reserved. // import UIKit import PSZCircularPicker class DragAndDropViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, CollectionViewDragAndDropControllerDelegate { // MARK: - Outlets @IBOutlet weak var pickerCollectionView: PickerCollectionView! @IBOutlet weak var presenterCollectionView: PresenterCollectionView! // MARK: - Data var data:[UIColor] = [ UIColor.grayColor(), UIColor.yellowColor(), UIColor.orangeColor(), UIColor.redColor(), UIColor.greenColor(), UIColor.magentaColor(), UIColor.purpleColor(), UIColor.blueColor(), UIColor.brownColor(), UIColor.blackColor() ] lazy var pickerData:[UIColor] = { return self.data }() var presenterData:[UIColor] = [] private var pickedColor:UIColor? var dragAndDropManager:CollectionViewDragAndDropController? // MARK: Lifecycle override func viewDidLoad() { super.viewDidLoad() self.dragAndDropManager = CollectionViewDragAndDropController(pickerCollectionView: self.pickerCollectionView, presenterCollectionView: self.presenterCollectionView, containerView: self.view) self.dragAndDropManager?.delegate = self self.presenterCollectionView.addGestureRecognizer(UITapGestureRecognizer(target:self, action:"test:")) } func test(gr:UITapGestureRecognizer) { println("\(self.presenterCollectionView.indexPathForItemAtPoint(gr.locationInView(gr.view)))") } // MARK: - UICollectionViewDataSource func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if collectionView is PickerCollectionView { return pickerData.count } else if collectionView is PresenterCollectionView { return presenterData.count } else { return 0 } } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { if collectionView is PickerCollectionView { var cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as UICollectionViewCell cell.addGestureRecognizer(self.dragAndDropManager!.dragAndDropLongPressGestureRecognizer) cell.backgroundColor = self.pickerData[indexPath.row] return cell } else if collectionView is PresenterCollectionView { var cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as UICollectionViewCell cell.backgroundColor = self.presenterData[indexPath.row] return cell } else { return UICollectionViewCell() } } // MARK: - PSZCollectionViewDragAndDropControllerDelegate func collectionViewDragAndDropController(collectionViewDragAndDropController: CollectionViewDragAndDropController, pickingUpView view: UIView, fromCollectionViewIndexPath indexPath: NSIndexPath) { UIView.animateWithDuration(0.25, animations: { () -> Void in view.transform = CGAffineTransformMakeScale(1.35, 1.35) }) self.pickedColor = self.pickerData.removeAtIndex(indexPath.row) self.pickerCollectionView.performBatchUpdates({ () -> Void in self.pickerCollectionView.deleteItemsAtIndexPaths([indexPath]) }, completion: nil) } func collectionViewDragAndDropController(collectionViewDragAndDropController: CollectionViewDragAndDropController, dragginView view: UIView, pickedInLocation: CGPoint) { //correct picked view origin after scale by 1.35 var origin = view.frame.origin var size = view.frame.size origin.x -= abs(pickedInLocation.x - size.width/2)*0.35 origin.y -= abs(pickedInLocation.y - size.height/2)*0.35 view.frame.origin = origin } func collectionViewDragAndDropController(collectionViewDragAndDropController: CollectionViewDragAndDropController, droppedView view: UIView, fromCollectionViewIndexPath fromIndexPath: NSIndexPath, toCollectionViewIndexPath toIndexPath: NSIndexPath, isCanceled canceled: Bool) { if canceled { self.pickerData.insert(self.pickedColor!, atIndex: fromIndexPath.row) self.pickerCollectionView.performBatchUpdates({ () -> Void in self.pickerCollectionView.insertItemsAtIndexPaths([fromIndexPath]) }, completion:nil) let orginalCell = self.pickerCollectionView.cellForItemAtIndexPath(fromIndexPath) let absoluteOrginalCellFrame = self.pickerCollectionView.convertRect(orginalCell!.frame, toView: self.view) UIView.animateWithDuration(0.25, animations: { () -> Void in view.frame = absoluteOrginalCellFrame view.alpha = 0 }, completion: { (_) -> Void in view.removeFromSuperview() }) } else { println("\(toIndexPath)") var targetIndexPath = toIndexPath if presenterData.count == 0 { targetIndexPath = NSIndexPathZero } self.presenterData.insert(self.pickedColor!, atIndex: targetIndexPath.row) self.presenterCollectionView.insertItemsAtIndexPaths([targetIndexPath]) var targetFrame = CGRectZero if let insertedCell = self.presenterCollectionView.cellForItemAtIndexPath(targetIndexPath) { targetFrame = self.view.convertRect(insertedCell.frame, fromView: self.presenterCollectionView) } UIView.animateWithDuration(0.25, animations: { () -> Void in view.frame = targetFrame view.alpha = 0 }, completion: { (_) -> Void in view.removeFromSuperview() }) } } }
7f317da3d201dd5cc8e29943008b995f
42.202797
281
0.679346
false
false
false
false
akrio714/Wbm
refs/heads/master
Wbm/Component/Calendar/CalendarView.swift
apache-2.0
1
// // CalendarView.swift // Wbm // // Created by akrio on 2017/7/21. // Copyright © 2017年 akrio. All rights reserved. // import UIKit import FSCalendar import SwiftDate import RxCocoa import RxSwift @IBDesignable class CalendarView: UIView { @IBOutlet weak var userHeaderButton: UserHeaderButton! @IBOutlet var contView: UIView! @IBOutlet weak var calendarView: FSCalendar! @IBOutlet weak var calendarHeightConstraint: NSLayoutConstraint! @IBOutlet weak var arrowImage: BaseImageView! @IBOutlet weak var dateTitleLabel: BaseLabel! @IBOutlet weak var backButton: UIButton! let selected:Variable<DateInRegion?> = Variable(nil) var days:[CalendarDayModel] = [] { didSet { self.calendarView.reloadData() if let date = days.first?.date.absoluteDate { self.calendarView.select(date) selected.value = date.inRegion() self.dateTitleLabel.text = date.inRegion().monthName } } } lazy var doneImage:UIImage? = CalendarDayModel.DayType.success.image() lazy var clearImage:UIImage? = CalendarDayModel.DayType.fail.image() lazy var circleImage:UIImage? = CalendarDayModel.DayType.wait.image() override init(frame: CGRect) { super.init(frame: frame) initFromXIB() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initFromXIB() } @IBAction func dateClick(_ sender: UITapGestureRecognizer) { UIView.animate(withDuration: 0.3){ [unowned self] in self.arrowImage.transform = self.arrowImage.transform.rotated(by: .pi) } self.calendarView.setScope(self.calendarView.scope == .month ? .week : .month, animated: true) } func initFromXIB() { let bundle = Bundle(for: type(of: self)) let nib = UINib(nibName: "CalendarView", bundle: bundle) contView = nib.instantiate(withOwner: self, options: nil)[0] as! UIView contView.frame = bounds self.addSubview(contView) calendarView.today = nil calendarView.clipsToBounds = true days = testData() } func testData() -> [CalendarDayModel] { let day1 = CalendarDayModel(date: DateInRegion() + 1.days, type: .fail) let day2 = CalendarDayModel(date: DateInRegion() + 2.days, type: .success) let day3 = CalendarDayModel(date: DateInRegion() + 3.days, type: .wait) let day4 = CalendarDayModel(date: DateInRegion() + 22.days, type: .success) let day5 = CalendarDayModel(date: DateInRegion() + 13.days, type: .wait) let day6 = CalendarDayModel(date: DateInRegion() - 2.days, type: .success) let day7 = CalendarDayModel(date: DateInRegion() - 3.days, type: .wait) return [day1,day2,day3,day4,day5,day6,day7].sorted{ $0.date < $1.date } } } extension CalendarView: FSCalendarDelegate,FSCalendarDataSource,FSCalendarDelegateAppearance { /// 设置日历下方图片 /// /// - Parameters: /// - calendar: 日历 /// - date: 日期 /// - Returns: 显示的图片 func calendar(_ calendar: FSCalendar, imageFor date: Date) -> UIImage? { return days.first{ $0.date.isInSameDayOf(date: date.inRegion()) }?.type.image() } /// 日历可滑动最小时间 /// /// - Parameter calendar: 日历 /// - Returns: 最小时间 func minimumDate(for calendar: FSCalendar) -> Date { return days.first?.date.absoluteDate ?? (DateInRegion() - 6.months).absoluteDate } /// 日历可滑动最大时间 /// /// - Parameter calendar: 日历 /// - Returns: 最大时间 func maximumDate(for calendar: FSCalendar) -> Date { return days.last?.date.absoluteDate ?? (DateInRegion() + 6.months).absoluteDate } /// 周月历切换时触发方法 /// /// - Parameters: /// - calendar: 日历 /// - bounds: 大小变化 /// - animated: 是否有动画 func calendar(_ calendar: FSCalendar, boundingRectWillChange bounds: CGRect, animated: Bool) { self.calendarHeightConstraint.constant = bounds.height self.superview?.layoutIfNeeded() print(bounds) } /// 日历是否可被选中 /// /// - Parameters: /// - calendar: 日历 /// - date: 日期 /// - monthPosition: <#monthPosition description#> /// - Returns: 是否可被选中 func calendar(_ calendar: FSCalendar, shouldSelect date: Date, at monthPosition: FSCalendarMonthPosition) -> Bool { return days.contains {$0.date.isInSameDayOf(date: date.inRegion()) } } /// 月份发生改变 /// /// - Parameter calendar: 日历 func calendarCurrentPageDidChange(_ calendar: FSCalendar) { self.dateTitleLabel.text = calendarView.currentPage.inRegion().monthName UIView.animate(withDuration: 0.3){ self.layoutIfNeeded() } } func calendar(_ calendar: FSCalendar, appearance: FSCalendarAppearance, titleDefaultColorFor date: Date) -> UIColor? { guard (days.contains {$0.date.isInSameDayOf(date: date.inRegion()) }) else { return appearance.titlePlaceholderColor } return nil } /// 日历被选中时圆圈的颜色 /// /// - Parameters: /// - calendar: 日历 /// - appearance: 日历一些配置 /// - date: 日期 /// - Returns: 选中后颜色 func calendar(_ calendar: FSCalendar, appearance: FSCalendarAppearance, fillSelectionColorFor date: Date) -> UIColor? { return days.first{ $0.date.isInSameDayOf(date: date.inRegion()) }?.type.color() } /// 日历选中事件 /// /// - Parameters: /// - calendar: <#calendar description#> /// - date: <#date description#> /// - monthPosition: <#monthPosition description#> func calendar(_ calendar: FSCalendar, didSelect date: Date, at monthPosition: FSCalendarMonthPosition) { self.selected.value = date.inRegion() } }
e3c52fedd2d4418860103ccae3cb3023
35.78481
123
0.630764
false
false
false
false
24/ios-o2o-c
refs/heads/master
BlueCapKit/External/ExtSwift/ExSwift.swift
bsd-2-clause
3
// // ExSwift.swift // ExSwift // // Created by pNre on 07/06/14. // Copyright (c) 2014 pNre. All rights reserved. // import Foundation infix operator =~ {} infix operator |~ {} infix operator .. {} public typealias Ex = ExSwift public class ExSwift { /** Creates a wrapper that, executes function only after being called n times. :param: n No. of times the wrapper has to be called before function is invoked :param: function Function to wrap :returns: Wrapper function */ public class func after <P, T> (n: Int, function: (P...) -> T) -> ((P...) -> T?) { typealias Function = [P] -> T var times = n return { (params: P...) -> T? in // Workaround for the now illegal (T...) type. let adaptedFunction = unsafeBitCast(function, Function.self) if times-- <= 0 { return adaptedFunction(params) } return nil } } /** Creates a wrapper that, executes function only after being called n times :param: n No. of times the wrapper has to be called before function is invoked :param: function Function to wrap :returns: Wrapper function */ public class func after <T> (n: Int, function: Void -> T) -> (Void -> T?) { func callAfter (args: Any?...) -> T { return function() } let f = ExSwift.after(n, function: callAfter) return { f([nil])? } } /** Creates a wrapper function that invokes function once. Repeated calls to the wrapper function will return the value of the first call. :param: function Function to wrap :returns: Wrapper function */ public class func once <P, T> (function: (P...) -> T) -> ((P...) -> T) { typealias Function = [P] -> T var returnValue: T? = nil return { (params: P...) -> T in if returnValue != nil { return returnValue! } let adaptedFunction = unsafeBitCast(function, Function.self) returnValue = adaptedFunction(params) return returnValue! } } /** Creates a wrapper function that invokes function once. Repeated calls to the wrapper function will return the value of the first call. :param: function Function to wrap :returns: Wrapper function */ public class func once <T> (function: Void -> T) -> (Void -> T) { let f = ExSwift.once { (params: Any?...) -> T in return function() } return { f([nil]) } } /** Creates a wrapper that, when called, invokes function with any additional partial arguments prepended to those provided to the new function. :param: function Function to wrap :param: parameters Arguments to prepend :returns: Wrapper function */ public class func partial <P, T> (function: (P...) -> T, _ parameters: P...) -> ((P...) -> T) { typealias Function = [P] -> T return { (params: P...) -> T in let adaptedFunction = unsafeBitCast(function, Function.self) return adaptedFunction(parameters + params) } } /** Creates a wrapper (without any parameter) that, when called, invokes function automatically passing parameters as arguments. :param: function Function to wrap :param: parameters Arguments to pass to function :returns: Wrapper function */ public class func bind <P, T> (function: (P...) -> T, _ parameters: P...) -> (Void -> T) { typealias Function = [P] -> T return { Void -> T in let adaptedFunction = unsafeBitCast(function, Function.self) return adaptedFunction(parameters) } } /** Creates a wrapper for function that caches the result of function's invocations. :param: function Function to cache :param: hash Parameters based hashing function that computes the key used to store each result in the cache :returns: Wrapper function */ public class func cached <P: Hashable, R> (function: (P...) -> R, hash: ((P...) -> P)) -> ((P...) -> R) { typealias Function = [P] -> R typealias Hash = [P] -> P var cache = [P:R]() return { (params: P...) -> R in let adaptedFunction = unsafeBitCast(function, Function.self) let adaptedHash = unsafeBitCast(hash, Hash.self) let key = adaptedHash(params) if let cachedValue = cache[key] { return cachedValue } cache[key] = adaptedFunction(params) return cache[key]! } } /** Creates a wrapper for function that caches the result of function's invocations. :param: function Function to cache :returns: Wrapper function */ public class func cached <P: Hashable, R> (function: (P...) -> R) -> ((P...) -> R) { return cached(function, hash: { (params: P...) -> P in return params[0] }) } /** Utility method to return an NSRegularExpression object given a pattern. :param: pattern Regex pattern :param: ignoreCase If true the NSRegularExpression is created with the NSRegularExpressionOptions.CaseInsensitive flag :returns: NSRegularExpression object */ internal class func regex (pattern: String, ignoreCase: Bool = false) -> NSRegularExpression? { var options = NSRegularExpressionOptions.DotMatchesLineSeparators.rawValue if ignoreCase { options = NSRegularExpressionOptions.CaseInsensitive.rawValue | options } var error: NSError? = nil let regex = NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions(rawValue: options), error: &error) return (error == nil) ? regex : nil } } /** * Internal methods */ extension ExSwift { /** * Converts, if possible, and flattens an object from its Objective-C * representation to the Swift one. * @param object Object to convert * @returns Flattenend array of converted values */ internal class func bridgeObjCObject <T, S> (object: S) -> [T] { var result = [T]() let reflection = reflect(object) // object has an Objective-C type if let obj = object as? T { // object has type T result.append(obj) } else if reflection.disposition == .ObjCObject { var bridgedValue: T!? // If it is an NSArray, flattening will produce the expected result if let array = object as? NSArray { result += array.flatten() } else if let bridged = reflection.value as? T { result.append(bridged) } } else if reflection.disposition == .IndexContainer { // object is a native Swift array // recursively convert each item (0..<reflection.count).each { let ref = reflection[$0].1 result += Ex.bridgeObjCObject(ref.value) } } return result } }
f30f7bc92fd583d9f34f5ef25e42e057
29.764
128
0.545053
false
false
false
false
raphaelhanneken/iconizer
refs/heads/master
Iconizer/Models/ImageSet.swift
mit
1
// // ImageSet.swift // Iconizer // https://github.com/raphaelhanneken/iconizer // import Cocoa class ImageSet: Codable { //scale of input image static let inputScale: CGFloat = 3 let idiom: String let scale: AssetScale var filename: String { return "image@\(scale.rawValue).png" } private enum ReadKeys: String, CodingKey { case idiom case scale } private enum WriteKeys: String, CodingKey { case idiom case scale case filename } init(idiom: String, scale: AssetScale) { self.idiom = idiom self.scale = scale } required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: ReadKeys.self) let idiom = try container.decode(String.self, forKey: .idiom) guard let scale = AssetScale(rawValue: try container.decode(String.self, forKey: .scale)) else { throw AssetCatalogError.invalidFormat(format: .scale) } self.idiom = idiom self.scale = scale } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: WriteKeys.self) try container.encode(idiom, forKey: .idiom) try container.encode(scale.rawValue, forKey: .scale) try container.encode(filename, forKey: .filename) } } extension ImageSet: Asset { static let resourcePrefix = "ImageSet" static func directory(named: String) -> String { return "\(Constants.Directory.imageSet)/\(named).\(Constants.AssetExtension.imageSet)" } func save(_ image: [ImageOrientation: NSImage], aspect: AspectMode?, to url: URL) throws { guard let image = image[.all] else { throw AssetCatalogError.missingImage } let url = url.appendingPathComponent(filename, isDirectory: false) let coef = CGFloat(scale.value) / ImageSet.inputScale let size = NSSize(width: ceil(image.size.width * coef), height: ceil(image.size.height * coef)) guard let resized = image.resize(toSize: size, aspectMode: aspect ?? .fit) else { throw AssetCatalogError.rescalingImageFailed } try resized.savePng(url: url) } }
ca1589d1a23408e8f34bf5071e915d5e
27.615385
104
0.642025
false
false
false
false
avario/ChainKit
refs/heads/master
ChainKit/ChainKit/UIImageView+ChainKit.swift
mit
1
// // UIImageView+ChainKit.swift // ChainKit // // Created by Avario. // import UIKit public extension UIImageView { public func image(_ image: UIImage?) -> Self { self.image = image return self } public func highlightedImage(_ highlightedImage: UIImage?) -> Self { self.highlightedImage = highlightedImage return self } public func isHighlighted(_ isHighlighted: Bool) -> Self { self.isHighlighted = isHighlighted return self } public func animationImages(_ animationImages: [UIImage]?) -> Self { self.animationImages = animationImages return self } public func highlightedAnimationImages(_ highlightedAnimationImages: [UIImage]?) -> Self { self.highlightedAnimationImages = highlightedAnimationImages return self } public func animationDuration(_ animationDuration: TimeInterval) -> Self { self.animationDuration = animationDuration return self } public func animationRepeatCount(_ animationRepeatCount: Int) -> Self { self.animationRepeatCount = animationRepeatCount return self } }
95306a644edf5451d72d2982d845959b
24.425532
94
0.648536
false
false
false
false
codefellows/sea-b23-iOS
refs/heads/master
TwitterClone/HomeTimeLineViewController.swift
mit
1
// // HomeTimeLineViewController.swift // TwitterClone // // Created by Bradley Johnson on 10/6/14. // Copyright (c) 2014 Code Fellows. All rights reserved. // import UIKit import Accounts import Social class HomeTimeLineViewController: UIViewController, UITableViewDataSource, UIApplicationDelegate { @IBOutlet weak var tableView: UITableView! var tweets : [Tweet]? var twitterAccount : ACAccount? var networkController : NetworkController! override func viewDidLoad() { super.viewDidLoad() self.tableView.registerNib(UINib(nibName: "TweetCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "TWEET_CELL") let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate self.networkController = appDelegate.networkController self.networkController.fetchHomeTimeLine { (errorDescription : String?, tweets : [Tweet]?) -> (Void) in if errorDescription != nil { //alert the user that something went wrong } else { self.tweets = tweets self.tableView.reloadData() } } println("Hello") if let path = NSBundle.mainBundle().pathForResource("tweet", ofType: "json") { var error : NSError? let jsonData = NSData(contentsOfFile: path) self.tweets = Tweet.parseJSONDataIntoTweets(jsonData) } } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if self.tweets != nil { return self.tweets!.count } else { return 0 } } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { //step 1 dequeue the cell let cell = tableView.dequeueReusableCellWithIdentifier("TWEET_CELL", forIndexPath: indexPath) as TweetCell //step 2 figure out which model object youre going to use to configure the cell //this is where we would grab a reference to the correct tweet and use it to configure the cell let tweet = self.tweets?[indexPath.row] cell.tweetLabel.text = tweet?.text if tweet?.avatarImage != nil { cell.avatarImageView.image = tweet?.avatarImage } else { self.networkController.downloadUserImageForTweet(tweet!, completionHandler: { (image) -> (Void) in let cellForImage = self.tableView.cellForRowAtIndexPath(indexPath) as TweetCell? cellForImage?.avatarImageView.image = image }) } //step 3 return the cell return cell } }
33e36f61af703c7b38db1549cfe3e21e
36.040541
132
0.631521
false
false
false
false
VladiMihaylenko/omim
refs/heads/master
iphone/Maps/UI/PlacePage/PlacePageLayout/Content/UGC/UGCSpecificReviewCell.swift
apache-2.0
14
@objc(MWMUGCSpecificReviewDelegate) protocol UGCSpecificReviewDelegate: NSObjectProtocol { func changeReviewRate(_ rate: Int, atIndexPath: NSIndexPath) } @objc(MWMUGCSpecificReviewCell) final class UGCSpecificReviewCell: MWMTableViewCell { @IBOutlet private weak var specification: UILabel! @IBOutlet private var stars: [UIButton]! private var indexPath: NSIndexPath = NSIndexPath() private var delegate: UGCSpecificReviewDelegate? @objc func configWith(specification: String, rate: Int, atIndexPath: NSIndexPath, delegate: UGCSpecificReviewDelegate?) { self.specification.text = specification self.delegate = delegate indexPath = atIndexPath stars.forEach { $0.isSelected = $0.tag <= rate } } @IBAction private func tap(on: UIButton) { stars.forEach { $0.isSelected = $0.tag <= on.tag } delegate?.changeReviewRate(on.tag, atIndexPath: indexPath) } // TODO: Make highlighting and dragging. @IBAction private func highlight(on _: UIButton) {} @IBAction private func touchingCanceled(on _: UIButton) {} @IBAction private func drag(inside _: UIButton) {} }
1ba2da22348193ed27f489c912ca9227
33.71875
123
0.747075
false
false
false
false
psharanda/vmc2
refs/heads/master
4. MVVM/MVVM/MainViewModel.swift
mit
1
// // Created by Pavel Sharanda on 17.11.16. // Copyright © 2016 psharanda. All rights reserved. // import Foundation class MainViewModel: MainViewModelProtocol { weak var delegate: MainViewModelDelegate? weak var routingDelegate: MainViewModelRoutingDelegate? var loading: Bool = false { didSet { delegate?.loadingWasChanged(viewModel: self) } } var text: String? { didSet { delegate?.textWasChanged(viewModel: self) } } let textLoader: TextLoaderProtocol init(textLoader: TextLoaderProtocol) { self.textLoader = textLoader } func loadButtonClicked() { loading = true text = nil self.textLoader.loadText { self.loading = false self.text = $0 } } func detailsClicked() { routingDelegate?.showDetails(viewModel: self) } }
15893af2a094a36ef4c28bc45dc79f76
20.860465
59
0.592553
false
false
false
false
PureSwift/Bluetooth
refs/heads/master
Sources/BluetoothGAP/GAP3DInformation.swift
mit
1
// // GAP3DInformation.swift // Bluetooth // // Created by Carlos Duclos on 6/14/18. // Copyright © 2018 PureSwift. All rights reserved. // import Foundation /** The 3DD shall include a section in its EIR data providing 3D Synchronization Profile - Note: Future versions of this EIR data may be extended to carry additional bytes in the Profile specific 3D Information data section. Therefore, 3DG compliant with this version of the Profile specification shall ignore any additional data beyond what is specified in Table 5.2, if present. */ @frozen public struct GAP3DInformation: GAPData, Equatable { public static var dataType: GAPDataType { return .informationData3D } /** GAP 3D Information Flags • Association Notification: (Byte 2, bit 0) 0 – Not supported 1 – Supported • Battery Level Reporting: (Byte 2, bit 1) 0 – Not supported 1 – Supported • Send Battery Level Report on Start-up Synchronization: (Byte 2, bit 2) 0 – 3DD requests 3DG to not send a 3DG Connection Announcement Message with Battery Level Report on Start-up Synchronization. 1 – 3DD requests 3DG to send a 3DG Connection Announcement Message with Battery Level Report on Start-up Synchronization. - Note: The value shall be set to 0 if the Battery Level Reporting is set to 0. • Factory Test Mode: (Byte 2, bit 7) 0 – normal operating mode 1 – vendor-defined factory test mode • Path Loss Threshold In dB. Maximum allowable path attenuation from 3DD to 3DG. Greater attenuation than this number will inform the 3DG that it is too far away and to look for another 3DD. */ public var flags: BitMaskOptionSet<Flag> /** Path Loss Threshold In dB. Maximum allowable path attenuation from 3DD to 3DG. Greater attenuation than this number will inform the 3DG that it is too far away and to look for another 3DD. */ public var pathLossThreshold: UInt8 public init(flags: BitMaskOptionSet<Flag> = 0, pathLossThreshold: UInt8 = 0) { self.flags = flags self.pathLossThreshold = pathLossThreshold } } public extension GAP3DInformation { init?(data: Data) { guard data.count == 2 else { return nil } let flags = BitMaskOptionSet<Flag>(rawValue: data[data.startIndex]) let pathLossThreshold = data[1] self.init(flags: flags, pathLossThreshold: pathLossThreshold) } func append(to data: inout Data) { data += flags.rawValue data += pathLossThreshold } var dataLength: Int { return 2 } } // MARK: - Supporting Types public extension GAP3DInformation { /// GAP 3D Information Flag enum Flag: UInt8, BitMaskOption { /// Association Notification case associationNotification = 0b01 /// Battery Level Reporting case batteryLevelReporting = 0b10 /// Send Battery Level Report on Start-up Synchronization case sendBatteryLevelOnStartUp = 0b100 /// Factory Test Mode case factoryTestMode = 0b10000000 public static let allCases: [Flag] = [ .associationNotification, .batteryLevelReporting, .sendBatteryLevelOnStartUp, .factoryTestMode ] } }
7d7cf9cd8bd68e5e7d82d90921cf07e6
29.356522
292
0.644801
false
false
false
false
AzenXu/Memo
refs/heads/master
Memo/Common/Views/SimpleCustomViews.swift
mit
1
// // SimpleCustomViews.swift // JFoundation // // Created by XuAzen on 16/7/4. // Copyright © 2016年 st. All rights reserved. // import Foundation import UIKit //MARK:- Custom ContentSizeChange Element public typealias UTravWebViewContentSizeChangeCallBack = (CGSize) -> () public class UTravWebView: UIWebView { var lastContentSize = CGSizeZero override public init(frame: CGRect) { super.init(frame: frame) scrollView.addObserver(self, forKeyPath: "contentSize", options: NSKeyValueObservingOptions.New, context: nil) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } var contentSizeChangeCallBack :UTravWebViewContentSizeChangeCallBack? public func setContentSizeCallBack(contentSizeChange :UTravWebViewContentSizeChangeCallBack) { contentSizeChangeCallBack = contentSizeChange } override public func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { if keyPath == "contentSize" { let contentSize = change!["new"]!.CGSizeValue() if contentSize != lastContentSize { lastContentSize = contentSize if let contentSizeChangeCallBack = contentSizeChangeCallBack { contentSizeChangeCallBack(contentSize) } } } } deinit { scrollView.removeObserver(self, forKeyPath: "contentSize") } } public class WebCollectionCell: BasicCollectionCell { private var webView: UTravWebView = UTravWebView(frame: CGRect.init(x: 0, y: 0, width: ScreenWidth, height: 300)) private var request: NSURLRequest? private var contentSizeCallBack: ((CGSize) -> ())? public override init(frame: CGRect) { super.init(frame: frame) makeupViews() } public func setContentSizeCallBack(callBack: CGSize -> ()) { self.contentSizeCallBack = callBack webView.setContentSizeCallBack { (newSize) in guard let contentSizeCallBack = self.contentSizeCallBack else {return} contentSizeCallBack(newSize) } } /** 防止每次reloadData都重新加载web */ public func setRequest(request: NSURLRequest) { if self.request != request { self.request = request loadRequest(request) } } private func loadRequest(request: NSURLRequest) { webView.loadRequest(request) } private func makeupViews() { webView.then { (web) in addSubview(web) web.snp_remakeConstraints(closure: { (make) in make.left.equalTo(0) make.right.equalTo(0) make.bottom.equalTo(0) make.top.equalTo(0) }) } } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } public class UICollectionViewWithContentSizeCallBack: UICollectionView { private var lastContentSize = CGSizeZero private var contentSizeChangeCallBack :UTravWebViewContentSizeChangeCallBack? public func setContentSizeCallBack(contentSizeChange :UTravWebViewContentSizeChangeCallBack) { contentSizeChangeCallBack = contentSizeChange } override public init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) { super.init(frame: frame, collectionViewLayout: layout) self.addObserver(self, forKeyPath: "contentSize", options: NSKeyValueObservingOptions.New, context: nil) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override public func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { if keyPath == "contentSize" { let contentSize = change!["new"]!.CGSizeValue() if contentSize != lastContentSize { lastContentSize = contentSize if let contentSizeChangeCallBack = contentSizeChangeCallBack { contentSizeChangeCallBack(contentSize) } } } } deinit { self.removeObserver(self, forKeyPath: "contentSize") } } //MARK:- Basic UI Element public class CustomColorButton: UIButton { public var selectedBorderColor: UIColor? public var unSelectedBorderColor: UIColor? override public var selected: Bool { didSet { if self.selected { if let selectedBorderColor = self.selectedBorderColor { self.layer.borderColor = selectedBorderColor.CGColor } } else { if let unSelectedBorderColor = self.unSelectedBorderColor { self.layer.borderColor = unSelectedBorderColor.CGColor } } } } public var hightlightedBackgroundColor: UIColor? public var normalBackgroundColor: UIColor? override public var highlighted: Bool { didSet { if highlighted { if let hightlightedBackgroundColor = self.hightlightedBackgroundColor { backgroundColor = hightlightedBackgroundColor } } else { if let normalBackgroundColor = self.normalBackgroundColor { backgroundColor = normalBackgroundColor } } } } public var disableBackgroundColor: UIColor? public var disableTextColor: UIColor? public var enableBackgroundColor: UIColor? public var enableTextColor: UIColor? public var clickCallBack: ((button: UIButton)->())? override public var enabled: Bool { didSet { if enabled { if let enableBackgroundColor = self.enableBackgroundColor { backgroundColor = enableBackgroundColor } if let enableTextColor = self.enableTextColor { setTitleColor(enableTextColor, forState: UIControlState.Normal) } } else { if let disableBackgroundColor = self.disableBackgroundColor { backgroundColor = disableBackgroundColor } if let disableTextColor = self.disableTextColor { setTitleColor(disableTextColor, forState: UIControlState.Normal) } } } } public override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { super.touchesBegan(touches, withEvent: event) clickCallBack?(button: self) } } public class RightIconButton: CustomColorButton { override public func layoutSubviews() { super.layoutSubviews() let titleL = titleLabel! let imageV = imageView! if titleL.x > imageV.x { titleL.x = imageV.x imageV.x = titleL.width + titleL.x + 7 } } }
183b058778e9ea706b92bc39cb4fe67c
32.892019
164
0.623026
false
false
false
false
rsyncOSX/RsyncOSX
refs/heads/master
RsyncOSX/Running.swift
mit
1
// // Running.swift // RsyncOSX // // Created by Thomas Evensen on 07.02.2018. // Copyright © 2018 Thomas Evensen. All rights reserved. // import AppKit import Foundation final class Running { let rsyncOSX = "no.blogspot.RsyncOSX" let rsyncOSXsched = "no.blogspot.RsyncOSXsched" var rsyncOSXisrunning: Bool = false var rsyncOSXschedisrunning: Bool = false var menuappnoconfig: Bool = true func verifyrsyncosxsched() -> Bool { let fileManager = FileManager.default guard fileManager.fileExists(atPath: (SharedReference.shared.pathrsyncosxsched ?? "/Applications/") + SharedReference.shared.namersyncosssched) else { return false } return true } @discardableResult init() { // Get all running applications let workspace = NSWorkspace.shared let applications = workspace.runningApplications let rsyncosx = applications.filter { $0.bundleIdentifier == self.rsyncOSX } let rsyncosxschde = applications.filter { $0.bundleIdentifier == self.rsyncOSXsched } if rsyncosx.count > 0 { rsyncOSXisrunning = true } else { rsyncOSXisrunning = false } if rsyncosxschde.count > 0 { rsyncOSXschedisrunning = true SharedReference.shared.menuappisrunning = true } else { rsyncOSXschedisrunning = false SharedReference.shared.menuappisrunning = false } } }
37698285e682879c15e83454223c95e9
31.173913
109
0.65473
false
false
false
false
segej87/ecomapper
refs/heads/master
iPhone/EcoMapper/EcoMapper/PhotoViewController.swift
gpl-3.0
2
// // PhotoViewController.swift // EcoMapper // // Created by Jon on 6/21/16. // Copyright © 2016 Sege Industries. All rights reserved. // import UIKit import CoreLocation import Photos class PhotoViewController: RecordViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate { // MARK: Properties // IB Properties @IBOutlet weak var nameTextField: UITextField! @IBOutlet weak var photoImageView: UIImageView! @IBOutlet weak var accessTextField: UITextField! @IBOutlet weak var notesTextField: UITextView! @IBOutlet weak var tagTextField: UITextField! @IBOutlet weak var saveButton: UIBarButtonItem! @IBOutlet weak var gpsAccView: UILabel! @IBOutlet weak var accessPickerButton: UIButton! @IBOutlet weak var tagPickerButton: UIButton! @IBOutlet weak var gpsStabView: UILabel! @IBOutlet weak var gpsReportArea: UIView! // The path to the photo on the device's drive var photoURL: URL? var media: Media? var medOutName: String? // MARK: Initialization override func viewDidLoad() { super.viewDidLoad() } // MARK: UI Methods override func setUpFields() { if mode == "old" { if let record = record { navigationItem.title = "Editing Photo" nameTextField.text = record.props["name"] as? String accessTextField.text = (record.props["access"] as? [String])?.joined(separator: ", ") accessArray = record.props["access"] as! [String] photoURL = URL(fileURLWithPath: record.props["filepath"] as! String) selectedImage = record.photo photoImageView.image = selectedImage photoImageView.isUserInteractionEnabled = false notesTextField.text = record.props["text"] as? String tagTextField.text = (record.props["tags"] as? [String])?.joined(separator: ", ") tagArray = record.props["tags"] as! [String] dateTime = record.props["datetime"] as? String userLoc = record.coords gpsReportArea.isHidden = true } } // Fill data into text fields accessTextField.text = accessArray.joined(separator: ", ") tagTextField.text = tagArray.joined(separator: ", ") // Add border to text view self.notesTextField.layer.borderWidth = 0.5 self.notesTextField.layer.cornerRadius = 10 self.notesTextField.layer.borderColor = UIColor.init(red: 200/255.0, green: 199/255.0, blue: 204/255.0, alpha: 1.0).cgColor // Handle text fields' user input through delegate callbacks. nameTextField.delegate = self accessTextField.delegate = self tagTextField.delegate = self // Handle the notes field's user input through delegate callbacks. notesTextField.delegate = self } // MARK: Camera alert func noCamera() { if #available(iOS 8.0, *) { let alertVC = UIAlertController(title: "No Camera", message: "Sorry, this device doesn't have a camera", preferredStyle: .alert) let okAction = UIAlertAction(title: "OK", style: .default, handler: nil) alertVC.addAction(okAction) present(alertVC, animated: true, completion: nil) } else { let alertVC = UIAlertView(title: "No Camera", message: "Sorry, this device doesn't have a camera", delegate: self, cancelButtonTitle: "OK") alertVC.show() } } // MARK: UIImagePickerControllerDelegate func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { // Dismiss the picker if the user canceled. dismiss(animated: true, completion: nil) } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { // The info dictionary contains multiple representations of the image, and this uses the original. let outImage = info[UIImagePickerControllerOriginalImage] as? UIImage // Dismiss the picker. dismiss(animated: true, completion: nil) // Segue to the crop view self.performSegue(withIdentifier: "CropSegue", sender: outImage) } // MARK: Location methods override func updateGPS() { if gpsAcc == -1 { gpsAccView.text = "Locking" gpsAccView.textColor = UIColor.red } else { gpsAccView.text = String(format: "%.1f m", abs(gpsAcc)) if gpsAcc <= minGPSAccuracy! { gpsAccView.textColor = UIColor.green } else { gpsAccView.textColor = UIColor.red } } if gpsStab == -1 { gpsStabView.text = "Locking" gpsStabView.textColor = UIColor.red } else { gpsStabView.text = String(format: "%.1f m", abs(gpsStab)) if gpsStab <= minGPSStability! { gpsStabView.textColor = UIColor.green } else { gpsStabView.textColor = UIColor.red } } } // MARK: Navigation @IBAction func cancel(_ sender: UIBarButtonItem) { cancelView() } // This method lets you configure a view controller before it's presented. override func prepare(for segue: UIStoryboardSegue, sender: Any?) { locationManager.stopUpdatingLocation() if segue.identifier == "CropSegue" { let secondVC = segue.destination as! CropImageViewController if let imageOut = sender as? UIImage { secondVC.inputImage = imageOut } } // If the add access button was pressed, present the item picker with an access item type if sender is UIButton && accessPickerButton === (sender as! UIButton) { let secondVC = segue.destination as! ListPickerViewController secondVC.itemType = "access" // Send previous access levels to ListPicker if accessTextField.text != "" { for a in accessArray { secondVC.selectedItems.append(a) } } } // If the add tags button was pressed, present the item picker with a tags item type if sender is UIButton && tagPickerButton === (sender as! UIButton) { let secondVC = segue.destination as! ListPickerViewController secondVC.itemType = "tags" // Send previous tags to ListPicker if tagTextField.text != "" { for t in tagArray { secondVC.selectedItems.append(t) } } } } // Handle returns from list pickers @IBAction func unwindFromListPicker(_ segue: UIStoryboardSegue) { // The view controller that initiated the segue let secondVC : ListPickerViewController = segue.source as! ListPickerViewController // The type of the view controller that initiated the segue let secondType = secondVC.itemType // The text field that should be modified by the results of the list picker var targetField : UITextField? // Set the target text field based on the second view controller's type switch secondType! { case "tags": targetField = tagTextField break case "access": targetField = accessTextField break default: targetField = nil } // Handle changes to User Variables due to the list picker activity handleListPickerResult(secondType: secondType!, secondVC: secondVC) targetField!.text = secondVC.selectedItems.joined(separator: ", ") } @IBAction func unwindFromCropView(_ segue: UIStoryboardSegue) { let secondVC = segue.source as! CropImageViewController if let outImage = secondVC.outputImage { selectedImage = outImage // Set the aspect ratio of the image in the view photoImageView.contentMode = .scaleAspectFit // Set photoImageView to display the selected image. photoImageView.image = selectedImage // Set the name of the photo medOutName = "Photo_\(dateTime!.replacingOccurrences(of: "-", with: "").replacingOccurrences(of: ":", with: "").replacingOccurrences(of: " ", with: "_")).jpg" // Set path of photo to be saved photoURL = UserVars.PhotosURL.appendingPathComponent(medOutName!) } } @IBAction func captureImage(_ sender: UITapGestureRecognizer) { if PHPhotoLibrary.authorizationStatus() == .notDetermined { PHPhotoLibrary.requestAuthorization(requestAuthorizationHandler) } startImageCapture() } func requestAuthorizationHandler(status: PHAuthorizationStatus) { if PHPhotoLibrary.authorizationStatus() == PHAuthorizationStatus.authorized { self.startImageCapture() } else { self.dismiss(animated: true, completion: nil) } } func startImageCapture() { if UIImagePickerController.availableCaptureModes(for: .rear) != nil { // Create a controller for handling the camera action let imageTakerController = UIImagePickerController() // Set camera options imageTakerController.allowsEditing = false imageTakerController.sourceType = .camera imageTakerController.cameraCaptureMode = .photo imageTakerController.modalPresentationStyle = .fullScreen // Make sure ViewController is notified when the user takes an image. imageTakerController.delegate = self present(imageTakerController, animated: true, completion: nil) } else { noCamera() } } // MARK: Actions @IBAction func setDefaultNameText(_ sender: UIButton) { nameTextField.text = "Photo" + " - " + dateTime! } @IBAction override func attemptSave(_ sender: AnyObject) { print("Saving record?: \(saveRecord())") if saveRecord() { if mode == "new" { // Set the media reference to be passed to NotebookViewController after the unwind segue. media = Media(name: medOutName!, path: photoURL, marked: false) //Save the photo // Create an NSCoded photo object let outPhoto = NewPhoto(photo: selectedImage) // Save the photo to the photos directory savePhoto(outPhoto!) } self.performSegue(withIdentifier: "exitSegue", sender: self) } } // MARK: NSCoding func savePhoto(_ photo: NewPhoto) { if !FileManager.default.fileExists(atPath: UserVars.PhotosURL.path) { do { try FileManager.default.createDirectory(atPath: UserVars.PhotosURL.path, withIntermediateDirectories: false, attributes: nil) } catch let error as NSError { print(error.localizedDescription); } } let isSuccessfulSave = NSKeyedArchiver.archiveRootObject(photo, toFile: photoURL!.path) if !isSuccessfulSave { NSLog("Failed to save photo...") } else { NSLog("Saving photo to \(photoURL!.path)") } } // MARK: Helper methods override func checkRequiredData() -> Bool { var errorString : String? let dateCheck = dateTime != nil && dateTime != "" let locCheck = mode == "old" || (userOverrideStale || checkLocationOK()) if !(nameTextField.text != nil && nameTextField.text != "") { errorString = "The Name field is required." } else if !(accessArray.count > 0) { errorString = "Select at least one Access Level." } else if !(photoURL?.absoluteString != nil && photoURL?.absoluteString != "") { errorString = "Take a photo." } else if !(tagArray.count > 0) { errorString = "Select at least one Tag." } if let error = errorString { if #available(iOS 8.0, *) { let alertVC = UIAlertController(title: "Missing required data.", message: error, preferredStyle: .alert) let okAction = UIAlertAction(title: "OK", style: .default, handler: nil) alertVC.addAction(okAction) present(alertVC, animated: true, completion: nil) } else { let alertVC = UIAlertView(title: "Missing required data.", message: error, delegate: self, cancelButtonTitle: "OK") alertVC.show() } } return errorString == nil && dateCheck && locCheck } override func setItemsOut() -> [String : AnyObject] { let name = nameTextField.text ?? "" let urlOut = photoURL!.absoluteString return ["name": name as AnyObject, "tags": tagArray as AnyObject, "datatype": "photo" as AnyObject, "datetime": dateTime! as AnyObject, "access": accessArray as AnyObject, "accuracy": gpsAcc as AnyObject, "text": notesTextField.text as AnyObject, "filepath": urlOut as AnyObject] as [String:AnyObject] } }
cc96489eb0d65fefeff0f727c83e5a6d
36.284182
309
0.587186
false
false
false
false
Arcovv/CleanArchitectureRxSwift
refs/heads/master
RealmPlatform/Entities/RMPhoto.swift
mit
1
// // RMPhoto.swift // CleanArchitectureRxSwift // // Created by Andrey Yastrebov on 10.03.17. // Copyright © 2017 sergdort. All rights reserved. // import QueryKit import Domain import RealmSwift import Realm final class RMPhoto: Object { dynamic var albumId: String = "" dynamic var thumbnailUrl: String = "" dynamic var title: String = "" dynamic var uid: String = "" dynamic var url: String = "" override class func primaryKey() -> String? { return "uid" } } extension RMPhoto { static var title: Attribute<String> { return Attribute("title")} static var thumbnailUrl: Attribute<String> { return Attribute("thumbnailUrl")} static var url: Attribute<String> { return Attribute("url")} static var albumId: Attribute<String> { return Attribute("albumId")} static var uid: Attribute<String> { return Attribute("uid")} } extension RMPhoto: DomainConvertibleType { func asDomain() -> Photo { return Photo(albumId: albumId, thumbnailUrl: thumbnailUrl, title: title, uid: uid, url: url) } } extension Photo: RealmRepresentable { func asRealm() -> RMPhoto { return RMPhoto.build { object in object.albumId = albumId object.thumbnailUrl = thumbnailUrl object.title = title object.uid = uid object.url = url } } }
9548f7a9cc707d438a6bb42bf2f9a034
25.654545
82
0.611187
false
false
false
false
manfengjun/KYMart
refs/heads/master
Section/Product/Detail/View/KYPropertyFootView.swift
mit
1
// // KYPropertyFootView.swift // KYMart // // Created by jun on 2017/6/8. // Copyright © 2017年 JUN. All rights reserved. // import UIKit import PPNumberButtonSwift class KYPropertyFootView: UIView { @IBOutlet var contentView: UIView! @IBOutlet weak var numberButton: PPNumberButton! var CountResultClosure: ResultClosure? // 闭包 override init(frame: CGRect) { super.init(frame: frame) contentView = Bundle.main.loadNibNamed("KYPropertyFootView", owner: self, options: nil)?.first as! UIView contentView.frame = self.bounds addSubview(contentView) awakeFromNib() } func reloadMaxValue(){ numberButton.maxValue = (SingleManager.instance.productBuyInfoModel?.good_buy_store_count)! } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func awakeFromNib() { super.awakeFromNib() numberButton.shakeAnimation = true numberButton.minValue = 1 numberButton.maxValue = (SingleManager.instance.productBuyInfoModel?.good_buy_store_count)! numberButton.borderColor(UIColor.hexStringColor(hex: "#666666")) numberButton.numberResult { (number) in if let count = Int(number){ self.CountResultClosure?(count) } } } /** 加减按钮的响应闭包回调 */ func countResult(_ finished: @escaping ResultClosure) { CountResultClosure = finished } }
234289398882af99970474a4d288690c
30.229167
113
0.657105
false
false
false
false
BruceFight/JHB_HUDView
refs/heads/master
JHB_HUDView/JHB_HUDDiyManager.swift
mit
1
/****************** JHB_HUDDiyManager.swift *********************/ /******* (JHB) ************************************************/ /******* Created by Leon_pan on 16/8/15. ***********************/ /******* Copyright © 2016年 CoderBala. All rights reserved.*****/ /****************** JHB_HUDDiyManager.swift *********************/ import UIKit class JHB_HUDDiyManager: JHB_HUDPublicManager { // MARK: parameters /*核心视图*//*Core View Part*/ var coreView = JHB_HUDDiyProgressView() /*透明背景*//*Clear Background*/ var bgClearView = UIView() // MARK: - Interface override init(frame: CGRect) { super.init(frame: UIScreen.main.bounds) self.setUp() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setUp() } func setUp() { self.setSubViews() self.addSubview(self.bgClearView) self.addSubview(self.coreView) PreOrientation = UIDevice.current.orientation InitOrientation = UIDevice.current.orientation self.registerDeviceOrientationNotification() if PreOrientation != .portrait { NotificationCenter.default.post(name: Notification.Name(rawValue: "JHB_HUDTopVcCannotRotated"), object: self.PreOrientation.hashValue, userInfo: nil) } } func setSubViews() { self.bgClearView = UIView.init() self.bgClearView.backgroundColor = UIColor.clear self.coreView = JHB_HUDDiyProgressView.init() self.coreView.sizeToFit() self.coreView.layer.cornerRadius = 10 self.coreView.layer.masksToBounds = true self.coreView.backgroundColor = UIColor.black self.coreView.alpha = 0 self.resetSubViews() } func resetSubViews() { self.bgClearView.frame = CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT) self.coreView.frame = CGRect(x: (SCREEN_WIDTH - 70) / 2, y: (SCREEN_HEIGHT - 70) / 2, width: 70, height: 70) self.coreView.center = CGPoint(x: SCREEN_WIDTH / 2, y: SCREEN_HEIGHT / 2 + 60) } // MARK: - 隐藏(Hidden❤️Type:dissolveToTop) public func hideProgress() {// DEFAULT self.perform(#selector(JHB_HUDDiyManager.hideWithAnimation), with: self, afterDelay: 0.6) } override func hideHud() { self.hideProgress() } override func ifBeMoved(bool: Bool) { let longTap = UILongPressGestureRecognizer.init(target: self, action: #selector(JHB_HUDDiyManager.hideHud)) self.isUserInteractionEnabled = bool self.addGestureRecognizer(longTap) } } extension JHB_HUDDiyManager{ // MARK: - 1⃣️单纯显示DIY进程中(Just Show In DIY-Progress) public func showDIYProgressWithType(_ img:NSString,diySpeed:CFTimeInterval,diyHudType:DiyHUDType, HudType:HUDType,ifCustom:Bool,to:UIView) { self.coreView.diyShowImage = img self.coreView.diySpeed = diySpeed self.coreView.diyHudType = diyHudType.hashValue self.type = HudType.hashValue self.showDIYProgressWithHUDType(HudType,ifCustom:ifCustom,to:to) } // MARK: - 2⃣️单纯显示DIY进程中(Just Show In DIY-Progress:❤️播放图片数组) public func showDIYProgressAnimated(_ imgsName:NSString,imgsNumber:NSInteger,diySpeed:TimeInterval, HudType:HUDType,ifCustom:Bool,to:UIView){ self.coreView.diyShowImage = imgsName self.coreView.diyImgsNumber = imgsNumber self.coreView.diySpeed = diySpeed self.type = HudType.hashValue self.showDIYProgressWithHUDType(HudType,ifCustom:ifCustom,to:to) } fileprivate func showDIYProgressWithHUDType(_ HudType:HUDType,ifCustom:Bool,to:UIView) { switch HudType { case .kHUDTypeDefaultly: self.EffectShowProgressAboutTopAndBottom(.kHUDTypeShowFromBottomToTop,ifCustom:ifCustom,to:to) case .kHUDTypeShowImmediately: self.EffectShowProgressAboutStablePositon(.kHUDTypeShowImmediately,ifCustom:ifCustom,to:to) case .kHUDTypeShowSlightly: self.EffectShowProgressAboutStablePositon(.kHUDTypeShowSlightly,ifCustom:ifCustom,to:to) case .kHUDTypeShowFromBottomToTop: self.EffectShowProgressAboutTopAndBottom(.kHUDTypeShowFromBottomToTop,ifCustom:ifCustom,to:to) case .kHUDTypeShowFromTopToBottom: self.EffectShowProgressAboutTopAndBottom(.kHUDTypeShowFromTopToBottom,ifCustom:ifCustom,to:to) case .kHUDTypeShowFromLeftToRight: self.EffectShowProgressAboutLeftAndRight(.kHUDTypeShowFromLeftToRight,ifCustom:ifCustom,to:to) case .kHUDTypeShowFromRightToLeft: self.EffectShowProgressAboutLeftAndRight(.kHUDTypeShowFromRightToLeft,ifCustom:ifCustom,to:to) case .kHUDTypeScaleFromInsideToOutside: self.EffectShowProgressAboutInsideAndOutside(.kHUDTypeScaleFromInsideToOutside,ifCustom:ifCustom,to:to) case .kHUDTypeScaleFromOutsideToInside: self.EffectShowProgressAboutInsideAndOutside(.kHUDTypeScaleFromOutsideToInside,ifCustom:ifCustom,to:to) } } // 1⃣️原位置不变化 fileprivate func EffectShowProgressAboutStablePositon(_ type:HUDType,ifCustom:Bool,to:UIView) { var kIfNeedEffect : Bool = false switch type { case .kHUDTypeShowImmediately: kIfNeedEffect = false self.coreView.alpha = 1 break case .kHUDTypeShowSlightly: kIfNeedEffect = true self.coreView.alpha = 0 break default: break } NotificationCenter.default.post(name: Notification.Name(rawValue: "JHB_DIYHUD_haveNoMsg"), object: nil) /*重写位置*/ self.coreView.diyMsgLabel.isHidden = true self.coreView.frame = CGRect(x: (SCREEN_WIDTH - 80) / 2, y: (SCREEN_HEIGHT - 80) / 2, width: 80, height: 80) self.coreView.center = CGPoint(x: SCREEN_WIDTH / 2, y: SCREEN_HEIGHT / 2 ) ifCustom == true ? self.addTo(to: to):self.ResetWindowPosition() if kIfNeedEffect == false { }else if kIfNeedEffect == true { /*实现动画*/ UIView.animate(withDuration: 0.65, animations: { self.coreView.alpha = 1 self.coreView.center = CGPoint(x: UIScreen.main.bounds.size.width / 2, y: UIScreen.main.bounds.size.height / 2) }) } } // 2⃣️上下相关 fileprivate func EffectShowProgressAboutTopAndBottom(_ type:HUDType,ifCustom:Bool,to:UIView) { var value : CGFloat = 0 switch type { case .kHUDTypeShowFromBottomToTop: value = -60 break case .kHUDTypeShowFromTopToBottom: value = 60 break default: break } NotificationCenter.default.post(name: Notification.Name(rawValue: "JHB_DIYHUD_haveNoMsg"), object: nil) /*重写位置*/ self.coreView.diyMsgLabel.isHidden = true self.coreView.frame = CGRect(x: (SCREEN_WIDTH - 80) / 2, y: (SCREEN_HEIGHT - 80) / 2, width: 80, height: 80) self.coreView.center = CGPoint(x: SCREEN_WIDTH / 2, y: SCREEN_HEIGHT / 2 - value) ifCustom == true ? self.addTo(to: to):self.ResetWindowPosition() /*实现动画*/ UIView.animate(withDuration: 0.65, animations: { self.coreView.alpha = 1 self.coreView.center = CGPoint(x: UIScreen.main.bounds.size.width / 2, y: UIScreen.main.bounds.size.height / 2) }) } // 3⃣️左右相关 fileprivate func EffectShowProgressAboutLeftAndRight(_ type:HUDType,ifCustom:Bool,to:UIView){ var value : CGFloat = 0 switch type { case .kHUDTypeShowFromLeftToRight: value = -60 break case .kHUDTypeShowFromRightToLeft: value = 60 break default: break } NotificationCenter.default.post(name: Notification.Name(rawValue: "JHB_DIYHUD_haveNoMsg"), object: nil) /*重写位置*/ self.coreView.diyMsgLabel.isHidden = true self.coreView.frame = CGRect(x: (SCREEN_WIDTH - 80) / 2, y: (SCREEN_HEIGHT - 80) / 2, width: 80, height: 80) self.coreView.center = CGPoint(x: SCREEN_WIDTH / 2 + value, y: SCREEN_HEIGHT / 2) ifCustom == true ? self.addTo(to: to):self.ResetWindowPosition() /*实现动画*/ UIView.animate(withDuration: 0.65, animations: { self.coreView.alpha = 1 self.coreView.center = CGPoint(x: UIScreen.main.bounds.size.width / 2, y: UIScreen.main.bounds.size.height / 2) }) } // 4⃣️内外相关 fileprivate func EffectShowProgressAboutInsideAndOutside(_ type:HUDType,ifCustom:Bool,to:UIView){ var kInitValue : CGFloat = 0 var kScaleValue : CGFloat = 0 switch type { case .kHUDTypeScaleFromInsideToOutside: kInitValue = 85 kScaleValue = 1.28 break case .kHUDTypeScaleFromOutsideToInside: kInitValue = 130 kScaleValue = 0.85 break default: break } NotificationCenter.default.post(name: Notification.Name(rawValue: "JHB_DIYHUD_haveNoMsgWithScale"), object: kScaleValue) /*重写位置*/ self.coreView.diyMsgLabel.isHidden = true self.coreView.frame = CGRect(x: (SCREEN_WIDTH - kInitValue) / 2, y: (SCREEN_HEIGHT - kInitValue) / 2, width: kInitValue, height: kInitValue) self.coreView.center = CGPoint(x: SCREEN_WIDTH / 2, y: SCREEN_HEIGHT / 2) ifCustom == true ? self.addTo(to: to):self.ResetWindowPosition() /*实现动画*/ UIView.animate(withDuration: 0.65, animations: { self.coreView.alpha = 1 self.coreView.transform = self.coreView.transform.scaledBy(x: kScaleValue,y: kScaleValue) }) } // MARK: - 3⃣️显示DIY进程及文字(Show DIY-InProgress-Status And The Words-Message) public func showDIYProgressMsgsWithType(_ msgs:NSString,img:NSString,diySpeed:CFTimeInterval,diyHudType:DiyHUDType, HudType:HUDType,ifCustom:Bool,to:UIView) {// NEW self.coreView.diySpeed = diySpeed self.coreView.diyHudType = diyHudType.hashValue self.coreView.diyShowImage = img self.type = HudType.hashValue self.showDIYProgressMsgsWithHUDType(msgs, HudType: HudType,ifCustom:ifCustom,to:to) } // MARK: - 4⃣️显示DIY进程及文字(Show DIY-InProgress-Status And The Words-Message❤️播放图片数组) public func showDIYProgressMsgsAnimated(_ msgs:NSString,imgsName:NSString,imgsNumber:NSInteger,diySpeed:TimeInterval, HudType:HUDType,ifCustom:Bool,to:UIView) {// NEW self.coreView.diyShowImage = imgsName self.coreView.diyImgsNumber = imgsNumber self.coreView.diySpeed = diySpeed self.type = HudType.hashValue self.showDIYProgressMsgsWithHUDType(msgs, HudType: HudType,ifCustom:ifCustom,to:to) } fileprivate func showDIYProgressMsgsWithHUDType(_ msgs:NSString,HudType:HUDType,ifCustom:Bool,to:UIView) { switch HudType { case .kHUDTypeDefaultly: self.EffectShowProgressMsgsAboutTopAndBottom(msgs,type: .kHUDTypeShowFromBottomToTop,ifCustom:ifCustom,to:to) case .kHUDTypeShowImmediately: self.EffectShowProgressMsgsAboutStablePosition(msgs, type: .kHUDTypeShowImmediately,ifCustom:ifCustom,to:to) case .kHUDTypeShowSlightly: self.EffectShowProgressMsgsAboutStablePosition(msgs, type: .kHUDTypeShowSlightly,ifCustom:ifCustom,to:to) case .kHUDTypeShowFromBottomToTop: self.EffectShowProgressMsgsAboutTopAndBottom(msgs,type: .kHUDTypeShowFromBottomToTop,ifCustom:ifCustom,to:to) case .kHUDTypeShowFromTopToBottom: self.EffectShowProgressMsgsAboutTopAndBottom(msgs,type:.kHUDTypeShowFromTopToBottom,ifCustom:ifCustom,to:to) case .kHUDTypeShowFromLeftToRight: self.EffectShowProgressMsgsAboutLeftAndRight(msgs, type: .kHUDTypeShowFromLeftToRight,ifCustom:ifCustom,to:to) case .kHUDTypeShowFromRightToLeft: self.EffectShowProgressMsgsAboutLeftAndRight(msgs, type: .kHUDTypeShowFromRightToLeft,ifCustom:ifCustom,to:to) case .kHUDTypeScaleFromInsideToOutside: self.EffectShowProgressMsgsAboutInsideAndOutside(msgs, type: .kHUDTypeScaleFromInsideToOutside,ifCustom:ifCustom,to:to) case .kHUDTypeScaleFromOutsideToInside: self.EffectShowProgressMsgsAboutInsideAndOutside(msgs, type: .kHUDTypeScaleFromOutsideToInside,ifCustom:ifCustom,to:to) } } // 1⃣️原位置不变 fileprivate func EffectShowProgressMsgsAboutStablePosition(_ msgs:NSString,type:HUDType,ifCustom:Bool,to:UIView) { switch type { case .kHUDTypeShowImmediately: self.coreView.alpha = 1 break case .kHUDTypeShowSlightly: self.coreView.alpha = 0 break default: break } coreViewRect = msgs.boundingRect(with: CGSize(width: self.coreView.diyMsgLabel.bounds.width, height: 1000), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [ NSFontAttributeName:UIFont.systemFont(ofSize: 15.0) ], context: nil) var msgLabelWidth = coreViewRect.width if msgLabelWidth + 2*kMargin >= (SCREEN_WIDTH - 30) { msgLabelWidth = SCREEN_WIDTH - 30 - 2*kMargin }else if msgLabelWidth + 2*kMargin <= 80 { msgLabelWidth = 80 } NotificationCenter.default.post(name: Notification.Name(rawValue: "JHB_DIYHUD_haveMsg"), object: nil) self.coreView.frame = CGRect(x: (SCREEN_WIDTH - msgLabelWidth) / 2, y: (SCREEN_HEIGHT - 80) / 2,width: msgLabelWidth + 2*kMargin , height: 105) self.coreView.center = CGPoint(x: SCREEN_WIDTH / 2, y: SCREEN_HEIGHT / 2) ifCustom == true ? self.addTo(to: to):self.ResetWindowPosition() UIView.animate(withDuration: 0.65, animations: { self.coreView.alpha = 1 self.coreView.center = CGPoint(x: UIScreen.main.bounds.size.width / 2, y: UIScreen.main.bounds.size.height / 2) self.setNeedsDisplay() }) self.coreView.diyMsgLabelWidth = msgLabelWidth self.coreView.diyMsgLabel.text = msgs as String } // 2⃣️上下相关 fileprivate func EffectShowProgressMsgsAboutTopAndBottom(_ msgs:NSString,type:HUDType,ifCustom:Bool,to:UIView){ var value : CGFloat = 0 switch type { case .kHUDTypeShowFromBottomToTop: value = 60 break case .kHUDTypeShowFromTopToBottom: value = -60 break default: break } coreViewRect = msgs.boundingRect(with: CGSize(width: self.coreView.diyMsgLabel.bounds.width, height: 1000), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [ NSFontAttributeName:UIFont.systemFont(ofSize: 15.0) ], context: nil) var msgLabelWidth = coreViewRect.width if msgLabelWidth + 2*kMargin >= (SCREEN_WIDTH - 30) { msgLabelWidth = SCREEN_WIDTH - 30 - 2*kMargin }else if msgLabelWidth + 2*kMargin <= 80 { msgLabelWidth = 80 } self.coreView.diyMsgLabelWidth = msgLabelWidth + 20 self.coreView.diyMsgLabel.text = msgs as String NotificationCenter.default.post(name: Notification.Name(rawValue: "JHB_DIYHUD_haveMsg"), object: nil) self.coreView.frame = CGRect(x: (SCREEN_WIDTH - msgLabelWidth) / 2, y: (SCREEN_HEIGHT - 80) / 2,width: msgLabelWidth + 2*kMargin , height: 105) self.coreView.center = CGPoint(x: SCREEN_WIDTH / 2, y: SCREEN_HEIGHT / 2 + value) ifCustom == true ? self.addTo(to: to):self.ResetWindowPosition() UIView.animate(withDuration: 0.65, animations: { self.coreView.alpha = 1 self.coreView.center = CGPoint(x: UIScreen.main.bounds.size.width / 2, y: UIScreen.main.bounds.size.height / 2) self.setNeedsDisplay() }) } // 3⃣️左右相关 fileprivate func EffectShowProgressMsgsAboutLeftAndRight(_ msgs:NSString,type:HUDType,ifCustom:Bool,to:UIView){ var value : CGFloat = 0 switch type { case .kHUDTypeShowFromLeftToRight: value = -60 break case .kHUDTypeShowFromRightToLeft: value = 60 break default: break } coreViewRect = msgs.boundingRect(with: CGSize(width: self.coreView.diyMsgLabel.bounds.width, height: 1000), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [ NSFontAttributeName:UIFont.systemFont(ofSize: 15.0) ], context: nil) var msgLabelWidth = coreViewRect.width if msgLabelWidth + 2*kMargin >= (SCREEN_WIDTH - 30) { msgLabelWidth = SCREEN_WIDTH - 30 - 2*kMargin }else if msgLabelWidth + 2*kMargin <= 80 { msgLabelWidth = 80 } self.coreView.diyMsgLabelWidth = msgLabelWidth + 20 self.coreView.diyMsgLabel.text = msgs as String NotificationCenter.default.post(name: Notification.Name(rawValue: "JHB_DIYHUD_haveMsg"), object: nil) self.coreView.frame = CGRect(x: (SCREEN_WIDTH - msgLabelWidth) / 2, y: (SCREEN_HEIGHT - 80) / 2,width: msgLabelWidth + 2*kMargin , height: 105) self.coreView.center = CGPoint(x: SCREEN_WIDTH / 2 + value, y: SCREEN_HEIGHT / 2) ifCustom == true ? self.addTo(to: to):self.ResetWindowPosition() UIView.animate(withDuration: 0.65, animations: { self.coreView.alpha = 1 self.coreView.center = CGPoint(x: UIScreen.main.bounds.size.width / 2, y: UIScreen.main.bounds.size.height / 2) self.setNeedsDisplay() }) } // 4⃣️内外相关 fileprivate func EffectShowProgressMsgsAboutInsideAndOutside(_ msgs:NSString,type:HUDType,ifCustom:Bool,to:UIView){ coreViewRect = msgs.boundingRect(with: CGSize(width: self.coreView.diyMsgLabel.bounds.width, height: 1000), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [ NSFontAttributeName:UIFont.systemFont(ofSize: 15.0) ], context: nil) var msgLabelWidth = coreViewRect.width if msgLabelWidth + 2*kMargin >= (SCREEN_WIDTH - 30) { msgLabelWidth = SCREEN_WIDTH - 30 - 2*kMargin }else if msgLabelWidth + 2*kMargin <= 80 { msgLabelWidth = 80 } let CoreWidth = msgLabelWidth + 2*kMargin var iniWidthValue : CGFloat = 0 var iniHeightValue : CGFloat = 0 var kScaleValue : CGFloat = 0 switch type { case .kHUDTypeScaleFromInsideToOutside: kScaleValue = 1.05 iniWidthValue = (CoreWidth + 10)/kScaleValue iniHeightValue = 105/kScaleValue break case .kHUDTypeScaleFromOutsideToInside: kScaleValue = 0.90 iniWidthValue = CoreWidth/kScaleValue iniHeightValue = 105/kScaleValue break default: break } self.coreView.diyMsgLabelWidth = iniWidthValue self.coreView.diyMsgLabel.text = msgs as String NotificationCenter.default.post(name: Notification.Name(rawValue: "JHB_DIYHUD_haveMsg_WithScale"), object: kScaleValue) self.coreView.frame = CGRect(x: (SCREEN_WIDTH - msgLabelWidth) / 2, y: (SCREEN_HEIGHT - iniHeightValue) / 2,width: iniWidthValue , height: iniHeightValue) self.coreView.center = CGPoint(x: SCREEN_WIDTH / 2, y: SCREEN_HEIGHT / 2) ifCustom == true ? self.addTo(to: to):self.ResetWindowPosition() UIView.animate(withDuration: 0.65, animations: { self.coreView.alpha = 1 self.coreView.transform = self.coreView.transform.scaledBy(x: kScaleValue,y: kScaleValue) self.coreView.center = CGPoint(x: UIScreen.main.bounds.size.width / 2, y: UIScreen.main.bounds.size.height / 2) self.setNeedsDisplay() }) } // MARK: - Self-Method Without Ask @objc fileprivate func hideWithAnimation() { switch self.type { case HUDType.kHUDTypeDefaultly.hashValue: // ❤️默认类型 self.EffectRemoveAboutBottomAndTop(.kHUDTypeShowFromBottomToTop) break case HUDType.kHUDTypeShowImmediately.hashValue: self.EffectRemoveAboutStablePositon(.kHUDTypeShowImmediately) break case HUDType.kHUDTypeShowSlightly.hashValue: self.EffectRemoveAboutStablePositon(.kHUDTypeShowSlightly) break case HUDType.kHUDTypeShowFromBottomToTop.hashValue: self.EffectRemoveAboutBottomAndTop(.kHUDTypeShowFromBottomToTop) break case HUDType.kHUDTypeShowFromTopToBottom.hashValue: self.EffectRemoveAboutBottomAndTop(.kHUDTypeShowFromTopToBottom) break case HUDType.kHUDTypeShowFromLeftToRight.hashValue: self.EffectRemoveAboutLeftAndRight(.kHUDTypeShowFromLeftToRight) break case HUDType.kHUDTypeShowFromRightToLeft.hashValue: self.EffectRemoveAboutLeftAndRight(.kHUDTypeShowFromRightToLeft) break case HUDType.kHUDTypeScaleFromInsideToOutside.hashValue: self.EffectRemoveAboutInsideAndOutside(.kHUDTypeScaleFromInsideToOutside) break case HUDType.kHUDTypeScaleFromOutsideToInside.hashValue: self.EffectRemoveAboutInsideAndOutside(.kHUDTypeScaleFromOutsideToInside) break default: break } } // 1⃣️原位置不变 func EffectRemoveAboutStablePositon(_ HudType:HUDType) { var kIfNeedEffect : Bool = false switch HudType { case .kHUDTypeShowImmediately: kIfNeedEffect = false break case .kHUDTypeShowSlightly: kIfNeedEffect = true break default: break } if kIfNeedEffect == false { self.SuperInitStatus() }else if kIfNeedEffect == true { UIView.animate(withDuration: 0.65, animations: { self.coreView.alpha = 0 self.coreView.center = CGPoint(x: self.bgClearView.bounds.size.width / 2, y: self.bgClearView.bounds.size.height / 2) }, completion: { (true) in self.SuperInitStatus() }) } } // 2⃣️上下相关 func EffectRemoveAboutBottomAndTop(_ HudType:HUDType) { var value : CGFloat = 0 switch HudType { case .kHUDTypeShowFromBottomToTop: value = -60 break case .kHUDTypeShowFromTopToBottom: value = 60 break default: break } UIView.animate(withDuration: 0.65, animations: { self.coreView.alpha = 0 self.coreView.center = CGPoint(x: self.bgClearView.bounds.size.width / 2, y: self.bgClearView.bounds.size.height / 2 + value) }, completion: { (true) in self.SuperInitStatus() }) } // 3⃣️左右相关 func EffectRemoveAboutLeftAndRight(_ HudType:HUDType) { var value : CGFloat = 0 switch HudType { case .kHUDTypeShowFromLeftToRight: value = 60 break case .kHUDTypeShowFromRightToLeft: value = -60 break default: break } UIView.animate(withDuration: 0.65, animations: { self.coreView.alpha = 0 self.coreView.center = CGPoint(x: self.bgClearView.bounds.size.width / 2 + value, y: self.bgClearView.bounds.size.height / 2) }, completion: { (true) in self.SuperInitStatus() }) } // 4⃣️内外相关 func EffectRemoveAboutInsideAndOutside(_ HudType:HUDType) { var kScaleValue : CGFloat = 0 switch HudType { case .kHUDTypeScaleFromInsideToOutside: kScaleValue = 1.78 break case .kHUDTypeScaleFromOutsideToInside: kScaleValue = 0.67 break default: break } UIView.animate(withDuration: 0.65, animations: { self.coreView.alpha = 0 self.coreView.transform = self.coreView.transform.scaledBy(x: 1/kScaleValue,y: 1/kScaleValue) self.coreView.center = CGPoint(x: self.bgClearView.bounds.size.width / 2, y: self.bgClearView.bounds.size.height / 2) }, completion: { (true) in self.SuperInitStatus() }) } /// public func addTo(to:UIView) { self.frame = to.frame self.center = to.center to.addSubview(self) } }
137975a5c19f2bc2991b243da69268e8
40.968386
185
0.62784
false
false
false
false
apple/swift-corelibs-foundation
refs/heads/main
Sources/Foundation/NSDateComponents.swift
apache-2.0
1
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // @_implementationOnly import CoreFoundation // This is a just used as an extensible struct, basically; // note that there are two uses: one for specifying a date // via components (some components may be missing, making the // specific date ambiguous), and the other for specifying a // set of component quantities (like, 3 months and 5 hours). // Undefined fields have (or fields can be set to) the value // NSDateComponentUndefined. // NSDateComponents is not responsible for answering questions // about a date beyond the information it has been initialized // with; for example, if you initialize one with May 6, 2004, // and then ask for the weekday, you'll get Undefined, not Thurs. // A NSDateComponents is meaningless in itself, because you need // to know what calendar it is interpreted against, and you need // to know whether the values are absolute values of the units, // or quantities of the units. // When you create a new one of these, all values begin Undefined. public var NSDateComponentUndefined: Int = Int.max open class NSDateComponents: NSObject, NSCopying, NSSecureCoding { internal var _calendar: Calendar? internal var _timeZone: TimeZone? internal var _values = [Int](repeating: NSDateComponentUndefined, count: 19) public override init() { super.init() } open override var hash: Int { var hasher = Hasher() var mask = 0 // The list of fields fed to the hasher here must be exactly // the same as the ones compared in isEqual(_:) (modulo // ordering). // // Given that NSDateComponents instances usually only have a // few fields present, it makes sense to only hash those, as // an optimization. We keep track of the fields hashed in the // mask value, which we also feed to the hasher to make sure // any two unequal values produce different hash encodings. // // FIXME: Why not just feed _values, calendar & timeZone to // the hasher? if let calendar = calendar { hasher.combine(calendar) mask |= 1 << 0 } if let timeZone = timeZone { hasher.combine(timeZone) mask |= 1 << 1 } if era != NSDateComponentUndefined { hasher.combine(era) mask |= 1 << 2 } if year != NSDateComponentUndefined { hasher.combine(year) mask |= 1 << 3 } if quarter != NSDateComponentUndefined { hasher.combine(quarter) mask |= 1 << 4 } if month != NSDateComponentUndefined { hasher.combine(month) mask |= 1 << 5 } if day != NSDateComponentUndefined { hasher.combine(day) mask |= 1 << 6 } if hour != NSDateComponentUndefined { hasher.combine(hour) mask |= 1 << 7 } if minute != NSDateComponentUndefined { hasher.combine(minute) mask |= 1 << 8 } if second != NSDateComponentUndefined { hasher.combine(second) mask |= 1 << 9 } if nanosecond != NSDateComponentUndefined { hasher.combine(nanosecond) mask |= 1 << 10 } if weekOfYear != NSDateComponentUndefined { hasher.combine(weekOfYear) mask |= 1 << 11 } if weekOfMonth != NSDateComponentUndefined { hasher.combine(weekOfMonth) mask |= 1 << 12 } if yearForWeekOfYear != NSDateComponentUndefined { hasher.combine(yearForWeekOfYear) mask |= 1 << 13 } if weekday != NSDateComponentUndefined { hasher.combine(weekday) mask |= 1 << 14 } if weekdayOrdinal != NSDateComponentUndefined { hasher.combine(weekdayOrdinal) mask |= 1 << 15 } hasher.combine(isLeapMonth) hasher.combine(mask) return hasher.finalize() } open override func isEqual(_ object: Any?) -> Bool { guard let other = object as? NSDateComponents else { return false } // FIXME: Why not just compare _values, calendar & timeZone? return self === other || (era == other.era && year == other.year && quarter == other.quarter && month == other.month && day == other.day && hour == other.hour && minute == other.minute && second == other.second && nanosecond == other.nanosecond && weekOfYear == other.weekOfYear && weekOfMonth == other.weekOfMonth && yearForWeekOfYear == other.yearForWeekOfYear && weekday == other.weekday && weekdayOrdinal == other.weekdayOrdinal && isLeapMonth == other.isLeapMonth && calendar == other.calendar && timeZone == other.timeZone) } public convenience required init?(coder aDecoder: NSCoder) { guard aDecoder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } self.init() self.era = aDecoder.decodeInteger(forKey: "NS.era") self.year = aDecoder.decodeInteger(forKey: "NS.year") self.quarter = aDecoder.decodeInteger(forKey: "NS.quarter") self.month = aDecoder.decodeInteger(forKey: "NS.month") self.day = aDecoder.decodeInteger(forKey: "NS.day") self.hour = aDecoder.decodeInteger(forKey: "NS.hour") self.minute = aDecoder.decodeInteger(forKey: "NS.minute") self.second = aDecoder.decodeInteger(forKey: "NS.second") self.nanosecond = aDecoder.decodeInteger(forKey: "NS.nanosec") self.weekOfYear = aDecoder.decodeInteger(forKey: "NS.weekOfYear") self.weekOfMonth = aDecoder.decodeInteger(forKey: "NS.weekOfMonth") self.yearForWeekOfYear = aDecoder.decodeInteger(forKey: "NS.yearForWOY") self.weekday = aDecoder.decodeInteger(forKey: "NS.weekday") self.weekdayOrdinal = aDecoder.decodeInteger(forKey: "NS.weekdayOrdinal") self.isLeapMonth = aDecoder.decodeBool(forKey: "NS.isLeapMonth") self.calendar = aDecoder.decodeObject(of: NSCalendar.self, forKey: "NS.calendar")?._swiftObject self.timeZone = aDecoder.decodeObject(of: NSTimeZone.self, forKey: "NS.timezone")?._swiftObject } open func encode(with aCoder: NSCoder) { guard aCoder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } aCoder.encode(self.era, forKey: "NS.era") aCoder.encode(self.year, forKey: "NS.year") aCoder.encode(self.quarter, forKey: "NS.quarter") aCoder.encode(self.month, forKey: "NS.month") aCoder.encode(self.day, forKey: "NS.day") aCoder.encode(self.hour, forKey: "NS.hour") aCoder.encode(self.minute, forKey: "NS.minute") aCoder.encode(self.second, forKey: "NS.second") aCoder.encode(self.nanosecond, forKey: "NS.nanosec") aCoder.encode(self.weekOfYear, forKey: "NS.weekOfYear") aCoder.encode(self.weekOfMonth, forKey: "NS.weekOfMonth") aCoder.encode(self.yearForWeekOfYear, forKey: "NS.yearForWOY") aCoder.encode(self.weekday, forKey: "NS.weekday") aCoder.encode(self.weekdayOrdinal, forKey: "NS.weekdayOrdinal") aCoder.encode(self.isLeapMonth, forKey: "NS.isLeapMonth") aCoder.encode(self.calendar?._nsObject, forKey: "NS.calendar") aCoder.encode(self.timeZone?._nsObject, forKey: "NS.timezone") } static public var supportsSecureCoding: Bool { return true } open override func copy() -> Any { return copy(with: nil) } open func copy(with zone: NSZone? = nil) -> Any { let newObj = NSDateComponents() newObj.calendar = calendar newObj.timeZone = timeZone newObj.era = era newObj.year = year newObj.month = month newObj.day = day newObj.hour = hour newObj.minute = minute newObj.second = second newObj.nanosecond = nanosecond newObj.weekOfYear = weekOfYear newObj.weekOfMonth = weekOfMonth newObj.yearForWeekOfYear = yearForWeekOfYear newObj.weekday = weekday newObj.weekdayOrdinal = weekdayOrdinal newObj.quarter = quarter if leapMonthSet { newObj.isLeapMonth = isLeapMonth } return newObj } /*@NSCopying*/ open var calendar: Calendar? { get { return _calendar } set { if let val = newValue { _calendar = val } else { _calendar = nil } } } /*@NSCopying*/ open var timeZone: TimeZone? open var era: Int { get { return _values[0] } set { _values[0] = newValue } } open var year: Int { get { return _values[1] } set { _values[1] = newValue } } open var month: Int { get { return _values[2] } set { _values[2] = newValue } } open var day: Int { get { return _values[3] } set { _values[3] = newValue } } open var hour: Int { get { return _values[4] } set { _values[4] = newValue } } open var minute: Int { get { return _values[5] } set { _values[5] = newValue } } open var second: Int { get { return _values[6] } set { _values[6] = newValue } } open var weekday: Int { get { return _values[8] } set { _values[8] = newValue } } open var weekdayOrdinal: Int { get { return _values[9] } set { _values[9] = newValue } } open var quarter: Int { get { return _values[10] } set { _values[10] = newValue } } open var nanosecond: Int { get { return _values[11] } set { _values[11] = newValue } } open var weekOfYear: Int { get { return _values[12] } set { _values[12] = newValue } } open var weekOfMonth: Int { get { return _values[13] } set { _values[13] = newValue } } open var yearForWeekOfYear: Int { get { return _values[14] } set { _values[14] = newValue } } open var isLeapMonth: Bool { get { return _values[15] == 1 } set { _values[15] = newValue ? 1 : 0 } } internal var leapMonthSet: Bool { return _values[15] != NSDateComponentUndefined } /*@NSCopying*/ open var date: Date? { if let tz = timeZone { calendar?.timeZone = tz } return calendar?.date(from: self._swiftObject) } /* This API allows one to set a specific component of NSDateComponents, by enum constant value rather than property name. The calendar and timeZone and isLeapMonth properties cannot be set by this method. */ open func setValue(_ value: Int, forComponent unit: NSCalendar.Unit) { switch unit { case .era: era = value case .year: year = value case .month: month = value case .day: day = value case .hour: hour = value case .minute: minute = value case .second: second = value case .nanosecond: nanosecond = value case .weekday: weekday = value case .weekdayOrdinal: weekdayOrdinal = value case .quarter: quarter = value case .weekOfMonth: weekOfMonth = value case .weekOfYear: weekOfYear = value case .yearForWeekOfYear: yearForWeekOfYear = value case .calendar: print(".Calendar cannot be set via \(#function)") case .timeZone: print(".TimeZone cannot be set via \(#function)") default: break } } /* This API allows one to get the value of a specific component of NSDateComponents, by enum constant value rather than property name. The calendar and timeZone and isLeapMonth property values cannot be gotten by this method. */ open func value(forComponent unit: NSCalendar.Unit) -> Int { switch unit { case .era: return era case .year: return year case .month: return month case .day: return day case .hour: return hour case .minute: return minute case .second: return second case .nanosecond: return nanosecond case .weekday: return weekday case .weekdayOrdinal: return weekdayOrdinal case .quarter: return quarter case .weekOfMonth: return weekOfMonth case .weekOfYear: return weekOfYear case .yearForWeekOfYear: return yearForWeekOfYear default: break } return NSDateComponentUndefined } /* Reports whether or not the combination of properties which have been set in the receiver is a date which exists in the calendar. This method is not appropriate for use on NSDateComponents objects which are specifying relative quantities of calendar components. Except for some trivial cases (e.g., 'seconds' should be 0 - 59 in any calendar), this method is not necessarily cheap. If the time zone property is set in the NSDateComponents object, it is used. The calendar property must be set, or NO is returned. */ open var isValidDate: Bool { if let cal = calendar { return isValidDate(in: cal) } return false } /* Reports whether or not the combination of properties which have been set in the receiver is a date which exists in the calendar. This method is not appropriate for use on NSDateComponents objects which are specifying relative quantities of calendar components. Except for some trivial cases (e.g., 'seconds' should be 0 - 59 in any calendar), this method is not necessarily cheap. If the time zone property is set in the NSDateComponents object, it is used. */ open func isValidDate(in calendar: Calendar) -> Bool { var cal = calendar if let tz = timeZone { cal.timeZone = tz } let ns = nanosecond if ns != NSDateComponentUndefined && 1000 * 1000 * 1000 <= ns { return false } if ns != NSDateComponentUndefined && 0 < ns { nanosecond = 0 } let d = calendar.date(from: self._swiftObject) if ns != NSDateComponentUndefined && 0 < ns { nanosecond = ns } if let date = d { let all: NSCalendar.Unit = [.era, .year, .month, .day, .hour, .minute, .second, .weekday, .weekdayOrdinal, .quarter, .weekOfMonth, .weekOfYear, .yearForWeekOfYear] let comps = cal._bridgeToObjectiveC().components(all, from: date) var val = era if val != NSDateComponentUndefined { if comps.era != val { return false } } val = year if val != NSDateComponentUndefined { if comps.year != val { return false } } val = month if val != NSDateComponentUndefined { if comps.month != val { return false } } if leapMonthSet { if comps.isLeapMonth != isLeapMonth { return false } } val = day if val != NSDateComponentUndefined { if comps.day != val { return false } } val = hour if val != NSDateComponentUndefined { if comps.hour != val { return false } } val = minute if val != NSDateComponentUndefined { if comps.minute != val { return false } } val = second if val != NSDateComponentUndefined { if comps.second != val { return false } } val = weekday if val != NSDateComponentUndefined { if comps.weekday != val { return false } } val = weekdayOrdinal if val != NSDateComponentUndefined { if comps.weekdayOrdinal != val { return false } } val = quarter if val != NSDateComponentUndefined { if comps.quarter != val { return false } } val = weekOfMonth if val != NSDateComponentUndefined { if comps.weekOfMonth != val { return false } } val = weekOfYear if val != NSDateComponentUndefined { if comps.weekOfYear != val { return false } } val = yearForWeekOfYear if val != NSDateComponentUndefined { if comps.yearForWeekOfYear != val { return false } } return true } return false } } extension NSDateComponents: _SwiftBridgeable { typealias SwiftType = DateComponents var _swiftObject: SwiftType { return DateComponents(reference: self) } } extension NSDateComponents: _StructTypeBridgeable { public typealias _StructType = DateComponents public func _bridgeToSwift() -> DateComponents { return DateComponents._unconditionallyBridgeFromObjectiveC(self) } } extension NSDateComponents { func _createCFDateComponents() -> CFDateComponents { let components = CFDateComponentsCreate(kCFAllocatorSystemDefault)! CFDateComponentsSetValue(components, kCFCalendarUnitEra, era) CFDateComponentsSetValue(components, kCFCalendarUnitYear, year) CFDateComponentsSetValue(components, kCFCalendarUnitMonth, month) CFDateComponentsSetValue(components, kCFCalendarUnitDay, day) CFDateComponentsSetValue(components, kCFCalendarUnitHour, hour) CFDateComponentsSetValue(components, kCFCalendarUnitMinute, minute) CFDateComponentsSetValue(components, kCFCalendarUnitSecond, second) CFDateComponentsSetValue(components, kCFCalendarUnitWeekday, weekday) CFDateComponentsSetValue(components, kCFCalendarUnitWeekdayOrdinal, weekdayOrdinal) CFDateComponentsSetValue(components, kCFCalendarUnitQuarter, quarter) CFDateComponentsSetValue(components, kCFCalendarUnitWeekOfMonth, weekOfMonth) CFDateComponentsSetValue(components, kCFCalendarUnitWeekOfYear, weekOfYear) CFDateComponentsSetValue(components, kCFCalendarUnitYearForWeekOfYear, yearForWeekOfYear) CFDateComponentsSetValue(components, kCFCalendarUnitNanosecond, nanosecond) return components } }
970a0ec8e34c1249969cdef18c074fc3
31.897314
175
0.553448
false
false
false
false
dreamsxin/swift
refs/heads/master
test/SILGen/specialize_attr.swift
apache-2.0
3
// RUN: %target-swift-frontend -emit-silgen -emit-verbose-sil %s | FileCheck %s // CHECK-LABEL: @_specialize(Int, Float) // CHECK-NEXT: func specializeThis<T, U>(_ t: T, u: U) @_specialize(Int, Float) func specializeThis<T, U>(_ t: T, u: U) {} public protocol PP { associatedtype PElt } public protocol QQ { associatedtype QElt } public struct RR : PP { public typealias PElt = Float } public struct SS : QQ { public typealias QElt = Int } public struct GG<T : PP> {} // CHECK-LABEL: public class CC<T : PP> { // CHECK-NEXT: @_specialize(RR, SS) // CHECK-NEXT: @inline(never) public func foo<U : QQ>(_ u: U, g: GG<T>) -> (U, GG<T>) public class CC<T : PP> { @inline(never) @_specialize(RR, SS) public func foo<U : QQ>(_ u: U, g: GG<T>) -> (U, GG<T>) { return (u, g) } } // CHECK-LABEL: sil hidden [_specialize <Int, Float>] @_TF15specialize_attr14specializeThisu0_rFTx1uq__T_ : $@convention(thin) <T, U> (@in T, @in U) -> () { // CHECK-LABEL: sil [noinline] [_specialize <RR, Float, SS, Int>] @_TFC15specialize_attr2CC3foouRd__S_2QQrfTqd__1gGVS_2GGx__Tqd__GS2_x__ : $@convention(method) <T where T : PP><U where U : QQ> (@in U, GG<T>, @guaranteed CC<T>) -> (@out U, GG<T>) { // ----------------------------------------------------------------------------- // Test user-specialized subscript accessors. public protocol TestSubscriptable { associatedtype Element subscript(i: Int) -> Element { get set } } public class ASubscriptable<Element> : TestSubscriptable { var storage: UnsafeMutablePointer<Element> init(capacity: Int) { storage = UnsafeMutablePointer<Element>(allocatingCapacity: capacity) } public subscript(i: Int) -> Element { @_specialize(Int) get { return storage[i] } @_specialize(Int) set(rhs) { storage[i] = rhs } } } // ASubscriptable.subscript.getter with _specialize // CHECK-LABEL: sil [_specialize <Int>] @_TFC15specialize_attr14ASubscriptableg9subscriptFSix : $@convention(method) <Element> (Int, @guaranteed ASubscriptable<Element>) -> @out Element { // ASubscriptable.subscript.setter with _specialize // CHECK-LABEL: sil [_specialize <Int>] @_TFC15specialize_attr14ASubscriptables9subscriptFSix : $@convention(method) <Element> (@in Element, Int, @guaranteed ASubscriptable<Element>) -> () { // ASubscriptable.subscript.materializeForSet with no attribute // CHECK-LABEL: sil [transparent] [fragile] @_TFC15specialize_attr14ASubscriptablem9subscriptFSix : $@convention(method) <Element> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, Int, @guaranteed ASubscriptable<Element>) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) { public class Addressable<Element> : TestSubscriptable { var storage: UnsafeMutablePointer<Element> init(capacity: Int) { storage = UnsafeMutablePointer<Element>(allocatingCapacity: capacity) } public subscript(i: Int) -> Element { @_specialize(Int) unsafeAddress { return UnsafePointer<Element>(storage + i) } @_specialize(Int) unsafeMutableAddress { return UnsafeMutablePointer<Element>(storage + i) } } } // Addressable.subscript.unsafeAddressor with _specialize // CHECK-LABEL: sil [_specialize <Int>] @_TFC15specialize_attr11Addressablelu9subscriptFSix : $@convention(method) <Element> (Int, @guaranteed Addressable<Element>) -> UnsafePointer<Element> { // Addressable.subscript.unsafeMutableAddressor with _specialize // CHECK-LABEL: sil [_specialize <Int>] @_TFC15specialize_attr11Addressableau9subscriptFSix : $@convention(method) <Element> (Int, @guaranteed Addressable<Element>) -> UnsafeMutablePointer<Element> { // Addressable.subscript.getter with no attribute // CHECK-LABEL: sil [transparent] [fragile] @_TFC15specialize_attr11Addressableg9subscriptFSix : $@convention(method) <Element> (Int, @guaranteed Addressable<Element>) -> @out Element { // Addressable.subscript.setter with no attribute // CHECK-LABEL: sil [transparent] [fragile] @_TFC15specialize_attr11Addressables9subscriptFSix : $@convention(method) <Element> (@in Element, Int, @guaranteed Addressable<Element>) -> () { // Addressable.subscript.materializeForSet with no attribute // CHECK-LABEL: sil [transparent] [fragile] @_TFC15specialize_attr11Addressablem9subscriptFSix : $@convention(method) <Element> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, Int, @guaranteed Addressable<Element>) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) {
3c5a0d43c8699df23c9ef6ef0de85f1d
40.203704
283
0.703371
false
false
false
false
DAloG/BlueCap
refs/heads/master
BlueCapKit/Central/Service.swift
mit
1
// // Service.swift // BlueCap // // Created by Troy Stribling on 6/11/14. // Copyright (c) 2014 Troy Stribling. The MIT License (MIT). // import Foundation import CoreBluetooth /////////////////////////////////////////// // ServiceImpl public protocol ServiceWrappable { var uuid : CBUUID {get} var name : String {get} var state: CBPeripheralState {get} func discoverCharacteristics(characteristics:[CBUUID]?) func didDiscoverCharacteristics(error:NSError?) func createCharacteristics() func discoverAllCharacteristics() -> Future<Self> } public final class ServiceImpl<Wrapper:ServiceWrappable> { private var characteristicsDiscoveredPromise = Promise<Wrapper>() public func discoverAllCharacteristics(service:Wrapper) -> Future<Wrapper> { Logger.debug("uuid=\(service.uuid.UUIDString), name=\(service.name)") return self.discoverIfConnected(service, characteristics:nil) } public func discoverCharacteristics(service:Wrapper, characteristics:[CBUUID]?) -> Future<Wrapper> { Logger.debug("uuid=\(service.uuid.UUIDString), name=\(service.name)") return self.discoverIfConnected(service, characteristics:characteristics) } public func discoverIfConnected(service:Wrapper, characteristics:[CBUUID]?) -> Future<Wrapper> { self.characteristicsDiscoveredPromise = Promise<Wrapper>() if service.state == .Connected { service.discoverCharacteristics(characteristics) } else { self.characteristicsDiscoveredPromise.failure(BCError.peripheralDisconnected) } return self.characteristicsDiscoveredPromise.future } public init() { } public func didDiscoverCharacteristics(service:Wrapper, error:NSError?) { if let error = error { Logger.debug("discover failed") self.characteristicsDiscoveredPromise.failure(error) } else { service.createCharacteristics() Logger.debug("discover success") self.characteristicsDiscoveredPromise.success(service) } } } // ServiceImpl /////////////////////////////////////////// public final class Service : ServiceWrappable { internal var impl = ServiceImpl<Service>() // ServiceWrappable public var name : String { if let profile = self.profile { return profile.name } else { return "Unknown" } } public var uuid : CBUUID { return self.cbService.UUID } public var state : CBPeripheralState { return self.peripheral.state } public func discoverCharacteristics(characteristics:[CBUUID]?) { self.peripheral.cbPeripheral.discoverCharacteristics(characteristics, forService:self.cbService) } public func createCharacteristics() { self.discoveredCharacteristics.removeAll() if let cbChracteristics = self.cbService.characteristics { for cbCharacteristic in cbChracteristics { let bcCharacteristic = Characteristic(cbCharacteristic:cbCharacteristic, service:self) self.discoveredCharacteristics[bcCharacteristic.uuid] = bcCharacteristic bcCharacteristic.didDiscover() Logger.debug("uuid=\(bcCharacteristic.uuid.UUIDString), name=\(bcCharacteristic.name)") } } } public func discoverAllCharacteristics() -> Future<Service> { Logger.debug() return self.impl.discoverIfConnected(self, characteristics:nil) } public func didDiscoverCharacteristics(error:NSError?) { self.impl.didDiscoverCharacteristics(self, error:error) } // ServiceWrappable private let profile : ServiceProfile? internal let _peripheral : Peripheral internal let cbService : CBService internal var discoveredCharacteristics = [CBUUID:Characteristic]() public var characteristics : [Characteristic] { return Array(self.discoveredCharacteristics.values) } public var peripheral : Peripheral { return self._peripheral } public func discoverCharacteristics(characteristics:[CBUUID]) -> Future<Service> { Logger.debug() return self.impl.discoverIfConnected(self, characteristics:characteristics) } internal init(cbService:CBService, peripheral:Peripheral) { self.cbService = cbService self._peripheral = peripheral self.profile = ProfileManager.sharedInstance.serviceProfiles[cbService.UUID] } public func characteristic(uuid:CBUUID) -> Characteristic? { return self.discoveredCharacteristics[uuid] } }
7081214298de4deb9b225d7355ed299e
31.993151
104
0.653862
false
false
false
false
broccolii/Demos
refs/heads/master
DEMO02-LoginAnimation/LoginAnimation/SwiftClass/SkyFloatingLabelTextField/SkyFloatingLabelTextField.swift
mit
1
// Copyright 2016 Skyscanner Ltd // // 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 /** A beautiful and flexible textfield implementation with support for title label, error message and placeholder. */ @IBDesignable public class SkyFloatingLabelTextField: UITextField { /// A Boolean value that determines if the language displayed is LTR. Default value set automatically from the application language settings. var isLTRLanguage = UIApplication.sharedApplication().userInterfaceLayoutDirection == .LeftToRight { didSet { self.updateTextAligment() } } private func updateTextAligment() { if(self.isLTRLanguage) { self.textAlignment = .Left } else { self.textAlignment = .Right } } // MARK: Animation timing /// The value of the title appearing duration public var titleFadeInDuration:NSTimeInterval = 0.2 /// The value of the title disappearing duration public var titleFadeOutDuration:NSTimeInterval = 0.3 // MARK: Colors private var cachedTextColor:UIColor? /// A UIColor value that determines the text color of the editable text @IBInspectable override public var textColor:UIColor? { set { self.cachedTextColor = newValue self.updateControl(false) } get { return cachedTextColor } } /// A UIColor value that determines text color of the placeholder label @IBInspectable public var placeholderColor:UIColor = UIColor.lightGrayColor() { didSet { self.updatePlaceholder() } } /// A UIColor value that determines text color of the placeholder label @IBInspectable public var placeholderFont:UIFont? { didSet { self.updatePlaceholder() } } private func updatePlaceholder() { if let placeholder = self.placeholder, font = self.placeholderFont ?? self.font { self.attributedPlaceholder = NSAttributedString(string: placeholder, attributes: [NSForegroundColorAttributeName:placeholderColor, NSFontAttributeName: font]) } } /// A UIColor value that determines the text color of the title label when in the normal state @IBInspectable public var titleColor:UIColor = UIColor.grayColor() { didSet { self.updateTitleColor() } } /// A UIColor value that determines the color of the bottom line when in the normal state @IBInspectable public var lineColor:UIColor = UIColor.lightGrayColor() { didSet { self.updateLineView() } } /// A UIColor value that determines the color used for the title label and the line when the error message is not `nil` @IBInspectable public var errorColor:UIColor = UIColor.redColor() { didSet { self.updateColors() } } /// A UIColor value that determines the text color of the title label when editing @IBInspectable public var selectedTitleColor:UIColor = UIColor.blueColor() { didSet { self.updateTitleColor() } } /// A UIColor value that determines the color of the line in a selected state @IBInspectable public var selectedLineColor:UIColor = UIColor.blackColor() { didSet { self.updateLineView() } } // MARK: Line height /// A CGFloat value that determines the height for the bottom line when the control is in the normal state @IBInspectable public var lineHeight:CGFloat = 0.5 { didSet { self.updateLineView() self.setNeedsDisplay() } } /// A CGFloat value that determines the height for the bottom line when the control is in a selected state @IBInspectable public var selectedLineHeight:CGFloat = 1.0 { didSet { self.updateLineView() self.setNeedsDisplay() } } // MARK: View components /// The internal `UIView` to display the line below the text input. public var lineView:UIView! /// The internal `UILabel` that displays the selected, deselected title or the error message based on the current state. public var titleLabel:UILabel! // MARK: Properties /** The formatter to use before displaying content in the title label. This can be the `title`, `selectedTitle` or the `errorMessage`. The default implementation converts the text to uppercase. */ public var titleFormatter:(String -> String) = { (text:String) -> String in return text.uppercaseString } /** Identifies whether the text object should hide the text being entered. */ override public var secureTextEntry:Bool { set { super.secureTextEntry = newValue self.fixCaretPosition() } get { return super.secureTextEntry } } /// A String value for the error message to display. public var errorMessage:String? { didSet { self.updateControl(true) } } /// The backing property for the highlighted property private var _highlighted = false /// A Boolean value that determines whether the receiver is highlighted. When changing this value, highlighting will be done with animation override public var highlighted:Bool { get { return _highlighted } set { _highlighted = newValue self.updateTitleColor() self.updateLineView() } } /// A Boolean value that determines whether the textfield is being edited or is selected. public var editingOrSelected:Bool { get { return super.editing || self.selected; } } /// A Boolean value that determines whether the receiver has an error message. public var hasErrorMessage:Bool { get { return self.errorMessage != nil && self.errorMessage != "" } } private var _renderingInInterfaceBuilder:Bool = false /// The text content of the textfield @IBInspectable override public var text:String? { didSet { self.updateControl(false) } } /** The String to display when the input field is empty. The placeholder can also appear in the title label when both `title` `selectedTitle` and are `nil`. */ @IBInspectable override public var placeholder:String? { didSet { self.setNeedsDisplay() self.updatePlaceholder() self.updateTitleLabel() } } /// The String to display when the textfield is editing and the input is not empty. @IBInspectable public var selectedTitle:String? { didSet { self.updateControl() } } /// The String to display when the textfield is not editing and the input is not empty. @IBInspectable public var title:String? { didSet { self.updateControl() } } // Determines whether the field is selected. When selected, the title floats above the textbox. public override var selected:Bool { didSet { self.updateControl(true) } } // MARK: - Initializers /** Initializes the control - parameter frame the frame of the control */ override public init(frame: CGRect) { super.init(frame: frame) self.init_SkyFloatingLabelTextField() } /** Intialzies the control by deserializing it - parameter coder the object to deserialize the control from */ required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.init_SkyFloatingLabelTextField() } private final func init_SkyFloatingLabelTextField() { self.borderStyle = .None self.createTitleLabel() self.createLineView() self.updateColors() self.addEditingChangedObserver() self.updateTextAligment() } private func addEditingChangedObserver() { self.addTarget(self, action: #selector(SkyFloatingLabelTextField.editingChanged), forControlEvents: .EditingChanged) } /** Invoked when the editing state of the textfield changes. Override to respond to this change. */ public func editingChanged() { updateControl(true) updateTitleLabel(true) } // MARK: create components private func createTitleLabel() { let titleLabel = UILabel() titleLabel.autoresizingMask = [.FlexibleWidth, .FlexibleHeight] titleLabel.font = UIFont.systemFontOfSize(13) titleLabel.alpha = 0.0 titleLabel.textColor = self.titleColor self.addSubview(titleLabel) self.titleLabel = titleLabel } private func createLineView() { if self.lineView == nil { let lineView = UIView() lineView.userInteractionEnabled = false self.lineView = lineView self.configureDefaultLineHeight() } lineView.autoresizingMask = [.FlexibleWidth, .FlexibleTopMargin] self.addSubview(lineView) } private func configureDefaultLineHeight() { let onePixel:CGFloat = 1.0 / UIScreen.mainScreen().scale self.lineHeight = 2.0 * onePixel self.selectedLineHeight = 2.0 * self.lineHeight } // MARK: Responder handling /** Attempt the control to become the first responder - returns: True when successfull becoming the first responder */ override public func becomeFirstResponder() -> Bool { let result = super.becomeFirstResponder() self.updateControl(true) return result } /** Attempt the control to resign being the first responder - returns: True when successfull resigning being the first responder */ override public func resignFirstResponder() -> Bool { let result = super.resignFirstResponder() self.updateControl(true) return result } // MARK: - View updates private func updateControl(animated:Bool = false) { self.updateColors() self.updateLineView() self.updateTitleLabel(animated) } private func updateLineView() { if let lineView = self.lineView { lineView.frame = self.lineViewRectForBounds(self.bounds, editing: self.editingOrSelected) } self.updateLineColor() } // MARK: - Color updates /// Update the colors for the control. Override to customize colors. public func updateColors() { self.updateLineColor() self.updateTitleColor() self.updateTextColor() } private func updateLineColor() { if self.hasErrorMessage { self.lineView.backgroundColor = self.errorColor } else { self.lineView.backgroundColor = self.editingOrSelected ? self.selectedLineColor : self.lineColor } } private func updateTitleColor() { if self.hasErrorMessage { self.titleLabel.textColor = self.errorColor } else { if self.editingOrSelected || self.highlighted { self.titleLabel.textColor = self.selectedTitleColor } else { self.titleLabel.textColor = self.titleColor } } } private func updateTextColor() { if self.hasErrorMessage { super.textColor = self.errorColor } else { super.textColor = self.cachedTextColor } } // MARK: - Title handling private func updateTitleLabel(animated:Bool = false) { var titleText:String? = nil if self.hasErrorMessage { titleText = self.titleFormatter(errorMessage!) } else { if self.editingOrSelected { titleText = self.selectedTitleOrTitlePlaceholder() if titleText == nil { titleText = self.titleOrPlaceholder() } } else { titleText = self.titleOrPlaceholder() } } self.titleLabel.text = titleText self.updateTitleVisibility(animated) } private var _titleVisible = false /* * Set this value to make the title visible */ public func setTitleVisible(titleVisible:Bool, animated:Bool = false, animationCompletion: (()->())? = nil) { if(_titleVisible == titleVisible) { return } _titleVisible = titleVisible self.updateTitleColor() self.updateTitleVisibility(animated, completion: animationCompletion) } /** Returns whether the title is being displayed on the control. - returns: True if the title is displayed on the control, false otherwise. */ public func isTitleVisible() -> Bool { return self.hasText() || self.hasErrorMessage || _titleVisible } private func updateTitleVisibility(animated:Bool = false, completion: (()->())? = nil) { let alpha:CGFloat = self.isTitleVisible() ? 1.0 : 0.0 let frame:CGRect = self.titleLabelRectForBounds(self.bounds, editing: self.isTitleVisible()) let updateBlock = { () -> Void in self.titleLabel.alpha = alpha self.titleLabel.frame = frame } if animated { let animationOptions:UIViewAnimationOptions = .CurveEaseOut; let duration = self.isTitleVisible() ? titleFadeInDuration : titleFadeOutDuration UIView.animateWithDuration(duration, delay: 0, options: animationOptions, animations: { () -> Void in updateBlock() }, completion: { _ in completion?() }) } else { updateBlock() completion?() } } // MARK: - UITextField text/placeholder positioning overrides /** Calculate the rectangle for the textfield when it is not being edited - parameter bounds: The current bounds of the field - returns: The rectangle that the textfield should render in */ override public func textRectForBounds(bounds: CGRect) -> CGRect { super.textRectForBounds(bounds) let titleHeight = self.titleHeight() let lineHeight = self.selectedLineHeight let rect = CGRectMake(0, titleHeight, bounds.size.width, bounds.size.height - titleHeight - lineHeight) return rect } /** Calculate the rectangle for the textfield when it is being edited - parameter bounds: The current bounds of the field - returns: The rectangle that the textfield should render in */ override public func editingRectForBounds(bounds: CGRect) -> CGRect { let titleHeight = self.titleHeight() let lineHeight = self.selectedLineHeight let rect = CGRectMake(0, titleHeight, bounds.size.width, bounds.size.height - titleHeight - lineHeight) return rect } /** Calculate the rectangle for the placeholder - parameter bounds: The current bounds of the placeholder - returns: The rectangle that the placeholder should render in */ override public func placeholderRectForBounds(bounds: CGRect) -> CGRect { let titleHeight = self.titleHeight() let lineHeight = self.selectedLineHeight let rect = CGRectMake(0, titleHeight, bounds.size.width, bounds.size.height - titleHeight - lineHeight) return rect } // MARK: - Positioning Overrides /** Calculate the bounds for the title label. Override to create a custom size title field. - parameter bounds: The current bounds of the title - parameter editing: True if the control is selected or highlighted - returns: The rectangle that the title label should render in */ public func titleLabelRectForBounds(bounds:CGRect, editing:Bool) -> CGRect { let titleHeight = self.titleHeight() if editing { return CGRectMake(0, 0, bounds.size.width, titleHeight) } return CGRectMake(0, titleHeight, bounds.size.width, titleHeight) } /** Calculate the bounds for the bottom line of the control. Override to create a custom size bottom line in the textbox. - parameter bounds: The current bounds of the line - parameter editing: True if the control is selected or highlighted - returns: The rectangle that the line bar should render in */ public func lineViewRectForBounds(bounds:CGRect, editing:Bool) -> CGRect { let lineHeight:CGFloat = editing ? CGFloat(self.selectedLineHeight) : CGFloat(self.lineHeight) return CGRectMake(0, bounds.size.height - lineHeight, bounds.size.width, lineHeight); } /** Calculate the height of the title label. -returns: the calculated height of the title label. Override to size the title with a different height */ public func titleHeight() -> CGFloat { if let titleLabel = self.titleLabel, font = titleLabel.font { return font.lineHeight } return 15.0 } /** Calcualte the height of the textfield. -returns: the calculated height of the textfield. Override to size the textfield with a different height */ public func textHeight() -> CGFloat { return self.font!.lineHeight + 7.0 } // MARK: - Layout /// Invoked when the interface builder renders the control override public func prepareForInterfaceBuilder() { if #available(iOS 8.0, *) { super.prepareForInterfaceBuilder() } self.selected = true _renderingInInterfaceBuilder = true self.updateControl(false) self.invalidateIntrinsicContentSize() } /// Invoked by layoutIfNeeded automatically override public func layoutSubviews() { super.layoutSubviews() self.titleLabel.frame = self.titleLabelRectForBounds(self.bounds, editing: self.isTitleVisible() || _renderingInInterfaceBuilder) self.lineView.frame = self.lineViewRectForBounds(self.bounds, editing: self.editingOrSelected || _renderingInInterfaceBuilder) } /** Calculate the content size for auto layout - returns: the content size to be used for auto layout */ override public func intrinsicContentSize() -> CGSize { return CGSizeMake(self.bounds.size.width, self.titleHeight() + self.textHeight()) } // MARK: - Helpers private func titleOrPlaceholder() -> String? { if let title = self.title ?? self.placeholder { return self.titleFormatter(title) } return nil } private func selectedTitleOrTitlePlaceholder() -> String? { if let title = self.selectedTitle ?? self.title ?? self.placeholder { return self.titleFormatter(title) } return nil } }
54d781a0511266eda6613e8aec807e30
32.950257
309
0.63088
false
false
false
false
mas-cli/mas
refs/heads/main
Package.swift
mit
1
// swift-tools-version:5.3 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "mas", platforms: [ .macOS(.v10_11) ], products: [ // Products define the executables and libraries a package produces, and make them visible to other packages. .executable( name: "mas", targets: ["mas"] ), .library( name: "MasKit", targets: ["MasKit"] ), ], dependencies: [ // Dependencies declare other packages that this package depends on. .package(url: "https://github.com/Carthage/Commandant.git", from: "0.18.0"), .package(url: "https://github.com/Quick/Nimble.git", from: "10.0.0"), .package(url: "https://github.com/Quick/Quick.git", from: "5.0.0"), .package(url: "https://github.com/mxcl/PromiseKit.git", from: "6.16.2"), .package(url: "https://github.com/mxcl/Version.git", from: "2.0.1"), ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages this package depends on. .target( name: "mas", dependencies: ["MasKit"], swiftSettings: [ .unsafeFlags([ "-I", "Sources/PrivateFrameworks/CommerceKit", "-I", "Sources/PrivateFrameworks/StoreFoundation", ]) ] ), .target( name: "MasKit", dependencies: ["Commandant", "PromiseKit", "Version"], swiftSettings: [ .unsafeFlags([ "-I", "Sources/PrivateFrameworks/CommerceKit", "-I", "Sources/PrivateFrameworks/StoreFoundation", ]) ], linkerSettings: [ .linkedFramework("CommerceKit"), .linkedFramework("StoreFoundation"), .unsafeFlags(["-F", "/System/Library/PrivateFrameworks"]), ] ), .testTarget( name: "MasKitTests", dependencies: ["MasKit", "Nimble", "Quick"], resources: [.copy("JSON")], swiftSettings: [ .unsafeFlags([ "-I", "Sources/PrivateFrameworks/CommerceKit", "-I", "Sources/PrivateFrameworks/StoreFoundation", ]) ] ), ], swiftLanguageVersions: [.v5] ) // https://github.com/apple/swift-format#matching-swift-format-to-your-swift-version-swift-57-and-earlier #if compiler(>=5.7) package.dependencies += [ .package(url: "https://github.com/apple/swift-format", .branch("release/5.7")) ] #elseif compiler(>=5.6) package.dependencies += [ .package(url: "https://github.com/apple/swift-format", .branch("release/5.6")) ] #elseif compiler(>=5.5) package.dependencies += [ .package(url: "https://github.com/apple/swift-format", .branch("swift-5.5-branch")) ] #elseif compiler(>=5.4) package.dependencies += [ .package(url: "https://github.com/apple/swift-format", .branch("swift-5.4-branch")) ] #elseif compiler(>=5.3) package.dependencies += [ .package(url: "https://github.com/apple/swift-format", .branch("swift-5.3-branch")) ] #endif
5ba3650cf33b05b8b4580269a897779a
36.138298
117
0.553423
false
false
false
false
DivineDominion/ErrorHandling
refs/heads/master
ErrorHandling/TextEmailer.swift
mit
1
// Copyright (c) 2015 Christian Tietze // // See the file LICENSE for copying permission. import Foundation import AppKit public class TextEmailer { static var appInfo: [String : Any]? { return Bundle.main.infoDictionary } static var appName: String? { return appInfo?["CFBundleName"] as? String } static var supportEmail: String? { return appInfo?["SupportEmail"] as? String } static var build: String { guard let build = appInfo?["CFBundleVersion"] as? String else { return "" } return "b\(build)" } static var version: String { guard let version = appInfo?["CFBundleShortVersionString"] as? String else { return "" } return "v\(version)" } static var versionString: String? { let combined = [version, build].filter { !$0.isEmpty }.joined(separator: " ") guard !combined.isEmpty else { return nil } return "(\(combined))" } static var emailSubject: String { let base = "Report for \(appName!)" guard let buildAndVersion = versionString else { return base } return "\(base) \(buildAndVersion)" } static func guardInfoPresent() { precondition(hasValue(appInfo), "Could not read app's Info dictionary.") precondition(hasValue(appName), "Expected CFBundleName in Info.plist to use as appName in e-mail.") precondition(hasValue(supportEmail), "Expected SupportEmail being set in Info.plist") } public init() { TextEmailer.guardInfoPresent() } } extension TextEmailer: ReportEmailer { public func email(error: Error, instructions: String? = nil) { email(text: (error as NSError).debugDescription, instructions: instructions) } public func email(report: Report, instructions: String? = nil) { email(text: report.localizedDescription, instructions: instructions) } public func email(text: String, instructions: String?) { guard let emailService = NSSharingService(named: .composeEmail) else { legacyURLEmailer(text: text) return } emailService.recipients = [TextEmailer.supportEmail!] emailService.subject = TextEmailer.emailSubject emailService.perform(withItems: [instructions, text].compactMap { $0 }) } private func legacyURLEmailer(text: String) { let recipient = TextEmailer.supportEmail! let subject = TextEmailer.emailSubject let query = "subject=\(subject)&body=\(text)".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)! let mailtoAddress = "mailto:\(recipient)?\(query)" let url = URL(string: mailtoAddress)! NSWorkspace.shared.open(url) } }
c9cd45802daae2dcd90b297555076371
29.369565
117
0.642806
false
false
false
false
LawrenceHan/iOS-project-playground
refs/heads/master
Homepwner_swift/Homepwner/DetailViewController.swift
mit
1
// // Copyright © 2015 Big Nerd Ranch // import UIKit class DetailViewController: UIViewController, UITextFieldDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate { @IBOutlet var nameField: UITextField! @IBOutlet var serialNumberField: UITextField! @IBOutlet var valueField: UITextField! @IBOutlet var dateLabel: UILabel! @IBOutlet var imageView: UIImageView! var item: Item! { didSet { navigationItem.title = item.name } } var imageStore: ImageStore! @IBAction func takePicture(sender: UIBarButtonItem) { let imagePicker = UIImagePickerController() // If the device has a camera, take a picture, otherwise, // just pick from photo library if UIImagePickerController.isSourceTypeAvailable(.Camera) { imagePicker.sourceType = .Camera } else { imagePicker.sourceType = .PhotoLibrary } imagePicker.delegate = self // Place image picker on the screen presentViewController(imagePicker, animated: true, completion: nil) } func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String: AnyObject]) { // Get picked image from info dictionary let image = info[UIImagePickerControllerOriginalImage] as! UIImage // Store the image in the ImageStore for the item's key imageStore.setImage(image, forKey:item.itemKey) // Put that image onto the screen in our image view imageView.image = image // Take image picker off the screen - // you must call this dismiss method dismissViewControllerAnimated(true, completion: nil) } let numberFormatter: NSNumberFormatter = { let formatter = NSNumberFormatter() formatter.numberStyle = .DecimalStyle formatter.minimumFractionDigits = 2 formatter.maximumFractionDigits = 2 return formatter }() let dateFormatter: NSDateFormatter = { let formatter = NSDateFormatter() formatter.dateStyle = .MediumStyle formatter.timeStyle = .NoStyle return formatter }() override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) nameField.text = item.name serialNumberField.text = item.serialNumber valueField.text = numberFormatter.stringFromNumber(item.valueInDollars) dateLabel.text = dateFormatter.stringFromDate(item.dateCreated) // Get the item key let key = item.itemKey // If there is an associated image with the item ... if let imageToDisplay = imageStore.imageForKey(key) { // ... display it on the image view imageView.image = imageToDisplay } } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) // Clear first responder view.endEditing(true) // "Save" changes to item item.name = nameField.text ?? "" item.serialNumber = serialNumberField.text if let valueText = valueField.text, let value = numberFormatter.numberFromString(valueText) { item.valueInDollars = value.integerValue } else { item.valueInDollars = 0 } } @IBAction func backgroundTapped(sender: UITapGestureRecognizer) { view.endEditing(true) } func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return true } }
2ec825a1ddb366db663cd3117c8136be
30.694215
79
0.61721
false
false
false
false
Pluto-tv/RxSwift
refs/heads/master
RxTests/RxSwiftTests/TestImplementations/Mocks/PrimitiveHotObservable.swift
mit
1
// // PrimitiveHotObservable.swift // RxTests // // Created by Krunoslav Zaher on 6/4/15. // // import Foundation import RxSwift let SubscribedToHotObservable = Subscription(0) let UnsunscribedFromHotObservable = Subscription(0, 0) class PrimitiveHotObservable<ElementType : Equatable> : ObservableType { typealias E = ElementType typealias Events = Recorded<E> typealias Observer = AnyObserver<E> var subscriptions: [Subscription] var observers: Bag<AnyObserver<E>> let lock = NSRecursiveLock() init() { self.subscriptions = [] self.observers = Bag() } func on(event: Event<E>) { observers.forEach { $0.on(event) } } func subscribe<O : ObserverType where O.E == E>(observer: O) -> Disposable { lock.lock() defer { lock.unlock() } let key = observers.insert(AnyObserver(observer)) subscriptions.append(SubscribedToHotObservable) let i = self.subscriptions.count - 1 return AnonymousDisposable { self.lock.lock() defer { self.lock.unlock() } let removed = self.observers.removeKey(key) assert(removed != nil) self.subscriptions[i] = UnsunscribedFromHotObservable } } }
8f01f7a8b1f02a7bb086cc6691ccbee9
23.181818
80
0.609023
false
false
false
false
venticake/RetricaImglyKit-iOS
refs/heads/master
RetricaImglyKit/Classes/Frontend/Editor/PhotoEditViewController.swift
mit
1
// This file is part of the PhotoEditor Software Development Kit. // Copyright (C) 2016 9elements GmbH <[email protected]> // All rights reserved. // Redistribution and use in source and binary forms, without // modification, are permitted provided that the following license agreement // is approved and a legal/financial contract was signed by the user. // The license agreement can be found under the following link: // https://www.photoeditorsdk.com/LICENSE.txt import UIKit import GLKit import ImageIO import MobileCoreServices /// Posted immediately after the selected overlay view was changed. /// The notification object is the view that was selected. The `userInfo` dictionary is `nil`. public let PhotoEditViewControllerSelectedOverlayViewDidChangeNotification = "PhotoEditViewControllerSelectedOverlayViewDidChangeNotification" /** The `PhotoEditViewControllerDelegate` protocol defines methods that allow you respond to the events of an instance of `PhotoEditViewController`. */ @available(iOS 8, *) @objc(IMGLYPhotoEditViewControllerDelegate) public protocol PhotoEditViewControllerDelegate { /** Called when a new tool was selected. - parameter photoEditViewController: The photo edit view controller that was used to select the new tool. - parameter toolController: The tool that was selected. - parameter replaceTopToolController: Whether or not the tool controller should be placed above the previous tool or whether it should be replaced. */ func photoEditViewController(photoEditViewController: PhotoEditViewController, didSelectToolController toolController: PhotoEditToolController, wantsCurrentTopToolControllerReplaced replaceTopToolController: Bool) /** Called when a tool should be dismissed. - parameter photoEditViewController: The photo edit view controller that was used to dismiss the tool. */ func photoEditViewControllerPopToolController(photoEditViewController: PhotoEditViewController) /** The currently active editing tool. - parameter photoEditViewController: The photo edit view controller that is asking for the active editing tool. - returns: An instance of `PhotoEditToolController` that is currently at the top. */ func photoEditViewControllerCurrentEditingTool(photoEditViewController: PhotoEditViewController) -> PhotoEditToolController? /** Called when the output image was generated. - parameter photoEditViewController: The photo edit view controller that created the output image. - parameter image: The output image that was generated. */ func photoEditViewController(photoEditViewController: PhotoEditViewController, didSaveImage image: UIImage) /** Called when the output image could not be generated. - parameter photoEditViewController: The photo edit view controller that was unable to generate the output image. */ func photoEditViewControllerDidFailToGeneratePhoto(photoEditViewController: PhotoEditViewController) /** Called when the user wants to dismiss the editor. - parameter photoEditviewController: The photo edit view controller that is asking to be cancelled. */ func photoEditViewControllerDidCancel(photoEditviewController: PhotoEditViewController) } /** * A `PhotoEditViewController` is responsible for presenting and rendering an edited image. */ @available(iOS 8, *) @objc(IMGLYPhotoEditViewController) public class PhotoEditViewController: UIViewController { // MARK: - Statics private static let IconCaptionCollectionViewCellReuseIdentifier = "IconCaptionCollectionViewCellReuseIdentifier" private static let IconCaptionCollectionViewCellSize = CGSize(width: 64, height: 80) private static let SeparatorCollectionViewCellReuseIdentifier = "SeparatorCollectionViewCellReuseIdentifier" private static let SeparatorCollectionViewCellSize = CGSize(width: 15, height: 80) // MARK: - View Properties private var collectionView: UICollectionView? private var previewViewScrollingContainer: UIScrollView? private var mainPreviewView: GLKView? private var overlayContainerView: UIView? private var frameImageView: UIImageView? private var placeholderImageView: UIImageView? private var tapGestureRecognizer: UITapGestureRecognizer? private var panGestureRecognizer: UIPanGestureRecognizer? private var pinchGestureRecognizer: UIPinchGestureRecognizer? private var rotationGestureRecognizer: UIRotationGestureRecognizer? // MARK: - Constraint Properties private var placeholderImageViewConstraints: [NSLayoutConstraint]? private var previewViewScrollingContainerConstraints: [NSLayoutConstraint]? // MARK: - Model Properties /// The tool stack item for this controller. /// - seealso: `ToolStackItem`. public private(set) lazy var toolStackItem = ToolStackItem() private var photo: UIImage? { didSet { updatePlaceholderImage() } } private var photoImageOrientation: UIImageOrientation = .Up private var photoFileURL: NSURL? private let configuration: Configuration private var photoEditModel: IMGLYPhotoEditMutableModel? { didSet { if oldValue != photoEditModel { if let oldPhotoEditModel = oldValue { NSNotificationCenter.defaultCenter().removeObserver(self, name: IMGLYPhotoEditModelDidChangeNotification, object: oldPhotoEditModel) } if let photoEditModel = photoEditModel { NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(PhotoEditViewController.photoEditModelDidChange(_:)), name: IMGLYPhotoEditModelDidChangeNotification, object: photoEditModel) updateMainRenderer() } } } } @NSCopying private var uneditedPhotoEditModel: IMGLYPhotoEditModel? private var baseWorkUIImage: UIImage? { didSet { if oldValue != baseWorkUIImage { let ciImage: CIImage? if let baseWorkUIImage = baseWorkUIImage { ciImage = orientedCIImageFromUIImage(baseWorkUIImage) } else { ciImage = nil } baseWorkCIImage = ciImage updateMainRenderer() loadFrameControllerIfNeeded() if baseWorkUIImage != nil { if let photo = photo { // Save original photo image orientation photoImageOrientation = photo.imageOrientation // Write full resolution image to disc to free memory let fileName = "\(NSProcessInfo.processInfo().globallyUniqueString)_photo.png" let fileURL = NSURL(fileURLWithPath: (NSTemporaryDirectory() as NSString).stringByAppendingPathComponent(fileName)) UIImagePNGRepresentation(photo)?.writeToURL(fileURL, atomically: true) photoFileURL = fileURL self.photo = nil } } } } } private var baseWorkCIImage: CIImage? private var mainRenderer: PhotoEditRenderer? private var nextRenderCompletionBlock: (() -> Void)? private var frameController: FrameController? // MARK: - State Properties private var previewViewScrollingContainerLayoutValid = false private var lastKnownWorkImageSize = CGSize.zero private var lastKnownPreviewViewSize = CGSize.zero /// The identifier of the photo effect to apply to the photo immediately. This is useful if you /// pass a photo that already has an effect applied by the `CameraViewController`. Note that you /// must set this property before presenting the view controller. public var initialPhotoEffectIdentifier: String? /// The intensity of the photo effect that is applied to the photo immediately. See /// `initialPhotoEffectIdentifier` for more information. public var initialPhotoEffectIntensity: CGFloat? private var toolForAction: [PhotoEditorAction: PhotoEditToolController]? private var selectedOverlayView: UIView? { didSet { NSNotificationCenter.defaultCenter().postNotificationName(PhotoEditViewControllerSelectedOverlayViewDidChangeNotification, object: selectedOverlayView) oldValue?.layer.borderWidth = 0 oldValue?.layer.shadowOffset = CGSize.zero oldValue?.layer.shadowColor = UIColor.clearColor().CGColor // Reset zoom updateScrollViewZoomScaleAnimated(true) if let selectedOverlayView = selectedOverlayView { selectedOverlayView.layer.borderWidth = 2 / (0.5 * (selectedOverlayView.transform.xScale + selectedOverlayView.transform.yScale)) selectedOverlayView.layer.borderColor = UIColor.whiteColor().CGColor selectedOverlayView.layer.shadowOffset = CGSize(width: 0, height: 2) selectedOverlayView.layer.shadowRadius = 2 selectedOverlayView.layer.shadowOpacity = 0.12 selectedOverlayView.layer.shadowColor = UIColor.blackColor().CGColor } } } private var draggedOverlayView: UIView? // MARK: - Other Properties weak var delegate: PhotoEditViewControllerDelegate? private lazy var stickerContextMenuController: ContextMenuController = { let flipHorizontallyAction = ContextMenuAction(image: UIImage(named: "imgly_icon_option_orientation_flip_h", inBundle: NSBundle.imglyKitBundle, compatibleWithTraitCollection: nil)!) { [weak self] _ in guard let overlayView = self?.selectedOverlayView as? StickerImageView else { return } self?.undoManager?.registerUndoForTarget(overlayView) { view in view.flipHorizontally() } overlayView.flipHorizontally() self?.configuration.stickerToolControllerOptions.stickerActionSelectedClosure?(.FlipHorizontally) } flipHorizontallyAction.accessibilityLabel = Localize("Flip horizontally") let flipVerticallyAction = ContextMenuAction(image: UIImage(named: "imgly_icon_option_orientation_flip_v", inBundle: NSBundle.imglyKitBundle, compatibleWithTraitCollection: nil)!) { [weak self] _ in guard let overlayView = self?.selectedOverlayView as? StickerImageView else { return } self?.undoManager?.registerUndoForTarget(overlayView) { view in view.flipVertically() } overlayView.flipVertically() self?.configuration.stickerToolControllerOptions.stickerActionSelectedClosure?(.FlipVertically) } flipVerticallyAction.accessibilityLabel = Localize("Flip vertically") let bringToFrontAction = ContextMenuAction(image: UIImage(named: "imgly_icon_option_bringtofront", inBundle: NSBundle.imglyKitBundle, compatibleWithTraitCollection: nil)!) { [weak self] _ in guard let overlayView = self?.selectedOverlayView as? StickerImageView else { return } if let overlayViewSuperview = overlayView.superview, currentOrder = overlayViewSuperview.subviews.indexOf(overlayView) { self?.undoManager?.registerUndoForTarget(overlayViewSuperview) { superview in superview.insertSubview(overlayView, atIndex: currentOrder) } } overlayView.superview?.bringSubviewToFront(overlayView) self?.configuration.stickerToolControllerOptions.stickerActionSelectedClosure?(.BringToFront) } bringToFrontAction.accessibilityLabel = Localize("Bring to front") let deleteAction = ContextMenuAction(image: UIImage(named: "imgly_icon_option_delete", inBundle: NSBundle.imglyKitBundle, compatibleWithTraitCollection: nil)!) { [weak self] _ in guard let overlayView = self?.selectedOverlayView as? StickerImageView, overlayContainerView = self?.overlayContainerView else { return } self?.undoManager?.registerUndoForTarget(overlayContainerView) { view in view.addSubview(overlayView) } self?.removeStickerOverlay(overlayView) if self?.selectedOverlayView == overlayView { self?.selectedOverlayView = nil self?.hideOptionsForOverlayIfNeeded() } self?.configuration.stickerToolControllerOptions.stickerActionSelectedClosure?(.Delete) } deleteAction.accessibilityLabel = Localize("Delete") let contextMenu = ContextMenuController() contextMenu.menuColor = self.configuration.contextMenuBackgroundColor let actions: [ContextMenuAction] = self.configuration.stickerToolControllerOptions.allowedStickerContextActions.map({ switch $0 { case .FlipHorizontally: self.configuration.stickerToolControllerOptions.contextActionConfigurationClosure?(flipHorizontallyAction, .FlipHorizontally) return flipHorizontallyAction case .FlipVertically: self.configuration.stickerToolControllerOptions.contextActionConfigurationClosure?(flipVerticallyAction, .FlipVertically) return flipVerticallyAction case .BringToFront: self.configuration.stickerToolControllerOptions.contextActionConfigurationClosure?(bringToFrontAction, .BringToFront) return bringToFrontAction case .Delete: self.configuration.stickerToolControllerOptions.contextActionConfigurationClosure?(deleteAction, .Delete) return deleteAction case .Separator: return ContextMenuDividerAction() } }) actions.forEach { contextMenu.addAction($0) } return contextMenu }() private lazy var textContextMenuController: ContextMenuController = { let bringToFrontAction = ContextMenuAction(image: UIImage(named: "imgly_icon_option_bringtofront", inBundle: NSBundle.imglyKitBundle, compatibleWithTraitCollection: nil)!) { [weak self] _ in guard let overlayView = self?.selectedOverlayView as? TextLabel else { return } if let overlayViewSuperview = overlayView.superview, currentOrder = overlayViewSuperview.subviews.indexOf(overlayView) { self?.undoManager?.registerUndoForTarget(overlayViewSuperview) { superview in superview.insertSubview(overlayView, atIndex: currentOrder) } } overlayView.superview?.bringSubviewToFront(overlayView) self?.configuration.textOptionsToolControllerOptions.textContextActionSelectedClosure?(.BringToFront) } bringToFrontAction.accessibilityLabel = Localize("Bring to front") let deleteAction = ContextMenuAction(image: UIImage(named: "imgly_icon_option_delete", inBundle: NSBundle.imglyKitBundle, compatibleWithTraitCollection: nil)!) { [weak self] _ in guard let overlayView = self?.selectedOverlayView as? TextLabel, overlayContainerView = self?.overlayContainerView else { return } self?.undoManager?.registerUndoForTarget(overlayContainerView) { view in view.addSubview(overlayView) } overlayView.removeFromSuperview() if let elements = self?.previewViewScrollingContainer?.accessibilityElements as? [NSObject], index = elements.indexOf({$0 == overlayView}) { self?.previewViewScrollingContainer?.accessibilityElements?.removeAtIndex(index) } self?.selectedOverlayView = nil self?.hideOptionsForOverlayIfNeeded() self?.configuration.textOptionsToolControllerOptions.textContextActionSelectedClosure?(.Delete) } deleteAction.accessibilityLabel = Localize("Delete") let contextMenu = ContextMenuController() contextMenu.menuColor = self.configuration.contextMenuBackgroundColor let actions: [ContextMenuAction] = self.configuration.textOptionsToolControllerOptions.allowedTextContextActions.map({ switch $0 { case .BringToFront: self.configuration.textOptionsToolControllerOptions.contextActionConfigurationClosure?(bringToFrontAction, .BringToFront) return bringToFrontAction case .Delete: self.configuration.textOptionsToolControllerOptions.contextActionConfigurationClosure?(deleteAction, .Delete) return deleteAction case .Separator: return ContextMenuDividerAction() } }) actions.forEach { contextMenu.addAction($0) } return contextMenu }() // MARK: - Initializers /** Returns a newly initialized photo edit view controller for the given photo with a default configuration. - parameter photo: The photo to edit. - returns: A newly initialized `PhotoEditViewController` object. */ convenience public init(photo: UIImage) { self.init(photo: photo, configuration: Configuration()) } /** Returns a newly initialized photo edit view controller for the given photo with the given configuration options. - parameter photo: The photo to edit. - parameter configuration: The configuration options to apply. - returns: A newly initialized and configured `PhotoEditViewController` object. */ required public init(photo: UIImage, configuration: Configuration) { self.photo = photo self.configuration = configuration super.init(nibName: nil, bundle: nil) updateLastKnownImageSize() } /** :nodoc: */ required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Configuration private var options: PhotoEditViewControllerOptions { return self.configuration.photoEditViewControllerOptions } // MARK: - UIViewController /** :nodoc: */ public override func viewDidLoad() { super.viewDidLoad() previewViewScrollingContainer = UIScrollView() view.addSubview(previewViewScrollingContainer!) previewViewScrollingContainer!.delegate = self previewViewScrollingContainer!.alwaysBounceHorizontal = true previewViewScrollingContainer!.alwaysBounceVertical = true previewViewScrollingContainer!.showsHorizontalScrollIndicator = false previewViewScrollingContainer!.showsVerticalScrollIndicator = false previewViewScrollingContainer!.maximumZoomScale = 3 previewViewScrollingContainer!.minimumZoomScale = 1 previewViewScrollingContainer!.clipsToBounds = false automaticallyAdjustsScrollViewInsets = false let context = EAGLContext(API: .OpenGLES2) mainPreviewView = GLKView(frame: CGRect.zero, context: context) mainPreviewView!.delegate = self mainPreviewView!.isAccessibilityElement = true mainPreviewView!.accessibilityLabel = Localize("Photo") mainPreviewView!.accessibilityTraits |= UIAccessibilityTraitImage previewViewScrollingContainer!.addSubview(mainPreviewView!) previewViewScrollingContainer!.accessibilityElements = [mainPreviewView!] overlayContainerView = UIView() overlayContainerView!.clipsToBounds = true mainPreviewView!.addSubview(overlayContainerView!) frameImageView = UIImageView() frameImageView!.contentMode = options.frameScaleMode overlayContainerView!.addSubview(frameImageView!) view.setNeedsUpdateConstraints() } /** :nodoc: */ public override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) loadPhotoEditModelIfNecessary() loadToolsIfNeeded() installGestureRecognizersIfNeeded() updateToolStackItem() updateBackgroundColor() updatePlaceholderImage() updateRenderedPreviewForceRender(false) } /** :nodoc: */ public override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() updateScrollViewContentSize() } /** :nodoc: */ public override func preferredStatusBarStyle() -> UIStatusBarStyle { return .LightContent } /** :nodoc: */ public override func prefersStatusBarHidden() -> Bool { return true } /** :nodoc: */ public override func updateViewConstraints() { super.updateViewConstraints() updatePreviewContainerLayout() if let placeholderImageView = placeholderImageView, _ = previewViewScrollingContainer where placeholderImageViewConstraints == nil { placeholderImageView.translatesAutoresizingMaskIntoConstraints = false var constraints = [NSLayoutConstraint]() constraints.append(NSLayoutConstraint(item: placeholderImageView, attribute: .Width, relatedBy: .Equal, toItem: mainPreviewView, attribute: .Width, multiplier: 1, constant: 0)) constraints.append(NSLayoutConstraint(item: placeholderImageView, attribute: .Height, relatedBy: .Equal, toItem: mainPreviewView, attribute: .Height, multiplier: 1, constant: 0)) constraints.append(NSLayoutConstraint(item: placeholderImageView, attribute: .CenterX, relatedBy: .Equal, toItem: mainPreviewView, attribute: .CenterX, multiplier: 1, constant: 0)) constraints.append(NSLayoutConstraint(item: placeholderImageView, attribute: .CenterY, relatedBy: .Equal, toItem: mainPreviewView, attribute: .CenterY, multiplier: 1, constant: 0)) placeholderImageViewConstraints = constraints NSLayoutConstraint.activateConstraints(constraints) } } // MARK: - Notification Callbacks @objc private func photoEditModelDidChange(notification: NSNotification) { updateRenderedPreviewForceRender(false) } // MARK: - Setup internal func updateLayoutForNewToolController() { updateRenderedPreviewForceRender(false) previewViewScrollingContainerLayoutValid = false updateLastKnownImageSize() updatePreviewContainerLayout() updateScrollViewZoomScaleAnimated(false) view.layoutIfNeeded() updateScrollViewContentSize() updateBackgroundColor() if let currentEditingTool = delegate?.photoEditViewControllerCurrentEditingTool(self) { previewViewScrollingContainer?.panGestureRecognizer.enabled = currentEditingTool.wantsScrollingInDefaultPreviewViewEnabled previewViewScrollingContainer?.pinchGestureRecognizer?.enabled = currentEditingTool.wantsScrollingInDefaultPreviewViewEnabled } else { previewViewScrollingContainer?.panGestureRecognizer.enabled = true previewViewScrollingContainer?.pinchGestureRecognizer?.enabled = true } } private func loadPhotoEditModelIfNecessary() { if photoEditModel == nil { let editModel = IMGLYPhotoEditMutableModel() if let photoEffectIdentifier = initialPhotoEffectIdentifier where editModel.effectFilterIdentifier != photoEffectIdentifier { editModel.effectFilterIdentifier = photoEffectIdentifier } if let photoEffectIntensity = initialPhotoEffectIntensity where editModel.effectFilterIntensity != CGFloat(photoEffectIntensity) { editModel.effectFilterIntensity = CGFloat(photoEffectIntensity) } loadBaseImageIfNecessary() photoEditModel = editModel uneditedPhotoEditModel = editModel } } private func installGestureRecognizersIfNeeded() { if tapGestureRecognizer == nil { let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(PhotoEditViewController.handleTap(_:))) view.addGestureRecognizer(tapGestureRecognizer) self.tapGestureRecognizer = tapGestureRecognizer } if panGestureRecognizer == nil { let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(PhotoEditViewController.handlePan(_:))) panGestureRecognizer.delegate = self view.addGestureRecognizer(panGestureRecognizer) self.panGestureRecognizer = panGestureRecognizer } if pinchGestureRecognizer == nil { let pinchGestureRecognizer = UIPinchGestureRecognizer(target: self, action: #selector(PhotoEditViewController.handlePinch(_:))) pinchGestureRecognizer.delegate = self view.addGestureRecognizer(pinchGestureRecognizer) self.pinchGestureRecognizer = pinchGestureRecognizer } if rotationGestureRecognizer == nil { let rotationGestureRecognizer = UIRotationGestureRecognizer(target: self, action: #selector(PhotoEditViewController.handleRotation(_:))) rotationGestureRecognizer.delegate = self view.addGestureRecognizer(rotationGestureRecognizer) self.rotationGestureRecognizer = rotationGestureRecognizer } } private func updateToolStackItem() { if collectionView == nil { let flowLayout = UICollectionViewFlowLayout() flowLayout.scrollDirection = .Horizontal flowLayout.minimumLineSpacing = 8 let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: flowLayout) collectionView.showsVerticalScrollIndicator = false collectionView.showsHorizontalScrollIndicator = false collectionView.dataSource = self collectionView.delegate = self collectionView.backgroundColor = UIColor.clearColor() collectionView.registerClass(IconCaptionCollectionViewCell.self, forCellWithReuseIdentifier: PhotoEditViewController.IconCaptionCollectionViewCellReuseIdentifier) collectionView.registerClass(SeparatorCollectionViewCell.self, forCellWithReuseIdentifier: PhotoEditViewController.SeparatorCollectionViewCellReuseIdentifier) self.collectionView = collectionView toolStackItem.performChanges { toolStackItem.mainToolbarView = collectionView if let applyButton = toolStackItem.applyButton { applyButton.addTarget(self, action: #selector(PhotoEditViewController.save(_:)), forControlEvents: .TouchUpInside) applyButton.accessibilityLabel = Localize("Save photo") options.applyButtonConfigurationClosure?(applyButton) } if let discardButton = toolStackItem.discardButton { discardButton.addTarget(self, action: #selector(PhotoEditViewController.cancel(_:)), forControlEvents: .TouchUpInside) discardButton.accessibilityLabel = Localize("Discard photo") options.discardButtonConfigurationClosure?(discardButton) } toolStackItem.titleLabel?.text = options.title } } } private func updateBackgroundColor() { view.backgroundColor = delegate?.photoEditViewControllerCurrentEditingTool(self)?.preferredPreviewBackgroundColor ?? (options.backgroundColor ?? configuration.backgroundColor) } private func loadBaseImageIfNecessary() { if let _ = baseWorkUIImage { return } guard let photo = photo else { return } let screen = UIScreen.mainScreen() var targetSize = workImageSizeForScreen(screen) if photo.size.width > photo.size.height { let aspectRatio = photo.size.height / photo.size.width targetSize = CGSize(width: targetSize.width, height: targetSize.height * aspectRatio) } else if photo.size.width < photo.size.height { let aspectRatio = photo.size.width / photo.size.height targetSize = CGSize(width: targetSize.width * aspectRatio, height: targetSize.height) } dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) { let resizedImage = photo.normalizedImageOfSize(targetSize) dispatch_async(dispatch_get_main_queue()) { self.baseWorkUIImage = resizedImage self.updateRenderedPreviewForceRender(false) } } } private func updateMainRenderer() { if mainRenderer == nil { if let photoEditModel = photoEditModel, baseWorkCIImage = baseWorkCIImage { mainRenderer = PhotoEditRenderer() mainRenderer!.photoEditModel = photoEditModel mainRenderer!.originalImage = baseWorkCIImage updateLastKnownImageSize() view.setNeedsLayout() updateRenderedPreviewForceRender(false) } } } internal func updateLastKnownImageSize() { let workImageSize: CGSize if let renderer = mainRenderer { workImageSize = renderer.outputImageSize } else if let photo = photo { workImageSize = photo.size * UIScreen.mainScreen().scale } else { workImageSize = CGSize.zero } if workImageSize != lastKnownWorkImageSize { lastKnownWorkImageSize = workImageSize updateScrollViewContentSize() updateRenderedPreviewForceRender(false) } } private func updatePlaceholderImage() { if isViewLoaded() { let showPlaceholderImageView: Bool if let _ = baseWorkUIImage { showPlaceholderImageView = false } else { showPlaceholderImageView = true } if let photo = photo where showPlaceholderImageView { if placeholderImageView == nil { placeholderImageView = UIImageView(image: photo) placeholderImageView!.contentMode = .ScaleAspectFit previewViewScrollingContainer?.addSubview(placeholderImageView!) updateSubviewsOrdering() view.setNeedsUpdateConstraints() } placeholderImageView?.hidden = false } else { if let placeholderImageView = placeholderImageView { placeholderImageView.hidden = true if photo == nil { placeholderImageView.removeFromSuperview() self.placeholderImageView = nil placeholderImageViewConstraints = nil } } } } } private func updateSubviewsOrdering() { guard let previewViewScrollingContainer = previewViewScrollingContainer else { return } view.sendSubviewToBack(previewViewScrollingContainer) if let mainPreviewView = mainPreviewView { previewViewScrollingContainer.sendSubviewToBack(mainPreviewView) } if let placeholderImageView = placeholderImageView { previewViewScrollingContainer.sendSubviewToBack(placeholderImageView) } } private func updatePreviewContainerLayout() { if previewViewScrollingContainerLayoutValid { return } guard let previewViewScrollingContainer = previewViewScrollingContainer else { return } if let previewViewScrollingContainerConstraints = previewViewScrollingContainerConstraints { NSLayoutConstraint.deactivateConstraints(previewViewScrollingContainerConstraints) self.previewViewScrollingContainerConstraints = nil } previewViewScrollingContainer.translatesAutoresizingMaskIntoConstraints = false var constraints = [NSLayoutConstraint]() var previewViewInsets = UIEdgeInsets(top: 0, left: 0, bottom: 124, right: 0) if let currentEditingTool = delegate?.photoEditViewControllerCurrentEditingTool(self) { previewViewInsets = previewViewInsets + currentEditingTool.preferredPreviewViewInsets } constraints.append(NSLayoutConstraint(item: previewViewScrollingContainer, attribute: .Left, relatedBy: .Equal, toItem: previewViewScrollingContainer.superview, attribute: .Left, multiplier: 1, constant: previewViewInsets.left)) constraints.append(NSLayoutConstraint(item: previewViewScrollingContainer, attribute: .Right, relatedBy: .Equal, toItem: previewViewScrollingContainer.superview, attribute: .Right, multiplier: 1, constant: -1 * previewViewInsets.right)) constraints.append(NSLayoutConstraint(item: previewViewScrollingContainer, attribute: .Top, relatedBy: .Equal, toItem: previewViewScrollingContainer.superview, attribute: .Top, multiplier: 1, constant: previewViewInsets.top)) constraints.append(NSLayoutConstraint(item: previewViewScrollingContainer, attribute: .Bottom, relatedBy: .Equal, toItem: previewViewScrollingContainer.superview, attribute: .Bottom, multiplier: 1, constant: -1 * previewViewInsets.bottom)) NSLayoutConstraint.activateConstraints(constraints) previewViewScrollingContainerConstraints = constraints previewViewScrollingContainerLayoutValid = true } internal func updateRenderedPreviewForceRender(forceRender: Bool) { mainRenderer?.renderMode = delegate?.photoEditViewControllerCurrentEditingTool(self)?.preferredRenderMode ?? [.AutoEnhancement, .Crop, .Orientation, .Focus, .PhotoEffect, .ColorAdjustments, .RetricaFilter] let updatePreviewView: Bool if let currentEditingTool = delegate?.photoEditViewControllerCurrentEditingTool(self) where !currentEditingTool.wantsDefaultPreviewView { updatePreviewView = false } else { updatePreviewView = baseWorkUIImage == nil ? false : true } mainPreviewView?.hidden = !updatePreviewView if let _ = mainRenderer where updatePreviewView || forceRender { mainPreviewView?.setNeedsDisplay() } frameController?.updatePositioning() } // MARK: - Helpers private func workImageSizeForScreen(screen: UIScreen) -> CGSize { let screenSize = screen.bounds.size let screenScale = screen.scale let scaledScreenSize = screenSize * screenScale let maxLength = max(scaledScreenSize.width, scaledScreenSize.height) return CGSize(width: maxLength, height: maxLength) } private func orientedCIImageFromUIImage(image: UIImage) -> CIImage { guard let cgImage = image.CGImage else { return CIImage.emptyImage() } var ciImage = CIImage(CGImage: cgImage) ciImage = ciImage.imageByApplyingOrientation(Int32(image.imageOrientation.rawValue)) return ciImage } private func scaleSize(size: CGSize, toFitSize targetSize: CGSize) -> CGSize { if size == CGSize.zero { return CGSize.zero } let scale = min(targetSize.width / size.width, targetSize.height / size.height) return size * scale } // MARK: - Tools private func loadToolsIfNeeded() { if toolForAction == nil { var toolForAction = [PhotoEditorAction: PhotoEditToolController]() for i in 0 ..< options.allowedPhotoEditorActions.count { let action = options.allowedPhotoEditorActions[i] if let photoEditModel = photoEditModel, toolController = InstanceFactory.toolControllerForEditorActionType(action, withPhotoEditModel: photoEditModel, configuration: configuration) { toolController.delegate = self toolForAction[action] = toolController } } self.toolForAction = toolForAction } } // MARK: - Overlays @objc private func removeStickerOverlay(overlayView: StickerImageView?) { guard let overlayView = overlayView else { return } configuration.stickerToolControllerOptions.removedStickerClosure?(overlayView.sticker) overlayView.removeFromSuperview() if let elements = previewViewScrollingContainer?.accessibilityElements as? [NSObject], index = elements.indexOf({$0 == overlayView}) { previewViewScrollingContainer?.accessibilityElements?.removeAtIndex(index) } } private func loadFrameControllerIfNeeded() { loadToolsIfNeeded() if let _ = toolForAction?[.Frame] where frameController == nil { frameController = FrameController() frameController!.delegate = self frameController!.imageView = frameImageView frameController!.imageViewContainerView = mainPreviewView if let baseWorkUIImage = baseWorkUIImage { frameController!.imageRatio = Float(baseWorkUIImage.size.width / baseWorkUIImage.size.height) } } } // MARK: - Actions /** Applies all changes to the photo and passes the edited image to the `delegate`. - parameter sender: The object that initiated the request. */ public func save(sender: AnyObject?) { ProgressView.sharedView.showWithMessage(Localize("Exporting image...")) // Load photo from disc if let photoFileURL = photoFileURL, path = photoFileURL.path, photo = UIImage(contentsOfFile: path) { if let mainPreviewView = mainPreviewView where photoEditModel == uneditedPhotoEditModel && mainPreviewView.subviews.count == 0 { ProgressView.sharedView.hide() delegate?.photoEditViewController(self, didSaveImage: photo) } else if let cgImage = photo.CGImage { var ciImage = CIImage(CGImage: cgImage) ciImage = ciImage.imageByApplyingOrientation(Int32(IMGLYOrientation(imageOrientation: photoImageOrientation).rawValue)) let photoEditRenderer = PhotoEditRenderer() photoEditRenderer.photoEditModel = photoEditModel?.mutableCopy() as? IMGLYPhotoEditMutableModel photoEditRenderer.originalImage = ciImage // Generate overlay if needed if let overlayContainerView = self.overlayContainerView where overlayContainerView.subviews.count > 0 { // Scale overlayContainerView to match the size of the high resolution photo let scale = photoEditRenderer.outputImageSize.width / overlayContainerView.bounds.width let scaledSize = overlayContainerView.bounds.size * scale let rect = CGRect(origin: .zero, size: scaledSize) // Create new image context UIGraphicsBeginImageContextWithOptions(scaledSize, false, 1) let cachedTransform = overlayContainerView.transform overlayContainerView.transform = CGAffineTransformScale(overlayContainerView.transform, scale, scale) // Draw the overlayContainerView on top of the image overlayContainerView.drawViewHierarchyInRect(rect, afterScreenUpdates: false) // Restore old transform overlayContainerView.transform = cachedTransform // Fetch image and end context if let cgImage = UIGraphicsGetImageFromCurrentImageContext().CGImage { (photoEditRenderer.photoEditModel as? IMGLYPhotoEditMutableModel)?.overlayImage = CIImage(CGImage: cgImage) } UIGraphicsEndImageContext() } let compressionQuality = CGFloat(0.9) photoEditRenderer.generateOutputImageDataWithCompressionQuality(compressionQuality, metadataSourceImageURL: photoFileURL) { imageData, imageWidth, imageHeight in dispatch_async(dispatch_get_main_queue()) { ProgressView.sharedView.hide() guard let imageData = imageData, image = UIImage(data: imageData) else { dispatch_async(dispatch_get_main_queue()) { ProgressView.sharedView.hide() } self.delegate?.photoEditViewControllerDidFailToGeneratePhoto(self) return } self.delegate?.photoEditViewController(self, didSaveImage: image) // Remove temporary file from disc _ = try? NSFileManager.defaultManager().removeItemAtURL(photoFileURL) } } } } } /** Discards all changes to the photo and call the `delegate`. - parameter sender: The object that initiated the request. */ public func cancel(sender: AnyObject?) { if let photoFileURL = photoFileURL { // Remove temporary file from disc _ = try? NSFileManager.defaultManager().removeItemAtURL(photoFileURL) } delegate?.photoEditViewControllerDidCancel(self) } // MARK: - Gesture Handling private func hideOptionsForOverlayIfNeeded() { if selectedOverlayView == nil { if presentedViewController is ContextMenuController { dismissViewControllerAnimated(true, completion: nil) } if let currentEditingTool = delegate?.photoEditViewControllerCurrentEditingTool(self) { if currentEditingTool is TextOptionsToolController { delegate?.photoEditViewControllerPopToolController(self) } else if currentEditingTool is StickerToolController { delegate?.photoEditViewControllerPopToolController(self) } } } } private func showOptionsForOverlayIfNeeded(view: UIView?) { if let view = view as? StickerImageView { showOptionsForStickerIfNeeded(view) } else if let view = view as? TextLabel { showOptionsForTextIfNeeded(view) } } private func showOptionsForStickerIfNeeded(stickerImageView: StickerImageView) { guard let photoEditModel = photoEditModel else { return } if !(delegate?.photoEditViewControllerCurrentEditingTool(self) is StickerToolController) { // swiftlint:disable force_cast let stickerOptionsToolController = (configuration.getClassForReplacedClass(StickerToolController.self) as! StickerToolController.Type).init(photoEditModel: photoEditModel, configuration: configuration) // swiftlint:enable force_cast stickerOptionsToolController.delegate = self if delegate?.photoEditViewControllerCurrentEditingTool(self) is TextOptionsToolController { delegate?.photoEditViewController(self, didSelectToolController: stickerOptionsToolController, wantsCurrentTopToolControllerReplaced: true) } else { delegate?.photoEditViewController(self, didSelectToolController: stickerOptionsToolController, wantsCurrentTopToolControllerReplaced: false) } } let configurePresentationController = { if let contextMenuPresentationController = self.stickerContextMenuController.presentationController as? ContextMenuPresentationController { var viewController: UIViewController = self while let parent = viewController.parentViewController { viewController = parent } contextMenuPresentationController.passthroughViews = [viewController.view] contextMenuPresentationController.contentFrame = self.previewViewScrollingContainer?.convertRect(self.previewViewScrollingContainer?.bounds ?? .zero, toView: nil) if var contentFrame = contextMenuPresentationController.contentFrame where contentFrame.origin.y < self.topLayoutGuide.length { contentFrame.size.height = contentFrame.size.height - self.topLayoutGuide.length - contentFrame.origin.y contentFrame.origin.y = self.topLayoutGuide.length contextMenuPresentationController.contentFrame = contentFrame } } } if presentedViewController == nil { presentViewController(stickerContextMenuController, animated: true, completion: nil) configurePresentationController() } else if presentedViewController == textContextMenuController { dismissViewControllerAnimated(false) { self.presentViewController(self.stickerContextMenuController, animated: false, completion: nil) configurePresentationController() } } } private func showOptionsForTextIfNeeded(label: TextLabel) { guard let photoEditModel = photoEditModel else { return } if !(delegate?.photoEditViewControllerCurrentEditingTool(self) is TextOptionsToolController) { // swiftlint:disable force_cast let textOptionsToolController = (configuration.getClassForReplacedClass(TextOptionsToolController.self) as! TextOptionsToolController.Type).init(photoEditModel: photoEditModel, configuration: configuration) // swiftlint:enable force_cast textOptionsToolController.delegate = self if delegate?.photoEditViewControllerCurrentEditingTool(self) is TextToolController || delegate?.photoEditViewControllerCurrentEditingTool(self) is StickerToolController { delegate?.photoEditViewController(self, didSelectToolController: textOptionsToolController, wantsCurrentTopToolControllerReplaced: true) } else { delegate?.photoEditViewController(self, didSelectToolController: textOptionsToolController, wantsCurrentTopToolControllerReplaced: false) } } let configurePresentationController = { if let contextMenuPresentationController = self.textContextMenuController.presentationController as? ContextMenuPresentationController { var viewController: UIViewController = self while let parent = viewController.parentViewController { viewController = parent } contextMenuPresentationController.passthroughViews = [viewController.view] contextMenuPresentationController.contentFrame = self.previewViewScrollingContainer?.convertRect(self.previewViewScrollingContainer?.bounds ?? .zero, toView: nil) if var contentFrame = contextMenuPresentationController.contentFrame where contentFrame.origin.y < self.topLayoutGuide.length { contentFrame.size.height = contentFrame.size.height - self.topLayoutGuide.length - contentFrame.origin.y contentFrame.origin.y = self.topLayoutGuide.length contextMenuPresentationController.contentFrame = contentFrame } } } if presentedViewController == nil { presentViewController(textContextMenuController, animated: true, completion: nil) configurePresentationController() } else if presentedViewController == stickerContextMenuController { dismissViewControllerAnimated(false) { self.presentViewController(self.textContextMenuController, animated: false, completion: nil) configurePresentationController() } } } @objc private func handleTap(gestureRecognizer: UITapGestureRecognizer) { let view = gestureRecognizer.view let location = gestureRecognizer.locationInView(view) let target = view?.hitTest(location, withEvent: nil) if let target = target as? StickerImageView { selectedOverlayView = target showOptionsForStickerIfNeeded(target) } else if let target = target as? TextLabel { selectedOverlayView = target showOptionsForTextIfNeeded(target) } else { selectedOverlayView = nil hideOptionsForOverlayIfNeeded() undoManager?.removeAllActions() } } @objc private func handlePan(gestureRecognizer: UIPanGestureRecognizer) { guard let mainPreviewView = mainPreviewView, mainRenderer = mainRenderer else { return } let location = gestureRecognizer.locationInView(mainPreviewView) let translation = gestureRecognizer.translationInView(mainPreviewView) let targetView = mainPreviewView.hitTest(location, withEvent: nil) switch gestureRecognizer.state { case .Began: if targetView is StickerImageView || targetView is TextLabel { draggedOverlayView = targetView selectedOverlayView = targetView showOptionsForOverlayIfNeeded(targetView) } case .Changed: if let draggedOverlayView = draggedOverlayView { let center = draggedOverlayView.center undoManager?.registerUndoForTarget(draggedOverlayView) { view in view.center = center } draggedOverlayView.center = center + translation } let renderMode = mainRenderer.renderMode mainRenderer.renderMode = mainRenderer.renderMode.subtract(.Crop) let outputImageSize = mainRenderer.outputImageSize mainRenderer.renderMode = renderMode if let stickerImageView = draggedOverlayView as? StickerImageView, photoEditModel = photoEditModel { stickerImageView.normalizedCenterInImage = normalizePoint(stickerImageView.center, inView: mainPreviewView, baseImageSize: outputImageSize, normalizedCropRect: photoEditModel.normalizedCropRect) } else if let textLabel = draggedOverlayView as? TextLabel, photoEditModel = photoEditModel { textLabel.normalizedCenterInImage = normalizePoint(textLabel.center, inView: mainPreviewView, baseImageSize: outputImageSize, normalizedCropRect: photoEditModel.normalizedCropRect) } gestureRecognizer.setTranslation(CGPoint.zero, inView: mainPreviewView) case .Cancelled, .Ended: draggedOverlayView = nil default: break } } @objc private func handlePinch(gestureRecognizer: UIPinchGestureRecognizer) { guard let mainPreviewView = mainPreviewView else { return } if gestureRecognizer.numberOfTouches() >= 2 { let point1 = gestureRecognizer.locationOfTouch(0, inView: mainPreviewView) let point2 = gestureRecognizer.locationOfTouch(1, inView: mainPreviewView) let midPoint = point1 + CGVector(startPoint: point1, endPoint: point2) * 0.5 let scale = gestureRecognizer.scale let targetView = mainPreviewView.hitTest(midPoint, withEvent: nil) switch gestureRecognizer.state { case .Began: if targetView is StickerImageView || targetView is TextLabel { draggedOverlayView = targetView selectedOverlayView = targetView showOptionsForOverlayIfNeeded(targetView) } case .Changed: if let draggedOverlayView = draggedOverlayView as? StickerImageView { let transform = draggedOverlayView.transform undoManager?.registerUndoForTarget(draggedOverlayView) { view in draggedOverlayView.transform = transform } draggedOverlayView.transform = CGAffineTransformScale(transform, scale, scale) if let selectedOverlayView = selectedOverlayView { selectedOverlayView.layer.borderWidth = 2 / (0.5 * (draggedOverlayView.transform.xScale + draggedOverlayView.transform.yScale)) } } else if let draggedOverlayView = draggedOverlayView as? TextLabel { let fontSize = draggedOverlayView.font.pointSize undoManager?.registerUndoForTarget(draggedOverlayView) { view in view.font = draggedOverlayView.font.fontWithSize(fontSize) view.sizeToFit() } draggedOverlayView.font = draggedOverlayView.font.fontWithSize(fontSize * scale) draggedOverlayView.sizeToFit() } gestureRecognizer.scale = 1 case .Cancelled, .Ended: draggedOverlayView = nil default: break } } } @objc private func handleRotation(gestureRecognizer: UIRotationGestureRecognizer) { guard let mainPreviewView = mainPreviewView else { return } if gestureRecognizer.numberOfTouches() >= 2 { let point1 = gestureRecognizer.locationOfTouch(0, inView: mainPreviewView) let point2 = gestureRecognizer.locationOfTouch(1, inView: mainPreviewView) let midPoint = point1 + CGVector(startPoint: point1, endPoint: point2) * 0.5 let rotation = gestureRecognizer.rotation let targetView = mainPreviewView.hitTest(midPoint, withEvent: nil) switch gestureRecognizer.state { case .Began: if targetView is StickerImageView || targetView is TextLabel { draggedOverlayView = targetView selectedOverlayView = targetView showOptionsForOverlayIfNeeded(targetView) } case .Changed: if let draggedOverlayView = draggedOverlayView { let transform = draggedOverlayView.transform undoManager?.registerUndoForTarget(draggedOverlayView) { view in draggedOverlayView.transform = transform } draggedOverlayView.transform = CGAffineTransformRotate(transform, rotation) } gestureRecognizer.rotation = 0 case .Cancelled, .Ended: draggedOverlayView = nil default: break } } } // MARK: - Orientation Handling private func normalizePoint(point: CGPoint, inView view: UIView, baseImageSize: CGSize, normalizedCropRect: CGRect) -> CGPoint { if normalizedCropRect == IMGLYPhotoEditModel.identityNormalizedCropRect() { return CGPoint(x: point.x / view.bounds.width, y: point.y / view.bounds.height) } let convertedNormalizedCropRect = CGRect(x: normalizedCropRect.origin.x, y: 1 - normalizedCropRect.origin.y - normalizedCropRect.size.height, width: normalizedCropRect.size.width, height: normalizedCropRect.size.height) let denormalizedCropRect = CGRect( x: convertedNormalizedCropRect.origin.x * baseImageSize.width, y: convertedNormalizedCropRect.origin.y * baseImageSize.height, width: convertedNormalizedCropRect.size.width * baseImageSize.width, height: convertedNormalizedCropRect.size.height * baseImageSize.height ) let viewToCroppedImageScale = denormalizedCropRect.size.width / view.bounds.width let pointInCropRect = CGPoint(x: point.x * viewToCroppedImageScale, y: point.y * viewToCroppedImageScale) let pointInImage = CGPoint(x: pointInCropRect.x + denormalizedCropRect.origin.x, y: pointInCropRect.y + denormalizedCropRect.origin.y) return CGPoint(x: pointInImage.x / baseImageSize.width, y: pointInImage.y / baseImageSize.height) } private func updateFromOrientation(fromOrientation: IMGLYOrientation, toOrientation: IMGLYOrientation) { if fromOrientation != toOrientation { updateCropRectFromOrientation(fromOrientation, toOrientation: toOrientation) updateOverlaysFromOrientation(fromOrientation, toOrientation: toOrientation) updateFocusControlPointsFromOrientation(fromOrientation, toOrientation: toOrientation) } } private func updateOverlaysFromOrientation(fromOrientation: IMGLYOrientation, toOrientation: IMGLYOrientation) { guard let overlayContainerView = overlayContainerView, mainPreviewView = mainPreviewView, mainRenderer = mainRenderer, containerBounds = previewViewScrollingContainer?.bounds else { return } let outputImageSize = mainRenderer.outputImageSize let newPreviewSize = scaleSize(outputImageSize, toFitSize: containerBounds.size) let scale: CGFloat if newPreviewSize == mainPreviewView.bounds.size { scale = 1 } else { scale = min(newPreviewSize.width / overlayContainerView.bounds.height, newPreviewSize.height / overlayContainerView.bounds.width) } let geometry = ImageGeometry(inputSize: overlayContainerView.bounds.size) geometry.appliedOrientation = toOrientation let transform = geometry.transformFromOrientation(fromOrientation) for overlay in overlayContainerView.subviews { if overlay is StickerImageView || overlay is TextLabel { overlay.center = CGPointApplyAffineTransform(overlay.center, transform) overlay.center = CGPoint(x: overlay.center.x * scale, y: overlay.center.y * scale) overlay.transform = CGAffineTransformScale(overlay.transform, scale, scale) var stickerTransform = transform stickerTransform.tx = 0 stickerTransform.ty = 0 overlay.transform = CGAffineTransformConcat(overlay.transform, stickerTransform) } if let stickerImageView = overlay as? StickerImageView { let normalizedGeometry = ImageGeometry(inputSize: CGSize(width: 1, height: 1)) normalizedGeometry.appliedOrientation = geometry.appliedOrientation stickerImageView.normalizedCenterInImage = CGPointApplyAffineTransform(stickerImageView.normalizedCenterInImage, normalizedGeometry.transformFromOrientation(fromOrientation)) } else if let textLabel = overlay as? TextLabel { let normalizedGeometry = ImageGeometry(inputSize: CGSize(width: 1, height: 1)) normalizedGeometry.appliedOrientation = geometry.appliedOrientation textLabel.normalizedCenterInImage = CGPointApplyAffineTransform(textLabel.normalizedCenterInImage, normalizedGeometry.transformFromOrientation(fromOrientation)) } } } private func updateCropRectFromOrientation(fromOrientation: IMGLYOrientation, toOrientation: IMGLYOrientation) { guard let photoEditModel = photoEditModel else { return } let geometry = ImageGeometry(inputSize: CGSize(width: 1, height: 1)) geometry.appliedOrientation = toOrientation let transform = geometry.transformFromOrientation(fromOrientation) var normalizedCropRect = photoEditModel.normalizedCropRect // Change origin from bottom left to top left, otherwise the transform won't work normalizedCropRect = CGRect(x: normalizedCropRect.origin.x, y: 1 - normalizedCropRect.origin.y - normalizedCropRect.height, width: normalizedCropRect.width, height: normalizedCropRect.height) // Apply transform normalizedCropRect = CGRectApplyAffineTransform(normalizedCropRect, transform) // Change origin from top left to bottom left again normalizedCropRect = CGRect(x: normalizedCropRect.origin.x, y: 1 - normalizedCropRect.origin.y - normalizedCropRect.height, width: normalizedCropRect.width, height: normalizedCropRect.height) photoEditModel.normalizedCropRect = normalizedCropRect } private func updateFocusControlPointsFromOrientation(fromOrientation: IMGLYOrientation, toOrientation: IMGLYOrientation) { guard let photoEditModel = photoEditModel else { return } let geometry = ImageGeometry(inputSize: CGSize(width: 1, height: 1)) geometry.appliedOrientation = toOrientation let transform = geometry.transformFromOrientation(fromOrientation) var controlPoint1 = photoEditModel.focusNormalizedControlPoint1 var controlPoint2 = photoEditModel.focusNormalizedControlPoint2 // Change origin from bottom left to top left, otherwise the transform won't work controlPoint1 = CGPoint(x: controlPoint1.x, y: 1 - controlPoint1.y) controlPoint2 = CGPoint(x: controlPoint2.x, y: 1 - controlPoint2.y) // Apply transform controlPoint1 = CGPointApplyAffineTransform(controlPoint1, transform) controlPoint2 = CGPointApplyAffineTransform(controlPoint2, transform) // Change origin from top left to bottom left again controlPoint1 = CGPoint(x: controlPoint1.x, y: 1 - controlPoint1.y) controlPoint2 = CGPoint(x: controlPoint2.x, y: 1 - controlPoint2.y) photoEditModel.focusNormalizedControlPoint1 = controlPoint1 photoEditModel.focusNormalizedControlPoint2 = controlPoint2 } } @available(iOS 8, *) extension PhotoEditViewController: GLKViewDelegate { /** :nodoc: */ public func glkView(view: GLKView, drawInRect rect: CGRect) { if let renderer = mainRenderer { renderer.drawOutputImageInContext(view.context, inRect: CGRect(x: 0, y: 0, width: view.drawableWidth, height: view.drawableHeight), viewportWidth: view.drawableWidth, viewportHeight: view.drawableHeight) nextRenderCompletionBlock?() nextRenderCompletionBlock = nil } } } @available(iOS 8, *) extension PhotoEditViewController: UIScrollViewDelegate { private func updateScrollViewCentering() { guard let previewViewScrollingContainer = previewViewScrollingContainer else { return } let containerSize = previewViewScrollingContainer.bounds.size let contentSize = previewViewScrollingContainer.contentSize let horizontalCenterOffset: CGFloat if contentSize.width < containerSize.width { horizontalCenterOffset = (containerSize.width - contentSize.width) * 0.5 } else { horizontalCenterOffset = 0 } let verticalCenterOffset: CGFloat if contentSize.height < containerSize.height { verticalCenterOffset = (containerSize.height - contentSize.height) * 0.5 } else { verticalCenterOffset = 0 } mainPreviewView?.center = CGPoint( x: contentSize.width * 0.5 + horizontalCenterOffset, y: contentSize.height * 0.5 + verticalCenterOffset ) } private func updateScrollViewContentSize() { guard let previewViewScrollingContainer = previewViewScrollingContainer else { return } let zoomScale = previewViewScrollingContainer.zoomScale let workImageSize = lastKnownWorkImageSize let containerSize = previewViewScrollingContainer.bounds.size let fittedSize = scaleSize(workImageSize, toFitSize: containerSize) if lastKnownPreviewViewSize != fittedSize { previewViewScrollingContainer.zoomScale = 1 lastKnownPreviewViewSize = fittedSize mainPreviewView?.frame = CGRect(x: 0, y: 0, width: fittedSize.width, height: fittedSize.height) overlayContainerView?.frame = CGRect(x: 0, y: 0, width: fittedSize.width, height: fittedSize.height) previewViewScrollingContainer.contentSize = fittedSize previewViewScrollingContainer.zoomScale = zoomScale } updateScrollViewCentering() } private func updateScrollViewZoomScaleAnimated(animated: Bool) { if selectedOverlayView != nil { previewViewScrollingContainer?.minimumZoomScale = delegate?.photoEditViewControllerCurrentEditingTool(self)?.preferredDefaultPreviewViewScale ?? 1 previewViewScrollingContainer?.maximumZoomScale = delegate?.photoEditViewControllerCurrentEditingTool(self)?.preferredDefaultPreviewViewScale ?? 1 previewViewScrollingContainer?.setZoomScale(delegate?.photoEditViewControllerCurrentEditingTool(self)?.preferredDefaultPreviewViewScale ?? 1, animated: animated) previewViewScrollingContainer?.scrollEnabled = false } else { previewViewScrollingContainer?.minimumZoomScale = min(delegate?.photoEditViewControllerCurrentEditingTool(self)?.preferredDefaultPreviewViewScale ?? 1, 1) previewViewScrollingContainer?.maximumZoomScale = max(delegate?.photoEditViewControllerCurrentEditingTool(self)?.preferredDefaultPreviewViewScale ?? 1, 3) previewViewScrollingContainer?.setZoomScale(delegate?.photoEditViewControllerCurrentEditingTool(self)?.preferredDefaultPreviewViewScale ?? 1, animated: animated) previewViewScrollingContainer?.scrollEnabled = true } } /** :nodoc: */ public func scrollViewDidZoom(scrollView: UIScrollView) { if previewViewScrollingContainer == scrollView { updateScrollViewCentering() } } /** :nodoc: */ public func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) { if previewViewScrollingContainer == scrollView { mainPreviewView?.contentScaleFactor = scale * UIScreen.mainScreen().scale updateRenderedPreviewForceRender(false) } } /** :nodoc: */ public func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? { if !options.allowsPreviewImageZoom { return nil } if previewViewScrollingContainer == scrollView { return mainPreviewView } return nil } } @available(iOS 8, *) extension PhotoEditViewController: UICollectionViewDataSource { /** :nodoc: */ public func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return options.allowedPhotoEditorActions.count } /** :nodoc: */ public func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let actionType = options.allowedPhotoEditorActions[indexPath.item] if actionType == .Separator { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PhotoEditViewController.SeparatorCollectionViewCellReuseIdentifier, forIndexPath: indexPath) if let separatorCell = cell as? SeparatorCollectionViewCell { separatorCell.separator.backgroundColor = configuration.separatorColor } return cell } let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PhotoEditViewController.IconCaptionCollectionViewCellReuseIdentifier, forIndexPath: indexPath) if let iconCaptionCell = cell as? IconCaptionCollectionViewCell { switch actionType { case .Separator: fallthrough case .Crop: iconCaptionCell.imageView.image = UIImage(named: "imgly_icon_tool_crop", inBundle: NSBundle.imglyKitBundle, compatibleWithTraitCollection: nil)?.imageWithRenderingMode(.AlwaysTemplate) iconCaptionCell.captionLabel.text = Localize("Crop") iconCaptionCell.accessibilityLabel = Localize("Crop") case .Orientation: iconCaptionCell.imageView.image = UIImage(named: "imgly_icon_tool_orientation", inBundle: NSBundle.imglyKitBundle, compatibleWithTraitCollection: nil)?.imageWithRenderingMode(.AlwaysTemplate) iconCaptionCell.captionLabel.text = Localize("Orientation") iconCaptionCell.accessibilityLabel = Localize("Orientation") case .Filter: iconCaptionCell.imageView.image = UIImage(named: "imgly_icon_tool_filters", inBundle: NSBundle.imglyKitBundle, compatibleWithTraitCollection: nil)?.imageWithRenderingMode(.AlwaysTemplate) iconCaptionCell.captionLabel.text = Localize("Filter") iconCaptionCell.accessibilityLabel = Localize("Filter") case .RetricaFilter: iconCaptionCell.imageView.image = UIImage(named: "imgly_icon_tool_filters", inBundle: NSBundle.imglyKitBundle, compatibleWithTraitCollection: nil)?.imageWithRenderingMode(.AlwaysTemplate) iconCaptionCell.captionLabel.text = Localize("Filter") iconCaptionCell.accessibilityLabel = Localize("Filter") case .Adjust: iconCaptionCell.imageView.image = UIImage(named: "imgly_icon_tool_adjust", inBundle: NSBundle.imglyKitBundle, compatibleWithTraitCollection: nil)?.imageWithRenderingMode(.AlwaysTemplate) iconCaptionCell.captionLabel.text = Localize("Adjust") iconCaptionCell.accessibilityLabel = Localize("Adjust") case .Text: iconCaptionCell.imageView.image = UIImage(named: "imgly_icon_tool_text", inBundle: NSBundle.imglyKitBundle, compatibleWithTraitCollection: nil)?.imageWithRenderingMode(.AlwaysTemplate) iconCaptionCell.captionLabel.text = Localize("Text") iconCaptionCell.accessibilityLabel = Localize("Text") case .Sticker: iconCaptionCell.imageView.image = UIImage(named: "imgly_icon_tool_sticker", inBundle: NSBundle.imglyKitBundle, compatibleWithTraitCollection: nil)?.imageWithRenderingMode(.AlwaysTemplate) iconCaptionCell.captionLabel.text = Localize("Sticker") iconCaptionCell.accessibilityLabel = Localize("Sticker") case .Focus: iconCaptionCell.imageView.image = UIImage(named: "imgly_icon_tool_focus", inBundle: NSBundle.imglyKitBundle, compatibleWithTraitCollection: nil)?.imageWithRenderingMode(.AlwaysTemplate) iconCaptionCell.captionLabel.text = Localize("Focus") iconCaptionCell.accessibilityLabel = Localize("Focus") case .Frame: iconCaptionCell.imageView.image = UIImage(named: "imgly_icon_tool_frame", inBundle: NSBundle.imglyKitBundle, compatibleWithTraitCollection: nil)?.imageWithRenderingMode(.AlwaysTemplate) iconCaptionCell.captionLabel.text = Localize("Frame") iconCaptionCell.accessibilityLabel = Localize("Frame") case .Magic: iconCaptionCell.imageView.image = UIImage(named: "imgly_icon_tool_magic", inBundle: NSBundle.imglyKitBundle, compatibleWithTraitCollection: nil)?.imageWithRenderingMode(.AlwaysTemplate) iconCaptionCell.captionLabel.text = Localize("Magic") iconCaptionCell.accessibilityLabel = Localize("Magic") } options.actionButtonConfigurationClosure?(iconCaptionCell, actionType) } return cell } } @available(iOS 8, *) extension PhotoEditViewController: UICollectionViewDelegate, UICollectionViewDelegateFlowLayout { /** :nodoc: */ public func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { let actionType = options.allowedPhotoEditorActions[indexPath.item] if actionType == .Separator { return PhotoEditViewController.SeparatorCollectionViewCellSize } return PhotoEditViewController.IconCaptionCollectionViewCellSize } /** :nodoc: */ public func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets { guard let flowLayout = collectionViewLayout as? UICollectionViewFlowLayout else { return UIEdgeInsetsZero } let cellSpacing = flowLayout.minimumInteritemSpacing let cellCount = collectionView.numberOfItemsInSection(section) let collectionViewWidth = collectionView.bounds.size.width var totalCellWidth: CGFloat = 0 for i in 0..<cellCount { let itemSize = self.collectionView(collectionView, layout: collectionViewLayout, sizeForItemAtIndexPath: NSIndexPath(forItem: i, inSection: section)) totalCellWidth = totalCellWidth + itemSize.width } let totalCellSpacing = cellSpacing * (CGFloat(cellCount) - 1) let totalCellsWidth = totalCellWidth + totalCellSpacing let edgeInsets = max((collectionViewWidth - totalCellsWidth) / 2.0, cellSpacing) return UIEdgeInsets(top: 0, left: edgeInsets, bottom: 0, right: edgeInsets) } /** :nodoc: */ public func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { let actionType = options.allowedPhotoEditorActions[indexPath.item] if actionType == .Separator { return } options.photoEditorActionSelectedClosure?(actionType) if actionType == .Magic { guard let photoEditModel = photoEditModel else { return } photoEditModel.performChangesWithBlock { photoEditModel.autoEnhancementEnabled = !photoEditModel.autoEnhancementEnabled } } else { selectedOverlayView = nil hideOptionsForOverlayIfNeeded() if let toolController = toolForAction?[actionType] { delegate?.photoEditViewController(self, didSelectToolController: toolController, wantsCurrentTopToolControllerReplaced: false) } } collectionView.reloadItemsAtIndexPaths([indexPath]) } /** :nodoc: */ public func collectionView(collectionView: UICollectionView, willDisplayCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) { let actionType = options.allowedPhotoEditorActions[indexPath.item] if actionType == .Magic { if let iconCaptionCell = cell as? IconCaptionCollectionViewCell { if photoEditModel?.autoEnhancementEnabled ?? false { iconCaptionCell.accessibilityTraits |= UIAccessibilityTraitSelected iconCaptionCell.imageView.image = iconCaptionCell.imageView.image?.imageWithRenderingMode(.AlwaysTemplate) iconCaptionCell.imageView.tintAdjustmentMode = .Dimmed } else { iconCaptionCell.accessibilityTraits &= ~UIAccessibilityTraitSelected iconCaptionCell.imageView.image = iconCaptionCell.imageView.image?.imageWithRenderingMode(.AlwaysTemplate) iconCaptionCell.imageView.tintAdjustmentMode = .Normal } } } } } @available(iOS 8, *) extension PhotoEditViewController: PhotoEditToolControllerDelegate { /** :nodoc: */ public func photoEditToolControllerMainRenderer(photoEditToolController: PhotoEditToolController) -> PhotoEditRenderer? { return mainRenderer } /** :nodoc: */ public func photoEditToolControllerBaseImage(photoEditToolController: PhotoEditToolController) -> UIImage? { return baseWorkUIImage } /** :nodoc: */ public func photoEditToolControllerPreviewViewScrollingContainer(photoEditToolController: PhotoEditToolController) -> UIScrollView? { return previewViewScrollingContainer } /** :nodoc: */ public func photoEditToolControllerPreviewView(photoEditToolController: PhotoEditToolController) -> UIView? { return mainPreviewView } /** :nodoc: */ public func photoEditToolControllerOverlayContainerView(photoEditToolController: PhotoEditToolController) -> UIView? { return overlayContainerView } /** :nodoc: */ public func photoEditToolControllerOverlayViews(photoEditToolController: PhotoEditToolController) -> [UIView]? { return overlayContainerView?.subviews } /** :nodoc: */ public func photoEditToolControllerFrameController(photoEditToolController: PhotoEditToolController) -> FrameController? { return frameController } /** :nodoc: */ public func photoEditToolControllerDidFinish(photoEditToolController: PhotoEditToolController) { if presentedViewController is ContextMenuController && !(photoEditToolController is TextFontToolController || photoEditToolController is TextColorToolController) { selectedOverlayView = nil dismissViewControllerAnimated(true, completion: nil) } delegate?.photoEditViewControllerPopToolController(self) } /** :nodoc: */ public func photoEditToolController(photoEditToolController: PhotoEditToolController, didDiscardChangesInFavorOfPhotoEditModel photoEditModel: IMGLYPhotoEditModel) { if presentedViewController is ContextMenuController && !(photoEditToolController is TextFontToolController || photoEditToolController is TextColorToolController) { selectedOverlayView = nil dismissViewControllerAnimated(true, completion: nil) } if let discardedPhotoEditModel = self.photoEditModel { updateFromOrientation(discardedPhotoEditModel.appliedOrientation, toOrientation: photoEditModel.appliedOrientation) } self.photoEditModel?.copyValuesFromModel(photoEditModel) delegate?.photoEditViewControllerPopToolController(self) } /** :nodoc: */ public func photoEditToolController(photoEditToolController: PhotoEditToolController, didChangeToOrientation orientation: IMGLYOrientation, fromOrientation: IMGLYOrientation) { updateFromOrientation(fromOrientation, toOrientation: orientation) } /** :nodoc: */ public func photoEditToolControllerDidChangePreferredRenderMode(photoEditToolController: PhotoEditToolController) { updateRenderedPreviewForceRender(false) } /** :nodoc: */ public func photoEditToolControllerDidChangeWantsDefaultPreviewView(photoEditToolController: PhotoEditToolController) { updateRenderedPreviewForceRender(false) } /** :nodoc: */ public func photoEditToolController(photoEditToolController: PhotoEditToolController, didAddOverlayView view: UIView) { guard let mainRenderer = mainRenderer else { return } let renderMode = mainRenderer.renderMode mainRenderer.renderMode = mainRenderer.renderMode.subtract(.Crop) let outputImageSize = mainRenderer.outputImageSize mainRenderer.renderMode = renderMode if let stickerImageView = view as? StickerImageView, photoEditModel = photoEditModel, mainPreviewView = mainPreviewView { undoManager?.registerUndoForTarget(self) { photoEditViewController in photoEditViewController.removeStickerOverlay(stickerImageView) } stickerImageView.normalizedCenterInImage = normalizePoint(stickerImageView.center, inView: mainPreviewView, baseImageSize: outputImageSize, normalizedCropRect: photoEditModel.normalizedCropRect) } else if let textLabel = view as? TextLabel, photoEditModel = photoEditModel, mainPreviewView = mainPreviewView { textLabel.activateHandler = { [weak self, unowned textLabel] in self?.selectedOverlayView = textLabel self?.showOptionsForTextIfNeeded(textLabel) } textLabel.normalizedCenterInImage = normalizePoint(textLabel.center, inView: mainPreviewView, baseImageSize: outputImageSize, normalizedCropRect: photoEditModel.normalizedCropRect) } selectedOverlayView = view showOptionsForOverlayIfNeeded(view) previewViewScrollingContainer?.accessibilityElements?.append(view) } /** :nodoc: */ public func photoEditToolController(photoEditToolController: PhotoEditToolController, didSelectToolController toolController: PhotoEditToolController) { delegate?.photoEditViewController(self, didSelectToolController: toolController, wantsCurrentTopToolControllerReplaced: false) } /** :nodoc: */ public func photoEditToolControllerSelectedOverlayView(photoEditToolController: PhotoEditToolController) -> UIView? { return selectedOverlayView } } @available(iOS 8, *) extension PhotoEditViewController: UIGestureRecognizerDelegate { /** :nodoc: */ public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true } /** :nodoc: */ public func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool { if gestureRecognizer == panGestureRecognizer || gestureRecognizer == pinchGestureRecognizer || gestureRecognizer == rotationGestureRecognizer { if presentedViewController == stickerContextMenuController { return true } if presentedViewController == textContextMenuController { return true } return false } return true } } @available(iOS 8, *) extension PhotoEditViewController: FrameControllerDelegate { /** :nodoc: */ public func frameControllerBaseImageSize(frameController: FrameController) -> CGSize { guard let mainRenderer = mainRenderer else { return .zero } let renderMode = mainRenderer.renderMode mainRenderer.renderMode = mainRenderer.renderMode.subtract(.Crop) let outputImageSize = mainRenderer.outputImageSize mainRenderer.renderMode = renderMode return outputImageSize } /** :nodoc: */ public func frameControllerNormalizedCropRect(frameController: FrameController) -> CGRect { return photoEditModel?.normalizedCropRect ?? .zero } }
86ba10c7529fb5d8d574a68fabb532d9
43.232855
247
0.684335
false
false
false
false
davecom/DKDropMenu
refs/heads/master
DKDropMenu.swift
mit
1
//The DKDropMenu License // //Copyright (c) 2015-2016 David Kopec // //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. // // DKDropMenu.swift // DKDropMenu // // Created by David Kopec on 6/5/15. // Copyright (c) 2015 Oak Snow Consulting. All rights reserved. // import UIKit /// Delegate protocol for receiving change in list selection @objc public protocol DKDropMenuDelegate { func itemSelected(withIndex: Int, name:String) @objc optional func collapsedChanged() } /// A simple drop down list like expandable menu for iOS @IBDesignable public class DKDropMenu: UIView { @IBInspectable public var itemHeight: CGFloat = 44 @IBInspectable public var selectedFontName: String = "HelveticaNeue-Bold" @IBInspectable public var listFontName: String = "HelveticaNeue-Thin" @IBInspectable public var textColor: UIColor = UIColor.darkGray @IBInspectable public var outlineColor: UIColor = UIColor.lightGray @IBInspectable public var selectedColor: UIColor = UIColor.green weak public var delegate: DKDropMenuDelegate? = nil //notified when a selection occurs private var items: [String] = [String]() public var selectedItem: String? = nil { didSet { setNeedsDisplay() } } public var collapsed: Bool = true { didSet { delegate?.collapsedChanged?() //animate collapsing or opening UIView.animate(withDuration: 0.5, delay: 0, options: .transitionCrossDissolve, animations: { var tempFrame = self.frame if (self.collapsed) { tempFrame.size.height = self.itemHeight } else { if (self.items.count > 1 && self.selectedItem != nil) { tempFrame.size.height = self.itemHeight * CGFloat(self.items.count) } else if (self.items.count > 0 && self.selectedItem == nil) { tempFrame.size.height = self.itemHeight * CGFloat(self.items.count) + self.itemHeight } } self.frame = tempFrame self.invalidateIntrinsicContentSize() }, completion: nil) setNeedsDisplay() } } // MARK: Overridden standard UIView methods override public func sizeThatFits(_ size: CGSize) -> CGSize { if (items.count < 2 || collapsed) { return CGSize(width: size.width, height: itemHeight) } else { return CGSize(width: size.width, height: (itemHeight * CGFloat(items.count))) } } override public var intrinsicContentSize: CGSize { if (items.count < 2 || collapsed) { return CGSize(width: bounds.size.width, height: itemHeight) } else { return CGSize(width: bounds.size.width, height: (itemHeight * CGFloat(items.count))) } } override public func draw(_ rect: CGRect) { // Drawing code //draw first box regardless let context = UIGraphicsGetCurrentContext() outlineColor.setStroke() context?.setLineWidth(1.0) context?.move(to: CGPoint(x: 0, y: itemHeight)) context?.addLine(to: CGPoint(x: 0, y: 0.5)) context?.addLine(to: CGPoint(x: frame.size.width, y: 0.5)) context?.addLine(to: CGPoint(x: frame.size.width, y: itemHeight)) context?.strokePath() if let sele = selectedItem { //draw item text let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.alignment = .center let attrs = [NSAttributedStringKey.font: UIFont(name: selectedFontName, size: 16)!, NSAttributedStringKey.paragraphStyle: paragraphStyle, NSAttributedStringKey.foregroundColor: textColor] if (collapsed) { let tempS = "\(sele)" //put chevron down facing here if right unicode found tempS.draw(in: CGRect(x: 20, y: itemHeight / 2 - 10, width: frame.size.width - 40, height: 20), withAttributes: attrs) } else { let tempS = "\(sele)" //put chevron up facing here if right unicode found tempS.draw(in: CGRect(x: 20, y: itemHeight / 2 - 10, width: frame.size.width - 40, height: 20), withAttributes: attrs) } //draw selected line selectedColor.setStroke() context?.move(to: CGPoint(x: 0, y: itemHeight - 2)) context?.setLineWidth(4.0) context?.addLine(to: CGPoint(x: frame.width, y: itemHeight - 2)) context?.strokePath() } else { context?.move(to: CGPoint(x: 0, y: itemHeight - 1)) context?.setLineWidth(1.0) context?.addLine(to: CGPoint(x: frame.width, y: itemHeight - 1)) context?.strokePath() } //draw lower boxes if (!collapsed && items.count > 1) { var currentY = itemHeight for item in items { if item == selectedItem { continue } //draw box outlineColor.setStroke() context?.setLineWidth(1.0) context?.move(to: CGPoint(x: 0, y: currentY)) context?.addLine(to: CGPoint(x: 0, y: currentY + itemHeight)) context?.strokePath() context?.setLineWidth(0.5) context?.move(to: CGPoint(x: 0, y: currentY + itemHeight - 1)) context?.addLine(to: CGPoint(x: frame.size.width, y: currentY + itemHeight - 1)) context?.strokePath() context?.setLineWidth(1.0) context?.move(to: CGPoint(x: frame.size.width, y: currentY + itemHeight)) context?.addLine(to: CGPoint(x: frame.size.width, y: currentY)) context?.strokePath() //draw item text let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.alignment = .center let attrs = [NSAttributedStringKey.font: UIFont(name: listFontName, size: 16)!, NSAttributedStringKey.paragraphStyle: paragraphStyle, NSAttributedStringKey.foregroundColor: textColor] item.draw(in: CGRect(x: 20, y: currentY + (itemHeight / 2 - 10), width: frame.size.width - 40, height: 20), withAttributes: attrs) currentY += itemHeight } } } // MARK: Add or remove items /// Add an array of items to the menu public func add(names: [String]) { for name in names { add(name: name) } } /// Add a single item to the menu public func add(name: String) { //if we have no selected items, we'll take it if items.isEmpty { selectedItem = name } items.append(name) //animate change if (!collapsed && items.count > 1) { UIView.animate(withDuration: 0.7, delay: 0, options: .curveEaseOut, animations: { var tempFrame = self.frame tempFrame.size.height = self.itemHeight * CGFloat(self.items.count) self.frame = tempFrame }, completion: nil) } //refresh display setNeedsDisplay() } /// Remove a single item from the menu public func remove(at index: Int) { if (items[index] == selectedItem) { selectedItem = nil } items.remove(at: index) //animate change if (!collapsed && items.count > 1) { UIView.animate(withDuration: 0.7, delay: 0, options: .curveEaseOut, animations: { var tempFrame = self.frame tempFrame.size.height = self.itemHeight * CGFloat(self.items.count) self.frame = tempFrame }, completion: nil) } else if (!collapsed) { UIView.animate(withDuration: 0.7, delay: 0, options: .curveEaseOut, animations: { var tempFrame = self.frame tempFrame.size.height = self.itemHeight self.frame = tempFrame }, completion: nil) } setNeedsDisplay() } /// Remove the first occurence of item named *name* public func remove(name: String) { if let index = items.index(of: name) { remove(at: index) } } /// Remove all items public func removeAll() { selectedItem = nil items.removeAll() if (!collapsed) { UIView.animate(withDuration: 0.7, delay: 0, options: .curveEaseOut, animations: { var tempFrame = self.frame tempFrame.size.height = self.itemHeight self.frame = tempFrame }, completion: nil) } setNeedsDisplay() } // MARK: Events override public func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { let touch: UITouch = touches.first! let point: CGPoint = touch.location(in: self) if point.y > itemHeight { if let dele = delegate { var thought = Int(point.y / itemHeight) - 1 if let sele = selectedItem { if items.index(of: sele)! <= thought { thought += 1 } } dele.itemSelected(withIndex: thought, name: items[thought]) selectedItem = items[thought] } } collapsed = !collapsed } }
689be0c1042974abea9b078431a7e339
40.513725
199
0.586246
false
false
false
false
buyiyang/iosstar
refs/heads/master
iOSStar/Scenes/Deal/Controllers/ContainPayVC.swift
gpl-3.0
3
// // ContainPayVC.swift // iOSStar // // Created by sum on 2017/6/13. // Copyright © 2017年 YunDian. All rights reserved. // import UIKit class ContainPayVC: UIViewController { var scrollView : UIScrollView? var showAll : Bool = true var contOffset : Bool = false var resultBlock: CompleteBlock? override func viewDidLoad() { super.viewDidLoad() if showAll{ initUI() }else{ initAllView() } view.backgroundColor = UIColor.clear } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController?.setNavigationBarHidden(true, animated: true) } func initAllView(){ self.automaticallyAdjustsScrollViewInsets = false; scrollView = UIScrollView.init(frame: CGRect.init(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height)) self.scrollView?.isScrollEnabled = false scrollView?.isPagingEnabled = true self.automaticallyAdjustsScrollViewInsets = false scrollView?.contentSize = CGSize.init(width: self.view.frame.size.width*2, height: 0) view.addSubview(scrollView!) scrollView?.isPagingEnabled = true scrollView?.backgroundColor = UIColor.clear //进入交易密码界面 let rvc = UIStoryboard.init(name: "Order", bundle: nil).instantiateViewController(withIdentifier: "InputPassVC") as! InputPassVC self.scrollView?.addSubview(rvc.view) rvc.resultBlock = { [weak self](result) in if result is String{ self?.resultBlock?(result ) //result 的值就是 // self?.dismissController() }else{ //忘记密码 switch result as! doStateClick { case .close: self?.resultBlock?(result ) self?.dismissController() break default: let vc = UIStoryboard.init(name: "User", bundle: nil).instantiateViewController(withIdentifier: "ResetTradePassVC") self?.navigationController?.pushViewController(vc, animated: true) } } } self.addChildViewController(rvc) //确认订单 let vc = UIStoryboard.init(name: "Order", bundle: nil).instantiateViewController(withIdentifier: "SurePayAllOrderVC") as! SurePayAllOrderVC vc.resultBlock = { [weak self](result) in switch result as! doStateClick{ case .close: self?.resultBlock?(result ) self?.dismissController() break default: rvc.textField.resignFirstResponder() self?.scrollView?.setContentOffset(CGPoint.init(x: (self?.scrollView?.frame.size.width)!, y: 0), animated: true) rvc.textField.becomeFirstResponder() } } vc.view.frame = CGRect.init(x: 0, y: 0, width: view.frame.size.width, height: ((self.scrollView?.frame.size.height)!+10)) scrollView?.addSubview(vc.view) rvc.view.frame = CGRect.init(x: vc.view.frame.size.width, y: -10, width: vc.view.frame.size.width, height: ((self.scrollView?.frame.size.height)!+10)) if contOffset{ rvc.textField.becomeFirstResponder() self.scrollView?.setContentOffset(CGPoint.init(x: (self.scrollView?.frame.size.width)!, y: 0), animated: true) } self.addChildViewController(vc) } func initUI(){ self.automaticallyAdjustsScrollViewInsets = false; scrollView = UIScrollView.init(frame: CGRect.init(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height)) self.scrollView?.isScrollEnabled = false scrollView?.isPagingEnabled = true self.automaticallyAdjustsScrollViewInsets = false scrollView?.contentSize = CGSize.init(width: self.view.frame.size.width*2, height: 0) view.addSubview(scrollView!) scrollView?.isPagingEnabled = true scrollView?.backgroundColor = UIColor.clear //进入交易密码界面 let rvc = UIStoryboard.init(name: "Order", bundle: nil).instantiateViewController(withIdentifier: "InputPassVC") as! InputPassVC self.scrollView?.addSubview(rvc.view) rvc.resultBlock = { [weak self](result) in if ((result as? String) != nil){ self?.resultBlock?(result ) //result 的值就是 // self?.dismissController() }else{ //忘记密码 switch result as! doStateClick { case .close: self?.dismissController() break default: let vc = UIStoryboard.init(name: "User", bundle: nil).instantiateViewController(withIdentifier: "ResetTradePassVC") self?.navigationController?.pushViewController(vc, animated: true) } } } self.addChildViewController(rvc) //确认订单 let vc = UIStoryboard.init(name: "Order", bundle: nil).instantiateViewController(withIdentifier: "SurePayOrderVC") as! SurePayOrderVC vc.resultBlock = { [weak self](result) in switch result as! doStateClick{ case .close: self?.dismissController() break default: rvc.textField.resignFirstResponder() self?.scrollView?.setContentOffset(CGPoint.init(x: (self?.scrollView?.frame.size.width)!, y: 0), animated: true) rvc.textField.becomeFirstResponder() } } vc.view.frame = CGRect.init(x: 0, y: 0, width: view.frame.size.width, height: ((self.scrollView?.frame.size.height)!+10)) scrollView?.addSubview(vc.view) rvc.view.frame = CGRect.init(x: vc.view.frame.size.width, y: -10, width: vc.view.frame.size.width, height: ((self.scrollView?.frame.size.height)!+10)) self.addChildViewController(vc) } }
b038f2a1ac84ab08cb0c4963e7f3febb
38.859756
159
0.560808
false
false
false
false
ilyahal/VKMusic
refs/heads/master
VkPlaylist/GetGroups.swift
mit
1
// // GetGroups.swift // VkPlaylist // // MIT License // // Copyright (c) 2016 Ilya Khalyapin // // 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 GetGroups: RequestManagerObject { override func performRequest(parameters: [Argument : AnyObject], withCompletionHandler completion: (Bool) -> Void) { super.performRequest(parameters, withCompletionHandler: completion) // Отмена выполнения предыдущего запроса и удаление загруженной информации cancel() DataManager.sharedInstance.groups.clear() // Если нет подключения к интернету if !Reachability.isConnectedToNetwork() { state = .NotSearchedYet error = .NetworkError UIApplication.sharedApplication().networkActivityIndicatorVisible = false completion(false) return } // Слушатель для уведомления об успешном завершении получения групп NSNotificationCenter.defaultCenter().addObserverForName(VKAPIManagerDidGetGroupsNotification, object: nil, queue: NSOperationQueue.mainQueue()) { notification in self.removeActivState() // Удаление состояние выполнения запроса // Сохранение данных let result = notification.userInfo!["Groups"] as! [Group] DataManager.sharedInstance.groups.saveNewArray(result) self.state = DataManager.sharedInstance.groups.array.count == 0 ? .NoResults : .Results self.error = .None completion(true) } // Слушатель для получения уведомления об ошибке при подключении к интернету NSNotificationCenter.defaultCenter().addObserverForName(VKAPIManagerGetGroupsNetworkErrorNotification, object: nil, queue: NSOperationQueue.mainQueue()) { _ in self.removeActivState() // Удаление состояние выполнения запроса // Сохранение данных DataManager.sharedInstance.groups.clear() self.state = .NotSearchedYet self.error = .NetworkError completion(false) } // Слушатель для уведомления о других ошибках NSNotificationCenter.defaultCenter().addObserverForName(VKAPIManagerGetGroupsErrorNotification, object: nil, queue: NSOperationQueue.mainQueue()) { _ in self.removeActivState() // Удаление состояние выполнения запроса // Сохранение данных DataManager.sharedInstance.groups.clear() self.state = .NotSearchedYet self.error = .UnknownError completion(false) } let request = VKAPIManager.groupsGet() state = .Loading error = .None RequestManager.sharedInstance.activeRequests[key] = request } }
7d3ad771d6ef25e746234afbc47d678b
39.28
169
0.65781
false
false
false
false
AngryLi/ResourceSummary
refs/heads/master
iOS/Demos/IBInspectorDemo/IBInspectorDemo/CustomView.swift
mit
3
// // CustomView.swift // IBInspectorDemo // // Created by 李亚洲 on 16/3/23. // Copyright © 2016年 angryli. All rights reserved. // import UIKit @IBDesignable class CustomView: UIView { // @IBInspectable // var currentColor : UIColor? { // didSet(newValue) { // backgroundColor = newValue // } // } /* // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { // Drawing code } */ override var frame: CGRect { set(newFrame) { if newFrame.size.width < newFrame.size.height { self.frame = CGRect(origin: frame.origin, size: CGSize(width: newFrame.size.height, height: newFrame.size.height)) } else { super.frame = newFrame } layer.cornerRadius = frame.size.height * 0.5 } get { return super.frame } // didSet(newFrame) { // if newFrame.size.width < newFrame.size.height { // self.frame = CGRect(origin: frame.origin, size: CGSize(width: newFrame.size.height, height: newFrame.size.height)) // } // layer.cornerRadius = frame.size.height * 0.5 // } } } extension UIView { @IBInspectable var boderWidth : CGFloat { get { return layer.borderWidth } set { // self.boderWidth = newValue; layer.borderWidth = newValue } } // @IBInspectable var cornerRadius: CGFloat { // get { // return layer.cornerRadius // } // set { // layer.cornerRadius = newValue // layer.masksToBounds = newValue > 0 // } // } @IBInspectable var p_boderColor: UIColor? { get { return UIColor(CGColor: layer.borderColor!) } set { layer.borderColor = newValue?.CGColor } } }
0f0646d1d2761c7e1f02eef3c42e8ca7
25.192308
132
0.540871
false
false
false
false
DanielCech/Vapor-Catalogue
refs/heads/master
Sources/App/Controllers/ArtistController.swift
mit
1
import Vapor import HTTP final class ArtistController { func addRoutes(drop: Droplet) { let group = drop.grouped("artists") group.get(handler: index) group.post(handler: create) group.get(Artist.self, handler: show) group.patch(Artist.self, handler: update) group.delete(Artist.self, handler: delete) group.get(Artist.self, "albums", handler: albumsIndex) let searchGroup = group.grouped("search") searchGroup.get(handler: search) } func index(request: Request) throws -> ResponseRepresentable { return try JSON(node: Artist.all().makeNode()) } func create(request: Request) throws -> ResponseRepresentable { var artist = try request.artist() try artist.save() return artist } func show(request: Request, artist: Artist) throws -> ResponseRepresentable { return artist } func update(request: Request, artist: Artist) throws -> ResponseRepresentable { let new = try request.artist() var artist = artist artist.name = new.name try artist.save() return artist } func delete(request: Request, artist: Artist) throws -> ResponseRepresentable { try artist.delete() return JSON([:]) } // func makeResource() -> Resource<Artist> { // return Resource( // index: index, // store: create, // show: show, // modify: update, // destroy: delete // ) // } func albumsIndex(request: Request, artist: Artist) throws -> ResponseRepresentable { let children = try artist.albums() return try JSON(node: children.makeNode()) } func search(request: Request) throws -> ResponseRepresentable { let results: Node if let searchQuery = request.query?["q"]?.string { results = try Artist.query().filter("name", .contains, searchQuery).all().makeNode() } else { results = [] } if request.accept.prefers("html") { let parameters = try Node(node: [ "searchResults": results, ]) return try drop.view.make("index", parameters) } else { return JSON(results) } } } extension Request { func artist() throws -> Artist { guard let json = json else { throw Abort.badRequest } return try Artist(node: json) } }
6217045bc84d0c974ff7e2038b4f761c
27.307692
96
0.5625
false
false
false
false
Moriquendi/SwiftCrunch
refs/heads/master
MMSVideoFun/MMSVideoFun/ViewController.swift
mit
1
// // ViewController.swift // MMSVideoFun // // Created by Michal Smialko on 7/5/14. // Copyright (c) 2014 NSSpot. All rights reserved. // import UIKit import AVFoundation import CoreMedia import MediaPlayer @infix func + ( left:AVURLAsset, right:(asset:AVURLAsset, range:Range<Int>)) -> AVURLAsset! { var fullRange:Range<Int> = Range(start: 0, end: Int(CMTimeGetSeconds(left.duration))) return (left, fullRange) + right } @infix func + ( left:(asset: AVURLAsset, range:Range<Int>), right:(asset:AVURLAsset, range:Range<Int>)) -> AVURLAsset! { // ------------------------------------------------- // func merge() -> AVURLAsset! { var composition = AVMutableComposition() var trackId = CMPersistentTrackID(kCMPersistentTrackID_Invalid) let compositionVideoTrack = composition.addMutableTrackWithMediaType(AVMediaTypeVideo, preferredTrackID:CMPersistentTrackID(kCMPersistentTrackID_Invalid)) var t = kCMTimeZero; let clips = [left.asset.URL, right.asset.URL] let ranges = [left.range, right.range] for i in 0..2 { let sourceAsset = AVURLAsset(URL: clips[i], options: [AVURLAssetPreferPreciseDurationAndTimingKey : true]) // Video var sourceVideoTrack:AVAssetTrack if sourceAsset.tracksWithMediaType(AVMediaTypeVideo).count > 0 { sourceVideoTrack = (sourceAsset.tracksWithMediaType(AVMediaTypeVideo))[0] as AVAssetTrack } else { break } var error:NSErrorPointer = nil var ok = false; let range = ranges[i] var startSeconds:Float64 = Float64(range.startIndex) var durationSeconds:Float64 = Float64(range.endIndex - range.startIndex) let timeRange:CMTimeRange = CMTimeRange(start: CMTimeMakeWithSeconds(startSeconds, 600), duration: CMTimeMakeWithSeconds(durationSeconds, 600)) ok = compositionVideoTrack.insertTimeRange(timeRange, ofTrack: sourceVideoTrack, atTime: composition.duration, error: error) if !ok { NSLog("something went wrong"); } // Audio if sourceAsset.tracksWithMediaType(AVMediaTypeAudio).count > 0 { let audioTrack = composition.addMutableTrackWithMediaType(AVMediaTypeAudio, preferredTrackID: CMPersistentTrackID(kCMPersistentTrackID_Invalid)) audioTrack.insertTimeRange(timeRange, ofTrack: sourceAsset.tracksWithMediaType(AVMediaTypeAudio)[0] as AVAssetTrack, atTime: t, error: nil) } t = CMTimeAdd(t, timeRange.duration); } let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true); var outputPath:NSString = "" while true { outputPath = paths[0] as NSString let prefix:Int = random() outputPath = outputPath.stringByAppendingPathComponent("out\(prefix).mov") if !NSFileManager.defaultManager().fileExistsAtPath(outputPath) { break } } let outputURL = NSURL(fileURLWithPath: outputPath) // First cleanup var error:NSErrorPointer = nil NSFileManager.defaultManager().removeItemAtURL(outputURL, error: error) let exporter = AVAssetExportSession(asset: composition, presetName: AVAssetExportPresetHighestQuality) exporter.outputURL = outputURL exporter.outputFileType = AVFileTypeQuickTimeMovie exporter.shouldOptimizeForNetworkUse = true var finished = false exporter.exportAsynchronouslyWithCompletionHandler({ if exporter.status != AVAssetExportSessionStatus.Completed { println("Merge error \(exporter.error)") } // Remove old assetes NSFileManager.defaultManager().removeItemAtURL(left.asset.URL, error: nil) NSFileManager.defaultManager().removeItemAtURL(right.asset.URL, error: nil) println("FINISH") finished = true }) // Wait for exporter to finish while !finished {} // Bleh, fuj. Exporter is deallocated. How to keep it? println("\(exporter)") return AVURLAsset(URL: outputURL, options: nil) } return merge() } class ViewController: UIViewController { let player = MPMoviePlayerViewController() @IBAction func didTapButton(sender : UIButton) { var bundle = NSBundle.mainBundle() let movie1 = AVURLAsset(URL: bundle.URLForResource("1", withExtension: "mov"), options: nil); let movie2 = AVURLAsset(URL: bundle.URLForResource("2", withExtension: "mov"), options: nil); let movie3 = AVURLAsset(URL: bundle.URLForResource("3", withExtension: "mov"), options: nil); //////////////////////////////////////////////////////////////////////////////////////// // let mergedAsset:AVURLAsset = movie1 + movie2 + movie3 //////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////// // Hey, this is crazy, so vote for me maybe? let mergedAsset:AVURLAsset = (movie1, 0..2) + (movie2, 0..2) + (movie3, 2..4) //////////////////////////////////////////////////////////////////////////////////////// self.player.moviePlayer.contentURL = mergedAsset.URL } @IBAction func play(sender : UIButton) { self.presentViewController(self.player, animated: true, completion: nil) } }
38393a2103769a04d1ef6008b17641ed
28.745455
160
0.525825
false
false
false
false
wangchong321/tucao
refs/heads/master
WCWeiBo/WCWeiBo/Classes/Model/Main/MainTabBar.swift
mit
1
// // MainTabBar.swift // WCWeiBo // // Created by 王充 on 15/5/10. // Copyright (c) 2015年 wangchong. All rights reserved. // import UIKit class MainTabBar: UITabBar { override func layoutSubviews() { super.layoutSubviews() let tabBarNum = 5 let w = frame.width / CGFloat(tabBarNum) let h = frame.height let myFrame = CGRectMake(0, 0, w, h) var index = 0 for v in subviews as! [UIView]{ if v is UIControl && !(v is UIButton) { // 设置frame let x = CGFloat(index) * w v.frame = CGRectMake(x ,CGFloat(0), w, h) // println(v) index += (index == 1) ? 2 : 1 } } // 设置中间按钮的frame centerButton.frame = CGRectMake(w * CGFloat(2), 0, w, h) } lazy var centerButton : UIButton = { let btn = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton btn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal) btn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted) btn.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal) btn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted) //btn.backgroundColor = UIColor.redColor() self.addSubview(btn) return btn }() }
102b3ae44906e52d0e833f74718b7415
32
121
0.590909
false
false
false
false
FreddyZeng/Charts
refs/heads/develop
Pods/Charts/Source/Charts/Highlight/RadarHighlighter.swift
apache-2.0
7
// // RadarHighlighter.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 @objc(RadarChartHighlighter) open class RadarHighlighter: PieRadarHighlighter { open override func closestHighlight(index: Int, x: CGFloat, y: CGFloat) -> Highlight? { guard let chart = self.chart as? RadarChartView else { return nil } let highlights = getHighlights(forIndex: index) let distanceToCenter = Double(chart.distanceToCenter(x: x, y: y) / chart.factor) var closest: Highlight? var distance = Double.greatestFiniteMagnitude for high in highlights { let cdistance = abs(high.y - distanceToCenter) if cdistance < distance { closest = high distance = cdistance } } return closest } /// - returns: An array of Highlight objects for the given index. /// The Highlight objects give information about the value at the selected index and DataSet it belongs to. /// /// - parameter index: internal func getHighlights(forIndex index: Int) -> [Highlight] { var vals = [Highlight]() guard let chart = self.chart as? RadarChartView, let chartData = chart.data else { return vals } let phaseX = chart.chartAnimator.phaseX let phaseY = chart.chartAnimator.phaseY let sliceangle = chart.sliceAngle let factor = chart.factor for i in chartData.dataSets.indices { guard let dataSet = chartData.getDataSetByIndex(i), let entry = dataSet.entryForIndex(index) else { continue } let y = (entry.y - chart.chartYMin) let p = chart.centerOffsets.moving(distance: CGFloat(y) * factor * CGFloat(phaseY), atAngle: sliceangle * CGFloat(index) * CGFloat(phaseX) + chart.rotationAngle) let highlight = Highlight(x: Double(index), y: entry.y, xPx: p.x, yPx: p.y, dataSetIndex: i, axis: dataSet.axisDependency) vals.append(highlight) } return vals } }
95e51dff84f2bac5b3d1f2a3b9b7af63
30.538462
134
0.581301
false
false
false
false
adrianomazucato/CoreStore
refs/heads/master
CoreStore/Internal/FetchedResultsControllerDelegate.swift
mit
2
// // FetchedResultsControllerDelegate.swift // CoreStore // // Copyright (c) 2015 John Rommel Estropia // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation import CoreData // MARK: - FetchedResultsControllerHandler internal protocol FetchedResultsControllerHandler: class { func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) func controllerWillChangeContent(controller: NSFetchedResultsController) func controllerDidChangeContent(controller: NSFetchedResultsController) func controller(controller: NSFetchedResultsController, sectionIndexTitleForSectionName sectionName: String?) -> String? } // MARK: - FetchedResultsControllerDelegate internal final class FetchedResultsControllerDelegate: NSObject, NSFetchedResultsControllerDelegate { // MARK: Internal internal weak var handler: FetchedResultsControllerHandler? internal weak var fetchedResultsController: NSFetchedResultsController? { didSet { oldValue?.delegate = nil self.fetchedResultsController?.delegate = self } } deinit { self.fetchedResultsController?.delegate = nil } // MARK: NSFetchedResultsControllerDelegate @objc dynamic func controllerWillChangeContent(controller: NSFetchedResultsController) { self.deletedSections = [] self.insertedSections = [] self.handler?.controllerWillChangeContent(controller) } @objc dynamic func controllerDidChangeContent(controller: NSFetchedResultsController) { self.handler?.controllerDidChangeContent(controller) } @objc dynamic func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) { if #available(iOS 9, *) { self.handler?.controller( controller, didChangeObject: anObject, atIndexPath: indexPath, forChangeType: type, newIndexPath: newIndexPath ) return } // Workaround a nasty bug introduced in XCode 7 targeted at iOS 8 devices // http://stackoverflow.com/questions/31383760/ios-9-attempt-to-delete-and-reload-the-same-index-path/31384014#31384014 // https://forums.developer.apple.com/message/9998#9998 // https://forums.developer.apple.com/message/31849#31849 switch type { case .Move: guard let indexPath = indexPath, let newIndexPath = newIndexPath else { return } if indexPath == newIndexPath && self.deletedSections.contains(indexPath.section) { self.handler?.controller( controller, didChangeObject: anObject, atIndexPath: nil, forChangeType: .Insert, newIndexPath: indexPath ) return } case .Update: guard let section = indexPath?.section else { return } if self.deletedSections.contains(section) || self.insertedSections.contains(section) { return } default: break } self.handler?.controller( controller, didChangeObject: anObject, atIndexPath: indexPath, forChangeType: type, newIndexPath: newIndexPath ) } @objc dynamic func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) { switch type { case .Delete: self.deletedSections.insert(sectionIndex) case .Insert: self.insertedSections.insert(sectionIndex) default: break } self.handler?.controller( controller, didChangeSection: sectionInfo, atIndex: sectionIndex, forChangeType: type ) } @objc dynamic func controller(controller: NSFetchedResultsController, sectionIndexTitleForSectionName sectionName: String) -> String? { return self.handler?.controller( controller, sectionIndexTitleForSectionName: sectionName ) } // MARK: Private private var deletedSections = Set<Int>() private var insertedSections = Set<Int>() }
c6edd3a23832ffc744d1a3c657f4d260
35.068571
225
0.640843
false
false
false
false
Scorocode/scorocode-SDK-swift
refs/heads/master
todolist/RegisterVC.swift
mit
1
// // RegisterVC.swift // todolist // // Created by Alexey Kuznetsov on 01.06.17. // Copyright © 2017 ProfIT. All rights reserved. // import UIKit class RegisterVC : UIViewController { //Mark: outlets @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var textFieldConfirmPassword: UITextField! @IBOutlet weak var textFieldPassword: UITextField! @IBOutlet weak var buttonRegister: UIButton! @IBOutlet weak var textFieldEmail: UITextField! @IBOutlet weak var textFieldName: UITextField! //Mark: vars let user = User.sharedInstance //Mark: override VC functions override func viewDidLoad() { super.viewDidLoad() // keyboard show-hide, resize window. setupViewResizerOnKeyboardShown() hideKeyboardWhenTappedAround() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) setupUI() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } //MARK: setupUI func setupUI() { //round login button buttonRegister.layer.cornerRadius = 5.0; buttonRegister.layer.masksToBounds = true; } func signup(email: String, password: String, name: String) { let scUser = SCUser() scUser.signup(name, email: email, password: password) { (success, error, result) in if success { self.user.saveCredentials(email: email, password: password) self.user.saveTokenToServer() self.user.parseUser(userDictionary: result?["user"] as? [String: Any]) self.showAlert(title: "Успешно", message: "Вы успешно зарегистрировались") { let taskListVC = self.storyboard?.instantiateViewController(withIdentifier: "TaskListVC") as! TaskListVC self.navigationController?.pushViewController(taskListVC, animated: true) } } else { self.showAlert(title: "Регистрация не выполнена!", message: "Попробуйте еще раз.", completion: nil) } } } //MARK: button actions @IBAction func buttonRegisterTapped(_ sender: AnyObject) { guard textFieldPassword.text == textFieldConfirmPassword.text, textFieldConfirmPassword.text != "" else { showAlert(title: "Пароли должны совпадать", message: "Пароль и подтверждение пароля не совпадают!", completion: nil) return } guard let email = textFieldEmail.text, email != "", let password = textFieldPassword.text, password != "" else { showAlert(title: "Регистрация не выполнена!", message: "Email и пароль доолжны быть заполнены.", completion: nil) return } signup(email: textFieldEmail.text!, password: textFieldPassword.text!, name: textFieldName.text ?? "") } }
18ac6e370a944c5edd2d2aae92cbc319
36.358974
128
0.639327
false
false
false
false
oleander/bitbar
refs/heads/master
Sources/Plugin/StopWatch.swift
mit
1
import SwiftyTimer class StopWatch: Base { enum Event: String { case stop, start } private let queue = DispatchQueue(label: "StopWatch", qos: .userInteractive, target: .main) private var timer: Timer? private let interval: Double private var fired: Timer? private weak var delegate: Timeable? init(every time: Int, delegate: Timeable, start autostart: Bool = true) { self.interval = Double(time) super.init() self.delegate = delegate if autostart { start() } } internal var id: Int { return ObjectIdentifier(timer ?? self).hashValue } public var isActive: Bool { return timer?.isValid ?? false } private func newTimer() -> Timer { return Timer.new(every: interval, onTick) } func fire(then event: Event) { queue.async { [weak self] in guard let this = self else { return } this.onTick() switch (event, this.isActive) { case (.start, true): this.log.info("Already started") case (.start, false): this.unsafeStart() case (.stop, false): this.log.info("Already stopped") case (.stop, true): this.unsafeStop() } } } func restart() { log.verbose("Restart timer") stop() start() } func stop() { queue.async { [weak self] in self?.unsafeStop() } } private func unsafeStop() { queue.async { [weak self] in self?.both() } } private func invalidate(_ timer: Timer?) { guard let aTimer = timer else { return } guard aTimer.isValid else { return } aTimer.invalidate() } func start() { queue.async { [weak self] in self?.unsafeStart() } } private func unsafeStart() { queue.async { [weak self] in guard let this = self else { return } if this.isActive { return this.log.info("Already active") } this.log.verbose("Start timer") this.both() this.timer = this.newTimer() this.timer?.start(modes: .defaultRunLoopMode, .eventTrackingRunLoopMode) } } private func both() { invalidate(timer) invalidate(fired) } private func onTick() { if let receiver = delegate { return receiver.timer(didTick: self) } stop() } }
e2a055fb937d5bc663977e2baa3ae324
19.906542
93
0.608404
false
false
false
false
alex-alex/S2Geometry
refs/heads/master
Sources/S1Angle.swift
mit
1
// // S1Angle.swift // S2Geometry // // Created by Alex Studnicka on 7/1/16. // Copyright © 2016 Alex Studnicka. MIT License. // #if os(Linux) import Glibc #else import Darwin.C #endif public struct S1Angle: Equatable, Comparable { public let radians: Double public var degrees: Double { return radians * (180 / M_PI) } private func getInteger(multipliedBy m: Double) -> Int64 { return Int64(round(degrees * m)) } public var e5: Int64 { return getInteger(multipliedBy: 1e5) } public var e6: Int64 { return getInteger(multipliedBy: 1e6) } public var e7: Int64 { return getInteger(multipliedBy: 1e7) } public init(radians: Double = 0) { self.radians = radians } public init(degrees: Double) { self.radians = degrees * (M_PI / 180) } public init(e5: Int64) { self.init(degrees: Double(e5) * 1e-5) } public init(e6: Int64) { self.init(degrees: Double(e6) * 1e-6) } public init(e7: Int64) { self.init(degrees: Double(e7) * 1e-7) } } public func ==(lhs: S1Angle, rhs: S1Angle) -> Bool { return lhs.radians == rhs.radians } public func <(lhs: S1Angle, rhs: S1Angle) -> Bool { return lhs.radians < rhs.radians } public func +(lhs: S1Angle, rhs: S1Angle) -> S1Angle { return S1Angle(radians: lhs.radians + rhs.radians) } public func -(lhs: S1Angle, rhs: S1Angle) -> S1Angle { return S1Angle(radians: lhs.radians - rhs.radians) } public func *(lhs: S1Angle, rhs: Double) -> S1Angle { return S1Angle(radians: lhs.radians * rhs) }
f2eac2950c0cbdf2104c88d83d6e7166
19.971831
62
0.671592
false
false
false
false
iOSTestApps/PhoneBattery
refs/heads/master
PhoneBattery WatchKit Extension/BatteryInformation.swift
mit
1
// // BatteryInformation.swift // PhoneBattery // // Created by Marcel Voß on 29.07.15. // Copyright (c) 2015 Marcel Voss. All rights reserved. // import UIKit class BatteryInformation: NSObject { class func stringForBatteryState(batteryState: UIDeviceBatteryState) -> String { if batteryState == UIDeviceBatteryState.Full { return NSLocalizedString("FULL", comment: "") } else if batteryState == UIDeviceBatteryState.Charging { return NSLocalizedString("CHARGING", comment: "") } else if batteryState == UIDeviceBatteryState.Unplugged { return NSLocalizedString("REMAINING", comment: "") } else { return NSLocalizedString("UNKNOWN", comment: "") } } }
7b06125d221eb18f1717709c9c7c7cd8
28.423077
84
0.647059
false
false
false
false
rolson/arcgis-runtime-samples-ios
refs/heads/master
arcgis-ios-sdk-samples/Search/Find address/FindAddressViewController.swift
apache-2.0
1
// Copyright 2016 Esri. // // 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 ArcGIS class FindAddressViewController: UIViewController, AGSGeoViewTouchDelegate, UISearchBarDelegate, UIAdaptivePresentationControllerDelegate, WorldAddressesVCDelegate { @IBOutlet private var mapView:AGSMapView! @IBOutlet private var button:UIButton! @IBOutlet private var searchBar:UISearchBar! private var locatorTask:AGSLocatorTask! private var geocodeParameters:AGSGeocodeParameters! private var graphicsOverlay:AGSGraphicsOverlay! private let locatorURL = "https://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer" override func viewDidLoad() { super.viewDidLoad() //add the source code button item to the right of navigation bar (self.navigationItem.rightBarButtonItem as! SourceCodeBarButtonItem).filenames = ["FindAddressViewController", "WorldAddressesViewController"] //instantiate a map with an imagery with labels basemap let map = AGSMap(basemap: AGSBasemap.imageryWithLabelsBasemap()) self.mapView.map = map self.mapView.touchDelegate = self //initialize the graphics overlay and add to the map view self.graphicsOverlay = AGSGraphicsOverlay() self.mapView.graphicsOverlays.addObject(self.graphicsOverlay) //initialize locator task self.locatorTask = AGSLocatorTask(URL: NSURL(string: self.locatorURL)!) //initialize geocode parameters self.geocodeParameters = AGSGeocodeParameters() self.geocodeParameters.resultAttributeNames.appendContentsOf(["*"]) self.geocodeParameters.minScore = 75 //register self for the keyboard show notification //in order to un hide the cancel button for search NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(FindAddressViewController.keyboardWillShow(_:)), name: UIKeyboardWillShowNotification, object: nil) } //method that returns a graphic object for the specified point and attributes //also sets the leader offset and offset private func graphicForPoint(point: AGSPoint, attributes: [String: AnyObject]?) -> AGSGraphic { let markerImage = UIImage(named: "RedMarker")! let symbol = AGSPictureMarkerSymbol(image: markerImage) symbol.leaderOffsetY = markerImage.size.height/2 symbol.offsetY = markerImage.size.height/2 let graphic = AGSGraphic(geometry: point, symbol: symbol, attributes: attributes) return graphic } private func geocodeSearchText(text:String) { //clear already existing graphics self.graphicsOverlay.graphics.removeAllObjects() //dismiss the callout if already visible self.mapView.callout.dismiss() //perform geocode with input text self.locatorTask.geocodeWithSearchText(text, parameters: self.geocodeParameters, completion: { [weak self] (results:[AGSGeocodeResult]?, error:NSError?) -> Void in if let error = error { self?.showAlert(error.localizedDescription) } else { if let results = results where results.count > 0 { //create a graphic for the first result and add to the graphics overlay let graphic = self?.graphicForPoint(results[0].displayLocation!, attributes: results[0].attributes) self?.graphicsOverlay.graphics.addObject(graphic!) //zoom to the extent of the result if let extent = results[0].extent { self?.mapView.setViewpointGeometry(extent, completion: nil) } } else { //provide feedback in case of failure self?.showAlert("No results found") } } }) } //MARK: - Callout //method shows the callout for the specified graphic, //populates the title and detail of the callout with specific attributes //hides the accessory button private func showCalloutForGraphic(graphic:AGSGraphic, tapLocation:AGSPoint) { let addressType = graphic.attributes["Addr_type"] as! String self.mapView.callout.title = graphic.attributes["Match_addr"] as? String ?? "" if addressType == "POI" { self.mapView.callout.detail = graphic.attributes["Place_addr"] as? String ?? "" } else { self.mapView.callout.detail = nil } self.mapView.callout.accessoryButtonHidden = true self.mapView.callout.showCalloutForGraphic(graphic, tapLocation: tapLocation, animated: true) } private func showAlert(message:String) { SVProgressHUD.showErrorWithStatus(message, maskType: .Gradient) } //MARK: - AGSGeoViewTouchDelegate func geoView(geoView: AGSGeoView, didTapAtScreenPoint screenPoint: CGPoint, mapPoint: AGSPoint) { //dismiss the callout self.mapView.callout.dismiss() //identify graphics at the tapped location self.mapView.identifyGraphicsOverlay(self.graphicsOverlay, screenPoint: screenPoint, tolerance: 5, returnPopupsOnly: false, maximumResults: 1) { (result: AGSIdentifyGraphicsOverlayResult) -> Void in if let error = result.error { self.showAlert(error.localizedDescription) } else if result.graphics.count > 0 { //show callout for the graphic self.showCalloutForGraphic(result.graphics[0], tapLocation: mapPoint) } } } //MARK: - UISearchBar delegates func searchBarSearchButtonClicked(searchBar: UISearchBar) { self.geocodeSearchText(searchBar.text!) self.hideKeyboard() } func searchBar(searchBar: UISearchBar, textDidChange searchText: String) { if searchText.isEmpty { self.graphicsOverlay.graphics.removeAllObjects() self.mapView.callout.dismiss() } } func searchBarResultsListButtonClicked(searchBar: UISearchBar) { self.performSegueWithIdentifier("AddressesListSegue", sender: self) } //MARK: - Actions func keyboardWillShow(sender:AnyObject) { self.button.hidden = false } @IBAction func hideKeyboard() { self.searchBar.resignFirstResponder() self.button.hidden = true } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } //MARK: - Navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "AddressesListSegue" { let controller = segue.destinationViewController as! WorldAddressesViewController controller.presentationController?.delegate = self controller.popoverPresentationController?.sourceView = self.view controller.popoverPresentationController?.sourceRect = self.searchBar.frame controller.preferredContentSize = CGSize(width: 300, height: 200) controller.delegate = self } } //MARK: - UIAdaptivePresentationControllerDelegate func adaptivePresentationStyleForPresentationController(controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle { return UIModalPresentationStyle.None } //MARK: - AddressesListVCDelegate func worldAddressesViewController(worldAddressesViewController: WorldAddressesViewController, didSelectAddress address: String) { self.searchBar.text = address self.geocodeSearchText(address) self.dismissViewControllerAnimated(true, completion: nil) self.hideKeyboard() } }
ce9ac6db51611bd6c059c82f7ea4c239
41.134328
206
0.671272
false
false
false
false
ozpopolam/DoctorBeaver
refs/heads/master
DoctorBeaver/DataPickerView.swift
mit
1
// // DataPickerView.swift // DoctorBeaver // // Created by Anastasia Stepanova-Kolupakhina on 03.03.16. // Copyright © 2016 Anastasia Stepanova-Kolupakhina. All rights reserved. // import UIKit protocol DataPickerViewDelegate: class { func dataPicker(picker: DataPickerView, didPickValues values: [String]) func dataStillNeeded(fromPicker picker: DataPickerView) -> Bool } class DataPickerView: UIView { weak var view: UIView! @IBOutlet weak var pickerView: UIPickerView! weak var delegate: DataPickerViewDelegate? let minCircularRows = 300 let minCircularRowsMultiplier = 3 var font = UIFont.systemFontOfSize(17.0) var textColor = UIColor.blackColor() var isEmpty: Bool { // data sourse is empty get { return rowsInComponent.isEmpty } } var needToResetInitialValues = false // need to be reloaded, when user selected some value, but later it wasn't used var rowsInComponent: [Int] = [] var options: [[String]] = [] { didSet { rowsInComponent = [] for component in 0..<options.count { rowsInComponent.append(circularNumberOfRowsFor(numberOfSourceRows: options[component].count)) } } } var initialValues: [String] = [] var selectedValues: [String] = [] override init(frame: CGRect) { super.init(frame: frame) xibSetup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) xibSetup() } func xibSetup() { view = loadViewFromNib() view.frame = bounds view.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight] addSubview(view) pickerView.dataSource = self pickerView.delegate = self } func loadViewFromNib() -> UIView { let bundle = NSBundle(forClass: self.dynamicType) let nib = UINib(nibName: "DataPickerView", bundle: bundle) let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView return view } func configure(withOptions options: [[String]], andInitialValues initialValues: [String], andDelegate delegate: DataPickerViewDelegate) { self.options = options self.initialValues = initialValues self.delegate = delegate pickerView.reloadAllComponents() setPickerToValues(initialValues) } func configure(withInitialValues initialValues: [String]) { self.initialValues = initialValues setPickerToValues(initialValues) } func setPickerToValues(initialValues: [String]) { for component in 0..<initialValues.count { if let rowInd = options[component].indexOf(initialValues[component]) { let row = ( rowsInComponent[component] / options[component].count / 2 ) * options[component].count + rowInd pickerView.selectRow(row, inComponent: component, animated: true) } } } func cleanAllData() { rowsInComponent = [] options = [] initialValues = [] selectedValues = [] } } extension DataPickerView: UIPickerViewDataSource { func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return rowsInComponent.count } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return rowsInComponent[component] } // number of rows to create effect of barrel func circularNumberOfRowsFor(numberOfSourceRows rows: Int) -> Int { var circularRows = 0 if rows >= minCircularRows { circularRows = rows * minCircularRowsMultiplier } else { if minCircularRows % rows == 0 { circularRows = minCircularRows } else { circularRows = rows * (minCircularRows / rows + 1) } } return circularRows } } extension DataPickerView: UIPickerViewDelegate { func pickerView(pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusingView view: UIView?) -> UIView { var title: UILabel if let ttl = view as? UILabel { title = ttl } else { title = UILabel() } title.textAlignment = NSTextAlignment.Center title.font = font title.textColor = textColor let sourceRow = row % options[component].count title.text = options[component][sourceRow] return title } // if all rows are empty -> combination is impossible func impossibleCombination(selectedValues: [String]) -> Bool { var selectedString = "" for s in selectedValues { selectedString += s } if selectedString.isVoid { return true } else { return false } } func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { selectedValues = [] var value: String var selectedRow: Int for ind in 0..<options.count { selectedRow = pickerView.selectedRowInComponent(ind) let sourceRow = selectedRow % options[ind].count value = options[ind][sourceRow] selectedValues.append(value) } selectedRow = pickerView.selectedRowInComponent(component) if impossibleCombination(selectedValues) { // select the next row selectedRow += 1 let sourceRow = (selectedRow) % options[component].count selectedValues[component] = options[component][sourceRow] pickerView.selectRow(selectedRow, inComponent: component, animated: true) } if let delegate = delegate { if delegate.dataStillNeeded(fromPicker: self) { needToResetInitialValues = false delegate.dataPicker(self, didPickValues: selectedValues) } else { needToResetInitialValues = true } } } }
72af1f2159387cbe09d3d308e1f4edf4
26.870647
139
0.681185
false
false
false
false
prot3ct/Ventio
refs/heads/master
Ventio/Ventio/Controllers/AccountViewController.swift
apache-2.0
1
import UIKit import RxSwift class AccountViewController: UIViewController { @IBOutlet weak var usernameTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! internal var userData: UserDataProtocol! private let disposeBag = DisposeBag() override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func onLoginClicked(_ sender: UIButton) { self.startLoading() let username = self.usernameTextField.text let password = self.passwordTextField.text guard username != nil, password != nil else { return } userData .signIn(username: username!, password: password!) .subscribeOn(ConcurrentDispatchQueueScheduler(qos: .default)) .observeOn(MainScheduler.instance) .subscribe(onNext: { res in self.changeInitialViewController(identifier: "myEventsViewController") self.showSuccess(withStatus: "You have signed in successfully") }, onError: { error in print(error) self.showError(withStatus: "Invalid username or password") }) .disposed(by: disposeBag) } @IBAction func onRegisterClicked(_ sender: UIButton) { self.startLoading() let username = self.usernameTextField.text let password = self.passwordTextField.text guard username != nil, password != nil else { return } guard username!.count() >= 4 && username!.count() <= 10 else { self.showError(withStatus: "Username must be between 4 and 10 symbols long") return } guard password!.count() >= 4 && password!.count() <= 20 else { self.showError(withStatus: "Password must be between 4 and 20 symbols long") return } userData .register(username: username!, password: password!) .subscribeOn(ConcurrentDispatchQueueScheduler(qos: .default)) .observeOn(MainScheduler.instance) .subscribe(onNext: { res in self.showSuccess(withStatus: "You have registered successfully") }, onError: { error in print(error); self.showError(withStatus: "Username already exists") }) .disposed(by: disposeBag) } private func changeInitialViewController(identifier: String) { let storyboard = UIStoryboard(name: "Main", bundle: nil) let initialViewController = storyboard .instantiateViewController(withIdentifier: identifier) UIApplication.shared.keyWindow?.rootViewController = initialViewController }}
c25682ad8967069607cc4c25d3faddd2
31.516484
88
0.593782
false
false
false
false
xxxAIRINxxx/ARNPageContainer-Swift
refs/heads/master
Example/ARNPageContainer-Swift/ViewController.swift
mit
1
// // ViewController.swift // ARNPageContainer-Swift // // Created by xxxAIRINxxx on 2015/01/20. // Copyright (c) 2015 xxxAIRINxxx. All rights reserved. // import UIKit class ViewController: UIViewController { var pageContainer : ARNPageContainer = ARNPageContainer() override func viewDidLoad() { super.viewDidLoad() self.pageContainer.setPasentVC(self) for index in 1...5 { let controller = UIViewController() controller.view.clipsToBounds = true let imageView = UIImageView(image: UIImage(named: "image.JPG")) imageView.contentMode = .ScaleAspectFill controller.view.addSubview(imageView) controller.view.arn_allPin(imageView) controller.title = "controller \(index)" self.pageContainer.addViewController(controller) } let tabView = ARNPageContainerTabView(frame: CGRectZero) tabView.font = UIFont.boldSystemFontOfSize(20) tabView.backgroundColor = UIColor.darkGrayColor() tabView.titleColor = UIColor(red: 130.0/255.0, green: 130.0/255.0, blue: 255.0/255.0, alpha: 1.0) tabView.itemTitles = self.pageContainer.headerTitles() pageContainer.setTopBarView(tabView) weak var weakTabView = tabView self.pageContainer.changeOffsetHandler = {(collectionView: UICollectionView, selectedIndex: Int) in if let _tabView = weakTabView { _tabView.changeParentScrollView(collectionView, selectedIndex: selectedIndex, totalVCCount: collectionView.numberOfItemsInSection(0)) } } weak var weakSelf = self tabView.selectTitleHandler = {(selectedIndex: Int) in print("selectTitleBlock selectedIndex : \(selectedIndex)") if let _self = weakSelf { _self.pageContainer.setSelectedIndex(selectedIndex, animated: true) } } self.pageContainer.changeIndexHandler = {(selectIndexController: UIViewController, selectedIndex: Int) in print("changeIndexBlock selectedIndex : \(selectedIndex)") if let _tabView = weakTabView { _tabView.selectedIndex = selectedIndex } } self.pageContainer.setSelectedIndex(2, animated: true) self.pageContainer.topBarHeight = 60.0 } }
036fb9ca56ecc1a8e7080c250af03b89
36.953125
149
0.638534
false
false
false
false
djq993452611/YiYuDaoJia_Swift
refs/heads/master
YiYuDaoJia/YiYuDaoJia/Classes/Tools/Vendor/YLCycleView/YLSinglerowView.swift
mit
1
// // YLSinglerowView.swift // YLCycleViewDemo // // Created by shuogao on 2016/11/3. // Copyright © 2016年 Yulu Zhang. All rights reserved. // import UIKit fileprivate let kSingCellId = "kSingCellId" //代理 protocol YLSinglerViewDelegate : class { func singlerView(_ singlerowView : YLSinglerowView, selectedIndex index: Int) } class YLSinglerowView: UIView { //枚举 enum ScrollStyle {//滚动方式 case right //向右滚动 case left //向左滚动 case up //向上滚动 case down //向下滚动 } //MARK: --属性 fileprivate var style : ScrollStyle? fileprivate var singlerTimer : Timer? fileprivate var time : Double? fileprivate var index : CGFloat? //MARK: -- 公开的属性=============================================== //背景颜色 var backColor : UIColor? { didSet { collectionView.backgroundColor = backColor } } var contentTextColor : UIColor = .white var contentFont : UIFont = .systemFont(ofSize: 13) var tagFont : UIFont = .systemFont(ofSize: 11) var tagTextColor : UIColor = .red var tagBackgroundColor : UIColor = UIColor(red: 230/255, green: 130/255, blue: 110/255, alpha: 1) var tagBackgroundColors : [UIColor]? = [] //如果你设置这个属性,务必保证数组个数和你的数据数组个数相同,否则你将收到程序的crash var tagTextColors : [UIColor]? = [] //如果你设置这个属性,务必保证数组个数和你的数据数组个数相同,否则你将收到程序的crash //================================================================ weak var delegate : YLSinglerViewDelegate? //MARK: -- 懒加载 fileprivate var contentSource : [String]? = [String]() fileprivate var tagSource : [String]? = [String]() fileprivate lazy var collectionView : UICollectionView = {[weak self] in //创建collectionView let layout = UICollectionViewFlowLayout() let collectionView = UICollectionView(frame: self!.bounds, collectionViewLayout: layout) collectionView.bounces = false collectionView.dataSource = self collectionView.backgroundColor = UIColor(red: 54/255, green: 54/255, blue: 54/255, alpha: 1) collectionView.isScrollEnabled = false collectionView.delegate = self collectionView.register(YLSinglerowCell.self, forCellWithReuseIdentifier: kSingCellId) return collectionView }() init(frame: CGRect, scrollStyle : ScrollStyle = .left, roundTime : Double = 4.5, contentSource : [String], tagSource : [String] = []) { /** frame scrollStyle contentSource 参数是必须传入的。 * 其他可不传入,直接删除代码即可 * 另外tagSource如不传入,则默认不再创建tagLabel这个控件 */ super.init(frame: frame) self.style = scrollStyle self.time = roundTime self.contentSource = contentSource self.tagSource = tagSource setupUI() } deinit { removeSinglerViewTimer() print("SinglerView销毁了") } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { //设置layout(获取的尺寸准确,所以在这里设置) let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout layout.itemSize = collectionView.bounds.size layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 if style == ScrollStyle.right || style == ScrollStyle.left { layout.scrollDirection = .horizontal }else { layout.scrollDirection = .vertical } collectionView.showsHorizontalScrollIndicator = false collectionView.isPagingEnabled = true //设置该空间不随着父控件的拉伸而拉伸 autoresizingMask = UIViewAutoresizing() } } //MARK: -- 设置UI extension YLSinglerowView { fileprivate func setupUI() { addSubview(collectionView) //滚动到该位置(让用户最开始就可以向左滚动) index = CGFloat((contentSource?.count)!) * 5000 if style == ScrollStyle.right || style == ScrollStyle.left { collectionView.setContentOffset(CGPoint(x: collectionView.bounds.width * index!, y: 0), animated: false) }else { collectionView.setContentOffset(CGPoint(x: 0, y: collectionView.bounds.height * index!), animated: false) } removeSinglerViewTimer() addSinglerViewTimer() } } //MARK: -- UICollectionViewcontentSource extension YLSinglerowView : UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return (contentSource?.count ?? 0) * 10000 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { //创建cell let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kSingCellId, for: indexPath) as! YLSinglerowCell cell.contentLabel?.textColor = contentTextColor cell.contentLabel?.text = contentSource![indexPath.row % contentSource!.count] cell.contentLabel?.font = contentFont if tagSource!.count > 0 { cell.tagLabel?.font = tagFont cell.tagLabel?.text = tagSource![indexPath.row % tagSource!.count] if tagBackgroundColors!.count > 0 { cell.tagLabel?.backgroundColor = tagBackgroundColors![indexPath.row % tagBackgroundColors!.count] }else { cell.tagLabel?.backgroundColor = tagBackgroundColor } if tagTextColors!.count > 0 { cell.tagLabel?.textColor = tagTextColors![indexPath.row % tagTextColors!.count] }else { cell.tagLabel?.textColor = tagTextColor } }else { cell.tagLabel?.removeFromSuperview() cell.contentLabel?.frame = CGRect(x: 5, y: 0, width: self.bounds.width, height: self.bounds.height) } return cell } } extension YLSinglerowView : UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { print("点击了第\(indexPath.row % contentSource!.count)个数据") self.delegate?.singlerView(self, selectedIndex: indexPath.row % contentSource!.count) } } //MARK: -- 时间控制器 extension YLSinglerowView { fileprivate func addSinglerViewTimer() { weak var weakSelf = self//解决循环引用 if #available(iOS 10.0, *) { singlerTimer = Timer(timeInterval: time!, repeats: true, block: {(timer) in weakSelf!.scrollToNextPage() }) } else { singlerTimer = Timer(timeInterval: time!, target: self, selector: #selector(scrollToNextPage), userInfo: nil, repeats: true) // Fallback on earlier versions } RunLoop.main.add(singlerTimer!, forMode: .commonModes) } fileprivate func removeSinglerViewTimer() { singlerTimer?.invalidate()//移除 singlerTimer = nil } @objc fileprivate func scrollToNextPage() { var position : UICollectionViewScrollPosition if style == ScrollStyle.right || style == ScrollStyle.left { position = style == .left ? UICollectionViewScrollPosition.left : UICollectionViewScrollPosition.right }else { position = style == .up ? UICollectionViewScrollPosition.top : UICollectionViewScrollPosition.bottom } if style == ScrollStyle.left || style == ScrollStyle.up { index! += 1 }else { index! -= 1 } let indexPath = IndexPath(item: Int(index!), section: 0) self.collectionView.scrollToItem(at: indexPath, at: position, animated: true) } } //MARK: ====================Cell类========================= class YLSinglerowCell: UICollectionViewCell { lazy var contentLabel : UILabel? = {[weak self] in let label = UILabel(frame: CGRect(x: 45, y: 0, width: self!.bounds.width - 43, height: self!.bounds.height)) return label }() lazy var tagLabel : UILabel? = {[weak self] in let label = UILabel(frame: CGRect(x: 3, y: (self!.bounds.height - 16) / 2, width: 40, height: 16)) label.layer.cornerRadius = 7 label.layer.masksToBounds = true label.textAlignment = .center return label }() override init(frame: CGRect) { super.init(frame: frame) setupContentUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { setupContentUI() } func setupContentUI() { contentView.addSubview(contentLabel!) contentView.addSubview(tagLabel!) } }
293d9c53d94188685dd79fea03b3df20
34.22541
139
0.634206
false
false
false
false
MengTo/Spring
refs/heads/master
Spring/SoundPlayer.swift
mit
2
// The MIT License (MIT) // // Copyright (c) 2015 James Tang ([email protected]) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit import AudioToolbox public struct SoundPlayer { static var filename : String? static var enabled : Bool = true private struct Internal { static var cache = [URL:SystemSoundID]() } public static func playSound(soundFile: String) { if !enabled { return } if let url = Bundle.main.url(forResource: soundFile, withExtension: nil) { var soundID : SystemSoundID = Internal.cache[url] ?? 0 if soundID == 0 { AudioServicesCreateSystemSoundID(url as CFURL, &soundID) Internal.cache[url] = soundID } AudioServicesPlaySystemSound(soundID) } else { print("Could not find sound file name `\(soundFile)`") } } static func play(file: String) { self.playSound(soundFile: file) } }
5db73461951e6fe72c6f443ed1e26264
34.25
82
0.656738
false
false
false
false
groue/GRDB.swift
refs/heads/master
Tests/CombineExpectations/PublisherExpectation.swift
mit
1
#if canImport(Combine) import XCTest /// A name space for publisher expectations public enum PublisherExpectations { } /// The base protocol for PublisherExpectation. It is an implementation detail /// that you are not supposed to use, as shown by the underscore prefix. public protocol _PublisherExpectationBase { /// Sets up an XCTestExpectation. This method is an implementation detail /// that you are not supposed to use, as shown by the underscore prefix. func _setup(_ expectation: XCTestExpectation) /// Returns an object that waits for the expectation. If nil, expectation /// is waited by the XCTestCase. func _makeWaiter() -> XCTWaiter? } extension _PublisherExpectationBase { public func _makeWaiter() -> XCTWaiter? { nil } } /// The protocol for publisher expectations. /// /// You can build publisher expectations from Recorder returned by the /// `Publisher.record()` method. /// /// For example: /// /// // The expectation for all published elements until completion /// let publisher = ["foo", "bar", "baz"].publisher /// let recorder = publisher.record() /// let expectation = recorder.elements /// /// When a test grants some time for the expectation to fulfill, use the /// XCTest `wait(for:timeout:description)` method: /// /// // SUCCESS: no timeout, no error /// func testArrayPublisherPublishesArrayElements() throws { /// let publisher = ["foo", "bar", "baz"].publisher /// let recorder = publisher.record() /// let expectation = recorder.elements /// let elements = try wait(for: expectation, timeout: 1) /// XCTAssertEqual(elements, ["foo", "bar", "baz"]) /// } /// /// On the other hand, when the expectation is supposed to be immediately /// fulfilled, use the PublisherExpectation `get()` method in order to grab the /// expected value: /// /// // SUCCESS: no error /// func testArrayPublisherSynchronouslyPublishesArrayElements() throws { /// let publisher = ["foo", "bar", "baz"].publisher /// let recorder = publisher.record() /// let elements = try recorder.elements.get() /// XCTAssertEqual(elements, ["foo", "bar", "baz"]) /// } public protocol PublisherExpectation: _PublisherExpectationBase { /// The type of the expected value. associatedtype Output /// Returns the expected value, or throws an error if the /// expectation fails. /// /// For example: /// /// // SUCCESS: no error /// func testArrayPublisherSynchronouslyPublishesArrayElements() throws { /// let publisher = ["foo", "bar", "baz"].publisher /// let recorder = publisher.record() /// let elements = try recorder.elements.get() /// XCTAssertEqual(elements, ["foo", "bar", "baz"]) /// } func get() throws -> Output } extension XCTestCase { /// Waits for the publisher expectation to fulfill, and returns the /// expected value. /// /// For example: /// /// // SUCCESS: no timeout, no error /// func testArrayPublisherPublishesArrayElements() throws { /// let publisher = ["foo", "bar", "baz"].publisher /// let recorder = publisher.record() /// let elements = try wait(for: recorder.elements, timeout: 1) /// XCTAssertEqual(elements, ["foo", "bar", "baz"]) /// } /// /// - parameter publisherExpectation: The publisher expectation. /// - parameter timeout: The number of seconds within which the expectation /// must be fulfilled. /// - parameter description: A string to display in the test log for the /// expectation, to help diagnose failures. /// - throws: An error if the expectation fails. public func wait<R: PublisherExpectation>( for publisherExpectation: R, timeout: TimeInterval, description: String = "") throws -> R.Output { let expectation = self.expectation(description: description) publisherExpectation._setup(expectation) if let waiter = publisherExpectation._makeWaiter() { waiter.wait(for: [expectation], timeout: timeout) } else { wait(for: [expectation], timeout: timeout) } return try publisherExpectation.get() } } #endif
95a47e521c7a15a9e832c1b3add5e250
37.477876
81
0.635005
false
true
false
false
IvoPaunov/selfie-apocalypse
refs/heads/master
Selfie apocalypse/Frameworks/DCKit/UITextFields/DCMandatoryTextField.swift
mit
1
// // BorderedTextField.swift // DCKit // // Created by Andrey Gordeev on 16/02/15. // Copyright (c) 2015 Andrey Gordeev ([email protected]). All rights reserved. // import UIKit /// Highlights the text field if the entered value is false. @IBDesignable public class DCMandatoryTextField: DCBorderedTextField { override public var selected: Bool { didSet { updateColor() } } @IBInspectable public var highlightedBorderColor: UIColor = UIColor.redColor() { didSet { updateColor() } } @IBInspectable public var isMandatory: Bool = true // MARK: - Build control override public func customInit() { super.customInit() updateColor() isValid() self.addTarget(self, action: Selector("isValid"), forControlEvents: UIControlEvents.EditingChanged) } // MARK: - Initializers // IBDesignables require both of these inits, otherwise we'll get an error: IBDesignable View Rendering times out. // http://stackoverflow.com/questions/26772729/ibdesignable-view-rendering-times-out override public init(frame: CGRect) { super.init(frame: frame) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } // MARK: - Build control override public func configurePlaceholder() { } // MARK: - Validation /// Checks if the field's value is valid. Can be overriden by subclasses. /// /// :return: True, if the field is mandatory and value is not empty. public func isValid() -> Bool { if isMandatory { let valid = !(text ?? "").isEmpty selected = !valid return valid } else { return true } } // MARK: - Misc func updateColor() { layer.borderColor = selected ? highlightedBorderColor.CGColor : normalBorderColor.CGColor } }
70e3eed5452603e6a3e1fa32d321b853
23.804878
118
0.598328
false
false
false
false
Alloc-Studio/Hypnos
refs/heads/master
Hypnos/Hypnos/Controller/Recommend/RecommendViewController.swift
mit
1
// // RecommendViewController.swift // Hypnos // // Created by Fay on 16/5/18. // Copyright © 2016年 DMT312. All rights reserved. // import UIKit import Alamofire import SwiftyJSON import SVProgressHUD class RecommendViewController: UITableViewController { var banner: RecommendBanner! var unloginView: UnloginView! var viewModel = RecommendViewModel() // MARK: - Life Cycle override func viewDidLoad() { super.viewDidLoad() setupUI() setupSetting() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) navigationController?.navigationBarHidden = false tabBarController?.tabBar.hidden = false } // MARK: - Private Method private func setupUI() { presentMusicItem() banner = NSBundle.mainBundle().loadNibNamed(String(RecommendBanner), owner: nil, options: nil).first as! RecommendBanner unloginView = NSBundle.mainBundle().loadNibNamed(String(UnloginView), owner: self, options: nil).first as! UnloginView WilddogService.loginStateWatching({ [unowned self] (data) in self.unloginView.removeFromSuperview() self.view.userInteractionEnabled = true self.viewModel.fetchLatestData { () -> ()? in dispatch_async(dispatch_get_main_queue(), { SVProgressHUD.showWithStatus("正在拉取数据...") }) } }) { self.view.addSubview(self.unloginView) } navigationController?.navigationBar.hideBottomHairline() tableView.showsVerticalScrollIndicator = false tableView.bounces = false } private func setupSetting() { unloginView.loginMotion = { [unowned self] in let loginVC = UIStoryboard.customInstanceViewController(.Independence, cls: LoginViewController.self) as! LoginViewController self.presentViewController(UINavigationController(rootViewController: loginVC), animated: true, completion: nil) } tableView.registerNib(UINib(nibName: String(MusicListCell),bundle: nil), forCellReuseIdentifier: String(MusicListCell)) viewModel.configSourceDidUpdate { [unowned self] in self.tableView.reloadData() SVProgressHUD.dismiss() } } private lazy var musicPlayerVc:MusicPlayerController = { let vc:MusicPlayerController = MusicPlayerController() return vc }() } extension RecommendViewController { // MARK: - Data Source override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { tableView.tableViewDisplay(emptyMessage: "对不起,暂时没有数据哦~", count: viewModel.source.count) return viewModel.source.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(String(MusicListCell), forIndexPath: indexPath) as! MusicListCell viewModel.updateCell(cell, AtIndex: indexPath) return cell } // MARK: - Delegate override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { musicPlayerVc.view.frame = view.bounds musicPlayerVc.musicModel = viewModel.source[indexPath.row] musicPlayerVc.musics = viewModel.source navigationController?.pushViewController(musicPlayerVc, animated: true) } override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return viewModel.heightForHeaderInSection(section) } override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { return banner } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return viewModel.heightForRow(indexPath) } override func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { return UIView() } } extension RecommendViewController: MCItemPresentable { func showMuicController() { guard let _ = Player.sharedPlayer().musicModel else { SweetAlert().showAlert("亲~", subTitle: "您还没有选择歌曲哦~~~", style: AlertStyle.CustomImag(imageFile: "recommend_cry")) return } navigationController?.pushViewController(Player.sharedPlayer(), animated: true) } }
1b7310196a10fa670a0ff9c4296cebd0
32.136986
137
0.661567
false
false
false
false
zvonler/PasswordElephant
refs/heads/master
external/github.com/apple/swift-protobuf/Sources/protoc-gen-swift/EnumGenerator.swift
gpl-3.0
1
// Sources/protoc-gen-swift/EnumGenerator.swift - Enum logic // // Copyright (c) 2014 - 2016 Apple Inc. and the project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See LICENSE.txt for license information: // https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt // // ----------------------------------------------------------------------------- /// /// This file handles the generation of a Swift enum for each .proto enum. /// // ----------------------------------------------------------------------------- import Foundation import SwiftProtobufPluginLibrary import SwiftProtobuf /// The name of the case used to represent unrecognized values in proto3. /// This case has an associated value containing the raw integer value. private let unrecognizedCaseName = "UNRECOGNIZED" /// Generates a Swift enum from a protobuf enum descriptor. class EnumGenerator { private let enumDescriptor: EnumDescriptor private let generatorOptions: GeneratorOptions private let namer: SwiftProtobufNamer /// The values that aren't aliases, sorted by number. private let mainEnumValueDescriptorsSorted: [EnumValueDescriptor] private let swiftRelativeName: String private let swiftFullName: String init(descriptor: EnumDescriptor, generatorOptions: GeneratorOptions, namer: SwiftProtobufNamer ) { self.enumDescriptor = descriptor self.generatorOptions = generatorOptions self.namer = namer mainEnumValueDescriptorsSorted = descriptor.values.filter({ return $0.aliasOf == nil }).sorted(by: { return $0.number < $1.number }) swiftRelativeName = namer.relativeName(enum: descriptor) swiftFullName = namer.fullName(enum: descriptor) } func generateMainEnum(printer p: inout CodePrinter) { let visibility = generatorOptions.visibilitySourceSnippet p.print("\n") p.print(enumDescriptor.protoSourceComments()) p.print("\(visibility)enum \(swiftRelativeName): SwiftProtobuf.Enum {\n") p.indent() p.print("\(visibility)typealias RawValue = Int\n") // Cases/aliases generateCasesOrAliases(printer: &p) // Generate the default initializer. p.print("\n") p.print("\(visibility)init() {\n") p.indent() let dottedDefault = namer.dottedRelativeName(enumValue: enumDescriptor.defaultValue) p.print("self = \(dottedDefault)\n") p.outdent() p.print("}\n") p.print("\n") generateInitRawValue(printer: &p) p.print("\n") generateRawValueProperty(printer: &p) p.outdent() p.print("\n") p.print("}\n") } func generateRuntimeSupport(printer p: inout CodePrinter) { p.print("\n") p.print("extension \(swiftFullName): SwiftProtobuf._ProtoNameProviding {\n") p.indent() generateProtoNameProviding(printer: &p) p.outdent() p.print("}\n") } /// Generates the cases or statics (for alias) for the values. /// /// - Parameter p: The code printer. private func generateCasesOrAliases(printer p: inout CodePrinter) { let visibility = generatorOptions.visibilitySourceSnippet for enumValueDescriptor in namer.uniquelyNamedValues(enum: enumDescriptor) { let comments = enumValueDescriptor.protoSourceComments() if !comments.isEmpty { p.print("\n", comments) } let relativeName = namer.relativeName(enumValue: enumValueDescriptor) if let aliasOf = enumValueDescriptor.aliasOf { let aliasOfName = namer.relativeName(enumValue: aliasOf) p.print("\(visibility)static let \(relativeName) = \(aliasOfName)\n") } else { p.print("case \(relativeName) // = \(enumValueDescriptor.number)\n") } } if enumDescriptor.hasUnknownPreservingSemantics { p.print("case \(unrecognizedCaseName)(Int)\n") } } /// Generates the mapping from case numbers to their text/JSON names. /// /// - Parameter p: The code printer. private func generateProtoNameProviding(printer p: inout CodePrinter) { let visibility = generatorOptions.visibilitySourceSnippet p.print("\(visibility)static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n") p.indent() for v in mainEnumValueDescriptorsSorted { if v.aliases.isEmpty { p.print("\(v.number): .same(proto: \"\(v.name)\"),\n") } else { let aliasNames = v.aliases.map({ "\"\($0.name)\"" }).joined(separator: ", ") p.print("\(v.number): .aliased(proto: \"\(v.name)\", aliases: [\(aliasNames)]),\n") } } p.outdent() p.print("]\n") } /// Generates `init?(rawValue:)` for the enum. /// /// - Parameter p: The code printer. private func generateInitRawValue(printer p: inout CodePrinter) { let visibility = generatorOptions.visibilitySourceSnippet p.print("\(visibility)init?(rawValue: Int) {\n") p.indent() p.print("switch rawValue {\n") for v in mainEnumValueDescriptorsSorted { let dottedName = namer.dottedRelativeName(enumValue: v) p.print("case \(v.number): self = \(dottedName)\n") } if enumDescriptor.hasUnknownPreservingSemantics { p.print("default: self = .\(unrecognizedCaseName)(rawValue)\n") } else { p.print("default: return nil\n") } p.print("}\n") p.outdent() p.print("}\n") } /// Generates the `rawValue` property of the enum. /// /// - Parameter p: The code printer. private func generateRawValueProperty(printer p: inout CodePrinter) { let visibility = generatorOptions.visibilitySourceSnippet p.print("\(visibility)var rawValue: Int {\n") p.indent() p.print("switch self {\n") for v in mainEnumValueDescriptorsSorted { let dottedName = namer.dottedRelativeName(enumValue: v) p.print("case \(dottedName): return \(v.number)\n") } if enumDescriptor.hasUnknownPreservingSemantics { p.print("case .\(unrecognizedCaseName)(let i): return i\n") } p.print("}\n") p.outdent() p.print("}\n") } }
7286132a3c67a669f8c7d3cb6bc045c4
32.233333
91
0.661317
false
false
false
false
FotiosTragopoulos/Core-Geometry
refs/heads/master
Core Geometry/Pol1ViewPolygon.swift
apache-2.0
1
// // Pol1ViewPolygon.swift // Core Geometry // // Created by Fotios Tragopoulos on 16/01/2017. // Copyright © 2017 Fotios Tragopoulos. All rights reserved. // import UIKit class Pol1ViewPolygon: UIView { override func draw(_ rect: CGRect) { let context = UIGraphicsGetCurrentContext() let myShadowOffset = CGSize (width: 10, height: 10) context?.setShadow (offset: myShadowOffset, blur: 8) context?.saveGState() context?.setLineWidth(3.0) context?.setStrokeColor(UIColor.blue.cgColor) let xView = viewWithTag(19)?.alignmentRect(forFrame: rect).midX let yView = viewWithTag(19)?.alignmentRect(forFrame: rect).midY let width = self.viewWithTag(19)?.frame.size.width let height = self.viewWithTag(19)?.frame.size.height let size = CGSize(width: width! * 0.6, height: height! * 0.4) let linePlacementX = CGFloat(size.width/1.6) let linePlacementY = CGFloat(size.height/1.6) context?.move(to: CGPoint(x: (xView! - linePlacementX), y: yView!)) context?.addLine(to: CGPoint(x: (xView! - (linePlacementX * 0.5)), y: (yView! - (linePlacementY * 1.3)))) context?.addLine(to: CGPoint(x: (xView! + (linePlacementX * 0.5)), y: (yView! - (linePlacementY * 1.3)))) context?.addLine(to: CGPoint(x: (xView! + linePlacementX), y: yView!)) context?.addLine(to: CGPoint(x: (xView! + (linePlacementX * 0.5)), y: (yView! + (linePlacementY * 1.3)))) context?.addLine(to: CGPoint(x: (xView! - (linePlacementX * 0.5)), y: (yView! + (linePlacementY * 1.3)))) context?.addLine(to: CGPoint(x: (xView! - linePlacementX), y: yView!)) let dashArray:[CGFloat] = [10, 4] context?.setLineDash(phase: 3, lengths: dashArray) context?.strokePath() context?.restoreGState() self.transform = CGAffineTransform(scaleX: 0.8, y: 0.8) UIView.animate(withDuration: 1.0, delay: 0, usingSpringWithDamping: 0.15, initialSpringVelocity: 6.0, options: .allowUserInteraction, animations: { self.transform = CGAffineTransform.identity } ,completion: nil) } }
dd445252fbfb3cde65910abaf6439b3a
43.28
219
0.62421
false
false
false
false
angmu/SwiftPlayCode
refs/heads/master
swift练习/playground Test.playground/Sources/Shape.swift
mit
1
import Foundation import UIKit //比较稳定的代码,放着里面 //: # Shape Type public enum ShapeType { case Triangle case Square case Round } //: # Shape View public class Shape: UIView { var type: ShapeType = .Triangle public init(frame: CGRect, type: ShapeType = .Triangle) { super.init(frame: frame) self.backgroundColor = UIColor.whiteColor() self.type = type } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not implement") } override public func drawRect(rect: CGRect) { let bezier: UIBezierPath = UIBezierPath() switch type { case .Triangle: bezier.moveToPoint(CGPoint(x: 0.0, y: 0.0)) bezier.addLineToPoint(CGPoint(x: 100.0, y: 20.0)) bezier.addLineToPoint(CGPoint(x: 30.0, y: 60.0)) case .Square: bezier.moveToPoint(CGPoint(x: 10.0, y: 20.0)) bezier.addLineToPoint(CGPoint(x: 90.0, y: 20.0)) bezier.addLineToPoint(CGPoint(x: 90.0, y: 80.0)) bezier.addLineToPoint(CGPoint(x: 10.0, y: 80.0)) case .Round: bezier.addArcWithCenter(CGPoint(x: self.center.x, y: self.center.y), radius: 25.0, startAngle: 0, endAngle: CGFloat(M_PI) * 2.0, clockwise: true) } bezier.lineWidth = 2.0 let fillColor = UIColor.redColor() fillColor.set() bezier.closePath() bezier.fill() } }
a7546b90e22fddf81ae56fd928fb52a2
26.142857
157
0.571053
false
false
false
false
MukeshKumarS/Swift
refs/heads/master
stdlib/public/core/OutputStream.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SwiftShims //===----------------------------------------------------------------------===// // Input/Output interfaces //===----------------------------------------------------------------------===// /// A target of text streaming operations. public protocol OutputStreamType { mutating func _lock() mutating func _unlock() /// Append the given `string` to this stream. mutating func write(string: String) } extension OutputStreamType { public mutating func _lock() {} public mutating func _unlock() {} } /// A source of text streaming operations. `Streamable` instances can /// be written to any *output stream*. /// /// For example: `String`, `Character`, `UnicodeScalar`. public protocol Streamable { /// Write a textual representation of `self` into `target`. func writeTo<Target : OutputStreamType>(inout target: Target) } /// A type with a customized textual representation. /// /// This textual representation is used when values are written to an /// *output stream*, for example, by `print`. /// /// - Note: `String(instance)` will work for an `instance` of *any* /// type, returning its `description` if the `instance` happens to be /// `CustomStringConvertible`. Using `CustomStringConvertible` as a /// generic constraint, or accessing a conforming type's `description` /// directly, is therefore discouraged. /// /// - SeeAlso: `String.init<T>(T)`, `CustomDebugStringConvertible` public protocol CustomStringConvertible { /// A textual representation of `self`. var description: String { get } } /// A type with a customized textual representation suitable for /// debugging purposes. /// /// This textual representation is used when values are written to an /// *output stream* by `debugPrint`, and is /// typically more verbose than the text provided by a /// `CustomStringConvertible`'s `description` property. /// /// - Note: `String(reflecting: instance)` will work for an `instance` /// of *any* type, returning its `debugDescription` if the `instance` /// happens to be `CustomDebugStringConvertible`. Using /// `CustomDebugStringConvertible` as a generic constraint, or /// accessing a conforming type's `debugDescription` directly, is /// therefore discouraged. /// /// - SeeAlso: `String.init<T>(reflecting: T)`, /// `CustomStringConvertible` public protocol CustomDebugStringConvertible { /// A textual representation of `self`, suitable for debugging. var debugDescription: String { get } } //===----------------------------------------------------------------------===// // Default (ad-hoc) printing //===----------------------------------------------------------------------===// /// Do our best to print a value that cannot be printed directly. internal func _adHocPrint<T, TargetStream : OutputStreamType>( value: T, inout _ target: TargetStream, isDebugPrint: Bool ) { func printTypeName(type: Any.Type) { // Print type names without qualification, unless we're debugPrint'ing. target.write(_typeName(type, qualified: isDebugPrint)) } let mirror = _reflect(value) switch mirror { // Checking the mirror kind is not a good way to implement this, but we don't // have a more expressive reflection API now. case is _TupleMirror: target.write("(") var first = true for i in 0..<mirror.count { if first { first = false } else { target.write(", ") } let (_, elementMirror) = mirror[i] let elt = elementMirror.value debugPrint(elt, terminator: "", toStream: &target) } target.write(")") case is _StructMirror: printTypeName(mirror.valueType) target.write("(") var first = true for i in 0..<mirror.count { if first { first = false } else { target.write(", ") } let (label, elementMirror) = mirror[i] print(label, terminator: "", toStream: &target) target.write(": ") debugPrint(elementMirror.value, terminator: "", toStream: &target) } target.write(")") case let enumMirror as _EnumMirror: if let caseName = String.fromCString(enumMirror.caseName) { // Write the qualified type name in debugPrint. if isDebugPrint { target.write(_typeName(mirror.valueType)) target.write(".") } target.write(caseName) } else { // If the case name is garbage, just print the type name. printTypeName(mirror.valueType) } if mirror.count == 0 { return } let (_, payload) = mirror[0] if payload is _TupleMirror { debugPrint(payload.value, terminator: "", toStream: &target) return } target.write("(") debugPrint(payload.value, terminator: "", toStream: &target) target.write(")") case is _MetatypeMirror: printTypeName(mirror.value as! Any.Type) default: print(mirror.summary, terminator: "", toStream: &target) } } @inline(never) @_semantics("stdlib_binary_only") internal func _print_unlocked<T, TargetStream : OutputStreamType>( value: T, inout _ target: TargetStream ) { // Optional has no representation suitable for display; therefore, // values of optional type should be printed as a debug // string. Check for Optional first, before checking protocol // conformance below, because an Optional value is convertible to a // protocol if its wrapped type conforms to that protocol. if _isOptional(value.dynamicType) { let debugPrintable = value as! CustomDebugStringConvertible debugPrintable.debugDescription.writeTo(&target) return } if case let streamableObject as Streamable = value { streamableObject.writeTo(&target) return } if case let printableObject as CustomStringConvertible = value { printableObject.description.writeTo(&target) return } if case let debugPrintableObject as CustomDebugStringConvertible = value { debugPrintableObject.debugDescription.writeTo(&target) return } _adHocPrint(value, &target, isDebugPrint: false) } /// Returns the result of `print`'ing `x` into a `String`. /// /// Exactly the same as `String`, but annotated 'readonly' to allow /// the optimizer to remove calls where results are unused. /// /// This function is forbidden from being inlined because when building the /// standard library inlining makes us drop the special semantics. @inline(never) @effects(readonly) func _toStringReadOnlyStreamable<T : Streamable>(x: T) -> String { var result = "" x.writeTo(&result) return result } @inline(never) @effects(readonly) func _toStringReadOnlyPrintable<T : CustomStringConvertible>(x: T) -> String { return x.description } //===----------------------------------------------------------------------===// // `debugPrint` //===----------------------------------------------------------------------===// @inline(never) public func _debugPrint_unlocked<T, TargetStream : OutputStreamType>( value: T, inout _ target: TargetStream ) { if let debugPrintableObject = value as? CustomDebugStringConvertible { debugPrintableObject.debugDescription.writeTo(&target) return } if let printableObject = value as? CustomStringConvertible { printableObject.description.writeTo(&target) return } if let streamableObject = value as? Streamable { streamableObject.writeTo(&target) return } _adHocPrint(value, &target, isDebugPrint: true) } //===----------------------------------------------------------------------===// // OutputStreams //===----------------------------------------------------------------------===// internal struct _Stdout : OutputStreamType { mutating func _lock() { _swift_stdlib_flockfile_stdout() } mutating func _unlock() { _swift_stdlib_funlockfile_stdout() } mutating func write(string: String) { // FIXME: buffering? // It is important that we use stdio routines in order to correctly // interoperate with stdio buffering. for c in string.utf8 { _swift_stdlib_putchar(Int32(c)) } } } extension String : OutputStreamType { /// Append `other` to this stream. public mutating func write(other: String) { self += other } } //===----------------------------------------------------------------------===// // Streamables //===----------------------------------------------------------------------===// extension String : Streamable { /// Write a textual representation of `self` into `target`. public func writeTo<Target : OutputStreamType>(inout target: Target) { target.write(self) } } extension Character : Streamable { /// Write a textual representation of `self` into `target`. public func writeTo<Target : OutputStreamType>(inout target: Target) { target.write(String(self)) } } extension UnicodeScalar : Streamable { /// Write a textual representation of `self` into `target`. public func writeTo<Target : OutputStreamType>(inout target: Target) { target.write(String(Character(self))) } } //===----------------------------------------------------------------------===// // Unavailable APIs //===----------------------------------------------------------------------===// @available(*, unavailable, renamed="CustomDebugStringConvertible") public typealias DebugPrintable = CustomDebugStringConvertible @available(*, unavailable, renamed="CustomStringConvertible") public typealias Printable = CustomStringConvertible @available(*, unavailable, renamed="print") public func println<T, TargetStream : OutputStreamType>( value: T, inout _ target: TargetStream ) { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed="print") public func println<T>(value: T) { fatalError("unavailable function can't be called") } @available(*, unavailable, message="use print(\"\")") public func println() { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed="String") public func toString<T>(x: T) -> String { fatalError("unavailable function can't be called") } @available(*, unavailable, message="use debugPrint()") public func debugPrintln<T, TargetStream : OutputStreamType>( x: T, inout _ target: TargetStream ) { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed="debugPrint") public func debugPrintln<T>(x: T) { fatalError("unavailable function can't be called") } /// Returns the result of `debugPrint`'ing `x` into a `String`. @available(*, unavailable, message="use String(reflecting:)") public func toDebugString<T>(x: T) -> String { fatalError("unavailable function can't be called") } /// A hook for playgrounds to print through. public var _playgroundPrintHook : ((String)->Void)? = {_ in () } internal struct _TeeStream< L : OutputStreamType, R : OutputStreamType > : OutputStreamType { var left: L var right: R /// Append the given `string` to this stream. mutating func write(string: String) { left.write(string); right.write(string) } mutating func _lock() { left._lock(); right._lock() } mutating func _unlock() { left._unlock(); right._unlock() } }
aa5ba0f7df977e3151b7964676909306
31.024862
80
0.631761
false
false
false
false
spark/photon-tinker-ios
refs/heads/master
Photon-Tinker/Mesh/Gen3SetupControlPanelPrepareForPairingViewController.swift
apache-2.0
1
// // Created by Raimundas Sakalauskas on 9/20/18. // Copyright (c) 2018 Particle. All rights reserved. // import UIKit import AVFoundation import AVKit class Gen3SetupControlPanelPrepareForPairingViewController: Gen3SetupViewController, Storyboardable { internal var videoPlayer: AVPlayer? internal var layer: AVPlayerLayer? internal var defaultVideo : AVPlayerItem? internal var defaultVideoURL: URL! internal var isSOM:Bool! @IBOutlet weak var textLabel: ParticleLabel! @IBOutlet weak var videoView: UIControl! @IBOutlet weak var signalSwitch: UISwitch! @IBOutlet weak var signalLabel: ParticleLabel! @IBOutlet weak var signalWarningLabel: ParticleLabel! private var device: ParticleDevice! override var customTitle: String { return Gen3SetupStrings.ControlPanel.PrepareForPairing.Title } override func viewDidLoad() { super.viewDidLoad() setContent() } func setup(device: ParticleDevice!) { self.device = device self.deviceName = device.name! self.deviceType = device.type self.isSOM = (self.deviceType! == ParticleDeviceType.aSeries || self.deviceType! == ParticleDeviceType.bSeries || self.deviceType! == ParticleDeviceType.xSeries) } override func setStyle() { videoView.backgroundColor = .clear videoView.layer.cornerRadius = 5 videoView.clipsToBounds = true textLabel.setStyle(font: ParticleStyle.RegularFont, size: ParticleStyle.RegularSize, color: ParticleStyle.PrimaryTextColor) signalLabel.setStyle(font: ParticleStyle.BoldFont, size: ParticleStyle.RegularSize, color: ParticleStyle.PrimaryTextColor) signalWarningLabel.setStyle(font: ParticleStyle.RegularFont, size: ParticleStyle.SmallSize, color: ParticleStyle.PrimaryTextColor) } override func setContent() { textLabel.text = Gen3SetupStrings.ControlPanel.PrepareForPairing.Text signalLabel.text = Gen3SetupStrings.ControlPanel.PrepareForPairing.Signal signalWarningLabel.text = Gen3SetupStrings.ControlPanel.PrepareForPairing.SignalWarning initializeVideoPlayerWithVideo(videoFileName: "prepare_for_pairing") videoView.addTarget(self, action: #selector(videoViewTapped), for: .touchUpInside) view.setNeedsLayout() view.layoutIfNeeded() } @objc public func videoViewTapped(sender: UIControl) { // TODO: uncomment this, but figure out how to exit fullscreen video mode if device enters listening mode while it is visible (otherwise flow stops) // let player = AVPlayer(url: defaultVideoURL) // // let playerController = AVPlayerViewController() // playerController.player = player // present(playerController, animated: true) { // player.play() // } } @IBAction func signalSwitchValueChanged(_ sender: Any) { if signalSwitch.isOn { self.device.signal(true) } else { self.device.signal(false) } } func initializeVideoPlayerWithVideo(videoFileName: String) { if (self.videoPlayer != nil) { return } // Create a new AVPlayerItem with the asset and an // array of asset keys to be automatically loaded let defaultVideoString:String? = Bundle.main.path(forResource: videoFileName, ofType: "mov") defaultVideoURL = URL(fileURLWithPath: defaultVideoString!) defaultVideo = AVPlayerItem(url: defaultVideoURL) self.videoPlayer = AVPlayer(playerItem: defaultVideo) layer = AVPlayerLayer(player: videoPlayer) layer!.frame = videoView.bounds layer!.videoGravity = AVLayerVideoGravity.resizeAspect NSLog("initializing layer?") videoView.layer.addSublayer(layer!) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) setVideoLoopObserver() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() layer?.frame = videoView.bounds } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) self.device.signal(false) self.signalSwitch.setOn(false, animated: false) desetVideoLoopObserver() } func desetVideoLoopObserver() { self.videoPlayer?.pause() NotificationCenter.default.removeObserver(self.videoPlayer?.currentItem) } func setVideoLoopObserver() { NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: self.videoPlayer?.currentItem, queue: .main) { _ in self.videoPlayer?.seek(to: CMTime.zero) self.videoPlayer?.play() } self.videoPlayer?.seek(to: CMTime.zero) self.videoPlayer?.play() } }
9974597d82181a539021f1f70f16deb9
30.406452
169
0.690427
false
false
false
false
obrichak/discounts
refs/heads/master
discounts/Classes/BarCodeGenerator/RSCodeGenerator.swift
gpl-3.0
1
// // RSCodeGenerator.swift // RSBarcodesSample // // Created by R0CKSTAR on 6/10/14. // Copyright (c) 2014 P.D.Q. All rights reserved. // import Foundation import UIKit import AVFoundation import CoreImage let DIGITS_STRING = "0123456789" // Code generators are required to provide these two functions. protocol RSCodeGenerator { func generateCode(machineReadableCodeObject:AVMetadataMachineReadableCodeObject) -> UIImage? func generateCode(contents:String, machineReadableCodeObjectType:String) -> UIImage? } // Check digit are not required for all code generators. // UPC-E is using check digit to valid the contents to be encoded. // Code39Mod43, Code93 and Code128 is using check digit to encode barcode. @objc protocol RSCheckDigitGenerator { func checkDigit(contents:String) -> String } // Abstract code generator, provides default functions for validations and generations. class RSAbstractCodeGenerator : RSCodeGenerator { // Check whether the given contents are valid. func isValid(contents:String) -> Bool { let length = contents.length() if length > 0 { for i in 0..<length { let character = contents[i] if !DIGITS_STRING.contains(character!) { return false } } return true } return false } // Barcode initiator, subclass should return its own value. func initiator() -> String { return "" } // Barcode terminator, subclass should return its own value. func terminator() -> String { return "" } // Barcode content, subclass should return its own value. func barcode(contents:String) -> String { return "" } // Composer for combining barcode initiator, contents, terminator together. func completeBarcode(barcode:String) -> String { return self.initiator() + barcode + self.terminator() } // Drawer for completed barcode. func drawCompleteBarcode(completeBarcode:String) -> UIImage? { let length:Int = completeBarcode.length() if length <= 0 { return nil } // Values taken from CIImage generated AVMetadataObjectTypePDF417Code type image // Top spacing = 1.5 // Bottom spacing = 2 // Left & right spacing = 2 // Height = 28 let width = length + 4 let size = CGSizeMake(CGFloat(width), 28) UIGraphicsBeginImageContextWithOptions(size, true, 0) let context = UIGraphicsGetCurrentContext() CGContextSetShouldAntialias(context, false) UIColor.whiteColor().setFill() UIColor.blackColor().setStroke() CGContextFillRect(context, CGRectMake(0, 0, size.width, size.height)) CGContextSetLineWidth(context, 1) for i in 0..<length { let character = completeBarcode[i] if character == "1" { let x = i + (2 + 1) CGContextMoveToPoint(context, CGFloat(x), 1.5) CGContextAddLineToPoint(context, CGFloat(x), size.height - 2) } } CGContextDrawPath(context, kCGPathFillStroke) let barcode = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return barcode } // RSCodeGenerator func generateCode(machineReadableCodeObject:AVMetadataMachineReadableCodeObject) -> UIImage? { return self.generateCode(machineReadableCodeObject.stringValue, machineReadableCodeObjectType: machineReadableCodeObject.type) } func generateCode(contents:String, machineReadableCodeObjectType:String) -> UIImage? { if self.isValid(contents) { return self.drawCompleteBarcode(self.completeBarcode(self.barcode(contents))) } return nil } // Class funcs // Get CIFilter name by machine readable code object type class func filterName(machineReadableCodeObjectType:String) -> String! { if machineReadableCodeObjectType == AVMetadataObjectTypeQRCode { return "CIQRCodeGenerator" } else if machineReadableCodeObjectType == AVMetadataObjectTypePDF417Code { return "CIPDF417BarcodeGenerator" } else if machineReadableCodeObjectType == AVMetadataObjectTypeAztecCode { return "CIAztecCodeGenerator" } else if machineReadableCodeObjectType == AVMetadataObjectTypeCode128Code { return "CICode128BarcodeGenerator" } else { return "" } } // Generate CI related code image class func generateCode(contents:String, filterName:String) -> UIImage { if filterName == "" { return UIImage() } let filter = CIFilter(name: filterName) filter.setDefaults() let inputMessage = contents.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) filter.setValue(inputMessage, forKey: "inputMessage") let outputImage = filter.outputImage let context = CIContext(options: nil) let cgImage = context.createCGImage(outputImage, fromRect: outputImage.extent()) return UIImage(CGImage: cgImage, scale: 1, orientation: UIImageOrientation.Up) } // Resize image class func resizeImage(source:UIImage, scale:CGFloat) -> UIImage { let width = source.size.width * scale let height = source.size.height * scale UIGraphicsBeginImageContext(CGSizeMake(width, height)) let context = UIGraphicsGetCurrentContext() CGContextSetInterpolationQuality(context, kCGInterpolationNone) source.drawInRect(CGRectMake(0, 0, width, height)) let target = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return target } }
b92db9ea9a7804a9c213dc49ecd20bfe
34.951807
134
0.648735
false
false
false
false
iAugux/GuillotineMenu
refs/heads/swift_2.0
GuillotineMenu/GuillotineMenuViewController.swift
mit
1
// // GuillotineViewController.swift // GuillotineMenu // // Created by Maksym Lazebnyi on 3/24/15. // Copyright (c) 2015 Yalantis. All rights reserved. // import UIKit class GuillotineMenuViewController: UIViewController { var hostNavigationBarHeight: CGFloat! var hostTitleText: NSString! var menuButton: UIButton! var menuButtonLeadingConstraint: NSLayoutConstraint! var menuButtonTopConstraint: NSLayoutConstraint! private let menuButtonLandscapeLeadingConstant: CGFloat = 1 private let menuButtonPortraitLeadingConstant: CGFloat = 7 private let hostNavigationBarHeightLandscape: CGFloat = 32 private let hostNavigationBarHeightPortrait: CGFloat = 44 override func viewDidLoad() { super.viewDidLoad() } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() } override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator) coordinator.animateAlongsideTransition(nil) { (context) -> Void in if UIDevice.currentDevice().orientation == .LandscapeLeft || UIDevice.currentDevice().orientation == .LandscapeRight { self.menuButtonLeadingConstraint.constant = self.menuButtonLandscapeLeadingConstant self.menuButtonTopConstraint.constant = self.menuButtonPortraitLeadingConstant } else { let statusbarHeight = UIApplication.sharedApplication().statusBarFrame.size.height self.menuButtonLeadingConstraint.constant = self.menuButtonPortraitLeadingConstant; self.menuButtonTopConstraint.constant = self.menuButtonPortraitLeadingConstant+statusbarHeight } } } // MARK: Actions func closeMenuButtonTapped() { self.dismissViewControllerAnimated(true, completion: nil) } func setMenuButtonWithImage(image: UIImage) { let statusbarHeight = UIApplication.sharedApplication().statusBarFrame.size.height let buttonImage = UIImage(CGImage: image.CGImage!, scale: 1.0, orientation: .Right) if UIDevice.currentDevice().orientation == .LandscapeLeft || UIDevice.currentDevice().orientation == .LandscapeRight { menuButton = UIButton(frame: CGRectMake(menuButtonPortraitLeadingConstant, menuButtonPortraitLeadingConstant+statusbarHeight, 30.0, 30.0)) } else { menuButton = UIButton(frame: CGRectMake(menuButtonPortraitLeadingConstant, menuButtonPortraitLeadingConstant+statusbarHeight, 30.0, 30.0)) } menuButton.setImage(image, forState: .Normal) menuButton.setImage(image, forState: .Highlighted) menuButton.imageView!.contentMode = .Center menuButton.addTarget(self, action: Selector("closeMenuButtonTapped"), forControlEvents: .TouchUpInside) menuButton.translatesAutoresizingMaskIntoConstraints = false menuButton.transform = CGAffineTransformMakeRotation( ( 90 * CGFloat(M_PI) ) / 180 ); self.view.addSubview(menuButton) if UIDevice.currentDevice().orientation == .LandscapeLeft || UIDevice.currentDevice().orientation == .LandscapeRight { var (leading, top) = self.view.addConstraintsForMenuButton(menuButton, offset: UIOffsetMake(menuButtonLandscapeLeadingConstant, menuButtonPortraitLeadingConstant)) menuButtonLeadingConstraint = leading menuButtonTopConstraint = top } else { var (leading, top) = self.view.addConstraintsForMenuButton(menuButton, offset: UIOffsetMake(menuButtonPortraitLeadingConstant, menuButtonPortraitLeadingConstant+statusbarHeight)) menuButtonLeadingConstraint = leading menuButtonTopConstraint = top } } } extension GuillotineMenuViewController: GuillotineAnimationProtocol { func anchorPoint() -> CGPoint { if UIDevice.currentDevice().orientation == .LandscapeLeft || UIDevice.currentDevice().orientation == .LandscapeRight { //In this case value is calculated manualy as the method is called before viewDidLayourSubbviews when the menuBarButton.frame is updated. return CGPointMake(16, 16) } return self.menuButton.center } func navigationBarHeight() -> CGFloat { if UIDevice.currentDevice().orientation == .LandscapeLeft || UIDevice.currentDevice().orientation == .LandscapeRight { return hostNavigationBarHeightLandscape } else { return hostNavigationBarHeightPortrait } } func hostTitle () -> NSString { return hostTitleText } }
f4aaf65569069e003ffd9a39f5bc8fc9
42.043103
190
0.707991
false
false
false
false
tasanobu/PullToRefreshSwift
refs/heads/master
Source/PullToRefreshView.swift
mit
1
// // PullToRefreshConst.swift // PullToRefreshSwift // // Created by Yuji Hato on 12/11/14. // import UIKit public class PullToRefreshView: UIView { enum PullToRefreshState { case Normal case Pulling case Refreshing } // MARK: Variables let contentOffsetKeyPath = "contentOffset" var kvoContext = "" private var options: PullToRefreshOption! private var backgroundView: UIView! private var arrow: UIImageView! private var indicator: UIActivityIndicatorView! private var scrollViewBounces: Bool = false private var scrollViewInsets: UIEdgeInsets = UIEdgeInsetsZero private var previousOffset: CGFloat = 0 private var refreshCompletion: (() -> ()) = {} var state: PullToRefreshState = PullToRefreshState.Normal { didSet { if self.state == oldValue { return } switch self.state { case .Normal: stopAnimating() case .Refreshing: startAnimating() default: break } } } // MARK: UIView override init(frame: CGRect) { super.init(frame: frame) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public convenience init(options: PullToRefreshOption, frame: CGRect, refreshCompletion :(() -> ())) { self.init(frame: frame) self.options = options self.refreshCompletion = refreshCompletion self.backgroundView = UIView(frame: CGRectMake(0, 0, frame.size.width, frame.size.height)) self.backgroundView.backgroundColor = self.options.backgroundColor self.backgroundView.autoresizingMask = UIViewAutoresizing.FlexibleWidth self.addSubview(backgroundView) self.arrow = UIImageView(frame: CGRectMake(0, 0, 30, 30)) self.arrow.autoresizingMask = [.FlexibleLeftMargin, .FlexibleRightMargin] self.arrow.image = UIImage(named: PullToRefreshConst.imageName, inBundle: NSBundle(forClass: self.dynamicType), compatibleWithTraitCollection: nil) self.addSubview(arrow) self.indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray) self.indicator.bounds = self.arrow.bounds self.indicator.autoresizingMask = self.arrow.autoresizingMask self.indicator.hidesWhenStopped = true self.indicator.color = options.indicatorColor self.addSubview(indicator) self.autoresizingMask = .FlexibleWidth } public override func layoutSubviews() { super.layoutSubviews() self.arrow.center = CGPointMake(self.frame.size.width / 2, self.frame.size.height / 2) self.indicator.center = self.arrow.center } public override func willMoveToSuperview(superView: UIView!) { superview?.removeObserver(self, forKeyPath: contentOffsetKeyPath, context: &kvoContext) if let scrollView = superView as? UIScrollView { scrollView.addObserver(self, forKeyPath: contentOffsetKeyPath, options: .Initial, context: &kvoContext) } } deinit { if let scrollView = superview as? UIScrollView { scrollView.removeObserver(self, forKeyPath: contentOffsetKeyPath, context: &kvoContext) } } // MARK: KVO public override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<()>) { if (context == &kvoContext && keyPath == contentOffsetKeyPath) { if let scrollView = object as? UIScrollView { // Debug //println(scrollView.contentOffset.y) let offsetWithoutInsets = self.previousOffset + self.scrollViewInsets.top // Update the content inset for fixed section headers if self.options.fixedSectionHeader && self.state == .Refreshing { if (scrollView.contentOffset.y > 0) { scrollView.contentInset = UIEdgeInsetsZero; } return } // Alpha set if PullToRefreshConst.alpha { var alpha = fabs(offsetWithoutInsets) / (self.frame.size.height + 30) if alpha > 0.8 { alpha = 0.8 } self.arrow.alpha = alpha } // Backgroundview frame set if PullToRefreshConst.fixedTop { if PullToRefreshConst.height < fabs(offsetWithoutInsets) { self.backgroundView.frame.size.height = fabs(offsetWithoutInsets) } else { self.backgroundView.frame.size.height = PullToRefreshConst.height } } else { self.backgroundView.frame.size.height = PullToRefreshConst.height + fabs(offsetWithoutInsets) self.backgroundView.frame.origin.y = -fabs(offsetWithoutInsets) } // Pulling State Check if (offsetWithoutInsets < -self.frame.size.height) { // pulling or refreshing if (scrollView.dragging == false && self.state != .Refreshing) { self.state = .Refreshing } else if (self.state != .Refreshing) { self.arrowRotation() self.state = .Pulling } } else if (self.state != .Refreshing && offsetWithoutInsets < 0) { // normal self.arrowRotationBack() } self.previousOffset = scrollView.contentOffset.y } } else { super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context) } } // MARK: private private func startAnimating() { self.indicator.startAnimating() self.arrow.hidden = true if let scrollView = superview as? UIScrollView { scrollViewBounces = scrollView.bounces scrollViewInsets = scrollView.contentInset var insets = scrollView.contentInset insets.top += self.frame.size.height scrollView.contentOffset.y = self.previousOffset scrollView.bounces = false UIView.animateWithDuration(PullToRefreshConst.animationDuration, delay: 0, options:[], animations: { scrollView.contentInset = insets scrollView.contentOffset = CGPointMake(scrollView.contentOffset.x, -insets.top) }, completion: {finished in if self.options.autoStopTime != 0 { let time = dispatch_time(DISPATCH_TIME_NOW, Int64(self.options.autoStopTime * Double(NSEC_PER_SEC))) dispatch_after(time, dispatch_get_main_queue()) { self.state = .Normal } } self.refreshCompletion() }) } } private func stopAnimating() { self.indicator.stopAnimating() self.arrow.transform = CGAffineTransformIdentity self.arrow.hidden = false if let scrollView = superview as? UIScrollView { scrollView.bounces = self.scrollViewBounces UIView.animateWithDuration(PullToRefreshConst.animationDuration, animations: { () -> Void in scrollView.contentInset = self.scrollViewInsets }) { (Bool) -> Void in } } } private func arrowRotation() { UIView.animateWithDuration(0.2, delay: 0, options:[], animations: { // -0.0000001 for the rotation direction control self.arrow.transform = CGAffineTransformMakeRotation(CGFloat(M_PI-0.0000001)) }, completion:nil) } private func arrowRotationBack() { UIView.animateWithDuration(0.2, delay: 0, options:[], animations: { self.arrow.transform = CGAffineTransformIdentity }, completion:nil) } }
9f1cc24832adce10612e253b50b94821
38.009132
162
0.572867
false
false
false
false
itsaboutcode/WordPress-iOS
refs/heads/develop
WordPress/Classes/ViewRelated/System/Notices/NoticeStyle.swift
gpl-2.0
1
public enum NoticeAnimationStyle { case moveIn case fade } /// A gesture which can be used to dismiss the notice. /// See `NoticeView.configurGestureRecognizer()` for more details. public enum NoticeDismissGesture { case tap } public protocol NoticeStyle { // Text var attributedMessage: NSAttributedString? { get } // Fonts var titleLabelFont: UIFont { get } var messageLabelFont: UIFont { get } var actionButtonFont: UIFont? { get } var cancelButtonFont: UIFont? { get } // Colors var titleColor: UIColor { get } var messageColor: UIColor { get } var backgroundColor: UIColor { get } /// The space between the border of the Notice and the contents (title, label, and buttons). var layoutMargins: UIEdgeInsets { get } // Misc var isDismissable: Bool { get } var animationStyle: NoticeAnimationStyle { get } var dismissGesture: NoticeDismissGesture? { get } } extension NoticeStyle { public var backgroundColor: UIColor { .invertedSystem5 } public var titleColor: UIColor { .invertedLabel } public var messageColor: UIColor { .invertedSecondaryLabel } } public struct NormalNoticeStyle: NoticeStyle { public let attributedMessage: NSAttributedString? = nil // Return new UIFont instance everytime in order to be responsive to accessibility font size changes public var titleLabelFont: UIFont { return UIFont.boldSystemFont(ofSize: 14.0) } public var messageLabelFont: UIFont { return UIFont.systemFont(ofSize: 14.0) } public var actionButtonFont: UIFont? { return UIFont.systemFont(ofSize: 14.0, weight: .medium) } public let cancelButtonFont: UIFont? = nil public let layoutMargins = UIEdgeInsets(top: 10.0, left: 16.0, bottom: 10.0, right: 16.0) public let isDismissable = true public let animationStyle = NoticeAnimationStyle.moveIn public let dismissGesture: NoticeDismissGesture? = nil } public struct QuickStartNoticeStyle: NoticeStyle { public let attributedMessage: NSAttributedString? // Return new UIFont instance everytime in order to be responsive to accessibility font size changes public var titleLabelFont: UIFont { return WPStyleGuide.fontForTextStyle(.subheadline, fontWeight: .semibold) } public var messageLabelFont: UIFont { return WPStyleGuide.fontForTextStyle(.subheadline) } public var actionButtonFont: UIFont? { return WPStyleGuide.fontForTextStyle(.headline) } public var cancelButtonFont: UIFont? { return WPStyleGuide.fontForTextStyle(.body) } public let layoutMargins = UIEdgeInsets(top: 13.0, left: 16.0, bottom: 13.0, right: 16.0) public let isDismissable = false public let animationStyle = NoticeAnimationStyle.moveIn public let dismissGesture: NoticeDismissGesture? = nil } public struct ToolTipNoticeStyle: NoticeStyle { public let attributedMessage: NSAttributedString? init(attributedMessage: NSAttributedString? = nil) { self.attributedMessage = attributedMessage } // Return new UIFont instance everytime in order to be responsive to accessibility font size changes public var titleLabelFont: UIFont { return WPStyleGuide.fontForTextStyle(.body) } public var messageLabelFont: UIFont { return WPStyleGuide.fontForTextStyle(.subheadline) } public var actionButtonFont: UIFont? { return WPStyleGuide.fontForTextStyle(.headline) } public var cancelButtonFont: UIFont? { return WPStyleGuide.fontForTextStyle(.body) } public let layoutMargins = UIEdgeInsets(top: 13.0, left: 16.0, bottom: 13.0, right: 16.0) public let isDismissable = false public let animationStyle = NoticeAnimationStyle.fade public let dismissGesture: NoticeDismissGesture? = NoticeDismissGesture.tap }
2e7fa42b4989cec14ff6f50f7d90d564
34.514019
115
0.736579
false
false
false
false
Henawey/TheArabianCenter
refs/heads/master
TheArabianCenter/ShareConfigurator.swift
mit
1
// // ShareConfigurator.swift // TheArabianCenter // // Created by Ahmed Henawey on 2/23/17. // Copyright (c) 2017 Ahmed Henawey. All rights reserved. // // This file was generated by the Clean Swift Xcode Templates so you can apply // clean architecture to your iOS and Mac projects, see http://clean-swift.com // import UIKit // MARK: - Connect View, Interactor, and Presenter extension ShareViewController: SharePresenterOutput { override func prepare(for segue: UIStoryboardSegue, sender: Any?) { router.passDataToNextScene(segue: segue) } } extension ShareInteractor: ShareViewControllerOutput { } extension SharePresenter: ShareInteractorOutput { } class ShareConfigurator { // MARK: - Object lifecycle static let sharedInstance = ShareConfigurator() private init() {} // MARK: - Configuration func configure(viewController: ShareViewController) { let router = ShareRouter() router.viewController = viewController let presenter = SharePresenter() presenter.output = viewController let interactor = ShareInteractor() interactor.output = presenter viewController.output = interactor viewController.router = router } }
35f7babd68b84d3a3e41c2c879aaf72e
20.732143
79
0.723911
false
true
false
false
jiaxw32/ZRSwiftKit
refs/heads/master
ZRSwiftKit/Demo/MonkeyPintch/TickleGestureRecognizer.swift
mit
1
// // TickleGestureRecognizer.swift // ZRSwiftKit // // Created by jiaxw-mac on 2017/9/22. // Copyright © 2017年 jiaxw32. All rights reserved. // import UIKit class TickleGestureRecognizer: UIGestureRecognizer { let requiredTickles = 2 let distanceForTickleGesture: CGFloat = 10.0 enum Direction: Int { case DirectionUnknow = 0 case DirectionLeft case DirectionRight } var tickleCount: Int = 0 var curTickleStart = CGPoint.zero var lastDirection = Direction.DirectionUnknow override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) { if let touch = touches.first { curTickleStart = touch.location(in: self.view) } } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent) { if let touch = touches.first { let ticklePoint = touch.location(in: self.view) let moveAmt = ticklePoint.x - curTickleStart.x print("moveAmt:\(moveAmt)") var curDirection = Direction.DirectionUnknow if moveAmt >= 0 { curDirection = .DirectionRight } else { curDirection = .DirectionLeft } if abs(moveAmt) < distanceForTickleGesture { return } if lastDirection == .DirectionUnknow || (lastDirection == .DirectionLeft && curDirection == .DirectionRight) || (lastDirection == .DirectionRight && curDirection == .DirectionLeft) { self.tickleCount += 1 self.curTickleStart = ticklePoint self.lastDirection = curDirection print("current direction:\(curDirection),tickle count:\(tickleCount)") if state == .possible && tickleCount > requiredTickles { state = .ended } } } } override func reset() { self.tickleCount = 0 self.curTickleStart = CGPoint.zero self.lastDirection = .DirectionUnknow if state == .possible { state = .failed } } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent) { reset() } override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent) { reset() } }
aabcea30487be5527d299ff72e79c8b2
29.769231
194
0.570417
false
false
false
false
salesawagner/wascar
refs/heads/master
wascarTests/ViewModels/PlaceDetailViewModelTests.swift
mit
1
// // PlaceDetailViewModelTests.swift // wascar // // Created by Wagner Sales on 25/11/16. // Copyright © 2016 Wagner Sales. All rights reserved. // import XCTest @testable import wascar class PlaceDetailViewModelTests: WCARTest { func testInitialization() { let placeCellViewModel = PlaceDetailViewModel(place: self.place) XCTAssertNotNil(placeCellViewModel, "The place detail view model should not be nil.") } func testUpdatePlace() { let expectation = self.expectation(description: #function) let placeDetailViewModel = PlaceDetailViewModel(place: self.place) placeDetailViewModel.loadPlaceById { (success) in expectation.fulfill() XCTAssert(success, "The success should be true.") } self.waitForExpectations(timeout: 60, handler: nil) } func testUpdatePlaceFail() { let expectation = self.expectation(description: #function) let placeDetailViewModel = PlaceDetailViewModel(place: self.place) placeDetailViewModel.placeId = "" placeDetailViewModel.loadPlaceById { (success) in expectation.fulfill() XCTAssert(success == false, "The success should be false.") } self.waitForExpectations(timeout: 60, handler: nil) } }
a0d56011628d22001a41f69121e8607d
26.627907
87
0.746633
false
true
false
false
JadenGeller/Edgy
refs/heads/master
Edgy/Edgy/UniqueNode.swift
mit
1
// // UniqueNode.swift // Edgy // // Created by Jaden Geller on 12/29/15. // Copyright © 2015 Jaden Geller. All rights reserved. // public class UniqueNode<Element>: Hashable { public let element: Element public init(_ element: Element) { self.element = element } public var hashValue: Int { return ObjectIdentifier(self).hashValue } } public func ==<Element>(lhs: UniqueNode<Element>, rhs: UniqueNode<Element>) -> Bool { return lhs === rhs }
1d19a036081526ee25337470df201a84
20.521739
85
0.643725
false
false
false
false
yoichitgy/SwinjectPropertyLoader
refs/heads/master
Tests/Resolver+PropertiesSpec.swift
mit
1
// // Resolver+PropertiesSpec.swift // SwinjectPropertyLoader // // Created by Yoichi Tagaya on 5/8/16. // Copyright © 2016 Swinject Contributors. All rights reserved. // import Foundation import Quick import Nimble import Swinject import SwinjectPropertyLoader class Resolver_PropertiesSpec: QuickSpec { override func spec() { var container: Container! beforeEach { container = Container() } describe("JSON properties") { it("can load properties from a single loader") { let loader = JsonPropertyLoader(bundle: Bundle(for: type(of: self).self), name: "first") try! container.applyPropertyLoader(loader) container.register(Properties.self) { r in let properties = Properties() properties.stringValue = r.property("test.string")! properties.optionalStringValue = r.property("test.string") properties.implicitStringValue = r.property("test.string") properties.intValue = r.property("test.int")! properties.optionalIntValue = r.property("test.int") properties.implicitIntValue = r.property("test.int") properties.doubleValue = r.property("test.double")! properties.optionalDoubleValue = r.property("test.double") properties.implicitDoubleValue = r.property("test.double") properties.arrayValue = r.property("test.array")! properties.optionalArrayValue = r.property("test.array") properties.implicitArrayValue = r.property("test.array") properties.dictValue = r.property("test.dict")! properties.optionalDictValue = r.property("test.dict") properties.implicitDictValue = r.property("test.dict") properties.boolValue = r.property("test.bool")! properties.optionalBoolValue = r.property("test.bool") properties.implicitBoolValue = r.property("test.bool") return properties } let properties = container.resolve(Properties.self)! expect(properties.stringValue) == "first" expect(properties.optionalStringValue) == "first" expect(properties.implicitStringValue) == "first" expect(properties.intValue) == 100 expect(properties.optionalIntValue) == 100 expect(properties.implicitIntValue) == 100 expect(properties.doubleValue) == 30.50 expect(properties.optionalDoubleValue) == 30.50 expect(properties.implicitDoubleValue) == 30.50 expect(properties.arrayValue.count) == 2 expect(properties.arrayValue[0]) == "item1" expect(properties.arrayValue[1]) == "item2" expect(properties.optionalArrayValue!.count) == 2 expect(properties.optionalArrayValue![0]) == "item1" expect(properties.optionalArrayValue![1]) == "item2" expect(properties.implicitArrayValue.count) == 2 expect(properties.implicitArrayValue![0]) == "item1" expect(properties.implicitArrayValue![1]) == "item2" expect(properties.dictValue.count) == 2 expect(properties.dictValue["key1"]) == "item1" expect(properties.dictValue["key2"]) == "item2" expect(properties.optionalDictValue!.count) == 2 expect(properties.optionalDictValue!["key1"]) == "item1" expect(properties.optionalDictValue!["key2"]) == "item2" expect(properties.implicitDictValue.count) == 2 expect(properties.implicitDictValue!["key1"]) == "item1" expect(properties.implicitDictValue!["key2"]) == "item2" expect(properties.boolValue) == true expect(properties.optionalBoolValue) == true expect(properties.implicitBoolValue) == true } it("can load properties from multiple loader") { let loader = JsonPropertyLoader(bundle: Bundle(for: type(of: self).self), name: "first") let loader2 = JsonPropertyLoader(bundle: Bundle(for: type(of: self).self), name: "second") try! container.applyPropertyLoader(loader) try! container.applyPropertyLoader(loader2) container.register(Properties.self) { r in let properties = Properties() properties.stringValue = r.property("test.string")! // from loader2 properties.intValue = r.property("test.int")! // from loader return properties } let properties = container.resolve(Properties.self)! expect(properties.stringValue) == "second" expect(properties.intValue) == 100 } } describe("Plist properties") { it("can load properties from a single loader") { let loader = PlistPropertyLoader(bundle: Bundle(for: type(of: self).self), name: "first") try! container.applyPropertyLoader(loader) container.register(Properties.self) { r in let properties = Properties() properties.stringValue = r.property("test.string")! properties.optionalStringValue = r.property("test.string") properties.implicitStringValue = r.property("test.string") properties.intValue = r.property("test.int")! properties.optionalIntValue = r.property("test.int") properties.implicitIntValue = r.property("test.int") properties.doubleValue = r.property("test.double")! properties.optionalDoubleValue = r.property("test.double") properties.implicitDoubleValue = r.property("test.double") properties.arrayValue = r.property("test.array")! properties.optionalArrayValue = r.property("test.array") properties.implicitArrayValue = r.property("test.array") properties.dictValue = r.property("test.dict")! properties.optionalDictValue = r.property("test.dict") properties.implicitDictValue = r.property("test.dict") properties.boolValue = r.property("test.bool")! properties.optionalBoolValue = r.property("test.bool") properties.implicitBoolValue = r.property("test.bool") return properties } let properties = container.resolve(Properties.self)! expect(properties.stringValue) == "first" expect(properties.optionalStringValue) == "first" expect(properties.implicitStringValue) == "first" expect(properties.intValue) == 100 expect(properties.optionalIntValue) == 100 expect(properties.implicitIntValue) == 100 expect(properties.doubleValue) == 30.50 expect(properties.optionalDoubleValue) == 30.50 expect(properties.implicitDoubleValue) == 30.50 expect(properties.arrayValue.count) == 2 expect(properties.arrayValue[0]) == "item1" expect(properties.arrayValue[1]) == "item2" expect(properties.optionalArrayValue!.count) == 2 expect(properties.optionalArrayValue![0]) == "item1" expect(properties.optionalArrayValue![1]) == "item2" expect(properties.implicitArrayValue.count) == 2 expect(properties.implicitArrayValue![0]) == "item1" expect(properties.implicitArrayValue![1]) == "item2" expect(properties.dictValue.count) == 2 expect(properties.dictValue["key1"]) == "item1" expect(properties.dictValue["key2"]) == "item2" expect(properties.optionalDictValue!.count) == 2 expect(properties.optionalDictValue!["key1"]) == "item1" expect(properties.optionalDictValue!["key2"]) == "item2" expect(properties.implicitDictValue.count) == 2 expect(properties.implicitDictValue!["key1"]) == "item1" expect(properties.implicitDictValue!["key2"]) == "item2" expect(properties.boolValue) == true expect(properties.optionalBoolValue) == true expect(properties.implicitBoolValue) == true } it("can load properties from multiple loader") { let loader = PlistPropertyLoader(bundle: Bundle(for: type(of: self).self), name: "first") let loader2 = PlistPropertyLoader(bundle: Bundle(for: type(of: self).self), name: "second") try! container.applyPropertyLoader(loader) try! container.applyPropertyLoader(loader2) container.register(Properties.self) { r in let properties = Properties() properties.stringValue = r.property("test.string")! // from loader2 properties.intValue = r.property("test.int")! // from loader return properties } let properties = container.resolve(Properties.self)! expect(properties.stringValue) == "second" expect(properties.intValue) == 100 } } } }
45f22aa315bbb669829c73bee7e44cde
48.924171
107
0.53484
false
true
false
false
BalestraPatrick/Tweetometer
refs/heads/develop
Carthage/Checkouts/IGListKit/Examples/Examples-iOS/IGListKitExamples/ViewControllers/EmptyViewController.swift
apache-2.0
4
/** Copyright (c) 2016-present, Facebook, Inc. All rights reserved. The examples provided by Facebook are for non-commercial testing and evaluation purposes only. Facebook reserves all rights not expressly granted. 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 FACEBOOK 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 IGListKit import UIKit final class EmptyViewController: UIViewController, ListAdapterDataSource, RemoveSectionControllerDelegate { lazy var adapter: ListAdapter = { return ListAdapter(updater: ListAdapterUpdater(), viewController: self) }() let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout()) let emptyLabel: UILabel = { let label = UILabel() label.numberOfLines = 0 label.textAlignment = .center label.text = "No more data!" label.backgroundColor = .clear return label }() var tally = 4 var data = [1, 2, 3, 4] override func viewDidLoad() { super.viewDidLoad() navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(EmptyViewController.onAdd)) collectionView.backgroundColor = UIColor(white: 0.9, alpha: 1) view.addSubview(collectionView) adapter.collectionView = collectionView adapter.dataSource = self } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() collectionView.frame = view.bounds } @objc func onAdd() { data.append(tally + 1) tally += 1 adapter.performUpdates(animated: true, completion: nil) } // MARK: ListAdapterDataSource func objects(for listAdapter: ListAdapter) -> [ListDiffable] { return data as [ListDiffable] } func listAdapter(_ listAdapter: ListAdapter, sectionControllerFor object: Any) -> ListSectionController { let sectionController = RemoveSectionController() sectionController.delegate = self return sectionController } func emptyView(for listAdapter: ListAdapter) -> UIView? { return emptyLabel } // MARK: RemoveSectionControllerDelegate func removeSectionControllerWantsRemoved(_ sectionController: RemoveSectionController) { let section = adapter.section(for: sectionController) guard let object = adapter.object(atSection: section) as? Int, let index = data.index(of: object) else { return } data.remove(at: index) adapter.performUpdates(animated: true, completion: nil) } }
1f60a2d1e6ac71d6e2c222fedc3ad356
33.761364
121
0.678326
false
false
false
false
fishcafe/SunnyHiddenBar
refs/heads/master
SunnyHiddenBar/Classes/UIViewController+SunnyHiddenBar.swift
mit
1
// // UIViewController+SunnyHiddenBar.swift // SunnyHiddenBar // // Created by amaker on 16/4/19. // Copyright © 2016年 CocoaPods. All rights reserved. // import Foundation import UIKit /** SunnyHiddenBar Extends UIViewController */ //定义关联的Key let key = "keyScrollView" let navBarBackgroundImageKey = "navBarBackgroundImage" let isLeftAlphaKey = "isLeftAlpha" let isRightAlphaKey = "isRightAlpha" let isTitleAlphaKey = "isTitleAlpha" var alpha:CGFloat = 0; public extension UIViewController { var keyScrollView:UIScrollView?{ set{ objc_setAssociatedObject(self, key, keyScrollView, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } get{ return objc_getAssociatedObject(self, key) as? UIScrollView } } var navBarBackgroundImage:UIImage?{ set{ objc_setAssociatedObject(self, navBarBackgroundImageKey, navBarBackgroundImage, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } get{ return objc_getAssociatedObject(self, navBarBackgroundImageKey) as? UIImage } } var isLeftAlpha:Bool?{ set{ return objc_setAssociatedObject(self, isLeftAlphaKey, (isLeftAlpha), .OBJC_ASSOCIATION_ASSIGN) } get{ return objc_getAssociatedObject(self, isLeftAlphaKey) as? Bool } } var isRightAlpha:Bool?{ set{ return objc_setAssociatedObject(self, isRightAlphaKey, (isRightAlpha), .OBJC_ASSOCIATION_ASSIGN) } get{ return objc_getAssociatedObject(self, isRightAlphaKey) as? Bool } } var isTitleAlpha:Bool?{ set{ return objc_setAssociatedObject(self, isTitleAlphaKey, (isTitleAlpha), .OBJC_ASSOCIATION_ASSIGN) } get{ return objc_getAssociatedObject(self, isTitleAlphaKey) as? Bool } } func scrollControlByOffsetY(offsetY:CGFloat){ if self.getScrollerView() != Optional.None{ let scrollerView = self.getScrollerView() alpha = scrollerView.contentOffset.y/offsetY }else { return } alpha = (alpha <= 0) ? 0 : alpha alpha = (alpha >= 1) ? 1 : alpha //TODO: titleView alpha no fix self.navigationItem.leftBarButtonItem?.customView?.alpha = (self.isLeftAlpha != nil) ? alpha : 1 self.navigationItem.titleView?.alpha = (self.isTitleAlpha != nil) ? alpha : 1 self.navigationItem.rightBarButtonItem?.customView?.alpha = (self.isRightAlpha != nil) ? alpha : 1 self.navigationController?.navigationBar.subviews.first?.alpha = alpha } func setInViewWillAppear() { struct Static { static var onceToken: dispatch_once_t = 0 } dispatch_once(&Static.onceToken) { self.navBarBackgroundImage = self.navigationController?.navigationBar.backgroundImageForBarMetrics(.Default) } self.navigationController?.navigationBar.shadowImage = UIImage() self.navigationController?.navigationBar.subviews.first?.alpha = 0 if self.keyScrollView != nil { self.getScrollerView().contentOffset = CGPointMake(0, self.keyScrollView!.contentOffset.y - 1) self.getScrollerView().contentOffset = CGPointMake(0, self.keyScrollView!.contentOffset.y + 1) } } func setInViewWillDisappear() { self.navigationController?.navigationBar.subviews.first?.alpha = 1 self.navigationController?.navigationBar.setBackgroundImage(nil, forBarMetrics: .Default) self.navigationController?.navigationBar.shadowImage = nil } func getScrollerView() -> UIScrollView{ if self.isKindOfClass(UITableViewController) || self.isKindOfClass(UICollectionViewController) { return self.view as! UIScrollView } else { for myView in self.view.subviews { if myView.isEqual(self.keyScrollView) && myView.isKindOfClass(UIScrollView) || myView.isEqual(self.keyScrollView) && view.isKindOfClass(UIScrollView){ return myView as! UIScrollView } } } return Optional.None! } }
deda142fb73e25ddc8b872e9cb866850
29.588652
166
0.632506
false
false
false
false
creatubbles/ctb-api-swift
refs/heads/develop
CreatubblesAPIClientUnitTests/Spec/Gallery/FavoriteGalleryRequestSpec.swift
mit
1
// // FavoriteGalleryRequestSpec.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 Quick import Nimble @testable import CreatubblesAPIClient class FavoriteGalleryRequestSpec: QuickSpec { override func spec() { let galleryId = "galleryId" describe("Favorite gallery request") { it("Should have proper endpoint for gallery") { let request = FavoriteGalleryRequest(galleryId: galleryId) expect(request.endpoint) == "galleries/\(galleryId)/favorite" } it("Should have proper method") { let request = FavoriteGalleryRequest(galleryId: galleryId) expect(request.method) == RequestMethod.post } } describe("Remove favorite gallery request") { it("Should have proper endpoint for gallery") { let request = RemoveFavoriteGalleryRequest(galleryId: galleryId) expect(request.endpoint) == "galleries/\(galleryId)/favorite" } it("Should have proper method") { let request = RemoveFavoriteGalleryRequest(galleryId: galleryId) expect(request.method) == RequestMethod.delete } } } }
1890c13006ed1b1a13ec640fbc3bbd0e
39.098361
81
0.6574
false
false
false
false
kickstarter/ios-oss
refs/heads/main
Library/String+Attributed.swift
apache-2.0
1
import Foundation import UIKit public func + (left: NSAttributedString, right: NSAttributedString) -> NSAttributedString { let combined = NSMutableAttributedString() combined.append(left) combined.append(right) return NSMutableAttributedString(attributedString: combined) } public extension String { func attributed( with font: UIFont, foregroundColor: UIColor, attributes: [NSAttributedString.Key: Any], bolding strings: [String] ) -> NSAttributedString { let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: self) let fullRange = (self as NSString).localizedStandardRange(of: self) let regularFontAttributes = [ NSAttributedString.Key.font: font, NSAttributedString.Key.foregroundColor: foregroundColor ] .withAllValuesFrom(attributes) attributedString.addAttributes(regularFontAttributes, range: fullRange) let boldFontAttribute = [NSAttributedString.Key.font: font.bolded] for string in strings { attributedString.addAttributes( boldFontAttribute, range: (self as NSString).localizedStandardRange(of: string) ) } return attributedString } }
770e8fe10be1d0f3d27729c006f652aa
28.825
93
0.74518
false
false
false
false
wuzzapcom/Fluffy-Book
refs/heads/master
FluffyBook/ContentsTableViewController.swift
mit
1
// // ContentsTableViewController.swift // FluffyBook // // Created by Владимир Лапатин on 20.05.17. // Copyright © 2017 FluffyBook. All rights reserved. // import UIKit class ContentsTableViewController: UITableViewController { public var currentBookModel : BookModel? //set in segue fileprivate var contentsTableViewModel : ContentsTableViewModel? public var delegate:TransferDataProtocol? fileprivate var settedValue : Int? override func viewDidLoad() { super.viewDidLoad() guard currentBookModel != nil else { print("No book model") return } let pair = currentBookModel!.getTitles() contentsTableViewModel = ContentsTableViewModel(withContent: pair.0) } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return contentsTableViewModel!.getNumberOfElements() } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: Constants.CONTENT_CELL_IDENTIFIER, for: indexPath) cell.textLabel?.text = contentsTableViewModel!.getChapterTitle(withIndexPath: indexPath) return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { settedValue = indexPath.row navigationController?.popViewController(animated: true) } override func viewDidDisappear(_ animated: Bool) { delegate?.setSelectedRow(number: settedValue) } }
35a916b7505d2217a851faf9c172b948
25.895522
116
0.663152
false
false
false
false
RxSwiftCommunity/RxDataSources
refs/heads/main
Examples/Example/Example2_RandomizedSectionsAnimation.swift
mit
1
// // ViewController.swift // Example // // Created by Krunoslav Zaher on 1/1/16. // Copyright © 2016 kzaher. All rights reserved. // import UIKit import RxDataSources import RxSwift import RxCocoa import CoreLocation class NumberCell : UICollectionViewCell { @IBOutlet private var value: UILabel? func configure(with value: String) { self.value?.text = value } } class NumberSectionView : UICollectionReusableView { @IBOutlet private weak var value: UILabel? func configure(value: String) { self.value?.text = value } } class PartialUpdatesViewController: UIViewController { @IBOutlet private weak var animatedTableView: UITableView! @IBOutlet private weak var tableView: UITableView! @IBOutlet private weak var animatedCollectionView: UICollectionView! @IBOutlet private weak var refreshButton: UIButton! let disposeBag = DisposeBag() override func viewDidLoad() { super.viewDidLoad() let initialRandomizedSections = Randomizer(rng: PseudoRandomGenerator(4, 3), sections: initialValue()) let ticks = Observable<Int>.interval(.seconds(1), scheduler: MainScheduler.instance).map { _ in () } let randomSections = Observable.of(ticks, refreshButton.rx.tap.asObservable()) .merge() .scan(initialRandomizedSections) { a, _ in return a.randomize() } .map { a in return a.sections } .share(replay: 1) let (configureCell, titleForSection) = PartialUpdatesViewController.tableViewDataSourceUI() let tvAnimatedDataSource = RxTableViewSectionedAnimatedDataSource<NumberSection>( configureCell: configureCell, titleForHeaderInSection: titleForSection ) let reloadDataSource = RxTableViewSectionedReloadDataSource<NumberSection>( configureCell: configureCell, titleForHeaderInSection: titleForSection ) randomSections .bind(to: animatedTableView.rx.items(dataSource: tvAnimatedDataSource)) .disposed(by: disposeBag) randomSections .bind(to: tableView.rx.items(dataSource: reloadDataSource)) .disposed(by: disposeBag) let (configureCollectionViewCell, configureSupplementaryView) = PartialUpdatesViewController.collectionViewDataSourceUI() let cvAnimatedDataSource = RxCollectionViewSectionedAnimatedDataSource( configureCell: configureCollectionViewCell, configureSupplementaryView: configureSupplementaryView ) randomSections .bind(to: animatedCollectionView.rx.items(dataSource: cvAnimatedDataSource)) .disposed(by: disposeBag) // touches Observable.of( tableView.rx.modelSelected(IntItem.self), animatedTableView.rx.modelSelected(IntItem.self), animatedCollectionView.rx.modelSelected(IntItem.self) ) .merge() .subscribe(onNext: { item in print("Let me guess, it's .... It's \(item), isn't it? Yeah, I've got it.") }) .disposed(by: disposeBag) } } // MARK: Skinning extension PartialUpdatesViewController { static func tableViewDataSourceUI() -> ( TableViewSectionedDataSource<NumberSection>.ConfigureCell, TableViewSectionedDataSource<NumberSection>.TitleForHeaderInSection ) { return ( { _, tv, ip, i in let cell = tv.dequeueReusableCell(withIdentifier: "Cell") ?? UITableViewCell(style:.default, reuseIdentifier: "Cell") cell.textLabel!.text = "\(i)" return cell }, { ds, section -> String? in return ds[section].header } ) } static func collectionViewDataSourceUI() -> ( CollectionViewSectionedDataSource<NumberSection>.ConfigureCell, CollectionViewSectionedDataSource<NumberSection>.ConfigureSupplementaryView ) { return ( { _, cv, ip, i in let cell = cv.dequeueReusableCell(withReuseIdentifier: "Cell", for: ip) as! NumberCell cell.configure(with: "\(i)") return cell }, { ds ,cv, kind, ip in let section = cv.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "Section", for: ip) as! NumberSectionView section.configure(value: "\(ds[ip.section].header)") return section } ) } // MARK: Initial value func initialValue() -> [NumberSection] { #if true let nSections = 10 let nItems = 100 /* let nSections = 10 let nItems = 2 */ return (0 ..< nSections).map { (i: Int) in NumberSection(header: "Section \(i + 1)", numbers: `$`(Array(i * nItems ..< (i + 1) * nItems)), updated: Date()) } #else return _initialValue #endif } } let _initialValue: [NumberSection] = [ NumberSection(header: "section 1", numbers: `$`([1, 2, 3]), updated: Date()), NumberSection(header: "section 2", numbers: `$`([4, 5, 6]), updated: Date()), NumberSection(header: "section 3", numbers: `$`([7, 8, 9]), updated: Date()), NumberSection(header: "section 4", numbers: `$`([10, 11, 12]), updated: Date()), NumberSection(header: "section 5", numbers: `$`([13, 14, 15]), updated: Date()), NumberSection(header: "section 6", numbers: `$`([16, 17, 18]), updated: Date()), NumberSection(header: "section 7", numbers: `$`([19, 20, 21]), updated: Date()), NumberSection(header: "section 8", numbers: `$`([22, 23, 24]), updated: Date()), NumberSection(header: "section 9", numbers: `$`([25, 26, 27]), updated: Date()), NumberSection(header: "section 10", numbers: `$`([28, 29, 30]), updated: Date()) ] func `$`(_ numbers: [Int]) -> [IntItem] { return numbers.map { IntItem(number: $0, date: Date()) } }
fc08473f63e4ef1325c1487f09732837
33.836158
142
0.609309
false
true
false
false
NickAger/elm-slider
refs/heads/master
Modules/HTTP/Sources/HTTP/Serializer/RequestSerializer.swift
mit
5
public class RequestSerializer { let stream: Stream let bufferSize: Int public init(stream: Stream, bufferSize: Int = 2048) { self.stream = stream self.bufferSize = bufferSize } public func serialize(_ request: Request, deadline: Double) throws { let newLine: [UInt8] = [13, 10] try stream.write("\(request.method) \(request.url.absoluteString) HTTP/\(request.version.major).\(request.version.minor)", deadline: deadline) try stream.write(newLine, deadline: deadline) for (name, value) in request.headers.headers { try stream.write("\(name): \(value)", deadline: deadline) try stream.write(newLine, deadline: deadline) } try stream.write(newLine, deadline: deadline) switch request.body { case .buffer(let buffer): try stream.write(buffer, deadline: deadline) case .reader(let reader): while !reader.closed { let buffer = try reader.read(upTo: bufferSize, deadline: deadline) guard !buffer.isEmpty else { break } try stream.write(String(buffer.count, radix: 16), deadline: deadline) try stream.write(newLine, deadline: deadline) try stream.write(buffer, deadline: deadline) try stream.write(newLine, deadline: deadline) } try stream.write("0", deadline: deadline) try stream.write(newLine, deadline: deadline) try stream.write(newLine, deadline: deadline) case .writer(let writer): let body = BodyStream(stream) try writer(body) try stream.write("0", deadline: deadline) try stream.write(newLine, deadline: deadline) try stream.write(newLine, deadline: deadline) } try stream.flush(deadline: deadline) } }
b32873b46e260a81a2cf858aa64bb691
35.603774
150
0.592784
false
false
false
false
Piwigo/Piwigo-Mobile
refs/heads/master
piwigo/Album/Cells/ImageCollectionViewCell.swift
mit
1
// // ImageCollectionViewCell.swift // piwigo // // Created by Spencer Baker on 1/27/15. // Copyright (c) 2015 bakercrew. All rights reserved. // // Converted to Swift 5.4 by Eddy Lelièvre-Berna on 31/01/2022 // import UIKit class ImageCollectionViewCell: UICollectionViewCell { var imageData: PiwigoImageData? @IBOutlet weak var cellImage: UIImageView! @IBOutlet weak var darkenView: UIView! @IBOutlet weak var darkImgWidth: NSLayoutConstraint! @IBOutlet weak var darkImgHeight: NSLayoutConstraint! // Image title @IBOutlet weak var bottomLayer: UIView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var noDataLabel: UILabel! // Icon showing that it is a movie @IBOutlet weak var playImg: UIImageView! @IBOutlet weak var playBckg: UIImageView! @IBOutlet weak var playLeft: NSLayoutConstraint! @IBOutlet weak var playTop: NSLayoutConstraint! // Icon showing that it is a favorite @IBOutlet weak var favImg: UIImageView! @IBOutlet weak var favBckg: UIImageView! @IBOutlet weak var favLeft: NSLayoutConstraint! @IBOutlet weak var favBottom: NSLayoutConstraint! // Selected images are darkened @IBOutlet weak var selectedImg: UIImageView! @IBOutlet weak var selImgRight: NSLayoutConstraint! @IBOutlet weak var selImgTop: NSLayoutConstraint! // On iPad, thumbnails are presented with native aspect ratio private var deltaX: CGFloat = 1.0 // Must be initialised with margin value private var deltaY: CGFloat = 1.0 // Must be initialised with margin value // Constants used to place and resize objects private let margin: CGFloat = 1.0 private let offset: CGFloat = 1.0 private let bannerHeight: CGFloat = 16.0 private let favScale: CGFloat = 0.12 private let favRatio: CGFloat = 1.0 private let selectScale: CGFloat = 0.2 private let playScale: CGFloat = 0.17 private let playRatio: CGFloat = 0.9 // was 58/75 = 0.7733; private var _isSelection = false @objc var isSelection: Bool { get { _isSelection } set(isSelection) { _isSelection = isSelection selectedImg?.isHidden = !isSelection darkenView?.isHidden = !isSelection } } private var _isFavorite = false @objc var isFavorite: Bool { get { _isFavorite } set(isFavorite) { _isFavorite = isFavorite // Update the vertical constraint if bottomLayer?.isHidden ?? false { // Place icon at the bottom favBottom?.constant = deltaY } else { // Place icon at the bottom but above the title let height = CGFloat(fmax(bannerHeight + margin, deltaY)) favBottom?.constant = height } // Display/hide the favorite icon favBckg?.isHidden = !isFavorite favImg?.isHidden = !isFavorite } } @objc func applyColorPalette() { bottomLayer?.backgroundColor = UIColor.piwigoColorBackground() nameLabel?.textColor = UIColor.piwigoColorLeftLabel() favBckg?.tintColor = UIColor(white: 0, alpha: 0.3) favImg?.tintColor = UIColor.white } func config(with imageData: PiwigoImageData?, inCategoryId categoryId: Int) { // Do we have any info on that image ? noDataLabel?.text = NSLocalizedString("loadingHUD_label", comment: "Loading…") guard let imageData = imageData else { return } if imageData.imageId == 0 { return } // Store image data self.imageData = imageData noDataLabel.isHidden = true isAccessibilityElement = true // Play button playImg?.isHidden = !(imageData.isVideo) playBckg?.isHidden = !(imageData.isVideo) // Title if AlbumVars.shared.displayImageTitles || (categoryId == kPiwigoVisitsCategoryId) || (categoryId == kPiwigoBestCategoryId) || (categoryId == kPiwigoRecentCategoryId) { bottomLayer?.isHidden = false nameLabel?.isHidden = false if categoryId == kPiwigoVisitsCategoryId { nameLabel?.text = String(format: "%ld %@", Int(imageData.visits), NSLocalizedString("categoryDiscoverVisits_legend", comment: "hits")) } else if categoryId == kPiwigoBestCategoryId { // self.nameLabel.text = [NSString stringWithFormat:@"(%.2f) %@", imageData.ratingScore, imageData.name]; if let imageTitle = imageData.imageTitle, imageTitle.isEmpty == false { nameLabel?.text = imageTitle } else { nameLabel?.text = imageData.fileName } } else if categoryId == kPiwigoRecentCategoryId, let dateCreated = imageData.dateCreated { nameLabel?.text = DateFormatter.localizedString(from: dateCreated, dateStyle: .medium, timeStyle: .none) } else { if let imageTitle = imageData.imageTitle, imageTitle.isEmpty == false { nameLabel?.text = imageTitle } else { nameLabel?.text = imageData.fileName } } } else { bottomLayer?.isHidden = true nameLabel?.isHidden = true } // Thumbnails are not squared on iPad if UIDevice.current.userInterfaceIdiom == .pad { cellImage?.contentMode = .scaleAspectFit } // Download the image of the requested resolution (or get it from the cache) switch kPiwigoImageSize(rawValue: AlbumVars.shared.defaultThumbnailSize) { case kPiwigoImageSizeSquare: if AlbumVars.shared.hasSquareSizeImages, let squarePath = imageData.squarePath, squarePath.isEmpty == false { setImageFromPath(squarePath) } else if AlbumVars.shared.hasThumbSizeImages, let thumbPath = imageData.thumbPath, thumbPath.isEmpty == false { setImageFromPath(thumbPath) } else { noDataLabel?.isHidden = false return } case kPiwigoImageSizeXXSmall: if AlbumVars.shared.hasXXSmallSizeImages, let xxSmallPath = imageData.xxSmallPath, xxSmallPath.isEmpty == false { setImageFromPath(xxSmallPath) } else if AlbumVars.shared.hasThumbSizeImages, let thumbPath = imageData.thumbPath, thumbPath.isEmpty == false { setImageFromPath(thumbPath) } else { noDataLabel?.isHidden = false return } case kPiwigoImageSizeXSmall: if AlbumVars.shared.hasXSmallSizeImages, let xSmallPath = imageData.xSmallPath, xSmallPath.isEmpty == false { setImageFromPath(xSmallPath) } else if AlbumVars.shared.hasThumbSizeImages, let thumbPath = imageData.thumbPath, thumbPath.isEmpty == false { setImageFromPath(thumbPath) } else { noDataLabel?.isHidden = false return } case kPiwigoImageSizeSmall: if AlbumVars.shared.hasSmallSizeImages, let smallPath = imageData.smallPath, smallPath.isEmpty == false { setImageFromPath(smallPath) } else if AlbumVars.shared.hasThumbSizeImages, let thumbPath = imageData.thumbPath, thumbPath.isEmpty == false { setImageFromPath(thumbPath) } else { noDataLabel?.isHidden = false return } case kPiwigoImageSizeMedium: if AlbumVars.shared.hasMediumSizeImages, let mediumPath = imageData.mediumPath, mediumPath.isEmpty == false { setImageFromPath(mediumPath) } else if AlbumVars.shared.hasThumbSizeImages, let thumbPath = imageData.thumbPath, thumbPath.isEmpty == false { setImageFromPath(thumbPath) } else { noDataLabel?.isHidden = false return } case kPiwigoImageSizeLarge: if AlbumVars.shared.hasLargeSizeImages, let largePath = imageData.largePath, largePath.isEmpty == false { setImageFromPath(largePath) } else if AlbumVars.shared.hasThumbSizeImages, let thumbPath = imageData.thumbPath, thumbPath.isEmpty == false { setImageFromPath(thumbPath) } else { noDataLabel?.isHidden = false return } case kPiwigoImageSizeXLarge: if AlbumVars.shared.hasXLargeSizeImages, let xLargePath = imageData.xLargePath, xLargePath.isEmpty == false { setImageFromPath(xLargePath) } else if AlbumVars.shared.hasThumbSizeImages, let thumbPath = imageData.thumbPath, thumbPath.isEmpty == false { setImageFromPath(thumbPath) } else { noDataLabel?.isHidden = false return } case kPiwigoImageSizeXXLarge: if AlbumVars.shared.hasXXLargeSizeImages, let xxLargePath = imageData.xxLargePath, xxLargePath.isEmpty == false { setImageFromPath(xxLargePath) } else if AlbumVars.shared.hasThumbSizeImages, let thumbPath = imageData.thumbPath, thumbPath.isEmpty == false { setImageFromPath(thumbPath) } else { noDataLabel?.isHidden = false return } case kPiwigoImageSizeThumb, kPiwigoImageSizeFullRes: fallthrough default: if AlbumVars.shared.hasThumbSizeImages, let thumbPath = imageData.thumbPath, thumbPath.isEmpty == false { setImageFromPath(thumbPath) } else { noDataLabel?.isHidden = false return } } applyColorPalette() } private func setImageFromPath(_ imagePath: String) { // Do we have a correct URL? let placeHolderImage = UIImage(named: "placeholderImage") if imagePath.isEmpty { // No image thumbnail cellImage?.image = placeHolderImage return } // Retrieve the image file let scale = CGFloat(fmax(1.0, Float(traitCollection.displayScale))) guard let anURL = URL(string: imagePath) else { return } var request = URLRequest(url: anURL) request.addValue("image/*", forHTTPHeaderField: "Accept") cellImage?.setImageWith(request, placeholderImage: placeHolderImage, success: { [self] _, _, image in // Downsample image is necessary var displayedImage = image let maxDimensionInPixels = CGFloat(max(self.bounds.size.width, self.bounds.size.height)) * scale if CGFloat(max(image.size.width, image.size.height)) > maxDimensionInPixels { displayedImage = ImageUtilities.downsample(image: image, to: self.bounds.size, scale: scale) } self.cellImage?.image = displayedImage // Favorite image position depends on device self.deltaX = margin self.deltaY = margin let imageScale = CGFloat(min(self.bounds.size.width / displayedImage.size.width, self.bounds.size.height / displayedImage.size.height)) if UIDevice.current.userInterfaceIdiom == .pad { // Case of an iPad: respect aspect ratio // Image width smaller than collection view cell? let imageWidth = displayedImage.size.width * imageScale if imageWidth < self.bounds.size.width { // The image does not fill the cell horizontally self.darkImgWidth?.constant = imageWidth self.deltaX += (self.bounds.size.width - imageWidth) / 2.0 } // Image height smaller than collection view cell? let imageHeight = displayedImage.size.height * imageScale if imageHeight < self.bounds.size.height { // The image does not fill the cell vertically self.darkImgHeight?.constant = imageHeight self.deltaY += (self.bounds.size.height - imageHeight) / 2.0 } } // Update horizontal constraints self.selImgRight?.constant = self.deltaX self.favLeft?.constant = self.deltaX self.playLeft?.constant = self.deltaX // Update vertical constraints self.selImgTop?.constant = self.deltaY + 2 * margin self.playTop?.constant = self.deltaY if self.bottomLayer?.isHidden ?? false { // The title is not displayed self.favBottom?.constant = self.deltaY } else { // The title is displayed let deltaY = CGFloat(fmax(bannerHeight + margin, self.deltaY)) self.favBottom?.constant = deltaY } }, failure: { request, response, error in debugPrint("••> cell image: \(error.localizedDescription)") }) } override func prepareForReuse() { super.prepareForReuse() imageData = nil cellImage?.image = nil deltaX = margin deltaY = margin isSelection = false isFavorite = false playImg?.isHidden = true noDataLabel?.isHidden = true } func highlight(onCompletion completion: @escaping () -> Void) { // Select cell of image of interest and apply effect backgroundColor = UIColor.piwigoColorBackground() contentMode = .scaleAspectFit UIView.animate(withDuration: 0.4, delay: 0.3, options: .allowUserInteraction, animations: { [self] in cellImage?.alpha = 0.2 }) { [self] finished in UIView.animate(withDuration: 0.4, delay: 0.7, options: .allowUserInteraction, animations: { [self] in cellImage?.alpha = 1.0 }) { finished in completion() } } } }
26d2d41850850ec01adac07034ae4b50
42.023739
150
0.594386
false
false
false
false
Adorkable/StoryboardKit
refs/heads/master
StoryboardKit/SegueInstanceInfo.swift
mit
1
// // SegueInstanceInfo.swift // StoryboardKit // // Created by Ian on 5/3/15. // Copyright (c) 2015 Adorkable. All rights reserved. // import Foundation // TODO: should we keep it weak? should we be using the weak attribute? public typealias SegueConnection = StoryboardKit_WeakWrapper<ViewControllerInstanceInfo> /// Represents a Segue Instance used in your application and its storyboards public class SegueInstanceInfo: NSObject, Idable { /// Class public let classInfo : SegueClassInfo /// Storyboard Id public let id : String /// Source public let source : SegueConnection /// Destination public let destination : SegueConnection /// Kind of Segue public let kind : String? /// Identifier public let identifier : String? /** Default init - parameter classInfo: Class - parameter id: Storyboard Id - parameter source: Source - parameter destination: Destination - parameter kind: Kind of Segue - parameter identifier: Identifier - returns: A new instance. */ public init(classInfo : SegueClassInfo, id : String, source : SegueConnection, destination : SegueConnection, kind : String?, identifier : String?) { self.classInfo = classInfo self.id = id self.source = source self.destination = destination self.kind = kind self.identifier = identifier super.init() self.classInfo.add(instanceInfo: self) } /** Convenience init: Destination as a View Controller Instance - parameter classInfo: Class - parameter id: Storyboard Id - parameter source: Source as SegueConnection - parameter destination: Destination as View Controller Instance - parameter kind: Kind of Segue - parameter identifier: Identifier - returns: A new instance. */ public convenience init(classInfo : SegueClassInfo, id : String, source : SegueConnection, destination : ViewControllerInstanceInfo, kind : String?, identifier : String?) { self.init(classInfo: classInfo, id: id, source: source, destination: StoryboardKit_WeakWrapper(destination), kind: kind, identifier: identifier) } } extension SegueInstanceInfo /*: CustomDebugStringConvertible*/ { /// Debug Description override public var debugDescription : String { get { var result = super.debugDescription result += "\n\(self.classInfo)" result += "\nId: \(self.id)" result += "\nSource: \(self.source.value)" result += "\nDestination: \(self.destination.value)" result += "\nKind: \(self.kind)" result += "\nIdentifier: \(self.identifier)" return result } } }
d1de87e9a26fcfa1bc4c6b3e82223485
30
176
0.625472
false
false
false
false
ThumbWorks/i-meditated
refs/heads/master
Carthage/Checkouts/Result/Result/Result.swift
apache-2.0
2
// Copyright (c) 2015 Rob Rix. All rights reserved. /// An enum representing either a failure with an explanatory error, or a success with a result value. public enum Result<T, Error: Swift.Error>: ResultProtocol, CustomStringConvertible, CustomDebugStringConvertible { case success(T) case failure(Error) // MARK: Constructors /// Constructs a success wrapping a `value`. public init(value: T) { self = .success(value) } /// Constructs a failure wrapping an `error`. public init(error: Error) { self = .failure(error) } /// Constructs a result from an Optional, failing with `Error` if `nil`. public init(_ value: T?, failWith: @autoclosure () -> Error) { self = value.map(Result.success) ?? .failure(failWith()) } /// Constructs a result from a function that uses `throw`, failing with `Error` if throws. public init(_ f: @autoclosure () throws -> T) { self.init(attempt: f) } /// Constructs a result from a function that uses `throw`, failing with `Error` if throws. public init(attempt f: () throws -> T) { do { self = .success(try f()) } catch { self = .failure(error as! Error) } } // MARK: Deconstruction #if !os(Linux) /// Returns the value from `Success` Results or `throw`s the error. public func dematerialize() throws -> T { switch self { case let .success(value): return value case let .failure(error): throw error } } #endif /// Case analysis for Result. /// /// Returns the value produced by applying `ifFailure` to `Failure` Results, or `ifSuccess` to `Success` Results. public func analysis<Result>(ifSuccess: (T) -> Result, ifFailure: (Error) -> Result) -> Result { switch self { case let .success(value): return ifSuccess(value) case let .failure(value): return ifFailure(value) } } // MARK: Errors /// The domain for errors constructed by Result. public static var errorDomain: String { return "com.antitypical.Result" } /// The userInfo key for source functions in errors constructed by Result. public static var functionKey: String { return "\(errorDomain).function" } /// The userInfo key for source file paths in errors constructed by Result. public static var fileKey: String { return "\(errorDomain).file" } /// The userInfo key for source file line numbers in errors constructed by Result. public static var lineKey: String { return "\(errorDomain).line" } /// Constructs an error. public static func error(_ message: String? = nil, function: String = #function, file: String = #file, line: Int = #line) -> NSError { var userInfo: [String: Any] = [ functionKey: function, fileKey: file, lineKey: line, ] if let message = message { userInfo[NSLocalizedDescriptionKey] = message } return NSError(domain: errorDomain, code: 0, userInfo: userInfo) } // MARK: CustomStringConvertible public var description: String { return analysis( ifSuccess: { ".success(\($0))" }, ifFailure: { ".failure(\($0))" }) } // MARK: CustomDebugStringConvertible public var debugDescription: String { return description } } // MARK: - Derive result from failable closure public func materialize<T>(_ f: () throws -> T) -> Result<T, NSError> { return materialize(try f()) } public func materialize<T>(_ f: @autoclosure () throws -> T) -> Result<T, NSError> { do { return .success(try f()) } catch let error as NSError { return .failure(error) } } // MARK: - Cocoa API conveniences #if !os(Linux) /// Constructs a Result with the result of calling `try` with an error pointer. /// /// This is convenient for wrapping Cocoa API which returns an object or `nil` + an error, by reference. e.g.: /// /// Result.try { NSData(contentsOfURL: URL, options: .DataReadingMapped, error: $0) } public func `try`<T>(_ function: String = #function, file: String = #file, line: Int = #line, `try`: (NSErrorPointer) -> T?) -> Result<T, NSError> { var error: NSError? return `try`(&error).map(Result.success) ?? .failure(error ?? Result<T, NSError>.error(function: function, file: file, line: line)) } /// Constructs a Result with the result of calling `try` with an error pointer. /// /// This is convenient for wrapping Cocoa API which returns a `Bool` + an error, by reference. e.g.: /// /// Result.try { NSFileManager.defaultManager().removeItemAtURL(URL, error: $0) } public func `try`(_ function: String = #function, file: String = #file, line: Int = #line, `try`: (NSErrorPointer) -> Bool) -> Result<(), NSError> { var error: NSError? return `try`(&error) ? .success(()) : .failure(error ?? Result<(), NSError>.error(function: function, file: file, line: line)) } #endif // MARK: - ErrorProtocolConvertible conformance extension NSError: ErrorProtocolConvertible { public static func error(from error: Swift.Error) -> Self { func cast<T: NSError>(_ error: Swift.Error) -> T { return error as! T } return cast(error) } } // MARK: - /// An “error” that is impossible to construct. /// /// This can be used to describe `Result`s where failures will never /// be generated. For example, `Result<Int, NoError>` describes a result that /// contains an `Int`eger and is guaranteed never to be a `Failure`. public enum NoError: Swift.Error { } // MARK: - migration support extension Result { @available(*, unavailable, renamed: "success") public static func Success(_: T) -> Result<T, Error> { fatalError() } @available(*, unavailable, renamed: "failure") public static func Failure(_: Error) -> Result<T, Error> { fatalError() } } extension NSError { @available(*, unavailable, renamed: "error(from:)") public static func errorFromErrorType(_ error: Swift.Error) -> Self { fatalError() } } import Foundation
6a78598663eab6ab8f59544faedd4bd4
28.427835
148
0.68138
false
false
false
false
zmian/xcore.swift
refs/heads/main
Sources/Xcore/Cocoa/Components/UIImage/ImageTransform/ResizeImageTransform.swift
mit
1
// // Xcore // Copyright © 2017 Xcore // MIT license, see LICENSE file for details // import UIKit public struct ResizeImageTransform: ImageTransform { private let size: CGSize private let scalingMode: ScalingMode public var id: String { "\(transformName)-size:(\(size.width)x\(size.height))-scalingMode:(\(scalingMode))" } public init(to size: CGSize, scalingMode: ScalingMode = .aspectFill) { self.size = size self.scalingMode = scalingMode } public func transform(_ image: UIImage, source: ImageRepresentable) -> UIImage { let rect = scalingMode.rect(newSize: size, and: image.size) return UIGraphicsImageRenderer(bounds: rect).image { _ in image.draw(in: rect) } } } extension ResizeImageTransform { /// Represents a scaling mode public enum ScalingMode { case fill case aspectFill case aspectFit /// Calculates the aspect ratio between two sizes. /// /// - Parameters: /// - size: The first size used to calculate the ratio. /// - otherSize: The second size used to calculate the ratio. /// - Returns: the aspect ratio between the two sizes. private func aspectRatio(between size: CGSize, and otherSize: CGSize) -> CGFloat { let aspectWidth = size.width / otherSize.width let aspectHeight = size.height / otherSize.height switch self { case .fill: return 1 case .aspectFill: return max(aspectWidth, aspectHeight) case .aspectFit: return min(aspectWidth, aspectHeight) } } fileprivate func rect(newSize: CGSize, and otherSize: CGSize) -> CGRect { guard self != .fill else { return CGRect(origin: .zero, size: newSize) } let aspectRatio = self.aspectRatio(between: newSize, and: otherSize) // Build the rectangle representing the area to be drawn let scaledImageRect = CGRect( x: (newSize.width - otherSize.width * aspectRatio) / 2.0, y: (newSize.height - otherSize.height * aspectRatio) / 2.0, width: otherSize.width * aspectRatio, height: otherSize.height * aspectRatio ) return scaledImageRect } } }
d5a7cda47df21630807b5352b348e5e5
31.666667
91
0.584898
false
false
false
false
LeaderQiu/SwiftWeibo
refs/heads/master
103 - swiftWeibo/103 - swiftWeibo/Classes/Tools/String+Hash.swift
mit
6
// // StringHash.swift // 黑马微博 // // Created by 刘凡 on 15/2/21. // Copyright (c) 2015年 joyios. All rights reserved. // /// 注意:要使用本分类,需要在 bridge.h 中添加以下头文件导入 /// #import <CommonCrypto/CommonCrypto.h> /// 如果使用了单元测试,项目 和 测试项目的 bridge.h 中都需要导入 import Foundation extension String { /// 返回字符串的 MD5 散列结果 var md5: String! { let str = self.cStringUsingEncoding(NSUTF8StringEncoding) let strLen = CC_LONG(self.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)) let digestLen = Int(CC_MD5_DIGEST_LENGTH) let result = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLen) CC_MD5(str!, strLen, result) var hash = NSMutableString() for i in 0..<digestLen { hash.appendFormat("%02x", result[i]) } result.dealloc(digestLen) return hash.copy() as! String } }
7d79089d3fc5f9e51890c6a521535c79
25.848485
83
0.621896
false
false
false
false
danthorpe/TaylorSource
refs/heads/development
Tests/Models.swift
mit
2
// // Models.swift // TaylorSource // // Created by Daniel Thorpe on 08/03/2016. // // import Foundation import ValueCoding import YapDatabaseExtensions import YapDatabase @testable import TaylorSource struct EventSection: SectionType { typealias ItemType = Event let title: String let items: [Event] } extension EventSection: CustomStringConvertible { var description: String { return "\(title) (\(items.count) items)" } } extension EventSection: Equatable { } func == (lhs: EventSection, rhs: EventSection) -> Bool { return lhs.title == rhs.title && lhs.items == rhs.items } struct Event { enum Color { case Red, Blue, Green } let uuid: String let color: Color let date: NSDate init(uuid: String = NSUUID().UUIDString, color: Color, date: NSDate = NSDate()) { self.uuid = uuid self.color = color self.date = date } static func create(color color: Color = .Red) -> Event { return Event(color: color) } } extension Event.Color: CustomStringConvertible { var description: String { switch self { case .Red: return "Red" case .Blue: return "Blue" case .Green: return "Green" } } } extension Event.Color: Equatable { } func == (lhs: Event.Color, rhs: Event.Color) -> Bool { switch (lhs,rhs) { case (.Red, .Red), (.Blue, .Blue), (.Green, .Green): return true default: return false } } extension Event: Equatable { } func == (lhs: Event, rhs: Event) -> Bool { return (lhs.color == rhs.color) && (lhs.uuid == rhs.uuid) && (lhs.date == rhs.date) } extension Event.Color: ValueCoding { typealias Coder = EventColorCoder enum Kind: Int { case Red = 1, Blue, Green } var kind: Kind { switch self { case .Red: return Kind.Red case .Blue: return Kind.Blue case .Green: return Kind.Green } } } class EventColorCoder: NSObject, NSCoding, CodingType { let value: Event.Color required init(_ v: Event.Color) { value = v } required init?(coder aDecoder: NSCoder) { if let kind = Event.Color.Kind(rawValue: aDecoder.decodeIntegerForKey("kind")) { switch kind { case .Red: value = Event.Color.Red case .Blue: value = Event.Color.Blue case .Green: value = Event.Color.Green } } else { fatalError("Event.Color.Kind not correctly encoded.") } } func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeInteger(value.kind.rawValue, forKey: "kind") } } extension Event: Identifiable { var identifier: String { return uuid } } extension Event: Persistable { static var collection: String { return "Events" } } extension Event: ValueCoding { typealias Coder = EventCoder } class EventCoder: NSObject, NSCoding, CodingType { let value: Event required init(_ v: Event) { value = v } required init?(coder aDecoder: NSCoder) { let color = Event.Color.decode(aDecoder.decodeObjectForKey("color")) let uuid = aDecoder.decodeObjectForKey("uuid") as? String let date = aDecoder.decodeObjectForKey("date") as? NSDate value = Event(uuid: uuid!, color: color!, date: date!) } func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(value.color.encoded, forKey: "color") aCoder.encodeObject(value.uuid, forKey: "uuid") aCoder.encodeObject(value.date, forKey: "date") } } func createSomeEvents(numberOfDays: Int = 10) -> [Event] { let today = NSDate() let interval: NSTimeInterval = 86_400 return (0..<numberOfDays).map { index in let date = today.dateByAddingTimeInterval(-1.0 * Double(index) * interval) return Event(color: .Red, date: date) } } func events(byColor: Bool = false) -> YapDB.Fetch { let grouping: YapDB.View.Grouping = .ByObject({ (_, collection, key, object) -> String! in if collection == Event.collection { if !byColor { return collection } if let event = Event.decode(object) { return event.color.description } } return .None }) let sorting: YapDB.View.Sorting = .ByObject({ (_, group, collection1, key1, object1, collection2, key2, object2) -> NSComparisonResult in if let event1 = Event.decode(object1), let event2 = Event.decode(object2) { return event1.date.compare(event2.date) } return .OrderedSame }) let view = YapDB.View(name: Event.collection, grouping: grouping, sorting: sorting, collections: [Event.collection]) return .View(view) } func events(byColor: Bool = false, mappingBlock: YapDB.FetchConfiguration.MappingsConfigurationBlock? = .None) -> YapDB.FetchConfiguration { return YapDB.FetchConfiguration(fetch: events(byColor), block: mappingBlock) } func events(byColor: Bool = false, mappingBlock: YapDB.FetchConfiguration.MappingsConfigurationBlock? = .None) -> Configuration<Event> { return Configuration(fetch: events(byColor), itemMapper: Event.decode) } func eventsWithColor(color: Event.Color, byColor: Bool = false) -> YapDB.Fetch { let filtering: YapDB.Filter.Filtering = .ByObject({ (_, group, collection, key, object) -> Bool in if let event = Event.decode(object) { return event.color == color } return false }) let filter = YapDB.Filter(name: "\(color) Events", parent: events(byColor), filtering: filtering, collections: [Event.collection]) return .Filter(filter) } func eventsWithColor(color: Event.Color, byColor: Bool = false, mappingBlock: YapDB.FetchConfiguration.MappingsConfigurationBlock? = .None) -> YapDB.FetchConfiguration { return YapDB.FetchConfiguration(fetch: eventsWithColor(color, byColor: byColor), block: mappingBlock) } func eventsWithColor(color: Event.Color, byColor: Bool = false, mappingBlock: YapDB.FetchConfiguration.MappingsConfigurationBlock? = .None) -> Configuration<Event> { return Configuration(fetch: eventsWithColor(color, byColor: byColor), itemMapper: Event.decode) }
4696621db5e0dbc18f719c9d7b809010
25.662447
169
0.634911
false
true
false
false
MakeSchool/Swift-Playgrounds
refs/heads/master
P5-Dictionaries.playground/Contents.swift
mit
2
import UIKit /*: # Dictionaries A Dictionary is Collection data structure which stores multiple values, where each value has a unique key associated with it. (If you know Python, you may be familiar with Python dictionaries; in Java these are called HashMaps.) Unlike arrays, dictionaries do not keep the values in any order. Dictionaries are helpful in a situation where you want to quickly look up a value based on its unique key. Let's jump right in and define a dictionary variable. */ var cities: [String : String] = ["New York City" : "USA", "Paris" : "France", "London" : "UK"] /*: As you can see, the type of a dictionary depends on the type of its key and the type of its value. The general dictionary type is defined as [<key type> : <value type>]. In the example above, the key and the value are both Strings. The key represents the name of the city, and the value represents the country the city is in. Just like arrays, the type of the dictionary can be inferred, so "[String : String]" is not necessary. To count the number of key-value pairs, you can use the count property just like arrays. "isEmpty" works as well. */ println("The dictionary contains \(cities.count) items.") /*: You can add a new key-value pair like this: */ cities["San Francisco"] = "USA" /*: It's similar to putting a value in an array, except instead of putting the index number inside the brackets, you put the key. You can also the change the value that a key is associated with in the same manner: */ cities["San Francisco"] = "United States of America" /*: When trying to retrieve a value for a key, there is a possibility that key-value pair does not exist, so you have to make sure you check for this case. As a result, it is best to use optional binding to retrieve a value from the dictionary: */ if let country = cities["London"] { println("London is in \(country).") } else { println("The dictionary does not contain London as a key.") } /*: You can remove a key-value pair simply by setting the key's value to nil: */ cities["London"] = nil println(cities) //does not contain "London" anymore /*: To empty the dictionary: */ cities = [:] /*: To define a new empty dictionary: */ var dictionary = [String : Int]() /*: Notice how the type of the values is Int. The value type can be any type you want. The key can also be any type you want. However, the key has to be a type that provides a value for its hashValue property. This is out of the scope of this tutorial, and there are rarely any situations that you will need a custom type to be the key type for a dictionary. */
29098121b4a3052e83b45c47f2c7ad30
42.3
400
0.733641
false
false
false
false