repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
MartinOSix/DemoKit | refs/heads/master | dSwift/SwiftSyntaxDemo/SwiftSyntaxDemo/ViewController_Function.swift | apache-2.0 | 1 | //
// ViewController_Function.swift
// SwiftSyntaxDemo
//
// Created by runo on 16/12/5.
// Copyright © 2016年 com.runo. All rights reserved.
//
import UIKit
class ViewController_Function: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.white
self.functionType1()
self.functionType2(Height: 10)
self.functionType3(Height: 10, Width: 20)
print("返回值\(self.functionType4(Height: 10, Width: 20))")
var sum = 10
self.functionType5(Sum: &sum)
print("sum=\(sum)")
self.functionType6(1, 2)
let value = self.functionType7()
print("第一个返回值\(value.a)")
print("第二个返回值\(value.b)")
//采用下标的方式返回
print("第一个返回值\(value.0)");
print("第二个返回值\(value.1)");
self.functionType8(fun: functionType4)
print("\(self.functionType5(Height: 1, Width: 2, Length: 3))")
print("函数嵌套\n\(functionType9())");
print("不定参数函数\n\(functionType11(parameters: 1,23,4,10))");
}
func functionType1(){
print("无参无返回值函数")
}
func functionType2(Height: Int){
print("带一个Int参数无返回值的函数\(Height)")
}
func functionType3(Height: Int, Width: Int){
print("带两个Int参数的函数\(Height)和\(Width)")
}
func functionType4(Height: Int, Width: Int) -> Int {
print("带两个Int参数的函数\(Height)和\(Width)返回两个数之和")
return Height + Width
}
func functionType5(Height: Int, Width: Int, Length: Int) -> Int {
print("函数重载")
return Height * Width * Length
}
func functionType5(Sum:inout Int) {
print("不管传进来的数是多少都会把原来的数改成0")
Sum = 0
}
//一般冒号前面是参数名,如果只有一个默认是外部参数名 “_”表示忽略名字 空格后面表示内部参数名
func functionType6(_ a:Int, _ b:Int) {
print("忽略外部参数名的函数\(a)和\(b)")
}
func functionType7() -> (a:Int,b:Int) {
print("元祖的形式返回两个参数")
return (1,2)
}
func functionType8(fun:(Int,Int)->Int) {
print("函数作为参数的形式执行结果为\(fun(10,20))")
}
/**函数嵌套
*item1
*item2
*/
func functionType9() -> Int {
func functionType10(num :Int) -> Int{
return num * num
}
return functionType10(num: 2)
}
///可变参数的函数
func functionType11(parameters :Int...) -> Int {
var sum = 0
for number in parameters {
sum = sum + number
}
return sum
}
}
| 1069e80df95a95094c20d531206cd837 | 22.851852 | 70 | 0.53882 | false | false | false | false |
Pluto-tv/RxSwift | refs/heads/master | RxSwift/Observable+Extensions.swift | mit | 1 | //
// Observable+Extensions.swift
// Rx
//
// Created by Krunoslav Zaher on 2/21/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
extension ObservableType {
/**
Subscribes an event handler to an observable sequence.
- parameter on: Action to invoke for each event in the observable sequence.
- returns: Subscription object used to unsubscribe from the observable sequence.
*/
@warn_unused_result(message="http://git.io/rxs.ud")
public func subscribe(on: (event: Event<E>) -> Void)
-> Disposable {
let observer = AnonymousObserver { e in
on(event: e)
}
return self.subscribeSafe(observer)
}
/**
Subscribes an element handler, an error handler, a completion handler and disposed handler to an observable sequence.
- parameter onNext: Action to invoke for each element in the observable sequence.
- parameter onError: Action to invoke upon errored termination of the observable sequence.
- parameter onCompleted: Action to invoke upon graceful termination of the observable sequence.
- parameter onDisposed: Action to invoke upon any type of termination of sequence (if the sequence has
gracefully completed, errored, or if the generation is cancelled by disposing subscription)
- returns: Subscription object used to unsubscribe from the observable sequence.
*/
@warn_unused_result(message="http://git.io/rxs.ud")
public func subscribe(onNext onNext: (E -> Void)? = nil, onError: (ErrorType -> Void)? = nil, onCompleted: (() -> Void)? = nil, onDisposed: (() -> Void)? = nil)
-> Disposable {
let disposable: Disposable
if let disposed = onDisposed {
disposable = AnonymousDisposable(disposed)
}
else {
disposable = NopDisposable.instance
}
let observer = AnonymousObserver<E> { e in
switch e {
case .Next(let value):
onNext?(value)
case .Error(let e):
onError?(e)
disposable.dispose()
case .Completed:
onCompleted?()
disposable.dispose()
}
}
return BinaryDisposable(
self.subscribeSafe(observer),
disposable
)
}
/**
Subscribes an element handler to an observable sequence.
- parameter onNext: Action to invoke for each element in the observable sequence.
- returns: Subscription object used to unsubscribe from the observable sequence.
*/
@warn_unused_result(message="http://git.io/rxs.ud")
public func subscribeNext(onNext: (E) -> Void)
-> Disposable {
let observer = AnonymousObserver<E> { e in
if case .Next(let value) = e {
onNext(value)
}
}
return self.subscribeSafe(observer)
}
/**
Subscribes an error handler to an observable sequence.
- parameter onRrror: Action to invoke upon errored termination of the observable sequence.
- returns: Subscription object used to unsubscribe from the observable sequence.
*/
@warn_unused_result(message="http://git.io/rxs.ud")
public func subscribeError(onError: (ErrorType) -> Void)
-> Disposable {
let observer = AnonymousObserver<E> { e in
if case .Error(let error) = e {
onError(error)
}
}
return self.subscribeSafe(observer)
}
/**
Subscribes a completion handler to an observable sequence.
- parameter onCompleted: Action to invoke upon graceful termination of the observable sequence.
- returns: Subscription object used to unsubscribe from the observable sequence.
*/
@warn_unused_result(message="http://git.io/rxs.ud")
public func subscribeCompleted(onCompleted: () -> Void)
-> Disposable {
let observer = AnonymousObserver<E> { e in
if case .Completed = e {
onCompleted()
}
}
return self.subscribeSafe(observer)
}
}
public extension ObservableType {
/**
All internal subscribe calls go through this method
*/
@warn_unused_result(message="http://git.io/rxs.ud")
func subscribeSafe<O: ObserverType where O.E == E>(observer: O) -> Disposable {
return self.subscribe(observer)
}
}
| 18f9d289c345d46e9f14887c3a5d9201 | 33.539063 | 164 | 0.628138 | false | false | false | false |
abertelrud/swift-package-manager | refs/heads/main | Sources/PackageModel/PackageIdentity.swift | apache-2.0 | 2 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2014-2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Foundation
import TSCBasic
/// The canonical identifier for a package, based on its source location.
public struct PackageIdentity: CustomStringConvertible {
/// A textual representation of this instance.
public let description: String
/// Creates a package identity from a string.
/// - Parameter value: A string used to identify a package.
init(_ value: String) {
self.description = value
}
/// Creates a package identity from a URL.
/// - Parameter url: The package's URL.
public init(url: URL) {
self.init(urlString: url.absoluteString)
}
/// Creates a package identity from a URL.
/// - Parameter urlString: The package's URL.
// FIXME: deprecate this
public init(urlString: String) {
self.description = PackageIdentityParser(urlString).description
}
/// Creates a package identity from a file path.
/// - Parameter path: An absolute path to the package.
public init(path: AbsolutePath) {
self.description = PackageIdentityParser(path.pathString).description
}
/// Creates a plain package identity for a root package
/// - Parameter value: A string used to identify a package, will be used unmodified
public static func plain(_ value: String) -> PackageIdentity {
PackageIdentity(value)
}
// TODO: formalize package registry identifier
public var scopeAndName: (scope: Scope, name: Name)? {
let components = description.split(separator: ".", maxSplits: 1, omittingEmptySubsequences: true)
guard components.count == 2,
let scope = Scope(components.first),
let name = Name(components.last)
else { return .none }
return (scope: scope, name: name)
}
}
extension PackageIdentity: Equatable, Comparable {
private func compare(to other: PackageIdentity) -> ComparisonResult {
return self.description.caseInsensitiveCompare(other.description)
}
public static func == (lhs: PackageIdentity, rhs: PackageIdentity) -> Bool {
return lhs.compare(to: rhs) == .orderedSame
}
public static func < (lhs: PackageIdentity, rhs: PackageIdentity) -> Bool {
return lhs.compare(to: rhs) == .orderedAscending
}
public static func > (lhs: PackageIdentity, rhs: PackageIdentity) -> Bool {
return lhs.compare(to: rhs) == .orderedDescending
}
}
extension PackageIdentity: Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(description.lowercased())
}
}
extension PackageIdentity: Codable {
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let description = try container.decode(String.self)
self.init(description)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self.description)
}
}
// MARK: -
extension PackageIdentity {
/// Provides a namespace for related packages within a package registry.
public struct Scope: LosslessStringConvertible, Hashable, Equatable, Comparable, ExpressibleByStringLiteral {
public let description: String
public init(validating description: String) throws {
guard !description.isEmpty else {
throw StringError("The minimum length of a package scope is 1 character.")
}
guard description.count <= 39 else {
throw StringError("The maximum length of a package scope is 39 characters.")
}
for (index, character) in zip(description.indices, description) {
guard character.isASCII,
character.isLetter ||
character.isNumber ||
character == "-"
else {
throw StringError("A package scope consists of alphanumeric characters and hyphens.")
}
if character.isPunctuation {
switch (index, description.index(after: index)) {
case (description.startIndex, _):
throw StringError("Hyphens may not occur at the beginning of a scope.")
case (_, description.endIndex):
throw StringError("Hyphens may not occur at the end of a scope.")
case (_, let nextIndex) where description[nextIndex].isPunctuation:
throw StringError("Hyphens may not occur consecutively within a scope.")
default:
continue
}
}
}
self.description = description
}
public init?(_ description: String) {
guard let scope = try? Scope(validating: description) else { return nil }
self = scope
}
fileprivate init?(_ substring: String.SubSequence?) {
guard let substring = substring else { return nil }
self.init(String(substring))
}
// MARK: - Equatable & Comparable
private func compare(to other: Scope) -> ComparisonResult {
// Package scopes are case-insensitive (for example, `mona` ≍ `MONA`).
return self.description.caseInsensitiveCompare(other.description)
}
public static func == (lhs: Scope, rhs: Scope) -> Bool {
return lhs.compare(to: rhs) == .orderedSame
}
public static func < (lhs: Scope, rhs: Scope) -> Bool {
return lhs.compare(to: rhs) == .orderedAscending
}
public static func > (lhs: Scope, rhs: Scope) -> Bool {
return lhs.compare(to: rhs) == .orderedDescending
}
// MARK: - Hashable
public func hash(into hasher: inout Hasher) {
hasher.combine(description.lowercased())
}
// MARK: - ExpressibleByStringLiteral
public init(stringLiteral value: StringLiteralType) {
try! self.init(validating: value)
}
}
/// Uniquely identifies a package in a scope
public struct Name: LosslessStringConvertible, Hashable, Equatable, Comparable, ExpressibleByStringLiteral {
public let description: String
public init(validating description: String) throws {
guard !description.isEmpty else {
throw StringError("The minimum length of a package name is 1 character.")
}
guard description.count <= 100 else {
throw StringError("The maximum length of a package name is 100 characters.")
}
for (index, character) in zip(description.indices, description) {
guard character.isASCII,
character.isLetter ||
character.isNumber ||
character == "-" ||
character == "_"
else {
throw StringError("A package name consists of alphanumeric characters, underscores, and hyphens.")
}
if character.isPunctuation {
switch (index, description.index(after: index)) {
case (description.startIndex, _):
throw StringError("Hyphens and underscores may not occur at the beginning of a name.")
case (_, description.endIndex):
throw StringError("Hyphens and underscores may not occur at the end of a name.")
case (_, let nextIndex) where description[nextIndex].isPunctuation:
throw StringError("Hyphens and underscores may not occur consecutively within a name.")
default:
continue
}
}
}
self.description = description
}
public init?(_ description: String) {
guard let name = try? Name(validating: description) else { return nil }
self = name
}
fileprivate init?(_ substring: String.SubSequence?) {
guard let substring = substring else { return nil }
self.init(String(substring))
}
// MARK: - Equatable & Comparable
private func compare(to other: Name) -> ComparisonResult {
// Package scopes are case-insensitive (for example, `LinkedList` ≍ `LINKEDLIST`).
return self.description.caseInsensitiveCompare(other.description)
}
public static func == (lhs: Name, rhs: Name) -> Bool {
return lhs.compare(to: rhs) == .orderedSame
}
public static func < (lhs: Name, rhs: Name) -> Bool {
return lhs.compare(to: rhs) == .orderedAscending
}
public static func > (lhs: Name, rhs: Name) -> Bool {
return lhs.compare(to: rhs) == .orderedDescending
}
// MARK: - Hashable
public func hash(into hasher: inout Hasher) {
hasher.combine(description.lowercased())
}
// MARK: - ExpressibleByStringLiteral
public init(stringLiteral value: StringLiteralType) {
try! self.init(validating: value)
}
}
}
// MARK: -
struct PackageIdentityParser {
/// A textual representation of this instance.
public let description: String
/// Instantiates an instance of the conforming type from a string representation.
public init(_ string: String) {
self.description = Self.computeDefaultName(fromLocation: string).lowercased()
}
/// Compute the default name of a package given its URL.
public static func computeDefaultName(fromURL url: URL) -> String {
Self.computeDefaultName(fromLocation: url.absoluteString)
}
/// Compute the default name of a package given its path.
public static func computeDefaultName(fromPath path: AbsolutePath) -> String {
Self.computeDefaultName(fromLocation: path.pathString)
}
/// Compute the default name of a package given its location.
public static func computeDefaultName(fromLocation url: String) -> String {
#if os(Windows)
let isSeparator : (Character) -> Bool = { $0 == "/" || $0 == "\\" }
#else
let isSeparator : (Character) -> Bool = { $0 == "/" }
#endif
// Get the last path component of the URL.
// Drop the last character in case it's a trailing slash.
var endIndex = url.endIndex
if let lastCharacter = url.last, isSeparator(lastCharacter) {
endIndex = url.index(before: endIndex)
}
let separatorIndex = url[..<endIndex].lastIndex(where: isSeparator)
let startIndex = separatorIndex.map { url.index(after: $0) } ?? url.startIndex
var lastComponent = url[startIndex..<endIndex]
// Strip `.git` suffix if present.
if lastComponent.hasSuffix(".git") {
lastComponent = lastComponent.dropLast(4)
}
return String(lastComponent)
}
}
/// A canonicalized package location.
///
/// A package may declare external packages as dependencies in its manifest.
/// Each external package is uniquely identified by the location of its source code.
///
/// An external package dependency may itself have one or more external package dependencies,
/// known as _transitive dependencies_.
/// When multiple packages have dependencies in common,
/// Swift Package Manager determines which version of that package should be used
/// (if any exist that satisfy all specified requirements)
/// in a process called package resolution.
///
/// External package dependencies are located by a URL
/// (which may be an implicit `file://` URL in the form of a file path).
/// For the purposes of package resolution,
/// package URLs are case-insensitive (mona ≍ MONA)
/// and normalization-insensitive (n + ◌̃ ≍ ñ).
/// Swift Package Manager takes additional steps to canonicalize URLs
/// to resolve insignificant differences between URLs.
/// For example,
/// the URLs `https://example.com/Mona/LinkedList` and `[email protected]:mona/linkedlist`
/// are equivalent, in that they both resolve to the same source code repository,
/// despite having different scheme, authority, and path components.
///
/// The `PackageIdentity` type canonicalizes package locations by
/// performing the following operations:
///
/// * Removing the scheme component, if present
/// ```
/// https://example.com/mona/LinkedList → example.com/mona/LinkedList
/// ```
/// * Removing the userinfo component (preceded by `@`), if present:
/// ```
/// [email protected]/mona/LinkedList → example.com/mona/LinkedList
/// ```
/// * Removing the port subcomponent, if present:
/// ```
/// example.com:443/mona/LinkedList → example.com/mona/LinkedList
/// ```
/// * Replacing the colon (`:`) preceding the path component in "`scp`-style" URLs:
/// ```
/// [email protected]:mona/LinkedList.git → example.com/mona/LinkedList
/// ```
/// * Expanding the tilde (`~`) to the provided user, if applicable:
/// ```
/// ssh://[email protected]/~/LinkedList.git → example.com/~mona/LinkedList
/// ```
/// * Removing percent-encoding from the path component, if applicable:
/// ```
/// example.com/mona/%F0%9F%94%97List → example.com/mona/🔗List
/// ```
/// * Removing the `.git` file extension from the path component, if present:
/// ```
/// example.com/mona/LinkedList.git → example.com/mona/LinkedList
/// ```
/// * Removing the trailing slash (`/`) in the path component, if present:
/// ```
/// example.com/mona/LinkedList/ → example.com/mona/LinkedList
/// ```
/// * Removing the fragment component (preceded by `#`), if present:
/// ```
/// example.com/mona/LinkedList#installation → example.com/mona/LinkedList
/// ```
/// * Removing the query component (preceded by `?`), if present:
/// ```
/// example.com/mona/LinkedList?utm_source=forums.swift.org → example.com/mona/LinkedList
/// ```
/// * Adding a leading slash (`/`) for `file://` URLs and absolute file paths:
/// ```
/// file:///Users/mona/LinkedList → /Users/mona/LinkedList
/// ```
public struct CanonicalPackageLocation: Equatable, CustomStringConvertible {
/// A textual representation of this instance.
public let description: String
/// Instantiates an instance of the conforming type from a string representation.
public init(_ string: String) {
var description = string.precomposedStringWithCanonicalMapping.lowercased()
// Remove the scheme component, if present.
let detectedScheme = description.dropSchemeComponentPrefixIfPresent()
// Remove the userinfo subcomponent (user / password), if present.
if case (let user, _)? = description.dropUserinfoSubcomponentPrefixIfPresent() {
// If a user was provided, perform tilde expansion, if applicable.
description.replaceFirstOccurenceIfPresent(of: "/~/", with: "/~\(user)/")
}
// Remove the port subcomponent, if present.
description.removePortComponentIfPresent()
// Remove the fragment component, if present.
description.removeFragmentComponentIfPresent()
// Remove the query component, if present.
description.removeQueryComponentIfPresent()
// Accomodate "`scp`-style" SSH URLs
if detectedScheme == nil || detectedScheme == "ssh" {
description.replaceFirstOccurenceIfPresent(of: ":", before: description.firstIndex(of: "/"), with: "/")
}
// Split the remaining string into path components,
// filtering out empty path components and removing valid percent encodings.
var components = description.split(omittingEmptySubsequences: true, whereSeparator: isSeparator)
.compactMap { $0.removingPercentEncoding ?? String($0) }
// Remove the `.git` suffix from the last path component.
var lastPathComponent = components.popLast() ?? ""
lastPathComponent.removeSuffixIfPresent(".git")
components.append(lastPathComponent)
description = components.joined(separator: "/")
// Prepend a leading slash for file URLs and paths
if detectedScheme == "file" || string.first.flatMap(isSeparator) ?? false {
description.insert("/", at: description.startIndex)
}
self.description = description
}
}
#if os(Windows)
fileprivate let isSeparator: (Character) -> Bool = { $0 == "/" || $0 == "\\" }
#else
fileprivate let isSeparator: (Character) -> Bool = { $0 == "/" }
#endif
private extension Character {
var isDigit: Bool {
switch self {
case "0", "1", "2", "3", "4", "5", "6", "7", "8", "9":
return true
default:
return false
}
}
var isAllowedInURLScheme: Bool {
return isLetter || self.isDigit || self == "+" || self == "-" || self == "."
}
}
private extension String {
@discardableResult
mutating func removePrefixIfPresent<T: StringProtocol>(_ prefix: T) -> Bool {
guard hasPrefix(prefix) else { return false }
removeFirst(prefix.count)
return true
}
@discardableResult
mutating func removeSuffixIfPresent<T: StringProtocol>(_ suffix: T) -> Bool {
guard hasSuffix(suffix) else { return false }
removeLast(suffix.count)
return true
}
@discardableResult
mutating func dropSchemeComponentPrefixIfPresent() -> String? {
if let rangeOfDelimiter = range(of: "://"),
self[startIndex].isLetter,
self[..<rangeOfDelimiter.lowerBound].allSatisfy({ $0.isAllowedInURLScheme })
{
defer { self.removeSubrange(..<rangeOfDelimiter.upperBound) }
return String(self[..<rangeOfDelimiter.lowerBound])
}
return nil
}
@discardableResult
mutating func dropUserinfoSubcomponentPrefixIfPresent() -> (user: String, password: String?)? {
if let indexOfAtSign = firstIndex(of: "@"),
let indexOfFirstPathComponent = firstIndex(where: isSeparator),
indexOfAtSign < indexOfFirstPathComponent
{
defer { self.removeSubrange(...indexOfAtSign) }
let userinfo = self[..<indexOfAtSign]
var components = userinfo.split(separator: ":", maxSplits: 2, omittingEmptySubsequences: false)
guard components.count > 0 else { return nil }
let user = String(components.removeFirst())
let password = components.last.map(String.init)
return (user, password)
}
return nil
}
@discardableResult
mutating func removePortComponentIfPresent() -> Bool {
if let indexOfFirstPathComponent = firstIndex(where: isSeparator),
let startIndexOfPort = firstIndex(of: ":"),
startIndexOfPort < endIndex,
let endIndexOfPort = self[index(after: startIndexOfPort)...].lastIndex(where: { $0.isDigit }),
endIndexOfPort <= indexOfFirstPathComponent
{
self.removeSubrange(startIndexOfPort ... endIndexOfPort)
return true
}
return false
}
@discardableResult
mutating func removeFragmentComponentIfPresent() -> Bool {
if let index = firstIndex(of: "#") {
self.removeSubrange(index...)
}
return false
}
@discardableResult
mutating func removeQueryComponentIfPresent() -> Bool {
if let index = firstIndex(of: "?") {
self.removeSubrange(index...)
}
return false
}
@discardableResult
mutating func replaceFirstOccurenceIfPresent<T: StringProtocol, U: StringProtocol>(
of string: T,
before index: Index? = nil,
with replacement: U
) -> Bool {
guard let range = range(of: string) else { return false }
if let index = index, range.lowerBound >= index {
return false
}
self.replaceSubrange(range, with: replacement)
return true
}
}
| af470c35698a89568ea24c4c21278103 | 35.994633 | 118 | 0.617311 | false | false | false | false |
alessiobrozzi/firefox-ios | refs/heads/master | Client/Frontend/Home/ActivityStreamTopSitesCell.swift | mpl-2.0 | 1 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import WebImage
import Storage
struct TopSiteCellUX {
static let TitleHeight: CGFloat = 20
static let TitleBackgroundColor = UIColor(colorLiteralRed: 1, green: 1, blue: 1, alpha: 0.7)
static let TitleTextColor = UIColor.black
static let TitleFont = DynamicFontHelper.defaultHelper.DefaultSmallFont
static let SelectedOverlayColor = UIColor(white: 0.0, alpha: 0.25)
static let CellCornerRadius: CGFloat = 4
static let TitleOffset: CGFloat = 5
static let OverlayColor = UIColor(white: 0.0, alpha: 0.25)
static let IconSize = CGSize(width: 40, height: 40)
static let BorderColor = UIColor(white: 0, alpha: 0.1)
static let BorderWidth: CGFloat = 0.5
}
/*
* The TopSite cell that appears in the ASHorizontalScrollView.
*/
class TopSiteItemCell: UICollectionViewCell {
var url: URL?
lazy var imageView: UIImageView = {
let imageView = UIImageView()
imageView.layer.masksToBounds = true
return imageView
}()
lazy fileprivate var titleLabel: UILabel = {
let titleLabel = UILabel()
titleLabel.layer.masksToBounds = true
titleLabel.textAlignment = .center
titleLabel.font = TopSiteCellUX.TitleFont
titleLabel.textColor = TopSiteCellUX.TitleTextColor
titleLabel.backgroundColor = UIColor.clear
return titleLabel
}()
lazy private var faviconBG: UIView = {
let view = UIView()
view.layer.cornerRadius = TopSiteCellUX.CellCornerRadius
view.layer.masksToBounds = true
view.layer.borderWidth = TopSiteCellUX.BorderWidth
view.layer.borderColor = TopSiteCellUX.BorderColor.cgColor
return view
}()
lazy var selectedOverlay: UIView = {
let selectedOverlay = UIView()
selectedOverlay.backgroundColor = TopSiteCellUX.OverlayColor
selectedOverlay.isHidden = true
return selectedOverlay
}()
lazy var titleBorder: CALayer = {
let border = CALayer()
border.backgroundColor = TopSiteCellUX.BorderColor.cgColor
return border
}()
override var isSelected: Bool {
didSet {
self.selectedOverlay.isHidden = !isSelected
}
}
override init(frame: CGRect) {
super.init(frame: frame)
isAccessibilityElement = true
accessibilityIdentifier = "TopSite"
contentView.addSubview(titleLabel)
contentView.addSubview(faviconBG)
contentView.addSubview(imageView)
contentView.addSubview(selectedOverlay)
titleLabel.snp.makeConstraints { make in
make.left.equalTo(self).offset(TopSiteCellUX.TitleOffset)
make.right.equalTo(self).offset(-TopSiteCellUX.TitleOffset)
make.height.equalTo(TopSiteCellUX.TitleHeight)
make.bottom.equalTo(self)
}
imageView.snp.makeConstraints { make in
make.size.equalTo(TopSiteCellUX.IconSize)
make.centerX.equalTo(self)
make.centerY.equalTo(self).inset(-TopSiteCellUX.TitleHeight/2)
}
selectedOverlay.snp.makeConstraints { make in
make.edges.equalTo(contentView)
}
faviconBG.snp.makeConstraints { make in
make.top.left.right.equalTo(self)
make.bottom.equalTo(self).inset(TopSiteCellUX.TitleHeight)
}
}
override func layoutSubviews() {
super.layoutSubviews()
titleBorder.frame = CGRect(x: 0, y: frame.height - TopSiteCellUX.TitleHeight - TopSiteCellUX.BorderWidth, width: frame.width, height: TopSiteCellUX.BorderWidth)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func prepareForReuse() {
super.prepareForReuse()
contentView.backgroundColor = UIColor.clear
imageView.image = nil
imageView.backgroundColor = UIColor.clear
faviconBG.backgroundColor = UIColor.clear
imageView.sd_cancelCurrentImageLoad()
titleLabel.text = ""
}
func configureWithTopSiteItem(_ site: Site) {
url = site.tileURL
if let provider = site.metadata?.providerName {
titleLabel.text = provider.lowercased()
} else {
titleLabel.text = site.tileURL.hostSLD
}
accessibilityLabel = titleLabel.text
if let suggestedSite = site as? SuggestedSite {
let img = UIImage(named: suggestedSite.faviconImagePath!)
imageView.image = img
// This is a temporary hack to make amazon/wikipedia have white backrounds instead of their default blacks
// Once we remove the old TopSitesPanel we can change the values of amazon/wikipedia to be white instead of black.
self.faviconBG.backgroundColor = suggestedSite.backgroundColor.isBlackOrWhite ? UIColor.white : suggestedSite.backgroundColor
imageView.backgroundColor = self.faviconBG.backgroundColor
} else {
imageView.setFavicon(forSite: site, onCompletion: { [weak self] (color, url) in
if let url = url, url == self?.url {
self?.faviconBG.backgroundColor = color
self?.imageView.backgroundColor = color
}
})
}
}
}
struct ASHorizontalScrollCellUX {
static let TopSiteCellIdentifier = "TopSiteItemCell"
static let TopSiteItemSize = CGSize(width: 75, height: 75)
static let BackgroundColor = UIColor.white
static let PageControlRadius: CGFloat = 3
static let PageControlSize = CGSize(width: 30, height: 15)
static let PageControlOffset: CGFloat = 12
static let MinimumInsets: CGFloat = 15
}
/*
The View that describes the topSite cell that appears in the tableView.
*/
class ASHorizontalScrollCell: UICollectionViewCell {
lazy var collectionView: UICollectionView = {
let layout = HorizontalFlowLayout()
layout.itemSize = ASHorizontalScrollCellUX.TopSiteItemSize
let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
collectionView.register(TopSiteItemCell.self, forCellWithReuseIdentifier: ASHorizontalScrollCellUX.TopSiteCellIdentifier)
collectionView.backgroundColor = UIColor.clear
collectionView.showsHorizontalScrollIndicator = false
collectionView.isPagingEnabled = true
return collectionView
}()
lazy fileprivate var pageControl: FilledPageControl = {
let pageControl = FilledPageControl()
pageControl.tintColor = UIColor.gray
pageControl.indicatorRadius = ASHorizontalScrollCellUX.PageControlRadius
pageControl.isUserInteractionEnabled = true
pageControl.isAccessibilityElement = true
pageControl.accessibilityIdentifier = "pageControl"
pageControl.accessibilityLabel = Strings.ASPageControlButton
pageControl.accessibilityTraits = UIAccessibilityTraitButton
return pageControl
}()
lazy fileprivate var pageControlPress: UITapGestureRecognizer = {
let press = UITapGestureRecognizer(target: self, action: #selector(ASHorizontalScrollCell.handlePageTap(_:)))
// press.delegate = self
return press
}()
weak var delegate: ASHorizontalScrollCellManager? {
didSet {
collectionView.delegate = delegate
collectionView.dataSource = delegate
delegate?.pageChangedHandler = { [weak self] progress in
self?.currentPageChanged(progress)
}
DispatchQueue.main.async {
self.setNeedsLayout()
self.collectionView.reloadData()
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
isAccessibilityElement = false
accessibilityIdentifier = "TopSitesCell"
backgroundColor = UIColor.clear
contentView.addSubview(collectionView)
contentView.addSubview(pageControl)
pageControl.addGestureRecognizer(self.pageControlPress)
collectionView.snp.makeConstraints { make in
make.edges.equalTo(contentView)
}
pageControl.snp.makeConstraints { make in
make.size.equalTo(ASHorizontalScrollCellUX.PageControlSize)
make.top.equalTo(collectionView.snp.bottom).inset(ASHorizontalScrollCellUX.PageControlOffset)
make.centerX.equalTo(self.snp.centerX)
}
}
override func layoutSubviews() {
super.layoutSubviews()
let layout = collectionView.collectionViewLayout as! HorizontalFlowLayout
pageControl.pageCount = layout.numberOfPages(with: self.frame.size)
pageControl.isHidden = pageControl.pageCount <= 1
}
func currentPageChanged(_ currentPage: CGFloat) {
pageControl.progress = currentPage
if currentPage == floor(currentPage) {
UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, nil)
self.setNeedsLayout()
}
}
func handlePageTap(_ gesture: UITapGestureRecognizer) {
guard pageControl.pageCount > 1 else {
return
}
if pageControl.pageCount > pageControl.currentPage + 1 {
pageControl.progress = CGFloat(pageControl.currentPage + 1)
} else {
pageControl.progress = CGFloat(pageControl.currentPage - 1)
}
let swipeCoordinate = CGFloat(pageControl.currentPage) * self.collectionView.frame.size.width
self.collectionView.setContentOffset(CGPoint(x: swipeCoordinate, y: 0), animated: true)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
/*
A custom layout used to show a horizontal scrolling list with paging. Similar to iOS springboard.
A modified version of http://stackoverflow.com/a/34167915
*/
class HorizontalFlowLayout: UICollectionViewLayout {
var itemSize = CGSize.zero
fileprivate var cellCount: Int {
if let collectionView = collectionView, let dataSource = collectionView.dataSource {
return dataSource.collectionView(collectionView, numberOfItemsInSection: 0)
}
return 0
}
var boundsSize = CGSize.zero
private var insets = UIEdgeInsets(equalInset: ASHorizontalScrollCellUX.MinimumInsets)
private var sectionInsets: CGFloat = 0
override func prepare() {
super.prepare()
boundsSize = self.collectionView?.frame.size ?? CGSize.zero
}
func numberOfPages(with bounds: CGSize) -> Int {
let itemsPerPage = maxVerticalItemsCount(height: bounds.height) * maxHorizontalItemsCount(width: bounds.width)
// Sometimes itemsPerPage is 0. In this case just return 0. We dont want to try dividing by 0.
return itemsPerPage == 0 ? 0 : Int(ceil(Double(cellCount) / Double(itemsPerPage)))
}
func calculateLayout(for size: CGSize) -> (size: CGSize, cellSize: CGSize, cellInsets: UIEdgeInsets) {
let width = size.width
let height = size.height
guard width != 0 else {
return (size: CGSize.zero, cellSize: self.itemSize, cellInsets: self.insets)
}
let horizontalItemsCount = maxHorizontalItemsCount(width: width)
var verticalItemsCount = maxVerticalItemsCount(height: height)
if cellCount <= horizontalItemsCount {
// If we have only a few items don't provide space for multiple rows.
verticalItemsCount = 1
}
// Take the number of cells and subtract its space in the view from the height. The left over space is the white space.
// The left over space is then devided evenly into (n + 1) parts to figure out how much space should be inbetween a cell
var verticalInsets = floor((height - (CGFloat(verticalItemsCount) * itemSize.height)) / CGFloat(verticalItemsCount + 1))
var horizontalInsets = floor((width - (CGFloat(horizontalItemsCount) * itemSize.width)) / CGFloat(horizontalItemsCount + 1))
// We want a minimum inset to make things not look crowded. We also don't want uneven spacing.
// If we dont have this. Set a minimum inset and recalculate the size of a cell
var estimatedItemSize = itemSize
if horizontalInsets < ASHorizontalScrollCellUX.MinimumInsets || horizontalInsets != verticalInsets {
verticalInsets = ASHorizontalScrollCellUX.MinimumInsets
horizontalInsets = ASHorizontalScrollCellUX.MinimumInsets
estimatedItemSize.width = floor((width - (CGFloat(horizontalItemsCount + 1) * horizontalInsets)) / CGFloat(horizontalItemsCount))
estimatedItemSize.height = estimatedItemSize.width + TopSiteCellUX.TitleHeight
}
//calculate our estimates.
let estimatedHeight = floor(estimatedItemSize.height * CGFloat(verticalItemsCount)) + (verticalInsets * (CGFloat(verticalItemsCount) + 1))
let estimatedSize = CGSize(width: CGFloat(numberOfPages(with: boundsSize)) * width, height: estimatedHeight)
let estimatedInsets = UIEdgeInsets(top: verticalInsets, left: horizontalInsets, bottom: verticalInsets, right: horizontalInsets)
return (size: estimatedSize, cellSize: estimatedItemSize, cellInsets: estimatedInsets)
}
override var collectionViewContentSize: CGSize {
let estimatedLayout = calculateLayout(for: boundsSize)
insets = estimatedLayout.cellInsets
itemSize = estimatedLayout.cellSize
boundsSize = estimatedLayout.size
return estimatedLayout.size
}
func maxVerticalItemsCount(height: CGFloat) -> Int {
let verticalItemsCount = Int(floor(height / (ASHorizontalScrollCellUX.TopSiteItemSize.height + insets.top)))
if let delegate = self.collectionView?.delegate as? ASHorizontalLayoutDelegate {
return delegate.numberOfVerticalItems()
} else {
return verticalItemsCount
}
}
func maxHorizontalItemsCount(width: CGFloat) -> Int {
let horizontalItemsCount = Int(floor(width / (ASHorizontalScrollCellUX.TopSiteItemSize.width + insets.left)))
if let delegate = self.collectionView?.delegate as? ASHorizontalLayoutDelegate {
return delegate.numberOfHorizontalItems() > horizontalItemsCount ? horizontalItemsCount : delegate.numberOfHorizontalItems()
} else {
return horizontalItemsCount
}
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
super.layoutAttributesForElements(in: rect)
var allAttributes = [UICollectionViewLayoutAttributes]()
for i in 0 ..< cellCount {
let indexPath = IndexPath(row: i, section: 0)
let attr = self.computeLayoutAttributesForCellAtIndexPath(indexPath)
allAttributes.append(attr)
}
return allAttributes
}
override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
return self.computeLayoutAttributesForCellAtIndexPath(indexPath)
}
override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
// Sometimes when the topsiteCell isnt on the screen the newbounds that it tries to layout in is very tiny
// Resulting in incorrect layouts. So only layout when the width is greater than 320.
return newBounds.width <= 320
}
func computeLayoutAttributesForCellAtIndexPath(_ indexPath: IndexPath) -> UICollectionViewLayoutAttributes {
let row = indexPath.row
let bounds = self.collectionView!.bounds
let verticalItemsCount = maxVerticalItemsCount(height: bounds.size.height)
let horizontalItemsCount = maxHorizontalItemsCount(width: bounds.size.width)
let itemsPerPage = verticalItemsCount * horizontalItemsCount
let columnPosition = row % horizontalItemsCount
let rowPosition = (row / horizontalItemsCount) % verticalItemsCount
let itemPage = Int(floor(Double(row)/Double(itemsPerPage)))
let attr = UICollectionViewLayoutAttributes(forCellWith: indexPath)
var frame = CGRect.zero
frame.origin.x = CGFloat(itemPage) * bounds.size.width + CGFloat(columnPosition) * (itemSize.width + insets.left) + insets.left
// If there is only 1 page. and only 1 row. Make sure to center.
if cellCount < horizontalItemsCount {
sectionInsets = floor((bounds.width - (CGFloat(cellCount) * (itemSize.width + insets.left))) / 2)
frame.origin.x += sectionInsets
}
frame.origin.y = CGFloat(rowPosition) * (itemSize.height + insets.top) + insets.top
frame.size = itemSize
attr.frame = frame
return attr
}
}
/*
Defines the number of items to show in topsites for different size classes.
*/
struct ASTopSiteSourceUX {
static let verticalItemsForTraitSizes = [UIUserInterfaceSizeClass.compact: 1, UIUserInterfaceSizeClass.regular: 2, UIUserInterfaceSizeClass.unspecified: 0]
static let horizontalItemsForTraitSizes = [UIUserInterfaceSizeClass.compact: 4, UIUserInterfaceSizeClass.regular: 8, UIUserInterfaceSizeClass.unspecified: 0]
static let maxNumberOfPages = 2
static let CellIdentifier = "TopSiteItemCell"
}
protocol ASHorizontalLayoutDelegate {
func numberOfVerticalItems() -> Int
func numberOfHorizontalItems() -> Int
}
/*
This Delegate/DataSource is used to manage the ASHorizontalScrollCell's UICollectionView.
This is left generic enough for it to be re used for other parts of Activity Stream.
*/
class ASHorizontalScrollCellManager: NSObject, UICollectionViewDelegate, UICollectionViewDataSource, ASHorizontalLayoutDelegate {
var content: [Site] = []
var urlPressedHandler: ((URL, IndexPath) -> Void)?
var pageChangedHandler: ((CGFloat) -> Void)?
// The current traits that define the parent ViewController. Used to determine how many rows/columns should be created.
var currentTraits: UITraitCollection?
// Size classes define how many items to show per row/column.
func numberOfVerticalItems() -> Int {
guard let traits = currentTraits else {
return 0
}
return ASTopSiteSourceUX.verticalItemsForTraitSizes[traits.verticalSizeClass]!
}
func numberOfHorizontalItems() -> Int {
guard let traits = currentTraits else {
return 0
}
// An iPhone 5 in both landscape/portrait is considered compactWidth which means we need to let the layout determine how many items to show based on actual width.
if traits.horizontalSizeClass == .compact && traits.verticalSizeClass == .compact {
return ASTopSiteSourceUX.horizontalItemsForTraitSizes[.regular]!
}
return ASTopSiteSourceUX.horizontalItemsForTraitSizes[traits.horizontalSizeClass]!
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.content.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ASTopSiteSourceUX.CellIdentifier, for: indexPath) as! TopSiteItemCell
let contentItem = content[indexPath.row]
cell.configureWithTopSiteItem(contentItem)
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let contentItem = content[indexPath.row]
guard let url = contentItem.url.asURL else {
return
}
urlPressedHandler?(url, indexPath)
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let pageWidth = scrollView.frame.width
pageChangedHandler?(scrollView.contentOffset.x / pageWidth)
}
}
| 7c86a2b9e58ffb2957d0141afc9154a3 | 40.652977 | 170 | 0.692038 | false | false | false | false |
sabensm/playgrounds | refs/heads/develop | some-dictonary-stuff.playground/Contents.swift | mit | 1 | //: Playground - noun: a place where people can play
import UIKit
var webster: [String: String] = ["krill":"any of the small crustceans","fire":"a burning mass of material"]
var anotherDictonary: [Int: String] = [44:"my fav number",349:"i hate this number"]
if let krill = webster["krill"] {
print(krill)
}
//CLears dictionary
webster = [:]
if webster.isEmpty {
print("Our dictionary is quite the empty!")
}
var highScores: [String: Int] = ["spentak": 401, "Player1": 200, "Tomtendo": 1]
for (user, score) in highScores {
print("\(user): \(score)")
}
| 84e9e5a36e4febc24e764c23de811c99 | 17.0625 | 107 | 0.652249 | false | false | false | false |
leftdal/youslow | refs/heads/master | iOS/YouSlow/Controllers/VideoTableViewController.swift | gpl-3.0 | 1 | //
// VideoTableViewController.swift
// Demo
//
// Created by to0 on 2/7/15.
// Copyright (c) 2015 to0. All rights reserved.
//
import UIKit
class VideoTableViewController: UITableViewController, UISearchBarDelegate, VideoListProtocol {
@IBOutlet var videoSearchBar: UISearchBar!
var videoDataSource = VideoTableDataSource()
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.dataSource = videoDataSource
self.tableView.delegate = videoDataSource
videoSearchBar.delegate = self
self.videoDataSource.videoList.delegate = self
self.videoDataSource.videoList.requestDataForRefresh("Grumpy cat")
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func viewWillAppear(animated: Bool) {
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func didReloadVideoData() {
dispatch_async(dispatch_get_main_queue(), {
self.tableView.reloadData()
})
}
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
}
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
let query = searchBar.text
self.videoDataSource.videoList.requestDataForRefresh(query!)
searchBar.resignFirstResponder()
}
// 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?) {
let dest = segue.destinationViewController as! SingleVideoViewController
let cell = sender as! UITableViewCell
let row = self.tableView.indexPathForCell(cell)!.row
cell.selected = false
dest.hidesBottomBarWhenPushed = true
dest.videoId = self.videoDataSource.videoList.videoIdOfIndex(row)
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
}
| 4a3126785db2c9553351d26e0020c47a | 32.430556 | 113 | 0.695887 | false | false | false | false |
nghialv/ReactiveCocoa | refs/heads/master | ReactiveCocoa/Swift/Flatten.swift | mit | 2 | //
// Flatten.swift
// ReactiveCocoa
//
// Created by Neil Pankey on 11/30/15.
// Copyright © 2015 GitHub. All rights reserved.
//
import enum Result.NoError
/// Describes how multiple producers should be joined together.
public enum FlattenStrategy: Equatable {
/// The producers should be merged, so that any value received on any of the
/// input producers will be forwarded immediately to the output producer.
///
/// The resulting producer will complete only when all inputs have completed.
case Merge
/// The producers should be concatenated, so that their values are sent in the
/// order of the producers themselves.
///
/// The resulting producer will complete only when all inputs have completed.
case Concat
/// Only the events from the latest input producer should be considered for
/// the output. Any producers received before that point will be disposed of.
///
/// The resulting producer will complete only when the producer-of-producers and
/// the latest producer has completed.
case Latest
}
extension SignalType where Value: SignalProducerType, Error == Value.Error {
/// Flattens the inner producers sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// If `signal` or an active inner producer fails, the returned signal will
/// forward that failure immediately.
///
/// `Interrupted` events on inner producers will be treated like `Completed`
/// events on inner producers.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func flatten(strategy: FlattenStrategy) -> Signal<Value.Value, Error> {
switch strategy {
case .Merge:
return self.merge()
case .Concat:
return self.concat()
case .Latest:
return self.switchToLatest()
}
}
}
extension SignalType where Value: SignalProducerType, Error == NoError {
/// Flattens the inner producers sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// If an active inner producer fails, the returned signal will forward that
/// failure immediately.
///
/// `Interrupted` events on inner producers will be treated like `Completed`
/// events on inner producers.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func flatten(strategy: FlattenStrategy) -> Signal<Value.Value, Value.Error> {
return self
.promoteErrors(Value.Error.self)
.flatten(strategy)
}
}
extension SignalType where Value: SignalProducerType, Error == NoError, Value.Error == NoError {
/// Flattens the inner producers sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// `Interrupted` events on inner producers will be treated like `Completed`
/// events on inner producers.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func flatten(strategy: FlattenStrategy) -> Signal<Value.Value, Value.Error> {
switch strategy {
case .Merge:
return self.merge()
case .Concat:
return self.concat()
case .Latest:
return self.switchToLatest()
}
}
}
extension SignalType where Value: SignalProducerType, Value.Error == NoError {
/// Flattens the inner producers sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// If `signal` fails, the returned signal will forward that failure
/// immediately.
///
/// `Interrupted` events on inner producers will be treated like `Completed`
/// events on inner producers.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func flatten(strategy: FlattenStrategy) -> Signal<Value.Value, Error> {
return self.flatMap(strategy) { $0.promoteErrors(Error.self) }
}
}
extension SignalProducerType where Value: SignalProducerType, Error == Value.Error {
/// Flattens the inner producers sent upon `producer` (into a single producer of
/// values), according to the semantics of the given strategy.
///
/// If `producer` or an active inner producer fails, the returned producer will
/// forward that failure immediately.
///
/// `Interrupted` events on inner producers will be treated like `Completed`
/// events on inner producers.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func flatten(strategy: FlattenStrategy) -> SignalProducer<Value.Value, Error> {
switch strategy {
case .Merge:
return self.merge()
case .Concat:
return self.concat()
case .Latest:
return self.switchToLatest()
}
}
}
extension SignalProducerType where Value: SignalProducerType, Error == NoError {
/// Flattens the inner producers sent upon `producer` (into a single producer of
/// values), according to the semantics of the given strategy.
///
/// If an active inner producer fails, the returned producer will forward that
/// failure immediately.
///
/// `Interrupted` events on inner producers will be treated like `Completed`
/// events on inner producers.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func flatten(strategy: FlattenStrategy) -> SignalProducer<Value.Value, Value.Error> {
return self
.promoteErrors(Value.Error.self)
.flatten(strategy)
}
}
extension SignalProducerType where Value: SignalProducerType, Error == NoError, Value.Error == NoError {
/// Flattens the inner producers sent upon `producer` (into a single producer of
/// values), according to the semantics of the given strategy.
///
/// `Interrupted` events on inner producers will be treated like `Completed`
/// events on inner producers.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func flatten(strategy: FlattenStrategy) -> SignalProducer<Value.Value, Value.Error> {
switch strategy {
case .Merge:
return self.merge()
case .Concat:
return self.concat()
case .Latest:
return self.switchToLatest()
}
}
}
extension SignalProducerType where Value: SignalProducerType, Value.Error == NoError {
/// Flattens the inner producers sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// If `signal` fails, the returned signal will forward that failure
/// immediately.
///
/// `Interrupted` events on inner producers will be treated like `Completed`
/// events on inner producers.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func flatten(strategy: FlattenStrategy) -> SignalProducer<Value.Value, Error> {
return self.flatMap(strategy) { $0.promoteErrors(Error.self) }
}
}
extension SignalType where Value: SignalType, Error == Value.Error {
/// Flattens the inner signals sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// If `signal` or an active inner signal emits an error, the returned
/// signal will forward that error immediately.
///
/// `Interrupted` events on inner signals will be treated like `Completed`
/// events on inner signals.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func flatten(strategy: FlattenStrategy) -> Signal<Value.Value, Error> {
return self
.map(SignalProducer.init)
.flatten(strategy)
}
}
extension SignalType where Value: SignalType, Error == NoError {
/// Flattens the inner signals sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// If an active inner signal emits an error, the returned signal will
/// forward that error immediately.
///
/// `Interrupted` events on inner signals will be treated like `Completed`
/// events on inner signals.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func flatten(strategy: FlattenStrategy) -> Signal<Value.Value, Value.Error> {
return self
.promoteErrors(Value.Error.self)
.flatten(strategy)
}
}
extension SignalType where Value: SignalType, Error == NoError, Value.Error == NoError {
/// Flattens the inner signals sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// `Interrupted` events on inner signals will be treated like `Completed`
/// events on inner signals.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func flatten(strategy: FlattenStrategy) -> Signal<Value.Value, Value.Error> {
return self
.map(SignalProducer.init)
.flatten(strategy)
}
}
extension SignalType where Value: SignalType, Value.Error == NoError {
/// Flattens the inner signals sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// If `signal` emits an error, the returned signal will forward
/// that error immediately.
///
/// `Interrupted` events on inner signals will be treated like `Completed`
/// events on inner signals.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func flatten(strategy: FlattenStrategy) -> Signal<Value.Value, Error> {
return self.flatMap(strategy) { $0.promoteErrors(Error.self) }
}
}
extension SignalProducerType where Value: SignalType, Error == Value.Error {
/// Flattens the inner signals sent upon `producer` (into a single producer of
/// values), according to the semantics of the given strategy.
///
/// If `producer` or an active inner signal emits an error, the returned
/// producer will forward that error immediately.
///
/// `Interrupted` events on inner signals will be treated like `Completed`
/// events on inner signals.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func flatten(strategy: FlattenStrategy) -> SignalProducer<Value.Value, Error> {
return self
.map(SignalProducer.init)
.flatten(strategy)
}
}
extension SignalProducerType where Value: SignalType, Error == NoError {
/// Flattens the inner signals sent upon `producer` (into a single producer of
/// values), according to the semantics of the given strategy.
///
/// If an active inner signal emits an error, the returned producer will
/// forward that error immediately.
///
/// `Interrupted` events on inner signals will be treated like `Completed`
/// events on inner signals.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func flatten(strategy: FlattenStrategy) -> SignalProducer<Value.Value, Value.Error> {
return self
.promoteErrors(Value.Error.self)
.flatten(strategy)
}
}
extension SignalProducerType where Value: SignalType, Error == NoError, Value.Error == NoError {
/// Flattens the inner signals sent upon `producer` (into a single producer of
/// values), according to the semantics of the given strategy.
///
/// `Interrupted` events on inner signals will be treated like `Completed`
/// events on inner signals.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func flatten(strategy: FlattenStrategy) -> SignalProducer<Value.Value, Value.Error> {
return self
.map(SignalProducer.init)
.flatten(strategy)
}
}
extension SignalProducerType where Value: SignalType, Value.Error == NoError {
/// Flattens the inner signals sent upon `producer` (into a single producer of
/// values), according to the semantics of the given strategy.
///
/// If `producer` emits an error, the returned producer will forward that
/// error immediately.
///
/// `Interrupted` events on inner signals will be treated like `Completed`
/// events on inner signals.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func flatten(strategy: FlattenStrategy) -> SignalProducer<Value.Value, Error> {
return self.flatMap(strategy) { $0.promoteErrors(Error.self) }
}
}
extension SignalType where Value: SignalProducerType, Error == Value.Error {
/// Returns a signal which sends all the values from producer signal emitted from
/// `signal`, waiting until each inner producer completes before beginning to
/// send the values from the next inner producer.
///
/// If any of the inner producers fail, the returned signal will forward
/// that failure immediately
///
/// The returned signal completes only when `signal` and all producers
/// emitted from `signal` complete.
private func concat() -> Signal<Value.Value, Error> {
return Signal<Value.Value, Error> { relayObserver in
let disposable = CompositeDisposable()
let relayDisposable = CompositeDisposable()
disposable += relayDisposable
disposable += self.observeConcat(relayObserver, relayDisposable)
return disposable
}
}
private func observeConcat(observer: Observer<Value.Value, Error>, _ disposable: CompositeDisposable? = nil) -> Disposable? {
let state = ConcatState(observer: observer, disposable: disposable)
return self.observe { event in
switch event {
case let .Next(value):
state.enqueueSignalProducer(value.producer)
case let .Failed(error):
observer.sendFailed(error)
case .Completed:
// Add one last producer to the queue, whose sole job is to
// "turn out the lights" by completing `observer`.
state.enqueueSignalProducer(SignalProducer.empty.on(completed: {
observer.sendCompleted()
}))
case .Interrupted:
observer.sendInterrupted()
}
}
}
}
extension SignalProducerType where Value: SignalProducerType, Error == Value.Error {
/// Returns a producer which sends all the values from each producer emitted from
/// `producer`, waiting until each inner producer completes before beginning to
/// send the values from the next inner producer.
///
/// If any of the inner producers emit an error, the returned producer will emit
/// that error.
///
/// The returned producer completes only when `producer` and all producers
/// emitted from `producer` complete.
private func concat() -> SignalProducer<Value.Value, Error> {
return SignalProducer<Value.Value, Error> { observer, disposable in
self.startWithSignal { signal, signalDisposable in
disposable += signalDisposable
signal.observeConcat(observer, disposable)
}
}
}
}
extension SignalProducerType {
/// `concat`s `next` onto `self`.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func concat(next: SignalProducer<Value, Error>) -> SignalProducer<Value, Error> {
return SignalProducer<SignalProducer<Value, Error>, Error>(values: [ self.producer, next ]).flatten(.Concat)
}
/// `concat`s `value` onto `self`.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func concat(value value: Value) -> SignalProducer<Value, Error> {
return self.concat(SignalProducer(value: value))
}
/// `concat`s `self` onto initial `previous`.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func prefix<P: SignalProducerType where P.Value == Value, P.Error == Error>(previous: P) -> SignalProducer<Value, Error> {
return previous.concat(self.producer)
}
/// `concat`s `self` onto initial `value`.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func prefix(value value: Value) -> SignalProducer<Value, Error> {
return self.prefix(SignalProducer(value: value))
}
}
private final class ConcatState<Value, Error: ErrorType> {
/// The observer of a started `concat` producer.
let observer: Observer<Value, Error>
/// The top level disposable of a started `concat` producer.
let disposable: CompositeDisposable?
/// The active producer, if any, and the producers waiting to be started.
let queuedSignalProducers: Atomic<[SignalProducer<Value, Error>]> = Atomic([])
init(observer: Signal<Value, Error>.Observer, disposable: CompositeDisposable?) {
self.observer = observer
self.disposable = disposable
}
func enqueueSignalProducer(producer: SignalProducer<Value, Error>) {
if let d = disposable where d.disposed {
return
}
var shouldStart = true
queuedSignalProducers.modify {
// An empty queue means the concat is idle, ready & waiting to start
// the next producer.
var queue = $0
shouldStart = queue.isEmpty
queue.append(producer)
return queue
}
if shouldStart {
startNextSignalProducer(producer)
}
}
func dequeueSignalProducer() -> SignalProducer<Value, Error>? {
if let d = disposable where d.disposed {
return nil
}
var nextSignalProducer: SignalProducer<Value, Error>?
queuedSignalProducers.modify {
// Active producers remain in the queue until completed. Since
// dequeueing happens at completion of the active producer, the
// first producer in the queue can be removed.
var queue = $0
if !queue.isEmpty { queue.removeAtIndex(0) }
nextSignalProducer = queue.first
return queue
}
return nextSignalProducer
}
/// Subscribes to the given signal producer.
func startNextSignalProducer(signalProducer: SignalProducer<Value, Error>) {
signalProducer.startWithSignal { signal, disposable in
let handle = self.disposable?.addDisposable(disposable) ?? nil
signal.observe { event in
switch event {
case .Completed, .Interrupted:
handle?.remove()
if let nextSignalProducer = self.dequeueSignalProducer() {
self.startNextSignalProducer(nextSignalProducer)
}
case .Next, .Failed:
self.observer.action(event)
}
}
}
}
}
extension SignalType where Value: SignalProducerType, Error == Value.Error {
/// Merges a `signal` of SignalProducers down into a single signal, biased toward the producer
/// added earlier. Returns a Signal that will forward events from the inner producers as they arrive.
private func merge() -> Signal<Value.Value, Error> {
return Signal<Value.Value, Error> { relayObserver in
let disposable = CompositeDisposable()
let relayDisposable = CompositeDisposable()
disposable += relayDisposable
disposable += self.observeMerge(relayObserver, relayDisposable)
return disposable
}
}
private func observeMerge(observer: Observer<Value.Value, Error>, _ disposable: CompositeDisposable) -> Disposable? {
let inFlight = Atomic(1)
let decrementInFlight = {
let orig = inFlight.modify { $0 - 1 }
if orig == 1 {
observer.sendCompleted()
}
}
return self.observe { event in
switch event {
case let .Next(producer):
producer.startWithSignal { innerSignal, innerDisposable in
inFlight.modify { $0 + 1 }
let handle = disposable.addDisposable(innerDisposable)
innerSignal.observe { event in
switch event {
case .Completed, .Interrupted:
handle.remove()
decrementInFlight()
case .Next, .Failed:
observer.action(event)
}
}
}
case let .Failed(error):
observer.sendFailed(error)
case .Completed:
decrementInFlight()
case .Interrupted:
observer.sendInterrupted()
}
}
}
}
extension SignalProducerType where Value: SignalProducerType, Error == Value.Error {
/// Merges a `signal` of SignalProducers down into a single signal, biased toward the producer
/// added earlier. Returns a Signal that will forward events from the inner producers as they arrive.
private func merge() -> SignalProducer<Value.Value, Error> {
return SignalProducer<Value.Value, Error> { relayObserver, disposable in
self.startWithSignal { signal, signalDisposable in
disposable.addDisposable(signalDisposable)
signal.observeMerge(relayObserver, disposable)
}
}
}
}
extension SignalType {
/// Merges the given signals into a single `Signal` that will emit all values
/// from each of them, and complete when all of them have completed.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public static func merge<Seq: SequenceType, S: SignalType where S.Value == Value, S.Error == Error, Seq.Generator.Element == S>(signals: Seq) -> Signal<Value, Error> {
let producer = SignalProducer<S, Error>(values: signals)
var result: Signal<Value, Error>!
producer.startWithSignal { signal, _ in
result = signal.flatten(.Merge)
}
return result
}
/// Merges the given signals into a single `Signal` that will emit all values
/// from each of them, and complete when all of them have completed.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public static func merge<S: SignalType where S.Value == Value, S.Error == Error>(signals: S...) -> Signal<Value, Error> {
return Signal.merge(signals)
}
}
extension SignalProducerType {
/// Merges the given producers into a single `SignalProducer` that will emit all values
/// from each of them, and complete when all of them have completed.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public static func merge<Seq: SequenceType, S: SignalProducerType where S.Value == Value, S.Error == Error, Seq.Generator.Element == S>(producers: Seq) -> SignalProducer<Value, Error> {
return SignalProducer(values: producers).flatten(.Merge)
}
/// Merges the given producers into a single `SignalProducer` that will emit all values
/// from each of them, and complete when all of them have completed.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public static func merge<S: SignalProducerType where S.Value == Value, S.Error == Error>(producers: S...) -> SignalProducer<Value, Error> {
return SignalProducer.merge(producers)
}
}
extension SignalType where Value: SignalProducerType, Error == Value.Error {
/// Returns a signal that forwards values from the latest signal sent on
/// `signal`, ignoring values sent on previous inner signal.
///
/// An error sent on `signal` or the latest inner signal will be sent on the
/// returned signal.
///
/// The returned signal completes when `signal` and the latest inner
/// signal have both completed.
private func switchToLatest() -> Signal<Value.Value, Error> {
return Signal<Value.Value, Error> { observer in
let composite = CompositeDisposable()
let serial = SerialDisposable()
composite += serial
composite += self.observeSwitchToLatest(observer, serial)
return composite
}
}
private func observeSwitchToLatest(observer: Observer<Value.Value, Error>, _ latestInnerDisposable: SerialDisposable) -> Disposable? {
let state = Atomic(LatestState<Value, Error>())
return self.observe { event in
switch event {
case let .Next(innerProducer):
innerProducer.startWithSignal { innerSignal, innerDisposable in
state.modify {
// When we replace the disposable below, this prevents the
// generated Interrupted event from doing any work.
var state = $0
state.replacingInnerSignal = true
return state
}
latestInnerDisposable.innerDisposable = innerDisposable
state.modify {
var state = $0
state.replacingInnerSignal = false
state.innerSignalComplete = false
return state
}
innerSignal.observe { event in
switch event {
case .Interrupted:
// If interruption occurred as a result of a new producer
// arriving, we don't want to notify our observer.
let original = state.modify {
var state = $0
if !state.replacingInnerSignal {
state.innerSignalComplete = true
}
return state
}
if !original.replacingInnerSignal && original.outerSignalComplete {
observer.sendCompleted()
}
case .Completed:
let original = state.modify {
var state = $0
state.innerSignalComplete = true
return state
}
if original.outerSignalComplete {
observer.sendCompleted()
}
case .Next, .Failed:
observer.action(event)
}
}
}
case let .Failed(error):
observer.sendFailed(error)
case .Completed:
let original = state.modify {
var state = $0
state.outerSignalComplete = true
return state
}
if original.innerSignalComplete {
observer.sendCompleted()
}
case .Interrupted:
observer.sendInterrupted()
}
}
}
}
extension SignalProducerType where Value: SignalProducerType, Error == Value.Error {
/// Returns a signal that forwards values from the latest signal sent on
/// `signal`, ignoring values sent on previous inner signal.
///
/// An error sent on `signal` or the latest inner signal will be sent on the
/// returned signal.
///
/// The returned signal completes when `signal` and the latest inner
/// signal have both completed.
private func switchToLatest() -> SignalProducer<Value.Value, Error> {
return SignalProducer<Value.Value, Error> { observer, disposable in
let latestInnerDisposable = SerialDisposable()
disposable.addDisposable(latestInnerDisposable)
self.startWithSignal { signal, signalDisposable in
disposable += signalDisposable
disposable += signal.observeSwitchToLatest(observer, latestInnerDisposable)
}
}
}
}
private struct LatestState<Value, Error: ErrorType> {
var outerSignalComplete: Bool = false
var innerSignalComplete: Bool = true
var replacingInnerSignal: Bool = false
}
extension SignalType {
/// Maps each event from `signal` to a new signal, then flattens the
/// resulting producers (into a signal of values), according to the
/// semantics of the given strategy.
///
/// If `signal` or any of the created producers fail, the returned signal
/// will forward that failure immediately.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func flatMap<U>(strategy: FlattenStrategy, transform: Value -> SignalProducer<U, Error>) -> Signal<U, Error> {
return map(transform).flatten(strategy)
}
/// Maps each event from `signal` to a new signal, then flattens the
/// resulting producers (into a signal of values), according to the
/// semantics of the given strategy.
///
/// If `signal` fails, the returned signal will forward that failure
/// immediately.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func flatMap<U>(strategy: FlattenStrategy, transform: Value -> SignalProducer<U, NoError>) -> Signal<U, Error> {
return map(transform).flatten(strategy)
}
/// Maps each event from `signal` to a new signal, then flattens the
/// resulting signals (into a signal of values), according to the
/// semantics of the given strategy.
///
/// If `signal` or any of the created signals emit an error, the returned
/// signal will forward that error immediately.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func flatMap<U>(strategy: FlattenStrategy, transform: Value -> Signal<U, Error>) -> Signal<U, Error> {
return map(transform).flatten(strategy)
}
/// Maps each event from `signal` to a new signal, then flattens the
/// resulting signals (into a signal of values), according to the
/// semantics of the given strategy.
///
/// If `signal` emits an error, the returned signal will forward that
/// error immediately.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func flatMap<U>(strategy: FlattenStrategy, transform: Value -> Signal<U, NoError>) -> Signal<U, Error> {
return map(transform).flatten(strategy)
}
}
extension SignalType where Error == NoError {
/// Maps each event from `signal` to a new signal, then flattens the
/// resulting signals (into a signal of values), according to the
/// semantics of the given strategy.
///
/// If any of the created signals emit an error, the returned signal
/// will forward that error immediately.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func flatMap<U, E>(strategy: FlattenStrategy, transform: Value -> SignalProducer<U, E>) -> Signal<U, E> {
return map(transform).flatten(strategy)
}
/// Maps each event from `signal` to a new signal, then flattens the
/// resulting signals (into a signal of values), according to the
/// semantics of the given strategy.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func flatMap<U>(strategy: FlattenStrategy, transform: Value -> SignalProducer<U, NoError>) -> Signal<U, NoError> {
return map(transform).flatten(strategy)
}
/// Maps each event from `signal` to a new signal, then flattens the
/// resulting signals (into a signal of values), according to the
/// semantics of the given strategy.
///
/// If any of the created signals emit an error, the returned signal
/// will forward that error immediately.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func flatMap<U, E>(strategy: FlattenStrategy, transform: Value -> Signal<U, E>) -> Signal<U, E> {
return map(transform).flatten(strategy)
}
/// Maps each event from `signal` to a new signal, then flattens the
/// resulting signals (into a signal of values), according to the
/// semantics of the given strategy.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func flatMap<U>(strategy: FlattenStrategy, transform: Value -> Signal<U, NoError>) -> Signal<U, NoError> {
return map(transform).flatten(strategy)
}
}
extension SignalProducerType {
/// Maps each event from `self` to a new producer, then flattens the
/// resulting producers (into a producer of values), according to the
/// semantics of the given strategy.
///
/// If `self` or any of the created producers fail, the returned producer
/// will forward that failure immediately.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func flatMap<U>(strategy: FlattenStrategy, transform: Value -> SignalProducer<U, Error>) -> SignalProducer<U, Error> {
return map(transform).flatten(strategy)
}
/// Maps each event from `self` to a new producer, then flattens the
/// resulting producers (into a producer of values), according to the
/// semantics of the given strategy.
///
/// If `self` fails, the returned producer will forward that failure
/// immediately.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func flatMap<U>(strategy: FlattenStrategy, transform: Value -> SignalProducer<U, NoError>) -> SignalProducer<U, Error> {
return map(transform).flatten(strategy)
}
/// Maps each event from `self` to a new producer, then flattens the
/// resulting signals (into a producer of values), according to the
/// semantics of the given strategy.
///
/// If `self` or any of the created signals emit an error, the returned
/// producer will forward that error immediately.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func flatMap<U>(strategy: FlattenStrategy, transform: Value -> Signal<U, Error>) -> SignalProducer<U, Error> {
return map(transform).flatten(strategy)
}
/// Maps each event from `self` to a new producer, then flattens the
/// resulting signals (into a producer of values), according to the
/// semantics of the given strategy.
///
/// If `self` emits an error, the returned producer will forward that
/// error immediately.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func flatMap<U>(strategy: FlattenStrategy, transform: Value -> Signal<U, NoError>) -> SignalProducer<U, Error> {
return map(transform).flatten(strategy)
}
}
extension SignalProducerType where Error == NoError {
/// Maps each event from `self` to a new producer, then flattens the
/// resulting producers (into a producer of values), according to the
/// semantics of the given strategy.
///
/// If any of the created producers fail, the returned producer will
/// forward that failure immediately.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func flatMap<U, E>(strategy: FlattenStrategy, transform: Value -> SignalProducer<U, E>) -> SignalProducer<U, E> {
return map(transform).flatten(strategy)
}
/// Maps each event from `self` to a new producer, then flattens the
/// resulting producers (into a producer of values), according to the
/// semantics of the given strategy.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func flatMap<U>(strategy: FlattenStrategy, transform: Value -> SignalProducer<U, NoError>) -> SignalProducer<U, NoError> {
return map(transform).flatten(strategy)
}
/// Maps each event from `self` to a new producer, then flattens the
/// resulting signals (into a producer of values), according to the
/// semantics of the given strategy.
///
/// If any of the created signals emit an error, the returned
/// producer will forward that error immediately.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func flatMap<U, E>(strategy: FlattenStrategy, transform: Value -> Signal<U, E>) -> SignalProducer<U, E> {
return map(transform).flatten(strategy)
}
/// Maps each event from `self` to a new producer, then flattens the
/// resulting signals (into a producer of values), according to the
/// semantics of the given strategy.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func flatMap<U>(strategy: FlattenStrategy, transform: Value -> Signal<U, NoError>) -> SignalProducer<U, NoError> {
return map(transform).flatten(strategy)
}
}
extension SignalType {
/// Catches any failure that may occur on the input signal, mapping to a new producer
/// that starts in its place.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func flatMapError<F>(handler: Error -> SignalProducer<Value, F>) -> Signal<Value, F> {
return Signal { observer in
self.observeFlatMapError(handler, observer, SerialDisposable())
}
}
private func observeFlatMapError<F>(handler: Error -> SignalProducer<Value, F>, _ observer: Observer<Value, F>, _ serialDisposable: SerialDisposable) -> Disposable? {
return self.observe { event in
switch event {
case let .Next(value):
observer.sendNext(value)
case let .Failed(error):
handler(error).startWithSignal { signal, disposable in
serialDisposable.innerDisposable = disposable
signal.observe(observer)
}
case .Completed:
observer.sendCompleted()
case .Interrupted:
observer.sendInterrupted()
}
}
}
}
extension SignalProducerType {
/// Catches any failure that may occur on the input producer, mapping to a new producer
/// that starts in its place.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func flatMapError<F>(handler: Error -> SignalProducer<Value, F>) -> SignalProducer<Value, F> {
return SignalProducer { observer, disposable in
let serialDisposable = SerialDisposable()
disposable.addDisposable(serialDisposable)
self.startWithSignal { signal, signalDisposable in
serialDisposable.innerDisposable = signalDisposable
signal.observeFlatMapError(handler, observer, serialDisposable)
}
}
}
}
| 7541569312651e1aa73f9db191599eca | 36.452229 | 186 | 0.720862 | false | false | false | false |
jurre/TravisToday | refs/heads/master | Today/RepoService.swift | mit | 1 | //
// RepoService.swift
// Travis
//
// Created by Jurre Stender on 22/10/14.
// Copyright (c) 2014 jurre. All rights reserved.
//
import Foundation
class RepoService: BaseService {
class var sharedService: RepoService {
struct Static {
static var onceToken : dispatch_once_t = 0
static var instance : RepoService? = nil
}
dispatch_once(&Static.onceToken) {
Static.instance = RepoService()
}
return Static.instance!
}
func find(repo: Repo, completion: (Bool, Repo?) -> Void) {
let request = self.request(repo.url)
let fetchRepo = {() -> Void in
let task = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data, request, error) -> Void in
if (error != nil) {
println(error.localizedDescription)
completion(false, .None)
} else {
if let parsedRepo = RepoParser.fromJSONData(data) {
parsedRepo.access = repo.access
completion(true, parsedRepo)
} else {
completion(false, .None)
}
}
})
task.resume()
}
if (repo.access == .Private) {
TokenService().fetchToken({ (success, token) -> Void in
if (success) {
request.setValue(token!, forHTTPHeaderField: "Authorization")
fetchRepo()
} else {
println("Error fetching token")
completion(false, .None)
}
})
} else {
fetchRepo()
}
}
}
| 288c16dc7a8314b663e2ff715021b2b4 | 22.431034 | 126 | 0.638705 | false | false | false | false |
hooliooo/Astral | refs/heads/master | Sources/Astral/HTTPMethod.swift | mit | 1 | //
// Astral
// Copyright (c) Julio Miguel Alorro
// Licensed under the MIT license. See LICENSE file
//
/**
An enum that represents http methods
*/
public enum HTTPMethod {
/**
- http GET method
*/
case get
/**
- http DELETE method
*/
case delete
/**
- http POST method
*/
case post
/**
- http PUT method
*/
case put
/**
- http PATCH method
*/
case patch
/**
- other http method
*/
case method(String)
// MARK: Initializer
/**
Initializer for creating an instance of HTTPMethod
- parameter method: The stringValue of the HTTPMethod to be created
*/
public init(_ method: String) {
switch method {
case "GET": self = HTTPMethod.get
case "DELETE": self = HTTPMethod.delete
case "POST": self = HTTPMethod.post
case "PUT": self = HTTPMethod.put
case "PATCH": self = HTTPMethod.patch
default: self = HTTPMethod.method(method)
}
}
/**
String representation of the HTTPMethod
*/
public var stringValue: String {
switch self {
case .get: return "GET"
case .delete: return "DELETE"
case .post: return "POST"
case .put: return "PUT"
case .patch: return "PATCH"
case .method(let method): return method
}
}
}
// MARK: Hashable Protocol
extension HTTPMethod: Hashable {
public static func == (lhs: HTTPMethod, rhs: HTTPMethod) -> Bool {
switch (lhs, rhs) {
case (.get, .get): return true
case (.delete, .delete): return true
case (.post, .post): return true
case (.put, .put): return true
case (.patch, .patch): return true
case let (.method(lhsMethod), .method(rhsMethod)): return lhsMethod == rhsMethod
default: return false
}
}
public func hash(into hasher: inout Hasher) {
switch self {
case .get: hasher.combine(1337)
case .delete: hasher.combine(1338)
case .post: hasher.combine(1339)
case .put: hasher.combine(1340)
case .patch: hasher.combine(1341)
case .method(let method): hasher.combine(1342 &+ method.hashValue)
}
}
}
extension HTTPMethod: CustomStringConvertible {
public var description: String {
return self.stringValue
}
}
extension HTTPMethod: CustomDebugStringConvertible {
public var debugDescription: String {
return self.description
}
}
| cba2f2a9c08f253ec637425d87c89c57 | 19.573913 | 86 | 0.625528 | false | false | false | false |
superpixelhq/AbairLeat-iOS | refs/heads/master | Abair Leat/Table Cells/OneToOneTableViewCell.swift | apache-2.0 | 1 | //
// OneToOneTableViewCell.swift
// Abair Leat
//
// Created by Aaron Signorelli on 30/11/2015.
// Copyright © 2015 Superpixel. All rights reserved.
//
import UIKit
import Firebase
class OneToOneTableViewCell: UITableViewCell, ChatsListTableViewControllerCell {
@IBOutlet weak var avatar: UIImageView!
@IBOutlet weak var otherPersonsName: UILabel!
@IBOutlet weak var lastChatMessage: UILabel!
@IBOutlet weak var dateLastMessageSent: UILabel!
override func awakeFromNib() {
self.contentView.backgroundColor = UIColor.clearColor()
self.contentView.opaque = false
self.contentView.superview?.backgroundColor = UIColor.clearColor()
self.contentView.superview?.opaque = false
}
func setup(conversation: ConversationMetadata) {
let me = AbairLeat.shared.profile.me!
let theirIndex = conversation.participants.indexOf({$0.1.id != me.id})!
let them = conversation.participants[theirIndex].1
self.avatar.hnk_setImageFromURL(NSURL(string: them.avatarUrlString)!)
self.otherPersonsName.text = them.name
self.lastChatMessage.text = conversation.lastMessageSent
if let sentDate = conversation.dateLastMessageSent {
self.dateLastMessageSent.text = sentDate.occuredToday() ? sentDate.toShortTimeStyle() : sentDate.toShortDateStyle()
} else {
self.dateLastMessageSent.text = ""
}
}
}
| 12ac012bf20edb849cb3fd68f1e0742f | 34.902439 | 127 | 0.690897 | false | false | false | false |
royhsu/tiny-core | refs/heads/master | Sources/Core/Array+InsertBetween.swift | mit | 1 | //
// Array+InsertBetween.swift
// TinyCore
//
// Created by Roy Hsu on 2018/4/5.
// Copyright © 2018 TinyWorld. All rights reserved.
//
// MARK: - Insert Between
extension Array {
/// You can specify the between to return nil for skipping the certain insertions.
///
/// For example:
///
/// let output = [ 1.0, 2.0, 3.0 ].insert { previous, next in
///
/// Only insert values if the previous is greater than or equal to 2.0
/// if previous >= 2.0 { return nil }
///
/// return (previous + next) / 2.0
///
/// }
///
/// The output is: [ 1.0, 1.5, 2.0, 3.0 ]
///
public func inserted(
between: (_ previous: Element, _ next: Element) -> Element?
)
-> [Element] {
return reduce([]) { currentResult, next in
var nextResult = currentResult
guard
let previous = currentResult.last,
let between = between(previous, next)
else { nextResult.append(next); return nextResult }
nextResult.append(contentsOf: [ between, next ])
return nextResult
}
}
public mutating func insert(
between: (_ previous: Element, _ next: Element) -> Element?
) { self = inserted(between: between) }
}
| 6a03cf4ed489294093e577f53c1b26ff | 23.166667 | 86 | 0.547126 | false | false | false | false |
dokun1/jordan-meme-ios | refs/heads/master | JordanHeadMeme/JordanHeadMeme/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// JordanHeadMeme
//
// Created by David Okun on 12/18/15.
// Copyright © 2015 David Okun, LLC. All rights reserved.
//
import UIKit
import SVProgressHUD
import Fabric
import Crashlytics
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
@available(iOS 9.0, *)
lazy var shortcutItem: UIApplicationShortcutItem? = {
return nil
}()
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
SVProgressHUD.setBackgroundColor(UIColor.colorSchemeTwo())
SVProgressHUD.setForegroundColor(UIColor.colorSchemeOne())
application.statusBarHidden = true
var performShortcutDelegate = true
if #available(iOS 9.0, *) {
if let shortcutItem = launchOptions?[UIApplicationLaunchOptionsShortcutItemKey] as? UIApplicationShortcutItem {
self.shortcutItem = shortcutItem
performShortcutDelegate = false
}
}
if UIApplication.sharedApplication().isDebugMode {
print("APP LOADED IN DEBUG MODE")
} else {
Fabric.with([Answers.self, Crashlytics.self])
}
return performShortcutDelegate
}
@available(iOS 9.0, *)
func application(application: UIApplication, performActionForShortcutItem shortcutItem: UIApplicationShortcutItem, completionHandler: (Bool) -> Void) {
completionHandler(handleShortcut(shortcutItem))
}
@available(iOS 9.0, *)
func handleShortcut( shortcutItem:UIApplicationShortcutItem ) -> Bool {
var succeeded = true
let mainViewController = self.window?.rootViewController as! ViewController
if shortcutItem.type.containsString("takeSelfie") {
Analytics.logCustomEventWithName("Shortcut Used", customAttributes: ["Method":"Take Selfie"])
mainViewController.takeSelfieTapped()
} else if shortcutItem.type.containsString("choosePhoto") {
Analytics.logCustomEventWithName("Shortcut Used", customAttributes: ["Method":"Choose Photo"])
mainViewController.choosePhotoTapped()
} else if shortcutItem.type.containsString("takePhoto") {
Analytics.logCustomEventWithName("Shortcut Used", customAttributes: ["Method":"Take Photo"])
mainViewController.takePhotoTapped()
} else {
succeeded = false
}
return succeeded
}
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:.
}
}
| 31fe8a3d253a642e442f8cd5a6625b3a | 45.681319 | 285 | 0.713748 | false | false | false | false |
DianQK/rx-sample-code | refs/heads/master | TextInput/InputCollectionViewCell.swift | mit | 1 | //
// InputCollectionViewCell.swift
// TextInputDemo
//
// Created by DianQK on 18/01/2017.
// Copyright © 2017 T. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
class InputCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var textField: InputTextField!
var isInputing: UIBindingObserver<InputCollectionViewCell, Bool> {
return UIBindingObserver(UIElement: self, binding: { (UIElement, value) in
UIElement.textField._canBecomeFirstResponder = value
if value {
_ = UIElement.becomeFirstResponder()
} else {
_ = UIElement.resignFirstResponder()
}
})
}
var canInput: UIBindingObserver<InputCollectionViewCell, Bool> {
return UIBindingObserver(UIElement: self, binding: { (UIElement, value) in
UIElement.textField._canBecomeFirstResponder = value
})
}
override func becomeFirstResponder() -> Bool {
return textField.becomeFirstResponder()
}
override var canBecomeFirstResponder: Bool {
return textField.canBecomeFirstResponder
}
override var canResignFirstResponder: Bool {
return textField.canResignFirstResponder
}
override func resignFirstResponder() -> Bool {
return textField.resignFirstResponder()
}
override var isFirstResponder: Bool {
return textField.isFirstResponder
}
private(set) var reuseDisposeBag = DisposeBag()
override func awakeFromNib() {
super.awakeFromNib()
textField.text = nil
}
override func prepareForReuse() {
super.prepareForReuse()
textField.text = nil
reuseDisposeBag = DisposeBag()
}
}
| 5e87af22611ebc8deafef113b9aac628 | 25.089552 | 82 | 0.657895 | false | false | false | false |
NickAger/elm-slider | refs/heads/master | Modules/HTTPFile/Sources/HTTPFile/Response+File.swift | mit | 5 | extension Response {
public init(status: Status = .ok, headers: Headers = [:], filePath: String) throws {
do {
var filePath = filePath
let file: File
// This logic should not be here. It should be defined before calling the initializer.
// Also use some String extension like String.fileExtension?
if filePath.split(separator: ".").count == 1 {
filePath += ".html"
}
do {
file = try File(path: filePath, mode: .read)
} catch {
file = try File(path: filePath + "html", mode: .read)
}
self.init(status: status, headers: headers, body: file)
if let fileExtension = file.fileExtension, let mediaType = mediaType(forFileExtension: fileExtension) {
self.contentType = mediaType
}
} catch {
throw HTTPError.notFound
}
}
}
| 419f3adea1d6591caa3ca9d58612b3ff | 33.678571 | 115 | 0.532441 | false | false | false | false |
sebcode/SwiftHelperKit | refs/heads/master | Source/IniParser.swift | mit | 1 | //
// IniParser.swift
// SwiftHelperKit
//
// Copyright © 2015 Sebastian Volland. All rights reserved.
//
import Foundation
open class IniParser {
open class func parse(string: String) -> [String: [String: String]] {
guard string != "" else {
return [:]
}
let lines = string.components(separatedBy: "\n") as [String]
var currentSectionName = ""
var currentSection: [String: String] = [:]
var ret: [String: [String: String]] = [:]
for line in lines {
if line.hasPrefix("[") {
if currentSectionName != "" {
ret[currentSectionName] = currentSection
currentSection = [:]
}
currentSectionName = String(line[line.index(line.startIndex, offsetBy: 1)..<line.index(line.endIndex, offsetBy: -1)])
}
if line != "" && currentSectionName != "" {
if let range = line.range(of: "=") {
let key = line[..<range.lowerBound].trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
let value = String(line.suffix(from: range.upperBound)).trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
currentSection[key] = value
}
}
}
if currentSectionName != "" {
ret[currentSectionName] = currentSection
}
return ret
}
}
| 657489c01c6400ee59bec3d5f4a657cd | 30.804348 | 135 | 0.539986 | false | false | false | false |
JerrySir/YCOA | refs/heads/master | YCOA/Main/Attendance/Controller/AttendanceViewController.swift | mit | 1 | //
// AttendanceViewController.swift
// YCOA
//
// Created by Jerry on 2016/12/15.
// Copyright © 2016年 com.baochunsteel. All rights reserved.
//
// 考勤中心
import UIKit
import MapKit
import CoreLocation
class AttendanceViewController: UIViewController, MKMapViewDelegate, UITableViewDataSource {
private var mapView : MKMapView?
private var locationManager : CLLocationManager?
private var geocoder : CLGeocoder?
private var annotation = MKPointAnnotation()
private var latitude : CGFloat = 0.0
private var longitude: CGFloat = 0.0
private var addressString : String?
private var historyRecordArr : [String] = [] //历史签到记录
private var tableView : UITableView?
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.groupTableViewBackground
self.title = "签到中心"
self.initMapView()
self.initHistoryRecordView()
self.getHistoryRecord()
// Do any additional setup after loading the view.
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
self.mapView?.showsUserLocation = false
self.mapView?.userTrackingMode = MKUserTrackingMode.none
self.mapView?.layer.removeAllAnimations()
self.mapView?.removeOverlays((self.mapView?.overlays)!)
self.mapView?.removeFromSuperview()
self.mapView?.delegate = nil
self.mapView = nil
self.locationManager = nil
self.geocoder = nil
self.annotation = MKPointAnnotation()
self.view.removeAllSubviews()
}
deinit {
NSLog("签到控制器正常释放")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: - History record View
func initHistoryRecordView() {
//
let label = UILabel(frame: CGRect(x: 8, y: JRSCREEN_HEIGHT - 170, width: JRSCREEN_WIDTH - 16, height: 50))
label.text = "历史签到记录:"
self.view.addSubview(label)
//签到按钮
let button = UIButton(frame: CGRect(x: JRSCREEN_WIDTH - 108, y: JRSCREEN_HEIGHT - 160, width: 100, height: 30))
button.setTitle("签到", for: UIControlState.normal)
button.setTitleColor(UIColor.white, for: UIControlState.normal)
button.backgroundColor = UIColor.lightGray
button.rac_signal(for: UIControlEvents.touchUpInside).subscribeNext { (sender) in
NSLog("签到")
guard self.addressString != nil else{
self.view.jrShow(withTitle: "还未定位成功,请稍后!")
return
}
guard UserCenter.shareInstance().isLogin else {
self.view.jrShow(withTitle: "未登录!")
return
}
let parameters = ["adminid": UserCenter.shareInstance().uid!,
"timekey": NSDate.nowTimeToTimeStamp(),
"token": UserCenter.shareInstance().token!,
"cfrom": "appiphone",
"appapikey": UserCenter.shareInstance().apikey!,
"location_x": self.latitude,
"location_y": self.longitude,
"scale": 18,
"label": self.addressString!] as [String : Any]
YCOA_NetWork.get(url: "/index.php?d=taskrun&m=kaoqin|appapi&a=dwdk&ajaxbool=true",
parameters: parameters,
completionHandler:
{ (error, returnValue) in
if(error != nil){
self.navigationController?.view.jrShow(withTitle: error!.domain)
return
}
self.navigationController?.view.jrShow(withTitle: "签到成功!")
self.getHistoryRecord()
})
}
self.view.addSubview(button)
button.layer.masksToBounds = true
button.layer.cornerRadius = 10/2
//历史签到记录列表
self.tableView = UITableView(frame: CGRect(x: 8, y: JRSCREEN_HEIGHT - 120, width: JRSCREEN_WIDTH - 16, height: 120), style: UITableViewStyle.plain)
self.tableView!.dataSource = self
self.view.addSubview(self.tableView!)
}
//MARK: - Map View
func initMapView() {
let rect = CGRect(x: 0, y: 0, width: JRSCREEN_WIDTH, height: JRSCREEN_HEIGHT - 170)
self.mapView = MKMapView(frame: rect)
self.view.addSubview(self.mapView!)
//设置代理
self.mapView!.delegate = self
//请求定位服务
self.locationManager = CLLocationManager()
if(!CLLocationManager.locationServicesEnabled() || CLLocationManager.authorizationStatus() != CLAuthorizationStatus.authorizedWhenInUse){
self.locationManager?.requestWhenInUseAuthorization()
}
//用户位置追踪(用户位置追踪用于标记用户当前位置,此时会调用定位服务)
self.mapView!.userTrackingMode = MKUserTrackingMode.follow
//设置地图类型
self.mapView!.mapType = MKMapType.standard
}
/// 添加大头针
func addAnnotation() {
self.mapView?.removeAnnotation(self.annotation)
let location = CLLocationCoordinate2DMake(CLLocationDegrees(self.latitude), CLLocationDegrees(self.longitude))
self.annotation = MKPointAnnotation()
self.annotation.title = "当前位置"
self.annotation.subtitle = self.addressString
self.annotation.coordinate = location
self.mapView?.addAnnotation(self.annotation)
self.mapView?.selectAnnotation(self.annotation, animated: true)
}
func mapView(_ mapView: MKMapView, didUpdate userLocation: MKUserLocation) {
self.latitude = CGFloat(userLocation.coordinate.latitude)
self.longitude = CGFloat(userLocation.coordinate.longitude)
self.getAddressByLatitude(latitude: CLLocationDegrees(self.latitude), longitude: CLLocationDegrees(self.longitude))
self.mapView?.showsUserLocation = true
}
func getAddressByLatitude(latitude: CLLocationDegrees, longitude: CLLocationDegrees) {
let location = CLLocation(latitude: latitude, longitude: longitude)
self.geocoder = CLGeocoder()
self.geocoder!.reverseGeocodeLocation(location, completionHandler: { (placemarks, error) in
guard error == nil else{
return
}
let placemark = placemarks?.first
guard let addressDic : NSDictionary = placemark?.addressDictionary as NSDictionary? else{
return
}
let adressString_ = (addressDic["FormattedAddressLines"] as! NSArray).componentsJoined(by: " ")
NSLog("\(adressString_)")
self.addressString = adressString_
self.mapView?.userLocation.title = self.addressString
self.mapView?.selectAnnotation(self.mapView!.userLocation, animated: true)
})
}
//MARK: - get history record
func getHistoryRecord() {
guard UserCenter.shareInstance().isLogin else {
self.view.jrShow(withTitle: "未登录!")
return
}
let parameters = ["adminid": UserCenter.shareInstance().uid!,
"timekey": NSDate.nowTimeToTimeStamp(),
"token": UserCenter.shareInstance().token!,
"cfrom": "appiphone",
"appapikey": UserCenter.shareInstance().apikey!]
YCOA_NetWork.get(url: "/index.php?d=taskrun&m=kaoqin|appapi&a=getlocation&ajaxbool=true",
parameters: parameters)
{ (error, returnValue) in
if(error != nil) {
self.navigationController?.view.jrShow(withTitle: error!.domain)
return
}
guard let data : NSArray = (returnValue as! NSDictionary).value(forKey: "data") as? NSArray else{
self.navigationController?.view.jrShow(withTitle: "暂无数据")
return
}
//同步数据
self.historyRecordArr = []
for item in data {
guard let itemDic = item as? NSDictionary else{
continue
}
let adress = itemDic["label"] as! String
let index = itemDic["id"] as! String
self.historyRecordArr.append(index + "次: " + adress)
}
self.tableView!.reloadData()
}
}
//MARK: - UITableViewDataSource
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.historyRecordArr.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "cell")
if(cell == nil){
cell = UITableViewCell(style: UITableViewCellStyle.value1, reuseIdentifier: "cell")
}
cell!.textLabel!.text = self.historyRecordArr[indexPath.row]
return cell!
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 61d6ea1154119c0c8fbb14dbd9134c65 | 37.498054 | 155 | 0.585102 | false | false | false | false |
lgp123456/tiantianTV | refs/heads/master | douyuTV/douyuTV/Classes/Live/Controller/ChildVc/XTTechnologyViewController.swift | mit | 1 | //
// XTTechnologyViewController.swift
// douyuTV
//
// Created by 李贵鹏 on 16/8/31.
// Copyright © 2016年 李贵鹏. All rights reserved.
//
import UIKit
class XTTechnologyViewController: XTBaseLiveViewController {
override func viewDidLoad() {
super.viewDidLoad()
// url = "http://capi.douyucdn.cn/api/v1/getColumnRoom/3?aid=ios&client_sys=ios&limit=20&offset=0&time=1469008980&auth=3392837008aa8938f7dce0d8c72c321d"
url = "http://capi.douyucdn.cn/api/v1/getColumnRoom/3?limit=20&offset=0"
}
}
| bc93aded020639bb18cef67d87776ba8 | 27.157895 | 160 | 0.695327 | false | false | false | false |
zapdroid/RXWeather | refs/heads/master | Pods/RxSwift/RxSwift/Observables/Implementations/Debounce.swift | mit | 1 | //
// Debounce.swift
// RxSwift
//
// Created by Krunoslav Zaher on 9/11/16.
// Copyright © 2016 Krunoslav Zaher. All rights reserved.
//
final class DebounceSink<O: ObserverType>
: Sink<O>
, ObserverType
, LockOwnerType
, SynchronizedOnType {
typealias Element = O.E
typealias ParentType = Debounce<Element>
private let _parent: ParentType
let _lock = RecursiveLock()
// state
private var _id = 0 as UInt64
private var _value: Element?
let cancellable = SerialDisposable()
init(parent: ParentType, observer: O, cancel: Cancelable) {
_parent = parent
super.init(observer: observer, cancel: cancel)
}
func run() -> Disposable {
let subscription = _parent._source.subscribe(self)
return Disposables.create(subscription, cancellable)
}
func on(_ event: Event<Element>) {
synchronizedOn(event)
}
func _synchronized_on(_ event: Event<Element>) {
switch event {
case let .next(element):
_id = _id &+ 1
let currentId = _id
_value = element
let scheduler = _parent._scheduler
let dueTime = _parent._dueTime
let d = SingleAssignmentDisposable()
cancellable.disposable = d
d.setDisposable(scheduler.scheduleRelative(currentId, dueTime: dueTime, action: propagate))
case .error:
_value = nil
forwardOn(event)
dispose()
case .completed:
if let value = _value {
_value = nil
forwardOn(.next(value))
}
forwardOn(.completed)
dispose()
}
}
func propagate(_ currentId: UInt64) -> Disposable {
_lock.lock(); defer { _lock.unlock() } // {
let originalValue = _value
if let value = originalValue, _id == currentId {
_value = nil
forwardOn(.next(value))
}
// }
return Disposables.create()
}
}
final class Debounce<Element>: Producer<Element> {
fileprivate let _source: Observable<Element>
fileprivate let _dueTime: RxTimeInterval
fileprivate let _scheduler: SchedulerType
init(source: Observable<Element>, dueTime: RxTimeInterval, scheduler: SchedulerType) {
_source = source
_dueTime = dueTime
_scheduler = scheduler
}
override func run<O: ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element {
let sink = DebounceSink(parent: self, observer: observer, cancel: cancel)
let subscription = sink.run()
return (sink: sink, subscription: subscription)
}
}
| 48221d2f7b9ccdb9c24d21987e817b2d | 26.47 | 144 | 0.593375 | false | false | false | false |
Keymochi/Keymochi | refs/heads/master | Keymochi/AppDelegate.swift | bsd-3-clause | 1 | //
// AppDelegate.swift
// Keymochi
//
// Created by Huai-Che Lu on 2/28/16.
// Copyright © 2016 Cornell Tech. All rights reserved.
//
import UIKit
import UserNotifications
import UserNotificationsUI
import Crashlytics
import Fabric
import Firebase
import FirebaseDatabase
import FirebaseMessaging
import PAM
import RealmSwift
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func applicationDidFinishLaunching(_ application: UIApplication) {
Fabric.with([Crashlytics.self])
FIRApp.configure()
if #available(iOS 10.0, *) {
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: {_, _ in })
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.current().delegate = self
// For iOS 10 data message (sent via FCM)
FIRMessaging.messaging().remoteMessageDelegate = self
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()
}
@nonobjc func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: Any]?) -> Bool {
// Override point for customization after application launch.
Fabric.with([Crashlytics.self])
let directoryURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: Constants.groupIdentifier)
let realmPath = (directoryURL?.appendingPathComponent("db.realm").path)!
var realmConfig = Realm.Configuration()
realmConfig.fileURL = URL.init(string: realmPath)
realmConfig.schemaVersion = 5
realmConfig.migrationBlock = { (migration, oldSchemaVersion) in
if oldSchemaVersion < 2 {
migration.enumerateObjects(ofType: DataChunk.className()) { (oldObject, newObject) in
newObject!["appVersion"] = "0.2.0"
}
}
if oldSchemaVersion < 3 {
migration.enumerateObjects(ofType: DataChunk.className()) { (oldObject, newObject) in
newObject!["firebaseKey"] = nil
}
}
}
Realm.Configuration.defaultConfiguration = realmConfig
return true
}
override init() {
super.init()
// not really needed unless you really need it FIRDatabase.database().persistenceEnabled = 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:.
}
}
extension AppDelegate: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
print(response)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
print(userInfo)
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
// Convert token to string
let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
// Print it to console
print("APNs device token: \(deviceTokenString)")
// Persist it in your backend in case it's new
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Fail to register for remote notification: \(error)")
}
}
extension AppDelegate: FIRMessagingDelegate {
func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) {
print(remoteMessage)
}
}
| 685365bf987955f3221e3ef515c00c3d | 42.251852 | 285 | 0.686076 | false | true | false | false |
macmade/AtomicKit | refs/heads/main | AtomicKitTests/Semaphore.swift | mit | 1 | /*******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2017 Jean-David Gadina - www.xs-labs.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
******************************************************************************/
import XCTest
import AtomicKit
class SemaphoreTest: XCTestCase
{
var testHelper: String?
override func setUp()
{
super.setUp()
let bundle = Bundle( identifier: "com.xs-labs.AtomicKitTests" )
if( bundle == nil || bundle?.executableURL == nil )
{
XCTFail( "Invalid bundle" )
}
let url = bundle?.executableURL?.deletingLastPathComponent().appendingPathComponent( "Test-Helper" )
if( url == nil || FileManager.default.fileExists( atPath: url!.path ) == false )
{
XCTFail( "Cannot find Test-Helper executable" )
}
self.testHelper = url!.path
}
override func tearDown()
{
super.tearDown()
}
func runHelper( command: String, args: [ String ] )
{
self.runHelper( commands: [ command : args ] )
}
func runHelper( commands: [ String : [ String ] ] )
{
var args = [ String ]()
if( self.testHelper == nil )
{
XCTFail( "Cannot find Test-Helper executable" )
}
for p in commands
{
args.append( p.key )
args.append( contentsOf: p.value )
}
let task = Process.launchedProcess( launchPath: self.testHelper!, arguments: args )
task.waitUntilExit()
}
func testUnnamedBinaryTryWait()
{
let sem = try? Semaphore()
XCTAssertNotNil( sem )
XCTAssertTrue( sem!.tryWait() )
XCTAssertFalse( sem!.tryWait() )
sem!.signal()
}
func testNamedBinaryTryWait()
{
let sem1 = try? Semaphore( count: 1, name: "XS-Test-Semaphore-1" )
let sem2 = try? Semaphore( count: 1, name: "XS-Test-Semaphore-1" )
XCTAssertNotNil( sem1 )
XCTAssertNotNil( sem2 )
XCTAssertTrue( sem1!.tryWait() )
XCTAssertFalse( sem1!.tryWait() )
XCTAssertFalse( sem2!.tryWait() )
sem1!.signal()
XCTAssertTrue( sem2!.tryWait() )
XCTAssertFalse( sem2!.tryWait() )
XCTAssertFalse( sem1!.tryWait() )
sem2!.signal()
}
func testUnnamedTryWait()
{
let sem = try? Semaphore( count: 2 )
XCTAssertNotNil( sem )
XCTAssertTrue( sem!.tryWait() )
XCTAssertTrue( sem!.tryWait() )
XCTAssertFalse( sem!.tryWait() )
sem!.signal()
sem!.signal()
}
func testNamedTryWait()
{
let sem1 = try? Semaphore( count: 2, name: "XS-Test-Semaphore-2" )
let sem2 = try? Semaphore( count: 2, name: "XS-Test-Semaphore-2" )
XCTAssertNotNil( sem1 )
XCTAssertNotNil( sem2 )
XCTAssertTrue( sem1!.tryWait() )
XCTAssertTrue( sem1!.tryWait() )
XCTAssertFalse( sem1!.tryWait() )
XCTAssertFalse( sem2!.tryWait() )
sem1!.signal()
XCTAssertTrue( sem2!.tryWait() )
XCTAssertFalse( sem1!.tryWait() )
sem1!.signal()
sem2!.signal()
}
func testUnnamedWaitSignal()
{
let sem = try? Semaphore( count: 1 )
XCTAssertNotNil( sem )
sem!.wait()
XCTAssertFalse( sem!.tryWait() )
sem!.signal()
XCTAssertTrue( sem!.tryWait() )
sem!.signal()
}
func testNamedWaitSignal()
{
let sem1 = try? Semaphore( count: 1, name: "XS-Test-Semaphore-1" )
let sem2 = try? Semaphore( count: 1, name: "XS-Test-Semaphore-1" )
XCTAssertNotNil( sem1 )
XCTAssertNotNil( sem2 )
sem1!.wait()
XCTAssertFalse( sem1!.tryWait() )
XCTAssertFalse( sem2!.tryWait() )
sem1!.signal()
XCTAssertTrue( sem2!.tryWait() )
XCTAssertFalse( sem1!.tryWait() )
sem2!.signal()
}
func testUnnamedThrowOnInvalidCount()
{
XCTAssertThrowsError( try Semaphore( count: 0 ) );
}
func testNamedThrowOnInvalidCount()
{
XCTAssertThrowsError( try Semaphore( count: 0, name: "XS-Test-Semaphore-0" ) );
}
func testNamedThrowOnInvalidName()
{
var name = "XS-Test-Semaphore-"
for _ in 0 ... 256
{
name += "X";
}
XCTAssertThrowsError( try Semaphore( count: 1, name:name ) );
}
func testIsNamed()
{
let sem1 = try? Semaphore( count: 1, name: "XS-Test-Semaphore-1" )
let sem2 = try? Semaphore()
XCTAssertNotNil( sem1 )
XCTAssertNotNil( sem2 )
XCTAssertTrue( sem1!.isNamed );
XCTAssertFalse( sem2!.isNamed );
}
func testGetName()
{
let sem1 = try? Semaphore( count: 1, name: "XS-Test-Semaphore-1" )
let sem2 = try? Semaphore()
XCTAssertNotNil( sem1 )
XCTAssertNotNil( sem2 )
XCTAssertEqual( sem1!.name, "/XS-Test-Semaphore-1" )
XCTAssertEqual( sem2!.name, nil )
}
}
| 8ad86760dc6c65bcecf552ceb613cfe7 | 27.769912 | 108 | 0.549985 | false | true | false | false |
damoyan/BYRClient | refs/heads/master | FromScratch/Utils.swift | mit | 1 | //
// Utils.swift
// FromScratch
//
// Created by Yu Pengyang on 11/7/15.
// Copyright © 2015 Yu Pengyang. All rights reserved.
//
import UIKit
import ImageIO
class Utils: NSObject {
static var defaultDateFormatter: NSDateFormatter = {
let formatter = NSDateFormatter()
formatter.dateStyle = .LongStyle
formatter.timeStyle = .LongStyle
return formatter
}()
static var main: UIStoryboard = {
return UIStoryboard.init(name: "Main", bundle: nil)
}()
static func dateFromUnixTimestamp(ts: Int?) -> NSDate? {
guard let ts = ts else {
return nil
}
return NSDate(timeIntervalSince1970: NSTimeInterval(ts))
}
static func getImagesFromData(data: NSData) throws -> [UIImage] {
guard let source = CGImageSourceCreateWithData(data, nil) else {
throw BYRError.CreateImageSourceFailed
}
var images = [UIImage]()
autoreleasepool {
let frameCount = CGImageSourceGetCount(source)
for var i = 0; i < frameCount; i++ {
if let image = CGImageSourceCreateImageAtIndex(source, i, nil) {
let alphaInfo = CGImageGetAlphaInfo(image).rawValue & CGBitmapInfo.AlphaInfoMask.rawValue
let hasAlpha: Bool
if (alphaInfo == CGImageAlphaInfo.PremultipliedLast.rawValue ||
alphaInfo == CGImageAlphaInfo.PremultipliedFirst.rawValue ||
alphaInfo == CGImageAlphaInfo.Last.rawValue ||
alphaInfo == CGImageAlphaInfo.First.rawValue) {
hasAlpha = true
} else {
hasAlpha = false
}
// // BGRA8888 (premultiplied) or BGRX8888
// // same as UIGraphicsBeginImageContext() and -[UIView drawRect:]
var bitmapInfo = CGBitmapInfo.ByteOrderDefault.rawValue // kCGBitmapByteOrder32Host;
bitmapInfo |= hasAlpha ? CGImageAlphaInfo.PremultipliedLast.rawValue : CGImageAlphaInfo.NoneSkipFirst.rawValue;
let context = CGBitmapContextCreate(nil, CGImageGetWidth(image), CGImageGetHeight(image), 8, 0, CGColorSpaceCreateDeviceRGB(), bitmapInfo)
CGContextDrawImage(context, CGRect(x: 0, y: 0, width: CGImageGetWidth(image), height: CGImageGetHeight(image)), image) // decode
let newImage = CGBitmapContextCreateImage(context)!
images.append(UIImage(CGImage: newImage))
}
}
}
return images
}
static func getEmotionData(name: String) -> NSData? {
var imageName: String, imageFolder: String
let folderPrefix = "emotions/"
if name.hasPrefix("emc") {
imageFolder = folderPrefix + "emc"
imageName = (name as NSString).substringFromIndex(3)
} else if name.hasPrefix("emb") {
imageFolder = folderPrefix + "emb"
imageName = (name as NSString).substringFromIndex(3)
} else if name.hasPrefix("ema") {
imageFolder = folderPrefix + "ema"
imageName = (name as NSString).substringFromIndex(3)
} else {
imageFolder = folderPrefix + "em"
imageName = (name as NSString).substringFromIndex(2)
}
let path = NSBundle.mainBundle().pathForResource(imageName, ofType: "gif", inDirectory: imageFolder)
if let path = path, data = NSData(contentsOfFile: path) {
return data
}
return nil
}
}
extension UIViewController {
func navigateToLogin() {
dismissViewControllerAnimated(true, completion: nil)
}
func navigateToSectionDetail(section: Section) {
let vc = Utils.main.instantiateViewControllerWithIdentifier("vcSection") as! SectionViewController
vc.section = section
navigationController?.pushViewController(vc, animated: true)
}
func navigateToFavorite(level: Int) {
let vc = Utils.main.instantiateViewControllerWithIdentifier("vcFavorite") as! FavoriteViewController
vc.level = level
navigationController?.pushViewController(vc, animated: true)
}
func navigateToBoard(name: String) {
let vc = Utils.main.instantiateViewControllerWithIdentifier("vcBoard") as! BoardViewController
vc.boardName = name
navigationController?.pushViewController(vc, animated: true)
}
func navigateToThread(article: Article) {
let vc = Utils.main.instantiateViewControllerWithIdentifier("vcThread") as! ThreadViewController
vc.topic = article
navigationController?.pushViewController(vc, animated: true)
}
}
extension NSDate {
}
extension UIImage {
class func imageWithColor(color: UIColor, side: CGFloat) -> UIImage {
let rect = CGRect(x: 0, y: 0, width: side, height: side)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
CGContextSetFillColorWithColor(context, color.CGColor)
CGContextFillRect(context, rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
extension UIColor {
convenience init(rgb: UInt, alpha: CGFloat = 1) {
self.init(red: CGFloat((rgb & 0xff0000) >> 16) / 255.0,
green: CGFloat((rgb & 0x00ff00) >> 8) / 255.0,
blue: CGFloat(rgb & 0x0000ff) / 255.0,
alpha: CGFloat(alpha))
}
convenience init(rgbString: String) {
var r: UInt32 = 0
var g: UInt32 = 0
var b: UInt32 = 0
let str = rgbString.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).uppercaseString
var start = -1
if str.hasPrefix("#") && str.characters.count == 7 {
start = 1
} else if str.hasPrefix("0X") && str.characters.count == 9 {
start = 2
}
if (start >= 0) {
let rStr = str[start..<start+2]
let gStr = str[start+2..<start+4]
let bStr = str[start+4..<start+6]
NSScanner(string: rStr).scanHexInt(&r)
NSScanner(string: gStr).scanHexInt(&g)
NSScanner(string: bStr).scanHexInt(&b)
}
self.init(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0,
blue: CGFloat(b) / 255.0, alpha: CGFloat(1))
}
}
extension String {
subscript (r: Range<Int>) -> String {
get {
let startIndex = self.startIndex.advancedBy(r.startIndex)
let endIndex = startIndex.advancedBy(r.endIndex - r.startIndex)
return self[Range(start: startIndex, end: endIndex)]
}
}
var floatValue: Float {
return (self as NSString).floatValue
}
var integerValue: Int {
return (self as NSString).integerValue
}
var sha1: String {
let data = self.dataUsingEncoding(NSUTF8StringEncoding)!
var digest = [UInt8](count:Int(CC_SHA1_DIGEST_LENGTH), repeatedValue: 0)
CC_SHA1(data.bytes, CC_LONG(data.length), &digest)
let hexBytes = digest.map { String(format: "%02hhx", $0) }
return hexBytes.joinWithSeparator("")
}
} | 46503a80940ed5879e2f5dfac20f6427 | 36.903553 | 158 | 0.600991 | false | false | false | false |
BrisyIOS/CustomAlbum | refs/heads/master | CustomAlbum/CustomAlbum/ModalAnimationDelegate.swift | apache-2.0 | 1 | //
// ModalAnimationDelegate.swift
// 仿微信照片弹出动画
//
// Created by zhangxu on 2016/12/21.
// Copyright © 2016年 zhangxu. All rights reserved.
//
import UIKit
class ModalAnimationDelegate: NSObject, UIViewControllerTransitioningDelegate, UIViewControllerAnimatedTransitioning {
// ⚠️ 一定要写成单粒,不然,下面的方法不会执行
static let shared: ModalAnimationDelegate = ModalAnimationDelegate();
private var isPresentAnimationing: Bool = true;
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
isPresentAnimationing = true;
return self;
}
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
isPresentAnimationing = false;
return self;
}
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.5;
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
if isPresentAnimationing {
presentViewAnimation(transitionContext: transitionContext);
} else {
dismissViewAnimation(transitionContext: transitionContext);
}
}
// 弹出动画
func presentViewAnimation(transitionContext: UIViewControllerContextTransitioning) {
// 过渡view
guard let toView = transitionContext.view(forKey: UITransitionContextViewKey.to) else {
return;
}
// 容器view
let containerView = transitionContext.containerView;
// 过渡view添加到容器view上
containerView.addSubview(toView);
// 目标控制器
guard let toVc = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to) as? PhotoDetailController else {
return;
}
// indexPath
guard let indexPath = toVc.indexPath else {
return;
}
// 当前跳转的控制器
guard let fromVc = ((transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from) as? UINavigationController)?.topViewController) as? PhotoListController else {
return;
};
// 获取collectionView
let collectionView = fromVc.collectionView;
// 获取当前选中的cell
guard let selectedCell = collectionView.cellForItem(at: indexPath) as? PhotoCell else {
return;
}
// 新建一个imageview添加到目标view之上,做为动画view
let imageView = UIImageView();
imageView.image = selectedCell.image;
imageView.contentMode = .scaleAspectFit;
imageView.clipsToBounds = true;
// 获取window
guard let window = UIApplication.shared.keyWindow else {
return;
}
// 被选中的cell到目标view上的座标转换
let originFrame = collectionView.convert(selectedCell.frame, to: window);
imageView.frame = originFrame;
// 将imageView 添加到容器视图上
containerView.addSubview(imageView);
let endFrame = window.bounds;
toView.alpha = 0;
UIView.animate(withDuration: 0.5, animations: {
_ in
imageView.frame = endFrame;
}, completion: {
_ in
transitionContext.completeTransition(true);
UIView.animate(withDuration: 0.2, animations: {
_ in
toView.alpha = 1;
}, completion: {
_ in
imageView.removeFromSuperview();
});
})
}
// 消失动画
func dismissViewAnimation(transitionContext: UIViewControllerContextTransitioning) {
let transitionView = transitionContext.view(forKey: UITransitionContextViewKey.from);
let contentView = transitionContext.containerView;
// 取出modal出的来控制器
guard let fromVc = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from) as? PhotoDetailController else {
return;
}
// 取出当前显示的collectionview
let collectionView = fromVc.collectionView;
// 取出控制器当前显示的cell
guard let dismissCell = collectionView.visibleCells.first as? PhotoDetailCell else {
return;
}
// 新建过渡动画imageview
let imageView = UIImageView();
imageView.contentMode = .scaleAspectFit;
imageView.clipsToBounds = true;
// 获取当前显示的cell 的image
imageView.image = dismissCell.icon.image;
// 获取当前显示cell在window中的frame
imageView.frame = dismissCell.icon.frame;
contentView.addSubview(imageView);
// 动画最后停止的frame
guard let indexPath = collectionView.indexPath(for: dismissCell) else {
return;
}
// 取出要返回的控制器
guard let toVC = ((transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to) as? UINavigationController)?.topViewController) as? PhotoListController else {
return;
}
let originView = toVC.collectionView;
guard let originCell = originView.cellForItem(at: indexPath) as? PhotoCell else {
originView.scrollToItem(at: indexPath, at: .centeredVertically, animated: false)
return;
}
guard let window = UIApplication.shared.keyWindow else {
return;
}
let originFrame = originView.convert(originCell.frame, to: window);
// 执行动画
UIView.animate(withDuration: 0.5, animations: {
_ in
imageView.frame = originFrame;
transitionView?.alpha = 0;
}, completion: {
_ in
imageView.removeFromSuperview();
transitionContext.completeTransition(true);
})
}
}
| 3928991cf6afadcda7c3eb09410226d4 | 33.404624 | 191 | 0.624832 | false | false | false | false |
MiniDOM/MiniDOM | refs/heads/master | Sources/MiniDOM/Search.swift | mit | 1 | //
// Search.swift
// MiniDOM
//
// Copyright 2017-2020 Anodized Software, Inc.
//
// 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
class ElementSearch: Visitor {
private(set) var elements: [Element] = []
let predicate: (Element) -> Bool
init(predicate: @escaping (Element) -> Bool) {
self.predicate = predicate
}
func beginVisit(_ element: Element) {
if predicate(element) {
elements.append(element)
}
}
}
public extension Document {
/**
Traverses the document tree, collecting `Element` nodes with the specified
tag name from anywhere in the document.
- parameter name: Collect elements with this tag name.
- returns: An array of elements with the specified tag name.
*/
final func elements(withTagName name: String) -> [Element] {
return elements(where: { $0.tagName == name })
}
/**
Traverses the document tree, collecting `Element` nodes that satisfy the
given predicate from anywhere in the document.
- parameter predicate: A closure that takes an element as its argument and
returns a Boolean value indicating whether the element should be included
in the returned array.
- returns: An array of the elements that `predicate` allowed.
*/
final func elements(where predicate: @escaping (Element) -> Bool) -> [Element] {
let visitor = ElementSearch(predicate: predicate)
documentElement?.accept(visitor)
return visitor.elements
}
}
| 2ad3eb960984a516b5c937d909bfa85d | 34.902778 | 84 | 0.700193 | false | false | false | false |
daggmano/photo-management-studio | refs/heads/develop | src/Client/OSX/PMS-2/Photo Management Studio/Photo Management Studio/MediaObject.swift | mit | 1 | //
// MediaObject.swift
// Photo Management Studio
//
// Created by Darren Oster on 6/04/2016.
// Copyright © 2016 Criterion Software. All rights reserved.
//
import Cocoa
class MediaObject: NSObject, JsonProtocol {
internal private(set) var mediaId: String?
internal private(set) var mediaRev: String?
internal private(set) var importId: String?
internal private(set) var uniqueId: String?
internal private(set) var fullFilePath: String?
internal private(set) var fileName: String?
internal private(set) var shotDate: String?
internal private(set) var rating: Int?
internal private(set) var dateAccuracy: Int?
internal private(set) var caption: String?
internal private(set) var rotate: Int?
internal private(set) var metadata: [MetadataObject]?
internal private(set) var tagIds: [String]?
init(mediaId: String, mediaRev: String, importId: String, uniqueId: String, fullFilePath: String, fileName: String, shotDate: String, rating: Int, dateAccuracy: Int, caption: String, rotate: Int, metadata: [MetadataObject], tagIds: [String]) {
self.mediaId = mediaId
self.mediaRev = mediaRev
self.importId = importId
self.uniqueId = uniqueId
self.fullFilePath = fullFilePath
self.fileName = fileName
self.shotDate = shotDate
self.rating = rating
self.dateAccuracy = dateAccuracy
self.caption = caption
self.rotate = rotate
self.metadata = metadata
self.tagIds = tagIds
}
required init(json: [String: AnyObject]) {
self.mediaId = json["_id"] as? String
self.mediaRev = json["_rev"] as? String
self.importId = json["importId"] as? String
self.uniqueId = json["uniqueId"] as? String
self.fullFilePath = json["fullFilePath"] as? String
self.fileName = json["fileName"] as? String
self.shotDate = json["shotDate"] as? String
self.rating = json["rating"] as? Int
self.dateAccuracy = json["dateAccuracy"] as? Int
self.caption = json["caption"] as? String
self.rotate = json["rotate"] as? Int
if let metadata = json["metadata"] as? [[String: AnyObject]] {
self.metadata = [MetadataObject]()
for item in metadata {
self.metadata!.append(MetadataObject(json: item))
}
}
self.tagIds = json["tagIds"] as? [String]
}
func toJSON() -> [String: AnyObject] {
var result = [String: AnyObject]()
if let mediaId = self.mediaId {
result["_id"] = mediaId
}
if let mediaRev = self.mediaRev {
result["_rev"] = mediaRev
}
if let importId = self.importId {
result["importId"] = importId
}
if let uniqueId = self.uniqueId {
result["uniqueId"] = uniqueId
}
if let fullFilePath = self.fullFilePath {
result["fullFilePath"] = fullFilePath
}
if let fileName = self.fileName {
result["fileName"] = fileName
}
if let shotDate = self.shotDate {
result["shotDate"] = shotDate
}
if let rating = self.rating {
result["rating"] = rating
}
if let dateAccuracy = self.dateAccuracy {
result["dateAccuracy"] = dateAccuracy
}
if let caption = self.caption {
result["caption"] = caption
}
if let rotate = self.rotate {
result["rotate"] = rotate
}
if let metadata = self.metadata {
var array = [[String: AnyObject]]()
for item in metadata {
array.append(item.toJSON())
}
result["metadata"] = array
}
if let tagIds = self.tagIds {
result["tagIds"] = tagIds
}
return result
}
}
class MetadataObject: NSObject, JsonProtocol {
internal private(set) var group: String?
internal private(set) var name: String?
internal private(set) var value: String?
init(group: String, name: String, value: String) {
self.group = group
self.name = name
self.value = value
}
required init(json: [String: AnyObject]) {
self.group = json["group"] as? String
self.name = json["name"] as? String
self.value = json["value"] as? String
}
func toJSON() -> [String: AnyObject] {
var result = [String: AnyObject]()
if let group = self.group {
result["group"] = group
}
if let name = self.name {
result["name"] = name
}
if let value = self.value {
result["value"] = value
}
return result
}
}
| 83d55d70eb81da58cb029fe9e8e13cff | 31.986395 | 247 | 0.573108 | false | false | false | false |
manavgabhawala/swift | refs/heads/master | test/IRGen/objc_ns_enum.swift | apache-2.0 | 1 | // RUN: rm -rf %t && mkdir -p %t
// RUN: %build-irgen-test-overlays
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -Xllvm -new-mangling-for-tests -primary-file %s -emit-ir | %FileCheck %s
// REQUIRES: CPU=x86_64
// REQUIRES: objc_interop
import Foundation
import gizmo
// CHECK: @_T0SC16NSRuncingOptionsOWV = linkonce_odr hidden constant
// CHECK: @_T0SC16NSRuncingOptionsOMn = linkonce_odr hidden constant
// CHECK: @_T0SC16NSRuncingOptionsON = linkonce_odr hidden global
// CHECK: @_T0SC28NeverActuallyMentionedByNameOs9Equatable5gizmoWP = linkonce_odr hidden constant
// CHECK-LABEL: define{{( protected)?}} i32 @main
// CHECK: call %swift.type* @_T0SC16NSRuncingOptionsOMa()
// CHECK: define hidden swiftcc i16 @_T012objc_ns_enum09imported_C9_inject_aSC16NSRuncingOptionsOyF()
// CHECK: ret i16 123
func imported_enum_inject_a() -> NSRuncingOptions {
return .mince
}
// CHECK: define hidden swiftcc i16 @_T012objc_ns_enum09imported_C9_inject_bSC16NSRuncingOptionsOyF()
// CHECK: ret i16 4567
func imported_enum_inject_b() -> NSRuncingOptions {
return .quinceSliced
}
// CHECK: define hidden swiftcc i16 @_T012objc_ns_enum09imported_C9_inject_cSC16NSRuncingOptionsOyF()
// CHECK: ret i16 5678
func imported_enum_inject_c() -> NSRuncingOptions {
return .quinceJulienned
}
// CHECK: define hidden swiftcc i16 @_T012objc_ns_enum09imported_C9_inject_dSC16NSRuncingOptionsOyF()
// CHECK: ret i16 6789
func imported_enum_inject_d() -> NSRuncingOptions {
return .quinceDiced
}
// CHECK: define hidden swiftcc i32 @_T012objc_ns_enum09imported_C17_inject_radixed_aSC16NSRadixedOptionsOyF() {{.*}} {
// -- octal 0755
// CHECK: ret i32 493
func imported_enum_inject_radixed_a() -> NSRadixedOptions {
return .octal
}
// CHECK: define hidden swiftcc i32 @_T012objc_ns_enum09imported_C17_inject_radixed_bSC16NSRadixedOptionsOyF() {{.*}} {
// -- hex 0xFFFF
// CHECK: ret i32 65535
func imported_enum_inject_radixed_b() -> NSRadixedOptions {
return .hex
}
// CHECK: define hidden swiftcc i32 @_T012objc_ns_enum09imported_C18_inject_negative_aSC17NSNegativeOptionsOyF() {{.*}} {
// CHECK: ret i32 -1
func imported_enum_inject_negative_a() -> NSNegativeOptions {
return .foo
}
// CHECK: define hidden swiftcc i32 @_T012objc_ns_enum09imported_C18_inject_negative_bSC17NSNegativeOptionsOyF() {{.*}} {
// CHECK: ret i32 -2147483648
func imported_enum_inject_negative_b() -> NSNegativeOptions {
return .bar
}
// CHECK: define hidden swiftcc i32 @_T012objc_ns_enum09imported_C27_inject_negative_unsigned_aSC25NSNegativeUnsignedOptionsOyF() {{.*}} {
// CHECK: ret i32 -1
func imported_enum_inject_negative_unsigned_a() -> NSNegativeUnsignedOptions {
return .foo
}
// CHECK: define hidden swiftcc i32 @_T012objc_ns_enum09imported_C27_inject_negative_unsigned_bSC25NSNegativeUnsignedOptionsOyF() {{.*}} {
// CHECK: ret i32 -2147483648
func imported_enum_inject_negative_unsigned_b() -> NSNegativeUnsignedOptions {
return .bar
}
func test_enum_without_name_Equatable(_ obj: TestThatEnumType) -> Bool {
return obj.getValue() != .ValueOfThatEnumType
}
func use_metadata<T>(_ t:T){}
use_metadata(NSRuncingOptions.mince)
// CHECK-LABEL: define linkonce_odr hidden %swift.type* @_T0SC16NSRuncingOptionsOMa()
// CHECK: call %swift.type* @swift_getForeignTypeMetadata({{.*}} @_T0SC16NSRuncingOptionsON {{.*}}) [[NOUNWIND_READNONE:#[0-9]+]]
@objc enum ExportedToObjC: Int {
case Foo = -1, Bar, Bas
}
// CHECK-LABEL: define hidden swiftcc i64 @_T012objc_ns_enum0a1_C7_injectAA14ExportedToObjCOyF()
// CHECK: ret i64 -1
func objc_enum_inject() -> ExportedToObjC {
return .Foo
}
// CHECK-LABEL: define hidden swiftcc i64 @_T012objc_ns_enum0a1_C7_switchSiAA14ExportedToObjCOF(i64)
// CHECK: switch i64 %0, label {{%.*}} [
// CHECK: i64 -1, label {{%.*}}
// CHECK: i64 0, label {{%.*}}
// CHECK: i64 1, label {{%.*}}
func objc_enum_switch(_ x: ExportedToObjC) -> Int {
switch x {
case .Foo:
return 0
case .Bar:
return 1
case .Bas:
return 2
}
}
@objc class ObjCEnumMethods : NSObject {
// CHECK: define internal void @_T012objc_ns_enum15ObjCEnumMethodsC0C2InyAA010ExportedToD1COFTo([[OBJC_ENUM_METHODS:.*]]*, i8*, i64)
dynamic func enumIn(_ x: ExportedToObjC) {}
// CHECK: define internal i64 @_T012objc_ns_enum15ObjCEnumMethodsC0C3OutAA010ExportedToD1COyFTo([[OBJC_ENUM_METHODS]]*, i8*)
dynamic func enumOut() -> ExportedToObjC { return .Foo }
// CHECK: define internal i64 @_T012objc_ns_enum15ObjCEnumMethodsC4propAA010ExportedToD1COfgTo([[OBJC_ENUM_METHODS]]*, i8*)
// CHECK: define internal void @_T012objc_ns_enum15ObjCEnumMethodsC4propAA010ExportedToD1COfsTo([[OBJC_ENUM_METHODS]]*, i8*, i64)
dynamic var prop: ExportedToObjC = .Foo
}
// CHECK-LABEL: define hidden swiftcc void @_T012objc_ns_enum0a1_C13_method_callsyAA15ObjCEnumMethodsCF(%T12objc_ns_enum15ObjCEnumMethodsC*)
func objc_enum_method_calls(_ x: ObjCEnumMethods) {
// CHECK: call i64 bitcast (void ()* @objc_msgSend to i64 ([[OBJC_ENUM_METHODS]]*, i8*)*)
// CHECK: call void bitcast (void ()* @objc_msgSend to void ([[OBJC_ENUM_METHODS]]*, i8*, i64)*)
x.enumIn(x.enumOut())
// CHECK: call i64 bitcast (void ()* @objc_msgSend to i64 ([[OBJC_ENUM_METHODS]]*, i8*)*)
// CHECK: call void bitcast (void ()* @objc_msgSend to void ([[OBJC_ENUM_METHODS]]*, i8*, i64)*)
x.enumIn(x.prop)
// CHECK: call i64 bitcast (void ()* @objc_msgSend to i64 ([[OBJC_ENUM_METHODS]]*, i8*)*)
// CHECK: call void bitcast (void ()* @objc_msgSend to void ([[OBJC_ENUM_METHODS]]*, i8*, i64)*)
x.prop = x.enumOut()
}
// CHECK: attributes [[NOUNWIND_READNONE]] = { nounwind readnone }
| 9b0d3367d4ed688f0f6ecb045dfa55d5 | 38.818182 | 140 | 0.707938 | false | false | false | false |
JadenGeller/CS-81-Project | refs/heads/master | Sources/DecimalDigit.swift | mit | 1 | //
// DecimalDigit.swift
// Language
//
// Created by Jaden Geller on 2/22/16.
// Copyright © 2016 Jaden Geller. All rights reserved.
//
public enum DecimalDigit: Int, Equatable {
case Zero
case One
case Two
case Three
case Four
case Five
case Six
case Seven
case Eight
case Nine
}
extension DecimalDigit: IntegerLiteralConvertible {
public init(integerLiteral value: Int) {
guard let this = DecimalDigit(rawValue: value) else {
fatalError("Decimal digit must be between 0 and 9")
}
self = this
}
}
public func ==(lhs: DecimalDigit, rhs: DecimalDigit) -> Bool {
return lhs.rawValue == rhs.rawValue
}
| 18073f4c37038e27b3ddcdf0304220be | 20.060606 | 63 | 0.641727 | false | false | false | false |
cam-hop/APIUtility | refs/heads/master | RxSwiftFluxDemo/Carthage/Checkouts/Kingfisher/Tests/KingfisherTests/KingfisherManagerTests.swift | mit | 2 | //
// KingfisherManagerTests.swift
// Kingfisher
//
// Created by Wei Wang on 15/10/22.
//
// Copyright (c) 2017 Wei Wang <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import XCTest
@testable import Kingfisher
class KingfisherManagerTests: XCTestCase {
var manager: KingfisherManager!
override class func setUp() {
super.setUp()
LSNocilla.sharedInstance().start()
}
override class func tearDown() {
super.tearDown()
LSNocilla.sharedInstance().stop()
}
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
manager = KingfisherManager()
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
LSNocilla.sharedInstance().clearStubs()
cleanDefaultCache()
manager = nil
super.tearDown()
}
func testRetrieveImage() {
let expectation = self.expectation(description: "wait for downloading image")
let URLString = testKeys[0]
_ = stubRequest("GET", URLString).andReturn(200)?.withBody(testImageData)
let url = URL(string: URLString)!
manager.retrieveImage(with: url, options: nil, progressBlock: nil) {
image, error, cacheType, imageURL in
XCTAssertNotNil(image)
XCTAssertEqual(cacheType, .none)
self.manager.retrieveImage(with: url, options: nil, progressBlock: nil) {
image, error, cacheType, imageURL in
XCTAssertNotNil(image)
XCTAssertEqual(cacheType, .memory)
self.manager.cache.clearMemoryCache()
self.manager.retrieveImage(with: url, options: nil, progressBlock: nil) {
image, error, cacheType, imageURL in
XCTAssertNotNil(image)
XCTAssertEqual(cacheType, .disk)
cleanDefaultCache()
self.manager.retrieveImage(with: url, options: [.forceRefresh], progressBlock: nil) {
image, error, cacheType, imageURL in
XCTAssertNotNil(image)
XCTAssertEqual(cacheType, CacheType.none)
expectation.fulfill()
}
}
}
}
waitForExpectations(timeout: 5, handler: nil)
}
func testRetrieveImageWithProcessor() {
cleanDefaultCache()
let expectation = self.expectation(description: "wait for downloading image")
let URLString = testKeys[0]
_ = stubRequest("GET", URLString).andReturn(200)?.withBody(testImageData)
let url = URL(string: URLString)!
let p = RoundCornerImageProcessor(cornerRadius: 20)
manager.retrieveImage(with: url, options: [.processor(p)], progressBlock: nil) {
image, error, cacheType, imageURL in
XCTAssertNotNil(image)
XCTAssertEqual(cacheType, .none)
self.manager.retrieveImage(with: url, options: nil, progressBlock: nil) {
image, error, cacheType, imageURL in
XCTAssertNotNil(image)
XCTAssertEqual(cacheType, .none, "Need a processor to get correct image. Cannot get from cache, need download again.")
self.manager.retrieveImage(with: url, options: [.processor(p)], progressBlock: nil) {
image, error, cacheType, imageURL in
XCTAssertNotNil(image)
XCTAssertEqual(cacheType, .memory)
self.manager.cache.clearMemoryCache()
self.manager.retrieveImage(with: url, options: [.processor(p)], progressBlock: nil) {
image, error, cacheType, imageURL in
XCTAssertNotNil(image)
XCTAssertEqual(cacheType, .disk)
cleanDefaultCache()
self.manager.retrieveImage(with: url, options: [.processor(p), .forceRefresh], progressBlock: nil) {
image, error, cacheType, imageURL in
XCTAssertNotNil(image)
XCTAssertEqual(cacheType, CacheType.none)
expectation.fulfill()
}
}
}
}
}
waitForExpectations(timeout: 5, handler: nil)
}
func testRetrieveImageNotModified() {
let expectation = self.expectation(description: "wait for downloading image")
let URLString = testKeys[0]
_ = stubRequest("GET", URLString).andReturn(200)?.withBody(testImageData)
let url = URL(string: URLString)!
manager.retrieveImage(with: url, options: nil, progressBlock: nil) {
image, error, cacheType, imageURL in
XCTAssertNotNil(image)
XCTAssertEqual(cacheType, CacheType.none)
self.manager.cache.clearMemoryCache()
_ = stubRequest("GET", URLString).andReturn(304)?.withBody("12345" as NSString)
var progressCalled = false
self.manager.retrieveImage(with: url, options: [.forceRefresh], progressBlock: {
_, _ in
progressCalled = true
}) {
image, error, cacheType, imageURL in
XCTAssertNotNil(image)
XCTAssertEqual(cacheType, CacheType.disk)
XCTAssertTrue(progressCalled, "The progress callback should be called at least once since network connecting happens.")
expectation.fulfill()
}
}
waitForExpectations(timeout: 5, handler: nil)
}
func testSuccessCompletionHandlerRunningOnMainQueueDefaultly() {
let progressExpectation = expectation(description: "progressBlock running on main queue")
let completionExpectation = expectation(description: "completionHandler running on main queue")
let URLString = testKeys[0]
_ = stubRequest("GET", URLString).andReturn(200)?.withBody(testImageData)
let url = URL(string: URLString)!
manager.retrieveImage(with: url, options: nil, progressBlock: { _, _ in
XCTAssertTrue(Thread.isMainThread)
progressExpectation.fulfill()
}, completionHandler: { _, error, _, _ in
XCTAssertNil(error)
XCTAssertTrue(Thread.isMainThread)
completionExpectation.fulfill()
})
waitForExpectations(timeout: 5, handler: nil)
}
func testShouldNotDownloadImageIfCacheOnlyAndNotInCache() {
cleanDefaultCache()
let expectation = self.expectation(description: "wait for retrieving image cache")
let URLString = testKeys[0]
_ = stubRequest("GET", URLString).andReturn(200)?.withBody(testImageData)
let url = URL(string: URLString)!
manager.retrieveImage(with: url, options: [.onlyFromCache], progressBlock: nil, completionHandler: { image, error, _, _ in
XCTAssertNil(image)
XCTAssertNotNil(error)
XCTAssertEqual(error!.code, KingfisherError.notCached.rawValue)
expectation.fulfill()
})
waitForExpectations(timeout: 5, handler: nil)
}
func testErrorCompletionHandlerRunningOnMainQueueDefaultly() {
let expectation = self.expectation(description: "running on main queue")
let URLString = testKeys[0]
_ = stubRequest("GET", URLString).andReturn(404)
let url = URL(string: URLString)!
manager.retrieveImage(with: url, options: nil, progressBlock: { _, _ in
//won't be called
}, completionHandler: { _, error, _, _ in
XCTAssertNotNil(error)
XCTAssertTrue(Thread.isMainThread)
expectation.fulfill()
})
waitForExpectations(timeout: 5, handler: nil)
}
func testSucessCompletionHandlerRunningOnCustomQueue() {
let progressExpectation = expectation(description: "progressBlock running on custom queue")
let completionExpectation = expectation(description: "completionHandler running on custom queue")
let URLString = testKeys[0]
_ = stubRequest("GET", URLString).andReturn(200)?.withBody(testImageData)
let url = URL(string: URLString)!
let customQueue = DispatchQueue(label: "com.kingfisher.testQueue")
manager.retrieveImage(with: url, options: [.callbackDispatchQueue(customQueue)], progressBlock: { _, _ in
XCTAssertTrue(Thread.isMainThread)
progressExpectation.fulfill()
}, completionHandler: { _, error, _, _ in
XCTAssertNil(error)
if #available(iOS 10.0, tvOS 10.0, macOS 10.12, *) {
dispatchPrecondition(condition: .onQueue(customQueue))
}
completionExpectation.fulfill()
})
waitForExpectations(timeout: 5, handler: nil)
}
func testErrorCompletionHandlerRunningOnCustomQueue() {
let expectation = self.expectation(description: "running on custom queue")
let URLString = testKeys[0]
_ = stubRequest("GET", URLString).andReturn(404)
let url = URL(string: URLString)!
let customQueue = DispatchQueue(label: "com.kingfisher.testQueue")
manager.retrieveImage(with: url, options: [.callbackDispatchQueue(customQueue)], progressBlock: { _, _ in
//won't be called
}, completionHandler: { _, error, _, _ in
XCTAssertNotNil(error)
if #available(iOS 10.0, tvOS 10.0, macOS 10.12, *) {
dispatchPrecondition(condition: .onQueue(customQueue))
}
expectation.fulfill()
})
waitForExpectations(timeout: 5, handler: nil)
}
func testDefaultOptionCouldApply() {
let expectation = self.expectation(description: "running on custom queue")
let URLString = testKeys[0]
_ = stubRequest("GET", URLString).andReturn(200)?.withBody(testImageData)
let url = URL(string: URLString)!
manager.defaultOptions = [.scaleFactor(2)]
manager.retrieveImage(with: url, options: nil, progressBlock: nil, completionHandler: { image, _, _, _ in
#if !os(macOS)
XCTAssertEqual(image!.scale, 2.0)
#endif
expectation.fulfill()
})
waitForExpectations(timeout: 5, handler: nil)
}
func testOriginalImageCouldBeStored() {
let expectation = self.expectation(description: "waiting for cache finished")
delay(0.1) {
let URLString = testKeys[0]
_ = stubRequest("GET", URLString).andReturn(200)?.withBody(testImageData)
let url = URL(string: URLString)!
let p = SimpleProcessor()
let options: KingfisherOptionsInfo = [.processor(p), .cacheOriginalImage]
self.manager.downloadAndCacheImage(with: url, forKey: URLString, retrieveImageTask: RetrieveImageTask(), progressBlock: nil, completionHandler: {
(image, error, cacheType, url) in
delay(0.1) {
var imageCached = self.manager.cache.isImageCached(forKey: URLString, processorIdentifier: p.identifier)
var originalCached = self.manager.cache.isImageCached(forKey: URLString)
XCTAssertEqual(imageCached.cacheType, .memory)
XCTAssertEqual(originalCached.cacheType, .memory)
self.manager.cache.clearMemoryCache()
imageCached = self.manager.cache.isImageCached(forKey: URLString, processorIdentifier: p.identifier)
originalCached = self.manager.cache.isImageCached(forKey: URLString)
XCTAssertEqual(imageCached.cacheType, .disk)
XCTAssertEqual(originalCached.cacheType, .disk)
expectation.fulfill()
}
}, options: options)
}
self.waitForExpectations(timeout: 5, handler: nil)
}
func testOriginalImageNotBeStoredWithoutOptionSet() {
let expectation = self.expectation(description: "waiting for cache finished")
let URLString = testKeys[0]
_ = stubRequest("GET", URLString).andReturn(200)?.withBody(testImageData)
let url = URL(string: URLString)!
let p = SimpleProcessor()
let options: KingfisherOptionsInfo = [.processor(p)]
manager.downloadAndCacheImage(with: url, forKey: URLString, retrieveImageTask: RetrieveImageTask(), progressBlock: nil, completionHandler: {
(image, error, cacheType, url) in
delay(0.1) {
var imageCached = self.manager.cache.isImageCached(forKey: URLString, processorIdentifier: p.identifier)
var originalCached = self.manager.cache.isImageCached(forKey: URLString)
XCTAssertEqual(imageCached.cacheType, .memory)
XCTAssertEqual(originalCached.cacheType, .none)
self.manager.cache.clearMemoryCache()
imageCached = self.manager.cache.isImageCached(forKey: URLString, processorIdentifier: p.identifier)
originalCached = self.manager.cache.isImageCached(forKey: URLString)
XCTAssertEqual(imageCached.cacheType, .disk)
XCTAssertEqual(originalCached.cacheType, .none)
expectation.fulfill()
}
}, options: options)
waitForExpectations(timeout: 5, handler: nil)
}
func testCouldProcessOnOriginalImage() {
let expectation = self.expectation(description: "waiting for downloading finished")
let URLString = testKeys[0]
manager.cache.store(testImage, original: testImageData! as Data,
forKey: URLString, processorIdentifier: DefaultImageProcessor.default.identifier,
cacheSerializer: DefaultCacheSerializer.default, toDisk: true)
{
let p = SimpleProcessor()
let cached = self.manager.cache.isImageCached(forKey: URLString, processorIdentifier: p.identifier)
XCTAssertFalse(cached.cached)
// No downloading will happen
self.manager.retrieveImage(with: URL(string: URLString)!, options: [.processor(p)], progressBlock: nil) {
image, error, cacheType, url in
XCTAssertNotNil(image)
XCTAssertEqual(cacheType, .none)
XCTAssertTrue(p.processed)
// The processed image should be cached
delay(0.1) {
let cached = self.manager.cache.isImageCached(forKey: URLString, processorIdentifier: p.identifier)
XCTAssertTrue(cached.cached)
expectation.fulfill()
}
}
}
waitForExpectations(timeout: 5, handler: nil)
}
}
class SimpleProcessor: ImageProcessor {
public let identifier = "id"
var processed = false
/// Initialize a `DefaultImageProcessor`
public init() {}
/// Process an input `ImageProcessItem` item to an image for this processor.
///
/// - parameter item: Input item which will be processed by `self`
/// - parameter options: Options when processing the item.
///
/// - returns: The processed image.
///
/// - Note: See documentation of `ImageProcessor` protocol for more.
public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
processed = true
switch item {
case .image(let image):
return image
case .data(let data):
return Kingfisher<Image>.image(
data: data,
scale: options.scaleFactor,
preloadAllAnimationData: options.preloadAllAnimationData,
onlyFirstFrame: options.onlyLoadFirstFrame)
}
}
}
| 931aff75448e8aa030b1f3a7c5e8df2d | 41.855107 | 157 | 0.590345 | false | true | false | false |
hpsoar/Knife | refs/heads/master | Knife/ViewController.swift | mit | 1 | //
// ViewController.swift
// Knife
//
// Created by HuangPeng on 8/23/14.
// Copyright (c) 2014 Beacon. All rights reserved.
//
import UIKit
class DateView: UIView {
var solarDateView: UIView!
var lunarDateView: UIView!
var weekLabel: UILabel!
var yearLabel: UILabel!
var dateLabel: UILabel!
var lunarDateLabel: UILabel!
init(frame: CGRect) {
super.init(frame: frame)
self.setup()
}
func weekString(week: NSInteger) -> String {
let weekString = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"]
return weekString[week - 1]
}
func setup() {
let date = NSDate()
/*
* ---------------------------
* solar date: week
* ---- month / day
* year
* ---------------------------
* lunar date: month day
* ---------------------------
*/
solarDateView = UIView(frame: CGRectMake(0, 0, 110, 44))
solarDateView.backgroundColor = UIColor(red: 1, green: 0, blue: 0, alpha: 0.6)
self.addSubview(solarDateView)
weekLabel = UILabel(frame: CGRectMake(4, 3, 30, solarDateView.frame.height / 2))
weekLabel.font = UIFont.systemFontOfSize(12)
weekLabel.textColor = UIColor.whiteColor()
yearLabel = UILabel(frame: CGRectMake(4, weekLabel.frame.height - 3, 30, solarDateView.frame.height / 2))
yearLabel.font = UIFont.systemFontOfSize(12)
yearLabel.textColor = UIColor.whiteColor()
weekLabel.text = self.weekString(date.week)
yearLabel.text = String(date.year)
solarDateView.addSubview(weekLabel)
solarDateView.addSubview(yearLabel)
dateLabel = UILabel(frame: CGRectMake(40, 0, solarDateView.frame.width - weekLabel.frame.width, solarDateView.frame.height))
dateLabel.font = UIFont.systemFontOfSize(28)
dateLabel.text = String(date.month) + "/" + String(date.day)
dateLabel.textColor = UIColor.whiteColor()
solarDateView.addSubview(dateLabel)
lunarDateView = UIView(frame: CGRectMake(0, solarDateView.frame.origin.y + solarDateView.frame.height, 110, 22))
lunarDateView.backgroundColor = UIColor(white: 0.3, alpha: 0.6)
self.addSubview(lunarDateView)
var lunarDate = LunarDate(date: date)
lunarDateLabel = UILabel(frame: CGRectMake(4, 0, lunarDateView.frame.width, lunarDateView.frame.height))
lunarDateLabel.text = "农历 \(lunarDate.monthString)月\(lunarDate.dayString)"
lunarDateLabel.textColor = UIColor.whiteColor()
lunarDateLabel.font = UIFont.systemFontOfSize(12)
lunarDateView.addSubview(lunarDateLabel)
}
}
class ViewController: UIViewController, WeatherUtilityDelegate {
var backgroundImageView: UIImageView?
var scrollView: UIScrollView?
var dateView: DateView?
var imageNames: NSString[] = NSString[]()
let weatherUtility = YahooWeather()
override func viewDidLoad() {
super.viewDidLoad()
imageNames = [ "nature-wallpaper-beach-wallpapers-delightful-tropical-images_Beaches_wallpapers_196.jpg" ]
var image = UIImage(named: imageNames[0])
image = image.applyBlurWithRadius(40, tintColor:nil, saturationDeltaFactor: 0.85, maskImage: nil, atFrame:CGRectMake(0, 0, image.size.width, image.size.height))
backgroundImageView = UIImageView(image: image)
backgroundImageView!.contentMode = UIViewContentMode.ScaleAspectFill
backgroundImageView!.frame = self.view.bounds
self.view.addSubview(backgroundImageView!)
scrollView = UIScrollView(frame: self.view.bounds)
scrollView!.alwaysBounceVertical = true
self.view.addSubview(scrollView!)
dateView = DateView(frame: CGRectMake(0, 20, 320, 44))
self.view.addSubview(dateView!)
weatherUtility.delegate = self
weatherUtility.updateWeather("Beijing")
weatherUtility.updatePM10("beijing")
weatherUtility.updatePM2_5("beijing")
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
}
func geometricLocationUpdated() {
println("hello")
}
func weatherUpdated() {
}
func pm10Updated() {
}
func pm2_5Updated() {
}
}
| 0fbd6e411270aa68cfef09af636e2edf | 32.029197 | 168 | 0.609945 | false | false | false | false |
huangboju/Moots | refs/heads/master | Examples/Thread/Thread_Swift3.0/Thread_Swift3.0/SecondController.swift | mit | 1 | //
// SecondController.swift
// Thread_Swift3.0
//
// Created by 伯驹 黄 on 2016/10/26.
// Copyright © 2016年 xiAo_Ju. All rights reserved.
//
import UIKit
// https://www.allaboutswift.com/dev/2016/7/12/gcd-with-swfit3
// http://www.cnblogs.com/ludashi/p/5336169.html
// https://justinyan.me/post/2420
// https://bestswifter.com/deep-gcd/
// http://www.cocoachina.com/ios/20170829/20404.html
class SecondController: UIViewController {
fileprivate lazy var tableView: UITableView = {
let tableView = UITableView(frame: self.view.frame, style: .grouped)
tableView.dataSource = self
tableView.delegate = self
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
return tableView
}()
let tags: [[(String, Selector)]] = [
[
("同步执行串行队列", #selector(performSerialQueuesUseSynchronization)),
("同步执行并行队列", #selector(performConcurrentQueuesUseSynchronization))
],
[
("异步执行串行队列", #selector(performSerialQueuesUseAsynchronization)),
("异步执行并行队列", #selector(performConcurrentQueuesUseAsynchronization))
],
[
("延迟执行", #selector(deferPerform))
],
[
("设置全局队列的优先级", #selector(globalQueuePriority)),
("设置自建队列优先级", #selector(setCustomeQueuePriority))
],
[
("自动执行任务组", #selector(autoGlobalQueue)),
("手动执行任务组", #selector(performGroupUseEnterAndleave))
],
[
("使用信号量添加同步锁", #selector(useSemaphoreLock))
],
[
("使用Apply循环执行", #selector(useDispatchApply)),
("暂停和重启队列", #selector(queueSuspendAndResume)),
("使用任务隔离栅栏", #selector(useBarrierAsync))
],
[
("dispatch源,ADD", #selector(useDispatchSourceAdd)),
("dispatch源,OR", #selector(useDispatchSourceOR)),
("dispatch源,定时器", #selector(useDispatchSourceTimer))
],
[
("不同queue opration 依赖", #selector(diffQueue))
]
]
override func viewDidLoad() {
super.viewDidLoad()
title = "Swift5.0 GCD"
view.addSubview(tableView)
}
@objc func performSerialQueuesUseSynchronization() {
let queue = DispatchQueue(label: "syn.serial.queue")
for i in 0..<3 {
queue.sync() {
currentThreadSleep(1)
print("当前执行线程:\(Thread.current)")
print("执行\(i.toEmoji)")
}
print("\(i.toEmoji)执行完毕")
}
print("所有队列使用同步方式执行完毕")
ended()
}
@objc func performConcurrentQueuesUseSynchronization() {
let queue = DispatchQueue(label: "syn.concurrent.queue", attributes: .concurrent)
for i in 0..<3 {
queue.sync() {
currentThreadSleep(1)
print("当前执行线程:\(Thread.current)")
print("执行\(i.toEmoji)")
}
print("\(i.toEmoji)执行完毕")
}
print("所有队列使用同步方式执行完毕")
ended()
}
@objc func performSerialQueuesUseAsynchronization() {
//一个串行队列,用于同步执行
let queue = DispatchQueue(label: "asyn.serial.queue")
let group = DispatchGroup()
let q = DispatchQueue(label: "serialQueue")
for i in 0..<3 {
group.enter()
queue.async(group: group) {
self.currentThreadSleep(Double(arc4random()%3))
let currentThread = Thread.current
q.sync { //同步锁
group.leave()
print("①Sleep的线程\(currentThread)")
print("②当前输出内容的线程\(Thread.current)")
print("③执行\(i.toEmoji):\(queue)\n")
}
}
print("\(i.toEmoji)添加完毕\n")
}
print("使用异步方式添加队列")
group.notify(queue: DispatchQueue.main) {
self.ended()
}
}
@objc func performConcurrentQueuesUseAsynchronization() {
//一个串行队列,用于同步执行
let queue = DispatchQueue(label: "asyn.concurrent.queue", attributes: .concurrent)
let group = DispatchGroup()
let q = DispatchQueue(label: "serialQueue")
for i in 0..<3 {
group.enter()
queue.async(group: group) {
self.currentThreadSleep(Double(arc4random()%3))
let currentThread = Thread.current
print("asyn.concurrent.queue", currentThread)
q.sync { //同步锁
group.leave()
print("①Sleep的线程\(currentThread)")
print("②当前输出内容的线程\(Thread.current)")
print("③执行\(i.toEmoji):\(queue)\n")
}
}
print("\(i.toEmoji)添加完毕\n")
}
print("使用异步方式添加队列")
group.notify(queue: DispatchQueue.main) {
self.ended()
}
}
@objc func diffQueue() {
let queue1 = OperationQueue()
queue1.name = "queue1"
let queue2 = OperationQueue()
queue2.name = "queue2"
let opration1 = BlockOperation {
sleep(2)
print("我是1")
}
queue1.addOperation(opration1)
let opration2 = BlockOperation {
print("我是2")
}
opration2.addDependency(opration1)
queue2.addOperation(opration2)
}
func currentThreadSleep(_ timer: TimeInterval) {
print("😪😪😪延时😪😪😪")
Thread.sleep(forTimeInterval: timer)
}
/// 创建并行队列
func getConcurrentQueue(_ label: String) -> DispatchQueue {
return DispatchQueue(label: label, attributes: .concurrent)
}
/// 延迟执行
@objc func deferPerform(_ time: Int = 1) {
let semaphore = DispatchSemaphore(value: 0)
let queue = globalQueue()
let delaySecond = DispatchTimeInterval.seconds(time)
print(Date())
let delayTime = DispatchTime.now() + delaySecond
queue.asyncAfter(deadline: delayTime) {
print("执行线程:\(Thread.current)\ndispatch_time: 延迟\(time)秒执行\n",Date())
semaphore.signal()
}
//DispatchWallTime用于计算绝对时间,而DispatchWallTime是根据挂钟来计算的时间,即使设备睡眠了,他也不会睡眠。
// let nowInterval = Date().timeIntervalSince1970
// let nowStruct = timespec(tv_sec: Int(nowInterval), tv_nsec: 0)
// let delayWalltime = DispatchWallTime(timespec: nowStruct)
let delayWalltime = DispatchWallTime.now() + delaySecond
queue.asyncAfter(wallDeadline: delayWalltime) {
print("执行线程:\(Thread.current)\ndispatch_walltime: 延迟\(time)秒执行\n", Date())
}
semaphore.wait()
ended()
}
/// 全局队列的优先级关系
@objc func globalQueuePriority() {
//高 > 默认 > 低 > 后台
let queueHeight = globalQueue(qos: .userInitiated)
let queueDefault = globalQueue()
let queueLow = globalQueue(qos: .utility)
let queueBackground = globalQueue(qos: .background)
let group = DispatchGroup()
//优先级不是绝对的,大体上会按这个优先级来执行。 一般都是使用默认(default)优先级
queueLow.async(group: group) {
print("Low:\(Thread.current)")
}
queueBackground.async(group: group) {
print("Background:\(Thread.current)")
}
queueDefault.async(group: group) {
print("Default:\(Thread.current)")
}
queueHeight.async(group: group) {
print("High:\(Thread.current)")
}
group.wait()
ended()
}
/// 给串行队列或者并行队列设置优先级
@objc func setCustomeQueuePriority() {
//优先级的执行顺序也不是绝对的
//给serialQueueHigh设定DISPATCH_QUEUE_PRIORITY_HIGH优先级
let serialQueueHigh = DispatchQueue(label: "cn.zeluli.serial1")
globalQueue(qos: .userInitiated).setTarget(queue: serialQueueHigh)
let serialQueueLow = DispatchQueue(label: "cn.zeluli.serial1")
globalQueue(qos: .utility).setTarget(queue: serialQueueLow)
serialQueueLow.async {
print("低:\(Thread.current)")
}
serialQueueHigh.async {
print("高:\(Thread.current)")
self.ended()
}
}
func performGroupQueue() {
let concurrentQueue = getConcurrentQueue("cn.zeluli")
let group = DispatchGroup()
//将group与queue进行管理,并且自动执行
for i in 1...3 {
concurrentQueue.async(group: group) {
self.currentThreadSleep(1)
print("任务\(i)执行完毕\n")
}
}
//队列组的都执行完毕后会进行通知
group.notify(queue: DispatchQueue.main) {
self.ended()
}
print("异步执行测试,不会阻塞当前线程")
}
@objc func autoGlobalQueue() {
globalQueue().async {
self.performGroupQueue()
}
}
/// 使用enter与leave手动管理group与queue
@objc func performGroupUseEnterAndleave() {
let concurrentQueue = getConcurrentQueue("cn.zeluli")
let group = DispatchGroup()
//将group与queue进行手动关联和管理,并且自动执行
for i in 1...3 {
group.enter() //进入队列组
concurrentQueue.async {
self.currentThreadSleep(1)
print("任务\(i.toEmoji)执行完毕\n")
group.leave() //离开队列组
}
}
_ = group.wait(timeout: .distantFuture) //阻塞当前线程,直到所有任务执行完毕
print("任务组执行完毕")
group.notify(queue: concurrentQueue) {
self.ended()
}
}
//信号量同步锁
@objc func useSemaphoreLock() {
let concurrentQueue = getConcurrentQueue("cn.zeluli")
//创建信号量
let semaphoreLock = DispatchSemaphore(value: 2)
var testNumber = 0
for index in 0 ... 9 {
concurrentQueue.async {
let wait = semaphoreLock.wait(timeout: .distantFuture) //上锁
print("wait=\(wait)")
testNumber += 1
self.currentThreadSleep(1)
print(Thread.current)
print("第\(index.toEmoji)次执行: testNumber = \(testNumber)\n")
semaphoreLock.signal() //开锁
}
}
}
@objc func useBarrierAsync() {
// 那你啥时候改用 barrier 方法,啥时候不该用呢?
//
// * 自定义串行队列 Custom Serial Queue: 没有必要在串行队列中使用,barrier 对于串行队列来说毫无用处,因为本来串行队列就是一次只会执行一个任务的。
// * 全局并发队列 Global Concurrent Queue: 要小心使用。在全局队列中使用 barrier 可能不是太好,因为系统也会使用这个队列,一般你不会希望自己的操作垄断了这个队列从而导致系统调用的延迟。
// * 自定义并发队列 Custom Concurrent Queue: 对于需要原子操作和访问临界区的代码,barrier 方法是最佳使用场景。任何你需要线程安全的实例,barrier 都是一个不错的选择。
let concurrentQueue = getConcurrentQueue("cn.zeluli")
for i in 0...2 {
concurrentQueue.async {
self.currentThreadSleep(Double(i))
print("第一批:\(i.toEmoji)\(Thread.current)")
}
}
for i in 0...3 {
concurrentQueue.async(flags: .barrier) {
self.currentThreadSleep(Double(i))
print("第二批:\(i.toEmoji)\(Thread.current)")
}
}
let workItem = DispatchWorkItem(flags: .barrier) {
print("\n第二批执行完毕后才会执行第三批\n\(Thread.current)\n")
}
concurrentQueue.async(execute: workItem)
for i in 0...3 {
concurrentQueue.async {
self.currentThreadSleep(Double(i))
print("第三批:\(i.toEmoji)\(Thread.current)")
}
}
print("😁😁😁不会阻塞主线程😁😁😁")
}
/// 循环执行
@objc func useDispatchApply() {
print("循环多次执行并行队列")
DispatchQueue.global(qos: .background).async {
DispatchQueue.concurrentPerform(iterations: 3) { index in
self.currentThreadSleep(Double(index))
print("第\(index)次执行,\n\(Thread.current)\n")
}
DispatchQueue.main.async {
self.ended()
}
}
}
//暂停和重启队列
@objc func queueSuspendAndResume() {
let concurrentQueue = getConcurrentQueue("cn.zeluli")
concurrentQueue.suspend() //将队列进行挂起
concurrentQueue.async {
print("任务执行, \(Thread.current)")
}
currentThreadSleep(2)
concurrentQueue.resume() //将挂起的队列进行唤醒
ended()
}
/// 以加法运算的方式合并数据
// http://www.tanhao.me/pieces/360.html/
@objc func useDispatchSourceAdd() {
var sum = 0 //手动计数的sum, 来模拟记录merge的数据
let queue = globalQueue()
//创建source
let dispatchSource = DispatchSource.makeUserDataAddSource(queue: queue)
dispatchSource.setEventHandler() {
print("source中所有的数相加的和等于\(dispatchSource.data)")
print("sum = \(sum)\n")
sum = 0
self.currentThreadSleep(0.3)
}
// DispatchQueue启动时默认状态是挂起的,创建完毕之后得主动恢复,否则事件不会被传送
dispatchSource.resume()
for i in 1...10 {
sum += i
print("i=\(i)")
dispatchSource.add(data: UInt(i))
currentThreadSleep(0.1)
}
ended()
}
/// 以或运算的方式合并数据
@objc func useDispatchSourceOR() {
var or = 0 //手动计数的sum, 来记录merge的数据
let queue = globalQueue()
//创建source
let dispatchSource = DispatchSource.makeUserDataOrSource(queue: queue)
dispatchSource.setEventHandler {
print("source中所有的数相加的和等于\(dispatchSource.data)")
print("or = \(or)\n")
or = 0
self.currentThreadSleep(0.3)
}
dispatchSource.resume()
for i in 1...10 {
or |= i
print("i=\(i)")
dispatchSource.or(data: UInt(i))
currentThreadSleep(0.1)
}
print("\nsum = \(or)")
}
/// 使用DispatchSource创建定时器
@objc func useDispatchSourceTimer() {
let queue = globalQueue()
let source = DispatchSource.makeTimerSource(queue: queue)
// deadline 结束时间
// interval 时间间隔
// leeway 时间精度
// source.schedule(deadline: .now(), leeway: .nanoseconds(0))
source.schedule(deadline: .now(), repeating: 1, leeway: .nanoseconds(0))
// source.scheduleRepeating(deadline: .now(), interval: 1, leeway: .nanoseconds(0))
var timeout = 10 //倒计时时间
//设置要处理的事件, 在我们上面创建的queue队列中进行执行
source.setEventHandler {
print(Thread.current)
if timeout <= 0 {
source.cancel()
} else {
print("\(timeout)s", Date())
timeout -= 1
}
}
//倒计时结束的事件
source.setCancelHandler {
print("倒计时结束")
}
source.resume()
}
func ended() { print("**************************结束**************************\n") }
// http://www.jianshu.com/p/7efbecee6af8
/*
* DISPATCH_QUEUE_PRIORITY_HIGH: .userInitiated
* DISPATCH_QUEUE_PRIORITY_DEFAULT: .default
* DISPATCH_QUEUE_PRIORITY_LOW: .utility
* DISPATCH_QUEUE_PRIORITY_BACKGROUND: .background
*/
// * QOS_CLASS_USER_INTERACTIVE:User Interactive(用户交互)类的任务关乎用户体验,这类任务是需要立刻被执行的。这类任务应该用在更新 UI,处理事件,执行一些需要低延迟的轻量的任务。这种类型的任务应该要压缩到尽可能少。
// * QOS_CLASS_USER_INITIATED: User Initiated(用户发起)类是指由 UI 发起的可以异步执行的任务。当用户在等待任务返回的结果,然后才能执行下一步动作的时候可以使用这种类型。
// * QOS_CLASS_UTILITY:Utility(工具)类是指耗时较长的任务,通常会展示给用户一个进度条。这种类型应该用在大量计算,I/O 操作,网络请求,实时数据推送之类的任务。这个类是带有节能设计的。
// * QOS_CLASS_BACKGROUND:background(后台)类是指用户并不会直接感受到的任务。这个类应该用在数据预拉取,维护以及其他不需要用户交互,对时间不敏感的任务。
func globalQueue(qos: DispatchQoS.QoSClass = .default) -> DispatchQueue {
return DispatchQueue.global(qos: qos)
}
}
extension DispatchQueue {
private static var _onceTracker = [String]()
/**
Executes a block of code, associated with a unique token, only once. The code is thread safe and will
only execute the code once even in the presence of multithreaded calls.
- parameter token: A unique reverse DNS style name such as com.vectorform.<name> or a GUID
- parameter block: Block to execute once
*/
public class func once(token: String, block: () -> Void) {
objc_sync_enter(self); defer { objc_sync_exit(self) }
if _onceTracker.contains(token) {
return
}
_onceTracker.append(token)
block()
}
}
extension Int {
var toEmoji: String {
let dict = [
0: "0️⃣",
1: "1️⃣",
2: "2️⃣",
3: "3️⃣",
4: "4️⃣",
5: "5️⃣",
6: "6️⃣",
7: "7️⃣",
8: "8️⃣",
9: "9️⃣",
]
return dict[self] ?? self.description
}
}
extension SecondController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return tags.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tags[section].count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
}
}
extension SecondController: UITableViewDelegate {
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell.tintColor = UIColor.red
cell.accessoryType = .disclosureIndicator
cell.textLabel?.text = tags[indexPath.section][indexPath.row].0
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: false)
let tag = tags[indexPath.section][indexPath.row]
print("🍀🍀🍀\(tag.0)🍀🍀🍀")
print("**************************开始**************************")
perform(tag.1)
}
}
| 5657cc9023e099773280f7a4f660ac96 | 29.91015 | 139 | 0.536255 | false | false | false | false |
S7Vyto/TouchVK | refs/heads/master | TouchVK/TouchVK/Services/Network/NetworkService.swift | apache-2.0 | 1 | //
// NetworkService.swift
// TouchVK
//
// Created by Sam on 07/02/2017.
// Copyright © 2017 Semyon Vyatkin. All rights reserved.
//
import Foundation
import UIKit
import RxSwift
import RealmSwift
enum NetworkError: Error {
case responseMalformed
case responseStatusCode(code: Int)
case unknownError(Error)
}
class NetworkService {
private let url: URL
init(url: URL) {
self.url = url
}
private func data(for urlResourse: URLResource) -> Observable<Data> {
let request = urlResourse.request(with: url)
return Observable.create({ (observer) -> Disposable in
UIApplication.shared.isNetworkActivityIndicatorVisible = true
let session = NetworkSession.shared.session
let task = session.dataTask(with: request as URLRequest,
completionHandler: { (jsonData, responseUrl, responseError) in
if let error = responseError {
observer.onError(NetworkError.unknownError(error))
}
else {
guard let httpResponse = responseUrl as? HTTPURLResponse else {
observer.onError(NetworkError.responseMalformed)
return
}
if 200 ..< 300 ~= httpResponse.statusCode {
observer.onNext(jsonData ?? Data())
observer.onCompleted()
}
else {
observer.onError(NetworkError.responseStatusCode(code: httpResponse.statusCode))
}
}
})
task.resume()
return Disposables.create(with: {
task.cancel()
})
})
}
func responseObjects<T: ParserService>(for urlResourse: URLResource) -> Observable<[T]> {
return
data(for: urlResourse)
.observeOn(MainScheduler.instance)
.do(onNext: { _ in
UIApplication.shared.isNetworkActivityIndicatorVisible = false
})
.map({ data in
guard let objects: [T] = data.decode() else {
throw NetworkError.responseMalformed
}
return objects
})
}
}
| 7751b8028c2535f1d1f890bbb01cd380 | 36.594937 | 132 | 0.424242 | false | false | false | false |
Acidburn0zzz/firefox-ios | refs/heads/main | Client/BottomSheet/BottomSheetViewController.swift | mpl-2.0 | 1 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import UIKit
import SnapKit
import Shared
enum BottomSheetState {
case none
case partial
case full
}
protocol BottomSheetDelegate {
func closeBottomSheet()
func showBottomToolbar()
}
class BottomSheetViewController: UIViewController, Themeable {
// Delegate
var delegate: BottomSheetDelegate?
private var currentState: BottomSheetState = .none
private var isLandscape: Bool {
return UIApplication.shared.statusBarOrientation.isLandscape
}
private var orientationBasedHeight: CGFloat {
return isLandscape ? DeviceInfo.screenSizeOrientationIndependent().width : DeviceInfo.screenSizeOrientationIndependent().height
}
// shows how much bottom sheet should be visible
// 1 = full, 0.5 = half, 0 = hidden
// and for landscape we show 0.5 specifier just because of very small height
private var heightSpecifier: CGFloat {
let height = orientationBasedHeight
let heightForTallScreen: CGFloat = height > 850 ? 0.65 : 0.74
var specifier = height > 668 ? heightForTallScreen : 0.84
if isLandscape {
specifier = 0.5
}
return specifier
}
private var navHeight: CGFloat {
return navigationController?.navigationBar.frame.height ?? 0
}
private var fullHeight: CGFloat {
return orientationBasedHeight - navHeight
}
private var partialHeight: CGFloat {
return fullHeight * heightSpecifier
}
private var maxY: CGFloat {
return fullHeight - partialHeight
}
private var minY: CGFloat {
return orientationBasedHeight
}
private var endedYVal: CGFloat = 0
private var endedTranslationYVal: CGFloat = 0
// Container child view controller
var containerViewController: UIViewController?
// Views
private var overlay: UIView = {
let view = UIView()
view.backgroundColor = UIColor.black.withAlphaComponent(0.50)
return view
}()
private var panView: UIView = {
let view = UIView()
return view
}()
// MARK: Initializers
init() {
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
roundViews()
initialViewSetup()
applyTheme()
}
// MARK: View setup
private func initialViewSetup() {
self.view.backgroundColor = .clear
self.view.addSubview(overlay)
overlay.snp.makeConstraints { make in
make.edges.equalToSuperview()
make.centerX.equalToSuperview()
}
self.view.addSubview(panView)
panView.snp.makeConstraints { make in
make.bottom.equalTo(self.view.safeArea.bottom)
make.centerX.equalToSuperview()
make.left.right.equalToSuperview()
make.height.equalTo(fullHeight)
}
let gesture = UIPanGestureRecognizer.init(target: self, action: #selector(panGesture))
panView.addGestureRecognizer(gesture)
panView.translatesAutoresizingMaskIntoConstraints = true
let overlayTapGesture = UITapGestureRecognizer(target: self, action: #selector(self.hideViewWithAnimation))
overlay.addGestureRecognizer(overlayTapGesture)
hideView(shouldAnimate: false)
}
private func roundViews() {
panView.layer.cornerRadius = 10
view.clipsToBounds = true
panView.clipsToBounds = true
}
// MARK: Bottomsheet swipe methods
private func moveView(state: BottomSheetState) {
self.currentState = state
let yVal = state == .full ? navHeight : state == .partial ? maxY : minY
panView.frame = CGRect(x: 0, y: yVal, width: view.frame.width, height: fullHeight)
}
private func moveView(panGestureRecognizer recognizer: UIPanGestureRecognizer) {
let translation = recognizer.translation(in: view)
let yVal: CGFloat = translation.y
let startedYVal = endedTranslationYVal + maxY
let newYVal = currentState == .full ? navHeight + yVal : startedYVal + yVal
let downYShiftSpecifier: CGFloat = isLandscape ? 0.3 : 0.2
// top
guard newYVal >= navHeight else {
endedTranslationYVal = 0
return
}
// move the frame according to pan gesture
panView.frame = CGRect(x: 0, y: newYVal, width: view.frame.width, height: fullHeight)
if recognizer.state == .ended {
self.endedTranslationYVal = 0
// moving down
if newYVal > self.maxY {
// past middle
if newYVal > self.maxY + (self.partialHeight * downYShiftSpecifier) {
hideView(shouldAnimate: true)
} else {
self.moveView(state: .partial)
}
// moving up
} else if newYVal < self.maxY {
self.showFullView(shouldAnimate: true)
}
}
}
@objc func hideView(shouldAnimate: Bool) {
let closure = {
self.moveView(state: .none)
self.view.isUserInteractionEnabled = true
}
guard shouldAnimate else {
closure()
self.overlay.alpha = 0
self.view.isHidden = true
delegate?.showBottomToolbar()
return
}
self.view.isUserInteractionEnabled = false
UIView.animate(withDuration: 0.25) {
closure()
self.overlay.alpha = 0
} completion: { value in
if value {
self.view.isHidden = true
self.delegate?.showBottomToolbar()
self.containerViewController?.view.removeFromSuperview()
}
}
}
@objc func showView() {
if let container = containerViewController {
panView.addSubview(container.view)
}
UIView.animate(withDuration: 0.26, animations: {
self.moveView(state: self.isLandscape ? .full : .partial)
self.overlay.alpha = 1
self.view.isHidden = false
})
}
func showFullView(shouldAnimate: Bool) {
let closure = {
self.moveView(state: .full)
self.overlay.alpha = 1
self.view.isHidden = false
}
guard shouldAnimate else {
closure()
return
}
UIView.animate(withDuration: 0.26, animations: {
closure()
})
}
@objc private func panGesture(_ recognizer: UIPanGestureRecognizer) {
moveView(panGestureRecognizer: recognizer)
}
@objc private func hideViewWithAnimation() {
hideView(shouldAnimate: true)
}
func applyTheme() {
if ThemeManager.instance.currentName == .normal {
panView.backgroundColor = UIColor(rgb: 0xF2F2F7)
} else {
panView.backgroundColor = UIColor(rgb: 0x1C1C1E)
}
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
coordinator.animate(alongsideTransition: { (UIViewControllerTransitionCoordinatorContext) -> Void in
let orient = UIApplication.shared.statusBarOrientation
switch orient {
case .portrait:
self.moveView(state: .partial)
case .landscapeLeft, .landscapeRight:
self.moveView(state: .full)
default:
print("orientation not supported")
}
}, completion: { (UIViewControllerTransitionCoordinatorContext) -> Void in
self.view.setNeedsLayout()
self.view.layoutIfNeeded()
self.containerViewController?.view.setNeedsLayout()
})
}
}
| 75a3af7aa805a5690b0f0cf2751f877b | 32.180723 | 135 | 0.609053 | false | false | false | false |
j13244231/BlackDesertNote | refs/heads/master | GameNote/Dish.swift | mit | 1 | //
// Dish.swift
// GameNote
//
// Created by 劉進泰 on 2017/6/26.
// Copyright © 2017年 劉進泰. All rights reserved.
//
import Foundation
import Firebase
class Dish:NSObject, NSCoding {
private var _dishRef:DatabaseReference!
//MARK: Types
struct PropertyKey {
static let key:String = "key"
static let dictionary:String = "dictionary"
}
//MARK: Archiving Paths
static let DocumentsDirectory:URL = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first!
static let ArchiveURL = DocumentsDirectory.appendingPathComponent("dishs")
private var _dishKey:String!
private var _dishName:String!
private var _dishDifficulty:String!
private var _dishMaterial:[String]!
private var _materialAmount:[Int]!
private var _dictionary:Dictionary<String, AnyObject>!
var dishKey:String {
return _dishKey
}
var dishName:String {
return _dishName
}
var dishDifficulty:String {
return _dishDifficulty
}
var dishMaterial:[String] {
return _dishMaterial
}
var materialAmount:[Int] {
return _materialAmount
}
var dictionary:Dictionary<String, AnyObject> {
return _dictionary
}
init(key:String, dictionary:Dictionary<String, AnyObject>) {
self._dishKey = key
self._dictionary = dictionary
if let dishName = dictionary["名稱"] as? String {
self._dishName = dishName
}
if let dishDifficulty = dictionary["難度"] as? String {
self._dishDifficulty = dishDifficulty
}
if let dishMaterial = dictionary["材料"] as? [String] {
self._dishMaterial = dishMaterial
}
if let materialAmount = dictionary["材料數量"] as? [Int] {
self._materialAmount = materialAmount
}
self._dishRef = Database.database().reference().child("料理").child(key)
}
//MARK: NSCoding
func encode(with aCoder: NSCoder) {
aCoder.encode(dishKey, forKey: PropertyKey.key)
aCoder.encode(dictionary, forKey: PropertyKey.dictionary)
}
required convenience init?(coder aDecoder: NSCoder) {
guard let key = aDecoder.decodeObject(forKey: PropertyKey.key) as? String else {
print("解碼 key 失敗!")
return nil
}
guard let dictionary = aDecoder.decodeObject(forKey: PropertyKey.dictionary) as? Dictionary<String, AnyObject> else {
print("解碼 dictionary 失敗!")
return nil
}
self.init(key: key, dictionary: dictionary)
}
}
| 9eac1bfac35360656573c0406c538c92 | 26.530612 | 125 | 0.604893 | false | false | false | false |
elationfoundation/Reporta-iOS | refs/heads/master | IWMF/Modal/Circle.swift | gpl-3.0 | 1 | //
// Circle.swift
// IWMF
//
// This class is used for Store circle detail.
//
//
import Foundation
enum CircleType: Int {
case Private = 1
case Public = 2
case Social = 3
}
class Circle: NSObject {
var circleName: String!
var circleType: CircleType!
var contactsList: NSMutableArray!
override init() {
circleName = ""
circleType = .Private
contactsList = NSMutableArray()
super.init()
}
init(name:String, type:CircleType, contactList:NSMutableArray ){
self.circleName = name;
circleType = type;
contactsList = contactList
super.init()
}
required init(coder aDecoder: NSCoder)
{
self.circleName = aDecoder.decodeObjectForKey("circleName") as! String
self.contactsList = aDecoder.decodeObjectForKey("contactsList") as! NSMutableArray
let circleTypeValue = Int(aDecoder.decodeObjectForKey("circleType") as! NSNumber)
if circleTypeValue == 1
{
self.circleType = CircleType.Private
}
else if circleTypeValue == 2
{
self.circleType = CircleType.Public
}
else if circleTypeValue == 3
{
self.circleType = CircleType.Social
}
}
func encodeWithCoder(aCoder: NSCoder) {
if let circleName = self.circleName{
aCoder.encodeObject(circleName, forKey: "circleName")
}
if let contactsList = self.contactsList{
aCoder.encodeObject(contactsList, forKey: "contactsList")
}
let circleTypeValue = NSNumber(integer: self.circleType.rawValue)
aCoder.encodeObject(circleTypeValue, forKey: "circleType")
}
func insertContactsListInCircle(conList: ContactList){
self.contactsList.addObject(conList)
}
} | beb603eae722021aa535c58f9f28859e | 26.746269 | 91 | 0.617869 | false | false | false | false |
cxk1992/Bonjour | refs/heads/master | Bonjour/ViewController.swift | mit | 1 | //
// ViewController.swift
// Bonjour
//
// Created by 陈旭珂 on 2016/8/16.
// Copyright © 2016年 陈旭珂. All rights reserved.
//
import UIKit
class ViewController: UIViewController , UITextFieldDelegate {
var handler : ConnectHandler?{
didSet{
handler?.dataReceiveClouser = { (data:Data ,handler:ConnectHandler) in
let message = String(data: data, encoding: String.Encoding.utf8)
let messageh = Message()
messageh.type = .fromOther
messageh.message = message
self.dataSource.append(messageh)
self.tableView.reloadData()
}
self.dataSource = (handler?.messages)!
self.tableView.reloadData()
}
}
var name = "viewController"{
didSet{
titleLabel.text = name
}
}
var dataSource : [Message] = []
let tableView = UITableView(frame: CGRect(), style: .plain)
let textField = UITextField()
let titleLabel = { () -> UILabel in
let label = UILabel()
label.textAlignment = .center
return label
}()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
view.backgroundColor = UIColor.white
titleLabel.frame = CGRect(x: 0, y: 20, width: view.bounds.size.width, height: 30)
titleLabel.autoresizingMask = [.flexibleWidth,.flexibleHeight]
view.addSubview(titleLabel)
view.addSubview(tableView)
tableView.frame = CGRect(x: 0, y: 50, width: view.bounds.size.width, height: view.bounds.size.height - 80)
tableView.delegate = self
tableView.dataSource = self
tableView.autoresizingMask = [.flexibleWidth,.flexibleHeight]
textField.frame = CGRect(x: 0, y: view.bounds.size.height - 50, width: view.bounds.size.width, height: 30)
textField.autoresizingMask = [.flexibleTopMargin,.flexibleWidth]
textField.delegate = self
textField.borderStyle = .roundedRect
view.addSubview(textField)
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField.text?.characters.count != 0{
handler?.send(data: (textField.text?.data(using: .utf8))!)
let message = Message()
message.message = textField.text
self.dataSource.append(message)
self.tableView.reloadData()
textField.text = ""
}
textField.resignFirstResponder()
return true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
print(#function)
}
deinit {
print(#function)
}
}
extension ViewController : UITableViewDelegate , UITableViewDataSource{
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSource.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "cell")
if cell == nil {
cell = UITableViewCell(style: .value1, reuseIdentifier: "cell")
cell?.detailTextLabel?.textColor = .black
cell?.textLabel?.textColor = .black
}
let message = dataSource[indexPath.row]
if message.type == .fromOther {
cell?.textLabel?.text = message.message
}else{
cell?.detailTextLabel?.text = message.message
}
return cell!
}
}
| 5d4a4cc208edfd6512f16891e5acf6de | 29.992188 | 114 | 0.594908 | false | false | false | false |
WestlakeAPC/game-off-2016 | refs/heads/master | external/Fiber2D/Fiber2D/PhysicsContact.swift | apache-2.0 | 1 | //
// PhysicsContact.swift
// Fiber2D
//
// Created by Andrey Volodin on 22.09.16.
// Copyright © 2016 s1ddok. All rights reserved.
//
import SwiftMath
public enum EventCode {
case none, begin, presolve, postsolve, separate
}
/**
* An object that implements the PhysicsContactDelegate protocol can respond
* when two physics bodies are in contact with each other in a physics world.
* To receive contact messages, you set the contactDelegate property of a PhysicsWorld object.
* The delegate is called when a contact starts or ends.
*/
public protocol PhysicsContactDelegate: class {
/** Called when two bodies first contact each other. */
func didBegin(contact: PhysicsContact)
/** Called when the contact ends between two physics bodies. */
func didEnd(contact: PhysicsContact)
}
public struct PhysicsContactData {
let points: [Point]
let normal: Vector2f
}
/**
* @brief Contact information.
* It will be created automatically when two shape contact with each other.
* And it will be destroyed automatically when two shape separated.
*/
public struct PhysicsContact {
/** Get contact shape A. */
public unowned var shapeA: PhysicsShape
/** Get contact shape B. */
public unowned var shapeB: PhysicsShape
/** Get contact data */
public var contactData: PhysicsContactData
/** Get previous contact data */
//public let previousContactData: PhysicsContactData
internal let arbiter: UnsafeMutablePointer<cpArbiter>!
internal init(shapeA: PhysicsShape, shapeB: PhysicsShape, arb: UnsafeMutablePointer<cpArbiter>!) {
self.shapeA = shapeA
self.shapeB = shapeB
self.arbiter = arb
let count = cpArbiterGetCount(arb)
var points = [Point](repeating: Point.zero, count: Int(count))
for i in 0..<count {
points[Int(i)] = Point(cpArbiterGetPointA(arb, i))
}
let normal = count == 0 ? vec2.zero : vec2(cpArbiterGetNormal(arb))
self.contactData = PhysicsContactData(points: points, normal: normal)
}
}
/**
* @brief Presolve value generated when onContactPreSolve called.
*/
public struct PhysicsContactPreSolve {
/** Get elasticity between two bodies.*/
let elasticity: Float
/** Get friction between two bodies.*/
let friction: Float
/** Get surface velocity between two bodies.*/
let surfaceVelocity: Vector2f
internal var contactInfo: OpaquePointer
/** Ignore the rest of the contact presolve and postsolve callbacks. */
func ignore() {
}
}
/**
* @brief Postsolve value generated when onContactPostSolve called.
*/
public struct PhysicsContactPostSolve {
/** Get elasticity between two bodies.*/
let elasticity: Float
/** Get friction between two bodies.*/
let friction: Float
/** Get surface velocity between two bodies.*/
let surfaceVelocity: Vector2f
internal var contactInfo: OpaquePointer
}
| 6936ec9e421ada4de2cf37c066c3baea | 28.84 | 102 | 0.689678 | false | false | false | false |
Rochester-Ting/DouyuTVDemo | refs/heads/master | RRDouyuTV/RRDouyuTV/Classes/Tools(工具)/NetworkTools.swift | mit | 1 | //
// NetworkTools.swift
// RRDouyuTV
//
// Created by 丁瑞瑞 on 13/10/16.
// Copyright © 2016年 Rochester. All rights reserved.
//
import UIKit
import Alamofire
enum MethodType {
case GET
case POST
}
class NetworkTools {
class func requestData(type : MethodType,urlString : String ,paramters : [String : NSString]? = nil,finishedCallBack : @escaping (_ result : AnyObject)->()) {
let methodType = type == .GET ? HTTPMethod.get : HTTPMethod.post
Alamofire.request(urlString, method: methodType, parameters: paramters, encoding: URLEncoding.default, headers: nil).responseJSON { (response) in
guard let result = response.result.value else{
print(response.result.error)
return
}
finishedCallBack(result as AnyObject)
}
}
}
| 6de8de34fb053a95c70297dc74ba65e2 | 26.580645 | 162 | 0.62807 | false | false | false | false |
mitochrome/complex-gestures-demo | refs/heads/master | apps/GestureInput/Carthage/Checkouts/RxDataSources/RxSwift/RxExample/RxExample/Examples/SimpleValidation/SimpleValidationViewController.swift | mit | 4 | //
// SimpleValidationViewController.swift
// RxExample
//
// Created by Krunoslav Zaher on 12/6/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import UIKit
#if !RX_NO_MODULE
import RxSwift
import RxCocoa
#endif
let minimalUsernameLength = 5
let minimalPasswordLength = 5
class SimpleValidationViewController : ViewController {
@IBOutlet weak var usernameOutlet: UITextField!
@IBOutlet weak var usernameValidOutlet: UILabel!
@IBOutlet weak var passwordOutlet: UITextField!
@IBOutlet weak var passwordValidOutlet: UILabel!
@IBOutlet weak var doSomethingOutlet: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
usernameValidOutlet.text = "Username has to be at least \(minimalUsernameLength) characters"
passwordValidOutlet.text = "Password has to be at least \(minimalPasswordLength) characters"
let usernameValid = usernameOutlet.rx.text.orEmpty
.map { $0.characters.count >= minimalUsernameLength }
.shareReplay(1) // without this map would be executed once for each binding, rx is stateless by default
let passwordValid = passwordOutlet.rx.text.orEmpty
.map { $0.characters.count >= minimalPasswordLength }
.shareReplay(1)
let everythingValid = Observable.combineLatest(usernameValid, passwordValid) { $0 && $1 }
.shareReplay(1)
usernameValid
.bind(to: passwordOutlet.rx.isEnabled)
.disposed(by: disposeBag)
usernameValid
.bind(to: usernameValidOutlet.rx.isHidden)
.disposed(by: disposeBag)
passwordValid
.bind(to: passwordValidOutlet.rx.isHidden)
.disposed(by: disposeBag)
everythingValid
.bind(to: doSomethingOutlet.rx.isEnabled)
.disposed(by: disposeBag)
doSomethingOutlet.rx.tap
.subscribe(onNext: { [weak self] _ in self?.showAlert() })
.disposed(by: disposeBag)
}
func showAlert() {
let alertView = UIAlertView(
title: "RxExample",
message: "This is wonderful",
delegate: nil,
cancelButtonTitle: "OK"
)
alertView.show()
}
}
| 418c42015c8c5b8fc491b5354bc7f7b1 | 28.350649 | 115 | 0.649558 | false | false | false | false |
BlakeBarrett/wndw | refs/heads/master | wtrmrkr/VideoPreviewPlayerViewController.swift | mit | 1 | //
// VideoPreviewPlayerViewController.swift
// wndw
//
// Created by Blake Barrett on 6/9/16.
// Copyright © 2016 Blake Barrett. All rights reserved.
//
import Foundation
import AVFoundation
import AVKit
class VideoPreviewPlayerViewController: UIViewController {
var url :NSURL?
var player :AVPlayer?
override func viewDidLoad() {
guard let url = url else { return }
self.player = AVPlayer(URL: url)
let playerController = AVPlayerViewController()
playerController.player = player
self.addChildViewController(playerController)
self.view.addSubview(playerController.view)
playerController.view.frame = self.view.frame
}
override func viewDidAppear(animated: Bool) {
player?.play()
}
}
| a861c998456acf8b0deb190927b99756 | 24.09375 | 58 | 0.673724 | false | false | false | false |
NikolaiRuhe/SwiftDigest | refs/heads/master | SwiftDigestTests/MD5DigestTests.swift | mit | 1 | import SwiftDigest
import XCTest
class MD5Tests: XCTestCase {
func testEmpty() {
XCTAssertEqual(
Data().md5,
MD5Digest(rawValue: "d41d8cd98f00b204e9800998ecf8427e")
)
}
func testData() {
XCTAssertEqual(
MD5Digest(rawValue: "d41d8cd98f00b204e9800998ecf8427e")?.data,
Data([212, 29, 140, 217, 143, 0, 178, 4, 233, 128, 9, 152, 236, 248, 66, 126,])
)
}
func testBytes() {
XCTAssertEqual(
"\(MD5Digest(rawValue: "d41d8cd98f00b204e9800998ecf8427e")!.bytes)",
"(212, 29, 140, 217, 143, 0, 178, 4, 233, 128, 9, 152, 236, 248, 66, 126)"
)
}
func testFox1() {
let input = "The quick brown fox jumps over the lazy dog"
XCTAssertEqual(
input.utf8.md5,
MD5Digest(rawValue: "9e107d9d372bb6826bd81d3542a419d6")
)
}
func testFox2() {
let input = "The quick brown fox jumps over the lazy dog."
XCTAssertEqual(
input.utf8.md5,
MD5Digest(rawValue: "e4d909c290d0fb1ca068ffaddf22cbd0")
)
}
func testTwoFooterChunks() {
let input = Data(count: 57)
XCTAssertEqual(
input.md5,
MD5Digest(rawValue: "ab9d8ef2ffa9145d6c325cefa41d5d4e")
)
}
func test4KBytes() {
var input = String(repeating: "The quick brown fox jumps over the lazy dog.", count: 100)
XCTAssertEqual(
input.utf8.md5,
MD5Digest(rawValue: "7052292b1c02ae4b0b35fabca4fbd487")
)
}
func test4MBytes() {
var input = String(repeating: "The quick brown fox jumps over the lazy dog.", count: 100000)
XCTAssertEqual(
input.utf8.md5,
MD5Digest(rawValue: "f8a4ffa8b1c902f072338caa1e4482ce")
)
}
func testRecursive() {
XCTAssertEqual(
"".utf8.md5.description.utf8.md5.description.utf8.md5.description.utf8.md5,
MD5Digest(rawValue: "5a8dccb220de5c6775c873ead6ff2e43")
)
}
func testEncoding() {
let sut = MD5Digest(rawValue: "d41d8cd98f00b204e9800998ecf8427e")!
let json = String(bytes: try! JSONEncoder().encode([sut]), encoding: .utf8)!
XCTAssertEqual(json, "[\"\(sut)\"]")
}
func testDecoding() {
let sut = MD5Digest(rawValue: "d41d8cd98f00b204e9800998ecf8427e")!
let json = Data("[\"\(sut)\"]".utf8)
let digest = try! JSONDecoder().decode(Array<MD5Digest>.self, from: json).first!
XCTAssertEqual(digest, sut)
}
}
| a4ed55ae9917bda6c2bcf849d68bc656 | 28.873563 | 100 | 0.586764 | false | true | false | false |
ThunderStruct/MSCircularSlider | refs/heads/master | MSCircularSliderExample/MSCircularSliderExample/SliderPropertiesVC.swift | mit | 1 | //
// SliderPropertiesVC.swift
// MSCircularSliderExample
//
// Created by Mohamed Shahawy on 10/2/17.
// Copyright © 2017 Mohamed Shahawy. All rights reserved.
//
import UIKit
class SliderProperties: UIViewController, MSCircularSliderDelegate, ColorPickerDelegate {
// Outlets
@IBOutlet weak var slider: MSCircularSlider!
@IBOutlet weak var handleTypeLbl: UILabel!
@IBOutlet weak var unfilledColorBtn: UIButton!
@IBOutlet weak var filledColorBtn: UIButton!
@IBOutlet weak var handleColorBtn: UIButton!
@IBOutlet weak var descriptionLbl: UILabel!
@IBOutlet weak var valueLbl: UILabel!
// Members
var currentColorPickTag = 0
var colorPicker: ColorPickerView?
var animationTimer: Timer?
var animationReversed = false
var currentRevolutions = 0
var currentValue = 0.0
// Actions
@IBAction func handleTypeValueChanged(_ sender: UIStepper) {
slider.handleType = MSCircularSliderHandleType(rawValue: Int(sender.value)) ?? slider.handleType
handleTypeLbl.text = handleTypeStrFrom(slider.handleType)
}
@IBAction func maxAngleAction(_ sender: UISlider) {
slider.maximumAngle = CGFloat(sender.value)
descriptionLbl.text = getDescription()
}
@IBAction func colorPickAction(_ sender: UIButton) {
currentColorPickTag = sender.tag
colorPicker?.isHidden = false
}
@IBAction func rotationAngleAction(_ sender: UISlider) {
descriptionLbl.text = getDescription()
if sender.value == 0 {
slider.rotationAngle = nil
return
}
slider.rotationAngle = CGFloat(sender.value)
}
@IBAction func lineWidthAction(_ sender: UIStepper) {
slider.lineWidth = Int(sender.value)
descriptionLbl.text = getDescription()
}
// Init
override func viewDidLoad() {
super.viewDidLoad()
handleTypeLbl.text = handleTypeStrFrom(slider.handleType)
colorPicker = ColorPickerView(frame: CGRect(x: 0, y: view.center.y - view.frame.height * 0.3 / 2.0, width: view.frame.width, height: view.frame.height * 0.3))
colorPicker?.isHidden = true
colorPicker?.delegate = self
slider.delegate = self
currentValue = slider.currentValue
valueLbl.text = String(format: "%.1f", currentValue)
descriptionLbl.text = getDescription()
view.addSubview(colorPicker!)
}
override func viewDidAppear(_ animated: Bool) {
// Slider animation
animateSlider()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// Support Methods
func handleTypeStrFrom(_ type: MSCircularSliderHandleType) -> String {
switch type {
case .smallCircle:
return "Small Circle"
case .mediumCircle:
return "Medium Circle"
case .largeCircle:
return "Large Circle"
case .doubleCircle:
return "Double Circle"
}
}
func directionToString(_ direction: MSCircularSliderDirection) -> String {
return direction == .none ? "None" : (direction == .clockwise ? "Clockwise" : "Counter-Clockwise")
}
func getDescription(_ sliderDirection: MSCircularSliderDirection = .none) -> String {
let rotationAngle = slider.rotationAngle == nil ? "Computed" : String(format: "%.1f", slider.rotationAngle!) + "°"
return "Maximum Angle: \(String(format: "%.1f", slider.maximumAngle))°\nLine Width: \(slider.lineWidth)\nRotation Angle: \(rotationAngle)\nSliding Direction: " + directionToString(sliderDirection)
}
// Delegate Methods
func circularSlider(_ slider: MSCircularSlider, valueChangedTo value: Double, fromUser: Bool) {
currentValue = value
if !slider.endlesslyLoops || !slider.fullCircle {
valueLbl.text = String(format: "%.1f\nx%d", currentValue, currentRevolutions + 1)
}
else {
valueLbl.text = String(format: "%.1f", currentValue)
}
}
func circularSlider(_ slider: MSCircularSlider, startedTrackingWith value: Double) {
// optional delegate method
}
func circularSlider(_ slider: MSCircularSlider, endedTrackingWith value: Double) {
// optional delegate method
}
func circularSlider(_ slider: MSCircularSlider, directionChangedTo value: MSCircularSliderDirection) {
descriptionLbl.text = getDescription(value)
}
func circularSlider(_ slider: MSCircularSlider, revolutionsChangedTo value: Int) {
currentRevolutions = value
valueLbl.text = String(format: "%.1f\nx%d", currentValue, currentRevolutions + 1)
}
func colorPickerTouched(sender: ColorPickerView, color: UIColor, point: CGPoint, state: UIGestureRecognizer.State) {
switch currentColorPickTag {
case 0:
unfilledColorBtn.setTitleColor(color, for: .normal)
slider.unfilledColor = color
case 1:
filledColorBtn.setTitleColor(color, for: .normal)
slider.filledColor = color
case 2:
handleColorBtn.setTitleColor(color, for: .normal)
slider.handleColor = color
default:
break
}
colorPicker?.isHidden = true
}
func animateSlider() {
animationTimer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(updateSliderValue), userInfo: nil, repeats: true)
}
@objc func updateSliderValue() {
slider.currentValue += animationReversed ? -1.0 : 1.0
if slider.currentValue >= slider.maximumValue {
animationTimer?.invalidate()
// Reverse animation
animationReversed = true
animationTimer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(updateSliderValue), userInfo: nil, repeats: true)
}
else if slider.currentValue <= slider.minimumValue && animationReversed {
// Animation ended
animationTimer?.invalidate()
}
}
}
| d589db9d626fe5db1c271b6a27d041fe | 34.559322 | 204 | 0.640769 | false | false | false | false |
sunweifeng/SWFKit | refs/heads/master | Example/SWFKit/TestPresentViewController.swift | mit | 1 | //
// TestPresentViewController.swift
// TestApp
//
// Created by 孙伟峰 on 2017/6/19.
// Copyright © 2017年 Sun Weifeng. All rights reserved.
//
import UIKit
import SWFKit
class TestPresentViewController: UIViewController, UIViewControllerTransitioningDelegate {
lazy var closeBtn: UIButton = {
let btn = UIButton(frame: CGRect(x: 0, y: 0, width: 200, height: 50))
btn.setTitle("Close", for: .normal)
btn.setTitleColor(UIColor.purple, for: .normal)
btn.addTarget(self, action: #selector(self.close), for: .touchUpInside)
return btn
}()
lazy var contentView: UIView = {
let view = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 300))
view.backgroundColor = UIColor.white
view.center = self.view.center
return view
}()
func close() {
self.dismiss(animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
self.contentView.addSubview(closeBtn)
self.view.addSubview(contentView)
// Do any additional setup after loading the view.
}
func commonInit() {
self.modalPresentationStyle = .custom
self.transitioningDelegate = self
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.commonInit()
}
override init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: Bundle!) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
self.commonInit()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? {
if presented == self {
return SWFPresentationController(presentedViewController: presented, presenting: presenting)
}
return nil
}
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
if presented == self {
return SWFControllerAnimatedTransitioning(isPresenting: true)
}
return nil
}
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
if dismissed == self {
return SWFControllerAnimatedTransitioning(isPresenting: false)
}
return nil
}
}
| c2cc249a3f9dbcf4c14130ef5789bb2f | 31.825 | 170 | 0.66032 | false | false | false | false |
auth0/Lock.swift | refs/heads/master | Lock/EnterpriseDomainInteractor.swift | mit | 1 | // EnterpriseDomainInteractor.swift
//
// Copyright (c) 2016 Auth0 (http://auth0.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import Auth0
struct EnterpriseDomainInteractor: HRDAuthenticatable {
var email: String? {
return self.user.email
}
var validEmail: Bool {
return self.user.validEmail
}
var connection: EnterpriseConnection?
var domain: String?
let user: User
let connections: [EnterpriseConnection]
let emailValidator: InputValidator = EmailValidator()
let authenticator: OAuth2Authenticatable
init(connections: Connections, user: User, authentication: OAuth2Authenticatable) {
self.connections = connections.enterprise
self.authenticator = authentication
if self.connections.count == 1 && connections.oauth2.isEmpty && connections.database == nil {
self.connection = self.connections.first
}
self.user = user
}
func match(domain: String) -> EnterpriseConnection? {
return connections.filter { $0.domains.contains(domain) }.first
}
mutating func updateEmail(_ value: String?) throws {
self.connection = nil
self.user.email = value?.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
let error = emailValidator.validate(self.email)
self.user.validEmail = error == nil
if let error = error {
throw error
}
self.connection = nil
if let domain = value?.components(separatedBy: "@").last?.lowercased() {
self.connection = match(domain: domain)
self.domain = domain
}
}
func login(_ callback: @escaping (OAuth2AuthenticatableError?) -> Void) {
guard let connection = self.connection else { return callback(.noConnectionAvailable) }
authenticator.start(connection.name, loginHint: self.email, screenHint: nil, useEphemeralSession: false, callback: callback)
}
}
| e81025a1f5a9e77bb9299fd33369d863 | 37.101266 | 132 | 0.703987 | false | false | false | false |
ortuman/SwiftForms | refs/heads/master | Sources/SwiftFormsPackage/cells/base/FormValueCell.swift | mit | 1 | //
// FormValueCell.swift
// SwiftForms
//
// Created by Miguel Ángel Ortuño Ortuño on 13/11/14.
// Copyright (c) 2014 Miguel Angel Ortuño. All rights reserved.
//
import UIKit
open class FormValueCell: FormBaseCell {
// MARK: Cell views
@objc public let titleLabel = UILabel()
@objc public let valueLabel = UILabel()
// MARK: Properties
fileprivate var customConstraints: [AnyObject]!
// MARK: FormBaseCell
open override func configure() {
super.configure()
accessoryType = .disclosureIndicator
titleLabel.translatesAutoresizingMaskIntoConstraints = false
valueLabel.translatesAutoresizingMaskIntoConstraints = false
titleLabel.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.body)
valueLabel.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.body)
valueLabel.textColor = UIColor.lightGray
valueLabel.textAlignment = .right
contentView.addSubview(titleLabel)
contentView.addSubview(valueLabel)
titleLabel.setContentHuggingPriority(UILayoutPriority(rawValue: 500), for: .horizontal)
titleLabel.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 1000), for: .horizontal)
// apply constant constraints
contentView.addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .height, relatedBy: .equal, toItem: contentView, attribute: .height, multiplier: 1.0, constant: 0.0))
contentView.addConstraint(NSLayoutConstraint(item: valueLabel, attribute: .height, relatedBy: .equal, toItem: contentView, attribute: .height, multiplier: 1.0, constant: 0.0))
contentView.addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .centerY, relatedBy: .equal, toItem: contentView, attribute: .centerY, multiplier: 1.0, constant: 0.0))
contentView.addConstraint(NSLayoutConstraint(item: valueLabel, attribute: .centerY, relatedBy: .equal, toItem: contentView, attribute: .centerY, multiplier: 1.0, constant: 0.0))
}
open override func constraintsViews() -> [String : UIView] {
return ["titleLabel" : titleLabel, "valueLabel" : valueLabel]
}
open override func defaultVisualConstraints() -> [String] {
// apply default constraints
var rightPadding = 0
if accessoryType == .none {
rightPadding = 16
}
if titleLabel.text != nil && (titleLabel.text!).count > 0 {
return ["H:|-16-[titleLabel]-[valueLabel]-\(rightPadding)-|"]
}
else {
return ["H:|-16-[valueLabel]-\(rightPadding)-|"]
}
}
}
| a9b14f7463546a4853fbf8dbce4e3148 | 38.085714 | 185 | 0.662281 | false | false | false | false |
XeresRazor/SwiftRaytracer | refs/heads/master | src/pathtracer/Traceable.swift | mit | 1 | //
// Traceable.swift
// Raytracer
//
// Created by David Green on 4/6/16.
// Copyright © 2016 David Green. All rights reserved.
//
import simd
public struct HitRecord {
var time: Double
var point: double4
var normal: double4
var u: Double
var v: Double
var material: Material?
init() {
time = 0
point = double4()
normal = double4()
u = 0.0
v = 0.0
}
init(_ t: Double, _ p: double4, _ n: double4, u newU: Double = 0.0, v newV: Double = 0.0) {
time = t
point = p
normal = n
u = newU
v = newV
}
}
public class Traceable {
public func trace(r: Ray, minimumT tMin: Double, maximumT tMax: Double) -> HitRecord? {
fatalError("trace() must be overridden")
}
public func boundingBox(t0: Double, t1: Double) -> AABB? {
fatalError("boundingBox() must be overridden")
}
}
| 3901606c5fe3f3fd3164eecc1d257691 | 17.454545 | 92 | 0.635468 | false | false | false | false |
iWeslie/Ant | refs/heads/master | Ant/Ant/LunTan/SendOutVC/Photo/PicPickerViewCell.swift | apache-2.0 | 2 |
//
// PicPickerViewCell.swift
// Ant
//
// Created by LiuXinQiang on 2017/7/12.
// Copyright © 2017年 LiuXinQiang. All rights reserved.
//
import UIKit
class PicPickerViewCell: UICollectionViewCell {
//MARK: - 控件的属性
@IBOutlet weak var addPhotoBtn: UIButton!
@IBOutlet weak var removePhotoBtn: UIButton!
@IBOutlet weak var imageView: UIImageView!
// MARK:- 定义属性
var image : UIImage? {
didSet {
if image != nil {
imageView.image = image
addPhotoBtn.isUserInteractionEnabled = false
removePhotoBtn.isHidden = false
} else {
imageView.image = nil
addPhotoBtn.isUserInteractionEnabled = true
removePhotoBtn.isHidden = true
}
}
}
// 事件监听
@IBAction func addPhotoClick(_ sender: Any) {
print("addPhotoClic")
NotificationCenter.default.post(name: PicPickerAddPhotoNote , object: nil)
}
@IBAction func removePhotoClick(_ sender: Any) {
NotificationCenter.default.post(name: PicPickerRemovePhotoNote, object: sender)
}
}
| 6c4d8ccde423dab48211c341f3062aa2 | 23.520833 | 87 | 0.593883 | false | false | false | false |
AxziplinLib/TabNavigations | refs/heads/master | TabNavigations/Classes/Generals/ViewControllers/TableViewController.swift | apache-2.0 | 1 | //
// TableViewController.swift
// AxReminder
//
// Created by devedbox on 2017/6/28.
// Copyright © 2017年 devedbox. All rights reserved.
//
import UIKit
class TableViewController: UITableViewController {
fileprivate lazy var _backgroundFilterView: UIView = UIView()
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
viewDidLoadSetup()
print(String(describing: type(of: self)) + " " + #function)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
_backgroundFilterView.frame = CGRect(x: 0.0, y: min(0.0, tableView.contentOffset.y), width: tabNavigationController?.tabNavigationBar.bounds.width ?? 0.0, height: tabNavigationController?.tabNavigationBar.bounds.height ?? 0.0)
}
public func viewDidLoadSetup() {
tableView.insertSubview(_backgroundFilterView, at: 0)
_backgroundFilterView.backgroundColor = .white
tabNavigationController?.tabNavigationBar.isTranslucent = true
}
#if swift(>=4.0)
#else
override func viewWillBeginInteractiveTransition() {
print(String(describing: type(of: self)) + " " + #function)
}
override func viewDidEndInteractiveTransition(appearing: Bool) {
print(String(describing: type(of: self)) + " " + #function + " " + String(describing: appearing))
}
#endif
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
print(String(describing: type(of: self)) + " " + #function + " " + String(describing: animated))
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
print(String(describing: type(of: self)) + " " + #function + " " + String(describing: animated))
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
print(String(describing: type(of: self)) + " " + #function + " " + String(describing: animated))
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
print(String(describing: type(of: self)) + " " + #function + " " + String(describing: animated))
}
deinit {
print(String(describing: type(of: self)) + " " + #function)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
// MARK: - UITableViewDelegate.
extension TableViewController {
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 20.0
}
override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 10.0
}
}
// MARK: - Status Bar Supporting.
extension TableViewController {
override var prefersStatusBarHidden: Bool { return true }
override var preferredStatusBarUpdateAnimation: UIStatusBarAnimation { return .fade }
}
| f1eadb61bfef15eb48f942ec8e965567 | 34.831579 | 234 | 0.658637 | false | false | false | false |
iyubinest/Encicla | refs/heads/master | encicla/location/Location.swift | mit | 1 | import CoreLocation
import RxSwift
protocol GPS {
func locate() -> Observable<CLLocation>
}
class DefaultGPS: NSObject, GPS, CLLocationManagerDelegate {
private var observer: AnyObserver<CLLocation>?
internal func locate() -> Observable<CLLocation> {
return Observable.create {
observer in
self.observer = observer
let locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
return Disposables.create { locationManager.delegate = nil }
}
}
internal func locationManager(_ manager: CLLocationManager,
didUpdateLocations locations: Array<CLLocation>) {
observer?.on(.next(locations.first!))
observer?.on(.completed)
}
internal func locationManager(_ manager: CLLocationManager,
didChangeAuthorization status: CLAuthorizationStatus) {
if status == .authorizedWhenInUse || status == .authorizedAlways {
manager.startUpdatingLocation()
} else if status == .denied {
observer?.on(.error(CLError(.denied)))
}
}
}
| d4060bfce3e94d342d8df4dbd07e3ce1 | 28.027027 | 70 | 0.716946 | false | false | false | false |
TG908/iOS | refs/heads/master | TUM Campus App/SearchViewController.swift | gpl-3.0 | 1 | //
// SearchViewController.swift
// TUM Campus App
//
// Created by Mathias Quintero on 10/28/15.
// Copyright © 2015 LS1 TUM. All rights reserved.
//
import UIKit
class SearchViewController: UITableViewController, DetailView {
@IBOutlet weak var searchTextField: UITextField! {
didSet {
searchTextField.delegate = self
}
}
var delegate: DetailViewDelegate?
var elements = [DataElement]()
var currentElement: DataElement?
var searchManagers: [TumDataItems]?
}
extension SearchViewController: DetailViewDelegate {
func dataManager() -> TumDataManager {
return delegate?.dataManager() ?? TumDataManager(user: nil)
}
}
extension SearchViewController: TumDataReceiver, ImageDownloadSubscriber {
func receiveData(_ data: [DataElement]) {
elements = data
for element in elements {
if let downloader = element as? ImageDownloader {
downloader.subscribeToImage(self)
}
}
tableView.reloadData()
}
func updateImageView() {
tableView.reloadData()
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
extension SearchViewController: UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if string != " " {
for element in elements {
if let downloader = element as? ImageDownloader {
downloader.clearSubscribers()
}
}
let replaced = NSString(string: textField.text ?? "").replacingCharacters(in: range, with: string)
if replaced != "" {
delegate?.dataManager().search(self, query: replaced, searchIn: searchManagers) // searchManager might be set during a segue. Otherwise it defaults to all searchManagers, defined in the TumDataManager
} else {
elements = []
tableView.reloadData()
}
}
return true
}
}
extension SearchViewController {
override func viewDidLoad() {
searchTextField.becomeFirstResponder()
tableView.tableFooterView = UIView(frame: CGRect.zero)
tableView.estimatedRowHeight = tableView.rowHeight
tableView.rowHeight = 102
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
searchTextField.resignFirstResponder()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if var mvc = segue.destination as? DetailView {
mvc.delegate = self
}
if let mvc = segue.destination as? RoomFinderViewController {
mvc.room = currentElement
}
if let mvc = segue.destination as? PersonDetailTableViewController {
mvc.user = currentElement
}
if let mvc = segue.destination as? LectureDetailsTableViewController {
mvc.lecture = currentElement
}
}
}
extension SearchViewController {
override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
currentElement = elements[indexPath.row]
return indexPath
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return elements.count
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: elements[indexPath.row].getCellIdentifier()) as? CardTableViewCell ?? CardTableViewCell()
cell.setElement(elements[indexPath.row])
return cell
}
}
| 8a06d2df76227a079d1045745de2712b | 29.074627 | 216 | 0.634491 | false | false | false | false |
epv44/TwitchAPIWrapper | refs/heads/master | Sources/TwitchAPIWrapper/Models/CodeStatus.swift | mit | 1 | //
// CodeStatus.swift
// TwitchAPIWrapper
//
// Created by Eric Vennaro on 5/8/21.
//
import Foundation
/// Code status response: https://dev.twitch.tv/docs/api/reference/#get-code-status
public struct CodeStatusResponse: Codable {
public let codeStatuses: [CodeStatus]
private enum CodingKeys: String, CodingKey {
case codeStatuses = "data"
}
}
/// Code status options mirroring: https://dev.twitch.tv/docs/api/reference/#get-code-status
public enum CodeSuccessStatus: String, Codable {
case successfullyRedeemed = "SUCCESSFULLY_REDEEMED"
case alreadyClaimed = "ALREADY_CLAIMED"
case expired = "EXPIRED"
case userNotEligible = "USER_NOT_ELIGIBLE"
case notFound = "NOT_FOUND"
case inactive = "INACTIVE"
case unused = "UNUSED"
case incorrectFormat = "INCORRECT_FORMAT"
case internalError = "INTERNAL_ERROR"
}
/// Code status object returned from the server as part of the `CodeStatusResponse` https://dev.twitch.tv/docs/api/reference/#get-code-status
public struct CodeStatus: Codable, Equatable {
public let code: String
public let status: CodeSuccessStatus
}
| ea9b4e86595a54ce1602052e88c9ea5e | 30.472222 | 141 | 0.72286 | false | false | false | false |
hayasilin/Crack-the-term | refs/heads/master | SignUpViewController.swift | mit | 1 | //
// SignUpViewController.swift
// CrackTheTerm_review
//
// Created by Kuan-Wei Lin on 8/20/15.
// Copyright (c) 2015 Kuan-Wei Lin. All rights reserved.
//
import UIKit
class SignUpViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextFieldDelegate {
@IBOutlet weak var usernameTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var signUpBtn: UIButton!
@IBAction func signUp(sender: UIButton) {
signUp()
}
func signUp(){
let user = PFUser();
user.username = usernameTextField.text
user.password = passwordTextField.text
user.email = emailTextField.text
user.signUpInBackgroundWithBlock({
(success: Bool, error: NSError?) -> Void in
if error == nil{
print("Sign up successfully")
//UIImagePickerController section
let imagePicker: UIImagePickerController = UIImagePickerController()
imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
imagePicker.delegate = self
self.presentViewController(imagePicker, animated: true, completion: nil)
let successAlertController: UIAlertController = UIAlertController(title: "註冊成功", message: "您已經成功註冊,請按下確定選擇大頭圖像", preferredStyle: UIAlertControllerStyle.Alert)
let alertAction: UIAlertAction = UIAlertAction(title: "開始選擇大頭圖像", style: UIAlertActionStyle.Default, handler: nil)
successAlertController.addAction(alertAction)
self.presentViewController(successAlertController, animated: true, completion: nil)
}else{
print("Sign up failed")
print(error?.localizedDescription)
let failAlertController: UIAlertController = UIAlertController(title: "註冊失敗", message: "該帳號已經有人使用了,請重新輸入", preferredStyle: UIAlertControllerStyle.Alert)
let alertAction: UIAlertAction = UIAlertAction(title: "我知道了", style: UIAlertActionStyle.Default, handler: nil)
failAlertController.addAction(alertAction)
self.presentViewController(failAlertController, animated: true, completion: nil)
}
})
}
//Sign Up image function
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
let pickedImage: UIImage = info[UIImagePickerControllerOriginalImage] as! UIImage;
//SCale down image
let scaledImage = self.scaleImageWith(pickedImage, and: CGSizeMake(80, 80))
let imageData = UIImagePNGRepresentation(scaledImage)
let imageFile: PFFile = PFFile(data: imageData!)
PFUser.currentUser()?.setObject(imageFile, forKey: "profileImage")
PFUser.currentUser()?.save()
picker.dismissViewControllerAnimated(true, completion: nil)
dispatch_async(dispatch_get_main_queue()){
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let timelineViewController: UINavigationController = storyboard.instantiateViewControllerWithIdentifier("timelineVC") as! UINavigationController
self.presentViewController(timelineViewController, animated: true, completion: nil)
}
}
func scaleImageWith(image: UIImage, and newSize: CGSize) -> UIImage{
UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
image.drawInRect(CGRectMake(0, 0, newSize.width, newSize.height))
let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
override func viewDidLoad() {
super.viewDidLoad()
signUpBtn.layer.cornerRadius = 5
usernameTextField.delegate = self
passwordTextField.delegate = self
emailTextField.delegate = self
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
view.endEditing(true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 728665adac4f1a292c7ba0820a7fdf89 | 39.637168 | 174 | 0.660061 | false | false | false | false |
iCrany/iOSExample | refs/heads/master | iOSExample/Module/NetworkExample/NetworkTableViewVC.swift | mit | 1 | //
// NetworkTableViewVC.swift
// iOSExample
//
// Created by iCrany on 2018/5/24.
// Copyright © 2018年 iCrany. All rights reserved.
//
import Foundation
class NetworkTableViewVC: UIViewController {
struct Constant {
static let kDemo1: String = "Http header Example"
}
private lazy var tableView: UITableView = {
let tableView = UITableView.init(frame: .zero, style: .plain)
tableView.tableFooterView = UIView.init()
tableView.delegate = self
tableView.dataSource = self
return tableView
}()
fileprivate var dataSource: [String] = []
init() {
super.init(nibName: nil, bundle: nil)
self.prepareDataSource()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Network Example"
self.setupUI()
}
private func setupUI() {
self.view.addSubview(self.tableView)
self.tableView.snp.makeConstraints { maker in
maker.edges.equalTo(self.view)
}
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: NSStringFromClass(UITableViewCell.self))
}
private func prepareDataSource() {
self.dataSource.append(Constant.kDemo1)
}
}
extension NetworkTableViewVC: UITableViewDelegate {
public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 60
}
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let selectedDataSourceStr = self.dataSource[indexPath.row]
switch selectedDataSourceStr {
case Constant.kDemo1:
let vc: HttpHeaderExampleVC = HttpHeaderExampleVC()
self.navigationController?.pushViewController(vc, animated: true)
default:
break
}
}
}
extension NetworkTableViewVC: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.dataSource.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let dataSourceStr: String = self.dataSource[indexPath.row]
let tableViewCell: UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(UITableViewCell.self))
if let cell = tableViewCell {
cell.textLabel?.text = dataSourceStr
cell.textLabel?.textColor = UIColor.black
return cell
} else {
return UITableViewCell.init(style: .default, reuseIdentifier: "error")
}
}
}
| 23dcf9cdec9f721f4d5ecf2590564339 | 28.430108 | 132 | 0.663135 | false | false | false | false |
webventil/Kroekln | refs/heads/master | Kroekln/Kroekln/MainTableViewController.swift | mit | 1 | //
// MainTableViewController.swift
// Kroekln
//
// Created by Arne Tempelhof on 07.11.14.
// Copyright (c) 2014 webventil. All rights reserved.
//
import UIKit
class MainTableViewController: UITableViewController {
var headerView: UIView!
var headerViewMaskLayer: CAShapeLayer!
var player: Player?
let kTableHeaderHeight: CGFloat = 270.0
@IBOutlet weak var avatarBlurImage: UIImageView!
@IBOutlet weak var avatar: UIButton!
@IBOutlet weak var userName: UILabel!
@IBOutlet weak var totalLabel: UILabel!
@IBOutlet weak var winLabel: UILabel!
@IBOutlet weak var losesLabel: UILabel!
@IBOutlet weak var totalCount: UILabel!
@IBOutlet weak var winCount: UILabel!
@IBOutlet weak var losesCount: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
tableView.rowHeight = UITableViewAutomaticDimension
headerView = tableView.tableHeaderView
tableView.tableHeaderView = nil
tableView.addSubview(headerView)
tableView.contentInset = UIEdgeInsets(top: kTableHeaderHeight, left: 0, bottom: 0, right: 0)
tableView.contentOffset = CGPoint(x: 0, y: -kTableHeaderHeight)
updateHeaderView()
avatar.layer.cornerRadius = 10.0
avatar.layer.borderWidth = 3.0
avatar.layer.borderColor = UIColor.whiteColor().CGColor
avatar.layer.masksToBounds = false
avatar.clipsToBounds = true
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
func updatePlayer() {
player = DatabaseManager.shared().getPlayer()
if let userAvatar = player?.avatar {
avatar.setImage(UIImage(data: userAvatar), forState: UIControlState.Normal)
var blurredImage = UIImage(data: userAvatar)?.applyLightEffect()
avatarBlurImage.image = blurredImage
}
if let name = player?.name {
userName.text = "Hallo \(name)!"
}
}
func updateHeaderView(){
var headerRect = CGRect(x: 0, y: -kTableHeaderHeight, width: tableView.bounds.width, height: kTableHeaderHeight)
if tableView.contentOffset.y < -kTableHeaderHeight {
headerRect.origin.y = tableView.contentOffset.y
headerRect.size.height = -tableView.contentOffset.y
}
headerView.frame = headerRect
}
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
coordinator.animateAlongsideTransition({ (context) -> Void in
[self]
self.updateHeaderView()
self.tableView.reloadData()
}, completion: { (context) -> Void in
})
}
override func scrollViewDidScroll(scrollView: UIScrollView) {
updateHeaderView()
}
override func viewWillAppear(animated: Bool) {
navigationController?.setNavigationBarHidden(true, animated: false)
updatePlayer()
}
override func viewWillDisappear(animated: Bool) {
navigationController?.setNavigationBarHidden(false, animated: true)
}
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 Potentially incomplete method implementation.
// Return the number of sections.
return 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return 0
}
/*
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as UITableViewCell
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO 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 NO 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.
}
*/
}
| 4e2af6ec2c9c2a1450c0441705e33d35 | 33.091954 | 156 | 0.696224 | false | false | false | false |
lyft/SwiftLint | refs/heads/master | Source/SwiftLintFramework/Rules/LargeTupleRule.swift | mit | 1 | import Foundation
import SourceKittenFramework
private enum LargeTupleRuleError: Error {
case unbalencedParentheses
}
private enum RangeKind {
case tuple
case generic
}
public struct LargeTupleRule: ASTRule, ConfigurationProviderRule {
public var configuration = SeverityLevelsConfiguration(warning: 2, error: 3)
public init() {}
public static let description = RuleDescription(
identifier: "large_tuple",
name: "Large Tuple",
description: "Tuples shouldn't have too many members. Create a custom type instead.",
kind: .metrics,
nonTriggeringExamples: [
"let foo: (Int, Int)\n",
"let foo: (start: Int, end: Int)\n",
"let foo: (Int, (Int, String))\n",
"func foo() -> (Int, Int)\n",
"func foo() -> (Int, Int) {}\n",
"func foo(bar: String) -> (Int, Int)\n",
"func foo(bar: String) -> (Int, Int) {}\n",
"func foo() throws -> (Int, Int)\n",
"func foo() throws -> (Int, Int) {}\n",
"let foo: (Int, Int, Int) -> Void\n",
"let foo: (Int, Int, Int) throws -> Void\n",
"func foo(bar: (Int, String, Float) -> Void)\n",
"func foo(bar: (Int, String, Float) throws -> Void)\n",
"var completionHandler: ((_ data: Data?, _ resp: URLResponse?, _ e: NSError?) -> Void)!\n",
"func getDictionaryAndInt() -> (Dictionary<Int, String>, Int)?\n",
"func getGenericTypeAndInt() -> (Type<Int, String, Float>, Int)?\n"
],
triggeringExamples: [
"↓let foo: (Int, Int, Int)\n",
"↓let foo: (start: Int, end: Int, value: String)\n",
"↓let foo: (Int, (Int, Int, Int))\n",
"func foo(↓bar: (Int, Int, Int))\n",
"func foo() -> ↓(Int, Int, Int)\n",
"func foo() -> ↓(Int, Int, Int) {}\n",
"func foo(bar: String) -> ↓(Int, Int, Int)\n",
"func foo(bar: String) -> ↓(Int, Int, Int) {}\n",
"func foo() throws -> ↓(Int, Int, Int)\n",
"func foo() throws -> ↓(Int, Int, Int) {}\n",
"func foo() throws -> ↓(Int, ↓(String, String, String), Int) {}\n",
"func getDictionaryAndInt() -> (Dictionary<Int, ↓(String, String, String)>, Int)?\n"
]
)
public func validate(file: File, kind: SwiftDeclarationKind,
dictionary: [String: SourceKitRepresentable]) -> [StyleViolation] {
let offsets = violationOffsetsForTypes(in: file, dictionary: dictionary, kind: kind) +
violationOffsetsForFunctions(in: file, dictionary: dictionary, kind: kind)
return offsets.compactMap { location, size in
for parameter in configuration.params where size > parameter.value {
let reason = "Tuples should have at most \(configuration.warning) members."
return StyleViolation(ruleDescription: type(of: self).description,
severity: parameter.severity,
location: Location(file: file, byteOffset: location),
reason: reason)
}
return nil
}
}
private func violationOffsetsForTypes(in file: File, dictionary: [String: SourceKitRepresentable],
kind: SwiftDeclarationKind) -> [(offset: Int, size: Int)] {
let kinds = SwiftDeclarationKind.variableKinds.subtracting([.varLocal])
guard kinds.contains(kind),
let type = dictionary.typeName,
let offset = dictionary.offset else {
return []
}
let sizes = violationOffsets(for: type).map { $0.1 }
return sizes.max().flatMap { [(offset: offset, size: $0)] } ?? []
}
private func violationOffsetsForFunctions(in file: File, dictionary: [String: SourceKitRepresentable],
kind: SwiftDeclarationKind) -> [(offset: Int, size: Int)] {
let contents = file.contents.bridge()
guard SwiftDeclarationKind.functionKinds.contains(kind),
let returnRange = returnRangeForFunction(dictionary: dictionary),
let returnSubstring = contents.substringWithByteRange(start: returnRange.location,
length: returnRange.length) else {
return []
}
let offsets = violationOffsets(for: returnSubstring, initialOffset: returnRange.location)
return offsets.sorted { $0.offset < $1.offset }
}
private func violationOffsets(for text: String, initialOffset: Int = 0) -> [(offset: Int, size: Int)] {
guard let ranges = try? parenthesesRanges(in: text) else {
return []
}
var text = text.bridge()
var offsets = [(offset: Int, size: Int)]()
for (range, kind) in ranges {
let substring = text.substring(with: range)
if kind != .generic,
let byteRange = text.NSRangeToByteRange(start: range.location, length: range.length),
!containsReturnArrow(in: text.bridge(), range: range) {
let size = substring.components(separatedBy: ",").count
let offset = byteRange.location + initialOffset
offsets.append((offset: offset, size: size))
}
let replacement = String(repeating: " ", count: substring.bridge().length)
text = text.replacingCharacters(in: range, with: replacement).bridge()
}
return offsets
}
private func returnRangeForFunction(dictionary: [String: SourceKitRepresentable]) -> NSRange? {
guard let nameOffset = dictionary.nameOffset,
let nameLength = dictionary.nameLength,
let length = dictionary.length,
let offset = dictionary.offset else {
return nil
}
let start = nameOffset + nameLength
let end = dictionary.bodyOffset ?? length + offset
guard end - start > 0 else {
return nil
}
return NSRange(location: start, length: end - start)
}
private func parenthesesRanges(in text: String) throws -> [(NSRange, RangeKind)] {
var stack = [(Int, String)]()
var balanced = true
var ranges = [(NSRange, RangeKind)]()
let nsText = text.bridge()
let parenthesesAndAngleBrackets = CharacterSet(charactersIn: "()<>")
var index = 0
let length = nsText.length
while balanced {
let searchRange = NSRange(location: index, length: length - index)
let range = nsText.rangeOfCharacter(from: parenthesesAndAngleBrackets,
options: [.literal], range: searchRange)
if range.location == NSNotFound {
break
}
index = NSMaxRange(range)
let symbol = nsText.substring(with: range)
// skip return arrows
if symbol == ">",
case let arrowRange = nsText.range(of: "->", options: [.literal], range: searchRange),
arrowRange.intersects(range) {
continue
}
if symbol == "(" || symbol == "<" {
stack.append((range.location, symbol))
} else if let (startIdx, previousSymbol) = stack.popLast(),
isBalanced(currentSymbol: symbol, previousSymbol: previousSymbol) {
let range = NSRange(location: startIdx, length: range.location - startIdx + 1)
let kind: RangeKind = symbol == ")" ? .tuple : .generic
ranges.append((range, kind))
} else {
balanced = false
}
}
guard balanced && stack.isEmpty else {
throw LargeTupleRuleError.unbalencedParentheses
}
return ranges
}
private func isBalanced(currentSymbol: String, previousSymbol: String) -> Bool {
return (currentSymbol == ")" && previousSymbol == "(") ||
(currentSymbol == ">" && previousSymbol == "<")
}
private func containsReturnArrow(in text: String, range: NSRange) -> Bool {
let arrowRegex = regex("\\A(?:\\s*throws)?\\s*->")
let start = NSMaxRange(range)
let restOfStringRange = NSRange(location: start, length: text.bridge().length - start)
return arrowRegex.firstMatch(in: text, options: [], range: restOfStringRange) != nil
}
}
| 2bc59ad4089913c0835ea42b0e7cd2ff | 40.370192 | 107 | 0.554794 | false | false | false | false |
CNKCQ/oschina | refs/heads/master | OSCHINA/Extensions/UIViewController+Preparation.swift | mit | 1 | //
// UIViewController+Preparation.swift
// OSCHINA
//
// Created by KingCQ on 2017/3/31.
// Copyright © 2017年 KingCQ. All rights reserved.
//
private func swizzle(_ cls: UIViewController.Type) {
[
(#selector(cls.viewDidLoad), #selector(cls.os_viewDidLoad)),
(#selector(cls.viewWillAppear(_:)), #selector(cls.os_viewWillAppear(_:)))
].forEach { original, swizzled in
let originalMethod = class_getInstanceMethod(cls, original)
let swizzledMethod = class_getInstanceMethod(cls, swizzled)
let didAddswizzledMethod = class_addMethod(cls, original, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod))
if didAddswizzledMethod {
class_replaceMethod(cls, swizzled, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod))
} else {
method_exchangeImplementations(originalMethod, swizzledMethod)
}
}
}
extension UIViewController {
open override class func initialize() {
guard self === UIViewController.self else { return }
swizzle(self)
}
internal func os_viewDidLoad() {
os_viewDidLoad()
print("你好,\(#function)")
}
internal func os_viewWillAppear(_ animated: Bool) {
os_viewWillAppear(animated)
print("你好,\(#function)")
}
}
| eb2732c5091a454ccb688d12e44a7240 | 32 | 147 | 0.669623 | false | false | false | false |
SRandazzo/Moya | refs/heads/master | Source/Response.swift | mit | 1 | import Foundation
public final class Response: CustomDebugStringConvertible, Equatable {
public let statusCode: Int
public let data: NSData
public let response: NSURLResponse?
public init(statusCode: Int, data: NSData, response: NSURLResponse? = nil) {
self.statusCode = statusCode
self.data = data
self.response = response
}
public var description: String {
return "Status Code: \(statusCode), Data Length: \(data.length)"
}
public var debugDescription: String {
return description
}
}
public func ==(lhs: Response, rhs: Response) -> Bool {
return lhs.statusCode == rhs.statusCode
&& lhs.data == rhs.data
&& lhs.response == rhs.response
}
public extension Response {
/// Filters out responses that don't fall within the given range, generating errors when others are encountered.
public func filterStatusCodes(range: ClosedInterval<Int>) throws -> Response {
guard range.contains(statusCode) else {
throw Error.StatusCode(self)
}
return self
}
public func filterStatusCode(code: Int) throws -> Response {
return try filterStatusCodes(code...code)
}
public func filterSuccessfulStatusCodes() throws -> Response {
return try filterStatusCodes(200...299)
}
public func filterSuccessfulStatusAndRedirectCodes() throws -> Response {
return try filterStatusCodes(200...399)
}
/// Maps data received from the signal into a UIImage.
func mapImage() throws -> Image {
guard let image = Image(data: data) else {
throw Error.ImageMapping(self)
}
return image
}
/// Maps data received from the signal into a JSON object.
func mapJSON() throws -> AnyObject {
do {
return try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments)
} catch {
throw Error.Underlying(error)
}
}
/// Maps data received from the signal into a String.
func mapString() throws -> String {
guard let string = NSString(data: data, encoding: NSUTF8StringEncoding) else {
throw Error.StringMapping(self)
}
return string as String
}
}
/// Required for making Endpoint conform to Equatable.
public func ==<T>(lhs: Endpoint<T>, rhs: Endpoint<T>) -> Bool {
return lhs.urlRequest.isEqual(rhs.urlRequest)
}
/// Required for using Endpoint as a key type in a Dictionary.
extension Endpoint: Equatable, Hashable {
public var hashValue: Int {
return urlRequest.hash
}
}
| 1f63c8c28a5b9dc46f65fc6685f03d4f | 29.103448 | 116 | 0.651394 | false | false | false | false |
downie/swift-daily-programmer | refs/heads/master | SwiftDailyChallenge.playground/Pages/267 - Places.xcplaygroundpage/Contents.swift | mit | 1 | /*:
# [2016-05-16] Challenge #267 [Easy] All the places your dog didn't win
Published on: 2016-05-16\
Difficulty: Easy\
[reddit link](https://www.reddit.com/r/dailyprogrammer/comments/4jom3a/20160516_challenge_267_easy_all_the_places_your/)
*/
func suffix(place : Int) -> String {
switch place {
case 11, 12, 13:
// These are the weird little exceptions.
return "th"
case 0..<100 where place % 10 == 1:
return "st"
case 0..<100 where place % 10 == 2:
return "nd"
case 0..<100 where place % 10 == 3:
return "rd"
case place where place >= 100:
return suffix(place-100)
default:
// This is by far the most common
return "th"
}
}
func namePlace(place: Int) -> String {
return "\(place)\(suffix(place))"
}
func allPlaces(to to: Int, from: Int = 1, except : Int? = nil) -> String {
var range = Array(from...to)
if let exceptPlace = except {
range = range.filter { $0 != exceptPlace }
}
return range.map(namePlace).joinWithSeparator(", ")
}
// Testing
allPlaces(to: 10) == "1st, 2nd, 3rd, 4th, 5th, 6th, 7th, 8th, 9th, 10th"
allPlaces(to: 10, except: 3) == "1st, 2nd, 4th, 5th, 6th, 7th, 8th, 9th, 10th"
allPlaces(to: 20, from: 10) == "10th, 11th, 12th, 13th, 14th, 15th, 16th, 17th, 18th, 19th, 20th"
allPlaces(to: 110, from: 100) == "100th, 101st, 102nd, 103rd, 104th, 105th, 106th, 107th, 108th, 109th, 110th"
allPlaces(to: 116, from: 110, except: 115) == "110th, 111th, 112th, 113th, 114th, 116th"
//: [Table of Contents](Table%20of%20Contents)
| 1085919180ad126f06129b3200afb64e | 30.72 | 121 | 0.611602 | false | false | false | false |
anyflow/Jonsnow | refs/heads/master | Jonsnow/ViewController/ChattingTableViewController.swift | apache-2.0 | 1 | //
// ChattingTableViewController.swift
// Jonsnow
//
// Created by Park Hyunjeong on 12/15/15.
// Copyright © 2015 Anyflow. All rights reserved.
//
import UIKit
class ChattingTableViewController: UITableViewController {
let logger: Logger = Logger(className: ChattingTableViewController.self.description())
override func viewDidLoad() {
super.viewDidLoad()
self.clearsSelectionOnViewWillAppear = false
self.navigationItem.leftBarButtonItem = self.editButtonItem()
self.navigationItem.leftBarButtonItem?.tintColor = UIColor.whiteColor()
}
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.
}
*/
}
| 645f7b86f36cbdb3dd7bbadf9724ea7a | 32.863158 | 157 | 0.689462 | false | false | false | false |
juliangrosshauser/MapsPlayground | refs/heads/master | Maps.playground/Contents.swift | mit | 1 | import CoreLocation
import MapKit
import XCPlayground
/*:
# Get current location
Based on Apple's ["Getting the User’s Location"](https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/LocationAwarenessPG/CoreLocation/CoreLocation.html#//apple_ref/doc/uid/TP40009497-CH2-SW1)
*/
class LocationManager: NSObject, CLLocationManagerDelegate {
let locationManager = CLLocationManager()
var currentLocation: CLLocation?
override init() {
super.init()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyKilometer
locationManager.distanceFilter = 500
locationManager.startUpdatingLocation()
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [AnyObject]) {
let location = locations.last as! CLLocation
let eventDate = location.timestamp
let timeSinceEvent = eventDate.timeIntervalSinceNow
if abs(timeSinceEvent) < 15 {
print("Current location: latitude = \(location.coordinate.latitude), longitude = \(location.coordinate.longitude)")
currentLocation = location
}
}
}
let locationManager = LocationManager()
/*:
# Display location in map view
Based on Apple's ["Displaying Maps"](https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/LocationAwarenessPG/MapKit/MapKit.html#//apple_ref/doc/uid/TP40009497-CH3-SW1)
*/
let mapView = MKMapView(frame: CGRect(x: 0, y: 0, width: 500, height: 500))
// show New York in map view
mapView.region = MKCoordinateRegionMakeWithDistance(CLLocationCoordinate2D(latitude: 40.7141667, longitude: -74.0063889), 5000, 5000)
XCPShowView("Map View", view: mapView)
| 59c3dbd1019e3611c75792866ee9fe8d | 34.12 | 219 | 0.735763 | false | false | false | false |
everald/JetPack | refs/heads/master | Sources/Extensions/Foundation/String+Foundation.swift | mit | 1 | import Foundation
public extension String {
public func firstMatchForRegularExpression(_ regularExpression: NSRegularExpression) -> [Substring?]? {
guard let match = regularExpression.firstMatch(in: self, options: [], range: NSMakeRange(0, utf16.count)) else {
return nil
}
return (0 ..< match.numberOfRanges).map { match.range(at: $0).rangeInString(self).map { self[$0] } }
}
public func firstMatchForRegularExpression(_ regularExpressionPattern: String) -> [Substring?]? {
do {
let regularExpression = try NSRegularExpression(pattern: regularExpressionPattern, options: [])
return firstMatchForRegularExpression(regularExpression)
}
catch let error {
fatalError("Invalid regular expression pattern: \(error)")
}
}
public func firstSubstringMatchingRegularExpression(_ regularExpressionPattern: String) -> Substring? {
if let range = range(of: regularExpressionPattern, options: .regularExpression) {
return self[range]
}
return nil
}
public func stringByReplacingRegularExpression(_ regularExpression: NSRegularExpression, withTemplate template: String) -> String {
return regularExpression.stringByReplacingMatches(in: self, options: [], range: NSMakeRange(0, utf16.count), withTemplate: template)
}
public func stringByReplacingRegularExpression(_ regularExpressionPattern: String, withTemplate template: String) -> String {
do {
let regularExpression = try NSRegularExpression(pattern: regularExpressionPattern, options: NSRegularExpression.Options.dotMatchesLineSeparators)
return stringByReplacingRegularExpression(regularExpression, withTemplate: template)
}
catch let error {
fatalError("Invalid regular expression pattern: \(error)")
}
}
public var urlEncodedHost: String {
var allowedCharacters = CharacterSet.urlHostAllowed
allowedCharacters.insert(":") // https://bugs.swift.org/projects/SR/issues/SR-5397
return addingPercentEncoding(withAllowedCharacters: allowedCharacters) ?? "<url encoding failed>"
}
public var urlEncodedPath: String {
var allowedCharacters = CharacterSet.urlPathAllowed
allowedCharacters.insert(":") // https://bugs.swift.org/projects/SR/issues/SR-5397
return addingPercentEncoding(withAllowedCharacters: allowedCharacters) ?? "<url encoding failed>"
}
public var urlEncodedPathComponent: String {
return addingPercentEncoding(withAllowedCharacters: CharacterSet.URLPathComponentAllowedCharacterSet()) ?? "<url encoding failed>"
}
public var urlEncodedQuery: String {
return addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) ?? "<url encoding failed>"
}
public var urlEncodedQueryParameter: String {
return addingPercentEncoding(withAllowedCharacters: CharacterSet.URLQueryParameterAllowedCharacterSet()) ?? "<url encoding failed>"
}
}
| 43d8b109af1813f592cf34425ff8dd7f | 34.1875 | 148 | 0.776909 | false | false | false | false |
ismailgulek/IGPagerView | refs/heads/master | IGPagerViewDemo/ViewController.swift | mit | 1 | //
// ViewController.swift
// IGPagerViewDemo
//
// Created by Ismail GULEK on 19/03/2017.
// Copyright © 2017 Ismail Gulek. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var pagerView: IGPagerView! {
didSet {
pagerView.dataSource = self
pagerView.delegate = self
}
}
@IBOutlet weak var segmentedControl: UISegmentedControl!
@IBAction func segmentedControlValueChanged(_ sender: UISegmentedControl) {
pagerView.goToPage(sender.selectedSegmentIndex)
}
}
extension ViewController: IGPagerViewDataSource {
func pagerViewNumberOfPages(_ pager: IGPagerView) -> Int {
return 3
}
func pagerView(_ pager: IGPagerView, viewAt index: Int) -> UIView {
if index == 0 {
let view = UIView()
view.backgroundColor = UIColor.red
return view
} else if index == 1 {
let view = UIView()
view.backgroundColor = UIColor.green
return view
} else {
let view = UIView()
view.backgroundColor = UIColor.blue
return view
}
}
}
extension ViewController: IGPagerViewDelegate {
func pagerView(_ pager: IGPagerView, didScrollToPageAt index: Int) {
print("Index: \(index)")
segmentedControl.selectedSegmentIndex = index
}
}
| dcbeacaedfce66143d07db30c37e97bc | 20.438596 | 76 | 0.713584 | false | false | false | false |
arbitur/Func | refs/heads/master | source/UI/Dialogs/SheetDialog.swift | mit | 1 | //
// SheetDialog.swift
// Pods
//
// Created by Philip Fryklund on 24/Apr/17.
//
//
import UIKit
public typealias SheetDialog = SheetDialogController // For backwards compatibility
open class SheetDialogController: ActionDialogController {
private let contentStackView = UIStackView(axis: .vertical)
open override var contentView: UIView { return contentStackView }
fileprivate var cancelActionView: UIView?
override open class func makeTitleLabel() -> UILabel {
let font = UIFont.boldSystemFont(ofSize: 13)
let color = UIColor(white: 0.56, alpha: 1)
return UILabel(font: font , color: color, alignment: .center, lines: 0)
}
override open class func makeSubtitleLabel() -> UILabel {
let font = UIFont.systemFont(ofSize: 13)
let color = UIColor(white: 0.56, alpha: 1)
return UILabel(font: font, color: color, alignment: .center, lines: 0)
}
open override class func makeActionButton(for type: DialogActionType) -> UIButton {
let color: UIColor
let font: UIFont
switch type {
case .normal: color = UIColor(red: 0.0, green: 0.48, blue: 1.00, alpha: 1.0) ; font = UIFont.systemFont(ofSize: 20)
case .delete: color = UIColor(red: 1.0, green: 0.23, blue: 0.19, alpha: 1.0) ; font = UIFont.systemFont(ofSize: 20)
case .cancel: color = UIColor(red: 0.0, green: 0.48, blue: 1.00, alpha: 1.0) ; font = UIFont.boldSystemFont(ofSize: 20)
}
let button = UIButton(type: .system)
button.setTitleColor(color, for: .normal)
button.titleLabel!.font = font
button.titleLabel!.textAlignment = .center
button.lac.height.equalTo(57)
return button
}
private func makeBorder() -> UIView {
UIView(backgroundColor: UIColor.lightGray.alpha(0.4))
}
override open func addAction(_ action: DialogAction) {
if action.type == .cancel, actions.contains(where: { $0.type == .cancel }) {
fatalError("There can only be one cancel action")
}
super.addAction(action)
}
@objc func dismissSheet() {
self.dismiss(animated: true, completion: nil)
}
open override func drawBackgroundHole(bezier: UIBezierPath) {
guard !self.isBeingPresented && !self.isBeingDismissed else {
return
}
let frame1 = contentStackView.convert(contentBlurView.frame, to: self.view)
bezier.append(UIBezierPath(roundedRect: frame1, cornerRadius: contentBlurView.cornerRadius))
if let cancelActionView = cancelActionView {
let frame2 = contentStackView.convert(cancelActionView.frame, to: self.view)
bezier.append(UIBezierPath(roundedRect: frame2, cornerRadius: cancelActionView.cornerRadius))
}
}
open override func loadView() {
super.loadView()
contentStackView.spacing = 8
contentView.lac.make {
$0.left.equalToSuperview(10)
$0.right.equalToSuperview(-10) //TODO: Check still works
$0.top.greaterThan(self.topLayoutGuide.lac.bottom, constant: 10)
// iPhone X
$0.bottom.equalTo(self.bottomLayoutGuide.lac.top, priority: .defaultHigh)
$0.bottom.lessThanSuperview(-10)
}
contentBlurView.cornerRadius = 13.5
contentBlurView.clipsToBounds = true
contentStackView.add(arrangedView: contentBlurView)
promptContentView?.layoutMargins = UIEdgeInsets(horizontal: 16, top: 14, bottom: (promptSubtitle == nil) ? 14 : 25)
promptContentView?.spacing = 12
if actions.isNotEmpty {
var actionButtons = self.actionButtons
let cancelButton = actions.firstIndex(where: { $0.type == .cancel }).map { actionButtons.remove(at: $0) }
let buttonContentView = UIStackView(axis: .vertical)
if promptContentView != nil || customViews.isNotEmpty {
mainContentStack.add(arrangedView: makeBorder()) {
$0.height.equalTo(points(pixels: 1))
}
}
var previousButton: UIButton?
for button in actionButtons {
if previousButton != nil {
buttonContentView.add(arrangedView: makeBorder()) {
$0.height.equalTo(points(pixels: 1))
}
}
buttonContentView.add(arrangedView: button)
previousButton = button
}
mainContentStack.addArrangedSubview(buttonContentView)
if let button = cancelButton {
let blurView = UIVisualEffectView(effect: UIBlurEffect(style: .extraLight))
blurView.cornerRadius = contentBlurView.cornerRadius
blurView.clipsToBounds = true
blurView.contentView.add(view: button) {
$0.edges.equalToSuperview()
}
contentStackView.add(arrangedView: blurView)
cancelActionView = blurView
}
}
}
open override func viewDidLoad() {
super.viewDidLoad()
// Dont dismiss when tapping background if there is no cancel option
if actions.contains(where: { $0.type == .cancel }) {
self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(dismissSheet)))
}
self.modalPresentationStyle = .custom
self.transitioningDelegate = self
}
}
extension SheetDialog: UIViewControllerTransitioningDelegate {
public func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return SheetAnimator(dismissing: false, duration: 1.0/3.0, controlPoints: (CGPoint(0.1, 1), CGPoint(0.85, 1)))
}
public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return SheetAnimator(dismissing: true, duration: 1.0/3.0, controlPoints: (CGPoint(0.1, 1), CGPoint(0.85, 1)))
}
}
private class SheetAnimator: DialogAnimator<SheetDialog> {
override func prepareAnimation(_ viewController: SheetDialog) {
viewController.contentBlurView.backgroundColor = .white
viewController.cancelActionView?.backgroundColor = .white
if !dismissing {
viewController.contentView.layoutIfNeeded()
viewController.contentView.transform(moveX: 0, y: viewController.contentView.frame.height)
viewController.view.alpha = 0.0
}
}
override func animation(_ viewController: SheetDialog) {
if dismissing {
viewController.view.alpha = 0.0
viewController.contentView.transform(moveX: 0, y: viewController.contentView.frame.height)
viewController.view.setNeedsDisplay()
}
else {
viewController.view.alpha = 1.0
viewController.contentView.transform(moveX: 0, y: 0)
}
}
override func completion(_ viewController: SheetDialog, finished: Bool) {
if !dismissing {
viewController.view.setNeedsDisplay()
viewController.contentBlurView.backgroundColor = nil
viewController.cancelActionView?.backgroundColor = nil
}
}
}
| d297e73ae9fd816c817cd4500c037d7a | 30.412621 | 174 | 0.729408 | false | false | false | false |
HamzaGhazouani/HGPlaceholders | refs/heads/master | HGPlaceholders/Classes/Views/CollectionView+Switcher.swift | mit | 1 | //
// CollectionView+Switcher.swift
// Pods
//
// Created by Hamza Ghazouani on 29/09/2017.
//
//
import UIKit
// TODO: try to refactor this code it looks like the TableView+Switcher code
// MARK: Utilities methods to switch to placeholders
extension CollectionView: PlaceholdersSwitcher {
public func showLoadingPlaceholder() {
guard let dataSource = placeholdersProvider.loadingDataSource() else {
assertionFailure(ErrorText.loadingPlaceholder.text)
return
}
self.switchTo(dataSource: dataSource, delegate: dataSource)
}
public func showNoResultsPlaceholder() {
guard let dataSource = placeholdersProvider.noResultsDataSource() else {
assertionFailure(ErrorText.noResultPlaceholder.text)
return
}
self.switchTo(dataSource: dataSource, delegate: dataSource)
}
public func showErrorPlaceholder() {
guard let dataSource = placeholdersProvider.errorDataSource() else {
assertionFailure(ErrorText.errorPlaceholder.text)
return
}
self.switchTo(dataSource: dataSource, delegate: dataSource)
}
public func showNoConnectionPlaceholder() {
guard let dataSource = placeholdersProvider.noConnectionDataSource() else {
assertionFailure(ErrorText.noConnectionPlaceholder.text)
return
}
self.switchTo(dataSource: dataSource, delegate: dataSource)
}
public func showCustomPlaceholder(with key: PlaceholderKey) {
guard let dataSource = placeholdersProvider.dataSourceAndDelegate(with: key) else {
assertionFailure(ErrorText.customPlaceholder(key: key.value).text)
return
}
self.switchTo(dataSource: dataSource, delegate: dataSource)
}
public func showDefault() {
self.switchTo(dataSource: defaultDataSource, delegate: defaultDelegate)
}
}
| 1dcf67d980e62ff09973b241d6da1a0c | 31.163934 | 91 | 0.67686 | false | false | false | false |
boxcast/boxcast-sdk-apple | refs/heads/master | Tests/MockedClientTestCase.swift | mit | 1 | //
// MockedClientTestCase.swift
// BoxCast
//
// Created by Camden Fullmer on 8/22/17.
// Copyright © 2017 BoxCast, Inc. All rights reserved.
//
import XCTest
@testable import BoxCast
class MockedClientTestCase: XCTestCase {
var client: BoxCastClient!
override func setUp() {
super.setUp()
// Set up mocking of the responses.
let configuration = URLSessionConfiguration.default
configuration.protocolClasses?.insert(MockedURLProtocol.self, at: 0)
client = BoxCastClient(scope: PublicScope(), configuration: configuration)
}
func fixtureData(for name: String) -> Data? {
let bundle = Bundle(for: MockedClientTestCase.self)
guard let resourceURL = bundle.resourceURL else {
return nil
}
let fileManager = FileManager.default
let fileURL = resourceURL.appendingPathComponent("\(name).json")
guard fileManager.fileExists(atPath: fileURL.path) else {
return nil
}
do {
let data = try Data(contentsOf: fileURL)
return data
} catch {
return nil
}
}
}
| 3806fab0d5a3f6cee193f2a733fa58fd | 25.711111 | 82 | 0.605657 | false | true | false | false |
CatchChat/Yep | refs/heads/master | Yep/Views/Cells/Feed/FeedCellLayout.swift | mit | 1 | //
// FeedCellLayout.swift
// Yep
//
// Created by nixzhu on 15/12/17.
// Copyright © 2015年 Catch Inc. All rights reserved.
//
import UIKit
import YepKit
private let screenWidth: CGFloat = UIScreen.mainScreen().bounds.width
struct FeedCellLayout {
typealias Update = (layout: FeedCellLayout) -> Void
typealias Cache = (layout: FeedCellLayout?, update: Update)
let height: CGFloat
struct BasicLayout {
func nicknameLabelFrameWhen(hasLogo hasLogo: Bool, hasSkill: Bool) -> CGRect {
var frame = nicknameLabelFrame
frame.size.width -= hasLogo ? (18 + 10) : 0
frame.size.width -= hasSkill ? (skillButtonFrame.width + 10) : 0
return frame
}
let avatarImageViewFrame: CGRect
private let nicknameLabelFrame: CGRect
let skillButtonFrame: CGRect
let messageTextViewFrame: CGRect
let leftBottomLabelFrame: CGRect
let messageCountLabelFrame: CGRect
let discussionImageViewFrame: CGRect
init(avatarImageViewFrame: CGRect,
nicknameLabelFrame: CGRect,
skillButtonFrame: CGRect,
messageTextViewFrame: CGRect,
leftBottomLabelFrame: CGRect,
messageCountLabelFrame: CGRect,
discussionImageViewFrame: CGRect) {
self.avatarImageViewFrame = avatarImageViewFrame
self.nicknameLabelFrame = nicknameLabelFrame
self.skillButtonFrame = skillButtonFrame
self.messageTextViewFrame = messageTextViewFrame
self.leftBottomLabelFrame = leftBottomLabelFrame
self.messageCountLabelFrame = messageCountLabelFrame
self.discussionImageViewFrame = discussionImageViewFrame
}
}
let basicLayout: BasicLayout
struct BiggerImageLayout {
let biggerImageViewFrame: CGRect
init(biggerImageViewFrame: CGRect) {
self.biggerImageViewFrame = biggerImageViewFrame
}
}
var biggerImageLayout: BiggerImageLayout?
struct NormalImagesLayout {
let imageView1Frame: CGRect
let imageView2Frame: CGRect
let imageView3Frame: CGRect
let imageView4Frame: CGRect
init(imageView1Frame: CGRect, imageView2Frame: CGRect, imageView3Frame: CGRect, imageView4Frame: CGRect) {
self.imageView1Frame = imageView1Frame
self.imageView2Frame = imageView2Frame
self.imageView3Frame = imageView3Frame
self.imageView4Frame = imageView4Frame
}
}
var normalImagesLayout: NormalImagesLayout?
struct AnyImagesLayout {
let mediaCollectionViewFrame: CGRect
init(mediaCollectionViewFrame: CGRect) {
self.mediaCollectionViewFrame = mediaCollectionViewFrame
}
}
var anyImagesLayout: AnyImagesLayout?
struct GithubRepoLayout {
let githubRepoContainerViewFrame: CGRect
}
var githubRepoLayout: GithubRepoLayout?
struct DribbbleShotLayout {
let dribbbleShotContainerViewFrame: CGRect
}
var dribbbleShotLayout: DribbbleShotLayout?
struct AudioLayout {
let voiceContainerViewFrame: CGRect
}
var audioLayout: AudioLayout?
struct LocationLayout {
let locationContainerViewFrame: CGRect
}
var locationLayout: LocationLayout?
struct URLLayout {
let URLContainerViewFrame: CGRect
}
var _URLLayout: URLLayout?
// MARK: - Init
init(height: CGFloat, basicLayout: BasicLayout) {
self.height = height
self.basicLayout = basicLayout
}
init(feed: DiscoveredFeed) {
let height: CGFloat
switch feed.kind {
case .Text:
height = FeedBasicCell.heightOfFeed(feed)
case .URL:
height = FeedURLCell.heightOfFeed(feed)
case .Image:
if feed.imageAttachmentsCount == 1 {
height = FeedBiggerImageCell.heightOfFeed(feed)
} else if feed.imageAttachmentsCount <= FeedsViewController.feedNormalImagesCountThreshold {
height = FeedNormalImagesCell.heightOfFeed(feed)
} else {
height = FeedAnyImagesCell.heightOfFeed(feed)
}
case .GithubRepo:
height = FeedGithubRepoCell.heightOfFeed(feed)
case .DribbbleShot:
height = FeedDribbbleShotCell.heightOfFeed(feed)
case .Audio:
height = FeedVoiceCell.heightOfFeed(feed)
case .Location:
height = FeedLocationCell.heightOfFeed(feed)
default:
height = FeedBasicCell.heightOfFeed(feed)
}
self.height = height
let avatarImageViewFrame = CGRect(x: 15, y: 10, width: 40, height: 40)
let nicknameLabelFrame: CGRect
let skillButtonFrame: CGRect
if let skill = feed.skill {
let rect = skill.localName.boundingRectWithSize(CGSize(width: 320, height: CGFloat(FLT_MAX)), options: [.UsesLineFragmentOrigin, .UsesFontLeading], attributes: YepConfig.FeedBasicCell.skillTextAttributes, context: nil)
let skillButtonWidth = ceil(rect.width) + 20
skillButtonFrame = CGRect(x: screenWidth - skillButtonWidth - 15, y: 19, width: skillButtonWidth, height: 22)
let nicknameLabelWidth = screenWidth - 65 - 15
nicknameLabelFrame = CGRect(x: 65, y: 21, width: nicknameLabelWidth, height: 18)
} else {
let nicknameLabelWidth = screenWidth - 65 - 15
nicknameLabelFrame = CGRect(x: 65, y: 21, width: nicknameLabelWidth, height: 18)
skillButtonFrame = CGRectZero
}
let _rect1 = feed.body.boundingRectWithSize(CGSize(width: FeedBasicCell.messageTextViewMaxWidth, height: CGFloat(FLT_MAX)), options: [.UsesLineFragmentOrigin, .UsesFontLeading], attributes: YepConfig.FeedBasicCell.textAttributes, context: nil)
let messageTextViewHeight = ceil(_rect1.height)
let messageTextViewFrame = CGRect(x: 65, y: 54, width: screenWidth - 65 - 15, height: messageTextViewHeight)
let leftBottomLabelOriginY = height - 17 - 15
let leftBottomLabelFrame = CGRect(x: 65, y: leftBottomLabelOriginY, width: screenWidth - 65 - 85, height: 17)
//let messagesCountString = feed.messagesCount > 99 ? "99+" : "\(feed.messagesCount)"
//let _rect2 = messagesCountString.boundingRectWithSize(CGSize(width: 320, height: CGFloat(FLT_MAX)), options: [.UsesLineFragmentOrigin, .UsesFontLeading], attributes: YepConfig.FeedBasicCell.bottomLabelsTextAttributes, context: nil)
//let _width = ceil(_rect2.width)
let _width: CGFloat = 30
let messageCountLabelFrame = CGRect(x: screenWidth - _width - 45 - 8, y: leftBottomLabelOriginY, width: _width, height: 19)
let discussionImageViewFrame = CGRect(x: screenWidth - 30 - 15, y: leftBottomLabelOriginY - 1, width: 30, height: 19)
let basicLayout = FeedCellLayout.BasicLayout(
avatarImageViewFrame: avatarImageViewFrame,
nicknameLabelFrame: nicknameLabelFrame,
skillButtonFrame: skillButtonFrame,
messageTextViewFrame: messageTextViewFrame,
leftBottomLabelFrame: leftBottomLabelFrame,
messageCountLabelFrame: messageCountLabelFrame,
discussionImageViewFrame: discussionImageViewFrame
)
self.basicLayout = basicLayout
let beginY = messageTextViewFrame.origin.y + messageTextViewFrame.height + 15
switch feed.kind {
case .Text:
break
case .URL:
let height: CGFloat = leftBottomLabelFrame.origin.y - beginY - 15
let URLContainerViewFrame = CGRect(x: 65, y: beginY, width: screenWidth - 65 - 60, height: height)
let _URLLayout = FeedCellLayout.URLLayout(URLContainerViewFrame: URLContainerViewFrame)
self._URLLayout = _URLLayout
case .Image:
if feed.imageAttachmentsCount == 1 {
let biggerImageViewFrame = CGRect(origin: CGPoint(x: 65, y: beginY), size: YepConfig.FeedBiggerImageCell.imageSize)
let biggerImageLayout = FeedCellLayout.BiggerImageLayout(biggerImageViewFrame: biggerImageViewFrame)
self.biggerImageLayout = biggerImageLayout
} else if feed.imageAttachmentsCount <= FeedsViewController.feedNormalImagesCountThreshold {
let x1 = 65 + (YepConfig.FeedNormalImagesCell.imageSize.width + 5) * 0
let imageView1Frame = CGRect(origin: CGPoint(x: x1, y: beginY), size: YepConfig.FeedNormalImagesCell.imageSize)
let x2 = 65 + (YepConfig.FeedNormalImagesCell.imageSize.width + 5) * 1
let imageView2Frame = CGRect(origin: CGPoint(x: x2, y: beginY), size: YepConfig.FeedNormalImagesCell.imageSize)
let x3 = 65 + (YepConfig.FeedNormalImagesCell.imageSize.width + 5) * 2
let imageView3Frame = CGRect(origin: CGPoint(x: x3, y: beginY), size: YepConfig.FeedNormalImagesCell.imageSize)
let x4 = 65 + (YepConfig.FeedNormalImagesCell.imageSize.width + 5) * 3
let imageView4Frame = CGRect(origin: CGPoint(x: x4, y: beginY), size: YepConfig.FeedNormalImagesCell.imageSize)
let normalImagesLayout = FeedCellLayout.NormalImagesLayout(imageView1Frame: imageView1Frame, imageView2Frame: imageView2Frame, imageView3Frame: imageView3Frame, imageView4Frame: imageView4Frame)
self.normalImagesLayout = normalImagesLayout
} else {
let height = YepConfig.FeedNormalImagesCell.imageSize.height
let mediaCollectionViewFrame = CGRect(x: 0, y: beginY, width: screenWidth, height: height)
let anyImagesLayout = FeedCellLayout.AnyImagesLayout(mediaCollectionViewFrame: mediaCollectionViewFrame)
self.anyImagesLayout = anyImagesLayout
}
case .GithubRepo:
let height: CGFloat = leftBottomLabelFrame.origin.y - beginY - 15
let githubRepoContainerViewFrame = CGRect(x: 65, y: beginY, width: screenWidth - 65 - 60, height: height)
let githubRepoLayout = FeedCellLayout.GithubRepoLayout(githubRepoContainerViewFrame: githubRepoContainerViewFrame)
self.githubRepoLayout = githubRepoLayout
case .DribbbleShot:
let height: CGFloat = leftBottomLabelFrame.origin.y - beginY - 15
let dribbbleShotContainerViewFrame = CGRect(x: 65, y: beginY, width: screenWidth - 65 - 60, height: height)
let dribbbleShotLayout = FeedCellLayout.DribbbleShotLayout(dribbbleShotContainerViewFrame: dribbbleShotContainerViewFrame)
self.dribbbleShotLayout = dribbbleShotLayout
case .Audio:
if let attachment = feed.attachment {
if case let .Audio(audioInfo) = attachment {
let timeLengthString = audioInfo.duration.yep_feedAudioTimeLengthString
let width = FeedVoiceContainerView.fullWidthWithSampleValuesCount(audioInfo.sampleValues.count, timeLengthString: timeLengthString)
let y = beginY + 2
let voiceContainerViewFrame = CGRect(x: 65, y: y, width: width, height: 50)
let audioLayout = FeedCellLayout.AudioLayout(voiceContainerViewFrame: voiceContainerViewFrame)
self.audioLayout = audioLayout
}
}
case .Location:
let height: CGFloat = leftBottomLabelFrame.origin.y - beginY - 15
let locationContainerViewFrame = CGRect(x: 65, y: beginY, width: screenWidth - 65 - 60, height: height)
let locationLayout = FeedCellLayout.LocationLayout(locationContainerViewFrame: locationContainerViewFrame)
self.locationLayout = locationLayout
default:
break
}
}
}
| babd9f2b105810423dfcf030a0363140 | 36.319876 | 251 | 0.662561 | false | false | false | false |
firebase/firebase-ios-sdk | refs/heads/master | FirebaseStorage/Tests/Integration/StorageIntegrationCommon.swift | apache-2.0 | 1 | // Copyright 2021 Google LLC
//
// 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 FirebaseAuth
import FirebaseCore
import FirebaseStorage
import XCTest
class StorageIntegrationCommon: XCTestCase {
var app: FirebaseApp!
var auth: Auth!
var storage: Storage!
static var configured = false
static var once = false
static var signedIn = false
override class func setUp() {
if !StorageIntegrationCommon.configured {
StorageIntegrationCommon.configured = true
FirebaseApp.configure()
}
}
override func setUp() {
super.setUp()
app = FirebaseApp.app()
auth = Auth.auth(app: app)
storage = Storage.storage(app: app!)
if !StorageIntegrationCommon.signedIn {
signInAndWait()
}
if !StorageIntegrationCommon.once {
StorageIntegrationCommon.once = true
let setupExpectation = expectation(description: "setUp")
let largeFiles = ["ios/public/1mb", "ios/public/1mb2"]
let emptyFiles =
["ios/public/empty", "ios/public/list/a", "ios/public/list/b", "ios/public/list/prefix/c"]
setupExpectation.expectedFulfillmentCount = largeFiles.count + emptyFiles.count
do {
let bundle = Bundle(for: StorageIntegrationCommon.self)
let filePath = try XCTUnwrap(bundle.path(forResource: "1mb", ofType: "dat"),
"Failed to get filePath")
let data = try XCTUnwrap(try Data(contentsOf: URL(fileURLWithPath: filePath)),
"Failed to load file")
for largeFile in largeFiles {
let ref = storage.reference().child(largeFile)
ref.putData(data) { result in
self.assertResultSuccess(result)
setupExpectation.fulfill()
}
}
for emptyFile in emptyFiles {
let ref = storage.reference().child(emptyFile)
ref.putData(Data()) { result in
self.assertResultSuccess(result)
setupExpectation.fulfill()
}
}
waitForExpectations()
} catch {
XCTFail("Error thrown setting up files in setUp")
}
}
}
override func tearDown() {
app = nil
storage = nil
super.tearDown()
}
private func signInAndWait() {
let expectation = self.expectation(description: #function)
auth.signIn(withEmail: Credentials.kUserName,
password: Credentials.kPassword) { result, error in
XCTAssertNil(error)
StorageIntegrationCommon.signedIn = true
print("Successfully signed in")
expectation.fulfill()
}
waitForExpectations()
}
private func waitForExpectations() {
let kTestTimeout = 60.0
waitForExpectations(timeout: kTestTimeout,
handler: { error in
if let error = error {
print(error)
}
})
}
private func assertResultSuccess<T>(_ result: Result<T, Error>,
file: StaticString = #file, line: UInt = #line) {
switch result {
case let .success(value):
XCTAssertNotNil(value, file: file, line: line)
case let .failure(error):
XCTFail("Unexpected error \(error)")
}
}
}
| e262697dbe9ed59d34276edd6397028a | 30.689076 | 98 | 0.627155 | false | false | false | false |
itsaboutcode/WordPress-iOS | refs/heads/develop | WordPress/Classes/ViewRelated/What's New/Data store/AnnouncementsDataSource.swift | gpl-2.0 | 1 |
protocol AnnouncementsDataSource: UITableViewDataSource {
func registerCells(for tableView: UITableView)
var dataDidChange: (() -> Void)? { get set }
}
class FeatureAnnouncementsDataSource: NSObject, AnnouncementsDataSource {
private let store: AnnouncementsStore
private let cellTypes: [String: UITableViewCell.Type]
private var features: [WordPressKit.Feature] {
store.announcements.reduce(into: [WordPressKit.Feature](), {
$0.append(contentsOf: $1.features)
})
}
var dataDidChange: (() -> Void)?
init(store: AnnouncementsStore, cellTypes: [String: UITableViewCell.Type]) {
self.store = store
self.cellTypes = cellTypes
super.init()
}
func registerCells(for tableView: UITableView) {
cellTypes.forEach {
tableView.register($0.value, forCellReuseIdentifier: $0.key)
}
}
func numberOfSections(in: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return features.count + 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard indexPath.row <= features.count - 1 else {
let cell = tableView.dequeueReusableCell(withIdentifier: "findOutMoreCell", for: indexPath) as? FindOutMoreCell ?? FindOutMoreCell()
cell.configure(with: URL(string: store.announcements.first?.detailsUrl ?? ""))
return cell
}
let cell = tableView.dequeueReusableCell(withIdentifier: "announcementCell", for: indexPath) as? AnnouncementCell ?? AnnouncementCell()
cell.configure(feature: features[indexPath.row])
return cell
}
}
| 2fe0084b96d74481c80b2e15910ccd1d | 32.396226 | 144 | 0.668362 | false | false | false | false |
aktowns/swen | refs/heads/master | Sources/Swen/Util/XPathDocument.swift | apache-2.0 | 1 | //
// XPathDocument.swift created on 29/12/15
// Swen project
//
// Copyright 2015 Ashley Towns <[email protected]>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
/*
This is a light wrapper around libxml2 to read xml based formats
this is being used mainly because NSXML lacks linux support at the moment.
This is really crude and only does what i need it to..
*/
import CXML2
enum XMLElementType: UInt32 {
case ElementNode = 1
case AttributeNode = 2
case TextNode = 3
case CDATASectionNode = 4
case EntityRefNode = 5
case EntityNode = 6
case PINode = 7
case CommentNode = 8
case DocumentNode = 9
case DocumentTypeNode = 10
case DocumentFragNode = 11
case NotationNode = 12
case HTMLDocumentNode = 13
case DTDNode = 14
case ElementDecl = 15
case AttributeDecl = 16
case EntityDecl = 17
case NamespaceDecl = 18
case XIncludeStart = 19
case XIncludeEnd = 20
}
public class XMLNode: CustomStringConvertible {
let handle: xmlNodePtr
public init(withHandle handle: xmlNodePtr) {
self.handle = handle
}
public func getProp(property: String) -> String? {
let prop = xmlGetProp(self.handle, property)
return String.fromCString(UnsafePointer<Int8>(prop))
}
var type: XMLElementType? {
return XMLElementType(rawValue: self.handle.memory.type.rawValue)
}
var name: String? {
let convName = UnsafePointer<Int8>(self.handle.memory.name)
return String.fromCString(convName)
}
var content: String? {
let convContent = UnsafePointer<Int8>(self.handle.memory.content)
return String.fromCString(convContent)
}
public var description: String {
return "#\(self.dynamicType)(name:\(name), type:\(type), content:\(content))"
}
}
public class XPathDocument {
let doc: xmlDocPtr
let ctx: xmlXPathContextPtr
public init(withPath path: String) {
let docptr = xmlParseFile(path)
assert(docptr != nil, "xmlParseFile failed, returned a null pointer.")
let ctxptr = xmlXPathNewContext(docptr)
assert(ctxptr != nil, "xmlXPathNewContext failed, returned a null pointer.")
self.doc = docptr
self.ctx = ctxptr
}
public func search(withXPath xpath: String) -> [XMLNode] {
let exprptr = xmlXPathEvalExpression(xpath, self.ctx)
assert(exprptr != nil, "xmlXPathEvalExpression failed, returned a null pointer.")
return getNodes(exprptr.memory.nodesetval)
}
private func getNodes(nodes: xmlNodeSetPtr) -> [XMLNode] {
let size: Int = (nodes != nil) ? Int(nodes.memory.nodeNr) : Int(0)
var outNodes = Array<XMLNode>()
for i in Range(start: Int(0), end: size) {
let node = XMLNode(withHandle: nodes.memory.nodeTab[i])
outNodes.append(node)
}
return outNodes
}
}
| b3659cf4496086bb23454df5f6c7d71b | 26.788136 | 85 | 0.703263 | false | false | false | false |
1457792186/JWSwift | refs/heads/master | BabyTunes/Pods/RxSwift/RxSwift/Observables/Concat.swift | apache-2.0 | 30 | //
// Concat.swift
// RxSwift
//
// Created by Krunoslav Zaher on 3/21/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
extension ObservableType {
/**
Concatenates the second observable sequence to `self` upon successful termination of `self`.
- seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html)
- parameter second: Second observable sequence.
- returns: An observable sequence that contains the elements of `self`, followed by those of the second sequence.
*/
public func concat<O: ObservableConvertibleType>(_ second: O) -> Observable<E> where O.E == E {
return Observable.concat([self.asObservable(), second.asObservable()])
}
}
extension ObservableType {
/**
Concatenates all observable sequences in the given sequence, as long as the previous observable sequence terminated successfully.
This operator has tail recursive optimizations that will prevent stack overflow.
Optimizations will be performed in cases equivalent to following:
[1, [2, [3, .....].concat()].concat].concat()
- seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html)
- returns: An observable sequence that contains the elements of each given sequence, in sequential order.
*/
public static func concat<S: Sequence >(_ sequence: S) -> Observable<E>
where S.Iterator.Element == Observable<E> {
return Concat(sources: sequence, count: nil)
}
/**
Concatenates all observable sequences in the given collection, as long as the previous observable sequence terminated successfully.
This operator has tail recursive optimizations that will prevent stack overflow.
Optimizations will be performed in cases equivalent to following:
[1, [2, [3, .....].concat()].concat].concat()
- seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html)
- returns: An observable sequence that contains the elements of each given sequence, in sequential order.
*/
public static func concat<S: Collection >(_ collection: S) -> Observable<E>
where S.Iterator.Element == Observable<E> {
return Concat(sources: collection, count: Int64(collection.count))
}
/**
Concatenates all observable sequences in the given collection, as long as the previous observable sequence terminated successfully.
This operator has tail recursive optimizations that will prevent stack overflow.
Optimizations will be performed in cases equivalent to following:
[1, [2, [3, .....].concat()].concat].concat()
- seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html)
- returns: An observable sequence that contains the elements of each given sequence, in sequential order.
*/
public static func concat(_ sources: Observable<E> ...) -> Observable<E> {
return Concat(sources: sources, count: Int64(sources.count))
}
}
final fileprivate class ConcatSink<S: Sequence, O: ObserverType>
: TailRecursiveSink<S, O>
, ObserverType where S.Iterator.Element : ObservableConvertibleType, S.Iterator.Element.E == O.E {
typealias Element = O.E
override init(observer: O, cancel: Cancelable) {
super.init(observer: observer, cancel: cancel)
}
func on(_ event: Event<Element>){
switch event {
case .next:
forwardOn(event)
case .error:
forwardOn(event)
dispose()
case .completed:
schedule(.moveNext)
}
}
override func subscribeToNext(_ source: Observable<E>) -> Disposable {
return source.subscribe(self)
}
override func extract(_ observable: Observable<E>) -> SequenceGenerator? {
if let source = observable as? Concat<S> {
return (source._sources.makeIterator(), source._count)
}
else {
return nil
}
}
}
final fileprivate class Concat<S: Sequence> : Producer<S.Iterator.Element.E> where S.Iterator.Element : ObservableConvertibleType {
typealias Element = S.Iterator.Element.E
fileprivate let _sources: S
fileprivate let _count: IntMax?
init(sources: S, count: IntMax?) {
_sources = sources
_count = count
}
override func run<O: ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element {
let sink = ConcatSink<S, O>(observer: observer, cancel: cancel)
let subscription = sink.run((_sources.makeIterator(), _count))
return (sink: sink, subscription: subscription)
}
}
| 1bf0a124826c802b05986209e6d8f3b5 | 35.59542 | 144 | 0.673133 | false | false | false | false |
sungkipyung/CodeSample | refs/heads/master | SimpleCameraApp/SimpleCameraApp/CollageCell.swift | apache-2.0 | 1 | //
// CollageCell.swift
// SimpleCameraApp
//
// Created by 성기평 on 2016. 4. 14..
// Copyright © 2016년 hothead. All rights reserved.
//
import UIKit
protocol CollageCellDelegate {
func collageCellDidSelect(_ cell: CollageCell)
}
class CollageCell: UIView, UIScrollViewDelegate {
@IBOutlet weak var cameraPreview: CameraPreview!
@IBOutlet weak var imageScrollView: UIScrollView!
weak var imageView: UIImageView!
var delegate: CollageCellDelegate?
var enableMask: Bool? = true
@IBOutlet weak var lineView: UIView!
fileprivate static let BORDER_WIDTH:CGFloat = 0
var polygon: Polygon! {
didSet {
if let p = polygon {
let path = p.path()
self.frame = CGRect(origin: p.origin, size: path.bounds.size)
self.imageScrollView.frame = self.bounds
// self.imageView.sizeThatFit(self.imageScrollView)
self.cameraPreview.frame = self.bounds
self.shapeLayerPath = path
}
}
}
internal fileprivate(set) var shapeLayerPath : UIBezierPath? {
didSet (newLayer) {
let shapeLayerPath = self.shapeLayerPath!
let path = shapeLayerPath.cgPath
if self.enableMask! {
let mask: CAShapeLayer = CAShapeLayer()
mask.path = path
self.layer.mask = mask
}
self.lineView.layer.sublayers?.forEach({ (sublayer) in
sublayer.removeFromSuperlayer()
})
if (self.imageView.image == nil) {
let line = CAShapeLayer.init()
line.path = path
line.lineDashPattern = [8, 8]
line.lineWidth = 2
line.fillColor = UIColor.clear.cgColor
line.strokeColor = UIColor.white.cgColor
self.lineView.layer.addSublayer(line)
}
}
}
func pointInside(_ point: CGPoint) -> Bool {
if let path:UIBezierPath = self.shapeLayerPath {
return path.contains(point)
}
return false
}
override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
if let path:UIBezierPath = self.shapeLayerPath {
return path.contains(point)
} else {
return super.point(inside: point, with: event)
}
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func awakeFromNib() {
self.imageScrollView.delegate = self
let imageView = UIImageView(frame: self.bounds)
imageView.contentMode = UIViewContentMode.scaleToFill
self.imageScrollView.addSubview(imageView)
self.imageView = imageView
}
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return self.imageView
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
// self.superview?.bringSubviewToFront(self)
}
@IBAction func imageScrollViewTapped(_ sender: AnyObject) {
delegate?.collageCellDidSelect(self)
}
}
| 9bc6a143ef9fea3f0a1459931d72aa4c | 29.364407 | 79 | 0.588334 | false | false | false | false |
Shivol/Swift-CS333 | refs/heads/master | playgrounds/uiKit/UIKitCatalog.playground/Pages/UIPickerView.xcplaygroundpage/Contents.swift | mit | 2 | import UIKit
import PlaygroundSupport
class Model: NSObject, UIPickerViewDataSource {
var data = [[String]]()
let fakeRowCount = 10_000
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return data.count
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return fakeRowCount // data[component].count
}
func data(forRow row: Int, inComponent component: Int) -> String {
return data[component][row % data[component].count]
}
}
class Controller: NSObject, UIPickerViewDelegate {
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
guard let dataSource = pickerView.dataSource as? Model else {
print("Wrong model!")
PlaygroundPage.current.finishExecution()
}
return dataSource.data(forRow: row, inComponent: component)
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
guard let dataSource = pickerView.dataSource as? Model else {
print("Wrong model!")
PlaygroundPage.current.finishExecution()
}
let items = [ dataSource.data(forRow: pickerView.selectedRow(inComponent: 0), inComponent: 0),
dataSource.data(forRow: pickerView.selectedRow(inComponent: 1), inComponent: 1),
dataSource.data(forRow: pickerView.selectedRow(inComponent: 2), inComponent: 2)]
if items[0] == items[1] && items[1] == items[2] {
let win = UILabel(frame: pickerView.frame)
win.text = "WIN!!!"
win.textAlignment = .center
win.font = UIFont(name: "Chalkduster", size: 48)
win.textColor = #colorLiteral(red: 0.5725490451, green: 0, blue: 0.2313725501, alpha: 1)
pickerView.addSubview(win)
// show and hide
win.alpha = 0
UIView.animate(withDuration: 0.5){ win.alpha = 1 }
UIView.animate(withDuration: 0.5, delay: 0.5, options: .curveLinear, animations: { win.alpha = 0 }, completion: { _ in win.removeFromSuperview() })
}
}
}
let slotView = UIPickerView(frame: CGRect(x: 0, y: 0, width: 300, height: 150))
let slots = Model()
slots.data.append(["⭐️","⚡️","🐸","🌈","🍎"])
slots.data.append(["⚡️","⭐️","🌈","🍎","🐸"])
slots.data.append(["🍎","🌈","⭐️","🐸","⚡️"])
slotView.dataSource = slots
let delegate = Controller()
slotView.delegate = delegate
slotView.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
PlaygroundPage.current.liveView = slotView
slotView.selectRow(1000, inComponent: 0, animated: true)
slotView.selectRow(1000, inComponent: 1, animated: true)
slotView.selectRow(1000, inComponent: 2, animated: true)
| ab278abee53fea56be57cea2baf746ee | 38.383562 | 159 | 0.62887 | false | false | false | false |
JohnSansoucie/MyProject2 | refs/heads/master | BlueCapKit/External/SimpleFutures/Future.swift | mit | 1 | //
// Future.swift
// SimpleFutures
//
// Created by Troy Stribling on 7/5/14.
// Copyright (c) 2014 gnos.us. All rights reserved.
//
import Foundation
public struct SimpleFuturesError {
static let domain = "SimpleFutures"
static let futureCompleted = NSError(domain:domain, code:1, userInfo:[NSLocalizedDescriptionKey:"Future has been completed"])
static let futureNotCompleted = NSError(domain:domain, code:2, userInfo:[NSLocalizedDescriptionKey:"Future has not been completed"])
}
public struct SimpleFuturesException {
static let futureCompleted = NSException(name:"Future complete error", reason: "Future previously completed.", userInfo:nil)
}
// Promise
public class Promise<T> {
public let future = Future<T>()
public init() {
}
public func completeWith(future:Future<T>) {
self.completeWith(self.future.defaultExecutionContext, future:future)
}
public func completeWith(executionContext:ExecutionContext, future:Future<T>) {
self.future.completeWith(executionContext, future:future)
}
public func complete(result:Try<T>) {
self.future.complete(result)
}
public func success(value:T) {
self.future.success(value)
}
public func failure(error:NSError) {
self.future.failure(error)
}
}
// Future
public class Future<T> {
private var result:Try<T>?
internal let defaultExecutionContext: ExecutionContext = QueueContext.main
typealias OnComplete = Try<T> -> Void
private var saveCompletes = [OnComplete]()
public init() {
}
// should be Futureable protocol
public func onComplete(executionContext:ExecutionContext, complete:Try<T> -> Void) -> Void {
Queue.simpleFutures.sync {
let savedCompletion : OnComplete = {result in
executionContext.execute {
complete(result)
}
}
if let result = self.result {
savedCompletion(result)
} else {
self.saveCompletes.append(savedCompletion)
}
}
}
// should be future mixin
internal func complete(result:Try<T>) {
Queue.simpleFutures.sync {
if self.result != nil {
SimpleFuturesException.futureCompleted.raise()
}
self.result = result
for complete in self.saveCompletes {
complete(result)
}
self.saveCompletes.removeAll()
}
}
public func onComplete(complete:Try<T> -> Void) {
self.onComplete(self.defaultExecutionContext, complete)
}
public func onSuccess(success:T -> Void) {
self.onSuccess(self.defaultExecutionContext, success)
}
public func onSuccess(executionContext:ExecutionContext, success:T -> Void){
self.onComplete(executionContext) {result in
switch result {
case .Success(let valueBox):
success(valueBox.value)
default:
break
}
}
}
public func onFailure(failure:NSError -> Void) -> Void {
return self.onFailure(self.defaultExecutionContext, failure)
}
public func onFailure(executionContext:ExecutionContext, failure:NSError -> Void) {
self.onComplete(executionContext) {result in
switch result {
case .Failure(let error):
failure(error)
default:
break
}
}
}
public func map<M>(mapping:T -> Try<M>) -> Future<M> {
return map(self.defaultExecutionContext, mapping:mapping)
}
public func map<M>(executionContext:ExecutionContext, mapping:T -> Try<M>) -> Future<M> {
let future = Future<M>()
self.onComplete(executionContext) {result in
future.complete(result.flatmap(mapping))
}
return future
}
public func flatmap<M>(mapping:T -> Future<M>) -> Future<M> {
return self.flatmap(self.defaultExecutionContext, mapping:mapping)
}
public func flatmap<M>(executionContext:ExecutionContext, mapping:T -> Future<M>) -> Future<M> {
let future = Future<M>()
self.onComplete(executionContext) {result in
switch result {
case .Success(let resultBox):
future.completeWith(executionContext, future:mapping(resultBox.value))
case .Failure(let error):
future.failure(error)
}
}
return future
}
public func andThen(complete:Try<T> -> Void) -> Future<T> {
return self.andThen(self.defaultExecutionContext, complete:complete)
}
public func andThen(executionContext:ExecutionContext, complete:Try<T> -> Void) -> Future<T> {
let future = Future<T>()
future.onComplete(executionContext, complete)
self.onComplete(executionContext) {result in
future.complete(result)
}
return future
}
public func recover(recovery: NSError -> Try<T>) -> Future<T> {
return self.recover(self.defaultExecutionContext, recovery:recovery)
}
public func recover(executionContext:ExecutionContext, recovery:NSError -> Try<T>) -> Future<T> {
let future = Future<T>()
self.onComplete(executionContext) {result in
future.complete(result.recoverWith(recovery))
}
return future
}
public func recoverWith(recovery:NSError -> Future<T>) -> Future<T> {
return self.recoverWith(self.defaultExecutionContext, recovery:recovery)
}
public func recoverWith(executionContext:ExecutionContext, recovery:NSError -> Future<T>) -> Future<T> {
let future = Future<T>()
self.onComplete(executionContext) {result in
switch result {
case .Success(let resultBox):
future.success(resultBox.value)
case .Failure(let error):
future.completeWith(executionContext, future:recovery(error))
}
}
return future
}
public func withFilter(filter:T -> Bool) -> Future<T> {
return self.withFilter(self.defaultExecutionContext, filter:filter)
}
public func withFilter(executionContext:ExecutionContext, filter:T -> Bool) -> Future<T> {
let future = Future<T>()
self.onComplete(executionContext) {result in
future.complete(result.filter(filter))
}
return future
}
public func foreach(apply:T -> Void) {
self.foreach(self.defaultExecutionContext, apply:apply)
}
public func foreach(executionContext:ExecutionContext, apply:T -> Void) {
self.onComplete(executionContext) {result in
result.foreach(apply)
}
}
internal func completeWith(future:Future<T>) {
self.completeWith(self.defaultExecutionContext, future:future)
}
internal func completeWith(executionContext:ExecutionContext, future:Future<T>) {
let isCompleted = Queue.simpleFutures.sync {Void -> Bool in
return self.result != nil
}
if isCompleted == false {
future.onComplete(executionContext) {result in
self.complete(result)
}
}
}
internal func success(value:T) {
self.complete(Try(value))
}
internal func failure(error:NSError) {
self.complete(Try<T>(error))
}
}
// create futures
public func future<T>(computeResult:Void -> Try<T>) -> Future<T> {
return future(QueueContext.global, computeResult)
}
public func future<T>(executionContext:ExecutionContext, calculateResult:Void -> Try<T>) -> Future<T> {
let promise = Promise<T>()
executionContext.execute {
promise.complete(calculateResult())
}
return promise.future
}
public func forcomp<T,U>(f:Future<T>, g:Future<U>, #apply:(T,U) -> Void) -> Void {
return forcomp(f.defaultExecutionContext, f, g, apply:apply)
}
public func forcomp<T,U>(executionContext:ExecutionContext, f:Future<T>, g:Future<U>, #apply:(T,U) -> Void) -> Void {
f.foreach(executionContext) {fvalue in
g.foreach(executionContext) {gvalue in
apply(fvalue, gvalue)
}
}
}
// for comprehensions
public func forcomp<T,U>(f:Future<T>, g:Future<U>, #filter:(T,U) -> Bool, #apply:(T,U) -> Void) -> Void {
return forcomp(f.defaultExecutionContext, f, g, filter:filter, apply:apply)
}
public func forcomp<T,U>(executionContext:ExecutionContext, f:Future<T>, g:Future<U>, #filter:(T,U) -> Bool, #apply:(T,U) -> Void) -> Void {
f.foreach(executionContext) {fvalue in
g.withFilter(executionContext) {gvalue in
filter(fvalue, gvalue)
}.foreach(executionContext) {gvalue in
apply(fvalue, gvalue)
}
}
}
public func forcomp<T,U,V>(f:Future<T>, g:Future<U>, h:Future<V>, #apply:(T,U,V) -> Void) -> Void {
return forcomp(f.defaultExecutionContext, f, g, h, apply:apply)
}
public func forcomp<T,U,V>(executionContext:ExecutionContext, f:Future<T>, g:Future<U>, h:Future<V>, #apply:(T,U,V) -> Void) -> Void {
f.foreach(executionContext) {fvalue in
g.foreach(executionContext) {gvalue in
h.foreach(executionContext) {hvalue in
apply(fvalue, gvalue, hvalue)
}
}
}
}
public func forcomp<T,U,V>(f:Future<T>, g:Future<U>, h:Future<V>, #filter:(T,U,V) -> Bool, #apply:(T,U,V) -> Void) -> Void {
return forcomp(f.defaultExecutionContext, f, g, h, filter:filter, apply:apply)
}
public func forcomp<T,U,V>(executionContext:ExecutionContext, f:Future<T>, g:Future<U>, h:Future<V>, #filter:(T,U,V) -> Bool, #apply:(T,U,V) -> Void) -> Void {
f.foreach(executionContext) {fvalue in
g.foreach(executionContext) {gvalue in
h.withFilter(executionContext) {hvalue in
filter(fvalue, gvalue, hvalue)
}.foreach(executionContext) {hvalue in
apply(fvalue, gvalue, hvalue)
}
}
}
}
public func forcomp<T,U,V>(f:Future<T>, g:Future<U>, #yield:(T,U) -> Try<V>) -> Future<V> {
return forcomp(f.defaultExecutionContext, f, g, yield:yield)
}
public func forcomp<T,U,V>(executionContext:ExecutionContext, f:Future<T>, g:Future<U>, #yield:(T,U) -> Try<V>) -> Future<V> {
return f.flatmap(executionContext) {fvalue in
g.map(executionContext) {gvalue in
yield(fvalue, gvalue)
}
}
}
public func forcomp<T,U,V>(f:Future<T>, g:Future<U>, #filter:(T,U) -> Bool, #yield:(T,U) -> Try<V>) -> Future<V> {
return forcomp(f.defaultExecutionContext, f, g, filter:filter, yield:yield)
}
public func forcomp<T,U,V>(executionContext:ExecutionContext, f:Future<T>, g:Future<U>, #filter:(T,U) -> Bool, #yield:(T,U) -> Try<V>) -> Future<V> {
return f.flatmap(executionContext) {fvalue in
g.withFilter(executionContext) {gvalue in
filter(fvalue, gvalue)
}.map(executionContext) {gvalue in
yield(fvalue, gvalue)
}
}
}
public func forcomp<T,U,V,W>(f:Future<T>, g:Future<U>, h:Future<V>, #yield:(T,U,V) -> Try<W>) -> Future<W> {
return forcomp(f.defaultExecutionContext, f, g, h, yield:yield)
}
public func forcomp<T,U,V,W>(executionContext:ExecutionContext, f:Future<T>, g:Future<U>, h:Future<V>, #yield:(T,U,V) -> Try<W>) -> Future<W> {
return f.flatmap(executionContext) {fvalue in
g.flatmap(executionContext) {gvalue in
h.map(executionContext) {hvalue in
yield(fvalue, gvalue, hvalue)
}
}
}
}
public func forcomp<T,U, V, W>(f:Future<T>, g:Future<U>, h:Future<V>, #filter:(T,U,V) -> Bool, #yield:(T,U,V) -> Try<W>) -> Future<W> {
return forcomp(f.defaultExecutionContext, f, g, h, filter:filter, yield:yield)
}
public func forcomp<T,U, V, W>(executionContext:ExecutionContext, f:Future<T>, g:Future<U>, h:Future<V>, #filter:(T,U,V) -> Bool, #yield:(T,U,V) -> Try<W>) -> Future<W> {
return f.flatmap(executionContext) {fvalue in
g.flatmap(executionContext) {gvalue in
h.withFilter(executionContext) {hvalue in
filter(fvalue, gvalue, hvalue)
}.map(executionContext) {hvalue in
yield(fvalue, gvalue, hvalue)
}
}
}
}
| 23389ca82d526f866ca42b77aeb9e457 | 32.83558 | 170 | 0.610213 | false | false | false | false |
DrabWeb/Sudachi | refs/heads/master | Sudachi/Sudachi/SCPlaylistTableView.swift | gpl-3.0 | 1 | //
// SCPlaylistTableView.swift
// Sudachi
//
// Created by Seth on 2016-04-02.
//
import Cocoa
class SCPlaylistTableView: NSTableView {
override func drawRect(dirtyRect: NSRect) {
super.drawRect(dirtyRect)
// Drawing code here.
}
override func awakeFromNib() {
// Add the observer for the playlist table view's selection change notification
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("selectionChanged:"), name: NSTableViewSelectionDidChangeNotification, object: nil);
}
/// The timer so playlist items get deselected after the selection doesnt change for 5 seconds
var deselectTimer : NSTimer = NSTimer();
/// When the playlist table view's selection changes...
func selectionChanged(notification : NSNotification) {
// If the notification object was this table view...
if((notification.object as? SCPlaylistTableView) == self) {
// Invalidate the current timer
deselectTimer.invalidate();
// Start a new timer for the deselect wait
deselectTimer = NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(5), target: self, selector: Selector("deselectAllItems"), userInfo: nil, repeats: false);
}
}
/// Deselects all the items for this table view
func deselectAllItems() {
// Deselect all the items
self.deselectAll(self);
}
override func rightMouseDown(theEvent: NSEvent) {
/// The index of the row that was right clicked
let row : Int = self.rowAtPoint(self.convertPoint(theEvent.locationInWindow, fromView: nil));
// Select the row the mouse is over
self.selectRowIndexes(NSIndexSet(index: row), byExtendingSelection: false);
// If the playlist has any items selected...
if(self.selectedRow != -1) {
/// The SCPlaylistTableCellView at the right clicked row index
let cellAtSelectedRow : SCPlaylistTableCellView = (self.rowViewAtRow(row, makeIfNecessary: false)!.subviews[0] as! SCPlaylistTableCellView);
// Display the right click menu for the row
NSMenu.popUpContextMenu(cellAtSelectedRow.menuForEvent(theEvent)!, withEvent: theEvent, forView: cellAtSelectedRow);
}
}
override func mouseDown(theEvent: NSEvent) {
super.mouseDown(theEvent);
/// The index of the row that was clicked
let row : Int = self.rowAtPoint(self.convertPoint(theEvent.locationInWindow, fromView: nil));
// Click the row the cursor is above
(self.rowViewAtRow(row, makeIfNecessary: false)?.subviews[0] as! SCPlaylistTableCellView).mouseDown(theEvent);
}
// Override the alternate row colors
private func alternateBackgroundColor() -> NSColor? {
self.superview?.superview?.superview?.layer?.backgroundColor = SCThemingEngine().defaultEngine().playlistSecondAlternatingColor.CGColor;
return SCThemingEngine().defaultEngine().playlistFirstAlternatingColor;
}
internal override func drawBackgroundInClipRect(clipRect: NSRect) {
// http://stackoverflow.com/questions/3973841/change-nstableview-alternate-row-colors
// Refactored
if(alternateBackgroundColor() == nil) {
// If we didn't set the alternate color, fall back to the default behaviour
super.drawBackgroundInClipRect(clipRect);
}
else {
// Fill in the background color
self.backgroundColor.set();
NSRectFill(clipRect);
// Check if we should be drawing alternating colored rows
if(usesAlternatingRowBackgroundColors) {
// Set the alternating background color
alternateBackgroundColor()!.set();
// Go through all of the intersected rows and draw their rects
var checkRect = bounds;
checkRect.origin.y = clipRect.origin.y;
checkRect.size.height = clipRect.size.height;
let rowsToDraw = rowsInRect(checkRect);
var curRow = rowsToDraw.location;
repeat {
if curRow % 2 != 0 {
// This is an alternate row
var rowRect = rectOfRow(curRow);
rowRect.origin.x = clipRect.origin.x;
rowRect.size.width = clipRect.size.width;
NSRectFill(rowRect);
}
curRow++;
} while curRow < rowsToDraw.location + rowsToDraw.length;
// Figure out the height of "off the table" rows
var thisRowHeight = rowHeight;
if gridStyleMask.contains(NSTableViewGridLineStyle.SolidHorizontalGridLineMask)
|| gridStyleMask.contains(NSTableViewGridLineStyle.DashedHorizontalGridLineMask) {
thisRowHeight += 2.0; // Compensate for a grid
}
// Draw fake rows below the table's last row
var virtualRowOrigin = 0.0 as CGFloat;
var virtualRowNumber = numberOfRows;
if(numberOfRows > 0) {
let finalRect = rectOfRow(numberOfRows-1);
virtualRowOrigin = finalRect.origin.y + finalRect.size.height;
}
repeat {
if virtualRowNumber % 2 != 0 {
// This is an alternate row
let virtualRowRect = NSRect(x: clipRect.origin.x, y: virtualRowOrigin, width: clipRect.size.width, height: thisRowHeight);
NSRectFill(virtualRowRect);
}
virtualRowNumber++;
virtualRowOrigin += thisRowHeight;
} while virtualRowOrigin < clipRect.origin.y + clipRect.size.height;
// Draw fake rows above the table's first row
virtualRowOrigin = -1 * thisRowHeight;
virtualRowNumber = -1;
repeat {
if(abs(virtualRowNumber) % 2 != 0) {
// This is an alternate row
let virtualRowRect = NSRect(x: clipRect.origin.x, y: virtualRowOrigin, width: clipRect.size.width, height: thisRowHeight);
NSRectFill(virtualRowRect);
}
virtualRowNumber--;
virtualRowOrigin -= thisRowHeight;
} while virtualRowOrigin + thisRowHeight > clipRect.origin.y;
}
}
}
} | c8e9e837d3e7c70143d82d9540556628 | 43.816993 | 171 | 0.582847 | false | false | false | false |
kharrison/CodeExamples | refs/heads/master | Container/Container-SB/Container/Location.swift | bsd-3-clause | 2 | //
// Location.swift
// Container
//
// Created by Keith Harrison http://useyourloaf.com
// Copyright (c) 2017 Keith Harrison. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
import CoreLocation
/// A structure representing the location of a point on
/// the map.
struct Location {
/// The name of the location.
let name: String
/// The latitude of the location in degrees.
let latitude: CLLocationDegrees
/// The longitude of the location in degrees.
let longitude: CLLocationDegrees
/// A read-only `CLLocationCoordinate2D` value for the
/// geographic coordinate of the location.
var coordinate: CLLocationCoordinate2D {
return CLLocationCoordinate2DMake(latitude, longitude)
}
}
extension Location {
/// A failable initializer that builds a `Location` from
/// a dictionary of String keys and values. The dictionary
/// must contain at least "name", "latitude" and "longitude"
/// items.
///
/// The values must all be `String` and the `latitude`
/// and `longitude` must convert to a `CLLocationDegrees`
/// value (Double) and specify a valid coordinate. A valid
/// latitude is from -90 to +90 and a valid longitude is
/// from -180 to +180.
///
/// - Parameter dictionary: A dictionary containing the
/// details to initialize the location.
///
/// - Returns: A `Location` structure or `nil` if the
/// dictionary was invalid,
init?(dictionary: Dictionary<String,String>) {
guard let name = dictionary["name"],
let latitudeItem = dictionary["latitude"],
let latitude = CLLocationDegrees(latitudeItem),
let longitudeItem = dictionary["longitude"],
let longitude = CLLocationDegrees(longitudeItem) else {
return nil
}
self.name = name
self.latitude = latitude
self.longitude = longitude
if !CLLocationCoordinate2DIsValid(coordinate) {
return nil
}
}
}
| d4f3b754af200d427626952b6364c2e8 | 35.760417 | 79 | 0.696515 | false | false | false | false |
darina/omim | refs/heads/master | iphone/Maps/Classes/Pages/ImageViewCrossDisolve.swift | apache-2.0 | 5 |
class ImageViewCrossDisolve: UIView {
private var imageViews: [UIImageView] = []
var images: [UIImage?] = [] {
didSet{
imageViews.forEach { (imageView) in
imageView.removeFromSuperview();
}
for image in images{
let imageView = UIImageView(image: image);
self.addSubview(imageView)
imageView.alpha = 0
imageView.contentMode = .scaleAspectFill
imageView.translatesAutoresizingMaskIntoConstraints = false;
imageView.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true
imageView.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true
imageView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
imageView.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true
self.imageViews.append(imageView)
}
updateLayout()
}
}
var pageCount: Int {
return images.count
}
var currentPage: CGFloat = 0.0 {
didSet {
updateLayout()
}
}
private func updateLayout() {
for i in 0..<imageViews.count {
let imageView = imageViews[i]
let progress:CGFloat = currentPage - CGFloat(i)
let alpha = max(CGFloat(0.0), min(CGFloat(1.0), progress+1))
imageView.alpha = alpha
}
}
override func layoutSubviews() {
super.layoutSubviews()
updateLayout()
}
}
| 8df9634463fb5db493cdcd934023e178 | 29.23913 | 89 | 0.662832 | false | false | false | false |
huangboju/QMUI.swift | refs/heads/master | QMUI.swift/QMUIKit/UIComponents/QMUINavigationTitleView.swift | mit | 1 | //
// QMUINavigationTitleView.swift
// QMUI.swift
//
// Created by 伯驹 黄 on 2017/1/17.
// Copyright © 2017年 伯驹 黄. All rights reserved.
//
@objc protocol QMUINavigationTitleViewDelegate {
/**
点击 titleView 后的回调,只需设置 titleView.userInteractionEnabled = YES 后即可使用。不过一般都用于配合 QMUINavigationTitleViewAccessoryTypeDisclosureIndicator。
@param titleView 被点击的 titleView
@param isActive titleView 是否处于活跃状态(所谓的活跃,对应右边的箭头而言,就是点击后箭头向上的状态)
*/
@objc optional func didTouch(_ titleView: QMUINavigationTitleView, isActive: Bool)
/**
titleView 的活跃状态发生变化时会被调用,也即 [titleView setActive:] 被调用时。
@param active 是否处于活跃状态
@param titleView 变换状态的 titleView
*/
@objc optional func didChanged(_ active: Bool, for titleView: QMUINavigationTitleView)
}
/// 设置title和subTitle的布局方式,默认是水平布局。
enum QMUINavigationTitleViewStyle {
case `default` // 水平
case subTitleVertical // 垂直
}
/// 设置titleView的样式,默认没有任何修饰
enum QMUINavigationTitleViewAccessoryType {
case none // 默认
case disclosureIndicator // 有下拉箭头
}
/**
* 可作为navgationItem.titleView 的标题控件。
*
* 支持主副标题,且可控制主副标题的布局方式(水平或垂直);支持在左边显示loading,在右边显示accessoryView(如箭头)。
*
* 默认情况下 titleView 是不支持点击的,需要支持点击的情况下,请把 `userInteractionEnabled` 设为 `YES`。
*
* 若要监听 titleView 的点击事件,有两种方法:
*
* 1. 使用 UIControl 默认的 addTarget:action:forControlEvents: 方式。这种适用于单纯的点击,不需要涉及到状态切换等。
* 2. 使用 QMUINavigationTitleViewDelegate 提供的接口。这种一般配合 titleView.accessoryType 来使用,这样就不用自己去做 accessoryView 的旋转、active 状态的维护等。
*/
class QMUINavigationTitleView: UIControl {
weak var delegate: QMUINavigationTitleViewDelegate?
var style: QMUINavigationTitleViewStyle {
didSet {
if style == .subTitleVertical {
titleLabel.font = verticalTitleFont
updateTitleLabelSize()
subtitleLabel.font = verticalSubtitleFont
updateSubtitleLabelSize()
} else {
titleLabel.font = horizontalTitleFont
updateTitleLabelSize()
subtitleLabel.font = horizontalSubtitleFont
updateSubtitleLabelSize()
}
refreshLayout()
}
}
var isActive = false {
didSet {
delegate?.didChanged?(isActive, for: self)
guard accessoryType == .disclosureIndicator else { return }
let angle: CGFloat = isActive ? -180 : 0.1
UIView.animate(withDuration: 0.25, delay: 0, options: .curveEaseIn, animations: {
self.accessoryTypeView?.transform = CGAffineTransform(rotationAngle: AngleWithDegrees(angle))
}, completion: { _ in
})
}
}
@objc dynamic var maximumWidth: CGFloat = 0 {
didSet {
refreshLayout()
}
}
// MARK: - Titles
private(set) var titleLabel: UILabel!
var title: String? {
didSet {
titleLabel.text = title
updateTitleLabelSize()
refreshLayout()
}
}
private(set) var subtitleLabel: UILabel!
var subtitle: String? {
didSet {
subtitleLabel.text = subtitle
updateSubtitleLabelSize()
refreshLayout()
}
}
/// 水平布局下的标题字体,默认为 NavBarTitleFont
@objc dynamic var horizontalTitleFont = NavBarTitleFont {
didSet {
if style == .default {
titleLabel.font = horizontalTitleFont
updateTitleLabelSize()
refreshLayout()
}
}
}
/// 水平布局下的副标题的字体,默认为 NavBarTitleFont
@objc dynamic var horizontalSubtitleFont = NavBarTitleFont {
didSet {
if style == .default {
subtitleLabel.font = horizontalSubtitleFont
updateSubtitleLabelSize()
refreshLayout()
}
}
}
/// 垂直布局下的标题字体,默认为 UIFontMake(15)
@objc dynamic var verticalTitleFont = UIFontMake(15) {
didSet {
if style == .subTitleVertical {
titleLabel.font = verticalTitleFont
updateTitleLabelSize()
refreshLayout()
}
}
}
/// 垂直布局下的副标题字体,默认为 UIFontLightMake(12)
@objc dynamic var verticalSubtitleFont = UIFontLightMake(12) {
didSet {
if style == .subTitleVertical {
subtitleLabel.font = verticalSubtitleFont
updateSubtitleLabelSize()
refreshLayout()
}
}
}
/// 标题的上下左右间距,当标题不显示时,计算大小及布局时也不考虑这个间距,默认为 UIEdgeInsetsZero
@objc dynamic var titleEdgeInsets = UIEdgeInsets.zero {
didSet {
refreshLayout()
}
}
/// 副标题的上下左右间距,当副标题不显示时,计算大小及布局时也不考虑这个间距,默认为 UIEdgeInsetsZero
@objc dynamic var subtitleEdgeInsets = UIEdgeInsets.zero {
didSet {
refreshLayout()
}
}
// MARK: - Loading
private(set) var loadingView: UIActivityIndicatorView?
/*
* 设置是否需要loading,只有开启了这个属性,loading才有可能显示出来。默认值为false。
*/
var needsLoadingView = false {
didSet {
if needsLoadingView {
if loadingView == nil {
loadingView = UIActivityIndicatorView(activityIndicatorStyle: NavBarActivityIndicatorViewStyle, size: loadingViewSize)
loadingView!.color = tintColor
loadingView!.stopAnimating()
addSubview(loadingView!)
}
} else {
if let loadingView = loadingView {
loadingView.stopAnimating()
loadingView.removeFromSuperview()
self.loadingView = nil
}
}
refreshLayout()
}
}
/*
* `needsLoadingView`开启之后,通过这个属性来控制loading的显示和隐藏,默认值为YES
*
* @see needsLoadingView
*/
var loadingViewHidden = true {
didSet {
if needsLoadingView {
loadingViewHidden ? loadingView?.stopAnimating() : loadingView?.startAnimating()
}
refreshLayout()
}
}
/*
* 如果为true则title居中,loading放在title的左边,title右边有一个跟左边loading一样大的占位空间;如果为false,loading和title整体居中。默认值为true。
*/
var needsLoadingPlaceholderSpace = true {
didSet {
refreshLayout()
}
}
@objc dynamic var loadingViewSize = CGSize(width: 18, height: 18)
/*
* 控制loading距离右边的距离
*/
@objc dynamic var loadingViewMarginRight: CGFloat = 3 {
didSet {
refreshLayout()
}
}
// MARK: - Accessory
/*
* 当accessoryView不为空时,QMUINavigationTitleViewAccessoryType设置无效,一直都是None
*/
private var _accessoryView: UIView?
var accessoryView: UIView? {
get {
return _accessoryView
}
set {
if _accessoryView != accessoryView {
_accessoryView?.removeFromSuperview()
_accessoryView = nil
}
if let accessoryView = accessoryView {
accessoryType = .none
accessoryView.sizeToFit()
addSubview(accessoryView)
}
refreshLayout()
}
}
/*
* 只有当accessoryView为空时才有效
*/
var accessoryType: QMUINavigationTitleViewAccessoryType = .none {
didSet {
if accessoryType == .none {
accessoryTypeView?.removeFromSuperview()
accessoryTypeView = nil
refreshLayout()
return
}
if accessoryTypeView == nil {
accessoryTypeView = UIImageView()
accessoryTypeView!.contentMode = .center
addSubview(accessoryTypeView!)
}
var accessoryImage: UIImage?
if accessoryType == .disclosureIndicator {
accessoryImage = NavBarAccessoryViewTypeDisclosureIndicatorImage?.qmui_image(orientation: .up)
}
accessoryTypeView!.image = accessoryImage
accessoryTypeView!.sizeToFit()
// 经过上面的 setImage 和 sizeToFit 之后再 addSubview,因为 addSubview 会触发系统来询问你的 sizeThatFits:
if accessoryTypeView!.superview != self {
addSubview(accessoryTypeView!)
}
refreshLayout()
}
}
/*
* 用于微调accessoryView的位置
*/
@objc dynamic var accessoryViewOffset: CGPoint = CGPoint(x: 3, y: 0) {
didSet {
refreshLayout()
}
}
/*
* 如果为true则title居中,`accessoryView`放在title的左边或右边;如果为false,`accessoryView`和title整体居中。默认值为false。
*/
var needsAccessoryPlaceholderSpace = false {
didSet {
refreshLayout()
}
}
private var titleLabelSize: CGSize = .zero
private var subtitleLabelSize: CGSize = .zero
private var accessoryTypeView: UIImageView?
convenience override init(frame: CGRect) {
self.init(style: .default, frame: frame)
}
convenience init(style: QMUINavigationTitleViewStyle) {
self.init(style: style, frame: .zero)
}
init(style: QMUINavigationTitleViewStyle, frame: CGRect) {
self.style = .default
super.init(frame: frame)
addTarget(self, action: #selector(handleTouchTitleViewEvent), for: .touchUpInside)
titleLabel = UILabel()
titleLabel.textAlignment = .center
titleLabel.lineBreakMode = .byTruncatingTail
addSubview(titleLabel)
subtitleLabel = UILabel()
subtitleLabel.textAlignment = .center
subtitleLabel.lineBreakMode = .byTruncatingTail
addSubview(subtitleLabel)
isUserInteractionEnabled = false
contentHorizontalAlignment = .center
let appearance = QMUINavigationTitleView.appearance()
maximumWidth = appearance.maximumWidth
loadingViewSize = appearance.loadingViewSize
loadingViewMarginRight = appearance.loadingViewMarginRight
horizontalTitleFont = appearance.horizontalTitleFont
horizontalSubtitleFont = appearance.horizontalSubtitleFont
verticalTitleFont = appearance.verticalTitleFont
verticalSubtitleFont = appearance.verticalSubtitleFont
accessoryViewOffset = appearance.accessoryViewOffset
tintColor = NavBarTitleColor
didInitialized(style)
}
private static let _onceToken = UUID().uuidString
fileprivate func didInitialized(_ style: QMUINavigationTitleViewStyle) {
self.style = style
DispatchQueue.once(token: QMUINavigationTitleView._onceToken) {
QMUINavigationTitleView.setDefaultAppearance()
}
}
override var description: String {
return "\(super.description), title = \(title ?? ""), subtitle = \(subtitle ?? "")"
}
// MARK: - 布局
fileprivate func refreshLayout() {
if let navigationBar = navigationBarSuperview(for: self) {
navigationBar.setNeedsLayout()
}
setNeedsLayout()
}
/// 找到 titleView 所在的 navigationBar(iOS 11 及以后,titleView.superview.superview == navigationBar,iOS 10 及以前,titleView.superview == navigationBar)
///
/// - Parameter subview: titleView
/// - Returns: navigationBar
fileprivate func navigationBarSuperview(for subview: UIView) -> UINavigationBar? {
guard let superview = subview.superview else { return nil }
if superview is UINavigationBar {
return superview as? UINavigationBar
}
return navigationBarSuperview(for: superview)
}
fileprivate func updateTitleLabelSize() {
if !(titleLabel.text?.isEmpty ?? true) {
// 这里用 CGSizeCeil 是特地保证 titleView 的 sizeThatFits 计算出来宽度是 pt 取整,这样在 layoutSubviews 我们以 px 取整时,才能保证不会出现水平居中时出现半像素的问题,然后由于我们对半像素会认为一像素,所以导致总体宽度多了一像素,从而导致文字布局可能出现缩略...
titleLabelSize = titleLabel.sizeThatFits(CGSize.max).sizeCeil
} else {
titleLabelSize = .zero
}
}
fileprivate func updateSubtitleLabelSize() {
if !(subtitleLabel.text?.isEmpty ?? true) {
// 这里用 CGSizeCeil 是特地保证 titleView 的 sizeThatFits 计算出来宽度是 pt 取整,这样在 layoutSubviews 我们以 px 取整时,才能保证不会出现水平居中时出现半像素的问题,然后由于我们对半像素会认为一像素,所以导致总体宽度多了一像素,从而导致文字布局可能出现缩略...
subtitleLabelSize = subtitleLabel.sizeThatFits(CGSize.max).sizeCeil
} else {
subtitleLabelSize = .zero
}
}
fileprivate var loadingViewSpacingSize: CGSize {
if needsLoadingView {
return CGSize(width: loadingViewSize.width + loadingViewMarginRight, height: loadingViewSize.height)
}
return .zero
}
fileprivate var loadingViewSpacingSizeIfNeedsPlaceholder: CGSize {
return CGSize(width: loadingViewSpacingSize.width * (needsLoadingPlaceholderSpace ? 2 : 1), height: loadingViewSpacingSize.height)
}
fileprivate var accessorySpacingSize: CGSize {
if accessoryView != nil || accessoryTypeView != nil {
let view = accessoryView ?? accessoryTypeView
return CGSize(width: view!.bounds.width + accessoryViewOffset.x, height: view!.bounds.height)
}
return .zero
}
fileprivate var accessorySpacingSizeIfNeedesPlaceholder: CGSize {
return CGSize(width: accessorySpacingSize.width * (needsAccessoryPlaceholderSpace ? 2 : 1), height: accessorySpacingSize.height)
}
fileprivate var titleEdgeInsetsIfShowingTitleLabel: UIEdgeInsets {
return titleLabelSize.isEmpty ? .zero : titleEdgeInsets
}
fileprivate var subtitleEdgeInsetsIfShowingSubtitleLabel: UIEdgeInsets {
return subtitleLabelSize.isEmpty ? .zero : subtitleEdgeInsets
}
private var contentSize: CGSize {
if style == .subTitleVertical {
var size = CGSize.zero
// 垂直排列的情况下,loading和accessory与titleLabel同一行
var firstLineWidth = titleLabelSize.width + titleEdgeInsetsIfShowingTitleLabel.horizontalValue
firstLineWidth += loadingViewSpacingSizeIfNeedsPlaceholder.width
firstLineWidth += accessorySpacingSizeIfNeedesPlaceholder.width
let secondLineWidth = subtitleLabelSize.width + subtitleEdgeInsetsIfShowingSubtitleLabel.horizontalValue
size.width = fmax(firstLineWidth, secondLineWidth)
size.height = titleLabelSize.height + titleEdgeInsetsIfShowingTitleLabel.verticalValue + subtitleLabelSize.height + subtitleEdgeInsetsIfShowingSubtitleLabel.verticalValue
return size.flatted
} else {
var size = CGSize.zero
size.width = titleLabelSize.width + titleEdgeInsetsIfShowingTitleLabel.horizontalValue + subtitleLabelSize.width + subtitleEdgeInsetsIfShowingSubtitleLabel.horizontalValue
size.width += loadingViewSpacingSizeIfNeedsPlaceholder.width + accessorySpacingSizeIfNeedesPlaceholder.width
size.height = fmax(titleLabelSize.height + titleEdgeInsetsIfShowingTitleLabel.verticalValue, subtitleLabelSize.height + subtitleEdgeInsetsIfShowingSubtitleLabel.verticalValue)
size.height = fmax(size.height, loadingViewSpacingSizeIfNeedsPlaceholder.height)
size.height = fmax(size.height, accessorySpacingSizeIfNeedesPlaceholder.height)
return size.flatted
}
}
override func sizeThatFits(_ : CGSize) -> CGSize {
var resultSize = contentSize
resultSize.width = fmin(resultSize.width, maximumWidth)
return resultSize
}
override func layoutSubviews() {
if bounds.size.isEmpty {
// print("\(classForCoder), layoutSubviews, size = \(bounds.size)")
return
}
super.layoutSubviews()
let alignLeft = contentHorizontalAlignment == .left
let alignRight = contentHorizontalAlignment == .right
// 通过sizeThatFit计算出来的size,如果大于可使用的最大宽度,则会被系统改为最大限制的最大宽度
let maxSize = bounds.size
// 实际内容的size,小于等于maxSize
var contentSize = self.contentSize
contentSize.width = fmin(maxSize.width, contentSize.width)
contentSize.height = fmin(maxSize.height, contentSize.height)
// 计算左右两边的偏移值
var offsetLeft: CGFloat = 0
var offsetRight: CGFloat = 0
if alignLeft {
offsetLeft = 0
offsetRight = maxSize.width - contentSize.width
} else if alignRight {
offsetLeft = maxSize.width - contentSize.width
offsetRight = 0
} else {
offsetLeft = floorInPixel((maxSize.width - contentSize.width) / 2.0)
offsetRight = offsetLeft
}
// 计算loading占的单边宽度
let loadingViewSpace = loadingViewSpacingSize.width
// 获取当前accessoryView
let accessoryView = self.accessoryView ?? accessoryTypeView
// 计算accessoryView占的单边宽度
let accessoryViewSpace = accessorySpacingSize.width
let isTitleLabelShowing = !(titleLabel.text?.isEmpty ?? true)
let isSubtitleLabelShowing = !(subtitleLabel.text?.isEmpty ?? true)
let titleEdgeInsets = titleEdgeInsetsIfShowingTitleLabel
let subtitleEdgeInsets = subtitleEdgeInsetsIfShowingSubtitleLabel
var minX = offsetLeft + (needsAccessoryPlaceholderSpace ? accessoryViewSpace : 0)
var maxX = maxSize.width - offsetRight - (needsLoadingPlaceholderSpace ? loadingViewSpace : 0)
if style == .subTitleVertical {
if let loadingView = loadingView {
loadingView.frame = loadingView.frame.setXY(minX, titleLabelSize.height.center(loadingViewSize.height) + titleEdgeInsets.top)
minX = loadingView.frame.maxX + loadingViewMarginRight
}
if let accessoryView = accessoryView {
accessoryView.frame = accessoryView.frame.setXY(maxX - accessoryView.bounds.width, titleLabelSize.height.center(accessoryView.bounds.height) + titleEdgeInsets.top + accessoryViewOffset.y)
maxX = accessoryView.frame.minX - accessoryViewOffset.x
}
if isTitleLabelShowing {
minX += titleEdgeInsets.left
maxX -= titleEdgeInsets.right
titleLabel.frame = CGRect(x: minX, y: titleEdgeInsets.top, width: maxX - minX, height: titleLabelSize.height).flatted
} else {
titleLabel.frame = .zero
}
if isSubtitleLabelShowing {
subtitleLabel.frame = CGRect(x: subtitleEdgeInsets.left, y: (isTitleLabelShowing ? titleLabel.frame.maxY + titleEdgeInsets.bottom : 0) + subtitleEdgeInsets.top, width: maxSize.width - subtitleEdgeInsets.horizontalValue, height: subtitleLabelSize.height)
} else {
subtitleLabel.frame = .zero
}
} else {
if let loadingView = loadingView {
loadingView.frame = loadingView.frame.setXY(minX, maxSize.height.center(loadingViewSize.height))
minX = loadingView.frame.maxX + loadingViewMarginRight
}
if let accessoryView = accessoryView {
accessoryView.frame = accessoryView.frame.setXY(maxX - accessoryView.bounds.width, maxSize.height.center(accessoryView.bounds.height) + accessoryViewOffset.y)
maxX = accessoryView.frame.minX - accessoryViewOffset.x
}
if isSubtitleLabelShowing {
maxX -= subtitleEdgeInsets.right
// 如果当前的 contentSize 就是以这个 label 的最大占位计算出来的,那么就不应该先计算 center 再计算偏移
let shouldSubtitleLabelCenterVertically = subtitleLabelSize.height + subtitleEdgeInsets.verticalValue < contentSize.height
let subtitleMinY = shouldSubtitleLabelCenterVertically ? maxSize.height.center(subtitleLabelSize.height) + subtitleEdgeInsets.top - subtitleEdgeInsets.bottom : subtitleEdgeInsets.top
subtitleLabel.frame = CGRect(x: maxX - subtitleLabelSize.width, y: subtitleMinY, width: subtitleLabelSize.width, height: subtitleLabelSize.height)
maxX = subtitleLabel.frame.minX - subtitleEdgeInsets.left
} else {
subtitleLabel.frame = .zero
}
if isTitleLabelShowing {
minX += titleEdgeInsets.left
maxX -= titleEdgeInsets.right
// 如果当前的 contentSize 就是以这个 label 的最大占位计算出来的,那么就不应该先计算 center 再计算偏移
let shouldTitleLabelCenterVertically = titleLabelSize.height + titleEdgeInsets.verticalValue < contentSize.height
let titleLabelMinY = shouldTitleLabelCenterVertically ? maxSize.height.center(titleLabelSize.height) + titleEdgeInsets.top - titleEdgeInsets.bottom : titleEdgeInsets.top
titleLabel.frame = CGRect(x: minX, y: titleLabelMinY, width: maxX - minX, height: titleLabelSize.height)
} else {
titleLabel.frame = .zero
}
}
}
// MARK: - setter / getter
override var contentHorizontalAlignment: UIControl.ContentHorizontalAlignment {
didSet {
refreshLayout()
}
}
override func tintColorDidChange() {
super.tintColorDidChange()
titleLabel.textColor = tintColor
subtitleLabel.textColor = tintColor
loadingView?.color = tintColor
}
// MARK: - Events
override var isHighlighted: Bool {
didSet {
alpha = isHighlighted ? UIControlHighlightedAlpha : 1
}
}
@objc func handleTouchTitleViewEvent() {
let active = !isActive
delegate?.didTouch?(self, isActive: active)
isActive = active
refreshLayout()
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension QMUINavigationTitleView {
static func setDefaultAppearance() {
let appearance = QMUINavigationTitleView.appearance()
appearance.maximumWidth = CGFloat.greatestFiniteMagnitude
appearance.loadingViewSize = CGSize(width: 18, height: 18)
appearance.loadingViewMarginRight = 3
appearance.horizontalTitleFont = NavBarTitleFont
appearance.horizontalSubtitleFont = NavBarTitleFont
appearance.verticalTitleFont = UIFontMake(15)
appearance.verticalSubtitleFont = UIFontLightMake(12)
appearance.accessoryViewOffset = CGPoint(x: 3, y: 0)
appearance.titleEdgeInsets = UIEdgeInsets.zero
appearance.subtitleEdgeInsets = UIEdgeInsets.zero
}
}
| 3eb25930f65e81084c582b4058018b05 | 34.977707 | 269 | 0.637913 | false | false | false | false |
sigmonky/hearthechanges | refs/heads/master | iHearChangesSwift/User Interface/MainDisplayCollectionViewExtensions.swift | mit | 1 | //
// MainDisplayCollectionViewExtensions.swift
// iHearChangesSwift
//
// Created by Randy Weinstein on 6/30/17.
// Copyright © 2017 fakeancient. All rights reserved.
//
import UIKit
// MARK: Collection View Delegates and Helper Methods
extension MainDisplay : UICollectionViewDataSource,UICollectionViewDelegate {
func initializeCollectionView() -> Void {
self.containerView.backgroundColor = UIColor.black
collectionView!.contentInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if progression != nil {
return progression!.chordProgression.count
} else {
return 0;
}
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "measure", for: indexPath) as! MeasureCell
var borderColor: CGColor! = UIColor.clear.cgColor
var borderWidth: CGFloat = 0
cell.chordId.text = measureStates[(indexPath as NSIndexPath).row].display
var textColor:UIColor
print(measureStates[(indexPath as NSIndexPath).row].answerStatus)
switch measureStates[(indexPath as NSIndexPath).row].answerStatus {
case .unanswered:
textColor = UIColor.white
case .correct:
textColor = UIColor.green
case.wrong:
textColor = UIColor.red
}
cell.chordId.textColor = textColor
if measureStates[(indexPath as NSIndexPath).row].selected == true {
borderColor = UIColor.orange.cgColor
borderWidth = 5
} else {
borderColor = UIColor.clear.cgColor
borderWidth = 0
}
cell.image.layer.borderWidth = borderWidth
cell.image.layer.borderColor = borderColor
if (indexPath as NSIndexPath).row == currentMeasure {
cell.image.backgroundColor = UIColor.yellow
cell.chordId.textColor = UIColor.black
} else {
cell.image.backgroundColor = UIColor.black
}
return cell
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if let lastPath = lastSelectedIndexPath {
measureStates[lastPath.row].selected = false
collectionView.reloadItems(at: [lastPath])
}
selectedIndexPath = indexPath
measureStates[(selectedIndexPath?.row)!].selected = true
collectionView.reloadItems(at: [selectedIndexPath!])
lastSelectedIndexPath = indexPath
}
}
extension MainDisplay : UICollectionViewDelegateFlowLayout
{
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = Int(view.bounds.size.width/5.0)
// each image has a ratio of 4:3
let height = Int( Double(width) * 0.75 )
return CGSize(width: width, height: height)
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 2.0, left: 2.0, bottom: 0.0, right: 0.0)
}
}
| 5c208752a3fb721de65a6b4b2b0462ae | 28.852713 | 160 | 0.61101 | false | false | false | false |
samwyndham/DictateSRS | refs/heads/master | Pods/CSV.swift/Sources/CSV.swift | mit | 1 | //
// CSV.swift
// CSV
//
// Created by Yasuhiro Hatta on 2016/06/11.
// Copyright © 2016 yaslab. All rights reserved.
//
import Foundation
private let LF = UnicodeScalar("\n")!
private let CR = UnicodeScalar("\r")!
private let DQUOTE = UnicodeScalar("\"")!
internal let defaultHasHeaderRow = false
internal let defaultTrimFields = false
internal let defaultDelimiter = UnicodeScalar(",")!
extension CSV: Sequence { }
extension CSV: IteratorProtocol {
// TODO: Documentation
/// No overview available.
public mutating func next() -> [String]? {
return readRow()
}
}
// TODO: Documentation
/// No overview available.
public struct CSV {
private var iterator: AnyIterator<UnicodeScalar>
private let trimFields: Bool
private let delimiter: UnicodeScalar
private var back: UnicodeScalar? = nil
internal var currentRow: [String]? = nil
/// CSV header row. To set a value for this property, you set `true` to `hasHeaerRow` in initializer.
public var headerRow: [String]? { return _headerRow }
private var _headerRow: [String]? = nil
private let whitespaces: CharacterSet
internal init<T: IteratorProtocol>(
iterator: T,
hasHeaderRow: Bool,
trimFields: Bool,
delimiter: UnicodeScalar)
throws
where T.Element == UnicodeScalar
{
self.iterator = AnyIterator(iterator)
self.trimFields = trimFields
self.delimiter = delimiter
var whitespaces = CharacterSet.whitespaces
whitespaces.remove(delimiter)
self.whitespaces = whitespaces
if hasHeaderRow {
guard let headerRow = next() else {
throw CSVError.cannotReadHeaderRow
}
_headerRow = headerRow
}
}
/// Create an instance with `InputStream`.
///
/// - parameter stream: An `InputStream` object. If the stream is not open, initializer opens automatically.
/// - parameter codecType: A `UnicodeCodec` type for `stream`.
/// - parameter hasHeaderRow: `true` if the CSV has a header row, otherwise `false`. Default: `false`.
/// - parameter delimiter: Default: `","`.
public init<T: UnicodeCodec>(
stream: InputStream,
codecType: T.Type,
hasHeaderRow: Bool = defaultHasHeaderRow,
trimFields: Bool = defaultTrimFields,
delimiter: UnicodeScalar = defaultDelimiter)
throws
where T.CodeUnit == UInt8
{
let reader = try BinaryReader(stream: stream, endian: .unknown, closeOnDeinit: true)
let iterator = UnicodeIterator(input: reader.makeUInt8Iterator(), inputEncodingType: codecType)
try self.init(iterator: iterator, hasHeaderRow: hasHeaderRow, trimFields: trimFields, delimiter: delimiter)
}
/// Create an instance with `InputStream`.
///
/// - parameter stream: An `InputStream` object. If the stream is not open, initializer opens automatically.
/// - parameter codecType: A `UnicodeCodec` type for `stream`.
/// - parameter endian: Endian to use when reading a stream. Default: `.big`.
/// - parameter hasHeaderRow: `true` if the CSV has a header row, otherwise `false`. Default: `false`.
/// - parameter delimiter: Default: `","`.
public init<T: UnicodeCodec>(
stream: InputStream,
codecType: T.Type,
endian: Endian = .big,
hasHeaderRow: Bool = defaultHasHeaderRow,
trimFields: Bool = defaultTrimFields,
delimiter: UnicodeScalar = defaultDelimiter)
throws
where T.CodeUnit == UInt16
{
let reader = try BinaryReader(stream: stream, endian: endian, closeOnDeinit: true)
let iterator = UnicodeIterator(input: reader.makeUInt16Iterator(), inputEncodingType: codecType)
try self.init(iterator: iterator, hasHeaderRow: hasHeaderRow, trimFields: trimFields, delimiter: delimiter)
}
/// Create an instance with `InputStream`.
///
/// - parameter stream: An `InputStream` object. If the stream is not open, initializer opens automatically.
/// - parameter codecType: A `UnicodeCodec` type for `stream`.
/// - parameter endian: Endian to use when reading a stream. Default: `.big`.
/// - parameter hasHeaderRow: `true` if the CSV has a header row, otherwise `false`. Default: `false`.
/// - parameter delimiter: Default: `","`.
public init<T: UnicodeCodec>(
stream: InputStream,
codecType: T.Type,
endian: Endian = .big,
hasHeaderRow: Bool = defaultHasHeaderRow,
trimFields: Bool = defaultTrimFields,
delimiter: UnicodeScalar = defaultDelimiter)
throws
where T.CodeUnit == UInt32
{
let reader = try BinaryReader(stream: stream, endian: endian, closeOnDeinit: true)
let iterator = UnicodeIterator(input: reader.makeUInt32Iterator(), inputEncodingType: codecType)
try self.init(iterator: iterator, hasHeaderRow: hasHeaderRow, trimFields: trimFields, delimiter: delimiter)
}
fileprivate mutating func readRow() -> [String]? {
currentRow = nil
var next = moveNext()
if next == nil {
return nil
}
var row = [String]()
var field: String
var end: Bool
while true {
if trimFields {
// Trim the leading spaces
while next != nil && whitespaces.contains(next!) {
next = moveNext()
}
}
if next == nil {
(field, end) = ("", true)
}
else if next == DQUOTE {
(field, end) = readField(quoted: true)
}
else {
back = next
(field, end) = readField(quoted: false)
if trimFields {
// Trim the trailing spaces
field = field.trimmingCharacters(in: whitespaces)
}
}
row.append(field)
if end {
break
}
next = moveNext()
}
currentRow = row
return row
}
private mutating func readField(quoted: Bool) -> (String, Bool) {
var field = ""
var next = moveNext()
while let c = next {
if quoted {
if c == DQUOTE {
var cNext = moveNext()
if trimFields {
// Trim the trailing spaces
while cNext != nil && whitespaces.contains(cNext!) {
cNext = moveNext()
}
}
if cNext == nil || cNext == CR || cNext == LF {
if cNext == CR {
let cNextNext = moveNext()
if cNextNext != LF {
back = cNextNext
}
}
// END ROW
return (field, true)
}
else if cNext == delimiter {
// END FIELD
return (field, false)
}
else if cNext == DQUOTE {
// ESC
field.append(String(DQUOTE))
}
else {
// ERROR?
field.append(String(c))
}
}
else {
field.append(String(c))
}
}
else {
if c == CR || c == LF {
if c == CR {
let cNext = moveNext()
if cNext != LF {
back = cNext
}
}
// END ROW
return (field, true)
}
else if c == delimiter {
// END FIELD
return (field, false)
}
else {
field.append(String(c))
}
}
next = moveNext()
}
// END FILE
return (field, true)
}
private mutating func moveNext() -> UnicodeScalar? {
if back != nil {
defer { back = nil }
return back
}
return iterator.next()
}
}
| 89ef881fff7dde6bd3e5fc7100d45449 | 32.280769 | 115 | 0.515775 | false | false | false | false |
Skyvive/JsonSerializer | refs/heads/master | JsonSerializer/JsonSerializer+Deserialization.swift | mit | 2 | //
// JsonSerializer+Deserialization.swift
// JsonSerializer
//
// Created by Bradley Hilton on 4/18/15.
// Copyright (c) 2015 Skyvive. All rights reserved.
//
import Foundation
// MARK: JsonObject+Initialization
extension JsonSerializer {
class func loadJsonDictionary(dictionary: NSDictionary, intoObject object: NSObject) {
for (key, value) in dictionary {
if let key = key as? String,
let mappedKey = propertyKeyForDictionaryKey(key, object: object),
let mappedValue: AnyObject = valueForValue(value, key: mappedKey, object: object) {
object.setValue(mappedValue, forKey: mappedKey)
}
}
}
private class func valueForValue(value: AnyObject, key: String, object: NSObject) -> AnyObject? {
for (propertyName, mirrorType) in properties(object) {
if propertyName == key {
if let mapper = mapperForType(mirrorType.valueType), let jsonValue = JsonValue(value: value) {
return mapper.propertyValueFromJsonValue(jsonValue)
}
}
}
return nil
}
class func properties(object: Any) -> [(String, MirrorType)] {
var properties = [(String, MirrorType)]()
for i in 1..<reflect(object).count {
properties.append(reflect(object)[i])
}
return properties
}
} | 0e9fef5ac412e55986d9d61c85242998 | 31.454545 | 110 | 0.606167 | false | false | false | false |
cornerstonecollege/402 | refs/heads/master | Digby/class_3/SwiftMovingThingsAround/SwiftMovingThingsAround/ViewController.swift | gpl-3.0 | 1 | //
// ViewController.swift
// SwiftMovingThingsAround
//
// Created by Digby Andrews on 2016-06-15.
// Copyright © 2016 Digby Andrews. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var label:UILabel = UILabel()
var isTouching = Bool()
override func viewDidLoad()
{
super.viewDidLoad()
self.label.text = "My Beautiful Label"
self.label.sizeToFit()
self.label.center = self.view.center
self.label.backgroundColor = UIColor.redColor()
self.view.addSubview(self.label)
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?)
{
let touch = touches.first!
let location = touch.locationInView(self.view)
self.isTouching = CGRectContainsPoint(self.label.frame, location);
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?)
{
if self.isTouching
{
let touch = touches.first!
let location = touch.locationInView(self.view)
self.label.center = location
}
}
}
| 7cde9f2f35144ce9645515a9e96e8e0b | 23.88 | 80 | 0.625402 | false | false | false | false |
Where2Go/swiftsina | refs/heads/master | GZWeibo05/Class/Module/Compose/Controller/CZComposeViewController.swift | apache-2.0 | 2 | //
// CZComposeViewController.swift
// GZWeibo05
//
// Created by zhangping on 15/11/3.
// Copyright © 2015年 zhangping. All rights reserved.
//
import UIKit
import SVProgressHUD
class CZComposeViewController: UIViewController {
// MARK: - 属性
/// toolBar底部约束
private var toolBarBottomCon: NSLayoutConstraint?
/// 照片选择器控制器view的底部约束
private var photoSelectorViewBottomCon: NSLayoutConstraint?
/// 微博内容的最大长度
private let statusMaxLength = 20
override func viewDidLoad() {
super.viewDidLoad()
// 需要设置背景颜色,不然弹出时动画有问题
view.backgroundColor = UIColor.whiteColor()
prepareUI()
// 添加键盘frame改变的通知
NSNotificationCenter.defaultCenter().addObserver(self, selector: "willChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
/*
notification:NSConcreteNotification 0x7f8fea5a4e20 {name = UIKeyboardDidChangeFrameNotification; userInfo = {
UIKeyboardAnimationCurveUserInfoKey = 7;
UIKeyboardAnimationDurationUserInfoKey = "0.25"; // 动画时间
UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {375, 258}}";
UIKeyboardCenterBeginUserInfoKey = "NSPoint: {187.5, 796}";
UIKeyboardCenterEndUserInfoKey = "NSPoint: {187.5, 538}";
UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 667}, {375, 258}}";
UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 409}, {375, 258}}"; // 键盘最终的位置
UIKeyboardIsLocalUserInfoKey = 1;
}}
*/
/// 键盘frame改变
func willChangeFrame(notification: NSNotification) {
// print("notification:\(notification)")
// 获取键盘最终位置
let endFrame = notification.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
// 动画时间
let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSTimeInterval
toolBarBottomCon?.constant = -(UIScreen.height() - endFrame.origin.y)
UIView.animateWithDuration(duration) { () -> Void in
// 不能直接更新toolBar的约束
// self.toolBar.layoutIfNeeded()
self.view.layoutIfNeeded()
}
}
// MARK: - 准备UI
private func prepareUI() {
// 添加子控件
view.addSubview(textView)
view.addSubview(photoSelectorVC.view)
view.addSubview(toolBar)
view.addSubview(lengthTipLabel)
setupNavigationBar()
setupTextView()
preparePhotoSelectorView()
setupToolBar()
prepareLengthTipLabel()
}
// override func viewWillAppear(animated: Bool) {
// super.viewWillAppear(animated)
//
// // 弹出键盘
// textView.becomeFirstResponder()
// }
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
// let view = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 10))
// view.backgroundColor = UIColor.redColor()
// textView.inputView = view
// 自定义键盘其实就是给 textView.inputView 赋值
// 如果照片选择器的view没有显示就弹出键盘
if photoSelectorViewBottomCon?.constant != 0 {
textView.becomeFirstResponder()
}
}
/// 设置导航栏
private func setupNavigationBar() {
// 设置按钮, 左边
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
// 右边
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "sendStatus")
navigationItem.rightBarButtonItem?.enabled = false
setupTitleView()
}
/// 设置toolBar
private func setupToolBar() {
// 添加约束
let cons = toolBar.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: CGSize(width: UIScreen.width(), height: 44))
// 获取底部约束
toolBarBottomCon = toolBar.ff_Constraint(cons, attribute: NSLayoutAttribute.Bottom)
// 创建toolBar item
var items = [UIBarButtonItem]()
// 每个item对应的图片名称
let itemSettings = [["imageName": "compose_toolbar_picture", "action": "picture"],
["imageName": "compose_trendbutton_background", "action": "trend"],
["imageName": "compose_mentionbutton_background", "action": "mention"],
["imageName": "compose_emoticonbutton_background", "action": "emoticon"],
["imageName": "compose_addbutton_background", "action": "add"]]
var index = 0
// 遍历 itemSettings 获取图片名称,创建items
for dict in itemSettings {
// 获取图片的名称
let imageName = dict["imageName"]!
// 获取图片对应点点击方法名称
let action = dict["action"]!
let item = UIBarButtonItem(imageName: imageName)
// 获取item里面的按钮
let button = item.customView as! UIButton
button.addTarget(self, action: Selector(action), forControlEvents: UIControlEvents.TouchUpInside)
items.append(item)
// 添加弹簧
items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
index++
}
// 移除最后一个弹簧
items.removeLast()
toolBar.items = items
}
/// 设置导航栏标题
private func setupTitleView() {
let prefix = "发微博"
// 获取用户的名称
if let name = CZUserAccount.loadAccount()?.name {
// 有用户名
let titleName = prefix + "\n" + name
// 创建可变的属性文本
let attrString = NSMutableAttributedString(string: titleName)
// 创建label
let label = UILabel()
// 设置属性文本
label.numberOfLines = 0
label.textAlignment = NSTextAlignment.Center
label.font = UIFont.systemFontOfSize(14)
// 获取NSRange
let nameRange = (titleName as NSString).rangeOfString(name)
// 设置属性文本的属性
attrString.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(12), range: nameRange)
attrString.addAttribute(NSForegroundColorAttributeName, value: UIColor.lightGrayColor(), range: nameRange)
// 顺序不要搞错
label.attributedText = attrString
label.sizeToFit()
navigationItem.titleView = label
} else {
// 没有用户名
navigationItem.title = prefix
}
}
/// 设置textView
private func setupTextView() {
/*
前提:
1.scrollView所在的控制器属于某个导航控制器
2.scrollView控制器的view或者控制器的view的第一个子view
*/
// scrollView会自动设置Insets, 比如scrollView所在的控制器属于某个导航控制器contentInset.top = 64
// automaticallyAdjustsScrollViewInsets = true
// 添加约束
// 相对控制器的view的内部左上角
textView.ff_AlignInner(type: ff_AlignType.TopLeft, referView: view, size: nil)
// 相对toolBar顶部右上角
textView.ff_AlignVertical(type: ff_AlignType.TopRight, referView: toolBar, size: nil)
}
/// 准备 显示微博剩余长度 label
func prepareLengthTipLabel() {
// 添加约束
lengthTipLabel.ff_AlignVertical(type: ff_AlignType.TopRight, referView: toolBar, size: nil, offset: CGPoint(x: -8, y: -8))
}
/// 准备 照片选择器
func preparePhotoSelectorView() {
// 照片选择器控制器的view
let photoSelectorView = photoSelectorVC.view
photoSelectorView.translatesAutoresizingMaskIntoConstraints = false
let views = ["psv": photoSelectorView]
// 添加约束
// 水平
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[psv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
// 高度
view.addConstraint(NSLayoutConstraint(item: photoSelectorView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Height, multiplier: 0.6, constant: 0))
// 底部重合,偏移photoSelectorView的高度
photoSelectorViewBottomCon = NSLayoutConstraint(item: photoSelectorView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: view.frame.height * 0.6)
view.addConstraint(photoSelectorViewBottomCon!)
}
// MARK: - 按钮点击事件
func picture() {
print("图片")
// 让照片选择器的view移动上来
photoSelectorViewBottomCon?.constant = 0
// 退下键盘
textView.resignFirstResponder()
UIView.animateWithDuration(0.25) { () -> Void in
self.view.layoutIfNeeded()
}
}
func trend() {
print("#")
}
func mention() {
print("@")
}
/*
1.textView.inputView == nil 弹出的是系统的键盘
2.正在显示的时候设置 textView.inputView 不会立马起效果
3.在弹出来之前判断使用什么键盘
*/
/// 切换表情键盘
func emoticon() {
print("切换前表情键盘:\(textView.inputView)")
// 先让键盘退回去
textView.resignFirstResponder()
// 延时0.25
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(250 * USEC_PER_SEC)), dispatch_get_main_queue()) { () -> Void in
// 如果inputView == nil 使用的是系统的键盘,切换到自定的键盘
// 如果inputView != nil 使用的是自定义键盘,切换到系统的键盘
self.textView.inputView = self.textView.inputView == nil ? self.emoticonVC.view : nil
// 弹出键盘
self.textView.becomeFirstResponder()
print("切换后表情键盘:\(self.textView.inputView)")
}
}
func add() {
print("加号")
}
/// toolBar item点击事件
// func itemClick(button: UIButton) {
// print(button.tag)
// switch button.tag {
// case 0:
// print("图片")
// case 1:
// print("#")
// case 2:
// print("@")
// case 3:
// print("表情")
// case 4:
// print("加号")
// default:
// print("没有这个按钮")
// }
// }
/// 关闭控制器
@objc private func close() {
// 关闭键盘
textView.resignFirstResponder()
// 关闭sv提示
SVProgressHUD.dismiss()
dismissViewControllerAnimated(true, completion: nil)
}
/// 发微博
func sendStatus() {
// 获取textView的文本内容发送给服务器
let text = textView.emoticonText()
// 判断微博内容的长度 < 0 不发送
let statusLength = text.characters.count
if statusMaxLength - statusLength < 0 {
// 微博内容超出,提示用户
SVProgressHUD.showErrorWithStatus("微博长度超出", maskType: SVProgressHUDMaskType.Black)
return
}
// 获取图片选择器中的图片
let image = photoSelectorVC.photos.first
// 显示正在发送
SVProgressHUD.showWithStatus("正在发布微博...", maskType: SVProgressHUDMaskType.Black)
// 发送微博
CZNetworkTools.sharedInstance.sendStatus(image, status: text) { (result, error) -> () in
if error != nil {
print("error:\(error)")
SVProgressHUD.showErrorWithStatus("网络不给力...", maskType: SVProgressHUDMaskType.Black)
return
}
// 发送成功, 直接关闭界面
self.close()
}
}
// MARK: - 懒加载
/// toolBar
private lazy var toolBar: UIToolbar = {
let toolBar = UIToolbar()
toolBar.backgroundColor = UIColor(white: 0.8, alpha: 1)
return toolBar
}()
/*
iOS中可以让用户输入的控件:
1.UITextField:
1.只能显示一行
2.可以有占位符
3.不能滚动
2.UITextView:
1.可以显示多行
2.没有占位符
3.继承UIScrollView,可以滚动
*/
/// textView
private lazy var textView: CZPlaceholderTextView = {
let textView = CZPlaceholderTextView()
// 当textView被拖动的时候就会将键盘退回,textView能拖动
textView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
textView.font = UIFont.systemFontOfSize(18)
textView.backgroundColor = UIColor.brownColor()
textView.textColor = UIColor.blackColor()
textView.bounces = true
textView.alwaysBounceVertical = true
// 设置占位文本
textView.placeholder = "分享新鲜事..."
// 设置顶部的偏移
// textView.contentInset = UIEdgeInsets(top: 64, left: 0, bottom: 0, right: 0)
// 设置控制器作为textView的代理来监听textView文本的改变
textView.delegate = self
return textView
}()
/// 表情键盘控制器
private lazy var emoticonVC: CZEmoticonViewController = {
let controller = CZEmoticonViewController()
// 设置textView
controller.textView = self.textView
return controller
}()
/// 显示微博剩余长度
private lazy var lengthTipLabel: UILabel = {
let label = UILabel(fonsize: 12, textColor: UIColor.lightGrayColor())
// 设置默认的长度
label.text = String(self.statusMaxLength)
return label
}()
/// 照片选择器的控制器
private lazy var photoSelectorVC: CZPhotoSelectorViewController = {
let controller = CZPhotoSelectorViewController()
// 让照片选择控制器被被人管理
self.addChildViewController(controller)
return controller
}()
}
extension CZComposeViewController: UITextViewDelegate {
/// textView文本改变的时候调用
func textViewDidChange(textView: UITextView) {
// 当textView 有文本的时候,发送按钮可用,
// 当textView 没有文本的时候,发送按钮不可用
navigationItem.rightBarButtonItem?.enabled = textView.hasText()
// 计算剩余微博的长度
let statusLength = textView.emoticonText().characters.count
// 剩余长度
let length = statusMaxLength - statusLength
lengthTipLabel.text = String(length)
// 判断 length 大于等于0显示灰色, 小于0显示红色
lengthTipLabel.textColor = length < 0 ? UIColor.redColor() : UIColor.lightGrayColor()
}
}
| 16021d998538bac2a475fe8c5947a9cf | 30.409978 | 253 | 0.576865 | false | false | false | false |
Khan/Cartography | refs/heads/master | Carthage/Checkouts/Cartography/Cartography/Context.swift | mit | 4 | //
// Context.swift
// Cartography
//
// Created by Robert Böhnke on 06/10/14.
// Copyright (c) 2014 Robert Böhnke. All rights reserved.
//
#if os(iOS) || os(tvOS)
import UIKit
#else
import AppKit
#endif
public class Context {
internal var constraints: [Constraint] = []
#if os(iOS) || os(tvOS)
internal func addConstraint(from: Property, to: LayoutSupport, coefficients: Coefficients = Coefficients(), relation: NSLayoutRelation = .Equal) -> NSLayoutConstraint {
from.view.car_translatesAutoresizingMaskIntoConstraints = false
let layoutConstraint = NSLayoutConstraint(item: from.view,
attribute: from.attribute,
relatedBy: relation,
toItem: to.layoutGuide,
attribute: to.attribute,
multiplier: CGFloat(coefficients.multiplier),
constant: CGFloat(coefficients.constant))
var view = from.view
while let superview = view.superview {
view = superview
}
constraints.append(Constraint(view: view, layoutConstraint: layoutConstraint))
return layoutConstraint
}
#endif
internal func addConstraint(from: Property, to: Property? = nil, coefficients: Coefficients = Coefficients(), relation: NSLayoutRelation = .Equal) -> NSLayoutConstraint {
from.view.car_translatesAutoresizingMaskIntoConstraints = false
let layoutConstraint = NSLayoutConstraint(item: from.view,
attribute: from.attribute,
relatedBy: relation,
toItem: to?.view,
attribute: to?.attribute ?? .NotAnAttribute,
multiplier: CGFloat(coefficients.multiplier),
constant: CGFloat(coefficients.constant))
if let to = to {
if let common = closestCommonAncestor(from.view, b: to.view ) {
constraints.append(Constraint(view: common, layoutConstraint: layoutConstraint))
} else {
fatalError("No common superview found between \(from.view) and \(to.view)")
}
} else {
constraints.append(Constraint(view: from.view, layoutConstraint: layoutConstraint))
}
return layoutConstraint
}
internal func addConstraint(from: Compound, coefficients: [Coefficients]? = nil, to: Compound? = nil, relation: NSLayoutRelation = NSLayoutRelation.Equal) -> [NSLayoutConstraint] {
var results: [NSLayoutConstraint] = []
for i in 0..<from.properties.count {
let n: Coefficients = coefficients?[i] ?? Coefficients()
results.append(addConstraint(from.properties[i], coefficients: n, to: to?.properties[i], relation: relation))
}
return results
}
}
| 51294fffe0622ed987aec0a9a4a22003 | 41.688312 | 184 | 0.535747 | false | false | false | false |
pennlabs/penn-mobile-ios | refs/heads/main | PennMobile/Home/Cells/News/HomeNewsCellItem.swift | mit | 1 | //
// HomeNewsCellItem.swift
// PennMobile
//
// Created by Josh Doman on 2/7/19.
// Copyright © 2019 PennLabs. All rights reserved.
//
import Foundation
final class HomeNewsCellItem: HomeCellItem {
static var jsonKey = "news"
static var associatedCell: ModularTableViewCell.Type = HomeNewsCell.self
let article: NewsArticle
var showSubtitle = true
init(for article: NewsArticle) {
self.article = article
}
static func getHomeCellItem(_ completion: @escaping (([HomeCellItem]) -> Void)) {
let task = URLSession.shared.dataTask(with: URL(string: "https://labs-graphql-295919.ue.r.appspot.com/graphql?query=%7BlabsArticle%7Bslug,headline,abstract,published_at,authors%7Bname%7D,dominantMedia%7BimageUrl,authors%7Bname%7D%7D,tag,content%7D%7D")!) { data, _, _ in
guard let data = data else { completion([]); return }
if let article = try? JSONDecoder().decode(NewsArticle.self, from: data) {
completion([HomeNewsCellItem(for: article)])
} else {
completion([])
}
}
task.resume()
}
func equals(item: ModularTableViewItem) -> Bool {
guard let item = item as? HomeNewsCellItem else { return false }
return article.data.labsArticle.headline == item.article.data.labsArticle.headline
}
}
// MARK: - Logging ID
extension HomeNewsCellItem: LoggingIdentifiable {
var id: String {
return article.data.labsArticle.slug
}
}
| a3052085ee117c54daed5adedc1664a2 | 32.444444 | 278 | 0.659136 | false | false | false | false |
leejayID/Linkage-Swift | refs/heads/master | Linkage/CollectionView/CollectionCategoryModel.swift | apache-2.0 | 1 | //
// CollectionCategoryModel.swift
// Linkage
//
// Created by LeeJay on 2017/3/10.
// Copyright © 2017年 LeeJay. All rights reserved.
//
import UIKit
class CollectionCategoryModel: NSObject {
var name : String?
var subcategories : [SubCategoryModel]?
init(dict : [String : Any]) {
super.init()
setValuesForKeys(dict)
}
override func setValue(_ value: Any?, forKey key: String) {
if key == "subcategories" {
subcategories = Array()
guard let datas = value as? [[String : Any]] else { return }
for dict in datas {
let subModel = SubCategoryModel(dict: dict)
subcategories?.append(subModel)
}
} else {
super.setValue(value, forKey: key)
}
}
override func setValue(_ value: Any?, forUndefinedKey key: String) {
}
}
class SubCategoryModel: NSObject {
var iconUrl : String?
var name : String?
init(dict : [String : Any]) {
super.init()
setValuesForKeys(dict)
}
override func setValue(_ value: Any?, forKey key: String) {
if key == "icon_url" {
guard let icon = value as? String else { return }
iconUrl = icon
} else {
super.setValue(value, forKey: key)
}
}
override func setValue(_ value: Any?, forUndefinedKey key: String) {
}
}
| 6cf4cbc6f047887469dc0f51e30b0224 | 22.078125 | 72 | 0.540961 | false | false | false | false |
stormpath/stormpath-sdk-swift | refs/heads/develop | Stormpath/Networking/ResetPasswordAPIRequestManager.swift | apache-2.0 | 1 | //
// ResetPasswordAPIRequestManager.swift
// Stormpath
//
// Created by Edward Jiang on 2/8/16.
// Copyright © 2016 Stormpath. All rights reserved.
//
import Foundation
typealias ResetPasswordAPIRequestCallback = ((NSError?) -> Void)
class ResetPasswordAPIRequestManager: APIRequestManager {
var email: String
var callback: ResetPasswordAPIRequestCallback
init(withURL url: URL, email: String, callback: @escaping ResetPasswordAPIRequestCallback) {
self.email = email
self.callback = callback
super.init(withURL: url)
}
override func prepareForRequest() {
request.httpMethod = "POST"
request.httpBody = try? JSONSerialization.data(withJSONObject: ["email": email], options: [])
}
override func requestDidFinish(_ data: Data, response: HTTPURLResponse) {
performCallback(nil)
}
override func performCallback(_ error: NSError?) {
DispatchQueue.main.async {
self.callback(error)
}
}
}
| 9395fd46c774f0ad5cef723270614be9 | 26.052632 | 101 | 0.668288 | false | false | false | false |
vasilyjp/tech_salon_ios_twitter_client | refs/heads/master | TwitterClient/TwitterFeedTableViewController.swift | mit | 1 | //
// TwitterFeedTableViewController.swift
// TwitterClient
//
// Created by Nicholas Maccharoli on 2016/09/26.
// Copyright © 2016 Vasily inc. All rights reserved.
//
import UIKit
import Accounts
import SVProgressHUD
final class TwitterFeedTableViewController: UITableViewController {
fileprivate var tweets: [Tweet] = []
fileprivate var isLoading: Bool = false
override func viewDidLoad() {
super.viewDidLoad()
setupTableView()
requestAccountPermision()
}
}
// MARK: - UITableViewDataSource
extension TwitterFeedTableViewController {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tweets.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
loadNextTweetsIfNeeded(indexPath: indexPath)
let cellId = String(describing: TweetCell.self)
let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! TweetCell
if tweets.count > indexPath.row {
cell.tweet = tweets[indexPath.row]
}
return cell
}
}
// MARK: - Private
private extension TwitterFeedTableViewController {
func setupTableView() {
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 100.0
}
func requestAccountPermision() {
TweetsRequest.requestPermission() { [weak self] _, _ in
guard let twitterAccount = TweetsRequest.firstAccount() else { return }
DispatchQueue.main.async {
if let username = twitterAccount.username {
self?.title = "@\(username)"
}
self?.loadNextTweets()
}
}
}
private func loadNextTweets() {
if isLoading { return }
let isRefreshFromRefreshControl = tableView.refreshControl?.isRefreshing ?? false
if !isRefreshFromRefreshControl {
SVProgressHUD.show()
}
isLoading = true
let maxId = maxTweetId()
TweetsRequest.timeline(maxId: maxId) { [weak self] tweets, _ in
guard let _self = self else { return }
_self.isLoading = false
if let tweets = tweets {
_self.tweets += tweets
_self.tableView.reloadData()
}
SVProgressHUD.dismiss()
if isRefreshFromRefreshControl {
_self.tableView.refreshControl?.endRefreshing()
}
}
}
private func refreshRequest() {
isLoading = true
tableView.refreshControl?.beginRefreshing()
TweetsRequest.timeline(maxId: nil) { [weak self] tweets, _ in
guard let _self = self else { return }
_self.isLoading = false
if let tweets = tweets {
_self.tweets = tweets
_self.tableView.reloadData()
}
_self.tableView.refreshControl?.endRefreshing()
}
}
private func maxTweetId() -> Int64? {
let oldestTweet: Tweet? = tweets.sorted(by: { $0.id < $1.id }).first
return oldestTweet.flatMap {
if $0.id > 0 {
return $0.id - 1
}
return nil
}
}
func loadNextTweetsIfNeeded(indexPath: IndexPath) {
let threshold: Int = TweetsRequest.requestMaxTweetCount
let shouldLoad = (tweets.count - indexPath.row) < threshold
if shouldLoad {
loadNextTweets()
}
}
@IBAction private func refresh() {
tweets = []
refreshRequest()
}
}
| e0a56b71c6e311597e18b8beee613a7c | 25.568345 | 109 | 0.597076 | false | false | false | false |
jedisct1/swift-sodium | refs/heads/master | Sodium/SecretBox.swift | isc | 1 | import Foundation
import Clibsodium
public struct SecretBox {
public let MacBytes = Int(crypto_secretbox_macbytes())
public typealias MAC = Bytes
}
extension SecretBox {
/**
Encrypts a message with a shared secret key.
- Parameter message: The message to encrypt.
- Parameter secretKey: The shared secret key.
- Returns: A `Bytes` object containing the nonce and authenticated ciphertext.
*/
public func seal(message: Bytes, secretKey: Key) -> Bytes? {
guard let (authenticatedCipherText, nonce): (Bytes, Nonce) = seal(
message: message,
secretKey: secretKey
) else { return nil }
return nonce + authenticatedCipherText
}
/**
Encrypts a message with a shared secret key.
- Parameter message: The message to encrypt.
- Parameter secretKey: The shared secret key.
- Returns: The authenticated ciphertext and encryption nonce.
*/
public func seal(message: Bytes, secretKey: Key) -> (authenticatedCipherText: Bytes, nonce: Nonce)? {
let nonce = self.nonce()
guard let authenticatedCipherText = seal(message: message, secretKey: secretKey, nonce: nonce) else {
return nil
}
return (authenticatedCipherText: authenticatedCipherText, nonce: nonce)
}
/**
Encrypts a message with a shared secret key and a user-provided nonce.
- Parameter message: The message to encrypt.
- Parameter secretKey: The shared secret key.
- Parameter nonce: The encryption nonce.
- Returns: The authenticated ciphertext.
*/
public func seal(message: Bytes, secretKey: Key, nonce: Nonce) -> Bytes? {
guard secretKey.count == KeyBytes else { return nil }
var authenticatedCipherText = Bytes(count: message.count + MacBytes)
guard .SUCCESS == crypto_secretbox_easy (
&authenticatedCipherText,
message, UInt64(message.count),
nonce,
secretKey
).exitCode else { return nil }
return authenticatedCipherText
}
/**
Encrypts a message with a shared secret key (detached mode).
- Parameter message: The message to encrypt.
- Parameter secretKey: The shared secret key.
- Returns: The encrypted ciphertext, encryption nonce, and authentication tag.
*/
public func seal(message: Bytes, secretKey: Key) -> (cipherText: Bytes, nonce: Nonce, mac: MAC)? {
guard secretKey.count == KeyBytes else { return nil }
var cipherText = Bytes(count: message.count)
var mac = Bytes(count: MacBytes)
let nonce = self.nonce()
guard .SUCCESS == crypto_secretbox_detached (
&cipherText,
&mac,
message, UInt64(message.count),
nonce,
secretKey
).exitCode else { return nil }
return (cipherText: cipherText, nonce: nonce, mac: mac)
}
}
extension SecretBox {
/**
Decrypts a message with a shared secret key.
- Parameter nonceAndAuthenticatedCipherText: A `Bytes` object containing the nonce and authenticated ciphertext.
- Parameter secretKey: The shared secret key.
- Returns: The decrypted message.
*/
public func open(nonceAndAuthenticatedCipherText: Bytes, secretKey: Key) -> Bytes? {
guard nonceAndAuthenticatedCipherText.count >= MacBytes + NonceBytes else { return nil }
let nonce = nonceAndAuthenticatedCipherText[..<NonceBytes].bytes as Nonce
let authenticatedCipherText = nonceAndAuthenticatedCipherText[NonceBytes...].bytes
return open(authenticatedCipherText: authenticatedCipherText, secretKey: secretKey, nonce: nonce)
}
/**
Decrypts a message with a shared secret key and encryption nonce.
- Parameter authenticatedCipherText: The authenticated ciphertext.
- Parameter secretKey: The shared secret key.
- Parameter nonce: The encryption nonce.
- Returns: The decrypted message.
*/
public func open(authenticatedCipherText: Bytes, secretKey: Key, nonce: Nonce) -> Bytes? {
guard authenticatedCipherText.count >= MacBytes else { return nil }
var message = Bytes(count: authenticatedCipherText.count - MacBytes)
guard .SUCCESS == crypto_secretbox_open_easy (
&message,
authenticatedCipherText, UInt64(authenticatedCipherText.count),
nonce,
secretKey
).exitCode else { return nil }
return message
}
/**
Decrypts a message with a shared secret key, encryption nonce, and authentication tag.
- Parameter cipherText: The encrypted ciphertext.
- Parameter secretKey: The shared secret key.
- Parameter nonce: The encryption nonce.
- Returns: The decrypted message.
*/
public func open(cipherText: Bytes, secretKey: Key, nonce: Nonce, mac: MAC) -> Bytes? {
guard nonce.count == NonceBytes,
mac.count == MacBytes,
secretKey.count == KeyBytes
else { return nil }
var message = Bytes(count: cipherText.count)
guard .SUCCESS == crypto_secretbox_open_detached (
&message,
cipherText,
mac,
UInt64(cipherText.count),
nonce,
secretKey
).exitCode else { return nil }
return message
}
}
extension SecretBox: NonceGenerator {
public var NonceBytes: Int { return Int(crypto_secretbox_noncebytes()) }
public typealias Nonce = Bytes
}
extension SecretBox: SecretKeyGenerator {
public typealias Key = Bytes
public var KeyBytes: Int { return Int(crypto_secretbox_keybytes()) }
public static let keygen: (_ k: UnsafeMutablePointer<UInt8>) -> Void = crypto_secretbox_keygen
}
| 359c9a0c2d5a5d4f918ef07b3fe2c923 | 32.350575 | 117 | 0.652766 | false | false | false | false |
gkaimakas/SwiftyForms | refs/heads/master | SwiftyForms/Classes/Inputs/SwitchInput.swift | mit | 1 | //
// SwitchInput.swift
// Pods
//
// Created by Γιώργος Καϊμακάς on 25/05/16.
//
//
import Foundation
open class SwitchInput: Input {
open static let OnValue = String(true)
open static let OffValue = String(false)
public convenience init(name: String) {
self.init(name: name, enabled: true, hidden: true)
}
public override init(name: String, enabled: Bool, hidden: Bool) {
super.init(name: name, enabled: enabled, hidden: hidden)
}
open var isOn: Bool {
return value == SwitchInput.OnValue
}
open func on() {
self.value = SwitchInput.OnValue
}
open func off() {
self.value = SwitchInput.OffValue
}
open func toogle() {
self.value = (isOn) ? SwitchInput.OffValue : SwitchInput.OnValue
}
}
| 86f2e0f184692268915ddff913b477ab | 17.820513 | 66 | 0.679837 | false | false | false | false |
xivol/MCS-V3-Mobile | refs/heads/master | examples/uiKit/UIKitCatalog.playground/Pages/UIView.xcplaygroundpage/Contents.swift | mit | 1 | //: # UIView
//: The `UIView` class defines a rectangular area on the screen and the interfaces for managing the content in that area.
//:
//: [UIView API Refernce](https://developer.apple.com/reference/uikit/uiview)
import UIKit
import PlaygroundSupport
//: ### View Frame
let containerView = UIView(frame: CGRect(x: 0, y: 0, width: 250, height: 250))
let subviews = [
UIView(frame: CGRect(x: 10, y: 10, width: 110, height: 110)),
UIView(frame: CGRect(x: 10, y: 130, width: 110, height: 110)),
UIView(frame: CGRect(x: 130, y: 10, width: 110, height: 110)),
UIView(frame: CGRect(x: 130, y: 130, width: 110, height: 110)),
]
subviews.forEach { containerView.addSubview($0) }
subviews[0].backgroundColor = #colorLiteral(red: 0.9529411793, green: 0.6862745285, blue: 0.1333333403, alpha: 1)
subviews[1].backgroundColor = #colorLiteral(red: 0.9254902005, green: 0.2352941185, blue: 0.1019607857, alpha: 1)
subviews[2].backgroundColor = #colorLiteral(red: 0.2392156869, green: 0.6745098233, blue: 0.9686274529, alpha: 1)
subviews[3].backgroundColor = #colorLiteral(red: 0.4666666687, green: 0.7647058964, blue: 0.2666666806, alpha: 1)
containerView.backgroundColor = #colorLiteral(red: 0.2549019754, green: 0.2745098174, blue: 0.3019607961, alpha: 1)
//: ### Subview Order
let circle = UIView(frame: CGRect(x: 75, y: 75, width: 100, height: 100))
circle.layer.cornerRadius = circle.bounds.width / 2
circle.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
containerView.insertSubview(circle, at: 1)
containerView.sendSubview(toBack: subviews[3])
//: ### View Bounds
subviews[1].bounds = CGRect(x: -10, y: -10, width: 120, height: 120)
subviews[2].bounds.size = CGSize(width: 90, height: 90)
// Populate view with subviews
let dotCount = 6
for i in 0..<dotCount + 1 {
for j in 0..<dotCount {
let dotSize = CGSize(width: subviews[1].bounds.width / CGFloat(dotCount), height: subviews[1].bounds.width / CGFloat(dotCount))
let originX = subviews[1].bounds.origin.x + (0.25 + CGFloat(i) - CGFloat(j % 2) / 2) * dotSize.width
let originY = subviews[1].bounds.origin.y + (0.25 + CGFloat(j)) * dotSize.height
let dot = UIView(frame: CGRect(x: originX, y: originY, width: dotSize.width / 2, height: dotSize.height / 2))
dot.backgroundColor = #colorLiteral(red: 0.9568627477, green: 0.6588235497, blue: 0.5450980663, alpha: 1)
dot.layer.cornerRadius = dot.bounds.width / 2
subviews[1].addSubview(dot)
}
}
//: Set bounds to clip subviews
subviews[1].clipsToBounds = true
//: ### View Masks
let patternDepth = 4
// Populate view with subviews
for i in 1...patternDepth {
let width = subviews[3].bounds.width / CGFloat(pow(sqrt(2), Double(i)))
let offset = (subviews[3].bounds.width - width) / 2
let squareFrame = CGRect(x: subviews[3].bounds.origin.x + offset,
y: subviews[3].bounds.origin.y + offset,
width: width, height: width)
let square = UIView(frame: squareFrame)
square.backgroundColor = i % 2 == 0 ? #colorLiteral(red: 0.4666666687, green: 0.7647058964, blue: 0.2666666806, alpha: 1) : #colorLiteral(red: 0.1960784346, green: 0.3411764801, blue: 0.1019607857, alpha: 1)
// View transform
square.transform = CGAffineTransform.init(rotationAngle: CGFloat(M_PI_4 * Double(i)))
subviews[3].addSubview(square)
}
//: Create mask
let circleMask = UIView(frame: CGRect(origin: CGPoint.zero, size: subviews[3].frame.size))
circleMask.layer.cornerRadius = circleMask.bounds.width / 2
//: Without any content view is transparent - it cannot be used as mask. By setting its color we allow it to be used as a mask
circleMask.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
subviews[3].mask = circleMask
PlaygroundPage.current.liveView = containerView
//: [Previous](@previous) | [Table of Contents](TableOfContents) | [Next](@next)
| 6691f3b19be20868bb7c1366d194b40f | 50.894737 | 211 | 0.689909 | false | false | false | false |
BelledonneCommunications/linphone-iphone | refs/heads/master | Classes/Swift/Voip/Widgets/CallControlButton.swift | gpl-3.0 | 1 | /*
* Copyright (c) 2010-2020 Belledonne Communications SARL.
*
* This file is part of linphone-iphone
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import Foundation
import UIKit
import SwiftUI
class CallControlButton : ButtonWithStateBackgrounds {
// Layout constants
static let default_size = 50
static let hungup_width = 65
var showActivityIndicatorDataSource : MutableLiveData<Bool>? = nil {
didSet {
if let showActivityIndicatorDataSource = self.showActivityIndicatorDataSource {
let spinner = UIActivityIndicatorView(style: .white)
spinner.color = VoipTheme.primary_color
self.addSubview(spinner)
spinner.matchParentDimmensions().center().done()
showActivityIndicatorDataSource.readCurrentAndObserve { (show) in
if (show == true) {
spinner.startAnimating()
spinner.isHidden = false
self.isEnabled = false
} else {
spinner.stopAnimating()
spinner.isHidden = true
self.isEnabled = true
}
}
}
}
}
var onClickAction : (()->Void)? = nil
required init?(coder: NSCoder) {
super.init(coder: coder)
}
init (width:Int = CallControlButton.default_size, height:Int = CallControlButton.default_size, imageInset:UIEdgeInsets = UIEdgeInsets(top: 2, left: 2, bottom: 2, right: 2), buttonTheme: ButtonTheme, onClickAction : (()->Void)? = nil ) {
super.init(backgroundStateColors: buttonTheme.backgroundStateColors)
layer.cornerRadius = CGFloat(height/2)
clipsToBounds = true
contentMode = .scaleAspectFit
applyTintedIcons(tintedIcons: buttonTheme.tintableStateIcons)
imageView?.contentMode = .scaleAspectFit
imageEdgeInsets = imageInset
size(w: CGFloat(width), h: CGFloat(height)).done()
self.onClickAction = onClickAction
onClick {
self.onClickAction?()
}
}
}
| eeab81331d3724f7651fabc4aa7d99f0 | 27.588235 | 238 | 0.718107 | false | false | false | false |
XWebView/XWebView | refs/heads/master | XWebView/XWVJson.swift | apache-2.0 | 2 | /*
Copyright 2015 XWebView
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
// JSON Array
public func jsonify<T: Collection>(_ array: T) -> String?
where T.Index: BinaryInteger {
// TODO: filter out values with negative index
return "[" + array.map{jsonify($0) ?? ""}.joined(separator: ",") + "]"
}
// JSON Object
public func jsonify<T: Collection, V>(_ object: T) -> String?
where T.Iterator.Element == (key: String, value: V) {
return "{" + object.flatMap(jsonify).joined(separator: ",") + "}"
}
private func jsonify<T>(_ pair: (key: String, value: T)) -> String? {
guard let val = jsonify(pair.value) else { return nil }
return jsonify(pair.key)! + ":" + val
}
// JSON Number
public func jsonify<T: BinaryInteger>(_ integer: T) -> String? {
return String(describing: integer)
}
public func jsonify<T: FloatingPoint>(_ float: T) -> String? {
return String(describing: float)
}
// JSON Boolean
public func jsonify(_ bool: Bool) -> String? {
return String(describing: bool)
}
// JSON String
public func jsonify<T: StringProtocol>(_ string: T) -> String? {
return string.unicodeScalars.reduce("\"") { $0 + $1.jsonEscaped } + "\""
}
private extension UnicodeScalar {
var jsonEscaped: String {
switch value {
case 0...7: fallthrough
case 11, 14, 15: return "\\u000" + String(value, radix: 16)
case 16...31: fallthrough
case 127...159: return "\\u00" + String(value, radix: 16)
case 8: return "\\b"
case 12: return "\\f"
case 39: return "'"
default: return escaped(asASCII: false)
}
}
}
@objc public protocol ObjCJSONStringable {
var jsonString: String? { get }
}
public protocol CustomJSONStringable {
var jsonString: String? { get }
}
extension CustomJSONStringable where Self: RawRepresentable {
public var jsonString: String? {
return jsonify(rawValue)
}
}
public func jsonify(_ value: Any?) -> String? {
guard let value = value else { return "null" }
switch (value) {
case is Void:
return "undefined"
case is NSNull:
return "null"
case let s as String:
return jsonify(s)
case let n as NSNumber:
if CFGetTypeID(n) == CFBooleanGetTypeID() {
return n.boolValue.description
}
return n.stringValue
case let a as Array<Any?>:
return jsonify(a)
case let d as Dictionary<String, Any?>:
return jsonify(d)
case let s as CustomJSONStringable:
return s.jsonString
case let o as ObjCJSONStringable:
return o.jsonString
case let d as Data:
return d.withUnsafeBytes {
(base: UnsafePointer<UInt8>) -> String? in
jsonify(UnsafeBufferPointer<UInt8>(start: base, count: d.count))
}
default:
let mirror = Mirror(reflecting: value)
guard let style = mirror.displayStyle else { return nil }
switch style {
case .optional: // nested optional
return jsonify(mirror.children.first?.value)
case .collection, .set, .tuple: // array-like type
return jsonify(mirror.children.map{$0.value})
case .class, .dictionary, .struct:
return "{" + mirror.children.flatMap(jsonify).joined(separator: ",") + "}"
case .enum:
return jsonify(String(describing: value))
}
}
}
private func jsonify(_ child: Mirror.Child) -> String? {
if let key = child.label {
return jsonify((key: key, value: child.value))
}
let m = Mirror(reflecting: child.value)
guard m.children.count == 2, m.displayStyle == .tuple,
let key = m.children.first!.value as? String else {
return nil
}
let val = m.children[m.children.index(after: m.children.startIndex)].value
return jsonify((key: key, value: val))
}
| 9a445998fa9ebbb413e49ca529bd8e17 | 31.20438 | 86 | 0.62874 | false | false | false | false |
Eonil/EditorLegacy | refs/heads/trial1 | Modules/EonilFileSystemEvents/Project/TestdriveApp/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// TestdriveApp
//
// Created by Hoon H. on 11/12/14.
// Copyright (c) 2014 Eonil. All rights reserved.
//
import Cocoa
import EonilFileSystemEvents
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate, NSTableViewDataSource, NSTableViewDelegate {
@IBOutlet weak var tableView:NSTableView!
@IBOutlet weak var window:NSWindow!
struct Item {
let flags:String
let path:String
}
var items = [] as [Item]
var monitor = nil as FileSystemEventMonitor?
var queue = dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0)
func applicationDidFinishLaunching(aNotification: NSNotification) {
/////////////////////////////////////////////////////////////////
// Here's the core of example.
/////////////////////////////////////////////////////////////////
let onEvents = { (events:[FileSystemEvent]) -> () in
dispatch_async(dispatch_get_main_queue()) {
self.items.append(Item(flags: "----", path: "----")) // Visual separator.
self.tableView.insertRowsAtIndexes(NSIndexSet(index: self.items.count-1), withAnimation: NSTableViewAnimationOptions.EffectNone)
for ev in events {
self.items.append(Item(flags: ev.flag.description, path: ev.path))
self.tableView.insertRowsAtIndexes(NSIndexSet(index: self.items.count-1), withAnimation: NSTableViewAnimationOptions.EffectNone)
}
self.tableView.scrollToEndOfDocument(self)
}
}
monitor = FileSystemEventMonitor(pathsToWatch: ["/", "/Users"], latency: 0, watchRoot: false, queue: queue, callback: onEvents)
/////////////////////////////////////////////////////////////////
// Here's the core of example.
/////////////////////////////////////////////////////////////////
}
func applicationWillTerminate(aNotification: NSNotification) {
// Insert code here to tear down your application
}
func numberOfRowsInTableView(tableView: NSTableView) -> Int {
return items.count
}
// func tableView(tableView: NSTableView, objectValueForTableColumn tableColumn: NSTableColumn?, row: Int) -> AnyObject? {
// let m1 = items[row]
// switch tableColumn!.identifier {
// case "TYPE": return m1.type
// case "PATH": return m1.path
// default: fatalError()
// }
// }
func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn?, row: Int) -> NSView? {
let tv1 = NSTextField()
let iv1 = NSImageView()
let cv1 = NSTableCellView()
cv1.textField = tv1
cv1.imageView = iv1
cv1.addSubview(tv1)
cv1.addSubview(iv1)
cv1.textField!.bordered = false
cv1.textField!.backgroundColor = NSColor.clearColor()
cv1.textField!.editable = false
(cv1.textField!.cell() as! NSCell).lineBreakMode = NSLineBreakMode.ByTruncatingHead
let n1 = items[row]
switch tableColumn!.identifier {
case "PATH":
iv1.image = NSWorkspace.sharedWorkspace().iconForFile(n1.path)
cv1.textField!.stringValue = n1.path
case "TYPE":
cv1.textField!.stringValue = n1.flags
default:
break
}
return cv1
}
}
| 369f5f71d53bbc09d660cc9df0eb75a6 | 30.715789 | 133 | 0.652506 | false | false | false | false |
FabioTacke/RingSig | refs/heads/master | Sources/RingSig/RSA.swift | mit | 1 | //
// RSA.swift
// RingSig
//
// Created by Fabio Tacke on 14.06.17.
//
//
import Foundation
import BigInt
public class RSA {
public static func generateKeyPair(length: Int = 128) -> KeyPair {
// Choose two distinct prime numbers
let p = BigUInt.randomPrime(length: length)
var q = BigUInt.randomPrime(length: length)
while p == q {
q = BigUInt.randomPrime(length: length)
}
// Calculate modulus and private key d
let n = p * q
let phi = (p-1) * (q-1)
let d = PublicKey.e.inverse(phi)!
return KeyPair(privateKey: d, publicKey: PublicKey(n: n))
}
public static func sign(message: BigUInt, privateKey: PrivateKey, publicKey: PublicKey) -> Signature {
return message.power(privateKey, modulus: publicKey.n)
}
public static func verify(message: BigUInt, signature: Signature, publicKey: PublicKey) -> Bool {
return signature.power(PublicKey.e, modulus: publicKey.n) == message
}
public struct KeyPair {
public let privateKey: PrivateKey
public let publicKey: PublicKey
}
public struct PublicKey: Hashable {
public let n: BigUInt
public static let e = BigUInt(65537)
public var hashValue: Int {
return n.hashValue
}
public static func ==(lhs: RSA.PublicKey, rhs: RSA.PublicKey) -> Bool {
return lhs.n == rhs.n
}
}
public typealias PrivateKey = BigUInt
public typealias Signature = BigUInt
}
| 4b2a974f67ca3753015b0d079ceb68d2 | 24.051724 | 104 | 0.655196 | false | false | false | false |
jisudong555/swift | refs/heads/master | weibo/weibo/Classes/Home/StatusNormalCell.swift | mit | 1 | //
// StatusNormalCell.swift
// weibo
//
// Created by jisudong on 16/5/20.
// Copyright © 2016年 jisudong. All rights reserved.
//
import UIKit
class StatusNormalCell: StatusCell {
override var status: Status?
{
didSet {
pictureView.status = status
let size = pictureView.calculateImageSize()
makeConstraints(size)
}
}
private func makeConstraints(pictureSize: CGSize)
{
let topSpace = pictureSize.height == 0 ? 0 : 10
pictureView.snp_updateConstraints { (make) in
make.top.equalTo(contentLabel.snp_bottom).offset(topSpace)
make.size.equalTo(pictureSize)
}
}
static let fakeCell = StatusNormalCell()
class func cellHeightWithModel(model: Status) -> CGFloat
{
if (fabs(model.cellHeight - 0.0) < 0.00000001)
{
fakeCell.status = model
model.cellHeight = fakeCell.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height
}
return model.cellHeight
}
}
| 6ab0a63d70583a0855d04a1cf69f97c0 | 23.466667 | 105 | 0.600363 | false | false | false | false |
Esri/arcgis-runtime-samples-ios | refs/heads/main | arcgis-ios-sdk-samples/Layers/Stretch renderer/StretchRendererViewController.swift | apache-2.0 | 1 | //
// Copyright 2016 Esri.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
import ArcGIS
class StretchRendererViewController: UIViewController, StretchRendererSettingsViewControllerDelegate {
@IBOutlet var mapView: AGSMapView!
private weak var rasterLayer: AGSRasterLayer?
override func viewDidLoad() {
super.viewDidLoad()
// add the source code button item to the right of navigation bar
(navigationItem.rightBarButtonItem as! SourceCodeBarButtonItem).filenames = ["StretchRendererViewController", "StretchRendererSettingsViewController", "StretchRendererInputCell", "OptionsTableViewController"]
// create raster
let raster = AGSRaster(name: "ShastaBW", extension: "tif")
// create raster layer using the raster
let rasterLayer = AGSRasterLayer(raster: raster)
self.rasterLayer = rasterLayer
// initialize a map with raster layer as the basemap
let map = AGSMap(basemap: AGSBasemap(baseLayer: rasterLayer))
// assign map to the map view
mapView.map = map
}
// MARK: - StretchRendererSettingsViewControllerDelegate
func stretchRendererSettingsViewController(_ stretchRendererSettingsViewController: StretchRendererSettingsViewController, didSelectStretchParameters parameters: AGSStretchParameters) {
let renderer = AGSStretchRenderer(stretchParameters: parameters, gammas: [], estimateStatistics: true, colorRamp: AGSColorRamp(type: .none, size: 1))
rasterLayer?.renderer = renderer
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let navController = segue.destination as? UINavigationController,
let controller = navController.viewControllers.first as? StretchRendererSettingsViewController {
controller.delegate = self
controller.preferredContentSize = CGSize(width: 375, height: 135)
navController.presentationController?.delegate = self
}
}
}
extension StretchRendererViewController: UIAdaptivePresentationControllerDelegate {
func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle {
return .none
}
}
| 29902a111a32e7ad28b57b1794a14852 | 42.30303 | 216 | 0.724983 | false | false | false | false |
SeptAi/Cooperate | refs/heads/master | Cooperate/Cooperate/Class/ViewModel/MessageViewModel.swift | mit | 1 | //
// MessageViewModel.swift
// Cooperate
//
// Created by J on 2017/1/17.
// Copyright © 2017年 J. All rights reserved.
//
import UIKit
class MessageViewModel: CustomStringConvertible {
// 项目模型
var notice:Notice
// 标题
var title:String?
// 作者
var author:String?
// 内容
var content:String?
// 正文的属性文本
var normalAttrText:NSAttributedString?
// 结束时间
var endAt:Date?
// 行高 -- 预留
var rowHeight:CGFloat = 0
init(model:Notice) {
self.notice = model
title = model.title
author = model.author
content = model.content
endAt = model.endAt
// 字体
let normalFont = UIFont.systemFont(ofSize:15)
// FIXME: - 表情
normalAttrText = NSAttributedString(string: model.content ?? " ", attributes: [NSFontAttributeName:normalFont,NSForegroundColorAttributeName:UIColor.darkGray])
// 计算行高
updateRowHeight()
}
// 根据当前模型内容计算行高
func updateRowHeight(){
rowHeight = 100
}
var description: String{
return notice.description
}
}
| c0752fbb64c66ce68246eba6056ccb87 | 19.642857 | 167 | 0.57872 | false | false | false | false |
DouKing/WYListView | refs/heads/master | WYListViewController/ListViewController/Views/WYSegmentCell.swift | mit | 1 | //
// WYSegmentCell.swift
// WYListViewController
//
// Created by iosci on 2016/10/20.
// Copyright © 2016年 secoo. All rights reserved.
//
import UIKit
class WYSegmentCell: UICollectionViewCell {
@IBOutlet weak var titleButton: UIButton!
static let contentInsert: CGFloat = 40
class func width(withTitle title: String?) -> CGFloat {
let t = NSString(string: (title == nil) ? "请选择" : title!)
let width = t.boundingRect(with: CGSize(width: CGFloat.greatestFiniteMagnitude, height: 0),
options: [.usesFontLeading, .usesLineFragmentOrigin, .truncatesLastVisibleLine],
attributes: [NSFontAttributeName : UIFont.systemFont(ofSize: 13)],
context: nil).size.width
return width + WYSegmentCell.contentInsert * 2
}
func setup(withTitle title: String?) {
if let text = title {
titleButton.setTitleColor(UIColor.black, for: .normal)
titleButton.setTitle(text, for: .normal)
} else {
titleButton.setTitleColor(UIColor.lightGray, for: .normal)
titleButton.setTitle("请选择", for: .normal)
}
}
}
| 723b81adea83fb676ea1b6f8479fac7c | 34.028571 | 115 | 0.60522 | false | false | false | false |
tluquet3/MonTennis | refs/heads/master | MonTennisTests/Match.swift | apache-2.0 | 1 | //
// Match.swift
// MonTennis
//
// Created by Thomas Luquet on 21/05/2015.
// Copyright (c) 2015 Thomas Luquet. All rights reserved.
//
import Foundation
class Match {
var resultat: Bool
var firstName: String
var lastName: String
var classement: Classement
var coef: Double
var bonus: Bool
var wo: Bool
init(resultat: Bool,firstName: String, lastName:String, classement: Classement,bonus: Bool, coef: Double, wo: Bool ){
self.resultat = resultat
self.firstName = firstName
self.lastName = lastName
self.classement = classement
self.bonus = bonus
self.coef = coef
self.wo = wo
}
} | d1468ef058e6865811c331d8dd49c837 | 21.548387 | 121 | 0.624642 | false | false | false | false |
darkzero/SimplePlayer | refs/heads/master | SimplePlayer/Player/MusicPlayer.swift | mit | 1 | //
// MusicPlayer.swift
// SimplePlayer
//
// Created by Lihua Hu on 2014/06/16.
// Copyright (c) 2014 darkzero. All rights reserved.
//
import UIKit
import AVFoundation
import MediaPlayer
// propeties
protocol EnumProtocol {
var simpleDescription: String { get }
mutating func adjust()
}
enum RepeatType : EnumProtocol{
case Off, On, One;
var simpleDescription: String {
get {
return self.getDescription()
}
}
func getDescription() -> String{
switch self{
case .Off:
return "No Repeat"
case .On:
return "Repeat is On"
case .One:
return "Repeat one song"
default:
return "Nothing"
}
}
mutating func adjust() -> Void{
self = RepeatType.Off;
}
}
enum ShuffleMode {
case Off, On;
}
class MusicPlayer: NSObject {
var currectTime = 0.0;
var repeat = RepeatType.Off;
var shuffle = ShuffleMode.Off;
var player:MPMusicPlayerController = MPMusicPlayerController.iPodMusicPlayer();
required override init() {
super.init();
// add notifications lisener
self.player.beginGeneratingPlaybackNotifications();
self.registeriPodPlayerNotifications();
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self);
}
class func defaultPlayer() -> MusicPlayer {
struct Static {
static var instance: MusicPlayer? = nil
static var onceToken: dispatch_once_t = 0
}
dispatch_once(&Static.onceToken) {
Static.instance = self()
}
return Static.instance!
}
func registeriPodPlayerNotifications() {
let notiCenter:NSNotificationCenter = NSNotificationCenter.defaultCenter();
notiCenter.addObserver(self,
selector: "onRecivePlaybackStateDidChangeNotification:",
name : MPMusicPlayerControllerPlaybackStateDidChangeNotification,
object : player);
notiCenter.addObserver(self,
selector: "onReciveNowPlayingItemDidChangeNotification:",
name : MPMusicPlayerControllerNowPlayingItemDidChangeNotification,
object : nil);
notiCenter.addObserver(self,
selector: "onReciveVolumeDidChangeNotification:",
name : MPMusicPlayerControllerVolumeDidChangeNotification,
object : nil);
}
var currentPlaybackTime : CGFloat {
get { return CGFloat(self.player.currentPlaybackTime); }
}
var nowPlayingTitle : NSString {
get {
if (( self.player.nowPlayingItem ) != nil) {
//NSLog("title : %s", self.player.nowPlayingItem.title);
return self.player.nowPlayingItem.title;
}
else {
return "";
}
}
}
var nowPlayingArtist : NSString {
get {
if (( self.player.nowPlayingItem ) != nil) {
return self.player.nowPlayingItem.artist;
}
else {
return "";
}
}
}
var nowPlayingArtwork : UIImage {
get {
if (( self.player.nowPlayingItem ) != nil) {
var pler:MPMusicPlayerController = MPMusicPlayerController.iPodMusicPlayer();
var item:MPMediaItem = self.player.nowPlayingItem;
var image:UIImage = item.artwork.imageWithSize(CGSizeMake(200, 200));
return image;
//return MusicPlayer.defaultPlayer().player.nowPlayingItem.artwork.imageWithSize(CGSizeMake(200, 200));
//return UIImage(named: "defaultArtwork");
}
else {
return UIImage(named: "defaultArtwork");
}
}
}
var playbackDuration : CGFloat {
get {
if (( self.player.nowPlayingItem ) != nil) {
return CGFloat(self.player.nowPlayingItem.playbackDuration);
}
else {
return 0.0;
}
}
}
// on playback state changed
func onRecivePlaybackStateDidChangeNotification(noti:NSNotification) {
var userInfo:NSDictionary = NSDictionary(object: noti.name, forKey: "NotificationName");
NSNotificationCenter.defaultCenter().postNotificationName("needRefreshPlayerViewNotification", object: self, userInfo: userInfo);
}
// on playing item changed
func onReciveNowPlayingItemDidChangeNotification(noti:NSNotification) {
var userInfo:NSDictionary = NSDictionary(object: noti.name, forKey: "NotificationName");
NSNotificationCenter.defaultCenter().postNotificationName("needRefreshPlayerViewNotification", object: self, userInfo: userInfo);
}
// on volume changed
func onReciveVolumeDidChangeNotification(noti:NSNotification) {
var userInfo:NSDictionary = NSDictionary(object: noti.name, forKey: "NotificationName");
NSNotificationCenter.defaultCenter().postNotificationName("needRefreshPlayerViewNotification", object: self, userInfo: userInfo);
}
}
| 340448c5a2acd478e844efc730c638f1 | 28.958824 | 137 | 0.621245 | false | false | false | false |
CodaFi/swift-compiler-crashes | refs/heads/master | crashes-fuzzing/04616-swift-parser-parseversiontuple.swift | mit | 11 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
case c
i> c : d = [Void{
let start = B<Int>: e) -> Void{
func c,
let f = [Void{
protocol c : b { func a
("\(false)?
protocol e : S<e>
func b<T where S<T where T>: Any).C(false)?
{
case c
protocol c : b { func b
Void{
protocol c : a<T where T.e = [Void{
class
case c
(e : b { func b<T>
class B<T where S<T where S<T where T>
struct S<T where S
0.e = []
protocol e : Any)?
let f = B<Int>(object1: e) -> c {
protocol c { func a<T where T: (f: d<T where S<T: b { func b<T>: (e : d = T>(object1: e) -> Void{
{
{
class
class B<Int>: (f: b { func a
i> Void{
"
func a
"
let start = [Void{
{
i> c : Any)?
i> c : S<T: d = B<U : ([Void{
Void{
let start = compose(((e : b { func a<T : a
{
func b
class d
class d<T.C
func b
0.e : b { e) -> c { e) -> c {
class
0.C
Void{
(e : d = compose((object1: (([Void{
{
let f = [[Void{
protocol e : S
func a<e) -> c : d = B<Int>(e : d = B<U : e) -> Void{
class
func a
func b
func c,
class B<T where T: d
protocol c : Any)?
struct A {
class
0.C
protocol e : Any).C
protocol c {
(object1: c {
class B<T>("
struct A {
{
let f = B<T where T: d
0.C(false)?
Void{
{
class
let start = T: S
0.C
let end = []
class d<T>(e : b { func b
protocol c : b { e>: b { func b<Int>: b { e>
class B<U : d<T where S<e) -> Void{
case c
class B<Int>: a<T>(e = T: B<T where S<T
| ea86a50022ea05ceedeca507352406f4 | 16.445783 | 97 | 0.582182 | false | false | false | false |
keyacid/keyacid-iOS | refs/heads/master | keyacid/SignViewController.swift | bsd-3-clause | 1 | //
// SignViewController.swift
// keyacid
//
// Created by Yuan Zhou on 6/24/17.
// Copyright © 2017 yvbbrjdr. All rights reserved.
//
import UIKit
class SignViewController: UIViewController {
@IBOutlet weak var signature: UITextField!
@IBOutlet weak var textView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
textView.inputAccessoryView = DoneView.init(frame: CGRect.init(x: 0, y: 0, width: 0, height: 40), textBox: textView)
}
func getSelectedRemoteProfile() -> RemoteProfile? {
if ProfilesTableViewController.selectedRemoteProfileIndex == -1 {
let remoteProfileNotSelected: UIAlertController = UIAlertController.init(title: "Error", message: "You have to select a remote profile!", preferredStyle: .alert)
let OKAction: UIAlertAction = UIAlertAction.init(title: "OK", style: .default, handler: { (action: UIAlertAction) in
self.performSegue(withIdentifier: "ShowProfiles", sender: self)
})
remoteProfileNotSelected.addAction(OKAction)
self.present(remoteProfileNotSelected, animated: true, completion: nil)
return nil
}
return ProfilesTableViewController.remoteProfiles[ProfilesTableViewController.selectedRemoteProfileIndex]
}
func getSelectedLocalProfile() -> LocalProfile? {
if ProfilesTableViewController.selectedLocalProfileIndex == -1 {
let localProfileNotSelected: UIAlertController = UIAlertController.init(title: "Error", message: "You have to select a local profile!", preferredStyle: .alert)
let OKAction: UIAlertAction = UIAlertAction.init(title: "OK", style: .default, handler: { (action: UIAlertAction) in
self.performSegue(withIdentifier: "ShowProfiles", sender: self)
})
localProfileNotSelected.addAction(OKAction)
self.present(localProfileNotSelected, animated: true, completion: nil)
return nil
}
return ProfilesTableViewController.localProfiles[ProfilesTableViewController.selectedLocalProfileIndex]
}
@IBAction func signClicked() {
let localProfile: LocalProfile? = getSelectedLocalProfile()
if localProfile == nil {
return
}
let sig: String = Crypto.sign(data: textView.text.data(using: String.Encoding.utf8)!, from: localProfile!).base64EncodedString()
if sig == "" {
let empty: UIAlertController = UIAlertController.init(title: "Error", message: "Corrupted profile!", preferredStyle: .alert)
let OKAction: UIAlertAction = UIAlertAction.init(title: "OK", style: .default, handler: nil)
empty.addAction(OKAction)
self.present(empty, animated: true, completion: nil)
return
}
signature.text = sig
UIPasteboard.general.string = sig
}
@IBAction func verifyClicked() {
let sig: Data? = Data.init(base64Encoded: signature.text!)
if sig == nil {
let notBase64: UIAlertController = UIAlertController.init(title: "Error", message: "Invalid signature!", preferredStyle: .alert)
let OKAction: UIAlertAction = UIAlertAction.init(title: "OK", style: .default, handler: nil)
notBase64.addAction(OKAction)
self.present(notBase64, animated: true, completion: nil)
return
}
let remoteProfile: RemoteProfile? = getSelectedRemoteProfile()
if remoteProfile == nil {
return
}
if Crypto.verify(data: textView.text.data(using: String.Encoding.utf8)!, signature: sig!, from: remoteProfile!) {
let success: UIAlertController = UIAlertController.init(title: "Success", message: "This message is signed by " + remoteProfile!.name + "!", preferredStyle: .alert)
let OKAction: UIAlertAction = UIAlertAction.init(title: "OK", style: .default, handler: nil)
success.addAction(OKAction)
self.present(success, animated: true, completion: nil)
} else {
let error: UIAlertController = UIAlertController.init(title: "Error", message: "Wrong profile or tampered data!", preferredStyle: .alert)
let OKAction: UIAlertAction = UIAlertAction.init(title: "OK", style: .default, handler: nil)
error.addAction(OKAction)
self.present(error, animated: true, completion: nil)
}
}
@IBAction func signatureDone() {
signature.resignFirstResponder()
}
}
| e7b1d7180c87b24b54b5a0cbac893728 | 47.795699 | 176 | 0.663508 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.