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
6a92d7436de57b632a7f1eb5a81e8f0a1627b94f
3,029
// // Tweet.swift // TwitterClone // // Created by Poojan Dave on 2/5/17. // Copyright © 2017 Poojan Dave. All rights reserved. // import UIKit //Tweet model is type NSObject class Tweet: NSObject { //properties for all relevant data var text: String? var timestamp: Date? //count properties, setting them to 0 var retweetCount: Int = 0 var favoritesCount: Int = 0 //isFavorite and is Retweeted property, setting them to false var isFavorited: Bool = false var isRetweeted: Bool = false //id for the tweet var idStr: String //user that created the tweet var user: User? //JSON for tweet var tweetDictionary: NSDictionary //Constructor that parses through the individual tweet dictionary init(dictionary: NSDictionary) { //store complete JSON dictionary tweetDictionary = dictionary //Initializing the user user = User(dictionary: dictionary["user"] as! NSDictionary) //Retrieving the text text = dictionary["text"] as? String //Retrieving the count //If nil, then the value is 0 retweetCount = (dictionary["retweet_count"] as? Int) ?? 0 favoritesCount = (dictionary["favorite_count"] as? Int) ?? 0 //Retrieving timestamp as String let timestampString = dictionary["created_at"] as? String //Safely unwrapping the timestampString if let timestampString = timestampString { //Declaring Dateformatter() let formatter = DateFormatter() //set the format for the date formatter.dateFormat = "EEE MMM d HH:mm:ss Z y" //format the timestampString using the dateFormatter() timestamp = formatter.date(from: timestampString) } //Figures out if favorited or retweeted by currentuser isFavorited = (dictionary["favorited"] as? Bool)! isRetweeted = (dictionary["retweeted"] as? Bool)! //Retrieves the id for the tweet idStr = (dictionary["id_str"] as? String)! } //Input: dictionaries of tweets //Adds individual tweets to array //Return: array of tweets class func tweetsWithArray(dictionaries: [NSDictionary]) -> [Tweet] { //Created an array of Tweet var tweets = [Tweet]() //Go through each dictionary to add to array for dictionary in dictionaries { //Initialize the Tweet and store it in tweet let tweet = Tweet(dictionary: dictionary) //Add to array tweets tweets.append(tweet) } return tweets } //Input: 1 tweet as a dictionary class func tweetAsDictionary (_ dict: NSDictionary) -> Tweet { //tweet is parsed and initialized let tweet = Tweet(dictionary: dict) return tweet } }
28.847619
73
0.595246
69ed56e85ce51571766bbed46f3632f12c96b243
12,718
// // Publishers.Sequence.swift // // // Created by Sergej Jaskiewicz on 19.06.2019. // extension Publishers { /// A publisher that publishes a given sequence of elements. /// /// When the publisher exhausts the elements in the sequence, the next request /// causes the publisher to finish. public struct Sequence<Elements: Swift.Sequence, Failure: Error>: Publisher { public typealias Output = Elements.Element /// The sequence of elements to publish. public let sequence: Elements /// Creates a publisher for a sequence of elements. /// /// - Parameter sequence: The sequence of elements to publish. public init(sequence: Elements) { self.sequence = sequence } public func receive<SubscriberType: Subscriber>(subscriber: SubscriberType) where Failure == SubscriberType.Failure, Elements.Element == SubscriberType.Input { if let inner = Inner(downstream: subscriber, sequence: sequence) { subscriber.receive(subscription: inner) } else { subscriber.receive(subscription: Subscriptions.empty) subscriber.receive(completion: .finished) } } } } extension Publishers.Sequence { private final class Inner<Downstream: Subscriber, Elements: Sequence, Failure> : Subscription, CustomStringConvertible, CustomReflectable where Downstream.Input == Elements.Element, Downstream.Failure == Failure { typealias Iterator = Elements.Iterator typealias Element = Elements.Element private var _downstream: Downstream? private var _sequence: Elements? private var _iterator: Iterator? private var _nextValue: Element? init?(downstream: Downstream, sequence: Elements) { // Early exit if the sequence is empty var iterator = sequence.makeIterator() guard iterator.next() != nil else { return nil } _downstream = downstream _sequence = sequence _iterator = sequence.makeIterator() _nextValue = iterator.next() } var description: String { return _sequence.map(String.init(describing:)) ?? "Sequence" } var customMirror: Mirror { let children: CollectionOfOne<(label: String?, value: Any)> = CollectionOfOne(("sequence", _sequence ?? [Element]())) return Mirror(self, children: children) } func request(_ demand: Subscribers.Demand) { guard let downstream = _downstream else { return } var demand = demand while demand > 0 { if let nextValue = _nextValue { demand += downstream.receive(nextValue) demand -= 1 } _nextValue = _iterator?.next() if _nextValue == nil { _downstream?.receive(completion: .finished) cancel() break } } } func cancel() { _downstream = nil _iterator = nil _sequence = nil } } } extension Publishers.Sequence: Equatable where Elements: Equatable {} extension Publishers.Sequence where Failure == Never { public func min( by areInIncreasingOrder: (Elements.Element, Elements.Element) -> Bool ) -> Optional<Elements.Element>.OCombine.Publisher { return .init(sequence.min(by: areInIncreasingOrder)) } public func max( by areInIncreasingOrder: (Elements.Element, Elements.Element) -> Bool ) -> Optional<Elements.Element>.OCombine.Publisher { return .init(sequence.max(by: areInIncreasingOrder)) } public func first( where predicate: (Elements.Element) -> Bool ) -> Optional<Elements.Element>.OCombine.Publisher { return .init(sequence.first(where: predicate)) } } extension Publishers.Sequence { public func allSatisfy( _ predicate: (Elements.Element) -> Bool ) -> Result<Bool, Failure>.OCombine.Publisher { return .init(sequence.allSatisfy(predicate)) } public func tryAllSatisfy( _ predicate: (Elements.Element) throws -> Bool ) -> Result<Bool, Error>.OCombine.Publisher { return .init(Result { try sequence.allSatisfy(predicate) }) } public func collect() -> Result<[Elements.Element], Failure>.OCombine.Publisher { return .init(Array(sequence)) } public func compactMap<ElementOfResult>( _ transform: (Elements.Element) -> ElementOfResult? ) -> Publishers.Sequence<[ElementOfResult], Failure> { return .init(sequence: sequence.compactMap(transform)) } public func contains( where predicate: (Elements.Element) -> Bool ) -> Result<Bool, Failure>.OCombine.Publisher { return .init(sequence.contains(where: predicate)) } public func tryContains( where predicate: (Elements.Element) throws -> Bool ) -> Result<Bool, Error>.OCombine.Publisher { return .init(Result { try sequence.contains(where: predicate) }) } public func drop( while predicate: (Elements.Element) -> Bool ) -> Publishers.Sequence<DropWhileSequence<Elements>, Failure> { return .init(sequence: sequence.drop(while: predicate)) } public func dropFirst( _ count: Int = 1 ) -> Publishers.Sequence<DropFirstSequence<Elements>, Failure> { return .init(sequence: sequence.dropFirst(count)) } public func filter( _ isIncluded: (Elements.Element) -> Bool ) -> Publishers.Sequence<[Elements.Element], Failure> { return .init(sequence: sequence.filter(isIncluded)) } public func ignoreOutput() -> Empty<Elements.Element, Failure> { return .init() } public func map<ElementOfResult>( _ transform: (Elements.Element) -> ElementOfResult ) -> Publishers.Sequence<[ElementOfResult], Failure> { return .init(sequence: sequence.map(transform)) } public func prefix( _ maxLength: Int ) -> Publishers.Sequence<PrefixSequence<Elements>, Failure> { return .init(sequence: sequence.prefix(maxLength)) } public func prefix( while predicate: (Elements.Element) -> Bool ) -> Publishers.Sequence<[Elements.Element], Failure> { return .init(sequence: sequence.prefix(while: predicate)) } public func reduce<Accumulator>( _ initialResult: Accumulator, _ nextPartialResult: @escaping (Accumulator, Elements.Element) -> Accumulator ) -> Result<Accumulator, Failure>.OCombine.Publisher { return .init(sequence.reduce(initialResult, nextPartialResult)) } public func tryReduce<Accumulator>( _ initialResult: Accumulator, _ nextPartialResult: @escaping (Accumulator, Elements.Element) throws -> Accumulator ) -> Result<Accumulator, Error>.OCombine.Publisher { return .init(Result { try sequence.reduce(initialResult, nextPartialResult) }) } public func replaceNil<ElementOfResult>( with output: ElementOfResult ) -> Publishers.Sequence<[Elements.Element], Failure> where Elements.Element == ElementOfResult? { return .init(sequence: sequence.map { $0 ?? output }) } public func scan<ElementOfResult>( _ initialResult: ElementOfResult, _ nextPartialResult: @escaping (ElementOfResult, Elements.Element) -> ElementOfResult ) -> Publishers.Sequence<[ElementOfResult], Failure> { var accumulator = initialResult return .init(sequence: sequence.map { accumulator = nextPartialResult(accumulator, $0) return accumulator }) } public func setFailureType<NewFailure: Error>( to error: NewFailure.Type ) -> Publishers.Sequence<Elements, NewFailure> { return .init(sequence: sequence) } } extension Publishers.Sequence where Elements.Element: Equatable { public func removeDuplicates() -> Publishers.Sequence<[Elements.Element], Failure> { var previous: Elements.Element? var result = [Elements.Element]() for element in sequence where element != previous { result.append(element) previous = element } return .init(sequence: result) } public func contains( _ output: Elements.Element ) -> Result<Bool, Failure>.OCombine.Publisher { return .init(sequence.contains(output)) } } extension Publishers.Sequence where Failure == Never, Elements.Element: Comparable { public func min() -> Optional<Elements.Element>.OCombine.Publisher { return .init(sequence.min()) } public func max() -> Optional<Elements.Element>.OCombine.Publisher { return .init(sequence.max()) } } extension Publishers.Sequence where Elements: Collection, Failure == Never { public func first() -> Optional<Elements.Element>.OCombine.Publisher { return .init(sequence.first) } public func output( at index: Elements.Index ) -> Optional<Elements.Element>.OCombine.Publisher { return .init(sequence.indices.contains(index) ? sequence[index] : nil) } } extension Publishers.Sequence where Elements: Collection { public func count() -> Result<Int, Failure>.OCombine.Publisher { return .init(sequence.count) } public func output( in range: Range<Elements.Index> ) -> Publishers.Sequence<[Elements.Element], Failure> { return .init(sequence: Array(sequence[range])) } } extension Publishers.Sequence where Elements: BidirectionalCollection, Failure == Never { public func last() -> Optional<Elements.Element>.OCombine.Publisher { return .init(sequence.last) } public func last( where predicate: (Elements.Element) -> Bool ) -> Optional<Elements.Element>.OCombine.Publisher { return .init(sequence.last(where: predicate)) } } extension Publishers.Sequence where Elements: RandomAccessCollection, Failure == Never { public func output( at index: Elements.Index ) -> Optional<Elements.Element>.OCombine.Publisher { return .init(sequence.indices.contains(index) ? sequence[index] : nil) } public func count() -> Just<Int> { return .init(sequence.count) } } extension Publishers.Sequence where Elements: RandomAccessCollection { public func output( in range: Range<Elements.Index> ) -> Publishers.Sequence<[Elements.Element], Failure> { return .init(sequence: Array(sequence[range])) } public func count() -> Result<Int, Failure>.OCombine.Publisher { return .init(sequence.count) } } extension Publishers.Sequence where Elements: RangeReplaceableCollection { public func prepend( _ elements: Elements.Element... ) -> Publishers.Sequence<Elements, Failure> { return prepend(elements) } public func prepend<OtherSequence: Sequence>( _ elements: OtherSequence ) -> Publishers.Sequence<Elements, Failure> where OtherSequence.Element == Elements.Element { var result = Elements() result.reserveCapacity( sequence.count + elements.underestimatedCount ) result.append(contentsOf: elements) result.append(contentsOf: sequence) return .init(sequence: result) } public func prepend( _ publisher: Publishers.Sequence<Elements, Failure> ) -> Publishers.Sequence<Elements, Failure> { var result = publisher.sequence result.append(contentsOf: sequence) return .init(sequence: result) } public func append( _ elements: Elements.Element... ) -> Publishers.Sequence<Elements, Failure> { return append(elements) } public func append<OtherSequence: Sequence>( _ elements: OtherSequence ) -> Publishers.Sequence<Elements, Failure> where OtherSequence.Element == Elements.Element { var result = sequence result.append(contentsOf: elements) return .init(sequence: result) } public func append( _ publisher: Publishers.Sequence<Elements, Failure> ) -> Publishers.Sequence<Elements, Failure> { return append(publisher.sequence) } } extension Sequence { public var publisher: Publishers.Sequence<Self, Never> { return .init(sequence: self) } }
31.325123
89
0.635792
d6d66ab20e3e1846350dc078139a0e34bc668d6a
705
// // Declayout // Created by Bayu Kurniawan (@overheardswift). // import XCTest import Declayout class DeclayoutTests: XCTestCase { func test_view_translatesAutoresizingMaskIntoConstraintIsFalse() { let view = UIView.make { $0 = UIView() } XCTAssertEqual(view.translatesAutoresizingMaskIntoConstraints, false) } func test_view_constraintsIsEmpty() { let view = UIView.make { $0 = UIView() } XCTAssertTrue(view.constraints.isEmpty) } func test_view_constraintsIsNotEmpty() { let view = UIView.make { $0 = UIView() } _ = UIView.make { $0.center(.horizontal, to: view) } XCTAssertEqual(view.constraints.isEmpty, false) } }
20.735294
73
0.673759
8af434b6019247b6fcd2b33c93c739e6b8682298
3,325
// // UICollectionView+Sizing.swift // Boomerang // // Created by Stefano Mondino on 26/01/2019. // Copyright © 2019 Synesthesia. All rights reserved. // #if os(iOS) || os(tvOS) import Foundation import UIKit public enum Direction { case horizontal case vertical public static func from(layout: UICollectionViewLayout) -> Direction { guard let flow = layout as? UICollectionViewFlowLayout else { return .vertical } switch flow.scrollDirection { case .horizontal: return .horizontal case .vertical: return .vertical @unknown default: return .vertical } } } public protocol CollectionViewSizeCalculator { func insets(for collectionView: UICollectionView, in section: Int) -> UIEdgeInsets func itemSpacing(for collectionView: UICollectionView, in section: Int) -> CGFloat func lineSpacing(for collectionView: UICollectionView, in section: Int) -> CGFloat func sizeForItem(at indexPath: IndexPath, in collectionView: UICollectionView, direction: Direction?, type: String?) -> CGSize } public extension CollectionViewSizeCalculator { private func flow(for collectionView: UICollectionView) -> UICollectionViewFlowLayout? { return collectionView.collectionViewLayout as? UICollectionViewFlowLayout } private func delegate(for collectionView: UICollectionView) -> UICollectionViewDelegateFlowLayout? { return collectionView.delegate as? UICollectionViewDelegateFlowLayout } func boundingBox(for collectionView: UICollectionView) -> CGSize { let width = collectionView.bounds.width - collectionView.contentInset.left - collectionView.contentInset.right let height = collectionView.bounds.height - collectionView.contentInset.top - collectionView.contentInset.top return CGSize(width: width, height: height) } func calculateFixedDimension(for direction: Direction, collectionView: UICollectionView, at indexPath: IndexPath, itemsPerLine: Int, type: String? = nil) -> CGFloat { let collectionViewSize = boundingBox(for: collectionView) if type == UICollectionView.elementKindSectionHeader || type == UICollectionView.elementKindSectionFooter { switch direction { case .vertical: return collectionViewSize.width case .horizontal: return collectionViewSize.height } } let itemsPerLine = CGFloat(itemsPerLine) let insets = self.insets(for: collectionView, in: indexPath.section) let itemSpacing = self.itemSpacing(for: collectionView, in: indexPath.section) let spacingDiff = (itemsPerLine - 1) * itemSpacing let value: CGFloat switch direction { case .vertical: value = (collectionViewSize.width - insets.left - insets.right - spacingDiff) / itemsPerLine case .horizontal: value = (collectionViewSize.height - insets.top - insets.bottom - spacingDiff) / itemsPerLine } return floor(floor(value * UIScreen.main.scale)/UIScreen.main.scale) } } #endif
41.049383
118
0.662256
184773e5918cb8e2867d4c3457fea4ba5bb36712
2,149
// // Copyright © 2020 Adyen. All rights reserved. // // This file is open source and available under the MIT license. See the LICENSE file for more info. // @testable import AdyenCard @testable import AdyenEncryption import XCTest class CardDetailsTests: XCTestCase { func testSerializeCreditCard() throws { let paymenthMethod = CardPaymentMethodMock(fundingSource: .credit, type: "test_type", name: "test name", brands: ["barnd_1", "barnd_2"]) let sut = CardDetails(paymentMethod: paymenthMethod, encryptedCard: CardEncryptor.EncryptedCard(number: "number", securityCode: "code", expiryMonth: "month", expiryYear: "year")) let data = try JSONEncoder().encode(sut) let dictionary = try JSONSerialization.jsonObject(with: data, options: []) as! [String: String] XCTAssertEqual(dictionary["fundingSource"], "credit") XCTAssertEqual(dictionary["type"], "test_type") XCTAssertEqual(dictionary["encryptedExpiryYear"], "year") XCTAssertEqual(dictionary["encryptedCardNumber"], "number") XCTAssertEqual(dictionary["encryptedSecurityCode"], "code") XCTAssertEqual(dictionary["encryptedExpiryMonth"], "month") } func testSerializeDeditCard() throws { let paymenthMethod = CardPaymentMethodMock(fundingSource: .debit, type: "test_type", name: "test name", brands: ["barnd_1", "barnd_2"]) let sut = CardDetails(paymentMethod: paymenthMethod, encryptedCard: CardEncryptor.EncryptedCard(number: "number", securityCode: "code", expiryMonth: "month", expiryYear: "year")) let data = try JSONEncoder().encode(sut) let dictionary = try JSONSerialization.jsonObject(with: data, options: []) as! [String: String] XCTAssertEqual(dictionary["fundingSource"], "debit") XCTAssertEqual(dictionary["type"], "test_type") XCTAssertEqual(dictionary["encryptedExpiryYear"], "year") XCTAssertEqual(dictionary["encryptedCardNumber"], "number") XCTAssertEqual(dictionary["encryptedSecurityCode"], "code") XCTAssertEqual(dictionary["encryptedExpiryMonth"], "month") } }
51.166667
186
0.702187
509d0977780ca66aa4c23e505b9e9434fd571510
389
public class TodayViewModel { private let medicationsController: MedicationsController public init(medicationsController: MedicationsController) { self.medicationsController = medicationsController } public func medicationsListViewModel() -> MedicationsListViewModel { return MedicationsListViewModel(medicationsController: medicationsController) } }
32.416667
85
0.784062
9c8e40de6a4c007ec964f2936d1a281d62f9eb06
454
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator. import Foundation // EnvironmentSettingProtocol is a collection of environment variables to set. public protocol EnvironmentSettingProtocol : Codable { var name: String { get set } var value: String? { get set } }
41.272727
96
0.742291
e2f3ddf969d26d29ec8652947fb6b9bb11a2474d
5,350
// // Helper.swift // Shared // // Created by Artur Mkrtchyan on 2/23/20. // Copyright © 2022 LXTeamDevs. All rights reserved. // import UIKit import RxSwift import RxCocoa public typealias BehaviorRelay = RxCocoa.BehaviorRelay public typealias Disposables = RxSwift.Disposables public typealias DisposeBag = RxSwift.DisposeBag public typealias Driver = RxCocoa.Driver public typealias MainScheduler = RxSwift.MainScheduler public typealias Observable = RxSwift.Observable public typealias PublishRelay = RxCocoa.PublishRelay public typealias PublishSubject = RxSwift.PublishSubject public typealias ReplaySubject = RxSwift.ReplaySubject public typealias Single = RxSwift.Single extension Driver { public func withLatestFromTwo<FirstO, SecondO>(_ first:FirstO ,_ second: SecondO) -> SharedSequence<SharingStrategy, (FirstO.Element, SecondO.Element)> where FirstO : SharedSequenceConvertibleType, SecondO: SharedSequenceConvertibleType, SecondO.SharingStrategy == SharingStrategy { return self.withLatestFrom(first).withLatestFrom(second) { ($0, $1) } } public func withLatestFromThree<FirstO, SecondO, ThirdO>(_ first:FirstO ,_ second: SecondO, _ third: ThirdO) -> SharedSequence<SharingStrategy, (FirstO.Element, SecondO.Element, ThirdO.Element)> where FirstO : SharedSequenceConvertibleType, SecondO: SharedSequenceConvertibleType, ThirdO: SharedSequenceConvertibleType, SecondO.SharingStrategy == SharingStrategy, ThirdO.SharingStrategy == SharingStrategy { return self.withLatestFrom(first).withLatestFrom(second) { ($0, $1) }.withLatestFrom(third) {($0.0, $0.1, $1)} } } extension ObservableType { public func withLatestFromTwo<FirstO, SecondO>(_ first:FirstO ,_ second: SecondO) -> Observable<(FirstO.Element, SecondO.Element)> where FirstO : ObservableConvertibleType, SecondO: ObservableConvertibleType { return self.withLatestFrom(first).withLatestFrom(second) { ($0, $1) } } } public extension Observable { func asDriver(_ `default`: Element) -> Driver<Element> { return asDriver(onErrorJustReturn: `default`) } func void() -> Observable<Void> { return map { _ in } } static func void() -> Observable<Void> { return .just(()) } } extension Observable where Element == Void { public func asDriver() -> Driver<Void> { return self.asDriver(onErrorJustReturn: ()) } } extension Observable where Element == Bool { public func asDriver() -> Driver<Bool> { return self.asDriver(onErrorJustReturn: false) } } extension Observable where Element == String { public func asDriver() -> Driver<String> { return self.asDriver(onErrorJustReturn: "") } } extension Observable where Element == NSAttributedString { public func asDriver() -> Driver<NSAttributedString> { return self.asDriver(onErrorJustReturn: NSAttributedString(string: "")) } } extension Observable where Element == Double { public func asDriver() -> Driver<Double> { return self.asDriver(onErrorJustReturn: 0) } } public extension SharedSequenceConvertibleType { func void() -> SharedSequence<SharingStrategy, Void> { return map{ _ in } } static func void() -> SharedSequence<SharingStrategy, Void> { return .just(()) } } public extension SharedSequence where Element == Bool { func ifTrue(do block:@escaping () -> Void) -> SharedSequence<SharingStrategy, Bool> { return self.map { val in if val { block() } return val } } func ifNotTrue(do block:@escaping () -> Void) -> SharedSequence<SharingStrategy, Bool> { return self.map { val in if !val { block() } return val } } } public extension SharedSequence { func doVoid(onNext: (() -> Void)?) -> RxCocoa.SharedSequence<Self.SharingStrategy, Self.Element> { self.do(onNext: { (_) in onNext?() }) } } public extension ObservableType { func doVoid(onNext: (() -> Void)?) -> Observable<Element> { return self.do(onNext: { (_) in onNext?() }) } } public protocol OptionalType { associatedtype Wrapped var optional: Wrapped? { get } } extension Optional: OptionalType { public var optional: Wrapped? { return self } public var notNil: Bool { return self != nil } public var isNil: Bool { return self == nil } } extension ObserverType where Element == Void { public func onNext() { self.on(.next(())) } } extension ObservableType { public func withPrevious() -> Observable<(Element, Element)> { return Observable.zip(self, skip(1)) } } public final class ReadOnlyBehaviorRelay<Element>: ObservableType { public typealias E = Element private let variable: BehaviorRelay<Element> public convenience init(_ value: Element) { self.init(BehaviorRelay(value: value)) } public init(_ variable: BehaviorRelay<Element>) { self.variable = variable } public var value: E { return variable.value } public func asObservable() -> Observable<E> { return variable.asObservable() } public func subscribe<Observer: ObserverType>(_ observer: Observer) -> Disposable where Observer.Element == Element { return self.variable.subscribe(observer) } } public extension BehaviorRelay { func asReadOnly() -> ReadOnlyBehaviorRelay<Element> { return ReadOnlyBehaviorRelay(self) } } public protocol DisposeBagOwner: AnyObject { var disposeBag: DisposeBag { get } }
25.35545
195
0.719252
dda7d8df15144a0caf8c40a6fdb549b8352ee6c8
10,072
// // File.swift // // // Created by Mahmood Tahir on 2021-01-22. // import Foundation import Quick import Nimble @testable import ChangeLogGenerator final class GeneratorSpec: QuickSpec { override func spec() { describe("a Generator") { var subject: Generator! context("when fetching all pages") { beforeEach { subject = try! Generator( repository: "AFNetworking/AFNetworking", token: nil, labels: [], excludedLabels: [], filterRegEx: nil, maximumNumberOfPages: nil, nextTag: nil, includeUntagged: true) } it("should generate correct changelog") { MockURLProtocol.responseJsonForURL = [ URL(string: "https://api.github.com/repos/AFNetworking/AFNetworking/pulls?state=closed&per_page=100&page=1")!: "pull_requests_1", URL(string: "https://api.github.com/repos/AFNetworking/AFNetworking/pulls?state=closed&per_page=100&page=2")!: "pull_requests_2", URL(string: "https://api.github.com/repos/AFNetworking/AFNetworking/pulls?state=closed&per_page=100&page=3")!: "pull_requests_3", URL(string: "https://api.github.com/repos/AFNetworking/AFNetworking/pulls?state=closed&per_page=100&page=4")!: "pull_requests_4", URL(string: "https://api.github.com/repos/AFNetworking/AFNetworking/tags?per_page=100&page=1")!: "tags_1", URL(string: "https://api.github.com/repos/AFNetworking/AFNetworking/tags?per_page=100&page=2")!: "tags_2", ] var result: Result<String, Error>? subject.generateCompleteChangeLog { result = $0 } expect(result).toEventuallyNot(beNil()) expect { _ = try result?.get() }.toNot(throwError()) let changelog = try? result?.get() expect(changelog) == Bundle.module.url(forResource: "CHANGELOG", withExtension: "md").map { try? String(contentsOf: $0) } } it("should generate changelog since release") { MockURLProtocol.responseJsonFiles = [ "release", "pull_request_search_2" ] var result: Result<String, Error>? subject.generateChangeLogSinceLatestRelease { result = $0 } expect(result).toEventuallyNot(beNil()) expect { _ = try result?.get() }.toNot(throwError()) let changelog = try? result?.get() expect(changelog) == Bundle.module.url(forResource: "CHANGELOG_release", withExtension: "md").map { try? String(contentsOf: $0) } } it("should generate changelog since given tag") { MockURLProtocol.responseJsonFiles = [ "tags_1", "pull_requests_1", "pull_requests_2", "pull_requests_3", "pull_requests_4", ] var result: Result<String, Error>? subject.generateChangeLogSince(tag: "3.2.0") { result = $0 } expect(result).toEventuallyNot(beNil()) expect { _ = try result?.get() }.toNot(throwError()) let changelog = try? result?.get() expect(changelog) == Bundle.module.url(forResource: "CHANGELOG_tag", withExtension: "md").map { try? String(contentsOf: $0) } } } context("when initialized with token") { beforeEach { subject = try! Generator( repository: "AFNetworking/AFNetworking", token: "123456789asdfghjkl", labels: [], excludedLabels: [], filterRegEx: nil, maximumNumberOfPages: nil, nextTag: nil, includeUntagged: true) } context("for complete changelog") { it("should send token in headers") { var result: Result<String, Error>? subject.generateCompleteChangeLog { result = $0 } expect(result).toEventuallyNot(beNil()) expect(MockURLProtocol.requestsCalled).toNot(beEmpty()) expect { MockURLProtocol.requestsCalled .allSatisfy { $0.allHTTPHeaderFields?["Authorization"] == "token 123456789asdfghjkl" } }.to(beTrue()) } } context("for latest release") { it("should send token in headers") { var result: Result<String, Error>? subject.generateChangeLogSinceLatestRelease { result = $0 } expect(result).toEventuallyNot(beNil()) expect(MockURLProtocol.requestsCalled).toNot(beEmpty()) expect { MockURLProtocol.requestsCalled .allSatisfy { $0.allHTTPHeaderFields?["Authorization"] == "token 123456789asdfghjkl" } }.to(beTrue()) } } context("for since tag") { it("should send token in headers") { var result: Result<String, Error>? subject.generateChangeLogSince(tag: "3.2.0") { result = $0 } expect(result).toEventuallyNot(beNil()) expect(MockURLProtocol.requestsCalled).toNot(beEmpty()) expect { MockURLProtocol.requestsCalled .allSatisfy { $0.allHTTPHeaderFields?["Authorization"] == "token 123456789asdfghjkl" } }.to(beTrue()) } } context("when filter regex is provided") { beforeEach { subject = try! Generator( repository: "AFNetworking/AFNetworking", token: nil, labels: [], excludedLabels: [], filterRegEx: "Fixed CLANG_ENABLE_CODE_COVERAGE flag so release can be made", maximumNumberOfPages: nil, nextTag: nil, includeUntagged: true) } it("should not include pull requests matching the regex") { MockURLProtocol.responseJsonForURL = [ URL(string: "https://api.github.com/repos/AFNetworking/AFNetworking/pulls?state=closed&per_page=100&page=1")!: "pull_requests_1", URL(string: "https://api.github.com/repos/AFNetworking/AFNetworking/pulls?state=closed&per_page=100&page=2")!: "pull_requests_2", URL(string: "https://api.github.com/repos/AFNetworking/AFNetworking/pulls?state=closed&per_page=100&page=3")!: "pull_requests_3", URL(string: "https://api.github.com/repos/AFNetworking/AFNetworking/pulls?state=closed&per_page=100&page=4")!: "pull_requests_4", URL(string: "https://api.github.com/repos/AFNetworking/AFNetworking/tags?per_page=100&page=1")!: "tags_1", URL(string: "https://api.github.com/repos/AFNetworking/AFNetworking/tags?per_page=100&page=2")!: "tags_2", ] var result: Result<String, Error>? subject.generateCompleteChangeLog { result = $0 } expect(result).toEventuallyNot(beNil()) expect { _ = try result?.get() }.toNot(throwError()) let changelog = try? result?.get() expect(changelog?.contains("Fixed CLANG_ENABLE_CODE_COVERAGE flag so release can be made")).to(beFalse()) } } } it("should not initialize if repository name does not match format") { expect { subject = try Generator( repository: "hello", token: nil, labels: [], excludedLabels: [], filterRegEx: nil, maximumNumberOfPages: nil, nextTag: nil, includeUntagged: true) }.to(throwError()) } } } }
42.142259
157
0.442017
03884810a54b3cdfbb96749b359034df29cc7da2
1,489
// // SignInViewController.swift // FoodieFun // // Created by Jesse Ruiz on 10/22/19. // Copyright © 2019 Lambda School. All rights reserved. // import UIKit class SignInViewController: UIViewController { // MARK: - Properties let foodieController = FoodieController() // MARK: - Outlets @IBOutlet weak var emailTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var signIn: UIButton! override func viewDidLoad() { super.viewDidLoad() updateViews() } // MARK: - Actions @IBAction func signInTapped(_ sender: UIButton) { guard let email = emailTextField.text, let password = passwordTextField.text, !email.isEmpty, !password.isEmpty else { return } let foodie = FoodieRepresentation(username: nil, userEmail: email, userPassword: password, id: nil) signIn(with: foodie) } // MARK: - Methods private func updateViews() { signIn.layer.cornerRadius = 8.0 } func signIn(with foodie: FoodieRepresentation) { foodieController.signIn(with: foodie) { (error) in if let error = error { NSLog("Error occured during sign in: \(error)") } else { DispatchQueue.main.async { self.dismiss(animated: true, completion: nil) } } } } }
25.672414
107
0.583613
de548c0740827fd780f054f846e26a59a2326c51
791
import Quick import Nimble @testable import Fakery class TeamSpec: QuickSpec { override func spec() { describe("Team") { var team: Team! beforeEach { let parser = Parser(locale: "en-TEST") team = Team(parser: parser) } describe("#name") { it("returns the correct text") { let name = team.name() expect(name).to(equal("California owls")) } } describe("#creature") { it("returns the correct text") { let creature = team.creature() expect(creature).to(equal("owls")) } } describe("#state") { it("returns the correct text") { let state = team.state() expect(state).to(equal("California")) } } } } }
20.282051
51
0.518331
fcf07bda51f209e171cfee10e2853871029bcbb1
1,321
// // CategoryTableViewCell.swift // Dominos // // Created by Lee on 2020/01/28. // Copyright © 2020 Up's. All rights reserved. // import UIKit class CategoryTableViewCell: UITableViewCell { static let identifier = "CategoryTableViewCell" private let categoryImageView = UIImageView() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setUI() setConstraint() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func configure(category: String) { categoryImageView.image = UIImage(named: category) } private func setUI() { categoryImageView.contentMode = .scaleToFill contentView.addSubview(categoryImageView) } private func setConstraint() { categoryImageView.translatesAutoresizingMaskIntoConstraints = false categoryImageView.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true categoryImageView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor).isActive = true categoryImageView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor).isActive = true categoryImageView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true } }
29.355556
100
0.750946
d73e7e579ecf3d359523d8aabdd3b69b507b6148
411
// // PresentationHandler.swift // SmartUniversity // // Created by Tomas Skypala on 18/06/2020. // Copyright © 2020 Tomas Skypala. All rights reserved. // import UIKit struct PresentationHandler: PresentationHandling { func present(_ viewController: UIViewController, onViewController: UIViewController, animated: Bool) { onViewController.present(viewController, animated: animated) } }
24.176471
106
0.746959
1c12aeb559d73104614d6d5e086ad7b3687d1373
591
// // ViewControllerHelpers.swift // pathsTests // // Created by Kevin Finn on 3/14/18. // Copyright © 2018 bingcrowsby. All rights reserved. // import Foundation import UIKit extension UIViewController { func triggerViewWillAppear(){ self.beginAppearanceTransition(true, animated: false) // Triggers viewWillAppear } func triggerViewDidAppear(){ self.endAppearanceTransition() // Triggers viewDidAppear } } extension UIWindow { func set(root: UIViewController){ self.makeKeyAndVisible() self.rootViewController = root } }
21.107143
88
0.693739
f436b848f02d76d0bf93bf53ab6177bc0632b047
1,957
// // AcceptanceTests.swift // VaultSDK // // Created by Fang-Pen Lin on 11/22/16. // Copyright © 2016 Very Good Security. All rights reserved. // import XCTest @testable import VaultSDK class AcceptanceTests: XCTestCase { static let baseURL = URL(string: "https://demo.sandbox.verygoodvault.com")! static let publishableKey = "demo-user" override func setUp() { super.setUp() } func testCreateToken() { let api: VaultAPI = VaultAPI( baseURL: AcceptanceTests.baseURL, publishableKey: AcceptanceTests.publishableKey ) let exp = expectation(description: "token created") api.createToken( payload: "4111111111111111", failure: { error in XCTFail("Failed to create token, error=\(error)") exp.fulfill() }, success: { token in if let id = token["id"] as? String { XCTAssert(id.hasPrefix("tok_")) } else { XCTFail("No token created") } exp.fulfill() } ) waitForExpectations(timeout: 10, handler: nil) } func testCreateTokenWithBadKey() { let api: VaultAPI = VaultAPI( baseURL: AcceptanceTests.baseURL, publishableKey: "bad key" ) let exp = expectation(description: "token creation failed") api.createToken( payload: "4111111111111111", failure: { error in XCTAssertEqual(error.code, VaultAPIError.badResponse.rawValue) XCTAssertEqual((error.userInfo["status_code"] as? NSNumber)?.intValue, 401) exp.fulfill() }, success: { token in XCTFail("Should bad response") exp.fulfill() } ) waitForExpectations(timeout: 10, handler: nil) } }
29.208955
91
0.547266
f937f388218c2d19436b185fcbad1c28795addae
798
// // DateButton.swift // Lifting Generations // // Created by Joseph Ivie on 5/13/19. // Copyright © 2019 Joseph Ivie. All rights reserved. // import Foundation import UIKit @IBDesignable public class TimeButton : DateButton { private var internalMinuteInterval: Int = 1 public var minuteInterval: Int{ get{ return internalMinuteInterval } set(value){ internalMinuteInterval = value picker.minuteInterval = value } } override public func commonInit() { super.commonInit() mode = .time picker.minuteInterval = minuteInterval let format = DateFormatter() format.dateStyle = .none; format.timeStyle = .short; self.format = format } }
21
54
0.606516
725730e08db739876b3fde6ba89fc4d510246446
473
// // HPGestureRecognizer.swift // SwiperYesSwiping // // Created by MMQ on 9/11/20. // import UIKit class HPGestureRecognizer: UIPanGestureRecognizer { override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent) { super.touchesMoved(touches, with: event) if state == .began { let vel = velocity(in: view) if abs(vel.y) > abs(vel.x) { state = .cancelled } } } }
21.5
78
0.56871
7a1f62b6e969af12d60b8a252715690b80d6d1cc
2,025
class Trie<ValueType> { var key: UInt8 var value: ValueType? var children: [Trie] = [] var isLeaf: Bool { return children.count == 0 } convenience init() { self.init(key: 0x00) } init(key: UInt8, value: ValueType? = nil) { self.key = key self.value = value } } extension Trie { subscript(_ key: UInt8) -> Trie? { get { return children.first(where: { $0.key == key }) } set { guard let index = children.index(where: { $0.key == key }) else { guard let newValue = newValue else { return } children.append(newValue) return } guard let newValue = newValue else { children.remove(at: index) return } let child = children[index] guard child.value == nil else { print("warning: inserted duplicate tokens into Trie.") return } child.value = newValue.value } } func insert(_ keypath: [UInt8], value: ValueType) { insert(value, for: keypath) } func insert(_ value: ValueType, for keypath: [UInt8]) { var current = self for (index, key) in keypath.enumerated() { guard let next = current[key] else { let next = Trie(key: key) current[key] = next current = next if index == keypath.endIndex - 1 { next.value = value } continue } if index == keypath.endIndex - 1 && next.value == nil { next.value = value } current = next } } func contains(_ keypath: [UInt8]) -> ValueType? { var current = self for key in keypath { guard let next = current[key] else { return nil } current = next } return current.value } }
23.823529
77
0.476543
1cee5f9ca3c42a634ff665ca4733c66e02e3048d
9,974
// // AddMountUserViewController.swift // Digi Cloud // // Created by Mihai Cristescu on 12/03/2017. // Copyright © 2017 Mihai Cristescu. All rights reserved. // import UIKit class AddMountUserViewController: UITableViewController, UITextFieldDelegate { var onUpdatedUser: (() -> Void)? var user: User let isUserEdited: Bool enum PermissionType: Int { case write case createLink case createReicever case mount } var permissions: [PermissionType] = [] private let mount: Mount private lazy var saveMemberButton: UIButton = { let button = UIButton(type: UIButtonType.contactAdd) button.addTarget(self, action: #selector(handleSaveMember), for: .touchUpInside) button.translatesAutoresizingMaskIntoConstraints = false return button }() private lazy var usernameTextField: UITextField = { let textField = UITextField() textField.translatesAutoresizingMaskIntoConstraints = false textField.placeholder = NSLocalizedString("Email address", comment: "") textField.clearButtonMode = .whileEditing textField.autocapitalizationType = .none textField.autocorrectionType = .no textField.keyboardType = .emailAddress textField.returnKeyType = .send textField.delegate = self textField.addTarget(self, action: #selector(handleTextFieldChange), for: .editingChanged) return textField }() let permissionWriteSwitch: UISwitch = { let uiSwitch = UISwitch() uiSwitch.translatesAutoresizingMaskIntoConstraints = false uiSwitch.tag = PermissionType.write.rawValue uiSwitch.addTarget(self, action: #selector(handleUpdateUserPermissions(_:)), for: .valueChanged) return uiSwitch }() let permissionCreateLinkSwitch: UISwitch = { let uiSwitch = UISwitch() uiSwitch.translatesAutoresizingMaskIntoConstraints = false uiSwitch.tag = PermissionType.createLink.rawValue uiSwitch.addTarget(self, action: #selector(handleUpdateUserPermissions(_:)), for: .valueChanged) return uiSwitch }() let permissionCreateReceiverSwitch: UISwitch = { let uiSwitch = UISwitch() uiSwitch.translatesAutoresizingMaskIntoConstraints = false uiSwitch.tag = PermissionType.createReicever.rawValue uiSwitch.addTarget(self, action: #selector(handleUpdateUserPermissions(_:)), for: .valueChanged) return uiSwitch }() let permissionManageShareSwitch: UISwitch = { let uiSwitch = UISwitch() uiSwitch.translatesAutoresizingMaskIntoConstraints = false uiSwitch.tag = PermissionType.mount.rawValue uiSwitch.addTarget(self, action: #selector(handleUpdateUserPermissions(_:)), for: .valueChanged) return uiSwitch }() init(mount: Mount, user: User? = nil) { self.mount = mount if let user = user { isUserEdited = true self.user = user } else { isUserEdited = false self.user = User(identifier: "", firstName: "", lastName: "", email: "", permissions: Permissions()) } super.init(style: .grouped) self.permissions.append(contentsOf: mount.permissions.write ? [.write] : []) self.permissions.append(contentsOf: mount.permissions.createLink ? [.createLink] : []) self.permissions.append(contentsOf: mount.permissions.createReceiver ? [.createReicever] : []) self.permissions.append(contentsOf: mount.permissions.mount ? [.mount] : []) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() title = NSLocalizedString("Add member", comment: "") let saveMemberButton = UIBarButtonItem(title: NSLocalizedString("Save", comment: ""), style: .done, target: self, action: #selector(handleSaveMember)) navigationItem.rightBarButtonItem = saveMemberButton navigationController?.isToolbarHidden = true tableView.rowHeight = AppSettings.tableViewRowHeight } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.usernameTextField.becomeFirstResponder() } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) navigationController?.isToolbarHidden = false } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 2 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return section == 0 ? 1 : permissions.count } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return section == 0 ? nil : NSLocalizedString("PERMISSIONS", comment: "") } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell() cell.selectionStyle = .none if indexPath.section == 0 { cell.selectionStyle = .none cell.contentView.addSubview(usernameTextField) if isUserEdited { usernameTextField.text = user.email usernameTextField.isUserInteractionEnabled = false } NSLayoutConstraint.activate([ usernameTextField.leftAnchor.constraint(equalTo: cell.contentView.layoutMarginsGuide.leftAnchor), usernameTextField.rightAnchor.constraint(equalTo: cell.contentView.layoutMarginsGuide.rightAnchor), usernameTextField.centerYAnchor.constraint(equalTo: cell.contentView.centerYAnchor) ]) return cell } else { let permissionType = permissions[indexPath.row] var aSwitch: UISwitch var permissionTitle: String switch permissionType { case .write: aSwitch = permissionWriteSwitch aSwitch.isOn = user.permissions.write permissionTitle = NSLocalizedString("Can modify", comment: "") case .createLink: aSwitch = permissionCreateLinkSwitch aSwitch.isOn = user.permissions.createLink permissionTitle = NSLocalizedString("Can create download links", comment: "") case .createReicever: aSwitch = permissionCreateReceiverSwitch aSwitch.isOn = user.permissions.createReceiver permissionTitle = NSLocalizedString("Can create receive links", comment: "") case .mount: aSwitch = permissionManageShareSwitch aSwitch.isOn = user.permissions.mount aSwitch.onTintColor = UIColor(red: 0.40, green: 0.43, blue: 0.98, alpha: 1.0) permissionTitle = NSLocalizedString("Can manage share", comment: "") } cell.textLabel?.text = permissionTitle cell.contentView.addSubview(aSwitch) NSLayoutConstraint.activate([ aSwitch.rightAnchor.constraint(equalTo: cell.contentView.layoutMarginsGuide.rightAnchor), aSwitch.centerYAnchor.constraint(equalTo: cell.contentView.centerYAnchor) ]) } return cell } @objc private func handleUpdateUserPermissions(_ sender: UISwitch) { guard let permissionType = PermissionType(rawValue: sender.tag) else { return } switch permissionType { case .write: user.permissions.write = sender.isOn case .mount: user.permissions.mount = sender.isOn case .createLink: user.permissions.createLink = sender.isOn case .createReicever: user.permissions.createReceiver = sender.isOn } } @objc private func handleSaveMember() { usernameTextField.resignFirstResponder() guard let username = usernameTextField.text, username.count > 3 else { self.showAlert(message: NSLocalizedString("Please provide the email address of the Digi Storage user.", comment: "")) return } if isUserEdited { DigiClient.shared.updateMount(mount: mount, operation: .updatePermissions, user: user, completion: { _, error in guard error == nil else { self.showAlert(message: NSLocalizedString("Could not update member permissions.", comment: "")) return } self.onUpdatedUser?() }) } else { DigiClient.shared.updateMount(mount: mount, operation: .add, user: user) { newUser, error in guard error == nil else { self.showAlert(message: NSLocalizedString("Could not add new member.", comment: "")) return } if newUser != nil { self.onUpdatedUser?() } } } } @objc private func handleTextFieldChange() { if let email = usernameTextField.text { self.user.email = email } } private func showAlert(message: String) { let alert = UIAlertController(title: NSLocalizedString("Error", comment: ""), message: message, preferredStyle: UIAlertControllerStyle.alert) let actionOK = UIAlertAction(title: NSLocalizedString("OK", comment: ""), style: UIAlertActionStyle.default, handler: nil) alert.addAction(actionOK) self.present(alert, animated: false) { self.usernameTextField.becomeFirstResponder() } } }
35.119718
130
0.630339
29ea85ec86bd7291688482dcc9423405928d63e4
741
// // LandmarkSettings.swift // Landmarks // // Created by Wouter Verweirder on 24/08/2021. // import SwiftUI struct LandmarkSettings: View { @AppStorage("MapView.zoom") private var zoom: MapView.Zoom = .medium var body: some View { Form { Picker("Map Zoom:", selection: $zoom) { ForEach(MapView.Zoom.allCases) { level in Text(level.rawValue) } } .pickerStyle(InlinePickerStyle()) } .frame(width: 300) .navigationTitle("Landmark Settings") .padding(80) } } struct LandmarkSettings_Previews: PreviewProvider { static var previews: some View { LandmarkSettings() } }
21.171429
57
0.565452
e5ecdaa4ef6a92c9fb3d9ba5df4fa75882894355
1,716
//: ## Low Pass Filter //: A low-pass filter takes an audio signal as an input, and cuts out the //: high-frequency components of the audio signal, allowing for the //: lower frequency components to "pass through" the filter. //: import AudioKitPlaygrounds import AudioKit let file = try AKAudioFile(readFileName: filtersPlaygroundFiles[0], baseDir: .resources) let player = try AKAudioPlayer(file: file) player.looping = true var lowPassFilter = AKLowPassFilter(player) lowPassFilter.cutoffFrequency = 6_900 // Hz lowPassFilter.resonance = 0 // dB AudioKit.output = lowPassFilter AudioKit.start() player.play() //: User Interface Set up class PlaygroundView: AKPlaygroundView { override func setup() { addTitle("Low Pass Filter") addSubview(AKResourcesAudioFileLoaderView( player: player, filenames: filtersPlaygroundFiles)) addSubview(AKBypassButton(node: lowPassFilter)) addSubview(AKPropertySlider( property: "Cutoff Frequency", format: "%0.1f Hz", value: lowPassFilter.cutoffFrequency, minimum: 20, maximum: 22_050, color: AKColor.green ) { sliderValue in lowPassFilter.cutoffFrequency = sliderValue }) addSubview(AKPropertySlider( property: "Resonance", format: "%0.1f dB", value: lowPassFilter.resonance, minimum: -20, maximum: 40, color: AKColor.red ) { sliderValue in lowPassFilter.resonance = sliderValue }) } } import PlaygroundSupport PlaygroundPage.current.needsIndefiniteExecution = true PlaygroundPage.current.liveView = PlaygroundView()
29.084746
79
0.668998
ab541f3d5a02373c3019066830105ca9cfeb88f8
2,523
import Foundation /** * Provides several conviences methods for Date. */ extension Date { // Returns `date` with (hour:min) of this Date. func sameTime(on date: Date) -> Date? { let calendar = Calendar.current let now = calendar.dateComponents([.year, .month, .day], from: date) var components = calendar.dateComponents([.hour, .minute], from: self) components.year = now.year components.month = now.month components.day = now.day return calendar.date(from: components) } // Returns today with (hour:min) of this Date. func sameTimeToday() -> Date? { return sameTime(on: Date()) } // Returns soonest date with (weekday:hour:min) of this Date. func sameDayThisWeek() -> Date? { let calendar = Calendar.current let components = calendar.dateComponents([.hour, .minute, .weekday], from: self) if self == calendar.startOfDay(for: Date()) { return self } return calendar.nextDate(after: calendar.startOfDay(for: Date()), matching: components, matchingPolicy: .nextTime, repeatedTimePolicy: .first, direction: .forward) } // Returns a date with this date's hour and minute component only. func timeOnly() -> Date? { let calendar = Calendar.current return calendar.date(from: calendar.dateComponents([.hour, .minute], from: self)) } // Returns a date with this date's year, month, and day component only. func dateOnly() -> Date? { let calendar = Calendar.current return calendar.date(from: calendar.dateComponents([.year, .month, .day], from: self)) } // Returns the weekday as an integer (0 -> Sunday, 6 -> Saturday) func weekday() -> Int { return Calendar.current.component(.weekday, from: self) - 1 } // Returns whether this Date is between Date range [a, b] inclusive. func isBetween(_ a: Date?, _ b: Date?) -> Bool { if a == nil || b == nil { return false } return a! <= self && self <= b! } // Returns true if this Date is earlier or equal to given other. static func <= (_ this: inout Date, _ other: Date) -> Bool { return (this < other) || (this == other) } // Returns true if this Date is later or equal to given other. static func >= (_ this: inout Date, _ other: Date) -> Bool { return (this > other) || (this == other) } }
34.561644
171
0.596116
e6fb3ea1a5bb0a849eaf7118434cf8de3f059761
5,604
// // FSBucketManager.swift // FlagShip-framework // // Created by Adel on 21/11/2019. // import Foundation /// :nodoc: class FSBucketManager: NSObject { let targetManager: FSTargetingManager! var matchedVariationGroup: [FSVariationGroup] = [] // Init with empty array var matchedCampaigns: [FSCampaignCache] = [] override init() { targetManager = FSTargetingManager() } /// This is the entry for bucketing , that give the campaign infos as we do in api decesion internal func bucketVariations(_ visitorId: String, _ scriptBucket: FSBucket) -> FSCampaigns? { /// Check the panic mode if scriptBucket.panic == true { return FSCampaigns(visitorId, panic: true) } // check if the user exist in the cache , if yes then read his own modification from the cache // If not extract the variations // check the targetings and filter the variation he can run // Match before let resultBucketCache = matchTargetingForCustomID(scriptBucket, visitorId, scriptBucket.visitorConsolidation) // Save My bucketing resultBucketCache.saveMe() // Fill Campaign with value to be read by singleton return FSCampaigns(resultBucketCache) } /// Extract the variations where the user is allowed to seee internal func matchTargetingForCustomID(_ scriptBucket: FSBucket?, _ visitorId: String, _ visitorConsolidation: Bool) -> FSBucketCache { let fsCampaignBucketCache = FSBucketCache(visitorId) matchedVariationGroup.removeAll() var groupCampaigns: [FSCampaignCache] = [] var groupVar: [FSVariationGroupCache] = [] groupCampaigns.removeAll() if let campaignsArray = scriptBucket?.campaigns { for bucketCampaignItem: FSBucketCampaign in campaignsArray { groupVar.removeAll() for variationGroupItem: FSVariationGroup in bucketCampaignItem.variationGroups { if targetManager.isTargetingGroupIsOkay(variationGroupItem.targeting) { FSLogger.FSlog("Target for \(variationGroupItem.idVariationGroup ?? "") is OKAY", .Campaign) // select variation here guard let variationIdSelected = selectVariationWithHashMurMur(visitorId, variationGroupItem, visitorConsolidation) else { FSLogger.FSlog("probleme here don 't found the id variation selected", .Campaign) continue } /// Get all modification according to id variation let variationCache: FSVariationCache = FSVariationCache(variationIdSelected) for itemVariation in variationGroupItem.variations { if itemVariation.idVariation == variationIdSelected { /// the variationIdSelected is found , populate the attributes variationCache.modification = itemVariation.modifications variationCache.reference = itemVariation.reference } } groupVar.append(FSVariationGroupCache(variationGroupItem.idVariationGroup, variationCache)) } else { FSLogger.FSlog("Target for \(variationGroupItem.idVariationGroup ?? "") is NOK", .Campaign) } } groupCampaigns.append(FSCampaignCache(bucketCampaignItem.idCampaign, groupVar)) } } fsCampaignBucketCache.campaigns = groupCampaigns return fsCampaignBucketCache } internal func selectVariationWithHashMurMur(_ visitorId: String, _ variationGroup: FSVariationGroup, _ visitorConsolidation: Bool) -> String? { // Before selected varaition have to chck user id exist if FSStorage.fileExists(String(format: "%@.json", visitorId), in: .documents) { FSLogger.FSlog("The Buketing already exist Will Re check targeting for the selected variation ", .Campaign) guard let cachedObject = FSStorage.retrieve(String(format: "%@.json", visitorId), from: .documents, as: FSBucketCache.self) else { FSLogger.FSlog(" Error on retreive cached object", .Campaign) return nil } for itemCached in cachedObject.campaigns { for subItemCached in itemCached.variationGroups { /// Variation Group already exist, then return the saved one if subItemCached.variationGroupId == variationGroup.idVariationGroup { return subItemCached.variation.variationId } } } } let hashAlloc: Int FSLogger.FSlog("Apply MurMurHash Algo on customId", .Campaign) /// We calculate the Hash allocation by the combonation of : visitorId + idVariationGroup let combinedId = variationGroup.idVariationGroup + visitorId FSLogger.FSlog(" The combined id for MurMurHash is : \(combinedId)", .Campaign) hashAlloc = (Int(MurmurHash3.hash32(key: combinedId) % 100)) var offsetAlloc = 0 for item: FSVariation in variationGroup.variations { if hashAlloc < item.allocation + offsetAlloc { return item.idVariation } offsetAlloc += item.allocation } return nil } }
33.759036
147
0.619736
9079652c8ce539eb8828440f8621e0e7e1ba67f3
1,599
// // GiphyAPIEnums.swift // GiphyViewer // // Created by Thierry Sansaricq on 4/20/18. // Copyright © 2018 Thierry Sansaricq. All rights reserved. // public enum GiphyAPIRating: String { case Y = "Y" case G = "G" case PG = "PG" case PG13 = "PG-13" case R = "R" static let allValues = [GiphyAPIRating.Y.rawValue, GiphyAPIRating.G.rawValue, GiphyAPIRating.PG.rawValue, GiphyAPIRating.PG13.rawValue, GiphyAPIRating.R.rawValue] } public enum GiphyAPIEndpoint: String { case Search = "search" case Trending = "trending" } public enum ImageVariant: String { case FixeHeightStill = "fixed_height_still" case OriginalStill = "original_still" case FixedWidth = "fixed_width" case FixedHeightSmallStill = "fixed_height_small_still" case FixedHeightDownsampled = "fixed_height_downsampled" case Preview = "preview" case FixedHeightSmall = "fixed_height_small" case DownsizedStill = "downsized_still" case Downsized = "downsized" case DownsizedLarge = "downsized_large" case FixedWidthSmallStill = "fixed_width_small_still" case PreviewWebp = "preview_webp" case FixedWidthStill = "fixed_width_still" case FixedWidthSmall = "fixed_width_small" case DownsizedSmall = "downsized_small" case FixedWidthDownsampled = "fixed_width_downsampled" case DownsizedMedium = "downsized_medium" case Looping = "looping" case OriginalMP4 = "original_mp4" case PreviewGif = "preview_gif" case Still480w = "480w_still" case FixedHeight = "fixed_height" case Original = "original" }
29.611111
166
0.716698
dea2f6603257b613ce0aed4ae9481e95a29ea64b
5,372
// // CATextLayer.swift // CALayerGuide // // Created by ShawnDu on 15/11/3. // Copyright © 2015年 ShawnDu. All rights reserved. // import UIKit class CATextLayerViewController: UIViewController { @IBOutlet weak var viewForTextLayer: UIView! @IBOutlet weak var fontSizeSliderValueLabel: UILabel! @IBOutlet weak var fontSizeSlider: UISlider! @IBOutlet weak var wrapTextSwitch: UISwitch! @IBOutlet weak var alignmentModeSegmentedControl: UISegmentedControl! @IBOutlet weak var truncationModeSegmentedControl: UISegmentedControl! enum Font: Int { case Helvetica, NoteworthyLight } enum AlignmentMode: Int { case Left, Center, Justified, Right } enum TruncationMode: Int { case Start, Middle, End } var noteworthyLightFont: AnyObject? var helveticaFont: AnyObject? let baseFontSize: CGFloat = 24.0 let textLayer = CATextLayer() var fontSize: CGFloat = 24.0 var previouslySelectedTruncationMode = TruncationMode.End // MARK: - Quick reference func setUpTextLayer() { textLayer.frame = viewForTextLayer.bounds var string = "" for _ in 1...20 { string += "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce auctor arcu quis velit congue dictum. " } textLayer.string = string textLayer.font = helveticaFont textLayer.foregroundColor = UIColor.darkGrayColor().CGColor textLayer.wrapped = true textLayer.alignmentMode = kCAAlignmentLeft textLayer.truncationMode = kCATruncationEnd textLayer.contentsScale = UIScreen.mainScreen().scale } func createFonts() { var fontName: CFStringRef = "Noteworthy-Light" noteworthyLightFont = CTFontCreateWithName(fontName, baseFontSize, nil) fontName = "Helvetica" helveticaFont = CTFontCreateWithName(fontName, baseFontSize, nil) } // MARK: - View life cycle override func viewDidLoad() { super.viewDidLoad() createFonts() setUpTextLayer() viewForTextLayer.layer.addSublayer(textLayer) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() textLayer.frame = viewForTextLayer.bounds print(textLayer.frame) textLayer.fontSize = fontSize print(textLayer.fontSize) } // MARK: - IBActions @IBAction func fontSegmentedControlChanged(sender: UISegmentedControl) { switch sender.selectedSegmentIndex { case Font.Helvetica.rawValue: textLayer.font = helveticaFont case Font.NoteworthyLight.rawValue: textLayer.font = noteworthyLightFont default: break } } @IBAction func fontSizeSliderChanged(sender: UISlider) { fontSizeSliderValueLabel.text = "\(Int(sender.value * 100.0))%" fontSize = baseFontSize * CGFloat(sender.value) } @IBAction func wrapTextSwitchChanged(sender: UISwitch) { alignmentModeSegmentedControl.selectedSegmentIndex = AlignmentMode.Left.rawValue textLayer.alignmentMode = kCAAlignmentLeft if sender.on { if let truncationMode = TruncationMode(rawValue: truncationModeSegmentedControl.selectedSegmentIndex) { previouslySelectedTruncationMode = truncationMode } truncationModeSegmentedControl.selectedSegmentIndex = UISegmentedControlNoSegment textLayer.wrapped = true } else { textLayer.wrapped = false truncationModeSegmentedControl.selectedSegmentIndex = previouslySelectedTruncationMode.rawValue } } @IBAction func alignmentModeSegmentedControlChanged(sender: UISegmentedControl) { wrapTextSwitch.on = true textLayer.wrapped = true truncationModeSegmentedControl.selectedSegmentIndex = UISegmentedControlNoSegment textLayer.truncationMode = kCATruncationNone switch sender.selectedSegmentIndex { case AlignmentMode.Left.rawValue: textLayer.alignmentMode = kCAAlignmentLeft case AlignmentMode.Center.rawValue: textLayer.alignmentMode = kCAAlignmentCenter case AlignmentMode.Justified.rawValue: textLayer.alignmentMode = kCAAlignmentJustified case AlignmentMode.Right.rawValue: textLayer.alignmentMode = kCAAlignmentRight default: textLayer.alignmentMode = kCAAlignmentLeft } } @IBAction func truncationModeSegmentedControlChanged(sender: UISegmentedControl) { wrapTextSwitch.on = false textLayer.wrapped = false alignmentModeSegmentedControl.selectedSegmentIndex = UISegmentedControlNoSegment textLayer.alignmentMode = kCAAlignmentLeft switch sender.selectedSegmentIndex { case TruncationMode.Start.rawValue: textLayer.truncationMode = kCATruncationStart case TruncationMode.Middle.rawValue: textLayer.truncationMode = kCATruncationMiddle case TruncationMode.End.rawValue: textLayer.truncationMode = kCATruncationEnd default: textLayer.truncationMode = kCATruncationNone } } }
34.658065
125
0.672934
1ab5b37c8c380a3ee88e94314ee60b1dca95947c
710
//: Playground - noun: a place where people can play import UIKit import Redux enum CounterAction: Action { case increment(Int) case decrement(Int) } let store = Store<Int>(initialState: 0) { state, action in switch action { case CounterAction.increment(let amount): return state + amount case CounterAction.decrement(let amount): return state - amount default: return state } } let unsubscribe = store.subscribe { state in print("Current counter: \(state)") } store.dispatch(CounterAction.increment(5)) store.dispatch(CounterAction.decrement(3)) store.dispatch(CounterAction.increment(7)) unsubscribe() store.dispatch(CounterAction.decrement(1))
21.515152
58
0.711268
21312a60ee3f27a365d9dc950cbf01c199edd5e6
2,838
// // NSAttributedString+Helpers.swift // DropBit // // Created by Mitch on 1/24/19. // Copyright © 2019 Coin Ninja, LLC. All rights reserved. // import Foundation import UIKit typealias StringAttributes = [NSAttributedString.Key: Any] extension NSAttributedString { static func + (left: NSAttributedString, right: NSAttributedString) -> NSAttributedString { let result = NSMutableAttributedString() result.append(left) result.append(right) return result } static func + (left: NSAttributedString, right: String) -> NSAttributedString { let rightAttributedString = NSAttributedString(string: right) let result = NSMutableAttributedString() result.append(left) result.append(rightAttributedString) return result } convenience init(image: UIImage, fontDescender: CGFloat, imageSize: CGSize = CGSize(width: 20, height: 20), offset: CGPoint = .zero) { let textAttribute = NSTextAttachment() textAttribute.image = image textAttribute.bounds = CGRect( x: 0, y: fontDescender, //(-size.height / (size.height / 3)), width: imageSize.width, height: imageSize.height ).offsetBy(dx: offset.x, dy: offset.y) self.init(attachment: textAttribute) } /// `sharedColor` is used for both the titleColor and a mask of the image convenience init(imageName: String, imageSize: CGSize = CGSize(width: 20, height: 20), title: String, sharedColor: UIColor, font: UIFont, titleOffset: Int = 0, imageOffset: CGPoint = .zero, spaceCount: Int = 2, trailingImage: Bool = false) { let attributes: StringAttributes = [ .font: font, .foregroundColor: sharedColor, .baselineOffset: titleOffset ] let image = UIImage(imageLiteralResourceName: imageName).maskWithColor(color: sharedColor) let attributedImage = NSAttributedString(image: image, fontDescender: font.descender, imageSize: imageSize, offset: imageOffset) let space = String(repeating: " ", count: spaceCount) let attributedText = NSAttributedString(string: title, attributes: attributes) if trailingImage { self.init(attributedString: attributedText + space + attributedImage) } else { self.init(attributedString: attributedImage + space + attributedText) } } convenience init(string: String, color: UIColor, font: UIFont) { let attributes: StringAttributes = [ .font: font, .foregroundColor: color ] self.init(string: string, attributes: attributes) } }
32.25
94
0.622974
ed182a6a8075f1516389a87e3b901c9db4f43d30
2,193
// // AppDelegate.swift // HHStaticThumbSliderView // // Created by shamzahasan88 on 11/07/2020. // Copyright (c) 2020 shamzahasan88. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
46.659574
285
0.756954
4676aa64273a4c25a61dec7e70505060f2b62d98
2,100
// // ViewController.swift // Demo // // Created by wanghongyun on 2016/12/6. // Copyright © 2016年 wanghongyun. All rights reserved. // import UIKit class ViewController: UIViewController { let cellId = "test" override func viewDidLoad() { super.viewDidLoad() let flowLayout = UICollectionViewFlowLayout() flowLayout.itemSize = CGSize(width: 100, height: 100) flowLayout.minimumInteritemSpacing = 10 flowLayout.minimumLineSpacing = 10 flowLayout.scrollDirection = .horizontal let collectionView = WHYCollectionView(with: view.bounds, layout: flowLayout) collectionView.backgroundColor = .white collectionView.collectionDataSource = self collectionView.collectionInset = UIEdgeInsetsMake(10, 10, 10, 10) collectionView.scrollDirection = .horizontal view.addSubview(collectionView) collectionView.register(cellClass:UICollectionViewCell.classForCoder(), forCellWithReuseIdentifier: cellId) let headerView = UIView(frame: CGRect(x: 110, y: 0, width: 60, height: 60)) headerView.backgroundColor = .red let footerView = UIView(frame: CGRect(x: 0, y: 0, width: 60, height: 60)) footerView.backgroundColor = .green collectionView.collectionHeaderView = headerView collectionView.collectionFooterView = footerView } } extension ViewController: UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 30 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) cell.backgroundColor = .cyan return cell; } }
32.307692
121
0.658571
90b166d2f429c5abc4ad37a5c8a2e9348f175b18
4,263
// // Copyright 2019 Wultra s.r.o. // // 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 extension DocumentationDatabase { /// Patches all repositories where the documentation is composed from single file. This typically /// means that "_Sidebar.md" file has to be created in the repository directory. /// /// - Returns: true if operation succeeded func patchSingleFileDocumentation() -> Bool { Console.info("Patching single docs...") repositories.forEach { repoId, repo in if repoId.contains("/") { return } if repo.params.hasSingleDocument { self.patchSingleFileRepo(repoId: repoId, repo: repo) } } return true } /// Patches repository where the documentation is composed from single file. /// /// - Parameters: /// - repoId: repository identifier /// - repo: RepositoryContent object private func patchSingleFileRepo(repoId: String, repo: RepositoryContent) { let fullIndexFile = repoId.addingPathComponent(effectiveGlobalParameters.targetHomeFile!) guard let document = findDocumentationItem(path: fullIndexFile)?.document else { Console.fatalError("Counld not find `\(fullIndexFile)` in database.") } var lines: [String] if let toc = document.firstMetadata(withName: "TOC") { lines = prepareSidebarContentFromTOC(document: document, toc: toc) } else { lines = prepareSidebarContentFromHeaders(document: document) } lines.insert(contentsOf: [ "<!-- ", " This file was autogenerated by DocuCheck utility.", " Do not manually edit this file.", " -->", "" ], at: 0) let indexFile = effectiveGlobalParameters.targetHomeFile! let sidebarFile = "_Sidebar.md" let sidebarFullPath = repo.fullRepositoryPath.addingPathComponent(sidebarFile) let sidebarDocName = repoId.addingPathComponent(sidebarFile) let sidebarSource = StringDocument(name: sidebarDocName, string: "", fileName: sidebarFullPath) let sidebar = MarkdownDocument(source: sidebarSource, repoIdentifier: repoId) sidebar.add(lines: lines, at: 0) sidebar.referenceCount += 1 // Patch links sidebar.allLinks.forEach { link in if link.path.hasPrefix("#") { link.path = indexFile + link.path } } add(item: sidebar, intoRepo: repo) } private func prepareSidebarContentFromHeaders(document: MarkdownDocument) -> [String] { var lines = [String]() document.allHeaders.forEach { header in let level = header.level if level == 2 { let padding = String(repeating: " ", count: level - 2) let title = header.title let link = header.anchorName let line = "\(padding)- [\(title)](#\(link))" lines.append(line) } } if lines.isEmpty { Console.warning(document, "There are no headers in the document, so sidebar will be empty.") } return lines } private func prepareSidebarContentFromTOC(document: MarkdownDocument, toc: MarkdownMetadata) -> [String] { guard let lines = document.getLinesForMetadata(metadata: toc, includeMarkers: true, removeLines: true) else { Console.error(document, "Unable to get TOC section from the document.") Console.onExit() } return lines.map { $0.toString() } } }
38.754545
117
0.614825
0edbc41813ee5749a981c43419df3dd9fb615b67
220
// // WurdleApp.swift // Wurdle // // Created by Ben Scheirman on 2/3/22. // import SwiftUI @main struct WurdleApp: App { var body: some Scene { WindowGroup { ContentView() } } }
12.222222
39
0.545455
2252ab37d34635df68f59f8c7118db2b8a735e7f
781
// // AnyTransitionExtensions.swift // FuturisticTimer // // Created by Martin Bjeld on 13/05/2020. // Copyright © 2020 Martin Bjeld. All rights reserved. // import SwiftUI extension AnyTransition { static func scaleAndFade(delay: Double = 0) -> AnyTransition { // When "Components" are added let insertion = AnyTransition.scale.combined(with: .opacity) .animation(Animation.spring(response: 0.6, dampingFraction: 0.5).speed(1.2).delay(delay)) // When "Components" are removed let removal = AnyTransition.scale.combined(with: .opacity) .animation(Animation.spring(response: 0.6, dampingFraction: 0.5).speed(1.2)) return .asymmetric(insertion: insertion, removal: removal) } }
31.24
101
0.65557
760d5bb6cc0a7cb715ea5460b913a3425453c34b
5,144
import AVKit import UIKit public protocol PickingMethodControllerDelegate: AnyObject { func pickingMethod(_ pickerController: PickingMethodController, wantToPresent controller: UIViewController) } open class PickingMethodController: UIAlertController { public weak var delegate: PickingMethodControllerDelegate? open func addDefaultActions(isSourceTypeAvailable: (_ sourceType: UIImagePickerController.SourceType) -> Bool = UIImagePickerController.isSourceTypeAvailable) { if isSourceTypeAvailable(.camera) { let action = UIAlertAction(title: "ใช้กล้องถ่ายรูป", style: .default, handler: askForCameraPermission(_:)) addAction(action) } if isSourceTypeAvailable(.photoLibrary) { let action = UIAlertAction(title: "เลือกรูปจากอัลบั้ม", style: .default, handler: openPhotoLibrary(_:)) addAction(action) } let cancelAction = UIAlertAction(title: "ยกเลิก", style: .cancel, handler: nil) addAction(cancelAction) } open func askForCameraPermission(_: UIAlertAction) { askForCameraPermission() } open func askForCameraPermission() { switch AVCaptureDevice.authorizationStatus(for: .video) { case .authorized: openCamera() case .notDetermined: AVCaptureDevice.requestAccess(for: .video) { granted in if granted { self.openCamera() } else { self.askingForPermissionGrant() } } case .denied: askingForPermissionGrant() case .restricted: showRestrictedDialog() @unknown default: showApplicationDoesNotSupportDialog() } } open func openCamera() { let controller = createCameraController() delegate?.pickingMethod(self, wantToPresent: controller) } open func openPhotoLibrary(_: UIAlertAction) { let controller = createPhotoLibraryPicker() delegate?.pickingMethod(self, wantToPresent: controller) } open func askingForPermissionGrant() { let controller = createAskingForPermissionViewController() DispatchQueue.main.async { self.delegate?.pickingMethod(self, wantToPresent: controller) } } open func showRestrictedDialog() { let controller = createCameraRestrictAlertController() delegate?.pickingMethod(self, wantToPresent: controller) } open func showApplicationDoesNotSupportDialog() { let controller = createApplicationDoesNotSupport() delegate?.pickingMethod(self, wantToPresent: controller) } open func gotoApplicationSetting(_: Any) { guard let applicationSettingURL = URL(string: UIApplication.openSettingsURLString) else { return } guard UIApplication.shared.canOpenURL(applicationSettingURL) else { return } if #available(iOS 10.0, *) { UIApplication.shared.open(applicationSettingURL) } else { UIApplication.shared.openURL(applicationSettingURL) } } } // MARK: - Factory extension PickingMethodController { open func getDefaultMessage() -> String { PickingMethodController.getDefaultMessage() } public static func getDefaultMessage() -> String { var string = "คุณสามารถ" var separator = "" if UIImagePickerController.isSourceTypeAvailable(.camera) { string += "ถ่ายรูปใหม่ หรือ " separator = "\n" } return string + "เลือกรูป\(separator)ที่มีอยู่แล้วจากอัลบั้มรูป" } open func createAskingForPermissionViewController() -> UIAlertController { let controller = UIAlertController( title: "กรุณาให้สิทธิ์ใช้งานกล้องถ่ายภาพ", message: "เพื่อใช้ในการถ่ายภาพ", preferredStyle: .alert ) let gotoApplicationSettingAction = UIAlertAction( title: "ดำเนินการต่อ", style: .default, handler: gotoApplicationSetting(_:) ) controller.addAction(gotoApplicationSettingAction) let cancelAction = UIAlertAction(title: "ยกเลิก", style: .cancel, handler: nil) controller.addAction(cancelAction) return controller } open func createCameraController() -> UIImagePickerController { let controller = UIImagePickerController() controller.allowsEditing = true controller.sourceType = .camera return controller } open func createPhotoLibraryPicker() -> UIImagePickerController { let controller = UIImagePickerController() controller.allowsEditing = true controller.sourceType = .photoLibrary return controller } open func createCameraRestrictAlertController() -> UIAlertController { let controller = UIAlertController( title: "กรุณาติดต่อผู้ปกครองของท่าน", message: "ให้อณุญาตใช้งานกล้องถ่ายภาพ", preferredStyle: .alert ) let cancelAction = UIAlertAction(title: "ตกลง", style: .default, handler: nil) controller.addAction(cancelAction) return controller } open func createApplicationDoesNotSupport() -> UIAlertController { let controller = UIAlertController( title: "แอปพลิเคชันยังไม่รอบรับรายการดังกล่าว", message: "โปรดลองอัพเดทแอปพลิเคชัน", preferredStyle: .alert ) let cancelAction = UIAlertAction(title: "ตกลง", style: .default, handler: nil) controller.addAction(cancelAction) return controller } }
30.619048
112
0.713064
d547f17469efe7e1faccd33839dde46f96f4ca8f
511
import Cocoa /// /// Extensions for UI elements. /// extension NSImageView { /// /// Gives an NSImageView a rounded appearance. /// The cornerRadius value indicates the amount of rounding. /// var cornerRadius: CGFloat { get {self.layer?.cornerRadius ?? 0} set { if !self.wantsLayer { self.wantsLayer = true self.layer?.masksToBounds = true; } self.layer?.cornerRadius = newValue; } } }
17.62069
64
0.542074
fc006cd4fff5dcc797f9cc03d350aa90928ad38f
120
import Foundation public protocol Delegate:AnyObject { func refreshed(list:List) func donations(error:Error) }
17.142857
36
0.758333
9b796136b86d1d64ff563b6c934b87d6922fae61
1,393
// // ViewController.swift // TipCalc2 // // Created by Adam Leesman on 12/15/15. // Copyright © 2015 Adam Leesman. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var tipControl: UISegmentedControl! @IBOutlet weak var billField: UITextField! @IBOutlet weak var tipLabel: UILabel! @IBOutlet weak var totalLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() tipLabel.text = "$0.00" totalLabel.text = "$0.00" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func onEditingChanged(sender: AnyObject) { let tipPercentages = [0.18, 0.20, 0.22] let tipPercentage = tipPercentages[tipControl.selectedSegmentIndex] let billAmount=NSString(string:billField.text!).doubleValue let tip = billAmount * tipPercentage let total = billAmount+tip tipLabel.text = "$\(tip)" totalLabel.text = "$\(tip)" tipLabel.text = String(format: "$%.2f",tip) totalLabel.text = String(format: "$%.2f",total) } @IBAction func onTap(sender: AnyObject) { view.endEditing(true) } }
22.467742
76
0.595118
698a73cbe8ea51264c76b3c4a32a7259f281d02f
3,860
// // RGBAColor.swift // Capable // // Created by Christoph Wendt on 20.11.18. // import CoreGraphics struct RGBAColor: Equatable { struct Colors { static let white = RGBAColor(red: 255.0, green: 255.0, blue: 255.0, alpha: 1.0) static let black = RGBAColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0) } var red, green, blue, alpha: CGFloat // https://www.w3.org/TR/WCAG20-TECHS/G17.html var relativeLuminance: CGFloat { func getAdjustedColorComponent(_ colorComponent: CGFloat) -> CGFloat { if colorComponent <= 0.03928 { return colorComponent / 12.92 } else { return pow((colorComponent + 0.055) / 1.055, 2.4) } } let adjustedRed = getAdjustedColorComponent(red / 255.0) let adjustedGreen = getAdjustedColorComponent(green / 255.0) let adjustedBlue = getAdjustedColorComponent(blue / 255.0) return (0.2126 * adjustedRed) + (0.7152 * adjustedGreen) + (0.0722 * adjustedBlue) } } // MARK: - Calculating color properties extension RGBAColor { static func getContrastRatio(forTextColor textColor: RGBAColor, onBackgroundColor backgroundColor: RGBAColor) -> CGFloat { let blendedColor = textColor.alpha < 1.0 ? textColor.blended(withFraction: textColor.alpha, ofColor: backgroundColor) : textColor let textColorLuminance = blendedColor.relativeLuminance let backgroundColorLuminance = backgroundColor.relativeLuminance return (max(textColorLuminance, backgroundColorLuminance) + 0.05) / (min(textColorLuminance, backgroundColorLuminance) + 0.05) } static func isValidColorCombination(textColor: RGBAColor, fontProps: FontProps, onBackgroundColor backgroundColor: RGBAColor, conformanceLevel: ConformanceLevel) -> Bool { let contrastRatio = RGBAColor.getContrastRatio(forTextColor: textColor, onBackgroundColor: backgroundColor) let currentConformanceLevel = ConformanceLevel(contrastRatio: contrastRatio, fontProps: fontProps) return currentConformanceLevel >= conformanceLevel } } // MARK: - Text colors extension RGBAColor { static func getTextColor(onBackgroundColor backgroundColor: RGBAColor) -> RGBAColor { let luminance = backgroundColor.relativeLuminance return luminance > 0.179 ? Colors.black : Colors.white } } // MARK: - Background colors extension RGBAColor { static func getBackgroundColor(forTextColor textColor: RGBAColor) -> RGBAColor { if textColor.alpha < 1.0 { let whiteContrastRatio = getContrastRatio(forTextColor: textColor, onBackgroundColor: Colors.white) let blackContrastRatio = getContrastRatio(forTextColor: textColor, onBackgroundColor: Colors.black) return whiteContrastRatio > blackContrastRatio ? Colors.white : Colors.black } else { return textColor.relativeLuminance > 0.179 ? Colors.black : Colors.white } } } // MARK: - Color operations extension RGBAColor { func blended(withFraction fraction: CGFloat, ofColor color: RGBAColor) -> RGBAColor { func getBlendedColorComponent(aColorComponent: CGFloat, fraction: CGFloat, otherColorComponent: CGFloat) -> CGFloat { let blendedComponent = fraction * aColorComponent + (1 - fraction) * otherColorComponent return blendedComponent } let red = getBlendedColorComponent(aColorComponent: self.red, fraction: alpha, otherColorComponent: color.red) let green = getBlendedColorComponent(aColorComponent: self.green, fraction: alpha, otherColorComponent: color.green) let blue = getBlendedColorComponent(aColorComponent: self.blue, fraction: alpha, otherColorComponent: color.blue) return RGBAColor(red: red, green: green, blue: blue, alpha: 1.0) } }
39.793814
175
0.702332
c1bd1393eb9d03dbcfbf2c6627fbfe26ec3c96a2
380
// // BorderButton.swift // swoosh // // Created by Nguyen Y Nguyen on 12/2/17. // Copyright © 2017 Nguyen Y Nguyen. All rights reserved. // import UIKit class BorderButton: UIButton { override func awakeFromNib() { super.awakeFromNib() layer.borderWidth = 1.0 layer.borderColor = UIColor.white.cgColor layer.cornerRadius = 3.0 } }
18.095238
58
0.642105
61ff1ba4bfab3600c20ca30d662dc3479560c686
825
// // TYPEPersistenceStrategy.swift // import AmberBase import Foundation public class Dictionary_C_InflectionRule_Locale_D_PersistenceStrategy: PersistenceStrategy { public var types: Types { return Types.generic("Dictionary", [Types.type("InflectionRule"), Types.type("Locale")]) } public func save(_ object: Any) throws -> Data { guard let typedObject = object as? Dictionary<InflectionRule, Locale> else { throw AmberError.wrongTypes(self.types, AmberBase.types(of: object)) } let encoder = JSONEncoder() return try encoder.encode(typedObject) } public func load(_ data: Data) throws -> Any { let decoder = JSONDecoder() return try decoder.decode(Dictionary<InflectionRule, Locale>.self, from: data) } }
26.612903
96
0.669091
796f01bf8cce0db2cc3b7b109b194807d383bc06
2,570
import Foundation /// A filename from another module @_spi(Testing) public struct ExternalDependency: Hashable, CustomStringConvertible { let fileName: String @_spi(Testing) public init(_ path: String) { self.fileName = path } public var description: String { fileName.description } } @_spi(Testing) public struct DependencyKey: Hashable { /// Instead of the status quo scheme of two kinds of "Depends", cascading and /// non-cascading this code represents each entity ("Provides" in the status /// quo), by a pair of nodes. One node represents the "implementation." If the /// implementation changes, users of the entity need not be recompiled. The /// other node represents the "interface." If the interface changes, any uses of /// that definition will need to be recompiled. The implementation always /// depends on the interface, since any change that alters the interface will /// require the implementation to be rebuilt. The interface does not depend on /// the implementation. In the dot files, interfaces are yellow and /// implementations white. Each node holds an instance variable describing which /// aspect of the entity it represents. @_spi(Testing) public enum DeclAspect { case interface, implementation } /// Encode the current sorts of dependencies as kinds of nodes in the dependency /// graph, splitting the current *member* into \ref member and \ref /// potentialMember and adding \ref sourceFileProvide. /// @_spi(Testing) public enum Designator: Hashable { case topLevel(name: String), dynamicLookup(name: String), externalDepend(ExternalDependency), sourceFileProvide(name: String) case nominal(context: String), potentialMember(context: String) case member(context: String, name: String) var externalDependency: ExternalDependency? { switch self { case let .externalDepend(externalDependency): return externalDependency default: return nil} } } @_spi(Testing) public let aspect: DeclAspect @_spi(Testing) public let designator: Designator @_spi(Testing) public init( aspect: DeclAspect, designator: Designator) { self.aspect = aspect self.designator = designator } @_spi(Testing) public var correspondingImplementation: Self { assert(aspect == .interface) return Self(aspect: .implementation, designator: designator) } @discardableResult func verify() -> Bool { // This space reserved for future use. return true } }
29.204545
84
0.710506
fe1b24af818ca5ee6355d15422e11b4606f89ec5
1,192
import Foundation import ProjectSpec extension Project { public var xcodeVersion: String { XCodeVersion.parse(options.xcodeVersion ?? "12.0") } var schemeVersion: String { "1.7" } var compatibilityVersion: String { "Xcode 11.0" } var objectVersion: UInt { 51 } } public struct XCodeVersion { public static func parse(_ version: String) -> String { if version.contains(".") { let parts = version.split(separator: ".").map(String.init) var string = "" let major = parts[0] if major.count == 1 { string = "0\(major)" } else { string = major } let minor = parts[1] string += minor if parts.count > 2 { let patch = parts[2] string += patch } else { string += "0" } return string } else if version.count == 2 { return "\(version)00" } else if version.count == 1 { return "0\(version)00" } else { return version } } }
21.672727
70
0.467282
90e464b56c4aece4454f5ff0abc92decc34200d9
693
//: [Previous](@previous) import Foundation var str = "Hello, playground" //: [Next](@next) struct Vector2D { var x = 0.0 var y = 0.0 } // if the operator is existed func +(left: Vector2D, right: Vector2D) -> Vector2D { return Vector2D(x: left.x + right.x, y: right.y + right.y) } // if the operator is not existed precedencegroup DotProductPrecedence { associativity: none higherThan: MultiplicationPrecedence } infix operator +*: DotProductPrecedence func +*(left: Vector2D, right: Vector2D) -> Double { return left.x * right.x + left.y * right.y } // test let v1 = Vector2D(x: 2, y: 3) let v2 = Vector2D(x: 1, y: 4) let v3 = v1 + v2 let v4 = v1 +* v2
16.5
62
0.646465
080c55de4fa83907dd4444098054f84cd2805ed0
230
// // AppConfiguration.swift // xkcd-swift // // Created by Aleksandr Gusev on 01/05/16. // // /// Protocol defining access to the root wireframe instance protocol AppConfiguration { var wireframe: MainWireframe { get } }
17.692308
59
0.7
766bd7e7ec47e0184b673d4c80dba4dbe16e1669
4,525
// // ProgramError.swift // ShapeScript Viewer // // Created by Nick Lockwood on 01/08/2021. // Copyright © 2021 Nick Lockwood. All rights reserved. // import Cocoa import ShapeScript protocol ProgramError { var message: String { get } var range: SourceRange { get } var hint: String? { get } } extension LexerError: ProgramError {} extension ParserError: ProgramError {} extension RuntimeError: ProgramError {} extension ImportError: ProgramError {} extension ProgramError { func rangeAndSource(with source: String) -> (SourceRange?, source: String) { switch self { case let error as ImportError: if case let .runtimeError(error) = error { return error.rangeAndSource(with: source) } return (error.range, source) case let error as ProgramError: switch (error as? RuntimeError)?.type { case let .importError(error, for: _, in: source)?: return error.rangeAndSource(with: source) default: return (error.range, source) } default: return (nil, source) } } } extension Error { func message(with source: String) -> NSAttributedString { var source = source let errorType: String let message: String, range: SourceRange?, hint: String? switch self { case let error as ProgramError: (range, source) = error.rangeAndSource(with: source) switch (error as? RuntimeError)?.type { case .fileAccessRestricted?: errorType = "Permission Required" default: errorType = "Error" } message = error.message hint = error.hint default: errorType = "Error" message = localizedDescription range = nil hint = nil } var location = "." var lineRange: SourceRange? if let range = range { let (line, _) = source.lineAndColumn(at: range.lowerBound) location = " on line \(line)." let lr = source.lineRange(at: range.lowerBound) if !lr.isEmpty { lineRange = lr } } let errorMessage = NSMutableAttributedString() errorMessage.append(NSAttributedString(string: "\(errorType)\n\n", attributes: [ .foregroundColor: NSColor.white, .font: NSFont.systemFont(ofSize: 17, weight: .bold), ])) let body = message + location errorMessage.append(NSAttributedString(string: "\(body)\n\n", attributes: [ .foregroundColor: NSColor.white.withAlphaComponent(0.7), .font: NSFont.systemFont(ofSize: 15, weight: .regular), ])) if let lineRange = lineRange, let range = range, let font = NSFont(name: "Courier", size: 15) { let sourceLine = String(source[lineRange]) let start = source.distance(from: lineRange.lowerBound, to: range.lowerBound) + emojiSpacing(for: source[lineRange.lowerBound ..< range.lowerBound]) let end = min(range.upperBound, lineRange.upperBound) let length = max(1, source.distance(from: range.lowerBound, to: end)) + emojiSpacing(for: source[range.lowerBound ..< end]) var underline = String(repeating: " ", count: max(0, start)) underline += String(repeating: "^", count: length) errorMessage.append(NSAttributedString( string: "\(sourceLine)\n\(underline)\n\n", attributes: [ .foregroundColor: NSColor.white, .font: font, ] )) } if let hint = hint { errorMessage.append(NSAttributedString(string: "\(hint)\n\n", attributes: [ .foregroundColor: NSColor.white.withAlphaComponent(0.7), .font: NSFont.systemFont(ofSize: 15, weight: .regular), ])) } return errorMessage } } private func numberOfEmoji<S: StringProtocol>(in string: S) -> Int { string.reduce(0) { count, c in let scalars = c.unicodeScalars if scalars.count > 1 || (scalars.first?.value ?? 0) > 0x238C { return count + 1 } return count } } private func emojiSpacing<S: StringProtocol>(for string: S) -> Int { Int(Double(numberOfEmoji(in: string)) * 1.25) }
34.807692
91
0.57105
29588d5a8fbe1488ffbe435ddd1109632b5b5887
3,906
// // ToolBarView.swift // CSPickerView // 弹出框顶部显示view // Created by CoderStar on 2021/6/6. // import UIKit @objcMembers open class ToolBarView: UIView { open var title = "" { didSet { titleLabel.text = title } } open var sureAction: PickerViewManager.BtnAction? open var cancelAction: PickerViewManager.BtnAction? // 用来产生上下分割线的效果 private lazy var contentView: UIView = { let content = UIView() content.backgroundColor = PickerViewConfig.shared.mainBackgroundColor return content }() // 文本框 private lazy var titleLabel: UILabel = { let label = UILabel() label.textColor = PickerViewConfig.shared.centerLabelColor label.font = PickerViewConfig.shared.centerLabelFont label.textAlignment = .center label.adjustsFontSizeToFitWidth = true return label }() // 取消按钮 private lazy var clearBtn: UIButton = { let btn = UIButton() btn.setTitle(PickerViewUtils.localizedString(key: "CSPickerView.cancel"), for: .normal) btn.setTitleColor(PickerViewConfig.shared.leftButtonColor, for: .normal) btn.titleLabel?.font = PickerViewConfig.shared.leftButtonFont return btn }() // 完成按钮 private lazy var doneBtn: UIButton = { let donebtn = UIButton() donebtn.setTitle(PickerViewUtils.localizedString(key: "CSPickerView.sure"), for: .normal) donebtn.setTitleColor(PickerViewConfig.shared.rightButtonColor, for: .normal) donebtn.titleLabel?.font = PickerViewConfig.shared.rightButtonFont return donebtn }() override public init(frame: CGRect) { super.init(frame: frame) commonInit() } @available(*, unavailable) required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func commonInit() { backgroundColor = PickerViewConfig.shared.lineColor addSubview(contentView) contentView.addSubview(clearBtn) contentView.addSubview(doneBtn) contentView.addSubview(titleLabel) doneBtn.addTarget(self, action: #selector(self.sureBtnOnClick(_:)), for: .touchUpInside) clearBtn.addTarget(self, action: #selector(self.cancelBtnOnClick(_:)), for: .touchUpInside) } @objc func sureBtnOnClick(_ sender: UIButton) { sureAction?() } @objc func cancelBtnOnClick(_ sender: UIButton) { cancelAction?() } override open func layoutSubviews() { super.layoutSubviews() if PickerViewConfig.shared.toolBarViewTopCornerRadius > 0 { let fieldPath = UIBezierPath(roundedRect: bounds, byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: PickerViewConfig.shared.toolBarViewTopCornerRadius, height: PickerViewConfig.shared.toolBarViewTopCornerRadius)) let fieldLayer = CAShapeLayer() fieldLayer.frame = bounds fieldLayer.path = fieldPath.cgPath layer.mask = fieldLayer } let margin: CGFloat = 15 let contentHeight = bounds.size.height - 1 contentView.frame = CGRect(x: 0, y: 0, width: bounds.size.width, height: contentHeight) let clearBtnSize = clearBtn.sizeThatFits(CGSize(width: 0, height: contentHeight)) let doneBtnSize = doneBtn.sizeThatFits(CGSize(width: 0, height: contentHeight)) clearBtn.frame = CGRect(x: margin, y: 0, width: clearBtnSize.width, height: contentHeight) doneBtn.frame = CGRect(x: bounds.size.width - doneBtnSize.width - margin, y: 0, width: doneBtnSize.width, height: contentHeight) let titleX = clearBtn.frame.maxX + margin let titleW = bounds.size.width - titleX - doneBtnSize.width - margin titleLabel.frame = CGRect(x: titleX, y: 0.0, width: titleW, height: contentHeight) } }
34.875
243
0.669227
7a78a79e623c369a44e2728c63d68cdd55e2bfec
538
// // WebView.swift // ZhiHuDaily // // Created by JasonEWNL on 8/8/20. // import SwiftUI import WebKit struct WebView: UIViewRepresentable { let url: String func makeUIView(context: Context) -> WKWebView { let webView = WKWebView() if let url = URL(string: url) { webView.load(URLRequest(url: url)) webView.allowsBackForwardNavigationGestures = false } return webView } func updateUIView(_ uiView: WKWebView, context: Context) {} }
19.925926
63
0.60223
bb1ec281706b06381190a09cabee442641e64f65
4,339
/* Copyright (C) 2016 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: A class that conforms to the `TVTopShelfProvider` protocol. The Top Shelf extension uses this class to query for items to show. */ import TVServices class ServiceProvider: NSObject, TVTopShelfProvider { // MARK: TVTopShelfProvider /** The style of Top Shelf items to show. Modify this property to view different styles. */ let topShelfStyle: TVTopShelfContentStyle = .Sectioned var topShelfItems: [TVContentItem] { switch topShelfStyle { case .Inset: return insetTopShelfItems case .Sectioned: return sectionedTopShelfItems } } // MARK: Convenience /// An array of `TVContentItem`s to show when `topShelfStyle` returns `.Inset`. private var insetTopShelfItems: [TVContentItem] { // Get an array of `DataItem`s to show on the Top Shelf. let itemsToDisplay = DataItem.sampleItemsForInsetTopShelfItems // Map the array of `DataItem`s to an array of `TVContentItem`s. let contentItems: [TVContentItem] = itemsToDisplay.map { dataItem in return contentItemWithDataItem(dataItem, imageShape: .ExtraWide) } return contentItems } /** An array of `TVContentItem`s to show when `topShelfStyle` returns `.Sectioned`. Each `TVContentItem` in the returned array represents a section of `TVContentItem`s on the Top Shelf. e.g. - TVContentItem, "Iceland" - TVContentItem, "Iceland one" - TVContentItem, "Iceland two" - TVContentItem, "Lola" - TVContentItem, "Lola one" - TVContentItem, "Lola two" */ private var sectionedTopShelfItems: [TVContentItem] { // Get an array of `DataItem` arrays to show on the Top Shelf. let groupedItemsToDisplay = DataItem.sampleItemsForSectionedTopShelfItems /* Map the array of `DataItem` arrays to an array of `TVContentItem`s. Each `TVContentItem` will represent a section of `TVContentItem`s on the Top Shelf. */ let sectionContentItems: [TVContentItem] = groupedItemsToDisplay.map { dataItems in // Determine the title of the `DataItem.Group` that the array of `DataItem`s belong to. let sectionTitle = dataItems.first!.group.rawValue /* Create a `TVContentItem` that will represent a section of `TVContentItem`s on the Top Shelf. */ guard let sectionIdentifier = TVContentIdentifier(identifier: sectionTitle, container: nil) else { fatalError("Error creating content identifier for section item.") } guard let sectionItem = TVContentItem(contentIdentifier: sectionIdentifier) else { fatalError("Error creating section content item.") } sectionItem.title = sectionTitle /* Map the array of `DataItem`s to an array of `TVContentItem`s and assign it to the `TVContentItem` that represents the section of Top Shelf items. */ sectionItem.topShelfItems = dataItems.map { dataItem in return contentItemWithDataItem(dataItem, imageShape: .Square) } return sectionItem } return sectionContentItems } /// Returns a `TVContentItem` for a `DataItem`. private func contentItemWithDataItem(dataItem: DataItem, imageShape: TVContentItemImageShape) -> TVContentItem { guard let contentIdentifier = TVContentIdentifier(identifier: dataItem.identifier, container: nil) else { fatalError("Error creating content identifier.") } guard let contentItem = TVContentItem(contentIdentifier: contentIdentifier) else { fatalError("Error creating content item.") } contentItem.title = dataItem.title contentItem.displayURL = dataItem.displayURL contentItem.imageURL = dataItem.imageURL contentItem.imageShape = imageShape return contentItem } }
39.807339
178
0.632865
5d6d7354c81035e9670e03833a86bec92e878af9
4,009
// // SCRadioButtonGroup.swift // https://github.com/Pimine/ScuffedUI // // This code is distributed under the terms and conditions of the MIT license. // Copyright (c) 2020 Pimine // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit open class SCRadioButtonGroup: UIControl { // MARK: - Public properties public private(set) var selectedIndex = -1 public var spacing: CGFloat { get { container.spacing } set { container.spacing = newValue } } public var distribution: UIStackView.Distribution { get { container.distribution } set { container.distribution = newValue } } public var buttons: [UIButton] { container.arrangedSubviews.compactMap { $0 as? UIButton } } // MARK: - User interface public let container = SCStack() // MARK: - Initialization public init( buttons: [UIButton] = [], spacing: CGFloat = 0.0, distribution: UIStackView.Distribution = .fillEqually) { super.init(frame: .zero) self.spacing = spacing self.distribution = distribution addAndLayoutSubviews() setButtons(buttons) } required public init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Public methods public func setButtons(_ buttons: [UIButton]) { // Remove previous buttons buttons.forEach { container.removeArrangedSubview($0) $0.removeTarget(self, action: #selector(onButtonPressed), for: .touchUpInside) } // Set new buttons for button in buttons { container.addArrangedSubview(button) button.addTarget(self, action: #selector(onButtonPressed), for: .touchUpInside) } } public func selectIndex(_ index: Int) { guard buttons.indices.contains(index) else { return } buttons[index].isSelected = true selectedIndex = index } // MARK: - Action @objc private func onButtonPressed(_ sender: UIButton) { buttons.forEach { $0.isSelected = false } sender.isSelected = true selectedIndex = buttons.firstIndex(of: sender)! sendActions(for: .valueChanged) } } // MARK: - Layout private extension SCRadioButtonGroup { func addAndLayoutSubviews() { // Container addSubview(container) container.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ container.leadingAnchor.constraint(equalTo: leadingAnchor), container.trailingAnchor.constraint(equalTo: trailingAnchor), container.topAnchor.constraint(equalTo: topAnchor), container.bottomAnchor.constraint(equalTo: bottomAnchor) ]) } }
31.566929
91
0.645548
ed83a81d640227cd93c389e2981a9cd070672485
6,037
func foo(a a: String) {} func foo(a a: Int) {} func foo(b b: Int) {} func test() { let x = 1 } // XFAIL: broken_std_regex // RUN: %sourcekitd-test -req=complete -req-opts=hidelowpriority=0 -pos=7:1 %s -- %s > %t.orig // RUN: %FileCheck -check-prefix=NAME %s < %t.orig // Make sure the order is as below, foo(Int) should come before foo(String). // NAME: key.description: "#column" // NAME: key.description: "foo(a: Int)" // NAME-NOT: key.description // NAME: key.description: "foo(a: String)" // NAME-NOT: key.description // NAME: key.description: "foo(b: Int)" // NAME: key.description: "test()" // NAME: key.description: "x" // RUN: %sourcekitd-test -req=complete.open -pos=7:1 -req-opts=hidelowpriority=0,hideunderscores=0 %s -- %s > %t.default // RUN: %sourcekitd-test -req=complete.open -pos=7:1 -req-opts=sort.byname=0,hidelowpriority=0,hideunderscores=0 %s -- %s > %t.on // RUN: %sourcekitd-test -req=complete.open -pos=7:1 -req-opts=sort.byname=1,hidelowpriority=0,hideunderscores=0 %s -- %s > %t.off // RUN: %FileCheck -check-prefix=CONTEXT %s < %t.default // RUN: %FileCheck -check-prefix=NAME %s < %t.off // FIXME: rdar://problem/20109989 non-deterministic sort order // RUN-disabled: diff %t.on %t.default // RUN: %FileCheck -check-prefix=CONTEXT %s < %t.on // CONTEXT: key.kind: source.lang.swift.decl // CONTEXT-NEXT: key.name: "x" // CONTEXT-NOT: key.name: // CONTEXT: key.name: "foo(a:)" // CONTEXT-NOT: key.name: // CONTEXT: key.name: "foo(a:)" // CONTEXT-NOT: key.name: // CONTEXT: key.name: "foo(b:)" // CONTEXT-NOT: key.name: // CONTEXT: key.name: "test()" // CONTEXT: key.name: "#column" // CONTEXT: key.name: "complete_sort_order" // RUN: %complete-test -tok=STMT_0 %s | %FileCheck %s -check-prefix=STMT func test1() { #^STMT_0^# } // STMT: let // STMT: var // STMT: if // STMT: for // STMT: while // STMT: return // STMT: func // STMT: foo(a: Int) // RUN: %complete-test -tok=STMT_1 %s | %FileCheck %s -check-prefix=STMT_1 func test5() { var retLocal: Int #^STMT_1,r,ret,retur,return^# } // STMT_1-LABEL: Results for filterText: r [ // STMT_1-NEXT: return // STMT_1-NEXT: retLocal // STMT_1-NEXT: repeat // STMT_1-NEXT: required // STMT_1: ] // STMT_1-LABEL: Results for filterText: ret [ // STMT_1-NEXT: return // STMT_1-NEXT: retLocal // STMT_1-NEXT: repeat // STMT_1: ] // STMT_1-LABEL: Results for filterText: retur [ // STMT_1-NEXT: return // STMT_1: ] // STMT_1-LABEL: Results for filterText: return [ // STMT_1-NEXT: return // STMT_1: ] // RUN: %complete-test -top=0 -tok=EXPR_0 %s | %FileCheck %s -check-prefix=EXPR func test2() { (#^EXPR_0^#) } // EXPR: 0 // EXPR: "abc" // EXPR: true // EXPR: false // EXPR: #colorLiteral(red: Float, green: Float, blue: Float, alpha: Float) // EXPR: #imageLiteral(resourceName: String) // EXPR: [values] // EXPR: [key: value] // EXPR: (values) // EXPR: nil // EXPR: foo(a: Int) // Top 1 // RUN: %complete-test -top=1 -tok=EXPR_1 %s | %FileCheck %s -check-prefix=EXPR_TOP_1 func test3(x: Int) { let y = x let z = x let zzz = x (#^EXPR_1^#) } // EXPR_TOP_1: x // EXPR_TOP_1: 0 // EXPR_TOP_1: "abc" // EXPR_TOP_1: true // EXPR_TOP_1: false // EXPR_TOP_1: #colorLiteral(red: Float, green: Float, blue: Float, alpha: Float) // EXPR_TOP_1: #imageLiteral(resourceName: String) // EXPR_TOP_1: [values] // EXPR_TOP_1: [key: value] // EXPR_TOP_1: (values) // EXPR_TOP_1: nil // EXPR_TOP_1: y // EXPR_TOP_1: z // EXPR_TOP_1: zzz // Test where there are fewer results than 'top'. // RUN: %complete-test -top=1000 -tok=FEW_1 %s | %FileCheck %s -check-prefix=FEW_1 func test3b() -> Int { return #^FEW_1^# } // FEW_1: test3b() // FEW_1: Int // FEW_1: 0 // Top 3 // RUN: %complete-test -top=3 -tok=EXPR_2 %s | %FileCheck %s -check-prefix=EXPR_TOP_3 func test4(x: Int) { let y = x let z = x let zzz = x (#^EXPR_2^#) } // EXPR_TOP_3: x // EXPR_TOP_3: y // EXPR_TOP_3: z // EXPR_TOP_3: 0 // EXPR_TOP_3: "abc" // EXPR_TOP_3: true // EXPR_TOP_3: false // EXPR_TOP_3: #colorLiteral(red: Float, green: Float, blue: Float, alpha: Float) // EXPR_TOP_3: #imageLiteral(resourceName: String) // EXPR_TOP_3: [values] // EXPR_TOP_3: [key: value] // EXPR_TOP_3: (values) // EXPR_TOP_3: nil // EXPR_TOP_3: zzz // Top 3 with type matching // RUN: %complete-test -top=3 -tok=EXPR_3 %s | %FileCheck %s -check-prefix=EXPR_TOP_3_TYPE_MATCH func test4(x: Int) { let y: String = "" let z: String = y let zzz = x let bar: Int = #^EXPR_3^# } // EXPR_TOP_3_TYPE_MATCH: x // EXPR_TOP_3_TYPE_MATCH: zzz // EXPR_TOP_3_TYPE_MATCH: 0 // EXPR_TOP_3_TYPE_MATCH: y // EXPR_TOP_3_TYPE_MATCH: z // RUN: %complete-test -tok=VOID_1 %s | %FileCheck %s -check-prefix=VOID_1 // RUN: %complete-test -tok=VOID_1 %s -raw | %FileCheck %s -check-prefix=VOID_1_RAW func test6() { func foo1() {} func foo2() -> Int {} func foo3() -> String {} let x: Int x = #^VOID_1,,foo^# } // VOID_1-LABEL: Results for filterText: [ // VOID_1-NOT: foo1 // VOID_1: foo2() // VOID_1-NOT: foo1 // VOID_1: foo3() // VOID_1-NOT: foo1 // VOID_1: ] // VOID_1-LABEL: Results for filterText: foo [ // VOID_1: foo2() // VOID_1: foo3() // VOID_1: foo1() // VOID_1: ] // VOID_1_RAW: key.name: "foo1()", // VOID_1_RAW-NEXT: key.sourcetext: "foo1()", // VOID_1_RAW-NEXT: key.description: "foo1()", // VOID_1_RAW-NEXT: key.typename: "Void", // VOID_1_RAW-NEXT: key.context: source.codecompletion.context.local, // VOID_1_RAW-NEXT: key.num_bytes_to_erase: 0, // VOID_1_RAW-NEXT: key.not_recommended: 1, // RUN: %complete-test -tok=CASE_0 %s | %FileCheck %s -check-prefix=CASE_0 func test7() { struct CaseSensitiveCheck { var member: Int = 0 } let caseSensitiveCheck = CaseSensitiveCheck() #^CASE_0,caseSensitiveCheck,CaseSensitiveCheck^# } // CASE_0: Results for filterText: caseSensitiveCheck [ // CASE_0: CaseSensitiveCheck // CASE_0: caseSensitiveCheck // CASE_0: caseSensitiveCheck. // CASE_0: ] // CASE_0: Results for filterText: CaseSensitiveCheck [ // CASE_0: caseSensitiveCheck // CASE_0: CaseSensitiveCheck // CASE_0: CaseSensitiveCheck( // CASE_0: ]
27.820276
130
0.662581
f8731e5fd03d6ac355036d6380f5b1f5dce29cee
647
// // OSLog+Extensions.swift // iOSSampleApp // // Created by Igor Kulman on 29/03/2019. // Copyright © 2019 Igor Kulman. All rights reserved. // import Foundation import os.log extension OSLog { private static var subsystem = Bundle.main.bundleIdentifier! static let data = OSLog(subsystem: subsystem, category: "data") static let conditions = OSLog(subsystem: subsystem, category: "conditions") static let lifeCycle = OSLog(subsystem: subsystem, category: "lifeCycle") static func log(_ message: String, log: OSLog = .default, type: OSLogType = .default) { os_log("%@", log: log, type: type, message) } }
28.130435
91
0.692427
69233f46accd51b514f8e488a3ddb62700e0f3a8
2,305
// // SceneDelegate.swift // AlbumMarvel // // Created by Gabriel Souza de Araujo on 17/08/21. // import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). guard let _ = (scene as? UIWindowScene) else { return } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. } }
43.490566
147
0.713666
381d7cb5712692987c4a8b1a6905d9f1342a3771
782
// Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/ extension AKOperation { /// Gate based linear AHD envelope generator /// /// - Parameters: /// - gate: 1 for on and 0 for off /// - attack: Attack duration, in seconds. (Default: 0.1) /// - hold: Hold duration, in seconds. (Default: 0.3) /// - release: Release duration, in seconds. (Default: 0.2) /// public func gatedADSREnvelope( gate: AKParameter, attack: AKParameter = 0.1, decay: AKParameter = 0.0, sustain: AKParameter = 1, release: AKParameter = 0.2 ) -> AKOperation { return AKOperation(module: "adsr *", inputs: toMono(), gate, attack, decay, sustain, release) } }
34
101
0.606138
fecccfa09316d4b8cdf984bec3c56c16be27339f
260
// // ItemsPresenterInterface.swift // CiaoExample // // Created by Alberto Aznar de los Ríos on 10/9/18. // Copyright © 2018 Alberto Aznar de los Ríos. All rights reserved. // import Foundation protocol ItemsPresenterInterface { func viewLoaded() }
18.571429
68
0.723077
265bf804fc21e2a65919839c1cf1369a256e9a56
31,029
// // PanModalPresentationController.swift // PanModal // // Copyright © 2019 Tiny Speck, Inc. All rights reserved. // import UIKit /** The PanModalPresentationController is the middle layer between the presentingViewController and the presentedViewController. It controls the coordination between the individual transition classes as well as provides an abstraction over how the presented view is presented & displayed. For example, we add a drag indicator view above the presented view and a background overlay between the presenting & presented view. The presented view's layout configuration & presentation is defined using the PanModalPresentable. By conforming to the PanModalPresentable protocol & overriding values the presented view can define its layout configuration & presentation. */ public class PanModalPresentationController: UIPresentationController { /** Enum representing the possible presentation states */ public enum PresentationState { case shortForm case longForm } /** Constants */ struct Constants { static let indicatorYOffset = CGFloat(8.0) static let snapMovementSensitivity = CGFloat(0.7) static let dragIndicatorSize = CGSize(width: 36.0, height: 5.0) } // MARK: - Properties /** A flag to track if the presented view is animating */ private var isPresentedViewAnimating = false /** A flag to determine if scrolling should seamlessly transition from the pan modal container view to the scroll view once the scroll limit has been reached. */ private var extendsPanScrolling = true /** A flag to determine if scrolling should be limited to the longFormHeight. Return false to cap scrolling at .max height. */ private var anchorModalToLongForm = true /** The y content offset value of the embedded scroll view */ private var scrollViewYOffset: CGFloat = 0.0 /** An observer for the scroll view content offset */ private var scrollObserver: NSKeyValueObservation? // store the y positions so we don't have to keep re-calculating /** The y value for the short form presentation state */ private var shortFormYPosition: CGFloat = 0 /** The y value for the long form presentation state */ private var longFormYPosition: CGFloat = 0 /** Determine anchored Y postion based on the `anchorModalToLongForm` flag */ private var anchoredYPosition: CGFloat { let defaultTopOffset = presentable?.topOffset ?? 0 return anchorModalToLongForm ? longFormYPosition : defaultTopOffset } /** Configuration object for PanModalPresentationController */ private var presentable: PanModalPresentable? { return presentedViewController as? PanModalPresentable } // MARK: - Views /** Background view used as an overlay over the presenting view */ private lazy var backgroundView: DimmedView = { let view: DimmedView if let alpha = presentable?.backgroundAlpha { view = DimmedView(dimAlpha: alpha) } else { view = DimmedView() } view.didTap = { [weak self] _ in self?.dismissPresentedViewController() } return view }() /** A wrapper around the presented view so that we can modify the presented view apperance without changing the presented view's properties */ private lazy var panContainerView: PanContainerView = { let frame = containerView?.frame ?? .zero return PanContainerView(presentedView: presentedViewController.view, frame: frame) }() /** Drag Indicator View */ private lazy var dragIndicatorView: UIView = { let view = UIView() view.layer.cornerRadius = Constants.dragIndicatorSize.height / 2.0 return view }() /** Override presented view to return the pan container wrapper */ public override var presentedView: UIView { return panContainerView } // MARK: - Gesture Recognizers /** Gesture recognizer to detect & track pan gestures */ private lazy var panGestureRecognizer: UIPanGestureRecognizer = { let gesture = UIPanGestureRecognizer(target: self, action: #selector(didPanOnPresentedView(_ :))) gesture.minimumNumberOfTouches = 1 gesture.maximumNumberOfTouches = 1 gesture.delegate = self return gesture }() // MARK: - Deinitializers deinit { scrollObserver?.invalidate() } // MARK: - Lifecycle override public func containerViewWillLayoutSubviews() { super.containerViewWillLayoutSubviews() configureViewLayout() } override public func presentationTransitionWillBegin() { guard let containerView = containerView else { return } layoutBackgroundView(in: containerView) layoutPresentedView(in: containerView) configureScrollViewInsets() guard let coordinator = presentedViewController.transitionCoordinator else { backgroundView.dimState = .max return } coordinator.animate(alongsideTransition: { [weak self] _ in self?.backgroundView.dimState = .max self?.presentedViewController.setNeedsStatusBarAppearanceUpdate() }) } override public func dismissalTransitionWillBegin() { guard let coordinator = presentedViewController.transitionCoordinator else { backgroundView.dimState = .off return } /** Drag indicator is drawn outside of view bounds so hiding it on view dismiss means avoiding visual bugs */ coordinator.animate(alongsideTransition: { [weak self] _ in self?.dragIndicatorView.alpha = 0.0 self?.backgroundView.dimState = .off self?.presentingViewController.setNeedsStatusBarAppearanceUpdate() }) } override public func presentationTransitionDidEnd(_ completed: Bool) { if completed { return } backgroundView.removeFromSuperview() } /** Update presented view size in response to size class changes */ override public func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) coordinator.animate(alongsideTransition: { [weak self] _ in guard let self = self, let presentable = self.presentable else { return } self.adjustPresentedViewFrame() if presentable.shouldRoundTopCorners { self.addRoundedCorners(to: self.presentedView) } }) } } // MARK: - Public Methods public extension PanModalPresentationController { /** Transition the PanModalPresentationController to the given presentation state */ func transition(to state: PresentationState) { guard presentable?.shouldTransition(to: state) == true else { return } presentable?.willTransition(to: state) switch state { case .shortForm: snap(toYPosition: shortFormYPosition) case .longForm: snap(toYPosition: longFormYPosition) } } /** Set the content offset of the scroll view Due to content offset observation, its not possible to programmatically set the content offset directly on the scroll view while in the short form. This method pauses the content offset KVO, performs the content offset change and then resumes content offset observation. */ func setContentOffset(offset: CGPoint) { guard let scrollView = presentable?.panScrollable else { return } /** Invalidate scroll view observer to prevent its overriding the content offset change */ scrollObserver?.invalidate() scrollObserver = nil /** Set scroll view offset & track scrolling */ scrollView.setContentOffset(offset, animated:false) trackScrolling(scrollView) /** Add the scroll view observer */ observe(scrollView: scrollView) } /** Updates the PanModalPresentationController layout based on values in the PanModalPresentable - Note: This should be called whenever any pan modal presentable value changes after the initial presentation */ func setNeedsLayoutUpdate() { configureViewLayout() adjustPresentedViewFrame() observe(scrollView: presentable?.panScrollable) configureScrollViewInsets() } } // MARK: - Presented View Layout Configuration private extension PanModalPresentationController { /** Boolean flag to determine if the presented view is anchored */ var isPresentedViewAnchored: Bool { if !isPresentedViewAnimating && extendsPanScrolling && presentedView.frame.minY <= anchoredYPosition { return true } return false } /** Adds the presented view to the given container view & configures the view elements such as drag indicator, rounded corners based on the pan modal presentable. */ func layoutPresentedView(in containerView: UIView) { /** If the presented view controller does not conform to pan modal presentable don't configure */ guard let presentable = presentable else { return } /** ⚠️ If this class is NOT used in conjunction with the PanModalPresentationAnimator & PanModalPresentable, the presented view should be added to the container view in the presentation animator instead of here */ containerView.addSubview(presentedView) containerView.addGestureRecognizer(panGestureRecognizer) if presentable.showDragIndicator { addDragIndicatorView(to: presentedView) dragIndicatorView.backgroundColor = presentable.dragIndicatorColor } if presentable.shouldRoundTopCorners { addRoundedCorners(to: presentedView) } setNeedsLayoutUpdate() adjustPanContainerBackgroundColor() } /** Reduce height of presentedView so that it sits at the bottom of the screen */ func adjustPresentedViewFrame() { guard let frame = containerView?.frame else { return } let adjustedSize = CGSize(width: frame.size.width, height: frame.size.height - anchoredYPosition) panContainerView.frame.size = frame.size presentedViewController.view.frame = CGRect(origin: .zero, size: adjustedSize) } /** Adds a background color to the pan container view in order to avoid a gap at the bottom during initial view presentation in longForm (when view bounces) */ func adjustPanContainerBackgroundColor() { panContainerView.backgroundColor = presentedViewController.view.backgroundColor ?? presentable?.panScrollable?.backgroundColor } /** Adds the background view to the view hierarchy & configures its layout constraints. */ func layoutBackgroundView(in containerView: UIView) { containerView.addSubview(backgroundView) backgroundView.translatesAutoresizingMaskIntoConstraints = false backgroundView.topAnchor.constraint(equalTo: containerView.topAnchor).isActive = true backgroundView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor).isActive = true backgroundView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor).isActive = true backgroundView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor).isActive = true } /** Adds the drag indicator view to the view hierarchy & configures its layout constraints. */ func addDragIndicatorView(to view: UIView) { view.addSubview(dragIndicatorView) dragIndicatorView.translatesAutoresizingMaskIntoConstraints = false dragIndicatorView.topAnchor.constraint(equalTo: view.topAnchor, constant: Constants.indicatorYOffset).isActive = true dragIndicatorView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true dragIndicatorView.widthAnchor.constraint(equalToConstant: Constants.dragIndicatorSize.width).isActive = true dragIndicatorView.heightAnchor.constraint(equalToConstant: Constants.dragIndicatorSize.height).isActive = true } /** Calculates & stores the layout anchor points & options */ func configureViewLayout() { guard let layoutPresentable = presentedViewController as? PanModalPresentable.LayoutType else { return } shortFormYPosition = layoutPresentable.shortFormYPos longFormYPosition = layoutPresentable.longFormYPos anchorModalToLongForm = layoutPresentable.anchorModalToLongForm extendsPanScrolling = layoutPresentable.allowsExtendedPanScrolling containerView?.isUserInteractionEnabled = layoutPresentable.isUserInteractionEnabled } /** Configures the scroll view insets */ func configureScrollViewInsets() { guard let scrollView = presentable?.panScrollable, !scrollView.isScrolling else { return } /** Disable vertical scroll indicator until we start to scroll to avoid visual bugs */ scrollView.showsVerticalScrollIndicator = false scrollView.scrollIndicatorInsets = presentable?.scrollIndicatorInsets ?? .zero /** Set the appropriate contentInset as the configuration within this class offsets it */ scrollView.contentInset.bottom = presentingViewController.bottomLayoutGuide.length /** As we adjust the bounds during `handleScrollViewTopBounce` we should assume that contentInsetAdjustmentBehavior will not be correct */ if #available(iOS 11.0, *) { scrollView.contentInsetAdjustmentBehavior = .never } } } // MARK: - Pan Gesture Event Handler private extension PanModalPresentationController { /** The designated function for handling pan gesture events */ @objc func didPanOnPresentedView(_ recognizer: UIPanGestureRecognizer) { guard shouldRespond(to: recognizer), let containerView = containerView else { recognizer.setTranslation(.zero, in: recognizer.view) return } switch recognizer.state { case .began, .changed: /** Respond accordingly to pan gesture translation */ respond(to: recognizer) /** If presentedView is translated above the longForm threshold, treat as transition */ if presentedView.frame.origin.y == anchoredYPosition && extendsPanScrolling { presentable?.willTransition(to: .longForm) } default: /** Use velocity sensitivity value to restrict snapping */ let velocity = recognizer.velocity(in: presentedView) if isVelocityWithinSensitivityRange(velocity.y) { /** If velocity is within the sensitivity range, transition to a presentation state or dismiss entirely. This allows the user to dismiss directly from long form instead of going to the short form state first. */ if velocity.y < 0 { transition(to: .longForm) } else if (nearest(to: presentedView.frame.minY, inValues: [longFormYPosition, containerView.bounds.height]) == longFormYPosition && presentedView.frame.minY < shortFormYPosition) || presentable?.allowsDragToDismiss == false { transition(to: .shortForm) } else { dismissPresentedViewController() } } else { /** The `containerView.bounds.height` is used to determine how close the presented view is to the bottom of the screen */ let position = nearest(to: presentedView.frame.minY, inValues: [containerView.bounds.height, shortFormYPosition, longFormYPosition]) if position == longFormYPosition { transition(to: .longForm) } else if position == shortFormYPosition || presentable?.allowsDragToDismiss == false { transition(to: .shortForm) } else { dismissPresentedViewController() } } } } /** Determine if the pan modal should respond to the gesture recognizer. If the pan modal is already being dragged & the delegate returns false, ignore until the recognizer is back to it's original state (.began) ⚠️ This is the only time we should be cancelling the pan modal gesture recognizer */ func shouldRespond(to panGestureRecognizer: UIPanGestureRecognizer) -> Bool { guard presentable?.shouldRespond(to: panGestureRecognizer) == true || !(panGestureRecognizer.state == .began || panGestureRecognizer.state == .cancelled) else { panGestureRecognizer.isEnabled = false panGestureRecognizer.isEnabled = true return false } return !shouldFail(panGestureRecognizer: panGestureRecognizer) } /** Communicate intentions to presentable and adjust subviews in containerView */ func respond(to panGestureRecognizer: UIPanGestureRecognizer) { presentable?.willRespond(to: panGestureRecognizer) var yDisplacement = panGestureRecognizer.translation(in: presentedView).y /** If the presentedView is not anchored to long form, reduce the rate of movement above the threshold */ if presentedView.frame.origin.y < longFormYPosition { yDisplacement /= 2.0 } adjust(toYPosition: presentedView.frame.origin.y + yDisplacement) panGestureRecognizer.setTranslation(.zero, in: presentedView) } /** Determines if we should fail the gesture recognizer based on certain conditions We fail the presented view's pan gesture recognizer if we are actively scrolling on the scroll view. This allows the user to drag whole view controller from outside scrollView touch area. Unfortunately, cancelling a gestureRecognizer means that we lose the effect of transition scrolling from one view to another in the same pan gesture so don't cancel */ func shouldFail(panGestureRecognizer: UIPanGestureRecognizer) -> Bool { /** Allow api consumers to override the internal conditions & decide if the pan gesture recognizer should be prioritized. ⚠️ This is the only time we should be cancelling the panScrollable recognizer, for the purpose of ensuring we're no longer tracking the scrollView */ guard !shouldPrioritize(panGestureRecognizer: panGestureRecognizer) else { presentable?.panScrollable?.panGestureRecognizer.isEnabled = false presentable?.panScrollable?.panGestureRecognizer.isEnabled = true return false } guard isPresentedViewAnchored, let scrollView = presentable?.panScrollable, scrollView.contentOffset.y > -scrollView.contentInset.top else { return false } let loc = panGestureRecognizer.location(in: presentedView) return (scrollView.frame.contains(loc) || scrollView.isScrolling) } /** Determine if the presented view's panGestureRecognizer should be prioritized over embedded scrollView's panGestureRecognizer. */ func shouldPrioritize(panGestureRecognizer: UIPanGestureRecognizer) -> Bool { return panGestureRecognizer.state == .began && presentable?.shouldPrioritize(panModalGestureRecognizer: panGestureRecognizer) == true } /** Check if the given velocity is within the sensitivity range */ func isVelocityWithinSensitivityRange(_ velocity: CGFloat) -> Bool { return (abs(velocity) - (1000 * (1 - Constants.snapMovementSensitivity))) > 0 } func snap(toYPosition yPos: CGFloat) { PanModalAnimator.animate({ [weak self] in self?.adjust(toYPosition: yPos) self?.isPresentedViewAnimating = true }, config: presentable) { [weak self] didComplete in self?.isPresentedViewAnimating = !didComplete } } /** Sets the y position of the presentedView & adjusts the backgroundView. */ func adjust(toYPosition yPos: CGFloat) { presentedView.frame.origin.y = max(yPos, anchoredYPosition) guard presentedView.frame.origin.y > shortFormYPosition else { backgroundView.dimState = .max return } let yDisplacementFromShortForm = presentedView.frame.origin.y - shortFormYPosition /** Once presentedView is translated below shortForm, calculate yPos relative to bottom of screen and apply percentage to backgroundView alpha */ backgroundView.dimState = .percent(1.0 - (yDisplacementFromShortForm / presentedView.frame.height)) } /** Finds the nearest value to a given number out of a given array of float values - Parameters: - number: reference float we are trying to find the closest value to - values: array of floats we would like to compare against */ func nearest(to number: CGFloat, inValues values: [CGFloat]) -> CGFloat { guard let nearestVal = values.min(by: { abs(number - $0) < abs(number - $1) }) else { return number } return nearestVal } /** Dismiss presented view */ func dismissPresentedViewController() { presentable?.panModalWillDismiss() presentedViewController.dismiss(animated: true, completion: nil) } } // MARK: - UIScrollView Observer private extension PanModalPresentationController { /** Creates & stores an observer on the given scroll view's content offset. This allows us to track scrolling without overriding the scrollView delegate */ func observe(scrollView: UIScrollView?) { /** Set this value incase we have a UIScrollView with a non-zero contentInset */ if let scrollView = scrollView, scrollView.contentInset.top != 0, scrollViewYOffset == 0 { scrollViewYOffset = -scrollView.contentInset.top } scrollObserver?.invalidate() scrollObserver = scrollView?.observe(\.contentOffset, options: .old) { [weak self] scrollView, change in /** Incase we have a situation where we have two containerViews in the same presentation */ guard self?.containerView != nil else { return } self?.didPanOnScrollView(scrollView, change: change) } } /** Scroll view content offset change event handler Also when scrollView is scrolled to the top, we disable the scroll indicator otherwise glitchy behaviour occurs This is also shown in Apple Maps (reverse engineering) which allows us to seamlessly transition scrolling from the panContainerView to the scrollView */ func didPanOnScrollView(_ scrollView: UIScrollView, change: NSKeyValueObservedChange<CGPoint>) { guard !presentedViewController.isBeingDismissed, !presentedViewController.isBeingPresented else { return } if !isPresentedViewAnchored && scrollView.contentOffset.y > scrollView.contentInset.top { /** Hold the scrollView in place if we're actively scrolling and not handling top bounce */ haltScrolling(scrollView) } else if scrollView.isScrolling || isPresentedViewAnimating { if isPresentedViewAnchored { /** While we're scrolling upwards on the scrollView, store the last content offset position */ trackScrolling(scrollView) } else { /** Keep scroll view in place while we're panning on main view */ haltScrolling(scrollView) } } else if presentedViewController.view.isKind(of: UIScrollView.self) && !isPresentedViewAnimating && scrollView.contentOffset.y <= -scrollView.contentInset.top { /** In the case where we drag down quickly on the scroll view and let go, `handleScrollViewTopBounce` adds a nice elegant touch. */ handleScrollViewTopBounce(scrollView: scrollView, change: change) } else { trackScrolling(scrollView) } } /** Halts the scroll of a given scroll view & anchors it at the `scrollViewYOffset` */ func haltScrolling(_ scrollView: UIScrollView) { scrollView.setContentOffset(CGPoint(x: -scrollView.contentInset.left, y: scrollViewYOffset), animated: false) scrollView.showsVerticalScrollIndicator = false } /** As the user scrolls, track & save the scroll view y offset. This helps halt scrolling when we want to hold the scroll view in place. */ func trackScrolling(_ scrollView: UIScrollView) { scrollViewYOffset = max(scrollView.contentOffset.y, -scrollView.contentInset.top) scrollView.showsVerticalScrollIndicator = true } /** To ensure that the scroll transition between the scrollView & the modal is completely seamless, we need to handle the case where content offset is negative. In this case, we follow the curve of the decelerating scroll view. This gives the effect that the modal view and the scroll view are one view entirely. - Note: This works best where the view behind view controller is a UIScrollView. So, for example, a UITableViewController. */ func handleScrollViewTopBounce(scrollView: UIScrollView, change: NSKeyValueObservedChange<CGPoint>) { guard let oldYValue = change.oldValue?.y else { return } let oldYOffset = oldYValue + scrollView.contentInset.top let yOffset = scrollView.contentOffset.y + scrollView.contentInset.top let presentedSize = containerView?.frame.size ?? .zero /** Decrease the view bounds by the y offset so the scroll view stays in place and we can still get updates on its content offset */ presentedView.bounds.size = CGSize(width: presentedSize.width, height: presentedSize.height + yOffset) if oldYOffset > yOffset { /** Move the view in the opposite direction to the decreasing bounds until half way through the deceleration so that it appears as if we're transferring the scrollView drag momentum to the entire view */ presentedView.frame.origin.y = longFormYPosition - yOffset } else { scrollViewYOffset = -scrollView.contentInset.top snap(toYPosition: longFormYPosition) } scrollView.showsVerticalScrollIndicator = false } } // MARK: - UIGestureRecognizerDelegate extension PanModalPresentationController: UIGestureRecognizerDelegate { /** Do not require any other gesture recognizers to fail */ public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer) -> Bool { return false } /** Allow simultaneous gesture recognizers only when the other gesture recognizer is a pan gesture recognizer */ public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { return otherGestureRecognizer.isKind(of: UIPanGestureRecognizer.self) } } // MARK: - UIBezierPath private extension PanModalPresentationController { /** Draws top rounded corners on a given view We have to set a custom path for corner rounding because we render the dragIndicator outside of view bounds */ func addRoundedCorners(to view: UIView) { let radius = presentable?.cornerRadius ?? 0 let path = UIBezierPath(roundedRect: view.bounds, byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: radius, height: radius)) // Draw around the drag indicator view, if displayed if presentable?.showDragIndicator == true { let indicatorLeftEdgeXPos = view.bounds.width/2.0 - Constants.dragIndicatorSize.width/2.0 drawAroundDragIndicator(currentPath: path, indicatorLeftEdgeXPos: indicatorLeftEdgeXPos) } // Set path as a mask to display optional drag indicator view & rounded corners let mask = CAShapeLayer() mask.path = path.cgPath view.layer.mask = mask // Improve performance by rasterizing the layer view.layer.shouldRasterize = true view.layer.rasterizationScale = UIScreen.main.scale } /** Draws a path around the drag indicator view */ func drawAroundDragIndicator(currentPath path: UIBezierPath, indicatorLeftEdgeXPos: CGFloat) { let totalIndicatorOffset = Constants.indicatorYOffset + Constants.dragIndicatorSize.height // Draw around drag indicator starting from the left path.addLine(to: CGPoint(x: indicatorLeftEdgeXPos, y: path.currentPoint.y)) path.addLine(to: CGPoint(x: path.currentPoint.x, y: path.currentPoint.y - totalIndicatorOffset)) path.addLine(to: CGPoint(x: path.currentPoint.x + Constants.dragIndicatorSize.width, y: path.currentPoint.y)) path.addLine(to: CGPoint(x: path.currentPoint.x, y: path.currentPoint.y + totalIndicatorOffset)) } } // MARK: - Helper Extensions private extension UIScrollView { /** A flag to determine if a scroll view is scrolling */ var isScrolling: Bool { return isDragging && !isDecelerating || isTracking } }
34.476667
164
0.658449
018cad0dc23b8211b9080e8d5907a64c9a3cf390
3,444
// // KMConversationService+ConversationFeedback.swift // Kommunicate // // Created by Mukesh on 30/12/19. // import Foundation extension KMConversationService { private enum FeedbackParamKey { static let groupId = "groupId" static let comment = "comments" static let rating = "rating" } /// Fetches conversation feedback for the given group id. /// - Parameters: /// - groupId: Group id for which feedback has to be fetched. /// - completion: A Result of type `ConversationFeedback`. func feedbackFor( groupId: Int, completion: @escaping (Result<ConversationFeedback, FeedbackError>)->() ) { guard let url = URLBuilder.feedbackURLFor(groupId: String(describing: groupId)).url else { completion(.failure(.api(.urlBuilding))) return } DataLoader.request(url: url) { result in switch result { case .success(let data): guard let feedbackResponse = try? ConversationFeedbackResponse(data: data) else { completion(.failure(.api(.jsonConversion))) return } print(feedbackResponse) do { let feedback = try feedbackResponse.conversationFeedback() completion(.success(feedback)) } catch let error as FeedbackError { completion(.failure(error)) } catch { completion(.failure(.notFound)) } case .failure(let error): completion(.failure(.api(.network(error)))) } } } /// Submits conversation feedback for the given group id. /// - Parameters: /// - groupId: Group id for which feedback has to be submitted. /// - feedback: Feedback that should be submitted. /// - completion: A Result of type `ConversationFeedback`. func submitFeedback( groupId: Int, feedback: Feedback, completion: @escaping (Result<ConversationFeedback, FeedbackError>)->() ) { guard let url = URLBuilder.feedbackURLForSubmission().url else { completion(.failure(.api(.urlBuilding))) return } var params: [String: Any] = [ FeedbackParamKey.groupId: groupId, FeedbackParamKey.rating: feedback.rating.rawValue ] if let comment = feedback.comment, !comment.isEmpty { params[FeedbackParamKey.comment] = [comment] } DataLoader.postRequest(url: url, params: params) { result in switch result { case .success(let data): guard let feedbackResponse = try? ConversationFeedbackSubmissionResponse(data: data) else { completion(.failure(.api(.jsonConversion))) return } do { let feedback = try feedbackResponse.conversationFeedback() completion(.success(feedback)) } catch let error as FeedbackError { completion(.failure(error)) } catch { completion(.failure(.notFound)) } case .failure(let error): completion(.failure(.api(.network(error)))) } } } }
35.875
98
0.549652
e87b345b5699b5a2b9c8234f04e7f854a3cb34a2
1,055
// // AuthenticationModule.swift // Authentication // // Created by Bartłomiej Nowak on 30/09/2018. // Copyright © 2018 Bartłomiej Nowak. All rights reserved. // import Core import UIKit public protocol AuthenticationModuleDelegate: AnyObject { func authenticationSuccess() } public protocol AuthenticationModuleProtocol: AnyObject { func show() func success() } public class AuthenticationModule { public weak var delegate: AuthenticationModuleDelegate? private let navigator: NavigatorProtocol private let viewFactory: AuthenticationViewFactoryProtocol public required init(navigator: NavigatorProtocol, viewFactory: AuthenticationViewFactoryProtocol){ self.navigator = navigator self.viewFactory = viewFactory } } extension AuthenticationModule: AuthenticationModuleProtocol { public func show() { navigator.present(as: .root, controller: viewFactory.authentication(module: self)) } public func success() { delegate?.authenticationSuccess() } }
22.446809
103
0.734597
e23c1c5b3c0a0098028713392667191b9ecf935a
3,465
// // ViewController.swift // GridSample // // Created by Tomoyuki Tsujimoto on 2019/02/17. // Copyright © 2019年 Tomoyuki Tsujimoto. All rights reserved. // import UIKit class ViewController: UIViewController { let numViewPerRow = 20 var cells = [String: UIView]() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let width = view.frame.width / CGFloat(numViewPerRow) for j in 0...50 { for i in 0...numViewPerRow { let cellView = UIView() cellView.backgroundColor = randomColor() cellView.frame = CGRect(x: CGFloat(i) * width, y: CGFloat(j) * width, width: width, height: width) cellView.layer.borderWidth = 0.25 cellView.layer.borderColor = UIColor.black.cgColor view.addSubview(cellView) let key = "\(i)|\(j)" cells[key] = cellView } } view.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: #selector(handlePan))) // print(2.square()) } var selectedCell: UIView? @objc func handlePan(gesture: UIPanGestureRecognizer){ let location = gesture.location(in: view) // print(location) let width = view.frame.width / CGFloat(numViewPerRow) let i = Int(location.x / width) let j = Int(location.y / width) let key = "\(i)|\(j)" guard let cellView = cells[key] else {return } if selectedCell != cellView { UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: UIView.AnimationOptions.curveEaseOut, animations: { self.selectedCell?.layer.transform = CATransform3DIdentity }, completion: nil) } selectedCell = cellView view.bringSubviewToFront(cellView) UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: UIView.AnimationOptions.curveEaseOut, animations: { cellView.layer.transform = CATransform3DMakeScale(5,5,5) }, completion: nil) if gesture.state == .ended { cellView.backgroundColor = .white UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: UIView.AnimationOptions.curveEaseOut, animations: { self.selectedCell?.layer.transform = CATransform3DIdentity }, completion: nil) } // var loopCount = 0 // for subView in view.subviews { // if subView.frame.contains(location) { // subView.backgroundColor = .black // print("loopCount:", loopCount) // } // loopCount += 1 // } } fileprivate func randomColor() -> UIColor { let red = CGFloat(drand48()) let green = CGFloat(drand48()) let blue = CGFloat(drand48()) return UIColor(red: red, green: green, blue: blue, alpha: 1) } } extension Int { func square() -> Int { return self * self } }
30.9375
169
0.556133
26dc22184e8ee22b85ef132ed2672a20e706f111
1,358
// // Copyright (c) 2016 Keun young Kim <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation var words = [String: String]() words["A"] = "Apple" words["B"] = "Banana" print(words) // ["B": "Banana", "A": "Apple"] words["B"] = "Blue" print(words) // ["B": "Blue", "A": "Apple"]
39.941176
81
0.720913
729dc0a2ffa484e94e7015c47d02161db124365c
3,039
// CometChatKingfisher // CometChatUIKit // Created by CometChat Inc. on 16/10/19. // Copyright © 2020 CometChat Inc. All rights reserved. import Foundation /// Protocol indicates that an authentication challenge could be handled. protocol AuthenticationChallengeResponsable: AnyObject { /// Called when a session level authentication challenge is received. /// This method provide a chance to handle and response to the authentication /// challenge before downloading could start. /// /// - Parameters: /// - downloader: The downloader which receives this challenge. /// - challenge: An object that contains the request for authentication. /// - completionHandler: A handler that your delegate method must call. /// /// - Note: This method is a forward from `URLSessionDelegate.urlSession(:didReceiveChallenge:completionHandler:)`. /// Please refer to the document of it in `URLSessionDelegate`. func downloader( _ downloader: ImageDownloader, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) /// Called when a task level authentication challenge is received. /// This method provide a chance to handle and response to the authentication /// challenge before downloading could start. /// /// - Parameters: /// - downloader: The downloader which receives this challenge. /// - task: The task whose request requires authentication. /// - challenge: An object that contains the request for authentication. /// - completionHandler: A handler that your delegate method must call. func downloader( _ downloader: ImageDownloader, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) } extension AuthenticationChallengeResponsable { func downloader( _ downloader: ImageDownloader, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { if let trustedHosts = downloader.trustedHosts, trustedHosts.contains(challenge.protectionSpace.host) { let credential = URLCredential(trust: challenge.protectionSpace.serverTrust!) completionHandler(.useCredential, credential) return } } completionHandler(.performDefaultHandling, nil) } func downloader( _ downloader: ImageDownloader, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { completionHandler(.performDefaultHandling, nil) } }
39.986842
119
0.707141
0a0ef066abf7d5185db32a948c068575e8eae153
49,646
// // ZLClipImageViewController.swift // ZLImageEditor // // Created by long on 2020/8/27. // // Copyright (c) 2020 Long Zhang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit extension ZLClipImageViewController { enum ClipPanEdge { case none case top case bottom case left case right case topLeft case topRight case bottomLeft case bottomRight } } class ZLClipImageViewController: UIViewController { static let bottomToolViewH: CGFloat = 90 static let clipRatioItemSize: CGSize = CGSize(width: 60, height: 70) var animateDismiss = true /// Animation starting frame when first enter var presentAnimateFrame: CGRect? /// Animation image var presentAnimateImage: UIImage? /// Animation starting frame when cancel clip var cancelClipAnimateFrame: CGRect = .zero var viewDidAppearCount = 0 let originalImage: UIImage let clipRatios: [ZLImageClipRatio] var editImage: UIImage var editRect: CGRect var scrollView: UIScrollView! var containerView: UIView! var imageView: UIImageView! var shadowView: ZLClipShadowView! var overlayView: ZLClipOverlayView! var gridPanGes: UIPanGestureRecognizer! var bottomToolView: UIView! var bottomShadowLayer: CAGradientLayer! var bottomToolLineView: UIView! var cancelBtn: UIButton! var revertBtn: UIButton! var doneBtn: UIButton! var rotateBtn: UIButton! var clipRatioColView: UICollectionView! var shouldLayout = true var panEdge: ZLClipImageViewController.ClipPanEdge = .none var beginPanPoint: CGPoint = .zero var clipBoxFrame: CGRect = .zero var clipOriginFrame: CGRect = .zero var isRotating = false var angle: CGFloat = 0 var selectedRatio: ZLImageClipRatio var thumbnailImage: UIImage? lazy var maxClipFrame: CGRect = { var insets = deviceSafeAreaInsets() insets.top += 20 var rect = CGRect.zero rect.origin.x = 15 rect.origin.y = insets.top rect.size.width = UIScreen.main.bounds.width - 15 * 2 rect.size.height = UIScreen.main.bounds.height - insets.top - ZLClipImageViewController.bottomToolViewH - ZLClipImageViewController.clipRatioItemSize.height - 25 return rect }() var minClipSize = CGSize(width: 45, height: 45) var resetTimer: Timer? var dismissAnimateFromRect: CGRect = .zero var dismissAnimateImage: UIImage? = nil // Angle, edit rect, clip ratio var clipDoneBlock: ( (CGFloat, CGRect, ZLImageClipRatio) -> Void )? var cancelClipBlock: ( () -> Void )? override var prefersStatusBarHidden: Bool { return true } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { return .portrait } deinit { zl_debugPrint("ZLClipImageViewController deinit") self.cleanTimer() } init(image: UIImage, editRect: CGRect?, angle: CGFloat = 0, selectRatio: ZLImageClipRatio?) { self.originalImage = image self.clipRatios = ZLImageEditorConfiguration.default().editImageClipRatios self.editRect = editRect ?? .zero self.angle = angle if angle == -90 { self.editImage = image.rotate(orientation: .left) } else if self.angle == -180 { self.editImage = image.rotate(orientation: .down) } else if self.angle == -270 { self.editImage = image.rotate(orientation: .right) } else { self.editImage = image } var firstEnter = false if let sr = selectRatio { self.selectedRatio = sr } else { firstEnter = true self.selectedRatio = ZLImageEditorConfiguration.default().editImageClipRatios.first! } super.init(nibName: nil, bundle: nil) if firstEnter { self.calculateClipRect() } } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() self.setupUI() self.generateThumbnailImage() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.viewDidAppearCount += 1 if self.presentingViewController is ZLEditImageViewController { self.transitioningDelegate = self } guard self.viewDidAppearCount == 1 else { return } if let frame = self.presentAnimateFrame, let image = self.presentAnimateImage { let animateImageView = UIImageView(image: image) animateImageView.contentMode = .scaleAspectFill animateImageView.clipsToBounds = true animateImageView.frame = frame self.view.addSubview(animateImageView) self.cancelClipAnimateFrame = self.clipBoxFrame UIView.animate(withDuration: 0.25, animations: { animateImageView.frame = self.clipBoxFrame self.bottomToolView.alpha = 1 self.rotateBtn.alpha = 1 }) { (_) in UIView.animate(withDuration: 0.1, animations: { self.scrollView.alpha = 1 self.overlayView.alpha = 1 }) { (_) in animateImageView.removeFromSuperview() } } } else { self.bottomToolView.alpha = 1 self.rotateBtn.alpha = 1 self.scrollView.alpha = 1 self.overlayView.alpha = 1 } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() guard self.shouldLayout else { return } self.shouldLayout = false self.scrollView.frame = self.view.bounds self.shadowView.frame = self.view.bounds self.layoutInitialImage() self.bottomToolView.frame = CGRect(x: 0, y: self.view.bounds.height-ZLClipImageViewController.bottomToolViewH, width: self.view.bounds.width, height: ZLClipImageViewController.bottomToolViewH) self.bottomShadowLayer.frame = self.bottomToolView.bounds self.bottomToolLineView.frame = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: 1/UIScreen.main.scale) let toolBtnH: CGFloat = 25 let toolBtnY = (ZLClipImageViewController.bottomToolViewH - toolBtnH) / 2 - 10 self.cancelBtn.frame = CGRect(x: 30, y: toolBtnY, width: toolBtnH, height: toolBtnH) let revertBtnW = localLanguageTextValue(.revert).boundingRect(font: ZLImageEditorLayout.bottomToolTitleFont, limitSize: CGSize(width: CGFloat.greatestFiniteMagnitude, height: toolBtnH)).width + 20 self.revertBtn.frame = CGRect(x: (self.view.bounds.width-revertBtnW)/2, y: toolBtnY, width: revertBtnW, height: toolBtnH) self.doneBtn.frame = CGRect(x: self.view.bounds.width-30-toolBtnH, y: toolBtnY, width: toolBtnH, height: toolBtnH) let ratioColViewY = self.bottomToolView.frame.minY - ZLClipImageViewController.clipRatioItemSize.height - 5 self.rotateBtn.frame = CGRect(x: 30, y: ratioColViewY + (ZLClipImageViewController.clipRatioItemSize.height-25)/2, width: 25, height: 25) let ratioColViewX = self.rotateBtn.frame.maxX + 15 self.clipRatioColView.frame = CGRect(x: ratioColViewX, y: ratioColViewY, width: self.view.bounds.width - ratioColViewX, height: 70) if self.clipRatios.count > 1, let index = self.clipRatios.firstIndex(where: { $0 == self.selectedRatio}) { self.clipRatioColView.scrollToItem(at: IndexPath(row: index, section: 0), at: .centeredHorizontally, animated: false) } } func setupUI() { self.view.backgroundColor = .black self.scrollView = UIScrollView() self.scrollView.alwaysBounceVertical = true self.scrollView.alwaysBounceHorizontal = true self.scrollView.showsVerticalScrollIndicator = false self.scrollView.showsHorizontalScrollIndicator = false if #available(iOS 11.0, *) { self.scrollView.contentInsetAdjustmentBehavior = .never } else { // Fallback on earlier versions } self.scrollView.delegate = self self.view.addSubview(self.scrollView) self.containerView = UIView() self.scrollView.addSubview(self.containerView) self.imageView = UIImageView(image: self.editImage) self.imageView.contentMode = .scaleAspectFit self.imageView.clipsToBounds = true self.containerView.addSubview(self.imageView) self.shadowView = ZLClipShadowView() self.shadowView.isUserInteractionEnabled = false self.shadowView.backgroundColor = UIColor.black.withAlphaComponent(0.3) self.view.addSubview(self.shadowView) self.overlayView = ZLClipOverlayView() self.overlayView.isUserInteractionEnabled = false self.view.addSubview(self.overlayView) self.bottomToolView = UIView() self.view.addSubview(self.bottomToolView) let color1 = UIColor.black.withAlphaComponent(0.15).cgColor let color2 = UIColor.black.withAlphaComponent(0.35).cgColor self.bottomShadowLayer = CAGradientLayer() self.bottomShadowLayer.colors = [color1, color2] self.bottomShadowLayer.locations = [0, 1] self.bottomToolView.layer.addSublayer(self.bottomShadowLayer) self.bottomToolLineView = UIView() self.bottomToolLineView.backgroundColor = zlRGB(240, 240, 240) self.bottomToolView.addSubview(self.bottomToolLineView) self.cancelBtn = UIButton(type: .custom) self.cancelBtn.setImage(getImage("zl_close"), for: .normal) self.cancelBtn.adjustsImageWhenHighlighted = false self.cancelBtn.zl_enlargeValidTouchArea(inset: 20) self.cancelBtn.addTarget(self, action: #selector(cancelBtnClick), for: .touchUpInside) self.bottomToolView.addSubview(self.cancelBtn) self.revertBtn = UIButton(type: .custom) // self.revertBtn.setTitleColor(.white, for: .normal) // self.revertBtn.setTitle(localLanguageTextValue(.revert), for: .normal) self.revertBtn.zl_enlargeValidTouchArea(inset: 20) self.revertBtn.titleLabel?.font = ZLImageEditorLayout.bottomToolTitleFont self.revertBtn.addTarget(self, action: #selector(revertBtnClick), for: .touchUpInside) self.bottomToolView.addSubview(self.revertBtn) self.doneBtn = UIButton(type: .custom) self.doneBtn.setImage(getImage("zl_right"), for: .normal) self.doneBtn.adjustsImageWhenHighlighted = false self.doneBtn.zl_enlargeValidTouchArea(inset: 20) self.doneBtn.addTarget(self, action: #selector(doneBtnClick), for: .touchUpInside) self.bottomToolView.addSubview(self.doneBtn) self.rotateBtn = UIButton(type: .custom) self.rotateBtn.setImage(getImage("zl_rotateimage"), for: .normal) self.rotateBtn.adjustsImageWhenHighlighted = false self.rotateBtn.zl_enlargeValidTouchArea(inset: 20) self.rotateBtn.addTarget(self, action: #selector(rotateBtnClick), for: .touchUpInside) self.view.addSubview(self.rotateBtn) let layout = UICollectionViewFlowLayout() layout.itemSize = ZLClipImageViewController.clipRatioItemSize layout.scrollDirection = .horizontal layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 20) self.clipRatioColView = UICollectionView(frame: .zero, collectionViewLayout: layout) self.clipRatioColView.delegate = self self.clipRatioColView.dataSource = self self.clipRatioColView.backgroundColor = .clear self.clipRatioColView.isHidden = self.clipRatios.count <= 1 self.clipRatioColView.showsHorizontalScrollIndicator = false self.view.addSubview(self.clipRatioColView) ZLImageClipRatioCell.zl_register(self.clipRatioColView) self.gridPanGes = UIPanGestureRecognizer(target: self, action: #selector(gridGesPanAction(_:))) self.gridPanGes.delegate = self self.view.addGestureRecognizer(self.gridPanGes) self.scrollView.panGestureRecognizer.require(toFail: self.gridPanGes) self.scrollView.alpha = 0 self.overlayView.alpha = 0 self.bottomToolView.alpha = 0 self.rotateBtn.alpha = 0 } func generateThumbnailImage() { let size: CGSize let ratio = (self.editImage.size.width / self.editImage.size.height) let fixLength: CGFloat = 100 if ratio >= 1 { size = CGSize(width: fixLength * ratio, height: fixLength) } else { size = CGSize(width: fixLength, height: fixLength / ratio) } self.thumbnailImage = self.editImage.resize(size) } func calculateClipRect() { if self.selectedRatio.whRatio == 0 { self.editRect = CGRect(origin: .zero, size: self.editImage.size) } else { let imageSize = self.editImage.size let imageWHRatio = imageSize.width / imageSize.height var w: CGFloat = 0, h: CGFloat = 0 if self.selectedRatio.whRatio >= imageWHRatio { w = imageSize.width h = w / self.selectedRatio.whRatio } else { h = imageSize.height w = h * self.selectedRatio.whRatio } self.editRect = CGRect(x: (imageSize.width - w) / 2, y: (imageSize.height - h) / 2, width: w, height: h) } } func layoutInitialImage() { self.scrollView.minimumZoomScale = 1 self.scrollView.maximumZoomScale = 1 self.scrollView.zoomScale = 1 let editSize = self.editRect.size self.scrollView.contentSize = editSize let maxClipRect = self.maxClipFrame self.containerView.frame = CGRect(origin: .zero, size: self.editImage.size) self.imageView.frame = self.containerView.bounds // editRect比例,计算editRect所占frame let editScale = min(maxClipRect.width/editSize.width, maxClipRect.height/editSize.height) let scaledSize = CGSize(width: floor(editSize.width * editScale), height: floor(editSize.height * editScale)) var frame = CGRect.zero frame.size = scaledSize frame.origin.x = maxClipRect.minX + floor((maxClipRect.width-frame.width) / 2) frame.origin.y = maxClipRect.minY + floor((maxClipRect.height-frame.height) / 2) // 按照edit image进行计算最小缩放比例 let originalScale = min(maxClipRect.width/self.editImage.size.width, maxClipRect.height/self.editImage.size.height) // 将 edit rect 相对 originalScale 进行缩放,缩放到图片未放大时候的clip rect let scaleEditSize = CGSize(width: self.editRect.width * originalScale, height: self.editRect.height * originalScale) // 计算缩放后的clip rect相对maxClipRect的比例 let clipRectZoomScale = min(maxClipRect.width/scaleEditSize.width, maxClipRect.height/scaleEditSize.height) self.scrollView.minimumZoomScale = originalScale self.scrollView.maximumZoomScale = 10 // 设置当前zoom scale let zoomScale = (clipRectZoomScale * originalScale) self.scrollView.zoomScale = zoomScale self.scrollView.contentSize = CGSize(width: self.editImage.size.width * zoomScale, height: self.editImage.size.height * zoomScale) self.changeClipBoxFrame(newFrame: frame) if (frame.size.width < scaledSize.width - CGFloat.ulpOfOne) || (frame.size.height < scaledSize.height - CGFloat.ulpOfOne) { var offset = CGPoint.zero offset.x = -floor((self.scrollView.frame.width - scaledSize.width) / 2) offset.y = -floor((self.scrollView.frame.height - scaledSize.height) / 2) self.scrollView.contentOffset = offset } // edit rect 相对 image size 的 偏移量 let diffX = self.editRect.origin.x / self.editImage.size.width * self.scrollView.contentSize.width let diffY = self.editRect.origin.y / self.editImage.size.height * self.scrollView.contentSize.height self.scrollView.contentOffset = CGPoint(x: -self.scrollView.contentInset.left+diffX, y: -self.scrollView.contentInset.top+diffY) } func changeClipBoxFrame(newFrame: CGRect) { guard self.clipBoxFrame != newFrame else { return } if newFrame.width < CGFloat.ulpOfOne || newFrame.height < CGFloat.ulpOfOne { return } var frame = newFrame let originX = ceil(self.maxClipFrame.minX) let diffX = frame.minX - originX frame.origin.x = max(frame.minX, originX) // frame.origin.x = floor(max(frame.minX, originX)) if diffX < -CGFloat.ulpOfOne { frame.size.width += diffX } let originY = ceil(self.maxClipFrame.minY) let diffY = frame.minY - originY frame.origin.y = max(frame.minY, originY) // frame.origin.y = floor(max(frame.minY, originY)) if diffY < -CGFloat.ulpOfOne { frame.size.height += diffY } let maxW = self.maxClipFrame.width + self.maxClipFrame.minX - frame.minX frame.size.width = max(self.minClipSize.width, min(frame.width, maxW)) // frame.size.width = floor(max(self.minClipSize.width, min(frame.width, maxW))) let maxH = self.maxClipFrame.height + self.maxClipFrame.minY - frame.minY frame.size.height = max(self.minClipSize.height, min(frame.height, maxH)) // frame.size.height = floor(max(self.minClipSize.height, min(frame.height, maxH))) self.clipBoxFrame = frame self.shadowView.clearRect = frame self.overlayView.frame = frame.insetBy(dx: -ZLClipOverlayView.cornerLineWidth, dy: -ZLClipOverlayView.cornerLineWidth) self.scrollView.contentInset = UIEdgeInsets(top: frame.minY, left: frame.minX, bottom: self.scrollView.frame.maxY-frame.maxY, right: self.scrollView.frame.maxX-frame.maxX) let scale = max(frame.height/self.editImage.size.height, frame.width/self.editImage.size.width) self.scrollView.minimumZoomScale = scale // var size = self.scrollView.contentSize // size.width = floor(size.width) // size.height = floor(size.height) // self.scrollView.contentSize = size self.scrollView.zoomScale = self.scrollView.zoomScale } @objc func cancelBtnClick() { self.dismissAnimateFromRect = self.cancelClipAnimateFrame self.dismissAnimateImage = self.presentAnimateImage self.cancelClipBlock?() self.dismiss(animated: self.animateDismiss, completion: nil) } @objc func revertBtnClick() { self.angle = 0 self.editImage = self.originalImage self.calculateClipRect() self.imageView.image = self.editImage self.layoutInitialImage() self.generateThumbnailImage() self.clipRatioColView.reloadData() } @objc func doneBtnClick() { let image = self.clipImage() self.dismissAnimateFromRect = self.clipBoxFrame self.dismissAnimateImage = image.clipImage self.clipDoneBlock?(self.angle, image.editRect, self.selectedRatio) self.dismiss(animated: self.animateDismiss, completion: nil) } @objc func rotateBtnClick() { guard !self.isRotating else { return } self.angle -= 90 if self.angle == -360 { self.angle = 0 } self.isRotating = true let animateImageView = UIImageView(image: self.editImage) animateImageView.contentMode = .scaleAspectFit animateImageView.clipsToBounds = true let originFrame = self.view.convert(self.containerView.frame, from: self.scrollView) animateImageView.frame = originFrame self.view.addSubview(animateImageView) if self.selectedRatio.whRatio == 0 || self.selectedRatio.whRatio == 1 { // 自由比例和1:1比例,进行edit rect转换 // 将edit rect转换为相对edit image的rect let rect = self.convertClipRectToEditImageRect() // 旋转图片 self.editImage = self.editImage.rotate(orientation: .left) // 将rect进行旋转,转换到相对于旋转后的edit image的rect self.editRect = CGRect(x: rect.minY, y: self.editImage.size.height-rect.minX-rect.width, width: rect.height, height: rect.width) } else { // 其他比例的裁剪框,旋转后都重置edit rect // 旋转图片 self.editImage = self.editImage.rotate(orientation: .left) self.calculateClipRect() } self.imageView.image = self.editImage self.layoutInitialImage() let toFrame = self.view.convert(self.containerView.frame, from: self.scrollView) let transform = CGAffineTransform(rotationAngle: -CGFloat.pi/2) self.overlayView.alpha = 0 self.containerView.alpha = 0 UIView.animate(withDuration: 0.3, animations: { animateImageView.transform = transform animateImageView.frame = toFrame }) { (_) in animateImageView.removeFromSuperview() self.overlayView.alpha = 1 self.containerView.alpha = 1 self.isRotating = false } self.generateThumbnailImage() self.clipRatioColView.reloadData() } @objc func gridGesPanAction(_ pan: UIPanGestureRecognizer) { let point = pan.location(in: self.view) if pan.state == .began { self.startEditing() self.beginPanPoint = point self.clipOriginFrame = self.clipBoxFrame self.panEdge = self.calculatePanEdge(at: point) } else if pan.state == .changed { guard self.panEdge != .none else { return } self.updateClipBoxFrame(point: point) } else if pan.state == .cancelled || pan.state == .ended { self.panEdge = .none self.startTimer() } } func calculatePanEdge(at point: CGPoint) -> ZLClipImageViewController.ClipPanEdge { let frame = self.clipBoxFrame.insetBy(dx: -30, dy: -30) let cornerSize = CGSize(width: 60, height: 60) let topLeftRect = CGRect(origin: frame.origin, size: cornerSize) if topLeftRect.contains(point) { return .topLeft } let topRightRect = CGRect(origin: CGPoint(x: frame.maxX-cornerSize.width, y: frame.minY), size: cornerSize) if topRightRect.contains(point) { return .topRight } let bottomLeftRect = CGRect(origin: CGPoint(x: frame.minX, y: frame.maxY-cornerSize.height), size: cornerSize) if bottomLeftRect.contains(point) { return .bottomLeft } let bottomRightRect = CGRect(origin: CGPoint(x: frame.maxX-cornerSize.width, y: frame.maxY-cornerSize.height), size: cornerSize) if bottomRightRect.contains(point) { return .bottomRight } let topRect = CGRect(origin: frame.origin, size: CGSize(width: frame.width, height: cornerSize.height)) if topRect.contains(point) { return .top } let bottomRect = CGRect(origin: CGPoint(x: frame.minX, y: frame.maxY-cornerSize.height), size: CGSize(width: frame.width, height: cornerSize.height)) if bottomRect.contains(point) { return .bottom } let leftRect = CGRect(origin: frame.origin, size: CGSize(width: cornerSize.width, height: frame.height)) if leftRect.contains(point) { return .left } let rightRect = CGRect(origin: CGPoint(x: frame.maxX-cornerSize.width, y: frame.minY), size: CGSize(width: cornerSize.width, height: frame.height)) if rightRect.contains(point) { return .right } return .none } func updateClipBoxFrame(point: CGPoint) { var frame = self.clipBoxFrame let originFrame = self.clipOriginFrame var newPoint = point newPoint.x = max(self.maxClipFrame.minX, newPoint.x) newPoint.y = max(self.maxClipFrame.minY, newPoint.y) let diffX = ceil(newPoint.x - self.beginPanPoint.x) let diffY = ceil(newPoint.y - self.beginPanPoint.y) let ratio = self.selectedRatio.whRatio switch self.panEdge { case .left: frame.origin.x = originFrame.minX + diffX frame.size.width = originFrame.width - diffX if ratio != 0 { frame.size.height = originFrame.height - diffX / ratio } case .right: frame.size.width = originFrame.width + diffX if ratio != 0 { frame.size.height = originFrame.height + diffX / ratio } case .top: frame.origin.y = originFrame.minY + diffY frame.size.height = originFrame.height - diffY if ratio != 0 { frame.size.width = originFrame.width - diffY * ratio } case .bottom: frame.size.height = originFrame.height + diffY if ratio != 0 { frame.size.width = originFrame.width + diffY * ratio } case .topLeft: if ratio != 0 { // if abs(diffX / ratio) >= abs(diffY) { frame.origin.x = originFrame.minX + diffX frame.size.width = originFrame.width - diffX frame.origin.y = originFrame.minY + diffX / ratio frame.size.height = originFrame.height - diffX / ratio // } else { // frame.origin.y = originFrame.minY + diffY // frame.size.height = originFrame.height - diffY // frame.origin.x = originFrame.minX + diffY * ratio // frame.size.width = originFrame.width - diffY * ratio // } } else { frame.origin.x = originFrame.minX + diffX frame.size.width = originFrame.width - diffX frame.origin.y = originFrame.minY + diffY frame.size.height = originFrame.height - diffY } case .topRight: if ratio != 0 { // if abs(diffX / ratio) >= abs(diffY) { frame.size.width = originFrame.width + diffX frame.origin.y = originFrame.minY - diffX / ratio frame.size.height = originFrame.height + diffX / ratio // } else { // frame.origin.y = originFrame.minY + diffY // frame.size.height = originFrame.height - diffY // frame.size.width = originFrame.width - diffY * ratio // } } else { frame.size.width = originFrame.width + diffX frame.origin.y = originFrame.minY + diffY frame.size.height = originFrame.height - diffY } case .bottomLeft: if ratio != 0 { // if abs(diffX / ratio) >= abs(diffY) { frame.origin.x = originFrame.minX + diffX frame.size.width = originFrame.width - diffX frame.size.height = originFrame.height - diffX / ratio // } else { // frame.origin.x = originFrame.minX - diffY * ratio // frame.size.width = originFrame.width + diffY * ratio // frame.size.height = originFrame.height + diffY // } } else { frame.origin.x = originFrame.minX + diffX frame.size.width = originFrame.width - diffX frame.size.height = originFrame.height + diffY } case .bottomRight: if ratio != 0 { // if abs(diffX / ratio) >= abs(diffY) { frame.size.width = originFrame.width + diffX frame.size.height = originFrame.height + diffX / ratio // } else { // frame.size.width += diffY * ratio // frame.size.height += diffY // } } else { frame.size.width = originFrame.width + diffX frame.size.height = originFrame.height + diffY } default: break } let minSize: CGSize let maxSize: CGSize let maxClipFrame: CGRect if ratio != 0 { if ratio >= 1 { minSize = CGSize(width: self.minClipSize.height * ratio, height: self.minClipSize.height) } else { minSize = CGSize(width: self.minClipSize.width, height: self.minClipSize.width / ratio) } if ratio > self.maxClipFrame.width / self.maxClipFrame.height { maxSize = CGSize(width: self.maxClipFrame.width, height: self.maxClipFrame.width / ratio) } else { maxSize = CGSize(width: self.maxClipFrame.height * ratio, height: self.maxClipFrame.height) } maxClipFrame = CGRect(origin: CGPoint(x: self.maxClipFrame.minX + (self.maxClipFrame.width-maxSize.width)/2, y: self.maxClipFrame.minY + (self.maxClipFrame.height-maxSize.height)/2), size: maxSize) } else { minSize = self.minClipSize maxSize = self.maxClipFrame.size maxClipFrame = self.maxClipFrame } frame.size.width = min(maxSize.width, max(minSize.width, frame.size.width)) frame.size.height = min(maxSize.height, max(minSize.height, frame.size.height)) frame.origin.x = min(maxClipFrame.maxX-minSize.width, max(frame.origin.x, maxClipFrame.minX)) frame.origin.y = min(maxClipFrame.maxY-minSize.height, max(frame.origin.y, maxClipFrame.minY)) if (self.panEdge == .topLeft || self.panEdge == .bottomLeft || self.panEdge == .left) && frame.size.width <= minSize.width + CGFloat.ulpOfOne { frame.origin.x = originFrame.maxX - minSize.width } if (self.panEdge == .topLeft || self.panEdge == .topRight || self.panEdge == .top) && frame.size.height <= minSize.height + CGFloat.ulpOfOne { frame.origin.y = originFrame.maxY - minSize.height } self.changeClipBoxFrame(newFrame: frame) } func startEditing() { self.cleanTimer() self.shadowView.alpha = 0 if self.rotateBtn.alpha != 0 { self.rotateBtn.layer.removeAllAnimations() self.clipRatioColView.layer.removeAllAnimations() UIView.animate(withDuration: 0.2) { self.rotateBtn.alpha = 0 self.clipRatioColView.alpha = 0 } } } @objc func endEditing() { self.moveClipContentToCenter() } func startTimer() { self.cleanTimer() self.resetTimer = Timer.scheduledTimer(timeInterval: 0.8, target: self, selector: #selector(endEditing), userInfo: nil, repeats: false) } func cleanTimer() { self.resetTimer?.invalidate() self.resetTimer = nil } func moveClipContentToCenter() { let maxClipRect = self.maxClipFrame var clipRect = self.clipBoxFrame if clipRect.width < CGFloat.ulpOfOne || clipRect.height < CGFloat.ulpOfOne { return } let scale = min(maxClipRect.width/clipRect.width, maxClipRect.height/clipRect.height) let focusPoint = CGPoint(x: clipRect.midX, y: clipRect.midY) let midPoint = CGPoint(x: maxClipRect.midX, y: maxClipRect.midY) clipRect.size.width = ceil(clipRect.width * scale) clipRect.size.height = ceil(clipRect.height * scale) clipRect.origin.x = maxClipRect.minX + ceil((maxClipRect.width-clipRect.width)/2) clipRect.origin.y = maxClipRect.minY + ceil((maxClipRect.height-clipRect.height)/2) var contentTargetPoint = CGPoint.zero contentTargetPoint.x = (focusPoint.x + self.scrollView.contentOffset.x) * scale contentTargetPoint.y = (focusPoint.y + self.scrollView.contentOffset.y) * scale var offset = CGPoint(x: contentTargetPoint.x - midPoint.x, y: contentTargetPoint.y - midPoint.y) offset.x = max(-clipRect.minX, offset.x) offset.y = max(-clipRect.minY, offset.y) UIView.animate(withDuration: 0.3) { if scale < 1 - CGFloat.ulpOfOne || scale > 1 + CGFloat.ulpOfOne { self.scrollView.zoomScale *= scale self.scrollView.zoomScale = min(self.scrollView.maximumZoomScale, self.scrollView.zoomScale) } if self.scrollView.zoomScale < self.scrollView.maximumZoomScale - CGFloat.ulpOfOne { offset.x = min(self.scrollView.contentSize.width-clipRect.maxX, offset.x) offset.y = min(self.scrollView.contentSize.height-clipRect.maxY, offset.y) self.scrollView.contentOffset = offset } self.rotateBtn.alpha = 1 self.clipRatioColView.alpha = 1 self.shadowView.alpha = 1 self.changeClipBoxFrame(newFrame: clipRect) } } func clipImage() -> (clipImage: UIImage, editRect: CGRect) { let frame = self.convertClipRectToEditImageRect() let origin = CGPoint(x: -frame.minX, y: -frame.minY) UIGraphicsBeginImageContextWithOptions(frame.size, false, self.editImage.scale) self.editImage.draw(at: origin) let temp = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() guard let cgi = temp?.cgImage else { return (self.editImage, CGRect(origin: .zero, size: self.editImage.size)) } let newImage = UIImage(cgImage: cgi, scale: self.editImage.scale, orientation: .up) return (newImage, frame) } func convertClipRectToEditImageRect() -> CGRect { let imageSize = self.editImage.size let contentSize = self.scrollView.contentSize let offset = self.scrollView.contentOffset let insets = self.scrollView.contentInset var frame = CGRect.zero frame.origin.x = floor((offset.x + insets.left) * (imageSize.width / contentSize.width)) frame.origin.x = max(0, frame.origin.x) frame.origin.y = floor((offset.y + insets.top) * (imageSize.height / contentSize.height)) frame.origin.y = max(0, frame.origin.y) frame.size.width = ceil(self.clipBoxFrame.width * (imageSize.width / contentSize.width)) frame.size.width = min(imageSize.width, frame.width) frame.size.height = ceil(self.clipBoxFrame.height * (imageSize.height / contentSize.height)) frame.size.height = min(imageSize.height, frame.height) return frame } } extension ZLClipImageViewController: UIGestureRecognizerDelegate { func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { guard gestureRecognizer == self.gridPanGes else { return true } let point = gestureRecognizer.location(in: self.view) let frame = self.overlayView.frame let innerFrame = frame.insetBy(dx: 22, dy: 22) let outerFrame = frame.insetBy(dx: -22, dy: -22) if innerFrame.contains(point) || !outerFrame.contains(point) { return false } return true } } extension ZLClipImageViewController: UICollectionViewDataSource, UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.clipRatios.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ZLImageClipRatioCell.zl_identifier(), for: indexPath) as! ZLImageClipRatioCell let ratio = self.clipRatios[indexPath.row] cell.configureCell(image: self.thumbnailImage ?? self.editImage, ratio: ratio) if ratio == self.selectedRatio { cell.titleLabel.textColor = .white } else { cell.titleLabel.textColor = zlRGB(160, 160, 160) } return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let ratio = self.clipRatios[indexPath.row] guard ratio != self.selectedRatio else { return } self.selectedRatio = ratio self.clipRatioColView.reloadData() self.clipRatioColView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true) self.calculateClipRect() self.layoutInitialImage() } } extension ZLClipImageViewController: UIScrollViewDelegate { func viewForZooming(in scrollView: UIScrollView) -> UIView? { return self.containerView } func scrollViewWillBeginZooming(_ scrollView: UIScrollView, with view: UIView?) { self.startEditing() } func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { guard scrollView == self.scrollView else { return } self.startEditing() } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { guard scrollView == self.scrollView else { return } self.startTimer() } func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { guard scrollView == self.scrollView else { return } if !decelerate { self.startTimer() } } } extension ZLClipImageViewController: UIViewControllerTransitioningDelegate { func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { return ZLClipImageDismissAnimatedTransition() } } // MARK: 裁剪比例cell class ZLImageClipRatioCell: UICollectionViewCell { var imageView: UIImageView! var titleLabel: UILabel! var image: UIImage? var ratio: ZLImageClipRatio! override init(frame: CGRect) { super.init(frame: frame) self.setupUI() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() guard let ratio = self.ratio, let image = self.image else { return } let center = self.imageView.center var w: CGFloat = 0, h: CGFloat = 0 let imageMaxW = self.bounds.width-10 if ratio.whRatio == 0 { let maxSide = max(image.size.width, image.size.height) w = imageMaxW * image.size.width / maxSide h = imageMaxW * image.size.height / maxSide } else { if ratio.whRatio >= 1 { w = imageMaxW h = w / ratio.whRatio } else { h = imageMaxW w = h * ratio.whRatio } } self.imageView.frame = CGRect(x: center.x-w/2, y: center.y-h/2, width: w, height: h) } func setupUI() { self.imageView = UIImageView(frame: CGRect(x: 8, y: 5, width: self.bounds.width-16, height: self.bounds.width-16)) self.imageView.contentMode = .scaleAspectFill self.imageView.layer.cornerRadius = 3 self.imageView.layer.masksToBounds = true self.imageView.clipsToBounds = true self.contentView.addSubview(self.imageView) self.titleLabel = UILabel(frame: CGRect(x: 0, y: self.bounds.height-15, width: self.bounds.width, height: 12)) self.titleLabel.font = UIFont.systemFont(ofSize: 12) self.titleLabel.textColor = .white self.titleLabel.textAlignment = .center self.titleLabel.layer.shadowColor = UIColor.black.withAlphaComponent(0.3).cgColor self.titleLabel.layer.shadowOffset = .zero self.titleLabel.layer.shadowOpacity = 1 self.contentView.addSubview(self.titleLabel) } func configureCell(image: UIImage, ratio: ZLImageClipRatio) { self.imageView.image = image self.titleLabel.text = ratio.title self.image = image self.ratio = ratio self.setNeedsLayout() } } class ZLClipShadowView: UIView { var clearRect: CGRect = .zero { didSet { self.setNeedsDisplay() } } override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = .clear self.isOpaque = false } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func draw(_ rect: CGRect) { UIColor(white: 0, alpha: 0.7).setFill() UIRectFill(rect) let cr = self.clearRect.intersection(rect) UIColor.clear.setFill() UIRectFill(cr) } } // MARK: 裁剪网格视图 class ZLClipOverlayView: UIView { static let cornerLineWidth: CGFloat = 3 var cornerBoldLines: [UIView] = [] var velLines: [UIView] = [] var horLines: [UIView] = [] override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = .clear self.clipsToBounds = false // 两种方法实现裁剪框,drawrect动画效果 更好一点 // func line(_ isCorner: Bool) -> UIView { // let line = UIView() // line.backgroundColor = .white // line.layer.shadowColor = UIColor.black.cgColor // if !isCorner { // line.layer.shadowOffset = .zero // line.layer.shadowRadius = 1.5 // line.layer.shadowOpacity = 0.8 // } // self.addSubview(line) // return line // } // // (0..<8).forEach { (_) in // self.cornerBoldLines.append(line(true)) // } // // (0..<4).forEach { (_) in // self.velLines.append(line(false)) // self.horLines.append(line(false)) // } } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() self.setNeedsDisplay() // let borderLineLength: CGFloat = 20 // let borderLineWidth: CGFloat = ZLClipOverlayView.cornerLineWidth // for (i, line) in self.cornerBoldLines.enumerated() { // switch i { // case 0: // // 左上 hor // line.frame = CGRect(x: -borderLineWidth, y: -borderLineWidth, width: borderLineLength, height: borderLineWidth) // case 1: // // 左上 vel // line.frame = CGRect(x: -borderLineWidth, y: -borderLineWidth, width: borderLineWidth, height: borderLineLength) // case 2: // // 右上 hor // line.frame = CGRect(x: self.bounds.width-borderLineLength+borderLineWidth, y: -borderLineWidth, width: borderLineLength, height: borderLineWidth) // case 3: // // 右上 vel // line.frame = CGRect(x: self.bounds.width, y: -borderLineWidth, width: borderLineWidth, height: borderLineLength) // case 4: // // 左下 hor // line.frame = CGRect(x: -borderLineWidth, y: self.bounds.height, width: borderLineLength, height: borderLineWidth) // case 5: // // 左下 vel // line.frame = CGRect(x: -borderLineWidth, y: self.bounds.height-borderLineLength+borderLineWidth, width: borderLineWidth, height: borderLineLength) // case 6: // // 右下 hor // line.frame = CGRect(x: self.bounds.width-borderLineLength+borderLineWidth, y: self.bounds.height, width: borderLineLength, height: borderLineWidth) // case 7: // line.frame = CGRect(x: self.bounds.width, y: self.bounds.height-borderLineLength+borderLineWidth, width: borderLineWidth, height: borderLineLength) // // default: // break // } // } // // let normalLineWidth: CGFloat = 1 // var x: CGFloat = 0 // var y: CGFloat = -1 // // 横线 // for (index, line) in self.horLines.enumerated() { // if index == 0 || index == 3 { // x = borderLineLength-borderLineWidth // } else { // x = 0 // } // line.frame = CGRect(x: x, y: y, width: self.bounds.width - x * 2, height: normalLineWidth) // y += (self.bounds.height + 1) / 3 // } // // x = -1 // y = 0 // // 竖线 // for (index, line) in self.velLines.enumerated() { // if index == 0 || index == 3 { // y = borderLineLength-borderLineWidth // } else { // y = 0 // } // line.frame = CGRect(x: x, y: y, width: normalLineWidth, height: self.bounds.height - y * 2) // x += (self.bounds.width + 1) / 3 // } } override func draw(_ rect: CGRect) { let context = UIGraphicsGetCurrentContext() context?.setFillColor(UIColor.clear.cgColor) context?.setStrokeColor(UIColor.white.cgColor) context?.setLineWidth(1) context?.beginPath() var dw: CGFloat = 3 for _ in 0..<4 { context?.move(to: CGPoint(x: rect.origin.x+dw, y: rect.origin.y+3)) context?.addLine(to: CGPoint(x: rect.origin.x+dw, y: rect.origin.y+rect.height-3)) dw += (rect.size.width - 6) / 3 } var dh: CGFloat = 3 for _ in 0..<4 { context?.move(to: CGPoint(x: rect.origin.x+3, y: rect.origin.y+dh)) context?.addLine(to: CGPoint(x: rect.origin.x+rect.width-3, y: rect.origin.y+dh)) dh += (rect.size.height - 6) / 3 } context?.strokePath() context?.setLineWidth(3) let boldLineLength: CGFloat = 20 // 左上 context?.move(to: CGPoint(x: 0, y: 1.5)) context?.addLine(to: CGPoint(x: boldLineLength, y: 1.5)) context?.move(to: CGPoint(x: 1.5, y: 0)) context?.addLine(to: CGPoint(x: 1.5, y: boldLineLength)) // 右上 context?.move(to: CGPoint(x: rect.width-boldLineLength, y: 1.5)) context?.addLine(to: CGPoint(x: rect.width, y: 1.5)) context?.move(to: CGPoint(x: rect.width-1.5, y: 0)) context?.addLine(to: CGPoint(x: rect.width-1.5, y: boldLineLength)) // 左下 context?.move(to: CGPoint(x: 1.5, y: rect.height-boldLineLength)) context?.addLine(to: CGPoint(x: 1.5, y: rect.height)) context?.move(to: CGPoint(x: 0, y: rect.height-1.5)) context?.addLine(to: CGPoint(x: boldLineLength, y: rect.height-1.5)) // 右下 context?.move(to: CGPoint(x: rect.width-boldLineLength, y: rect.height-1.5)) context?.addLine(to: CGPoint(x: rect.width, y: rect.height-1.5)) context?.move(to: CGPoint(x: rect.width-1.5, y: rect.height-boldLineLength)) context?.addLine(to: CGPoint(x: rect.width-1.5, y: rect.height)) context?.strokePath() context?.setShadow(offset: CGSize(width: 1, height: 1), blur: 0) } }
38.785938
209
0.60732
f7e00254e43754a194337df1c7666bece971bd46
5,215
// // NSDateTimeAgoTests.swift // NSDateTimeAgoTests // // Created by David Keegan on 10/15/15. // Copyright © 2015 Kevin Lawler. All rights reserved. // import XCTest import NSDateTimeAgo class NSDateTimeAgoTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func dateForComponents(block: (components: NSDateComponents) -> Void) -> NSDate? { let calander = NSCalendar.currentCalendar() let components = NSDateComponents() block(components: components) return calander.dateByAddingComponents(components, toDate: NSDate(), options: []) } // MARK: - timeAgoSimple func testTimeAgoSimpleSeconds() { XCTAssertEqual(self.dateForComponents { $0.second = -1 }?.timeAgoSimple, "1s") XCTAssertEqual(self.dateForComponents { $0.second = -2 }?.timeAgoSimple, "2s") XCTAssertEqual(self.dateForComponents { $0.second = -10 }?.timeAgoSimple, "10s") } func testTimeAgoSimpleMinutes() { XCTAssertEqual(self.dateForComponents { $0.minute = -1 }?.timeAgoSimple, "1m") XCTAssertEqual(self.dateForComponents { $0.minute = -2 }?.timeAgoSimple, "2m") XCTAssertEqual(self.dateForComponents { $0.minute = -10 }?.timeAgoSimple, "10m") } func testTimeAgoSimpleHours() { XCTAssertEqual(self.dateForComponents { $0.hour = -1 }?.timeAgoSimple, "1h") XCTAssertEqual(self.dateForComponents { $0.hour = -2 }?.timeAgoSimple, "2h") XCTAssertEqual(self.dateForComponents { $0.hour = -10 }?.timeAgoSimple, "10h") } func testTimeAgoSimpleDays() { XCTAssertEqual(self.dateForComponents { $0.day = -1 }?.timeAgoSimple, "1d") XCTAssertEqual(self.dateForComponents { $0.day = -2 }?.timeAgoSimple, "2d") XCTAssertEqual(self.dateForComponents { $0.day = -10 }?.timeAgoSimple, "1w") } func testTimeAgoSimpleWeeks() { XCTAssertEqual(self.dateForComponents { $0.day = -7 }?.timeAgoSimple, "1w") XCTAssertEqual(self.dateForComponents { $0.day = -7*2 }?.timeAgoSimple, "2w") XCTAssertEqual(self.dateForComponents { $0.day = -7*10 }?.timeAgoSimple, "2mo") } func testTimeAgoSimpleMonths() { XCTAssertEqual(self.dateForComponents { $0.month = -1 }?.timeAgoSimple, "1mo") XCTAssertEqual(self.dateForComponents { $0.month = -2 }?.timeAgoSimple, "2mo") XCTAssertEqual(self.dateForComponents { $0.month = -10 }?.timeAgoSimple, "10mo") } func testTimeAgoSimpleYears() { XCTAssertEqual(self.dateForComponents { $0.year = -1 }?.timeAgoSimple, "1yr") XCTAssertEqual(self.dateForComponents { $0.year = -2 }?.timeAgoSimple, "2yr") XCTAssertEqual(self.dateForComponents { $0.year = -10 }?.timeAgoSimple, "10yr") } // MARK: - timeAgo func testTimeAgoSeconds() { XCTAssertEqual(self.dateForComponents { $0.second = -1 }?.timeAgo, "Just now") XCTAssertEqual(self.dateForComponents { $0.second = -2 }?.timeAgo, "Just now") XCTAssertEqual(self.dateForComponents { $0.second = -10 }?.timeAgo, "10 seconds ago") } func testTimeAgoMinutes() { XCTAssertEqual(self.dateForComponents { $0.minute = -1 }?.timeAgo, "A minute ago") XCTAssertEqual(self.dateForComponents { $0.minute = -2 }?.timeAgo, "2 minutes ago") XCTAssertEqual(self.dateForComponents { $0.minute = -10 }?.timeAgo, "10 minutes ago") } func testTimeAgoHours() { XCTAssertEqual(self.dateForComponents { $0.hour = -1 }?.timeAgo, "An hour ago") XCTAssertEqual(self.dateForComponents { $0.hour = -2 }?.timeAgo, "2 hours ago") XCTAssertEqual(self.dateForComponents { $0.hour = -10 }?.timeAgo, "10 hours ago") } func testTimeAgoDays() { XCTAssertEqual(self.dateForComponents { $0.day = -1 }?.timeAgo, "Yesterday") XCTAssertEqual(self.dateForComponents { $0.day = -2 }?.timeAgo, "2 days ago") XCTAssertEqual(self.dateForComponents { $0.day = -10 }?.timeAgo, "Last week") } func testTimeAgoWeeks() { XCTAssertEqual(self.dateForComponents { $0.day = -7 }?.timeAgo, "Last week") XCTAssertEqual(self.dateForComponents { $0.day = -7*2 }?.timeAgo, "2 weeks ago") XCTAssertEqual(self.dateForComponents { $0.day = -7*10 }?.timeAgo, "2 months ago") } func testTimeAgoMonths() { XCTAssertEqual(self.dateForComponents { $0.month = -1 }?.timeAgo, "Last month") XCTAssertEqual(self.dateForComponents { $0.month = -2 }?.timeAgo, "2 months ago") XCTAssertEqual(self.dateForComponents { $0.month = -10 }?.timeAgo, "10 months ago") } func testTimeAgoYears() { XCTAssertEqual(self.dateForComponents { $0.year = -1 }?.timeAgo, "Last year") XCTAssertEqual(self.dateForComponents { $0.year = -2 }?.timeAgo, "2 years ago") XCTAssertEqual(self.dateForComponents { $0.year = -10 }?.timeAgo, "10 years ago") } }
43.458333
111
0.65139
de14ab70586d81d03af1c56c7d58149421380c5c
30,586
// // CropView.swift // Mantis // // Created by Echo on 10/20/18. // Copyright © 2018 Echo. 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 protocol CropViewDelegate: AnyObject { func cropViewDidBecomeResettable(_ cropView: CropView) func cropViewDidBecomeUnResettable(_ cropView: CropView) func cropViewDidBeginResize(_ cropView: CropView) func cropViewDidEndResize(_ cropView: CropView) } let cropViewMinimumBoxSize: CGFloat = 42 let minimumAspectRatio: CGFloat = 0 let hotAreaUnit: CGFloat = 32 let cropViewPadding:CGFloat = 14.0 public class CropView: UIView { public var dialConfig = Mantis.Config().dialConfig var cropShapeType: CropShapeType = .rect var cropVisualEffectType: CropVisualEffectType = .blurDark var angleDashboardHeight: CGFloat = 60 var image: UIImage { didSet { imageContainer.image = image } } let viewModel: CropViewModel weak var delegate: CropViewDelegate? { didSet { checkImageStatusChanged() } } var aspectRatioLockEnabled = false // Referred to in extension let imageContainer: ImageContainer let gridOverlayView: CropOverlayView var rotationDial: RotationDial? lazy var scrollView = CropScrollView(frame: bounds) lazy var cropMaskViewManager = CropMaskViewManager(with: self, cropRatio: CGFloat(getImageRatioH()), cropShapeType: cropShapeType, cropVisualEffectType: cropVisualEffectType) var manualZoomed = false private var cropFrameKVO: NSKeyValueObservation? var forceFixedRatio = false var imageStatusChangedCheckForForceFixedRatio = false deinit { print("CropView deinit.") } init(image: UIImage, viewModel: CropViewModel = CropViewModel(), dialConfig: DialConfig = Mantis.Config().dialConfig) { self.image = image self.viewModel = viewModel self.dialConfig = dialConfig imageContainer = ImageContainer() gridOverlayView = CropOverlayView() super.init(frame: CGRect.zero) self.viewModel.statusChanged = { [weak self] status in self?.render(by: status) } cropFrameKVO = viewModel.observe(\.cropBoxFrame, options: [.new, .old]) { [unowned self] _, changed in guard let cropFrame = changed.newValue else { return } self.gridOverlayView.frame = cropFrame var cropRatio: CGFloat = 1.0 if self.gridOverlayView.frame.height != 0 { cropRatio = self.gridOverlayView.frame.width / self.gridOverlayView.frame.height } self.cropMaskViewManager.adaptMaskTo(match: cropFrame, cropRatio: cropRatio) } initalRender() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func initalRender() { setupUI() checkImageStatusChanged() } private func render(by viewStatus: CropViewStatus) { gridOverlayView.isHidden = false switch viewStatus { case .initial: initalRender() case .rotating(let angle): viewModel.degrees = angle.degrees rotateScrollView() case .degree90Rotating: cropMaskViewManager.showVisualEffectBackground() gridOverlayView.isHidden = true rotationDial?.isHidden = true case .touchImage: cropMaskViewManager.showDimmingBackground() gridOverlayView.gridLineNumberType = .crop gridOverlayView.setGrid(hidden: false, animated: true) case .touchCropboxHandle(let tappedEdge): gridOverlayView.handleEdgeTouched(with: tappedEdge) rotationDial?.isHidden = true cropMaskViewManager.showDimmingBackground() case .touchRotationBoard: gridOverlayView.gridLineNumberType = .rotate gridOverlayView.setGrid(hidden: false, animated: true) cropMaskViewManager.showDimmingBackground() case .betweenOperation: gridOverlayView.handleEdgeUntouched() rotationDial?.isHidden = false adaptAngleDashboardToCropBox() cropMaskViewManager.showVisualEffectBackground() checkImageStatusChanged() } } private func isTheSamePoint(p1: CGPoint, p2: CGPoint) -> Bool { let tolerance = CGFloat.ulpOfOne * 10 if abs(p1.x - p2.x) > tolerance { return false } if abs(p1.y - p2.y) > tolerance { return false } return true } private func imageStatusChanged() -> Bool { if viewModel.getTotalRadians() != 0 { return true } if (forceFixedRatio) { if imageStatusChangedCheckForForceFixedRatio { imageStatusChangedCheckForForceFixedRatio = false return scrollView.zoomScale != 1 } } if !isTheSamePoint(p1: getImageLeftTopAnchorPoint(), p2: .zero) { return true } if !isTheSamePoint(p1: getImageRightBottomAnchorPoint(), p2: CGPoint(x: 1, y: 1)) { return true } return false } private func checkImageStatusChanged() { if imageStatusChanged() { delegate?.cropViewDidBecomeResettable(self) } else { delegate?.cropViewDidBecomeUnResettable(self) } } private func setupUI() { setupScrollView() imageContainer.image = image scrollView.addSubview(imageContainer) scrollView.imageContainer = imageContainer setGridOverlayView() } func resetUIFrame() { cropMaskViewManager.removeMaskViews() cropMaskViewManager.setup(in: self, cropRatio: CGFloat(getImageRatioH())) viewModel.resetCropFrame(by: getInitialCropBoxRect()) scrollView.transform = .identity scrollView.resetBy(rect: viewModel.cropBoxFrame) imageContainer.frame = scrollView.bounds imageContainer.center = CGPoint(x: scrollView.bounds.width/2, y: scrollView.bounds.height/2) gridOverlayView.superview?.bringSubviewToFront(gridOverlayView) setupAngleDashboard() if aspectRatioLockEnabled { setFixedRatioCropBox() } } func adaptForCropBox() { resetUIFrame() } private func setupScrollView() { scrollView.touchesBegan = { [weak self] in self?.viewModel.setTouchImageStatus() } scrollView.touchesEnded = { [weak self] in self?.viewModel.setBetweenOperationStatus() } scrollView.delegate = self addSubview(scrollView) } private func setGridOverlayView() { gridOverlayView.isUserInteractionEnabled = false gridOverlayView.gridHidden = true addSubview(gridOverlayView) } private func setupAngleDashboard() { if angleDashboardHeight == 0 { return } if rotationDial != nil { rotationDial?.removeFromSuperview() } let boardLength = min(bounds.width, bounds.height) * 0.6 let rotationDial = RotationDial(frame: CGRect(x: 0, y: 0, width: boardLength, height: angleDashboardHeight), dialConfig: dialConfig) self.rotationDial = rotationDial rotationDial.isUserInteractionEnabled = true addSubview(rotationDial) rotationDial.setRotationCenter(by: gridOverlayView.center, of: self) rotationDial.didRotate = { [unowned self] angle in if self.forceFixedRatio { let newRadians = self.viewModel.getTotalRadias(by: angle.radians) self.viewModel.setRotatingStatus(by: CGAngle(radians: newRadians)) } else { self.viewModel.setRotatingStatus(by: angle) } } rotationDial.didFinishedRotate = { [unowned self] in self.viewModel.setBetweenOperationStatus() } rotationDial.rotateDialPlate(by: CGAngle(radians: viewModel.radians)) adaptAngleDashboardToCropBox() } private func adaptAngleDashboardToCropBox() { guard let rotationDial = rotationDial else { return } if Orientation.isPortrait { rotationDial.transform = CGAffineTransform(rotationAngle: 0) rotationDial.frame.origin.x = gridOverlayView.frame.origin.x + (gridOverlayView.frame.width - rotationDial.frame.width) / 2 rotationDial.frame.origin.y = gridOverlayView.frame.maxY } else if Orientation.isLandscapeLeft { rotationDial.transform = CGAffineTransform(rotationAngle: -CGFloat.pi / 2) rotationDial.frame.origin.x = gridOverlayView.frame.maxX rotationDial.frame.origin.y = gridOverlayView.frame.origin.y + (gridOverlayView.frame.height - rotationDial.frame.height) / 2 } else if Orientation.isLandscapeRight { rotationDial.transform = CGAffineTransform(rotationAngle: CGFloat.pi / 2) rotationDial.frame.origin.x = gridOverlayView.frame.minX - rotationDial.frame.width rotationDial.frame.origin.y = gridOverlayView.frame.origin.y + (gridOverlayView.frame.height - rotationDial.frame.height) / 2 } } func updateCropBoxFrame(with point: CGPoint) { let contentFrame = getContentBounds() let newCropBoxFrame = viewModel.getNewCropBoxFrame(with: point, and: contentFrame, aspectRatioLockEnabled: aspectRatioLockEnabled) let contentBounds = getContentBounds() guard newCropBoxFrame.width >= cropViewMinimumBoxSize && newCropBoxFrame.minX >= contentBounds.minX && newCropBoxFrame.maxX <= contentBounds.maxX && newCropBoxFrame.height >= cropViewMinimumBoxSize && newCropBoxFrame.minY >= contentBounds.minY && newCropBoxFrame.maxY <= contentBounds.maxY else { return } if imageContainer.contains(rect: newCropBoxFrame, fromView: self) { viewModel.cropBoxFrame = newCropBoxFrame } else { let minX = max(viewModel.cropBoxFrame.minX, newCropBoxFrame.minX) let minY = max(viewModel.cropBoxFrame.minY, newCropBoxFrame.minY) let maxX = min(viewModel.cropBoxFrame.maxX, newCropBoxFrame.maxX) let maxY = min(viewModel.cropBoxFrame.maxY, newCropBoxFrame.maxY) var rect: CGRect rect = CGRect(x: minX, y: minY, width: newCropBoxFrame.width, height: maxY - minY) if imageContainer.contains(rect: rect, fromView: self) { viewModel.cropBoxFrame = rect return } rect = CGRect(x: minX, y: minY, width: maxX - minX, height: newCropBoxFrame.height) if imageContainer.contains(rect: rect, fromView: self) { viewModel.cropBoxFrame = rect return } rect = CGRect(x: newCropBoxFrame.minX, y: minY, width: newCropBoxFrame.width, height: maxY - minY) if imageContainer.contains(rect: rect, fromView: self) { viewModel.cropBoxFrame = rect return } rect = CGRect(x: minX, y: newCropBoxFrame.minY, width: maxX - minX, height: newCropBoxFrame.height) if imageContainer.contains(rect: rect, fromView: self) { viewModel.cropBoxFrame = rect return } viewModel.cropBoxFrame = CGRect(x: minX, y: minY, width: maxX - minX, height: maxY - minY) } } } // MARK: - Adjust UI extension CropView { private func rotateScrollView() { let totalRadians = forceFixedRatio ? viewModel.radians : viewModel.getTotalRadians() self.scrollView.transform = CGAffineTransform(rotationAngle: totalRadians) self.updatePosition(by: totalRadians) } private func getInitialCropBoxRect() -> CGRect { guard image.size.width > 0 && image.size.height > 0 else { return .zero } let outsideRect = getContentBounds() let insideRect: CGRect if viewModel.isUpOrUpsideDown() { insideRect = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height) } else { insideRect = CGRect(x: 0, y: 0, width: image.size.height, height: image.size.width) } return GeometryHelper.getInscribeRect(fromOutsideRect: outsideRect, andInsideRect: insideRect) } func getContentBounds() -> CGRect { let rect = self.bounds var contentRect = CGRect.zero if Orientation.isPortrait { contentRect.origin.x = rect.origin.x + cropViewPadding contentRect.origin.y = rect.origin.y + cropViewPadding contentRect.size.width = rect.width - 2 * cropViewPadding contentRect.size.height = rect.height - 2 * cropViewPadding - angleDashboardHeight } else if Orientation.isLandscape { contentRect.size.width = rect.width - 2 * cropViewPadding - angleDashboardHeight contentRect.size.height = rect.height - 2 * cropViewPadding contentRect.origin.y = rect.origin.y + cropViewPadding if Orientation.isLandscapeLeft { contentRect.origin.x = rect.origin.x + cropViewPadding } else { contentRect.origin.x = rect.origin.x + cropViewPadding + angleDashboardHeight } } return contentRect } fileprivate func getImageLeftTopAnchorPoint() -> CGPoint { if imageContainer.bounds.size == .zero { return viewModel.cropLeftTopOnImage } let lt = gridOverlayView.convert(CGPoint(x: 0, y: 0), to: imageContainer) let point = CGPoint(x: lt.x / imageContainer.bounds.width, y: lt.y / imageContainer.bounds.height) return point } fileprivate func getImageRightBottomAnchorPoint() -> CGPoint { if imageContainer.bounds.size == .zero { return viewModel.cropRightBottomOnImage } let rb = gridOverlayView.convert(CGPoint(x: gridOverlayView.bounds.width, y: gridOverlayView.bounds.height), to: imageContainer) let point = CGPoint(x: rb.x / imageContainer.bounds.width, y: rb.y / imageContainer.bounds.height) return point } fileprivate func saveAnchorPoints() { viewModel.cropLeftTopOnImage = getImageLeftTopAnchorPoint() viewModel.cropRightBottomOnImage = getImageRightBottomAnchorPoint() } func adjustUIForNewCrop(contentRect:CGRect, animation: Bool = true, zoom: Bool = true, completion: @escaping ()->Void) { let scaleX: CGFloat let scaleY: CGFloat scaleX = contentRect.width / viewModel.cropBoxFrame.size.width scaleY = contentRect.height / viewModel.cropBoxFrame.size.height let scale = min(scaleX, scaleY) let newCropBounds = CGRect(x: 0, y: 0, width: viewModel.cropBoxFrame.width * scale, height: viewModel.cropBoxFrame.height * scale) let radians = forceFixedRatio ? viewModel.radians : viewModel.getTotalRadians() // calculate the new bounds of scroll view let newBoundWidth = abs(cos(radians)) * newCropBounds.size.width + abs(sin(radians)) * newCropBounds.size.height let newBoundHeight = abs(sin(radians)) * newCropBounds.size.width + abs(cos(radians)) * newCropBounds.size.height // calculate the zoom area of scroll view var scaleFrame = viewModel.cropBoxFrame let refContentWidth = abs(cos(radians)) * scrollView.contentSize.width + abs(sin(radians)) * scrollView.contentSize.height let refContentHeight = abs(sin(radians)) * scrollView.contentSize.width + abs(cos(radians)) * scrollView.contentSize.height if scaleFrame.width >= refContentWidth { scaleFrame.size.width = refContentWidth } if scaleFrame.height >= refContentHeight { scaleFrame.size.height = refContentHeight } let contentOffset = scrollView.contentOffset let contentOffsetCenter = CGPoint(x: (contentOffset.x + scrollView.bounds.width / 2), y: (contentOffset.y + scrollView.bounds.height / 2)) scrollView.bounds = CGRect(x: 0, y: 0, width: newBoundWidth, height: newBoundHeight) let newContentOffset = CGPoint(x: (contentOffsetCenter.x - newBoundWidth / 2), y: (contentOffsetCenter.y - newBoundHeight / 2)) scrollView.contentOffset = newContentOffset let newCropBoxFrame = GeometryHelper.getInscribeRect(fromOutsideRect: contentRect, andInsideRect: viewModel.cropBoxFrame) func updateUI(by newCropBoxFrame: CGRect, and scaleFrame: CGRect) { viewModel.cropBoxFrame = newCropBoxFrame if zoom { let zoomRect = convert(scaleFrame, to: scrollView.imageContainer) scrollView.zoom(to: zoomRect, animated: false) } scrollView.checkContentOffset() makeSureImageContainsCropOverlay() } if animation { UIView.animate(withDuration: 0.25, animations: { updateUI(by: newCropBoxFrame, and: scaleFrame) }) {_ in completion() } } else { updateUI(by: newCropBoxFrame, and: scaleFrame) completion() } manualZoomed = true } func makeSureImageContainsCropOverlay() { if !imageContainer.contains(rect: gridOverlayView.frame, fromView: self, tolerance: 0.25) { scrollView.zoomScaleToBound(animated: true) } } fileprivate func updatePosition(by radians: CGFloat) { let width = abs(cos(radians)) * gridOverlayView.frame.width + abs(sin(radians)) * gridOverlayView.frame.height let height = abs(sin(radians)) * gridOverlayView.frame.width + abs(cos(radians)) * gridOverlayView.frame.height scrollView.updateLayout(byNewSize: CGSize(width: width, height: height)) if !manualZoomed || scrollView.shouldScale() { scrollView.zoomScaleToBound() manualZoomed = false } else { scrollView.updateMinZoomScale() } scrollView.checkContentOffset() } fileprivate func updatePositionFor90Rotation(by radians: CGFloat) { func adjustScrollViewForNormalRatio(by radians: CGFloat) -> CGFloat { let width = abs(cos(radians)) * gridOverlayView.frame.width + abs(sin(radians)) * gridOverlayView.frame.height let height = abs(sin(radians)) * gridOverlayView.frame.width + abs(cos(radians)) * gridOverlayView.frame.height let newSize: CGSize if viewModel.rotationType == .none || viewModel.rotationType == .counterclockwise180 { newSize = CGSize(width: width, height: height) } else { newSize = CGSize(width: height, height: width) } let scale = newSize.width / scrollView.bounds.width scrollView.updateLayout(byNewSize: newSize) return scale } let scale = adjustScrollViewForNormalRatio(by: radians) let newZoomScale = scrollView.zoomScale * scale scrollView.minimumZoomScale = newZoomScale scrollView.zoomScale = newZoomScale scrollView.checkContentOffset() } } // MARK: - internal API extension CropView { func crop(_ image: UIImage) -> (croppedImage: UIImage?, transformation: Transformation) { let info = getCropInfo() let transformation = Transformation( offset: scrollView.contentOffset, rotation: getTotalRadians(), scale: scrollView.zoomScale, manualZoomed: manualZoomed, intialMaskFrame: getInitialCropBoxRect(), maskFrame: gridOverlayView.frame, scrollBounds: scrollView.bounds, imageViewBounds: imageContainer.bounds, imageViewFrame: imageContainer.frame ) guard let croppedImage = image.getCroppedImage(byCropInfo: info) else { return (nil, transformation) } switch cropShapeType { case .rect, .square, .circle(maskOnly: true), .roundedRect(_, maskOnly: true), .path(_, maskOnly: true), .diamond(maskOnly: true), .heart(maskOnly: true), .polygon(_, _, maskOnly: true): return (croppedImage, transformation) case .ellipse: return (croppedImage.ellipseMasked, transformation) case .circle: return (croppedImage.ellipseMasked, transformation) case .roundedRect(let radiusToShortSide, maskOnly: false): let radius = min(croppedImage.size.width, croppedImage.size.height) * radiusToShortSide return (croppedImage.roundRect(radius), transformation) case .path(let points, maskOnly: false): return (croppedImage.clipPath(points), transformation) case .diamond(maskOnly: false): let points = [CGPoint(x: 0.5, y: 0), CGPoint(x: 1, y: 0.5), CGPoint(x: 0.5, y: 1), CGPoint(x: 0, y: 0.5)] return (croppedImage.clipPath(points), transformation) case .heart(maskOnly: false): return (croppedImage.heart, transformation) case .polygon(let sides, let offset, maskOnly: false): let points = polygonPointArray(sides: sides, originX: 0.5, originY: 0.5, radius: 0.5, offset: 90 + offset) return (croppedImage.clipPath(points), transformation) } } func getCropInfo() -> CropInfo { let rect = imageContainer.convert(imageContainer.bounds, to: self) let point = rect.center let zeroPoint = gridOverlayView.center let translation = CGPoint(x: (point.x - zeroPoint.x), y: (point.y - zeroPoint.y)) return CropInfo( translation: translation, rotation: getTotalRadians(), scale: scrollView.zoomScale, cropSize: gridOverlayView.frame.size, imageViewSize: imageContainer.bounds.size ) } func getTotalRadians() -> CGFloat { return forceFixedRatio ? viewModel.radians : viewModel.getTotalRadians() } func crop() -> (croppedImage: UIImage?, transformation: Transformation) { return crop(image) } func handleRotate() { viewModel.resetCropFrame(by: getInitialCropBoxRect()) scrollView.transform = .identity scrollView.resetBy(rect: viewModel.cropBoxFrame) setupAngleDashboard() rotateScrollView() if viewModel.cropRightBottomOnImage != .zero { var lt = CGPoint(x: viewModel.cropLeftTopOnImage.x * imageContainer.bounds.width, y: viewModel.cropLeftTopOnImage.y * imageContainer.bounds.height) var rb = CGPoint(x: viewModel.cropRightBottomOnImage.x * imageContainer.bounds.width, y: viewModel.cropRightBottomOnImage.y * imageContainer.bounds.height) lt = imageContainer.convert(lt, to: self) rb = imageContainer.convert(rb, to: self) let rect = CGRect(origin: lt, size: CGSize(width: rb.x - lt.x, height: rb.y - lt.y)) viewModel.cropBoxFrame = rect let contentRect = getContentBounds() adjustUIForNewCrop(contentRect: contentRect) { [weak self] in self?.adaptAngleDashboardToCropBox() self?.viewModel.setBetweenOperationStatus() } } } func rotateBy90(rotateAngle: CGFloat, completion: @escaping ()->Void = {}) { viewModel.setDegree90RotatingStatus() let rorateDuration = 0.25 if forceFixedRatio { viewModel.setRotatingStatus(by: CGAngle(radians: viewModel.radians)) let angle = CGAngle(radians: rotateAngle + viewModel.radians) UIView.animate(withDuration: rorateDuration, animations: { self.viewModel.setRotatingStatus(by: angle) }) {[weak self] _ in guard let self = self else { return } self.viewModel.rotateBy90(rotateAngle: rotateAngle) self.viewModel.setBetweenOperationStatus() completion() } return } var rect = gridOverlayView.frame rect.size.width = gridOverlayView.frame.height rect.size.height = gridOverlayView.frame.width let newRect = GeometryHelper.getInscribeRect(fromOutsideRect: getContentBounds(), andInsideRect: rect) let radian = rotateAngle let transfrom = scrollView.transform.rotated(by: radian) UIView.animate(withDuration: rorateDuration, animations: { self.viewModel.cropBoxFrame = newRect self.scrollView.transform = transfrom self.updatePositionFor90Rotation(by: radian + self.viewModel.radians) }) {[weak self] _ in guard let self = self else { return } self.scrollView.updateMinZoomScale() self.viewModel.rotateBy90(rotateAngle: rotateAngle) self.viewModel.setBetweenOperationStatus() completion() } } func reset() { scrollView.removeFromSuperview() gridOverlayView.removeFromSuperview() rotationDial?.removeFromSuperview() if forceFixedRatio { aspectRatioLockEnabled = true } else { aspectRatioLockEnabled = false } viewModel.reset(forceFixedRatio: forceFixedRatio) resetUIFrame() delegate?.cropViewDidBecomeUnResettable(self) } func prepareForDeviceRotation() { viewModel.setDegree90RotatingStatus() saveAnchorPoints() } fileprivate func setRotation(byRadians radians: CGFloat) { scrollView.transform = CGAffineTransform(rotationAngle: radians) updatePosition(by: radians) rotationDial?.rotateDialPlate(to: CGAngle(radians: radians), animated: false) } func setFixedRatioCropBox(zoom: Bool = true, cropBox: CGRect? = nil) { let refCropBox = cropBox ?? getInitialCropBoxRect() viewModel.setCropBoxFrame(by: refCropBox, and: getImageRatioH()) let contentRect = getContentBounds() adjustUIForNewCrop(contentRect: contentRect, animation: false, zoom: zoom) { [weak self] in guard let self = self else { return } if self.forceFixedRatio { self.imageStatusChangedCheckForForceFixedRatio = true } self.viewModel.setBetweenOperationStatus() } adaptAngleDashboardToCropBox() scrollView.updateMinZoomScale() } func getRatioType(byImageIsOriginalisHorizontal isHorizontal: Bool) -> RatioType { return viewModel.getRatioType(byImageIsOriginalHorizontal: isHorizontal) } func getImageRatioH() -> Double { if viewModel.rotationType == .none || viewModel.rotationType == .counterclockwise180 { return Double(image.ratioH()) } else { return Double(1/image.ratioH()) } } func transform(byTransformInfo transformation: Transformation, rotateDial: Bool = true) { viewModel.setRotatingStatus(by: CGAngle(radians:transformation.rotation)) if (transformation.scrollBounds != .zero) { scrollView.bounds = transformation.scrollBounds } manualZoomed = transformation.manualZoomed scrollView.zoomScale = transformation.scale scrollView.contentOffset = transformation.offset viewModel.setBetweenOperationStatus() if (transformation.maskFrame != .zero) { viewModel.cropBoxFrame = transformation.maskFrame } if (rotateDial) { rotationDial?.rotateDialPlate(by: CGAngle(radians: viewModel.radians)) adaptAngleDashboardToCropBox() } } }
39.162612
167
0.616132
f7bdbaaa965337e5e9b6bac1aa1d57f7f13cf7ab
1,161
import Foundation import ExposureNotification class ConfigurationProvider { static func checkForUpdate(success: @escaping (Update)-> Void, failure: @escaping (CustomError) -> Void) { ApiConnector.request(url: Configuration.updateUrlString, params: nil, method: .get, completion: { (response: UpdateWrapper) in success(response.update) }) { error in failure(error) } } static func getExposureConfiguration(completion: (Result<ENExposureConfiguration, Error>) -> Void) { let en = ENExposureConfiguration() en.metadata = ["attenuationDurationThresholds": [50, 70] as [NSNumber]] // Requires iOS 13.6 en.attenuationWeight = 50 en.minimumRiskScore = 1 en.transmissionRiskWeight = 50 en.daysSinceLastExposureWeight = 50 en.daysSinceLastExposureLevelValues = [1,2,2,4,6,8,8,8] as [NSNumber] en.attenuationLevelValues = [0,0,1,6,6,7,8,8] as [NSNumber] en.transmissionRiskLevelValues = [8,8,8,8,8,8,8,8] as [NSNumber] en.durationLevelValues = [1,1,5,8,8,8,8,8] return completion(.success(en)) } }
38.7
134
0.652024
48f344e53b6f08d82cb9d4176e6b55d22062ee57
1,492
// // DemoViewController.swift // TexturedMaakuDemo // // Created by Kris Baker on 12/20/17. // Copyright © 2017 Kristopher Baker. All rights reserved. // import Maaku import TexturedMaaku import UIKit class DemoViewController: DocumentViewController { init(resourceName: String) { PluginManager.registerParsers([YoutubePluginParser()]) NodePluginManager.registerMappings([YoutubeNodePluginMap()]) guard let path = Bundle.main.path(forResource: resourceName, ofType: "md"), let text: String = try? String(contentsOfFile: path), let document = try? Document(text: text, options: .footnotes) else { fatalError() } super.init(document: document) title = resourceName.capitalized } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func linkTapped(_ url: URL) { if let scheme = url.scheme, scheme == "commonmark", let host = url.host, !host.isEmpty { let vc = DemoViewController(resourceName: host) navigationController?.pushViewController(vc, animated: true) } else { super.linkTapped(url) } debugPrint(url) } }
27.127273
96
0.615952
760e119098f9650c3d396875a3b7fd6eb18f33df
2,038
// // CountriesTableViewCell.swift // Auth // // Created by Adam Cseke on 2022. 02. 22.. // Copyright © 2022. levivig. All rights reserved. // import UIKit class CountriesTableViewCell: UITableViewCell { static let reuseID = "CountriesCell" private var countryFlagLabel: UILabel! private var countryLabel: UILabel! private var countryNumberLabel: UILabel! override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) configure() } required init?(coder: NSCoder) { super.init(coder: coder) configure() } func set(countryFlag: String, countryText: String, countryNumber: String) { countryFlagLabel.text = countryFlag countryLabel.text = countryText countryNumberLabel.text = countryNumber } private func configure() { countryFlagLabel = UILabel() countryLabel = UILabel() countryNumberLabel = UILabel() addSubview(countryFlagLabel) addSubview(countryLabel) addSubview(countryNumberLabel) countryLabel.font = UIFont(name: "Hind-Bold", size: 15) countryNumberLabel.font = UIFont(name: "Hind-Regular", size: 15) countryFlagLabel.layer.cornerRadius = 12 countryFlagLabel.layer.masksToBounds = true accessoryType = .disclosureIndicator countryFlagLabel.snp.makeConstraints { make in make.height.width.equalTo(30) make.centerY.equalTo(snp.centerY) make.leading.equalTo(21) } countryLabel.snp.makeConstraints { make in make.centerY.equalTo(snp.centerY) make.leading.equalTo(countryFlagLabel.snp.trailing).offset(20) } countryNumberLabel.snp.makeConstraints { make in make.centerY.equalTo(snp.centerY) make.leading.equalTo(countryLabel.snp.trailing).offset(35) } } }
29.536232
79
0.640334
215c9b8bea1e317cdf0169d526742bdf95062f43
813
// // SessionStorageIdfa.swift // ZappSessionStorageIdfa // // Created by Alex Zchut on 24/03/2021. // Copyright © 2021 Applicaster Ltd. All rights reserved. // import Foundation #if canImport(AppTrackingTransparency) import AppTrackingTransparency #endif public extension SessionStorageIdfa { enum AuthorizationStatus: UInt { case notDetermined = 0 case restricted = 1 case denied = 2 case authorized = 3 } func requestTrackingAuthorization() async -> AuthorizationStatus { #if canImport(AppTrackingTransparency) let status = await ATTrackingManager.requestTrackingAuthorization() return AuthorizationStatus(rawValue: status.rawValue) ?? .notDetermined #else return .notDetermined #endif } }
25.40625
83
0.685117
e9fd77839bb3a6970f19e91dbc814fe80c974199
572
// // CustomCollectionViewCell.swift // DesafioAula08_01 // // Created by SP11793 on 16/03/22. // import UIKit class CustomCollectionViewCell: UICollectionViewCell { @IBOutlet weak var imageAlbum: UIImageView! @IBOutlet weak var labelAlbumName: UILabel! static let identifier = "CustomCollectionViewCell" override func awakeFromNib() { super.awakeFromNib() } func setupCollectionView(image: String, title: String) { imageAlbum.image = UIImage(named: image) labelAlbumName.text = title } }
20.428571
60
0.673077
d6bf9f0d914a1adb0a9a1197c71e123e184262bd
265
// // TableViewCell.swift // TableViewControllerDataHandleDemo // // Created by Robert Wong on 8/9/18. // Copyright © 2018 Robert Wong. All rights reserved. // import UIKit class TableViewCell: UITableViewCell { @IBOutlet weak var testLabel: UILabel! }
16.5625
54
0.720755
bb08e180acadb4e1696eccbecf9caa4aa73e9f3a
1,295
// // WritingDataToTheDocumentsDerectory.swift // BucketList // // Created by Petro Onishchuk on 3/12/20. // Copyright © 2020 Petro Onishchuk. All rights reserved. // import SwiftUI struct WritingDataToTheDocumentsDirectory: View { var body: some View { Text(/*@START_MENU_TOKEN@*/"Hello, World!"/*@END_MENU_TOKEN@*/) .onTapGesture { let str = "Test Message" let url = self.getDocumentDirectory().appendingPathComponent("message.txt") do { try str.write(to: url, atomically: true, encoding: .utf8) let input = try String(contentsOf: url) print(input) } catch { print(error.localizedDescription) } } } func getDocumentDirectory() -> URL { // find all possible documents directory for this user let path = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) // just send back the first one, which ought to be the only one return path[0] } } struct WritingDataToTheDocumentsDirectory_Previews: PreviewProvider { static var previews: some View { WritingDataToTheDocumentsDirectory() } }
28.777778
91
0.591506
ac2269488d0aa0c977dccb989d46b845908c56f7
429
func foo() {} foo() // RUN: %sourcekitd-test -req=open %s -- %s \ // RUN: == -req=edit -offset=0 -replace="" -length=0 %s \ // RUN: == -req=edit -offset=0 -replace="" -length=0 %s \ // RUN: == -req=edit -pos=3:1 -replace="foo()" -length=0 %s \ // RUN: == -req=edit -offset=0 -replace="" -length=0 %s \ // RUN: == -req=edit -offset=0 -replace="" -length=0 %s > %t.response // RUN: %diff -u %s.response %t.response
39
72
0.540793
efa04835a459d5324c387b1e6bdedec1f94f6ba0
7,751
// // Date+Config.swift // TTBaseUIKit // // Created by Truong Quang Tuan on 5/21/19. // Copyright © 2019 Truong Quang Tuan. All rights reserved. // import Foundation extension Date { public func getDateWithEvenTime(byPeriod interval:Int) -> Date { let calendar = Calendar.current let nextDiff = interval - (calendar.component(.minute, from: self) % interval) return calendar.date(byAdding: .minute, value: nextDiff, to: self) ?? Date() } public func getDateWithEvenTimeWithSecondRounding(byPeriod interval:Int) -> Date { let calendar = Calendar.current let nextDiff = interval - (calendar.component(.minute, from: self) % interval) let dateAddInterVal = calendar.date(byAdding: .minute, value: nextDiff, to: self) ?? Date() return calendar.date(bySettingHour: dateAddInterVal.hour(), minute: dateAddInterVal.minute(), second: 0, of: dateAddInterVal) ?? Date() } public func getAllDateOfMonth(with currentDate:Date) -> ([Date],Int) { var days = [Date]() var index:Int = -1 let calendar = Calendar.current guard let range = calendar.range(of: .day, in: .month, for: self) else {return (days,0)} var day = self.firstDayOfMonth() for count in 0 ..< range.count { days.append(day) if Calendar.current.compare(day, to: currentDate, toGranularity: .day) == ComparisonResult.orderedSame { index = count } day = day.dateByAddingDays(1) } return (days,index) } public func getNextMonth() -> Date { return (Calendar.current.date(byAdding: .month, value: 1, to: self.firstDayOfMonth()) ?? Date() ) } public func getPreviousMonth() -> Date { return ( Calendar.current.date(byAdding: .month, value: -1, to: self.firstDayOfMonth()) ?? Date() ) } public func dateString(withFormat format: CONSTANT.FORMAT_DATE) -> String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = format.rawValue dateFormatter.amSymbol = "AM" dateFormatter.pmSymbol = "PM" dateFormatter.locale = Locale(identifier: "en_US_POSIX") return dateFormatter.string(from: self) } public func firstDayOfMonth () -> Date { let calendar = Calendar.current var dateComponent = (calendar as NSCalendar).components([.year, .month, .day ], from: self) dateComponent.day = 1 return calendar.date(from: dateComponent)! } public init(year : Int, month : Int, day : Int) { let calendar = Calendar.current var dateComponent = DateComponents() dateComponent.year = year dateComponent.month = month dateComponent.day = day self.init(timeInterval: 0, since: calendar.date(from: dateComponent)!) } public func dateByAddingMonths(_ months : Int ) -> Date { let calendar = Calendar.current var dateComponent = DateComponents() dateComponent.month = months return (calendar as NSCalendar).date(byAdding: dateComponent, to: self, options: NSCalendar.Options.matchNextTime)! } public func dateByAddingDays(_ days : Int ) -> Date { let calendar = Calendar.current var dateComponent = DateComponents() dateComponent.day = days return (calendar as NSCalendar).date(byAdding: dateComponent, to: self, options: NSCalendar.Options.matchNextTime)! } public func dateByAddingHours(_ hours : Int ) -> Date { let calendar = Calendar.current var dateComponent = DateComponents() dateComponent.hour = hours return (calendar as NSCalendar).date(byAdding: dateComponent, to: self, options: NSCalendar.Options.matchNextTime)! } public func dateByAddingMinutes(_ minutes : Int ) -> Date { let calendar = Calendar.current var dateComponent = DateComponents() dateComponent.minute = minutes return (calendar as NSCalendar).date(byAdding: dateComponent, to: self, options: NSCalendar.Options.matchNextTime)! } public func hour() -> Int { let calendar = Calendar.current let dateComponent = (calendar as NSCalendar).components(.hour, from: self) return dateComponent.hour! } public func second() -> Int { let calendar = Calendar.current let dateComponent = (calendar as NSCalendar).components(.second, from: self) return dateComponent.second! } public func minute() -> Int { let calendar = Calendar.current let dateComponent = (calendar as NSCalendar).components(.minute, from: self) return dateComponent.minute! } public func day() -> Int { let calendar = Calendar.current let dateComponent = (calendar as NSCalendar).components(.day, from: self) return dateComponent.day! } public func weekday() -> Int { let calendar = Calendar.current let dateComponent = (calendar as NSCalendar).components(.weekday, from: self) return dateComponent.weekday! } public func month() -> Int { let calendar = Calendar.current let dateComponent = (calendar as NSCalendar).components(.month, from: self) return dateComponent.month! } public func year() -> Int { let calendar = Calendar.current let dateComponent = (calendar as NSCalendar).components(.year, from: self) return dateComponent.year! } public func numberOfDaysInMonth() -> Int { let calendar = Calendar.current let days = (calendar as NSCalendar).range(of: NSCalendar.Unit.day, in: NSCalendar.Unit.month, for: self) return days.length } public func dateByIgnoringTime() -> Date { let calendar = Calendar.current let dateComponent = (calendar as NSCalendar).components([.year, .month, .day ], from: self) return calendar.date(from: dateComponent)! } public func monthNameFull() -> String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "MMMM YYYY" return dateFormatter.string(from: self) } public func isSunday() -> Bool { return (self.getWeekday() == 1) } public func isMonday() -> Bool { return (self.getWeekday() == 2) } public func isTuesday() -> Bool { return (self.getWeekday() == 3) } public func isWednesday() -> Bool { return (self.getWeekday() == 4) } public func isThursday() -> Bool { return (self.getWeekday() == 5) } public func isFriday() -> Bool { return (self.getWeekday() == 6) } public func isSaturday() -> Bool { return (self.getWeekday() == 7) } public func getWeekday() -> Int { let calendar = Calendar.current return (calendar as NSCalendar).components( .weekday, from: self).weekday! } public func isToday() -> Bool { return self.isDateSameDay(Date()) } public func isDateSameDay(_ date: Date) -> Bool { return (self.day() == date.day()) && (self.month() == self.month() && (self.year() == date.year())) } } public func ==(lhs: Date, rhs: Date) -> Bool { return lhs.compare(rhs) == ComparisonResult.orderedSame } public func <(lhs: Date, rhs: Date) -> Bool { return lhs.compare(rhs) == ComparisonResult.orderedAscending } public func >(lhs: Date, rhs: Date) -> Bool { return rhs.compare(lhs) == ComparisonResult.orderedAscending }
33.554113
143
0.617856
90e554c7de042158c641d4cd3614ec304f3bb497
331
// // LibraryPath.swift // LibraryPath // // Created by Rudrank Riyam on 14/08/21. // import Foundation public enum LibraryPath: String { case catalog case user var url: String { switch self { case .catalog: return "/v1/catalog/" case .user: return "/v1/me/" } } }
15.761905
48
0.555891
fb68d55fef5b4093177b12441fc85b4cbcb858a4
4,099
/* * Copyright (c) 2019 STMicroelectronics – All rights reserved * The STMicroelectronics corporate logo is a trademark of STMicroelectronics * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this list of conditions * and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other materials provided * with the distribution. * * - Neither the name nor trademarks of STMicroelectronics International N.V. nor any other * STMicroelectronics company nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * - All of the icons, pictures, logos and other images that are provided with the source code * in a directory whose title begins with st_images may only be used for internal purposes and * shall not be redistributed to any third party or modified in any way. * * - Any redistributions in binary form shall not include the capability to display any of the * icons, pictures, logos and other images that are provided with the source code in a directory * whose title begins with st_images. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. */ import Foundation import BlueSTSDK /// implementation of the fw read version for STM32WB Ota /// in this implementation we don't request any verison, just check if the node is valid and return a /// fixed version public class BlueNRGFwVersionConsole:BlueSTSDKFwReadVersionConsole{ private let boardInfoFeature:BlueNRGMemoryInfoFeature init?(node:BlueSTSDKNode){ if let f = node.getFeatureOfType(BlueNRGMemoryInfoFeature.self) as? BlueNRGMemoryInfoFeature{ boardInfoFeature = f }else{ return nil } }//init public func readFwVersion(onComplete:@escaping (BlueSTSDKFwVersion?)->())->Bool{ boardInfoFeature.add(BlueNRGFwVersionInfoDelegate(onComplete: onComplete)) boardInfoFeature.parentNode.read(boardInfoFeature) return true; } } fileprivate class BlueNRGFwVersionInfoDelegate : NSObject, BlueSTSDKFeatureDelegate { private static let DEFAULT_BOARD_NAME = "BLUENRG OTA"; private static let DEFAULT_MCU_NAME = "BLUENRG"; private let onComplete:(BlueSTSDKFwVersion?)->() fileprivate init(onComplete:@escaping (BlueSTSDKFwVersion?)->()){ self.onComplete = onComplete } func didUpdate(_ feature: BlueSTSDKFeature, sample: BlueSTSDKFeatureSample) { feature.remove(self) if let version = BlueNRGMemoryInfoFeature.getProtocolVersion(sample){ let fullVersion = BlueSTSDKFwVersion(name: BlueNRGFwVersionInfoDelegate.DEFAULT_BOARD_NAME, mcuType: BlueNRGFwVersionInfoDelegate.DEFAULT_MCU_NAME, major: version.major, minor: version.minor, patch: version.patch) onComplete(fullVersion) }else{ onComplete(nil) } } }
44.554348
114
0.723591
6904450678a4a538fc146e90a352644c15b84bf4
462
import XCTest @testable import utfunzombie final class UtfUnzombieTests: XCTestCase { func testUTFUnZombie() { var datafile = URL(fileURLWithPath: #file).deletingLastPathComponent() datafile.appendPathComponent("Testdata.txt") let string = convert(path: datafile) XCTAssertNotNil(string) XCTAssertEqual(string, "hinzufügen\n") } static var allTests = [ ("testExample", testUTFUnZombie), ] }
25.666667
78
0.67316
22bd8ca4c84e47257a1d499cc7aeab8b8cce3b15
8,228
// Douglas Hill, December 2019 import UIKit /// A navigation controller that supports using a hardware keyboard to navigate back using ⌘ + `[` or /// ⌘ + ← (mirrored for right-to-left layouts) and triggering the actions of the bar button items in /// the navigation bar and toolbar. /// /// Bar button items must be instances of `KeyboardBarButtonItem` to support keyboard equivalents, even /// for system items (because otherwise there is no way to know the system item after initialisation). /// /// From iOS 15, `UINavigationController` itself provides a ⌘ + `[` key command to go back, but /// the UIKit implementation doesn’t correctly handle nested navigation controllers which is common /// when `UISplitViewController` collapses. Therefore `KeyboardNavigationController` will remove /// this key command from the superclass and adds in its own commands. /// /// The concept for this class was originally developed for [PSPDFKit]( https://pspdfkit.com/ ). open class KeyboardNavigationController: UINavigationController { open override var canBecomeFirstResponder: Bool { true } /// A key command that enables users to go back. /// /// Title: Back /// /// Input: ⌘`[` (Users can also use ⌘←. Both of these inputs are mirrored in right-to-left layouts.) /// /// UIKit has this functionality on iOS 15, but KeyboardKit does this back to iOS 12. /// This API is only available from iOS 15 because using a single key command for this requires automatic /// mirroring, which was not available until iOS 15. However KeyboardKit provides this functionality back /// to iOS 12 using multiple internal key commands to implement mirroring. @available(iOS 15.0, *) public static let backKeyCommand = discoverableLeftToRightBackCommand private static let discoverableLeftToRightBackCommand = DiscoverableKeyCommand((.command, "["), action: #selector(kbd_handleCmdLeftBracket), title: localisedString(.navigation_back)) // Note that on iOS 14 and earlier the system will incorrectly show this in the discoverability HUD as a leftwards // pointing arrow. The discoverability HUD mirrors the arrow keys it displays when in a right-to-left layout, but // the inputs on the actual events received are not mirrored. This was reported as FB8963593 and resolved in iOS 15. // TODO: Update this comment since the discoverable one was switched to ] so maybe that doesn’t have the same problem. private static let discoverableRightToLeftBackCommand = UIKeyCommand((.command, "]"), action: #selector(kbd_handleCmdRightBracket), title: localisedString(.navigation_back)) private static let nonDiscoverableLeftToRightBackCommand = UIKeyCommand((.command, .leftArrow), action: #selector(kbd_goBackFromKeyCommand)) private static let nonDiscoverableRightToLeftBackCommand = UIKeyCommand((.command, .rightArrow), action: #selector(kbd_goBackFromKeyCommand)) private var shouldUseRightToLeftBackCommand: Bool { if #available(iOS 15.0, *) { // Handled by allowsAutomaticMirroring. return false } else { switch view.effectiveUserInterfaceLayoutDirection { case .rightToLeft: return true case .leftToRight: fallthrough @unknown default: return false } } } open override var keyCommands: [UIKeyCommand]? { var commands = super.keyCommands ?? [] if let topViewController = topViewController { let navigationItem = topViewController.navigationItem var additionalCommands: [UIKeyCommand] = [] // On iOS 15 and later, UIKit provides cmd-[ to go back in UINavigationController. // However as of iOS 15.0 beta 4 this has a bug seen in the KeyboardKit demo app table // view or list in compact widths where it pops all the way to the root (the sidebar // VC) instead of just popping one level. Additionally, the KeyboardKit command has a // localised title and the user can use either cmd-[ or cmd-left. Therefore filter // out the system provided command for going back and add our own instead. commands = commands.filter { systemCommand in (systemCommand.input == "[" && systemCommand.modifierFlags == .command) == false } // It’s useful to check canGoBack otherwise these commands can block rewind/fast-forward bar button items unnecessarily. // Although when using the menu builder we can’t do anything about that. if canGoBack { if shouldUseRightToLeftBackCommand { additionalCommands.append(Self.nonDiscoverableRightToLeftBackCommand) additionalCommands.append(Self.discoverableRightToLeftBackCommand) } else { additionalCommands.append(Self.nonDiscoverableLeftToRightBackCommand) if Self.discoverableLeftToRightBackCommand.shouldBeIncludedInResponderChainKeyCommands { additionalCommands.append(Self.discoverableLeftToRightBackCommand) } } } let keyCommandFromBarButtonItem: (UIBarButtonItem) -> UIKeyCommand? = { $0.isEnabled ? ($0 as? KeyboardBarButtonItem)?.keyCommand : nil } additionalCommands += navigationItem.nnLeadingBarButtonItems.compactMap(keyCommandFromBarButtonItem) additionalCommands += navigationItem.nnTrailingBarButtonItems.compactMap(keyCommandFromBarButtonItem).reversed() additionalCommands += topViewController.nnToolbarItems.compactMap(keyCommandFromBarButtonItem) if #available(iOS 15.0, *) { /* wantsPriorityOverSystemBehavior defaulting to false handles commands not overriding text input. */ } else if UIResponder.isTextInputActive { additionalCommands = additionalCommands.filter { $0.doesConflictWithTextInput == false } } commands += additionalCommands } return commands } open override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool { // The menu builder provides both the LtR and RtL commands, so block the wrong one. For this reason, the menu // builder support here can’t be used on Catalyst since it would show the available command as disabled. switch action { case #selector(kbd_goBackFromKeyCommand): return canGoBack case #selector(kbd_handleCmdLeftBracket): return shouldUseRightToLeftBackCommand ? false : canGoBack case #selector(kbd_handleCmdRightBracket): return shouldUseRightToLeftBackCommand ? canGoBack : false default: return super.canPerformAction(action, withSender: sender) } } private var canGoBack: Bool { viewControllers.count > 1 && presentedViewController == nil && navigationItem.hidesBackButton == false && (navigationItem.nnLeadingBarButtonItems.isEmpty || navigationItem.leftItemsSupplementBackButton) } @objc private func kbd_handleCmdLeftBracket(sender: UIKeyCommand) { self.kbd_goBackFromKeyCommand(sender) } @objc private func kbd_handleCmdRightBracket(sender: UIKeyCommand) { self.kbd_goBackFromKeyCommand(sender) } // Important to not put this on all UINavigationController instances via an extension because those // instances lack our override of canPerformAction so could allow the action incorrectly. @objc private func kbd_goBackFromKeyCommand(_ keyCommand: UIKeyCommand) { let allowsPop = navigationBar.delegate?.navigationBar?(navigationBar, shouldPop: topViewController!.navigationItem) ?? true guard allowsPop else { return } popViewController(animated: true) } } private extension UINavigationItem { var nnLeadingBarButtonItems: [UIBarButtonItem] { leftBarButtonItems ?? [] } var nnTrailingBarButtonItems: [UIBarButtonItem] { rightBarButtonItems ?? [] } } private extension UIViewController { var nnToolbarItems: [UIBarButtonItem] { toolbarItems ?? [] } }
53.777778
210
0.703573
ebdecf30bb4854e9483d00bb2599ffc3bc280adf
4,375
/** The outcome of running a test. */ public struct Outcome { /** Whether the test passed or failed. From the [TAP v13 specification](https://testanything.org/tap-version-13-specification.html): > #### • ok or not ok > > This tells whether the test point passed or failed. > It must be at the beginning of the line. > `/^not ok/` indicates a failed test point. > `/^ok/` is a successful test point. > This is the only mandatory part of the line. > Note that unlike the Directives below, > ok and not ok are case-sensitive. */ public let ok: Bool /** A description of the tested behavior. From the [TAP v13 specification](https://testanything.org/tap-version-13-specification.html): > #### • Description > > Any text after the test number but before a `#` > is the description of the test point. > > `ok 42 this is the description of the test` > > Descriptions should not begin with a digit > so that they are not confused with the test point number. > The harness may do whatever it wants with the description. */ public let description: String? /** A directive for how to interpret a test outcome. From the [TAP v13 specification](https://testanything.org/tap-version-13-specification.html): > #### • Directive > > The test point may include a directive, > following a hash on the test line. > There are currently two directives allowed: > `TODO` and `SKIP`. */ public let directive: Directive? /** Additional information about a test, such as its source location (file / line) or the actual and expected results. Test outcome metadata is encoded as [YAML](https://yaml.org). From the [TAP v13 specification](https://testanything.org/tap-version-13-specification.html): > ### YAML blocks > > If the test line is immediately followed by > an indented block beginning with `/^\s+---/` and ending with `/^\s+.../` > that block will be interpreted as an inline YAML document. > The YAML encodes a data structure that provides > more detailed information about the preceding test. > The YAML document is indented to make it > visually distinct from the surrounding test results > and to make it easier for the parser to recover > if the trailing ‘…’ terminator is missing. > For example: > > not ok 3 Resolve address > --- > message: "Failed with error 'hostname peebles.example.com not found'" > severity: fail > data: > got: > hostname: 'peebles.example.com' > address: ~ > expected: > hostname: 'peebles.example.com' > address: '85.193.201.85' > ... */ public let metadata: [String: Any]? /** Creates a successful test outcome. - Parameters: - description: A description of the tested behavior. `nil` by default. - directive: A directive for how to interpret a test outcome. `nil` by default. - metadata: Additional information about a test. `nil` by default. - Returns: A successful test outcome. */ public static func success(_ description: String? = nil, directive: Directive? = nil, metadata: [String: Any]? = nil) -> Outcome { return Outcome(ok: true, description: description, directive: directive, metadata: metadata) } /** Creates an unsuccessful test outcome. - Parameters: - description: A description of the tested behavior. `nil` by default. - directive: A directive for how to interpret a test outcome. `nil` by default. - metadata: Additional information about a test. `nil` by default. - Returns: An unsuccessful test outcome. */ public static func failure(_ description: String? = nil, directive: Directive? = nil, metadata: [String: Any]? = nil) -> Outcome { return Outcome(ok: false, description: description, directive: directive, metadata: metadata) } }
33.914729
101
0.5984
bb6717775a16477ba8e7a9d8bed50b9105a9ca1f
267
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing if true { struct c { { { } } protocol a { func a protocol a { func a typealias e : a } } var e: a
14.052632
87
0.70412
5d707b5a3bcb6ecdea07685dc00f57e085c3ef22
5,619
// // CompoundKeyPath.swift // CDG // // Copyright © 2021 LotusFlare. All rights reserved. // import Foundation public class CompoundKeyPath<Root>: ComparablePredicate { let compoundKeyPath: String let modifier: NSComparisonPredicate.Modifier let rootExpression: NSExpression let relationshipVariable: String public init< RootType, RelationshipType: Persistable, EquatableType: Equatable, CollectionType: Collection, RootKeyPathType: KeyPath<RootType, CollectionType>, ChildKeyPathType: KeyPath<RelationshipType, EquatableType>> (rootKeyPath: RootKeyPathType, relationshipKeyPath: ChildKeyPathType, modifier: NSComparisonPredicate.Modifier) where CollectionType.Element == RelationshipType { self.rootExpression = rootKeyPath.keyPathExpression self.relationshipVariable = rootKeyPath.keyPathExpression.keyPath self.compoundKeyPath = "$value.\(relationshipKeyPath.keyPathExpression.keyPath)" self.modifier = modifier } public init< RootType, RelationshipType: Persistable, EquatableType: Equatable, CollectionType: Collection, RootKeyPathType: KeyPath<RootType, CollectionType?>, ChildKeyPathType: KeyPath<RelationshipType, EquatableType>> (rootKeyPath: RootKeyPathType, relationshipKeyPath: ChildKeyPathType, modifier: NSComparisonPredicate.Modifier) where CollectionType.Element == RelationshipType { self.rootExpression = rootKeyPath.keyPathExpression self.relationshipVariable = rootKeyPath.keyPathExpression.keyPath self.compoundKeyPath = "$value.\(relationshipKeyPath.keyPathExpression.keyPath)" self.modifier = modifier } public init< RootType, RelationshipType: Persistable, EquatableType: Equatable, RootKeyPathType: KeyPath<RootType, NSOrderedSet>, ChildKeyPathType: KeyPath<RelationshipType, EquatableType>> (rootKeyPath: RootKeyPathType, relationshipKeyPath: ChildKeyPathType, modifier: NSComparisonPredicate.Modifier) { self.rootExpression = rootKeyPath.keyPathExpression self.relationshipVariable = rootKeyPath.keyPathExpression.keyPath self.compoundKeyPath = "$value.\(relationshipKeyPath.keyPathExpression.keyPath)" self.modifier = modifier } public func predicate(op: NSComparisonPredicate.Operator, value: Any?) -> ComparisonPredicate<Root> { var countExpression = NSExpression(forConstantValue: 0) var operatorType: NSComparisonPredicate.Operator = .greaterThan if modifier == .all { countExpression = NSExpression(forKeyPath: "\(relationshipVariable).@count") operatorType = .equalTo } return ComparisonPredicate<Root>(leftExpression: count(NSExpression(forSubquery: rootExpression, usingIteratorVariable: "value", predicate: ComparisonPredicate<Root>(leftExpression: NSExpression(forKeyPath: compoundKeyPath), rightExpression: NSExpression(forConstantValue: value), modifier: .direct, type: op))), rightExpression: countExpression, modifier: .direct, type: operatorType, options: []) } func count(_ expression: NSExpression) -> NSExpression { return NSExpression(forFunction: "count:", arguments: [expression]) } } public func all< RootType, RelationshipType: Persistable, EquatableType: Equatable, CollectionType: Collection, RootKeyPathType: KeyPath<RootType, CollectionType?>, ChildKeyPathType: KeyPath<RelationshipType, EquatableType>>(_ rootKeyPath: RootKeyPathType, _ relationshipKeyPath: ChildKeyPathType) -> CompoundKeyPath<RootType> where CollectionType.Element == RelationshipType { return CompoundKeyPath(rootKeyPath: rootKeyPath, relationshipKeyPath: relationshipKeyPath, modifier: .all) } public func all< RootType, RelationshipType: Persistable, EquatableType: Equatable, RootKeyPathType: KeyPath<RootType, NSOrderedSet>, ChildKeyPathType: KeyPath<RelationshipType, EquatableType>>(_ rootKeyPath: RootKeyPathType, _ relationshipKeyPath: ChildKeyPathType) -> CompoundKeyPath<RootType> { return CompoundKeyPath(rootKeyPath: rootKeyPath, relationshipKeyPath: relationshipKeyPath, modifier: .all) } public func any< RootType, RelationshipType: Persistable, EquatableType: Equatable, CollectionType: Collection, RootKeyPathType: KeyPath<RootType, CollectionType?>, ChildKeyPathType: KeyPath<RelationshipType, EquatableType>>(_ rootKeyPath: RootKeyPathType, _ relationshipKeyPath: ChildKeyPathType) -> CompoundKeyPath<RootType> where CollectionType.Element == RelationshipType { return CompoundKeyPath(rootKeyPath: rootKeyPath, relationshipKeyPath: relationshipKeyPath, modifier: .any) } public func any< RootType, RelationshipType: Persistable, EquatableType: Equatable, RootKeyPathType: KeyPath<RootType, NSOrderedSet>, ChildKeyPathType: KeyPath<RelationshipType, EquatableType>>(_ rootKeyPath: RootKeyPathType, _ relationshipKeyPath: ChildKeyPathType) -> CompoundKeyPath<RootType> { return CompoundKeyPath(rootKeyPath: rootKeyPath, relationshipKeyPath: relationshipKeyPath, modifier: .any) }
52.514019
171
0.70226
892fbf978733d17d3ce1dba85dfefd6f973b791f
3,354
import Foundation import XCTest @testable import MaskInterpreter public class TokenParserTests: XCTestCase { public func testQIWIMasksParsing() { // Arrange guard let url = Bundle(for: type(of: self)).url(forResource: "all_qiwi_masks", withExtension: "txt") else { XCTFail("Cant load all_qiwi_masks.txt") return } guard let string = try? String(contentsOf: url) else { XCTFail("Cant read all_qiwi_masks.txt") return } let parser = TokenParser() let regexps = string.split(separator: "\n").map { String($0).replacingOccurrences(of: "\\\\", with: "\\") } // Act var results = [String: [Token]?]() let values = regexps.compactMap { item -> [Token]? in guard let tokens = try? parser.parse(from: CharStream(string: item)) else { results[item] = nil return nil } results[item] = tokens return tokens } // Assert XCTAssertEqual(regexps.count, values.count) for index in 0..<regexps.count { let value = values[index] XCTAssertEqual(regexps[index], value.reduce(into: "", { $0 += $1.rawView }) ) } } /// Проверяет что размеченые маски парсятся public func testMarkedQIWIMasksParsed() { // Arrange guard let url = Bundle(for: type(of: self)).url(forResource: "marked_qiwi_masks", withExtension: "txt") else { XCTFail("Cant load marked_qiwi_masks.txt") return } guard let string = try? String(contentsOf: url) else { XCTFail("Cant read marked_qiwi_masks.txt") return } let parser = TokenParser() let lines = string.split(separator: "\n").map { String($0).replacingOccurrences(of: "\\\\", with: "\\") } let regexps = lines.reduce(into: [String]()) { ( lhs: inout [String], rhs: String) in let rhs = rhs.split(separator: "@").map { String($0) } lhs.append(rhs[0]) } let marks = lines.reduce(into: [String]()) { ( lhs: inout [String], rhs: String) in let rhs = rhs.split(separator: "@").map { String($0) } lhs.append(rhs[1]) } // Act var results = [String: [Token]?]() let values = regexps.compactMap { item -> [Token]? in guard let tokens = try? parser.parse(from: CharStream(string: item)) else { results[item] = nil return nil } results[item] = tokens return tokens } // Assert XCTAssertEqual(regexps.count, values.count) for index in 0..<regexps.count { let value = values[index] XCTAssertEqual(marks[index], String(value.reduce(into: "", { $0 += $1.tokenIndex + " " }).dropLast()) ) } } /// Проверяет, что парсер упадет если нет мета символа public func testThatParserFailWithoutMeta() { // Arrange let regexp = "+<!^[0-9]> (<!^[0-9]+${3}>) <!^[0-9]+${3}>-<!^[0-9]+${2}>-<!^[0-9]+${2}>" let parser = TokenParser() // Act - Assert XCTAssertThrowsError(try parser.parse(from: CharStream(string: regexp))) } }
29.421053
118
0.537269
f9cbcb53b29c985a5eee3bc981faffda26c11ac1
2,084
// // AppDelegate.swift // CruxClimbing // // Created by Worth Baker on 8/28/15. // Copyright © 2015 Worth Baker. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
44.340426
281
0.776392
d9f0b1ebc48372cf1f1f86a074c058600e0d824f
4,893
// // CreateTransactionViewController.swift // AmartPhoto // // Created by Bryan Workman on 10/30/20. // import UIKit class CreateTransactionViewController: UIViewController { //MARK: - Outlets @IBOutlet weak var addressTextField: UITextField! @IBOutlet weak var cityTextField: UITextField! @IBOutlet weak var stateTextField: UITextField! @IBOutlet weak var zipcodeTextField: UITextField! @IBOutlet weak var sqftTextField: UITextField! @IBOutlet weak var vacantSegmentedControl: UISegmentedControl! @IBOutlet weak var phoneNumberTextField: UITextField! @IBOutlet weak var preferredDateDatePicker: UIDatePicker! @IBOutlet weak var preferredDateTimeSegmentedControl: UISegmentedControl! @IBOutlet weak var secondaryDateDatePicker: UIDatePicker! @IBOutlet weak var secondaryDateTimeSegmentedControl: UISegmentedControl! @IBOutlet weak var continueButton: UIButton! //MARK: - Properties var isVacant = false var preferredTime: Transaction.TimeOfDay = .morning var secondaryTime: Transaction.TimeOfDay = .morning //MARK: - Lifecycles override func viewDidLoad() { super.viewDidLoad() setUpView() } //MARK: - Actions @IBAction func continueButtonTapped(_ sender: Any) { } @IBAction func vacantSegmentedControlChanged(_ sender: Any) { switch vacantSegmentedControl.selectedSegmentIndex { case 1: isVacant = true default: isVacant = false } } @IBAction func preferredDateSegmentedControlChanged(_ sender: Any) { switch preferredDateTimeSegmentedControl.selectedSegmentIndex { case 1: preferredTime = .afternoon case 2: preferredTime = .any default: preferredTime = .morning } } @IBAction func secondaryDateSegmentedControlChanged(_ sender: Any) { switch secondaryDateTimeSegmentedControl.selectedSegmentIndex { case 1: secondaryTime = .afternoon case 2: secondaryTime = .any default: secondaryTime = .morning } } //MARK: - Helper Methods func setUpView() { let tap = UITapGestureRecognizer(target: self.view, action: #selector(UIView.endEditing)) view.addGestureRecognizer(tap) NotificationCenter.default.addObserver(self, selector: #selector(CreateTransactionContinuedViewController.keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(CreateTransactionContinuedViewController.keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil) } @objc func keyboardWillShow(notification: NSNotification) { guard let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else {return} if phoneNumberTextField.isEditing { self.view.frame.origin.y = 0 - keyboardSize.height + 50 } else if sqftTextField.isEditing { self.view.frame.origin.y = 0 - 50 } } @objc func keyboardWillHide(notification: NSNotification) { self.view.frame.origin.y = 0 } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "CreateToCreate2" { guard let destination = segue.destination as? CreateTransactionContinuedViewController else {return} guard let address = addressTextField.text, !address.isEmpty else {return} guard let city = cityTextField.text, !city.isEmpty else {return} guard let state = stateTextField.text, !state.isEmpty else {return} guard let zipcode = zipcodeTextField.text, !zipcode.isEmpty else {return} guard let sqft = sqftTextField.text, !sqft.isEmpty else {return} guard let phoneNumber = phoneNumberTextField.text, !phoneNumber.isEmpty else {return} let homeIsVacant = self.isVacant let dateOne = preferredDateDatePicker.date.dateAsString() let timeOne = self.preferredTime let dateTwo = secondaryDateDatePicker.date.dateAsString() let timeTwo = self.secondaryTime destination.address = address destination.city = city destination.state = state destination.zipcode = zipcode destination.sqft = sqft destination.phoneNumber = phoneNumber destination.homeIsVacant = homeIsVacant destination.dateOne = dateOne destination.timeOne = timeOne destination.dateTwo = dateTwo destination.timeTwo = timeTwo } } } //End of class
38.833333
193
0.669324
fbc005ce3d8ab48c4622a71ee947632a1fa50716
1,027
// // SMBusExample.swift // GPIOSwiftyBlaster // // Created by Claudio Carnino on 05/08/2016. // Copyright © 2016 Tugulab. All rights reserved. // import Foundation // Open the bus guard let bus = try? SMBus(busNumber: 1) else { fatalError("It has not been possible to open the I2C bus") } for i in 0...10 { // Blink the led few times (high/medium brightness) try! bus.writeByteData(address: 0x40, command: 0x06, value: 0x00) try! bus.writeByteData(address: 0x40, command: 0x07, value: 0x00) try! bus.writeByteData(address: 0x40, command: 0x08, value: (i % 2 == 0) ? 0xff : 0x99) try! bus.writeByteData(address: 0x40, command: 0x09, value: (i % 2 == 0) ? 0x0f : 0x00) Thread.sleepForTimeInterval(1) } // Turn off the led try! bus.writeByteData(address: 0x40, command: 0x06, value: 0x00) try! bus.writeByteData(address: 0x40, command: 0x07, value: 0x00) try! bus.writeByteData(address: 0x40, command: 0x08, value: 0x00) try! bus.writeByteData(address: 0x40, command: 0x09, value: 0x00)
32.09375
91
0.691334
5d39fafc1a9f7dfc9a0d34e95aa3ba2f6bdbdb24
1,353
/** * Copyright IBM Corporation 2018 * * 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 /** DocumentAccepted. */ public struct DocumentAccepted: Decodable { /// Status of the document in the ingestion process. public enum Status: String { case processing = "processing" } /// The unique identifier of the ingested document. public var documentID: String? /// Status of the document in the ingestion process. public var status: String? /// Array of notices produced by the document-ingestion process. public var notices: [Notice]? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case documentID = "document_id" case status = "status" case notices = "notices" } }
30.75
82
0.704361
ccd1db2a3b7a684c947b02e9321bd6430187fdd6
508
// // Copyright Amazon.com Inc. or its affiliates. // All Rights Reserved. // // SPDX-License-Identifier: Apache-2.0 // /// API Category public protocol APICategory: Category, APICategoryBehavior { /// Add a plugin to the API category /// /// - Parameter plugin: API plugin object func add(plugin: APICategoryPlugin) throws /// Retrieve an API plugin /// - Parameter key: the key which is defined in the plugin. func getPlugin(for key: PluginKey) throws -> APICategoryPlugin }
25.4
66
0.688976
e92451a5020351da12d6b10162bc8e9f84144c2f
1,102
// // Extension.swift // CustomNavigationBar // // Created by Ravi Vora on 24/08/16. // Copyright © 2016 Ravi Vora. All rights reserved. // import Foundation import UIKit extension UIImage { func maskWithColor(color: UIColor) -> UIImage? { let maskImage = cgImage! let width = size.width let height = size.height let bounds = CGRect(x: 0, y: 0, width: width, height: height) let colorSpace = CGColorSpaceCreateDeviceRGB() let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue) let context = CGContext(data: nil, width: Int(width), height: Int(height), bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: bitmapInfo.rawValue)! context.clip(to: bounds, mask: maskImage) context.setFillColor(color.cgColor) context.fill(bounds) if let cgImage = context.makeImage() { let coloredImage = UIImage(cgImage: cgImage) return coloredImage } else { return nil } } }
28.25641
172
0.622505
ddabd276c7072b6d520c7fd9beacf14f7de43875
3,830
// // JCMineInfoCell.swift // JChat // // Created by JIGUANG on 2017/3/28. // Copyright © 2017年 HXHG. All rights reserved. // import UIKit @objc public protocol JCMineInfoCellDelegate: NSObjectProtocol { @objc optional func mineInfoCell(clickSwitchButton button: UISwitch, indexPath: IndexPath?) } class JCMineInfoCell: JCTableViewCell { open weak var delegate: JCMineInfoCellDelegate? var indexPate: IndexPath? var title: String { get { return titleLabel.text ?? "" } set { return titleLabel.text = newValue } } var detail: String? { get { return detailLabel.text } set { detailLabel.isHidden = false detailLabel.text = newValue } } var isShowSwitch: Bool { get { return !switchButton.isHidden } set { switchButton.isHidden = !newValue } } var isSwitchOn: Bool { get { return switchButton.isOn } set { switchButton.isOn = newValue } } override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) _init() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) _init() } override func awakeFromNib() { super.awakeFromNib() _init() } private lazy var titleLabel: UILabel = { let titleLabel = UILabel() titleLabel.textAlignment = .left titleLabel.font = UIFont.systemFont(ofSize: 16) titleLabel.backgroundColor = .white titleLabel.layer.masksToBounds = true return titleLabel }() private lazy var switchButton: UISwitch = { let switchButton = UISwitch() switchButton.isHidden = true switchButton.addTarget(self, action: #selector(clickSwitch(_:)), for: .valueChanged) return switchButton }() private lazy var detailLabel: UILabel = { let detailLabel = UILabel() detailLabel.textAlignment = .right detailLabel.font = UIFont.systemFont(ofSize: 14) detailLabel.isHidden = true detailLabel.textColor = UIColor(netHex: 0x999999) detailLabel.backgroundColor = .white detailLabel.layer.masksToBounds = true return detailLabel }() //MARK: - private func private func _init() { contentView.addSubview(switchButton) contentView.addSubview(titleLabel) contentView.addSubview(detailLabel) addConstraint(_JCLayoutConstraintMake(titleLabel, .left, .equal, contentView, .left, 15)) addConstraint(_JCLayoutConstraintMake(titleLabel, .right, .equal, contentView, .centerX)) addConstraint(_JCLayoutConstraintMake(titleLabel, .centerY, .equal, contentView, .centerY)) addConstraint(_JCLayoutConstraintMake(titleLabel, .height, .equal, nil, .notAnAttribute, 22.5)) addConstraint(_JCLayoutConstraintMake(detailLabel, .centerY, .equal, contentView, .centerY)) addConstraint(_JCLayoutConstraintMake(detailLabel, .left, .equal, titleLabel, .right)) addConstraint(_JCLayoutConstraintMake(detailLabel, .right, .equal, contentView, .right)) addConstraint(_JCLayoutConstraintMake(detailLabel, .height, .equal, contentView, .height)) addConstraint(_JCLayoutConstraintMake(switchButton, .right, .equal, contentView, .right, -15)) addConstraint(_JCLayoutConstraintMake(switchButton, .centerY, .equal, contentView, .centerY)) } @objc func clickSwitch(_ sender: UISwitch) { delegate?.mineInfoCell?(clickSwitchButton: sender, indexPath: indexPate) } }
31.393443
103
0.638642
d7898c9009f847a6be974c1d5e14bdb1c43ce1c7
6,881
import Foundation import MapKit import WMF struct PlaceSearchResult { let locationResults: [MWKSearchResult]? let fetchRequest: NSFetchRequest<WMFArticle>? let error: Error? init(locationResults: [MWKSearchResult]?, fetchRequest: NSFetchRequest<WMFArticle>?) { self.locationResults = locationResults self.fetchRequest = fetchRequest self.error = nil } init(error: Error?) { // TODO: make non-optional? self.locationResults = nil self.fetchRequest = nil self.error = error } } class PlaceSearchService { public let dataStore: MWKDataStore private let locationSearchFetcher = WMFLocationSearchFetcher() private let wikidataFetcher: WikidataFetcher init(dataStore: MWKDataStore) { self.dataStore = dataStore self.wikidataFetcher = WikidataFetcher(session: dataStore.session, configuration: dataStore.configuration) } var fetchRequestForSavedArticlesWithLocation: NSFetchRequest<WMFArticle> { get { let savedRequest = WMFArticle.fetchRequest() savedRequest.predicate = NSPredicate(format: "savedDate != NULL && signedQuadKey != NULL") return savedRequest } } var fetchRequestForSavedArticles: NSFetchRequest<WMFArticle> { get { let savedRequest = WMFArticle.fetchRequest() savedRequest.predicate = NSPredicate(format: "savedDate != NULL") return savedRequest } } public func performSearch(_ search: PlaceSearch, defaultSiteURL: URL, region: MKCoordinateRegion, completion: @escaping (PlaceSearchResult) -> Void) { var result: PlaceSearchResult? let siteURL = search.siteURL ?? defaultSiteURL var searchTerm: String? = nil let sortStyle = search.sortStyle let done = { let completionResult: PlaceSearchResult if var actualResult = result { if let searchResult = search.searchResult { var foundResult = false var locationResults = actualResult.locationResults ?? [] for result in locationResults { if result.articleID == searchResult.articleID { foundResult = true break } } if !foundResult { locationResults.append(searchResult) actualResult = PlaceSearchResult(locationResults: locationResults, fetchRequest: actualResult.fetchRequest) } } completionResult = actualResult } else { completionResult = PlaceSearchResult(error: nil) } DispatchQueue.main.async { completion(completionResult) } } searchTerm = search.string switch search.filter { case .saved: self.fetchSavedArticles(searchString: search.string, completion: { (request) in result = PlaceSearchResult(locationResults: nil, fetchRequest: request) done() }) case .top: let center = region.center let halfLatitudeDelta = region.span.latitudeDelta * 0.5 let halfLongitudeDelta = region.span.longitudeDelta * 0.5 let top = CLLocation(latitude: center.latitude + halfLatitudeDelta, longitude: center.longitude) let bottom = CLLocation(latitude: center.latitude - halfLatitudeDelta, longitude: center.longitude) let left = CLLocation(latitude: center.latitude, longitude: center.longitude - halfLongitudeDelta) let right = CLLocation(latitude: center.latitude, longitude: center.longitude + halfLongitudeDelta) let height = top.distance(from: bottom) let width = right.distance(from: left) let radius = round(0.5*max(width, height)) let searchRegion = CLCircularRegion(center: center, radius: radius, identifier: "") locationSearchFetcher.fetchArticles(withSiteURL: siteURL, in: searchRegion, matchingSearchTerm: searchTerm, sortStyle: sortStyle, resultLimit: 50, completion: { (searchResults) in result = PlaceSearchResult(locationResults: searchResults.results, fetchRequest: nil) done() }) { (error) in result = PlaceSearchResult(error: error) done() } } } public func fetchSavedArticles(searchString: String?, completion: @escaping (NSFetchRequest<WMFArticle>?) -> () = {_ in }) { let moc = dataStore.viewContext let done = { let request = WMFArticle.fetchRequest() let basePredicate = NSPredicate(format: "savedDate != NULL && signedQuadKey != NULL") request.predicate = basePredicate if let searchString = searchString { let searchPredicate = NSPredicate(format: "(displayTitle CONTAINS[cd] '\(searchString)') OR (snippet CONTAINS[cd] '\(searchString)')") request.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [basePredicate, searchPredicate]) } request.sortDescriptors = [NSSortDescriptor(keyPath: \WMFArticle.savedDate, ascending: false)] completion(request) } do { let savedPagesWithLocation = try moc.fetch(fetchRequestForSavedArticlesWithLocation) guard savedPagesWithLocation.count >= 99 else { let savedPagesWithoutLocationRequest = WMFArticle.fetchRequest() savedPagesWithoutLocationRequest.predicate = NSPredicate(format: "savedDate != NULL && signedQuadKey == NULL") savedPagesWithoutLocationRequest.sortDescriptors = [NSSortDescriptor(keyPath: \WMFArticle.savedDate, ascending: false)] let savedPagesWithoutLocation = try moc.fetch(savedPagesWithoutLocationRequest) guard !savedPagesWithoutLocation.isEmpty else { done() return } let keys = savedPagesWithoutLocation.compactMap({ (article) -> String? in return article.key }) // Fetch summaries from the server and update WMFArticle objects dataStore.articleSummaryController.updateOrCreateArticleSummariesForArticles(withKeys: keys) { (articles, _) in done() } return } } catch let error { DDLogError("Error fetching saved articles: \(error.localizedDescription)") } done() } }
43.828025
191
0.606453
2974eafe0e8ef41cde23d0c0a706f65e06a1abd6
335
// // Print+Extension.swift // VoxeetUXKit // // Created by Corentin Larroque on 03/07/2017. // Copyright © 2017 Voxeet. All rights reserved. // func print(_ items: Any..., separator: String = " ", terminator: String = "\n") { #if DEBUG Swift.print(items[0], separator: separator, terminator: terminator) #endif }
23.928571
81
0.647761
6a937448c832024c2f1411f5d07a185db21a0243
2,276
// // UILabelX.swift // Pods-ViewDesignableHelpers_Tests // // Created by Sami Ali on 11/19/18. // import Foundation import UIKit @IBDesignable public class UILabelX: UILabel { required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! dynamicFontSize() } override init(frame: CGRect) { super.init(frame: frame) dynamicFontSize() } func dynamicFontSize() { let font = self.font self.font = getScaledFont(for: font) self.adjustsFontForContentSizeCategory = true } func getScaledFont(for font: UIFont?) -> UIFont { guard let customFont = font else { return UIFont.systemFont(ofSize: 17) } if #available(iOS 11.0, *) { return UIFontMetrics.default.scaledFont(for: customFont) } else { return customFont.withSize(customFont.pointSize) } } @IBInspectable public var cornerRadius: CGFloat = 0 { didSet { self.layer.cornerRadius = cornerRadius } } @IBInspectable public var borderWidth: CGFloat = 0.0 { didSet { self.layer.borderWidth = borderWidth } } @IBInspectable public var borderColor: UIColor = UIColor.clear { didSet { self.layer.borderColor = borderColor.cgColor } } @IBInspectable public var rotationAngle: CGFloat = 0 { didSet { self.transform = CGAffineTransform(rotationAngle: rotationAngle * .pi / 180) } } // MARK: - Shadow Text Properties @IBInspectable public var shadowOpacity: CGFloat = 0 { didSet { layer.shadowOpacity = Float(shadowOpacity) } } @IBInspectable public var shadowColorLayer: UIColor = UIColor.clear { didSet { layer.shadowColor = shadowColorLayer.cgColor } } @IBInspectable public var shadowRadius: CGFloat = 0 { didSet { layer.shadowRadius = shadowRadius } } @IBInspectable public var shadowOffsetLayer: CGSize = CGSize(width: 0, height: 0) { didSet { layer.shadowOffset = shadowOffsetLayer } } }
24.473118
88
0.582162
dd42739fa098e072dee07cf563a14cf8de508057
1,143
class BoxInt { let value: Int init(value: Int) { self.value = value } } public struct ChangeSize { public init(value: Int) { #if BEFORE _value = BoxInt(value: value) #else _value1 = Int64(value) _value2 = Int64(value) #endif } public var value: Int { #if BEFORE return _value.value #else precondition(_value1 == _value2, "state corrupted") return Int(_value1) #endif } #if BEFORE private let _value: BoxInt #else private let _value1: Int64 private let _value2: Int64 #endif } @_fixed_layout public enum SingletonEnum { case X(ChangeSize) } public func getSingletonEnumValues(_ c: ChangeSize) -> [SingletonEnum?] { return [.X(c), nil] } @_fixed_layout public enum SinglePayloadEnum { case X(ChangeSize) case Y case Z } public func getSinglePayloadEnumValues(_ c: ChangeSize) -> [SinglePayloadEnum?] { return [.X(c), .Y, .Z, nil] } @_fixed_layout public enum MultiPayloadEnum { case X(ChangeSize) case Y(ChangeSize) case Z } public func getMultiPayloadEnumValues(_ c: ChangeSize, _ d: ChangeSize) -> [MultiPayloadEnum?] { return [.X(c), .Y(d), .Z, nil] }
17.318182
71
0.678915
7a4ba4f8ada09f88cd028a4d2b14d8e3c2cfa2e6
477
// // Color+Ext.Swift // MacTemplet // // Created by Bin Shang on 2021/05/26 14:30 // Copyright © 2021 Bin Shang. All rights reserved. // import UIKit import Foundation @objc public extension UIColor{ convenience init(light: UIColor, dark: UIColor) { if #available(iOS 13.0, tvOS 13.0, *) { self.init(dynamicProvider: { $0.userInterfaceStyle == .dark ? dark : light }) } else { self.init(cgColor: light.cgColor) } } }
21.681818
89
0.614256
38132621b30943155970081b7342f41b9b0218fa
1,810
// // ChannelsCollectionViewCell.swift // Test // // Created by bayareahank on 12/13/21. // import UIKit // import Kingfisher class ChannelsCollectionViewCell: UICollectionViewCell { static let cellId = "channelsCVCell" @IBOutlet var channelImageView: UIImageView! @IBOutlet var channelLabel: UILabel! func configure(_ channel: Channel) { // print ("ChannelsCell.configure \(channel)") channelLabel.text = channel.name let trueUrlName = "https://mobile-interview.s3.amazonaws.com/" + channel.imageUrl guard let url = URL(string: trueUrlName) else { return } downloadImage(from: url) /* channelImageView.kf.setImage(with: url) { result in switch result { case .success(let value): print("Task done for: \(value.source.url?.absoluteString ?? "")") case .failure(let error): print("Job failed: \(error.localizedDescription)") } } */ } func getData(from url: URL, completion: @escaping (Data?, URLResponse?, Error?) -> ()) { URLSession.shared.dataTask(with: url, completionHandler: completion).resume() } func downloadImage(from url: URL) { print("Download Started") getData(from: url) { data, response, error in guard let data = data, error == nil else { return } print(response?.suggestedFilename ?? url.lastPathComponent) print("Download Finished") // always update the UI from the main thread DispatchQueue.main.async() { [weak self] in self?.channelImageView.image = UIImage(data: data) } } } }
30.166667
92
0.573481
910c5800b2405b87b75656b3bdd78098a2d1e4c8
989
// // ViewController+UIImagePickerControllerDelegate.swift // HY_Image_uploading // // Created by sushmit yadav on 12/6/18. // Copyright © 2018 sushmit yadav. All rights reserved. // import UIKit extension ViewController : UIImagePickerControllerDelegate,UINavigationControllerDelegate { func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { // Local variable inserted by Swift 4.2 migrator. var selectedImage: UIImage? if let editedImage = info[.editedImage] as? UIImage { selectedImage = editedImage self.hy_imgView.image = selectedImage! picker.dismiss(animated: true, completion: nil) } else if let originalImage = info[.originalImage] as? UIImage { selectedImage = originalImage self.hy_imgView.image = selectedImage! picker.dismiss(animated: true, completion: nil) } } }
39.56
144
0.700708
5bd2c991c1a5adf6ebdbe464de452c14107dcbe6
277
// // Bike.swift // bicicletasSeguras // // Created by Carlos Obregón on 7/8/20. // Copyright © 2020 Carlos Obregón. All rights reserved. // import Foundation struct Bike { let idBike: String let idSecure: String let brandmark: String var color: String }
16.294118
57
0.67509
4b0299946700a55695f38d7bce778701dee07eff
4,800
// // OxygenSaturationConversionTests.swift // HealthKitToFhir_Tests // // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. import Foundation import Foundation import Quick import Nimble import HealthKit import FHIR class OxygenSaturationConversionSpec : QuickSpec { override func spec() { describe("an oxygen saturation sample conversion") { context("the output FHIR Observation") { let expectedDate = Date.init(timeIntervalSince1970: 0) let sample = HKQuantitySample.init(type: HKQuantityType.quantityType(forIdentifier: .oxygenSaturation)!, quantity: HKQuantity(unit: HKUnit(from: "%"), doubleValue: 98), start: expectedDate, end: expectedDate) let expectedCoding1 = Coding() expectedCoding1.code = FHIRString("2708-6") expectedCoding1.display = FHIRString("Oxygen saturation in Arterial blood") expectedCoding1.system = FHIRURL("http://loinc.org") let expectedCoding2 = Coding() expectedCoding2.code = FHIRString("59408-5") expectedCoding2.display = FHIRString("Oxygen saturation in Arterial blood by Pulse oximetry") expectedCoding2.system = FHIRURL("http://loinc.org") let expectedCoding3 = Coding() expectedCoding3.code = FHIRString("HKQuantityTypeIdentifierOxygenSaturation") expectedCoding3.display = FHIRString("Oxygen saturation in Arterial blood by Pulse oximetry") expectedCoding3.system = FHIRURL("com.apple.health") let expectedIdentifier = Identifier() expectedIdentifier.system = FHIRURL("com.apple.health") expectedIdentifier.value = FHIRString(sample.uuid.uuidString) context("when using the default config") { let observationFactory = try? ObservationFactory() let observation = try! observationFactory!.observation(from: sample) itBehavesLike("observation resource") { ["observation" : observation, "codings" : [expectedCoding1, expectedCoding2, expectedCoding3], "effectiveDateTime" : expectedDate, "identifers" : [expectedIdentifier]] } it("includes the expected value") { if let value = observation.valueQuantity{ expect(value.value) == 98 expect(value.code) == "%" expect(value.unit) == "%" expect(value.system?.absoluteString) == "http://unitsofmeasure.org" } else { fail() } } context("when calling the generic resource method") { let observation: Observation = try! observationFactory!.resource(from: sample) itBehavesLike("observation resource") { ["observation" : observation, "codings" : [expectedCoding1, expectedCoding2, expectedCoding3], "effectiveDateTime" : expectedDate, "identifers" : [expectedIdentifier]] } it("includes the expected value") { if let value = observation.valueQuantity{ expect(value.value) == 98 expect(value.code) == "%" expect(value.unit) == "%" expect(value.system?.absoluteString) == "http://unitsofmeasure.org" } else { fail() } } context("The incorrect type is used") { it("throws an error") { expect { let _: Device? = try observationFactory?.resource(from: sample) }.to(throwError(ConversionError.incorrectTypeForFactory)) } } } } } } } }
50.526316
224
0.471458
5d074783c940e154aacc0340b0ec66d30f64fa8f
408
// // ZAssert.swift // EosioSwift // // Created by Steve McCoole on 1/30/19. // Copyright (c) 2017-2019 block.one and its contributors. All rights reserved. // import Foundation func ZAssert(_ test: Bool, message: String) { if test { return } #if DEBUG print(message) let exception = NSException() exception.raise() #else NSLog(message) return #endif }
16.32
80
0.625
29a48c9638ecca015322d135a6a7a1ad70e80d0d
5,788
// // Copyright 2021 Guillaume Algis. // Licensed under the MIT License. See the LICENSE.md file in the project root for more information. // import Foundation /// A struct representing a "semantic versioning" version number. /// /// While this struct tries to follow the [SemVer 2.0.0](https://semver.org) as close as possible, it takes some /// liberties for simplicity and convenience sake: /// - String version numbers omitting a "patch" component are accepted, and their `patch` component defaults to `0`. /// - "Pre-release" version numbers (with an hyphen after the patch component) are currently not supported. public struct Version: Codable, Comparable, LosslessStringConvertible { /// The major version number of the release. Incremented when making incompatible API changes. let major: Int /// The minor version number of the release. Incremented when adding functionality in a backwards-compatible /// manner. let minor: Int /// The patch version number of the release. Incremented when making backwards-compatible bug fixes. let patch: Int /// A textual representation of this version number. public var description: String { "\(major).\(minor).\(patch)" } // MARK: - Memberwise initializer /// Memberwise initializer. public init(major: Int, minor: Int, patch: Int) { self.major = major self.minor = minor self.patch = patch } // MARK: - LosslessStringConvertible /// Instantiates a version number from a string representation. /// /// The string will be parsed and the expected formats are either: /// - "MAJOR.MINOR", or /// - "MAJOR.MINOR.PATCH" /// /// In the first case, the patch component of the version will default to `0`. /// /// If the parsed string is not in a valid format, the initializer will fail and return `nil`. /// /// - Parameter value: The formatted version number. public init?(_ description: String) { guard let (major, minor, patch) = Version.parseSemVerString(description) else { return nil } self.major = major self.minor = minor self.patch = patch } // MARK: - Decodable /// Creates a new instance by decoding from the given decoder. /// /// This initializer throws an error if reading from the decoder fails, or if the data if not in the expected /// version number format. /// /// - Parameter decoder: The decoder to read data from. /// /// - SeeAlso: `init(string:)`. public init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() let value = try container.decode(String.self) guard let (major, minor, patch) = Version.parseSemVerString(value) else { throw DecodingError.dataCorruptedError(in: container, debugDescription: "Invalid SemVer format") } self.major = major self.minor = minor self.patch = patch } // MARK: - Comparable /// Returns a Boolean value indicating whether the value of the first argument is less than that of the second /// argument. /// /// A version number is considered less than another version number if any of its components, starting from `major` /// and ending with `patch`, is less than same component of the other version number. /// /// - Parameters: /// - lhs: A value to compare. /// - rhs: Another value to compare. public static func < (lhs: Version, rhs: Version) -> Bool { if lhs.major != rhs.major { return lhs.major < rhs.major } else if lhs.minor != rhs.minor { return lhs.minor < rhs.minor } return lhs.patch < rhs.patch } // MARK: - Equatable /// Returns a Boolean value indicating whether two version numbers are equal. /// /// Two version numbers are equal if all their components are equal. /// /// - Parameters: /// - lhs: A value to compare. /// - rhs: Another value to compare. public static func == (lhs: Version, rhs: Version) -> Bool { return lhs.major == rhs.major && lhs.minor == rhs.minor && lhs.patch == rhs.patch } // MARK: - Version Parsing // swiftlint:disable:next large_tuple private static func parseSemVerString(_ value: String) -> (Int, Int, Int)? { let bits = value.split(separator: ".", omittingEmptySubsequences: false) guard bits.count == 2 || bits.count == 3 else { return nil } guard let major = parseSemVerSubstring(bits[0]) else { return nil } guard let minor = parseSemVerSubstring(bits[1]) else { return nil } let patch: Int if bits.count == 3 { guard let value = parseSemVerSubstring(bits[2]) else { return nil } patch = value } else { patch = 0 } return (major, minor, patch) } private static func parseSemVerSubstring(_ substring: String.SubSequence) -> Int? { let string = String(substring) guard let number = Int(string) else { return nil } return number } // MARK: - Encodable /// Encodes this value into the given encoder. /// /// If the value fails to encode anything, `encoder` will encode an empty keyed container in its place. /// /// This function throws an error if any values are invalid for the given encoder's format. /// /// - Parameter encoder: The encoder to write data to. public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(description) } }
35.728395
119
0.626641
ac0529eba23a86803d7af53c83b866bb5e31824f
4,912
// // ServiceCharacteristicProfileViewController.swift // BlueCap // // Created by Troy Stribling on 8/5/14. // Copyright (c) 2014 Troy Stribling. The MIT License (MIT). // import UIKit import CoreBluetooth import BlueCapKit class ServiceCharacteristicProfileViewController : UITableViewController { var characteristicProfile : CharacteristicProfile? @IBOutlet var uuidLabel : UILabel! @IBOutlet var permissionReadableLabel : UILabel! @IBOutlet var permissionWriteableLabel : UILabel! @IBOutlet var permissionReadEncryptionLabel : UILabel! @IBOutlet var permissionWriteEncryptionLabel : UILabel! @IBOutlet var propertyBroadcastLabel : UILabel! @IBOutlet var propertyReadLabel : UILabel! @IBOutlet var propertyWriteWithoutResponseLabel : UILabel! @IBOutlet var propertyWriteLabel : UILabel! @IBOutlet var propertyNotifyLabel : UILabel! @IBOutlet var propertyIndicateLabel : UILabel! @IBOutlet var propertyAuthenticatedSignedWritesLabel : UILabel! @IBOutlet var propertyExtendedPropertiesLabel : UILabel! @IBOutlet var propertyNotifyEncryptionRequiredLabel : UILabel! @IBOutlet var propertyIndicateEncryptionRequiredLabel : UILabel! struct MainStoryboard { static let serviceCharacteristicProfileValuesSegue = "ServiceCharacteristicProfileValues" } required init(coder aDecoder:NSCoder) { super.init(coder:aDecoder) } override func viewDidLoad() { super.viewDidLoad() if let characteristicProfile = self.characteristicProfile { self.navigationItem.title = characteristicProfile.name self.navigationItem.backBarButtonItem = UIBarButtonItem(title:"", style:.Plain, target:nil, action:nil) self.uuidLabel.text = characteristicProfile.uuid.UUIDString self.permissionReadableLabel.text = self.booleanStringValue(characteristicProfile.permissionEnabled(CBAttributePermissions.Readable)) self.permissionWriteableLabel.text = self.booleanStringValue(characteristicProfile.permissionEnabled(CBAttributePermissions.Writeable)) self.permissionReadEncryptionLabel.text = self.booleanStringValue(characteristicProfile.permissionEnabled(CBAttributePermissions.ReadEncryptionRequired)) self.permissionWriteEncryptionLabel.text = self.booleanStringValue(characteristicProfile.permissionEnabled(CBAttributePermissions.WriteEncryptionRequired)) self.propertyBroadcastLabel.text = self.booleanStringValue(characteristicProfile.propertyEnabled(CBCharacteristicProperties.Broadcast)) self.propertyReadLabel.text = self.booleanStringValue(characteristicProfile.propertyEnabled(CBCharacteristicProperties.Read)) self.propertyWriteWithoutResponseLabel.text = self.booleanStringValue(characteristicProfile.propertyEnabled(CBCharacteristicProperties.WriteWithoutResponse)) self.propertyWriteLabel.text = self.booleanStringValue(characteristicProfile.propertyEnabled(CBCharacteristicProperties.Write)) self.propertyNotifyLabel.text = self.booleanStringValue(characteristicProfile.propertyEnabled(CBCharacteristicProperties.Notify)) self.propertyIndicateLabel.text = self.booleanStringValue(characteristicProfile.propertyEnabled(CBCharacteristicProperties.Indicate)) self.propertyAuthenticatedSignedWritesLabel.text = self.booleanStringValue(characteristicProfile.propertyEnabled(CBCharacteristicProperties.AuthenticatedSignedWrites)) self.propertyExtendedPropertiesLabel.text = self.booleanStringValue(characteristicProfile.propertyEnabled(CBCharacteristicProperties.ExtendedProperties)) self.propertyNotifyEncryptionRequiredLabel.text = self.booleanStringValue(characteristicProfile.propertyEnabled(CBCharacteristicProperties.NotifyEncryptionRequired)) self.propertyIndicateEncryptionRequiredLabel.text = self.booleanStringValue(characteristicProfile.propertyEnabled(CBCharacteristicProperties.IndicateEncryptionRequired)) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func prepareForSegue(segue:UIStoryboardSegue, sender:AnyObject!) { if segue.identifier == MainStoryboard.serviceCharacteristicProfileValuesSegue { let viewController = segue.destinationViewController as! ServiceCharacteristicProfileValuesViewController viewController.characteristicProfile = self.characteristicProfile } } func booleanStringValue(value:Bool) -> String { return value ? "YES" : "NO" } }
56.45977
181
0.742671
e6e53867bfe5899f3636acf2ae554ec0776f73f6
6,402
// // AutoInsetter.swift // AutoInset // // Created by Merrick Sapsford on 16/01/2018. // Copyright © 2018 UI At Six. All rights reserved. // import UIKit /// Engine that provides Auto Insetting to UIViewControllers. public final class AutoInsetter { // MARK: Properties private var currentScrollViewInsets = [UIScrollView: UIEdgeInsets]() /// Whether auto-insetting is enabled. public var isEnabled: Bool = true // MARK: Init public init() {} // MARK: Insetting /// Inset a child view controller by a set of required insets. /// /// - Parameters: /// - childViewController: Child view controller to inset. /// - requiredInsetSpec: The required inset specification. public func inset(_ childViewController: UIViewController?, requiredInsetSpec: AutoInsetSpec) { guard let childViewController = childViewController, isEnabled else { return } if #available(iOS 11, *) { childViewController.additionalSafeAreaInsets = requiredInsetSpec.additionalRequiredInsets } childViewController.forEachEmbeddedScrollView { (scrollView) in if #available(iOS 11.0, *) { scrollView.contentInsetAdjustmentBehavior = .never } let requiredContentInset = calculateActualRequiredContentInset(for: scrollView, from: requiredInsetSpec, in: childViewController) // dont update if we dont need to if scrollView.contentInset != requiredContentInset { let isTopInsetChanged = requiredContentInset.top != scrollView.contentInset.top let topInsetDelta = requiredContentInset.top - scrollView.contentInset.top scrollView.contentInset = requiredContentInset scrollView.scrollIndicatorInsets = requiredContentInset // only update contentOffset if the top contentInset has updated. if isTopInsetChanged { var contentOffset = scrollView.contentOffset contentOffset.y -= topInsetDelta scrollView.contentOffset = contentOffset } } } } private func reset(_ childViewController: UIViewController, from requiredInsetSpec: AutoInsetSpec) { if #available(iOS 11, *) { childViewController.additionalSafeAreaInsets = .zero } childViewController.forEachEmbeddedScrollView { (scrollView) in if #available(iOS 11, *) { scrollView.contentInsetAdjustmentBehavior = .automatic } scrollView.contentInset = .zero scrollView.contentOffset = .zero scrollView.scrollIndicatorInsets = .zero } } } // MARK: - Utilities private extension AutoInsetter { /// Calculate the actual inset values to use for a scroll view. /// /// - Parameters: /// - scrollView: Scroll view. /// - requiredInsets: Required TabmanBar insets. /// - viewController: The view controller that contains the scroll view. /// - Returns: Actual contentInset values to use. func calculateActualRequiredContentInset(for scrollView: UIScrollView, from requiredInsetSpec: AutoInsetSpec, in viewController: UIViewController) -> UIEdgeInsets { viewController.view.layoutIfNeeded() let requiredContentInset = requiredInsetSpec.allRequiredInsets let previousContentInset = currentScrollViewInsets[scrollView] ?? .zero // Calculate top / bottom insets relative to view position in child vc. var proposedContentInset: UIEdgeInsets if isEmbeddedViewController(viewController) { // Embedded VC is always full canvas proposedContentInset = requiredContentInset } else { // Standard View controller let relativeSuperview = viewController.view let relativeFrame = viewController.view.convert(scrollView.frame, from: relativeSuperview) let relativeTopInset = max(requiredContentInset.top - relativeFrame.minY, 0.0) let bottomInsetMinY = viewController.view.bounds.height - requiredContentInset.bottom let relativeBottomInset = fabs(min(bottomInsetMinY - relativeFrame.maxY, 0.0)) let originalContentInset = scrollView.contentInset proposedContentInset = UIEdgeInsets(top: relativeTopInset, left: originalContentInset.left, bottom: relativeBottomInset, right: originalContentInset.right) } currentScrollViewInsets[scrollView] = proposedContentInset var actualRequiredContentInset = proposedContentInset // Take into account any custom insets for top / bottom if scrollView.contentInset.top != 0.0 { let customTopInset = scrollView.contentInset.top - previousContentInset.top actualRequiredContentInset.top += customTopInset } if scrollView.contentInset.bottom != 0.0 { let customBottomInset = scrollView.contentInset.bottom - previousContentInset.bottom actualRequiredContentInset.bottom += customBottomInset } return actualRequiredContentInset } /// Check whether a view controller is an 'embedded' view controller type (i.e. UITableViewController) /// /// - Parameters: /// - viewController: The view controller. /// - success: Execution if view controller is not embedded type. func isEmbeddedViewController(_ viewController: UIViewController) -> Bool { if (viewController is UITableViewController) || (viewController is UICollectionViewController) { return true } return false } }
40.77707
106
0.601999
1a62938cbdeb5b626ba7d8dbc41ab5bef98c00b1
4,140
// // SubscriptionCell.swift // Rocket.Chat // // Created by Rafael K. Streit on 8/4/16. // Copyright © 2016 Rocket.Chat. All rights reserved. // import UIKit final class SubscriptionCell: UITableViewCell { static let identifier = "CellSubscription" internal let labelSelectedTextColor = UIColor(rgb: 0x000000, alphaVal: 1) internal let labelReadTextColor = UIColor(rgb: 0x585b5c, alphaVal: 1) internal let labelUnreadTextColor = UIColor(rgb: 0x000000, alphaVal: 1) internal let defaultBackgroundColor = UIColor.clear internal let selectedBackgroundColor = UIColor(rgb: 0x0, alphaVal: 0.18) internal let highlightedBackgroundColor = UIColor(rgb: 0x0, alphaVal: 0.27) var subscription: Subscription? { didSet { updateSubscriptionInformatin() } } @IBOutlet weak var imageViewAvatar: UIImageView! @IBOutlet weak var labelName: UILabel! @IBOutlet weak var labelUnread: UILabel! @IBOutlet weak var labelUnreadWidth: NSLayoutConstraint! @IBOutlet weak var statusView: UIView! func updateSubscriptionInformatin() { guard let subscription = self.subscription else { return } imageViewAvatar.setImageWithCensorship(with: User.avatarURL(subscription.name), placeholderImage: UIImage(namedInBundle: "SoyouAvatarPlaceholder"), options: [.allowInvalidSSLCertificates]) { (_, error, _, _) in if error != nil { self.imageViewAvatar.image = UIImage(namedInBundle: "SoyouAvatarPlaceholder") } } labelName.text = subscription.displayName() if subscription.unread > 0 || subscription.alert { labelName.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.headline) labelName.textColor = labelUnreadTextColor } else { labelName.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.body) labelName.textColor = labelReadTextColor } labelUnread.alpha = subscription.unread > 0 ? 1 : 0 labelUnreadWidth.constant = subscription.unread > 99 ? 30 : (subscription.unread > 9 ? 23 : (subscription.unread > 0 ? 16 : 0)) labelUnread.text = "\(subscription.unread)" updateStatus() } func updateStatus() { if let user = self.subscription?.directMessageUser { switch user.status { case .online: statusView.backgroundColor = UIColor(rgb: 0x2DE0A5, alphaVal: 1) case .offline: statusView.backgroundColor = UIColor(rgb: 0xCBCED1, alphaVal: 1) case .away: statusView.backgroundColor = UIColor(rgb: 0xFFD21F, alphaVal: 1) case .busy: statusView.backgroundColor = UIColor(rgb: 0xF5455C, alphaVal: 1) } } else { statusView.backgroundColor = UIColor(rgb: 0xCBCED1, alphaVal: 1) } } } extension SubscriptionCell { override func setSelected(_ selected: Bool, animated: Bool) { let transition = { switch selected { case true: self.backgroundColor = self.selectedBackgroundColor case false: self.backgroundColor = self.defaultBackgroundColor } } if animated { UIView.animate(withDuration: 0.18, animations: transition) } else { transition() } } override func setHighlighted(_ highlighted: Bool, animated: Bool) { let transition = { switch highlighted { case true: self.backgroundColor = self.highlightedBackgroundColor case false: self.backgroundColor = self.defaultBackgroundColor } } if animated { UIView.animate(withDuration: 0.18, animations: transition) } else { transition() } } }
35.384615
135
0.59686