repo_name
stringlengths 6
91
| path
stringlengths 6
999
| copies
stringclasses 283
values | size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|---|
OscarSwanros/swift | test/SILGen/dynamic_self.swift | 2 | 19026 | // RUN: %target-swift-frontend -emit-silgen %s -disable-objc-attr-requires-foundation-module | %FileCheck %s
// RUN: %target-swift-frontend -emit-sil -O %s -disable-objc-attr-requires-foundation-module
// RUN: %target-swift-frontend -emit-ir %s -disable-objc-attr-requires-foundation-module
protocol P {
func f() -> Self
}
protocol CP : class {
func f() -> Self
}
class X : P, CP {
required init(int i: Int) { }
// CHECK-LABEL: sil hidden @_T012dynamic_self1XC1f{{[_0-9a-zA-Z]*}}F : $@convention(method) (@guaranteed X) -> @owned
func f() -> Self { return self }
// CHECK-LABEL: sil hidden @_T012dynamic_self1XC7factory{{[_0-9a-zA-Z]*}}FZ : $@convention(method) (Int, @thick X.Type) -> @owned X
// CHECK: bb0([[I:%[0-9]+]] : $Int, [[SELF:%[0-9]+]] : $@thick X.Type):
// CHECK: [[DYNAMIC_SELF:%[0-9]+]] = unchecked_trivial_bit_cast [[SELF]] : $@thick X.Type to $@thick @dynamic_self X.Type
// CHECK: [[STATIC_SELF:%[0-9]+]] = upcast [[DYNAMIC_SELF]] : $@thick @dynamic_self X.Type to $@thick X.Type
// CHECK: [[CTOR:%[0-9]+]] = class_method [[STATIC_SELF]] : $@thick X.Type, #X.init!allocator.1 : (X.Type) -> (Int) -> X, $@convention(method) (Int, @thick X.Type) -> @owned X
// CHECK: apply [[CTOR]]([[I]], [[STATIC_SELF]]) : $@convention(method) (Int, @thick X.Type) -> @owned X
class func factory(i: Int) -> Self { return self.init(int: i) }
}
class Y : X {
required init(int i: Int) {
super.init(int: i)
}
}
class GX<T> {
func f() -> Self { return self }
}
class GY<T> : GX<[T]> { }
// CHECK-LABEL: sil hidden @_T012dynamic_self23testDynamicSelfDispatch{{[_0-9a-zA-Z]*}}F : $@convention(thin) (@owned Y) -> ()
// CHECK: bb0([[Y:%[0-9]+]] : $Y):
// CHECK: [[BORROWED_Y:%.*]] = begin_borrow [[Y]]
// CHECK: [[BORROWED_Y_AS_X:%[0-9]+]] = upcast [[BORROWED_Y]] : $Y to $X
// CHECK: [[X_F:%[0-9]+]] = class_method [[BORROWED_Y_AS_X]] : $X, #X.f!1 : (X) -> () -> @dynamic_self X, $@convention(method) (@guaranteed X) -> @owned X
// CHECK: [[X_RESULT:%[0-9]+]] = apply [[X_F]]([[BORROWED_Y_AS_X]]) : $@convention(method) (@guaranteed X) -> @owned X
// CHECK: [[Y_RESULT:%[0-9]+]] = unchecked_ref_cast [[X_RESULT]] : $X to $Y
// CHECK: destroy_value [[Y_RESULT]] : $Y
// CHECK: end_borrow [[BORROWED_Y]] from [[Y]]
// CHECK: destroy_value [[Y]] : $Y
func testDynamicSelfDispatch(y: Y) {
_ = y.f()
}
// CHECK-LABEL: sil hidden @_T012dynamic_self30testDynamicSelfDispatchGeneric{{[_0-9a-zA-Z]*}}F : $@convention(thin) (@owned GY<Int>) -> ()
func testDynamicSelfDispatchGeneric(gy: GY<Int>) {
// CHECK: bb0([[GY:%[0-9]+]] : $GY<Int>):
// CHECK: [[BORROWED_GY:%.*]] = begin_borrow [[GY]]
// CHECK: [[BORROWED_GY_AS_GX:%[0-9]+]] = upcast [[BORROWED_GY]] : $GY<Int> to $GX<Array<Int>>
// CHECK: [[GX_F:%[0-9]+]] = class_method [[BORROWED_GY_AS_GX]] : $GX<Array<Int>>, #GX.f!1 : <T> (GX<T>) -> () -> @dynamic_self GX<T>, $@convention(method) <τ_0_0> (@guaranteed GX<τ_0_0>) -> @owned GX<τ_0_0>
// CHECK: [[GX_RESULT:%[0-9]+]] = apply [[GX_F]]<[Int]>([[BORROWED_GY_AS_GX]]) : $@convention(method) <τ_0_0> (@guaranteed GX<τ_0_0>) -> @owned GX<τ_0_0>
// CHECK: [[GY_RESULT:%[0-9]+]] = unchecked_ref_cast [[GX_RESULT]] : $GX<Array<Int>> to $GY<Int>
// CHECK: destroy_value [[GY_RESULT]] : $GY<Int>
// CHECK: end_borrow [[BORROWED_GY]] from [[GY]]
// CHECK: destroy_value [[GY]]
_ = gy.f()
}
// CHECK-LABEL: sil hidden @_T012dynamic_self21testArchetypeDispatch{{[_0-9a-zA-Z]*}}F : $@convention(thin) <T where T : P> (@in T) -> ()
func testArchetypeDispatch<T: P>(t: T) {
// CHECK: bb0([[T:%[0-9]+]] : $*T):
// CHECK: [[ARCHETYPE_F:%[0-9]+]] = witness_method $T, #P.f!1 : {{.*}} : $@convention(witness_method) <τ_0_0 where τ_0_0 : P> (@in_guaranteed τ_0_0) -> @out τ_0_0
// CHECK: [[T_RESULT:%[0-9]+]] = alloc_stack $T
// CHECK: [[SELF_RESULT:%[0-9]+]] = apply [[ARCHETYPE_F]]<T>([[T_RESULT]], [[T]]) : $@convention(witness_method) <τ_0_0 where τ_0_0 : P> (@in_guaranteed τ_0_0) -> @out τ_0_0
_ = t.f()
}
// CHECK-LABEL: sil hidden @_T012dynamic_self23testExistentialDispatch{{[_0-9a-zA-Z]*}}F
func testExistentialDispatch(p: P) {
// CHECK: bb0([[P:%[0-9]+]] : $*P):
// CHECK: [[PCOPY_ADDR:%[0-9]+]] = open_existential_addr immutable_access [[P]] : $*P to $*@opened([[N:".*"]]) P
// CHECK: [[P_RESULT:%[0-9]+]] = alloc_stack $P
// CHECK: [[P_RESULT_ADDR:%[0-9]+]] = init_existential_addr [[P_RESULT]] : $*P, $@opened([[N]]) P
// CHECK: [[P_F_METHOD:%[0-9]+]] = witness_method $@opened([[N]]) P, #P.f!1 : {{.*}}, [[PCOPY_ADDR]]{{.*}} : $@convention(witness_method) <τ_0_0 where τ_0_0 : P> (@in_guaranteed τ_0_0) -> @out τ_0_0
// CHECK: apply [[P_F_METHOD]]<@opened([[N]]) P>([[P_RESULT_ADDR]], [[PCOPY_ADDR]]) : $@convention(witness_method) <τ_0_0 where τ_0_0 : P> (@in_guaranteed τ_0_0) -> @out τ_0_0
// CHECK: destroy_addr [[P_RESULT]] : $*P
// CHECK: dealloc_stack [[P_RESULT]] : $*P
// CHECK: destroy_addr [[P]] : $*P
_ = p.f()
}
// CHECK-LABEL: sil hidden @_T012dynamic_self28testExistentialDispatchClass{{[_0-9a-zA-Z]*}}F : $@convention(thin) (@owned CP) -> ()
// CHECK: bb0([[CP:%[0-9]+]] : $CP):
// CHECK: [[BORROWED_CP:%.*]] = begin_borrow [[CP]]
// CHECK: [[CP_ADDR:%[0-9]+]] = open_existential_ref [[BORROWED_CP]] : $CP to $@opened([[N:".*"]]) CP
// CHECK: [[CP_F:%[0-9]+]] = witness_method $@opened([[N]]) CP, #CP.f!1 : {{.*}}, [[CP_ADDR]]{{.*}} : $@convention(witness_method) <τ_0_0 where τ_0_0 : CP> (@guaranteed τ_0_0) -> @owned τ_0_0
// CHECK: [[CP_F_RESULT:%[0-9]+]] = apply [[CP_F]]<@opened([[N]]) CP>([[CP_ADDR]]) : $@convention(witness_method) <τ_0_0 where τ_0_0 : CP> (@guaranteed τ_0_0) -> @owned τ_0_0
// CHECK: [[RESULT_EXISTENTIAL:%[0-9]+]] = init_existential_ref [[CP_F_RESULT]] : $@opened([[N]]) CP : $@opened([[N]]) CP, $CP
// CHECK: destroy_value [[RESULT_EXISTENTIAL]]
// CHECK: end_borrow [[BORROWED_CP]] from [[CP]]
// CHECK: destroy_value [[CP]]
func testExistentialDispatchClass(cp: CP) {
_ = cp.f()
}
@objc class ObjC {
@objc func method() -> Self { return self }
}
// CHECK-LABEL: sil hidden @_T012dynamic_self21testAnyObjectDispatchyyXl1o_tF : $@convention(thin) (@owned AnyObject) -> () {
func testAnyObjectDispatch(o: AnyObject) {
// CHECK: dynamic_method_br [[O_OBJ:%[0-9]+]] : $@opened({{.*}}) AnyObject, #ObjC.method!1.foreign, bb1, bb2
// CHECK: bb1([[METHOD:%[0-9]+]] : $@convention(objc_method) (@opened({{.*}}) AnyObject) -> @autoreleased AnyObject):
// CHECK: [[O_OBJ_COPY:%.*]] = copy_value [[O_OBJ]]
// CHECK: [[VAR_9:%[0-9]+]] = partial_apply [[METHOD]]([[O_OBJ_COPY]]) : $@convention(objc_method) (@opened({{.*}}) AnyObject) -> @autoreleased AnyObject
var _ = o.method
}
// CHECK: } // end sil function '_T012dynamic_self21testAnyObjectDispatchyyXl1o_tF'
// <rdar://problem/16270889> Dispatch through ObjC metatypes.
class ObjCInit {
dynamic required init() { }
}
// CHECK-LABEL: sil hidden @_T012dynamic_self12testObjCInit{{[_0-9a-zA-Z]*}}F : $@convention(thin) (@thick ObjCInit.Type) -> ()
func testObjCInit(meta: ObjCInit.Type) {
// CHECK: bb0([[THICK_META:%[0-9]+]] : $@thick ObjCInit.Type):
// CHECK: [[OBJC_META:%[0-9]+]] = thick_to_objc_metatype [[THICK_META]] : $@thick ObjCInit.Type to $@objc_metatype ObjCInit.Type
// CHECK: [[OBJ:%[0-9]+]] = alloc_ref_dynamic [objc] [[OBJC_META]] : $@objc_metatype ObjCInit.Type, $ObjCInit
// CHECK: [[BORROWED_OBJ:%.*]] = begin_borrow [[OBJ]]
// CHECK: [[INIT:%[0-9]+]] = objc_method [[BORROWED_OBJ]] : $ObjCInit, #ObjCInit.init!initializer.1.foreign : (ObjCInit.Type) -> () -> ObjCInit, $@convention(objc_method) (@owned ObjCInit) -> @owned ObjCInit
// CHECK: [[RESULT_OBJ:%[0-9]+]] = apply [[INIT]]([[OBJ]]) : $@convention(objc_method) (@owned ObjCInit) -> @owned ObjCInit
// CHECK: [[RESULT:%[0-9]+]] = tuple ()
// CHECK: return [[RESULT]] : $()
_ = meta.init()
}
class OptionalResult {
func foo() -> Self? { return self }
}
// CHECK-LABEL: sil hidden @_T012dynamic_self14OptionalResultC3fooACXDSgyF : $@convention(method) (@guaranteed OptionalResult) -> @owned Optional<OptionalResult> {
// CHECK: bb0([[SELF:%.*]] : $OptionalResult):
// CHECK-NEXT: debug_value [[SELF]] : $OptionalResult
// CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK-NEXT: [[T0:%.*]] = enum $Optional<OptionalResult>, #Optional.some!enumelt.1, [[SELF_COPY]] : $OptionalResult
// CHECK-NEXT: return [[T0]] : $Optional<OptionalResult>
// CHECK: } // end sil function '_T012dynamic_self14OptionalResultC3fooACXDSgyF'
class OptionalResultInheritor : OptionalResult {
func bar() {}
}
func testOptionalResult(v : OptionalResultInheritor) {
v.foo()?.bar()
}
// CHECK-LABEL: sil hidden @_T012dynamic_self18testOptionalResultyAA0dE9InheritorC1v_tF : $@convention(thin) (@owned OptionalResultInheritor) -> () {
// CHECK: bb0([[ARG:%.*]] : $OptionalResultInheritor):
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: [[CAST_BORROWED_ARG:%.*]] = upcast [[BORROWED_ARG]]
// CHECK: [[T0:%.*]] = class_method [[CAST_BORROWED_ARG]] : $OptionalResult, #OptionalResult.foo!1 : (OptionalResult) -> () -> @dynamic_self OptionalResult?, $@convention(method) (@guaranteed OptionalResult) -> @owned Optional<OptionalResult>
// CHECK-NEXT: [[RES:%.*]] = apply [[T0]]([[CAST_BORROWED_ARG]])
// CHECK-NEXT: [[T4:%.*]] = unchecked_ref_cast [[RES]] : $Optional<OptionalResult> to $Optional<OptionalResultInheritor>
func id<T>(_ t: T) -> T { return t }
class Z {
required init() {}
// CHECK-LABEL: sil hidden @_T012dynamic_self1ZC23testDynamicSelfCapturesACXDSi1x_tF : $@convention(method) (Int, @guaranteed Z) -> @owned Z {
func testDynamicSelfCaptures(x: Int) -> Self {
// CHECK: bb0({{.*}}, [[SELF:%.*]] : $Z):
// Single capture of 'self' type
// CHECK: [[FN:%.*]] = function_ref @_T012dynamic_self1ZC23testDynamicSelfCapturesACXDSi1x_tFyycfU_ : $@convention(thin) (@owned Z) -> ()
// CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $Z
// CHECK-NEXT: partial_apply [[FN]]([[SELF_COPY]])
let fn1 = { _ = self }
fn1()
// Capturing 'self', but it's not the last capture. Make sure it ends
// up at the end of the list anyway
// CHECK: [[FN:%.*]] = function_ref @_T012dynamic_self1ZC23testDynamicSelfCapturesACXDSi1x_tFyycfU0_ : $@convention(thin) (Int, @owned Z) -> ()
// CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $Z
// CHECK-NEXT: partial_apply [[FN]]({{.*}}, [[SELF_COPY]])
let fn2 = {
_ = self
_ = x
}
fn2()
// Capturing 'self' weak, so we have to pass in a metatype explicitly
// so that IRGen can recover metadata.
// CHECK: [[WEAK_SELF:%.*]] = alloc_box ${ var @sil_weak Optional<Z> }
// CHECK: [[FN:%.*]] = function_ref @_T012dynamic_self1ZC23testDynamicSelfCapturesACXDSi1x_tFyycfU1_ : $@convention(thin) (@owned { var @sil_weak Optional<Z> }, @thick @dynamic_self Z.Type) -> ()
// CHECK: [[WEAK_SELF_COPY:%.*]] = copy_value [[WEAK_SELF]] : ${ var @sil_weak Optional<Z> }
// CHECK-NEXT: [[DYNAMIC_SELF:%.*]] = metatype $@thick @dynamic_self Z.Type
// CHECK: partial_apply [[FN]]([[WEAK_SELF_COPY]], [[DYNAMIC_SELF]]) : $@convention(thin) (@owned { var @sil_weak Optional<Z> }, @thick @dynamic_self Z.Type) -> ()
let fn3 = {
[weak self] in
_ = self
}
fn3()
// Capturing a value with a complex type involving self
// CHECK: [[FN:%.*]] = function_ref @_T012dynamic_self1ZC23testDynamicSelfCapturesACXDSi1x_tFyycfU2_ : $@convention(thin) (@owned (Z, Z), @thick @dynamic_self Z.Type) -> ()
let xx = (self, self)
let fn4 = {
_ = xx
}
fn4()
return self
}
// Capturing metatype of dynamic self
static func testStaticMethodDynamicSelfCaptures() -> Self {
let fn0 = { _ = self; _ = { _ = self } }
fn0()
let x = self
let fn1 = { _ = x; _ = { _ = x } }
fn1()
let xx = (self, self)
let fn2 = { _ = xx; _ = { _ = xx } }
fn2()
return self.init()
}
// Make sure the actual self value has the same lowered type as the
// substituted result of a generic function call
func testDynamicSelfSubstitution(_ b: Bool) -> Self {
return b ? self : id(self)
}
// Same for metatype of self
static func testStaticMethodDynamicSelfSubstitution(_ b: Bool) -> Self {
_ = (b ? self : id(self))
return self.init()
}
}
// Unbound reference to a method returning Self.
class Factory {
required init() {}
func newInstance() -> Self { return self }
class func classNewInstance() -> Self { return self.init() }
static func staticNewInstance() -> Self { return self.init() }
}
// CHECK-LABEL: sil hidden @_T012dynamic_self22partialApplySelfReturnyAA7FactoryC1c_ADm1ttF : $@convention(thin) (@owned Factory, @thick Factory.Type) -> ()
func partialApplySelfReturn(c: Factory, t: Factory.Type) {
// CHECK: function_ref @_T012dynamic_self7FactoryC11newInstanceACXDyFTc : $@convention(thin) (@owned Factory) -> @owned @callee_owned () -> @owned Factory
_ = c.newInstance
// CHECK: function_ref @_T012dynamic_self7FactoryC11newInstanceACXDyFTc : $@convention(thin) (@owned Factory) -> @owned @callee_owned () -> @owned Factory
_ = Factory.newInstance
// CHECK: function_ref @_T012dynamic_self7FactoryC11newInstanceACXDyFTc : $@convention(thin) (@owned Factory) -> @owned @callee_owned () -> @owned Factory
_ = t.newInstance
_ = type(of: c).newInstance
// CHECK: function_ref @_T012dynamic_self7FactoryC16classNewInstanceACXDyFZTc : $@convention(thin) (@thick Factory.Type) -> @owned @callee_owned () -> @owned Factory
_ = t.classNewInstance
// CHECK: function_ref @_T012dynamic_self7FactoryC16classNewInstanceACXDyFZTc : $@convention(thin) (@thick Factory.Type) -> @owned @callee_owned () -> @owned Factory
_ = type(of: c).classNewInstance
// CHECK: function_ref @_T012dynamic_self7FactoryC16classNewInstanceACXDyFZTc : $@convention(thin) (@thick Factory.Type) -> @owned @callee_owned () -> @owned Factory
_ = Factory.classNewInstance
// CHECK: function_ref @_T012dynamic_self7FactoryC17staticNewInstanceACXDyFZTc : $@convention(thin) (@thick Factory.Type) -> @owned @callee_owned () -> @owned Factory
_ = t.staticNewInstance
// CHECK: function_ref @_T012dynamic_self7FactoryC17staticNewInstanceACXDyFZTc : $@convention(thin) (@thick Factory.Type) -> @owned @callee_owned () -> @owned Factory
_ = type(of: c).staticNewInstance
// CHECK: function_ref @_T012dynamic_self7FactoryC17staticNewInstanceACXDyFZTc : $@convention(thin) (@thick Factory.Type) -> @owned @callee_owned () -> @owned Factory
_ = Factory.staticNewInstance
}
class FactoryFactory {
// CHECK-LABEL: sil hidden @_T012dynamic_self07FactoryC0C11newInstanceACXDyFZ : $@convention(method) (@thick FactoryFactory.Type) -> @owned FactoryFactory
static func newInstance() -> Self {
// CHECK: bb0(%0 : $@thick FactoryFactory.Type):
// CHECK: [[DYNAMIC_SELF:%.*]] = unchecked_trivial_bit_cast %0 : $@thick FactoryFactory.Type to $@thick @dynamic_self FactoryFactory.Type
// CHECK: [[METATYPE:%.*]] = value_metatype $@thick @dynamic_self FactoryFactory.Type.Type, [[DYNAMIC_SELF]] : $@thick @dynamic_self FactoryFactory.Type
// CHECK: [[ANY:%.*]] = init_existential_metatype [[METATYPE]] : $@thick @dynamic_self FactoryFactory.Type.Type, $@thick Any.Type
let _: Any.Type = type(of: self)
while true {}
}
}
// Super call to a method returning Self
class Base {
required init() {}
func returnsSelf() -> Self {
return self
}
static func returnsSelfStatic() -> Self {
return self.init()
}
}
class Derived : Base {
// CHECK-LABEL: sil hidden @_T012dynamic_self7DerivedC9superCallyyF : $@convention(method) (@guaranteed Derived) -> ()
// CHECK: [[SELF:%.*]] = copy_value %0
// CHECK: [[SUPER:%.*]] = upcast [[SELF]] : $Derived to $Base
// CHECK: [[METHOD:%.*]] = function_ref @_T012dynamic_self4BaseC11returnsSelfACXDyF
// CHECK: apply [[METHOD]]([[SUPER]])
// CHECK: return
func superCall() {
_ = super.returnsSelf()
}
// CHECK-LABEL: sil hidden @_T012dynamic_self7DerivedC15superCallStaticyyFZ : $@convention(method) (@thick Derived.Type) -> ()
// CHECK: [[SUPER:%.*]] = upcast %0 : $@thick Derived.Type to $@thick Base.Type
// CHECK: [[METHOD:%.*]] = function_ref @_T012dynamic_self4BaseC17returnsSelfStaticACXDyFZ
// CHECK: apply [[METHOD]]([[SUPER]])
// CHECK: return
static func superCallStatic() {
_ = super.returnsSelfStatic()
}
// CHECK-LABEL: sil hidden @_T012dynamic_self7DerivedC32superCallFromMethodReturningSelfACXDyF : $@convention(method) (@guaranteed Derived) -> @owned Derived
// CHECK: [[SELF:%.*]] = copy_value %0
// CHECK: [[SUPER:%.*]] = upcast [[SELF]] : $Derived to $Base
// CHECK: [[METHOD:%.*]] = function_ref @_T012dynamic_self4BaseC11returnsSelfACXDyF
// CHECK: apply [[METHOD]]([[SUPER]])
// CHECK: return
func superCallFromMethodReturningSelf() -> Self {
_ = super.returnsSelf()
return self
}
// CHECK-LABEL: sil hidden @_T012dynamic_self7DerivedC38superCallFromMethodReturningSelfStaticACXDyFZ : $@convention(method) (@thick Derived.Type) -> @owned Derived
// CHECK; [[DYNAMIC_SELF:%.*]] = unchecked_trivial_bit_cast %0 : $@thick Derived.Type to $@thick @synamic_self Derived.Type
// CHECK: [[SUPER:%.*]] = upcast [[DYNAMIC_SELF]] : $@thick @dynamic_self Derived.Type to $@thick Base.Type
// CHECK: [[METHOD:%.*]] = function_ref @_T012dynamic_self4BaseC17returnsSelfStaticACXDyFZ
// CHECK: apply [[METHOD]]([[SUPER]])
// CHECK: return
static func superCallFromMethodReturningSelfStatic() -> Self {
_ = super.returnsSelfStatic()
return self.init()
}
}
class Generic<T> {
// Examples where we have to add a special argument to capture Self's metadata
func t1() -> Self {
// CHECK-LABEL: sil private @_T012dynamic_self7GenericC2t1ACyxGXDyFAEXDSgycfU_ : $@convention(thin) <T> (@owned <τ_0_0> { var @sil_weak Optional<Generic<τ_0_0>> } <T>, @thick @dynamic_self Generic<T>.Type) -> @owned Optional<Generic<T>>
_ = {[weak self] in self }
return self
}
func t2() -> Self {
// CHECK-LABEL: sil private @_T012dynamic_self7GenericC2t2ACyxGXDyFAEXD_AEXDtycfU_ : $@convention(thin) <T> (@owned (Generic<T>, Generic<T>), @thick @dynamic_self Generic<T>.Type) -> (@owned Generic<T>, @owned Generic<T>)
let selves = (self, self)
_ = { selves }
return self
}
func t3() -> Self {
// CHECK-LABEL: sil private @_T012dynamic_self7GenericC2t3ACyxGXDyFAEXDycfU_ : $@convention(thin) <T> (@owned @sil_unowned Generic<T>, @thick @dynamic_self Generic<T>.Type) -> @owned Generic<T>
_ = {[unowned self] in self }
return self
}
}
// CHECK-LABEL: sil_witness_table hidden X: P module dynamic_self {
// CHECK: method #P.f!1: {{.*}} : @_T012dynamic_self1XCAA1PA2aDP1f{{[_0-9a-zA-Z]*}}FTW
// CHECK-LABEL: sil_witness_table hidden X: CP module dynamic_self {
// CHECK: method #CP.f!1: {{.*}} : @_T012dynamic_self1XCAA2CPA2aDP1f{{[_0-9a-zA-Z]*}}FTW
| apache-2.0 |
AKIRA-MIYAKE/BisectionViewController | Carthage/Checkouts/SwiftyEvents/SwiftyEvents/Emittable.swift | 2 | 927 | //
// Emittable.swift
// SwiftyEvents
//
// Created by MiyakeAkira on 2015/04/01.
// Copyright (c) 2015年 Miyake Akira. All rights reserved.
//
public protocol Emittable {
typealias EventType: Hashable
typealias ValueType: Any
typealias FunctionType = ValueType -> Void
func on(event: EventType, _ function: FunctionType) -> Listener<ValueType>
func on(event: EventType, listener: Listener<ValueType>) -> Listener<ValueType>
func once(event: EventType, _ function: FunctionType) -> Listener<ValueType>
func removeListener(event: EventType, listener: Listener<ValueType>) -> Void
func removeAllListeners() -> Void
func removeAllListeners(events: [EventType]) -> Void
func listeners(event: EventType) -> [Listener<ValueType>]
func emit(event: EventType, value: ValueType) -> Bool
func newListener(function: FunctionType) -> Listener<ValueType>
} | mit |
ashfurrow/pragma-2015-rx-workshop | Session 4/Signup Demo/Pods/RxCocoa/RxCocoa/iOS/UILabel+Rx.swift | 11 | 782 | //
// UILabel+Rx.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 4/1/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
#if os(iOS) || os(tvOS)
import Foundation
#if !RX_NO_MODULE
import RxSwift
#endif
import UIKit
extension UILabel {
/**
Bindable sink for `text` property.
*/
public var rx_text: ObserverOf<String> {
return ObserverOf { [weak self] event in
MainScheduler.ensureExecutingOnScheduler()
switch event {
case .Next(let value):
self?.text = value
case .Error(let error):
bindingErrorToInterface(error)
break
case .Completed:
break
}
}
}
}
#endif
| mit |
natecook1000/swift-compiler-crashes | crashes-fuzzing/27933-swift-constraints-constraintsystem-simplifytype.swift | 3 | 220 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
.B:{struct B<T where h:C{class B{class a
class d:a
| mit |
natecook1000/swift-compiler-crashes | crashes-duplicates/15267-swift-sourcemanager-getmessage.swift | 11 | 202 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
for
e( {
struct A {
class
case ,
| mit |
natecook1000/swift-compiler-crashes | crashes-duplicates/19431-swift-nominaltypedecl-getdeclaredtypeincontext.swift | 11 | 265 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
var b {
protocol c : d
struct Q<T where H : String {
let a {
class A {
struct Q<T where H.b = b
| mit |
natecook1000/swift-compiler-crashes | crashes-duplicates/25275-swift-constraints-constraintsystem-solve.swift | 7 | 274 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
struct S<T{
func a{
func a{func a{A{
}
class A{
class A{struct c:a
}
}{}
}
protocol a}
class T
class b:T
| mit |
maxoumime/emoji-data-ios | Example/Tests/TableGenerator.swift | 1 | 638 | //
// TableGenerator.swift
// emojidataios
//
// Created by Maxime Bertheau on 2/15/18.
// Copyright © 2018 CocoaPods. All rights reserved.
//
import Foundation
import Quick
import Nimble
import emojidataios
class TableGenerator: QuickSpec {
override func spec() {
let table = EmojiParser.getTable()
let filename = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("table.txt")
do {
try table.write(to: filename, atomically: true, encoding: String.Encoding.utf8)
} catch {
print("Ooops! Something went wrong: \(error)")
}
}
}
| mit |
natecook1000/swift-compiler-crashes | crashes-duplicates/20894-swift-typebase-getdesugaredtype.swift | 10 | 209 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
extension t{protocol b{func<}}if true{f< | mit |
lyle-luan/firefox-ios | Client/Frontend/Login/LoginView.swift | 3 | 7875 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
// TODO: Use a strings file.
private let TextLogin = "Login"
private let TextLoginLabel = "Sign in with your Firefox account"
private let TextLoginInstead = "Sign in instead"
private let TextSignUp = "Sign up"
private let TextSignUpLabel = "Create a new Firefox account"
private let TextSignUpInstead = "Sign up instead"
private let TextForgotPassword = "Forgot password?"
private let ImagePathLogo = "guidelines-logo"
private let ImagePathEmail = "email.png"
private let ImagePathPassword = "password.png"
class LoginView: UIView {
var didClickLogin: (() -> ())?
private var loginButton: UIButton!
private var loginLabel: UILabel!
private var forgotPasswordButton: UIButton!
private var switchLoginOrSignUpButton: UIButton!
private var userText: ImageTextField!
private var passText: PasswordTextField!
private var statusLabel: UILabel!
// True if showing login state; false if showing sign up state.
private var stateLogin = true
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
didInitView()
}
override init(frame: CGRect) {
super.init(frame: frame)
didInitView()
}
override init() {
// init() calls init(frame) with a 0 rect.
super.init()
}
var username: String {
get {
return userText.text
}
set(username) {
userText.text = username
}
}
var password: String {
get {
return passText.text
}
set(password) {
passText.text = password
}
}
private func didInitView() {
backgroundColor = UIColor.darkGrayColor()
// Firefox logo
let image = UIImage(named: ImagePathLogo)!
let logo = UIImageView(image: image)
addSubview(logo)
let ratio = image.size.width / image.size.height
logo.snp_makeConstraints { make in
make.top.equalTo(60)
make.centerX.equalTo(self)
make.width.equalTo(75)
make.width.equalTo(logo.snp_height).multipliedBy(ratio)
}
// 105 text
let label105 = UILabel()
label105.textColor = UIColor.whiteColor()
label105.font = UIFont(name: "HelveticaNeue-UltraLight", size: 25)
label105.text = "105"
addSubview(label105)
label105.snp_makeConstraints { make in
make.top.equalTo(logo.snp_bottom).offset(8)
make.centerX.equalTo(self)
}
// Email address
userText = ImageTextField()
userText.setLeftImage(UIImage(named: ImagePathEmail))
userText.backgroundColor = UIColor.lightGrayColor()
userText.font = UIFont(name: "HelveticaNeue-Thin", size: 14)
userText.textColor = UIColor.whiteColor()
userText.placeholder = "Email address"
userText.layer.borderColor = UIColor.whiteColor().CGColor
userText.layer.borderWidth = 1
userText.keyboardType = UIKeyboardType.EmailAddress
addSubview(userText)
userText.snp_makeConstraints { make in
make.top.equalTo(label105.snp_bottom).offset(40)
make.left.equalTo(self.snp_left)
make.right.equalTo(self.snp_right)
make.height.equalTo(30)
}
// Password
passText = PasswordTextField()
passText.setLeftImage(UIImage(named: ImagePathPassword))
passText.backgroundColor = UIColor.lightGrayColor()
passText.font = UIFont(name: "HelveticaNeue-Thin", size: 14)
passText.textColor = UIColor.whiteColor()
passText.placeholder = "Password"
passText.layer.borderColor = UIColor.whiteColor().CGColor
passText.layer.borderWidth = 1
passText.secureTextEntry = true
addSubview(passText)
passText.snp_makeConstraints { make in
make.top.equalTo(self.userText.snp_bottom).offset(-1)
make.left.equalTo(self.snp_left)
make.right.equalTo(self.snp_right)
make.height.equalTo(30)
}
// Login label
loginLabel = UILabel()
loginLabel.font = UIFont(name: "HelveticaNeue-Thin", size: 12)
loginLabel.textColor = UIColor.whiteColor()
loginLabel.text = "Sign in with your Firefox account"
addSubview(loginLabel)
loginLabel.snp_makeConstraints { make in
make.top.equalTo(self.passText.snp_bottom).offset(5)
make.centerX.equalTo(self)
}
// Login button
loginButton = UIButton()
loginButton.titleLabel!.font = UIFont(name: "HelveticaNeue-Thin", size: 15)
loginButton.setTitle("Login", forState: UIControlState.Normal)
loginButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
loginButton.contentEdgeInsets = UIEdgeInsets(top: 10, left: 20, bottom: 10, right: 20)
loginButton.layer.borderColor = UIColor.whiteColor().CGColor
loginButton.layer.borderWidth = 1
loginButton.layer.cornerRadius = 6
addSubview(loginButton)
loginButton.snp_makeConstraints { make in
make.top.equalTo(self.loginLabel.snp_bottom).offset(25)
make.centerX.equalTo(self)
}
// Forgot password button
forgotPasswordButton = UIButton()
forgotPasswordButton.titleLabel!.font = UIFont(name: "HelveticaNeue-Thin", size: 12)
forgotPasswordButton.setTitle("Forgot password?", forState: UIControlState.Normal)
forgotPasswordButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
addSubview(forgotPasswordButton)
forgotPasswordButton.snp_makeConstraints { make in
make.top.equalTo(self.loginButton.snp_bottom).offset(25)
make.centerX.equalTo(self)
}
// Sign up or login instead button
switchLoginOrSignUpButton = UIButton()
switchLoginOrSignUpButton.titleLabel!.font = UIFont(name: "HelveticaNeue-Thin", size: 12)
switchLoginOrSignUpButton.setTitle("Sign up instead", forState: UIControlState.Normal)
switchLoginOrSignUpButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
addSubview(switchLoginOrSignUpButton)
switchLoginOrSignUpButton.snp_makeConstraints { make in
make.top.equalTo(self.forgotPasswordButton.snp_bottom)
make.centerX.equalTo(self)
}
// Click listeners
switchLoginOrSignUpButton.addTarget(self, action: "SELdidClickSwitchLoginOrSignUp", forControlEvents: UIControlEvents.TouchUpInside)
forgotPasswordButton.addTarget(self, action: "SELdidClickForgotPassword", forControlEvents: UIControlEvents.TouchUpInside)
loginButton.addTarget(self, action: "SELdidClickLogin", forControlEvents: UIControlEvents.TouchUpInside)
}
func SELdidClickSwitchLoginOrSignUp() {
stateLogin = !stateLogin
if (stateLogin) {
loginButton.setTitle(TextLogin, forState: UIControlState.Normal)
loginLabel.text = TextLoginLabel
forgotPasswordButton.hidden = false
switchLoginOrSignUpButton.setTitle(TextSignUpInstead, forState: UIControlState.Normal)
} else {
loginButton.setTitle(TextSignUp, forState: UIControlState.Normal)
loginLabel.text = TextSignUpLabel
forgotPasswordButton.hidden = true
switchLoginOrSignUpButton.setTitle(TextLoginInstead, forState: UIControlState.Normal)
}
}
func SELdidClickForgotPassword() {
}
func SELdidClickLogin() {
didClickLogin?()
}
}
| mpl-2.0 |
airspeedswift/swift-compiler-crashes | crashes-fuzzing/01726-getmemberforbasetype.swift | 12 | 267 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
protocol A {
{
{
}
}
func e
{
{
{
}
{
}
}
}
typealias e
init( )
}
func f<T {
{
}
let f = A<T> ( )
| mit |
kean/Nuke | Tests/NukeTests/ImagePrefetcherTests.swift | 1 | 8164 | // The MIT License (MIT)
//
// Copyright (c) 2015-2022 Alexander Grebenyuk (github.com/kean).
import XCTest
@testable import Nuke
final class ImagePrefetcherTests: XCTestCase {
private var pipeline: ImagePipeline!
private var dataLoader: MockDataLoader!
private var dataCache: MockDataCache!
private var imageCache: MockImageCache!
private var observer: ImagePipelineObserver!
private var prefetcher: ImagePrefetcher!
override func setUp() {
super.setUp()
dataLoader = MockDataLoader()
dataCache = MockDataCache()
imageCache = MockImageCache()
observer = ImagePipelineObserver()
pipeline = ImagePipeline(delegate: observer) {
$0.dataLoader = dataLoader
$0.imageCache = imageCache
$0.dataCache = dataCache
}
prefetcher = ImagePrefetcher(pipeline: pipeline)
}
override func tearDown() {
super.tearDown()
observer = nil
}
// MARK: Basics
/// Start prefetching for the request and then request an image separarely.
func testBasicScenario() {
dataLoader.isSuspended = true
expect(prefetcher.queue).toEnqueueOperationsWithCount(1)
prefetcher.startPrefetching(with: [Test.url])
wait()
expect(pipeline).toLoadImage(with: Test.url)
pipeline.queue.async {
self.dataLoader.isSuspended = false
}
wait()
// THEN
XCTAssertEqual(dataLoader.createdTaskCount, 1)
XCTAssertEqual(observer.startedTaskCount, 2)
}
// MARK: Start Prefetching
func testStartPrefetching() {
expectPrefetcherToComplete()
// WHEN
prefetcher.startPrefetching(with: [Test.url])
wait()
// THEN image saved in both caches
XCTAssertNotNil(pipeline.cache[Test.request])
XCTAssertNotNil(pipeline.cache.cachedData(for: Test.request))
}
func testStartPrefetchingWithTwoEquivalentURLs() {
dataLoader.isSuspended = true
expectPrefetcherToComplete()
// WHEN
prefetcher.startPrefetching(with: [Test.url])
prefetcher.startPrefetching(with: [Test.url])
pipeline.queue.async {
self.dataLoader.isSuspended = false
}
wait()
// THEN only one task is started
XCTAssertEqual(observer.startedTaskCount, 1)
}
func testWhenImageIsInMemoryCacheNoTaskStarted() {
dataLoader.isSuspended = true
// GIVEN
pipeline.cache[Test.request] = Test.container
// WHEN
prefetcher.startPrefetching(with: [Test.url])
pipeline.queue.sync {}
// THEN
XCTAssertEqual(observer.startedTaskCount, 0)
}
// MARK: Stop Prefetching
func testStopPrefetching() {
dataLoader.isSuspended = true
// WHEN
let url = Test.url
expectNotification(ImagePipelineObserver.didStartTask, object: observer)
prefetcher.startPrefetching(with: [url])
wait()
expectNotification(ImagePipelineObserver.didCancelTask, object: observer)
prefetcher.stopPrefetching(with: [url])
wait()
}
// MARK: Destination
func testStartPrefetchingDestinationDisk() {
// GIVEN
pipeline = pipeline.reconfigured {
$0.makeImageDecoder = { _ in
XCTFail("Expect image not to be decoded")
return nil
}
}
prefetcher = ImagePrefetcher(pipeline: pipeline, destination: .diskCache)
expectPrefetcherToComplete()
// WHEN
prefetcher.startPrefetching(with: [Test.url])
wait()
// THEN image saved in both caches
XCTAssertNil(pipeline.cache[Test.request])
XCTAssertNotNil(pipeline.cache.cachedData(for: Test.request))
}
// MARK: Pause
func testPausingPrefetcher() {
// WHEN
prefetcher.isPaused = true
prefetcher.startPrefetching(with: [Test.url])
let expectation = self.expectation(description: "TimePassed")
pipeline.queue.asyncAfter(deadline: .now() + .milliseconds(10)) {
expectation.fulfill()
}
wait()
// THEN
XCTAssertEqual(observer.startedTaskCount, 0)
}
// MARK: Priority
func testDefaultPrioritySetToLow() {
// WHEN start prefetching with URL
pipeline.configuration.dataLoadingQueue.isSuspended = true
let observer = expect(pipeline.configuration.dataLoadingQueue).toEnqueueOperationsWithCount(1)
prefetcher.startPrefetching(with: [Test.url])
wait()
// THEN priority is set to .low
guard let operation = observer.operations.first else {
return XCTFail("Failed to find operation")
}
XCTAssertEqual(operation.queuePriority, .low)
// Cleanup
prefetcher.stopPrefetching()
}
func testDefaultPriorityAffectsRequests() {
// WHEN start prefetching with ImageRequest
pipeline.configuration.dataLoadingQueue.isSuspended = true
let observer = expect(pipeline.configuration.dataLoadingQueue).toEnqueueOperationsWithCount(1)
let request = Test.request
XCTAssertEqual(request.priority, .normal) // Default is .normal
prefetcher.startPrefetching(with: [request])
wait()
// THEN priority is set to .low
guard let operation = observer.operations.first else {
return XCTFail("Failed to find operation")
}
XCTAssertEqual(operation.queuePriority, .low)
}
func testLowerPriorityThanDefaultNotAffected() {
// WHEN start prefetching with ImageRequest with .veryLow priority
pipeline.configuration.dataLoadingQueue.isSuspended = true
let observer = expect(pipeline.configuration.dataLoadingQueue).toEnqueueOperationsWithCount(1)
var request = Test.request
request.priority = .veryLow
prefetcher.startPrefetching(with: [request])
wait()
// THEN priority is set to .low (prefetcher priority)
guard let operation = observer.operations.first else {
return XCTFail("Failed to find operation")
}
XCTAssertEqual(operation.queuePriority, .low)
}
func testChangePriority() {
// GIVEN
prefetcher.priority = .veryHigh
// WHEN
pipeline.configuration.dataLoadingQueue.isSuspended = true
let observer = expect(pipeline.configuration.dataLoadingQueue).toEnqueueOperationsWithCount(1)
prefetcher.startPrefetching(with: [Test.url])
wait()
// THEN
guard let operation = observer.operations.first else {
return XCTFail("Failed to find operation")
}
XCTAssertEqual(operation.queuePriority, .veryHigh)
}
func testChangePriorityOfOutstandingTasks() {
// WHEN
pipeline.configuration.dataLoadingQueue.isSuspended = true
let observer = expect(pipeline.configuration.dataLoadingQueue).toEnqueueOperationsWithCount(1)
prefetcher.startPrefetching(with: [Test.url])
wait()
guard let operation = observer.operations.first else {
return XCTFail("Failed to find operation")
}
// WHEN/THEN
expect(operation).toUpdatePriority(from: .low, to: .veryLow)
prefetcher.priority = .veryLow
wait()
}
// MARK: Misc
func testThatAllPrefetchingRequestsAreStoppedWhenPrefetcherIsDeallocated() {
pipeline.configuration.dataLoadingQueue.isSuspended = true
let request = Test.request
expectNotification(ImagePipelineObserver.didStartTask, object: observer)
prefetcher.startPrefetching(with: [request])
wait()
expectNotification(ImagePipelineObserver.didCancelTask, object: observer)
autoreleasepool {
prefetcher = nil
}
wait()
}
func expectPrefetcherToComplete() {
let expectation = self.expectation(description: "PrefecherDidComplete")
prefetcher.didComplete = {
expectation.fulfill()
}
}
}
| mit |
abaca100/Nest | iOS-NestDK/TimeConditionViewController.swift | 1 | 13526 | /*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
The `TimeConditionViewController` allows the user to create a new time condition.
*/
import UIKit
import HomeKit
/// Represents a section in the `TimeConditionViewController`.
enum TimeConditionTableViewSection: Int {
/**
This section contains the segmented control to
choose a time condition type.
*/
case TimeOrSun
/**
This section contains cells to allow the selection
of 'before', 'after', or 'at'. 'At' is only available
when the exact time is specified.
*/
case BeforeOrAfter
/**
If the condition type is exact time, this section will
only have one cell, the date picker cell.
If the condition type is relative to a solar event,
this section will have two cells, one for 'sunrise' and
one for 'sunset.
*/
case Value
static let count = 3
}
/**
Represents the type of time condition.
The condition can be an exact time, or relative to a solar event.
*/
enum TimeConditionType: Int {
case Time, Sun
}
/**
Represents the type of solar event.
This can be sunrise or sunset.
*/
enum TimeConditionSunState: Int {
case Sunrise, Sunset
}
/**
Represents the condition order.
Conditions can be before, after, or exactly at a given time.
*/
enum TimeConditionOrder: Int {
case Before, After, At
}
/// A view controller that facilitates the creation of time conditions for triggers.
class TimeConditionViewController: HMCatalogViewController {
// MARK: Types
struct Identifiers {
static let selectionCell = "SelectionCell"
static let timePickerCell = "TimePickerCell"
static let segmentedTimeCell = "SegmentedTimeCell"
}
static let timeOrSunTitles = [
NSLocalizedString("Relative to time", comment: "Relative to time"),
NSLocalizedString("Relative to sun", comment: "Relative to sun")
]
static let beforeOrAfterTitles = [
NSLocalizedString("Before", comment: "Before"),
NSLocalizedString("After", comment: "After"),
NSLocalizedString("At", comment: "At")
]
static let sunriseSunsetTitles = [
NSLocalizedString("Sunrise", comment: "Sunrise"),
NSLocalizedString("Sunset", comment: "Sunset")
]
// MARK: Properties
private var timeType: TimeConditionType = .Time
private var order: TimeConditionOrder = .Before
private var sunState: TimeConditionSunState = .Sunrise
private var datePicker: UIDatePicker?
var triggerCreator: EventTriggerCreator?
// MARK: View Methods
/// Configures the table view.
override func viewDidLoad() {
super.viewDidLoad()
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 44.0
}
// MARK: Table View Methods
/// - returns: The number of `TimeConditionTableViewSection`s.
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return TimeConditionTableViewSection.count
}
/**
- returns: The number rows based on the `TimeConditionTableViewSection`
and the `timeType`.
*/
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch TimeConditionTableViewSection(rawValue: section) {
case .TimeOrSun?:
return 1
case .BeforeOrAfter?:
// If we're choosing an exact time, we add the 'At' row.
return (timeType == .Time) ? 3 : 2
case .Value?:
// Date picker cell or sunrise/sunset selection cells
return (timeType == .Time) ? 1 : 2
case nil:
fatalError("Unexpected `TimeConditionTableViewSection` raw value.")
}
}
/// Switches based on the section to generate a cell.
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
switch TimeConditionTableViewSection(rawValue: indexPath.section) {
case .TimeOrSun?:
return self.tableView(tableView, segmentedCellForRowAtIndexPath: indexPath)
case .BeforeOrAfter?:
return self.tableView(tableView, selectionCellForRowAtIndexPath: indexPath)
case .Value?:
switch timeType {
case .Time:
return self.tableView(tableView, datePickerCellForRowAtIndexPath: indexPath)
case .Sun:
return self.tableView(tableView, selectionCellForRowAtIndexPath: indexPath)
}
case nil:
fatalError("Unexpected `TimeConditionTableViewSection` raw value.")
}
}
/// - returns: A localized string describing the section.
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
switch TimeConditionTableViewSection(rawValue: section) {
case .TimeOrSun?:
return NSLocalizedString("Condition Type", comment: "Condition Type")
case .BeforeOrAfter?:
return nil
case .Value?:
if timeType == .Time {
return NSLocalizedString("Time", comment: "Time")
}
else {
return NSLocalizedString("Event", comment: "Event")
}
case nil:
fatalError("Unexpected `TimeConditionTableViewSection` raw value.")
}
}
/// - returns: A localized description for condition type section; `nil` otherwise.
override func tableView(tableView: UITableView, titleForFooterInSection section: Int) -> String? {
switch TimeConditionTableViewSection(rawValue: section) {
case .TimeOrSun?:
return NSLocalizedString("Time conditions can relate to specific times or special events, like sunrise and sunset.", comment: "Condition Type Description")
case .BeforeOrAfter?:
return nil
case .Value?:
return nil
case nil:
fatalError("Unexpected `TimeConditionTableViewSection` raw value.")
}
}
/// Updates internal values based on row selection.
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let cell = tableView.cellForRowAtIndexPath(indexPath)!
if cell.selectionStyle == .None {
return
}
tableView.deselectRowAtIndexPath(indexPath, animated: true)
switch TimeConditionTableViewSection(rawValue: indexPath.section) {
case .TimeOrSun?:
timeType = TimeConditionType(rawValue: indexPath.row)!
reloadDynamicSections()
return
case .BeforeOrAfter?:
order = TimeConditionOrder(rawValue: indexPath.row)!
tableView.reloadSections(NSIndexSet(index: indexPath.section), withRowAnimation: .Automatic)
case .Value?:
if timeType == .Sun {
sunState = TimeConditionSunState(rawValue: indexPath.row)!
}
tableView.reloadSections(NSIndexSet(index: indexPath.section), withRowAnimation: .Automatic)
case nil:
fatalError("Unexpected `TimeConditionTableViewSection` raw value.")
}
}
// MARK: Helper Methods
/**
Generates a selection cell based on the section.
Ordering and sun-state sections have selections.
*/
private func tableView(tableView: UITableView, selectionCellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(Identifiers.selectionCell, forIndexPath: indexPath)
switch TimeConditionTableViewSection(rawValue: indexPath.section) {
case .BeforeOrAfter?:
cell.textLabel?.text = TimeConditionViewController.beforeOrAfterTitles[indexPath.row]
cell.accessoryType = (order.rawValue == indexPath.row) ? .Checkmark : .None
case .Value?:
if timeType == .Sun {
cell.textLabel?.text = TimeConditionViewController.sunriseSunsetTitles[indexPath.row]
cell.accessoryType = (sunState.rawValue == indexPath.row) ? .Checkmark : .None
}
case nil:
fatalError("Unexpected `TimeConditionTableViewSection` raw value.")
default:
break
}
return cell
}
/// Generates a date picker cell and sets the internal date picker when created.
private func tableView(tableView: UITableView, datePickerCellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(Identifiers.timePickerCell, forIndexPath: indexPath) as! TimePickerCell
// Save the date picker so we can get the result later.
datePicker = cell.datePicker
return cell
}
/// Generates a segmented cell and sets its target when created.
private func tableView(tableView: UITableView, segmentedCellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(Identifiers.segmentedTimeCell, forIndexPath: indexPath) as! SegmentedTimeCell
cell.segmentedControl.selectedSegmentIndex = timeType.rawValue
cell.segmentedControl.removeTarget(nil, action: nil, forControlEvents: .AllEvents)
cell.segmentedControl.addTarget(self, action: "segmentedControlDidChange:", forControlEvents: .ValueChanged)
return cell
}
/// Creates date components from the date picker's date.
var dateComponents: NSDateComponents? {
guard let datePicker = datePicker else { return nil }
let flags: NSCalendarUnit = [.Hour, .Minute]
return NSCalendar.currentCalendar().components(flags, fromDate: datePicker.date)
}
/**
Updates the time type and reloads dynamic sections.
- parameter segmentedControl: The segmented control that changed.
*/
func segmentedControlDidChange(segmentedControl: UISegmentedControl) {
if let segmentedControlType = TimeConditionType(rawValue: segmentedControl.selectedSegmentIndex) {
timeType = segmentedControlType
}
reloadDynamicSections()
}
/// Reloads the BeforeOrAfter and Value section.
private func reloadDynamicSections() {
if timeType == .Sun && order == .At {
order = .Before
}
let reloadIndexSet = NSIndexSet(indexesInRange: NSMakeRange(TimeConditionTableViewSection.BeforeOrAfter.rawValue, 2))
tableView.reloadSections(reloadIndexSet, withRowAnimation: .Automatic)
}
// MARK: IBAction Methods
/**
Generates a predicate based on the stored values, adds
the condition to the trigger, then dismisses the view.
*/
@IBAction func saveAndDismiss(sender: UIBarButtonItem) {
var predicate: NSPredicate?
switch timeType {
case .Time:
switch order {
case .Before:
predicate = HMEventTrigger.predicateForEvaluatingTriggerOccurringBeforeDateWithComponents(dateComponents!)
case .After:
predicate = HMEventTrigger.predicateForEvaluatingTriggerOccurringAfterDateWithComponents(dateComponents!)
case .At:
predicate = HMEventTrigger.predicateForEvaluatingTriggerOccurringOnDateWithComponents(dateComponents!)
}
case .Sun:
let significantEventString = (sunState == .Sunrise) ? HMSignificantEventSunrise : HMSignificantEventSunset
switch order {
case .Before:
predicate = HMEventTrigger.predicateForEvaluatingTriggerOccurringBeforeSignificantEvent(significantEventString, applyingOffset: nil)
case .After:
predicate = HMEventTrigger.predicateForEvaluatingTriggerOccurringAfterSignificantEvent(significantEventString, applyingOffset: nil)
case .At:
// Significant events must be specified 'before' or 'after'.
break
}
}
if let predicate = predicate {
triggerCreator?.addCondition(predicate)
}
dismissViewControllerAnimated(true, completion: nil)
}
/// Cancels the creation of the conditions and exits.
@IBAction func dismiss(sender: UIBarButtonItem) {
dismissViewControllerAnimated(true, completion: nil)
}
} | apache-2.0 |
vulgur/Sources | CodeReader/View/RecentFileCell.swift | 1 | 571 | //
// RecentFileCell.swift
// CodeReader
//
// Created by vulgur on 16/6/23.
// Copyright © 2016年 MAD. All rights reserved.
//
import UIKit
class RecentFileCell: UITableViewCell {
@IBOutlet var fileNameLabel: UILabel!
@IBOutlet var ownerRepoLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| mit |
iWeslie/Ant | Ant/Ant/Me/LoginTableViewCell.swift | 2 | 1631 | //
// LoginTableViewCell.swift
// AntProfileDemo
//
// Created by Weslie on 2017/7/7.
// Copyright © 2017年 Weslie. All rights reserved.
//
import UIKit
class LoginTableViewCell: UITableViewCell {
@IBOutlet weak var avaImage: UIImageView!
@IBOutlet weak var loginHint: UILabel!
@IBOutlet weak var detialHint: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
let profileNumber = UserInfoModel.shareInstance.account?.phoneNumber
loginHint.text = profileNumber != nil ? profileNumber : "点击登录账号"
detialHint.text = profileNumber != nil ? "查看个人资料" : "登陆享用同步数据等完整功能"
//接受通知
NotificationCenter.default.addObserver(self, selector: #selector(didLogin), name: isLoginNotification, object: nil)
//登录后点击头像跳转个人界面
// let avatarTap = UITapGestureRecognizer(target: self, action: #selector(loadSelfProfileVC))
// avaImage.addGestureRecognizer(avatarTap)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
func didLogin() {
if isLogin == true {
loginHint.text = UserInfoModel.shareInstance.account?.phoneNumber
detialHint.text = "查看个人资料"
} else {
loginHint.text = "点击登录账号"
detialHint.text = "登陆享用同步数据等完整功能"
}
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
| apache-2.0 |
cardstream/iOS-SDK | cardstream-ios-sdk/CryptoSwift-0.7.2/Sources/CryptoSwift/Cipher.swift | 7 | 1800 | //
// Cipher.swift
// CryptoSwift
//
// Copyright (C) 2014-2017 Marcin Krzyżanowski <marcin@krzyzanowskim.com>
// This software is provided 'as-is', without any express or implied warranty.
//
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
//
// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required.
// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
// - This notice may not be removed or altered from any source or binary distribution.
//
public enum CipherError: Error {
case encrypt
case decrypt
}
public protocol Cipher: class {
/// Encrypt given bytes at once
///
/// - parameter bytes: Plaintext data
/// - returns: Encrypted data
func encrypt(_ bytes: ArraySlice<UInt8>) throws -> Array<UInt8>
func encrypt(_ bytes: Array<UInt8>) throws -> Array<UInt8>
/// Decrypt given bytes at once
///
/// - parameter bytes: Ciphertext data
/// - returns: Plaintext data
func decrypt(_ bytes: ArraySlice<UInt8>) throws -> Array<UInt8>
func decrypt(_ bytes: Array<UInt8>) throws -> Array<UInt8>
}
extension Cipher {
public func encrypt(_ bytes: Array<UInt8>) throws -> Array<UInt8> {
return try encrypt(bytes.slice)
}
public func decrypt(_ bytes: Array<UInt8>) throws -> Array<UInt8> {
return try decrypt(bytes.slice)
}
}
| gpl-3.0 |
rxwei/dlvm-tensor | Sources/RankedTensor/Rank.swift | 2 | 12134 | //
// Rank.swift
// RankedTensor
//
// Copyright 2016-2018 The DLVM Team.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import struct CoreTensor.TensorShape
import struct CoreTensor.TensorSlice
public protocol StaticRank {
associatedtype UnitType
associatedtype Shape
associatedtype ElementTensor
associatedtype ArrayLiteralElement
static var rank: UInt { get }
static func makeTensor(from literal: [ArrayLiteralElement]) -> Tensor<Self>
static func element(of tensor: Tensor<Self>, at index: Int) -> ElementTensor
static func element(of tensor: TensorSlice<Self>,
at index: Int) -> ElementTensor
static func updateElement(_ newElement: ElementTensor,
at index: Int, in tensor: inout Tensor<Self>)
static func updateElement(_ newElement: ElementTensor,
at index: Int, in tensor: inout TensorSlice<Self>)
}
public typealias Shape1D = (UInt)
public typealias Shape2D = (UInt, UInt)
public typealias Shape3D = (UInt, UInt, UInt)
public typealias Shape4D = (UInt, UInt, UInt, UInt)
extension StaticRank {
static func staticShape(from shape: TensorShape) -> Shape {
var elements = shape.map(UInt.init)
return withUnsafePointer(to: &elements[0]) { ptr in
ptr.withMemoryRebound(to: Shape.self, capacity: 1) { ptr in
return ptr.pointee
}
}
}
static func dynamicShape(from shape: Shape) -> TensorShape {
var shape = shape
return withUnsafePointer(to: &shape) { ptr in
ptr.withMemoryRebound(to: UInt.self, capacity: 1) { ptr in
let buf = UnsafeBufferPointer(start: ptr, count: Int(rank))
return TensorShape(buf.lazy.map {Int($0)})
}
}
}
}
public struct Rank1<T> : StaticRank {
public typealias UnitType = T
public typealias Shape = Shape1D
public typealias ElementTensor = T
public typealias ArrayLiteralElement = T
public static var rank: UInt { return 1 }
public static func makeTensor(from literal: [T]) -> Tensor<Rank1<T>> {
return Tensor<Rank1<T>>(shape: (UInt(literal.count)),
units: ContiguousArray(literal))
}
public static func makeTensor(with elements: [T]) -> Tensor<Rank1<T>> {
return makeTensor(from: elements)
}
public static func element(of tensor: Tensor<Rank1<T>>,
at index: Int) -> T {
return tensor.units[index]
}
public static func element(of tensor: TensorSlice<Rank1<T>>,
at index: Int) -> T {
let unitIndex = index.advanced(by: tensor.units.startIndex)
return tensor.units[unitIndex]
}
public static func updateElement(_ newElement: T, at index: Int,
in tensor: inout Tensor<Rank1<T>>) {
tensor.base[index] = CoreTensor.TensorSlice(scalar: newElement)
}
public static func updateElement(_ newElement: T, at index: Int,
in tensor: inout TensorSlice<Rank1<T>>) {
tensor.base[index] = CoreTensor.TensorSlice(scalar: newElement)
}
}
public struct Rank2<T> : StaticRank {
public typealias UnitType = T
public typealias Shape = Shape2D
public typealias ElementTensor = TensorSlice1D<T>
public typealias ArrayLiteralElement = [T]
public static var rank: UInt { return 2 }
public static func makeTensor(from literal: [[T]]) -> Tensor<Rank2<T>> {
let dim0 = UInt(literal.count)
guard dim0 > 0 else {
fatalError("Array literal cannot be empty")
}
let dim1 = UInt(literal[0].count)
guard dim1 > 0 else {
fatalError("The 2nd dimension cannot be empty")
}
let contSize = dim0 * dim1
var units: ContiguousArray<T> = []
units.reserveCapacity(Int(contSize))
for subArray in literal {
guard subArray.count == dim1 else {
fatalError("""
Element tensors in the 2nd dimension have mismatching shapes
""")
}
units.append(contentsOf: subArray)
}
return Tensor<Rank2<T>>(shape: (dim0, dim1), units: units)
}
public static func makeTensor(
with elements: [Tensor<Rank1<T>>]) -> Tensor<Rank2<T>> {
return makeTensor(from: elements.map { Array($0.units) })
}
public static func makeTensor(
with elements: [TensorSlice<Rank1<T>>]) -> Tensor<Rank2<T>> {
return makeTensor(from: elements.map { Array($0.units) })
}
public static func element(
of tensor: Tensor<Rank2<T>>, at index: Int) -> TensorSlice<Rank1<T>> {
return TensorSlice1D(base: tensor, index: index)
}
public static func element(
of tensor: TensorSlice<Rank2<T>>,
at index: Int
) -> TensorSlice<Rank1<T>> {
return TensorSlice1D(base: tensor, index: index)
}
public static func updateElement(_ newElement: TensorSlice<Rank1<T>>,
at index: Int,
in tensor: inout Tensor<Rank2<T>>) {
tensor.base[index] = newElement.base
}
public static func updateElement(_ newElement: TensorSlice<Rank1<T>>,
at index: Int,
in tensor: inout TensorSlice<Rank2<T>>) {
tensor.base[index] = newElement.base
}
}
public struct Rank3<T> : StaticRank {
public typealias UnitType = T
public typealias Shape = Shape3D
public typealias ElementTensor = TensorSlice2D<T>
public typealias ArrayLiteralElement = [[T]]
public static var rank: UInt { return 3 }
public static func makeTensor(from literal: [[[T]]]) -> Tensor<Rank3<T>> {
let dim0 = UInt(literal.count)
guard dim0 > 0 else {
fatalError("Array literal cannot be empty")
}
let dim1 = UInt(literal[0].count)
guard dim1 > 0 else {
fatalError("The 2nd dimension cannot be empty")
}
let dim2 = UInt(literal[0][0].count)
guard dim2 > 0 else {
fatalError("The 3rd dimension cannot be empty")
}
let contSize = dim0 * dim1 * dim2
var units: ContiguousArray<T> = []
units.reserveCapacity(Int(contSize))
for subArray in literal {
guard subArray.count == dim1 else {
fatalError("""
Element tensors in the 2nd dimension have mismatching shapes
""")
}
for subSubArray in subArray {
guard subSubArray.count == dim2 else {
fatalError("""
Element tensors in the 3nd dimension have mismatching \
shapes
""")
}
units.append(contentsOf: subSubArray)
}
}
return Tensor<Rank3<T>>(shape: (dim0, dim1, dim2), units: units)
}
public static func makeTensor(
with elements: [Tensor<Rank2<T>>]) -> Tensor<Rank3<T>> {
return makeTensor(from: elements.map { $0.map { Array($0.units) } })
}
public static func makeTensor(
with elements: [TensorSlice<Rank2<T>>]) -> Tensor<Rank3<T>> {
return makeTensor(from: elements.map { $0.map { Array($0.units) } })
}
public static func element(
of tensor: Tensor<Rank3<T>>, at index: Int) -> TensorSlice<Rank2<T>> {
return TensorSlice2D(base: tensor, index: index)
}
public static func element(of tensor: TensorSlice<Rank3<T>>,
at index: Int) -> TensorSlice<Rank2<T>> {
return TensorSlice2D(base: tensor, index: index)
}
public static func updateElement(
_ newElement: TensorSlice<Rank2<T>>,
at index: Int, in tensor: inout Tensor<Rank3<T>>
) {
tensor.base[index] = newElement.base
}
public static func updateElement(
_ newElement: TensorSlice<Rank2<T>>,
at index: Int, in tensor: inout TensorSlice<Rank3<T>>
) {
tensor.base[index] = newElement.base
}
}
public struct Rank4<T> : StaticRank {
public typealias UnitType = T
public typealias Shape = Shape4D
public typealias ElementTensor = TensorSlice3D<T>
public typealias ArrayLiteralElement = [[[T]]]
public static var rank: UInt { return 4 }
public static func makeTensor(from literal: [[[[T]]]]) -> Tensor<Rank4<T>> {
let dim0 = UInt(literal.count)
guard dim0 > 0 else {
fatalError("Array literal cannot be empty")
}
let dim1 = UInt(literal[0].count)
guard dim1 > 0 else {
fatalError("The 2nd dimension cannot be empty")
}
let dim2 = UInt(literal[0][0].count)
guard dim2 > 0 else {
fatalError("The 3rd dimension cannot be empty")
}
let dim3 = UInt(literal[0][0][0].count)
guard dim3 > 0 else {
fatalError("The 3rd dimension cannot be empty")
}
let contSize = dim0 * dim1 * dim2 * dim3
var units: ContiguousArray<T> = []
units.reserveCapacity(Int(contSize))
for subArray in literal {
guard subArray.count == dim1 else {
fatalError("""
Element tensors in the 2nd dimension have mismatching shapes
""")
}
for subSubArray in subArray {
guard subSubArray.count == dim2 else {
fatalError("""
Element tensors in the 3nd dimension have mismatching \
shapes
""")
}
for subSubSubArray in subSubArray {
guard subSubSubArray.count == dim3 else {
fatalError("""
Element tensors in the 4nd dimension have \
mismatching shapes
""")
}
units.append(contentsOf: subSubSubArray)
}
}
}
return Tensor<Rank4<T>>(shape: (dim0, dim1, dim2, dim3), units: units)
}
public static func makeTensor(
with elements: [Tensor<Rank3<T>>]) -> Tensor<Rank4<T>> {
return makeTensor(from: elements.map {
$0.map { $0.map { Array($0.units) } }
})
}
public static func makeTensor(
with elements: [TensorSlice<Rank3<T>>]) -> Tensor<Rank4<T>> {
return makeTensor(from: elements.map {
$0.map { $0.map { Array($0.units) } }
})
}
public static func element(of tensor: Tensor<Rank4<T>>,
at index: Int) -> TensorSlice<Rank3<T>> {
return TensorSlice3D(base: tensor, index: index)
}
public static func element(of tensor: TensorSlice<Rank4<T>>,
at index: Int) -> TensorSlice<Rank3<T>> {
return TensorSlice3D(base: tensor, index: index)
}
public static func updateElement(
_ newElement: TensorSlice<Rank3<T>>,
at index: Int, in tensor: inout Tensor<Rank4<T>>
) {
tensor.base[index] = newElement.base
}
public static func updateElement(
_ newElement: TensorSlice<Rank3<T>>,
at index: Int, in tensor: inout TensorSlice<Rank4<T>>
) {
tensor.base[index] = newElement.base
}
}
| apache-2.0 |
SoneeJohn/WWDC | WWDC/VideoPlayerWindowController.swift | 1 | 7028 | //
// VideoPlayerWindowController.swift
// WWDC
//
// Created by Guilherme Rambo on 04/06/16.
// Copyright © 2016 Guilherme Rambo. All rights reserved.
//
import Cocoa
import PlayerUI
public enum PUIPlayerWindowSizePreset: CGFloat {
case quarter = 0.25
case half = 0.50
case max = 1.0
}
final class VideoPlayerWindowController: NSWindowController, NSWindowDelegate {
fileprivate let fullscreenOnly: Bool
fileprivate let originalContainer: NSView!
var actionOnWindowClosed = {}
init(playerViewController: VideoPlayerViewController, fullscreenOnly: Bool = false, originalContainer: NSView? = nil) {
self.fullscreenOnly = fullscreenOnly
self.originalContainer = originalContainer
let styleMask: NSWindow.StyleMask = [NSWindow.StyleMask.titled, NSWindow.StyleMask.closable, NSWindow.StyleMask.miniaturizable, NSWindow.StyleMask.resizable, NSWindow.StyleMask.fullSizeContentView]
var rect = PUIPlayerWindow.bestScreenRectFromDetachingContainer(playerViewController.view.superview)
if rect == NSZeroRect { rect = PUIPlayerWindow.centerRectForProposedContentRect(playerViewController.view.bounds) }
let window = PUIPlayerWindow(contentRect: rect, styleMask: styleMask, backing: .buffered, defer: false)
window.isReleasedWhenClosed = true
if #available(OSX 10.11, *) {
// ¯\_(ツ)_/¯
} else {
window.collectionBehavior = NSWindow.CollectionBehavior.fullScreenPrimary
}
super.init(window: window)
window.delegate = self
contentViewController = playerViewController
window.title = playerViewController.title ?? ""
if let aspect = playerViewController.player.currentItem?.presentationSize, aspect != NSZeroSize {
window.aspectRatio = aspect
}
}
required public init?(coder: NSCoder) {
fatalError("VideoPlayerWindowController can't be initialized with a coder")
}
override func showWindow(_ sender: Any?) {
super.showWindow(sender)
if !fullscreenOnly {
(window as! PUIPlayerWindow).applySizePreset(.half)
} else {
window?.toggleFullScreen(sender)
}
}
// MARK: - Reattachment and fullscreen support
func windowWillClose(_ notification: Notification) {
(contentViewController as? VideoPlayerViewController)?.player.cancelPendingPrerolls()
(contentViewController as? VideoPlayerViewController)?.player.pause()
actionOnWindowClosed()
guard fullscreenOnly && contentViewController is VideoPlayerViewController else { return }
reattachContentViewController()
}
func windowWillExitFullScreen(_ notification: Notification) {
guard fullscreenOnly && contentViewController is VideoPlayerViewController else { return }
window?.resizeIncrements = NSSize(width: 1.0, height: 1.0)
}
func windowDidExitFullScreen(_ notification: Notification) {
guard fullscreenOnly && contentViewController is VideoPlayerViewController else { return }
reattachContentViewController()
}
fileprivate func reattachContentViewController() {
contentViewController!.view.frame = originalContainer.bounds
originalContainer.addSubview(contentViewController!.view)
originalContainer.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "|-(0)-[playerView]-(0)-|", options: [], metrics: nil, views: ["playerView": contentViewController!.view]))
originalContainer.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-(0)-[playerView]-(0)-|", options: [], metrics: nil, views: ["playerView": contentViewController!.view]))
contentViewController = nil
close()
}
func customWindowsToExitFullScreen(for window: NSWindow) -> [NSWindow]? {
guard fullscreenOnly else { return nil }
return [window]
}
func window(_ window: NSWindow, startCustomAnimationToExitFullScreenWithDuration duration: TimeInterval) {
NSAnimationContext.runAnimationGroup({ ctx in
ctx.duration = duration
let frame = PUIPlayerWindow.bestScreenRectFromDetachingContainer(originalContainer)
window.animator().setFrame(frame, display: false)
}, completionHandler: nil)
}
@IBAction func sizeWindowToHalfSize(_ sender: AnyObject?) {
(window as! PUIPlayerWindow).applySizePreset(.half)
}
@IBAction func sizeWindowToQuarterSize(_ sender: AnyObject?) {
(window as! PUIPlayerWindow).applySizePreset(.quarter)
}
@IBAction func sizeWindowToFill(_ sender: AnyObject?) {
(window as! PUIPlayerWindow).applySizePreset(.max)
}
@IBAction func floatOnTop(_ sender: NSMenuItem) {
if sender.state == .on {
toggleFloatOnTop(false)
sender.state = .off
} else {
toggleFloatOnTop(true)
sender.state = .on
}
}
fileprivate func toggleFloatOnTop(_ enable: Bool) {
let level = enable ? Int(CGWindowLevelForKey(CGWindowLevelKey.floatingWindow)) : Int(CGWindowLevelForKey(CGWindowLevelKey.normalWindow))
window?.level = NSWindow.Level(rawValue: level)
}
deinit {
#if DEBUG
Swift.print("VideoPlayerWindowController is gone")
#endif
}
}
private extension PUIPlayerWindow {
class func centerRectForProposedContentRect(_ rect: NSRect) -> NSRect {
guard let screen = NSScreen.main else { return NSZeroRect }
return NSRect(x: screen.frame.width / 2.0 - rect.width / 2.0, y: screen.frame.height / 2.0 - rect.height / 2.0, width: rect.width, height: rect.height)
}
class func bestScreenRectFromDetachingContainer(_ containerView: NSView?) -> NSRect {
guard let view = containerView, let superview = view.superview else { return NSZeroRect }
return view.window?.convertToScreen(superview.convert(view.frame, to: nil)) ?? NSZeroRect
}
func applySizePreset(_ preset: PUIPlayerWindowSizePreset, center: Bool = true, animated: Bool = true) {
guard let screen = screen else { return }
let proportion = frame.size.width / screen.visibleFrame.size.width
let idealSize: NSSize
if proportion != preset.rawValue {
let rect = NSRect(origin: CGPoint.zero, size: NSSize(width: screen.frame.size.width * preset.rawValue, height: screen.frame.size.height * preset.rawValue))
idealSize = constrainFrameRect(rect, to: screen).size
} else {
idealSize = constrainFrameRect(frame, to: screen).size
}
let origin: NSPoint
if center {
origin = NSPoint(x: screen.frame.width / 2.0 - idealSize.width / 2.0, y: screen.frame.height / 2.0 - idealSize.height / 2.0)
} else {
origin = frame.origin
}
setFrame(NSRect(origin: origin, size: idealSize), display: true, animate: animated)
}
}
| bsd-2-clause |
zhixingxi/JJA_Swift | JJA_Swift/JJA_Swift/Utils/Extensions/UIScreen+QLExtension.swift | 1 | 2924 | //
// UIScreen+QLExtension.swift
// JJA_Swift
//
// Created by MQL-IT on 2017/8/8.
// Copyright © 2017年 MQL-IT. All rights reserved.
// 根据屏幕进行尺寸和字体大小的适配
import UIKit
// MARK: - 字体大小计算属性, 相当于宏定义
var kFont10: UIFont {
return ql_autoFont(10)
}
var kFont11: UIFont {
return ql_autoFont(11)
}
var kFont12: UIFont {
return ql_autoFont(12)
}
var kFont13: UIFont {
return ql_autoFont(13)
}
var kFont14: UIFont {
return ql_autoFont(14)
}
var kFont15: UIFont {
return ql_autoFont(15)
}
var kFont16: UIFont {
return ql_autoFont(16)
}
var kFont17: UIFont {
return ql_autoFont(17)
}
/// 屏幕宽度
var myScreenWith: Double {
return Double(UIScreen.main.bounds.size.width)
}
/// 屏幕高度
var myScreenHeight: Double {
return Double(UIScreen.main.bounds.size.height)
}
//屏幕缩放比例
var myScreenScale: Double {
return Double(UIScreen.main.scale)
}
private let screen: UIScreen = UIScreen.main
func ql_autoWidth(_ width: Double) -> Double {
return screen.size_iphoneMini ? screen.width_to_mini(width) : screen.size_iphonePlus ? screen.width_to_plus(width) : width
}
func ql_autoHeight(_ height: Double) -> Double {
return screen.size_iphoneMini ? screen.height_to_mini(height) : screen.size_iphonePlus ? screen.height_to_plus(height) : height
}
func ql_autoFont(_ fontSize: Double) -> UIFont {
if screen.size_iphoneMini {
return UIFont.systemFont(ofSize: CGFloat(fontSize - 1))
} else if screen.size_iphonePlus {
return UIFont.systemFont(ofSize: CGFloat(fontSize + 1))
} else {
return UIFont.systemFont(ofSize: CGFloat(fontSize))
}
}
// MARK: - 屏幕尺寸适配相关
extension UIScreen {
//4,5,4s,5s,SE
fileprivate var size_iphoneMini: Bool {
return UIScreen.instancesRespond(to: #selector(getter: currentMode)) ? __CGSizeEqualToSize(CGSize(width: 640, height: 1136), (UIScreen.main.currentMode?.size)!) : false
}
// 6,7
fileprivate var size_iphone: Bool {
return UIScreen.instancesRespond(to: #selector(getter: currentMode)) ? __CGSizeEqualToSize(CGSize(width: 750, height: 1334), (UIScreen.main.currentMode?.size)!) : false
}
//6plus,7plus
fileprivate var size_iphonePlus: Bool {
return UIScreen.instancesRespond(to: #selector(getter: currentMode)) ? __CGSizeEqualToSize(CGSize(width: 1242, height: 2208), (UIScreen.main.currentMode?.size)!) : false
}
fileprivate func width_to_mini(_ width: Double) -> Double {
return width * 320 / 375.0
}
fileprivate func width_to_plus(_ width: Double) -> Double {
return width * 414 / 375.0
}
fileprivate func height_to_mini(_ height: Double) -> Double {
return height * 568 / 667.0
}
fileprivate func height_to_plus(_ height: Double) -> Double {
return height * 736 / 667.0
}
}
| mit |
vgorloff/AUHost | Vendor/mc/mcxUIExtensions/Sources/AppKit/NSControl.swift | 1 | 1563 | //
// NSControl.swift
// MCA-OSS-VSTNS;MCA-OSS-AUH
//
// Created by Vlad Gorlov on 06.06.2020.
// Copyright © 2020 Vlad Gorlov. All rights reserved.
//
#if canImport(AppKit) && !targetEnvironment(macCatalyst)
import AppKit
import mcxTypes
extension NSControl {
// Stub for iOS
public func setEditingChangedHandler(_ handler: (() -> Void)?) {
setHandler(handler)
}
public func setHandler(_ handler: (() -> Void)?) {
target = self
action = #selector(appActionHandler(_:))
if let handler = handler {
ObjCAssociation.setCopyNonAtomic(value: handler, to: self, forKey: &OBJCAssociationKeys.actionHandler)
}
}
public func setHandler<T: AnyObject>(_ caller: T, _ handler: @escaping (T) -> Void) {
setHandler { [weak caller] in guard let caller = caller else { return }
handler(caller)
}
}
}
extension NSControl {
private enum OBJCAssociationKeys {
static var actionHandler = "app.ui.actionHandler"
}
@objc private func appActionHandler(_ sender: NSControl) {
guard sender == self else {
return
}
if let handler: (() -> Void) = ObjCAssociation.value(from: self, forKey: &OBJCAssociationKeys.actionHandler) {
handler()
}
}
}
extension Array where Element == NSControl {
public func enable() {
forEach { $0.isEnabled = true }
}
public func disable() {
forEach { $0.isEnabled = false }
}
public func setEnabled(_ isEnabled: Bool) {
forEach { $0.isEnabled = isEnabled }
}
}
#endif
| mit |
tzhenghao/Psychologist | Psychologist/EmotionViewController.swift | 1 | 1605 | //
// EmotionViewController.swift
// Emotions
//
// Created by Zheng Hao Tan on 6/20/15.
// Copyright (c) 2015 Zheng Hao Tan. All rights reserved.
//
import UIKit
class EmotionViewController: UIViewController, FaceViewDataSource {
private struct Constants {
static let HappinessGestureScale: CGFloat = 4
}
@IBAction func changeHappiness(gesture: UIPanGestureRecognizer) {
switch gesture.state {
case .Ended: fallthrough
case .Changed:
let translation = gesture.translationInView(faceView)
let happinessChange = Int(translation.y/Constants.HappinessGestureScale)
if happinessChange != 0 {
happiness += happinessChange
gesture.setTranslation(CGPointZero, inView: faceView)
}
default: break
}
}
@IBOutlet weak var faceView: FaceView! {
didSet {
faceView.dataSource = self
faceView.addGestureRecognizer(UIPinchGestureRecognizer(target: faceView, action: "scale:"))
}
}
var happiness : Int = 75 { // 0 = very sad, 100 = happiest
didSet {
// Bound it to have range between 0 and 100
happiness = min(max(happiness, 0), 100)
println("happiness = \(happiness)")
updateUI();
}
}
func updateUI() {
faceView?.setNeedsDisplay()
title = "\(happiness)"
}
func smilinessForFaceView(sender: FaceView) -> Double? {
return Double(happiness-50)/50 // Convert from 0 to 100 scale -> -1 to 1 range.
}
}
| mit |
saidmarouf/SMZoomTransition | Example/SMNavigationController.swift | 1 | 3302 | //
// SMNavigationController.swift
// ZoomTransition
//
// Created by Said Marouf on 8/13/15.
// Copyright © 2015 Said Marouf. All rights reserved.
//
import Foundation
import UIKit
/// Naivgation controller which uses the SMZoomNavigationTransition.
/// Also combines that with a UIPercentDrivenInteractiveTransition interactive transition.
class SMNavigationController: UINavigationController, UINavigationControllerDelegate {
private var percentDrivenInteraction: UIPercentDrivenInteractiveTransition?
private var edgeGestureRecognizer: UIScreenEdgePanGestureRecognizer!
override init(rootViewController: UIViewController) {
super.init(rootViewController: rootViewController)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
func commonInit() {
self.delegate = self
}
override func viewDidLoad() {
super.viewDidLoad()
//self.view.backgroundColor = UIColor.whiteColor()
edgeGestureRecognizer = UIScreenEdgePanGestureRecognizer(target: self, action: "handleScreenEdgePan:")
edgeGestureRecognizer.edges = UIRectEdge.Left
view.addGestureRecognizer(edgeGestureRecognizer)
}
func handleScreenEdgePan(gestureRecognizer: UIScreenEdgePanGestureRecognizer) {
if let vc = topViewController {
let location = gestureRecognizer.translationInView(vc.view)
let percentage = location.x / CGRectGetWidth(vc.view.bounds)
let velocity_x = gestureRecognizer.velocityInView(vc.view).x
switch gestureRecognizer.state {
case .Began:
popViewControllerAnimated(true)
case .Changed:
percentDrivenInteraction?.updateInteractiveTransition(percentage)
case .Ended:
if percentage > 0.3 || velocity_x > 1000 {
percentDrivenInteraction?.finishInteractiveTransition()
}
else {
percentDrivenInteraction?.cancelInteractiveTransition()
}
case .Cancelled:
percentDrivenInteraction?.cancelInteractiveTransition()
default:
break
}
}
}
// MARK: - UINavigationControllerDelegate
func navigationController(navigationController: UINavigationController, animationControllerForOperation operation: UINavigationControllerOperation, fromViewController fromVC: UIViewController, toViewController toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return SMZoomNavigationAnimator(navigationOperation: operation)
}
func navigationController(navigationController: UINavigationController, interactionControllerForAnimationController animationController: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
if edgeGestureRecognizer.state == .Began {
percentDrivenInteraction = UIPercentDrivenInteractiveTransition()
percentDrivenInteraction!.completionCurve = .EaseOut
}
else {
percentDrivenInteraction = nil
}
return percentDrivenInteraction
}
}
| mit |
raulriera/TextFieldEffects | TextFieldEffects/TextFieldEffects/AkiraTextField.swift | 1 | 4486 | //
// AkiraTextField.swift
// TextFieldEffects
//
// Created by Mihaela Miches on 5/31/15.
// Copyright (c) 2015 Raul Riera. All rights reserved.
//
import UIKit
/**
An AkiraTextField is a subclass of the TextFieldEffects object, is a control that displays an UITextField with a customizable visual effect around the edges of the control.
*/
@IBDesignable open class AkiraTextField : TextFieldEffects {
private let borderSize: (active: CGFloat, inactive: CGFloat) = (1, 2)
private let borderLayer = CALayer()
private let textFieldInsets = CGPoint(x: 6, y: 0)
private let placeholderInsets = CGPoint(x: 6, y: 0)
/**
The color of the border.
This property applies a color to the bounds of the control. The default value for this property is a clear color.
*/
@IBInspectable dynamic open var borderColor: UIColor? {
didSet {
updateBorder()
}
}
/**
The color of the placeholder text.
This property applies a color to the complete placeholder string. The default value for this property is a black color.
*/
@IBInspectable dynamic open var placeholderColor: UIColor = .black {
didSet {
updatePlaceholder()
}
}
/**
The scale of the placeholder font.
This property determines the size of the placeholder label relative to the font size of the text field.
*/
@IBInspectable dynamic open var placeholderFontScale: CGFloat = 0.7 {
didSet {
updatePlaceholder()
}
}
override open var placeholder: String? {
didSet {
updatePlaceholder()
}
}
override open var bounds: CGRect {
didSet {
updateBorder()
}
}
// MARK: TextFieldEffects
override open func drawViewsForRect(_ rect: CGRect) {
updateBorder()
updatePlaceholder()
addSubview(placeholderLabel)
layer.addSublayer(borderLayer)
}
override open func animateViewsForTextEntry() {
UIView.animate(withDuration: 0.3, animations: {
self.updateBorder()
self.updatePlaceholder()
}, completion: { _ in
self.animationCompletionHandler?(.textEntry)
})
}
override open func animateViewsForTextDisplay() {
UIView.animate(withDuration: 0.3, animations: {
self.updateBorder()
self.updatePlaceholder()
}, completion: { _ in
self.animationCompletionHandler?(.textDisplay)
})
}
// MARK: Private
private func updatePlaceholder() {
placeholderLabel.frame = placeholderRect(forBounds: bounds)
placeholderLabel.text = placeholder
placeholderLabel.font = placeholderFontFromFont(font!)
placeholderLabel.textColor = placeholderColor
placeholderLabel.textAlignment = textAlignment
}
private func updateBorder() {
borderLayer.frame = rectForBounds(bounds)
borderLayer.borderWidth = (isFirstResponder || text!.isNotEmpty) ? borderSize.active : borderSize.inactive
borderLayer.borderColor = borderColor?.cgColor
}
private func placeholderFontFromFont(_ font: UIFont) -> UIFont! {
let smallerFont = UIFont(descriptor: font.fontDescriptor, size: font.pointSize * placeholderFontScale)
return smallerFont
}
private var placeholderHeight : CGFloat {
return placeholderInsets.y + placeholderFontFromFont(font!).lineHeight
}
private func rectForBounds(_ bounds: CGRect) -> CGRect {
return CGRect(x: bounds.origin.x, y: bounds.origin.y + placeholderHeight, width: bounds.size.width, height: bounds.size.height - placeholderHeight)
}
// MARK: - Overrides
open override func placeholderRect(forBounds bounds: CGRect) -> CGRect {
if isFirstResponder || text!.isNotEmpty {
return CGRect(x: placeholderInsets.x, y: placeholderInsets.y, width: bounds.width, height: placeholderHeight)
} else {
return textRect(forBounds: bounds)
}
}
open override func editingRect(forBounds bounds: CGRect) -> CGRect {
return textRect(forBounds: bounds)
}
override open func textRect(forBounds bounds: CGRect) -> CGRect {
return bounds.offsetBy(dx: textFieldInsets.x, dy: textFieldInsets.y + placeholderHeight/2)
}
}
| mit |
lady12/firefox-ios | Extensions/ShareTo/ShareViewController.swift | 7 | 11135 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import Storage
struct ShareDestination {
let code: String
let name: String
let image: String
}
// TODO: See if we can do this with an Enum instead. Previous attempts failed because for example NSSet does not take (string) enum values.
let ShareDestinationBookmarks: String = "Bookmarks"
let ShareDestinationReadingList: String = "ReadingList"
let ShareDestinations = [
ShareDestination(code: ShareDestinationReadingList, name: NSLocalizedString("Add to Reading List", tableName: "ShareTo", comment: "On/off toggle to select adding this url to your reading list"), image: "AddToReadingList"),
ShareDestination(code: ShareDestinationBookmarks, name: NSLocalizedString("Add to Bookmarks", tableName: "ShareTo", comment: "On/off toggle to select adding this url to your bookmarks"), image: "AddToBookmarks")
]
protocol ShareControllerDelegate {
func shareControllerDidCancel(shareController: ShareDialogController) -> Void
func shareController(shareController: ShareDialogController, didShareItem item: ShareItem, toDestinations destinations: NSSet) -> Void
}
private struct ShareDialogControllerUX {
static let CornerRadius: CGFloat = 4 // Corner radius of the dialog
static let NavigationBarTintColor = UIColor(rgb: 0xf37c00) // Tint color changes the text color in the navigation bar
static let NavigationBarCancelButtonFont = UIFont.systemFontOfSize(UIFont.buttonFontSize()) // System default
static let NavigationBarAddButtonFont = UIFont.boldSystemFontOfSize(UIFont.buttonFontSize()) // System default
static let NavigationBarIconSize = 38 // Width and height of the icon
static let NavigationBarBottomPadding = 12
@available(iOSApplicationExtension 8.2, *)
static let ItemTitleFontMedium = UIFont.systemFontOfSize(15, weight: UIFontWeightMedium)
static let ItemTitleFont = UIFont.systemFontOfSize(15)
static let ItemTitleMaxNumberOfLines = 2
static let ItemTitleLeftPadding = 44
static let ItemTitleRightPadding = 44
static let ItemTitleBottomPadding = 12
static let ItemLinkFont = UIFont.systemFontOfSize(12)
static let ItemLinkMaxNumberOfLines = 3
static let ItemLinkLeftPadding = 44
static let ItemLinkRightPadding = 44
static let ItemLinkBottomPadding = 14
static let DividerColor = UIColor.lightGrayColor() // Divider between the item and the table with destinations
static let DividerHeight = 0.5
static let TableRowHeight: CGFloat = 44 // System default
static let TableRowFont = UIFont.systemFontOfSize(UIFont.labelFontSize())
static let TableRowTintColor = UIColor(red:0.427, green:0.800, blue:0.102, alpha:1.0) // Green tint for the checkmark
static let TableRowTextColor = UIColor(rgb: 0x555555)
static let TableHeight = 88 // Height of 2 standard 44px cells
}
class ShareDialogController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var delegate: ShareControllerDelegate!
var item: ShareItem!
var initialShareDestinations: NSSet = NSSet(object: ShareDestinationBookmarks)
var selectedShareDestinations: NSMutableSet = NSMutableSet()
var navBar: UINavigationBar!
var navItem: UINavigationItem!
override func viewDidLoad() {
super.viewDidLoad()
selectedShareDestinations = NSMutableSet(set: initialShareDestinations)
self.view.backgroundColor = UIColor.whiteColor()
self.view.layer.cornerRadius = ShareDialogControllerUX.CornerRadius
self.view.clipsToBounds = true
// Setup the NavigationBar
navBar = UINavigationBar()
navBar.translatesAutoresizingMaskIntoConstraints = false
navBar.tintColor = ShareDialogControllerUX.NavigationBarTintColor
navBar.translucent = false
self.view.addSubview(navBar)
// Setup the NavigationItem
navItem = UINavigationItem()
navItem.leftBarButtonItem = UIBarButtonItem(title: NSLocalizedString("Cancel", comment: "Cancel button title in share dialog"), style: .Plain, target: self, action: "cancel")
navItem.leftBarButtonItem?.setTitleTextAttributes([NSFontAttributeName: ShareDialogControllerUX.NavigationBarCancelButtonFont], forState: UIControlState.Normal)
navItem.rightBarButtonItem = UIBarButtonItem(title: NSLocalizedString("Add", tableName: "ShareTo", comment: "Add button in the share dialog"), style: UIBarButtonItemStyle.Done, target: self, action: "add")
navItem.rightBarButtonItem?.setTitleTextAttributes([NSFontAttributeName: ShareDialogControllerUX.NavigationBarAddButtonFont], forState: UIControlState.Normal)
let logo = UIImageView(frame: CGRect(x: 0, y: 0, width: ShareDialogControllerUX.NavigationBarIconSize, height: ShareDialogControllerUX.NavigationBarIconSize))
logo.image = UIImage(named: "Icon-Small")
logo.contentMode = UIViewContentMode.ScaleAspectFit // TODO Can go away if icon is provided in correct size
navItem.titleView = logo
navBar.pushNavigationItem(navItem, animated: false)
// Setup the title view
let titleView = UILabel()
titleView.translatesAutoresizingMaskIntoConstraints = false
titleView.numberOfLines = ShareDialogControllerUX.ItemTitleMaxNumberOfLines
titleView.lineBreakMode = NSLineBreakMode.ByTruncatingTail
titleView.text = item.title
if #available(iOSApplicationExtension 8.2, *) {
titleView.font = ShareDialogControllerUX.ItemTitleFontMedium
} else {
// Fallback on earlier versions
titleView.font = ShareDialogControllerUX.ItemTitleFont
}
view.addSubview(titleView)
// Setup the link view
let linkView = UILabel()
linkView.translatesAutoresizingMaskIntoConstraints = false
linkView.numberOfLines = ShareDialogControllerUX.ItemLinkMaxNumberOfLines
linkView.lineBreakMode = NSLineBreakMode.ByTruncatingTail
linkView.text = item.url
linkView.font = ShareDialogControllerUX.ItemLinkFont
view.addSubview(linkView)
// Setup the icon
let iconView = UIImageView()
iconView.translatesAutoresizingMaskIntoConstraints = false
iconView.image = UIImage(named: "defaultFavicon")
view.addSubview(iconView)
// Setup the divider
let dividerView = UIView()
dividerView.translatesAutoresizingMaskIntoConstraints = false
dividerView.backgroundColor = ShareDialogControllerUX.DividerColor
view.addSubview(dividerView)
// Setup the table with destinations
let tableView = UITableView()
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.separatorInset = UIEdgeInsetsZero
tableView.layoutMargins = UIEdgeInsetsZero
tableView.userInteractionEnabled = true
tableView.delegate = self
tableView.allowsSelection = true
tableView.dataSource = self
tableView.scrollEnabled = false
view.addSubview(tableView)
// Setup constraints
let views = [
"nav": navBar,
"title": titleView,
"link": linkView,
"icon": iconView,
"divider": dividerView,
"table": tableView
]
// TODO See Bug 1102516 - Use Snappy to define share extension layout constraints
let constraints = [
"H:|[nav]|",
"V:|[nav]",
"H:|-\(ShareDialogControllerUX.ItemTitleLeftPadding)-[title]-\(ShareDialogControllerUX.ItemTitleRightPadding)-|",
"V:[nav]-\(ShareDialogControllerUX.NavigationBarBottomPadding)-[title]",
"H:|-\(ShareDialogControllerUX.ItemLinkLeftPadding)-[link]-\(ShareDialogControllerUX.ItemLinkLeftPadding)-|",
"V:[title]-\(ShareDialogControllerUX.ItemTitleBottomPadding)-[link]",
"H:|[divider]|",
"V:[divider(\(ShareDialogControllerUX.DividerHeight))]",
"V:[link]-\(ShareDialogControllerUX.ItemLinkBottomPadding)-[divider]",
"H:|[table]|",
"V:[divider][table]",
"V:[table(\(ShareDialogControllerUX.TableHeight))]|"
]
for constraint in constraints {
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(constraint, options: NSLayoutFormatOptions(), metrics: nil, views: views))
}
}
// UITabBarItem Actions that map to our delegate methods
func cancel() {
delegate?.shareControllerDidCancel(self)
}
func add() {
delegate?.shareController(self, didShareItem: item, toDestinations: NSSet(set: selectedShareDestinations))
}
// UITableView Delegate and DataSource
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return ShareDestinations.count
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return ShareDialogControllerUX.TableRowHeight
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell()
cell.textLabel?.textColor = UIAccessibilityDarkerSystemColorsEnabled() ? UIColor.darkGrayColor() : ShareDialogControllerUX.TableRowTextColor
cell.textLabel?.font = ShareDialogControllerUX.TableRowFont
cell.accessoryType = selectedShareDestinations.containsObject(ShareDestinations[indexPath.row].code) ? UITableViewCellAccessoryType.Checkmark : UITableViewCellAccessoryType.None
cell.tintColor = ShareDialogControllerUX.TableRowTintColor
cell.layoutMargins = UIEdgeInsetsZero
cell.textLabel?.text = ShareDestinations[indexPath.row].name
cell.imageView?.image = UIImage(named: ShareDestinations[indexPath.row].image)
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: false)
let code = ShareDestinations[indexPath.row].code
if selectedShareDestinations.containsObject(code) {
selectedShareDestinations.removeObject(code)
} else {
selectedShareDestinations.addObject(code)
}
tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
navItem.rightBarButtonItem?.enabled = (selectedShareDestinations.count != 0)
}
}
| mpl-2.0 |
swift-tweets/tweetup-kit | Sources/TweetupKit/APIError.swift | 1 | 244 | import Foundation
public struct APIError: Error {
public let response: HTTPURLResponse
public let json: Any
public init(response: HTTPURLResponse, json: Any) {
self.response = response
self.json = json
}
}
| mit |
vsubrahmanian/UTDemo | UTDemoTests/UTDemoTests.swift | 1 | 912 | //
// UTDemoTests.swift
// UTDemoTests
//
// Created by Vijay Subrahmanian on 25/05/15.
// Copyright (c) 2015 Vijay Subrahmanian. All rights reserved.
//
import UIKit
import XCTest
class UTDemoTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| apache-2.0 |
nathanlea/CS4153MobileAppDev | WIA/WIA9_Lea_Nathan/WIA9_Lea_Nathan/AppDelegate.swift | 1 | 6105 | //
// AppDelegate.swift
// WIA9_Lea_Nathan
//
// Created by Nathan on 10/19/15.
// Copyright © 2015 Okstate. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "CS4153AppDev.WIA9_Lea_Nathan" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("WIA9_Lea_Nathan", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| mit |
lyft/SwiftLint | Source/SwiftLintFramework/Rules/TrailingWhitespaceRule.swift | 1 | 3662 | import Foundation
import SourceKittenFramework
public struct TrailingWhitespaceRule: CorrectableRule, ConfigurationProviderRule {
public var configuration = TrailingWhitespaceConfiguration(ignoresEmptyLines: false,
ignoresComments: true)
public init() {}
public static let description = RuleDescription(
identifier: "trailing_whitespace",
name: "Trailing Whitespace",
description: "Lines should not have trailing whitespace.",
kind: .style,
nonTriggeringExamples: [ "let name: String\n", "//\n", "// \n",
"let name: String //\n", "let name: String // \n" ],
triggeringExamples: [ "let name: String \n", "/* */ let name: String \n" ],
corrections: [ "let name: String \n": "let name: String\n",
"/* */ let name: String \n": "/* */ let name: String\n"]
)
public func validate(file: File) -> [StyleViolation] {
let filteredLines = file.lines.filter {
guard $0.content.hasTrailingWhitespace() else { return false }
let commentKinds = SyntaxKind.commentKinds
if configuration.ignoresComments,
let lastSyntaxKind = file.syntaxKindsByLines[$0.index].last,
commentKinds.contains(lastSyntaxKind) {
return false
}
return !configuration.ignoresEmptyLines ||
// If configured, ignore lines that contain nothing but whitespace (empty lines)
!$0.content.trimmingCharacters(in: .whitespaces).isEmpty
}
return filteredLines.map {
StyleViolation(ruleDescription: type(of: self).description,
severity: configuration.severityConfiguration.severity,
location: Location(file: file.path, line: $0.index))
}
}
public func correct(file: File) -> [Correction] {
let whitespaceCharacterSet = CharacterSet.whitespaces
var correctedLines = [String]()
var corrections = [Correction]()
for line in file.lines {
guard line.content.hasTrailingWhitespace() else {
correctedLines.append(line.content)
continue
}
let commentKinds = SyntaxKind.commentKinds
if configuration.ignoresComments,
let lastSyntaxKind = file.syntaxKindsByLines[line.index].last,
commentKinds.contains(lastSyntaxKind) {
correctedLines.append(line.content)
continue
}
let correctedLine = line.content.bridge()
.trimmingTrailingCharacters(in: whitespaceCharacterSet)
if configuration.ignoresEmptyLines && correctedLine.isEmpty {
correctedLines.append(line.content)
continue
}
if file.ruleEnabled(violatingRanges: [line.range], for: self).isEmpty {
correctedLines.append(line.content)
continue
}
if line.content != correctedLine {
let description = type(of: self).description
let location = Location(file: file.path, line: line.index)
corrections.append(Correction(ruleDescription: description, location: location))
}
correctedLines.append(correctedLine)
}
if !corrections.isEmpty {
// join and re-add trailing newline
file.write(correctedLines.joined(separator: "\n") + "\n")
return corrections
}
return []
}
}
| mit |
haskellswift/swift-package-manager | Sources/Basic/StringConversions.swift | 2 | 2530 | /*
This source file is part of the Swift.org open source project
Copyright 2015 - 2016 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
/// Check if the given code unit needs shell escaping.
//
/// - Parameters:
/// - codeUnit: The code unit to be checked.
///
/// - Returns: True if shell escaping is not needed.
private func inShellWhitelist(_ codeUnit: UInt8) -> Bool {
switch codeUnit {
case UInt8(ascii: "a")...UInt8(ascii: "z"),
UInt8(ascii: "A")...UInt8(ascii: "Z"),
UInt8(ascii: "0")...UInt8(ascii: "9"),
UInt8(ascii: "-"),
UInt8(ascii: "_"),
UInt8(ascii: "/"),
UInt8(ascii: ":"),
UInt8(ascii: "@"),
UInt8(ascii: "%"),
UInt8(ascii: "+"),
UInt8(ascii: "="),
UInt8(ascii: "."),
UInt8(ascii: ","):
return true
default:
return false
}
}
public extension String {
/// Creates a shell escaped string. If the string does not need escaping, returns the original string.
/// Otherwise escapes using single quotes. For eg: hello -> hello, hello$world -> 'hello$world', input A -> 'input A'
///
/// - Returns: Shell escaped string.
public func shellEscaped() -> String {
// If all the characters in the string are in whitelist then no need to escape.
guard let pos = utf8.index(where: { !inShellWhitelist($0) }) else {
return self
}
// If there are no single quotes then we can just wrap the string around single quotes.
guard let singleQuotePos = utf8[pos..<utf8.endIndex].index(of: UInt8(ascii: "'")) else {
return "'" + self + "'"
}
// Otherwise iterate and escape all the single quotes.
var newString = "'" + String(utf8[utf8.startIndex..<singleQuotePos])!
for char in utf8[singleQuotePos..<utf8.endIndex] {
if char == UInt8(ascii: "'") {
newString += "'\\''"
} else {
newString += String(UnicodeScalar(char))
}
}
newString += "'"
return newString
}
/// Shell escapes the current string. This method is mutating version of shellEscaped().
public mutating func shellEscape() {
self = shellEscaped()
}
}
| apache-2.0 |
Mars182838/WJCycleScrollView | WJCycleScrollViewDemo/AppDelegate.swift | 1 | 2144 | //
// AppDelegate.swift
// WJCycleScrollViewDemo
//
// Created by 俊王 on 16/6/1.
// Copyright © 2016年 WJ. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
ftxbird/NetEaseMoive | NetEaseMoive/NetEaseMoive/Helper/YSSegmentedControl.swift | 1 | 7449 | //
// YSSegmentedControl.swift
// yemeksepeti
//
// Created by Cem Olcay on 22/04/15.
// Copyright (c) 2015 yemeksepeti. All rights reserved.
//
import UIKit
// MARK: - 主题
public struct YSSegmentedControlAppearance {
//背景色
public var backgroundColor: UIColor
//高亮背景色
public var selectedBackgroundColor: UIColor
//文本颜色
public var textColor: UIColor
//字体
public var font: UIFont
//高亮字体颜色
public var selectedTextColor: UIColor
//高亮字体
public var selectedFont: UIFont
//底部指示线颜色
public var bottomLineColor: UIColor
public var selectorColor: UIColor
//底部指示线高
public var bottomLineHeight: CGFloat
public var selectorHeight: CGFloat
//文本上部间距
public var labelTopPadding: CGFloat
}
// MARK: - Control Item
typealias YSSegmentedControlItemAction = (item: YSSegmentedControlItem) -> Void
class YSSegmentedControlItem: UIControl {
// MARK: Properties
private var willPress: YSSegmentedControlItemAction?
private var didPressed: YSSegmentedControlItemAction?
var label: UILabel!
// MARK: Init
init (
frame: CGRect,
text: String,
appearance: YSSegmentedControlAppearance,
willPress: YSSegmentedControlItemAction?,
didPressed: YSSegmentedControlItemAction?) {
super.init(frame: frame)
self.willPress = willPress
self.didPressed = didPressed
label = UILabel(frame: CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height))
label.textColor = appearance.textColor
label.font = appearance.font
label.textAlignment = .Center
label.text = text
addSubview(label)
}
required init?(coder aDecoder: NSCoder) {
super.init (coder: aDecoder)
}
// MARK: Events
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
willPress?(item: self)
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
didPressed?(item: self)
}
}
// MARK: - Control
@objc public protocol YSSegmentedControlDelegate {
optional func segmentedControlWillPressItemAtIndex (segmentedControl: YSSegmentedControl, index: Int)
optional func segmentedControlDidPressedItemAtIndex (segmentedControl: YSSegmentedControl, index: Int)
}
public typealias YSSegmentedControlAction = (segmentedControl: YSSegmentedControl, index: Int) -> Void
public class YSSegmentedControl: UIView {
// MARK: Properties
weak var delegate: YSSegmentedControlDelegate?
var action: YSSegmentedControlAction?
public var appearance: YSSegmentedControlAppearance! {
didSet {
self.draw()
}
}
var titles: [String]!
var items: [YSSegmentedControlItem]!
var selector: UIView!
// MARK: Init
public init (frame: CGRect, titles: [String], action: YSSegmentedControlAction? = nil) {
super.init (frame: frame)
self.action = action
self.titles = titles
defaultAppearance()
}
required public init? (coder aDecoder: NSCoder) {
super.init (coder: aDecoder)
}
// MARK: Draw
private func reset () {
for sub in subviews {
let v = sub
v.removeFromSuperview()
}
items = []
}
private func draw () {
reset()
backgroundColor = appearance.backgroundColor
let width = frame.size.width / CGFloat(titles.count)
var currentX: CGFloat = 0
for title in titles {
let item = YSSegmentedControlItem(
frame: CGRect(
x: currentX,
y: appearance.labelTopPadding,
width: width,
height: frame.size.height - appearance.labelTopPadding),
text: title,
appearance: appearance,
willPress: { segmentedControlItem in
let index = self.items.indexOf(segmentedControlItem)!
self.delegate?.segmentedControlWillPressItemAtIndex?(self, index: index)
},
didPressed: {
segmentedControlItem in
let index = self.items.indexOf(segmentedControlItem)!
self.selectItemAtIndex(index, withAnimation: true)
self.action?(segmentedControl: self, index: index)
self.delegate?.segmentedControlDidPressedItemAtIndex?(self, index: index)
})
addSubview(item)
items.append(item)
currentX += width
}
// bottom line
let bottomLine = CALayer ()
bottomLine.frame = CGRect(
x: 0,
y: frame.size.height - appearance.bottomLineHeight,
width: frame.size.width,
height: appearance.bottomLineHeight)
bottomLine.backgroundColor = appearance.bottomLineColor.CGColor
layer.addSublayer(bottomLine)
// selector
selector = UIView (frame: CGRect (
x: 0,
y: frame.size.height - appearance.selectorHeight,
width: width,
height: appearance.selectorHeight))
selector.backgroundColor = appearance.selectorColor
addSubview(selector)
selectItemAtIndex(0, withAnimation: true)
}
private func defaultAppearance () {
appearance = YSSegmentedControlAppearance(
backgroundColor: UIColor.clearColor(),
selectedBackgroundColor: UIColor.clearColor(),
textColor: UIColor.grayColor(),
font: UIFont.systemFontOfSize(15),
selectedTextColor: SEUIConfigCenter.sharedCenter.appColor,
selectedFont: UIFont.systemFontOfSize(15),
bottomLineColor: UIColor.blackColor(),
selectorColor: SEUIConfigCenter.sharedCenter.appColor,
bottomLineHeight: 0.5,
selectorHeight: 2,
labelTopPadding: 0)
}
// MARK: Select
public func selectItemAtIndex (index: Int, withAnimation: Bool) {
moveSelectorAtIndex(index, withAnimation: withAnimation)
for item in items {
if item == items[index] {
item.label.textColor = appearance.selectedTextColor
item.label.font = appearance.selectedFont
item.backgroundColor = appearance.selectedBackgroundColor
} else {
item.label.textColor = appearance.textColor
item.label.font = appearance.font
item.backgroundColor = appearance.backgroundColor
}
}
}
private func moveSelectorAtIndex (index: Int, withAnimation: Bool) {
let width = frame.size.width / CGFloat(items.count)
let target = width * CGFloat(index)
UIView.animateWithDuration(withAnimation ? 0.3 : 0,
delay: 0,
usingSpringWithDamping: 1,
initialSpringVelocity: 0,
options: [],
animations: {
[unowned self] in
self.selector.frame.origin.x = target
},
completion: nil)
}
}
| mit |
creatubbles/ctb-api-swift | CreatubblesAPIClient/Sources/Requests/Bubble/UpdateBubbleRequest.swift | 1 | 1894 | //
// UpdateBubbleRequest.swift
// CreatubblesAPIClient
//
// Copyright (c) 2017 Creatubbles Pte. Ltd.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
class UpdateBubbleRequest: Request {
override var method: RequestMethod { return .put }
override var parameters: Dictionary<String, AnyObject> { return prepareParameters() }
override var endpoint: String { return "bubbles/\(data.identifier)" }
fileprivate let data: UpdateBubbleData
init(data: UpdateBubbleData) {
self.data = data
}
fileprivate func prepareParameters() -> Dictionary<String, AnyObject> {
var params = Dictionary<String, AnyObject>()
params["id"] = data.identifier as AnyObject?
if let color = data.colorName {
params["color"] = color as AnyObject?
}
return params
}
}
| mit |
zozep/Alimentum | alimentum/alimentum/BusinessListingTableViewCell.swift | 1 | 619 | //
// AppDelegate.swift
// alimentum
//
// Created by Joseph Park, Nitish Dayal
// Copyright © 2016 Joseph Park, Nitish Dayal. All rights reserved.
//
// Libraries used in project include: UIKit, CoreLocation, 0AuthSwift
//
import UIKit
//MARK: - Define custom cell in MainViewController
class BusinessListingTableViewCell: UITableViewCell {
@IBOutlet weak var businessName: UILabel!
@IBOutlet weak var phoneNumber: UILabel!
@IBOutlet weak var address: UILabel!
@IBOutlet weak var foodType: UILabel!
@IBOutlet weak var rating: UILabel!
@IBOutlet weak var callPhoneNumber: UIButton!
}
| mit |
bitrise-samples/tvos-xcode72-app | tvos-xcode72-app/tvos-xcode72-appTests/tvos_xcode72_appTests.swift | 1 | 1008 | //
// tvos_xcode72_appTests.swift
// tvos-xcode72-appTests
//
// Created by Viktor Benei on 30/12/15.
// Copyright © 2015 bitrise. All rights reserved.
//
import XCTest
@testable import tvos_xcode72_app
class tvos_xcode72_appTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock {
// Put the code you want to measure the time of here.
}
}
}
| mit |
RocketChat/Rocket.Chat.iOS | Rocket.Chat/Controllers/User/UserDetail/UserDetailViewModel.swift | 1 | 1540 | //
// UserDetailViewModel.swift
// Rocket.Chat
//
// Created by Matheus Cardoso on 6/26/18.
// Copyright © 2018 Rocket.Chat. All rights reserved.
//
import Foundation
struct UserDetailViewModel {
let name: String
let username: String
let avatarUrl: URL?
let cells: [UserDetailFieldCellModel]
let messageButtonText = localized("user_details.message_button")
let voiceCallButtonText = localized("user_details.voice_call_button")
let videoCallButtonText = localized("user_details.video_call_button")
}
// MARK: Empty State
extension UserDetailViewModel {
static var emptyState: UserDetailViewModel {
return UserDetailViewModel(name: "", username: "", avatarUrl: nil, cells: [])
}
}
// MARK: User
extension UserDetailViewModel {
static func forUser(_ user: User) -> UserDetailViewModel {
return UserDetailViewModel(
name: user.name ?? user.username ?? "",
username: user.username ?? "",
avatarUrl: user.avatarURL(),
cells: UserDetailFieldCellModel.cellsForUser(user)
)
}
}
// MARK: Table View
extension UserDetailViewModel {
var numberOfSections: Int {
return 1
}
func numberOfRowsForSection(_ section: Int) -> Int {
return section == 0 ? cells.count : 0
}
func cellForRowAtIndexPath(_ indexPath: IndexPath) -> UserDetailFieldCellModel {
return
indexPath.section == 0 &&
indexPath.row < cells.count ? cells[indexPath.row] : .emptyState
}
}
| mit |
rnystrom/GitHawk | FreetimeTests/IssueCommentTableTests.swift | 1 | 3124 | //
// IssueCommentTableTests.swift
// FreetimeTests
//
// Created by B_Litwin on 6/6/18.
// Copyright © 2018 Ryan Nystrom. All rights reserved.
//
import XCTest
import StyledText
@testable import Freetime
class IssueCommentTableTests: XCTestCase {
var textItem: StyledTextRenderer!
var medTextItem: StyledTextRenderer!
var longerTextItem: StyledTextRenderer!
var tallerItem: StyledTextRenderer!
let contentSizeCategory = UIApplication.shared.preferredContentSizeCategory
override func setUp() {
super.setUp()
textItem = StyledTextRenderer(
string: StyledTextString(
styledTexts: [StyledText(
text: "item"
)]
),
contentSizeCategory: contentSizeCategory
)
medTextItem = StyledTextRenderer(
string: StyledTextString(
styledTexts: [StyledText(
text: "medium item"
)]
),
contentSizeCategory: contentSizeCategory
)
longerTextItem = StyledTextRenderer(
string: StyledTextString(
styledTexts: [StyledText(
text: "longer text length item"
)]
),
contentSizeCategory: contentSizeCategory
)
tallerItem = StyledTextRenderer(
string: StyledTextString(
styledTexts: [StyledText(
text: "T"
)]
),
contentSizeCategory: .accessibilityExtraExtraLarge
)
}
func test_tableDimensions() {
// create table rows with text elements of different sizes and test whether the
// model recieves appropriate height and width dimensions
let rowOne: [StyledTextRenderer] = [textItem, textItem, textItem]
let rowTwo: [StyledTextRenderer] = [textItem, medTextItem, textItem]
let rowThree: [StyledTextRenderer] = [textItem, textItem, longerTextItem]
let rowFour: [StyledTextRenderer] = [tallerItem, textItem, textItem]
let rows = [rowOne, rowTwo, rowThree, rowFour]
var buckets = [TableBucket()]
var rowHeights = [CGFloat]()
rows.forEach {
fillBuckets(
rows: $0,
buckets: &buckets,
rowHeights: &rowHeights,
fill: false
)
}
let model = IssueCommentTableModel(
buckets: buckets,
rowHeights: rowHeights
)
let columns = model.columns
//widths should reflect the width of widest cell in column
XCTAssertEqual(columns[0].width, textItem.viewSize(in: 0).width)
XCTAssertEqual(columns[1].width, medTextItem.viewSize(in: 0).width)
XCTAssertEqual(columns[2].width, longerTextItem.viewSize(in: 0).width)
//heights should reflect the height of the tallest cell across horizontal row
XCTAssertEqual(rowHeights[0], textItem.viewSize(in: 0).height)
XCTAssertEqual(rowHeights[3], tallerItem.viewSize(in: 0).height)
}
}
| mit |
pepibumur/Szimpla | Szimpla/Classes/Client/Fetchers/RequestsLocalFetcher.swift | 1 | 814 | import Foundation
import SwiftyJSON
internal class RequestsLocalFetcher: Fetcher<[Request]> {
// MARK: - Attributes
private let path: String
private let fileManager: FileManager
// MARK: - Init
internal init(path: String, fileManager: FileManager = FileManager.instance) {
self.path = path
self.fileManager = fileManager
}
internal static func withPath(path: String) -> RequestsLocalFetcher {
return RequestsLocalFetcher(path: path)
}
// MARK: - Fetcher
override func fetch() throws -> [Request]! {
guard let data = self.fileManager.read(path: self.path) else {
throw SnapshotFetcherError.NotFound(path)
}
return JSON(data: data).arrayValue.map(Request.init)
}
}
| mit |
adrfer/swift | validation-test/compiler_crashers_fixed/26233-swift-iterabledeclcontext-getmembers.swift | 13 | 380 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func g{{
}
({{{{{{}{{{{{{{}{{{{{{{{{{{}}{{{{{{{{}{{{(({{{}{{{{{[{{}{{{{{
class B{
func A{
{
g:
{{d:{{{f p(){
var b{{{
a){{
struct a{func g{
struct B{class S{
class a
| apache-2.0 |
thatseeyou/iOSSDKExamples | Pages/[UITableViewController] UIRefreshControl.xcplaygroundpage/Contents.swift | 1 | 2466 | /*:
# UIRefreshControl
* UITableView가 아닌 UITableViewController에서 지원한다.
* refreshControl 속성을 지정하면 된다.
*/
import Foundation
import UIKit
class TableViewController: UITableViewController {
let cellIdentifier = "Cell"
let cellImage = [#Image(imageLiteral: "people.user_simple 64.png")#]
/*:
## override UIViewController method
*/
override func viewDidLoad() {
print ("viewDidLoad")
super.viewDidLoad()
self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: cellIdentifier)
// 줄의 좌우 여백을 준다.
self.tableView.separatorInset = UIEdgeInsetsMake(0, 15, 0, 15)
self.tableView.backgroundColor = [#Color(colorLiteralRed: 0, green: 1, blue: 0, alpha: 1)#]
// UIRefreshControl
self.refreshControl = UIRefreshControl()
self.refreshControl!.addTarget(self, action: "doRefresh", forControlEvents: .ValueChanged)
}
/*:
## UITableViewDelegate protocol
*/
/*:
## UITableViewDataSource protocol
*/
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 4
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell : UITableViewCell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath)
// one-time configuration
cell.imageView?.image = cellImage
cell.textLabel?.text = "textLabel \(indexPath.section)-\(indexPath.row)"
cell.detailTextLabel?.text = "detailTextLabel"
return cell
}
func doRefresh(sender: UIRefreshControl) {
print("doRefresh")
}
func simulateUserInput() {
self.tableView.setContentOffset(CGPointMake(0, -self.refreshControl!.bounds.height), animated: true)
// 실제 환경에서는 아래의 코드는 자동으로 호출된다.
self.refreshControl!.beginRefreshing()
self.doRefresh(self.refreshControl!)
}
}
let viewController = TableViewController(style: .Plain)
PlaygroundHelper.showViewController(viewController)
Utility.runActionAfterTime(1.0) {
viewController.simulateUserInput()
}
Utility.runActionAfterTime(5.0) {
viewController.refreshControl!.endRefreshing()
}
| mit |
RxSwiftCommunity/RxWebKit | Example/RedirectViewController.swift | 1 | 1501 | //
// RedirectViewController.swift
// Example
//
// Created by Bob Godwin Obi on 10/25/17.
// Copyright © 2017 RxSwift Community. All rights reserved.
//
import UIKit
import WebKit
import RxWebKit
import RxSwift
import RxCocoa
class RedirectViewController: UIViewController {
let bag = DisposeBag()
let wkWebView = WKWebView()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(wkWebView)
wkWebView.load(URLRequest(url: URL(string: "http://www.webconfs.com/http-header-check.php")!))
wkWebView.rx
.didReceiveServerRedirectForProvisionalNavigation
.observe(on: MainScheduler.instance)
.debug("didReceiveServerRedirectForProvisionalNavigation")
.subscribe(onNext: { [weak self] webView, navigation in
guard let self = self else { return }
let alert = UIAlertController(title: "Redirect Navigation", message: "you have bene redirected", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
self.present(alert, animated: true, completion: nil)
})
.disposed(by: bag)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let originY = UIApplication.shared.statusBarFrame.maxY
wkWebView.frame = CGRect(x: 0, y: originY, width: view.bounds.width, height: view.bounds.height)
}
}
| mit |
kusl/swift | test/Serialization/function.swift | 12 | 5300 | // RUN: rm -rf %t
// RUN: mkdir %t
// RUN: %target-swift-frontend -emit-module -o %t %S/Inputs/def_func.swift
// RUN: llvm-bcanalyzer %t/def_func.swiftmodule | FileCheck %s
// RUN: %target-swift-frontend -emit-silgen -I %t %s | FileCheck %s -check-prefix=SIL
// CHECK-NOT: FALL_BACK_TO_TRANSLATION_UNIT
// CHECK-NOT: UnknownCode
import def_func
func useEq<T: EqualOperator>(x: T, y: T) -> Bool {
return x == y
}
// SIL: sil @main
// SIL: [[RAW:%.+]] = global_addr @_Tv8function3rawSi : $*Int
// SIL: [[ZERO:%.+]] = function_ref @_TF8def_func7getZeroFT_Si : $@convention(thin) () -> Int
// SIL: [[RESULT:%.+]] = apply [[ZERO]]() : $@convention(thin) () -> Int
// SIL: store [[RESULT]] to [[RAW]] : $*Int
var raw = getZero()
// Check that 'raw' is an Int
var cooked : Int = raw
// SIL: [[GET_INPUT:%.+]] = function_ref @_TF8def_func8getInputFT1xSi_Si : $@convention(thin) (Int) -> Int
// SIL: {{%.+}} = apply [[GET_INPUT]]({{%.+}}) : $@convention(thin) (Int) -> Int
var raw2 = getInput(x: raw)
// SIL: [[GET_SECOND:%.+]] = function_ref @_TF8def_func9getSecondFTSi1ySi_Si : $@convention(thin) (Int, Int) -> Int
// SIL: {{%.+}} = apply [[GET_SECOND]]({{%.+}}, {{%.+}}) : $@convention(thin) (Int, Int) -> Int
var raw3 = getSecond(raw, y: raw2)
// SIL: [[USE_NESTED:%.+]] = function_ref @_TF8def_func9useNestedFTT1xSi1ySi_1nSi_T_ : $@convention(thin) (Int, Int, Int) -> ()
// SIL: {{%.+}} = apply [[USE_NESTED]]({{%.+}}, {{%.+}}, {{%.+}}) : $@convention(thin) (Int, Int, Int) -> ()
useNested((raw, raw2), n: raw3)
// SIL: [[VARIADIC:%.+]] = function_ref @_TF8def_func8variadicFt1xSdGSaSi__T_ : $@convention(thin) (Double, @owned Array<Int>) -> ()
// SIL: [[VA_SIZE:%.+]] = integer_literal $Builtin.Word, 2
// SIL: {{%.+}} = apply {{%.*}}<Int>([[VA_SIZE]])
// SIL: {{%.+}} = apply [[VARIADIC]]({{%.+}}, {{%.+}}) : $@convention(thin) (Double, @owned Array<Int>) -> ()
variadic(x: 2.5, 4, 5)
// SIL: [[VARIADIC:%.+]] = function_ref @_TF8def_func9variadic2FTGSaSi_1xSd_T_ : $@convention(thin) (@owned Array<Int>, Double) -> ()
variadic2(1, 2, 3, x: 5.0)
// SIL: [[SLICE:%.+]] = function_ref @_TF8def_func5sliceFT1xGSaSi__T_ : $@convention(thin) (@owned Array<Int>) -> ()
// SIL: [[SLICE_SIZE:%.+]] = integer_literal $Builtin.Word, 3
// SIL: {{%.+}} = apply {{%.*}}<Int>([[SLICE_SIZE]])
// SIL: {{%.+}} = apply [[SLICE]]({{%.+}}) : $@convention(thin) (@owned Array<Int>) -> ()
slice(x: [2, 4, 5])
optional(x: .Some(23))
optional(x: .None)
// SIL: [[MAKE_PAIR:%.+]] = function_ref @_TF8def_func8makePair{{.*}} : $@convention(thin) <τ_0_0, τ_0_1> (@out (τ_0_0, τ_0_1), @in τ_0_0, @in τ_0_1) -> ()
// SIL: {{%.+}} = apply [[MAKE_PAIR]]<Int, Double>({{%.+}}, {{%.+}})
var pair : (Int, Double) = makePair(a: 1, b: 2.5)
// SIL: [[DIFFERENT_A:%.+]] = function_ref @_TF8def_func9different{{.*}} : $@convention(thin) <τ_0_0 where τ_0_0 : Equatable> (@in τ_0_0, @in τ_0_0) -> Bool
// SIL: [[DIFFERENT_B:%.+]] = function_ref @_TF8def_func9different{{.*}} : $@convention(thin) <τ_0_0 where τ_0_0 : Equatable> (@in τ_0_0, @in τ_0_0) -> Bool
different(a: 1, b: 2)
different(a: false, b: false)
// SIL: [[DIFFERENT2_A:%.+]] = function_ref @_TF8def_func10different2{{.*}} : $@convention(thin) <τ_0_0 where τ_0_0 : Equatable> (@in τ_0_0, @in τ_0_0) -> Bool
// SIL: [[DIFFERENT2_B:%.+]] = function_ref @_TF8def_func10different2{{.*}} : $@convention(thin) <τ_0_0 where τ_0_0 : Equatable> (@in τ_0_0, @in τ_0_0) -> Bool
different2(a: 1, b: 2)
different2(a: false, b: false)
struct IntWrapper1 : Wrapped {
typealias Value = Int
func getValue() -> Int { return 1 }
}
struct IntWrapper2 : Wrapped {
typealias Value = Int
func getValue() -> Int { return 2 }
}
// SIL: [[DIFFERENT_WRAPPED:%.+]] = function_ref @_TF8def_func16differentWrapped{{.*}} : $@convention(thin) <τ_0_0, τ_0_1 where τ_0_0 : Wrapped, τ_0_1 : Wrapped, τ_0_0.Value : Equatable, τ_0_0.Value == τ_0_1.Value> (@in τ_0_0, @in τ_0_1) -> Bool
differentWrapped(a: IntWrapper1(), b: IntWrapper2())
// SIL: {{%.+}} = function_ref @_TF8def_func10overloadedFT1xSi_T_ : $@convention(thin) (Int) -> ()
// SIL: {{%.+}} = function_ref @_TF8def_func10overloadedFT1xSb_T_ : $@convention(thin) (Bool) -> ()
overloaded(x: 1)
overloaded(x: false)
// SIL: {{%.+}} = function_ref @primitive : $@convention(thin) () -> ()
primitive()
if raw == 5 {
testNoReturnAttr()
testNoReturnAttrPoly(x: 5)
}
// SIL: {{%.+}} = function_ref @_TF8def_func16testNoReturnAttrFT_T_ : $@convention(thin) @noreturn () -> ()
// SIL: {{%.+}} = function_ref @_TF8def_func20testNoReturnAttrPoly{{.*}} : $@convention(thin) @noreturn <τ_0_0> (@in τ_0_0) -> ()
// SIL: sil @_TF8def_func16testNoReturnAttrFT_T_ : $@convention(thin) @noreturn () -> ()
// SIL: sil @_TF8def_func20testNoReturnAttrPoly{{.*}} : $@convention(thin) @noreturn <τ_0_0> (@in τ_0_0) -> ()
do {
try throws1()
try throws2(1)
} catch _ {}
// SIL: sil @_TF8def_func7throws1FzT_T_ : $@convention(thin) () -> @error ErrorType
// SIL: sil @_TF8def_func7throws2{{.*}} : $@convention(thin) <τ_0_0> (@out τ_0_0, @in τ_0_0) -> @error ErrorType
// LLVM: }
mineGold() // expected-warning{{you might want to keep it}}
var foo = Foo()
foo.reverse() // expected-warning{{reverseInPlace}}{{5-12=reverseInPlace}}
| apache-2.0 |
willer88/Rappi-Catalog | RappiCatalog/RappiCatalog/AppDelegate.swift | 1 | 2145 | //
// AppDelegate.swift
// RappiCatalog
//
// Created by wilmar lema on 6/13/16.
// Copyright © 2016 Lemax Inc. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
xibe/WordPress-iOS | WordPress/Classes/ViewRelated/Notifications/Controllers/NotificationSettingDetailsViewController.swift | 3 | 11022 | import Foundation
/**
* @class NotificationSettingDetailsViewController
* @brief The purpose of this class is to render a collection of NotificationSettings for a given
* Stream, encapsulated in the class NotificationSettings.Stream, and to provide the user
* a simple interface to update those settings, as needed.
*/
public class NotificationSettingDetailsViewController : UITableViewController
{
// MARK: - Initializers
public convenience init(settings: NotificationSettings) {
self.init(settings: settings, stream: settings.streams.first!)
}
public convenience init(settings: NotificationSettings, stream: NotificationSettings.Stream) {
self.init(style: .Grouped)
self.settings = settings
self.stream = stream
}
// MARK: - View Lifecycle
public override func viewDidLoad() {
super.viewDidLoad()
setupTitle()
setupNotifications()
setupTableView()
reloadTable()
}
public override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
WPAnalytics.track(.OpenedNotificationSettingDetails)
}
public override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
saveSettingsIfNeeded()
}
// MARK: - Setup Helpers
private func setupTitle() {
switch settings!.channel {
case .WordPressCom:
title = NSLocalizedString("WordPress.com Updates", comment: "WordPress.com Notification Settings Title")
default:
title = stream!.kind.description()
}
}
private func setupNotifications() {
// Reload whenever the app becomes active again since Push Settings may have changed in the meantime!
let notificationCenter = NSNotificationCenter.defaultCenter()
notificationCenter.addObserver(self,
selector: "reloadTable",
name: UIApplicationDidBecomeActiveNotification,
object: nil)
}
private func setupTableView() {
// Register the cells
tableView.registerClass(SwitchTableViewCell.self, forCellReuseIdentifier: Row.Kind.Setting.rawValue)
tableView.registerClass(WPTableViewCell.self, forCellReuseIdentifier: Row.Kind.Text.rawValue)
// Hide the separators, whenever the table is empty
tableView.tableFooterView = UIView()
// Style!
WPStyleGuide.configureColorsForView(view, andTableView: tableView)
}
@IBAction private func reloadTable() {
sections = isDeviceStreamDisabled() ? sectionsForDisabledDeviceStream() : sectionsForSettings(settings!, stream: stream!)
tableView.reloadData()
}
// MARK: - Private Helpers
private func sectionsForSettings(settings: NotificationSettings, stream: NotificationSettings.Stream) -> [Section] {
// WordPress.com Channel requires a brief description per row.
// For that reason, we'll render each row in its own section, with it's very own footer
let singleSectionMode = settings.channel != .WordPressCom
// Parse the Rows
var rows = [Row]()
for key in settings.sortedPreferenceKeys(stream) {
let description = settings.localizedDescription(key)
let value = stream.preferences?[key] ?? true
let row = Row(kind: .Setting, description: description, key: key, value: value)
rows.append(row)
}
// Single Section Mode: A single section will contain all of the rows
if singleSectionMode {
return [Section(rows: rows)]
}
// Multi Section Mode: We'll have one Section per Row
var sections = [Section]()
for row in rows {
let unwrappedKey = row.key ?? String()
let details = settings.localizedDetails(unwrappedKey)
let section = Section(rows: [row], footerText: details)
sections.append(section)
}
return sections
}
private func sectionsForDisabledDeviceStream() -> [Section] {
let description = NSLocalizedString("Go to iPhone Settings", comment: "Opens WPiOS Settings.app Section")
let row = Row(kind: .Text, description: description, key: nil, value: nil)
let footerText = NSLocalizedString("Push Notifications have been turned off in iOS Settings App. " +
"Toggle \"Allow Notifications\" to turn them back on.",
comment: "Suggests to enable Push Notification Settings in Settings.app")
let section = Section(rows: [row], footerText: footerText)
return [section]
}
// MARK: - UITableView Delegate Methods
public override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return sections.count
}
public override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sections[section].rows.count
}
public override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let section = sections[indexPath.section]
let row = section.rows[indexPath.row]
let cell = tableView.dequeueReusableCellWithIdentifier(row.kind.rawValue) as! UITableViewCell
switch row.kind {
case .Text:
configureTextCell(cell as! WPTableViewCell, row: row)
case .Setting:
configureSwitchCell(cell as! SwitchTableViewCell, row: row)
}
return cell
}
public override func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
if let footerText = sections[section].footerText {
return WPTableViewSectionHeaderFooterView.heightForFooter(footerText, width: view.bounds.width)
}
return CGFloat.min
}
public override func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
if let footerText = sections[section].footerText {
let footerView = WPTableViewSectionHeaderFooterView(reuseIdentifier: nil, style: .Footer)
footerView.title = footerText
return footerView
}
return nil
}
public override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectSelectedRowWithAnimation(true)
if isDeviceStreamDisabled() {
openApplicationSettings()
}
}
// MARK: - UITableView Helpers
private func configureTextCell(cell: WPTableViewCell, row: Row) {
cell.textLabel?.text = row.description
WPStyleGuide.configureTableViewCell(cell)
}
private func configureSwitchCell(cell: SwitchTableViewCell, row: Row) {
let settingKey = row.key ?? String()
cell.name = row.description
cell.on = newValues[settingKey] ?? (row.value ?? true)
cell.onChange = { [weak self] (newValue: Bool) in
self?.newValues[settingKey] = newValue
}
}
// MARK: - Disabled Push Notifications Handling
private func isDeviceStreamDisabled() -> Bool {
return stream?.kind == .Device && !NotificationsManager.pushNotificationsEnabledInDeviceSettings()
}
private func openApplicationSettings() {
if !UIDevice.isOS8() {
return
}
let targetURL = NSURL(string: UIApplicationOpenSettingsURLString)
UIApplication.sharedApplication().openURL(targetURL!)
}
// MARK: - Service Helpers
private func saveSettingsIfNeeded() {
if newValues.count == 0 || settings == nil {
return
}
let context = ContextManager.sharedInstance().mainContext
let service = NotificationsService(managedObjectContext: context)
service.updateSettings(settings!,
stream : stream!,
newValues : newValues,
success : {
WPAnalytics.track(.NotificationsSettingsUpdated, withProperties: ["success" : true])
},
failure : { (error: NSError!) in
WPAnalytics.track(.NotificationsSettingsUpdated, withProperties: ["success" : false])
self.handleUpdateError()
})
}
private func handleUpdateError() {
UIAlertView.showWithTitle(NSLocalizedString("Oops!", comment: ""),
message : NSLocalizedString("There has been an unexpected error while updating " +
"your Notification Settings",
comment: "Displayed after a failed Notification Settings call"),
style : .Default,
cancelButtonTitle : NSLocalizedString("Cancel", comment: "Cancel. Action."),
otherButtonTitles : [ NSLocalizedString("Retry", comment: "Retry. Action") ],
tapBlock : { (alertView: UIAlertView!, buttonIndex: Int) -> Void in
if alertView.cancelButtonIndex == buttonIndex {
return
}
self.saveSettingsIfNeeded()
})
}
// MARK: - Private Nested Class'ess
private class Section {
var rows : [Row]
var footerText : String?
init(rows: [Row], footerText: String? = nil) {
self.rows = rows
self.footerText = footerText
}
}
private class Row {
let description : String
let kind : Kind
let key : String?
let value : Bool?
init(kind: Kind, description: String, key: String? = nil, value: Bool? = nil) {
self.description = description
self.kind = kind
self.key = key
self.value = value
}
enum Kind : String {
case Setting = "SwitchCell"
case Text = "TextCell"
}
}
// MARK: - Private Properties
private var settings : NotificationSettings?
private var stream : NotificationSettings.Stream?
// MARK: - Helpers
private var sections = [Section]()
private var newValues = [String: Bool]()
}
| gpl-2.0 |
producthunt/PHImageKit | PHImageKitTests/PHDonwloaderTests.swift | 1 | 4780 | //
// PHDonwloaderTests.swift
// PHImageKit
//
// Created by Vlado on 12/7/15.
// Copyright © 2015 Product Hunt. All rights reserved.
//
import XCTest
import UIKit
@testable import PHImageKit
class PHDonwloaderTests: XCTestCase {
let downloader = PHDownloader()
let urlPath = "http://producthunt.com/test.jpg"
override class func setUp() {
super.setUp()
// LSNocilla.sharedInstance().start()
}
override class func tearDown() {
super.tearDown()
// LSNocilla.sharedInstance().stop()
}
override func tearDown() {
// LSNocilla.sharedInstance().clearStubs()
super.tearDown()
}
func testDownloadImage() {
// let url = URL(string: urlPath)!
//
// let expectedData = ik_imageData()
//
// stubRequest("GET", urlPath as LSMatcheable!).withBody(expectedData)
//
// ik_expectation("Image download expectation") { (expectation) -> Void in
//
// let _ = self.downloader.download(url, progress: { (percent) -> Void in }, completion: { (imageObject, error) -> Void in
// XCTAssertNotNil(imageObject!.image)
// XCTAssertEqual(imageObject!.data, expectedData)
// XCTAssertNil(error)
// expectation.fulfill()
// })
// }
}
func testThatReturnsErrorForInvalidUrlScheme() {
// let url = URL(string: "file://localFile")
//
// stubRequest("GET", urlPath as LSMatcheable!)
//
// ik_expectation("Invalid url error expectaion") { (expectation) -> Void in
// let _ = self.downloader.download(url!, progress: { (percent) -> Void in }, completion: { (imageObject, error) -> Void in
// XCTAssertNil(imageObject)
// XCTAssertEqual(error, NSError.ik_invalidUrlError())
// expectation.fulfill()
// })
// }
}
func testThatReturnsErrorForEmptyUrl() {
// let url = URL(string: "")
//
// stubRequest("GET", urlPath as LSMatcheable!)
//
// ik_expectation("Error for empty url") { (expectation) -> Void in
// let _ = self.downloader.download(url!, progress: { (percent) -> Void in }, completion: { (imageObject, error) -> Void in
// XCTAssertNil(imageObject)
// XCTAssertEqual(error, NSError.ik_invalidUrlError())
// expectation.fulfill()
// })
// }
}
func testThatItReturnsServerError() {
// let url = URL(string: urlPath)
//
// stubRequest("GET", urlPath as LSMatcheable!).andFailWithError(NSError(domain: "error", code: 404, userInfo: nil))
//
// ik_expectation("Server error expectation") { (expectation) -> Void in
// let _ = self.downloader.download(url!, progress: { (percent) -> Void in }, completion: { (imageObject, error) -> Void in
// XCTAssertNil(imageObject)
// XCTAssertNotNil(error)
// expectation.fulfill()
// })
// }
}
func testThatItFailsWithInvalidImageDataError() {
// let url = URL(string: urlPath)
//
// stubRequest("GET", urlPath as LSMatcheable!).andReturn(200)?.withBody(Data())
//
// ik_expectation("Invalid data expectation") { (expectation) -> Void in
// let _ = self.downloader.download(url!, progress: { (percent) -> Void in }, completion: { (imageObject, error) -> Void in
// XCTAssertNil(imageObject)
// XCTAssertEqual(error, NSError.ik_invalidDataError())
// expectation.fulfill()
// })
// }
}
func testDownloadRetry() {
// let url = URL(string: urlPath)
//
// let expectedData = ik_imageData()
//
// let expectedError = NSError(domain: "test.domain", code: -1, userInfo: nil)
//
// stubRequest("GET", urlPath as LSMatcheable!).andFailWithError(expectedError)
//
// ik_expectation("Download retry expectation") { (expectation) -> Void in
// let _ = self.downloader.download(url!, progress: { (percent) -> Void in }, completion: { (imageObject, error) -> Void in
//
// XCTAssertEqual(error, expectedError)
//
// LSNocilla.sharedInstance().clearStubs()
//
// stubRequest("GET", self.urlPath as LSMatcheable!).andReturn(200)?.withBody(expectedData)
//
// let _ = self.downloader.download(url!, progress: { (percent) -> Void in }, completion: { (imageObject, error) -> Void in
// XCTAssertNotNil(imageObject!.image)
// XCTAssertEqual(imageObject!.data, expectedData)
// XCTAssertNil(error)
// expectation.fulfill()
// })
// })
// }
}
}
| mit |
ianfelzer1/ifelzer-advprog | Last Year/IOS Development- J Term 2017/Stopwatch/StopwatchUITests/StopwatchUITests.swift | 1 | 1249 | //
// StopwatchUITests.swift
// StopwatchUITests
//
// Created by Programming on 1/18/17.
// Copyright © 2017 Ian Felzer. All rights reserved.
//
import XCTest
class StopwatchUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| gpl-3.0 |
Lucky-Orange/Tenon | Pitaya/Source/File.swift | 1 | 1488 | // The MIT License (MIT)
// Copyright (c) 2015 JohnLui <wenhanlv@gmail.com> https://github.com/johnlui
// 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.
//
// File.swift
// Pitaya
//
// Created by 吕文翰 on 15/10/7.
//
import Foundation
/**
* the file struct for Pitaya to upload
*/
public struct File {
public let name: String!
public let url: NSURL!
public init(name: String, url: NSURL) {
self.name = name
self.url = url
}
} | mit |
SwiftFMI/iOS_2017_2018 | Lectures/code/10.11.2017/UITableView Demo/UITableView Demo/AppDelegate.swift | 1 | 2180 | //
// AppDelegate.swift
// UITableView Demo
//
// Created by Emil Atanasov on 11/10/17.
// Copyright © 2017 SwiftFMI. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and 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:.
}
}
| apache-2.0 |
tkremenek/swift | test/Syntax/round_trip_invalid.swift | 28 | 725 | // RUN: rm -rf %t
// RUN: %swift-syntax-test -input-source-filename %s -parse-gen > %t
// RUN: diff -u %s %t
// RUN: %swift-syntax-test -input-source-filename %s -parse-gen -print-node-kind > %t.withkinds
// RUN: diff -u %S/Outputs/round_trip_invalid.swift.withkinds %t.withkinds
// RUN: %swift-syntax-test -input-source-filename %s -eof > %t
// RUN: diff -u %s %t
// RUN: %swift-syntax-test -serialize-raw-tree -input-source-filename %s > %t.dump
// RUN: %swift-syntax-test -deserialize-raw-tree -input-source-filename %t.dump -output-filename %t
// RUN: diff -u %s %t
let strings: [Strin[g]?
// Function body without closing brace token.
func foo() {
var a = 2
class C {
struct S {
enum E {
protocol P {
extension P {
| apache-2.0 |
danielgindi/Charts | Source/Charts/Renderers/RadarChartRenderer.swift | 1 | 18066 | //
// RadarChartRenderer.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
open class RadarChartRenderer: LineRadarRenderer
{
private lazy var accessibilityXLabels: [String] = {
guard let chart = chart else { return [] }
guard let formatter = chart.xAxis.valueFormatter else { return [] }
let maxEntryCount = chart.data?.maxEntryCountSet?.entryCount ?? 0
return stride(from: 0, to: maxEntryCount, by: 1).map {
formatter.stringForValue(Double($0), axis: chart.xAxis)
}
}()
@objc open weak var chart: RadarChartView?
@objc public init(chart: RadarChartView, animator: Animator, viewPortHandler: ViewPortHandler)
{
super.init(animator: animator, viewPortHandler: viewPortHandler)
self.chart = chart
}
open override func drawData(context: CGContext)
{
guard let chart = chart,
let radarData = chart.data as? RadarChartData else
{
return
}
let mostEntries = radarData.maxEntryCountSet?.entryCount ?? 0
// If we redraw the data, remove and repopulate accessible elements to update label values and frames
self.accessibleChartElements.removeAll()
// Make the chart header the first element in the accessible elements array
let element = createAccessibleHeader(usingChart: chart,
andData: radarData,
withDefaultDescription: "Radar Chart")
self.accessibleChartElements.append(element)
for case let set as RadarChartDataSetProtocol in (radarData as ChartData) where set.isVisible
{
drawDataSet(context: context, dataSet: set, mostEntries: mostEntries)
}
}
/// Draws the RadarDataSet
///
/// - Parameters:
/// - context:
/// - dataSet:
/// - mostEntries: the entry count of the dataset with the most entries
internal func drawDataSet(context: CGContext, dataSet: RadarChartDataSetProtocol, mostEntries: Int)
{
guard let chart = chart else { return }
context.saveGState()
let phaseX = animator.phaseX
let phaseY = animator.phaseY
let sliceangle = chart.sliceAngle
// calculate the factor that is needed for transforming the value to pixels
let factor = chart.factor
let center = chart.centerOffsets
let entryCount = dataSet.entryCount
let path = CGMutablePath()
var hasMovedToPoint = false
let prefix: String = chart.data?.accessibilityEntryLabelPrefix ?? "Item"
let description = dataSet.label ?? ""
// Make a tuple of (xLabels, value, originalIndex) then sort it
// This is done, so that the labels are narrated in decreasing order of their corresponding value
// Otherwise, there is no non-visual logic to the data presented
let accessibilityEntryValues = Array(0 ..< entryCount).map { (dataSet.entryForIndex($0)?.y ?? 0, $0) }
let accessibilityAxisLabelValueTuples = zip(accessibilityXLabels, accessibilityEntryValues).map { ($0, $1.0, $1.1) }.sorted { $0.1 > $1.1 }
let accessibilityDataSetDescription: String = description + ". \(entryCount) \(prefix + (entryCount == 1 ? "" : "s")). "
let accessibilityFrameWidth: CGFloat = 22.0 // To allow a tap target of 44x44
var accessibilityEntryElements: [NSUIAccessibilityElement] = []
for j in 0 ..< entryCount
{
guard let e = dataSet.entryForIndex(j) else { continue }
let p = center.moving(distance: CGFloat((e.y - chart.chartYMin) * Double(factor) * phaseY),
atAngle: sliceangle * CGFloat(j) * CGFloat(phaseX) + chart.rotationAngle)
if p.x.isNaN
{
continue
}
if !hasMovedToPoint
{
path.move(to: p)
hasMovedToPoint = true
}
else
{
path.addLine(to: p)
}
let accessibilityLabel = accessibilityAxisLabelValueTuples[j].0
let accessibilityValue = accessibilityAxisLabelValueTuples[j].1
let accessibilityValueIndex = accessibilityAxisLabelValueTuples[j].2
let axp = center.moving(distance: CGFloat((accessibilityValue - chart.chartYMin) * Double(factor) * phaseY),
atAngle: sliceangle * CGFloat(accessibilityValueIndex) * CGFloat(phaseX) + chart.rotationAngle)
let axDescription = description + " - " + accessibilityLabel + ": \(accessibilityValue) \(chart.data?.accessibilityEntryLabelSuffix ?? "")"
let axElement = createAccessibleElement(withDescription: axDescription,
container: chart,
dataSet: dataSet)
{ (element) in
element.accessibilityFrame = CGRect(x: axp.x - accessibilityFrameWidth,
y: axp.y - accessibilityFrameWidth,
width: 2 * accessibilityFrameWidth,
height: 2 * accessibilityFrameWidth)
}
accessibilityEntryElements.append(axElement)
}
// if this is the largest set, close it
if dataSet.entryCount < mostEntries
{
// if this is not the largest set, draw a line to the center before closing
path.addLine(to: center)
}
path.closeSubpath()
// draw filled
if dataSet.isDrawFilledEnabled
{
if dataSet.fill != nil
{
drawFilledPath(context: context, path: path, fill: dataSet.fill!, fillAlpha: dataSet.fillAlpha)
}
else
{
drawFilledPath(context: context, path: path, fillColor: dataSet.fillColor, fillAlpha: dataSet.fillAlpha)
}
}
// draw the line (only if filled is disabled or alpha is below 255)
if !dataSet.isDrawFilledEnabled || dataSet.fillAlpha < 1.0
{
context.setStrokeColor(dataSet.color(atIndex: 0).cgColor)
context.setLineWidth(dataSet.lineWidth)
context.setAlpha(1.0)
context.beginPath()
context.addPath(path)
context.strokePath()
let axElement = createAccessibleElement(withDescription: accessibilityDataSetDescription,
container: chart,
dataSet: dataSet)
{ (element) in
element.isHeader = true
element.accessibilityFrame = path.boundingBoxOfPath
}
accessibleChartElements.append(axElement)
accessibleChartElements.append(contentsOf: accessibilityEntryElements)
}
accessibilityPostLayoutChangedNotification()
context.restoreGState()
}
open override func drawValues(context: CGContext)
{
guard
let chart = chart,
let data = chart.data
else { return }
let phaseX = animator.phaseX
let phaseY = animator.phaseY
let sliceangle = chart.sliceAngle
// calculate the factor that is needed for transforming the value to pixels
let factor = chart.factor
let center = chart.centerOffsets
let yoffset = CGFloat(5.0)
for i in data.indices
{
guard let
dataSet = data[i] as? RadarChartDataSetProtocol,
shouldDrawValues(forDataSet: dataSet)
else { continue }
let angleRadians = dataSet.valueLabelAngle.DEG2RAD
let entryCount = dataSet.entryCount
let iconsOffset = dataSet.iconsOffset
for j in 0 ..< entryCount
{
guard let e = dataSet.entryForIndex(j) else { continue }
let p = center.moving(distance: CGFloat(e.y - chart.chartYMin) * factor * CGFloat(phaseY),
atAngle: sliceangle * CGFloat(j) * CGFloat(phaseX) + chart.rotationAngle)
let valueFont = dataSet.valueFont
let formatter = dataSet.valueFormatter
if dataSet.isDrawValuesEnabled
{
context.drawText(formatter.stringForValue(e.y,
entry: e,
dataSetIndex: i,
viewPortHandler: viewPortHandler),
at: CGPoint(x: p.x, y: p.y - yoffset - valueFont.lineHeight),
align: .center,
angleRadians: angleRadians,
attributes: [.font: valueFont,
.foregroundColor: dataSet.valueTextColorAt(j)])
}
if let icon = e.icon, dataSet.isDrawIconsEnabled
{
var pIcon = center.moving(distance: CGFloat(e.y) * factor * CGFloat(phaseY) + iconsOffset.y,
atAngle: sliceangle * CGFloat(j) * CGFloat(phaseX) + chart.rotationAngle)
pIcon.y += iconsOffset.x
context.drawImage(icon,
atCenter: CGPoint(x: pIcon.x, y: pIcon.y),
size: icon.size)
}
}
}
}
open override func drawExtras(context: CGContext)
{
drawWeb(context: context)
}
private var _webLineSegmentsBuffer = [CGPoint](repeating: CGPoint(), count: 2)
@objc open func drawWeb(context: CGContext)
{
guard
let chart = chart,
let data = chart.data
else { return }
let sliceangle = chart.sliceAngle
context.saveGState()
// calculate the factor that is needed for transforming the value to
// pixels
let factor = chart.factor
let rotationangle = chart.rotationAngle
let center = chart.centerOffsets
// draw the web lines that come from the center
context.setLineWidth(chart.webLineWidth)
context.setStrokeColor(chart.webColor.cgColor)
context.setAlpha(chart.webAlpha)
let xIncrements = 1 + chart.skipWebLineCount
let maxEntryCount = chart.data?.maxEntryCountSet?.entryCount ?? 0
for i in stride(from: 0, to: maxEntryCount, by: xIncrements)
{
let p = center.moving(distance: CGFloat(chart.yRange) * factor,
atAngle: sliceangle * CGFloat(i) + rotationangle)
_webLineSegmentsBuffer[0].x = center.x
_webLineSegmentsBuffer[0].y = center.y
_webLineSegmentsBuffer[1].x = p.x
_webLineSegmentsBuffer[1].y = p.y
context.strokeLineSegments(between: _webLineSegmentsBuffer)
}
// draw the inner-web
context.setLineWidth(chart.innerWebLineWidth)
context.setStrokeColor(chart.innerWebColor.cgColor)
context.setAlpha(chart.webAlpha)
let labelCount = chart.yAxis.entryCount
for j in 0 ..< labelCount
{
for i in 0 ..< data.entryCount
{
let r = CGFloat(chart.yAxis.entries[j] - chart.chartYMin) * factor
let p1 = center.moving(distance: r, atAngle: sliceangle * CGFloat(i) + rotationangle)
let p2 = center.moving(distance: r, atAngle: sliceangle * CGFloat(i + 1) + rotationangle)
_webLineSegmentsBuffer[0].x = p1.x
_webLineSegmentsBuffer[0].y = p1.y
_webLineSegmentsBuffer[1].x = p2.x
_webLineSegmentsBuffer[1].y = p2.y
context.strokeLineSegments(between: _webLineSegmentsBuffer)
}
}
context.restoreGState()
}
private var _highlightPointBuffer = CGPoint()
open override func drawHighlighted(context: CGContext, indices: [Highlight])
{
guard
let chart = chart,
let radarData = chart.data as? RadarChartData
else { return }
context.saveGState()
let sliceangle = chart.sliceAngle
// calculate the factor that is needed for transforming the value pixels
let factor = chart.factor
let center = chart.centerOffsets
for high in indices
{
guard
let set = chart.data?[high.dataSetIndex] as? RadarChartDataSetProtocol,
set.isHighlightEnabled
else { continue }
guard let e = set.entryForIndex(Int(high.x)) as? RadarChartDataEntry
else { continue }
if !isInBoundsX(entry: e, dataSet: set)
{
continue
}
context.setLineWidth(radarData.highlightLineWidth)
if radarData.highlightLineDashLengths != nil
{
context.setLineDash(phase: radarData.highlightLineDashPhase, lengths: radarData.highlightLineDashLengths!)
}
else
{
context.setLineDash(phase: 0.0, lengths: [])
}
context.setStrokeColor(set.highlightColor.cgColor)
let y = e.y - chart.chartYMin
_highlightPointBuffer = center.moving(distance: CGFloat(y) * factor * CGFloat(animator.phaseY),
atAngle: sliceangle * CGFloat(high.x) * CGFloat(animator.phaseX) + chart.rotationAngle)
high.setDraw(pt: _highlightPointBuffer)
// draw the lines
drawHighlightLines(context: context, point: _highlightPointBuffer, set: set)
if set.isDrawHighlightCircleEnabled
{
if !_highlightPointBuffer.x.isNaN && !_highlightPointBuffer.y.isNaN
{
var strokeColor = set.highlightCircleStrokeColor
if strokeColor == nil
{
strokeColor = set.color(atIndex: 0)
}
if set.highlightCircleStrokeAlpha < 1.0
{
strokeColor = strokeColor?.withAlphaComponent(set.highlightCircleStrokeAlpha)
}
drawHighlightCircle(
context: context,
atPoint: _highlightPointBuffer,
innerRadius: set.highlightCircleInnerRadius,
outerRadius: set.highlightCircleOuterRadius,
fillColor: set.highlightCircleFillColor,
strokeColor: strokeColor,
strokeWidth: set.highlightCircleStrokeWidth)
}
}
}
context.restoreGState()
}
internal func drawHighlightCircle(
context: CGContext,
atPoint point: CGPoint,
innerRadius: CGFloat,
outerRadius: CGFloat,
fillColor: NSUIColor?,
strokeColor: NSUIColor?,
strokeWidth: CGFloat)
{
context.saveGState()
if let fillColor = fillColor
{
context.beginPath()
context.addEllipse(in: CGRect(x: point.x - outerRadius, y: point.y - outerRadius, width: outerRadius * 2.0, height: outerRadius * 2.0))
if innerRadius > 0.0
{
context.addEllipse(in: CGRect(x: point.x - innerRadius, y: point.y - innerRadius, width: innerRadius * 2.0, height: innerRadius * 2.0))
}
context.setFillColor(fillColor.cgColor)
context.fillPath(using: .evenOdd)
}
if let strokeColor = strokeColor
{
context.beginPath()
context.addEllipse(in: CGRect(x: point.x - outerRadius, y: point.y - outerRadius, width: outerRadius * 2.0, height: outerRadius * 2.0))
context.setStrokeColor(strokeColor.cgColor)
context.setLineWidth(strokeWidth)
context.strokePath()
}
context.restoreGState()
}
private func createAccessibleElement(withDescription description: String,
container: RadarChartView,
dataSet: RadarChartDataSetProtocol,
modifier: (NSUIAccessibilityElement) -> ()) -> NSUIAccessibilityElement {
let element = NSUIAccessibilityElement(accessibilityContainer: container)
element.accessibilityLabel = description
// The modifier allows changing of traits and frame depending on highlight, rotation, etc
modifier(element)
return element
}
}
| apache-2.0 |
soverby/SOUIControlsContainer | SOUIControlsContainer/SecondViewController.swift | 1 | 729 | //
// SecondViewController.swift
// SOUIControlsContainer
//
// Created by Overby, Sean on 6/19/15.
// Copyright (c) 2015 Sean Overby. All rights reserved.
//
import UIKit
class SecondViewController: UIViewController {
@IBOutlet weak var buttonOutlet: UIButton!
@IBOutlet weak var myLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func buttonPress(sender: AnyObject) {
self.myLabel.text = "Button Pressed!"
}
}
| mit |
cailingyun2010/swift-weibo | 微博-S/Classes/Home/PhotoBrowserController.swift | 1 | 4958 | //
// PhotoBrowserController.swift
// 微博-S
//
// Created by nimingM on 16/3/30.
// Copyright © 2016年 蔡凌云. All rights reserved.
//
import UIKit
import SVProgressHUD
private let photoBrowserCellReuseIdentifier = "pictureCell"
class PhotoBrowserController: UIViewController {
// MARK: - propety
var currentIndex: Int?
var pictureURLs: [NSURL]?
// MARK: - private method
init(index: Int, urls: [NSURL]) {
// swift 语法规定,必须先调用本类的初始化,在调用父类的
currentIndex = index
pictureURLs = urls
// 并且调用设计的构造方法
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.whiteColor()
setupUI()
}
// MARK: - 初始化
private func setupUI() {
// 1.添加子控件
view.addSubview(collectionView)
view.addSubview(closeBtn)
view.addSubview(saveBtn)
// 布局子控件
closeBtn.xmg_AlignInner(type: XMG_AlignType.BottomLeft, referView: view, size: CGSize(width: 100, height: 35), offset: CGPoint(x: 10, y: -10))
saveBtn.xmg_AlignInner(type: XMG_AlignType.BottomRight, referView: view, size: CGSize(width: 100, height: 35), offset: CGPoint(x: -10, y: -10))
collectionView.frame = UIScreen.mainScreen().bounds
// 3.设置数据源
collectionView.dataSource = self
collectionView.registerClass(PhotoBrowserCell.self, forCellWithReuseIdentifier: photoBrowserCellReuseIdentifier)
}
// MARK: - 懒加载
private lazy var closeBtn:UIButton = {
let btn = UIButton()
btn.setTitle("关闭", forState: UIControlState.Normal)
btn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
btn.backgroundColor = UIColor.darkGrayColor()
btn.addTarget(self, action: "close", forControlEvents: UIControlEvents.TouchUpInside)
return btn
}()
private lazy var saveBtn: UIButton = {
let btn = UIButton()
btn.setTitle("保存", forState: UIControlState.Normal)
btn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
btn.backgroundColor = UIColor.darkGrayColor()
btn.addTarget(self, action: "save", forControlEvents: UIControlEvents.TouchUpInside)
return btn
}()
private lazy var collectionView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: PhotoBrowserLayout())
// MARK: - actions
func close()
{
dismissViewControllerAnimated(true, completion: nil)
}
func save()
{
// 获得当前正在显示cell的索引
let index = collectionView.indexPathsForVisibleItems().last!
let cell = collectionView.cellForItemAtIndexPath(index) as! PhotoBrowserCell
// 保存图片
let image = cell.iconView.image
UIImageWriteToSavedPhotosAlbum(image!, self, "image:didFinishSavingWithError:contextInfo:", nil)
}
func image(image:UIImage, didFinishSavingWithError error:NSError?, contextInfo:AnyObject) {
if error != nil
{
SVProgressHUD.showErrorWithStatus("保存失败", maskType: SVProgressHUDMaskType.Black)
}else
{
SVProgressHUD.showSuccessWithStatus("保存成功", maskType: SVProgressHUDMaskType.Black)
}
}
}
extension PhotoBrowserController : UICollectionViewDataSource,PhotoBrowserCellDelegate
{
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return pictureURLs?.count ?? 0
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(photoBrowserCellReuseIdentifier, forIndexPath: indexPath) as! PhotoBrowserCell
cell.backgroundColor = UIColor.whiteColor()
cell.imageURL = pictureURLs![indexPath.item]
cell.photoDelegate = self
return cell
}
func photoBrowserCellDidClose(cell: PhotoBrowserCell) {
dismissViewControllerAnimated(true, completion: nil)
}
}
class PhotoBrowserLayout : UICollectionViewFlowLayout {
override func prepareLayout() {
itemSize = UIScreen.mainScreen().bounds.size
minimumInteritemSpacing = 0
minimumLineSpacing = 0
scrollDirection = UICollectionViewScrollDirection.Horizontal
collectionView?.showsHorizontalScrollIndicator = false
collectionView?.pagingEnabled = true
collectionView?.bounces = false
}
}
| apache-2.0 |
robconrad/fledger-common | FledgerCommonTests/test/AppTestSuite.swift | 1 | 582 | //
// Created by Robert Conrad on 5/10/15.
// Copyright (c) 2015 Robert Conrad. All rights reserved.
//
import XCTest
import FledgerCommon
#if os(iOS)
import Parse
#elseif os(OSX)
import ParseOSX
#endif
class AppTestSuite: XCTestCase {
override class func setUp() {
super.setUp()
// reinitialize all services on test suite initialization
ServiceBootstrap.preRegister()
do {
try PFUser.logInWithUsername("test", password: "test")
}
catch {
// sigh
}
ServiceBootstrap.register()
}
}
| mit |
garygriswold/Bible.js | SafeBible2/SafeBible_ios/SafeBible/ToolBars/SettingsSearchController.swift | 1 | 2602 | //
// SettingsSearchController.swift
// Settings
//
// Created by Gary Griswold on 9/9/18.
// Copyright © 2018 ShortSands. All rights reserved.
//
import UIKit
class SettingsSearchController: NSObject, UISearchResultsUpdating {
private weak var controller: AppTableViewController?
private let availableSection: Int
private let searchController: UISearchController
private var dataModel: SettingsModel?
init(controller: AppTableViewController, selectionViewSection: Int) {
self.controller = controller
self.availableSection = selectionViewSection + 1
self.searchController = UISearchController(searchResultsController: nil)
self.searchController.searchBar.placeholder = NSLocalizedString("Find Languages",
comment: "Languages search bar")
super.init()
self.searchController.searchResultsUpdater = self
self.searchController.obscuresBackgroundDuringPresentation = false
self.searchController.hidesNavigationBarDuringPresentation = false
self.controller?.navigationItem.hidesSearchBarWhenScrolling = false
//self.searchController.searchBar.setShowsCancelButton(false, animated: true)
}
deinit {
print("**** deinit SettingsSearchController ******")
}
func viewAppears(dataModel: SettingsModel?) {
if let data = dataModel {
self.dataModel = data
self.controller?.navigationItem.searchController = self.searchController
} else {
self.dataModel = nil
self.controller?.navigationItem.searchController = nil
}
}
func isSearching() -> Bool {
let searchBarEmpty: Bool = self.searchController.searchBar.text?.isEmpty ?? true
return self.searchController.isActive && !searchBarEmpty
}
func updateSearchResults() {
if isSearching() {
updateSearchResults(for: self.searchController)
}
}
// MARK: - UISearchResultsUpdating Delegate
func updateSearchResults(for searchController: UISearchController) {
print("****** INSIDE update Search Results ********")
if let text = self.searchController.searchBar.text {
if text.count > 0 {
self.dataModel?.filterForSearch(searchText: text)
}
let sections = IndexSet(integer: self.availableSection)
self.controller?.tableView.reloadSections(sections, with: UITableView.RowAnimation.automatic)
}
}
}
| mit |
lexchou/swallow | stdlib/core/DictionaryIndex.swift | 1 | 905 | /// Used to access the key-value pairs in an instance of
/// `Dictionary<Key,Value>`.
///
/// Remember that Dictionary has two subscripting interfaces:
///
/// 1. Subscripting with a key, yielding an optional value::
///
/// v = d[k]!
///
/// 2. Subscripting with an index, yielding a key-value pair:
///
/// (k,v) = d[i]
struct DictionaryIndex<Key : Hashable, Value> : BidirectionalIndexType, Comparable {
/// Identical to `self.dynamicType`
typealias Index = DictionaryIndex<Key, Value>
/// Returns the previous consecutive value before `self`.
///
/// Requires: the previous value is representable.
func predecessor() -> DictionaryIndex<Key, Value> {
//TODO
}
/// Returns the next consecutive value after `self`.
///
/// Requires: the next value is representable.
func successor() -> DictionaryIndex<Key, Value> {
//TODO
}
}
| bsd-3-clause |
wibosco/ASOS-Consumer | ASOSConsumer/Networking/CategoryProducts/Operations/Retrieval/CategoryProductsRetrievalOperation.swift | 1 | 1845 | //
// CategoryProductsRetrievalOperation.swift
// ASOSConsumer
//
// Created by William Boles on 02/03/2016.
// Copyright © 2016 Boles. All rights reserved.
//
import UIKit
class CategoryProductsRetrievalOperation: NSOperation {
//MARK: - Accessors
var category : Category
var data : NSData
var completion : ((category: Category, categoryProducts: Array<CategoryProduct>?) -> (Void))?
var callBackQueue : NSOperationQueue
//MARK: - Init
init(category: Category, data: NSData, completion: ((category: Category, categoryProducts: Array<CategoryProduct>?) -> Void)?) {
self.category = category
self.data = data
self.completion = completion
self.callBackQueue = NSOperationQueue.currentQueue()!
super.init()
}
//MARK: - Main
override func main() {
super.main()
do {
let jsonResponse = try NSJSONSerialization.JSONObjectWithData(self.data, options: NSJSONReadingOptions.MutableContainers) as! Dictionary<String, AnyObject>
let parser = CategoryProductParser()
let categoryProducts = parser.parseCategoryProducts(jsonResponse)
self.callBackQueue.addOperationWithBlock({ () -> Void in
if (self.completion != nil) {
self.completion!(category: self.category, categoryProducts: categoryProducts)
}
})
} catch let error as NSError {
print("Failed to load \(error.localizedDescription)")
self.callBackQueue.addOperationWithBlock({ () -> Void in
if (self.completion != nil) {
self.completion!(category: self.category, categoryProducts: nil)
}
})
}
}
}
| mit |
rokuz/omim | iphone/Maps/Bookmarks/Catalog/Subscription/BookmarksSubscriptionViewController.swift | 1 | 2646 | import SafariServices
@objc class BookmarksSubscriptionViewController: BaseSubscriptionViewController {
//MARK: outlets
@IBOutlet private var annualSubscriptionButton: BookmarksSubscriptionButton!
@IBOutlet private var annualDiscountLabel: BookmarksSubscriptionDiscountLabel!
@IBOutlet private var monthlySubscriptionButton: BookmarksSubscriptionButton!
override var subscriptionManager: ISubscriptionManager? {
get { return InAppPurchase.bookmarksSubscriptionManager }
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
get { return [.portrait] }
}
override var preferredStatusBarStyle: UIStatusBarStyle {
get { return UIColor.isNightMode() ? .lightContent : .default }
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
annualSubscriptionButton.config(title: L("annual_subscription_title"),
price: "...",
enabled: false)
monthlySubscriptionButton.config(title: L("montly_subscription_title"),
price: "...",
enabled: false)
if !UIColor.isNightMode() {
annualDiscountLabel.layer.shadowRadius = 4
annualDiscountLabel.layer.shadowOffset = CGSize(width: 0, height: 2)
annualDiscountLabel.layer.shadowColor = UIColor.blackHintText().cgColor
annualDiscountLabel.layer.shadowOpacity = 0.62
}
annualDiscountLabel.layer.cornerRadius = 6
annualDiscountLabel.isHidden = true
self.configure(buttons: [
.year: annualSubscriptionButton,
.month: monthlySubscriptionButton],
discountLabels:[
.year: annualDiscountLabel])
Statistics.logEvent(kStatInappShow, withParameters: [kStatVendor: MWMPurchaseManager.bookmarksSubscriptionVendorId(),
kStatPurchase: MWMPurchaseManager.bookmarksSubscriptionServerId(),
kStatProduct: BOOKMARKS_SUBSCRIPTION_YEARLY_PRODUCT_ID,
kStatFrom: source], with: .realtime)
}
@IBAction func onAnnualButtonTap(_ sender: UIButton) {
purchase(sender: sender, period: .year)
}
@IBAction func onMonthlyButtonTap(_ sender: UIButton) {
purchase(sender: sender, period: .month)
}
}
| apache-2.0 |
ResearchSuite/ResearchSuiteExtensions-iOS | Example/Pods/ResearchSuiteTaskBuilder/ResearchSuiteTaskBuilder/Classes/Service Protocols/RSTBTaskGenerator.swift | 1 | 339 | //
// RSTBTaskGenerator.swift
// Pods
//
// Created by James Kizer on 6/30/17.
//
//
import Foundation
import ResearchKit
import Gloss
public protocol RSTBTaskGenerator {
static func supportsType(type: String) -> Bool
static func generateTask(type: String, jsonObject: JSON, helper: RSTBTaskBuilderHelper) -> ORKTask?
}
| apache-2.0 |
goinvo/pearl | PearlTests/PearlTests.swift | 1 | 901 | //
// PearlTests.swift
// PearlTests
//
// Created by Rob Sterner on 4/19/15.
// Copyright (c) 2015 Involution Studios. All rights reserved.
//
import UIKit
import XCTest
class PearlTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| gpl-2.0 |
sayheyrickjames/codepath-dev | week3/week3-class1-project2/week3-class1-project2/AppDelegate.swift | 1 | 2159 | //
// AppDelegate.swift
// week3-class1-project2
//
// Created by Rick James! Chatas on 5/18/15.
// Copyright (c) 2015 SayHey. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| gpl-2.0 |
sschiau/swift-package-manager | Sources/Commands/GenerateLinuxMain.swift | 1 | 6704 | /*
This source file is part of the Swift.org open source project
Copyright 2015 - 2018 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import Basic
import PackageGraph
import PackageModel
/// A utility for generating test entries on linux.
///
/// This uses input from macOS's test discovery and generates
/// corelibs-xctest compatible test manifests.
final class LinuxMainGenerator {
enum Error: Swift.Error {
case noTestTargets
}
/// The package graph we're working on.
let graph: PackageGraph
/// The test suites that we need to write.
let testSuites: [TestSuite]
init(graph: PackageGraph, testSuites: [TestSuite]) {
self.graph = graph
self.testSuites = testSuites
}
/// Generate the XCTestManifests.swift and LinuxMain.swift for the package.
func generate() throws {
// Create the module struct from input.
//
// This converts the input test suite into a structure that
// is more suitable for generating linux test entries.
let modulesBuilder = ModulesBuilder()
for suite in testSuites {
modulesBuilder.add(suite.tests)
}
let modules = modulesBuilder.build().sorted(by: { $0.name < $1.name })
// Generate manifest file for each test module we got from XCTest discovery.
for module in modules {
guard let target = graph.reachableTargets.first(where: { $0.c99name == module.name }) else {
print("warning: did not find target '\(module.name)'")
continue
}
assert(target.type == .test, "Unexpected target type \(target.type) for \(target)")
// Write the manifest file for this module.
let testManifest = target.sources.root.appending(component: "XCTestManifests.swift")
let stream = try LocalFileOutputByteStream(testManifest)
stream <<< "#if !canImport(ObjectiveC)" <<< "\n"
stream <<< "import XCTest" <<< "\n"
for klass in module.classes.lazy.sorted(by: { $0.name < $1.name }) {
stream <<< "\n"
stream <<< "extension " <<< klass.name <<< " {" <<< "\n"
stream <<< indent(4) <<< "// DO NOT MODIFY: This is autogenerated, use: \n"
stream <<< indent(4) <<< "// `swift test --generate-linuxmain`\n"
stream <<< indent(4) <<< "// to regenerate.\n"
stream <<< indent(4) <<< "static let __allTests__\(klass.name) = [" <<< "\n"
for method in klass.methods {
stream <<< indent(8) <<< "(\"\(method)\", \(method))," <<< "\n"
}
stream <<< indent(4) <<< "]" <<< "\n"
stream <<< "}" <<< "\n"
}
stream <<<
"""
public func __allTests() -> [XCTestCaseEntry] {
return [
"""
for klass in module.classes {
stream <<< indent(8) <<< "testCase(" <<< klass.name <<< ".__allTests__\(klass.name))," <<< "\n"
}
stream <<< """
]
}
#endif
"""
stream.flush()
}
/// Write LinuxMain.swift file.
guard let testTarget = graph.reachableProducts.first(where: { $0.type == .test })?.targets.first else {
throw Error.noTestTargets
}
let linuxMain = testTarget.sources.root.parentDirectory.appending(components: SwiftTarget.linuxMainBasename)
let stream = try LocalFileOutputByteStream(linuxMain)
stream <<< "import XCTest" <<< "\n\n"
for module in modules {
stream <<< "import " <<< module.name <<< "\n"
}
stream <<< "\n"
stream <<< "var tests = [XCTestCaseEntry]()" <<< "\n"
for module in modules {
stream <<< "tests += \(module.name).__allTests()" <<< "\n"
}
stream <<< "\n"
stream <<< "XCTMain(tests)" <<< "\n"
stream.flush()
}
private func indent(_ spaces: Int) -> ByteStreamable {
return Format.asRepeating(string: " ", count: spaces)
}
}
// MARK: - Internal data structure for LinuxMainGenerator.
private struct Module {
struct Class {
let name: String
let methods: [String]
}
let name: String
let classes: [Class]
}
private final class ModulesBuilder {
final class ModuleBuilder {
let name: String
var classes: [ClassBuilder]
init(_ name: String) {
self.name = name
self.classes = []
}
func build() -> Module {
return Module(name: name, classes: classes.map({ $0.build() }))
}
}
final class ClassBuilder {
let name: String
var methods: [String]
init(_ name: String) {
self.name = name
self.methods = []
}
func build() -> Module.Class {
return .init(name: name, methods: methods)
}
}
/// The built modules.
private var modules: [ModuleBuilder] = []
func add(_ cases: [TestSuite.TestCase]) {
for testCase in cases {
let (module, theKlass) = testCase.name.spm_split(around: ".")
guard let klass = theKlass else {
// Ignore the classes that have zero tests.
if testCase.tests.isEmpty {
continue
}
fatalError("unreachable \(testCase.name)")
}
for method in testCase.tests {
add(module, klass, method)
}
}
}
private func add(_ moduleName: String, _ klassName: String, _ methodName: String) {
// Find or create the module.
let module: ModuleBuilder
if let theModule = modules.first(where: { $0.name == moduleName }) {
module = theModule
} else {
module = ModuleBuilder(moduleName)
modules.append(module)
}
// Find or create the class.
let klass: ClassBuilder
if let theKlass = module.classes.first(where: { $0.name == klassName }) {
klass = theKlass
} else {
klass = ClassBuilder(klassName)
module.classes.append(klass)
}
// Finally, append the method to the class.
klass.methods.append(methodName)
}
func build() -> [Module] {
return modules.map({ $0.build() })
}
}
| apache-2.0 |
sschiau/swift-package-manager | Sources/Basic/JSON.swift | 2 | 11348 | /*
This source file is part of the Swift.org open source project
Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
-------------------------------------------------------------------------
This file defines JSON support infrastructure. It is not designed to be general
purpose JSON utilities, but rather just the infrastructure which SwiftPM needs
to manage serialization of data through JSON.
*/
// MARK: JSON Item Definition
/// A JSON value.
///
/// This type uses container wrappers in order to allow for mutable elements.
public enum JSON {
/// The null value.
case null
/// A boolean value.
case bool(Bool)
/// An integer value.
///
/// While not strictly present in JSON, we use this as a convenience to
/// parsing code.
case int(Int)
/// A floating-point value.
case double(Double)
/// A string.
case string(String)
/// An array.
case array([JSON])
/// A dictionary.
case dictionary([String: JSON])
/// An ordered dictionary.
case orderedDictionary(DictionaryLiteral<String, JSON>)
}
/// A JSON representation of an element.
public protocol JSONSerializable {
/// Return a JSON representation.
func toJSON() -> JSON
}
extension JSON: CustomStringConvertible {
public var description: Swift.String {
switch self {
case .null: return "null"
case .bool(let value): return value.description
case .int(let value): return value.description
case .double(let value): return value.description
case .string(let value): return value.debugDescription
case .array(let values): return values.description
case .dictionary(let values): return values.description
case .orderedDictionary(let values): return values.description
}
}
}
/// Equatable conformance.
extension JSON: Equatable {
public static func == (lhs: JSON, rhs: JSON) -> Bool {
switch (lhs, rhs) {
case (.null, .null): return true
case (.null, _): return false
case (.bool(let a), .bool(let b)): return a == b
case (.bool, _): return false
case (.int(let a), .int(let b)): return a == b
case (.int, _): return false
case (.double(let a), .double(let b)): return a == b
case (.double, _): return false
case (.string(let a), .string(let b)): return a == b
case (.string, _): return false
case (.array(let a), .array(let b)): return a == b
case (.array, _): return false
case (.dictionary(let a), .dictionary(let b)): return a == b
case (.dictionary, _): return false
case (.orderedDictionary(let a), .orderedDictionary(let b)): return a == b
case (.orderedDictionary, _): return false
}
}
}
// MARK: JSON Encoding
extension JSON {
/// Encode a JSON item into a string of bytes.
public func toBytes(prettyPrint: Bool = false) -> ByteString {
let stream = BufferedOutputByteStream()
write(to: stream, indent: prettyPrint ? 0 : nil)
if prettyPrint {
stream.write("\n")
}
return stream.bytes
}
/// Encode a JSON item into a JSON string
public func toString(prettyPrint: Bool = false) -> String {
guard let contents = self.toBytes(prettyPrint: prettyPrint).asString else {
fatalError("Failed to serialize JSON: \(self)")
}
return contents
}
}
/// Support writing to a byte stream.
extension JSON: ByteStreamable {
public func write(to stream: OutputByteStream) {
write(to: stream, indent: nil)
}
public func write(to stream: OutputByteStream, indent: Int?) {
func indentStreamable(offset: Int? = nil) -> ByteStreamable {
return Format.asRepeating(string: " ", count: indent.flatMap({ $0 + (offset ?? 0) }) ?? 0)
}
let shouldIndent = indent != nil
switch self {
case .null:
stream <<< "null"
case .bool(let value):
stream <<< Format.asJSON(value)
case .int(let value):
stream <<< Format.asJSON(value)
case .double(let value):
// FIXME: What happens for NaN, etc.?
stream <<< Format.asJSON(value)
case .string(let value):
stream <<< Format.asJSON(value)
case .array(let contents):
stream <<< "[" <<< (shouldIndent ? "\n" : "")
for (i, item) in contents.enumerated() {
if i != 0 { stream <<< "," <<< (shouldIndent ? "\n" : " ") }
stream <<< indentStreamable(offset: 2)
item.write(to: stream, indent: indent.flatMap({ $0 + 2 }))
}
stream <<< (shouldIndent ? "\n" : "") <<< indentStreamable() <<< "]"
case .dictionary(let contents):
// We always output in a deterministic order.
stream <<< "{" <<< (shouldIndent ? "\n" : "")
for (i, key) in contents.keys.sorted().enumerated() {
if i != 0 { stream <<< "," <<< (shouldIndent ? "\n" : " ") }
stream <<< indentStreamable(offset: 2) <<< Format.asJSON(key) <<< ": "
contents[key]!.write(to: stream, indent: indent.flatMap({ $0 + 2 }))
}
stream <<< (shouldIndent ? "\n" : "") <<< indentStreamable() <<< "}"
case .orderedDictionary(let contents):
stream <<< "{" <<< (shouldIndent ? "\n" : "")
for (i, item) in contents.enumerated() {
if i != 0 { stream <<< "," <<< (shouldIndent ? "\n" : " ") }
stream <<< indentStreamable(offset: 2) <<< Format.asJSON(item.key) <<< ": "
item.value.write(to: stream, indent: indent.flatMap({ $0 + 2 }))
}
stream <<< (shouldIndent ? "\n" : "") <<< indentStreamable() <<< "}"
}
}
}
// MARK: JSON Decoding
import Foundation
enum JSONDecodingError: Swift.Error {
/// The input byte string is malformed.
case malformed
}
// NOTE: This implementation is carefully crafted to work correctly on both
// Linux and OS X while still compiling for both. Thus, the implementation takes
// Any even though it could take AnyObject on OS X, and it uses converts to
// direct Swift types (for Linux) even though those don't apply on OS X.
//
// This allows the code to be portable, and expose a portable API, but it is not
// very efficient.
private let nsBooleanType = type(of: NSNumber(value: false))
extension JSON {
private static func convertToJSON(_ object: Any) -> JSON {
switch object {
case is NSNull:
return .null
case let value as String:
return .string(value)
case let value as NSNumber:
// Check if this is a boolean.
//
// FIXME: This is all rather unfortunate and expensive.
if type(of: value) === nsBooleanType {
return .bool(value != 0)
}
// Check if this is an exact integer.
//
// FIXME: This is highly questionable. Aside from the performance of
// decoding in this fashion, it means clients which truly have
// arrays of real numbers will need to be prepared to see either an
// .int or a .double. However, for our specific use case we usually
// want to get integers out of JSON, and so it seems an ok tradeoff
// versus forcing all clients to cast out of a double.
let asInt = value.intValue
if NSNumber(value: asInt) == value {
return .int(asInt)
}
// Otherwise, we have a floating point number.
return .double(value.doubleValue)
case let value as NSArray:
return .array(value.map(convertToJSON))
case let value as NSDictionary:
var result = [String: JSON]()
for (key, val) in value {
result[key as! String] = convertToJSON(val)
}
return .dictionary(result)
// On Linux, the JSON deserialization handles this.
case let asBool as Bool: // This is true on Linux.
return .bool(asBool)
case let asInt as Int: // This is true on Linux.
return .int(asInt)
case let asDouble as Double: // This is true on Linux.
return .double(asDouble)
case let value as [Any]:
return .array(value.map(convertToJSON))
case let value as [String: Any]:
var result = [String: JSON]()
for (key, val) in value {
result[key] = convertToJSON(val)
}
return .dictionary(result)
default:
fatalError("unexpected object: \(object) \(type(of: object))")
}
}
/// Load a JSON item from a Data object.
public init(data: Data) throws {
do {
let result = try JSONSerialization.jsonObject(with: data, options: [.allowFragments])
// Convert to a native representation.
//
// FIXME: This is inefficient; eventually, we want a way to do the
// loading and not need to copy / traverse all of the data multiple
// times.
self = JSON.convertToJSON(result)
} catch {
throw JSONDecodingError.malformed
}
}
/// Load a JSON item from a byte string.
public init(bytes: ByteString) throws {
try self.init(data: Data(bytes: bytes.contents))
}
/// Convenience initalizer for UTF8 encoded strings.
///
/// - Throws: JSONDecodingError
public init(string: String) throws {
let bytes = ByteString(encodingAsUTF8: string)
try self.init(bytes: bytes)
}
}
// MARK: - JSONSerializable helpers.
extension JSON {
public init(_ dict: [String: JSONSerializable]) {
self = .dictionary(Dictionary(items: dict.map({ ($0.0, $0.1.toJSON()) })))
}
}
extension Int: JSONSerializable {
public func toJSON() -> JSON {
return .int(self)
}
}
extension Double: JSONSerializable {
public func toJSON() -> JSON {
return .double(self)
}
}
extension String: JSONSerializable {
public func toJSON() -> JSON {
return .string(self)
}
}
extension Bool: JSONSerializable {
public func toJSON() -> JSON {
return .bool(self)
}
}
extension AbsolutePath: JSONSerializable {
public func toJSON() -> JSON {
return .string(asString)
}
}
extension RelativePath: JSONSerializable {
public func toJSON() -> JSON {
return .string(asString)
}
}
extension Optional where Wrapped: JSONSerializable {
public func toJSON() -> JSON {
switch self {
case .some(let wrapped): return wrapped.toJSON()
case .none: return .null
}
}
}
extension Sequence where Iterator.Element: JSONSerializable {
public func toJSON() -> JSON {
return .array(map({ $0.toJSON() }))
}
}
extension JSON: JSONSerializable {
public func toJSON() -> JSON {
return self
}
}
| apache-2.0 |
apple/swift-nio | Tests/NIOPosixTests/SystemTest+XCTest.swift | 1 | 1391 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
//
// SystemTest+XCTest.swift
//
import XCTest
///
/// NOTE: This file was generated by generate_linux_tests.rb
///
/// Do NOT edit this file directly as it will be regenerated automatically when needed.
///
extension SystemTest {
@available(*, deprecated, message: "not actually deprecated. Just deprecated to allow deprecated tests (which test deprecated functionality) without warnings")
static var allTests : [(String, (SystemTest) -> () throws -> Void)] {
return [
("testSystemCallWrapperPerformance", testSystemCallWrapperPerformance),
("testErrorsWorkCorrectly", testErrorsWorkCorrectly),
("testCmsgFirstHeader", testCmsgFirstHeader),
("testCMsgNextHeader", testCMsgNextHeader),
("testCMsgData", testCMsgData),
("testCMsgCollection", testCMsgCollection),
]
}
}
| apache-2.0 |
juangdelvalle/clinicadelvalle_ios | clinicadelvalle/Views/API/AuthenticationManager.swift | 1 | 240 | //
// AuthenticationManager.swift
// clinicadelvalle
//
// Created by Juan del Valle Ruiz on 3/18/15.
// Copyright (c) 2015 Juan del Valle Ruiz. All rights reserved.
//
import UIKit
class AuthenticationManager: NSObject {
}
| mit |
eduardourso/GIFGenerator | Example/GIFGenerator/AppDelegate.swift | 1 | 2180 | //
// AppDelegate.swift
// GIFGenerator
//
// Created by Eduardo Urso on 01/26/2016.
// Copyright (c) 2016 Eduardo Urso. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
27629678/web_dev | client/Pods/FileBrowser/FileBrowser/WebviewPreviewViewContoller.swift | 3 | 3865 | //
// WebviewPreviewViewContoller.swift
// FileBrowser
//
// Created by Roy Marmelstein on 16/02/2016.
// Copyright © 2016 Roy Marmelstein. All rights reserved.
//
import UIKit
import WebKit
/// Webview for rendering items QuickLook will struggle with.
class WebviewPreviewViewContoller: UIViewController {
var webView = WKWebView()
var file: FBFile? {
didSet {
self.title = file?.displayName
self.processForDisplay()
}
}
//MARK: Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(webView)
// Add share button
let shareButton = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(WebviewPreviewViewContoller.shareFile))
self.navigationItem.rightBarButtonItem = shareButton
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
webView.frame = self.view.bounds
}
//MARK: Share
func shareFile() {
guard let file = file else {
return
}
let activityViewController = UIActivityViewController(activityItems: [file.filePath], applicationActivities: nil)
self.present(activityViewController, animated: true, completion: nil)
}
//MARK: Processing
func processForDisplay() {
guard let file = file, let data = try? Data(contentsOf: file.filePath as URL) else {
return
}
var rawString: String?
// Prepare plist for display
if file.type == .PLIST {
do {
if let plistDescription = try (PropertyListSerialization.propertyList(from: data, options: [], format: nil) as AnyObject).description {
rawString = plistDescription
}
} catch {}
}
// Prepare json file for display
else if file.type == .JSON {
do {
let jsonObject = try JSONSerialization.jsonObject(with: data, options: [])
if JSONSerialization.isValidJSONObject(jsonObject) {
let prettyJSON = try JSONSerialization.data(withJSONObject: jsonObject, options: .prettyPrinted)
var jsonString = String(data: prettyJSON, encoding: String.Encoding.utf8)
// Unescape forward slashes
jsonString = jsonString?.replacingOccurrences(of: "\\/", with: "/")
rawString = jsonString
}
} catch {}
}
// Default prepare for display
if rawString == nil {
rawString = String(data: data, encoding: String.Encoding.utf8)
}
// Convert and display string
if let convertedString = convertSpecialCharacters(rawString) {
let htmlString = "<html><head><meta name='viewport' content='initial-scale=1.0, user-scalable=no'></head><body><pre>\(convertedString)</pre></body></html>"
webView.loadHTMLString(htmlString, baseURL: nil)
}
}
// Make sure we convert HTML special characters
// Code from https://gist.github.com/mikesteele/70ae98d04fdc35cb1d5f
func convertSpecialCharacters(_ string: String?) -> String? {
guard let string = string else {
return nil
}
var newString = string
let char_dictionary = [
"&": "&",
"<": "<",
">": ">",
""": "\"",
"'": "'"
];
for (escaped_char, unescaped_char) in char_dictionary {
newString = newString.replacingOccurrences(of: escaped_char, with: unescaped_char, options: NSString.CompareOptions.regularExpression, range: nil)
}
return newString
}
}
| mit |
realm/SwiftLint | Source/SwiftLintFramework/Rules/Idiomatic/PreferZeroOverExplicitInitRule.swift | 1 | 5296 | import SwiftSyntax
struct PreferZeroOverExplicitInitRule: SwiftSyntaxCorrectableRule, OptInRule, ConfigurationProviderRule {
var configuration = SeverityConfiguration(.warning)
static let description = RuleDescription(
identifier: "prefer_zero_over_explicit_init",
name: "Prefer Zero Over Explicit Init",
description: "Prefer `.zero` over explicit init with zero parameters (e.g. `CGPoint(x: 0, y: 0)`)",
kind: .idiomatic,
nonTriggeringExamples: [
Example("CGRect(x: 0, y: 0, width: 0, height: 1)"),
Example("CGPoint(x: 0, y: -1)"),
Example("CGSize(width: 2, height: 4)"),
Example("CGVector(dx: -5, dy: 0)"),
Example("UIEdgeInsets(top: 0, left: 1, bottom: 0, right: 1)")
],
triggeringExamples: [
Example("↓CGPoint(x: 0, y: 0)"),
Example("↓CGPoint(x: 0.000000, y: 0)"),
Example("↓CGPoint(x: 0.000000, y: 0.000)"),
Example("↓CGRect(x: 0, y: 0, width: 0, height: 0)"),
Example("↓CGSize(width: 0, height: 0)"),
Example("↓CGVector(dx: 0, dy: 0)"),
Example("↓UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)")
],
corrections: [
Example("↓CGPoint(x: 0, y: 0)"): Example("CGPoint.zero"),
Example("(↓CGPoint(x: 0, y: 0))"): Example("(CGPoint.zero)"),
Example("↓CGRect(x: 0, y: 0, width: 0, height: 0)"): Example("CGRect.zero"),
Example("↓CGSize(width: 0, height: 0.000)"): Example("CGSize.zero"),
Example("↓CGVector(dx: 0, dy: 0)"): Example("CGVector.zero"),
Example("↓UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)"): Example("UIEdgeInsets.zero")
]
)
init() {}
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
Visitor(viewMode: .sourceAccurate)
}
func makeRewriter(file: SwiftLintFile) -> ViolationsSyntaxRewriter? {
Rewriter(
locationConverter: file.locationConverter,
disabledRegions: disabledRegions(file: file)
)
}
}
private extension PreferZeroOverExplicitInitRule {
final class Visitor: ViolationsSyntaxVisitor {
override func visitPost(_ node: FunctionCallExprSyntax) {
if node.hasViolation {
violations.append(node.positionAfterSkippingLeadingTrivia)
}
}
}
private final class Rewriter: SyntaxRewriter, ViolationsSyntaxRewriter {
private(set) var correctionPositions: [AbsolutePosition] = []
let locationConverter: SourceLocationConverter
let disabledRegions: [SourceRange]
init(locationConverter: SourceLocationConverter, disabledRegions: [SourceRange]) {
self.locationConverter = locationConverter
self.disabledRegions = disabledRegions
}
override func visit(_ node: FunctionCallExprSyntax) -> ExprSyntax {
guard node.hasViolation,
let name = node.name,
!node.isContainedIn(regions: disabledRegions, locationConverter: locationConverter) else {
return super.visit(node)
}
correctionPositions.append(node.positionAfterSkippingLeadingTrivia)
let newNode: MemberAccessExprSyntax = "\(name).zero"
return super.visit(
newNode
.withLeadingTrivia(node.leadingTrivia ?? .zero)
.withTrailingTrivia(node.trailingTrivia ?? .zero)
)
}
}
}
private extension FunctionCallExprSyntax {
var hasViolation: Bool {
isCGPointZeroCall ||
isCGSizeCall ||
isCGRectCall ||
isCGVectorCall ||
isUIEdgeInsetsCall
}
var isCGPointZeroCall: Bool {
return name == "CGPoint" &&
argumentNames == ["x", "y"] &&
argumentsAreAllZero
}
var isCGSizeCall: Bool {
return name == "CGSize" &&
argumentNames == ["width", "height"] &&
argumentsAreAllZero
}
var isCGRectCall: Bool {
return name == "CGRect" &&
argumentNames == ["x", "y", "width", "height"] &&
argumentsAreAllZero
}
var isCGVectorCall: Bool {
return name == "CGVector" &&
argumentNames == ["dx", "dy"] &&
argumentsAreAllZero
}
var isUIEdgeInsetsCall: Bool {
return name == "UIEdgeInsets" &&
argumentNames == ["top", "left", "bottom", "right"] &&
argumentsAreAllZero
}
var name: String? {
guard let expr = calledExpression.as(IdentifierExprSyntax.self) else {
return nil
}
return expr.identifier.text
}
var argumentNames: [String?] {
argumentList.map(\.label?.text)
}
var argumentsAreAllZero: Bool {
argumentList.allSatisfy { arg in
if let intExpr = arg.expression.as(IntegerLiteralExprSyntax.self) {
return intExpr.isZero
} else if let floatExpr = arg.expression.as(FloatLiteralExprSyntax.self) {
return floatExpr.isZero
} else {
return false
}
}
}
}
| mit |
keshavvishwkarma/KVConstraintKit | KVConstraintKit/NSLayoutConstraintExtension.swift | 1 | 6082 | //
// NSLayoutConstraintExtension.swift
// https://github.com/keshavvishwkarma/KVConstraintKit.git
//
// Distributed under the MIT License.
//
// Copyright © 2016-2017 Keshav Vishwkarma <keshavvbe@gmail.com>. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
#if os(iOS) || os(tvOS)
import UIKit
#else
import AppKit
#endif
public enum SelfAttribute: Int {
case width = 7, height, aspectRatio = 64
func attribute()-> (LayoutAttribute,LayoutAttribute){
if self == .aspectRatio {
return (.width, .height)
}else{
return (LayoutAttribute(rawValue: self.rawValue)!, .notAnAttribute )
}
}
}
extension NSLayoutConstraint
{
public struct Defualt {
#if os(iOS) || os(tvOS)
public static let iPadRatio = CGFloat(3.0/4.0)
#endif
public static let lessMaxPriority = CGFloat(999.99996)
}
/// :name: prepareConstraint
public final class func prepareConstraint(_ item: Any, attribute attr1: LayoutAttribute, relation: LayoutRelation = .equal, toItem: Any?=nil, attribute attr2: LayoutAttribute = .notAnAttribute, multiplier: CGFloat = 1.0, constant: CGFloat = 0) -> NSLayoutConstraint {
return NSLayoutConstraint(item: item, attribute: attr1, relatedBy: relation, toItem: toItem, attribute: attr2, multiplier: multiplier, constant: constant)
}
}
extension NSLayoutConstraint
{
public final func isEqualTo(constraint c:NSLayoutConstraint, shouldIgnoreMutiplier m:Bool = true, shouldIgnoreRelation r:Bool = true)-> Bool
{
var isEqualExceptMultiplier = firstItem === c.firstItem && firstAttribute == c.firstAttribute && secondItem === c.secondItem && secondAttribute == c.secondAttribute
if !isEqualExceptMultiplier
{
isEqualExceptMultiplier = firstItem === c.secondItem && firstAttribute == c.secondAttribute && secondItem === c.firstItem && secondAttribute == c.firstAttribute
}
log(isEqualExceptMultiplier)
if m && r {
return isEqualExceptMultiplier
}
else if m {
return isEqualExceptMultiplier && multiplier == c.multiplier
}
else if r {
return isEqualExceptMultiplier && relation == c.relation
}
return isEqualExceptMultiplier && multiplier == c.multiplier && relation == c.relation
}
public final func reversed() -> NSLayoutConstraint
{
if let secondItemObj = secondItem {
return NSLayoutConstraint(item: secondItemObj, attribute: secondAttribute, relatedBy: relation, toItem: firstItem, attribute: firstAttribute, multiplier: multiplier, constant: constant)
} else {
return self
}
}
public final func modified(relation r: LayoutRelation) -> NSLayoutConstraint?
{
if relation == r { return self }
#if swift(>=4.0) || (!swift(>=4.0) && os(OSX))
guard let firstItem = self.firstItem else { return nil }
#endif
return NSLayoutConstraint(item: firstItem, attribute: firstAttribute, relatedBy: r, toItem: secondItem, attribute: secondAttribute, multiplier: multiplier, constant: constant)
}
public final func modified(multiplier m: CGFloat) -> NSLayoutConstraint?
{
if multiplier == m { return self }
#if swift(>=4.0) || (!swift(>=4.0) && os(OSX))
guard let firstItem = self.firstItem else { return nil }
#endif
return NSLayoutConstraint(item: firstItem, attribute: firstAttribute, relatedBy: relation, toItem: secondItem, attribute: secondAttribute, multiplier: m, constant: constant)
}
internal final func isSelfConstraint() -> Bool {
// For aspect Ratio
if firstItem === secondItem && ( firstAttribute == .width && secondAttribute == .height || firstAttribute == .height && secondAttribute == .width){
return true
}
if (secondItem == nil && secondAttribute == .notAnAttribute) && (firstAttribute == .width || firstAttribute == .height) {
return true
}
return false
}
}
extension Array where Element: NSLayoutConstraint {
internal func containsApplied(constraint c: Element, shouldIgnoreMutiplier m:Bool = true) -> Element? {
#if os(iOS) || os(tvOS)
let reverseConstraints = reversed().filter {
!( $0.firstItem is UILayoutSupport || $0.secondItem is UILayoutSupport)
}
#else
let reverseConstraints = reversed()
#endif
return reverseConstraints.filter {
$0.isEqualTo(constraint: c, shouldIgnoreMutiplier: m)
}.first
}
}
internal func log( disable: Bool = true, _ args: Any...) {
if !disable {
var messageFormat = ""
args.forEach { messageFormat.append( " " + String(describing: $0) ) }
print( "👀 KVConstraintKit :", messageFormat )
}
}
| mit |
cnbin/WordPress-iOS | WordPress/Classes/ViewRelated/Notifications/Views/NoteTableHeaderView.swift | 6 | 2731 | import Foundation
/**
* @class NoteTableHeaderView
* @brief This class renders a view with top and bottom separators, meant to be used as UITableView
* section header in NotificationsViewController.
*/
@objc public class NoteTableHeaderView : UIView
{
// MARK: - Public Properties
public var title: String? {
set {
// For layout reasons, we need to ensure that the titleLabel uses an exact Paragraph Height!
let unwrappedTitle = newValue?.uppercaseStringWithLocale(NSLocale.currentLocale()) ?? String()
let attributes = Style.sectionHeaderRegularStyle
titleLabel.attributedText = NSAttributedString(string: unwrappedTitle, attributes: attributes)
setNeedsLayout()
}
get {
return titleLabel.text
}
}
public var separatorColor: UIColor? {
set {
layoutView.bottomColor = newValue ?? UIColor.clearColor()
layoutView.topColor = newValue ?? UIColor.clearColor()
}
get {
return layoutView.bottomColor
}
}
// MARK: - Convenience Initializers
public convenience init() {
self.init(frame: CGRectZero)
}
required override public init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
setupView()
}
// MARK - Private Helpers
private func setupView() {
NSBundle.mainBundle().loadNibNamed("NoteTableHeaderView", owner: self, options: nil)
addSubview(contentView)
// Make sure the Outlets are loaded
assert(contentView != nil)
assert(layoutView != nil)
assert(imageView != nil)
assert(titleLabel != nil)
// Layout
contentView.translatesAutoresizingMaskIntoConstraints = false
pinSubviewToAllEdges(contentView)
// Background + Separators
backgroundColor = UIColor.clearColor()
layoutView.backgroundColor = Style.sectionHeaderBackgroundColor
layoutView.bottomVisible = true
layoutView.topVisible = true
}
// MARK: - Aliases
typealias Style = WPStyleGuide.Notifications
// MARK: - Static Properties
public static let headerHeight = CGFloat(26)
// MARK: - Outlets
@IBOutlet private var contentView: UIView!
@IBOutlet private var layoutView: SeparatorsView!
@IBOutlet private var imageView: UIImageView!
@IBOutlet private var titleLabel: UILabel!
}
| gpl-2.0 |
OakCityLabs/VizFig | Example/VizFig/AppDelegate.swift | 1 | 518 | //
// AppDelegate.swift
// VizFig
//
// Created by Jay Lyerly on 07/27/2015.
// Copyright (c) 2015 Jay Lyerly. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
// Override point for customization after application launch.
return true
}
}
| mit |
yunfeng1299/XQ_IDYLive | Imitate_DY/Imitate_DY/Classes/Main/View/ChannelContentView.swift | 1 | 5379 |
//
// ChannelContentView.swift
// Imitate_DY
//
// Created by 夏琪 on 2017/5/4.
// Copyright © 2017年 yunfeng. All rights reserved.
//
import UIKit
//自定义代理(联动)
protocol ChanelContentViewDelegate : class {
func channelContentView(_ contentView : ChannelContentView, progress : CGFloat, sourceIndex : Int, targetIndex : Int)
}
private let ContentCellID = "channelContentCell"
class ChannelContentView: UIView {
//定义属性:
fileprivate var childVcs : [UIViewController]
fileprivate weak var parentViewController : UIViewController?
fileprivate var startOffsetX : CGFloat = 0
fileprivate var isForbidScrollDelegate : Bool = false
weak var delegate : ChanelContentViewDelegate?
//懒加载控件:
fileprivate lazy var collectionView:UICollectionView = {[weak self] in
let layout = UICollectionViewFlowLayout()
layout.itemSize = (self?.bounds.size)!
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.scrollDirection = .horizontal
let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
collectionView.showsHorizontalScrollIndicator = false
collectionView.isPagingEnabled = true
collectionView.bounces = false
collectionView.dataSource = self
collectionView.delegate = self
collectionView.scrollsToTop = false
//注册cell
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: ContentCellID)
return collectionView
}()
init(frame:CGRect,childVcs:[UIViewController],parentViewController:UIViewController?) {
self.childVcs = childVcs
self.parentViewController = parentViewController
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
//搭建界面:
extension ChannelContentView {
fileprivate func setupUI() {
for childVc in childVcs {
parentViewController?.addChildViewController(childVc)
}
addSubview(collectionView)
collectionView.frame = bounds
}
}
//MARK: - colectionView代理方法:
extension ChannelContentView:UICollectionViewDelegate {
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
isForbidScrollDelegate = false
startOffsetX = scrollView.contentOffset.x
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if isForbidScrollDelegate {
return
}
var progress : CGFloat = 0
var sourceIndex : Int = 0
var targetIndex : Int = 0
let currentOffsetX = scrollView.contentOffset.x
let scrollViewW = scrollView.bounds.width
if currentOffsetX > startOffsetX {
progress = currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW)
sourceIndex = Int(currentOffsetX / scrollViewW)
targetIndex = sourceIndex + 1
if targetIndex >= childVcs.count {
targetIndex = childVcs.count - 1
}
if currentOffsetX - startOffsetX == scrollViewW {
progress = 1
targetIndex = sourceIndex
}
} else {
progress = 1 - (currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW))
targetIndex = Int(currentOffsetX / scrollViewW)
sourceIndex = targetIndex + 1
if sourceIndex >= childVcs.count {
sourceIndex = childVcs.count - 1
}
}
//将数值传给代理属性
delegate?.channelContentView(self, progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex)
}
}
//MARK: - collectionView数据源方法
extension ChannelContentView:UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return childVcs.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ContentCellID, for: indexPath)
//给每一个cell设置内容:
for view in cell.contentView.subviews {
view.removeFromSuperview()
}
let childVc = childVcs[indexPath.item]
childVc.view.frame = bounds
cell.contentView.addSubview(childVc.view)
return cell
}
}
//MARK: - 外界获取到的方法:
extension ChannelContentView {
func setCurrentIndex(_ currentIndex:Int) {
isForbidScrollDelegate = true
let offsetX = CGFloat(currentIndex) * collectionView.frame.width
collectionView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: false)
}
}
| mit |
LibraryLoupe/PhotosPlus | PhotosPlus/Cameras/Canon/CanonEOS7D.swift | 3 | 486 | //
// Photos Plus, https://github.com/LibraryLoupe/PhotosPlus
//
// Copyright (c) 2016-2017 Matt Klosterman and contributors. All rights reserved.
//
import Foundation
extension Cameras.Manufacturers.Canon {
public struct EOS7D: CameraModel {
public init() {}
public let name = "Canon EOS 7D"
public let manufacturerType: CameraManufacturer.Type = Cameras.Manufacturers.Canon.self
}
}
public typealias CanonEOS7D = Cameras.Manufacturers.Canon.EOS7D
| mit |
vishw3/IOSChart-IOS-7.0-Support | VisChart/Classes/Utils/ChartTransformer.swift | 2 | 9442 | //
// ChartTransformer.swift
// Charts
//
// Created by Daniel Cohen Gindi on 6/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import UIKit
/// Transformer class that contains all matrices and is responsible for transforming values into pixels on the screen and backwards.
public class ChartTransformer: NSObject
{
/// matrix to map the values to the screen pixels
internal var _matrixValueToPx = CGAffineTransformIdentity
/// matrix for handling the different offsets of the chart
internal var _matrixOffset = CGAffineTransformIdentity
internal var _viewPortHandler: ChartViewPortHandler
public init(viewPortHandler: ChartViewPortHandler)
{
_viewPortHandler = viewPortHandler;
}
/// Prepares the matrix that transforms values to pixels. Calculates the scale factors from the charts size and offsets.
public func prepareMatrixValuePx(#chartXMin: Float, deltaX: CGFloat, deltaY: CGFloat, chartYMin: Float)
{
var scaleX = (_viewPortHandler.contentWidth / deltaX);
var scaleY = (_viewPortHandler.contentHeight / deltaY);
// setup all matrices
_matrixValueToPx = CGAffineTransformIdentity;
_matrixValueToPx = CGAffineTransformScale(_matrixValueToPx, scaleX, -scaleY);
_matrixValueToPx = CGAffineTransformTranslate(_matrixValueToPx, CGFloat(-chartXMin), CGFloat(-chartYMin));
}
/// Prepares the matrix that contains all offsets.
public func prepareMatrixOffset(inverted: Bool)
{
if (!inverted)
{
_matrixOffset = CGAffineTransformMakeTranslation(_viewPortHandler.offsetLeft, _viewPortHandler.chartHeight - _viewPortHandler.offsetBottom);
}
else
{
_matrixOffset = CGAffineTransformMakeScale(1.0, -1.0);
_matrixOffset = CGAffineTransformTranslate(_matrixOffset, _viewPortHandler.offsetLeft, -_viewPortHandler.offsetTop);
}
}
/// Transforms an arraylist of Entry into a float array containing the x and y values transformed with all matrices for the SCATTERCHART.
public func generateTransformedValuesScatter(entries: [ChartDataEntry], phaseY: CGFloat) -> [CGPoint]
{
var valuePoints = [CGPoint]();
valuePoints.reserveCapacity(entries.count);
for (var j = 0; j < entries.count; j++)
{
var e = entries[j];
valuePoints.append(CGPoint(x: CGFloat(e.xIndex), y: CGFloat(e.value) * phaseY));
}
pointValuesToPixel(&valuePoints);
return valuePoints;
}
/// Transforms an arraylist of Entry into a float array containing the x and y values transformed with all matrices for the LINECHART.
public func generateTransformedValuesLine(entries: [ChartDataEntry], phaseX: CGFloat, phaseY: CGFloat, from: Int, to: Int) -> [CGPoint]
{
let count = Int(ceil(CGFloat(to - from) * phaseX));
var valuePoints = [CGPoint]();
valuePoints.reserveCapacity(count);
for (var j = 0; j < count; j++)
{
var e = entries[j + from];
valuePoints.append(CGPoint(x: CGFloat(e.xIndex), y: CGFloat(e.value) * phaseY));
}
pointValuesToPixel(&valuePoints);
return valuePoints;
}
/// Transforms an arraylist of Entry into a float array containing the x and y values transformed with all matrices for the CANDLESTICKCHART.
public func generateTransformedValuesCandle(entries: [CandleChartDataEntry], phaseY: CGFloat) -> [CGPoint]
{
var valuePoints = [CGPoint]();
valuePoints.reserveCapacity(entries.count);
for (var j = 0; j < entries.count; j++)
{
var e = entries[j];
valuePoints.append(CGPoint(x: CGFloat(e.xIndex), y: CGFloat(e.high) * phaseY));
}
pointValuesToPixel(&valuePoints);
return valuePoints;
}
/// Transforms an arraylist of Entry into a float array containing the x and y values transformed with all matrices for the BARCHART.
public func generateTransformedValuesBarChart(entries: [BarChartDataEntry], dataSet: Int, barData: BarChartData, phaseY: CGFloat) -> [CGPoint]
{
var valuePoints = [CGPoint]();
valuePoints.reserveCapacity(entries.count);
var setCount = barData.dataSetCount;
var space = barData.groupSpace;
for (var j = 0; j < entries.count; j++)
{
var e = entries[j];
// calculate the x-position, depending on datasetcount
var x = CGFloat(e.xIndex + (j * (setCount - 1)) + dataSet) + space * CGFloat(j) + space / 2.0;
var y = e.value;
valuePoints.append(CGPoint(x: x, y: CGFloat(y) * phaseY));
}
pointValuesToPixel(&valuePoints);
return valuePoints;
}
/// Transforms an arraylist of Entry into a float array containing the x and y values transformed with all matrices for the BARCHART.
public func generateTransformedValuesHorizontalBarChart(entries: [ChartDataEntry], dataSet: Int, barData: BarChartData, phaseY: CGFloat) -> [CGPoint]
{
var valuePoints = [CGPoint]();
valuePoints.reserveCapacity(entries.count);
var setCount = barData.dataSetCount;
var space = barData.groupSpace;
for (var j = 0; j < entries.count; j++)
{
var e = entries[j];
// calculate the x-position, depending on datasetcount
var x = CGFloat(e.xIndex + (j * (setCount - 1)) + dataSet) + space * CGFloat(j) + space / 2.0;
var y = e.value;
valuePoints.append(CGPoint(x: CGFloat(y) * phaseY, y: x));
}
pointValuesToPixel(&valuePoints);
return valuePoints;
}
/// Transform an array of points with all matrices.
// VERY IMPORTANT: Keep matrix order "value-touch-offset" when transforming.
public func pointValuesToPixel(inout pts: [CGPoint])
{
var trans = valueToPixelMatrix;
for (var i = 0, count = pts.count; i < count; i++)
{
pts[i] = CGPointApplyAffineTransform(pts[i], trans);
}
}
public func pointValueToPixel(inout point: CGPoint)
{
point = CGPointApplyAffineTransform(point, valueToPixelMatrix);
}
/// Transform a rectangle with all matrices.
public func rectValueToPixel(inout r: CGRect)
{
r = CGRectApplyAffineTransform(r, valueToPixelMatrix);
}
/// Transform a rectangle with all matrices with potential animation phases.
public func rectValueToPixel(inout r: CGRect, phaseY: CGFloat)
{
// multiply the height of the rect with the phase
if (r.origin.y > 0.0)
{
r.origin.y *= phaseY;
}
else
{
var bottom = r.origin.y + r.size.height;
bottom *= phaseY;
r.size.height = bottom - r.origin.y;
}
r = CGRectApplyAffineTransform(r, valueToPixelMatrix);
}
/// Transform a rectangle with all matrices with potential animation phases.
public func rectValueToPixelHorizontal(inout r: CGRect, phaseY: CGFloat)
{
// multiply the height of the rect with the phase
if (r.origin.x > 0.0)
{
r.origin.x *= phaseY;
}
else
{
var right = r.origin.x + r.size.width;
right *= phaseY;
r.size.width = right - r.origin.x;
}
r = CGRectApplyAffineTransform(r, valueToPixelMatrix);
}
/// transforms multiple rects with all matrices
public func rectValuesToPixel(inout rects: [CGRect])
{
var trans = valueToPixelMatrix;
for (var i = 0; i < rects.count; i++)
{
rects[i] = CGRectApplyAffineTransform(rects[i], trans);
}
}
/// Transforms the given array of touch points (pixels) into values on the chart.
public func pixelsToValue(inout pixels: [CGPoint])
{
var trans = pixelToValueMatrix;
for (var i = 0; i < pixels.count; i++)
{
pixels[i] = CGPointApplyAffineTransform(pixels[i], trans);
}
}
/// Transforms the given touch point (pixels) into a value on the chart.
public func pixelToValue(inout pixel: CGPoint)
{
pixel = CGPointApplyAffineTransform(pixel, pixelToValueMatrix);
}
/// Returns the x and y values in the chart at the given touch point
/// (encapsulated in a PointD). This method transforms pixel coordinates to
/// coordinates / values in the chart.
public func getValueByTouchPoint(point: CGPoint) -> CGPoint
{
return CGPointApplyAffineTransform(point, pixelToValueMatrix);
}
public var valueToPixelMatrix: CGAffineTransform
{
return
CGAffineTransformConcat(
CGAffineTransformConcat(
_matrixValueToPx,
_viewPortHandler.touchMatrix
),
_matrixOffset
);
}
public var pixelToValueMatrix: CGAffineTransform
{
return CGAffineTransformInvert(valueToPixelMatrix);
}
} | mit |
Bluthwort/Bluthwort | Sources/Classes/UI/ButtonTableViewCell.swift | 1 | 2197 | //
// ButtonTableViewCell.swift
//
// Copyright (c) 2018 Bluthwort
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
private let kDefaultButtonHeight: CGFloat = 44.0
open class ButtonTableViewCell: UITableViewCell {
// MARK: Properties
open let button = UIButton()
// MARK: Lifecycle
public override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setup()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
private func setup() {
backgroundColor = .clear
separatorInset = .init(top: 0.0, left: 0.0, bottom: 0.0, right: kScreenWidth)
selectionStyle = .none
setupSubviews()
}
// MARK: Subviews Configuration
private func setupSubviews() {
button.bw.backgroundColor(UIColor.bw.init(hex: 0x007AFF)).add(to: self) {
$0.top.leading.equalToSuperview().offset(kMargin12)
$0.trailing.bottom.equalToSuperview().offset(-kMargin12)
$0.height.equalTo(kDefaultButtonHeight)
}
}
}
| mit |
siyana/SwiftMaps | PhotoMaps/PhotoMaps/PlacesSection.swift | 1 | 377 | //
// PlacesSection.swift
// PhotoMaps
//
// Created by Siyana Slavova on 4/7/15.
// Copyright (c) 2015 Siyana Slavova. All rights reserved.
//
import UIKit
class PlacesSection: NSObject {
var sectionTitle: String
var sectionItems: Array<String>
init(name: String, items: Array<String>) {
sectionTitle = name
sectionItems = items
}
}
| mit |
matthewpurcell/firefox-ios | ThirdParty/SQLite.swift/Source/Core/Connection.swift | 5 | 23944 | //
// SQLite.swift
// https://github.com/stephencelis/SQLite.swift
// Copyright © 2014-2015 Stephen Celis.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Dispatch
/// A connection to SQLite.
public final class Connection {
/// The location of a SQLite database.
public enum Location {
/// An in-memory database (equivalent to `.URI(":memory:")`).
///
/// See: <https://www.sqlite.org/inmemorydb.html#sharedmemdb>
case InMemory
/// A temporary, file-backed database (equivalent to `.URI("")`).
///
/// See: <https://www.sqlite.org/inmemorydb.html#temp_db>
case Temporary
/// A database located at the given URI filename (or path).
///
/// See: <https://www.sqlite.org/uri.html>
///
/// - Parameter filename: A URI filename
case URI(String)
}
public var handle: COpaquePointer { return _handle }
private var _handle: COpaquePointer = nil
/// Initializes a new SQLite connection.
///
/// - Parameters:
///
/// - location: The location of the database. Creates a new database if it
/// doesn’t already exist (unless in read-only mode).
///
/// Default: `.InMemory`.
///
/// - readonly: Whether or not to open the database in a read-only state.
///
/// Default: `false`.
///
/// - Returns: A new database connection.
public init(_ location: Location = .InMemory, readonly: Bool = false) throws {
let flags = readonly ? SQLITE_OPEN_READONLY : SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE
try check(sqlite3_open_v2(location.description, &_handle, flags | SQLITE_OPEN_FULLMUTEX, nil))
dispatch_queue_set_specific(queue, Connection.queueKey, queueContext, nil)
}
/// Initializes a new connection to a database.
///
/// - Parameters:
///
/// - filename: The location of the database. Creates a new database if
/// it doesn’t already exist (unless in read-only mode).
///
/// - readonly: Whether or not to open the database in a read-only state.
///
/// Default: `false`.
///
/// - Throws: `Result.Error` iff a connection cannot be established.
///
/// - Returns: A new database connection.
public convenience init(_ filename: String, readonly: Bool = false) throws {
try self.init(.URI(filename), readonly: readonly)
}
deinit {
sqlite3_close_v2(handle)
}
// MARK: -
/// Whether or not the database was opened in a read-only state.
public var readonly: Bool { return sqlite3_db_readonly(handle, nil) == 1 }
/// The last rowid inserted into the database via this connection.
public var lastInsertRowid: Int64? {
let rowid = sqlite3_last_insert_rowid(handle)
return rowid > 0 ? rowid : nil
}
/// The last number of changes (inserts, updates, or deletes) made to the
/// database via this connection.
public var changes: Int {
return Int(sqlite3_changes(handle))
}
/// The total number of changes (inserts, updates, or deletes) made to the
/// database via this connection.
public var totalChanges: Int {
return Int(sqlite3_total_changes(handle))
}
// MARK: - Execute
/// Executes a batch of SQL statements.
///
/// - Parameter SQL: A batch of zero or more semicolon-separated SQL
/// statements.
///
/// - Throws: `Result.Error` if query execution fails.
public func execute(SQL: String) throws {
try sync { try check(sqlite3_exec(self.handle, SQL, nil, nil, nil)) }
}
// MARK: - Prepare
/// Prepares a single SQL statement (with optional parameter bindings).
///
/// - Parameters:
///
/// - statement: A single SQL statement.
///
/// - bindings: A list of parameters to bind to the statement.
///
/// - Returns: A prepared statement.
@warn_unused_result public func prepare(statement: String, _ bindings: Binding?...) -> Statement {
if !bindings.isEmpty { return prepare(statement, bindings) }
return Statement(self, statement)
}
/// Prepares a single SQL statement and binds parameters to it.
///
/// - Parameters:
///
/// - statement: A single SQL statement.
///
/// - bindings: A list of parameters to bind to the statement.
///
/// - Returns: A prepared statement.
@warn_unused_result public func prepare(statement: String, _ bindings: [Binding?]) -> Statement {
return prepare(statement).bind(bindings)
}
/// Prepares a single SQL statement and binds parameters to it.
///
/// - Parameters:
///
/// - statement: A single SQL statement.
///
/// - bindings: A dictionary of named parameters to bind to the statement.
///
/// - Returns: A prepared statement.
@warn_unused_result public func prepare(statement: String, _ bindings: [String: Binding?]) -> Statement {
return prepare(statement).bind(bindings)
}
// MARK: - Run
/// Runs a single SQL statement (with optional parameter bindings).
///
/// - Parameters:
///
/// - statement: A single SQL statement.
///
/// - bindings: A list of parameters to bind to the statement.
///
/// - Throws: `Result.Error` if query execution fails.
///
/// - Returns: The statement.
public func run(statement: String, _ bindings: Binding?...) throws -> Statement {
return try run(statement, bindings)
}
/// Prepares, binds, and runs a single SQL statement.
///
/// - Parameters:
///
/// - statement: A single SQL statement.
///
/// - bindings: A list of parameters to bind to the statement.
///
/// - Throws: `Result.Error` if query execution fails.
///
/// - Returns: The statement.
public func run(statement: String, _ bindings: [Binding?]) throws -> Statement {
return try prepare(statement).run(bindings)
}
/// Prepares, binds, and runs a single SQL statement.
///
/// - Parameters:
///
/// - statement: A single SQL statement.
///
/// - bindings: A dictionary of named parameters to bind to the statement.
///
/// - Throws: `Result.Error` if query execution fails.
///
/// - Returns: The statement.
public func run(statement: String, _ bindings: [String: Binding?]) throws -> Statement {
return try prepare(statement).run(bindings)
}
// MARK: - Scalar
/// Runs a single SQL statement (with optional parameter bindings),
/// returning the first value of the first row.
///
/// - Parameters:
///
/// - statement: A single SQL statement.
///
/// - bindings: A list of parameters to bind to the statement.
///
/// - Returns: The first value of the first row returned.
@warn_unused_result public func scalar(statement: String, _ bindings: Binding?...) -> Binding? {
return scalar(statement, bindings)
}
/// Runs a single SQL statement (with optional parameter bindings),
/// returning the first value of the first row.
///
/// - Parameters:
///
/// - statement: A single SQL statement.
///
/// - bindings: A list of parameters to bind to the statement.
///
/// - Returns: The first value of the first row returned.
@warn_unused_result public func scalar(statement: String, _ bindings: [Binding?]) -> Binding? {
return prepare(statement).scalar(bindings)
}
/// Runs a single SQL statement (with optional parameter bindings),
/// returning the first value of the first row.
///
/// - Parameters:
///
/// - statement: A single SQL statement.
///
/// - bindings: A dictionary of named parameters to bind to the statement.
///
/// - Returns: The first value of the first row returned.
@warn_unused_result public func scalar(statement: String, _ bindings: [String: Binding?]) -> Binding? {
return prepare(statement).scalar(bindings)
}
// MARK: - Transactions
/// The mode in which a transaction acquires a lock.
public enum TransactionMode : String {
/// Defers locking the database till the first read/write executes.
case Deferred = "DEFERRED"
/// Immediately acquires a reserved lock on the database.
case Immediate = "IMMEDIATE"
/// Immediately acquires an exclusive lock on all databases.
case Exclusive = "EXCLUSIVE"
}
// TODO: Consider not requiring a throw to roll back?
/// Runs a transaction with the given mode.
///
/// - Note: Transactions cannot be nested. To nest transactions, see
/// `savepoint()`, instead.
///
/// - Parameters:
///
/// - mode: The mode in which a transaction acquires a lock.
///
/// Default: `.Deferred`
///
/// - block: A closure to run SQL statements within the transaction.
/// The transaction will be committed when the block returns. The block
/// must throw to roll the transaction back.
///
/// - Throws: `Result.Error`, and rethrows.
public func transaction(mode: TransactionMode = .Deferred, block: () throws -> Void) throws {
try transaction("BEGIN \(mode.rawValue) TRANSACTION", block, "COMMIT TRANSACTION", or: "ROLLBACK TRANSACTION")
}
// TODO: Consider not requiring a throw to roll back?
// TODO: Consider removing ability to set a name?
/// Runs a transaction with the given savepoint name (if omitted, it will
/// generate a UUID).
///
/// - SeeAlso: `transaction()`.
///
/// - Parameters:
///
/// - savepointName: A unique identifier for the savepoint (optional).
///
/// - block: A closure to run SQL statements within the transaction.
/// The savepoint will be released (committed) when the block returns.
/// The block must throw to roll the savepoint back.
///
/// - Throws: `SQLite.Result.Error`, and rethrows.
public func savepoint(name: String = NSUUID().UUIDString, block: () throws -> Void) throws {
let name = name.quote("'")
let savepoint = "SAVEPOINT \(name)"
try transaction(savepoint, block, "RELEASE \(savepoint)", or: "ROLLBACK TO \(savepoint)")
}
private func transaction(begin: String, _ block: () throws -> Void, _ commit: String, or rollback: String) throws {
return try sync {
try self.run(begin)
do {
try block()
} catch {
try self.run(rollback)
throw error
}
try self.run(commit)
}
}
/// Interrupts any long-running queries.
public func interrupt() {
sqlite3_interrupt(handle)
}
// MARK: - Handlers
/// The number of seconds a connection will attempt to retry a statement
/// after encountering a busy signal (lock).
public var busyTimeout: Double = 0 {
didSet {
sqlite3_busy_timeout(handle, Int32(busyTimeout * 1_000))
}
}
/// Sets a handler to call after encountering a busy signal (lock).
///
/// - Parameter callback: This block is executed during a lock in which a
/// busy error would otherwise be returned. It’s passed the number of
/// times it’s been called for this lock. If it returns `true`, it will
/// try again. If it returns `false`, no further attempts will be made.
public func busyHandler(callback: ((tries: Int) -> Bool)?) {
guard let callback = callback else {
sqlite3_busy_handler(handle, nil, nil)
busyHandler = nil
return
}
let box: BusyHandler = {
callback(tries: Int($0)) ? 1 : 0
}
sqlite3_busy_handler(handle, { callback, tries in
unsafeBitCast(callback, BusyHandler.self)(tries)
}, unsafeBitCast(box, UnsafeMutablePointer<Void>.self))
busyHandler = box
}
private typealias BusyHandler = @convention(block) Int32 -> Int32
private var busyHandler: BusyHandler?
/// Sets a handler to call when a statement is executed with the compiled
/// SQL.
///
/// - Parameter callback: This block is invoked when a statement is executed
/// with the compiled SQL as its argument.
///
/// db.trace { SQL in print(SQL) }
public func trace(callback: (String -> Void)?) {
guard let callback = callback else {
sqlite3_trace(handle, nil, nil)
trace = nil
return
}
let box: Trace = { callback(String.fromCString($0)!) }
sqlite3_trace(handle, { callback, SQL in
unsafeBitCast(callback, Trace.self)(SQL)
}, unsafeBitCast(box, UnsafeMutablePointer<Void>.self))
trace = box
}
private typealias Trace = @convention(block) UnsafePointer<Int8> -> Void
private var trace: Trace?
/// Registers a callback to be invoked whenever a row is inserted, updated,
/// or deleted in a rowid table.
///
/// - Parameter callback: A callback invoked with the `Operation` (one of
/// `.Insert`, `.Update`, or `.Delete`), database name, table name, and
/// rowid.
public func updateHook(callback: ((operation: Operation, db: String, table: String, rowid: Int64) -> Void)?) {
guard let callback = callback else {
sqlite3_update_hook(handle, nil, nil)
updateHook = nil
return
}
let box: UpdateHook = {
callback(
operation: Operation(rawValue: $0),
db: String.fromCString($1)!,
table: String.fromCString($2)!,
rowid: $3
)
}
sqlite3_update_hook(handle, { callback, operation, db, table, rowid in
unsafeBitCast(callback, UpdateHook.self)(operation, db, table, rowid)
}, unsafeBitCast(box, UnsafeMutablePointer<Void>.self))
updateHook = box
}
private typealias UpdateHook = @convention(block) (Int32, UnsafePointer<Int8>, UnsafePointer<Int8>, Int64) -> Void
private var updateHook: UpdateHook?
/// Registers a callback to be invoked whenever a transaction is committed.
///
/// - Parameter callback: A callback invoked whenever a transaction is
/// committed. If this callback throws, the transaction will be rolled
/// back.
public func commitHook(callback: (() throws -> Void)?) {
guard let callback = callback else {
sqlite3_commit_hook(handle, nil, nil)
commitHook = nil
return
}
let box: CommitHook = {
do {
try callback()
} catch {
return 1
}
return 0
}
sqlite3_commit_hook(handle, { callback in
unsafeBitCast(callback, CommitHook.self)()
}, unsafeBitCast(box, UnsafeMutablePointer<Void>.self))
commitHook = box
}
private typealias CommitHook = @convention(block) () -> Int32
private var commitHook: CommitHook?
/// Registers a callback to be invoked whenever a transaction rolls back.
///
/// - Parameter callback: A callback invoked when a transaction is rolled
/// back.
public func rollbackHook(callback: (() -> Void)?) {
guard let callback = callback else {
sqlite3_rollback_hook(handle, nil, nil)
rollbackHook = nil
return
}
let box: RollbackHook = { callback() }
sqlite3_rollback_hook(handle, { callback in
unsafeBitCast(callback, RollbackHook.self)()
}, unsafeBitCast(box, UnsafeMutablePointer<Void>.self))
rollbackHook = box
}
private typealias RollbackHook = @convention(block) () -> Void
private var rollbackHook: RollbackHook?
/// Creates or redefines a custom SQL function.
///
/// - Parameters:
///
/// - function: The name of the function to create or redefine.
///
/// - argumentCount: The number of arguments that the function takes. If
/// `nil`, the function may take any number of arguments.
///
/// Default: `nil`
///
/// - deterministic: Whether or not the function is deterministic (_i.e._
/// the function always returns the same result for a given input).
///
/// Default: `false`
///
/// - block: A block of code to run when the function is called. The block
/// is called with an array of raw SQL values mapped to the function’s
/// parameters and should return a raw SQL value (or nil).
public func createFunction(function: String, argumentCount: UInt? = nil, deterministic: Bool = false, _ block: (args: [Binding?]) -> Binding?) {
let argc = argumentCount.map { Int($0) } ?? -1
let box: Function = { context, argc, argv in
let arguments: [Binding?] = (0..<Int(argc)).map { idx in
let value = argv[idx]
switch sqlite3_value_type(value) {
case SQLITE_BLOB:
return Blob(bytes: sqlite3_value_blob(value), length: Int(sqlite3_value_bytes(value)))
case SQLITE_FLOAT:
return sqlite3_value_double(value)
case SQLITE_INTEGER:
return sqlite3_value_int64(value)
case SQLITE_NULL:
return nil
case SQLITE_TEXT:
return String.fromCString(UnsafePointer(sqlite3_value_text(value)))!
case let type:
fatalError("unsupported value type: \(type)")
}
}
let result = block(args: arguments)
if let result = result as? Blob {
sqlite3_result_blob(context, result.bytes, Int32(result.bytes.count), nil)
} else if let result = result as? Double {
sqlite3_result_double(context, result)
} else if let result = result as? Int64 {
sqlite3_result_int64(context, result)
} else if let result = result as? String {
sqlite3_result_text(context, result, Int32(result.characters.count), SQLITE_TRANSIENT)
} else if result == nil {
sqlite3_result_null(context)
} else {
fatalError("unsupported result type: \(result)")
}
}
var flags = SQLITE_UTF8
if deterministic {
flags |= SQLITE_DETERMINISTIC
}
sqlite3_create_function_v2(handle, function, Int32(argc), flags, unsafeBitCast(box, UnsafeMutablePointer<Void>.self), { context, argc, value in
unsafeBitCast(sqlite3_user_data(context), Function.self)(context, argc, value)
}, nil, nil, nil)
if functions[function] == nil { self.functions[function] = [:] }
functions[function]?[argc] = box
}
private typealias Function = @convention(block) (COpaquePointer, Int32, UnsafeMutablePointer<COpaquePointer>) -> Void
private var functions = [String: [Int: Function]]()
/// The return type of a collation comparison function.
public typealias ComparisonResult = NSComparisonResult
/// Defines a new collating sequence.
///
/// - Parameters:
///
/// - collation: The name of the collation added.
///
/// - block: A collation function that takes two strings and returns the
/// comparison result.
public func createCollation(collation: String, _ block: (lhs: String, rhs: String) -> ComparisonResult) {
let box: Collation = { lhs, rhs in
Int32(block(lhs: String.fromCString(UnsafePointer<Int8>(lhs))!, rhs: String.fromCString(UnsafePointer<Int8>(rhs))!).rawValue)
}
try! check(sqlite3_create_collation_v2(handle, collation, SQLITE_UTF8, unsafeBitCast(box, UnsafeMutablePointer<Void>.self), { callback, _, lhs, _, rhs in
unsafeBitCast(callback, Collation.self)(lhs, rhs)
}, nil))
collations[collation] = box
}
private typealias Collation = @convention(block) (UnsafePointer<Void>, UnsafePointer<Void>) -> Int32
private var collations = [String: Collation]()
// MARK: - Error Handling
func sync<T>(block: () throws -> T) rethrows -> T {
var success: T?
var failure: ErrorType?
let box: () -> Void = {
do {
success = try block()
} catch {
failure = error
}
}
if dispatch_get_specific(Connection.queueKey) == queueContext {
box()
} else {
dispatch_sync(queue, box) // FIXME: rdar://problem/21389236
}
if let failure = failure {
try { () -> Void in throw failure }()
}
return success!
}
private var queue = dispatch_queue_create("SQLite.Database", DISPATCH_QUEUE_SERIAL)
private static let queueKey = unsafeBitCast(Connection.self, UnsafePointer<Void>.self)
private lazy var queueContext: UnsafeMutablePointer<Void> = unsafeBitCast(self, UnsafeMutablePointer<Void>.self)
}
extension Connection : CustomStringConvertible {
public var description: String {
return String.fromCString(sqlite3_db_filename(handle, nil))!
}
}
extension Connection.Location : CustomStringConvertible {
public var description: String {
switch self {
case .InMemory:
return ":memory:"
case .Temporary:
return ""
case .URI(let URI):
return URI
}
}
}
/// An SQL operation passed to update callbacks.
public enum Operation {
/// An INSERT operation.
case Insert
/// An UPDATE operation.
case Update
/// A DELETE operation.
case Delete
private init(rawValue: Int32) {
switch rawValue {
case SQLITE_INSERT:
self = .Insert
case SQLITE_UPDATE:
self = .Update
case SQLITE_DELETE:
self = .Delete
default:
fatalError("unhandled operation code: \(rawValue)")
}
}
}
public enum Result : ErrorType {
private static let successCodes: Set = [SQLITE_OK, SQLITE_ROW, SQLITE_DONE]
case Error(code: Int32, statement: Statement?)
init?(errorCode: Int32, statement: Statement? = nil) {
guard !Result.successCodes.contains(errorCode) else {
return nil
}
self = Error(code: errorCode, statement: statement)
}
}
extension Result : CustomStringConvertible {
public var description: String {
switch self {
case .Error(let code, _):
return String.fromCString(sqlite3_errstr(code))!
}
}
}
| mpl-2.0 |
Prodisky/LASS-Dial | StyleKitDial.swift | 1 | 10766 | //
// StyleKitDial.swift
// LASS Dial
//
// Created by Paul Wu on 2016/2/4.
// Copyright (c) 2016 Prodisky Inc. All rights reserved.
//
// Generated by PaintCode (www.paintcodeapp.com)
//
import UIKit
public class StyleKitDial : NSObject {
//// Drawing Methods
public class func drawRing(value value: CGFloat = 0.14, colorR: CGFloat = 1, colorG: CGFloat = 1, colorB: CGFloat = 1, colorA: CGFloat = 1) {
//// General Declarations
let context = UIGraphicsGetCurrentContext()
//// Color Declarations
let colorRingBack = UIColor(red: 1.000, green: 1.000, blue: 1.000, alpha: 0.200)
//// Variable Declarations
let expressionAngle: CGFloat = -value * 360
let expressionColor = UIColor(red: colorR, green: colorG, blue: colorB, alpha: colorA)
//// Oval Line Back Drawing
CGContextSaveGState(context)
CGContextTranslateCTM(context, 100, 100)
CGContextRotateCTM(context, -90 * CGFloat(M_PI) / 180)
let ovalLineBackPath = UIBezierPath(ovalInRect: CGRectMake(-91, -91, 182, 182))
colorRingBack.setStroke()
ovalLineBackPath.lineWidth = 16
ovalLineBackPath.stroke()
CGContextRestoreGState(context)
//// Oval Line Drawing
CGContextSaveGState(context)
CGContextTranslateCTM(context, 100, 100)
CGContextRotateCTM(context, -90 * CGFloat(M_PI) / 180)
let ovalLineRect = CGRectMake(-91, -91, 182, 182)
let ovalLinePath = UIBezierPath()
ovalLinePath.addArcWithCenter(CGPointMake(ovalLineRect.midX, ovalLineRect.midY), radius: ovalLineRect.width / 2, startAngle: 0 * CGFloat(M_PI)/180, endAngle: -expressionAngle * CGFloat(M_PI)/180, clockwise: true)
expressionColor.setStroke()
ovalLinePath.lineWidth = 16
ovalLinePath.stroke()
CGContextRestoreGState(context)
//// Oval Line Back 2 Drawing
CGContextSaveGState(context)
CGContextTranslateCTM(context, 100, 100)
CGContextRotateCTM(context, -90 * CGFloat(M_PI) / 180)
let ovalLineBack2Path = UIBezierPath(ovalInRect: CGRectMake(-78, -78, 156, 156))
colorRingBack.setFill()
ovalLineBack2Path.fill()
CGContextRestoreGState(context)
}
public class func drawDataItem(frame frame: CGRect = CGRectMake(0, 0, 240, 320), name: String = "PM 2.5", data: String = "35", unit: String = "μg/m3", value: CGFloat = 0.14, station: String = "臺東 1.4KM", time: String = "2016/01/23 14:31", colorR: CGFloat = 1, colorG: CGFloat = 1, colorB: CGFloat = 1, colorA: CGFloat = 1) {
//// General Declarations
let context = UIGraphicsGetCurrentContext()
//// Symbol Time Drawing
let symbolTimeRect = CGRectMake(frame.minX + floor(frame.width * 0.08333 + 0.5), frame.minY + floor(frame.height * 0.90000 + 0.5), floor(frame.width * 0.91667 + 0.5) - floor(frame.width * 0.08333 + 0.5), floor(frame.height * 0.97500 + 0.5) - floor(frame.height * 0.90000 + 0.5))
CGContextSaveGState(context)
UIRectClip(symbolTimeRect)
CGContextTranslateCTM(context, symbolTimeRect.origin.x, symbolTimeRect.origin.y)
CGContextScaleCTM(context, symbolTimeRect.size.width / 200, symbolTimeRect.size.height / 24)
StyleKitDial.drawCenterText(label: time, colorR: colorR, colorG: colorG, colorB: colorB, colorA: colorA)
CGContextRestoreGState(context)
//// Symbol Station Drawing
let symbolStationRect = CGRectMake(frame.minX + floor(frame.width * -0.12500 + 0.5), frame.minY + floor(frame.height * 0.78750 + 0.5), floor(frame.width * 1.12500 + 0.5) - floor(frame.width * -0.12500 + 0.5), floor(frame.height * 0.90000 + 0.5) - floor(frame.height * 0.78750 + 0.5))
CGContextSaveGState(context)
UIRectClip(symbolStationRect)
CGContextTranslateCTM(context, symbolStationRect.origin.x, symbolStationRect.origin.y)
CGContextScaleCTM(context, symbolStationRect.size.width / 200, symbolStationRect.size.height / 24)
StyleKitDial.drawCenterText(label: station, colorR: colorR, colorG: colorG, colorB: colorB, colorA: colorA)
CGContextRestoreGState(context)
//// Symbol Name Drawing
let symbolNameRect = CGRectMake(frame.minX + floor(frame.width * -0.33333 + 0.5), frame.minY + floor(frame.height * 0.01875 + 0.5), floor(frame.width * 1.33333 + 0.5) - floor(frame.width * -0.33333 + 0.5), floor(frame.height * 0.16875 + 0.5) - floor(frame.height * 0.01875 + 0.5))
CGContextSaveGState(context)
UIRectClip(symbolNameRect)
CGContextTranslateCTM(context, symbolNameRect.origin.x, symbolNameRect.origin.y)
CGContextScaleCTM(context, symbolNameRect.size.width / 200, symbolNameRect.size.height / 24)
StyleKitDial.drawCenterText(label: name, colorR: colorR, colorG: colorG, colorB: colorB, colorA: colorA)
CGContextRestoreGState(context)
//// Symbol Ring Drawing
let symbolRingRect = CGRectMake(frame.minX + floor(frame.width * 0.08333 + 0.5), frame.minY + floor(frame.height * 0.15625 + 0.5), floor(frame.width * 0.91667 + 0.5) - floor(frame.width * 0.08333 + 0.5), floor(frame.height * 0.78125 + 0.5) - floor(frame.height * 0.15625 + 0.5))
CGContextSaveGState(context)
UIRectClip(symbolRingRect)
CGContextTranslateCTM(context, symbolRingRect.origin.x, symbolRingRect.origin.y)
StyleKitDial.drawDataRing(frame: CGRectMake(0, 0, symbolRingRect.size.width, symbolRingRect.size.height), data: data, unit: unit, value: value, colorR: colorR, colorG: colorG, colorB: colorB, colorA: colorA)
CGContextRestoreGState(context)
}
public class func drawCenterText(label label: String = "PM 2.5", colorR: CGFloat = 1, colorG: CGFloat = 1, colorB: CGFloat = 1, colorA: CGFloat = 1) {
//// General Declarations
let context = UIGraphicsGetCurrentContext()
//// Variable Declarations
let expressionColor = UIColor(red: colorR, green: colorG, blue: colorB, alpha: colorA)
//// Text Drawing
let textRect = CGRectMake(0, 0, 200, 24)
let textStyle = NSParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle
textStyle.alignment = .Center
let textFontAttributes = [NSFontAttributeName: UIFont.systemFontOfSize(19), NSForegroundColorAttributeName: expressionColor, NSParagraphStyleAttributeName: textStyle]
let textTextHeight: CGFloat = NSString(string: label).boundingRectWithSize(CGSizeMake(textRect.width, CGFloat.infinity), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: textFontAttributes, context: nil).size.height
CGContextSaveGState(context)
CGContextClipToRect(context, textRect);
NSString(string: label).drawInRect(CGRectMake(textRect.minX, textRect.minY + (textRect.height - textTextHeight) / 2, textRect.width, textTextHeight), withAttributes: textFontAttributes)
CGContextRestoreGState(context)
}
public class func drawDataRing(frame frame: CGRect = CGRectMake(0, 0, 200, 200), data: String = "35", unit: String = "μg/m3", value: CGFloat = 0.14, colorR: CGFloat = 1, colorG: CGFloat = 1, colorB: CGFloat = 1, colorA: CGFloat = 1) {
//// General Declarations
let context = UIGraphicsGetCurrentContext()
//// Symbol Ring Drawing
let symbolRingRect = CGRectMake(frame.minX + floor(frame.width * 0.00000 + 0.5), frame.minY + floor(frame.height * 0.00000 + 0.5), floor(frame.width * 1.00000 + 0.5) - floor(frame.width * 0.00000 + 0.5), floor(frame.height * 1.00000 + 0.5) - floor(frame.height * 0.00000 + 0.5))
CGContextSaveGState(context)
UIRectClip(symbolRingRect)
CGContextTranslateCTM(context, symbolRingRect.origin.x, symbolRingRect.origin.y)
CGContextScaleCTM(context, symbolRingRect.size.width / 200, symbolRingRect.size.height / 200)
StyleKitDial.drawRing(value: value, colorR: colorR, colorG: colorG, colorB: colorB, colorA: colorA)
CGContextRestoreGState(context)
//// Symbol Data Drawing
let symbolDataRect = CGRectMake(frame.minX + floor(frame.width * -1.50000 + 0.5), frame.minY + floor(frame.height * 0.26000 + 0.5), floor(frame.width * 2.50000 + 0.5) - floor(frame.width * -1.50000 + 0.5), floor(frame.height * 0.74000 + 0.5) - floor(frame.height * 0.26000 + 0.5))
CGContextSaveGState(context)
UIRectClip(symbolDataRect)
CGContextTranslateCTM(context, symbolDataRect.origin.x, symbolDataRect.origin.y)
CGContextScaleCTM(context, symbolDataRect.size.width / 200, symbolDataRect.size.height / 24)
StyleKitDial.drawCenterText(label: data, colorR: colorR, colorG: colorG, colorB: colorB, colorA: colorA)
CGContextRestoreGState(context)
//// Symbol Unit Drawing
let symbolUnitRect = CGRectMake(frame.minX + floor(frame.width * 0.00000 + 0.5), frame.minY + floor(frame.height * 0.68000 + 0.5), floor(frame.width * 1.00000 + 0.5) - floor(frame.width * 0.00000 + 0.5), floor(frame.height * 0.80000 + 0.5) - floor(frame.height * 0.68000 + 0.5))
CGContextSaveGState(context)
UIRectClip(symbolUnitRect)
CGContextTranslateCTM(context, symbolUnitRect.origin.x, symbolUnitRect.origin.y)
CGContextScaleCTM(context, symbolUnitRect.size.width / 200, symbolUnitRect.size.height / 24)
StyleKitDial.drawCenterText(label: unit, colorR: colorR, colorG: colorG, colorB: colorB, colorA: colorA)
CGContextRestoreGState(context)
}
//// Generated Images
public class func imageOfRing(value value: CGFloat = 0.14, colorR: CGFloat = 1, colorG: CGFloat = 1, colorB: CGFloat = 1, colorA: CGFloat = 1) -> UIImage {
UIGraphicsBeginImageContextWithOptions(CGSizeMake(200, 200), false, 0)
StyleKitDial.drawRing(value: value, colorR: colorR, colorG: colorG, colorB: colorB, colorA: colorA)
let imageOfRing = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return imageOfRing
}
public class func imageOfDataRing(frame frame: CGRect = CGRectMake(0, 0, 200, 200), data: String = "35", unit: String = "μg/m3", value: CGFloat = 0.14, colorR: CGFloat = 1, colorG: CGFloat = 1, colorB: CGFloat = 1, colorA: CGFloat = 1) -> UIImage {
UIGraphicsBeginImageContextWithOptions(frame.size, false, 0)
StyleKitDial.drawDataRing(frame: CGRectMake(0, 0, frame.size.width, frame.size.height), data: data, unit: unit, value: value, colorR: colorR, colorG: colorG, colorB: colorB, colorA: colorA)
let imageOfDataRing = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return imageOfDataRing
}
}
| mit |
skedgo/tripkit-ios | Sources/TripKitUI/cards/TKUIHomeCard+MapManager.swift | 1 | 1554 | //
// TKUIHomeCard+MapManager.swift
// TripKitUI-iOS
//
// Created by Brian Huang on 26/8/20.
// Copyright © 2020 SkedGo Pty Ltd. All rights reserved.
//
import Foundation
import MapKit
import RxSwift
import RxCocoa
import TGCardViewController
import TripKit
/// This protocol defines the requirements for any map managers that want
/// to take control of the map in a `TKUIHomeCard`
@MainActor
public protocol TKUICompatibleHomeMapManager: TGCompatibleMapManager {
/// This returns an observable sequence that emits an element whenever an
/// action is triggered on the map
var nextFromMap: Observable<TKUIHomeCard.ComponentAction> { get }
/// This returns an observable sequence that emits an element whenever the
/// map's mapRect changes
var mapRect: Driver<MKMapRect> { get }
/// This provides you an opportunity to perform actions on the map when
/// a `TKUIHomeCard` appears
/// - Parameter appear: `true` when a home card just appeared
func onHomeCardAppearance(_ appear: Bool)
/// This is called when the user searches for and selects a city
func zoom(to city: TKRegion.City, animated: Bool)
/// This allows the map manager to respond to a `TKUIHomeCard`'s request
/// to select an annotation on the map
/// - Parameter annotation: The annotation to select on the map.
func select(_ annotation: MKAnnotation)
}
public extension TKUICompatibleHomeMapManager {
var nextFromMap: Observable<TKUIHomeCard.ComponentAction> { .empty() }
func onHomeCardAppearance(_ appear: Bool) { }
}
| apache-2.0 |
samodom/TestableUIKit | TestableUIKitTests/Tests/UIViewControllerIndirectSpiesTests.swift | 1 | 44118 | //
// UIViewControllerIndirectSpiesTests.swift
// TestableUIKit
//
// Created by Sam Odom on 2/25/17.
// Copyright © 2017 Swagger Soft. All rights reserved.
//
import XCTest
import SampleTypes
import TestableUIKit
class UIViewControllerIndirectSpiesTests: XCTestCase {
let plainController = PlainController()
let compliantController = CompliantController()
let subCompliantController = CompliantControllerSubclass()
let nonCompliantController = NonCompliantController()
var compliantControllers: [UIViewController]!
let sourceController = UIViewController()
let destinationController = UIViewController()
let duration = 0.111
let options = UIViewAnimationOptions.curveEaseIn
var animationsClosureInvoked = false
var animations: UIViewAnimations!
var completionHandlerInvoked = false
var completion: UIViewAnimationsCompletion!
override func setUp() {
super.setUp()
compliantControllers = [
plainController,
compliantController,
subCompliantController
]
animations = { [weak self] in
self?.animationsClosureInvoked = true
}
completion = { [weak self] _ in
self?.completionHandlerInvoked = true
}
}
// MARK: - `loadView`
func testLoadViewControllerForwardingBehavior() {
XCTAssertTrue(UIViewController.LoadViewSpyController.forwardsInvocations,
"Spies on `loadView` should always forward their method invocations")
}
func testLoadViewSpyWithCompliantControllers() {
subCompliantController.compliantControllerSubclassLoadViewCalled = false
[compliantController, subCompliantController].forEach { controller in
XCTAssertFalse(controller.superclassLoadViewCalled,
"By default the controller should not indicate having asked its superclass to load its view")
let spy = UIViewController.LoadViewSpyController.createSpy(on: controller)!
spy.beginSpying()
controller.loadView()
XCTAssertFalse(controller.superclassLoadViewCalled,
"A `UIViewController` subclass that does not call its superclass's implementation of `loadView` should not indicate having called that method when being spied upon")
if controller === subCompliantController {
XCTAssertTrue(subCompliantController.compliantControllerSubclassLoadViewCalled,
"The spy method should always forward the method call to the original implementation")
}
spy.endSpying()
XCTAssertFalse(controller.superclassLoadViewCalled,
"The flag should be cleared after spying is complete")
}
}
func testLoadViewSpyWithNonCompliantController() {
let spy = UIViewController.LoadViewSpyController.createSpy(on: nonCompliantController)!
spy.beginSpying()
nonCompliantController.loadView()
XCTAssertTrue(nonCompliantController.superclassLoadViewCalled,
"A `UIViewController` subclass that calls its superclass implementation of `loadView` should indicate having called that method when being spied upon")
spy.endSpying()
}
// MARK: - `viewDidLoad`
func testViewDidLoadControllerForwardingBehavior() {
XCTAssertTrue(UIViewController.ViewDidLoadSpyController.forwardsInvocations,
"Spies on `viewDidLoad` should always forward their method invocations")
}
func testViewDidLoadSpyWithCompliantControllers() {
subCompliantController.compliantControllerViewDidLoadCalled = false
compliantControllers.forEach { controller in
XCTAssertFalse(controller.superclassViewDidLoadCalled,
"By default the controller should not indicate having invoked its superclass's implementation of `viewDidLoad`")
let spy = UIViewController.ViewDidLoadSpyController.createSpy(on: controller)!
spy.beginSpying()
controller.viewDidLoad()
XCTAssertTrue(controller.superclassViewDidLoadCalled,
"A `UIViewController` subclass that calls its superclass's implementation of `viewDidLoad` should indicate having called that method when being spied upon")
if controller === subCompliantController {
XCTAssertTrue(subCompliantController.compliantControllerViewDidLoadCalled,
"The spy method should always forward the method call to the original implementation")
}
spy.endSpying()
XCTAssertFalse(controller.superclassViewDidLoadCalled,
"The flag should be cleared after spying is complete")
}
}
func testViewDidLoadSpyWithNonCompliantController() {
let spy = UIViewController.ViewDidLoadSpyController.createSpy(on: nonCompliantController)!
spy.beginSpying()
nonCompliantController.viewDidLoad()
XCTAssertFalse(nonCompliantController.superclassViewDidLoadCalled,
"A `UIViewController` subclass that does not call its superclass implementation of `viewDidLoad` should not indicate having called that method when being spied upon")
spy.endSpying()
}
// MARK: - `viewWillAppear(_:)`
func testViewWillAppearControllerForwardingBehavior() {
XCTAssertTrue(UIViewController.ViewWillAppearSpyController.forwardsInvocations,
"Spies on `viewWillAppear(_:)` should always forward their method invocations")
}
func testViewWillAppearSpyWithCompliantControllers() {
subCompliantController.compliantControllerViewWillAppearCalled = false
compliantControllers.forEach { controller in
XCTAssertFalse(controller.superclassViewWillAppearCalled,
"By default the controller should not indicate having invoked its superclass's implementation of `viewWillAppear(_:)`")
XCTAssertNil(controller.superclassViewWillAppearAnimated,
"By default the animation flag should be clear")
let spy = UIViewController.ViewWillAppearSpyController.createSpy(on: controller)!
spy.beginSpying()
controller.viewWillAppear(true)
XCTAssertTrue(controller.superclassViewWillAppearCalled,
"A `UIViewController` subclass that calls its superclass's implementation of `viewWillAppear(_:)` should indicate having called that method when being spied upon")
XCTAssertTrue(controller.superclassViewWillAppearAnimated!,
"The animation flag should be captured")
if controller === subCompliantController {
XCTAssertTrue(subCompliantController.compliantControllerViewWillAppearCalled,
"The spy method should always forward the method call to the original implementation")
}
spy.endSpying()
XCTAssertFalse(controller.superclassViewWillAppearCalled,
"The flag should be cleared after spying is complete")
XCTAssertNil(controller.superclassViewWillAppearAnimated,
"The flag should be cleared after spying is complete")
}
}
func testViewWillAppearSpyWithNonCompliantController() {
let spy = UIViewController.ViewWillAppearSpyController.createSpy(on: nonCompliantController)!
spy.beginSpying()
nonCompliantController.viewWillAppear(true)
XCTAssertFalse(nonCompliantController.superclassViewWillAppearCalled,
"A `UIViewController` subclass that does not call its superclass implementation of `viewWillAppear(_:)` should not indicate having called that method when being spied upon")
spy.endSpying()
}
// MARK: - `viewDidAppear(_:)`
func testViewDidAppearControllerForwardingBehavior() {
XCTAssertTrue(UIViewController.ViewDidAppearSpyController.forwardsInvocations,
"Spies on `viewDidAppear(_:)` should always forward their method invocations")
}
func testViewDidAppearSpyWithCompliantControllers() {
subCompliantController.compliantControllerViewDidAppearCalled = false
compliantControllers.forEach { controller in
XCTAssertFalse(controller.superclassViewDidAppearCalled,
"By default the controller should not indicate having invoked its superclass's implementation of `viewDidAppear(_:)`")
XCTAssertNil(controller.superclassViewDidAppearAnimated,
"By default the animation flag should be clear")
let spy = UIViewController.ViewDidAppearSpyController.createSpy(on: controller)!
spy.beginSpying()
controller.viewDidAppear(true)
XCTAssertTrue(controller.superclassViewDidAppearCalled,
"A `UIViewController` subclass that calls its superclass's implementation of `viewDidAppear(_:)` should indicate having called that method when being spied upon")
XCTAssertTrue(controller.superclassViewDidAppearAnimated!,
"The animation flag should be captured")
if controller === subCompliantController {
XCTAssertTrue(subCompliantController.compliantControllerViewDidAppearCalled,
"The spy method should always forward the method call to the original implementation")
}
spy.endSpying()
XCTAssertFalse(controller.superclassViewDidAppearCalled,
"The flag should be cleared after spying is complete")
XCTAssertNil(controller.superclassViewDidAppearAnimated,
"The flag should be cleared after spying is complete")
}
}
func testViewDidAppearSpyWithNonCompliantController() {
let spy = UIViewController.ViewDidAppearSpyController.createSpy(on: nonCompliantController)!
spy.beginSpying()
nonCompliantController.viewDidAppear(true)
XCTAssertFalse(nonCompliantController.superclassViewDidAppearCalled,
"A `UIViewController` subclass that does not call its superclass implementation of `viewDidAppear(_:)` should not indicate having called that method when being spied upon")
spy.endSpying()
}
// MARK: - `viewWillDisappear(_:)`
func testViewWillDisappearControllerForwardingBehavior() {
XCTAssertTrue(UIViewController.ViewWillDisappearSpyController.forwardsInvocations,
"Spies on `viewWillDisappear(_:)` should always forward their method invocations")
}
func testViewWillDisappearSpyWithCompliantControllers() {
subCompliantController.compliantControllerViewWillDisappearCalled = false
compliantControllers.forEach { controller in
XCTAssertFalse(controller.superclassViewWillDisappearCalled,
"By default the controller should not indicate having invoked its superclass's implementation of `viewWillDisappear(_:)`")
XCTAssertNil(controller.superclassViewWillDisappearAnimated,
"By default the animation flag should be clear")
let spy = UIViewController.ViewWillDisappearSpyController.createSpy(on: controller)!
spy.beginSpying()
controller.viewWillDisappear(true)
XCTAssertTrue(controller.superclassViewWillDisappearCalled,
"A `UIViewController` subclass that calls its superclass's implementation of `viewWillDisappear(_:)` should indicate having called that method when being spied upon")
XCTAssertTrue(controller.superclassViewWillDisappearAnimated!,
"The animation flag should be captured")
if controller === subCompliantController {
XCTAssertTrue(subCompliantController.compliantControllerViewWillDisappearCalled,
"The spy method should always forward the method call to the original implementation")
}
spy.endSpying()
XCTAssertFalse(controller.superclassViewWillDisappearCalled,
"The flag should be cleared after spying is complete")
XCTAssertNil(controller.superclassViewWillDisappearAnimated,
"The flag should be cleared after spying is complete")
}
}
func testViewWillDisappearSpyWithNonCompliantController() {
let spy = UIViewController.ViewWillDisappearSpyController.createSpy(on: nonCompliantController)!
spy.beginSpying()
nonCompliantController.viewWillDisappear(true)
XCTAssertFalse(nonCompliantController.superclassViewWillDisappearCalled,
"A `UIViewController` subclass that does not call its superclass implementation of `viewWillDisappear(_:)` should not indicate having called that method when being spied upon")
spy.endSpying()
}
// MARK: - `viewDidDisappear(_:)`
func testViewDidDisappearControllerForwardingBehavior() {
XCTAssertTrue(UIViewController.ViewDidDisappearSpyController.forwardsInvocations,
"Spies on `viewDidDisappear(_:)` should always forward their method invocations")
}
func testViewDidDisappearSpyWithCompliantControllers() {
subCompliantController.compliantControllerViewDidDisappearCalled = false
compliantControllers.forEach { controller in
XCTAssertFalse(controller.superclassViewDidDisappearCalled,
"By default the controller should not indicate having invoked its superclass's implementation of `viewDidDisappear(_:)`")
XCTAssertNil(controller.superclassViewDidDisappearAnimated,
"By default the animation flag should be clear")
let spy = UIViewController.ViewDidDisappearSpyController.createSpy(on: controller)!
spy.beginSpying()
controller.viewDidDisappear(true)
XCTAssertTrue(controller.superclassViewDidDisappearCalled,
"A `UIViewController` subclass that calls its superclass's implementation of `viewDidDisappear(_:)` should indicate having called that method when being spied upon")
XCTAssertTrue(controller.superclassViewDidDisappearAnimated!,
"The animation flag should be captured")
if controller === subCompliantController {
XCTAssertTrue(subCompliantController.compliantControllerViewDidDisappearCalled,
"The spy method should always forward the method call to the original implementation")
}
spy.endSpying()
XCTAssertFalse(controller.superclassViewDidDisappearCalled,
"The flag should be cleared after spying is complete")
XCTAssertNil(controller.superclassViewDidDisappearAnimated,
"The flag should be cleared after spying is complete")
}
}
func testViewDidDisappearSpyWithNonCompliantController() {
let spy = UIViewController.ViewDidDisappearSpyController.createSpy(on: nonCompliantController)!
spy.beginSpying()
nonCompliantController.viewDidDisappear(true)
XCTAssertFalse(nonCompliantController.superclassViewDidDisappearCalled,
"A `UIViewController` subclass that does not call its superclass implementation of `viewDidDisappear(_:)` should not indicate having called that method when being spied upon")
spy.endSpying()
}
// MARK: - `didReceiveMemoryWarning`
func testDidReceiveMemoryWarningControllerForwardingBehavior() {
XCTAssertTrue(UIViewController.DidReceiveMemoryWarningSpyController.forwardsInvocations,
"Spies on `didReceiveMemoryWarning` should always forward their method invocations")
}
func testDidReceiveMemoryWarningSpyWithCompliantControllers() {
subCompliantController.compliantControllerDidReceiveMemoryWarningCalled = false
compliantControllers.forEach { controller in
XCTAssertFalse(controller.superclassDidReceiveMemoryWarningCalled,
"By default the controller should not indicate having invoked its superclass's implementation of `didReceiveMemoryWarning`")
let spy = UIViewController.DidReceiveMemoryWarningSpyController.createSpy(on: controller)!
spy.beginSpying()
controller.didReceiveMemoryWarning()
XCTAssertTrue(controller.superclassDidReceiveMemoryWarningCalled,
"A `UIViewController` subclass that calls its superclass's implementation of `didReceiveMemoryWarning` should indicate having called that method when being spied upon")
if controller === subCompliantController {
XCTAssertTrue(subCompliantController.compliantControllerDidReceiveMemoryWarningCalled,
"The spy method should always forward the method call to the original implementation")
}
spy.endSpying()
XCTAssertFalse(controller.superclassDidReceiveMemoryWarningCalled,
"The flag should be cleared after spying is complete")
}
}
func testDidReceiveMemoryWarningSpyWithNonCompliantController() {
let spy = UIViewController.DidReceiveMemoryWarningSpyController.createSpy(on: nonCompliantController)!
spy.beginSpying()
nonCompliantController.didReceiveMemoryWarning()
XCTAssertFalse(nonCompliantController.superclassDidReceiveMemoryWarningCalled,
"A `UIViewController` subclass that does not call its superclass implementation of `didReceiveMemoryWarning` should not indicate having called that method when being spied upon")
spy.endSpying()
}
// MARK: - `updateViewConstraints`
func testUpdateViewConstraintsControllerForwardingBehavior() {
XCTAssertTrue(UIViewController.UpdateViewConstraintsSpyController.forwardsInvocations,
"Spies on `updateViewConstraints` should always forward their method invocations")
}
func testUpdateViewConstraintsSpyWithCompliantControllers() {
subCompliantController.compliantControllerUpdateViewConstraintsCalled = false
compliantControllers.forEach { controller in
XCTAssertFalse(controller.superclassUpdateViewConstraintsCalled,
"By default the controller should not indicate having invoked its superclass's implementation of `updateViewConstraints`")
let spy = UIViewController.UpdateViewConstraintsSpyController.createSpy(on: controller)!
spy.beginSpying()
controller.updateViewConstraints()
XCTAssertTrue(controller.superclassUpdateViewConstraintsCalled,
"A `UIViewController` subclass that calls its superclass's implementation of `updateViewConstraints` should indicate having called that method when being spied upon")
if controller === subCompliantController {
XCTAssertTrue(subCompliantController.compliantControllerUpdateViewConstraintsCalled,
"The spy method should always forward the method call to the original implementation")
}
spy.endSpying()
XCTAssertFalse(controller.superclassUpdateViewConstraintsCalled,
"The flag should be cleared after spying is complete")
}
}
func testUpdateViewConstraintsSpyWithNonCompliantController() {
let spy = UIViewController.UpdateViewConstraintsSpyController.createSpy(on: nonCompliantController)!
spy.beginSpying()
nonCompliantController.updateViewConstraints()
XCTAssertFalse(nonCompliantController.superclassUpdateViewConstraintsCalled,
"A `UIViewController` subclass that does not call its superclass implementation of `updateViewConstraints` should not indicate having called that method when being spied upon")
spy.endSpying()
}
// MARK: - `addChildViewController(_:)`
func testAddChildViewControllerControllerForwardingBehavior() {
XCTAssertTrue(UIViewController.AddChildViewControllerSpyController.forwardsInvocations,
"Spies on `addChildViewController(_:)` should always forward their method invocations")
}
func testAddChildViewControllerSpyWithCompliantControllers() {
compliantControllers.forEach { controller in
XCTAssertFalse(controller.superclassAddChildViewControllerCalled,
"By default the controller should not indicate having invoked its superclass's implementation of `addChildViewController(_:)`")
XCTAssertNil(controller.superclassAddChildViewControllerChild,
"By default the child controller should be clear")
let spy = UIViewController.AddChildViewControllerSpyController.createSpy(on: controller)!
spy.beginSpying()
let child = UIViewController()
controller.addChildViewController(child)
XCTAssertTrue(controller.superclassAddChildViewControllerCalled,
"A `UIViewController` subclass that calls its superclass's implementation of `addChildViewController(_:)` should indicate having called that method when being spied upon")
XCTAssertEqual(controller.superclassAddChildViewControllerChild!, child,
"The child controller should be captured")
XCTAssertTrue(controller.childViewControllers.contains(child),
"The spy method should always forward the method call to the original implementation")
spy.endSpying()
XCTAssertFalse(controller.superclassAddChildViewControllerCalled,
"The flag should be cleared after spying is complete")
XCTAssertNil(controller.superclassAddChildViewControllerChild,
"The child should be cleared after spying is complete")
}
}
func testAddChildViewControllerSpyWithNonCompliantController() {
let child = UIViewController()
let spy = UIViewController.AddChildViewControllerSpyController.createSpy(on: nonCompliantController)!
spy.beginSpying()
nonCompliantController.addChildViewController(child)
XCTAssertFalse(nonCompliantController.superclassAddChildViewControllerCalled,
"A `UIViewController` subclass that does not call its superclass implementation of `addChildViewController(_:)` should not indicate having called that method when being spied upon")
spy.endSpying()
}
// MARK: - `removeFromParentViewController`
func testRemoveFromParentViewControllerControllerForwardingBehavior() {
XCTAssertTrue(UIViewController.RemoveFromParentViewControllerSpyController.forwardsInvocations,
"Spies on `removeFromParentViewController` should always forward their method invocations")
}
func testRemoveFromParentViewControllerSpyWithCompliantControllers() {
compliantControllers.forEach { controller in
XCTAssertFalse(controller.superclassRemoveFromParentViewControllerCalled,
"By default the controller should not indicate having invoked its superclass's implementation of `removeFromParentViewController`")
let spy = UIViewController.RemoveFromParentViewControllerSpyController.createSpy(on: controller)!
spy.beginSpying()
let child = UIViewController()
controller.addChildViewController(child)
assert(controller.childViewControllers.contains(child))
controller.removeFromParentViewController()
XCTAssertTrue(controller.superclassRemoveFromParentViewControllerCalled,
"A `UIViewController` subclass that calls its superclass's implementation of `removeFromParentViewController` should indicate having called that method when being spied upon")
XCTAssertFalse(!controller.childViewControllers.contains(child),
"The spy method should always forward the method call to the original implementation")
spy.endSpying()
XCTAssertFalse(controller.superclassRemoveFromParentViewControllerCalled,
"The flag should be cleared after spying is complete")
}
}
func testRemoveFromParentViewControllerSpyWithNonCompliantController() {
let spy = UIViewController.RemoveFromParentViewControllerSpyController.createSpy(on: nonCompliantController)!
spy.beginSpying()
nonCompliantController.removeFromParentViewController()
XCTAssertFalse(nonCompliantController.superclassRemoveFromParentViewControllerCalled,
"A `UIViewController` subclass that does not call its superclass implementation of `removeFromParentViewController` should not indicate having called that method when being spied upon")
spy.endSpying()
}
// MARK: - `transition(from:to:duration:options:animations:completion:)`
func testTransitionSpyWithCompliantControllersWithoutForwarding() {
compliantControllers.forEach { controller in
controller.addChildViewController(sourceController)
controller.addChildViewController(destinationController)
XCTAssertFalse(controller.superclassTransitionCalled,
"By default the controller should not indicate having invoked its superclass's implementation of `transition(from:to:duration:options:animations:completion:)`")
XCTAssertNil(controller.superclassTransitionFromController,
"By default the source controller should be clear")
XCTAssertNil(controller.superclassTransitionToController,
"By default the destination controller should be clear")
XCTAssertNil(controller.superclassTransitionDuration,
"By default the duration should be clear")
XCTAssertNil(controller.superclassTransitionOptions,
"By default the options should be clear")
XCTAssertNil(controller.superclassTransitionAnimations,
"By default the animations closure should be clear")
XCTAssertNil(controller.superclassTransitionCompletion,
"By default the completion handler should be clear")
animationsClosureInvoked = false
completionHandlerInvoked = false
UIViewController.TransitionIndirectSpyController.forwardsInvocations = false
let spy = UIViewController.TransitionIndirectSpyController.createSpy(on: controller)!
spy.beginSpying()
controller.transition(
from: sourceController,
to: destinationController,
duration: duration,
options: options,
animations: animations,
completion: completion
)
XCTAssertTrue(controller.superclassTransitionCalled,
"A `UIViewController` subclass that calls its superclass's implementation of `transition(from:to:duration:options:animations:completion:)` should indicate having called that method when being spied upon")
XCTAssertEqual(controller.superclassTransitionFromController!, sourceController,
"The source controller should be captured")
XCTAssertEqual(controller.superclassTransitionToController!, destinationController,
"The destination controller should be captured")
XCTAssertEqual(controller.superclassTransitionDuration!, duration,
"The duration should be captured")
XCTAssertEqual(controller.superclassTransitionOptions!, options,
"The options should be captured")
XCTAssertFalse(animationsClosureInvoked,
"The spy method should not forward the method call to the original implementation")
let capturedAnimations = controller.superclassTransitionAnimations
capturedAnimations!()
XCTAssertTrue(animationsClosureInvoked, "The animations closure should be captured")
XCTAssertFalse(completionHandlerInvoked,
"The spy method should not forward the method call to the original implementation")
let capturedCompletion = controller.superclassTransitionCompletion
capturedCompletion!(true)
XCTAssertTrue(completionHandlerInvoked, "The completion handler should be captured")
spy.endSpying()
UIViewController.TransitionIndirectSpyController.forwardsInvocations = true
XCTAssertFalse(controller.superclassTransitionCalled,
"The flag should be cleared after spying is complete")
XCTAssertNil(controller.superclassTransitionFromController,
"The source controller should be cleared after spying is complete")
XCTAssertNil(controller.superclassTransitionToController,
"The destination controller should be cleared after spying is complete")
XCTAssertNil(controller.superclassTransitionDuration,
"The duration should be cleared after spying is complete")
XCTAssertNil(controller.superclassTransitionOptions,
"The options should be cleared after spying is complete")
XCTAssertNil(controller.superclassTransitionAnimations,
"The animations closure should be cleared after spying is complete")
XCTAssertNil(controller.superclassTransitionCompletion,
"The completion handler should be cleared after spying is complete")
}
}
func testTransitionSpyWithCompliantControllersWithForwarding() {
compliantControllers.forEach { controller in
controller.addChildViewController(sourceController)
controller.addChildViewController(destinationController)
XCTAssertFalse(controller.superclassTransitionCalled,
"By default the controller should not indicate having invoked its superclass's implementation of `transition(from:to:duration:options:animations:completion:)`")
XCTAssertNil(controller.superclassTransitionFromController,
"By default the source controller should be clear")
XCTAssertNil(controller.superclassTransitionToController,
"By default the destination controller should be clear")
XCTAssertNil(controller.superclassTransitionDuration,
"By default the duration should be clear")
XCTAssertNil(controller.superclassTransitionOptions,
"By default the options should be clear")
XCTAssertNil(controller.superclassTransitionAnimations,
"By default the animations closure should be clear")
XCTAssertNil(controller.superclassTransitionCompletion,
"By default the completion handler should be clear")
animationsClosureInvoked = false
completionHandlerInvoked = false
let spy = UIViewController.TransitionIndirectSpyController.createSpy(on: controller)!
spy.beginSpying()
controller.transition(
from: sourceController,
to: destinationController,
duration: duration,
options: options,
animations: animations,
completion: completion
)
XCTAssertTrue(controller.superclassTransitionCalled,
"A `UIViewController` subclass that calls its superclass's implementation of `transition(from:to:duration:options:animations:completion:)` should indicate having called that method when being spied upon")
XCTAssertEqual(controller.superclassTransitionFromController!, sourceController,
"The source controller should be captured")
XCTAssertEqual(controller.superclassTransitionToController!, destinationController,
"The destination controller should be captured")
XCTAssertEqual(controller.superclassTransitionDuration!, duration,
"The duration should be captured")
XCTAssertEqual(controller.superclassTransitionOptions!, options,
"The options should be captured")
XCTAssertNil(controller.superclassTransitionAnimations,
"The animations closure should not be captured when forwarding to the original implementation")
XCTAssertNil(controller.superclassTransitionCompletion,
"The completion handler should not be captured when forwarding to the original implementation")
if controller == subCompliantController {
XCTAssertTrue(subCompliantController.compliantControllerTransitionCalled,
"The spy method should not forward the method call to the original implementation")
}
spy.endSpying()
XCTAssertFalse(controller.superclassTransitionCalled,
"The flag should be cleared after spying is complete")
XCTAssertNil(controller.superclassTransitionFromController,
"The source controller should be cleared after spying is complete")
XCTAssertNil(controller.superclassTransitionToController,
"The destination controller should be cleared after spying is complete")
XCTAssertNil(controller.superclassTransitionDuration,
"The duration should be cleared after spying is complete")
XCTAssertNil(controller.superclassTransitionOptions,
"The options should be cleared after spying is complete")
}
}
func testTransitionSpyWithNonCompliantController() {
let spy = UIViewController.TransitionIndirectSpyController.createSpy(on: nonCompliantController)!
spy.beginSpying()
nonCompliantController.transition(
from: sourceController,
to: destinationController,
duration: duration,
options: options,
animations: animations,
completion: completion
)
XCTAssertFalse(nonCompliantController.superclassTransitionCalled,
"A `UIViewController` subclass that does not call its superclass implementation of `transition(from:to:duration:options:animations:completion:)` should not indicate having called that method when being spied upon")
spy.endSpying()
}
// MARK: - `setEditing(_:animated:)`
func testSetEditingControllerForwardingBehavior() {
XCTAssertTrue(UIViewController.SetEditingSpyController.forwardsInvocations,
"Spies on `setEditing(_:animated:)` should always forward their method invocations")
}
func testSetEditingSpyWithCompliantControllers() {
compliantControllers.forEach { controller in
XCTAssertFalse(controller.superclassSetEditingCalled,
"By default the controller should not indicate having invoked its superclass's implementation of `setEditing(_:animated:)`")
XCTAssertNil(controller.superclassSetEditingEditing,
"By default the editing flag should be clear")
XCTAssertNil(controller.superclassSetEditingAnimated,
"By default the animation flag should be clear")
let spy = UIViewController.SetEditingSpyController.createSpy(on: controller)!
spy.beginSpying()
controller.setEditing(true, animated: true)
XCTAssertTrue(controller.superclassSetEditingCalled,
"A `UIViewController` subclass that calls its superclass's implementation of `setEditing(_:animated:)` should indicate having called that method when being spied upon")
XCTAssertTrue(controller.superclassSetEditingEditing!,
"The editing flag should be captured")
XCTAssertTrue(controller.superclassSetEditingAnimated!,
"The animation flag should be captured")
XCTAssertTrue(controller.isEditing,
"The spy method should always forward the method call to the original implementation")
spy.endSpying()
XCTAssertFalse(controller.superclassSetEditingCalled,
"The flag should be cleared after spying is complete")
XCTAssertNil(controller.superclassSetEditingEditing,
"The editing flag should be cleared after spying is complete")
XCTAssertNil(controller.superclassSetEditingAnimated,
"The animation flag should be cleared after spying is complete")
controller.setEditing(false, animated: true)
}
}
func testSetEditingSpyWithNonCompliantController() {
let spy = UIViewController.SetEditingSpyController.createSpy(on: nonCompliantController)!
spy.beginSpying()
nonCompliantController.setEditing(true, animated: true)
XCTAssertFalse(nonCompliantController.superclassSetEditingCalled,
"A `UIViewController` subclass that does not call its superclass implementation of `setEditing(_:animated:)` should not indicate having called that method when being spied upon")
spy.endSpying()
nonCompliantController.setEditing(false, animated: true)
}
// MARK: - `encodeRestorableState(with:)`
func testEncodeRestorableStateControllerForwardingBehavior() {
XCTAssertTrue(UIViewController.EncodeRestorableStateSpyController.forwardsInvocations,
"Spies on `encodeRestorableState(with:)` should always forward their method invocations")
}
func testEncodeRestorableStateSpyWithCompliantControllers() {
subCompliantController.compliantControllerEncodeRestorableStateCalled = false
compliantControllers.forEach { controller in
XCTAssertFalse(controller.superclassEncodeRestorableStateCalled,
"By default the controller should not indicate having invoked its superclass's implementation of `encodeRestorableState(with:)`")
XCTAssertNil(controller.superclassEncodeRestorableStateCoder,
"By default the coder should be clear")
let spy = UIViewController.EncodeRestorableStateSpyController.createSpy(on: controller)!
spy.beginSpying()
let coder = NSCoder()
controller.encodeRestorableState(with: coder)
XCTAssertTrue(controller.superclassEncodeRestorableStateCalled,
"A `UIViewController` subclass that calls its superclass's implementation of `encodeRestorableState(with:)` should indicate having called that method when being spied upon")
XCTAssertEqual(controller.superclassEncodeRestorableStateCoder!, coder,
"The coder should be captured")
if controller == subCompliantController {
XCTAssertTrue(subCompliantController.compliantControllerEncodeRestorableStateCalled,
"The spy method should always forward the method call to the original implementation")
}
spy.endSpying()
XCTAssertFalse(controller.superclassEncodeRestorableStateCalled,
"The flag should be cleared after spying is complete")
XCTAssertNil(controller.superclassEncodeRestorableStateCoder,
"The coder should be cleared after spying is complete")
}
}
func testEncodeRestorableStateSpyWithNonCompliantController() {
let spy = UIViewController.EncodeRestorableStateSpyController.createSpy(on: nonCompliantController)!
spy.beginSpying()
nonCompliantController.encodeRestorableState(with: NSCoder())
XCTAssertFalse(nonCompliantController.superclassEncodeRestorableStateCalled,
"A `UIViewController` subclass that does not call its superclass implementation of `encodeRestorableState(with:)` should not indicate having called that method when being spied upon")
spy.endSpying()
}
// MARK: - `decodeRestorableState(with:)`
func testDecodeRestorableStateControllerForwardingBehavior() {
XCTAssertTrue(UIViewController.DecodeRestorableStateSpyController.forwardsInvocations,
"Spies on `decodeRestorableState(with:)` should always forward their method invocations")
}
func testDecodeRestorableStateSpyWithCompliantControllers() {
subCompliantController.compliantControllerDecodeRestorableStateCalled = false
compliantControllers.forEach { controller in
XCTAssertFalse(controller.superclassDecodeRestorableStateCalled,
"By default the controller should not indicate having invoked its superclass's implementation of `decodeRestorableState(with:)`")
XCTAssertNil(controller.superclassDecodeRestorableStateCoder,
"By default the coder should be clear")
let spy = UIViewController.DecodeRestorableStateSpyController.createSpy(on: controller)!
spy.beginSpying()
let coder = NSCoder()
controller.decodeRestorableState(with: coder)
XCTAssertTrue(controller.superclassDecodeRestorableStateCalled,
"A `UIViewController` subclass that calls its superclass's implementation of `decodeRestorableState(with:)` should indicate having called that method when being spied upon")
XCTAssertEqual(controller.superclassDecodeRestorableStateCoder!, coder,
"The coder should be captured")
if controller == subCompliantController {
XCTAssertTrue(subCompliantController.compliantControllerDecodeRestorableStateCalled,
"The spy method should always forward the method call to the original implementation")
}
spy.endSpying()
XCTAssertFalse(controller.superclassDecodeRestorableStateCalled,
"The flag should be cleared after spying is complete")
XCTAssertNil(controller.superclassDecodeRestorableStateCoder,
"The coder should be cleared after spying is complete")
}
}
func testDecodeRestorableStateSpyWithNonCompliantController() {
let spy = UIViewController.DecodeRestorableStateSpyController.createSpy(on: nonCompliantController)!
spy.beginSpying()
nonCompliantController.decodeRestorableState(with: NSCoder())
XCTAssertFalse(nonCompliantController.superclassDecodeRestorableStateCalled,
"A `UIViewController` subclass that does not call its superclass implementation of `decodeRestorableState(with:)` should not indicate having called that method when being spied upon")
spy.endSpying()
}
}
| mit |
szysz3/ios-timetracker | TimeTracker/TaskCell.swift | 1 | 922 | //
// TaskCell.swift
// TimeTracker
//
// Created by Michał Szyszka on 21.09.2016.
// Copyright © 2016 Michał Szyszka. All rights reserved.
//
import UIKit
class TaskCell: UITableViewCell {
//MARK: Outlets
@IBOutlet weak var activityInidcator: UIActivityIndicatorView!
@IBOutlet weak var lblTitle: UILabel!
@IBOutlet weak var imgColor: UIView!
@IBOutlet weak var overlay: UIView!
@IBOutlet weak var lblDuration: UILabel!
@IBOutlet weak var activityIndicatorOverlay: UIView!
//MARK: Fields
static let tag = "TaskCell"
//MARK: Functions
override func awakeFromNib() {
super.awakeFromNib()
initialize()
}
private func initialize(){
imgColor.layer.cornerRadius = UIConsts.cornerRadius
imgColor.layer.borderWidth = UIConsts.borderWidth
imgColor.layer.borderColor = UIColor.lightGray.cgColor
}
}
| mit |
Davidde94/StemCode_iOS | StemCode/StemKit/AppVersion.swift | 1 | 2640 | //
// AppVersion.swift
// StemCode
//
// Created by David Evans on 07/09/2018.
// Copyright © 2018 BlackPoint LTD. All rights reserved.
//
import Foundation
public struct AppVersion: Codable {
public let majorVersion: UInt
public let minorVersion: UInt
public let patchVersion: UInt
public var isOutdated: Bool {
return self < AppVersion.current
}
public static let current: AppVersion = {
guard
let infoDictionary = Bundle.main.infoDictionary,
let versionString = infoDictionary["CFBundleShortVersionString"] as? String
else {
return AppVersion(1, 0, 0)
}
return AppVersion(versionString) ?? AppVersion(1, 0, 0)
}()
public init?(_ string: String) {
let components = string.split(separator: Character("."))
guard components.count == 3 else {
return nil
}
guard
let majorVersion = UInt(components[0]),
let minorVersion = UInt(components[1]),
let patchVersion = UInt(components[2])
else {
return nil
}
self.majorVersion = majorVersion
self.minorVersion = minorVersion
self.patchVersion = patchVersion
}
public init(_ majorVersion: UInt, _ minorVersion: UInt, _ patchVersion: UInt) {
self.init(majorVersion: majorVersion, minorVersion: minorVersion, patchVersion: patchVersion)
}
public init(majorVersion: UInt, minorVersion: UInt, patchVersion: UInt) {
self.majorVersion = majorVersion
self.minorVersion = minorVersion
self.patchVersion = patchVersion
}
}
extension AppVersion: Equatable {
}
extension AppVersion: Comparable {
public static func < (lhs: AppVersion, rhs: AppVersion) -> Bool {
if lhs.majorVersion < rhs.majorVersion {
return true
} else if lhs.minorVersion < rhs.minorVersion {
return true
} else if lhs.patchVersion < rhs.patchVersion {
return true
}
return false
}
public static func > (lhs: AppVersion, rhs: AppVersion) -> Bool {
if lhs.majorVersion > rhs.majorVersion {
return true
} else if lhs.minorVersion > rhs.minorVersion {
return true
} else if lhs.patchVersion > rhs.patchVersion {
return true
}
return false
}
public static func >= (lhs: AppVersion, rhs: AppVersion) -> Bool {
if lhs.majorVersion < rhs.majorVersion {
return false
} else if lhs.minorVersion < rhs.minorVersion {
return false
} else if lhs.patchVersion < rhs.patchVersion {
return false
}
return true
}
public static func <= (lhs: AppVersion, rhs: AppVersion) -> Bool {
if lhs.majorVersion > rhs.majorVersion {
return false
} else if lhs.minorVersion > rhs.minorVersion {
return false
} else if lhs.patchVersion > rhs.patchVersion {
return false
}
return true
}
}
| mit |
azac/swift-faker | Faker/ViewController.swift | 1 | 1449 |
import UIKit
class ViewController: UIViewController {
@IBOutlet var avatarImage: UIImageView!
@IBOutlet var label: UILabel!
@IBAction func klik(sender: AnyObject) {
var fakeGuy = Faker()
label.text=fakeGuy.fullDescription
avatarImage.image = UIImage(named:"")
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
let imgURL = NSURL.URLWithString(fakeGuy.photo);
var request: NSURLRequest = NSURLRequest(URL: imgURL)
var urlConnection: NSURLConnection = NSURLConnection(request: request, delegate: self)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response: NSURLResponse!,data: NSData!,error: NSError!) -> Void in
if !error? {
var downloadedImage = UIImage(data: data)
self.avatarImage.image = downloadedImage
}
else {
println("Error: \(error.localizedDescription)")
}
})
})
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| apache-2.0 |
Lomotif/swipe-navigation | swipe-navigationUITests/swipe_navigationUITests.swift | 1 | 1269 | //
// swipe_navigationUITests.swift
// swipe-navigationUITests
//
// Created by Donald Lee on 28/6/16.
// Copyright © 2016 Donald Lee. All rights reserved.
//
import XCTest
class swipe_navigationUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| mit |
Driftt/drift-sdk-ios | Drift/Birdsong/Presence.swift | 2 | 3858 | //
// Presence.swift
// Pods
//
// Created by Simon Manning on 6/07/2016.
//
//
import Foundation
internal final class Presence {
// MARK: - Convenience typealiases
public typealias PresenceState = [String: [Meta]]
public typealias Diff = [String: [String: Any]]
public typealias Meta = [String: Any]
// MARK: - Properties
fileprivate(set) public var state: PresenceState
// MARK: - Callbacks
public var onJoin: ((_ id: String, _ meta: Meta) -> ())?
public var onLeave: ((_ id: String, _ meta: Meta) -> ())?
public var onStateChange: ((_ state: PresenceState) -> ())?
// MARK: - Initialisation
init(state: PresenceState = Presence.PresenceState()) {
self.state = state
}
// MARK: - Syncing
func sync(_ diff: Response) {
// Initial state event
if diff.event == "presence_state" {
diff.payload.forEach{ id, entry in
if let entry = entry as? [String: Any] {
if let metas = entry["metas"] as? [Meta] {
state[id] = metas
}
}
}
}
else if diff.event == "presence_diff" {
if let leaves = diff.payload["leaves"] as? Diff {
syncLeaves(leaves)
}
if let joins = diff.payload["joins"] as? Diff {
syncJoins(joins)
}
}
onStateChange?(state)
}
func syncLeaves(_ diff: Diff) {
defer {
diff.forEach { id, entry in
if let metas = entry["metas"] as? [Meta] {
metas.forEach { onLeave?(id, $0) }
}
}
}
for (id, entry) in diff where state[id] != nil {
guard var existing = state[id] else {
continue
}
// If there's only one entry for the id, just remove it.
if existing.count == 1 {
state.removeValue(forKey: id)
continue
}
// Otherwise, we need to find the phx_ref keys to delete.
let metas = entry["metas"] as? [Meta]
if let refsToDelete = metas?.compactMap({ $0["phx_ref"] as? String }) {
existing = existing.filter {
if let phxRef = $0["phx_ref"] as? String {
return !refsToDelete.contains(phxRef)
}
return true
}
state[id] = existing
}
}
}
func syncJoins(_ diff: Diff) {
diff.forEach { id, entry in
if let metas = entry["metas"] as? [Meta] {
if var existing = state[id] {
existing += metas
}
else {
state[id] = metas
}
metas.forEach { onJoin?(id, $0) }
}
}
}
// MARK: - Presence access convenience
func metas(id: String) -> [Meta]? {
return state[id]
}
func firstMeta(id: String) -> Meta? {
return state[id]?.first
}
func firstMetas() -> [String: Meta] {
var result = [String: Meta]()
state.forEach { id, metas in
result[id] = metas.first
}
return result
}
func firstMetaValue<T>(id: String, key: String) -> T? {
guard let meta = state[id]?.first, let value = meta[key] as? T else {
return nil
}
return value
}
func firstMetaValues<T>(key: String) -> [T] {
var result = [T]()
state.forEach { id, metas in
if let meta = metas.first, let value = meta[key] as? T {
result.append(value)
}
}
return result
}
}
| mit |
AutomationStation/BouncerBuddy | BouncerBuddyV6/BouncerBuddy/MainViewController.swift | 1 | 1369 | //
// ViewController.swift
// BouncerBuddy
//
// Created by Sha Wu on 16/3/2.
// Copyright © 2016年 Sheryl Hong. All rights reserved.
//
import UIKit
class MainViewController: UIViewController {
@IBOutlet weak var usernameLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidAppear(animated: Bool) {
// comment out the next lines if you want to go to homepage without sign in
let prefs:NSUserDefaults = NSUserDefaults.standardUserDefaults()
let isLoggedIn:Int = prefs.integerForKey("ISLOGGEDIN") as Int
if (isLoggedIn != 1){
self.performSegueWithIdentifier("SignInView", sender: self)
}else{
self.usernameLabel.text = prefs.valueForKey("USERNAME") as? String
}
}
@IBAction func LogoutTapped(sender: AnyObject) {
let appDomain = NSBundle.mainBundle().bundleIdentifier
NSUserDefaults.standardUserDefaults().removePersistentDomainForName(appDomain!)
self.performSegueWithIdentifier("SignInView", sender: self)
}
}
| apache-2.0 |
nathawes/swift | test/IDE/print_synthesized_extensions.swift | 6 | 12899 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module-path %t/print_synthesized_extensions.swiftmodule -emit-module-doc -emit-module-doc-path %t/print_synthesized_extensions.swiftdoc %s
// RUN: %target-swift-ide-test -print-module -annotate-print -synthesize-extension -print-interface -no-empty-line-between-members -module-to-print=print_synthesized_extensions -I %t -source-filename=%s > %t.syn.txt
// RUN: %FileCheck %s -check-prefix=CHECK1 < %t.syn.txt
// RUN: %FileCheck %s -check-prefix=CHECK2 < %t.syn.txt
// RUN: %FileCheck %s -check-prefix=CHECK3 < %t.syn.txt
// RUN: %FileCheck %s -check-prefix=CHECK4 < %t.syn.txt
// RUN: %FileCheck %s -check-prefix=CHECK5 < %t.syn.txt
// RUN: %FileCheck %s -check-prefix=CHECK6 < %t.syn.txt
// RUN: %FileCheck %s -check-prefix=CHECK7 < %t.syn.txt
// RUN: %FileCheck %s -check-prefix=CHECK8 < %t.syn.txt
// RUN: %FileCheck %s -check-prefix=CHECK9 < %t.syn.txt
// RUN: %FileCheck %s -check-prefix=CHECK10 < %t.syn.txt
// RUN: %FileCheck %s -check-prefix=CHECK11 < %t.syn.txt
// RUN: %FileCheck %s -check-prefix=CHECK12 < %t.syn.txt
// RUN: %FileCheck %s -check-prefix=CHECK13 < %t.syn.txt
// RUN: %FileCheck %s -check-prefix=CHECK14 < %t.syn.txt
public protocol P1 {
associatedtype T1
associatedtype T2
func f1(t : T1) -> T1
func f2(t : T2) -> T2
}
public extension P1 where T1 == Int {
func p1IntFunc(i : Int) -> Int {return 0}
}
public extension P1 where T1 : P3 {
func p3Func(i : Int) -> Int {return 0}
}
public protocol P2 {
associatedtype P2T1
}
public extension P2 where P2T1 : P2{
public func p2member() {}
}
public protocol P3 {}
public extension P1 where T1 : P2 {
public func ef1(t : T1) {}
public func ef2(t : T2) {}
}
public extension P1 where T1 == P3, T2 : P3 {
public func ef3(t : T1) {}
public func ef4(t : T1) {}
}
public extension P1 where T2 : P3 {
public func ef5(t : T2) {}
}
public struct S2 {}
public struct S1<T> : P1, P2 {
public typealias T1 = T
public typealias T2 = S2
public typealias P2T1 = T
public func f1(t : T1) -> T1 {
return t
}
public func f2(t : T2) -> T2 {
return t
}
}
public struct S3<T> : P1 {
public typealias T1 = (T, T)
public typealias T2 = (T, T)
public func f1(t : T1) -> T1 {
return t
}
public func f2(t : T2) -> T2 {
return t
}
}
public struct S4<T> : P1 {
public typealias T1 = Int
public typealias T2 = Int
public func f1(t : T1) -> T1 {
return t
}
public func f2(t : T2) -> T2 {
return t
}
}
public struct S5 : P3 {}
public struct S6<T> : P1 {
public typealias T1 = S5
public typealias T2 = S5
public func f1(t : T1) -> T1 {
return t
}
public func f2(t : T2) -> T2 {
return t
}
}
public extension S6 {
public func f3() {}
}
public struct S7 {
public struct S8 : P1 {
public typealias T1 = S5
public typealias T2 = S5
public func f1(t : T1) -> T1 {
return t
}
public func f2(t : T2) -> T2 {
return t
}
}
}
public extension P1 where T1 == S9<Int> {
public func S9IntFunc() {}
}
public struct S9<T> : P3 {}
public struct S10 : P1 {
public typealias T1 = S9<Int>
public typealias T2 = S9<Int>
public func f1(t : T1) -> T1 {
return t
}
public func f2(t : T2) -> T2 {
return t
}
}
public protocol P4 {}
/// Extension on P4Func1
public extension P4 {
func P4Func1() {}
}
/// Extension on P4Func2
public extension P4 {
func P4Func2() {}
}
public struct S11 : P4 {}
public extension S6 {
public func fromActualExtension() {}
}
public protocol P5 {
associatedtype T1
/// This is picked
func foo1()
}
public extension P5 {
/// This is not picked
public func foo1() {}
}
public extension P5 where T1 == Int {
/// This is picked
public func foo2() {}
}
public extension P5 {
/// This is not picked
public func foo2() {}
}
public extension P5 {
/// This is not picked
public func foo3() {}
}
public extension P5 where T1 : Comparable{
/// This is picked
public func foo3() {}
}
public extension P5 where T1 : Comparable {
/// This is picked
public func foo4() {}
}
public extension P5 where T1 : AnyObject {
/// This should not crash
public func foo5() {}
}
public extension P5 {
/// This is not picked
public func foo4() {}
}
public struct S12 : P5{
public typealias T1 = Int
public func foo1() {}
}
public protocol P6 {
func foo1()
func foo2()
}
public extension P6 {
public func foo1() {}
}
public protocol P7 {
associatedtype T1
func f1(t: T1)
}
public extension P7 {
public func nomergeFunc(t: T1) -> T1 { return t }
public func f1(t: T1) -> T1 { return t }
}
public struct S13 {}
extension S13 : P5 {
public typealias T1 = Int
public func foo1() {}
}
// CHECK1: <synthesized>extension <ref:Struct>S1</ref> where T : <ref:Protocol>P2</ref> {
// CHECK1-NEXT: <decl:Func>public func <loc>p2member()</loc></decl>
// CHECK1-NEXT: <decl:Func>public func <loc>ef1(<decl:Param>t: T</decl>)</loc></decl>
// CHECK1-NEXT: <decl:Func>public func <loc>ef2(<decl:Param>t: <ref:Struct>S2</ref></decl>)</loc></decl>
// CHECK1-NEXT: }</synthesized>
// CHECK2: <synthesized>extension <ref:Struct>S1</ref> where T : <ref:Protocol>P3</ref> {
// CHECK2-NEXT: <decl:Func>public func <loc>p3Func(<decl:Param>i: <ref:Struct>Int</ref></decl>)</loc> -> <ref:Struct>Int</ref></decl>
// CHECK2-NEXT: }</synthesized>
// CHECK3: <synthesized>extension <ref:Struct>S1</ref> where T == <ref:Struct>Int</ref> {
// CHECK3-NEXT: <decl:Func>public func <loc>p1IntFunc(<decl:Param>i: <ref:Struct>Int</ref></decl>)</loc> -> <ref:Struct>Int</ref></decl>
// CHECK3-NEXT: }</synthesized>
// CHECK4: <synthesized>extension <ref:Struct>S1</ref> where T == <ref:Struct>S9</ref><<ref:Struct>Int</ref>> {
// CHECK4-NEXT: <decl:Func>public func <loc>S9IntFunc()</loc></decl>
// CHECK4-NEXT: }</synthesized>
// CHECK5: <decl:Struct>public struct <loc>S10</loc> : <ref:module>print_synthesized_extensions</ref>.<ref:Protocol>P1</ref> {
// CHECK5-NEXT: <decl:TypeAlias>public typealias <loc>T1</loc> = <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S9</ref><<ref:Struct>Int</ref>></decl>
// CHECK5-NEXT: <decl:TypeAlias>public typealias <loc>T2</loc> = <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S9</ref><<ref:Struct>Int</ref>></decl>
// CHECK5-NEXT: <decl:Func>public func <loc>f1(<decl:Param>t: <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S10</ref>.<ref:TypeAlias>T1</ref></decl>)</loc> -> <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S10</ref>.<ref:TypeAlias>T1</ref></decl>
// CHECK5-NEXT: <decl:Func>public func <loc>f2(<decl:Param>t: <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S10</ref>.<ref:TypeAlias>T2</ref></decl>)</loc> -> <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S10</ref>.<ref:TypeAlias>T2</ref></decl></decl>
// CHECK5-NEXT: <decl:Func>public func <loc>p3Func(<decl:Param>i: <ref:Struct>Int</ref></decl>)</loc> -> <ref:Struct>Int</ref></decl>
// CHECK5-NEXT: <decl:Func>public func <loc>ef5(<decl:Param>t: <ref:Struct>S9</ref><<ref:Struct>Int</ref>></decl>)</loc></decl>
// CHECK5-NEXT: <decl:Func>public func <loc>S9IntFunc()</loc></decl>
// CHECK5-NEXT: }</synthesized>
// CHECK6: <synthesized>/// Extension on P4Func1
// CHECK6-NEXT: extension <ref:Struct>S11</ref> {
// CHECK6-NEXT: <decl:Func>public func <loc>P4Func1()</loc></decl>
// CHECK6-NEXT: }</synthesized>
// CHECK7: <synthesized>/// Extension on P4Func2
// CHECK7-NEXT: extension <ref:Struct>S11</ref> {
// CHECK7-NEXT: <decl:Func>public func <loc>P4Func2()</loc></decl>
// CHECK7-NEXT: }</synthesized>
// CHECK8: <decl:Struct>public struct <loc>S4<<decl:GenericTypeParam>T</decl>></loc> : <ref:module>print_synthesized_extensions</ref>.<ref:Protocol>P1</ref> {
// CHECK8-NEXT: <decl:TypeAlias>public typealias <loc>T1</loc> = <ref:Struct>Int</ref></decl>
// CHECK8-NEXT: <decl:TypeAlias>public typealias <loc>T2</loc> = <ref:Struct>Int</ref></decl>
// CHECK8-NEXT: <decl:Func>public func <loc>f1(<decl:Param>t: <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S4</ref><T>.<ref:TypeAlias>T1</ref></decl>)</loc> -> <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S4</ref><T>.<ref:TypeAlias>T1</ref></decl>
// CHECK8-NEXT: <decl:Func>public func <loc>f2(<decl:Param>t: <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S4</ref><T>.<ref:TypeAlias>T2</ref></decl>)</loc> -> <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S4</ref><T>.<ref:TypeAlias>T2</ref></decl></decl>
// CHECK8-NEXT: <decl:Func>public func <loc>p1IntFunc(<decl:Param>i: <ref:Struct>Int</ref></decl>)</loc> -> <ref:Struct>Int</ref></decl>
// CHECK8-NEXT: }</synthesized>
// CHECK9: <decl:Struct>public struct <loc>S6<<decl:GenericTypeParam>T</decl>></loc> : <ref:module>print_synthesized_extensions</ref>.<ref:Protocol>P1</ref> {
// CHECK9-NEXT: <decl:TypeAlias>public typealias <loc>T1</loc> = <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S5</ref></decl>
// CHECK9-NEXT: <decl:TypeAlias>public typealias <loc>T2</loc> = <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S5</ref></decl>
// CHECK9-NEXT: <decl:Func>public func <loc>f1(<decl:Param>t: <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S6</ref><T>.<ref:TypeAlias>T1</ref></decl>)</loc> -> <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S6</ref><T>.<ref:TypeAlias>T1</ref></decl>
// CHECK9-NEXT: <decl:Func>public func <loc>f2(<decl:Param>t: <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S6</ref><T>.<ref:TypeAlias>T2</ref></decl>)</loc> -> <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S6</ref><T>.<ref:TypeAlias>T2</ref></decl></decl>
// CHECK9-NEXT: <decl:Extension><decl:Func>public func <loc>f3()</loc></decl></decl>
// CHECK9-NEXT: <decl:Extension><decl:Func>public func <loc>fromActualExtension()</loc></decl></decl>
// CHECK9-NEXT: <decl:Func>public func <loc>p3Func(<decl:Param>i: <ref:Struct>Int</ref></decl>)</loc> -> <ref:Struct>Int</ref></decl>
// CHECK9-NEXT: <decl:Func>public func <loc>ef5(<decl:Param>t: <ref:Struct>S5</ref></decl>)</loc></decl>
// CHECK9-NEXT: }</synthesized>
// CHECK10: <synthesized>extension <ref:Struct>S7</ref>.<ref:Struct>S8</ref> {
// CHECK10-NEXT: <decl:Func>public func <loc>p3Func(<decl:Param>i: <ref:Struct>Int</ref></decl>)</loc> -> <ref:Struct>Int</ref></decl>
// CHECK10-NEXT: <decl:Func>public func <loc>ef5(<decl:Param>t: <ref:Struct>S5</ref></decl>)</loc></decl>
// CHECK10-NEXT: }</synthesized>
// CHECK11: <decl:Struct>public struct <loc>S12</loc> : <ref:module>print_synthesized_extensions</ref>.<ref:Protocol>P5</ref> {
// CHECK11-NEXT: <decl:TypeAlias>public typealias <loc>T1</loc> = <ref:Struct>Int</ref></decl>
// CHECK11-NEXT: <decl:Func>/// This is picked
// CHECK11-NEXT: public func <loc>foo1()</loc></decl></decl>
// CHECK11-NEXT: <decl:Func>/// This is picked
// CHECK11-NEXT: public func <loc>foo2()</loc></decl>
// CHECK11-NEXT: <decl:Func>/// This is picked
// CHECK11-NEXT: public func <loc>foo3()</loc></decl>
// CHECK11-NEXT: <decl:Func>/// This is picked
// CHECK11-NEXT: public func <loc>foo4()</loc></decl>
// CHECK11-NEXT: <decl:Func>/// This should not crash
// CHECK11-NEXT: public func <loc>foo5()</loc></decl>
// CHECK11-NEXT: }</synthesized>
// CHECK12: <decl:Protocol>public protocol <loc>P6</loc> {
// CHECK12-NEXT: <decl:Func(HasDefault)>func <loc>foo1()</loc></decl>
// CHECK12-NEXT: <decl:Func>func <loc>foo2()</loc></decl>
// CHECK12-NEXT: }</decl>
// CHECK13: <decl:Protocol>public protocol <loc>P7</loc> {
// CHECK13-NEXT: <decl:AssociatedType>associatedtype <loc>T1</loc></decl>
// CHECK13-NEXT: <decl:Func(HasDefault)>func <loc>f1(<decl:Param>t: <ref:GenericTypeParam>Self</ref>.T1</decl>)</loc></decl>
// CHECK13-NEXT: }</decl>
// CHECK13: <decl:Extension>extension <loc><ref:Protocol>P7</ref></loc> {
// CHECK13-NEXT: <decl:Func>public func <loc>nomergeFunc(<decl:Param>t: <ref:GenericTypeParam>Self</ref>.T1</decl>)</loc> -> <ref:GenericTypeParam>Self</ref>.T1</decl>
// CHECK13-NEXT: <decl:Func>public func <loc>f1(<decl:Param>t: <ref:GenericTypeParam>Self</ref>.T1</decl>)</loc> -> <ref:GenericTypeParam>Self</ref>.T1</decl>
// CHECK13-NEXT: }</decl>
// CHECK14: <decl:Struct>public struct <loc>S13</loc> {</decl>
// CHECK14-NEXT: <decl:Func>/// This is picked
// CHECK14-NEXT: public func <loc>foo2()</loc></decl>
// CHECK14-NEXT: <decl:Func>/// This is picked
// CHECK14-NEXT: public func <loc>foo3()</loc></decl>
// CHECK14-NEXT: <decl:Func>/// This is picked
// CHECK14-NEXT: public func <loc>foo4()</loc></decl>
// CHECK14-NEXT: <decl:Func>/// This should not crash
// CHECK14-NEXT: public func <loc>foo5()</loc></decl>
// CHECK14-NEXT: }</synthesized>
| apache-2.0 |
roambotics/swift | test/SILOptimizer/static_arrays.swift | 2 | 9332 | // RUN: %target-swift-frontend -primary-file %s -O -sil-verify-all -Xllvm -sil-disable-pass=FunctionSignatureOpts -module-name=test -emit-sil | %FileCheck %s
// RUN: %target-swift-frontend -primary-file %s -O -sil-verify-all -Xllvm -sil-disable-pass=FunctionSignatureOpts -module-name=test -emit-ir | %FileCheck %s -check-prefix=CHECK-LLVM
// Also do an end-to-end test to check all components, including IRGen.
// RUN: %empty-directory(%t)
// RUN: %target-build-swift -O -Xllvm -sil-disable-pass=FunctionSignatureOpts -module-name=test %s -o %t/a.out
// RUN: %target-run %t/a.out | %FileCheck %s -check-prefix=CHECK-OUTPUT
// REQUIRES: executable_test,swift_stdlib_no_asserts,optimized_stdlib
// REQUIRES: CPU=arm64 || CPU=x86_64
// REQUIRES: swift_in_compiler
// Check if the optimizer is able to convert array literals to statically initialized arrays.
// CHECK-LABEL: sil_global @$s4test4FStrV10globalFuncyS2icvpZ : $@callee_guaranteed (Int) -> Int = {
// CHECK: %0 = function_ref @$s4test3fooyS2iF : $@convention(thin) (Int) -> Int
// CHECK-NEXT: %initval = thin_to_thick_function %0
// CHECK-NEXT: }
// CHECK-LABEL: outlined variable #0 of arrayLookup(_:)
// CHECK-NEXT: sil_global private @{{.*}}arrayLookup{{.*}} = {
// CHECK-DAG: integer_literal $Builtin.Int{{[0-9]+}}, 10
// CHECK-DAG: integer_literal $Builtin.Int{{[0-9]+}}, 11
// CHECK-DAG: integer_literal $Builtin.Int{{[0-9]+}}, 12
// CHECK: object {{.*}} ({{[^,]*}}, [tail_elems] {{[^,]*}}, {{[^,]*}}, {{[^,]*}})
// CHECK-NEXT: }
// CHECK-LABEL: outlined variable #0 of returnArray()
// CHECK-NEXT: sil_global private @{{.*}}returnArray{{.*}} = {
// CHECK-DAG: integer_literal $Builtin.Int{{[0-9]+}}, 20
// CHECK-DAG: integer_literal $Builtin.Int{{[0-9]+}}, 21
// CHECK: object {{.*}} ({{[^,]*}}, [tail_elems] {{[^,]*}}, {{[^,]*}})
// CHECK-NEXT: }
// CHECK-LABEL: outlined variable #0 of returnStaticStringArray()
// CHECK-NEXT: sil_global private @{{.*}}returnStaticStringArray{{.*}} = {
// CHECK-DAG: string_literal utf8 "a"
// CHECK-DAG: string_literal utf8 "b"
// CHECK: object {{.*}} ({{[^,]*}}, [tail_elems] {{[^,]*}}, {{[^,]*}})
// CHECK-NEXT: }
// CHECK-LABEL: outlined variable #0 of passArray()
// CHECK-NEXT: sil_global private @{{.*}}passArray{{.*}} = {
// CHECK-DAG: integer_literal $Builtin.Int{{[0-9]+}}, 27
// CHECK-DAG: integer_literal $Builtin.Int{{[0-9]+}}, 28
// CHECK: object {{.*}} ({{[^,]*}}, [tail_elems] {{[^,]*}}, {{[^,]*}})
// CHECK-NEXT: }
// CHECK-LABEL: outlined variable #1 of passArray()
// CHECK-NEXT: sil_global private @{{.*}}passArray{{.*}} = {
// CHECK: integer_literal $Builtin.Int{{[0-9]+}}, 29
// CHECK: object {{.*}} ({{[^,]*}}, [tail_elems] {{[^,]*}})
// CHECK-NEXT: }
// CHECK-LABEL: outlined variable #0 of storeArray()
// CHECK-NEXT: sil_global private @{{.*}}storeArray{{.*}} = {
// CHECK-DAG: integer_literal $Builtin.Int{{[0-9]+}}, 227
// CHECK-DAG: integer_literal $Builtin.Int{{[0-9]+}}, 228
// CHECK: object {{.*}} ({{[^,]*}}, [tail_elems] {{[^,]*}}, {{[^,]*}})
// CHECK-NEXT: }
// CHECK-LABEL: outlined variable #0 of functionArray()
// CHECK-NEXT: sil_global private @{{.*functionArray.*}} = {
// CHECK: function_ref
// CHECK: thin_to_thick_function
// CHECK: convert_function
// CHECK: function_ref
// CHECK: thin_to_thick_function
// CHECK: convert_function
// CHECK: object {{.*}} ({{[^,]*}}, [tail_elems]
// CHECK-NEXT: }
// CHECK-LABEL: outlined variable #0 of returnDictionary()
// CHECK-NEXT: sil_global private @{{.*}}returnDictionary{{.*}} = {
// CHECK-DAG: integer_literal $Builtin.Int{{[0-9]+}}, 5
// CHECK-DAG: integer_literal $Builtin.Int{{[0-9]+}}, 4
// CHECK-DAG: integer_literal $Builtin.Int{{[0-9]+}}, 2
// CHECK-DAG: integer_literal $Builtin.Int{{[0-9]+}}, 1
// CHECK-DAG: integer_literal $Builtin.Int{{[0-9]+}}, 6
// CHECK-DAG: integer_literal $Builtin.Int{{[0-9]+}}, 3
// CHECK: object {{.*}} ({{[^,]*}}, [tail_elems]
// CHECK-NEXT: }
// CHECK-LABEL: outlined variable #0 of returnStringDictionary()
// CHECK-NEXT: sil_global private @{{.*}}returnStringDictionary{{.*}} = {
// CHECK: object {{.*}} ({{[^,]*}}, [tail_elems]
// CHECK-NEXT: }
// CHECK-LABEL: sil_global private @{{.*}}main{{.*}} = {
// CHECK-DAG: integer_literal $Builtin.Int{{[0-9]+}}, 100
// CHECK-DAG: integer_literal $Builtin.Int{{[0-9]+}}, 101
// CHECK-DAG: integer_literal $Builtin.Int{{[0-9]+}}, 102
// CHECK: object {{.*}} ({{[^,]*}}, [tail_elems] {{[^,]*}}, {{[^,]*}}, {{[^,]*}})
// CHECK-NEXT: }
// CHECK-LABEL: sil {{.*}}@main
// CHECK: global_value @{{.*}}main{{.*}}
// CHECK: return
public let globalVariable = [ 100, 101, 102 ]
// CHECK-LABEL: sil [noinline] @$s4test11arrayLookupyS2iF
// CHECK: global_value @$s4test11arrayLookupyS2iFTv_
// CHECK-NOT: retain
// CHECK-NOT: release
// CHECK: } // end sil function '$s4test11arrayLookupyS2iF'
// CHECK-LLVM-LABEL: define {{.*}} @"$s4test11arrayLookupyS2iF"
// CHECK-LLVM-NOT: call
// CHECK-LLVM: [[E:%[0-9]+]] = getelementptr {{.*}} @"$s4test11arrayLookupyS2iFTv_"
// CHECK-LLVM-NEXT: [[L:%[0-9]+]] = load {{.*}} [[E]]
// CHECK-LLVM-NEXT: ret {{.*}} [[L]]
// CHECK-LLVM: }
@inline(never)
public func arrayLookup(_ i: Int) -> Int {
let lookupTable = [10, 11, 12]
return lookupTable[i]
}
// CHECK-LABEL: sil {{.*}}returnArray{{.*}} : $@convention(thin) () -> @owned Array<Int> {
// CHECK: global_value @{{.*}}returnArray{{.*}}
// CHECK: return
@inline(never)
public func returnArray() -> [Int] {
return [20, 21]
}
// CHECK-LABEL: sil {{.*}}returnStaticStringArray{{.*}} : $@convention(thin) () -> @owned Array<StaticString> {
// CHECK: global_value @{{.*}}returnStaticStringArray{{.*}}
// CHECK: return
@inline(never)
public func returnStaticStringArray() -> [StaticString] {
return ["a", "b"]
}
public var gg: [Int]?
@inline(never)
public func receiveArray(_ a: [Int]) {
gg = a
}
// CHECK-LABEL: sil {{.*}}passArray{{.*}} : $@convention(thin) () -> () {
// CHECK: global_value @{{.*}}passArray{{.*}}
// CHECK: global_value @{{.*}}passArray{{.*}}
// CHECK: return
@inline(never)
public func passArray() {
receiveArray([27, 28])
receiveArray([29])
}
// CHECK-LABEL: sil {{.*}}storeArray{{.*}} : $@convention(thin) () -> () {
// CHECK: global_value @{{.*}}storeArray{{.*}}
// CHECK: return
@inline(never)
public func storeArray() {
gg = [227, 228]
}
struct Empty { }
// CHECK-LABEL: sil {{.*}}arrayWithEmptyElements{{.*}} : $@convention(thin) () -> @owned Array<Empty> {
func arrayWithEmptyElements() -> [Empty] {
// CHECK: global_value @{{.*}}arrayWithEmptyElements{{.*}}
// CHECK: return
return [Empty()]
}
// CHECK-LABEL: sil {{.*}}returnDictionary{{.*}} : $@convention(thin) () -> @owned Dictionary<Int, Int> {
// CHECK: global_value @{{.*}}returnDictionary{{.*}}
// CHECK: return
@inline(never)
public func returnDictionary() -> [Int:Int] {
return [1:2, 3:4, 5:6]
}
// CHECK-LABEL: sil {{.*}}returnStringDictionary{{.*}} : $@convention(thin) () -> @owned Dictionary<String, String> {
// CHECK: global_value @{{.*}}returnStringDictionary{{.*}}
// CHECK: return
@inline(never)
public func returnStringDictionary() -> [String:String] {
return ["1":"2", "3":"4", "5":"6"]
}
func foo(_ i: Int) -> Int { return i }
// CHECK-LABEL: sil {{.*functionArray.*}} : $@convention(thin) () -> @owned Array<(Int) -> Int> {
// CHECK: global_value @{{.*functionArray.*}}
// CHECK: } // end sil function '{{.*functionArray.*}}'
@inline(never)
func functionArray() -> [(Int) -> Int] {
func bar(_ i: Int) -> Int { return i + 1 }
return [foo, bar, { $0 + 10 }]
}
public struct FStr {
// Not an array, but also tested here.
public static var globalFunc = foo
}
// CHECK-OUTPUT: [100, 101, 102]
print(globalVariable)
// CHECK-OUTPUT-NEXT: 11
print(arrayLookup(1))
// CHECK-OUTPUT-NEXT: [20, 21]
print(returnArray())
// CHECK-OUTPUT-NEXT: ["a", "b"]
print(returnStaticStringArray())
passArray()
// CHECK-OUTPUT-NEXT: [29]
print(gg!)
storeArray()
// CHECK-OUTPUT-NEXT: [227, 228]
print(gg!)
// CHECK-OUTPUT-NEXT: 311
print(functionArray()[0](100) + functionArray()[1](100) + functionArray()[2](100))
// CHECK-OUTPUT-NEXT: 27
print(FStr.globalFunc(27))
let dict = returnDictionary()
// CHECK-OUTPUT-NEXT: dict 3: 2, 4, 6
print("dict \(dict.count): \(dict[1]!), \(dict[3]!), \(dict[5]!)")
let sdict = returnStringDictionary()
// CHECK-OUTPUT-NEXT: sdict 3: 2, 4, 6
print("sdict \(sdict.count): \(sdict["1"]!), \(sdict["3"]!), \(sdict["5"]!)")
public class SwiftClass {}
@inline(never)
func takeUnsafePointer(ptr : UnsafePointer<SwiftClass>, len: Int) {
print(ptr, len) // Use the arguments somehow so they don't get removed.
}
// This should be a single basic block, and the array should end up being stack
// allocated.
//
// CHECK-LABEL: sil @{{.*}}passArrayOfClasses
// CHECK: bb0(%0 : $SwiftClass, %1 : $SwiftClass, %2 : $SwiftClass):
// CHECK-NOT: bb1(
// CHECK: alloc_ref{{(_dynamic)?}} {{.*}}[tail_elems $SwiftClass *
// CHECK-NOT: bb1(
// CHECK: return
public func passArrayOfClasses(a: SwiftClass, b: SwiftClass, c: SwiftClass) {
let arr = [a, b, c]
takeUnsafePointer(ptr: arr, len: arr.count)
}
| apache-2.0 |
MooYoo/UINavigationBarStyle | Example/UINavigationBarStyle/TableViewController.swift | 1 | 2270 | //
// TableViewController.swift
// UINavigationBarStyle
//
// Created by Alan on 17/4/6.
// Copyright © 2017年 CocoaPods. All rights reserved.
//
import UIKit
import UINavigationBarExtension
var aindex: Int = 1
class TableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
automaticallyAdjustsScrollViewInsets = false
navigationBarBackgroundAlpha = 0
navigationBarTintColor = UIColor.red
statusBarStyle = .lightContent
navigationBarTitleTextAttributes = [NSForegroundColorAttributeName: UIColor.white]
statusBarStyle = .lightContent
navigationBarShadowImageHidden = true
title = String(describing: aindex)
aindex = aindex + 1
}
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
let alpha = min(max(scrollView.contentOffset.y / 80, 0), 1)
navigationBarBackgroundAlpha = alpha
if alpha > 0.9 {
navigationBarTintColor = nil
statusBarStyle = .default
navigationBarTitleTextAttributes = nil
} else {
navigationBarTintColor = UIColor.red
statusBarStyle = .lightContent
navigationBarTitleTextAttributes = [NSForegroundColorAttributeName: UIColor.white]
}
}
@IBAction func clickBarButtonItem(_ sender: AnyObject) {
let controller = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "TableViewController")
navigationController?.pushViewController(controller, animated: true)
}
@IBAction func clickPopToButton(_ sender: AnyObject) {
let count = navigationController!.viewControllers.count - 3
guard count < navigationController!.viewControllers.count else {return}
let controller = navigationController!.viewControllers[count]
navigationController?.popToViewController(controller, animated: true)
}
@IBAction func clickPopRootButton(_ sender: AnyObject) {
navigationController?.popToRootViewController(animated: true)
}
// override func preferredStatusBarStyle() -> UIStatusBarStyle {
// return statusBarStyle
// }
}
| mit |
Colrying/DouYuZB | DouYuZB/DouYuZB/Classes/Home/Model/RecommendCycleModel.swift | 1 | 789 | //
// RecommendCycleModel.swift
// DouYuZB
//
// Created by 皇坤鹏 on 17/4/19.
// Copyright © 2017年 皇坤鹏. All rights reserved.
//
import UIKit
class RecommendCycleModel: NSObject {
/// 标题
var title : String = ""
/// 图片url
var pic_url : String = ""
/// 对应的房间信息
var room : [NSString : NSObject]? {
didSet {
guard let room = room else {return}
anchor = AnchorModel.init(dic: room as [String : NSObject])
}
}
/// 房间信息对应的模型
var anchor : AnchorModel?
init(dic : [NSString : NSObject]) {
super.init()
setValuesForKeys(dic as [String : Any])
}
override func setValue(_ value: Any?, forUndefinedKey key: String) {}
}
| mit |
kamleshgk/iOSStarterTemplate | foodcolors/ThirdParty/Dodo/DodoDistrib.swift | 1 | 80269 | //
// Dodo
//
// A message bar for iOS.
//
// https://github.com/marketplacer/Dodo
//
// This file was automatically generated by combining multiple Swift source files.
//
// ----------------------------
//
// DodoAnimation.swift
//
// ----------------------------
import UIKit
/// A closure that is called for animation of the bar when it is being shown or hidden.
public typealias DodoAnimation = (UIView, _ duration: TimeInterval?,
_ locationTop: Bool, _ completed: @escaping DodoAnimationCompleted)->()
/// A closure that is called by the animator when animation has finished.
public typealias DodoAnimationCompleted = ()->()
// ----------------------------
//
// DodoAnimations.swift
//
// ----------------------------
import UIKit
/// Collection of animation effects use for showing and hiding the notification bar.
public enum DodoAnimations: String {
/// Animation that fades the bar in/out.
case fade = "Fade"
/// Used for showing notification without animation.
case noAnimation = "No animation"
/// Animation that rotates the bar around X axis in perspective with spring effect.
case rotate = "Rotate"
/// Animation that swipes the bar to/from the left with fade effect.
case slideLeft = "Slide left"
/// Animation that swipes the bar to/from the right with fade effect.
case slideRight = "Slide right"
/// Animation that slides the bar in/out vertically.
case slideVertically = "Slide vertically"
/**
Get animation function that can be used for showing notification bar.
- returns: Animation function.
*/
public var show: DodoAnimation {
switch self {
case .fade:
return DodoAnimationsShow.fade
case .noAnimation:
return DodoAnimations.doNoAnimation
case .rotate:
return DodoAnimationsShow.rotate
case .slideLeft:
return DodoAnimationsShow.slideLeft
case .slideRight:
return DodoAnimationsShow.slideRight
case .slideVertically:
return DodoAnimationsShow.slideVertically
}
}
/**
Get animation function that can be used for hiding notification bar.
- returns: Animation function.
*/
public var hide: DodoAnimation {
switch self {
case .fade:
return DodoAnimationsHide.fade
case .noAnimation:
return DodoAnimations.doNoAnimation
case .rotate:
return DodoAnimationsHide.rotate
case .slideLeft:
return DodoAnimationsHide.slideLeft
case .slideRight:
return DodoAnimationsHide.slideRight
case .slideVertically:
return DodoAnimationsHide.slideVertically
}
}
/**
A empty animator which is used when no animation is supplied.
It simply calls the completion closure.
- parameter view: View supplied for animation.
- parameter completed: A closure to be called after animation completes.
*/
static func doNoAnimation(_ view: UIView, duration: TimeInterval?, locationTop: Bool,
completed: DodoAnimationCompleted) {
completed()
}
/// Helper function for fading the view in and out.
static func doFade(_ duration: TimeInterval?, showView: Bool, view: UIView,
completed: @escaping DodoAnimationCompleted) {
let actualDuration = duration ?? 0.5
let startAlpha: CGFloat = showView ? 0 : 1
let endAlpha: CGFloat = showView ? 1 : 0
view.alpha = startAlpha
UIView.animate(withDuration: actualDuration,
animations: {
view.alpha = endAlpha
},
completion: { finished in
completed()
}
)
}
/// Helper function for sliding the view vertically
static func doSlideVertically(_ duration: TimeInterval?, showView: Bool, view: UIView,
locationTop: Bool, completed: @escaping DodoAnimationCompleted) {
let actualDuration = duration ?? 0.5
view.layoutIfNeeded()
var distance: CGFloat = 0
if locationTop {
distance = view.frame.height + view.frame.origin.y
} else {
distance = UIScreen.main.bounds.height - view.frame.origin.y
}
let transform = CGAffineTransform(translationX: 0, y: locationTop ? -distance : distance)
let start: CGAffineTransform = showView ? transform : CGAffineTransform.identity
let end: CGAffineTransform = showView ? CGAffineTransform.identity : transform
view.transform = start
UIView.animate(withDuration: actualDuration,
delay: 0,
usingSpringWithDamping: 1,
initialSpringVelocity: 1,
options: [],
animations: {
view.transform = end
},
completion: { finished in
completed()
}
)
}
static weak var timer: MoaTimer?
/// Animation that rotates the bar around X axis in perspective with spring effect.
static func doRotate(_ duration: TimeInterval?, showView: Bool, view: UIView, completed: @escaping DodoAnimationCompleted) {
let actualDuration = duration ?? 2.0
let start: Double = showView ? Double(M_PI / 2) : 0
let end: Double = showView ? 0 : Double(M_PI / 2)
let damping = showView ? 0.85 : 3
let myCALayer = view.layer
var transform = CATransform3DIdentity
transform.m34 = -1.0/200.0
myCALayer.transform = CATransform3DRotate(transform, CGFloat(end), 1, 0, 0)
myCALayer.zPosition = 300
SpringAnimationCALayer.animate(myCALayer,
keypath: "transform.rotation.x",
duration: actualDuration,
usingSpringWithDamping: damping,
initialSpringVelocity: 1,
fromValue: start,
toValue: end,
onFinished: showView ? completed : nil)
// Hide the bar prematurely for better looks
timer?.cancel()
if !showView {
timer = MoaTimer.runAfter(0.3) { timer in
completed()
}
}
}
/// Animation that swipes the bar to the right with fade-out effect.
static func doSlide(_ duration: TimeInterval?, right: Bool, showView: Bool,
view: UIView, completed: @escaping DodoAnimationCompleted) {
let actualDuration = duration ?? 0.4
let distance = UIScreen.main.bounds.width
let transform = CGAffineTransform(translationX: right ? distance : -distance, y: 0)
let start: CGAffineTransform = showView ? transform : CGAffineTransform.identity
let end: CGAffineTransform = showView ? CGAffineTransform.identity : transform
let alphaStart: CGFloat = showView ? 0.2 : 1
let alphaEnd: CGFloat = showView ? 1 : 0.2
view.transform = start
view.alpha = alphaStart
UIView.animate(withDuration: actualDuration,
delay: 0,
options: UIViewAnimationOptions.curveEaseOut,
animations: {
view.transform = end
view.alpha = alphaEnd
},
completion: { finished in
completed()
}
)
}
}
// ----------------------------
//
// DodoAnimationsHide.swift
//
// ----------------------------
import UIKit
/// Collection of animation effects use for hiding the notification bar.
struct DodoAnimationsHide {
/**
Animation that rotates the bar around X axis in perspective with spring effect.
- parameter view: View supplied for animation.
- parameter completed: A closure to be called after animation completes.
*/
static func rotate(_ view: UIView, duration: TimeInterval?, locationTop: Bool,
completed: @escaping DodoAnimationCompleted) {
DodoAnimations.doRotate(duration, showView: false, view: view, completed: completed)
}
/**
Animation that swipes the bar from to the left with fade-in effect.
- parameter view: View supplied for animation.
- parameter completed: A closure to be called after animation completes.
*/
static func slideLeft(_ view: UIView, duration: TimeInterval?, locationTop: Bool,
completed: @escaping DodoAnimationCompleted) {
DodoAnimations.doSlide(duration, right: false, showView: false, view: view, completed: completed)
}
/**
Animation that swipes the bar to the right with fade-out effect.
- parameter view: View supplied for animation.
- parameter completed: A closure to be called after animation completes.
*/
static func slideRight(_ view: UIView, duration: TimeInterval?, locationTop: Bool,
completed: @escaping DodoAnimationCompleted) {
DodoAnimations.doSlide(duration, right: true, showView: false, view: view, completed: completed)
}
/**
Animation that fades the bar out.
- parameter view: View supplied for animation.
- parameter completed: A closure to be called after animation completes.
*/
static func fade(_ view: UIView, duration: TimeInterval?, locationTop: Bool,
completed: @escaping DodoAnimationCompleted) {
DodoAnimations.doFade(duration, showView: false, view: view, completed: completed)
}
/**
Animation that slides the bar vertically out of view.
- parameter view: View supplied for animation.
- parameter completed: A closure to be called after animation completes.
*/
static func slideVertically(_ view: UIView, duration: TimeInterval?, locationTop: Bool,
completed: @escaping DodoAnimationCompleted) {
DodoAnimations.doSlideVertically(duration, showView: false, view: view,
locationTop: locationTop, completed: completed)
}
}
// ----------------------------
//
// DodoAnimationsShow.swift
//
// ----------------------------
import UIKit
/// Collection of animation effects use for showing the notification bar.
struct DodoAnimationsShow {
/**
Animation that rotates the bar around X axis in perspective with spring effect.
- parameter view: View supplied for animation.
- parameter completed: A closure to be called after animation completes.
*/
static func rotate(_ view: UIView, duration: TimeInterval?,
locationTop: Bool, completed: @escaping DodoAnimationCompleted) {
DodoAnimations.doRotate(duration, showView: true, view: view, completed: completed)
}
/**
Animation that swipes the bar from the left with fade-in effect.
- parameter view: View supplied for animation.
- parameter completed: A closure to be called after animation completes.
*/
static func slideLeft(_ view: UIView, duration: TimeInterval?, locationTop: Bool,
completed: @escaping DodoAnimationCompleted) {
DodoAnimations.doSlide(duration, right: false, showView: true, view: view, completed: completed)
}
/**
Animation that swipes the bar from the right with fade-in effect.
- parameter view: View supplied for animation.
- parameter completed: A closure to be called after animation completes.
*/
static func slideRight(_ view: UIView, duration: TimeInterval?, locationTop: Bool,
completed: @escaping DodoAnimationCompleted) {
DodoAnimations.doSlide(duration, right: true, showView: true, view: view, completed: completed)
}
/**
Animation that fades the bar in.
- parameter view: View supplied for animation.
- parameter completed: A closure to be called after animation completes.
*/
static func fade(_ view: UIView, duration: TimeInterval?, locationTop: Bool,
completed: @escaping DodoAnimationCompleted) {
DodoAnimations.doFade(duration, showView: true, view: view, completed: completed)
}
/**
Animation that slides the bar in/out vertically.
- parameter view: View supplied for animation.
- parameter completed: A closure to be called after animation completes.
*/
static func slideVertically(_ view: UIView, duration: TimeInterval?, locationTop: Bool,
completed: @escaping DodoAnimationCompleted) {
DodoAnimations.doSlideVertically(duration, showView: true, view: view,
locationTop: locationTop,completed: completed)
}
}
// ----------------------------
//
// DodoButtonOnTap.swift
//
// ----------------------------
/// A closure that is called when a bar button is tapped
public typealias DodoButtonOnTap = ()->()
// ----------------------------
//
// DodoButtonView.swift
//
// ----------------------------
import UIKit
class DodoButtonView: UIImageView {
private let style: DodoButtonStyle
weak var delegate: DodoButtonViewDelegate?
var onTap: OnTap?
init(style: DodoButtonStyle) {
self.style = style
super.init(frame: CGRect())
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// Create button views for given button styles.
static func createMany(_ styles: [DodoButtonStyle]) -> [DodoButtonView] {
if !haveButtons(styles) { return [] }
return styles.map { style in
let view = DodoButtonView(style: style)
view.setup()
return view
}
}
static func haveButtons(_ styles: [DodoButtonStyle]) -> Bool {
let hasImages = styles.filter({ $0.image != nil }).count > 0
let hasIcons = styles.filter({ $0.icon != nil }).count > 0
return hasImages || hasIcons
}
func doLayout(onLeftSide: Bool) {
precondition(delegate != nil, "Button view delegate can not be nil")
translatesAutoresizingMaskIntoConstraints = false
// Set button's size
TegAutolayoutConstraints.width(self, value: style.size.width)
TegAutolayoutConstraints.height(self, value: style.size.height)
if let superview = superview {
let alignAttribute = onLeftSide ? NSLayoutAttribute.left : NSLayoutAttribute.right
let marginHorizontal = onLeftSide ? style.horizontalMarginToBar : -style.horizontalMarginToBar
// Align the button to the left/right of the view
TegAutolayoutConstraints.alignSameAttributes(self, toItem: superview,
constraintContainer: superview,
attribute: alignAttribute, margin: marginHorizontal)
// Center the button verticaly
TegAutolayoutConstraints.centerY(self, viewTwo: superview, constraintContainer: superview)
}
}
func setup() {
if let image = DodoButtonView.image(style) { applyStyle(image) }
setupTap()
}
/// Increase the hitsize of the image view if it's less than 44px for easier tapping.
override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
let oprimizedBounds = DodoTouchTarget.optimize(bounds)
return oprimizedBounds.contains(point)
}
/// Returns the image supplied by user or create one from the icon
class func image(_ style: DodoButtonStyle) -> UIImage? {
if style.image != nil {
return style.image
}
if let icon = style.icon {
let bundle = Bundle(for: self)
let imageName = icon.rawValue
return UIImage(named: imageName, in: bundle, compatibleWith: nil)
}
return nil
}
private func applyStyle(_ imageIn: UIImage) {
var imageToShow = imageIn
if let tintColorToShow = style.tintColor {
// Replace image colors with the specified tint color
imageToShow = imageToShow.withRenderingMode(UIImageRenderingMode.alwaysTemplate)
tintColor = tintColorToShow
}
layer.minificationFilter = kCAFilterTrilinear // make the image crisp
image = imageToShow
contentMode = UIViewContentMode.scaleAspectFit
// Make button accessible
if let accessibilityLabelToShow = style.accessibilityLabel {
isAccessibilityElement = true
accessibilityLabel = accessibilityLabelToShow
accessibilityTraits = UIAccessibilityTraitButton
}
}
private func setupTap() {
onTap = OnTap(view: self, gesture: UITapGestureRecognizer()) { [weak self] in
self?.didTap()
}
}
private func didTap() {
self.delegate?.buttonDelegateDidTap(self.style)
style.onTap?()
}
}
// ----------------------------
//
// DodoButtonViewDelegate.swift
//
// ----------------------------
protocol DodoButtonViewDelegate: class {
func buttonDelegateDidTap(_ buttonStyle: DodoButtonStyle)
}
// ----------------------------
//
// Dodo.swift
//
// ----------------------------
import UIKit
/**
Main class that coordinates the process of showing and hiding of the message bar.
Instance of this class is created automatically in the `dodo` property of any UIView instance.
It is not expected to be instantiated manually anywhere except unit tests.
For example:
let view = UIView()
view.dodo.info("Horses are blue?")
*/
final class Dodo: DodoInterface, DodoButtonViewDelegate {
private weak var superview: UIView!
private var hideTimer: MoaTimer?
// Gesture handler that hides the bar when it is tapped
var onTap: OnTap?
/// Specify optional layout guide for positioning the bar view.
var topLayoutGuide: UILayoutSupport?
/// Specify optional layout guide for positioning the bar view.
var bottomLayoutGuide: UILayoutSupport?
/// Defines styles for the bar.
var style = DodoStyle(parentStyle: DodoPresets.defaultPreset.style)
/// Creates an instance of Dodo class
init(superview: UIView) {
self.superview = superview
DodoKeyboardListener.startListening()
}
/// Changes the style preset for the bar widget.
var preset: DodoPresets = DodoPresets.defaultPreset {
didSet {
if preset != oldValue {
style.parent = preset.style
}
}
}
/**
Shows the message bar with *.success* preset. It can be used to indicate successful completion of an operation.
- parameter message: The text message to be shown.
*/
func success(_ message: String) {
preset = .success
show(message)
}
/**
Shows the message bar with *.Info* preset. It can be used for showing information messages that have neutral emotional value.
- parameter message: The text message to be shown.
*/
func info(_ message: String) {
preset = .info
show(message)
}
/**
Shows the message bar with *.warning* preset. It can be used for for showing warning messages.
- parameter message: The text message to be shown.
*/
func warning(_ message: String) {
preset = .warning
show(message)
}
/**
Shows the message bar with *.warning* preset. It can be used for showing critical error messages
- parameter message: The text message to be shown.
*/
func error(_ message: String) {
preset = .error
show(message)
}
/**
Shows the message bar. Set `preset` property to change the appearance of the message bar, or use the shortcut methods: `success`, `info`, `warning` and `error`.
- parameter message: The text message to be shown.
*/
func show(_ message: String) {
removeExistingBars()
setupHideTimer()
let bar = DodoToolbar(witStyle: style)
setupHideOnTap(bar)
bar.layoutGuide = style.bar.locationTop ? topLayoutGuide : bottomLayoutGuide
bar.buttonViewDelegate = self
bar.show(inSuperview: superview, withMessage: message)
}
/// Hide the message bar if it's currently shown.
func hide() {
hideTimer?.cancel()
toolbar?.hide({})
}
func listenForKeyboard() {
}
private var toolbar: DodoToolbar? {
get {
return superview.subviews.filter { $0 is DodoToolbar }.map { $0 as! DodoToolbar }.first
}
}
private func removeExistingBars() {
for view in superview.subviews {
if let existingToolbar = view as? DodoToolbar {
existingToolbar.removeFromSuperview()
}
}
}
// MARK: - Hiding after delay
private func setupHideTimer() {
hideTimer?.cancel()
if style.bar.hideAfterDelaySeconds > 0 {
hideTimer = MoaTimer.runAfter(style.bar.hideAfterDelaySeconds) { [weak self] timer in
DispatchQueue.main.async {
self?.hide()
}
}
}
}
// MARK: - Reacting to tap
private func setupHideOnTap(_ toolbar: UIView) {
onTap = OnTap(view: toolbar, gesture: UITapGestureRecognizer()) { [weak self] in
self?.didTapTheBar()
}
}
/// The bar has been tapped
private func didTapTheBar() {
style.bar.onTap?()
if style.bar.hideOnTap {
hide()
}
}
// MARK: - DodoButtonViewDelegate
func buttonDelegateDidTap(_ buttonStyle: DodoButtonStyle) {
if buttonStyle.hideOnTap {
hide()
}
}
}
// ----------------------------
//
// DodoBarOnTap.swift
//
// ----------------------------
/// A closure that is called when a bar is tapped
public typealias DodoBarOnTap = ()->()
// ----------------------------
//
// DodoInterface.swift
//
// ----------------------------
import UIKit
/**
Coordinates the process of showing and hiding of the message bar.
The instance is created automatically in the `dodo` property of any UIView instance.
It is not expected to be instantiated manually anywhere except unit tests.
For example:
let view = UIView()
view.dodo.info("Horses are blue?")
*/
public protocol DodoInterface: class {
/// Specify optional layout guide for positioning the bar view.
var topLayoutGuide: UILayoutSupport? { get set }
/// Specify optional layout guide for positioning the bar view.
var bottomLayoutGuide: UILayoutSupport? { get set }
/// Defines styles for the bar.
var style: DodoStyle { get set }
/// Changes the style preset for the bar widget.
var preset: DodoPresets { get set }
/**
Shows the message bar with *.success* preset. It can be used to indicate successful completion of an operation.
- parameter message: The text message to be shown.
*/
func success(_ message: String)
/**
Shows the message bar with *.Info* preset. It can be used for showing information messages that have neutral emotional value.
- parameter message: The text message to be shown.
*/
func info(_ message: String)
/**
Shows the message bar with *.warning* preset. It can be used for for showing warning messages.
- parameter message: The text message to be shown.
*/
func warning(_ message: String)
/**
Shows the message bar with *.warning* preset. It can be used for showing critical error messages
- parameter message: The text message to be shown.
*/
func error(_ message: String)
/**
Shows the message bar. Set `preset` property to change the appearance of the message bar, or use the shortcut methods: `success`, `info`, `warning` and `error`.
- parameter message: The text message to be shown.
*/
func show(_ message: String)
/// Hide the message bar if it's currently shown.
func hide()
}
// ----------------------------
//
// DodoKeyboardListener.swift
//
// ----------------------------
/**
Start listening for keyboard events. Used for moving the message bar from under the keyboard when the bar is shown at the bottom of the screen.
*/
struct DodoKeyboardListener {
static let underKeyboardLayoutConstraint = UnderKeyboardLayoutConstraint()
static func startListening() {
// Just access the static property to make it initialize itself lazily if it hasn't been already.
underKeyboardLayoutConstraint.isAccessibilityElement = false
}
}
// ----------------------------
//
// DodoToolbar.swift
//
// ----------------------------
import UIKit
class DodoToolbar: UIView {
var layoutGuide: UILayoutSupport?
var style: DodoStyle
weak var buttonViewDelegate: DodoButtonViewDelegate?
private var didCallHide = false
convenience init(witStyle style: DodoStyle) {
self.init(frame: CGRect())
self.style = style
}
override init(frame: CGRect) {
style = DodoStyle()
super.init(frame: frame)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func show(inSuperview parentView: UIView, withMessage message: String) {
if superview != nil { return } // already being shown
parentView.addSubview(self)
applyStyle()
layoutBarInSuperview()
let buttons = createButtons()
createLabel(message, withButtons: buttons)
style.bar.animationShow(self, style.bar.animationShowDuration, style.bar.locationTop, {})
}
func hide(_ onAnimationCompleted: @escaping ()->()) {
// Respond only to the first hide() call
if didCallHide { return }
didCallHide = true
style.bar.animationHide(self, style.bar.animationHideDuration,
style.bar.locationTop, { [weak self] in
self?.removeFromSuperview()
onAnimationCompleted()
})
}
// MARK: - Label
private func createLabel(_ message: String, withButtons buttons: [UIView]) {
let label = UILabel()
label.font = style.label.font
label.text = message
label.textColor = style.label.color
label.textAlignment = NSTextAlignment.center
label.numberOfLines = style.label.numberOfLines
if style.bar.debugMode {
label.backgroundColor = UIColor.red
}
if let shadowColor = style.label.shadowColor {
label.shadowColor = shadowColor
label.shadowOffset = style.label.shadowOffset
}
addSubview(label)
layoutLabel(label, withButtons: buttons)
}
private func layoutLabel(_ label: UILabel, withButtons buttons: [UIView]) {
label.translatesAutoresizingMaskIntoConstraints = false
// Stretch the label vertically
TegAutolayoutConstraints.fillParent(label, parentView: self,
margin: style.label.horizontalMargin, vertically: true)
if buttons.count == 0 {
if let superview = superview {
// If there are no buttons - stretch the label to the entire width of the view
TegAutolayoutConstraints.fillParent(label, parentView: superview,
margin: style.label.horizontalMargin, vertically: false)
}
} else {
layoutLabelWithButtons(label, withButtons: buttons)
}
}
private func layoutLabelWithButtons(_ label: UILabel, withButtons buttons: [UIView]) {
if buttons.count != 2 { return }
let views = [buttons[0], label, buttons[1]]
if let superview = superview {
TegAutolayoutConstraints.viewsNextToEachOther(views,
constraintContainer: superview, margin: style.label.horizontalMargin, vertically: false)
}
}
// MARK: - Buttons
private func createButtons() -> [DodoButtonView] {
precondition(buttonViewDelegate != nil, "Button view delegate can not be nil")
let buttonStyles = [style.leftButton, style.rightButton]
let buttonViews = DodoButtonView.createMany(buttonStyles)
for (index, button) in buttonViews.enumerated() {
addSubview(button)
button.delegate = buttonViewDelegate
button.doLayout(onLeftSide: index == 0)
if style.bar.debugMode {
button.backgroundColor = UIColor.yellow
}
}
return buttonViews
}
// MARK: - Style the bar
private func applyStyle() {
backgroundColor = style.bar.backgroundColor
layer.cornerRadius = style.bar.cornerRadius
layer.masksToBounds = true
if let borderColor = style.bar.borderColor , style.bar.borderWidth > 0 {
layer.borderColor = borderColor.cgColor
layer.borderWidth = style.bar.borderWidth
}
}
private func layoutBarInSuperview() {
translatesAutoresizingMaskIntoConstraints = false
if let superview = superview {
// Stretch the toobar horizontally to the width if its superview
TegAutolayoutConstraints.fillParent(self, parentView: superview,
margin: style.bar.marginToSuperview.width, vertically: false)
let vMargin = style.bar.marginToSuperview.height
let verticalMargin = style.bar.locationTop ? -vMargin : vMargin
var verticalConstraints = [NSLayoutConstraint]()
if let layoutGuide = layoutGuide {
// Align the top/bottom edge of the toolbar with the top/bottom layout guide
// (a tab bar, for example)
verticalConstraints = TegAutolayoutConstraints.alignVerticallyToLayoutGuide(self,
onTop: style.bar.locationTop,
layoutGuide: layoutGuide,
constraintContainer: superview,
margin: verticalMargin)
} else {
// Align the top/bottom of the toolbar with the top/bottom of its superview
verticalConstraints = TegAutolayoutConstraints.alignSameAttributes(superview, toItem: self,
constraintContainer: superview,
attribute: style.bar.locationTop ? NSLayoutAttribute.top : NSLayoutAttribute.bottom,
margin: verticalMargin)
}
setupKeyboardEvader(verticalConstraints)
}
}
// Moves the message bar from under the keyboard
private func setupKeyboardEvader(_ verticalConstraints: [NSLayoutConstraint]) {
if let bottomConstraint = verticalConstraints.first,
let superview = superview
, !style.bar.locationTop {
DodoKeyboardListener.underKeyboardLayoutConstraint.setup(bottomConstraint,
view: superview, bottomLayoutGuide: layoutGuide)
}
}
}
// ----------------------------
//
// DodoTouchTarget.swift
//
// ----------------------------
import UIKit
/**
Helper function to make sure bounds are big enought to be used as touch target.
The function is used in pointInside(point: CGPoint, withEvent event: UIEvent?) of UIImageView.
*/
struct DodoTouchTarget {
static func optimize(_ bounds: CGRect) -> CGRect {
let recommendedHitSize: CGFloat = 44
var hitWidthIncrease:CGFloat = recommendedHitSize - bounds.width
var hitHeightIncrease:CGFloat = recommendedHitSize - bounds.height
if hitWidthIncrease < 0 { hitWidthIncrease = 0 }
if hitHeightIncrease < 0 { hitHeightIncrease = 0 }
let extendedBounds: CGRect = bounds.insetBy(dx: -hitWidthIncrease / 2,
dy: -hitHeightIncrease / 2)
return extendedBounds
}
}
// ----------------------------
//
// DodoIcons.swift
//
// ----------------------------
/**
Collection of icons included with Dodo library.
*/
public enum DodoIcons: String {
/// Icon for closing the bar.
case close = "Close"
/// Icon for reloading.
case reload = "Reload"
}
// ----------------------------
//
// DodoMock.swift
//
// ----------------------------
import UIKit
/**
This class is for testing the code that uses Dodo. It helps verifying the messages that were shown in the message bar without actually showing them.
Here is how to use it in your unit test.
1. Create an instance of DodoMock.
2. Set it to the `view.dodo` property of the view.
3. Run the code that you are testing.
4. Finally, verify which messages were shown in the message bar.
Example:
// Supply mock to the view
let dodoMock = DodoMock()
view.dodo = dodoMock
// Run the code from the app
runSomeAppCode()
// Verify the message is visible
XCTAssert(dodoMock.results.visible)
// Check total number of messages shown
XCTAssertEqual(1, dodoMock.results.total)
// Verify the text of the success message
XCTAssertEqual("To be prepared is half the victory.", dodoMock.results.success[0])
*/
public class DodoMock: DodoInterface {
/// This property is used in unit tests to verify which messages were displayed in the message bar.
public var results = DodoMockResults()
/// Specify optional layout guide for positioning the bar view.
public var topLayoutGuide: UILayoutSupport?
/// Specify optional layout guide for positioning the bar view.
public var bottomLayoutGuide: UILayoutSupport?
/// Defines styles for the bar.
public var style = DodoStyle(parentStyle: DodoPresets.defaultPreset.style)
/// Creates an instance of DodoMock class
public init() { }
/// Changes the style preset for the bar widget.
public var preset: DodoPresets = DodoPresets.defaultPreset {
didSet {
if preset != oldValue {
style.parent = preset.style
}
}
}
/**
Shows the message bar with *.success* preset. It can be used to indicate successful completion of an operation.
- parameter message: The text message to be shown.
*/
public func success(_ message: String) {
preset = .success
show(message)
}
/**
Shows the message bar with *.Info* preset. It can be used for showing information messages that have neutral emotional value.
- parameter message: The text message to be shown.
*/
public func info(_ message: String) {
preset = .info
show(message)
}
/**
Shows the message bar with *.warning* preset. It can be used for for showing warning messages.
- parameter message: The text message to be shown.
*/
public func warning(_ message: String) {
preset = .warning
show(message)
}
/**
Shows the message bar with *.warning* preset. It can be used for showing critical error messages
- parameter message: The text message to be shown.
*/
public func error(_ message: String) {
preset = .error
show(message)
}
/**
Shows the message bar. Set `preset` property to change the appearance of the message bar, or use the shortcut methods: `success`, `info`, `warning` and `error`.
- parameter message: The text message to be shown.
*/
public func show(_ message: String) {
let mockMessage = DodoMockMessage(preset: preset, message: message)
results.messages.append(mockMessage)
results.visible = true
}
/// Hide the message bar if it's currently shown.
public func hide() {
results.visible = false
}
}
// ----------------------------
//
// DodoMockMessage.swift
//
// ----------------------------
/**
Contains information about the message that was displayed in message bar. Used in unit tests.
*/
struct DodoMockMessage {
let preset: DodoPresets
let message: String
}
// ----------------------------
//
// DodoMockResults.swift
//
// ----------------------------
/**
Used in unit tests to verify the messages that were shown in the message bar.
*/
public struct DodoMockResults {
/// An array of success messages displayed in the message bar.
public var success: [String] {
return messages.filter({ $0.preset == DodoPresets.success }).map({ $0.message })
}
/// An array of information messages displayed in the message bar.
public var info: [String] {
return messages.filter({ $0.preset == DodoPresets.info }).map({ $0.message })
}
/// An array of warning messages displayed in the message bar.
public var warning: [String] {
return messages.filter({ $0.preset == DodoPresets.warning }).map({ $0.message })
}
/// An array of error messages displayed in the message bar.
public var errors: [String] {
return messages.filter({ $0.preset == DodoPresets.error }).map({ $0.message })
}
/// Total number of messages shown.
public var total: Int {
return messages.count
}
/// Indicates whether the message is visible
public var visible = false
var messages = [DodoMockMessage]()
}
// ----------------------------
//
// DodoBarDefaultStyles.swift
//
// ----------------------------
import UIKit
/**
Default styles for the bar view.
Default styles are used when individual element styles are not set.
*/
public struct DodoBarDefaultStyles {
/// Revert the property values to their defaults
public static func resetToDefaults() {
animationHide = _animationHide
animationHideDuration = _animationHideDuration
animationShow = _animationShow
animationShowDuration = _animationShowDuration
backgroundColor = _backgroundColor
borderColor = _borderColor
borderWidth = _borderWidth
cornerRadius = _cornerRadius
debugMode = _debugMode
hideAfterDelaySeconds = _hideAfterDelaySeconds
hideOnTap = _hideOnTap
locationTop = _locationTop
marginToSuperview = _marginToSuperview
onTap = _onTap
}
// ---------------------------
private static let _animationHide: DodoAnimation = DodoAnimationsHide.rotate
/// Specify a function for animating the bar when it is hidden.
public static var animationHide: DodoAnimation = _animationHide
// ---------------------------
private static let _animationHideDuration: TimeInterval? = nil
/// Duration of hide animation. When nil it uses default duration for selected animation function.
public static var animationHideDuration: TimeInterval? = _animationHideDuration
// ---------------------------
private static let _animationShow: DodoAnimation = DodoAnimationsShow.rotate
/// Specify a function for animating the bar when it is shown.
public static var animationShow: DodoAnimation = _animationShow
// ---------------------------
private static let _animationShowDuration: TimeInterval? = nil
/// Duration of show animation. When nil it uses default duration for selected animation function.
public static var animationShowDuration: TimeInterval? = _animationShowDuration
// ---------------------------
private static let _backgroundColor: UIColor? = nil
/// Background color of the bar.
public static var backgroundColor = _backgroundColor
// ---------------------------
private static let _borderColor: UIColor? = nil
/// Color of the bar's border.
public static var borderColor = _borderColor
// ---------------------------
private static let _borderWidth: CGFloat = 1 / UIScreen.main.scale
/// Border width of the bar.
public static var borderWidth = _borderWidth
// ---------------------------
private static let _cornerRadius: CGFloat = 20
/// Corner radius of the bar view.
public static var cornerRadius = _cornerRadius
// ---------------------------
private static let _debugMode = false
/// When true it highlights the view background for spotting layout issues.
public static var debugMode = _debugMode
// ---------------------------
private static let _hideAfterDelaySeconds: TimeInterval = 0
/**
Hides the bar automatically after the specified number of seconds.
The bar is kept on screen indefinitely if the value is zero.
*/
public static var hideAfterDelaySeconds = _hideAfterDelaySeconds
// ---------------------------
private static let _hideOnTap = false
/// When true the bar is hidden when user taps on it.
public static var hideOnTap = _hideOnTap
// ---------------------------
private static let _locationTop = true
/// Position of the bar. When true the bar is shown on top of the screen.
public static var locationTop = _locationTop
// ---------------------------
private static let _marginToSuperview = CGSize(width: 5, height: 5)
/// Margin between the bar edge and its superview.
public static var marginToSuperview = _marginToSuperview
// ---------------------------
private static let _onTap: DodoBarOnTap? = nil
/// Supply a function that will be called when user taps the bar.
public static var onTap = _onTap
// ---------------------------
}
// ----------------------------
//
// DodoBarStyle.swift
//
// ----------------------------
import UIKit
/// Defines styles related to the bar view in general.
public class DodoBarStyle {
/// The parent style is used to get the property value if the object is missing one.
var parent: DodoBarStyle?
init(parentStyle: DodoBarStyle? = nil) {
self.parent = parentStyle
}
/// Clears the styles for all properties for this style object. The styles will be taken from parent and default properties.
public func clear() {
_animationHide = nil
_animationHideDuration = nil
_animationShow = nil
_animationShowDuration = nil
_backgroundColor = nil
_borderColor = nil
_borderWidth = nil
_cornerRadius = nil
_debugMode = nil
_hideAfterDelaySeconds = nil
_hideOnTap = nil
_locationTop = nil
_marginToSuperview = nil
_onTap = nil
}
// -----------------------------
private var _animationHide: DodoAnimation?
/// Specify a function for animating the bar when it is hidden.
public var animationHide: DodoAnimation {
get {
return (_animationHide ?? parent?.animationHide) ?? DodoBarDefaultStyles.animationHide
}
set {
_animationHide = newValue
}
}
// ---------------------------
private var _animationHideDuration: TimeInterval?
/// Duration of hide animation. When nil it uses default duration for selected animation function.
public var animationHideDuration: TimeInterval? {
get {
return (_animationHideDuration ?? parent?.animationHideDuration) ??
DodoBarDefaultStyles.animationHideDuration
}
set {
_animationHideDuration = newValue
}
}
// ---------------------------
private var _animationShow: DodoAnimation?
/// Specify a function for animating the bar when it is shown.
public var animationShow: DodoAnimation {
get {
return (_animationShow ?? parent?.animationShow) ?? DodoBarDefaultStyles.animationShow
}
set {
_animationShow = newValue
}
}
// ---------------------------
private var _animationShowDuration: TimeInterval?
/// Duration of show animation. When nil it uses default duration for selected animation function.
public var animationShowDuration: TimeInterval? {
get {
return (_animationShowDuration ?? parent?.animationShowDuration) ??
DodoBarDefaultStyles.animationShowDuration
}
set {
_animationShowDuration = newValue
}
}
// ---------------------------
private var _backgroundColor: UIColor?
/// Background color of the bar.
public var backgroundColor: UIColor? {
get {
return _backgroundColor ?? parent?.backgroundColor ?? DodoBarDefaultStyles.backgroundColor
}
set {
_backgroundColor = newValue
}
}
// -----------------------------
private var _borderColor: UIColor?
/// Color of the bar's border.
public var borderColor: UIColor? {
get {
return _borderColor ?? parent?.borderColor ?? DodoBarDefaultStyles.borderColor
}
set {
_borderColor = newValue
}
}
// -----------------------------
private var _borderWidth: CGFloat?
/// Border width of the bar.
public var borderWidth: CGFloat {
get {
return _borderWidth ?? parent?.borderWidth ?? DodoBarDefaultStyles.borderWidth
}
set {
_borderWidth = newValue
}
}
// -----------------------------
private var _cornerRadius: CGFloat?
/// Corner radius of the bar view.
public var cornerRadius: CGFloat {
get {
return _cornerRadius ?? parent?.cornerRadius ?? DodoBarDefaultStyles.cornerRadius
}
set {
_cornerRadius = newValue
}
}
// -----------------------------
private var _debugMode: Bool?
/// When true it highlights the view background for spotting layout issues.
public var debugMode: Bool {
get {
return _debugMode ?? parent?.debugMode ?? DodoBarDefaultStyles.debugMode
}
set {
_debugMode = newValue
}
}
// ---------------------------
private var _hideAfterDelaySeconds: TimeInterval?
/**
Hides the bar automatically after the specified number of seconds.
If nil the bar is kept on screen.
*/
public var hideAfterDelaySeconds: TimeInterval {
get {
return _hideAfterDelaySeconds ?? parent?.hideAfterDelaySeconds ??
DodoBarDefaultStyles.hideAfterDelaySeconds
}
set {
_hideAfterDelaySeconds = newValue
}
}
// -----------------------------
private var _hideOnTap: Bool?
/// When true the bar is hidden when user taps on it.
public var hideOnTap: Bool {
get {
return _hideOnTap ?? parent?.hideOnTap ??
DodoBarDefaultStyles.hideOnTap
}
set {
_hideOnTap = newValue
}
}
// -----------------------------
private var _locationTop: Bool?
/// Position of the bar. When true the bar is shown on top of the screen.
public var locationTop: Bool {
get {
return _locationTop ?? parent?.locationTop ?? DodoBarDefaultStyles.locationTop
}
set {
_locationTop = newValue
}
}
// -----------------------------
private var _marginToSuperview: CGSize?
/// Margin between the bar edge and its superview.
public var marginToSuperview: CGSize {
get {
return _marginToSuperview ?? parent?.marginToSuperview ??
DodoBarDefaultStyles.marginToSuperview
}
set {
_marginToSuperview = newValue
}
}
// ---------------------------
private var _onTap: DodoBarOnTap?
/// Supply a function that will be called when user taps the bar.
public var onTap: DodoBarOnTap? {
get {
return _onTap ?? parent?.onTap ?? DodoBarDefaultStyles.onTap
}
set {
_onTap = newValue
}
}
// -----------------------------
}
// ----------------------------
//
// DodoButtonDefaultStyles.swift
//
// ----------------------------
import UIKit
/**
Default styles for the bar button.
Default styles are used when individual element styles are not set.
*/
public struct DodoButtonDefaultStyles {
/// Revert the property values to their defaults
public static func resetToDefaults() {
accessibilityLabel = _accessibilityLabel
hideOnTap = _hideOnTap
horizontalMarginToBar = _horizontalMarginToBar
icon = _icon
image = _image
onTap = _onTap
size = _size
tintColor = _tintColor
}
// ---------------------------
private static let _accessibilityLabel: String? = nil
/**
This text is spoken by the device when it is in accessibility mode. It is recommended to always set the accessibility label for your button. The text can be a short localized description of the button function, for example: "Close the message", "Reload" etc.
*/
public static var accessibilityLabel = _accessibilityLabel
// ---------------------------
private static let _hideOnTap = false
/// When true it hides the bar when the button is tapped.
public static var hideOnTap = _hideOnTap
// ---------------------------
private static let _horizontalMarginToBar: CGFloat = 10
/// Margin between the bar edge and the button
public static var horizontalMarginToBar = _horizontalMarginToBar
// ---------------------------
private static let _icon: DodoIcons? = nil
/// When set it shows one of the default Dodo icons. Use `image` property to supply a custom image. The color of the image can be changed with `tintColor` property.
public static var icon = _icon
// ---------------------------
private static let _image: UIImage? = nil
/// Custom image for the button. One can also use the `icon` property to show one of the default Dodo icons. The color of the image can be changed with `tintColor` property.
public static var image = _image
// ---------------------------
private static let _onTap: DodoButtonOnTap? = nil
/// Supply a function that will be called when user taps the button.
public static var onTap = _onTap
// ---------------------------
private static let _size = CGSize(width: 25, height: 25)
/// Size of the button.
public static var size = _size
// ---------------------------
private static let _tintColor: UIColor? = nil
/// Replaces the color of the image or icon. The original colors are used when nil.
public static var tintColor = _tintColor
// ---------------------------
}
// ----------------------------
//
// DodoButtonStyle.swift
//
// ----------------------------
import UIKit
/// Defines styles for the bar button.
public class DodoButtonStyle {
/// The parent style is used to get the property value if the object is missing one.
var parent: DodoButtonStyle?
init(parentStyle: DodoButtonStyle? = nil) {
self.parent = parentStyle
}
/// Clears the styles for all properties for this style object. The styles will be taken from parent and default properties.
public func clear() {
_accessibilityLabel = nil
_hideOnTap = nil
_horizontalMarginToBar = nil
_icon = nil
_image = nil
_onTap = nil
_size = nil
_tintColor = nil
}
// -----------------------------
private var _accessibilityLabel: String?
/**
This text is spoken by the device when it is in accessibility mode. It is recommended to always set the accessibility label for your button. The text can be a short localized description of the button function, for example: "Close the message", "Reload" etc.
*/
public var accessibilityLabel: String? {
get {
return _accessibilityLabel ?? parent?.accessibilityLabel ?? DodoButtonDefaultStyles.accessibilityLabel
}
set {
_accessibilityLabel = newValue
}
}
// -----------------------------
private var _hideOnTap: Bool?
/// When true it hides the bar when the button is tapped.
public var hideOnTap: Bool {
get {
return _hideOnTap ?? parent?.hideOnTap ?? DodoButtonDefaultStyles.hideOnTap
}
set {
_hideOnTap = newValue
}
}
// -----------------------------
private var _horizontalMarginToBar: CGFloat?
/// Horizontal margin between the bar edge and the button.
public var horizontalMarginToBar: CGFloat {
get {
return _horizontalMarginToBar ?? parent?.horizontalMarginToBar ??
DodoButtonDefaultStyles.horizontalMarginToBar
}
set {
_horizontalMarginToBar = newValue
}
}
// -----------------------------
private var _icon: DodoIcons?
/// When set it shows one of the default Dodo icons. Use `image` property to supply a custom image. The color of the image can be changed with `tintColor` property.
public var icon: DodoIcons? {
get {
return _icon ?? parent?.icon ?? DodoButtonDefaultStyles.icon
}
set {
_icon = newValue
}
}
// -----------------------------
private var _image: UIImage?
/// Custom image for the button. One can also use the `icon` property to show one of the default Dodo icons. The color of the image can be changed with `tintColor` property.
public var image: UIImage? {
get {
return _image ?? parent?.image ?? DodoButtonDefaultStyles.image
}
set {
_image = newValue
}
}
// ---------------------------
private var _onTap: DodoButtonOnTap?
/// Supply a function that will be called when user taps the button.
public var onTap: DodoButtonOnTap? {
get {
return _onTap ?? parent?.onTap ?? DodoButtonDefaultStyles.onTap
}
set {
_onTap = newValue
}
}
// -----------------------------
private var _size: CGSize?
/// Size of the button.
public var size: CGSize {
get {
return _size ?? parent?.size ?? DodoButtonDefaultStyles.size
}
set {
_size = newValue
}
}
// -----------------------------
private var _tintColor: UIColor?
/// Replaces the color of the image or icon. The original colors are used when nil.
public var tintColor: UIColor? {
get {
return _tintColor ?? parent?.tintColor ?? DodoButtonDefaultStyles.tintColor
}
set {
_tintColor = newValue
}
}
// -----------------------------
}
// ----------------------------
//
// DodoLabelDefaultStyles.swift
//
// ----------------------------
import UIKit
/**
Default styles for the text label.
Default styles are used when individual element styles are not set.
*/
public struct DodoLabelDefaultStyles {
/// Revert the property values to their defaults
public static func resetToDefaults() {
color = _color
font = _font
horizontalMargin = _horizontalMargin
numberOfLines = _numberOfLines
shadowColor = _shadowColor
shadowOffset = _shadowOffset
}
// ---------------------------
private static let _color = UIColor.white
/// Color of the label text.
public static var color = _color
// ---------------------------
private static let _font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.headline)
/// Font of the label text.
public static var font = _font
// ---------------------------
private static let _horizontalMargin: CGFloat = 10
/// Margin between the bar/button edge and the label.
public static var horizontalMargin = _horizontalMargin
// ---------------------------
private static let _numberOfLines: Int = 3
/// The maximum number of lines in the label.
public static var numberOfLines = _numberOfLines
// ---------------------------
private static let _shadowColor: UIColor? = nil
/// Color of text shadow.
public static var shadowColor = _shadowColor
// ---------------------------
private static let _shadowOffset = CGSize(width: 0, height: 1)
/// Text shadow offset.
public static var shadowOffset = _shadowOffset
// ---------------------------
}
// ----------------------------
//
// DodoLabelStyle.swift
//
// ----------------------------
import UIKit
/// Defines styles related to the text label.
public class DodoLabelStyle {
/// The parent style is used to get the property value if the object is missing one.
var parent: DodoLabelStyle?
init(parentStyle: DodoLabelStyle? = nil) {
self.parent = parentStyle
}
/// Clears the styles for all properties for this style object. The styles will be taken from parent and default properties.
public func clear() {
_color = nil
_font = nil
_horizontalMargin = nil
_numberOfLines = nil
_shadowColor = nil
_shadowOffset = nil
}
// -----------------------------
private var _color: UIColor?
/// Color of the label text.
public var color: UIColor {
get {
return _color ?? parent?.color ?? DodoLabelDefaultStyles.color
}
set {
_color = newValue
}
}
// -----------------------------
private var _font: UIFont?
/// Color of the label text.
public var font: UIFont {
get {
return _font ?? parent?.font ?? DodoLabelDefaultStyles.font
}
set {
_font = newValue
}
}
// -----------------------------
private var _horizontalMargin: CGFloat?
/// Margin between the bar/button edge and the label.
public var horizontalMargin: CGFloat {
get {
return _horizontalMargin ?? parent?.horizontalMargin ??
DodoLabelDefaultStyles.horizontalMargin
}
set {
_horizontalMargin = newValue
}
}
// -----------------------------
private var _numberOfLines: Int?
/// The maximum number of lines in the label.
public var numberOfLines: Int {
get {
return _numberOfLines ?? parent?.numberOfLines ??
DodoLabelDefaultStyles.numberOfLines
}
set {
_numberOfLines = newValue
}
}
// -----------------------------
private var _shadowColor: UIColor?
/// Color of text shadow.
public var shadowColor: UIColor? {
get {
return _shadowColor ?? parent?.shadowColor ?? DodoLabelDefaultStyles.shadowColor
}
set {
_shadowColor = newValue
}
}
// -----------------------------
private var _shadowOffset: CGSize?
/// Text shadow offset.
public var shadowOffset: CGSize {
get {
return _shadowOffset ?? parent?.shadowOffset ?? DodoLabelDefaultStyles.shadowOffset
}
set {
_shadowOffset = newValue
}
}
// -----------------------------
}
// ----------------------------
//
// DodoPresets.swift
//
// ----------------------------
/**
Defines the style presets for the bar.
*/
public enum DodoPresets {
/// A styling preset used for indicating successful completion of an operation. Usually styled with green color.
case success
/// A styling preset for showing information messages, neutral in color.
case info
/// A styling preset for showing warning messages. Can be styled with yellow/orange colors.
case warning
/// A styling preset for showing critical error messages. Usually styled with red color.
case error
/// The preset is used by default for the bar if it's not set by the user.
static let defaultPreset = DodoPresets.success
/// The preset cache.
private static var styles = [DodoPresets: DodoStyle]()
/// Returns the style for the preset
public var style: DodoStyle {
var style = DodoPresets.styles[self]
if style == nil {
style = DodoPresets.makeStyle(forPreset: self)
DodoPresets.styles[self] = style
}
precondition(style != nil, "Failed to create style")
return style ?? DodoStyle()
}
/// Reset alls preset styles to their initial states.
public static func resetAll() {
styles = [:]
}
/// Reset the preset style to its initial state.
public func reset() {
DodoPresets.styles.removeValue(forKey: self)
}
private static func makeStyle(forPreset preset: DodoPresets) -> DodoStyle{
let style = DodoStyle()
switch preset {
case .success:
style.bar.backgroundColor = DodoColor.fromHexString("#00CC03C9")
case .info:
style.bar.backgroundColor = DodoColor.fromHexString("#0057FF96")
case .warning:
style.bar.backgroundColor = DodoColor.fromHexString("#CEC411DD")
case .error:
style.bar.backgroundColor = DodoColor.fromHexString("#FF0B0BCC")
}
return style
}
}
// ----------------------------
//
// DodoStyle.swift
//
// ----------------------------
import UIKit
/// Combines various styles for the toolbar element.
public class DodoStyle {
/// The parent style is used to get the property value if the object is missing one.
var parent: DodoStyle? {
didSet {
changeParent()
}
}
init(parentStyle: DodoStyle? = nil) {
self.parent = parentStyle
}
private func changeParent() {
bar.parent = parent?.bar
label.parent = parent?.label
leftButton.parent = parent?.leftButton
rightButton.parent = parent?.rightButton
}
/**
Reverts all the default styles to their initial values. Usually used in setUp() function in the unit tests.
*/
public static func resetDefaultStyles() {
DodoBarDefaultStyles.resetToDefaults()
DodoLabelDefaultStyles.resetToDefaults()
DodoButtonDefaultStyles.resetToDefaults()
}
/// Clears the styles for all properties for this style object. The styles will be taken from parent and default properties.
public func clear() {
bar.clear()
label.clear()
leftButton.clear()
rightButton.clear()
}
/**
Styles for the bar view.
*/
public lazy var bar: DodoBarStyle = self.initBarStyle()
private func initBarStyle() -> DodoBarStyle {
return DodoBarStyle(parentStyle: parent?.bar)
}
/**
Styles for the text label.
*/
public lazy var label: DodoLabelStyle = self.initLabelStyle()
private func initLabelStyle() -> DodoLabelStyle {
return DodoLabelStyle(parentStyle: parent?.label)
}
/**
Styles for the left button.
*/
public lazy var leftButton: DodoButtonStyle = self.initLeftButtonStyle()
private func initLeftButtonStyle() -> DodoButtonStyle {
return DodoButtonStyle(parentStyle: parent?.leftButton)
}
/**
Styles for the right button.
*/
public lazy var rightButton: DodoButtonStyle = self.initRightButtonStyle()
private func initRightButtonStyle() -> DodoButtonStyle {
return DodoButtonStyle(parentStyle: parent?.rightButton)
}
}
// ----------------------------
//
// UIView+SwiftAlertBar.swift
//
// ----------------------------
import UIKit
private var sabAssociationKey: UInt8 = 0
/**
UIView extension for showing a notification widget.
let view = UIView()
view.dodo.show("Hello World!")
*/
public extension UIView {
/**
Message bar extension.
Call `dodo.show`, `dodo.success`, dodo.error` functions to show a notification widget in the view.
let view = UIView()
view.dodo.show("Hello World!")
*/
public var dodo: DodoInterface {
get {
if let value = objc_getAssociatedObject(self, &sabAssociationKey) as? DodoInterface {
return value
} else {
let dodo = Dodo(superview: self)
objc_setAssociatedObject(self, &sabAssociationKey, dodo,
objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
return dodo
}
}
set {
objc_setAssociatedObject(self, &sabAssociationKey, newValue,
objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
}
}
}
// ----------------------------
//
// DodoColor.swift
//
// ----------------------------
import UIKit
/**
Creates a UIColor object from a string.
Examples:
DodoColor.fromHexString('#340f9a')
// With alpha channel
DodoColor.fromHexString('#f1a2b3a6')
*/
public class DodoColor {
/**
Creates a UIColor object from a string.
- parameter rgba: a RGB/RGBA string representation of color. It can include optional alpha value. Example: "#cca213" or "#cca21312" (with alpha value).
- returns: UIColor object.
*/
public class func fromHexString(_ rgba: String) -> UIColor {
var red: CGFloat = 0.0
var green: CGFloat = 0.0
var blue: CGFloat = 0.0
var alpha: CGFloat = 1.0
if !rgba.hasPrefix("#") {
print("Warning: DodoColor.fromHexString, # character missing")
return UIColor()
}
let index = rgba.characters.index(rgba.startIndex, offsetBy: 1)
let hex = rgba.substring(from: index)
let scanner = Scanner(string: hex)
var hexValue: CUnsignedLongLong = 0
if !scanner.scanHexInt64(&hexValue) {
print("Warning: DodoColor.fromHexString, error scanning hex value")
return UIColor()
}
if hex.characters.count == 6 {
red = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0
green = CGFloat((hexValue & 0x00FF00) >> 8) / 255.0
blue = CGFloat(hexValue & 0x0000FF) / 255.0
} else if hex.characters.count == 8 {
red = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0
green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0
blue = CGFloat((hexValue & 0x0000FF00) >> 8) / 255.0
alpha = CGFloat(hexValue & 0x000000FF) / 255.0
} else {
print("Warning: DodoColor.fromHexString, invalid rgb string, length should be 7 or 9")
return UIColor()
}
return UIColor(red: red, green: green, blue: blue, alpha: alpha)
}
}
// ----------------------------
//
// MoaTimer.swift
//
// ----------------------------
import UIKit
/**
Creates a timer that executes code after delay.
Usage
var timer: MoaTimer.runAfter?
...
func myFunc() {
timer = MoaTimer.runAfter(0.010) { timer in
... code to run
}
}
Canceling the timer
Timer is Canceling automatically when it is deallocated. You can also cancel it manually:
let timer = MoaTimer.runAfter(0.010) { timer in ... }
timer.cancel()
*/
final class MoaTimer: NSObject {
private let repeats: Bool
private var timer: Timer?
private var callback: ((MoaTimer)->())?
private init(interval: TimeInterval, repeats: Bool = false, callback: @escaping (MoaTimer)->()) {
self.repeats = repeats
super.init()
self.callback = callback
timer = Timer.scheduledTimer(timeInterval: interval, target: self,
selector: #selector(MoaTimer.timerFired(_:)), userInfo: nil, repeats: repeats)
}
/// Timer is cancelled automatically when it is deallocated.
deinit {
cancel()
}
/**
Cancels the timer and prevents it from firing in the future.
Note that timer is cancelled automatically whe it is deallocated.
*/
func cancel() {
timer?.invalidate()
timer = nil
}
/**
Runs the closure after specified time interval.
- parameter interval: Time interval in milliseconds.
:repeats: repeats When true, the code is run repeatedly.
- returns: callback A closure to be run by the timer.
*/
@discardableResult
class func runAfter(_ interval: TimeInterval, repeats: Bool = false,
callback: @escaping (MoaTimer)->()) -> MoaTimer {
return MoaTimer(interval: interval, repeats: repeats, callback: callback)
}
func timerFired(_ timer: Timer) {
self.callback?(self)
if !repeats { cancel() }
}
}
// ----------------------------
//
// OnTap.swift
//
// ----------------------------
import UIKit
/**
Calling tap with closure.
*/
class OnTap: NSObject {
var closure: ()->()
init(view: UIView, gesture: UIGestureRecognizer, closure: @escaping ()->()) {
self.closure = closure
super.init()
view.addGestureRecognizer(gesture)
view.isUserInteractionEnabled = true
gesture.addTarget(self, action: #selector(OnTap.didTap(_:)))
}
func didTap(_ gesture: UIGestureRecognizer) {
closure()
}
}
// ----------------------------
//
// SpringAnimationCALayer.swift
//
// ----------------------------
import UIKit
/**
Animating CALayer with spring effect in iOS with Swift
https://github.com/evgenyneu/SpringAnimationCALayer
*/
class SpringAnimationCALayer {
// Animates layer with spring effect.
class func animate(_ layer: CALayer,
keypath: String,
duration: CFTimeInterval,
usingSpringWithDamping: Double,
initialSpringVelocity: Double,
fromValue: Double,
toValue: Double,
onFinished: (()->())?) {
CATransaction.begin()
CATransaction.setCompletionBlock(onFinished)
let animation = create(keypath, duration: duration,
usingSpringWithDamping: usingSpringWithDamping,
initialSpringVelocity: initialSpringVelocity,
fromValue: fromValue, toValue: toValue)
layer.add(animation, forKey: keypath + " spring animation")
CATransaction.commit()
}
// Creates CAKeyframeAnimation object
class func create(_ keypath: String,
duration: CFTimeInterval,
usingSpringWithDamping: Double,
initialSpringVelocity: Double,
fromValue: Double,
toValue: Double) -> CAKeyframeAnimation {
let dampingMultiplier = Double(10)
let velocityMultiplier = Double(10)
let values = animationValues(fromValue, toValue: toValue,
usingSpringWithDamping: dampingMultiplier * usingSpringWithDamping,
initialSpringVelocity: velocityMultiplier * initialSpringVelocity)
let animation = CAKeyframeAnimation(keyPath: keypath)
animation.values = values
animation.duration = duration
return animation
}
class func animationValues(_ fromValue: Double, toValue: Double,
usingSpringWithDamping: Double, initialSpringVelocity: Double) -> [Double]{
let numOfPoints = 1000
var values = [Double](repeating: 0.0, count: numOfPoints)
let distanceBetweenValues = toValue - fromValue
for point in (0..<numOfPoints) {
let x = Double(point) / Double(numOfPoints)
let valueNormalized = animationValuesNormalized(x,
usingSpringWithDamping: usingSpringWithDamping, initialSpringVelocity: initialSpringVelocity)
let value = toValue - distanceBetweenValues * valueNormalized
values[point] = value
}
return values
}
private class func animationValuesNormalized(_ x: Double, usingSpringWithDamping: Double,
initialSpringVelocity: Double) -> Double {
return pow(M_E, -usingSpringWithDamping * x) * cos(initialSpringVelocity * x)
}
}
// ----------------------------
//
// TegAutolayoutConstraints.swift
//
// ----------------------------
//
// TegAlign.swift
//
// Collection of shortcuts to create autolayout constraints.
//
import UIKit
class TegAutolayoutConstraints {
class func centerX(_ viewOne: UIView, viewTwo: UIView,
constraintContainer: UIView) -> [NSLayoutConstraint] {
return center(viewOne, viewTwo: viewTwo, constraintContainer: constraintContainer, vertically: false)
}
@discardableResult
class func centerY(_ viewOne: UIView, viewTwo: UIView,
constraintContainer: UIView) -> [NSLayoutConstraint] {
return center(viewOne, viewTwo: viewTwo, constraintContainer: constraintContainer, vertically: true)
}
private class func center(_ viewOne: UIView, viewTwo: UIView,
constraintContainer: UIView, vertically: Bool = false) -> [NSLayoutConstraint] {
let attribute = vertically ? NSLayoutAttribute.centerY : NSLayoutAttribute.centerX
let constraint = NSLayoutConstraint(
item: viewOne,
attribute: attribute,
relatedBy: NSLayoutRelation.equal,
toItem: viewTwo,
attribute: attribute,
multiplier: 1,
constant: 0)
constraintContainer.addConstraint(constraint)
return [constraint]
}
@discardableResult
class func alignSameAttributes(_ item: AnyObject, toItem: AnyObject,
constraintContainer: UIView, attribute: NSLayoutAttribute, margin: CGFloat = 0) -> [NSLayoutConstraint] {
let constraint = NSLayoutConstraint(
item: item,
attribute: attribute,
relatedBy: NSLayoutRelation.equal,
toItem: toItem,
attribute: attribute,
multiplier: 1,
constant: margin)
constraintContainer.addConstraint(constraint)
return [constraint]
}
class func alignVerticallyToLayoutGuide(_ item: AnyObject, onTop: Bool,
layoutGuide: UILayoutSupport, constraintContainer: UIView,
margin: CGFloat = 0) -> [NSLayoutConstraint] {
let constraint = NSLayoutConstraint(
item: layoutGuide,
attribute: onTop ? NSLayoutAttribute.bottom : NSLayoutAttribute.top,
relatedBy: NSLayoutRelation.equal,
toItem: item,
attribute: onTop ? NSLayoutAttribute.top : NSLayoutAttribute.bottom,
multiplier: 1,
constant: margin)
constraintContainer.addConstraint(constraint)
return [constraint]
}
class func aspectRatio(_ view: UIView, ratio: CGFloat) {
let constraint = NSLayoutConstraint(
item: view,
attribute: NSLayoutAttribute.width,
relatedBy: NSLayoutRelation.equal,
toItem: view,
attribute: NSLayoutAttribute.height,
multiplier: ratio,
constant: 0)
view.addConstraint(constraint)
}
class func fillParent(_ view: UIView, parentView: UIView, margin: CGFloat = 0, vertically: Bool = false) {
var marginFormat = ""
if margin != 0 {
marginFormat = "-\(margin)-"
}
var format = "|\(marginFormat)[view]\(marginFormat)|"
if vertically {
format = "V:" + format
}
let constraints = NSLayoutConstraint.constraints(withVisualFormat: format,
options: [], metrics: nil,
views: ["view": view])
parentView.addConstraints(constraints)
}
@discardableResult
class func viewsNextToEachOther(_ views: [UIView],
constraintContainer: UIView, margin: CGFloat = 0,
vertically: Bool = false) -> [NSLayoutConstraint] {
if views.count < 2 { return [] }
var constraints = [NSLayoutConstraint]()
for (index, view) in views.enumerated() {
if index >= views.count - 1 { break }
let viewTwo = views[index + 1]
constraints += twoViewsNextToEachOther(view, viewTwo: viewTwo,
constraintContainer: constraintContainer, margin: margin, vertically: vertically)
}
return constraints
}
class func twoViewsNextToEachOther(_ viewOne: UIView, viewTwo: UIView,
constraintContainer: UIView, margin: CGFloat = 0,
vertically: Bool = false) -> [NSLayoutConstraint] {
var marginFormat = ""
if margin != 0 {
marginFormat = "-\(margin)-"
}
var format = "[viewOne]\(marginFormat)[viewTwo]"
if vertically {
format = "V:" + format
}
let constraints = NSLayoutConstraint.constraints(withVisualFormat: format,
options: [], metrics: nil,
views: [ "viewOne": viewOne, "viewTwo": viewTwo ])
constraintContainer.addConstraints(constraints)
return constraints
}
class func equalWidth(_ viewOne: UIView, viewTwo: UIView,
constraintContainer: UIView) -> [NSLayoutConstraint] {
let constraints = NSLayoutConstraint.constraints(withVisualFormat: "[viewOne(==viewTwo)]",
options: [], metrics: nil,
views: ["viewOne": viewOne, "viewTwo": viewTwo])
constraintContainer.addConstraints(constraints)
return constraints
}
@discardableResult
class func height(_ view: UIView, value: CGFloat) -> [NSLayoutConstraint] {
return widthOrHeight(view, value: value, isWidth: false)
}
@discardableResult
class func width(_ view: UIView, value: CGFloat) -> [NSLayoutConstraint] {
return widthOrHeight(view, value: value, isWidth: true)
}
private class func widthOrHeight(_ view: UIView, value: CGFloat,
isWidth: Bool) -> [NSLayoutConstraint] {
let attribute = isWidth ? NSLayoutAttribute.width : NSLayoutAttribute.height
let constraint = NSLayoutConstraint(
item: view,
attribute: attribute,
relatedBy: NSLayoutRelation.equal,
toItem: nil,
attribute: NSLayoutAttribute.notAnAttribute,
multiplier: 1,
constant: value)
view.addConstraint(constraint)
return [constraint]
}
}
// ----------------------------
//
// UnderKeyboardDistrib.swift
//
// ----------------------------
//
// An iOS libary for moving content from under the keyboard.
//
// https://github.com/marketplacer/UnderKeyboard
//
// This file was automatically generated by combining multiple Swift source files.
//
// ----------------------------
//
// UnderKeyboardLayoutConstraint.swift
//
// ----------------------------
import UIKit
/**
Adjusts the length (constant value) of the bottom layout constraint when keyboard shows and hides.
*/
@objc public class UnderKeyboardLayoutConstraint: NSObject {
private weak var bottomLayoutConstraint: NSLayoutConstraint?
private weak var bottomLayoutGuide: UILayoutSupport?
private var keyboardObserver = UnderKeyboardObserver()
private var initialConstraintConstant: CGFloat = 0
private var minMargin: CGFloat = 10
private var viewToAnimate: UIView?
/// Creates an instance of the class
public override init() {
super.init()
keyboardObserver.willAnimateKeyboard = keyboardWillAnimate
keyboardObserver.animateKeyboard = animateKeyboard
keyboardObserver.start()
}
deinit {
stop()
}
/// Stop listening for keyboard notifications.
public func stop() {
keyboardObserver.stop()
}
/**
Supply a bottom Auto Layout constraint. Its constant value will be adjusted by the height of the keyboard when it appears and hides.
- parameter bottomLayoutConstraint: Supply a bottom layout constraint. Its constant value will be adjusted when keyboard is shown and hidden.
- parameter view: Supply a view that will be used to animate the constraint. It is usually the superview containing the view with the constraint.
- parameter minMargin: Specify the minimum margin between the keyboard and the bottom of the view the constraint is attached to. Default: 10.
- parameter bottomLayoutGuide: Supply an optional bottom layout guide (like a tab bar) that will be taken into account during height calculations.
*/
public func setup(_ bottomLayoutConstraint: NSLayoutConstraint,
view: UIView, minMargin: CGFloat = 10,
bottomLayoutGuide: UILayoutSupport? = nil) {
initialConstraintConstant = bottomLayoutConstraint.constant
self.bottomLayoutConstraint = bottomLayoutConstraint
self.minMargin = minMargin
self.bottomLayoutGuide = bottomLayoutGuide
self.viewToAnimate = view
// Keyboard is already open when setup is called
if let currentKeyboardHeight = keyboardObserver.currentKeyboardHeight
, currentKeyboardHeight > 0 {
keyboardWillAnimate(currentKeyboardHeight)
}
}
func keyboardWillAnimate(_ height: CGFloat) {
guard let bottomLayoutConstraint = bottomLayoutConstraint else { return }
let layoutGuideHeight = bottomLayoutGuide?.length ?? 0
let correctedHeight = height - layoutGuideHeight
if height > 0 {
let newConstantValue = correctedHeight + minMargin
if newConstantValue > initialConstraintConstant {
// Keyboard height is bigger than the initial constraint length.
// Increase constraint length.
bottomLayoutConstraint.constant = newConstantValue
} else {
// Keyboard height is NOT bigger than the initial constraint length.
// Show the initial constraint length.
bottomLayoutConstraint.constant = initialConstraintConstant
}
} else {
bottomLayoutConstraint.constant = initialConstraintConstant
}
}
func animateKeyboard(_ height: CGFloat) {
viewToAnimate?.layoutIfNeeded()
}
}
// ----------------------------
//
// UnderKeyboardObserver.swift
//
// ----------------------------
import UIKit
/**
Detects appearance of software keyboard and calls the supplied closures that can be used for changing the layout and moving view from under the keyboard.
*/
public final class UnderKeyboardObserver: NSObject {
public typealias AnimationCallback = (_ height: CGFloat) -> ()
let notificationCenter: NotificationCenter
/// Function that will be called before the keyboard is shown and before animation is started.
public var willAnimateKeyboard: AnimationCallback?
/// Function that will be called inside the animation block. This can be used to call `layoutIfNeeded` on the view.
public var animateKeyboard: AnimationCallback?
/// Current height of the keyboard. Has value `nil` if unknown.
public var currentKeyboardHeight: CGFloat?
/// Creates an instance of the class
public override init() {
notificationCenter = NotificationCenter.default
super.init()
}
deinit {
stop()
}
/// Start listening for keyboard notifications.
public func start() {
stop()
notificationCenter.addObserver(self, selector: #selector(UnderKeyboardObserver.keyboardNotification(_:)), name:NSNotification.Name.UIKeyboardWillShow, object: nil);
notificationCenter.addObserver(self, selector: #selector(UnderKeyboardObserver.keyboardNotification(_:)), name:NSNotification.Name.UIKeyboardWillHide, object: nil);
}
/// Stop listening for keyboard notifications.
public func stop() {
notificationCenter.removeObserver(self)
}
// MARK: - Notification
func keyboardNotification(_ notification: Notification) {
let isShowing = notification.name == NSNotification.Name.UIKeyboardWillShow
if let userInfo = (notification as NSNotification).userInfo,
let height = (userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue.height,
let duration: TimeInterval = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue,
let animationCurveRawNSN = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber {
let correctedHeight = isShowing ? height : 0
willAnimateKeyboard?(correctedHeight)
UIView.animate(withDuration: duration,
delay: TimeInterval(0),
options: UIViewAnimationOptions(rawValue: animationCurveRawNSN.uintValue),
animations: { [weak self] in
self?.animateKeyboard?(correctedHeight)
},
completion: nil
)
currentKeyboardHeight = correctedHeight
}
}
}
| mit |
sdhzwm/WMMatchbox | WMMatchbox/WMMatchbox/Classes/Topic(话题)/Controller/WMTopController.swift | 1 | 3713 | //
// WMTopController.swift
// WMMatchbox
//
// Created by 王蒙 on 15/7/21.
// Copyright © 2015年 wm. All rights reserved.
//
import UIKit
extension UIImage{
class func imageWithOriRenderingImage(imageName:String) -> UIImage{
let image = UIImage(named: imageName)
return (image?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal))!
}
}
class WMTopController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
//设置leftBarButtonItem
self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: (UIImage.imageWithOriRenderingImage("Social_GoToGift")), style: UIBarButtonItemStyle.Done, target: self, action: "leftBtnClick")
//设置rightBarButtonItem
self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: (UIImage.imageWithOriRenderingImage("creatTopic")), style: UIBarButtonItemStyle.Done, target: self, action: "rightBtnClick")
}
func leftBtnClick(){
print("这是左边")
}
func rightBtnClick(){
print("这是右边")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 0
}
/*
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| apache-2.0 |
practicalswift/swift | validation-test/compiler_crashers_fixed/01656-swift-astcontext-getconformsto.swift | 65 | 509 | // 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
// RUN: not %target-swift-frontend %s -typecheck
class A : Collection where H) {
}
protocol a {
enum A = {
}
typealias B : B<T> {
func b() -> {
}
}
init() -> {
| apache-2.0 |
AlexeyGolovenkov/DevHelper | DevHelper/Ext/SwtExtensionCommand.swift | 1 | 1163 | //
// SwiftExtensionCommand.swift
// DevHelperContainer
//
// Created by Alex Golovenkov on 05/02/2019.
// Copyright © 2019 Alexey Golovenkov. All rights reserved.
//
import Cocoa
import XcodeKit
class SwtExtensionCommand: NSObject, XCSourceEditorCommand {
func perform(with invocation: XCSourceEditorCommandInvocation, completionHandler: @escaping (Error?) -> Void ) {
guard invocation.buffer.selections.count > 0 else {
completionHandler(nil)
return
}
let selection = invocation.buffer.selections[0] as? XCSourceTextRange
guard let range = DHTextRange(textRange: selection) else {
completionHandler(nil)
return
}
let newSelection = invocation.buffer.lines.addSwiftExtension(for: range.start)
if let textSelection = selection {
textSelection.start.column = newSelection.start.column
textSelection.start.line = newSelection.start.line
textSelection.end.column = newSelection.end.column
textSelection.end.line = newSelection.end.line
}
completionHandler(nil)
}
}
| mit |
blockchain/My-Wallet-V3-iOS | Modules/FeatureInterest/Sources/FeatureInterestUI/Dashboard/InterestDashboardAnnouncementViewController.swift | 1 | 4105 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import PlatformUIKit
public final class InterestDashboardAnnouncementViewController: UIViewController {
private let tableView = SelfSizingTableView()
private let presenter: InterestDashboardAnnouncementPresenting
public init(presenter: InterestDashboardAnnouncementPresenting) {
self.presenter = presenter
super.init(nibName: nil, bundle: nil)
}
@available(*, unavailable)
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Lifecycle
override public func loadView() {
view = UIView()
view.backgroundColor = .white
}
override public func viewDidLoad() {
super.viewDidLoad()
setupTableView()
tableView.reloadData()
}
private func setupTableView() {
view.addSubview(tableView)
tableView.layoutToSuperview(axis: .horizontal, usesSafeAreaLayoutGuide: true)
tableView.layoutToSuperview(axis: .vertical, usesSafeAreaLayoutGuide: true)
tableView.tableFooterView = UIView()
tableView.estimatedRowHeight = 100
tableView.rowHeight = UITableView.automaticDimension
tableView.register(AnnouncementTableViewCell.self)
tableView.register(BadgeNumberedTableViewCell.self)
tableView.registerNibCell(ButtonsTableViewCell.self, in: .platformUIKit)
tableView.register(LineItemTableViewCell.self)
tableView.register(FooterTableViewCell.self)
tableView.separatorColor = .clear
tableView.delegate = self
tableView.dataSource = self
}
}
// MARK: - UITableViewDelegate, UITableViewDataSource
extension InterestDashboardAnnouncementViewController: UITableViewDelegate, UITableViewDataSource {
public func tableView(
_ tableView: UITableView,
numberOfRowsInSection section: Int
) -> Int {
presenter.cellCount
}
public func tableView(
_ tableView: UITableView,
cellForRowAt indexPath: IndexPath
) -> UITableViewCell {
let cell: UITableViewCell
let type = presenter.cellArrangement[indexPath.row]
switch type {
case .announcement(let viewModel):
cell = announcement(for: indexPath, viewModel: viewModel)
case .numberedItem(let viewModel):
cell = numberedCell(for: indexPath, viewModel: viewModel)
case .buttons(let buttons):
cell = buttonsCell(for: indexPath, buttons: buttons)
case .item(let presenter):
cell = lineItemCell(for: indexPath, presenter: presenter)
case .footer(let presenter):
cell = footerCell(for: indexPath, presenter: presenter)
}
return cell
}
// MARK: - Accessors
private func announcement(for indexPath: IndexPath, viewModel: AnnouncementCardViewModel) -> UITableViewCell {
let cell = tableView.dequeue(AnnouncementTableViewCell.self, for: indexPath)
cell.viewModel = viewModel
return cell
}
private func numberedCell(for indexPath: IndexPath, viewModel: BadgeNumberedItemViewModel) -> UITableViewCell {
let cell = tableView.dequeue(BadgeNumberedTableViewCell.self, for: indexPath)
cell.viewModel = viewModel
return cell
}
private func lineItemCell(for indexPath: IndexPath, presenter: LineItemCellPresenting) -> UITableViewCell {
let cell = tableView.dequeue(LineItemTableViewCell.self, for: indexPath)
cell.presenter = presenter
return cell
}
private func footerCell(for indexPath: IndexPath, presenter: FooterTableViewCellPresenter) -> FooterTableViewCell {
let cell = tableView.dequeue(FooterTableViewCell.self, for: indexPath)
cell.presenter = presenter
return cell
}
private func buttonsCell(for indexPath: IndexPath, buttons: [ButtonViewModel]) -> UITableViewCell {
let cell = tableView.dequeue(ButtonsTableViewCell.self, for: indexPath)
cell.models = buttons
return cell
}
}
| lgpl-3.0 |
blockchain/My-Wallet-V3-iOS | Modules/BlockchainComponentLibrary/Sources/BlockchainComponentLibrary/Utilities/View+If.swift | 1 | 3152 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import SwiftUI
/// Helpers for conditionally applying modifiers
extension View {
/// Conditionally apply modifiers to a given view
///
/// See `ifLet` for version that takes an optional.
///
/// - Parameters:
/// - condition: Condition returning true/false for execution of the following blocks
/// - then: If condition is true, apply modifiers here.
/// - else: If condition is false, apply modifiers here.
/// - Returns: Self with modifiers applied accordingly.
@ViewBuilder public func `if`<Then: View, Else: View>(
_ condition: @autoclosure () -> Bool,
@ViewBuilder then: (Self) -> Then,
@ViewBuilder else: (Self) -> Else
) -> some View {
if condition() {
then(self)
} else {
`else`(self)
}
}
/// Conditionally apply modifiers to a given view
///
/// See `ifLet` for version that takes an optional.
///
/// - Parameters:
/// - condition: Condition returning true/false for execution of the following blocks
/// - then: If condition is true, apply modifiers here.
/// - Returns: Self with modifiers applied, or unchanged self if condition was false
@ViewBuilder public func `if`<Then: View>(
_ condition: @autoclosure () -> Bool,
@ViewBuilder then: (Self) -> Then
) -> some View {
if condition() {
then(self)
} else {
self
}
}
/// Conditionally apply modifiers to a given view
/// - Parameters:
/// - optional: Optional value to be ifLetped.
/// - then: Apply modifiers with ifLetped optional.
/// - else: Apply modifiers if optional is nil
/// - Returns: Self with modifiers applied accordingly.
@ViewBuilder public func ifLet<Value, Then: View, Else: View>(
_ optional: Value?,
@ViewBuilder then: (Self, Value) -> Then,
@ViewBuilder else: (Self) -> Else
) -> some View {
if let value = optional {
then(self, value)
} else {
`else`(self)
}
}
/// Conditionally apply modifiers to a given view
/// - Parameters:
/// - optional: Optional value to be ifLetped.
/// - then: Apply modifiers with ifLetped optional.
/// - Returns: Self with modifiers applied, or unchanged self if optional is nil
@ViewBuilder public func ifLet<Value, Then: View>(
_ optional: Value?,
@ViewBuilder then: (Self, Value) -> Then
) -> some View {
if let value = optional {
then(self, value)
} else {
self
}
}
/// apply the closure to a given view, allows you to jump out of the current context
/// and provide conditional modifiers like #if os(iOS) to decide what should be applied to the view
/// - Parameters:
/// - then: call closure with self
/// - Returns: Self with modifiers applied,
@ViewBuilder public func apply<Then: View>(
@ViewBuilder _ then: (Self) -> Then
) -> some View {
then(self)
}
}
| lgpl-3.0 |
lukevanin/OCRAI | CardScanner/UICollectionView+Photos.swift | 1 | 1603 | //
// UICollectionView+Photos.swift
// CardScanner
//
// Created by Luke Van In on 2017/03/07.
// Copyright © 2017 Luke Van In. All rights reserved.
//
import UIKit
import Photos
extension UICollectionView {
func applyChanges(_ changes: PHFetchResultChangeDetails<PHAsset>, inSection section: Int, completion: ((Bool) -> Void)? = nil) {
if changes.hasIncrementalChanges {
performBatchUpdates({ [weak self] in
if let indexSet = changes.removedIndexes {
let indexPaths = indexSet.map { IndexPath(item: $0, section: section) }
self?.deleteItems(at: indexPaths)
}
if let indexSet = changes.insertedIndexes {
let indexPaths = indexSet.map { IndexPath(item: $0, section: section) }
self?.insertItems(at: indexPaths)
}
if let indexSet = changes.changedIndexes {
let indexPaths = indexSet.map { IndexPath(item: $0, section: section) }
self?.reloadItems(at: indexPaths)
}
if changes.hasMoves {
changes.enumerateMoves {
self?.moveItem(
at: IndexPath(item: $0, section: 0),
to: IndexPath(item: $1, section: 0)
)
}
}
}, completion: completion)
}
else {
reloadData()
}
}
}
| mit |
HarukaMa/iina | iina/UpdateChecker.swift | 1 | 4706 | //
// UpdateChecker.swift
// iina
//
// Created by lhc on 12/1/2017.
// Copyright © 2017 lhc. All rights reserved.
//
import Foundation
import Just
class UpdateChecker {
enum State {
case updateDetected, noUpdate, error, networkError
}
struct GithubTag {
var name: String
var numericName: [Int]
var commitSHA: String
var commitUrl: String
var zipUrl: String
var tarUrl: String
}
static let githubTagApiPath = "https://api.github.com/repos/lhc70000/iina/tags"
static func checkUpdate(alertIfOfflineOrNoUpdate: Bool = true) {
var tagList: [GithubTag] = []
Just.get(githubTagApiPath) { response in
// network error
guard response.ok else {
if response.statusCode == nil {
// if network not available
if alertIfOfflineOrNoUpdate {
showUpdateAlert(.networkError, message: response.reason)
}
} else {
// if network error
showUpdateAlert(.error, message: response.reason)
}
return
}
guard let tags = response.json as? [[String: Any]] else {
showUpdateAlert(.error, message: "Wrong response format")
return
}
// parse tags
tags.forEach { tag in
guard let name = tag["name"] as? String else { return }
// discard tags like "v0.0.1-build2"
guard Regex.tagVersion.matches(name) else { return }
let numericName = Regex.tagVersion.captures(in: name)[1].components(separatedBy: ".").map { str -> Int in
return Int(str) ?? 0
}
guard let commitInfo = tag["commit"] as? [String: String] else { return }
tagList.append(GithubTag(name: name,
numericName: numericName,
commitSHA: commitInfo["sha"] ?? "",
commitUrl: commitInfo["url"] ?? "",
zipUrl: tag["zipball_url"] as! String,
tarUrl: tag["tarball_url"] as! String))
}
// tagList should not be empty
guard tagList.count > 0 else {
showUpdateAlert(.error, message: "Wrong response format")
return
}
// get latest
let latest = tagList.sorted { $1.numericName.lexicographicallyPrecedes($0.numericName) }.first!.numericName
// get current
let currentVer = Bundle.main.infoDictionary!["CFBundleShortVersionString"] as! String
let current = currentVer.components(separatedBy: ".").map { str -> Int in
return Int(str) ?? 0
}
// compare
let hasUpdate = current.lexicographicallyPrecedes(latest)
if hasUpdate {
showUpdateAlert(.updateDetected)
} else if alertIfOfflineOrNoUpdate {
showUpdateAlert(.noUpdate)
}
}
}
private static func showUpdateAlert(_ state: State, message: String? = nil) {
DispatchQueue.main.sync {
let alert = NSAlert()
let isError = state == .error || state == .networkError
let title: String
var mainMessage: String
switch state {
case .updateDetected:
title = NSLocalizedString("update.title_update_found", comment: "Title")
mainMessage = NSLocalizedString("update.update_found", comment: "Update found")
case .noUpdate:
title = NSLocalizedString("update.title_no_update", comment: "Title")
mainMessage = NSLocalizedString("update.no_update", comment: "No update")
case .error, .networkError:
title = NSLocalizedString("update.title_error", comment: "Title")
mainMessage = NSLocalizedString("update.check_failed", comment: "Error")
alert.alertStyle = .warning
}
if let message = message { mainMessage.append("\n\n\(message)") }
alert.alertStyle = isError ? .warning : .informational
alert.messageText = title
alert.informativeText = mainMessage
if state == .noUpdate {
// if no update
alert.addButton(withTitle: "OK")
alert.runModal()
} else {
// if require user action
alert.addButton(withTitle: NSLocalizedString("update.dl_from_website", comment: "Website"))
alert.addButton(withTitle: NSLocalizedString("update.dl_from_github", comment: "Github"))
alert.addButton(withTitle: "Cancel")
let result = alert.runModal()
if result == NSAlertFirstButtonReturn {
// website
NSWorkspace.shared().open(URL(string: AppData.websiteLink)!)
} else if result == NSAlertSecondButtonReturn {
// github
NSWorkspace.shared().open(URL(string: AppData.githubReleaseLink)!)
}
}
}
}
}
| gpl-3.0 |
JerrySir/YCOA | YCOA/Main/My/View/MyInfoDescriptionTableViewCell.swift | 1 | 2230 | //
// MyInfoDescriptionTableViewCell.swift
// YCOA
//
// Created by Jerry on 2016/12/14.
// Copyright © 2016年 com.baochunsteel. All rights reserved.
//
import UIKit
import ReactiveCocoa
class MyInfoDescriptionTableViewCell: UITableViewCell {
@IBOutlet weak var headIconImageView: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var departmentLabel: UILabel!
@IBOutlet weak var positionLabel: UILabel!
@IBOutlet weak var accountLabel: UILabel!
@IBOutlet weak var companyLabel: UILabel!
@IBOutlet weak var uidLabel: UILabel!
@IBOutlet weak var logoutButton: UIButton!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func configure(headIconURL: String?, name: String?, department: String?, position: String?, account: String?, company: String?, uid: String?)
{
self.nameLabel.text = name
self.departmentLabel.text = department
self.positionLabel.text = position
self.accountLabel.text = account
self.companyLabel.text = company
self.uidLabel.text = uid
guard headIconURL != nil && headIconURL!.utf8.count > 0 else {
self.headIconImageView.image = #imageLiteral(resourceName: "contact_place_holder_icon")
return
}
self.headIconImageView.sd_setImage(with: URL(string: headIconURL!), placeholderImage: #imageLiteral(resourceName: "contact_place_holder_icon"), options: .lowPriority)
//样式
self.headIconImageView.layer.masksToBounds = true
self.headIconImageView.layer.cornerRadius = JRSCREEN_WIDTH / 3.0 / 2.0
self.headIconImageView.layer.borderWidth = 2.0
self.headIconImageView.layer.borderColor = UIColor.white.cgColor
}
func configureLogout(action: @escaping () -> Void) {
self.logoutButton.rac_signal(for: .touchUpInside).take(until: self.rac_prepareForReuseSignal).subscribeNext { (sender) in
action()
}
}
}
| mit |
ncsrobin/Fuber | SplashScreenUI/Constants.swift | 1 | 1603 | /**
* Copyright (c) 2016 Razeware LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import Foundation
/// The total animation duration of the splash animation
let kAnimationDuration: TimeInterval = 3.0
/// The length of the second part of the duration
let kAnimationDurationDelay: TimeInterval = 0.5
/// The offset between the AnimatedULogoView and the background Grid
let kAnimationTimeOffset: CFTimeInterval = 0.35 * kAnimationDuration
/// The ripple magnitude. Increase by small amounts for amusement ( <= .2) :]
let kRippleMagnitudeMultiplier: CGFloat = 0.025
| apache-2.0 |
lucasmcdonald3/HomeRemote | HomeRemote/ButtonRemoteViewController.swift | 1 | 505 | //
// StepperRemoteViewController.swift
// HomeRemote
//
// Created by Lucas McDonald on 2/25/17.
// Copyright © 2017 Lucas McDonald.
//
import Foundation
import UIKit
class ButtonRemoteViewController: RemoteViewController {
@IBOutlet weak var remoteButton: UIButton!
@IBAction func buttonPressed(_ sender: Any) {
session.sendCommand("cd LEDController; python SSHtoHomeRemote.py")
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
| apache-2.0 |
sjf0213/DingShan | DingshanSwift/DingshanSwift/StageMenuView.swift | 1 | 7959 | //
// StageMenuView.swift
// DingshanSwift
//
// Created by song jufeng on 15/11/30.
// Copyright © 2015年 song jufeng. All rights reserved.
//
import Foundation
class StageMenuView : UIView{
var tapItemHandler : ((index:Int) -> Void)?// 用户点击处理
var userSelectIndex:Int = 0
var mainBtn = GalleryMenuButtton()
var subItemContainer = UIView()// 按钮容器
var mask:UIView?// 黑色半透明背景,相应点击收起
var container_h:CGFloat = 0.0
// 菜单内容的配置
var menuConfig = [AnyObject](){
didSet{
if menuConfig.count > 0{
if let one = menuConfig[0] as? [NSObject:AnyObject]{
if let title = one["title"] as? String{
self.mainBtn.btnText = title
}
}
}
self.mainBtn.curSelected = false
}
}
// 菜单的展开与收起
var isExpanded:Bool = false {
didSet{
if isExpanded{
// UIView.animateWithDuration(0.2, delay: 0.0, options: UIViewAnimationOptions.CurveEaseIn, animations: { () -> Void in
// //
// }, completion: { (finished) -> Void in
// self.subItemContainer.layer.position = CGPoint(x: 160, y: 20)
// })
self.frame = CGRectMake(0, 20, UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.height-20)
self.mainBtn.frame = CGRect(x: 50, y: 0, width: UIScreen.mainScreen().bounds.width - 100, height: TopBar_H - 21)
print("- - - ****2222 self.mainBtn.frame = \(self.mainBtn.frame)")
self.mainBtn.curSelected = true
// 点击菜单覆盖的黑色半透明区域,收起菜单
self.mask = UIView(frame: CGRect(x: 0, y: TopBar_H-20, width: UIScreen.mainScreen().bounds.width, height: UIScreen.mainScreen().bounds.height-TopBar_H+20))
self.mask?.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.5)
self.mask?.alpha = 0.0
let tapRec = UITapGestureRecognizer(target: self, action: Selector("resetMenu"))
self.mask?.addGestureRecognizer(tapRec)
self.insertSubview(self.mask!, belowSubview: self.subItemContainer)
UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.3, options:UIViewAnimationOptions([.AllowUserInteraction, .BeginFromCurrentState]), animations: { () -> Void in
self.subItemContainer.frame = CGRectMake(0, TopBar_H-20, UIScreen.mainScreen().bounds.width, self.container_h)
self.mask?.alpha = 1.0
}, completion: { (finished) -> Void in
print("self.mainBtn.frame = \(self.mainBtn.frame)")
})
}else{
// UIView.animateWithDuration(0.2, delay: 0.0, options: UIViewAnimationOptions.CurveEaseIn, animations: { () -> Void in
// //
// }, completion: { (finished) -> Void in
// self.subItemContainer.layer.position = CGPoint(x: 160, y: 160)
// })
self.frame = CGRectMake(50, 20, UIScreen.mainScreen().bounds.width - 100, TopBar_H - 20)
self.mainBtn.frame = CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width - 100, height: TopBar_H - 21)
UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.3, options:UIViewAnimationOptions([.AllowUserInteraction, .BeginFromCurrentState]), animations: { () -> Void in
self.subItemContainer.frame = CGRect(x: 0, y: TopBar_H-20, width: UIScreen.mainScreen().bounds.width, height: 0)
}, completion: { (finished) -> Void in
self.mainBtn.curSelected = false
self.mask?.removeFromSuperview()
self.mask = nil
})
}
}
}
// MARK: init
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(frame aRect: CGRect) {
super.init(frame: aRect);
self.backgroundColor = UIColor.clearColor()
self.clipsToBounds = true
self.subItemContainer = UIView(frame: CGRect(x: 0, y: TopBar_H-20, width: UIScreen.mainScreen().bounds.width, height: 0))
self.subItemContainer.backgroundColor = UIColor.whiteColor()
self.subItemContainer.clipsToBounds = true
self.addSubview(self.subItemContainer)
self.mainBtn = GalleryMenuButtton(frame: CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width - 100, height: TopBar_H - 21))
self.mainBtn.backgroundColor = NAVI_COLOR
self.mainBtn.setTitleColor(UIColor.blackColor(), forState:.Normal)
self.mainBtn.addTarget(self, action: Selector("onTapMainBtn:"), forControlEvents: UIControlEvents.TouchUpInside)
self.addSubview(self.mainBtn)
self.isExpanded = false
}
override func layoutSubviews() {
// self.btnBgContainer?.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: GalleryMenuBar_H)
}
// 复位所有菜单状态
func resetMenu(){
// 收起菜单
self.isExpanded = false
// 清空二级项
for v in self.subItemContainer.subviews{
v.removeFromSuperview()
}
}
// 点击按钮
func onTapMainBtn(sender:UIButton) {
if(self.isExpanded){
self.resetMenu()
return;
}
print(sender, terminator: "")
// 生成所有菜单项
let w:CGFloat = UIScreen.mainScreen().bounds.width / 2
let h:CGFloat = 58
for (var i = 0; i < self.menuConfig.count; i++){
if let one = self.menuConfig[i] as? [NSObject:AnyObject]{
let row:Int = i/2
let col:Int = i%2
let rect = CGRect(x: w * CGFloat(col), y: h * CGFloat(row), width: w, height: h)
let btn = StageMenuItem(frame: rect)
btn.tag = i
if let t = one["title"] as? String{
btn.setTitle(t, forState: UIControlState.Normal)
}
// 显示当前正在选中的项目
if userSelectIndex == i{
btn.curSelected = true
}
btn.addTarget(self, action: Selector("onTapItem:"), forControlEvents: UIControlEvents.TouchUpInside)
self.subItemContainer.addSubview(btn)
}
}
let rowCount:Int = (self.menuConfig.count-1)/2 + 1
self.container_h = h*CGFloat(rowCount) + 10
self.isExpanded = true
}
// 点击二级菜单项
func onTapItem(item:GalleryMenuItem) {
print("----------sub menu items title:\(item.titleLabel?.text), tagIndex:\(item.tag)")
// 低亮其他
for v in self.subItemContainer.subviews{
if let i = v as? GalleryMenuItem{
if i != item{
i.curSelected = false
}
}
}
// 高亮所选
item.curSelected = true
// 更新设置
userSelectIndex = item.tag
// 更新Btn显示
mainBtn.btnText = item.titleForState(UIControlState.Normal)!
// 点击动作,进入下一个页面
// dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.0 * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), {
self.resetMenu()
if (self.tapItemHandler != nil) {
self.tapItemHandler?(index:self.userSelectIndex)
}
// })
}
} | mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.