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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
uber/RIBs | refs/heads/main | ios/RIBs/Classes/Workflow/Workflow.swift | apache-2.0 | 1 | //
// Copyright (c) 2017. Uber Technologies
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import RxSwift
/// Defines the base class for a sequence of steps that execute a flow through the application RIB tree.
///
/// At each step of a `Workflow` is a pair of value and actionable item. The value can be used to make logic decisions.
/// The actionable item is invoked to perform logic for the step. Typically the actionable item is the `Interactor` of a
/// RIB.
///
/// A workflow should always start at the root of the tree.
open class Workflow<ActionableItemType> {
/// Called when the last step observable is completed.
///
/// Subclasses should override this method if they want to execute logic at this point in the `Workflow` lifecycle.
/// The default implementation does nothing.
open func didComplete() {
// No-op
}
/// Called when the `Workflow` is forked.
///
/// Subclasses should override this method if they want to execute logic at this point in the `Workflow` lifecycle.
/// The default implementation does nothing.
open func didFork() {
// No-op
}
/// Called when the last step observable is has error.
///
/// Subclasses should override this method if they want to execute logic at this point in the `Workflow` lifecycle.
/// The default implementation does nothing.
open func didReceiveError(_ error: Error) {
// No-op
}
/// Initializer.
public init() {}
/// Execute the given closure as the root step.
///
/// - parameter onStep: The closure to execute for the root step.
/// - returns: The next step.
public final func onStep<NextActionableItemType, NextValueType>(_ onStep: @escaping (ActionableItemType) -> Observable<(NextActionableItemType, NextValueType)>) -> Step<ActionableItemType, NextActionableItemType, NextValueType> {
return Step(workflow: self, observable: subject.asObservable().take(1))
.onStep { (actionableItem: ActionableItemType, _) in
onStep(actionableItem)
}
}
/// Subscribe and start the `Workflow` sequence.
///
/// - parameter actionableItem: The initial actionable item for the first step.
/// - returns: The disposable of this workflow.
public final func subscribe(_ actionableItem: ActionableItemType) -> Disposable {
guard compositeDisposable.count > 0 else {
assertionFailure("Attempt to subscribe to \(self) before it is comitted.")
return Disposables.create()
}
subject.onNext((actionableItem, ()))
return compositeDisposable
}
// MARK: - Private
private let subject = PublishSubject<(ActionableItemType, ())>()
private var didInvokeComplete = false
/// The composite disposable that contains all subscriptions including the original workflow
/// as well as all the forked ones.
fileprivate let compositeDisposable = CompositeDisposable()
fileprivate func didCompleteIfNotYet() {
// Since a workflow may be forked to produce multiple subscribed Rx chains, we should
// ensure the didComplete method is only invoked once per Workflow instance. See `Step.commit`
// on why the side-effects must be added at the end of the Rx chains.
guard !didInvokeComplete else {
return
}
didInvokeComplete = true
didComplete()
}
}
/// Defines a single step in a `Workflow`.
///
/// A step may produce a next step with a new value and actionable item, eventually forming a sequence of `Workflow`
/// steps.
///
/// Steps are asynchronous by nature.
open class Step<WorkflowActionableItemType, ActionableItemType, ValueType> {
private let workflow: Workflow<WorkflowActionableItemType>
private var observable: Observable<(ActionableItemType, ValueType)>
fileprivate init(workflow: Workflow<WorkflowActionableItemType>, observable: Observable<(ActionableItemType, ValueType)>) {
self.workflow = workflow
self.observable = observable
}
/// Executes the given closure for this step.
///
/// - parameter onStep: The closure to execute for the `Step`.
/// - returns: The next step.
public final func onStep<NextActionableItemType, NextValueType>(_ onStep: @escaping (ActionableItemType, ValueType) -> Observable<(NextActionableItemType, NextValueType)>) -> Step<WorkflowActionableItemType, NextActionableItemType, NextValueType> {
let confinedNextStep = observable
.flatMapLatest { (actionableItem, value) -> Observable<(Bool, ActionableItemType, ValueType)> in
// We cannot use generic constraint here since Swift requires constraints be
// satisfied by concrete types, preventing using protocol as actionable type.
if let interactor = actionableItem as? Interactable {
return interactor
.isActiveStream
.map({ (isActive: Bool) -> (Bool, ActionableItemType, ValueType) in
(isActive, actionableItem, value)
})
} else {
return Observable.just((true, actionableItem, value))
}
}
.filter { (isActive: Bool, _, _) -> Bool in
isActive
}
.take(1)
.flatMapLatest { (_, actionableItem: ActionableItemType, value: ValueType) -> Observable<(NextActionableItemType, NextValueType)> in
onStep(actionableItem, value)
}
.take(1)
.share()
return Step<WorkflowActionableItemType, NextActionableItemType, NextValueType>(workflow: workflow, observable: confinedNextStep)
}
/// Executes the given closure when the `Step` produces an error.
///
/// - parameter onError: The closure to execute when an error occurs.
/// - returns: This step.
public final func onError(_ onError: @escaping ((Error) -> ())) -> Step<WorkflowActionableItemType, ActionableItemType, ValueType> {
observable = observable.do(onError: onError)
return self
}
/// Commit the steps of the `Workflow` sequence.
///
/// - returns: The committed `Workflow`.
@discardableResult
public final func commit() -> Workflow<WorkflowActionableItemType> {
// Side-effects must be chained at the last observable sequence, since errors and complete
// events can be emitted by any observables on any steps of the workflow.
let disposable = observable
.do(onError: workflow.didReceiveError, onCompleted: workflow.didCompleteIfNotYet)
.subscribe()
_ = workflow.compositeDisposable.insert(disposable)
return workflow
}
/// Convert the `Workflow` into an obseravble.
///
/// - returns: The observable representation of this `Workflow`.
public final func asObservable() -> Observable<(ActionableItemType, ValueType)> {
return observable
}
}
/// `Workflow` related obervable extensions.
public extension ObservableType {
/// Fork the step from this obervable.
///
/// - parameter workflow: The workflow this step belongs to.
/// - returns: The newly forked step in the workflow. `nil` if this observable does not conform to the required
/// generic type of (ActionableItemType, ValueType).
func fork<WorkflowActionableItemType, ActionableItemType, ValueType>(_ workflow: Workflow<WorkflowActionableItemType>) -> Step<WorkflowActionableItemType, ActionableItemType, ValueType>? {
if let stepObservable = self as? Observable<(ActionableItemType, ValueType)> {
workflow.didFork()
return Step(workflow: workflow, observable: stepObservable)
}
return nil
}
}
/// `Workflow` related `Disposable` extensions.
public extension Disposable {
/// Dispose the subscription when the given `Workflow` is disposed.
///
/// When using this composition, the subscription closure may freely retain the workflow itself, since the
/// subscription closure is disposed once the workflow is disposed, thus releasing the retain cycle before the
/// `Workflow` needs to be deallocated.
///
/// - note: This is the preferred method when trying to confine a subscription to the lifecycle of a `Workflow`.
///
/// - parameter workflow: The workflow to dispose the subscription with.
func disposeWith<ActionableItemType>(workflow: Workflow<ActionableItemType>) {
_ = workflow.compositeDisposable.insert(self)
}
/// Dispose the subscription when the given `Workflow` is disposed.
///
/// When using this composition, the subscription closure may freely retain the workflow itself, since the
/// subscription closure is disposed once the workflow is disposed, thus releasing the retain cycle before the
/// `Workflow` needs to be deallocated.
///
/// - note: This is the preferred method when trying to confine a subscription to the lifecycle of a `Workflow`.
///
/// - parameter workflow: The workflow to dispose the subscription with.
@available(*, deprecated, renamed: "disposeWith(workflow:)")
func disposeWith<ActionableItemType>(worflow: Workflow<ActionableItemType>) {
disposeWith(workflow: worflow)
}
}
| 8576c927f7e331d54bc6c6b0fcb45834 | 42.89823 | 252 | 0.675033 | false | false | false | false |
nerd0geek1/NSPageControl | refs/heads/master | Example/Example/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// Example
//
// Created by Kohei Tabata on 2016/03/25.
// Copyright © 2016年 Kohei Tabata. All rights reserved.
//
import Cocoa
import NSPageControl
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet weak var window: NSWindow!
private var pageControl: NSPageControl!
func applicationDidFinishLaunching(_ aNotification: Notification) {
setupPageControl()
}
func applicationWillTerminate(_ aNotification: Notification) {
}
// MARK: - private
private func setupPageControl() {
pageControl = NSPageControl()
pageControl.numberOfPages = 4
let width: CGFloat = 200
let x: CGFloat = (window.frame.width - width) / 2
pageControl.frame = CGRect(x: x, y: 20, width: 200, height: 20)
window.contentView?.addSubview(pageControl)
}
// MARK: - IBAction
@IBAction func tapPreviousButton(_ sender: NSButton) {
pageControl.currentPage -= 1
}
@IBAction func tapNextButton(_ sender: NSButton) {
pageControl.currentPage += 1
}
}
| 6063583bfb0e75c8d3066df548bde2bc | 24 | 72 | 0.654222 | false | false | false | false |
huangboju/AsyncDisplay_Study | refs/heads/master | AsyncDisplay/PhotoFeed/PhotoCommentsNode.swift | mit | 1 | //
// PhotoCommentsNode.swift
// AsyncDisplay
//
// Created by 伯驹 黄 on 2017/4/27.
// Copyright © 2017年 伯驹 黄. All rights reserved.
//
let INTER_COMMENT_SPACING: CGFloat = 5
let NUM_COMMENTS_TO_SHOW = 3
import AsyncDisplayKit
class PhotoCommentsNode: ASDisplayNode {
var commentFeed: CommentFeedModel?
lazy var commentNodes: [ASTextNode] = []
override init() {
super.init()
automaticallyManagesSubnodes = true
}
override func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec {
return ASStackLayoutSpec(direction: .vertical, spacing: INTER_COMMENT_SPACING, justifyContent: .start, alignItems: .stretch, children: commentNodes)
}
func updateWithCommentFeedModel(_ feed: CommentFeedModel) {
commentFeed = feed
commentNodes.removeAll(keepingCapacity: true)
if let commentFeed = commentFeed {
createCommentLabels()
let addViewAllCommentsLabel = feed.numberOfComments(forPhotoExceedsInteger: NUM_COMMENTS_TO_SHOW)
var commentLabelString: NSAttributedString
var labelsIndex = 0
if addViewAllCommentsLabel {
commentLabelString = commentFeed.viewAllCommentsAttributedString()
commentNodes[labelsIndex].attributedText = commentLabelString
labelsIndex += 1
}
let numCommentsInFeed = commentFeed.numberOfItemsInFeed()
for feedIndex in 0 ..< numCommentsInFeed {
commentLabelString = commentFeed.object(at: feedIndex).commentAttributedString()
commentNodes[labelsIndex].attributedText = commentLabelString
labelsIndex += 1
}
setNeedsLayout()
}
}
private func createCommentLabels() {
guard let commentFeed = commentFeed else { return }
let addViewAllCommentsLabel = commentFeed.numberOfComments(forPhotoExceedsInteger: NUM_COMMENTS_TO_SHOW)
let numCommentsInFeed = commentFeed.numberOfItemsInFeed()
let numLabelsToAdd = (addViewAllCommentsLabel) ? numCommentsInFeed + 1 : numCommentsInFeed
for _ in 0 ..< numLabelsToAdd {
let commentLabel = ASTextNode()
commentLabel.isLayerBacked = true
commentLabel.maximumNumberOfLines = 3
commentNodes.append(commentLabel)
}
}
}
| 5474a5ba1a592a8ac8024161440604dc | 32.616438 | 156 | 0.650367 | false | false | false | false |
aidenluo177/GitHubber | refs/heads/master | GitHubber/Pods/CoreStore/CoreStore/Internal/FetchedResultsControllerDelegate.swift | mit | 1 | //
// 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
@available(OSX, unavailable)
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
@available(OSX, unavailable)
internal final class FetchedResultsControllerDelegate: NSObject, NSFetchedResultsControllerDelegate {
// MARK: Internal
internal var enabled = true
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) {
guard self.enabled else {
return
}
self.deletedSections = []
self.insertedSections = []
self.handler?.controllerWillChangeContent(controller)
}
@objc dynamic func controllerDidChangeContent(controller: NSFetchedResultsController) {
guard self.enabled else {
return
}
self.handler?.controllerDidChangeContent(controller)
}
@objc dynamic func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {
guard self.enabled else {
return
}
guard let actualType = NSFetchedResultsChangeType(rawValue: type.rawValue) else {
// This fix is for a bug where iOS passes 0 for NSFetchedResultsChangeType, but this is not a valid enum case.
// Swift will then always execute the first case of the switch causing strange behaviour.
// https://forums.developer.apple.com/thread/12184#31850
return
}
// This whole dance is a workaround for 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 actualType {
case .Update:
guard let section = indexPath?.indexAtPosition(0) else {
return
}
if self.deletedSections.contains(section)
|| self.insertedSections.contains(section) {
return
}
case .Move:
guard let indexPath = indexPath, let newIndexPath = newIndexPath else {
return
}
guard indexPath == newIndexPath else {
break
}
if self.insertedSections.contains(indexPath.indexAtPosition(0)) {
// Observers that handle the .Move change are advised to delete then reinsert the object instead of just moving. This is especially true when indexPath and newIndexPath are equal. For example, calling tableView.moveRowAtIndexPath(_:toIndexPath) when both indexPaths are the same will crash the tableView.
self.handler?.controller(
controller,
didChangeObject: anObject,
atIndexPath: indexPath,
forChangeType: .Move,
newIndexPath: newIndexPath
)
return
}
if self.deletedSections.contains(indexPath.indexAtPosition(0)) {
self.handler?.controller(
controller,
didChangeObject: anObject,
atIndexPath: nil,
forChangeType: .Insert,
newIndexPath: indexPath
)
return
}
self.handler?.controller(
controller,
didChangeObject: anObject,
atIndexPath: indexPath,
forChangeType: .Update,
newIndexPath: nil
)
return
default:
break
}
self.handler?.controller(
controller,
didChangeObject: anObject,
atIndexPath: indexPath,
forChangeType: actualType,
newIndexPath: newIndexPath
)
}
@objc dynamic func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) {
guard self.enabled else {
return
}
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>()
}
| dfd1302922e3398434843496418d60e3 | 35.196347 | 320 | 0.625836 | false | false | false | false |
Fenrikur/ef-app_ios | refs/heads/master | Domain Model/EurofurenceModelTestDoubles/CapturingJSONSession.swift | mit | 2 | import EurofurenceModel
import Foundation
public class CapturingJSONSession: JSONSession {
public init() {
}
public private(set) var getRequestURL: String?
public private(set) var capturedAdditionalGETHeaders: [String: String]?
private var GETCompletionHandler: ((Data?, Error?) -> Void)?
public func get(_ request: JSONRequest, completionHandler: @escaping (Data?, Error?) -> Void) {
getRequestURL = request.url
capturedAdditionalGETHeaders = request.headers
GETCompletionHandler = completionHandler
}
public private(set) var postedURL: String?
public private(set) var capturedAdditionalPOSTHeaders: [String: String]?
public private(set) var POSTData: Data?
private var POSTCompletionHandler: ((Data?, Error?) -> Void)?
public func post(_ request: JSONRequest, completionHandler: @escaping (Data?, Error?) -> Void) {
postedURL = request.url
POSTData = request.body
self.POSTCompletionHandler = completionHandler
capturedAdditionalPOSTHeaders = request.headers
}
public func postedJSONValue<T>(forKey key: String) -> T? {
guard let POSTData = POSTData else { return nil }
guard let json = try? JSONSerialization.jsonObject(with: POSTData, options: .allowFragments) else { return nil }
guard let jsonDictionary = json as? [String: Any] else { return nil }
return jsonDictionary[key] as? T
}
public func invokeLastGETCompletionHandler(responseData: Data?) {
GETCompletionHandler?(responseData, nil)
}
public func invokeLastPOSTCompletionHandler(responseData: Data?, error: Error? = nil) {
POSTCompletionHandler?(responseData, error)
}
}
| ef241926b507ca371720bd3af041d9b2 | 36.5 | 120 | 0.698551 | false | false | false | false |
selfzhou/Swift3 | refs/heads/master | Playground/Swift3-II.playground/Pages/StringsAndCharacters.xcplaygroundpage/Contents.swift | mit | 1 | //: [Previous](@previous)
import Foundation
var emptyString = ""
var anotherEmptyString = String()
if emptyString == anotherEmptyString {
print("Equal")
}
for character in "Dog!🐶".characters {
print(character)
}
let catChatacters: [Character] = ["C", "a", "t"]
let catString = String(catChatacters)
var welcome = "welcome"
welcome.append("!")
/**
NSString length 利用 UTF-16 表示的十六位代码单元数字,而不是 Unicode 可扩展字符群集
当一个 NSString length 属性被一个 Swift 的 String 值访问时,实际上是调用了 utf16Count
*/
/**
startIndex 获取 String 的第一个 Character 的索引
endIndex 获取最后一个 Character 的`后一个位置`的索引
*/
let greeting = "Guten Tag!"
greeting[greeting.startIndex]
greeting[greeting.index(before: greeting.endIndex)]
greeting[greeting.index(after: greeting.startIndex)]
let index = greeting.index(greeting.startIndex, offsetBy: 7)
greeting[index]
/**
`indices`
characters 属性的 indices 属性会创建一个包含全部索引的范围(Range),用来在一个字符串中访问单个字符
*/
for index in greeting.characters.indices {
print("\(greeting[index])", terminator: "")
}
welcome.insert(contentsOf: " hello".characters, at: welcome.index(before: welcome.endIndex))
| 3570660172e52304a2fa76ecefdad72a | 18.789474 | 92 | 0.715426 | false | false | false | false |
neoneye/SwiftyFORM | refs/heads/master | Source/FormItems/TextFieldFormItem.swift | mit | 1 | // MIT license. Copyright (c) 2021 SwiftyFORM. All rights reserved.
import UIKit
public class TextFieldFormItem: FormItem, CustomizableLabel {
override func accept(visitor: FormItemVisitor) {
visitor.visit(object: self)
}
public var keyboardType: UIKeyboardType = .default
@discardableResult
public func keyboardType(_ keyboardType: UIKeyboardType) -> Self {
self.keyboardType = keyboardType
return self
}
public var autocorrectionType: UITextAutocorrectionType = .no
public var autocapitalizationType: UITextAutocapitalizationType = .none
public var spellCheckingType: UITextSpellCheckingType = .no
public var secureTextEntry = false
public var textAlignment: NSTextAlignment = .left
public var clearButtonMode: UITextField.ViewMode = .whileEditing
public var returnKeyType: UIReturnKeyType = .default
@discardableResult
public func returnKeyType(_ returnKeyType: UIReturnKeyType) -> Self {
self.returnKeyType = returnKeyType
return self
}
public typealias SyncBlock = (_ value: String) -> Void
public var syncCellWithValue: SyncBlock = { (string: String) in
SwiftyFormLog("sync is not overridden")
}
internal var innerValue: String = ""
public var value: String {
get {
return self.innerValue
}
set {
self.assignValueAndSync(newValue)
}
}
public typealias TextDidChangeBlock = (_ value: String) -> Void
public var textDidChangeBlock: TextDidChangeBlock = { (value: String) in
SwiftyFormLog("not overridden")
}
public func textDidChange(_ value: String) {
innerValue = value
textDidChangeBlock(value)
}
public typealias TextEditingEndBlock = (_ value: String) -> Void
public var textEditingEndBlock: TextEditingEndBlock = { (value: String) in
SwiftyFormLog("not overridden")
}
public func editingEnd(_ value: String) {
textEditingEndBlock(value)
}
public func assignValueAndSync(_ value: String) {
innerValue = value
syncCellWithValue(value)
}
public var reloadPersistentValidationState: () -> Void = {}
public var obtainTitleWidth: () -> CGFloat = {
return 0
}
public var assignTitleWidth: (CGFloat) -> Void = { (width: CGFloat) in
// do nothing
}
public var placeholder: String = ""
@discardableResult
public func placeholder(_ placeholder: String) -> Self {
self.placeholder = placeholder
return self
}
public var title: String = ""
public var titleFont: UIFont = .preferredFont(forTextStyle: .body)
public var titleTextColor: UIColor = Colors.text
public var detailFont: UIFont = .preferredFont(forTextStyle: .body)
public var detailTextColor: UIColor = Colors.secondaryText
public var errorFont: UIFont = .preferredFont(forTextStyle: .caption2)
public var errorTextColor: UIColor = UIColor.red
@discardableResult
public func password() -> Self {
self.secureTextEntry = true
return self
}
public let validatorBuilder = ValidatorBuilder()
@discardableResult
public func validate(_ specification: Specification, message: String) -> Self {
validatorBuilder.hardValidate(specification, message: message)
return self
}
@discardableResult
public func softValidate(_ specification: Specification, message: String) -> Self {
validatorBuilder.softValidate(specification, message: message)
return self
}
@discardableResult
public func submitValidate(_ specification: Specification, message: String) -> Self {
validatorBuilder.submitValidate(specification, message: message)
return self
}
@discardableResult
public func required(_ message: String) -> Self {
submitValidate(CountSpecification.min(1), message: message)
return self
}
public func liveValidateValueText() -> ValidateResult {
validatorBuilder.build().liveValidate(self.value)
}
public func liveValidateText(_ text: String) -> ValidateResult {
validatorBuilder.build().validate(text, checkHardRule: true, checkSoftRule: true, checkSubmitRule: false)
}
public func submitValidateValueText() -> ValidateResult {
validatorBuilder.build().submitValidate(self.value)
}
public func submitValidateText(_ text: String) -> ValidateResult {
validatorBuilder.build().validate(text, checkHardRule: true, checkSoftRule: true, checkSubmitRule: true)
}
public func validateText(_ text: String, checkHardRule: Bool, checkSoftRule: Bool, checkSubmitRule: Bool) -> ValidateResult {
validatorBuilder.build().validate(text, checkHardRule: checkHardRule, checkSoftRule: checkSoftRule, checkSubmitRule: checkSubmitRule)
}
}
| e04a79d057a8eed98f9f61b38d2a462b | 28.225806 | 135 | 0.745475 | false | false | false | false |
CoderSLZeng/SLWeiBo | refs/heads/master | SLWeiBo/SLWeiBo/Classes/Home/PhotoBrowser/PhotoBrowserAnimator.swift | mit | 1 | //
// PhotoBrowserAnimator.swift
// SLWeiBo
//
// Created by Anthony on 17/3/20.
// Copyright © 2017年 SLZeng. All rights reserved.
//
import UIKit
// 面向协议开发
protocol AnimatorPresentedDelegate : NSObjectProtocol {
func startRect(_ indexPath : IndexPath) -> CGRect
func endRect(_ indexPath : IndexPath) -> CGRect
func imageView(_ indexPath : IndexPath) -> UIImageView
}
protocol AnimatorDismissDelegate : NSObjectProtocol {
func indexPathForDimissView() -> IndexPath
func imageViewForDimissView() -> UIImageView
}
class PhotoBrowserAnimator: NSObject {
var isPresented : Bool = false
var indexPath : IndexPath?
var presentedDelegate : AnimatorPresentedDelegate?
var dismissDelegate : AnimatorDismissDelegate?
}
extension PhotoBrowserAnimator : UIViewControllerTransitioningDelegate {
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
isPresented = true
return self
}
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
isPresented = false
return self
}
}
extension PhotoBrowserAnimator : UIViewControllerAnimatedTransitioning {
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.5
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
isPresented ? animationForPresentedView(transitionContext) : animationForDismissView(transitionContext)
}
func animationForPresentedView(_ transitionContext: UIViewControllerContextTransitioning) {
// 0.nil值校验
guard let presentedDelegate = presentedDelegate, let indexPath = indexPath else {
return
}
// 1.取出弹出的View
let presentedView = transitionContext.view(forKey: UITransitionContextViewKey.to)!
// 2.将prensentedView添加到containerView中
transitionContext.containerView.addSubview(presentedView)
// 3.获取执行动画的imageView
let startRect = presentedDelegate.startRect(indexPath)
let imageView = presentedDelegate.imageView(indexPath)
transitionContext.containerView.addSubview(imageView)
imageView.frame = startRect
// 4.执行动画
presentedView.alpha = 0.0
transitionContext.containerView.backgroundColor = UIColor.black
UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: { () -> Void in
imageView.frame = presentedDelegate.endRect(indexPath)
}, completion: { (_) -> Void in
imageView.removeFromSuperview()
presentedView.alpha = 1.0
transitionContext.containerView.backgroundColor = UIColor.clear
transitionContext.completeTransition(true)
})
}
func animationForDismissView(_ transitionContext: UIViewControllerContextTransitioning) {
// nil值校验
guard let dismissDelegate = dismissDelegate, let presentedDelegate = presentedDelegate else {
return
}
// 1.取出消失的View
let dismissView = transitionContext.view(forKey: UITransitionContextViewKey.from)
dismissView?.removeFromSuperview()
// 2.获取执行动画的ImageView
let imageView = dismissDelegate.imageViewForDimissView()
transitionContext.containerView.addSubview(imageView)
let indexPath = dismissDelegate.indexPathForDimissView()
// 3.执行动画
UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: { () -> Void in
imageView.frame = presentedDelegate.startRect(indexPath)
}, completion: { (_) -> Void in
transitionContext.completeTransition(true)
})
}
}
| 6822d41271ef4f4694ce39a13572b327 | 36.320755 | 170 | 0.699949 | false | false | false | false |
herobin22/TopOmnibus | refs/heads/master | TopOmnibus/TopOmnibus/Commons/OYViewController.swift | mit | 1 | //
// OYViewController.swift
// TopOmnibus
//
// Created by Gold on 2016/11/11.
// Copyright © 2016年 herob. All rights reserved.
//
import UIKit
import MJRefresh
import GoogleMobileAds//广告
class OYViewController: UIViewController, GADBannerViewDelegate {
let tableView = UITableView()
var curPage: Int = 1
var bannerView: GADBannerView = GADBannerView()
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
setupRefresh()
setupTitleView()
}
private func setupUI() {
view.backgroundColor = UIColor.white
tableView.frame = view.bounds
view.addSubview(tableView)
tableView.delegate = self
tableView.dataSource = self
tableView.estimatedRowHeight = 100
tableView.rowHeight = UITableViewAutomaticDimension
tableView.tableFooterView = UIView()
tableView.scrollsToTop = true
}
private func setupRefresh() {
tableView.mj_header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(headRefresh))
tableView.mj_header.beginRefreshing()
tableView.mj_footer = MJRefreshAutoNormalFooter(refreshingTarget: self, refreshingAction: #selector(footRefresh))
tableView.mj_footer.isHidden = true
}
private func setupTitleView() {
let imageView = UIImageView(image: UIImage(named: "titleBus"))
imageView.contentMode = .scaleAspectFit
imageView.bounds = CGRect(x: 0, y: 0, width: 150, height: 44)
navigationItem.titleView = imageView
}
@objc private func headRefresh() {
curPage = 1
refreshAction()
}
@objc private func footRefresh() {
curPage = curPage + 1
refreshAction()
}
private func refreshAction() -> Void {
loadData()
}
func endRefresh() {
tableView.mj_header.endRefreshing()
tableView.mj_footer.endRefreshing()
}
func loadData() {
}
}
extension OYViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
}
}
| 939411ebed7019ff67cde9fed4ff0b5c | 27.102273 | 121 | 0.650222 | false | false | false | false |
jisudong/study | refs/heads/master | Study/Study/Study_RxSwift/Platform/DataStructures/Bag.swift | mit | 1 | //
// Bag.swift
// Study
//
// Created by syswin on 2017/7/31.
// Copyright © 2017年 syswin. All rights reserved.
//
import Swift
let arrayDictionaryMaxSize = 30
struct BagKey {
fileprivate let rawValue: UInt64
}
struct Bag<T> : CustomDebugStringConvertible {
typealias KeyType = BagKey
typealias Entry = (key: BagKey, value: T)
fileprivate var _nextKey: BagKey = BagKey(rawValue: 0)
var _key0: BagKey? = nil
var _value0: T? = nil
var _pairs = ContiguousArray<Entry>()
var _dictionary: [BagKey : T]? = nil
var _onlyFastPath = true
init() { }
mutating func insert(_ element: T) -> BagKey {
let key = _nextKey
_nextKey = BagKey(rawValue: _nextKey.rawValue &+ 1)
if _key0 == nil {
_key0 = key
_value0 = element
return key
}
_onlyFastPath = false
if _dictionary != nil {
_dictionary![key] = element
return key
}
if _pairs.count < arrayDictionaryMaxSize {
_pairs.append(key: key, value: element)
return key
}
if _dictionary == nil {
_dictionary = [:]
}
_dictionary![key] = element
return key
}
var count: Int {
let dictionaryCount: Int = _dictionary?.count ?? 0
return (_value0 != nil ? 1 : 0) + _pairs.count + dictionaryCount
}
mutating func removeAll() {
_key0 = nil
_value0 = nil
_pairs.removeAll(keepingCapacity: false)
_dictionary?.removeAll(keepingCapacity: false)
}
mutating func removeKey(_ key: BagKey) -> T? {
if _key0 == key {
_key0 = nil
let value = _value0!
_value0 = nil
return value
}
if let existingObject = _dictionary?.removeValue(forKey: key) {
return existingObject
}
for i in 0 ..< _pairs.count {
if _pairs[i].key == key {
let value = _pairs[i].value
_pairs.remove(at: i)
return value
}
}
return nil
}
}
extension Bag {
var debugDescription: String {
return "\(self.count) elements in Bag"
}
}
extension Bag {
func forEach(_ action: (T) -> Void) {
if _onlyFastPath {
if let value0 = _value0 {
action(value0)
}
return
}
let value0 = _value0
let dictionary = _dictionary
if let value0 = value0 {
action(value0)
}
for i in 0 ..< _pairs.count {
action(_pairs[i].value)
}
if dictionary?.count ?? 0 > 0 {
for element in dictionary!.values {
action(element)
}
}
}
}
extension BagKey: Hashable {
var hashValue: Int {
return rawValue.hashValue
}
}
func ==(lhs: BagKey, rhs: BagKey) -> Bool {
return lhs.rawValue == rhs.rawValue
}
| f6c7c89f77b1c5128504f03a26507838 | 20.271523 | 72 | 0.482877 | false | false | false | false |
KyoheiG3/TableViewDragger | refs/heads/master | TableViewDragger/TableViewDraggerCell.swift | mit | 1 | //
// TableViewDraggerCell.swift
// TableViewDragger
//
// Created by Kyohei Ito on 2015/09/24.
// Copyright © 2015年 kyohei_ito. All rights reserved.
//
import UIKit
class TableViewDraggerCell: UIScrollView {
private let zoomingView: UIView!
var dragAlpha: CGFloat = 1
var dragScale: CGFloat = 1
var dragShadowOpacity: Float = 0.4
var dropIndexPath: IndexPath = IndexPath(index: 0)
var offset: CGPoint = CGPoint.zero {
didSet {
offset.x -= (bounds.width / 2)
offset.y -= (bounds.height / 2)
center = adjustCenter(location)
}
}
var location: CGPoint = CGPoint.zero {
didSet {
center = adjustCenter(location)
}
}
var viewHeight: CGFloat {
return zoomingView.bounds.height * zoomScale
}
private func adjustCenter(_ center: CGPoint) -> CGPoint {
var center = center
center.x -= offset.x
center.y -= offset.y
return center
}
required init?(coder aDecoder: NSCoder) {
zoomingView = UIView(frame: .zero)
super.init(coder: aDecoder)
}
init(cell: UIView) {
zoomingView = UIView(frame: cell.bounds)
zoomingView.addSubview(cell)
super.init(frame: cell.bounds)
delegate = self
clipsToBounds = false
layer.shadowColor = UIColor.black.cgColor
layer.shadowOpacity = 0
layer.shadowRadius = 5
layer.shadowOffset = .zero
addSubview(zoomingView)
}
func transformToPoint(_ point: CGPoint) {
if dragScale > 1 {
maximumZoomScale = dragScale
} else {
minimumZoomScale = dragScale
}
var center = zoomingView.center
center.x -= (center.x * dragScale) - point.x
center.y -= (center.y * dragScale) - point.y
UIView.animate(withDuration: 0.25, delay: 0.1, options: .curveEaseInOut, animations: {
self.zoomingView.center = center
self.zoomScale = self.dragScale
self.alpha = self.dragAlpha
}, completion: nil)
CATransaction.begin()
let anim = CABasicAnimation(keyPath: "shadowOpacity")
anim.fromValue = 0
anim.toValue = dragShadowOpacity
anim.duration = 0.1
anim.isRemovedOnCompletion = false
anim.fillMode = .forwards
layer.add(anim, forKey: "cellDragAnimation")
CATransaction.commit()
}
func adjustedCenter(on scrollView: UIScrollView) -> CGPoint {
var center = location
center.y -= scrollView.contentOffset.y
center.x = scrollView.center.x
return center
}
func drop(_ center: CGPoint, completion: (() -> Void)? = nil) {
UIView.animate(withDuration: 0.25) {
self.zoomingView.adjustCenterAtRect(self.zoomingView.frame)
self.center = center
self.zoomScale = 1.0
self.alpha = 1.0
}
CATransaction.begin()
let anim = CABasicAnimation(keyPath: "shadowOpacity")
anim.fromValue = dragShadowOpacity
anim.toValue = 0
anim.duration = 0.15
anim.beginTime = CACurrentMediaTime() + 0.15
anim.isRemovedOnCompletion = false
anim.fillMode = .forwards
CATransaction.setCompletionBlock {
self.removeFromSuperview()
completion?()
}
layer.add(anim, forKey: "cellDropAnimation")
CATransaction.commit()
}
}
extension TableViewDraggerCell: UIScrollViewDelegate {
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return zoomingView
}
}
private extension UIView {
func adjustCenterAtRect(_ rect: CGRect) {
let center = CGPoint(x: rect.size.width / 2, y: rect.size.height / 2)
self.center = center
}
}
| e9f9e839590171b540e4cfa38ecb1290 | 27.279412 | 94 | 0.605044 | false | false | false | false |
volendavidov/NagBar | refs/heads/master | NagBar/Icinga2URLProvider.swift | apache-2.0 | 1 | //
// Icinga2URLProvider.swift
// NagBar
//
// Created by Volen Davidov on 02.07.16.
// Copyright © 2016 Volen Davidov. All rights reserved.
//
import Foundation
class Icinga2URLProvider : MonitoringProcessorBase, URLProvider {
func create() -> Array<MonitoringURL> {
var urls: Array<MonitoringURL> = []
urls.append(MonitoringURL.init(urlType: MonitoringURLType.hosts, priority: 1, url: self.monitoringInstance!.url + "/objects/hosts?attrs=name&attrs=address&attrs=last_state_change&attrs=check_attempt&attrs=last_check_result&attrs=state&attrs=acknowledgement&attrs=downtime_depth&filter=" + Icinga2Settings().getHostStatusTypes() + Icinga2Settings().getHostProperties()))
urls.append(MonitoringURL.init(urlType: MonitoringURLType.services, priority: 2, url: self.monitoringInstance!.url + "/objects/services?attrs=name&attrs=last_state_change&attrs=check_attempt&attrs=max_check_attempts&attrs=last_check_result&attrs=state&attrs=host_name&attrs=acknowledgement&attrs=downtime_depth&filter=" + Icinga2Settings().getServiceStatusTypes() + Icinga2Settings().getServiceProperties()))
if Settings().boolForKey("skipServicesOfHostsWithScD") {
urls.append(MonitoringURL.init(urlType: MonitoringURLType.hostScheduledDowntime, priority: 3, url: self.monitoringInstance!.url + "/objects/hosts?attrs=name&filter=host.last_in_downtime==true"))
}
return urls
}
}
| ea4e689fffc2cc3fa1c13a070ca27822 | 59.583333 | 416 | 0.741403 | false | false | false | false |
erikmartens/NearbyWeather | refs/heads/develop | NearbyWeather/Commons/Core User Interface Building Blocks/TableView/BaseTableViewDataSource.swift | mit | 1 | //
// TableViewDataSource.swift
// NearbyWeather
//
// Created by Erik Maximilian Martens on 02.01.21.
// Copyright © 2021 Erik Maximilian Martens. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
class BaseTableViewDataSource: NSObject {
weak var cellEditingDelegate: BaseTableViewDataSourceEditingDelegate?
var sectionDataSources: BehaviorRelay<[TableViewSectionDataProtocol]?> = BehaviorRelay(value: nil)
init(cellEditingDelegate: BaseTableViewDataSourceEditingDelegate? = nil) {
self.cellEditingDelegate = cellEditingDelegate
}
}
extension BaseTableViewDataSource: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
sectionDataSources.value?.count ?? 0
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
sectionDataSources.value?[safe: section]?.sectionCellsCount ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cellIdentifier = sectionDataSources.value?[safe: indexPath.section]?.sectionCellsIdentifiers?[safe: indexPath.row] else {
fatalError("Could not determine reuse-identifier for sections-cells.")
}
guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? BaseCellProtocol else {
fatalError("Cell does not conform to the correct protocol (BaseCellProtocol).")
}
cell.configure(with: sectionDataSources[indexPath])
return cell
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
sectionDataSources.value?[safe: section]?.sectionHeaderTitle
}
func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
sectionDataSources.value?[safe: section]?.sectionFooterTitle
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
sectionDataSources.value?[safe: indexPath.section]?.sectionItems[safe: indexPath.row]?.canEditRow ?? false
}
func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
sectionDataSources.value?[safe: indexPath.section]?.sectionItems[safe: indexPath.row]?.canMoveRow ?? false
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
cellEditingDelegate?.didCommitEdit(with: editingStyle, forRowAt: indexPath)
}
func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
cellEditingDelegate?.didMoveRow(at: sourceIndexPath, to: destinationIndexPath)
}
}
| a1cf5afaa29e1165db7d26b700a156ee | 39.757576 | 135 | 0.762082 | false | false | false | false |
felipeuntill/WeddingPlanner | refs/heads/master | IOS/WeddingPlanner/GenericRepository.swift | mit | 1 | //
// GenericRepository.swift
// WeddingPlanner
//
// Created by Felipe Assunção on 4/21/16.
// Copyright © 2016 Felipe Assunção. All rights reserved.
//
import Foundation
import ObjectMapper
class GenericRepository<T: Mappable> {
private var address : String!
init(address: String!) {
self.address = address
}
func insert (entity : T) -> T {
let json = Mapper().toJSONString(entity, prettyPrint: true)
let raw = NSDataProvider.LoadFromUri(address, method: "POST", json: json)
let result = Mapper<T>().map(raw)
return result!
}
func list () -> Array<T>? {
let raw = NSDataProvider.LoadFromUri(address)
let list = Mapper<T>().mapArray(raw)
return list
}
func load (id : String) -> T? {
let uri = "\(address)/\(id)"
let raw = NSDataProvider.LoadFromUri(uri)
let entity = Mapper<T>().map(raw)
return entity
}
} | 4b572fc4e169afd365cac7af629e8979 | 23.820513 | 81 | 0.593588 | false | false | false | false |
fahlout/SimpleWebRequests | refs/heads/master | Sources/Web Service Layer/JSON Coder/JSONCoder.swift | mit | 1 | //
// JSONCoder.swift
// SimpleWebServiceRequestsDemo
//
// Created by Niklas Fahl on 10/11/17.
// Copyright © 2017 Niklas Fahl. All rights reserved.
//
import Foundation
public final class JSONCoder {
public class func encode<T>(object: T, dateEncodingStrategy: JSONEncoder.DateEncodingStrategy = .iso8601) -> Data? where T: Encodable {
do {
let encoder = JSONEncoder()
encoder.dateEncodingStrategy = dateEncodingStrategy
return try encoder.encode(object)
} catch let error {
print("JSON Coder: Could not encode object to JSON data. Error: \(error)")
return nil
}
}
public class func decode<T>(data: Data?, dateDecodingStrategy: JSONDecoder.DateDecodingStrategy = .iso8601) -> T? where T: Decodable {
guard let data = data else { return nil }
do {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = dateDecodingStrategy
return try decoder.decode(T.self, from: data)
} catch let error {
print("JSON Coder: Could not decode JSON data to object. Error: \(error)")
return nil
}
}
}
| 039a3881cc65ed15eb9ba55a3dda64b7 | 32.444444 | 139 | 0.61794 | false | false | false | false |
Connecthings/sdk-tutorial | refs/heads/master | ios/ObjectiveC/Zone/3-InApp-Action/Complete/InAppAction/TimeConditions.swift | apache-2.0 | 1 | //
// TimeConditions.swift
// InAppAction
//
// Created by Connecthings on 14/11/2017.
// Copyright © 2017 Connecthings. All rights reserved.
//
import Foundation
import ConnectPlaceActions
import ConnectPlaceCommon
@objc public class TimeConditions: InAppActionConditionsDefault {
@objc let delayBeforeCreation: Double
@objc public init(maxTimeBeforeReset: Double, delayBeforeCreation: Double) {
self.delayBeforeCreation = delayBeforeCreation
super.init(maxTimeBeforeReset: maxTimeBeforeReset)
}
public override func getApplicationNamespace() -> String {
return String(reflecting: TimeConditions.self).split(separator: ".")[0].description
}
public override func getConditionsKey() -> String {
return "inAppActionTimeConditions"
}
public override func getInAppActionParameterClass() -> String {
return "TimeConditionsParameter"
}
public override func updateInAppActionConditionsParameter(_ conditionsParameter: InAppActionConditionsParameter) {
if let strategyParameter = conditionsParameter as? TimeConditionsParameter {
let currentTime: Double = CFAbsoluteTimeGetCurrent()
if strategyParameter.lastDetectionTime + 3 < currentTime {
GlobalLogger.shared.debug("delay before creating " , delayBeforeCreation)
strategyParameter.timeToShowAlert = currentTime + delayBeforeCreation
}
strategyParameter.lastDetectionTime = currentTime + 0
}
super.updateInAppActionConditionsParameter(conditionsParameter)
}
public override func isConditionValid(_ conditionsParameter: InAppActionConditionsParameter) -> Bool {
if let strategyParameter = conditionsParameter as? TimeConditionsParameter {
GlobalLogger.shared.debug("delay remaining " , ( CFAbsoluteTimeGetCurrent() - strategyParameter.timeToShowAlert))
return strategyParameter.timeToShowAlert < CFAbsoluteTimeGetCurrent()
}
return true
}
}
| 6c72596e5bf2a66a6b8c0d555a887b06 | 38.692308 | 125 | 0.717054 | false | false | false | false |
calebkleveter/BluetoothKit | refs/heads/master | Source/BKDiscoveriesChange.swift | mit | 2 | //
// BluetoothKit
//
// Copyright (c) 2015 Rasmus Taulborg Hummelmose - https://github.com/rasmusth
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
public func == (lhs: BKDiscoveriesChange, rhs: BKDiscoveriesChange) -> Bool {
switch (lhs, rhs) {
case (.insert(let lhsDiscovery), .insert(let rhsDiscovery)): return lhsDiscovery == rhsDiscovery || lhsDiscovery == nil || rhsDiscovery == nil
case (.remove(let lhsDiscovery), .remove(let rhsDiscovery)): return lhsDiscovery == rhsDiscovery || lhsDiscovery == nil || rhsDiscovery == nil
default: return false
}
}
/**
Change in available discoveries.
- Insert: A new discovery.
- Remove: A discovery has become unavailable.
Cases without associated discoveries can be used to validate whether or not a change is and insert or a remove.
*/
public enum BKDiscoveriesChange: Equatable {
case insert(discovery: BKDiscovery?)
case remove(discovery: BKDiscovery?)
/// The discovery associated with the change.
public var discovery: BKDiscovery! {
switch self {
case .insert(let discovery): return discovery
case .remove(let discovery): return discovery
}
}
}
| 3f1f2ac66e78ff05d8fb6441efe5d891 | 40.418182 | 150 | 0.717296 | false | false | false | false |
zhou9734/Warm | refs/heads/master | Warm/Classes/Experience/View/EPageScrollView.swift | mit | 1 | //
// EPageScrollView.swift
// Warm
//
// Created by zhoucj on 16/9/14.
// Copyright © 2016年 zhoucj. All rights reserved.
//
import UIKit
import SDWebImage
class EPageScrollView: UIView {
let pageWidth: CGFloat = UIScreen.mainScreen().bounds.width
// let pageHeight: CGFloat = self.frame.size.height
let imageView0: UIImageView = UIImageView()
let imageView1: UIImageView = UIImageView()
let imageView2: UIImageView = UIImageView()
/// 图片数组
private var currentPage = 0{
didSet{
if tags.count > 0{
unowned let tmpSelf = self
imageView.sd_setImageWithURL(NSURL(string: tags[currentPage].avatar!), placeholderImage: placeholderImage, completed: { (image, error, _, _) -> Void in
tmpSelf.imageView.image = image.applyLightEffect()
})
}
}
}
var tags: [WTags] = [WTags](){
didSet{
updateImageData()
currentPage = 0
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupUI(){
addSubview(imageView)
addSubview(scrollView)
}
private lazy var scrollView: UIScrollView = {
let scrollView = UIScrollView()
scrollView.frame = self.bounds
//为了让内容横向滚动,设置横向内容宽度为3个页面的宽度总和
let pageHeight: CGFloat = self.frame.size.height
scrollView.contentSize=CGSizeMake(CGFloat(self.pageWidth*3),
CGFloat(pageHeight))
scrollView.pagingEnabled = true
scrollView.showsHorizontalScrollIndicator = false
scrollView.showsVerticalScrollIndicator = false
scrollView.scrollsToTop = false
scrollView.delegate = self
let imageW = self.pageWidth - (self.pageWidth*0.5)
let imageH = pageHeight - (pageHeight*0.3)
let offsetY = pageHeight*0.15
self.imageView0.frame = CGRect(x: (self.pageWidth - imageW)/2, y: offsetY, width: imageW, height: imageH)
self.imageView1.frame = CGRect(x: self.pageWidth + (self.pageWidth - imageW)/2, y: offsetY, width: imageW, height: imageH)
self.imageView2.frame = CGRect(x: self.pageWidth * 2 + (self.pageWidth - imageW)/2, y: offsetY, width: imageW, height: imageH)
scrollView.addSubview(self.imageView0)
scrollView.addSubview(self.imageView1)
scrollView.addSubview(self.imageView2)
let tap = UITapGestureRecognizer(target: self, action: "imageViewClick:")
scrollView.addGestureRecognizer(tap)
return scrollView
}()
private lazy var imageView: UIImageView = {
let iv = UIImageView()
iv.frame = CGRect(x: 0.0, y: 0.0, width: self.pageWidth, height: self.frame.size.height)
return iv
}()
// MARK: - 点击图片调转
@objc private func imageViewClick(tap: UITapGestureRecognizer) {
NSNotificationCenter.defaultCenter().postNotificationName(TagsImageClick, object: self, userInfo: [ "index" : currentPage])
}
}
extension EPageScrollView: UIScrollViewDelegate{
func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
let ratio = scrollView.contentOffset.x/scrollView.frame.size.width
self.endScrollMethod(ratio)
}
func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if !decelerate{
let ratio = scrollView.contentOffset.x/scrollView.frame.size.width
endScrollMethod(ratio)
}
}
private func endScrollMethod(ratio:CGFloat){
if ratio <= 0.7{
if currentPage - 1 < 0{
currentPage = tags.count - 1
}else{
currentPage -= 1
}
}
if ratio >= 1.3{
if currentPage == tags.count - 1{
currentPage = 0
}else{
currentPage += 1
}
}
updateImageData()
}
//MARK: - reload data
private func updateImageData(){
if currentPage == 0{
imageView0.sd_setImageWithURL(NSURL(string: tags.last!.avatar!), placeholderImage: placeholderImage)
imageView1.sd_setImageWithURL(NSURL(string: tags[currentPage].avatar!), placeholderImage: placeholderImage)
imageView2.sd_setImageWithURL(NSURL(string: tags[currentPage + 1].avatar!), placeholderImage: placeholderImage)
}else if currentPage == tags.count - 1{
imageView0.sd_setImageWithURL(NSURL(string: tags[currentPage - 1 ].avatar!), placeholderImage: placeholderImage)
imageView1.sd_setImageWithURL(NSURL(string: tags[currentPage].avatar!), placeholderImage: placeholderImage)
imageView2.sd_setImageWithURL(NSURL(string: tags.first!.avatar!), placeholderImage: placeholderImage)
}else{
imageView0.sd_setImageWithURL(NSURL(string: tags[currentPage - 1 ].avatar!), placeholderImage: placeholderImage)
imageView1.sd_setImageWithURL(NSURL(string: tags[currentPage].avatar!), placeholderImage: placeholderImage)
imageView2.sd_setImageWithURL(NSURL(string: tags[currentPage + 1].avatar!), placeholderImage: placeholderImage)
}
scrollView.contentOffset = CGPoint(x: scrollView.frame.size.width, y: 0)
}
}
| d37a958371075103fa074d3d4fba5c2a | 39.840909 | 167 | 0.644778 | false | false | false | false |
Artilles/FloppyCows | refs/heads/master | Floppy Cows/FloppyCow.swift | gpl-2.0 | 1 | //
// FloppyCow.swift
// Floppy Cows
//
// Created by Ray Young on 2014-10-31.
// Copyright (c) 2014 Velocitrix. All rights reserved.
//
import Foundation
import SpriteKit
import AVFoundation
// Cow
class FloppyCow : SKSpriteNode
{
private let cowCategory: UInt32 = 0x1 << 1
private let playerCategory: UInt32 = 0x1 << 0
private let madBullCategory: UInt32 = 0x1 << 3
private let deadCategory: UInt32 = 0x1 << 5
var cowID : Int = 0
var targetPosition : CGPoint;
var ready = false;
var textureChanged = false;
var rnd = arc4random_uniform(2)
var posIndex : Int = -1;
var soundPlayer:AVAudioPlayer = AVAudioPlayer()
var mooPlayer:AVAudioPlayer = AVAudioPlayer()
var mooURL:NSURL = NSBundle.mainBundle().URLForResource("moo", withExtension: "mp3")!
var gallopURL:NSURL = NSBundle.mainBundle().URLForResource("gallop", withExtension: "mp3")!
//MadBull
var madTimer : Double = 0
var rampageTime : CGFloat = 60.0;
var rampageTimer : CGFloat = 0.0;
var rampageInterval : CGFloat = 1.0;
var rampageCounter : CGFloat = 1.0;
var rampageSpeed : CGFloat = 1.0;
var isMad : Bool = false;
var isCharging : Bool = false
var removedWarning : Bool = false;
var playerPos: CGPoint = CGPoint(x:0,y: 0);
var rampageVector :CGPoint = CGPoint(x :0, y :0);
var pathLineMod :CGPoint = CGPoint(x :2, y :4);
var cowSpeed : CGFloat = 10;
var lockOnPlayer : Bool = false
var isAlive : Bool = true;
var direction : CGPoint = CGPoint(x :0, y :0);
var madBullID : Int = 0
var removeCow = false;
//var warnSprite : SKSpriteNode
var warn: Warning = Warning()
var temp : CGFloat = 1.0;
//fade
var isFade : Bool = false;
convenience override init()
{
// init then swap texture if the arc4random generated number is 0
// 0 is facing bottom left, 1 is facing bottom right
self.init(imageNamed: "mama_cow_falling2")
if(rnd == 0) {
self.texture = SKTexture(imageNamed:"mama_cow_falling")
}
xScale = 0.35
yScale = 0.35
physicsBody = SKPhysicsBody(rectangleOfSize: size)
physicsBody?.dynamic = true
physicsBody?.categoryBitMask = cowCategory
physicsBody?.contactTestBitMask = playerCategory
physicsBody?.collisionBitMask = 0
soundPlayer = AVAudioPlayer(contentsOfURL: gallopURL, error: nil)
mooPlayer = AVAudioPlayer(contentsOfURL: mooURL, error: nil)
//warnSprite = SKSpriteNode(imageNamed: "warning")
}
override init(texture: SKTexture!, color: UIColor!, size: CGSize)
{
targetPosition = CGPoint(x: 0, y: 0)
super.init(texture: texture, color: color, size: size)
}
required init?(coder decoder: NSCoder) {
targetPosition = CGPoint(x: 0, y: 0)
super.init(coder: decoder)
}
func SetCowID(ID: Int)
{
cowID = ID
}
func incrementTime(time : Double)
{
madTimer += time;
}
func gettingMad()
{
if(rampageCounter >= rampageInterval){
rampageTimer += 0.1;
rampageCounter += 0.1;
}
}
func switchToMadCow()
{
physicsBody = SKPhysicsBody(circleOfRadius: (size.width / 3.5))
physicsBody?.dynamic = true
physicsBody?.categoryBitMask = madBullCategory
physicsBody?.contactTestBitMask = playerCategory
physicsBody?.collisionBitMask = 0
// if(rnd == 0) {
// self.texture = SKTexture(imageNamed: "redcow_horizontal_Right.png")
// self.texture = SKTexture(imageNamed: "redcow_horizontal_Left.png")
//}
}
func UpdateCow(currentTime: CFTimeInterval)
{
if (!ready)
{
position.y -= 15
if (position.y < targetPosition.y)
{
// cow has landed
ready = true
position.y = targetPosition.y
// switch the cow texture after landing
if (rnd == 1) {
self.texture = SKTexture(imageNamed: "Mama_Cow")
} else {
self.texture = SKTexture(imageNamed: "mama_cow2")
}
}
}
else if(ready)
{
rampage()
}
}
func rampage()
{
if(rampageTime > rampageTimer){
if(rampageCounter >= rampageInterval){
rampageVector.x = self.position.x-CGFloat(arc4random_uniform(1024));
rampageVector.y = self.position.y-CGFloat(arc4random_uniform(768));
var hypotonuse : CGFloat = sqrt((rampageVector.x * rampageVector.x) + (rampageVector.y * rampageVector.y));
rampageVector.x = (rampageVector.x / hypotonuse);
rampageVector.y = (rampageVector.y / hypotonuse);
rampageVector.x *= CGFloat(arc4random())%2 == 0 ? -1 : 1;
rampageVector.y *= CGFloat(arc4random())%2 == 0 ? -1 : 1;
rampageVector.x *= rampageSpeed;
rampageVector.y *= rampageSpeed;
rampageCounter = 0.0;
zRotation = -zRotation;
}
self.position.x += rampageVector.x;
self.position.y += rampageVector.y;
warn.setPostion(self.position)
rampageTimer += 0.1;
rampageCounter += 0.1;
warn.alpha = (rampageTimer/rampageTime)
}
else{
//position.x += speed*5;
switchToMadCow()
isCharging = true
//mooPlayer.prepareToPlay()
mooPlayer.play()
//soundPlayer.prepareToPlay()
soundPlayer.volume = 0.3
soundPlayer.play()
if(!lockOnPlayer)
{
direction = CGPoint(x: playerPos.x - position.x, y: playerPos.y - position.y)
var temp : CGPoint = CGPoint(x: 0, y: 0)
temp.x = direction.x - self.position.x
//temp.y = self.position.y - direction.y
if(direction.x < 0)
{
self.texture = SKTexture(imageNamed: "redcow_horizontal_Left.png")
}
else if(direction.x >= 0)
{
self.texture = SKTexture(imageNamed: "redcow_horizontal_Right.png")
}
if(direction.x > -20 && direction.x < 20 && direction.y > 0)
{
self.texture = SKTexture(imageNamed: "Cow BUtt.png")
}
//self.texture = SKTexture(imageNamed: "Cow BUtt.png")
lockOnPlayer = true
}
let mag = sqrt(direction.x ** 2 + direction.y ** 2 )
let normalizedDirection = CGPoint(x: direction.x / mag, y: direction.y / mag)
if (mag < cowSpeed) {
self.position = playerPos
} else {
self.position.x += normalizedDirection.x * cowSpeed
self.position.y += normalizedDirection.y * cowSpeed
}
if (position.x > 1200 || position.x < -100 || position.y > 900 || position.y < -100)
{
removeCow = true
}
}
zPosition = -position.y;
}
func setPlayerPos(pos : CGPoint)
{
playerPos = pos;
}
func setDeadCategory()
{
physicsBody?.contactTestBitMask = deadCategory
physicsBody?.categoryBitMask = madBullCategory
}
} | 1f1b1e103956b7b03fd881aad7eb9d0c | 31.048193 | 123 | 0.526758 | false | false | false | false |
apple/swift-experimental-string-processing | refs/heads/main | Sources/_StringProcessing/Executor.swift | apache-2.0 | 1 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2021-2022 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
//
//===----------------------------------------------------------------------===//
@_implementationOnly import _RegexParser
struct Executor {
// TODO: consider let, for now lets us toggle tracing
var engine: Engine
init(program: MEProgram) {
self.engine = Engine(program)
}
@available(SwiftStdlib 5.7, *)
func firstMatch<Output>(
_ input: String,
subjectBounds: Range<String.Index>,
searchBounds: Range<String.Index>,
graphemeSemantic: Bool
) throws -> Regex<Output>.Match? {
var cpu = engine.makeFirstMatchProcessor(
input: input,
subjectBounds: subjectBounds,
searchBounds: searchBounds)
#if PROCESSOR_MEASUREMENTS_ENABLED
defer { if cpu.shouldMeasureMetrics { cpu.printMetrics() } }
#endif
var low = searchBounds.lowerBound
let high = searchBounds.upperBound
while true {
if let m: Regex<Output>.Match = try _match(
input, from: low, using: &cpu
) {
return m
}
if low >= high { return nil }
if graphemeSemantic {
input.formIndex(after: &low)
} else {
input.unicodeScalars.formIndex(after: &low)
}
cpu.reset(currentPosition: low)
}
}
@available(SwiftStdlib 5.7, *)
func match<Output>(
_ input: String,
in subjectBounds: Range<String.Index>,
_ mode: MatchMode
) throws -> Regex<Output>.Match? {
var cpu = engine.makeProcessor(
input: input, bounds: subjectBounds, matchMode: mode)
#if PROCESSOR_MEASUREMENTS_ENABLED
defer { if cpu.shouldMeasureMetrics { cpu.printMetrics() } }
#endif
return try _match(input, from: subjectBounds.lowerBound, using: &cpu)
}
@available(SwiftStdlib 5.7, *)
func _match<Output>(
_ input: String,
from currentPosition: String.Index,
using cpu: inout Processor
) throws -> Regex<Output>.Match? {
// FIXME: currentPosition is already encapsulated in cpu, don't pass in
// FIXME: cpu.consume() should return the matched range, not the upper bound
guard let endIdx = cpu.consume() else {
if let e = cpu.failureReason {
throw e
}
return nil
}
let capList = MECaptureList(
values: cpu.storedCaptures,
referencedCaptureOffsets: engine.program.referencedCaptureOffsets)
let range = currentPosition..<endIdx
let caps = engine.program.captureList.createElements(capList)
let anyRegexOutput = AnyRegexOutput(input: input, elements: caps)
return .init(anyRegexOutput: anyRegexOutput, range: range)
}
@available(SwiftStdlib 5.7, *)
func dynamicMatch(
_ input: String,
in subjectBounds: Range<String.Index>,
_ mode: MatchMode
) throws -> Regex<AnyRegexOutput>.Match? {
try match(input, in: subjectBounds, mode)
}
}
| 650c108e082dcd9401fe34fad47f0322 | 29.470588 | 80 | 0.638674 | false | false | false | false |
simplepanda/SimpleSQL | refs/heads/master | Sources/SSConnectionEncoding.swift | apache-2.0 | 1 | //
// Part of SimpleSQL
// https://github.com/simplepanda/SimpleSQL
//
// Created by Dylan Neild - July 2016
// [email protected]
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
import MySQL
extension SSConnection {
// Get information about the server we're connected to.
//
public func getCharacterSet() -> SSCharacterEncoding {
return SSUtils.translateCharacterString(chars: mysql_character_set_name(mysql))
}
/**
Get a string in the connection centric character set, as a Data object.
- Parameters:
- from: The string to encode into data.
- Returns: A Data object, representing the original string as encoded data.
*/
public func stringToConnectionEncoding(_ from: String) -> Data? {
return from.data(using: getCharacterSet().getPlatformEncoding(), allowLossyConversion: false)
}
/**
SQL Escape a String using the current connection character encoding
- Parameters:
- from: The String to escape
- Returns: The String, escaped and encoded into the connecton character encoding.
*/
public func escapeString(_ from: String) -> String? {
guard let encoded = stringToConnectionEncoding(from) else {
return nil
}
let sourceLength = encoded.count
let targetLength = (sourceLength * 2) + 1
let buffer : UnsafeMutablePointer<Int8> = UnsafeMutablePointer<Int8>.allocate(capacity: targetLength)
let conversionSize = encoded.withUnsafeBytes { (ptr: UnsafePointer<Int8>) -> UInt in
return mysql_real_escape_string(mysql, buffer, ptr, UInt(sourceLength))
}
guard conversionSize >= 0 else {
return nil
}
let r = SSUtils.encodingDataToString(chars: buffer, characterSet: getCharacterSet())
buffer.deallocate(capacity: targetLength)
return r
}
}
| db7520e81efed20bffb25312bd2d643f | 32.220779 | 109 | 0.648944 | false | false | false | false |
phelgo/Vectors | refs/heads/master | Vectors/Vector3D.swift | mit | 1 | // Vector structs for Swift
// Copyright (c) 2015 phelgo. MIT licensed.
import SceneKit
public struct Vector3D: CustomDebugStringConvertible, CustomStringConvertible, Equatable, Hashable {
public let x: Double
public let y: Double
public let z: Double
public init(_ x: Double, _ y: Double, _ z: Double) {
self.x = x
self.y = y
self.z = z
}
public var magnitude: Double {
return sqrt(x * x + y * y + z * z)
}
public var squaredMagnitude: Double {
return x * x + y * y + z * z
}
public var normalized: Vector3D {
return Vector3D(x / magnitude, y / magnitude, z / magnitude)
}
public var description: String {
return "Vector3D(\(x), \(y), \(z))"
}
public var debugDescription: String {
return "Vector3D(\(x), \(y), \(z)), magnitude: \(magnitude)"
}
public var hashValue: Int {
return x.hashValue ^ y.hashValue ^ z.hashValue
}
public static let zero = Vector3D(0, 0, 0)
public static let one = Vector3D(1, 1, 1)
public static let left = Vector3D(-1, 0, 0)
public static let right = Vector3D(1, 0, 0)
public static let up = Vector3D(0, 1, 0)
public static let down = Vector3D(0, -1, 0)
public static let forward = Vector3D(0, 0, 1)
public static let back = Vector3D(0, 0, -1)
}
public func == (left: Vector3D, right: Vector3D) -> Bool {
return (left.x == right.x) && (left.y == right.y) && (left.z == right.z)
}
public func + (left: Vector3D, right: Vector3D) -> Vector3D {
return Vector3D(left.x + right.x, left.y + right.y, left.z + right.z)
}
public func - (left: Vector3D, right: Vector3D) -> Vector3D {
return Vector3D(left.x - right.x, left.y - right.y, left.z - right.z)
}
public func += (inout left: Vector3D, right: Vector3D) {
left = left + right
}
public func -= (inout left: Vector3D, right: Vector3D) {
left = left - right
}
public func * (value: Double, vector: Vector3D) -> Vector3D {
return Vector3D(value * vector.x, value * vector.y, value * vector.z)
}
public func * (vector: Vector3D, value: Double) -> Vector3D {
return value * vector
}
public prefix func - (vector: Vector3D) -> Vector3D {
return Vector3D(-vector.x, -vector.y, -vector.z)
}
public func dotProduct(vectorA: Vector3D, vectorB:Vector3D) -> Double {
return vectorA.x * vectorB.x + vectorA.y * vectorB.y + vectorA.z * vectorB.z
}
infix operator -* { associativity left }
public func -*(left: Vector3D, right:Vector3D) -> Double {
return dotProduct(left, vectorB: right)
}
public func crossProduct(vectorA: Vector3D, vectorB:Vector3D) -> Vector3D {
return Vector3D(vectorA.y * vectorB.z - vectorA.z * vectorB.y, vectorA.z * vectorB.x - vectorA.x * vectorB.z, vectorA.x * vectorB.y - vectorA.y * vectorB.x)
}
infix operator +* { associativity left }
public func +*(left: Vector3D, right: Vector3D) -> Vector3D {
return crossProduct(left, vectorB: right)
}
public extension SCNVector3 {
init (_ value: Vector3D) {
self.init(x: Float(value.x), y: Float(value.y), z: Float(value.z))
}
}
public prefix func ~ (vector: Vector3D) -> SCNVector3 {
return SCNVector3(vector)
}
| 90ef9bc0ac0827133eff497ca27c7596 | 28.216216 | 160 | 0.629047 | false | false | false | false |
RamonGilabert/RamonGilabert | refs/heads/master | RamonGilabert/RamonGilabert/RGVideoViewController.swift | mit | 1 | import AVFoundation
import MediaPlayer
import UIKit
class RGVideoViewController: UIViewController {
let session = AVAudioSession()
let transitionManager = CustomVideoTransition()
var moviePlayerController = MPMoviePlayerController()
// MARK: View lifecycle
override func viewDidLoad() {
super.viewDidLoad()
self.transitioningDelegate = self.transitionManager
self.moviePlayerController = MPMoviePlayerController(contentURL: Video.MainVideoURL)
self.moviePlayerController.view.frame = CGRectMake(0, 0, Constant.Size.DeviceWidth, Constant.Size.DeviceHeight)
self.view.addSubview(self.moviePlayerController.view)
configureMoviePlayer()
addObserverToMoviePlayer()
crossButtonLayout()
self.session.setCategory(AVAudioSessionCategoryPlayback, error: nil)
self.moviePlayerController.play()
}
// MARK: Notification methods
func moviePlayerDidFinishPlaying(notification: NSNotification) {
self.session.setCategory(AVAudioSessionCategorySoloAmbient, error: nil)
self.dismissViewControllerAnimated(true, completion: { () -> Void in
NSNotificationCenter.defaultCenter().postNotificationName(Constant.Setup.NameOfNotification, object: nil)
})
}
// MARK: UIButton handler
func onCrossButtonPressed() {
self.moviePlayerController.pause()
self.session.setCategory(AVAudioSessionCategorySoloAmbient, error: nil)
self.dismissViewControllerAnimated(true, completion: { () -> Void in
self.moviePlayerController.stop()
NSNotificationCenter.defaultCenter().postNotificationName(Constant.Setup.NameOfNotification, object: nil)
})
}
// MARK: MoviePlayer configuration
func crossButtonLayout() {
let crossButton = UIButton(frame: CGRectMake(20, 20, 28, 28))
crossButton.addTarget(self, action: "onCrossButtonPressed", forControlEvents: UIControlEvents.TouchUpInside)
crossButton.setBackgroundImage(UIImage(named: "cross-button-shadow"), forState: UIControlState.Normal)
self.view.addSubview(crossButton)
}
func configureMoviePlayer() {
self.moviePlayerController.scalingMode = MPMovieScalingMode.AspectFill
self.moviePlayerController.controlStyle = MPMovieControlStyle.None
self.moviePlayerController.backgroundView.backgroundColor = UIColor_WWDC.backgroundDarkGrayColor()
self.moviePlayerController.repeatMode = MPMovieRepeatMode.None
self.moviePlayerController.allowsAirPlay = true
self.moviePlayerController.prepareToPlay()
}
func addObserverToMoviePlayer() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: "moviePlayerDidFinishPlaying:" , name: MPMoviePlayerPlaybackDidFinishNotification, object: self.moviePlayerController)
}
}
| 3cc410a1af392d05fe32d31ef0d497dd | 39.535211 | 191 | 0.740097 | false | false | false | false |
whiteshadow-gr/HatForIOS | refs/heads/master | HAT/Objects/Notes/HATNotesData.swift | mpl-2.0 | 1 | /**
* Copyright (C) 2018 HAT Data Exchange Ltd
*
* SPDX-License-Identifier: MPL2
*
* This file is part of the Hub of All Things project (HAT).
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/
*/
import SwiftyJSON
// MARK: Struct
public struct HATNotesData: HATObject, HatApiType {
// MARK: - Coding Keys
/**
The JSON fields used by the hat
The Fields are the following:
* `authorV1` in JSON is `authorv1`
* `photoV1` in JSON is `photov1`
* `locationV1` in JSON is `locationv1`
* `createdTime` in JSON is `created_time`
* `publicUntil` in JSON is `public_until`
* `updatedTime` in JSON is `updated_time`
* `isShared` in JSON is `shared`
* `isCurrentlyShared` in JSON is `currently_shared`
* `sharedOn` in JSON is `sharedOn`
* `message` in JSON is `message`
* `kind` in JSON is `kind`
*/
private enum CodingKeys: String, CodingKey {
case authorV1 = "authorv1"
case photoV1 = "photov1"
case locationV1 = "locationv1"
case createdTime = "created_time"
case publicUntil = "public_until"
case updatedTime = "updated_time"
case isShared = "shared"
case isCurrentlyShared = "currently_shared"
case sharedOn = "shared_on"
case message = "message"
case kind = "kind"
}
// MARK: - Variables
/// the author data
public var authorV1: HATNotesAuthor = HATNotesAuthor()
/// the photo data. Optional
public var photoV1: HATNotesPhoto?
/// the location data. Optional
public var locationV1: HATNotesLocation?
/// creation date
public var createdTime: String = ""
/// the date until this note will be public. Optional
public var publicUntil: String?
/// the updated time of the note
public var updatedTime: String = ""
/// if true this note is shared to facebook etc.
public var isShared: Bool = false
/// if true this note is shared to facebook etc.
public var isCurrentlyShared: Bool = false
/// If shared, where is it shared? Coma seperated string (don't know if it's optional or not)
public var sharedOn: [String] = []
/// the actual message of the note
public var message: String = ""
/// the kind of the note. 3 types available note, blog or list
public var kind: String = ""
// MARK: - Initialiser
/**
The default initialiser. Initialises everything to default values.
*/
public init() {
}
/**
It initialises everything from the received JSON file from the HAT
- dict: The JSON file received from the HAT
*/
public init(dict: Dictionary<String, JSON>) {
self.init()
self.inititialize(dict: dict)
}
/**
It initialises everything from the received JSON file from the HAT
*/
public mutating func inititialize(dict: Dictionary<String, JSON>) {
let tempDict: Dictionary<String, JSON>
if let temp: [String: JSON] = dict["notablesv1"]?.dictionaryValue {
tempDict = temp
} else {
tempDict = dict
}
if let tempAuthorData: [String: JSON] = tempDict[CodingKeys.authorV1.rawValue]?.dictionary {
authorV1 = HATNotesAuthor.init(dict: tempAuthorData)
}
if let tempPhotoData: [String: JSON] = tempDict[CodingKeys.photoV1.rawValue]?.dictionary {
photoV1 = HATNotesPhoto.init(dict: tempPhotoData)
}
if let tempLocationData: [String: JSON] = tempDict[CodingKeys.locationV1.rawValue]?.dictionary {
locationV1 = HATNotesLocation.init(dict: tempLocationData)
}
if let tempSharedOn: [JSON] = tempDict[CodingKeys.sharedOn.rawValue]?.arrayValue {
for item: JSON in tempSharedOn {
sharedOn.append(item.stringValue)
}
}
if let tempPublicUntil: String = tempDict[CodingKeys.publicUntil.rawValue]?.string {
publicUntil = tempPublicUntil
}
if let tempCreatedTime: String = tempDict[CodingKeys.createdTime.rawValue]?.string {
createdTime = tempCreatedTime
}
if let tempUpdatedTime: String = tempDict[CodingKeys.updatedTime.rawValue]?.string {
updatedTime = tempUpdatedTime
}
if let tempShared: Bool = tempDict[CodingKeys.isShared.rawValue]?.boolValue {
isShared = tempShared
}
if let tempCurrentlyShared: Bool = tempDict[CodingKeys.isCurrentlyShared.rawValue]?.boolValue {
isCurrentlyShared = tempCurrentlyShared
}
if let tempMessage: String = tempDict[CodingKeys.message.rawValue]?.string {
message = tempMessage
}
if let tempKind: String = tempDict[CodingKeys.kind.rawValue]?.string {
kind = tempKind
}
}
// MARK: - HatApiType Protocol
/**
Returns the object as Dictionary, JSON
- returns: Dictionary<String, String>
*/
public func toJSON() -> Dictionary<String, Any> {
return [
CodingKeys.authorV1.rawValue: authorV1.toJSON(),
CodingKeys.photoV1.rawValue: photoV1?.toJSON() ?? HATNotesPhoto().toJSON(),
CodingKeys.locationV1.rawValue: locationV1?.toJSON() ?? HATNotesLocation().toJSON(),
CodingKeys.createdTime.rawValue: createdTime,
CodingKeys.publicUntil.rawValue: publicUntil ?? "",
CodingKeys.updatedTime.rawValue: updatedTime,
CodingKeys.isShared.rawValue: isShared,
CodingKeys.isCurrentlyShared.rawValue: isCurrentlyShared,
CodingKeys.sharedOn.rawValue: sharedOn,
CodingKeys.message.rawValue: message,
CodingKeys.kind.rawValue: kind
]
}
/**
It initialises everything from the received Dictionary file from the cache
- fromCache: The dictionary file received from the cache
*/
public mutating func initialize(fromCache: Dictionary<String, Any>) {
let dictionary: JSON = JSON(fromCache)
self.inititialize(dict: dictionary.dictionaryValue)
}
}
| de13919bfa15eb87813af7bbd2521b50 | 31.009569 | 104 | 0.596562 | false | false | false | false |
BeckWang0912/GesturePasswordKit | refs/heads/master | Dota2Helper/Pods/Kingfisher/Sources/Filter.swift | apache-2.0 | 7 | //
// Filter.swift
// Kingfisher
//
// Created by Wei Wang on 2016/08/31.
//
// Copyright (c) 2018 Wei Wang <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import CoreImage
import Accelerate
// Reuse the same CI Context for all CI drawing.
private let ciContext = CIContext(options: nil)
/// Transformer method which will be used in to provide a `Filter`.
public typealias Transformer = (CIImage) -> CIImage?
/// Supply a filter to create an `ImageProcessor`.
public protocol CIImageProcessor: ImageProcessor {
var filter: Filter { get }
}
extension CIImageProcessor {
public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
switch item {
case .image(let image):
return image.kf.apply(filter)
case .data(_):
return (DefaultImageProcessor.default >> self).process(item: item, options: options)
}
}
}
/// Wrapper for a `Transformer` of CIImage filters.
public struct Filter {
let transform: Transformer
public init(tranform: @escaping Transformer) {
self.transform = tranform
}
/// Tint filter which will apply a tint color to images.
public static var tint: (Color) -> Filter = {
color in
Filter { input in
let colorFilter = CIFilter(name: "CIConstantColorGenerator")!
colorFilter.setValue(CIColor(color: color), forKey: kCIInputColorKey)
let colorImage = colorFilter.outputImage
let filter = CIFilter(name: "CISourceOverCompositing")!
filter.setValue(colorImage, forKey: kCIInputImageKey)
filter.setValue(input, forKey: kCIInputBackgroundImageKey)
#if swift(>=4.0)
return filter.outputImage?.cropped(to: input.extent)
#else
return filter.outputImage?.cropping(to: input.extent)
#endif
}
}
public typealias ColorElement = (CGFloat, CGFloat, CGFloat, CGFloat)
/// Color control filter which will apply color control change to images.
public static var colorControl: (ColorElement) -> Filter = { arg -> Filter in
let (brightness, contrast, saturation, inputEV) = arg
return Filter { input in
let paramsColor = [kCIInputBrightnessKey: brightness,
kCIInputContrastKey: contrast,
kCIInputSaturationKey: saturation]
let paramsExposure = [kCIInputEVKey: inputEV]
#if swift(>=4.0)
let blackAndWhite = input.applyingFilter("CIColorControls", parameters: paramsColor)
return blackAndWhite.applyingFilter("CIExposureAdjust", parameters: paramsExposure)
#else
let blackAndWhite = input.applyingFilter("CIColorControls", withInputParameters: paramsColor)
return blackAndWhite.applyingFilter("CIExposureAdjust", withInputParameters: paramsExposure)
#endif
}
}
}
extension Kingfisher where Base: Image {
/// Apply a `Filter` containing `CIImage` transformer to `self`.
///
/// - parameter filter: The filter used to transform `self`.
///
/// - returns: A transformed image by input `Filter`.
///
/// - Note: Only CG-based images are supported. If any error happens during transforming, `self` will be returned.
public func apply(_ filter: Filter) -> Image {
guard let cgImage = cgImage else {
assertionFailure("[Kingfisher] Tint image only works for CG-based image.")
return base
}
let inputImage = CIImage(cgImage: cgImage)
guard let outputImage = filter.transform(inputImage) else {
return base
}
guard let result = ciContext.createCGImage(outputImage, from: outputImage.extent) else {
assertionFailure("[Kingfisher] Can not make an tint image within context.")
return base
}
#if os(macOS)
return fixedForRetinaPixel(cgImage: result, to: size)
#else
return Image(cgImage: result, scale: base.scale, orientation: base.imageOrientation)
#endif
}
}
| 841014b7006deba7b05ea9bdefda7002 | 37.671533 | 118 | 0.655342 | false | false | false | false |
crossroadlabs/Markdown | refs/heads/master | Tests/MarkdownTests/MarkdownTests.swift | gpl-3.0 | 1 | //===--- MarkdownTests.swift ----------------------------------------------------===//
//
//Copyright (c) 2015-2016 Daniel Leping (dileping)
//
//This file is part of Markdown.
//
//Swift Express is free software: you can redistribute it and/or modify
//it under the terms of the GNU Lesser General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.
//
//Swift Express is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU Lesser General Public License for more details.
//
//You should have received a copy of the GNU Lesser General Public License
//along with Swift Express. If not, see <http://www.gnu.org/licenses/>.
//
//===----------------------------------------------------------------------===//
import XCTest
import Foundation
@testable import Markdown
#if !os(Linux) || dispatch
import Dispatch
#endif
class MarkdownTests: XCTestCase {
func testHeader() {
do {
let md = try Markdown(string:"% test\n% daniel\n% 02.03.2016\n")
let title = md.title
XCTAssertNotNil(title)
XCTAssertEqual(title!, "test")
let author = md.author
XCTAssertNotNil(author)
XCTAssertEqual(author!, "daniel")
let date = md.date
XCTAssertNotNil(date)
XCTAssertEqual(date!, "02.03.2016")
} catch {
XCTFail("Exception caught")
}
}
func testBody() {
do {
let md = try Markdown(string:"# test header")
let document = try md.document()
XCTAssertEqual(document, "<h1>test header</h1>")
} catch {
XCTFail("Exception caught")
}
}
func testTableOfContents() {
do {
let md = try Markdown(string:"# test header", options: .TableOfContents)
let document = try md.document()
XCTAssertEqual(document, "<a name=\"test.header\"></a>\n<h1>test header</h1>")
let toc = try md.tableOfContents()
XCTAssertEqual(toc, "<ul>\n <li><a href=\"#test.header\">test header</a></li>\n</ul>\n")
} catch {
XCTFail("Exception caught")
}
}
func testStyle() {
do {
let md = try Markdown(string:"<style>background-color: yellow;</style>\n# test header")
let document = try md.document()
XCTAssertEqual(document, "\n\n<h1>test header</h1>")
let css = try md.css()
XCTAssertEqual(css, "<style>background-color: yellow;</style>\n")
} catch {
XCTFail("Exception caught")
}
}
#if !os(Linux) || dispatch
// no dispatch
func testStress() {
let id = UUID().uuidString
let queue = DispatchQueue(label: id, attributes: .concurrent)
for i in 0...10000 {
let expectation = self.expectation(description: "OK " + String(i))
queue.async {
do {
let markdown = try Markdown(string: "# test line " + String(i), options: .None)
let html = try markdown.document()
XCTAssertEqual(html, "<h1>test line " + String(i) + "</h1>")
expectation.fulfill()
} catch {
XCTFail("Exception caught")
}
}
}
self.waitForExpectations(timeout: 60, handler: nil)
}
#endif
}
#if os(Linux)
extension MarkdownTests {
static var allTests : [(String, (MarkdownTests) -> () throws -> Void)] {
var tests:[(String, (MarkdownTests) -> () throws -> Void)] = [
("testHeader", testHeader),
("testBody", testBody),
("testTableOfContents", testTableOfContents),
("testStyle", testStyle),
]
#if dispatch
tests.append(("testStress", testStress))
#endif
return tests
}
}
#endif
| 93bfe23ec9674e1779ed624c34e1b5d9 | 30.666667 | 100 | 0.538756 | false | true | false | false |
SirapatBoonyasiwapong/grader | refs/heads/master | Sources/App/Database/Seeders/SeedDatabase.swift | mit | 1 | import Vapor
import Console
final class SeedCommand: Command {
public let id = "seed"
public let help = ["Seed the database."]
public let console: ConsoleProtocol
public init(console: ConsoleProtocol) {
self.console = console
}
public func run(arguments: [String]) throws {
try deleteAll()
try insertUsers()
try insertProblems()
try insertEvents()
}
private func deleteAll() throws {
try ResultCase.all().forEach { try $0.delete() }
try Submission.all().forEach { try $0.delete() }
try EventProblem.all().forEach { try $0.delete() }
try Event.all().forEach { try $0.delete() }
try ProblemCase.all().forEach { try $0.delete() }
try Problem.all().forEach { try $0.delete() }
try User.all().forEach { try $0.delete() }
}
private func insertProblems() throws {
let problem1 = Problem(name: "Hello", description: "Print \"Hello Mor Nor\" (without quotes).")
try problem1.save()
try ProblemCase(input: "", output: "Hello Mor Nor", visible: true, problemID: problem1.id).save()
let problem2 = Problem(name: "Fibonacci", description: "Print the Fibonacci sequence. The number of items to print is determined by an integer read in on the input. If the input is 0 then print nothing.")
try problem2.save()
try ProblemCase(input: "3", output: "1 1 2", visible: true, problemID: problem2.id).save()
try ProblemCase(input: "8", output: "1 1 2 3 5 8 13 21", problemID: problem2.id).save()
try ProblemCase(input: "1", output: "1", problemID: problem2.id).save()
try ProblemCase(input: "0", output: "", problemID: problem2.id).save()
let problem3 = Problem(name: "FizzBuzz 4.0", description: "Print FizzBuzz from 1 to 20. Read the Fizz value and the Buzz value from the input.")
try problem3.save()
try ProblemCase(input: "3\n5", output: "1\n2\nFizz\n4\nBuzz\nFizz\n7\n8\nFizz\nBuzz\n11\nFizz\n13\n14\nFizzBuzz\n16\n17\nFizz\n19\nBuzz", visible: true, problemID: problem3.id).save()
try ProblemCase(input: "6\n8", output: "1\n2\n3\n4\n5\nFizz\n7\nBuzz\n9\n10\n11\nFizz\n13\n14\n15\nBuzz\n17\nFizz\n19\n20", problemID: problem3.id).save()
try ProblemCase(input: "10\n20", output: "1\n2\n3\n4\n5\n6\n7\n8\n9\nFizz\n11\n12\n13\n14\n15\n16\n17\n18\n19\nFizzBuzz", problemID: problem3.id).save()
try ProblemCase(input: "10\n5", output: "1\n2\n3\n4\nBuzz\n6\n7\n8\n9\nFizzBuzz\n11\n12\n13\n14\nBuzz\n16\n17\n18\n19\nFizzBuzz", visible: true, problemID: problem3.id).save()
let problem4 = Problem(name: "Plus Seven", description: "Read in a number, add 7, and print it out.")
try problem4.save()
try ProblemCase(input: "1", output: "8", visible: true, problemID: problem4.id).save()
try ProblemCase(input: "9", output: "16", visible: true, problemID: problem4.id).save()
try ProblemCase(input: "100", output: "107", problemID: problem4.id).save()
try ProblemCase(input: "0", output: "7", problemID: problem4.id).save()
let problem5 = Problem(name: "Semi-Diagonal Alphabet", description: "First, you take the position of the letter in the alphabet, P (P is 1-indexed here). Then, you print each letter until the input (inclusive) on a line, preceded by P-1 and repeat that letter P times, interleaving with spaces.")
try problem5.save()
try ProblemCase(input: "A", output: "A", problemID: problem5.id).save()
try ProblemCase(input: "B", output: "A\n B B", visible: true, problemID: problem5.id).save()
try ProblemCase(input: "F", output: "A\n B B\n C C C\n D D D D\n E E E E E\n F F F F F F", visible: true, problemID: problem5.id).save()
try ProblemCase(input: "K", output: "A\n B B\n C C C\n D D D D\n E E E E E\n F F F F F F\n G G G G G G G\n H H H H H H H H\n I I I I I I I I I\n J J J J J J J J J J\n K K K K K K K K K K K", problemID: problem5.id).save()
let problem6 = Problem(name: "Palindrome Numbers", description: "Read in a number and check if it is a palindrome or not.")
try problem6.save()
try ProblemCase(input: "1221", output: "true", visible: true, problemID: problem6.id).save()
try ProblemCase(input: "3345433", output: "true", visible: true, problemID: problem6.id).save()
try ProblemCase(input: "1212", output: "false", visible: true, problemID: problem6.id).save()
try ProblemCase(input: "98712421789", output: "true", problemID: problem6.id).save()
}
private func insertUsers() throws {
let admin = User(name: "Administrator", username: "admin", password: "1234", role: .admin)
try admin.save()
let teacher = User(name: "Antony Harfield", username: "ant", password: "1234", role: .teacher)
try teacher.save()
let student1 = User(name: "Arya Stark", username: "student1", password: "1234", role: .student)
try student1.save()
let student2 = User(name: "Jon Snow", username: "student2", password: "1234", role: .student)
try student2.save()
let myClass: [(String, String)] = [("58312020", "Pimonrat Mayoo"),
("58313942", "Kamolporn Khankhai"),
("58313959", "Kamonphon Chaihan"),
("58313973", "Kettanok Yodsunthon"),
("58314024", "Julalak Phumket"),
("58314048", "Chanisara Uttamawetin"),
("58314062", "Titawan Laksukthom"),
("58314079", "Natdanai Phoopheeyo"),
("58314086", "Nattapon Phothima"),
("58314093", "Nattaphon Yooson"),
("58314109", "Nattawan Chomchuen"),
("58314116", "Nattawat Ruamsuk"),
("58314123", "Tuangporn Kaewchue"),
("58314130", "Tawanrung Keawjeang"),
("58314154", "Thodsaphon Phimket"),
("58314178", "Thanaphong Rittem"),
("58314185", "Thanaphon Wetchaphon"),
("58314192", "Thanawat Makenin"),
("58314222", "Tansiri Saetung"),
("58314246", "Thirakan Jeenduang"),
("58314277", "Nadia Nusak"),
("58314284", "Nitiyaporn Pormin"),
("58314321", "Bunlung Korkeattomrong"),
("58314338", "Patiphan Bunaum"),
("58314345", "Pathompong Jankom"),
("58314352", "Piyapong Ruengsiri"),
("58314369", "Pongchakorn Kanthong"),
("58314376", "Phongsiri Mahingsa"),
("58314406", "Phatcharaphon Naun-Ngam"),
("58314420", "Pittaya Boonyam"),
("58314444", "Peeraphon Khoeitui"),
("58314475", "Pakaporn Kiewpuampuang"),
("58314499", "Panusorn Banlue"),
("58314550", "Ronnachai Kammeesawang"),
("58314574", "Ratree Onchana"),
("58314581", "Lisachol Srichomchun"),
("58314628", "Vintaya Prasertsit"),
("58314642", "Witthaya Ngamprong"),
("58314659", "Winai Kengthunyakarn"),
("58314666", "Wisit Soontron"),
("58314697", "Sakchai Yotthuean"),
("58314703", "Sansanee Yimyoo"),
("58314710", "Siripaporn Kannga"),
("58314734", "Supawit Kiewbanyang"),
("58314741", "Supisara Wongkhamma"),
("58314789", "Suchada Buathong"),
("58314802", "Supicha Tejasan"),
("58314819", "Surachai Detmee"),
("58314826", "Surasit Yerpui"),
("58314840", "Athit Saenwaet"),
("58314857", "Anucha Thavorn"),
("58314864", "Apichai Noihilan"),
("58314895", "Akarapon Thaidee"),
("58314901", "Auravee Malha")]
for x in myClass {
try User(name: x.1, username: x.0, password: "1234", role: .student).save()
}
}
private func insertChaz() throws {
// Teacher
let chaz = User(name: "Charles Allen", username: "chaz", password: "cave of wonders", role: .teacher)
try chaz.save()
// Dump student users here
let myClass: [(String, String, String)] = [
("58244888", "Punyapat Supakong", "dwe7qw"),
("58344281", "Kanokwan Noppakun", "w32mqb"),
("58344298", "Krit Fumin", "9cv6rx"),
("58344311", "Kollawat Sonchai", "ky92eg"),
("58344342", "Kittinan Sukkasem", "4dvuqn"),
("58344458", "Chanthaapha Chaemchon", "mc4cns"),
("58344519", "Nuttapong Laoanantasap", "szptc7"),
("58344526", "Natthamol Unboon", "a2d32d"),
("58344571", "Tawatpong Tongmuang", "cgdv64"),
("58344588", "Tarin Gurin", "erj9sb"),
("58344625", "Photsawee Phomsawat", "zxa8ed"),
("58344632", "Pittaya Pinmanee", "7dsbp2"),
("58344656", "Peerada Sornchai", "63vxya"),
("58344724", "Chavakorn Wongnuch", "p75wza"),
("58344748", "Siripron Muangprem", "p7e246"),
("58344779", "Sarawut Poree", "gvs5pr"),
("58344830", "Sumitta Siriwat", "4ce78s"),
("58344847", "Suranart Seemarksuk", "4z9v72"),
("58344854", "Saowalak Aeamsamang", "pbf5rq"),
("58344892", "Aniwat Prakart", "r3bza4"),
("58344915", "Areeya Aongsan", "dt9p5a"),
("58348005", "Suchada Rodthongdee", "af3753"),
("58364678", "Somrak Boonkerdma", "ngw75b"),
("58364692", "Sorawit Phuthirangsriwong", "rz25dp"),
("58344328", "Kanjana Healong", "u5va4f"),
("58344373", "Kasem Senket", "2sq6n3"),
("58344403", "Jinnipa Keschai", "2rejxq"),
("58344410", "Jiradet Bunyim", "s957zk"),
("58344427", "Jirawat Nutmee", "e69g3v"),
("58344434", "Jutamad Boonmark", "fa72s2"),
("58344441", "Jutamas Duangmalai", "jw5nbt"),
("58344465", "Channarong Rodthong", "rf2n7w"),
("58344472", "Chutipong Kitsanakun", "3cpa3k"),
("58344489", "Chaowat Thaiprayun", "fxcdq5"),
("58344496", "Tanawan Kietbunditkun", "3x74zs"),
("58344533", "Duangkamon Boonrot", "7ej6z5"),
("58344557", "Tanatip Kiawngam", "6j3q6t"),
("58344564", "Thanaruk Promchai", "x5kh34"),
("58344595", "Naratorn Payaksri", "76wge6"),
("58344649", "Pawis Fuenton", "gmu47t"),
("58344694", "Rattanawalee Songwattana", "rxzwm4"),
("58344700", "Ramet Natphu", "gqhs77"),
("58344717", "Laddawan Somrak", "7ezj99"),
("58344755", "Supanida Yatopama", "f9aedk"),
("58344762", "Sanphet Duanhkham", "6u3wz6"),
("58344786", "Savinee Thaworanant", "5a6h2j"),
("58344793", "Sitanan Rodcharoen", "82zbtd"),
("58344809", "Sirikhwan Homsuwan", "5yftnm"),
("58344816", "Sukanya Iambu", "7y8wbh"),
("58344823", "Suphattra Piluek", "e98tb9"),
("58344885", "Anonset Natsaphat", "5sy756"),
("58344908", "Anucha Kaewmongkonh", "aj7gk9"),
("58344922", "Aittiporn Meekaew", "m5yw73"),
("58344946", "Opas Sakulpram", "dx5upp"),
("58347930", "Chamaiporn Rhianthong", "e8thgk"),
("58347954", "Pornpan Rungsri", "v7xb6f"),
("58347961", "Patsakon Junvee", "wxrtu5"),
("58347978", "Pawin Potijinda", "69de5h"),
]
// Save students
for x in myClass {
try User(name: x.1, username: x.0, password: x.2, role: .student).save()
}
}
private func insertEvents() throws {
guard let teacher = try User.all().first, let teacherID = teacher.id else {
console.print("Cannot find teacher or it's id")
return
}
guard let problems = try? Problem.all(), problems.count >= 3 else {
console.print("Problems not found")
return
}
let event1 = Event(name: "Swift Warm-up (Week 2)", userID: teacherID)
try event1.save()
try EventProblem(eventID: event1.id!, problemID: problems[0].id!, sequence: 1).save()
try EventProblem(eventID: event1.id!, problemID: problems[1].id!, sequence: 4).save()
try EventProblem(eventID: event1.id!, problemID: problems[2].id!, sequence: 3).save()
try EventProblem(eventID: event1.id!, problemID: problems[3].id!, sequence: 2).save()
try EventProblem(eventID: event1.id!, problemID: problems[4].id!, sequence: 5).save()
try EventProblem(eventID: event1.id!, problemID: problems[5].id!, sequence: 6).save()
// let event2 = Event(name: "Swift Mini-test 1", userID: teacherID)
// try event2.save()
// try EventProblem(eventID: event2.id!, problemID: problems[1].id!, sequence: 2).save()
// try EventProblem(eventID: event2.id!, problemID: problems[2].id!, sequence: 3).save()
}
private func insertSubmissions() throws {
guard let student = try User.makeQuery().filter("role", Role.student.rawValue).first() else {
console.print("Student not found")
return
}
guard let problem = try EventProblem.makeQuery().first() else {
console.print("Problem not found")
return
}
let submission1 = Submission(eventProblemID: problem.id!, userID: student.id!, language: .swift, files: ["hello.swift"], state: .compileFailed, compilerOutput: "Missing semicolon")
try submission1.save()
let submission2 = Submission(eventProblemID: problem.id!, userID: student.id!, language: .swift, files: ["hello.swift"], state: .graded, score: 200)
try submission2.save()
let submission3 = Submission(eventProblemID: problem.id!, userID: student.id!, language: .swift, files: ["hello.swift"], state: .submitted)
try submission3.save()
let submission4 = Submission(eventProblemID: problem.id!, userID: student.id!, language: .swift, files: ["hello.swift"], state: .submitted)
try submission4.save()
}
}
extension SeedCommand: ConfigInitializable {
public convenience init(config: Config) throws {
self.init(console: try config.resolveConsole())
}
}
| ab30669b3f69790d3154ad5f0ee6cf4e | 58.227941 | 304 | 0.518436 | false | false | false | false |
wuyezhiguhun/DDMusicFM | refs/heads/master | DDMusicFM/DDFound/Helper/DDFindRecommendHelper.swift | apache-2.0 | 1 | //
// DDFindRecommendHelper.swift
// DDMusicFM
//
// Created by yutongmac on 2017/9/14.
// Copyright © 2017年 王允顶. All rights reserved.
//
import UIKit
class DDFindRecommendHelper: NSObject {
static let helper = DDFindRecommendHelper()
var findRecommendHeaderTimer: Timer?
//MARK: == 头部定时器相关 ==
func startHeadTimer() -> Void {
self.destoryHeaderTimer()
self.findRecommendHeaderTimer = Timer.scheduledTimer(timeInterval: 3.0, target: self, selector: #selector(headerTimerChanged), userInfo: nil, repeats: true)
RunLoop.current.add(self.findRecommendHeaderTimer!, forMode: RunLoopMode.commonModes)
}
func destoryHeaderTimer() -> Void {
if self.findRecommendHeaderTimer != nil {
self.findRecommendHeaderTimer?.fireDate = NSDate.distantFuture
self.findRecommendHeaderTimer?.invalidate()
self.findRecommendHeaderTimer = nil
}
}
func headerTimerChanged() -> Void {
NotificationCenter.default.post(name: NSNotification.Name(rawValue: kNotificationFindRecommendHeaderTimer), object: nil)
}
}
| 445bfe42b1f55729c1cea965a8a56994 | 32.818182 | 164 | 0.698029 | false | false | false | false |
296245482/ILab-iOS | refs/heads/master | Charts-master/Charts/Classes/Charts/ScatterChartView.swift | apache-2.0 | 15 | //
// ScatterChartView.swift
// Charts
//
// Created by Daniel Cohen Gindi on 4/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
/// The ScatterChart. Draws dots, triangles, squares and custom shapes into the chartview.
public class ScatterChartView: BarLineChartViewBase, ScatterChartDataProvider
{
public override func initialize()
{
super.initialize()
renderer = ScatterChartRenderer(dataProvider: self, animator: _animator, viewPortHandler: _viewPortHandler)
_xAxis._axisMinimum = -0.5
}
public override func calcMinMax()
{
super.calcMinMax()
guard let data = _data else { return }
if _xAxis.axisRange == 0.0 && data.yValCount > 0
{
_xAxis.axisRange = 1.0
}
_xAxis._axisMaximum += 0.5
_xAxis.axisRange = abs(_xAxis._axisMaximum - _xAxis._axisMinimum)
}
// MARK: - ScatterChartDataProbider
public var scatterData: ScatterChartData? { return _data as? ScatterChartData }
} | da0988efc8bc9e2902a816d400b897aa | 25.888889 | 115 | 0.652605 | false | false | false | false |
SkyGrass/souyun | refs/heads/master | Pods/SnapKit/Source/ConstraintMakerRelatable.swift | apache-2.0 | 2 | //
// SnapKit
//
// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if os(iOS) || os(tvOS)
import UIKit
#else
import AppKit
#endif
public class ConstraintMakerRelatable {
internal let description: ConstraintDescription
internal init(_ description: ConstraintDescription) {
self.description = description
}
internal func relatedTo(other: ConstraintRelatableTarget, relation: ConstraintRelation, file: String, line: UInt) -> ConstraintMakerEditable {
let related: ConstraintItem
let constant: ConstraintConstantTarget
if let other = other as? ConstraintItem {
guard other.attributes == ConstraintAttributes.None ||
other.attributes.layoutAttributes.count <= 1 ||
other.attributes.layoutAttributes == self.description.attributes.layoutAttributes else {
fatalError("Cannot constraint to multiple non identical attributes. (\(file), \(line))");
}
related = other
constant = 0.0
} else if let other = other as? ConstraintView {
related = ConstraintItem(target: other, attributes: ConstraintAttributes.None)
constant = 0.0
} else if let other = other as? ConstraintConstantTarget {
related = ConstraintItem(target: nil, attributes: ConstraintAttributes.None)
constant = other
} else {
fatalError("Invalid constraint. (\(file), \(line))")
}
let editable = ConstraintMakerEditable(self.description)
editable.description.sourceLocation = (file, line)
editable.description.relation = relation
editable.description.related = related
editable.description.constant = constant
return editable
}
public func equalTo(other: ConstraintRelatableTarget, _ file: String = #file, _ line: UInt = #line) -> ConstraintMakerEditable {
return self.relatedTo(other, relation: .Equal, file: file, line: line)
}
public func lessThanOrEqualTo(other: ConstraintRelatableTarget, _ file: String = #file, _ line: UInt = #line) -> ConstraintMakerEditable {
return self.relatedTo(other, relation: .LessThanOrEqual, file: file, line: line)
}
public func greaterThanOrEqualTo(other: ConstraintRelatableTarget, _ file: String = #file, line: UInt = #line) -> ConstraintMakerEditable {
return self.relatedTo(other, relation: .GreaterThanOrEqual, file: file, line: line)
}
}
| 7cbfe180022e48fa8aea59394da6b099 | 43.670732 | 146 | 0.683593 | false | false | false | false |
RiBj1993/CodeRoute | refs/heads/master | DemoExpandingCollection/ViewControllers/DemoViewController/DemoViewController.swift | apache-2.0 | 1 | //
// DemoViewController.swift
// TestCollectionView
//
// Created by Alex K. on 12/05/16.
// Copyright © 2016 Alex K. All rights reserved.
//
import UIKit
class DemoViewController: ExpandingViewController {
typealias ItemInfo = (imageName: String, title: String)
fileprivate var cellsIsOpen = [Bool]()
fileprivate let items: [ItemInfo] = [("item0", "Boston"),("item1", "New York"),("item2", "San Francisco"),("item3", "Washington")]
@IBOutlet weak var pageLabel: UILabel!
}
// MARK: life cicle
extension DemoViewController {
override func viewDidLoad() {
itemSize = CGSize(width: 256, height: 335)
super.viewDidLoad()
registerCell()
fillCellIsOpeenArry()
addGestureToView(collectionView!)
configureNavBar()
}
}
// MARK: Helpers
extension DemoViewController {
fileprivate func registerCell() {
let nib = UINib(nibName: String(describing: DemoCollectionViewCell.self), bundle: nil)
collectionView?.register(nib, forCellWithReuseIdentifier: String(describing: DemoCollectionViewCell.self))
}
fileprivate func fillCellIsOpeenArry() {
for _ in items {
cellsIsOpen.append(false)
}
}
fileprivate func getViewController() -> ExpandingTableViewController {
let storyboard = UIStoryboard(storyboard: .Main)
let toViewController: DemoTableViewController = storyboard.instantiateViewController()
return toViewController
}
fileprivate func configureNavBar() {
navigationItem.leftBarButtonItem?.image = navigationItem.leftBarButtonItem?.image!.withRenderingMode(UIImageRenderingMode.alwaysOriginal)
}
}
/// MARK: Gesture
extension DemoViewController {
fileprivate func addGestureToView(_ toView: UIView) {
let gesutereUp = Init(UISwipeGestureRecognizer(target: self, action: #selector(DemoViewController.swipeHandler(_:)))) {
$0.direction = .up
}
let gesutereDown = Init(UISwipeGestureRecognizer(target: self, action: #selector(DemoViewController.swipeHandler(_:)))) {
$0.direction = .down
}
toView.addGestureRecognizer(gesutereUp)
toView.addGestureRecognizer(gesutereDown)
}
func swipeHandler(_ sender: UISwipeGestureRecognizer) {
let indexPath = IndexPath(row: currentIndex, section: 0)
guard let cell = collectionView?.cellForItem(at: indexPath) as? DemoCollectionViewCell else { return }
// double swipe Up transition
if cell.isOpened == true && sender.direction == .up {
pushToViewController(getViewController())
if let rightButton = navigationItem.rightBarButtonItem as? AnimatingBarButton {
rightButton.animationSelected(true)
}
}
let open = sender.direction == .up ? true : false
cell.cellIsOpen(open)
cellsIsOpen[(indexPath as NSIndexPath).row] = cell.isOpened
}
}
// MARK: UIScrollViewDelegate
extension DemoViewController {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
pageLabel.text = "\(currentIndex+1)/\(items.count)"
}
}
// MARK: UICollectionViewDataSource
extension DemoViewController {
override func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
super.collectionView(collectionView, willDisplay: cell, forItemAt: indexPath)
guard let cell = cell as? DemoCollectionViewCell else { return }
let index = (indexPath as NSIndexPath).row % items.count
let info = items[index]
cell.backgroundImageView?.image = UIImage(named: info.imageName)
cell.customTitle.text = info.title
cell.cellIsOpen(cellsIsOpen[index], animated: false)
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: IndexPath) {
guard let cell = collectionView.cellForItem(at: indexPath) as? DemoCollectionViewCell
, currentIndex == (indexPath as NSIndexPath).row else { return }
if cell.isOpened == false {
cell.cellIsOpen(true)
} else {
pushToViewController(getViewController())
if let rightButton = navigationItem.rightBarButtonItem as? AnimatingBarButton {
rightButton.animationSelected(true)
}
}
}
}
// MARK: UICollectionViewDataSource
extension DemoViewController {
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return items.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
return collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: DemoCollectionViewCell.self), for: indexPath)
}
}
| ae03c70798e077d9494952e7a33ae995 | 30.938356 | 141 | 0.726142 | false | false | false | false |
tomasharkema/HoelangTotTrein2.iOS | refs/heads/master | HoelangTotTrein2/Services/AppLocationService.swift | mit | 1 | //
// LocationService.swift
// HoelangTotTrein2
//
// Created by Tomas Harkema on 03-10-15.
// Copyright © 2015 Tomas Harkema. All rights reserved.
//
import CoreLocation
import Foundation
import Promissum
import RxSwift
#if os(watchOS)
import HoelangTotTreinAPIWatch
import HoelangTotTreinCoreWatch
#elseif os(iOS)
import HoelangTotTreinAPI
import HoelangTotTreinCore
#endif
struct SignificantLocation: Equatable {
let location: CLLocation
let neighbouringStations: [Station]
}
func == (lhs: SignificantLocation, rhs: SignificantLocation) -> Bool {
lhs.location == rhs.location
}
class AppLocationService: NSObject, CLLocationManagerDelegate, LocationService {
let manager: CLLocationManager
let significantLocationChangeObservable = Variable<SignificantLocation?>(nil).asObservable()
override init() {
manager = CLLocationManager()
super.init()
manager.delegate = self
initialize()
}
func initialize() {}
deinit {
requestAuthorizationPromise = nil
currentLocationPromise = nil
}
func locationManager(_: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
requestAuthorizationPromise?.resolve(status)
switch status {
case .authorizedAlways:
initialize()
default:
break
}
}
fileprivate var requestAuthorizationPromise: PromiseSource<CLAuthorizationStatus, Error>?
func requestAuthorization() -> Promise<CLAuthorizationStatus, Error> {
let currentState = CLLocationManager.authorizationStatus()
switch currentState {
case .authorizedAlways:
return Promise(value: currentState)
default:
requestAuthorizationPromise = PromiseSource<CLAuthorizationStatus, Error>()
manager.requestAlwaysAuthorization()
return requestAuthorizationPromise?.promise ?? Promise(error: NSError(domain: "HLTT", code: 500, userInfo: nil))
}
}
fileprivate var currentLocationPromise: PromiseSource<CLLocation, Error>?
func currentLocation() -> Promise<CLLocation, Error> {
if let location = manager.location, DateInterval(start: location.timestamp, end: Date()).duration < 560 {
return Promise(value: location)
}
if currentLocationPromise?.promise.result != nil || currentLocationPromise == nil {
currentLocationPromise = PromiseSource<CLLocation, Error>()
}
manager.requestLocation()
return currentLocationPromise!.promise
}
func locationManager(_: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let closestLocation = locations.sorted { lhs, rhs in
(lhs.horizontalAccuracy + lhs.verticalAccuracy) > (rhs.horizontalAccuracy + rhs.verticalAccuracy)
}.first
if let closestLocation = closestLocation {
currentLocationPromise?.resolve(closestLocation)
} else {
currentLocationPromise?.reject(NSError(domain: "HLTT", code: 500, userInfo: nil))
}
}
}
extension AppLocationService {
func locationManager(_: CLLocationManager, didFailWithError error: Error) {
currentLocationPromise?.reject(error)
}
}
| 2ed1ff16382dc9852462939c3e376b2d | 27.598131 | 118 | 0.741176 | false | false | false | false |
manavgabhawala/UberSDK | refs/heads/master | Shared/UberProduct.swift | apache-2.0 | 1 | //
// UberProduct.swift
// UberSDK
//
// Created by Manav Gabhawala on 6/12/15.
//
//
import Foundation
/// The Products endpoint returns information about the Uber products offered at a given location. The response includes the display name and other details about each product, and lists the products in the proper display order.
@objc public final class UberProduct : NSObject, JSONCreateable, UberObjectHasImage
{
/// Unique identifier representing a specific product for a given latitude & longitude.
@objc public let productID: String
/// Display name of product.
@objc public let name: String
/// Image URL representing the product. Depending on the platform you are using you can ask the UberProduct class to download the image `asynchronously` for you too.
@objc public let imageURL : NSURL?
/// Description of product.
@objc public let productDescription: String
/// Capacity of product. For example, 4 people.
@objc public let capacity : Int
/// The basic price details (not including any surge pricing adjustments). If null, the price is a metered fare such as a taxi service.
@objc public var priceDetails : UberPriceDetails?
@objc public override var description : String { get { return "\(name): \(productDescription)" } }
private init?(productID: String? = nil, name: String? = nil, productDescription: String? = nil, capacity: Int? = nil, imageURL: String? = nil)
{
guard let id = productID, let name = name, let description = productDescription, let capacity = capacity
else
{
self.productID = ""; self.name = ""; self.productDescription = ""; self.capacity = 0; self.imageURL = nil
super.init()
return nil
}
self.productID = id
self.name = name
self.productDescription = description
self.capacity = capacity
if let URL = imageURL
{
self.imageURL = NSURL(string: URL)
}
else
{
self.imageURL = nil
}
super.init()
}
public convenience required init?(JSON: [NSObject: AnyObject])
{
self.init(productID: JSON["product_id"] as? String, name: JSON["display_name"] as? String, productDescription: JSON["description"] as? String, capacity: JSON["capacity"] as? Int, imageURL: JSON["image"] as? String)
if self.productID.isEmpty
{
return nil
}
self.priceDetails = UberPriceDetails(JSON: JSON["price_details"] as? [NSObject: AnyObject])
}
}
| 6c2593e65bf5f5b2c5711e6203b68022 | 34.515152 | 227 | 0.719283 | false | false | false | false |
ellipse43/v2ex | refs/heads/master | v2ex/SimpleAnimate.swift | mit | 1 | //
// SimpleAnimate.swift
// v2ex
//
// Created by ellipse42 on 15/8/17.
// Copyright (c) 2015年 ellipse42. All rights reserved.
//
import Foundation
import Refresher
import QuartzCore
import UIKit
class SimpleAnimator: UIView, PullToRefreshViewDelegate {
let layerLoader = CAShapeLayer()
let imageLayer = CALayer()
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func pullToRefresh(_ view: PullToRefreshView, progressDidChange progress: CGFloat) {
layerLoader.strokeEnd = progress
}
func pullToRefresh(_ view: PullToRefreshView, stateDidChange state: PullToRefreshViewState) {
}
func pullToRefreshAnimationDidEnd(_ view: PullToRefreshView) {
layerLoader.removeAllAnimations()
}
func pullToRefreshAnimationDidStart(_ view: PullToRefreshView) {
if layerLoader.strokeEnd != 0.6 {
layerLoader.strokeEnd = 0.6
}
let pathAnimationEnd = CABasicAnimation(keyPath: "transform.rotation")
pathAnimationEnd.duration = 1.5
pathAnimationEnd.repeatCount = HUGE
pathAnimationEnd.isRemovedOnCompletion = false
pathAnimationEnd.fromValue = 0
pathAnimationEnd.toValue = 2 * M_PI
layerLoader.add(pathAnimationEnd, forKey: "strokeEndAnimation")
}
override func layoutSubviews() {
super.layoutSubviews()
if let superview = superview {
if layerLoader.superlayer == nil {
layerLoader.lineWidth = 1
layerLoader.strokeColor = UIColor.black.cgColor
layerLoader.fillColor = UIColor.clear.cgColor
layerLoader.strokeEnd = 0.6
layerLoader.lineCap = kCALineCapRound
superview.layer.addSublayer(layerLoader)
}
if imageLayer.superlayer == nil {
imageLayer.cornerRadius = 10.0
imageLayer.contents = UIImage(named:"refresh")?.cgImage
imageLayer.masksToBounds = true
imageLayer.frame = CGRect(x: superview.frame.size.width / 2 - 10, y: superview.frame.size.height / 2 - 10, width: 20.0, height: 20.0)
superview.layer.addSublayer(imageLayer)
}
let center = CGPoint(x: superview.frame.size.width / 2, y: superview.frame.size.height / 2)
let bezierPathLoader = UIBezierPath(arcCenter: center, radius: CGFloat(10), startAngle: CGFloat(0), endAngle: CGFloat(2 * M_PI), clockwise: true)
layerLoader.path = bezierPathLoader.cgPath
layerLoader.bounds = bezierPathLoader.cgPath.boundingBox
layerLoader.frame = bezierPathLoader.cgPath.boundingBox
}
}
}
| 77ed4ddeb1c6e51f379451a50cbdd3f7 | 35.820513 | 157 | 0.637535 | false | false | false | false |
efeconirulez/daily-affirmation | refs/heads/master | Daily Affirmation/Models/Affirmation.swift | apache-2.0 | 1 | //
// Affirmation.swift
// Daily Affirmation
//
// Created by Efe Helvacı on 22.10.2017.
// Copyright © 2017 efehelvaci. All rights reserved.
//
import Foundation
class Affirmation {
struct AffirmationStoreKeys {
static let BannedAffirmationsKey = "BannedAffirmations"
static let FavoriteAffirmationKey = "FavoriteAffirmations"
static let SeenAffirmationKey = "SeenAffirmations"
static let LastSeenAffirmationID = "LastSeenAffirmationID"
static let LastLaunchDate = "LastLaunchDate"
}
var id: Int
var clause: String
var isFavorite: Bool {
willSet {
guard isFavorite != newValue else {
return
}
Affirmation.isChanged = true
var favoriteAffirmations = UserDefaults.standard.array(forKey: AffirmationStoreKeys.FavoriteAffirmationKey) as? [Int] ?? [Int]()
if newValue {
favoriteAffirmations.append(self.id)
} else {
if let index = favoriteAffirmations.index(of: self.id) {
favoriteAffirmations.remove(at: index)
}
}
UserDefaults.standard.set(favoriteAffirmations, forKey: AffirmationStoreKeys.FavoriteAffirmationKey)
UserDefaults.standard.synchronize()
}
}
var isBanned: Bool {
willSet {
Affirmation.isChanged = true
var bannedAffirmations = UserDefaults.standard.array(forKey: AffirmationStoreKeys.BannedAffirmationsKey) as? [Int] ?? [Int]()
if newValue {
bannedAffirmations.append(self.id)
} else {
if let index = bannedAffirmations.index(of: self.id) {
bannedAffirmations.remove(at: index)
}
}
UserDefaults.standard.set(bannedAffirmations, forKey: AffirmationStoreKeys.BannedAffirmationsKey)
UserDefaults.standard.removeObject(forKey: AffirmationStoreKeys.LastLaunchDate)
UserDefaults.standard.synchronize()
}
}
var isSeen: Bool {
willSet {
guard isSeen != newValue else {
return
}
Affirmation.isChanged = true
var seenAffirmations = UserDefaults.standard.array(forKey: AffirmationStoreKeys.SeenAffirmationKey) as? [Int] ?? [Int]()
if newValue {
seenAffirmations.append(self.id)
} else {
if let index = seenAffirmations.index(of: self.id) {
seenAffirmations.remove(at: index)
}
}
UserDefaults.standard.set(seenAffirmations, forKey: AffirmationStoreKeys.SeenAffirmationKey)
UserDefaults.standard.synchronize()
}
}
init(id: Int, clause: String, isFavorite: Bool, isBanned: Bool, isSeen: Bool) {
self.id = id
self.clause = clause
self.isFavorite = isFavorite
self.isBanned = isBanned
self.isSeen = isSeen
}
}
extension Affirmation {
static fileprivate var shared: [Affirmation]?
static fileprivate var isChanged: Bool = true
static func getAffirmations(shouldUpdate update: Bool = isChanged) -> [Affirmation] {
if let affirmations = shared, !update {
return affirmations
}
if let plistFile = Bundle.main.path(forResource: "Affirmations", ofType: "plist"),
let affirmationObjects = NSArray(contentsOfFile: plistFile) as? [NSDictionary] {
var affirmations = [Affirmation]()
for affirmationObject in affirmationObjects {
let id = affirmationObject["id"] as! Int
let clause = affirmationObject["clause"] as! String
var isBanned = false
var isFavorite = false
var isSeen = false
if let bannedAffirmations = UserDefaults.standard.array(forKey: AffirmationStoreKeys.BannedAffirmationsKey) as? [Int] {
isBanned = bannedAffirmations.contains(id)
}
if let seenAffirmations = UserDefaults.standard.array(forKey: AffirmationStoreKeys.SeenAffirmationKey) as? [Int] {
isSeen = seenAffirmations.contains(id)
}
if let favoriteAffirmations = UserDefaults.standard.array(forKey: AffirmationStoreKeys.FavoriteAffirmationKey) as? [Int] {
isFavorite = favoriteAffirmations.contains(id)
}
affirmations.append(Affirmation(id: id, clause: clause, isFavorite: isFavorite, isBanned: isBanned, isSeen: isSeen))
}
shared = affirmations
isChanged = false
return affirmations
}
return [Affirmation]()
}
// Affirmations that can be shown
static private func validAffirmations() -> [Affirmation] {
var affirmations = getAffirmations()
affirmations = affirmations.filter{ !$0.isBanned }
if affirmations.count == 0 {
print("All clauses are banned!!!")
// TODO show message to notify user
UserDefaults.standard.removeObject(forKey: AffirmationStoreKeys.BannedAffirmationsKey)
affirmations = getAffirmations(shouldUpdate: true)
}
affirmations = affirmations.filter{ !$0.isSeen }
if affirmations.count == 0 {
print("All clauses are seen!!!")
// TODO show message to notify user
UserDefaults.standard.removeObject(forKey: AffirmationStoreKeys.SeenAffirmationKey)
affirmations = getAffirmations(shouldUpdate: true)
}
return affirmations
}
static private func storeLastAffirmation(_ affirmation: Affirmation) {
UserDefaults.standard.set(affirmation.id, forKey: AffirmationStoreKeys.LastSeenAffirmationID)
UserDefaults.standard.set(Date(), forKey: AffirmationStoreKeys.LastLaunchDate)
UserDefaults.standard.synchronize()
}
static private func random() -> Affirmation {
let affirmations = validAffirmations()
let randomAffirmation = affirmations.randomItem!
storeLastAffirmation(randomAffirmation)
return randomAffirmation
}
class public var favorites: [Affirmation] {
let affirmations = getAffirmations()
return affirmations.filter { $0.isFavorite && !$0.isBanned }
}
class public func daily() -> Affirmation {
if let previousdate = UserDefaults.standard.object(forKey: AffirmationStoreKeys.LastLaunchDate) as? Date, previousdate.isInToday {
let affirmations = getAffirmations()
let affirmationID = UserDefaults.standard.integer(forKey: AffirmationStoreKeys.LastSeenAffirmationID)
if let index = affirmations.index(where: { $0.id == affirmationID }) {
return affirmations[index]
}
}
return Affirmation.random()
}
}
| 61150abe7a14387179f52f86837caccd | 35.202899 | 140 | 0.581799 | false | false | false | false |
itsaboutcode/WordPress-iOS | refs/heads/develop | WordPress/WordPressTest/PostCompactCellTests.swift | gpl-2.0 | 2 | import UIKit
import XCTest
@testable import WordPress
class PostCompactCellTests: XCTestCase {
var postCell: PostCompactCell!
override func setUp() {
postCell = postCellFromNib()
}
func testShowImageWhenAvailable() {
let post = PostBuilder().withImage().build()
postCell.configure(with: post)
XCTAssertFalse(postCell.featuredImageView.isHidden)
}
func testHideImageWhenNotAvailable() {
let post = PostBuilder().build()
postCell.configure(with: post)
XCTAssertTrue(postCell.featuredImageView.isHidden)
}
func testShowPostTitle() {
let post = PostBuilder().with(title: "Foo bar").build()
postCell.configure(with: post)
XCTAssertEqual(postCell.titleLabel.text, "Foo bar")
}
func testShowDate() {
let post = PostBuilder().with(remoteStatus: .sync)
.with(dateCreated: Date()).build()
postCell.configure(with: post)
XCTAssertEqual(postCell.timestampLabel.text, "now")
}
func testMoreAction() {
let postActionSheetDelegateMock = PostActionSheetDelegateMock()
let post = PostBuilder().published().build()
postCell.configure(with: post)
postCell.setActionSheetDelegate(postActionSheetDelegateMock)
postCell.menuButton.sendActions(for: .touchUpInside)
XCTAssertEqual(postActionSheetDelegateMock.calledWithPost, post)
XCTAssertEqual(postActionSheetDelegateMock.calledWithView, postCell.menuButton)
}
func testStatusAndBadgeLabels() {
let post = PostBuilder().with(remoteStatus: .sync)
.with(dateCreated: Date()).is(sticked: true).build()
postCell.configure(with: post)
XCTAssertEqual(postCell.badgesLabel.text, "Sticky")
}
func testHideBadgesWhenEmpty() {
let post = PostBuilder().build()
postCell.configure(with: post)
XCTAssertEqual(postCell.badgesLabel.text, "Uploading post...")
XCTAssertFalse(postCell.badgesLabel.isHidden)
}
func testShowBadgesWhenNotEmpty() {
let post = PostBuilder()
.with(remoteStatus: .sync)
.build()
postCell.configure(with: post)
XCTAssertEqual(postCell.badgesLabel.text, "")
XCTAssertTrue(postCell.badgesLabel.isHidden)
}
func testShowProgressView() {
let post = PostBuilder()
.with(remoteStatus: .pushing)
.published().build()
postCell.configure(with: post)
XCTAssertFalse(postCell.progressView.isHidden)
}
func testHideProgressView() {
let post = PostBuilder()
.with(remoteStatus: .sync)
.published().build()
postCell.configure(with: post)
XCTAssertTrue(postCell.progressView.isHidden)
}
func testShowsWarningMessageForFailedPublishedPosts() {
// Given
let post = PostBuilder().published().with(remoteStatus: .failed).confirmedAutoUpload().build()
// When
postCell.configure(with: post)
// Then
XCTAssertEqual(postCell.badgesLabel.text, i18n("We'll publish the post when your device is back online."))
XCTAssertEqual(postCell.badgesLabel.textColor, UIColor.warning)
}
private func postCellFromNib() -> PostCompactCell {
let bundle = Bundle(for: PostCompactCell.self)
guard let postCell = bundle.loadNibNamed("PostCompactCell", owner: nil)?.first as? PostCompactCell else {
fatalError("PostCompactCell does not exist")
}
return postCell
}
}
| dc5692ef73bf4ee5a1f72f8328769c1b | 26.914729 | 114 | 0.655374 | false | true | false | false |
OscarSwanros/swift | refs/heads/master | test/Sema/enum_raw_representable.swift | apache-2.0 | 2 | // RUN: %target-typecheck-verify-swift
enum Foo : Int {
case a, b, c
}
var raw1: Int = Foo.a.rawValue
var raw2: Foo.RawValue = raw1
var cooked1: Foo? = Foo(rawValue: 0)
var cooked2: Foo? = Foo(rawValue: 22)
enum Bar : Double {
case a, b, c
}
func localEnum() -> Int {
enum LocalEnum : Int {
case a, b, c
}
return LocalEnum.a.rawValue
}
enum MembersReferenceRawType : Int {
case a, b, c
init?(rawValue: Int) {
self = MembersReferenceRawType(rawValue: rawValue)!
}
func successor() -> MembersReferenceRawType {
return MembersReferenceRawType(rawValue: rawValue + 1)!
}
}
func serialize<T : RawRepresentable>(_ values: [T]) -> [T.RawValue] {
return values.map { $0.rawValue }
}
func deserialize<T : RawRepresentable>(_ serialized: [T.RawValue]) -> [T] {
return serialized.map { T(rawValue: $0)! }
}
var ints: [Int] = serialize([Foo.a, .b, .c])
var doubles: [Double] = serialize([Bar.a, .b, .c])
var foos: [Foo] = deserialize([1, 2, 3])
var bars: [Bar] = deserialize([1.2, 3.4, 5.6])
// Infer RawValue from witnesses.
enum Color : Int {
case red
case blue
init?(rawValue: Double) {
return nil
}
var rawValue: Double {
return 1.0
}
}
var colorRaw: Color.RawValue = 7.5
// Mismatched case types
enum BadPlain : UInt { // expected-error {{'BadPlain' declares raw type 'UInt', but does not conform to RawRepresentable and conformance could not be synthesized}}
case a = "hello" // expected-error {{cannot convert value of type 'String' to raw type 'UInt'}}
}
// Recursive diagnostics issue in tryRawRepresentableFixIts()
class Outer {
// The setup is that we have to trigger the conformance check
// while diagnosing the conversion here. For the purposes of
// the test I'm putting everything inside a class in the right
// order, but the problem can trigger with a multi-file
// scenario too.
let a: Int = E.a // expected-error {{cannot convert value of type 'Outer.E' to specified type 'Int'}}
enum E : Array<Int> { // expected-error {{raw type 'Array<Int>' is not expressible by any literal}}
// expected-error@-1 {{'Outer.E' declares raw type 'Array<Int>', but does not conform to RawRepresentable and conformance could not be synthesized}}
// expected-error@-2 {{RawRepresentable conformance cannot be synthesized because raw type 'Array<Int>' is not Equatable}}
case a
}
}
// rdar://problem/32431736 - Conversion fix-it from String to String raw value enum can't look through optionals
func rdar32431736() {
enum E : String {
case A = "A"
case B = "B"
}
let items1: [String] = ["A", "a"]
let items2: [String]? = ["A"]
let myE1: E = items1.first
// expected-error@-1 {{cannot convert value of type 'String?' to specified type 'E'}}
// expected-note@-2 {{construct 'E' from unwrapped 'String' value}} {{17-17=E(rawValue: }} {{29-29=!)}}
let myE2: E = items2?.first
// expected-error@-1 {{cannot convert value of type 'String?' to specified type 'E'}}
// expected-note@-2 {{construct 'E' from unwrapped 'String' value}} {{17-17=E(rawValue: (}} {{30-30=)!)}}
}
// rdar://problem/32431165 - improve diagnostic for raw representable argument mismatch
enum E_32431165 : String {
case foo = "foo"
case bar = "bar" // expected-note {{did you mean 'bar'?}}
}
func rdar32431165_1(_: E_32431165) {}
func rdar32431165_1(_: Int) {}
func rdar32431165_1(_: Int, _: E_32431165) {}
rdar32431165_1(E_32431165.baz)
// expected-error@-1 {{type 'E_32431165' has no member 'baz'}}
rdar32431165_1(.baz)
// expected-error@-1 {{reference to member 'baz' cannot be resolved without a contextual type}}
rdar32431165_1("")
// expected-error@-1 {{cannot convert value of type 'String' to expected argument type 'E_32431165'}} {{15-15=E_32431165(rawValue: }} {{19-19=)}}
rdar32431165_1(42, "")
// expected-error@-1 {{cannot convert value of type 'String' to expected argument type 'E_32431165'}} {{20-20=E_32431165(rawValue: }} {{22-22=)}}
func rdar32431165_2(_: String) {}
func rdar32431165_2(_: Int) {}
func rdar32431165_2(_: Int, _: String) {}
rdar32431165_2(E_32431165.bar)
// expected-error@-1 {{cannot convert value of type 'E_32431165' to expected argument type 'String'}} {{15-15=}} {{31-31=.rawValue}}
rdar32431165_2(42, E_32431165.bar)
// expected-error@-1 {{cannot convert value of type 'E_32431165' to expected argument type 'String'}} {{20-20=}} {{34-34=.rawValue}}
E_32431165.bar == "bar"
// expected-error@-1 {{cannot convert value of type 'E_32431165' to expected argument type 'String}} {{1-1=}} {{15-15=.rawValue}}
"bar" == E_32431165.bar
// expected-error@-1 {{cannot convert value of type 'E_32431165' to expected argument type 'String}} {{10-10=}} {{24-24=.rawValue}}
func rdar32432253(_ condition: Bool = false) {
let choice: E_32431165 = condition ? .foo : .bar
let _ = choice == "bar"
// expected-error@-1 {{cannot convert value of type 'E_32431165' to expected argument type 'String'}} {{11-11=}} {{17-17=.rawValue}}
}
| b6116fee630f12c1b119c23754f3d399 | 32.581081 | 163 | 0.670825 | false | false | false | false |
jameslinjl/SHPJavaGrader | refs/heads/master | Sources/App/Controllers/AssignmentController.swift | mit | 1 | import HTTP
import Vapor
final class AssignmentController {
func create(_ req: Request) throws -> ResponseRepresentable {
if let labNumberString = req.data["labNumber"]?.string {
if let labNumber = Int(labNumberString) {
// ensure that a lab with this number exists
let assignmentMapping = try AssignmentMapping.query().filter(
"lab_number",
labNumber
).first()
if assignmentMapping != nil {
if let username = try req.session().data["username"]?.string {
var assignment = Assignment(
username: username,
labNumber: labNumber,
content: ""
)
try assignment.save()
return assignment
}
}
}
}
return Response(status: .badRequest)
}
func show(_ req: Request, _ assignment: Assignment) -> ResponseRepresentable {
return assignment
}
func update(_ req: Request, _ assignment: Assignment) throws -> ResponseRepresentable {
var assignment = assignment
assignment.merge(patch: req.json?.node)
try assignment.save()
return assignment
}
func destroy(_ req: Request, _ assignment: Assignment) throws -> ResponseRepresentable {
// delete all grades associated with that assignment
let grades = try GradingResult.query().filter(
"assignmentId",
assignment.id!
).all()
for grade in grades {
try grade.delete()
}
try assignment.delete()
return Response(status: .noContent)
}
}
extension AssignmentController: ResourceRepresentable {
func makeResource() -> Resource<Assignment> {
return Resource(
store: create,
show: show,
modify: update,
destroy: destroy
)
}
}
| 4d97254d8bc388b4a80c07e8baddbf2f | 24.47619 | 89 | 0.683489 | false | false | false | false |
jverkoey/FigmaKit | refs/heads/main | Sources/FigmaKit/Effect.swift | apache-2.0 | 1 | /// A Figma effect.
///
/// "A visual effect such as a shadow or blur."
/// https://www.figma.com/developers/api#effect-type
public class Effect: PolymorphicDecodable {
/// The Type of effect.
public let type: EffectType
/// Is the effect active?
public let visible: Bool
/// Radius of the blur effect (applies to shadows as well).
public let radius: Double
private enum CodingKeys: String, CodingKey {
case type
case visible
case radius
}
public required init(from decoder: Decoder) throws {
let keyedDecoder = try decoder.container(keyedBy: Self.CodingKeys)
self.type = try keyedDecoder.decode(EffectType.self, forKey: .type)
self.visible = try keyedDecoder.decode(Bool.self, forKey: .visible)
self.radius = try keyedDecoder.decode(Double.self, forKey: .radius)
}
public static func decodePolymorphicArray(from decoder: UnkeyedDecodingContainer) throws -> [Effect] {
return try decodePolyType(from: decoder, keyedBy: Effect.CodingKeys.self, key: .type, typeMap: Effect.typeMap)
}
static let typeMap: [EffectType: Effect.Type] = [
.innerShadow: Shadow.self,
.dropShadow: DropShadow.self,
.layerBlur: Effect.self,
.backgroundBlur: Effect.self,
]
public enum EffectType: String, Codable {
case innerShadow = "INNER_SHADOW"
case dropShadow = "DROP_SHADOW"
case layerBlur = "LAYER_BLUR"
case backgroundBlur = "BACKGROUND_BLUR"
}
public var description: String {
return """
<\(Swift.type(of: self))
- type: \(type)
- visible: \(visible)
- radius: \(radius)
\(effectDescription.isEmpty ? "" : "\n" + effectDescription)
>
"""
}
var effectDescription: String {
return ""
}
}
extension Effect {
/// A Figma shadow effect.
public final class Shadow: Effect {
/// The color of the shadow.
public let color: Color
/// The blend mode of the shadow.
public let blendMode: BlendMode
/// How far the shadow is projected in the x and y directions.
public let offset: Vector
/// How far the shadow spreads.
public let spread: Double
private enum CodingKeys: String, CodingKey {
case color
case blendMode
case offset
case spread
}
public required init(from decoder: Decoder) throws {
let keyedDecoder = try decoder.container(keyedBy: Self.CodingKeys)
self.color = try keyedDecoder.decode(Color.self, forKey: .color)
self.blendMode = try keyedDecoder.decode(BlendMode.self, forKey: .blendMode)
self.offset = try keyedDecoder.decode(Vector.self, forKey: .offset)
self.spread = try keyedDecoder.decodeIfPresent(Double.self, forKey: .spread) ?? 0
try super.init(from: decoder)
}
override var effectDescription: String {
return """
- color: \(color)
- blendMode: \(blendMode)
- offset: \(offset)
- spread: \(spread)
"""
}
}
/// A Figma drop shadow effect.
public final class DropShadow: Effect {
/// Whether to show the shadow behind translucent or transparent pixels.
public let showShadowBehindNode: Bool
private enum CodingKeys: String, CodingKey {
case showShadowBehindNode
}
public required init(from decoder: Decoder) throws {
let keyedDecoder = try decoder.container(keyedBy: Self.CodingKeys)
self.showShadowBehindNode = try keyedDecoder.decode(Bool.self, forKey: .showShadowBehindNode)
try super.init(from: decoder)
}
override var effectDescription: String {
return super.effectDescription + """
- showShadowBehindNode: \(showShadowBehindNode)
"""
}
}
}
| 31c33482e1b588b6b2723ca0dd5b3517 | 28.880952 | 114 | 0.651262 | false | false | false | false |
keitaoouchi/RxAudioVisual | refs/heads/master | RxAudioVisualTests/AVPlayer+RxSpec.swift | mit | 1 | import Quick
import Nimble
import RxSwift
import AVFoundation
@testable import RxAudioVisual
class AVPlayerSpec: QuickSpec {
override func spec() {
describe("KVO through rx") {
var player: AVPlayer!
var disposeBag: DisposeBag!
beforeEach {
player = AVPlayer(url: TestHelper.sampleURL)
disposeBag = DisposeBag()
}
it("should load status") {
var e: AVPlayerStatus?
player.rx.status.subscribe(onNext: { v in e = v }).disposed(by: disposeBag)
expect(e).toEventuallyNot(beNil())
expect(e).toEventually(equal(AVPlayerStatus.readyToPlay))
}
it("should load timeControlStatus") {
player.pause()
var e: AVPlayerTimeControlStatus?
player.rx.timeControlStatus.subscribe(onNext: { v in e = v }).disposed(by: disposeBag)
expect(e).toEventuallyNot(beNil())
expect(e).toEventually(equal(AVPlayerTimeControlStatus.paused))
player.play()
expect(e).toEventually(equal(AVPlayerTimeControlStatus.playing))
}
it("should load rate") {
var e: Float?
player.rx.rate.subscribe(onNext: { v in e = v }).disposed(by: disposeBag)
expect(e).toEventuallyNot(beNil())
expect(e).toEventually(equal(0.0))
player.rate = 1.0
expect(e).toEventually(equal(1.0))
}
it("should load currentItem") {
var e: AVPlayerItem?
player.rx.currentItem.subscribe(onNext: { v in e = v }).disposed(by: disposeBag)
expect(e).toEventuallyNot(beNil())
}
it("should load actionAtItemEnd") {
var e: AVPlayerActionAtItemEnd?
player.rx.actionAtItemEnd.subscribe(onNext: { v in e = v }).disposed(by: disposeBag)
expect(e).toEventuallyNot(beNil())
expect(e).toEventually(equal(AVPlayerActionAtItemEnd.pause))
}
it("should load volume") {
var e: Float?
player.rx.volume.subscribe(onNext: { v in e = v }).disposed(by: disposeBag)
expect(e).toEventuallyNot(beNil())
expect(e).toEventually(equal(1.0))
player.volume = 0.0
expect(e).toEventually(equal(0.0))
}
it("should load muted") {
var e: Bool?
player.rx.muted.subscribe(onNext: { v in e = v }).disposed(by: disposeBag)
expect(e).toEventuallyNot(beNil())
expect(e).toEventually(beFalse())
player.isMuted = true
expect(e).toEventually(beTrue())
}
it("should load closedCaptionDisplayEnabled") {
var e: Bool?
player.rx.closedCaptionDisplayEnabled.subscribe(onNext: { v in e = v }).disposed(by: disposeBag)
expect(e).toEventuallyNot(beNil())
expect(e).toEventually(beFalse())
}
it("should load allowsExternalPlayback") {
var e: Bool?
player.rx.allowsExternalPlayback.subscribe(onNext: { v in e = v }).disposed(by: disposeBag)
expect(e).toEventuallyNot(beNil())
expect(e).toEventually(beTrue())
}
it("should load externalPlaybackActive") {
var e: Bool?
player.rx.externalPlaybackActive.subscribe(onNext: { v in e = v }).disposed(by: disposeBag)
expect(e).toEventuallyNot(beNil())
expect(e).toEventually(beFalse())
}
it("should load usesExternalPlaybackWhileExternalScreenIsActive") {
var e: Bool?
player.rx.usesExternalPlaybackWhileExternalScreenIsActive.subscribe(onNext: { v in e = v }).disposed(by: disposeBag)
expect(e).toEventuallyNot(beNil())
expect(e).toEventually(beFalse())
}
}
}
}
| 0ac0c051f04e8c8e47f5762762c059dc | 32.240741 | 124 | 0.627298 | false | false | false | false |
PauloMigAlmeida/Signals | refs/heads/master | SwiftSignalKit/Signal_Timing.swift | mit | 1 | import Foundation
public func delay<T, E>(timeout: NSTimeInterval, queue: Queue)(signal: Signal<T, E>) -> Signal<T, E> {
return Signal<T, E> { subscriber in
let disposable = MetaDisposable()
let timer = Timer(timeout: timeout, repeat: false, completion: {
disposable.set(signal.start(next: { next in
subscriber.putNext(next)
}, error: { error in
subscriber.putError(error)
}, completed: {
subscriber.putCompletion()
}))
}, queue: queue)
disposable.set(ActionDisposable {
timer.invalidate()
})
timer.start()
return disposable
}
}
public func timeout<T, E>(timeout: NSTimeInterval, queue: Queue, alternate: Signal<T, E>)(signal: Signal<T, E>) -> Signal<T, E> {
return Signal<T, E> { subscriber in
let disposable = MetaDisposable()
let timer = Timer(timeout: timeout, repeat: false, completion: {
disposable.set(alternate.start(next: { next in
subscriber.putNext(next)
}, error: { error in
subscriber.putError(error)
}, completed: {
subscriber.putCompletion()
}))
}, queue: queue)
disposable.set(signal.start(next: { next in
timer.invalidate()
subscriber.putNext(next)
}, error: { error in
timer.invalidate()
subscriber.putError(error)
}, completed: {
timer.invalidate()
subscriber.putCompletion()
}))
timer.start()
let disposableSet = DisposableSet()
disposableSet.add(ActionDisposable {
timer.invalidate()
})
disposableSet.add(disposable)
return disposableSet
}
}
| 5f4eb6983f1262e1ab86e1fcaca1752f | 32.142857 | 129 | 0.545259 | false | false | false | false |
SymbolLong/Photo | refs/heads/master | photo-ios/photo-ios/Common.swift | apache-2.0 | 1 | //
// File.swift
// photo-ios
//
// Created by 张圣龙 on 2017/4/14.
// Copyright © 2017年 张圣龙. All rights reserved.
//
import Foundation
class Common{
static let HOST_KEY = "host"
static let PORT_KEY = "port"
static let ID_KEY = "id"
static let API_GET = "/api/get?id="
}
| 1b14d74edaf24853b9c58d3a3c6d6890 | 17.125 | 47 | 0.613793 | false | false | false | false |
tgu/HAP | refs/heads/master | Sources/HAP/Endpoints/pairSetup().swift | mit | 1 | import Cryptor
import func Evergreen.getLogger
import Foundation
import SRP
fileprivate let logger = getLogger("hap.pairSetup")
fileprivate typealias Session = PairSetupController.Session
fileprivate let SESSION_KEY = "hap.pair-setup.session"
fileprivate enum Error: Swift.Error {
case noSession
}
// swiftlint:disable:next cyclomatic_complexity
func pairSetup(device: Device) -> Application {
let group = Group.N3072
let algorithm = Digest.Algorithm.sha512
let username = "Pair-Setup"
let (salt, verificationKey) = createSaltedVerificationKey(username: username,
password: device.setupCode,
group: group,
algorithm: algorithm)
let controller = PairSetupController(device: device)
func createSession() -> Session {
return Session(server: SRP.Server(username: username,
salt: salt,
verificationKey: verificationKey,
group: group,
algorithm: algorithm))
}
func getSession(_ connection: Server.Connection) throws -> Session {
guard let session = connection.context[SESSION_KEY] as? Session else {
throw Error.noSession
}
return session
}
return { connection, request in
var body = Data()
guard
(try? request.readAllData(into: &body)) != nil,
let data: PairTagTLV8 = try? decode(body),
let sequence = data[.state]?.first.flatMap({ PairSetupStep(rawValue: $0) })
else {
return .badRequest
}
let response: PairTagTLV8?
do {
switch sequence {
// M1: iOS Device -> Accessory -- `SRP Start Request'
case .startRequest:
let session = createSession()
response = try controller.startRequest(data, session)
connection.context[SESSION_KEY] = session
// M3: iOS Device -> Accessory -- `SRP Verify Request'
case .verifyRequest:
let session = try getSession(connection)
response = try controller.verifyRequest(data, session)
// M5: iOS Device -> Accessory -- `Exchange Request'
case .keyExchangeRequest:
let session = try getSession(connection)
response = try controller.keyExchangeRequest(data, session)
// Unknown state - return error and abort
default:
throw PairSetupController.Error.invalidParameters
}
} catch {
logger.warning(error)
connection.context[SESSION_KEY] = nil
try? device.changePairingState(.notPaired)
switch error {
case PairSetupController.Error.invalidParameters:
response = [
(.state, Data(bytes: [PairSetupStep.waiting.rawValue])),
(.error, Data(bytes: [PairError.unknown.rawValue]))
]
case PairSetupController.Error.alreadyPaired:
response = [
(.state, Data(bytes: [PairSetupStep.startResponse.rawValue])),
(.error, Data(bytes: [PairError.unavailable.rawValue]))
]
case PairSetupController.Error.alreadyPairing:
response = [
(.state, Data(bytes: [PairSetupStep.startResponse.rawValue])),
(.error, Data(bytes: [PairError.busy.rawValue]))
]
case PairSetupController.Error.invalidSetupState:
response = [
(.state, Data(bytes: [PairSetupStep.verifyResponse.rawValue])),
(.error, Data(bytes: [PairError.unknown.rawValue]))
]
case PairSetupController.Error.authenticationFailed:
response = [
(.state, Data(bytes: [PairSetupStep.verifyResponse.rawValue])),
(.error, Data(bytes: [PairError.authenticationFailed.rawValue]))
]
default:
response = nil
}
}
if let response = response {
return Response(status: .ok, data: encode(response), mimeType: "application/pairing+tlv8")
} else {
return .badRequest
}
}
}
| ffd49b5ebdd321f6943252676c77b155 | 41.738318 | 102 | 0.542314 | false | false | false | false |
xiaoleixy/Cocoa_swift | refs/heads/master | RaiseMan/RaiseMan/Document.swift | mit | 1 | //
// Document.swift
// RaiseMan
//
// Created by michael on 15/2/14.
// Copyright (c) 2015年 michael. All rights reserved.
//
import Cocoa
//忘记加前缀了, 看着这不要有疑惑 就是RMDocument
class Document: NSDocument {
@objc(employees)
var employees:[Person] = [Person]() {
willSet {
for person in employees {
self.stopObservingPerson(person as Person)
}
}
didSet {
for person in employees {
self.startObservingPerson(person as Person)
}
}
}
@IBOutlet var tableView: NSTableView!
@IBOutlet var employeeController: NSArrayController!
private var RMDocumentKVOContext = 0
override init() {
super.init()
// Add your subclass-specific initialization here.
NSNotificationCenter.defaultCenter().addObserver(self, selector:"handleColorChange:" , name: BNRColorChangedNotification, object: nil)
}
override func windowControllerDidLoadNib(aController: NSWindowController) {
super.windowControllerDidLoadNib(aController)
// Add any code here that needs to be executed once the windowController has loaded the document's window.
tableView.backgroundColor = PreferenceController.preferenceTableBgColor()
}
override class func autosavesInPlace() -> Bool {
return true
}
override var windowNibName: String? {
// Returns the nib file name of the document
// If you need to use a subclass of NSWindowController or if your document supports multiple NSWindowControllers, you should remove this property and override -makeWindowControllers instead.
return "Document"
}
override func dataOfType(typeName: String, error outError: NSErrorPointer) -> NSData? {
// Insert code here to write your document to data of the specified type. If outError != nil, ensure that you create and set an appropriate error when returning nil.
// You can also choose to override fileWrapperOfType:error:, writeToURL:ofType:error:, or writeToURL:ofType:forSaveOperation:originalContentsURL:error: instead.
// outError.memory = NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil)
// return nil
//保存
tableView.window?.endEditingFor(nil)
return NSKeyedArchiver.archivedDataWithRootObject(employees)
}
override func readFromData(data: NSData, ofType typeName: String, error outError: NSErrorPointer) -> Bool {
// Insert code here to read your document from the given data of the specified type. If outError != nil, ensure that you create and set an appropriate error when returning false.
// You can also choose to override readFromFileWrapper:ofType:error: or readFromURL:ofType:error: instead.
// If you override either of these, you should also override -isEntireFileLoaded to return NO if the contents are lazily loaded.
if let newArray = NSKeyedUnarchiver.unarchiveObjectWithData(data) as? [Person] {
self.employees = newArray
return true
}else
{
outError.memory = NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil)
return false
}
}
override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {
if (context != &RMDocumentKVOContext)
{
super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
return
}
let undo = self.undoManager
var oldValue: AnyObject? = change[NSKeyValueChangeOldKey]
undo?.prepareWithInvocationTarget(self).changeKeyPath(keyPath, ofObject: object, toValue: oldValue!)
undo?.setActionName("Edit")
}
@IBAction func onCheck(sender: AnyObject) {
println(self.employees)
}
@IBAction func createEmployee(sender: AnyObject)
{
let w: NSWindow = self.tableView.window!
//准备结束正在发生的编辑动作
let editingEnded = w.makeFirstResponder(w)
if (!editingEnded)
{
println("Unable to end editing")
return
}
let undo = self.undoManager
if undo?.groupingLevel > 0 {
undo?.endUndoGrouping()
undo?.beginUndoGrouping()
}
let p = self.employeeController.newObject() as Person
self.employeeController.addObject(p)
//重新排序
self.employeeController.rearrangeObjects()
//排序后的数组
var a = self.employeeController.arrangedObjects as NSArray
let row = a.indexOfObjectIdenticalTo(p)
self.tableView.editColumn(0, row: row, withEvent: nil, select: true)
}
func startObservingPerson(person: Person)
{
person.addObserver(self, forKeyPath: "personName", options: NSKeyValueObservingOptions.Old, context: &RMDocumentKVOContext)
person.addObserver(self, forKeyPath: "expectedRaise", options: NSKeyValueObservingOptions.Old, context: &RMDocumentKVOContext)
}
func stopObservingPerson(person: Person)
{
person.removeObserver(self, forKeyPath: "personName", context: &RMDocumentKVOContext)
person.removeObserver(self, forKeyPath: "expectedRaise", context: &RMDocumentKVOContext)
}
func changeKeyPath(keyPath:NSString, ofObject obj: AnyObject, toValue newValue:AnyObject)
{
obj.setValue(newValue, forKeyPath: keyPath)
}
func insertObject(p: Person, inEmployeesAtIndex index: Int){
println("adding \(p) to \(self.employees)")
let undo = self.undoManager
undo?.prepareWithInvocationTarget(self).removeObjectFromEmployeesAtIndex(index)
if (false == undo?.undoing) {
undo?.setActionName("Add Person")
}
self.employees.insert(p, atIndex: index)
}
func removeObjectFromEmployeesAtIndex(index: Int) {
let p: Person = self.employees[index] as Person
println("removing \(p) to \(self.employees)")
let undo = self.undoManager
undo?.prepareWithInvocationTarget(self).insertObject(p, inEmployeesAtIndex: index)
if (false == undo?.undoing) {
undo?.setActionName("Remove Person")
}
self.employees.removeAtIndex(index)
}
func handleColorChange(notification: NSNotification)
{
tableView.backgroundColor = PreferenceController.preferenceTableBgColor()
}
}
| 8a5988168797952e7b281e5b8f28c099 | 35.33871 | 198 | 0.648321 | false | false | false | false |
tise/SwipeableViewController | refs/heads/master | SwipeableViewController/Source/SwipeableNavigationBar.swift | mit | 1 | //
// SwipeableNavigationBar.swift
// SwipingViewController
//
// Created by Oscar Apeland on 12.10.2017.
// Copyright © 2017 Tise. All rights reserved.
//
import UIKit
open class SwipeableNavigationBar: UINavigationBar {
public override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
private func setup() {
if #available(iOS 11.0, *) {
largeTitleTextAttributes = [.foregroundColor: UIColor.clear]
prefersLargeTitles = true
}
}
// MARK: Properties
lazy var largeTitleView: UIView? = {
return subviews.first {
String(describing: type(of: $0)) == "_UINavigationBarLargeTitleView"
}
}()
var largeTitleLabel: UILabel? {
return largeTitleView?.subviews.first { $0 is UILabel } as? UILabel
}
lazy var collectionView: SwipeableCollectionView = {
$0.autoresizingMask = [.flexibleWidth, .flexibleTopMargin]
return $0
}(SwipeableCollectionView(frame: largeTitleView!.bounds,
collectionViewLayout: SwipeableCollectionViewFlowLayout()))
}
| 891a03600962e55809956ebbc1124705 | 26.608696 | 89 | 0.615748 | false | false | false | false |
narner/AudioKit | refs/heads/master | Playgrounds/AudioKitPlaygrounds/Playgrounds/Filters.playground/Pages/Resonant Filter.xcplaygroundpage/Contents.swift | mit | 1 | //: ## Resonant Filter
//:
import AudioKitPlaygrounds
import AudioKit
let file = try AKAudioFile(readFileName: playgroundAudioFiles[0])
let player = try AKAudioPlayer(file: file)
player.looping = true
var filter = AKResonantFilter(player)
filter.frequency = 5_000 // Hz
filter.bandwidth = 600 // Cents
AudioKit.output = filter
AudioKit.start()
player.play()
//: User Interface Set up
import AudioKitUI
class LiveView: AKLiveViewController {
override func viewDidLoad() {
addTitle("Resonant Filter")
addView(AKResourcesAudioFileLoaderView(player: player, filenames: playgroundAudioFiles))
addView(AKButton(title: "Stop") { button in
filter.isStarted ? filter.stop() : filter.play()
button.title = filter.isStarted ? "Stop" : "Start"
})
addView(AKSlider(property: "Frequency",
value: filter.frequency,
range: 20 ... 22_050,
taper: 5,
format: "%0.1f Hz"
) { sliderValue in
filter.frequency = sliderValue
})
addView(AKSlider(property: "Bandwidth",
value: filter.bandwidth,
range: 100 ... 1_200,
format: "%0.1f Hz"
) { sliderValue in
filter.bandwidth = sliderValue
})
}
}
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
PlaygroundPage.current.liveView = LiveView()
| 9aa5b235ced717b8ee1aa84f9f7fba6e | 26.563636 | 96 | 0.600264 | false | false | false | false |
ikesyo/Swiftz | refs/heads/master | Swiftz/State.swift | bsd-3-clause | 3 | //
// State.swift
// Swiftz
//
// Created by Robert Widmann on 2/21/15.
// Copyright (c) 2015 TypeLift. All rights reserved.
//
/// The State Monad represents a computation that threads a piece of state through each step.
public struct State<S, A> {
public let runState : S -> (A, S)
/// Creates a new State Monad given a function from a piece of state to a value and an updated
/// state.
public init(_ runState : S -> (A, S)) {
self.runState = runState
}
/// Evaluates the computation given an initial state then returns a final value after running
/// each step.
public func eval(s : S) -> A {
return self.runState(s).0
}
/// Evaluates the computation given an initial state then returns the final state after running
/// each step.
public func exec(s : S) -> S {
return self.runState(s).1
}
/// Executes an action that can modify the inner state.
public func withState(f : S -> S) -> State<S, A> {
return State(self.runState • f)
}
}
/// Fetches the current value of the state.
public func get<S>() -> State<S, S> {
return State<S, S> { ($0, $0) }
}
/// Sets the state.
public func put<S>(s : S) -> State<S, ()> {
return State<S, ()> { _ in ((), s) }
}
/// Gets a specific component of the state using a projection function.
public func gets<S, A>(f : S -> A) -> State<S, A> {
return State { s in (f(s), s) }
}
/// Updates the state with the result of executing the given function.
public func modify<S>(f : S -> S) -> State<S, ()> {
return State<S, ()> { s in ((), f(s)) }
}
extension State : Functor {
public typealias B = Swift.Any
public typealias FB = State<S, B>
public func fmap<B>(f : A -> B) -> State<S, B> {
return State<S, B> { s in
let (val, st2) = self.runState(s)
return (f(val), st2)
}
}
}
public func <^> <S, A, B>(f : A -> B, s : State<S, A>) -> State<S, B> {
return s.fmap(f)
}
extension State : Pointed {
public static func pure(x : A) -> State<S, A> {
return State { s in (x, s) }
}
}
extension State : Applicative {
public typealias FAB = State<S, A -> B>
public func ap<B>(stfn : State<S, A -> B>) -> State<S, B> {
return stfn.bind { f in
return self.bind { a in
return State<S, B>.pure(f(a))
}
}
}
}
public func <*> <S, A, B>(f : State<S, A -> B> , s : State<S, A>) -> State<S, B> {
return s.ap(f)
}
extension State : ApplicativeOps {
public typealias C = Any
public typealias FC = State<S, C>
public typealias D = Any
public typealias FD = State<S, D>
public static func liftA<B>(f : A -> B) -> State<S, A> -> State<S, B> {
return { a in State<S, A -> B>.pure(f) <*> a }
}
public static func liftA2<B, C>(f : A -> B -> C) -> State<S, A> -> State<S, B> -> State<S, C> {
return { a in { b in f <^> a <*> b } }
}
public static func liftA3<B, C, D>(f : A -> B -> C -> D) -> State<S, A> -> State<S, B> -> State<S, C> -> State<S, D> {
return { a in { b in { c in f <^> a <*> b <*> c } } }
}
}
extension State : Monad {
public func bind<B>(f : A -> State<S, B>) -> State<S, B> {
return State<S, B> { s in
let (a, s2) = self.runState(s)
return f(a).runState(s2)
}
}
}
public func >>- <S, A, B>(xs : State<S, A>, f : A -> State<S, B>) -> State<S, B> {
return xs.bind(f)
}
extension State : MonadOps {
public static func liftM<B>(f : A -> B) -> State<S, A> -> State<S, B> {
return { m1 in m1 >>- { x1 in State<S, B>.pure(f(x1)) } }
}
public static func liftM2<B, C>(f : A -> B -> C) -> State<S, A> -> State<S, B> -> State<S, C> {
return { m1 in { m2 in m1 >>- { x1 in m2 >>- { x2 in State<S, C>.pure(f(x1)(x2)) } } } }
}
public static func liftM3<B, C, D>(f : A -> B -> C -> D) -> State<S, A> -> State<S, B> -> State<S, C> -> State<S, D> {
return { m1 in { m2 in { m3 in m1 >>- { x1 in m2 >>- { x2 in m3 >>- { x3 in State<S, D>.pure(f(x1)(x2)(x3)) } } } } } }
}
}
public func >>->> <S, A, B, C>(f : A -> State<S, B>, g : B -> State<S, C>) -> (A -> State<S, C>) {
return { x in f(x) >>- g }
}
public func <<-<< <S, A, B, C>(g : B -> State<S, C>, f : A -> State<S, B>) -> (A -> State<S, C>) {
return f >>->> g
}
| 829e8723e4cd2bbbe08c1d2ca5985e37 | 26.493243 | 121 | 0.557877 | false | false | false | false |
TotalDigital/People-iOS | refs/heads/master | People at Total/Profile.swift | apache-2.0 | 1 | //
// Profile.swift
// justOne
//
// Created by Florian Letellier on 29/01/2017.
// Copyright © 2017 Florian Letellier. All rights reserved.
//
import Foundation
class Profile: NSObject, NSCoding {
var id: Int = 0
var user: User!
var jobs: [Job] = []
var degree: [Degree] = []
var projects: [Project] = []
var relations: Relation = Relation()
var skills: Skill = Skill()
var langues: Language = Language()
var contact: Contact = Contact()
override init() {
}
init(id: Int, user: User, jobs: [Job],projects: [Project],relations: Relation,skills: Skill,langues: Language,contact: Contact) {
self.id = id
self.user = user
self.jobs = jobs
self.projects = projects
self.relations = relations
self.skills = skills
self.langues = langues
self.contact = contact
}
required convenience init(coder aDecoder: NSCoder) {
let id = aDecoder.decodeInteger(forKey: "id")
let user = aDecoder.decodeObject(forKey: "user") as! User
let jobs = aDecoder.decodeObject(forKey: "jobs") as! [Job]
let projects = aDecoder.decodeObject(forKey: "projects") as! [Project]
let relations = aDecoder.decodeObject(forKey: "relations") as! Relation
let skills = aDecoder.decodeObject(forKey: "skills") as! Skill
let langues = aDecoder.decodeObject(forKey: "langues") as! Language
let contact = aDecoder.decodeObject(forKey: "contact") as! Contact
self.init(id: id, user: user, jobs: jobs,projects: projects,relations: relations,skills: skills,langues: langues,contact: contact)
}
func encode(with aCoder: NSCoder) {
aCoder.encode(id, forKey: "id")
aCoder.encode(user, forKey: "user")
aCoder.encode(jobs, forKey: "jobs")
aCoder.encode(projects, forKey: "projects")
aCoder.encode(relations, forKey: "relations")
aCoder.encode(skills, forKey: "skills")
aCoder.encode(langues, forKey: "langues")
aCoder.encode(contact, forKey: "contact")
}
}
| 1ee9ab276b073b601054506dde2c0b44 | 34.216667 | 138 | 0.62991 | false | false | false | false |
Finb/V2ex-Swift | refs/heads/master | View/MemberTopicCell.swift | mit | 1 | //
// MemberTopicCell.swift
// V2ex-Swift
//
// Created by huangfeng on 2/1/16.
// Copyright © 2016 Fin. All rights reserved.
//
import UIKit
class MemberTopicCell: UITableViewCell {
/// 日期 和 最后发送人
var dateAndLastPostUserLabel: UILabel = {
let dateAndLastPostUserLabel = UILabel();
dateAndLastPostUserLabel.font=v2Font(12);
return dateAndLastPostUserLabel
}()
/// 评论数量
var replyCountLabel: UILabel = {
let replyCountLabel = UILabel()
replyCountLabel.font = v2Font(12)
return replyCountLabel
}()
var replyCountIconImageView: UIImageView = {
let replyCountIconImageView = UIImageView(image: UIImage(named: "reply_n"))
replyCountIconImageView.contentMode = .scaleAspectFit
return replyCountIconImageView
}()
/// 节点
var nodeNameLabel: UILabel = {
let nodeNameLabel = UILabel();
nodeNameLabel.font = v2Font(11)
nodeNameLabel.layer.cornerRadius=2;
nodeNameLabel.clipsToBounds = true
return nodeNameLabel
}()
/// 帖子标题
var topicTitleLabel: UILabel = {
let topicTitleLabel=V2SpacingLabel();
topicTitleLabel.font=v2Font(15);
topicTitleLabel.numberOfLines=0;
topicTitleLabel.preferredMaxLayoutWidth=SCREEN_WIDTH-24;
return topicTitleLabel
}()
/// 装上面定义的那些元素的容器
var contentPanel:UIView = {
let contentPanel = UIView();
return contentPanel
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier);
self.setup();
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setup()->Void{
self.selectionStyle = .none
self.contentView .addSubview(self.contentPanel);
self.contentPanel.addSubview(self.dateAndLastPostUserLabel);
self.contentPanel.addSubview(self.replyCountLabel);
self.contentPanel.addSubview(self.replyCountIconImageView);
self.contentPanel.addSubview(self.nodeNameLabel)
self.contentPanel.addSubview(self.topicTitleLabel);
self.setupLayout()
self.themeChangedHandler = {[weak self] _ in
self?.contentPanel.backgroundColor = V2EXColor.colors.v2_CellWhiteBackgroundColor
self?.backgroundColor = V2EXColor.colors.v2_backgroundColor
self?.dateAndLastPostUserLabel.textColor=V2EXColor.colors.v2_TopicListDateColor;
self?.replyCountLabel.textColor = V2EXColor.colors.v2_TopicListDateColor
self?.nodeNameLabel.textColor = V2EXColor.colors.v2_TopicListDateColor
self?.nodeNameLabel.backgroundColor = V2EXColor.colors.v2_NodeBackgroundColor
self?.topicTitleLabel.textColor=V2EXColor.colors.v2_TopicListTitleColor;
self?.dateAndLastPostUserLabel.backgroundColor = self?.contentPanel.backgroundColor
self?.replyCountLabel.backgroundColor = self?.contentPanel.backgroundColor
self?.replyCountIconImageView.backgroundColor = self?.contentPanel.backgroundColor
self?.topicTitleLabel.backgroundColor = self?.contentPanel.backgroundColor
}
}
func setupLayout(){
self.contentPanel.snp.makeConstraints{ (make) -> Void in
make.top.left.right.equalTo(self.contentView);
}
self.dateAndLastPostUserLabel.snp.makeConstraints{ (make) -> Void in
make.top.equalTo(self.contentPanel).offset(12);
make.left.equalTo(self.contentPanel).offset(12);
}
self.replyCountLabel.snp.makeConstraints{ (make) -> Void in
make.centerY.equalTo(self.dateAndLastPostUserLabel);
make.right.equalTo(self.contentPanel).offset(-12);
}
self.replyCountIconImageView.snp.makeConstraints{ (make) -> Void in
make.centerY.equalTo(self.replyCountLabel);
make.width.height.equalTo(18);
make.right.equalTo(self.replyCountLabel.snp.left).offset(-2);
}
self.nodeNameLabel.snp.makeConstraints{ (make) -> Void in
make.centerY.equalTo(self.replyCountLabel);
make.right.equalTo(self.replyCountIconImageView.snp.left).offset(-4)
make.bottom.equalTo(self.replyCountLabel).offset(1);
make.top.equalTo(self.replyCountLabel).offset(-1);
}
self.topicTitleLabel.snp.makeConstraints{ (make) -> Void in
make.top.equalTo(self.dateAndLastPostUserLabel.snp.bottom).offset(12);
make.left.equalTo(self.dateAndLastPostUserLabel);
make.right.equalTo(self.contentPanel).offset(-12);
}
self.contentPanel.snp.makeConstraints{ (make) -> Void in
make.bottom.equalTo(self.topicTitleLabel.snp.bottom).offset(12);
make.bottom.equalTo(self.contentView).offset(SEPARATOR_HEIGHT * -1);
}
}
func bind(_ model:MemberTopicsModel){
self.dateAndLastPostUserLabel.text = model.date
self.topicTitleLabel.text = model.topicTitle;
self.replyCountLabel.text = model.replies;
if let node = model.nodeName{
self.nodeNameLabel.text = " " + node + " "
}
}
}
| 3e6cad5cf8cf29e5205b351558064dcf | 38.411765 | 95 | 0.658582 | false | false | false | false |
iwufan/SocketServerDemo | refs/heads/master | SocketDemo-Server/SocketDemo/Custom/Extensions/UIButton+Extension.swift | mit | 1 | //
// UIButton+Extension.swift
// MusicWorld
//
// Created by David Jia on 15/8/2017.
// Copyright © 2017 David Jia. All rights reserved.
//
import UIKit
// MARK: - init method
extension UIButton {
/// quick way to create a button with image and background image
convenience init (normalImage: UIImage? = nil, selectedImage: UIImage? = nil, backgroundImage: UIImage? = nil) {
self.init()
setImage(normalImage, for: .normal)
setImage(selectedImage, for: .selected)
setBackgroundImage(backgroundImage, for: .normal)
}
/// create a button with title/fontSize/TitleColor/bgColor
convenience init (title: String, fontSize: CGFloat, titleColor: UIColor, selTitleColor: UIColor? = nil, bgColor: UIColor = UIColor.clear, isBold: Bool = false) {
self.init()
setTitle(title, for: .normal)
titleLabel?.font = isBold ? UIFont.boldSystemFont(ofSize: fontSize) : UIFont.systemFont(ofSize: fontSize)
setTitleColor(titleColor, for: .normal)
setTitleColor(selTitleColor == nil ? titleColor : selTitleColor, for: .selected)
backgroundColor = bgColor
}
}
// MARK: - instance method
extension UIButton {
func setup(title: String, selTitle: String? = nil, fontSize: CGFloat, isBold: Bool = false, titleColor: UIColor, bgColor: UIColor = UIColor.clear, titleOffset: UIEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0)) {
setTitle(title, for: .normal)
setTitle(selTitle == nil ? title : selTitle, for: .selected)
titleLabel?.font = isBold ? UIFont.boldSystemFont(ofSize: fontSize) : UIFont.systemFont(ofSize: fontSize)
setTitleColor(titleColor, for: .normal)
backgroundColor = bgColor
titleEdgeInsets = titleOffset
}
}
| 7453d7b709dd6d7c9cccc6c7168d4224 | 35.979592 | 210 | 0.6617 | false | false | false | false |
honghaoz/CrackingTheCodingInterview | refs/heads/master | Swift/LeetCode/Array/492_Construct the Rectangle.swift | mit | 1 | // 492_Construct the Rectangle
// https://leetcode.com/problems/construct-the-rectangle/
//
// Created by Honghao Zhang on 9/20/19.
// Copyright © 2019 Honghaoz. All rights reserved.
//
// Description:
// For a web developer, it is very important to know how to design a web page's size. So, given a specific rectangular web page’s area, your job by now is to design a rectangular web page, whose length L and width W satisfy the following requirements:
//
//1. The area of the rectangular web page you designed must equal to the given target area.
//
//2. The width W should not be larger than the length L, which means L >= W.
//
//3. The difference between length L and width W should be as small as possible.
//You need to output the length L and the width W of the web page you designed in sequence.
//Example:
//
//Input: 4
//Output: [2, 2]
//Explanation: The target area is 4, and all the possible ways to construct it are [1,4], [2,2], [4,1].
//But according to requirement 2, [1,4] is illegal; according to requirement 3, [4,1] is not optimal compared to [2,2]. So the length L is 2, and the width W is 2.
//Note:
//
//The given area won't exceed 10,000,000 and is a positive integer
//The web page's width and length you designed must be positive integers.
//
import Foundation
class Num492 {
// Easy one
func constructRectangle(_ area: Int) -> [Int] {
guard area > 0 else {
return []
}
var width = Int(sqrt(Double(area)))
while width > 0 {
let height = area / width
if width * height == area {
return [height, width]
}
width -= 1
}
assertionFailure()
return []
}
}
| 87dbdc5288c931769855058f707c8375 | 33.416667 | 251 | 0.677361 | false | false | false | false |
applivery/applivery-ios-sdk | refs/heads/master | AppliverySDK/Applivery/Coordinators/FeedbackCoordinator.swift | mit | 1 | //
// FeedbackCoordinator.swift
// AppliverySDK
//
// Created by Alejandro Jiménez on 28/2/16.
// Copyright © 2016 Applivery S.L. All rights reserved.
//
import Foundation
protocol PFeedbackCoordinator {
func showFeedack()
func closeFeedback()
}
class FeedbackCoordinator: PFeedbackCoordinator {
var feedbackVC: FeedbackView!
fileprivate var app: AppProtocol
fileprivate var isFeedbackPresented = false
// MARK: - Initializers
init(app: AppProtocol = App()) {
self.app = app
}
func showFeedack() {
guard !self.isFeedbackPresented else {
logWarn("Feedback view is already presented")
return
}
self.isFeedbackPresented = true
let feedbackVC = FeedbackVC.viewController()
self.feedbackVC = feedbackVC
feedbackVC.presenter = FeedbackPresenter(
view: self.feedbackVC,
feedbackInteractor: Configurator.feedbackInteractor(),
feedbackCoordinator: self,
screenshotInteractor: Configurator.screenshotInteractor()
)
self.app.presentModal(feedbackVC, animated: false)
}
func closeFeedback() {
self.feedbackVC.dismiss(animated: true) {
self.isFeedbackPresented = false
}
}
}
| 11b1723b057b9013468b9aa383143350 | 19.672727 | 60 | 0.740545 | false | false | false | false |
WagnerUmezaki/SwiftCharts | refs/heads/master | SwiftCharts/DiscreteLineChartView.swift | mit | 1 | import UIKit
@IBDesignable public class DiscreteLineChartView: UIView {
@IBInspectable public var startColor: UIColor = UIColor.red
@IBInspectable public var endColor: UIColor = UIColor.orange
private var graphPoints:[Int] = []
override public init(frame: CGRect) {
super.init(frame: frame)
}
convenience public init( graphPoints: [Int] ) {
self.init(frame: CGRect.zero)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override public func draw(_ rect: CGRect) {
let width = rect.width
let height = rect.height
//set up background clipping area
let path = UIBezierPath(roundedRect: rect,
byRoundingCorners: UIRectCorner.allCorners,
cornerRadii: CGSize(width: 8.0, height: 8.0))
path.addClip()
//2 - get the current context
let context = UIGraphicsGetCurrentContext()
let colors = [startColor.cgColor, endColor.cgColor] as CFArray
//3 - set up the color space
let colorSpace = CGColorSpaceCreateDeviceRGB()
//4 - set up the color stops
let colorLocations:[CGFloat] = [0.0, 1.0]
//5 - create the gradient
let gradient = CGGradient(colorsSpace: colorSpace,
colors: colors,
locations: colorLocations)
//6 - draw the gradient
var startPoint = CGPoint.zero
var endPoint = CGPoint(x:0, y:self.bounds.height)
context!.drawLinearGradient(gradient!,
start: startPoint,
end: endPoint,
options: CGGradientDrawingOptions(rawValue: 0))
let margin:CGFloat = 20.0
let columnXPoint = { (column:Int) -> CGFloat in
//Calculate gap between points
let spacer = (width - margin*2 - 4) /
CGFloat((self.graphPoints.count - 1))
var x:CGFloat = CGFloat(column) * spacer
x += margin + 2
return x
}
let topBorder:CGFloat = 20
let bottomBorder:CGFloat = 20
let graphHeight = height - topBorder - bottomBorder
let maxValue = graphPoints.max() ?? 0
let columnYPoint = { (graphPoint:Int) -> CGFloat in
var y:CGFloat = CGFloat(graphPoint) /
CGFloat(maxValue) * graphHeight
y = graphHeight + topBorder - y // Flip the graph
return y
}
if(graphPoints.count > 0){
// draw the line graph
UIColor.white.setFill()
UIColor.white.setStroke()
//set up the points line
let graphPath = UIBezierPath()
//go to start of line
graphPath.move(to: CGPoint(x:columnXPoint(0), y:columnYPoint(graphPoints[0])))
//add points for each item in the graphPoints array
//at the correct (x, y) for the point
for i in 1..<graphPoints.count {
let nextPoint = CGPoint(x:columnXPoint(i), y:columnYPoint(graphPoints[i]))
graphPath.addLine(to: nextPoint)
}
//Create the clipping path for the graph gradient
//1 - save the state of the context (commented out for now)
context!.saveGState()
//2 - make a copy of the path
let clippingPath = graphPath.copy() as! UIBezierPath
//3 - add lines to the copied path to complete the clip area
clippingPath.addLine(to: CGPoint(
x: columnXPoint(graphPoints.count - 1),
y:height))
clippingPath.addLine(to: CGPoint(
x:columnXPoint(0),
y:height))
clippingPath.close()
//4 - add the clipping path to the context
clippingPath.addClip()
let highestYPoint = columnYPoint(maxValue)
startPoint = CGPoint(x:margin, y: highestYPoint)
endPoint = CGPoint(x:margin, y:self.bounds.height)
context!.drawLinearGradient(gradient!, start: startPoint, end: endPoint, options: CGGradientDrawingOptions(rawValue: 0))
context!.restoreGState()
//draw the line on top of the clipped gradient
graphPath.lineWidth = 2.0
graphPath.stroke()
//Draw the circles on top of graph stroke
for i in 0..<graphPoints.count {
var point = CGPoint(x:columnXPoint(i), y:columnYPoint(graphPoints[i]))
point.x -= 5.0/2
point.y -= 5.0/2
let circle = UIBezierPath(ovalIn:
CGRect(origin: point,
size: CGSize(width: 5.0, height: 5.0)))
circle.fill()
}
//Draw horizontal graph lines on the top of everything
let linePath = UIBezierPath()
//top line
linePath.move(to: CGPoint(x:margin, y: topBorder))
linePath.addLine(to: CGPoint(x: width - margin,
y:topBorder))
//center line
linePath.move(to: CGPoint(x:margin,
y: graphHeight/2 + topBorder))
linePath.addLine(to: CGPoint(x:width - margin,
y:graphHeight/2 + topBorder))
//bottom line
linePath.move(to: CGPoint(x:margin,
y:height - bottomBorder))
linePath.addLine(to: CGPoint(x:width - margin,
y:height - bottomBorder))
let color = UIColor(white: 1.0, alpha: 0.3)
color.setStroke()
linePath.lineWidth = 1.0
linePath.stroke()
}
}
public func setChartData(data: [Int]) {
self.graphPoints = data
self.setNeedsDisplay()
}
}
| 3946adde481efe50eadc18d3b02d1f02 | 36.825581 | 132 | 0.516446 | false | false | false | false |
Suninus/SwiftyDrop | refs/heads/master | SwiftyDrop/Drop.swift | mit | 1 | //
// Drop.swift
// SwiftyDrop
//
// Created by MORITANAOKI on 2015/06/18.
//
import UIKit
public enum DropState {
case Default, Info, Success, Warning, Error
private func backgroundColor() -> UIColor? {
switch self {
case Default: return UIColor(red: 41/255.0, green: 128/255.0, blue: 185/255.0, alpha: 1.0)
case Info: return UIColor(red: 52/255.0, green: 152/255.0, blue: 219/255.0, alpha: 1.0)
case Success: return UIColor(red: 39/255.0, green: 174/255.0, blue: 96/255.0, alpha: 1.0)
case Warning: return UIColor(red: 241/255.0, green: 196/255.0, blue: 15/255.0, alpha: 1.0)
case Error: return UIColor(red: 192/255.0, green: 57/255.0, blue: 43/255.0, alpha: 1.0)
}
}
}
public enum DropBlur {
case Light, ExtraLight, Dark
private func blurEffect() -> UIBlurEffect {
switch self {
case .Light: return UIBlurEffect(style: .Light)
case .ExtraLight: return UIBlurEffect(style: .ExtraLight)
case .Dark: return UIBlurEffect(style: .Dark)
}
}
}
public final class Drop: UIView {
private var backgroundView: UIView!
private var statusLabel: UILabel!
private var topConstraint: NSLayoutConstraint!
private var heightConstraint: NSLayoutConstraint!
private let statusTopMargin: CGFloat = 10.0
private let statusBottomMargin: CGFloat = 10.0
private var minimumHeight: CGFloat { return Drop.statusBarHeight() + 44.0 }
private var upTimer: NSTimer?
private var startTop: CGFloat?
override init(frame: CGRect) {
super.init(frame: frame)
heightConstraint = NSLayoutConstraint(
item: self,
attribute: .Height,
relatedBy: .Equal,
toItem: nil,
attribute: .Height,
multiplier: 1.0,
constant: 100.0
)
self.addConstraint(heightConstraint)
scheduleUpTimer(4.0)
NSNotificationCenter.defaultCenter().addObserverForName(UIApplicationDidEnterBackgroundNotification, object: nil, queue: nil) { [weak self] notification in
if let s = self {
s.stopUpTimer()
s.removeFromSuperview()
}
}
NSNotificationCenter.defaultCenter().addObserverForName(UIDeviceOrientationDidChangeNotification, object: nil, queue: nil) { [weak self] notification in
if let s = self {
s.updateHeight()
}
}
}
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
deinit {
stopUpTimer()
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func up() {
scheduleUpTimer(0.0)
}
func upFromTimer(timer: NSTimer) {
if let interval = timer.userInfo as? Double {
Drop.up(self, interval: interval)
}
}
private func scheduleUpTimer(after: Double) {
scheduleUpTimer(after, interval: 0.25)
}
private func scheduleUpTimer(after: Double, interval: Double) {
stopUpTimer()
upTimer = NSTimer.scheduledTimerWithTimeInterval(after, target: self, selector: "upFromTimer:", userInfo: interval, repeats: false)
}
private func stopUpTimer() {
upTimer?.invalidate()
upTimer = nil
}
private func updateHeight() {
let calculatedHeight = self.statusLabel.frame.size.height + Drop.statusBarHeight() + statusTopMargin + statusBottomMargin
println("cal: \(calculatedHeight)")
heightConstraint.constant = calculatedHeight > minimumHeight ? calculatedHeight : minimumHeight
self.layoutIfNeeded()
}
}
extension Drop {
public class func down(status: String) {
down(status, state: .Default)
}
public class func down(status: String, state: DropState) {
down(status, state: state, blur: nil)
}
public class func down(status: String, blur: DropBlur) {
down(status, state: nil, blur: blur)
}
private class func down(status: String, state: DropState?, blur: DropBlur?) {
self.upAll()
let drop = Drop(frame: CGRectZero)
Drop.window().addSubview(drop)
let sideConstraints = ([.Left, .Right] as [NSLayoutAttribute]).map {
return NSLayoutConstraint(
item: drop,
attribute: $0,
relatedBy: .Equal,
toItem: Drop.window(),
attribute: $0,
multiplier: 1.0,
constant: 0.0
)
}
drop.topConstraint = NSLayoutConstraint(
item: drop,
attribute: .Top,
relatedBy: .Equal,
toItem: Drop.window(),
attribute: .Top,
multiplier: 1.0,
constant: -drop.heightConstraint.constant
)
Drop.window().addConstraints(sideConstraints)
Drop.window().addConstraint(drop.topConstraint)
drop.setup(status, state: state, blur: blur)
drop.updateHeight()
drop.topConstraint.constant = 0.0
UIView.animateWithDuration(
NSTimeInterval(0.25),
delay: NSTimeInterval(0.0),
options: .AllowUserInteraction | .CurveEaseOut,
animations: { [weak drop] () -> Void in
if let drop = drop { drop.layoutIfNeeded() }
}, completion: nil
)
}
private class func up(drop: Drop, interval: NSTimeInterval) {
drop.topConstraint.constant = -drop.heightConstraint.constant
UIView.animateWithDuration(
interval,
delay: NSTimeInterval(0.0),
options: .AllowUserInteraction | .CurveEaseIn,
animations: { [weak drop] () -> Void in
if let drop = drop {
drop.layoutIfNeeded()
}
}) { [weak drop] finished -> Void in
if let drop = drop { drop.removeFromSuperview() }
}
}
public class func upAll() {
for view in Drop.window().subviews {
if let drop = view as? Drop {
drop.up()
}
}
}
}
extension Drop {
private func setup(status: String, state: DropState?, blur: DropBlur?) {
self.setTranslatesAutoresizingMaskIntoConstraints(false)
if let blur = blur {
let blurEffect = blur.blurEffect()
// Visual Effect View
let visualEffectView = UIVisualEffectView(effect: blurEffect)
visualEffectView.setTranslatesAutoresizingMaskIntoConstraints(false)
self.addSubview(visualEffectView)
let visualEffectViewConstraints = ([.Right, .Bottom, .Left] as [NSLayoutAttribute]).map {
return NSLayoutConstraint(
item: visualEffectView,
attribute: $0,
relatedBy: .Equal,
toItem: self,
attribute: $0,
multiplier: 1.0,
constant: 0.0
)
}
let topConstraint = NSLayoutConstraint(
item: visualEffectView,
attribute: .Top,
relatedBy: .Equal,
toItem: self,
attribute: .Top,
multiplier: 1.0,
constant: -UIScreen.mainScreen().bounds.height
)
self.addConstraints(visualEffectViewConstraints)
self.addConstraint(topConstraint)
self.backgroundView = visualEffectView
// Vibrancy Effect View
let vibrancyEffectView = UIVisualEffectView(effect: UIVibrancyEffect(forBlurEffect: blurEffect))
vibrancyEffectView.setTranslatesAutoresizingMaskIntoConstraints(false)
visualEffectView.contentView.addSubview(vibrancyEffectView)
let vibrancyLeft = NSLayoutConstraint(
item: vibrancyEffectView,
attribute: .Left,
relatedBy: .Equal,
toItem: visualEffectView.contentView,
attribute: .LeftMargin,
multiplier: 1.0,
constant: 0.0
)
let vibrancyRight = NSLayoutConstraint(
item: vibrancyEffectView,
attribute: .Right,
relatedBy: .Equal,
toItem: visualEffectView.contentView,
attribute: .RightMargin,
multiplier: 1.0,
constant: 0.0
)
let vibrancyTop = NSLayoutConstraint(
item: vibrancyEffectView,
attribute: .Top,
relatedBy: .Equal,
toItem: visualEffectView.contentView,
attribute: .Top,
multiplier: 1.0,
constant: 0.0
)
let vibrancyBottom = NSLayoutConstraint(
item: vibrancyEffectView,
attribute: .Bottom,
relatedBy: .Equal,
toItem: visualEffectView.contentView,
attribute: .Bottom,
multiplier: 1.0,
constant: 0.0
)
visualEffectView.contentView.addConstraints([vibrancyTop, vibrancyRight, vibrancyBottom, vibrancyLeft])
// STATUS LABEL
let statusLabel = createStatusLabel(status, isVisualEffect: true)
vibrancyEffectView.contentView.addSubview(statusLabel)
let statusLeft = NSLayoutConstraint(
item: statusLabel,
attribute: .Left,
relatedBy: .Equal,
toItem: vibrancyEffectView.contentView,
attribute: .Left,
multiplier: 1.0,
constant: 0.0
)
let statusRight = NSLayoutConstraint(
item: statusLabel,
attribute: .Right,
relatedBy: .Equal,
toItem: vibrancyEffectView.contentView,
attribute: .Right,
multiplier: 1.0,
constant: 0.0
)
let statusBottom = NSLayoutConstraint(
item: statusLabel,
attribute: .Bottom,
relatedBy: .Equal,
toItem: vibrancyEffectView.contentView,
attribute: .Bottom,
multiplier: 1.0,
constant: -statusBottomMargin
)
vibrancyEffectView.contentView.addConstraints([statusRight, statusLeft, statusBottom])
self.statusLabel = statusLabel
}
if let state = state {
// Background View
let backgroundView = UIView(frame: CGRectZero)
backgroundView.setTranslatesAutoresizingMaskIntoConstraints(false)
backgroundView.alpha = 0.9
backgroundView.backgroundColor = state.backgroundColor()
self.addSubview(backgroundView)
let backgroundConstraints = ([.Right, .Bottom, .Left] as [NSLayoutAttribute]).map {
return NSLayoutConstraint(
item: backgroundView,
attribute: $0,
relatedBy: .Equal,
toItem: self,
attribute: $0,
multiplier: 1.0,
constant: 0.0
)
}
let topConstraint = NSLayoutConstraint(
item: backgroundView,
attribute: .Top,
relatedBy: .Equal,
toItem: self,
attribute: .Top,
multiplier: 1.0,
constant: -UIScreen.mainScreen().bounds.height
)
self.addConstraints(backgroundConstraints)
self.addConstraint(topConstraint)
self.backgroundView = backgroundView
// Status Label
let statusLabel = createStatusLabel(status, isVisualEffect: false)
self.addSubview(statusLabel)
let statusLeft = NSLayoutConstraint(
item: statusLabel,
attribute: .Left,
relatedBy: .Equal,
toItem: self,
attribute: .LeftMargin,
multiplier: 1.0,
constant: 0.0
)
let statusRight = NSLayoutConstraint(
item: statusLabel,
attribute: .Right,
relatedBy: .Equal,
toItem: self,
attribute: .RightMargin,
multiplier: 1.0,
constant: 0.0
)
let statusBottom = NSLayoutConstraint(
item: statusLabel,
attribute: .Bottom,
relatedBy: .Equal,
toItem: self,
attribute: .Bottom,
multiplier: 1.0,
constant: -statusBottomMargin
)
self.addConstraints([statusLeft, statusRight, statusBottom])
self.statusLabel = statusLabel
}
self.layoutIfNeeded()
let tapRecognizer = UITapGestureRecognizer(target: self, action: "up:")
self.addGestureRecognizer(tapRecognizer)
let panRecognizer = UIPanGestureRecognizer(target: self, action: "pan:")
self.addGestureRecognizer(panRecognizer)
}
private func createStatusLabel(status: String, isVisualEffect: Bool) -> UILabel {
let label = UILabel(frame: CGRectZero)
label.setTranslatesAutoresizingMaskIntoConstraints(false)
label.numberOfLines = 0
label.font = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline)
label.textAlignment = .Center
label.text = status
if !isVisualEffect { label.textColor = UIColor.whiteColor() }
return label
}
}
extension Drop {
func up(sender: AnyObject) {
self.up()
}
func pan(sender: AnyObject) {
let pan = sender as! UIPanGestureRecognizer
switch pan.state {
case .Began:
stopUpTimer()
startTop = topConstraint.constant
case .Changed:
let translation = pan.translationInView(Drop.window())
let top = startTop! + translation.y
if top > 0.0 {
topConstraint.constant = top * 0.2
} else {
topConstraint.constant = top
}
case .Ended:
startTop = nil
if topConstraint.constant < 0.0 {
scheduleUpTimer(0.0, interval: 0.1)
} else {
scheduleUpTimer(4.0)
topConstraint.constant = 0.0
UIView.animateWithDuration(
NSTimeInterval(0.1),
delay: NSTimeInterval(0.0),
options: .AllowUserInteraction | .CurveEaseOut,
animations: { [weak self] () -> Void in
if let s = self { s.layoutIfNeeded() }
}, completion: nil
)
}
case .Failed, .Cancelled:
startTop = nil
scheduleUpTimer(2.0)
case .Possible: break
}
}
}
extension Drop {
private class func window() -> UIWindow {
return UIApplication.sharedApplication().keyWindow!
}
private class func statusBarHeight() -> CGFloat {
return UIApplication.sharedApplication().statusBarFrame.size.height
}
}
| 534e17ff27c4e6e7902172437adf3519 | 34.136161 | 163 | 0.545899 | false | false | false | false |
SakuragiTen/DYTV | refs/heads/master | DYTV/DYTV/Classes/Home/Controllers/HomeViewController.swift | mit | 1 | //
// HomeViewController.swift
// DYTV
//
// Created by gongsheng on 16/11/13.
// Copyright © 2016年 gongsheng. All rights reserved.
//
import UIKit
import Alamofire
private let kTitleViewH : CGFloat = 40
class HomeViewController: UIViewController {
//懒加载属性
fileprivate lazy var pageTieleView : PageTitleView = {[weak self] in
let frame = CGRect(x: 0, y: kStatusBarH + kNavigationBarH, width: kScreenW, height: kTitleViewH)
let titles = ["推荐", "游戏", "娱乐", "趣玩"]
let titleView = PageTitleView(frame: frame, titles: titles)
// titleView.backgroundColor = UIColor.cyan;
titleView.delegate = self
return titleView
}()
fileprivate lazy var pageContentView : PageContentView = {[weak self] in
var childVcs = [UIViewController]()
let recommend = RecommendViewController()
recommend.view.backgroundColor = UIColor.cyan
let game = UIViewController()
game.view.backgroundColor = UIColor.red
let amuse = UIViewController()
amuse.view.backgroundColor = UIColor.blue
let funny = UIViewController()
funny.view.backgroundColor = UIColor.purple
childVcs.append(recommend)
childVcs.append(game)
childVcs.append(amuse)
childVcs.append(funny)
let contentH = kScreenH - kStatusBarH - kNavigationBarH - kTitleViewH - kTabBarH
let contentFrame = CGRect(x: 0, y: kStatusBarH + kNavigationBarH + kTitleViewH, width: kScreenW, height: contentH)
let contentView = PageContentView(frame: contentFrame, childVcs: childVcs, parentViewController: self)
contentView.delegate = self
return contentView
}()
override func viewDidLoad() {
super.viewDidLoad()
// Alamofire.request("http://capi.douyucdn.cn/api/v1/getbigDataRoom", method : .get, parameters: ["time" : Date.getCurrentTime()]).responseJSON { (response) in
// guard let result = response.result.value else {
//
// print("erro : \(response.result.error)")
// return
// }
// print("resulf = \(result) ")
//
// }
setupUI()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
// MARK: - 设置UI界面
extension HomeViewController {
fileprivate func setupUI() {
automaticallyAdjustsScrollViewInsets = false
//设置导航栏
setupNavigationBar()
//添加titleView
view.addSubview(pageTieleView)
//添加contentView
view.addSubview(pageContentView)
pageContentView.backgroundColor = UIColor.orange
}
fileprivate func setupNavigationBar() {
// navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "logo")
navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "logo", target: self, action: #selector(self.leftItemClicked))
let size = CGSize(width: 40, height: 40)
let historyItem = UIBarButtonItem(imageName: "image_my_history", highImageName: "Image_my_history_click", size: size, target: self, action: #selector(self.historyItemClicked))
let searchItem = UIBarButtonItem(imageName: "btn_search", highImageName: "btn_search_clicked", size: size, target : self, action : #selector(self.seachItemClicked))
let qrcodeItem = UIBarButtonItem(imageName: "Image_scan", highImageName: "Image_scan_click", size: size, target : self, action : #selector(self.qrcodeItemClicked))
navigationItem.rightBarButtonItems = [historyItem, searchItem, qrcodeItem]
}
@objc func leftItemClicked() {
print("左侧的按钮点击了")
}
@objc private func historyItemClicked() {
print("点击历史记录")
}
@objc func seachItemClicked() {
print("点击搜索")
}
@objc func qrcodeItemClicked() {
print("点击扫描二维码")
}
}
//Mark - 遵守PageTitleViewDelegate
extension HomeViewController : PageTitleViewDelegate {
func pageTitleView(titleView: PageTitleView, selectIndex: Int) {
pageContentView.scrollToIndex(index: selectIndex)
}
}
extension HomeViewController : PageContentViewDelegate {
func pageContentView(contentView: PageContentView, progress: CGFloat, sourceIndex: Int, targetIndex: Int) {
pageTieleView.setCurrentTitle(sourceIndex: sourceIndex, targetIndex: targetIndex, progress: progress)
}
}
| 6bba8c1d1ec0d642673716ccf3487799 | 25.772727 | 183 | 0.630306 | false | false | false | false |
voucherifyio/voucherify-ios-sdk | refs/heads/master | VoucherifySwiftSdk/Classes/Models/Customer.swift | mit | 1 | import Foundation
import ObjectMapper
public struct Customer: Mappable {
public var id: String?
public var sourceId: String?
public var name: String?
public var email: String?
public var description: String?
public var createdAt: Date?
public var metadata: Dictionary<String, AnyObject>?
public var object: String?
public init(id: String, sourceId: String?) {
self.id = id
self.sourceId = sourceId
}
public init?(map: Map) {
mapping(map: map)
}
mutating public func mapping(map: Map) {
id <- map["id"]
sourceId <- map["source_id"]
name <- map["name"]
email <- map["email"]
description <- map["description"]
createdAt <- (map["created_at"], ISO8601DateTransform())
metadata <- map["metadata"]
object <- map["object"]
}
}
extension Customer: Querable {
func asDictionary() -> Dictionary<String, Any> {
var queryItems: [String: Any] = [:]
queryItems["customer[id]"] = id
queryItems["customer[source_id]"] = sourceId
queryItems["customer[name]"] = name
queryItems["customer[email]"] = email
queryItems["customer[created_at]"] = createdAt
queryItems["customer[object]"] = object
if let metadata = metadata {
for (key, value) in metadata {
queryItems["customer[metadata][\(key)]"] = value
}
}
return queryItems.filter({ !($0.value is NSNull) })
}
}
| bcbc326218aa6317631c39891db6df0d | 27.22807 | 66 | 0.554382 | false | false | false | false |
spacedog-io/spacedog-ios-sdk | refs/heads/master | SpaceDogSDK/SDContext.swift | mit | 1 | //
// SDContext.swift
// caremen-robot
//
// Created by philippe.rolland on 13/10/2016.
// Copyright © 2016 in-tact. All rights reserved.
//
import Foundation
public class SDContext : CustomStringConvertible {
static let InstanceId = "InstanceId"
static let AccessToken = "AccessToken"
static let CredentialsId = "CredentialsId"
static let CredentialsEmail = "CredentialsEmail"
static let ExpiresIn = "ExpiresIn"
static let IssuedOn = "IssuedOn"
static let DeviceId = "DeviceId"
static let InstallationId = "InstallationId"
let instanceId: String
let appId: String
var deviceId: String?
var installationId: String?
var credentials: SDCredentials?
public init(instanceId: String, appId: String) {
self.instanceId = instanceId
self.appId = appId
}
public func setLogged(with credentials: SDCredentials) -> Void {
self.credentials = credentials
}
public func isLogged() -> Bool {
return self.credentials != nil
}
public func setLoggedOut() -> Void {
self.credentials = nil
}
public var description: String {
return "{instanceId: \(instanceId), credentials: \(credentials?.description ?? "nil"), installationId: \(installationId ?? "nil"), deviceId: \(deviceId ?? "nil")}"
}
}
| 9beac20ef5c87676f34d605e90281237 | 27.208333 | 171 | 0.653619 | false | false | false | false |
dongdongSwift/guoke | refs/heads/master | gouke/果壳/launchViewController.swift | mit | 1 | //
// launchViewController.swift
// 果壳
//
// Created by qianfeng on 2016/11/8.
// Copyright © 2016年 张冬. All rights reserved.
//
import UIKit
class launchViewController: UIViewController,NavigationProtocol {
@IBAction func btnClick(btn: UIButton) {
if btn.tag==300{
print("微信登录")
}else if btn.tag==301{
print("微博登录")
}else if btn.tag==302{
print("QQ登录")
}else if btn.tag==303{
print("豆瓣登录")
}else if btn.tag==304{
print("登录")
}else if btn.tag==305{
print("查看用户协议")
}else if btn.tag==306{
print("刷新验证码")
}else if btn.tag==307{
navigationController?.pushViewController(forgetController(), animated: true)
}
}
@IBAction func back(sender: AnyObject) {
dismissViewControllerAnimated(true, completion: nil)
}
@IBOutlet weak var accountTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var verificationCodeTextField: UITextField!
@IBOutlet weak var verificationImage: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
addTitle("登录")
}
func keyBoardDidReturn(){
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
accountTextField.resignFirstResponder()
passwordTextField.resignFirstResponder()
verificationCodeTextField.resignFirstResponder()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 2aa75bfa4880a7dfb4a08d08a9233d3b | 26.552632 | 106 | 0.622254 | false | false | false | false |
AlexRamey/mbird-iOS | refs/heads/master | Pods/Nuke/Sources/Processor.swift | mit | 1 | // The MIT License (MIT)
//
// Copyright (c) 2015-2018 Alexander Grebenyuk (github.com/kean).
import Foundation
/// Performs image processing.
public protocol Processing: Equatable {
/// Returns processed image.
func process(_ image: Image) -> Image?
}
/// Composes multiple processors.
public struct ProcessorComposition: Processing {
private let processors: [AnyProcessor]
/// Composes multiple processors.
public init(_ processors: [AnyProcessor]) {
self.processors = processors
}
/// Processes the given image by applying each processor in an order in
/// which they were added. If one of the processors fails to produce
/// an image the processing stops and `nil` is returned.
public func process(_ input: Image) -> Image? {
return processors.reduce(input) { image, processor in
return autoreleasepool { image.flatMap(processor.process) }
}
}
/// Returns true if the underlying processors are pairwise-equivalent.
public static func ==(lhs: ProcessorComposition, rhs: ProcessorComposition) -> Bool {
return lhs.processors == rhs.processors
}
}
/// Type-erased image processor.
public struct AnyProcessor: Processing {
private let _process: (Image) -> Image?
private let _processor: Any
private let _equals: (AnyProcessor) -> Bool
public init<P: Processing>(_ processor: P) {
self._process = { processor.process($0) }
self._processor = processor
self._equals = { ($0._processor as? P) == processor }
}
public func process(_ image: Image) -> Image? {
return self._process(image)
}
public static func ==(lhs: AnyProcessor, rhs: AnyProcessor) -> Bool {
return lhs._equals(rhs)
}
}
internal struct AnonymousProcessor<Key: Hashable>: Processing {
private let _key: Key
private let _closure: (Image) -> Image?
init(_ key: Key, _ closure: @escaping (Image) -> Image?) {
self._key = key; self._closure = closure
}
func process(_ image: Image) -> Image? {
return self._closure(image)
}
static func ==(lhs: AnonymousProcessor, rhs: AnonymousProcessor) -> Bool {
return lhs._key == rhs._key
}
}
#if !os(macOS)
import UIKit
/// Decompresses and (optionally) scales down input images. Maintains
/// original aspect ratio.
///
/// Decompressing compressed image formats (such as JPEG) can significantly
/// improve drawing performance as it allows a bitmap representation to be
/// created in a background rather than on the main thread.
public struct Decompressor: Processing {
/// An option for how to resize the image.
public enum ContentMode {
/// Scales the image so that it completely fills the target size.
/// Doesn't clip images.
case aspectFill
/// Scales the image so that it fits the target size.
case aspectFit
}
/// Size to pass to disable resizing.
public static let MaximumSize = CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)
private let targetSize: CGSize
private let contentMode: ContentMode
/// Initializes `Decompressor` with the given parameters.
/// - parameter targetSize: Size in pixels. `MaximumSize` by default.
/// - parameter contentMode: An option for how to resize the image
/// to the target size. `.aspectFill` by default.
public init(targetSize: CGSize = MaximumSize, contentMode: ContentMode = .aspectFill) {
self.targetSize = targetSize
self.contentMode = contentMode
}
/// Decompresses and scales the image.
public func process(_ image: Image) -> Image? {
return decompress(image, targetSize: targetSize, contentMode: contentMode)
}
/// Returns true if both have the same `targetSize` and `contentMode`.
public static func ==(lhs: Decompressor, rhs: Decompressor) -> Bool {
return lhs.targetSize == rhs.targetSize && lhs.contentMode == rhs.contentMode
}
#if !os(watchOS)
/// Returns target size in pixels for the given view. Takes main screen
/// scale into the account.
public static func targetSize(for view: UIView) -> CGSize { // in pixels
let scale = UIScreen.main.scale
let size = view.bounds.size
return CGSize(width: size.width * scale, height: size.height * scale)
}
#endif
}
private func decompress(_ image: UIImage, targetSize: CGSize, contentMode: Decompressor.ContentMode) -> UIImage {
guard let cgImage = image.cgImage else { return image }
let bitmapSize = CGSize(width: cgImage.width, height: cgImage.height)
let scaleHor = targetSize.width / bitmapSize.width
let scaleVert = targetSize.height / bitmapSize.height
let scale = contentMode == .aspectFill ? max(scaleHor, scaleVert) : min(scaleHor, scaleVert)
return decompress(image, scale: CGFloat(min(scale, 1)))
}
private func decompress(_ image: UIImage, scale: CGFloat) -> UIImage {
guard let cgImage = image.cgImage else { return image }
let size = CGSize(width: round(scale * CGFloat(cgImage.width)), height: round(scale * CGFloat(cgImage.height)))
// For more info see:
// - Quartz 2D Programming Guide
// - https://github.com/kean/Nuke/issues/35
// - https://github.com/kean/Nuke/issues/57
let alphaInfo: CGImageAlphaInfo = isOpaque(cgImage) ? .noneSkipLast : .premultipliedLast
guard let ctx = CGContext(data: nil, width: Int(size.width), height: Int(size.height), bitsPerComponent: 8, bytesPerRow: 0, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: alphaInfo.rawValue) else {
return image
}
ctx.draw(cgImage, in: CGRect(origin: CGPoint.zero, size: size))
guard let decompressed = ctx.makeImage() else { return image }
return UIImage(cgImage: decompressed, scale: image.scale, orientation: image.imageOrientation)
}
private func isOpaque(_ image: CGImage) -> Bool {
let alpha = image.alphaInfo
return alpha == .none || alpha == .noneSkipFirst || alpha == .noneSkipLast
}
#endif
| a0e4170ad85275b31fa1de14006b913f | 37.551515 | 208 | 0.647854 | false | false | false | false |
u10int/Kinetic | refs/heads/master | Pod/Classes/Event.swift | mit | 1 | //
// Event.swift
// Kinetic
//
// Created by Nicholas Shipes on 11/19/17.
//
import Foundation
public enum EventState<T> {
case active
case closed(T)
}
public final class Event<T> {
public typealias Observer = (T) -> Void
private(set) internal var state = EventState<T>.active
internal var closed: Bool {
if case .active = state {
return false
} else {
return true
}
}
private var observers = [Observer]()
private var keyedObservers = [String: Observer]()
internal func trigger(_ payload: T) {
guard closed == false else { return }
deliver(payload)
}
internal func observe(_ observer: @escaping Observer) {
guard closed == false else {
// observer(T)
return
}
observers.append(observer)
}
internal func observe(_ observer: @escaping Observer, key: String) {
guard closed == false else {
// observer(T)
return
}
keyedObservers[key] = observer
}
internal func unobserve(key: String) {
keyedObservers.removeValue(forKey: key)
}
internal func close(_ payload: T) {
guard closed == false else { return }
state = .closed(payload)
deliver(payload)
}
private func deliver(_ payload: T) {
observers.forEach { (observer) in
observer(payload)
}
keyedObservers.forEach { (key, observer) in
observer(payload)
}
}
}
| 0e74b2f6f8f2497996015a635ba5356d | 17.671429 | 69 | 0.665647 | false | false | false | false |
centrifugal/centrifuge-ios | refs/heads/develop | Example/CentrifugeiOS/ViewController.swift | mit | 2 | //
// ViewController.swift
// CentrifugeiOS
//
// Created by German Saprykin on 04/18/2016.
// Copyright (c) 2016 German Saprykin. All rights reserved.
//
import UIKit
import CentrifugeiOS
typealias MessagesCallback = (CentrifugeServerMessage) -> Void
class ViewController: UIViewController, CentrifugeChannelDelegate, CentrifugeClientDelegate {
@IBOutlet weak var nickTextField: UITextField!
@IBOutlet weak var messageTextField: UITextField!
@IBOutlet weak var tableView: UITableView!
let datasource = TableViewDataSource()
var nickName: String {
get {
if let nick = self.nickTextField.text, nick.count > 0 {
return nick
}else {
return "anonymous"
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = datasource
let timestamp = "\(Int(Date().timeIntervalSince1970))"
let token = Centrifuge.createToken(string: "\(user)\(timestamp)", key: secret)
let creds = CentrifugeCredentials(token: token, user: user, timestamp: timestamp)
let url = "wss://centrifugo.herokuapp.com/connection/websocket"
client = Centrifuge.client(url: url, creds: creds, delegate: self)
}
//MARK:- Interactions with server
var client: CentrifugeClient!
let channel = "jsfiddle-chat"
let user = "ios-swift"
let secret = "secret"
func publish(_ text: String) {
client.publish(toChannel: channel, data: ["nick" : nickName, "input" : text]) { message, error in
print("publish message: \(String(describing: message))")
}
}
//MARK: CentrifugeClientDelegate
func client(_ client: CentrifugeClient, didDisconnectWithError error: Error) {
showError(error)
}
func client(_ client: CentrifugeClient, didReceiveRefreshMessage message: CentrifugeServerMessage) {
print("didReceiveRefresh message: \(message)")
}
//MARK: CentrifugeChannelDelegate
func client(_ client: CentrifugeClient, didReceiveMessageInChannel channel: String, message: CentrifugeServerMessage) {
if let data = message.body?["data"] as? [String : AnyObject], let input = data["input"] as? String, let nick = data["nick"] as? String {
addItem(nick, subtitle: input)
}
}
func client(_ client: CentrifugeClient, didReceiveJoinInChannel channel: String, message: CentrifugeServerMessage) {
if let data = message.body?["data"] as? [String : AnyObject], let user = data["user"] as? String {
addItem(message.method.rawValue, subtitle: user)
}
}
func client(_ client: CentrifugeClient, didReceiveLeaveInChannel channel: String, message: CentrifugeServerMessage) {
if let data = message.body?["data"] as? [String : AnyObject], let user = data["user"] as? String {
addItem(message.method.rawValue, subtitle: user)
}
}
func client(_ client: CentrifugeClient, didReceiveUnsubscribeInChannel channel: String, message: CentrifugeServerMessage) {
print("didReceiveUnsubscribeInChannel \(message)" )
}
//MARK: Presentation
func addItem(_ title: String, subtitle: String) {
self.datasource.addItem(TableViewItem(title: title, subtitle: subtitle))
self.tableView.reloadData()
}
func showAlert(_ title: String, message: String) {
let vc = UIAlertController(title: title, message: message, preferredStyle: .alert)
let close = UIAlertAction(title: "Close", style: .cancel) { _ in
vc.dismiss(animated: true, completion: nil)
}
vc.addAction(close)
show(vc, sender: self)
}
func showError(_ error: Any) {
showAlert("Error", message: "\(error)")
}
func showMessage(_ message: CentrifugeServerMessage) {
showAlert("Message", message: "\(message)")
}
func showResponse(_ message: CentrifugeServerMessage?, error: Error?) {
if let msg = message {
showMessage(msg)
} else if let err = error {
showError(err)
}
}
//MARK:- Interactions with user
@IBAction func sendButtonDidPress(_ sender: AnyObject) {
if let text = messageTextField.text, text.count > 0 {
messageTextField.text = ""
publish(text)
}
}
@IBAction func actionButtonDidPress() {
let alert = UIAlertController(title: "Choose command", message: nil, preferredStyle: .actionSheet)
let cancel = UIAlertAction(title: "Cancel", style: .cancel) { _ in
alert.dismiss(animated: true, completion: nil)
}
alert.addAction(cancel)
let connect = UIAlertAction(title: "Connect", style: .default) { _ in
self.client.connect(withCompletion: self.showResponse)
}
alert.addAction(connect)
let disconnect = UIAlertAction(title: "Disconnect", style: .default) { _ in
self.client.disconnect()
}
alert.addAction(disconnect)
let ping = UIAlertAction(title: "Ping", style: .default) { _ in
self.client.ping(withCompletion: self.showResponse)
}
alert.addAction(ping)
let subscribe = UIAlertAction(title: "Subscribe to \(channel)", style: .default) { _ in
self.client.subscribe(toChannel: self.channel, delegate: self, completion: self.showResponse)
}
alert.addAction(subscribe)
let unsubscribe = UIAlertAction(title: "Unsubscribe from \(channel)", style: .default) { _ in
self.client.unsubscribe(fromChannel: self.channel, completion: self.showResponse)
}
alert.addAction(unsubscribe)
let history = UIAlertAction(title: "History \(channel)", style: .default) { _ in
self.client.history(ofChannel: self.channel, completion: self.showResponse)
}
alert.addAction(history)
let presence = UIAlertAction(title: "Presence \(channel)", style: .default) { _ in
self.client.presence(inChannel: self.channel, completion:self.showResponse)
}
alert.addAction(presence)
present(alert, animated: true, completion: nil)
}
}
| 59baeabbfc1f23ffbffb26efc7ebd2a2 | 34.788889 | 144 | 0.62108 | false | false | false | false |
SanctionCo/pilot-ios | refs/heads/master | Pods/Gallery/Sources/Utils/VideoEditor/AdvancedVideoEditor.swift | mit | 1 | import Foundation
import AVFoundation
import Photos
public class AdvancedVideoEditor: VideoEditing {
var writer: AVAssetWriter!
var videoInput: AVAssetWriterInput?
var audioInput: AVAssetWriterInput?
var reader: AVAssetReader!
var videoOutput: AVAssetReaderVideoCompositionOutput?
var audioOutput: AVAssetReaderAudioMixOutput?
var audioCompleted: Bool = false
var videoCompleted: Bool = false
let requestQueue = DispatchQueue(label: "no.hyper.Gallery.AdvancedVideoEditor.RequestQueue", qos: .background)
let finishQueue = DispatchQueue(label: "no.hyper.Gallery.AdvancedVideoEditor.FinishQueue", qos: .background)
// MARK: - Initialization
public init() {
}
// MARK: - Edit
public func edit(video: Video, completion: @escaping (_ video: Video?, _ tempPath: URL?) -> Void) {
process(video: video, completion: completion)
}
public func crop(avAsset: AVAsset, completion: @escaping (URL?) -> Void) {
guard let outputURL = EditInfo.outputURL else {
completion(nil)
return
}
guard let writer = try? AVAssetWriter(outputURL: outputURL as URL, fileType: EditInfo.file.type),
let reader = try? AVAssetReader(asset: avAsset)
else {
completion(nil)
return
}
// Config
writer.shouldOptimizeForNetworkUse = true
self.writer = writer
self.reader = reader
wire(avAsset)
// Start
writer.startWriting()
reader.startReading()
writer.startSession(atSourceTime: kCMTimeZero)
// Video
if let videoOutput = videoOutput, let videoInput = videoInput {
videoInput.requestMediaDataWhenReady(on: requestQueue) {
if !self.stream(from: videoOutput, to: videoInput) {
self.finishQueue.async {
self.videoCompleted = true
if self.audioCompleted {
self.finish(outputURL: outputURL, completion: completion)
}
}
}
}
}
// Audio
if let audioOutput = audioOutput, let audioInput = audioInput {
audioInput.requestMediaDataWhenReady(on: requestQueue) {
if !self.stream(from: audioOutput, to: audioInput) {
self.finishQueue.async {
self.audioCompleted = true
if self.videoCompleted {
self.finish(outputURL: outputURL, completion: completion)
}
}
}
}
}
}
// MARK: - Finish
fileprivate func finish(outputURL: URL, completion: @escaping (URL?) -> Void) {
if reader.status == .failed {
writer.cancelWriting()
}
guard reader.status != .cancelled
&& reader.status != .failed
&& writer.status != .cancelled
&& writer.status != .failed
else {
completion(nil)
return
}
writer.finishWriting {
switch self.writer.status {
case .completed:
completion(outputURL)
default:
completion(nil)
}
}
}
// MARK: - Helper
fileprivate func wire(_ avAsset: AVAsset) {
wireVideo(avAsset)
wireAudio(avAsset)
}
fileprivate func wireVideo(_ avAsset: AVAsset) {
let videoTracks = avAsset.tracks(withMediaType: AVMediaType.video)
if !videoTracks.isEmpty {
// Output
let videoOutput = AVAssetReaderVideoCompositionOutput(videoTracks: videoTracks, videoSettings: nil)
videoOutput.videoComposition = EditInfo.composition(avAsset)
if reader.canAdd(videoOutput) {
reader.add(videoOutput)
}
// Input
let videoInput = AVAssetWriterInput(mediaType: AVMediaType.video,
outputSettings: EditInfo.videoSettings,
sourceFormatHint: avAsset.g_videoDescription)
if writer.canAdd(videoInput) {
writer.add(videoInput)
}
self.videoInput = videoInput
self.videoOutput = videoOutput
}
}
fileprivate func wireAudio(_ avAsset: AVAsset) {
let audioTracks = avAsset.tracks(withMediaType: AVMediaType.audio)
if !audioTracks.isEmpty {
// Output
let audioOutput = AVAssetReaderAudioMixOutput(audioTracks: audioTracks, audioSettings: nil)
audioOutput.alwaysCopiesSampleData = true
if reader.canAdd(audioOutput) {
reader.add(audioOutput)
}
// Input
let audioInput = AVAssetWriterInput(mediaType: AVMediaType.audio,
outputSettings: EditInfo.audioSettings,
sourceFormatHint: avAsset.g_audioDescription)
if writer.canAdd(audioInput) {
writer.add(audioInput)
}
self.audioOutput = audioOutput
self.audioInput = audioInput
}
}
fileprivate func stream(from output: AVAssetReaderOutput, to input: AVAssetWriterInput) -> Bool {
while input.isReadyForMoreMediaData {
guard reader.status == .reading && writer.status == .writing,
let buffer = output.copyNextSampleBuffer()
else {
input.markAsFinished()
return false
}
return input.append(buffer)
}
return true
}
}
| 2976aa7b5deacfae6284b2d15722e680 | 27.088398 | 112 | 0.641031 | false | false | false | false |
johnno1962e/swift-corelibs-foundation | refs/heads/master | Foundation/NSDictionary.swift | apache-2.0 | 2 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
import CoreFoundation
import Dispatch
open class NSDictionary : NSObject, NSCopying, NSMutableCopying, NSSecureCoding, NSCoding {
private let _cfinfo = _CFInfo(typeID: CFDictionaryGetTypeID())
internal var _storage: [NSObject: AnyObject]
open var count: Int {
guard type(of: self) === NSDictionary.self || type(of: self) === NSMutableDictionary.self else {
NSRequiresConcreteImplementation()
}
return _storage.count
}
open func object(forKey aKey: Any) -> Any? {
guard type(of: self) === NSDictionary.self || type(of: self) === NSMutableDictionary.self else {
NSRequiresConcreteImplementation()
}
if let val = _storage[_SwiftValue.store(aKey)] {
return _SwiftValue.fetch(nonOptional: val)
}
return nil
}
open func keyEnumerator() -> NSEnumerator {
guard type(of: self) === NSDictionary.self || type(of: self) === NSMutableDictionary.self else {
NSRequiresConcreteImplementation()
}
return NSGeneratorEnumerator(_storage.keys.map { _SwiftValue.fetch(nonOptional: $0) }.makeIterator())
}
public override convenience init() {
self.init(objects: [], forKeys: [], count: 0)
}
public required init(objects: UnsafePointer<AnyObject>!, forKeys keys: UnsafePointer<NSObject>!, count cnt: Int) {
_storage = [NSObject : AnyObject](minimumCapacity: cnt)
for idx in 0..<cnt {
let key = keys[idx].copy()
let value = objects[idx]
_storage[key as! NSObject] = value
}
}
public required convenience init?(coder aDecoder: NSCoder) {
guard aDecoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
if type(of: aDecoder) == NSKeyedUnarchiver.self || aDecoder.containsValue(forKey: "NS.objects") {
let keys = aDecoder._decodeArrayOfObjectsForKey("NS.keys").map() { return $0 as! NSObject }
let objects = aDecoder._decodeArrayOfObjectsForKey("NS.objects")
self.init(objects: objects as! [NSObject], forKeys: keys)
} else {
var objects = [AnyObject]()
var keys = [NSObject]()
var count = 0
while let key = aDecoder.decodeObject(forKey: "NS.key.\(count)"),
let object = aDecoder.decodeObject(forKey: "NS.object.\(count)") {
keys.append(key as! NSObject)
objects.append(object as! NSObject)
count += 1
}
self.init(objects: objects, forKeys: keys)
}
}
open func encode(with aCoder: NSCoder) {
if let keyedArchiver = aCoder as? NSKeyedArchiver {
keyedArchiver._encodeArrayOfObjects(self.allKeys._nsObject, forKey:"NS.keys")
keyedArchiver._encodeArrayOfObjects(self.allValues._nsObject, forKey:"NS.objects")
} else {
NSUnimplemented()
}
}
public static var supportsSecureCoding: Bool {
return true
}
open override func copy() -> Any {
return copy(with: nil)
}
open func copy(with zone: NSZone? = nil) -> Any {
if type(of: self) === NSDictionary.self {
// return self for immutable type
return self
} else if type(of: self) === NSMutableDictionary.self {
let dictionary = NSDictionary()
dictionary._storage = self._storage
return dictionary
}
return NSDictionary(objects: self.allValues, forKeys: self.allKeys.map({ $0 as! NSObject}))
}
open override func mutableCopy() -> Any {
return mutableCopy(with: nil)
}
open func mutableCopy(with zone: NSZone? = nil) -> Any {
if type(of: self) === NSDictionary.self || type(of: self) === NSMutableDictionary.self {
// always create and return an NSMutableDictionary
let mutableDictionary = NSMutableDictionary()
mutableDictionary._storage = self._storage
return mutableDictionary
}
return NSMutableDictionary(objects: self.allValues, forKeys: self.allKeys.map { _SwiftValue.store($0) } )
}
public convenience init(object: Any, forKey key: NSCopying) {
self.init(objects: [object], forKeys: [key as! NSObject])
}
public convenience init(objects: [Any], forKeys keys: [NSObject]) {
let keyBuffer = UnsafeMutablePointer<NSObject>.allocate(capacity: keys.count)
keyBuffer.initialize(from: keys, count: keys.count)
let valueBuffer = UnsafeMutablePointer<AnyObject>.allocate(capacity: objects.count)
valueBuffer.initialize(from: objects.map { _SwiftValue.store($0) }, count: objects.count)
self.init(objects: valueBuffer, forKeys:keyBuffer, count: keys.count)
keyBuffer.deinitialize(count: keys.count)
valueBuffer.deinitialize(count: objects.count)
keyBuffer.deallocate(capacity: keys.count)
valueBuffer.deallocate(capacity: objects.count)
}
public convenience init(dictionary otherDictionary: [AnyHashable : Any]) {
self.init(objects: Array(otherDictionary.values), forKeys: otherDictionary.keys.map { _SwiftValue.store($0) })
}
open override func isEqual(_ value: Any?) -> Bool {
switch value {
case let other as Dictionary<AnyHashable, Any>:
return isEqual(to: other)
case let other as NSDictionary:
return isEqual(to: Dictionary._unconditionallyBridgeFromObjectiveC(other))
default:
return false
}
}
open override var hash: Int {
return self.count
}
open var allKeys: [Any] {
if type(of: self) === NSDictionary.self || type(of: self) === NSMutableDictionary.self {
return Array(_storage.keys)
} else {
var keys = [Any]()
let enumerator = keyEnumerator()
while let key = enumerator.nextObject() {
keys.append(key)
}
return keys
}
}
open var allValues: [Any] {
if type(of: self) === NSDictionary.self || type(of: self) === NSMutableDictionary.self {
return Array(_storage.values)
} else {
var values = [Any]()
let enumerator = keyEnumerator()
while let key = enumerator.nextObject() {
values.append(object(forKey: key)!)
}
return values
}
}
/// Alternative pseudo funnel method for fastpath fetches from dictionaries
/// - Experiment: This is a draft API currently under consideration for official import into Foundation
/// - Note: Since this API is under consideration it may be either removed or revised in the near future
open func getObjects(_ objects: inout [Any], andKeys keys: inout [Any], count: Int) {
if type(of: self) === NSDictionary.self || type(of: self) === NSMutableDictionary.self {
for (key, value) in _storage {
keys.append(_SwiftValue.fetch(nonOptional: key))
objects.append(_SwiftValue.fetch(nonOptional: value))
}
} else {
let enumerator = keyEnumerator()
while let key = enumerator.nextObject() {
let value = object(forKey: key)!
keys.append(key)
objects.append(value)
}
}
}
open subscript (key: Any) -> Any? {
return object(forKey: key)
}
open func allKeys(for anObject: Any) -> [Any] {
var matching = Array<Any>()
enumerateKeysAndObjects(options: []) { key, value, _ in
if let val = value as? AnyHashable,
let obj = anObject as? AnyHashable {
if val == obj {
matching.append(key)
}
}
}
return matching
}
/// A string that represents the contents of the dictionary, formatted as
/// a property list (read-only)
///
/// If each key in the dictionary is an NSString object, the entries are
/// listed in ascending order by key, otherwise the order in which the entries
/// are listed is undefined. This property is intended to produce readable
/// output for debugging purposes, not for serializing data. If you want to
/// store dictionary data for later retrieval, see
/// [Property List Programming Guide](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/PropertyLists/Introduction/Introduction.html#//apple_ref/doc/uid/10000048i)
/// and [Archives and Serializations Programming Guide](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Archiving/Archiving.html#//apple_ref/doc/uid/10000047i).
open override var description: String {
return description(withLocale: nil)
}
private func getDescription(of object: Any) -> String? {
switch object {
case is NSArray.Type:
return (object as! NSArray).description(withLocale: nil, indent: 1)
case is NSDecimalNumber.Type:
return (object as! NSDecimalNumber).description(withLocale: nil)
case is NSDate.Type:
return (object as! NSDate).description(with: nil)
case is NSOrderedSet.Type:
return (object as! NSOrderedSet).description(withLocale: nil)
case is NSSet.Type:
return (object as! NSSet).description(withLocale: nil)
case is NSDictionary.Type:
return (object as! NSDictionary).description(withLocale: nil)
default:
if let hashableObject = object as? Dictionary<AnyHashable, Any> {
return hashableObject._nsObject.description(withLocale: nil, indent: 1)
} else {
return nil
}
}
}
open var descriptionInStringsFileFormat: String {
var lines = [String]()
for key in self.allKeys {
let line = NSMutableString(capacity: 0)
line.append("\"")
if let descriptionByType = getDescription(of: key) {
line.append(descriptionByType)
} else {
line.append("\(key)")
}
line.append("\"")
line.append(" = ")
line.append("\"")
let value = self.object(forKey: key)!
if let descriptionByTypeValue = getDescription(of: value) {
line.append(descriptionByTypeValue)
} else {
line.append("\(value)")
}
line.append("\"")
line.append(";")
lines.append(line._bridgeToSwift())
}
return lines.joined(separator: "\n")
}
/// Returns a string object that represents the contents of the dictionary,
/// formatted as a property list.
///
/// - parameter locale: An object that specifies options used for formatting
/// each of the dictionary’s keys and values; pass `nil` if you don’t
/// want them formatted.
open func description(withLocale locale: Locale?) -> String {
return description(withLocale: locale, indent: 0)
}
/// Returns a string object that represents the contents of the dictionary,
/// formatted as a property list.
///
/// - parameter locale: An object that specifies options used for formatting
/// each of the dictionary’s keys and values; pass `nil` if you don’t
/// want them formatted.
///
/// - parameter level: Specifies a level of indentation, to make the output
/// more readable: the indentation is (4 spaces) * level.
///
/// - returns: A string object that represents the contents of the dictionary,
/// formatted as a property list.
open func description(withLocale locale: Locale?, indent level: Int) -> String {
if level > 100 { return "..." }
var lines = [String]()
let indentation = String(repeating: " ", count: level * 4)
lines.append(indentation + "{")
for key in self.allKeys {
var line = String(repeating: " ", count: (level + 1) * 4)
if key is NSArray {
line += (key as! NSArray).description(withLocale: locale, indent: level + 1)
} else if key is Date {
line += (key as! NSDate).description(with: locale)
} else if key is NSDecimalNumber {
line += (key as! NSDecimalNumber).description(withLocale: locale)
} else if key is NSDictionary {
line += (key as! NSDictionary).description(withLocale: locale, indent: level + 1)
} else if key is NSOrderedSet {
line += (key as! NSOrderedSet).description(withLocale: locale, indent: level + 1)
} else if key is NSSet {
line += (key as! NSSet).description(withLocale: locale)
} else {
line += "\(key)"
}
line += " = "
let object = self.object(forKey: key)!
if object is NSArray {
line += (object as! NSArray).description(withLocale: locale, indent: level + 1)
} else if object is Date {
line += (object as! NSDate).description(with: locale)
} else if object is NSDecimalNumber {
line += (object as! NSDecimalNumber).description(withLocale: locale)
} else if object is NSDictionary {
line += (object as! NSDictionary).description(withLocale: locale, indent: level + 1)
} else if object is NSOrderedSet {
line += (object as! NSOrderedSet).description(withLocale: locale, indent: level + 1)
} else if object is NSSet {
line += (object as! NSSet).description(withLocale: locale)
} else {
if let hashableObject = object as? Dictionary<AnyHashable, Any> {
line += hashableObject._nsObject.description(withLocale: nil, indent: level+1)
} else {
line += "\(object)"
}
}
line += ";"
lines.append(line)
}
lines.append(indentation + "}")
return lines.joined(separator: "\n")
}
open func isEqual(to otherDictionary: [AnyHashable : Any]) -> Bool {
if count != otherDictionary.count {
return false
}
for key in keyEnumerator() {
if let otherValue = otherDictionary[key as! AnyHashable] as? AnyHashable,
let value = object(forKey: key)! as? AnyHashable {
if otherValue != value {
return false
}
} else if let otherBridgeable = otherDictionary[key as! AnyHashable] as? _ObjectBridgeable,
let bridgeable = object(forKey: key)! as? _ObjectBridgeable {
if !(otherBridgeable._bridgeToAnyObject() as! NSObject).isEqual(bridgeable._bridgeToAnyObject()) {
return false
}
} else {
return false
}
}
return true
}
public struct Iterator : IteratorProtocol {
let dictionary : NSDictionary
var keyGenerator : Array<Any>.Iterator
public mutating func next() -> (key: Any, value: Any)? {
if let key = keyGenerator.next() {
return (key, dictionary.object(forKey: key)!)
} else {
return nil
}
}
init(_ dict : NSDictionary) {
self.dictionary = dict
self.keyGenerator = dict.allKeys.makeIterator()
}
}
internal struct ObjectGenerator: IteratorProtocol {
let dictionary : NSDictionary
var keyGenerator : Array<Any>.Iterator
mutating func next() -> Any? {
if let key = keyGenerator.next() {
return dictionary.object(forKey: key)!
} else {
return nil
}
}
init(_ dict : NSDictionary) {
self.dictionary = dict
self.keyGenerator = dict.allKeys.makeIterator()
}
}
open func objectEnumerator() -> NSEnumerator {
return NSGeneratorEnumerator(ObjectGenerator(self))
}
open func objects(forKeys keys: [Any], notFoundMarker marker: Any) -> [Any] {
var objects = [Any]()
for key in keys {
if let object = object(forKey: key) {
objects.append(object)
} else {
objects.append(marker)
}
}
return objects
}
open func write(toFile path: String, atomically useAuxiliaryFile: Bool) -> Bool {
return write(to: URL(fileURLWithPath: path), atomically: useAuxiliaryFile)
}
// the atomically flag is ignored if url of a type that cannot be written atomically.
open func write(to url: URL, atomically: Bool) -> Bool {
do {
let pListData = try PropertyListSerialization.data(fromPropertyList: self, format: PropertyListSerialization.PropertyListFormat.xml, options: 0)
try pListData.write(to: url, options: atomically ? .atomic : [])
return true
} catch {
return false
}
}
open func enumerateKeysAndObjects(_ block: (Any, Any, UnsafeMutablePointer<ObjCBool>) -> Swift.Void) {
enumerateKeysAndObjects(options: [], using: block)
}
open func enumerateKeysAndObjects(options opts: NSEnumerationOptions = [], using block: (Any, Any, UnsafeMutablePointer<ObjCBool>) -> Void) {
let count = self.count
var keys = [Any]()
var objects = [Any]()
var sharedStop = ObjCBool(false)
let lock = NSLock()
getObjects(&objects, andKeys: &keys, count: count)
let iteration: (Int) -> Void = withoutActuallyEscaping(block) { (closure: @escaping (Any, Any, UnsafeMutablePointer<ObjCBool>) -> Void) -> (Int) -> Void in
return { (idx) in
lock.lock()
var stop = sharedStop
lock.unlock()
if stop { return }
closure(keys[idx], objects[idx], &stop)
if stop {
lock.lock()
sharedStop = stop
lock.unlock()
return
}
}
}
if opts.contains(.concurrent) {
DispatchQueue.concurrentPerform(iterations: count, execute: iteration)
} else {
for idx in 0..<count {
iteration(idx)
}
}
}
open func keysSortedByValue(comparator cmptr: (Any, Any) -> ComparisonResult) -> [Any] {
return keysSortedByValue(options: [], usingComparator: cmptr)
}
open func keysSortedByValue(options opts: NSSortOptions = [], usingComparator cmptr: (Any, Any) -> ComparisonResult) -> [Any] {
let sorted = allKeys.sorted { lhs, rhs in
return cmptr(lhs, rhs) == .orderedSame
}
return sorted
}
open func keysOfEntries(passingTest predicate: (Any, Any, UnsafeMutablePointer<ObjCBool>) -> Bool) -> Set<AnyHashable> {
return keysOfEntries(options: [], passingTest: predicate)
}
open func keysOfEntries(options opts: NSEnumerationOptions = [], passingTest predicate: (Any, Any, UnsafeMutablePointer<ObjCBool>) -> Bool) -> Set<AnyHashable> {
var matching = Set<AnyHashable>()
enumerateKeysAndObjects(options: opts) { key, value, stop in
if predicate(key, value, stop) {
matching.insert(key as! AnyHashable)
}
}
return matching
}
override open var _cfTypeID: CFTypeID {
return CFDictionaryGetTypeID()
}
required public convenience init(dictionaryLiteral elements: (Any, Any)...) {
var keys = [NSObject]()
var values = [Any]()
for (key, value) in elements {
keys.append(_SwiftValue.store(key))
values.append(value)
}
self.init(objects: values, forKeys: keys)
}
}
extension NSDictionary : _CFBridgeable, _SwiftBridgeable {
internal var _cfObject: CFDictionary { return unsafeBitCast(self, to: CFDictionary.self) }
internal var _swiftObject: Dictionary<AnyHashable, Any> { return Dictionary._unconditionallyBridgeFromObjectiveC(self) }
}
extension NSMutableDictionary {
internal var _cfMutableObject: CFMutableDictionary { return unsafeBitCast(self, to: CFMutableDictionary.self) }
}
extension CFDictionary : _NSBridgeable, _SwiftBridgeable {
internal var _nsObject: NSDictionary { return unsafeBitCast(self, to: NSDictionary.self) }
internal var _swiftObject: [AnyHashable: Any] { return _nsObject._swiftObject }
}
extension Dictionary : _NSBridgeable, _CFBridgeable {
internal var _nsObject: NSDictionary { return _bridgeToObjectiveC() }
internal var _cfObject: CFDictionary { return _nsObject._cfObject }
}
open class NSMutableDictionary : NSDictionary {
open func removeObject(forKey aKey: Any) {
guard type(of: self) === NSDictionary.self || type(of: self) === NSMutableDictionary.self else {
NSRequiresConcreteImplementation()
}
_storage.removeValue(forKey: _SwiftValue.store(aKey))
}
/// - Note: this diverges from the darwin version that requires NSCopying (this differential preserves allowing strings and such to be used as keys)
open func setObject(_ anObject: Any, forKey aKey: AnyHashable) {
guard type(of: self) === NSDictionary.self || type(of: self) === NSMutableDictionary.self else {
NSRequiresConcreteImplementation()
}
_storage[(aKey as! NSObject)] = _SwiftValue.store(anObject)
}
public convenience required init() {
self.init(capacity: 0)
}
public convenience init(capacity numItems: Int) {
self.init(objects: [], forKeys: [], count: 0)
// It is safe to reset the storage here because we know is empty
_storage = [NSObject: AnyObject](minimumCapacity: numItems)
}
public required init(objects: UnsafePointer<AnyObject>!, forKeys keys: UnsafePointer<NSObject>!, count cnt: Int) {
super.init(objects: objects, forKeys: keys, count: cnt)
}
public convenience init?(contentsOfFile path: String) {
self.init(contentsOfURL: URL(fileURLWithPath: path))
}
public convenience init?(contentsOfURL url: URL) {
do {
guard let plistDoc = try? Data(contentsOf: url) else { return nil }
let plistDict = try PropertyListSerialization.propertyList(from: plistDoc, options: [], format: nil) as? Dictionary<AnyHashable,Any>
guard let plistDictionary = plistDict else { return nil }
self.init(dictionary: plistDictionary)
} catch {
return nil
}
}
}
extension NSMutableDictionary {
open func addEntries(from otherDictionary: [AnyHashable : Any]) {
for (key, obj) in otherDictionary {
setObject(obj, forKey: key)
}
}
open func removeAllObjects() {
if type(of: self) === NSDictionary.self || type(of: self) === NSMutableDictionary.self {
_storage.removeAll()
} else {
for key in allKeys {
removeObject(forKey: key)
}
}
}
open func removeObjects(forKeys keyArray: [Any]) {
for key in keyArray {
removeObject(forKey: key)
}
}
open func setDictionary(_ otherDictionary: [AnyHashable : Any]) {
removeAllObjects()
for (key, obj) in otherDictionary {
setObject(obj, forKey: key)
}
}
/// - Note: See setObject(_:,forKey:) for details on the differential here
public subscript (key: AnyHashable) -> Any? {
get {
return object(forKey: key)
}
set {
if let val = newValue {
setObject(val, forKey: key)
} else {
removeObject(forKey: key)
}
}
}
}
extension NSDictionary : Sequence {
public func makeIterator() -> Iterator {
return Iterator(self)
}
}
// MARK - Shared Key Sets
extension NSDictionary {
/* Use this method to create a key set to pass to +dictionaryWithSharedKeySet:.
The keys are copied from the array and must be copyable.
If the array parameter is nil or not an NSArray, an exception is thrown.
If the array of keys is empty, an empty key set is returned.
The array of keys may contain duplicates, which are ignored (it is undefined which object of each duplicate pair is used).
As for any usage of hashing, is recommended that the keys have a well-distributed implementation of -hash, and the hash codes must satisfy the hash/isEqual: invariant.
Keys with duplicate hash codes are allowed, but will cause lower performance and increase memory usage.
*/
open class func sharedKeySet(forKeys keys: [NSCopying]) -> Any { NSUnimplemented() }
}
extension NSMutableDictionary {
/* Create a mutable dictionary which is optimized for dealing with a known set of keys.
Keys that are not in the key set can still be set into the dictionary, but that usage is not optimal.
As with any dictionary, the keys must be copyable.
If keyset is nil, an exception is thrown.
If keyset is not an object returned by +sharedKeySetForKeys:, an exception is thrown.
*/
public convenience init(sharedKeySet keyset: Any) { NSUnimplemented() }
}
extension NSDictionary : ExpressibleByDictionaryLiteral { }
extension NSDictionary : CustomReflectable {
public var customMirror: Mirror { NSUnimplemented() }
}
extension NSDictionary : _StructTypeBridgeable {
public typealias _StructType = Dictionary<AnyHashable,Any>
public func _bridgeToSwift() -> _StructType {
return _StructType._unconditionallyBridgeFromObjectiveC(self)
}
}
| 4d161e33c62075a040430bc9f31b4279 | 37.597983 | 188 | 0.597603 | false | false | false | false |
grandiere/box | refs/heads/master | box/View/GridVisor/VGridVisorMenuButton.swift | mit | 1 | import UIKit
class VGridVisorMenuButton:UIButton
{
private let kAlphaNotSelected:CGFloat = 1
private let kAlphaSelected:CGFloat = 0.3
private let kAnimationDuration:TimeInterval = 0.5
init(image:UIImage)
{
super.init(frame:CGRect.zero)
clipsToBounds = true
translatesAutoresizingMaskIntoConstraints = false
setImage(
image.withRenderingMode(UIImageRenderingMode.alwaysOriginal),
for:UIControlState.normal)
setImage(
image.withRenderingMode(UIImageRenderingMode.alwaysOriginal),
for:UIControlState.highlighted)
imageView!.clipsToBounds = true
imageView!.contentMode = UIViewContentMode.center
alpha = 0
}
required init?(coder:NSCoder)
{
return nil
}
override var isSelected:Bool
{
didSet
{
hover()
}
}
override var isHighlighted:Bool
{
didSet
{
hover()
}
}
//MARK: private
private func hover()
{
if isSelected || isHighlighted
{
alpha = kAlphaSelected
}
else
{
alpha = kAlphaNotSelected
}
}
//MARK: public
func animate(show:Bool)
{
let alpha:CGFloat
if show
{
alpha = 1
isUserInteractionEnabled = true
}
else
{
alpha = 0
isUserInteractionEnabled = false
}
UIView.animate(withDuration:kAnimationDuration)
{ [weak self] in
self?.alpha = alpha
}
}
}
| b938bcac37709c060fe7c100a5b8d575 | 19.650602 | 73 | 0.528588 | false | false | false | false |
tutao/tutanota | refs/heads/master | app-ios/tutanota/Sources/Remote/IosCommonSystemFacade.swift | gpl-3.0 | 1 | import Foundation
import Combine
enum InitState {
case waitingForInit
case initReceived
}
class IosCommonSystemFacade: CommonSystemFacade {
private let viewController: ViewController
private var initialized = CurrentValueSubject<InitState, Never>(.waitingForInit)
init(viewController: ViewController) {
self.viewController = viewController
}
func initializeRemoteBridge() async throws {
self.initialized.send(.initReceived)
}
func reload(_ query: [String : String]) async throws {
self.initialized = CurrentValueSubject(.waitingForInit)
await self.viewController.loadMainPage(params: query)
}
func getLog() async throws -> String {
let entries = TUTLogger.sharedInstance().entries()
return entries.joined(separator: "\n")
}
func awaitForInit() async {
/// awaiting for the first and hopefully only void object in this publisher
/// could be simpler but .values is iOS > 15
await withCheckedContinuation { (continuation: CheckedContinuation<Void, Never>) in
// first will end the subscription after the first match so we don't need to cancel manually
// (it is anyway hard to do as .sink() is called sync right away before we get subscription)
let _ = self.initialized
.first(where: { $0 == .initReceived })
.sink { v in
continuation.resume()
}
}
}
}
| a1b3e977b2fea2fba2fd782aba48a22f | 29.866667 | 98 | 0.701224 | false | false | false | false |
yunzixun/V2ex-Swift | refs/heads/master | View/NotificationTableViewCell.swift | mit | 1 | //
// NotificationTableViewCell.swift
// V2ex-Swift
//
// Created by huangfeng on 1/29/16.
// Copyright © 2016 Fin. All rights reserved.
//
import UIKit
class NotificationTableViewCell: UITableViewCell {
/// 头像
var avatarImageView: UIImageView = {
let imageView = UIImageView()
imageView.contentMode=UIViewContentMode.scaleAspectFit
imageView.layer.cornerRadius = 3
imageView.layer.masksToBounds = true
return imageView
}()
/// 用户名
var userNameLabel: UILabel = {
let label = UILabel()
label.textColor = V2EXColor.colors.v2_TopicListUserNameColor
label.font=v2Font(14)
return label
}()
/// 日期
var dateLabel: UILabel = {
let label = UILabel()
label.textColor=V2EXColor.colors.v2_TopicListDateColor
label.font=v2Font(12)
return label
}()
/// 操作描述
var detailLabel: UILabel = {
let label = V2SpacingLabel()
label.textColor=V2EXColor.colors.v2_TopicListTitleColor
label.font=v2Font(14)
label.numberOfLines=0
label.preferredMaxLayoutWidth = SCREEN_WIDTH-24
return label
}()
/// 回复正文
var commentLabel: UILabel = {
let label = V2SpacingLabel();
label.textColor=V2EXColor.colors.v2_TopicListTitleColor
label.font=v2Font(14)
label.numberOfLines=0
label.preferredMaxLayoutWidth=SCREEN_WIDTH-24
return label
}()
/// 回复正文的背景容器
var commentPanel: UIView = {
let view = UIView()
view.layer.cornerRadius = 3
view.layer.masksToBounds = true
view.backgroundColor = V2EXColor.colors.v2_backgroundColor
return view
}()
lazy var dropUpImageView: UIImageView = {
let imageView = UIImageView()
imageView.image = UIImage.imageUsedTemplateMode("ic_arrow_drop_up")
imageView.contentMode = .scaleAspectFit
imageView.tintColor = self.commentPanel.backgroundColor
return imageView
}()
/// 整个cell元素的容器
var contentPanel:UIView = {
let view = UIView()
view.backgroundColor = V2EXColor.colors.v2_CellWhiteBackgroundColor
view.clipsToBounds = true
return view
}()
/// 回复按钮
var replyButton:UIButton = {
let button = UIButton.roundedButton()
button.setTitle(NSLocalizedString("reply"), for: UIControlState())
return button
}()
weak var itemModel:NotificationsModel?
/// 点击回复按钮,调用的事件
var replyButtonClickHandler: ((UIButton) -> Void)?
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier);
self.setup();
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func setup()->Void{
self.backgroundColor=V2EXColor.colors.v2_backgroundColor;
let selectedBackgroundView = UIView()
selectedBackgroundView.backgroundColor = V2EXColor.colors.v2_backgroundColor
self.selectedBackgroundView = selectedBackgroundView
self.contentView .addSubview(self.contentPanel);
self.contentPanel.addSubview(self.avatarImageView);
self.contentPanel.addSubview(self.userNameLabel);
self.contentPanel.addSubview(self.dateLabel);
self.contentPanel.addSubview(self.detailLabel);
self.contentPanel.addSubview(self.commentPanel);
self.contentPanel.addSubview(self.commentLabel);
self.contentPanel.addSubview(self.dropUpImageView)
self.contentPanel.addSubview(self.replyButton)
self.setupLayout()
//点击用户头像,跳转到用户主页
self.avatarImageView.isUserInteractionEnabled = true
self.userNameLabel.isUserInteractionEnabled = true
var userNameTap = UITapGestureRecognizer(target: self, action: #selector(NotificationTableViewCell.userNameTap(_:)))
self.avatarImageView.addGestureRecognizer(userNameTap)
userNameTap = UITapGestureRecognizer(target: self, action: #selector(NotificationTableViewCell.userNameTap(_:)))
self.userNameLabel.addGestureRecognizer(userNameTap)
//按钮点击事件
self.replyButton.addTarget(self, action: #selector(replyButtonClick(_:)), for: .touchUpInside)
}
fileprivate func setupLayout(){
self.avatarImageView.snp.makeConstraints{ (make) -> Void in
make.left.top.equalTo(self.contentView).offset(12);
make.width.height.equalTo(35);
}
self.userNameLabel.snp.makeConstraints{ (make) -> Void in
make.left.equalTo(self.avatarImageView.snp.right).offset(10);
make.top.equalTo(self.avatarImageView);
}
self.dateLabel.snp.makeConstraints{ (make) -> Void in
make.bottom.equalTo(self.avatarImageView);
make.left.equalTo(self.userNameLabel);
}
self.detailLabel.snp.makeConstraints{ (make) -> Void in
make.top.equalTo(self.avatarImageView.snp.bottom).offset(12);
make.left.equalTo(self.avatarImageView);
make.right.equalTo(self.contentPanel).offset(-12);
}
self.commentLabel.snp.makeConstraints{ (make) -> Void in
make.top.equalTo(self.detailLabel.snp.bottom).offset(20);
make.left.equalTo(self.contentPanel).offset(22);
make.right.equalTo(self.contentPanel).offset(-22);
}
self.commentPanel.snp.makeConstraints{ (make) -> Void in
make.top.left.equalTo(self.commentLabel).offset(-10)
make.right.bottom.equalTo(self.commentLabel).offset(10)
}
self.dropUpImageView.snp.makeConstraints{ (make) -> Void in
make.bottom.equalTo(self.commentPanel.snp.top)
make.left.equalTo(self.commentPanel).offset(25)
make.width.equalTo(10)
make.height.equalTo(5)
}
self.replyButton.snp.makeConstraints{ (make) -> Void in
make.centerY.equalTo(self.avatarImageView)
make.right.equalTo(self.contentPanel).offset(-12)
make.width.equalTo(50)
make.height.equalTo(25)
}
}
@objc func userNameTap(_ sender:UITapGestureRecognizer) {
if let _ = self.itemModel , let username = itemModel?.userName {
let memberViewController = MemberViewController()
memberViewController.username = username
V2Client.sharedInstance.centerNavigation?.pushViewController(memberViewController, animated: true)
}
}
@objc func replyButtonClick(_ sender:UIButton){
self.replyButtonClickHandler?(sender)
}
func bind(_ model: NotificationsModel){
self.itemModel = model
self.userNameLabel.text = model.userName
self.dateLabel.text = model.date
self.detailLabel.text = model.title
if let text = model.reply {
self.commentLabel.text = text
self.setCommentPanelHidden(false)
}
else {
self.setCommentPanelHidden(true)
}
if let avata = model.avata {
self.avatarImageView.kf.setImage(with: URL(string: "https:" + avata)!)
}
}
func setCommentPanelHidden(_ hidden:Bool) {
if hidden {
self.commentPanel.isHidden = true
self.dropUpImageView.isHidden = true
self.commentLabel.text = ""
self.contentPanel.snp.remakeConstraints{ (make) -> Void in
make.bottom.equalTo(self.detailLabel.snp.bottom).offset(12);
make.top.left.right.equalTo(self.contentView);
make.bottom.equalTo(self.contentView).offset(SEPARATOR_HEIGHT * -1)
}
}
else{
self.commentPanel.isHidden = false
self.dropUpImageView.isHidden = false
self.contentPanel.snp.remakeConstraints{ (make) -> Void in
make.bottom.equalTo(self.commentPanel.snp.bottom).offset(12);
make.top.left.right.equalTo(self.contentView);
make.bottom.equalTo(self.contentView).offset(SEPARATOR_HEIGHT * -1)
}
}
}
}
| e236fe5d9a4f667470e25a929aafcfc9 | 35.628319 | 124 | 0.634936 | false | false | false | false |
longsirhero/DinDinShop | refs/heads/master | DinDinShopDemo/Pods/ImageViewer/ImageViewer/Source/GalleryViewController.swift | mit | 1 | //
// GalleryViewController.swift
// ImageViewer
//
// Created by Kristian Angyal on 01/07/2016.
// Copyright © 2016 MailOnline. All rights reserved.
//
import UIKit
open class GalleryViewController: UIPageViewController, ItemControllerDelegate {
// UI
fileprivate let overlayView = BlurView()
/// A custom view on the top of the gallery with layout using default (or custom) pinning settings for header.
open var headerView: UIView?
/// A custom view at the bottom of the gallery with layout using default (or custom) pinning settings for footer.
open var footerView: UIView?
fileprivate var closeButton: UIButton? = UIButton.closeButton()
fileprivate var seeAllCloseButton: UIButton? = nil
fileprivate var thumbnailsButton: UIButton? = UIButton.thumbnailsButton()
fileprivate var deleteButton: UIButton? = UIButton.deleteButton()
fileprivate let scrubber = VideoScrubber()
fileprivate weak var initialItemController: ItemController?
// LOCAL STATE
// represents the current page index, updated when the root view of the view controller representing the page stops animating inside visible bounds and stays on screen.
public var currentIndex: Int
// Picks up the initial value from configuration, if provided. Subsequently also works as local state for the setting.
fileprivate var decorationViewsHidden = false
fileprivate var isAnimating = false
fileprivate var initialPresentationDone = false
// DATASOURCE/DELEGATE
fileprivate let itemsDelegate: GalleryItemsDelegate?
fileprivate let itemsDataSource: GalleryItemsDataSource
fileprivate let pagingDataSource: GalleryPagingDataSource
// CONFIGURATION
fileprivate var spineDividerWidth: Float = 10
fileprivate var galleryPagingMode = GalleryPagingMode.standard
fileprivate var headerLayout = HeaderLayout.center(25)
fileprivate var footerLayout = FooterLayout.center(25)
fileprivate var closeLayout = ButtonLayout.pinRight(8, 16)
fileprivate var seeAllCloseLayout = ButtonLayout.pinRight(8, 16)
fileprivate var thumbnailsLayout = ButtonLayout.pinLeft(8, 16)
fileprivate var deleteLayout = ButtonLayout.pinRight(8, 66)
fileprivate var statusBarHidden = true
fileprivate var overlayAccelerationFactor: CGFloat = 1
fileprivate var rotationDuration = 0.15
fileprivate var rotationMode = GalleryRotationMode.always
fileprivate let swipeToDismissFadeOutAccelerationFactor: CGFloat = 6
fileprivate var decorationViewsFadeDuration = 0.15
/// COMPLETION BLOCKS
/// If set, the block is executed right after the initial launch animations finish.
open var launchedCompletion: (() -> Void)?
/// If set, called every time ANY animation stops in the page controller stops and the viewer passes a page index of the page that is currently on screen
open var landedPageAtIndexCompletion: ((Int) -> Void)?
/// If set, launched after all animations finish when the close button is pressed.
open var closedCompletion: (() -> Void)?
/// If set, launched after all animations finish when the close() method is invoked via public API.
open var programmaticallyClosedCompletion: (() -> Void)?
/// If set, launched after all animations finish when the swipe-to-dismiss (applies to all directions and cases) gesture is used.
open var swipedToDismissCompletion: (() -> Void)?
@available(*, unavailable)
required public init?(coder: NSCoder) { fatalError() }
public init(startIndex: Int, itemsDataSource: GalleryItemsDataSource, itemsDelegate: GalleryItemsDelegate? = nil, displacedViewsDataSource: GalleryDisplacedViewsDataSource? = nil, configuration: GalleryConfiguration = []) {
self.currentIndex = startIndex
self.itemsDelegate = itemsDelegate
self.itemsDataSource = itemsDataSource
var continueNextVideoOnFinish: Bool = false
///Only those options relevant to the paging GalleryViewController are explicitly handled here, the rest is handled by ItemViewControllers
for item in configuration {
switch item {
case .imageDividerWidth(let width): spineDividerWidth = Float(width)
case .pagingMode(let mode): galleryPagingMode = mode
case .headerViewLayout(let layout): headerLayout = layout
case .footerViewLayout(let layout): footerLayout = layout
case .closeLayout(let layout): closeLayout = layout
case .thumbnailsLayout(let layout): thumbnailsLayout = layout
case .statusBarHidden(let hidden): statusBarHidden = hidden
case .hideDecorationViewsOnLaunch(let hidden): decorationViewsHidden = hidden
case .decorationViewsFadeDuration(let duration): decorationViewsFadeDuration = duration
case .rotationDuration(let duration): rotationDuration = duration
case .rotationMode(let mode): rotationMode = mode
case .overlayColor(let color): overlayView.overlayColor = color
case .overlayBlurStyle(let style): overlayView.blurringView.effect = UIBlurEffect(style: style)
case .overlayBlurOpacity(let opacity): overlayView.blurTargetOpacity = opacity
case .overlayColorOpacity(let opacity): overlayView.colorTargetOpacity = opacity
case .blurPresentDuration(let duration): overlayView.blurPresentDuration = duration
case .blurPresentDelay(let delay): overlayView.blurPresentDelay = delay
case .colorPresentDuration(let duration): overlayView.colorPresentDuration = duration
case .colorPresentDelay(let delay): overlayView.colorPresentDelay = delay
case .blurDismissDuration(let duration): overlayView.blurDismissDuration = duration
case .blurDismissDelay(let delay): overlayView.blurDismissDelay = delay
case .colorDismissDuration(let duration): overlayView.colorDismissDuration = duration
case .colorDismissDelay(let delay): overlayView.colorDismissDelay = delay
case .continuePlayVideoOnEnd(let enabled): continueNextVideoOnFinish = enabled
case .seeAllCloseLayout(let layout): seeAllCloseLayout = layout
case .videoControlsColor(let color): scrubber.tintColor = color
case .closeButtonMode(let buttonMode):
switch buttonMode {
case .none: closeButton = nil
case .custom(let button): closeButton = button
case .builtIn: break
}
case .seeAllCloseButtonMode(let buttonMode):
switch buttonMode {
case .none: seeAllCloseButton = nil
case .custom(let button): seeAllCloseButton = button
case .builtIn: break
}
case .thumbnailsButtonMode(let buttonMode):
switch buttonMode {
case .none: thumbnailsButton = nil
case .custom(let button): thumbnailsButton = button
case .builtIn: break
}
case .deleteButtonMode(let buttonMode):
switch buttonMode {
case .none: deleteButton = nil
case .custom(let button): deleteButton = button
case .builtIn: break
}
default: break
}
}
pagingDataSource = GalleryPagingDataSource(itemsDataSource: itemsDataSource, displacedViewsDataSource: displacedViewsDataSource, scrubber: scrubber, configuration: configuration)
super.init(transitionStyle: UIPageViewControllerTransitionStyle.scroll,
navigationOrientation: UIPageViewControllerNavigationOrientation.horizontal,
options: [UIPageViewControllerOptionInterPageSpacingKey : NSNumber(value: spineDividerWidth as Float)])
pagingDataSource.itemControllerDelegate = self
///This feels out of place, one would expect even the first presented(paged) item controller to be provided by the paging dataSource but there is nothing we can do as Apple requires the first controller to be set via this "setViewControllers" method.
let initialController = pagingDataSource.createItemController(startIndex, isInitial: true)
self.setViewControllers([initialController], direction: UIPageViewControllerNavigationDirection.forward, animated: false, completion: nil)
if let controller = initialController as? ItemController {
initialItemController = controller
}
///This less known/used presentation style option allows the contents of parent view controller presenting the gallery to "bleed through" the blurView. Otherwise we would see only black color.
self.modalPresentationStyle = .overFullScreen
self.dataSource = pagingDataSource
UIApplication.applicationWindow.windowLevel = (statusBarHidden) ? UIWindowLevelStatusBar + 1 : UIWindowLevelNormal
NotificationCenter.default.addObserver(self, selector: #selector(GalleryViewController.rotate), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
if continueNextVideoOnFinish {
NotificationCenter.default.addObserver(self, selector: #selector(didEndPlaying), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil)
}
}
deinit {
NotificationCenter.default.removeObserver(self)
}
func didEndPlaying() {
page(toIndex: currentIndex+1)
}
fileprivate func configureOverlayView() {
overlayView.bounds.size = UIScreen.main.bounds.insetBy(dx: -UIScreen.main.bounds.width / 2, dy: -UIScreen.main.bounds.height / 2).size
overlayView.center = CGPoint(x: (UIScreen.main.bounds.width / 2), y: (UIScreen.main.bounds.height / 2))
self.view.addSubview(overlayView)
self.view.sendSubview(toBack: overlayView)
}
fileprivate func configureHeaderView() {
if let header = headerView {
header.alpha = 0
self.view.addSubview(header)
}
}
fileprivate func configureFooterView() {
if let footer = footerView {
footer.alpha = 0
self.view.addSubview(footer)
}
}
fileprivate func configureCloseButton() {
if let closeButton = closeButton {
closeButton.addTarget(self, action: #selector(GalleryViewController.closeInteractively), for: .touchUpInside)
closeButton.alpha = 0
self.view.addSubview(closeButton)
}
}
fileprivate func configureThumbnailsButton() {
if let thumbnailsButton = thumbnailsButton {
thumbnailsButton.addTarget(self, action: #selector(GalleryViewController.showThumbnails), for: .touchUpInside)
thumbnailsButton.alpha = 0
self.view.addSubview(thumbnailsButton)
}
}
fileprivate func configureDeleteButton() {
if let deleteButton = deleteButton {
deleteButton.addTarget(self, action: #selector(GalleryViewController.deleteItem), for: .touchUpInside)
deleteButton.alpha = 0
self.view.addSubview(deleteButton)
}
}
fileprivate func configureScrubber() {
scrubber.alpha = 0
self.view.addSubview(scrubber)
}
open override func viewDidLoad() {
super.viewDidLoad()
configureHeaderView()
configureFooterView()
configureCloseButton()
configureThumbnailsButton()
configureDeleteButton()
configureScrubber()
self.view.clipsToBounds = false
}
open override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
guard initialPresentationDone == false else { return }
///We have to call this here (not sooner), because it adds the overlay view to the presenting controller and the presentingController property is set only at this moment in the VC lifecycle.
configureOverlayView()
///The initial presentation animations and transitions
presentInitially()
initialPresentationDone = true
}
fileprivate func presentInitially() {
isAnimating = true
///Animates decoration views to the initial state if they are set to be visible on launch. We do not need to do anything if they are set to be hidden because they are already set up as hidden by default. Unhiding them for the launch is part of chosen UX.
initialItemController?.presentItem(alongsideAnimation: { [weak self] in
self?.overlayView.present()
}, completion: { [weak self] in
if let strongSelf = self {
if strongSelf.decorationViewsHidden == false {
strongSelf.animateDecorationViews(visible: true)
}
strongSelf.isAnimating = false
strongSelf.launchedCompletion?()
}
})
}
open override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if rotationMode == .always && UIApplication.isPortraitOnly {
let transform = windowRotationTransform()
let bounds = rotationAdjustedBounds()
self.view.transform = transform
self.view.bounds = bounds
}
overlayView.frame = view.bounds.insetBy(dx: -UIScreen.main.bounds.width * 2, dy: -UIScreen.main.bounds.height * 2)
layoutButton(closeButton, layout: closeLayout)
layoutButton(thumbnailsButton, layout: thumbnailsLayout)
layoutButton(deleteButton, layout: deleteLayout)
layoutHeaderView()
layoutFooterView()
layoutScrubber()
}
fileprivate func layoutButton(_ button: UIButton?, layout: ButtonLayout) {
guard let button = button else { return }
switch layout {
case .pinRight(let marginTop, let marginRight):
button.autoresizingMask = [.flexibleBottomMargin, .flexibleLeftMargin]
button.frame.origin.x = self.view.bounds.size.width - marginRight - button.bounds.size.width
button.frame.origin.y = marginTop
case .pinLeft(let marginTop, let marginLeft):
button.autoresizingMask = [.flexibleBottomMargin, .flexibleRightMargin]
button.frame.origin.x = marginLeft
button.frame.origin.y = marginTop
}
}
fileprivate func layoutHeaderView() {
guard let header = headerView else { return }
switch headerLayout {
case .center(let marginTop):
header.autoresizingMask = [.flexibleBottomMargin, .flexibleLeftMargin, .flexibleRightMargin]
header.center = self.view.boundsCenter
header.frame.origin.y = marginTop
case .pinBoth(let marginTop, let marginLeft,let marginRight):
header.autoresizingMask = [.flexibleBottomMargin, .flexibleWidth]
header.bounds.size.width = self.view.bounds.width - marginLeft - marginRight
header.sizeToFit()
header.frame.origin = CGPoint(x: marginLeft, y: marginTop)
case .pinLeft(let marginTop, let marginLeft):
header.autoresizingMask = [.flexibleBottomMargin, .flexibleRightMargin]
header.frame.origin = CGPoint(x: marginLeft, y: marginTop)
case .pinRight(let marginTop, let marginRight):
header.autoresizingMask = [.flexibleBottomMargin, .flexibleLeftMargin]
header.frame.origin = CGPoint(x: self.view.bounds.width - marginRight - header.bounds.width, y: marginTop)
}
}
fileprivate func layoutFooterView() {
guard let footer = footerView else { return }
switch footerLayout {
case .center(let marginBottom):
footer.autoresizingMask = [.flexibleTopMargin, .flexibleLeftMargin, .flexibleRightMargin]
footer.center = self.view.boundsCenter
footer.frame.origin.y = self.view.bounds.height - footer.bounds.height - marginBottom
case .pinBoth(let marginBottom, let marginLeft,let marginRight):
footer.autoresizingMask = [.flexibleTopMargin, .flexibleWidth]
footer.frame.size.width = self.view.bounds.width - marginLeft - marginRight
footer.sizeToFit()
footer.frame.origin = CGPoint(x: marginLeft, y: self.view.bounds.height - footer.bounds.height - marginBottom)
case .pinLeft(let marginBottom, let marginLeft):
footer.autoresizingMask = [.flexibleTopMargin, .flexibleRightMargin]
footer.frame.origin = CGPoint(x: marginLeft, y: self.view.bounds.height - footer.bounds.height - marginBottom)
case .pinRight(let marginBottom, let marginRight):
footer.autoresizingMask = [.flexibleTopMargin, .flexibleLeftMargin]
footer.frame.origin = CGPoint(x: self.view.bounds.width - marginRight - footer.bounds.width, y: self.view.bounds.height - footer.bounds.height - marginBottom)
}
}
fileprivate func layoutScrubber() {
scrubber.bounds = CGRect(origin: CGPoint.zero, size: CGSize(width: self.view.bounds.width, height: 40))
scrubber.center = self.view.boundsCenter
scrubber.frame.origin.y = (footerView?.frame.origin.y ?? self.view.bounds.maxY) - scrubber.bounds.height
}
@objc fileprivate func deleteItem() {
deleteButton?.isEnabled = false
view.isUserInteractionEnabled = false
itemsDelegate?.removeGalleryItem(at: currentIndex)
removePage(atIndex: currentIndex) {
[weak self] in
self?.deleteButton?.isEnabled = true
self?.view.isUserInteractionEnabled = true
}
}
//ThumbnailsimageBlock
@objc fileprivate func showThumbnails() {
let thumbnailsController = ThumbnailsViewController(itemsDataSource: self.itemsDataSource)
if let closeButton = seeAllCloseButton {
thumbnailsController.closeButton = closeButton
thumbnailsController.closeLayout = seeAllCloseLayout
} else if let closeButton = closeButton {
let seeAllCloseButton = UIButton(frame: CGRect(origin: CGPoint.zero, size: closeButton.bounds.size))
seeAllCloseButton.setImage(closeButton.image(for: UIControlState()), for: UIControlState())
seeAllCloseButton.setImage(closeButton.image(for: .highlighted), for: .highlighted)
thumbnailsController.closeButton = seeAllCloseButton
thumbnailsController.closeLayout = closeLayout
}
thumbnailsController.onItemSelected = { [weak self] index in
self?.page(toIndex: index)
}
present(thumbnailsController, animated: true, completion: nil)
}
open func page(toIndex index: Int) {
guard currentIndex != index && index >= 0 && index < self.itemsDataSource.itemCount() else { return }
let imageViewController = self.pagingDataSource.createItemController(index)
let direction: UIPageViewControllerNavigationDirection = index > currentIndex ? .forward : .reverse
// workaround to make UIPageViewController happy
if direction == .forward {
let previousVC = self.pagingDataSource.createItemController(index - 1)
setViewControllers([previousVC], direction: direction, animated: true, completion: { finished in
DispatchQueue.main.async(execute: { [weak self] in
self?.setViewControllers([imageViewController], direction: direction, animated: false, completion: nil)
})
})
} else {
let nextVC = self.pagingDataSource.createItemController(index + 1)
setViewControllers([nextVC], direction: direction, animated: true, completion: { finished in
DispatchQueue.main.async(execute: { [weak self] in
self?.setViewControllers([imageViewController], direction: direction, animated: false, completion: nil)
})
})
}
}
func removePage(atIndex index: Int, completion: @escaping () -> Void) {
// If removing last item, go back, otherwise, go forward
let direction: UIPageViewControllerNavigationDirection = index < self.itemsDataSource.itemCount() ? .forward : .reverse
let newIndex = direction == .forward ? index : index - 1
if newIndex < 0 { close(); return }
let vc = self.pagingDataSource.createItemController(newIndex)
setViewControllers([vc], direction: direction, animated: true) { _ in completion() }
}
open func reload(atIndex index: Int) {
guard index >= 0 && index < self.itemsDataSource.itemCount() else { return }
guard let firstVC = viewControllers?.first, let itemController = firstVC as? ItemController else { return }
itemController.fetchImage()
}
// MARK: - Animations
@objc fileprivate func rotate() {
/// If the app supports rotation on global level, we don't need to rotate here manually because the rotation
/// of key Window will rotate all app's content with it via affine transform and from the perspective of the
/// gallery it is just a simple relayout. Allowing access to remaining code only makes sense if the app is
/// portrait only but we still want to support rotation inside the gallery.
guard UIApplication.isPortraitOnly else { return }
guard UIDevice.current.orientation.isFlat == false &&
isAnimating == false else { return }
isAnimating = true
UIView.animate(withDuration: rotationDuration, delay: 0, options: UIViewAnimationOptions.curveLinear, animations: { [weak self] () -> Void in
self?.view.transform = windowRotationTransform()
self?.view.bounds = rotationAdjustedBounds()
self?.view.setNeedsLayout()
self?.view.layoutIfNeeded()
})
{ [weak self] finished in
self?.isAnimating = false
}
}
/// Invoked when closed programmatically
open func close() {
closeDecorationViews(programmaticallyClosedCompletion)
}
/// Invoked when closed via close button
@objc fileprivate func closeInteractively() {
closeDecorationViews(closedCompletion)
}
fileprivate func closeDecorationViews(_ completion: (() -> Void)?) {
guard isAnimating == false else { return }
isAnimating = true
if let itemController = self.viewControllers?.first as? ItemController {
itemController.closeDecorationViews(decorationViewsFadeDuration)
}
UIView.animate(withDuration: decorationViewsFadeDuration, animations: { [weak self] in
self?.headerView?.alpha = 0.0
self?.footerView?.alpha = 0.0
self?.closeButton?.alpha = 0.0
self?.thumbnailsButton?.alpha = 0.0
self?.deleteButton?.alpha = 0.0
self?.scrubber.alpha = 0.0
}, completion: { [weak self] done in
if let strongSelf = self,
let itemController = strongSelf.viewControllers?.first as? ItemController {
itemController.dismissItem(alongsideAnimation: {
strongSelf.overlayView.dismiss()
}, completion: { [weak self] in
self?.isAnimating = true
self?.closeGallery(false, completion: completion)
})
}
})
}
func closeGallery(_ animated: Bool, completion: (() -> Void)?) {
self.overlayView.removeFromSuperview()
self.modalTransitionStyle = .crossDissolve
self.dismiss(animated: animated) {
UIApplication.applicationWindow.windowLevel = UIWindowLevelNormal
completion?()
}
}
fileprivate func animateDecorationViews(visible: Bool) {
let targetAlpha: CGFloat = (visible) ? 1 : 0
UIView.animate(withDuration: decorationViewsFadeDuration, animations: { [weak self] in
self?.headerView?.alpha = targetAlpha
self?.footerView?.alpha = targetAlpha
self?.closeButton?.alpha = targetAlpha
self?.thumbnailsButton?.alpha = targetAlpha
self?.deleteButton?.alpha = targetAlpha
if let _ = self?.viewControllers?.first as? VideoViewController {
UIView.animate(withDuration: 0.3, animations: { [weak self] in
self?.scrubber.alpha = targetAlpha
})
}
})
}
public func itemControllerWillAppear(_ controller: ItemController) {
if let videoController = controller as? VideoViewController {
scrubber.player = videoController.player
}
}
public func itemControllerWillDisappear(_ controller: ItemController) {
if let _ = controller as? VideoViewController {
scrubber.player = nil
UIView.animate(withDuration: 0.3, animations: { [weak self] in
self?.scrubber.alpha = 0
})
}
}
public func itemControllerDidAppear(_ controller: ItemController) {
self.currentIndex = controller.index
self.landedPageAtIndexCompletion?(self.currentIndex)
self.headerView?.sizeToFit()
self.footerView?.sizeToFit()
if let videoController = controller as? VideoViewController {
scrubber.player = videoController.player
if scrubber.alpha == 0 && decorationViewsHidden == false {
UIView.animate(withDuration: 0.3, animations: { [weak self] in
self?.scrubber.alpha = 1
})
}
}
}
open func itemControllerDidSingleTap(_ controller: ItemController) {
self.decorationViewsHidden.flip()
animateDecorationViews(visible: !self.decorationViewsHidden)
}
public func itemController(_ controller: ItemController, didSwipeToDismissWithDistanceToEdge distance: CGFloat) {
if decorationViewsHidden == false {
let alpha = 1 - distance * swipeToDismissFadeOutAccelerationFactor
closeButton?.alpha = alpha
thumbnailsButton?.alpha = alpha
deleteButton?.alpha = alpha
headerView?.alpha = alpha
footerView?.alpha = alpha
if controller is VideoViewController {
scrubber.alpha = alpha
}
}
self.overlayView.blurringView.alpha = 1 - distance
self.overlayView.colorView.alpha = 1 - distance
}
public func itemControllerDidFinishSwipeToDismissSuccessfully() {
self.swipedToDismissCompletion?()
self.overlayView.removeFromSuperview()
self.dismiss(animated: false, completion: nil)
}
}
| 5a218c46994593e17436fbd050b0fc2c | 39.392387 | 262 | 0.651008 | false | false | false | false |
KennethTsang/GrowingTextView | refs/heads/master | Example/GrowingTextView/Example2.swift | mit | 1 | //
// Example2.swift
// GrowingTextView
//
// Created by Tsang Kenneth on 16/3/2017.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import UIKit
import GrowingTextView
class Example2: UIViewController {
@IBOutlet weak var inputToolbar: UIView!
@IBOutlet weak var textView: GrowingTextView!
@IBOutlet weak var textViewBottomConstraint: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
// *** Customize GrowingTextView ***
textView.layer.cornerRadius = 4.0
// *** Listen to keyboard show / hide ***
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChangeFrame), name: UIResponder.keyboardWillChangeFrameNotification, object: nil)
// *** Hide keyboard when tapping outside ***
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(tapGestureHandler))
view.addGestureRecognizer(tapGesture)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
@objc private func keyboardWillChangeFrame(_ notification: Notification) {
if let endFrame = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
var keyboardHeight = UIScreen.main.bounds.height - endFrame.origin.y
if #available(iOS 11, *) {
if keyboardHeight > 0 {
keyboardHeight = keyboardHeight - view.safeAreaInsets.bottom
}
}
textViewBottomConstraint.constant = keyboardHeight + 8
view.layoutIfNeeded()
}
}
@objc func tapGestureHandler() {
view.endEditing(true)
}
}
extension Example2: GrowingTextViewDelegate {
// *** Call layoutIfNeeded on superview for animation when changing height ***
func textViewDidChangeHeight(_ textView: GrowingTextView, height: CGFloat) {
UIView.animate(withDuration: 0.3, delay: 0.0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.7, options: [.curveLinear], animations: { () -> Void in
self.view.layoutIfNeeded()
}, completion: nil)
}
}
| be3974f3429217154b0baa03459eceff | 33.460317 | 166 | 0.663749 | false | false | false | false |
youngsoft/TangramKit | refs/heads/master | TangramKitDemo/IntegratedDemo/AllTestModel&View/AllTest1TableViewCell.swift | mit | 1 | //
// AllTest1TableViewCell.swift
// TangramKit
//
// Created by apple on 16/8/23.
// Copyright © 2016年 youngsoft. All rights reserved.
//
import UIKit
protocol AllTest1Cell {
var rootLayout:TGBaseLayout!{get}
func setModel(model: AllTest1DataModel, isImageMessageHidden: Bool)
}
class AllTest1TableViewCell: UITableViewCell,AllTest1Cell {
//对于需要动态评估高度的UITableViewCell来说可以把布局视图暴露出来。用于高度评估和边界线处理。以及事件处理的设置。
fileprivate(set) var rootLayout:TGBaseLayout!
weak var headImageView:UIImageView!
weak var nickNameLabel:UILabel!
weak var textMessageLabel:UILabel!
weak var imageMessageImageView:UIImageView!
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?)
{
super.init(style: style, reuseIdentifier: reuseIdentifier)
/**
* 您可以尝试用不同的布局来实现相同的功能。
*/
self.createLinearRootLayout()
// self.createRelativeRootLayout()
// self.createFloatRootLayout()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder:aDecoder)
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
//iOS8以后您可以重载这个方法来动态的评估cell的高度,Autolayout内部是通过这个方法来评估高度的,因此如果用TangramKit实现的话就不需要调用基类的方法,而是调用根布局视图的sizeThatFits来评估获取动态的高度。
override func systemLayoutSizeFitting(_ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority, verticalFittingPriority: UILayoutPriority) -> CGSize
{
/*
通过布局视图的sizeThatFits方法能够评估出UITableViewCell的动态高度。sizeThatFits并不会进行布局而只是评估布局的尺寸。
因为cell的高度是自适应的,因此这里通过调用高度为wrap的布局视图的sizeThatFits来获取真实的高度。
*/
if #available(iOS 11.0, *) {
//如果你的界面要支持横屏的话,因为iPhoneX的横屏左右有44的安全区域,所以这里要减去左右的安全区域的值,来作为布局宽度尺寸的评估值。
//如果您的界面不需要支持横屏,或者延伸到安全区域外则不需要做这个特殊处理,而直接使用else部分的代码即可。
return self.rootLayout.sizeThatFits(CGSize(width:targetSize.width - self.safeAreaInsets.left - self.safeAreaInsets.right, height:targetSize.height))
} else {
// Fallback on earlier versions
return self.rootLayout.sizeThatFits(targetSize) //如果使用系统自带的分割线,请记得将返回的高度height+1
}
}
func setModel(model: AllTest1DataModel, isImageMessageHidden: Bool)
{
self.headImageView.image = UIImage(named: model.headImage)
self.headImageView.sizeToFit()
self.nickNameLabel.text = model.nickName
self.nickNameLabel.sizeToFit()
self.textMessageLabel.text = model.textMessage
if model.imageMessage.isEmpty
{
self.imageMessageImageView.tg_visibility = .gone
}
else
{
self.imageMessageImageView.image = UIImage(named: model.imageMessage)
self.imageMessageImageView.sizeToFit()
if isImageMessageHidden
{
self.imageMessageImageView.tg_visibility = .gone
}
else
{
self.imageMessageImageView.tg_visibility = .visible
}
}
}
}
//MARK: Layout Construction
extension AllTest1TableViewCell
{
//用线性布局来实现UI界面
func createLinearRootLayout()
{
/*
在UITableViewCell中使用TGLayout中的布局时请将布局视图作为contentView的子视图。如果我们的UITableViewCell的高度是动态的,请务必在将布局视图添加到contentView之前进行如下设置:
self.rootLayout.tg_width.equal(.fill)
self.rootLayout.tg_height.equal(.wrap)
*/
self.rootLayout = TGLinearLayout(.horz)
self.rootLayout.tg_topPadding = 5
self.rootLayout.tg_bottomPadding = 5
self.rootLayout.tg_width.equal(.fill)
self.rootLayout.tg_height.equal(.wrap)
self.rootLayout.tg_cacheEstimatedRect = true //这个属性只局限于在UITableViewCell中使用,用来优化tableviewcell的高度自适应的性能,其他地方请不要使用!!!
self.contentView.addSubview(self.rootLayout)
//如果您将布局视图作为子视图添加到UITableViewCell本身,并且同时设置了布局视图的宽度等于父布局的情况下,那么有可能最终展示的宽度会不正确。经过试验是因为对UITableViewCell本身的KVO监控所得到的新老尺寸的问题导致的这应该是iOS的一个BUG。所以这里建议最好是把布局视图添加到UITableViewCell的子视图contentView里面去。
/*
用线性布局实现时,整体用一个水平线性布局:左边是头像,右边是一个垂直的线性布局。垂直线性布局依次加入昵称、文本消息、图片消息。
*/
let headImageView = UIImageView()
self.rootLayout.addSubview(headImageView)
self.headImageView = headImageView
let messageLayout = TGLinearLayout(.vert)
messageLayout.tg_width.equal(.fill) //等价于tg_width.equal(100%)
messageLayout.tg_height.equal(.wrap)
messageLayout.tg_leading.equal(5)
messageLayout.tg_vspace = 5 //前面4行代码描述的是垂直布局占用除头像外的所有宽度,并和头像保持5个点的间距。
self.rootLayout.addSubview(messageLayout)
let nickNameLabel = UILabel()
nickNameLabel.textColor = CFTool.color(3)
nickNameLabel.font = CFTool.font(17)
messageLayout.addSubview(nickNameLabel)
self.nickNameLabel = nickNameLabel
let textMessageLabel = UILabel()
textMessageLabel.font = CFTool.font(15)
textMessageLabel.textColor = CFTool.color(4)
textMessageLabel.tg_width.equal(.fill)
textMessageLabel.tg_height.equal(.wrap) //高度为包裹,也就是动态高度。
messageLayout.addSubview(textMessageLabel)
self.textMessageLabel = textMessageLabel
let imageMessageImageView = UIImageView()
imageMessageImageView.tg_centerX.equal(0) //图片视图在父布局视图中水平居中。
messageLayout.addSubview(imageMessageImageView)
self.imageMessageImageView = imageMessageImageView
}
//用相对布局来实现UI界面
func createRelativeRootLayout() {
/*
在UITableViewCell中使用TGLayout中的布局时请将布局视图作为contentView的子视图。如果我们的UITableViewCell的高度是动态的,请务必在将布局视图添加到contentView之前进行如下设置:
self.rootLayout.tg_width.equal(.fill)
self.rootLayout.tg_height.equal(.wrap)
*/
self.rootLayout = TGRelativeLayout()
self.rootLayout.tg_topPadding = 5
self.rootLayout.tg_bottomPadding = 5
self.rootLayout.tg_width.equal(.fill)
self.rootLayout.tg_height.equal(.wrap)
self.rootLayout.tg_cacheEstimatedRect = true //这个属性只局限于在UITableViewCell中使用,用来优化tableviewcell的高度自适应的性能,其他地方请不要使用!!!
self.contentView.addSubview(self.rootLayout)
/*
用相对布局实现时,左边是头像视图,昵称文本在头像视图的右边,文本消息在昵称文本的下面,图片消息在文本消息的下面。
*/
let headImageView = UIImageView()
rootLayout.addSubview(headImageView)
self.headImageView = headImageView
let nickNameLabel = UILabel()
nickNameLabel.textColor = CFTool.color(3)
nickNameLabel.font = CFTool.font(17)
nickNameLabel.tg_leading.equal(self.headImageView.tg_trailing, offset:5) //昵称文本的左边在头像视图的右边并偏移5个点。
rootLayout.addSubview(nickNameLabel)
self.nickNameLabel = nickNameLabel
//昵称文本的左边在头像视图的右边并偏移5个点。
let textMessageLabel = UILabel()
textMessageLabel.font = CFTool.font(15)
textMessageLabel.textColor = CFTool.color(4)
textMessageLabel.tg_leading.equal(self.headImageView.tg_trailing, offset:5) //文本消息的左边在头像视图的右边并偏移5个点。
textMessageLabel.tg_trailing.equal(rootLayout.tg_trailing) //文本消息的右边和父布局的右边对齐。上面2行代码也同时确定了文本消息的宽度。
textMessageLabel.tg_top.equal(self.nickNameLabel.tg_bottom,offset:5) //文本消息的顶部在昵称文本的底部并偏移5个点
textMessageLabel.tg_height.equal(.wrap)
rootLayout.addSubview(textMessageLabel)
self.textMessageLabel = textMessageLabel
let imageMessageImageView = UIImageView()
imageMessageImageView.tg_centerX.equal(5) //图片消息的水平中心点等于父布局的水平中心点并偏移5个点的位置,这里要偏移5的原因是头像和消息之间需要5个点的间距。
imageMessageImageView.tg_top.equal(self.textMessageLabel.tg_bottom, offset:5) //图片消息的顶部在文本消息的底部并偏移5个点。
rootLayout.addSubview(imageMessageImageView)
self.imageMessageImageView = imageMessageImageView
}
//用浮动布局来实现UI界面
func createFloatRootLayout()
{
/*
在UITableViewCell中使用TGLayout中的布局时请将布局视图作为contentView的子视图。如果我们的UITableViewCell的高度是动态的,请务必在将布局视图添加到contentView之前进行如下设置:
self.rootLayout.tg_width.equal(.fill)
self.rootLayout.tg_height.equal(.wrap)
*/
self.rootLayout = TGFloatLayout(.vert)
self.rootLayout.tg_topPadding = 5
self.rootLayout.tg_bottomPadding = 5
self.rootLayout.tg_width.equal(.fill)
self.rootLayout.tg_height.equal(.wrap)
self.rootLayout.tg_cacheEstimatedRect = true //这个属性只局限于在UITableViewCell中使用,用来优化tableviewcell的高度自适应的性能,其他地方请不要使用!!!
self.contentView.addSubview(self.rootLayout)
/*
用浮动布局实现时,头像视图浮动到最左边,昵称文本跟在头像视图后面并占用剩余宽度,文本消息也跟在头像视图后面并占用剩余宽度,图片消息不浮动占据所有宽度。
要想了解浮动布局的原理,请参考文章:http://www.jianshu.com/p/0c075f2fdab2 中的介绍。
*/
let headImageView = UIImageView()
headImageView.tg_trailing.equal(5) //右边保留出5个点的视图间距。
rootLayout.addSubview(headImageView)
self.headImageView = headImageView
let nickNameLabel = UILabel()
nickNameLabel.textColor = CFTool.color(3)
nickNameLabel.font = CFTool.font(17)
nickNameLabel.tg_bottom.equal(5) //下边保留出5个点的视图间距。
nickNameLabel.tg_width.equal(.fill) //占用剩余宽度。
rootLayout.addSubview(nickNameLabel)
self.nickNameLabel = nickNameLabel
let textMessageLabel = UILabel()
textMessageLabel.font = CFTool.font(15)
textMessageLabel.textColor = CFTool.color(4)
textMessageLabel.tg_width.equal(.fill) //占用剩余宽度。
textMessageLabel.tg_height.equal(.wrap) //高度包裹
rootLayout.addSubview(textMessageLabel)
self.textMessageLabel = textMessageLabel
let imageMessageImageView = UIImageView()
imageMessageImageView.tg_top.equal(5)
imageMessageImageView.tg_reverseFloat = true //反向浮动
imageMessageImageView.tg_width.equal(.fill) //占用剩余空间
imageMessageImageView.contentMode = .center
rootLayout.addSubview(imageMessageImageView)
self.imageMessageImageView = imageMessageImageView
}
}
| 50e373b2e7ab6a721d584a48cccddba6 | 37.59176 | 195 | 0.683424 | false | false | false | false |
linhaosunny/smallGifts | refs/heads/master | 小礼品/小礼品/Classes/Module/Me/Chat/ChatBar/KeyBoard/Emoji/EmojiGroupControlCell.swift | mit | 1 | //
// EmojiGroupControlCell.swift
// 小礼品
//
// Created by 李莎鑫 on 2017/5/12.
// Copyright © 2017年 李莎鑫. All rights reserved.
//
import UIKit
import SnapKit
class EmojiGroupControlCell: UICollectionViewCell {
//MARK: 属性
var viewModel:EmojiGroupControlCellViewModel? {
didSet{
backView.image = viewModel?.backViewImage
imageView.image = viewModel?.imageViewImage
isbackViewHide = viewModel!.backViewHide
leftLine.backgroundColor = viewModel?.lineColor
rightLine.backgroundColor = viewModel?.lineColor
backView.isHidden = isbackViewHide
}
}
var isbackViewHide:Bool = false {
didSet{
backView.isHidden = isbackViewHide
}
}
//MARK: 懒加载
var backView:UIImageView = { () -> UIImageView in
let view = UIImageView()
view.contentMode = .scaleAspectFill
return view
}()
var imageView:UIImageView = { () -> UIImageView in
let view = UIImageView()
return view
}()
var leftLine:UIView = { () -> UIView in
let view = UIView()
view.backgroundColor = UIColor.lightGray
return view
}()
var rightLine:UIView = { () -> UIView in
let view = UIView()
view.backgroundColor = UIColor.lightGray
return view
}()
//MARK: 构造方法
override init(frame: CGRect) {
super.init(frame: frame)
setupEmojiGroupControlCell()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
setupEmojiGroupControlCellSubView()
}
//MARK: 私有方法
private func setupEmojiGroupControlCell() {
addSubview(backView)
addSubview(imageView)
addSubview(leftLine)
addSubview(rightLine)
}
private func setupEmojiGroupControlCellSubView() {
backView.snp.makeConstraints { (make) in
make.top.bottom.equalToSuperview()
make.left.equalTo(leftLine.snp.right)
make.right.equalTo(rightLine.snp.left)
}
leftLine.snp.makeConstraints { (make) in
make.left.equalToSuperview()
make.width.equalTo(margin*0.1)
make.top.equalToSuperview().offset(margin*0.3)
make.bottom.equalToSuperview().offset(-margin*0.3)
}
imageView.snp.makeConstraints { (make) in
make.left.equalTo(leftLine.snp.right)
make.top.bottom.equalTo(leftLine)
make.right.equalTo(rightLine.snp.left)
}
rightLine.snp.makeConstraints { (make) in
make.top.bottom.width.equalTo(leftLine)
make.right.equalToSuperview()
}
}
}
| f47927ae507e624c15a527e0eadd603d | 26.708738 | 62 | 0.597758 | false | false | false | false |
SwiftGen/SwiftGen | refs/heads/stable | Sources/SwiftGenKit/Parsers/Colors/ColorsTXTFileParser.swift | mit | 1 | //
// SwiftGenKit
// Copyright © 2022 SwiftGen
// MIT Licence
//
import Foundation
import PathKit
extension Colors {
final class TextFileParser: ColorsFileTypeParser {
private var colors = [String: UInt32]()
init(options: ParserOptionValues) throws {
}
static let extensions = ["txt"]
// Text file expected to be:
// - One line per entry
// - Each line composed by the color name, then ":", then the color hex representation
// - Extra spaces will be skipped
func parseFile(at path: Path) throws -> Palette {
do {
let dict = try keyValueDict(from: path, withSeperator: ":")
for key in dict.keys {
try addColor(named: key, value: colorValue(forKey: key, onDict: dict), path: path)
}
} catch let error as ParserError {
throw error
} catch let error {
throw ParserError.invalidFile(path: path, reason: error.localizedDescription)
}
let name = path.lastComponentWithoutExtension
return Palette(name: name, colors: colors)
}
private func addColor(named name: String, value: String, path: Path) throws {
try addColor(named: name, value: Colors.parse(hex: value, key: name, path: path))
}
private func addColor(named name: String, value: UInt32) {
colors[name] = value
}
private func keyValueDict(from path: Path, withSeperator seperator: String = ":") throws -> [String: String] {
let content = try path.read(.utf8)
let lines = content.components(separatedBy: CharacterSet.newlines)
var dict: [String: String] = [:]
for line in lines {
let scanner = Scanner(string: line)
scanner.charactersToBeSkipped = .whitespaces
var key: NSString?
var value: NSString?
guard scanner.scanUpTo(seperator, into: &key) &&
scanner.scanString(seperator, into: nil) &&
scanner.scanUpToCharacters(from: .whitespaces, into: &value) else {
continue
}
if let key: String = key?.trimmingCharacters(in: .whitespaces),
let value: String = value?.trimmingCharacters(in: .whitespaces) {
dict[key] = value
}
}
return dict
}
private func colorValue(forKey key: String, onDict dict: [String: String]) -> String {
var currentKey = key
var stringValue: String = ""
while let value = dict[currentKey]?.trimmingCharacters(in: CharacterSet.whitespaces) {
currentKey = value
stringValue = value
}
return stringValue
}
}
}
| f228f1040727f994f0f687ec7f8a0e04 | 29.583333 | 114 | 0.630596 | false | false | false | false |
WalterCreazyBear/Swifter30 | refs/heads/master | ArtList/ArtList/WorksViewController.swift | mit | 1 | //
// WorksViewController.swift
// ArtList
//
// Created by Bear on 2017/6/26.
// Copyright © 2017年 Bear. All rights reserved.
//
import UIKit
class WorksViewController: UIViewController {
var model:Artist!
let cellID = "CELLID"
lazy var table:UITableView = {
let table = UITableView.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height))
table.backgroundColor = UIColor.white
table.delegate = self
table.dataSource = self
table.register(WorkDetailTableViewCell.self, forCellReuseIdentifier: self.cellID)
return table
}()
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
init(model:Artist) {
self.model = model
super.init(nibName: nil, bundle: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
title = model.name
view.backgroundColor = UIColor.white
self.view.addSubview(self.table)
}
}
extension WorksViewController:UITableViewDelegate,UITableViewDataSource
{
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.model.works.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath)
let work = model.works[indexPath.row]
cell.selectionStyle = .none
if cell.isKind(of: WorkDetailTableViewCell.self)
{
(cell as! WorkDetailTableViewCell).bindData(model: work)
}
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let work = model.works[indexPath.row]
if work.isExpanded
{
return 380
}
else{
return 250
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
var work = model.works[indexPath.row]
work.isExpanded = !work.isExpanded
model.works[indexPath.row] = work
(tableView.cellForRow(at: indexPath) as! WorkDetailTableViewCell).bindData(model: work)
tableView.beginUpdates()
tableView.endUpdates()
// tableView.reloadData()
tableView.scrollToRow(at: indexPath, at: .top, animated: true)
}
}
| 116ee8e36f9d317b2c87179031f71674 | 28.181818 | 140 | 0.636682 | false | false | false | false |
daniel-barros/TV-Calendar | refs/heads/master | TV Calendar/TrackingLimitGuard.swift | gpl-3.0 | 1 | //
// TrackingLimitGuard.swift
// TV Calendar
//
// Created by Daniel Barros López on 3/14/17.
// Copyright © 2017 Daniel Barros. All rights reserved.
//
import ExtendedFoundation
import RealmSwift
fileprivate let userTrackingLimitKey = "userTrackingLimitKey"
/// Knows about limits on the number of shows the user can track and how to remove them via in-app purchases.
/// There's a common limit and a user-specific limit which will be used instead for users who exceeded the limit before it was applied on previous app versions.
struct TrackingLimitGuard {
init(trackedShows: Results<Show>, iapManager: InAppPurchaseManager = .shared) {
self.trackedShows = trackedShows
self.iapManager = iapManager
setUserTrackingLimit()
}
fileprivate let trackedShows: Results<Show>
fileprivate let iapManager: InAppPurchaseManager
/// True unless the corresponding in-app purchase has being acquired.
var hasTrackingLimit: Bool {
return !iapManager.isProductPurchased(InAppPurchaseManager.ProductIdentifiers.unlockUnlimitedTracking)
}
/// The maximum number of shows a user is allowed to track if the tracking limit applies.
static var trackingLimit: Int {
return userTrackingLimit ?? commonTrackingLimit
}
/// `true` if user has a tracking limit and it has being reached.
var hasReachedTrackingLimit: Bool {
return hasTrackingLimit && trackedShows.count >= TrackingLimitGuard.trackingLimit
}
func buyTrackingLimitRemoval(firstTry: Bool = true, completion: @escaping (BooleanResult<InAppPurchaseManager.IAPError>) -> ()) {
// Get iap product
guard let product = iapManager.unlockUnlimitedTrackingProduct else {
if firstTry {
// Retrieve products and try again
iapManager.findProducts(completion: { result in
self.buyTrackingLimitRemoval(firstTry: false, completion: completion)
})
} else {
completion(.failure(.productUnavailable))
}
return
}
// Purchase it
iapManager.purchase(product, completion: completion)
}
func restoreTrackingLimitRemoval(completion: @escaping (BooleanResult<InAppPurchaseManager.IAPError>) -> ()) {
iapManager.restorePurchases(completion: completion)
}
static var priceForRemovingTrackingLimit: (Double, Locale)? {
if let product = InAppPurchaseManager.shared.unlockUnlimitedTrackingProduct {
return (product.price.doubleValue, product.priceLocale)
}
return nil
}
static fileprivate let commonTrackingLimit = 6
static fileprivate(set) var userTrackingLimit: Int? {
get { return nil }
set { }
// get { return UserDefaults.standard.value(forKey: userTrackingLimitKey) as? Int }
// set { return UserDefaults.standard.set(newValue, forKey: userTrackingLimitKey) }
}
}
// MARK: Helpers
fileprivate extension TrackingLimitGuard {
/// Sets the current number of tracked shows as a user-specific tracking limit for early adopters.
mutating func setUserTrackingLimit() {
if trackedShows.count > TrackingLimitGuard.commonTrackingLimit && TrackingLimitGuard.userTrackingLimit == nil {
TrackingLimitGuard.userTrackingLimit = trackedShows.count
}
}
}
| ac9c9ea8b85cae04c0c47ef82482349b | 37.588889 | 160 | 0.68068 | false | false | false | false |
tjw/swift | refs/heads/master | stdlib/public/core/Collection.swift | apache-2.0 | 1 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// A type that provides subscript access to its elements, with forward
/// index traversal.
///
/// In most cases, it's best to ignore this protocol and use the `Collection`
/// protocol instead, because it has a more complete interface.
@available(*, deprecated, message: "it will be removed in Swift 4.0. Please use 'Collection' instead")
public typealias IndexableBase = Collection
/// A type that provides subscript access to its elements, with forward index
/// traversal.
///
/// In most cases, it's best to ignore this protocol and use the `Collection`
/// protocol instead, because it has a more complete interface.
@available(*, deprecated, message: "it will be removed in Swift 4.0. Please use 'Collection' instead")
public typealias Indexable = Collection
/// A type that iterates over a collection using its indices.
///
/// The `IndexingIterator` type is the default iterator for any collection that
/// doesn't declare its own. It acts as an iterator by using a collection's
/// indices to step over each value in the collection. Most collections in the
/// standard library use `IndexingIterator` as their iterator.
///
/// By default, any custom collection type you create will inherit a
/// `makeIterator()` method that returns an `IndexingIterator` instance,
/// making it unnecessary to declare your own. When creating a custom
/// collection type, add the minimal requirements of the `Collection`
/// protocol: starting and ending indices and a subscript for accessing
/// elements. With those elements defined, the inherited `makeIterator()`
/// method satisfies the requirements of the `Sequence` protocol.
///
/// Here's an example of a type that declares the minimal requirements for a
/// collection. The `CollectionOfTwo` structure is a fixed-size collection
/// that always holds two elements of a specific type.
///
/// struct CollectionOfTwo<Element>: Collection {
/// let elements: (Element, Element)
///
/// init(_ first: Element, _ second: Element) {
/// self.elements = (first, second)
/// }
///
/// var startIndex: Int { return 0 }
/// var endIndex: Int { return 2 }
///
/// subscript(index: Int) -> Element {
/// switch index {
/// case 0: return elements.0
/// case 1: return elements.1
/// default: fatalError("Index out of bounds.")
/// }
/// }
///
/// func index(after i: Int) -> Int {
/// precondition(i < endIndex, "Can't advance beyond endIndex")
/// return i + 1
/// }
/// }
///
/// Because `CollectionOfTwo` doesn't define its own `makeIterator()`
/// method or `Iterator` associated type, it uses the default iterator type,
/// `IndexingIterator`. This example shows how a `CollectionOfTwo` instance
/// can be created holding the values of a point, and then iterated over
/// using a `for`-`in` loop.
///
/// let point = CollectionOfTwo(15.0, 20.0)
/// for element in point {
/// print(element)
/// }
/// // Prints "15.0"
/// // Prints "20.0"
@_fixed_layout
public struct IndexingIterator<Elements : Collection> {
@usableFromInline
internal let _elements: Elements
@usableFromInline
internal var _position: Elements.Index
@inlinable
@inline(__always)
/// Creates an iterator over the given collection.
public /// @testable
init(_elements: Elements) {
self._elements = _elements
self._position = _elements.startIndex
}
@inlinable
@inline(__always)
/// Creates an iterator over the given collection.
public /// @testable
init(_elements: Elements, _position: Elements.Index) {
self._elements = _elements
self._position = _position
}
}
extension IndexingIterator: IteratorProtocol, Sequence {
public typealias Element = Elements.Element
public typealias Iterator = IndexingIterator<Elements>
public typealias SubSequence = AnySequence<Element>
/// Advances to the next element and returns it, or `nil` if no next element
/// exists.
///
/// Repeatedly calling this method returns all the elements of the underlying
/// sequence in order. As soon as the sequence has run out of elements, all
/// subsequent calls return `nil`.
///
/// This example shows how an iterator can be used explicitly to emulate a
/// `for`-`in` loop. First, retrieve a sequence's iterator, and then call
/// the iterator's `next()` method until it returns `nil`.
///
/// let numbers = [2, 3, 5, 7]
/// var numbersIterator = numbers.makeIterator()
///
/// while let num = numbersIterator.next() {
/// print(num)
/// }
/// // Prints "2"
/// // Prints "3"
/// // Prints "5"
/// // Prints "7"
///
/// - Returns: The next element in the underlying sequence if a next element
/// exists; otherwise, `nil`.
@inlinable
@inline(__always)
public mutating func next() -> Elements.Element? {
if _position == _elements.endIndex { return nil }
let element = _elements[_position]
_elements.formIndex(after: &_position)
return element
}
}
/// A sequence whose elements can be traversed multiple times,
/// nondestructively, and accessed by an indexed subscript.
///
/// Collections are used extensively throughout the standard library. When you
/// use arrays, dictionaries, and other collections, you benefit from the
/// operations that the `Collection` protocol declares and implements. In
/// addition to the operations that collections inherit from the `Sequence`
/// protocol, you gain access to methods that depend on accessing an element
/// at a specific position in a collection.
///
/// For example, if you want to print only the first word in a string, you can
/// search for the index of the first space, and then create a substring up to
/// that position.
///
/// let text = "Buffalo buffalo buffalo buffalo."
/// if let firstSpace = text.index(of: " ") {
/// print(text[..<firstSpace])
/// }
/// // Prints "Buffalo"
///
/// The `firstSpace` constant is an index into the `text` string---the position
/// of the first space in the string. You can store indices in variables, and
/// pass them to collection algorithms or use them later to access the
/// corresponding element. In the example above, `firstSpace` is used to
/// extract the prefix that contains elements up to that index.
///
/// Accessing Individual Elements
/// =============================
///
/// You can access an element of a collection through its subscript by using
/// any valid index except the collection's `endIndex` property. This property
/// is a "past the end" index that does not correspond with any element of the
/// collection.
///
/// Here's an example of accessing the first character in a string through its
/// subscript:
///
/// let firstChar = text[text.startIndex]
/// print(firstChar)
/// // Prints "B"
///
/// The `Collection` protocol declares and provides default implementations for
/// many operations that depend on elements being accessible by their
/// subscript. For example, you can also access the first character of `text`
/// using the `first` property, which has the value of the first element of
/// the collection, or `nil` if the collection is empty.
///
/// print(text.first)
/// // Prints "Optional("B")"
///
/// You can pass only valid indices to collection operations. You can find a
/// complete set of a collection's valid indices by starting with the
/// collection's `startIndex` property and finding every successor up to, and
/// including, the `endIndex` property. All other values of the `Index` type,
/// such as the `startIndex` property of a different collection, are invalid
/// indices for this collection.
///
/// Saved indices may become invalid as a result of mutating operations. For
/// more information about index invalidation in mutable collections, see the
/// reference for the `MutableCollection` and `RangeReplaceableCollection`
/// protocols, as well as for the specific type you're using.
///
/// Accessing Slices of a Collection
/// ================================
///
/// You can access a slice of a collection through its ranged subscript or by
/// calling methods like `prefix(while:)` or `suffix(_:)`. A slice of a
/// collection can contain zero or more of the original collection's elements
/// and shares the original collection's semantics.
///
/// The following example creates a `firstWord` constant by using the
/// `prefix(while:)` method to get a slice of the `text` string.
///
/// let firstWord = text.prefix(while: { $0 != " " })
/// print(firstWord)
/// // Prints "Buffalo"
///
/// You can retrieve the same slice using the string's ranged subscript, which
/// takes a range expression.
///
/// if let firstSpace = text.index(of: " ") {
/// print(text[..<firstSpace]
/// // Prints "Buffalo"
/// }
///
/// The retrieved slice of `text` is equivalent in each of these cases.
///
/// Slices Share Indices
/// --------------------
///
/// A collection and its slices share the same indices. An element of a
/// collection is located under the same index in a slice as in the base
/// collection, as long as neither the collection nor the slice has been
/// mutated since the slice was created.
///
/// For example, suppose you have an array holding the number of absences from
/// each class during a session.
///
/// var absences = [0, 2, 0, 4, 0, 3, 1, 0]
///
/// You're tasked with finding the day with the most absences in the second
/// half of the session. To find the index of the day in question, follow
/// these steps:
///
/// 1) Create a slice of the `absences` array that holds the second half of the
/// days.
/// 2) Use the `max(by:)` method to determine the index of the day with the
/// most absences.
/// 3) Print the result using the index found in step 2 on the original
/// `absences` array.
///
/// Here's an implementation of those steps:
///
/// let secondHalf = absences.suffix(absences.count / 2)
/// if let i = secondHalf.indices.max(by: { secondHalf[$0] < secondHalf[$1] }) {
/// print("Highest second-half absences: \(absences[i])")
/// }
/// // Prints "Highest second-half absences: 3"
///
/// Slices Inherit Collection Semantics
/// -----------------------------------
///
/// A slice inherits the value or reference semantics of its base collection.
/// That is, when working with a slice of a mutable collection that has value
/// semantics, such as an array, mutating the original collection triggers a
/// copy of that collection and does not affect the contents of the slice.
///
/// For example, if you update the last element of the `absences` array from
/// `0` to `2`, the `secondHalf` slice is unchanged.
///
/// absences[7] = 2
/// print(absences)
/// // Prints "[0, 2, 0, 4, 0, 3, 1, 2]"
/// print(secondHalf)
/// // Prints "[0, 3, 1, 0]"
///
/// Traversing a Collection
/// =======================
///
/// Although a sequence can be consumed as it is traversed, a collection is
/// guaranteed to be *multipass*: Any element can be repeatedly accessed by
/// saving its index. Moreover, a collection's indices form a finite range of
/// the positions of the collection's elements. The fact that all collections
/// are finite guarantees the safety of many sequence operations, such as
/// using the `contains(_:)` method to test whether a collection includes an
/// element.
///
/// Iterating over the elements of a collection by their positions yields the
/// same elements in the same order as iterating over that collection using
/// its iterator. This example demonstrates that the `characters` view of a
/// string returns the same characters in the same order whether the view's
/// indices or the view itself is being iterated.
///
/// let word = "Swift"
/// for character in word {
/// print(character)
/// }
/// // Prints "S"
/// // Prints "w"
/// // Prints "i"
/// // Prints "f"
/// // Prints "t"
///
/// for i in word.indices {
/// print(word[i])
/// }
/// // Prints "S"
/// // Prints "w"
/// // Prints "i"
/// // Prints "f"
/// // Prints "t"
///
/// Conforming to the Collection Protocol
/// =====================================
///
/// If you create a custom sequence that can provide repeated access to its
/// elements, make sure that its type conforms to the `Collection` protocol in
/// order to give a more useful and more efficient interface for sequence and
/// collection operations. To add `Collection` conformance to your type, you
/// must declare at least the following requirements:
///
/// - The `startIndex` and `endIndex` properties
/// - A subscript that provides at least read-only access to your type's
/// elements
/// - The `index(after:)` method for advancing an index into your collection
///
/// Expected Performance
/// ====================
///
/// Types that conform to `Collection` are expected to provide the `startIndex`
/// and `endIndex` properties and subscript access to elements as O(1)
/// operations. Types that are not able to guarantee this performance must
/// document the departure, because many collection operations depend on O(1)
/// subscripting performance for their own performance guarantees.
///
/// The performance of some collection operations depends on the type of index
/// that the collection provides. For example, a random-access collection,
/// which can measure the distance between two indices in O(1) time, can
/// calculate its `count` property in O(1) time. Conversely, because a forward
/// or bidirectional collection must traverse the entire collection to count
/// the number of contained elements, accessing its `count` property is an
/// O(*n*) operation.
public protocol Collection: Sequence where SubSequence: Collection {
// FIXME(ABI): Associated type inference requires this.
associatedtype Element
/// A type that represents a position in the collection.
///
/// Valid indices consist of the position of every element and a
/// "past the end" position that's not valid for use as a subscript
/// argument.
associatedtype Index : Comparable
/// The position of the first element in a nonempty collection.
///
/// If the collection is empty, `startIndex` is equal to `endIndex`.
var startIndex: Index { get }
/// The collection's "past the end" position---that is, the position one
/// greater than the last valid subscript argument.
///
/// When you need a range that includes the last element of a collection, use
/// the half-open range operator (`..<`) with `endIndex`. The `..<` operator
/// creates a range that doesn't include the upper bound, so it's always
/// safe to use with `endIndex`. For example:
///
/// let numbers = [10, 20, 30, 40, 50]
/// if let index = numbers.index(of: 30) {
/// print(numbers[index ..< numbers.endIndex])
/// }
/// // Prints "[30, 40, 50]"
///
/// If the collection is empty, `endIndex` is equal to `startIndex`.
var endIndex: Index { get }
/// A type that provides the collection's iteration interface and
/// encapsulates its iteration state.
///
/// By default, a collection conforms to the `Sequence` protocol by
/// supplying `IndexingIterator` as its associated `Iterator`
/// type.
associatedtype Iterator = IndexingIterator<Self>
// FIXME(ABI)#179 (Type checker): Needed here so that the `Iterator` is properly deduced from
// a custom `makeIterator()` function. Otherwise we get an
// `IndexingIterator`. <rdar://problem/21539115>
/// Returns an iterator over the elements of the collection.
func makeIterator() -> Iterator
/// A sequence that represents a contiguous subrange of the collection's
/// elements.
///
/// This associated type appears as a requirement in the `Sequence`
/// protocol, but it is restated here with stricter constraints. In a
/// collection, the subsequence should also conform to `Collection`.
associatedtype SubSequence = Slice<Self> where SubSequence.Index == Index
/// Accesses the element at the specified position.
///
/// The following example accesses an element of an array through its
/// subscript to print its value:
///
/// var streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]
/// print(streets[1])
/// // Prints "Bryant"
///
/// You can subscript a collection with any valid index other than the
/// collection's end index. The end index refers to the position one past
/// the last element of a collection, so it doesn't correspond with an
/// element.
///
/// - Parameter position: The position of the element to access. `position`
/// must be a valid index of the collection that is not equal to the
/// `endIndex` property.
///
/// - Complexity: O(1)
subscript(position: Index) -> Element { get }
/// Accesses a contiguous subrange of the collection's elements.
///
/// For example, using a `PartialRangeFrom` range expression with an array
/// accesses the subrange from the start of the range expression until the
/// end of the array.
///
/// let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]
/// let streetsSlice = streets[2..<5]
/// print(streetsSlice)
/// // ["Channing", "Douglas", "Evarts"]
///
/// The accessed slice uses the same indices for the same elements as the
/// original collection. This example searches `streetsSlice` for one of the
/// strings in the slice, and then uses that index in the original array.
///
/// let index = streetsSlice.index(of: "Evarts")! // 4
/// print(streets[index])
/// // "Evarts"
///
/// Always use the slice's `startIndex` property instead of assuming that its
/// indices start at a particular value. Attempting to access an element by
/// using an index outside the bounds of the slice may result in a runtime
/// error, even if that index is valid for the original collection.
///
/// print(streetsSlice.startIndex)
/// // 2
/// print(streetsSlice[2])
/// // "Channing"
///
/// print(streetsSlice[0])
/// // error: Index out of bounds
///
/// - Parameter bounds: A range of the collection's indices. The bounds of
/// the range must be valid indices of the collection.
///
/// - Complexity: O(1)
subscript(bounds: Range<Index>) -> SubSequence { get }
/// A type that represents the indices that are valid for subscripting the
/// collection, in ascending order.
associatedtype Indices : Collection = DefaultIndices<Self>
where Indices.Element == Index,
Indices.Index == Index,
Indices.SubSequence == Indices
/// The indices that are valid for subscripting the collection, in ascending
/// order.
///
/// A collection's `indices` property can hold a strong reference to the
/// collection itself, causing the collection to be nonuniquely referenced.
/// If you mutate the collection while iterating over its indices, a strong
/// reference can result in an unexpected copy of the collection. To avoid
/// the unexpected copy, use the `index(after:)` method starting with
/// `startIndex` to produce indices instead.
///
/// var c = MyFancyCollection([10, 20, 30, 40, 50])
/// var i = c.startIndex
/// while i != c.endIndex {
/// c[i] /= 5
/// i = c.index(after: i)
/// }
/// // c == MyFancyCollection([2, 4, 6, 8, 10])
var indices: Indices { get }
/// Returns a subsequence from the start of the collection up to, but not
/// including, the specified position.
///
/// The resulting subsequence *does not include* the element at the position
/// `end`. The following example searches for the index of the number `40`
/// in an array of integers, and then prints the prefix of the array up to,
/// but not including, that index:
///
/// let numbers = [10, 20, 30, 40, 50, 60]
/// if let i = numbers.index(of: 40) {
/// print(numbers.prefix(upTo: i))
/// }
/// // Prints "[10, 20, 30]"
///
/// Passing the collection's starting index as the `end` parameter results in
/// an empty subsequence.
///
/// print(numbers.prefix(upTo: numbers.startIndex))
/// // Prints "[]"
///
/// Using the `prefix(upTo:)` method is equivalent to using a partial
/// half-open range as the collection's subscript. The subscript notation is
/// preferred over `prefix(upTo:)`.
///
/// if let i = numbers.index(of: 40) {
/// print(numbers[..<i])
/// }
/// // Prints "[10, 20, 30]"
///
/// - Parameter end: The "past the end" index of the resulting subsequence.
/// `end` must be a valid index of the collection.
/// - Returns: A subsequence up to, but not including, the `end` position.
///
/// - Complexity: O(1)
func prefix(upTo end: Index) -> SubSequence
/// Returns a subsequence from the specified position to the end of the
/// collection.
///
/// The following example searches for the index of the number `40` in an
/// array of integers, and then prints the suffix of the array starting at
/// that index:
///
/// let numbers = [10, 20, 30, 40, 50, 60]
/// if let i = numbers.index(of: 40) {
/// print(numbers.suffix(from: i))
/// }
/// // Prints "[40, 50, 60]"
///
/// Passing the collection's `endIndex` as the `start` parameter results in
/// an empty subsequence.
///
/// print(numbers.suffix(from: numbers.endIndex))
/// // Prints "[]"
///
/// Using the `suffix(from:)` method is equivalent to using a partial range
/// from the index as the collection's subscript. The subscript notation is
/// preferred over `suffix(from:)`.
///
/// if let i = numbers.index(of: 40) {
/// print(numbers[i...])
/// }
/// // Prints "[40, 50, 60]"
///
/// - Parameter start: The index at which to start the resulting subsequence.
/// `start` must be a valid index of the collection.
/// - Returns: A subsequence starting at the `start` position.
///
/// - Complexity: O(1)
func suffix(from start: Index) -> SubSequence
/// Returns a subsequence from the start of the collection through the
/// specified position.
///
/// The resulting subsequence *includes* the element at the position `end`.
/// The following example searches for the index of the number `40` in an
/// array of integers, and then prints the prefix of the array up to, and
/// including, that index:
///
/// let numbers = [10, 20, 30, 40, 50, 60]
/// if let i = numbers.index(of: 40) {
/// print(numbers.prefix(through: i))
/// }
/// // Prints "[10, 20, 30, 40]"
///
/// Using the `prefix(through:)` method is equivalent to using a partial
/// closed range as the collection's subscript. The subscript notation is
/// preferred over `prefix(through:)`.
///
/// if let i = numbers.index(of: 40) {
/// print(numbers[...i])
/// }
/// // Prints "[10, 20, 30, 40]"
///
/// - Parameter end: The index of the last element to include in the
/// resulting subsequence. `end` must be a valid index of the collection
/// that is not equal to the `endIndex` property.
/// - Returns: A subsequence up to, and including, the `end` position.
///
/// - Complexity: O(1)
func prefix(through position: Index) -> SubSequence
/// A Boolean value indicating whether the collection is empty.
///
/// When you need to check whether your collection is empty, use the
/// `isEmpty` property instead of checking that the `count` property is
/// equal to zero. For collections that don't conform to
/// `RandomAccessCollection`, accessing the `count` property iterates
/// through the elements of the collection.
///
/// let horseName = "Silver"
/// if horseName.isEmpty {
/// print("I've been through the desert on a horse with no name.")
/// } else {
/// print("Hi ho, \(horseName)!")
/// }
/// // Prints "Hi ho, Silver!"
///
/// - Complexity: O(1)
var isEmpty: Bool { get }
/// The number of elements in the collection.
///
/// To check whether a collection is empty, use its `isEmpty` property
/// instead of comparing `count` to zero. Unless the collection guarantees
/// random-access performance, calculating `count` can be an O(*n*)
/// operation.
///
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the length
/// of the collection.
var count: Int { get }
// The following requirement enables dispatching for index(of:) when
// the element type is Equatable.
/// Returns `Optional(Optional(index))` if an element was found
/// or `Optional(nil)` if an element was determined to be missing;
/// otherwise, `nil`.
///
/// - Complexity: O(*n*)
func _customIndexOfEquatableElement(_ element: Element) -> Index??
/// The first element of the collection.
///
/// If the collection is empty, the value of this property is `nil`.
///
/// let numbers = [10, 20, 30, 40, 50]
/// if let firstNumber = numbers.first {
/// print(firstNumber)
/// }
/// // Prints "10"
var first: Element? { get }
/// Returns an index that is the specified distance from the given index.
///
/// The following example obtains an index advanced four positions from a
/// string's starting index and then prints the character at that position.
///
/// let s = "Swift"
/// let i = s.index(s.startIndex, offsetBy: 4)
/// print(s[i])
/// // Prints "t"
///
/// The value passed as `n` must not offset `i` beyond the bounds of the
/// collection.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - n: The distance to offset `i`. `n` must not be negative unless the
/// collection conforms to the `BidirectionalCollection` protocol.
/// - Returns: An index offset by `n` from the index `i`. If `n` is positive,
/// this is the same value as the result of `n` calls to `index(after:)`.
/// If `n` is negative, this is the same value as the result of `-n` calls
/// to `index(before:)`.
///
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute
/// value of `n`.
func index(_ i: Index, offsetBy n: Int) -> Index
/// Returns an index that is the specified distance from the given index,
/// unless that distance is beyond a given limiting index.
///
/// The following example obtains an index advanced four positions from a
/// string's starting index and then prints the character at that position.
/// The operation doesn't require going beyond the limiting `s.endIndex`
/// value, so it succeeds.
///
/// let s = "Swift"
/// if let i = s.index(s.startIndex, offsetBy: 4, limitedBy: s.endIndex) {
/// print(s[i])
/// }
/// // Prints "t"
///
/// The next example attempts to retrieve an index six positions from
/// `s.startIndex` but fails, because that distance is beyond the index
/// passed as `limit`.
///
/// let j = s.index(s.startIndex, offsetBy: 6, limitedBy: s.endIndex)
/// print(j)
/// // Prints "nil"
///
/// The value passed as `n` must not offset `i` beyond the bounds of the
/// collection, unless the index passed as `limit` prevents offsetting
/// beyond those bounds.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - n: The distance to offset `i`. `n` must not be negative unless the
/// collection conforms to the `BidirectionalCollection` protocol.
/// - limit: A valid index of the collection to use as a limit. If `n > 0`,
/// a limit that is less than `i` has no effect. Likewise, if `n < 0`, a
/// limit that is greater than `i` has no effect.
/// - Returns: An index offset by `n` from the index `i`, unless that index
/// would be beyond `limit` in the direction of movement. In that case,
/// the method returns `nil`.
///
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute
/// value of `n`.
func index(
_ i: Index, offsetBy n: Int, limitedBy limit: Index
) -> Index?
/// Returns the distance between two indices.
///
/// Unless the collection conforms to the `BidirectionalCollection` protocol,
/// `start` must be less than or equal to `end`.
///
/// - Parameters:
/// - start: A valid index of the collection.
/// - end: Another valid index of the collection. If `end` is equal to
/// `start`, the result is zero.
/// - Returns: The distance between `start` and `end`. The result can be
/// negative only if the collection conforms to the
/// `BidirectionalCollection` protocol.
///
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the
/// resulting distance.
func distance(from start: Index, to end: Index) -> Int
/// Performs a range check in O(1), or a no-op when a range check is not
/// implementable in O(1).
///
/// The range check, if performed, is equivalent to:
///
/// precondition(bounds.contains(index))
///
/// Use this function to perform a cheap range check for QoI purposes when
/// memory safety is not a concern. Do not rely on this range check for
/// memory safety.
///
/// The default implementation for forward and bidirectional indices is a
/// no-op. The default implementation for random access indices performs a
/// range check.
///
/// - Complexity: O(1).
func _failEarlyRangeCheck(_ index: Index, bounds: Range<Index>)
func _failEarlyRangeCheck(_ index: Index, bounds: ClosedRange<Index>)
/// Performs a range check in O(1), or a no-op when a range check is not
/// implementable in O(1).
///
/// The range check, if performed, is equivalent to:
///
/// precondition(
/// bounds.contains(range.lowerBound) ||
/// range.lowerBound == bounds.upperBound)
/// precondition(
/// bounds.contains(range.upperBound) ||
/// range.upperBound == bounds.upperBound)
///
/// Use this function to perform a cheap range check for QoI purposes when
/// memory safety is not a concern. Do not rely on this range check for
/// memory safety.
///
/// The default implementation for forward and bidirectional indices is a
/// no-op. The default implementation for random access indices performs a
/// range check.
///
/// - Complexity: O(1).
func _failEarlyRangeCheck(_ range: Range<Index>, bounds: Range<Index>)
/// Returns the position immediately after the given index.
///
/// The successor of an index must be well defined. For an index `i` into a
/// collection `c`, calling `c.index(after: i)` returns the same index every
/// time.
///
/// - Parameter i: A valid index of the collection. `i` must be less than
/// `endIndex`.
/// - Returns: The index value immediately after `i`.
func index(after i: Index) -> Index
/// Replaces the given index with its successor.
///
/// - Parameter i: A valid index of the collection. `i` must be less than
/// `endIndex`.
func formIndex(after i: inout Index)
@available(*, deprecated, message: "all index distances are now of type Int")
typealias IndexDistance = Int
}
/// Default implementation for forward collections.
extension Collection {
/// Replaces the given index with its successor.
///
/// - Parameter i: A valid index of the collection. `i` must be less than
/// `endIndex`.
@inlinable // FIXME(sil-serialize-all)
@inline(__always)
public func formIndex(after i: inout Index) {
i = index(after: i)
}
@inlinable
public func _failEarlyRangeCheck(_ index: Index, bounds: Range<Index>) {
// FIXME: swift-3-indexing-model: tests.
_precondition(
bounds.lowerBound <= index,
"Out of bounds: index < startIndex")
_precondition(
index < bounds.upperBound,
"Out of bounds: index >= endIndex")
}
@inlinable
public func _failEarlyRangeCheck(_ index: Index, bounds: ClosedRange<Index>) {
// FIXME: swift-3-indexing-model: tests.
_precondition(
bounds.lowerBound <= index,
"Out of bounds: index < startIndex")
_precondition(
index <= bounds.upperBound,
"Out of bounds: index > endIndex")
}
@inlinable
public func _failEarlyRangeCheck(_ range: Range<Index>, bounds: Range<Index>) {
// FIXME: swift-3-indexing-model: tests.
_precondition(
bounds.lowerBound <= range.lowerBound,
"Out of bounds: range begins before startIndex")
_precondition(
range.lowerBound <= bounds.upperBound,
"Out of bounds: range ends after endIndex")
_precondition(
bounds.lowerBound <= range.upperBound,
"Out of bounds: range ends before bounds.lowerBound")
_precondition(
range.upperBound <= bounds.upperBound,
"Out of bounds: range begins after bounds.upperBound")
}
/// Returns an index that is the specified distance from the given index.
///
/// The following example obtains an index advanced four positions from a
/// string's starting index and then prints the character at that position.
///
/// let s = "Swift"
/// let i = s.index(s.startIndex, offsetBy: 4)
/// print(s[i])
/// // Prints "t"
///
/// The value passed as `n` must not offset `i` beyond the bounds of the
/// collection.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - n: The distance to offset `i`. `n` must not be negative unless the
/// collection conforms to the `BidirectionalCollection` protocol.
/// - Returns: An index offset by `n` from the index `i`. If `n` is positive,
/// this is the same value as the result of `n` calls to `index(after:)`.
/// If `n` is negative, this is the same value as the result of `-n` calls
/// to `index(before:)`.
///
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute
/// value of `n`.
@inlinable
public func index(_ i: Index, offsetBy n: Int) -> Index {
return self._advanceForward(i, by: n)
}
/// Returns an index that is the specified distance from the given index,
/// unless that distance is beyond a given limiting index.
///
/// The following example obtains an index advanced four positions from a
/// string's starting index and then prints the character at that position.
/// The operation doesn't require going beyond the limiting `s.endIndex`
/// value, so it succeeds.
///
/// let s = "Swift"
/// if let i = s.index(s.startIndex, offsetBy: 4, limitedBy: s.endIndex) {
/// print(s[i])
/// }
/// // Prints "t"
///
/// The next example attempts to retrieve an index six positions from
/// `s.startIndex` but fails, because that distance is beyond the index
/// passed as `limit`.
///
/// let j = s.index(s.startIndex, offsetBy: 6, limitedBy: s.endIndex)
/// print(j)
/// // Prints "nil"
///
/// The value passed as `n` must not offset `i` beyond the bounds of the
/// collection, unless the index passed as `limit` prevents offsetting
/// beyond those bounds.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - n: The distance to offset `i`. `n` must not be negative unless the
/// collection conforms to the `BidirectionalCollection` protocol.
/// - limit: A valid index of the collection to use as a limit. If `n > 0`,
/// a limit that is less than `i` has no effect. Likewise, if `n < 0`, a
/// limit that is greater than `i` has no effect.
/// - Returns: An index offset by `n` from the index `i`, unless that index
/// would be beyond `limit` in the direction of movement. In that case,
/// the method returns `nil`.
///
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute
/// value of `n`.
@inlinable
public func index(
_ i: Index, offsetBy n: Int, limitedBy limit: Index
) -> Index? {
return self._advanceForward(i, by: n, limitedBy: limit)
}
/// Offsets the given index by the specified distance.
///
/// The value passed as `n` must not offset `i` beyond the bounds of the
/// collection.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - n: The distance to offset `i`. `n` must not be negative unless the
/// collection conforms to the `BidirectionalCollection` protocol.
///
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute
/// value of `n`.
@inlinable
public func formIndex(_ i: inout Index, offsetBy n: Int) {
i = index(i, offsetBy: n)
}
/// Offsets the given index by the specified distance, or so that it equals
/// the given limiting index.
///
/// The value passed as `n` must not offset `i` beyond the bounds of the
/// collection, unless the index passed as `limit` prevents offsetting
/// beyond those bounds.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - n: The distance to offset `i`. `n` must not be negative unless the
/// collection conforms to the `BidirectionalCollection` protocol.
/// - limit: A valid index of the collection to use as a limit. If `n > 0`,
/// a limit that is less than `i` has no effect. Likewise, if `n < 0`, a
/// limit that is greater than `i` has no effect.
/// - Returns: `true` if `i` has been offset by exactly `n` steps without
/// going beyond `limit`; otherwise, `false`. When the return value is
/// `false`, the value of `i` is equal to `limit`.
///
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute
/// value of `n`.
@inlinable
public func formIndex(
_ i: inout Index, offsetBy n: Int, limitedBy limit: Index
) -> Bool {
if let advancedIndex = index(i, offsetBy: n, limitedBy: limit) {
i = advancedIndex
return true
}
i = limit
return false
}
/// Returns the distance between two indices.
///
/// Unless the collection conforms to the `BidirectionalCollection` protocol,
/// `start` must be less than or equal to `end`.
///
/// - Parameters:
/// - start: A valid index of the collection.
/// - end: Another valid index of the collection. If `end` is equal to
/// `start`, the result is zero.
/// - Returns: The distance between `start` and `end`. The result can be
/// negative only if the collection conforms to the
/// `BidirectionalCollection` protocol.
///
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the
/// resulting distance.
@inlinable
public func distance(from start: Index, to end: Index) -> Int {
_precondition(start <= end,
"Only BidirectionalCollections can have end come before start")
var start = start
var count = 0
while start != end {
count = count + 1
formIndex(after: &start)
}
return count
}
/// Do not use this method directly; call advanced(by: n) instead.
@inlinable
@inline(__always)
internal func _advanceForward(_ i: Index, by n: Int) -> Index {
_precondition(n >= 0,
"Only BidirectionalCollections can be advanced by a negative amount")
var i = i
for _ in stride(from: 0, to: n, by: 1) {
formIndex(after: &i)
}
return i
}
/// Do not use this method directly; call advanced(by: n, limit) instead.
@inlinable
@inline(__always)
internal func _advanceForward(
_ i: Index, by n: Int, limitedBy limit: Index
) -> Index? {
_precondition(n >= 0,
"Only BidirectionalCollections can be advanced by a negative amount")
var i = i
for _ in stride(from: 0, to: n, by: 1) {
if i == limit {
return nil
}
formIndex(after: &i)
}
return i
}
}
/// Supply the default `makeIterator()` method for `Collection` models
/// that accept the default associated `Iterator`,
/// `IndexingIterator<Self>`.
extension Collection where Iterator == IndexingIterator<Self> {
/// Returns an iterator over the elements of the collection.
@inlinable // FIXME(sil-serialize-all)
@inline(__always)
public func makeIterator() -> IndexingIterator<Self> {
return IndexingIterator(_elements: self)
}
}
/// Supply the default "slicing" `subscript` for `Collection` models
/// that accept the default associated `SubSequence`, `Slice<Self>`.
extension Collection where SubSequence == Slice<Self> {
/// Accesses a contiguous subrange of the collection's elements.
///
/// The accessed slice uses the same indices for the same elements as the
/// original collection. Always use the slice's `startIndex` property
/// instead of assuming that its indices start at a particular value.
///
/// This example demonstrates getting a slice of an array of strings, finding
/// the index of one of the strings in the slice, and then using that index
/// in the original array.
///
/// let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]
/// let streetsSlice = streets[2 ..< streets.endIndex]
/// print(streetsSlice)
/// // Prints "["Channing", "Douglas", "Evarts"]"
///
/// let index = streetsSlice.index(of: "Evarts") // 4
/// print(streets[index!])
/// // Prints "Evarts"
///
/// - Parameter bounds: A range of the collection's indices. The bounds of
/// the range must be valid indices of the collection.
///
/// - Complexity: O(1)
@inlinable
public subscript(bounds: Range<Index>) -> Slice<Self> {
_failEarlyRangeCheck(bounds, bounds: startIndex..<endIndex)
return Slice(base: self, bounds: bounds)
}
}
extension Collection where SubSequence == Self {
/// Removes and returns the first element of the collection.
///
/// - Returns: The first element of the collection if the collection is
/// not empty; otherwise, `nil`.
///
/// - Complexity: O(1)
@inlinable
public mutating func popFirst() -> Element? {
// TODO: swift-3-indexing-model - review the following
guard !isEmpty else { return nil }
let element = first!
self = self[index(after: startIndex)..<endIndex]
return element
}
}
/// Default implementations of core requirements
extension Collection {
/// A Boolean value indicating whether the collection is empty.
///
/// When you need to check whether your collection is empty, use the
/// `isEmpty` property instead of checking that the `count` property is
/// equal to zero. For collections that don't conform to
/// `RandomAccessCollection`, accessing the `count` property iterates
/// through the elements of the collection.
///
/// let horseName = "Silver"
/// if horseName.isEmpty {
/// print("I've been through the desert on a horse with no name.")
/// } else {
/// print("Hi ho, \(horseName)!")
/// }
/// // Prints "Hi ho, Silver!")
///
/// - Complexity: O(1)
@inlinable
public var isEmpty: Bool {
return startIndex == endIndex
}
/// The first element of the collection.
///
/// If the collection is empty, the value of this property is `nil`.
///
/// let numbers = [10, 20, 30, 40, 50]
/// if let firstNumber = numbers.first {
/// print(firstNumber)
/// }
/// // Prints "10"
@inlinable
public var first: Element? {
@inline(__always)
get {
// NB: Accessing `startIndex` may not be O(1) for some lazy collections,
// so instead of testing `isEmpty` and then returning the first element,
// we'll just rely on the fact that the iterator always yields the
// first element first.
var i = makeIterator()
return i.next()
}
}
// TODO: swift-3-indexing-model - uncomment and replace above ready (or should we still use the iterator one?)
/// Returns the first element of `self`, or `nil` if `self` is empty.
///
/// - Complexity: O(1)
// public var first: Element? {
// return isEmpty ? nil : self[startIndex]
// }
/// A value less than or equal to the number of elements in the collection.
///
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the length
/// of the collection.
@inlinable
public var underestimatedCount: Int {
// TODO: swift-3-indexing-model - review the following
return count
}
/// The number of elements in the collection.
///
/// To check whether a collection is empty, use its `isEmpty` property
/// instead of comparing `count` to zero. Unless the collection guarantees
/// random-access performance, calculating `count` can be an O(*n*)
/// operation.
///
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the length
/// of the collection.
@inlinable
public var count: Int {
return distance(from: startIndex, to: endIndex)
}
// TODO: swift-3-indexing-model - rename the following to _customIndexOfEquatable(element)?
/// Customization point for `Collection.index(of:)`.
///
/// Define this method if the collection can find an element in less than
/// O(*n*) by exploiting collection-specific knowledge.
///
/// - Returns: `nil` if a linear search should be attempted instead,
/// `Optional(nil)` if the element was not found, or
/// `Optional(Optional(index))` if an element was found.
///
/// - Complexity: O(`count`).
@inlinable
public // dispatching
func _customIndexOfEquatableElement(_: Iterator.Element) -> Index?? {
return nil
}
}
//===----------------------------------------------------------------------===//
// Default implementations for Collection
//===----------------------------------------------------------------------===//
extension Collection {
/// Returns an array containing the results of mapping the given closure
/// over the sequence's elements.
///
/// In this example, `map` is used first to convert the names in the array
/// to lowercase strings and then to count their characters.
///
/// let cast = ["Vivien", "Marlon", "Kim", "Karl"]
/// let lowercaseNames = cast.map { $0.lowercased() }
/// // 'lowercaseNames' == ["vivien", "marlon", "kim", "karl"]
/// let letterCounts = cast.map { $0.count }
/// // 'letterCounts' == [6, 6, 3, 4]
///
/// - Parameter transform: A mapping closure. `transform` accepts an
/// element of this sequence as its parameter and returns a transformed
/// value of the same or of a different type.
/// - Returns: An array containing the transformed elements of this
/// sequence.
@inlinable
public func map<T>(
_ transform: (Element) throws -> T
) rethrows -> [T] {
// TODO: swift-3-indexing-model - review the following
let n = self.count
if n == 0 {
return []
}
var result = ContiguousArray<T>()
result.reserveCapacity(n)
var i = self.startIndex
for _ in 0..<n {
result.append(try transform(self[i]))
formIndex(after: &i)
}
_expectEnd(of: self, is: i)
return Array(result)
}
/// Returns a subsequence containing all but the given number of initial
/// elements.
///
/// If the number of elements to drop exceeds the number of elements in
/// the collection, the result is an empty subsequence.
///
/// let numbers = [1, 2, 3, 4, 5]
/// print(numbers.dropFirst(2))
/// // Prints "[3, 4, 5]"
/// print(numbers.dropFirst(10))
/// // Prints "[]"
///
/// - Parameter n: The number of elements to drop from the beginning of
/// the collection. `n` must be greater than or equal to zero.
/// - Returns: A subsequence starting after the specified number of
/// elements.
///
/// - Complexity: O(*n*), where *n* is the number of elements to drop from
/// the beginning of the collection.
@inlinable
public func dropFirst(_ n: Int) -> SubSequence {
_precondition(n >= 0, "Can't drop a negative number of elements from a collection")
let start = index(startIndex,
offsetBy: n, limitedBy: endIndex) ?? endIndex
return self[start..<endIndex]
}
/// Returns a subsequence containing all but the specified number of final
/// elements.
///
/// If the number of elements to drop exceeds the number of elements in the
/// collection, the result is an empty subsequence.
///
/// let numbers = [1, 2, 3, 4, 5]
/// print(numbers.dropLast(2))
/// // Prints "[1, 2, 3]"
/// print(numbers.dropLast(10))
/// // Prints "[]"
///
/// - Parameter n: The number of elements to drop off the end of the
/// collection. `n` must be greater than or equal to zero.
/// - Returns: A subsequence that leaves off the specified number of elements
/// at the end.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
public func dropLast(_ n: Int) -> SubSequence {
_precondition(
n >= 0, "Can't drop a negative number of elements from a collection")
let amount = Swift.max(0, count - n)
let end = index(startIndex,
offsetBy: amount, limitedBy: endIndex) ?? endIndex
return self[startIndex..<end]
}
/// Returns a subsequence by skipping elements while `predicate` returns
/// `true` and returning the remaining elements.
///
/// - Parameter predicate: A closure that takes an element of the
/// sequence as its argument and returns `true` if the element should
/// be skipped or `false` if it should be included. Once the predicate
/// returns `false` it will not be called again.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
public func drop(
while predicate: (Element) throws -> Bool
) rethrows -> SubSequence {
var start = startIndex
while try start != endIndex && predicate(self[start]) {
formIndex(after: &start)
}
return self[start..<endIndex]
}
/// Returns a subsequence, up to the specified maximum length, containing
/// the initial elements of the collection.
///
/// If the maximum length exceeds the number of elements in the collection,
/// the result contains all the elements in the collection.
///
/// let numbers = [1, 2, 3, 4, 5]
/// print(numbers.prefix(2))
/// // Prints "[1, 2]"
/// print(numbers.prefix(10))
/// // Prints "[1, 2, 3, 4, 5]"
///
/// - Parameter maxLength: The maximum number of elements to return.
/// `maxLength` must be greater than or equal to zero.
/// - Returns: A subsequence starting at the beginning of this collection
/// with at most `maxLength` elements.
@inlinable
public func prefix(_ maxLength: Int) -> SubSequence {
_precondition(
maxLength >= 0,
"Can't take a prefix of negative length from a collection")
let end = index(startIndex,
offsetBy: maxLength, limitedBy: endIndex) ?? endIndex
return self[startIndex..<end]
}
/// Returns a subsequence containing the initial elements until `predicate`
/// returns `false` and skipping the remaining elements.
///
/// - Parameter predicate: A closure that takes an element of the
/// sequence as its argument and returns `true` if the element should
/// be included or `false` if it should be excluded. Once the predicate
/// returns `false` it will not be called again.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
public func prefix(
while predicate: (Element) throws -> Bool
) rethrows -> SubSequence {
var end = startIndex
while try end != endIndex && predicate(self[end]) {
formIndex(after: &end)
}
return self[startIndex..<end]
}
/// Returns a subsequence, up to the given maximum length, containing the
/// final elements of the collection.
///
/// If the maximum length exceeds the number of elements in the collection,
/// the result contains all the elements in the collection.
///
/// let numbers = [1, 2, 3, 4, 5]
/// print(numbers.suffix(2))
/// // Prints "[4, 5]"
/// print(numbers.suffix(10))
/// // Prints "[1, 2, 3, 4, 5]"
///
/// - Parameter maxLength: The maximum number of elements to return. The
/// value of `maxLength` must be greater than or equal to zero.
/// - Returns: A subsequence terminating at the end of the collection with at
/// most `maxLength` elements.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
public func suffix(_ maxLength: Int) -> SubSequence {
_precondition(
maxLength >= 0,
"Can't take a suffix of negative length from a collection")
let amount = Swift.max(0, count - maxLength)
let start = index(startIndex,
offsetBy: amount, limitedBy: endIndex) ?? endIndex
return self[start..<endIndex]
}
/// Returns a subsequence from the start of the collection up to, but not
/// including, the specified position.
///
/// The resulting subsequence *does not include* the element at the position
/// `end`. The following example searches for the index of the number `40`
/// in an array of integers, and then prints the prefix of the array up to,
/// but not including, that index:
///
/// let numbers = [10, 20, 30, 40, 50, 60]
/// if let i = numbers.index(of: 40) {
/// print(numbers.prefix(upTo: i))
/// }
/// // Prints "[10, 20, 30]"
///
/// Passing the collection's starting index as the `end` parameter results in
/// an empty subsequence.
///
/// print(numbers.prefix(upTo: numbers.startIndex))
/// // Prints "[]"
///
/// Using the `prefix(upTo:)` method is equivalent to using a partial
/// half-open range as the collection's subscript. The subscript notation is
/// preferred over `prefix(upTo:)`.
///
/// if let i = numbers.index(of: 40) {
/// print(numbers[..<i])
/// }
/// // Prints "[10, 20, 30]"
///
/// - Parameter end: The "past the end" index of the resulting subsequence.
/// `end` must be a valid index of the collection.
/// - Returns: A subsequence up to, but not including, the `end` position.
///
/// - Complexity: O(1)
@inlinable
public func prefix(upTo end: Index) -> SubSequence {
return self[startIndex..<end]
}
/// Returns a subsequence from the specified position to the end of the
/// collection.
///
/// The following example searches for the index of the number `40` in an
/// array of integers, and then prints the suffix of the array starting at
/// that index:
///
/// let numbers = [10, 20, 30, 40, 50, 60]
/// if let i = numbers.index(of: 40) {
/// print(numbers.suffix(from: i))
/// }
/// // Prints "[40, 50, 60]"
///
/// Passing the collection's `endIndex` as the `start` parameter results in
/// an empty subsequence.
///
/// print(numbers.suffix(from: numbers.endIndex))
/// // Prints "[]"
///
/// Using the `suffix(from:)` method is equivalent to using a partial range
/// from the index as the collection's subscript. The subscript notation is
/// preferred over `suffix(from:)`.
///
/// if let i = numbers.index(of: 40) {
/// print(numbers[i...])
/// }
/// // Prints "[40, 50, 60]"
///
/// - Parameter start: The index at which to start the resulting subsequence.
/// `start` must be a valid index of the collection.
/// - Returns: A subsequence starting at the `start` position.
///
/// - Complexity: O(1)
@inlinable
public func suffix(from start: Index) -> SubSequence {
return self[start..<endIndex]
}
/// Returns a subsequence from the start of the collection through the
/// specified position.
///
/// The resulting subsequence *includes* the element at the position `end`.
/// The following example searches for the index of the number `40` in an
/// array of integers, and then prints the prefix of the array up to, and
/// including, that index:
///
/// let numbers = [10, 20, 30, 40, 50, 60]
/// if let i = numbers.index(of: 40) {
/// print(numbers.prefix(through: i))
/// }
/// // Prints "[10, 20, 30, 40]"
///
/// Using the `prefix(through:)` method is equivalent to using a partial
/// closed range as the collection's subscript. The subscript notation is
/// preferred over `prefix(through:)`.
///
/// if let i = numbers.index(of: 40) {
/// print(numbers[...i])
/// }
/// // Prints "[10, 20, 30, 40]"
///
/// - Parameter end: The index of the last element to include in the
/// resulting subsequence. `end` must be a valid index of the collection
/// that is not equal to the `endIndex` property.
/// - Returns: A subsequence up to, and including, the `end` position.
///
/// - Complexity: O(1)
@inlinable
public func prefix(through position: Index) -> SubSequence {
return prefix(upTo: index(after: position))
}
/// Returns the longest possible subsequences of the collection, in order,
/// that don't contain elements satisfying the given predicate.
///
/// The resulting array consists of at most `maxSplits + 1` subsequences.
/// Elements that are used to split the sequence are not returned as part of
/// any subsequence.
///
/// The following examples show the effects of the `maxSplits` and
/// `omittingEmptySubsequences` parameters when splitting a string using a
/// closure that matches spaces. The first use of `split` returns each word
/// that was originally separated by one or more spaces.
///
/// let line = "BLANCHE: I don't want realism. I want magic!"
/// print(line.split(whereSeparator: { $0 == " " }))
/// // Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"
///
/// The second example passes `1` for the `maxSplits` parameter, so the
/// original string is split just once, into two new strings.
///
/// print(line.split(maxSplits: 1, whereSeparator: { $0 == " " }))
/// // Prints "["BLANCHE:", " I don\'t want realism. I want magic!"]"
///
/// The final example passes `false` for the `omittingEmptySubsequences`
/// parameter, so the returned array contains empty strings where spaces
/// were repeated.
///
/// print(line.split(omittingEmptySubsequences: false, whereSeparator: { $0 == " " }))
/// // Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"
///
/// - Parameters:
/// - maxSplits: The maximum number of times to split the collection, or
/// one less than the number of subsequences to return. If
/// `maxSplits + 1` subsequences are returned, the last one is a suffix
/// of the original collection containing the remaining elements.
/// `maxSplits` must be greater than or equal to zero. The default value
/// is `Int.max`.
/// - omittingEmptySubsequences: If `false`, an empty subsequence is
/// returned in the result for each pair of consecutive elements
/// satisfying the `isSeparator` predicate and for each element at the
/// start or end of the collection satisfying the `isSeparator`
/// predicate. The default value is `true`.
/// - isSeparator: A closure that takes an element as an argument and
/// returns a Boolean value indicating whether the collection should be
/// split at that element.
/// - Returns: An array of subsequences, split from this collection's
/// elements.
@inlinable
public func split(
maxSplits: Int = Int.max,
omittingEmptySubsequences: Bool = true,
whereSeparator isSeparator: (Element) throws -> Bool
) rethrows -> [SubSequence] {
// TODO: swift-3-indexing-model - review the following
_precondition(maxSplits >= 0, "Must take zero or more splits")
var result: [SubSequence] = []
var subSequenceStart: Index = startIndex
func appendSubsequence(end: Index) -> Bool {
if subSequenceStart == end && omittingEmptySubsequences {
return false
}
result.append(self[subSequenceStart..<end])
return true
}
if maxSplits == 0 || isEmpty {
_ = appendSubsequence(end: endIndex)
return result
}
var subSequenceEnd = subSequenceStart
let cachedEndIndex = endIndex
while subSequenceEnd != cachedEndIndex {
if try isSeparator(self[subSequenceEnd]) {
let didAppend = appendSubsequence(end: subSequenceEnd)
formIndex(after: &subSequenceEnd)
subSequenceStart = subSequenceEnd
if didAppend && result.count == maxSplits {
break
}
continue
}
formIndex(after: &subSequenceEnd)
}
if subSequenceStart != cachedEndIndex || !omittingEmptySubsequences {
result.append(self[subSequenceStart..<cachedEndIndex])
}
return result
}
}
extension Collection where Element : Equatable {
/// Returns the longest possible subsequences of the collection, in order,
/// around elements equal to the given element.
///
/// The resulting array consists of at most `maxSplits + 1` subsequences.
/// Elements that are used to split the collection are not returned as part
/// of any subsequence.
///
/// The following examples show the effects of the `maxSplits` and
/// `omittingEmptySubsequences` parameters when splitting a string at each
/// space character (" "). The first use of `split` returns each word that
/// was originally separated by one or more spaces.
///
/// let line = "BLANCHE: I don't want realism. I want magic!"
/// print(line.split(separator: " "))
/// // Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"
///
/// The second example passes `1` for the `maxSplits` parameter, so the
/// original string is split just once, into two new strings.
///
/// print(line.split(separator: " ", maxSplits: 1))
/// // Prints "["BLANCHE:", " I don\'t want realism. I want magic!"]"
///
/// The final example passes `false` for the `omittingEmptySubsequences`
/// parameter, so the returned array contains empty strings where spaces
/// were repeated.
///
/// print(line.split(separator: " ", omittingEmptySubsequences: false))
/// // Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"
///
/// - Parameters:
/// - separator: The element that should be split upon.
/// - maxSplits: The maximum number of times to split the collection, or
/// one less than the number of subsequences to return. If
/// `maxSplits + 1` subsequences are returned, the last one is a suffix
/// of the original collection containing the remaining elements.
/// `maxSplits` must be greater than or equal to zero. The default value
/// is `Int.max`.
/// - omittingEmptySubsequences: If `false`, an empty subsequence is
/// returned in the result for each consecutive pair of `separator`
/// elements in the collection and for each instance of `separator` at
/// the start or end of the collection. If `true`, only nonempty
/// subsequences are returned. The default value is `true`.
/// - Returns: An array of subsequences, split from this collection's
/// elements.
@inlinable
public func split(
separator: Element,
maxSplits: Int = Int.max,
omittingEmptySubsequences: Bool = true
) -> [SubSequence] {
// TODO: swift-3-indexing-model - review the following
return split(
maxSplits: maxSplits,
omittingEmptySubsequences: omittingEmptySubsequences,
whereSeparator: { $0 == separator })
}
}
extension Collection where SubSequence == Self {
/// Removes and returns the first element of the collection.
///
/// The collection must not be empty.
///
/// - Returns: The first element of the collection.
///
/// - Complexity: O(1)
@inlinable
@discardableResult
public mutating func removeFirst() -> Element {
// TODO: swift-3-indexing-model - review the following
_precondition(!isEmpty, "Can't remove items from an empty collection")
let element = first!
self = self[index(after: startIndex)..<endIndex]
return element
}
/// Removes the specified number of elements from the beginning of the
/// collection.
///
/// - Parameter n: The number of elements to remove. `n` must be greater than
/// or equal to zero, and must be less than or equal to the number of
/// elements in the collection.
///
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*).
@inlinable
public mutating func removeFirst(_ n: Int) {
if n == 0 { return }
_precondition(n >= 0, "Number of elements to remove should be non-negative")
_precondition(count >= n,
"Can't remove more items from a collection than it contains")
self = self[index(startIndex, offsetBy: n)..<endIndex]
}
}
extension Collection {
@inlinable
public func _preprocessingPass<R>(
_ preprocess: () throws -> R
) rethrows -> R? {
return try preprocess()
}
}
extension Collection {
// FIXME: <rdar://problem/34142121>
// This typealias should be removed as it predates the source compatibility
// guarantees of Swift 3, but it cannot due to a bug.
@available(*, unavailable, renamed: "Iterator")
public typealias Generator = Iterator
@available(swift, deprecated: 3.2, renamed: "Element")
public typealias _Element = Element
@available(*, deprecated, message: "all index distances are now of type Int")
public func index<T: BinaryInteger>(_ i: Index, offsetBy n: T) -> Index {
return index(i, offsetBy: Int(n))
}
@available(*, deprecated, message: "all index distances are now of type Int")
public func formIndex<T: BinaryInteger>(_ i: inout Index, offsetBy n: T) {
return formIndex(&i, offsetBy: Int(n))
}
@available(*, deprecated, message: "all index distances are now of type Int")
public func index<T: BinaryInteger>(_ i: Index, offsetBy n: T, limitedBy limit: Index) -> Index? {
return index(i, offsetBy: Int(n), limitedBy: limit)
}
@available(*, deprecated, message: "all index distances are now of type Int")
public func formIndex<T: BinaryInteger>(_ i: inout Index, offsetBy n: T, limitedBy limit: Index) -> Bool {
return formIndex(&i, offsetBy: Int(n), limitedBy: limit)
}
@available(*, deprecated, message: "all index distances are now of type Int")
public func distance<T: BinaryInteger>(from start: Index, to end: Index) -> T {
return numericCast(distance(from: start, to: end) as Int)
}
}
| 91b7380e1696c9cd770532880d64772b | 38.190668 | 112 | 0.64045 | false | false | false | false |
rodrigoff/hackingwithswift | refs/heads/master | project15/Project15/ViewController.swift | mit | 1 | //
// ViewController.swift
// Project15
//
// Created by Rodrigo F. Fernandes on 7/24/17.
// Copyright © 2017 Rodrigo F. Fernandes. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var tap: UIButton!
var imageView: UIImageView!
var currentAnimation = 0
override func viewDidLoad() {
super.viewDidLoad()
imageView = UIImageView(image: UIImage(named: "penguin"))
imageView.center = CGPoint(x: 512, y: 384)
view.addSubview(imageView)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func tapped(_ sender: UIButton) {
tap.isHidden = true
UIView.animate(withDuration: 1, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 5, options: [],
animations: { [unowned self] in
switch self.currentAnimation {
case 0:
self.imageView.transform = CGAffineTransform(scaleX: 2, y: 2)
case 1:
self.imageView.transform = CGAffineTransform.identity
case 2:
self.imageView.transform = CGAffineTransform(translationX: -256, y: -256)
case 3:
self.imageView.transform = CGAffineTransform.identity
case 4:
self.imageView.transform = CGAffineTransform(rotationAngle: CGFloat.pi)
case 5:
self.imageView.transform = CGAffineTransform.identity
case 6:
self.imageView.alpha = 0.1
self.imageView.backgroundColor = UIColor.green
case 7:
self.imageView.alpha = 1
self.imageView.backgroundColor = UIColor.clear
default:
break
}
}) { [unowned self] (finished: Bool) in
self.tap.isHidden = false
}
currentAnimation += 1
if currentAnimation > 7 {
currentAnimation = 0
}
}
}
| 73cfcf09f7b2bdd0787e6f2190c6ce81 | 33.246575 | 117 | 0.4876 | false | false | false | false |
tavultesoft/keymanweb | refs/heads/master | ios/tools/KeyboardCalibrator/KeyboardCalibrator/DummyInputViewController.swift | apache-2.0 | 1 | //
// DummyInputViewController.swift
// DefaultKeyboardHost
//
// Created by Joshua Horton on 1/13/20.
// Copyright © 2020 SIL International. All rights reserved.
//
import Foundation
import UIKit
private class CustomInputView: UIInputView {
var height: CGFloat
var inset: CGFloat
var innerView: UIView!
var insetView: UIView!
var heightLabel: UILabel!
var insetHeightLabel: UILabel!
init(height: CGFloat, inset: CGFloat) {
self.height = height
self.inset = inset
super.init(frame: CGRect.zero, inputViewStyle: .keyboard)
}
override var intrinsicContentSize: CGSize {
get {
return CGSize(width: UIScreen.main.bounds.width, height: height > 0 ? height + inset : 100)
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setConstraints() {
var guide: UILayoutGuide
if #available(iOS 11.0, *) {
guide = self.safeAreaLayoutGuide
} else {
guide = self.layoutMarginsGuide
}
if height != 0 {
innerView.heightAnchor.constraint(equalToConstant: height).isActive = true
} else {
innerView.heightAnchor.constraint(equalTo: guide.heightAnchor).isActive = true
}
if #available(iOS 11.0, *) {
innerView.widthAnchor.constraint(equalTo: guide.widthAnchor).isActive = true
innerView.leftAnchor.constraint(equalTo: guide.leftAnchor).isActive = true
insetView.widthAnchor.constraint(equalTo: guide.widthAnchor).isActive = true
} else {
innerView.widthAnchor.constraint(equalTo: self.widthAnchor).isActive = true
innerView.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true
insetView.widthAnchor.constraint(equalTo: self.widthAnchor).isActive = true
}
innerView.bottomAnchor.constraint(equalTo: insetView.topAnchor).isActive = true
insetView.heightAnchor.constraint(equalToConstant: inset).isActive = true
insetView.bottomAnchor.constraint(equalTo: guide.bottomAnchor).isActive = true
}
func load() {
innerView = UIView()
innerView.backgroundColor = .red
innerView.translatesAutoresizingMaskIntoConstraints = false
heightLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 21))
heightLabel.text = "Hello World"
innerView.addSubview(heightLabel)
self.addSubview(innerView)
insetView = UIView()
insetView.backgroundColor = .green
insetView.translatesAutoresizingMaskIntoConstraints = false
insetHeightLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 21))
insetHeightLabel.text = "(0.0, \(inset))"
insetView.addSubview(insetHeightLabel)
self.addSubview(insetView)
}
override func layoutSubviews() {
super.layoutSubviews()
if innerView.bounds.size != CGSize.zero {
heightLabel.text = "\(innerView.bounds.size)"
} else {
heightLabel.text = "\(intrinsicContentSize)"
}
}
}
class DummyInputViewController: UIInputViewController {
var kbdHeight: CGFloat
var insetHeight: CGFloat
// The app group used to access common UserDefaults settings.
static let appGroup = "group.horton.kmtesting"
static var keyboardHeightDefault: CGFloat {
get {
let userDefaults = UserDefaults(suiteName: DummyInputViewController.appGroup)!
return (userDefaults.object(forKey: "height") as? CGFloat) ?? 0
}
set(value) {
let userDefaults = UserDefaults(suiteName: DummyInputViewController.appGroup)!
userDefaults.set(value, forKey: "height")
}
}
@IBOutlet var nextKeyboardButton: UIButton!
var asSystemKeyboard: Bool = false
// This is the one used to initialize the keyboard as the app extension, marking "system keyboard" mode.
convenience init() {
// Retrieve kbd height from app group!
let userDefaults = UserDefaults(suiteName: DummyInputViewController.appGroup)!
let height = userDefaults.float(forKey: "height")
self.init(height: CGFloat(height))
asSystemKeyboard = true
}
init(height: CGFloat, inset: CGFloat = 0) {
kbdHeight = height
insetHeight = inset
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open override func loadView() {
let baseView = CustomInputView(height: kbdHeight, inset: insetHeight)
baseView.backgroundColor = .blue
baseView.translatesAutoresizingMaskIntoConstraints = false
self.inputView = baseView
}
open override func viewDidLoad() {
let baseView = self.inputView as! CustomInputView
// Perform custom UI setup here
baseView.load()
baseView.setConstraints()
// Adds a very basic "Next keyboard" button to ensure we can always swap keyboards, even on iPhone SE.
self.nextKeyboardButton = UIButton(type: .system)
self.nextKeyboardButton.setTitle(NSLocalizedString("Next Keyboard", comment: "Title for 'Next Keyboard' button"), for: [])
self.nextKeyboardButton.sizeToFit()
self.nextKeyboardButton.translatesAutoresizingMaskIntoConstraints = false
self.nextKeyboardButton.addTarget(self, action: #selector(handleInputModeList(from:with:)), for: .allTouchEvents)
self.view.addSubview(self.nextKeyboardButton)
var guide: UILayoutGuide
if #available(iOS 11.0, *) {
guide = self.view.safeAreaLayoutGuide
self.nextKeyboardButton.isHidden = !self.needsInputModeSwitchKey || !asSystemKeyboard
} else {
guide = self.view.layoutMarginsGuide
self.nextKeyboardButton.isHidden = false // Seems buggy to vary, and it matters greatly on older devices.
}
self.nextKeyboardButton.leftAnchor.constraint(equalTo: guide.leftAnchor).isActive = true
self.nextKeyboardButton.bottomAnchor.constraint(equalTo: guide.bottomAnchor).isActive = true
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
}
}
| ca3dbdf6a1b72cbae4fddfa6a37f92b9 | 29.936842 | 126 | 0.718612 | false | false | false | false |
johndpope/Palettes | refs/heads/master | Palettes/ViewController.swift | mit | 1 | //
// ViewController.swift
// Palettes
//
// Created by Amit Burstein on 11/26/14.
// Copyright (c) 2014 Amit Burstein. All rights reserved.
//
import Cocoa
class ViewController: NSViewController, NSTableViewDataSource, NSTableViewDelegate, NSWindowDelegate {
// MARK: Properties
let DefaultNumResults = 20
let RowHeight = 110
let PaletteViewCornerRadius = 5
let CopiedViewAnimationSpringBounciness = 20
let CopiedViewAnimationSpringSpeed = 15
let CopiedViewReverseAnimationSpringBounciness = 10
let CopiedViewReverseAnimationSpringSpeed = 15
let CopiedViewAnimationToValue = -20
let CopiedViewReverseAnimationToValue = -40
let CopiedViewHeight = 40
let CopiedViewBackgroundColor = "#67809FF5"
let CopiedViewText = "Copied!"
let CopiedViewTextSize = 12
let CopiedViewTextColor = "#ECF0F1"
let TableTextHeight = 40
let TableTextSize = 16
let TableTextColor = "#bdc3c7"
let TableTextNoResults = "No Results Found"
let TableTextError = "Error Loading Palettes :("
let PaletteViewBorderColor = NSColor.gridColor().CGColor
let PaletteViewBorderWidth = 0.2
let PaletteCellIdentifier = "PaletteCell"
let CopyTypeKey = "CopyType"
let PalettesEndpoint = "http://www.colourlovers.com/api/palettes"
let TopPalettesEndpoint = "http://www.colourlovers.com/api/palettes/top"
var manager: AFHTTPRequestOperationManager!
var preferences: NSUserDefaults!
var showingTopPalettes: Bool!
var scrolledToBottom: Bool!
var noResults: Bool!
var lastEndpoint: String!
var lastParams: [String:String]!
var resultsPage: Int!
var palettes: [Palette]!
var copyType: Int!
var copiedView: NSView!
var copiedViewAnimation: POPSpringAnimation!
var copiedViewReverseAnimation: POPSpringAnimation!
var fadeAnimation: POPBasicAnimation!
var fadeReverseAnimation: POPBasicAnimation!
var tableText: NSTextField!
@IBOutlet weak var tableView: MainTableView!
@IBOutlet weak var scrollView: NSScrollView!
// MARK: Structs
struct Palette {
var url: String
var colors: [String]
var title: String
}
// MARK: Initialization
required init?(coder: NSCoder) {
super.init(coder: coder)
manager = AFHTTPRequestOperationManager()
preferences = NSUserDefaults.standardUserDefaults()
showingTopPalettes = true
scrolledToBottom = false
noResults = false
lastEndpoint = ""
lastParams = [String:String]()
resultsPage = 0
palettes = []
copyType = 0
copiedView = NSView()
copiedViewAnimation = POPSpringAnimation()
copiedViewReverseAnimation = POPSpringAnimation()
fadeAnimation = POPBasicAnimation()
fadeReverseAnimation = POPBasicAnimation()
tableText = NSTextField()
}
// MARK: NSViewController
override func viewDidLoad() {
if #available(OSX 10.10, *) {
super.viewDidLoad()
} else {
// Fallback on earlier versions
}
let window = NSApplication.sharedApplication().windows[0] as NSWindow
window.delegate = self
NSNotificationCenter.defaultCenter().addObserver(self, selector: "scrollViewDidScroll:", name: NSViewBoundsDidChangeNotification, object: scrollView.contentView)
setupCopiedView()
setupTableText()
setupAnimations()
getPalettes(endpoint: TopPalettesEndpoint, params: nil)
}
override func viewDidAppear() {
if let lastCopyType = preferences.valueForKey(CopyTypeKey) as? Int {
copyType = lastCopyType
let window = NSApplication.sharedApplication().windows[0] as NSWindow
window.delegate = self
let popUpButton = window.toolbar?.items[1].view as! NSPopUpButton
popUpButton.selectItemAtIndex(copyType)
}
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
// MARK: NSTableViewDataSource
func numberOfRowsInTableView(tableView: NSTableView) -> Int {
return palettes.count
}
// MARK: NSTableViewDelegate
func tableView(tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
return CGFloat(RowHeight)
}
func tableView(tableView: NSTableView, selectionIndexesForProposedSelection proposedSelectionIndexes: NSIndexSet) -> NSIndexSet {
return NSIndexSet()
}
func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn?, row: Int) -> NSView? {
// Create and get references to other important items
let cell = tableView.makeViewWithIdentifier(PaletteCellIdentifier, owner: self) as! PaletteTableCellView
let paletteView = cell.paletteView
let openButton = cell.openButton
let palette = palettes[row]
// Set cell properties
cell.textField?.stringValue = palette.title
cell.colors = palette.colors
cell.url = palette.url
cell.addTrackingArea(NSTrackingArea(rect: NSZeroRect, options: [.ActiveInActiveApp, .InVisibleRect, .MouseEnteredAndExited], owner: cell, userInfo: nil))
// Set cell's open button properties
cell.openButton.wantsLayer = true
cell.openButton.layer?.opacity = 0
// Set cell's palette view properties
paletteView.wantsLayer = true
paletteView.layer?.cornerRadius = CGFloat(PaletteViewCornerRadius)
paletteView.layer?.borderColor = PaletteViewBorderColor
paletteView.layer?.borderWidth = CGFloat(PaletteViewBorderWidth)
paletteView.subviews = []
paletteView.addTrackingArea(NSTrackingArea(rect: NSZeroRect, options: [.ActiveAlways , .InVisibleRect ,.CursorUpdate], owner: cell, userInfo: nil))
// Calculate width and height of each color view
let colorViewWidth = ceil(paletteView.bounds.width / CGFloat(cell.colors.count))
let colorViewHeight = paletteView.bounds.height
// Create and append color views to palette view
for i in 0..<cell.colors.count {
let colorView = NSView(frame: CGRectMake(CGFloat(i) * colorViewWidth, 0, colorViewWidth, colorViewHeight))
colorView.wantsLayer = true
colorView.layer?.backgroundColor = NSColor(rgba: "#\(cell.colors[i])").CGColor
paletteView.addSubview(colorView)
}
return cell
}
// MARK: IBActions
@IBAction func searchFieldChanged(searchField: NSSearchField!) {
resultsPage = 0
if searchField.stringValue == "" {
if !showingTopPalettes {
getPalettes(endpoint: TopPalettesEndpoint, params: nil)
showingTopPalettes = true
}
} else {
if let match = searchField.stringValue.rangeOfString("^#?[0-9a-fA-F]{6}$", options: .RegularExpressionSearch) {
var query = searchField.stringValue
if query.hasPrefix("#") {
query = query[1...6]
}
getPalettes(endpoint: PalettesEndpoint, params: ["hex": query])
} else {
getPalettes(endpoint: PalettesEndpoint, params: ["keywords": searchField.stringValue])
}
showingTopPalettes = false
}
}
@IBAction func copyTypeChanged(button: NSPopUpButton!) {
copyType = button.indexOfSelectedItem
preferences.setInteger(copyType, forKey: CopyTypeKey)
preferences.synchronize()
}
// MARK: Functions
func setupCopiedView() {
// Set up copied view text
let copiedViewTextField = NSTextField(frame: CGRectMake(0, 0, view.bounds.width, CGFloat(CopiedViewHeight)))
copiedViewTextField.bezeled = false
copiedViewTextField.drawsBackground = false
copiedViewTextField.editable = false
copiedViewTextField.selectable = false
// copiedViewTextField.alignment = .CenterTextAlignment
copiedViewTextField.textColor = NSColor(rgba: CopiedViewTextColor)
copiedViewTextField.font = NSFont.boldSystemFontOfSize(CGFloat(CopiedViewTextSize))
copiedViewTextField.stringValue = CopiedViewText
// Set up copied view
copiedView = NSView(frame: CGRectMake(0, CGFloat(-CopiedViewHeight), view.bounds.width, CGFloat(CopiedViewHeight)))
copiedView.addSubview(copiedViewTextField)
copiedView.wantsLayer = true
copiedView.layer?.backgroundColor = NSColor(rgba: CopiedViewBackgroundColor).CGColor
view.addSubview(copiedView)
}
func setupTableText() {
// Set up table text
tableText = NSTextField(frame: CGRectMake(0, view.bounds.height / 2 - CGFloat(TableTextHeight) / 4, view.bounds.width, CGFloat(TableTextHeight)))
tableText.bezeled = false
tableText.drawsBackground = false
tableText.editable = false
tableText.selectable = false
//tableText.alignment = .CenterTextAlignment
tableText.textColor = NSColor(rgba: TableTextColor)
tableText.font = NSFont.boldSystemFontOfSize(CGFloat(TableTextSize))
}
func setupAnimations() {
// Set up copied view animation
copiedViewAnimation.property = POPAnimatableProperty.propertyWithName(kPOPLayerPositionY) as! POPAnimatableProperty
copiedViewAnimation.toValue = CopiedViewAnimationToValue
copiedViewAnimation.springBounciness = CGFloat(CopiedViewAnimationSpringBounciness)
copiedViewAnimation.springSpeed = CGFloat(CopiedViewAnimationSpringSpeed)
// Set up copied view reverse animation
copiedViewReverseAnimation.property = POPAnimatableProperty.propertyWithName(kPOPLayerPositionY) as! POPAnimatableProperty
copiedViewReverseAnimation.toValue = CopiedViewReverseAnimationToValue
copiedViewReverseAnimation.springBounciness = CGFloat(CopiedViewReverseAnimationSpringBounciness)
copiedViewReverseAnimation.springSpeed = CGFloat(CopiedViewReverseAnimationSpringSpeed)
// Set up fade animation
fadeAnimation.property = POPAnimatableProperty.propertyWithName(kPOPLayerOpacity) as! POPAnimatableProperty
fadeAnimation.fromValue = 0
fadeAnimation.toValue = 1
// Set up fade reverse animation
fadeReverseAnimation.property = POPAnimatableProperty.propertyWithName(kPOPLayerOpacity) as! POPAnimatableProperty
fadeReverseAnimation.fromValue = 1
fadeReverseAnimation.toValue = 0
}
func getPalettes(endpoint endpoint: String, params: [String:String]?) {
// Add default keys to params
var params = params
if params == nil {
params = [String:String]()
}
params?.updateValue("json", forKey: "format")
params?.updateValue(String(DefaultNumResults), forKey: "numResults")
// No request if endpoint ans params are unchanged
if endpoint == lastEndpoint && params! == lastParams {
return
}
// Make the request
manager.GET(endpoint, parameters: params, success: { operation, responseObject in
// Save the latest endpoint and params
self.lastEndpoint = operation.request.URL!.absoluteString
self.lastParams = params!
// Parse the response object
if let jsonArray = responseObject as? [NSDictionary] {
// Remove all palettes if this is a new query
if params?.indexForKey("resultOffset") == nil {
self.palettes.removeAll()
}
// Keep track of whether any results were returned
// Show and hide table text accordingly
self.noResults = jsonArray.count == 0
if self.noResults! {
if params?.indexForKey("resultOffset") == nil {
self.showErrorMessage(self.TableTextNoResults)
}
return
} else {
self.tableText.removeFromSuperview()
self.tableText.layer?.pop_addAnimation(self.fadeReverseAnimation, forKey: nil)
}
// Parse JSON for each palette and add to palettes array
for paletteInfo in jsonArray {
let url = paletteInfo.objectForKey("url") as? String
let colors = paletteInfo.objectForKey("colors") as? [String]
let title = paletteInfo.objectForKey("title") as? String
self.palettes.append(Palette(url: url!, colors: colors!, title: title!))
}
// Reload table in main queue and scroll to top if this is a new query
dispatch_async(dispatch_get_main_queue(), {
if params?.indexForKey("resultOffset") == nil {
self.tableView.scrollRowToVisible(0)
self.tableView.layer?.pop_addAnimation(self.fadeAnimation, forKey: nil)
} else {
self.scrolledToBottom = false
}
self.tableView.reloadData()
})
} else {
self.showErrorMessage(self.TableTextError)
}
}) { _, _ in
self.showErrorMessage(self.TableTextError)
}
}
func showErrorMessage(errorMessage: String) {
palettes.removeAll()
tableText.stringValue = errorMessage
view.addSubview(tableText)
tableText.layer?.pop_addAnimation(fadeAnimation, forKey: nil)
dispatch_async(dispatch_get_main_queue(), {
self.tableView.reloadData()
self.tableView.layer?.pop_addAnimation(self.fadeReverseAnimation, forKey: nil)
})
}
func scrollViewDidScroll(notification: NSNotification) {
let currentPosition = CGRectGetMaxY(scrollView.contentView.visibleRect)
let contentHeight = tableView.bounds.size.height - 5;
if !noResults && !scrolledToBottom && currentPosition > contentHeight - 2 {
scrolledToBottom = true
resultsPage = resultsPage + 1
var params = lastParams
params.updateValue(String(DefaultNumResults * resultsPage), forKey: "resultOffset")
getPalettes(endpoint: lastEndpoint, params: params)
}
}
}
| a326909c1630c47ce62abca81db11892 | 39.941667 | 169 | 0.643463 | false | false | false | false |
ontouchstart/swift3-playground | refs/heads/playgroundbook | Learn to Code 2.playgroundbook/Contents/Chapters/Document9.playgroundchapter/Pages/Exercise1.playgroundpage/Contents.swift | mit | 1 | //#-hidden-code
//
// Contents.swift
//
// Copyright (c) 2016 Apple Inc. All Rights Reserved.
//
//#-end-hidden-code
/*:
**Goal:** Create a [variable](glossary://variable) to track the number of gems collected.
For this puzzle, you’ll need to keep track of how many gems Byte collects. This value should be 0 in the beginning; after Byte picks up the first gem, the value should change to 1.
To [declare](glossary://declaration) (create) a variable, use `var` and give your variable a name. Then use the [assignment operator](glossary://assignment%20operator) (`=`) to set an initial value for the variable.
var myAge = 15
Once a variable has been declared, you may [assign](glossary://assignment) it a new value at any time:
myAge = 16
1. steps: Set the initial value of `gemCounter` to `0`.
2. Move to the gem and pick it up.
3. Set the value of `gemCounter` to `1`.
*/
//#-hidden-code
playgroundPrologue()
//#-end-hidden-code
//#-code-completion(everything, hide)
//#-code-completion(currentmodule, show)
//#-code-completion(identifier, show, isOnOpenSwitch, moveForward(), turnLeft(), turnRight(), collectGem(), toggleSwitch(), isOnGem, isOnClosedSwitch, var, =, isBlocked, true, false, isBlockedLeft, &&, ||, !, isBlockedRight, if, func, for, while)
var gemCounter = /*#-editable-code yourFuncName*/<#T##Set the initial value##Int#>/*#-end-editable-code*/
//#-editable-code Tap to enter code
//#-end-editable-code
//#-hidden-code
finalGemCount = gemCounter
playgroundEpilogue()
//#-end-hidden-code
| 55c8793e5b99fb57eb918d6081cdc26c | 38.25641 | 246 | 0.708034 | false | false | false | false |
miletliyusuf/VisionDetect | refs/heads/master | VisionDetect/VisionDetect.swift | mit | 1 | //
// VisionDetect.swift
// VisionDetect
//
// Created by Yusuf Miletli on 8/21/17.
// Copyright © 2017 Miletli. All rights reserved.
//
import Foundation
import UIKit
import CoreImage
import AVFoundation
import ImageIO
public protocol VisionDetectDelegate: AnyObject {
func didNoFaceDetected()
func didFaceDetected()
func didSmile()
func didNotSmile()
func didBlinked()
func didNotBlinked()
func didWinked()
func didNotWinked()
func didLeftEyeClosed()
func didLeftEyeOpened()
func didRightEyeClosed()
func didRightEyeOpened()
}
///Makes every method is optional
public extension VisionDetectDelegate {
func didNoFaceDetected() { }
func didFaceDetected() { }
func didSmile() { }
func didNotSmile() { }
func didBlinked() { }
func didNotBlinked() { }
func didWinked() { }
func didNotWinked() { }
func didLeftEyeClosed() { }
func didLeftEyeOpened() { }
func didRightEyeClosed() { }
func didRightEyeOpened() { }
}
public enum VisionDetectGestures {
case face
case noFace
case smile
case noSmile
case blink
case noBlink
case wink
case noWink
case leftEyeClosed
case noLeftEyeClosed
case rightEyeClosed
case noRightEyeClosed
}
open class VisionDetect: NSObject {
public weak var delegate: VisionDetectDelegate? = nil
public enum DetectorAccuracy {
case BatterySaving
case HigherPerformance
}
public enum CameraDevice {
case ISightCamera
case FaceTimeCamera
}
public typealias TakenImageStateHandler = ((UIImage) -> Void)
public var onlyFireNotificatonOnStatusChange : Bool = true
public var visageCameraView : UIView = UIView()
//Private properties of the detected face that can be accessed (read-only) by other classes.
private(set) var faceDetected : Bool?
private(set) var faceBounds : CGRect?
private(set) var faceAngle : CGFloat?
private(set) var faceAngleDifference : CGFloat?
private(set) var leftEyePosition : CGPoint?
private(set) var rightEyePosition : CGPoint?
private(set) var mouthPosition : CGPoint?
private(set) var hasSmile : Bool?
private(set) var isBlinking : Bool?
private(set) var isWinking : Bool?
private(set) var leftEyeClosed : Bool?
private(set) var rightEyeClosed : Bool?
//Private variables that cannot be accessed by other classes in any way.
private var faceDetector : CIDetector?
private var videoDataOutput : AVCaptureVideoDataOutput?
private var videoDataOutputQueue : DispatchQueue?
private var cameraPreviewLayer : AVCaptureVideoPreviewLayer?
private var captureSession : AVCaptureSession = AVCaptureSession()
private let notificationCenter : NotificationCenter = NotificationCenter.default
private var currentOrientation : Int?
private let stillImageOutput = AVCapturePhotoOutput()
private var detectedGestures:[VisionDetectGestures] = []
private var takenImageHandler: TakenImageStateHandler?
private var takenImage: UIImage? {
didSet {
if let image = self.takenImage {
takenImageHandler?(image)
}
}
}
public init(cameraPosition: CameraDevice, optimizeFor: DetectorAccuracy) {
super.init()
currentOrientation = convertOrientation(deviceOrientation: UIDevice.current.orientation)
switch cameraPosition {
case .FaceTimeCamera : self.captureSetup(position: AVCaptureDevice.Position.front)
case .ISightCamera : self.captureSetup(position: AVCaptureDevice.Position.back)
}
var faceDetectorOptions : [String : AnyObject]?
switch optimizeFor {
case .BatterySaving : faceDetectorOptions = [CIDetectorAccuracy : CIDetectorAccuracyLow as AnyObject]
case .HigherPerformance : faceDetectorOptions = [CIDetectorAccuracy : CIDetectorAccuracyHigh as AnyObject]
}
self.faceDetector = CIDetector(ofType: CIDetectorTypeFace, context: nil, options: faceDetectorOptions)
}
public func addTakenImageChangeHandler(handler: TakenImageStateHandler?) {
self.takenImageHandler = handler
}
//MARK: SETUP OF VIDEOCAPTURE
public func beginFaceDetection() {
self.captureSession.startRunning()
setupSaveToCameraRoll()
}
public func endFaceDetection() {
self.captureSession.stopRunning()
}
private func setupSaveToCameraRoll() {
if captureSession.canAddOutput(stillImageOutput) {
captureSession.addOutput(stillImageOutput)
}
}
public func saveTakenImageToPhotos() {
if let image = self.takenImage {
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
}
}
public func takeAPicture() {
if self.stillImageOutput.connection(with: .video) != nil {
let settings = AVCapturePhotoSettings()
let previewPixelType = settings.availablePreviewPhotoPixelFormatTypes.first ?? nil
let previewFormat = [String(kCVPixelBufferPixelFormatTypeKey): previewPixelType,
String(kCVPixelBufferWidthKey): 160,
String(kCVPixelBufferHeightKey): 160]
settings.previewPhotoFormat = previewFormat as [String : Any]
self.stillImageOutput.capturePhoto(with: settings, delegate: self)
}
}
private func captureSetup(position: AVCaptureDevice.Position) {
var captureError: NSError?
var captureDevice: AVCaptureDevice?
let devices = AVCaptureDevice.DiscoverySession(
deviceTypes: [.builtInWideAngleCamera],
mediaType: .video,
position: position
).devices
for testedDevice in devices {
if ((testedDevice as AnyObject).position == position) {
captureDevice = testedDevice
}
}
if (captureDevice == nil) {
captureDevice = AVCaptureDevice.default(for: .video)
}
var deviceInput : AVCaptureDeviceInput?
do {
if let device = captureDevice {
deviceInput = try AVCaptureDeviceInput(device: device)
}
} catch let error as NSError {
captureError = error
deviceInput = nil
}
captureSession.sessionPreset = .high
if (captureError == nil) {
if let input = deviceInput,
captureSession.canAddInput(input) {
captureSession.addInput(input)
}
self.videoDataOutput = AVCaptureVideoDataOutput()
self.videoDataOutput?.videoSettings = [
String(kCVPixelBufferPixelFormatTypeKey): Int(kCVPixelFormatType_32BGRA)
]
self.videoDataOutput?.alwaysDiscardsLateVideoFrames = true
self.videoDataOutputQueue = DispatchQueue(label: "VideoDataOutputQueue")
self.videoDataOutput?.setSampleBufferDelegate(self, queue: self.videoDataOutputQueue)
if let output = self.videoDataOutput,
captureSession.canAddOutput(output) {
captureSession.addOutput(output)
}
}
visageCameraView.frame = UIScreen.main.bounds
let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
previewLayer.frame = UIScreen.main.bounds
previewLayer.videoGravity = .resizeAspectFill
visageCameraView.layer.addSublayer(previewLayer)
}
private func addItemToGestureArray(item:VisionDetectGestures) {
if !self.detectedGestures.contains(item) {
self.detectedGestures.append(item)
}
}
var options : [String : AnyObject]?
//TODO: 🚧 HELPER TO CONVERT BETWEEN UIDEVICEORIENTATION AND CIDETECTORORIENTATION 🚧
private func convertOrientation(deviceOrientation: UIDeviceOrientation) -> Int {
var orientation: Int = 0
switch deviceOrientation {
case .portrait:
orientation = 6
case .portraitUpsideDown:
orientation = 2
case .landscapeLeft:
orientation = 3
case .landscapeRight:
orientation = 4
default : orientation = 1
}
return orientation
}
}
// MARK: - AVCapturePhotoCaptureDelegate
extension VisionDetect: AVCapturePhotoCaptureDelegate {
public func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {
if let imageData = photo.fileDataRepresentation(),
let image = UIImage(data: imageData) {
self.takenImage = image
}
}
}
// MARK: - AVCaptureVideoDataOutputSampleBufferDelegate
extension VisionDetect: AVCaptureVideoDataOutputSampleBufferDelegate {
public func captureOutput(
_ output: AVCaptureOutput,
didOutput sampleBuffer: CMSampleBuffer,
from connection: AVCaptureConnection
) {
var sourceImage = CIImage()
if takenImage == nil {
let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer)
let opaqueBuffer = Unmanaged<CVImageBuffer>.passUnretained(imageBuffer!).toOpaque()
let pixelBuffer = Unmanaged<CVPixelBuffer>.fromOpaque(opaqueBuffer).takeUnretainedValue()
sourceImage = CIImage(cvPixelBuffer: pixelBuffer, options: nil)
}
else {
if let ciImage = takenImage?.ciImage {
sourceImage = ciImage
}
}
options = [
CIDetectorSmile: true as AnyObject,
CIDetectorEyeBlink: true as AnyObject,
CIDetectorImageOrientation: 6 as AnyObject
]
let features = self.faceDetector!.features(in: sourceImage, options: options)
if (features.count != 0) {
if (onlyFireNotificatonOnStatusChange == true) {
if (self.faceDetected == false) {
self.delegate?.didFaceDetected()
self.addItemToGestureArray(item: .face)
}
} else {
self.delegate?.didFaceDetected()
self.addItemToGestureArray(item: .face)
}
self.faceDetected = true
for feature in features as! [CIFaceFeature] {
faceBounds = feature.bounds
if (feature.hasFaceAngle) {
if (faceAngle != nil) {
faceAngleDifference = CGFloat(feature.faceAngle) - faceAngle!
} else {
faceAngleDifference = CGFloat(feature.faceAngle)
}
faceAngle = CGFloat(feature.faceAngle)
}
if (feature.hasLeftEyePosition) {
leftEyePosition = feature.leftEyePosition
}
if (feature.hasRightEyePosition) {
rightEyePosition = feature.rightEyePosition
}
if (feature.hasMouthPosition) {
mouthPosition = feature.mouthPosition
}
if (feature.hasSmile) {
if (onlyFireNotificatonOnStatusChange == true) {
if (self.hasSmile == false) {
self.delegate?.didSmile()
self.addItemToGestureArray(item: .smile)
}
} else {
self.delegate?.didSmile()
self.addItemToGestureArray(item: .smile)
}
hasSmile = feature.hasSmile
} else {
if (onlyFireNotificatonOnStatusChange == true) {
if (self.hasSmile == true) {
self.delegate?.didNotSmile()
self.addItemToGestureArray(item: .noSmile)
}
} else {
self.delegate?.didNotSmile()
self.addItemToGestureArray(item: .noSmile)
}
hasSmile = feature.hasSmile
}
if (feature.leftEyeClosed || feature.rightEyeClosed) {
if (onlyFireNotificatonOnStatusChange == true) {
if (self.isWinking == false) {
self.delegate?.didWinked()
self.addItemToGestureArray(item: .wink)
}
} else {
self.delegate?.didWinked()
self.addItemToGestureArray(item: .wink)
}
isWinking = true
if (feature.leftEyeClosed) {
if (onlyFireNotificatonOnStatusChange == true) {
if (self.leftEyeClosed == false) {
self.delegate?.didLeftEyeClosed()
self.addItemToGestureArray(item: .leftEyeClosed)
}
} else {
self.delegate?.didLeftEyeClosed()
self.addItemToGestureArray(item: .leftEyeClosed)
}
leftEyeClosed = feature.leftEyeClosed
}
if (feature.rightEyeClosed) {
if (onlyFireNotificatonOnStatusChange == true) {
if (self.rightEyeClosed == false) {
self.delegate?.didRightEyeClosed()
self.addItemToGestureArray(item: .rightEyeClosed)
}
} else {
self.delegate?.didRightEyeClosed()
self.addItemToGestureArray(item: .rightEyeClosed)
}
rightEyeClosed = feature.rightEyeClosed
}
if (feature.leftEyeClosed && feature.rightEyeClosed) {
if (onlyFireNotificatonOnStatusChange == true) {
if (self.isBlinking == false) {
self.delegate?.didBlinked()
self.addItemToGestureArray(item: .blink)
}
} else {
self.delegate?.didBlinked()
self.addItemToGestureArray(item: .blink)
}
isBlinking = true
}
} else {
if (onlyFireNotificatonOnStatusChange == true) {
if (self.isBlinking == true) {
self.delegate?.didNotBlinked()
self.addItemToGestureArray(item: .noBlink)
}
if (self.isWinking == true) {
self.delegate?.didNotWinked()
self.addItemToGestureArray(item: .noWink)
}
if (self.leftEyeClosed == true) {
self.delegate?.didLeftEyeOpened()
self.addItemToGestureArray(item: .noLeftEyeClosed)
}
if (self.rightEyeClosed == true) {
self.delegate?.didRightEyeOpened()
self.addItemToGestureArray(item: .noRightEyeClosed)
}
} else {
self.delegate?.didNotBlinked()
self.addItemToGestureArray(item: .noBlink)
self.delegate?.didNotWinked()
self.addItemToGestureArray(item: .noWink)
self.delegate?.didLeftEyeOpened()
self.addItemToGestureArray(item: .noLeftEyeClosed)
self.delegate?.didRightEyeOpened()
self.addItemToGestureArray(item: .noRightEyeClosed)
}
isBlinking = false
isWinking = false
leftEyeClosed = feature.leftEyeClosed
rightEyeClosed = feature.rightEyeClosed
}
}
} else {
if (onlyFireNotificatonOnStatusChange == true) {
if (self.faceDetected == true) {
self.delegate?.didNoFaceDetected()
self.addItemToGestureArray(item: .noFace)
}
} else {
self.delegate?.didNoFaceDetected()
self.addItemToGestureArray(item: .noFace)
}
self.faceDetected = false
}
}
}
| b80bfdfebb94868b8ecd10bcd0581505 | 34.704641 | 124 | 0.564287 | false | false | false | false |
Appsaurus/Infinity | refs/heads/master | Infinity/controls/spark/SparkRefreshAnimator.swift | mit | 1 | //
// SparkRefreshAnimator.swift
// InfinitySample
//
// Created by Danis on 16/1/2.
// Copyright © 2016年 danis. All rights reserved.
//
import UIKit
extension UIColor {
convenience init(hex: Int, alpha: CGFloat) {
let red = CGFloat((hex & 0xFF0000) >> 16) / 255.0
let green = CGFloat((hex & 0xFF00) >> 8) / 255.0
let blue = CGFloat(hex & 0xFF) / 255.0
self.init(red: red, green: green, blue: blue, alpha: alpha)
}
convenience init(hex: Int) {
self.init(hex:hex, alpha:1.0)
}
static func sparkColorWithIndex(_ index: Int) -> UIColor {
switch index % 8 {
case 0:
return UIColor(hex: 0xf9b60f)
case 1:
return UIColor(hex: 0xf78a44)
case 2:
return UIColor(hex: 0xf05e4d)
case 3:
return UIColor(hex: 0xf75078)
case 4:
return UIColor(hex: 0xc973e4)
case 5:
return UIColor(hex: 0x1bbef1)
case 6:
return UIColor(hex: 0x5593f0)
case 7:
return UIColor(hex: 0x00cf98)
default:
return UIColor.clear
}
}
}
open class SparkRefreshAnimator: UIView, CustomPullToRefreshAnimator {
fileprivate var circles = [CAShapeLayer]()
var animating = false
fileprivate var positions = [CGPoint]()
public override init(frame: CGRect) {
super.init(frame: frame)
let ovalDiameter = min(frame.width,frame.height) / 8
let ovalPath = UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: ovalDiameter, height: ovalDiameter))
let count = 8
for index in 0..<count {
let circleLayer = CAShapeLayer()
circleLayer.path = ovalPath.cgPath
circleLayer.fillColor = UIColor.sparkColorWithIndex(index).cgColor
circleLayer.anchorPoint = CGPoint(x: 0.5, y: 0.5)
self.circles.append(circleLayer)
self.layer.addSublayer(circleLayer)
let angle = CGFloat(M_PI * 2) / CGFloat(count) * CGFloat(index)
let radius = min(frame.width, frame.height) * 0.4
let position = CGPoint(x: bounds.midX + sin(angle) * radius, y: bounds.midY - cos(angle) * radius)
circleLayer.position = position
positions.append(position)
}
alpha = 0
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open override func didMoveToWindow() {
super.didMoveToWindow()
if window != nil && animating {
startAnimating()
}
}
open func animateState(_ state: PullToRefreshState) {
switch state {
case .none:
alpha = 0
stopAnimating()
case .loading:
startAnimating()
case .releasing(let progress):
alpha = 1.0
updateForProgress(progress)
}
}
func updateForProgress(_ progress: CGFloat) {
let number = progress * CGFloat(circles.count)
for index in 0..<8 {
let circleLayer = circles[index]
if CGFloat(index) < number {
circleLayer.isHidden = false
}else {
circleLayer.isHidden = true
}
}
}
func startAnimating() {
animating = true
for index in 0..<8 {
applyAnimationForIndex(index)
}
}
fileprivate let CircleAnimationKey = "CircleAnimationKey"
fileprivate func applyAnimationForIndex(_ index: Int) {
let moveAnimation = CAKeyframeAnimation(keyPath: "position")
let moveV1 = NSValue(cgPoint: positions[index])
let moveV2 = NSValue(cgPoint: CGPoint(x: bounds.midX, y: bounds.midY))
let moveV3 = NSValue(cgPoint: positions[index])
moveAnimation.values = [moveV1,moveV2,moveV3]
let scaleAnimation = CAKeyframeAnimation(keyPath: "transform")
let scaleV1 = NSValue(caTransform3D: CATransform3DIdentity)
let scaleV2 = NSValue(caTransform3D: CATransform3DMakeScale(0.1, 0.1, 1.0))
let scaleV3 = NSValue(caTransform3D: CATransform3DIdentity)
scaleAnimation.values = [scaleV1,scaleV2,scaleV3]
let animationGroup = CAAnimationGroup()
animationGroup.animations = [moveAnimation,scaleAnimation]
animationGroup.duration = 1.0
animationGroup.repeatCount = 1000
animationGroup.beginTime = CACurrentMediaTime() + Double(index) * animationGroup.duration / 8 / 2
animationGroup.timingFunction = CAMediaTimingFunction(controlPoints: 1, 0.27, 0, 0.75)
let circleLayer = circles[index]
circleLayer.isHidden = false
circleLayer.add(animationGroup, forKey: CircleAnimationKey)
}
func stopAnimating() {
for circleLayer in circles {
circleLayer.removeAnimation(forKey: CircleAnimationKey)
circleLayer.transform = CATransform3DIdentity
circleLayer.isHidden = true
}
animating = false
}
}
| a296bc1cb9bbe89965ca5e60375b5ace | 32.548387 | 110 | 0.589231 | false | false | false | false |
VoIPGRID/vialer-ios | refs/heads/master | Vialer/Calling/Dialer/Controllers/DialerViewController.swift | gpl-3.0 | 1 | //
// DialerViewController.swift
// Copyright © 2017 VoIPGRID. All rights reserved.
//
import UIKit
import AVFoundation
class DialerViewController: UIViewController, SegueHandler {
enum SegueIdentifier: String {
case sipCalling = "SIPCallingSegue"
case twoStepCalling = "TwoStepCallingSegue"
case reachabilityBar = "ReachabilityBarSegue"
}
fileprivate struct Config {
struct ReachabilityBar {
static let animationDuration = 0.3
static let height: CGFloat = 30.0
}
}
// MARK: - Properties
var numberText: String? {
didSet {
if let number = numberText {
numberText = PhoneNumberUtils.cleanPhoneNumber(number)
}
numberLabel.text = numberText
setupButtons()
}
}
var sounds = [String: AVAudioPlayer]()
var lastCalledNumber: String? {
didSet {
setupButtons()
}
}
var user = SystemUser.current()!
fileprivate let reachability = ReachabilityHelper.instance.reachability!
fileprivate var notificationCenter = NotificationCenter.default
fileprivate var reachabilityChanged: NotificationToken?
fileprivate var sipDisabled: NotificationToken?
fileprivate var sipChanged: NotificationToken?
fileprivate var encryptionUsageChanged: NotificationToken?
// MARK: - Outlets
@IBOutlet weak var leftDrawerButton: UIBarButtonItem!
@IBOutlet weak var numberLabel: PasteableUILabel! {
didSet {
numberLabel.delegate = self
}
}
@IBOutlet weak var callButton: UIButton!
@IBOutlet weak var deleteButton: UIButton!
@IBOutlet weak var reachabilityBarHeigthConstraint: NSLayoutConstraint!
@IBOutlet weak var reachabilityBar: UIView!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupUI()
}
}
// MARK: - Lifecycle
extension DialerViewController {
override func viewDidLoad() {
super.viewDidLoad()
setupLayout()
setupSounds()
reachabilityChanged = notificationCenter.addObserver(descriptor: Reachability.changed) { [weak self] _ in
self?.updateReachabilityBar()
}
sipDisabled = notificationCenter.addObserver(descriptor: SystemUser.sipDisabledNotification) { [weak self] _ in
self?.updateReachabilityBar()
}
sipChanged = notificationCenter.addObserver(descriptor: SystemUser.sipChangedNotification) { [weak self] _ in
self?.updateReachabilityBar()
}
encryptionUsageChanged = notificationCenter.addObserver(descriptor:SystemUser.encryptionUsageNotification) { [weak self] _ in
self?.updateReachabilityBar()
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
updateReachabilityBar()
VialerGAITracker.trackScreenForController(name: controllerName)
try! AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category(rawValue: AVAudioSession.Category.ambient.rawValue))
setupButtons()
}
}
// MARK: - Actions
extension DialerViewController {
@IBAction func leftDrawerButtonPressed(_ sender: UIBarButtonItem) {
mm_drawerController.toggle(.left, animated: true, completion: nil)
}
@IBAction func deleteButtonPressed(_ sender: UIButton) {
if let number = numberText {
numberText = String(number.dropLast())
setupButtons()
}
}
@IBAction func deleteButtonLongPress(_ sender: UILongPressGestureRecognizer) {
if sender.state == .began {
numberText = nil
}
}
@IBAction func callButtonPressed(_ sender: UIButton) {
guard numberText != nil else {
numberText = lastCalledNumber
return
}
lastCalledNumber = numberText
if ReachabilityHelper.instance.connectionFastEnoughForVoIP() {
VialerGAITracker.setupOutgoingSIPCallEvent()
DispatchQueue.main.async {
self.performSegue(segueIdentifier: .sipCalling)
}
} else {
VialerGAITracker.setupOutgoingConnectABCallEvent()
DispatchQueue.main.async {
self.performSegue(segueIdentifier: .twoStepCalling)
}
}
}
@IBAction func numberPressed(_ sender: NumberPadButton) {
numberPadPressed(character: sender.number)
playSound(character: sender.number)
}
@IBAction func zeroButtonLongPress(_ sender: UILongPressGestureRecognizer) {
if sender.state == .began {
playSound(character: "0")
numberPadPressed(character: "+")
}
}
}
// MARK: - Segues
extension DialerViewController {
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
switch segueIdentifier(segue: segue) {
case .sipCalling:
let sipCallingVC = segue.destination as! SIPCallingViewController
if (UIApplication.shared.delegate as! AppDelegate).isScreenshotRun {
sipCallingVC.handleOutgoingCallForScreenshot(phoneNumber: numberText!)
} else {
sipCallingVC.handleOutgoingCall(phoneNumber: numberText!, contact: nil)
}
numberText = nil
case .twoStepCalling:
let twoStepCallingVC = segue.destination as! TwoStepCallingViewController
twoStepCallingVC.handlePhoneNumber(numberText!)
numberText = nil
case .reachabilityBar:
break
}
}
}
// MARK: - PasteableUILabelDelegate
extension DialerViewController : PasteableUILabelDelegate {
func pasteableUILabel(_ label: UILabel!, didReceivePastedText text: String!) {
numberText = text
}
}
// MARK: - Helper functions layout
extension DialerViewController {
fileprivate func setupUI() {
title = NSLocalizedString("Keypad", comment: "Keypad")
tabBarItem.image = UIImage(asset: .tabKeypad)
tabBarItem.selectedImage = UIImage(asset: .tabKeypadActive)
}
fileprivate func setupLayout() {
navigationItem.titleView = UIImageView(image: UIImage(asset: .logo))
updateReachabilityBar()
}
fileprivate func setupSounds() {
DispatchQueue.global(qos: .userInteractive).async {
var sounds = [String: AVAudioPlayer]()
for soundNumber in ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "#", "*"] {
let soundFileName = "dtmf-\(soundNumber)"
let soundURL = Bundle.main.url(forResource: soundFileName, withExtension: "aif")
assert(soundURL != nil, "No sound available")
do {
let player = try AVAudioPlayer(contentsOf: soundURL!)
player.prepareToPlay()
sounds[soundNumber] = player
} catch let error {
VialerLogError("Couldn't load sound: \(error)")
}
}
self.sounds = sounds
}
}
fileprivate func setupButtons() {
// Enable callbutton if:
// - status isn't offline or
// - there is a number in memory or
// - there is a number to be called
if reachability.status == .notReachable || (lastCalledNumber == nil && numberText == nil) {
callButton.isEnabled = false
} else {
callButton.isEnabled = true
}
UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseIn, animations: {
self.callButton.alpha = self.callButton.isEnabled ? 1.0 : 0.5
}, completion: nil)
deleteButton.isEnabled = numberText != nil
UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseIn, animations: {
self.deleteButton.alpha = self.deleteButton.isEnabled ? 1.0 : 0.0
}, completion: nil)
}
fileprivate func numberPadPressed(character: String) {
if character == "+" {
if numberText == "0" || numberText == nil {
numberText = "+"
}
} else if numberText != nil {
numberText = "\(numberText!)\(character)"
} else {
numberText = character
}
}
fileprivate func playSound(character: String) {
if let player = sounds[character] {
player.currentTime = 0
player.play()
}
}
fileprivate func updateReachabilityBar() {
DispatchQueue.main.async {
self.setupButtons()
if (!self.user.sipEnabled) {
self.reachabilityBarHeigthConstraint.constant = Config.ReachabilityBar.height
} else if (!self.reachability.hasHighSpeed) {
self.reachabilityBarHeigthConstraint.constant = Config.ReachabilityBar.height
} else if (!self.user.sipUseEncryption){
self.reachabilityBarHeigthConstraint.constant = Config.ReachabilityBar.height
} else {
self.reachabilityBarHeigthConstraint.constant = 0
}
UIView.animate(withDuration: Config.ReachabilityBar.animationDuration) {
self.reachabilityBar.setNeedsUpdateConstraints()
self.view.layoutIfNeeded()
}
}
}
}
| c75e0c043899b9f2e82699b2f0aa8729 | 34.146067 | 133 | 0.622762 | false | false | false | false |
swiftde/Udemy-Swift-Kurs | refs/heads/master | Kapitel 1/Kapitel 1/AppDelegate.swift | apache-2.0 | 1 | //
// AppDelegate.swift
// Kapitel 1
//
// Created by Udemy on 27.12.14.
// Copyright (c) 2014 Udemy. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "de.benchr.Kapitel_1" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1] as NSURL
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("Kapitel_1", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("Kapitel_1.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| 63fd6cbb695e8466d31cf742bb3f7ac3 | 49 | 291 | 0.69914 | false | false | false | false |
Stitch7/mclient | refs/heads/master | mclient/PrivateMessages/_MessageKit/Views/MessageLabel.swift | mit | 1 | /*
MIT License
Copyright (c) 2017-2018 MessageKit
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
open class MessageLabel: UILabel {
// MARK: - Private Properties
private lazy var layoutManager: NSLayoutManager = {
let layoutManager = NSLayoutManager()
layoutManager.addTextContainer(self.textContainer)
return layoutManager
}()
private lazy var textContainer: NSTextContainer = {
let textContainer = NSTextContainer()
textContainer.lineFragmentPadding = 0
textContainer.maximumNumberOfLines = self.numberOfLines
textContainer.lineBreakMode = self.lineBreakMode
textContainer.size = self.bounds.size
return textContainer
}()
private lazy var textStorage: NSTextStorage = {
let textStorage = NSTextStorage()
textStorage.addLayoutManager(self.layoutManager)
return textStorage
}()
private lazy var rangesForDetectors: [DetectorType: [(NSRange, MessageTextCheckingType)]] = [:]
private var isConfiguring: Bool = false
// MARK: - Public Properties
open weak var delegate: MessageLabelDelegate?
open var enabledDetectors: [DetectorType] = [] {
didSet {
setTextStorage(attributedText, shouldParse: true)
}
}
open override var attributedText: NSAttributedString? {
didSet {
setTextStorage(attributedText, shouldParse: true)
}
}
open override var text: String? {
didSet {
setTextStorage(attributedText, shouldParse: true)
}
}
open override var font: UIFont! {
didSet {
setTextStorage(attributedText, shouldParse: false)
}
}
open override var textColor: UIColor! {
didSet {
setTextStorage(attributedText, shouldParse: false)
}
}
open override var lineBreakMode: NSLineBreakMode {
didSet {
textContainer.lineBreakMode = lineBreakMode
if !isConfiguring { setNeedsDisplay() }
}
}
open override var numberOfLines: Int {
didSet {
textContainer.maximumNumberOfLines = numberOfLines
if !isConfiguring { setNeedsDisplay() }
}
}
open override var textAlignment: NSTextAlignment {
didSet {
setTextStorage(attributedText, shouldParse: false)
}
}
open var textInsets: UIEdgeInsets = .zero {
didSet {
if !isConfiguring { setNeedsDisplay() }
}
}
open override var intrinsicContentSize: CGSize {
var size = super.intrinsicContentSize
size.width += textInsets.horizontal
size.height += textInsets.vertical
return size
}
internal var messageLabelFont: UIFont?
private var attributesNeedUpdate = false
public static var defaultAttributes: [NSAttributedString.Key: Any] = {
return [
NSAttributedString.Key.foregroundColor: UIColor.darkText,
NSAttributedString.Key.underlineStyle: NSUnderlineStyle.single.rawValue,
NSAttributedString.Key.underlineColor: UIColor.darkText
]
}()
open internal(set) var addressAttributes: [NSAttributedString.Key: Any] = defaultAttributes
open internal(set) var dateAttributes: [NSAttributedString.Key: Any] = defaultAttributes
open internal(set) var phoneNumberAttributes: [NSAttributedString.Key: Any] = defaultAttributes
open internal(set) var urlAttributes: [NSAttributedString.Key: Any] = defaultAttributes
open internal(set) var transitInformationAttributes: [NSAttributedString.Key: Any] = defaultAttributes
public func setAttributes(_ attributes: [NSAttributedString.Key: Any], detector: DetectorType) {
switch detector {
case .phoneNumber:
phoneNumberAttributes = attributes
case .address:
addressAttributes = attributes
case .date:
dateAttributes = attributes
case .url:
urlAttributes = attributes
case .transitInformation:
transitInformationAttributes = attributes
}
if isConfiguring {
attributesNeedUpdate = true
} else {
updateAttributes(for: [detector])
}
}
// MARK: - Initializers
public override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupView()
}
// MARK: - Open Methods
open override func drawText(in rect: CGRect) {
let insetRect = rect.inset(by: textInsets)
textContainer.size = CGSize(width: insetRect.width, height: rect.height)
let origin = insetRect.origin
let range = layoutManager.glyphRange(for: textContainer)
layoutManager.drawBackground(forGlyphRange: range, at: origin)
layoutManager.drawGlyphs(forGlyphRange: range, at: origin)
}
// MARK: - Public Methods
public func configure(block: () -> Void) {
isConfiguring = true
block()
if attributesNeedUpdate {
updateAttributes(for: enabledDetectors)
}
attributesNeedUpdate = false
isConfiguring = false
setNeedsDisplay()
}
// MARK: - Private Methods
private func setTextStorage(_ newText: NSAttributedString?, shouldParse: Bool) {
guard let newText = newText, newText.length > 0 else {
textStorage.setAttributedString(NSAttributedString())
setNeedsDisplay()
return
}
let style = paragraphStyle(for: newText)
let range = NSRange(location: 0, length: newText.length)
let mutableText = NSMutableAttributedString(attributedString: newText)
mutableText.addAttribute(.paragraphStyle, value: style, range: range)
if shouldParse {
rangesForDetectors.removeAll()
let results = parse(text: mutableText)
setRangesForDetectors(in: results)
}
for (detector, rangeTuples) in rangesForDetectors {
if enabledDetectors.contains(detector) {
let attributes = detectorAttributes(for: detector)
rangeTuples.forEach { (range, _) in
mutableText.addAttributes(attributes, range: range)
}
}
}
let modifiedText = NSAttributedString(attributedString: mutableText)
textStorage.setAttributedString(modifiedText)
if !isConfiguring { setNeedsDisplay() }
}
private func paragraphStyle(for text: NSAttributedString) -> NSParagraphStyle {
guard text.length > 0 else { return NSParagraphStyle() }
var range = NSRange(location: 0, length: text.length)
let existingStyle = text.attribute(.paragraphStyle, at: 0, effectiveRange: &range) as? NSMutableParagraphStyle
let style = existingStyle ?? NSMutableParagraphStyle()
style.lineBreakMode = lineBreakMode
style.alignment = textAlignment
return style
}
private func updateAttributes(for detectors: [DetectorType]) {
guard let attributedText = attributedText, attributedText.length > 0 else { return }
let mutableAttributedString = NSMutableAttributedString(attributedString: attributedText)
for detector in detectors {
guard let rangeTuples = rangesForDetectors[detector] else { continue }
for (range, _) in rangeTuples {
let attributes = detectorAttributes(for: detector)
mutableAttributedString.addAttributes(attributes, range: range)
}
let updatedString = NSAttributedString(attributedString: mutableAttributedString)
textStorage.setAttributedString(updatedString)
}
}
private func detectorAttributes(for detectorType: DetectorType) -> [NSAttributedString.Key: Any] {
switch detectorType {
case .address:
return addressAttributes
case .date:
return dateAttributes
case .phoneNumber:
return phoneNumberAttributes
case .url:
return urlAttributes
case .transitInformation:
return transitInformationAttributes
}
}
private func detectorAttributes(for checkingResultType: NSTextCheckingResult.CheckingType) -> [NSAttributedString.Key: Any] {
switch checkingResultType {
case .address:
return addressAttributes
case .date:
return dateAttributes
case .phoneNumber:
return phoneNumberAttributes
case .link:
return urlAttributes
case .transitInformation:
return transitInformationAttributes
default:
fatalError(MessageKitError.unrecognizedCheckingResult)
}
}
private func setupView() {
numberOfLines = 0
lineBreakMode = .byWordWrapping
}
// MARK: - Parsing Text
private func parse(text: NSAttributedString) -> [NSTextCheckingResult] {
guard enabledDetectors.isEmpty == false else { return [] }
let checkingTypes = enabledDetectors.reduce(0) { $0 | $1.textCheckingType.rawValue }
let detector = try? NSDataDetector(types: checkingTypes)
let range = NSRange(location: 0, length: text.length)
let matches = detector?.matches(in: text.string, options: [], range: range) ?? []
guard enabledDetectors.contains(.url) else {
return matches
}
// Enumerate NSAttributedString NSLinks and append ranges
var results: [NSTextCheckingResult] = matches
text.enumerateAttribute(NSAttributedString.Key.link, in: range, options: []) { value, range, _ in
guard let url = value as? URL else { return }
let result = NSTextCheckingResult.linkCheckingResult(range: range, url: url)
results.append(result)
}
return results
}
private func setRangesForDetectors(in checkingResults: [NSTextCheckingResult]) {
guard checkingResults.isEmpty == false else { return }
for result in checkingResults {
switch result.resultType {
case .address:
var ranges = rangesForDetectors[.address] ?? []
let tuple: (NSRange, MessageTextCheckingType) = (result.range, .addressComponents(result.addressComponents))
ranges.append(tuple)
rangesForDetectors.updateValue(ranges, forKey: .address)
case .date:
var ranges = rangesForDetectors[.date] ?? []
let tuple: (NSRange, MessageTextCheckingType) = (result.range, .date(result.date))
ranges.append(tuple)
rangesForDetectors.updateValue(ranges, forKey: .date)
case .phoneNumber:
var ranges = rangesForDetectors[.phoneNumber] ?? []
let tuple: (NSRange, MessageTextCheckingType) = (result.range, .phoneNumber(result.phoneNumber))
ranges.append(tuple)
rangesForDetectors.updateValue(ranges, forKey: .phoneNumber)
case .link:
var ranges = rangesForDetectors[.url] ?? []
let tuple: (NSRange, MessageTextCheckingType) = (result.range, .link(result.url))
ranges.append(tuple)
rangesForDetectors.updateValue(ranges, forKey: .url)
case .transitInformation:
var ranges = rangesForDetectors[.transitInformation] ?? []
let tuple: (NSRange, MessageTextCheckingType) = (result.range, .transitInfoComponents(result.components))
ranges.append(tuple)
rangesForDetectors.updateValue(ranges, forKey: .transitInformation)
default:
fatalError("Received an unrecognized NSTextCheckingResult.CheckingType")
}
}
}
// MARK: - Gesture Handling
private func stringIndex(at location: CGPoint) -> Int? {
guard textStorage.length > 0 else { return nil }
var location = location
location.x -= textInsets.left
location.y -= textInsets.top
let index = layoutManager.glyphIndex(for: location, in: textContainer)
let lineRect = layoutManager.lineFragmentUsedRect(forGlyphAt: index, effectiveRange: nil)
var characterIndex: Int?
if lineRect.contains(location) {
characterIndex = layoutManager.characterIndexForGlyph(at: index)
}
return characterIndex
}
open func handleGesture(_ touchLocation: CGPoint) -> Bool {
guard let index = stringIndex(at: touchLocation) else { return false }
for (detectorType, ranges) in rangesForDetectors {
for (range, value) in ranges {
if range.contains(index) {
handleGesture(for: detectorType, value: value)
return true
}
}
}
return false
}
private func handleGesture(for detectorType: DetectorType, value: MessageTextCheckingType) {
switch value {
case let .addressComponents(addressComponents):
var transformedAddressComponents = [String: String]()
guard let addressComponents = addressComponents else { return }
addressComponents.forEach { (key, value) in
transformedAddressComponents[key.rawValue] = value
}
handleAddress(transformedAddressComponents)
case let .phoneNumber(phoneNumber):
guard let phoneNumber = phoneNumber else { return }
handlePhoneNumber(phoneNumber)
case let .date(date):
guard let date = date else { return }
handleDate(date)
case let .link(url):
guard let url = url else { return }
handleURL(url)
case let .transitInfoComponents(transitInformation):
var transformedTransitInformation = [String: String]()
guard let transitInformation = transitInformation else { return }
transitInformation.forEach { (key, value) in
transformedTransitInformation[key.rawValue] = value
}
handleTransitInformation(transformedTransitInformation)
}
}
private func handleAddress(_ addressComponents: [String: String]) {
delegate?.didSelectAddress(addressComponents)
}
private func handleDate(_ date: Date) {
delegate?.didSelectDate(date)
}
private func handleURL(_ url: URL) {
delegate?.didSelectURL(url)
}
private func handlePhoneNumber(_ phoneNumber: String) {
delegate?.didSelectPhoneNumber(phoneNumber)
}
private func handleTransitInformation(_ components: [String: String]) {
delegate?.didSelectTransitInformation(components)
}
}
private enum MessageTextCheckingType {
case addressComponents([NSTextCheckingKey: String]?)
case date(Date?)
case phoneNumber(String?)
case link(URL?)
case transitInfoComponents([NSTextCheckingKey: String]?)
}
| a354b0e30bef19c3ddb9e507fb1dcfed | 33.550633 | 129 | 0.640777 | false | false | false | false |
RTWeiss/pretto | refs/heads/master | Pretto/ZoomableCollectionView.swift | mit | 1 | //
// ZoomableCollectionViewController.swift
// ZoomableCollectionsView
//
// Created by Josiah Gaskin on 6/1/15.
// Copyright (c) 2015 asp2insp. All rights reserved.
//
import UIKit
import AudioToolbox
class ZoomableCollectionViewController: UIViewController, UICollectionViewDelegate {
@IBOutlet weak var collectionView: UICollectionView!
let flowLayout = UICollectionViewFlowLayout()
var baseSize : CGSize!
var maxSize : CGSize!
var minSize : CGSize!
// Long press handling
var selectionStart : NSIndexPath!
var previousRange : [NSIndexPath]?
var previousIndex : NSIndexPath?
// Set to enable/disable selection and checkboxes
var allowsSelection : Bool = true
var selectedPaths = NSMutableSet()
override func viewDidLoad() {
super.viewDidLoad()
collectionView.setCollectionViewLayout(flowLayout, animated: false)
collectionView.allowsMultipleSelection = true
flowLayout.sectionInset = UIEdgeInsetsMake(8, 8, 8, 8)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
maxSize = CGSizeMake(view.bounds.size.width/2 - 2*flowLayout.minimumInteritemSpacing, view.bounds.size.height/2 - 2*flowLayout.minimumLineSpacing)
minSize = CGSizeMake(view.bounds.size.width/5 - 5*flowLayout.minimumInteritemSpacing, view.bounds.size.height/5 - 5*flowLayout.minimumLineSpacing)
}
internal func onSelectionChange() {
// Override this in subclasses to respond to selection change
}
@IBAction func didPinch(sender: UIPinchGestureRecognizer) {
switch sender.state {
case .Began:
baseSize = flowLayout.itemSize
case .Changed:
flowLayout.itemSize = aspectScaleWithConstraints(baseSize, scale: sender.scale, max: maxSize, min: minSize)
case .Ended, .Cancelled:
flowLayout.itemSize = aspectScaleWithConstraints(baseSize, scale: sender.scale, max: maxSize, min: minSize)
default:
return
}
}
func aspectScaleWithConstraints(size: CGSize, scale: CGFloat, max: CGSize, min: CGSize) -> CGSize {
let maxHScale = fmax(max.width / size.width, 1.0)
let maxVScale = fmax(max.height / size.height, 1.0)
let scaleBoundedByMax = fmin(fmin(scale, maxHScale), maxVScale)
let minHScale = fmin(min.width / size.width, 1.0)
let minVScale = fmin(min.height / size.height, 1.0)
let scaleBoundedByMin = fmax(fmax(scaleBoundedByMax, minHScale), minVScale)
return CGSizeMake(size.width * scaleBoundedByMin, size.height * scaleBoundedByMin)
}
@IBAction func didLongPressAndDrag(sender: UILongPressGestureRecognizer) {
let touchCoords = sender.locationInView(collectionView)
switch sender.state {
case .Began, .Changed:
let currentIndex = pointToIndexPath(touchCoords, fuzzySize: 5)
if currentIndex != nil {
if selectionStart == nil {
selectionStart = currentIndex
selectItemAtIndexPathIfNecessary(selectionStart)
AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate))
return
}
// Change detection
if currentIndex != previousIndex {
let itemsToSelect = getIndexRange(start: selectionStart, end: currentIndex!)
let itemsToDeselect = difference(previousRange, minus: itemsToSelect)
for path in itemsToDeselect {
deselectItemAtIndexPathIfNecessary(path)
}
for path in itemsToSelect {
selectItemAtIndexPathIfNecessary(path)
}
previousRange = itemsToSelect
previousIndex = currentIndex
}
}
case .Cancelled, .Ended:
selectionStart = nil
previousRange = nil
previousIndex = nil
default:
return
}
}
func selectItemAtIndexPathIfNecessary(path: NSIndexPath) {
if !allowsSelection {
return
}
if let cell = collectionView.cellForItemAtIndexPath(path) as? SelectableImageCell {
if !cell.selected {
collectionView.selectItemAtIndexPath(path, animated: true, scrollPosition: UICollectionViewScrollPosition.None)
}
cell.checkbox.checkState = M13CheckboxStateChecked
cell.animateStateChange()
}
self.selectedPaths.addObject(path)
onSelectionChange()
}
func deselectItemAtIndexPathIfNecessary(path: NSIndexPath) {
if !allowsSelection {
return
}
if let cell = collectionView.cellForItemAtIndexPath(path) as? SelectableImageCell {
if (cell.selected) {
collectionView.deselectItemAtIndexPath(path, animated: true)
}
cell.checkbox.checkState = M13CheckboxStateUnchecked
cell.animateStateChange()
}
self.selectedPaths.removeObject(path)
onSelectionChange()
}
// Return the difference of the given arrays of index paths
func difference(a: [NSIndexPath]?, minus b: [NSIndexPath]?) -> [NSIndexPath] {
if a == nil {
return []
}
if b == nil {
return a!
}
var final = a!
for item in b! {
if let index = find(final, item) {
final.removeAtIndex(index)
}
}
return final
}
// Return an array of NSIndexPaths between the given start and end, inclusive
func getIndexRange(#start: NSIndexPath, end: NSIndexPath) -> [NSIndexPath] {
var range : [NSIndexPath] = []
let numItems = abs(start.row - end.row)
let section = start.section
for var i = 0; i <= numItems; i++ {
let newRow = start.row < end.row ? start.row+i : start.row-i
if newRow >= 0 && newRow < collectionView.numberOfItemsInSection(section) {
range.append(NSIndexPath(forRow: newRow, inSection: section))
}
}
return range
}
// Convert a touch point to an index path of the cell under the point.
// Returns nil if no cell exists under the given point.
func pointToIndexPath(point: CGPoint, fuzzySize: CGFloat) -> NSIndexPath? {
let fingerRect = CGRectMake(point.x-fuzzySize, point.y-fuzzySize, fuzzySize*2, fuzzySize*2)
for item in collectionView.visibleCells() {
let cell = item as! SelectableImageCell
if CGRectIntersectsRect(fingerRect, cell.frame) {
return collectionView.indexPathForCell(cell)
}
}
return nil
}
}
// UICollectionViewDelegate Extension
extension ZoomableCollectionViewController {
func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
deselectItemAtIndexPathIfNecessary(indexPath)
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
selectItemAtIndexPathIfNecessary(indexPath)
}
func collectionView(collectionView: UICollectionView, willDisplayCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
if let c = cell as? SelectableImageCell {
c.showCheckbox = self.allowsSelection
}
}
}
class SelectableImageCell : UICollectionViewCell {
var image: PFImageView!
var checkbox: M13Checkbox!
var showCheckbox : Bool = true {
didSet {
self.checkbox.hidden = !showCheckbox
self.checkbox.setNeedsDisplay()
}
}
override func awakeFromNib() {
image = PFImageView(frame: self.bounds)
checkbox = M13Checkbox(frame: CGRectMake(0, 0, 20, 20))
checkbox.center = CGPointMake(25, 25)
checkbox.userInteractionEnabled = false
checkbox.checkState = selected ? M13CheckboxStateChecked : M13CheckboxStateUnchecked
checkbox.radius = 0.5 * checkbox.frame.size.width;
checkbox.flat = true
checkbox.tintColor = checkbox.strokeColor
checkbox.checkColor = UIColor.whiteColor()
self.addSubview(image)
self.addSubview(checkbox)
}
override func layoutSubviews() {
super.layoutSubviews()
image.frame = self.bounds
}
func animateStateChange() {
UIView.animateWithDuration(0.5, animations: { () -> Void in
self.checkbox.transform = CGAffineTransformMakeScale(2, 2)
self.checkbox.transform = CGAffineTransformMakeScale(1, 1)
})
}
func updateCheckState() {
checkbox.checkState = selected ? M13CheckboxStateChecked : M13CheckboxStateUnchecked
}
} | fab2ea246a74011ad96d8b8ea2fd3768 | 36.560166 | 154 | 0.631422 | false | false | false | false |
JGiola/swift | refs/heads/main | validation-test/Sema/type_checker_perf/fast/fast-operator-typechecking.swift | apache-2.0 | 9 | // RUN: %target-typecheck-verify-swift -swift-version 5 -solver-expression-time-threshold=1
// rdar://problem/32998180
func checksum(value: UInt16) -> UInt16 {
var checksum = (((value >> 2) ^ (value >> 8) ^ (value >> 12) ^ (value >> 14)) & 0x01) << 1
checksum |= (((value) ^ (value >> UInt16(4)) ^ (value >> UInt16(6)) ^ (value >> UInt16(10))) & 0x01)
checksum ^= 0x02
return checksum
}
// rdar://problem/42672829
func f(tail: UInt64, byteCount: UInt64) {
if tail & ~(1 << ((byteCount & 7) << 3) - 1) == 0 { }
}
// rdar://problem/32547805
func size(count: Int) {
// Size of the buffer we need to allocate
let _ = count * MemoryLayout<Float>.size * (4 + 3 + 3 + 2 + 4)
}
| 122531ba1271fc4c8c919808e62e4370 | 33.35 | 102 | 0.598253 | false | false | false | false |
zhouxj6112/ARKit | refs/heads/master | ARKitInteraction/ARKitInteraction/ViewController+ObjectSelection.swift | apache-2.0 | 1 | /*
See LICENSE folder for this sample’s licensing information.
Abstract:
Methods on the main view controller for handling virtual object loading and movement
*/
import UIKit
import SceneKit
extension ViewController: VirtualObjectSelectionViewControllerDelegate {
/**
Adds the specified virtual object to the scene, placed using
the focus square's estimate of the world-space position
currently corresponding to the center of the screen.
- Tag: PlaceVirtualObject
*/
func placeVirtualObject(_ virtualObject: VirtualObject) {
guard let cameraTransform = session.currentFrame?.camera.transform,
let focusSquarePosition = focusSquare.lastPosition else {
statusViewController.showMessage("CANNOT PLACE OBJECT\nTry moving left or right.")
return
}
virtualObjectInteraction.selectedObject = virtualObject
// 控制位置
virtualObject.setPosition(focusSquarePosition, relativeTo: cameraTransform, smoothMovement: false)
// 缩放比例
virtualObject.setScale();
// 控制方向
virtualObject.setDirection();
updateQueue.async {
if self.sceneView.scene.rootNode.childNodes.count > 3 {
let preObj = self.sceneView.scene.rootNode.childNodes[3];
let max = preObj.boundingBox.max;
let min = preObj.boundingBox.min;
virtualObject.simdPosition = simd_float3(0, (max.y-min.y), 0);
preObj.addChildNode(virtualObject);
self.virtualObjectInteraction.selectedObject = preObj as? VirtualObject;
} else {
self.sceneView.scene.rootNode.addChildNode(virtualObject)
}
}
}
// MARK: - VirtualObjectSelectionViewControllerDelegate
func virtualObjectSelectionViewController(_: VirtualObjectSelectionViewController, didSelectObject object: VirtualObject) {
virtualObjectLoader.loadVirtualObject(object, loadedHandler: { [unowned self] loadedObject in
DispatchQueue.main.async {
self.hideObjectLoadingUI()
self.placeVirtualObject(loadedObject)
}
})
displayObjectLoadingUI()
}
func virtualObjectSelectionViewController(_: VirtualObjectSelectionViewController, didDeselectObject object: VirtualObject) {
guard let objectIndex = virtualObjectLoader.loadedObjects.index(of: object) else {
fatalError("Programmer error: Failed to lookup virtual object in scene.")
}
virtualObjectLoader.removeVirtualObject(at: objectIndex)
}
// MARK: Object Loading UI
func displayObjectLoadingUI() {
// Show progress indicator.
spinner.startAnimating()
addObjectButton.setImage(#imageLiteral(resourceName: "buttonring"), for: [])
addObjectButton.isEnabled = false
isRestartAvailable = false
}
func hideObjectLoadingUI() {
// Hide progress indicator.
spinner.stopAnimating()
addObjectButton.setImage(#imageLiteral(resourceName: "add"), for: [])
addObjectButton.setImage(#imageLiteral(resourceName: "addPressed"), for: [.highlighted])
addObjectButton.isEnabled = true
isRestartAvailable = true
}
}
| 70f7d0722a77611f7ea385b22a1be568 | 36.022222 | 129 | 0.668067 | false | false | false | false |
ericyanush/Plex-TVOS | refs/heads/master | Pods/Swifter/Common/DemoServer.swift | mit | 1 | //
// DemoServer.swift
// Swifter
// Copyright (c) 2014 Damian Kołakowski. All rights reserved.
//
import Foundation
func demoServer(publicDir: String?) -> HttpServer {
let server = HttpServer()
if let publicDir = publicDir {
server["/resources/(.+)"] = HttpHandlers.directory(publicDir)
}
server["/files(.+)"] = HttpHandlers.directoryBrowser("~/")
server["/magic"] = { .OK(.HTML("You asked for " + $0.url)) }
server["/test"] = { request in
var headersInfo = ""
for (name, value) in request.headers {
headersInfo += "\(name) : \(value)<br>"
}
var queryParamsInfo = ""
for (name, value) in request.urlParams {
queryParamsInfo += "\(name) : \(value)<br>"
}
return .OK(.HTML("<h3>Address: \(request.address)</h3><h3>Url:</h3> \(request.url)<h3>Method: \(request.method)</h3><h3>Headers:</h3>\(headersInfo)<h3>Query:</h3>\(queryParamsInfo)"))
}
server["/params/(.+)/(.+)"] = { request in
var capturedGroups = ""
for (index, group) in request.capturedUrlGroups.enumerate() {
capturedGroups += "Expression group \(index) : \(group)<br>"
}
return .OK(.HTML("Url: \(request.url)<br>Method: \(request.method)<br>\(capturedGroups)"))
}
server["/json"] = { request in
return .OK(.JSON(["posts" : [[ "id" : 1, "message" : "hello world"],[ "id" : 2, "message" : "sample message"]], "new_updates" : false]))
}
server["/redirect"] = { request in
return .MovedPermanently("http://www.google.com")
}
server["/long"] = { request in
var longResponse = ""
for k in 0..<1000 { longResponse += "(\(k)),->" }
return .OK(.HTML(longResponse))
}
server["/demo"] = { request in
return .OK(.HTML("<center><h2>Hello Swift</h2>" +
"<img src=\"https://devimages.apple.com.edgekey.net/swift/images/swift-hero_2x.png\"/><br>" +
"</center>"))
}
server["/login"] = { request in
switch request.method.uppercaseString {
case "GET":
if let rootDir = publicDir {
if let html = NSData(contentsOfFile:"\(rootDir)/login.html") {
return HttpResponse.RAW(200, "OK", nil, html)
} else {
return .NotFound
}
}
break;
case "POST":
if let body = request.body {
return .OK(.HTML(body))
} else {
return .OK(.HTML("No POST params."))
}
default:
return .NotFound
}
return .NotFound
}
server["/raw"] = { request in
return HttpResponse.RAW(200, "OK", ["XXX-Custom-Header": "value"], "Sample Response".dataUsingEncoding(NSUTF8StringEncoding)!)
}
server["/"] = { request in
var listPage = "Available services:<br><ul>"
for item in server.routes() {
listPage += "<li><a href=\"\(item)\">\(item)</a></li>"
}
listPage += "</ul>"
return .OK(.HTML(listPage))
}
return server
} | dae4acf6d61c83e8aea54e4b63d4bd43 | 36.658824 | 191 | 0.515938 | false | false | false | false |
bhold6160/GITList | refs/heads/master | GITList/GITList/Cloudkit.swift | mit | 1 | //
// Cloudkit.swift
// GITList
//
// Created by Louis W. Haywood on 8/23/17.
// Copyright © 2017 Brandon Holderman. All rights reserved.
//
import Foundation
import CloudKit
typealias ListCompletion = (Bool)->()
typealias GetListCompletion = ([List]?)->()
class CloudKit {
static let shared = CloudKit()
let container = CKContainer.default()
var database : CKDatabase {
return container.privateCloudDatabase
}
private init (){}
func save(list: List, completion: @escaping ListCompletion) {
do {
if let record = try list.record() {
self.database.save(record, completionHandler: { (record, error) in
if error != nil {
print(error!)
completion(false)
}
if let record = record {
print(record)
completion(true)
}
})
}
} catch {
print(error)
}
}
func getList(completion: @escaping GetListCompletion) {
let query = CKQuery(recordType: "List", predicate: NSPredicate(value: true))
query.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
self.database.perform(query, inZoneWith: nil) { (records, error) in
if error != nil {
print(error!.localizedDescription)
completion(nil)
}
if let records = records {
var allLists = [List]()
for record in records {
guard let recordValue = record["items"] as? [String] else { continue }
guard let createdAt = record["creationDate"] as? Date else { continue }
let newList = List()
newList.items = recordValue
newList.createdAtDate = createdAt
allLists.append(newList)
}
OperationQueue.main.addOperation {
completion(allLists)
}
completion(nil)
}
}
}
}
| d69f21f6a790402e27b19b77a68fa05e | 28.876712 | 91 | 0.508482 | false | false | false | false |
AgaKhanFoundation/WCF-iOS | refs/heads/develop | Floral/Pods/RxSwift/RxSwift/Observables/Sample.swift | apache-2.0 | 14 | //
// Sample.swift
// RxSwift
//
// Created by Krunoslav Zaher on 5/1/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
extension ObservableType {
/**
Samples the source observable sequence using a sampler observable sequence producing sampling ticks.
Upon each sampling tick, the latest element (if any) in the source sequence during the last sampling interval is sent to the resulting sequence.
**In case there were no new elements between sampler ticks, no element is sent to the resulting sequence.**
- seealso: [sample operator on reactivex.io](http://reactivex.io/documentation/operators/sample.html)
- parameter sampler: Sampling tick sequence.
- returns: Sampled observable sequence.
*/
public func sample<Source: ObservableType>(_ sampler: Source)
-> Observable<Element> {
return Sample(source: self.asObservable(), sampler: sampler.asObservable())
}
}
final private class SamplerSink<Observer: ObserverType, SampleType>
: ObserverType
, LockOwnerType
, SynchronizedOnType {
typealias Element = SampleType
typealias Parent = SampleSequenceSink<Observer, SampleType>
fileprivate let _parent: Parent
var _lock: RecursiveLock {
return self._parent._lock
}
init(parent: Parent) {
self._parent = parent
}
func on(_ event: Event<Element>) {
self.synchronizedOn(event)
}
func _synchronized_on(_ event: Event<Element>) {
switch event {
case .next, .completed:
if let element = _parent._element {
self._parent._element = nil
self._parent.forwardOn(.next(element))
}
if self._parent._atEnd {
self._parent.forwardOn(.completed)
self._parent.dispose()
}
case .error(let e):
self._parent.forwardOn(.error(e))
self._parent.dispose()
}
}
}
final private class SampleSequenceSink<Observer: ObserverType, SampleType>
: Sink<Observer>
, ObserverType
, LockOwnerType
, SynchronizedOnType {
typealias Element = Observer.Element
typealias Parent = Sample<Element, SampleType>
fileprivate let _parent: Parent
let _lock = RecursiveLock()
// state
fileprivate var _element = nil as Element?
fileprivate var _atEnd = false
fileprivate let _sourceSubscription = SingleAssignmentDisposable()
init(parent: Parent, observer: Observer, cancel: Cancelable) {
self._parent = parent
super.init(observer: observer, cancel: cancel)
}
func run() -> Disposable {
self._sourceSubscription.setDisposable(self._parent._source.subscribe(self))
let samplerSubscription = self._parent._sampler.subscribe(SamplerSink(parent: self))
return Disposables.create(_sourceSubscription, samplerSubscription)
}
func on(_ event: Event<Element>) {
self.synchronizedOn(event)
}
func _synchronized_on(_ event: Event<Element>) {
switch event {
case .next(let element):
self._element = element
case .error:
self.forwardOn(event)
self.dispose()
case .completed:
self._atEnd = true
self._sourceSubscription.dispose()
}
}
}
final private class Sample<Element, SampleType>: Producer<Element> {
fileprivate let _source: Observable<Element>
fileprivate let _sampler: Observable<SampleType>
init(source: Observable<Element>, sampler: Observable<SampleType>) {
self._source = source
self._sampler = sampler
}
override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element {
let sink = SampleSequenceSink(parent: self, observer: observer, cancel: cancel)
let subscription = sink.run()
return (sink: sink, subscription: subscription)
}
}
| 0d6a79b499c47c87988a2e8925c6e82d | 29.766917 | 171 | 0.639052 | false | false | false | false |
ajaybeniwal/SwiftTransportApp | refs/heads/master | TransitFare/TopMostViewController.swift | mit | 1 | //
// TopMostViewController.swift
// TransitFare
//
// Created by ajaybeniwal203 on 24/2/16.
// Copyright © 2016 ajaybeniwal203. All rights reserved.
//
import UIKit
extension UIViewController{
class func topMostViewController() -> UIViewController?{
let rootViewController = UIApplication.sharedApplication().keyWindow?.rootViewController
return self.topMostViewControllerOfViewController(rootViewController)
}
class func topMostViewControllerOfViewController(viewController: UIViewController?) -> UIViewController? {
// UITabBarController
if let tabBarController = viewController as? UITabBarController,
let selectedViewController = tabBarController.selectedViewController {
return self.topMostViewControllerOfViewController(selectedViewController)
}
// UINavigationController
if let navigationController = viewController as? UINavigationController,
let visibleViewController = navigationController.visibleViewController {
return self.topMostViewControllerOfViewController(visibleViewController)
}
// presented view controller
if let presentedViewController = viewController?.presentedViewController {
return self.topMostViewControllerOfViewController(presentedViewController)
}
return viewController
}
}
| b6204048561e5eb148d259407fd1f37b | 35.564103 | 110 | 0.721599 | false | false | false | false |
JOCR10/iOS-Curso | refs/heads/master | Clases/NewsWithRealm/News/RealmManager.swift | mit | 1 | //
// RealmManager.swift
// News
//
// Created by Local User on 5/25/17.
// Copyright © 2017 Local User. All rights reserved.
//
import UIKit
import RealmSwift
class RealmManager: NSObject {
class func getAllCategories() -> Results<Category>
{
let realm = try! Realm()
let categories = realm.objects(Category.self)
if categories.count > 0
{
return categories
}
else
{
return createDefaultCategories()
}
}
private class func createDefaultCategories() -> Results<Category>
{
let economyCategory = Category(value: ["name":"Economía", "imageName":"economy", "type": 1])
let sportsCategory = Category(value: ["name":"Deportes", "imageName":"sports", "type": 2])
let technologyCategory = Category(value: ["name":"Tecnología", "imageName":"technology", "type": 3])
let incidentCategory = Category(value: ["name":"Sucesos", "imageName":"incident", "type": 4])
addObjectToRealm(realmObject: economyCategory)
addObjectToRealm(realmObject: sportsCategory)
addObjectToRealm(realmObject: technologyCategory)
addObjectToRealm(realmObject: incidentCategory)
return getAllCategories()
}
private class func addObjectToRealm(realmObject: Object)
{
let realm = try! Realm()
try! realm.write {
realm.add(realmObject)
}
}
private class func getCategory(type: Int ) -> Category
{
let realm = try! Realm()
let predicate = NSPredicate(format: "type = %d", type)
return realm.objects(Category.self).filter(predicate).first!
}
class func getAllNews(categoryType : Int) -> List<News>?
{
return getCategory(type: categoryType).news
}
class func createNews(categoryType: Int, title: String, description: String )
{
let category = getCategory(type: categoryType)
let news = News()
news.titleNews = title
news.descriptionNews = description
news.createdAt = Date()
let realm = try! Realm()
try! realm.write {
category.news.append(news)
}
addObjectToRealm(realmObject: news)
}
}
| be649375cf19f357086bd4b21c74cc07 | 29.226667 | 108 | 0.611822 | false | false | false | false |
gossipgeek/gossipgeek | refs/heads/develop | GossipGeek/GossipGeek/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// GossipGeek
//
// Created by Toureek on 10/05/2017.
// Copyright © 2017 application. All rights reserved.
//
import UIKit
let kApplicationID = "B4wHEEb4qLnekUEb6uiiwo4w-gzGzoHsz"
let kApplicationKey = "bvkHfVjS1pmOA14SFujzxxGE"
let kStoryBoardName = "Main"
let kAppTabBarStoryBoardId = "tabbarviewcontroller"
let kAppLoginStoryBoardId = "loginviewcontroller"
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
connectToAVOSCloudSDKService(launchOptions: launchOptions)
if isUserLogin() {
showMainPage()
} else {
showLoginPage()
}
return true
}
func connectToAVOSCloudSDKService(launchOptions: [UIApplicationLaunchOptionsKey: Any]?) {
initLCObject()
AVOSCloud.setApplicationId(kApplicationID, clientKey: kApplicationKey)
AVOSCloud.setAllLogsEnabled(true)
}
func initLCObject() {
Magazine.registerSubclass()
}
// TODO: - It will be removed after register-feature finished
func isUserLogin() -> Bool {
return true
}
func showMainPage() {
let storyboard = UIStoryboard.init(name: kStoryBoardName, bundle: nil)
let mainTabPage = storyboard.instantiateViewController(withIdentifier: kAppTabBarStoryBoardId)
self.window?.rootViewController = mainTabPage
}
func showLoginPage() {
let storyboard = UIStoryboard.init(name: kStoryBoardName, bundle: nil)
let loginView = storyboard.instantiateViewController(withIdentifier: kAppLoginStoryBoardId)
let navigator = UINavigationController.init(rootViewController: loginView)
self.window?.rootViewController = navigator
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 6c0be789981773a36c40f5c0ede55675 | 38.402174 | 285 | 0.726897 | false | false | false | false |
arsonik/AKTrakt | refs/heads/master | Source/shared/Requests/Movie.swift | mit | 1 | //
// Movie.swift
// Pods
//
// Created by Florian Morello on 26/05/16.
//
//
import Foundation
import Alamofire
public class TraktRequestMovie: TraktRequest {
public init(id: AnyObject, extended: TraktRequestExtendedOptions? = nil) {
super.init(path: "/movies/\(id)", params: extended?.value())
}
public func request(trakt: Trakt, completion: (TraktMovie?, NSError?) -> Void) -> Request? {
return trakt.request(self) { response in
completion(TraktMovie(data: response.result.value as? JSONHash), response.result.error)
}
}
}
public class TraktRequestMovieReleases: TraktRequest {
public init(id: AnyObject, country: String? = nil, extended: TraktRequestExtendedOptions? = nil) {
super.init(path: "/movies/\(id)/releases" + (country != nil ? "/\(country!)" : ""), params: extended?.value())
}
public func request(trakt: Trakt, completion: ([TraktRelease]?, NSError?) -> Void) -> Request? {
return trakt.request(self) { response in
guard let data = response.result.value as? [JSONHash] else {
return completion(nil, response.result.error)
}
completion(data.flatMap { TraktRelease(data: $0) }, response.result.error)
}
}
}
| e0960401c0ba93a9215d765f35ffa5ea | 32.526316 | 118 | 0.636578 | false | false | false | false |
overtake/TelegramSwift | refs/heads/master | Telegram-Mac/InlineAuthOptionRowItem.swift | gpl-2.0 | 1 | //
// InlineAuthOptionRowItem.swift
// Telegram
//
// Created by Mikhail Filimonov on 22/05/2019.
// Copyright © 2019 Telegram. All rights reserved.
//
import Cocoa
import TGUIKit
class InlineAuthOptionRowItem: GeneralRowItem {
fileprivate let selected: Bool
fileprivate let textLayout: TextViewLayout
init(_ initialSize: NSSize, stableId: AnyHashable, attributedString: NSAttributedString, selected: Bool, action: @escaping()->Void) {
self.selected = selected
self.textLayout = TextViewLayout(attributedString, maximumNumberOfLines: 3, alwaysStaticItems: true)
super.init(initialSize, stableId: stableId, action: action, inset: NSEdgeInsetsMake(10, 30, 10, 30))
}
override func makeSize(_ width: CGFloat, oldWidth: CGFloat) -> Bool {
textLayout.measure(width: width - inset.left - inset.right - 50)
return super.makeSize(width, oldWidth: oldWidth)
}
override func viewClass() -> AnyClass {
return InlineAuthOptionRowView.self
}
override var height: CGFloat {
return max(textLayout.layoutSize.height + inset.top + inset.bottom, 30)
}
}
private final class InlineAuthOptionRowView : TableRowView {
private let textView = TextView()
private let selectView: SelectingControl = SelectingControl(unselectedImage: theme.icons.chatGroupToggleUnselected, selectedImage: theme.icons.chatGroupToggleSelected)
required init(frame frameRect: NSRect) {
super.init(frame: frameRect)
addSubview(textView)
addSubview(selectView)
selectView.userInteractionEnabled = false
textView.userInteractionEnabled = false
textView.isSelectable = false
}
override func mouseUp(with event: NSEvent) {
guard let item = item as? InlineAuthOptionRowItem else {
return
}
item.action()
}
override func set(item: TableRowItem, animated: Bool) {
super.set(item: item, animated: animated)
guard let item = item as? InlineAuthOptionRowItem else {
return
}
selectView.set(selected: item.selected, animated: animated)
}
override func layout() {
super.layout()
guard let item = item as? InlineAuthOptionRowItem else {
return
}
textView.update(item.textLayout)
if item.textLayout.layoutSize.height < selectView.frame.height {
selectView.centerY(x: item.inset.left)
textView.centerY(x: selectView.frame.maxX + 10)
} else {
selectView.setFrameOrigin(NSMakePoint(item.inset.left, item.inset.top))
textView.setFrameOrigin(NSMakePoint(selectView.frame.maxX + 10, selectView.frame.minY))
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 9093967567cd2c1e0fbddc37534cafa6 | 31.32967 | 171 | 0.653977 | false | false | false | false |
HenningBrandt/SwiftPromise | refs/heads/master | Source/SwiftPromise.swift | mit | 1 | //
// SwiftPromise.swift
//
// Copyright (c) 2015 Henning Brandt (http://thepurecoder.com/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/**
Bind-Operator.
Operator for Promises flatMap.
*/
public func >>=<T,R>(p: Promise<T>, f: (T) -> Promise<R>) -> Promise<R> {
return p.flatMap(f: f)
}
public class Promise<T> {
/**
Type for the final result of the promise.
It consists of a fulfilled or failed result represented by an Either and
all callbacks scheduled for the advent of the result.
*/
private typealias PromiseValue = (Either<T>?, [DeliverBlock])
/**
A GCD queue.
The future block or any method dealing with the promise result is executed in an execution enviroment.
This enviroment or context is a dispatch queue on which the corresponding computations are performed
*/
public typealias ExecutionContext = DispatchQueue
/**
A block of work that can be performed in the background.
The return value of the block becomes the value of the fulfilled promise.
If the block throws an error, the promise fails with this error.
*/
public typealias BackgroundTask = (() throws -> T)
/**
A unit of work. It consists of the execution context on which it should be performed and
the task itself doing the work with the result of the fulfilled promise.
*/
private typealias DeliverBlock = (ExecutionContext, (Either<T>) -> ())
/**
The internal result holding the promises value and any callbacks.
Any code interested in the result must schedule one of the different callbacks or access it via
- `value`
- `error`
- `result`
fulfillment can be tested via
- `isFulfilled`
*/
private var internalValue: PromiseValue = (nil, [])
/**
A sempahore to synchronize the critial path concerning fulfillment of the promises result.
Setting the value can occur from many different threads. The promise must, on a thread safe level, ensure that:
- a promises value can only be set once and after that can never change.
- any callback scheduled before or after setting the promises value is guaranteed to be invoked with the result
*/
private let fulfillSemaphore = DispatchSemaphore(value: 1)
/**
The default execution context used for the background task the promise was initialized with and
any scheduled callback not specifying its own context when scheduled.
- important:
Exceptions are the three result callbacks:
- `onComplete()`
- `onSuccess()`
- `onFailure()`
These three normally mark endpoints in the value processing and will presumably
used for interacting with UIKit for updating UI elements etc. So for convenience
they are performed on the main queue by default.
*/
private let defaultExecutionContext: ExecutionContext
/**
Initializer for creating a Promise whose value comes from a block.
Use this if you want the promise to manage asynchronous execution and
fulfill itself with the computed value. This mimics more or less the concept of
a _Future_ combined with a _Promise_.
- parameter executionContext: The default execution context. The given task will be performed on this queue among others.
Default is a global queue with the default quality of service.
- parameter task: A block that gets executed immediately on the given execution context.
The value returned by this block will fulfill the promise.
*/
public init(_ executionContext: ExecutionContext = ExecutionContextConstant.DefaultContext, task: BackgroundTask) {
self.defaultExecutionContext = executionContext
self.defaultExecutionContext.async {
do {
let result = try task()
self.fulfill(.result(result))
} catch let error {
self.fulfill(.failure(error))
}
}
}
/**
Initializer for creating a _Promise_ with an already computed value.
The _Promise_ will fulfill itself immediately with a given value.
You can use this when you have code returning a _Promise_ with a future value, but once you have it you return a cached result
or some function wants a _Promise_ but you just want to pass an inexpensive value that don't need background computation etc.
- parameter executionContext: The default execution context.
Default is the main queue.
- parameter value: The value to fulfill the _Promise_ with.
*/
public init(_ executionContext: ExecutionContext = ExecutionContextConstant.MainContext, value: T) {
self.defaultExecutionContext = executionContext
self.fulfill(.result(value))
}
/**
Initialier for creating an empty _Promise_.
Use this if your background computation is more complicated and doesn't fit in a block.
For example when you use libraries requiring own callback blocks or delegate callbacks.
You can than create an empty _Promise_ return it immediately, performing your work
and fulfill it manually later via `fulfill()`.
- parameter executionContext: The default execution context.
Default is a global queue with the default quality of service.
*/
public init(_ executionContext: ExecutionContext = ExecutionContextConstant.DefaultContext) {
self.defaultExecutionContext = executionContext
}
/**
Method for providing the promise with a value.
Use this to fulfill the _Promise_ with either a result or an error.
All callbacks already queued up will be called with the given value.
`fulfill()` is thread safe and can safely be called from any thread.
- important:
A _Promise_ can only be fulfilled once and will have this value over its whole lifetime.
You can have multiple threads compute a value and call fulfill on the same _Promise_ but only
the first value will be excepted and set on the _Promise_. All later calls to fulfill are ignored
and its value will be droped.
- parameter value: The value to set on the _Promise_. This can either be a result or a failure.
See `Either` for this.
*/
public func fulfill(_ value: Either<T>) {
self.fulfillSemaphore.wait()
defer { self.fulfillSemaphore.signal() }
let (internalResult, blocks) = self.internalValue
guard internalResult == nil else { return }
self.internalValue = (value, blocks)
self.executeDeliverBlocks(value)
}
/**
Gives back if the promise is fulfilled with either a value or an error.
- returns: true if promise is fulfilled otherwise false
*/
public func isFulfilled() -> Bool {
self.fulfillSemaphore.wait()
defer { self.fulfillSemaphore.signal() }
let (internalResult, _) = self.internalValue
return internalResult != nil
}
/**
Returns the value the promise was fulfilled with.
A Promise can either be fulfilled with a result or an error,
so value returns an Either.
- returns: An Either with the Promises result/error or nil if the Promise is not fulfilled yet
*/
public func value() -> Either<T>? {
self.fulfillSemaphore.wait()
defer { self.fulfillSemaphore.signal() }
let (internalResult, _) = self.internalValue
return internalResult
}
/**
Returns the Promises result if there is one.
- returns: The Promises result if there is one or nil if the Promise is not fulfilled yet
or is fulfilled with an error.
*/
public func result() -> T? {
self.fulfillSemaphore.wait()
defer { self.fulfillSemaphore.signal() }
let (internalResult, _) = self.internalValue
guard let result = internalResult else {
return nil
}
switch result {
case .result(let r):
return r
case .failure:
return nil
}
}
/**
Returns the Promises error if there is one.
- returns: The Promises error if there is one or nil if the Promise is not fulfilled yet
or is fulfilled with a result.
*/
public func error() -> ErrorProtocol? {
self.fulfillSemaphore.wait()
defer { self.fulfillSemaphore.signal() }
let (internalResult, _) = self.internalValue
guard let result = internalResult else {
return nil
}
switch result {
case .result:
return nil
case .failure(let error):
return error
}
}
/**
Callback triggered at fulfillment of the Promise.
Registers a callback interested in general fulfillment of the Promise with eiter a result or an error.
- parameter context: dispatch_queue on which to perform the block. Default is the main queue.
- parameter f: The block scheduled for fulfillment. Takes the value of the Promise as argument.
*/
@discardableResult
public func onComplete(_ context: ExecutionContext = ExecutionContextConstant.MainContext, f: (Either<T>) -> ()) -> Promise<T> {
self.enqueueDeliverBlock({ f($0) }, context)
return self
}
/**
Callback triggered at fulfillment of the Promise.
Registers a callback interested in fulfillment of the Promise with a result.
- parameter context: dispatch_queue on which to perform the block. Default is the main queue.
- parameter f: The block scheduled for fulfillment. Takes the result of the Promise as argument.
*/
@discardableResult
public func onSuccess(_ context: ExecutionContext = ExecutionContextConstant.MainContext, f: (T) -> ()) -> Promise<T> {
self.enqueueDeliverBlock({
switch $0 {
case .result(let result):
f(result)
case .failure:
break
}
}, context)
return self
}
/**
Callback triggered at fulfillment of the Promise.
Registers a callback interested in fulfillment of the Promise with an error.
- parameter context: dispatch_queue on which to perform the block. Default is the main queue.
- parameter f: The block scheduled for fulfillment. Takes the value of the Promise as argument.
Can throw an error wich will be carried up the Promise chain.
*/
@discardableResult
public func onFailure(_ context: ExecutionContext = ExecutionContextConstant.MainContext, f: (ErrorProtocol) -> ()) -> Promise<T> {
self.enqueueDeliverBlock({
switch $0 {
case .result:
break
case .failure(let error):
f(error)
}
}, context)
return self
}
/**
Map a Promise of type A to a Promise of type B.
Registers a callback on fulfillment, which will map the Promise to a Promise of another type.
- parameter context: dispatch queue on which to perform the block.
Default is the default queue the Promise was initialized with.
- parameter f: The block scheduled for fulfillment. Takes the result of the Promise as an argument and returning another result.
Can throw an error wich will be carried up the Promise chain.
- returns: A Promise wrapping the value produced by f
*/
public func map<R>(_ context: ExecutionContext = ExecutionContextConstant.PlaceHolderContext, f: (T) throws -> R) -> Promise<R> {
let promise = Promise<R>(self.validContext(context))
self.enqueueDeliverBlock({
switch $0 {
case .failure(let error):
promise.fulfill(.failure(error))
case .result(let result):
do {
let mappedResult = try f(result)
promise.fulfill(.result(mappedResult))
} catch let error {
promise.fulfill(.failure(error))
}
}
}, context)
return promise
}
/**
Returning a second Promise produced with the value of self by a given function f.
Monadic bind-function. Can among others be used to sequence Promises.
Because f, returning the second Promise, is called with the result of the first Promise,
the execution of f is delayed until the first Promise is fulfilled.
Has also an operator: >>=
- parameter context: dispatch queue on which to perform the block.
Default is the default queue the Promise was initialized with.
- parameter f: The block scheduled for fulfillment. Takes the value of the Promise as argument and returning a second Promise.
Can throw an error wich will be carried up the Promise chain.
- returns: The Promise produced by f
*/
public func flatMap<R>(_ context: ExecutionContext = ExecutionContextConstant.PlaceHolderContext, f: (T) throws -> Promise<R>) -> Promise<R> {
let ctx = self.validContext(context)
let placeholder = Promise<R>(ctx)
self.enqueueDeliverBlock({
switch $0 {
case .failure(let error):
placeholder.fulfill(.failure(error))
case .result(let result):
do {
// The f function can't produce a Promise until the current promise is fulfilled
// but it is required to return a promise immediately for this reason we introduce
// a placeholder which completes simultaneously with the promise produced by f.
let promise = try f(result)
promise.onComplete(ctx) { placeholder.fulfill($0) }
} catch let error {
placeholder.fulfill(.failure(error))
}
}
}, context)
return placeholder
}
public func filter(_ context: ExecutionContext = ExecutionContextConstant.PlaceHolderContext, f: (T) throws -> Bool) -> Promise<T> {
let promise = Promise<T>(self.validContext(context))
self.enqueueDeliverBlock({
switch $0 {
case .failure:
promise.fulfill($0)
case .result(let result):
do {
let passedFilter = try f(result)
if passedFilter {
promise.fulfill($0)
} else {
promise.fulfill(.failure(Error.filterNotPassed))
}
} catch let error {
promise.fulfill(.failure(error))
}
}
}, context)
return promise
}
public class func collect<R>(_ promises: [Promise<R>]) -> Promise<[R]> {
func comb(_ acc: Promise<[R]>, elem: Promise<R>) -> Promise<[R]> {
return elem >>= { x in
acc >>= { xs in
var _xs = xs
_xs.append(x)
return Promise<[R]>(value: _xs)
}
}
}
return promises.reduce(Promise<[R]>(value: []), combine: comb)
}
public class func select<R>(_ promises: [Promise<R>], context: ExecutionContext = ExecutionContextConstant.DefaultContext)
-> Promise<(Promise<R>, [Promise<R>])>
{
let promise = Promise<(Promise<R>, [Promise<R>])>(context)
for p in promises {
p.onComplete { _ in
let result = (p, promises.filter { $0 !== p } )
promise.fulfill(.result(result))
}
}
return promise
}
}
extension Promise {
private func enqueueDeliverBlock(_ block: (Either<T>) -> (), _ executionContext: ExecutionContext?) {
self.fulfillSemaphore.wait()
defer { self.fulfillSemaphore.signal() }
let ctx = executionContext != nil ? executionContext! : self.defaultExecutionContext
var (result, deliverBlocks) = self.internalValue
deliverBlocks.append((ctx, block))
self.internalValue = (result, deliverBlocks)
if let _result = result {
self.executeDeliverBlocks(_result)
}
}
private func executeDeliverBlocks(_ value: Either<T>) {
var (_, deliverBlocks) = self.internalValue
for deliverBlock in deliverBlocks {
let (executionContext, block) = deliverBlock
executionContext.async {
block(value)
}
}
deliverBlocks.removeAll()
}
private func validContext(_ context: ExecutionContext) -> ExecutionContext {
guard context.isEqual(ExecutionContextConstant.PlaceHolderContext) else {
return self.defaultExecutionContext
}
return context
}
}
private struct ExecutionContextConstant {
static let MainContext = DispatchQueue.main
static let DefaultContext = DispatchQueue.global(attributes: DispatchQueue.GlobalAttributes(rawValue: UInt64(Int(DispatchQueueAttributes.qosDefault.rawValue))))
static let PlaceHolderContext = DispatchQueue(label: "com.promise.placeHolder", attributes: DispatchQueueAttributes.concurrent)
}
| f31fa281f6629e918ad6abb7d4e04356 | 36.381148 | 161 | 0.644831 | false | false | false | false |
wireapp/wire-ios-sync-engine | refs/heads/develop | Source/Synchronization/Strategies/TeamRolesDownloadRequestStrategy.swift | gpl-3.0 | 1 | //
// Wire
// Copyright (C) 2017 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
fileprivate extension Team {
static var predicateForTeamRolesNeedingToBeUpdated: NSPredicate = {
NSPredicate(format: "%K == YES AND %K != NULL", #keyPath(Team.needsToDownloadRoles), Team.remoteIdentifierDataKey()!)
}()
func updateRoles(with payload: [String: Any]) {
guard let rolesPayload = payload["conversation_roles"] as? [[String: Any]] else { return }
let existingRoles = self.roles
// Update or insert new roles
let newRoles = rolesPayload.compactMap {
Role.createOrUpdate(with: $0, teamOrConversation: .team(self), context: managedObjectContext!)
}
// Delete removed roles
let rolesToDelete = existingRoles.subtracting(newRoles)
rolesToDelete.forEach {
managedObjectContext?.delete($0)
}
}
}
public final class TeamRolesDownloadRequestStrategy: AbstractRequestStrategy, ZMContextChangeTrackerSource, ZMRequestGeneratorSource, ZMRequestGenerator, ZMDownstreamTranscoder {
private (set) var downstreamSync: ZMDownstreamObjectSync!
fileprivate unowned var syncStatus: SyncStatus
public init(withManagedObjectContext managedObjectContext: NSManagedObjectContext, applicationStatus: ApplicationStatus, syncStatus: SyncStatus) {
self.syncStatus = syncStatus
super.init(withManagedObjectContext: managedObjectContext, applicationStatus: applicationStatus)
downstreamSync = ZMDownstreamObjectSync(
transcoder: self,
entityName: Team.entityName(),
predicateForObjectsToDownload: Team.predicateForTeamRolesNeedingToBeUpdated,
filter: nil,
managedObjectContext: managedObjectContext
)
}
public override func nextRequest(for apiVersion: APIVersion) -> ZMTransportRequest? {
let request = downstreamSync.nextRequest(for: apiVersion)
if request == nil {
completeSyncPhaseIfNoTeam()
}
return request
}
public var contextChangeTrackers: [ZMContextChangeTracker] {
return [downstreamSync]
}
public var requestGenerators: [ZMRequestGenerator] {
return [self]
}
fileprivate let expectedSyncPhase = SyncPhase.fetchingTeamRoles
fileprivate var isSyncing: Bool {
return syncStatus.currentSyncPhase == self.expectedSyncPhase
}
private func completeSyncPhaseIfNoTeam() {
if self.syncStatus.currentSyncPhase == self.expectedSyncPhase && !self.downstreamSync.hasOutstandingItems {
self.syncStatus.finishCurrentSyncPhase(phase: self.expectedSyncPhase)
}
}
// MARK: - ZMDownstreamTranscoder
public func request(forFetching object: ZMManagedObject!, downstreamSync: ZMObjectSync!, apiVersion: APIVersion) -> ZMTransportRequest! {
guard downstreamSync as? ZMDownstreamObjectSync == self.downstreamSync, let team = object as? Team else { fatal("Wrong sync or object for: \(object.safeForLoggingDescription)") }
return TeamDownloadRequestFactory.requestToDownloadRoles(for: team.remoteIdentifier!, apiVersion: apiVersion)
}
public func update(_ object: ZMManagedObject!, with response: ZMTransportResponse!, downstreamSync: ZMObjectSync!) {
guard downstreamSync as? ZMDownstreamObjectSync == self.downstreamSync,
let team = object as? Team,
let payload = response.payload?.asDictionary() as? [String: Any] else { return }
team.needsToDownloadRoles = false
team.updateRoles(with: payload)
if self.isSyncing {
self.syncStatus.finishCurrentSyncPhase(phase: self.expectedSyncPhase)
}
}
public func delete(_ object: ZMManagedObject!, with response: ZMTransportResponse!, downstreamSync: ZMObjectSync!) {
// pass
}
}
| b715d7000f0eb3ee2fcb45b59a5c6925 | 39.513514 | 186 | 0.71203 | false | false | false | false |
brunophilipe/Noto | refs/heads/master | Noto/Misc/MetricsTextStorage.swift | gpl-3.0 | 1 | //
// MetricsTextStorage.swift
// Noto
//
// Created by Bruno Philipe on 5/8/17.
// Copyright © 2017 Bruno Philipe. All rights reserved.
//
import Foundation
class MetricsTextStorage: ConcreteTextStorage
{
private var textMetrics = StringMetrics()
private var _isUpdatingMetrics = false
var observer: TextStorageObserver? = nil
var metrics: StringMetrics
{
return textMetrics
}
var isUpdatingMetrics: Bool
{
return _isUpdatingMetrics
}
override func replaceCharacters(in range: NSRange, with str: String)
{
let stringLength = (string as NSString).length
let delta = (str as NSString).length - range.length
let testRange = range.expanding(byEncapsulating: 1, maxLength: stringLength)
_isUpdatingMetrics = true
let oldMetrics = textMetrics
if let observer = self.observer
{
observer.textStorageWillUpdateMetrics(self)
}
let stringBeforeChange = attributedSubstring(from: testRange).string
super.replaceCharacters(in: range, with: str)
let rangeAfterChange = testRange.expanding(by: delta).meaningfulRange
let stringAfterChange = (stringLength + delta) > 0 ? attributedSubstring(from: rangeAfterChange).string : ""
DispatchQueue.global(qos: .utility).async
{
let metricsBeforeChange = stringBeforeChange.metrics
let metricsAfterChange = stringAfterChange.metrics
self.textMetrics = self.textMetrics - metricsBeforeChange + metricsAfterChange
self._isUpdatingMetrics = false
if let observer = self.observer
{
DispatchQueue.main.async
{
observer.textStorage(self, didUpdateMetrics: self.metrics, fromOldMetrics: oldMetrics)
}
}
}
}
}
protocol TextStorageObserver
{
func textStorageWillUpdateMetrics(_ textStorage: MetricsTextStorage)
func textStorage(_ textStorage: MetricsTextStorage, didUpdateMetrics: StringMetrics, fromOldMetrics: StringMetrics)
}
| 401544284cc89625c97b0926767f99a3 | 23.986667 | 116 | 0.751868 | false | false | false | false |
KyoheiG3/SpringIndicator | refs/heads/master | SpringIndicator/CAPropertyAnimation+Key.swift | mit | 1 | //
// CAPropertyAnimation+Key.swift
// SpringIndicator
//
// Created by Kyohei Ito on 2017/09/25.
// Copyright © 2017年 kyohei_ito. All rights reserved.
//
import UIKit
extension CAPropertyAnimation {
enum Key: String {
case strokeStart = "strokeStart"
case strokeEnd = "strokeEnd"
case strokeColor = "strokeColor"
case rotationZ = "transform.rotation.z"
case scale = "transform.scale"
}
convenience init(key: Key) {
self.init(keyPath: key.rawValue)
}
}
| e536ea8f141902681d51e22c4f780ec3 | 21.782609 | 54 | 0.64313 | false | false | false | false |
quangvu1994/Exchange | refs/heads/master | Exchange/Extension /CollapsibleTableViewHeader.swift | mit | 1 | //
// CollapsibleTableViewHeader.swift
// Exchange
//
// Created by Quang Vu on 7/27/17.
// Copyright © 2017 Quang Vu. All rights reserved.
//
import UIKit
protocol CollapsibleTableViewHeaderDelegate {
func toggleSection(header: CollapsibleTableViewHeader, section: Int)
}
class CollapsibleTableViewHeader: UITableViewHeaderFooterView {
var delegate: CollapsibleTableViewHeaderDelegate?
var section: Int = 0
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
self.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(CollapsibleTableViewHeader.selectHeaderAction(gestureRecognizer:))))
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func selectHeaderAction(gestureRecognizer: UITapGestureRecognizer){
let cell = gestureRecognizer.view as! CollapsibleTableViewHeader
delegate?.toggleSection(header: self, section: cell.section)
}
func customInit(title: String ,section: Int, delegate: CollapsibleTableViewHeaderDelegate) {
self.textLabel?.text = title
self.section = section
self.delegate = delegate
}
override func layoutSubviews() {
super.layoutSubviews()
self.textLabel?.textColor = UIColor(red: 44/255, green: 62/255, blue: 80/255, alpha: 1.0)
self.contentView.backgroundColor = UIColor(red: 234/255, green: 234/255, blue: 234/255, alpha: 1.0)
}
}
| 16620b6f06f0ae247325350e7365deef | 32.369565 | 157 | 0.708795 | false | false | false | false |
brunomorgado/ScrollableAnimation | refs/heads/master | ScrollableAnimation/Tests/ScrollableAnimationTests.swift | mit | 1 | //
// ScrollableAnimationTests.swift
// ScrollableAnimationExample
//
// Created by Bruno Morgado on 30/12/14.
// Copyright (c) 2014 kocomputer. All rights reserved.
//
import UIKit
import XCTest
import ScrollableAnimationExample
class ScrollableAnimationTests: XCTestCase {
let animationController: ScrollableAnimationController = ScrollableAnimationController()
override func setUp() {
super.setUp()
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testAddScrollableAnimation() {
var mockAnimatable = UIView(frame: CGRectMake(0, 0, 100, 100))
let animationDistance = Float(300)
let fromValue = mockAnimatable.layer.position
let toValue = CGPointMake(mockAnimatable.layer.position.x, mockAnimatable.layer.position.y + CGFloat(animationDistance))
let animatableExpectedPosition = toValue
let completionExpectation = expectationWithDescription("finished")
let translation = self.getMockTranslationFromValue(fromValue, toValue: toValue, withDistance: animationDistance)
mockAnimatable.layer.addScrollableAnimation(translation, forKey: nil, withController: self.animationController)
self.animationController.updateAnimatablesForOffset(animationDistance) {
XCTAssertEqual(mockAnimatable.layer.position, animatableExpectedPosition)
completionExpectation.fulfill()
}
waitForExpectationsWithTimeout(2, { error in
XCTAssertNil(error, "Error")
})
}
func testRemoveAllScrollableAnimations() {
var mockAnimatable = UIView(frame: CGRectMake(0, 0, 100, 100))
let animationDistance = Float(300)
let fromValue = mockAnimatable.layer.position
let toValue = CGPointMake(mockAnimatable.layer.position.x, mockAnimatable.layer.position.y + CGFloat(animationDistance))
let animatableExpectedPosition = fromValue
let translation1 = self.getMockTranslationFromValue(fromValue, toValue: toValue, withDistance: animationDistance)
let translation2 = self.getMockTranslationFromValue(fromValue, toValue: toValue, withDistance: animationDistance)
mockAnimatable.layer.addScrollableAnimation(translation1, forKey: nil, withController: self.animationController)
mockAnimatable.layer.removeAllScrollableAnimationsWithController(animationController)
self.animationController.updateAnimatablesForOffset(animationDistance, nil)
XCTAssertEqual(mockAnimatable.layer.position, animatableExpectedPosition)
mockAnimatable.layer.addScrollableAnimation(translation1, forKey: nil, withController: self.animationController)
mockAnimatable.layer.addScrollableAnimation(translation2, forKey: nil, withController: self.animationController)
mockAnimatable.layer.removeAllScrollableAnimationsWithController(animationController)
self.animationController.updateAnimatablesForOffset(animationDistance, nil)
XCTAssertEqual(mockAnimatable.layer.position, animatableExpectedPosition)
}
func testRemoveScrollableAnimationForKey() {
var mockAnimatable = UIView(frame: CGRectMake(0, 0, 100, 100))
let animationDistance = Float(300)
let fromValue = mockAnimatable.layer.position
let toValue = CGPointMake(mockAnimatable.layer.position.x, mockAnimatable.layer.position.y + CGFloat(animationDistance))
let animatableExpectedPosition = fromValue
let animationKey = "animationKey"
let completionExpectation = expectationWithDescription("finished")
let translation1 = self.getMockTranslationFromValue(fromValue, toValue: toValue, withDistance: animationDistance)
let translation2 = self.getMockTranslationFromValue(fromValue, toValue: toValue, withDistance: animationDistance)
mockAnimatable.layer.addScrollableAnimation(translation1, forKey: animationKey, withController: self.animationController)
mockAnimatable.layer.removeScrollableAnimationForKey(animationKey, withController: animationController)
self.animationController.updateAnimatablesForOffset(animationDistance, nil)
XCTAssertEqual(mockAnimatable.layer.position, animatableExpectedPosition)
mockAnimatable.layer.addScrollableAnimation(translation1, forKey: animationKey, withController: self.animationController)
mockAnimatable.layer.addScrollableAnimation(translation2, forKey: nil, withController: self.animationController)
mockAnimatable.layer.removeScrollableAnimationForKey(animationKey, withController: animationController)
self.animationController.updateAnimatablesForOffset(animationDistance) {
XCTAssertEqual(mockAnimatable.layer.position, toValue)
completionExpectation.fulfill()
}
waitForExpectationsWithTimeout(2, { error in
XCTAssertNil(error, "Error")
})
}
func testScrollableAnimationForKey() {
var mockAnimatable = UIView(frame: CGRectMake(0, 0, 100, 100))
let animationDistance = Float(300)
let fromValue = mockAnimatable.layer.position
let toValue = CGPointMake(mockAnimatable.layer.position.x, mockAnimatable.layer.position.y + CGFloat(animationDistance))
let animatableExpectedPosition = fromValue
let animationKey = "animationKey"
let translation = self.getMockTranslationFromValue(fromValue, toValue: toValue, withDistance: animationDistance)
}
// MARK: - Helper methods
private func getMockTranslationFromValue(fromValue: CGPoint, toValue: CGPoint, withDistance distance: Float) -> ScrollableBasicAnimation {
let translation = ScrollableBasicAnimation(keyPath: "position")
translation.beginOffset = 0
translation.distance = distance
translation.fromValue = NSValue(CGPoint: fromValue)
translation.toValue = NSValue(CGPoint: toValue)
return translation
}
}
| e03ab96a03e6a482fd5a7f01ec932d0a | 49.463415 | 142 | 0.736266 | false | true | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.