repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
Constructor-io/constructorio-client-swift
AutocompleteClient/FW/Logic/Result/CIOFilterFacetOption.swift
1
1488
// // CIOFilterFacetOption.swift // AutocompleteClient // // Copyright © Constructor.io. All rights reserved. // http://constructor.io/ // import Foundation /** Struct encapsulating a filter facet option with information about the status and results associated with it. */ public struct CIOFilterFacetOption { /** The number of results that will be returned when selected */ public let count: Int /** Display name of the facet option */ public let displayName: String /** Status of the facet option (i.e. "selected" or "") */ public let status: String /** The facet value */ public let value: String /** Additional metadata for the facet option */ public let data: [String: Any] } public extension CIOFilterFacetOption { /** Create a filter facet option - Parameters: - json: JSON data from server response */ init?(json: JSONObject) { guard let count = json["count"] as? Int else { return nil } guard let displayName = json["display_name"] as? String else { return nil } guard let status = json["status"] as? String else { return nil } guard let value = json["value"] as? String else { return nil } let data = json["data"] as? [String: Any] ?? [:] self.count = count self.value = value self.status = status self.displayName = displayName self.data = data } }
mit
f51961601ca70ee22601879e067ba459
22.603175
109
0.61197
4.386431
false
false
false
false
whiteath/ReadFoundationSource
Foundation/JSONSerialization.swift
2
39969
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // import CoreFoundation #if os(OSX) || os(iOS) import Darwin #elseif os(Linux) || CYGWIN import Glibc #endif extension JSONSerialization { public struct ReadingOptions : OptionSet { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let mutableContainers = ReadingOptions(rawValue: 1 << 0) public static let mutableLeaves = ReadingOptions(rawValue: 1 << 1) public static let allowFragments = ReadingOptions(rawValue: 1 << 2) internal static let useReferenceNumericTypes = ReadingOptions(rawValue: 1 << 15) } public struct WritingOptions : OptionSet { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let prettyPrinted = WritingOptions(rawValue: 1 << 0) public static let sortedKeys = WritingOptions(rawValue: 1 << 1) } } /* A class for converting JSON to Foundation/Swift objects and converting Foundation/Swift objects to JSON. An object that may be converted to JSON must have the following properties: - Top level object is a `Swift.Array` or `Swift.Dictionary` - All objects are `Swift.String`, `Foundation.NSNumber`, `Swift.Array`, `Swift.Dictionary`, or `Foundation.NSNull` - All dictionary keys are `Swift.String`s - `NSNumber`s are not NaN or infinity */ open class JSONSerialization : NSObject { /* Determines whether the given object can be converted to JSON. Other rules may apply. Calling this method or attempting a conversion are the definitive ways to tell if a given object can be converted to JSON data. - parameter obj: The object to test. - returns: `true` if `obj` can be converted to JSON, otherwise `false`. */ open class func isValidJSONObject(_ obj: Any) -> Bool { // TODO: - revisit this once bridging story gets fully figured out func isValidJSONObjectInternal(_ obj: Any?) -> Bool { // Emulate the SE-0140 behavior bridging behavior for nils guard let obj = obj else { return true } // object is Swift.String, NSNull, Int, Bool, or UInt if obj is String || obj is NSNull || obj is Int || obj is Bool || obj is UInt { return true } // object is a Double and is not NaN or infinity if let number = obj as? Double { return number.isFinite } // object is a Float and is not NaN or infinity if let number = obj as? Float { return number.isFinite } // object is Swift.Array if let array = obj as? [Any?] { for element in array { guard isValidJSONObjectInternal(element) else { return false } } return true } // object is Swift.Dictionary if let dictionary = obj as? [String: Any?] { for (_, value) in dictionary { guard isValidJSONObjectInternal(value) else { return false } } return true } // object is NSNumber and is not NaN or infinity // For better performance, this (most expensive) test should be last. if let number = _SwiftValue.store(obj) as? NSNumber { let invalid = number.doubleValue.isInfinite || number.doubleValue.isNaN return !invalid } // invalid object return false } // top level object must be an Swift.Array or Swift.Dictionary guard obj is [Any?] || obj is [String: Any?] else { return false } return isValidJSONObjectInternal(obj) } /* Generate JSON data from a Foundation object. If the object will not produce valid JSON then an exception will be thrown. Setting the NSJSONWritingPrettyPrinted option will generate JSON with whitespace designed to make the output more readable. If that option is not set, the most compact possible JSON will be generated. If an error occurs, the error parameter will be set and the return value will be nil. The resulting data is a encoded in UTF-8. */ internal class func _data(withJSONObject value: Any, options opt: WritingOptions, stream: Bool) throws -> Data { var jsonStr = String() var writer = JSONWriter( pretty: opt.contains(.prettyPrinted), sortedKeys: opt.contains(.sortedKeys), writer: { (str: String?) in if let str = str { jsonStr.append(str) } } ) if let container = value as? NSArray { try writer.serializeJSON(container._bridgeToSwift()) } else if let container = value as? NSDictionary { try writer.serializeJSON(container._bridgeToSwift()) } else if let container = value as? Array<Any> { try writer.serializeJSON(container) } else if let container = value as? Dictionary<AnyHashable, Any> { try writer.serializeJSON(container) } else { fatalError("Top-level object was not NSArray or NSDictionary") // This is a fatal error in objective-c too (it is an NSInvalidArgumentException) } let count = jsonStr.lengthOfBytes(using: .utf8) let bufferLength = count+1 // Allow space for null terminator var utf8: [CChar] = Array<CChar>(repeating: 0, count: bufferLength) if !jsonStr.getCString(&utf8, maxLength: bufferLength, encoding: .utf8) { fatalError("Failed to generate a CString from a String") } let rawBytes = UnsafeRawPointer(UnsafePointer(utf8)) let result = Data(bytes: rawBytes.bindMemory(to: UInt8.self, capacity: count), count: count) return result } open class func data(withJSONObject value: Any, options opt: WritingOptions = []) throws -> Data { return try _data(withJSONObject: value, options: opt, stream: false) } /* Create a Foundation object from JSON data. Set the NSJSONReadingAllowFragments option if the parser should allow top-level objects that are not an NSArray or NSDictionary. Setting the NSJSONReadingMutableContainers option will make the parser generate mutable NSArrays and NSDictionaries. Setting the NSJSONReadingMutableLeaves option will make the parser generate mutable NSString objects. If an error occurs during the parse, then the error parameter will be set and the result will be nil. The data must be in one of the 5 supported encodings listed in the JSON specification: UTF-8, UTF-16LE, UTF-16BE, UTF-32LE, UTF-32BE. The data may or may not have a BOM. The most efficient encoding to use for parsing is UTF-8, so if you have a choice in encoding the data passed to this method, use UTF-8. */ open class func jsonObject(with data: Data, options opt: ReadingOptions = []) throws -> Any { return try data.withUnsafeBytes { (bytes: UnsafePointer<UInt8>) -> Any in let encoding: String.Encoding let buffer: UnsafeBufferPointer<UInt8> if let detected = parseBOM(bytes, length: data.count) { encoding = detected.encoding buffer = UnsafeBufferPointer(start: bytes.advanced(by: detected.skipLength), count: data.count - detected.skipLength) } else { encoding = detectEncoding(bytes, data.count) buffer = UnsafeBufferPointer(start: bytes, count: data.count) } let source = JSONReader.UnicodeSource(buffer: buffer, encoding: encoding) let reader = JSONReader(source: source) if let (object, _) = try reader.parseObject(0, options: opt) { return object } else if let (array, _) = try reader.parseArray(0, options: opt) { return array } else if opt.contains(.allowFragments), let (value, _) = try reader.parseValue(0, options: opt) { return value } throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.propertyListReadCorrupt.rawValue, userInfo: [ "NSDebugDescription" : "JSON text did not start with array or object and option to allow fragments not set." ]) } } /* Write JSON data into a stream. The stream should be opened and configured. The return value is the number of bytes written to the stream, or 0 on error. All other behavior of this method is the same as the dataWithJSONObject:options:error: method. */ open class func writeJSONObject(_ obj: Any, toStream stream: OutputStream, options opt: WritingOptions) throws -> Int { let jsonData = try _data(withJSONObject: obj, options: opt, stream: true) let count = jsonData.count return jsonData.withUnsafeBytes { (bytePtr: UnsafePointer<UInt8>) -> Int in let res: Int = stream.write(bytePtr, maxLength: count) /// TODO: If the result here is negative the error should be obtained from the stream to propigate as a throw return res } } /* Create a JSON object from JSON data stream. The stream should be opened and configured. All other behavior of this method is the same as the JSONObjectWithData:options:error: method. */ open class func jsonObject(with stream: InputStream, options opt: ReadingOptions = []) throws -> Any { var data = Data() guard stream.streamStatus == .open || stream.streamStatus == .reading else { fatalError("Stream is not available for reading") } repeat { var buffer = [UInt8](repeating: 0, count: 1024) var bytesRead: Int = 0 bytesRead = stream.read(&buffer, maxLength: buffer.count) if bytesRead < 0 { throw stream.streamError! } else { data.append(&buffer, count: bytesRead) } } while stream.hasBytesAvailable return try jsonObject(with: data, options: opt) } } //MARK: - Encoding Detection internal extension JSONSerialization { /// Detect the encoding format of the NSData contents class func detectEncoding(_ bytes: UnsafePointer<UInt8>, _ length: Int) -> String.Encoding { if length >= 4 { switch (bytes[0], bytes[1], bytes[2], bytes[3]) { case (0, 0, 0, _): return .utf32BigEndian case (_, 0, 0, 0): return .utf32LittleEndian case (0, _, 0, _): return .utf16BigEndian case (_, 0, _, 0): return .utf16LittleEndian default: break } } else if length >= 2 { switch (bytes[0], bytes[1]) { case (0, _): return .utf16BigEndian case (_, 0): return .utf16LittleEndian default: break } } return .utf8 } static func parseBOM(_ bytes: UnsafePointer<UInt8>, length: Int) -> (encoding: String.Encoding, skipLength: Int)? { if length >= 2 { switch (bytes[0], bytes[1]) { case (0xEF, 0xBB): if length >= 3 && bytes[2] == 0xBF { return (.utf8, 3) } case (0x00, 0x00): if length >= 4 && bytes[2] == 0xFE && bytes[3] == 0xFF { return (.utf32BigEndian, 4) } case (0xFF, 0xFE): if length >= 4 && bytes[2] == 0 && bytes[3] == 0 { return (.utf32LittleEndian, 4) } return (.utf16LittleEndian, 2) case (0xFE, 0xFF): return (.utf16BigEndian, 2) default: break } } return nil } } //MARK: - JSONSerializer private struct JSONWriter { private let maxUIntLength = String(describing: UInt.max).count private let maxIntLength = String(describing: Int.max).count var indent = 0 let pretty: Bool let sortedKeys: Bool let writer: (String?) -> Void private lazy var _numberformatter: CFNumberFormatter = { let formatter: CFNumberFormatter formatter = CFNumberFormatterCreate(nil, CFLocaleCopyCurrent(), kCFNumberFormatterNoStyle) CFNumberFormatterSetProperty(formatter, kCFNumberFormatterMaxFractionDigits, NSNumber(value: 15)) CFNumberFormatterSetFormat(formatter, "0.###############"._cfObject) return formatter }() init(pretty: Bool = false, sortedKeys: Bool = false, writer: @escaping (String?) -> Void) { self.pretty = pretty self.sortedKeys = sortedKeys self.writer = writer } mutating func serializeJSON(_ obj: Any?) throws { guard let obj = obj else { try serializeNull() return } // For better performance, the most expensive conditions to evaluate should be last. switch (obj) { case let str as String: try serializeString(str) case let boolValue as Bool: serializeBool(boolValue) case let num as Int: try serializeInt(value: num) case let num as UInt: try serializeUInt(value: num) case let array as Array<Any?>: try serializeArray(array) case let dict as Dictionary<AnyHashable, Any?>: try serializeDictionary(dict) case is NSNull: try serializeNull() case _ where _SwiftValue.store(obj) is NSNumber: try serializeNumber(_SwiftValue.store(obj) as! NSNumber) default: throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.propertyListReadCorrupt.rawValue, userInfo: ["NSDebugDescription" : "Invalid object cannot be serialized"]) } } private func serializeUInt(value: UInt) throws { if value == 0 { writer("0") return } var array: [UInt] = [] var stringResult = "" //Maximum length of an UInt array.reserveCapacity(maxUIntLength) stringResult.reserveCapacity(maxUIntLength) var number = value while number != 0 { array.append(number % 10) number /= 10 } /* Step backwards through the array and append the values to the string. This way the values are appended in the correct order. */ var counter = array.count while counter > 0 { counter -= 1 let digit: UInt = array[counter] switch digit { case 0: stringResult.append("0") case 1: stringResult.append("1") case 2: stringResult.append("2") case 3: stringResult.append("3") case 4: stringResult.append("4") case 5: stringResult.append("5") case 6: stringResult.append("6") case 7: stringResult.append("7") case 8: stringResult.append("8") case 9: stringResult.append("9") default: fatalError() } } writer(stringResult) } private func serializeInt(value: Int) throws { if value == 0 { writer("0") return } var array: [Int] = [] var stringResult = "" array.reserveCapacity(maxIntLength) //Account for a negative sign stringResult.reserveCapacity(maxIntLength + 1) var number = value while number != 0 { array.append(number % 10) number /= 10 } //If negative add minus sign before adding any values if value < 0 { stringResult.append("-") } /* Step backwards through the array and append the values to the string. This way the values are appended in the correct order. */ var counter = array.count while counter > 0 { counter -= 1 let digit = array[counter] switch digit { case 0: stringResult.append("0") case 1, -1: stringResult.append("1") case 2, -2: stringResult.append("2") case 3, -3: stringResult.append("3") case 4, -4: stringResult.append("4") case 5, -5: stringResult.append("5") case 6, -6: stringResult.append("6") case 7, -7: stringResult.append("7") case 8, -8: stringResult.append("8") case 9, -9: stringResult.append("9") default: fatalError() } } writer(stringResult) } func serializeString(_ str: String) throws { writer("\"") for scalar in str.unicodeScalars { switch scalar { case "\"": writer("\\\"") // U+0022 quotation mark case "\\": writer("\\\\") // U+005C reverse solidus // U+002F solidus not escaped case "\u{8}": writer("\\b") // U+0008 backspace case "\u{c}": writer("\\f") // U+000C form feed case "\n": writer("\\n") // U+000A line feed case "\r": writer("\\r") // U+000D carriage return case "\t": writer("\\t") // U+0009 tab case "\u{0}"..."\u{f}": writer("\\u000\(String(scalar.value, radix: 16))") // U+0000 to U+000F case "\u{10}"..."\u{1f}": writer("\\u00\(String(scalar.value, radix: 16))") // U+0010 to U+001F default: writer(String(scalar)) } } writer("\"") } func serializeBool(_ bool: Bool) { switch bool { case true: writer("true") case false: writer("false") } } mutating func serializeNumber(_ num: NSNumber) throws { if num.doubleValue.isInfinite || num.doubleValue.isNaN { throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.propertyListReadCorrupt.rawValue, userInfo: ["NSDebugDescription" : "Number cannot be infinity or NaN"]) } switch num._cfTypeID { case CFBooleanGetTypeID(): serializeBool(num.boolValue) default: writer(_serializationString(for: num)) } } mutating func serializeArray(_ array: [Any?]) throws { writer("[") if pretty { writer("\n") incAndWriteIndent() } var first = true for elem in array { if first { first = false } else if pretty { writer(",\n") writeIndent() } else { writer(",") } try serializeJSON(elem) } if pretty { writer("\n") decAndWriteIndent() } writer("]") } mutating func serializeDictionary(_ dict: Dictionary<AnyHashable, Any?>) throws { writer("{") if pretty { writer("\n") incAndWriteIndent() } var first = true func serializeDictionaryElement(key: AnyHashable, value: Any?) throws { if first { first = false } else if pretty { writer(",\n") writeIndent() } else { writer(",") } if let key = key as? String { try serializeString(key) } else { throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.propertyListReadCorrupt.rawValue, userInfo: ["NSDebugDescription" : "NSDictionary key must be NSString"]) } pretty ? writer(": ") : writer(":") try serializeJSON(value) } if sortedKeys { let elems = try dict.sorted(by: { a, b in guard let a = a.key as? String, let b = b.key as? String else { throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.propertyListReadCorrupt.rawValue, userInfo: ["NSDebugDescription" : "NSDictionary key must be NSString"]) } let options: NSString.CompareOptions = [.numeric, .caseInsensitive, .forcedOrdering] let range: Range<String.Index> = a.startIndex..<a.endIndex let locale = NSLocale.system return a.compare(b, options: options, range: range, locale: locale) == .orderedAscending }) for elem in elems { try serializeDictionaryElement(key: elem.key, value: elem.value) } } else { for (key, value) in dict { try serializeDictionaryElement(key: key, value: value) } } if pretty { writer("\n") decAndWriteIndent() } writer("}") } func serializeNull() throws { writer("null") } let indentAmount = 2 mutating func incAndWriteIndent() { indent += indentAmount writeIndent() } mutating func decAndWriteIndent() { indent -= indentAmount writeIndent() } func writeIndent() { for _ in 0..<indent { writer(" ") } } //[SR-2151] https://bugs.swift.org/browse/SR-2151 private mutating func _serializationString(for number: NSNumber) -> String { if !CFNumberIsFloatType(number._cfObject) { return number.stringValue } return CFNumberFormatterCreateStringWithNumber(nil, _numberformatter, number._cfObject)._swiftObject } } //MARK: - JSONDeserializer private struct JSONReader { static let whitespaceASCII: [UInt8] = [ 0x09, // Horizontal tab 0x0A, // Line feed or New line 0x0D, // Carriage return 0x20, // Space ] struct Structure { static let BeginArray: UInt8 = 0x5B // [ static let EndArray: UInt8 = 0x5D // ] static let BeginObject: UInt8 = 0x7B // { static let EndObject: UInt8 = 0x7D // } static let NameSeparator: UInt8 = 0x3A // : static let ValueSeparator: UInt8 = 0x2C // , static let QuotationMark: UInt8 = 0x22 // " static let Escape: UInt8 = 0x5C // \ } typealias Index = Int typealias IndexDistance = Int struct UnicodeSource { let buffer: UnsafeBufferPointer<UInt8> let encoding: String.Encoding let step: Int init(buffer: UnsafeBufferPointer<UInt8>, encoding: String.Encoding) { self.buffer = buffer self.encoding = encoding self.step = { switch encoding { case String.Encoding.utf8: return 1 case String.Encoding.utf16BigEndian, String.Encoding.utf16LittleEndian: return 2 case String.Encoding.utf32BigEndian, String.Encoding.utf32LittleEndian: return 4 default: return 1 } }() } func takeASCII(_ input: Index) -> (UInt8, Index)? { guard hasNext(input) else { return nil } let index: Int switch encoding { case String.Encoding.utf8: index = input case String.Encoding.utf16BigEndian where buffer[input] == 0: index = input + 1 case String.Encoding.utf32BigEndian where buffer[input] == 0 && buffer[input+1] == 0 && buffer[input+2] == 0: index = input + 3 case String.Encoding.utf16LittleEndian where buffer[input+1] == 0: index = input case String.Encoding.utf32LittleEndian where buffer[input+1] == 0 && buffer[input+2] == 0 && buffer[input+3] == 0: index = input default: return nil } return (buffer[index] < 0x80) ? (buffer[index], input + step) : nil } func takeString(_ begin: Index, end: Index) throws -> String { let byteLength = begin.distance(to: end) guard let chunk = String(data: Data(bytes: buffer.baseAddress!.advanced(by: begin), count: byteLength), encoding: encoding) else { throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.propertyListReadCorrupt.rawValue, userInfo: [ "NSDebugDescription" : "Unable to convert data to a string using the detected encoding. The data may be corrupt." ]) } return chunk } func hasNext(_ input: Index) -> Bool { return input + step <= buffer.endIndex } func distanceFromStart(_ index: Index) -> IndexDistance { return buffer.startIndex.distance(to: index) / step } } let source: UnicodeSource func consumeWhitespace(_ input: Index) -> Index? { var index = input while let (char, nextIndex) = source.takeASCII(index), JSONReader.whitespaceASCII.contains(char) { index = nextIndex } return index } func consumeStructure(_ ascii: UInt8, input: Index) throws -> Index? { return try consumeWhitespace(input).flatMap(consumeASCII(ascii)).flatMap(consumeWhitespace) } func consumeASCII(_ ascii: UInt8) -> (Index) throws -> Index? { return { (input: Index) throws -> Index? in switch self.source.takeASCII(input) { case .none: throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.propertyListReadCorrupt.rawValue, userInfo: [ "NSDebugDescription" : "Unexpected end of file during JSON parse." ]) case let (taken, index)? where taken == ascii: return index default: return nil } } } func consumeASCIISequence(_ sequence: String, input: Index) throws -> Index? { var index = input for scalar in sequence.unicodeScalars { guard let nextIndex = try consumeASCII(UInt8(scalar.value))(index) else { return nil } index = nextIndex } return index } func takeMatching(_ match: @escaping (UInt8) -> Bool) -> ([Character], Index) -> ([Character], Index)? { return { input, index in guard let (byte, index) = self.source.takeASCII(index), match(byte) else { return nil } return (input + [Character(UnicodeScalar(byte))], index) } } //MARK: - String Parsing func parseString(_ input: Index) throws -> (String, Index)? { guard let beginIndex = try consumeWhitespace(input).flatMap(consumeASCII(Structure.QuotationMark)) else { return nil } var chunkIndex: Int = beginIndex var currentIndex: Int = chunkIndex var output: String = "" while source.hasNext(currentIndex) { guard let (ascii, index) = source.takeASCII(currentIndex) else { currentIndex += source.step continue } switch ascii { case Structure.QuotationMark: output += try source.takeString(chunkIndex, end: currentIndex) return (output, index) case Structure.Escape: output += try source.takeString(chunkIndex, end: currentIndex) if let (escaped, nextIndex) = try parseEscapeSequence(index) { output += escaped chunkIndex = nextIndex currentIndex = nextIndex continue } else { throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.propertyListReadCorrupt.rawValue, userInfo: [ "NSDebugDescription" : "Invalid escape sequence at position \(source.distanceFromStart(currentIndex))" ]) } default: currentIndex = index } } throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.propertyListReadCorrupt.rawValue, userInfo: [ "NSDebugDescription" : "Unexpected end of file during string parse." ]) } func parseEscapeSequence(_ input: Index) throws -> (String, Index)? { guard let (byte, index) = source.takeASCII(input) else { throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.propertyListReadCorrupt.rawValue, userInfo: [ "NSDebugDescription" : "Early end of unicode escape sequence around character" ]) } let output: String switch byte { case 0x22: output = "\"" case 0x5C: output = "\\" case 0x2F: output = "/" case 0x62: output = "\u{08}" // \b case 0x66: output = "\u{0C}" // \f case 0x6E: output = "\u{0A}" // \n case 0x72: output = "\u{0D}" // \r case 0x74: output = "\u{09}" // \t case 0x75: return try parseUnicodeSequence(index) default: return nil } return (output, index) } func parseUnicodeSequence(_ input: Index) throws -> (String, Index)? { guard let (codeUnit, index) = parseCodeUnit(input) else { return nil } if !UTF16.isLeadSurrogate(codeUnit) { return (String(UnicodeScalar(codeUnit)!), index) } guard let (trailCodeUnit, finalIndex) = try consumeASCIISequence("\\u", input: index).flatMap(parseCodeUnit) , UTF16.isTrailSurrogate(trailCodeUnit) else { throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.propertyListReadCorrupt.rawValue, userInfo: [ "NSDebugDescription" : "Unable to convert unicode escape sequence (no low-surrogate code point) to UTF8-encoded character at position \(source.distanceFromStart(input))" ]) } let highValue = (UInt32(codeUnit - 0xD800) << 10) let lowValue = UInt32(trailCodeUnit - 0xDC00) return (String(UnicodeScalar(highValue + lowValue + 0x10000)!), finalIndex) } func isHexChr(_ byte: UInt8) -> Bool { return (byte >= 0x30 && byte <= 0x39) || (byte >= 0x41 && byte <= 0x46) || (byte >= 0x61 && byte <= 0x66) } func parseCodeUnit(_ input: Index) -> (UTF16.CodeUnit, Index)? { let hexParser = takeMatching(isHexChr) guard let (result, index) = hexParser([], input).flatMap(hexParser).flatMap(hexParser).flatMap(hexParser), let value = Int(String(result), radix: 16) else { return nil } return (UTF16.CodeUnit(value), index) } //MARK: - Number parsing static let numberCodePoints: [UInt8] = [ 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, // 0...9 0x2E, 0x2D, 0x2B, 0x45, 0x65, // . - + E e ] func parseNumber(_ input: Index, options opt: JSONSerialization.ReadingOptions) throws -> (Any, Index)? { func parseTypedNumber(_ address: UnsafePointer<UInt8>, count: Int) -> (Any, IndexDistance)? { let temp_buffer_size = 64 var temp_buffer = [Int8](repeating: 0, count: temp_buffer_size) return temp_buffer.withUnsafeMutableBufferPointer { (buffer: inout UnsafeMutableBufferPointer<Int8>) -> (Any, IndexDistance)? in memcpy(buffer.baseAddress!, address, min(count, temp_buffer_size - 1)) // ensure null termination let startPointer = buffer.baseAddress! let intEndPointer = UnsafeMutablePointer<UnsafeMutablePointer<Int8>?>.allocate(capacity: 1) defer { intEndPointer.deallocate(capacity: 1) } let doubleEndPointer = UnsafeMutablePointer<UnsafeMutablePointer<Int8>?>.allocate(capacity: 1) defer { doubleEndPointer.deallocate(capacity: 1) } let intResult = strtol(startPointer, intEndPointer, 10) let intDistance = startPointer.distance(to: intEndPointer[0]!) let doubleResult = strtod(startPointer, doubleEndPointer) let doubleDistance = startPointer.distance(to: doubleEndPointer[0]!) guard intDistance > 0 || doubleDistance > 0 else { return nil } let shouldUseReferenceType = opt.contains(.useReferenceNumericTypes) if intDistance == doubleDistance { return (shouldUseReferenceType ? NSNumber(value: intResult) : intResult, intDistance) } guard doubleDistance > 0 else { return nil } if doubleResult == doubleResult.rounded() { return (shouldUseReferenceType ? NSNumber(value: Int(doubleResult)) : Int(doubleResult), doubleDistance) } return (shouldUseReferenceType ? NSNumber(value: doubleResult) : doubleResult, doubleDistance) } } if source.encoding == String.Encoding.utf8 { return parseTypedNumber(source.buffer.baseAddress!.advanced(by: input), count: source.buffer.count - input).map { return ($0.0, input + $0.1) } } else { var numberCharacters = [UInt8]() var index = input while let (ascii, nextIndex) = source.takeASCII(index), JSONReader.numberCodePoints.contains(ascii) { numberCharacters.append(ascii) index = nextIndex } numberCharacters.append(0) return numberCharacters.withUnsafeBufferPointer { parseTypedNumber($0.baseAddress!, count: $0.count) }.map { return ($0.0, index) } } } //MARK: - Value parsing func parseValue(_ input: Index, options opt: JSONSerialization.ReadingOptions) throws -> (Any, Index)? { if let (value, parser) = try parseString(input) { return (value, parser) } else if let parser = try consumeASCIISequence("true", input: input) { let result: Any = opt.contains(.useReferenceNumericTypes) ? NSNumber(value: true) : true return (result, parser) } else if let parser = try consumeASCIISequence("false", input: input) { let result: Any = opt.contains(.useReferenceNumericTypes) ? NSNumber(value: false) : false return (result, parser) } else if let parser = try consumeASCIISequence("null", input: input) { return (NSNull(), parser) } else if let (object, parser) = try parseObject(input, options: opt) { return (object, parser) } else if let (array, parser) = try parseArray(input, options: opt) { return (array, parser) } else if let (number, parser) = try parseNumber(input, options: opt) { return (number, parser) } return nil } //MARK: - Object parsing func parseObject(_ input: Index, options opt: JSONSerialization.ReadingOptions) throws -> ([String: Any], Index)? { guard let beginIndex = try consumeStructure(Structure.BeginObject, input: input) else { return nil } var index = beginIndex var output: [String: Any] = [:] while true { if let finalIndex = try consumeStructure(Structure.EndObject, input: index) { return (output, finalIndex) } if let (key, value, nextIndex) = try parseObjectMember(index, options: opt) { output[key] = value if let finalParser = try consumeStructure(Structure.EndObject, input: nextIndex) { return (output, finalParser) } else if let nextIndex = try consumeStructure(Structure.ValueSeparator, input: nextIndex) { index = nextIndex continue } else { return nil } } return nil } } func parseObjectMember(_ input: Index, options opt: JSONSerialization.ReadingOptions) throws -> (String, Any, Index)? { guard let (name, index) = try parseString(input) else { throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.propertyListReadCorrupt.rawValue, userInfo: [ "NSDebugDescription" : "Missing object key at location \(source.distanceFromStart(input))" ]) } guard let separatorIndex = try consumeStructure(Structure.NameSeparator, input: index) else { throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.propertyListReadCorrupt.rawValue, userInfo: [ "NSDebugDescription" : "Invalid separator at location \(source.distanceFromStart(index))" ]) } guard let (value, finalIndex) = try parseValue(separatorIndex, options: opt) else { throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.propertyListReadCorrupt.rawValue, userInfo: [ "NSDebugDescription" : "Invalid value at location \(source.distanceFromStart(separatorIndex))" ]) } return (name, value, finalIndex) } //MARK: - Array parsing func parseArray(_ input: Index, options opt: JSONSerialization.ReadingOptions) throws -> ([Any], Index)? { guard let beginIndex = try consumeStructure(Structure.BeginArray, input: input) else { return nil } var index = beginIndex var output: [Any] = [] while true { if let finalIndex = try consumeStructure(Structure.EndArray, input: index) { return (output, finalIndex) } if let (value, nextIndex) = try parseValue(index, options: opt) { output.append(value) if let finalIndex = try consumeStructure(Structure.EndArray, input: nextIndex) { return (output, finalIndex) } else if let nextIndex = try consumeStructure(Structure.ValueSeparator, input: nextIndex) { index = nextIndex continue } } throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.propertyListReadCorrupt.rawValue, userInfo: [ "NSDebugDescription" : "Badly formed array at location \(source.distanceFromStart(index))" ]) } } }
apache-2.0
fc6223faf5e4ae6cbff2f0b9aefd729a
39.009009
499
0.564663
4.869518
false
false
false
false
imzyf/99-projects-of-swift
012-coredata-todo-list/012-coredata-todo-list/AppDelegate.swift
1
4754
// // AppDelegate.swift // 012-coredata-todo-list // // Created by moma on 2017/10/30. // Copyright © 2017年 yifans. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. let dictionary: [String: Any] = ["ChecklistItemID": 0] UserDefaults.standard.register(defaults: dictionary) return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "_12_coredata_todo_list") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
mit
d50284295a09ec47796c0e9bc3424a41
48.489583
285
0.683225
5.758788
false
false
false
false
kickstarter/Kickstarter-Prelude
Prelude-UIKit/lenses/UITextFieldLenses.swift
1
1393
import Prelude import UIKit public protocol UITextFieldProtocol: UIControlProtocol, UITextInputTraitsProtocol { var borderStyle: UITextField.BorderStyle { get set } var font: UIFont? { get set } var placeholder: String? { get set } var textAlignment: NSTextAlignment { get set } var textColor: UIColor? { get set } var text: String? { get set } } extension UITextField: UITextFieldProtocol {} public extension LensHolder where Object: UITextFieldProtocol { public var borderStyle: Lens<Object, UITextField.BorderStyle> { return Lens( view: { $0.borderStyle }, set: { $1.borderStyle = $0; return $1 } ) } public var font: Lens<Object, UIFont?> { return Lens( view: { $0.font }, set: { $1.font = $0; return $1 } ) } public var placeholder: Lens<Object, String?> { return Lens( view: { $0.placeholder }, set: { $1.placeholder = $0; return $1 } ) } public var textAlignment: Lens<Object, NSTextAlignment> { return Lens( view: { $0.textAlignment }, set: { $1.textAlignment = $0; return $1 } ) } public var textColor: Lens<Object, UIColor?> { return Lens( view: { $0.textColor }, set: { $1.textColor = $0; return $1 } ) } public var text: Lens<Object, String?> { return Lens( view: { $0.text }, set: { $1.text = $0; return $1 } ) } }
apache-2.0
084a5412917e2cbb93c052ec7bd6f644
23.017241
83
0.613783
3.714667
false
false
false
false
atuooo/notGIF
notGIF/Service/Share/OpenShare.swift
1
4780
// // OpenShare.swift // notGIF // // Created by Atuooo on 16/10/2016. // Copyright © 2016 xyz. All rights reserved. // import UIKit import Photos import MobileCoreServices public enum Platform: String { case wechat = "weixin://" var url: URL { return URL(string: rawValue)! } var appID: String { switch self { case .wechat: return "wxb073e64ef4cef14f" } } } final class OpenShare { class func canOpen(_ platform: Platform) -> Bool { switch platform { case .wechat: return UIApplication.shared.canOpenURL(platform.url) } } class func shareGIF(with gifInfo: GIFDataInfo, to platform: Platform) { guard let thumbData = gifInfo.thumbnail.monkeyking_compressedImageData else { // 发送失败? return } switch platform { case .wechat: var wechatMessageInfo: [String: Any] = [ "result": "1", "returnFromApp": "0", "scene": "0", "sdkver": "1.5", "command": "1010", ] wechatMessageInfo["objectType"] = "8" // emoticon wechatMessageInfo["thumbData"] = thumbData wechatMessageInfo["fileData"] = gifInfo.data let wechatMessage = [platform.appID: wechatMessageInfo] guard let messageData = try? PropertyListSerialization.data(fromPropertyList: wechatMessage, format: .binary, options: 0), let openURL = URL(string: "weixin://app/\(platform.appID)/sendreq/?") else { // alert ? 数据初始化失败 return } UIPasteboard.general.setData(messageData, forPasteboardType: "content") if #available(iOS 10.0, *) { UIApplication.shared.open(openURL, options: [:], completionHandler: nil) } else { UIApplication.shared.openURL(openURL) } } } } private extension UIImage { var monkeyking_compressedImageData: Data? { var compressionQuality: CGFloat = 0.7 func compressedDataOfImage(_ image: UIImage) -> Data? { let maxHeight: CGFloat = 240.0 let maxWidth: CGFloat = 240.0 var actualHeight: CGFloat = image.size.height var actualWidth: CGFloat = image.size.width var imgRatio: CGFloat = actualWidth/actualHeight let maxRatio: CGFloat = maxWidth/maxHeight if actualHeight > maxHeight || actualWidth > maxWidth { if imgRatio < maxRatio { // adjust width according to maxHeight imgRatio = maxHeight / actualHeight actualWidth = imgRatio * actualWidth actualHeight = maxHeight } else if imgRatio > maxRatio { // adjust height according to maxWidth imgRatio = maxWidth / actualWidth actualHeight = imgRatio * actualHeight actualWidth = maxWidth } else { actualHeight = maxHeight actualWidth = maxWidth } } let rect = CGRect(x: 0.0, y: 0.0, width: actualWidth, height: actualHeight) UIGraphicsBeginImageContext(rect.size) defer { UIGraphicsEndImageContext() } image.draw(in: rect) let imageData = UIGraphicsGetImageFromCurrentImageContext().flatMap({ UIImageJPEGRepresentation($0, compressionQuality) }) return imageData } let fullImageData = UIImageJPEGRepresentation(self, compressionQuality) guard var imageData = fullImageData else { return nil } let minCompressionQuality: CGFloat = 0.01 let dataLengthCeiling: Int = 31500 while imageData.count > dataLengthCeiling && compressionQuality > minCompressionQuality { compressionQuality -= 0.1 guard let image = UIImage(data: imageData) else { break } if let compressedImageData = compressedDataOfImage(image) { imageData = compressedImageData } else { break } } return imageData } }
mit
ea66879fa28a9211b7369f79ed102d8d
29.677419
134
0.512093
5.784672
false
false
false
false
Nyx0uf/MPDRemote
src/common/misc/AlbumCoverGenerator.swift
1
2784
// AlbumCoverGenerator.swift // Copyright (c) 2017 Nyx0uf // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit func generateCoverForAlbum(_ album: Album, size: CGSize) -> UIImage? { return generateCoverFromString(album.name, size: size, useGradient: false) } func generateCoverForGenre(_ genre: Genre, size: CGSize) -> UIImage? { return generateCoverFromString(genre.name, size: size, useGradient: false) } func generateCoverForArtist(_ artist: Artist, size: CGSize) -> UIImage? { return generateCoverFromString(artist.name, size: size, useGradient: false) } func generateCoverForPlaylist(_ playlist: Playlist, size: CGSize) -> UIImage? { return generateCoverFromString(playlist.name, size: size, useGradient: false) } func generateCoverFromString(_ string: String, size: CGSize, useGradient: Bool = false) -> UIImage? { let backgroundColor = UIColor(rgb: string.djb2()) if useGradient { if let gradient = makeLinearGradient(startColor: backgroundColor, endColor: backgroundColor.inverted()) { return UIImage.fromString(string, font: UIFont(name: "Chalkduster", size: size.width / 4.0)!, fontColor: backgroundColor.inverted(), gradient: gradient, maxSize: size) } } return UIImage.fromString(string, font: UIFont(name: "Chalkduster", size: size.width / 4.0)!, fontColor: backgroundColor.inverted(), backgroundColor: backgroundColor, maxSize: size) } private func makeLinearGradient(startColor: UIColor, endColor: UIColor) -> CGGradient? { let colors = [startColor.cgColor, endColor.cgColor] let colorSpace = CGColorSpace.NYXAppropriateColorSpace() let colorLocations: [CGFloat] = [0.0, 1.0] let gradient = CGGradient(colorsSpace: colorSpace, colors: colors as CFArray, locations: colorLocations) return gradient }
mit
9b167c41052ac1409b29238cc7537aa6
39.347826
182
0.763649
4.100147
false
false
false
false
weijentu/ResearchKit
samples/ORKSample/ORKSample/WithdrawViewController.swift
10
2730
/* Copyright (c) 2015, Apple Inc. 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(s) nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. No license is granted to the trademarks of the copyright holders even if such marks are included in this software. 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 OWNER 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 UIKit import ResearchKit class WithdrawViewController: ORKTaskViewController { // MARK: Initialization init() { let instructionStep = ORKInstructionStep(identifier: "WithdrawlInstruction") instructionStep.title = NSLocalizedString("Are you sure you want to withdraw?", comment: "") instructionStep.text = NSLocalizedString("Withdrawing from the study will reset the app to the state it was in prior to you originally joining the study.", comment: "") let completionStep = ORKCompletionStep(identifier: "Withdraw") completionStep.title = NSLocalizedString("We appreciate your time.", comment: "") completionStep.text = NSLocalizedString("Thank you for your contribution to this study. We are sorry that you could not continue.", comment: "") let withdrawTask = ORKOrderedTask(identifier: "Withdraw", steps: [instructionStep, completionStep]) super.init(task: withdrawTask, taskRunUUID: nil) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
bsd-3-clause
645a5fb645558cb2d59756f3ae342a41
49.555556
176
0.765934
4.990859
false
false
false
false
EZ-NET/ESNotification
ESNotification/HandlerID.swift
1
910
// // HandlerID.swift // ESNotification // // Created by Tomohiro Kumagai on H27/12/01. // Copyright © 平成27年 EasyStyle G.K. All rights reserved. // public struct HandlerID : Hashable { internal var value:Int internal weak var handlerManager: NotificationHandlers? init(_ value:Int, handlerManager: NotificationHandlers?) { self.value = value self.handlerManager = handlerManager } mutating func increment() { self.value = value.successor() } public var hashValue: Int { return Int(self.value) } /// Release observing handler by HandlerID public func release() { if let handlerManager = self.handlerManager { try! handlerManager.releaseHandler(self) } else { _notificationManager.releaseObservingHandlers([self]) } } func containsInHandler(handler: _NotificationObservingHandler) -> Bool { return handler.handlerID == self } }
mit
13e626db9030133a0dbd3c4781721905
18.212766
73
0.703212
3.641129
false
false
false
false
Egibide-DAM/swift
02_ejemplos/10_varios/01_optional_chaining/07_utilizando_subindices.playground/Contents.swift
1
1566
class Person { var residence: Residence? } class Room { let name: String init(name: String) { self.name = name } } class Address { var buildingName: String? var buildingNumber: String? var street: String? func buildingIdentifier() -> String? { if let buildingNumber = buildingNumber, let street = street { return "\(buildingNumber) \(street)" } else if buildingName != nil { return buildingName } else { return nil } } } class Residence { var rooms = [Room]() var numberOfRooms: Int { return rooms.count } subscript(i: Int) -> Room { get { return rooms[i] } set { rooms[i] = newValue } } func printNumberOfRooms() { print("The number of rooms is \(numberOfRooms)") } var address: Address? } let john = Person() // ----- if let firstRoomName = john.residence?[0].name { print("The first room name is \(firstRoomName).") } else { print("Unable to retrieve the first room name.") } // Prints "Unable to retrieve the first room name." john.residence?[0] = Room(name: "Bathroom") let johnsHouse = Residence() johnsHouse.rooms.append(Room(name: "Living Room")) johnsHouse.rooms.append(Room(name: "Kitchen")) john.residence = johnsHouse if let firstRoomName = john.residence?[0].name { print("The first room name is \(firstRoomName).") } else { print("Unable to retrieve the first room name.") } // Prints "The first room name is Living Room."
apache-2.0
ec62be2ce5abd83d301cfe275b4c3880
22.373134
69
0.60728
3.954545
false
false
false
false
gkye/TheMovieDatabaseSwiftWrapper
Sources/TMDBSwift/Models/Video.swift
1
3938
import Foundation /// <#Description#> public struct Video: Codable, Equatable { /// <#Description#> public var id: String /// <#Description#> public var countryCode: String? /// <#Description#> public var language: Language? /// <#Description#> public var key: String? /// <#Description#> public var name: String? /// <#Description#> public var site: String? /// <#Description#> public var size: Int? /// <#Description#> public var type: String? /// <#Description#> public var isOfficial: Bool = false /// <#Description#> public var publishedDate: Date? public init(id: String, countryCode: String? = nil, language: Language? = nil, key: String? = nil, name: String? = nil, site: String? = nil, size: Int? = nil, type: String? = nil, isOfficial: Bool = false, publishedDate: Date? = nil) { self.id = id self.countryCode = countryCode self.language = language self.key = key self.name = name self.site = site self.size = size self.type = type self.isOfficial = isOfficial self.publishedDate = publishedDate } public enum CodingKeys: String, CodingKey { case id case countryCode = "iso_3166_1" case language = "iso_639_1" case key case name case site case size case type case isOfficial = "official" case publishedDate = "published_at" } public init(from decoder: Decoder) throws { let container: KeyedDecodingContainer<Video.CodingKeys> = try decoder.container(keyedBy: Video.CodingKeys.self) self.id = try container.decode(String.self, forKey: Video.CodingKeys.id) self.countryCode = try container.decode(String.self, forKey: Video.CodingKeys.countryCode) self.language = try container.decode(Language.self, forKey: Video.CodingKeys.language) self.key = try container.decode(String.self, forKey: Video.CodingKeys.key) self.name = try container.decode(String.self, forKey: Video.CodingKeys.name) self.site = try container.decode(String.self, forKey: Video.CodingKeys.site) self.size = try container.decode(Int.self, forKey: Video.CodingKeys.size) self.type = try container.decode(String.self, forKey: Video.CodingKeys.type) self.isOfficial = try container.decode(Bool.self, forKey: Video.CodingKeys.isOfficial) let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" if let publishedDateString = try? container.decode(String.self, forKey: .publishedDate), let publishedDate = dateFormatter.date(from: publishedDateString) { self.publishedDate = publishedDate } } public func encode(to encoder: Encoder) throws { var container: KeyedEncodingContainer<Video.CodingKeys> = encoder.container(keyedBy: Video.CodingKeys.self) try container.encode(self.id, forKey: Video.CodingKeys.id) try container.encode(self.countryCode, forKey: Video.CodingKeys.countryCode) try container.encode(self.language, forKey: Video.CodingKeys.language) try container.encode(self.key, forKey: Video.CodingKeys.key) try container.encode(self.name, forKey: Video.CodingKeys.name) try container.encode(self.site, forKey: Video.CodingKeys.site) try container.encode(self.size, forKey: Video.CodingKeys.size) try container.encode(self.type, forKey: Video.CodingKeys.type) try container.encode(self.isOfficial, forKey: Video.CodingKeys.isOfficial) let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" if let publishedDate = self.publishedDate { try container.encodeIfPresent(dateFormatter.string(from: publishedDate), forKey: Video.CodingKeys.publishedDate) } } }
mit
24a274c620cf3707e0309f899b1147f7
42.274725
239
0.66709
4.22986
false
false
false
false
Yurssoft/QuickFile
QuickFile/Additional_Classes/YSTabBarController.swift
1
985
// // YSTabBarController.swift // YSGGP // // Created by Yurii Boiko on 10/21/16. // Copyright © 2016 Yurii Boiko. All rights reserved. // import UIKit class YSTabBarController: UITabBarController { override func viewDidLoad() { super.viewDidLoad() var driveTopViewController: YSDriveTopViewController? = nil for navigationVC in childViewControllers { for topVC in navigationVC.childViewControllers { if let drTopVC = topVC as? YSDriveTopViewController { driveTopViewController = drTopVC } } } let coordinator = YSDriveTopCoordinator() YSAppDelegate.appDelegate().driveTopCoordinator = coordinator coordinator.start(driveTopVC: driveTopViewController!) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) YSAppDelegate.appDelegate().playerCoordinator.start(tabBarController: self) } }
mit
826c1eaaea63935caa695de3dd6f7728
30.741935
83
0.66565
5.098446
false
false
false
false
bmoliveira/BOShareComposer
BOShareComposer/Classes/ShareViewController.swift
1
10937
// // ShareViewController.swift // BOShareComposer // // Created by Bruno Oliveira on 19/07/16. // Copyright © 2016 CocoaPods. All rights reserved. // import UIKit import SnapKit import WebKit public extension ShareViewController { public static func presentShareViewController(from viewController: UIViewController, shareContent: ShareContent, options: ShareOptions = ShareOptions(), completion: ((Bool, ShareContent?) -> ())) { let shareViewController = ShareViewController() shareViewController.completion = completion shareViewController.options = options shareViewController.shareContent = shareContent shareViewController.modalPresentationStyle = .OverCurrentContext viewController.presentViewController(shareViewController, animated: false, completion: nil) } } public class ShareViewController: UIViewController { private var metadataImageViewSize = CGSize(width: 70, height: 70) private var shareContent: ShareContent? { willSet(value) { if let currentValue = shareContent, newValue = value where newValue.link == currentValue.link { return } guard let newValue = value else { return } loadMetadata(newValue) } didSet { guard let shareContent = shareContent else { return } popupBody.text = shareContent.text if shareContent.link == nil { showMetadata = false } } } private var options: ShareOptions? { didSet { guard let options = options else { return } dismissButton.tintColor = options.tintColor dismissButton.setTitle(options.dismissText, forState: .Normal) dismissButton.setTitleColor(options.tintColor, forState: .Normal) confirmButton.titleLabel?.textColor = options.tintColor confirmButton.setTitle(options.confirmText, forState: .Normal) confirmButton.setTitleColor(options.tintColor, forState: .Normal) popupTitle.text = options.title popupBody.resignFirstResponder() popupBody.keyboardAppearance = options.keyboardAppearance popupBody.becomeFirstResponder() showMetadata = options.showMetadata } } private var showMetadata = true { didSet { guard !metadataImageView.constraints.isEmpty else { return } let size = showMetadata ? metadataImageViewSize : CGSize.zero metadataImageView.snp_updateConstraints { make in make.height.equalTo(size.height) make.width.equalTo(size.width) } UIView.animateWithDuration(0.5) { self.metadataImageView.layoutIfNeeded() } } } private var completion: ((Bool, ShareContent?) -> ())? lazy var dismissButton: UIButton = { let button = UIButton(type: .Custom) button.addTarget(self, action: #selector(cancelAction), forControlEvents: .TouchUpInside) button.titleLabel?.font = UIFont.systemFontOfSize(15) button.titleLabel?.textAlignment = .Right return button }() lazy var confirmButton: UIButton = { let button = UIButton(type: .Custom) button.addTarget(self, action: #selector(sendAction), forControlEvents: .TouchUpInside) button.titleLabel?.font = UIFont.boldSystemFontOfSize(17) button.titleLabel?.textAlignment = .Left return button }() lazy var popupTitle: UILabel = { let label = UILabel() label.font = UIFont.systemFontOfSize(17) label.minimumScaleFactor = 0.5 label.adjustsFontSizeToFitWidth = true label.textAlignment = .Center return label }() lazy var titleDivider: UIView = { let view = UIView() view.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.3) return view }() lazy var popupBody: UITextView = { let textField = UITextView() textField.editable = true textField.backgroundColor = UIColor.clearColor() textField.scrollEnabled = true textField.font = UIFont.systemFontOfSize(17) textField.becomeFirstResponder() return textField }() lazy var metadataImageView: UIImageView = { let imageView = UIImageView() imageView.contentMode = .ScaleAspectFill imageView.clipsToBounds = true imageView.backgroundColor = UIColor.whiteColor() imageView.layer.borderWidth = 1 imageView.layer.borderColor = UIColor.blackColor().colorWithAlphaComponent(0.3).CGColor return imageView }() lazy var backgroundView: UIView = { let view = UIView() view.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.6) return view }() lazy var containerView: UIVisualEffectView = { let visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .ExtraLight)) visualEffectView.layer.cornerRadius = 8 visualEffectView.clipsToBounds = true visualEffectView.alpha = 0 return visualEffectView }() var metadataWebView = WKWebView() override public func viewDidLoad() { super.viewDidLoad() setupViews() } public override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) showView() } public override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) hideView() } public override func preferredStatusBarStyle() -> UIStatusBarStyle { return .LightContent } func cancelAction() { shareContent?.text = popupBody.text completion?(false, shareContent) hideView { _ in self.dismissViewControllerAnimated(false, completion: nil) } } func sendAction() { shareContent?.text = popupBody.text completion?(true, shareContent) hideView { _ in self.dismissViewControllerAnimated(false, completion: nil) } } } extension ShareViewController: WKNavigationDelegate { public func webView(webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: NSError) { print("failed navigation") } public func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) { let dispatchTime: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(1 * Double(NSEC_PER_SEC))) dispatch_after(dispatchTime, dispatch_get_main_queue(), { self.snapWebView(webView) }) } } extension ShareViewController { private func loadMetadata(shareContent: ShareContent) { guard let link = shareContent.link where self.showMetadata else { print("No link found / metadata disabled") return } OpenGraph.fetchMetadata(link, completion: { [weak self] (response) in guard let response = response, imageURL = response.imageURL else { self?.loadWebView(link) return } self?.metadataImageView.setImage(withUrl: imageURL) }) } private func loadWebView(url: NSURL) { metadataWebView.navigationDelegate = self metadataWebView.loadRequest(NSURLRequest(URL: url)) } private func snapWebView(webView: WKWebView) { metadataImageView.fadeSetImage(webView.screenshot) } private func showView() { UIView.animateWithDuration(0.7) { self.containerView.alpha = 1 } } private func hideView(completion: ((Bool)->())? = nil) { popupBody.resignFirstResponder() UIView.animateWithDuration(0.5) { self.backgroundView.alpha = 0 } UIView.animateWithDuration(0.5, animations: { self.containerView.alpha = 0 }, completion: completion) } private func setupViews() { view.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.1) view.addSubview(backgroundView) backgroundView.snp_makeConstraints { make in make.edges.equalTo(self.view) } view.addSubview(containerView) containerView.snp_makeConstraints { make in make.top.equalTo(backgroundView).inset(70) make.left.equalTo(backgroundView).inset(16) make.right.equalTo(backgroundView).inset(16) } let contentView = containerView.contentView contentView.addSubview(dismissButton) dismissButton.snp_makeConstraints { make in make.top.equalTo(contentView) make.left.equalTo(contentView).inset(8) make.height.equalTo(40) } dismissButton.setContentCompressionResistancePriority(UILayoutPriority.init(1000), forAxis: UILayoutConstraintAxis.Horizontal) contentView.addSubview(confirmButton) confirmButton.snp_makeConstraints { make in make.top.equalTo(contentView) make.right.equalTo(contentView).inset(8) make.height.equalTo(40) } confirmButton.setContentCompressionResistancePriority(UILayoutPriority.init(1000), forAxis: .Horizontal) contentView.addSubview(titleDivider) titleDivider.snp_makeConstraints { make in make.top.equalTo(dismissButton.snp_bottom) make.left.equalTo(contentView) make.right.equalTo(contentView) make.height.equalTo(1) } contentView.addSubview(popupTitle) popupTitle.snp_makeConstraints { make in make.top.equalTo(contentView).priorityMedium() make.bottom.equalTo(titleDivider.snp_top).priorityMedium() make.centerX.equalTo(contentView) make.centerY.equalTo(dismissButton).priorityHigh() make.left.equalTo(dismissButton.snp_right).offset(2) make.right.equalTo(confirmButton.snp_left).offset(-4) } popupTitle.setContentHuggingPriority(UILayoutPriority.init(1), forAxis: .Horizontal) let dummyContentView = UIView() contentView.addSubview(dummyContentView) dummyContentView.snp_makeConstraints { make in make.top.equalTo(titleDivider.snp_bottom) make.left.equalTo(contentView).inset(8) make.right.equalTo(contentView).inset(8) make.bottom.equalTo(contentView).inset(8) make.height.equalTo(160) } dummyContentView.addSubview(metadataImageView) metadataImageView.snp_makeConstraints { make in make.right.equalTo(dummyContentView) make.height.equalTo(showMetadata ? metadataImageViewSize.height : 0) make.width.equalTo(showMetadata ? metadataImageViewSize.width : 0) make.top.equalTo(dummyContentView).inset(8) } dummyContentView.addSubview(popupBody) popupBody.snp_makeConstraints { make in make.top.equalTo(dummyContentView) make.left.equalTo(dummyContentView) make.right.equalTo(metadataImageView.snp_left).offset(-4) make.bottom.equalTo(dummyContentView) } view.addSubview(metadataWebView) metadataWebView.snp_makeConstraints { make in make.top.equalTo(view.snp_bottom) make.left.equalTo(view.snp_right) make.height.equalTo(view.snp_width) make.width.equalTo(view.snp_width) } } }
mit
488f658c79c2d33a90b390b120938fac
30.518732
130
0.690289
4.849667
false
false
false
false
maximbilan/SwiftlySlider
SwiftlySlider/Sources/SwiftlySlider.swift
1
9424
// // SwiftlySlider.swift // SwiftlySlider // // Created by Maxim Bilan on 6/6/16. // Copyright © 2016 Maxim Bilan. All rights reserved. // import UIKit public protocol SwiftlySliderDelegate : class { func swiftlySliderValueChanged(_ value: Int) } open class SwiftlySlider: UIView { // MARK: - Direction public enum PickerDirection: Int { case horizontal case vertical } // MARK: - Public properties open weak var delegate: SwiftlySliderDelegate! open var direction: PickerDirection = .horizontal open var currentValue: Int { get { return value } set(newValue) { if newValue >= maxValue { self.value = maxValue } else if newValue <= minValue { self.value = minValue } else { self.value = newValue } update() setNeedsDisplay() } } open var minValue: Int = 0 open var maxValue: Int = 20 open var normalValue: Int = 0 // MARK: - Additional public properties open var labelFontColor: UIColor = UIColor.white open var labelBackgroundColor: UIColor = UIColor.black open var labelFont = UIFont(name: "Helvetica Neue", size: 12) open var bgColor: UIColor = UIColor.white open var bgCornerRadius: CGFloat = 30 open var barColor: UIColor = UIColor.gray open var sliderImage: UIImage? open var sliderImageOffset: CGPoint = CGPoint.zero open var sliderSize: CGSize = CGSize.zero open var useNormalIndicator = false // MARK: - Private properties fileprivate var value: Int = 0 fileprivate var image: UIImage! fileprivate var currentSelectionY: CGFloat = 0 fileprivate var currentSelectionX: CGFloat = 0 // MARK: - Initialization required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.backgroundColor = UIColor.clear value = minValue } override public init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor.clear value = minValue } override open func layoutSubviews() { super.layoutSubviews() update() } // MARK: - Prerendering func generateHUEImage(_ size: CGSize) -> UIImage { let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) var barRect = CGRect.null if direction == .horizontal { let barHeight = size.height * 0.2 barRect = CGRect(x: 0, y: size.height * 0.5 - barHeight * 0.5, width: size.width, height: barHeight) } else { let barWidth = size.width * 0.2 barRect = CGRect(x: size.width * 0.5 - barWidth * 0.5, y: 0, width: barWidth, height: size.height) } UIGraphicsBeginImageContextWithOptions(size, false, 0) UIBezierPath(roundedRect: barRect, cornerRadius: bgCornerRadius).addClip() bgColor.set() UIRectFill(rect) let context = UIGraphicsGetCurrentContext() barColor.set() context!.setFillColor(barColor.cgColor.components!) context!.fill(barRect) let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return image } // MARK: - Updating func update() { let offset = (direction == .horizontal ? self.frame.size.height : self.frame.size.width) let halfOffset = offset * 0.5 var size = self.frame.size if direction == .horizontal { size.width -= offset } else { size.height -= offset } currentSelectionX = ((CGFloat(value - minValue) * (size.width)) / CGFloat(maxValue - minValue)) + halfOffset currentSelectionY = ((CGFloat(value - minValue) * (size.height)) / CGFloat(maxValue - minValue)) + halfOffset image = generateHUEImage(self.frame.size) } // MARK: - Drawing override open func draw(_ rect: CGRect) { super.draw(rect) let context = UIGraphicsGetCurrentContext() if useNormalIndicator { var barRect = CGRect.null if direction == .horizontal { let barHeight = rect.size.height * 0.2 barRect = CGRect(x: 0, y: rect.size.height * 0.5 - barHeight * 0.5, width: rect.size.width, height: barHeight) } else { let barWidth = rect.size.width * 0.2 barRect = CGRect(x: rect.size.width * 0.5 - barWidth * 0.5, y: 0, width: barWidth, height: rect.size.height) } let offset = (direction == .horizontal ? self.frame.size.height : self.frame.size.width) let halfOffset = offset * 0.5 var size = self.frame.size let trianglePath = UIBezierPath() if direction == .horizontal { size.width -= offset let triangleHeight = rect.size.height * 0.3 let triangleX = ((CGFloat(normalValue - minValue) * (size.width)) / CGFloat(maxValue - minValue)) + halfOffset trianglePath.move(to: CGPoint(x: triangleX, y: barRect.origin.y)) trianglePath.addLine(to: CGPoint(x: triangleX - triangleHeight * 0.5, y: barRect.origin.y - triangleHeight)) trianglePath.addLine(to: CGPoint(x: triangleX + triangleHeight * 0.5, y: barRect.origin.y - triangleHeight)) trianglePath.addLine(to: CGPoint(x: triangleX, y: barRect.origin.y)) } else { size.height -= offset let triangleWidth = rect.size.width * 0.3 let triangleY = ((CGFloat(normalValue - minValue) * (size.height)) / CGFloat(maxValue - minValue)) + halfOffset trianglePath.move(to: CGPoint(x: barRect.origin.x, y: triangleY)) trianglePath.addLine(to: CGPoint(x: barRect.origin.x - triangleWidth, y: triangleY - triangleWidth * 0.5)) trianglePath.addLine(to: CGPoint(x: barRect.origin.x - triangleWidth, y: triangleY + triangleWidth * 0.5)) trianglePath.addLine(to: CGPoint(x: barRect.origin.x, y: triangleY)) } context!.setFillColor(barColor.cgColor) trianglePath.fill() } let radius = (direction == .horizontal ? self.frame.size.height : self.frame.size.width) let halfRadius = radius * 0.5 var circleX = currentSelectionX - halfRadius var circleY = currentSelectionY - halfRadius if circleX >= rect.size.width - radius { circleX = rect.size.width - radius } else if circleX < 0 { circleX = 0 } if circleY >= rect.size.height - radius { circleY = rect.size.height - radius } else if circleY < 0 { circleY = 0 } let circleRect = (direction == .horizontal ? CGRect(x: circleX, y: 0, width: radius, height: radius) : CGRect(x: 0, y: circleY, width: radius, height: radius)) let circleColor = labelBackgroundColor var imageRect = rect if image != nil { if direction == .horizontal { imageRect.size.width -= radius imageRect.origin.x += halfRadius } else { imageRect.size.height -= radius imageRect.origin.y += halfRadius } image.draw(in: imageRect) } if let image = sliderImage { if direction == .horizontal { context!.translateBy(x: 0, y: imageRect.size.height) context!.scaleBy(x: 1.0, y: -1.0) } else { context!.scaleBy(x: 1.0, y: 1.0) } context!.draw(image.cgImage!, in: (sliderSize != CGSize.zero ? CGRect(x: circleRect.origin.x + sliderImageOffset.x, y: radius * 0.5 - sliderSize.height * 0.5 + sliderImageOffset.y, width: sliderSize.width, height: sliderSize.height) : circleRect)) } else { circleColor.set() context!.addEllipse(in: circleRect) context!.setFillColor(circleColor.cgColor.components!) context!.fillPath() context!.strokePath() let textParagraphStyle = NSMutableParagraphStyle() textParagraphStyle.alignment = .center let attributes: [NSAttributedString.Key : Any] = [NSAttributedString.Key.foregroundColor: labelFontColor, NSAttributedString.Key.paragraphStyle: textParagraphStyle, NSAttributedString.Key.font: labelFont!] let text: NSString = "\(value)" as NSString var textRect = circleRect textRect.origin.y += (textRect.size.height - (labelFont?.lineHeight)!) * 0.5 text.draw(in: textRect, withAttributes: attributes) } } // MARK: - Touch events override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { let touch: AnyObject? = touches.first let point = touch!.location(in: self) handleTouch(point) } override open func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { let touch: AnyObject? = touches.first let point = touch!.location(in: self) handleTouch(point) } override open func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { let touch: AnyObject? = touches.first let point = touch!.location(in: self) handleTouch(point) } override open func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { } // MARK: - Touch handling func handleTouch(_ touchPoint: CGPoint) { currentSelectionX = touchPoint.x currentSelectionY = touchPoint.y let offset = (direction == .horizontal ? self.frame.size.height : self.frame.size.width) let halfOffset = offset * 0.5 if currentSelectionX < halfOffset { currentSelectionX = halfOffset } else if currentSelectionX >= self.frame.size.width - halfOffset { currentSelectionX = self.frame.size.width - halfOffset } if currentSelectionY < halfOffset { currentSelectionY = halfOffset } else if currentSelectionY >= self.frame.size.height - halfOffset { currentSelectionY = self.frame.size.height - halfOffset } let percent = (direction == .horizontal ? CGFloat((currentSelectionX - halfOffset) / (self.frame.size.width - offset)) : CGFloat((currentSelectionY - halfOffset) / (self.frame.size.height - offset))) value = minValue + Int(percent * CGFloat(maxValue - minValue)) if delegate != nil { delegate.swiftlySliderValueChanged(value) } setNeedsDisplay() } }
mit
4818efdc92654cd615e44455f868167b
29.495146
250
0.69012
3.525253
false
false
false
false
TwoRingSoft/shared-utils
Examples/OperationDemo/OperationDemo/DemoCompoundOperation.swift
1
2188
// // CompoundOperation.swift // OperationDemo // // Created by Andrew McKnight on 3/15/16. // Copyright © 2018 Two Ring Software. All rights reserved. // import Cocoa import PippinLibrary final class DemoCompoundOperation: CompoundOperation { private var delegate: OperationStateChangeDelegate private var color: NSColor init(delegate: OperationStateChangeDelegate) { self.delegate = delegate self.color = colors[currentColor % colors.count] currentColor += 1 let op1 = DemoAsyncOperation(delegate: delegate) op1.asyncCompletionBlock = { error in delegate.operationAsyncCompletionCalled(operation: op1) } op1.completionBlock = { delegate.operationSyncCompletionCalled(operation: op1) } let op2 = DemoAsyncOperation(delegate: delegate) op2.asyncCompletionBlock = { error in delegate.operationAsyncCompletionCalled(operation: op2) } op2.completionBlock = { delegate.operationSyncCompletionCalled(operation: op2) } let op3 = DemoAsyncOperation(delegate: delegate) op3.asyncCompletionBlock = { error in delegate.operationAsyncCompletionCalled(operation: op3) } op3.completionBlock = { delegate.operationSyncCompletionCalled(operation: op3) } super.init(operations: [op1, op2, op3]) self.name = "compound \(compoundOperationNumber)" compoundOperationNumber += 1 self.compoundQueue.maxConcurrentOperationCount = 1 self.completionBlock = { delegate.operationSyncCompletionCalled(operation: self) } self.asyncCompletionBlock = { errorOptional in if let error = errorOptional { delegate.operationAsyncCompletionCalled(operation: self, withError: error) } else { delegate.operationAsyncCompletionCalled(operation: self) } } } override func main() { super.main() delegate.operationMainMethodFinished(operation: self) } }
mit
02042604b16a53df0f52835083dea6fe
30.695652
90
0.634659
5.016055
false
false
false
false
CoderAlexChan/AlexCocoa
Extension/Color+extension.swift
1
6548
// // UIColor+Extension.swift // MTodo // // Created by 陈文强 on 16/3/2. // Copyright © 2016 CWQ. All rights reserved. // #if os(iOS) // iOS 系统下 import Foundation import UIKit public typealias Color = UIColor #elseif os(OSX) // OSX 系统下 import Cocoa public typealias Color = NSColor #endif /** * RANDOMCOLOR * 快速对UIView设置随机背景色 * * @param view 需要设置背景色的view */ private let useRandomColor = false private func shouldAutoBackgroundColor() -> Bool { if useRandomColor == true { return AlexCocoa.debug } return false } public func RANDOMCOLOR(_ view: UIView?) { if shouldAutoBackgroundColor() == true { view?.backgroundColor = UIColor.randomColor() } } // MARK: - RandomColor extension Color { /// Create a random color /// 获得一个随机UIColor\NSColor对象 /// /// -return: A new UIColor\NSColor instance public class func randomColor() -> Color { let r : CGFloat = CGFloat(arc4random() % 256) / 255.0 let g : CGFloat = CGFloat(arc4random() % 256) / 255.0 let b : CGFloat = CGFloat(arc4random() % 256) / 255.0 return Color(red: r, green: g, blue: b, alpha: 1) } } // MARK: - Image extension Color { public var toImage: UIImage? { return toImage() } public func toImage(size: CGSize = CGSize(width: 1, height: 1)) -> UIImage? { let rect = CGRect(x: 0.0, y: 0.0, width: size.width, height: size.height) UIGraphicsBeginImageContext(size) let context = UIGraphicsGetCurrentContext() context?.setFillColor(cgColor) context?.fill(rect) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image?.stretch() } } // MARK: - HexColor /// Color /// UIColor\NSColor 的类拓展 /// /// 快速创建UIColor\NSColor对象 extension Color { /// Initializes UIColor\NSColor with an integer. /// 通过16进制数获取一个UIColor\NSColor对象 /// /// -parameter value The integer value of the color. E.g. 0xFF0000 is red, 0x0000FF is blue. public convenience init(_ value: Int) { let components = getColorComponents(value) self.init(red: components.red, green: components.green, blue: components.blue, alpha: 1.0) } /// Initializes UIColor\NSColor with an integer and alpha value. /// 通过16进制数和透明度(alpha)获取一个UIColor\NSColor对象 /// /// -parameter value The integer value of the color /// -parameter alpha The integer alpha of the color public convenience init(_ value: Int, alpha: CGFloat) { let components = getColorComponents(value) self.init(red: components.red, green: components.green, blue: components.blue, alpha: alpha) } /// Creates a new color with the given alpha value /// 通过透明度(alpha)获取一个新的UIColor\NSColor对象 /// /// -parameter value The integer value of the color public func alpha(_ value:CGFloat) -> Color { var red: CGFloat = 0 var green: CGFloat = 0 var blue: CGFloat = 0 var alpha: CGFloat = 0 self.getRed(&red, green: &green, blue: &blue, alpha: &alpha) return Color(red: red, green: green, blue: blue, alpha: value) } /// Mixes the color with another color /// 混合两个color /// /// - parameter color: The color to mix with /// - parameter amount: The amount (0-1) to mix the new color in. /// - returns: A new UIColor instance representing the resulting color public func mix(with color:Color, amount:Float) -> Color { var comp1: [CGFloat] = Array(repeating: 0, count: 4); self.getRed(&comp1[0], green: &comp1[1], blue: &comp1[2], alpha: &comp1[3]) var comp2: [CGFloat] = Array(repeating: 0, count: 4); color.getRed(&comp2[0], green: &comp2[1], blue: &comp2[2], alpha: &comp2[3]) var comp: [CGFloat] = Array(repeating: 0, count: 4); for i in 0...3 { comp[i] = comp1[i] + (comp2[i] - comp1[i]) * CGFloat(amount) } return Color(red:comp[0], green: comp[1], blue: comp[2], alpha: comp[3]) } } // MARK: - ComponmentColor extension Color { var redValue: CGFloat { get { let components = self.cgColor.components return components![0] } } var greenValue: CGFloat { get { let components = self.cgColor.components return components![1] } } var blueValue: CGFloat { get { let components = self.cgColor.components return components![2] } } var alphaValue: CGFloat { get { return self.cgColor.alpha } } func white(_ scale: CGFloat) -> Color { return Color( red: self.redValue + (1.0 - self.redValue) * scale, green: self.greenValue + (1.0 - self.greenValue) * scale, blue: self.blueValue + (1.0 - self.blueValue) * scale, alpha: 1.0 ) } } // MARK: - Description extension Color { /// Hex string of a UIColor instance. /// /// -parameter rgba: Whether the alpha should be included. /// -return: The hex string of the color public func hexString(_ includeAlpha: Bool) -> String { var r: CGFloat = 0.0 var g: CGFloat = 0.0 var b: CGFloat = 0.0 var a: CGFloat = 0.0 self.getRed(&r, green: &g, blue: &b, alpha: &a) if (includeAlpha) { return String(format: "#%02X%02X%02X%02X", Int(r * 255), Int(g * 255), Int(b * 255), Int(a * 255)) } else { return String(format: "#%02X%02X%02X", Int(r * 255), Int(g * 255), Int(b * 255)) } } open override var description: String { return self.hexString(true) } open override var debugDescription: String { return self.hexString(true) } } /// MARK: - Private /// Get (r,g,b) value from color private func getColorComponents(_ value: Int) -> (red: CGFloat, green: CGFloat, blue: CGFloat) { let r = CGFloat(value >> 16 & 0xFF) / 255.0 let g = CGFloat(value >> 8 & 0xFF) / 255.0 let b = CGFloat(value & 0xFF) / 255.0 return (r, g, b) }
mit
943d60f28b10a695465b1f5b2dc0f65c
26.580087
110
0.576362
3.803582
false
false
false
false
ontouchstart/swift3-playground
Swift Standard Library.playground/Pages/Understanding Collection Protocols.xcplaygroundpage/Contents.swift
1
17076
/*: [Table of Contents](Table%20of%20Contents) | [Previous](@previous) | [Next](@next) **** # Understanding Collection Protocols The best way to understand how collection protocols work in the standard library is to implement your own conforming type. Let's build a daily photo app that allows users to capture the most important moment of every day and view these moments in a timeline. To implement the model layer, we'll create a custom collection type that represents a continuous range of dates and associated images. Here's what the finished app looks like: */ import UIKit let app = finishedApp /*: ## Model Architecture When you model your app's storage, it's important to consider the required behaviors and expected performance characteristics. This is true whether you implement your own custom storage or use a combination of standard library data types. For the timeline app, there are three areas to consider: 1. Each date can be associated with an image 2. The timeline displays a continuous, ordered series of days 3. Dates can be incremented arbitrarily and compared in constant time When you look at the sum of these considerations, the built-in collection types can be ruled out. Dictionaries provide adequate representation for pairs of dates and images and support fast retrieval of values using keys, but are not ordered and cannot contain keys that do not have associated values. On the other hand, arrays are ordered but cannot quickly retrieve values using keys. Additionally, there are application-specific constraints and behaviors that could be modeled at a higher level, but would be simpler to maintain in the storage itself. A collection type that is not generic, but instead understands the qualities of the types it contains may provide considerable benefits. Let's examine the second and third areas more closely. The timeline displays an _ordered_ series of days. With a collection that has knowledge of the type of the elements, this is trivial to implement–dates have a natural, well defined order. The series is _continuous_ as well–even if a day is not associated with an image, it is still present in the collection and displayed in the timeline. Therefore, in addition to order, the indices are trivially knowable and can be generated as needed. This means the collection can represent every date in a large span of time–without using any memory for dates without images. Finally, because dates can be incremented and compared in constant time, indexing by date can be implemented in constant time. Therefore, a collection with a date 100 years in the past and 100 years in the future should be just as performance and memory efficient as a collection containing two consecutive dates. With this information, the shape of our collection comes into focus: A collection called `ImageTimeline` with the behaviors and performance characteristics of an array, but with an API that–in some important cases–mirrors that of a dictionary. ## Implementing the Index Before we implement the collection, let's implement the collection's index type–the type you use to iterate over and subscript into the collection. In our `ImageTimeline` type, the indices into the collection are dates. To be used as a collection index, a type must implement basic behavior to support operations like subscripting and `for`-`in` style iteration. At a minimum, an index type must adopt the `Comparable` protocol, so indices can quickly be put in order. Rather than use Foundation's `Date` type itself as the collection's index type, let's wrap the `Date` type in a new `DateIndex` where we can implement additional behavior, starting with this simple structure: */ struct DateIndex { let date: Date } /*: The `Date` type doesn't just store the date–it also stores the time down to the millisecond. Recall that the timeline app is designed to capture and display the most important moment in a user's day. The particular time of day isn't important, and every time a user takes a new photo on the same day it should replace the current photo for that day if one exists. To make it easy to step through and look up images for particular days, the `DateIndex` type needs to normalize the date when one is created. In the extension below, the `DateIndex` structure is extended with a new initializer that uses the `startOfDay(for:)` method on the user's current calendar to shift the provided date to the first moment in that date's day. As long as the rest of the collection implementation traffics in `DateIndex` objects rather than directly in `Date` objects, we can be sure that the time of day of a date will not impact comparison, iteration, or image lookup. */ private let calendar = Calendar.current extension DateIndex { init (_ date: Date) { self.date = calendar.startOfDay(for: date) } } /*: After you write the basic implementation of a type, it's useful to adopt the `CustomDebugStringConvertible` protocol. Whenever you use the type in a playground or as an argument to the `debugPrint` function, the `debugDescription` property is used to print a description of the type. You can read more about custom descriptions in [Customizing Textual Representations](Customizing%20Textual%20Representations). In the code below, the `DateIndex` structure conforms to `CustomDebugStringConvertible` and returns the stored date as a simple string containing the month and the day. */ let dateFormatter = DateFormatter() dateFormatter.dateFormat = DateFormatter.dateFormat(fromTemplate: "MMMM d", options: 0, locale: .current) extension DateIndex: CustomDebugStringConvertible { var debugDescription: String { return dateFormatter.string(from: date) } } /*: Now that instances of `DateIndex` are normalized and debuggable, the next step is to adopt the `Comparable` protocol. There are two requirements in the `Comparable` protocol: You must provide a less-than operator (`<`) and an equal-to operator (`==`). Using your implementations, the standard library fills in the rest of the relational operators, so you can use `>`, `<=`, `>=`, and `!=` without any additional code on your part. */ func < (lhs: DateIndex, rhs: DateIndex) -> Bool { return lhs.date.compare(rhs.date) == .orderedAscending } extension DateIndex: Comparable { } /*: The `Comparable` protocol inherits from the `Equatable` protocol. The `Date` type already implements the `==` operator (by implementing the `isEqual:` method), so the operator implementation below simply compares the indices' dates. After implementing this operator, the `DateIndex` structure completely adopts the `Comparable` protocol. */ func == (lhs: DateIndex, rhs: DateIndex) -> Bool { return lhs.date == rhs.date } extension DateIndex: Equatable { } /*: ## Implementing the Collection To implement a type that conforms to the `Collection` protocol, you implement–at a minimum–four requirements of the protocol: 1. A property called `startIndex` that returns the first index in the collection. 2. A property called `endIndex` that returns the index one past the end. 3. A function called `index(after:)` that advances an index by one position. 4. A subscript that accepts an index and returns an element in the collection. In addition to these syntactically defined requirements, there are also _semantic_ and _performance_ requirements. These are requirements that cannot be expressed in code, but are still equally important. The `Collection` protocol documentation contains two such requirements: * Computing the each of these requirements—the start and end index, the successor of an index, and the value at a specific index—must be a constant-time (`O(1)`) operation. Otherwise, generic collection algorithms would have inconsistent or unexpected performance characteristics. * The successor of an index must be well-defined. In other words, you must consistently return the same successor from the `index(after:)` method for a given index. From these four requirements, the remaining requirements in the `Collection` protocol—such as `makeIterator()`, `isEmpty`, and `count`—are implemented for you using default implementations in protocol extensions. For example, the `isEmpty` property has a default implementation expressed in terms of the `startIndex` and `endIndex`: If the `startIndex` and `endIndex` are equal, then there are no elements in the collection. In the code below, we implement the `ImageTimeline` structure and the minimum syntactic, semantic, and performance requirements to act as a collection. The timeline collection implements its underlying storage as a dictionary of `DateIndex`-`UIImage` pairs for performance and efficiency, but provides access to this storage through `DateIndex` APIs to maintain our high level constraints. This achieves performance characteristics and API influenced by both `Array` and `Dictionary`–while maintaining higher level application constraints like order. - Note: Although we're learning about the `Collection` protocol now, we need to declare conformance in this declaration to the `RandomAccessCollection` protocol and declare the `index(before:)` method, which satisfies a `BidirectionalCollection` protocol requirement. You'll read more about `BidirectionalCollection` and `RandomAccessCollection` below. */ struct ImageTimeline: RandomAccessCollection { private var storage: [Date: UIImage] = [:] var startIndex = DateIndex(Date.distantPast) var endIndex = DateIndex(Date.distantPast) func index(after i: DateIndex) -> DateIndex { let nextDay = calendar.date(byAdding: .day, value: 1, to: i.date)! return DateIndex(nextDay) } func index(before i: DateIndex) -> DateIndex { let previousDay = calendar.date(byAdding: .day, value: -1, to: i.date)! return DateIndex(previousDay) } subscript (i: DateIndex) -> UIImage? { get { return storage[i.date] } set { // `ImageTimeline` expands dynamically to include the earliest // and latest dates. To implement this functionality, any time // a new date-image pair is stored using this subscript, we check // to see if the date is before the `startIndex` or after the // `endIndex`. Additionally, if the `startIndex` is one of the // placeholder dates, we adjust the `startIndex` upwards to the // passed-in date. if isEmpty { startIndex = i endIndex = index(after: i) } else if i < startIndex { startIndex = i } else if i >= endIndex { endIndex = index(after: i) } storage[i.date] = newValue } } } /*: In particular, note that the `index(after:)` method creates a new date by incrementing the given index's date by one day and then returns a new `DateIndex` instance with the new date. Because successive dates are consistently producible and can be computed in constant time, we have satisfied both additional documented requirements. We'll also implement a subscript and range operators that take `Date` objects and wrap them up as `DateIndex` instances. While the collection uses normalized `DateIndex` objects in its implementation, it surfaces those implementation details as little as possible as they are not semantically important. */ extension ImageTimeline { subscript (date: Date) -> UIImage? { get { return self[DateIndex(date)] } set { self[DateIndex(date)] = newValue } } } func ... (lhs: Date, rhs: Date) -> ClosedRange<DateIndex> { return DateIndex(lhs)...DateIndex(rhs) } func ..< (lhs: Date, rhs: Date) -> Range<DateIndex> { return DateIndex(lhs)..<DateIndex(rhs) } /*: At this point, we've implemented everything that's required for `ImageTimeline` to conform to the `Collection` protocol. The Swift standard library includes default implementations that use the methods and properties we've defined so far to implement the remaining `Collection` requirements like `count`, `map`, and efficient slicing. Let's take a look at the timeline of images in action: */ var timeline = ImageTimeline() for elem in loadElements() { timeline[elem.date] = elem.image } maySeventh let image = timeline[maySeventh] let view = UIView(frame: CGRect(x: 0, y: 0, width: timeline.count * 75, height: 75)) for (position, image) in timeline.enumerated() { let imageView = UIImageView(frame: CGRect(x: position * 75, y: 0, width: 75, height: 75)) imageView.image = image ?? UIImage(named: "NoImage.jpg") view.addSubview(imageView) } view /*: ## Refining the Collection The timeline collection now sufficiently implements the syntactic, semantic, and performance requirements of the `Collection` protocol. However, we've missed out on some easy performance enhancements and additional functionality. By continually refining the collection, we can drastically improve performance and opt in to additional functionality. The first of these refinements is the `BidirectionalCollection` protocol. The `BidirectionalCollection` protocol inherits from the `Collection` protocol and adds one method, `index(before:)`. The `index(before:)` method mirrors the `index(after:)` method–including the semantic and performance requirements–and decrements the index by one. Using the same constant time `Calendar` method, the extension below adopts `BidirectionalCollection` and implements the `index(before:)` method. By adopting the `BidirectionalCollection` protocol, the timeline collection gains access to additional default implementation, such as `reverse()`, which provides an efficient reverse view into the collection, and a more efficient `suffix(_:)` operation. extension ImageTimeline: BidirectionalCollection { func index(before i: DateIndex) -> DateIndex { let previousDay = calendar.date(byAdding: .day, value: -1, to: i.date)! return DateIndex(previousDay) } } The default implementation for `count` that is applied to forward or bidirectional collections retrieves the `startIndex` and then counts how many times `index(after:)` must be called to reach the `endIndex` of the collection. This is a reasonable `O(n)` implementation, but offers poor performance in the case where dates with images are spread far apart. It's also a problem that's easily resolved with a constant time implementation because dates are used as indices. The `RandomAccessCollection` protocol can be adopted by collections that are able to compute the distance between two indices and advance multiple positions in constant time. For example, an array's index type is `Int`. `Array` conforms to `RandomAccessCollection` because you can add an offset to a position represented by an integer in constant time. When you adopt the `RandomAccessCollection` protocol, a more specific, faster default implementation for collection APIs like `count` is used instead. Conforming to `RandomAccessCollection` imposes only _performance_ requirements. The methods defined below are provided to every collection through default implementations—a random access collection must implement both methods as `O(1)` operations to meet the performance expectations of the `RandomAccessCollection` protocol. The code below implements its two requirements in terms of `Calendar` methods that compute and compare dates. */ extension ImageTimeline { func distance(from start: DateIndex, to end: DateIndex) -> Int { return calendar.dateComponents([.day], from: start.date, to: end.date).day! } func index(_ i: DateIndex, offsetBy n: Int) -> DateIndex { let offsetDate = calendar.date(byAdding: .day, value: n, to: i.date)! return DateIndex(offsetDate) } } let fastCount = timeline.count /*: Here is the completed photo memory app: */ visualize(timeline) /*: - callout(Checkpoint): At this point you've processed and sliced collections using generic algorithms, and you've learned how standard library protocols combine to define collections and sequences. The concepts you've learned on this page apply whether or not you plan to implement your own custom collection type. By understanding how the standard library divides functionality into small protocols that work together to define many different types, you can write generic code that is flexible and expressive. More generally, the design patterns used by the standard library apply to your own code–consider reaching first for protocols and structures to improve how you reason about your code. In the next section, you'll convert the `ImageTimeline` from a collection of images to a generic collection that can store a timeline of any type of element. **** [Table of Contents](Table%20of%20Contents) | [Previous](@previous) | [Next](@next) */
mit
de0ec3ea36b4a4f279c93f10be56a328
74.39823
933
0.754049
4.762437
false
false
false
false
fandongtongxue/Unsplash
Unsplash/Controller/PictureViewController.swift
1
7389
// // PictureViewController.swift // Unsplash // // Created by 范东 on 17/2/6. // Copyright © 2017年 范东. All rights reserved. // import UIKit import SDWebImage import MBProgressHUD class PictureViewController: UIViewController { var model : UnsplashPictureModel! var finalImage : UIImage! lazy var progressView:UIProgressView = { let progressView = UIProgressView.init(frame: CGRect.init(x: 0, y: statusBarHeight, width: screenWidth, height: 2)) progressView.progressViewStyle = UIProgressViewStyle.bar progressView.tintColor = UIColor.white return progressView }() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.view.backgroundColor = UIColor.black self.finalImage = nil; //Log log.info("图片宽:" + (self.model?.width)! + "高:" + (self.model?.height)!) //初始化滚动视图坐标 var scrollViewHeight : CGFloat = 0.0 scrollViewHeight = screenHeight - statusBarHeight var scrollViewWidth : CGFloat = 0.0 scrollViewWidth = self.stringToFloat(str: (self.model?.width)!) * scrollViewHeight / self.stringToFloat(str: (self.model?.height)!) log.info("适应后图片宽:" + String.init(format: "%.2f", scrollViewWidth) + "高:" + String.init(format: "%.2f", scrollViewHeight)) //滚动视图 let scrollView = UIScrollView.init(frame: CGRect.init(x: 0, y: statusBarHeight, width: screenWidth, height: screenHeight - statusBarHeight)) scrollView.contentSize = CGSize.init(width: scrollViewWidth, height: scrollViewHeight) self.view.addSubview(scrollView) //图片 let imageView = UIImageView.init(frame: CGRect.init(x: 0, y: 0, width: scrollView.contentSize.width, height: scrollView.contentSize.height)) imageView.contentMode = UIViewContentMode.scaleAspectFill scrollView.addSubview(imageView) log.info("图片地址" + (self.model?.urls.regular)!) imageView.sd_setImage(with: URL.init(string: (self.model?.urls.regular)!), placeholderImage: nil, options: SDWebImageOptions.progressiveDownload, progress: { (complete, total) in // log.info("已完成" + String.init(format: "%dKB", complete / 1024)) // log.info("总共" + String.init(format: "%dKB", total / 1024)) // log.info("图片下载进度" + String.init(format: "%.2f", Float(complete) / Float(total))) self.progressView.setProgress(Float(complete) / Float(total), animated: true) }, completed: { (image, error, cacheType, url) in self.progressView.progress = 0 self.finalImage = image; }) self.view.addSubview(self.progressView) //下滑手势 let swipe = UISwipeGestureRecognizer.init(target: self, action: #selector(dismissVC)) swipe.direction = UISwipeGestureRecognizerDirection.down self.view.addGestureRecognizer(swipe) // //工具栏 // let toolView = UIView.init(frame: CGRect.init(x: 10, y: screenHeight - 60, width: screenWidth - 20, height: 50)) // toolView.backgroundColor = UIColor.white // toolView.layer.cornerRadius = 5 // toolView.clipsToBounds = true // self.view.addSubview(toolView) // //下载按钮 // let downloadBtn = UIButton.init(frame: CGRect.init(x: 5, y: 5, width: 40, height: 40)) // downloadBtn.setImage(UIImage.init(named: "picture_btn_download"), for: UIControlState.normal) // downloadBtn.setImage(UIImage.init(named: "picture_btn_download"), for: UIControlState.highlighted) // downloadBtn.addTarget(self, action: #selector(downloadBtnAction), for: UIControlEvents.touchUpInside) // toolView.addSubview(downloadBtn) // //分享按钮 // let shareBtn = UIButton.init(frame: CGRect.init(x: 50, y: 5, width: 40, height: 40)) // shareBtn.setImage(UIImage.init(named: "picture_btn_share"), for: UIControlState.normal) // shareBtn.setImage(UIImage.init(named: "picture_btn_share"), for: UIControlState.highlighted) // shareBtn.addTarget(self, action: #selector(shareBtnAction), for: UIControlEvents.touchUpInside) // toolView.addSubview(shareBtn) } func dismissVC() { self.dismiss(animated: true, completion: nil) } func downloadBtnAction() { log.info("点击下载图片"+self.model.urls.raw) if self.finalImage != nil { UIImageWriteToSavedPhotosAlbum(self.finalImage, self, #selector(image(image:didFinishSavingWithError:contextInfo:)), nil) }else{ let hud = MBProgressHUD.showAdded(to: self.view, animated: true) hud.mode = MBProgressHUDMode.text hud.label.text = "未完成下载" hud.label.numberOfLines = 0; hud.hide(animated: true, afterDelay: 1) } } func image(image: UIImage, didFinishSavingWithError: NSError?,contextInfo: AnyObject) { let hud = MBProgressHUD.showAdded(to: self.view, animated: true) hud.mode = MBProgressHUDMode.text if didFinishSavingWithError != nil { log.info("保存失败"+String.init(format: "%@", didFinishSavingWithError!)) hud.label.text = String.init(format: "%@", didFinishSavingWithError!) } else { log.info("保存成功") hud.label.text = "保存成功" } hud.label.numberOfLines = 0; hud.hide(animated: true, afterDelay: 1) } func shareBtnAction() { log.info("分享图片"+self.model.urls.raw) if self.finalImage != nil { let activityItems = NSArray.init(object:self.finalImage) let activityVC:UIActivityViewController = UIActivityViewController.init(activityItems: activityItems as! [Any], applicationActivities: nil) activityVC.excludedActivityTypes = NSArray.init(objects:UIActivityType.airDrop,UIActivityType.postToWeibo,UIActivityType.mail,UIActivityType.saveToCameraRoll) as? [UIActivityType] self.present(activityVC, animated: true, completion: nil) }else{ let hud = MBProgressHUD.showAdded(to: self.view, animated: true) hud.mode = MBProgressHUDMode.text hud.label.text = "未完成下载" hud.label.numberOfLines = 0; hud.hide(animated: true, afterDelay: 1) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override var preferredStatusBarStyle: UIStatusBarStyle{ return UIStatusBarStyle.lightContent } //String to Float func stringToFloat(str:String)->(CGFloat){ let string = str var cgFloat: CGFloat = 0 if let doubleValue = Double(string) { cgFloat = CGFloat(doubleValue) } return cgFloat } /* // 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. } */ }
mit
8cf915527d0407acf5eb5cc88cce17a6
44.295597
191
0.652041
4.407589
false
false
false
false
monyschuk/CwlSignal
Tests/CwlSignalTests/CwlSignalTests.swift
1
63592
// // CwlSignalTests.swift // CwlSignal // // Created by Matt Gallagher on 2016/06/08. // Copyright © 2016 Matt Gallagher ( http://cocoawithlove.com ). All rights reserved. // // Permission to use, copy, modify, and/or distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY // SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR // IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. // import Foundation import XCTest import CwlSignal import CwlPreconditionTesting #if SWIFT_PACKAGE import CwlUtils #endif private enum TestError: Error { case zeroValue case oneValue case twoValue } class SignalTests: XCTestCase { func testBasics() { var results = [Result<Int>]() let (i1, ep) = Signal<Int>.create { $0.subscribe { r in results.append(r) } } i1.send(result: .success(1)) i1.send(value: 3) XCTAssert(ep.isClosed == false) ep.cancel() XCTAssert(ep.isClosed == true) i1.send(value: 5) XCTAssert(results.at(0)?.value == 1) XCTAssert(results.at(1)?.value == 3) withExtendedLifetime(ep) {} let (i2, ep2) = Signal<Int>.create { $0.transform { r, n in n.send(result: r) }.subscribe { r in results.append(r) } } i2.send(result: .success(5)) i2.send(error: TestError.zeroValue) XCTAssert(i2.send(value: 0) == SignalError.cancelled) XCTAssert(results.at(2)?.value == 5) XCTAssert(results.at(3)?.error as? TestError == TestError.zeroValue) ep2.cancel() _ = Signal<Int>.preclosed().subscribe { r in results.append(r) } XCTAssert(results.at(4)?.isSignalClosed == true) } func testKeepAlive() { var results = [Result<Int>]() let (i, _) = Signal<Int>.create { $0.subscribeAndKeepAlive { r in results.append(r) return r.value != 7 } } i.send(value: 5) i.send(value: 7) i.send(value: 9) i.close() XCTAssert(results.count == 2) XCTAssert(results.at(0)?.value == 5) XCTAssert(results.at(1)?.value == 7) } func testLifetimes() { weak var weakEndpoint1: SignalEndpoint<Int>? = nil weak var weakToken: NSObject? = nil weak var weakSignal1: Signal<Int>? = nil weak var weakSignal2: Signal<Int>? = nil var results1 = [Result<Int>]() var results2 = [Result<Int>]() do { let (input1, signal1) = Signal<Int>.create() weakSignal1 = signal1 do { let endPoint = signal1.subscribe { (r: Result<Int>) in results1.append(r) } weakEndpoint1 = endPoint input1.send(result: .success(5)) XCTAssert(weakEndpoint1 != nil) XCTAssert(weakSignal1 != nil) withExtendedLifetime(endPoint) {} } XCTAssert(weakEndpoint1 == nil) let (input2, signal2) = Signal<Int>.create() weakSignal2 = signal2 do { do { let token = NSObject() signal2.subscribeAndKeepAlive { (r: Result<Int>) in withExtendedLifetime(token) {} results2.append(r) return true } weakToken = token } input2.send(result: .success(5)) XCTAssert(weakToken != nil) XCTAssert(weakSignal2 != nil) } XCTAssert(weakToken != nil) input2.close() } XCTAssert(results1.count == 1) XCTAssert(results1.at(0)?.value == 5) XCTAssert(weakSignal1 == nil) XCTAssert(weakToken == nil) XCTAssert(results2.count == 2) XCTAssert(results2.at(0)?.value == 5) XCTAssert(results2.at(1)?.error as? SignalError == .closed) XCTAssert(weakSignal2 == nil) } func testCreate() { // Create a signal with default behavior let (input, signal) = Signal<Int>.create() // Make sure we get an .Inactive response before anything is connected XCTAssert(input.send(result: .success(321)) == SignalError.inactive) // Subscribe var results = [Result<Int>]() let (context, specificKey) = Exec.syncQueueWithSpecificKey() let ep1 = signal.subscribe(context: context) { r in XCTAssert(DispatchQueue.getSpecific(key: specificKey) != nil) results.append(r) } // Ensure we don't immediately receive anything XCTAssert(results.count == 0) // Adding a second subscriber cancels the first var results2 = [Result<Int>]() let ep2 = signal.subscribe { r in results2.append(r) } XCTAssert(results2.count == 1) XCTAssert(results2.at(0)?.error as? SignalError == SignalError.duplicate) // Send a value and close XCTAssert(input.send(result: .success(123)) == nil) XCTAssert(input.send(result: .failure(SignalError.closed)) == nil) // Confirm sending worked XCTAssert(results.count == 2) XCTAssert(results.at(0)?.value == 123) XCTAssert(results.at(1)?.error as? SignalError == SignalError.closed) // Confirm we can't send to a closed signal XCTAssert(input.send(result: .success(234)) == SignalError.cancelled) withExtendedLifetime(ep1) {} withExtendedLifetime(ep2) {} } func testSignalPassthrough() { // Create a restartable let (input, s) = Signal<Int>.create() let signal = s.multicast() // Make sure we get an .Inactive response before anything is connected XCTAssert(input.send(result: .success(321)) == SignalError.inactive) // Subscribe send and close var results1 = [Result<Int>]() let ep1 = signal.subscribe { r in results1.append(r) } // Ensure we don't immediately receive anything XCTAssert(results1.count == 0) // Send a value and close XCTAssert(input.send(result: .success(123)) == nil) XCTAssert(results1.count == 1) XCTAssert(results1.at(0)?.value == 123) // Subscribe and send again, leaving open var results2 = [Result<Int>]() let ep2 = signal.subscribe { r in results2.append(r) } XCTAssert(input.send(result: .success(345)) == nil) XCTAssert(results1.count == 2) XCTAssert(results1.at(1)?.value == 345) XCTAssert(results2.count == 1) XCTAssert(results2.at(0)?.value == 345) // Add a third subscriber var results3 = [Result<Int>]() let ep3 = signal.subscribe { r in results3.append(r) } XCTAssert(input.send(result: .success(678)) == nil) XCTAssert(input.close() == nil) XCTAssert(results1.count == 4) XCTAssert(results1.at(2)?.value == 678) XCTAssert(results1.at(3)?.error as? SignalError == .closed) XCTAssert(results3.count == 2) XCTAssert(results3.at(0)?.value == 678) XCTAssert(results3.at(1)?.error as? SignalError == .closed) XCTAssert(results2.count == 3) XCTAssert(results2.at(1)?.value == 678) XCTAssert(results2.at(2)?.error as? SignalError == .closed) XCTAssert(input.send(value: 0) == .cancelled) withExtendedLifetime(ep1) {} withExtendedLifetime(ep2) {} withExtendedLifetime(ep3) {} } func testSignalContinuous() { // Create a signal let (input, s) = Signal<Int>.create() let signal = s.continuous() // Subscribe twice var results1 = [Result<Int>]() let ep1 = signal.subscribe { r in results1.append(r) } var results2 = [Result<Int>]() let ep2 = signal.subscribe { r in results2.append(r) } // Ensure we don't immediately receive anything XCTAssert(results1.count == 0) XCTAssert(results2.count == 0) // Send a value and leave open XCTAssert(input.send(result: .success(123)) == nil) // Confirm receipt XCTAssert(results1.count == 1) XCTAssert(results1.at(0)?.value == 123) XCTAssert(results2.count == 1) XCTAssert(results2.at(0)?.value == 123) // Subscribe again var results3 = [Result<Int>]() let ep3 = signal.subscribe { r in results3.append(r) } XCTAssert(results3.count == 1) XCTAssert(results3.at(0)?.value == 123) // Send another XCTAssert(input.send(result: .success(234)) == nil) // Subscribe again, leaving open var results4 = [Result<Int>]() let ep4 = signal.subscribe { r in results4.append(r) } XCTAssert(results4.count == 1) XCTAssert(results4.at(0)?.value == 234) // Confirm receipt XCTAssert(results1.count == 2) XCTAssert(results1.at(1)?.value == 234) XCTAssert(results2.count == 2) XCTAssert(results2.at(1)?.value == 234) XCTAssert(results3.count == 2) XCTAssert(results3.at(1)?.value == 234) XCTAssert(results4.count == 1) XCTAssert(results4.at(0)?.value == 234) // Close XCTAssert(input.send(result: .failure(SignalError.closed)) == nil) XCTAssert(results1.count == 3) XCTAssert(results1.at(2)?.error as? SignalError == SignalError.closed) XCTAssert(results2.count == 3) XCTAssert(results2.at(2)?.error as? SignalError == SignalError.closed) XCTAssert(results3.count == 3) XCTAssert(results3.at(2)?.error as? SignalError == SignalError.closed) XCTAssert(results4.count == 2) XCTAssert(results4.at(1)?.error as? SignalError == SignalError.closed) // Subscribe again, leaving open var results5 = [Result<Int>]() let ep5 = signal.subscribe { r in results5.append(r) } XCTAssert(results5.count == 1) XCTAssert(results5.at(0)?.error as? SignalError == SignalError.closed) withExtendedLifetime(ep1) {} withExtendedLifetime(ep2) {} withExtendedLifetime(ep3) {} withExtendedLifetime(ep4) {} withExtendedLifetime(ep5) {} } func testSignalContinuousWithinitial() { // Create a signal let (input, s) = Signal<Int>.create() let signal = s.continuous(initial: 5) // Subscribe twice var results1 = [Result<Int>]() let ep1 = signal.subscribe { r in results1.append(r) } var results2 = [Result<Int>]() let ep2 = signal.subscribe { r in results2.append(r) } // Ensure we immediately receive the initial XCTAssert(results1.count == 1) XCTAssert(results1.at(0)?.value == 5) XCTAssert(results2.count == 1) XCTAssert(results2.at(0)?.value == 5) // Send a value and leave open XCTAssert(input.send(result: .success(123)) == nil) // Confirm receipt XCTAssert(results1.count == 2) XCTAssert(results1.at(1)?.value == 123) XCTAssert(results2.count == 2) XCTAssert(results2.at(1)?.value == 123) withExtendedLifetime(ep1) {} withExtendedLifetime(ep2) {} } func testSignalPlayback() { // Create a signal let (input, s) = Signal<Int>.create() let signal = s.playback() // Send a value and leave open XCTAssert(input.send(value: 3) == nil) XCTAssert(input.send(value: 4) == nil) XCTAssert(input.send(value: 5) == nil) // Subscribe twice var results1 = [Result<Int>]() let ep1 = signal.subscribe { r in results1.append(r) } var results2 = [Result<Int>]() let ep2 = signal.subscribe { r in results2.append(r) } // Ensure we immediately receive the values XCTAssert(results1.count == 3) XCTAssert(results1.at(0)?.value == 3) XCTAssert(results1.at(1)?.value == 4) XCTAssert(results1.at(2)?.value == 5) XCTAssert(results2.count == 3) XCTAssert(results2.at(0)?.value == 3) XCTAssert(results2.at(1)?.value == 4) XCTAssert(results2.at(2)?.value == 5) // Send a value and leave open XCTAssert(input.send(result: .success(6)) == nil) // Confirm receipt XCTAssert(results1.count == 4) XCTAssert(results1.at(3)?.value == 6) XCTAssert(results2.count == 4) XCTAssert(results2.at(3)?.value == 6) // Close XCTAssert(input.send(error: SignalError.closed) == nil) // Subscribe again var results3 = [Result<Int>]() let ep3 = signal.subscribe { r in results3.append(r) } XCTAssert(results1.count == 5) XCTAssert(results2.count == 5) XCTAssert(results3.count == 5) XCTAssert(results1.at(4)?.isSignalClosed == true) XCTAssert(results2.at(4)?.isSignalClosed == true) XCTAssert(results3.at(0)?.value == 3) XCTAssert(results3.at(1)?.value == 4) XCTAssert(results3.at(2)?.value == 5) XCTAssert(results3.at(3)?.value == 6) XCTAssert(results3.at(4)?.isSignalClosed == true) withExtendedLifetime(ep1) {} withExtendedLifetime(ep2) {} withExtendedLifetime(ep3) {} } func testSignalCacheUntilActive() { // Create a signal let (input, s) = Signal<Int>.create() let signal = s.cacheUntilActive() // Send a value and leave open XCTAssert(input.send(result: .success(5)) == nil) do { // Subscribe once var results1 = [Result<Int>]() let ep1 = signal.subscribe { r in results1.append(r) } // Ensure we immediately receive the values XCTAssert(results1.count == 1) XCTAssert(results1.at(0)?.value == 5) // Subscribe again var results2 = [Result<Int>]() let ep2 = signal.subscribe { r in results2.append(r) } // Ensure error received XCTAssert(results2.count == 1) XCTAssert(results2.at(0)?.error as? SignalError == SignalError.duplicate) withExtendedLifetime(ep1) {} withExtendedLifetime(ep2) {} } // Send a value again XCTAssert(input.send(result: .success(7)) == nil) do { // Subscribe once var results3 = [Result<Int>]() let ep3 = signal.subscribe { r in results3.append(r) } // Ensure we get just the value sent after reactivation XCTAssert(results3.count == 1) XCTAssert(results3.at(0)?.value == 7) withExtendedLifetime(ep3) {} } } func testSignalCustomActivation() { // Create a signal let (input, s) = Signal<Int>.create() let (context, specificKey) = Exec.syncQueueWithSpecificKey() let signal = s.customActivation(initial: [3, 4], context: context) { (activationValues: inout Array<Int>, preclosed: inout Error?, result: Result<Int>) -> Void in XCTAssert(DispatchQueue.getSpecific(key: specificKey) != nil) if case .success(6) = result { activationValues = [7] } } // Send a value and leave open XCTAssert(input.send(value: 5) == nil) // Subscribe twice var results1 = [Result<Int>]() let ep1 = signal.subscribe { r in results1.append(r) } var results2 = [Result<Int>]() let ep2 = signal.subscribe { r in results2.append(r) } // Ensure we immediately receive the values XCTAssert(results1.count == 2) XCTAssert(results1.at(0)?.value == 3) XCTAssert(results1.at(1)?.value == 4) XCTAssert(results2.count == 2) XCTAssert(results2.at(0)?.value == 3) XCTAssert(results2.at(1)?.value == 4) // Send a value and leave open XCTAssert(input.send(value: 6) == nil) // Confirm receipt XCTAssert(results1.count == 3) XCTAssert(results1.at(2)?.value == 6) XCTAssert(results2.count == 3) XCTAssert(results2.at(2)?.value == 6) // Subscribe again var results3 = [Result<Int>]() let ep3 = signal.subscribe { r in results3.append(r) } XCTAssert(results1.count == 3) XCTAssert(results2.count == 3) XCTAssert(results3.at(0)?.value == 7) withExtendedLifetime(ep1) {} withExtendedLifetime(ep2) {} withExtendedLifetime(ep3) {} } func testPreclosed() { var results1 = [Result<Int>]() _ = Signal<Int>.preclosed(values: [1, 3, 5], error: TestError.oneValue).subscribe { r in results1.append(r) } XCTAssert(results1.count == 4) XCTAssert(results1.at(0)?.value == 1) XCTAssert(results1.at(1)?.value == 3) XCTAssert(results1.at(2)?.value == 5) XCTAssert(results1.at(3)?.error as? TestError == .oneValue) var results2 = [Result<Int>]() _ = Signal<Int>.preclosed().subscribe { r in results2.append(r) } XCTAssert(results2.count == 1) XCTAssert(results2.at(0)?.error as? SignalError == .closed) var results3 = [Result<Int>]() _ = Signal<Int>.preclosed(7).subscribe { r in results3.append(r) } XCTAssert(results3.count == 2) XCTAssert(results3.at(0)?.value == 7) XCTAssert(results3.at(1)?.error as? SignalError == .closed) } func testCapture() { let (input, s) = Signal<Int>.create() let signal = s.continuous() input.send(value: 1) let capture = signal.capture() var results = [Result<Int>]() let (subsequentInput, subsequentSignal) = Signal<Int>.create() let ep = subsequentSignal.subscribe { (r: Result<Int>) in results.append(r) } // Send a value between construction and join. This must be *blocked* in the capture queue. XCTAssert(input.send(value: 5) == nil) let (values, error) = capture.activation() do { try capture.join(to: subsequentInput) } catch { XCTFail() } input.send(value: 3) input.close() XCTAssert(values == [1]) XCTAssert(error == nil) XCTAssert(results.count == 3) XCTAssert(results.at(0)?.value == 5) XCTAssert(results.at(1)?.value == 3) XCTAssert(results.at(2)?.isSignalClosed == true) withExtendedLifetime(ep) {} } func testCaptureAndSubscribe() { let (input, output) = Signal<Int>.create { signal in signal.continuous() } input.send(value: 1) input.send(value: 2) do { let capture = output.capture() let (values, error) = capture.activation() XCTAssert(values == [2]) XCTAssert(error == nil) input.send(value: 3) var results = [Result<Int>]() _ = capture.subscribe { r in results += r } XCTAssert(results.count == 1) XCTAssert(results.at(0)?.value == 3) } do { let capture = output.capture() let (values, error) = capture.activation() XCTAssert(values == [3]) XCTAssert(error == nil) input.send(value: 4) var results = [Result<Int>]() _ = capture.subscribe(onError: { (j, e, i) in }) { r in results += r } XCTAssert(results.count == 1) XCTAssert(results.at(0)?.value == 4) } withExtendedLifetime(input) {} } func testCaptureAndSubscribeValues() { let (input, output) = Signal<Int>.create { signal in signal.continuous() } input.send(value: 1) input.send(value: 2) do { let capture = output.capture() let (values, error) = capture.activation() XCTAssert(values == [2]) XCTAssert(error == nil) input.send(value: 3) var results = [Int]() _ = capture.subscribeValues { r in results += r } XCTAssert(results.count == 1) XCTAssert(results.at(0) == 3) } do { let capture = output.capture() let (values, error) = capture.activation() XCTAssert(values == [3]) XCTAssert(error == nil) input.send(value: 4) var results = [Int]() _ = capture.subscribeValues(onError: { (j, e, i) in }) { r in results += r } XCTAssert(results.count == 1) XCTAssert(results.at(0) == 4) } withExtendedLifetime(input) {} } func testCaptureOnError() { let (input, s) = Signal<Int>.create() let signal = s.continuous() input.send(value: 1) let capture = signal.capture() var results = [Result<Int>]() let (subsequentInput, subsequentSignal) = Signal<Int>.create() let ep1 = subsequentSignal.subscribe { (r: Result<Int>) in results.append(r) } let (values, error) = capture.activation() do { try capture.join(to: subsequentInput) { (c: SignalCapture<Int>, e: Error, i: SignalInput<Int>) in XCTAssert(c === capture) XCTAssert(e as? SignalError == .closed) i.send(error: TestError.twoValue) } } catch { XCTFail() } input.send(value: 3) input.close() XCTAssert(values == [1]) XCTAssert(error == nil) XCTAssert(results.count == 2) XCTAssert(results.at(0)?.value == 3) XCTAssert(results.at(1)?.error as? TestError == .twoValue) let (values2, error2) = capture.activation() XCTAssert(values2.count == 0) XCTAssert(error2 as? SignalError == .closed) let pc = Signal<Int>.preclosed(values: [], error: TestError.oneValue) let capture2 = pc.capture() let (values3, error3) = capture2.activation() var results2 = [Result<Int>]() let (subsequentInput2, subsequentSignal2) = Signal<Int>.create() let ep2 = subsequentSignal2.subscribe { (r: Result<Int>) in results2.append(r) } do { try capture2.join(to: subsequentInput2, resend: true) { (c, e, i) in XCTAssert(c === capture2) XCTAssert(e as? TestError == .oneValue) i.send(error: TestError.zeroValue) } } catch { XCTFail() } XCTAssert(values3 == []) XCTAssert(error3 as? TestError == .oneValue) XCTAssert(results2.count == 1) XCTAssert(results2.at(0)?.error as? TestError == .zeroValue) withExtendedLifetime(ep1) {} withExtendedLifetime(ep2) {} } func testGenerate() { var count = 0 var results = [Result<Int>]() weak var lifetimeCheck: Box<()>? = nil var nilCount = 0 do { let closureLifetime = Box<()>(()) lifetimeCheck = closureLifetime let (context, specificKey) = Exec.syncQueueWithSpecificKey() let s = Signal<Int>.generate(context: context) { input in XCTAssert(DispatchQueue.getSpecific(key: specificKey) != nil) guard let i = input else { switch (results.count, nilCount) { case (0, 0), (6, 0), (12, 1): nilCount += 1 default: XCTFail() } return } if count == 0 { count += 1 for j in 0..<5 { i.send(value: j) } i.send(error: TestError.zeroValue) } else { for j in 10..<15 { i.send(value: j) } i.send(error: SignalError.closed) } withExtendedLifetime(closureLifetime) {} } do { let ep1 = s.subscribe { (r: Result<Int>) in results.append(r) } XCTAssert(results.count == 6) XCTAssert(results.at(0)?.value == 0) XCTAssert(results.at(1)?.value == 1) XCTAssert(results.at(2)?.value == 2) XCTAssert(results.at(3)?.value == 3) XCTAssert(results.at(4)?.value == 4) XCTAssert(results.at(5)?.error as? TestError == .zeroValue) withExtendedLifetime(ep1) {} } let ep2 = s.subscribe { (r: Result<Int>) in results.append(r) } XCTAssert(results.count == 12) XCTAssert(results.at(6)?.value == 10) XCTAssert(results.at(7)?.value == 11) XCTAssert(results.at(8)?.value == 12) XCTAssert(results.at(9)?.value == 13) XCTAssert(results.at(10)?.value == 14) XCTAssert(results.at(11)?.isSignalClosed == true) XCTAssert(lifetimeCheck != nil) withExtendedLifetime(ep2) {} } XCTAssert(nilCount == 2) XCTAssert(lifetimeCheck == nil) } func testJoinDisconnect() { var firstInput: SignalInput<Int>? = nil let sequence1 = Signal<Int>.generate { (input) in if let i = input { firstInput = i for x in 0..<3 { i.send(value: x) } } } let sequence2 = Signal<Int>.generate { (input) in if let i = input { for x in 3..<6 { i.send(value: x) } } } let sequence3 = Signal<Int>.generate { (input) in if let i = input { i.send(value: 5) } } var results = [Result<Int>]() do { let (i1, s) = Signal<Int>.create() let ep = s.subscribe { results.append($0) } let d = try sequence1.join(to: i1) i1.send(value: 3) XCTAssert(results.count == 3) XCTAssert(results.at(0)?.value == 0) XCTAssert(results.at(1)?.value == 1) XCTAssert(results.at(2)?.value == 2) if let i2 = d.disconnect() { let d2 = try sequence2.join(to: i2) i2.send(value: 6) XCTAssert(results.count == 7) XCTAssert(results.at(3)?.value == 3) XCTAssert(results.at(4)?.value == 4) XCTAssert(results.at(5)?.value == 5) XCTAssert(results.at(6)?.error as? SignalError == .cancelled) if let i3 = d2.disconnect() { _ = try d.join(to: i3) i3.send(value: 3) XCTAssert(results.count == 7) } else { XCTFail() } } else { XCTFail() } withExtendedLifetime(ep) {} } catch { XCTFail() } withExtendedLifetime(firstInput) {} var results2 = [Result<Int>]() let (i4, ep2) = Signal<Int>.create { $0.subscribe { results2.append($0) } } do { try sequence3.join(to: i4) { d, e, i in XCTAssert(e as? SignalError == .cancelled) i.send(value: 7) i.close() } } catch { XCTFail() } XCTAssert(results2.count == 3) XCTAssert(results2.at(0)?.value == 5) XCTAssert(results2.at(1)?.value == 7) XCTAssert(results2.at(2)?.error as? SignalError == .closed) withExtendedLifetime(ep2) {} } func testJunctionSignal() { var results = [Result<Int>]() var endpoints = [Cancellable]() do { let signal = Signal<Int>.generate { i in _ = i?.send(value: 5) } let (_, output) = signal.junctionSignal { (j, err, input) in XCTAssert(err as? SignalError == SignalError.cancelled) input.close() } endpoints += output.subscribe { r in results += r } XCTAssert(results.count == 2) XCTAssert(results.at(1)?.isSignalClosed == true) } results.removeAll() do { var input: SignalInput<Int>? var count = 0 let signal = Signal<Int>.generate { inp in if let i = inp { input = i i.send(value: 5) count += 1 if count == 3 { i.close() } } } let (junction, output) = signal.junctionSignal() endpoints += output.subscribe { r in results += r } XCTAssert(results.count == 1) XCTAssert(results.at(0)?.value == 5) junction.rejoin() XCTAssert(results.count == 2) XCTAssert(results.at(1)?.value == 5) junction.rejoin { (j, err, i) in XCTAssert(err as? SignalError == SignalError.closed) i.send(error: TestError.zeroValue) } XCTAssert(results.count == 4) XCTAssert(results.at(3)?.error as? TestError == TestError.zeroValue) withExtendedLifetime(input) {} } } func testGraphLoop() { do { let (input1, signal1) = Signal<Int>.create() let (input2, signal2) = Signal<Int>.create() let combined = signal1.combine(second: signal2) { (cr: EitherResult2<Int, Int>, next: SignalNext<Int>) in switch cr { case .result1(let r): next.send(result: r) case .result2(let r): next.send(result: r) } }.transform { r, n in n.send(result: r) }.continuous() let ex = catchBadInstruction { _ = try? combined.join(to: input2) XCTFail() } XCTAssert(ex != nil) withExtendedLifetime(input1) {} } } func testTransform() { let (input, signal) = Signal<Int>.create() var results = [Result<String>]() // Test using default behavior and context let ep1 = signal.transform { (r: Result<Int>, n: SignalNext<String>) in switch r { case .success(let v): n.send(value: "\(v)") case .failure(let e): n.send(error: e) } }.subscribe { (r: Result<String>) in results.append(r) } input.send(value: 0) input.send(value: 1) input.send(value: 2) input.close() XCTAssert(results.count == 4) XCTAssert(results.at(0)?.value == "0") XCTAssert(results.at(1)?.value == "1") XCTAssert(results.at(2)?.value == "2") XCTAssert(results.at(3)?.error as? SignalError == .closed) results.removeAll() // Test using custom behavior and context let (context, specificKey) = Exec.syncQueueWithSpecificKey() let (input2, signal2) = Signal<Int>.create() let ep2 = signal2.transform(context: context) { (r: Result<Int>, n: SignalNext<String>) in XCTAssert(DispatchQueue.getSpecific(key: specificKey) != nil) switch r { case .success(let v): n.send(value: "\(v)") case .failure(let e): n.send(error: e) } }.subscribe { (r: Result<String>) in results.append(r) } input2.send(value: 0) input2.send(value: 1) input2.send(value: 2) input2.cancel() XCTAssert(results.count == 4) XCTAssert(results.at(0)?.value == "0") XCTAssert(results.at(1)?.value == "1") XCTAssert(results.at(2)?.value == "2") XCTAssert(results.at(3)?.error as? SignalError == .cancelled) withExtendedLifetime(ep1) {} withExtendedLifetime(ep2) {} } func testTransformWithState() { let (input, signal) = Signal<Int>.create() var results = [Result<String>]() // Scope the creation of 't' so we can ensure it is removed before we re-add to the signal. do { // Test using default behavior and context let t = signal.transform(withState: 10) { (state: inout Int, r: Result<Int>, n: SignalNext<String>) in switch r { case .success(let v): XCTAssert(state == v + 10) state += 1 n.send(value: "\(v)") case .failure(let e): n.send(error: e); } } let ep1 = t.subscribe { (r: Result<String>) in results.append(r) } input.send(value: 0) input.send(value: 1) input.send(value: 2) input.close() withExtendedLifetime(ep1) {} } XCTAssert(results.count == 4) XCTAssert(results.at(0)?.value == "0") XCTAssert(results.at(1)?.value == "1") XCTAssert(results.at(2)?.value == "2") XCTAssert(results.at(3)?.error as? SignalError == .closed) results.removeAll() // Test using custom context let (context, specificKey) = Exec.syncQueueWithSpecificKey() let (input2, signal2) = Signal<Int>.create() let ep2 = signal2.transform(withState: 10, context: context) { (state: inout Int, r: Result<Int>, n: SignalNext<String>) in switch r { case .success(let v): XCTAssert(DispatchQueue.getSpecific(key: specificKey) != nil) XCTAssert(state == v + 10) state += 1 n.send(value: "\(v)") case .failure(let e): n.send(error: e); } }.subscribe { (r: Result<String>) in results.append(r) } input2.send(value: 0) input2.send(value: 1) input2.send(value: 2) input2.close() withExtendedLifetime(ep2) {} XCTAssert(results.count == 4) XCTAssert(results.at(0)?.value == "0") XCTAssert(results.at(1)?.value == "1") XCTAssert(results.at(2)?.value == "2") XCTAssert(results.at(3)?.error as? SignalError == .closed) } func testEscapingTransformer() { var results = [Result<Double>]() let (input, signal) = Signal<Int>.create() var escapedNext: SignalNext<Double>? = nil var escapedValue: Int = 0 let ep = signal.transform { (r: Result<Int>, n: SignalNext<Double>) in switch r { case .success(let v): escapedNext = n escapedValue = v case .failure(let e): n.send(error: e) } }.subscribe { results.append($0) } input.send(value: 1) XCTAssert(results.count == 0) XCTAssert(escapedNext != nil) XCTAssert(escapedValue == 1) input.send(value: 3) XCTAssert(results.count == 0) XCTAssert(escapedNext != nil) XCTAssert(escapedValue == 1) input.send(value: 5) _ = escapedNext?.send(value: Double(escapedValue * 2)) escapedNext = nil XCTAssert(results.count == 1) XCTAssert(results.at(0)?.value == 2) XCTAssert(escapedNext != nil) XCTAssert(escapedValue == 3) _ = escapedNext?.send(value: Double(escapedValue * 2)) escapedNext = nil XCTAssert(results.count == 2) XCTAssert(results.at(1)?.value == 6) XCTAssert(escapedNext != nil) XCTAssert(escapedValue == 5) _ = escapedNext?.send(value: Double(escapedValue * 2)) escapedNext = nil XCTAssert(results.count == 3) XCTAssert(results.at(2)?.value == 10) XCTAssert(escapedNext == nil) XCTAssert(escapedValue == 5) withExtendedLifetime(ep) {} } func testEscapingTransformerWithState() { var results = [Result<Double>]() let (input, signal) = Signal<Int>.create() var escapedNext: SignalNext<Double>? = nil var escapedValue: Int = 0 let ep = signal.transform(withState: 0) { (s: inout Int, r: Result<Int>, n: SignalNext<Double>) in switch r { case .success(let v): escapedNext = n escapedValue = v case .failure(let e): n.send(error: e) } }.subscribe { results.append($0) } input.send(value: 1) XCTAssert(results.count == 0) XCTAssert(escapedNext != nil) XCTAssert(escapedValue == 1) input.send(value: 3) XCTAssert(results.count == 0) XCTAssert(escapedNext != nil) XCTAssert(escapedValue == 1) input.send(value: 5) _ = escapedNext?.send(value: Double(escapedValue * 2)) escapedNext = nil XCTAssert(results.count == 1) XCTAssert(results.at(0)?.value == 2) XCTAssert(escapedNext != nil) XCTAssert(escapedValue == 3) _ = escapedNext?.send(value: Double(escapedValue * 2)) escapedNext = nil XCTAssert(results.count == 2) XCTAssert(results.at(1)?.value == 6) XCTAssert(escapedNext != nil) XCTAssert(escapedValue == 5) _ = escapedNext?.send(value: Double(escapedValue * 2)) escapedNext = nil XCTAssert(results.count == 3) XCTAssert(results.at(2)?.value == 10) XCTAssert(escapedNext == nil) XCTAssert(escapedValue == 5) withExtendedLifetime(ep) {} } func testClosedTriangleGraphLeft() { var results = [Result<Int>]() let (input, signal) = Signal<Int>.create { s in s.multicast() } let left = signal.transform { (r: Result<Int>, n: SignalNext<Int>) in switch r { case .success(let v): n.send(value: v * 10) case .failure: n.send(error: TestError.oneValue) } } let (_, ep) = Signal<Int>.createMergeSet([left, signal], closesOutput: true) { s in s.subscribe { r in results.append(r) } } input.send(value: 3) input.send(value: 5) input.close() withExtendedLifetime(ep) {} XCTAssert(results.count == 5) XCTAssert(results.at(0)?.value == 30) XCTAssert(results.at(1)?.value == 3) XCTAssert(results.at(2)?.value == 50) XCTAssert(results.at(3)?.value == 5) XCTAssert(results.at(4)?.error as? TestError == .oneValue) } func testClosedTriangleGraphRight() { var results = [Result<Int>]() let (input, signal) = Signal<Int>.create { s in s.multicast() } let (mergeSet, signal2) = Signal<Int>.createMergeSet([signal], closesOutput: true) let ep = signal2.subscribe { r in results.append(r) } let right = signal.transform { (r: Result<Int>, n: SignalNext<Int>) in switch r { case .success(let v): n.send(value: v * 10) case .failure: n.send(error: TestError.oneValue) } } do { try mergeSet.add(right, closesOutput: true) } catch { XCTFail() } input.send(value: 3) input.send(value: 5) input.close() withExtendedLifetime(ep) {} XCTAssert(results.count == 5) XCTAssert(results.at(0)?.value == 3) XCTAssert(results.at(1)?.value == 30) XCTAssert(results.at(2)?.value == 5) XCTAssert(results.at(3)?.value == 50) XCTAssert(results.at(4)?.error as? SignalError == .closed) } func testMergeSet() { do { var results = [Result<Int>]() let (mergeSet, mergeSignal) = Signal<Int>.createMergeSet() let (input, ep) = Signal<Int>.create { $0.subscribe { r in results.append(r) } } let disconnector = try mergeSignal.join(to: input) let (input1, signal1) = Signal<Int>.create { $0.cacheUntilActive() } let (input2, signal2) = Signal<Int>.create { $0.cacheUntilActive() } let (input3, signal3) = Signal<Int>.create { $0.cacheUntilActive() } let (input4, signal4) = Signal<Int>.create { $0.cacheUntilActive() } do { try mergeSet.add(signal1, closesOutput: false, removeOnDeactivate: false) try mergeSet.add(signal2, closesOutput: true, removeOnDeactivate: false) try mergeSet.add(signal3, closesOutput: false, removeOnDeactivate: true) try mergeSet.add(signal4, closesOutput: false, removeOnDeactivate: false) } catch { XCTFail() } input1.send(value: 3) input2.send(value: 4) input3.send(value: 5) input4.send(value: 9) input1.close() let reconnectable = disconnector.disconnect() try reconnectable.map { _ = try disconnector.join(to: $0) } mergeSet.remove(signal4) input1.send(value: 6) input2.send(value: 7) input3.send(value: 8) input4.send(value: 10) input2.close() input3.close() XCTAssert(results.count == 7) XCTAssert(results.at(0)?.value == 3) XCTAssert(results.at(1)?.value == 4) XCTAssert(results.at(2)?.value == 5) XCTAssert(results.at(3)?.value == 9) XCTAssert(results.at(4)?.value == 7) XCTAssert(results.at(5)?.value == 8) XCTAssert(results.at(6)?.isSignalClosed == true) withExtendedLifetime(ep) {} } catch { XCTFail() } } func testCombine2() { var results = [Result<String>]() let (input1, signal1) = Signal<Int>.create() let (input2, signal2) = Signal<Double>.create() let (context, specificKey) = Exec.syncQueueWithSpecificKey() let combined = signal1.combine(second: signal2, context: context) { (cr: EitherResult2<Int, Double>, n: SignalNext<String>) in XCTAssert(DispatchQueue.getSpecific(key: specificKey) != nil) switch cr { case .result1(.success(let v)): n.send(value: "1 v: \(v)") case .result1(.failure(let e)): n.send(value: "1 e: \(e)") case .result2(.success(let v)): n.send(value: "2 v: \(v)") case .result2(.failure(let e)): n.send(value: "2 e: \(e)") } }.subscribe { (r: Result<String>) in results.append(r) } input1.send(value: 1) input1.send(value: 3) input1.close() input2.send(value: 5.0) input2.send(value: 7.0) input2.close() XCTAssert(results.count == 6) XCTAssert(results.at(0)?.value == "1 v: 1") XCTAssert(results.at(1)?.value == "1 v: 3") XCTAssert(results.at(2)?.value == "1 e: closed") XCTAssert(results.at(3)?.value == "2 v: 5.0") XCTAssert(results.at(4)?.value == "2 v: 7.0") XCTAssert(results.at(5)?.value == "2 e: closed") withExtendedLifetime(combined) {} } func testCombine2WithState() { var results = [Result<String>]() let (input1, signal1) = Signal<Int>.create() let (input2, signal2) = Signal<Double>.create() let (context, specificKey) = Exec.syncQueueWithSpecificKey() let combined = signal1.combine(withState: "", second: signal2, context: context) { (state: inout String, cr: EitherResult2<Int, Double>, n: SignalNext<String>) in XCTAssert(DispatchQueue.getSpecific(key: specificKey) != nil) state += "\(results.count)" switch cr { case .result1(.success(let v)): n.send(value: "1 v: \(v) \(state)") case .result1(.failure(let e)): n.send(value: "1 e: \(e) \(state)") case .result2(.success(let v)): n.send(value: "2 v: \(v) \(state)") case .result2(.failure(let e)): n.send(value: "2 e: \(e) \(state)") } }.subscribe { (r: Result<String>) in results.append(r) } input1.send(value: 1) input1.send(value: 3) input1.close() input2.send(value: 5.0) input2.send(value: 7.0) input2.close() XCTAssert(results.count == 6) XCTAssert(results.at(0)?.value == "1 v: 1 0") XCTAssert(results.at(1)?.value == "1 v: 3 01") XCTAssert(results.at(2)?.value == "1 e: closed 012") XCTAssert(results.at(3)?.value == "2 v: 5.0 0123") XCTAssert(results.at(4)?.value == "2 v: 7.0 01234") XCTAssert(results.at(5)?.value == "2 e: closed 012345") withExtendedLifetime(combined) {} } func testCombine3() { var results = [Result<String>]() let (input1, signal1) = Signal<Int>.create() let (input2, signal2) = Signal<Double>.create() let (input3, signal3) = Signal<Int8>.create() let (context, specificKey) = Exec.syncQueueWithSpecificKey() let combined = signal1.combine(second: signal2, third: signal3, context: context) { (cr: EitherResult3<Int, Double, Int8>, n: SignalNext<String>) in XCTAssert(DispatchQueue.getSpecific(key: specificKey) != nil) switch cr { case .result1(.success(let v)): n.send(value: "1 v: \(v)") case .result1(.failure(let e)): n.send(value: "1 e: \(e)") case .result2(.success(let v)): n.send(value: "2 v: \(v)") case .result2(.failure(let e)): n.send(value: "2 e: \(e)") case .result3(.success(let v)): n.send(value: "3 v: \(v)") case .result3(.failure(let e)): n.send(value: "3 e: \(e)") } }.subscribe { (r: Result<String>) in results.append(r) } input3.send(value: 13) input1.send(value: 1) input2.send(value: 5.0) input1.send(value: 3) input1.close() input3.send(value: 17) input3.close() input2.send(value: 7.0) input2.close() XCTAssert(results.count == 9) XCTAssert(results.at(0)?.value == "3 v: 13") XCTAssert(results.at(1)?.value == "1 v: 1") XCTAssert(results.at(2)?.value == "2 v: 5.0") XCTAssert(results.at(3)?.value == "1 v: 3") XCTAssert(results.at(4)?.value == "1 e: closed") XCTAssert(results.at(5)?.value == "3 v: 17") XCTAssert(results.at(6)?.value == "3 e: closed") XCTAssert(results.at(7)?.value == "2 v: 7.0") XCTAssert(results.at(8)?.value == "2 e: closed") withExtendedLifetime(combined) {} } func testCombine3WithState() { var results = [Result<String>]() let (input1, signal1) = Signal<Int>.create() let (input2, signal2) = Signal<Double>.create() let (input3, signal3) = Signal<Int8>.create() let (context, specificKey) = Exec.syncQueueWithSpecificKey() let combined = signal1.combine(withState: "", second: signal2, third: signal3, context: context) { (state: inout String, cr: EitherResult3<Int, Double, Int8>, n: SignalNext<String>) in XCTAssert(DispatchQueue.getSpecific(key: specificKey) != nil) state += "\(results.count)" switch cr { case .result1(.success(let v)): n.send(value: "1 v: \(v) \(state)") case .result1(.failure(let e)): n.send(value: "1 e: \(e) \(state)") case .result2(.success(let v)): n.send(value: "2 v: \(v) \(state)") case .result2(.failure(let e)): n.send(value: "2 e: \(e) \(state)") case .result3(.success(let v)): n.send(value: "3 v: \(v) \(state)") case .result3(.failure(let e)): n.send(value: "3 e: \(e) \(state)") } }.subscribe { (r: Result<String>) in results.append(r) } input3.send(value: 13) input1.send(value: 1) input2.send(value: 5.0) input1.send(value: 3) input1.close() input3.send(value: 17) input3.close() input2.send(value: 7.0) input2.close() XCTAssert(results.count == 9) XCTAssert(results.at(0)?.value == "3 v: 13 0") XCTAssert(results.at(1)?.value == "1 v: 1 01") XCTAssert(results.at(2)?.value == "2 v: 5.0 012") XCTAssert(results.at(3)?.value == "1 v: 3 0123") XCTAssert(results.at(4)?.value == "1 e: closed 01234") XCTAssert(results.at(5)?.value == "3 v: 17 012345") XCTAssert(results.at(6)?.value == "3 e: closed 0123456") XCTAssert(results.at(7)?.value == "2 v: 7.0 01234567") XCTAssert(results.at(8)?.value == "2 e: closed 012345678") withExtendedLifetime(combined) {} } func testCombine4() { var results = [Result<String>]() let (input1, signal1) = Signal<Int>.create() let (input2, signal2) = Signal<Double>.create() let (input3, signal3) = Signal<Int8>.create() let (input4, signal4) = Signal<Int16>.create() let (context, specificKey) = Exec.syncQueueWithSpecificKey() let combined = signal1.combine(second: signal2, third: signal3, fourth: signal4, context: context) { (cr: EitherResult4<Int, Double, Int8, Int16>, n: SignalNext<String>) in XCTAssert(DispatchQueue.getSpecific(key: specificKey) != nil) switch cr { case .result1(.success(let v)): n.send(value: "1 v: \(v)") case .result1(.failure(let e)): n.send(value: "1 e: \(e)") case .result2(.success(let v)): n.send(value: "2 v: \(v)") case .result2(.failure(let e)): n.send(value: "2 e: \(e)") case .result3(.success(let v)): n.send(value: "3 v: \(v)") case .result3(.failure(let e)): n.send(value: "3 e: \(e)") case .result4(.success(let v)): n.send(value: "4 v: \(v)") case .result4(.failure(let e)): n.send(value: "4 e: \(e)") } }.subscribe { (r: Result<String>) in results.append(r) } input4.send(value: 11) input4.send(value: 19) input3.send(value: 13) input1.send(value: 1) input2.send(value: 5.0) input1.send(value: 3) input1.close() input3.send(value: 17) input3.close() input2.send(value: 7.0) input2.close() input4.close() XCTAssert(results.count == 12) XCTAssert(results.at(0)?.value == "4 v: 11") XCTAssert(results.at(1)?.value == "4 v: 19") XCTAssert(results.at(2)?.value == "3 v: 13") XCTAssert(results.at(3)?.value == "1 v: 1") XCTAssert(results.at(4)?.value == "2 v: 5.0") XCTAssert(results.at(5)?.value == "1 v: 3") XCTAssert(results.at(6)?.value == "1 e: closed") XCTAssert(results.at(7)?.value == "3 v: 17") XCTAssert(results.at(8)?.value == "3 e: closed") XCTAssert(results.at(9)?.value == "2 v: 7.0") XCTAssert(results.at(10)?.value == "2 e: closed") XCTAssert(results.at(11)?.value == "4 e: closed") withExtendedLifetime(combined) {} } func testCombine4WithState() { var results = [Result<String>]() let (input1, signal1) = Signal<Int>.create() let (input2, signal2) = Signal<Double>.create() let (input3, signal3) = Signal<Int8>.create() let (input4, signal4) = Signal<Int16>.create() let (context, specificKey) = Exec.syncQueueWithSpecificKey() let combined = signal1.combine(withState: "", second: signal2, third: signal3, fourth: signal4, context: context) { (state: inout String, cr: EitherResult4<Int, Double, Int8, Int16>, n: SignalNext<String>) in XCTAssert(DispatchQueue.getSpecific(key: specificKey) != nil) state += "\(results.count)" switch cr { case .result1(.success(let v)): n.send(value: "1 v: \(v) \(state)") case .result1(.failure(let e)): n.send(value: "1 e: \(e) \(state)") case .result2(.success(let v)): n.send(value: "2 v: \(v) \(state)") case .result2(.failure(let e)): n.send(value: "2 e: \(e) \(state)") case .result3(.success(let v)): n.send(value: "3 v: \(v) \(state)") case .result3(.failure(let e)): n.send(value: "3 e: \(e) \(state)") case .result4(.success(let v)): n.send(value: "4 v: \(v) \(state)") case .result4(.failure(let e)): n.send(value: "4 e: \(e) \(state)") } }.subscribe { (r: Result<String>) in results.append(r) } input4.send(value: 11) input4.send(value: 19) input3.send(value: 13) input1.send(value: 1) input2.send(value: 5.0) input1.send(value: 3) input1.close() input3.send(value: 17) input3.close() input2.send(value: 7.0) input2.close() input4.close() XCTAssert(results.count == 12) XCTAssert(results.at(0)?.value == "4 v: 11 0") XCTAssert(results.at(1)?.value == "4 v: 19 01") XCTAssert(results.at(2)?.value == "3 v: 13 012") XCTAssert(results.at(3)?.value == "1 v: 1 0123") XCTAssert(results.at(4)?.value == "2 v: 5.0 01234") XCTAssert(results.at(5)?.value == "1 v: 3 012345") XCTAssert(results.at(6)?.value == "1 e: closed 0123456") XCTAssert(results.at(7)?.value == "3 v: 17 01234567") XCTAssert(results.at(8)?.value == "3 e: closed 012345678") XCTAssert(results.at(9)?.value == "2 v: 7.0 0123456789") XCTAssert(results.at(10)?.value == "2 e: closed 012345678910") XCTAssert(results.at(11)?.value == "4 e: closed 01234567891011") withExtendedLifetime(combined) {} } func testCombine5() { var results = [Result<String>]() let (input1, signal1) = Signal<Int>.create() let (input2, signal2) = Signal<Double>.create() let (input3, signal3) = Signal<Int8>.create() let (input4, signal4) = Signal<Int16>.create() let (input5, signal5) = Signal<Int32>.create() let (context, specificKey) = Exec.syncQueueWithSpecificKey() let combined = signal1.combine(second: signal2, third: signal3, fourth: signal4, fifth: signal5, context: context) { (cr: EitherResult5<Int, Double, Int8, Int16, Int32>, n: SignalNext<String>) in XCTAssert(DispatchQueue.getSpecific(key: specificKey) != nil) switch cr { case .result1(.success(let v)): n.send(value: "1 v: \(v)") case .result1(.failure(let e)): n.send(value: "1 e: \(e)") case .result2(.success(let v)): n.send(value: "2 v: \(v)") case .result2(.failure(let e)): n.send(value: "2 e: \(e)") case .result3(.success(let v)): n.send(value: "3 v: \(v)") case .result3(.failure(let e)): n.send(value: "3 e: \(e)") case .result4(.success(let v)): n.send(value: "4 v: \(v)") case .result4(.failure(let e)): n.send(value: "4 e: \(e)") case .result5(.success(let v)): n.send(value: "5 v: \(v)") case .result5(.failure(let e)): n.send(value: "5 e: \(e)") } }.subscribe { (r: Result<String>) in results.append(r) } input4.send(value: 11) input4.send(value: 19) input3.send(value: 13) input1.send(value: 1) input2.send(value: 5.0) input1.send(value: 3) input1.close() input3.send(value: 17) input3.close() input2.send(value: 7.0) input2.close() input4.close() input5.send(value: 23) input5.send(error: TestError.oneValue) XCTAssert(results.count == 14) XCTAssert(results.at(0)?.value == "4 v: 11") XCTAssert(results.at(1)?.value == "4 v: 19") XCTAssert(results.at(2)?.value == "3 v: 13") XCTAssert(results.at(3)?.value == "1 v: 1") XCTAssert(results.at(4)?.value == "2 v: 5.0") XCTAssert(results.at(5)?.value == "1 v: 3") XCTAssert(results.at(6)?.value == "1 e: closed") XCTAssert(results.at(7)?.value == "3 v: 17") XCTAssert(results.at(8)?.value == "3 e: closed") XCTAssert(results.at(9)?.value == "2 v: 7.0") XCTAssert(results.at(10)?.value == "2 e: closed") XCTAssert(results.at(11)?.value == "4 e: closed") XCTAssert(results.at(12)?.value == "5 v: 23") XCTAssert(results.at(13)?.value == "5 e: oneValue") withExtendedLifetime(combined) {} } func testCombine5WithState() { var results = [Result<String>]() let (input1, signal1) = Signal<Int>.create() let (input2, signal2) = Signal<Double>.create() let (input3, signal3) = Signal<Int8>.create() let (input4, signal4) = Signal<Int16>.create() let (input5, signal5) = Signal<Int32>.create() let (context, specificKey) = Exec.syncQueueWithSpecificKey() let combined = signal1.combine(withState: "", second: signal2, third: signal3, fourth: signal4, fifth: signal5, context: context) { (state: inout String, cr: EitherResult5<Int, Double, Int8, Int16, Int32>, n: SignalNext<String>) in XCTAssert(DispatchQueue.getSpecific(key: specificKey) != nil) state += "\(results.count)" switch cr { case .result1(.success(let v)): n.send(value: "1 v: \(v) \(state)") case .result1(.failure(let e)): n.send(value: "1 e: \(e) \(state)") case .result2(.success(let v)): n.send(value: "2 v: \(v) \(state)") case .result2(.failure(let e)): n.send(value: "2 e: \(e) \(state)") case .result3(.success(let v)): n.send(value: "3 v: \(v) \(state)") case .result3(.failure(let e)): n.send(value: "3 e: \(e) \(state)") case .result4(.success(let v)): n.send(value: "4 v: \(v) \(state)") case .result4(.failure(let e)): n.send(value: "4 e: \(e) \(state)") case .result5(.success(let v)): n.send(value: "5 v: \(v) \(state)") case .result5(.failure(let e)): n.send(value: "5 e: \(e) \(state)") } }.subscribe { (r: Result<String>) in results.append(r) } input4.send(value: 11) input4.send(value: 19) input3.send(value: 13) input1.send(value: 1) input2.send(value: 5.0) input1.send(value: 3) input1.close() input3.send(value: 17) input3.close() input2.send(value: 7.0) input2.close() input4.close() input5.send(value: 23) input5.send(error: TestError.oneValue) XCTAssert(results.count == 14) XCTAssert(results.at(0)?.value == "4 v: 11 0") XCTAssert(results.at(1)?.value == "4 v: 19 01") XCTAssert(results.at(2)?.value == "3 v: 13 012") XCTAssert(results.at(3)?.value == "1 v: 1 0123") XCTAssert(results.at(4)?.value == "2 v: 5.0 01234") XCTAssert(results.at(5)?.value == "1 v: 3 012345") XCTAssert(results.at(6)?.value == "1 e: closed 0123456") XCTAssert(results.at(7)?.value == "3 v: 17 01234567") XCTAssert(results.at(8)?.value == "3 e: closed 012345678") XCTAssert(results.at(9)?.value == "2 v: 7.0 0123456789") XCTAssert(results.at(10)?.value == "2 e: closed 012345678910") XCTAssert(results.at(11)?.value == "4 e: closed 01234567891011") XCTAssert(results.at(12)?.value == "5 v: 23 0123456789101112") XCTAssert(results.at(13)?.value == "5 e: oneValue 012345678910111213") withExtendedLifetime(combined) {} } @inline(never) private static func noinlineMapFunction(_ value: Int) -> Result<Int> { return Result<Int>.success(value) } #if !SWIFT_PACKAGE func testSinglePerformance() { var sequenceLength = 10_000_000 var expected = 3.25 // +/- 0.4 var upperThreshold = 4.0 // Override the test parameters when running in Debug. #if DEBUG sequenceLength = 10_000 expected = 0.015 // +/- 0.15 upperThreshold = 0.5 #endif let t = mach_absolute_time() var count = 0 // A basic test designed to exercise (sequence -> SignalInput -> SignalNode -> SignalQueue) performance. _ = Signal<Int>.generate(context: .direct) { input in guard let i = input else { return } for v in 0..<sequenceLength { if let _ = i.send(value: v) { break } } i.close() }.subscribe { r in switch r { case .success: count += 1 case .failure: break } } XCTAssert(count == sequenceLength) let elapsed = 1e-9 * Double(mach_absolute_time() - t) XCTAssert(elapsed < upperThreshold) print("Performance is \(elapsed) seconds versus expected \(expected). Rate is \(Double(sequenceLength) / elapsed) per second.") // Approximate analogue to Signal architecture (sequence -> lazy map to Result -> iterate -> unwrap) let t2 = mach_absolute_time() var count2 = 0 (0..<sequenceLength).lazy.map(SignalTests.noinlineMapFunction).forEach { r in switch r { case .success: count2 += 1 case .failure: break } } XCTAssert(count2 == sequenceLength) let elapsed2 = 1e-9 * Double(mach_absolute_time() - t2) print("Baseline is is \(elapsed2) seconds (\(elapsed / elapsed2) times faster).") } func testSyncMapPerformance() { var sequenceLength = 10_000_000 var expected = 7.3 // +/- 0.4 var upperThreshold = 8.0 // Override the test parameters when running in Debug. #if DEBUG sequenceLength = 10_000 expected = 0.03 upperThreshold = 0.5 #endif let t = mach_absolute_time() var count = 0 // A basic test designed to exercise (sequence -> SignalInput -> SignalNode -> SignalQueue) performance. _ = Signal<Int>.generate(context: .direct) { input in guard let i = input else { return } for v in 0..<sequenceLength { if let _ = i.send(value: v) { break } } i.close() }.map { v in v }.subscribe { r in switch r { case .success: count += 1 case .failure: break } } XCTAssert(count == sequenceLength) let elapsed = 1e-9 * Double(mach_absolute_time() - t) XCTAssert(elapsed < upperThreshold) print("Performance is \(elapsed) seconds versus expected \(expected). Rate is \(Double(sequenceLength) / elapsed) per second.") // Approximate analogue to Signal architecture (sequence -> lazy map to Result -> iterate -> unwrap) let t2 = mach_absolute_time() var count2 = 0 (0..<sequenceLength).lazy.map(SignalTests.noinlineMapFunction).forEach { r in switch r { case .success: count2 += 1 case .failure: break } } XCTAssert(count2 == sequenceLength) let elapsed2 = 1e-9 * Double(mach_absolute_time() - t2) print("Baseline is is \(elapsed2) seconds (\(elapsed / elapsed2) times faster).") } func testAsyncMapPerformance() { var sequenceLength = 1_000_000 var expected = 9.9 // +/- 0.4 // Override the test parameters when running in Debug. #if DEBUG sequenceLength = 10_000 expected = 0.2 #endif let t1 = mach_absolute_time() var count1 = 0 let ex = expectation(description: "Waiting for signal") // A basic test designed to exercise (sequence -> SignalInput -> SignalNode -> SignalQueue) performance. let ep = Signal<Int>.generate { input in guard let i = input else { return } for v in 0..<sequenceLength { _ = i.send(value: v) } }.map(context: .default) { v in v }.subscribeValues(context: .main) { v in count1 += 1 if count1 == sequenceLength { ex.fulfill() } } waitForExpectations(timeout: 1e2, handler: nil) withExtendedLifetime(ep) {} precondition(count1 == sequenceLength) let elapsed1 = 1e-9 * Double(mach_absolute_time() - t1) print("Performance is \(elapsed1) seconds versus expected \(expected). Rate is \(Double(sequenceLength) / elapsed1) per second.") } @inline(never) private static func noinlineMapToDepthFunction(_ value: Int, _ depth: Int) -> Result<Int> { var result = SignalTests.noinlineMapFunction(value) for _ in 0..<depth { switch result { case .success(let v): result = SignalTests.noinlineMapFunction(v) case .failure(let e): result = .failure(e) } } return result } func testDeepSyncPerformance() { var sequenceLength = 1_000_000 var expected = 3.4 // +/- 0.4 var upperThreshold = 6.5 // Override the test parameters when running with Debug Assertions. // This is a hack but it avoids the need for conditional compilation options. #if DEBUG sequenceLength = 10_000 expected = 0.02 // +/- 0.15 upperThreshold = 3.0 #endif let depth = 10 let t = mach_absolute_time() var count = 0 // Similar to the "Single" performance test but further inserts 100 map nodes between the initial node and the endpoint var signal = Signal<Int>.generate { (input) in if let i = input { for x in 0..<sequenceLength { i.send(value: x) } } } for _ in 0..<depth { signal = signal.transform { r, n in n.send(result: r) } } _ = signal.subscribe { r in switch r { case .success: count += 1 case .failure: break } } XCTAssert(count == sequenceLength) let elapsed = 1e-9 * Double(mach_absolute_time() - t) XCTAssert(elapsed < upperThreshold) print("Performance is \(elapsed) seconds versus expected \(expected). Rate is \(Double(sequenceLength * depth) / elapsed) per second.") let t2 = mach_absolute_time() var count2 = 0 // Again, as close an equivalent as possible (0..<sequenceLength).lazy.map { SignalTests.noinlineMapToDepthFunction($0, depth) }.forEach { r in switch r { case .success: count2 += 1 case .failure: break } } XCTAssert(count2 == sequenceLength) let elapsed2 = 1e-9 * Double(mach_absolute_time() - t2) print("Baseline is is \(elapsed2) seconds (\(elapsed / elapsed2) times faster).") } #endif func testAsynchronousJoinAndDetach() { #if true let numRuns = 10 #else // I've occasionally needed a very high number here to fully exercise some obscure threading bugs. It's not exactly time efficient for common usage. let numRuns = 10000 #endif for run in 1...numRuns { asynchronousJoinAndDetachRun(run: run) } } func asynchronousJoinAndDetachRun(run: Int) { // This is a multi-threaded graph manipulation test. // Four threads continually try to disconnect the active graph and attach their own subgraph. // Important expectations: // 1. some should succeed to completion // 2. some should be interrupted // 3. streams of values should never arrive out-of-order // NOTE: Parameter tweaking may be required here. // This method tests thread contention over over a SignalJunction. Doing so may require tweaking of the following parameters to ensure the appropriate amount of contention occurs. A good target is an average of 25% completion and a range between 10% and 50% completion – this should ensure the test remains reliable under a wide range of host conditions. let sequenceLength = 10 let iterations = 50 let threadCount = 4 let depth = 10 var completionCount = 0 var failureCount = 0 var allEndpoints = [String: SignalEndpoint<(thread: Int, iteration: Int, value: Int)>]() let junction = Signal<Int>.generate { (input) in if let i = input { for x in 0..<sequenceLength { i.send(value: x) } i.close() } }.junction() let triple = { (j: Int, i: Int, v: Int) -> String in return "Thread \(j), iteration \(i), value \(v)" } let double = { (j: Int, i: Int) -> String in return "Thread \(j), iteration \(i)" } let ex = expectation(description: "Waiting for thread completions") for j in 0..<threadCount { Exec.default.invoke { for i in 0..<iterations { let (input, s) = Signal<Int>.create() var signal = s.transform(withState: 0) { (count: inout Int, r: Result<Int>, n: SignalNext<(thread: Int, iteration: Int, value: Int)>) in switch r { case .success(let v): n.send(value: (thread: j, iteration: i, value: v)) case .failure(let e): n.send(error: e) } } for d in 0..<depth { signal = signal.transform(withState: 0, context: .default) { (state: inout Int, r: Result<(thread: Int, iteration: Int, value: Int)>, n: SignalNext<(thread: Int, iteration: Int, value: Int)>) in switch r { case .success(let v): if v.value != state { XCTFail("Failed at depth \(d)") } state += 1 n.send(value: v) case .failure(let e): n.send(error: e) } } } var results = [String]() let ep = signal.subscribe(context: .direct) { r in switch r { case .success(let v): results.append(triple(v.thread, v.iteration, v.value)) case .failure(SignalError.closed): XCTAssert(results.count == sequenceLength) let expected = Array(0..<results.count).map { triple(j, i, $0) } let match = results == expected XCTAssert(match) if !match { print("Mismatched on completion:\n\(results)") } DispatchQueue.main.async { completionCount += 1 XCTAssert(allEndpoints[double(j, i)] != nil) allEndpoints.removeValue(forKey: double(j, i)) if completionCount + failureCount == iterations * threadCount { ex.fulfill() } } case .failure(let e): XCTAssert(e as? SignalError != .closed) let expected = Array(0..<results.count).map { triple(j, i, $0) } let match = results == expected XCTAssert(match) if !match { print("Mismatched on interruption:\n\(results)") } DispatchQueue.main.async { failureCount += 1 XCTAssert(allEndpoints[double(j, i)] != nil) allEndpoints.removeValue(forKey: double(j, i)) if completionCount + failureCount == iterations * threadCount { ex.fulfill() } } } } DispatchQueue.main.async { allEndpoints[double(j, i)] = ep } _ = junction.disconnect() _ = try? junction.join(to: input) } } } // This timeout is relatively low. It's helpful to get a failure message within a reasonable time. waitForExpectations(timeout: 1e1, handler: nil) XCTAssert(completionCount + failureCount == iterations * threadCount) XCTAssert(completionCount > threadCount) XCTAssert(completionCount < (iterations - 1) * threadCount) print("Finished run \(run) with completion count \(completionCount) of \(iterations * threadCount) (roughly 25% completion desired)") } func testIsSignalClosed() { let v1 = Result<Int>.success(5) let e1 = Result<Int>.failure(SignalError.cancelled) let e2 = Result<Int>.failure(SignalError.closed) XCTAssert(v1.isSignalClosed == false) XCTAssert(e1.isSignalClosed == false) XCTAssert(e2.isSignalClosed == true) } func testReactivateDeadlockBug() { // This bug exercises the `if itemContextNeedsRefresh` branch in `send(result:predecessor:activationCount:activated:)` and deadlocks if the previous handler is released incorrectly. var results = [Result<String?>]() let sig1 = Signal<String?>.create { s in s.continuous(initial: "hello") } let sig2 = sig1.composed.startWith(["boop"]) for _ in 1...3 { let ep = sig2.subscribe(context: .main) { r in results.append(r) } ep.cancel() } XCTAssert(results.count == 6) XCTAssert(results.at(0)?.value.flatMap { $0 } == "boop") XCTAssert(results.at(1)?.value.flatMap { $0 } == "hello") XCTAssert(results.at(2)?.value.flatMap { $0 } == "boop") XCTAssert(results.at(3)?.value.flatMap { $0 } == "hello") XCTAssert(results.at(4)?.value.flatMap { $0 } == "boop") XCTAssert(results.at(5)?.value.flatMap { $0 } == "hello") withExtendedLifetime(sig1.input) {} } }
isc
fd7ccf9ca8b1f027266452664378ceeb
30.58917
356
0.644262
3.086395
false
false
false
false
mcxiaoke/learning-ios
cocoa_programming_for_osx/30_ViewControllers/ViewControl/ViewControl/MainWindowController.swift
1
1006
// // MainWindowController.swift // ViewControl // // Created by mcxiaoke on 16/5/24. // Copyright © 2016年 mcxiaoke. All rights reserved. // import Cocoa class MainWindowController: NSWindowController { override var windowNibName: String? { return "MainWindowController" } override func windowDidLoad() { super.windowDidLoad() print("windowDidLoad") setUpViewController() } func setUpViewController(){ let flowViewController = ImageViewController() flowViewController.title = "Rainy" flowViewController.image = NSImage(named: "rainy") let columnViewController = ImageViewController() columnViewController.title = "Cloudy" columnViewController.image = NSImage(named: "cloudy") let tabViewController = NSTabViewController() tabViewController.addChildViewController(flowViewController) tabViewController.addChildViewController(columnViewController) self.contentViewController = tabViewController } }
apache-2.0
cb97a62cee8c3db7b100a2f1e65bc8fb
25.394737
66
0.730808
5.363636
false
false
false
false
bearMountain/MovingLetters
Moving Letters/SourceCode/LetterView.swift
1
4296
import UIKit class LetterView: UIView { //MARK: - Init override init(frame: CGRect) { super.init(frame: frame) } //MARK: - Public func drawLetter(newLetter: Letter) { let maxI = max(newLetter.strokes.count, strokeLayers.count) var newStrokeLayers = [CAShapeLayer]() for i in 0..<maxI { // More Strokes in new letter if (i >= strokeLayers.count) { // add layer let path = pathForStroke(newLetter.strokes[i]) let lineLayer = lineLayerWithPath(path) self.layer.addSublayer(lineLayer) // animate stroke in let animation = CABasicAnimation(keyPath: "strokeEnd") animation.duration = animationDuration animation.fromValue = 0 animation.toValue = 1 animation.removedOnCompletion = false animation.fillMode = kCAFillModeForwards lineLayer.addAnimation(animation, forKey: "strokeEnd") newStrokeLayers.append(lineLayer) } // More Strokes in old letter else if (i >= newLetter.strokes.count) { // animate stroke out let layerToRemove = strokeLayers[i] CATransaction.begin() CATransaction.setCompletionBlock{ layerToRemove.removeFromSuperlayer() } let animation = CABasicAnimation(keyPath: "strokeEnd") animation.duration = animationDuration animation.fromValue = 1 animation.toValue = 0 animation.removedOnCompletion = false animation.fillMode = kCAFillModeForwards layerToRemove.addAnimation(animation, forKey: "strokeEnd") CATransaction.commit() } // Changing old stroke to new stroke else { let path = pathForStroke(newLetter.strokes[i]) let strokeLayer = strokeLayers[i] let animation = CABasicAnimation(keyPath: "path") animation.duration = animationDuration animation.fromValue = strokeLayer.path strokeLayer.path = path animation.toValue = path strokeLayers[i].addAnimation(animation, forKey: "path") newStrokeLayers.append(strokeLayers[i]) } } strokeLayers = newStrokeLayers } //MARK: - Private // Vars var strokeLayers = [CAShapeLayer]() let animationDuration = 2.0 // Methods func lineLayerWithPath(path: CGPath) -> CAShapeLayer { let shapeLayer = CAShapeLayer() shapeLayer.path = path shapeLayer.strokeColor = UIColor.whiteColor().CGColor shapeLayer.fillColor = UIColor.clearColor().CGColor shapeLayer.lineWidth = 3 shapeLayer.lineCap = "round" return shapeLayer; } func pathForStroke(stroke: Any) -> CGPath { let path = UIBezierPath() if let lineSegment = stroke as? LineSegment { path.moveToPoint(lineSegment.start) path.addLineToPoint(lineSegment.end) } if let bezierPath = stroke as? BezierPath { path.moveToPoint(bezierPath.start) var previousPoint = bezierPath.start for bezierPoint in bezierPath.points { let controlPoint1 = bezierPoint.controlPoint1 == nil ? previousPoint : bezierPoint.controlPoint1! let controlPoint2 = bezierPoint.controlPoint2 == nil ? bezierPoint.point : bezierPoint.controlPoint2! path.addCurveToPoint(bezierPoint.point, controlPoint1: controlPoint1, controlPoint2: controlPoint2) previousPoint = bezierPoint.point } } return path.CGPath } //MARK: - Boilerplate required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
e5ee0c71ae801cf960bf556ff54b1b6f
32.302326
117
0.550745
5.893004
false
false
false
false
cocoaswifty/V2EX
V2EX/UITableView.swift
1
1648
// // UITableViewExtension.swift // EngineerMaster_iOS_APP // // Created by tracetw on 2016/3/24. // Copyright © 2016年 mycena. All rights reserved. // import UIKit public extension UITableView { func registerCellClass(_ cellClass: AnyClass) { let identifier = String.className(cellClass) self.register(cellClass, forCellReuseIdentifier: identifier) } func registerCellNib(_ cellClass: AnyClass) { let identifier = String.className(cellClass) let nib = UINib(nibName: identifier, bundle: nil) self.register(nib, forCellReuseIdentifier: identifier) } func registerHeaderFooterViewClass(_ viewClass: AnyClass) { let identifier = String.className(viewClass) self.register(viewClass, forHeaderFooterViewReuseIdentifier: identifier) } func registerHeaderFooterViewNib(_ viewClass: AnyClass) { let identifier = String.className(viewClass) let nib = UINib(nibName: identifier, bundle: nil) self.register(nib, forHeaderFooterViewReuseIdentifier: identifier) } func setTableViewBackgroundGradient(_ topColor:UIColor, _ bottomColor:UIColor) { let gradientLayer = CAGradientLayer() gradientLayer.colors = [topColor.cgColor, bottomColor.cgColor] gradientLayer.startPoint = CGPoint(x: 0, y: 0) gradientLayer.endPoint = CGPoint(x: 1, y: 1) gradientLayer.frame = self.bounds let backgroundView = UIView(frame: self.bounds) backgroundView.layer.insertSublayer(gradientLayer, at: 0) self.backgroundView = backgroundView } }
apache-2.0
d8ce59a1a4a26e0e385187cb7b37024e
33.270833
84
0.683891
4.895833
false
false
false
false
rcasanovan/Social-Feed
Social Feed/Social Feed/UI/Feed List/View/Cell/SFTwitterFeedImageTableViewCell.swift
1
2907
// // SFTwitterFeedImageTableViewCell.swift // Social Feed // // Created by Ricardo Casanova on 05/08/2017. // Copyright © 2017 Social Feed. All rights reserved. // import UIKit //__ Haneke import Haneke class SFTwitterFeedImageTableViewCell: UITableViewCell { //__ IBOutlets @IBOutlet weak private var itemFeedUserImageView: UIImageView? @IBOutlet weak private var itemFeedUsernameLabel: UILabel? @IBOutlet weak private var itemFeedTextLabel: UILabel? @IBOutlet weak private var itemFeedImageView: UIImageView? @IBOutlet weak private var itemFeedTextHeightConstraint: NSLayoutConstraint? @IBOutlet weak private var itemFeedCreatedAtLabel : UILabel? override func awakeFromNib() { super.awakeFromNib() setupViewCell() } override func prepareForReuse() { super.prepareForReuse() self.itemFeedUserImageView?.image = nil self.itemFeedTextLabel?.text = "" self.itemFeedImageView?.image = nil self.itemFeedTextHeightConstraint?.constant = 18.0 self.itemFeedCreatedAtLabel?.text = "" } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } private func setupViewCell() { self.selectionStyle = UITableViewCellSelectionStyle.none } func heightForItem(text: String, font: UIFont) -> CGFloat { return (font.sizeOfString(string: text, constrainedToWidth: Double(self.frame.size.width - 64.0)).height) } //__ DVATableViewModelProtocol method func bind(withModel viewModel: DVATableViewModelProtocol!) { //__ Get the view model for cell let model : SFFeedViewObject = (viewModel as? SFFeedViewObject)! //__ Configure outlets self.itemFeedUserImageView?.contentMode = UIViewContentMode.scaleAspectFill self.itemFeedUserImageView?.clipsToBounds = true self.itemFeedUserImageView?.layer.cornerRadius = (self.itemFeedUserImageView?.frame.size.height)! / 2.0 itemFeedUserImageView?.hnk_setImageFromURL((model.itemUserImageURL?.absoluteURL)!) self.itemFeedUsernameLabel?.text = model.itemUsername self.itemFeedCreatedAtLabel?.text = model.itemCreatedAt self.itemFeedTextLabel?.font = model.itemTextFont self.itemFeedTextLabel?.text = model.itemText self.itemFeedTextLabel?.numberOfLines = 0 self.itemFeedTextHeightConstraint?.constant = 10.0 + heightForItem(text: model.itemText, font: model.itemTextFont) if (model.itemImageURL != nil) { self.itemFeedImageView?.contentMode = UIViewContentMode.scaleAspectFill self.itemFeedImageView?.clipsToBounds = true itemFeedImageView?.hnk_setImageFromURL(model.itemImageURL!) itemFeedImageView?.isHidden = false } } }
apache-2.0
dc3dc2142d330d02f69fedc14d9c52b0
37.746667
122
0.696146
4.859532
false
false
false
false
safx/yavfl
yavfl.swift
1
11458
// // yavfl.swift // // yavfl : Yet Another Visual Format Language for Auto layout // // Created by Safx Developer on 2014/12/08. // Copyright (c) 2014 Safx Developers. All rights reserved. // import Foundation #if os(iOS) || os(tvOS) import UIKit public typealias YAVView = UIView public typealias LayoutFormatOptions = NSLayoutFormatOptions #else import AppKit public typealias YAVView = NSView public typealias LayoutFormatOptions = NSLayoutConstraint.FormatOptions #endif public func visualFormat(_ v1: YAVView, closure: (ViewExpression) -> ()) { v1.translatesAutoresizingMaskIntoConstraints = false closure(.view(LayoutViewName(view: v1, index: 1))) v1.updateConstraints() } public func visualFormat(_ v1: YAVView, _ v2: YAVView, closure: (ViewExpression, ViewExpression) -> ()) { v1.translatesAutoresizingMaskIntoConstraints = false v2.translatesAutoresizingMaskIntoConstraints = false closure(.view(LayoutViewName(view: v1, index: 1)), .view(LayoutViewName(view: v2, index: 2))) v1.updateConstraints() v2.updateConstraints() } public func visualFormat(_ v1: YAVView, _ v2: YAVView, _ v3: YAVView, closure: (ViewExpression, ViewExpression, ViewExpression) -> ()) { v1.translatesAutoresizingMaskIntoConstraints = false v2.translatesAutoresizingMaskIntoConstraints = false v3.translatesAutoresizingMaskIntoConstraints = false closure(.view(LayoutViewName(view: v1, index: 1)), .view(LayoutViewName(view: v2, index: 2)), .view(LayoutViewName(view: v3, index: 3))) v1.updateConstraints() v2.updateConstraints() v3.updateConstraints() } public func visualFormat(_ v1: YAVView, _ v2: YAVView, _ v3: YAVView, _ v4: YAVView, closure: (ViewExpression, ViewExpression, ViewExpression, ViewExpression) -> ()) { v1.translatesAutoresizingMaskIntoConstraints = false v2.translatesAutoresizingMaskIntoConstraints = false v3.translatesAutoresizingMaskIntoConstraints = false v4.translatesAutoresizingMaskIntoConstraints = false closure(.view(LayoutViewName(view: v1, index: 1)), .view(LayoutViewName(view: v2, index: 2)), .view(LayoutViewName(view: v3, index: 3)), .view(LayoutViewName(view: v4, index: 4))) v1.updateConstraints() v2.updateConstraints() v3.updateConstraints() v4.updateConstraints() } public func visualFormat(_ v1: YAVView, _ v2: YAVView, _ v3: YAVView, _ v4: YAVView, _ v5: YAVView, closure: (ViewExpression, ViewExpression, ViewExpression, ViewExpression, ViewExpression) -> ()) { v1.translatesAutoresizingMaskIntoConstraints = false v2.translatesAutoresizingMaskIntoConstraints = false v3.translatesAutoresizingMaskIntoConstraints = false v4.translatesAutoresizingMaskIntoConstraints = false v5.translatesAutoresizingMaskIntoConstraints = false closure(.view(LayoutViewName(view: v1, index: 1)), .view(LayoutViewName(view: v2, index: 2)), .view(LayoutViewName(view: v3, index: 3)), .view(LayoutViewName(view: v4, index: 4)), .view(LayoutViewName(view: v5, index: 5))) v1.updateConstraints() v2.updateConstraints() v3.updateConstraints() v4.updateConstraints() v5.updateConstraints() } // MARK: public enum ViewExpression { case view(LayoutViewName) case predicate(LayoutPredicate) } // MARK: <viewName> public struct LayoutViewName : CustomStringConvertible { internal let view: YAVView internal let index: Int public var description: String { return "v" + String(index) } } // MARK: <predicate> public struct LayoutPredicate : CustomStringConvertible { fileprivate let relation: LayoutRelation fileprivate let object: LayoutObjectOfPredicate fileprivate let priority: Int? public var description: String { let d = relation.rawValue + object.description guard let p = priority else { return d } return d + "@" + String(p) } } // MARK: <relation> public enum LayoutRelation : String { case equal = "==" case greaterThanOrEqual = ">=" case lessThanOrEqual = "<=" } // MARK: <objectOfPredicate> public enum LayoutObjectOfPredicate : CustomStringConvertible { case constant(Int) case view(LayoutViewName) public var description: String { switch self { case .constant(let n): return String(n) case .view(let view): return view.description } } } // MARK: <orientation> public enum LayoutOrientation : String { case v = "V" case h = "H" } // MARK: <view> public struct LayoutView : CustomStringConvertible { fileprivate let view: LayoutViewName fileprivate let predicates: [LayoutPredicate] public var description: String { let v = view.description if predicates.isEmpty { return v } return v + "(" + predicates.map { $0.description } .joined(separator: ",") + ")" } internal var relatedViews: [LayoutViewName] { return [view] + predicates.flatMap { e -> LayoutViewName? in switch e.object { case .view(let v): return v default: return nil } } } fileprivate init(_ elements: [ViewExpression]) { guard let view_part = elements.first, case let .view(v) = view_part else { fatalError("View expected") } view = v let pred_part = elements.dropFirst() predicates = pred_part.map { e in if case let .predicate(p) = e { return p } fatalError("Predicate expected") } } } // MARK: <visualFormatString> public enum VisualFormat : CustomStringConvertible, ExpressibleByIntegerLiteral, ExpressibleByArrayLiteral { case superview case view(LayoutView) case connection case predicate(LayoutPredicate) case number(Int) case composition([VisualFormat]) case options(LayoutFormatOptions) public var description: String { switch self { case .superview: return "|" case .view(let v): return "[" + v.description + "]" case .connection: return "-" case .predicate(let p): return "(" + p.description + ")" case .number(let n): return String(n) case .composition(let c): return c.map { $0.description } .joined(separator: "") case .options: return "" } } // FIXME: report error for multiple options internal var options: LayoutFormatOptions { switch self { case .options(let opts): return opts case .composition(let c): for case let .options(o) in c { return o } default: () } return LayoutFormatOptions() } internal var relatedViews: [LayoutViewName] { switch self { case .view(let v): return v.relatedViews case .composition(let c): return c.flatMap { $0.relatedViews } default: return [] } } internal var viewsDictionary: [String:AnyObject] { var d = [String:AnyObject]() relatedViews.forEach { d[$0.description] = $0.view } return d } public init(integerLiteral value: IntegerLiteralType) { self = .number(value) } public init(arrayLiteral elements: ViewExpression...) { self = .view(LayoutView(elements)) } fileprivate init(composition elements: VisualFormat...) { let t = elements.flatMap { e -> [VisualFormat] in switch e { case .composition(let c): return c default: return [e] } } self = .composition(t) } } // MARK: helper funcs private func createVisualFormatPredicate(view: ViewExpression, priority: Int? = nil) -> VisualFormat { if case let .predicate(p) = view { return .predicate(LayoutPredicate(relation: p.relation, object: p.object, priority: priority)) } fatalError("Error") } private func createViewExpressionPredicate(view: ViewExpression, relation: LayoutRelation) -> ViewExpression { if case let .view(v) = view { return .predicate(LayoutPredicate(relation: relation, object: .view(v), priority: nil)) } fatalError("Error") } // MARK: - operators prefix operator | public prefix func |(e: VisualFormat) -> VisualFormat { return VisualFormat(composition: .superview, e) } postfix operator | public postfix func |(e: VisualFormat) -> VisualFormat { return VisualFormat(composition: e, .superview) } prefix operator |- public prefix func |-(e: VisualFormat) -> VisualFormat { return VisualFormat(composition: .superview, .connection, e) } public prefix func |-(e: (ViewExpression)) -> VisualFormat { return VisualFormat(composition: .superview, .connection, createVisualFormatPredicate(view: e)) } postfix operator -| public postfix func -|(e: VisualFormat) -> VisualFormat { return VisualFormat(composition: e, .connection, .superview) } public postfix func -|(e: (ViewExpression)) -> VisualFormat { return VisualFormat(composition: createVisualFormatPredicate(view: e), .connection, .superview) } //infix operator -: AdditionPrecedence public func -(lhs: VisualFormat, rhs: VisualFormat) -> VisualFormat { return VisualFormat(composition: lhs, .connection, rhs) } public func -(lhs: VisualFormat, rhs: (ViewExpression)) -> VisualFormat { return VisualFormat(composition: lhs, .connection, createVisualFormatPredicate(view: rhs)) } prefix operator == public prefix func ==(n: Int) -> ViewExpression { return .predicate(LayoutPredicate(relation: .equal, object: .constant(n), priority: nil)) } public prefix func ==(view: ViewExpression) -> ViewExpression { return createViewExpressionPredicate(view: view, relation: .equal) } prefix operator <= public prefix func <=(n: Int) -> ViewExpression { return .predicate(LayoutPredicate(relation: .lessThanOrEqual, object: .constant(n), priority: nil)) } public prefix func <=(view: ViewExpression) -> ViewExpression { return createViewExpressionPredicate(view: view, relation: .lessThanOrEqual) } prefix operator >= public prefix func >=(n: Int) -> ViewExpression { return .predicate(LayoutPredicate(relation: .greaterThanOrEqual, object: .constant(n), priority: nil)) } public prefix func >=(view: ViewExpression) -> ViewExpression { return createViewExpressionPredicate(view: view, relation: .greaterThanOrEqual) } //infix operator % {} public func %(lhs: VisualFormat, rhs: LayoutFormatOptions) -> VisualFormat { return VisualFormat(composition: lhs, .options(rhs)) } infix operator ~: AssignmentPrecedence @discardableResult public func ~(lhs: ViewExpression, rhs: Int) -> ViewExpression { if case let .predicate(p) = lhs { return .predicate(LayoutPredicate(relation: p.relation, object: p.object, priority: rhs)) } fatalError("Error") } @discardableResult public func ~(lhs: LayoutOrientation, rhs: VisualFormat) -> [AnyObject] { let exp = lhs.rawValue + ":" + rhs.description let c = NSLayoutConstraint.constraints(withVisualFormat: exp, options: rhs.options, metrics: nil, views: rhs.viewsDictionary) NSLayoutConstraint.activate(c) return c }
mit
095a3828b9968f162e910245d7f9a868
29.073491
129
0.663728
4.307519
false
false
false
false
jseanj/SwiftPullToRefresh
Demo/SwiftPullRefreshDemo/SwiftPullRefreshDemo/SwiftPullRefresh/StateMachine.swift
1
3383
// // StateMachine.swift // SwiftPullRefreshDemo // // Created by jins on 14/10/29. // Copyright (c) 2014年 BlackWater. All rights reserved. // import Foundation protocol EventType { var name: String {get set} var code: String {get set} } struct Event { var name: String var code: String } //为什么struct不可以 class StateType { var name: String! var entry: (()->())? var exit: (()->())? var transitions: [String: Transition] = [:] init(name: String, entry: (()->())? = nil, exit: (()->())? = nil) { self.name = name self.entry = entry self.exit = exit } func hasTransition(eventCode: String) -> Bool { return transitions[eventCode] != nil ? true : false } func addTransition(event: Event, toState: StateType) { transitions[ event.code ] = Transition(from: self, to: toState, trigger: event) } func getAllToStates() -> [StateType] { var result = [StateType]() for transition in transitions.values { result.append(transition.to) } return result } // 根据事件获得下一个状态 func getToState(eventCode: String) -> StateType? { if transitions[eventCode] != nil { let transition = transitions[eventCode] as Transition? return transition!.to } return nil } func executeEntry() { if entry != nil { entry!() } } func executeExit() { if exit != nil { exit!() } } } struct Transition { var from: StateType var to: StateType var trigger: Event } class StateMachine { var initState: StateType var resetEvents = [Event]() init(initState: StateType) { self.initState = initState } func addResetEvents(events: Event...) { for event in events { resetEvents.append(event) } } func addResetEventByAddingTransitions(event: Event) { } func isResetEvent(eventCode: String) -> Bool { for resetEvent in resetEvents { if resetEvent.code == eventCode { return true } } return false } // func getAllStatesFromState(fromeState: StateType) -> [StateType] { // var result = [StateType]() // for state in fromeState.getAllToStates() { // result += getAllStatesFromState(state) // } // return result // } } class Controller { var currentState: StateType var machine: StateMachine init(currentState: StateType, machine: StateMachine) { self.currentState = currentState self.machine = machine } func handle(eventCode: String) { if currentState.hasTransition(eventCode) { // 如果当前状态可以转移,则转移到对应的状态 transitionToState(currentState.getToState(eventCode)!) } else if (machine.isResetEvent(eventCode)) { // 如果是重置事件,则转移到初始状态 transitionToState(machine.initState) } } // 转移状态 func transitionToState(toState: StateType) { currentState.executeExit() currentState = toState currentState.executeEntry() } }
mit
eb87903cac5c5e632fc995c975370c20
23.380597
87
0.566881
4.344415
false
false
false
false
khizkhiz/swift
test/DebugInfo/inlinedAt.swift
1
1813
// RUN: %target-swift-frontend %s -O -I %t -emit-sil -emit-verbose-sil -o - \ // RUN: | FileCheck %s --check-prefix=CHECK-SIL // RUN: %target-swift-frontend %s -O -I %t -emit-ir -g -o - | FileCheck %s #setline 100 "abc.swift" @inline(__always) func h(k : Int) -> Int { // 101 return k // 102 } #setline 200 "abc.swift" @inline(__always) func g(j : Int) -> Int { // 201 return h(j) // 202 } #setline 301 "abc.swift" public func f(i : Int) -> Int { // 301 return g(i) // 302 } // CHECK-SIL: sil {{.*}}@_TF9inlinedAt1fFSiSi : // CHECK-SIL-NOT: return // CHECK-SIL: debug_value %0 : $Int, let, name "k", argno 1 // CHECK-SIL-SAME: line:101:8:in_prologue // CHECK-SIL-SAME: perf_inlined_at line:202:10 // CHECK-SIL-SAME: perf_inlined_at line:302:10 // CHECK: define {{.*}}@_TF9inlinedAt1fFSiSi // CHECK-NOT: ret // CHECK: @llvm.dbg.value // CHECK: @llvm.dbg.value // CHECK: @llvm.dbg.value({{.*}}), !dbg ![[L1:.*]] // CHECK: ![[F:.*]] = distinct !DISubprogram(name: "f", // CHECK: ![[G:.*]] = distinct !DISubprogram(name: "g", // CHECK: ![[H:.*]] = distinct !DISubprogram(name: "h", // CHECK: ![[L3:.*]] = !DILocation(line: 302, column: 13, // CHECK-SAME: scope: ![[F_SCOPE:.*]]) // CHECK: ![[F_SCOPE]] = distinct !DILexicalBlock(scope: ![[F]], // CHECK-SAME: line: 301, column: 31) // CHECK: ![[L1]] = !DILocation(line: 101, column: 8, scope: ![[H]], // CHECK-SAME: inlinedAt: ![[L2:.*]]) // CHECK: ![[L2]] = !DILocation(line: 202, column: 13, scope: ![[G_SCOPE:.*]], // CHECK-SAME: inlinedAt: ![[L3]]) // CHECK: ![[G_SCOPE]] = distinct !DILexicalBlock(scope: ![[G]], // CHECK-SAME: line: 201, column: 24)
apache-2.0
8e64d168e812e0b18960206f3b2c3084
36.770833
78
0.5262
3.021667
false
false
false
false
tkremenek/swift
test/SILGen/generic_casts.swift
9
13202
// RUN: %target-swift-emit-silgen -swift-version 5 -module-name generic_casts -Xllvm -sil-full-demangle %s | %FileCheck %s protocol ClassBound : class {} protocol NotClassBound {} class C : ClassBound, NotClassBound {} struct S : NotClassBound {} struct Unloadable : NotClassBound { var x : NotClassBound } // CHECK-LABEL: sil hidden [ossa] @$s13generic_casts020opaque_archetype_to_c1_D0{{[_0-9a-zA-Z]*}}F func opaque_archetype_to_opaque_archetype <T:NotClassBound, U>(_ t:T) -> U { return t as! U // CHECK: bb0([[RET:%.*]] : $*U, {{%.*}}: $*T): // CHECK: unconditional_checked_cast_addr T in {{%.*}} : $*T to U in [[RET]] : $*U } // CHECK-LABEL: sil hidden [ossa] @$s13generic_casts020opaque_archetype_is_c1_D0{{[_0-9a-zA-Z]*}}F func opaque_archetype_is_opaque_archetype <T:NotClassBound, U>(_ t:T, u:U.Type) -> Bool { return t is U // CHECK: checked_cast_addr_br take_always T in [[VAL:%.*]] : $*T to U in [[DEST:%.*]] : $*U, [[YES:bb[0-9]+]], [[NO:bb[0-9]+]] // CHECK: [[YES]]: // CHECK: [[Y:%.*]] = integer_literal $Builtin.Int1, -1 // CHECK: destroy_addr [[DEST]] // CHECK: br [[CONT:bb[0-9]+]]([[Y]] : $Builtin.Int1) // CHECK: [[NO]]: // CHECK: [[N:%.*]] = integer_literal $Builtin.Int1, 0 // CHECK: br [[CONT]]([[N]] : $Builtin.Int1) // CHECK: [[CONT]]([[I1:%.*]] : $Builtin.Int1): // CHECK-NEXT: [[META:%.*]] = metatype $@thin Bool.Type // CHECK-NEXT: function_ref Swift.Bool.init(_builtinBooleanLiteral: Builtin.Int1) // CHECK-NEXT: [[BOOL:%.*]] = function_ref @$sSb22_builtinBooleanLiteralSbBi1__tcfC : // CHECK-NEXT: [[RES:%.*]] = apply [[BOOL]]([[I1]], [[META]]) // -- we don't consume the checked value // CHECK: return [[RES]] : $Bool } // CHECK-LABEL: sil hidden [ossa] @$s13generic_casts026opaque_archetype_to_class_D0{{[_0-9a-zA-Z]*}}F func opaque_archetype_to_class_archetype <T:NotClassBound, U:ClassBound> (_ t:T) -> U { return t as! U // CHECK: unconditional_checked_cast_addr T in {{%.*}} : $*T to U in [[DOWNCAST_ADDR:%.*]] : $*U // CHECK: [[DOWNCAST:%.*]] = load [take] [[DOWNCAST_ADDR]] : $*U // CHECK: return [[DOWNCAST]] : $U } // CHECK-LABEL: sil hidden [ossa] @$s13generic_casts026opaque_archetype_is_class_D0{{[_0-9a-zA-Z]*}}F func opaque_archetype_is_class_archetype <T:NotClassBound, U:ClassBound> (_ t:T, u:U.Type) -> Bool { return t is U // CHECK: copy_addr {{.*}} : $*T // CHECK: checked_cast_addr_br take_always T in [[VAL:%.*]] : {{.*}} to U } // CHECK-LABEL: sil hidden [ossa] @$s13generic_casts019class_archetype_to_c1_D0{{[_0-9a-zA-Z]*}}F func class_archetype_to_class_archetype <T:ClassBound, U:ClassBound>(_ t:T) -> U { return t as! U // Error bridging can change the identity of class-constrained archetypes. // CHECK: unconditional_checked_cast_addr T in {{%.*}} : $*T to U in [[DOWNCAST_ADDR:%.*]] : $*U // CHECK: [[DOWNCAST:%.*]] = load [take] [[DOWNCAST_ADDR]] // CHECK: return [[DOWNCAST]] : $U } // CHECK-LABEL: sil hidden [ossa] @$s13generic_casts019class_archetype_is_c1_D0{{[_0-9a-zA-Z]*}}F func class_archetype_is_class_archetype <T:ClassBound, U:ClassBound>(_ t:T, u:U.Type) -> Bool { return t is U // Error bridging can change the identity of class-constrained archetypes. // CHECK: checked_cast_addr_br {{.*}} T in {{%.*}} : $*T to U in {{%.*}} : $*U } // CHECK-LABEL: sil hidden [ossa] @$s13generic_casts38opaque_archetype_to_addr_only_concrete{{[_0-9a-zA-Z]*}}F func opaque_archetype_to_addr_only_concrete <T:NotClassBound> (_ t:T) -> Unloadable { return t as! Unloadable // CHECK: bb0([[RET:%.*]] : $*Unloadable, {{%.*}}: $*T): // CHECK: unconditional_checked_cast_addr T in {{%.*}} : $*T to Unloadable in [[RET]] : $*Unloadable } // CHECK-LABEL: sil hidden [ossa] @$s13generic_casts38opaque_archetype_is_addr_only_concrete{{[_0-9a-zA-Z]*}}F func opaque_archetype_is_addr_only_concrete <T:NotClassBound> (_ t:T) -> Bool { return t is Unloadable // CHECK: checked_cast_addr_br take_always T in [[VAL:%.*]] : {{.*}} to Unloadable in } // CHECK-LABEL: sil hidden [ossa] @$s13generic_casts37opaque_archetype_to_loadable_concrete{{[_0-9a-zA-Z]*}}F func opaque_archetype_to_loadable_concrete <T:NotClassBound>(_ t:T) -> S { return t as! S // CHECK: unconditional_checked_cast_addr T in {{%.*}} : $*T to S in [[DOWNCAST_ADDR:%.*]] : $*S // CHECK: [[DOWNCAST:%.*]] = load [trivial] [[DOWNCAST_ADDR]] : $*S // CHECK: return [[DOWNCAST]] : $S } // CHECK-LABEL: sil hidden [ossa] @$s13generic_casts37opaque_archetype_is_loadable_concrete{{[_0-9a-zA-Z]*}}F func opaque_archetype_is_loadable_concrete <T:NotClassBound>(_ t:T) -> Bool { return t is S // CHECK: checked_cast_addr_br take_always T in {{%.*}} : $*T to S in } // CHECK-LABEL: sil hidden [ossa] @$s13generic_casts019class_archetype_to_C0{{[_0-9a-zA-Z]*}}F func class_archetype_to_class <T:ClassBound>(_ t:T) -> C { return t as! C // CHECK: [[DOWNCAST:%.*]] = unconditional_checked_cast {{%.*}} to C // CHECK: return [[DOWNCAST]] : $C } // CHECK-LABEL: sil hidden [ossa] @$s13generic_casts019class_archetype_is_C0{{[_0-9a-zA-Z]*}}F func class_archetype_is_class <T:ClassBound>(_ t:T) -> Bool { return t is C // CHECK: checked_cast_br {{%.*}} to C } // CHECK-LABEL: sil hidden [ossa] @$s13generic_casts022opaque_existential_to_C10_archetype{{[_0-9a-zA-Z]*}}F func opaque_existential_to_opaque_archetype <T:NotClassBound>(_ p:NotClassBound) -> T { return p as! T // CHECK: bb0([[RET:%.*]] : $*T, [[ARG:%.*]] : $*NotClassBound): // CHECK: [[TEMP:%.*]] = alloc_stack $NotClassBound // CHECK-NEXT: copy_addr [[ARG]] to [initialization] [[TEMP]] // CHECK-NEXT: unconditional_checked_cast_addr NotClassBound in [[TEMP]] : $*NotClassBound to T in [[RET]] : $*T // CHECK-NEXT: dealloc_stack [[TEMP]] // CHECK-NEXT: [[T0:%.*]] = tuple () // CHECK-NEXT: return [[T0]] } // CHECK-LABEL: sil hidden [ossa] @$s13generic_casts022opaque_existential_is_C10_archetype{{[_0-9a-zA-Z]*}}F func opaque_existential_is_opaque_archetype <T:NotClassBound>(_ p:NotClassBound, _: T) -> Bool { return p is T // CHECK: checked_cast_addr_br take_always NotClassBound in [[CONTAINER:%.*]] : {{.*}} to T in } // CHECK-LABEL: sil hidden [ossa] @$s13generic_casts37opaque_existential_to_class_archetype{{[_0-9a-zA-Z]*}}F func opaque_existential_to_class_archetype <T:ClassBound>(_ p:NotClassBound) -> T { return p as! T // CHECK: unconditional_checked_cast_addr NotClassBound in {{%.*}} : $*NotClassBound to T in [[DOWNCAST_ADDR:%.*]] : $*T // CHECK: [[DOWNCAST:%.*]] = load [take] [[DOWNCAST_ADDR]] : $*T // CHECK: return [[DOWNCAST]] : $T } // CHECK-LABEL: sil hidden [ossa] @$s13generic_casts37opaque_existential_is_class_archetype{{[_0-9a-zA-Z]*}}F func opaque_existential_is_class_archetype <T:ClassBound>(_ p:NotClassBound, _: T) -> Bool { return p is T // CHECK: checked_cast_addr_br take_always NotClassBound in {{%.*}} : $*NotClassBound to T in } // CHECK-LABEL: sil hidden [ossa] @$s13generic_casts021class_existential_to_C10_archetype{{[_0-9a-zA-Z]*}}F func class_existential_to_class_archetype <T:ClassBound>(_ p:ClassBound) -> T { return p as! T // CHECK: unconditional_checked_cast_addr ClassBound in {{%.*}} : $*ClassBound to T in [[DOWNCAST_ADDR:%.*]] : $*T // CHECK: [[DOWNCAST:%.*]] = load [take] [[DOWNCAST_ADDR]] // CHECK: return [[DOWNCAST]] : $T } // CHECK-LABEL: sil hidden [ossa] @$s13generic_casts021class_existential_is_C10_archetype{{[_0-9a-zA-Z]*}}F func class_existential_is_class_archetype <T:ClassBound>(_ p:ClassBound, _: T) -> Bool { return p is T // CHECK: checked_cast_addr_br {{.*}} ClassBound in {{%.*}} : $*ClassBound to T in {{%.*}} : $*T } // CHECK-LABEL: sil hidden [ossa] @$s13generic_casts40opaque_existential_to_addr_only_concrete{{[_0-9a-zA-Z]*}}F func opaque_existential_to_addr_only_concrete(_ p: NotClassBound) -> Unloadable { return p as! Unloadable // CHECK: bb0([[RET:%.*]] : $*Unloadable, {{%.*}}: $*NotClassBound): // CHECK: unconditional_checked_cast_addr NotClassBound in {{%.*}} : $*NotClassBound to Unloadable in [[RET]] : $*Unloadable } // CHECK-LABEL: sil hidden [ossa] @$s13generic_casts40opaque_existential_is_addr_only_concrete{{[_0-9a-zA-Z]*}}F func opaque_existential_is_addr_only_concrete(_ p: NotClassBound) -> Bool { return p is Unloadable // CHECK: checked_cast_addr_br take_always NotClassBound in {{%.*}} : $*NotClassBound to Unloadable in } // CHECK-LABEL: sil hidden [ossa] @$s13generic_casts39opaque_existential_to_loadable_concrete{{[_0-9a-zA-Z]*}}F func opaque_existential_to_loadable_concrete(_ p: NotClassBound) -> S { return p as! S // CHECK: unconditional_checked_cast_addr NotClassBound in {{%.*}} : $*NotClassBound to S in [[DOWNCAST_ADDR:%.*]] : $*S // CHECK: [[DOWNCAST:%.*]] = load [trivial] [[DOWNCAST_ADDR]] : $*S // CHECK: return [[DOWNCAST]] : $S } // CHECK-LABEL: sil hidden [ossa] @$s13generic_casts39opaque_existential_is_loadable_concrete{{[_0-9a-zA-Z]*}}F func opaque_existential_is_loadable_concrete(_ p: NotClassBound) -> Bool { return p is S // CHECK: checked_cast_addr_br take_always NotClassBound in {{%.*}} : $*NotClassBound to S in } // CHECK-LABEL: sil hidden [ossa] @$s13generic_casts021class_existential_to_C0{{[_0-9a-zA-Z]*}}F func class_existential_to_class(_ p: ClassBound) -> C { return p as! C // CHECK: [[DOWNCAST:%.*]] = unconditional_checked_cast {{%.*}} to C // CHECK: return [[DOWNCAST]] : $C } // CHECK-LABEL: sil hidden [ossa] @$s13generic_casts021class_existential_is_C0{{[_0-9a-zA-Z]*}}F func class_existential_is_class(_ p: ClassBound) -> Bool { return p is C // CHECK: checked_cast_br {{%.*}} to C } // CHECK-LABEL: sil hidden [ossa] @$s13generic_casts27optional_anyobject_to_classyAA1CCSgyXlSgF func optional_anyobject_to_class(_ p: AnyObject?) -> C? { return p as? C // CHECK: checked_cast_br {{%.*}} : $AnyObject to C } // The below tests are to ensure we don't dig into an optional operand when // casting to a non-class archetype, as it could dynamically be an optional type. // CHECK-LABEL: sil hidden [ossa] @$s13generic_casts32optional_any_to_opaque_archetype{{[_0-9a-zA-Z]*}}F func optional_any_to_opaque_archetype<T>(_ x: Any?) -> T { return x as! T // CHECK: bb0([[RET:%.*]] : $*T, {{%.*}} : $*Optional<Any>): // CHECK: unconditional_checked_cast_addr Optional<Any> in {{%.*}} : $*Optional<Any> to T in [[RET]] : $*T } // CHECK-LABEL: sil hidden [ossa] @$s13generic_casts46optional_any_conditionally_to_opaque_archetype{{[_0-9a-zA-Z]*}}F func optional_any_conditionally_to_opaque_archetype<T>(_ x: Any?) -> T? { return x as? T // CHECK: checked_cast_addr_br take_always Optional<Any> in {{%.*}} : $*Optional<Any> to T in {{%.*}} : $*T } // CHECK-LABEL: sil hidden [ossa] @$s13generic_casts32optional_any_is_opaque_archetype{{[_0-9a-zA-Z]*}}F func optional_any_is_opaque_archetype<T>(_ x: Any?, _: T) -> Bool { return x is T // CHECK: checked_cast_addr_br take_always Optional<Any> in {{%.*}} : $*Optional<Any> to T in {{%.*}} : $*T } // But we can dig into at most one layer of the operand if it's // an optional archetype... // CHECK-LABEL: sil hidden [ossa] @$s13generic_casts016optional_any_to_C17_opaque_archetype{{[_0-9a-zA-Z]*}}F func optional_any_to_optional_opaque_archetype<T>(_ x: Any?) -> T? { return x as! T? // CHECK: unconditional_checked_cast_addr Any in {{%.*}} : $*Any to T in {{%.*}} : $*T } // CHECK-LABEL: sil hidden [ossa] @$s13generic_casts030optional_any_conditionally_to_C17_opaque_archetype{{[_0-9a-zA-Z]*}}F func optional_any_conditionally_to_optional_opaque_archetype<T>(_ x: Any?) -> T?? { return x as? T? // CHECK: checked_cast_addr_br take_always Any in {{%.*}} : $*Any to T in {{%.*}} : $*T } // CHECK-LABEL: sil hidden [ossa] @$s13generic_casts016optional_any_is_C17_opaque_archetype{{[_0-9a-zA-Z]*}}F func optional_any_is_optional_opaque_archetype<T>(_ x: Any?, _: T) -> Bool { return x is T? // Because the levels of optional are the same, 'is' doesn't transform into an 'as?', // so we just cast directly without digging into the optional operand. // CHECK: checked_cast_addr_br take_always Optional<Any> in {{%.*}} : $*Optional<Any> to Optional<T> in {{%.*}} : $*Optional<T> } // And we can dig into the operand when casting to a class archetype, as it // cannot dynamically be optional... // CHECK-LABEL: sil hidden [ossa] @$s13generic_casts31optional_any_to_class_archetype{{[_0-9a-zA-Z]*}}F func optional_any_to_class_archetype<T : AnyObject>(_ x: Any?) -> T { return x as! T // CHECK: unconditional_checked_cast_addr Any in {{%.*}} : $*Any to T in {{%.*}} : $*T } // CHECK-LABEL: sil hidden [ossa] @$s13generic_casts45optional_any_conditionally_to_class_archetype{{[_0-9a-zA-Z]*}}F func optional_any_conditionally_to_class_archetype<T : AnyObject>(_ x: Any?) -> T? { return x as? T // CHECK: checked_cast_addr_br take_always Any in {{%.*}} : $*Any to T in {{%.*}} : $*T } // CHECK-LABEL: sil hidden [ossa] @$s13generic_casts31optional_any_is_class_archetype{{[_0-9a-zA-Z]*}}F func optional_any_is_class_archetype<T : AnyObject>(_ x: Any?, _: T) -> Bool { return x is T // CHECK: checked_cast_addr_br take_always Any in {{%.*}} : $*Any to T in {{%.*}} : $*T }
apache-2.0
b2a178d94862e2295876d60a4c9ca278
45.485915
131
0.643539
3.155354
false
false
false
false
lennet/bugreporter
Bugreporter/Screen Recorder/RingBuffer.swift
1
834
// // RingBuffer.swift // Bugreporter // // Created by Leo Thomas on 18/07/16. // Copyright © 2016 Leonard Thomas. All rights reserved. // import Foundation class RingBuffer<T> { var elements: [T?] final private var writeIndex = 0 var length: Int init(length: Int) { elements = [T?](repeating: nil, count: length) self.length = length } subscript(index: Int) -> T? { get { return elements[index] } } var count: Int { get { return writeIndex > length ? elements.count : writeIndex } } var isEmpty: Bool { get { return count == 0 } } func append(element: T) { elements[writeIndex % length] = element writeIndex += 1 } }
mit
331f78f0ce3f7afeff012cad7657bfea
16.723404
68
0.511405
4.063415
false
false
false
false
garricn/CopyPaste
CopyPaste/DataContext.swift
1
1129
// // Copyright © 2017 SwiftCoders. All rights reserved. // import Foundation public final class DataContext<D: Codable> { private(set) var data: D private let initialValue: D private let store: DataStore public init(initialValue: D, store: DataStore) { self.initialValue = initialValue self.store = store if let decoded = store.decode(D.self) { data = decoded } else { data = initialValue } defer { store.encode(data) } #if DEBUG let key = Globals.EnvironmentVariables.codables.appending(store.name) let string = ProcessInfo.processInfo.environment[key] guard let data = string?.data(using: .utf8), let decoded = store.decode(type: D.self, from: data) else { return } self.data = decoded #endif } public func save(_ data: D) { self.data = data store.encode(data) } public func reset() { data = initialValue store.encode(data) } }
mit
e709a584aa789dc581005541604cdcab
22.020408
112
0.546986
4.53012
false
false
false
false
vinivendra/jokr
tests/Unit Tests/Antlr to Jokr Tests/AntlrToJokrTests.swift
1
10594
import Antlr4 import XCTest private let testFilesPath = CommandLine.arguments[1] + "/tests/Unit Tests/Antlr To Jokr Tests/" class AntlrToJokrTests: XCTestCase { func getProgram( inFile filename: String) throws -> JokrParser.ProgramContext { do { let contents = try! String(contentsOfFile: testFilesPath + filename) let inputStream = ANTLRInputStream(contents) let lexer = JokrLexer(inputStream) let tokens = CommonTokenStream(lexer) let parser = try JokrParser(tokens) parser.setBuildParseTree(true) return try parser.program() } catch (let error) { throw error } } //////////////////////////////////////////////////////////////////////////// // MARK: - Tests func testEmpty() { do { // WITH: let tree = try getProgram(inFile: "TestEmpty") // TEST: program contains no statements or declarations XCTAssertNil(tree.toJKRTreeStatements()) XCTAssertNil(tree.toJKRTreeDeclarations()) } catch (let error) { XCTFail("Lexer or Parser failed during test.\nError: \(error)") } } func testIDs() { do { // WITH: let tree = try getProgram(inFile: "TestIDs") let ids = tree.filter(type: JokrParser.AssignmentContext.self) .flatMap { $0.variableDeclaration()?.ID()?.toJKRTreeID() } let expectedIDs: [JKRTreeID] = ["bla", "fooBar", "baz", "fooBar", "bla"] // TEST: All elements were converted successfully XCTAssertEqual(ids, expectedIDs) } catch (let error) { XCTFail("Lexer or Parser failed during test.\nError: \(error)") } } func testTypes() { do { // WITH: let tree = try getProgram(inFile: "TestTypes") let types = tree.filter(type: JokrParser.AssignmentContext.self) .flatMap { $0.variableDeclaration()?.TYPE()?.toJKRTreeType() } let expectedTypes: [JKRTreeType] = ["Int", "Float", "Blah", "Int", "Void"] // TEST: All elements were converted successfully XCTAssertEqual(types, expectedTypes) } catch (let error) { XCTFail("Lexer or Parser failed during test.\nError: \(error)") } } func testStatements() { do { // WITH: let tree = try getProgram(inFile: "TestStatements") guard let statements = tree.toJKRTreeStatements() else { XCTFail("Failed to get statements from statements file.") return } let expectedStatements: [JKRTreeStatement] = [ .assignment(.declaration("Int", "x", 0)), .assignment(.declaration("Int", "y", 0)), .functionCall(JKRTreeFunctionCall(id: "f")), .returnStm(1) ] // TEST: All elements were converted successfully XCTAssertEqual(statements, expectedStatements) } catch (let error) { XCTFail("Lexer or Parser failed during test.\nError: \(error)") } } func testDeclarations() { do { // WITH: let tree = try getProgram(inFile: "TestDeclarations") guard let declarations = tree.toJKRTreeDeclarations() else { XCTFail("Failed to get declarations from declarations file.") return } let expectedDeclarations: [JKRTreeDeclaration] = [ .functionDeclaration( JKRTreeFunctionDeclaration( type: "Int", id: "func1", parameters: [], block: [.returnStm(0)] ) ), .functionDeclaration( JKRTreeFunctionDeclaration( type: "Int", id: "func2", parameters: [JKRTreeParameterDeclaration(type: "Float", id: "bla")], block: [ JKRTreeStatement.assignment(.declaration( "String", "baz", .operation(5, "+", 6))), JKRTreeStatement.returnStm(0)] ) ) ] // TEST: All elements were converted successfully XCTAssertEqual(declarations, expectedDeclarations) } catch (let error) { XCTFail("Lexer or Parser failed during test.\nError: \(error)") } } func testOperator() { do { // WITH: let tree = try getProgram(inFile: "TestOperators") let operators = tree.filter(type: JokrParser.ExpressionContext.self) .flatMap { $0.OPERATOR()?.toJKRTreeOperator() } let expectedOperators: [JKRTreeOperator] = ["+", "-", "+"] // TEST: All elements were converted successfully XCTAssertEqual(operators, expectedOperators) } catch (let error) { XCTFail("Lexer or Parser failed during test.\nError: \(error)") } } func testExpressions() { do { // WITH: let tree = try getProgram(inFile: "TestExpressions") let expressions = tree.filter(type: JokrParser.ExpressionContext.self) // Filter only root expressions, subexpressions get tested too .filter { !($0.parent is JokrParser.ExpressionContext) } .map { $0.toJKRTreeExpression() } let expectedExpressions: [JKRTreeExpression] = [ 0, .parenthesized(1), .operation(2, "+", 3), JKRTreeExpression.lvalue("foo"), .operation(4, "+", .parenthesized( .operation(.parenthesized(5), "+", "foo"))) ] // TEST: All elements were converted successfully XCTAssertEqual(expressions, expectedExpressions) } catch (let error) { XCTFail("Lexer or Parser failed during test.\nError: \(error)") } } func testParameters() { do { let tree = try getProgram(inFile: "TestParameters") let parameterLists = tree.filter(type: JokrParser.ParameterListContext.self) // Filter only root parameter lists, sublists get tested too .filter { !($0.parent is JokrParser.ParameterListContext) }.map { $0.toJKRTreeExpressions() } let expectedParameterLists: [[JKRTreeExpression]] = [ [], ["bar"], [.parenthesized(.operation(1, "+", 2))], [.parenthesized("hue")], ["foo", .parenthesized("baz"), "blah"] ] // TEST: All elements were converted successfully // (multi-dimensional array equality has to be unrolled like this) for (parameterList, expectedParameterList) in zip(parameterLists, expectedParameterLists) { XCTAssertEqual(parameterList, expectedParameterList) } XCTAssertEqual(parameterLists.count, expectedParameterLists.count) } catch (let error) { XCTFail("Lexer or Parser failed during test.\nError: \(error)") } } func testAssignments() { do { // WITH: let tree = try getProgram(inFile: "TestAssignments") let assignments = tree.filter(type: JokrParser.AssignmentContext.self) .map { $0.toJKRTreeAssignment() } let expectedAssignments: [JKRTreeAssignment] = [ .declaration("Int", "bla", 2), .declaration("Float", "fooBar", 3), .declaration("Blah", "baz", "fooBar"), .assignment("fooBar", "bla"), .assignment("bla", 300) ] // TEST: All elements were converted successfully XCTAssertEqual(assignments, expectedAssignments) } catch (let error) { XCTFail("Lexer or Parser failed during test.\nError: \(error)") } } func testFunctionCall() { do { // WITH: let tree = try getProgram(inFile: "TestFunctionCalls") let functionCalls = tree.filter(type: JokrParser.FunctionCallContext.self) .map { $0.toJKRTreeFunctionCall() } let expectedFunctionCalls: [JKRTreeFunctionCall] = [ JKRTreeFunctionCall(id: "print"), JKRTreeFunctionCall(id: "someFunctionName"), JKRTreeFunctionCall(id: "f"), JKRTreeFunctionCall(id: "f", parameters: [1]), JKRTreeFunctionCall(id: "f", parameters: [1, 2]) ] // TEST: All elements were converted successfully XCTAssertEqual(functionCalls, expectedFunctionCalls) } catch (let error) { XCTFail("Lexer or Parser failed during test.\nError: \(error)") } } func testReturns() { do { // WITH: let tree = try getProgram(inFile: "TestReturns") let returns = tree.filter(type: JokrParser.ReturnStatementContext.self) .map { $0.toJKRTreeReturn() } let expectedReturns: [JKRTreeReturn] = [ 0, JKRTreeReturn(.operation(5, "+", 6)), JKRTreeReturn(.parenthesized(9)), "bla" ] // TEST: All elements were converted successfully XCTAssertEqual(returns, expectedReturns) } catch (let error) { XCTFail("Lexer or Parser failed during test.\nError: \(error)") } } func testParameterDeclarations() { do { let tree = try getProgram(inFile: "TestParameterDeclarations") let parameterLists = tree.filter(type: JokrParser.ParameterDeclarationListContext.self) // Filter only root parameter lists, sublists get tested too .filter { !($0.parent is JokrParser.ParameterDeclarationListContext) }.map { $0.toJKRTreeParameterDeclarations() } let expectedParameterLists: [[JKRTreeParameterDeclaration]] = [ [], [JKRTreeParameterDeclaration(type: "Float", id: "bla")], [JKRTreeParameterDeclaration(type: "Int", id: "bla"), JKRTreeParameterDeclaration(type: "Float", id: "foo")], [JKRTreeParameterDeclaration(type: "Int", id: "bla"), JKRTreeParameterDeclaration(type: "Float", id: "foo"), JKRTreeParameterDeclaration(type: "Double", id: "hue")] ] // TEST: All elements were converted successfully // (multi-dimensional array equality has to be unrolled like this) for (parameterList, expectedParameterList) in zip(parameterLists, expectedParameterLists) { XCTAssertEqual(parameterList, expectedParameterList) } XCTAssertEqual(parameterLists.count, expectedParameterLists.count) } catch (let error) { XCTFail("Lexer or Parser failed during test.\nError: \(error)") } } func testFunctionDeclarations() { do { // WITH: let tree = try getProgram(inFile: "TestFunctionDeclarations") let declarations = tree.filter(type: JokrParser.FunctionDeclarationContext.self) .map { $0.toJKRTreeFunctionDeclaration() } let expectedDeclarations: [JKRTreeFunctionDeclaration] = [ JKRTreeFunctionDeclaration( type: "Int", id: "func1", parameters: [], block: [.returnStm(0)]), JKRTreeFunctionDeclaration( type: "Int", id: "func2", parameters: [JKRTreeParameterDeclaration(type: "Float", id: "bla")], block: [ .assignment(.declaration( "String", "baz", .operation(5, "+", 6))), .returnStm(0)]), JKRTreeFunctionDeclaration( type: "Void", id: "func4", parameters: [JKRTreeParameterDeclaration(type: "Int", id: "bla"), JKRTreeParameterDeclaration(type: "Float", id: "foo"), JKRTreeParameterDeclaration(type: "Double", id: "hue")], block: [.returnStm(0)]) ] // TEST: All elements were converted successfully XCTAssertEqual(declarations, expectedDeclarations) } catch (let error) { XCTFail("Lexer or Parser failed during test.\nError: \(error)") } } }
apache-2.0
398bcbf737f6458095e8fce0f4fe326e
27.250667
77
0.65556
3.58997
false
true
false
false
aleufms/JeraUtils
JeraUtils/Base/I18nAdditions.swift
1
1330
// // I18nAdditions.swift // Glambox // // Created by Alessandro Nakamuta on 1/19/16. // Copyright © 2016 Glambox. All rights reserved. // import UIKit //extension String{ // func i18n(args: [CVarArgType]? = nil, defaultString: String? = nil) -> String{ // let localizedString = NSLocalizedString(self, comment: "") // // if let args = args{ // if let defaultString = defaultString where localizedString == self{ // return String(format: defaultString, arguments: args) // } // return String(format: localizedString, arguments: args) // } // // return localizedString // } //} public func I18n(localizableString: String, defaultString: String? = nil, args: [CVarArgType]? = nil) -> String { let localizedString = NSLocalizedString(localizableString, comment: "") if let args = args { if let defaultString = defaultString where localizedString == localizableString { return String(format: defaultString, arguments: args) } return String(format: localizedString, arguments: args) } else { if let defaultString = defaultString where localizedString == localizableString { return String(format: defaultString) } return String(format: localizedString) } }
mit
fecfb0daac8c4fa1afdc6c5a4abcf732
32.225
113
0.639579
4.400662
false
false
false
false
Prashant-mahajan/iOS-apps
NumberGames/NumberGames/ViewController.swift
1
912
// // ViewController.swift // NumberGames // // Created by Prashant Mahajan on 19/02/17. // Copyright © 2017 Prashant Mahajan. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var textInput: UITextField! @IBOutlet weak var textOutput: UITextField! @IBAction func Evaluate(_ sender: Any) { let x = Int(arc4random_uniform(5)) let y = Int(textInput.text!)! if (x == y){ textOutput.text = String("You win!!!!") } else{ textOutput.text = String("You lose") } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
571f0a05ff1f9d96f0c3497944bf7057
22.358974
80
0.610318
4.443902
false
false
false
false
iAugux/iBBS-Swift
iBBS/Additions/UIButton+Extension.swift
2
840
// // UIButton+Extension.swift // // Created by Augus on 2/6/16. // Copyright © 2016 iAugus. All rights reserved. // import UIKit extension UIButton { override public func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? { let minimalWidthAndHeight: CGFloat = 60 let buttonSize = frame.size let widthToAdd = (minimalWidthAndHeight - buttonSize.width > 0) ? minimalWidthAndHeight - buttonSize.width : 0 let heightToAdd = (minimalWidthAndHeight - buttonSize.height > 0) ? minimalWidthAndHeight - buttonSize.height : 0 let largerFrame = CGRect(x: 0-(widthToAdd / 2), y: 0-(heightToAdd / 2), width: buttonSize.width + widthToAdd, height: buttonSize.height + heightToAdd) return CGRectContainsPoint(largerFrame, point) ? self : nil } }
mit
7ede4e82c7b5d4d322712a70ecceac7d
31.307692
158
0.667461
4.302564
false
false
false
false
genedelisa/MIDISynth
MIDISynth/AVAudioUnitMIDISynth.swift
1
5825
// // AVAudioUnitMIDISynth.swift // MIDISynth // // Created by Gene De Lisa on 2/6/16. // Copyright © 2016 Gene De Lisa. All rights reserved. // import Foundation import AVFoundation // swiftlint:disable line_length /// # An AVAudioUnit example. /// /// A multi-timbral implementation of `AVAudioUnitMIDIInstrument` as an `AVAudioUnit`. /// This will use the polyphonic `kAudioUnitSubType_MIDISynth` audio unit. /// /// - author: Gene De Lisa /// - copyright: 2016 Gene De Lisa /// - date: February 2016 /// - requires: AVFoundation /// - seealso: ///[The Swift Standard Library Reference](https://developer.apple.com/library/prerelease/ios//documentation/General/Reference/SwiftStandardLibraryReference/index.html) /// /// - seealso: ///[Constructing Audio Unit Apps](https://developer.apple.com/library/ios/documentation/MusicAudio/Conceptual/AudioUnitHostingGuide_iOS/ConstructingAudioUnitApps/ConstructingAudioUnitApps.html) /// /// - seealso: ///[Audio Unit Reference](https://developer.apple.com/library/ios/documentation/AudioUnit/Reference/AudioUnit_Framework/index.html) class AVAudioUnitMIDISynth: AVAudioUnitMIDIInstrument { override init() { var description = AudioComponentDescription() description.componentType = kAudioUnitType_MusicDevice description.componentSubType = kAudioUnitSubType_MIDISynth description.componentManufacturer = kAudioUnitManufacturer_Apple description.componentFlags = 0 description.componentFlagsMask = 0 super.init(audioComponentDescription: description) //name parameter is in the form "Company Name:Unit Name" //AUAudioUnit.registerSubclass(AVAudioUnitMIDISynth.self, as: description, name: "foocom:myau", version: 1) } let soundFontFileName = "FluidR3 GM2-2" let soundFontFileExt = "SF2" // there is a problem with a drop out using this soundfont //let soundFontFileName = "GeneralUser GS v1.471" //let soundFontFileExt = "sf2" /// Loads the default sound font. /// If the file is not found, halt with an error message. func loadMIDISynthSoundFont() { guard let bankURL = Bundle.main.url(forResource: soundFontFileName, withExtension: soundFontFileExt) else { fatalError("Get the default sound font URL correct!") } loadMIDISynthSoundFont(bankURL) } /// Loads the specified sound font. /// - parameter bankURL: A URL to the sound font. func loadMIDISynthSoundFont(_ bankURL: URL) { var bankURL = bankURL let status = AudioUnitSetProperty( self.audioUnit, AudioUnitPropertyID(kMusicDeviceProperty_SoundBankURL), AudioUnitScope(kAudioUnitScope_Global), 0, &bankURL, UInt32(MemoryLayout<URL>.size)) if status != OSStatus(noErr) { print("error \(status)") } print("loaded sound font") } /// Pre-load the patches you will use. /// /// Turn on `kAUMIDISynthProperty_EnablePreload` so the midisynth will load the patch data from the file into memory. /// You load the patches first before playing a sequence or sending messages. /// Then you turn `kAUMIDISynthProperty_EnablePreload` off. It is now in a state where it will respond to MIDI program /// change messages and switch to the already cached instrument data. /// /// - precondition: the graph must be initialized /// /// [Doug's post](http://prod.lists.apple.com/archives/coreaudio-api/2016/Jan/msg00018.html) func loadPatches(_ patches: [UInt32]) throws { if let e = engine { if !e.isRunning { print("audio engine needs to be running") throw AVAudioUnitMIDISynthError.engineNotStarted } } let channel = UInt32(0) var enabled = UInt32(1) var status = AudioUnitSetProperty( self.audioUnit, AudioUnitPropertyID(kAUMIDISynthProperty_EnablePreload), AudioUnitScope(kAudioUnitScope_Global), 0, &enabled, UInt32(MemoryLayout<UInt32>.size)) if status != noErr { print("error \(status)") } // let bankSelectCommand = UInt32(0xB0 | 0) // status = MusicDeviceMIDIEvent(self.midisynthUnit, bankSelectCommand, 0, 0, 0) let pcCommand = UInt32(0xC0 | channel) for patch in patches { print("preloading patch \(patch)") status = MusicDeviceMIDIEvent(self.audioUnit, pcCommand, patch, 0, 0) if status != noErr { print("error \(status)") AudioUtils.CheckError(status) } } enabled = UInt32(0) status = AudioUnitSetProperty( self.audioUnit, AudioUnitPropertyID(kAUMIDISynthProperty_EnablePreload), AudioUnitScope(kAudioUnitScope_Global), 0, &enabled, UInt32(MemoryLayout<UInt32>.size)) if status != noErr { print("error \(status)") } // at this point the patches are loaded. You still have to send a program change at "play time" for the synth // to switch to that patch } } /// Possible Errors for this `AVAudioUnit`. /// /// - EngineNotStarted: /// The AVAudioEngine needs to be started /// /// - BadSoundFont: /// The specified sound font is no good enum AVAudioUnitMIDISynthError: Error { /// The AVAudioEngine needs to be started and it's not. case engineNotStarted /// The specified sound font is no good. case badSoundFont }
mit
1ec9bd731ac201339a3b2e7166cf67ae
34.950617
194
0.634444
4.476556
false
false
false
false
alvinvarghese/swift-hoedown
source/Hoedown.swift
2
3986
// // Markdown.swift // MarkPub // // Created by Niels de Hoog on 17/04/15. // Copyright (c) 2015 Invisible Pixel. All rights reserved. // import Foundation import Hoedown public class Hoedown { public class func renderHTMLForMarkdown(string: String, flags: HoedownHTMLFlags = .None, extensions: HoedownExtensions = .None) -> String? { let renderer = HoedownHTMLRenderer(flags: flags) let document = HoedownDocument(renderer: renderer, extensions: extensions) return document.renderMarkdown(string) } } public protocol HoedownRenderer { var internalRenderer: UnsafeMutablePointer<hoedown_renderer> { get } } public class HoedownHTMLRenderer: HoedownRenderer { public let internalRenderer: UnsafeMutablePointer<hoedown_renderer> public init(flags: HoedownHTMLFlags = .None, nestingLevel: Int = 0) { self.internalRenderer = hoedown_html_renderer_new(hoedown_html_flags(flags.rawValue), CInt(nestingLevel)) } deinit { hoedown_html_renderer_free(self.internalRenderer) } } public class HoedownDocument { let internalDocument: COpaquePointer public init(renderer: HoedownRenderer, extensions: HoedownExtensions = .None, maxNesting: UInt = 16) { self.internalDocument = hoedown_document_new(renderer.internalRenderer, hoedown_extensions(extensions.rawValue), Int(maxNesting)) } public func renderMarkdown(string: String, bufferSize: UInt = 16) -> String? { let buffer = hoedown_buffer_new(Int(bufferSize)) hoedown_document_render(self.internalDocument, buffer, string, string.characters.count); let htmlOutput = hoedown_buffer_cstr(buffer) let output = String.fromCString(htmlOutput) hoedown_buffer_free(buffer) return output } deinit { hoedown_document_free(self.internalDocument) } } public struct HoedownExtensions : OptionSetType { public let rawValue: UInt32 public init(rawValue: UInt32) { self.rawValue = rawValue } init(_ value: hoedown_extensions) { self.rawValue = value.rawValue } public static let None = HoedownExtensions(rawValue: 0) // Block-level extensions public static let Tables = HoedownExtensions(HOEDOWN_EXT_TABLES) public static let FencedCodeBlocks = HoedownExtensions(HOEDOWN_EXT_FENCED_CODE) public static let FootNotes = HoedownExtensions(HOEDOWN_EXT_FOOTNOTES) // Span-level extensions public static let AutoLinkURLs = HoedownExtensions(HOEDOWN_EXT_AUTOLINK) public static let StrikeThrough = HoedownExtensions(HOEDOWN_EXT_STRIKETHROUGH) public static let Underline = HoedownExtensions(HOEDOWN_EXT_UNDERLINE) public static let Highlight = HoedownExtensions(HOEDOWN_EXT_HIGHLIGHT) public static let Quote = HoedownExtensions(HOEDOWN_EXT_QUOTE) public static let Superscript = HoedownExtensions(HOEDOWN_EXT_SUPERSCRIPT) public static let Math = HoedownExtensions(HOEDOWN_EXT_MATH) // Other flags public static let NoIntraEmphasis = HoedownExtensions(HOEDOWN_EXT_NO_INTRA_EMPHASIS) public static let SpaceHeaders = HoedownExtensions(HOEDOWN_EXT_SPACE_HEADERS) public static let MathExplicit = HoedownExtensions(HOEDOWN_EXT_MATH_EXPLICIT) // Negative flags public static let DisableIndentedCode = HoedownExtensions(HOEDOWN_EXT_DISABLE_INDENTED_CODE) } public struct HoedownHTMLFlags : OptionSetType { public let rawValue: UInt32 public init(rawValue: UInt32) { self.rawValue = rawValue } init(_ value: hoedown_html_flags) { self.rawValue = value.rawValue } public static let None = HoedownHTMLFlags(rawValue: 0) public static let SkipHTML = HoedownHTMLFlags(HOEDOWN_HTML_SKIP_HTML) public static let Escape = HoedownHTMLFlags(HOEDOWN_HTML_ESCAPE) public static let HardWrap = HoedownHTMLFlags(HOEDOWN_HTML_HARD_WRAP) public static let UseXHTML = HoedownHTMLFlags(HOEDOWN_HTML_USE_XHTML) }
mit
afdd3cd2cf852b56e7a5a6c8896f5ca4
38.86
144
0.731059
3.739212
false
false
false
false
Neft-io/neft
packages/neft-runtime-macos/io.neft.mac/Utils.swift
1
2801
import Cocoa extension String { var uppercaseFirst: String { return String(characters.prefix(1)).uppercased() + String(characters.dropFirst()) } } func thread(_ background: @escaping () -> Void, _ completion: (() -> Void)? = nil) { let priority = DispatchQueue.GlobalQueuePriority.default DispatchQueue.global(priority: priority).async { background() DispatchQueue.main.async { if completion != nil { completion!() } } } } func thread<T>(_ background: @escaping (_ completion: (_ param: T?) -> Void) -> Void, _ completion: ((T?) -> Void)? = nil) { let priority = DispatchQueue.GlobalQueuePriority.default DispatchQueue.global(priority: priority).async { background() { (result: T?) in DispatchQueue.main.async { if completion != nil { completion!(result) } } } } } func synced<T>(_ lock: Any, _ body: () throws -> T) rethrows -> T { objc_sync_enter(lock) defer { objc_sync_exit(lock) } return try body() } class Signal { fileprivate var listeners: [(_ arg: Any?) -> Void] = [] func connect(_ listener: @escaping (_ arg: Any?) -> Void) { listeners.append(listener) } func emit(_ arg: Any? = nil) { for listener in listeners { listener(arg) } } } class Color { static fileprivate let colorDivisor: CGFloat = 255 static fileprivate let colorSpace = CGColorSpaceCreateDeviceRGB() static fileprivate var colorComponents: [CGFloat] = Array(repeating: 0, count: 4) static func hexColorToCGColor(_ hex: Int) -> CGColor { colorComponents[0] = CGFloat(hex >> 24) / colorDivisor colorComponents[1] = CGFloat(hex >> 16 & 0xFF) / colorDivisor colorComponents[2] = CGFloat(hex >> 8 & 0xFF) / colorDivisor colorComponents[3] = CGFloat(hex & 0xFF) / colorDivisor return CGColor(colorSpace: colorSpace, components: colorComponents)! } static func hexColorToNSColor(_ hex: Int) -> NSColor { return NSColor(cgColor: hexColorToCGColor(hex))! } } struct Number { let val: Any init(_ val: Int) { self.val = val } init(_ val: CGFloat) { self.val = val } func int() -> Int { switch val { case let int as Int: return int case let float as CGFloat: return Int(float) default: fatalError() } } func float() -> CGFloat { switch val { case let int as Int: return CGFloat(int) case let float as CGFloat: return float default: fatalError() } } }
apache-2.0
c69ef708d398205af4aad1d8df90404b
25.424528
124
0.560157
4.369735
false
false
false
false
material-motion/material-motion-swift
src/operators/rubberBanded.swift
2
4008
/* Copyright 2016-present The Material Motion Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation import UIKit extension MotionObservableConvertible where T == CGFloat { /** Applies resistance to values that fall outside of the given range. */ public func rubberBanded(below: CGFloat, above: CGFloat, maxLength: CGFloat) -> MotionObservable<CGFloat> { return _map { return rubberBand(value: $0, min: below, max: above, bandLength: maxLength) } } } extension MotionObservableConvertible where T == CGPoint { /** Applies resistance to values that fall outside of the given range. Does not modify the value if CGRect is .null. */ public func rubberBanded(outsideOf rect: CGRect, maxLength: CGFloat) -> MotionObservable<CGPoint> { return _map { guard rect != .null else { return $0 } return CGPoint(x: rubberBand(value: $0.x, min: rect.minX, max: rect.maxX, bandLength: maxLength), y: rubberBand(value: $0.y, min: rect.minY, max: rect.maxY, bandLength: maxLength)) } } /** Applies resistance to values that fall outside of the given range. Does not modify the value if CGRect is .null. */ public func rubberBanded<O1, O2>(outsideOf rectStream: O1, maxLength maxLengthStream: O2) -> MotionObservable<CGPoint> where O1: MotionObservableConvertible, O1.T == CGRect, O2: MotionObservableConvertible, O2.T == CGFloat { var lastRect: CGRect? var lastMaxLength: CGFloat? var lastValue: CGPoint? return MotionObservable { observer in let checkAndEmit = { guard let rect = lastRect, let maxLength = lastMaxLength, let value = lastValue else { return } guard lastRect != .null else { observer.next(value) return } observer.next(CGPoint(x: rubberBand(value: value.x, min: rect.minX, max: rect.maxX, bandLength: maxLength), y: rubberBand(value: value.y, min: rect.minY, max: rect.maxY, bandLength: maxLength))) } let rectSubscription = rectStream.subscribeToValue { rect in lastRect = rect checkAndEmit() } let maxLengthSubscription = maxLengthStream.subscribeToValue { maxLength in lastMaxLength = maxLength checkAndEmit() } let upstreamSubscription = self.subscribeAndForward(to: observer) { value in lastValue = value checkAndEmit() } return { rectSubscription.unsubscribe() maxLengthSubscription.unsubscribe() upstreamSubscription.unsubscribe() } } } } private func rubberBand(value: CGFloat, min: CGFloat, max: CGFloat, bandLength: CGFloat) -> CGFloat { if value >= min && value <= max { // While we're within range we don't rubber band the value. return value } if bandLength <= 0 { // The rubber band doesn't exist, return the minimum value so that we stay put. return min } // 0.55 chosen as an approximation of iOS' rubber banding behavior. let rubberBandCoefficient: CGFloat = 0.55 // Accepts values from [0...+inf and ensures that f(x) < bandLength for all values. let band: (CGFloat) -> CGFloat = { value in let demoninator = value * rubberBandCoefficient / bandLength + 1 return bandLength * (1 - 1 / demoninator) } if (value > max) { return band(value - max) + max } else if (value < min) { return min - band(min - value) } return value }
apache-2.0
1f50c4ad5e0877b773dc97b120fbd77d
31.585366
226
0.673403
4.175
false
false
false
false
OneBusAway/onebusaway-iphone
Carthage/Checkouts/SwiftEntryKit/Carthage/Checkouts/QuickLayout/Example/QuickLayout/Samples/TableView/TableSampleViewController.swift
6
1986
// // TableSampleViewController.swift // QuickLayout_Example // // Created by Daniel Huri on 11/21/17. // Copyright (c) 2018 [email protected]. All rights reserved. // import UIKit import QuickLayout class TableSampleViewController: UIViewController { // MARK: Data Source private let dataSource = DataSource<Contact>() // MARK: UI Props private let tableView = UITableView() // MARK: Setup override func loadView() { super.loadView() view.backgroundColor = .white navigationItem.title = "Table View" setupDataSource() setupContentTableView() } private func setupDataSource() { dataSource.setup(from: .contacts) { self.tableView.reloadData() } } private func setupContentTableView() { tableView.delegate = self tableView.dataSource = self tableView.estimatedRowHeight = UITableView.automaticDimension view.addSubview(tableView) tableView.register(ContactTableViewCell.self, forCellReuseIdentifier: ContactTableViewCell.classType) tableView.layoutToSuperview(.left, .right, .bottom, .top) } } // MARK: UITableViewDelegate, UITableViewDataSource extension TableSampleViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat { return 80 } 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 { let cell = tableView.dequeueReusableCell(withIdentifier: ContactTableViewCell.classType, for: indexPath) as! ContactTableViewCell cell.contact = dataSource[indexPath.row] return cell } }
apache-2.0
1e09d526559e43d0b3b72a1598e06ecf
30.03125
137
0.686808
5.324397
false
false
false
false
pgorzelany/experimental-swift-server
Sources/App/Utils/OneDigitSegmentDisplay.swift
1
3940
// // OneDigitSegmentDisplay.swift // experimental-swift-server // // Created by Piotr Gorzelany on 01/05/2017. // // import Foundation import SwiftyGPIO class OneDigitSegmentDisplay { enum Digit: Int { case zero = 0 ,one, two ,three, four, five, six, seven, eight, nine } private enum Segment { case a,b,c,d,e,f,g } // MARK: Properties private let gpios: [GPIO] private let agpio: GPIO private let bgpio: GPIO private let cgpio: GPIO private let dgpio: GPIO private let egpio: GPIO private let fgpio: GPIO private let ggpio: GPIO // Lifecycle init(gpios: [GPIO]) { guard gpios.count == 7 else { fatalError("There should be 7 gpios for the one digit segment display") } self.gpios = gpios self.agpio = gpios[0] self.bgpio = gpios[1] self.cgpio = gpios[2] self.dgpio = gpios[3] self.egpio = gpios[4] self.fgpio = gpios[5] self.ggpio = gpios[6] self.gpios.forEach { (gpio) in gpio.direction = .OUT } } // MARK: Private methods private func switchSegment(_ segment: Segment, to value: Int) { switch segment { case .a: agpio.value = value case .b: bgpio.value = value case .c: cgpio.value = value case .d: dgpio.value = value case .e: egpio.value = value case .f: fgpio.value = value case .g: ggpio.value = value } } // MARK: Public methods func displayDigit(_ digit: Digit) { switchOff() switch digit { case .zero: switchSegment(.a, to: 1) switchSegment(.b, to: 1) switchSegment(.c, to: 1) switchSegment(.d, to: 1) switchSegment(.e, to: 1) switchSegment(.f, to: 1) case .one: switchSegment(.b, to: 1) switchSegment(.c, to: 1) case .two: switchSegment(.a, to: 1) switchSegment(.b, to: 1) switchSegment(.g, to: 1) switchSegment(.e, to: 1) switchSegment(.d, to: 1) case .three: switchSegment(.a, to: 1) switchSegment(.b, to: 1) switchSegment(.g, to: 1) switchSegment(.c, to: 1) switchSegment(.d, to: 1) case .four: switchSegment(.f, to: 1) switchSegment(.g, to: 1) switchSegment(.b, to: 1) switchSegment(.c, to: 1) case .five: switchSegment(.a, to: 1) switchSegment(.f, to: 1) switchSegment(.g, to: 1) switchSegment(.c, to: 1) switchSegment(.d, to: 1) case .six: switchSegment(.a, to: 1) switchSegment(.f, to: 1) switchSegment(.g, to: 1) switchSegment(.c, to: 1) switchSegment(.d, to: 1) switchSegment(.e, to: 1) case .seven: switchSegment(.a, to: 1) switchSegment(.b, to: 1) switchSegment(.c, to: 1) case .eight: switchSegment(.a, to: 1) switchSegment(.b, to: 1) switchSegment(.c, to: 1) switchSegment(.d, to: 1) switchSegment(.e, to: 1) switchSegment(.f, to: 1) switchSegment(.g, to: 1) case .nine: switchSegment(.a, to: 1) switchSegment(.b, to: 1) switchSegment(.c, to: 1) switchSegment(.d, to: 1) switchSegment(.f, to: 1) switchSegment(.g, to: 1) } } func switchOff() { print("Switch segment off called") self.gpios.forEach { (gpio) in gpio.value = 0 } } }
mit
e9676d7546452ef4d9c05b8a81c720cc
25.802721
83
0.486548
3.73814
false
false
false
false
P9SOFT/HJPhotoAlbumManager
Samples/Sample/Sample/AlbumListViewController.swift
1
9467
// // AlbumListViewController.swift // Sample // // Created by Tae Hyun Na on 2016. 2. 25. // Copyright (c) 2014, P9 SOFT, Inc. All rights reserved. // // Licensed under the MIT license. import UIKit class AlbumListViewController: UIViewController { private var createAlbumButton:UIButton = UIButton(type: .custom) private var editAlbumButton:UIButton = UIButton(type: .custom) private var albumTableView:UITableView = UITableView(frame: .zero) override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(self, selector: #selector(photoAlbumManagerReport(_:)), name: .P9PhotoAlbumManager, object: nil) automaticallyAdjustsScrollViewInsets = false; view.backgroundColor = UIColor.white createAlbumButton.setTitle("➕", for: .normal) createAlbumButton.addTarget(self, action: #selector(createAlbumButtonTouchUpInside(sender:)), for: .touchUpInside) createAlbumButton.isHidden = true editAlbumButton.setTitle("EDIT", for: .normal) editAlbumButton.setTitleColor(.black, for: .normal) editAlbumButton.titleLabel?.font = UIFont.boldSystemFont(ofSize: 12) editAlbumButton.addTarget(self, action: #selector(editAlbumButtonTouchUpInside(sender:)), for: .touchUpInside) albumTableView.register(UINib(nibName:"AlbumRecordTableViewCell", bundle:nil), forCellReuseIdentifier:"AlbumRecordTableViewCell") albumTableView.dataSource = self albumTableView.delegate = self albumTableView.backgroundColor = UIColor.clear view.addSubview(albumTableView) view.addSubview(createAlbumButton) view.addSubview(editAlbumButton) // request album list, and write code for result handling. // you can write code for result handling with response of notification handler 'photoAlbumManagerReport' as below. let cameraRoll = P9PhotoAlbumManager.AlbumInfo.init(type: .cameraRoll) let favorite = P9PhotoAlbumManager.AlbumInfo.init(type: .favorite) let recentlyAdded = P9PhotoAlbumManager.AlbumInfo.init(type: .recentlyAdded) let screenshots = P9PhotoAlbumManager.AlbumInfo.init(type: .screenshots) let videos = P9PhotoAlbumManager.AlbumInfo.init(type: .videos, mediaTypes: [.video], ascending: false) let regular = P9PhotoAlbumManager.AlbumInfo.init(type: .regular) let albumInfos = [cameraRoll, favorite, recentlyAdded, screenshots, videos, regular] if P9PhotoAlbumManager.shared.authorized == false { P9PhotoAlbumManager.shared.authorization { (operation, status) in if status == .succeed { P9PhotoAlbumManager.shared.requestAlbums(byInfos: albumInfos) { (operation, status) in self.albumTableView.reloadData() } } else { let alert = UIAlertController(title: "Need Authorization", message: "You need to move setting to give access authorization of photo for this app", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil)) self.present(alert, animated: true, completion: nil) } } return; } P9PhotoAlbumManager.shared.requestAlbums(byInfos: albumInfos) { (operation, status) in self.albumTableView.reloadData() } } deinit { NotificationCenter.default.removeObserver(self) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) albumTableView.reloadData() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() var frame:CGRect = .zero frame.size = CGSize(width: 30, height: 30) frame.origin.x = 20 frame.origin.y = UIApplication.shared.statusBarFrame.size.height + 5 createAlbumButton.frame = frame frame.size = CGSize(width: 40, height: 30) frame.origin.x = self.view.bounds.size.width - 20 - frame.size.width frame.origin.y = UIApplication.shared.statusBarFrame.size.height + 5 editAlbumButton.frame = frame frame = self.view.bounds frame.origin.y += (UIApplication.shared.statusBarFrame.size.height + 40) frame.size.height -= (UIApplication.shared.statusBarFrame.size.height + 40) albumTableView.frame = frame } @objc func photoAlbumManagerReport(_ notification:Notification) { // you can write code as below for result handling, but in this case, just print log. // because we already pass the code for result handler when requesting data at 'viewDidLoad'. if let userInfo = notification.userInfo, let operation = userInfo[P9PhotoAlbumManager.NotificationOperationKey] as? P9PhotoAlbumManager.Operation, let status = userInfo[P9PhotoAlbumManager.NotificationStatusKey] as? P9PhotoAlbumManager.Status { print("Operatoin[\(operation.rawValue)], Status[\(status.rawValue)]") if operation == .reload { albumTableView.reloadData() } } } @objc func createAlbumButtonTouchUpInside(sender:UIButton) { let alert = UIAlertController(title: "Create Album", message: "Enter album title to create", preferredStyle: .alert) alert.addTextField { (textField) in textField.placeholder = "Album Title" textField.textColor = .black } alert.addAction(UIAlertAction(title: "Create", style: .default, handler: { (action) in if let textField = alert.textFields?.first, let title = textField.text { P9PhotoAlbumManager.shared.createAlbum(title: title, mediaTypes: [.image], ascending: false, completion: { (operation, status) in self.albumTableView.reloadData() }) } })) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) present(alert, animated: true, completion: nil) } @objc func editAlbumButtonTouchUpInside(sender:UIButton) { if albumTableView.isEditing == false { createAlbumButton.isHidden = false albumTableView.setEditing(true, animated: true) editAlbumButton.setTitle("DONE", for: .normal) } else { createAlbumButton.isHidden = true albumTableView.setEditing(false, animated: true) editAlbumButton.setTitle("EDIT", for: .normal) } } } extension AlbumListViewController: UITableViewDataSource, UITableViewDelegate { func numberOfSections(in tableView:UITableView) -> Int { return 1 } func tableView(_ tableView:UITableView, numberOfRowsInSection section:Int) -> Int { return P9PhotoAlbumManager.shared.numberOfAlbums() } func tableView(_ tableView:UITableView, heightForRowAt indexPath:IndexPath) -> CGFloat { return 80 } func tableView(_ tableView:UITableView, cellForRowAt indexPath:IndexPath) -> UITableViewCell { if let cell = albumTableView.dequeueReusableCell(withIdentifier: "AlbumRecordTableViewCell") as? AlbumRecordTableViewCell { cell.coverImageView.image = P9PhotoAlbumManager.shared.imageOfMedia(forIndex: 0, atAlbumIndex: indexPath.row, targetSize: CGSize.init(width: 80, height: 80), contentMode: .aspectFill) cell.titleLabel.text = P9PhotoAlbumManager.shared.titleOfAlbum(forIndex: indexPath.row) cell.countLabel.text = "\(P9PhotoAlbumManager.shared.numberOfMediaAtAlbum(forIndex: indexPath.row))" return cell } return UITableViewCell() } func tableView(_ tableView:UITableView, didSelectRowAt indexPath:IndexPath) { tableView.deselectRow(at: indexPath, animated:true) let photoListViewController = PhotoListViewController() photoListViewController.albumIndex = indexPath.row navigationController?.pushViewController(photoListViewController, animated:true) } func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { if let type = P9PhotoAlbumManager.shared.predefineTypeOfAlbum(forIndex: indexPath.row), type == .regular { return true } return false } func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle { if let type = P9PhotoAlbumManager.shared.predefineTypeOfAlbum(forIndex: indexPath.row), type == .regular { return .delete } return .none } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { P9PhotoAlbumManager.shared.deleteAlbum(index: indexPath.row) { (operation, status) in self.albumTableView.reloadData() } } } }
mit
be2f612fb665861a0d58ccea3221fc49
42.219178
253
0.656947
4.984202
false
false
false
false
hhyyg/Miso.Gistan
GistanTests/APIClient/GitHub/GitHubClientTest.swift
1
1549
// // GitHubClientTest.swift // GistanTests // // Created by Hiroka Yago on 2017/10/01. // Copyright © 2017 miso. All rights reserved. // import XCTest @testable import Gistan class GitHubClientTest: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } /// API get Gists を実行し、何かしらのレスポンスが返っているか func testGetUsersGist() { var finished = false let userName = "hhyyg" let client = GitHubClient() let request = GitHubAPI.GetUsersGists(userName: userName) client.send(request: request) { result in switch result { case let .success(response): XCTAssertNotNil(response[0]) print(response[0].htmlUrl) case let .failure(error): print(error) XCTAssert(false) } finished = true } while !finished { RunLoop.current.run(mode: .defaultRunLoopMode, before: .distantFuture) } } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
mit
ec9e7b31e4439b24e89bee5dce6f0142
26.345455
111
0.585771
4.502994
false
true
false
false
roelspruit/RSMetronome
Sources/RSMetronome/Settings.swift
1
436
// // Settings.swift // // Created by Roel Spruit on 02/12/15. // Copyright © 2015 DinkyWonder. All rights reserved. // import Foundation public struct Settings { public var timeSignature = TimeSignature(beats: 4, noteValue: .Quarter) public var tempo = 100 public var tempoNote = NoteValue.Quarter public var pattern = Pattern.QuarterNotes public var audioEnabled = true public init() { } }
mit
fd59e74e2664b63ee53c6cdd4e7be4d2
20.75
75
0.678161
3.990826
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureCardPayment/Sources/FeatureCardPaymentDomain/Model/PartnerAuthorizationData.swift
1
2573
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Foundation public struct PartnerAuthorizationData: Equatable { public init(state: PartnerAuthorizationData.State, paymentMethodId: String) { self.state = state self.paymentMethodId = paymentMethodId } public static var exitLink = "https://www.blockchain.com/" /// Required authorization type public enum State: Equatable { public struct PaymentParams: Equatable { public let cardAcquirer: CardPayload.Acquirer public let clientSecret: String? public let publishableApiKey: String? public let paymentLink: URL? public let exitLink: URL public init( cardAcquirer: CardPayload.Acquirer, clientSecret: String? = nil, paymentLink: URL? = nil, publishableApiKey: String? = nil ) { self.cardAcquirer = cardAcquirer self.paymentLink = paymentLink self.clientSecret = clientSecret self.publishableApiKey = publishableApiKey exitLink = URL(string: PartnerAuthorizationData.exitLink)! } } /// Requires user user authorization by visiting the associated link case required(PaymentParams) /// Confirmed authorization case confirmed /// Authorized to proceed - no auth required case none public var isRequired: Bool { switch self { case .required: return true case .confirmed, .none: return false } } public var isConfirmed: Bool { switch self { case .confirmed: return true case .required, .none: return false } } } /// The type of required authorization public let state: State /// The payment method id that needs to be authorized public let paymentMethodId: String } public protocol OrderPayloadResponseAPI { var paymentMethodId: String? { get } var authorizationState: PartnerAuthorizationData.State { get } } extension PartnerAuthorizationData { public init?(orderPayloadResponse: OrderPayloadResponseAPI) { guard let paymentMethodId = orderPayloadResponse.paymentMethodId else { return nil } self.paymentMethodId = paymentMethodId state = orderPayloadResponse.authorizationState } }
lgpl-3.0
e4380211e760c186ed8d00592a16b334
29.619048
81
0.606532
5.555076
false
false
false
false
enpitut/SAWARITAI
iOS/Pods/BubbleTransition/Source/BubbleTransition.swift
1
5938
// // BubbleTransition.swift // BubbleTransition // // Created by Andrea Mazzini on 04/04/15. // Copyright (c) 2015 Fancy Pixel. All rights reserved. // import UIKit /** A custom modal transition that presents and dismiss a controller with an expanding bubble effect. */ public class BubbleTransition: NSObject, UIViewControllerAnimatedTransitioning { /** The point that originates the bubble. */ public var startingPoint = CGPointZero { didSet { if let bubble = bubble { bubble.center = startingPoint } } } /** The transition duration. */ public var duration = 0.5 /** The transition direction. Either `.Present` or `.Dismiss.` */ public var transitionMode: BubbleTransitionMode = .Present /** The color of the bubble. Make sure that it matches the destination controller's background color. */ public var bubbleColor: UIColor = .whiteColor() private var bubble: UIView? // MARK: - UIViewControllerAnimatedTransitioning /** Required by UIViewControllerAnimatedTransitioning */ public func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return duration } /** Required by UIViewControllerAnimatedTransitioning */ public func animateTransition(transitionContext: UIViewControllerContextTransitioning) { let containerView = transitionContext.containerView() if transitionMode == .Present { let presentedControllerView = transitionContext.viewForKey(UITransitionContextToViewKey)! let originalCenter = presentedControllerView.center let originalSize = presentedControllerView.frame.size bubble = UIView(frame: frameForBubble(originalCenter, size: originalSize, start: startingPoint)) bubble!.layer.cornerRadius = bubble!.frame.size.height / 2 bubble!.center = startingPoint bubble!.transform = CGAffineTransformMakeScale(0.001, 0.001) bubble!.backgroundColor = bubbleColor containerView!.addSubview(bubble!) presentedControllerView.center = startingPoint presentedControllerView.transform = CGAffineTransformMakeScale(0.001, 0.001) presentedControllerView.alpha = 0 containerView!.addSubview(presentedControllerView) UIView.animateWithDuration(duration, animations: { self.bubble!.transform = CGAffineTransformIdentity presentedControllerView.transform = CGAffineTransformIdentity presentedControllerView.alpha = 1 presentedControllerView.center = originalCenter }) { (_) -> Void in transitionContext.completeTransition(true) } } else if transitionMode == .Pop { let returningControllerView = transitionContext.viewForKey(UITransitionContextToViewKey)! let originalCenter = returningControllerView.center let originalSize = returningControllerView.frame.size bubble!.frame = frameForBubble(originalCenter, size: originalSize, start: startingPoint) bubble!.layer.cornerRadius = bubble!.frame.size.height / 2 bubble!.center = startingPoint UIView.animateWithDuration(duration, animations: { self.bubble!.transform = CGAffineTransformMakeScale(0.001, 0.001) returningControllerView.transform = CGAffineTransformMakeScale(0.001, 0.001) returningControllerView.center = self.startingPoint returningControllerView.alpha = 0 containerView!.insertSubview(returningControllerView, belowSubview: returningControllerView) containerView!.insertSubview(self.bubble!, belowSubview: returningControllerView) }) { (_) -> Void in returningControllerView.removeFromSuperview() self.bubble!.removeFromSuperview() transitionContext.completeTransition(true) } } else { let returningControllerView = transitionContext.viewForKey(UITransitionContextFromViewKey)! let originalCenter = returningControllerView.center let originalSize = returningControllerView.frame.size bubble!.frame = frameForBubble(originalCenter, size: originalSize, start: startingPoint) bubble!.layer.cornerRadius = bubble!.frame.size.height / 2 bubble!.center = startingPoint UIView.animateWithDuration(duration, animations: { self.bubble!.transform = CGAffineTransformMakeScale(0.001, 0.001) returningControllerView.transform = CGAffineTransformMakeScale(0.001, 0.001) returningControllerView.center = self.startingPoint returningControllerView.alpha = 0 }) { (_) -> Void in returningControllerView.removeFromSuperview() self.bubble!.removeFromSuperview() transitionContext.completeTransition(true) } } } /** The possible directions of the transition */ @objc public enum BubbleTransitionMode: Int { case Present, Dismiss, Pop } } private extension BubbleTransition { private func frameForBubble(originalCenter: CGPoint, size originalSize: CGSize, start: CGPoint) -> CGRect { let lengthX = fmax(start.x, originalSize.width - start.x); let lengthY = fmax(start.y, originalSize.height - start.y) let offset = sqrt(lengthX * lengthX + lengthY * lengthY) * 2; let size = CGSize(width: offset, height: offset) return CGRect(origin: CGPointZero, size: size) } }
gpl-2.0
f95a77a06e8a23e1d5f7eb267b2a31c3
39.951724
112
0.651061
6.084016
false
false
false
false
michaello/Aloha
AlohaGIF/SwiftyOnboard/SwiftyOnboardPage.swift
1
1230
// // customPageView.swift // SwiftyOnboard // // Created by Jay on 3/25/17. // Copyright © 2017 Juan Pablo Fernandez. All rights reserved. // import UIKit open class SwiftyOnboardPage: UIView { public var title: UILabel = { let label = UILabel() label.text = "Title" label.textAlignment = .center label.numberOfLines = 0 label.lineBreakMode = NSLineBreakMode.byWordWrapping label.sizeToFit() return label }() public var subTitle: UILabel = { let label = UILabel() label.text = "Sub Title" label.textAlignment = .center label.numberOfLines = 0 label.lineBreakMode = NSLineBreakMode.byWordWrapping label.sizeToFit() return label }() public var imageView: UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFit return imageView }() func set(style: SwiftyOnboardStyle) { switch style { case .light: title.textColor = .white subTitle.textColor = .white case .dark: title.textColor = .black subTitle.textColor = .black } } }
mit
e07db0a2f78bf88f04c6d148891b48b2
24.081633
63
0.585028
4.896414
false
false
false
false
coach-plus/ios
Pods/YPImagePicker/Source/Pages/Gallery/YPLibraryVC+CollectionView.swift
1
10564
// // YPLibraryVC+CollectionView.swift // YPImagePicker // // Created by Sacha DSO on 26/01/2018. // Copyright © 2018 Yummypets. All rights reserved. // import UIKit extension YPLibraryVC { var isLimitExceeded: Bool { return selection.count >= YPConfig.library.maxNumberOfItems } func setupCollectionView() { v.collectionView.backgroundColor = YPConfig.colors.libraryScreenBackgroundColor v.collectionView.dataSource = self v.collectionView.delegate = self v.collectionView.register(YPLibraryViewCell.self, forCellWithReuseIdentifier: "YPLibraryViewCell") // Long press on cell to enable multiple selection let longPressGR = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress(longPressGR:))) longPressGR.minimumPressDuration = 0.5 v.collectionView.addGestureRecognizer(longPressGR) } /// When tapping on the cell with long press, clear all previously selected cells. @objc func handleLongPress(longPressGR: UILongPressGestureRecognizer) { if multipleSelectionEnabled || isProcessing || YPConfig.library.maxNumberOfItems <= 1 { return } if longPressGR.state == .began { let point = longPressGR.location(in: v.collectionView) guard let indexPath = v.collectionView.indexPathForItem(at: point) else { return } startMultipleSelection(at: indexPath) } } func startMultipleSelection(at indexPath: IndexPath) { currentlySelectedIndex = indexPath.row multipleSelectionButtonTapped() // Update preview. changeAsset(mediaManager.fetchResult[indexPath.row]) // Bring preview down and keep selected cell visible. panGestureHelper.resetToOriginalState() if !panGestureHelper.isImageShown { v.collectionView.scrollToItem(at: indexPath, at: .top, animated: true) } v.refreshImageCurtainAlpha() } // MARK: - Library collection view cell managing /// Removes cell from selection func deselect(indexPath: IndexPath) { if let positionIndex = selection.firstIndex(where: { $0.assetIdentifier == mediaManager.fetchResult[indexPath.row].localIdentifier }) { selection.remove(at: positionIndex) // Refresh the numbers var selectedIndexPaths = [IndexPath]() mediaManager.fetchResult.enumerateObjects { [unowned self] (asset, index, _) in if self.selection.contains(where: { $0.assetIdentifier == asset.localIdentifier }) { selectedIndexPaths.append(IndexPath(row: index, section: 0)) } } v.collectionView.reloadItems(at: selectedIndexPaths) // Replace the current selected image with the previously selected one if let previouslySelectedIndexPath = selectedIndexPaths.last { v.collectionView.deselectItem(at: indexPath, animated: false) v.collectionView.selectItem(at: previouslySelectedIndexPath, animated: false, scrollPosition: []) currentlySelectedIndex = previouslySelectedIndexPath.row changeAsset(mediaManager.fetchResult[previouslySelectedIndexPath.row]) } checkLimit() } } /// Adds cell to selection func addToSelection(indexPath: IndexPath) { let asset = mediaManager.fetchResult[indexPath.item] selection.append( YPLibrarySelection( index: indexPath.row, assetIdentifier: asset.localIdentifier ) ) checkLimit() } func isInSelectionPool(indexPath: IndexPath) -> Bool { return selection.contains(where: { $0.assetIdentifier == mediaManager.fetchResult[indexPath.row].localIdentifier }) } /// Checks if there can be selected more items. If no - present warning. func checkLimit() { v.maxNumberWarningView.isHidden = !isLimitExceeded || multipleSelectionEnabled == false } } extension YPLibraryVC: UICollectionViewDataSource { public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return mediaManager.fetchResult.count } } extension YPLibraryVC: UICollectionViewDelegate { public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let asset = mediaManager.fetchResult[indexPath.item] guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "YPLibraryViewCell", for: indexPath) as? YPLibraryViewCell else { fatalError("unexpected cell in collection view") } cell.representedAssetIdentifier = asset.localIdentifier cell.multipleSelectionIndicator.selectionColor = YPConfig.colors.multipleItemsSelectedCircleColor ?? YPConfig.colors.tintColor mediaManager.imageManager?.requestImage(for: asset, targetSize: v.cellSize(), contentMode: .aspectFill, options: nil) { image, _ in // The cell may have been recycled when the time this gets called // set image only if it's still showing the same asset. if cell.representedAssetIdentifier == asset.localIdentifier && image != nil { cell.imageView.image = image } } let isVideo = (asset.mediaType == .video) cell.durationLabel.isHidden = !isVideo cell.durationLabel.text = isVideo ? YPHelper.formattedStrigFrom(asset.duration) : "" cell.multipleSelectionIndicator.isHidden = !multipleSelectionEnabled cell.isSelected = currentlySelectedIndex == indexPath.row // Set correct selection number if let index = selection.firstIndex(where: { $0.assetIdentifier == asset.localIdentifier }) { let currentSelection = selection[index] if currentSelection.index < 0 { selection[index] = YPLibrarySelection(index: indexPath.row, cropRect: currentSelection.cropRect, scrollViewContentOffset: currentSelection.scrollViewContentOffset, scrollViewZoomScale: currentSelection.scrollViewZoomScale, assetIdentifier: currentSelection.assetIdentifier) } cell.multipleSelectionIndicator.set(number: index + 1) // start at 1, not 0 } else { cell.multipleSelectionIndicator.set(number: nil) } // Prevent weird animation where thumbnail fills cell on first scrolls. UIView.performWithoutAnimation { cell.layoutIfNeeded() } return cell } public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let previouslySelectedIndexPath = IndexPath(row: currentlySelectedIndex, section: 0) currentlySelectedIndex = indexPath.row changeAsset(mediaManager.fetchResult[indexPath.row]) panGestureHelper.resetToOriginalState() // Only scroll cell to top if preview is hidden. if !panGestureHelper.isImageShown { collectionView.scrollToItem(at: indexPath, at: .top, animated: true) } v.refreshImageCurtainAlpha() if multipleSelectionEnabled { let cellIsInTheSelectionPool = isInSelectionPool(indexPath: indexPath) let cellIsCurrentlySelected = previouslySelectedIndexPath.row == currentlySelectedIndex if cellIsInTheSelectionPool { if cellIsCurrentlySelected { deselect(indexPath: indexPath) } } else if isLimitExceeded == false { addToSelection(indexPath: indexPath) } collectionView.reloadItems(at: [indexPath]) collectionView.reloadItems(at: [previouslySelectedIndexPath]) } else { selection.removeAll() addToSelection(indexPath: indexPath) // Force deseletion of previously selected cell. // In the case where the previous cell was loaded from iCloud, a new image was fetched // which triggered photoLibraryDidChange() and reloadItems() which breaks selection. // if let previousCell = collectionView.cellForItem(at: previouslySelectedIndexPath) as? YPLibraryViewCell { previousCell.isSelected = false } } } public func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool { return isProcessing == false } public func collectionView(_ collectionView: UICollectionView, shouldDeselectItemAt indexPath: IndexPath) -> Bool { return isProcessing == false } } extension YPLibraryVC: UICollectionViewDelegateFlowLayout { public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let margins = YPConfig.library.spacingBetweenItems * CGFloat(YPConfig.library.numberOfItemsInRow - 1) let width = (collectionView.frame.width - margins) / CGFloat(YPConfig.library.numberOfItemsInRow) return CGSize(width: width, height: width) } public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return YPConfig.library.spacingBetweenItems } public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return YPConfig.library.spacingBetweenItems } }
mit
22364412fa6f7105ddf583c6e5ad0a42
45.328947
182
0.634005
5.93427
false
false
false
false
srosskopf/Geschmacksbildung
Geschmacksbildung/Geschmacksbildung/Ex3Controller.swift
1
7056
// // Ex3Controller.swift // Geschmacksbildung // // Created by Sebastian Roßkopf on 18.06.16. // Copyright © 2016 sebastian rosskopf. All rights reserved. // import UIKit class Ex3Controller: UIViewController { @IBOutlet var contentView: UIView! @IBOutlet var letsStartButton: UIButton! @IBOutlet var scrollView: UIScrollView! @IBOutlet var fullRoomImage: UIImageView! @IBOutlet var timerLabel: UILabel! @IBOutlet var key1Button: UIButton! @IBOutlet var key2Button: UIButton! @IBOutlet var nextButton: UIButton! @IBOutlet var keyImage: UIImageView! @IBOutlet var room1TimeLabel: UILabel! @IBOutlet var room2TimeLabel: UILabel! @IBOutlet var introTextView: UITextView! @IBOutlet var textView: UITextView! var timer: NSTimer? var time: Int = 1 var room1Finished: Bool = false var room2Finished: Bool = false override func viewDidLoad() { super.viewDidLoad() let path = NSBundle.mainBundle().pathForResource("04_Structure", ofType: "rtf") let textURL = NSURL.fileURLWithPath(path!) let options = [NSDocumentTypeDocumentAttribute: NSRTFTextDocumentType] let attribText = try! NSAttributedString(URL: textURL, options: options, documentAttributes: nil) introTextView.attributedText = attribText let _path = NSBundle.mainBundle().pathForResource("04_Structure_Explanation", ofType: "rtf") let _textURL = NSURL.fileURLWithPath(_path!) let _attribText = try! NSAttributedString(URL: _textURL, options: options, documentAttributes: nil) textView.attributedText = _attribText self.textView.scrollRangeToVisible(NSMakeRange(0, 0)) self.introTextView.scrollRangeToVisible(NSMakeRange(0, 0)) nextButton.alpha = 0 key2Button.hidden = true keyImage.alpha = 0 // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func resetStuff() { fullRoomImage.image = UIImage(named: "Room_FULL-1-NEW-2") fullRoomImage.alpha = 1 keyImage.alpha = 0 keyImage.image = UIImage(named: "KEYS-ROOM-1") key1Button.hidden = false key2Button.hidden = true nextButton.alpha = 0 room1Finished = false room2Finished = false time = 1 timerLabel.text = "0 sec." if let timer = timer { timer.invalidate() } } @IBAction func startButtonTapped(sender: UIButton) { scrollView.setContentOffset(CGPoint(x: self.scrollView.frame.size.width ,y: 0), animated: true) timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(Ex3Controller.updateTimerLabel), userInfo: nil, repeats: true) } func updateTimerLabel() { timerLabel.text = "\(time) sec." time += 1 } @IBAction func key1ButtonTapped(sender: UIButton) { print("key in full room found!") if let timer = timer { timer.invalidate() } saveTime(time-1, room: "room1") room1Finished = true UIView.animateWithDuration(0.5, delay: 0, options: .CurveEaseInOut, animations: { self.fullRoomImage.alpha = 0 self.nextButton.alpha = 1 self.keyImage.alpha = 1 }) { (finished) in print("room1 not visible anymore") self.key1Button.hidden = true } } @IBAction func key2ButtonTapped(sender: UIButton) { print("key in empty room found!") if let timer = timer { timer.invalidate() } saveTime(time-1, room: "room2") room2Finished = true keyImage.image = UIImage(named: "KEYS-ROOM-2") UIView.animateWithDuration(0.5, delay: 0, options: .CurveEaseInOut, animations: { self.fullRoomImage.alpha = 0 self.nextButton.alpha = 1 self.keyImage.alpha = 1 }) { (finished) in print("room2 not visible anymore") self.key2Button.hidden = true } } func saveTime(time: Int, room: String) { NSUserDefaults.standardUserDefaults().setInteger(time, forKey: room) NSUserDefaults.standardUserDefaults().synchronize() } func getTimeForRoom(room: String) -> Int { let time = NSUserDefaults.standardUserDefaults().integerForKey(room) return time } @IBAction func nextButtonTapped(sender: UIButton) { if room2Finished { print("go to results") NSUserDefaults.standardUserDefaults().setBool(true, forKey: "exercise3Finished") room1TimeLabel.text = "Room 1 took you: \(getTimeForRoom("room1")) sec" room2TimeLabel.text = "Room 2 took you: \(getTimeForRoom("room2")) sec" scrollView.setContentOffset(CGPoint(x: 2 * scrollView.frame.size.width, y: 0), animated: true) } else { timerLabel.text = "0 sec." time = 1 timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(Ex3Controller.updateTimerLabel), userInfo: nil, repeats: true) key2Button.hidden = false key1Button.hidden = true fullRoomImage.image = UIImage(named: "ROOM_EMPTY-1-NEW") UIView.animateWithDuration(0.5, delay: 0, options: .CurveEaseInOut, animations: { self.fullRoomImage.alpha = 1 self.nextButton.alpha = 0 self.keyImage.alpha = 0 }) { (finished) in print("room 2 now visible") } } } @IBAction func mainButtonTapped(sender: UIButton) { NSNotificationCenter.defaultCenter().postNotificationName("menuButtonTapped", object: sender) } /* // 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. } */ }
mit
956579767bf6a79b638c8db420d6988b
27.103586
158
0.567196
5.04578
false
false
false
false
Antondomashnev/Sourcery
SourceryTests/Stub/Performance-Code/Kiosk/Bid Fulfillment/ConfirmYourBidEnterYourEmailViewController.swift
2
2887
import UIKit import RxSwift import RxCocoa import Action class ConfirmYourBidEnterYourEmailViewController: UIViewController { @IBOutlet var emailTextField: UITextField! @IBOutlet var confirmButton: UIButton! @IBOutlet var bidDetailsPreviewView: BidDetailsPreviewView! class func instantiateFromStoryboard(_ storyboard: UIStoryboard) -> ConfirmYourBidEnterYourEmailViewController { return storyboard.viewController(withID: .ConfirmYourBidEnterEmail) as! ConfirmYourBidEnterYourEmailViewController } var provider: Networking! override func viewDidLoad() { super.viewDidLoad() let emailText = emailTextField.rx.textInput.text.asObservable().replaceNil(with: "") let inputIsEmail = emailText.map(stringIsEmailAddress) let action = CocoaAction(enabledIf: inputIsEmail) { [weak self] _ in guard let me = self else { return .empty() } let endpoint: ArtsyAPI = ArtsyAPI.findExistingEmailRegistration(email: me.emailTextField.text ?? "") return self?.provider.request(endpoint) .filterStatusCode(200) .doOnNext { _ in me.performSegue(.ExistingArtsyUserFound) } .doOnError { error in self?.performSegue(.EmailNotFoundonArtsy) } .map(void) ?? .empty() } confirmButton.rx.action = action let unbind = action.executing.ignore(value: false) let nav = self.fulfillmentNav() bidDetailsPreviewView.bidDetails = nav.bidDetails emailText .asObservable() .mapToOptional() .takeUntil(unbind) .bindTo(nav.bidDetails.newUser.email) .addDisposableTo(rx_disposeBag) emailTextField.rx_returnKey.subscribe(onNext: { _ in action.execute() }).addDisposableTo(rx_disposeBag) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.emailTextField.becomeFirstResponder() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { super.prepare(for: segue, sender: sender) if segue == .EmailNotFoundonArtsy { let viewController = segue.destination as! RegisterViewController viewController.provider = provider } else if segue == .ExistingArtsyUserFound { let viewController = segue.destination as! ConfirmYourBidArtsyLoginViewController viewController.provider = provider } } } private extension ConfirmYourBidEnterYourEmailViewController { @IBAction func dev_emailFound(_ sender: AnyObject) { performSegue(.ExistingArtsyUserFound) } @IBAction func dev_emailNotFound(_ sender: AnyObject) { performSegue(.EmailNotFoundonArtsy) } }
mit
72f5713f04f9bf6f66ee34102c38a35b
31.077778
122
0.658469
5.478178
false
false
false
false
fespinoza/linked-ideas-osx
LinkedIdeas/Utilities/2DMath/NSView+Debugging.swift
1
1679
// // NSView+Debugging.swift // LinkedIdeas // // Created by Felipe Espinoza Castillo on 04/12/15. // Copyright © 2015 Felipe Espinoza Dev. All rights reserved. // import Cocoa extension NSView { var area: CGFloat { return 8 } func debugDrawing() { drawBorderForRect(bounds) drawCenteredDotAtPoint(bounds.center) } func drawDotAtPoint(_ point: CGPoint) { NSColor.red.set() var x: CGFloat = point.x var y: CGFloat = point.y if x >= bounds.maxX { x = bounds.maxX - area } if y >= bounds.maxY { y = bounds.maxY - area } let rect = CGRect( origin: CGPoint(x: x, y: y), size: CGSize(width: area, height: area) ) NSBezierPath(ovalIn: rect).fill() } func drawCenteredDotAtPoint(_ point: CGPoint, color: NSColor = NSColor.yellow) { color.set() var x: CGFloat = point.x - area / 2 var y: CGFloat = point.y - area / 2 if x >= bounds.maxX { x = bounds.maxX - area / 2 } if y >= bounds.maxY { y = bounds.maxY - area / 2 } let rect = CGRect( origin: CGPoint(x: x, y: y), size: CGSize(width: area, height: area) ) NSBezierPath(ovalIn: rect).fill() } func drawBorderForRect(_ rect: CGRect) { NSColor.blue.set() let border = NSBezierPath() border.move(to: rect.bottomLeftPoint) border.line(to: rect.bottomRightPoint) border.line(to: rect.topRightPoint) border.line(to: rect.topLeftPoint) border.line(to: rect.bottomLeftPoint) border.stroke() } func drawFullRect(_ rect: CGRect) { rect.fill() drawBorderForRect(rect) drawCenteredDotAtPoint(rect.origin, color: NSColor.red) drawCenteredDotAtPoint(rect.center) } }
mit
71ec808c9ca9faaf4e5d69e06b5ffd65
24.044776
82
0.64124
3.459794
false
false
false
false
luinily/hOme
hOme/Model/CommandTime.swift
1
1381
// // CommandTime.swift // hOme // // Created by Coldefy Yoann on 2016/05/16. // Copyright © 2016年 YoannColdefy. All rights reserved. // import Foundation enum CommandTimeError: Error { case stringFormatInvalid } struct CommandTime { //add an init to be able to init with values //add set from string private var _hours: Int = 0 var hours: Int { get {return _hours} set { _hours = ensureRange(value: newValue, min: 0, max: 23) } } private var _minutes: Int = 0 var minutes: Int { get {return _minutes} set { _minutes = ensureRange(value: newValue, min: 0, max: 59) } } var time: String { get { var hours = String(_hours) if hours.characters.count == 1 { hours = "0" + hours } var minutes = String(_minutes) if minutes.characters.count == 1 { minutes = "0" + minutes } return hours + ":" + minutes } set { if let separationIndex = newValue.characters.index(of: ":") { let nextCharIndex = newValue.index(after: separationIndex) let hoursString = newValue.substring(to: separationIndex) if let newHours = Int(hoursString) { hours = newHours } let minutesString = newValue.substring(from: nextCharIndex) if let newMinutes = Int(minutesString) { minutes = newMinutes } } else { // throw CommandTimeError.StringFormatInvalid } } } }
mit
fb59453dbf12b2a8a3719b59394b9693
18.971014
64
0.637881
3.227166
false
false
false
false
bitboylabs/selluv-ios
selluv-ios/Pods/FacebookShare/Sources/Share/Content/OpenGraph/OpenGraphAction.swift
13
3263
// Copyright (c) 2016-present, Facebook, Inc. All rights reserved. // // You are hereby granted a non-exclusive, worldwide, royalty-free license to use, // copy, modify, and distribute this software in source code or binary form for use // in connection with the web services and APIs provided by Facebook. // // As with any software that integrates with the Facebook platform, your use of // this software is subject to the Facebook Developer Principles and Policies // [http://developers.facebook.com/policy/]. This copyright 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 FBSDKShareKit @testable import FacebookCore /** An Open Graph action for sharing. */ public struct OpenGraphAction { // TODO (richardross): Make ActionType an enum with common action types. /// The action type. public var type: String fileprivate var properties: [OpenGraphPropertyName : OpenGraphPropertyValue] /** Create an `OpenGraphAction` with a specific action type. - parameter type: The type of the action. */ public init(type: String) { self.type = type self.properties = [:] } } extension OpenGraphAction: OpenGraphPropertyContaining { /// Get the property names contained in this container. public var propertyNames: Set<OpenGraphPropertyName> { return Set(properties.keys) } public subscript(key: OpenGraphPropertyName) -> OpenGraphPropertyValue? { get { return properties[key] } set { properties[key] = newValue } } } extension OpenGraphAction { internal var sdkActionRepresentation: FBSDKShareOpenGraphAction { let sdkAction = FBSDKShareOpenGraphAction() sdkAction.actionType = type sdkAction.parseProperties(properties.keyValueMap { key, value in (key.rawValue, value.openGraphPropertyValue) }) return sdkAction } internal init(sdkAction: FBSDKShareOpenGraphAction) { self.type = sdkAction.actionType var properties = [OpenGraphPropertyName : OpenGraphPropertyValue]() sdkAction.enumerateKeysAndObjects { (key: String?, value: Any?, stop) in guard let key = key.map(OpenGraphPropertyName.init(rawValue:)), let value = value.map(OpenGraphPropertyValueConverter.valueFrom) else { return } properties[key] = value } self.properties = properties } } extension OpenGraphAction: Equatable { /** Compare two `OpenGraphAction`s for equality. - parameter lhs: The first action to compare. - parameter rhs: The second action to compare. - returns: Whether or not the actions are equal. */ public static func == (lhs: OpenGraphAction, rhs: OpenGraphAction) -> Bool { return lhs.sdkActionRepresentation == rhs.sdkActionRepresentation } }
mit
adc89d936aedb8a38afd0cab57adf78f
32.295918
83
0.732455
4.506906
false
false
false
false
Shivol/Swift-CS333
playgrounds/swift/SwiftClasses.playground/Pages/Protocols.xcplaygroundpage/Contents.swift
2
2174
//: ## Protocols //: [Table of Contents](TableOfContents) · [Previous](@previous) · [Next](@next) //: **** //: ### Protocol Requrements protocol Printable { func printMe() } //: ### Conforming to a Protocol struct Student: Printable { let name: String var course: UInt8 let group: UInt8 func printMe() { print("\(name) \(course).\(group)") } } let john = Student(name: "John Smith", course: 1, group: 9) //: ### Protocol Adoption protocol Person { var name: String { get } } extension Student: Person {} // already has a name //: ### Protocol Inheritace import Foundation protocol RealPerson: Person { var birthDate: Date { get } } class Citizen: RealPerson { let name: String let birthDate: Date let country: String init(name: String, birthDate: Date, country: String){ self.name = name self.birthDate = birthDate self.country = country } } let formatter = DateFormatter() // Date ⇆ String formatter.dateFormat = "dd.MM.yyyy" let anna = Citizen(name: "Anna Smith", birthDate: formatter.date(from: "01.01.1997")!, country: "Sweden") //: ### Protocol as a Type var people = [Person]() people.append(john) people.append(anna) //: ### Checking for Conformance for person in people { if person is Printable { print("\(person.name) is printable:", separator: "", terminator: " ") (person as! Printable).printMe() } if let realPerson = person as? RealPerson { print("\(realPerson.name) \(formatter.string(from: realPerson.birthDate))") } else { print("\(person.name) is not a RealPerson") } } //: ### Associated Types protocol Stack { associatedtype Element mutating func push(value: Element) mutating func pop() -> Element? } struct StackOfInt: Stack { var items = [Int]() mutating func push(value: Int) { items.append(value) } mutating func pop() -> Int? { if let value = items.last { items.removeLast() return value } return nil } } //: **** //: [Table of Contents](TableOfContents) · [Previous](@previous) · [Next](@next)
mit
28ce00360e70fca24a0261f2eece329a
24.809524
105
0.613469
3.948998
false
false
false
false
imobilize/Molib
Molib/Classes/Categories/UIViewController+Helpers.swift
1
3724
import Foundation import UIKit public enum UIViewControllerTransition { case FlowFromRight case PushToBack } extension UIStoryboard { public class func controllerWithIdentifier(identifier: String) -> AnyObject { let storyBoard = UIStoryboard(name: "Main", bundle: nil) return storyBoard.instantiateViewController(withIdentifier: identifier) } } extension UIViewController { public var navController: UINavigationController { get { return self.navigationController! } } public func setRightButtonItem(item: UIBarButtonItem?) { self.navigationItem.rightBarButtonItem = item } public func setLeftButtonItem(item: UIBarButtonItem?) { self.navigationItem.leftBarButtonItem = item } public func pushViewController(viewController: UIViewController) { if self is UINavigationController { let controller = self as! UINavigationController controller.pushViewController(viewController, animated: true) } else { self.navController.pushViewController(viewController, animated: true) } } public func insertViewController(controller: UIViewController, belowViewController: UIViewController, withTransition: UIViewControllerTransition, duration: TimeInterval) { } public func presentViewControllerNonAnimated(viewController: UIViewController) { present(viewController, animated: false, completion: nil) } public func presentViewController(viewController: UIViewController) { present(viewController, animated: true, completion: nil) } public func dismissViewController() { self.dismiss(animated: true, completion: nil) } public func addViewController(viewController: UIViewController, inView:UIView) { addViewController(viewController: viewController, inView: inView, underView:nil, parentController:self) } public func addViewController(viewController: UIViewController, inView:UIView, fromController:UIViewController) { addViewController(viewController: viewController, inView: inView, underView: nil, parentController: fromController) } public func removeViewController(viewController: UIViewController) { viewController.willMove(toParentViewController: nil) viewController.view.removeFromSuperview() viewController.removeFromParentViewController() } public func addViewController(viewController: UIViewController, inView:UIView, underView:UIView?, parentController:UIViewController) { viewController.willMove(toParentViewController: parentController) parentController.addChildViewController(viewController) if let topView = underView { inView.insertSubview(viewController.view, belowSubview:topView) } else { inView.addSubview(viewController.view) } let myView = viewController.view myView?.translatesAutoresizingMaskIntoConstraints = false myView?.pinToSuperview([.top, .bottom, .left, .right]) inView.sizeToFit() viewController.didMove(toParentViewController: parentController) } public func applicationRootViewController() -> UIViewController { let window: UIWindow = UIApplication.shared.windows[0] return window.rootViewController! } }
apache-2.0
2e2aaa729ee9e015885ace405e99f1d6
27.212121
175
0.660311
6.661896
false
false
false
false
tbaranes/SwiftyUtils
Sources/Extensions/Foundation/NSRange/NSRangeExtension.swift
1
1344
// // Created by Tom Baranes on 24/04/16. // Copyright © 2016 Tom Baranes. All rights reserved. // import Foundation extension NSRange { /// Finds and returns the range of the first occurrence of a given string within the string. /// - Parameters: /// - text: The text where the `textToFind` will be searched. /// - occurence: The text will be searched after this specified text. /// - Returns: The range corresponding to `textToFind` in `text`. /// If the text has not been found then it will returns `NSNotFound`. public init(text: String, afterOccurence occurence: String) { self = (text as NSString).range(of: occurence, options: []) if location != NSNotFound { location += 1 length = text.count - location } } /// Finds and returns the range of the first occurrence of a given string within the string. /// - Parameters: /// - textToFind: The text to search for. /// - text: The text where the `textToFind` will be searched. /// - Returns: The range corresponding to `textToFind` in `text`. /// If the text has not been found then it will returns `NSNotFound`. public init(textToFind: String, in text: String) { self = (text as NSString).range(of: textToFind, options: []) } }
mit
9ba4d5e5d2c1e095f98b203c739ca8ba
38.5
96
0.629188
4.290735
false
false
false
false
open-telemetry/opentelemetry-swift
Sources/Exporters/DatadogExporter/Utils/JSONEncoder.swift
1
635
/* * Copyright The OpenTelemetry Authors * SPDX-License-Identifier: Apache-2.0 */ import Foundation extension JSONEncoder { static func `default`() -> JSONEncoder { let encoder = JSONEncoder() encoder.dateEncodingStrategy = .custom { date, encoder in var container = encoder.singleValueContainer() let formatted = iso8601DateFormatter.string(from: date) try container.encode(formatted) } if #available(iOS 13.0, OSX 10.15, watchOS 6.0, tvOS 13.0, *) { encoder.outputFormatting = [.withoutEscapingSlashes] } return encoder } }
apache-2.0
138c0fb06e7e1b134ee4c15ee4911e99
29.238095
71
0.633071
4.635036
false
false
false
false
mshafer/stock-portfolio-ios
Portfolio/MasterViewController.swift
1
10933
// // MasterViewController.swift // Portfolio // // Created by Michael Shafer on 22/09/15. // Copyright © 2015 mshafer. All rights reserved. // import UIKit class MasterViewController: UITableViewController, EditHoldingDelegate, ExchangeRateListener { var detailViewController: DetailViewController? = nil var holdings: [Holding] = [] var encounteredErrorLoadingData = false var stockQuoteService = YahooStockQuoteService() var userHoldingsService = UserHoldingsService() var exchangeRateService = FixerExchangeRateService(baseCurrency: Util.getLocalCurrencyCode()) // MARK: - Computed properties var portfolioTotalValue: Double? { get { guard exchangeRateService.exchangeRatesAreAvailable else { return nil } var valueSum = 0.0 for holding in self.holdings { if let holdingValue = holding.currentValue { valueSum += exchangeRateService.convert(holdingValue, fromCurrency: holding.currencyCode)! } else { return nil } } return valueSum } } var portfolioChangeTodayAsFraction: Double? { get { guard let changeInDollars = self.portfolioChangeTodayAsDollars, let totalValue = self.portfolioTotalValue else { return nil } return changeInDollars / totalValue } } var portfolioChangeTodayAsDollars: Double? { get { var sum = 0.0 for holding in holdings { if let change = holding.changeTodayAsDollars { sum += exchangeRateService.convert(change, fromCurrency: holding.currencyCode)! } else { return nil } } return sum } } // MARK: - View Outlets @IBOutlet var portfolioTotalValueLabel: UILabel! @IBOutlet var portfolioChangeTodayLabel: UILabel! @IBOutlet var portfolioTotalLabelLabel: UILabel! // MARK: - View Lifecycle override func viewDidLoad() { super.viewDidLoad() // Refresh exchange rates exchangeRateService.addListener(self) exchangeRateService.updateExchangeRates() self.navigationItem.leftBarButtonItem = self.editButtonItem() // Set up the Add button let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "showSearchScreen:") self.navigationItem.rightBarButtonItem = addButton // Configure the detailViewController if let split = self.splitViewController { let controllers = split.viewControllers self.detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController } self.refreshControl = UIRefreshControl() self.refreshControl?.addTarget(self, action: "refresh:", forControlEvents: UIControlEvents.ValueChanged) self.tableView.setContentOffset(CGPointMake(0, -self.refreshControl!.frame.size.height), animated: true) self.holdings = userHoldingsService.loadUserHoldings() self.refreshControl?.beginRefreshing() self.refresh(self) } override func viewWillAppear(animated: Bool) { self.clearsSelectionOnViewWillAppear = self.splitViewController!.collapsed super.viewWillAppear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func showSearchScreen(sender: AnyObject) { let searchNavigationController = self.storyboard?.instantiateViewControllerWithIdentifier("SearchNavigationController") as! SearchNavigationController! let searchViewController = searchNavigationController.viewControllers.first as! SearchBarViewController searchViewController.editHoldingDelegate = self self.presentViewController(searchNavigationController!, animated: true, completion: nil) } func insertNewObject(sender: AnyObject) { holdings.insert(Holding(symbol: "AIR.NZ", name: "Air New Zealand", numberOfShares: 1000, totalPurchasePrice: 10000, currencyCode: "NZD"), atIndex: 0) let indexPath = NSIndexPath(forRow: 0, inSection: 0) self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic) } // MARK: - Refresh model func refresh(sender:AnyObject) { self.updateHeaderView() stockQuoteService.getQuotesForHoldings(self.holdings, onCompletion: self.onRefreshSuccess, onError: self.onRefreshError) } func onRefreshSuccess(_: [Holding]) { // The StockQuoteService directly modifies the holdings in the array so we don't actually need to use // the holdings argument given to us self.encounteredErrorLoadingData = false self.tableView.reloadData() self.refreshControl?.endRefreshing() self.updateHeaderView() self.userHoldingsService.saveUserHoldings(self.holdings) } func onRefreshError() { self.encounteredErrorLoadingData = true self.tableView.reloadData() self.refreshControl?.endRefreshing() } // MARK: - Segues override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showDetail" { if let indexPath = self.tableView.indexPathForSelectedRow { let holding = holdings[indexPath.row] let controller = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController controller.detailItem = holding controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem() controller.navigationItem.leftItemsSupplementBackButton = true } } } // MARK: - Table View override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if encounteredErrorLoadingData { return 1 } else { return holdings.count } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if (encounteredErrorLoadingData) { return tableView.dequeueReusableCellWithIdentifier("ErrorCell")! } let cell = tableView.dequeueReusableCellWithIdentifier("HoldingCell", forIndexPath: indexPath) as! HoldingTableViewCell let holding = holdings[indexPath.row] cell.configureForHolding(holding) return cell } override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return !encounteredErrorLoadingData } override func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle { if self.tableView.editing { return .Delete } else { return .None } } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { holdings.removeAtIndex(indexPath.row) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) self.updateHeaderView() userHoldingsService.saveUserHoldings(self.holdings) } 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 func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { return !encounteredErrorLoadingData } override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { let holding = holdings[fromIndexPath.row] holdings.removeAtIndex(fromIndexPath.row) holdings.insert(holding, atIndex: toIndexPath.row) self.userHoldingsService.saveUserHoldings(self.holdings) } // MARK: - Edit Holding Delegate func newHoldingWasCreated(holding: Holding) { holdings.insert(holding, atIndex: 0) let indexPath = NSIndexPath(forRow: 0, inSection: 0) self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic) userHoldingsService.saveUserHoldings(self.holdings) self.refresh(self) } func holdingWasEdited(oldHolding: Holding, editedHolding: Holding) { let indexOfHolding = holdings.indexOf(oldHolding) holdings[indexOfHolding!] = editedHolding self.tableView.reloadData() userHoldingsService.saveUserHoldings(self.holdings) self.refresh(self) } // MARK: - Exchange Rate Listener func exchangeRatesDidChange() { self.updateHeaderView() } // MARK: - Header View (Portfolio Totals) func updateHeaderView() { let currencyCode = Util.getLocalCurrencyCode() self.portfolioTotalLabelLabel.text = "PORTFOLIO TOTAL (\(currencyCode))" guard let totalValue = self.portfolioTotalValue, let changeTodayString = self.portfolioChangeTodayString() else { self.portfolioTotalValueLabel.text = "" self.portfolioChangeTodayLabel.text = "" return } self.portfolioTotalValueLabel.text = Util.currencyToString(totalValue, currencyCode: currencyCode) self.portfolioChangeTodayLabel.text = changeTodayString // Set red or green var colour: UIColor = UIColor.dangerColor() if let changeTodayAsFraction = self.portfolioChangeTodayAsFraction { if changeTodayAsFraction >= 0 { colour = UIColor(hex: "#45BF55") } } self.portfolioChangeTodayLabel.textColor = colour } private func portfolioChangeTodayString() -> String? { guard let changeInDollars = self.portfolioChangeTodayAsDollars, let changeAsFraction = self.portfolioChangeTodayAsFraction else { return nil } let changeInDollarsString = Util.currencyToString(changeInDollars, currencyCode: Util.getLocalCurrencyCode()) let changeInPercentString = Util.fractionToPercentage(changeAsFraction) return "\(changeInDollarsString) (\(changeInPercentString))" } }
gpl-3.0
eed041bfa43b83eb4fc28e3049c37449
37.765957
159
0.664746
5.474211
false
false
false
false
ktustanowski/toucher
Toucher/UICollectionView+Tap.swift
2
1476
// // UICollectionView+Tap.swift // Toucher // // Created by Kamil Tustanowski on 11.03.2017. // Copyright © 2017 Kamil Tustanowski. All rights reserved. // import UIKit public extension UICollectionView { public func tapItem(at indexPath: IndexPath) { checkDelegate() checkDataSource() check(indexPath: indexPath) delegate?.collectionView?(self, didSelectItemAt: indexPath) } } fileprivate extension UICollectionView { func checkDelegate() { guard let _ = delegate else { assertionFailure("No delegate associated!") return } } func checkDataSource() { guard let _ = dataSource else { assertionFailure("No data source associated!") return } } func check(indexPath: IndexPath) { let sectionCount = dataSource?.numberOfSections?(in: self) ?? 1 guard indexPath.section >= 0, indexPath.section < sectionCount else { assertionFailure("Not found section \(indexPath.section) in Table View") return } let rowCount = dataSource?.collectionView(self, numberOfItemsInSection: indexPath.section) ?? 0 guard indexPath.row >= 0, indexPath.row < rowCount else { assertionFailure("Not found row \(indexPath.row) in Table View") return } } }
mit
851a06eb8c49bec7a66aa189155ebe26
25.818182
103
0.583729
5.267857
false
false
false
false
iHunterX/SocketIODemo
DemoSocketIO/Classes/LoginViewController.swift
1
2777
// // ViewController.swift // DemoSocketIO // // Created by Đinh Xuân Lộc on 10/20/16. // Copyright © 2016 Loc Dinh Xuan. All rights reserved. // import UIKit import SocketIO class ViewController: BaseViewController, UITextFieldDelegate{ @IBOutlet weak var userNameTextField: iHUnderLineColorTextField! @IBOutlet weak var connectButton: UIButton! var lastControllerRotationStatus: Bool? var userInfo:User? var validationRuleSetUserName: ValidationRuleSet<String>? = ValidationRuleSet<String>() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. userNameTextField.delegate = self userNameTextField.tfdelegate = self addTextFieldRules() connectButton.isEnabled = false } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController?.navigationBar.isHidden = true if let appDelegate = UIApplication.shared.delegate as? AppDelegate { lastControllerRotationStatus = appDelegate.shouldRotate appDelegate.shouldRotate = false } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func addTextFieldRules(){ self.validationRuleSetUserName?.add(rule: UserName) self.validationRuleSetUserName?.add(rule: rangeLengthRule) userNameTextField.validationRuleSet = validationRuleSetUserName userNameTextField.validateOnInputChange(validationEnabled: true) } @IBAction func JoinChatAction(_ sender: AnyObject) { let nickName = self.userNameTextField.text! SocketIOManager.sharedInstance.registerWithNickname(nickname: nickName) { (userInfo, error) in print(userInfo) if error != nil{ print(error) }else{ if userInfo != nil { self.userInfo = userInfo self.performSegue(withIdentifier: "logInSegue", sender: sender) } } } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "logInSegue" { if let destination = segue.destination as? InitalTableViewController { destination.userInfo = self.userInfo! } } } } extension ViewController: TextFieldEffectsDelegate{ func validTextField(valid: Bool) { connectButton.isEnabled = valid } }
gpl-3.0
02e23896692c4839e7c977593ccb54a0
28.178947
102
0.647547
5.269962
false
false
false
false
lelandjansen/fatigue
ios/fatigue/HomePageCell.swift
1
4134
import UIKit class HomePageCell: UICollectionViewCell { override init(frame: CGRect) { super.init(frame: frame) setupViews() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } weak var delegate: HomePageControllerDelegate? let logoImage: UIImageView = { return UIImageView(image: #imageLiteral(resourceName: "iagsa-logo-full-dark")) }() let titleLabel: UILabel = { let attributedText = NSMutableAttributedString( string: "Fatigue Self-Assessment", attributes: [ NSFontAttributeName: UIFont.systemFont(ofSize: 22, weight: UIFontWeightSemibold) ] ) let label = UILabel() label.attributedText = attributedText label.textAlignment = .center label.lineBreakMode = .byWordWrapping label.numberOfLines = 0 label.textColor = .dark return label }() let subtitleLabel: UILabel = { let label = UILabel() label.text = "Safety in the air begins on the ground." label.font = .systemFont(ofSize: 17) label.textAlignment = .center label.lineBreakMode = .byWordWrapping label.numberOfLines = 0 label.textColor = .medium return label }() let beginButton: UIButton = { let button = UIButton.createStyledButton(withColor: .violet) button.setTitle("Begin", for: .normal) return button }() let settingsButton: UIButton = { let button = UIButton() button.titleLabel?.font = .systemFont(ofSize: 17, weight: UIFontWeightSemibold) button.setTitleColor(.medium, for: .normal) button.setTitleColor(UIColor.medium.withAlphaComponent(1/2), for: .highlighted) button.setTitle("Settings", for: .normal) button.sizeToFit() button.translatesAutoresizingMaskIntoConstraints = false return button }() func setupViews() { addSubview(logoImage) addSubview(titleLabel) addSubview(subtitleLabel) addSubview(beginButton) addSubview(settingsButton) let padding: CGFloat = 16 logoImage.anchorWithConstantsToTop( nil, left: leftAnchor, bottom: topAnchor, right: rightAnchor, leftConstant: (self.frame.width - logoImage.frame.width) / 2, bottomConstant: padding, rightConstant: (self.frame.width - logoImage.frame.width) / 2 ) titleLabel.anchorWithConstantsToTop( topAnchor, left: leftAnchor, right: rightAnchor, topConstant: 96, leftConstant: padding, rightConstant: padding ) subtitleLabel.anchorWithConstantsToTop( titleLabel.bottomAnchor, left: leftAnchor, right: rightAnchor, topConstant: padding, leftConstant: padding, rightConstant: padding ) beginButton.frame = CGRect( x: (self.frame.size.width - UIConstants.buttonWidth) / 2, y: (self.frame.size.height + UIConstants.tableViewRowHeight + UIConstants.navigationBarHeight - UIConstants.buttonHeight - UIConstants.buttonSpacing + 38) / 2, width: UIConstants.buttonWidth, height: UIConstants.buttonHeight ) beginButton.addTarget(self, action: #selector(handleBeginButton), for: .touchUpInside) settingsButton.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true settingsButton.centerYAnchor.constraint(equalTo: centerYAnchor, constant: UIConstants.tableViewRowHeight + UIConstants.buttonHeight + UIConstants.buttonSpacing).isActive = true settingsButton.addTarget(self, action: #selector(handleSettingsButton), for: .touchUpInside) } func handleBeginButton() { delegate?.presentQuestionnaire() } func handleSettingsButton() { delegate?.presentSettings() } }
apache-2.0
6f532ec144d93ec9a0e9210b61588220
33.45
184
0.619497
5.389831
false
false
false
false
WestlakeAPC/game-off-2016
external/Fiber2D/Fiber2D/PhysicsShape.swift
1
8082
// // PhysicsShape.swift // Fiber2D // // Created by Andrey Volodin on 20.09.16. // Copyright © 2016 s1ddok. All rights reserved. // import SwiftMath public enum PhysicsShapeType { case unknown, circle, box, polygon case edgeSegment, edgeBox, edgePolygon, edgeChain } public struct PhysicsMaterial { var density: Float ///< The density of the object. var elasticity: Float ///< The bounciness of the physics body. var friction: Float ///< The roughness of the surface of a shape. public static let `default` = PhysicsMaterial(density: 0.1, elasticity: 0.5, friction: 0.5) } /** * @brief A shape for body. You do not create PhysicsShape objects directly, instead, you can view PhysicsBody to see how to create it. */ public class PhysicsShape: Tagged { public var tag: Int = 0 /** * Get the body that this shape attaches. * * @return A PhysicsBody object pointer. */ internal(set) weak public var body: PhysicsBody? { didSet { for cps in chipmunkShapes { cpShapeSetBody(cps, body?.chipmunkBody ?? SHARED_BODY) } } } /** * Return this shape's type. * * @return A Type object. */ internal(set) public var type: PhysicsShapeType = .unknown /** * Return this shape's area. * * @return A float number. */ internal(set) public var area: Float = 0.0 // MARK: Physics properties /** * This shape's moment. * * It will change the body's moment this shape attaches. * * @param moment A float number. */ public var moment: Float = 0.0 { didSet { guard moment >= 0.0 else { return } if let body = self.body { body.add(moment: -oldValue) body.add(moment: moment) } } } /** * This shape's mass. * * It will change the body's mass this shape attaches. * * @param mass A float number. */ public var mass: Float = 0.0 { didSet { guard moment >= 0.0 else { return } if let body = self.body { body.add(mass: -oldValue) body.add(mass: mass) } } } // MARK: Material /** * Get this shape's PhysicsMaterial object. * * @return A PhysicsMaterial object reference. */ public var material: PhysicsMaterial { get { return _material } set { self.density = newValue.density self.elasticity = newValue.elasticity self.friction = newValue.friction } } /** * This shape's density. * * It will change the body's mass this shape attaches. * * @param density A float number. */ public var density: Float { get { return _material.density } set { guard newValue >= 0.0 else { return } _material.density = newValue if newValue == Float.infinity { mass = Float.infinity } else { mass = newValue * area } } } /** * This shape's elasticity. * * It will change the shape's elasticity. * * @param restitution A float number. */ public var elasticity: Float { get { return _material.elasticity } set { _material.elasticity = newValue for cps in chipmunkShapes { cpShapeSetElasticity(cps, cpFloat(newValue)) } } } /** * This shape's friction. * * It will change the shape's friction. * * @param friction A float number. */ public var friction: Float { get { return _material.friction } set { _material.friction = newValue for cps in chipmunkShapes { cpShapeSetFriction(cps, cpFloat(newValue)) } } } // MARK: Interaction properties /** * Set the group of body. * * Collision groups let you specify an integral group index. You can have all fixtures with the same group index always collide (positive index) or never collide (negative index). * @param group An integer number, it have high priority than bit masks. */ public var group: Int = 0 { didSet { if group < 0 { for shape in chipmunkShapes { cpShapeSetFilter(shape, cpShapeFilterNew(cpGroup(group), CP_ALL_CATEGORIES, CP_ALL_CATEGORIES)) } } } } /** * Get this shape's position offset. * * This function should be overridden in inherit classes. * @return A Vec2 object. */ public var offset: Vector2f { return Vector2f.zero } /** * Get this shape's center position. * * This function should be overridden in inherit classes. * @return A Vec2 object. */ public var center: Vector2f { return offset } /** * A mask that defines which categories of physics bodies can collide with this physics body. * * When two physics bodies contact each other, a collision may occur. This body's collision mask is compared to the other body's category mask by performing a logical AND operation. If the result is a non-zero value, then this body is affected by the collision. Each body independently chooses whether it wants to be affected by the other body. For example, you might use this to avoid collision calculations that would make negligible changes to a body's velocity. * @param bitmask An integer number, the default value is 0xFFFFFFFF (all bits set). */ public var collisionBitmask = UInt32.max /** * A mask that defines which categories of bodies cause intersection notifications with this physics body. * * When two bodies share the same space, each body's category mask is tested against the other body's contact mask by performing a logical AND operation. If either comparison results in a non-zero value, an PhysicsContact object is created and passed to the physics world’s delegate. For best performance, only set bits in the contacts mask for interactions you are interested in. * @param bitmask An integer number, the default value is 0x00000000 (all bits cleared). */ public var contactTestBitmask = UInt32(0) /** * Set a mask that defines which categories this physics body belongs to. * * Every physics body in a scene can be assigned to up to 32 different categories, each corresponding to a bit in the bit mask. You define the mask values used in your game. In conjunction with the collisionBitMask and contactTestBitMask properties, you define which physics bodies interact with each other and when your game is notified of these interactions. * @param bitmask An integer number, the default value is 0xFFFFFFFF (all bits set). */ public var categoryBitmask = UInt32.max public var isSensor: Bool = false { didSet { if isSensor != oldValue { for cps in chipmunkShapes { cpShapeSetSensor(cps, isSensor ? 1 : 0) } } } } // Override me in subclasses open func calculateArea() -> Float { return 0.0 } /** * Calculate the default moment value. * * This function should be overridden in inherit classes. * @return A float number, equals 0.0. */ open func calculateDefaultMoment() -> Float { return 0.0 } // MARK: Internal vars internal var chipmunkShapes = [UnsafeMutablePointer<cpShape>]() internal var _material = PhysicsMaterial.default // MARK: Private vars }
apache-2.0
e7304db4169f6a94779cb997d72dc35c
30.073077
469
0.584231
4.661858
false
false
false
false
treejames/firefox-ios
Client/Frontend/Browser/SwipeAnimator.swift
7
5586
/* 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 struct SwipeAnimationParameters { let totalRotationInDegrees: Double let deleteThreshold: CGFloat let totalScale: CGFloat let totalAlpha: CGFloat let minExitVelocity: CGFloat let recenterAnimationDuration: NSTimeInterval } private let DefaultParameters = SwipeAnimationParameters( totalRotationInDegrees: 10, deleteThreshold: 80, totalScale: 0.9, totalAlpha: 0, minExitVelocity: 800, recenterAnimationDuration: 0.15) protocol SwipeAnimatorDelegate: class { func swipeAnimator(animator: SwipeAnimator, viewDidExitContainerBounds: UIView) } class SwipeAnimator: NSObject { weak var delegate: SwipeAnimatorDelegate? weak var container: UIView! weak var animatingView: UIView! private var prevOffset: CGPoint! private let params: SwipeAnimationParameters var containerCenter: CGPoint { return CGPoint(x: CGRectGetWidth(container.frame) / 2, y: CGRectGetHeight(container.frame) / 2) } init(animatingView: UIView, container: UIView, params: SwipeAnimationParameters = DefaultParameters) { self.animatingView = animatingView self.container = container self.params = params super.init() let panGesture = UIPanGestureRecognizer(target: self, action: Selector("SELdidPan:")) container.addGestureRecognizer(panGesture) panGesture.delegate = self } } //MARK: Private Helpers extension SwipeAnimator { private func animateBackToCenter() { UIView.animateWithDuration(params.recenterAnimationDuration, animations: { self.animatingView.transform = CGAffineTransformIdentity self.animatingView.alpha = 1 }) } private func animateAwayWithVelocity(velocity: CGPoint, speed: CGFloat) { // Calculate the edge to calculate distance from let translation = velocity.x >= 0 ? CGRectGetWidth(container.frame) : -CGRectGetWidth(container.frame) let timeStep = NSTimeInterval(abs(translation) / speed) UIView.animateWithDuration(timeStep, animations: { self.animatingView.transform = self.transformForTranslation(translation) self.animatingView.alpha = self.alphaForDistanceFromCenter(abs(translation)) }, completion: { finished in if finished { self.animatingView.alpha = 0 self.delegate?.swipeAnimator(self, viewDidExitContainerBounds: self.animatingView) } }) } private func transformForTranslation(translation: CGFloat) -> CGAffineTransform { let swipeWidth = container.frame.size.width let totalRotationInRadians = CGFloat(params.totalRotationInDegrees / 180.0 * M_PI) // Determine rotation / scaling amounts by the distance to the edge var rotation = (translation / swipeWidth) * totalRotationInRadians var scale = 1 - (abs(translation) / swipeWidth) * (1 - params.totalScale) let rotationTransform = CGAffineTransformMakeRotation(rotation) let scaleTransform = CGAffineTransformMakeScale(scale, scale) let translateTransform = CGAffineTransformMakeTranslation(translation, 0) return CGAffineTransformConcat(CGAffineTransformConcat(rotationTransform, scaleTransform), translateTransform) } private func alphaForDistanceFromCenter(distance: CGFloat) -> CGFloat { let swipeWidth = container.frame.size.width return 1 - (distance / swipeWidth) * (1 - params.totalAlpha) } } //MARK: Selectors extension SwipeAnimator { @objc func SELdidPan(recognizer: UIPanGestureRecognizer!) { let translation = recognizer.translationInView(container) switch (recognizer.state) { case .Began: prevOffset = containerCenter case .Changed: animatingView.transform = transformForTranslation(translation.x) animatingView.alpha = alphaForDistanceFromCenter(abs(translation.x)) prevOffset = CGPoint(x: translation.x, y: 0) case .Cancelled: animateBackToCenter() case .Ended: let velocity = recognizer.velocityInView(container) // Bounce back if the velocity is too low or if we have not reached the threshold yet let speed = max(abs(velocity.x), params.minExitVelocity) if (speed < params.minExitVelocity || abs(prevOffset.x) < params.deleteThreshold) { animateBackToCenter() } else { animateAwayWithVelocity(velocity, speed: speed) } default: break } } func close(#right: Bool) { let direction = CGFloat(right ? -1 : 1) animateAwayWithVelocity(CGPoint(x: -direction * params.minExitVelocity, y: 0), speed: direction * params.minExitVelocity) } @objc func SELcloseWithoutGesture() -> Bool { close(right: false) return true } } extension SwipeAnimator: UIGestureRecognizerDelegate { @objc func gestureRecognizerShouldBegin(recognizer: UIGestureRecognizer) -> Bool { let cellView = recognizer.view as UIView! let panGesture = recognizer as! UIPanGestureRecognizer let translation = panGesture.translationInView(cellView.superview!) return fabs(translation.x) > fabs(translation.y) } }
mpl-2.0
4caeee7edb8d662b381ef9040d91a1ca
37.798611
129
0.686896
5.304843
false
false
false
false
box/box-ios-sdk
Sources/Responses/SharedItem.swift
1
1425
// // SharedItem.swift // BoxSDK-iOS // // Created by Cary Cheng on 6/10/19. // Copyright © 2019 Box. All rights reserved. // import Foundation /// Item shared by shared link. public class SharedItem: BoxModel { // MARK: - BoxModel public private(set) var rawData: [String: Any] /// Type of shared item public enum SharedItemType { /// File type case file(File) /// Folder type case folder(Folder) /// Web link type case webLink(WebLink) } /// Shared item value public var itemValue: SharedItemType /// Initializer. /// /// - Parameter json: JSON dictionary. /// - Throws: Decoding error. public required init(json: [String: Any]) throws { rawData = json guard let type = json["type"] as? String else { throw BoxCodingError(message: .typeMismatch(key: "type")) } switch type { case "file": let file = try File(json: json) itemValue = .file(file) case "folder": let folder = try Folder(json: json) itemValue = .folder(folder) case "web_link": let webLink = try WebLink(json: json) itemValue = .webLink(webLink) default: throw BoxCodingError(message: .valueMismatch(key: "type", value: type, acceptedValues: ["file", "folder", "web_link"])) } } }
apache-2.0
790214f46fa0f93d943a05d355185f87
25.37037
131
0.568118
4.103746
false
false
false
false
midoks/Swift-Learning
GitHubStar/GitHubStar/GitHubStar/Controllers/common/users/GsOrgListViewController.swift
1
3123
// // GsOrgViewController.swift // GitHubStar // // Created by midoks on 16/3/17. // Copyright © 2016年 midoks. All rights reserved. // import UIKit import SwiftyJSON class GsOrgListViewController: GsListViewController { override func viewDidLoad() { super.viewDidLoad() self.delegate = self } override func refreshUrl(){ super.refreshUrl() self.startPull() GitHubApi.instance.urlGet(url: _fixedUrl) { (data, response, error) -> Void in self.pullingEnd() if data != nil { let _dataJson = self.gitJsonParse(data: data!) for i in _dataJson { self._tableData.append(i.1) } self._tableView?.reloadData() let rep = response as! HTTPURLResponse if rep.allHeaderFields["Link"] != nil { let r = self.gitParseLink(urlLink: rep.allHeaderFields["Link"] as! String) self.pageInfo = r } } } } func setUrlData(url:String){ _fixedUrl = url } } extension GsOrgListViewController:GsListViewDelegate { func listTableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let indexData = self.getSelectTableData(indexPath: indexPath) let cell = GsOrgIconTableViewCell(style: .default, reuseIdentifier: cellIdentifier) cell.imageView?.MDCacheImage(url: indexData["avatar_url"].stringValue, defaultImage: "github_default_28") cell.textLabel?.text = indexData["login"].stringValue cell.accessoryType = .disclosureIndicator return cell } func listTableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let indexData = self.getSelectTableData(indexPath: indexPath) let orgHome = GsOrgHomeViewController() orgHome.setUrlData(data: indexData) self.push(v: orgHome) } func applyFilter(searchKey:String, data:JSON) -> Bool { if data["login"].stringValue.lowercased().contains(searchKey.lowercased()) { return true } return false } func pullUrlLoad(url: String){ GitHubApi.instance.webGet(absoluteUrl: url) { (data, response, error) -> Void in self.pullingEnd() if data != nil { let _dataJson = self.gitJsonParse(data: data!) for i in _dataJson { self._tableData.append(i.1) } self._tableView?.reloadData() let rep = response as! HTTPURLResponse if rep.allHeaderFields["Link"] != nil { let r = self.gitParseLink(urlLink: rep.allHeaderFields["Link"] as! String) self.pageInfo = r } } else { print("error") } } } }
apache-2.0
1397d0f073a061ff633da162fe424053
29.891089
113
0.551282
4.936709
false
false
false
false
sergdort/CleanArchitectureRxSwift
RealmPlatform/Entities/RMTodo.swift
1
1288
// // RMTodo.swift // CleanArchitectureRxSwift // // Created by Andrey Yastrebov on 10.03.17. // Copyright © 2017 sergdort. All rights reserved. // import QueryKit import Domain import RealmSwift import Realm final class RMTodo: Object { @objc dynamic var completed: Bool = false @objc dynamic var title: String = "" @objc dynamic var uid: String = "" @objc dynamic var userId: String = "" override class func primaryKey() -> String? { return "uid" } } extension RMTodo { static var title: Attribute<String> { return Attribute("title")} static var completed: Attribute<Bool> { return Attribute("completed")} static var userId: Attribute<String> { return Attribute("userId")} static var uid: Attribute<String> { return Attribute("uid")} } extension RMTodo: DomainConvertibleType { func asDomain() -> Todo { return Todo(completed: completed, title: title, uid: uid, userId: userId) } } extension Todo: RealmRepresentable { func asRealm() -> RMTodo { return RMTodo.build { object in object.uid = uid object.userId = userId object.title = title object.completed = completed } } }
mit
868b12badc4109c2aa7cdfef97f07c2c
24.235294
74
0.616939
4.377551
false
false
false
false
niunaruto/DeDaoAppSwift
testSwift/Pods/BSImagePicker/Sources/Controller/BSImagePickerViewController.swift
1
9088
// The MIT License (MIT) // // Copyright (c) 2015 Joakim Gyllström // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit import Photos /** BSImagePickerViewController. Use settings or buttons to customize it to your needs. */ open class BSImagePickerViewController : UINavigationController { /** Object that keeps settings for the picker. */ open var settings: BSImagePickerSettings = Settings() /** Done button. */ @objc open var doneButton: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: nil) /** Cancel button */ @objc open var cancelButton: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: nil, action: nil) /** Default selections */ @objc open var defaultSelections: PHFetchResult<PHAsset>? /** Fetch results. */ @objc open lazy var fetchResults: [PHFetchResult] = { () -> [PHFetchResult<PHAssetCollection>] in let fetchOptions = PHFetchOptions() // Camera roll fetch result let cameraRollResult = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: .smartAlbumUserLibrary, options: fetchOptions) // Albums fetch result let albumResult = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: fetchOptions) return [cameraRollResult, albumResult] }() @objc var albumTitleView: UIButton = { // .custom type used to avoid sizing animation uglyness when changing the title let btn = UIButton(type: .custom) // Positions the image to the right btn.semanticContentAttribute = .forceRightToLeft // Padding between the title and image let titleImageGap: CGFloat = 6.0 btn.titleEdgeInsets = UIEdgeInsets(top: 0.0, left: -titleImageGap, bottom: 0.0, right: titleImageGap) btn.contentEdgeInsets = UIEdgeInsets(top: 0.0, left: titleImageGap, bottom: 0.0, right: 0.0) let image = UIImage(named: "arrow_down", in: BSImagePickerViewController.bundle, compatibleWith: nil)?.withRenderingMode(.alwaysTemplate) btn.setImage(image, for: .normal) btn.setTitleColor(btn.tintColor, for: .normal) // Font size specified to match the default font size for a UIButton with .system type btn.titleLabel?.font = .systemFont(ofSize: 15.0) return btn }() static var bundle: Bundle { if let path = Bundle(for: PhotosViewController.self).path(forResource: "BSImagePicker", ofType: "bundle"), let b = Bundle(path: path) { return b } else { return Bundle(for: PhotosViewController.self) } } @objc lazy var photosViewController: PhotosViewController = { var selections: [PHAsset] = [] defaultSelections?.enumerateObjects({ (asset, idx, stop) in selections.append(asset) }) let assetStore = AssetStore(assets: selections) let vc = PhotosViewController(fetchResults: self.fetchResults, assetStore: assetStore, settings: self.settings) vc.doneBarButton = self.doneButton vc.cancelBarButton = self.cancelButton vc.albumTitleView = self.albumTitleView return vc }() @objc class func authorize(_ status: PHAuthorizationStatus = PHPhotoLibrary.authorizationStatus(), fromViewController: UIViewController, completion: @escaping (_ authorized: Bool) -> Void) { switch status { case .authorized: // We are authorized. Run block completion(true) case .notDetermined: // Ask user for permission PHPhotoLibrary.requestAuthorization({ (status) -> Void in DispatchQueue.main.async(execute: { () -> Void in self.authorize(status, fromViewController: fromViewController, completion: completion) }) }) default: () DispatchQueue.main.async(execute: { () -> Void in completion(false) }) } } /** Sets up an classic image picker with results from camera roll and albums */ public init() { super.init(nibName: nil, bundle: nil) } /** https://www.youtube.com/watch?v=dQw4w9WgXcQ */ required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } /** Load view. See apple documentation */ open override func loadView() { super.loadView() // TODO: Settings view.backgroundColor = UIColor.white // Make sure we really are authorized if PHPhotoLibrary.authorizationStatus() == .authorized { setViewControllers([photosViewController], animated: false) } } } // MARK: ImagePickerSettings proxy extension BSImagePickerViewController: BSImagePickerSettings { /** See BSImagePicketSettings for documentation */ @objc public var maxNumberOfSelections: Int { get { return settings.maxNumberOfSelections } set { settings.maxNumberOfSelections = newValue } } /** See BSImagePicketSettings for documentation */ public var selectionCharacter: Character? { get { return settings.selectionCharacter } set { settings.selectionCharacter = newValue } } /** See BSImagePicketSettings for documentation */ @objc public var selectionFillColor: UIColor { get { return settings.selectionFillColor } set { settings.selectionFillColor = newValue } } /** See BSImagePicketSettings for documentation */ @objc public var selectionStrokeColor: UIColor { get { return settings.selectionStrokeColor } set { settings.selectionStrokeColor = newValue } } /** See BSImagePicketSettings for documentation */ @objc public var selectionShadowColor: UIColor { get { return settings.selectionShadowColor } set { settings.selectionShadowColor = newValue } } /** See BSImagePicketSettings for documentation */ @objc public var selectionTextAttributes: [NSAttributedString.Key: AnyObject] { get { return settings.selectionTextAttributes } set { settings.selectionTextAttributes = newValue } } /** BackgroundColor */ @objc public var backgroundColor: UIColor { get { return settings.backgroundColor } set { settings.backgroundColor = newValue } } /** See BSImagePicketSettings for documentation */ @objc public var cellsPerRow: (_ verticalSize: UIUserInterfaceSizeClass, _ horizontalSize: UIUserInterfaceSizeClass) -> Int { get { return settings.cellsPerRow } set { settings.cellsPerRow = newValue } } /** See BSImagePicketSettings for documentation */ @objc public var takePhotos: Bool { get { return settings.takePhotos } set { settings.takePhotos = newValue } } @objc public var takePhotoIcon: UIImage? { get { return settings.takePhotoIcon } set { settings.takePhotoIcon = newValue } } } // MARK: Album button extension BSImagePickerViewController { /** Album button in title view */ @objc public var albumButton: UIButton { get { return albumTitleView } set { albumTitleView = newValue } } }
mit
fc995f509e9fb193e2f80055a1028bca
29.29
194
0.617035
5.219414
false
false
false
false
apple/swift-experimental-string-processing
Sources/_StringProcessing/Algorithms/Searchers/NaivePatternSearcher.swift
1
2702
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2021-2022 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // //===----------------------------------------------------------------------===// struct NaivePatternSearcher<Searched: Collection, Pattern: Collection> where Searched.Element: Equatable, Pattern.Element == Searched.Element { let pattern: Pattern } extension NaivePatternSearcher: StatelessCollectionSearcher { func search( _ searched: Searched, in range: Range<Searched.Index> ) -> Range<Searched.Index>? { var searchStart = range.lowerBound guard let patternFirst = pattern.first else { return searchStart..<searchStart } while let matchStart = searched[searchStart..<range.upperBound] .firstIndex(of: patternFirst) { var index = matchStart var patternIndex = pattern.startIndex repeat { searched.formIndex(after: &index) pattern.formIndex(after: &patternIndex) if patternIndex == pattern.endIndex { return matchStart..<index } else if index == range.upperBound { return nil } } while searched[index] == pattern[patternIndex] searchStart = searched.index(after: matchStart) } return nil } } extension NaivePatternSearcher: BackwardCollectionSearcher, BackwardStatelessCollectionSearcher where Searched: BidirectionalCollection, Pattern: BidirectionalCollection { typealias BackwardSearched = Searched func searchBack( _ searched: BackwardSearched, in range: Range<Searched.Index> ) -> Range<Searched.Index>? { var searchEnd = range.upperBound guard let otherLastIndex = pattern.indices.last else { return searchEnd..<searchEnd } let patternLast = pattern[otherLastIndex] while let matchEnd = searched[range.lowerBound..<searchEnd] .lastIndex(of: patternLast) { var index = matchEnd var otherIndex = otherLastIndex repeat { if otherIndex == pattern.startIndex { return index..<searched.index(after: matchEnd) } else if index == range.lowerBound { return nil } searched.formIndex(before: &index) pattern.formIndex(before: &otherIndex) } while searched[index] == pattern[otherIndex] searchEnd = matchEnd } return nil } }
apache-2.0
e98017595499d61ac09da4c16862a842
28.053763
80
0.61473
4.903811
false
false
false
false
TheHolyGrail/Shrubbery
ELLog/LogDestinationBase.swift
2
4275
// // LogDestinationBase.swift // ELLog // // Created by Brandon Sneed on 3/24/15. // Copyright (c) 2015 WalmartLabs. All rights reserved. // import Foundation /// Protocol that destination classes must support @objc(ELLogDestinationProtocol) public protocol LogDestinationProtocol: class { /** Sent to the destination when a log statement is executed. - parameter detail: Detailed information about the log statement. */ func log(_ detail: LogDetail) /** A unique identifier representing this destination. */ var identifier: String { get } /** The levels that this destination actually records. See LogLevel. */ var level: UInt { get set } } @objc(ELLogDestinationFormattible) public protocol LogDestinationFormattible: class { /// Specifies whether this destination should show the caller information. var showCaller: Bool { get } /// Specifies whether this destination should show the log level. var showLogLevel: Bool { get set } /// Specifies whether this destination should show the timestamp. var showTimestamp: Bool { get set } /// The dateformatter that will be used to format the timestamp. var dateFormatter: DateFormatter { get } /** Converts a `LogDetail` into a formatted string based on the current properties. This is what you should output into the destination verbatim. - parameter detail: The `LogDetail` that to be formatted for the destination. - returns: The formatted string. */ func formatted(_ detail: LogDetail) -> String } /// A struct describing a log message in detail. @objc(ELLogDetail) open class LogDetail: NSObject { /// The date at which the log call was made. Note: This will never be an exact time, but approximate. open var date: Date? = nil /// The message. @objc open var message: String? = nil /// The level at which this was logged. open var level: UInt? = .none /// The function in which log was called. open var function: String? = nil /// The filename in which log was called. open var filename: String? = nil /// The line number which called log. open var line: UInt? = nil } /** Base class for new destinations. Provides a default identifier (a GUID), a default level of .Debug, and a date formatter for use with output timestamps. */ @objc(ELLogDestinationBase) open class LogDestinationBase: NSObject, LogDestinationProtocol, LogDestinationFormattible { fileprivate static let DateFormat = "yyyy-MM-dd HH:mm:ss.SSS" public init(level: LogLevel) { self.level = level.rawValue showCaller = false showLogLevel = false showTimestamp = false dateFormatter = Thread.dateFormatter_ELLog(LogDestinationBase.DateFormat) } public override convenience init() { self.init(level: LogLevel.Debug) } // MARK: LogDestinationProtocol open var identifier: String = UUID().uuidString open var level: UInt /// Subclasses must override open func log(_ detail: LogDetail) { assert(false, "This method must be overriden by the subclass.") } // MARK: LogDestinationFormattible open var showCaller: Bool open var showLogLevel: Bool open var showTimestamp: Bool open var dateFormatter: DateFormatter open func formatted(_ detail: LogDetail) -> String { var logString: String = "" if showLogLevel { if let level = detail.level { logString += "[\(LogLevel(rawValue: level).description)] " } } if showTimestamp { if let date = detail.date { logString += "[\(dateFormatter.string(from: date))] " } } if showCaller { if let filename = detail.filename, let line = detail.line, let function = detail.function { logString += "(\(function), \((filename as NSString).lastPathComponent):\(line)) " } } logString += ": " if let message = detail.message { logString += message } return logString } }
mit
447c4607f5e2a27acf47a8fc393fe8a1
28.280822
106
0.636725
4.830508
false
false
false
false
mobgeek/swift
Swift em 4 Semanas/Swift4Semanas (7.0).playground/Pages/S1 - Conheça o Playground.xcplaygroundpage/Contents.swift
1
712
//: [Anterior: Intro](@previous) // Playground - noun: a place where people can play import UIKit var str = "Hello, playground" // Exemplo #01 var linguagem = "Obj-C" linguagem = "Swift" // Exemplo #02 var idade = 18 var novaIdade = idade + 2 // Exemplo #03 for i in 0..<50 { i*i } // Exemplo #04 var preço = 3.46 var avaliação: String switch preço { case 0...10: avaliação = "Aproveita! o preço está bom!" case 11...50: avaliação = "Caro, não?" default: avaliação = "Espera por uma melhor oportunidade de compra." } // Exemplo Extra: let color = UIColor.greenColor() //: [Começar: Constantes e Variáveis](@next)
mit
13e9bc27c3e97b8105aebc282cf93439
10.616667
63
0.602582
2.776892
false
false
false
false
mshhmzh/firefox-ios
Extensions/SendTo/ActionViewController.swift
2
3156
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import Shared import Storage import SnapKit /// The ActionViewController is the initial viewcontroller that is presented (full screen) when the share extension /// is activated. Depending on whether the user is logged in or not, this viewcontroller will present either the /// InstructionsVC or the ClientPicker VC. @objc(ActionViewController) class ActionViewController: UIViewController, ClientPickerViewControllerDelegate, InstructionsViewControllerDelegate { private lazy var profile: Profile = { return BrowserProfile(localName: "profile", app: nil) }() private var sharedItem: ShareItem? override func viewDidLoad() { view.backgroundColor = UIColor.whiteColor() super.viewDidLoad() guard profile.hasAccount() else { let instructionsViewController = InstructionsViewController() instructionsViewController.delegate = self let navigationController = UINavigationController(rootViewController: instructionsViewController) presentViewController(navigationController, animated: false, completion: nil) return } ExtensionUtils.extractSharedItemFromExtensionContext(self.extensionContext, completionHandler: { (item, error) -> Void in guard let item = item where error == nil && item.isShareable else { let alert = UIAlertController(title: Strings.SendToErrorTitle, message: Strings.SendToErrorMessage, preferredStyle: .Alert) alert.addAction(UIAlertAction(title: Strings.SendToErrorOKButton, style: .Default) { _ in self.finish() }) self.presentViewController(alert, animated: true, completion: nil) return } self.sharedItem = item let clientPickerViewController = ClientPickerViewController() clientPickerViewController.clientPickerDelegate = self clientPickerViewController.profile = self.profile let navigationController = UINavigationController(rootViewController: clientPickerViewController) self.presentViewController(navigationController, animated: false, completion: nil) }) } func finish() { self.extensionContext!.completeRequestReturningItems(nil, completionHandler: nil) } func clientPickerViewController(clientPickerViewController: ClientPickerViewController, didPickClients clients: [RemoteClient]) { // TODO: hook up Send Tab via Sync. // profile?.clients.sendItem(self.sharedItem!, toClients: clients) if let item = sharedItem { self.profile.sendItems([item], toClients: clients) } finish() } func clientPickerViewControllerDidCancel(clientPickerViewController: ClientPickerViewController) { finish() } func instructionsViewControllerDidClose(instructionsViewController: InstructionsViewController) { finish() } }
mpl-2.0
5ac5cbf563af1da62dbaa954da540806
44.085714
139
0.714512
5.844444
false
false
false
false
ExTEnS10N/The-Month
月历/NSDateExtension.swift
1
3525
// // NSDateExtension.swift // The Month // // Created by macsjh on 15/10/19. // Copyright © 2015年 TurboExtension. All rights reserved. // import Foundation extension NSDate { var year:Int? { get { let formatter = NSDateFormatter() formatter.dateFormat = "yyyy" let yearString = formatter.stringFromDate(self) return NSNumberFormatter().numberFromString(yearString)?.integerValue } } var month:Int? { get { let formatter = NSDateFormatter() formatter.dateFormat = "MM" let monthString = formatter.stringFromDate(self) return NSNumberFormatter().numberFromString(monthString)?.integerValue } } var dayOfMonth:Int? { get { let formatter = NSDateFormatter() formatter.dateFormat = "dd" let dayString = formatter.stringFromDate(self) return NSNumberFormatter().numberFromString(dayString)?.integerValue } } var dayOfWeek:Int? { get { let formatter = NSDateFormatter() formatter.dateFormat = "e" let dayString = formatter.stringFromDate(self) return NSNumberFormatter().numberFromString(dayString)?.integerValue } } var hour:Int? { get { let formatter = NSDateFormatter() formatter.dateFormat = "HH" let hourString = formatter.stringFromDate(self) return NSNumberFormatter().numberFromString(hourString)?.integerValue } } var minute:Int? { get { let formatter = NSDateFormatter() formatter.dateFormat = "mm" let minuteString = formatter.stringFromDate(self) return NSNumberFormatter().numberFromString(minuteString)?.integerValue } } var second:Int? { get { let formatter = NSDateFormatter() formatter.dateFormat = "mm" let secondString = formatter.stringFromDate(self) return NSNumberFormatter().numberFromString(secondString)?.integerValue } } func dateStringByFormat(format:String)->String? { let formatter = NSDateFormatter() formatter.dateFormat = format return formatter.stringFromDate(self) } var firstDayOfMonth:NSDate? { get { var exceptDayFormat = "" if(self.year != nil) { exceptDayFormat += "yyyy/" } if (self.month != nil) { exceptDayFormat += "MM/" } if (self.hour != nil) { exceptDayFormat += "HH/" } if (self.minute != nil) { exceptDayFormat += "mm/" } if (self.second != nil) { exceptDayFormat += "ss/" } let exceptDay = dateStringByFormat(exceptDayFormat) let formatter = NSDateFormatter() formatter.dateFormat = exceptDayFormat + "dd" if(exceptDay != nil) { return formatter.dateFromString(exceptDay! + "01") } return nil } } var lastDayOfMonth:NSDate? { get { if(self.month != nil) { var exceptMonthFormat = "" if(self.year != nil) { exceptMonthFormat += "yyyy/" } if (self.dayOfMonth != nil) { exceptMonthFormat += "dd/" } if (self.hour != nil) { exceptMonthFormat += "HH/" } if (self.minute != nil) { exceptMonthFormat += "mm/" } if (self.second != nil) { exceptMonthFormat += "ss/" } let exceptDay = dateStringByFormat(exceptMonthFormat) let formatter = NSDateFormatter() formatter.dateFormat = exceptMonthFormat + "MM" if(exceptDay != nil) { let nextMonth = formatter.dateFromString(exceptDay! + "\(self.month!)") if(nextMonth != nil) { return NSDate(timeInterval: -24*60*60, sinceDate: nextMonth!.firstDayOfMonth!) } } } return nil } } }
gpl-2.0
c2be2340e8ee85b1ef8dcda9e68e1945
18.786517
84
0.647076
3.446184
false
false
false
false
dashboardearth/rewardsplatform
src/Halo-iOS-App/Halo/User Interface/CityViewViewController.swift
1
6501
// // CityViewViewController.swift // Halo // // Created by Sattawat Suppalertporn on 24/7/17. // Copyright © 2017 dashboardearth. All rights reserved. // import UIKit import CoreLocation import GoogleMaps class CityViewViewController: UIViewController { // Views private var tableView:UITableView? private var mapCardView:MapCardView? // Data Model private var player:Player = Player() private var challenges:[Challenge] = [] private let locationManager = CLLocationManager() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.setupDataModel() self.layout() self.setupConstraints() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) let nc = self.navigationController as? RootNavigationController nc?.showHalo() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func layout() { // layout tableView let nc = self.navigationController as? RootNavigationController nc?.showHalo() self.tableView = UITableView() let tableView = self.tableView! tableView.translatesAutoresizingMaskIntoConstraints = false tableView.backgroundColor = UIColor(red: 0.95, green: 0.95, blue: 0.95, alpha: 1.0) tableView.dataSource = self tableView.delegate = self tableView.register(UITableViewCell.classForCoder(), forCellReuseIdentifier: "LabelCell") self.view.addSubview(tableView) } func setupConstraints() { let views = ["topLayoutGuide": self.topLayoutGuide, "bottomLayoutGuide": self.bottomLayoutGuide, "tableView": self.tableView!] as [String : Any] var allConstraints = [NSLayoutConstraint]() // overall layout allConstraints.append(contentsOf: NSLayoutConstraint.horizontalFillSuperview(view: self.tableView!)) allConstraints.append(contentsOf: NSLayoutConstraint.constraints( withVisualFormat: "V:|[topLayoutGuide][tableView][bottomLayoutGuide]|", options: [], metrics: nil, views: views)) NSLayoutConstraint.activate(allConstraints) } func setupDataModel() { // Ask for Authorisation from the User. // self.locationManager.requestAlwaysAuthorization() // For use in foreground self.locationManager.requestWhenInUseAuthorization() if CLLocationManager.locationServicesEnabled() { locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters locationManager.startUpdatingLocation() } // init map view self.mapCardView = MapCardView(frame: CGRect(x: 0, y: 0, width: 400, height: 400)) self.mapCardView!.translatesAutoresizingMaskIntoConstraints = false self.challenges = Challenge.GetActiveList() self.player = Player.SharedInstance() for c in self.challenges { self.mapCardView?.addMarker(latitude: c.latitude, longitue: c.longitude) } } } extension CityViewViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 2 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 0 { return 1 } else { return self.challenges.count } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.section == 0 { let cell = tableView.dequeueReusableCell(withIdentifier: "LabelCell", for: indexPath) cell.selectionStyle = .none if let mapView = self.mapCardView { cell.contentView.addSubview(mapView) NSLayoutConstraint.activate(NSLayoutConstraint.fillSuperview(view: mapView)) } return cell } else { let cell = tableView.dequeueReusableCell(withIdentifier: "LabelCell", for: indexPath) if indexPath.row < self.challenges.count { let challenge = self.challenges[indexPath.row] cell.textLabel?.text = challenge.name cell.detailTextLabel?.text = "\(challenge.points) points" } return cell } } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if section == 0 { return "" } else { return "Challenges near Me" } } } extension CityViewViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if section == 0 { return 0.01 } else { return 30 } } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if indexPath.section == 0 { return 400 } else { return 80 } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { self.tableView?.deselectRow(at: indexPath, animated: true) // let vc = ChallengeViewController() // self.navigationController?.present(vc, animated: true, completion: nil) } } extension CityViewViewController: CLLocationManagerDelegate { func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let locValue:CLLocationCoordinate2D = manager.location!.coordinate // let camera = GMSCameraPosition.camera(withLatitude: locValue.latitude, // longitude: locValue.longitude, // zoom: 16) self.mapCardView?.moveCurrentMarker(latitude: locValue.latitude, longitue: locValue.longitude) self.mapCardView?.updateCameraPosition(latitude: locValue.latitude, longitue: locValue.longitude) } }
apache-2.0
207b9ec818abb03611e24eec3a5192c4
32.163265
108
0.613692
5.584192
false
false
false
false
DungFu/TrafficSweetSpot
TrafficSweetSpot/PreferencesWindow.swift
1
5651
// // PreferencesWindow.swift // TrafficSweetSpot // // Created by Freddie Meyer on 7/19/16. // Copyright © 2016 Freddie Meyer. All rights reserved. // import Cocoa protocol PreferencesWindowDelegate { func preferencesDidUpdate() } class PreferencesWindow: NSWindowController { @IBOutlet weak var apiKeyInput: NSTextField! @IBOutlet weak var originInput: NSTextField! @IBOutlet weak var destInput: NSTextField! @IBOutlet weak var cacheInput: NSPopUpButton! @IBOutlet weak var notificationsCheckbox: NSButton! @IBOutlet weak var notificationsTimeSlider: NSSlider! @IBOutlet weak var notificationsTimeLabel: NSTextField! @IBOutlet weak var travelTimeMenuBarCheckBox: NSButton! @IBOutlet weak var checkForUpdatesCheckBox: NSButton! @IBOutlet weak var startTimeDropdown: NSPopUpButton! @IBOutlet weak var endTimeDropdown: NSPopUpButton! var delegate: PreferencesWindowDelegate? override var windowNibName : NSNib.Name? { return NSNib.Name.init("PreferencesWindow") } override func windowDidLoad() { super.windowDidLoad() self.window?.center() self.window?.title = "Preferences" NSApp.activate(ignoringOtherApps: true) self.window?.makeKeyAndOrderFront(self) let defaults = UserDefaults.standard if let apiKeyVal = defaults.string(forKey: "apiKey") { apiKeyInput.stringValue = apiKeyVal } if let originVal = defaults.string(forKey: "origin") { originInput.stringValue = originVal } if let destVal = defaults.string(forKey: "dest") { destInput.stringValue = destVal } if let cacheVal = defaults.string(forKey: "cache") { cacheInput.stringValue = cacheVal } if let notificationsEnabledVal = defaults.string(forKey: "notificationsEnabled") { notificationsCheckbox.stringValue = notificationsEnabledVal } if let notificationsTimeVal = defaults.string(forKey: "notificationsTime") { notificationsTimeSlider.stringValue = notificationsTimeVal } if let travelTimeMenuBarVal = defaults.string(forKey: "travelTimeMenuBar") { travelTimeMenuBarCheckBox.stringValue = travelTimeMenuBarVal } if let checkForUpdatesVal = defaults.string(forKey: "checkForUpdates") { checkForUpdatesCheckBox.stringValue = checkForUpdatesVal } startTimeDropdown.removeAllItems() endTimeDropdown.removeAllItems() for index in 0...23 { var hour = String(index) if (index < 10) { hour = "0" + hour } startTimeDropdown.addItem(withTitle: hour + ":00") endTimeDropdown.addItem(withTitle: hour + ":00") } if let startTimeNotifVal = defaults.string(forKey: "startTimeNotif") { startTimeDropdown.selectItem(at: Int(startTimeNotifVal) ?? 17) } else { startTimeDropdown.selectItem(at: 17) } if let endTimeNotifVal = defaults.string(forKey: "endTimeNotif") { endTimeDropdown.selectItem(at: Int(endTimeNotifVal) ?? 20) } else { endTimeDropdown.selectItem(at: 20) } updateStartTimeDropdownItems() updateEndTimeDropdownItems() updateSliderLabel() } @IBAction func onSliderUpdate(_ sender: Any) { updateSliderLabel() } @IBAction func onStartTimeDropdownUpdate(_ sender: Any) { updateEndTimeDropdownItems() } @IBAction func onEndTimeDropdownUpdate(_ sender: Any) { updateStartTimeDropdownItems() } @IBAction func saveClicked(_ sender: AnyObject) { let defaults = UserDefaults.standard defaults.setValue(apiKeyInput.stringValue, forKey: "apiKey") defaults.setValue(originInput.stringValue, forKey: "origin") defaults.setValue(destInput.stringValue, forKey: "dest") defaults.setValue(cacheInput.stringValue, forKey: "cache") defaults.setValue(notificationsCheckbox.stringValue, forKey: "notificationsEnabled") defaults.setValue(notificationsTimeSlider.stringValue, forKey: "notificationsTime") defaults.setValue(travelTimeMenuBarCheckBox.stringValue, forKey: "travelTimeMenuBar") defaults.setValue(checkForUpdatesCheckBox.stringValue, forKey: "checkForUpdates") defaults.setValue(String(startTimeDropdown.indexOfSelectedItem), forKey: "startTimeNotif") defaults.setValue(String(endTimeDropdown.indexOfSelectedItem), forKey: "endTimeNotif") defaults.synchronize() delegate?.preferencesDidUpdate() self.window?.close() } func updateSliderLabel() { notificationsTimeSlider.integerValue = Int(notificationsTimeSlider.floatValue.rounded()) let value = notificationsTimeSlider.integerValue var hours = String(value / 60) if (hours.count < 2) { hours = "0" + hours } var minutes = String(value % 60) if (minutes.count < 2) { minutes = "0" + minutes } notificationsTimeLabel.stringValue = hours + ":" + minutes } func updateStartTimeDropdownItems() { for item in startTimeDropdown.itemArray { item.isHidden = startTimeDropdown.index(of: item) >= endTimeDropdown.indexOfSelectedItem } } func updateEndTimeDropdownItems() { for item in endTimeDropdown.itemArray { item.isHidden = endTimeDropdown.index(of: item) <= startTimeDropdown.indexOfSelectedItem } } }
mit
f306dd01098ed6c6f81e2a11ad312ad7
38.236111
100
0.667257
4.951797
false
false
false
false
AshuMishra/BMSLocationFinder
BMSLocationFinder/BMSLocationFinder/Controller Classes/BMSListViewController.swift
1
9856
// // BMSListViewController.swift // BMSLocationFinder // // Created by Ashutosh on 03/04/2015. // Copyright (c) 2015 Ashutosh. All rights reserved. // import Foundation import UIKit import CoreLocation import CoreData class BMSListViewController: UIViewController, ENSideMenuDelegate { @IBOutlet weak var listTableView: UITableView! var placesArray: NSArray? var currentPlaceType: PlaceType = .Food var radius: Int = 5000 var shouldShowLoadMore: Bool = false var shouldShowFavorite: Bool = false var isLoadingData:Bool = false var refreshControl: UIRefreshControl! var footerView: UIView? @IBOutlet weak var noResultMessageLabel: UILabel! @IBOutlet weak var noResultScreen: UIImageView! //MARK: View LifeCycle Methods:- override func viewDidLoad() { super.viewDidLoad() placesArray = NSArray() listTableView.tableFooterView = UIView()// To hide cell layout while there is no cell self.initFooterView() //To add pull to refresh in tableview. self.refreshControl = UIRefreshControl() self.refreshControl.attributedTitle = NSAttributedString(string: "Pull to refersh") self.refreshControl.addTarget(self, action: "refreshPlace:", forControlEvents: UIControlEvents.ValueChanged) self.listTableView.addSubview(refreshControl) self.configureTable() } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } //MARK: User defined methods:- func configureTable() { // To check from where to show values in UITableView if (!self.shouldShowFavorite) { self.navigationItem.title = self.stringForPlaceType(self.currentPlaceType).capitalizedString self.configureForPlaceType() } else { self.navigationItem.title = "Favorites" self.configureForFavorites() } } func refreshPlace(sender:AnyObject) { //Pull to refresh method self.configureForPlaceType() } func configureForFavorites() { //To fetch data from favorites. self.placesArray = DataModel.sharedModel.fetchFavoritePlaces() self.updateViews() } func configureForPlaceType() { self.sideMenuController()?.sideMenu?.delegate = self var checkInternetConnection:Bool = IJReachability.isConnectedToNetwork() if checkInternetConnection { BMSUtil.showProressHUD() BMSNetworkManager.sharedInstance.fetchLocation({(location:CLLocation?,error:NSError?) -> () in if (error != nil) { UIAlertView(title: "Error", message: "Location could not be updated. Please check internet connection and settings and try again", delegate: nil, cancelButtonTitle: "OK").show() }else { //To make url for downloading first page. BMSNetworkManager.sharedInstance.updatePlacePaginator(radius: self.radius, type: self.stringForPlaceType(self.currentPlaceType)) //To hit web service to get data BMSNetworkManager.sharedInstance.placePaginator?.loadFirst({ (result, error, allPagesLoaded) -> () in self.updatePlacesArray(result) self.shouldShowLoadMore = true self.updateViews() BMSUtil.hideProgressHUD() self.refreshControl.endRefreshing() }) } }) } else { //To hide refresh control self.refreshControl.endRefreshing() self.shouldShowLoadMore = true UIAlertView(title: "Error", message: "Device is not connected to internet. Please check connection and try again.", delegate: nil, cancelButtonTitle: "OK").show() } } func updateViews() { self.noResultMessageLabel.text = self.shouldShowFavorite ? "No Favorites yet." : "Please increase the radius of search." if self.placesArray?.count == 0 { self.noResultScreen.hidden = false self.listTableView.hidden = true }else { self.noResultScreen.hidden = true self.listTableView.hidden = false self.listTableView.reloadData() } } func initFooterView() { //Make custom footer view to indicate load more data footerView = UIView(frame: CGRectMake(0.0, 0.0, 320.0, 60.0)) var activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .Gray) activityIndicator.tag = 10 activityIndicator.frame = CGRectMake(160, 15.0, 30, 30.0) activityIndicator.hidesWhenStopped = true footerView?.addSubview(activityIndicator) } func stringForPlaceType(placetype:PlaceType)-> NSString! { switch(placetype) { case PlaceType.Food: return "food" case PlaceType.Gym: return "gym" case PlaceType.Hospital: return "hospital" case PlaceType.Restaurant: return "restaurant" case PlaceType.School: return "school" case PlaceType.Spa: return "spa" } } // MARK: - ENSideMenu Delegate func sideMenuWillOpen() { self.view.userInteractionEnabled = false println("sideMenuWillOpen") } func sideMenuWillClose() { println("sideMenuWillClose") self.view.userInteractionEnabled = true } func sideMenuShouldOpenSideMenu() -> Bool { println("sideMenuShouldOpenSideMenu") return true; } //MARK: IBAction Methods:- @IBAction func popoverButtonPressed(sender: AnyObject) { //Toggle slide menu toggleSideMenuView() } //MARK: UITableView Datasource and Delegate Methods: func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return(self.placesArray)?.count ?? 0 } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 60.0 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var currentPlace: Place = self.placesArray?.objectAtIndex(indexPath.row) as Place let cell = tableView.dequeueReusableCellWithIdentifier("listCell", forIndexPath: indexPath) as ListCell cell.backgroundColor = UIColor.whiteColor() cell.separatorInset = UIEdgeInsetsMake(0.0, cell.frame.size.width, 0.0, cell.frame.size.width) //Configure cell to show data cell.configure(placeObject: self.placesArray?.objectAtIndex(indexPath.row) as Place) return cell } func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { if (indexPath.row == self.placesArray!.count - 1 && self.shouldShowLoadMore && !isLoadingData) { println("should show loading") self.isLoadingData = true self.listTableView.tableFooterView = self.footerView (self.footerView?.viewWithTag(10) as UIActivityIndicatorView).startAnimating() //To load more data if exists var checkInternetConnection:Bool = IJReachability.isConnectedToNetwork() if checkInternetConnection { BMSNetworkManager.sharedInstance.placePaginator?.loadNext({ (result, error, allPagesLoaded) -> () in self.isLoadingData = false self.updatePlacesArray(result) self.shouldShowLoadMore = !allPagesLoaded self.listTableView.reloadData() BMSUtil.hideProgressHUD() }) } else { UIAlertView(title: "Error", message: "Device is not connected to internet. Please check connection and try again.", delegate: nil, cancelButtonTitle: "OK").show() } }else { (self.footerView?.viewWithTag(10) as UIActivityIndicatorView).stopAnimating() self.listTableView.tableFooterView = UIView() } } func updatePlacesArray(result:NSArray?) { var newPlaceArray = NSMutableArray() for (var i = 0 ; i < result?.count ; i++) { var place = Place(dictionary: result?[i] as NSDictionary) newPlaceArray.addObject(place) } self.placesArray = newPlaceArray var descriptor: NSSortDescriptor? = NSSortDescriptor(key: "distance", ascending: true)//Sort the array according to it's distance var sortedResults: NSArray = self.placesArray!.sortedArrayUsingDescriptors(NSArray(object: descriptor!)) self.placesArray = sortedResults } func registerNotification() { //Register notification to load the table with new data NSNotificationCenter.defaultCenter().addObserver( self, selector: "configureTable", name: notificationStruct.didSetFavorite, object: nil) } //MARK: Segue Method:- override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { self.registerNotification() var destinationController = segue.destinationViewController as BMSDetailViewController var indexPath: NSIndexPath = self.listTableView.indexPathForSelectedRow()! destinationController.currentPlace = self.placesArray?.objectAtIndex(indexPath.row) as? Place } }
mit
12a803e70ee9fd0643ce24107c025f43
38.266932
197
0.633827
5.39759
false
false
false
false
saitjr/STBurgerButtonManager
BurgerButtonManager-class/BurgerButtonManager-class/BurgerButtonManager.swift
1
1219
// // BurgerButtonManager.swift // BurgerButtonManager-class // // Created by TangJR on 2/8/16. // Copyright © 2016 tangjr. All rights reserved. // import UIKit typealias STBarButtonItemBlock = ()->() class BlockBarButtonItem: UIBarButtonItem { var block: STBarButtonItemBlock? convenience init(title: String, style: UIBarButtonItemStyle, block: STBarButtonItemBlock) { self.init(title: title, style: style, target: nil, action: "buttonTapped") self.target = self self.block = block } convenience init(image: UIImage, style: UIBarButtonItemStyle, block: STBarButtonItemBlock) { self.init(image: image, style: style, target: nil, action: "buttonTapped") self.target = self self.block = block } func buttonTapped() { guard let block = block else { return } block() } } protocol BurgerButtonManager { func needBurgerButton() } extension BurgerButtonManager where Self: UIViewController { func needBurgerButton() { let item = BlockBarButtonItem(title: "菜单", style: .Plain) { print("123"); } self.navigationItem.leftBarButtonItem = item } }
mit
83d771b9adf85fa40ad8d1caf00b50ff
25.413043
96
0.649094
4.229965
false
false
false
false
tzef/BmoViewPager
Example/BmoViewPager/Extension/Color+Image.swift
1
865
// // Color+Image.swift // BmoViewPager // // Created by LEE ZHE YU on 2017/6/4. // Copyright © 2017年 CocoaPods. All rights reserved. // import UIKit extension UIColor { func darkerColor() -> UIColor { var red : CGFloat = 0 var green : CGFloat = 0 var blue : CGFloat = 0 var alpha: CGFloat = 0 self.getRed(&red, green: &green, blue: &blue, alpha: &alpha) return UIColor(red: red - 0.1, green: green - 0.1, blue: blue - 0.1, alpha: alpha) } func pixelImage() -> UIImage { let rect = CGRect(origin: .zero, size: CGSize(width: 1, height: 1)) UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0) self.setFill() UIRectFill(rect) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image! } }
mit
6a618531a9bace919feac1c867f82248
27.733333
90
0.610209
3.954128
false
false
false
false
AIEPhoenix/StringAttributesKit
Example/Tests/Tests.swift
1
1169
// https://github.com/Quick/Quick import Quick import Nimble import StringAttributesKit class TableOfContentsSpec: QuickSpec { override func spec() { describe("these will fail") { it("can do maths") { expect(1) == 2 } it("can read") { expect("number") == "string" } it("will eventually fail") { expect("time").toEventually( equal("done") ) } context("these will pass") { it("can do maths") { expect(23) == 23 } it("can read") { expect("🐮") == "🐮" } it("will eventually pass") { var time = "passing" DispatchQueue.main.async { time = "done" } waitUntil { done in Thread.sleep(forTimeInterval: 0.5) expect(time) == "done" done() } } } } } }
mit
f353492684e63a8c0bcd976c96d80d51
22.26
60
0.362855
5.538095
false
false
false
false
Jubilant-Appstudio/Scuba
Pods/IQKeyboardManagerSwift/IQKeyboardManagerSwift/IQKeyboardManager.swift
2
109208
// // IQKeyboardManager.swift // https://github.com/hackiftekhar/IQKeyboardManager // Copyright (c) 2013-16 Iftekhar Qurashi. // // 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 CoreGraphics import UIKit import QuartzCore ///--------------------- /// MARK: IQToolbar tags ///--------------------- /** Codeless drop-in universal library allows to prevent issues of keyboard sliding up and cover UITextField/UITextView. Neither need to write any code nor any setup required and much more. A generic version of KeyboardManagement. https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html */ open class IQKeyboardManager: NSObject, UIGestureRecognizerDelegate { /** Default tag for toolbar with Done button -1002. */ fileprivate static let kIQDoneButtonToolbarTag = -1002 /** Default tag for toolbar with Previous/Next buttons -1005. */ fileprivate static let kIQPreviousNextButtonToolbarTag = -1005 ///--------------------------- /// MARK: UIKeyboard handling ///--------------------------- /** Registered classes list with library. */ fileprivate var registeredClasses = [UIView.Type]() /** Enable/disable managing distance between keyboard and textField. Default is YES(Enabled when class loads in `+(void)load` method). */ open var enable = false { didSet { //If not enable, enable it. if enable == true && oldValue == false { //If keyboard is currently showing. Sending a fake notification for keyboardWillShow to adjust view according to keyboard. if _kbShowNotification != nil { keyboardWillShow(_kbShowNotification) } showLog("Enabled") } else if enable == false && oldValue == true { //If not disable, desable it. keyboardWillHide(nil) showLog("Disabled") } } } fileprivate func privateIsEnabled()-> Bool { var isEnabled = enable if let textFieldViewController = _textFieldView?.viewController() { if isEnabled == false { //If viewController is kind of enable viewController class, then assuming it's enabled. for enabledClass in enabledDistanceHandlingClasses { if textFieldViewController.isKind(of: enabledClass) { isEnabled = true break } } } if isEnabled == true { //If viewController is kind of disabled viewController class, then assuming it's disabled. for disabledClass in disabledDistanceHandlingClasses { if textFieldViewController.isKind(of: disabledClass) { isEnabled = false break } } //Special Controllers if isEnabled == true { let classNameString = NSStringFromClass(type(of:textFieldViewController.self)) //_UIAlertControllerTextFieldViewController if (classNameString.contains("UIAlertController") && classNameString.hasSuffix("TextFieldViewController")) { isEnabled = false } } } } return isEnabled } /** To set keyboard distance from textField. can't be less than zero. Default is 10.0. */ open var keyboardDistanceFromTextField: CGFloat { set { _privateKeyboardDistanceFromTextField = max(0, newValue) showLog("keyboardDistanceFromTextField: \(_privateKeyboardDistanceFromTextField)") } get { return _privateKeyboardDistanceFromTextField } } /** Boolean to know if keyboard is showing. */ open var keyboardShowing: Bool { get { return _privateIsKeyboardShowing } } /** moved distance to the top used to maintain distance between keyboard and textField. Most of the time this will be a positive value. */ open var movedDistance: CGFloat { get { return _privateMovedDistance } } /** Prevent keyboard manager to slide up the rootView to more than keyboard height. Default is YES. */ open var preventShowingBottomBlankSpace = true /** Returns the default singleton instance. */ @objc open class func sharedManager() -> IQKeyboardManager { struct Static { //Singleton instance. Initializing keyboard manger. static let kbManager = IQKeyboardManager() } /** @return Returns the default singleton instance. */ return Static.kbManager } ///------------------------- /// MARK: IQToolbar handling ///------------------------- /** Automatic add the IQToolbar functionality. Default is YES. */ open var enableAutoToolbar = true { didSet { privateIsEnableAutoToolbar() ?addToolbarIfRequired():removeToolbarIfRequired() let enableToolbar = enableAutoToolbar ? "Yes" : "NO" showLog("enableAutoToolbar: \(enableToolbar)") } } fileprivate func privateIsEnableAutoToolbar() -> Bool { var enableToolbar = enableAutoToolbar if let textFieldViewController = _textFieldView?.viewController() { if enableToolbar == false { //If found any toolbar enabled classes then return. for enabledClass in enabledToolbarClasses { if textFieldViewController.isKind(of: enabledClass) { enableToolbar = true break } } } if enableToolbar == true { //If found any toolbar disabled classes then return. for disabledClass in disabledToolbarClasses { if textFieldViewController.isKind(of: disabledClass) { enableToolbar = false break } } //Special Controllers if enableToolbar == true { let classNameString = NSStringFromClass(type(of:textFieldViewController.self)) //_UIAlertControllerTextFieldViewController if (classNameString.contains("UIAlertController") && classNameString.hasSuffix("TextFieldViewController")) { enableToolbar = false } } } } return enableToolbar } /** /** IQAutoToolbarBySubviews: Creates Toolbar according to subview's hirarchy of Textfield's in view. IQAutoToolbarByTag: Creates Toolbar according to tag property of TextField's. IQAutoToolbarByPosition: Creates Toolbar according to the y,x position of textField in it's superview coordinate. Default is IQAutoToolbarBySubviews. */ AutoToolbar managing behaviour. Default is IQAutoToolbarBySubviews. */ open var toolbarManageBehaviour = IQAutoToolbarManageBehaviour.bySubviews /** If YES, then uses textField's tintColor property for IQToolbar, otherwise tint color is black. Default is NO. */ open var shouldToolbarUsesTextFieldTintColor = false /** This is used for toolbar.tintColor when textfield.keyboardAppearance is UIKeyboardAppearanceDefault. If shouldToolbarUsesTextFieldTintColor is YES then this property is ignored. Default is nil and uses black color. */ open var toolbarTintColor : UIColor? /** This is used for toolbar.barTintColor. Default is nil and uses white color. */ open var toolbarBarTintColor : UIColor? /** IQPreviousNextDisplayModeDefault: Show NextPrevious when there are more than 1 textField otherwise hide. IQPreviousNextDisplayModeAlwaysHide: Do not show NextPrevious buttons in any case. IQPreviousNextDisplayModeAlwaysShow: Always show nextPrevious buttons, if there are more than 1 textField then both buttons will be visible but will be shown as disabled. */ open var previousNextDisplayMode = IQPreviousNextDisplayMode.Default /** Toolbar done button icon, If nothing is provided then check toolbarDoneBarButtonItemText to draw done button. */ open var toolbarDoneBarButtonItemImage : UIImage? /** Toolbar done button text, If nothing is provided then system default 'UIBarButtonSystemItemDone' will be used. */ open var toolbarDoneBarButtonItemText : String? /** If YES, then it add the textField's placeholder text on IQToolbar. Default is YES. */ @available(*,deprecated, message: "This is renamed to `shouldShowToolbarPlaceholder` for more clear naming.") open var shouldShowTextFieldPlaceholder: Bool { set { shouldShowToolbarPlaceholder = newValue } get { return shouldShowToolbarPlaceholder } } open var shouldShowToolbarPlaceholder = true /** Placeholder Font. Default is nil. */ open var placeholderFont: UIFont? ///-------------------------- /// MARK: UITextView handling ///-------------------------- /** used to adjust contentInset of UITextView. */ fileprivate var startingTextViewContentInsets = UIEdgeInsets.zero /** used to adjust scrollIndicatorInsets of UITextView. */ fileprivate var startingTextViewScrollIndicatorInsets = UIEdgeInsets.zero /** used with textView to detect a textFieldView contentInset is changed or not. (Bug ID: #92)*/ fileprivate var isTextViewContentInsetChanged = false ///--------------------------------------- /// MARK: UIKeyboard appearance overriding ///--------------------------------------- /** Override the keyboardAppearance for all textField/textView. Default is NO. */ open var overrideKeyboardAppearance = false /** If overrideKeyboardAppearance is YES, then all the textField keyboardAppearance is set using this property. */ open var keyboardAppearance = UIKeyboardAppearance.default ///----------------------------------------------------------- /// MARK: UITextField/UITextView Next/Previous/Resign handling ///----------------------------------------------------------- /** Resigns Keyboard on touching outside of UITextField/View. Default is NO. */ open var shouldResignOnTouchOutside = false { didSet { _tapGesture.isEnabled = privateShouldResignOnTouchOutside() let shouldResign = shouldResignOnTouchOutside ? "Yes" : "NO" showLog("shouldResignOnTouchOutside: \(shouldResign)") } } /** TapGesture to resign keyboard on view's touch. It's a readonly property and exposed only for adding/removing dependencies if your added gesture does have collision with this one */ fileprivate var _tapGesture: UITapGestureRecognizer! open var resignFirstResponderGesture: UITapGestureRecognizer { get { return _tapGesture } } /*******************************************/ fileprivate func privateShouldResignOnTouchOutside() -> Bool { var shouldResign = shouldResignOnTouchOutside if let textFieldViewController = _textFieldView?.viewController() { if shouldResign == false { //If viewController is kind of enable viewController class, then assuming shouldResignOnTouchOutside is enabled. for enabledClass in enabledTouchResignedClasses { if textFieldViewController.isKind(of: enabledClass) { shouldResign = true break } } } if shouldResign == true { //If viewController is kind of disable viewController class, then assuming shouldResignOnTouchOutside is disable. for disabledClass in disabledTouchResignedClasses { if textFieldViewController.isKind(of: disabledClass) { shouldResign = false break } } //Special Controllers if shouldResign == true { let classNameString = NSStringFromClass(type(of:textFieldViewController.self)) //_UIAlertControllerTextFieldViewController if (classNameString.contains("UIAlertController") && classNameString.hasSuffix("TextFieldViewController")) { shouldResign = false } } } } return shouldResign } /** Resigns currently first responder field. */ @discardableResult open func resignFirstResponder()-> Bool { if let textFieldRetain = _textFieldView { //Resigning first responder let isResignFirstResponder = textFieldRetain.resignFirstResponder() // If it refuses then becoming it as first responder again. (Bug ID: #96) if isResignFirstResponder == false { //If it refuses to resign then becoming it first responder again for getting notifications callback. textFieldRetain.becomeFirstResponder() showLog("Refuses to resign first responder: \(String(describing: _textFieldView?._IQDescription()))") } return isResignFirstResponder } return false } /** Returns YES if can navigate to previous responder textField/textView, otherwise NO. */ @objc open var canGoPrevious: Bool { //Getting all responder view's. if let textFields = responderViews() { if let textFieldRetain = _textFieldView { //Getting index of current textField. if let index = textFields.index(of: textFieldRetain) { //If it is not first textField. then it's previous object canBecomeFirstResponder. if index > 0 { return true } } } } return false } /** Returns YES if can navigate to next responder textField/textView, otherwise NO. */ @objc open var canGoNext: Bool { //Getting all responder view's. if let textFields = responderViews() { if let textFieldRetain = _textFieldView { //Getting index of current textField. if let index = textFields.index(of: textFieldRetain) { //If it is not first textField. then it's previous object canBecomeFirstResponder. if index < textFields.count-1 { return true } } } } return false } /** Navigate to previous responder textField/textView. */ @objc @discardableResult open func goPrevious()-> Bool { //Getting all responder view's. if let textFieldRetain = _textFieldView { if let textFields = responderViews() { //Getting index of current textField. if let index = textFields.index(of: textFieldRetain) { //If it is not first textField. then it's previous object becomeFirstResponder. if index > 0 { let nextTextField = textFields[index-1] let isAcceptAsFirstResponder = nextTextField.becomeFirstResponder() // If it refuses then becoming previous textFieldView as first responder again. (Bug ID: #96) if isAcceptAsFirstResponder == false { //If next field refuses to become first responder then restoring old textField as first responder. textFieldRetain.becomeFirstResponder() showLog("Refuses to become first responder: \(nextTextField._IQDescription())") } return isAcceptAsFirstResponder } } } } return false } /** Navigate to next responder textField/textView. */ @objc @discardableResult open func goNext()-> Bool { //Getting all responder view's. if let textFieldRetain = _textFieldView { if let textFields = responderViews() { //Getting index of current textField. if let index = textFields.index(of: textFieldRetain) { //If it is not last textField. then it's next object becomeFirstResponder. if index < textFields.count-1 { let nextTextField = textFields[index+1] let isAcceptAsFirstResponder = nextTextField.becomeFirstResponder() // If it refuses then becoming previous textFieldView as first responder again. (Bug ID: #96) if isAcceptAsFirstResponder == false { //If next field refuses to become first responder then restoring old textField as first responder. textFieldRetain.becomeFirstResponder() showLog("Refuses to become first responder: \(nextTextField._IQDescription())") } return isAcceptAsFirstResponder } } } } return false } /** previousAction. */ @objc internal func previousAction (_ barButton : IQBarButtonItem) { //If user wants to play input Click sound. if shouldPlayInputClicks == true { //Play Input Click Sound. UIDevice.current.playInputClick() } if canGoPrevious == true { if let textFieldRetain = _textFieldView { let isAcceptAsFirstResponder = goPrevious() if isAcceptAsFirstResponder && barButton.invocation.target != nil && barButton.invocation.action != nil { UIApplication.shared.sendAction(barButton.invocation.action!, to: barButton.invocation.target, from: textFieldRetain, for: UIEvent()) } } } } /** nextAction. */ @objc internal func nextAction (_ barButton : IQBarButtonItem) { //If user wants to play input Click sound. if shouldPlayInputClicks == true { //Play Input Click Sound. UIDevice.current.playInputClick() } if canGoNext == true { if let textFieldRetain = _textFieldView { let isAcceptAsFirstResponder = goNext() if isAcceptAsFirstResponder && barButton.invocation.target != nil && barButton.invocation.action != nil { UIApplication.shared.sendAction(barButton.invocation.action!, to: barButton.invocation.target, from: textFieldRetain, for: UIEvent()) } } } } /** doneAction. Resigning current textField. */ @objc internal func doneAction (_ barButton : IQBarButtonItem) { //If user wants to play input Click sound. if shouldPlayInputClicks == true { //Play Input Click Sound. UIDevice.current.playInputClick() } if let textFieldRetain = _textFieldView { //Resign textFieldView. let isResignedFirstResponder = resignFirstResponder() if isResignedFirstResponder && barButton.invocation.target != nil && barButton.invocation.action != nil{ UIApplication.shared.sendAction(barButton.invocation.action!, to: barButton.invocation.target, from: textFieldRetain, for: UIEvent()) } } } /** Resigning on tap gesture. (Enhancement ID: #14)*/ @objc internal func tapRecognized(_ gesture: UITapGestureRecognizer) { if gesture.state == UIGestureRecognizerState.ended { //Resigning currently responder textField. _ = resignFirstResponder() } } /** Note: returning YES is guaranteed to allow simultaneous recognition. returning NO is not guaranteed to prevent simultaneous recognition, as the other gesture's delegate may return YES. */ open func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { return false } /** To not detect touch events in a subclass of UIControl, these may have added their own selector for specific work */ open func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { // Should not recognize gesture if the clicked view is either UIControl or UINavigationBar(<Back button etc...) (Bug ID: #145) for ignoreClass in touchResignedGestureIgnoreClasses { if touch.view?.isKind(of: ignoreClass) == true { return false } } return true } ///----------------------- /// MARK: UISound handling ///----------------------- /** If YES, then it plays inputClick sound on next/previous/done click. */ open var shouldPlayInputClicks = true ///--------------------------- /// MARK: UIAnimation handling ///--------------------------- /** If YES, then calls 'setNeedsLayout' and 'layoutIfNeeded' on any frame update of to viewController's view. */ open var layoutIfNeededOnUpdate = false ///----------------------------------------------- /// @name InteractivePopGestureRecognizer handling ///----------------------------------------------- /** If YES, then always consider UINavigationController.view begin point as {0,0}, this is a workaround to fix a bug #464 because there are no notification mechanism exist when UINavigationController.view.frame gets changed internally. */ open var shouldFixInteractivePopGestureRecognizer = true #if swift(>=3.2) ///------------------------------------ /// MARK: Safe Area ///------------------------------------ /** If YES, then library will try to adjust viewController.additionalSafeAreaInsets to automatically handle layout guide. Default is NO. */ open var canAdjustAdditionalSafeAreaInsets = false #endif ///------------------------------------ /// MARK: Class Level disabling methods ///------------------------------------ /** Disable distance handling within the scope of disabled distance handling viewControllers classes. Within this scope, 'enabled' property is ignored. Class should be kind of UIViewController. */ open var disabledDistanceHandlingClasses = [UIViewController.Type]() /** Enable distance handling within the scope of enabled distance handling viewControllers classes. Within this scope, 'enabled' property is ignored. Class should be kind of UIViewController. If same Class is added in disabledDistanceHandlingClasses list, then enabledDistanceHandlingClasses will be ignored. */ open var enabledDistanceHandlingClasses = [UIViewController.Type]() /** Disable automatic toolbar creation within the scope of disabled toolbar viewControllers classes. Within this scope, 'enableAutoToolbar' property is ignored. Class should be kind of UIViewController. */ open var disabledToolbarClasses = [UIViewController.Type]() /** Enable automatic toolbar creation within the scope of enabled toolbar viewControllers classes. Within this scope, 'enableAutoToolbar' property is ignored. Class should be kind of UIViewController. If same Class is added in disabledToolbarClasses list, then enabledToolbarClasses will be ignore. */ open var enabledToolbarClasses = [UIViewController.Type]() /** Allowed subclasses of UIView to add all inner textField, this will allow to navigate between textField contains in different superview. Class should be kind of UIView. */ open var toolbarPreviousNextAllowedClasses = [UIView.Type]() /** Disabled classes to ignore 'shouldResignOnTouchOutside' property, Class should be kind of UIViewController. */ open var disabledTouchResignedClasses = [UIViewController.Type]() /** Enabled classes to forcefully enable 'shouldResignOnTouchOutsite' property. Class should be kind of UIViewController. If same Class is added in disabledTouchResignedClasses list, then enabledTouchResignedClasses will be ignored. */ open var enabledTouchResignedClasses = [UIViewController.Type]() /** if shouldResignOnTouchOutside is enabled then you can customise the behaviour to not recognise gesture touches on some specific view subclasses. Class should be kind of UIView. Default is [UIControl, UINavigationBar] */ open var touchResignedGestureIgnoreClasses = [UIView.Type]() ///------------------------------------------- /// MARK: Third Party Library support /// Add TextField/TextView Notifications customised NSNotifications. For example while using YYTextView https://github.com/ibireme/YYText ///------------------------------------------- /** Add/Remove customised Notification for third party customised TextField/TextView. Please be aware that the NSNotification object must be idential to UITextField/UITextView NSNotification objects and customised TextField/TextView support must be idential to UITextField/UITextView. @param didBeginEditingNotificationName This should be identical to UITextViewTextDidBeginEditingNotification @param didEndEditingNotificationName This should be identical to UITextViewTextDidEndEditingNotification */ open func registerTextFieldViewClass(_ aClass: UIView.Type, didBeginEditingNotificationName : String, didEndEditingNotificationName : String) { registeredClasses.append(aClass) NotificationCenter.default.addObserver(self, selector: #selector(self.textFieldViewDidBeginEditing(_:)), name: NSNotification.Name(rawValue: didBeginEditingNotificationName), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(self.textFieldViewDidEndEditing(_:)), name: NSNotification.Name(rawValue: didEndEditingNotificationName), object: nil) } open func unregisterTextFieldViewClass(_ aClass: UIView.Type, didBeginEditingNotificationName : String, didEndEditingNotificationName : String) { if let index = registeredClasses.index(where: { element in return element == aClass.self }) { registeredClasses.remove(at: index) } NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: didBeginEditingNotificationName), object: nil) NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: didEndEditingNotificationName), object: nil) } /**************************************************************************************/ ///------------------------ /// MARK: Private variables ///------------------------ /*******************************************/ /** To save UITextField/UITextView object voa textField/textView notifications. */ fileprivate weak var _textFieldView: UIView? /** To save rootViewController.view.frame. */ fileprivate var _topViewBeginRect = CGRect.zero /** To save rootViewController */ fileprivate weak var _rootViewController: UIViewController? #if swift(>=3.2) /** To save additionalSafeAreaInsets of rootViewController to tweak iOS11 Safe Area */ fileprivate var _initialAdditionalSafeAreaInsets = UIEdgeInsets.zero #endif /** To save topBottomLayoutConstraint original constant */ fileprivate var _layoutGuideConstraintInitialConstant: CGFloat = 0 /** To save topBottomLayoutConstraint original constraint reference */ fileprivate weak var _layoutGuideConstraint: NSLayoutConstraint? /*******************************************/ /** Variable to save lastScrollView that was scrolled. */ fileprivate weak var _lastScrollView: UIScrollView? /** LastScrollView's initial contentOffset. */ fileprivate var _startingContentOffset = CGPoint.zero /** LastScrollView's initial scrollIndicatorInsets. */ fileprivate var _startingScrollIndicatorInsets = UIEdgeInsets.zero /** LastScrollView's initial contentInsets. */ fileprivate var _startingContentInsets = UIEdgeInsets.zero /*******************************************/ /** To save keyboardWillShowNotification. Needed for enable keyboard functionality. */ fileprivate var _kbShowNotification: Notification? /** To save keyboard size. */ fileprivate var _kbSize = CGSize.zero /** To save Status Bar size. */ fileprivate var _statusBarFrame = CGRect.zero /** To save keyboard animation duration. */ fileprivate var _animationDuration = 0.25 /** To mimic the keyboard animation */ fileprivate var _animationCurve = UIViewAnimationOptions.curveEaseOut /*******************************************/ /** Boolean to maintain keyboard is showing or it is hide. To solve rootViewController.view.frame calculations. */ fileprivate var _privateIsKeyboardShowing = false fileprivate var _privateMovedDistance : CGFloat = 0.0 /** To use with keyboardDistanceFromTextField. */ fileprivate var _privateKeyboardDistanceFromTextField: CGFloat = 10.0 /**************************************************************************************/ ///-------------------------------------- /// MARK: Initialization/Deinitialization ///-------------------------------------- /* Singleton Object Initialization. */ override init() { super.init() self.registerAllNotifications() //Creating gesture for @shouldResignOnTouchOutside. (Enhancement ID: #14) _tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.tapRecognized(_:))) _tapGesture.cancelsTouchesInView = false _tapGesture.delegate = self _tapGesture.isEnabled = shouldResignOnTouchOutside //Loading IQToolbar, IQTitleBarButtonItem, IQBarButtonItem to fix first time keyboard appearance delay (Bug ID: #550) let textField = UITextField() textField.addDoneOnKeyboardWithTarget(nil, action: #selector(self.doneAction(_:))) textField.addPreviousNextDoneOnKeyboardWithTarget(nil, previousAction: #selector(self.previousAction(_:)), nextAction: #selector(self.nextAction(_:)), doneAction: #selector(self.doneAction(_:))) disabledDistanceHandlingClasses.append(UITableViewController.self) disabledDistanceHandlingClasses.append(UIAlertController.self) disabledToolbarClasses.append(UIAlertController.self) disabledTouchResignedClasses.append(UIAlertController.self) toolbarPreviousNextAllowedClasses.append(UITableView.self) toolbarPreviousNextAllowedClasses.append(UICollectionView.self) toolbarPreviousNextAllowedClasses.append(IQPreviousNextView.self) touchResignedGestureIgnoreClasses.append(UIControl.self) touchResignedGestureIgnoreClasses.append(UINavigationBar.self) } /** Override +load method to enable KeyboardManager when class loader load IQKeyboardManager. Enabling when app starts (No need to write any code) */ /** It doesn't work from Swift 1.2 */ // override public class func load() { // super.load() // // //Enabling IQKeyboardManager. // IQKeyboardManager.sharedManager().enable = true // } deinit { // Disable the keyboard manager. enable = false //Removing notification observers on dealloc. NotificationCenter.default.removeObserver(self) } /** Getting keyWindow. */ fileprivate func keyWindow() -> UIWindow? { if let keyWindow = _textFieldView?.window { return keyWindow } else { struct Static { /** @abstract Save keyWindow object for reuse. @discussion Sometimes [[UIApplication sharedApplication] keyWindow] is returning nil between the app. */ static var keyWindow : UIWindow? } /* (Bug ID: #23, #25, #73) */ let originalKeyWindow = UIApplication.shared.keyWindow //If original key window is not nil and the cached keywindow is also not original keywindow then changing keywindow. if originalKeyWindow != nil && (Static.keyWindow == nil || Static.keyWindow != originalKeyWindow) { Static.keyWindow = originalKeyWindow } //Return KeyWindow return Static.keyWindow } } ///----------------------- /// MARK: Helper Functions ///----------------------- /* Helper function to manipulate RootViewController's frame with animation. */ fileprivate func setRootViewFrame(_ frame: CGRect) { // Getting topMost ViewController. var controller = _textFieldView?.topMostController() if controller == nil { controller = keyWindow()?.topMostWindowController() } if let unwrappedController = controller { var newFrame = frame //frame size needs to be adjusted on iOS8 due to orientation structure changes. newFrame.size = unwrappedController.view.frame.size var safeAreaNewInset = UIEdgeInsets.zero; #if swift(>=3.2) if canAdjustAdditionalSafeAreaInsets { if #available(iOS 11, *) { if let textFieldView = _textFieldView { safeAreaNewInset = _initialAdditionalSafeAreaInsets; let viewMovement : CGFloat = _topViewBeginRect.maxY - newFrame.maxY; //Maintain keyboardDistanceFromTextField var specialKeyboardDistanceFromTextField = textFieldView.keyboardDistanceFromTextField if textFieldView.isSearchBarTextField() { if let searchBar = textFieldView.superviewOfClassType(UISearchBar.self) { specialKeyboardDistanceFromTextField = searchBar.keyboardDistanceFromTextField } } let newKeyboardDistanceFromTextField = (specialKeyboardDistanceFromTextField == kIQUseDefaultKeyboardDistance) ? keyboardDistanceFromTextField : specialKeyboardDistanceFromTextField let textFieldDistance = textFieldView.frame.size.height + newKeyboardDistanceFromTextField; safeAreaNewInset.bottom += min(viewMovement, textFieldDistance); } } } #endif //Used UIViewAnimationOptionBeginFromCurrentState to minimize strange animations. UIView.animate(withDuration: _animationDuration, delay: 0, options: UIViewAnimationOptions.beginFromCurrentState.union(_animationCurve), animations: { () -> Void in #if swift(>=3.2) if self.canAdjustAdditionalSafeAreaInsets { if #available(iOS 11, *) { unwrappedController.additionalSafeAreaInsets = safeAreaNewInset; } } #endif // Setting it's new frame unwrappedController.view.frame = newFrame self.showLog("Set \(String(describing: controller?._IQDescription())) frame to : \(newFrame)") //Animating content if needed (Bug ID: #204) if self.layoutIfNeededOnUpdate == true { //Animating content (Bug ID: #160) unwrappedController.view.setNeedsLayout() unwrappedController.view.layoutIfNeeded() } }) { (animated:Bool) -> Void in} } else { // If can't get rootViewController then printing warning to user. showLog("You must set UIWindow.rootViewController in your AppDelegate to work with IQKeyboardManager") } } /* Adjusting RootViewController's frame according to interface orientation. */ fileprivate func adjustFrame() { // We are unable to get textField object while keyboard showing on UIWebView's textField. (Bug ID: #11) if _textFieldView == nil { return } let textFieldView = _textFieldView! let startTime = CACurrentMediaTime() showLog("****** \(#function) started ******") // Getting KeyWindow object. let optionalWindow = keyWindow() // Getting RootViewController. (Bug ID: #1, #4) var optionalRootController = _textFieldView?.topMostController() if optionalRootController == nil { optionalRootController = keyWindow()?.topMostWindowController() } // Converting Rectangle according to window bounds. let optionalTextFieldViewRect = textFieldView.superview?.convert(textFieldView.frame, to: optionalWindow) if optionalRootController == nil || optionalWindow == nil || optionalTextFieldViewRect == nil { return } let rootController = optionalRootController! let window = optionalWindow! let textFieldViewRect = optionalTextFieldViewRect! // Getting RootViewRect. var rootViewRect = rootController.view.frame //Getting statusBarFrame //Maintain keyboardDistanceFromTextField var specialKeyboardDistanceFromTextField = textFieldView.keyboardDistanceFromTextField if textFieldView.isSearchBarTextField() { if let searchBar = textFieldView.superviewOfClassType(UISearchBar.self) { specialKeyboardDistanceFromTextField = searchBar.keyboardDistanceFromTextField } } let newKeyboardDistanceFromTextField = (specialKeyboardDistanceFromTextField == kIQUseDefaultKeyboardDistance) ? keyboardDistanceFromTextField : specialKeyboardDistanceFromTextField var kbSize = _kbSize kbSize.height += newKeyboardDistanceFromTextField let statusBarFrame = UIApplication.shared.statusBarFrame // (Bug ID: #250) var layoutGuidePosition = IQLayoutGuidePosition.none if let viewController = textFieldView.viewController() { if let constraint = _layoutGuideConstraint { var layoutGuide : UILayoutSupport? if let itemLayoutGuide = constraint.firstItem as? UILayoutSupport { layoutGuide = itemLayoutGuide } else if let itemLayoutGuide = constraint.secondItem as? UILayoutSupport { layoutGuide = itemLayoutGuide } if let itemLayoutGuide : UILayoutSupport = layoutGuide { if (itemLayoutGuide === viewController.topLayoutGuide) //If topLayoutGuide constraint { layoutGuidePosition = .top } else if (itemLayoutGuide === viewController.bottomLayoutGuide) //If bottomLayoutGuice constraint { layoutGuidePosition = .bottom } } } } let topLayoutGuide : CGFloat = statusBarFrame.height var move : CGFloat = 0.0 // Move positive = textField is hidden. // Move negative = textField is showing. // Checking if there is bottomLayoutGuide attached (Bug ID: #250) if layoutGuidePosition == .bottom { // Calculating move position. move = textFieldViewRect.maxY-(window.frame.height-kbSize.height) } else { // Calculating move position. Common for both normal and special cases. move = min(textFieldViewRect.minY-(topLayoutGuide+5), textFieldViewRect.maxY-(window.frame.height-kbSize.height)) } showLog("Need to move: \(move)") var superScrollView : UIScrollView? = nil var superView = textFieldView.superviewOfClassType(UIScrollView.self) as? UIScrollView //Getting UIScrollView whose scrolling is enabled. // (Bug ID: #285) while let view = superView { if (view.isScrollEnabled && view.shouldIgnoreScrollingAdjustment == false) { superScrollView = view break } else { // Getting it's superScrollView. // (Enhancement ID: #21, #24) superView = view.superviewOfClassType(UIScrollView.self) as? UIScrollView } } //If there was a lastScrollView. // (Bug ID: #34) if let lastScrollView = _lastScrollView { //If we can't find current superScrollView, then setting lastScrollView to it's original form. if superScrollView == nil { showLog("Restoring \(lastScrollView._IQDescription()) contentInset to : \(_startingContentInsets) and contentOffset to : \(_startingContentOffset)") UIView.animate(withDuration: _animationDuration, delay: 0, options: UIViewAnimationOptions.beginFromCurrentState.union(_animationCurve), animations: { () -> Void in lastScrollView.contentInset = self._startingContentInsets lastScrollView.scrollIndicatorInsets = self._startingScrollIndicatorInsets }) { (animated:Bool) -> Void in } if lastScrollView.shouldRestoreScrollViewContentOffset == true { lastScrollView.setContentOffset(_startingContentOffset, animated: true) } _startingContentInsets = UIEdgeInsets.zero _startingScrollIndicatorInsets = UIEdgeInsets.zero _startingContentOffset = CGPoint.zero _lastScrollView = nil } else if superScrollView != lastScrollView { //If both scrollView's are different, then reset lastScrollView to it's original frame and setting current scrollView as last scrollView. showLog("Restoring \(lastScrollView._IQDescription()) contentInset to : \(_startingContentInsets) and contentOffset to : \(_startingContentOffset)") UIView.animate(withDuration: _animationDuration, delay: 0, options: UIViewAnimationOptions.beginFromCurrentState.union(_animationCurve), animations: { () -> Void in lastScrollView.contentInset = self._startingContentInsets lastScrollView.scrollIndicatorInsets = self._startingScrollIndicatorInsets }) { (animated:Bool) -> Void in } if lastScrollView.shouldRestoreScrollViewContentOffset == true { lastScrollView.setContentOffset(_startingContentOffset, animated: true) } _lastScrollView = superScrollView _startingContentInsets = superScrollView!.contentInset _startingScrollIndicatorInsets = superScrollView!.scrollIndicatorInsets _startingContentOffset = superScrollView!.contentOffset showLog("Saving New \(lastScrollView._IQDescription()) contentInset : \(_startingContentInsets) and contentOffset : \(_startingContentOffset)") } //Else the case where superScrollView == lastScrollView means we are on same scrollView after switching to different textField. So doing nothing, going ahead } else if let unwrappedSuperScrollView = superScrollView { //If there was no lastScrollView and we found a current scrollView. then setting it as lastScrollView. _lastScrollView = unwrappedSuperScrollView _startingContentInsets = unwrappedSuperScrollView.contentInset _startingScrollIndicatorInsets = unwrappedSuperScrollView.scrollIndicatorInsets _startingContentOffset = unwrappedSuperScrollView.contentOffset showLog("Saving \(unwrappedSuperScrollView._IQDescription()) contentInset : \(_startingContentInsets) and contentOffset : \(_startingContentOffset)") } // Special case for ScrollView. // If we found lastScrollView then setting it's contentOffset to show textField. if let lastScrollView = _lastScrollView { //Saving var lastView = textFieldView var superScrollView = _lastScrollView while let scrollView = superScrollView { //Looping in upper hierarchy until we don't found any scrollView in it's upper hirarchy till UIWindow object. if move > 0 ? (move > (-scrollView.contentOffset.y - scrollView.contentInset.top)) : scrollView.contentOffset.y>0 { var tempScrollView = scrollView.superviewOfClassType(UIScrollView.self) as? UIScrollView var nextScrollView : UIScrollView? = nil while let view = tempScrollView { if (view.isScrollEnabled && view.shouldIgnoreScrollingAdjustment == false) { nextScrollView = view break } else { tempScrollView = view.superviewOfClassType(UIScrollView.self) as? UIScrollView } } //Getting lastViewRect. if let lastViewRect = lastView.superview?.convert(lastView.frame, to: scrollView) { //Calculating the expected Y offset from move and scrollView's contentOffset. var shouldOffsetY = scrollView.contentOffset.y - min(scrollView.contentOffset.y,-move) //Rearranging the expected Y offset according to the view. shouldOffsetY = min(shouldOffsetY, lastViewRect.origin.y /*-5*/) //-5 is for good UI.//Commenting -5 (Bug ID: #69) //[_textFieldView isKindOfClass:[UITextView class]] If is a UITextView type //nextScrollView == nil If processing scrollView is last scrollView in upper hierarchy (there is no other scrollView upper hierrchy.) //[_textFieldView isKindOfClass:[UITextView class]] If is a UITextView type //shouldOffsetY >= 0 shouldOffsetY must be greater than in order to keep distance from navigationBar (Bug ID: #92) if textFieldView is UITextView == true && nextScrollView == nil && shouldOffsetY >= 0 { var maintainTopLayout : CGFloat = 0 if let navigationBarFrame = textFieldView.viewController()?.navigationController?.navigationBar.frame { maintainTopLayout = navigationBarFrame.maxY } maintainTopLayout += 10.0 //For good UI // Converting Rectangle according to window bounds. if let currentTextFieldViewRect = textFieldView.superview?.convert(textFieldView.frame, to: window) { //Calculating expected fix distance which needs to be managed from navigation bar let expectedFixDistance = currentTextFieldViewRect.minY - maintainTopLayout //Now if expectedOffsetY (superScrollView.contentOffset.y + expectedFixDistance) is lower than current shouldOffsetY, which means we're in a position where navigationBar up and hide, then reducing shouldOffsetY with expectedOffsetY (superScrollView.contentOffset.y + expectedFixDistance) shouldOffsetY = min(shouldOffsetY, scrollView.contentOffset.y + expectedFixDistance) //Setting move to 0 because now we don't want to move any view anymore (All will be managed by our contentInset logic. move = 0 } else { //Subtracting the Y offset from the move variable, because we are going to change scrollView's contentOffset.y to shouldOffsetY. move -= (shouldOffsetY-scrollView.contentOffset.y) } } else { //Subtracting the Y offset from the move variable, because we are going to change scrollView's contentOffset.y to shouldOffsetY. move -= (shouldOffsetY-scrollView.contentOffset.y) } //Getting problem while using `setContentOffset:animated:`, So I used animation API. UIView.animate(withDuration: _animationDuration, delay: 0, options: UIViewAnimationOptions.beginFromCurrentState.union(_animationCurve), animations: { () -> Void in self.showLog("Adjusting \(scrollView.contentOffset.y-shouldOffsetY) to \(scrollView._IQDescription()) ContentOffset") self.showLog("Remaining Move: \(move)") scrollView.contentOffset = CGPoint(x: scrollView.contentOffset.x, y: shouldOffsetY) }) { (animated:Bool) -> Void in } } // Getting next lastView & superScrollView. lastView = scrollView superScrollView = nextScrollView } else { break } } //Updating contentInset if let lastScrollViewRect = lastScrollView.superview?.convert(lastScrollView.frame, to: window) { let bottom : CGFloat = kbSize.height-newKeyboardDistanceFromTextField-(window.frame.height-lastScrollViewRect.maxY) // Update the insets so that the scroll vew doesn't shift incorrectly when the offset is near the bottom of the scroll view. var movedInsets = lastScrollView.contentInset movedInsets.bottom = max(_startingContentInsets.bottom, bottom) showLog("\(lastScrollView._IQDescription()) old ContentInset : \(lastScrollView.contentInset)") //Getting problem while using `setContentOffset:animated:`, So I used animation API. UIView.animate(withDuration: _animationDuration, delay: 0, options: UIViewAnimationOptions.beginFromCurrentState.union(_animationCurve), animations: { () -> Void in lastScrollView.contentInset = movedInsets var newInset = lastScrollView.scrollIndicatorInsets newInset.bottom = movedInsets.bottom lastScrollView.scrollIndicatorInsets = newInset }) { (animated:Bool) -> Void in } showLog("\(lastScrollView._IQDescription()) new ContentInset : \(lastScrollView.contentInset)") } } //Going ahead. No else if. if layoutGuidePosition == .top { if let constraint = _layoutGuideConstraint { let constant = min(_layoutGuideConstraintInitialConstant, constraint.constant-move) UIView.animate(withDuration: _animationDuration, delay: 0, options: (_animationCurve.union(UIViewAnimationOptions.beginFromCurrentState)), animations: { () -> Void in constraint.constant = constant self._rootViewController?.view.setNeedsLayout() self._rootViewController?.view.layoutIfNeeded() }, completion: { (finished) -> Void in }) } } else if layoutGuidePosition == .bottom { if let constraint = _layoutGuideConstraint { let constant = max(_layoutGuideConstraintInitialConstant, constraint.constant+move) UIView.animate(withDuration: _animationDuration, delay: 0, options: (_animationCurve.union(UIViewAnimationOptions.beginFromCurrentState)), animations: { () -> Void in constraint.constant = constant self._rootViewController?.view.setNeedsLayout() self._rootViewController?.view.layoutIfNeeded() }, completion: { (finished) -> Void in }) } } else { //Special case for UITextView(Readjusting textView.contentInset when textView hight is too big to fit on screen) //_lastScrollView If not having inside any scrollView, (now contentInset manages the full screen textView. //[_textFieldView isKindOfClass:[UITextView class]] If is a UITextView type if let textView = textFieldView as? UITextView { let textViewHeight = min(textView.frame.height, (window.frame.height-kbSize.height-(topLayoutGuide))) if (textView.frame.size.height-textView.contentInset.bottom>textViewHeight) { UIView.animate(withDuration: _animationDuration, delay: 0, options: (_animationCurve.union(UIViewAnimationOptions.beginFromCurrentState)), animations: { () -> Void in self.showLog("\(textFieldView._IQDescription()) Old UITextView.contentInset : \(textView.contentInset)") //_isTextViewContentInsetChanged, If frame is not change by library in past, then saving user textView properties (Bug ID: #92) if (self.isTextViewContentInsetChanged == false) { self.startingTextViewContentInsets = textView.contentInset self.startingTextViewScrollIndicatorInsets = textView.scrollIndicatorInsets } var newContentInset = textView.contentInset newContentInset.bottom = textView.frame.size.height-textViewHeight textView.contentInset = newContentInset textView.scrollIndicatorInsets = newContentInset self.isTextViewContentInsetChanged = true self.showLog("\(textFieldView._IQDescription()) Old UITextView.contentInset : \(textView.contentInset)") }, completion: { (finished) -> Void in }) } } // Special case for iPad modalPresentationStyle. if rootController.modalPresentationStyle == UIModalPresentationStyle.formSheet || rootController.modalPresentationStyle == UIModalPresentationStyle.pageSheet { showLog("Found Special case for Model Presentation Style: \(rootController.modalPresentationStyle)") // +Positive or zero. if move >= 0 { // We should only manipulate y. rootViewRect.origin.y -= move // From now prevent keyboard manager to slide up the rootView to more than keyboard height. (Bug ID: #93) if preventShowingBottomBlankSpace == true { let minimumY: CGFloat = (window.frame.height-rootViewRect.size.height-topLayoutGuide)/2-(kbSize.height-newKeyboardDistanceFromTextField) rootViewRect.origin.y = max(rootViewRect.minY, minimumY) } showLog("Moving Upward") // Setting adjusted rootViewRect setRootViewFrame(rootViewRect) _privateMovedDistance = (_topViewBeginRect.origin.y-rootViewRect.origin.y) } else { // -Negative // Calculating disturbed distance. Pull Request #3 let disturbDistance = rootViewRect.minY-_topViewBeginRect.minY // disturbDistance Negative = frame disturbed. // disturbDistance positive = frame not disturbed. if disturbDistance <= 0 { // We should only manipulate y. rootViewRect.origin.y -= max(move, disturbDistance) showLog("Moving Downward") // Setting adjusted rootViewRect setRootViewFrame(rootViewRect) _privateMovedDistance = (_topViewBeginRect.origin.y-rootViewRect.origin.y) } } } else { //If presentation style is neither UIModalPresentationFormSheet nor UIModalPresentationPageSheet then going ahead.(General case) // +Positive or zero. if move >= 0 { rootViewRect.origin.y -= move // From now prevent keyboard manager to slide up the rootView to more than keyboard height. (Bug ID: #93) if preventShowingBottomBlankSpace == true { rootViewRect.origin.y = max(rootViewRect.origin.y, min(0, -kbSize.height+newKeyboardDistanceFromTextField)) } showLog("Moving Upward") // Setting adjusted rootViewRect setRootViewFrame(rootViewRect) _privateMovedDistance = (_topViewBeginRect.origin.y-rootViewRect.origin.y) } else { // -Negative let disturbDistance : CGFloat = rootViewRect.minY-_topViewBeginRect.minY // disturbDistance Negative = frame disturbed. // disturbDistance positive = frame not disturbed. if disturbDistance <= 0 { rootViewRect.origin.y -= max(move, disturbDistance) showLog("Moving Downward") // Setting adjusted rootViewRect // Setting adjusted rootViewRect setRootViewFrame(rootViewRect) _privateMovedDistance = (_topViewBeginRect.origin.y-rootViewRect.origin.y) } } } } let elapsedTime = CACurrentMediaTime() - startTime showLog("****** \(#function) ended: \(elapsedTime) seconds ******") } ///--------------------- /// MARK: Public Methods ///--------------------- /* Refreshes textField/textView position if any external changes is explicitly made by user. */ open func reloadLayoutIfNeeded() -> Void { if privateIsEnabled() == true { if _textFieldView != nil && _privateIsKeyboardShowing == true && _topViewBeginRect.equalTo(CGRect.zero) == false && _textFieldView?.isAlertViewTextField() == false { adjustFrame() } } } ///------------------------------- /// MARK: UIKeyboard Notifications ///------------------------------- /* UIKeyboardWillShowNotification. */ @objc internal func keyboardWillShow(_ notification : Notification?) -> Void { _kbShowNotification = notification // Boolean to know keyboard is showing/hiding _privateIsKeyboardShowing = true let oldKBSize = _kbSize if let info = (notification as NSNotification?)?.userInfo { // Getting keyboard animation. if let curve = (info[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber)?.uintValue { _animationCurve = UIViewAnimationOptions(rawValue: curve) } else { _animationCurve = UIViewAnimationOptions.curveEaseOut } // Getting keyboard animation duration if let duration = (info[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue { //Saving animation duration if duration != 0.0 { _animationDuration = duration } } else { _animationDuration = 0.25 } // Getting UIKeyboardSize. if let kbFrame = (info[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue { let screenSize = UIScreen.main.bounds //Calculating actual keyboard displayed size, keyboard frame may be different when hardware keyboard is attached (Bug ID: #469) (Bug ID: #381) let intersectRect = kbFrame.intersection(screenSize) if intersectRect.isNull { _kbSize = CGSize(width: screenSize.size.width, height: 0) } else { _kbSize = intersectRect.size } showLog("UIKeyboard Size : \(_kbSize)") } } if privateIsEnabled() == false { return } let startTime = CACurrentMediaTime() showLog("****** \(#function) started ******") // (Bug ID: #5) if _textFieldView != nil && _topViewBeginRect.equalTo(CGRect.zero) == true { // keyboard is not showing(At the beginning only). We should save rootViewRect. if let constraint = _textFieldView?.viewController()?.IQLayoutGuideConstraint { _layoutGuideConstraint = constraint _layoutGuideConstraintInitialConstant = constraint.constant } // keyboard is not showing(At the beginning only). We should save rootViewRect. _rootViewController = _textFieldView?.topMostController() if _rootViewController == nil { _rootViewController = keyWindow()?.topMostWindowController() } if let unwrappedRootController = _rootViewController { _topViewBeginRect = unwrappedRootController.view.frame #if swift(>=3.2) if #available(iOS 11, *) { _initialAdditionalSafeAreaInsets = unwrappedRootController.additionalSafeAreaInsets; } #endif if _topViewBeginRect.origin.y != 0 && shouldFixInteractivePopGestureRecognizer == true && unwrappedRootController is UINavigationController && unwrappedRootController.modalPresentationStyle != UIModalPresentationStyle.formSheet && unwrappedRootController.modalPresentationStyle != UIModalPresentationStyle.pageSheet { if let window = keyWindow() { _topViewBeginRect.origin.y = window.frame.size.height-unwrappedRootController.view.frame.size.height } else { _topViewBeginRect.origin.y = 0 } } showLog("Saving \(unwrappedRootController._IQDescription()) beginning Frame: \(_topViewBeginRect)") } else { _topViewBeginRect = CGRect.zero } } // Getting topMost ViewController. var topMostController = _textFieldView?.topMostController() if topMostController == nil { topMostController = keyWindow()?.topMostWindowController() } //If last restored keyboard size is different(any orientation accure), then refresh. otherwise not. if _kbSize.equalTo(oldKBSize) == false { //If _textFieldView is inside UITableViewController then let UITableViewController to handle it (Bug ID: #37) (Bug ID: #76) See note:- https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html If it is UIAlertView textField then do not affect anything (Bug ID: #70). if _privateIsKeyboardShowing == true && _textFieldView != nil && _textFieldView?.isAlertViewTextField() == false { // keyboard is already showing. adjust frame. adjustFrame() } } let elapsedTime = CACurrentMediaTime() - startTime showLog("****** \(#function) ended: \(elapsedTime) seconds ******") } /* UIKeyboardDidShowNotification. */ @objc internal func keyboardDidShow(_ notification : Notification?) -> Void { if privateIsEnabled() == false { return } let startTime = CACurrentMediaTime() showLog("****** \(#function) started ******") // Getting topMost ViewController. var topMostController = _textFieldView?.topMostController() if topMostController == nil { topMostController = keyWindow()?.topMostWindowController() } if _textFieldView != nil && (topMostController?.modalPresentationStyle == UIModalPresentationStyle.formSheet || topMostController?.modalPresentationStyle == UIModalPresentationStyle.pageSheet) && _textFieldView?.isAlertViewTextField() == false { //In case of form sheet or page sheet, we'll add adjustFrame call in main queue to perform it when UI thread will do all framing updation so adjustFrame will be executed after all internal operations. OperationQueue.main.addOperation { self.adjustFrame() } } let elapsedTime = CACurrentMediaTime() - startTime showLog("****** \(#function) ended: \(elapsedTime) seconds ******") } /* UIKeyboardWillHideNotification. So setting rootViewController to it's default frame. */ @objc internal func keyboardWillHide(_ notification : Notification?) -> Void { //If it's not a fake notification generated by [self setEnable:NO]. if notification != nil { _kbShowNotification = nil } // Boolean to know keyboard is showing/hiding _privateIsKeyboardShowing = false let info : [AnyHashable: Any]? = (notification as NSNotification?)?.userInfo // Getting keyboard animation duration if let duration = (info?[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue { if duration != 0 { // Setitng keyboard animation duration _animationDuration = duration } } //If not enabled then do nothing. if privateIsEnabled() == false { return } let startTime = CACurrentMediaTime() showLog("****** \(#function) started ******") //Commented due to #56. Added all the conditions below to handle UIWebView's textFields. (Bug ID: #56) // We are unable to get textField object while keyboard showing on UIWebView's textField. (Bug ID: #11) // if (_textFieldView == nil) return //Restoring the contentOffset of the lastScrollView if let lastScrollView = _lastScrollView { UIView.animate(withDuration: _animationDuration, delay: 0, options: UIViewAnimationOptions.beginFromCurrentState.union(_animationCurve), animations: { () -> Void in lastScrollView.contentInset = self._startingContentInsets lastScrollView.scrollIndicatorInsets = self._startingScrollIndicatorInsets if lastScrollView.shouldRestoreScrollViewContentOffset == true { lastScrollView.contentOffset = self._startingContentOffset } self.showLog("Restoring \(lastScrollView._IQDescription()) contentInset to : \(self._startingContentInsets) and contentOffset to : \(self._startingContentOffset)") // TODO: restore scrollView state // This is temporary solution. Have to implement the save and restore scrollView state var superScrollView : UIScrollView? = lastScrollView while let scrollView = superScrollView { let contentSize = CGSize(width: max(scrollView.contentSize.width, scrollView.frame.width), height: max(scrollView.contentSize.height, scrollView.frame.height)) let minimumY = contentSize.height - scrollView.frame.height if minimumY < scrollView.contentOffset.y { scrollView.contentOffset = CGPoint(x: scrollView.contentOffset.x, y: minimumY) self.showLog("Restoring \(scrollView._IQDescription()) contentOffset to : \(self._startingContentOffset)") } superScrollView = scrollView.superviewOfClassType(UIScrollView.self) as? UIScrollView } }) { (finished) -> Void in } } // Setting rootViewController frame to it's original position. // (Bug ID: #18) if _topViewBeginRect.equalTo(CGRect.zero) == false { if let rootViewController = _rootViewController { //frame size needs to be adjusted on iOS8 due to orientation API changes. _topViewBeginRect.size = rootViewController.view.frame.size //Used UIViewAnimationOptionBeginFromCurrentState to minimize strange animations. UIView.animate(withDuration: _animationDuration, delay: 0, options: UIViewAnimationOptions.beginFromCurrentState.union(_animationCurve), animations: { () -> Void in if let constraint = self._layoutGuideConstraint { constraint.constant = self._layoutGuideConstraintInitialConstant rootViewController.view.setNeedsLayout() rootViewController.view.layoutIfNeeded() } else { self.showLog("Restoring \(rootViewController._IQDescription()) frame to : \(self._topViewBeginRect)") // Setting it's new frame rootViewController.view.frame = self._topViewBeginRect #if swift(>=3.2) if #available(iOS 11, *) { rootViewController.additionalSafeAreaInsets = self._initialAdditionalSafeAreaInsets; } #endif self._privateMovedDistance = 0 //Animating content if needed (Bug ID: #204) if self.layoutIfNeededOnUpdate == true { //Animating content (Bug ID: #160) rootViewController.view.setNeedsLayout() rootViewController.view.layoutIfNeeded() } } }) { (finished) -> Void in } _rootViewController = nil } } else if let constraint = self._layoutGuideConstraint { if let rootViewController = _rootViewController { UIView.animate(withDuration: _animationDuration, delay: 0, options: UIViewAnimationOptions.beginFromCurrentState.union(_animationCurve), animations: { () -> Void in constraint.constant = self._layoutGuideConstraintInitialConstant rootViewController.view.setNeedsLayout() rootViewController.view.layoutIfNeeded() }) { (finished) -> Void in } } } //Reset all values _lastScrollView = nil _kbSize = CGSize.zero _layoutGuideConstraint = nil _layoutGuideConstraintInitialConstant = 0 _startingContentInsets = UIEdgeInsets.zero _startingScrollIndicatorInsets = UIEdgeInsets.zero _startingContentOffset = CGPoint.zero // topViewBeginRect = CGRectZero //Commented due to #82 let elapsedTime = CACurrentMediaTime() - startTime showLog("****** \(#function) ended: \(elapsedTime) seconds ******") } @objc internal func keyboardDidHide(_ notification:Notification) { let startTime = CACurrentMediaTime() showLog("****** \(#function) started ******") _topViewBeginRect = CGRect.zero #if swift(>=3.2) if #available(iOS 11, *) { _initialAdditionalSafeAreaInsets = .zero; } #endif _kbSize = CGSize.zero let elapsedTime = CACurrentMediaTime() - startTime showLog("****** \(#function) ended: \(elapsedTime) seconds ******") } ///------------------------------------------- /// MARK: UITextField/UITextView Notifications ///------------------------------------------- /** UITextFieldTextDidBeginEditingNotification, UITextViewTextDidBeginEditingNotification. Fetching UITextFieldView object. */ @objc internal func textFieldViewDidBeginEditing(_ notification:Notification) { let startTime = CACurrentMediaTime() showLog("****** \(#function) started ******") // Getting object _textFieldView = notification.object as? UIView if overrideKeyboardAppearance == true { if let textFieldView = _textFieldView as? UITextField { //If keyboard appearance is not like the provided appearance if textFieldView.keyboardAppearance != keyboardAppearance { //Setting textField keyboard appearance and reloading inputViews. textFieldView.keyboardAppearance = keyboardAppearance textFieldView.reloadInputViews() } } else if let textFieldView = _textFieldView as? UITextView { //If keyboard appearance is not like the provided appearance if textFieldView.keyboardAppearance != keyboardAppearance { //Setting textField keyboard appearance and reloading inputViews. textFieldView.keyboardAppearance = keyboardAppearance textFieldView.reloadInputViews() } } } //If autoToolbar enable, then add toolbar on all the UITextField/UITextView's if required. if privateIsEnableAutoToolbar() == true { //UITextView special case. Keyboard Notification is firing before textView notification so we need to resign it first and then again set it as first responder to add toolbar on it. if _textFieldView is UITextView == true && _textFieldView?.inputAccessoryView == nil { UIView.animate(withDuration: 0.00001, delay: 0, options: UIViewAnimationOptions.beginFromCurrentState.union(_animationCurve), animations: { () -> Void in self.addToolbarIfRequired() }, completion: { (finished) -> Void in //On textView toolbar didn't appear on first time, so forcing textView to reload it's inputViews. self._textFieldView?.reloadInputViews() }) } else { //Adding toolbar addToolbarIfRequired() } } else { removeToolbarIfRequired() } resignFirstResponderGesture.isEnabled = privateShouldResignOnTouchOutside() _textFieldView?.window?.addGestureRecognizer(resignFirstResponderGesture) // (Enhancement ID: #14) if privateIsEnabled() == true { if _topViewBeginRect.equalTo(CGRect.zero) == true { // (Bug ID: #5) // keyboard is not showing(At the beginning only). We should save rootViewRect. if let constraint = _textFieldView?.viewController()?.IQLayoutGuideConstraint { _layoutGuideConstraint = constraint _layoutGuideConstraintInitialConstant = constraint.constant } _rootViewController = _textFieldView?.topMostController() if _rootViewController == nil { _rootViewController = keyWindow()?.topMostWindowController() } if let rootViewController = _rootViewController { _topViewBeginRect = rootViewController.view.frame #if swift(>=3.2) if #available(iOS 11, *) { _initialAdditionalSafeAreaInsets = rootViewController.additionalSafeAreaInsets; } #endif if _topViewBeginRect.origin.y != 0 && shouldFixInteractivePopGestureRecognizer == true && rootViewController is UINavigationController && rootViewController.modalPresentationStyle != UIModalPresentationStyle.formSheet && rootViewController.modalPresentationStyle != UIModalPresentationStyle.pageSheet { if let window = keyWindow() { _topViewBeginRect.origin.y = window.frame.size.height-rootViewController.view.frame.size.height } else { _topViewBeginRect.origin.y = 0 } } showLog("Saving \(rootViewController._IQDescription()) beginning frame : \(_topViewBeginRect)") } } //If _textFieldView is inside ignored responder then do nothing. (Bug ID: #37, #74, #76) //See notes:- https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html If it is UIAlertView textField then do not affect anything (Bug ID: #70). if _privateIsKeyboardShowing == true && _textFieldView != nil && _textFieldView?.isAlertViewTextField() == false { // keyboard is already showing. adjust frame. adjustFrame() } } let elapsedTime = CACurrentMediaTime() - startTime showLog("****** \(#function) ended: \(elapsedTime) seconds ******") } /** UITextFieldTextDidEndEditingNotification, UITextViewTextDidEndEditingNotification. Removing fetched object. */ @objc internal func textFieldViewDidEndEditing(_ notification:Notification) { let startTime = CACurrentMediaTime() showLog("****** \(#function) started ******") //Removing gesture recognizer (Enhancement ID: #14) _textFieldView?.window?.removeGestureRecognizer(resignFirstResponderGesture) // We check if there's a change in original frame or not. if let textView = _textFieldView as? UITextView { if isTextViewContentInsetChanged == true { UIView.animate(withDuration: _animationDuration, delay: 0, options: UIViewAnimationOptions.beginFromCurrentState.union(_animationCurve), animations: { () -> Void in self.isTextViewContentInsetChanged = false self.showLog("Restoring \(textView._IQDescription()) textView.contentInset to : \(self.startingTextViewContentInsets)") //Setting textField to it's initial contentInset textView.contentInset = self.startingTextViewContentInsets textView.scrollIndicatorInsets = self.startingTextViewScrollIndicatorInsets }, completion: { (finished) -> Void in }) } } //Setting object to nil _textFieldView = nil let elapsedTime = CACurrentMediaTime() - startTime showLog("****** \(#function) ended: \(elapsedTime) seconds ******") } ///------------------------------------------ /// MARK: UIStatusBar Notification methods ///------------------------------------------ /** UIApplicationWillChangeStatusBarOrientationNotification. Need to set the textView to it's original position. If any frame changes made. (Bug ID: #92)*/ @objc internal func willChangeStatusBarOrientation(_ notification:Notification) { let startTime = CACurrentMediaTime() showLog("****** \(#function) started ******") //If textViewContentInsetChanged is saved then restore it. if let textView = _textFieldView as? UITextView { if isTextViewContentInsetChanged == true { UIView.animate(withDuration: _animationDuration, delay: 0, options: UIViewAnimationOptions.beginFromCurrentState.union(_animationCurve), animations: { () -> Void in self.isTextViewContentInsetChanged = false self.showLog("Restoring \(textView._IQDescription()) textView.contentInset to : \(self.startingTextViewContentInsets)") //Setting textField to it's initial contentInset textView.contentInset = self.startingTextViewContentInsets textView.scrollIndicatorInsets = self.startingTextViewScrollIndicatorInsets }, completion: { (finished) -> Void in }) } } if privateIsEnabled() == false { return } if let rootViewController = _rootViewController { #if swift(>=3.2) if #available(iOS 11, *) { if UIEdgeInsetsEqualToEdgeInsets(_initialAdditionalSafeAreaInsets, rootViewController.additionalSafeAreaInsets) { rootViewController.additionalSafeAreaInsets = _initialAdditionalSafeAreaInsets; } } #endif } let elapsedTime = CACurrentMediaTime() - startTime showLog("****** \(#function) ended: \(elapsedTime) seconds ******") } /** UIApplicationDidChangeStatusBarFrameNotification. Need to refresh view position and update _topViewBeginRect. (Bug ID: #446)*/ @objc internal func didChangeStatusBarFrame(_ notification : Notification?) -> Void { let oldStatusBarFrame = _statusBarFrame // Getting keyboard animation duration if let newFrame = ((notification as NSNotification?)?.userInfo?[UIApplicationStatusBarFrameUserInfoKey] as? NSNumber)?.cgRectValue { _statusBarFrame = newFrame } if privateIsEnabled() == false { return } let startTime = CACurrentMediaTime() showLog("****** \(#function) started ******") if _rootViewController != nil && !_topViewBeginRect.equalTo(_rootViewController!.view.frame) == true { if let unwrappedRootController = _rootViewController { _topViewBeginRect = unwrappedRootController.view.frame #if swift(>=3.2) if #available(iOS 11, *) { _initialAdditionalSafeAreaInsets = unwrappedRootController.additionalSafeAreaInsets; } #endif if _topViewBeginRect.origin.y != 0 && shouldFixInteractivePopGestureRecognizer == true && unwrappedRootController is UINavigationController && unwrappedRootController.modalPresentationStyle != UIModalPresentationStyle.formSheet && unwrappedRootController.modalPresentationStyle != UIModalPresentationStyle.pageSheet { if let window = keyWindow() { _topViewBeginRect.origin.y = window.frame.size.height-unwrappedRootController.view.frame.size.height } else { _topViewBeginRect.origin.y = 0 } } showLog("Saving \(unwrappedRootController._IQDescription()) beginning Frame: \(_topViewBeginRect)") } else { _topViewBeginRect = CGRect.zero } } //If _textFieldView is inside UITableViewController then let UITableViewController to handle it (Bug ID: #37) (Bug ID: #76) See note:- https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html If it is UIAlertView textField then do not affect anything (Bug ID: #70). if _privateIsKeyboardShowing == true && _textFieldView != nil && _statusBarFrame.size.equalTo(oldStatusBarFrame.size) == false && _textFieldView?.isAlertViewTextField() == false { // keyboard is already showing. adjust frame. adjustFrame() } let elapsedTime = CACurrentMediaTime() - startTime showLog("****** \(#function) ended: \(elapsedTime) seconds ******") } ///------------------ /// MARK: AutoToolbar ///------------------ /** Get all UITextField/UITextView siblings of textFieldView. */ fileprivate func responderViews()-> [UIView]? { var superConsideredView : UIView? //If find any consider responderView in it's upper hierarchy then will get deepResponderView. for disabledClass in toolbarPreviousNextAllowedClasses { superConsideredView = _textFieldView?.superviewOfClassType(disabledClass) if superConsideredView != nil { break } } //If there is a superConsideredView in view's hierarchy, then fetching all it's subview that responds. No sorting for superConsideredView, it's by subView position. (Enhancement ID: #22) if superConsideredView != nil { return superConsideredView?.deepResponderViews() } else { //Otherwise fetching all the siblings if let textFields = _textFieldView?.responderSiblings() { //Sorting textFields according to behaviour switch toolbarManageBehaviour { //If autoToolbar behaviour is bySubviews, then returning it. case IQAutoToolbarManageBehaviour.bySubviews: return textFields //If autoToolbar behaviour is by tag, then sorting it according to tag property. case IQAutoToolbarManageBehaviour.byTag: return textFields.sortedArrayByTag() //If autoToolbar behaviour is by tag, then sorting it according to tag property. case IQAutoToolbarManageBehaviour.byPosition: return textFields.sortedArrayByPosition() } } else { return nil } } } /** Add toolbar if it is required to add on textFields and it's siblings. */ fileprivate func addToolbarIfRequired() { let startTime = CACurrentMediaTime() showLog("****** \(#function) started ******") // Getting all the sibling textFields. if let siblings = responderViews(), !siblings.isEmpty { showLog("Found \(siblings.count) responder sibling(s)") if let textField = _textFieldView { //Either there is no inputAccessoryView or if accessoryView is not appropriate for current situation(There is Previous/Next/Done toolbar). //setInputAccessoryView: check (Bug ID: #307) if textField.responds(to: #selector(setter: UITextField.inputAccessoryView)) { if textField.inputAccessoryView == nil || textField.inputAccessoryView?.tag == IQKeyboardManager.kIQPreviousNextButtonToolbarTag || textField.inputAccessoryView?.tag == IQKeyboardManager.kIQDoneButtonToolbarTag { // If only one object is found, then adding only Done button. if (siblings.count == 1 && previousNextDisplayMode == .Default) || previousNextDisplayMode == .alwaysHide { if let doneBarButtonItemImage = toolbarDoneBarButtonItemImage { textField.addRightButtonOnKeyboardWithImage(doneBarButtonItemImage, target: self, action: #selector(self.doneAction(_:)), shouldShowPlaceholder: shouldShowToolbarPlaceholder) } //Supporting Custom Done button text (Enhancement ID: #209, #411, Bug ID: #376) else if let doneBarButtonItemText = toolbarDoneBarButtonItemText { textField.addRightButtonOnKeyboardWithText(doneBarButtonItemText, target: self, action: #selector(self.doneAction(_:)), shouldShowPlaceholder: shouldShowToolbarPlaceholder) } else { //Now adding textField placeholder text as title of IQToolbar (Enhancement ID: #27) textField.addDoneOnKeyboardWithTarget(self, action: #selector(self.doneAction(_:)), shouldShowPlaceholder: shouldShowToolbarPlaceholder) } textField.inputAccessoryView?.tag = IQKeyboardManager.kIQDoneButtonToolbarTag // (Bug ID: #78) } else if (siblings.count > 1 && previousNextDisplayMode == .Default) || previousNextDisplayMode == .alwaysShow { //Supporting Custom Done button image (Enhancement ID: #366) if let doneBarButtonItemImage = toolbarDoneBarButtonItemImage { textField.addPreviousNextRightOnKeyboardWithTarget(self, rightButtonImage: doneBarButtonItemImage, previousAction: #selector(self.previousAction(_:)), nextAction: #selector(self.nextAction(_:)), rightButtonAction: #selector(self.doneAction(_:)), shouldShowPlaceholder: shouldShowToolbarPlaceholder) } //Supporting Custom Done button text (Enhancement ID: #209, #411, Bug ID: #376) else if let doneBarButtonItemText = toolbarDoneBarButtonItemText { textField.addPreviousNextRightOnKeyboardWithTarget(self, rightButtonTitle: doneBarButtonItemText, previousAction: #selector(self.previousAction(_:)), nextAction: #selector(self.nextAction(_:)), rightButtonAction: #selector(self.doneAction(_:)), shouldShowPlaceholder: shouldShowToolbarPlaceholder) } else { //Now adding textField placeholder text as title of IQToolbar (Enhancement ID: #27) textField.addPreviousNextDoneOnKeyboardWithTarget(self, previousAction: #selector(self.previousAction(_:)), nextAction: #selector(self.nextAction(_:)), doneAction: #selector(self.doneAction(_:)), shouldShowPlaceholder: shouldShowToolbarPlaceholder) } textField.inputAccessoryView?.tag = IQKeyboardManager.kIQPreviousNextButtonToolbarTag // (Bug ID: #78) } let toolbar = textField.keyboardToolbar // Setting toolbar to keyboard. if let _textField = textField as? UITextField { //Bar style according to keyboard appearance switch _textField.keyboardAppearance { case UIKeyboardAppearance.dark: toolbar.barStyle = UIBarStyle.black toolbar.tintColor = UIColor.white toolbar.barTintColor = nil default: toolbar.barStyle = UIBarStyle.default if let barTintColor = toolbarBarTintColor { toolbar.barTintColor = barTintColor } else { toolbar.barTintColor = nil } //Setting toolbar tintColor // (Enhancement ID: #30) if shouldToolbarUsesTextFieldTintColor { toolbar.tintColor = _textField.tintColor } else if let tintColor = toolbarTintColor { toolbar.tintColor = tintColor } else { toolbar.tintColor = UIColor.black } } } else if let _textView = textField as? UITextView { //Bar style according to keyboard appearance switch _textView.keyboardAppearance { case UIKeyboardAppearance.dark: toolbar.barStyle = UIBarStyle.black toolbar.tintColor = UIColor.white toolbar.barTintColor = nil default: toolbar.barStyle = UIBarStyle.default if let barTintColor = toolbarBarTintColor { toolbar.barTintColor = barTintColor } else { toolbar.barTintColor = nil } if shouldToolbarUsesTextFieldTintColor { toolbar.tintColor = _textView.tintColor } else if let tintColor = toolbarTintColor { toolbar.tintColor = tintColor } else { toolbar.tintColor = UIColor.black } } } //Setting toolbar title font. // (Enhancement ID: #30) if shouldShowToolbarPlaceholder == true && textField.shouldHideToolbarPlaceholder == false { //Updating placeholder font to toolbar. //(Bug ID: #148, #272) if toolbar.titleBarButton.title == nil || toolbar.titleBarButton.title != textField.drawingToolbarPlaceholder { toolbar.titleBarButton.title = textField.drawingToolbarPlaceholder } //Setting toolbar title font. // (Enhancement ID: #30) if placeholderFont != nil { toolbar.titleBarButton.titleFont = placeholderFont } } else { toolbar.titleBarButton.title = nil } //In case of UITableView (Special), the next/previous buttons has to be refreshed everytime. (Bug ID: #56) // If firstTextField, then previous should not be enabled. if siblings.first == textField { if (siblings.count == 1) { textField.keyboardToolbar.previousBarButton.isEnabled = false textField.keyboardToolbar.nextBarButton.isEnabled = false } else { textField.keyboardToolbar.previousBarButton.isEnabled = false textField.keyboardToolbar.nextBarButton.isEnabled = true } } else if siblings.last == textField { // If lastTextField then next should not be enaled. textField.keyboardToolbar.previousBarButton.isEnabled = true textField.keyboardToolbar.nextBarButton.isEnabled = false } else { textField.keyboardToolbar.previousBarButton.isEnabled = true textField.keyboardToolbar.nextBarButton.isEnabled = true } } } } } let elapsedTime = CACurrentMediaTime() - startTime showLog("****** \(#function) ended: \(elapsedTime) seconds ******") } /** Remove any toolbar if it is IQToolbar. */ fileprivate func removeToolbarIfRequired() { // (Bug ID: #18) let startTime = CACurrentMediaTime() showLog("****** \(#function) started ******") // Getting all the sibling textFields. if let siblings = responderViews() { showLog("Found \(siblings.count) responder sibling(s)") for view in siblings { if let toolbar = view.inputAccessoryView as? IQToolbar { //setInputAccessoryView: check (Bug ID: #307) if view.responds(to: #selector(setter: UITextField.inputAccessoryView)) && (toolbar.tag == IQKeyboardManager.kIQDoneButtonToolbarTag || toolbar.tag == IQKeyboardManager.kIQPreviousNextButtonToolbarTag) { if let textField = view as? UITextField { textField.inputAccessoryView = nil textField.reloadInputViews() } else if let textView = view as? UITextView { textView.inputAccessoryView = nil textView.reloadInputViews() } } } } } let elapsedTime = CACurrentMediaTime() - startTime showLog("****** \(#function) ended: \(elapsedTime) seconds ******") } /** reloadInputViews to reload toolbar buttons enable/disable state on the fly Enhancement ID #434. */ open func reloadInputViews() { //If enabled then adding toolbar. if privateIsEnableAutoToolbar() == true { self.addToolbarIfRequired() } else { self.removeToolbarIfRequired() } } ///------------------ /// MARK: Debugging & Developer options ///------------------ open var enableDebugging = false /** @warning Use below methods to completely enable/disable notifications registered by library internally. Please keep in mind that library is totally dependent on NSNotification of UITextField, UITextField, Keyboard etc. If you do unregisterAllNotifications then library will not work at all. You should only use below methods if you want to completedly disable all library functions. You should use below methods at your own risk. */ open func registerAllNotifications() { // Registering for keyboard notification. NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardDidShow(_:)), name: NSNotification.Name.UIKeyboardDidShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardDidHide(_:)), name: NSNotification.Name.UIKeyboardDidHide, object: nil) // Registering for UITextField notification. registerTextFieldViewClass(UITextField.self, didBeginEditingNotificationName: NSNotification.Name.UITextFieldTextDidBeginEditing.rawValue, didEndEditingNotificationName: NSNotification.Name.UITextFieldTextDidEndEditing.rawValue) // Registering for UITextView notification. registerTextFieldViewClass(UITextView.self, didBeginEditingNotificationName: NSNotification.Name.UITextViewTextDidBeginEditing.rawValue, didEndEditingNotificationName: NSNotification.Name.UITextViewTextDidEndEditing.rawValue) // Registering for orientation changes notification NotificationCenter.default.addObserver(self, selector: #selector(self.willChangeStatusBarOrientation(_:)), name: NSNotification.Name.UIApplicationWillChangeStatusBarOrientation, object: UIApplication.shared) // Registering for status bar frame change notification NotificationCenter.default.addObserver(self, selector: #selector(self.didChangeStatusBarFrame(_:)), name: NSNotification.Name.UIApplicationDidChangeStatusBarFrame, object: UIApplication.shared) } open func unregisterAllNotifications() { // Unregistering for keyboard notification. NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardDidShow, object: nil) NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil) NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardDidHide, object: nil) // Unregistering for UITextField notification. unregisterTextFieldViewClass(UITextField.self, didBeginEditingNotificationName: NSNotification.Name.UITextFieldTextDidBeginEditing.rawValue, didEndEditingNotificationName: NSNotification.Name.UITextFieldTextDidEndEditing.rawValue) // Unregistering for UITextView notification. unregisterTextFieldViewClass(UITextView.self, didBeginEditingNotificationName: NSNotification.Name.UITextViewTextDidBeginEditing.rawValue, didEndEditingNotificationName: NSNotification.Name.UITextViewTextDidEndEditing.rawValue) // Unregistering for orientation changes notification NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIApplicationWillChangeStatusBarOrientation, object: UIApplication.shared) // Unregistering for status bar frame change notification NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIApplicationDidChangeStatusBarFrame, object: UIApplication.shared) } fileprivate func showLog(_ logString: String) { if enableDebugging { print("IQKeyboardManager: " + logString) } } }
mit
6248816039eb1b4f41cbd002f2fdfabc
46.440487
434
0.573291
7.028446
false
false
false
false
brentsimmons/Evergreen
Mac/Preferences/Accounts/AccountsFeedbinWindowController.swift
1
4556
// // AccountsAddFeedbinWindowController.swift // NetNewsWire // // Created by Maurice Parker on 5/2/19. // Copyright © 2019 Ranchero Software. All rights reserved. // import AppKit import Account import RSWeb import Secrets class AccountsFeedbinWindowController: NSWindowController { @IBOutlet weak var signInTextField: NSTextField! @IBOutlet weak var noAccountTextField: NSTextField! @IBOutlet weak var createNewAccountButton: NSButton! @IBOutlet weak var progressIndicator: NSProgressIndicator! @IBOutlet weak var usernameTextField: NSTextField! @IBOutlet weak var passwordTextField: NSSecureTextField! @IBOutlet weak var errorMessageLabel: NSTextField! @IBOutlet weak var actionButton: NSButton! var account: Account? private weak var hostWindow: NSWindow? convenience init() { self.init(windowNibName: NSNib.Name("AccountsFeedbin")) } override func windowDidLoad() { if let account = account, let credentials = try? account.retrieveCredentials(type: .basic) { usernameTextField.stringValue = credentials.username actionButton.title = NSLocalizedString("Update", comment: "Update") signInTextField.stringValue = NSLocalizedString("Update your Feedbin account credentials.", comment: "SignIn") noAccountTextField.isHidden = true createNewAccountButton.isHidden = true } else { actionButton.title = NSLocalizedString("Create", comment: "Add Account") signInTextField.stringValue = NSLocalizedString("Sign in to your Feedbin account.", comment: "SignIn") } enableAutofill() usernameTextField.becomeFirstResponder() } // MARK: API func runSheetOnWindow(_ hostWindow: NSWindow, completion: ((NSApplication.ModalResponse) -> Void)? = nil) { self.hostWindow = hostWindow hostWindow.beginSheet(window!, completionHandler: completion) } // MARK: Actions @IBAction func cancel(_ sender: Any) { hostWindow!.endSheet(window!, returnCode: NSApplication.ModalResponse.cancel) } @IBAction func action(_ sender: Any) { self.errorMessageLabel.stringValue = "" guard !usernameTextField.stringValue.isEmpty && !passwordTextField.stringValue.isEmpty else { self.errorMessageLabel.stringValue = NSLocalizedString("Username & password required.", comment: "Credentials Error") return } guard account != nil || !AccountManager.shared.duplicateServiceAccount(type: .feedbin, username: usernameTextField.stringValue) else { self.errorMessageLabel.stringValue = NSLocalizedString("There is already a Feedbin account with that username created.", comment: "Duplicate Error") return } actionButton.isEnabled = false progressIndicator.isHidden = false progressIndicator.startAnimation(self) let credentials = Credentials(type: .basic, username: usernameTextField.stringValue, secret: passwordTextField.stringValue) Account.validateCredentials(type: .feedbin, credentials: credentials) { [weak self] result in guard let self = self else { return } self.actionButton.isEnabled = true self.progressIndicator.isHidden = true self.progressIndicator.stopAnimation(self) switch result { case .success(let validatedCredentials): guard let validatedCredentials = validatedCredentials else { self.errorMessageLabel.stringValue = NSLocalizedString("Invalid email/password combination.", comment: "Credentials Error") return } if self.account == nil { self.account = AccountManager.shared.createAccount(type: .feedbin) } do { try self.account?.removeCredentials(type: .basic) try self.account?.storeCredentials(validatedCredentials) self.account?.refreshAll() { result in switch result { case .success: break case .failure(let error): NSApplication.shared.presentError(error) } } self.hostWindow?.endSheet(self.window!, returnCode: NSApplication.ModalResponse.OK) } catch { self.errorMessageLabel.stringValue = NSLocalizedString("Keychain error while storing credentials.", comment: "Credentials Error") } case .failure: self.errorMessageLabel.stringValue = NSLocalizedString("Network error. Try again later.", comment: "Credentials Error") } } } @IBAction func createAccountWithProvider(_ sender: Any) { NSWorkspace.shared.open(URL(string: "https://feedbin.com/signup")!) } // MARK: Autofill func enableAutofill() { if #available(macOS 11, *) { usernameTextField.contentType = .username passwordTextField.contentType = .password } } }
mit
dfddef72be299bcc44804ea0d162696e
31.077465
151
0.738529
4.405222
false
false
false
false
raymondshadow/SwiftDemo
SwiftApp/StudyNote/StudyNote/SHRoute/Demo/swift/SNRouteModuleViewController_2.swift
1
999
// // SNRouteModuleViewController_2.swift // StudyNote // // Created by wuyp on 2020/3/16. // Copyright © 2020 Raymond. All rights reserved. // import UIKit class SNRouteModuleViewController_2: UIViewController { @objc private lazy dynamic var textLbl: UILabel = { let lbl = UILabel(frame: CGRect(x: 0, y: 200, width: ScreenWidth, height: 200)) lbl.text = "SNRouteModuleViewController_2" lbl.font = UIFont.systemFont(ofSize: 28) lbl.textAlignment = .center return lbl }() @objc override dynamic func viewDidLoad() { super.viewDidLoad() self.view.addSubview(textLbl) } @objc override dynamic func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } // MARK: - Public Method } // MARK: - Private Method extension SNRouteModuleViewController_2: SNRoutePageProtocol { @objc static dynamic func routeKey() -> [String] { return ["module_2/page_2"] } }
apache-2.0
4098726a771cb37f2ed8402bc6379c46
24.589744
87
0.646293
4.073469
false
false
false
false
abdelrahman-ahmed/QRScanner-iOS-Swift
QRScanner/QRScanner/Controller/ScannerViewController.swift
1
8394
// // ViewController.swift // QRScanner // // Created by Abdelrahman Ahmed on 5/18/16. // Copyright © 2016 Abdelrahman Ahmed. All rights reserved. // import UIKit import AVFoundation import UIKit protocol QRScannerViewControllerDelegate:class { func codeDidFound(code: String) func didFail() func didCancel() func isValidCode()->Bool } class ScannerViewController: UIViewController, AVCaptureMetadataOutputObjectsDelegate { var containerView: UIView = UIView() var headerView = UIView() var footerView = UIView() var scannerOverlayView: QRSCannerView = QRSCannerView() var notesLabel: UILabel = UILabel() var cancelButton: UIButton = UIButton() var note:String? = "Scan QR" var captureSession: AVCaptureSession! var previewLayer: AVCaptureVideoPreviewLayer! weak var delegate:QRScannerViewControllerDelegate? override func viewDidLoad() { super.viewDidLoad() setUpContainerView() setupQROverlayView() setupHeaderView() setupFooterView() view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[containerView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["containerView" : containerView])) view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[headerView(==40)][scannerOverlayView][footerView(==30)]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["scannerOverlayView" : scannerOverlayView, "headerView" : headerView, "footerView" : footerView])) view.backgroundColor = UIColor.blackColor() captureSession = AVCaptureSession() let videoCaptureDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo) let videoInput: AVCaptureDeviceInput do { videoInput = try AVCaptureDeviceInput(device: videoCaptureDevice) } catch { return } if (captureSession.canAddInput(videoInput)) { captureSession.addInput(videoInput) } else { failed() return } let metadataOutput = AVCaptureMetadataOutput() if (captureSession.canAddOutput(metadataOutput)) { captureSession.addOutput(metadataOutput) metadataOutput.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue()) metadataOutput.metadataObjectTypes = [AVMetadataObjectTypeQRCode] } else { failed() return } setupPreviewLayer() captureSession.startRunning() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if (captureSession?.running == false) { captureSession.startRunning() } } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) if (captureSession?.running == true) { captureSession.stopRunning() } } //MARK:- func setUpContainerView() { containerView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(containerView) view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[containerView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["containerView" : containerView])) } func setupQROverlayView() { scannerOverlayView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(scannerOverlayView) scannerOverlayView.backgroundColor = UIColor.clearColor() view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[scannerOverlayView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["scannerOverlayView" : scannerOverlayView])) } func setupHeaderView() { headerView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(headerView) headerView.backgroundColor = UIColor.lightGrayColor() view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[headerView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["headerView" : headerView])) setupButtons() } func setupFooterView() { footerView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(footerView) footerView.backgroundColor = UIColor.lightGrayColor() view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[footerView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["footerView" : footerView])) setupNotesLabel() } func setupButtons() { cancelButton.translatesAutoresizingMaskIntoConstraints = false cancelButton.setTitle("Cancel", forState: .Normal) cancelButton.addTarget(self, action: #selector(cancel), forControlEvents: .TouchUpInside) headerView.addSubview(cancelButton) headerView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-8-[cancelButton]->=8-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["cancelButton":cancelButton])) headerView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[cancelButton]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views:["cancelButton":cancelButton])) } func setupNotesLabel(){ notesLabel.translatesAutoresizingMaskIntoConstraints = false footerView.addSubview(notesLabel) notesLabel.text = note notesLabel.textAlignment = .Center notesLabel.textColor = UIColor.whiteColor() footerView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[notesLabel]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["notesLabel" : notesLabel])) footerView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[notesLabel]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["notesLabel" : notesLabel])) } func setupPreviewLayer() { previewLayer = AVCaptureVideoPreviewLayer(session: captureSession) previewLayer.frame = view.layer.bounds previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill containerView.layer.addSublayer(previewLayer) } //MARK:- Cancel action func cancel() { print("cancelled") dismissViewControllerAnimated(true) {[weak self] in self?.delegate?.didCancel() } } //MARK:- func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) { captureSession.stopRunning() if let metadataObject = metadataObjects.first { let readableObject = metadataObject as! AVMetadataMachineReadableCodeObject AudioServicesPlaySystemSound(SystemSoundID(kSystemSoundID_Vibrate)) foundCode(readableObject.stringValue) } } //MARK:- func foundCode(code: String) { print(code) scannerOverlayView.removeLaserLayer() if delegate?.isValidCode() == true { delegate?.codeDidFound(code) } } func failed() { let ac = UIAlertController(title: "Scanning not supported", message: "Your device does not support scanning a code from an item. Please use a device with a camera.", preferredStyle: .Alert) let alertAction = UIAlertAction(title: "OK", style: .Default) {[weak self] _ in self?.delegate?.didFail() } ac.addAction(alertAction) presentViewController(ac, animated: true, completion: nil) captureSession = nil } override func prefersStatusBarHidden() -> Bool { return true } override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { return .Portrait } }
gpl-3.0
bd29dce1843ebfd982eef5e52c216b41
33.54321
304
0.657572
6.162261
false
false
false
false
yariksmirnov/aerial
ios/Aerial.swift
1
1537
// // Session.swift // Aerial-iOS // // Created by Yaroslav Smirnov on 01/12/2016. // Copyright © 2016 Yaroslav Smirnov. All rights reserved. // import UIKit import MultipeerConnectivity import ObjectMapper import Dollar public class Aerial: NSObject { private var session = PeerSession() var device: Device? { didSet { if let _ = device { updateSubsystems() } } } public var loggers = [CorkLogger]() var container: Container? public override init() { super.init() session.delegate = self } public func startSession() { session.advertise() } func updateSubsystems() { for var logger in loggers { logger.device = device } container = Container(device: device!) sendDebugInfo() } private var inspectorInfo = [String: Any]() public func updateDebugInfo(_ info: () -> [String: Any]) { inspectorInfo = $.merge(inspectorInfo, info()) sendDebugInfo() } private func sendDebugInfo() { let records = inspectorInfo.map { InspectorRecord(title: $0.key, value: $0.value) }.toJSON() device?.service.send(event: .inspector, withData: records) } } extension Aerial: PeerSessionDelegate { func session(_ session: PeerSession, didCreate device: Device) { self.device = device } func session(_ session: PeerSession, didLost device: Device) { } }
mit
e3a4c50d76aa1dc448a8e74f9f7abc99
21.26087
100
0.589193
4.426513
false
false
false
false
yanif/circator
MetabolicCompass/NutritionManager/ViewController/NutritionixSearchViewController.swift
1
5136
// // NutritionixSearchViewController.swift // MetabolicCompassNutritionManager // // Created by Edwin L. Whitman on 7/21/16. // Copyright © 2016 Edwin L. Whitman. All rights reserved. // import UIKit class NutritionixSearchViewController: UIViewController, UISearchBarDelegate, UITableViewDataSource, UITableViewDelegate, ConfigurableStatusBar, FoodItemSelectionDelegate { let search = NutritionixSearch() let searchBar = UISearchBar() let tableView = UITableView() var didSelectFoodItem : (FoodItem->Void)? class SearchItemTableViewCell : UITableViewCell { static let CellID = "SearchItemTableViewCell" override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: .Subtitle, reuseIdentifier: reuseIdentifier) self.configureView() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } func configureView() { } } override func viewDidLoad() { super.viewDidLoad() self.searchBar.delegate = self self.tableView.delegate = self self.tableView.dataSource = self self.tableView.registerClass(SearchItemTableViewCell.self, forCellReuseIdentifier: SearchItemTableViewCell.CellID) self.configureView() } private func configureView() { self.search.searchResultsDidLoad = { self.updateUI() } self.searchBar.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(self.searchBar) let searchBarConstraints : [NSLayoutConstraint] = [ self.searchBar.topAnchor.constraintEqualToAnchor(topLayoutGuide.bottomAnchor), self.searchBar.leftAnchor.constraintEqualToAnchor(self.view.leftAnchor), self.searchBar.rightAnchor.constraintEqualToAnchor(self.view.rightAnchor) ] self.view.addConstraints(searchBarConstraints) self.tableView.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(self.tableView) let tableViewConstraints : [NSLayoutConstraint] = [ self.tableView.topAnchor.constraintEqualToAnchor(self.searchBar.bottomAnchor), self.tableView.leftAnchor.constraintEqualToAnchor(self.view.leftAnchor), self.tableView.rightAnchor.constraintEqualToAnchor(self.view.rightAnchor), self.tableView.bottomAnchor.constraintEqualToAnchor(bottomLayoutGuide.topAnchor) ] self.view.addConstraints(tableViewConstraints) } func updateUI() { self.tableView.reloadData() } // MARK: UISearchBarDelegate func searchBar(searchBar: UISearchBar, textDidChange searchText: String) { //TURN ON FOR DEMO self.search.filter = searchText } func searchBarSearchButtonClicked(searchBar: UISearchBar) { searchBar.resignFirstResponder() self.search.filter = searchBar.text } func searchBarCancelButtonClicked(searchBar: UISearchBar) { searchBar.resignFirstResponder() } // MARK: UITableViewDelegate func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { //self.searchBar.resignFirstResponder() //TODO: move to detail view controller print("selected") self.didSelectFoodItem?(self.search.results[indexPath.row]) } // MARK: UITableViewDataSource func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.search.results.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { guard let cell = self.tableView.dequeueReusableCellWithIdentifier(SearchItemTableViewCell.CellID) as? SearchItemTableViewCell else { preconditionFailure("failed to initialize table view cell") } cell.accessoryType = .DisclosureIndicator //print(self.search.results[indexPath.row].name) cell.textLabel?.text = self.search.results[indexPath.row].name cell.detailTextLabel?.text = "\(self.search.results[indexPath.row].brandName!), \(self.search.results[indexPath.row].servingQuantity) \(self.search.results[indexPath.row].servingSizeUnit!)" return cell } //status bar animation add-on var showStatusBar = true override func prefersStatusBarHidden() -> Bool { return !self.showStatusBar } override func preferredStatusBarUpdateAnimation() -> UIStatusBarAnimation { return .Slide } func showStatusBar(enabled: Bool) { self.showStatusBar = enabled UIView.animateWithDuration(0.5, animations: { self.setNeedsStatusBarAppearanceUpdate() }) } }
apache-2.0
9507f8315b33acb2329c90230e3a956a
33.233333
197
0.665044
5.763187
false
false
false
false
pjcau/LocalNotifications_Over_iOS10
Pods/SwiftDate/Sources/SwiftDate/TimeZoneName.swift
2
18860
// SwiftDate // Manage Date/Time & Timezone in Swift // // Created by: Daniele Margutti // Email: <[email protected]> // Web: <http://www.danielemargutti.com> // // Licensed under MIT License. import Foundation /// MARK: - TimeZoneName Shortcut /// This enum allows you set a valid timezone using swift's type safe support public enum TimeZoneName: String { /// Return a valid TimeZone instance from an enum public var timeZone: TimeZone { switch self { case .current: return TimeZone.current case .currentAutoUpdating: return TimeZone.autoupdatingCurrent default: return TimeZone(identifier: self.rawValue)! } } /// Return a `TimeZone` instance with a fixed number of seconds from GMT zone /// /// - parameter seconds: seconds from GMT /// /// - returns: a new `TimeZone` instance public static func secondsFromGMT(seconds: Int) -> TimeZone? { return TimeZone(secondsFromGMT: seconds) } case current = "Current" case currentAutoUpdating = "CurrentAutoUpdating" case africaAbidjan = "Africa/Abidjan" case africaAccra = "Africa/Accra" case africaAddisAbaba = "Africa/Addis_Ababa" case africaAlgiers = "Africa/Algiers" case africaAsmara = "Africa/Asmara" case africaBamako = "Africa/Bamako" case africaBangui = "Africa/Bangui" case africaBanjul = "Africa/Banjul" case africaBissau = "Africa/Bissau" case africaBlantyre = "Africa/Blantyre" case africaBrazzaville = "Africa/Brazzaville" case africaBujumbura = "Africa/Bujumbura" case africaCairo = "Africa/Cairo" case africaCasablanca = "Africa/Casablanca" case africaCeuta = "Africa/Ceuta" case africaConakry = "Africa/Conakry" case africaDakar = "Africa/Dakar" case africaDarEsSalaam = "Africa/Dar_es_Salaam" case africaDjibouti = "Africa/Djibouti" case africaDouala = "Africa/Douala" case africaElAaiun = "Africa/El_Aaiun" case africaFreetown = "Africa/Freetown" case africaGaborone = "Africa/Gaborone" case africaHarare = "Africa/Harare" case africaJohannesburg = "Africa/Johannesburg" case africaJuba = "Africa/Juba" case africaKampala = "Africa/Kampala" case africaKhartoum = "Africa/Khartoum" case fricaKigali = "Africa/Kigali" case africaKinshasa = "Africa/Kinshasa" case africaLagos = "Africa/Lagos" case africaLibreville = "Africa/Libreville" case africaLome = "Africa/Lome" case africaLuanda = "Africa/Luanda" case africaLubumbashi = "Africa/Lubumbashi" case africaLusaka = "Africa/Lusaka" case africaMalabo = "Africa/Malabo" case africaMaputo = "Africa/Maputo" case africaMaseru = "Africa/Maseru" case africaMbabane = "Africa/Mbabane" case africaMogadishu = "Africa/Mogadishu" case africaMonrovia = "Africa/Monrovia" case africaNairobi = "Africa/Nairobi" case africaNdjamena = "Africa/Ndjamena" case africaNiamey = "Africa/Niamey" case africaNouakchott = "Africa/Nouakchott" case africaOuagadougou = "Africa/Ouagadougou" case africaPortoNovo = "Africa/Porto-Novo" case africaSaoTome = "Africa/Sao_Tome" case africaTripoli = "Africa/Tripoli" case africaTunis = "Africa/Tunis" case africaWindhoek = "Africa/Windhoek" case americaAdak = "America/Adak" case americaAnchorage = "America/Anchorage" case americaAnguilla = "America/Anguilla" case americaAntigua = "America/Antigua" case americaAraguaina = "America/Araguaina" case americaArgentinaBuenosAires = "America/Argentina/Buenos_Aires" case americaArgentinaCatamarca = "America/Argentina/Catamarca" case americaArgentinaCordoba = "America/Argentina/Cordoba" case americaArgentinaJujuy = "America/Argentina/Jujuy" case americaArgentinaLaRioja = "America/Argentina/La_Rioja" case americaArgentinaMendoza = "America/Argentina/Mendoza" case americaArgentinaRioGallegos = "America/Argentina/Rio_Gallegos" case americaArgentinaSalta = "America/Argentina/Salta" case americaArgentinaSanJuan = "America/Argentina/San_Juan" case americaArgentinaSanLuis = "America/Argentina/San_Luis" case americaArgentinaTucuman = "America/Argentina/Tucuman" case americaArgentinaUshuaia = "America/Argentina/Ushuaia" case americaAruba = "America/Aruba" case americaAsuncion = "America/Asuncion" case americaAtikokan = "America/Atikokan" case americaBahia = "America/Bahia" case americaBahiaBanderas = "America/Bahia_Banderas" case americaBarbados = "America/Barbados" case americaBelem = "America/Belem" case americaBelize = "America/Belize" case americaBlancSablon = "America/Blanc-Sablon" case americaBoaVista = "America/Boa_Vista" case americaBogota = "America/Bogota" case americaBoise = "America/Boise" case americaCambridgeBay = "America/Cambridge_Bay" case americaCampoGrande = "America/Campo_Grande" case americaCancun = "America/Cancun" case americaCaracas = "America/Caracas" case americaCayenne = "America/Cayenne" case americaCayman = "America/Cayman" case americaChicago = "America/Chicago" case americaChihuahua = "America/Chihuahua" case americaCostaRica = "America/Costa_Rica" case americaCreston = "America/Creston" case americaCuiaba = "America/Cuiaba" case americaCuracao = "America/Curacao" case americaDanmarkshavn = "America/Danmarkshavn" case americaDawson = "America/Dawson" case americaDawsonCreek = "America/Dawson_Creek" case americaDenver = "America/Denver" case americaDetroit = "America/Detroit" case americaDominica = "America/Dominica" case americaEdmonton = "America/Edmonton" case americaEirunepe = "America/Eirunepe" case americaElSalvador = "America/El_Salvador" case americaFortNelson = "America/Fort_Nelson" case americaFortaleza = "America/Fortaleza" case americaGlaceBay = "America/Glace_Bay" case americaGodthab = "America/Godthab" case americaGooseBay = "America/Goose_Bay" case americaGrandTurk = "America/Grand_Turk" case americaGrenada = "America/Grenada" case americaGuadeloupe = "America/Guadeloupe" case americaGuatemala = "America/Guatemala" case americaGuayaquil = "America/Guayaquil" case americaGuyana = "America/Guyana" case americaHalifax = "America/Halifax" case americaHavana = "America/Havana" case americaHermosillo = "America/Hermosillo" case americaIndianaIndianapolis = "America/Indiana/Indianapolis" case americaIndianaKnox = "America/Indiana/Knox" case americaIndianaMarengo = "America/Indiana/Marengo" case americaIndianaPetersburg = "America/Indiana/Petersburg" case americaIndianaTellCity = "America/Indiana/Tell_City" case americaIndianaVevay = "America/Indiana/Vevay" case americaIndianaVincennes = "America/Indiana/Vincennes" case americaIndianaWinamac = "America/Indiana/Winamac" case americaInuvik = "America/Inuvik" case americaIqaluit = "America/Iqaluit" case americaJamaica = "America/Jamaica" case americaJuneau = "America/Juneau" case americaKentuckyLouisville = "America/Kentucky/Louisville" case americaKentuckyMonticello = "America/Kentucky/Monticello" case americaKralendijk = "America/Kralendijk" case americaLaPaz = "America/La_Paz" case americaLima = "America/Lima" case americaLosAngeles = "America/Los_Angeles" case americaLowerPrinces = "America/Lower_Princes" case americaMaceio = "America/Maceio" case americaManagua = "America/Managua" case americaManaus = "America/Manaus" case americaMarigot = "America/Marigot" case americaMartinique = "America/Martinique" case americaMatamoros = "America/Matamoros" case americaMazatlan = "America/Mazatlan" case americaMenominee = "America/Menominee" case americaMerida = "America/Merida" case americaMetlakatla = "America/Metlakatla" case americaMexicoCity = "America/Mexico_City" case americaMiquelon = "America/Miquelon" case americaMoncton = "America/Moncton" case americaMonterrey = "America/Monterrey" case americaMontevideo = "America/Montevideo" case americaMontreal = "America/Montreal" case americaMontserrat = "America/Montserrat" case americaNassau = "America/Nassau" case americaNewYork = "America/New_York" case americaNipigon = "America/Nipigon" case americaNome = "America/Nome" case americaNoronha = "America/Noronha" case americaNorthDakotaBeulah = "America/North_Dakota/Beulah" case americaNorthDakotaCenter = "America/North_Dakota/Center" case americaNorthDakotaNewSalem = "America/North_Dakota/New_Salem" case americaOjinaga = "America/Ojinaga" case americaPanama = "America/Panama" case americaPangnirtung = "America/Pangnirtung" case americaParamaribo = "America/Paramaribo" case americaPhoenix = "America/Phoenix" case americaPortAuPrince = "America/Port-au-Prince" case americaPortOfSpain = "America/Port_of_Spain" case americaPortoVelho = "America/Porto_Velho" case americaPuertoRico = "America/Puerto_Rico" case americaRainyRiver = "America/Rainy_River" case americaRankinInlet = "America/Rankin_Inlet" case americaRecife = "America/Recife" case americaRegina = "America/Regina" case americaResolute = "America/Resolute" case americaRioBranco = "America/Rio_Branco" case americaSantaIsabel = "America/Santa_Isabel" case americaSantarem = "America/Santarem" case americaSantiago = "America/Santiago" case americaSantoDomingo = "America/Santo_Domingo" case americaSaoPaulo = "America/Sao_Paulo" case americaScoresbysund = "America/Scoresbysund" case americaShiprock = "America/Shiprock" case americaSitka = "America/Sitka" case americaStBarthelemy = "America/St_Barthelemy" case americaStJohns = "America/St_Johns" case americaStKitts = "America/St_Kitts" case americaStLucia = "America/St_Lucia" case americaStThomas = "America/St_Thomas" case americaStVincent = "America/St_Vincent" case americaSwiftCurrent = "America/Swift_Current" case americaTegucigalpa = "America/Tegucigalpa" case americaThule = "America/Thule" case americaThunderBay = "America/Thunder_Bay" case americaTijuana = "America/Tijuana" case americaToronto = "America/Toronto" case americaTortola = "America/Tortola" case americaVancouver = "America/Vancouver" case americaWhitehorse = "America/Whitehorse" case americaWinnipeg = "America/Winnipeg" case americaYakutat = "America/Yakutat" case americaYellowknife = "America/Yellowknife" case antarcticaCasey = "Antarctica/Casey" case antarcticaDavis = "Antarctica/Davis" case antarcticaDumontdurville = "Antarctica/DumontDUrville" case antarcticaMacquarie = "Antarctica/Macquarie" case antarcticaMawson = "Antarctica/Mawson" case antarcticaMcmurdo = "Antarctica/McMurdo" case antarcticaPalmer = "Antarctica/Palmer" case antarcticaRothera = "Antarctica/Rothera" case antarcticaSouthPole = "Antarctica/South_Pole" case antarcticaSyowa = "Antarctica/Syowa" case antarcticaTroll = "Antarctica/Troll" case antarcticaVostok = "Antarctica/Vostok" case arcticLongyearbyen = "Arctic/Longyearbyen" case asiaAden = "Asia/Aden" case asiaAlmaty = "Asia/Almaty" case asiaAmman = "Asia/Amman" case asiaAnadyr = "Asia/Anadyr" case asiaAqtau = "Asia/Aqtau" case asiaAqtobe = "Asia/Aqtobe" case asiaAshgabat = "Asia/Ashgabat" case asiaBaghdad = "Asia/Baghdad" case asiaBahrain = "Asia/Bahrain" case asiaBaku = "Asia/Baku" case asiaBangkok = "Asia/Bangkok" case asiaBeirut = "Asia/Beirut" case asiaBishkek = "Asia/Bishkek" case asiaBrunei = "Asia/Brunei" case asiaChita = "Asia/Chita" case asiaChoibalsan = "Asia/Choibalsan" case asiaChongqing = "Asia/Chongqing" case asiaColombo = "Asia/Colombo" case asiaDamascus = "Asia/Damascus" case asiaDhaka = "Asia/Dhaka" case asiaDili = "Asia/Dili" case asiaDubai = "Asia/Dubai" case asiaDushanbe = "Asia/Dushanbe" case asiaGaza = "Asia/Gaza" case asiaHarbin = "Asia/Harbin" case asiaHebron = "Asia/Hebron" case asiaHoChiMinh = "Asia/Ho_Chi_Minh" case asiaHongKong = "Asia/Hong_Kong" case asiaHovd = "Asia/Hovd" case asiaIrkutsk = "Asia/Irkutsk" case asiaJakarta = "Asia/Jakarta" case asiaJayapura = "Asia/Jayapura" case asiaJerusalem = "Asia/Jerusalem" case asiaKabul = "Asia/Kabul" case asiaKamchatka = "Asia/Kamchatka" case asiaKarachi = "Asia/Karachi" case asiaKashgar = "Asia/Kashgar" case asiaKathmandu = "Asia/Kathmandu" case asiaKatmandu = "Asia/Katmandu" case asiaKhandyga = "Asia/Khandyga" case asiaKolkata = "Asia/Kolkata" case asiaKrasnoyarsk = "Asia/Krasnoyarsk" case asiaKualaLumpur = "Asia/Kuala_Lumpur" case asiaKuching = "Asia/Kuching" case asiaKuwait = "Asia/Kuwait" case asiaMacau = "Asia/Macau" case asiaMagadan = "Asia/Magadan" case asiaMakassar = "Asia/Makassar" case asiaManila = "Asia/Manila" case asiaMuscat = "Asia/Muscat" case asiaNicosia = "Asia/Nicosia" case asiaNovokuznetsk = "Asia/Novokuznetsk" case asiaNovosibirsk = "Asia/Novosibirsk" case asiaOmsk = "Asia/Omsk" case asiaOral = "Asia/Oral" case asiaPhnomPenh = "Asia/Phnom_Penh" case asiaPontianak = "Asia/Pontianak" case asiaPyongyang = "Asia/Pyongyang" case asiaQatar = "Asia/Qatar" case asiaQyzylorda = "Asia/Qyzylorda" case asiaRangoon = "Asia/Rangoon" case asiaRiyadh = "Asia/Riyadh" case asiaSakhalin = "Asia/Sakhalin" case asiaSamarkand = "Asia/Samarkand" case asiaSeoul = "Asia/Seoul" case asiaShanghai = "Asia/Shanghai" case asiaSingapore = "Asia/Singapore" case asiaSrednekolymsk = "Asia/Srednekolymsk" case asiaTaipei = "Asia/Taipei" case asiaTashkent = "Asia/Tashkent" case asiaTbilisi = "Asia/Tbilisi" case asiaTehran = "Asia/Tehran" case asiaThimphu = "Asia/Thimphu" case asiaTokyo = "Asia/Tokyo" case asiaUlaanbaatar = "Asia/Ulaanbaatar" case asiaUrumqi = "Asia/Urumqi" case asiaUstNera = "Asia/Ust-Nera" case asiaVientiane = "Asia/Vientiane" case asiaVladivostok = "Asia/Vladivostok" case asiaYakutsk = "Asia/Yakutsk" case asiaYekaterinburg = "Asia/Yekaterinburg" case asiaYerevan = "Asia/Yerevan" case atlanticAzores = "Atlantic/Azores" case atlanticBermuda = "Atlantic/Bermuda" case atlanticCanary = "Atlantic/Canary" case atlanticCapeVerde = "Atlantic/Cape_Verde" case atlanticFaroe = "Atlantic/Faroe" case atlanticMadeira = "Atlantic/Madeira" case atlanticReykjavik = "Atlantic/Reykjavik" case atlanticSouthGeorgia = "Atlantic/South_Georgia" case atlanticStHelena = "Atlantic/St_Helena" case atlanticStanley = "Atlantic/Stanley" case australiaAdelaide = "Australia/Adelaide" case australiaBrisbane = "Australia/Brisbane" case australiaBrokenHill = "Australia/Broken_Hill" case australiaCurrie = "Australia/Currie" case australiaDarwin = "Australia/Darwin" case australiaEucla = "Australia/Eucla" case australiaHobart = "Australia/Hobart" case australiaLindeman = "Australia/Lindeman" case australiaLordHowe = "Australia/Lord_Howe" case australiaMelbourne = "Australia/Melbourne" case australiaPerth = "Australia/Perth" case australiaSydney = "Australia/Sydney" case europeAmsterdam = "Europe/Amsterdam" case europeAndorra = "Europe/Andorra" case europeAthens = "Europe/Athens" case europeBelgrade = "Europe/Belgrade" case europeBerlin = "Europe/Berlin" case europeBratislava = "Europe/Bratislava" case europeBrussels = "Europe/Brussels" case europeBucharest = "Europe/Bucharest" case europeBudapest = "Europe/Budapest" case europeBusingen = "Europe/Busingen" case europeChisinau = "Europe/Chisinau" case europeCopenhagen = "Europe/Copenhagen" case europeDublin = "Europe/Dublin" case europeGibraltar = "Europe/Gibraltar" case europeGuernsey = "Europe/Guernsey" case europeHelsinki = "Europe/Helsinki" case europeIsleOfMan = "Europe/Isle_of_Man" case europeIstanbul = "Europe/Istanbul" case europeJersey = "Europe/Jersey" case europeKaliningrad = "Europe/Kaliningrad" case europeKiev = "Europe/Kiev" case europeLisbon = "Europe/Lisbon" case europeLjubljana = "Europe/Ljubljana" case europeLondon = "Europe/London" case europeLuxembourg = "Europe/Luxembourg" case europeMadrid = "Europe/Madrid" case europeMalta = "Europe/Malta" case europeMariehamn = "Europe/Mariehamn" case europeMinsk = "Europe/Minsk" case europeMonaco = "Europe/Monaco" case europeMoscow = "Europe/Moscow" case europeOslo = "Europe/Oslo" case europeParis = "Europe/Paris" case europePodgorica = "Europe/Podgorica" case europePrague = "Europe/Prague" case europeRiga = "Europe/Riga" case europeRome = "Europe/Rome" case europeSamara = "Europe/Samara" case europeSanMarino = "Europe/San_Marino" case europeSarajevo = "Europe/Sarajevo" case europeSimferopol = "Europe/Simferopol" case europeSkopje = "Europe/Skopje" case europeSofia = "Europe/Sofia" case europeStockholm = "Europe/Stockholm" case europeTallinn = "Europe/Tallinn" case europeTirane = "Europe/Tirane" case europeUzhgorod = "Europe/Uzhgorod" case europeVaduz = "Europe/Vaduz" case europeVatican = "Europe/Vatican" case europeVienna = "Europe/Vienna" case europeVilnius = "Europe/Vilnius" case europeVolgograd = "Europe/Volgograd" case europeWarsaw = "Europe/Warsaw" case europeZagreb = "Europe/Zagreb" case europeZaporozhye = "Europe/Zaporozhye" case europeZurich = "Europe/Zurich" case gmt = "GMT" case IndianAntananarivo = "Indian/Antananarivo" case indianChagos = "Indian/Chagos" case indianChristmas = "Indian/Christmas" case indianCocos = "Indian/Cocos" case indianComoro = "Indian/Comoro" case indianKerguelen = "Indian/Kerguelen" case indianMahe = "Indian/Mahe" case indianMaldives = "Indian/Maldives" case indianMauritius = "Indian/Mauritius" case indianMayotte = "Indian/Mayotte" case indianReunion = "Indian/Reunion" case pacificApia = "Pacific/Apia" case pacificAuckland = "Pacific/Auckland" case pacificBougainville = "Pacific/Bougainville" case pacificChatham = "Pacific/Chatham" case pacificChuuk = "Pacific/Chuuk" case pacificEaster = "Pacific/Easter" case pacificEfate = "Pacific/Efate" case pacificEnderbury = "Pacific/Enderbury" case pacificFakaofo = "Pacific/Fakaofo" case pacificFiji = "Pacific/Fiji" case pacificFunafuti = "Pacific/Funafuti" case pacificGalapagos = "Pacific/Galapagos" case pacificGambier = "Pacific/Gambier" case pacificGuadalcanal = "Pacific/Guadalcanal" case pacificGuam = "Pacific/Guam" case pacificHonolulu = "Pacific/Honolulu" case pacificJohnston = "Pacific/Johnston" case pacificKiritimati = "Pacific/Kiritimati" case pacificKosrae = "Pacific/Kosrae" case pacificKwajalein = "Pacific/Kwajalein" case pacificMajuro = "Pacific/Majuro" case pacificMarquesas = "Pacific/Marquesas" case pacificMidway = "Pacific/Midway" case pacificNauru = "Pacific/Nauru" case pacificNiue = "Pacific/Niue" case pacificNorfolk = "Pacific/Norfolk" case pacificNoumea = "Pacific/Noumea" case pacificPagoPago = "Pacific/Pago_Pago" case pacificPalau = "Pacific/Palau" case pacificPitcairn = "Pacific/Pitcairn" case pacificPohnpei = "Pacific/Pohnpei" case pacificPonape = "Pacific/Ponape" case pacificPortMoresby = "Pacific/Port_Moresby" case pacificRarotonga = "Pacific/Rarotonga" case pacificSaipan = "Pacific/Saipan" case pacificTahiti = "Pacific/Tahiti" case pacificTarawa = "Pacific/Tarawa" case pacificTongatapu = "Pacific/Tongatapu" case pacificTruk = "Pacific/Truk" case pacificWake = "Pacific/Wake" case pacificWallis = "Pacific/Wallis" }
mit
588c9c92dcfa7d423075ae701b424ee4
39.385439
78
0.776299
2.54624
false
false
false
false
coderQuanjun/PigTV
GYJTV/GYJTV/Classes/Live/ViewModel/GiftViewModel.swift
1
1330
// // GiftViewModel.swift // GYJTV // // Created by zcm_iOS on 2017/5/25. // Copyright © 2017年 Quanjun. All rights reserved. // import UIKit class GiftViewModel: NSObject { lazy var giftListData : [GiftPackages] = [GiftPackages]() } extension GiftViewModel{ func loadGiftData(finishedCallBack : @escaping () -> ()) { // http://qf.56.com/pay/v4/giftList.ios?type=0&page=1&rows=150 if giftListData.count != 0 { finishedCallBack() } //请求数据 NetworkTool.requestData(.get, URLString: kRoomGiftListUrl, parameters: ["type" : 0, "page" : 1, "rows" : 150], finishedCallback: { result in guard let resultDic = result as? [String : Any] else { return } guard let message = resultDic["message"] as? [String : Any] else { return } for i in 0..<message.count{ guard let type = message["type\(i + 1)"] as? [String : Any] else { continue } self.giftListData.append(GiftPackages(dic: type)) } //先过滤掉没有礼物的数组,再按照有多到少排序 self.giftListData = self.giftListData.filter({ return $0.list.count > 0 }).sorted(by: { return $0.list.count > $1.list.count }) finishedCallBack() }) } }
mit
09a634cb3230350070f0c2b78e1bb055
33.567568
148
0.579359
3.739766
false
false
false
false
tlax/looper
looper/View/Camera/Crop/VCameraCropImageThumb.swift
1
3047
import UIKit class VCameraCropImageThumb:UIImageView { enum Location { case topLeft case topRight case bottomLeft case bottomRight } var positionX:CGFloat var positionY:CGFloat var originalX:CGFloat! var originalY:CGFloat! let location:Location private weak var layoutTop:NSLayoutConstraint! private weak var layoutLeft:NSLayoutConstraint! private var size_2:CGFloat class func topLeft() -> VCameraCropImageThumb { let thumb:VCameraCropImageThumb = VCameraCropImageThumb( location:Location.topLeft) return thumb } class func topRight() -> VCameraCropImageThumb { let thumb:VCameraCropImageThumb = VCameraCropImageThumb( location:Location.topRight) return thumb } class func bottomLeft() -> VCameraCropImageThumb { let thumb:VCameraCropImageThumb = VCameraCropImageThumb( location:Location.bottomLeft) return thumb } class func bottomRight() -> VCameraCropImageThumb { let thumb:VCameraCropImageThumb = VCameraCropImageThumb( location:Location.bottomRight) return thumb } private init(location:Location) { self.location = location positionX = 0 positionY = 0 size_2 = 0 super.init(frame:CGRect.zero) isUserInteractionEnabled = true clipsToBounds = true translatesAutoresizingMaskIntoConstraints = false contentMode = UIViewContentMode.center state(selected:false) } required init?(coder:NSCoder) { return nil } //MARK: public func position(positionX:CGFloat, positionY:CGFloat) { self.positionX = positionX self.positionY = positionY layoutTop.constant = positionY - size_2 layoutLeft.constant = positionX - size_2 if originalX == nil { originalX = positionX originalY = positionY } } func initConstraints(size:CGFloat) { guard let superview:UIView = self.superview else { return } size_2 = size / 2.0 layoutTop = NSLayoutConstraint.topToTop( view:self, toView:superview) layoutLeft = NSLayoutConstraint.leftToLeft( view:self, toView:superview) NSLayoutConstraint.size( view:self, constant:size) } func state(selected:Bool) { if selected { image = #imageLiteral(resourceName: "assetCameraCropThumbSelected") } else { image = #imageLiteral(resourceName: "assetCameraCropThumb") } } func reset() { position( positionX:originalX, positionY:originalY) } }
mit
0614e7a4dde5888f500d03219b497448
22.083333
79
0.570397
5.383392
false
false
false
false
auth0/Lock.swift
Lock/Connections.swift
2
3013
// Connections.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 public protocol Connections { var database: DatabaseConnection? { get } var oauth2: [OAuth2Connection] { get } var enterprise: [EnterpriseConnection] {get} var passwordless: [PasswordlessConnection] { get } var isEmpty: Bool { get } /** Select only the connections whose names are in the array - parameter names: names of the connections to keep - returns: filtered connections */ func select(byNames names: [String]) -> Self } public struct DatabaseConnection { public let name: String public let requiresUsername: Bool public let usernameValidator: UsernameValidator public let passwordValidator: PasswordPolicyValidator public init(name: String, requiresUsername: Bool, usernameValidator: UsernameValidator = UsernameValidator(), passwordValidator: PasswordPolicyValidator = PasswordPolicyValidator(policy: .none())) { self.name = name self.requiresUsername = requiresUsername self.usernameValidator = usernameValidator self.passwordValidator = passwordValidator } } public protocol OAuth2Connection { var name: String { get } var style: AuthStyle { get } } public struct SocialConnection: OAuth2Connection { public let name: String public let style: AuthStyle } public struct EnterpriseConnection: OAuth2Connection { public let name: String public let domains: [String] public let style: AuthStyle init(name: String, domains: [String], style: AuthStyle? = nil) { self.name = name self.domains = domains self.style = style ?? AuthStyle(name: name) } } public struct PasswordlessConnection { public let name: String public let strategy: String public init(name: String, strategy: String) { self.name = name self.strategy = strategy } }
mit
ad301ab969b23469f814a861a6bd7713
33.632184
202
0.724195
4.635385
false
false
false
false
domenicosolazzo/practice-swift
CoreData/SuperDB/SuperDB/SuperDBColorCell.swift
1
2103
// // SuperDBColorCell.swift // SuperDB // // Created by Domenico on 02/06/15. // Copyright (c) 2015 Domenico. All rights reserved. // import UIKit class SuperDBColorCell: SuperDBEditCell { var colorPicker: UIColorPicker! var attributedColorString: NSAttributedString!{ get{ var block = NSString(UTF8String: "\u{2588}\u{2588}\u{2588}\u{2588}\u{2588}\u{2588}\u{2588}\u{2588}\u{2588}\u{2588}") var color:UIColor = self.colorPicker.color var attrs:NSDictionary = [ NSForegroundColorAttributeName:color, NSFontAttributeName:UIFont.boldSystemFontOfSize(UIFont.systemFontSize())] var attributedString = NSAttributedString(string: block! as String, attributes:attrs as [NSObject : AnyObject] as [NSObject : AnyObject]) return attributedString } } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.colorPicker = UIColorPicker(frame: CGRectMake(0, 0, 320, 216)) self.colorPicker.addTarget(self, action: "colorPickerChanged:", forControlEvents: .ValueChanged) self.textField.inputView = self.colorPicker self.textField.clearButtonMode = .Never } //MARK: - SuperDBEditCell Overrides override var value: AnyObject!{ get{ return self.colorPicker.color } set{ if let _color = newValue as? UIColor { //self.value = _color self.colorPicker.color = _color //newValue as! UIColor } else { self.colorPicker.color = UIColor(red: 1, green: 1, blue: 1, alpha: 1) } self.textField.attributedText = self.attributedColorString self.textField.text = nil } } func colorPickerChanged(sender: AnyObject){ self.textField.attributedText = self.attributedColorString } }
mit
fa0dbc14aee66d62ee728c23e68a47f9
33.47541
149
0.625773
4.474468
false
false
false
false
february29/Learning
swift/Fch_Contact/Pods/RxCocoa/RxCocoa/Common/Binder.swift
21
1859
// // Binder.swift // RxCocoa // // Created by Krunoslav Zaher on 9/17/17. // Copyright © 2017 Krunoslav Zaher. All rights reserved. // import RxSwift /** Observer that enforces interface binding rules: * can't bind errors (in debug builds binding of errors causes `fatalError` in release builds errors are being logged) * ensures binding is performed on a specific scheduler `Binder` doesn't retain target and in case target is released, element isn't bound. By default it binds elements on main scheduler. */ public struct Binder<Value>: ObserverType { public typealias E = Value private let _binding: (Event<Value>) -> () /// Initializes `Binder` /// /// - parameter target: Target object. /// - parameter scheduler: Scheduler used to bind the events. /// - parameter binding: Binding logic. public init<Target: AnyObject>(_ target: Target, scheduler: ImmediateSchedulerType = MainScheduler(), binding: @escaping (Target, Value) -> ()) { weak var weakTarget = target _binding = { event in switch event { case .next(let element): _ = scheduler.schedule(element) { element in if let target = weakTarget { binding(target, element) } return Disposables.create() } case .error(let error): bindingError(error) case .completed: break } } } /// Binds next element to owner view as described in `binding`. public func on(_ event: Event<Value>) { _binding(event) } /// Erases type of observer. /// /// - returns: type erased observer. public func asObserver() -> AnyObserver<Value> { return AnyObserver(eventHandler: on) } }
mit
2f5d296539a79a8a2c742b9a87792f78
29.459016
149
0.596878
4.78866
false
false
false
false
volythat/HNHelper
HNHelper/Helper/HNLog.swift
1
1254
// // HNLog.swift // HNHelper // // Created by oneweek on 9/7/17. // Copyright © 2017 Harry Nguyen. All rights reserved. // import UIKit func LogD(_ message:String, function:String = #function) { #if !NDEBUG let formatter = DateFormatter() formatter.dateFormat = "HH:mm:ss" let date = formatter.string(from: Date()) print("=================================================") print("\(date) Func: \(function) : \(message)") #endif } func Log(_ object:Any, function:String = #function){ #if !NDEBUG if let str = object as? String { LogD(str,function: function) }else if let obj = object as? NSObject { let formatter = DateFormatter() formatter.dateFormat = "HH:mm:ss" let date = formatter.string(from: Date()) let properties = Mirror(reflecting: obj).children print("=================================================") print("\(date) Func: \(function) :") for property in properties { print("\(property.label!) : \(property.value)") } print("=================================================") } #endif }
mit
ab98df8324719aea720b716c6b5ec0b0
29.560976
70
0.47087
4.556364
false
false
false
false
abunur/quran-ios
Quran/AyahBookmarkDataSource.swift
1
3015
// // AyahBookmarkDataSource.swift // Quran // // Created by Mohamed Afifi on 11/1/16. // // Quran for iOS is a Quran reading application for iOS. // Copyright (C) 2017 Quran.com // // 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. // import Foundation import GenericDataSources class AyahBookmarkDataSource: BaseBookmarkDataSource<AyahBookmark, AyahBookmarkTableViewCell> { let ayahCache: Cache<AyahNumber, String> = { let cache = Cache<AyahNumber, String>() cache.countLimit = 30 return cache }() let numberFormatter = NumberFormatter() let ayahPersistence: AyahTextPersistence init(persistence: BookmarksPersistence, ayahPersistence: AyahTextPersistence) { self.ayahPersistence = ayahPersistence super.init(persistence: persistence) } override func ds_collectionView(_ collectionView: GeneralCollectionView, configure cell: AyahBookmarkTableViewCell, with item: AyahBookmark, at indexPath: IndexPath) { cell.ayahLabel.text = item.ayah.localizedName cell.iconImage.image = #imageLiteral(resourceName: "bookmark-filled").withRenderingMode(.alwaysTemplate) cell.iconImage.tintColor = .bookmark() cell.descriptionLabel.text = item.creationDate.bookmarkTimeAgo() cell.startPage.text = numberFormatter.format(NSNumber(value: item.page)) let name: String // get from cache if let text = ayahCache.object(forKey: item.ayah) { name = text } else { do { // get from persistence let text = try self.ayahPersistence.getAyahTextForNumber(item.ayah) // save to cache self.ayahCache.setObject(text, forKey: item.ayah) // update the UI name = text } catch { name = item.ayah.localizedName Crash.recordError(error, reason: "AyahTextPersistence.getAyahTextForNumber", fatalErrorOnDebug: false) } } cell.name.text = name } func reloadData() { DispatchQueue.default .promise2(execute: self.persistence.retrieveAyahBookmarks) .then(on: .main) { items -> Void in self.items = items self.ds_reusableViewDelegate?.ds_reloadSections(IndexSet(integer: 0), with: .automatic) }.cauterize(tag: "BookmarksPersistence.retrieveAyahBookmarks") } }
gpl-3.0
0f97e5189fd9ddb3265d9b4ba7d464db
37.164557
118
0.642786
4.793323
false
false
false
false
nacho4d/Kitura-net
Sources/KituraNet/ClientRequest.swift
1
13162
/** * Copyright IBM Corporation 2016 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import KituraSys import CurlHelpers import BlueSocket import Foundation // MARK: ClientRequest public class ClientRequest: BlueSocketWriter { /// /// Internal lock to the request /// static private var lock = 0 public var headers = [String: String]() // MARK: -- Private /// /// URL used for the request /// private var url: String /// /// HTTP method (GET, POST, PUT, DELETE) for the request /// private var method: String = "get" /// /// Username if using Basic Auth /// private var userName: String? = nil /// /// Password if using Basic Auth /// private var password: String? = nil /// /// Maximum number of redirects before failure /// private var maxRedirects = 10 /// /// ??? /// private var handle: UnsafeMutablePointer<Void>? /// /// List of header information /// private var headersList: UnsafeMutablePointer<curl_slist> = nil /// /// BufferList to store bytes to be written /// private var writeBuffers = BufferList() /// /// Response instance for communicating with client /// private var response = ClientResponse() private var callback: ClientRequestCallback /// /// Initializes a ClientRequest instance /// /// - Parameter url: url for the request /// - Parameter callback: /// /// - Returns: a ClientRequest instance /// init(url: String, callback: ClientRequestCallback) { self.url = url self.callback = callback } /// /// Initializes a ClientRequest instance /// /// - Parameter options: a list of options describing the request /// - Parameter callback: /// /// - Returns: a ClientRequest instance /// init(options: [ClientRequestOptions], callback: ClientRequestCallback) { self.callback = callback var theSchema = "http://" var hostName = "localhost" var path = "/" var port:Int16 = 80 for option in options { switch(option) { case .Method(let method): self.method = method case .Schema(let schema): theSchema = schema case .Hostname(let host): hostName = host case .Port(let thePort): port = thePort case .Path(let thePath): path = thePath case .Headers(let headers): for (key, value) in headers { self.headers[key] = value } case .Username(let userName): self.userName = userName case .Password(let password): self.password = password case .MaxRedirects(let maxRedirects): self.maxRedirects = maxRedirects } } // Adding support for Basic HTTP authentication let user = self.userName != nil ? self.userName! : "" let pwd = self.password != nil ? self.password! : "" var authenticationClause = "" if (!user.isEmpty && !pwd.isEmpty) { authenticationClause = "\(user):\(pwd)@" } let portNumber = String(port) url = "\(theSchema)\(authenticationClause)\(hostName):\(portNumber)\(path)" } /// /// Instance destruction /// deinit { if let handle = handle { curl_easy_cleanup(handle) } if headersList != nil { curl_slist_free_all(headersList) } } /// /// Writes a string to the response /// /// - Parameter str: String to be written /// public func writeString(str: String) { if let data = StringUtils.toUtf8String(str) { writeData(data) } } /// /// Writes data to the response /// /// - Parameter data: NSData to be written /// public func writeData(data: NSData) { writeBuffers.appendData(data) } /// /// End servicing the request, send response back /// /// - Parameter data: string to send before ending /// public func end(data: String) { writeString(data) end() } /// /// End servicing the request, send response back /// /// - Parameter data: data to send before ending /// public func end(data: NSData) { writeData(data) end() } /// /// End servicing the request, send response back /// public func end() { // Be sure that a lock is obtained before this can be executed SysUtils.doOnce(&ClientRequest.lock) { curl_global_init(Int(CURL_GLOBAL_SSL)) } var callCallback = true let urlBuf = StringUtils.toNullTerminatedUtf8String(url) if let _ = urlBuf { prepareHandle(urlBuf!) let invoker = CurlInvoker(handle: handle!, maxRedirects: maxRedirects) invoker.delegate = self var code = invoker.invoke() if code == CURLE_OK { code = curlHelperGetInfoLong(handle!, CURLINFO_RESPONSE_CODE, &response.status) if code == CURLE_OK { response.parse() {status in switch(status) { case .Success: self.callback(response: self.response) callCallback = false default: print("ClientRequest error. Failed to parse response. status=\(status)") } } } } else { print("ClientRequest Error. CURL Return code=\(code)") } } if callCallback { callback(response: nil) } } /// /// Prepare the handle /// /// Parameter urlBuf: ??? /// private func prepareHandle(urlBuf: NSData) { handle = curl_easy_init() // HTTP parser does the decoding curlHelperSetOptInt(handle!, CURLOPT_HTTP_TRANSFER_DECODING, 0) curlHelperSetOptString(handle!, CURLOPT_URL, UnsafeMutablePointer<Int8>(urlBuf.bytes)) setMethod() let count = writeBuffers.count if count != 0 { curlHelperSetOptInt(handle!, CURLOPT_POSTFIELDSIZE, count) } setupHeaders() } /// /// Sets the HTTP method in libCurl to the one specified in method /// private func setMethod() { let methodUpperCase = method.uppercaseString switch(methodUpperCase) { case "GET": curlHelperSetOptBool(handle!, CURLOPT_HTTPGET, CURL_TRUE) case "POST": curlHelperSetOptBool(handle!, CURLOPT_POST, CURL_TRUE) case "PUT": curlHelperSetOptBool(handle!, CURLOPT_PUT, CURL_TRUE) default: let methodCstring = StringUtils.toNullTerminatedUtf8String(methodUpperCase)! curlHelperSetOptString(handle!, CURLOPT_CUSTOMREQUEST, UnsafeMutablePointer<Int8>(methodCstring.bytes)) } } /// /// Sets the headers in libCurl to the ones in headers /// private func setupHeaders() { for (headerKey, headerValue) in headers { let headerString = StringUtils.toNullTerminatedUtf8String("\(headerKey): \(headerValue)") if let headerString = headerString { headersList = curl_slist_append(headersList, UnsafeMutablePointer<Int8>(headerString.bytes)) } } curlHelperSetOptHeaders(handle!, headersList) } } // MARK: CurlInvokerDelegate extension extension ClientRequest: CurlInvokerDelegate { /// /// private func curlWriteCallback(buf: UnsafeMutablePointer<Int8>, size: Int) -> Int { response.responseBuffers.appendBytes(UnsafePointer<UInt8>(buf), length: size) return size } private func curlReadCallback(buf: UnsafeMutablePointer<Int8>, size: Int) -> Int { let count = writeBuffers.fillBuffer(UnsafeMutablePointer<UInt8>(buf), length: size) return count } private func prepareForRedirect() { response.responseBuffers.reset() writeBuffers.rewind() } } /// /// Client request option values /// public enum ClientRequestOptions { case Method(String), Schema(String), Hostname(String), Port(Int16), Path(String), Headers([String: String]), Username(String), Password(String), MaxRedirects(Int) } /// /// Response callback closure /// public typealias ClientRequestCallback = (response: ClientResponse?) -> Void /// /// Helper class for invoking commands through libCurl /// private class CurlInvoker { /// /// Pointer to the libCurl handle /// private var handle: UnsafeMutablePointer<Void> /// /// Delegate that can have a read or write callback /// private weak var delegate: CurlInvokerDelegate? = nil /// /// Maximum number of redirects /// private let maxRedirects: Int /// /// Initializes a new CurlInvoker instance /// private init(handle: UnsafeMutablePointer<Void>, maxRedirects: Int) { self.handle = handle self.maxRedirects = maxRedirects } /// /// Run the HTTP method through the libCurl library /// /// - Returns: a status code for the success of the operation /// private func invoke() -> CURLcode { var rc: CURLcode = CURLE_FAILED_INIT if let _ = delegate { withUnsafeMutablePointer(&delegate) {ptr in self.prepareHandle(ptr) var redirected = false var redirectCount = 0 repeat { rc = curl_easy_perform(handle) if rc == CURLE_OK { var redirectUrl: UnsafeMutablePointer<Int8> = nil let infoRc = curlHelperGetInfoCString(handle, CURLINFO_REDIRECT_URL, &redirectUrl) if infoRc == CURLE_OK { if redirectUrl != nil { curlHelperSetOptString(handle, CURLOPT_URL, redirectUrl) redirected = true delegate?.prepareForRedirect() redirectCount+=1 } else { redirected = false } } } } while rc == CURLE_OK && redirected && redirectCount < maxRedirects } } return rc } /// /// Prepare the handle /// /// - Parameter ptr: pointer to the CurlInvokerDelegate /// private func prepareHandle(ptr: UnsafeMutablePointer<CurlInvokerDelegate?>) { curlHelperSetOptReadFunc(handle, ptr) { (buf: UnsafeMutablePointer<Int8>, size: Int, nMemb: Int, privateData: UnsafeMutablePointer<Void>) -> Int in let p = UnsafePointer<CurlInvokerDelegate?>(privateData) return (p.memory?.curlReadCallback(buf, size: size*nMemb))! } curlHelperSetOptWriteFunc(handle, ptr) { (buf: UnsafeMutablePointer<Int8>, size: Int, nMemb: Int, privateData: UnsafeMutablePointer<Void>) -> Int in let p = UnsafePointer<CurlInvokerDelegate?>(privateData) return (p.memory?.curlWriteCallback(buf, size: size*nMemb))! } } } /// /// Delegate protocol for objects operated by CurlInvoker /// private protocol CurlInvokerDelegate: class { func curlWriteCallback(buf: UnsafeMutablePointer<Int8>, size: Int) -> Int func curlReadCallback(buf: UnsafeMutablePointer<Int8>, size: Int) -> Int func prepareForRedirect() }
apache-2.0
d6d193ce83d9226f0f3bc3f70311055c
26.767932
156
0.541331
4.914862
false
false
false
false
bvic23/VinceRP
VinceRP/Common/Core/Hub.swift
1
1814
// // Created by Viktor Belenyesi on 27/09/15. // Copyright (c) 2015 Viktor Belenyesi. All rights reserved. // public class Hub<T>: Node { public var dispatchQueue: dispatch_queue_t? func currentValue() -> T { if case .Success(let value) = toTry() { return value } var exceptionError = noValueError if case .Failure(let error) = toTry() { exceptionError = error } NSException(name: "name", reason: "domain", userInfo:["error": exceptionError]).raise() abort() } public func value() -> T { if let (e, d) = globalDynamic.value { let deps = d ?? [] linkChild(e) globalDynamic.value = (e, deps.arrayByPrepending(self)) } return currentValue() } func propagate() { Propagator.instance.propagate { self.children.map { NodeTuple(self, $0) } } } public func toTry() -> Try<T> { return Try(noValueError) } public func killAll() { kill() descendants.forEach { $0.kill() } } public func recalc() { Propagator.instance.propagate(toSet(NodeTuple(self, self))) } public func onChange(skipInitial skipInitial: Bool = true, callback: (T) -> ()) -> ChangeObserver<T> { return onChangeDo(self, skipInitial: skipInitial, callback: callback) } public func onError(callback: (NSError) -> ()) -> ErrorObserver<T> { return onErrorDo(self, callback: callback) } } extension Hub: Dispatchable { public func dispatchOnQueue(dispatchQueue: dispatch_queue_t?) -> Hub<T> { self.dispatchQueue = dispatchQueue return self } }
mit
24936c6ce53fa9a95e9b0d1a63049d9d
24.549296
106
0.550717
4.288416
false
false
false
false
qmihara/ice-weather-ios
IceWeather/Models.swift
1
1146
// // Models.swift // IceWeather // // Created by Kyusaku Mihara on 6/8/15. // Copyright (c) 2015 epohsoft. All rights reserved. // import Foundation class IceImage { var URL: String! var createdAt: String! init?(dictionary: [String: AnyObject]) { if let imageDictionary = dictionary["image"] as? [String: AnyObject] { if let URL = imageDictionary["url"] as? String { self.URL = URL if let createdAt = imageDictionary["created_at"] as? String { self.createdAt = createdAt } else if let createdAtDictionary = imageDictionary["created_at"] as? [String: AnyObject] { if let createdAt = createdAtDictionary["date"] as? String { self.createdAt = createdAt.stringByReplacingOccurrencesOfString(".000000", withString: "") } else { return nil } } else { return nil } } else { return nil } } else { return nil } } }
mit
a7cd6ca76d8aaf23e18718e5b734be24
29.972973
114
0.506108
4.876596
false
false
false
false
foxswang/PureLayout
PureLayout/Example-iOS/Demos/iOSDemo7ViewController.swift
20
5796
// // iOSDemo7ViewController.swift // PureLayout Example-iOS // // Copyright (c) 2015 Tyler Fox // https://github.com/PureLayout/PureLayout // import UIKit import PureLayout @objc(iOSDemo7ViewController) class iOSDemo7ViewController: UIViewController { let blueView: UIView = { let view = UIView.newAutoLayoutView() view.backgroundColor = .blueColor() return view }() let redView: UIView = { let view = UIView.newAutoLayoutView() view.backgroundColor = .redColor() return view }() var didSetupConstraints = false // Tracks the state of the animation: whether we are animating to the end state (true), or back to the initial state (false) var isAnimatingToEndState = true // Store some constraints that we intend to modify as part of the animation var blueViewHeightConstraint: NSLayoutConstraint? var redViewEdgeConstraint: NSLayoutConstraint? override func loadView() { view = UIView() view.backgroundColor = UIColor(white: 0.1, alpha: 1.0) view.addSubview(blueView) view.addSubview(redView) view.setNeedsUpdateConstraints() // bootstrap Auto Layout } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) /** Start the animation when the view appears. Note that the first initial constraint setup and layout pass has already occurred at this point. To switch between spring animation and regular animation, comment & uncomment the two lines below! (Don't uncomment both lines, one at a time!) */ animateLayoutWithSpringAnimation() // uncomment to use spring animation // animateLayoutWithRegularAnimation() // uncomment to use regular animation } override func updateViewConstraints() { let blueViewInitialHeight: CGFloat = 40.0 let blueViewEndHeight: CGFloat = 100.0 // Remember, this code is just the initial constraint setup which only happens the first time this method is called if (!didSetupConstraints) { blueView.autoPinToTopLayoutGuideOfViewController(self, withInset: 20.0) blueView.autoAlignAxisToSuperviewAxis(.Vertical) blueView.autoSetDimension(.Width, toSize: 50.0) blueViewHeightConstraint = blueView.autoSetDimension(.Height, toSize: blueViewInitialHeight) redView.autoSetDimension(.Height, toSize: 50.0) redView.autoMatchDimension(.Width, toDimension: .Height, ofView: blueView, withMultiplier: 1.5) redView.autoAlignAxisToSuperviewAxis(.Vertical) didSetupConstraints = true } // Unlike the code above, this is code that will execute every time this method is called. // Updating the `constant` property of a constraint is very efficient and can be done without removing/recreating the constraint. // Any other changes will require you to remove and re-add new constraints. Make sure to remove constraints before you create new ones! redViewEdgeConstraint?.autoRemove() if isAnimatingToEndState { blueViewHeightConstraint?.constant = blueViewEndHeight redViewEdgeConstraint = redView.autoPinEdgeToSuperviewEdge(.Bottom, withInset: 150.0) } else { blueViewHeightConstraint?.constant = blueViewInitialHeight redViewEdgeConstraint = redView.autoPinEdge(.Top, toEdge: .Bottom, ofView: blueView, withOffset: 20.0) } super.updateViewConstraints() } /// See the comments in viewDidAppear: above. func animateLayoutWithSpringAnimation() { // These 2 lines will cause updateViewConstraints() to be called again on this view controller, where the constraints will be adjusted to the new state view.setNeedsUpdateConstraints() view.updateConstraintsIfNeeded() UIView.animateWithDuration(1.0, delay: 0, usingSpringWithDamping: 0.6, initialSpringVelocity: 0, options: UIViewAnimationOptions(), animations: { self.view.layoutIfNeeded() }, completion: { (finished: Bool) -> Void in // Run the animation again in the other direction self.isAnimatingToEndState = !self.isAnimatingToEndState if (self.navigationController != nil) { // this will be nil if this view controller is no longer in the navigation stack (stops animation when this view controller is no longer onscreen) self.animateLayoutWithSpringAnimation() } }) } /// See the comments in viewDidAppear: above. func animateLayoutWithRegularAnimation() { // These 2 lines will cause updateViewConstraints() to be called again on this view controller, where the constraints will be adjusted to the new state view.setNeedsUpdateConstraints() view.updateConstraintsIfNeeded() UIView.animateWithDuration(1.0, delay: 0, options: UIViewAnimationOptions(), animations: { self.view.layoutIfNeeded() }, completion: { (finished: Bool) -> Void in // Run the animation again in the other direction self.isAnimatingToEndState = !self.isAnimatingToEndState if (self.navigationController != nil) { // this will be nil if this view controller is no longer in the navigation stack (stops animation when this view controller is no longer onscreen) self.animateLayoutWithRegularAnimation() } }) } }
mit
3ef5cb005f7a4429d25e3e4fe11040f9
43.244275
202
0.658213
5.56238
false
false
false
false
wookay/Look
samples/LookSample/Pods/C4/C4/UI/C4Star.swift
3
2547
// Copyright © 2014 C4 // // 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 CoreGraphics /// C4Star is a concrete subclass of C4Polygon that defines a star shape. public class C4Star: C4Polygon { /// Initializes a new C4Star shape. /// /// ```` /// let star = C4Star( /// center: canvas.center, /// pointCount: 5, /// innerRadius: 50, /// outerRadius: 100) /// canvas.add(star) /// ```` /// /// - parameter center: The center of the star /// - parameter pointCount: The number of points on the star /// - parameter innerRadius: The radial distance from the center of the star to the inner points /// - parameter outerRadius: The radial distance from the center of the start to the outer points convenience public init(center: C4Point, pointCount: Int, innerRadius: Double, outerRadius: Double) { let wedgeAngle = 2.0 * M_PI / Double(pointCount) var angle = M_PI_2 var pointArray = [C4Point]() for i in 0..<pointCount * 2 { angle += wedgeAngle / 2.0 if i % 2 != 0 { pointArray.append(C4Point(center.x + innerRadius * cos(angle), center.y + innerRadius * sin(angle))) } else { pointArray.append(C4Point(center.x + outerRadius * cos(angle), center.y + outerRadius * sin(angle))) } } self.init(pointArray) self.close() self.fillColor = C4Blue } }
mit
1ee2ccc6d21de36ea837c35ac1f89dff
41.45
116
0.660644
4.367067
false
false
false
false
zshannon/ZCSSlideToAction
Example App/ZCSSlideToAction/SubClassViewController.swift
1
2901
// // SubClassViewController.swift // ZCSSlideToAction // // Created by Zane Shannon on 10/13/14. // Copyright (c) 2014 Zane Shannon. All rights reserved. // import Foundation class SubClassViewController: UIViewController, ZCSSlideToActionViewDelegate { var subClassObject:[String: String]? = nil { didSet (newVal) { println("didSet: \(subClassObject)") if let o = subClassObject { self.sildeToActionViewLabel?.text = o["Label"] as AnyObject? as? String if let bg = o["Background"] as AnyObject? as? String { self.backgroundImageView?.image = UIImage(named: bg) } if let hbg = o["Background-Action"] as AnyObject? as? String { self.backgroundImageView?.highlightedImage = UIImage(named: hbg) } if let klass = NSClassFromString(o["Class"] as AnyObject? as? String) as? NSObject.Type { self.slideToActionView = klass() as? ZCSSlideToActionView if let actionView = self.slideToActionView { actionView.delegate = self self.slideToActionViewPlaceholder!.addSubview(actionView) actionView.awakeFromNib() actionView.frame = self.slideToActionViewPlaceholder!.bounds actionView.layoutSubviews() let singleTapGestureRecognizer = UITapGestureRecognizer(target: actionView, action: "reset") actionView.addGestureRecognizer(singleTapGestureRecognizer) } } } } } @IBOutlet var backgroundImageView:UIImageView? = nil @IBOutlet var slideToActionViewPlaceholder:UIView? = nil var slideToActionView:ZCSSlideToActionView? = nil @IBOutlet var sildeToActionViewLabel:UILabel? = nil var resetLabel:UILabel? = nil override func viewDidLoad() { super.viewDidLoad() if let v = self.slideToActionView { } } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() if let v = self.slideToActionViewPlaceholder { v.frame = CGRectMake(0, 0, view.frame.width, v.frame.height) v.layoutSubviews() } } func slideToActionCancelled(sender:ZCSSlideToActionView) { self.backgroundImageView?.highlighted = false } func slideToActionActivated(sender:ZCSSlideToActionView) { self.backgroundImageView?.highlighted = true if let v = self.slideToActionViewPlaceholder { self.resetLabel = UILabel(frame: v.bounds) self.resetLabel?.text = "Tap to Reset" self.resetLabel?.textColor = UIColor.whiteColor() self.resetLabel?.textAlignment = NSTextAlignment.Center self.resetLabel?.font = UIFont(name: "HelveticaNeue", size: 20) self.resetLabel?.alpha = 0.0 v.addSubview(self.resetLabel!) UIView.animateWithDuration(1.0, animations: { self.resetLabel!.alpha = 1.0 }) } } func slideToActionReset(sender:ZCSSlideToActionView) { self.backgroundImageView?.highlighted = false self.resetLabel?.removeFromSuperview() } }
mit
f7ecb1a1b9904cd9142cfbf09d4c64f1
33.141176
104
0.704585
4.080169
false
false
false
false
nathawes/swift
test/IRGen/struct_resilience.swift
7
19490
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -emit-module -enable-library-evolution -emit-module-path=%t/resilient_struct.swiftmodule -module-name=resilient_struct %S/../Inputs/resilient_struct.swift // RUN: %target-swift-frontend -emit-module -enable-library-evolution -emit-module-path=%t/resilient_enum.swiftmodule -module-name=resilient_enum -I %t %S/../Inputs/resilient_enum.swift // RUN: %target-swift-frontend -module-name struct_resilience -Xllvm -sil-disable-pass=GuaranteedARCOpts -I %t -emit-ir -enable-library-evolution %s | %FileCheck %s // RUN: %target-swift-frontend -module-name struct_resilience -I %t -emit-ir -enable-library-evolution -O %s import resilient_struct import resilient_enum // CHECK: %TSi = type <{ [[INT:i32|i64]] }> // CHECK-LABEL: @"$s17struct_resilience26StructWithResilientStorageVMf" = internal global // Resilient structs from outside our resilience domain are manipulated via // value witnesses // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s17struct_resilience30functionWithResilientTypesSize_1f010resilient_A00G0VAFn_A2FnXEtF"(%swift.opaque* noalias nocapture sret %0, %swift.opaque* noalias nocapture %1, i8* %2, %swift.opaque* %3) public func functionWithResilientTypesSize(_ s: __owned Size, f: (__owned Size) -> Size) -> Size { // CHECK: entry: // CHECK: [[TMP:%.*]] = call swiftcc %swift.metadata_response @"$s16resilient_struct4SizeVMa"([[INT]] 0) // CHECK: [[METADATA:%.*]] = extractvalue %swift.metadata_response [[TMP]], 0 // CHECK: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i8*** // CHECK: [[VWT_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[METADATA_ADDR]], [[INT]] -1 // CHECK: [[VWT:%.*]] = load i8**, i8*** [[VWT_ADDR]] // CHECK-NEXT: [[VWT_CAST:%.*]] = bitcast i8** [[VWT]] to %swift.vwtable* // CHECK-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds %swift.vwtable, %swift.vwtable* [[VWT_CAST]], i32 0, i32 8 // CHECK: [[WITNESS_FOR_SIZE:%.*]] = load [[INT]], [[INT]]* [[WITNESS_ADDR]] // CHECK: [[ALLOCA:%.*]] = alloca i8, {{.*}} [[WITNESS_FOR_SIZE]], align 16 // CHECK: [[STRUCT_ADDR:%.*]] = bitcast i8* [[ALLOCA]] to %swift.opaque* // CHECK: [[WITNESS_PTR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 2 // CHECK: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_PTR]] // CHECK: [[initializeWithCopy:%.*]] = bitcast i8* [[WITNESS]] // CHECK: [[STRUCT_LOC:%.*]] = call %swift.opaque* [[initializeWithCopy]](%swift.opaque* noalias [[STRUCT_ADDR]], %swift.opaque* noalias %1, %swift.type* [[METADATA]]) // CHECK: [[FN:%.*]] = bitcast i8* %2 to void (%swift.opaque*, %swift.opaque*, %swift.refcounted*)* // CHECK: [[SELF:%.*]] = bitcast %swift.opaque* %3 to %swift.refcounted* // CHECK: call swiftcc void [[FN]](%swift.opaque* noalias nocapture sret %0, %swift.opaque* noalias nocapture [[STRUCT_ADDR]], %swift.refcounted* swiftself [[SELF]]) // CHECK: [[WITNESS_PTR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 1 // CHECK: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_PTR]] // CHECK: [[destroy:%.*]] = bitcast i8* [[WITNESS]] to void (%swift.opaque*, %swift.type*)* // CHECK: call void [[destroy]](%swift.opaque* noalias %1, %swift.type* [[METADATA]]) // CHECK-NEXT: bitcast // CHECK-NEXT: call // CHECK-NEXT: ret void return f(s) } // CHECK-LABEL: declare{{( dllimport)?}} swiftcc %swift.metadata_response @"$s16resilient_struct4SizeVMa" // CHECK-SAME: ([[INT]]) // Rectangle has fixed layout inside its resilience domain, and dynamic // layout on the outside. // // Make sure we use a type metadata accessor function, and load indirect // field offsets from it. // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s17struct_resilience35functionWithResilientTypesRectangleyy010resilient_A00G0VF"(%T16resilient_struct9RectangleV* noalias nocapture %0) public func functionWithResilientTypesRectangle(_ r: Rectangle) { // CHECK: entry: // CHECK-NEXT: [[TMP:%.*]] = call swiftcc %swift.metadata_response @"$s16resilient_struct9RectangleVMa"([[INT]] 0) // CHECK-NEXT: [[METADATA:%.*]] = extractvalue %swift.metadata_response [[TMP]], 0 // CHECK-NEXT: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i32* // CHECK-NEXT: [[FIELD_OFFSET_PTR:%.*]] = getelementptr inbounds i32, i32* [[METADATA_ADDR]], [[INT]] [[IDX:2|4|6]] // CHECK-NEXT: [[FIELD_OFFSET:%.*]] = load i32, i32* [[FIELD_OFFSET_PTR]] // CHECK-NEXT: [[STRUCT_ADDR:%.*]] = bitcast %T16resilient_struct9RectangleV* %0 to i8* // CHECK-NEXT: [[FIELD_ADDR:%.*]] = getelementptr inbounds i8, i8* [[STRUCT_ADDR]], i32 [[FIELD_OFFSET]] // CHECK-NEXT: [[FIELD_PTR:%.*]] = bitcast i8* [[FIELD_ADDR]] to %TSi* // CHECK-NEXT: [[FIELD_PAYLOAD_PTR:%.*]] = getelementptr inbounds %TSi, %TSi* [[FIELD_PTR]], i32 0, i32 0 // CHECK-NEXT: [[FIELD_PAYLOAD:%.*]] = load [[INT]], [[INT]]* [[FIELD_PAYLOAD_PTR]] _ = r.color // CHECK-NEXT: ret void } // Resilient structs from inside our resilience domain are manipulated // directly. public struct MySize { public let w: Int public let h: Int } // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s17struct_resilience32functionWithMyResilientTypesSize_1fAA0eH0VAEn_A2EnXEtF"(%T17struct_resilience6MySizeV* noalias nocapture sret %0, %T17struct_resilience6MySizeV* noalias nocapture dereferenceable({{8|(16)}}) %1, i8* %2, %swift.opaque* %3) public func functionWithMyResilientTypesSize(_ s: __owned MySize, f: (__owned MySize) -> MySize) -> MySize { // There's an alloca for debug info? // CHECK: {{%.*}} = alloca %T17struct_resilience6MySizeV // CHECK: [[DST:%.*]] = alloca %T17struct_resilience6MySizeV // CHECK: [[W_ADDR:%.*]] = getelementptr inbounds %T17struct_resilience6MySizeV, %T17struct_resilience6MySizeV* %1, i32 0, i32 0 // CHECK: [[W_PTR:%.*]] = getelementptr inbounds %TSi, %TSi* [[W_ADDR]], i32 0, i32 0 // CHECK: [[W:%.*]] = load [[INT]], [[INT]]* [[W_PTR]] // CHECK: [[H_ADDR:%.*]] = getelementptr inbounds %T17struct_resilience6MySizeV, %T17struct_resilience6MySizeV* %1, i32 0, i32 1 // CHECK: [[H_PTR:%.*]] = getelementptr inbounds %TSi, %TSi* [[H_ADDR]], i32 0, i32 0 // CHECK: [[H:%.*]] = load [[INT]], [[INT]]* [[H_PTR]] // CHECK: [[DST_ADDR:%.*]] = bitcast %T17struct_resilience6MySizeV* [[DST]] to i8* // CHECK: call void @llvm.lifetime.start.p0i8({{i32|i64}} {{8|16}}, i8* [[DST_ADDR]]) // CHECK: [[W_ADDR:%.*]] = getelementptr inbounds %T17struct_resilience6MySizeV, %T17struct_resilience6MySizeV* [[DST]], i32 0, i32 0 // CHECK: [[W_PTR:%.*]] = getelementptr inbounds %TSi, %TSi* [[W_ADDR]], i32 0, i32 0 // CHECK: store [[INT]] [[W]], [[INT]]* [[W_PTR]] // CHECK: [[H_ADDR:%.*]] = getelementptr inbounds %T17struct_resilience6MySizeV, %T17struct_resilience6MySizeV* [[DST]], i32 0, i32 1 // CHECK: [[H_PTR:%.*]] = getelementptr inbounds %TSi, %TSi* [[H_ADDR]], i32 0, i32 0 // CHECK: store [[INT]] [[H]], [[INT]]* [[H_PTR]] // CHECK: [[FN:%.*]] = bitcast i8* %2 to void (%T17struct_resilience6MySizeV*, %T17struct_resilience6MySizeV*, %swift.refcounted*)* // CHECK: [[CONTEXT:%.*]] = bitcast %swift.opaque* %3 to %swift.refcounted* // CHECK: call swiftcc void [[FN]](%T17struct_resilience6MySizeV* noalias nocapture sret %0, %T17struct_resilience6MySizeV* noalias nocapture dereferenceable({{8|16}}) [[DST]], %swift.refcounted* swiftself [[CONTEXT]]) // CHECK: [[DST_ADDR:%.*]] = bitcast %T17struct_resilience6MySizeV* [[DST]] to i8* // CHECK: call void @llvm.lifetime.end.p0i8({{i32|i64}} {{8|16}}, i8* [[DST_ADDR]]) // CHECK: ret void return f(s) } // Structs with resilient storage from a different resilience domain require // runtime metadata instantiation, just like generics. public struct StructWithResilientStorage { public let s: Size public let ss: (Size, Size) public let n: Int public let i: ResilientInt } // Make sure we call a function to access metadata of structs with // resilient layout, and go through the field offset vector in the // metadata when accessing stored properties. // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc {{i32|i64}} @"$s17struct_resilience26StructWithResilientStorageV1nSivg"(%T17struct_resilience26StructWithResilientStorageV* {{.*}}) // CHECK: [[TMP:%.*]] = call swiftcc %swift.metadata_response @"$s17struct_resilience26StructWithResilientStorageVMa"([[INT]] 0) // CHECK: [[METADATA:%.*]] = extractvalue %swift.metadata_response [[TMP]], 0 // CHECK-NEXT: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i32* // CHECK-NEXT: [[FIELD_OFFSET_PTR:%.*]] = getelementptr inbounds i32, i32* [[METADATA_ADDR]], [[INT]] [[IDX:2|4|6]] // CHECK-NEXT: [[FIELD_OFFSET:%.*]] = load i32, i32* [[FIELD_OFFSET_PTR]] // CHECK-NEXT: [[STRUCT_ADDR:%.*]] = bitcast %T17struct_resilience26StructWithResilientStorageV* %0 to i8* // CHECK-NEXT: [[FIELD_ADDR:%.*]] = getelementptr inbounds i8, i8* [[STRUCT_ADDR]], i32 [[FIELD_OFFSET]] // CHECK-NEXT: [[FIELD_PTR:%.*]] = bitcast i8* [[FIELD_ADDR]] to %TSi* // CHECK-NEXT: [[FIELD_PAYLOAD_PTR:%.*]] = getelementptr inbounds %TSi, %TSi* [[FIELD_PTR]], i32 0, i32 0 // CHECK-NEXT: [[FIELD_PAYLOAD:%.*]] = load [[INT]], [[INT]]* [[FIELD_PAYLOAD_PTR]] // CHECK-NEXT: ret [[INT]] [[FIELD_PAYLOAD]] // Indirect enums with resilient payloads are still fixed-size. public struct StructWithIndirectResilientEnum { public let s: FunnyShape public let n: Int } // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc {{i32|i64}} @"$s17struct_resilience31StructWithIndirectResilientEnumV1nSivg"(%T17struct_resilience31StructWithIndirectResilientEnumV* {{.*}}) // CHECK: [[FIELD_PTR:%.*]] = getelementptr inbounds %T17struct_resilience31StructWithIndirectResilientEnumV, %T17struct_resilience31StructWithIndirectResilientEnumV* %0, i32 0, i32 1 // CHECK-NEXT: [[FIELD_PAYLOAD_PTR:%.*]] = getelementptr inbounds %TSi, %TSi* [[FIELD_PTR]], i32 0, i32 0 // CHECK-NEXT: [[FIELD_PAYLOAD:%.*]] = load [[INT]], [[INT]]* [[FIELD_PAYLOAD_PTR]] // CHECK: ret [[INT]] [[FIELD_PAYLOAD]] // Partial application of methods on resilient value types public struct ResilientStructWithMethod { public func method() {} } // Corner case -- type is address-only in SIL, but empty in IRGen // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s17struct_resilience29partialApplyOfResilientMethod1ryAA0f10StructWithG0V_tF"(%T17struct_resilience25ResilientStructWithMethodV* noalias nocapture %0) public func partialApplyOfResilientMethod(r: ResilientStructWithMethod) { _ = r.method } // Type is address-only in SIL, and resilient in IRGen // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s17struct_resilience29partialApplyOfResilientMethod1sy010resilient_A04SizeV_tF"(%swift.opaque* noalias nocapture %0) public func partialApplyOfResilientMethod(s: Size) { _ = s.method } public func wantsAny(_ any: Any) {} public func resilientAny(s : ResilientWeakRef) { wantsAny(s) } // CHECK-LABEL: define{{.*}} swiftcc void @"$s17struct_resilience12resilientAny1sy0c1_A016ResilientWeakRefV_tF"(%swift.opaque* noalias nocapture %0) // CHECK: entry: // CHECK: [[ANY:%.*]] = alloca %Any // CHECK: [[META:%.*]] = call swiftcc %swift.metadata_response @"$s16resilient_struct16ResilientWeakRefVMa"([[INT]] 0) // CHECK: [[META2:%.*]] = extractvalue %swift.metadata_response %3, 0 // CHECK: [[TYADDR:%.*]] = getelementptr inbounds %Any, %Any* [[ANY]], i32 0, i32 1 // CHECK: store %swift.type* [[META2]], %swift.type** [[TYADDR]] // CHECK: [[BITCAST:%.*]] = bitcast %Any* [[ANY]] to %__opaque_existential_type_0* // CHECK: call %swift.opaque* @__swift_allocate_boxed_opaque_existential_0(%__opaque_existential_type_0* [[BITCAST]]) // CHECK: call swiftcc void @"$s17struct_resilience8wantsAnyyyypF"(%Any* noalias nocapture dereferenceable({{(32|16)}}) [[ANY]]) // CHECK: [[BITCAST:%.*]] = bitcast %Any* [[ANY]] to %__opaque_existential_type_0* // CHECK: call void @__swift_destroy_boxed_opaque_existential_0(%__opaque_existential_type_0* [[BITCAST]]) // CHECK: ret void // Make sure that MemoryLayout properties access resilient types' metadata // instead of hardcoding sizes based on compile-time layouts. // CHECK-LABEL: define{{.*}} swiftcc {{i32|i64}} @"$s17struct_resilience38memoryLayoutDotSizeWithResilientStructSiyF"() public func memoryLayoutDotSizeWithResilientStruct() -> Int { // CHECK: entry: // CHECK: [[TMP:%.*]] = call swiftcc %swift.metadata_response @"$s16resilient_struct4SizeVMa"([[INT]] 0) // CHECK: [[METADATA:%.*]] = extractvalue %swift.metadata_response [[TMP]], 0 // CHECK: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i8*** // CHECK: [[VWT_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[METADATA_ADDR]], [[INT]] -1 // CHECK: [[VWT:%.*]] = load i8**, i8*** [[VWT_ADDR]] // CHECK-NEXT: [[VWT_CAST:%.*]] = bitcast i8** [[VWT]] to %swift.vwtable* // CHECK-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds %swift.vwtable, %swift.vwtable* [[VWT_CAST]], i32 0, i32 8 // CHECK: [[WITNESS_FOR_SIZE:%.*]] = load [[INT]], [[INT]]* [[WITNESS_ADDR]] // CHECK: ret [[INT]] [[WITNESS_FOR_SIZE]] return MemoryLayout<Size>.size } // CHECK-LABEL: define{{.*}} swiftcc {{i32|i64}} @"$s17struct_resilience40memoryLayoutDotStrideWithResilientStructSiyF"() public func memoryLayoutDotStrideWithResilientStruct() -> Int { // CHECK: entry: // CHECK: [[TMP:%.*]] = call swiftcc %swift.metadata_response @"$s16resilient_struct4SizeVMa"([[INT]] 0) // CHECK: [[METADATA:%.*]] = extractvalue %swift.metadata_response [[TMP]], 0 // CHECK: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i8*** // CHECK: [[VWT_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[METADATA_ADDR]], [[INT]] -1 // CHECK: [[VWT:%.*]] = load i8**, i8*** [[VWT_ADDR]] // CHECK-NEXT: [[VWT_CAST:%.*]] = bitcast i8** [[VWT]] to %swift.vwtable* // CHECK-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds %swift.vwtable, %swift.vwtable* [[VWT_CAST]], i32 0, i32 9 // CHECK: [[WITNESS_FOR_STRIDE:%.*]] = load [[INT]], [[INT]]* [[WITNESS_ADDR]] // CHECK: ret [[INT]] [[WITNESS_FOR_STRIDE]] return MemoryLayout<Size>.stride } // CHECK-LABEL: define{{.*}} swiftcc {{i32|i64}} @"$s17struct_resilience43memoryLayoutDotAlignmentWithResilientStructSiyF"() public func memoryLayoutDotAlignmentWithResilientStruct() -> Int { // CHECK: entry: // CHECK: [[TMP:%.*]] = call swiftcc %swift.metadata_response @"$s16resilient_struct4SizeVMa"([[INT]] 0) // CHECK: [[METADATA:%.*]] = extractvalue %swift.metadata_response [[TMP]], 0 // CHECK: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i8*** // CHECK: [[VWT_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[METADATA_ADDR]], [[INT]] -1 // CHECK: [[VWT:%.*]] = load i8**, i8*** [[VWT_ADDR]] // CHECK-NEXT: [[VWT_CAST:%.*]] = bitcast i8** [[VWT]] to %swift.vwtable* // CHECK-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds %swift.vwtable, %swift.vwtable* [[VWT_CAST]], i32 0, i32 10 // CHECK: [[WITNESS_FOR_FLAGS:%.*]] = load i32, i32* [[WITNESS_ADDR]] // Not checked because it only exists on 64-bit: [[EXTENDED_FLAGS:%.*]] = zext i32 [[WITNESS_FOR_FLAGS]] to [[INT]] // CHECK: [[ALIGNMENT_MASK:%.*]] = and [[INT]] {{%.*}}, 255 // CHECK: [[ALIGNMENT:%.*]] = add [[INT]] [[ALIGNMENT_MASK]], 1 // CHECK: ret [[INT]] [[ALIGNMENT]] return MemoryLayout<Size>.alignment } // Make sure that MemoryLayout.offset(of:) on a resilient type uses the accessor // in the key path instead of hardcoding offsets based on compile-time layouts. // CHECK-LABEL: define{{.*}} swiftcc { {{i32|i64}}, i8 } @"$s17struct_resilience42memoryLayoutDotOffsetOfWithResilientStructSiSgyF"() public func memoryLayoutDotOffsetOfWithResilientStruct() -> Int? { // CHECK-NEXT: entry: // CHECK: [[RAW_KEY_PATH:%.*]] = call %swift.refcounted* @swift_getKeyPath // CHECK: [[WRITABLE_KEY_PATH:%.*]] = bitcast %swift.refcounted* [[RAW_KEY_PATH]] to %Ts15WritableKeyPathCy16resilient_struct4SizeVSiG* // CHECK: [[PARTIAL_KEY_PATH:%.*]] = bitcast %Ts15WritableKeyPathCy16resilient_struct4SizeVSiG* [[WRITABLE_KEY_PATH]] to %Ts14PartialKeyPathCy16resilient_struct4SizeVG* // CHECK: [[ANY_KEY_PATH:%.*]] = bitcast %Ts14PartialKeyPathCy16resilient_struct4SizeVG* [[PARTIAL_KEY_PATH]] to %Ts10AnyKeyPathC* // CHECK: [[STORED_INLINE_OFFSET:%.*]] = call swiftcc { [[INT]], i8 } @"$ss10AnyKeyPathC19_storedInlineOffsetSiSgvgTj"(%Ts10AnyKeyPathC* swiftself [[ANY_KEY_PATH]]) // CHECK: [[VALUE:%.*]] = extractvalue { [[INT]], i8 } [[STORED_INLINE_OFFSET]], 0 // CHECK: [[RET_PARTIAL:%.*]] = insertvalue { [[INT]], i8 } undef, [[INT]] [[VALUE]], 0 // CHECK: [[RET:%.*]] = insertvalue { [[INT]], i8 } [[RET_PARTIAL]] // CHECK: ret { [[INT]], i8 } [[RET]] return MemoryLayout<Size>.offset(of: \Size.w) } // Public metadata accessor for our resilient struct // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc %swift.metadata_response @"$s17struct_resilience6MySizeVMa" // CHECK-SAME: ([[INT]] %0) // CHECK: ret %swift.metadata_response { %swift.type* bitcast ([[INT]]* getelementptr inbounds {{.*}} @"$s17struct_resilience6MySizeVMf", i32 0, i32 1) to %swift.type*), [[INT]] 0 } // CHECK-LABEL: define internal swiftcc %swift.metadata_response @"$s17struct_resilience26StructWithResilientStorageVMr"(%swift.type* %0, i8* %1, i8** %2) // CHECK: [[FIELDS:%.*]] = alloca [4 x i8**] // CHECK: [[TUPLE_LAYOUT:%.*]] = alloca %swift.full_type_layout, // CHECK: [[FIELDS_ADDR:%.*]] = getelementptr inbounds [4 x i8**], [4 x i8**]* [[FIELDS]], i32 0, i32 0 // public let s: Size // CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s16resilient_struct4SizeVMa"([[INT]] 319) // CHECK: [[SIZE_METADATA:%.*]] = extractvalue %swift.metadata_response [[T0]], 0 // CHECK: [[T0:%.*]] = bitcast %swift.type* [[SIZE_METADATA]] to i8*** // CHECK: [[T1:%.*]] = getelementptr inbounds i8**, i8*** [[T0]], [[INT]] -1 // CHECK: [[SIZE_VWT:%.*]] = load i8**, i8*** [[T1]], // CHECK: [[SIZE_LAYOUT_1:%.*]] = getelementptr inbounds i8*, i8** [[SIZE_VWT]], i32 8 // CHECK: [[FIELD_1:%.*]] = getelementptr inbounds i8**, i8*** [[FIELDS_ADDR]], i32 0 // CHECK: store i8** [[SIZE_LAYOUT_1:%.*]], i8*** [[FIELD_1]] // public let ss: (Size, Size) // CHECK: [[SIZE_LAYOUT_2:%.*]] = getelementptr inbounds i8*, i8** [[SIZE_VWT]], i32 8 // CHECK: [[SIZE_LAYOUT_3:%.*]] = getelementptr inbounds i8*, i8** [[SIZE_VWT]], i32 8 // CHECK: call swiftcc [[INT]] @swift_getTupleTypeLayout2(%swift.full_type_layout* [[TUPLE_LAYOUT]], i8** [[SIZE_LAYOUT_2]], i8** [[SIZE_LAYOUT_3]]) // CHECK: [[T0:%.*]] = bitcast %swift.full_type_layout* [[TUPLE_LAYOUT]] to i8** // CHECK: [[FIELD_2:%.*]] = getelementptr inbounds i8**, i8*** [[FIELDS_ADDR]], i32 1 // CHECK: store i8** [[T0]], i8*** [[FIELD_2]] // Fixed-layout aggregate -- we can reference a static value witness table // public let n: Int // CHECK: [[FIELD_3:%.*]] = getelementptr inbounds i8**, i8*** [[FIELDS_ADDR]], i32 2 // CHECK: store i8** getelementptr inbounds (i8*, i8** @"$sBi{{32|64}}_WV", i32 {{.*}}), i8*** [[FIELD_3]] // Resilient aggregate with one field -- make sure we don't look inside it // public let i: ResilientInt // CHECK: call swiftcc %swift.metadata_response @"$s16resilient_struct12ResilientIntVMa"([[INT]] 319) // CHECK: [[FIELD_4:%.*]] = getelementptr inbounds i8**, i8*** [[FIELDS_ADDR]], i32 3 // CHECK: store i8** [[SIZE_AND_ALIGNMENT:%.*]], i8*** [[FIELD_4]] // CHECK: call void @swift_initStructMetadata(%swift.type* {{.*}}, [[INT]] 256, [[INT]] 4, i8*** [[FIELDS_ADDR]], i32* {{.*}})
apache-2.0
c64dea7dc217713907bcdccc77c748ff
56.155425
316
0.662134
3.503505
false
false
false
false
crazypoo/PTools
Pods/PhoneNumberKit/PhoneNumberKit/Formatter.swift
2
5396
// // Formatter.swift // PhoneNumberKit // // Created by Roy Marmelstein on 03/11/2015. // Copyright © 2021 Roy Marmelstein. All rights reserved. // import Foundation final class Formatter { weak var regexManager: RegexManager? init(phoneNumberKit: PhoneNumberKit) { self.regexManager = phoneNumberKit.regexManager } init(regexManager: RegexManager) { self.regexManager = regexManager } // MARK: Formatting functions /// Formats phone numbers for display /// /// - Parameters: /// - phoneNumber: Phone number object. /// - formatType: Format type. /// - regionMetadata: Region meta data. /// - Returns: Formatted Modified national number ready for display. func format(phoneNumber: PhoneNumber, formatType: PhoneNumberFormat, regionMetadata: MetadataTerritory?) -> String { var formattedNationalNumber = phoneNumber.adjustedNationalNumber() if let regionMetadata = regionMetadata { formattedNationalNumber = self.formatNationalNumber(formattedNationalNumber, regionMetadata: regionMetadata, formatType: formatType) if let formattedExtension = formatExtension(phoneNumber.numberExtension, regionMetadata: regionMetadata) { formattedNationalNumber = formattedNationalNumber + formattedExtension } } return formattedNationalNumber } /// Formats extension for display /// /// - Parameters: /// - numberExtension: Number extension string. /// - regionMetadata: Region meta data. /// - Returns: Modified number extension with either a preferred extension prefix or the default one. func formatExtension(_ numberExtension: String?, regionMetadata: MetadataTerritory) -> String? { if let extns = numberExtension { if let preferredExtnPrefix = regionMetadata.preferredExtnPrefix { return "\(preferredExtnPrefix)\(extns)" } else { return "\(PhoneNumberConstants.defaultExtnPrefix)\(extns)" } } return nil } /// Formats national number for display /// /// - Parameters: /// - nationalNumber: National number string. /// - regionMetadata: Region meta data. /// - formatType: Format type. /// - Returns: Modified nationalNumber for display. func formatNationalNumber(_ nationalNumber: String, regionMetadata: MetadataTerritory, formatType: PhoneNumberFormat) -> String { guard let regexManager = regexManager else { return nationalNumber } let formats = regionMetadata.numberFormats var selectedFormat: MetadataPhoneNumberFormat? for format in formats { if let leadingDigitPattern = format.leadingDigitsPatterns?.last { if regexManager.stringPositionByRegex(leadingDigitPattern, string: String(nationalNumber)) == 0 { if regexManager.matchesEntirely(format.pattern, string: String(nationalNumber)) { selectedFormat = format break } } } else { if regexManager.matchesEntirely(format.pattern, string: String(nationalNumber)) { selectedFormat = format break } } } if let formatPattern = selectedFormat { guard let numberFormatRule = (formatType == PhoneNumberFormat.international && formatPattern.intlFormat != nil) ? formatPattern.intlFormat : formatPattern.format, let pattern = formatPattern.pattern else { return nationalNumber } var formattedNationalNumber = String() var prefixFormattingRule = String() if let nationalPrefixFormattingRule = formatPattern.nationalPrefixFormattingRule, let nationalPrefix = regionMetadata.nationalPrefix { prefixFormattingRule = regexManager.replaceStringByRegex(PhoneNumberPatterns.npPattern, string: nationalPrefixFormattingRule, template: nationalPrefix) prefixFormattingRule = regexManager.replaceStringByRegex(PhoneNumberPatterns.fgPattern, string: prefixFormattingRule, template: "\\$1") } if formatType == PhoneNumberFormat.national, regexManager.hasValue(prefixFormattingRule) { let replacePattern = regexManager.replaceFirstStringByRegex(PhoneNumberPatterns.firstGroupPattern, string: numberFormatRule, templateString: prefixFormattingRule) formattedNationalNumber = regexManager.replaceStringByRegex(pattern, string: nationalNumber, template: replacePattern) } else { formattedNationalNumber = regexManager.replaceStringByRegex(pattern, string: nationalNumber, template: numberFormatRule) } return formattedNationalNumber } else { return nationalNumber } } } public extension PhoneNumber { /** Adjust national number for display by adding leading zero if needed. Used for basic formatting functions. - Returns: A string representing the adjusted national number. */ func adjustedNationalNumber() -> String { if self.leadingZero == true { return "0" + String(nationalNumber) } else { return String(nationalNumber) } } }
mit
83c849b6b1b93a87f919c7aaad23eef2
43.958333
217
0.662836
5.619792
false
false
false
false
AbelSu131/ios-charts
Charts/Classes/Renderers/CombinedChartRenderer.swift
2
13294
// // CombinedChartRenderer.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics public class CombinedChartRenderer: ChartDataRendererBase, LineChartRendererDelegate, BarChartRendererDelegate, ScatterChartRendererDelegate, CandleStickChartRendererDelegate, BubbleChartRendererDelegate { private weak var _chart: CombinedChartView!; /// flag that enables or disables the highlighting arrow public var drawHighlightArrowEnabled = false; /// if set to true, all values are drawn above their bars, instead of below their top public var drawValueAboveBarEnabled = true; /// if set to true, all values of a stack are drawn individually, and not just their sum public var drawValuesForWholeStackEnabled = true; /// if set to true, a grey area is darawn behind each bar that indicates the maximum value public var drawBarShadowEnabled = true; internal var _renderers = [ChartDataRendererBase](); internal var _drawOrder: [CombinedChartView.CombinedChartDrawOrder] = [.Bar, .Bubble, .Line, .Candle, .Scatter]; public init(chart: CombinedChartView, animator: ChartAnimator, viewPortHandler: ChartViewPortHandler) { super.init(animator: animator, viewPortHandler: viewPortHandler); _chart = chart; createRenderers(); } /// Creates the renderers needed for this combined-renderer in the required order. Also takes the DrawOrder into consideration. internal func createRenderers() { _renderers = [ChartDataRendererBase](); for order in drawOrder { switch (order) { case .Bar: if (_chart.barData !== nil) { _renderers.append(BarChartRenderer(delegate: self, animator: _animator, viewPortHandler: viewPortHandler)); } break; case .Line: if (_chart.lineData !== nil) { _renderers.append(LineChartRenderer(delegate: self, animator: _animator, viewPortHandler: viewPortHandler)); } break; case .Candle: if (_chart.candleData !== nil) { _renderers.append(CandleStickChartRenderer(delegate: self, animator: _animator, viewPortHandler: viewPortHandler)); } break; case .Scatter: if (_chart.scatterData !== nil) { _renderers.append(ScatterChartRenderer(delegate: self, animator: _animator, viewPortHandler: viewPortHandler)); } break; case .Bubble: if (_chart.bubbleData !== nil) { _renderers.append(BubbleChartRenderer(delegate: self, animator: _animator, viewPortHandler: viewPortHandler)); } break; } } } public override func drawData(#context: CGContext) { for renderer in _renderers { renderer.drawData(context: context); } } public override func drawValues(#context: CGContext) { for renderer in _renderers { renderer.drawValues(context: context); } } public override func drawExtras(#context: CGContext) { for renderer in _renderers { renderer.drawExtras(context: context); } } public override func drawHighlighted(#context: CGContext, indices: [ChartHighlight]) { for renderer in _renderers { renderer.drawHighlighted(context: context, indices: indices); } } public override func calcXBounds(#chart: BarLineChartViewBase, xAxisModulus: Int) { for renderer in _renderers { renderer.calcXBounds(chart: chart, xAxisModulus: xAxisModulus); } } /// Returns the sub-renderer object at the specified index. public func getSubRenderer(#index: Int) -> ChartDataRendererBase! { if (index >= _renderers.count || index < 0) { return nil; } else { return _renderers[index]; } } // MARK: - LineChartRendererDelegate public func lineChartRendererData(renderer: LineChartRenderer) -> LineChartData! { return _chart.lineData; } public func lineChartRenderer(renderer: LineChartRenderer, transformerForAxis which: ChartYAxis.AxisDependency) -> ChartTransformer! { return _chart.getTransformer(which); } public func lineChartRendererFillFormatter(renderer: LineChartRenderer) -> ChartFillFormatter { return _chart.fillFormatter; } public func lineChartDefaultRendererValueFormatter(renderer: LineChartRenderer) -> NSNumberFormatter! { return _chart._defaultValueFormatter; } public func lineChartRendererChartYMax(renderer: LineChartRenderer) -> Double { return _chart.chartYMax; } public func lineChartRendererChartYMin(renderer: LineChartRenderer) -> Double { return _chart.chartYMin; } public func lineChartRendererChartXMax(renderer: LineChartRenderer) -> Double { return _chart.chartXMax; } public func lineChartRendererChartXMin(renderer: LineChartRenderer) -> Double { return _chart.chartXMin; } public func lineChartRendererMaxVisibleValueCount(renderer: LineChartRenderer) -> Int { return _chart.maxVisibleValueCount; } // MARK: - BarChartRendererDelegate public func barChartRendererData(renderer: BarChartRenderer) -> BarChartData! { return _chart.barData; } public func barChartRenderer(renderer: BarChartRenderer, transformerForAxis which: ChartYAxis.AxisDependency) -> ChartTransformer! { return _chart.getTransformer(which); } public func barChartRendererMaxVisibleValueCount(renderer: BarChartRenderer) -> Int { return _chart.maxVisibleValueCount; } public func barChartDefaultRendererValueFormatter(renderer: BarChartRenderer) -> NSNumberFormatter! { return _chart._defaultValueFormatter; } public func barChartRendererChartYMax(renderer: BarChartRenderer) -> Double { return _chart.chartYMax; } public func barChartRendererChartYMin(renderer: BarChartRenderer) -> Double { return _chart.chartYMin; } public func barChartRendererChartXMax(renderer: BarChartRenderer) -> Double { return _chart.chartXMax; } public func barChartRendererChartXMin(renderer: BarChartRenderer) -> Double { return _chart.chartXMin; } public func barChartIsDrawHighlightArrowEnabled(renderer: BarChartRenderer) -> Bool { return drawHighlightArrowEnabled; } public func barChartIsDrawValueAboveBarEnabled(renderer: BarChartRenderer) -> Bool { return drawValueAboveBarEnabled; } public func barChartIsDrawValuesForWholeStackEnabled(renderer: BarChartRenderer) -> Bool { return drawValuesForWholeStackEnabled; } public func barChartIsDrawBarShadowEnabled(renderer: BarChartRenderer) -> Bool { return drawBarShadowEnabled; } public func barChartIsInverted(renderer: BarChartRenderer, axis: ChartYAxis.AxisDependency) -> Bool { return _chart.getAxis(axis).isInverted; } // MARK: - ScatterChartRendererDelegate public func scatterChartRendererData(renderer: ScatterChartRenderer) -> ScatterChartData! { return _chart.scatterData; } public func scatterChartRenderer(renderer: ScatterChartRenderer, transformerForAxis which: ChartYAxis.AxisDependency) -> ChartTransformer! { return _chart.getTransformer(which); } public func scatterChartDefaultRendererValueFormatter(renderer: ScatterChartRenderer) -> NSNumberFormatter! { return _chart._defaultValueFormatter; } public func scatterChartRendererChartYMax(renderer: ScatterChartRenderer) -> Double { return _chart.chartYMax; } public func scatterChartRendererChartYMin(renderer: ScatterChartRenderer) -> Double { return _chart.chartYMin; } public func scatterChartRendererChartXMax(renderer: ScatterChartRenderer) -> Double { return _chart.chartXMax; } public func scatterChartRendererChartXMin(renderer: ScatterChartRenderer) -> Double { return _chart.chartXMin; } public func scatterChartRendererMaxVisibleValueCount(renderer: ScatterChartRenderer) -> Int { return _chart.maxVisibleValueCount; } // MARK: - CandleStickChartRendererDelegate public func candleStickChartRendererCandleData(renderer: CandleStickChartRenderer) -> CandleChartData! { return _chart.candleData; } public func candleStickChartRenderer(renderer: CandleStickChartRenderer, transformerForAxis which: ChartYAxis.AxisDependency) -> ChartTransformer! { return _chart.getTransformer(which); } public func candleStickChartDefaultRendererValueFormatter(renderer: CandleStickChartRenderer) -> NSNumberFormatter! { return _chart._defaultValueFormatter; } public func candleStickChartRendererChartYMax(renderer: CandleStickChartRenderer) -> Double { return _chart.chartYMax; } public func candleStickChartRendererChartYMin(renderer: CandleStickChartRenderer) -> Double { return _chart.chartYMin; } public func candleStickChartRendererChartXMax(renderer: CandleStickChartRenderer) -> Double { return _chart.chartXMax; } public func candleStickChartRendererChartXMin(renderer: CandleStickChartRenderer) -> Double { return _chart.chartXMin; } public func candleStickChartRendererMaxVisibleValueCount(renderer: CandleStickChartRenderer) -> Int { return _chart.maxVisibleValueCount; } // MARK: - BubbleChartRendererDelegate public func bubbleChartRendererData(renderer: BubbleChartRenderer) -> BubbleChartData! { return _chart.bubbleData; } public func bubbleChartRenderer(renderer: BubbleChartRenderer, transformerForAxis which: ChartYAxis.AxisDependency) -> ChartTransformer! { return _chart.getTransformer(which); } public func bubbleChartDefaultRendererValueFormatter(renderer: BubbleChartRenderer) -> NSNumberFormatter! { return _chart._defaultValueFormatter; } public func bubbleChartRendererChartYMax(renderer: BubbleChartRenderer) -> Double { return _chart.chartYMax; } public func bubbleChartRendererChartYMin(renderer: BubbleChartRenderer) -> Double { return _chart.chartYMin; } public func bubbleChartRendererChartXMax(renderer: BubbleChartRenderer) -> Double { return _chart.chartXMax; } public func bubbleChartRendererChartXMin(renderer: BubbleChartRenderer) -> Double { return _chart.chartXMin; } public func bubbleChartRendererMaxVisibleValueCount(renderer: BubbleChartRenderer) -> Int { return _chart.maxVisibleValueCount; } public func bubbleChartRendererXValCount(renderer: BubbleChartRenderer) -> Int { return _chart.data!.xValCount; } // MARK: Accessors /// returns true if drawing the highlighting arrow is enabled, false if not public var isDrawHighlightArrowEnabled: Bool { return drawHighlightArrowEnabled; } /// returns true if drawing values above bars is enabled, false if not public var isDrawValueAboveBarEnabled: Bool { return drawValueAboveBarEnabled; } /// returns true if all values of a stack are drawn, and not just their sum public var isDrawValuesForWholeStackEnabled: Bool { return drawValuesForWholeStackEnabled; } /// returns true if drawing shadows (maxvalue) for each bar is enabled, false if not public var isDrawBarShadowEnabled: Bool { return drawBarShadowEnabled; } /// the order in which the provided data objects should be drawn. /// The earlier you place them in the provided array, the further they will be in the background. /// e.g. if you provide [DrawOrder.Bar, DrawOrder.Line], the bars will be drawn behind the lines. public var drawOrder: [CombinedChartView.CombinedChartDrawOrder] { get { return _drawOrder; } set { if (newValue.count > 0) { _drawOrder = newValue; } } } }
apache-2.0
b722420a422a75ce465c1db4f7cbd8d6
30.063084
150
0.651196
5.840949
false
false
false
false
openbuild-sheffield/jolt
Sources/RouteCMS/route.CMSPageAdd.swift
1
3946
import Foundation import PerfectLib import PerfectHTTP import OpenbuildExtensionCore import OpenbuildExtensionPerfect import OpenbuildMysql import OpenbuildRepository import OpenbuildRouteRegistry import OpenbuildSingleton public class RequestCMSPageAdd: OpenbuildExtensionPerfect.RequestProtocol { public var method: String public var uri: String public var description: String = "Add a CMS page." public var validation: OpenbuildExtensionPerfect.RequestValidation public init(method: String, uri: String){ self.method = method self.uri = uri self.validation = OpenbuildExtensionPerfect.RequestValidation() self.validation.addValidators(validators: [ //ValidateTokenRoles, ValidateBodyPageURI, ValidateBodyTemplatePath, ValidateBodyPageTitle, ValidateBodyPageDescription, ValidateBodyPageVariables ]) } } public let handlerRouteCMSPageAdd = { (request: HTTPRequest, response: HTTPResponse) in guard let handlerResponse = RouteRegistry.getHandlerResponse( uri: request.path.lowercased(), method: request.method, response: response ) else { return } print("handlerRouteCMSWordsAdd") print() print(request.validatedRequestData as Any) print(request.validatedRequestData?.validated["uri"] as! String) print(request.validatedRequestData?.validated["template_path"] as! String) print(request.validatedRequestData?.validated["title"] as! String) print(request.validatedRequestData?.validated["description"] as! String) print(request.validatedRequestData?.validated["variables"] as! [Any]) // response.appendBody(string: "handlerRouteCMSWordsAdd") // response.completed() do { var repository = try RepositoryCMSPage() var model = ModelCMSPage( uri: request.validatedRequestData?.validated["uri"] as! String, template_path: request.validatedRequestData?.validated["template_path"] as! String, title: request.validatedRequestData?.validated["title"] as! String, description: request.validatedRequestData?.validated["description"] as! String, variables: request.validatedRequestData?.validated["variables"] as! [Any] ) let entity = repository.create( model: model ) if entity.errors.isEmpty { //Success handlerResponse.complete( status: 200, model: ModelCMSPage200Entity(entity: entity) ) } else { //422 Unprocessable Entity handlerResponse.complete( status: 422, model: ResponseModel422( validation: request.validatedRequestData!, messages: [ "added": false, "errors": entity.errors ] ) ) } } catch { print(error) handlerResponse.complete( status: 500, model: ResponseModel500Messages(messages: [ "message": "Failed to generate a successful response." ]) ) } } public class RouteCMSPageAdd: OpenbuildRouteRegistry.FactoryRoute { override public func route() -> NamedRoute? { let handlerResponse = ResponseDefined() handlerResponse.register(status: 200, model: "RouteCMS.ModelCMSPage200Entity") handlerResponse.register(status: 403) handlerResponse.register(status: 422) handlerResponse.register(status: 500) return NamedRoute( handlerRequest: RequestCMSPageAdd( method: "post", uri: "/api/cms/page" ), handlerResponse: handlerResponse, handlerRoute: handlerRouteCMSPageAdd ) } }
gpl-2.0
b274022cc04cdfd95e8a74c471c925a1
28.237037
95
0.630765
5.124675
false
false
false
false
wwq0327/iOS8Example
Diary/Diary/DiaryViewController.swift
1
5355
// // DiaryViewController.swift // Diary // // Created by wyatt on 15/6/14. // Copyright (c) 2015年 Wanqing Wang. All rights reserved. // import UIKit class DiaryViewController: UIViewController, UIWebViewDelegate, UIScrollViewDelegate, UIGestureRecognizerDelegate { var diary: Diary! var webView: UIWebView! override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.whiteColor() setupUI() } func setupUI() { webView = UIWebView(frame: CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)) webView.scrollView.bounces = true webView.delegate = self webView.backgroundColor = UIColor.whiteColor() self.view.addSubview(webView) // 添加手势 var mDoubleUpRecognizer = UITapGestureRecognizer(target: self, action: "hideDiary") mDoubleUpRecognizer.delegate = self mDoubleUpRecognizer.numberOfTapsRequired = 2 self.webView.addGestureRecognizer(mDoubleUpRecognizer) var mTapUpRecognizer = UITapGestureRecognizer(target: self, action: "showButtons") mTapUpRecognizer.delegate = self mTapUpRecognizer.numberOfTapsRequired = 1 self.webView.addGestureRecognizer(mTapUpRecognizer) mTapUpRecognizer.requireGestureRecognizerToFail(mDoubleUpRecognizer) webView.alpha = 0.0 NSNotificationCenter.defaultCenter().addObserver(self, selector: "reloadWebView:", name: "DiaryChangeFont", object: nil) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) reloadWebView() } func reloadWebView() { var timeString = "\(numberToChinese(NSCalendar.currentCalendar().component(NSCalendarUnit.CalendarUnitYear, fromDate: diary.created_at)))年 \(numberToChineseWithUnit(NSCalendar.currentCalendar().component(NSCalendarUnit.CalendarUnitMonth, fromDate: diary.created_at)))月 \(numberToChineseWithUnit(NSCalendar.currentCalendar().component(NSCalendarUnit.CalendarUnitDay, fromDate: diary.created_at)))日" var newDiaryString = diary.content.stringByReplacingOccurrencesOfString("\n", withString: "<br>", options: NSStringCompareOptions.LiteralSearch, range: nil) var title = "" var contentWidthOffset = 140 var contentMargin:CGFloat = 10 if let titleStr = diary?.title { var parsedTime = "\(numberToChineseWithUnit(NSCalendar.currentCalendar().component(NSCalendarUnit.CalendarUnitDay, fromDate: diary.created_at))) 日" if titleStr != parsedTime { title = titleStr contentWidthOffset = 205 contentMargin = 10 title = "<div class='title'>\(title)</div>" } } var minWidth = self.view.frame.size.width - CGFloat(contentWidthOffset) var fontStr = defaultFont var bodyPadding = 0 var containerCSS = " padding:25px 10px 25px 25px; " var titleMarginRight:CGFloat = 15 let headertags = "<!DOCTYPE html><html><meta charset='utf-8'><head><title></title><style>" let bodyCSS = "body{padding:\(bodyPadding)px;} " let allCSS = "* {-webkit-text-size-adjust: 100%; margin:0; font-family: '\(fontStr)'; -webkit-writing-mode: vertical-rl; letter-spacing: 3px;}" let contentCSS = ".content { min-width: \(minWidth)px; margin-right: \(contentMargin)px;} .content p{ font-size: 12pt; line-height: 24pt;}" let titleCSS = ".title {font-size: 12pt; font-weight:bold; line-height: 24pt; margin-right: \(titleMarginRight)px; padding-left: 20px;} " let extraCSS = ".extra{ font-size:12pt; line-height: 24pt; margin-right:30px; }" let stampCSS = ".stamp {width:24px; height:auto; position:fixed; bottom:20px;}" let extraHTML = "<div class='extra'>于 \(diary.location!)<br>\(timeString) </div>" let contentHTML = "<div class='container'>\(title)<div class='content'><p>\(newDiaryString)</p></div>" webView.loadHTMLString("\(headertags)\(bodyCSS) \(allCSS) \(contentCSS) \(titleCSS) \(extraCSS) .container { \(containerCSS) } \(stampCSS) </style></head> <body> \(contentHTML) \(extraHTML)</body></html>", baseURL: nil) } func webViewDidFinishLoad(webView: UIWebView) { UIView.animateWithDuration(1.0, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { () -> Void in self.webView.alpha = 1.0 }, completion: nil) webView.scrollView.contentOffset = CGPointMake(webView.scrollView.contentSize.width - webView.frame.size.width, 0) } func hideDiary() { self.navigationController?.popViewControllerAnimated(true) } func showButtons() { } func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailByGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true } func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) { if scrollView.contentOffset.y < -80 { hideDiary() } } }
apache-2.0
35c45afd3d09f3a80784d93bcd846821
41.68
405
0.652484
4.643168
false
false
false
false