hexsha
stringlengths
40
40
size
int64
3
1.03M
content
stringlengths
3
1.03M
avg_line_length
float64
1.33
100
max_line_length
int64
2
1k
alphanum_fraction
float64
0.25
0.99
e62ed0324668f50c516d3568f45841f05d2ae0fe
916
// // bottleshootTests.swift // bottleshootTests // // Created by Fahreddin Gölcük on 29.06.2021. // import XCTest @testable import bottleshoot class bottleshootTests: XCTestCase { override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() throws { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() throws { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
26.941176
111
0.670306
61b241c178865be9a6a7b60e2ae6516d54cfd800
4,873
/**************************************************************************** * Copyright 2019-2020, Optimizely, Inc. and contributors * * * * 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 /// Implementation of OPTDataStore as a generic for per type storeage in a flat file. /// This class should be used as a singleton per storeName and type (T) public class DataStoreFile<T>: OPTDataStore where T: Codable { let dataStoreName: String let lock: DispatchQueue let async: Bool public let url: URL lazy var logger: OPTLogger? = OPTLoggerFactory.getLogger() init(storeName: String, async: Bool = true) { self.async = async dataStoreName = storeName lock = DispatchQueue(label: storeName) #if os(tvOS) || os(macOS) let directory = FileManager.SearchPathDirectory.cachesDirectory #else let directory = FileManager.SearchPathDirectory.documentDirectory #endif if let url = FileManager.default.urls(for: directory, in: .userDomainMask).first { self.url = url.appendingPathComponent(storeName, isDirectory: false) } else { self.url = URL(fileURLWithPath: storeName) } } func isArray() -> Bool { let t = "\(type(of: T.self))" return t.hasPrefix("Array") || t.hasPrefix("Swift.Array") || t.hasPrefix("__C.NSArray") || t.hasPrefix("NSArray") } public func getItem(forKey: String) -> Any? { var returnItem: T? lock.sync { do { if !FileManager.default.fileExists(atPath: self.url.path) { return } let contents = try Data(contentsOf: self.url) if type(of: T.self) == type(of: Data.self) { returnItem = contents as? T } else { if isArray() { let item = try JSONDecoder().decode(T.self, from: contents) returnItem = item } else { let item = try JSONDecoder().decode([T].self, from: contents) returnItem = item.first } } } catch let e as NSError { if e.code != 260 { self.logger?.e(e.localizedDescription) } } } return returnItem } func doCall(async: Bool, block:@escaping () -> Void) { if async { lock.async { block() } } else { lock.sync { block() } } } public func saveItem(forKey: String, value: Any) { doCall(async: self.async) { do { if let value = value as? T { var data: Data? // don't bother to convert... otherwise, do if let value = value as? Data { data = value } else if (value as? NSArray) != nil { data = try JSONEncoder().encode(value) } else { data = try JSONEncoder().encode([value]) } if let data = data { try data.write(to: self.url, options: .atomic) } } } catch let e { self.logger?.e(e.localizedDescription) } } } public func removeItem(forKey: String) { doCall(async: self.async) { do { try FileManager.default.removeItem(at: self.url) } catch let e { self.logger?.e(e.localizedDescription) } } } }
37.484615
121
0.452493
dee15cdec989de6f8cff09e28270423440c6ce42
4,113
// // AudioStream.swift // NuguCore // // Created by childc on 03/05/2019. // Copyright (c) 2019 SK Telecom Co., Ltd. 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 AVFoundation /** AudioStream made from RingBuffer. This stream can notify audio stream is needed or not using a delegator - seeAlso: AudioStreamDelegate */ public class AudioStream { private let buffer: AudioBuffer public weak var delegate: AudioStreamDelegate? { didSet { buffer.streamDelegate = delegate } } public init(capacity: Int) { buffer = AudioBuffer(capacity: capacity) } } extension AudioStream { public class AudioBuffer: SharedBuffer<AVAudioPCMBuffer> { public weak var streamDelegate: AudioStreamDelegate? private let delegateQueue = DispatchQueue(label: "com.sktelecom.romaine.audio_stream_delegate") private var refCnt = 0 { didSet { log.debug("audio reference count: \(oldValue) -> \(refCnt)") switch (oldValue, refCnt) { case (_, 0): self.streamDelegate?.audioStreamDidStop() case (0, 1): self.streamDelegate?.audioStreamWillStart() default: break } } } private func increaseRef() { delegateQueue.async { [weak self] in guard let self = self else { return } self.refCnt += 1 } } private func decreaseRef() { delegateQueue.async { [weak self] in guard let self = self else { return } self.refCnt -= 1 } } public override func makeBufferWriter() -> SharedBuffer<AVAudioPCMBuffer>.Writer { let writer = AudioBufferWriter(buffer: self) self.writer = writer return writer } public class AudioBufferWriter: SharedBuffer<AVAudioPCMBuffer>.Writer { /** Copy AVAudioBuffer and store it. So, we can have independent life cycle. */ public override func write(_ element: AVAudioPCMBuffer) throws { guard let newElement = element.copy() as? AVAudioPCMBuffer else { try super.write(element) return } try super.write(newElement) } } public override func makeBufferReader() -> SharedBuffer<AVAudioPCMBuffer>.Reader { return AudioBufferReader(buffer: self) } public class AudioBufferReader: SharedBuffer<AVAudioPCMBuffer>.Reader { private let audioBuffer: AudioBuffer init(buffer: AudioBuffer) { audioBuffer = buffer super.init(buffer: buffer) audioBuffer.increaseRef() } deinit { audioBuffer.decreaseRef() } } } } extension AudioStream: AudioStreamable { public func makeAudioStreamWriter() -> AudioStreamWritable { return buffer.makeBufferWriter() } public func makeAudioStreamReader() -> AudioStreamReadable { return buffer.makeBufferReader() } } extension SharedBuffer.Reader: AudioStreamReadable where Element == AVAudioPCMBuffer {} extension SharedBuffer.Writer: AudioStreamWritable where Element == AVAudioPCMBuffer {}
32.385827
103
0.592025
8a4acb8298cdfec275099554d923b19a8f4fc649
3,542
// // ViewController.swift // Toucher // // Created by Kamil Tustanowski on 08.03.2017. // Copyright © 2017 Kamil Tustanowski. All rights reserved. // import UIKit struct Sections { static let controls = 0 static let tableCells = 1 static let collectionCells = 2 } struct TableCells { static let plus = 0 static let minus = 1 } struct CollectionCells { static let plus = 0 static let minus = 1 } class TableViewController: UITableViewController { @IBOutlet weak var plusSegmented: UISegmentedControl! @IBOutlet weak var topPlusButton: UIBarButtonItem! @IBOutlet weak var topMinusButton: UIBarButtonItem! @IBOutlet weak var bottomPlusButton: UIButton! @IBOutlet weak var bottomMinusButton: UIButton! @IBOutlet weak var counterSwitch: UISwitch! @IBOutlet weak var counterStepper: UIStepper! @IBOutlet weak var counterSlider: UISlider! @IBOutlet weak var collectionView: UICollectionView! var count: Int? var counter: Int { get { return count ?? 0 } set { if counterSwitch.isOn { self.count = newValue title = "\(newValue)" } } } override func viewDidLoad() { super.viewDidLoad() counter = 0 } @IBAction func plusTapped() { counter += 1 } @IBAction func minusTapped() { counter -= 1 } @IBAction func plusSegmentedTapped(_ sender: UISegmentedControl) { let index = sender.selectedSegmentIndex counter += index + 1 } @IBAction func counterSwitchTapped(_ sender: UISwitch) { self.title = sender.isOn ? "\(counter)" : "🔒" } @IBAction func counterStepperTapped(_ sender: UIStepper) { let value = Int(sender.value) counter = value } @IBAction func counterSliderUsed(_ sender: UISlider) { let value = Int(sender.value) counter = value } } extension TableViewController { override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if indexPath.section == Sections.tableCells { if indexPath.row == TableCells.plus { counter += 1 } else { counter -= 1 } } } override func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) { if indexPath.section == Sections.tableCells { if indexPath.row == TableCells.plus { title = "+" } else { title = "-" } } } } extension TableViewController: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if indexPath.row == CollectionCells.plus { counter += 1 } else { counter -= 1 } } } extension TableViewController: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 2 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CVCell", for: indexPath) cell.backgroundColor = indexPath.row == 0 ? .green : .red return cell } }
25.854015
121
0.607002
bb6c6ad0f9238b7ac8acc4db131108f1d1281bbe
861
// // ZLEmotionsViewController.swift // FaceIt // // Created by yuzeux on 2018/2/1. // Copyright © 2018年 晶石. All rights reserved. // import UIKit class ZLEmotionsViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
23.916667
106
0.671312
fee05a9435187daab3d18eb58192afb6e4ec84a4
2,624
// // AnimationHelpers.swift // Created by Austin on 5/6/17. // import UIKit extension UIViewController { func setVisible(visible: Bool, animated: Bool, duration: TimeInterval = 0.25, visibleConstraint: NSLayoutConstraint?, hiddenConstraint: NSLayoutConstraint?, completion: (() -> Void)?) { if visible { hiddenConstraint?.isActive = false visibleConstraint?.isActive = true } else { visibleConstraint?.isActive = false hiddenConstraint?.isActive = true } guard animated else { view.layoutIfNeeded(); completion?() return } UIView.animate(withDuration: duration, animations: { self.view.layoutIfNeeded() }) { _ in completion?() } } } extension UIView { static func setViews(hidden: [UIView], visible: [UIView], animated: Bool = true, duration: TimeInterval = 0.1) { for view in visible { view.alpha = 0 view.isHidden = false } let animations = { for view in hidden { view.alpha = 0 } for view in visible { view.alpha = 1 } } let completion: (Bool) -> Void = { _ in for view in hidden { view.alpha = 1 view.isHidden = true } } if animated { UIView.animate(withDuration: duration, animations: animations, completion: completion) } else { animations() completion(true) } } func pop(scale: CGFloat = 1.25, duration: TimeInterval = 0.25, completion: ((Bool) -> Void)? = nil) { let originalTransform = transform let firstAnimation = { self.transform = originalTransform.scaledBy(x: scale, y: scale) } let secondAnimation = { self.transform = originalTransform } UIView.animate(withDuration: duration / 3, animations: firstAnimation) { _ in UIView.animate(withDuration: duration / 1.5, delay: 0, usingSpringWithDamping: 0.3, initialSpringVelocity: 1, options: [], animations: secondAnimation, completion: completion) } } }
26.77551
98
0.483232
0ec6d9b0d3d17e1de21c39de0d36e07a26378b2a
3,051
//****************************************************************************** // Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://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. // #if swift(>=5.3) && canImport(_Differentiation) import Numerics import _Differentiation @derivative(of:sum) @usableFromInline func _vjpSum<S, E>( _ x: Tensor<S, E>, axes: [Int]? = nil ) -> (value: Tensor<S, E>, pullback: (Tensor<S, E>) -> Tensor<S, E>) where E.Value: DifferentiableNumeric { let xshape = x.shape return ( sum(x, axes: axes), { Tensor<S, E>(repeating: $0, to: xshape) } ) } @derivative(of:mean) @usableFromInline func _vjpMean<S, E>( _ x: Tensor<S, E>, axes: [Int]? = nil ) -> (value: Tensor<S, E>, pullback: (Tensor<S, E>) -> Tensor<S, E>) where E.Value: DifferentiableNumeric & AlgebraicField { let count = E.Value(exactly: x.count)! return ( x.mean(axes: axes), { [xshape = x.shape] in Tensor<S, E>(repeating: $0, to: xshape) / count } ) } @derivative(of:prod) @usableFromInline func _vjpProd<S, E>( _ x: Tensor<S, E>, axes: [Int]? = nil ) -> (value: Tensor<S, E>, pullback: (Tensor<S, E>) -> Tensor<S, E>) where E.Value: DifferentiableNumeric { ( prod(x, axes: axes), { [xshape = x.shape] in Tensor<S, E>(repeating: $0, to: xshape) } ) } @derivative(of:prodNonZeros) @usableFromInline func _vjpProdNonZeros<S, E>( _ x: Tensor<S, E>, axes: [Int]? = nil ) -> (value: Tensor<S, E>, pullback: (Tensor<S, E>) -> Tensor<S, E>) where E.Value: DifferentiableNumeric { // REVIEW: this is probably wrong // Dan let value = prodNonZeros(x, axes: axes) return ( value, { [xshape = x.shape] in Tensor<S, E>(repeating: $0, to: xshape) } ) } @derivative(of:min) @usableFromInline func _vjpMin<S, E>( _ x: Tensor<S, E>, axes: [Int]? = nil ) -> (value: Tensor<S, E>, pullback: (Tensor<S, E>) -> Tensor<S, E>) where E.Value: DifferentiableNumeric & Comparable & ComparableLimits { // Dan fatalError() } @derivative(of:max) @usableFromInline func _vjpMax<S, E>( _ x: Tensor<S, E>, axes: [Int]? = nil ) -> (value: Tensor<S, E>, pullback: (Tensor<S, E>) -> Tensor<S, E>) where E.Value: DifferentiableNumeric & Comparable & ComparableLimits { // Dan fatalError() } @derivative(of:abssum) @usableFromInline func _vjpAbsSum<S, E>( _ x: Tensor<S, E>, axes: [Int]? = nil ) -> (value: Tensor<S, E>, pullback: (Tensor<S, E>) -> Tensor<S, E>) where E.Value: DifferentiableNumeric & SignedNumeric & Comparable { // Dan fatalError() } #endif
26.530435
80
0.62668
29774a6b0f9c71a4965fd4d0469bf3aced5ce090
1,789
// RUN: %target-swift-frontend -emit-sil -verify %s @_silgen_name("opaque") func opaque() -> Int func test_constantFoldAnd1() -> Int { while true && true { return 42 } // FIXME: this is a false positive. } // expected-error {{missing return in a function expected to return 'Int'}} func test_constantFoldAnd2() -> Int { while true && false { return 42 } } // expected-error {{missing return in a function expected to return 'Int'}} func test_constantFoldAnd3() -> Int { while false && true { return 42 } } // expected-error {{missing return in a function expected to return 'Int'}} func test_constantFoldAnd4() -> Int { while false && false { return 42 } } // expected-error {{missing return in a function expected to return 'Int'}} func test_constantFoldOr1() -> Int { while true || true { return 42 } // FIXME: this is a false positive. } // expected-error {{missing return in a function expected to return 'Int'}} func test_constantFoldOr2() -> Int { while true || false { return 42 } // FIXME: this is a false positive. } // expected-error {{missing return in a function expected to return 'Int'}} func test_constantFoldOr3() -> Int { while false || true { return 42 } // FIXME: this is a false positive. } // expected-error {{missing return in a function expected to return 'Int'}} func test_constantFoldOr4() -> Int { while false || false { return 42 } } // expected-error {{missing return in a function expected to return 'Int'}} // expected-warning@+1 {{'ExpressibleByStringInterpolation' is deprecated: it will be replaced or redesigned in Swift 4.0. Instead of conforming to 'ExpressibleByStringInterpolation', consider adding an 'init(_:String)'}} typealias X = ExpressibleByStringInterpolation
29.816667
222
0.687535
1a8e611b698c7c76527046c047b05a0ed4c436b5
8,335
// // InAppPurchaseManager.swift // MBLibrary // // Created by Marco Boschi on 05/08/16. // Copyright © 2016 Marco Boschi. All rights reserved. // import Foundation import StoreKit public struct TransactionStatus { /// The product identifier the transaction referes to. public let product: String /// The status of the transaction. public let status: MBPaymentTransactionState /// If the transaction has status `.failed` the error, `nil` otherwise. public let error: Error? } public struct RestorationStatus { /// Whether or not the restoration process was successful. public let success: Bool /// In case of success the number of restored transactions, `nil` otherwise. public let restored: Int? /// The error in case of failure, `nil` otherwise. public let error: Error? } public enum MBPaymentTransactionState { /// Tha transaction is completed as the payment has been finished. case purchased /// The transaction is completed as the purchase has been restored. case restored /// Tha transaction has somehow failed. case failed /// The transaction has been deferred waiting for approval by family manager, any modal view locking the app should be dismissed while waiting for `failed` or `completed` status. case deferred public func isSuccess() -> Bool { return self == .purchased || self == .restored } } public class InAppPurchaseManager: NSObject { public static let transactionNotification = NSNotification.Name("MBLibraryIAPManagerTransactionNotification") public static let restoreNotification = NSNotification.Name("MBLibraryIAPManagerRestoreNotification") public static let defaultsKeyPrefix = "iapStatus_" public fileprivate(set) var areProductsLoaded = false fileprivate let defaults: KeyValueStore fileprivate var productsStatus: [String: (purchased: Bool, product: SKProduct?)] fileprivate var productsRequest: SKProductsRequest? fileprivate var productsRequestHandler: ((_ success: Bool, _ products: [SKProduct]?) -> ())? fileprivate var restoredTransaction = 0 override private init() { fatalError("Use the public init method.") } convenience public init(productIds: Set<String>, inUserDefaults defaults: UserDefaults) { self.init(productIds: productIds, inUserDefaults: KeyValueStore(userDefaults: defaults)) } public init(productIds: Set<String>, inUserDefaults defaults: KeyValueStore) { self.defaults = defaults productsStatus = [:] super.init() SKPaymentQueue.default().add(self) for pId in productIds { productsStatus[pId] = (defaults.bool(forKey: InAppPurchaseManager.defaultsKeyPrefix + pId), nil) } } public func loadProducts(completion: ((_ success: Bool, _ products: [SKProduct]?) -> ())?) { productsRequest?.cancel() productsRequestHandler = completion productsRequest = SKProductsRequest(productIdentifiers: Set(productsStatus.keys)) productsRequest!.delegate = self productsRequest!.start() } /// Check if the specified product has been purchased. /// /// - parameter pId: The product identifier of the product to check. /// /// - returns: Whether or not the product has been purchased, at least once in case of consumable. public func isProductPurchased(pId: String) -> Bool { return productsStatus[pId]?.purchased ?? false } /// Check if the specified product has been purchased. /// /// - parameter product: The product to check. /// /// - returns: Whether or not the product has been purchased, at least once in case of consumable. public func isProductPurchased(product: SKProduct) -> Bool { return isProductPurchased(pId: product.productIdentifier) } public class var canMakePayments: Bool { return SKPaymentQueue.canMakePayments() } ///Initialize the transaction for buying the specified product. /// ///Listen to `InAppPurchaseManager.transactionNotification` notification to receive feedback on the transaction as `TransactionStatus` in the notification object. ///- returns: Whether or not the specified product identifier exist and the payment has been initialized. public func buyProduct(pId: String) -> Bool { guard let (_, tmp) = productsStatus[pId], let p = tmp else { return false } buyProduct(product: p) return true } ///Initialize the transaction for buying the specified product. /// ///Listen to `InAppPurchaseManager.transactionNotification` notification to receive feedback on the transaction as `TransactionStatus` in the notification object. public func buyProduct(product: SKProduct) { let payment = SKPayment(product: product) SKPaymentQueue.default().add(payment) } ///Initialize restore process for previous purchases. /// ///Listen to `InAppPurchaseManager.restoreNotification` notification to receive the result of the process stored as `RestorationStatus` in the notification object. public func restorePurchases() { restoredTransaction = 0 SKPaymentQueue.default().restoreCompletedTransactions() } class func shouldDisplayError(for e: Error) -> Bool { let err = e as NSError // No need to display any error if the payment was cancelled. return err.code != SKError.Code.paymentCancelled.rawValue } } // MARK: - Product request delegate methods extension InAppPurchaseManager: SKProductsRequestDelegate { public func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) { let products = response.products for p in products { productsStatus[p.productIdentifier]?.product = p } areProductsLoaded = true productsRequestHandler?(true, products) clearRequestAndHandler() } public func request(_ request: SKRequest, didFailWithError error: Error) { productsRequestHandler?(false, nil) clearRequestAndHandler() } private func clearRequestAndHandler() { productsRequest = nil productsRequestHandler = nil } } // MARK: - Transaction observer methods extension InAppPurchaseManager: SKPaymentTransactionObserver { public func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) { for transaction in transactions { switch (transaction.transactionState) { case .purchased: complete(transaction) case .failed: failed(transaction) case .restored: restore(transaction) case .deferred: updateTransaction(for: transaction.payment.productIdentifier, withStatus: .deferred) case .purchasing: fallthrough default: break } } } public func paymentQueueRestoreCompletedTransactionsFinished(_ queue: SKPaymentQueue) { NotificationCenter.default.post(name: InAppPurchaseManager.restoreNotification, object: RestorationStatus(success: true, restored: restoredTransaction, error: nil)) } public func paymentQueue(_ queue: SKPaymentQueue, restoreCompletedTransactionsFailedWithError error: Error) { NotificationCenter.default.post(name: InAppPurchaseManager.restoreNotification, object: RestorationStatus(success: false, restored: nil, error: error)) } private func complete(_ transaction: SKPaymentTransaction) { updateTransaction(for: transaction.payment.productIdentifier, withStatus: .purchased) SKPaymentQueue.default().finishTransaction(transaction) } private func restore(_ transaction: SKPaymentTransaction) { guard let productIdentifier = transaction.original?.payment.productIdentifier else { return } restoredTransaction += 1 updateTransaction(for: productIdentifier, withStatus: .restored) SKPaymentQueue.default().finishTransaction(transaction) } private func failed(_ transaction: SKPaymentTransaction) { updateTransaction(for: transaction.payment.productIdentifier, withStatus: .failed, andError: transaction.error) SKPaymentQueue.default().finishTransaction(transaction) } private func updateTransaction(for product: String, withStatus status: MBPaymentTransactionState, andError error: Error? = nil) { precondition(error != nil || status != .failed, "Missing error") if status.isSuccess() { productsStatus[product]?.purchased = true defaults.set(true, forKey: InAppPurchaseManager.defaultsKeyPrefix + product) defaults.synchronize() } NotificationCenter.default.post(name: InAppPurchaseManager.transactionNotification, object: TransactionStatus(product: product, status: status, error: status == .failed ? error : nil)) } }
33.744939
186
0.762448
dd48a5e72672905d190bc859867172110ad5360d
349
// RUN: not --crash %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing var b{ let a{ struct d<T where H:A {struct c<I{ var _=B struct B struct B } }}enum a{ struct Q{enum A{ struct S:BooleanType d
19.388889
87
0.724928
6a29d5be427a30f200dfe00e8e055dfb022f54f5
2,038
// // LoginViewController.swift // Instagrem // // Created by Oscar G.M on 3/1/16. // Copyright © 2016 GMStudios. All rights reserved. // import UIKit import Parse class LoginViewController: UIViewController { @IBOutlet weak var usernameField: UITextField! @IBOutlet weak var passwordField: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func onSignIn(sender: AnyObject) { PFUser.logInWithUsernameInBackground(usernameField.text!, password: passwordField.text!) { (user: PFUser?, error: NSError?) -> Void in if(user != nil){ print("you're logged in") self.performSegueWithIdentifier("loginSegue", sender: nil) } } } @IBAction func onSignUp(sender: AnyObject) { let newUser = PFUser() newUser.username = usernameField.text newUser.password = passwordField.text newUser.signUpInBackgroundWithBlock { (success:Bool,error: NSError?) -> Void in if(success){ print("user successfully created") self.performSegueWithIdentifier("loginSegue", sender: nil) } else{ print(error?.localizedDescription) if(error?.code == 202){ print("Username already taken") } } } } /* // 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. } */ }
29.114286
142
0.603042
edefa3ad0aa725ab7a3e82fa5645112047eee0f2
2,468
// // Operator.swift // WebimClientLibrary // // Created by Nikita Lazarev-Zubov on 09.08.17. // Copyright © 2017 Webim. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation /** Abstracts a chat operator. - seealso: `MessageStream.getCurrentOperator()` - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ public protocol Operator { /** - returns: Unique ID of the operator. - seealso: `MessageStream.rateOperatorWith(id:byRate:completionHandler:)` `MessageStream.getLastRatingOfOperatorWith(id:)` - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ func getID() -> String /** - returns: Display name of the operator. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ func getName() -> String /** - returns: URL of the operator’s avatar or `nil` if does not exist. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ func getAvatarURL() -> URL? /** - returns: Display operator title. - author: Anna Frolova - copyright: 2021 Webim */ func getTitle() -> String? /** - returns: Display operator additional Information. - author: Anna Frolova - copyright: 2021 Webim */ func getInfo() -> String? }
26.537634
82
0.660454
50c7d866033dfa34798c55d8cc0a10b90b92c942
811
// // AppDelegate.swift // MVC-Code // // Created by giftbot on 2017. 9. 27.. // Copyright © 2017년 giftbot. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { setupKeyWindow() return true } private func setupKeyWindow() { window = UIWindow(frame: UIScreen.main.bounds) let serviceSetting = ServiceSetting.decode() let repositoriesViewController = RepositoriesViewController(serviceSetting: serviceSetting) window?.rootViewController = UINavigationController(rootViewController: repositoriesViewController) window?.makeKeyAndVisible() } }
27.965517
142
0.759556
2f9effbb74e1592d85317b748fa132542288c575
1,490
// // TrailerViewController.swift // Flix // // Created by Alberto on 2/12/18. // Copyright © 2018 Alberto Nencioni. All rights reserved. // import UIKit import WebKit class TrailerViewController: UIViewController, WKUIDelegate { @IBOutlet weak var webView: WKWebView! var movie: Movie! override func viewDidLoad() { super.viewDidLoad() self.fetchTrailer() } func fetchTrailer() { let request = URLRequest(url: (movie?.trailerURL)!, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 10) let session = URLSession(configuration: .default, delegate: nil, delegateQueue: OperationQueue.main) let task = session.dataTask(with: request) { (data, response, error) in // This will run when the network request returns if let error = error { print(error.localizedDescription) } else if let data = data { let dataDictionary = try! JSONSerialization.jsonObject(with: data, options: []) as! [String: Any] let videos = dataDictionary["results"] as! [[String: Any]] let video = videos[0] let key = video["key"] as! String if let myURL = URL(string: "https://www.youtube.com/watch?v=" + key) { let myRequest = URLRequest(url: myURL) self.webView.load(myRequest) } } } task.resume() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
29.215686
120
0.65906
3a23c21b589a090c2393bda716274f1b8b2ccf53
2,844
// // ViewModel.swift // PracticeCombine // // Created by nyon on 2022/03/30. // import Foundation import Combine protocol ViewModelable: AnyObject { var service: Serviceable { get } var presenter: Presentable? { get set } func requestAction(with inputAction: InputAction) } enum Output { case list([String]) case indicator(Bool) case error(String) } protocol Presentable: AnyObject { func updateState(with output: Output) } final class ViewModel: ViewModelable { let service: Serviceable weak var presenter: Presentable? private var cancelBags = [AnyCancellable]() private var list: [String] = [] private var users: [User] = [] init(service: Serviceable) { self.service = service } } extension ViewModel { func requestAction(with inputAction: InputAction) { print(">>> requestAction \(inputAction)") switch inputAction { case .viewDidLoad: fetchCompanyList() case let .touchedInfoButton(index): let name = list[index] requestUser(name: name) .receive(on: DispatchQueue.main) .sink { [weak self] users in print(">>> users \(users)") self?.users = users } .store(in: &cancelBags) } } } private extension ViewModel { private func fetchCompanyList() { presenter?.updateState(with: .indicator(true)) service.fetchCompanies() .receive(on: DispatchQueue.main) .sink { [weak presenter] completion in presenter?.updateState(with: .indicator(false)) switch completion { case let .failure(error): print(">>> error \(error)") presenter?.updateState(with: .error(error.localizedDescription)) case .finished: print(">>> finished") } } receiveValue: { [weak self, weak presenter] values in self?.list = values presenter?.updateState(with: .list(values)) } .store(in: &cancelBags) } private func requestUser(name: String) -> AnyPublisher<[User], Never> { let path = "https://jsonplaceholder.typicode.com/users" guard let url = URL(string: path) else { // eraseToAnyPublisher AnyPublisher를 따르도록 타입을 지운다.. return Just([]).eraseToAnyPublisher() } return URLSession.shared .dataTaskPublisher(for: url) .subscribe(on: DispatchQueue.global()) .map { $0.data } .decode(type: [User].self, decoder: JSONDecoder()) .catch { _ in Just([]) } .eraseToAnyPublisher() } }
29.020408
84
0.559423
7a9944b75d906810484b442d43ce430054cbb2b0
258
// // AskedToLeaveSwitchDelegate.swift // FieldTheBern // // Created by Josh Smith on 10/28/15. // Copyright © 2015 Josh Smith. All rights reserved. // import Foundation protocol AskedToLeaveSwitchDelegate { func askedToLeaveSwitched(state: Bool) }
19.846154
53
0.74031
f41092c00af93644165352357b4cfb5ceab3a636
1,114
// // RxTableViewSectionedAnimatedDataSource.swift // RxExample // // Created by Krunoslav Zaher on 6/27/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation import UIKit #if !RX_NO_MODULE import RxSwift import RxCocoa #endif public class RxTableViewSectionedAnimatedDataSource<S: SectionModelType> : RxTableViewSectionedDataSource<S> , RxTableViewDataSourceType { public typealias Element = [Changeset<S>] public var animationConfiguration: AnimationConfiguration? = nil public override init() { super.init() } public func tableView(tableView: UITableView, observedEvent: Event<Element>) { UIBindingObserver(UIElement: self) { dataSource, element in for c in element { dataSource.setSections(c.finalSections) if c.reloadData { tableView.reloadData() } else { tableView.performBatchUpdates(c, animationConfiguration: self.animationConfiguration) } } }.on(observedEvent) } }
27.85
103
0.64991
9cf4e59becf62ac68e567e367914b8787cbfbadc
11,236
/** * https://github.com/tadija/AEXML * Copyright (c) Marko Tadić 2014-2018 * Licensed under the MIT license. See LICENSE file. */ import Foundation /** This is base class for holding XML structure. You can access its structure by using subscript like this: `element["foo"]["bar"]` which would return `<bar></bar>` element from `<element><foo><bar></bar></foo></element>` XML as an `AEXMLElement` object. */ open class AEXMLElement { // MARK: - Properties /// Every `AEXMLElement` should have its parent element instead of `AEXMLDocument` which parent is `nil`. open internal(set) weak var parent: AEXMLElement? /// Child XML elements. open internal(set) var children = [AEXMLElement]() /// XML Element name. open var name: String /// XML Element value. open var value: String? /// XML Element attributes. open var attributes: [String : String] /// Error value (`nil` if there is no error). open var error: AEXMLError? /// String representation of `value` property (if `value` is `nil` this is empty String). open var string: String { return value ?? String() } /// Boolean representation of `value` property (`nil` if `value` can't be represented as Bool). open var bool: Bool? { return Bool(string) } /// Integer representation of `value` property (`nil` if `value` can't be represented as Integer). open var int: Int? { return Int(string) } /// Double representation of `value` property (`nil` if `value` can't be represented as Double). open var double: Double? { return Double(string) } // MARK: - Lifecycle /** Designated initializer - all parameters are optional. - parameter name: XML element name. - parameter value: XML element value (defaults to `nil`). - parameter attributes: XML element attributes (defaults to empty dictionary). - returns: An initialized `AEXMLElement` object. */ public init(name: String, value: String? = nil, attributes: [String : String] = [String : String]()) { self.name = name self.value = value self.attributes = attributes } // MARK: - XML Read /// The first element with given name **(Empty element with error if not exists)**. open subscript(key: String) -> AEXMLElement { guard let first = children.first(where: { $0.name == key }) else { let errorElement = AEXMLElement(name: key) errorElement.error = AEXMLError.elementNotFound return errorElement } return first } /// Returns all of the elements with equal name as `self` **(nil if not exists)**. open var all: [AEXMLElement]? { return parent?.children.filter { $0.name == self.name } } /// Returns the first element with equal name as `self` **(nil if not exists)**. open var first: AEXMLElement? { return all?.first } /// Returns the last element with equal name as `self` **(nil if not exists)**. open var last: AEXMLElement? { return all?.last } /// Returns number of all elements with equal name as `self`. open var count: Int { return all?.count ?? 0 } /** Returns all elements with given value. - parameter value: XML element value. - returns: Optional Array of found XML elements. */ open func all(withValue value: String) -> [AEXMLElement]? { let found = all?.compactMap { $0.value == value ? $0 : nil } return found } /** Returns all elements containing given attributes. - parameter attributes: Array of attribute names. - returns: Optional Array of found XML elements. */ open func all(containingAttributeKeys keys: [String]) -> [AEXMLElement]? { let found = all?.compactMap { element in keys.reduce(true) { (result, key) in result && Array(element.attributes.keys).contains(key) } ? element : nil } return found } /** Returns all elements with given attributes. - parameter attributes: Dictionary of Keys and Values of attributes. - returns: Optional Array of found XML elements. */ open func all(withAttributes attributes: [String : String]) -> [AEXMLElement]? { let keys = Array(attributes.keys) let found = all(containingAttributeKeys: keys)?.compactMap { element in attributes.reduce(true) { (result, attribute) in result && element.attributes[attribute.key] == attribute.value } ? element : nil } return found } /** Returns all descendant elements which satisfy the given predicate. Searching is done vertically; children are tested before siblings. Elements appear in the list in the order in which they are found. - parameter predicate: Function which returns `true` for a desired element and `false` otherwise. - returns: Array of found XML elements. */ open func allDescendants(where predicate: (AEXMLElement) -> Bool) -> [AEXMLElement] { var result: [AEXMLElement] = [] for child in children { if predicate(child) { result.append(child) } result.append(contentsOf: child.allDescendants(where: predicate)) } return result } /** Returns the first descendant element which satisfies the given predicate, or nil if no such element is found. Searching is done vertically; children are tested before siblings. - parameter predicate: Function which returns `true` for the desired element and `false` otherwise. - returns: Optional AEXMLElement. */ open func firstDescendant(where predicate: (AEXMLElement) -> Bool) -> AEXMLElement? { for child in children { if predicate(child) { return child } else if let descendant = child.firstDescendant(where: predicate) { return descendant } } return nil } /** Indicates whether the element has a descendant satisfying the given predicate. - parameter predicate: Function which returns `true` for the desired element and `false` otherwise. - returns: Bool. */ open func hasDescendant(where predicate: (AEXMLElement) -> Bool) -> Bool { return firstDescendant(where: predicate) != nil } // MARK: - XML Write /** Adds child XML element to `self`. - parameter child: Child XML element to add. - returns: Child XML element with `self` as `parent`. */ @discardableResult open func addChild(_ child: AEXMLElement) -> AEXMLElement { child.parent = self children.append(child) return child } /** Adds child XML element to `self`. - parameter name: Child XML element name. - parameter value: Child XML element value (defaults to `nil`). - parameter attributes: Child XML element attributes (defaults to empty dictionary). - returns: Child XML element with `self` as `parent`. */ @discardableResult open func addChild(name: String, value: String? = nil, attributes: [String : String] = [String : String]()) -> AEXMLElement { let child = AEXMLElement(name: name, value: value, attributes: attributes) return addChild(child) } /** Adds an array of XML elements to `self`. - parameter children: Child XML element array to add. - returns: Child XML elements with `self` as `parent`. */ @discardableResult open func addChildren(_ children: [AEXMLElement]) -> [AEXMLElement] { children.forEach{ addChild($0) } return children } /// Removes `self` from `parent` XML element. open func removeFromParent() { parent?.removeChild(self) } fileprivate func removeChild(_ child: AEXMLElement) { if let childIndex = children.firstIndex(where: { $0 === child }) { children.remove(at: childIndex) } } fileprivate var parentsCount: Int { var count = 0 var element = self while let parent = element.parent { count += 1 element = parent } return count } fileprivate func indent(withDepth depth: Int) -> String { var count = depth var indent = String() while count > 0 { indent += "\t" count -= 1 } return indent } /// Complete hierarchy of `self` and `children` in **XML** escaped and formatted String open var xml: String { var xml = String() // open element xml += indent(withDepth: parentsCount - 1) xml += "<\(name)" if attributes.count > 0 { // insert attributes for (key, value) in attributes { xml += " \(key)=\"\(value.xmlEscaped)\"" } } if value == nil && children.count == 0 { // close element xml += " />" } else { if children.count > 0 { // add children xml += ">\n" for child in children { xml += "\(child.xml)\n" } // add indentation xml += indent(withDepth: parentsCount - 1) xml += "</\(name)>" } else { // insert string value and close element xml += ">\(string.xmlEscaped)</\(name)>" } } return xml } /// Same as `xmlString` but without `\n` and `\t` characters open var xmlCompact: String { let chars = CharacterSet(charactersIn: "\n\t") return xml.components(separatedBy: chars).joined(separator: "") } /// Same as `xmlString` but with 4 spaces instead '\t' characters open var xmlSpaces: String { let chars = CharacterSet(charactersIn: "\t") return xml.components(separatedBy: chars).joined(separator: " ") } } public extension String { /// String representation of self with XML special characters escaped. public var xmlEscaped: String { // we need to make sure "&" is escaped first. Not doing this may break escaping the other characters var escaped = replacingOccurrences(of: "&", with: "&amp;", options: .literal) // replace the other four special characters let escapeChars = ["<" : "&lt;", ">" : "&gt;", "'" : "&apos;", "\"" : "&quot;"] for (char, echar) in escapeChars { escaped = escaped.replacingOccurrences(of: char, with: echar, options: .literal) } return escaped } }
33.242604
117
0.573781
cca46c4f781f789bbcc12f5d0d3e06709695d872
2,139
/// These materials have been reviewed and are updated as of September, 2020 /// /// Copyright (c) 2020 Razeware LLC /// /// Permission is hereby granted, free of charge, to any person obtaining a copy /// of this software and associated documentation files (the "Software"), to deal /// in the Software without restriction, including without limitation the rights /// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell /// copies of the Software, and to permit persons to whom the Software is /// furnished to do so, subject to the following conditions: /// /// The above copyright notice and this permission notice shall be included in /// all copies or substantial portions of the Software. /// /// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish, /// distribute, sublicense, create a derivative work, and/or sell copies of the /// Software in any work that is designed, intended, or marketed for pedagogical or /// instructional purposes related to programming, coding, application development, /// or information technology. Permission for such use, copying, modification, /// merger, publication, distribution, sublicensing, creation of derivative works, /// or sale is expressly withheld. /// /// This project and source code may use libraries or frameworks that are /// released under various Open-Source licenses. Use of those libraries and /// frameworks are governed by their own individual licenses. /// /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR /// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, /// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE /// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER /// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, /// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN /// THE SOFTWARE. /// import UIKit class ViewController: UIViewController { @IBOutlet weak var collectionView: UICollectionView! override func viewDidLoad() { super.viewDidLoad() } }
46.5
83
0.755961
db0840114576b3e7e7791f20d09969b69d8edc7e
862
// // AppRouter.swift // mvvm-base // // Created by nb-058-41b on 6/15/20. // Copyright © 2020 Alexander Tereshkov. All rights reserved. // import UIKit final class AppRouter: AppRouterProtocol { private(set) var window: UIWindow private var session: SessionType init(window: UIWindow, session: SessionType) { self.window = window self.session = session } var rootViewController: UIViewController? { return window.rootViewController } } // MARK: - Public API extension AppRouter { func start(with session: SessionType) { let rootRouter = RootRouter(session: session) guard let vc = rootRouter.initializeRootView() else { return } window.rootViewController = UINavigationController(rootViewController: vc) window.makeKeyAndVisible() } }
22.102564
82
0.660093
69190f3d92cae89550bb8eef46500104e59777e0
4,293
// // Copyright (C) 2018 Google, Inc. // // CustomControlsView.h // APIDemo // // 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 GoogleMobileAds import UIKit /// A custom view which encapsulates the display of video controller related information and also /// custom video controls. Set the video options when requesting an ad, then set the video /// controller when the ad is received. class CustomControlsView: UIView { /// Resets the controls status, and lets the controls view know the initial mute state. /// The controller for the ad currently being displayed. Setting this sets up the view according to /// the video controller state. weak var controller: GADVideoController? { didSet { if let controller = controller { controlsView.isHidden = !controller.customControlsEnabled() controller.delegate = self videoStatusLabel.text = controller.hasVideoContent() ? "Ad contains video content." : "Ad does not contain video content." } else { controlsView.isHidden = true videoStatusLabel.text = "" } } } /// The container view for the actual video controls @IBOutlet weak var controlsView: UIView! /// The play button. @IBOutlet weak var playButton: UIButton! /// The mute button. @IBOutlet weak var muteButton: UIButton! /// The label showing the video status for the current video controller. @IBOutlet weak var videoStatusLabel: UILabel! /// Boolean reflecting current playback state for UI. private var _isPlaying = false var isPlaying: Bool { get { return _isPlaying } set(playing) { _isPlaying = playing let title: String = _isPlaying ? "Pause" : "Play" playButton.setTitle(title, for: .normal) } } /// Boolean reflecting current mute state for UI. private var _isMuted = false var isMuted: Bool { get { return _isMuted } set(muted) { if muted != isMuted { let title: String = muted ? "Unmute" : "Mute" muteButton.setTitle(title, for: .normal) } _isMuted = muted } } func reset(withStartMuted startMuted: Bool) { isMuted = startMuted isPlaying = false controlsView.isHidden = true videoStatusLabel.text = "" } @IBAction func playPause(_ sender: Any) { if isPlaying { controller?.pause() } else { controller?.play() } } @IBAction func muteUnmute(_ sender: Any) { isMuted = !isMuted controller?.setMute(isMuted) } } extension CustomControlsView : GADVideoControllerDelegate { func videoControllerDidPlayVideo(_ videoController: GADVideoController) { videoStatusLabel.text = "Video did play." print("\(#function)") isPlaying = true } func videoControllerDidPauseVideo(_ videoController: GADVideoController) { videoStatusLabel.text = "Video did pause." print("\(#function)") isPlaying = false } func videoControllerDidMuteVideo(_ videoController: GADVideoController) { videoStatusLabel.text = "Video has muted." print("\(#function)") isMuted = true } func videoControllerDidUnmuteVideo(_ videoController: GADVideoController) { videoStatusLabel.text = "Video has unmuted." print("\(#function)") isMuted = false } func videoControllerDidEndVideoPlayback(_ videoController: GADVideoController) { videoStatusLabel.text = "Video playback has ended." print("\(#function)") isPlaying = false } }
34.071429
132
0.643839
5df6809fd2f3ff8aa8b8b2ce0e4dbd4c0cb43907
707
// // BeamSafariViewController.swift // beam // // Created by Robin Speijer on 16-12-15. // Copyright © 2015 Awkward. All rights reserved. // import UIKit import SafariServices final class BeamSafariViewController: SFSafariViewController { init(url: URL) { let configuration = SFSafariViewController.Configuration() configuration.entersReaderIfAvailable = UserSettings[.prefersSafariViewControllerReaderMode] super.init(url: url, configuration: configuration) if AppDelegate.shared.displayModeController.currentMode == .dark { self.preferredBarTintColor = UIColor.black self.preferredControlTintColor = UIColor.white } } }
28.28
100
0.7157
03774de03b3388a458a8f578b631551cc6af3d60
205
// // EventsFile.swift // Split // // Created by Javier L. Avrudsky on 6/19/18. // import Foundation class EventsFile: Codable { var oldHits: [String: EventsHit]? var currentHit: EventsHit? }
14.642857
45
0.663415
5092431e4d4f4862bcac3395270b41e27f7596b0
3,269
// // CouchbaseLiteFeedStore.swift // FeedStoreChallenge // // Created by Fabio Mignogna on 04/03/2021. // Copyright © 2021 Essential Developer. All rights reserved. // import CouchbaseLiteSwift import Foundation public final class CouchbaseLiteFeedStore: FeedStore { private static let documentID = "cache-document" private struct Cache { let feed: [LocalFeedImage] let timestamp: Date var toDocument: MutableDocument { MutableDocument(id: CouchbaseLiteFeedStore.documentID) .setArray(MutableArrayObject(data: feed.map { $0.toDictionaryObject }), forKey: "feed") .setDouble(timestamp.timeIntervalSinceReferenceDate, forKey: "timestamp") } init(feed: [LocalFeedImage], timestamp: Date) { self.feed = feed self.timestamp = timestamp } init?(document: Document) { guard let feedJSON = document.array(forKey: "feed") else { return nil } self.feed = feedJSON.reduce(into: [DictionaryObject]()) { output, element in if let dicationary = element as? DictionaryObject { output.append(dicationary) } }.compactMap(LocalFeedImage.init) self.timestamp = Date(timeIntervalSinceReferenceDate: document.double(forKey: "timestamp")) } } private let database: Database private let queue = DispatchQueue( label: "\(CouchbaseLiteFeedStore.self).queue", qos: .userInitiated, attributes: .concurrent ) public init(storeURL: URL) throws { let dbConfig = DatabaseConfiguration() dbConfig.directory = storeURL.path self.database = try Database(name: "feed-store", config: dbConfig) } public func deleteCachedFeed(completion: @escaping DeletionCompletion) { let database = self.database queue.async(flags: .barrier) { guard let cache = database.document(withID: Self.documentID) else { return completion(nil) } do { try database.deleteDocument(cache) completion(nil) } catch { completion(error) } } } public func insert(_ feed: [LocalFeedImage], timestamp: Date, completion: @escaping InsertionCompletion) { let database = self.database queue.async(flags: .barrier) { do { try database.saveDocument(Cache(feed: feed, timestamp: timestamp).toDocument) completion(nil) } catch { completion(error) } } } public func retrieve(completion: @escaping RetrievalCompletion) { let database = self.database queue.async { guard let cacheDocument = database.document(withID: Self.documentID), let cache = Cache(document: cacheDocument) else { return completion(.empty) } completion( .found( feed: cache.feed, timestamp: cache.timestamp ) ) } } } private extension LocalFeedImage { var toDictionaryObject: DictionaryObject { MutableDictionaryObject( data: [ "id": id.uuidString, "description": description, "location": location, "url": url.absoluteString ].compactMapValues { $0 } ) } init?(json: DictionaryObject) { guard let idString = json.string(forKey: "id"), let id = UUID(uuidString: idString), let urlString = json.string(forKey: "url"), let url = URL(string: urlString) else { return nil } self.id = id self.description = json.string(forKey: "description") self.location = json.string(forKey: "location") self.url = url } }
25.539063
107
0.704191
f72ff3a95e4f6093322756d418a6bd44e3f503b7
2,120
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend-emit-module -emit-module-path %t/FakeDistributedActorSystems.swiftmodule -module-name FakeDistributedActorSystems -disable-availability-checking %S/../Inputs/FakeDistributedActorSystems.swift // RUN: %target-build-swift -module-name main -Xfrontend -enable-experimental-distributed -Xfrontend -disable-availability-checking -j2 -parse-as-library -I %t %s %S/../Inputs/FakeDistributedActorSystems.swift -o %t/a.out // RUN: %target-run %t/a.out | %FileCheck %s --color --dump-input=always // REQUIRES: executable_test // REQUIRES: concurrency // REQUIRES: distributed // rdar://76038845 // UNSUPPORTED: use_os_stdlib // UNSUPPORTED: back_deployment_runtime // FIXME(distributed): Distributed actors currently have some issues on windows, isRemote always returns false. rdar://82593574 // UNSUPPORTED: windows // FIXME(distributed): remote calls seem to hang on linux - rdar://87240034 // UNSUPPORTED: linux // rdar://87568630 - segmentation fault on 32-bit WatchOS simulator // UNSUPPORTED: OS=watchos && CPU=i386 // rdar://88228867 - remoteCall_* tests have been disabled due to random failures // OK: rdar88228867 import _Distributed import FakeDistributedActorSystems typealias DefaultDistributedActorSystem = FakeRoundtripActorSystem distributed actor Greeter { distributed func echo(name: String) -> String { return "Echo: \(name)" } } func test() async throws { let system = DefaultDistributedActorSystem() let local = Greeter(system: system) let ref = try Greeter.resolve(id: local.id, using: system) let reply = try await ref.echo(name: "Caplin") // CHECK: >> remoteCall: on:main.Greeter, target:RemoteCallTarget(_mangledName: "$s4main7GreeterC4echo4nameS2S_tFTE"), invocation:FakeInvocationEncoder(genericSubs: [], arguments: ["Caplin"], returnType: Optional(Swift.String), errorType: nil), throwing:Swift.Never, returning:Swift.String // CHECK: << remoteCall return: Echo: Caplin print("reply: \(reply)") // CHECK: reply: Echo: Caplin } @main struct Main { static func main() async { try! await test() } }
37.857143
291
0.750472
113ca3c45aa2615f8baab8bc56dbb517495f6b8a
3,045
// // SearchedMessageCell.swift // Yep // // Created by NIX on 16/4/5. // Copyright © 2016年 Catch Inc. All rights reserved. // import UIKit import YepKit final class SearchedMessageCell: UITableViewCell { @IBOutlet weak var avatarImageView: UIImageView! @IBOutlet weak var nicknameLabel: UILabel! @IBOutlet weak var timeLabel: UILabel! @IBOutlet weak var messageLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() separatorInset = YepConfig.SearchedItemCell.separatorInset } override func prepareForReuse() { super.prepareForReuse() avatarImageView.image = nil nicknameLabel.text = nil timeLabel.text = nil messageLabel.text = nil } func configureWithMessage(_ message: Message, keyword: String?) { guard let user = message.fromFriend else { return } let userAvatar = UserAvatar(userID: user.userID, avatarURLString: user.avatarURLString, avatarStyle: miniAvatarStyle) avatarImageView.navi_setAvatar(userAvatar, withFadeTransitionDuration: avatarFadeTransitionDuration) nicknameLabel.text = user.nickname if let keyword = keyword { messageLabel.attributedText = message.textContent.yep_hightlightSearchKeyword(keyword, baseFont: YepConfig.SearchedItemCell.messageFont, baseColor: YepConfig.SearchedItemCell.messageColor) } else { messageLabel.text = message.textContent } timeLabel.text = Date(timeIntervalSince1970: message.createdUnixTime).timeAgo.lowercased() } func configureWithUserMessages(_ userMessages: SearchConversationsViewController.UserMessages, keyword: String?) { let user = userMessages.user let userAvatar = UserAvatar(userID: user.userID, avatarURLString: user.avatarURLString, avatarStyle: nanoAvatarStyle) avatarImageView.navi_setAvatar(userAvatar, withFadeTransitionDuration: avatarFadeTransitionDuration) nicknameLabel.text = user.nickname let count = userMessages.messages.count if let message = userMessages.messages.first { if count > 1 { messageLabel.textColor = UIColor.yepTintColor() messageLabel.text = String(format: NSLocalizedString("countMessages%d", comment: ""), count) timeLabel.isHidden = true timeLabel.text = nil } else { messageLabel.textColor = UIColor.black if let keyword = keyword { messageLabel.attributedText = message.textContent.yep_hightlightSearchKeyword(keyword, baseFont: YepConfig.SearchedItemCell.messageFont, baseColor: YepConfig.SearchedItemCell.messageColor) } else { messageLabel.text = message.textContent } timeLabel.isHidden = false timeLabel.text = Date(timeIntervalSince1970: message.createdUnixTime).timeAgo.lowercased() } } } }
33.097826
208
0.675205
56fa4347280b96a8a6a3dea471e2cbedcb305e84
418
// // ViewPortsConstructor.swift // BackstopJS SC // // Created by Enzo Sterro on 17.05.2017. // Copyright © 2017 Enzo Sterro. All rights reserved. // import Foundation struct ViewPortsConstructor { static func construct(_ vpName: String, vpWidth: Int, vpPortHeight: Int) -> [String: AnyObject] { return ["name": vpName as AnyObject, "width": vpWidth as AnyObject, "height": vpPortHeight as AnyObject] } }
23.222222
106
0.715311
161bb63e6141f3f5b68a0ca6f4fd28a8b0ed8585
3,234
// // CxCViewController.swift // MP-Yoogooo // // Created by Sleyter Angulo on 11/24/16. // Copyright © 2016 Sleyter Angulo. All rights reserved. // import UIKit import Foundation class CxCViewController: UIViewController { @IBOutlet weak var txtBusqueda: UISearchBar! @IBOutlet weak var menuButton: UIBarButtonItem! let dato = UserDefaults() override func viewDidLoad() { super.viewDidLoad() if self.revealViewController() != nil { menuButton.target = self.revealViewController() menuButton.action = #selector(SWRevealViewController.revealToggle(_:)) self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer()) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func searchBarSearchButtonClicked( _ searchBar: UISearchBar!) { let search: String = txtBusqueda.text! self.closeTaskService(search, completionHandler: { (response) -> () in print(response) }) } func closeTaskService(_ valor: String, completionHandler: (_ response:NSString) -> ()) { var i = 0 let request = NSMutableURLRequest(url: URL(string: "http://demomp2015.yoogooo.com/demoMovil/Web-Service/CxC.php")!) let db = self.dato.object(forKey: "dbName") let db1 = db as AnyObject? as? String let dbName : String = (db1 as AnyObject? as? String)! let idC = self.dato.object(forKey: "id_company") let idComp : String = idC as Any as! String request.httpMethod = "POST" let postParams = "DB_name="+dbName+"&"+"id_company="+idComp+"valor=%"+valor+"%" request.httpBody = postParams.data(using: String.Encoding.utf8) let task = URLSession.shared.dataTask(with: request as URLRequest) { (data, response, error ) in //print("response = \(response)") //imprime los datos del servidor al que me conecte let responseString: String = String(data: data!, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue))! let numbers = responseString.replacingOccurrences(of: "[", with: "", options: .literal, range: nil) let numbers1 = numbers.replacingOccurrences(of: "]", with: "", options: .literal, range: nil) var number2: [String] = numbers1.components(separatedBy: ",\"+\"") let cont = number2.count - 1 number2.remove(at: cont) while i < cont { //var dictionary: Dictionary <String,String> = [number2[i]] //print(dictionary) print(number2[i]) i += 1 } } task.resume() } func convertToDictionary(text: String) -> [String: String]? { if let data = text.data(using: .utf8) { do { return try JSONSerialization.jsonObject(with: data, options: []) as? [String: String] } catch { print(error.localizedDescription) } } return nil } }
36.337079
129
0.595857
8fd40509a2eef000afa190fe9484f1549367eaf3
222
// // FemhootApp.swift // Femhoot // // Created by Silvia España on 23/1/22. // import SwiftUI @main struct FemhootApp: App { var body: some Scene { WindowGroup { LoginView() } } }
12.333333
40
0.54955
72ae43446b8f3c9fbb63275cbba921de0e7fa899
46,563
// // SubredditThemeViewController.swift // Slide for Reddit // // Created by Carlos Crane on 1/20/17. // Copyright © 2017 Haptic Apps. All rights reserved. // import MKColorPicker import reddift import UIKit class SubredditThemeViewController: UITableViewController, ColorPickerViewDelegate { var subs: [String] = [] var accentChosen: UIColor? var colorChosen: UIColor? var chosenButtons = [UIBarButtonItem]() var regularButtons = [UIBarButtonItem]() override var preferredStatusBarStyle: UIStatusBarStyle { if ColorUtil.theme.isLight() && SettingValues.reduceColor { return .default } else { return .lightContent } } override func viewDidLoad() { super.viewDidLoad() self.tableView.separatorStyle = .none self.tableView.register(SubredditCellView.classForCoder(), forCellReuseIdentifier: "sub") self.tableView.isEditing = true self.tableView.backgroundColor = ColorUtil.backgroundColor self.tableView.allowsSelectionDuringEditing = true self.tableView.allowsMultipleSelectionDuringEditing = true subs = Subscriptions.subreddits self.subs = self.subs.sorted() { $0.localizedCaseInsensitiveCompare($1) == ComparisonResult.orderedAscending } tableView.reloadData() self.title = "Subreddit themes" let sync = UIButton.init(type: .custom) sync.setImage(UIImage.init(named: "sync")!.navIcon(), for: UIControl.State.normal) sync.addTarget(self, action: #selector(self.sync(_:)), for: UIControl.Event.touchUpInside) sync.frame = CGRect.init(x: -15, y: 0, width: 30, height: 30) let syncB = UIBarButtonItem.init(customView: sync) let add = UIButton.init(type: .custom) add.setImage(UIImage.init(named: "edit")!.navIcon(), for: UIControl.State.normal) add.addTarget(self, action: #selector(self.add(_:)), for: UIControl.Event.touchUpInside) add.frame = CGRect.init(x: -15, y: 0, width: 30, height: 30) let addB = UIBarButtonItem.init(customView: add) let delete = UIButton.init(type: .custom) delete.setImage(UIImage.init(named: "delete")!.navIcon(), for: UIControl.State.normal) delete.addTarget(self, action: #selector(self.remove(_:)), for: UIControl.Event.touchUpInside) delete.frame = CGRect.init(x: -15, y: 0, width: 30, height: 30) let deleteB = UIBarButtonItem.init(customView: delete) let all = UIButton.init(type: .custom) all.setImage(UIImage.init(named: "selectall")!.navIcon(), for: UIControl.State.normal) all.addTarget(self, action: #selector(self.all(_:)), for: UIControl.Event.touchUpInside) all.frame = CGRect.init(x: -15, y: 0, width: 30, height: 30) let allB = UIBarButtonItem.init(customView: all) regularButtons = [allB, syncB] chosenButtons = [deleteB, addB] self.navigationItem.rightBarButtonItems = regularButtons self.tableView.tableFooterView = UIView() } @objc public func all(_ selector: AnyObject) { for row in 0..<subs.count { tableView.selectRow(at: IndexPath(row: row, section: 0), animated: false, scrollPosition: .none) } self.navigationItem.setRightBarButtonItems(chosenButtons, animated: true) } @objc public func add(_ selector: AnyObject) { var selected: [String] = [] if tableView.indexPathsForSelectedRows != nil { for i in tableView.indexPathsForSelectedRows! { selected.append(subs[i.row]) } self.edit(selected, sender: selector as! UIButton) } } @objc public func remove(_ selector: AnyObject) { if tableView.indexPathsForSelectedRows != nil { for i in tableView.indexPathsForSelectedRows! { doDelete(subs[i.row]) } var toRemove = [String]() for i in tableView.indexPathsForSelectedRows! { toRemove.append(subs[i.row]) } self.subs = self.subs.filter({ (input) -> Bool in return !toRemove.contains(input) }) self.tableView.reloadData() } } public static var changed = false override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableView.automaticDimension } override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat { return UITableView.automaticDimension } var alertController: UIAlertController? var count = 0 @objc func sync(_ selector: AnyObject) { let defaults = UserDefaults.standard alertController = UIAlertController(title: "Syncing colors...\n\n\n", message: nil, preferredStyle: .alert) let spinnerIndicator = UIActivityIndicatorView(style: .whiteLarge) spinnerIndicator.center = CGPoint(x: 135.0, y: 65.5) spinnerIndicator.color = ColorUtil.fontColor spinnerIndicator.startAnimating() alertController?.view.addSubview(spinnerIndicator) self.present(alertController!, animated: true, completion: nil) var toReturn: [String] = [] defaults.set(true, forKey: "sc" + AccountController.currentName) defaults.synchronize() do { if !AccountController.isLoggedIn { try (UIApplication.shared.delegate as! AppDelegate).session!.getSubreddit(.default, paginator: Paginator(), completion: { (result) -> Void in switch result { case .failure: print(result.error!) case .success(let listing): let subs = listing.children.compactMap({ $0 as? Subreddit }) for sub in subs { if sub.keyColor.hexString() != "#FFFFFF" { toReturn.append(sub.displayName) let color = ColorUtil.getClosestColor(hex: sub.keyColor.hexString()) if UserDefaults.standard.colorForKey(key: "color+" + sub.displayName) == nil && color != .black { defaults.setColor(color: color, forKey: "color+" + sub.displayName) self.count += 1 } } } } DispatchQueue.main.async(execute: { () -> Void in self.complete() }) }) } else { Subscriptions.getSubscriptionsFully(session: (UIApplication.shared.delegate as! AppDelegate).session!, completion: { (subs, multis) in for sub in subs { if sub.keyColor.hexString() != "#FFFFFF" { toReturn.append(sub.displayName) let color = ColorUtil.getClosestColor(hex: sub.keyColor.hexString()) if UserDefaults.standard.colorForKey(key: "color+" + sub.displayName) == nil && color.hexString() != "#000000" { defaults.setColor(color: color, forKey: "color+" + sub.displayName) self.count += 1 } } } for m in multis { toReturn.append("/m/" + m.displayName) let color = (UIColor.init(hexString: m.keyColor)) if UserDefaults.standard.colorForKey(key: "color+" + m.displayName) == nil && color.hexString() != "#000000" { defaults.setColor(color: color, forKey: "color+" + m.displayName) self.count += 1 } } toReturn = toReturn.sorted { $0.localizedCaseInsensitiveCompare($1) == ComparisonResult.orderedAscending } toReturn.insert("all", at: 0) toReturn.insert("frontpage", at: 0) DispatchQueue.main.async(execute: { () -> Void in self.complete() }) }) } } catch { print(error) self.complete() } } func complete() { alertController!.dismiss(animated: true, completion: nil) BannerUtil.makeBanner(text: "\(count) subs colored", seconds: 5, context: self) count = 0 subs.removeAll() for sub in Subscriptions.subreddits { if UserDefaults.standard.colorForKey(key: "color+" + sub) != nil || UserDefaults.standard.colorForKey(key: "accent+" + sub) != nil { subs.append(sub) } } self.subs = self.subs.sorted() { $0.localizedCaseInsensitiveCompare($1) == ComparisonResult.orderedAscending } tableView.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: – Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return subs.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let thing = subs[indexPath.row] var cell: SubredditCellView? let c = tableView.dequeueReusableCell(withIdentifier: "sub", for: indexPath) as! SubredditCellView c.setSubreddit(subreddit: thing, nav: nil) cell = c cell?.backgroundColor = ColorUtil.foregroundColor return cell! } override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle { return .delete } override func tableView(_ tableView: UITableView, shouldIndentWhileEditingRowAt indexPath: IndexPath) -> Bool { return true } override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { return false } var savedView = UIView() var selected = false override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if !selected { self.navigationItem.setRightBarButtonItems(chosenButtons, animated: true) selected = true } } override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) { if tableView.indexPathsForSelectedRows == nil || tableView.indexPathsForSelectedRows!.isEmpty { selected = false self.navigationItem.setRightBarButtonItems(regularButtons, animated: true) } } var editSubs: [String] = [] public func colorPickerView(_ colorPickerView: ColorPickerView, didSelectItemAt indexPath: IndexPath) { if isAccent { accentChosen = colorPickerView.colors[indexPath.row] } else { colorChosen = colorPickerView.colors[indexPath.row] } } func edit(_ sub: [String], sender: UIButton) { editSubs = sub let alertController = UIAlertController(title: "\n\n\n\n\n\n\n\n", message: nil, preferredStyle: UIAlertController.Style.actionSheet) isAccent = false let margin: CGFloat = 10.0 let rect = CGRect(x: margin, y: margin, width: UIScreen.main.traitCollection.userInterfaceIdiom == .pad ? 314 - margin * 4.0: alertController.view.bounds.size.width - margin * 4.0, height: 150) let MKColorPicker = ColorPickerView.init(frame: rect) MKColorPicker.delegate = self MKColorPicker.colors = GMPalette.allColor() MKColorPicker.selectionStyle = .check MKColorPicker.scrollDirection = .vertical MKColorPicker.style = .circle alertController.view.addSubview(MKColorPicker) alertController.addAction(image: UIImage(named: "colors"), title: "Accent color", color: ColorUtil.baseAccent, style: .default) { _ in if self.colorChosen != nil { for sub in self.editSubs { ColorUtil.setColorForSub(sub: sub, color: self.colorChosen!) } } self.pickAccent(sub, sender: sender) } alertController.addAction(image: nil, title: "Save", color: ColorUtil.baseAccent, style: .default) { _ in if self.colorChosen != nil { for sub in self.editSubs { ColorUtil.setColorForSub(sub: sub, color: self.colorChosen!) } } self.tableView.reloadData() } alertController.addCancelButton() alertController.modalPresentationStyle = .popover if let presenter = alertController.popoverPresentationController { presenter.sourceView = savedView presenter.sourceRect = savedView.bounds } present(alertController, animated: true, completion: nil) } var isAccent = false func pickAccent(_ sub: [String], sender: UIButton) { isAccent = true let alertController = UIAlertController(title: "\n\n\n\n\n\n\n\n", message: nil, preferredStyle: UIAlertController.Style.actionSheet) let margin: CGFloat = 10.0 let rect = CGRect(x: margin, y: margin, width: UIScreen.main.traitCollection.userInterfaceIdiom == .pad ? 314 - margin * 4.0: alertController.view.bounds.size.width - margin * 4.0, height: 150) let MKColorPicker = ColorPickerView.init(frame: rect) MKColorPicker.delegate = self MKColorPicker.colors = GMPalette.allColorAccent() MKColorPicker.selectionStyle = .check self.isAccent = true MKColorPicker.scrollDirection = .vertical MKColorPicker.style = .circle alertController.view.addSubview(MKColorPicker) alertController.addAction(image: UIImage(named: "palette"), title: "Primary color", color: ColorUtil.baseAccent, style: .default) { _ in if self.accentChosen != nil { for sub in self.editSubs { ColorUtil.setAccentColorForSub(sub: sub, color: self.accentChosen!) } } self.edit(sub, sender: sender) self.tableView.reloadData() } alertController.addAction(image: nil, title: "Save", color: ColorUtil.baseAccent, style: .default) { _ in if self.accentChosen != nil { for sub in self.editSubs { ColorUtil.setAccentColorForSub(sub: sub, color: self.accentChosen!) } } self.tableView.reloadData() } if let presenter = alertController.popoverPresentationController { presenter.sourceView = savedView presenter.sourceRect = savedView.bounds } alertController.addCancelButton() present(alertController, animated: true, completion: nil) } override func tableView(_ tableView: UITableView, willBeginEditingRowAt indexPath: IndexPath) { let cell = tableView.cellForRow(at: indexPath) cell?.backgroundColor = ColorUtil.foregroundColor } func doDelete(_ sub: String) { UserDefaults.standard.removeObject(forKey: "color+" + sub) UserDefaults.standard.removeObject(forKey: "accent+" + sub) UserDefaults.standard.synchronize() } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { doDelete(subs[indexPath.row]) } } } public enum ToastPosition { case top case center case bottom } // // Toast.swift // Toast-Swift // // Copyright (c) 2015 Charles Scalesse. // // 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. /** Toast is a Swift extension that adds toast notifications to the `UIView` object class. It is intended to be simple, lightweight, and easy to use. Most toast notifications can be triggered with a single line of code. The `makeToast` methods create a new view and then display it as toast. The `showToast` methods display any view as toast. */ public extension UIView { /** Keys used for associated objects. */ private struct ToastKeys { static var Timer = "CSToastTimerKey" static var Duration = "CSToastDurationKey" static var Position = "CSToastPositionKey" static var Completion = "CSToastCompletionKey" static var ActiveToast = "CSToastActiveToastKey" static var ActivityView = "CSToastActivityViewKey" static var Queue = "CSToastQueueKey" } /** Swift closures can't be directly associated with objects via the Objective-C runtime, so the (ugly) solution is to wrap them in a class that can be used with associated objects. */ private class ToastCompletionWrapper { var completion: ((Bool) -> Void)? init(_ completion: ((Bool) -> Void)?) { self.completion = completion } } private enum ToastError: Error { case insufficientData } private var queue: NSMutableArray { if let queue = objc_getAssociatedObject(self, &ToastKeys.Queue) as? NSMutableArray { return queue } else { let queue = NSMutableArray() objc_setAssociatedObject(self, &ToastKeys.Queue, queue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) return queue } } // MARK: - Make Toast Methods /** Creates and presents a new toast view with a message and displays it with the default duration and position. Styled using the shared style. @param message The message to be displayed */ public func makeToast(_ message: String) { self.makeToast(message, duration: ToastManager.shared.duration, position: ToastManager.shared.position) } /** Creates and presents a new toast view with a message. Duration and position can be set explicitly. Styled using the shared style. @param message The message to be displayed @param duration The toast duration @param position The toast's position */ public func makeToast(_ message: String, duration: TimeInterval, position: ToastPosition) { self.makeToast(message, duration: duration, position: position, style: nil) } /** Creates and presents a new toast view with a message. Duration and position can be set explicitly. Styled using the shared style. @param message The message to be displayed @param duration The toast duration @param position The toast's center point */ public func makeToast(_ message: String, duration: TimeInterval, position: CGPoint) { self.makeToast(message, duration: duration, position: position, style: nil) } /** Creates and presents a new toast view with a message. Duration, position, and style can be set explicitly. @param message The message to be displayed @param duration The toast duration @param position The toast's position @param style The style. The shared style will be used when nil */ public func makeToast(_ message: String, duration: TimeInterval, position: ToastPosition, style: ToastStyle?) { self.makeToast(message, duration: duration, position: position, title: nil, image: nil, style: style, completion: nil) } /** Creates and presents a new toast view with a message. Duration, position, and style can be set explicitly. @param message The message to be displayed @param duration The toast duration @param position The toast's center point @param style The style. The shared style will be used when nil */ public func makeToast(_ message: String, duration: TimeInterval, position: CGPoint, style: ToastStyle?) { self.makeToast(message, duration: duration, position: position, title: nil, image: nil, style: style, completion: nil) } /** Creates and presents a new toast view with a message, title, and image. Duration, position, and style can be set explicitly. The completion closure executes when the toast completes presentation. `didTap` will be `true` if the toast view was dismissed from a tap. @param message The message to be displayed @param duration The toast duration @param position The toast's position @param title The title @param image The image @param style The style. The shared style will be used when nil @param completion The completion closure, executed after the toast view disappears. didTap will be `true` if the toast view was dismissed from a tap. */ public func makeToast(_ message: String?, duration: TimeInterval, position: ToastPosition, title: String?, image: UIImage?, style: ToastStyle?, completion: ((_ didTap: Bool) -> Void)?) { var toastStyle = ToastManager.shared.style if let style = style { toastStyle = style } do { let toast = try self.toastViewForMessage(message, title: title, image: image, style: toastStyle) self.showToast(toast, duration: duration, position: position, completion: completion) } catch ToastError.insufficientData { print("Error: message, title, and image are all nil") } catch { } } /** Creates and presents a new toast view with a message, title, and image. Duration, position, and style can be set explicitly. The completion closure executes when the toast completes presentation. `didTap` will be `true` if the toast view was dismissed from a tap. @param message The message to be displayed @param duration The toast duration @param position The toast's center point @param title The title @param image The image @param style The style. The shared style will be used when nil @param completion The completion closure, executed after the toast view disappears. didTap will be `true` if the toast view was dismissed from a tap. */ public func makeToast(_ message: String?, duration: TimeInterval, position: CGPoint, title: String?, image: UIImage?, style: ToastStyle?, completion: ((_ didTap: Bool) -> Void)?) { var toastStyle = ToastManager.shared.style if let style = style { toastStyle = style } do { let toast = try self.toastViewForMessage(message, title: title, image: image, style: toastStyle) self.showToast(toast, duration: duration, position: position, completion: completion) } catch ToastError.insufficientData { print("Error: message, title, and image cannot all be nil") } catch { } } // MARK: - Show Toast Methods /** Displays any view as toast using the default duration and position. @param toast The view to be displayed as toast */ public func showToast(_ toast: UIView) { self.showToast(toast, duration: ToastManager.shared.duration, position: ToastManager.shared.position, completion: nil) } /** Displays any view as toast at a provided position and duration. The completion closure executes when the toast view completes. `didTap` will be `true` if the toast view was dismissed from a tap. @param toast The view to be displayed as toast @param duration The notification duration @param position The toast's position @param completion The completion block, executed after the toast view disappears. didTap will be `true` if the toast view was dismissed from a tap. */ public func showToast(_ toast: UIView, duration: TimeInterval, position: ToastPosition, completion: ((_ didTap: Bool) -> Void)?) { let point = self.centerPointForPosition(position, toast: toast) self.showToast(toast, duration: duration, position: point, completion: completion) } /** Displays any view as toast at a provided position and duration. The completion closure executes when the toast view completes. `didTap` will be `true` if the toast view was dismissed from a tap. @param toast The view to be displayed as toast @param duration The notification duration @param position The toast's center point @param completion The completion block, executed after the toast view disappears. didTap will be `true` if the toast view was dismissed from a tap. */ public func showToast(_ toast: UIView, duration: TimeInterval, position: CGPoint, completion: ((_ didTap: Bool) -> Void)?) { objc_setAssociatedObject(toast, &ToastKeys.Completion, ToastCompletionWrapper(completion), .OBJC_ASSOCIATION_RETAIN_NONATOMIC) if objc_getAssociatedObject(self, &ToastKeys.ActiveToast) as? UIView != nil, ToastManager.shared.queueEnabled { objc_setAssociatedObject(toast, &ToastKeys.Duration, NSNumber(value: duration), .OBJC_ASSOCIATION_RETAIN_NONATOMIC) objc_setAssociatedObject(toast, &ToastKeys.Position, NSValue(cgPoint: position), .OBJC_ASSOCIATION_RETAIN_NONATOMIC) self.queue.add(toast) } else { self.showToast(toast, duration: duration, position: position) } } // MARK: - Activity Methods /** Creates and displays a new toast activity indicator view at a specified position. @warning Only one toast activity indicator view can be presented per superview. Subsequent calls to `makeToastActivity(position:)` will be ignored until `hideToastActivity()` is called. @warning `makeToastActivity(position:)` works independently of the `showToast` methods. Toast activity views can be presented and dismissed while toast views are being displayed. `makeToastActivity(position:)` has no effect on the queueing behavior of the `showToast` methods. @param position The toast's position */ public func makeToastActivity(_ position: ToastPosition) { // sanity if objc_getAssociatedObject(self, &ToastKeys.ActivityView) as? UIView != nil { return } let toast = self.createToastActivityView() let point = self.centerPointForPosition(position, toast: toast) self.makeToastActivity(toast, position: point) } /** Creates and displays a new toast activity indicator view at a specified position. @warning Only one toast activity indicator view can be presented per superview. Subsequent calls to `makeToastActivity(position:)` will be ignored until `hideToastActivity()` is called. @warning `makeToastActivity(position:)` works independently of the `showToast` methods. Toast activity views can be presented and dismissed while toast views are being displayed. `makeToastActivity(position:)` has no effect on the queueing behavior of the `showToast` methods. @param position The toast's center point */ public func makeToastActivity(_ position: CGPoint) { // sanity if objc_getAssociatedObject(self, &ToastKeys.ActivityView) as? UIView != nil { return } let toast = self.createToastActivityView() self.makeToastActivity(toast, position: position) } /** Dismisses the active toast activity indicator view. */ public func hideToastActivity() { if let toast = objc_getAssociatedObject(self, &ToastKeys.ActivityView) as? UIView { UIView.animate(withDuration: ToastManager.shared.style.fadeDuration, delay: 0.0, options: [.curveEaseIn, .beginFromCurrentState], animations: { () -> Void in toast.alpha = 0.0 }, completion: { (_: Bool) -> Void in toast.removeFromSuperview() objc_setAssociatedObject(self, &ToastKeys.ActivityView, nil, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) }) } } // MARK: - Private Activity Methods private func makeToastActivity(_ toast: UIView, position: CGPoint) { toast.alpha = 0.0 toast.center = position objc_setAssociatedObject(self, &ToastKeys.ActivityView, toast, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) self.addSubview(toast) UIView.animate(withDuration: ToastManager.shared.style.fadeDuration, delay: 0.0, options: .curveEaseOut, animations: { () -> Void in toast.alpha = 1.0 }, completion: nil) } private func createToastActivityView() -> UIView { let style = ToastManager.shared.style let activityView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: style.activitySize.width, height: style.activitySize.height)) activityView.backgroundColor = style.backgroundColor activityView.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin, .flexibleTopMargin, .flexibleBottomMargin] activityView.layer.cornerRadius = style.cornerRadius if style.displayShadow { activityView.layer.shadowColor = style.shadowColor.cgColor activityView.layer.shadowOpacity = style.shadowOpacity activityView.layer.shadowRadius = style.shadowRadius activityView.layer.shadowOffset = style.shadowOffset } let activityIndicatorView = UIActivityIndicatorView(style: .whiteLarge) activityIndicatorView.center = CGPoint(x: activityView.bounds.size.width / 2.0, y: activityView.bounds.size.height / 2.0) activityView.addSubview(activityIndicatorView) activityIndicatorView.startAnimating() return activityView } // MARK: - Private Show/Hide Methods private func showToast(_ toast: UIView, duration: TimeInterval, position: CGPoint) { toast.center = position toast.alpha = 0.0 if ToastManager.shared.tapToDismissEnabled { let recognizer = UITapGestureRecognizer(target: self, action: #selector(UIView.handleToastTapped(_:))) toast.addGestureRecognizer(recognizer) toast.isUserInteractionEnabled = true toast.isExclusiveTouch = true } objc_setAssociatedObject(self, &ToastKeys.ActiveToast, toast, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) self.addSubview(toast) UIView.animate(withDuration: ToastManager.shared.style.fadeDuration, delay: 0.0, options: [.curveEaseOut, .allowUserInteraction], animations: { () -> Void in toast.alpha = 1.0 }, completion: { _ in let timer = Timer(timeInterval: duration, target: self, selector: #selector(UIView.toastTimerDidFinish(_:)), userInfo: toast, repeats: false) RunLoop.main.add(timer, forMode: RunLoop.Mode.common) objc_setAssociatedObject(toast, &ToastKeys.Timer, timer, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) }) } private func hideToast(_ toast: UIView) { self.hideToast(toast, fromTap: false) } private func hideToast(_ toast: UIView, fromTap: Bool) { UIView.animate(withDuration: ToastManager.shared.style.fadeDuration, delay: 0.0, options: [.curveEaseIn, .beginFromCurrentState], animations: { () -> Void in toast.alpha = 0.0 }, completion: { _ in toast.removeFromSuperview() objc_setAssociatedObject(self, &ToastKeys.ActiveToast, nil, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) if let wrapper = objc_getAssociatedObject(toast, &ToastKeys.Completion) as? ToastCompletionWrapper, let completion = wrapper.completion { completion(fromTap) } if let nextToast = self.queue.firstObject as? UIView, let duration = objc_getAssociatedObject(nextToast, &ToastKeys.Duration) as? NSNumber, let position = objc_getAssociatedObject(nextToast, &ToastKeys.Position) as? NSValue { self.queue.removeObject(at: 0) self.showToast(nextToast, duration: duration.doubleValue, position: position.cgPointValue) } }) } // MARK: - Events @objc func handleToastTapped(_ recognizer: UITapGestureRecognizer) { if let toast = recognizer.view, let timer = objc_getAssociatedObject(toast, &ToastKeys.Timer) as? Timer { timer.invalidate() self.hideToast(toast, fromTap: true) } } @objc func toastTimerDidFinish(_ timer: Timer) { if let toast = timer.userInfo as? UIView { self.hideToast(toast) } } // MARK: - Toast Construction /** Creates a new toast view with any combination of message, title, and image. The look and feel is configured via the style. Unlike the `makeToast` methods, this method does not present the toast view automatically. One of the `showToast` methods must be used to present the resulting view. @warning if message, title, and image are all nil, this method will throw `ToastError.InsufficientData` @param message The message to be displayed @param title The title @param image The image @param style The style. The shared style will be used when nil @throws `ToastError.InsufficientData` when message, title, and image are all nil @return The newly created toast view */ public func toastViewForMessage(_ message: String?, title: String?, image: UIImage?, style: ToastStyle) throws -> UIView { // sanity if message == nil && title == nil && image == nil { throw ToastError.insufficientData } var messageLabel: UILabel? var titleLabel: UILabel? var imageView: UIImageView? let wrapperView = UIView() wrapperView.backgroundColor = style.backgroundColor wrapperView.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin, .flexibleTopMargin, .flexibleBottomMargin] wrapperView.layer.cornerRadius = style.cornerRadius if style.displayShadow { wrapperView.layer.shadowColor = UIColor.black.cgColor wrapperView.layer.shadowOpacity = style.shadowOpacity wrapperView.layer.shadowRadius = style.shadowRadius wrapperView.layer.shadowOffset = style.shadowOffset } if let image = image { imageView = UIImageView(image: image) imageView?.contentMode = .scaleAspectFit imageView?.frame = CGRect(x: style.horizontalPadding, y: style.verticalPadding, width: style.imageSize.width, height: style.imageSize.height) } var imageRect = CGRect.zero if let imageView = imageView { imageRect.origin.x = style.horizontalPadding imageRect.origin.y = style.verticalPadding imageRect.size.width = imageView.bounds.size.width imageRect.size.height = imageView.bounds.size.height } if let title = title { titleLabel = UILabel() titleLabel?.numberOfLines = style.titleNumberOfLines titleLabel?.font = style.titleFont titleLabel?.textAlignment = style.titleAlignment titleLabel?.lineBreakMode = .byTruncatingTail titleLabel?.textColor = style.titleColor titleLabel?.backgroundColor = UIColor.clear titleLabel?.text = title // let maxTitleSize = CGSize(width: (self.bounds.size.width * style.maxWidthPercentage) - imageRect.size.width, height: self.bounds.size.height * style.maxHeightPercentage) // let titleSize = titleLabel?.sizeThatFits(maxTitleSize) // if let titleSize = titleSize { // titleLabel?.frame = CGRect(x: 0.0, y: 0.0, width: titleSize.width, height: titleSize.height) // } } if let message = message { messageLabel = UILabel() messageLabel?.text = message messageLabel?.numberOfLines = style.messageNumberOfLines messageLabel?.font = style.messageFont messageLabel?.textAlignment = style.messageAlignment messageLabel?.lineBreakMode = .byTruncatingTail messageLabel?.textColor = style.messageColor messageLabel?.backgroundColor = UIColor.clear // let maxMessageSize = CGSize(width: (self.bounds.size.width * style.maxWidthPercentage) - imageRect.size.width, height: self.bounds.size.height * style.maxHeightPercentage) // let messageSize = messageLabel?.sizeThatFits(maxMessageSize) // if let messageSize = messageSize { //// let actualWidth = min(messageSize.width, maxMessageSize.width) // let actualHeight = min(messageSize.height, maxMessageSize.height) // messageLabel?.frame = CGRect(x: 0.0, y: 0.0, width: actualWidth, height: actualHeight) // } } var titleRect = CGRect.zero if let titleLabel = titleLabel { titleRect.origin.x = imageRect.origin.x + imageRect.size.width + style.horizontalPadding titleRect.origin.y = style.verticalPadding titleRect.size.width = titleLabel.bounds.size.width titleRect.size.height = titleLabel.bounds.size.height } var messageRect = CGRect.zero if let messageLabel = messageLabel { messageRect.origin.x = imageRect.origin.x + imageRect.size.width + style.horizontalPadding messageRect.origin.y = titleRect.origin.y + titleRect.size.height + style.verticalPadding messageRect.size.width = messageLabel.bounds.size.width messageRect.size.height = messageLabel.bounds.size.height } let longerWidth = max(titleRect.size.width, messageRect.size.width) let longerX = max(titleRect.origin.x, messageRect.origin.x) let wrapperWidth = max((imageRect.size.width + (style.horizontalPadding * 2.0)), (longerX + longerWidth + style.horizontalPadding)) let wrapperHeight = max((messageRect.origin.y + messageRect.size.height + style.verticalPadding), (imageRect.size.height + (style.verticalPadding * 2.0))) wrapperView.frame = CGRect(x: 0.0, y: 0.0, width: wrapperWidth, height: wrapperHeight) if let titleLabel = titleLabel { titleLabel.frame = titleRect wrapperView.addSubview(titleLabel) } if let messageLabel = messageLabel { messageLabel.frame = messageRect wrapperView.addSubview(messageLabel) } if let imageView = imageView { wrapperView.addSubview(imageView) } return wrapperView } // MARK: - Helpers private func centerPointForPosition(_ position: ToastPosition, toast: UIView) -> CGPoint { let padding: CGFloat = ToastManager.shared.style.verticalPadding switch position { case .top: return CGPoint(x: self.bounds.size.width / 2.0, y: (toast.frame.size.height / 2.0) + padding) case .center: return CGPoint(x: self.bounds.size.width / 2.0, y: self.bounds.size.height / 2.0) case .bottom: return CGPoint(x: self.bounds.size.width / 2.0, y: (self.bounds.size.height - (toast.frame.size.height / 2.0)) - padding) } } } // MARK: - Toast Style /** `ToastStyle` instances define the look and feel for toast views created via the `makeToast` methods as well for toast views created directly with `toastViewForMessage(message:title:image:style:)`. @warning `ToastStyle` offers relatively simple styling options for the default toast view. If you require a toast view with more complex UI, it probably makes more sense to create your own custom UIView subclass and present it with the `showToast` methods. */ public struct ToastStyle { public init() { } /** The background color. Default is `UIColor.blackColor()` at 80% opacity. */ public var backgroundColor = UIColor.black.withAlphaComponent(0.8) /** The title color. Default is `UIColor.whiteColor()`. */ public var titleColor = UIColor.white /** The message color. Default is `UIColor.whiteColor()`. */ public var messageColor = UIColor.white /** A percentage value from 0.0 to 1.0, representing the maximum width of the toast view relative to it's superview. Default is 0.8 (80% of the superview's width). */ public var maxWidthPercentage: CGFloat = 0.8 { didSet { maxWidthPercentage = max(min(maxWidthPercentage, 1.0), 0.0) } } /** A percentage value from 0.0 to 1.0, representing the maximum height of the toast view relative to it's superview. Default is 0.8 (80% of the superview's height). */ public var maxHeightPercentage: CGFloat = 0.8 { didSet { maxHeightPercentage = max(min(maxHeightPercentage, 1.0), 0.0) } } /** The spacing from the horizontal edge of the toast view to the content. When an image is present, this is also used as the padding between the image and the text. Default is 10.0. */ public var horizontalPadding: CGFloat = 10.0 /** The spacing from the vertical edge of the toast view to the content. When a title is present, this is also used as the padding between the title and the message. Default is 10.0. */ public var verticalPadding: CGFloat = 10.0 /** The corner radius. Default is 10.0. */ public var cornerRadius: CGFloat = 10.0 /** The title font. Default is `UIFont.boldSystemFontOfSize(16.0)`. */ public var titleFont = UIFont.boldSystemFont(ofSize: 16.0) /** The message font. Default is `UIFont.systemFontOfSize(16.0)`. */ public var messageFont = UIFont.systemFont(ofSize: 16.0) /** The title text alignment. Default is `NSTextAlignment.Left`. */ public var titleAlignment = NSTextAlignment.left /** The message text alignment. Default is `NSTextAlignment.Left`. */ public var messageAlignment = NSTextAlignment.left /** The maximum number of lines for the title. The default is 0 (no limit). */ public var titleNumberOfLines = 0 /** The maximum number of lines for the message. The default is 0 (no limit). */ public var messageNumberOfLines = 0 /** Enable or disable a shadow on the toast view. Default is `false`. */ public var displayShadow = false /** The shadow color. Default is `UIColor.blackColor()`. */ public var shadowColor = UIColor.black /** A value from 0.0 to 1.0, representing the opacity of the shadow. Default is 0.8 (80% opacity). */ public var shadowOpacity: Float = 0.8 { didSet { shadowOpacity = max(min(shadowOpacity, 1.0), 0.0) } } /** The shadow radius. Default is 6.0. */ public var shadowRadius: CGFloat = 6.0 /** The shadow offset. The default is 4 x 4. */ public var shadowOffset = CGSize(width: 4.0, height: 4.0) /** The image size. The default is 80 x 80. */ public var imageSize = CGSize(width: 80.0, height: 80.0) /** The size of the toast activity view when `makeToastActivity(position:)` is called. Default is 100 x 100. */ public var activitySize = CGSize(width: 100.0, height: 100.0) /** The fade in/out animation duration. Default is 0.2. */ public var fadeDuration: TimeInterval = 0.2 } // MARK: - Toast Manager /** `ToastManager` provides general configuration options for all toast notifications. Backed by a singleton instance. */ public class ToastManager { /** The `ToastManager` singleton instance. */ public static let shared = ToastManager() /** The shared style. Used whenever toastViewForMessage(message:title:image:style:) is called with with a nil style. */ public var style = ToastStyle() /** Enables or disables tap to dismiss on toast views. Default is `true`. */ public var tapToDismissEnabled = true /** Enables or disables queueing behavior for toast views. When `true`, toast views will appear one after the other. When `false`, multiple toast views will appear at the same time (potentially overlapping depending on their positions). This has no effect on the toast activity view, which operates independently of normal toast views. Default is `true`. */ public var queueEnabled = true /** The default duration. Used for the `makeToast` and `showToast` methods that don't require an explicit duration. Default is 3.0. */ public var duration: TimeInterval = 3.0 /** Sets the default position. Used for the `makeToast` and `showToast` methods that don't require an explicit position. Default is `ToastPosition.Bottom`. */ public var position = ToastPosition.bottom }
40.209845
237
0.647209
e40a1a5d526247d76af038d4d30166ce93936306
2,873
// // LocationManager.swift // WebService // // Created by Gaurang Lathiya on 11/20/17. // Copyright © 2017 Gaurang Lathiya. All rights reserved. // import UIKit import CoreLocation class LocationManager: NSObject, CLLocationManagerDelegate { let manager = CLLocationManager() class var sharedInstance: LocationManager { //creating Shared Instance struct Static { static let instance: LocationManager = LocationManager() } return Static.instance } override init() { super.init() manager.delegate = self manager.requestWhenInUseAuthorization() } func updateCurrentLocation() { manager.requestLocation() } // MARK: - CLLocationManagerDelegate func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { switch status { case .authorizedWhenInUse: break case .notDetermined: break default: if let topController = UIApplication.shared.keyWindow?.rootViewController { topController.topMostViewController().showAlert(withTitle: Constants.kApplicationName, message: Constants.kNoLocationInformation) } } } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { if let location = locations.first { // print("Found user's location: \(location)") LocationManager.fetchCountryAndCity(location: location) { country, state, city in // save current location // "Nashik (Maharashtra), India" let currentLocation: String = "\(city) (\(state)), \(country)" print("Current Location: \(currentLocation)") UserDefaults.standard.setValue(currentLocation, forKey: Constants.kUserSavedLocation) UserDefaults.standard.synchronize() } } } func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { print("Failed to find user's location: \(error.localizedDescription)") // Remove saved location UserDefaults.standard.removeObject(forKey: Constants.kUserSavedLocation) UserDefaults.standard.synchronize() } class func fetchCountryAndCity(location: CLLocation, completion: @escaping (String, String, String) -> ()) { CLGeocoder().reverseGeocodeLocation(location) { placemarks, error in if let error = error { print(error) } else if let country = placemarks?.first?.country, let state = placemarks?.first?.administrativeArea, let city = placemarks?.first?.locality { completion(country, state, city) } } } }
35.036585
145
0.631396
f4b1c0f541a29ac4cbc18a930140901befa5c0c0
2,177
// // AppDelegate.swift // MyApp // // Created by 冯志浩 on 2017/2/16. // Copyright © 2017年 FZH. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. chooseRootVC() 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:. } }
46.319149
285
0.751952
cc426376c224e4dbfb182b415fd9e6f470cf7c63
952
// // ERNSTextAlignmentExtension.swift // ErKit // // Created by Erbash on 11/29/2021. // Copyright (c) 2021 Erbash. All rights reserved. // // leading 与 left 的区别 (同 trailing 与 right 的区别) // leading 的含义是头部, left 的含义是左. 对所有人来说, left 都是 left. 对中国人来说, 一行文字的 leading 是 left, 但是对一些其他文化的人 (比如穆斯林) 来说, 一行文字的 leading 则是 right import UIKit public extension NSTextAlignment { /// leading 对齐方式 /// /// 布局方向 LTR 时左对齐 /// /// 布局方向 RTL 时右对齐 static var leading: NSTextAlignment { if UIView.appearance().semanticContentAttribute == .forceRightToLeft { return .right }else { return .left } } /// trailing 对齐方式 /// /// 布局方向 LTR 时右对齐 /// /// 布局方向 RTL 时左对齐 static var trailing: NSTextAlignment { if UIView.appearance().semanticContentAttribute == .forceRightToLeft { return .left }else { return .right } } }
23.219512
129
0.594538
d6c64f4341c49e7463a3a62238495e5d240f5f1f
2,482
// // Global.swift // weibo_swift // // Created by ocean on 16/6/17. // Copyright © 2016年 ocean. All rights reserved. // import UIKit //MARK: - 屏幕尺寸 let kScreenW = UIScreen.mainScreen().bounds.size.width let kScreenH = UIScreen.mainScreen().bounds.size.height //MARK: - 沙盒保存用户的文件名称 let kUserAccountName = "account.plist" //MARK: - OAuth授权登录 let oauthURLString = "https://api.weibo.com/oauth2/authorize" let redirect_uri = "http://weibo.com/u/3216382533/home?wvr=5" let accessTokenURLString = "https://api.weibo.com/oauth2/access_token" let client_id = "4017753567" let client_secret = "528d174ef961f18dfe3acce2be8b1e69" let grant_type = "authorization_code" //MARK: - 微博相关接口 //获取当前登录用户及其所关注(授权)用户的最新微博 let kHome_timelineString = "https://api.weibo.com/2/statuses/home_timeline.json" //MARK: - 微博cell相关属性设置 //原创微博nameLabel let kHomeCellNameLableFont = UIFont.systemFontOfSize(14.0) let kHomeCellNameLableColorVip = UIColor.orangeColor() let kHomeCellNameLableColorNormal = UIColor.blackColor() //原创微博timeLable let kHomeCellTimeLableFont = UIFont.systemFontOfSize(11.0) let kHomeCellTimeLableColor = UIColor.orangeColor() //原创微博sourceLabel let kHomeCellSourceLabelFont = UIFont.systemFontOfSize(11.0) let kHomeCellSourceLabelColor = UIColor.blackColor() //原创微博text let kHomeCellTextLabelFont = UIFont.systemFontOfSize(14.0) let kHomeCellTextLabelColor = UIColor.blackColor() //转发微博name let kHomeCellRetweetedNameLabelFont = UIFont.systemFontOfSize(12.0) let kHomeCellRetweetedNameLabelColor = UIColor.blueColor() //转发微博text let kHomeCellRetweetedTextLabelFont = UIFont.systemFontOfSize(12.0) let kHomeCellRetweetedTextLabelColor = UIColor.blackColor() //toolbar let kHomeCellToolBarFont = UIFont.systemFontOfSize(12.0) let kHomeCellToolBarColor = UIColor.blackColor() //MARK: - tabBar属性 let kTabBarTtitleFont = UIFont.systemFontOfSize(12.0) let kTabBarTintColor = UIColor.orangeColor() //MARK: - navigationBar 和 左右item不同状态下的 的属性 let kNaviBarTitleFont = UIFont.systemFontOfSize(20.0) let kNaviBarTitleColor = UIColor.blackColor() let kNaviItemTitleFontOfNormal = UIFont.systemFontOfSize(15.0) let kNaviItemTitleColorOfNormal = UIColor.orangeColor() let kNaviItemTitleFontOfHighlighted = UIFont.systemFontOfSize(15.0) let kNaviItemTitleColorOfHighlighted = UIColor.redColor() //MARK: - cell的重用标示符 //主页 let kHomeTableCellIdentifier = "homeTableCellIdentifier" //MARK: - 第三方登录信息 /* App Key 14084daaa97b6 App Secret eb42509eea896a142ba669eb0b071929 */
24.82
80
0.798147
61a8e6eacaf2ed1dc5768ac55f9b148d5e71e0cb
2,679
// // NFXServer.swift // netfox_ios // // Created by Alexandru Tudose on 01/11/2017. // Copyright © 2017 kasketis. All rights reserved. // import Foundation import UIKit public class NFXServer: NSObject { public struct Options { public static let bonjourServiceType = "_NFX._tcp." public static let port: UInt16 = 12222 } var netService: NetService? var port: UInt16 = Options.port var numberOfRetries = 0 var connectedClients: [NFXClientConnection] = [] public func startServer() { publishHttpService() #if os(iOS) NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil) #endif } public func stopServer() { netService?.stop() netService = nil NotificationCenter.default.removeObserver(self) } func publishHttpService() { let bundleIdentifier = Bundle.main.bundleIdentifier ?? "" let netService = NetService(domain: "", type: NFXServer.Options.bonjourServiceType, name: bundleIdentifier, port: Int32(port)) netService.delegate = self netService.publish(options: [.listenForConnections]) self.netService = netService } func broadcastModel(_ model: NFXHTTPModel) { connectedClients.forEach({ $0.writeModel(model) }) } @objc func applicationDidBecomeActive() { DispatchQueue.main.asyncAfter(deadline: .now() + 1) { if self.connectedClients.isEmpty { self.stopServer() DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { self.startServer() } } } } } extension NFXServer: NetServiceDelegate { public func netServiceDidPublish(_ sender: NetService) { } public func netService(_ sender: NetService, didNotPublish errorDict: [String : NSNumber]) { print("failed to publish http service: \(errorDict)") } public func netService(_ sender: NetService, didAcceptConnectionWith inputStream: InputStream, outputStream: OutputStream) { let client = NFXClientConnection(inputStream: inputStream, outputStream: outputStream) client.scheduleOnBackgroundRunLoop() connectedClients.append(client) client.prepareForWritingStream() client.writeAllModels() client.onClose = { [unowned self] in if let index = self.connectedClients.firstIndex(of: client) { self.connectedClients.remove(at: index) } } } }
31.892857
163
0.640911
f5b2b3f2facadc64766661e08a9f00d1c2be99f6
1,548
// // UPennBiometricsEnableCell.swift // Penn Chart Live // // Created by Rashad Abdul-Salam on 3/18/19. // Copyright © 2019 University of Pennsylvania Health System. All rights reserved. // import Foundation import UIKit class UPennBiometricsEnableCell : UPennBasicCell, UPennImageLabelSwitchConfigureInterface { @IBOutlet weak var biometricsImage: UIImageView! @IBOutlet weak var biometricsToggleLabel: UPennLabel! @IBOutlet weak var biometricsSwitch: UISwitch! @IBOutlet weak var imageLabelSwitchView: UPennImageLabelSwitchView! var biometricsDelegate: UPennBiometricsToggleDelegate? @IBAction func toggledBiometrics(_ sender: UISwitch) { self.biometricsDelegate?.toggledBiometrics(self.biometricsSwitch.isOn) } func configure(_ decorator: UPennImageLabelSwitchControlDecorated) { self.imageLabelSwitchView.configure(decorator) } // func configure(with delegate: // UPennBiometricsToggleDelegate, biometricsService: UPennBiometricsAuthenticationInterface ) { // self.biometricsToggleLabel.text = biometricsService.toggleTitleText // self.biometricsDelegate = delegate // self.biometricsSwitch.isEnabled = biometricsService.biometricsAvailable // self.biometricsSwitch.isSelected = biometricsService.biometricsEnabled // self.biometricsImage.image = biometricsService.biometricsImage // self.biometricsSwitch.setOn(biometricsService.biometricsEnabled, animated: false) // } }
36.857143
102
0.744832
1eebc89e9edd238393e3d8e4498dde633ab46c4b
1,259
// // KLNetworkSession.swift // KLNetwork // // Created by Kuroba.Lei on 2018/6/11. // Copyright © 2018年 雷珂阳. All rights reserved. // import UIKit import Alamofire ///请求方式 enum RequestMethod: String { case options = "OPTIONS" case get = "GET" case head = "HEAD" case post = "POST" case put = "PUT" case patch = "PATCH" case delete = "DELETE" case trace = "TRACE" case connect = "CONNECT" } /// 参数拼接的类型 enum ParamaetersType: String { case body = "body" case query = "query" } /// 请求 数据类型 enum ResponseDateType: String { case array = "array" case object = "Object" case json = "json" } class AlamofireSession: NSObject { static let `default`: AlamofireSession = AlamofireSession() /// 请求数据的 Menager var sessionMenager: SessionManager = { let configuration = URLSessionConfiguration.default configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders configuration.timeoutIntervalForRequest = TimeInterval(Alamafire_TimeoutIntervalForRequest) let sessionMenager = SessionManager.init(configuration: configuration, delegate: KLNetworkSessionDelegate(), serverTrustPolicyManager: nil) return sessionMenager }() }
24.686275
147
0.680699
114adf3caa0ed3f4156e230e685ddd3bd578d4a6
452
// // HttpBadRequestResponse.swift // // Generated by openapi-generator // https://openapi-generator.tech // import Foundation public struct HttpBadRequestResponse: Codable { public var statusCode: Int64 public var error: String public var message: [String] public init(statusCode: Int64, error: String, message: [String]) { self.statusCode = statusCode self.error = error self.message = message } }
18.08
70
0.679204
d50a36818f15cb50d04fbb7dd3f86aa74d26a8ea
718
// // NotExistViewController.swift // SwiftExtensions // // Created by 赵国庆 on 2017/4/27. // Copyright © 2017年 Kagen Zhao. All rights reserved. // import UIKit class NotExistViewController: UIViewController { var pageName: String? convenience init(pageName: String) { self.init(nibName: nil, bundle: nil) self.pageName = pageName } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white let label = UILabel(frame: view.bounds) label.text = "page \(pageName != nil ? "\"\(pageName!)\"" : "") not found\n" label.textColor = .gray label.textAlignment = .center view.addSubview(label) } }
23.933333
84
0.619777
abf2b3ebe333a239576de9a5766a9c5bd08fb5ab
299
// // GlobalVariables.swift // Common // // Created by Mortennn on 26/12/2017. // Copyright © 2017 Mortennn. All rights reserved. // import Foundation public enum GlobalVariables:String { case sharedContainerID = "group.Mortennn.FiScript" case commonBundleID = "com.Mortennn.Common" }
19.933333
54
0.719064
2927c4007a5fb393688044953ceb62800876fa8a
467
// // CircleImage.swift // View // // Created by Vcvc on 2021/10/17. // import SwiftUI struct CircleImage: View { var body: some View { Image("turtlerock") .clipShape(/*@START_MENU_TOKEN@*/Circle()/*@END_MENU_TOKEN@*/) .overlay(Circle().stroke(Color.white, lineWidth: 2)) .shadow(radius: 7) } } struct CircleImage_Previews: PreviewProvider { static var previews: some View { CircleImage() } }
19.458333
74
0.601713
f8957ab2443a3b153b9b61d5d4b8c850fbf14b5b
396
// // UITextFieldExtension.swift // MavenTest // // Created by German on 9/13/19. // Copyright © 2019 Rootstrap Inc. All rights reserved. // import UIKit extension UITextField { func setPlaceholder(color: UIColor = .lightGray) { attributedPlaceholder = NSAttributedString( string: placeholder ?? "", attributes: [NSAttributedString.Key.foregroundColor: color] ) } }
20.842105
65
0.694444
fce356347a410e8ab5ec48bd670feb7c5b485947
862
// // String+Extension.swift // SortPbxprojCore // // Created by Keisuke Shoji on 2018/12/01. // import Foundation extension String { private var nsString: NSString { return self as NSString } private func regexMatch(_ pattern: String) throws -> NSTextCheckingResult? { let regex: NSRegularExpression = try .init(pattern: pattern) return regex.firstMatch(in: self, range: NSMakeRange(0, nsString.length)) } func regexMatches(_ pattern: String) -> [String] { guard case .some(.some(let result)) = try? regexMatch(pattern) else { return [] } return (0..<result.numberOfRanges) .map { result.range(at: $0) } .map { nsString.substring(with: $0) } } func appendingPathComponent(_ path: String) -> String { return nsString.appendingPathComponent(path) } }
27.806452
89
0.642691
484d37a1659fa8003d8d71adc61f0890fd0b09f0
3,723
/* The MIT License (MIT) Original work Copyright (c) 2015 pluralsight Modified work Copyright 2016 Ben Kraus 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 /** `ExclusivityController` is a singleton to keep track of all the in-flight `Operation` instances that have declared themselves as requiring mutual exclusivity. We use a singleton because mutual exclusivity must be enforced across the entire app, regardless of the `OperationQueue` on which an `Operation` was executed. */ class ExclusivityController { static let sharedExclusivityController = ExclusivityController() private let serialQueue = dispatch_queue_create("Operations.ExclusivityController", DISPATCH_QUEUE_SERIAL) private var operations: [String: [Operation]] = [:] private init() { /* A private initializer effectively prevents any other part of the app from accidentally creating an instance. */ } /// Registers an operation as being mutually exclusive func addOperation(operation: Operation, categories: [String]) { /* This needs to be a synchronous operation. If this were async, then we might not get around to adding dependencies until after the operation had already begun, which would be incorrect. */ dispatch_sync(serialQueue) { for category in categories { self.noqueue_addOperation(operation, category: category) } } } /// Unregisters an operation from being mutually exclusive. func removeOperation(operation: Operation, categories: [String]) { dispatch_async(serialQueue) { for category in categories { self.noqueue_removeOperation(operation, category: category) } } } // MARK: Operation Management private func noqueue_addOperation(operation: Operation, category: String) { var operationsWithThisCategory = operations[category] ?? [] if let last = operationsWithThisCategory.last { operation.addDependency(last) } operationsWithThisCategory.append(operation) operations[category] = operationsWithThisCategory } private func noqueue_removeOperation(operation: Operation, category: String) { let matchingOperations = operations[category] if var operationsWithThisCategory = matchingOperations, let index = operationsWithThisCategory.indexOf(operation) { operationsWithThisCategory.removeAtIndex(index) operations[category] = operationsWithThisCategory } } }
38.381443
110
0.703734
9ba352308d684375b1bfd7265ae5df73208de38a
1,034
import XCTest @testable import DifferenceRepresentable struct User: DifferenceRepresentable { let name: String let age: Int let country: String let imageUrl: URL? } final class DifferenceRepresentableTests: XCTestCase { func testExample() { let userA = User(name: "Bob", age: 10, country: "Japan", imageUrl: URL(string: "https://example.com")) let userB = User(name: "Bob", age: 20, country: "United States", imageUrl: nil) var diff = userA.difference(from: userB) XCTAssertEqual(diff.keys.count, 3) XCTAssertEqual(diff["age"], 10) XCTAssertEqual(diff["country"], "Japan") XCTAssertEqual(diff["imageUrl"] as? URL, URL(string: "https://example.com")) diff = userB.difference(from: userA) XCTAssertEqual(diff.keys.count, 3) XCTAssertEqual(diff["age"], 20) XCTAssertEqual(diff["country"], "United States") XCTAssertNil(diff["imageUrl"]) } static var allTests = [ ("testExample", testExample), ] }
32.3125
110
0.643133
50aa7d9d94d076cf63b7ad481898914faada997b
16,832
// // PaymentSheet+SwiftUI.swift // StripeiOS // // Created by David Estes on 1/14/21. // Copyright © 2021 Stripe, Inc. All rights reserved. // // This is adapted from a strategy used in BetterSafariView by Dongkyu Kim. // https://github.com/stleamist/BetterSafariView import SwiftUI @available(iOS 13.0, *) @available(iOSApplicationExtension, unavailable) @available(macCatalystApplicationExtension, unavailable) extension View { /// Presents a sheet for a customer to complete their payment. /// - Parameter isPresented: A binding to whether the sheet is presented. /// - Parameter paymentSheet: A PaymentSheet to present. /// - Parameter onCompletion: Called with the result of the payment after the payment sheet is dismissed. public func paymentSheet( isPresented: Binding<Bool>, paymentSheet: PaymentSheet, onCompletion: @escaping (PaymentSheetResult) -> Void ) -> some View { self.modifier( PaymentSheet.PaymentSheetPresentationModifier( isPresented: isPresented, paymentSheet: paymentSheet, onCompletion: onCompletion ) ) } /// Presents a sheet for a customer to select a payment option. /// - Parameter isPresented: A binding to whether the sheet is presented. /// - Parameter paymentSheetFlowController: A PaymentSheet.FlowController to present. /// - Parameter onSheetDismissed: Called after the payment options sheet is dismissed. public func paymentOptionsSheet( isPresented: Binding<Bool>, paymentSheetFlowController: PaymentSheet.FlowController, onSheetDismissed: (() -> Void)? ) -> some View { self.modifier( PaymentSheet.PaymentSheetFlowControllerPresentationModifier( isPresented: isPresented, paymentSheetFlowController: paymentSheetFlowController, action: .presentPaymentOptions, optionsCompletion: onSheetDismissed, paymentCompletion: nil ) ) } /// Confirm the payment, presenting a sheet for the user to confirm their payment if needed. /// - Parameter isConfirming: A binding to whether the payment is being confirmed. This will present a sheet if needed. It will be updated to `false` after performing the payment confirmation. /// - Parameter paymentSheetFlowController: A PaymentSheet.FlowController to present. /// - Parameter onCompletion: Called with the result of the payment after the payment confirmation is done and the sheet (if any) is dismissed. public func paymentConfirmationSheet( isConfirming: Binding<Bool>, paymentSheetFlowController: PaymentSheet.FlowController, onCompletion: @escaping (PaymentSheetResult) -> Void ) -> some View { self.modifier( PaymentSheet.PaymentSheetFlowControllerPresentationModifier( isPresented: isConfirming, paymentSheetFlowController: paymentSheetFlowController, action: .confirm, optionsCompletion: nil, paymentCompletion: onCompletion ) ) } /// :nodoc: @available( *, deprecated, renamed: "paymentConfirmationSheet(isConfirming:paymentSheetFlowController:onCompletion:)" ) public func paymentConfirmationSheet( isConfirmingPayment: Binding<Bool>, paymentSheetFlowController: PaymentSheet.FlowController, onCompletion: @escaping (PaymentSheetResult) -> Void ) -> some View { return paymentConfirmationSheet( isConfirming: isConfirmingPayment, paymentSheetFlowController: paymentSheetFlowController, onCompletion: onCompletion ) } } @available(iOS 13.0, *) @available(iOSApplicationExtension, unavailable) @available(macCatalystApplicationExtension, unavailable) extension PaymentSheet { /// A button which presents a sheet for a customer to complete their payment. /// This is a convenience wrapper for the .paymentSheet() ViewModifier. /// - Parameter paymentSheet: A PaymentSheet to present. /// - Parameter onCompletion: Called with the result of the payment after the payment sheet is dismissed. /// - Parameter content: The content of the view. public struct PaymentButton<Content: View>: View { private let paymentSheet: PaymentSheet private let onCompletion: (PaymentSheetResult) -> Void private let content: Content @State private var showingPaymentSheet = false /// Initialize a `PaymentButton` with required parameters. public init( paymentSheet: PaymentSheet, onCompletion: @escaping (PaymentSheetResult) -> Void, @ViewBuilder content: () -> Content ) { self.paymentSheet = paymentSheet self.onCompletion = onCompletion self.content = content() } public var body: some View { Button(action: { showingPaymentSheet = true }) { content }.paymentSheet( isPresented: $showingPaymentSheet, paymentSheet: paymentSheet, onCompletion: onCompletion) } } } @available(iOS 13.0, *) @available(iOSApplicationExtension, unavailable) @available(macCatalystApplicationExtension, unavailable) extension PaymentSheet.FlowController { /// A button which presents a sheet for a customer to select a payment method. /// This is a convenience wrapper for the .paymentOptionsSheet() ViewModifier. /// - Parameter paymentSheetFlowController: A PaymentSheet.FlowController to present. /// - Parameter onSheetDismissed: Called after the payment method selector is dismissed. /// - Parameter content: The content of the view. public struct PaymentOptionsButton<Content: View>: View { private let paymentSheetFlowController: PaymentSheet.FlowController private let onSheetDismissed: () -> Void private let content: Content @State private var showingPaymentSheet = false /// Initialize a `PaymentOptionsButton` with required parameters. public init( paymentSheetFlowController: PaymentSheet.FlowController, onSheetDismissed: @escaping () -> Void, @ViewBuilder content: () -> Content ) { self.paymentSheetFlowController = paymentSheetFlowController self.onSheetDismissed = onSheetDismissed self.content = content() } public var body: some View { Button(action: { showingPaymentSheet = true }) { content }.paymentOptionsSheet( isPresented: $showingPaymentSheet, paymentSheetFlowController: paymentSheetFlowController, onSheetDismissed: onSheetDismissed) } } /// :nodoc: @available(*, deprecated, renamed: "ConfirmButton") public typealias ConfirmPaymentButton = ConfirmButton /// A button which confirms the payment or setup. Depending on the user's payment method, it may present a confirmation sheet. /// This is a convenience wrapper for the .paymentConfirmationSheet() ViewModifier. /// - Parameter paymentSheetFlowController: A PaymentSheet.FlowController to present. /// - Parameter onCompletion: Called with the result of the payment/setup confirmation, after the PaymentSheet (if any) is dismissed. /// - Parameter content: The content of the view. public struct ConfirmButton<Content: View>: View { private let paymentSheetFlowController: PaymentSheet.FlowController private let onCompletion: (PaymentSheetResult) -> Void private let content: Content @State private var showingPaymentSheet = false /// Initialize a `ConfirmPaymentButton` with required parameters. public init( paymentSheetFlowController: PaymentSheet.FlowController, onCompletion: @escaping (PaymentSheetResult) -> Void, @ViewBuilder content: () -> Content ) { self.paymentSheetFlowController = paymentSheetFlowController self.onCompletion = onCompletion self.content = content() } public var body: some View { Button(action: { showingPaymentSheet = true }) { content }.paymentConfirmationSheet( isConfirming: $showingPaymentSheet, paymentSheetFlowController: paymentSheetFlowController, onCompletion: onCompletion) } } } @available(iOS 13.0, *) @available(iOSApplicationExtension, unavailable) @available(macCatalystApplicationExtension, unavailable) extension PaymentSheet { struct PaymentSheetPresenter: UIViewRepresentable { @Binding var presented: Bool weak var paymentSheet: PaymentSheet? let onCompletion: (PaymentSheetResult) -> Void func makeCoordinator() -> Coordinator { return Coordinator(parent: self) } func makeUIView(context: Context) -> UIView { return context.coordinator.view } func updateUIView(_ uiView: UIView, context: Context) { context.coordinator.parent = self context.coordinator.presented = presented } class Coordinator { var parent: PaymentSheetPresenter let view = UIView() var presented: Bool { didSet { switch (oldValue, presented) { case (false, false): break case (false, true): guard let viewController = findViewController(for: view) else { parent.presented = false return } presentPaymentSheet(on: viewController) case (true, false): guard let viewController = findViewController(for: view) else { parent.presented = true return } forciblyDismissPaymentSheet(from: viewController) case (true, true): break } } } init(parent: PaymentSheetPresenter) { self.parent = parent self.presented = parent.presented } func presentPaymentSheet(on controller: UIViewController) { let presenter = findViewControllerPresenter(from: controller) parent.paymentSheet?.present(from: presenter) { (result: PaymentSheetResult) in self.parent.presented = false self.parent.onCompletion(result) } } func forciblyDismissPaymentSheet(from controller: UIViewController) { if let bsvc = controller.presentedViewController as? BottomSheetViewController { bsvc.didTapOrSwipeToDismiss() } } } } struct PaymentSheetFlowControllerPresenter: UIViewRepresentable { @Binding var presented: Bool weak var paymentSheetFlowController: PaymentSheet.FlowController? let action: FlowControllerAction let optionsCompletion: (() -> Void)? let paymentCompletion: ((PaymentSheetResult) -> Void)? func makeCoordinator() -> Coordinator { return Coordinator(parent: self) } func makeUIView(context: Context) -> UIView { return context.coordinator.view } func updateUIView(_ uiView: UIView, context: Context) { context.coordinator.parent = self context.coordinator.presented = presented } class Coordinator { var parent: PaymentSheetFlowControllerPresenter let view = UIView() var presented: Bool { didSet { switch (oldValue, presented) { case (false, false): break case (false, true): guard let viewController = findViewController(for: view) else { parent.presented = false return } presentPaymentSheet(on: viewController) case (true, false): guard let viewController = findViewController(for: view) else { parent.presented = true return } forciblyDismissPaymentSheet(from: viewController) case (true, true): break } } } init(parent: PaymentSheetFlowControllerPresenter) { self.parent = parent self.presented = parent.presented } func presentPaymentSheet(on controller: UIViewController) { let presenter = findViewControllerPresenter(from: controller) switch parent.action { case .confirm: parent.paymentSheetFlowController?.confirm(from: presenter) { (result) in self.parent.presented = false self.parent.paymentCompletion?(result) } case .presentPaymentOptions: parent.paymentSheetFlowController?.presentPaymentOptions(from: presenter) { self.parent.presented = false self.parent.optionsCompletion?() } } } func forciblyDismissPaymentSheet(from controller: UIViewController) { if let bsvc = controller.presentedViewController as? BottomSheetViewController { bsvc.didTapOrSwipeToDismiss() } } } } struct PaymentSheetPresentationModifier: ViewModifier { @Binding var isPresented: Bool let paymentSheet: PaymentSheet let onCompletion: (PaymentSheetResult) -> Void func body(content: Content) -> some View { content.background( PaymentSheetPresenter( presented: $isPresented, paymentSheet: paymentSheet, onCompletion: onCompletion ) ) } } enum FlowControllerAction { case presentPaymentOptions case confirm } struct PaymentSheetFlowControllerPresentationModifier: ViewModifier { @Binding var isPresented: Bool let paymentSheetFlowController: PaymentSheet.FlowController let action: FlowControllerAction let optionsCompletion: (() -> Void)? let paymentCompletion: ((PaymentSheetResult) -> Void)? func body(content: Content) -> some View { content.background( PaymentSheetFlowControllerPresenter( presented: $isPresented, paymentSheetFlowController: paymentSheetFlowController, action: action, optionsCompletion: optionsCompletion, paymentCompletion: paymentCompletion ) ) } } } // MARK: - Helper functions func findViewControllerPresenter(from uiViewController: UIViewController) -> UIViewController { // Note: creating a UIViewController inside here results in a nil window // This is a bit of a hack: We traverse the view hierarchy looking for the most reasonable VC to present from. // A VC hosted within a SwiftUI cell, for example, doesn't have a parent, so we need to find the UIWindow. var presentingViewController: UIViewController = uiViewController.view.window?.rootViewController ?? uiViewController // Find the most-presented UIViewController while let presented = presentingViewController.presentedViewController { presentingViewController = presented } return presentingViewController } func findViewController(for uiView: UIView) -> UIViewController? { if let nextResponder = uiView.next as? UIViewController { return nextResponder } else if let nextResponder = uiView.next as? UIView { return findViewController(for: nextResponder) } else { return nil } }
39.144186
196
0.611157
16c8d5da583a8f80b5d5951b51f8febb2dc58afb
373
// // Generated.swift // CodeGenTemplate // // Created by Akkharawat Chayapiwat on 10/4/18. // Copyright © 2018 Akkharawat Chayapiwat. All rights reserved. // import Foundation protocol AutoViewModelType { } protocol AutoCoordinatorType { } protocol AutoDependencyType { } protocol AutoCoordinatorTargetType { } protocol AutoInitialize { } protocol AutoCaseName { }
20.722222
64
0.761394
387d23793bfd96ad29554548e8676dd2436195bd
1,310
import UIKit import SnapKit final class PlaceholderView: UIView { let imageView = UIImageView() override init(frame: CGRect) { super.init(frame: frame) setup() } @available(*, unavailable) required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) setupColors() } private func setupColors() { backgroundColor = traitCollection.userInterfaceStyle == .dark ? .black : .systemGray6 } private func setup() { backgroundColor = .systemGray6 setupLayout() setupColors() imageView.image = Constants.image imageView.tintColor = .systemGray5 } private func setupLayout() { addSubview(imageView) imageView.snp.makeConstraints { make in make.center .equalToSuperview() make.size .equalTo(Constants.imageDimension) } } } private extension PlaceholderView { enum Constants { static let image = UIImage(systemName: "globe") static let imageDimension: CGFloat = 150 } }
22.982456
91
0.619084
d957a537efbd3d6931c38c5ff87f120aa8b911ee
3,601
import Foundation import azureSwiftRuntime public protocol ComputePoliciesUpdate { var headerParameters: [String: String] { get set } var subscriptionId : String { get set } var resourceGroupName : String { get set } var accountName : String { get set } var computePolicyName : String { get set } var apiVersion : String { get set } var parameters : UpdateComputePolicyParametersProtocol? { get set } func execute(client: RuntimeClient, completionHandler: @escaping (ComputePolicyProtocol?, Error?) -> Void) -> Void ; } extension Commands.ComputePolicies { // Update updates the specified compute policy. internal class UpdateCommand : BaseCommand, ComputePoliciesUpdate { public var subscriptionId : String public var resourceGroupName : String public var accountName : String public var computePolicyName : String public var apiVersion = "2016-11-01" public var parameters : UpdateComputePolicyParametersProtocol? public init(subscriptionId: String, resourceGroupName: String, accountName: String, computePolicyName: String) { self.subscriptionId = subscriptionId self.resourceGroupName = resourceGroupName self.accountName = accountName self.computePolicyName = computePolicyName super.init() self.method = "Patch" self.isLongRunningOperation = false self.path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeAnalytics/accounts/{accountName}/computePolicies/{computePolicyName}" self.headerParameters = ["Content-Type":"application/json; charset=utf-8"] } public override func preCall() { self.pathParameters["{subscriptionId}"] = String(describing: self.subscriptionId) self.pathParameters["{resourceGroupName}"] = String(describing: self.resourceGroupName) self.pathParameters["{accountName}"] = String(describing: self.accountName) self.pathParameters["{computePolicyName}"] = String(describing: self.computePolicyName) self.queryParameters["api-version"] = String(describing: self.apiVersion) self.body = parameters } public override func encodeBody() throws -> Data? { let contentType = "application/json" if let mimeType = MimeType.getType(forStr: contentType) { let encoder = try CoderFactory.encoder(for: mimeType) let encodedValue = try encoder.encode(parameters as? UpdateComputePolicyParametersData?) return encodedValue } throw DecodeError.unknownMimeType } public override func returnFunc(data: Data) throws -> Decodable? { let contentType = "application/json" if let mimeType = MimeType.getType(forStr: contentType) { let decoder = try CoderFactory.decoder(for: mimeType) let result = try decoder.decode(ComputePolicyData?.self, from: data) return result; } throw DecodeError.unknownMimeType } public func execute(client: RuntimeClient, completionHandler: @escaping (ComputePolicyProtocol?, Error?) -> Void) -> Void { client.executeAsync(command: self) { (result: ComputePolicyData?, error: Error?) in completionHandler(result, error) } } } }
48.662162
190
0.645654
f89357ce9fc28c6dfa16d668d20d5400194cfa17
1,035
// // HoomanView.swift // Walkies // // Created by Mayuko Inoue on 9/23/20. // import SwiftUI import Firebase struct HoomanView: View { @ObservedObject var walkiesFetcher = WalkiesFetcher() var body: some View { VStack { HStack { Image("kona_large") Text("kona\n wants\n to walk.").fontWeight(.bold).font(/*@START_MENU_TOKEN@*/.title/*@END_MENU_TOKEN@*/) Spacer() }.frame(height:200).padding() List(walkiesFetcher.walkRequests) { request in HStack { Image(request.walkType?.imageName ?? "kona_0") Text(request.walkType?.mumble ?? "") Spacer() Text(request.timestamp?.timeString() ?? "").font(.caption).foregroundColor(Color.gray) }.frame(height:55) } } } } struct HoomanView_Previews: PreviewProvider { static var previews: some View { HoomanView() } }
25.243902
120
0.529469
e90f8c1bfdafd2c876bba04d617ecc1e1a9a725a
2,250
import UIKit import CoreLocation enum LocationFetchingError: Error { case error(Error) case noErrorMessage } class ZipCodeHelper { private init() {} static func getLatLong(fromZipCode zipCode: String, completionHandler: @escaping (Result<(lat: Double, long: Double), LocationFetchingError>) -> Void) { let geocoder = CLGeocoder() DispatchQueue.global(qos: .userInitiated).async { geocoder.geocodeAddressString(zipCode){(placemarks, error) -> Void in DispatchQueue.main.async { if let placemark = placemarks?.first, let coordinate = placemark.location?.coordinate { completionHandler(.success((coordinate.latitude, coordinate.longitude))) } else { let locationError: LocationFetchingError if let error = error { locationError = .error(error) } else { locationError = .noErrorMessage } completionHandler(.failure(locationError)) } } } } } static func getLatLongName(fromZipCode zipCode: String, completionHandler: @escaping (Result<(lat: Double, long: Double, placeName: String), LocationFetchingError>) -> Void) { let geocoder = CLGeocoder() DispatchQueue.global(qos: .userInitiated).async { geocoder.geocodeAddressString(zipCode){(placemarks, error) -> Void in DispatchQueue.main.async { if let placemark = placemarks?.first, let coordinate = placemark.location?.coordinate, let name = placemark.locality { completionHandler(.success((lat: coordinate.latitude, long: coordinate.longitude, placeName: name))) } else { let locationError: LocationFetchingError if let error = error { locationError = .error(error) } else { locationError = .noErrorMessage } completionHandler(.failure(locationError)) } } } } } }
39.473684
156
0.556889
bf6109dc11d99e9574412f0d1bb4b09917edf745
2,172
/// HTTP class with HTML and JSON functionality /// /// - author: Marc Lavergne <[email protected]> /// - copyright: 2017 Marc Lavergne. All rights reserved. /// - license: MIT import Foundation public class HTTPBackground: NSObject, URLSessionDelegate, URLSessionDataDelegate { public static func demoBackgroundFetch() { guard let url = URL.init(string: "https://jsonplaceholder.typicode.com/posts") else { print("error") return } let uuid = "com.example." + NSUUID().uuidString let params: [AnyHashable: Any] = [ "title": "foo", "body": "bar", "userId": 1 ] guard let body = try? JSONSerialization.data(withJSONObject: params, options: []) else { print("error") return } HTTPBackground().backgroundSession(url, uniqueId: uuid, body: body, delay: Date().addingTimeInterval(30)) } @discardableResult public func backgroundSession(_ url: URL, uniqueId: String, body: Data, delay: Date = Date()) -> URLSessionDataTask { let config = URLSessionConfiguration.background(withIdentifier: uniqueId) config.allowsCellularAccess = true config.timeoutIntervalForRequest = 60 config.timeoutIntervalForResource = 5 * 60 // how many seconds is a session valid (5 mins) config.httpMaximumConnectionsPerHost = 4 config.networkServiceType = .background config.isDiscretionary = false var request = URLRequest(url: url) request.httpMethod = "POST" request.httpBody = body let session = URLSession(configuration: config, delegate: self, delegateQueue: OperationQueue()) let backgroundTask = session.dataTask(with: request) backgroundTask.earliestBeginDate = delay backgroundTask.countOfBytesClientExpectsToSend = Int64(body.count) backgroundTask.countOfBytesClientExpectsToReceive = 1024 backgroundTask.resume() return backgroundTask } public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { print(#function) } }
37.448276
121
0.662983
16662d123287d4be877030701a88e2558c8a9fd3
148
// // Copyright (c) Emarsys on 2021. 10. 26.. // import Foundation @objc public protocol LogLevelProtocol { var level: String { get set } }
14.8
44
0.655405
ff252c9af7f188b042cab5fc237fee1715f89864
825
// Created on 20/01/21. import UIKit import SnapKit import SkeletonView public extension UIView { @objc var isLoading: Bool { get { isSkeletonActive } set { isSkeletonable = newValue newValue ? showAnimatedGradientSkeleton() : hideSkeleton() } } class func spaceView( height: Double? = nil, width: Double? = nil, backgroundColor: UIColor = .clear ) -> UIView { let view = UIView() view.backgroundColor = backgroundColor view.snp.makeConstraints { maker in if let height = height { maker.height.equalTo(height) } if let width = width { maker.width.equalTo(width) } } return view } }
19.186047
70
0.526061
5be8a951ce1bf865d6700f1347df2ca4a4635a35
10,683
// // NumberInputTextField.Swift // Caishen // // Created by Daniel Vancura on 2/9/16. // Copyright © 2016 Prolific Interactive. All rights reserved. // import UIKit /** This kind of text field only allows entering card numbers and provides means to customize the appearance of entered card numbers by changing the card number group separator. */ @IBDesignable open class NumberInputTextField: StylizedTextField { // MARK: - Variables /** The card number that has been entered into this text field. - note: This card number may be incomplete and invalid while the user is entering a card number. Be sure to validate it against a proper card type before assuming it is valid. */ open var cardNumber: Number { let textFieldTextUnformatted = cardNumberFormatter.unformat(cardNumber: text ?? "") return Number(rawValue: textFieldTextUnformatted) } /** */ @IBOutlet open weak var numberInputTextFieldDelegate: NumberInputTextFieldDelegate? /** The string that is used to separate different groups in a card number. */ @IBInspectable open var cardNumberSeparator: String = "-" open override var accessibilityValue: String? { get { // In order to read digits of the card number one by one, return them as "4 1 1 ..." separated by single spaces and commas inbetween groups for pauses var singleDigits: [Character] = [] var lastCharWasReplacedWithComma = false text?.forEach({ if !$0.isNumeric() { if !lastCharWasReplacedWithComma { singleDigits.append(",") lastCharWasReplacedWithComma = true } else { lastCharWasReplacedWithComma = false } } singleDigits.append($0) singleDigits.append(" ") }) return String(singleDigits) + ". " + Localization.CardType.localizedStringWithComment("Description for detected card type.") + ": " + cardTypeRegister.cardType(for: cardNumber).name } set { } } /// Variable to store the text color of this text field. The actual property `textColor` (as inherited from UITextField) will change based on whether or not the entered card number was invalid and may be `invalidInputColor` in this case. In order to always set and retreive the actual text color for this text field, it is saved and retreived to and from this private property. private var _textColor: UIColor? override open var textColor: UIColor? { get { return _textColor } set { /// Just store the text color in `_textColor`. It will be set as soon as input has been entered by setting super.textColor = _textColor. /// This is to avoid overriding `textColor` with `invalidInputColor` when invalid input has been entered. _textColor = newValue } } /** The card type register that holds information about which card types are accepted and which ones are not. */ open var cardTypeRegister: CardTypeRegister = CardTypeRegister.sharedCardTypeRegister /** A card number formatter used to format the input */ private var cardNumberFormatter: CardNumberFormatter { return CardNumberFormatter(cardTypeRegister: cardTypeRegister, separator: cardNumberSeparator) } // MARK: - UITextFieldDelegate open override func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { // Current text in text field, formatted and unformatted: let textFieldTextFormatted = NSString(string: textField.text ?? "") // Text in text field after applying changes, formatted and unformatted: let newTextFormatted = textFieldTextFormatted.replacingCharacters(in: range, with: string) let newTextUnformatted = cardNumberFormatter.unformat(cardNumber: newTextFormatted) // Set the text color to invalid - this will be changed to `validTextColor` later in this method if the input was valid super.textColor = invalidInputColor if !newTextUnformatted.isEmpty && !newTextUnformatted.isNumeric() { return false } let parsedCardNumber = Number(rawValue: newTextUnformatted) let oldValidation = cardTypeRegister.cardType(for: cardNumber).validate(number: cardNumber) let newValidation = cardTypeRegister.cardType(for: parsedCardNumber).validate(number: parsedCardNumber) if !newValidation.contains(.NumberTooLong) { cardNumberFormatter.format(range: range, inTextField: textField, andReplaceWith: string) numberInputTextFieldDelegate?.numberInputTextFieldDidChangeText(self) } else if oldValidation == .Valid { // If the card number is already valid, should call numberInputTextFieldDidComplete on delegate // then set the text color back to normal and return numberInputTextFieldDelegate?.numberInputTextFieldDidComplete(self) super.textColor = _textColor return false } else { notifyNumberInvalidity() } let newLengthComplete = parsedCardNumber.length == cardTypeRegister.cardType(for: parsedCardNumber).maxLength if newLengthComplete && newValidation != .Valid { addNumberInvalidityObserver() } else if newValidation == .Valid { numberInputTextFieldDelegate?.numberInputTextFieldDidComplete(self) } /// If the number is incomplete or valid, assume it's valid and show it in `textColor` /// Also, if the number is of unknown type and the full IIN has not been entered yet, assume it's valid. if (newValidation.contains(.UnknownType) && newTextUnformatted.count <= 6) || newValidation.contains(.NumberIncomplete) || newValidation == .Valid { super.textColor = _textColor } return false } /** Prefills the card number. The entered card number will only be prefilled if it is at least partially valid and will be displayed formatted. - parameter text: The card number which should be displayed in `self`. */ open func prefill(_ text: String) { let unformattedCardNumber = String(text.filter({$0.isNumeric()})) let cardNumber = Number(rawValue: unformattedCardNumber) let type = cardTypeRegister.cardType(for: cardNumber) let numberPartiallyValid = type.checkCardNumberPartiallyValid(cardNumber) == .Valid if numberPartiallyValid { // Set text and apply text color changes if the prefilled card type is unknown self.text = text _ = textField(self, shouldChangeCharactersIn: NSRange(location: 0, length: text.count), replacementString: cardNumber.rawValue) } } // MARK: - Helper functions /** Computes the rect that contains the specified text range within the text field. - precondition: This function will only work, when `textField` is the first responder. If `textField` is not first responder, `textField.beginningOfDocument` will not be initialized and this function will return nil. - parameter range: The range of the text in the text field whose bounds should be detected. - parameter textField: The text field containing the text. - returns: A rect indicating the location and bounds of the text within the text field, or nil, if an invalid range has been entered. */ private func rectFor(range: NSRange, in textField: UITextField) -> CGRect? { guard let rangeStart = textField.position(from: textField.beginningOfDocument, offset: range.location) else { return nil } guard let rangeEnd = textField.position(from: rangeStart, offset: range.length) else { return nil } guard let textRange = textField.textRange(from: rangeStart, to: rangeEnd) else { return nil } return textField.firstRect(for: textRange) } /** - precondition: This function will only work, when `self` is the first responder. If `self` is not first responder, `self.beginningOfDocument` will not be initialized and this function will return nil. - returns: The CGRect in `self` that contains the last group of the card number. */ open func rectForLastGroup() -> CGRect? { guard let lastGroupLength = text?.components(separatedBy: cardNumberFormatter.separator).last?.count else { return nil } guard let textLength = text?.count else { return nil } return rectFor(range: NSMakeRange(textLength - lastGroupLength, lastGroupLength), in: self) } // MARK: Accessibility /** Add an observer to listen to the event of UIAccessibilityAnnouncementDidFinishNotification, and then post an accessibility notification to user that the entered card number is not valid. The reason why can't we just post an accessbility notification is that only the last accessibility notification would be read to users. As each time users input something there will be an accessibility notification from the system which will always replace what we have posted here. Thus we need to listen to the notification from the system first, wait until it is finished, and post ours afterwards. */ private func addNumberInvalidityObserver() { NotificationCenter.default.addObserver(self, selector: #selector(notifyNumberInvalidity), name: NSNotification.Name.UIAccessibilityAnnouncementDidFinish, object: nil) } /** Notify user the entered card number is invalid when accessibility is turned on */ @objc private func notifyNumberInvalidity() { let localizedString = Localization.InvalidCardNumber.localizedStringWithComment("The expiration date entered is not valid") UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, localizedString) NotificationCenter.default.removeObserver(self) } }
46.246753
381
0.658991
e275f6401837b68f28b93facca114034a00dcb59
1,135
// // ViewController.swift // CopyClass // // Created by Tatsuya Tobioka on 2017/11/29. // Copyright © 2017 tnantoka. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. /// [marker1] class User { var name: String init(name: String) { self.name = name } } let user1 = User(name: "スティープ") let user2 = User(name: "ジョニー") var info1 = [ "user1": user1, "user2": user2 ] var info2 = info1 info1["user1"]?.name = "ティム" print("info1") info1.forEach { key, user in print("\(key): \(user.name)") } print("\ninfo2") info2.forEach { key, user in print("\(key): \(user.name)") } /// [marker1] } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
23.163265
80
0.526872
14a7abb70eb0c99234fbc0e30d70c90fd7af5d30
2,990
// // ContentView.swift // Example // // Created by Daniil Manin on 07.10.2021. // Copyright © 2021 Exyte. All rights reserved. // import SwiftUI import ProgressIndicatorView struct ContentView: View { @State private var showProgressIndicator: Bool = true @State private var progress: CGFloat = 0.0 @State private var progressForDefaultSector: CGFloat = 0.0 private let timer = Timer.publish(every: 1 / 5, on: .main, in: .common).autoconnect() var body: some View { GeometryReader { geometry in let size = geometry.size.width / 5 VStack { Spacer() ProgressIndicatorView(isVisible: $showProgressIndicator, type: .bar(progress: $progress, backgroundColor: .gray.opacity(0.25))) .frame(height: 8.0) .foregroundColor(.red) .padding([.bottom, .horizontal], size) ProgressIndicatorView(isVisible: $showProgressIndicator, type: .impulseBar(progress: $progress, backgroundColor: .gray.opacity(0.25))) .frame(height: 8.0) .foregroundColor(.red) .padding([.bottom, .horizontal], size) ProgressIndicatorView(isVisible: $showProgressIndicator, type: .dashBar(progress: $progress, numberOfItems: 8, backgroundColor: .gray.opacity(0.25))) .frame(height: 12.0) .foregroundColor(.red) .padding([.bottom, .horizontal], size) HStack { Spacer() ProgressIndicatorView(isVisible: $showProgressIndicator, type: .default(progress: $progressForDefaultSector)) .foregroundColor(.red) .frame(width: size, height: size) Spacer() ProgressIndicatorView(isVisible: $showProgressIndicator, type: .circle(progress: $progress, lineWidth: 8.0, strokeColor: .red, backgroundColor: .gray.opacity(0.25))) .frame(width: size, height: size) Spacer() } Spacer() } } .onReceive(timer) { _ in switch progress { case ...0.3, 0.4...0.6: progress += 1 / 30 case 0.3...0.4, 0.6...0.9: progress += 1 / 120 case 0.9...0.99: progress = 1 case 1.0...: progress = 0 default: break } if progressForDefaultSector >= 1.5 { progressForDefaultSector = 0 } else { progressForDefaultSector += 1 / 10 } } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
35.176471
185
0.508361
21b8f0dc381ec19bfc76f858f40ba9c724baa768
2,739
// // TernarySearchTree.swift // // // Created by Siddharth Atre on 3/15/16. // // import Foundation public class TernarySearchTree<Element> { var root: TSTNode<Element>? public init() {} // MARK: - Insertion public func insert(data: Element, withKey key: String) -> Bool { return insert(node: &root, withData: data, andKey: key, atIndex: 0) } private func insert(node: inout TSTNode<Element>?, withData data: Element, andKey key: String, atIndex charIndex: Int) -> Bool { //sanity check. if key.characters.count == 0 { return false } //create a new node if necessary. if node == nil { let index = key.index(key.startIndex, offsetBy: charIndex) node = TSTNode<Element>(key: key[index]) } //if current char is less than the current node's char, go left let index = key.index(key.startIndex, offsetBy: charIndex) if key[index] < node!.key { return insert(node: &node!.left, withData: data, andKey: key, atIndex: charIndex) } //if it's greater, go right. else if key[index] > node!.key { return insert(node: &node!.right, withData: data, andKey: key, atIndex: charIndex) } //current char is equal to the current nodes, go middle else { //continue down the middle. if charIndex + 1 < key.characters.count { return insert(node: &node!.middle, withData: data, andKey: key, atIndex: charIndex + 1) } //otherwise, all done. else { node!.data = data node?.hasData = true return true } } } // MARK: - Finding public func find(key: String) -> Element? { return find(node: root, withKey: key, atIndex: 0) } private func find(node: TSTNode<Element>?, withKey key: String, atIndex charIndex: Int) -> Element? { //Given key does not exist in tree. if node == nil { return nil } let index = key.index(key.startIndex, offsetBy: charIndex) //go left if key[index] < node!.key { return find(node: node!.left, withKey: key, atIndex: charIndex) } //go right else if key[index] > node!.key { return find(node: node!.right, withKey: key, atIndex: charIndex) } //go middle else { if charIndex + 1 < key.characters.count { return find(node: node!.middle, withKey: key, atIndex: charIndex + 1) } else { return node!.data } } } }
28.831579
132
0.542169
e46a4449aff2b2aa6912d309e4bd95c663742a2a
1,742
// // DispatchQueue+Cloudinary.swift // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Dispatch import Foundation extension DispatchQueue { static var CLDNUserInteractive: DispatchQueue { return DispatchQueue.global(qos: .userInteractive) } static var CLDNUserInitiated: DispatchQueue { return DispatchQueue.global(qos: .userInitiated) } static var CLDNUtility: DispatchQueue { return DispatchQueue.global(qos: .utility) } static var CLDNBackground: DispatchQueue { return DispatchQueue.global(qos: .background) } func CLDN_after(_ delay: TimeInterval, execute closure: @escaping () -> Void) { asyncAfter(deadline: .now() + delay, execute: closure) } }
47.081081
104
0.752009
1ce2028e69fc25e25621a9fb247372f6f07411a4
2,824
// swift-tools-version:5.0 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "ImageSlideshow", platforms: [ .iOS(.v10), ], products: [ .library( name: "ImageSlideshow", targets: ["ImageSlideshow", "ImageSlideshowSDWebImage"]), // .library( // name: "ImageSlideshow/Alamofire", // targets: ["ImageSlideshowAlamofire"]), // .library( // name: "ImageSlideshow/SDWebImage", // targets: ["ImageSlideshowSDWebImage"]), // .library( // name: "ImageSlideshow/Kingfisher", // targets: ["ImageSlideshowKingfisher"]) ], dependencies: [ // .package(url: "https://github.com/onevcat/Kingfisher.git", from: "5.8.0"), // .package(url: "https://github.com/Alamofire/AlamofireImage.git", from: "4.0.0"), .package(url: "https://github.com/SDWebImage/SDWebImage.git", from: "5.1.0") ], targets: [ .target( name: "ImageSlideshow", path: "ImageSlideshow", sources: [ "Classes/Core/ActivityIndicator.swift", "Classes/Core/FullScreenSlideshowViewController.swift", "Classes/Core/ImageSlideshow.swift", "Classes/Core/ImageSlideshowItem.swift", "Classes/Core/InputSource.swift", "Classes/Core/PageIndicator.swift", "Classes/Core/PageIndicatorPosition.swift", "Classes/Core/SwiftSupport.swift", "Classes/Core/UIImage+AspectFit.swift", "Classes/Core/UIImageView+Tools.swift", "Classes/Core/ZoomAnimatedTransitioning.swift", // "Classes/InputSources/VideoSource.swift", // "Classes/InputSources/SDWebImageSource.swift", "Assets/[email protected]", "Assets/[email protected]", ]), // .target( // name: "ImageSlideshowAlamofire", // dependencies: ["ImageSlideshow", "AlamofireImage"], // path: "ImageSlideshow/Classes/InputSources", // sources: ["AlamofireSource.swift"]), .target( name: "ImageSlideshowSDWebImage", dependencies: ["ImageSlideshow", "SDWebImage"], path: "ImageSlideshow/Classes/InputSources", sources: ["SDWebImageSource.swift", "VideoSource.swift"]), // .target( // name: "ImageSlideshowKingfisher", // dependencies: ["ImageSlideshow", "Kingfisher"], // path: "ImageSlideshow/Classes/InputSources", // sources: ["KingfisherSource.swift"]) ], swiftLanguageVersions: [.v4, .v4_2, .v5] )
41.529412
96
0.575071
e8da81165d510683f7d5b8e6b27cc62fd588f1ac
3,960
// DO NOT EDIT. // swift-format-ignore-file // // Generated by the Swift generator plugin for the protocol buffer compiler. // Source: ScheduleSign.proto // // For information on using the generated types, please see the documentation: // https://github.com/apple/swift-protobuf/ import Foundation import SwiftProtobuf // If the compiler emits an error on this type, it is because this file // was generated by a version of the `protoc` Swift plug-in that is // incompatible with the version of SwiftProtobuf to which you are linking. // Please ensure that you are building against the same version of the API // that was used to generate this file. fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck { struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {} typealias Version = _2 } /// ///Adds zero or more signing keys to a schedule. If the resulting set of signing keys satisfy the scheduled ///transaction's signing requirements, it will be executed immediately after the triggering <tt>ScheduleSign</tt>. /// ///Upon <tt>SUCCESS</tt>, the receipt includes the <tt>scheduledTransactionID</tt> to use to query for the ///record of the scheduled transaction's execution (if it occurs). /// ///Other notable response codes include <tt>INVALID_SCHEDULE_ID</tt>, <tt>SCHEDULE_WAS_DELETD</tt>, ///<tt>INVALID_ACCOUNT_ID</tt>, <tt>UNRESOLVABLE_REQUIRED_SIGNERS</tt>, <tt>SOME_SIGNATURES_WERE_INVALID</tt>, ///and <tt>NO_NEW_VALID_SIGNATURES</tt>. For more information please see the section of this ///documentation on the <tt>ResponseCode</tt> enum. public struct Proto_ScheduleSignTransactionBody { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. /// The id of the schedule to add signing keys to public var scheduleID: Proto_ScheduleID { get {return _scheduleID ?? Proto_ScheduleID()} set {_scheduleID = newValue} } /// Returns true if `scheduleID` has been explicitly set. public var hasScheduleID: Bool {return self._scheduleID != nil} /// Clears the value of `scheduleID`. Subsequent reads from it will return its default value. public mutating func clearScheduleID() {self._scheduleID = nil} public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} fileprivate var _scheduleID: Proto_ScheduleID? = nil } // MARK: - Code below here is support for the SwiftProtobuf runtime. fileprivate let _protobuf_package = "proto" extension Proto_ScheduleSignTransactionBody: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".ScheduleSignTransactionBody" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "scheduleID"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularMessageField(value: &self._scheduleID) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if let v = self._scheduleID { try visitor.visitSingularMessageField(value: v, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Proto_ScheduleSignTransactionBody, rhs: Proto_ScheduleSignTransactionBody) -> Bool { if lhs._scheduleID != rhs._scheduleID {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } }
43.516484
145
0.752525
d5b25c513c8e1e86613751270c0022b95b70d368
259
extension String{ internal func padWith(_ char: Character, for length: Int) -> String{ if self.count >= length{ return self } let diff = length - self.count let padding = [Character].init(repeating: char, count: diff) return padding + self } }
23.545455
69
0.683398
e0431c73fbebc6360051ed00816804b41fb7c347
28,963
// // SWXMLHash+TypeConversion.swift // SWXMLHash // // Copyright (c) 2016 Maciek Grzybowskio // // 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. // // swiftlint:disable line_length // swiftlint:disable file_length import Foundation // MARK: - XMLIndexerDeserializable /// Provides XMLIndexer deserialization / type transformation support protocol XMLIndexerDeserializable { /// Method for deserializing elements from XMLIndexer static func deserialize(_ element: XMLIndexer) throws -> Self } /// Provides XMLIndexer deserialization / type transformation support extension XMLIndexerDeserializable { /** A default implementation that will throw an error if it is called - parameters: - element: the XMLIndexer to be deserialized - throws: an XMLDeserializationError.implementationIsMissing if no implementation is found - returns: this won't ever return because of the error being thrown */ static func deserialize(_ element: XMLIndexer) throws -> Self { throw XMLDeserializationError.implementationIsMissing( method: "XMLIndexerDeserializable.deserialize(element: XMLIndexer)") } } // MARK: - XMLElementDeserializable /// Provides XMLElement deserialization / type transformation support protocol XMLElementDeserializable { /// Method for deserializing elements from XMLElement static func deserialize(_ element: XMLElement) throws -> Self } /// Provides XMLElement deserialization / type transformation support extension XMLElementDeserializable { /** A default implementation that will throw an error if it is called - parameters: - element: the XMLElement to be deserialized - throws: an XMLDeserializationError.implementationIsMissing if no implementation is found - returns: this won't ever return because of the error being thrown */ static func deserialize(_ element: XMLElement) throws -> Self { throw XMLDeserializationError.implementationIsMissing( method: "XMLElementDeserializable.deserialize(element: XMLElement)") } } // MARK: - XMLAttributeDeserializable /// Provides XMLAttribute deserialization / type transformation support protocol XMLAttributeDeserializable { static func deserialize(_ attribute: XMLAttribute) throws -> Self } /// Provides XMLAttribute deserialization / type transformation support extension XMLAttributeDeserializable { /** A default implementation that will throw an error if it is called - parameters: - attribute: The XMLAttribute to be deserialized - throws: an XMLDeserializationError.implementationIsMissing if no implementation is found - returns: this won't ever return because of the error being thrown */ static func deserialize(attribute: XMLAttribute) throws -> Self { throw XMLDeserializationError.implementationIsMissing( method: "XMLAttributeDeserializable(element: XMLAttribute)") } } // MARK: - XMLIndexer Extensions extension XMLIndexer { // MARK: - XMLAttributeDeserializable /** Attempts to deserialize the value of the specified attribute of the current XMLIndexer element to `T` - parameter attr: The attribute to deserialize - throws: an XMLDeserializationError if there is a problem with deserialization - returns: The deserialized `T` value */ func value<T: XMLAttributeDeserializable>(ofAttribute attr: String) throws -> T { switch self { case .element(let element): return try element.value(ofAttribute: attr) case .stream(let opStream): return try opStream.findElements().value(ofAttribute: attr) default: throw XMLDeserializationError.nodeIsInvalid(node: self) } } /** Attempts to deserialize the value of the specified attribute of the current XMLIndexer element to `T?` - parameter attr: The attribute to deserialize - returns: The deserialized `T?` value, or nil if the attribute does not exist */ func value<T: XMLAttributeDeserializable>(ofAttribute attr: String) -> T? { switch self { case .element(let element): return element.value(ofAttribute: attr) case .stream(let opStream): return opStream.findElements().value(ofAttribute: attr) default: return nil } } /** Attempts to deserialize the value of the specified attribute of the current XMLIndexer element to `[T]` - parameter attr: The attribute to deserialize - throws: an XMLDeserializationError if there is a problem with deserialization - returns: The deserialized `[T]` value */ func value<T: XMLAttributeDeserializable>(ofAttribute attr: String) throws -> [T] { switch self { case .list(let elements): return try elements.map { try $0.value(ofAttribute: attr) } case .element(let element): return try [element].map { try $0.value(ofAttribute: attr) } case .stream(let opStream): return try opStream.findElements().value(ofAttribute: attr) default: throw XMLDeserializationError.nodeIsInvalid(node: self) } } /** Attempts to deserialize the value of the specified attribute of the current XMLIndexer element to `[T]?` - parameter attr: The attribute to deserialize - throws: an XMLDeserializationError if there is a problem with deserialization - returns: The deserialized `[T]?` value */ func value<T: XMLAttributeDeserializable>(ofAttribute attr: String) throws -> [T]? { switch self { case .list(let elements): return try elements.map { try $0.value(ofAttribute: attr) } case .element(let element): return try [element].map { try $0.value(ofAttribute: attr) } case .stream(let opStream): return try opStream.findElements().value(ofAttribute: attr) default: return nil } } /** Attempts to deserialize the value of the specified attribute of the current XMLIndexer element to `[T?]` - parameter attr: The attribute to deserialize - throws: an XMLDeserializationError if there is a problem with deserialization - returns: The deserialized `[T?]` value */ func value<T: XMLAttributeDeserializable>(ofAttribute attr: String) throws -> [T?] { switch self { case .list(let elements): return elements.map { $0.value(ofAttribute: attr) } case .element(let element): return [element].map { $0.value(ofAttribute: attr) } case .stream(let opStream): return try opStream.findElements().value(ofAttribute: attr) default: throw XMLDeserializationError.nodeIsInvalid(node: self) } } // MARK: - XMLElementDeserializable /** Attempts to deserialize the current XMLElement element to `T` - throws: an XMLDeserializationError.nodeIsInvalid if the current indexed level isn't an Element - returns: the deserialized `T` value */ func value<T: XMLElementDeserializable>() throws -> T { switch self { case .element(let element): return try T.deserialize(element) case .stream(let opStream): return try opStream.findElements().value() default: throw XMLDeserializationError.nodeIsInvalid(node: self) } } /** Attempts to deserialize the current XMLElement element to `T?` - returns: the deserialized `T?` value - throws: an XMLDeserializationError is there is a problem with deserialization */ func value<T: XMLElementDeserializable>() throws -> T? { switch self { case .element(let element): return try T.deserialize(element) case .stream(let opStream): return try opStream.findElements().value() default: return nil } } /** Attempts to deserialize the current XMLElement element to `[T]` - returns: the deserialized `[T]` value - throws: an XMLDeserializationError is there is a problem with deserialization */ func value<T: XMLElementDeserializable>() throws -> [T] { switch self { case .list(let elements): return try elements.map { try T.deserialize($0) } case .element(let element): return try [element].map { try T.deserialize($0) } case .stream(let opStream): return try opStream.findElements().value() default: return [] } } /** Attempts to deserialize the current XMLElement element to `[T]?` - returns: the deserialized `[T]?` value - throws: an XMLDeserializationError is there is a problem with deserialization */ func value<T: XMLElementDeserializable>() throws -> [T]? { switch self { case .list(let elements): return try elements.map { try T.deserialize($0) } case .element(let element): return try [element].map { try T.deserialize($0) } case .stream(let opStream): return try opStream.findElements().value() default: return nil } } /** Attempts to deserialize the current XMLElement element to `[T?]` - returns: the deserialized `[T?]` value - throws: an XMLDeserializationError is there is a problem with deserialization */ func value<T: XMLElementDeserializable>() throws -> [T?] { switch self { case .list(let elements): return try elements.map { try T.deserialize($0) } case .element(let element): return try [element].map { try T.deserialize($0) } case .stream(let opStream): return try opStream.findElements().value() default: return [] } } // MARK: - XMLIndexerDeserializable /** Attempts to deserialize the current XMLIndexer element to `T` - returns: the deserialized `T` value - throws: an XMLDeserializationError is there is a problem with deserialization */ func value<T: XMLIndexerDeserializable>() throws -> T { switch self { case .element: return try T.deserialize(self) case .stream(let opStream): return try opStream.findElements().value() default: throw XMLDeserializationError.nodeIsInvalid(node: self) } } /** Attempts to deserialize the current XMLIndexer element to `T?` - returns: the deserialized `T?` value - throws: an XMLDeserializationError is there is a problem with deserialization */ func value<T: XMLIndexerDeserializable>() throws -> T? { switch self { case .element: return try T.deserialize(self) case .stream(let opStream): return try opStream.findElements().value() default: return nil } } /** Attempts to deserialize the current XMLIndexer element to `[T]` - returns: the deserialized `[T]` value - throws: an XMLDeserializationError is there is a problem with deserialization */ func value<T>() throws -> [T] where T: XMLIndexerDeserializable { switch self { case .list(let elements): return try elements.map { try T.deserialize( XMLIndexer($0) ) } case .element(let element): return try [element].map { try T.deserialize( XMLIndexer($0) ) } case .stream(let opStream): return try opStream.findElements().value() default: throw XMLDeserializationError.nodeIsInvalid(node: self) } } /** Attempts to deserialize the current XMLIndexer element to `[T]?` - returns: the deserialized `[T]?` value - throws: an XMLDeserializationError is there is a problem with deserialization */ func value<T: XMLIndexerDeserializable>() throws -> [T]? { switch self { case .list(let elements): return try elements.map { try T.deserialize( XMLIndexer($0) ) } case .element(let element): return try [element].map { try T.deserialize( XMLIndexer($0) ) } case .stream(let opStream): return try opStream.findElements().value() default: return nil } } /** Attempts to deserialize the current XMLIndexer element to `[T?]` - returns: the deserialized `[T?]` value - throws: an XMLDeserializationError is there is a problem with deserialization */ func value<T: XMLIndexerDeserializable>() throws -> [T?] { switch self { case .list(let elements): return try elements.map { try T.deserialize( XMLIndexer($0) ) } case .element(let element): return try [element].map { try T.deserialize( XMLIndexer($0) ) } case .stream(let opStream): return try opStream.findElements().value() default: throw XMLDeserializationError.nodeIsInvalid(node: self) } } } // MARK: - XMLAttributeDeserializable String RawRepresentable /*: Provides XMLIndexer XMLAttributeDeserializable deserialization from String backed RawRepresentables Added by [PeeJWeeJ](https://github.com/PeeJWeeJ) */ extension XMLIndexer { /** Attempts to deserialize the value of the specified attribute of the current XMLIndexer element to `T` using a String backed RawRepresentable (E.g. `String` backed `enum` cases) - Note: Convenience for value(ofAttribute: String) - parameter attr: The attribute to deserialize - throws: an XMLDeserializationError if there is a problem with deserialization - returns: The deserialized `T` value */ func value<T: XMLAttributeDeserializable, A: RawRepresentable>(ofAttribute attr: A) throws -> T where A.RawValue == String { try value(ofAttribute: attr.rawValue) } /** Attempts to deserialize the value of the specified attribute of the current XMLIndexer element to `T?` using a String backed RawRepresentable (E.g. `String` backed `enum` cases) - Note: Convenience for value(ofAttribute: String) - parameter attr: The attribute to deserialize - returns: The deserialized `T?` value, or nil if the attribute does not exist */ func value<T: XMLAttributeDeserializable, A: RawRepresentable>(ofAttribute attr: A) -> T? where A.RawValue == String { value(ofAttribute: attr.rawValue) } /** Attempts to deserialize the value of the specified attribute of the current XMLIndexer element to `[T]` using a String backed RawRepresentable (E.g. `String` backed `enum` cases) - Note: Convenience for value(ofAttribute: String) - parameter attr: The attribute to deserialize - throws: an XMLDeserializationError if there is a problem with deserialization - returns: The deserialized `[T]` value */ func value<T: XMLAttributeDeserializable, A: RawRepresentable>(ofAttribute attr: A) throws -> [T] where A.RawValue == String { try value(ofAttribute: attr.rawValue) } /** Attempts to deserialize the value of the specified attribute of the current XMLIndexer element to `[T]?` using a String backed RawRepresentable (E.g. `String` backed `enum` cases) - Note: Convenience for value(ofAttribute: String) - parameter attr: The attribute to deserialize - throws: an XMLDeserializationError if there is a problem with deserialization - returns: The deserialized `[T]?` value */ func value<T: XMLAttributeDeserializable, A: RawRepresentable>(ofAttribute attr: A) throws -> [T]? where A.RawValue == String { try value(ofAttribute: attr.rawValue) } /** Attempts to deserialize the value of the specified attribute of the current XMLIndexer element to `[T?]` using a String backed RawRepresentable (E.g. `String` backed `enum` cases) - Note: Convenience for value(ofAttribute: String) - parameter attr: The attribute to deserialize - throws: an XMLDeserializationError if there is a problem with deserialization - returns: The deserialized `[T?]` value */ func value<T: XMLAttributeDeserializable, A: RawRepresentable>(ofAttribute attr: A) throws -> [T?] where A.RawValue == String { try value(ofAttribute: attr.rawValue) } } // MARK: - XMLElement Extensions extension XMLElement { /** Attempts to deserialize the specified attribute of the current XMLElement to `T` - parameter attr: The attribute to deserialize - throws: an XMLDeserializationError if there is a problem with deserialization - returns: The deserialized `T` value */ func value<T: XMLAttributeDeserializable>(ofAttribute attr: String) throws -> T { if let attr = self.attribute(by: attr) { return try T.deserialize(attr) } else { throw XMLDeserializationError.attributeDoesNotExist(element: self, attribute: attr) } } /** Attempts to deserialize the specified attribute of the current XMLElement to `T?` - parameter attr: The attribute to deserialize - returns: The deserialized `T?` value, or nil if the attribute does not exist. */ func value<T: XMLAttributeDeserializable>(ofAttribute attr: String) -> T? { if let attr = self.attribute(by: attr) { return try? T.deserialize(attr) } else { return nil } } /** Gets the text associated with this element, or throws an exception if the text is empty - throws: XMLDeserializationError.nodeHasNoValue if the element text is empty - returns: The element text */ internal func nonEmptyTextOrThrow() throws -> String { let textVal = text if !textVal.isEmpty { return textVal } throw XMLDeserializationError.nodeHasNoValue } } // MARK: String RawRepresentable /*: Provides XMLElement XMLAttributeDeserializable deserialization from String backed RawRepresentables Added by [PeeJWeeJ](https://github.com/PeeJWeeJ) */ extension XMLElement { /** Attempts to deserialize the specified attribute of the current XMLElement to `T` using a String backed RawRepresentable (E.g. `String` backed `enum` cases) - Note: Convenience for value(ofAttribute: String) - parameter attr: The attribute to deserialize - throws: an XMLDeserializationError if there is a problem with deserialization - returns: The deserialized `T` value */ func value<T: XMLAttributeDeserializable, A: RawRepresentable>(ofAttribute attr: A) throws -> T where A.RawValue == String { try value(ofAttribute: attr.rawValue) } /** Attempts to deserialize the specified attribute of the current XMLElement to `T?` using a String backed RawRepresentable (E.g. `String` backed `enum` cases) - Note: Convenience for value(ofAttribute: String) - parameter attr: The attribute to deserialize - returns: The deserialized `T?` value, or nil if the attribute does not exist. */ func value<T: XMLAttributeDeserializable, A: RawRepresentable>(ofAttribute attr: A) -> T? where A.RawValue == String { value(ofAttribute: attr.rawValue) } } // MARK: - XMLDeserializationError /// The error that is thrown if there is a problem with deserialization enum XMLDeserializationError: Error, CustomStringConvertible { case implementationIsMissing(method: String) case nodeIsInvalid(node: XMLIndexer) case nodeHasNoValue case typeConversionFailed(type: String, element: XMLElement) case attributeDoesNotExist(element: XMLElement, attribute: String) case attributeDeserializationFailed(type: String, attribute: XMLAttribute) // swiftlint:disable identifier_name @available(*, unavailable, renamed: "implementationIsMissing(method:)") static func ImplementationIsMissing(method: String) -> XMLDeserializationError { fatalError("unavailable") } @available(*, unavailable, renamed: "nodeHasNoValue(_:)") static func NodeHasNoValue(_: IndexOps) -> XMLDeserializationError { fatalError("unavailable") } @available(*, unavailable, renamed: "typeConversionFailed(_:)") static func TypeConversionFailed(_: IndexingError) -> XMLDeserializationError { fatalError("unavailable") } @available(*, unavailable, renamed: "attributeDoesNotExist(_:_:)") static func AttributeDoesNotExist(_ attr: String, _ value: String) throws -> XMLDeserializationError { fatalError("unavailable") } @available(*, unavailable, renamed: "attributeDeserializationFailed(_:_:)") static func AttributeDeserializationFailed(_ attr: String, _ value: String) throws -> XMLDeserializationError { fatalError("unavailable") } // swiftlint:enable identifier_name /// The text description for the error thrown var description: String { switch self { case .implementationIsMissing(let method): return "This deserialization method is not implemented: \(method)" case .nodeIsInvalid(let node): return "This node is invalid: \(node)" case .nodeHasNoValue: return "This node is empty" case let .typeConversionFailed(type, node): return "Can't convert node \(node) to value of type \(type)" case let .attributeDoesNotExist(element, attribute): return "Element \(element) does not contain attribute: \(attribute)" case let .attributeDeserializationFailed(type, attribute): return "Can't convert attribute \(attribute) to value of type \(type)" } } } // MARK: - Common types deserialization extension String: XMLElementDeserializable, XMLAttributeDeserializable { /** Attempts to deserialize XML element content to a String - parameters: - element: the XMLElement to be deserialized - throws: an XMLDeserializationError.typeConversionFailed if the element cannot be deserialized - returns: the deserialized String value */ static func deserialize(_ element: XMLElement) -> String { element.text } /** Attempts to deserialize XML Attribute content to a String - parameter attribute: the XMLAttribute to be deserialized - returns: the deserialized String value */ static func deserialize(_ attribute: XMLAttribute) -> String { attribute.text } } extension Int: XMLElementDeserializable, XMLAttributeDeserializable { /** Attempts to deserialize XML element content to a Int - parameters: - element: the XMLElement to be deserialized - throws: an XMLDeserializationError.typeConversionFailed if the element cannot be deserialized - returns: the deserialized Int value */ static func deserialize(_ element: XMLElement) throws -> Int { guard let value = Int(try element.nonEmptyTextOrThrow()) else { throw XMLDeserializationError.typeConversionFailed(type: "Int", element: element) } return value } /** Attempts to deserialize XML attribute content to an Int - parameter attribute: The XMLAttribute to be deserialized - throws: an XMLDeserializationError.attributeDeserializationFailed if the attribute cannot be deserialized - returns: the deserialized Int value */ static func deserialize(_ attribute: XMLAttribute) throws -> Int { guard let value = Int(attribute.text) else { throw XMLDeserializationError.attributeDeserializationFailed( type: "Int", attribute: attribute) } return value } } extension Double: XMLElementDeserializable, XMLAttributeDeserializable { /** Attempts to deserialize XML element content to a Double - parameters: - element: the XMLElement to be deserialized - throws: an XMLDeserializationError.typeConversionFailed if the element cannot be deserialized - returns: the deserialized Double value */ static func deserialize(_ element: XMLElement) throws -> Double { guard let value = Double(try element.nonEmptyTextOrThrow()) else { throw XMLDeserializationError.typeConversionFailed(type: "Double", element: element) } return value } /** Attempts to deserialize XML attribute content to a Double - parameter attribute: The XMLAttribute to be deserialized - throws: an XMLDeserializationError.attributeDeserializationFailed if the attribute cannot be deserialized - returns: the deserialized Double value */ static func deserialize(_ attribute: XMLAttribute) throws -> Double { guard let value = Double(attribute.text) else { throw XMLDeserializationError.attributeDeserializationFailed( type: "Double", attribute: attribute) } return value } } extension Float: XMLElementDeserializable, XMLAttributeDeserializable { /** Attempts to deserialize XML element content to a Float - parameters: - element: the XMLElement to be deserialized - throws: an XMLDeserializationError.typeConversionFailed if the element cannot be deserialized - returns: the deserialized Float value */ static func deserialize(_ element: XMLElement) throws -> Float { guard let value = Float(try element.nonEmptyTextOrThrow()) else { throw XMLDeserializationError.typeConversionFailed(type: "Float", element: element) } return value } /** Attempts to deserialize XML attribute content to a Float - parameter attribute: The XMLAttribute to be deserialized - throws: an XMLDeserializationError.attributeDeserializationFailed if the attribute cannot be deserialized - returns: the deserialized Float value */ static func deserialize(_ attribute: XMLAttribute) throws -> Float { guard let value = Float(attribute.text) else { throw XMLDeserializationError.attributeDeserializationFailed( type: "Float", attribute: attribute) } return value } } extension Bool: XMLElementDeserializable, XMLAttributeDeserializable { // swiftlint:disable line_length /** Attempts to deserialize XML element content to a Bool. This uses NSString's 'boolValue' described [here](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/#//apple_ref/occ/instp/NSString/boolValue) - parameters: - element: the XMLElement to be deserialized - throws: an XMLDeserializationError.typeConversionFailed if the element cannot be deserialized - returns: the deserialized Bool value */ static func deserialize(_ element: XMLElement) throws -> Bool { let value = Bool(NSString(string: try element.nonEmptyTextOrThrow()).boolValue) return value } /** Attempts to deserialize XML attribute content to a Bool. This uses NSString's 'boolValue' described [here](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/#//apple_ref/occ/instp/NSString/boolValue) - parameter attribute: The XMLAttribute to be deserialized - throws: an XMLDeserializationError.attributeDeserializationFailed if the attribute cannot be deserialized - returns: the deserialized Bool value */ static func deserialize(_ attribute: XMLAttribute) throws -> Bool { let value = Bool(NSString(string: attribute.text).boolValue) return value } // swiftlint:enable line_length }
37.810705
168
0.677381
b96853515e5ca61e722dbc82b5939a87c77b4ae2
3,541
// // FireButtonAnimationSettingsViewController.swift // DuckDuckGo // // Copyright © 2020 DuckDuckGo. 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 UIKit import Core class FireButtonAnimationSettingsViewController: UITableViewController { private lazy var appSettings = AppDependencyProvider.shared.appSettings private lazy var availableAnimations = FireButtonAnimationType.allCases private var animator: FireButtonAnimator = FireButtonAnimator(appSettings: AppUserDefaults()) override func viewDidLoad() { super.viewDidLoad() applyTheme(ThemeManager.shared.currentTheme) } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return availableAnimations.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { return tableView.dequeueReusableCell(withIdentifier: "FireAnimationTypeCell", for: indexPath) } override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { guard let cell = cell as? FireAnimationTypeCell else { fatalError("Expected FireAnimationTypeCell") } let theme = ThemeManager.shared.currentTheme cell.backgroundColor = theme.tableCellBackgroundColor cell.setHighlightedStateBackgroundColor(theme.tableCellHighlightedBackgroundColor) // Checkmark color cell.tintColor = theme.buttonTintColor cell.nameLabel.textColor = theme.tableCellTextColor let animationType = availableAnimations[indexPath.row] cell.name = animationType.descriptionText cell.accessoryType = animationType == appSettings.currentFireButtonAnimation ? .checkmark : .none } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let type = availableAnimations[indexPath.row] appSettings.currentFireButtonAnimation = type NotificationCenter.default.post(name: AppUserDefaults.Notifications.currentFireButtonAnimationChange, object: self) tableView.reloadData() animator.animate { // no op } onTransitionCompleted: { // no op } completion: { // no op } } } class FireAnimationTypeCell: UITableViewCell { @IBOutlet weak var nameLabel: UILabel! var name: String? { get { return nameLabel.text } set { nameLabel.text = newValue } } } extension FireButtonAnimationSettingsViewController: Themable { func decorate(with theme: Theme) { tableView.backgroundColor = theme.backgroundColor tableView.separatorColor = theme.tableCellSeparatorColor tableView.reloadData() } }
33.093458
123
0.695849
f95e88923d8bb63451a36f85e3bf3c44b0892206
11,009
// // KeyboardAutoNavigator.swift // KeyboardSupport-iOS // // Created by John Davis on 12/3/18. // Copyright © 2018 Bottle Rocket. All rights reserved. // import UIKit /// Contains callbacks for `KeyboardAutoNavigator` navigation events. public protocol KeyboardAutoNavigatorDelegate: class { func keyboardAutoNavigatorDidTapBack(_ navigator: KeyboardAutoNavigator) func keyboardAutoNavigatorDidTapNext(_ navigator: KeyboardAutoNavigator) func keyboardAutoNavigatorDidTapDone(_ navigator: KeyboardAutoNavigator) } /// Handles navigating between text fields in a containing view hierarchy. open class KeyboardAutoNavigator: KeyboardNavigatorBase { /// AutoPilot is a collection of static functions that enable navigating between `UITextInputViews` in a view hierarchy public enum AutoPilot { /// Returns the "next" `UITextInputView` from the provided view within the provided container /// The next view is found in a left-to-right, top-to-bottom fashion /// /// - Parameters: /// - source: `UITextInputView` to find the next field from /// - container: Optional form container. If nil, the top-level container of the source will be determined and used. /// - Returns: The next `UITextInputView` from the source, or nil if one could not be found. public static func nextField(from source: UITextInputView, in container: UIView?) -> UITextInputView? { let fields = sortedFields(around: source, in: container) guard let currentFieldIndex = fields.firstIndex(where: { $0 == source }) else { return nil } let nextIndex = min(currentFieldIndex + 1, fields.count - 1) // Add to index or max out let nextField = fields[nextIndex] return (nextField as UIView) != (source as UIView) ? nextField : nil } /// Returns the "previous" `UITextInputView` from the provided view. /// The previous view is found in a right-to-left, bottom-to-top fashion /// /// - Parameters: /// - source: `UITextInputView` to find the previous field from /// - container: Optional form container. If nil, the top-level container of the source will be determined and used. /// - Returns: The previous `UITextInputView` from the source, or nil if one could not be found. public static func previousField(from source: UITextInputView, in container: UIView?) -> UITextInputView? { let fields = sortedFields(around: source, in: container) guard let currentFieldIndex = fields.firstIndex(where: { $0 == source }) else { return nil } let previousIndex = max(currentFieldIndex - 1, 0) // Subtract from index, or bottom out at zero let previousField = fields[previousIndex] return (previousField as UIView) != (source as UIView) ? previousField : nil } /// Indicates if a following `UITextInputView` from the provided view exists. /// /// - Parameters: /// - source: `UITextInputView` to find the next field from /// - container: Optional form container. If nil, the top-level container of the source will be determined and used. /// - Returns: True if there is a next field. Otherwise false. public static func hasNextField(from source: UITextInputView, in container: UIView?) -> Bool { return nextField(from: source, in: container) != nil } /// Indicates if a preceding `UITextInputView` from the provided view exists. /// /// - Parameters: /// - source: `UITextInputView` to find the previous field from /// - container: Optional form container. If nil, the top-level container of the source will be determined and used. /// - Returns: True if there is a previous field. Otherwise false. public static func hasPreviousField(from source: UITextInputView, in container: UIView?) -> Bool { return previousField(from: source, in: container) != nil } private static func sortedFields(around source: UITextInputView, in container: UIView?) -> [UITextInputView] { let container = container ?? source.topLevelContainer return container.textInputViews.sortedByPosition(in: container) } } // MARK: - Properties private var currentTextInputView: UITextInputView? { willSet { guard let currentTextField = currentTextInputView else { return } if let toolbar = currentTextField.inputAccessoryView as? KeyboardToolbar { toolbar.keyboardAccessoryDelegate = nil } if let control = currentTextField as? UIControl { control.removeTarget(self, action: #selector(textFieldEditingDidEndOnExit(_:)), for: UIControl.Event.editingDidEndOnExit) } } } /// Containing view of text inputs that can be navigated by the AutoNavigator instance private var containerView: UIView /// Delegate that will be informed of navigation tap events weak open var delegate: KeyboardAutoNavigatorDelegate? // MARK: - Init /// Initializes a `KeyboardAutoNavigator` /// /// - Parameters: /// - containerView: Containing view of text inputs that can be navigated by the AutoNavigator instance /// - defaultToolbar: Default toolbar to be populated on a textInput when editing begins. If that input implements `KeyboardToolbarProviding` that input's toolbar will be used instead. /// - returnKeyNavigationEnabled: If enabled, the auto navigator will add itself as a target to a `UITextField`'s textFieldEditingDidEndOnExit action and advance to the next field when the return key is tapped. public init(containerView: UIView, defaultToolbar: NavigatingKeyboardAccessoryView? = nil, returnKeyNavigationEnabled: Bool = true) { self.containerView = containerView super.init(keyboardToolbar: defaultToolbar, returnKeyNavigationEnabled: returnKeyNavigationEnabled) NotificationCenter.default.addObserver(self, selector: #selector(textEditingDidBegin(_:)), name: UITextField.textDidBeginEditingNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(textEditingDidBegin(_:)), name: UITextView.textDidBeginEditingNotification, object: nil) } deinit { NotificationCenter.default.removeObserver(self, name: UITextField.textDidBeginEditingNotification, object: nil) NotificationCenter.default.removeObserver(self, name: UITextView.textDidBeginEditingNotification, object: nil) } public func refreshCurrentToolbarButtonStates() { guard let currentTextInput = currentTextInputView, let currentToolbar = currentTextInputView?.inputAccessoryView as? NavigatingKeyboardAccessory else { return } let hasNext = AutoPilot.hasNextField(from: currentTextInput, in: containerView) let hasPrevious = AutoPilot.hasPreviousField(from: currentTextInput, in: containerView) if !hasNext && !hasPrevious { currentToolbar.setNextAndBackButtonsHidden(true) } else { currentToolbar.setNextAndBackButtonsHidden(false) currentToolbar.backButton?.isEnabled = hasPrevious currentToolbar.nextButton?.isEnabled = hasNext } } } // MARK: - UI Event Handlers extension KeyboardAutoNavigator { @objc private func textEditingDidBegin(_ notification: Notification) { guard let inputView = notification.object as? UITextInputView, inputView.isDescendant(of: containerView) else { return } currentTextInputView = inputView if returnKeyNavigationEnabled, let controlInput = currentTextInputView as? UIControl { controlInput.addTarget(self, action: #selector(textFieldEditingDidEndOnExit(_:)), for: UIControl.Event.editingDidEndOnExit) } applyToolbarToTextInput(inputView) // There's a chance that the TextInput gaining first responder will trigger a containing scroll view to scroll new textfields into view. // We want to try to refresh our toolbar buttons after the scrollview has settled so those new views are taken into consideration. Using // async here is a "best effort" approach. If your app has an opportunity to call this method at a more concrete time, such as in // ScrollViewDidEndDragging, or ScrollViewDidEndDecelerating, do so for the best results. DispatchQueue.main.async { self.refreshCurrentToolbarButtonStates() } } @objc private func textFieldEditingDidEndOnExit(_ sender: UITextInputView) { if returnKeyNavigationEnabled { AutoPilot.nextField(from: sender, in: containerView)?.becomeFirstResponder() } } } // MARK: - Helpers extension KeyboardAutoNavigator { private func applyToolbarToTextInput(_ textInput: UITextInputView) { let toolbar = (textInput as? KeyboardToolbarProviding)?.keyboardToolbar ?? keyboardToolbar toolbar?.keyboardAccessoryDelegate = self if let textInput = textInput as? UITextField { textInput.inputAccessoryView = toolbar } else if let textInput = textInput as? UITextView { textInput.inputAccessoryView = toolbar // UITextView does not display its toolbar if it's set via a textDidBeginEditingNotification handler. Force a reload of the input views to make it display. textInput.reloadInputViews() } } } // MARK: - KeyboardAccessoryDelegate extension KeyboardAutoNavigator: KeyboardAccessoryDelegate { private func didTapBack() { defer { delegate?.keyboardAutoNavigatorDidTapBack(self) } guard let currentTextField = currentTextInputView else { return } AutoPilot.previousField(from: currentTextField, in: containerView)?.becomeFirstResponder() } private func didTapNext() { defer { delegate?.keyboardAutoNavigatorDidTapNext(self) } guard let currentTextField = currentTextInputView else { return } AutoPilot.nextField(from: currentTextField, in: containerView)?.becomeFirstResponder() } private func didTapDone() { currentTextInputView?.resignFirstResponder() delegate?.keyboardAutoNavigatorDidTapDone(self) } public func keyboardAccessoryDidTapBack(_ inputAccessory: UIView) { didTapBack() } public func keyboardAccessoryDidTapNext(_ inputAccessory: UIView) { didTapNext() } public func keyboardAccessoryDidTapDone(_ inputAccessory: UIView) { didTapDone() } }
48.074236
216
0.680352
9c994f76153b1aa665f842d854032c72c723385b
621
// // MovieVideo.swift // MovieDemo // // Created by Oscar Vernis on 25/09/20. // Copyright © 2020 Oscar Vernis. All rights reserved. // import ObjectMapper class MovieVideo: Mappable { var key: String! var name: String? var type: String? //MARK: - ObjectMapper required init?(map: Map) { if map.JSON["key"] == nil { return nil } if map.JSON["site"] as? String != "YouTube" { return nil } } func mapping(map: Map) { key <- map["key"] name <- map["name"] type <- map["type"] } }
18.264706
55
0.507246
5b6a5933900e7aacbcac8aec8e0b116d834a3d58
821
// // DashedLineLayer.swift // MapRadar // // Created by Ivan Sapozhnik on 6/16/18. // Copyright © 2018 Ivan Sapozhnik. All rights reserved. // import UIKit import QuartzCore class DashedLine: CALayer { override func draw(in ctx: CGContext) { super.draw(in: ctx) let dashHeight: CGFloat = 2.0 let path = UIBezierPath() path.move(to: CGPoint(x: dashHeight/2, y: dashHeight / 2)) path.addLine(to: CGPoint(x: dashHeight/2, y: bounds.maxY - dashHeight / 2)) let dashes: [CGFloat] = [5, 8] ctx.setLineWidth(dashHeight) ctx.setLineDash(phase: 0, lengths: dashes) ctx.setLineCap(.round) ctx.addPath(path.cgPath) ctx.setStrokeColor(RGB(r: 9, g: 82, b: 86).color.cgColor) ctx.strokePath() } }
26.483871
83
0.604141
e83c4ee931738df624efc94559d4c04f5e8a122c
486
import WidgetKit extension LatestArticles { struct Timeline { static func generate(completion: @escaping (WidgetKit.Timeline<Entry>) -> ()) { ArticleStore.fetch() { articles in let schedule = Schedule() let entry = Entry(articles: articles, date: Date()) let timeline = WidgetKit.Timeline(entries: [entry], policy: .after(schedule.nextUpdate)) completion(timeline) } } } }
32.4
104
0.576132
1e017f60855237197770c915f35f24acccc2cc20
6,976
import Foundation import Yams import Quick import Nimble @testable import SwaggerKit final class SpecExampleTests: QuickSpec { // MARK: - Instance Methods override func spec() { var example: SpecExample! var exampleYAML: String! describe("UID example") { beforeEach { example = SpecExampleSeeds.uid exampleYAML = SpecExampleSeeds.uidYAML } it("should be correctly decoded from YAML string") { do { let decodedExample = try YAMLDecoder.test.decode( SpecExample.self, from: exampleYAML ) expect(decodedExample).to(equal(example)) } catch { fail("Test encountered unexpected error: \(error)") } } it("should be correctly encoded to YAML string") { do { let encodedExampleYAML = try YAMLEncoder.test.encode(example) expect(encodedExampleYAML).to(equal(try exampleYAML.yamlSorted())) } catch { fail("Test encountered unexpected error: \(error)") } } } describe("Rating example") { beforeEach { example = SpecExampleSeeds.rating exampleYAML = SpecExampleSeeds.ratingYAML } it("should be correctly decoded from YAML string") { do { let decodedExample = try YAMLDecoder.test.decode( SpecExample.self, from: exampleYAML ) expect(decodedExample).to(equal(example)) } catch { fail("Test encountered unexpected error: \(error)") } } it("should be correctly encoded to YAML string") { do { let encodedExampleYAML = try YAMLEncoder.test.encode(example) expect(encodedExampleYAML).to(equal(try exampleYAML.yamlSorted())) } catch { fail("Test encountered unexpected error: \(error)") } } } describe("Email example") { beforeEach { example = SpecExampleSeeds.email exampleYAML = SpecExampleSeeds.emailYAML } it("should be correctly decoded from YAML string") { do { let decodedExample = try YAMLDecoder.test.decode( SpecExample.self, from: exampleYAML ) expect(decodedExample).to(equal(example)) } catch { fail("Test encountered unexpected error: \(error)") } } it("should be correctly encoded to YAML string") { do { let encodedExampleYAML = try YAMLEncoder.test.encode(example) expect(encodedExampleYAML).to(equal(try exampleYAML.yamlSorted())) } catch { fail("Test encountered unexpected error: \(error)") } } } describe("Languages example") { beforeEach { example = SpecExampleSeeds.languages exampleYAML = SpecExampleSeeds.languagesYAML } it("should be correctly decoded from YAML string") { do { let decodedExample = try YAMLDecoder.test.decode( SpecExample.self, from: exampleYAML ) expect(decodedExample).to(equal(example)) } catch { fail("Test encountered unexpected error: \(error)") } } it("should be correctly encoded to YAML string") { do { let encodedExampleYAML = try YAMLEncoder.test.encode(example) expect(encodedExampleYAML).to(equal(try exampleYAML.yamlSorted())) } catch { fail("Test encountered unexpected error: \(error)") } } } describe("Image size example") { beforeEach { example = SpecExampleSeeds.imageSize exampleYAML = SpecExampleSeeds.imageSizeYAML } it("should be correctly decoded from YAML string") { do { let decodedExample = try YAMLDecoder.test.decode( SpecExample.self, from: exampleYAML ) expect(decodedExample).to(equal(example)) } catch { fail("Test encountered unexpected error: \(error)") } } it("should be correctly encoded to YAML string") { do { let encodedExampleYAML = try YAMLEncoder.test.encode(example) expect(encodedExampleYAML).to(equal(try exampleYAML.yamlSorted())) } catch { fail("Test encountered unexpected error: \(error)") } } } describe("Image example") { beforeEach { example = SpecExampleSeeds.image exampleYAML = SpecExampleSeeds.imageYAML } it("should be correctly decoded from YAML string") { do { let decodedExample = try YAMLDecoder.test.decode( SpecExample.self, from: exampleYAML ) expect(decodedExample).to(equal(example)) } catch { fail("Test encountered unexpected error: \(error)") } } it("should be correctly encoded to YAML string") { do { let encodedExampleYAML = try YAMLEncoder.test.encode(example) expect(encodedExampleYAML).to(equal(try exampleYAML.yamlSorted())) } catch { fail("Test encountered unexpected error: \(error)") } } } describe(".extensions") { beforeEach { example = SpecExampleSeeds.image } it("should return extensions") { expect(example.extensions as? [String: Bool]).to(equal(["private": true])) } it("should modify extensions") { example.extensions["private"] = false expect(example.extensions as? [String: Bool]).to(equal(["private": false])) } } } }
32.751174
91
0.473194
f4e3dddcd425c47a2b46d8e6e0fd8f61d8948b95
2,196
// // TipMeTests.swift // TipMeTests // // Created by Carlos Martinez on 8/15/17. // Copyright © 2017 Carlos Martinez. All rights reserved. // import XCTest @testable import TipMe // MARK: - Tip Calculator Model Tests class TipMeTests: XCTestCase { var tipCalc:TipCalc? override func setUp() { super.setUp() let MIN_VAL = Float(10) let DEFAULT = Float(15) let MAX_VAL = Float(20) tipCalc = TipCalc(withMinTip: MIN_VAL, maxTip: MAX_VAL, defaultTip: DEFAULT) XCTAssertNotNil(tipCalc, "Found nil after initialization.") XCTAssert(tipCalc?.tipRangeValues[0] == MIN_VAL,"Tip Range Values not correctly initialized") XCTAssert(tipCalc?.tipRangeValues[1] == DEFAULT,"Tip Range Values not correctly initialized") XCTAssert(tipCalc?.tipRangeValues[2] == MAX_VAL,"Tip Range Values not correctly initialized") } override func tearDown(){ // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() tipCalc = nil } func testTipAndTotalUsingPercentage() { guard let tipCalc = tipCalc else { return } let bill = Float(100) let percentage = Float(12) let tipAndTotalUsingPercentage = tipCalc.getTipAndTotal(fromBill: bill, andPercentage: percentage) XCTAssert(tipAndTotalUsingPercentage.tip == Float(12), "Incorrect Tip Calculation") XCTAssert(tipAndTotalUsingPercentage.total == Float(112), "Incorrect Total Bill Calculation") } func testTipAndTotalUsingDecimalPercentage() { guard let tipCalc = tipCalc else { return } let bill = Float(100) let decimalPercentage = Float(0.12) let tipAndTotalUsingDecimalPercentage = tipCalc.getTipAndTotal(fromBill: bill, andPercentage: decimalPercentage) XCTAssert(tipAndTotalUsingDecimalPercentage.tip == Float(12), "Incorrect Tip Calculation using decimal percentage") XCTAssert(tipAndTotalUsingDecimalPercentage.total == Float(112), "Incorrect Total Bill Calculation using decimal percentage") } }
35.419355
133
0.67623
f51fd1ffd376a3fff08c9a4bd370cc12d50aba4b
4,632
// // ThreadedDictionary.swift // Threading // // Created by Jeremy Schwartz on 2018-06-17. // import Foundation public class ThreadedDictionary<Key: Hashable, Value> : ThreadedObject<Dictionary<Key, Value>> { public typealias InternalCollectionType = Dictionary<Key, Value> public typealias Index = InternalCollectionType.Index public typealias Element = InternalCollectionType.Element public typealias Keys = InternalCollectionType.Keys public typealias Values = InternalCollectionType.Values /// Constructs from an existing dictionary and a threading type. /// /// - parameters: /// - dictionary: A dictionary who's elements will be copied to the /// threaded dictionary. /// /// - type: The threading type which defines how this object should act. public override init(_ dictionary: [Key : Value], type: ThreadingType) { super.init(dictionary, type: type) } /// Initializes with a blank dictionary and concurrent type. public convenience init() { self.init([Key : Value](), type: .concurrent) } /// Constructs from an existing dictionary. /// /// - parameters: /// - dictionary: A dictionary who's elements will be copied to the /// threaded dictionary. /// /// Threading type is set to concurrent. public convenience init(_ dictionary: [Key : Value]) { self.init(dictionary, type: .concurrent) } /// Key style access for the dictionary. /// /// - parameters: /// - key: Access key for the desired value. /// /// If no key-value pair exists in the dictionary with the given key, then /// the subscript returns nil. /// /// Setting a value to nil will remove that key-value pair from the /// dictionary. public subscript(key: Key) -> Value? { get { return sync { collection in return collection[key] } } set { async { collection in collection[key] = newValue } } } } // MARK: - Computed Properties public extension ThreadedDictionary { /// A collection containing just the keys of the dictionary. public var keys: Keys { return sync { collection in return collection.keys } } /// A collection containing just the values of the dictionary. public var values: Values { return sync { collection in return collection.values } } } // MARK: - Non-mutating Methods public extension ThreadedDictionary { public func mapValues<T> (_ transform: @escaping (Value) -> T) -> [Key : T] { var result = [Key : T]() sync { collection in result = collection.mapValues(transform) } return result } } // MARK: - Threaded Collection Conformance extension ThreadedDictionary : ThreadedCollection { /// Returns an unmanaged version of the underlying object. public var unthreaded: Dictionary<Key, Value> { return sync { collection in return collection } } } // MARK: - Swift Collection Conformance extension ThreadedDictionary : Collection { /// Positional based subscript for the dictionary. /// /// - parameters: /// - position: The zero-indexed location of the element to access. /// `position` must be witin the range /// `startIndex..<endIndex`, otherwise a fatal, uncatchable /// exception will be thrown. public subscript(position: Index) -> Element { return sync { collection in return collection[position] } } /// Returns the position immediately after a given index. /// /// - parameters: /// - i: A valid position in the collection, /// i must be less than `endIndex`, public func index(after i: Index) -> Index { return sync { collection in return collection.index(after: i) } } /// The position of the first element in a non-empty dictionary. public var startIndex: Index { return sync { collection in return collection.startIndex } } /// The collection's "past the end" position – that is the position one /// past the last valid subscript argument. public var endIndex: Index { return sync { collection in return collection.endIndex } } }
27.903614
80
0.594991
e53530735bbb5086f26f8593ba09dde9a75b139b
481
import XCPlayground import XCDYouTubeKit setenv("XCDYouTubeKitLogLevel", "0", 1) var client = XCDYouTubeClient(languageIdentifier: "en") client.getVideoWithIdentifier("6v2L2UGZJAM") { (video: XCDYouTubeVideo?, error: NSError?) -> Void in video error?.localizedDescription } client.getVideoWithIdentifier("xxxxxxxxxxx") { (video: XCDYouTubeVideo?, error: NSError?) -> Void in video error?.localizedDescription } XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
25.315789
100
0.790021
22f1986207f6b4be65ec46259c7c0d8f98878c96
5,375
// // SettingsController.swift // uber-clone // // Created by Ted Hyeong on 28/10/2020. // import UIKit private let reuseIdentifier = "LocationCell" protocol SettingsControllerDelegate: class { func updateUser(_ controller: SettingsController) } enum LocationType: Int, CaseIterable, CustomStringConvertible { case home case work var description: String { switch self { case .home: return "Home" case .work: return "Work" } } var subtitle: String { switch self { case .home: return "Add Home" case .work: return "Add Work" } } } class SettingsController: UITableViewController { // MARK: - Properties var user: User private let locationManager = LocationHandler.shared.locationManager weak var delegate: SettingsControllerDelegate? var userInfoUpdated = false private lazy var infoHeader: UserInfoHeader = { let frame = CGRect(x: 0, y: 0, width: view.frame.width, height: 100) let view = UserInfoHeader(user: user, frame: frame) return view }() // MARK: - Lifecycle init(user: User) { self.user = user super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() configureTableView() configureNavigationBar() } // MARK: - Selectors @objc func handleDismissal() { if userInfoUpdated { delegate?.updateUser(self) } self.dismiss(animated: true, completion: nil) } // MARK: - Helpers func locationText(forType type: LocationType) -> String { switch type { case .home: return user.homeLocation ?? type.subtitle case .work: return user.workLocation ?? type.subtitle } } func configureTableView() { tableView.rowHeight = 60 tableView.register(LocationCell.self, forCellReuseIdentifier: reuseIdentifier) tableView.backgroundColor = .white tableView.tableHeaderView = infoHeader tableView.tableFooterView = UIView() } func configureNavigationBar() { navigationController?.navigationBar.prefersLargeTitles = true navigationController?.navigationBar.isTranslucent = false navigationController?.navigationBar.barStyle = .black navigationItem.title = "Settings" navigationController?.navigationBar.barTintColor = .backgroundColor navigationItem.leftBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "baseline_clear_white_36pt_2x").withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(handleDismissal)) } } // MARK: - UITableViewDelegate/Datasource extension SettingsController { override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return LocationType.allCases.count } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let view = UIView() view.backgroundColor = .backgroundColor let title = UILabel() title.font = UIFont.systemFont(ofSize: 16) title.textColor = .white title.text = "Favorites" view.addSubview(title) title.centerY(inView: view, leftAnchor: view.leftAnchor, paddingLeft: 16) return view } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 40 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath) as! LocationCell guard let type = LocationType(rawValue: indexPath.row) else { return cell } cell.titleLabel.text = type.description cell.addressLabel.text = locationText(forType: type) return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard let type = LocationType(rawValue: indexPath.row) else { return } guard let location = locationManager?.location else { return } let controller = AddLocationController(type: type, location: location) controller.delegate = self let nav = UINavigationController(rootViewController: controller) present(nav, animated: true, completion: nil) } } // MARK: - AddLocationControllerDelegate extension SettingsController: AddLocationControllerDelegate { func updateLocation(locationString: String, type: LocationType) { PassengerService.shared.saveLocation(locationString: locationString, type: type) { (err, rf) in self.dismiss(animated: true, completion: nil) self.userInfoUpdated = true switch type { case .home: self.user.homeLocation = locationString case .work: self.user.workLocation = locationString } self.tableView.reloadData() } } }
31.069364
226
0.645023
6aae8b867688cba1fb147de3eb9106e84d808323
2,409
// // SideMenuHeader.swift // WooStudio // // Created by Gati Shah on 7/15/18. // Copyright © 2018 Gati Shah. All rights reserved. // import UIKit import SideMenu /** The purpose of 'SideMenuHeader' view is to configure side menu header. There's matching scene in the *SideMenuHeader.xib* file. Go to Interface Builder for details. The 'SideMenuHeader' class is a subclass of the 'UIView'. */ class SideMenuHeader: UIView { //MARK:- Outlets @IBOutlet weak var viewContent: UIView! @IBOutlet weak var imageUser : UIImageView! @IBOutlet weak var labelFullName : UILabel! @IBOutlet weak var labelUserName : UILabel! @IBOutlet weak var viewSep : UIView! //MARK:- Properties var vController : SideMenu? class func instanceFromNib() -> SideMenuHeader { return UINib(nibName: ViewIdentifier.SideMenuHeader, bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! SideMenuHeader } // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing code self.setUpView() } //MARK:- Custom Method /** setUpView function is used to setup default values, messages and UI related changes for the current class. */ func setUpView() { DispatchQueue.main.async { self.imageUser.layer.cornerRadius = self.imageUser.frame.size.width / 2 self.imageUser.layer.masksToBounds = true } labelFullName.font = GetAppFont(FontType: .Bold, FontSize: .Large) labelUserName.font = GetAppFont(FontType: .Regular, FontSize: .Small) viewSep.backgroundColor = UIColor.black } //MARK:- Set Data /** setFullName function is used to set full name of user - Parameter strFullname: Full name parameter string - Returns: nil */ func setFullName(strFullname : String) { labelFullName.setUpLabel(title: strFullname, titleColor: .darkGray) } /** setUserName function is used to set username of user - Parameter strUserName: Username parameter string - Returns: nil */ func setUserName(strUserName : String) { labelUserName.setUpLabel(title: strUserName, titleColor: .orange) } }
28.678571
137
0.655874
abf5b472c5b72da3b13d2fb130fa8305cc583f0f
2,647
// // DeatailViewController.swift // iOSEngineerCodeCheck // // Created by 酒井ゆうき on 2020/12/18. // Copyright © 2020 YUMEMI Inc. All rights reserved. // import UIKit class DetailViewController : UIViewController { //MARK: - Properties var repositry : Repositry private let RM = RealmManager() private let screenHight = UIScreen.main.bounds.height private let topPadding : CGFloat = 5 /// footer はview表示毎に,checkfavoritedを行う為 var footer : DetailFooterView! var didLoad = true //MARK: - LifeCycle init(repo : Repositry) { self.repositry = repo super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() repositry.favorited = RM.checkFavorited(repoID: repositry.id) configureUI() didLoad = false } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if !didLoad { repositry.favorited = RM.checkFavorited(repoID: repositry.id) footer.repo = repositry } } //MARK: - UI private func configureUI() { navigationItem.title = repositry.name navigationController?.navigationBar.isTranslucent = false view.backgroundColor = .white let header = DetailHeaderView(frame: CGRect(x: 0, y: topPadding, width: view.frame.width, height:screenHight / 2)) header.repo = repositry view.addSubview(header) footer = DetailFooterView(frame:CGRect(x: 0, y: screenHight / 2 + topPadding, width: view.frame.width, height:screenHight / 2)) footer.delegate = self footer.repo = repositry view.addSubview(footer) } } //MARK: - Manage Favorite extension DetailViewController : DetailFooterViewProtocol { func tappedUrl(footer: DetailFooterView) { if let url = URL(string:repositry.htmlURL) { UIApplication.shared.open(url, options: [:], completionHandler: nil) } } func handleFavorite(footer: DetailFooterView) { if repositry.favorited { /// remove fav RM.deleteFavorite(repo: repositry) } else { /// add fav RM.addFavorite(repo: repositry) } repositry.favorited.toggle() footer.configureStarImage(repo: repositry) } }
23.846847
135
0.589724
720c1a6234343559fac3542d8862e264cf124c1a
827
/*: > # IMPORTANT: To use `Rx.playground`, please: 1. Open `Rx.xcworkspace` 2. Build `RxSwift-OSX` scheme 3. And then open `Rx` playground in `Rx.xcworkspace` tree view. 4. Choose `View > Show Debug Area` */ /*: ## Index: 1. [Introduction](Introduction) 1. [Subjects](Subjects) 1. [Transforming Observables](Transforming_Observables) 1. [Filtering Observables](Filtering_Observables) 1. [Combining Observables](Combining_Observables) 1. [Error Handling Operators](Error_Handling_Operators) 1. [Observable Utility Operators](Observable_Utility_Operators) 1. [Conditional and Boolean Operators](Conditional_and_Boolean_Operators) 1. [Mathematical and Aggregate Operators](Mathematical_and_Aggregate_Operators) 1. [Connectable Observable Operators](Connectable_Observable_Operators) */ //: [Index](Index) - [Next >>](@next)
29.535714
79
0.772672
28aaabd5639ca70eb78890bf971fcbb77eb32f96
739
// // UIColor+Extension.swift // Vankeyi-Swift // // Created by SimonYHB on 2016/12/8. // Copyright © 2016年 yhb. All rights reserved. // import UIKit extension UIColor{ static let backgroundColor = UIColor.init(hexString: "f2f7f7")! static let globalColor = UIColor.init(hexString: "ec6b39")! class func setGradualChangingColor(view:UIView, fromColor:String, toColor:String) -> CAGradientLayer { let layer = CAGradientLayer.init() layer.frame = view.bounds layer.colors = [UIColor.init(hexString: fromColor)!.cgColor, UIColor.init(hexString: toColor)!.cgColor] layer.startPoint = CGPoint.init(x: 0, y: 0) layer.endPoint = CGPoint.init(x: 1, y: 0) return layer } }
30.791667
111
0.673884
1cb7582fe3bebc689f4a2543d0eb05780fc08284
423
// // RegisterAssistantRequest.swift // FanapPodChatSDK // // Created by Hamed Hosseini on 4/6/21. // import Foundation public class DeactiveAssistantRequest : BaseRequest{ public let assistants: [Assistant] public init(assistants: [Assistant], typeCode: String? = nil, uniqueId: String? = nil) { self.assistants = assistants super.init(uniqueId: uniqueId, typeCode: typeCode) } }
23.5
92
0.685579
20724d103a56d48db0d1142b2c70fdacca1fcbfb
1,245
// // StarRatingUITests.swift // StarRatingUITests // // Created by Andy on 2017/7/13. // Copyright © 2017年 AndyCuiYTT. All rights reserved. // import XCTest class StarRatingUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
33.648649
182
0.664257
ed3717f676fe70ca23f98389712838c88957d818
818
func makeAnagram(a: String, b: String) -> Int { var charArray = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"] var aDict = [String: Int]() var bDict = [String: Int]() var deletions: Int = 0 for char in charArray { aDict[char] = 0 bDict[char] = 0 } for char in a { var value = aDict[String(char)] as! Int value += 1 aDict[String(char)] = value } for char in b { var value = bDict[String(char)] as! Int value += 1 bDict[String(char)] = value } for char in charArray { if aDict[char] != bDict[char] { deletions += abs((aDict[char] as! Int) - (bDict[char] as! Int)) } } return deletions }
25.5625
150
0.463325
7ad047c68aa42997b844983e8d24d9b4b7e6b08f
2,099
// // WidgetLoader.swift // Widget Extension // // Created by David Sinclair on 2019-11-29. // Copyright © 2019 NewsBlur. All rights reserved. // import UIKit /// Network loader for the widget. class Loader: NSObject, URLSessionDataDelegate { typealias Completion = (Result<Data, Error>) -> Void private var completion: Completion private var receivedData = Data() init(url: URL, completion: @escaping Completion) { self.completion = completion super.init() var request = URLRequest(url: url) request.httpMethod = "GET" // request.addValue(accept, forHTTPHeaderField: "Accept") let config = URLSessionConfiguration.background(withIdentifier: UUID().uuidString) config.sharedContainerIdentifier = "group.com.newsblur.NewsBlur-Group" let session = URLSession(configuration: config, delegate: self, delegateQueue: nil) let task = session.dataTask(with: request) task.resume() } // MARK: - URL session delegate func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) { guard let response = response as? HTTPURLResponse, (200...299).contains(response.statusCode) else { completionHandler(.cancel) return } completionHandler(.allow) } func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) { print("error: \(error.debugDescription)") } func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { print("data: \(data)") receivedData.append(data) } func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { if let error = error { completion(.failure(error)) } else { completion(.success(receivedData)) } } }
30.867647
179
0.633159
e8ba12beafbd4fbf8b51d4cc27e06a14bcf6d8d5
1,305
// RUN: rm -rf %t // RUN: mkdir -p %t // RUN: echo "public var x = Int64()" \ // RUN: | %target-swift-frontend -module-name FooBar -emit-module -o %t - // RUN: %target-swift-frontend %s -O -I %t -emit-ir -g -o %t.ll // RUN: %FileCheck %s < %t.ll // RUN: %FileCheck %s -check-prefix=TRANSPARENT-CHECK < %t.ll // CHECK: define{{( protected)?( signext)?}} i32 @main // CHECK: call {{.*}}noinline{{.*}}, !dbg ![[CALL:.*]] // CHECK-DAG: ![[TOPLEVEL:.*]] = !DIFile(filename: "inlinescopes.swift" import FooBar func use<T>(_ t: T) {} @inline(never) func noinline(_ x: Int64) -> Int64 { return x } @_transparent func transparent(_ x: Int64) -> Int64 { return noinline(x) } @inline(__always) func inlined(_ x: Int64) -> Int64 { // CHECK-DAG: ![[CALL]] = !DILocation(line: [[@LINE+2]], column: {{.*}}, scope: ![[SCOPE:.*]], inlinedAt: ![[INLINED:.*]]) // CHECK-DAG: ![[SCOPE:.*]] = distinct !DILexicalBlock( let result = transparent(x) // TRANSPARENT-CHECK-NOT: !DISubprogram(name: "transparent" return result } // CHECK-DAG: !DIGlobalVariable(name: "y",{{.*}} file: ![[TOPLEVEL]],{{.*}} line: [[@LINE+1]] let y = inlined(x) use(y) // Check if the inlined and removed function still has the correct linkage name. // CHECK-DAG: !DISubprogram(name: "inlined", linkageName: "_T04main7inlineds5Int64VADF"
34.342105
122
0.630651
8aa931123d7ce5672ab7edcd75cc6ed9459082fe
640
// // LoginViewController.swift // Budgeter // // Created by Harry Nelken on 3/18/18. // Copyright © 2018 Harry Nelken. All rights reserved. // import UIKit import LocalAuthentication final class LoginViewController: UIViewController { @IBOutlet weak var enterButton: UIButton! override func viewDidLoad() { super.viewDidLoad() setupButton() } // MARK: Setup private func setupButton() { enterButton.layer.cornerRadius = enterButton.frame.height / 2 enterButton.clipsToBounds = true } @IBAction func enterButtonTapped(_ sender: Any) { } }
19.393939
69
0.646875
1f03763a2118c86fa7dfd3778bcf2999bc106420
533
// // SetDataCell.swift // Raspisach // // Created by  Евгений on 11/01/2019. // Copyright © 2019 Евгений Фомин. All rights reserved. // import UIKit class SetDataCell: UITableViewCell { @IBOutlet weak var textField: UITextField! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
19.740741
65
0.660413
20b2cd3655a822f95b2d95dd5f6e7015f509182b
197
// // NetworkError.swift // ios-network-module // // Created by Abhishek on 13/06/21. // import Foundation enum NetworkError: Error { case parsingError(String) case network(String?) }
14.071429
36
0.680203
f592c6b0fb1c94342f2df0abb89bfe65603de50a
8,562
// // ManagedObjectsProvider.swift // // WidgetKit, Copyright (c) 2018 Favio Mobile (http://favio.mobi) // // 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 Groot public class ManagedObjectsProvider: BaseContentProvider, NSFetchedResultsControllerDelegate { @objc public var entityName: String? @objc public var groupByField: String? @objc public var cacheName: String? var _fetchedResultsController: NSFetchedResultsController<NSFetchRequestResult>? var fetchedResultsController: NSFetchedResultsController<NSFetchRequestResult> { if _fetchedResultsController == nil { fetch() } return _fetchedResultsController! } private func masterPredicate() -> NSPredicate? { guard let masterObject = masterObject, let masterKeyPath = masterKeyPath else { return nil } return NSPredicate(format: "%K = %@", masterKeyPath, masterObject) } private func filterPredicate() -> NSPredicate? { guard let filterFormat = filterFormat, let searchString = searchString, searchString.count > 0 else { return nil } let predicate = NSPredicate(format: filterFormat).withSubstitutionVariables([TextInputView.inputFieldName: searchString]) return predicate } private func predicateFromString(_ string: String?) -> NSPredicate? { return string != nil ? NSPredicate(format: string!) : nil } private func predicate() -> NSPredicate? { var predicates = [NSPredicate]() if let mainPredicate = predicateFromString(predicateFormat) { predicates.append(mainPredicate) } if let masterPredicate = masterPredicate() { predicates.append(masterPredicate) } if let filterPredicate = filterPredicate() { predicates.append(filterPredicate) } return NSCompoundPredicate.init(andPredicateWithSubpredicates: predicates) } private var _managedObjectContext: NSManagedObjectContext? public var managedObjectContext: NSManagedObjectContext { get { return _managedObjectContext ?? (widget?.defaultContext ?? NSManagedObjectContext.main) } set { _managedObjectContext = newValue } } public override var sectionsCount: Int { return fetchedResultsController.sections?.count ?? 0 } public override func itemsCountInSection(_ section: Int) -> Int { return fetchedResultsController.sections?[section].numberOfObjects ?? 0 } public override var allItems: [Any] { return fetchedResultsController.fetchedObjects ?? [] } public override func item(at indexPath: IndexPath) -> Any? { return fetchedResultsController.object(at: indexPath) } public override func indexPath(for item: Any) -> IndexPath? { return fetchedResultsController.indexPath(forObject: item as! NSFetchRequestResult) } public override func totalCount() -> Int { guard let sections = fetchedResultsController.sections else { return 0 } var count = 0 for section in sections { count += section.numberOfObjects } return count } public override func firstIndexPath() -> IndexPath? { guard let sections = fetchedResultsController.sections else { return nil } let firstSection = sections.first! let count = firstSection.numberOfObjects return count > 0 ? IndexPath.first : nil } public override func lastIndexPath() -> IndexPath? { guard let sections = fetchedResultsController.sections else { return nil } let lastSection = sections.last! let count = lastSection.numberOfObjects return count > 0 ? IndexPath(row: count - 1, section: sections.count - 1) : nil } public override func reset() { _fetchedResultsController = nil super.reset() } public override func insertItem(_ item: Any, at indexPath: IndexPath) { assert(false, "Inserting items directly is not supported for 'ManagedObjectsProvider'.") } public override func fetch() { var sortDescriptors = self.sortDescriptors if groupByField != nil && groupByField != "" { sortDescriptors.insert(NSSortDescriptor(key: groupByField!, ascending: sortAscending), at: 0) } let fetchRequest = NSFetchRequest<NSFetchRequestResult>() fetchRequest.entity = NSEntityDescription.entity(forEntityName: entityName!, in: managedObjectContext)! fetchRequest.sortDescriptors = sortDescriptors fetchRequest.predicate = predicate() _fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: managedObjectContext, sectionNameKeyPath: groupByField, cacheName: cacheName) _fetchedResultsController!.delegate = self do { try _fetchedResultsController!.performFetch() contentConsumer?.renderContent(from: self) } catch let error { print(error) } } } extension ManagedObjectsProvider { public func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { contentConsumer?.prepareRenderContent?(from: self) } public func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { if let finalizeRenderContent = contentConsumer?.finalizeRenderContent { finalizeRenderContent(self) } else { contentConsumer?.renderContent(from: self) } } public func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) { if type == .insert, let newIndexPath = newIndexPath { contentConsumer?.renderContent?(anObject, change: .insert, at: newIndexPath, from: self) } else if type == .update, let indexPath = indexPath { contentConsumer?.renderContent?(anObject, change: .update, at: indexPath, from: self) } else if type == .delete, let indexPath = indexPath { contentConsumer?.renderContent?(anObject, change: .delete, at: indexPath, from: self) } else if type == .move, let oldIndexPath = indexPath, let newIndexPath = newIndexPath { contentConsumer?.renderContent?(anObject, change: .delete, at: oldIndexPath, from: self) contentConsumer?.renderContent?(anObject, change: .insert, at: newIndexPath, from: self) } } } public class ManagedObjectsCollection: BaseContentProvider { private var _provider = ManagedObjectsProvider() public override func fetch() { _provider.masterKeyPath = masterKeyPath _provider.sortByFields = sortByFields _provider.sortAscending = sortAscending _provider.searchString = searchString _provider.resultChain = resultChain _provider.resultChainArgs = resultChainArgs _provider.predicateFormat = predicateFormat if let value = _provider.value { items = value as? [Any] ?? [value] } } }
41.765854
207
0.671689
644fa6a6b8647d02f0685c100e04e8f4c887c29d
154
// // Extensions.swift // BaseTest // // Created by Kruperfone on 19.11.15. // Copyright © 2015 Flatstack. All rights reserved. // import Foundation
15.4
52
0.681818
e5caa3085a92dd396b7981289be188fdea8594e3
1,802
// // SwiftyColor // // The MIT License (MIT) // // Copyright (c) 2015 Suyeol Jeon (xoul.kr) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #if os(iOS) import UIKit #elseif os(OSX) import AppKit #endif import XCTest import SwiftyColor final class SwiftyColorTests: XCTestCase { func testHex() { let color = 0x123456.color var (red, green, blue) = (CGFloat(), CGFloat(), CGFloat()) color.getRed(&red, green: &green, blue: &blue, alpha: nil) XCTAssert(Int(red * 255) == 0x12) XCTAssert(Int(green * 255) == 0x34) XCTAssert(Int(blue * 255) == 0x56) } func testAlpha() { XCTAssertEqual(0x123456.color ~ 50%, 0x123456.color.withAlphaComponent(0.5)) } func testPercent() { XCTAssert(50% == 0.5) XCTAssert(12% == 0.12) } }
32.178571
81
0.714761
eb25ac149ff551a2e640df8d54b42d87d8e6ee90
502
// // ViewController.swift // CustomNavigationBarDemo // // Created by 也许、 on 16/9/27. // Copyright © 2016年 K. All rights reserved. // import UIKit class ViewController: UIViewController { 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. } }
19.307692
80
0.667331
ab5d9cab7df175be78895b7fa534b2a931cec5f8
4,903
//: # Lesson 1 Exercises //: ## String Manipulation import UIKit import Foundation //: ### Exercise 1 //: Example: Here I've declared one String that forms a sentence that makes sense. I've declared a second String that forms a silly sentence when random words are chosen. let nounArray = ["puppy", "laptop", "ocean","app", "cow", "skateboard", "developer", "coffee", "moon"] let index1 = Int(arc4random() % 9) let index2 = Int(arc4random() % 9) let sentence = "The \(nounArray[6]) spilled her \(nounArray[7])." let sillySentence = "The \(nounArray[index1]) jumped over the \(nounArray[index2])." //: Now try it yourself! Declare a new string that incorporates objects from the noun array above. Write one sentence that makes sense and one "Madlib" sentence with randomly chosen words. Feel free to add words to the noun array or declare a new array. let yourSentence = "TODO: Incorporate objects from the noun array here." let yourSillySentence = "TODO: Incorporate randomly chosen objects from the noun array here." //: ### Exercise 2 //: Recreate the shoutString by using the didYouKnowString as a stem. let didYouKnowString = "Did you know that the Swift String class comes with lots of useful methods?" let whisperString = "psst" + ", " + didYouKnowString.lowercased() let shoutString = "HEY! DID YOU KNOW THAT THE SWIFT STRING CLASS COMES WITH LOTS OF USEFUL METHODS?" //: ### Exercise 3 //: How many characters are in this string? let howManyCharacters = "How much wood could a woodchuck chuck if a woodchuck could chuck wood?" //: ### Exercise 4 //: How many times does the letter "g" or "G" appear in the following string? Use a for-in loop to find out! let gString = "Gary's giraffe gobbled gooseberries greedily" var count = 0 //: ### Exercise 5 //: Write a program that tells you whether or not this string contains the substring "tuna". let word = "fortunate" //: ### Exercise 6 //: Write a program that deletes all occurrences of the word "like" in the following string. let lottaLikes = "If like, you wanna learn Swift, like, you should build lots of small apps, cuz it's like, a good way to practice." //: ### Exercise 7 // Example let sillyMonkeyString = "A monkey stole my iPhone" let newString = sillyMonkeyString.replacingOccurrences(of: "monkey", with: "🐒") let newerString = newString.replacingOccurrences(of: "iPhone", with: "📱") //: Repeat the above string manipulation, but this time using a for-in loop. //: You can start off with this dictionary and string. let dictionary = ["monkey": "🐒", "iPhone":"📱"] var newestString = sillyMonkeyString //: ### Exercise 8 //: Josie has been saving her pennies and has them all counted up. Write a program that, given a number of pennies, prints out how much money Josie has in dollars and cents. // Example let numOfPennies = 567 //desired output = "$5.67" //: # Let or Var? import UIKit import Foundation //: ### Exercise 9 //: Below is the code to find all the numbers present in an array, convert them to Ints, and calculate their sum. Have a look at the entities declared below: array, sum, and intToAdd. Think about whether each should be a constant or a variable and choose whether to declare them with let or var. When you're finished uncomment the code and see if the compiler agrees with your choices! // let or var array = ["A", "13", "B","5","87", "t", "41"] // TODO: Choose constant or variable // let or var sum = 0 // TODO: Choose constant or variable // for string in array { // if Int(string) != nil { // let or var intToAdd = Int(string)! // TODO: Choose constant or variable // sum += intToAdd // } // } // print(sum) //: ### Exercise 10 //: For each of the following pairs, choose whether to declare a constant or a variable. //: //: Example: Two hikers are climbing up to the summit of a mountain. Along the way, they stop a few times to check their current elevation. //: //: Example response: let summitElevation: Int var currentElevation: Int //: 10a) Imagine you are writing a quiz app, and you need to program a timer that will stop a quiz after 20 min. Declare four entities: startTime, currentTime, maximumTimeAllowed, and timeRemaining. Don't worry about encoding their values. //: 10b) Imagine you are writing an app for a credit card company. Declare two entities: creditLimit and balance. //: ### Exercise 11 //: Below is the code to reverse a string. Have a look at the entities declared: stringToReverse and reversedString. Choose whether to declare each with let or var. When you're finished uncomment the code and see if the compiler agrees with your choices! //let or var stringToReverse = "Mutable or Immutable? That is the question." //TODO:Choose let or var //let or var reversedString = "" //TODO:Choose let or var //for character in stringToReverse.characters { // reversedString = "\(character)" + reversedString //} //print(reversedString, terminator: "")
56.356322
385
0.726494
feb21e6b807d3b11bf44d820f0f121707e8ef00f
2,709
import UIKit final class TabItemView: UIView { private(set) var titleLabel: UILabel = UILabel() public var textColor: UIColor = UIColor(red: 140/255, green: 140/255, blue: 140/255, alpha: 1.0) public var selectedBackgroundColor = UIColor(red: 234/255, green: 237/255, blue: 18/255, alpha: 1.0) public var unSelectedBackgroundColor = UIColor(red: 75/255, green: 75/255, blue: 75/255, alpha: 1.0) public var selectedTextColor: UIColor = .white public var container: UIView = UIView() public var isSelected: Bool = false { didSet { if isSelected { titleLabel.textColor = selectedTextColor container.backgroundColor = selectedBackgroundColor container.layer.borderColor = UIColor.white.cgColor } else { titleLabel.textColor = textColor container.backgroundColor = unSelectedBackgroundColor container.layer.borderColor = UIColor.clear.cgColor } } } public override init(frame: CGRect) { super.init(frame: frame) setupLabel() container.backgroundColor = unSelectedBackgroundColor // container.layer.cornerRadius = frame.height/2 // container.layer.borderWidth = 1 } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override public func layoutSubviews() { super.layoutSubviews() } private func setupLabel() { titleLabel = UILabel(frame: bounds) titleLabel.textAlignment = .center titleLabel.numberOfLines = 2 titleLabel.font = UIFont.boldSystemFont(ofSize: 14) titleLabel.textColor = UIColor(red: 140/255, green: 140/255, blue: 140/255, alpha: 1.0) titleLabel.backgroundColor = UIColor.clear addSubview(container) container.addSubview(titleLabel) layoutLabel() } private func layoutLabel() { container.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ container.topAnchor.constraint(equalTo: self.topAnchor, constant: 3), container.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 3), container.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -3), container.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -3) ]) titleLabel.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ titleLabel.topAnchor.constraint(equalTo: self.topAnchor, constant: 12), titleLabel.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 8), titleLabel.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -8), titleLabel.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -12) ]) } }
33.8625
102
0.707272
7a4f2b2e5ed6886abc7ce39737ed764d79eaaec9
565
// // Created by Jérôme Alves on 11/12/2019. // Copyright © 2019 TwentyLayout. All rights reserved. // import Foundation import UIKit public struct SizeAnchor<Base: FrameConstrainable> { public let item: Base public var constraintAttributes: [NSLayoutConstraint.Attribute] { [.width, .height] } internal init(_ item: Base) { self.item = item } internal var width: SingleAnchor<Base, Width> { SingleAnchor(item) } internal var height: SingleAnchor<Base, Height> { SingleAnchor(item) } }
20.925926
69
0.651327
712c5011b4f51639d18e018c9685f7b3900cefff
28,531
// // AKImageCropperView.swift // // Created by Artem Krachulov. // Copyright (c) 2016 Artem Krachulov. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software // and associated documentation files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, publish, distribute, // sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // import UIKit typealias CGPointPercentage = CGPoint open class AKImageCropperView: UIView, UIScrollViewDelegate, UIGestureRecognizerDelegate, AKImageCropperOverlayViewDelegate { /** Current rotation angle */ fileprivate var angle: Double = 0.0 /** Scroll view minimum edge insets (current value) */ fileprivate var minEdgeInsets: UIEdgeInsets = .zero /** Reversed frame direct to current rotation angle */ fileprivate var reversedRect: CGRect { return CGRect( origin : .zero, size : ((angle / (.pi / 2)).truncatingRemainder(dividingBy: 2)) == 1 ? CGSize(width: frame.size.height, height: frame.size.width) : frame.size) } /** Reversed minimum edge insets direct to current rotation angle */ fileprivate var reversedEdgeInsets: UIEdgeInsets { var newEdgeInsets: UIEdgeInsets switch angle { case .pi / 2: newEdgeInsets = UIEdgeInsets( top: minEdgeInsets.right, left: minEdgeInsets.top, bottom: minEdgeInsets.left, right: minEdgeInsets.bottom) case .pi: newEdgeInsets = UIEdgeInsets( top: minEdgeInsets.bottom, left: minEdgeInsets.right, bottom: minEdgeInsets.top, right: minEdgeInsets.left) case (.pi / 2) * 3: newEdgeInsets = UIEdgeInsets( top: minEdgeInsets.left, left: minEdgeInsets.bottom, bottom: minEdgeInsets.right, right: minEdgeInsets.top) default: newEdgeInsets = minEdgeInsets } return newEdgeInsets } /** Reversed frame + edgeInsets direct to current rotation angle */ var reversedFrameWithInsets: CGRect { return reversedRect.inset(by: reversedEdgeInsets) } // MARK: - // MARK: ** Saved properties ** fileprivate struct SavedProperty { var scaleAspectRatio: CGFloat! var contentOffset: CGPoint! var contentOffsetPercentage: CGPoint! var cropRectSize: CGSize! init() { scaleAspectRatio = 1.0 contentOffset = .zero contentOffsetPercentage = .zero cropRectSize = .zero } mutating func save(scrollView: AKImageCropperScrollView) { scaleAspectRatio = scrollView.zoomScale / scrollView.minimumZoomScale contentOffset = CGPoint( x: scrollView.contentOffset.x + scrollView.contentInset.left, y: scrollView.contentOffset.y + scrollView.contentInset.top) let contentSize = CGSize( width : (scrollView.contentSize.width - scrollView.visibleRect.width).ic_roundTo(precision: 3), height : (scrollView.contentSize.height - scrollView.visibleRect.height).ic_roundTo(precision: 3)) contentOffsetPercentage = CGPointPercentage( x: (contentOffset.x > 0 && contentSize.width != 0) ? ic_round(x: contentOffset.x / contentSize.width, multiplier: 0.005) : 0, y: (contentOffset.y > 0 && contentSize.height != 0) ? ic_round(x: contentOffset.y / contentSize.height, multiplier: 0.005) : 0) cropRectSize = scrollView.visibleRect.size } } /** Saved Scroll View parameters before complex layout animation */ fileprivate var savedProperty = SavedProperty() // MARK: Accessing the Displayed Images /** The image displayed in the image cropper view. Default is nil. */ open var image: UIImage? { didSet { guard let image = image else { return } scrollView.image = image overlayView?.image = image reset() } } /** Cropperd image in the specified crop rectangle */ open var croppedImage: UIImage? { return image?.ic_imageInRect(scrollView.scaledVisibleRect)?.ic_rotateByAngle(angle) } // MARK: States /** Returns the image edited state flag. */ open var isEdited: Bool { guard let image = image else { return false } let fitScaleMultiplier = ic_CGSizeFitScaleMultiplier(image.size, relativeToSize: reversedFrameWithInsets.size) return angle != 0 || fitScaleMultiplier != scrollView.minimumZoomScale || fitScaleMultiplier != scrollView.zoomScale } /** Determines the overlay view current state. Default is false. */ open private(set) var isOverlayViewActive: Bool = false fileprivate var layoutByImage: Bool = true /** Сompletion blocker. */ fileprivate var isAnimation: Bool = false // MARK: Managing the Delegate /** The delegate of the cropper view object. */ weak open var delegate: AKImageCropperViewDelegate? // MARK: - // MARK: ** Initialization OBJECTS(VIEWS) & theirs parameters ** // MARK: Rotate view fileprivate lazy var rotateView: UIView! = { let view = UIView() view.clipsToBounds = true return view }() // MARK: Scroll view var scrollView: AKImageCropperScrollView! // MARK: Overlay Crop view open var overlayView: AKImageCropperOverlayView? { willSet { if overlayView != nil { overlayView?.removeFromSuperview() } if newValue != nil { newValue?.delegate = self newValue?.cropperView = self rotateView.addSubview(newValue!) } layoutSubviews() } } // MARK: - Initializing an Image Cropper View required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initialize() } override public init(frame: CGRect) { super.init(frame: frame) initialize() } /** Returns an image cropper view initialized with the specified image. - Parameter image: The initial image to display in the image cropper view. */ public init(image: UIImage?) { super.init(frame:CGRect.zero) initialize() self.image = image } fileprivate func initialize() { /* Create views layout. Step by step 1. Scroll view ‹‹ Image view */ scrollView = AKImageCropperScrollView() scrollView.delegate = self rotateView.addSubview(scrollView) /* 2. Overlay view with crop rectangle */ overlayView = AKImageCropperOverlayView() /* 3. Rotate view */ addSubview(rotateView) /** Add Observers To controll all parameters changing and pass them to foreground image view */ initObservers() let pressGesture = UILongPressGestureRecognizer(target: self, action: #selector(pressGestureAction(_ :))) pressGesture.minimumPressDuration = 0 pressGesture.cancelsTouchesInView = false pressGesture.delegate = self addGestureRecognizer(pressGesture) } @objc fileprivate func pressGestureAction(_ gesture: UITapGestureRecognizer) { if gesture.state == .began { beforeInteraction() } else if gesture.state == .cancelled || gesture.state == .ended { afterInteraction() } } // MARK: - UIGestureRecognizerDelegate public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true } deinit { removeObservers() #if AKImageCropperViewDEBUG print("deinit AKImageCropperView") #endif } // MARK: - Observe Scroll view values fileprivate func initObservers() { for forKeyPath in ["contentOffset", "contentSize"] { scrollView.addObserver(self, forKeyPath: forKeyPath, options: [.new, .old], context: nil) } } open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { guard let keyPath = keyPath else { return } switch keyPath { case "contentOffset": if let _ = change![NSKeyValueChangeKey.newKey] { overlayView?.matchForegroundToBackgroundScrollViewOffset() } case "contentSize": if let _ = change![NSKeyValueChangeKey.newKey] { overlayView?.matchForegroundToBackgroundScrollViewSize() } default: () } } fileprivate func removeObservers() { for forKeyPath in ["contentOffset", "contentSize"] { scrollView.removeObserver(self, forKeyPath: forKeyPath) } } // MARK: - Life cycle override open func layoutSubviews() { super.layoutSubviews() layoutSubviews(byImage: layoutByImage) } func layoutSubviews(byImage: Bool) { rotateView.frame = CGRect(origin: .zero, size: self.frame.size) let frame = reversedRect let reversedFrameWithInsetsSize = reversedFrameWithInsets.size if byImage { /* Zoom */ let fitScaleMultiplier = image == nil ? 1 : ic_CGSizeFitScaleMultiplier(image!.size, relativeToSize: reversedFrameWithInsetsSize) scrollView.maximumZoomScale = fitScaleMultiplier * 1000 scrollView.minimumZoomScale = fitScaleMultiplier scrollView.zoomScale = fitScaleMultiplier * savedProperty.scaleAspectRatio } else { /* Zoom */ let fitScaleMultiplier = ic_CGSizeFitScaleMultiplier(scrollView.visibleRect.size, relativeToSize: reversedFrameWithInsetsSize) scrollView.maximumZoomScale *= fitScaleMultiplier scrollView.minimumZoomScale *= fitScaleMultiplier scrollView.zoomScale *= fitScaleMultiplier /* Content inset */ var size: CGSize if overlayView?.alpha == 1 { size = CGSize( width : scrollView.visibleRect.size.width * fitScaleMultiplier, height : scrollView.visibleRect.size.height * fitScaleMultiplier) } else { size = ic_CGSizeFits(scrollView.contentSize, minSize: .zero, maxSize: reversedFrameWithInsetsSize) } scrollView.contentInset = centeredInsets(from: size, to: reversedFrameWithInsetsSize) /* Content offset */ let savedFitScaleMultiplier = ic_CGSizeFitScaleMultiplier(savedProperty.cropRectSize, relativeToSize: reversedFrameWithInsetsSize) var contentOffset = CGPoint( x: savedProperty.contentOffset.x * savedFitScaleMultiplier, y: savedProperty.contentOffset.y * savedFitScaleMultiplier) contentOffset.x -= scrollView.contentInset.left contentOffset.y -= scrollView.contentInset.top scrollView.contentOffset = contentOffset } scrollView.frame = frame overlayView?.frame = frame overlayView?.cropRect = scrollView.visibleRect overlayView?.layoutSubviews() } // MARK: - // MARK: ** Actions ** // MARK: Overlay actions /** Show the overlay view with crop rectangle. - Parameter duration: The total duration of the animations, measured in seconds. If you specify a negative value or 0, the changes are made without animating them. Default value is 0. - Parameter options: A mask of options indicating how you want to perform the animations. For a list of valid constants, see UIViewAnimationOptions. Default value is .curveEaseInOut. - Parameter completion: A block object to be executed when the animation sequence ends. This block has no return value and takes a single Boolean argument that indicates whether or not the animations actually finished before the completion handler was called. If the duration of the animation is 0, this block is performed at the beginning of the next run loop cycle. This parameter may be NULL. */ open func showOverlayView(animationDuration duration: TimeInterval = 0, options: UIView.AnimationOptions = .curveEaseInOut, completion: ((Bool) -> Void)? = nil) { guard let image = image, let overlayView = overlayView, !isOverlayViewActive && !isAnimation else { return } minEdgeInsets = overlayView.configuraiton.cropRectInsets savedProperty.save(scrollView: scrollView) cancelZoomingTimer() let _animations: () -> Void = { self.layoutSubviews() // Update scroll view content offsets using active zooming scale and insets. self.scrollView.contentOffset = self.contentOffset(from: self.savedProperty.contentOffsetPercentage) } let _completion: (Bool) -> Void = { isFinished in // Update zoom relative to crop rext let fillScaleMultiplier = ic_CGSizeFillScaleMultiplier(image.size, relativeToSize: overlayView.cropRect.size) self.scrollView.maximumZoomScale = fillScaleMultiplier * 1000 self.scrollView.minimumZoomScale = fillScaleMultiplier /* */ self.isAnimation = false self.isOverlayViewActive = true completion?(isFinished) } /* Show */ layoutByImage = false isAnimation = true if duration == 0 { _animations() overlayView.alpha = 1 _completion(true) } else { UIView.animate(withDuration: duration, delay: 0, options: options, animations: _animations, completion: { _ in UIView.animate(withDuration: duration, delay: 0, options: options, animations: { overlayView.alpha = 1 }, completion: _completion) }) } } /** Hide the overlay view with crop rectangle. - Parameter duration: The total duration of the animations, measured in seconds. If you specify a negative value or 0, the changes are made without animating them. Default value is 0. - Parameter options: A mask of options indicating how you want to perform the animations. For a list of valid constants, see UIViewAnimationOptions. Default value is .curveEaseInOut. - Parameter completion: A block object to be executed when the animation sequence ends. This block has no return value and takes a single Boolean argument that indicates whether or not the animations actually finished before the completion handler was called. If the duration of the animation is 0, this block is performed at the beginning of the next run loop cycle. This parameter may be NULL. */ open func hideOverlayView(animationDuration duration: TimeInterval = 0, options: UIView.AnimationOptions = .curveEaseInOut, completion: ((Bool) -> Void)? = nil) { guard let image = image, let overlayView = overlayView, isOverlayViewActive && !isAnimation else { return } minEdgeInsets = .zero savedProperty.save(scrollView: scrollView) cancelZoomingTimer() isAnimation = true let _animations: () -> Void = { self.layoutSubviews() /** Update scroll view content offsets using active zooming scale and insets. */ self.scrollView.contentOffset = self.contentOffset(from: self.savedProperty.contentOffsetPercentage) } let _completion: (Bool) -> Void = { isFinished in // Update zoom relative to crop rext let fitScaleMultiplier = ic_CGSizeFitScaleMultiplier(image.size, relativeToSize: self.reversedFrameWithInsets.size) self.scrollView.maximumZoomScale = fitScaleMultiplier * 1000 self.scrollView.minimumZoomScale = fitScaleMultiplier /* */ self.isAnimation = false self.isOverlayViewActive = false self.layoutByImage = false completion?(isFinished) } if duration == 0 { overlayView.alpha = 0 _animations() _completion(true) } else { UIView.animate(withDuration: duration, delay: 0, options: options, animations: { overlayView.alpha = 0 }, completion: { _ in UIView.animate(withDuration: duration, delay: 0, options: options, animations: _animations, completion: _completion) }) } } // MARK: Rotate /** Rotate the image on the angle in multiples of 90 degrees (M_PI_2). - Parameter angle: Rotation angle. The angle a multiple of 90 degrees (M_PI_2). - Parameter duration: The total duration of the animations, measured in seconds. If you specify a negative value or 0, the changes are made without animating them. Default value is 0. - Parameter options: A mask of options indicating how you want to perform the animations. For a list of valid constants, see UIViewAnimationOptions. Default value is .curveEaseInOut. - Parameter completion: A block object to be executed when the animation sequence ends. This block has no return value and takes a single Boolean argument that indicates whether or not the animations actually finished before the completion handler was called. If the duration of the animation is 0, this block is performed at the beginning of the next run loop cycle. This parameter may be NULL. */ open func rotate(_ angle: Double, withDuration duration: TimeInterval = 0, options: UIView.AnimationOptions = .curveEaseInOut, completion: ((Bool) -> Void)? = nil) { guard angle.truncatingRemainder(dividingBy: .pi / 2) == 0 else { return } self.angle = angle savedProperty.save(scrollView: scrollView) let _animations: () -> Void = { self.rotateView.transform = CGAffineTransform(rotationAngle: CGFloat(angle)) self.layoutSubviews() } let _completion: (Bool) -> Void = { isFinished in completion?(isFinished) } if duration == 0 { _animations() _completion(true) } else { UIView.animate(withDuration: duration, delay: 0, options: options, animations: _animations, completion: _completion) } } // MARK: Reset /** Return Cropper view to the initial state. - Parameter duration: The total duration of the animations, measured in seconds. If you specify a negative value or 0, the changes are made without animating them. Default value is 0. - Parameter options: A mask of options indicating how you want to perform the animations. For a list of valid constants, see UIViewAnimationOptions. Default value is .curveEaseInOut. - Parameter completion: A block object to be executed when the animation sequence ends. This block has no return value and takes a single Boolean argument that indicates whether or not the animations actually finished before the completion handler was called. If the duration of the animation is 0, this block is performed at the beginning of the next run loop cycle. This parameter may be NULL. */ open func reset(animationDuration duration: TimeInterval = 0, options: UIView.AnimationOptions = .curveEaseInOut, completion: ((Bool) -> Void)? = nil) { guard !isAnimation else { return } savedProperty = SavedProperty() angle = 0 cancelZoomingTimer() let _animations: () -> Void = { self.rotateView.transform = CGAffineTransform.identity let _layoutByImage = self.layoutByImage self.layoutByImage = true self.layoutSubviews() self.layoutByImage = _layoutByImage } let _completion: (Bool) -> Void = { isFinished in self.isAnimation = false completion?(isFinished) } isAnimation = true if duration == 0 { _animations() _completion(true) } else { UIView.animate(withDuration: duration, delay: 0, options: options, animations: _animations, completion: _completion) } } // MARK: - Edge insets zooming fileprivate var zoomingTimer: Timer? fileprivate func startZoomingTimer() { guard let overlayView = overlayView else { return } cancelZoomingTimer() zoomingTimer = Timer.scheduledTimer(timeInterval: overlayView.configuraiton.zoomingToFitDelay, target: self, selector: #selector(zoomAction), userInfo: nil, repeats: false) } @objc fileprivate func zoomAction() { guard let overlayView = overlayView else { return } savedProperty.save(scrollView: scrollView) overlayView.showGrid(false) overlayView.showOverlayBlur(true) UIView.animate(withDuration: overlayView.configuraiton.animation.duration, delay: 0, options: overlayView.configuraiton.animation.options, animations: { self.layoutSubviews() }) } fileprivate func cancelZoomingTimer() { zoomingTimer?.invalidate() zoomingTimer = nil } // MARK: - After interaction actions fileprivate func beforeInteraction() { guard let overlayView = overlayView, overlayView.alpha == 1.0 else { return } cancelZoomingTimer() overlayView.showGrid(true) overlayView.showOverlayBlur(false) } fileprivate func afterInteraction() { guard let overlayView = overlayView, overlayView.alpha == 1.0 else { return } startZoomingTimer() savedProperty.save(scrollView: scrollView) } // MARK: - Helper methods private func centeredInsets(from size: CGSize, to relativeSize: CGSize) -> UIEdgeInsets { let center = ic_CGPointCenters(size, relativeToSize: relativeSize) // Fix insets direct to orientation return UIEdgeInsets( top: center.y + minEdgeInsets.top, left: center.x + minEdgeInsets.left, bottom: center.y + minEdgeInsets.bottom, right: center.x + minEdgeInsets.right) } private func contentOffset(from savedContentOffsetPercentage: CGPointPercentage) -> CGPoint { var contentOffset = CGPoint( x: scrollView.contentInset.left > minEdgeInsets.left ? 0 : ((scrollView.contentSize.width - reversedFrameWithInsets.size.width) * savedContentOffsetPercentage.x), y: scrollView.contentInset.top > minEdgeInsets.left ? 0 : ((scrollView.contentSize.height - reversedFrameWithInsets.size.height) * savedContentOffsetPercentage.y)) contentOffset.x -= scrollView.contentInset.left contentOffset.y -= scrollView.contentInset.top return contentOffset } // MARK: - AKImageCropperOverlayViewDelegate func cropperOverlayViewDidChangeCropRect(_ view: AKImageCropperOverlayView, _ cropRect: CGRect) { scrollView.contentInset = UIEdgeInsets( top: cropRect.origin.y, left: cropRect.origin.x, bottom: view.frame.size.height - cropRect.size.height - cropRect.origin.y, right: view.frame.size.width - cropRect.size.width - cropRect.origin.x) if cropRect.size.height > scrollView.contentSize.height || cropRect.size.width > scrollView.contentSize.width { let fillScaleMultiplier = ic_CGSizeFillScaleMultiplier(scrollView.contentSize, relativeToSize: cropRect.size) scrollView.maximumZoomScale *= fillScaleMultiplier scrollView.minimumZoomScale *= fillScaleMultiplier scrollView.zoomScale *= fillScaleMultiplier } } // MARK: - UIScrollViewDelegate public func viewForZooming(in scrollView: UIScrollView) -> UIView? { return scrollView.subviews.first } public func scrollViewDidZoom(_ scrollView: UIScrollView) { guard layoutByImage else { return } let size = ic_CGSizeFits(scrollView.contentSize, minSize: .zero, maxSize: reversedFrameWithInsets.size) scrollView.contentInset = centeredInsets(from: size, to: reversedFrameWithInsets.size) } public func scrollViewWillBeginZooming(_ scrollView: UIScrollView, with view: UIView?) { beforeInteraction() } public func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) { afterInteraction() } public func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) { beforeInteraction() } public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { afterInteraction() } } // MARK: - AKImageCropperViewDelegate public protocol AKImageCropperViewDelegate : class { /** Tells the delegate that crop frame was changed. - Parameter view : The image cropper view. - Parameter rect : New crop rectangle origin and size. */ func imageCropperViewDidChangeCropRect(view: AKImageCropperView, cropRect rect: CGRect) } public extension AKImageCropperViewDelegate { func imageCropperViewDidChangeCropRect(view: AKImageCropperView, cropRect rect: CGRect) {} }
35.574813
400
0.610459
879b21b285380e55db77379974c4990ece3e21c4
1,327
// // XCFitWaiter.swift // XCFit // // Created by Shashikant Jagtap on 28/01/2017. // // import XCTest import Foundation @available(OSX 10.11, *) extension XCFit { open func whenIexpectElementToAppear(_ element: XCUIElement) { XCTContext.runActivity(named: "When I Expect Element \(element) to appear") { _ in let result = waitForElementToAppearCommpleted(element) XCTAssertTrue(result) } } open func whenIexpectElementTimeOut(_ element: XCUIElement) { XCTContext.runActivity(named: "When I Expect Element \(element) to Timeout") { _ in let result = waitForElementToAppearTimedOut(element) XCTAssertTrue(result) } } open func whenIexpectElementIncorrectOrder(_ element: XCUIElement) { XCTContext.runActivity(named: "When I Expect Element \(element) in incorrect order") { _ in let result = waitForElementToAppearIncorrectOrder(element) XCTAssertTrue(result) } } open func whenIexpectElementInvertedFulfillment(_ element: XCUIElement) { XCTContext.runActivity(named: "When I Expect Element \(element) in Inverted Fullfillment") { _ in let result = waitForElementToAppearinvertedFulfillment(element) XCTAssertTrue(result) } } }
30.860465
105
0.672193
ab390da61ba2924728a4b785a36d1fcb48e70d6c
175
public enum TMDBError: Error { case networkError(Error) case dataNotFound case jsonParsingError(Error) case invalidStatusCode(Int) case apiError(String) }
21.875
32
0.731429
7559d6ebd842beb32bcd6aeeee9424e447ac068e
15,957
// // BookmarksViewController.swift // DuckDuckGo // // Copyright © 2017 DuckDuckGo. 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 UIKit import Core import os.log // swiftlint:disable file_length // swiftlint:disable type_body_length class BookmarksViewController: UITableViewController { @IBOutlet weak var addFolderButton: UIBarButtonItem! @IBOutlet weak var editButton: UIBarButtonItem! @IBOutlet weak var doneButton: UIBarButtonItem! private var searchController: UISearchController? weak var delegate: BookmarksDelegate? fileprivate lazy var dataSource: MainBookmarksViewDataSource = DefaultBookmarksDataSource(alertDelegate: self) fileprivate var searchDataSource = SearchBookmarksDataSource() private var bookmarksCachingSearch: BookmarksCachingSearch? fileprivate var onDidAppearAction: () -> Void = {} override func viewDidLoad() { super.viewDidLoad() registerForNotifications() configureTableView() configureSearchIfNeeded() configureBars() applyTheme(ThemeManager.shared.currentTheme) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) onDidAppearAction() onDidAppearAction = {} } @objc func dataDidChange(notification: Notification) { tableView.reloadData() refreshEditButton() } func openEditFormWhenPresented(bookmark: Bookmark) { onDidAppearAction = { [weak self] in self?.performSegue(withIdentifier: "AddOrEditBookmark", sender: bookmark) } } func openEditFormWhenPresented(link: Link) { onDidAppearAction = { [weak self] in self?.dataSource.bookmarksManager.bookmark(forURL: link.url) { bookmark in if let bookmark = bookmark { self?.performSegue(withIdentifier: "AddOrEditBookmark", sender: bookmark) } } } } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard let item = currentDataSource.item(at: indexPath) else { return } if tableView.isEditing { tableView.deselectRow(at: indexPath, animated: true) if let bookmark = item as? Bookmark { performSegue(withIdentifier: "AddOrEditBookmark", sender: bookmark) } else if let folder = item as? BookmarkFolder { performSegue(withIdentifier: "AddOrEditBookmarkFolder", sender: folder) } } else { if let bookmark = item as? Bookmark { select(bookmark: bookmark) } else if let folder = item as? BookmarkFolder { let storyboard = UIStoryboard(name: "Bookmarks", bundle: nil) guard let viewController = storyboard.instantiateViewController(withIdentifier: "BookmarksViewController") as? BookmarksViewController else { return } viewController.dataSource = DefaultBookmarksDataSource(alertDelegate: viewController, parentFolder: folder) viewController.delegate = delegate navigationController?.pushViewController(viewController, animated: true) } } } override func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? { guard let item = currentDataSource.item(at: indexPath), item as? BookmarkFolder == nil else { return nil } let shareContextualAction = UIContextualAction(style: .normal, title: UserText.actionShare) { (_, _, completionHandler) in self.showShareSheet(for: indexPath) completionHandler(true) } shareContextualAction.backgroundColor = UIColor.cornflowerBlue return UISwipeActionsConfiguration(actions: [shareContextualAction]) } override func tableView(_ tableView: UITableView, targetIndexPathForMoveFromRowAt sourceIndexPath: IndexPath, toProposedIndexPath proposedDestinationIndexPath: IndexPath) -> IndexPath { // Can't move folders into favorites if let item = currentDataSource.item(at: sourceIndexPath), item as? BookmarkFolder != nil && proposedDestinationIndexPath.section == currentDataSource.favoritesSectionIndex { return sourceIndexPath } // Check if the proposed section is empty, if so we need to make sure the proposed row is 0, not 1 let sectionIndexPath = IndexPath(row: 0, section: proposedDestinationIndexPath.section) if currentDataSource.item(at: sectionIndexPath) == nil { return sectionIndexPath } return proposedDestinationIndexPath } private func registerForNotifications() { NotificationCenter.default.addObserver(self, selector: #selector(onApplicationBecameActive), name: UIApplication.didBecomeActiveNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(dataDidChange), name: BookmarksManager.Notifications.bookmarksDidChange, object: nil) } private func configureTableView() { tableView.dataSource = dataSource if dataSource.folder != nil { tableView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: view.frame.size.width, height: CGFloat.leastNormalMagnitude)) } } private func configureSearchIfNeeded() { guard dataSource.showSearch else { // Don't show search for sub folders return } let searchController = UISearchController(searchResultsController: nil) navigationItem.searchController = searchController searchController.obscuresBackgroundDuringPresentation = false searchController.searchBar.delegate = self searchController.searchResultsUpdater = self searchController.automaticallyShowsScopeBar = false searchController.searchBar.searchTextField.font = UIFont.semiBoldAppFont(ofSize: 16.0) // Add separator if let nv = navigationController?.navigationBar { let separator = UIView() separator.backgroundColor = .greyish nv.addSubview(separator) separator.translatesAutoresizingMaskIntoConstraints = false separator.widthAnchor.constraint(equalTo: nv.widthAnchor).isActive = true separator.leadingAnchor.constraint(equalTo: nv.leadingAnchor).isActive = true separator.bottomAnchor.constraint(equalTo: nv.bottomAnchor, constant: 1.0 / UIScreen.main.scale).isActive = true separator.heightAnchor.constraint(equalToConstant: 1.0 / UIScreen.main.scale).isActive = true } self.searchController = searchController // Initially puling down the table to reveal search bar will result in a glitch if content offset is 0 and we are using `isModalInPresentation` set to true tableView.setContentOffset(CGPoint(x: 0, y: 1), animated: false) } private var currentDataSource: MainBookmarksViewDataSource { if tableView.dataSource === dataSource { return dataSource } return searchDataSource } @objc func onApplicationBecameActive(notification: NSNotification) { tableView.reloadData() } private func configureBars() { self.navigationController?.setToolbarHidden(false, animated: true) let flexibleSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: self, action: nil) toolbarItems?.insert(flexibleSpace, at: 1) if let dataSourceTitle = dataSource.navigationTitle { title = dataSourceTitle } refreshEditButton() } private func refreshEditButton() { if currentDataSource.isEmpty || currentDataSource === searchDataSource { disableEditButton() } else if !tableView.isEditing { enableEditButton() } } private func refreshAddFolderButton() { if currentDataSource === searchDataSource { disableAddFolderButton() } else { enableAddFolderButton() } } @IBAction func onAddFolderPressed(_ sender: Any) { performSegue(withIdentifier: "AddOrEditBookmarkFolder", sender: nil) } @IBAction func onEditPressed(_ sender: UIBarButtonItem) { if tableView.isEditing && !currentDataSource.isEmpty { finishEditing() } else { startEditing() } } @IBAction func onDonePressed(_ sender: UIBarButtonItem) { dismiss() } private func startEditing() { // necessary in case a cell is swiped (which would mean isEditing is already true, and setting it again wouldn't do anything) tableView.isEditing = false tableView.isEditing = true changeEditButtonToDone() } private func finishEditing() { tableView.isEditing = false refreshEditButton() enableDoneButton() } private func enableEditButton() { editButton.title = UserText.navigationTitleEdit editButton.isEnabled = true } private func disableEditButton() { editButton.title = "" editButton.isEnabled = false } private func enableAddFolderButton() { addFolderButton.title = UserText.addbookmarkFolderButton addFolderButton.isEnabled = true } private func disableAddFolderButton() { addFolderButton.title = "" addFolderButton.isEnabled = false } private func changeEditButtonToDone() { editButton.title = UserText.navigationTitleDone doneButton.title = "" doneButton.isEnabled = false } private func enableDoneButton() { doneButton.title = UserText.navigationTitleDone doneButton.isEnabled = true } private func prepareForSearching() { finishEditing() disableEditButton() disableAddFolderButton() } private func finishSearching() { tableView.dataSource = dataSource tableView.reloadData() enableEditButton() enableAddFolderButton() } fileprivate func showShareSheet(for indexPath: IndexPath) { if let item = currentDataSource.item(at: indexPath), let bookmark = item as? Bookmark { presentShareSheet(withItems: [bookmark], fromView: self.view) } else { os_log("Invalid share link found", log: generalLog, type: .debug) } } fileprivate func select(bookmark: Bookmark) { dismiss() delegate?.bookmarksDidSelect(bookmark: bookmark) } private func dismiss() { delegate?.bookmarksUpdated() if let searchController = searchController, searchController.isActive { searchController.dismiss(animated: false) { self.dismiss(animated: true, completion: nil) } } else { dismiss(animated: true, completion: nil) } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let viewController = segue.destination.children.first as? AddOrEditBookmarkFolderViewController { viewController.hidesBottomBarWhenPushed = true viewController.setExistingFolder(sender as? BookmarkFolder, initialParentFolder: dataSource.folder) } else if let viewController = segue.destination.children.first as? AddOrEditBookmarkViewController { viewController.hidesBottomBarWhenPushed = true viewController.setExistingBookmark(sender as? Bookmark, initialParentFolder: dataSource.folder) } } override func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { if (searchController?.searchBar.bounds.height ?? 0) == 0 { // Disable drag-to-dismiss if we start scrolling and search bar is still hidden isModalInPresentation = true } } override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { guard let searchController = searchController else { return } if isModalInPresentation, searchController.searchBar.bounds.height > 0 { // Re-enable drag-to-dismiss if needed isModalInPresentation = false } } override func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { guard let searchController = searchController else { return } if isModalInPresentation, searchController.searchBar.bounds.height > 0 { // Re-enable drag-to-dismiss if needed isModalInPresentation = false } } } extension BookmarksViewController: UISearchBarDelegate { func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) { bookmarksCachingSearch = BookmarksCachingSearch() } func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { guard !searchText.isEmpty else { if tableView.dataSource !== dataSource { finishSearching() } return } if currentDataSource !== searchDataSource { prepareForSearching() tableView.dataSource = searchDataSource } let bookmarksSearch = bookmarksCachingSearch ?? BookmarksCachingSearch() searchDataSource.performSearch(query: searchText, searchEngine: bookmarksSearch) { self.tableView.reloadData() } } func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { finishSearching() } } extension BookmarksViewController: UISearchResultsUpdating { func updateSearchResults(for searchController: UISearchController) { finishEditing() } } extension BookmarksViewController: BookmarksSectionDataSourceDelegate { func bookmarksSectionDataSourceDidRequestViewControllerForDeleteAlert( _ bookmarksSectionDataSource: BookmarksSectionDataSource) -> UIViewController { return self } } extension BookmarksViewController: Themable { func decorate(with theme: Theme) { decorateNavigationBar(with: theme) decorateToolbar(with: theme) overrideSystemTheme(with: theme) searchController?.searchBar.searchTextField.textColor = theme.searchBarTextColor tableView.separatorColor = theme.tableCellSeparatorColor navigationController?.view.backgroundColor = tableView.backgroundColor tableView.reloadData() } } // swiftlint:enable type_body_length // swiftlint:enable file_length
36.9375
163
0.648618
20dd63a116077eb56b56dd2e302650ac7cd29347
14,239
// // Pill.swift // Pill // // Created by Chris Zielinski on 8/21/18. // Copyright © 2018 Big Z Labs. All rights reserved. // import Cocoa open class PillTextView: NSTextView { /// The pill text view's delegate. /// /// The default behavior of pill replacement is as so: /// - The enter key inserts the pill's text content. /// - Double clicking and pressing the delete key, deletes the pill. public weak var pillTextViewDelegate: PillTextViewDelegate! { didSet { // Can never be nil. if pillTextViewDelegate == nil { pillTextViewDelegate = self } } } /// The currently selected (focused) pill in the text view. open weak var selectedPill: Pill? /// The strong referenced pill text storage object. Also, accessible from the `textStorage` property. Property initialized with the `PillTextStorage` object returned by `createPillTextStorage()`. public var pillTextStorage: PillTextStorage! /// The weak referenced pill layout manager object. Also, accessible from the `layoutManager` property. Property initialized with the `PillLayoutManager` object returned by `createPillLayoutManager()`. public private(set) weak var pillLayoutManager: PillLayoutManager! /// Whether there is a pill that is currently selected (focused). public var hasSelectedPill: Bool { return selectedPill != nil } /// Whether the text view has any visible pills. public var hasPills: Bool { return pillTextStorage.hasPills } override public init(frame frameRect: NSRect) { super.init(frame: frameRect) } override public init(frame frameRect: NSRect, textContainer container: NSTextContainer?) { super.init(frame: frameRect, textContainer: container) commonInit() } required public init?(coder: NSCoder) { super.init(coder: coder) } override open func awakeFromNib() { super.awakeFromNib() commonInit() } open func commonInit() { let createdPillLayoutManager = createPillLayoutManager() pillLayoutManager = createdPillLayoutManager pillTextStorage = createPillTextStorage() textContainer!.replaceLayoutManager(createdPillLayoutManager) layoutManager!.replaceTextStorage(pillTextStorage) pillTextViewDelegate = self } /// Creates the back-end pill text storage instance used by the front-end pill text view object. The default implementation returns an instance of `PillTextStorage`; however, descendants can override this method and return a subclass of `PillTextStorage`. /// /// - Returns: The `PillTextStorage`, or subclass thereof, object used by the pill text view object. open func createPillTextStorage() -> PillTextStorage { return PillTextStorage() } /// Creates the back-end pill layout manager instance used by the front-end pill text view class. The default implementation returns an instance of `PillLayoutManager`; however, descendants can override this method and return a subclass of `PillLayoutManager`. /// /// - Returns: The `PillLayoutManager`, or subclass thereof, object used by the pill text view object. open func createPillLayoutManager() -> PillLayoutManager { return PillLayoutManager() } } // MARK: - Pill Query Methods extension PillTextView { /// Returns the pill falling under the given point, expressed in the text view's coordinate system. /// /// - Parameter point: The point for which to return the pill, in coordinates of the text view. /// - Returns: The pill falling under the given point, expressed in the text view's coordinate system. internal func pill(at point: NSPoint) -> Pill? { let pointInTextContainer = convertToTextContainer(point) guard let characterIndex = pillLayoutManager.characterIndex(for: pointInTextContainer, in: textContainer!) else { return nil } return pillTextStorage.pill(at: characterIndex) } } // MARK: - Pill Selection Methods extension PillTextView { /// Calls the necessary methods to redraw the specified pill as highlighted or unhighlighted. /// /// - Parameters: /// - pill: The pill that will be redrawn. /// - flag: When `true`, redraws the pill as highlighted; otherwise, redraws it normally. private func highlight(_ pill: Pill, flag: Bool) { if let characterRange = pillTextStorage.characterRange(of: pill) { pill.pillAttachmentCell.highlight(flag, withFrame: pill.bounds, in: self) pillLayoutManager.invalidateDisplay(forCharacterRange: characterRange) } } /// Selects the given pill, deselecting a currently selected one. Redrawing involved pills with appropriate highlighting. /// /// - Parameter pill: The pill to select. public func selectPill(_ pill: Pill) { guard pill != selectedPill else { return } deselectSelectedPill() highlight(pill, flag: true) selectedPill = pill if let characterIndex = pillTextStorage.characterIndex(of: pill) { setSelectedRange(NSRange(location: characterIndex, length: 1)) } } /// Deselects the currently select pill, if there is one. public func deselectSelectedPill() { if let selectedPill = selectedPill { highlight(selectedPill, flag: false) self.selectedPill = nil } } } // MARK: - Pill Interaction Methods extension PillTextView { /// Handles the user's interaction with a pill by querying the replacement action from the pill view's delegate and invoking the respective replacement methods. /// /// - Parameters: /// - interaction: The type of interaction to handle. /// - pill: The pill to replace. internal func handlePillInteraction(_ interaction: Pill.UserInteraction, for pill: Pill) { let replacementAction = pillTextViewDelegate.pillTextView(self, userInteraction: interaction, for: pill) switch replacementAction { case .insert: crushPill(pill) case .delete: swallowPill(pill) case .ignore: () } } /// Replaces the pill with an empty string. /// /// - Parameter pill: The pill to replace. public func deletePill(_ pill: Pill) { if let characterRange = pillTextStorage.characterRange(of: pill) { selectedPill = nil shouldChangeText(in: characterRange, replacementString: "") pillTextStorage.deletePill(at: characterRange.location) didChangeText() setSelectedRange(NSRange(location: characterRange.location, length: 0)) } } /// Replaces the pill with its text contents. /// /// - Parameter pill: The pill to replace. public func insertText(for pill: Pill) { if let characterRange = pillTextStorage.characterRange(of: pill) { selectedPill = nil shouldChangeText(in: characterRange, replacementString: pill.contentStringValue) pillTextStorage.replaceCharacters(in: characterRange, with: pill.contentStringValue) didChangeText() } } /// Replaces the pill with an empty string. /// /// - Parameter pill: The pill to replace. private func swallowPill(_ pill: Pill) { deletePill(pill) } /// Replaces the pill with its text contents. /// /// - Parameter pill: The pill to open. private func crushPill(_ pill: Pill) { insertText(for: pill) } } // MARK: - Overridden Properties extension PillTextView { override open var defaultParagraphStyle: NSParagraphStyle? { get { return super.defaultParagraphStyle } set { super.defaultParagraphStyle = newValue if let paragraphStyle = defaultParagraphStyle { pillTextStorage.addAttribute(.paragraphStyle, value: paragraphStyle) } } } override open var typingAttributes: [NSAttributedStringKey: Any] { get { return super.typingAttributes } set { // Never want to type in the AppleColorEmoji font. 🚮 guard (newValue[.font] as? NSFont)?.fontName != "AppleColorEmoji" else { return } super.typingAttributes = newValue } } } // MARK: - Overridden Methods extension PillTextView { override open func changeFont(_ sender: Any?) { super.changeFont(sender) Pill.sharedFont = NSFontManager.shared.convert(Pill.sharedFont) pillLayoutManager.invalidateAllPills() } override open func writeSelection(to pboard: NSPasteboard, type: NSPasteboard.PasteboardType) -> Bool { let writeRange = selectedRange() if pillTextStorage.containsAttachments(in: writeRange) { // Currently only support copying plain text. let mutableString = NSMutableAttributedString(attributedString: pillTextStorage.attributedSubstring(from: writeRange)) mutableString.enumerateAttribute(.attachment, in: mutableString.contentRange, options: .longestEffectiveRangeNotRequired) { (attachment, range, _) in guard let pill = attachment as? Pill else { return } mutableString.replaceCharacters(in: range, with: pill.contentStringValue) } pboard.clearContents() pboard.writeObjects([mutableString.mutableString]) return true } else { return super.writeSelection(to: pboard, type: type) } } } // MARK: - Text Selection Methods extension PillTextView { override open func setSelectedRange(_ charRange: NSRange, affinity: NSSelectionAffinity, stillSelecting stillSelectingFlag: Bool) { // If selection is a pill, select it. This is meant for a drag selection. if let selectionPill = pillTextStorage.pill(at: charRange) { selectPill(selectionPill) } else { // Otherwise, deselect any currently selected pill. deselectSelectedPill() } super.setSelectedRange(charRange, affinity: affinity, stillSelecting: stillSelectingFlag) } } // MARK: - Responder Methods extension PillTextView { override open func mouseDown(with event: NSEvent) { guard let pill = pill(at: convert(event.locationInWindow, from: nil)) else { // Click was not on a pill, so deselect any select pill and call super. deselectSelectedPill() return super.mouseDown(with: event) } if pill != selectedPill { // Pill is not already selected, so select it. selectPill(pill) } else if event.clickCount > 1 { // Pill interaction was (at least) a double click, so handle it, appropriately. handlePillInteraction(.doubleClick, for: pill) } } override open func insertTab(_ sender: Any?) { if let selectedPill = selectedPill { // If there's a following pill, select it. Otherwise, do nothing. if let nextPill = pillTextStorage.pillFollowing(selectedPill) { selectPill(nextPill) } } else { // No currently selected pill, find closest one and select it. if let closestPill = pillTextStorage.closestPill(to: selectedRange().location) { selectPill(closestPill) } else { // Otherwise, call super. super.insertTab(sender) } } } override open func insertNewline(_ sender: Any?) { if let selectedPill = selectedPill { handlePillInteraction(.enter, for: selectedPill) } else { super.insertNewline(sender) } } override open func deleteBackward(_ sender: Any?) { if let selectedPill = selectedPill { handlePillInteraction(.delete, for: selectedPill) } else { super.deleteBackward(sender) } } override open func moveLeft(_ sender: Any?) { let currentSelectedRange = selectedRange() if hasSelectedPill { // There's a selected pill, so deselect it and call super (which will move the insertion point to the left side of the pill). // Note: There may be a neighboring pill to the left, so need to check this case before the next one. deselectSelectedPill() } else if currentSelectedRange.length == 0, let pill = pillTextStorage.pill(at: currentSelectedRange.location - 1) { // No current selection and previous character index is a pill, so just select it. return selectPill(pill) } else { // Otherwise, deselect a selected pill, if there is one. deselectSelectedPill() } super.moveLeft(sender) } override open func moveRight(_ sender: Any?) { let currentSelectedRange = selectedRange() if hasSelectedPill { // There's a selected pill, so deselect it and call super (which will move the insertion point to the right side of the pill). // Note: There may be a neighboring pill to the right, so need to check this case before the next one. deselectSelectedPill() } else if currentSelectedRange.length == 0, let pill = pillTextStorage.pill(at: currentSelectedRange.location) { // No current selection and bordering a pill, so just select it. return selectPill(pill) } else { // Otherwise, deselect a selected pill, if there is one. deselectSelectedPill() } super.moveRight(sender) } } // MARK: - Default Delegate Methods extension PillTextView: PillTextViewDelegate { open func pillTextView(_ pillTextView: PillTextView, userInteraction: Pill.UserInteraction, for pill: Pill) -> Pill.ReplacementAction { switch userInteraction { case .enter: return .insert default: return .delete } } }
38.174263
264
0.649343
9baf6629b0dc8641c5261f71de8bfdc71debe7ee
2,976
// // GYZGoodsDetailsHeaderView.swift // baking // 商品详情header // Created by gouyz on 2017/4/17. // Copyright © 2017年 gouyz. All rights reserved. // import UIKit class GYZGoodsDetailsHeaderView: UIView { // MARK: 生命周期方法 override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = kWhiteColor setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setupUI(){ addSubview(headerImg) addSubview(nameLab) addSubview(saleLab) addSubview(priceLab) headerImg.snp.makeConstraints { (make) in make.top.left.right.equalTo(self) make.bottom.equalTo(nameLab.snp.top) } nameLab.snp.makeConstraints { (make) in make.bottom.equalTo(saleLab.snp.top) make.left.equalTo(kMargin) make.right.equalTo(-kMargin) make.height.equalTo(30) } saleLab.snp.makeConstraints { (make) in make.bottom.equalTo(priceLab.snp.top) make.left.right.equalTo(nameLab) make.height.equalTo(nameLab) } priceLab.snp.makeConstraints { (make) in make.bottom.equalTo(-kMargin) make.left.right.equalTo(nameLab) make.height.equalTo(nameLab) } } /// 商品logo lazy var headerImg : UIImageView = UIImageView.init(image: UIImage.init(named: "icon_banner_default")) /// 商品名称 lazy var nameLab : UILabel = { let lab = UILabel() lab.font = k15Font lab.textColor = kBlackFontColor return lab }() /// 销量 lazy var saleLab : UILabel = { let lab = UILabel() lab.font = k12Font lab.textColor = kGaryFontColor return lab }() /// 商品价格 lazy var priceLab : UILabel = { let lab = UILabel() lab.font = k15Font lab.textColor = kYellowFontColor return lab }() /// 填充数据 var dataModel : GYZGoodsDetailModel?{ didSet{ if let model = dataModel { let urlArr = GYZTool.getImgUrls(url: model.goods_img) if urlArr != nil { headerImg.kf.setImage(with: URL.init(string: (urlArr?[0])!), placeholder: UIImage.init(named: "icon_banner_default"), options: nil, progressBlock: nil, completionHandler: nil) }else{ headerImg.image = UIImage.init(named: "icon_banner_default") } //设置数据 nameLab.text = model.cn_name saleLab.text = "月销\(model.month_num!)单" if model.attr != nil { let attrModel = model.attr?[0] priceLab.text = "¥" + (attrModel?.price)! } } } } }
28.615385
195
0.537634
e605a4b3668a99b90428518ff9a82686db7feab5
6,104
// // JobCompanyCell.swift // AtalasDream // // Created by GuoGongbin on 6/27/17. // Copyright © 2017 GuoGongbin. All rights reserved. // import UIKit fileprivate let LabelFontSize: CGFloat = 16 class JobCompanyCell: BaseCollectionViewCell { let labelHeight: CGFloat = 20 let nameLabelWidth: CGFloat = 50 var job: Job? { didSet{ if let companyName = job?.company { companyNameLabel.text = companyName } if let email = job?.email { emailLabel.text = email } if let phone = job?.phoneNumber { phoneLabel.text = phone } if let location = job?.location { locationLabel.text = location } } } let company: UILabel = { let label = UILabel() label.text = "公司:" label.font = UIFont.boldSystemFont(ofSize: JobConstant.LabelFontSize) label.translatesAutoresizingMaskIntoConstraints = false return label }() let companyNameLabel: UILabel = { let label = UILabel() label.font = UIFont.boldSystemFont(ofSize: JobConstant.LabelFontSize) label.translatesAutoresizingMaskIntoConstraints = false return label }() let email: UILabel = { let label = UILabel() label.text = "邮箱:" label.font = UIFont.systemFont(ofSize: JobConstant.LabelFontSize) label.translatesAutoresizingMaskIntoConstraints = false return label }() let emailLabel: UILabel = { let label = UILabel() label.font = UIFont.systemFont(ofSize: JobConstant.LabelFontSize) label.translatesAutoresizingMaskIntoConstraints = false return label }() let phone: UILabel = { let label = UILabel() label.text = "电话:" label.font = UIFont.systemFont(ofSize: JobConstant.LabelFontSize) label.translatesAutoresizingMaskIntoConstraints = false return label }() let phoneLabel: UILabel = { let label = UILabel() label.font = UIFont.systemFont(ofSize: JobConstant.LabelFontSize) label.translatesAutoresizingMaskIntoConstraints = false return label }() let location: UILabel = { let label = UILabel() label.text = "地址:" label.font = UIFont.systemFont(ofSize: JobConstant.LabelFontSize) label.translatesAutoresizingMaskIntoConstraints = false return label }() let locationLabel: UILabel = { let label = UILabel() label.font = UIFont.systemFont(ofSize: JobConstant.LabelFontSize) label.translatesAutoresizingMaskIntoConstraints = false return label }() override func setupViews() { backgroundColor = .white addSubview(company) company.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 20).isActive = true company.topAnchor.constraint(equalTo: self.topAnchor, constant: 10).isActive = true company.widthAnchor.constraint(equalToConstant: nameLabelWidth).isActive = true company.heightAnchor.constraint(equalToConstant: labelHeight).isActive = true addSubview(companyNameLabel) companyNameLabel.leftAnchor.constraint(equalTo: company.rightAnchor, constant: 5).isActive = true companyNameLabel.topAnchor.constraint(equalTo: company.topAnchor).isActive = true companyNameLabel.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -20).isActive = true companyNameLabel.heightAnchor.constraint(equalToConstant: labelHeight).isActive = true addSubview(email) email.leftAnchor.constraint(equalTo: company.leftAnchor).isActive = true email.topAnchor.constraint(equalTo: company.bottomAnchor, constant: 5).isActive = true email.widthAnchor.constraint(equalToConstant: nameLabelWidth).isActive = true email.heightAnchor.constraint(equalToConstant: labelHeight).isActive = true addSubview(emailLabel) emailLabel.leftAnchor.constraint(equalTo: companyNameLabel.leftAnchor).isActive = true emailLabel.rightAnchor.constraint(equalTo: companyNameLabel.rightAnchor).isActive = true emailLabel.topAnchor.constraint(equalTo: companyNameLabel.bottomAnchor, constant: 5).isActive = true emailLabel.heightAnchor.constraint(equalToConstant: labelHeight).isActive = true addSubview(phone) phone.leftAnchor.constraint(equalTo: company.leftAnchor).isActive = true phone.topAnchor.constraint(equalTo: email.bottomAnchor, constant: 5).isActive = true phone.widthAnchor.constraint(equalToConstant: nameLabelWidth).isActive = true phone.heightAnchor.constraint(equalToConstant: labelHeight).isActive = true addSubview(phoneLabel) phoneLabel.leftAnchor.constraint(equalTo: companyNameLabel.leftAnchor).isActive = true phoneLabel.rightAnchor.constraint(equalTo: companyNameLabel.rightAnchor).isActive = true phoneLabel.topAnchor.constraint(equalTo: emailLabel.bottomAnchor, constant: 5).isActive = true phoneLabel.heightAnchor.constraint(equalToConstant: labelHeight).isActive = true addSubview(location) location.leftAnchor.constraint(equalTo: company.leftAnchor).isActive = true location.topAnchor.constraint(equalTo: phone.bottomAnchor, constant: 5).isActive = true location.widthAnchor.constraint(equalToConstant: nameLabelWidth).isActive = true location.heightAnchor.constraint(equalToConstant: labelHeight).isActive = true addSubview(locationLabel) locationLabel.leftAnchor.constraint(equalTo: companyNameLabel.leftAnchor).isActive = true locationLabel.rightAnchor.constraint(equalTo: companyNameLabel.rightAnchor).isActive = true locationLabel.topAnchor.constraint(equalTo: phoneLabel.bottomAnchor, constant: 5).isActive = true locationLabel.heightAnchor.constraint(equalToConstant: labelHeight).isActive = true } }
43.913669
108
0.687418
383e0e69fa55fc831b2fea3baef59ae1ff57ae98
4,432
// // ShareApp.swift // PaintCodeKit_Example // // Created by Alberto Aznar de los Ríos on 04/05/2019. // Copyright © 2019 CocoaPods. All rights reserved. // import Foundation import PaintCodeKit extension PaintCodeImages { class func drawShareApp(frame targetFrame: CGRect = CGRect(x: 0, y: 0, width: 400, height: 400), resizing: ResizingBehavior = .aspectFit) { /// General Declarations let context = UIGraphicsGetCurrentContext()! /// Resize to Target Frame context.saveGState() let resizedFrame = resizing.apply(rect: CGRect(x: 0, y: 0, width: 24, height: 24), target: targetFrame) context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY) context.scaleBy(x: resizedFrame.width / 24, y: resizedFrame.height / 24) /// Combined Shape let combinedShape = UIBezierPath() combinedShape.move(to: CGPoint(x: 10, y: 3.41)) combinedShape.addLine(to: CGPoint(x: 10, y: 14)) combinedShape.addCurve(to: CGPoint(x: 9, y: 15), controlPoint1: CGPoint(x: 10, y: 14.55), controlPoint2: CGPoint(x: 9.55, y: 15)) combinedShape.addCurve(to: CGPoint(x: 8, y: 14), controlPoint1: CGPoint(x: 8.45, y: 15), controlPoint2: CGPoint(x: 8, y: 14.55)) combinedShape.addLine(to: CGPoint(x: 8, y: 3.41)) combinedShape.addLine(to: CGPoint(x: 5.71, y: 5.71)) combinedShape.addCurve(to: CGPoint(x: 4.29, y: 5.71), controlPoint1: CGPoint(x: 5.32, y: 6.1), controlPoint2: CGPoint(x: 4.68, y: 6.1)) combinedShape.addCurve(to: CGPoint(x: 4.29, y: 4.29), controlPoint1: CGPoint(x: 3.9, y: 5.32), controlPoint2: CGPoint(x: 3.9, y: 4.68)) combinedShape.addLine(to: CGPoint(x: 8.29, y: 0.29)) combinedShape.addCurve(to: CGPoint(x: 9.71, y: 0.29), controlPoint1: CGPoint(x: 8.68, y: -0.1), controlPoint2: CGPoint(x: 9.32, y: -0.1)) combinedShape.addLine(to: CGPoint(x: 13.71, y: 4.29)) combinedShape.addCurve(to: CGPoint(x: 13.71, y: 5.71), controlPoint1: CGPoint(x: 14.1, y: 4.68), controlPoint2: CGPoint(x: 14.1, y: 5.32)) combinedShape.addCurve(to: CGPoint(x: 12.29, y: 5.71), controlPoint1: CGPoint(x: 13.32, y: 6.1), controlPoint2: CGPoint(x: 12.68, y: 6.1)) combinedShape.addLine(to: CGPoint(x: 10, y: 3.41)) combinedShape.close() combinedShape.move(to: CGPoint(x: 0, y: 11)) combinedShape.addCurve(to: CGPoint(x: 1, y: 10), controlPoint1: CGPoint(x: 0, y: 10.45), controlPoint2: CGPoint(x: 0.45, y: 10)) combinedShape.addCurve(to: CGPoint(x: 2, y: 11), controlPoint1: CGPoint(x: 1.55, y: 10), controlPoint2: CGPoint(x: 2, y: 10.45)) combinedShape.addLine(to: CGPoint(x: 2, y: 19)) combinedShape.addCurve(to: CGPoint(x: 3, y: 20), controlPoint1: CGPoint(x: 2, y: 19.55), controlPoint2: CGPoint(x: 2.45, y: 20)) combinedShape.addLine(to: CGPoint(x: 15, y: 20)) combinedShape.addCurve(to: CGPoint(x: 16, y: 19), controlPoint1: CGPoint(x: 15.55, y: 20), controlPoint2: CGPoint(x: 16, y: 19.55)) combinedShape.addLine(to: CGPoint(x: 16, y: 11)) combinedShape.addCurve(to: CGPoint(x: 17, y: 10), controlPoint1: CGPoint(x: 16, y: 10.45), controlPoint2: CGPoint(x: 16.45, y: 10)) combinedShape.addCurve(to: CGPoint(x: 18, y: 11), controlPoint1: CGPoint(x: 17.55, y: 10), controlPoint2: CGPoint(x: 18, y: 10.45)) combinedShape.addLine(to: CGPoint(x: 18, y: 19)) combinedShape.addCurve(to: CGPoint(x: 15, y: 22), controlPoint1: CGPoint(x: 18, y: 20.66), controlPoint2: CGPoint(x: 16.66, y: 22)) combinedShape.addLine(to: CGPoint(x: 3, y: 22)) combinedShape.addCurve(to: CGPoint(x: 0, y: 19), controlPoint1: CGPoint(x: 1.34, y: 22), controlPoint2: CGPoint(x: 0, y: 20.66)) combinedShape.addLine(to: CGPoint(x: 0, y: 11)) combinedShape.close() context.saveGState() context.translateBy(x: 3, y: 1) UIColor.black.setFill() combinedShape.fill() context.restoreGState() /// Combined Shape (Outline Mask) context.saveGState() combinedShape.apply(CGAffineTransform(translationX: 3, y: 1)) combinedShape.addClip() /// COLOR/ black // Warning: New symbols are not supported. context.restoreGState() // End Combined Shape (Outline Mask) context.restoreGState() } }
56.820513
146
0.630866