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
|
---|---|---|---|---|---|
ffb34458a23eb269d3867bd9660ad4b5fd5832d9 | 562 | //
// WeatherListService.swift
// WeatherApp
//
// Created by Юрий Девятаев on 07.01.2022.
//
import Foundation
protocol WeatherListService {
func addtoList(entity: CWEntity)
func updateList(entity: CWEntity, index: Int)
func deleteFromList(for index: Int)
func getList() -> [CWEntity]
func getCountList() -> Int
func getCurrentIndex() -> Int
func updateCurrentIndex(value: Int)
func getCurrentWeatherConditions() -> String
func setTemporary(entity: CWEntity)
func getTemporaryEntity() -> CWEntity?
}
| 21.615385 | 49 | 0.685053 |
56a09e8bd1b28a21cc22d11ff80bb0ecdbf0dd51 | 15,831 | //
// LocalizedFrame.swift
// SwiftTaggerID3
//
// Created by Nolaine Crusher on 9/18/20.
//
/*
v2.2:
User defined text information frame
This frame is intended for one-string text information concerning the
audiofile in a similar way to the other "T"-frames. The frame body
consists of a description of the string, represented as a terminated
string, followed by the actual string. There may be more than one
"TXXX" frame in each tag, but only one with the same description.
<Header for 'User defined text information frame', ID: (TXX or )"TXXX">
Text encoding $xx
Description <text string according to encoding> $00 (00)
Value <text string according to encoding>
User defined URL link frame
This frame is intended for URL [URL] links concerning the audio file
in a similar way to the other "W"-frames. The frame body consists
of a description of the string, represented as a terminated string,
followed by the actual URL. The URL is always encoded with ISO-8859-1
[ISO-8859-1]. There may be more than one "WXXX" frame in each tag,
but only one with the same description.
<Header for 'User defined URL link frame', ID: "WXXX">
Text encoding $xx
Description <text string according to encoding> $00 (00)
URL <text string>
Comments
This frame is intended for any kind of full text information that
does not fit in any other frame. It consists of a frame header
followed by encoding, language and content descriptors and is ended
with the actual comment as a text string. Newline characters are
allowed in the comment text string. There may be more than one
comment frame in each tag, but only one with the same language and
content descriptor.
<Header for 'Comment', ID: "COMM">
Text encoding $xx
Language $xx xx xx
Short content descrip. <text string according to encoding> $00 (00)
The actual text <full text string according to encoding>
Unsynchronised lyrics/text transcription
This frame contains the lyrics of the song or a text transcription of
other vocal activities. The head includes an encoding descriptor and
a content descriptor. The body consists of the actual text. The
'Content descriptor' is a terminated string. If no descriptor is
entered, 'Content descriptor' is $00 (00) only. Newline characters
are allowed in the text. There may be more than one 'Unsynchronised
lyrics/text transcription' frame in each tag, but only one with the
same language and content descriptor.
<Header for 'Unsynchronised lyrics/text transcription', ID: "USLT">
Text encoding $xx
Language $xx xx xx
Content descriptor <text string according to encoding> $00 (00)
Lyrics/text <full text string according to encoding>
*/
import Foundation
import SwiftLanguageAndLocaleCodes
/// A type representing an ID3 frame that holds a three string fields: `Language` contains the 3-charcter string for the ISO-639-2 language code, `Description` contains a null-terminated string describing the frame content, and `Content`.
///
/// This frame type will be used for `UserDefinedText`, `UserDefinedWebpage`, `Comment` and `UnsynchronizedLyrics` frames. A tag may have multiple frames of these types, but only one frame with the same `Description` and/or `Language`.
///
/// To preserve frame uniqueness while allowing multiple frames of these types, the `Description` field will be used as part of the `FrameKey`.///
///
/// `Comment` and `UnsynchronizedLyrics` frames are the only frames that allow the use of new-line characters. Therefore, they are ideally suited for long remarks and convenience getter-setter properties for the most common types have been added.
class LocalizedFrame: Frame {
override var description: String {
return """
Identifier: \(self.identifier.rawValue):
Language: \(self.language?.rawValue ?? "und")
Description: \(self.descriptionString ?? "")
Content: \(self.stringValue)
"""
}
/// ISO-639-2 languge code
var language: ISO6392Code?
/// A short description of the frame content.
var descriptionString: String?
/// the content of the frame
var stringValue: String
// MARK: - Frame Parsing
init(identifier: FrameIdentifier,
version: Version,
size: Int,
flags: Data,
payload: Data) throws {
var data = payload
let encoding = try data.extractEncoding()
// if it's a frame with a language string, parse that out
if identifier == .comments ||
identifier == .unsynchronizedLyrics {
/// parse out a language string only for these frame types
let codeString = try String(ascii: data.extractFirst(3))
if let languageCode = ISO6392Code(rawValue: codeString) {
self.language = languageCode
} else {
self.language = .und
}
}
let parsed = data.extractDescriptionAndContent(encoding)
self.descriptionString = parsed.description
self.stringValue = parsed.content
super.init(identifier: identifier,
version: version,
size: size,
flags: flags)
}
override var frameKey: FrameKey {
switch self.identifier {
case .comments, .unsynchronizedLyrics: return self.identifier.frameKey(language: self.language, description: self.descriptionString)
case .userDefinedText, .userDefinedWebpage: return self.identifier.frameKey(self.descriptionString)
default: fatalError("Invalid frame key for localizedFrame \(self.identifier)")
}
}
private static func encoding(description: String?,
stringValue: String) -> String.Encoding {
var descriptionEncoding = String.Encoding.isoLatin1
if let descriptionString = description {
descriptionEncoding = String.Encoding(string: descriptionString)
}
let stringValueEncoding = String.Encoding(string: stringValue)
if descriptionEncoding != .isoLatin1 ||
stringValueEncoding != .isoLatin1 {
return .utf16
} else {
return .isoLatin1
}
}
/*
Text encoding $xx
Description <textstring> $00 (00)
URL <textstring>
Text encoding $xx
Language $xx xx xx
Short content descrip. <text string according to encoding> $00 (00)
The actual text <full text string according to encoding>
*/
override var contentData: Data {
var data = Data()
let encoding = LocalizedFrame.encoding(description: descriptionString,
stringValue: stringValue)
data.append(encoding.encodingByte)
if self.identifier == .comments || self.identifier == .unsynchronizedLyrics {
// encode and append language string
if let language = self.language {
let languageString = language.rawValue
data.append(languageString.encodedASCII)
} else {
data.append("und".encodedASCII)
}
}
if let description = self.descriptionString {
data.append(description.attemptTerminatedStringEncoding(encoding))
} else {
data.append(encoding.nullTerminator)
}
data.append(self.stringValue.attemptStringEncoding(encoding))
return data
}
// MARK: - Frame building
/// - parameter languageString: the ISO-639-2 language code. default is `undetermined`
/// - parameter descriptionString: a terminated text string describing the frame content
/// - parameter contentString: the full text of the comment or lyric frame.
init(_ identifier: FrameIdentifier,
version: Version,
language: ISO6392Code?,
description: String?,
stringValue: String) {
self.language = language
self.descriptionString = description
self.stringValue = stringValue
let encoding = LocalizedFrame.encoding(description: descriptionString,
stringValue: stringValue)
var size = 1 // +1 for encoding byte
if language != nil {
size += 3
}
if let description = description {
size += description.attemptTerminatedStringEncoding(encoding).count
}
size += stringValue.attemptStringEncoding(encoding).count
let flags = version.defaultFlags
super.init(identifier: identifier,
version: version,
size: size,
flags: flags)
}
}
// MARK: - Tag extension
// get and set functions for `LocalizedFrame` frame types, which retrieves or sets up to three strings, one of which may be a language code, and one of which is an optional description string. Each individual frame of this type will call these functions in a get-set property or function, where appropriate.
extension Tag {
/// `comments` frame getter-setter. ID3 Identifier `COM`/`COMM`
public subscript(comment description: String?, language: ISO6392Code? = nil) -> String? {
get {
if let string = get(localizedFrame: .comments,
language: language,
description: description) {
return string
} else {
return nil
}
}
set {
if let new = newValue {
set(localizedFrame: .comments,
language: language,
description: description,
stringValue: new)
} else {
set(localizedFrame: .comments,
language: language,
description: description,
stringValue: nil)
}
}
}
/// `unsynchronizedLyrics` frame getter-setter. ID3 Identifier `ULT`/`USLT`
public subscript(lyrics description: String?, language: ISO6392Code? = nil) -> String? {
get {
if let string = get(localizedFrame: .unsynchronizedLyrics,
language: language,
description: description) {
return string
} else {
return nil
}
}
set {
if let new = newValue {
set(localizedFrame: .unsynchronizedLyrics,
language: language,
description: description,
stringValue: new)
} else {
set(localizedFrame: .unsynchronizedLyrics,
language: language,
description: description,
stringValue: nil)
}
}
}
/// `userDefinedText` frame getter-setter. ID3 Identifier `TXX`/`TXXX`
public subscript(_ description: String?) -> String? {
get {
if let string = get(userDefinedFrame: .userDefinedText,
description: description) {
return string
} else {
return nil
}
}
set {
if let new = newValue {
set(userDefinedFrame: .userDefinedText,
description: description,
stringValue: new)
} else {
set(userDefinedFrame: .userDefinedText,
description: description,
stringValue: nil)
}
}
}
/// `userDefinedWebpage` frame getter-setter. ID3 Identifier `WXX`/`WXXX`
public subscript(userDefinedUrl description: String?) -> String? {
get {
if let string = get(userDefinedFrame: .userDefinedWebpage,
description: description) {
return string
} else {
return nil
}
}
set {
if let new = newValue {
set(userDefinedFrame: .userDefinedWebpage,
description: description,
stringValue: new)
} else {
set(userDefinedFrame: .userDefinedWebpage,
description: description,
stringValue: nil)
}
}
}
// MARK: - Private and Internal
private func get(localizedFrame identifier: FrameIdentifier,
language: ISO6392Code?,
description: String?) -> String? {
let frameKey = identifier.frameKey(language: language, description: description)
if identifier == .unsynchronizedLyrics {
if let frame = self.frames[frameKey] as? LocalizedFrame {
return frame.stringValue
} else {
return nil
}
} else if identifier == .comments {
if let frame = self.frames[frameKey] as? LocalizedFrame {
return frame.stringValue
} else {
return nil
}
} else {
return nil
}
}
private func get(userDefinedFrame identifier: FrameIdentifier,
description: String?) -> String? {
let frameKey = identifier.frameKey(description)
// check that the frame is a UserDefinedWebpage frame or a UserText frame
if identifier == .userDefinedWebpage {
if let frame = self.frames[frameKey] as? LocalizedFrame {
// return the content string of a specific frame by searching using the description string
return frame.stringValue
} else {
return nil
}
} else if identifier == .userDefinedText {
if let frame = self.frames[frameKey] as? LocalizedFrame {
return frame.stringValue
} else {
return nil
}
} else {
return nil
}
}
private mutating func set(localizedFrame identifier: FrameIdentifier,
language: ISO6392Code?,
description: String?,
stringValue: String?) {
let frameKey = identifier.frameKey(language: language, description: description)
if let stringValue = stringValue {
let frame = LocalizedFrame(identifier,
version: self.version,
language: language,
description: description,
stringValue: stringValue)
self.frames[frameKey] = frame
} else {
self.frames[frameKey] = nil
}
}
private mutating func set(userDefinedFrame identifier: FrameIdentifier,
description: String?,
stringValue: String?) {
let frameKey = identifier.frameKey(description)
if let stringValue = stringValue {
let frame = LocalizedFrame(identifier,
version: self.version,
language: nil,
description: description,
stringValue: stringValue)
self.frames[frameKey] = frame
} else {
self.frames[frameKey] = nil
}
}
}
| 39.380597 | 307 | 0.581201 |
e9ce1e32dd042f6b1afc399cfdd3e75da347906a | 947 | //
// BindableType.swift
// RXDemo
//
// Created by Alex.Shen on 1/14/20.
// Copyright © 2020 沈海超. All rights reserved.
//
import Foundation
import UIKit
protocol BindableType {
associatedtype ViewModelType
var viewModel: ViewModelType! { get set }
func bindViewModel()
}
extension BindableType where Self: UIViewController {
mutating func bind(to model: Self.ViewModelType) {
viewModel = model
if #available(iOS 9.0, *) {
loadViewIfNeeded()
} else {
// Fallback on earlier versions
}
bindViewModel()
}
}
extension BindableType where Self: UITableViewCell {
mutating func bind(to model: Self.ViewModelType) {
viewModel = model
bindViewModel()
}
}
extension BindableType where Self: UICollectionViewCell {
mutating func bind(to model: Self.ViewModelType) {
viewModel = model
bindViewModel()
}
}
| 20.148936 | 57 | 0.63886 |
87f459c77ea80f32a469b60796e9da4b85f69925 | 9,081 | //
// PresentationViewController.swift
// iOSArtLogicChallenge
//
// Created by Ramon Haro Marques on 06/12/2019.
// Copyright © 2019 Ramon Haro Marques. All rights reserved.
//
import UIKit
class PresentationViewController: BaseViewController {
//MARK: - Properties
private let presentationID: String
private let apiManager: ApiManaging
private let queue = DispatchQueue(label: "PresentationQueue", qos: .userInteractive)
private var presentationResponse: PresentationResponse? {
didSet {
updateView(presentationResponse: presentationResponse)
}
}
//UI
private lazy var scrollView: UIScrollView = {
let rtView = UIScrollView()
rtView.bounces = false
rtView.delegate = self
return rtView
}()
private lazy var contenView: UIView = { return UIView()}()
//TODO Replace to its own UIView
private lazy var headerImageView: UIImageView = {
let rtView = UIImageView()
rtView.contentMode = .scaleAspectFill
rtView.clipsToBounds = true
return rtView
}()
private lazy var headerTitleLabel: BaseLabel = {
let rtView = BaseLabel(withConfiguration: .header)
rtView.textAlignment = .center
rtView.textColor = UIColor.mainTextInverted
return rtView
}()
private lazy var presentationContainerView: UIView = { return UIView() }()
//MARK: - Constructor
init(presentationID: String, apiManager: ApiManaging) {
self.presentationID = presentationID
self.apiManager = apiManager
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
//MARK: - Lifecycle methods
extension PresentationViewController {
override func viewDidLoad() {
super.viewDidLoad()
makeTransparentNavigationBar()
setupView()
loaderOverlay.showOverlay()
apiManager.getPresentation(uid: presentationID) { [weak self] (result) in
guard let strongSelf = self else { return }
DispatchQueue.main.async {
strongSelf.loaderOverlay.hideOverlayView()
switch result {
case .success(let presentationResponse):
strongSelf.presentationResponse = presentationResponse
case .failure(let error):
print(strongSelf.logClassName, "ERROR -> ", error)
strongSelf.showAlert(withTitle: "error".localized, message: "error_generic".localized, sender: strongSelf, completion: nil)
}
}
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
makeSolidtNavigationBar()
}
}
//MARK: - Private methods
private extension PresentationViewController {
func setupView() {
isScrolling = true
view.addSubview(scrollView)
scrollView.snp.makeConstraints { (builder) in
builder.top.equalToSuperview().inset(-2*topbarHeight)
builder.left.bottom.right.equalToSuperview()
}
scrollView.addSubview(contenView)
contenView.snp.makeConstraints { (builder) in
builder.top.left.bottom.right.equalToSuperview()
builder.width.equalToSuperview()
}
contenView.addSubview(headerImageView)
headerImageView.snp.makeConstraints { (builder) in
builder.top.equalToSuperview()
builder.left.right.equalToSuperview()
builder.height.equalTo((view.frame.height * 2) / 3)
}
headerImageView.addSubview(headerTitleLabel)
headerTitleLabel.snp.makeConstraints { (builder) in
builder.left.right.equalToSuperview()
builder.centerX.equalToSuperview()
builder.centerY.equalToSuperview()
}
contenView.addSubview(presentationContainerView)
presentationContainerView.snp.makeConstraints { (builder) in
builder.top.equalTo(headerImageView.snp.bottom).inset(-Margins.large)
builder.left.right.equalToSuperview()
builder.height.equalTo(0).priority(.low)
builder.bottom.equalToSuperview()
builder.bottom.equalTo(scrollView.snp.bottom)
}
}
func updateView(presentationResponse: PresentationResponse?) {
guard let presentationResponse = presentationResponse else { return }
let firstPresentation = presentationResponse.presentationItems[0]
titleView.title = presentationResponse.galleryName
headerImageView.sd_setImage(with: URL(string: firstPresentation.imageSet.fullSize ?? ""), placeholderImage: nil)
headerTitleLabel.text = presentationResponse.galleryName
let dispatchGroup = DispatchGroup()
let presentationStackView = UIStackView()
presentationStackView.alignment = .fill
presentationStackView.distribution = .fill
presentationStackView.axis = .vertical
presentationStackView.spacing = Margins.medium
presentationContainerView.addSubview(presentationStackView)
presentationStackView.snp.makeConstraints { (builder) in
builder.top.left.bottom.right.equalToSuperview().inset(Margins.medium)
}
for item in presentationResponse.presentationItems.dropFirst() {
dispatchGroup.enter()
queue.async { [weak self] in
guard let strongSelf = self else { return }
if let imageURL = URL(string: item.imageSet.defaultImage ?? ""),
let imageData = try? Data(contentsOf: imageURL),
let image = UIImage(data: imageData){
DispatchQueue.main.async {
let presetationItemView = UIStackView()
presetationItemView.alignment = .top
presetationItemView.distribution = .fillProportionally
presetationItemView.axis = .horizontal
presetationItemView.spacing = Margins.xSmall
// Add image
let imageView = UIImageView(image: image)
let width:CGFloat = strongSelf.view.frame.size.width / 3
let height = width * (1 / image.aspectRatioValue)
imageView.snp.makeConstraints { (builder) in
builder.width.equalTo(width)
builder.height.equalTo(height)
}
presetationItemView.addArrangedSubview(imageView)
// Add caption
let sectionCaptionLabel = BaseLabel(withConfiguration: .normal)
let captionSeparated = item.rowCaption.components(separatedBy: ",")
let combination = NSMutableAttributedString()
for i in 0 ..< captionSeparated.count {
let font = i == 0 ? UIFont.bold(size: TextSize.normal):UIFont.regular(size: TextSize.normal)
let attributes = [NSAttributedString.Key.font: font]
let attString = NSAttributedString(string: " \(i == 0 ? " ":"") \(captionSeparated[i])\n", attributes: attributes)
combination.append(attString)
}
sectionCaptionLabel.attributedText = combination
presetationItemView.addArrangedSubview(sectionCaptionLabel)
presentationStackView.addArrangedSubview(presetationItemView)
dispatchGroup.leave()
}
}
else {
dispatchGroup.leave()
}
}
}
}
}
//MARK:- UIScrollViewDelegate implementation
extension PresentationViewController: UIScrollViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let labelAbsolutePoint = headerTitleLabel.convert(headerTitleLabel.bounds.origin, to: view)
let invertedAbsolutePointY = -labelAbsolutePoint.y
titleView.updateTitleMargin(invertedAbsolutePointY)
if invertedAbsolutePointY > -88 {
makeSolidtNavigationBar()
}
else {
makeTransparentNavigationBar()
}
//print(logClassName, "TEST -> ", invertedAbsolutePointY)
}
}
| 36.179283 | 143 | 0.580222 |
1af7e3856b5e54233cf98fbfece5707c94aa161d | 898 | //
// HomeViewModel.swift
// PokeMe
//
// Created by mmalaqui on 12/02/2021.
//
//
import Foundation
import UIKit
//Class that represents the model that should be used in the view of Home
class HomeViewModel {
var idHome: String?
var pokemonModel : HomeViewPokemonModel?
init() {}
init(homeInteractorModel : HomeInteractorModel){
if let pokemon = homeInteractorModel.pokemon {
self.pokemonModel = HomeViewPokemonModel(homeInteractorModel: pokemon)
}
}
}
class HomeViewPokemonModel {
var id : Int?
var name : String?
var height : Int?
var imageURL : String?
init(homeInteractorModel : HomeInteractorPokemonModel) {
self.id = homeInteractorModel.id
self.name = homeInteractorModel.name
self.height = homeInteractorModel.height
self.imageURL = homeInteractorModel.imageURL
}
}
| 23.025641 | 82 | 0.674833 |
2660794db8676c05d0d3ef8316585377ed43dd3e | 1,651 | //
// Ext.swift
// testDemoSwift
//
// Created by 陈亮陈亮 on 2017/5/22.
// Copyright © 2017年 陈亮陈亮. All rights reserved.
//
import UIKit
extension UIImage {
// 对截取的长图进行压缩,因为项目中的长图是设置为背景颜色,如果不压缩到适当的尺寸图片就会平铺
static func scaleImage(image: UIImage) -> UIImage {
// 画板高度
let boardH = KScreenHeight-64-50-40
// 图片的宽高比
let picBili: CGFloat = image.size.width/image.size.height
// 画板的宽高比
let boardBili: CGFloat = KScreenWidth/boardH
// 图片大小
UIGraphicsBeginImageContext(CGSize(width:KScreenWidth,height:boardH))
// 真正图片显示的位置
// 如果图片太长,以高为准,否则以宽为准
if picBili<=boardBili {
image.draw(in: CGRect(x: 0.5*(KScreenWidth-boardH*picBili), y: 0, width: boardH*picBili, height: boardH))
} else {
image.draw(in: CGRect(x: 0, y:0.5*(boardH-KScreenWidth/picBili) , width: KScreenWidth, height: KScreenWidth/picBili))
}
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
//对图片包得大小进行压缩
let imageData = UIImagePNGRepresentation(scaledImage!)
let m_selectImage = UIImage.init(data: imageData!)
return m_selectImage!
}
// 截取一部分
static func screenShotForPart(view:UIView,size:CGSize) -> UIImage{
var image = UIImage()
UIGraphicsBeginImageContextWithOptions(size, true, UIScreen.main.scale)
view.layer.render(in: UIGraphicsGetCurrentContext()!)
image = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return image
}
}
| 31.150943 | 129 | 0.637795 |
ace4ab64f65bc4917cf1318d1704b39d6b5c3032 | 3,590 | //
// PLMenuDetailComboView.swift
// PLMenuBar
//
// Created by Patrick Lin on 4/13/16.
// Copyright © 2016 Patrick Lin. All rights reserved.
//
@objc public protocol PLMenuDetailComboViewDelegate: NSObjectProtocol {
func combo(_ combo: PLMenuDetailComboView, didChangeValueAtSection section: Int, Row row: Int)
}
open class PLMenuDetailComboView: PLMenuDetailView, PLMenuDetailComboSectionViewDelegate {
var items: [PLMenuComboSection] = [PLMenuComboSection]()
open var delegate: PLMenuDetailComboViewDelegate?
// MARK: Combo Section Delegate Methods
func section(_ section: PLMenuDetailComboSectionView, didChangeValueAtRow row: Int) {
for (indexOfSection, sectionView) in self.contentViews.enumerated() {
if sectionView == section {
self.delegate?.combo(self, didChangeValueAtSection: indexOfSection, Row: row)
break
}
}
}
// MARK: Public Methods
override open func layoutSubviews() {
super.layoutSubviews()
let contentWidth = self.bounds.size.width / CGFloat(self.items.count)
let contentHeight = self.bounds.size.height
for (index, content) in self.contentViews.enumerated() {
content.frame = CGRect(x: contentWidth * CGFloat(index), y: 0, width: contentWidth, height: contentHeight)
}
}
override open func didUpdateFocus(in context: UIFocusUpdateContext, with coordinator: UIFocusAnimationCoordinator) {
if context.nextFocusedView != nil {
for (_, contentView) in self.contentViews.enumerated() {
let sectionView = contentView as! PLMenuDetailComboSectionView
for (_, rowView) in sectionView.rowViews.enumerated() {
if rowView.contentBtn === context.nextFocusedView! {
rowView.isHighLighted = true
}
}
}
}
if context.previouslyFocusedView != nil {
for (_, contentView) in self.contentViews.enumerated() {
let sectionView = contentView as! PLMenuDetailComboSectionView
for (_, rowView) in sectionView.rowViews.enumerated() {
if rowView.contentBtn === context.previouslyFocusedView! {
rowView.isHighLighted = false
}
}
}
}
}
// MARK: Init Methods
func commonInit() {
for (_, item) in self.items.enumerated() {
let content = PLMenuDetailComboSectionView(item: item)
content.delegate = self
self.addSubview(content)
self.contentViews.append(content)
}
}
convenience init(items: [PLMenuComboSection]) {
self.init(frame: CGRect.zero)
self.items.append(contentsOf: items)
self.commonInit()
}
}
| 27.615385 | 120 | 0.500557 |
62cae2d8383b30b73302ddea4467f16bd9d2c885 | 2,735 | //
// BottomOrderView.swift
// TeslaOrderForm
//
// Created by Craig Clayton on 2/23/20.
// Copyright © 2020 Cocoa Academy. All rights reserved.
//
import SwiftUI
struct BottomOrderView: View {
@EnvironmentObject var order:OrderViewModel
var body: some View {
VStack {
info
map
button
Spacer()
}.padding(.horizontal, 10)
}
var info: some View {
HStack {
HStack(spacing: 4) {
Text("1")
.custom(font: .medium, size: 22)
Text("car")
.custom(font: .ultralight, size: 22)
}
Spacer()
HStack(spacing: 4) {
Text("2")
.custom(font: .medium, size: 22)
Text("hours")
.custom(font: .ultralight, size: 22)
}
Spacer()
HStack(spacing: 4) {
Text("$160")
.custom(font: .medium, size: 22)
}
}
.padding(.horizontal, 15)
.frame(height: 55)
.frame(minWidth: 0, maxWidth: .infinity)
.background(Color.baseGray)
.cornerRadius(10)
}
var map: some View {
ZStack(alignment: Alignment(horizontal: .center, vertical: .bottom)) {
Image("sample-map")
.resizable()
.scaledToFit()
.padding(.bottom, 30)
HStack {
Image(systemName: "clock")
HStack(spacing: 4) {
Text("The car will arrive in")
.custom(font: .ultralight, size: 22)
Text("20 mins")
.custom(font: .medium, size: 22)
}
Spacer()
Image("disclosure-indicator")
}
.frame(height: 40)
.padding(.horizontal, 5)
.background(Color.white)
.cornerRadius(5)
.offset(y: -35)
.padding(.horizontal, 5)
}
.frame(maxWidth: 370)
}
var button: some View {
Button(action: { self.order.isCancelOrderVisible.toggle() }) {
Text("CANCEL ORDER")
}
.frame(height: 55)
.frame(minWidth: 0, maxWidth: .infinity)
.background(Color.baseGray)
.buttonStyle(PlainButtonStyle())
.cornerRadius(10)
.foregroundColor(.baseCardinal)
.custom(font: .bold, size: 28)
}
}
struct BottomOrderView_Previews: PreviewProvider {
static var previews: some View {
BottomOrderView()
.previewLayout(.fixed(width: 320, height: 400))
}
}
| 26.553398 | 78 | 0.472395 |
901b65108a797d6b2930d7ebfebfcf4332a00d49 | 2,370 | //
// ConfirmationCallbackTableViewCell.swift
// FRUI
//
// Copyright (c) 2019 ForgeRock. All rights reserved.
//
// This software may be modified and distributed under the terms
// of the MIT license. See the LICENSE file for details.
//
import UIKit
import FRAuth
class ConfirmationCallbackTableViewCell: UITableViewCell, FRUICallbackTableViewCell {
// MARK: - Properties
public static let cellIdentifier = "ConfirmationCallbackTableViewCellId"
public static let cellHeight: CGFloat = 100.0
public var delegate: AuthStepProtocol?
var callback: ConfirmationCallback?
var buttons: [FRButton] = []
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
override func layoutSubviews() {
super.layoutSubviews()
let xOrigin = 35
let yOrigin = 10
let spacing = 20
let buttonWidth = (Int(self.contentView.bounds.width) - 70 - (spacing * (buttons.count - 1))) / buttons.count
let buttonHeight = 40
for (index, button) in buttons.enumerated() {
let buttonXOrigin = xOrigin + ((buttonWidth + spacing) * index)
button.frame = CGRect(x: buttonXOrigin, y: yOrigin, width: buttonWidth, height: buttonHeight)
}
}
@objc func buttonClicked(sender: UIButton) {
callback?.value = sender.tag
delegate?.submitNode()
}
// MARK: - Public
public func updateCellData(callback: Callback) {
self.callback = callback as? ConfirmationCallback
if let options = self.callback?.options {
for (index, option) in options.enumerated() {
let button = FRButton(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
button.setTitle(option, for: .normal)
button.backgroundColor = FRUI.shared.primaryColor
button.titleColor = UIColor.white
button.tag = index
button.addTarget(self, action: #selector(buttonClicked(sender:)), for: .touchUpInside)
self.contentView.addSubview(button)
buttons.append(button)
}
}
}
}
| 30.779221 | 118 | 0.613924 |
20f92827751462f50334e25a6615ebbb56d74c83 | 3,344 | import Graphiti
let starWarsSchema = Schema<StarWarsAPI, StarWarsStore> {
Enum(Episode.self) {
Value(.newHope)
.description("Released in 1977.")
Value(.empire)
.description("Released in 1980.")
Value(.jedi)
.description("Released in 1983.")
}
.description("One of the films in the Star Wars Trilogy.")
Interface(Character.self, fieldKeys: CharacterFieldKeys.self) {
Field(.id, at: \.id)
.description("The id of the character.")
Field(.name, at: \.name)
.description("The name of the character.")
Field(.friends, at: \.friends, overridingType: [TypeReference<Character>].self)
.description("The friends of the character, or an empty list if they have none.")
Field(.appearsIn, at: \.appearsIn)
.description("Which movies they appear in.")
Field(.secretBackstory, at: \.secretBackstory)
.description("All secrets about their past.")
}
.description("A character in the Star Wars Trilogy.")
Type(Planet.self) {
Field(.id, at: \.id)
Field(.name, at: \.name)
Field(.diameter, at: \.diameter)
Field(.rotationPeriod, at: \.rotationPeriod)
Field(.orbitalPeriod, at: \.orbitalPeriod)
Field(.residents, at: \.residents, overridingType: [TypeReference<Human>].self)
}
.description("A large mass, planet or planetoid in the Star Wars Universe, at the time of 0 ABY.")
Type(Human.self, interfaces: Character.self) {
Field(.id, at: \.id)
Field(.name, at: \.name)
Field(.appearsIn, at: \.appearsIn)
Field(.homePlanet, at: \.homePlanet)
Field(.friends, at: Human.getFriends)
.description("The friends of the human, or an empty list if they have none.")
Field(.secretBackstory, at: Human.getSecretBackstory)
.description("Where are they from and how they came to be who they are.")
}
.description("A humanoid creature in the Star Wars universe.")
Type(Droid.self, interfaces: Character.self) {
Field(.id, at: \.id)
Field(.name, at: \.name)
Field(.appearsIn, at: \.appearsIn)
Field(.primaryFunction, at: \.primaryFunction)
Field(.friends, at: Droid.getFriends)
.description("The friends of the droid, or an empty list if they have none.")
Field(.secretBackstory, at: Droid.getSecretBackstory)
.description("Where are they from and how they came to be who they are.")
}
.description("A mechanical creature in the Star Wars universe.")
Union(SearchResult.self, members: Planet.self, Human.self, Droid.self)
Query {
Field(.hero, at: StarWarsAPI.getHero)
.description("Returns a hero based on the given episode.")
.argument(.episode, at: \.episode, description: "If omitted, returns the hero of the whole saga. If provided, returns the hero of that particular episode.")
Field(.human, at: StarWarsAPI.getHuman)
.argument(.id, at: \.id, description: "Id of the human.")
Field(.droid, at: StarWarsAPI.getDroid)
.argument(.id, at: \.id, description: "Id of the droid.")
Field(.search, at: StarWarsAPI.search)
.argument(.query, at: \.query, defaultValue: "R2-D2")
}
Types(Human.self, Droid.self)
}
| 36.747253 | 164 | 0.633971 |
09657bb42f3d7b3e36a1fcd8862927b7f3ea13af | 362 | // swift-tools-version:5.5
import PackageDescription
let package = Package(
name: "TeslaSwift",
platforms: [
.macOS(.v10_12), .iOS(.v15), .watchOS(.v3), .tvOS(.v10)
],
products: [
.library(name: "TeslaSwift", targets: ["TeslaSwift"]),
],
dependencies: [
],
targets: [
.target(name: "TeslaSwift"),
]
)
| 20.111111 | 63 | 0.555249 |
75a2bdb90d632ee127da6df5b54334ac03faeae3 | 1,157 | //
// SwiftIconFont+UITabBarItem.swift
// SwiftIconFont
//
// Created by Sedat Gökbek ÇİFTÇİ on 13.10.2017.
// Copyright © 2017 Sedat Gökbek ÇİFTÇİ. All rights reserved.
//
import UIKit
public extension UITabBarItem {
func iconWithSwiftIcon(defaultIcon: SwiftIcon) {
self.image = UIImage.icon(from: defaultIcon.font, iconColor: defaultIcon.color, code: defaultIcon.code, imageSize: defaultIcon.imageSize, ofSize: defaultIcon.fontSize)
}
func icon(from font: Fonts, code: String, iconColor: Color, imageSize: CGSize, ofSize size: CGFloat) {
self.image = UIImage.icon(from: font, iconColor: iconColor, code: code, imageSize: imageSize, ofSize: size)
}
func iconWithSelectedIcon(from defaultIcon: SwiftIcon, selectedIcon: SwiftIcon) {
self.image = UIImage.icon(from: defaultIcon.font, iconColor: defaultIcon.color, code: defaultIcon.code, imageSize: defaultIcon.imageSize, ofSize: defaultIcon.fontSize)
self.selectedImage = UIImage.icon(from: selectedIcon.font, iconColor: selectedIcon.color, code: selectedIcon.code, imageSize: selectedIcon.imageSize, ofSize: selectedIcon.fontSize)
}
}
| 46.28 | 188 | 0.740709 |
71bd0ffa0fb135c71cc3d12644e3fa21c678129f | 6,256 | //
// storyboardViewController.swift
// PlantML
//
// Created by Pritesh Nadiadhara on 10/5/20.
// Copyright © 2020 PriteshN. All rights reserved.
//
// this version of VC only to check against progamatic UI issues
import UIKit
import CoreML
import Vision // Apply computer vision algorithms to perform a variety of tasks on input images and video
import Alamofire
import SwiftyJSON
import SDWebImage
class SBViewController: UIViewController {
@IBOutlet weak var imageView : UIImageView!
@IBOutlet weak var descriptionLabel: UITextView!
let wikipediaURl = "https://en.wikipedia.org/w/api.php"
private let imagePicker = UIImagePickerController()
// MARK: - UI Elements
private let stackView : UIStackView = {
let sv = UIStackView()
sv.axis = .vertical
sv.distribution = .fillEqually
sv.spacing = 20
return sv
}()
private let scrollView: UIScrollView = {
let scrollView = UIScrollView()
scrollView.clipsToBounds = true
scrollView.isScrollEnabled = true
return scrollView
}()
private let descriptionLabelScrollView: UIScrollView = {
let scrollView = UIScrollView()
scrollView.clipsToBounds = true
scrollView.isScrollEnabled = true
return scrollView
}()
// MARK: - viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .camera,
target: self,
action: #selector (didTapCameraButton))
view.backgroundColor = .gray
imagePicker.delegate = self
imagePicker.allowsEditing = true
imagePicker.sourceType = .camera
}
//MARK: - Functions
@objc func didTapCameraButton(){
print("camera tapped")
present(imagePicker, animated: true, completion: nil)
}
func setUpStackView(){
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: 8).isActive = true
stackView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 8).isActive = true
stackView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -8).isActive = true
stackView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -8).isActive = true
}
func detectImage(image: CIImage){
// flower classifiers comes from auto generated .mlmodel
guard let model = try? VNCoreMLModel(for: FlowerClassifier().model) else {
fatalError("cannot import model")
}
let request = VNCoreMLRequest(model: model) { (request, error) in
// this returns the flower type
guard let classification = request.results?.first as? VNClassificationObservation else {
fatalError("couldn't clasify image")
}
self.navigationItem.title = classification.identifier.capitalized
self.requestWikiInfo(flowerName: classification.identifier)
}
let handler = VNImageRequestHandler(ciImage: image)
do {
try handler.perform([request])
} catch {
print(error)
}
}
func requestWikiInfo(flowerName: String){
let parameters : [String:String] = [
"format" : "json",
"action" : "query",
"prop" : "extracts|pageimages",
"exintro" : "",
"explaintext" : "",
"titles" : flowerName,
"indexpageids" : "",
"redirects" : "1",
"pithumbsize" : "500"
]
AF.request(wikipediaURl, method: .get, parameters: parameters).responseJSON { (response) in
switch response.result {
case .success(_):
print("got wiki info")
//print(response)
let flowerJSON : JSON = JSON(response.value as Any)
print("flowerJSON : ", flowerJSON)
//page id required to get wiki blurb on flower
let pageid = flowerJSON["query"]["pageids"][0].stringValue
print("page id : " ,pageid)
let flowerDescription = flowerJSON["query"]["pages"][pageid]["extract"].stringValue
print("flower description : ", flowerDescription)
let flowerImageURL = flowerJSON["query"]["pages"][pageid]["thumbnail"]["source"].stringValue
print(flowerImageURL)
self.imageView.sd_setImage(with: URL(string: flowerImageURL))
self.descriptionLabel.text = flowerDescription
self.descriptionLabel.adjustsFontForContentSizeCategory = true
case .failure(_):
print("failed to get wiki info")
break
}
}
}
}
extension SBViewController : UIImagePickerControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let userPickedImage = info[UIImagePickerController.InfoKey.editedImage] as? UIImage{
DispatchQueue.main.async {
guard let ciImage = CIImage(image: userPickedImage) else {
fatalError("Cannot convert to CI Image")
}
self.detectImage(image: ciImage)
}
}
imagePicker.dismiss(animated: true, completion: nil)
}
}
extension SBViewController: UINavigationControllerDelegate {
}
| 32.247423 | 144 | 0.571451 |
75a005c91e2b57237324f27ab68ea084715599d7 | 2,368 | //
// OneAPI.swift
// Demo
//
// Created by apple on 2017/12/11.
// Copyright © 2017年 apple. All rights reserved.
//
import Foundation
import Moya
import IGListKit
// MARK: - Provider setup
private func JSONResponseDataFormatter(_ data: Data) -> Data {
do {
let dataAsJSON = try JSONSerialization.jsonObject(with: data)
let prettyData = try JSONSerialization.data(withJSONObject: dataAsJSON, options: .prettyPrinted)
return prettyData
} catch {
return data // fallback to original data if it can't be serialized.
}
}
let oneProvider = MoyaProvider<OneAPI>(plugins: [NetworkLoggerPlugin(verbose: true, responseDataFormatter: JSONResponseDataFormatter)])
// MARK: - Provider support
private extension String {
var urlEscaped: String {
return self.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
}
}
public enum OneAPI {
case zen
case userProfile(String)
case userRepositories(String)
}
extension OneAPI: TargetType {
public var baseURL: URL { return URL(string: "https://api.github.com")! }
public var path: String {
switch self {
case .zen:
return "/zen"
case .userProfile(let name):
return "/users/\(name.urlEscaped)"
case .userRepositories(let name):
return "/users/\(name.urlEscaped)/repos"
}
}
public var method: Moya.Method {
return .get
}
public var task: Task {
switch self {
case .userRepositories:
return .requestParameters(parameters: ["sort": "pushed"], encoding: URLEncoding.default)
default:
return .requestPlain
}
}
public var validate: Bool {
switch self {
case .zen:
return true
default:
return false
}
}
public var sampleData: Data {
switch self {
case .zen:
return "Half measures are as bad as nothing at all.".data(using: String.Encoding.utf8)!
case .userProfile(let name):
return "{\"login\": \"\(name)\", \"id\": 100}".data(using: String.Encoding.utf8)!
case .userRepositories(let name):
return "[{\"name\": \"\(name)\"}]".data(using: String.Encoding.utf8)!
}
}
public var headers: [String: String]? {
return nil
}
}
| 27.858824 | 135 | 0.611064 |
50adcd726f7d363476ef74069883838eb1f5eae8 | 4,518 | //
// SerialInterfacePeripheralTests.swift
// TurtleSimulatorCoreTests
//
// Created by Andrew Fox on 1/2/20.
// Copyright © 2020 Andrew Fox. All rights reserved.
//
import XCTest
import TurtleSimulatorCore
extension SerialInterfacePeripheral {
func tick() {
onControlClock()
onRegisterClock()
onPeripheralClock()
}
func doLoad(at address: UInt16) {
self.address = address
bus = Register(withValue: 0)
PI = .inactive
PO = .active
tick()
}
func doStore(value: UInt8, at address: UInt16) {
self.address = address
bus = Register(withValue: value)
PI = .active
PO = .inactive
tick()
}
func doCommand(command: UInt8) -> UInt8 {
doStore(value: command, at: kDataRegister)
doStore(value: 1, at: kControlRegister)
tick() // NOP
doLoad(at: kDataRegister)
let byte = bus.value
doStore(value: 0, at: kControlRegister)
return byte
}
}
class SerialInterfacePeripheralTests: XCTestCase {
func makeStringBytes(_ string: String) -> [UInt8] {
return Array(string.data(using: .utf8)!)
}
func testInitiallyEmptySerialInputAndOutput() {
let serial = SerialInterfacePeripheral()
XCTAssertEqual(serial.serialInput.bytes, [])
XCTAssertEqual(serial.serialOutput, [])
XCTAssertEqual(serial.describeSerialOutput(), "")
}
func testDescribeSerialBytesAsBasicUTF8String() {
let serial = SerialInterfacePeripheral()
serial.serialOutput = Array("hello".data(using: .utf8)!)
XCTAssertEqual(serial.describeSerialOutput(), "hello")
}
func testDescribeSerialBytesContainingInvalidUTF8Character() {
let serial = SerialInterfacePeripheral()
serial.serialOutput = [65, 255, 66]
XCTAssertEqual(serial.describeSerialOutput(), "A�B")
}
func testReadOutputBuffer() {
let serial = SerialInterfacePeripheral()
serial.outputBuffer = 1
serial.doLoad(at: serial.kDataRegister)
XCTAssertEqual(serial.bus.value, 1)
}
func testWriteToInputBuffer() {
let serial = SerialInterfacePeripheral()
serial.doStore(value: 1, at: serial.kDataRegister)
XCTAssertEqual(serial.inputBuffer, 1)
}
func testWriteToSCK() {
let serial = SerialInterfacePeripheral()
serial.doStore(value: 1, at: serial.kControlRegister)
XCTAssertEqual(serial.sck, 1)
}
func testCommandResetSerialLink() {
let serial = SerialInterfacePeripheral()
serial.serialInput.bytes = [1, 2, 3]
serial.serialOutput = [1, 2, 3]
let status = serial.doCommand(command: serial.kCommandResetSerialLink)
XCTAssertEqual(status, serial.kStatusSuccess)
XCTAssertEqual(serial.serialInput.bytes, [])
XCTAssertEqual(serial.serialOutput, [])
}
func testCommandPutByte() {
let serial = SerialInterfacePeripheral()
let status1 = serial.doCommand(command: serial.kCommandPutByte)
let status2 = serial.doCommand(command: 65)
XCTAssertEqual(status1, serial.kStatusSuccess)
XCTAssertEqual(status2, serial.kStatusSuccess)
XCTAssertEqual(serial.serialInput.bytes, [])
XCTAssertEqual(serial.serialOutput, [65])
}
func testCommandGetNumBytesWithNoneAvailable() {
let serial = SerialInterfacePeripheral()
let count = serial.doCommand(command: serial.kCommandGetNumBytes)
XCTAssertEqual(count, 0)
}
func testCommandGetNumBytesWithSomeAvailable() {
let serial = SerialInterfacePeripheral()
serial.serialInput.bytes = [1, 2, 3]
let count = serial.doCommand(command: serial.kCommandGetNumBytes)
XCTAssertEqual(count, 3)
}
func testCommandGetByteWithNoneAvailable() {
let serial = SerialInterfacePeripheral()
let byte = serial.doCommand(command: serial.kCommandGetByte)
XCTAssertEqual(byte, 255)
}
func testCommandGetByteWithSomeAvailable() {
let serial = SerialInterfacePeripheral()
serial.serialInput.bytes = [1, 2, 3]
let byte = serial.doCommand(command: serial.kCommandGetByte)
XCTAssertEqual(byte, 1)
XCTAssertEqual(serial.serialInput.bytes, [2, 3])
}
}
| 30.527027 | 78 | 0.63568 |
e5c400d332507c33f4159bc0f369806cdb4d570c | 1,094 | //
// QXError.swift
// QXUIKitExtension
//
// Created by labi3285 on 2019/7/5.
// Copyright © 2019 labi3285_lab. All rights reserved.
//
import Foundation
public struct QXError: Error {
public var code: String
public var message: String
public var info: Any?
public init(_ code: Any, _ message: String, _ info: Any?) {
self.code = "\(code)"
self.message = message
self.info = info
}
public init(_ code: Any, _ message: String) {
self.code = "\(code)"
self.message = message
self.info = nil
}
public static let unknown: QXError = QXError(-1, "未知错误")
public static let parse: QXError = QXError(-1, "解析错误")
public static let format: QXError = QXError(-1, "格式错误")
public static let noData: QXError = QXError(-1, "数据丢失")
}
extension Error {
public var qxError: QXError {
if let err = self as? QXError {
return err
} else {
let err = self as NSError
return QXError("\(err.code)", err.domain, err.userInfo)
}
}
}
| 23.782609 | 67 | 0.582267 |
d994ac0174072d6688af06f9ed81617d5e1c313a | 378 | /*
* This file is part of the HSTracker package.
* (c) Benjamin Michotte <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* Created on 19/02/16.
*/
import Foundation
enum CardMark: Int {
case None,
Coin,
Returned,
Mulliganed,
Created,
Kept
}
| 18 | 74 | 0.677249 |
8fda8afb40ecba3a15384ede2ca5b0146882a79e | 773 | //
// User.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
open class User: Codable {
public var id: Int64?
public var username: String?
public var firstName: String?
public var lastName: String?
public var email: String?
public var password: String?
public var phone: String?
/** User Status */
public var userStatus: Int?
public init() {}
private enum CodingKeys: String, CodingKey {
case id = "id"
case username = "username"
case firstName = "firstName"
case lastName = "lastName"
case email = "email"
case password = "password"
case phone = "phone"
case userStatus = "userStatus"
}
}
| 20.342105 | 49 | 0.617076 |
6433955716349bae89b97b587603be0415387a41 | 2,358 | //
// FloatingActionButton.swift
// ios-interface-trace
//
// Created by ky0me22 on 2022/02/21.
//
import SwiftUI
struct FloatingActionButton: View {
// 子アイテムの展開アニメーションを制御するために配列にする
@State private var tapped = [false, false, false]
var body: some View {
// .zIndex() でViewの重なり順を指定する
ZStack {
// tappedの状態切り替えで子アイテムの表示/非表示を制御する
if tapped[0] {
ChildItemButton(offsetY: -150, color: Color.green, sfName: "paperplane")
.zIndex(2)
}
if tapped[1] {
ChildItemButton(offsetY: -300, color: Color.yellow, sfName: "lasso")
.zIndex(1)
}
if tapped[2] {
ChildItemButton(offsetY: -450, color: Color.red, sfName: "trash")
.zIndex(0)
}
Button(action: {
// 展開のアニメーションは全体で0.9秒
// それぞれの子アイテムの移動時間を計算して、移動開始時間のズレを調整する
// 展開する時(tappedがfalse→trueになるとき)はdelayは不要
// 格納する時は合計で0.9秒になるようにdurationとdelayを設定
withAnimation(Animation.linear(duration: 0.3).delay(tapped[0] ? 0.6 : 0)) {
tapped[0].toggle()
}
withAnimation(Animation.linear(duration: 0.6).delay(tapped[1] ? 0.3 : 0)) {
tapped[1].toggle()
}
withAnimation(Animation.linear(duration: 0.9)) {
tapped[2].toggle()
}
}, label: {
Image(systemName: "plus")
.resizable()
.frame(width: 40, height: 40, alignment: .center)
})
.foregroundColor(.white)
.frame(width: 100, height: 100, alignment: .center)
.background(Color.gray)
.cornerRadius(50)
.rotationEffect(tapped[0] ? Angle(degrees: 135) : .zero)
.shadow(color: .gray, radius: 6, x: 0.0, y: 5)
.zIndex(3)
}
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottomTrailing)
.padding(20)
}
}
struct FloatingActionButton_Previews: PreviewProvider {
static var previews: some View {
FloatingActionButton()
.previewDevice(PreviewDevice(rawValue: "iPhone 13"))
}
}
| 34.676471 | 91 | 0.511874 |
91aac934b3fad727d0428ed0bf2456bff2cccbae | 883 | import FluentProvider
import PostgreSQLProvider
extension Config {
public func setup() throws {
// allow fuzzy conversions for these types
// (add your own types here)
Node.fuzzy = [Row.self, JSON.self, Node.self]
try setupProviders()
try setupPreparations()
}
/// Configure providers
private func setupProviders() throws {
try addProvider(FluentProvider.Provider.self)
try addProvider(PostgreSQLProvider.Provider.self)
}
/// Add all models that should have their
/// schemas prepared before the app boots
private func setupPreparations() throws {
// preparations.append(Post.self)
preparations.append(User.self)
preparations.append(Reminder.self)
preparations.append(Category.self)
preparations.append(Pivot<Reminder, Category>.self)
}
}
| 29.433333 | 59 | 0.664779 |
2926915f2c49929c55d2ecae36f31ceedc15fee5 | 1,076 | //
// CodeSystems.swift
// HealthRecords
//
// Generated from FHIR 4.5.0-a621ed4bdc
// Copyright 2020 Apple Inc.
//
// 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 FMCore
/**
The type of participant.
URL: http://hl7.org/fhir/report-participant-type
ValueSet: http://hl7.org/fhir/ValueSet/report-participant-type
*/
public enum TestReportParticipantType: String, FHIRPrimitiveType {
/// The test execution engine.
case testEngine = "test-engine"
/// A FHIR Client.
case client = "client"
/// A FHIR Server.
case server = "server"
}
| 27.589744 | 76 | 0.72026 |
09dabf9c8537955bb346f7439c0c954780fe7c90 | 7,076 | //
// Copyright (c) 2017. Uber Technologies
//
// 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 Combine
/// The base protocol of all workers that perform a self-contained piece of logic.
///
/// `Worker`s are always bound to an `Interactor`. A `Worker` can only start if its bound `Interactor` is active.
/// It is stopped when its bound interactor is deactivated.
public protocol Working: AnyObject {
/// Starts the `Worker`.
///
/// If the bound `InteractorScope` is active, this method starts the `Worker` immediately. Otherwise the `Worker`
/// will start when its bound `Interactor` scope becomes active.
///
/// - parameter interactorScope: The interactor scope this worker is bound to.
func start(_ interactorScope: InteractorScope)
/// Stops the worker.
///
/// Unlike `start`, this method always stops the worker immediately.
func stop()
/// Indicates if the worker is currently started.
var isStarted: Bool { get }
/// The lifecycle of this worker.
///
/// Subscription to this stream always immediately returns the last event. This stream terminates after the
/// `Worker` is deallocated.
var isStartedStream: AnyPublisher<Bool, Never> { get }
}
/// The base `Worker` implementation.
open class Worker: Working {
/// Indicates if the `Worker` is started.
public final var isStarted: Bool {
isStartedSubject.value
}
/// The lifecycle stream of this `Worker`.
public final var isStartedStream: AnyPublisher<Bool, Never> {
return isStartedSubject
.removeDuplicates()
.eraseToAnyPublisher()
}
/// Initializer.
public init() {
// No-op
}
/// Starts the `Worker`.
///
/// If the bound `InteractorScope` is active, this method starts the `Worker` immediately. Otherwise the `Worker`
/// will start when its bound `Interactor` scope becomes active.
///
/// - parameter interactorScope: The interactor scope this worker is bound to.
public final func start(_ interactorScope: InteractorScope) {
guard !isStarted else {
return
}
stop()
isStartedSubject.send(true)
// Create a separate scope struct to avoid passing the given scope instance, since usually
// the given instance is the interactor itself. If the interactor holds onto the worker without
// de-referencing it when it becomes inactive, there will be a retain cycle.
let weakInteractorScope = WeakInteractorScope(sourceScope: interactorScope)
bind(to: weakInteractorScope)
}
/// Called when the the worker has started.
///
/// Subclasses should override this method and implment any logic that they would want to execute when the `Worker`
/// starts. The default implementation does nothing.
///
/// - parameter interactorScope: The interactor scope this `Worker` is bound to.
open func didStart(_ interactorScope: InteractorScope) {
}
/// Stops the worker.
///
/// Unlike `start`, this method always stops the worker immediately.
public final func stop() {
guard isStarted else {
return
}
isStartedSubject.send(false)
executeStop()
}
/// Called when the worker has stopped.
///
/// Subclasses should override this method abnd implement any cleanup logic that they might want to execute when
/// the `Worker` stops. The default implementation does noting.
///
/// - note: All subscriptions added to the disposable provided in the `didStart` method are automatically disposed
/// when the worker stops.
open func didStop() {
// No-op
}
// MARK: - Private
private let isStartedSubject = CurrentValueSubject<Bool, Never>(false)
fileprivate var cancellable: CompositeCancellable?
private var interactorBindingCancellable: AnyCancellable?
private func bind(to interactorScope: InteractorScope) {
unbindInteractor()
interactorBindingCancellable = interactorScope.isActiveStream
.sink(receiveValue: { [weak self] (isInteractorActive: Bool) in
if isInteractorActive {
if self?.isStarted == true {
self?.executeStart(interactorScope)
}
} else {
self?.executeStop()
}
})
}
private func executeStart(_ interactorScope: InteractorScope) {
cancellable = CompositeCancellable()
didStart(interactorScope)
}
private func executeStop() {
guard let cancellable = cancellable else {
return
}
cancellable.cancel()
self.cancellable = nil
didStop()
}
private func unbindInteractor() {
interactorBindingCancellable?.cancel()
interactorBindingCancellable = nil
}
deinit {
stop()
unbindInteractor()
isStartedSubject.send(completion: .finished)
}
}
/// Worker related `Disposable` extensions.
public extension AnyCancellable {
/// Disposes the subscription based on the lifecycle of the given `Worker`. The subscription is disposed when the
/// `Worker` is stopped.
///
/// If the given worker is stopped at the time this method is invoked, the subscription is immediately terminated.
///
/// - note: When using this composition, the subscription closure may freely retain the `Worker` itself, since the
/// subscription closure is disposed once the `Worker` is stopped, thus releasing the retain cycle before the
/// `worker` needs to be deallocated.
///
/// - parameter worker: The `Worker` to dispose the subscription based on.
@discardableResult
func cancelOnStop(_ worker: Worker) -> AnyCancellable {
if let compositeCancellable = worker.cancellable {
compositeCancellable.insert(self)
} else {
cancel()
print("Subscription immediately terminated, since \(worker) is stopped.")
}
return self
}
}
fileprivate class WeakInteractorScope: InteractorScope {
weak var sourceScope: InteractorScope?
var isActive: Bool {
return sourceScope?.isActive ?? false
}
var isActiveStream: AnyPublisher<Bool, Never> {
sourceScope?.isActiveStream ?? Just(false).eraseToAnyPublisher()
}
fileprivate init(sourceScope: InteractorScope) {
self.sourceScope = sourceScope
}
}
| 33.065421 | 119 | 0.658282 |
8ff6547eec409ab2d573d6ca8381486146336de5 | 627 | //
// CustomButton.swift
// FP_TABLE_GUIDE
//
// Created by 이신우 on 2019/11/15.
// Copyright © 2019 고정아. All rights reserved.
//
import UIKit
class CustomButton: UIButton {
let myLabel:CustomLabel = CustomLabel()
func setMyButton() {
myLabel.frame = self.bounds
// myLabel.myStyle()
self.addSubview(myLabel)
}
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
}
| 17.416667 | 78 | 0.586922 |
ff4a0f20efcf078fc82c714951fed8a2aed370bb | 371 | //
// Currency.swift
// Solera
//
// Created by Manuel on 1/18/17.
// Copyright © 2017 Manuel Escrig. All rights reserved.
//
import RealmSwift
// MARK: Currency model
class Currency: Object {
dynamic var key = ""
dynamic var name = ""
dynamic var rate = 1.0
override class func primaryKey() -> String? {
return "key"
}
}
| 16.130435 | 56 | 0.592992 |
1843e2ce63b01da39e39ca91f6e1d0ef3538815a | 1,771 | //
// ProductTableViewPresenter.swift
// ClassifiedApp
//
// Created by AJ Sagar Parwani on 12/02/2021.
//
import Foundation
import UIKit
protocol ProductPresenter {
func viewDidLoad() -> Void
func getName() -> String?
func getCreatedDate() -> String?
func getPrice() -> Double
func getCurrency() -> String?
func getUID() -> String?
func getImages() -> [String]
var imagesCount: Int { get }
}
class ProductDetailPresenter: NSObject {
private weak var viewController: UIViewController?
private var interactor: ProductInteractor
private var router: ProductRouter
fileprivate var product: Product
init(withViewController: UIViewController, withInteractor: ProductInteractor, withRouter: ProductRouter, withProduct: Product) {
self.viewController = withViewController
self.interactor = withInteractor
self.router = withRouter
self.product = withProduct
}
}
extension ProductDetailPresenter: ProductPresenter {
var imagesCount: Int {
return product.imageUrls?.count ?? 0
}
func viewDidLoad() -> Void {
DispatchQueue.main.async { [weak self] in
self?.viewController?.notifiyDataUpdate(data: nil)
}
}
func getName() -> String? {
return product.name
}
func getCreatedDate() -> String? {
return product.createdDate
}
func getPrice() -> Double {
return self.interactor.getPrice()
}
func getCurrency() -> String? {
return self.interactor.getCurrency()
}
func getUID() -> String? {
return product.uid
}
func getImages() -> [String] {
return product.imageUrls ?? []
}
}
| 22.705128 | 132 | 0.625635 |
264563d5a41c77cee2b35102ad68a596169735ea | 16,782 | /*
* Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0.
* This product includes software developed at Datadog (https://www.datadoghq.com/).
* Copyright 2019-2020 Datadog, Inc.
*/
import XCTest
@testable import Datadog
@testable import DatadogObjc
class UIKitRUMViewsPredicateBridgeTests: XCTestCase {
func testItForwardsCallToObjcPredicate() {
class MockPredicate: DDUIKitRUMViewsPredicate {
var didCallRUMView = false
func rumView(for viewController: UIViewController) -> DDRUMView? {
didCallRUMView = true
return nil
}
}
let objcPredicate = MockPredicate()
let predicateBridge = UIKitRUMViewsPredicateBridge(objcPredicate: objcPredicate)
_ = predicateBridge.rumView(for: mockView)
XCTAssertTrue(objcPredicate.didCallRUMView)
}
}
class DDRUMViewTests: XCTestCase {
func testItCreatesSwiftRUMView() {
let objcRUMView = DDRUMView(name: "name", attributes: ["foo": "bar"])
XCTAssertEqual(objcRUMView.swiftView.name, "name")
XCTAssertEqual((objcRUMView.swiftView.attributes["foo"] as? AnyEncodable)?.value as? String, "bar")
XCTAssertEqual(objcRUMView.name, "name")
XCTAssertEqual((objcRUMView.attributes["foo"] as? AnyEncodable)?.value as? String, "bar")
}
}
class DDRUMUserActionTypeTests: XCTestCase {
func testMappingToSwiftRUMUserActionType() {
XCTAssertEqual(DDRUMUserActionType.tap.swiftType, .tap)
XCTAssertEqual(DDRUMUserActionType.scroll.swiftType, .scroll)
XCTAssertEqual(DDRUMUserActionType.swipe.swiftType, .swipe)
XCTAssertEqual(DDRUMUserActionType.custom.swiftType, .custom)
}
}
class DDRUMErrorSourceTests: XCTestCase {
func testMappingToSwiftRUMErrorSource() {
XCTAssertEqual(DDRUMErrorSource.source.swiftType, .source)
XCTAssertEqual(DDRUMErrorSource.network.swiftType, .network)
XCTAssertEqual(DDRUMErrorSource.webview.swiftType, .webview)
XCTAssertEqual(DDRUMErrorSource.custom.swiftType, .custom)
}
}
class DDRUMResourceKindTests: XCTestCase {
func testMappingToSwiftRUMResourceKind() {
XCTAssertEqual(DDRUMResourceType.image.swiftType, .image)
XCTAssertEqual(DDRUMResourceType.xhr.swiftType, .xhr)
XCTAssertEqual(DDRUMResourceType.beacon.swiftType, .beacon)
XCTAssertEqual(DDRUMResourceType.css.swiftType, .css)
XCTAssertEqual(DDRUMResourceType.document.swiftType, .document)
XCTAssertEqual(DDRUMResourceType.fetch.swiftType, .fetch)
XCTAssertEqual(DDRUMResourceType.font.swiftType, .font)
XCTAssertEqual(DDRUMResourceType.js.swiftType, .js)
XCTAssertEqual(DDRUMResourceType.media.swiftType, .media)
XCTAssertEqual(DDRUMResourceType.other.swiftType, .other)
}
}
class DDRUMMethodTests: XCTestCase {
func testMappingToSwiftRUMMethod() {
XCTAssertEqual(DDRUMMethod.post.swiftType, .post)
XCTAssertEqual(DDRUMMethod.get.swiftType, .get)
XCTAssertEqual(DDRUMMethod.head.swiftType, .head)
XCTAssertEqual(DDRUMMethod.put.swiftType, .put)
XCTAssertEqual(DDRUMMethod.delete.swiftType, .delete)
XCTAssertEqual(DDRUMMethod.patch.swiftType, .patch)
}
}
class DDRUMMonitorTests: XCTestCase {
override func setUp() {
super.setUp()
XCTAssertNil(RUMFeature.instance)
temporaryFeatureDirectories.create()
}
override func tearDown() {
XCTAssertNil(RUMFeature.instance)
temporaryFeatureDirectories.delete()
super.tearDown()
}
func testSendingViewEvents() throws {
RUMFeature.instance = .mockByRecordingRUMEventMatchers(directories: temporaryFeatureDirectories)
defer { RUMFeature.instance?.deinitialize() }
let objcRUMMonitor = DatadogObjc.DDRUMMonitor()
let mockView = createMockView(viewControllerClassName: "FirstViewController")
objcRUMMonitor.startView(viewController: mockView, name: "FirstView", attributes: ["event-attribute1": "foo1"])
objcRUMMonitor.stopView(viewController: mockView, attributes: ["event-attribute2": "foo2"])
objcRUMMonitor.startView(key: "view2", name: "SecondView", attributes: ["event-attribute1": "bar1"])
objcRUMMonitor.stopView(key: "view2", attributes: ["event-attribute2": "bar2"])
let rumEventMatchers = try RUMFeature.waitAndReturnRUMEventMatchers(count: 5)
let viewEvents = rumEventMatchers.filterRUMEvents(ofType: RUMViewEvent.self)
XCTAssertEqual(viewEvents.count, 4)
let event1: RUMViewEvent = try viewEvents[0].model()
let event2: RUMViewEvent = try viewEvents[1].model()
let event3: RUMViewEvent = try viewEvents[2].model()
let event4: RUMViewEvent = try viewEvents[3].model()
XCTAssertEqual(event1.view.name, "FirstView")
XCTAssertEqual(event1.view.url, "FirstViewController")
XCTAssertEqual(event2.view.name, "FirstView")
XCTAssertEqual(event2.view.url, "FirstViewController")
XCTAssertEqual(event3.view.name, "SecondView")
XCTAssertEqual(event3.view.url, "SecondView")
XCTAssertEqual(event4.view.name, "SecondView")
XCTAssertEqual(event4.view.url, "SecondView")
XCTAssertEqual(try viewEvents[1].attribute(forKeyPath: "context.event-attribute1"), "foo1")
XCTAssertEqual(try viewEvents[1].attribute(forKeyPath: "context.event-attribute2"), "foo2")
XCTAssertEqual(try viewEvents[3].attribute(forKeyPath: "context.event-attribute1"), "bar1")
XCTAssertEqual(try viewEvents[3].attribute(forKeyPath: "context.event-attribute2"), "bar2")
}
func testSendingViewEventsWithTiming() throws {
RUMFeature.instance = .mockByRecordingRUMEventMatchers(directories: temporaryFeatureDirectories)
defer { RUMFeature.instance?.deinitialize() }
let objcRUMMonitor = DatadogObjc.DDRUMMonitor()
objcRUMMonitor.startView(viewController: mockView, name: "SomeView", attributes: ["event-attribute1": "foo1"])
objcRUMMonitor.addTiming(name: "timing")
objcRUMMonitor.stopView(viewController: mockView, attributes: ["event-attribute2": "foo2"])
let rumEventMatchers = try RUMFeature.waitAndReturnRUMEventMatchers(count: 3)
let viewEvents = rumEventMatchers.filterRUMEvents(ofType: RUMViewEvent.self)
XCTAssertEqual(viewEvents.count, 3)
let event1: RUMViewEvent = try viewEvents[0].model()
let event2: RUMViewEvent = try viewEvents[1].model()
XCTAssertEqual(event1.view.name, "SomeView")
XCTAssertEqual(event2.view.name, "SomeView")
XCTAssertEqual(try viewEvents.first?.attribute(forKeyPath: "context.event-attribute1"), "foo1")
XCTAssertEqual(try viewEvents.last?.attribute(forKeyPath: "context.event-attribute1"), "foo1")
XCTAssertEqual(try viewEvents.last?.attribute(forKeyPath: "context.event-attribute2"), "foo2")
XCTAssertNotNil(try? viewEvents.last?.timing(named: "timing"))
}
func testSendingResourceEvents() throws {
guard #available(iOS 13, *) else {
return // `URLSessionTaskMetrics` mocking doesn't work prior to iOS 13.0
}
RUMFeature.instance = .mockByRecordingRUMEventMatchers(directories: temporaryFeatureDirectories)
defer { RUMFeature.instance?.deinitialize() }
let objcRUMMonitor = DatadogObjc.DDRUMMonitor()
objcRUMMonitor.startView(viewController: mockView, name: .mockAny(), attributes: [:])
objcRUMMonitor.startResourceLoading(resourceKey: "/resource1", url: URL(string: "https://foo.com/1")!, attributes: ["event-attribute1": "foo1"])
objcRUMMonitor.addResourceMetrics(
resourceKey: "/resource1",
metrics: .mockWith(
taskInterval: .init(start: .mockDecember15th2019At10AMUTC(), end: .mockDecember15th2019At10AMUTC(addingTimeInterval: 2)),
transactionMetrics: [
.mockBySpreadingDetailsBetween(start: .mockDecember15th2019At10AMUTC(), end: .mockDecember15th2019At10AMUTC(addingTimeInterval: 2))
]
),
attributes: ["event-attribute2": "foo2"]
)
objcRUMMonitor.stopResourceLoading(resourceKey: "/resource1", response: .mockAny(), size: nil, attributes: ["event-attribute3": "foo3"])
objcRUMMonitor.startResourceLoading(resourceKey: "/resource2", httpMethod: .get, urlString: "/some/url/2", attributes: [:])
objcRUMMonitor.stopResourceLoading(resourceKey: "/resource2", statusCode: 333, kind: .beacon, size: 142, attributes: [:])
objcRUMMonitor.startResourceLoading(resourceKey: "/resource3", httpMethod: .get, urlString: "/some/url/3", attributes: [:])
objcRUMMonitor.stopResourceLoading(resourceKey: "/resource3", response: .mockAny(), size: 242, attributes: [:])
let rumEventMatchers = try RUMFeature.waitAndReturnRUMEventMatchers(count: 6)
let resourceEvents = rumEventMatchers.filterRUMEvents(ofType: RUMResourceEvent.self)
XCTAssertEqual(resourceEvents.count, 3)
let event1Matcher = resourceEvents[0]
let event1: RUMResourceEvent = try event1Matcher.model()
XCTAssertEqual(event1.resource.url, "https://foo.com/1")
XCTAssertEqual(event1.resource.duration, 2_000_000_000)
XCTAssertNotNil(event1.resource.dns)
XCTAssertEqual(try event1Matcher.attribute(forKeyPath: "context.event-attribute1"), "foo1")
XCTAssertEqual(try event1Matcher.attribute(forKeyPath: "context.event-attribute2"), "foo2")
XCTAssertEqual(try event1Matcher.attribute(forKeyPath: "context.event-attribute3"), "foo3")
let event2Matcher = resourceEvents[1]
let event2: RUMResourceEvent = try event2Matcher.model()
XCTAssertEqual(event2.resource.url, "/some/url/2")
XCTAssertEqual(event2.resource.size, 142)
XCTAssertEqual(event2.resource.type, .beacon)
XCTAssertEqual(event2.resource.statusCode, 333)
let event3: RUMResourceEvent = try resourceEvents[2].model()
XCTAssertEqual(event3.resource.url, "/some/url/3")
XCTAssertEqual(event3.resource.size, 242)
}
func testSendingErrorEvents() throws {
RUMFeature.instance = .mockByRecordingRUMEventMatchers(directories: temporaryFeatureDirectories)
defer { RUMFeature.instance?.deinitialize() }
let objcRUMMonitor = DatadogObjc.DDRUMMonitor()
objcRUMMonitor.startView(viewController: mockView, name: .mockAny(), attributes: [:])
let request: URLRequest = .mockAny()
let error = ErrorMock("error details")
objcRUMMonitor.startResourceLoading(resourceKey: "/resource1", request: request, attributes: ["event-attribute1": "foo1"])
objcRUMMonitor.stopResourceLoadingWithError(
resourceKey: "/resource1", error: error, response: .mockAny(), attributes: ["event-attribute2": "foo2"]
)
objcRUMMonitor.startResourceLoading(resourceKey: "/resource2", request: request, attributes: ["event-attribute1": "foo1"])
objcRUMMonitor.stopResourceLoadingWithError(
resourceKey: "/resource2", errorMessage: "error message", response: .mockAny(), attributes: ["event-attribute2": "foo2"]
)
objcRUMMonitor.addError(error: error, source: .custom, attributes: ["event-attribute1": "foo1"])
objcRUMMonitor.addError(message: "error message", source: .source, stack: "error stack", attributes: [:])
let rumEventMatchers = try RUMFeature.waitAndReturnRUMEventMatchers(count: 9)
let errorEvents = rumEventMatchers.filterRUMEvents(ofType: RUMErrorEvent.self)
XCTAssertEqual(errorEvents.count, 4)
let event1Matcher = errorEvents[0]
let event1: RUMErrorEvent = try event1Matcher.model()
XCTAssertEqual(event1.error.resource?.url, request.url!.absoluteString)
XCTAssertEqual(event1.error.type, "ErrorMock")
XCTAssertEqual(event1.error.message, "error details")
XCTAssertEqual(event1.error.source, .network)
XCTAssertEqual(event1.error.stack, "error details")
XCTAssertEqual(try event1Matcher.attribute(forKeyPath: "context.event-attribute1"), "foo1")
XCTAssertEqual(try event1Matcher.attribute(forKeyPath: "context.event-attribute2"), "foo2")
let event2Matcher = errorEvents[1]
let event2: RUMErrorEvent = try event2Matcher.model()
XCTAssertEqual(event2.error.resource?.url, request.url!.absoluteString)
XCTAssertEqual(event2.error.message, "error message")
XCTAssertEqual(event2.error.source, .network)
XCTAssertNil(event2.error.stack)
XCTAssertEqual(try event2Matcher.attribute(forKeyPath: "context.event-attribute1"), "foo1")
XCTAssertEqual(try event2Matcher.attribute(forKeyPath: "context.event-attribute2"), "foo2")
let event3Matcher = errorEvents[2]
let event3: RUMErrorEvent = try event3Matcher.model()
XCTAssertNil(event3.error.resource)
XCTAssertEqual(event3.error.type, "ErrorMock")
XCTAssertEqual(event3.error.message, "error details")
XCTAssertEqual(event3.error.source, .custom)
XCTAssertEqual(event3.error.stack, "error details")
XCTAssertEqual(try event3Matcher.attribute(forKeyPath: "context.event-attribute1"), "foo1")
let event4Matcher = errorEvents[3]
let event4: RUMErrorEvent = try event4Matcher.model()
XCTAssertEqual(event4.error.message, "error message")
XCTAssertEqual(event4.error.source, .source)
XCTAssertEqual(event4.error.stack, "error stack")
}
func testSendingActionEvents() throws {
RUMFeature.instance = .mockByRecordingRUMEventMatchers(
directories: temporaryFeatureDirectories,
dependencies: .mockWith(
dateProvider: RelativeDateProvider(startingFrom: Date(), advancingBySeconds: 1)
)
)
defer { RUMFeature.instance?.deinitialize() }
let objcRUMMonitor = DatadogObjc.DDRUMMonitor()
objcRUMMonitor.startView(viewController: mockView, name: .mockAny(), attributes: [:])
objcRUMMonitor.addUserAction(type: .tap, name: "tap action", attributes: ["event-attribute1": "foo1"])
objcRUMMonitor.startUserAction(type: .swipe, name: "swipe action", attributes: ["event-attribute1": "foo1"])
objcRUMMonitor.stopUserAction(type: .swipe, name: "swipe action", attributes: ["event-attribute2": "foo2"])
let rumEventMatchers = try RUMFeature.waitAndReturnRUMEventMatchers(count: 4)
let actionEvents = rumEventMatchers.filterRUMEvents(ofType: RUMActionEvent.self)
XCTAssertEqual(actionEvents.count, 3)
let event1Matcher = actionEvents[0]
let event1: RUMActionEvent = try event1Matcher.model()
XCTAssertEqual(event1.action.type, .applicationStart)
let event2Matcher = actionEvents[1]
let event2: RUMActionEvent = try event2Matcher.model()
XCTAssertEqual(event2.action.type, .tap)
XCTAssertEqual(try event2Matcher.attribute(forKeyPath: "context.event-attribute1"), "foo1")
let event3Matcher = actionEvents[2]
let event3: RUMActionEvent = try event3Matcher.model()
XCTAssertEqual(event3.action.type, .swipe)
XCTAssertEqual(try event3Matcher.attribute(forKeyPath: "context.event-attribute1"), "foo1")
XCTAssertEqual(try event3Matcher.attribute(forKeyPath: "context.event-attribute2"), "foo2")
}
func testSendingGlobalAttributes() throws {
RUMFeature.instance = .mockByRecordingRUMEventMatchers(directories: temporaryFeatureDirectories)
defer { RUMFeature.instance?.deinitialize() }
let objcRUMMonitor = DatadogObjc.DDRUMMonitor()
objcRUMMonitor.addAttribute(forKey: "global-attribute1", value: "foo1")
objcRUMMonitor.addAttribute(forKey: "global-attribute2", value: "foo2")
objcRUMMonitor.removeAttribute(forKey: "global-attribute2")
objcRUMMonitor.startView(viewController: mockView, name: .mockAny(), attributes: ["event-attribute1": "foo1"])
let rumEventMatchers = try RUMFeature.waitAndReturnRUMEventMatchers(count: 2)
let viewEvents = rumEventMatchers.filterRUMEvents(ofType: RUMViewEvent.self)
XCTAssertEqual(viewEvents.count, 1)
XCTAssertEqual(try viewEvents[0].attribute(forKeyPath: "context.global-attribute1"), "foo1")
XCTAssertNil(try? viewEvents[0].attribute(forKeyPath: "context.global-attribute2") as String)
XCTAssertEqual(try viewEvents[0].attribute(forKeyPath: "context.event-attribute1"), "foo1")
}
}
| 49.79822 | 152 | 0.709153 |
22e9d0aa529dc6569cfc9b238a13e06f1dc342d0 | 35,588 | // Generated by Lona Compiler 0.8.0
import UIKit
// MARK: - LonaCollectionViewCell
public class LonaCollectionViewCell<T: UIView>: UICollectionViewCell {
// MARK: Lifecycle
override public init(frame: CGRect) {
super.init(frame: frame)
setUpViews()
setUpConstraints()
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Public
public var view: T = T()
public var scrollDirection = UICollectionView.ScrollDirection.vertical
override public func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
layoutIfNeeded()
let preferredLayoutAttributes =
super.preferredLayoutAttributesFitting(layoutAttributes)
preferredLayoutAttributes.bounds = layoutAttributes.bounds
switch scrollDirection {
case .vertical:
preferredLayoutAttributes.bounds.size.height = systemLayoutSizeFitting(
UIView.layoutFittingCompressedSize,
withHorizontalFittingPriority: .required,
verticalFittingPriority: .defaultLow).height
case .horizontal:
preferredLayoutAttributes.bounds.size.width = systemLayoutSizeFitting(
UIView.layoutFittingCompressedSize,
withHorizontalFittingPriority: .defaultLow,
verticalFittingPriority: .required).width
}
return preferredLayoutAttributes
}
// MARK: Private
private func setUpViews() {
contentView.addSubview(view)
}
private func setUpConstraints() {
contentView.translatesAutoresizingMaskIntoConstraints = false
contentView.topAnchor.constraint(equalTo: topAnchor).isActive = true
contentView.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
let width = contentView.widthAnchor.constraint(equalTo: widthAnchor)
width.priority = .required - 1
width.isActive = true
let height = contentView.heightAnchor.constraint(equalTo: heightAnchor)
height.priority = .required - 1
height.isActive = true
view.translatesAutoresizingMaskIntoConstraints = false
view.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true
view.leadingAnchor.constraint(equalTo: contentView.leadingAnchor).isActive = true
view.trailingAnchor.constraint(equalTo: contentView.trailingAnchor).isActive = true
view.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true
}
}
// MARK: - LonaCollectionViewListLayout
public class LonaCollectionViewListLayout: UICollectionViewFlowLayout {
override public init() {
super.init()
self.minimumInteritemSpacing = 0
self.minimumLineSpacing = 0
self.sectionInset = .zero
self.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override public func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
guard let layoutAttributes = super.layoutAttributesForItem(at: indexPath),
let collectionView = collectionView else { return nil }
switch scrollDirection {
case .vertical:
layoutAttributes.bounds.size.width =
collectionView.safeAreaLayoutGuide.layoutFrame.width -
sectionInset.left - sectionInset.right -
collectionView.adjustedContentInset.left - collectionView.adjustedContentInset.right
case .horizontal:
layoutAttributes.bounds.size.height =
collectionView.safeAreaLayoutGuide.layoutFrame.height -
sectionInset.top - sectionInset.bottom -
collectionView.adjustedContentInset.top - collectionView.adjustedContentInset.bottom
}
return layoutAttributes
}
override public func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
guard let superLayoutAttributes = super.layoutAttributesForElements(in: rect) else { return nil }
let computedAttributes = superLayoutAttributes.compactMap { layoutAttribute in
return layoutAttribute.representedElementCategory == .cell
? layoutAttributesForItem(at: layoutAttribute.indexPath)
: layoutAttribute
}
return computedAttributes
}
}
// MARK: - LonaCollectionView
public class LonaCollectionView: UICollectionView,
UICollectionViewDataSource,
UICollectionViewDelegate,
UICollectionViewDelegateFlowLayout {
// MARK: Lifecycle
private override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
parameters = Parameters()
super.init(frame: frame, collectionViewLayout: LonaCollectionViewListLayout())
contentInsetAdjustmentBehavior = .automatic
backgroundColor = .clear
delegate = self
dataSource = self
register(LonaNestedCollectionViewCell.self, forCellWithReuseIdentifier: LonaNestedCollectionViewCell.identifier)
register(NestedBottomLeftLayoutCell.self, forCellWithReuseIdentifier: NestedBottomLeftLayoutCell.identifier)
register(NestedButtonsCell.self, forCellWithReuseIdentifier: NestedButtonsCell.identifier)
register(NestedComponentCell.self, forCellWithReuseIdentifier: NestedComponentCell.identifier)
register(NestedLayoutCell.self, forCellWithReuseIdentifier: NestedLayoutCell.identifier)
register(NestedOptionalsCell.self, forCellWithReuseIdentifier: NestedOptionalsCell.identifier)
register(ImageCroppingCell.self, forCellWithReuseIdentifier: ImageCroppingCell.identifier)
register(LocalAssetCell.self, forCellWithReuseIdentifier: LocalAssetCell.identifier)
register(VectorAssetCell.self, forCellWithReuseIdentifier: VectorAssetCell.identifier)
register(AccessibilityNestedCell.self, forCellWithReuseIdentifier: AccessibilityNestedCell.identifier)
register(AccessibilityTestCell.self, forCellWithReuseIdentifier: AccessibilityTestCell.identifier)
register(AccessibilityVisibilityCell.self, forCellWithReuseIdentifier: AccessibilityVisibilityCell.identifier)
register(ButtonCell.self, forCellWithReuseIdentifier: ButtonCell.identifier)
register(PressableRootViewCell.self, forCellWithReuseIdentifier: PressableRootViewCell.identifier)
register(FillWidthFitHeightCardCell.self, forCellWithReuseIdentifier: FillWidthFitHeightCardCell.identifier)
register(
FitContentParentSecondaryChildrenCell.self,
forCellWithReuseIdentifier: FitContentParentSecondaryChildrenCell.identifier)
register(
FixedParentFillAndFitChildrenCell.self,
forCellWithReuseIdentifier: FixedParentFillAndFitChildrenCell.identifier)
register(FixedParentFitChildCell.self, forCellWithReuseIdentifier: FixedParentFitChildCell.identifier)
register(MultipleFlexTextCell.self, forCellWithReuseIdentifier: MultipleFlexTextCell.identifier)
register(PrimaryAxisCell.self, forCellWithReuseIdentifier: PrimaryAxisCell.identifier)
register(
PrimaryAxisFillNestedSiblingsCell.self,
forCellWithReuseIdentifier: PrimaryAxisFillNestedSiblingsCell.identifier)
register(PrimaryAxisFillSiblingsCell.self, forCellWithReuseIdentifier: PrimaryAxisFillSiblingsCell.identifier)
register(SecondaryAxisCell.self, forCellWithReuseIdentifier: SecondaryAxisCell.identifier)
register(AssignCell.self, forCellWithReuseIdentifier: AssignCell.identifier)
register(IfCell.self, forCellWithReuseIdentifier: IfCell.identifier)
register(OptionalsCell.self, forCellWithReuseIdentifier: OptionalsCell.identifier)
register(RepeatedVectorCell.self, forCellWithReuseIdentifier: RepeatedVectorCell.identifier)
register(VectorLogicCell.self, forCellWithReuseIdentifier: VectorLogicCell.identifier)
register(BorderStyleTestCell.self, forCellWithReuseIdentifier: BorderStyleTestCell.identifier)
register(BorderWidthColorCell.self, forCellWithReuseIdentifier: BorderWidthColorCell.identifier)
register(BoxModelConditionalCell.self, forCellWithReuseIdentifier: BoxModelConditionalCell.identifier)
register(InlineVariantTestCell.self, forCellWithReuseIdentifier: InlineVariantTestCell.identifier)
register(OpacityTestCell.self, forCellWithReuseIdentifier: OpacityTestCell.identifier)
register(ShadowsTestCell.self, forCellWithReuseIdentifier: ShadowsTestCell.identifier)
register(TextAlignmentCell.self, forCellWithReuseIdentifier: TextAlignmentCell.identifier)
register(TextStyleConditionalCell.self, forCellWithReuseIdentifier: TextStyleConditionalCell.identifier)
register(TextStylesTestCell.self, forCellWithReuseIdentifier: TextStylesTestCell.identifier)
register(VisibilityTestCell.self, forCellWithReuseIdentifier: VisibilityTestCell.identifier)
}
public convenience init(
_ parameters: Parameters = Parameters(),
collectionViewLayout layout: UICollectionViewLayout = LonaCollectionViewListLayout()) {
self.init(frame: .zero, collectionViewLayout: layout)
let oldParameters = self.parameters
self.parameters = parameters
parametersDidChange(oldValue: oldParameters)
}
public convenience init(
items: [LonaViewModel] = [],
scrollDirection: UICollectionView.ScrollDirection = .vertical,
padding: UIEdgeInsets = .zero,
itemSpacing: CGFloat = 0,
fixedSize: CGFloat? = nil,
collectionViewLayout layout: UICollectionViewLayout = LonaCollectionViewListLayout()) {
self.init(
Parameters(
items: items,
scrollDirection: scrollDirection,
padding: padding,
itemSpacing: itemSpacing,
fixedSize: fixedSize),
collectionViewLayout: layout)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Public
public var parameters: Parameters {
didSet {
parametersDidChange(oldValue: oldValue)
}
}
public var items: [LonaViewModel] {
get { return parameters.items }
set { parameters.items = newValue }
}
public var scrollDirection: UICollectionView.ScrollDirection {
get { return parameters.scrollDirection }
set { parameters.scrollDirection = newValue }
}
// MARK: Data Source
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return items.count
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let item = items[indexPath.row]
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: item.type, for: indexPath)
let scrollDirection = self.scrollDirection
switch (item.type) {
case LonaNestedCollectionViewCell.identifier:
if let cell = cell as? LonaNestedCollectionViewCell, let item = item as? LonaCollectionView.Model {
cell.parameters = item.parameters
cell.scrollDirection = scrollDirection
cell.view.onSelectItem = onSelectItem
}
case NestedBottomLeftLayoutCell.identifier:
if let cell = cell as? NestedBottomLeftLayoutCell, let item = item as? NestedBottomLeftLayout.Model {
cell.parameters = item.parameters
cell.scrollDirection = scrollDirection
}
case NestedButtonsCell.identifier:
if let cell = cell as? NestedButtonsCell, let item = item as? NestedButtons.Model {
cell.parameters = item.parameters
cell.scrollDirection = scrollDirection
}
case NestedComponentCell.identifier:
if let cell = cell as? NestedComponentCell, let item = item as? NestedComponent.Model {
cell.parameters = item.parameters
cell.scrollDirection = scrollDirection
}
case NestedLayoutCell.identifier:
if let cell = cell as? NestedLayoutCell, let item = item as? NestedLayout.Model {
cell.parameters = item.parameters
cell.scrollDirection = scrollDirection
}
case NestedOptionalsCell.identifier:
if let cell = cell as? NestedOptionalsCell, let item = item as? NestedOptionals.Model {
cell.parameters = item.parameters
cell.scrollDirection = scrollDirection
}
case ImageCroppingCell.identifier:
if let cell = cell as? ImageCroppingCell, let item = item as? ImageCropping.Model {
cell.parameters = item.parameters
cell.scrollDirection = scrollDirection
}
case LocalAssetCell.identifier:
if let cell = cell as? LocalAssetCell, let item = item as? LocalAsset.Model {
cell.parameters = item.parameters
cell.scrollDirection = scrollDirection
}
case VectorAssetCell.identifier:
if let cell = cell as? VectorAssetCell, let item = item as? VectorAsset.Model {
cell.parameters = item.parameters
cell.scrollDirection = scrollDirection
}
case AccessibilityNestedCell.identifier:
if let cell = cell as? AccessibilityNestedCell, let item = item as? AccessibilityNested.Model {
cell.parameters = item.parameters
cell.scrollDirection = scrollDirection
}
case AccessibilityTestCell.identifier:
if let cell = cell as? AccessibilityTestCell, let item = item as? AccessibilityTest.Model {
cell.parameters = item.parameters
cell.scrollDirection = scrollDirection
}
case AccessibilityVisibilityCell.identifier:
if let cell = cell as? AccessibilityVisibilityCell, let item = item as? AccessibilityVisibility.Model {
cell.parameters = item.parameters
cell.scrollDirection = scrollDirection
}
case ButtonCell.identifier:
if let cell = cell as? ButtonCell, let item = item as? Button.Model {
cell.parameters = item.parameters
cell.scrollDirection = scrollDirection
cell.view.isEnabled = false
}
case PressableRootViewCell.identifier:
if let cell = cell as? PressableRootViewCell, let item = item as? PressableRootView.Model {
cell.parameters = item.parameters
cell.scrollDirection = scrollDirection
cell.view.isRootControlTrackingEnabled = false
}
case FillWidthFitHeightCardCell.identifier:
if let cell = cell as? FillWidthFitHeightCardCell, let item = item as? FillWidthFitHeightCard.Model {
cell.parameters = item.parameters
cell.scrollDirection = scrollDirection
}
case FitContentParentSecondaryChildrenCell.identifier:
if
let cell = cell as? FitContentParentSecondaryChildrenCell, let item = item as? FitContentParentSecondaryChildren.Model
{
cell.parameters = item.parameters
cell.scrollDirection = scrollDirection
}
case FixedParentFillAndFitChildrenCell.identifier:
if let cell = cell as? FixedParentFillAndFitChildrenCell, let item = item as? FixedParentFillAndFitChildren.Model {
cell.parameters = item.parameters
cell.scrollDirection = scrollDirection
}
case FixedParentFitChildCell.identifier:
if let cell = cell as? FixedParentFitChildCell, let item = item as? FixedParentFitChild.Model {
cell.parameters = item.parameters
cell.scrollDirection = scrollDirection
}
case MultipleFlexTextCell.identifier:
if let cell = cell as? MultipleFlexTextCell, let item = item as? MultipleFlexText.Model {
cell.parameters = item.parameters
cell.scrollDirection = scrollDirection
}
case PrimaryAxisCell.identifier:
if let cell = cell as? PrimaryAxisCell, let item = item as? PrimaryAxis.Model {
cell.parameters = item.parameters
cell.scrollDirection = scrollDirection
}
case PrimaryAxisFillNestedSiblingsCell.identifier:
if let cell = cell as? PrimaryAxisFillNestedSiblingsCell, let item = item as? PrimaryAxisFillNestedSiblings.Model {
cell.parameters = item.parameters
cell.scrollDirection = scrollDirection
}
case PrimaryAxisFillSiblingsCell.identifier:
if let cell = cell as? PrimaryAxisFillSiblingsCell, let item = item as? PrimaryAxisFillSiblings.Model {
cell.parameters = item.parameters
cell.scrollDirection = scrollDirection
}
case SecondaryAxisCell.identifier:
if let cell = cell as? SecondaryAxisCell, let item = item as? SecondaryAxis.Model {
cell.parameters = item.parameters
cell.scrollDirection = scrollDirection
}
case AssignCell.identifier:
if let cell = cell as? AssignCell, let item = item as? Assign.Model {
cell.parameters = item.parameters
cell.scrollDirection = scrollDirection
}
case IfCell.identifier:
if let cell = cell as? IfCell, let item = item as? If.Model {
cell.parameters = item.parameters
cell.scrollDirection = scrollDirection
}
case OptionalsCell.identifier:
if let cell = cell as? OptionalsCell, let item = item as? Optionals.Model {
cell.parameters = item.parameters
cell.scrollDirection = scrollDirection
}
case RepeatedVectorCell.identifier:
if let cell = cell as? RepeatedVectorCell, let item = item as? RepeatedVector.Model {
cell.parameters = item.parameters
cell.scrollDirection = scrollDirection
}
case VectorLogicCell.identifier:
if let cell = cell as? VectorLogicCell, let item = item as? VectorLogic.Model {
cell.parameters = item.parameters
cell.scrollDirection = scrollDirection
}
case BorderStyleTestCell.identifier:
if let cell = cell as? BorderStyleTestCell, let item = item as? BorderStyleTest.Model {
cell.parameters = item.parameters
cell.scrollDirection = scrollDirection
}
case BorderWidthColorCell.identifier:
if let cell = cell as? BorderWidthColorCell, let item = item as? BorderWidthColor.Model {
cell.parameters = item.parameters
cell.scrollDirection = scrollDirection
}
case BoxModelConditionalCell.identifier:
if let cell = cell as? BoxModelConditionalCell, let item = item as? BoxModelConditional.Model {
cell.parameters = item.parameters
cell.scrollDirection = scrollDirection
}
case InlineVariantTestCell.identifier:
if let cell = cell as? InlineVariantTestCell, let item = item as? InlineVariantTest.Model {
cell.parameters = item.parameters
cell.scrollDirection = scrollDirection
}
case OpacityTestCell.identifier:
if let cell = cell as? OpacityTestCell, let item = item as? OpacityTest.Model {
cell.parameters = item.parameters
cell.scrollDirection = scrollDirection
}
case ShadowsTestCell.identifier:
if let cell = cell as? ShadowsTestCell, let item = item as? ShadowsTest.Model {
cell.parameters = item.parameters
cell.scrollDirection = scrollDirection
}
case TextAlignmentCell.identifier:
if let cell = cell as? TextAlignmentCell, let item = item as? TextAlignment.Model {
cell.parameters = item.parameters
cell.scrollDirection = scrollDirection
}
case TextStyleConditionalCell.identifier:
if let cell = cell as? TextStyleConditionalCell, let item = item as? TextStyleConditional.Model {
cell.parameters = item.parameters
cell.scrollDirection = scrollDirection
}
case TextStylesTestCell.identifier:
if let cell = cell as? TextStylesTestCell, let item = item as? TextStylesTest.Model {
cell.parameters = item.parameters
cell.scrollDirection = scrollDirection
}
case VisibilityTestCell.identifier:
if let cell = cell as? VisibilityTestCell, let item = item as? VisibilityTest.Model {
cell.parameters = item.parameters
cell.scrollDirection = scrollDirection
}
default:
break
}
return cell
}
// MARK: Delegate
public var onSelectItem: ((Int) -> Void)?
public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let item = items[indexPath.row]
let cell = cellForItem(at: indexPath)
switch (item.type) {
case ButtonCell.identifier:
if let cell = cell as? ButtonCell {
cell.view.sendActions(for: .touchUpInside)
}
case PressableRootViewCell.identifier:
if let cell = cell as? PressableRootViewCell {
cell.view.sendActions(for: .touchUpInside)
}
default:
break
}
onSelectItem?(indexPath.item)
}
// MARK: Layout
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
switch scrollDirection {
case .horizontal:
return CGSize(width: 50, height: collectionView.safeAreaLayoutGuide.layoutFrame.height)
case .vertical:
return CGSize(width: collectionView.safeAreaLayoutGuide.layoutFrame.width, height: 50)
}
}
// MARK: Scrolling
override public func touchesShouldCancel(in view: UIView) -> Bool {
if view is LonaControl {
return true
}
return super.touchesShouldCancel(in: view)
}
// MARK: Private
private func updateAlwaysBounce(for scrollDirection: ScrollDirection) {
alwaysBounceVertical = scrollDirection == .vertical
alwaysBounceHorizontal = scrollDirection == .horizontal
}
private func parametersDidChange(oldValue: Parameters) {
updateAlwaysBounce(for: parameters.scrollDirection)
contentInset = parameters.padding
switch parameters.scrollDirection {
case .horizontal:
showsHorizontalScrollIndicator = false
case .vertical:
showsHorizontalScrollIndicator = true
}
if let layout = collectionViewLayout as? UICollectionViewFlowLayout {
layout.minimumLineSpacing = parameters.itemSpacing
layout.scrollDirection = parameters.scrollDirection
layout.invalidateLayout()
}
reloadData()
layoutIfNeeded()
contentOffset = CGPoint(
x: contentOffset.x - parameters.padding.left + oldValue.padding.left,
y: contentOffset.y - parameters.padding.top + oldValue.padding.top)
}
}
// MARK: - Parameters
extension LonaCollectionView {
public struct Parameters {
public var items: [LonaViewModel]
public var scrollDirection: UICollectionView.ScrollDirection
public var padding: UIEdgeInsets
public var itemSpacing: CGFloat
public var fixedSize: CGFloat?
public init(
items: [LonaViewModel],
scrollDirection: UICollectionView.ScrollDirection,
padding: UIEdgeInsets,
itemSpacing: CGFloat,
fixedSize: CGFloat? = nil)
{
self.items = items
self.scrollDirection = scrollDirection
self.padding = padding
self.itemSpacing = itemSpacing
self.fixedSize = fixedSize
}
public init() {
self.init(items: [], scrollDirection: .vertical, padding: .zero, itemSpacing: 0)
}
}
}
// MARK: - Model
extension LonaCollectionView {
public struct Model: LonaViewModel {
public var id: String?
public var parameters: Parameters
public var type: String {
return "LonaCollectionView"
}
public init(id: String?, parameters: Parameters) {
self.id = id
self.parameters = parameters
}
public init(_ parameters: Parameters) {
self.parameters = parameters
}
public init(
items: [LonaViewModel],
scrollDirection: UICollectionView.ScrollDirection,
padding: UIEdgeInsets = .zero,
itemSpacing: CGFloat = 0,
fixedSize: CGFloat? = nil)
{
self.init(
Parameters(
items: items,
scrollDirection: scrollDirection,
padding: padding,
itemSpacing: itemSpacing,
fixedSize: fixedSize))
}
public init() {
self.init(items: [], scrollDirection: .vertical)
}
}
}
// MARK: - Cell Classes
public class LonaNestedCollectionViewCell: LonaCollectionViewCell<LonaCollectionView> {
public var parameters: LonaCollectionView.Parameters {
get { return view.parameters }
set { view.parameters = newValue }
}
public static var identifier: String {
return "LonaCollectionView"
}
override public func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
let preferredLayoutAttributes = super.preferredLayoutAttributesFitting(layoutAttributes)
if let fixedSize = parameters.fixedSize {
switch scrollDirection {
case .vertical:
preferredLayoutAttributes.bounds.size.height = fixedSize
case .horizontal:
preferredLayoutAttributes.bounds.size.width = fixedSize
}
}
return preferredLayoutAttributes
}
public override func layoutSubviews() {
super.layoutSubviews()
if (contentView.bounds != view.bounds) {
view.collectionViewLayout.invalidateLayout()
}
}
}
public class NestedBottomLeftLayoutCell: LonaCollectionViewCell<NestedBottomLeftLayout> {
public var parameters: NestedBottomLeftLayout.Parameters {
get { return view.parameters }
set { view.parameters = newValue }
}
public static var identifier: String {
return "NestedBottomLeftLayout"
}
}
public class NestedButtonsCell: LonaCollectionViewCell<NestedButtons> {
public var parameters: NestedButtons.Parameters {
get { return view.parameters }
set { view.parameters = newValue }
}
public static var identifier: String {
return "NestedButtons"
}
}
public class NestedComponentCell: LonaCollectionViewCell<NestedComponent> {
public var parameters: NestedComponent.Parameters {
get { return view.parameters }
set { view.parameters = newValue }
}
public static var identifier: String {
return "NestedComponent"
}
}
public class NestedLayoutCell: LonaCollectionViewCell<NestedLayout> {
public var parameters: NestedLayout.Parameters {
get { return view.parameters }
set { view.parameters = newValue }
}
public static var identifier: String {
return "NestedLayout"
}
}
public class NestedOptionalsCell: LonaCollectionViewCell<NestedOptionals> {
public var parameters: NestedOptionals.Parameters {
get { return view.parameters }
set { view.parameters = newValue }
}
public static var identifier: String {
return "NestedOptionals"
}
}
public class ImageCroppingCell: LonaCollectionViewCell<ImageCropping> {
public var parameters: ImageCropping.Parameters {
get { return view.parameters }
set { view.parameters = newValue }
}
public static var identifier: String {
return "ImageCropping"
}
}
public class LocalAssetCell: LonaCollectionViewCell<LocalAsset> {
public var parameters: LocalAsset.Parameters {
get { return view.parameters }
set { view.parameters = newValue }
}
public static var identifier: String {
return "LocalAsset"
}
}
public class VectorAssetCell: LonaCollectionViewCell<VectorAsset> {
public var parameters: VectorAsset.Parameters {
get { return view.parameters }
set { view.parameters = newValue }
}
public static var identifier: String {
return "VectorAsset"
}
}
public class AccessibilityNestedCell: LonaCollectionViewCell<AccessibilityNested> {
public var parameters: AccessibilityNested.Parameters {
get { return view.parameters }
set { view.parameters = newValue }
}
public static var identifier: String {
return "AccessibilityNested"
}
}
public class AccessibilityTestCell: LonaCollectionViewCell<AccessibilityTest> {
public var parameters: AccessibilityTest.Parameters {
get { return view.parameters }
set { view.parameters = newValue }
}
public static var identifier: String {
return "AccessibilityTest"
}
}
public class AccessibilityVisibilityCell: LonaCollectionViewCell<AccessibilityVisibility> {
public var parameters: AccessibilityVisibility.Parameters {
get { return view.parameters }
set { view.parameters = newValue }
}
public static var identifier: String {
return "AccessibilityVisibility"
}
}
public class ButtonCell: LonaCollectionViewCell<Button> {
public var parameters: Button.Parameters {
get { return view.parameters }
set { view.parameters = newValue }
}
public override var isHighlighted: Bool { didSet { view.isControlPressed = isHighlighted } }
public static var identifier: String {
return "Button"
}
}
public class PressableRootViewCell: LonaCollectionViewCell<PressableRootView> {
public var parameters: PressableRootView.Parameters {
get { return view.parameters }
set { view.parameters = newValue }
}
public override var isHighlighted: Bool { didSet { view.isControlPressed = isHighlighted } }
public static var identifier: String {
return "PressableRootView"
}
}
public class FillWidthFitHeightCardCell: LonaCollectionViewCell<FillWidthFitHeightCard> {
public var parameters: FillWidthFitHeightCard.Parameters {
get { return view.parameters }
set { view.parameters = newValue }
}
public static var identifier: String {
return "FillWidthFitHeightCard"
}
}
public class FitContentParentSecondaryChildrenCell: LonaCollectionViewCell<FitContentParentSecondaryChildren> {
public var parameters: FitContentParentSecondaryChildren.Parameters {
get { return view.parameters }
set { view.parameters = newValue }
}
public static var identifier: String {
return "FitContentParentSecondaryChildren"
}
}
public class FixedParentFillAndFitChildrenCell: LonaCollectionViewCell<FixedParentFillAndFitChildren> {
public var parameters: FixedParentFillAndFitChildren.Parameters {
get { return view.parameters }
set { view.parameters = newValue }
}
public static var identifier: String {
return "FixedParentFillAndFitChildren"
}
}
public class FixedParentFitChildCell: LonaCollectionViewCell<FixedParentFitChild> {
public var parameters: FixedParentFitChild.Parameters {
get { return view.parameters }
set { view.parameters = newValue }
}
public static var identifier: String {
return "FixedParentFitChild"
}
}
public class MultipleFlexTextCell: LonaCollectionViewCell<MultipleFlexText> {
public var parameters: MultipleFlexText.Parameters {
get { return view.parameters }
set { view.parameters = newValue }
}
public static var identifier: String {
return "MultipleFlexText"
}
}
public class PrimaryAxisCell: LonaCollectionViewCell<PrimaryAxis> {
public var parameters: PrimaryAxis.Parameters {
get { return view.parameters }
set { view.parameters = newValue }
}
public static var identifier: String {
return "PrimaryAxis"
}
}
public class PrimaryAxisFillNestedSiblingsCell: LonaCollectionViewCell<PrimaryAxisFillNestedSiblings> {
public var parameters: PrimaryAxisFillNestedSiblings.Parameters {
get { return view.parameters }
set { view.parameters = newValue }
}
public static var identifier: String {
return "PrimaryAxisFillNestedSiblings"
}
}
public class PrimaryAxisFillSiblingsCell: LonaCollectionViewCell<PrimaryAxisFillSiblings> {
public var parameters: PrimaryAxisFillSiblings.Parameters {
get { return view.parameters }
set { view.parameters = newValue }
}
public static var identifier: String {
return "PrimaryAxisFillSiblings"
}
}
public class SecondaryAxisCell: LonaCollectionViewCell<SecondaryAxis> {
public var parameters: SecondaryAxis.Parameters {
get { return view.parameters }
set { view.parameters = newValue }
}
public static var identifier: String {
return "SecondaryAxis"
}
}
public class AssignCell: LonaCollectionViewCell<Assign> {
public var parameters: Assign.Parameters {
get { return view.parameters }
set { view.parameters = newValue }
}
public static var identifier: String {
return "Assign"
}
}
public class IfCell: LonaCollectionViewCell<If> {
public var parameters: If.Parameters {
get { return view.parameters }
set { view.parameters = newValue }
}
public static var identifier: String {
return "If"
}
}
public class OptionalsCell: LonaCollectionViewCell<Optionals> {
public var parameters: Optionals.Parameters {
get { return view.parameters }
set { view.parameters = newValue }
}
public static var identifier: String {
return "Optionals"
}
}
public class RepeatedVectorCell: LonaCollectionViewCell<RepeatedVector> {
public var parameters: RepeatedVector.Parameters {
get { return view.parameters }
set { view.parameters = newValue }
}
public static var identifier: String {
return "RepeatedVector"
}
}
public class VectorLogicCell: LonaCollectionViewCell<VectorLogic> {
public var parameters: VectorLogic.Parameters {
get { return view.parameters }
set { view.parameters = newValue }
}
public static var identifier: String {
return "VectorLogic"
}
}
public class BorderStyleTestCell: LonaCollectionViewCell<BorderStyleTest> {
public var parameters: BorderStyleTest.Parameters {
get { return view.parameters }
set { view.parameters = newValue }
}
public static var identifier: String {
return "BorderStyleTest"
}
}
public class BorderWidthColorCell: LonaCollectionViewCell<BorderWidthColor> {
public var parameters: BorderWidthColor.Parameters {
get { return view.parameters }
set { view.parameters = newValue }
}
public static var identifier: String {
return "BorderWidthColor"
}
}
public class BoxModelConditionalCell: LonaCollectionViewCell<BoxModelConditional> {
public var parameters: BoxModelConditional.Parameters {
get { return view.parameters }
set { view.parameters = newValue }
}
public static var identifier: String {
return "BoxModelConditional"
}
}
public class InlineVariantTestCell: LonaCollectionViewCell<InlineVariantTest> {
public var parameters: InlineVariantTest.Parameters {
get { return view.parameters }
set { view.parameters = newValue }
}
public static var identifier: String {
return "InlineVariantTest"
}
}
public class OpacityTestCell: LonaCollectionViewCell<OpacityTest> {
public var parameters: OpacityTest.Parameters {
get { return view.parameters }
set { view.parameters = newValue }
}
public static var identifier: String {
return "OpacityTest"
}
}
public class ShadowsTestCell: LonaCollectionViewCell<ShadowsTest> {
public var parameters: ShadowsTest.Parameters {
get { return view.parameters }
set { view.parameters = newValue }
}
public static var identifier: String {
return "ShadowsTest"
}
}
public class TextAlignmentCell: LonaCollectionViewCell<TextAlignment> {
public var parameters: TextAlignment.Parameters {
get { return view.parameters }
set { view.parameters = newValue }
}
public static var identifier: String {
return "TextAlignment"
}
}
public class TextStyleConditionalCell: LonaCollectionViewCell<TextStyleConditional> {
public var parameters: TextStyleConditional.Parameters {
get { return view.parameters }
set { view.parameters = newValue }
}
public static var identifier: String {
return "TextStyleConditional"
}
}
public class TextStylesTestCell: LonaCollectionViewCell<TextStylesTest> {
public var parameters: TextStylesTest.Parameters {
get { return view.parameters }
set { view.parameters = newValue }
}
public static var identifier: String {
return "TextStylesTest"
}
}
public class VisibilityTestCell: LonaCollectionViewCell<VisibilityTest> {
public var parameters: VisibilityTest.Parameters {
get { return view.parameters }
set { view.parameters = newValue }
}
public static var identifier: String {
return "VisibilityTest"
}
} | 35.131293 | 165 | 0.738873 |
f7c1753ed4c27eb6217093313ed8bdea071b8264 | 3,613 | //
// MyStocksVC.swift
// ZeusApp
//
// Created by Macbook Pro 15 on 2/3/20.
// Copyright © 2020 SamuelFolledo. All rights reserved.
//
import UIKit
class MyStocksVC: UIViewController {
//MARK: Properties
var stocks: [Stock] = []
//MARK: IBOutlets
@IBOutlet weak var tableView: UITableView!
//MARK: App Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
setupViews()
}
//MARK: Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
switch segue.identifier {
case kSEGUETOSTOCKDETAILSVC:
guard let stock = sender as? Stock else { return }
let vc: StockDetailsVC = (segue.destination as? StockDetailsVC)!
vc.stock = stock
default:
break
}
}
//MARK: Private Methods
fileprivate func setupViews() {
self.title = "My Stocks"
setupTableView()
createTestStocks()
}
fileprivate func setupTableView() {
tableView.register(UINib(nibName: "StockCell", bundle: nil), forCellReuseIdentifier: "stockCell")
tableView.delegate = self
tableView.dataSource = self
tableView.tableFooterView = UIView() //removes extra unpopulated cells
}
fileprivate func createTestStocks() {
let stock1 = Stock(_name: "Bitcoin", _shortName: "BTC", _price: "8,900", _imageUrl: "")
let stock2 = Stock(_name: "Etherium", _shortName: "ETH", _price: "80", _imageUrl: "")
let stock3 = Stock(_name: "Tesla", _shortName: "TSL", _price: "600", _imageUrl: "")
let stock4 = Stock(_name: "Apple", _shortName: "APL", _price: "8,900", _imageUrl: "")
let stock5 = Stock(_name: "Bitcoin", _shortName: "BTC", _price: "8,900", _imageUrl: "")
let stock6 = Stock(_name: "Etherium", _shortName: "ETH", _price: "80", _imageUrl: "")
let stock7 = Stock(_name: "Tesla", _shortName: "TSL", _price: "600", _imageUrl: "")
let stock8 = Stock(_name: "Apple", _shortName: "APL", _price: "8,900", _imageUrl: "")
let stock9 = Stock(_name: "Bitcoin", _shortName: "BTC", _price: "8,900", _imageUrl: "")
let stock10 = Stock(_name: "Etherium", _shortName: "ETH", _price: "80", _imageUrl: "")
let stock11 = Stock(_name: "Tesla", _shortName: "TSL", _price: "600", _imageUrl: "")
let stock12 = Stock(_name: "Apple", _shortName: "APL", _price: "8,900", _imageUrl: "")
stocks.append(contentsOf: [stock1, stock2, stock3, stock4, stock5, stock6, stock7, stock8, stock9, stock10, stock11, stock12])
}
//MARK: IBActions
//MARK: Helpers
}
//MARK: Extensions
extension MyStocksVC: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let stock = stocks[indexPath.row]
self.performSegue(withIdentifier: kSEGUETOSTOCKDETAILSVC, sender: stock)
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 70
}
}
extension MyStocksVC: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return stocks.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: StockCell = tableView.dequeueReusableCell(withIdentifier: "stockCell") as! StockCell
cell.selectionStyle = .none //remove the selection indicator
cell.stock = stocks[indexPath.row]
cell.populateViews(showRank: false)
return cell
}
}
| 37.247423 | 134 | 0.641572 |
f79350662bf5587d42a35a9dd57782f765333407 | 892 | //
// AltoClef.swift
// StaffClef
//
// Created by James Bean on 6/13/16.
//
//
import Geometry
import Path
import Rendering
import PlotView
import StaffModel
public final class AltoClef: StaffClefView {
public override var ornamentAltitude: Double {
return 4 * staffSlotHeight + extenderLength
}
public override var ornament: StyledPath {
let width = staffSlotHeight
let position = Point(x: 0, y: ornamentAltitude)
let path = Path
.square(center: position, width: width)
.rotated(by: Angle(degrees: 45), around: position)
let styling = Styling(
fill: Fill(color: configuration.maskColor),
stroke: Stroke(width: lineWidth, color: configuration.foregroundColor)
)
return StyledPath(frame: frame, path: path, styling: styling)
}
}
| 23.473684 | 82 | 0.625561 |
f8458529e19c704ff8f122b7522070d9351c2a6c | 2,168 | //
// AppDelegate.swift
// Flix
//
// Created by Isaac Avila on 9/11/19.
// Copyright © 2019 Isaac Avila. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.12766 | 285 | 0.754151 |
9c1040df6af848f3457d7fa8ff8426a4657d9681 | 1,191 | import XCTest
@testable import Apollo
public func XCTAssertEqual<T, U>(_ expression1: @autoclosure () throws -> [T : U]?, _ expression2: @autoclosure () throws -> [T : U]?, file: StaticString = #file, line: UInt = #line) rethrows {
let optionalValue1 = try expression1()
let optionalValue2 = try expression2()
let message = {
"(\"\(String(describing: optionalValue1))\") is not equal to (\"\(String(describing: optionalValue2))\")"
}
switch (optionalValue1, optionalValue2) {
case (.none, .none):
break
case let (value1 as NSDictionary, value2 as NSDictionary):
XCTAssertEqual(value1, value2, message(), file: file, line: line)
default:
XCTFail(message(), file: file, line: line)
}
}
public func XCTAssertMatch<Pattern: Matchable>(_ valueExpression: @autoclosure () throws -> Pattern.Base, _ patternExpression: @autoclosure () throws -> Pattern, file: StaticString = #file, line: UInt = #line) rethrows {
let value = try valueExpression()
let pattern = try patternExpression()
let message = {
"(\"\(value)\") does not match (\"\(pattern)\")"
}
if case pattern = value { return }
XCTFail(message(), file: file, line: line)
}
| 35.029412 | 220 | 0.670025 |
e4ddb5dfdeeaae6b3cce71f8455878204e97863c | 410 | //
// ProfileViewController.swift
// Quizzes
//
// Created by Yaz Burrell on 2/1/19.
// Copyright © 2019 Alex Paul. All rights reserved.
//
import UIKit
class ProfileViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = #colorLiteral(red: 0.6000000238, green: 0.6000000238, blue: 0.6000000238, alpha: 1)
}
}
| 17.826087 | 114 | 0.658537 |
2249d701f4af37c9281ae023b1a2354e4e150f72 | 2,952 | //
// AppDelegate.swift
// RxSwiftAPIGithubsExample
//
// Created by Nguyễn Trọng Anh Tuấn on 14/07/2019.
// Copyright © 2019 Cock Developer. All rights reserved.
//
import UIKit
import SwiftyBeaver
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// setting log
// add log destinations. at least one is needed!
let console = ConsoleDestination() // log to Xcode Console
// use custom format and set console output to short time, log level & message
// console.format = "$DHH:mm:ss$d $L $M"
// or use this for JSON output: console.format = "$J"
// add the destinations to SwiftyBeaver
logger.addDestination(console)
logger.enter()
// Override point for customization after application launch.
logger.exit("true")
return true
}
func applicationWillResignActive(_ application: UIApplication) {
logger.enter()
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
logger.exit()
}
func applicationDidEnterBackground(_ application: UIApplication) {
logger.enter()
// 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.
logger.exit()
}
func applicationWillEnterForeground(_ application: UIApplication) {
logger.enter()
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
logger.exit()
}
func applicationDidBecomeActive(_ application: UIApplication) {
logger.enter()
// 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.
logger.exit()
}
func applicationWillTerminate(_ application: UIApplication) {
logger.enter()
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
logger.exit()
}
}
| 43.411765 | 285 | 0.70664 |
d51a42d580909ad6967827ba1ee1db334f994fca | 1,171 | import SwiftUI
struct LandmarkList: View {
@EnvironmentObject var modelData: ModelData
@State private var showFavoritesOnly = false
var filteredLandmarks: [Landmark] {
modelData.landmarks.filter { landmark in
(!showFavoritesOnly || landmark.isFavorite)
}
}
var body: some View {
NavigationView {
List {
Toggle(isOn: $showFavoritesOnly) {
Text("Favorites only")
}
ForEach(filteredLandmarks) { landmark in
NavigationLink {
LandmarkDetail(landmark: landmark)
} label: {
LandmarkRow(landmark: landmark)
}
}
}.navigationTitle("Landmarks")
}
}
}
struct LandmarkList_Previews: PreviewProvider {
static var previews: some View {
ForEach(["iPhone SE (2nd generation)", "iPhone XS Max"], id: \.self) { deviceName in
LandmarkList()
.previewDevice(PreviewDevice(rawValue: deviceName))
.previewDisplayName(deviceName)
}
}
}
| 29.275 | 92 | 0.534586 |
1dfdb26ec1a843f11b7d920a68adc1fb018cb6ae | 1,211 | //
// MessageStore.swift
// MojeyMessage
//
// Created by Todd Bowden on 8/15/19.
// Copyright © 2020 Mojey. All rights reserved.
//
import Foundation
class MessageStore {
static let `default` = MessageStore()
private var processedMessagesUrl: URL
private static func getDocumentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let documentsDirectory = paths[0]
return documentsDirectory
}
init() {
processedMessagesUrl = MessageStore.getDocumentsDirectory().appendingPathComponent("processedMessages.plist")
}
func getProcessedMessageIds() -> [String] {
guard let array = NSArray(contentsOf: processedMessagesUrl) else { return [String]() }
return array as? [String] ?? [String]()
}
func addProcessedMessageId(_ id: String) {
var array = getProcessedMessageIds()
array.insert(id, at: 0)
(array as NSArray).write(to: processedMessagesUrl, atomically: true)
}
func hasMessageBeenProcessed(id: String) -> Bool {
let processedMessageIds = getProcessedMessageIds()
return processedMessageIds.contains(id)
}
}
| 27.522727 | 117 | 0.676301 |
6298b625f5c2f0c2f7b8e37d34acf7f88d1cfef5 | 1,460 | //
// PDLazyListRepository.swift
// PD
//
// Created by Henry on 2019/06/30.
//
public struct PDLazyListRepository<Base> where Base: PDListRepositoryProtocol {
let base: Base
}
public extension PDLazyListRepository {
typealias Map<X> = PDLazyMapListRepository<Base,X>
func map<X>(_ mfx: @escaping (Base.Element) -> X) -> Map<X> {
return PDLazyMapListRepository<Base,X>(base: base, mfx: mfx)
}
}
public struct PDLazyMapListRepository<Base,Element>:
PDListRepositoryProtocol where
Base: PDListRepositoryProtocol {
let base: Base
let mfx: (Base.Element) -> Element
}
public extension PDLazyMapListRepository {
typealias Timeline = PDLazyMapTimeline<Base.Timeline,Step>
typealias Step = PDListStep<Base.Snapshot>.Lazy.MapStep<Element>
typealias Snapshot = LazyMapCollection<Base.Snapshot,Element>
var timeline: Timeline {
let mfx1 = mfx
return Timeline(base: base.timeline, mfx: { s in s.lazyStep.map(mfx1) })
}
var latestOnly: PDLazyMapListRepository {
return PDLazyMapListRepository(base: base.latestOnly, mfx: mfx)
}
func latest(since p: PDTimestamp) -> PDLazyMapListRepository? {
guard let r = base.latest(since: p) else { return nil }
return PDLazyMapListRepository(base: r, mfx: mfx)
}
var startIndex: Int { return base.startIndex }
var endIndex: Int { return base.endIndex }
subscript(_ i: Int) -> Element { return mfx(base[i]) }
}
| 33.953488 | 80 | 0.70137 |
fc90bdc8e1912588d611f45e21e6a53364f0b61c | 549 | //
// TrackViewPopulator.swift
// AlbumFolks
//
// Created by NTW-laptop on 17/02/18.
// Copyright © 2018 carlosmouracorreia. All rights reserved.
//
public class TrackViewPopulator {
public var number: Int
public var title: String
public var album: AlbumViewPopulator
public var lengthStatic: String?
init(album: AlbumViewPopulator, number: Int, title: String, lengthStatic: String?) {
self.album = album
self.number = number
self.title = title
self.lengthStatic = lengthStatic
}
}
| 24.954545 | 88 | 0.673953 |
db794c75ca9e22ef8c5d7ee8ca9794eee841ecdd | 6,949 | //
// BTCTest.swift
// imKeyConnector_Example
//
// Created by joe on 7/16/19.
// Copyright © 2019 CocoaPods. All rights reserved.
//
import Foundation
import imKeyBleLib
class USDTTest:FeatTest{
class func testUSDTSign(handle:UInt) -> TestResult{
// var sucessCount = 0
// var failCount = 0
// var failCaseInfo = [String]()
// let jsonRoot = readJson(resource: "usdttransactiontest.json")
// for (key, value) in jsonRoot {
// if let jsonObject = value as? [String: Any], let utxoArray = jsonObject["utxo"] as? [[String: Any]]{
// let to = jsonObject["to"] as! String
// let amount = jsonObject["amount"] as! Int64
// let fee = jsonObject["fee"] as! Int64
// let propertyId = jsonObject["propertyId"] as! Int
// let payment = jsonObject["payment"] as! String
// let toDis = jsonObject["toDis"] as! String
// let from = jsonObject["from"] as! String
// let feeDis = jsonObject["feeDis"] as! String
// let txHash = jsonObject["txHash"] as! String
//
// var utxos = [UTXO]()
// for item in utxoArray{
// let utxo = UTXO(txHash: item["txHash"] as! String,vout: item["vout"] as! Int,
// amount: item["amount"] as! Int64,address: item["address"] as! String,
// scriptPubKey: item["scriptPubKey"] as! String,
// derivedPath: item["derivedPath"] as? String)
// utxos.append(utxo)
// }
//
// for i in 0...3{
// do {
// let sign = try OmniTransaction.omniSign(utxos: utxos,
// amount: amount,
// fee: fee,
// toAddress: BTCAddress(string:to)!,
// propertyId: propertyId,
// handle: handle,
// network: Network.mainnet,
// pathPrefix: BIP44.btcMainnet + "/",
// payment: payment,
// receiver: toDis,
// sender: from,
// feeDis: feeDis
// )
// if sign.txHash == txHash{
// sucessCount += 1
// break
// }else{
// failCount += 1
// failCaseInfo.append("\(key) \(i) time: Assert fail")
// }
// } catch let e as ImkeyError {
// failCount += 1
// failCaseInfo.append("\(key) \(i) time: \(e.message)")
// }catch{
// failCount += 1
// failCaseInfo.append("\(key) \(i) time: \(error)")
// }
// }
// }
// }
// return TestResult(totalCaseCount: jsonRoot.count, successCaseCount: sucessCount, failCaseCount: failCount, failCaseInfo: failCaseInfo)
return TestResult(totalCaseCount: 0, successCaseCount: 0, failCaseCount: 0, failCaseInfo: ["failCaseInfo"])
}
class func testUSDTSegwitSign(handle:UInt) -> TestResult{
// var sucessCount = 0
// var failCount = 0
// var failCaseInfo = [String]()
// let jsonRoot = readJson(resource: "usdtsegwittransactiontest.json")
// for (key, value) in jsonRoot {
// if let jsonObject = value as? [String: Any], let utxoArray = jsonObject["utxo"] as? [[String: Any]]{
// let to = jsonObject["to"] as! String
// let amount = jsonObject["amount"] as! Int64
// let fee = jsonObject["fee"] as! Int64
// let propertyId = jsonObject["propertyId"] as! Int
// let payment = jsonObject["payment"] as! String
// let toDis = jsonObject["toDis"] as! String
// let from = jsonObject["from"] as! String
// let feeDis = jsonObject["feeDis"] as! String
// let txHash = jsonObject["txHash"] as! String
// let wtxID = jsonObject["wtxID"] as! String
//
// var utxos = [UTXO]()
// for item in utxoArray{
// let utxo = UTXO(txHash: item["txHash"] as! String,vout: item["vout"] as! Int,
// amount: item["amount"] as! Int64,address: item["address"] as! String,
// scriptPubKey: item["scriptPubKey"] as! String,
// derivedPath: item["derivedPath"] as? String)
// utxos.append(utxo)
// }
//
// for i in 0...3{
// do {
//// let changeAddress = try Wallet.getBTCSegwitAddress(handle:handle, version:5, path: BIP44.btcSegwitMainnet + "/1/" + String(changeIdx))
//// let sign = try Wallet.btcSignSegwitTransaction(utxos: utxos,amount: amount,fee: fee,toAddress: BTCAddress(string:to)!,changeAddress: BTCAddress(string:changeAddress)!,handle: handle,network: Network.mainnet,pathPrefix: BIP44.btcSegwitMainnet + "/",payment: payment,receiver: toDis,sender: from,feeDis: feeDis)
//
// let sign = try OmniTransaction.omniSignSegwit(utxos: utxos,
// amount: amount,
// fee: fee,
// toAddress: BTCAddress(string:to)!,
// propertyId: propertyId,
// handle: handle,
// network: Network.mainnet,
// pathPrefix: BIP44.btcSegwitMainnet + "/",
// payment: payment,
// receiver: toDis,
// sender: from,
// feeDis: feeDis
// )
//
// if sign.txHash == txHash && sign.wtxID == wtxID{
// sucessCount += 1
// break
// }else{
// failCount += 1
// failCaseInfo.append("\(key) \(i) time: Assert fail")
// }
// } catch let e as ImkeyError {
// failCount += 1
// failCaseInfo.append("\(key) \(i) time: \(e.message)")
// }catch{
// failCount += 1
// failCaseInfo.append("\(key) \(i) time: \(error)")
// }
// break
// }
// }
// }
// return TestResult(totalCaseCount: jsonRoot.count, successCaseCount: sucessCount, failCaseCount: failCount, failCaseInfo: failCaseInfo)
return TestResult(totalCaseCount: 0, successCaseCount: 0, failCaseCount: 0, failCaseInfo: ["failCaseInfo"])
}
}
| 47.924138 | 325 | 0.471291 |
46eed0e1e4fb70f0287d1b25c93c3e44ad29560e | 2,923 | //
// RegisterView.swift
// LittleManComputer
//
// Created by Thomas J. Rademaker on 4/4/20.
// Copyright © 2020 SparrowTek LLC. All rights reserved.
//
import SwiftUI
struct RegisterView: View {
@EnvironmentObject var appState: AppState
private var registerNumber: Int
init(registerNumber: Int) {
self.registerNumber = registerNumber
}
var body: some View {
if appState.programState.registersCurrentlyBeingEvaluated[registerNumber] ?? false {
return RegisterViewSelected(registerNumber: registerNumber, backgroundColor: Color(Colors.highlightedRegisterBackground), textColor: Color(Colors.highlightedRegisterText), borderColor: Color(Colors.highlightedRegisterBorder))
} else {
return RegisterViewSelected(registerNumber: registerNumber, backgroundColor: Color(Colors.registerBackground), textColor: Color(Colors.registerText), borderColor: Color(Colors.registerBorder))
}
}
}
struct RegisterViewSelected: View {
@EnvironmentObject var appState: AppState
@Environment(\.horizontalSizeClass) var horizontalSizeClass
private var registerNumber: Int
private var backgroundColor: Color
private var textColor: Color
private var borderColor: Color
private var fontSize: CGFloat { horizontalSizeClass == .compact ? 10 : 18 }
private var titleFontSize: CGFloat {horizontalSizeClass == .compact ? 10 : 20 }
private var bottomPadding: CGFloat {
appState.isIpad ? 1 : 1
}
init(registerNumber: Int, backgroundColor: Color, textColor: Color, borderColor: Color) {
self.registerNumber = registerNumber
self.backgroundColor = backgroundColor
self.textColor = textColor
self.borderColor = borderColor
}
var body: some View {
VStack {
Text("\(registerNumber)")
.font(.system(size: titleFontSize))
.minimumScaleFactor(0.75)
.padding(.bottom, bottomPadding)
Button(action: {
self.appState.registerToUpdate = self.registerNumber
}) {
Text(appState.programState.registers[registerNumber].toStringWith3IntegerDigits())
.frame(maxWidth: .infinity, maxHeight: .infinity)
.multilineTextAlignment(.center)
.font(.system(size: fontSize))
.minimumScaleFactor(0.75)
.background(backgroundColor)
.foregroundColor(textColor)
.overlay(
Rectangle()
.stroke(borderColor, lineWidth: 1)
.padding(-2)
)
}
}
}
}
struct RegisterView_Previews: PreviewProvider {
static var previews: some View {
RegisterView(registerNumber: 0).environmentObject(AppState())
}
}
| 37 | 237 | 0.63599 |
1a51d610d78819263b3216d85b8325b2aef0a33d | 960 | //
// ViewController.swift
// GithubTestDemo
//
// Created by K.Yawn Xoan on 3/13/15.
// Copyright (c) 2015 K.Yawn Xoan. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBAction func closeConfirm(sender: UIButton) {
UIAlertView(title: "确认关闭?", message: "确认关闭当前窗口吗?", delegate: self, cancelButtonTitle: "确认").show()
UIAlertView(title: "问你一个问题", message: "你是傻逼吗?", delegate: <#UIAlertViewDelegate?#>, cancelButtonTitle: <#String?#>, otherButtonTitles: <#String#>, <#moreButtonTitles: String#>...)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var cities = ["fuyang","hefei","wuhan"]
var myCity = "KYawn"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 28.235294 | 187 | 0.64375 |
2f9133ca52d823d517bbbf1a58957f9c170b18a1 | 304 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
:as b: C {
struct B<j>(")
var d = compose(v: S.h() {
struct B<T where T: S<T: C {
func a
{
{
{
[k<f : NSObject {
class
case c,
if true
| 17.882353 | 87 | 0.674342 |
388f1eab6dee65f959305c44cd28c6ca26d2be2e | 1,992 | //
// BQTrendingViewController.swift
// YouTube
//
// Created by xiupai on 2017/3/15.
// Copyright © 2017年 QQLS. All rights reserved.
//
import UIKit
private let trendingTopCellReuseID = BQTrendingTopCell.nameOfClass
class BQTrendingViewController: BQBaseCollectionViewController {
override var loadNewDataURL: URL {
get {
return URLLink.trending.link()
}
set {}
}
override var loadMoreDataURL: URL {
get {
return URLLink.home.link()
}
set {}
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
// MARK: - UICollectionViewDataSource
extension BQTrendingViewController {
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return videoList.count + 1
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if 0 == indexPath.item {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: trendingTopCellReuseID, for: indexPath)
return cell
} else {
if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: videoCellReuseID, for: indexPath) as? BQVideoListCell {
cell.videoModel = videoList[indexPath.item - 1]
return cell
}
}
return UICollectionViewCell()
}
}
// MARK: - UICollectionViewDelegateFlowLayout
extension BQTrendingViewController {
override func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if 0 == indexPath.item {
return CGSize(width: collectionView.width, height: 60)
} else {
return super.collectionView(collectionView, layout: collectionViewLayout, sizeForItemAt: indexPath)
}
}
}
| 30.646154 | 169 | 0.667169 |
2126c49c0487a3dd31f74929a4286f66cdbcf014 | 1,601 | //
// DownloadAnimationView.swift
// WTestToolKit
//
// Created by Jefferson de Souza Batista on 24/07/21.
//
import Lottie
import SnapKit
extension DownloadAnimationView {
struct Appearance: UIGridPT {}
}
public class DownloadAnimationView: UIView {
fileprivate let appearance = Appearance()
// MARK: Do Lottie reference View
var animationView = AnimationView()
// MARK: Do Animation Var
private lazy var animation: AnimationView = {
let animation = Animation.named("download-from-cloud", bundle: Bundle(for: DownloadAnimationView.self))
animationView.animation = animation
animationView.loopMode = .loop
return animationView
}()
// MARK: Do Init
override init(frame: CGRect = CGRect.zero) {
super.init(frame: frame)
commonInit()
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Do Start Animation
public func startAnimation() {
animationView.play()
}
// MARK: Do Stop Animation
public func stopAnimation() {
animation.removeFromSuperview()
animationView.stop()
}
// MARK: Do Common Init
func commonInit() {
addSubviews()
makeConstraints()
}
// MARK: Do Add Subviews
func addSubviews() {
addSubview(animation)
}
// MARK: Do Constraints
func makeConstraints() {
animation.snp.makeConstraints {
$0.centerY.centerX.equalToSuperview()
$0.size.equalTo(appearance.xxxlSize)
}
}
}
| 20.792208 | 111 | 0.63148 |
e2cee87a67322d5e257205dc5e2692b2cf3dbd4d | 217 | //
// TimeZone+LSFoundation.swift
// LSFoundation
//
import Foundation
public extension TimeZone {
/// Convenience initializer for UTC time
static var UTC: TimeZone? {
return TimeZone(identifier: "UTC")
}
}
| 14.466667 | 41 | 0.714286 |
399020f631f8275796da435e1c04bd327cf7d1bf | 15,218 | //
// TDMUserLoginViewController.swift
// Tadaima
//
// Created by Dustyn August on 8/23/19.
// Copyright © 2019 Dustyn August. All rights reserved.
//
import Foundation
import UIKit
import FirebaseAuth
import FirebaseFirestore
import MBProgressHUD
class TDMUserLoginViewController: UIViewController {
static func storyboardInstance() -> TDMUserLoginViewController? {
let storyboard = UIStoryboard(name: StoryboardKeys.UserLoginSignup, bundle: nil)
return storyboard.instantiateViewController(withIdentifier: String(describing: TDMUserLoginViewController.self)) as? TDMUserLoginViewController
}
private let keyboardAwareBottomLayoutGuide: UILayoutGuide = UILayoutGuide()
private var keyboardTopAnchorConstraint: NSLayoutConstraint!
let containerView: UIView = {
let view = UIView()
view.backgroundColor = .clear
view.translatesAutoresizingMaskIntoConstraints = false
view.layer.cornerRadius = 6
view.layer.masksToBounds = false
return view
}()
let inputsContainerView: UIView = {
let view = UIView()
view.backgroundColor = .white
view.translatesAutoresizingMaskIntoConstraints = false
view.layer.cornerRadius = 6
view.layer.masksToBounds = false
return view
}()
let loginButton: UIButton = {
let button = UIButton(type: .roundedRect)
button.setTitle("Login", for: .normal)
button.setTitleColor(.white, for: .normal)
button.backgroundColor = .lightGray
button.addTarget(self, action: #selector(loginButtonTapped), for: .touchUpInside)
button.layer.cornerRadius = 6
button.translatesAutoresizingMaskIntoConstraints = false
return button
}()
let emailTextField: UITextField = {
let textField = UITextField()
textField.textColor = .coolBlue
textField.keyboardType = .emailAddress
textField.attributedPlaceholder = NSAttributedString(string: "email",
attributes: [NSAttributedString.Key.foregroundColor: UIColor.coolBlue])
textField.translatesAutoresizingMaskIntoConstraints = false
textField.autocapitalizationType = .none
textField.autocorrectionType = .no
textField.spellCheckingType = .no
return textField
}()
let passwordTextField: UITextField = {
let textField = UITextField()
textField.textColor = .coolBlue
textField.attributedPlaceholder = NSAttributedString(string: "password",
attributes: [NSAttributedString.Key.foregroundColor: UIColor.coolBlue])
textField.translatesAutoresizingMaskIntoConstraints = false
textField.isSecureTextEntry = true
textField.autocapitalizationType = .none
textField.autocorrectionType = .no
textField.spellCheckingType = .no
return textField
}()
let separatorView: UIView = {
let view = UIView()
view.backgroundColor = .coolBlue
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
lazy var gestureRecognizer: UISwipeGestureRecognizer = {
let gestureRecognizer = UISwipeGestureRecognizer()
gestureRecognizer.direction = .down
gestureRecognizer.addTarget(self, action: #selector(respondTo(gesture:)))
return gestureRecognizer
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .coolBlue
self.navigationItem.title = "Login User"
self.navigationController?.navigationBar.barTintColor = self.view.backgroundColor
setupUI()
setupNotificationCenter()
setupGestureRecognizer()
}
override func viewDidAppear(_ animated: Bool) {
print("TDMUserLoginViewController: viewDidAppear")
print("Current user: \(String(describing: Auth.auth().currentUser?.email))")
}
private func setupUI() {
setupKeyboardAwareBottomLayoutGuide()
self.view.addSubview(containerView)
setupContainerViewConstraints()
self.view.addSubview(inputsContainerView)
setupInputsContainerView()
self.view.addSubview(loginButton)
setupLoginButtonConstraints()
}
private func setupKeyboardAwareBottomLayoutGuide() {
self.view.addLayoutGuide(self.keyboardAwareBottomLayoutGuide)
// this will control keyboardAwareBottomLayoutGuide.topAnchor to be so far from bottom of the bottom as is the height of the presented keyboard
self.keyboardTopAnchorConstraint = self.view.layoutMarginsGuide.bottomAnchor.constraint(equalTo: keyboardAwareBottomLayoutGuide.topAnchor, constant: 0)
self.keyboardTopAnchorConstraint.isActive = true
self.keyboardAwareBottomLayoutGuide.bottomAnchor.constraint(equalTo: view.layoutMarginsGuide.bottomAnchor).isActive = true
}
private func setupContainerViewConstraints() {
containerView.heightAnchor.constraint(equalToConstant: 212).isActive = true
containerView.widthAnchor.constraint(equalTo: self.view.widthAnchor, constant: -24).isActive = true
containerView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
containerView.bottomAnchor.constraint(equalTo: keyboardAwareBottomLayoutGuide.topAnchor).isActive = true
}
private func setupInputsContainerView() {
setupInputsContainerViewConstraints()
inputsContainerView.addSubview(emailTextField)
setupEmailTextFieldConstraints()
inputsContainerView.addSubview(separatorView)
setupSeparatorViewConstraints()
inputsContainerView.addSubview(passwordTextField)
setupPasswordTextFieldConstraints()
}
private func setupInputsContainerViewConstraints() {
inputsContainerView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
inputsContainerView.topAnchor.constraint(equalTo: containerView.topAnchor).isActive = true
inputsContainerView.widthAnchor.constraint(equalTo: self.view.widthAnchor, constant: -24).isActive = true
inputsContainerView.heightAnchor.constraint(equalToConstant: 150).isActive = true
}
private func setupEmailTextFieldConstraints() {
emailTextField.delegate = self
emailTextField.leftAnchor.constraint(equalTo: inputsContainerView.leftAnchor, constant: 12).isActive = true
emailTextField.rightAnchor.constraint(equalTo: inputsContainerView.rightAnchor, constant: -12).isActive = true
emailTextField.topAnchor.constraint(equalTo: inputsContainerView.topAnchor).isActive = true
emailTextField.heightAnchor.constraint(equalTo: inputsContainerView.heightAnchor, multiplier: 1/2).isActive = true
}
private func setupSeparatorViewConstraints() {
separatorView.leftAnchor.constraint(equalTo: inputsContainerView.leftAnchor).isActive = true
separatorView.topAnchor.constraint(equalTo: emailTextField.bottomAnchor).isActive = true
separatorView.widthAnchor.constraint(equalTo: inputsContainerView.widthAnchor).isActive = true
separatorView.heightAnchor.constraint(equalToConstant: 1).isActive = true
}
private func setupPasswordTextFieldConstraints() {
passwordTextField.delegate = self
passwordTextField.leftAnchor.constraint(equalTo: inputsContainerView.leftAnchor, constant: 12).isActive = true
passwordTextField.rightAnchor.constraint(equalTo: inputsContainerView.rightAnchor, constant: -12).isActive = true
passwordTextField.topAnchor.constraint(equalTo: emailTextField.bottomAnchor).isActive = true
passwordTextField.heightAnchor.constraint(equalTo: inputsContainerView.heightAnchor, multiplier: 1/2).isActive = true
}
private func setupLoginButtonConstraints() {
loginButton.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
loginButton.topAnchor.constraint(equalTo: inputsContainerView.bottomAnchor, constant: 12).isActive = true
loginButton.widthAnchor.constraint(equalTo: inputsContainerView.widthAnchor).isActive = true
loginButton.heightAnchor.constraint(equalToConstant: 50).isActive = true
}
private func setupNotificationCenter() {
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShowNotification(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHideNotification(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)
}
@objc
private func keyboardWillShowNotification(notification: NSNotification) {
updateKeyboardAwareBottomLayoutGuide(with: notification, hiding: false)
}
@objc
private func keyboardWillHideNotification(notification: NSNotification) {
updateKeyboardAwareBottomLayoutGuide(with: notification, hiding: true)
}
private func updateKeyboardAwareBottomLayoutGuide(with notification: NSNotification, hiding: Bool) {
let userInfo = notification.userInfo
let animationDuration = (userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue
let keyboardEndFrame = (userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue
let rawAnimationCurve = (userInfo?[UIResponder.keyboardAnimationCurveUserInfoKey] as? NSNumber)?.uint32Value
guard let animDuration = animationDuration,
let keybrdEndFrame = keyboardEndFrame,
let rawAnimCurve = rawAnimationCurve else {
return
}
let convertedKeyboardEndFrame = view.convert(keybrdEndFrame, from: view.window)
let rawAnimCurveAdjusted = UInt(rawAnimCurve << 16)
let animationCurve = UIView.AnimationOptions(rawValue: rawAnimCurveAdjusted)
// this will move the topAnchor of the keyboardAwareBottomLayoutGuide to height of the keyboard
self.keyboardTopAnchorConstraint.constant = hiding ? 0 : convertedKeyboardEndFrame.size.height
self.view.setNeedsLayout()
UIView.animate(withDuration: animDuration, delay: 0.0, options: [.beginFromCurrentState, animationCurve], animations: {
self.view.layoutIfNeeded()
self.setupContainerViewConstraints()
self.setupInputsContainerViewConstraints()
self.setupEmailTextFieldConstraints()
self.setupSeparatorViewConstraints()
self.setupPasswordTextFieldConstraints()
}, completion: { success in
})
}
@objc func loginButtonTapped(sender: UIButton) {
guard let email = emailTextField.text,
let password = passwordTextField.text
else {
//TODO: Create an alert
print("Form is not valid.")
return
}
MBProgressHUD.showAdded(to: self.view, animated: true)
TDMUser.loginUser(email: email, password: password) { (error) in
if let error = error {
print(error)
let alert = UIAlertController(title: "User Sign Up Failed", message: error.localizedDescription, preferredStyle: .alert)
//TODO: MAY want to use the handler
alert.addAction(UIAlertAction(title: "Dismiss", style: .cancel, handler: { [weak self] action in
self?.emailTextField.text = ""
self?.passwordTextField.text = ""
self?.emailTextField.becomeFirstResponder()
}))
return
}
guard let window = UIApplication.shared.keyWindow, let rootViewController = window.rootViewController else { return }
guard let user = Auth.auth().currentUser else { return }
TDMUser.getHomeName(for: user) { (homeName, error) in
if let error = error {
print(error)
return
}
let viewController: UIViewController?
if homeName == "" {
viewController = TDMHomeWelcomeViewController.storyboardInstance()
} else {
viewController = TDMMainScreenViewController.storyboardInstance()
}
guard let newVC = viewController else { return }
let navigationController = UINavigationController(rootViewController: newVC)
navigationController.view.frame = rootViewController.view.frame
navigationController.view.layoutIfNeeded()
MBProgressHUD.hide(for: self.view, animated: true)
UIView.transition(with: window, duration: 0.5, options: .transitionFlipFromRight, animations: {
window.rootViewController = navigationController
}, completion: { completed in
// maybe do something here
})
}
}
}
private func setupGestureRecognizer() {
self.view.addGestureRecognizer(gestureRecognizer)
}
@objc
private func respondTo(gesture: UIGestureRecognizer) {
guard let swipeGesture = gesture as? UISwipeGestureRecognizer else { return }
switch swipeGesture.direction {
case UISwipeGestureRecognizer.Direction.right:
print("Swiped right")
case UISwipeGestureRecognizer.Direction.down:
print("Swiped down")
self.view.endEditing(true)
case UISwipeGestureRecognizer.Direction.left:
print("Swiped left")
case UISwipeGestureRecognizer.Direction.up:
print("Swiped up")
default:
break
}
}
}
extension UIColor {
convenience init(r:CGFloat, g: CGFloat, b: CGFloat) {
self.init(red: r/255,green: g/255, blue: b/255, alpha:1)
}
static let coolBlue = UIColor(r: 26, g: 152, b: 210)
}
extension TDMUserLoginViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField == emailTextField {
passwordTextField.becomeFirstResponder()
return false
} else if textField == passwordTextField {
textField.resignFirstResponder()
return false
}
return true
}
}
| 44.367347 | 179 | 0.657379 |
4b40dbf497ec228d3efccfc218ccfcf782faf73c | 1,625 | import Cocoa
class NewTagOpController: OperationController
{
override func start() throws
{
let panelController = TagPanelController.controller()
guard let selectedSHA = windowController?.selection?.shaToSelect,
let selectedOID = repository?.oid(forSHA: selectedSHA),
let repository = repository,
let commit = repository.commit(forSHA: selectedSHA)
else { throw XTRepository.Error.unexpected }
let config = repository.config!
let userName = config.userName
let userEmail = config.userEmail
panelController.commitMessage = commit.message ?? selectedSHA
panelController.signature = "\(userName ?? "") <\(userEmail ?? "")>"
windowController?.window?.beginSheet(panelController.window!) {
(response) in
if response == .OK {
self.executeTag(name: panelController.tagName,
oid: selectedOID,
message: panelController.lightweight ?
nil : panelController.message)
}
else {
self.ended()
}
}
}
func executeTag(name: String, oid: OID, message: String?)
{
guard let repository = self.repository
else { return }
tryRepoOperation {
if let message = message {
try? repository.createTag(name: name, targetOID: oid, message: message)
}
else {
try? repository.createLightweightTag(name: name, targetOID: oid)
}
NotificationCenter.default.post(name: .XTRepositoryRefsChanged,
object: repository)
self.ended()
}
}
}
| 31.862745 | 79 | 0.619077 |
f7dfed348fb60ab9aa3a996cf99a86e4fd8610a5 | 4,318 | // swiftlint:disable all
// Generated using SwiftGen — https://github.com/SwiftGen/SwiftGen
#if os(OSX)
import AppKit.NSFont
internal typealias Font = NSFont
#elseif os(iOS) || os(tvOS) || os(watchOS)
import UIKit.UIFont
internal typealias Font = UIFont
#endif
// swiftlint:disable superfluous_disable_command
// swiftlint:disable file_length
// MARK: - Fonts
// swiftlint:disable identifier_name line_length type_body_length
internal enum FontFamily {
internal enum Inconsolata {
internal static let bold = FontConvertible(name: "Inconsolata-Bold", family: "Inconsolata", path: "inconsolata-bold.ttf")
internal static let regular = FontConvertible(name: "Inconsolata-Regular", family: "Inconsolata", path: "inconsolata-regular.ttf")
internal static let all: [FontConvertible] = [bold, regular]
}
internal enum Lato {
internal static let black = FontConvertible(name: "Lato-Black", family: "Lato", path: "lato-black.ttf")
internal static let bold = FontConvertible(name: "Lato-Bold", family: "Lato", path: "lato-bold.ttf")
internal static let light = FontConvertible(name: "Lato-Light", family: "Lato", path: "lato-light.ttf")
internal static let regular = FontConvertible(name: "Lato-Regular", family: "Lato", path: "lato-regular.ttf")
internal static let all: [FontConvertible] = [black, bold, light, regular]
}
internal enum OpenSans {
internal static let bold = FontConvertible(name: "OpenSans-Bold", family: "Open Sans", path: "opensans-bold.ttf")
internal static let extraBold = FontConvertible(name: "OpenSans-ExtraBold", family: "Open Sans", path: "opensans-extrabold.ttf")
internal static let italic = FontConvertible(name: "OpenSans-Italic", family: "Open Sans", path: "opensans-italic.ttf")
internal static let light = FontConvertible(name: "OpenSans-Light", family: "Open Sans", path: "opensans-light.ttf")
internal static let regular = FontConvertible(name: "OpenSans-Regular", family: "Open Sans", path: "opensans-regular.ttf")
internal static let semiBold = FontConvertible(name: "OpenSans-SemiBold", family: "Open Sans", path: "opensans-semibold.ttf")
internal static let all: [FontConvertible] = [bold, extraBold, italic, light, regular, semiBold]
}
internal enum Overpass {
internal static let regular = FontConvertible(name: "Overpass-Regular", family: "Overpass", path: "overpass-regular.ttf")
internal static let all: [FontConvertible] = [regular]
}
internal enum OverpassExtraBold {
internal static let regular = FontConvertible(name: "Overpass-ExtraBold", family: "Overpass ExtraBold", path: "overpass-extrabold.ttf")
internal static let all: [FontConvertible] = [regular]
}
internal enum OverpassLight {
internal static let regular = FontConvertible(name: "Overpass-Light", family: "Overpass Light", path: "overpass-light.ttf")
internal static let all: [FontConvertible] = [regular]
}
internal static let allCustomFonts: [FontConvertible] = [Inconsolata.all, Lato.all, OpenSans.all, Overpass.all, OverpassExtraBold.all, OverpassLight.all].flatMap { $0 }
internal static func registerAllCustomFonts() {
allCustomFonts.forEach { $0.register() }
}
}
// swiftlint:enable identifier_name line_length type_body_length
// MARK: - Implementation Details
internal struct FontConvertible {
internal let name: String
internal let family: String
internal let path: String
internal func font(size: CGFloat) -> Font! {
return Font(font: self, size: size)
}
internal func register() {
// swiftlint:disable:next conditional_returns_on_newline
guard let url = url else { return }
CTFontManagerRegisterFontsForURL(url as CFURL, .process, nil)
}
fileprivate var url: URL? {
let bundle = Bundle(for: BundleToken.self)
return bundle.url(forResource: path, withExtension: nil)
}
}
internal extension Font {
convenience init!(font: FontConvertible, size: CGFloat) {
#if os(iOS) || os(tvOS) || os(watchOS)
if !UIFont.fontNames(forFamilyName: font.family).contains(font.name) {
font.register()
}
#elseif os(OSX)
if let url = font.url, CTFontManagerGetScopeForURL(url as CFURL) == .none {
font.register()
}
#endif
self.init(name: font.name, size: size)
}
}
private final class BundleToken {}
| 43.616162 | 170 | 0.723483 |
5b100e20b1dd856975bd2e060bb704ed2fed3112 | 2,682 | //
// ViewController.swift
// RxSwiftCollections
//
// Created by Mike Roberts on 05/19/2018.
// Copyright (c) 2018 Mike Roberts. All rights reserved.
//
import UIKit
import RxSwift
import RxSwiftCollections
extension Array {
mutating func shuffle() {
for _ in 0..<(!isEmpty ? (count - 1) : 0) {
sort { (_, _) in arc4random() < arc4random() }
}
}
}
class ViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
fileprivate let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
let cellNib = UINib(nibName: "DemoTableViewCell", bundle: nil)
tableView.register(cellNib, forCellReuseIdentifier: "Demo")
self.setup()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
func randomInt(_ upperBound: Int) -> Int {
return Int(arc4random_uniform(UInt32(upperBound)))
}
extension ViewController {
func setup() {
let removeCount = 100
let upperBound = 1000
let original = Array([Int](1...upperBound))
let randomIntStream = Observable<Int>
.interval(2.0, scheduler: ConcurrentDispatchQueueScheduler(qos: .background))
.scan(original, accumulator: { (previous, _) -> [Int] in
var next = Array(previous)
// remove some numbers
for _ in 0...randomInt(removeCount) {
next.remove(at: randomInt(next.count))
}
// add some numbers back
let additions = original.filter({ (number) -> Bool in !previous.contains(number) })
if !additions.isEmpty {
for i in 0...randomInt(additions.count) {
let position = randomInt(next.count)
next.insert(additions[i], at: position)
}
}
return next
})
.asObservable()
ObservableList<Int>
.diff(randomIntStream)
.map { "\($0)" }
.bind(to: self.tableView,
reusing: "Demo",
with: { (cell, text) -> DemoTableViewCell in
cell.titleLabel.text = text
return cell
}, onSelected: { text in
print("selected: \(text)")
}, onUpdatesCompleted: { (_) in
print("updates completed")
})
.disposed(by: disposeBag)
}
}
| 29.152174 | 99 | 0.515287 |
38898abe7d1b58be74301cfd1d8c95b842f24197 | 819 | /// The interface for accessing the server API.
public protocol ServerWorkerInterface {
/**
Performs a server request.
The endpoint URL will be created from the provided request object.
When the server returns no data or a status code not equal to 200 then a failure with `ServerWorkerError.server` is returned.
When data is returned, but can't be decoded into the type defined by the request's `Response` type a failure with `ServerWorkerError.decoding` is returned.
If no error occured then a success with the decoded data is returned.
- parameter request: The request to perform.
- parameter completion: The callback informing about the request's result. Will be called on the main thread.
*/
func send<T: ServerRequest>(_ request: T, completion: @escaping ServerResultCallback<T.Response>)
}
| 51.1875 | 157 | 0.769231 |
03d650a0685e2dd565d51fe3c8d2c4949680ceaa | 2,079 | //
// CloneBinaryTreeWithRandomPointerTests.swift
// CodingChallengesTests
//
// Created by William Boles on 10/12/2021.
// Copyright © 2021 Boles. All rights reserved.
//
import XCTest
@testable import LeetCode
class CloneBinaryTreeWithRandomPointerTests: XCTestCase {
// MARK: - Tests
func test_A() {
let data = [[1, nil], nil, [4, 3], [7,0]]
let root = BinaryTreeNodeRandom.deserialize(data)
let clone = CloneBinaryTreeWithRandomPointer.copyRandomBinaryTree(root)
let values = BinaryTreeNodeRandom.serialize(clone)
XCTAssertEqual(values, data)
}
func test_B() {
let data = [[1, 4], nil, [1,0], nil, [1, 5], [1, 5]]
let root = BinaryTreeNodeRandom.deserialize(data)
let clone = CloneBinaryTreeWithRandomPointer.copyRandomBinaryTree(root)
let values = BinaryTreeNodeRandom.serialize(clone)
XCTAssertEqual(values, data)
}
func test_C() {
let data = [[1, 6], [2, 5], [3, 4], [4, 3], [5, 2], [6, 1], [7,0]]
let root = BinaryTreeNodeRandom.deserialize(data)
let clone = CloneBinaryTreeWithRandomPointer.copyRandomBinaryTree(root)
let values = BinaryTreeNodeRandom.serialize(clone)
XCTAssertEqual(values, data)
}
func test_D() {
let data = [[Int?]?]()
let root = BinaryTreeNodeRandom.deserialize(data)
let clone = CloneBinaryTreeWithRandomPointer.copyRandomBinaryTree(root)
let values = BinaryTreeNodeRandom.serialize(clone)
XCTAssertEqual(values, data)
}
func test_E() {
let data = [[1, nil], nil, [2, nil], nil, [1, nil]]
let root = BinaryTreeNodeRandom.deserialize(data)
let clone = CloneBinaryTreeWithRandomPointer.copyRandomBinaryTree(root)
let values = BinaryTreeNodeRandom.serialize(clone)
XCTAssertEqual(values, data)
}
}
| 27 | 79 | 0.593555 |
01792e63ba06c98f92c15e856d1452472ac5d3ce | 2,255 | //
// FileUtil.swift
// StudioApp
//
// Created by user on 2018/8/30.
// Copyright © 2018 ifundit. All rights reserved.
//
import Foundation
class FileUtil {
static func allFiles(path: String, filterTypes: [String]) -> [String] {
do {
let files = try FileManager.default.contentsOfDirectory(atPath: path)
if filterTypes.count == 0 {
return files
} else {
let filteredfiles = NSArray(array: files).pathsMatchingExtensions(filterTypes)
return filteredfiles
}
} catch {
return []
}
}
static func path(name: String) -> String? {
return NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last?.appending(name)
}
static func createFolder(name: String) {
if let path = path(name: name) {
if false == FileManager.default.fileExists(atPath: path) {
try! FileManager.default.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil)
}
}
}
static func delFile(path: String) -> Bool {
do {
try FileManager.default.removeItem(atPath: path)
} catch {
return false
}
return true
}
static func identityForFile(file: String) -> String {
var identity = file
let names = file.components(separatedBy: "-")
if names.count > 1 {
identity = names[0]
} else {
let names = file.components(separatedBy: ".")
if names.count > 1 {
identity = names[0]
}
}
return identity
}
static func copyFile(at: URL) -> String? {
do {
let identity = FileUtil.identityForFile(file: at.lastPathComponent)
if let path = FileUtil.path(name: "/com.mmoaay.findme.routes".appending("/").appending(identity).appending(".fmr")) {
try FileManager.default.copyItem(at: at, to: URL(fileURLWithPath: path))
return path
} else {
return nil
}
} catch {
return nil
}
}
}
| 28.910256 | 129 | 0.54235 |
798b75a2f50309b941a89915cd44896da0f14484 | 1,752 | //
// InfoViewController.swift
// Music Mate
//
// Created by John on 4/2/17.
// Copyright © 2017 Bruce32. All rights reserved.
//
import Cocoa
class InfoViewController: NSViewController {
weak var api: SpotifyAPI?
fileprivate let progressIndicator = NSProgressIndicator()
@IBOutlet fileprivate var nameLabel: NSTextField!
@IBOutlet fileprivate var artistLabel: NSTextField!
@IBOutlet fileprivate var albumLabel: NSTextField!
@IBOutlet fileprivate var albumView: NSImageView!
override func viewDidLoad() {
super.viewDidLoad()
progressIndicator.isDisplayedWhenStopped = false
progressIndicator.style = .spinningStyle
albumView.addSubview(progressIndicator)
}
override func viewWillAppear() {
super.viewWillAppear()
progressIndicator.frame = albumView.bounds
}
}
/// MARK: SongChangeDelegate
extension InfoViewController: SongChangeDelegate {
func songDidChange(_ song: Song) {
self.nameLabel.stringValue = song.name
self.albumLabel.stringValue = song.album.name
if let artist = song.artists.first {
self.artistLabel.stringValue = artist.name
}
// Replace image with an empty clear image of
// the same size to avoid resizing while loading the new one
if let image = self.albumView.image {
let clearImage = NSImage(size: image.size)
clearImage.backgroundColor = .clear
self.albumView.image = clearImage
}
self.progressIndicator.startAnimation(self)
self.api?.image(for: song.album.imageURL) { image in
DispatchQueue.main.async {
self.progressIndicator.stopAnimation(self)
guard
let imageData = image,
let image = NSImage(data: imageData) else {
return
}
self.albumView.image = image
}
}
}
}
| 22.461538 | 62 | 0.72089 |
08c893cde29b3a753752b1e816aa0fc988e921de | 2,950 | //
// AppDelegate.swift
// ConnectionSample
//
// Created by Pawel Kadluczka on 2/26/17.
// Copyright © 2017 Pawel Kadluczka. All rights reserved.
//
import Cocoa
import SignalRClient
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet weak var window: NSWindow!
@IBOutlet weak var openBtn: NSButton!
@IBOutlet weak var sendBtn: NSButton!
@IBOutlet weak var closeBtn: NSButton!
@IBOutlet weak var urlTextField: NSTextField!
@IBOutlet weak var msgTextField: NSTextField!
@IBOutlet weak var logTextField: NSTextField!
@IBOutlet weak var historyTextField: NSTextField!
var echoConnection: Connection?
var echoConnectionDelegate: ConnectionDelegate?
func applicationDidFinishLaunching(_ aNotification: Notification) {
toggleSend(isEnabled: false)
appendLog(string: "Log")
}
func applicationWillTerminate(_ aNotification: Notification) {
echoConnection?.stop(stopError: nil)
}
@IBAction func btnOpen(sender: AnyObject) {
let url = URL(string: urlTextField.stringValue)!
echoConnection = HttpConnection(url: url)
echoConnectionDelegate = EchoConnectionDelegate(app: self)
echoConnection!.delegate = echoConnectionDelegate
echoConnection!.start(transport: nil)
}
@IBAction func btnSend(sender: AnyObject) {
appendLog(string: "Sending: " + msgTextField.stringValue)
echoConnection?.send(data: msgTextField.stringValue.data(using: .utf8)!) { error in
if let e = error {
print(e)
}
}
msgTextField.stringValue = ""
}
@IBAction func btnClose(sender: AnyObject) {
echoConnection?.stop(stopError: nil)
}
func toggleSend(isEnabled: Bool) {
urlTextField.isEnabled = !isEnabled
openBtn.isEnabled = !isEnabled
msgTextField.isEnabled = isEnabled
sendBtn.isEnabled = isEnabled
closeBtn.isEnabled = isEnabled
}
func appendLog(string: String) {
logTextField.stringValue += string + "\n"
}
}
class EchoConnectionDelegate: ConnectionDelegate {
weak var app: AppDelegate?
init(app: AppDelegate) {
self.app = app
}
func connectionDidOpen(connection: Connection!) {
app?.appendLog(string: "Connection started")
app?.toggleSend(isEnabled: true)
}
func connectionDidFailToOpen(error: Error) {
app?.appendLog(string: "Error")
}
func connectionDidReceiveData(connection: Connection!, data: Data) {
app?.appendLog(string: "Received: " + String(data: data, encoding: .utf8)!)
}
func connectionDidClose(error: Error?) {
app?.appendLog(string: "Connection stopped")
if error != nil {
print(error.debugDescription)
app?.appendLog(string: error.debugDescription)
}
app?.toggleSend(isEnabled: false)
}
}
| 28.095238 | 91 | 0.664746 |
6710136d5fd0c16874c7d7c114dec03d865f0307 | 505 | //
// TailIndentThemeAttribute.swift
//
//
// Created by Matthew Davidson on 16/12/19.
//
import Foundation
import EditorCore
#if os(iOS)
import UIKit
#elseif os(macOS)
import Cocoa
#endif
public class TailIndentThemeAttribute: LineThemeAttribute {
public let key = "tail-indent"
public let value: CGFloat
public init(value: CGFloat = 0) {
self.value = value
}
public func apply(to style: MutableParagraphStyle) {
style.tailIndent = value
}
}
| 16.833333 | 59 | 0.665347 |
8fec9d82870f143b8d814d71a0557df7cda8fab2 | 2,473 | //
// Alertable.swift
// Stickman Runner
//
// Created by Vlad Munteanu on 1/12/19.
// Copyright © 2019 LesGarcons. All rights reserved.
//
import SpriteKit
protocol Alertable { }
extension Alertable where Self: SKScene {
func showAlert(withTitle title: String, message: String) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
// let okAction = UIAlertAction(title: "OK", style: .cancel) { _ in }
// alertController.addAction(okAction)
alertController.addTextField(configurationHandler: { (textField) -> Void in
textField.text = ""
})
alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in
let textField = alertController.textFields![0] as UITextField
if(alertController.title == "Remove Network") {
let defaults = UserDefaults.standard
defaults.removeObject(forKey: textField.text ?? "")
let scene = ChooseNetwork(size: self.size)
self.view?.presentScene(scene)
} else {
if(textField.text != "") {
print("Text field: \(textField.text ?? "")")
currentName = textField.text!
let scene = NormalGameScene(size: self.size)
self.view?.presentScene(scene)
}
}
}))
view?.window?.rootViewController?.present(alertController, animated: true)
}
func showAlertWithSettings(withTitle title: String, message: String) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .cancel) { _ in }
alertController.addAction(okAction)
let settingsAction = UIAlertAction(title: "Settings", style: .default) { _ in
guard let url = URL(string: UIApplication.openSettingsURLString) else { return }
if #available(iOS 10.0, *) {
UIApplication.shared.open(url)
} else {
UIApplication.shared.openURL(url)
}
}
alertController.addAction(settingsAction)
view?.window?.rootViewController?.present(alertController, animated: true)
}
}
| 36.367647 | 108 | 0.578245 |
ab53261d7cd1353d1de95e64cc249c7a803edeca | 318 | func foo() -> String {
return "abc"
}
// RUN: %empty-directory(%t.result)
// RUN: %sourcekitd-test -req=localize-string -pos=2:10 %s -- %s > %t.result/localize-string.swift.expected
// RUN: diff -u %S/localize-string.swift.expected %t.result/localize-string.swift.expected
// REQUIRES-ANY: OS=macosx, OS=linux-gnu
| 31.8 | 107 | 0.694969 |
e02621ea7c816bdfa20687ea3075779e512fe83d | 1,782 | //
// CodeSystems.swift
// HealthRecords
//
// Generated from FHIR 4.4.0-29ad3ab0
// Copyright 2020 Apple Inc.
//
// 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 FMCore
/**
How an entity was used in an activity.
URL: http://hl7.org/fhir/provenance-entity-role
ValueSet: http://hl7.org/fhir/ValueSet/provenance-entity-role
*/
public enum ProvenanceEntityRole: String, FHIRPrimitiveType {
/// A transformation of an entity into another, an update of an entity resulting in a new one, or the construction
/// of a new entity based on a pre-existing entity.
case derivation = "derivation"
/// A derivation for which the resulting entity is a revised version of some original.
case revision = "revision"
/// The repeat of (some or all of) an entity, such as text or image, by someone who might or might not be its
/// original author.
case quotation = "quotation"
/// A primary source for a topic refers to something produced by some agent with direct experience and knowledge
/// about the topic, at the time of the topic's study, without benefit from hindsight.
case source = "source"
/// A derivation for which the entity is removed from accessibility usually through the use of the Delete operation.
case removal = "removal"
}
| 37.125 | 117 | 0.736813 |
61c4b284e11eecb3b601f716396e06e75f0c86ed | 1,655 | //
// Copyright (c) 2019 Theis Holdings, LLC.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/// Conform to this protocol to handle an error from a `ServiceRequest`. This allows you to handle
/// common errors in a global way. While the error will still be sent up to the `ServiceRequest`'s
/// completion block, you can ignore it if you know it's being handled by one of these types. See
/// `ServiceErrorSifter` for more info.
public protocol ServiceErrorHandler {
/// Handle the error. Return `true` if handled, return `false` if not.
func handle(error: Error) -> Bool
}
| 47.285714 | 98 | 0.743202 |
7a389261363270dd1e34357f3652e013059eea4d | 5,356 | //
// ActiveAppViewModel.swift
// eRouska
//
// Created by Lukáš Foldýna on 25/03/2020.
// Copyright © 2020 Covid19CZ. All rights reserved.
//
import UIKit
import RxSwift
import RealmSwift
import RxRealm
final class ActiveAppVM {
enum State: String {
case enabled
case paused
case disabledBluetooth = "disabled"
case disabledExposures
var tabBarIcon: (UIImage, UIImage) {
switch self {
case .enabled:
return (Asset.homeActive.image, Asset.homeActiveSelected.image)
case .paused:
return (Asset.homePaused.image, Asset.homePausedSelected.image)
case .disabledBluetooth, .disabledExposures:
return (Asset.homeDisabled.image, Asset.homePausedSelected.image)
}
}
var color: UIColor {
switch self {
case .enabled:
return Asset.appEnabled.color
case .paused:
return Asset.appPaused.color
case .disabledBluetooth, .disabledExposures:
return Asset.appDisabled.color
}
}
var image: UIImage {
switch self {
case .enabled:
return Asset.scanActive.image
case .paused:
return Asset.bluetoothPaused.image
case .disabledBluetooth:
return Asset.bluetoothOff.image
case .disabledExposures:
return Asset.exposuresOff.image
}
}
var headline: String {
switch self {
case .enabled:
return L10n.activeHeadEnabled
case .paused:
return L10n.activeHeadPaused
case .disabledBluetooth:
return L10n.activeHeadDisabledBluetooth
case .disabledExposures:
return L10n.activeHeadDisabledExposures
}
}
var title: String? {
switch self {
case .enabled:
return L10n.activeTitleHighlightedEnabled
default:
return nil
}
}
var text: String {
switch self {
case .enabled:
return L10n.activeFooter
case .paused:
return L10n.activeTitlePaused
case .disabledBluetooth:
return L10n.activeTitleDisabledBluetooth
case .disabledExposures:
return L10n.activeTitleDisabledExposures
}
}
var actionTitle: String {
switch self {
case .enabled:
return L10n.activeButtonEnabled
case .paused:
return L10n.activeButtonPaused
case .disabledBluetooth:
return L10n.activeButtonDisabledBluetooth
case .disabledExposures:
return L10n.activeButtonDisabledExposures
}
}
}
var menuRiskyEncounters: String {
RemoteValues.exposureUITitle
}
var exposureTitle: String {
RemoteValues.exposureBannerTitle
}
lazy var dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.timeStyle = .short
formatter.dateStyle = .medium
return formatter
}()
var state: State {
let state = try? observableState.value()
return state ?? .disabledExposures
}
private(set) var observableState: BehaviorSubject<State>
private(set) var exposureToShow: Observable<Exposure?>
private let disposeBag = DisposeBag()
let exposureService: ExposureServicing = AppDelegate.dependency.exposureService
let reporter: ReportServicing = AppDelegate.dependency.reporter
let backgroundService = AppDelegate.dependency.background
init() {
observableState = BehaviorSubject<State>(value: .paused)
let showForDays = RemoteValues.serverConfiguration.showExposureForDays
let realm = try? Realm()
guard let exposures = realm?.objects(ExposureRealm.self).sorted(byKeyPath: "date") else {
exposureToShow = .empty()
return
}
let showForDate = Calendar.current.date(byAdding: .day, value: -showForDays, to: Date()) ?? Date()
exposureToShow = Observable.collection(from: exposures).map {
$0.last(where: { $0.date > showForDate })?.toExposure()
}
exposureService.readyToUse
.subscribe { [weak self] _ in
self?.updateStateIfNeeded()
}.disposed(by: disposeBag)
}
func cardShadowColor(traitCollection: UITraitCollection) -> CGColor {
return UIColor.label.resolvedColor(with: traitCollection).withAlphaComponent(0.2).cgColor
}
func updateStateIfNeeded() {
switch exposureService.status {
case .active:
observableState.onNext(.enabled)
case .paused, .disabled, .unauthorized:
observableState.onNext(.paused)
case .bluetoothOff:
observableState.onNext(.disabledBluetooth)
case .restricted:
observableState.onNext(.disabledExposures)
case .unknown:
observableState.onNext(.paused)
@unknown default:
return
}
}
}
| 30.605714 | 106 | 0.586445 |
f4a15fca114c831a0f16b375264d0a42e9ef5a07 | 520 | //
// PostModel.swift
// Zeta
//
// Created by Leandro Gamarra on 11/21/21.
//
import Foundation
import SwiftUI
struct PostModel: Identifiable, Hashable {
var id = UUID()
var postID: String // id for post in database
var userID: String // id for user in database
var username: String // username of user in database
var caption: String?
var dateCreated: Date
var likeCount: Int
var likedByUser: Bool
func hash(into hasher: inout Hasher) {
hasher.combine(id)
}
}
| 20.8 | 56 | 0.657692 |
1e9a8e4ccd8d6229e0ea9c343262815795defec0 | 3,009 | /*
* Copyright IBM Corporation 2016
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
/// The ServerRequest protocol allows requests to be abstracted
/// across different networking protocols in an agnostic way to the
/// Kitura project Router.
public protocol ServerRequest: AnyObject {
/// The set of headers received with the incoming request
var headers: HeadersContainer { get }
/// The URL from the request in string form
/// This contains just the path and query parameters starting with '/'
/// Use 'urlURL' for the full URL
@available(*, deprecated, message:
"This contains just the path and query parameters starting with '/'. use 'urlURL' instead")
var urlString: String { get }
/// The URL from the request in UTF-8 form
/// This contains just the path and query parameters starting with '/'
/// Use 'urlURL' for the full URL
var url: Data { get }
/// The URL from the request as URLComponents
/// URLComponents has a memory leak on linux as of swift 3.0.1. Use 'urlURL' instead
@available(*, deprecated, message:
"URLComponents has a memory leak on linux as of swift 3.0.1. use 'urlURL' instead")
var urlComponents: URLComponents { get }
/// The URL from the request
var urlURL: URL { get }
/// The IP address of the client
var remoteAddress: String { get }
/// Major version of HTTP of the request
var httpVersionMajor: UInt16? { get }
/// Minor version of HTTP of the request
var httpVersionMinor: UInt16? { get }
/// The HTTP Method specified in the request
var method: String { get }
/// Read data from the body of the request
///
/// - Parameter data: A Data struct to hold the data read in.
///
/// - Throws: Socket.error if an error occurred while reading from the socket
/// - Returns: The number of bytes read
func read(into data: inout Data) throws -> Int
/// Read a string from the body of the request.
///
/// - Throws: Socket.error if an error occurred while reading from the socket
/// - Returns: An Optional string
func readString() throws -> String?
/// Read all of the data in the body of the request
///
/// - Parameter data: A Data struct to hold the data read in.
///
/// - Throws: Socket.error if an error occurred while reading from the socket
/// - Returns: The number of bytes read
func readAllData(into data: inout Data) throws -> Int
}
| 36.695122 | 99 | 0.67996 |
9bf4a8351cc8c9c8d5fe6c3cb5564d81a4db4146 | 1,692 | //
// ViewController.swift
// View To Image Swift
//
// Created by Alex Duffell on 18/12/2017.
// Copyright © 2017 Alex Duffell. All rights reserved.
//
// Project files are from of my UIView -> UIImage tutorial on wordpress
// https://alexduffell.wordpress.com/2017/12/19/how-to-make-a-uiimage-from-a-uiview-gradients/
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var progressView: UIProgressView!
@IBOutlet weak var containerView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
//Increase height of progress view
progressView.transform = CGAffineTransform(scaleX: 1, y: 20)
//Round the corners of the progress view (using its container view)
containerView.layer.cornerRadius = 10
containerView.layer.masksToBounds = true
//Create a gradient
let colour1 = UIColor.yellow.cgColor
let colour2 = UIColor.red.cgColor
let gradientLayer = CAGradientLayer()
gradientLayer.frame = containerView.bounds
gradientLayer.colors = [colour1, colour2]
gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5)
gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5)
//Create a view
let gradientView = UIView(frame: containerView.bounds)
gradientView.layer.addSublayer(gradientLayer)
let renderer = UIGraphicsImageRenderer(size: gradientView.bounds.size)
let image = renderer.image { ctx in
gradientView.drawHierarchy(in: gradientView.bounds, afterScreenUpdates: true)
}
progressView.progressImage = image
}
}
| 32.538462 | 94 | 0.657801 |
e99e6841f51be4ac751311285a8ced75a10f3a56 | 8,756 | //
// Copyright (c) 2018 KxCoding <[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
class GridViewController: UIViewController {
@IBOutlet weak var redView: UIView!
@IBOutlet weak var blueView: UIView!
@IBOutlet weak var yellowView: UIView!
@IBOutlet weak var blackView: UIView!
@IBOutlet weak var bottomContainer: UIView!
override func viewDidLoad() {
super.viewDidLoad()
//layoutWithInitializer()
//layoutWithVisualFormatLanguage()
layoutWithAnchor()
}
}
extension GridViewController {
func layoutWithInitializer() {
redView.translatesAutoresizingMaskIntoConstraints = false
blueView.translatesAutoresizingMaskIntoConstraints = false
yellowView.translatesAutoresizingMaskIntoConstraints = false
blackView.translatesAutoresizingMaskIntoConstraints = false
let margin: CGFloat = 10.0
var leading = NSLayoutConstraint(item: redView, attribute: .leading, relatedBy: .equal, toItem: bottomContainer, attribute: .leading, multiplier: 1.0, constant: margin)
var top = NSLayoutConstraint(item: redView, attribute: .top, relatedBy: .equal, toItem: bottomContainer, attribute: .top, multiplier: 1.0, constant: margin)
var trailing = NSLayoutConstraint(item: redView, attribute: .trailing, relatedBy: .equal, toItem: blueView, attribute: .leading, multiplier: 1.0, constant: -margin)
var bottom = NSLayoutConstraint(item: redView, attribute: .bottom, relatedBy: .equal, toItem: yellowView, attribute: .top, multiplier: 1.0, constant: -margin)
NSLayoutConstraint.activate([leading, top, trailing, bottom])
top = NSLayoutConstraint(item: blueView, attribute: .top, relatedBy: .equal, toItem: bottomContainer, attribute: .top, multiplier: 1.0, constant: margin)
trailing = NSLayoutConstraint(item: blueView, attribute: .trailing, relatedBy: .equal, toItem: bottomContainer, attribute: .trailing, multiplier: 1.0, constant: -margin)
bottom = NSLayoutConstraint(item: blueView, attribute: .bottom, relatedBy: .equal, toItem: blackView, attribute: .top, multiplier: 1.0, constant: -margin)
NSLayoutConstraint.activate([top, trailing, bottom])
leading = NSLayoutConstraint(item: yellowView, attribute: .leading, relatedBy: .equal, toItem: bottomContainer, attribute: .leading, multiplier: 1.0, constant: margin)
bottom = NSLayoutConstraint(item: yellowView, attribute: .bottom, relatedBy: .equal, toItem: bottomContainer, attribute: .bottom, multiplier: 1.0, constant: -margin)
trailing = NSLayoutConstraint(item: yellowView, attribute: .trailing, relatedBy: .equal, toItem: blackView, attribute: .leading, multiplier: 1.0, constant: -margin)
NSLayoutConstraint.activate([leading, bottom, trailing])
trailing = NSLayoutConstraint(item: blackView, attribute: .trailing, relatedBy: .equal, toItem: bottomContainer, attribute: .trailing, multiplier: 1.0, constant: -margin)
bottom = NSLayoutConstraint(item: blackView, attribute: .bottom, relatedBy: .equal, toItem: bottomContainer, attribute: .bottom, multiplier: 1.0, constant: -margin)
NSLayoutConstraint.activate([trailing, bottom])
let list: [UIView] = [blueView, yellowView, blackView]
for v in list {
let equalWidth = NSLayoutConstraint(item: v, attribute: .width, relatedBy: .equal, toItem: redView, attribute: .width, multiplier: 1.0, constant: 0.0)
let equalHeight = NSLayoutConstraint(item: v, attribute: .height, relatedBy: .equal, toItem: redView, attribute: .height, multiplier: 1.0, constant: 0.0)
NSLayoutConstraint.activate([equalWidth, equalHeight])
}
}
}
extension GridViewController {
func layoutWithVisualFormatLanguage() {
redView.translatesAutoresizingMaskIntoConstraints = false
blueView.translatesAutoresizingMaskIntoConstraints = false
yellowView.translatesAutoresizingMaskIntoConstraints = false
blackView.translatesAutoresizingMaskIntoConstraints = false
let margin: CGFloat = 10.0
//let horzFmt1 = "|-10-[redView]-10-[blueView]-10-|"
let horzFmt1 = "|-m-[red]-m-[blue(==red)]-m-|"
let horzFmt2 = "|-m-[yellow]-m-[black(==yellow)]-m-|"
let vertFmt1 = "V:|-m-[red]-m-[yellow(==red)]-m-|"
let vertFmt2 = "V:|-m-[blue]-m-[black(==blue)]-m-|"
let views: [String: Any] = ["red": redView,
"blue": blueView,
"yellow": yellowView,
"black": blackView]
let metrics: [String: Any] = ["m": margin]
var horzConstraints = NSLayoutConstraint.constraints(withVisualFormat: horzFmt1, options: [], metrics: metrics, views: views)
NSLayoutConstraint.activate(horzConstraints)
horzConstraints = NSLayoutConstraint.constraints(withVisualFormat: horzFmt2, options: [], metrics: metrics, views: views)
NSLayoutConstraint.activate(horzConstraints)
var vertConstraints = NSLayoutConstraint.constraints(withVisualFormat: vertFmt1, options: [], metrics: metrics, views: views)
NSLayoutConstraint.activate(vertConstraints)
vertConstraints = NSLayoutConstraint.constraints(withVisualFormat: vertFmt2, options: [], metrics: metrics, views: views)
NSLayoutConstraint.activate(vertConstraints)
}
}
extension GridViewController {
func layoutWithAnchor() {
redView.translatesAutoresizingMaskIntoConstraints = false
blueView.translatesAutoresizingMaskIntoConstraints = false
yellowView.translatesAutoresizingMaskIntoConstraints = false
blackView.translatesAutoresizingMaskIntoConstraints = false
let margin: CGFloat = 10.0
redView.leadingAnchor.constraint(equalTo: bottomContainer.leadingAnchor, constant: margin).isActive = true
redView.topAnchor.constraint(equalTo: bottomContainer.topAnchor, constant: margin).isActive = true
redView.trailingAnchor.constraint(equalTo: blueView.leadingAnchor, constant: -margin).isActive = true
redView.bottomAnchor.constraint(equalTo: yellowView.topAnchor, constant: -margin).isActive = true
blueView.topAnchor.constraint(equalTo: bottomContainer.topAnchor, constant: margin).isActive = true
blueView.trailingAnchor.constraint(equalTo: bottomContainer.trailingAnchor, constant: -margin).isActive = true
blueView.bottomAnchor.constraint(equalTo: blackView.topAnchor, constant: -margin).isActive = true
yellowView.leadingAnchor.constraint(equalTo: bottomContainer.leadingAnchor, constant: margin).isActive = true
yellowView.trailingAnchor.constraint(equalTo: blackView.leadingAnchor, constant: -margin).isActive = true
yellowView.bottomAnchor.constraint(equalTo: bottomContainer.bottomAnchor, constant: -margin).isActive = true
blackView.trailingAnchor.constraint(equalTo: bottomContainer.trailingAnchor, constant: -margin).isActive = true
blackView.bottomAnchor.constraint(equalTo: bottomContainer.bottomAnchor, constant: -margin).isActive = true
blueView.widthAnchor.constraint(equalTo: redView.widthAnchor).isActive = true
blueView.heightAnchor.constraint(equalTo: redView.heightAnchor).isActive = true
yellowView.widthAnchor.constraint(equalTo: redView.widthAnchor).isActive = true
yellowView.heightAnchor.constraint(equalTo: redView.heightAnchor).isActive = true
blackView.widthAnchor.constraint(equalTo: redView.widthAnchor).isActive = true
blackView.heightAnchor.constraint(equalTo: redView.heightAnchor).isActive = true
}
}
| 49.468927 | 176 | 0.724189 |
165bd70c891214efd179f4d2ff9cc15fd00d1904 | 33,538 | // swiftlint:disable type_body_length
#if os(OSX)
import Foundation
#else
import UIKit
#endif
/// SpotsControllerManager handles mutation on a controller level.
/// It relays mutating operations to `ComponentManger` when the affected `Component` has been resolved.
/// It supports both reloading with JSON payloads and with collections of `ComponentModel`'s.
/// Similar to `ComponentManager`, each mutating operation has a completion that will be invoked when
/// the operation reaches its end, this way you can respond to chained mutations on a controller level.
/// `SpotsControllerManager` also supports model diffing, which means that it will only insert, update, reload
/// or delete components or items that changed. This is supported on a `ComponentModel` level.
/// It can also pinpoint updates on a specific component by supplying the component index of the `Component`
/// that you which to mutate. `SpotsController` has a protocol extension which makes these method directly accessable
/// on the controller (see `SpotsController+SpotsControllerManager`). `SpotsControllerManager` lives on `SpotsController`.
/// It is created during init and is publicly accessable via `.manager`.
///
/// Usage:
///
///
/// ```
/// // Reload with a collection of `ComponentModel`s
/// controller.reloadIfNeeded(components: [componentModel, ...]) {}
/// ```
/// // Updating the item at index 0
/// ```
/// controller.update(item: Item(...), index: 0) {}
///
/// ```
///
public class SpotsControllerManager {
/// A comparison closure type alias for comparing collections of component models.
public typealias CompareClosure = ((_ lhs: [ComponentModel], _ rhs: [ComponentModel]) -> Bool)
/**
Reload all components.
- parameter animation: A ComponentAnimation struct that determines which animation that should be used for the updates
- parameter completion: A completion block that is run when the reloading is done
*/
public func reload(controller: SpotsController, withAnimation animation: Animation = .automatic, completion: Completion = nil) {
var componentsLeft = controller.components.count
Dispatch.main {
controller.components.forEach { component in
component.reload([], withAnimation: animation) {
componentsLeft -= 1
if componentsLeft == 0 {
completion?()
}
}
}
}
}
/// Reload if needed using JSON
///
/// - parameter components: A collection of components that gets parsed into UI elements
/// - parameter compare: A closure that is used for comparing a ComponentModel collections
/// - parameter animated: An animation closure that can be used to perform custom animations when reloading
/// - parameter completion: A closure that will be run after reload has been performed on all components
public func reloadIfNeeded(components: [ComponentModel],
controller: SpotsController,
compare: @escaping CompareClosure = { lhs, rhs in return lhs !== rhs },
withAnimation animation: Animation = .automatic,
completion: Completion = nil) {
guard !components.isEmpty else {
Dispatch.main {
controller.components.forEach {
$0.view.removeFromSuperview()
}
controller.components = []
completion?()
}
return
}
// Opt-out from performing any kind of diffing if the controller has no components.
if controller.components.isEmpty {
reload(models: components, controller: controller, completion: completion)
return
}
Dispatch.interactive { [weak self] in
guard let strongSelf = self else {
completion?()
return
}
let oldComponents = controller.components
let oldComponentModels = oldComponents.map { $0.model }
let newComponentModels = components
guard compare(newComponentModels, oldComponentModels) else {
Dispatch.main {
controller.scrollView.layoutViews()
SpotsController.componentsDidReloadComponentModels?(controller)
completion?()
}
return
}
let changes = strongSelf.generateChanges(from: newComponentModels, and: oldComponentModels)
strongSelf.process(changes: changes, controller: controller, components: newComponentModels, withAnimation: animation) {
Dispatch.main {
controller.scrollView.setNeedsLayout()
SpotsController.componentsDidReloadComponentModels?(controller)
completion?()
}
}
}
}
/// Generate a change set by comparing two component collections
///
/// - parameter components: A collection of components
/// - parameter oldComponentModels: A collection of components
///
/// - returns: A ComponentModelDiff struct
func generateChanges(from models: [ComponentModel], and oldComponentModels: [ComponentModel]) -> [ComponentModelDiff] {
let oldComponentModelCount = oldComponentModels.count
var changes = [ComponentModelDiff]()
for (index, model) in models.enumerated() {
if index >= oldComponentModelCount {
changes.append(.new)
continue
}
changes.append(model.diff(model: oldComponentModels[index]))
}
if oldComponentModelCount > models.count {
oldComponentModels[models.count..<oldComponentModels.count].forEach { _ in
changes.append(.removed)
}
}
return changes
}
/// Replace component at index
///
/// - Parameters:
/// - index: The index of the component
/// - controller: A SpotsController
/// - newComponentModels: The new component model that should replace the existing component.
fileprivate func replaceComponent(atIndex index: Int, with preparedComponent: Component? = nil, controller: SpotsController, newComponentModels: [ComponentModel], completion: Completion = nil) {
let component: Component
let oldComponent = controller.components[index]
if let preparedComponent = preparedComponent {
component = preparedComponent
defer {
completion?()
}
} else {
component = Component(model: newComponentModels[index], configuration: controller.configuration)
component.view.frame = oldComponent.view.frame
defer {
controller.setupComponent(at: index, component: component)
}
}
oldComponent.view.removeFromSuperview()
controller.components[index] = component
controller.scrollView.componentsView.insertSubview(component.view, at: index)
}
/// Insert new component at index.
///
/// - Parameters:
/// - index: The index of the component
/// - controller: A SpotsController instance.
/// - newComponentModels: The new component model that should replace the existing component.
fileprivate func newComponent(atIndex index: Int, controller: SpotsController, newComponentModels: [ComponentModel]) {
let component = Component(model: newComponentModels[index], configuration: controller.configuration)
controller.components.append(component)
controller.setupComponent(at: index, component: component)
}
/// Remove component at index
///
/// - Parameters:
/// - index: The index of the component that should be removed.
/// - controller: A SpotsController instance.
fileprivate func removeComponent(atIndex index: Int, controller: SpotsController) {
guard index < controller.components.count else {
return
}
controller.components[index].view.removeFromSuperview()
}
/// Set up items for a Component object
///
/// - parameter index: The index of the Component object
/// - parameter controller: A SpotsController instance.
/// - parameter newComponentModels: A collection of new components
/// - parameter animation: A Animation that is used to determine which animation to use when performing the update
/// - parameter closure: A completion closure that is invoked when the setup of the new items is complete
///
/// - returns: A boolean value that determines if the closure should run in `process(changes:)`
fileprivate func setupItemsForComponent(atIndex index: Int, controller: SpotsController, newComponentModels: [ComponentModel], withAnimation animation: Animation = .automatic, completion: Completion = nil) {
guard let component = controller.component(at: index) else {
return
}
updateComponentModel(newComponentModels[index],
on: component,
in: controller,
withAnimation: animation,
completion: completion)
}
/// Reload Component object with changes and new items.
///
/// - parameter changes: A ItemChanges tuple.
/// - parameter controller: A SpotsController instance.
/// - parameter component: The component that should be updated.
/// - parameter newItems: The new items that should be used to updated the data source.
/// - parameter animation: The animation that should be used when updating.
/// - parameter closure: A completion closure.
private func reload(with changes: (Changes),
controller: SpotsController,
in component: Component,
newItems: [Item],
animation: Animation,
completion: (() -> Void)? = nil) {
component.reloadIfNeeded(changes, withAnimation: animation, updateDataSource: {
component.model.items = newItems
}, completion: completion)
}
/// Reload Component object with less items
///
/// - parameter changes: A ItemChanges tuple.
/// - parameter controller: A SpotsController instance.
/// - parameter component: The component that should be updated.
/// - parameter newItems: The new items that should be used to updated the data source.
/// - parameter animation: The animation that should be used when updating.
/// - parameter closure: A completion closure.
private func reload(with changes: Changes,
controller: SpotsController,
in component: Component,
lessItems newItems: [Item],
animation: Animation,
completion: (() -> Void)? = nil) {
let updateDatasource = {
component.model.items = newItems
}
component.reloadIfNeeded(changes, withAnimation: animation, updateDataSource: updateDatasource, completion: completion)
}
/// Reload Component object with more items
///
/// - parameter changes: A ItemChanges tuple.
/// - parameter controller: A SpotsController instance.
/// - parameter component: The component that should be updated.
/// - parameter newItems: The new items that should be used to updated the data source.
/// - parameter animation: The animation that should be used when updating.
/// - parameter closure: A completion closure.
private func reload(with changes: Changes,
controller: SpotsController,
in component: Component,
moreItems newItems: [Item],
animation: Animation,
completion: (() -> Void)? = nil) {
let updateDataSource = {
component.model.items = newItems
}
let completion = {
controller.scrollView.setNeedsLayout()
completion?()
}
component.reloadIfNeeded(changes, withAnimation: animation, updateDataSource: updateDataSource, completion: completion)
}
/// Process a collection of component model diffs.
///
/// - Parameters:
/// - changes: A collection of component model diffs.
/// - controller: A SpotsController instance.
/// - newComponentModels: A collection of new component models.
/// - animation: The animation that should be used when updating the components.
/// - completion: A completion closure that is run when the process is done.
func process(changes: [ComponentModelDiff],
controller: SpotsController,
components newComponentModels: [ComponentModel],
withAnimation animation: Animation = .automatic,
completion: Completion = nil) {
Dispatch.main { [weak self] in
guard let strongSelf = self else {
completion?()
return
}
let finalCompletion = completion
let lastItemChange: Int = changes.count - 1
var runCompletion = true
var completion: Completion = nil
for (index, change) in changes.enumerated() {
switch change {
case .identifier, .kind, .layout, .meta, .model:
strongSelf.replaceComponent(atIndex: index, controller: controller, newComponentModels: newComponentModels)
case .new:
strongSelf.newComponent(atIndex: index, controller: controller, newComponentModels: newComponentModels)
case .removed:
strongSelf.removeComponent(atIndex: index, controller: controller)
case .header:
controller.components[index].model.header = newComponentModels[index].header
controller.components[index].reloadHeader()
fallthrough
case .footer:
controller.components[index].model.header = newComponentModels[index].footer
controller.components[index].reloadFooter()
fallthrough
case .items:
if index == lastItemChange {
completion = { [weak self] in
self?.purgeCachedViews(in: controller.components)
finalCompletion?()
}
runCompletion = false
}
strongSelf.setupItemsForComponent(atIndex: index,
controller: controller,
newComponentModels: newComponentModels,
withAnimation: animation,
completion: completion)
case .none:
continue
}
}
for removedComponent in controller.components where removedComponent.view.superview == nil {
if let index = controller.components.index(where: { removedComponent.view.isEqual($0.view) }) {
controller.components.remove(at: index)
}
}
if runCompletion {
controller.scrollView.setNeedsLayout()
finalCompletion?()
}
}
}
///Reload if needed using JSON
///
/// - parameter json: A JSON dictionary that gets parsed into UI elements
/// - parameter controller: A SpotsController instance.
/// - parameter compare: A closure that is used for comparing a ComponentModel collections
/// - parameter animated: An animation closure that can be used to perform custom animations when reloading
/// - parameter completion: A closure that will be run after reload has been performed on all components
public func reloadIfNeeded(_ json: [String: Any],
controller: SpotsController,
compare: @escaping CompareClosure = { lhs, rhs in return lhs !== rhs },
animated: ((_ view: View) -> Void)? = nil,
completion: Completion = nil) {
Dispatch.main { [weak self] in
guard let strongSelf = self else {
completion?()
return
}
let newComponents: [Component] = Parser.parseComponents(json: json,
configuration: controller.configuration)
let newComponentModels = newComponents.map { $0.model }
let oldComponentModels = controller.components.map { $0.model }
guard compare(newComponentModels, oldComponentModels) else {
SpotsController.componentsDidReloadComponentModels?(controller)
completion?()
return
}
var offsets = [CGPoint]()
if newComponentModels.count == oldComponentModels.count {
offsets = controller.components.map { $0.view.contentOffset }
}
controller.components = newComponents
if controller.scrollView.superview == nil {
controller.view.addSubview(controller.scrollView)
}
strongSelf.cleanUpComponentView(controller: controller)
controller.setupComponents(animated: animated)
completion?()
offsets.enumerated().forEach {
newComponents[$0.offset].view.contentOffset = $0.element
}
controller.scrollView.setNeedsLayout()
SpotsController.componentsDidReloadComponentModels?(controller)
}
}
/// Reload with component models
///
///- parameter component models: A collection of component models.
///- parameter controller: A SpotsController instance.
///- parameter animated: An animation closure that can be used to perform custom animations when reloading
///- parameter completion: A closure that will be run after reload has been performed on all components
public func reload(models: [ComponentModel], controller: SpotsController, animated: ((_ view: View) -> Void)? = nil, completion: Completion = nil) {
Dispatch.main { [weak self] in
guard let strongSelf = self else {
completion?()
return
}
// Opt-out of doing component cleanup if the controller has no components.
let performCleanup = !controller.components.isEmpty
let previousContentOffset = controller.scrollView.contentOffset
controller.components = Parser.parseComponents(models: models,
configuration: controller.configuration)
if performCleanup {
if controller.scrollView.superview == nil {
controller.view.addSubview(controller.scrollView)
}
strongSelf.cleanUpComponentView(controller: controller)
}
controller.setupComponents(animated: animated)
controller.components.forEach { component in
component.afterUpdate()
}
SpotsController.componentsDidReloadComponentModels?(controller)
controller.scrollView.setNeedsLayout()
if performCleanup {
controller.scrollView.contentOffset = previousContentOffset
}
completion?()
}
}
/// Reload with JSON
///
///- parameter json: A JSON dictionary that gets parsed into UI elements
///- parameter controller: A SpotsController instance.
///- parameter animated: An animation closure that can be used to perform custom animations when reloading
///- parameter completion: A closure that will be run after reload has been performed on all components
public func reload(json: [String: Any], controller: SpotsController, animated: ((_ view: View) -> Void)? = nil, completion: Completion = nil) {
Dispatch.main { [weak self] in
guard let strongSelf = self else {
completion?()
return
}
controller.components = Parser.parseComponents(json: json, configuration: controller.configuration)
if controller.scrollView.superview == nil {
controller.view.addSubview(controller.scrollView)
}
let previousContentOffset = controller.scrollView.contentOffset
strongSelf.cleanUpComponentView(controller: controller)
controller.setupComponents(animated: animated)
controller.components.forEach { component in
component.afterUpdate()
}
SpotsController.componentsDidReloadComponentModels?(controller)
controller.scrollView.setNeedsLayout()
controller.scrollView.contentOffset = previousContentOffset
completion?()
}
}
/**
- parameter componentAtIndex: The index of the component that you want to perform updates on.
- parameter controller: A SpotsController instance.
- parameter animation: A Animation struct that determines which animation that should be used to perform the update.
- parameter completion: A completion closure that is performed when the update is completed.
- parameter closure: A transform closure to perform the proper modification to the target component before updating the internals.
*/
public func update(componentAtIndex index: Int = 0, controller: SpotsController, withAnimation animation: Animation = .automatic, withCompletion completion: Completion = nil, _ closure: (_ component: Component) -> Void) {
guard let component = controller.component(at: index) else {
assertionFailure("Could not resolve component at index: \(index).")
controller.scrollView.setNeedsLayout()
completion?()
return
}
closure(component)
component.prepareItems()
Dispatch.main {
#if !os(OSX)
if animation != .none {
let isScrolling = controller.scrollView.isDragging == true || controller.scrollView.isTracking == true
if let superview = component.view.superview, !isScrolling {
component.view.frame.size.height = superview.frame.height
}
}
#endif
component.reload(nil, withAnimation: animation) {
controller.scrollView.setNeedsLayout()
completion?()
}
}
}
/**
Updates component only if the passed view models are not the same with the current ones.
- parameter componentAtIndex: The index of the component that you want to perform updates on
- parameter controller: A SpotsController instance.
- parameter items: An array of view models
- parameter animation: A Animation struct that determines which animation that should be used to perform the update
- parameter completion: A completion closure that is run when the update is completed
*/
public func updateIfNeeded(componentAtIndex index: Int = 0, controller: SpotsController, items: [Item], withAnimation animation: Animation = .automatic, completion: Completion = nil) {
guard let component = controller.component(at: index) else {
assertionFailure("Could not resolve component at index: \(index).")
controller.scrollView.setNeedsLayout()
completion?()
return
}
var newModel = component.model
newModel.items = items
updateComponentModel(newModel, on: component, in: controller, withAnimation: animation) {
controller.scrollView.setNeedsLayout()
completion?()
}
}
/**
- parameter item: The view model that you want to append
- parameter componentIndex: The index of the component that you want to append to, defaults to 0
- parameter controller: A SpotsController instance.
- parameter animation: A Animation struct that determines which animation that should be used to perform the update
- parameter completion: A completion closure that will run after the component has performed updates internally
*/
public func append(_ item: Item, componentIndex: Int = 0, controller: SpotsController, withAnimation animation: Animation = .none, completion: Completion = nil) {
resolveComponent(atIndex: componentIndex, controller: controller, completion: completion) { component in
component.append(item, withAnimation: animation, completion: completion)
}
}
/**
- parameter items: A collection of view models
- parameter componentIndex: The index of the component that you want to append to, defaults to 0
- parameter controller: A SpotsController instance.
- parameter animation: A Animation struct that determines which animation that should be used to perform the update
- parameter completion: A completion closure that will run after the component has performed updates internally
*/
public func append(_ items: [Item], componentIndex: Int = 0, controller: SpotsController, withAnimation animation: Animation = .none, completion: Completion = nil) {
resolveComponent(atIndex: componentIndex, controller: controller, completion: completion) { component in
component.append(items, withAnimation: animation, completion: completion)
}
}
/**
- parameter items: A collection of view models
- parameter componentIndex: The index of the component that you want to prepend to, defaults to 0
- parameter controller: A SpotsController instance.
- parameter animation: A Animation struct that determines which animation that should be used to perform the update
- parameter completion: A completion closure that will run after the component has performed updates internally
*/
public func prepend(_ items: [Item], componentIndex: Int = 0, controller: SpotsController, withAnimation animation: Animation = .none, completion: Completion = nil) {
resolveComponent(atIndex: componentIndex, controller: controller, completion: completion) { component in
component.prepend(items, withAnimation: animation, completion: completion)
}
}
/**
- parameter item: The view model that you want to insert
- parameter index: The index that you want to insert the view model at
- parameter componentIndex: The index of the component that you want to insert into
- parameter controller: A SpotsController instance.
- parameter animation: A Animation struct that determines which animation that should be used to perform the update
- parameter completion: A completion closure that will run after the component has performed updates internally
*/
public func insert(_ item: Item, index: Int = 0, componentIndex: Int, controller: SpotsController, withAnimation animation: Animation = .none, completion: Completion = nil) {
resolveComponent(atIndex: componentIndex, controller: controller, completion: completion) { component in
component.insert(item, index: index, withAnimation: animation, completion: completion)
}
}
/// Update item at index inside a specific Component object
///
/// - parameter item: The view model that you want to update.
/// - parameter index: The index that you want to insert the view model at.
/// - parameter componentIndex: The index of the component that you want to update into.
/// - parameter controller: A SpotsController instance.
/// - parameter animation: A Animation struct that determines which animation that should be used to perform the update.
/// - parameter completion: A completion closure that will run after the component has performed updates internally.
public func update(_ item: Item, index: Int = 0, componentIndex: Int, controller: SpotsController, withAnimation animation: Animation = .none, completion: Completion = nil) {
guard let oldItem = controller.component(at: componentIndex)?.item(at: index)
else {
completion?()
return
}
guard item != oldItem else {
completion?()
return
}
#if os(iOS)
if animation == .none {
CATransaction.begin()
}
#endif
resolveComponent(atIndex: componentIndex, controller: controller, completion: completion) { component in
component.update(item, index: index, withAnimation: animation) {
completion?()
#if os(iOS)
if animation == .none {
CATransaction.commit()
}
#endif
}
}
}
/**
- parameter indexes: An integer array of indexes that you want to update
- parameter componentIndex: The index of the component that you want to update into
- parameter controller: A SpotsController instance.
- parameter animation: A Animation struct that determines which animation that should be used to perform the update
- parameter completion: A completion closure that will run after the component has performed updates internally
*/
public func update(_ indexes: [Int], componentIndex: Int = 0, controller: SpotsController, withAnimation animation: Animation = .automatic, completion: Completion = nil) {
resolveComponent(atIndex: componentIndex, controller: controller, completion: completion) { component in
component.reload(indexes, withAnimation: animation, completion: completion)
}
}
/**
- parameter index: The index of the view model that you want to remove
- parameter componentIndex: The index of the component that you want to remove into
- parameter controller: A SpotsController instance.
- parameter animation: A Animation struct that determines which animation that should be used to perform the update
- parameter completion: A completion closure that will run after the component has performed updates internally
*/
public func delete(_ index: Int, componentIndex: Int = 0, controller: SpotsController, withAnimation animation: Animation = .none, completion: Completion = nil) {
resolveComponent(atIndex: componentIndex, controller: controller, completion: completion) { component in
component.delete(index, withAnimation: animation, completion: completion)
}
}
/**
- parameter indexes: A collection of indexes for view models that you want to remove
- parameter componentIndex: The index of the component that you want to remove into
- parameter controller: A SpotsController instance.
- parameter animation: A Animation struct that determines which animation that should be used to perform the update
- parameter completion: A completion closure that will run after the component has performed updates internally
*/
public func delete(_ indexes: [Int], componentIndex: Int = 0, controller: SpotsController, withAnimation animation: Animation = .none, completion: Completion = nil) {
resolveComponent(atIndex: componentIndex, controller: controller, completion: completion) { component in
component.delete(indexes, withAnimation: animation, completion: completion)
}
}
private func resolveComponent(atIndex componentIndex: Int, controller: SpotsController, completion: Completion, closure: (Component) -> Void) {
guard let component = controller.component(at: componentIndex) else {
assertionFailure("Could not resolve component at index: \(componentIndex).")
completion?()
return
}
closure(component)
}
/// Remove all views from components view.
///
/// - Parameter controller: A SpotsController instance.
private func cleanUpComponentView(controller: SpotsController) {
controller.scrollView.componentsView.subviews.forEach {
$0.removeFromSuperview()
}
}
/// Update `Component` with new `ComponentModel` based of changes from `Item`'s diff.
/// This is used when reloading a `SpotsController` with a collection of `ComponentModel`'s.
/// It is also used in `updateIfNeeded` to update with more precision, and only if it is needed.
///
/// - Parameters:
/// - model: The new model that
/// - component: The component that should be updated.
/// - controller: The controller that the component belongs to.
/// - animation: The animation that should be used when performing the update.
/// - completion: A completion closure that will run if updates where performed.
/// - Returns: Will return `true` if updates where performed, otherwise `false`.
private func updateComponentModel(_ model: ComponentModel, on component: Component, in controller: SpotsController, withAnimation animation: Animation = .automatic, completion: Completion) {
let setupSize: CGSize
if component.view.frame.size == .zero {
setupSize = controller.view.frame.size
} else {
setupSize = component.view.frame.size
}
let tempComponent = Component(model: model, configuration: controller.configuration)
tempComponent.setup(with: setupSize, needsLayout: false)
tempComponent.model.size = CGSize(
width: controller.view.frame.width,
height: ceil(tempComponent.view.frame.height))
Dispatch.interactive { [weak self] in
guard let changes = component.manager.diffManager.compare(oldItems: component.model.items, newItems: tempComponent.model.items) else {
Dispatch.main {
completion?()
}
return
}
Dispatch.main { [weak self] in
// If the component is empty, then replace the old one with the temporary component
// used for diffing.
if component.model.items.isEmpty {
self?.replaceComponent(atIndex: component.model.index, with: tempComponent, controller: controller, newComponentModels: [], completion: completion)
return
}
let newItems = tempComponent.model.items
if newItems.count == component.model.items.count {
self?.reload(with: changes,
controller: controller,
in: component,
newItems: newItems,
animation: animation,
completion: completion)
} else if newItems.count < component.model.items.count {
self?.reload(with: changes,
controller: controller,
in: component,
lessItems: newItems,
animation: animation,
completion: completion)
} else if newItems.count > component.model.items.count {
self?.reload(with: changes,
controller: controller,
in: component,
moreItems: newItems,
animation: animation,
completion: completion)
}
}
}
}
func purgeCachedViews(in components: [Component]) {
for component in components {
component.configuration.views.purge()
}
}
}
| 43.219072 | 223 | 0.681555 |
1807755824204a0651f3ea9b23da671a22c81374 | 385 | //
// AppDelegate.swift
// SafeEject
//
// Created by Tanner W. Stokes on 7/1/17.
// Copyright © 2017 Tanner W. Stokes. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ aNotification: Notification) {}
func applicationWillTerminate(_ aNotification: Notification) {}
}
| 20.263158 | 72 | 0.732468 |
18c5d02113908f8dbf127bdb1f511a4d1670ab1d | 2,896 | // Generated using SwiftGen, by O.Halligon — https://github.com/SwiftGen/SwiftGen
#if os(OSX)
import AppKit.NSImage
typealias AssetColorTypeAlias = NSColor
typealias Image = NSImage
#elseif os(iOS) || os(tvOS) || os(watchOS)
import UIKit.UIImage
typealias AssetColorTypeAlias = UIColor
typealias Image = UIImage
#endif
// swiftlint:disable superfluous_disable_command
// swiftlint:disable file_length
@available(*, deprecated, renamed: "ImageAsset")
typealias AssetType = ImageAsset
struct ImageAsset {
fileprivate var name: String
var image: Image {
let bundle = Bundle(for: BundleToken.self)
#if os(iOS) || os(tvOS)
let image = Image(named: name, in: bundle, compatibleWith: nil)
#elseif os(OSX)
let image = bundle.image(forResource: name)
#elseif os(watchOS)
let image = Image(named: name)
#endif
guard let result = image else { fatalError("Unable to load image named \(name).") }
return result
}
}
struct ColorAsset {
fileprivate var name: String
#if swift(>=3.2)
@available(iOS 11.0, tvOS 11.0, watchOS 4.0, OSX 10.13, *)
var color: AssetColorTypeAlias {
return AssetColorTypeAlias(asset: self)
}
#endif
}
// swiftlint:disable identifier_name line_length nesting type_body_length type_name
enum Asset {
enum Icons {
static let albumCoverPlaceholder = ImageAsset(name: "album_cover_placeholder")
static let starEmptyIcon = ImageAsset(name: "star_empty_icon")
static let starFullIcon = ImageAsset(name: "star_full_icon")
}
// swiftlint:disable trailing_comma
static let allColors: [ColorAsset] = [
]
static let allImages: [ImageAsset] = [
Icons.albumCoverPlaceholder,
Icons.starEmptyIcon,
Icons.starFullIcon,
]
// swiftlint:enable trailing_comma
@available(*, deprecated, renamed: "allImages")
static let allValues: [AssetType] = allImages
}
// swiftlint:enable identifier_name line_length nesting type_body_length type_name
extension Image {
@available(iOS 1.0, tvOS 1.0, watchOS 1.0, *)
@available(OSX, deprecated,
message: "This initializer is unsafe on macOS, please use the ImageAsset.image property")
convenience init!(asset: ImageAsset) {
#if os(iOS) || os(tvOS)
let bundle = Bundle(for: BundleToken.self)
self.init(named: asset.name, in: bundle, compatibleWith: nil)
#elseif os(OSX) || os(watchOS)
self.init(named: asset.name)
#endif
}
}
extension AssetColorTypeAlias {
#if swift(>=3.2)
@available(iOS 11.0, tvOS 11.0, watchOS 4.0, OSX 10.13, *)
convenience init!(asset: ColorAsset) {
let bundle = Bundle(for: BundleToken.self)
#if os(iOS) || os(tvOS)
self.init(named: asset.name, in: bundle, compatibleWith: nil)
#elseif os(OSX)
self.init(named: asset.name, bundle: bundle)
#elseif os(watchOS)
self.init(named: asset.name)
#endif
}
#endif
}
private final class BundleToken {}
| 28.96 | 93 | 0.706146 |
1170e4dee8e52c9e0868e855728f426c1eb9ec7a | 6,130 | //
// APIWrappersViewController.swift
// RxExample
//
// Created by Carlos García on 8/7/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import UIKit
import CoreLocation
import RxSwift
import RxCocoa
extension UILabel {
open override var accessibilityValue: String! {
get {
return self.text
}
set {
self.text = newValue
self.accessibilityValue = newValue
}
}
}
class APIWrappersViewController: ViewController {
@IBOutlet weak var debugLabel: UILabel!
@IBOutlet weak var openActionSheet: UIButton!
@IBOutlet weak var openAlertView: UIButton!
@IBOutlet weak var bbitem: UIBarButtonItem!
@IBOutlet weak var segmentedControl: UISegmentedControl!
@IBOutlet weak var switcher: UISwitch!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
@IBOutlet weak var button: UIButton!
@IBOutlet weak var slider: UISlider!
@IBOutlet weak var textField: UITextField!
@IBOutlet weak var textField2: UITextField!
@IBOutlet weak var datePicker: UIDatePicker!
@IBOutlet weak var mypan: UIPanGestureRecognizer!
@IBOutlet weak var textView: UITextView!
@IBOutlet weak var textView2: UITextView!
let manager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
datePicker.date = Date(timeIntervalSince1970: 0)
// MARK: UIBarButtonItem
bbitem.rx.tap
.subscribe(onNext: { [weak self] x in
self?.debug("UIBarButtonItem Tapped")
})
.disposed(by: disposeBag)
// MARK: UISegmentedControl
// also test two way binding
let segmentedValue = Variable(0)
_ = segmentedControl.rx.value <-> segmentedValue
segmentedValue.asObservable()
.subscribe(onNext: { [weak self] x in
self?.debug("UISegmentedControl value \(x)")
})
.disposed(by: disposeBag)
// MARK: UISwitch
// also test two way binding
let switchValue = Variable(true)
_ = switcher.rx.value <-> switchValue
switchValue.asObservable()
.subscribe(onNext: { [weak self] x in
self?.debug("UISwitch value \(x)")
})
.disposed(by: disposeBag)
// MARK: UIActivityIndicatorView
switcher.rx.value
.bind(to: activityIndicator.rx.isAnimating)
.disposed(by: disposeBag)
// MARK: UIButton
button.rx.tap
.subscribe(onNext: { [weak self] x in
self?.debug("UIButton Tapped")
})
.disposed(by: disposeBag)
// MARK: UISlider
// also test two way binding
let sliderValue = Variable<Float>(1.0)
_ = slider.rx.value <-> sliderValue
sliderValue.asObservable()
.subscribe(onNext: { [weak self] x in
self?.debug("UISlider value \(x)")
})
.disposed(by: disposeBag)
// MARK: UIDatePicker
// also test two way binding
let dateValue = Variable(Date(timeIntervalSince1970: 0))
_ = datePicker.rx.date <-> dateValue
dateValue.asObservable()
.subscribe(onNext: { [weak self] x in
self?.debug("UIDatePicker date \(x)")
})
.disposed(by: disposeBag)
// MARK: UITextField
// also test two way binding
let textValue = Variable("")
_ = textField.rx.textInput <-> textValue
textValue.asObservable()
.subscribe(onNext: { [weak self] x in
self?.debug("UITextField text \(x)")
})
.disposed(by: disposeBag)
textValue.asObservable()
.subscribe(onNext: { [weak self] x in
self?.debug("UITextField text \(x)")
})
.disposed(by: disposeBag)
let attributedTextValue = Variable<NSAttributedString?>(NSAttributedString(string: ""))
_ = textField2.rx.attributedText <-> attributedTextValue
attributedTextValue.asObservable()
.subscribe(onNext: { [weak self] x in
self?.debug("UITextField attributedText \(x?.description ?? "")")
})
.disposed(by: disposeBag)
// MARK: UIGestureRecognizer
mypan.rx.event
.subscribe(onNext: { [weak self] x in
self?.debug("UIGestureRecognizer event \(x.state.rawValue)")
})
.disposed(by: disposeBag)
// MARK: UITextView
// also test two way binding
let textViewValue = Variable("")
_ = textView.rx.textInput <-> textViewValue
textViewValue.asObservable()
.subscribe(onNext: { [weak self] x in
self?.debug("UITextView text \(x)")
})
.disposed(by: disposeBag)
let attributedTextViewValue = Variable<NSAttributedString?>(NSAttributedString(string: ""))
_ = textView2.rx.attributedText <-> attributedTextViewValue
attributedTextViewValue.asObservable()
.subscribe(onNext: { [weak self] x in
self?.debug("UITextView attributedText \(x?.description ?? "")")
})
.disposed(by: disposeBag)
// MARK: CLLocationManager
manager.requestWhenInUseAuthorization()
manager.rx.didUpdateLocations
.subscribe(onNext: { x in
print("rx.didUpdateLocations \(x)")
})
.disposed(by: disposeBag)
_ = manager.rx.didFailWithError
.subscribe(onNext: { x in
print("rx.didFailWithError \(x)")
})
manager.rx.didChangeAuthorizationStatus
.subscribe(onNext: { status in
print("Authorization status \(status)")
})
.disposed(by: disposeBag)
manager.startUpdatingLocation()
}
func debug(_ string: String) {
print(string)
debugLabel.text = string
}
}
| 27.123894 | 99 | 0.577325 |
9017b72bc5f5b12518f71d85b836771669a77a41 | 791 | // CharonCollections - A Collection Library for Swift
//
// Copyright 2019 Charon Technology G.K.
//
// 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 XCTest
import CharonCollectionTests
var tests = [XCTestCaseEntry]()
tests += CharonCollectionTests.allTests()
XCTMain(tests)
| 32.958333 | 75 | 0.756005 |
76bc52868dd0df41f85e718173df0cbe4d33709a | 1,723 | ////
// 🦠 Corona-Warn-App
//
#if !RELEASE
import Foundation
import OpenCombine
final class DMPosterGenerationViewModel {
// MARK: - Init
init(
traceLocation: TraceLocation,
qrCodePosterTemplateProvider: QRCodePosterTemplateProviding
) {
self.traceLocation = traceLocation
self.qrCodePosterTemplateProvider = qrCodePosterTemplateProvider
}
// MARK: - Internal
let traceLocation: TraceLocation
typealias QRCodePosterTemplateCompletionHandler = (Result<SAP_Internal_Pt_QRCodePosterTemplateIOS, Error>) -> Void
var title: String {
return traceLocation.description
}
var address: String {
return traceLocation.address
}
func fetchQRCodePosterTemplateData(completion: @escaping QRCodePosterTemplateCompletionHandler) {
qrCodePosterTemplateProvider.latestQRCodePosterTemplate()
.sink(
receiveCompletion: { result in
switch result {
case .finished:
break
case .failure(let error):
if case CachingHTTPClient.CacheError.dataVerificationError = error {
Log.error("Signature verification error.", log: .qrCode, error: error)
completion(.failure(error))
}
Log.error("Could not fetch QR code poster template protobuf.", log: .qrCode, error: error)
completion(.failure(error))
}
}, receiveValue: { [weak self] in
self?.qrCodePosterTemplate = $0
completion(.success($0))
}
)
.store(in: &subscriptions)
}
// MARK: - Private
private let qrCodePosterTemplateProvider: QRCodePosterTemplateProviding
private var subscriptions = Set<AnyCancellable>()
@OpenCombine.Published private(set) var qrCodePosterTemplate: SAP_Internal_Pt_QRCodePosterTemplateIOS = SAP_Internal_Pt_QRCodePosterTemplateIOS()
}
#endif
| 26.507692 | 146 | 0.746373 |
acc2003d18544afa69f4a551da770705b6b59f84 | 2,106 | //
// Font.swift
// InkwellExample
//
// Copyright (c) 2017 Vinh Nguyen
// 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.
//
/// The struct encapsulating font information.
public struct Font {
/// The font variant.
///
/// - regular: Regular.
/// - _700: Bold.
/// - italic: Italic.
/// - _700italic: BoldItalic.
public enum Variant: String {
/// Regular.
case regular
/// Bold.
case _700 = "700"
/// Italic.
case italic
/// BoldItalic
case _700italic = "700italic"
}
/// The font family.
public let family: String
/// The font variant.
public let variant: Variant
var name: String {
return "\(family)-\(variant.rawValue)"
}
var filename: String {
return "\(name).ttf"
}
/// Create a new font struct.
///
/// - Parameters:
/// - family: The font family.
/// - variant: The font variant.
public init(family: String, variant: Variant) {
self.family = family
self.variant = variant
}
}
| 28.849315 | 81 | 0.655271 |
eb6f8fa10bed8bc61c945c4d615ae2f7c59b7825 | 6,642 | // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -I %S/../IDE/Inputs/custom-modules %s -emit-silgen -enable-sil-ownership | %FileCheck %s
// REQUIRES: objc_interop
import Foundation
import ImportAsMember.Class
// CHECK-LABEL: sil shared [serializable] [thunk] @_T0So4HiveCSQyABGSQySo3BeeCG5queen_tcfCTO : $@convention(method) (@owned Optional<Bee>, @thick Hive.Type) -> @owned Optional<Hive>
func testInstanceTypeFactoryMethod(queen: Bee) {
// CHECK: bb0([[QUEEN:%[0-9]+]] : @owned $Optional<Bee>, [[HIVE_META:%[0-9]+]] : @trivial $@thick Hive.Type):
// CHECK-NEXT: [[HIVE_META_OBJC:%[0-9]+]] = thick_to_objc_metatype [[HIVE_META]] : $@thick Hive.Type to $@objc_metatype Hive.Type
// CHECK-NEXT: [[FACTORY:%[0-9]+]] = class_method [volatile] [[HIVE_META_OBJC]] : $@objc_metatype Hive.Type, #Hive.init!allocator.1.foreign : (Hive.Type) -> (Bee!) -> Hive!, $@convention(objc_method) (Optional<Bee>, @objc_metatype Hive.Type) -> @autoreleased Optional<Hive>
// CHECK-NEXT: [[HIVE:%[0-9]+]] = apply [[FACTORY]]([[QUEEN]], [[HIVE_META_OBJC]]) : $@convention(objc_method) (Optional<Bee>, @objc_metatype Hive.Type) -> @autoreleased Optional<Hive>
// CHECK-NEXT: destroy_value [[QUEEN]]
// CHECK-NEXT: return [[HIVE]] : $Optional<Hive>
var hive1 = Hive(queen: queen)
}
extension Hive {
// FIXME: This whole approach is wrong. This should be a factory initializer,
// not a convenience initializer, which means it does not have an initializing
// entry point at all.
// CHECK-LABEL: sil hidden @_T0So4HiveC17objc_factory_initEABSo3BeeC10otherQueen_tcfc : $@convention(method) (@owned Bee, @owned Hive) -> @owned Hive {
// CHECK: bb0([[QUEEN:%.*]] : @owned $Bee, [[OLD_HIVE:%.*]] : @owned $Hive):
// CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var Hive }, let, name "self"
// CHECK: [[MU:%.*]] = mark_uninitialized [delegatingself] [[SELF_BOX]]
// CHECK: [[PB_BOX:%.*]] = project_box [[MU]] : ${ var Hive }, 0
// CHECK: store [[OLD_HIVE]] to [init] [[PB_BOX]]
// CHECK: [[BORROWED_SELF:%.*]] = load_borrow [[PB_BOX]]
// CHECK: [[META:%[0-9]+]] = value_metatype $@thick Hive.Type, [[BORROWED_SELF]] : $Hive
// CHECK: end_borrow [[BORROWED_SELF]] from [[PB_BOX]]
// CHECK: [[FACTORY:%[0-9]+]] = class_method [volatile] [[META]] : $@thick Hive.Type, #Hive.init!allocator.1.foreign : (Hive.Type) -> (Bee!) -> Hive!, $@convention(objc_method) (Optional<Bee>, @objc_metatype Hive.Type) -> @autoreleased Optional<Hive>
// CHECK: [[OBJC_META:%[0-9]+]] = thick_to_objc_metatype [[META]] : $@thick Hive.Type to $@objc_metatype Hive.Type
// CHECK: [[BORROWED_QUEEN:%.*]] = begin_borrow [[QUEEN]]
// CHECK: [[COPIED_BORROWED_QUEEN:%.*]] = copy_value [[BORROWED_QUEEN]]
// CHECK: [[OPT_COPIED_BORROWED_QUEEN:%.*]] = enum $Optional<Bee>, #Optional.some!enumelt.1, [[COPIED_BORROWED_QUEEN]]
// CHECK: [[NEW_HIVE:%.*]] = apply [[FACTORY]]([[OPT_COPIED_BORROWED_QUEEN]], [[OBJC_META]]) : $@convention(objc_method) (Optional<Bee>, @objc_metatype Hive.Type) -> @autoreleased Optional<Hive>
// CHECK: destroy_value [[OPT_COPIED_BORROWED_QUEEN]]
// CHECK: end_borrow [[BORROWED_QUEEN]] from [[QUEEN]]
// CHECK: switch_enum [[NEW_HIVE]] : $Optional<Hive>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]]
//
// CHECK: [[SOME_BB]]([[NEW_HIVE:%.*]] : @owned $Hive):
// CHECK: assign [[NEW_HIVE]] to [[PB_BOX]]
// CHECK: } // end sil function '_T0So4HiveC17objc_factory_initEABSo3BeeC10otherQueen_tcfc'
convenience init(otherQueen other: Bee) {
self.init(queen: other)
}
// CHECK-LABEL: sil hidden @_T0So4HiveC17objc_factory_initEABSo3BeeC15otherFlakyQueen_tKcfC : $@convention(method) (@owned Bee, @thick Hive.Type) -> (@owned Hive, @error Error) {
// CHECK: bb0([[QUEEN:%.*]] : @owned $Bee, [[METATYPE:%.*]] : @trivial $@thick Hive.Type):
// CHECK: [[OBJC_METATYPE:%.*]] = thick_to_objc_metatype [[METATYPE]]
// CHECK: [[HIVE:%.*]] = alloc_ref_dynamic [objc] [[OBJC_METATYPE]]
// CHECK: try_apply {{.*}}([[QUEEN]], [[HIVE]]) : $@convention(method) (@owned Bee, @owned Hive) -> (@owned Hive, @error Error), normal [[NORMAL_BB:bb[0-9]+]], error [[ERROR_BB:bb[0-9]+]]
//
// CHECK: [[NORMAL_BB]]([[HIVE:%.*]] : @owned $Hive):
// CHECK: return [[HIVE]]
//
// CHECK: [[ERROR_BB]]([[ERROR:%.*]] : @owned $Error):
// CHECK: builtin "willThrow"([[ERROR]] : $Error)
// CHECK: throw [[ERROR]]
// CHECK: } // end sil function '_T0So4HiveC17objc_factory_initEABSo3BeeC15otherFlakyQueen_tKcfC'
convenience init(otherFlakyQueen other: Bee) throws {
try self.init(flakyQueen: other)
}
}
extension SomeClass {
// CHECK-LABEL: sil hidden @_T0So9SomeClassC17objc_factory_initEABSd6double_tcfc : $@convention(method) (Double, @owned SomeClass) -> @owned SomeClass {
// CHECK: bb0([[DOUBLE:%.*]] : @trivial $Double,
// CHECK-NOT: value_metatype
// CHECK: [[FNREF:%[0-9]+]] = function_ref @MakeIAMSomeClass
// CHECK: apply [[FNREF]]([[DOUBLE]])
// CHECK: } // end sil function '_T0So9SomeClassC17objc_factory_initEABSd6double_tcfc'
convenience init(double: Double) {
self.init(value: double)
}
}
class SubHive : Hive {
// CHECK-LABEL: sil hidden @_T017objc_factory_init7SubHiveCACyt20delegatesToInherited_tcfc : $@convention(method) (@owned SubHive) -> @owned SubHive {
// CHECK: bb0([[SUBHIVE:%.*]] : @owned $SubHive):
// CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var SubHive }, let, name "self"
// CHECK: [[MU:%.*]] = mark_uninitialized [delegatingself] [[SELF_BOX]] : ${ var SubHive }
// CHECK: [[PB_BOX:%.*]] = project_box [[MU]] : ${ var SubHive }, 0
// CHECK: store [[SUBHIVE]] to [init] [[PB_BOX]]
// CHECK: [[BORROWED_SELF:%.*]] = load_borrow [[PB_BOX]]
// CHECK: [[UPCAST_BORROWED_SELF:%.*]] = upcast [[BORROWED_SELF]] : $SubHive to $Hive
// CHECK: [[METATYPE:%.*]] = value_metatype $@thick Hive.Type, [[UPCAST_BORROWED_SELF:%.*]]
// CHECK: end_borrow [[BORROWED_SELF]] from [[PB_BOX]]
// CHECK: [[HIVE_INIT_FN:%.*]] = class_method [volatile] [[METATYPE]] : $@thick Hive.Type, #Hive.init!allocator.1.foreign
// CHECK: [[OBJC_METATYPE:%.*]] = thick_to_objc_metatype [[METATYPE]]
// CHECK: [[QUEEN:%.*]] = unchecked_ref_cast {{.*}} : $Bee to $Optional<Bee>
// CHECK: apply [[HIVE_INIT_FN]]([[QUEEN]], [[OBJC_METATYPE]]) : $@convention(objc_method) (Optional<Bee>, @objc_metatype Hive.Type) -> @autoreleased Optional<Hive>
// CHECK: destroy_value [[QUEEN]]
// CHECK: } // end sil function '_T017objc_factory_init7SubHiveCACyt20delegatesToInherited_tcfc'
convenience init(delegatesToInherited: ()) {
self.init(queen: Bee())
}
}
| 65.762376 | 277 | 0.655977 |
9ccc5ff7886f3c407ad7a9a78a23d3aa8f14f5c2 | 1,978 | //
// DMGoldPerMin.swift
//
// Created by Philip DesJean on 9/11/16
// Copyright (c) . All rights reserved.
//
import Foundation
import SwiftyJSON
open class DMGoldPerMin: NSObject, NSCoding {
// MARK: Declaration for string constants to be used to decode and also serialize.
internal let kDMGoldPerMinPctKey: String = "pct"
internal let kDMGoldPerMinRawKey: String = "raw"
// MARK: Properties
open var pct: Float?
open var raw: Int?
// MARK: SwiftyJSON Initalizers
/**
Initates the class based on the object
- parameter object: The object of either Dictionary or Array kind that was passed.
- returns: An initalized instance of the class.
*/
convenience public init(object: AnyObject) {
self.init(json: JSON(object))
}
/**
Initates the class based on the JSON that was passed.
- parameter json: JSON object from SwiftyJSON.
- returns: An initalized instance of the class.
*/
public init(json: JSON) {
pct = json[kDMGoldPerMinPctKey].float
raw = json[kDMGoldPerMinRawKey].int
}
/**
Generates description of the object in the form of a NSDictionary.
- returns: A Key value pair containing all valid values in the object.
*/
open func dictionaryRepresentation() -> [String : AnyObject ] {
var dictionary: [String : AnyObject ] = [ : ]
if pct != nil {
dictionary.updateValue(pct! as AnyObject, forKey: kDMGoldPerMinPctKey)
}
if raw != nil {
dictionary.updateValue(raw! as AnyObject, forKey: kDMGoldPerMinRawKey)
}
return dictionary
}
// MARK: NSCoding Protocol
required public init(coder aDecoder: NSCoder) {
self.pct = aDecoder.decodeObject(forKey: kDMGoldPerMinPctKey) as? Float
self.raw = aDecoder.decodeObject(forKey: kDMGoldPerMinRawKey) as? Int
}
open func encode(with aCoder: NSCoder) {
aCoder.encode(pct, forKey: kDMGoldPerMinPctKey)
aCoder.encode(raw, forKey: kDMGoldPerMinRawKey)
}
}
| 26.026316 | 86 | 0.688574 |
de69d0464490e489d099dbea20df2bf257c33168 | 1,070 | //
// Joint.swift
//
import Foundation
public protocol AnyJoint: class {
func broadcast()
func invalidate()
}
public class Joint<Sender: Sendable> {
typealias Value = Sender.SendValue
public weak var sender: Sender?
public var handlers: [Any] = []
public var subJoints: [AnyJoint] = []
init(sender: Sender) {
self.sender = sender
}
deinit {
self.sender?.core.remove(joint: self)
}
func call(first value: Value) {
if let handler = self.handlers.first as? (Value) -> Void {
handler(value)
}
}
}
extension Joint: AnyJoint {
public func broadcast() {
self.sender?.fetch(for: self)
for subJoint in self.subJoints {
subJoint.broadcast()
}
}
public func invalidate() {
for subJoint in self.subJoints {
subJoint.invalidate()
}
self.sender?.core.remove(joint: self)
self.sender = nil
self.handlers = []
self.subJoints = []
}
}
| 19.814815 | 66 | 0.550467 |
23ae4af996db5a5c165fe4dfae0c3a60fa272d6c | 278 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
let a {
let f = [ {
for {
extension NSData {
protocol a
{
class A {
func a( ) {
case
{
enum A {
class
case ,
| 15.444444 | 87 | 0.701439 |
4b1abbdf756c196d449d5de494270ac3d76e447e | 11,540 | //
// PaymentQueueController.swift
// SwiftyStoreKit
//
// Copyright (c) 2017 Andrea Bizzotto ([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
import StoreKit
protocol TransactionController {
/// Process the supplied transactions on a given queue.
/// - parameter transactions: transactions to process
/// - parameter paymentQueue: payment queue for finishing transactions
/// - returns: array of unhandled transactions
func processTransactions(_ transactions: [SKPaymentTransaction], on paymentQueue: PaymentQueue) -> [SKPaymentTransaction]
}
public enum TransactionResult {
case purchased(purchase: PurchaseDetails)
case restored(purchase: Purchase)
case deferred(purchase: PurchaseDetails)
case failed(error: SKError)
}
public protocol PaymentQueue: AnyObject {
func add(_ observer: SKPaymentTransactionObserver)
func remove(_ observer: SKPaymentTransactionObserver)
func add(_ payment: SKPayment)
func start(_ downloads: [SKDownload])
func pause(_ downloads: [SKDownload])
func resume(_ downloads: [SKDownload])
func cancel(_ downloads: [SKDownload])
func restoreCompletedTransactions(withApplicationUsername username: String?)
func finishTransaction(_ transaction: SKPaymentTransaction)
}
extension SKPaymentQueue: PaymentQueue {
#if os(watchOS) && swift(<5.3)
public func resume(_ downloads: [SKDownload]) {
resumeDownloads(downloads)
}
#endif
}
extension SKPaymentTransaction {
open override var debugDescription: String {
let transactionId = transactionIdentifier ?? "null"
return "productId: \(payment.productIdentifier), transactionId: \(transactionId), state: \(transactionState), date: \(String(describing: transactionDate))"
}
}
extension SKPaymentTransactionState: CustomDebugStringConvertible {
public var debugDescription: String {
switch self {
case .purchasing: return "purchasing"
case .purchased: return "purchased"
case .failed: return "failed"
case .restored: return "restored"
case .deferred: return "deferred"
@unknown default: return "default"
}
}
}
struct EntitlementRevocation {
let callback: ([String]) -> Void
init(callback: @escaping ([String]) -> Void) {
self.callback = callback
}
}
class PaymentQueueController: NSObject, SKPaymentTransactionObserver {
private let paymentsController: PaymentsController
private let restorePurchasesController: RestorePurchasesController
private let completeTransactionsController: CompleteTransactionsController
unowned let paymentQueue: PaymentQueue
private var entitlementRevocation: EntitlementRevocation?
deinit {
paymentQueue.remove(self)
}
init(paymentQueue: PaymentQueue = SKPaymentQueue.default(),
paymentsController: PaymentsController = PaymentsController(),
restorePurchasesController: RestorePurchasesController = RestorePurchasesController(),
completeTransactionsController: CompleteTransactionsController = CompleteTransactionsController()) {
self.paymentQueue = paymentQueue
self.paymentsController = paymentsController
self.restorePurchasesController = restorePurchasesController
self.completeTransactionsController = completeTransactionsController
super.init()
paymentQueue.add(self)
}
private func assertCompleteTransactionsWasCalled() {
let message = "SwiftyStoreKit.completeTransactions() must be called when the app launches."
assert(completeTransactionsController.completeTransactions != nil, message)
}
func startPayment(_ payment: Payment) {
assertCompleteTransactionsWasCalled()
let skPayment = SKMutablePayment(product: payment.product)
skPayment.applicationUsername = payment.applicationUsername
skPayment.quantity = payment.quantity
if #available(iOS 12.2, tvOS 12.2, OSX 10.14.4, watchOS 6.2, *) {
if let discount = payment.paymentDiscount?.discount as? SKPaymentDiscount {
skPayment.paymentDiscount = discount
}
}
#if os(iOS) || os(tvOS) || os(watchOS)
if #available(iOS 8.3, watchOS 6.2, *) {
skPayment.simulatesAskToBuyInSandbox = payment.simulatesAskToBuyInSandbox
}
#endif
paymentQueue.add(skPayment)
paymentsController.append(payment)
}
func onEntitlementRevocation(_ revocation: EntitlementRevocation) {
guard entitlementRevocation == nil else {
print("SwiftyStoreKit.onEntitlementRevocation() should only be called once when the app launches. Ignoring this call")
return
}
self.entitlementRevocation = revocation
}
func restorePurchases(_ restorePurchases: RestorePurchases) {
assertCompleteTransactionsWasCalled()
if restorePurchasesController.restorePurchases != nil {
return
}
paymentQueue.restoreCompletedTransactions(withApplicationUsername: restorePurchases.applicationUsername)
restorePurchasesController.restorePurchases = restorePurchases
}
func completeTransactions(_ completeTransactions: CompleteTransactions) {
guard completeTransactionsController.completeTransactions == nil else {
print("SwiftyStoreKit.completeTransactions() should only be called once when the app launches. Ignoring this call")
return
}
completeTransactionsController.completeTransactions = completeTransactions
}
func finishTransaction(_ transaction: PaymentTransaction) {
guard let skTransaction = transaction as? SKPaymentTransaction else {
print("Object is not a SKPaymentTransaction: \(transaction)")
return
}
paymentQueue.finishTransaction(skTransaction)
}
func start(_ downloads: [SKDownload]) {
paymentQueue.start(downloads)
}
func pause(_ downloads: [SKDownload]) {
paymentQueue.pause(downloads)
}
func resume(_ downloads: [SKDownload]) {
paymentQueue.resume(downloads)
}
func cancel(_ downloads: [SKDownload]) {
paymentQueue.cancel(downloads)
}
var shouldAddStorePaymentHandler: ShouldAddStorePaymentHandler?
var updatedDownloadsHandler: UpdatedDownloadsHandler?
// MARK: - SKPaymentTransactionObserver
func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
/*
* Some notes about how requests are processed by SKPaymentQueue:
*
* SKPaymentQueue is used to queue payments or restore purchases requests.
* Payments are processed serially and in-order and require user interaction.
* Restore purchases requests don't require user interaction and can jump ahead of the queue.
* SKPaymentQueue rejects multiple restore purchases calls.
* Having one payment queue observer for each request causes extra processing
* Failed transactions only ever belong to queued payment requests.
* restoreCompletedTransactionsFailedWithError is always called when a restore purchases request fails.
* paymentQueueRestoreCompletedTransactionsFinished is always called following 0 or more update transactions when a restore purchases request succeeds.
* A complete transactions handler is required to catch any transactions that are updated when the app is not running.
* Registering a complete transactions handler when the app launches ensures that any pending transactions can be cleared.
* If a complete transactions handler is missing, pending transactions can be mis-attributed to any new incoming payments or restore purchases.
*
* The order in which transaction updates are processed is:
* 1. payments (transactionState: .purchased and .failed for matching product identifiers)
* 2. restore purchases (transactionState: .restored, or restoreCompletedTransactionsFailedWithError, or paymentQueueRestoreCompletedTransactionsFinished)
* 3. complete transactions (transactionState: .purchased, .failed, .restored, .deferred)
* Any transactions where state == .purchasing are ignored.
*/
var unhandledTransactions = transactions.filter { $0.transactionState != .purchasing }
if unhandledTransactions.count > 0 {
unhandledTransactions = paymentsController.processTransactions(transactions, on: paymentQueue)
unhandledTransactions = restorePurchasesController.processTransactions(unhandledTransactions, on: paymentQueue)
unhandledTransactions = completeTransactionsController.processTransactions(unhandledTransactions, on: paymentQueue)
if unhandledTransactions.count > 0 {
let strings = unhandledTransactions.map { $0.debugDescription }.joined(separator: "\n")
print("unhandledTransactions:\n\(strings)")
}
}
}
func paymentQueue(_ queue: SKPaymentQueue, didRevokeEntitlementsForProductIdentifiers productIdentifiers: [String]) {
self.entitlementRevocation?.callback(productIdentifiers)
}
func paymentQueue(_ queue: SKPaymentQueue, removedTransactions transactions: [SKPaymentTransaction]) {
}
func paymentQueue(_ queue: SKPaymentQueue, restoreCompletedTransactionsFailedWithError error: Error) {
restorePurchasesController.restoreCompletedTransactionsFailed(withError: error)
}
func paymentQueueRestoreCompletedTransactionsFinished(_ queue: SKPaymentQueue) {
restorePurchasesController.restoreCompletedTransactionsFinished()
}
func paymentQueue(_ queue: SKPaymentQueue, updatedDownloads downloads: [SKDownload]) {
updatedDownloadsHandler?(downloads)
}
#if !os(watchOS)
func paymentQueue(_ queue: SKPaymentQueue, shouldAddStorePayment payment: SKPayment, for product: SKProduct) -> Bool {
return shouldAddStorePaymentHandler?(payment, product) ?? false
}
#endif
}
| 40.921986 | 163 | 0.707279 |
4b8feacea655f4cdc131b5150ec7a1ee3ea81a50 | 1,444 | //
// 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
let result = "result"
let doubleValue = 12.34
let valueStr = String(format: "%.1f", doubleValue)
var str = "The \(result) is \(valueStr)."
print(str)
// The result is 12.3.
str = "The \(result) is \(round(doubleValue * 10.0) / 10.0)."
print(str)
// The result is 12.3.
| 40.111111 | 81 | 0.731302 |
61c4134e6dbb2ecf341170ffd6740e057562a10f | 1,949 | //
// Label.swift
// Floral
//
// Created by LDD on 2019/7/18.
// Copyright © 2019 文刂Rn. All rights reserved.
//
import UIKit
class Label: UILabel {
var textInsets = UIEdgeInsets.zero {
didSet { invalidateIntrinsicContentSize() }
}
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupUI()
}
func setupUI() {
layer.masksToBounds = true
numberOfLines = 1
// cornerRadius = Configs.BaseDimensions.cornerRadius
updateUI()
}
func updateUI() {
setNeedsDisplay()
}
}
extension Label {
override func textRect(forBounds bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
let insetRect = bounds.inset(by: textInsets)
let textRect = super.textRect(forBounds: insetRect, limitedToNumberOfLines: numberOfLines)
let invertedInsets = UIEdgeInsets(top: -textInsets.top,
left: -textInsets.left,
bottom: -textInsets.bottom,
right: -textInsets.right)
return textRect.inset(by: invertedInsets)
}
override func drawText(in rect: CGRect) {
super.drawText(in: rect.inset(by: textInsets))
}
var leftTextInset: CGFloat {
set { textInsets.left = newValue }
get { return textInsets.left }
}
var rightTextInset: CGFloat {
set { textInsets.right = newValue }
get { return textInsets.right }
}
var topTextInset: CGFloat {
set { textInsets.top = newValue }
get { return textInsets.top }
}
var bottomTextInset: CGFloat {
set { textInsets.bottom = newValue }
get { return textInsets.bottom }
}
}
| 25.644737 | 107 | 0.572601 |
e8dec605da9d415db15d7648d62571a680d9dd25 | 2,810 | //
// LayoutBuilder.swift
// LayoutBuilder
//
// Created by Ihor Malovanyi on 04.05.2021.
//
#if canImport(UIKit)
import UIKit
#elseif canImport(AppKit)
import AppKit
#endif
public class Layout {
///All constraints in the Layout instance
private(set) var constraints: [NSLayoutConstraint] = []
///Layout active status. Shows built constraints are active or not
private(set) var isActive = true {
didSet {
constraints.forEach { $0.isActive = isActive }
}
}
@resultBuilder
public struct LayoutResultBuilder {
public static func buildBlock(_ components: ConstraintsGroup...) -> [NSLayoutConstraint] { components.flatMap(\.constraints) }
public static func buildOptional(_ components: [ConstraintsGroup]?) -> [NSLayoutConstraint] { components?.flatMap(\.constraints) ?? [] }
public static func buildEither(first components: [ConstraintsGroup]) -> [NSLayoutConstraint] { components.flatMap(\.constraints) }
public static func buildEither(second components: [ConstraintsGroup]) -> [NSLayoutConstraint] { components.flatMap(\.constraints) }
public static func buildArray(_ components: [[ConstraintsGroup]]) -> [NSLayoutConstraint] { components.reduce([], +).flatMap(\.constraints) }
}
@discardableResult
public init(@LayoutResultBuilder _ build: () -> [NSLayoutConstraint]) {
constraints = buildConstraints(build)
}
private func buildConstraints(@LayoutResultBuilder _ build: () -> [NSLayoutConstraint]) -> [NSLayoutConstraint] {
let constraints = build()
constraints.forEach {
($0.firstItem as? View)?.translatesAutoresizingMaskIntoConstraints = false
}
if isActive {
NSLayoutConstraint.activate(constraints)
}
return constraints
}
///Deactivates all constraints previously built in the Layout instance and replaces them with new constraints build.
public func rebuild(@LayoutResultBuilder _ build: () -> [NSLayoutConstraint]) {
let oldActiveStatus = isActive
deactivate()
constraints.removeAll()
if oldActiveStatus {
activate()
}
constraints = buildConstraints(build)
}
///Appends new constraints to exist in the Layout instance constraints. Activates them if `isActive` is true.
public func append(@LayoutResultBuilder _ build: () -> [NSLayoutConstraint]) {
constraints += buildConstraints(build)
}
///Deactivates all constraints in the Layout instance
public func deactivate() {
isActive = false
}
///Activates all constraints in the Layout instance
public func activate() {
isActive = true
}
}
| 34.691358 | 149 | 0.657651 |
f9f6259bdab36bd34e7a47dd56e87a407d15aa67 | 273 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/fluidsonic (Marc Knaup)
class A {
func a() -> String {
struct c {
static let a = {
self.a()
}()
}
}
}
| 21 | 79 | 0.509158 |
f42c79ca91305f7a4637aa5b5cef2abbf009810a | 956 | //
// textKitTests.swift
// textKitTests
//
// Created by jyh on 2017/12/15.
// Copyright © 2017年 jyh. All rights reserved.
//
import XCTest
@testable import textKit
class textKitTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 25.837838 | 111 | 0.628661 |
9c9d13c00ce6f29751a513b0e20deedb6377995e | 1,209 | import UIKit
var str = "Reverse an array"
extension Array {
// Iterative approach
func reverseArrUsingIterativeApproach() -> Array {
var startIndex = 0
var endIndex = self.count - 1
var output = self
while startIndex < endIndex {
let temp = self[startIndex]
output[startIndex] = self[endIndex]
output[endIndex] = temp
startIndex += 1
endIndex -= 1
}
return output
}
// Recursive approach
func reverseArrUsingRecursiveApproach(arr: inout Array, startIndex: Int, endIndex: Int) {
if startIndex >= endIndex {
return
}
let temp = arr[startIndex]
arr[startIndex] = arr[endIndex]
arr[endIndex] = temp
reverseArrUsingRecursiveApproach(arr: &arr, startIndex: startIndex + 1, endIndex: endIndex - 1)
}
}
var arr1 = [1,2,3,4,5]
assert(arr1.reverseArrUsingIterativeApproach() == arr1.reversed())
var arr2 = [1,2,3,4,5]
arr2.reverseArrUsingRecursiveApproach(arr: &arr2, startIndex: 0, endIndex: arr2.count - 1)
assert(arr2 == [5,4,3,2,1])
| 25.723404 | 103 | 0.569892 |
488f3fa7e2b1388b61cb5f1b618899b04729ff5c | 440 | //
// ___FILENAME___
// ___PROJECTNAME___
//
// Created ___FULLUSERNAME___ on ___DATE___.
// Copyright © ___YEAR___ ___ORGANIZATIONNAME___. All rights reserved.
//
import Foundation
protocol ___VARIABLE_MODULENAME___Presenter: class {
var router: ___VARIABLE_MODULENAME___Router? { get set }
var interactor: ___VARIABLE_MODULENAME___Interactor? { get set }
var view: ___VARIABLE_MODULENAME___View? { get set }
}
| 24.444444 | 71 | 0.752273 |
23048708284001f2dd88e9eed5e8c2111ff2bc27 | 3,633 | //
// DetailInfoCell.swift
// Technical_Exercise
//
// Created by Fuh chang Loi on 29/5/21.
//
import Foundation
import UIKit
class DetailInfoCell: UITableViewCell {
lazy var avatarView: UIImageView = {
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFit
return imageView
}()
lazy var displayName: UILabel = {
let label = UILabel()
label.font = UIFont.boldSystemFont(ofSize: 20.0)
return label
}()
lazy var displayType: UILabel = {
let label = UILabel()
label.font = UIFont.boldSystemFont(ofSize: 15.0)
return label
}()
lazy var displayDate: UILabel = {
let label = UILabel()
return label
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
layout()
addConstraints()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func configure(name: String, type: String, date: String, imageData: Data?) {
if let imgData = imageData {
avatarView.image = UIImage(data: imgData)
avatarView.contentMode = .scaleAspectFit
}
displayName.text = "Display name: \(name)"
displayType.text = "Owner Type: \(type)"
displayDate.text = "Created on: \(Utility.shared.dateFormatter(strDate: date))"
}
func layout() {
self.addSubview(avatarView)
self.addSubview(displayName)
self.addSubview(displayType)
self.addSubview(displayDate)
}
private func addConstraints() {
avatarView.translatesAutoresizingMaskIntoConstraints = false
avatarView.widthAnchor.constraint(equalToConstant: 80).isActive = true
avatarView.heightAnchor.constraint(equalToConstant: 100).isActive = true
avatarView.contentMode = .scaleAspectFit
avatarView.topAnchor.constraint(equalTo: self.safeAreaLayoutGuide.topAnchor).isActive = true
avatarView.leadingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.leadingAnchor, constant: 5).isActive = true
avatarView.bottomAnchor.constraint(equalTo: self.safeAreaLayoutGuide.bottomAnchor).isActive = true
displayName.translatesAutoresizingMaskIntoConstraints = false
displayName.leadingAnchor.constraint(equalTo: avatarView.safeAreaLayoutGuide.trailingAnchor, constant: 5).isActive = true
displayName.trailingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.trailingAnchor).isActive = true
displayName.bottomAnchor.constraint(equalTo: displayType.safeAreaLayoutGuide.topAnchor, constant: -5).isActive = true
displayType.translatesAutoresizingMaskIntoConstraints = false
displayType.centerYAnchor.constraint(equalTo: avatarView.safeAreaLayoutGuide.centerYAnchor).isActive = true
displayType.leadingAnchor.constraint(equalTo: avatarView.safeAreaLayoutGuide.trailingAnchor, constant: 5).isActive = true
displayType.trailingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.trailingAnchor).isActive = true
displayDate.translatesAutoresizingMaskIntoConstraints = false
displayDate.topAnchor.constraint(equalTo: displayType.safeAreaLayoutGuide.bottomAnchor, constant: 5).isActive = true
displayDate.leadingAnchor.constraint(equalTo: avatarView.safeAreaLayoutGuide.trailingAnchor, constant: 5).isActive = true
displayDate.trailingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.trailingAnchor).isActive = true
}
}
| 42.741176 | 129 | 0.709331 |
28fd93e847dc42a7af32e10121767420f0f14293 | 1,402 | //
// AppDelegate.swift
// Calculator
//
// Created by ray on 2020/5/24.
// Copyright © 2020 ray. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
| 36.894737 | 179 | 0.746077 |
2282c260c770e5d8048741fd1a6ed59ea97d755b | 1,341 | //
// Preferences.swift
// GIFSearch
//
// Created by Moshe Berman on 9/4/17.
// Copyright © 2017 Moshe Berman. All rights reserved.
//
import Foundation
class Preferences: NSObject {
// MARK: - Singleton Access
static let shared = Preferences()
private override init() {
super.init()
self.registerDefaults()
}
// MARK: - Default Preferences
/// Register default values for the preferences.
func registerDefaults()
{
UserDefaults.standard.register(defaults: [
PreferencesKey.rating.rawValue : "G",
PreferencesKey.language.rawValue : "en"
])
}
// MARK: - Setting a Specific Preference
func set(preference: String, for key: PreferencesKey)
{
UserDefaults.standard.set(preference, forKey: key.rawValue)
NotificationCenter.default.post(name: Notification.Name.PreferencesChanged, object: nil, userInfo:[key:preference])
}
// MARK: - Accessing a Specific Preference
func preference(for key: PreferencesKey) -> String?
{
guard let preference = UserDefaults.standard.string(forKey: key.rawValue) else
{
print("\(self.self): Could not read preference for key \(key.rawValue).")
return nil
}
return preference
}
}
| 26.82 | 123 | 0.623415 |
e2e976c57c33fd85d8762278c11fbc5b8c82896d | 1,219 | //
// MainUser.swift
// Valeo
//
// Created by Laurenz Hill on 13.12.20.
//
import SwiftUI
/// Main user view.
/// Displays all interesting information of a user by using grafics etc.
struct MainUser: View {
@EnvironmentObject var navigator: Navigator
@EnvironmentObject var user: UserViewModel
@Environment(\.colorScheme) var scheme
var body: some View {
NavigationView{
UserView()
.navigationBarTitle(user.name + " \(user.age)")
.navigationBarItems(leading: Button(action: { withAnimation {
navigator.setCurrentView(to: .main)
}}, label: {
Image(systemName: "chevron.left")
.font(.title3)
.foregroundColor(self.scheme == .dark ? .white : .black)
.animation(.easeIn)
.padding(.trailing, 20)
.padding(.vertical, 10)
}))
}
}
}
struct MainUser_Previews: PreviewProvider {
static var previews: some View {
MainUser()
.environmentObject(Navigator())
.environmentObject(UserViewModel())
}
}
| 27.704545 | 80 | 0.538966 |
767b4b244a5e9ca0e98f176e685351863ea4bfab | 773 | //
// ModuleTemplatePresenter.swift
// MG2
//
// Created by Darko Damjanovic on 29.05.18.
// Copyright © 2018 Marktguru. All rights reserved.
//
import Foundation
protocol ModuleTemplatePresenterProtocol {
}
/// This is just a template which can be re-used to create other modules.
/// It is not compiled with the project.
class ModuleTemplatePresenter {
private let log = Logger()
private unowned let view: ModuleTemplateViewProtocol
private let router: ModuleTemplateRouterProtocol
init(view: ModuleTemplateViewProtocol, router: ModuleTemplateRouterProtocol) {
self.view = view
self.router = router
}
deinit {
log.info("")
}
}
extension ModuleTemplatePresenter: ModuleTemplatePresenterProtocol {
}
| 21.472222 | 82 | 0.712807 |
1a00684a6a9be84da20e4a2be73fca09ee9f4585 | 554 | //
// AppDelegate.swift
// DouYuZhiBo
//
// Created by 买明 on 22/04/2017.
// Copyright © 2017 买明. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
UITabBar.appearance().tintColor = .orange
UINavigationBar.appearance().barTintColor = .orange
return true
}
}
| 21.307692 | 144 | 0.6787 |
01af4dfd18bbea116c312e651d156e4b1d99256f | 9,628 | //
// StringExtension.swift
// DatianFinancial
//
// Created by gaof on 2018/8/16.
// Copyright © 2018年 qiaoxy. All rights reserved.
//
import UIKit
import AVFoundation
import CommonCrypto
extension String {
func size(with font: UIFont, maxSize: CGSize) -> CGSize{
let attrs = [NSAttributedString.Key.font: font]
let string = NSString(string: self)
return string.boundingRect(with: maxSize, options: .usesLineFragmentOrigin, attributes: attrs, context: nil).size
}
func toObj() -> Dictionary<String,Any>? {
let data = self.data(using: .utf8)!
do {
if let jsonObj = try JSONSerialization.jsonObject(with: data, options : .allowFragments) as? Dictionary<String,Any>
{
return jsonObj
} else {
return nil
}
} catch let error as NSError {
return nil
}
}
///网络路径获取
func oe_getScreenShotImageFromVideoURL() -> UIImage? {
let asset = AVAsset(url: URL(string: self)!)
let gen = AVAssetImageGenerator(asset: asset)
gen.appliesPreferredTrackTransform = true
let time = CMTime(seconds: 0.0, preferredTimescale: 600)
var actualTime:CMTime = CMTime()
var shotImage:UIImage?
do {
let image = try gen.copyCGImage(at: time, actualTime: &actualTime)
shotImage = UIImage(cgImage: image)
}catch {
shotImage = nil
}
return shotImage
}
var floatValue: Float {
return (self as NSString).floatValue
}
//拼接必填星号
func requiredStar() -> NSMutableAttributedString {
let muAttri = NSMutableAttributedString(string: self, attributes: [NSAttributedString.Key.foregroundColor:UIColor.gray6Color])
let starAttri = NSAttributedString(string: "*", attributes: [NSAttributedString.Key.foregroundColor : UIColor.red])
muAttri.append(starAttri)
return muAttri
}
func formatterPhone() -> String {
if self.count == 11 {
let range = Range(NSRange(location: 3, length: 4), in: self)
let formatterStr = self.replacingCharacters(in: range!, with: "****")
return formatterStr
}
return self
}
func md5() -> String {
let str = self.cString(using: String.Encoding.utf8)
let strLen = CUnsignedInt(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_MD5_DIGEST_LENGTH)
let result = UnsafeMutablePointer<UInt8>.allocate(capacity: 16)
CC_MD5(str!, strLen, result)
let hash = NSMutableString()
for i in 0 ..< digestLen {
hash.appendFormat("%02x", result[i])
}
free(result)
return String(format: hash as String)
}
func changeTextColor(text: String, color: UIColor, range: NSRange) -> NSAttributedString {
let attributeStr = NSMutableAttributedString(string:text);attributeStr.addAttribute(NSAttributedString.Key.foregroundColor, value:color , range: range)
return attributeStr
}
func subString(start:Int,length:Int = -1) -> String {
var len = length
if len == -1 {
len = self.count - start
}
let st = self.index(startIndex, offsetBy: start)
let en = self.index(st, offsetBy: len)
return String(self[st ..< en])
}
func toRange(_ range: NSRange) -> Range<String.Index>? {
guard let from16 = utf16.index(utf16.startIndex, offsetBy: range.location, limitedBy: utf16.endIndex) else { return nil }
guard let to16 = utf16.index(from16, offsetBy: range.length, limitedBy: utf16.endIndex) else { return nil }
guard let from = String.Index(from16, within: self) else { return nil }
guard let to = String.Index(to16, within: self) else { return nil }
return from ..< to
}
/// 根据亩数获得平方米
///
/// - Returns: 面积平方米
func transformMuToMeter() -> String {
let area = (Double(self) ?? 0) / 0.0015
return String(format: "%.2f", area)
}
/// 将平方米转为亩
func transformMeterToMu() -> String {
let acreageFloat = (Double(self) ?? 0) / 666.67
return String(format: "%.1f", acreageFloat)
}
func getVedioImage(imageBlock:@escaping (UIImage)->()) {
//异步获取网络视频
DispatchQueue.global().async {
//获取网络视频
let videoURL = URL(string: self)!
let avAsset = AVURLAsset(url: videoURL )
//生成视频截图
let generator = AVAssetImageGenerator(asset: avAsset)
generator.appliesPreferredTrackTransform = true
let time = CMTimeMakeWithSeconds(0.0,preferredTimescale: 600)
var actualTime:CMTime = CMTimeMake(value: 0,timescale: 0)
do {
let imageRef:CGImage = try generator.copyCGImage(at: time, actualTime: &actualTime)
let frameImg = UIImage(cgImage: imageRef)
//在主线程中显示截图
DispatchQueue.main.async(execute: {
imageBlock(frameImg)
})
}catch let error {
print(error)
}
}
}
static func windOrientation(wind:String) -> String {
var windOrientation = ""
switch wind {
case "0.0":
windOrientation = "北风"
case "22.5":
windOrientation = "北东北风"
case "45.0":
windOrientation = "东北风"
case "67.5":
windOrientation = "东东北风"
case "90.0":
windOrientation = "东风"
case "112.5":
windOrientation = "东东南风"
case "135.0":
windOrientation = "东南风"
case "157.5":
windOrientation = "南东南风"
case "180.0":
windOrientation = "南风"
case "202.5":
windOrientation = "南西南风"
case "225.0":
windOrientation = "西南风"
case "247.5":
windOrientation = "西西南风"
case "270.0":
windOrientation = "西风"
case "295.5":
windOrientation = "西西北风"
case "315.0":
windOrientation = "西北风"
case "337.5":
windOrientation = "北西北风"
default:
break
}
return windOrientation
}
static func toWeekWithNumber(num:String) -> String {
var week = ""
switch num {
case "1":
week = "每周一"
case "2":
week = "每周二"
case "3":
week = "每周三"
case "4":
week = "每周四"
case "5":
week = "每周五"
case "6":
week = "每周六"
case "7":
week = "每周日"
default:
break
}
return week
}
var htmlToAttributedString: NSAttributedString? {
guard let data = data(using: .utf8) else { return NSAttributedString() }
do {
return try NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding:String.Encoding.utf8.rawValue], documentAttributes: nil)
} catch {
return NSAttributedString()
}
}
var htmlToString: String {
return htmlToAttributedString?.string ?? ""
}
func getFileSize() -> UInt64 {
var size: UInt64 = 0
let fileManager = FileManager.default
var isDir: ObjCBool = false
let isExists = fileManager.fileExists(atPath: self, isDirectory: &isDir)
// 判断文件存在
if isExists {
// 是否为文件夹
if isDir.boolValue {
// 迭代器 存放文件夹下的所有文件名
let enumerator = fileManager.enumerator(atPath: self)
for subPath in enumerator! {
// 获得全路径
let fullPath = self.appending("/\(subPath)")
do {
let attr = try fileManager.attributesOfItem(atPath: fullPath)
size += attr[FileAttributeKey.size] as! UInt64
} catch {
print("error :\(error)")
}
}
} else { // 单文件
do {
let attr = try fileManager.attributesOfItem(atPath: self)
size += attr[FileAttributeKey.size] as! UInt64
} catch {
print("error :\(error)")
}
}
}
return size
}
func hasEmoji()->Bool {
let pattern = "[^\\u0020-\\u007E\\u00A0-\\u00BE\\u2E80-\\uA4CF\\uF900-\\uFAFF\\uFE30-\\uFE4F\\uFF00-\\uFFEF\\u0080-\\u009F\\u2000-\\u201f\r\n]"
let pred = NSPredicate(format: "SELF MATCHES %@",pattern)
return pred.evaluate(with: self)
}
func containsEmoji()->Bool{
for scalar in unicodeScalars {
switch scalar.value {
case 0x00A0...0x00AF,
0x2030...0x204F,
0x2120...0x213F,
0x2190...0x21AF,
0x2310...0x329F,
0x1F000...0x1F9CF,
0x1F600...0x1F64F,
0x1F300...0x1F5FF,
0x1F680...0x1F6FF,
0x2600...0x26FF,
0x2700...0x27BF,
0xFE00...0xFE0F:
return true
default:
continue
}
}
return false
}
}
| 33.2 | 192 | 0.53012 |
088fdf182ea660df1879f072e3ab216b7dd21079 | 233 | //
// Menu.swift
// HotmartTest
//
// Created by Tiago Braga on 06/02/17.
// Copyright © 2017 Tiago Braga. All rights reserved.
//
import UIKit
struct Menu {
var icon: UIImage? = nil
var name: String? = nil
}
| 13.705882 | 54 | 0.60515 |
f9c20f69135b090e79b022f03019feb380cc7448 | 4,952 | //
// CVCalendarMenuView.swift
// CVCalendar
//
// Created by E. Mozharovsky on 12/26/14.
// Copyright (c) 2014 GameApp. All rights reserved.
//
import UIKit
public typealias WeekdaySymbolType = CVWeekdaySymbolType
public final class CVCalendarMenuView: UIView {
public var symbols = [String]()
public var symbolViews: [UILabel]?
public var firstWeekday: Weekday? = .sunday
public var dayOfWeekTextColor: UIColor? = .darkGray
public var dayofWeekBackgroundColor: UIColor? = .white
public var dayOfWeekTextUppercase: Bool? = true
public var dayOfWeekFont: UIFont? = UIFont(name: "Avenir", size: 10)
public var weekdaySymbolType: WeekdaySymbolType? = .short
public var calendar: Calendar? = Calendar.current
@IBOutlet public weak var menuViewDelegate: AnyObject? {
set {
if let delegate = newValue as? MenuViewDelegate {
self.delegate = delegate
}
}
get {
return delegate
}
}
public weak var delegate: MenuViewDelegate? {
didSet {
setupAppearance()
setupWeekdaySymbols()
createDaySymbols()
}
}
public init() {
super.init(frame: CGRect.zero)
}
public override init(frame: CGRect) {
super.init(frame: frame)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public func setupAppearance() {
if let delegate = delegate {
firstWeekday~>delegate.firstWeekday?()
dayOfWeekTextColor~>delegate.dayOfWeekTextColor?()
dayofWeekBackgroundColor~>delegate.dayOfWeekBackGroundColor?()
dayOfWeekTextUppercase~>delegate.dayOfWeekTextUppercase?()
dayOfWeekFont~>delegate.dayOfWeekFont?()
weekdaySymbolType~>delegate.weekdaySymbolType?()
}
}
public func setupWeekdaySymbols() {
if var calendar = self.calendar {
(calendar as NSCalendar).components([NSCalendar.Unit.month, NSCalendar.Unit.day], from: Date())
calendar.firstWeekday = firstWeekday!.rawValue
symbols = calendar.weekdaySymbols
}
}
public func createDaySymbols() {
// Change symbols with their places if needed.
let dateFormatter = DateFormatter()
dateFormatter.locale = calendar?.locale ?? Locale.current
var weekdays: NSArray
switch weekdaySymbolType! {
case .normal:
weekdays = dateFormatter.weekdaySymbols as NSArray
case .short:
weekdays = dateFormatter.shortWeekdaySymbols as NSArray
case .veryShort:
weekdays = dateFormatter.veryShortWeekdaySymbols as NSArray
}
let firstWeekdayIndex = firstWeekday!.rawValue - 1
if firstWeekdayIndex > 0 {
let copy = weekdays
weekdays = weekdays.subarray(
with: NSRange(location: firstWeekdayIndex, length: 7 - firstWeekdayIndex)) as NSArray
weekdays = weekdays.addingObjects(
from: copy.subarray(with: NSRange(location: 0, length: firstWeekdayIndex))) as NSArray
}
self.symbols = weekdays as! [String]
// Add symbols.
self.symbolViews = [UILabel]()
let space = 0 as CGFloat
let width = self.frame.width / 7 - space
let height = self.frame.height
var x: CGFloat = 0
let y: CGFloat = 0
for i in 0..<7 {
x = CGFloat(i) * width + space
let symbol = UILabel(frame: CGRect(x: x, y: y, width: width, height: height))
symbol.textAlignment = .center
symbol.text = self.symbols[i]
if dayOfWeekTextUppercase! {
symbol.text = (self.symbols[i]).uppercased()
}
let weekDay = Weekday(rawValue: (firstWeekday!.rawValue + i) % 7) ?? .saturday
symbol.font = dayOfWeekFont
symbol.textColor = self.delegate?.dayOfWeekTextColor?(by: weekDay)
?? dayOfWeekTextColor
symbol.backgroundColor = self.delegate?.dayOfWeekBackGroundColor?(by: weekDay)
?? dayofWeekBackgroundColor
self.symbolViews?.append(symbol)
self.addSubview(symbol)
}
}
public func commitMenuViewUpdate() {
setNeedsLayout()
layoutIfNeeded()
if let _ = delegate {
let space = 0 as CGFloat
let width = self.frame.width / 7 - space
let height = self.frame.height
var x: CGFloat = 0
let y: CGFloat = 0
for i in 0..<self.symbolViews!.count {
x = CGFloat(i) * width + space
let frame = CGRect(x: x, y: y, width: width, height: height)
let symbol = self.symbolViews![i]
symbol.frame = frame
}
}
}
}
| 32.155844 | 107 | 0.595719 |
e52b6a740ea4198ad43b2e1e27c188e1a9b108af | 2,637 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2016 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import Foundation
import PathKit
import Realm
import TGSpreadsheetWriter
@objc(RLMXLSXDataImporter)
open class XLSXDataImporter: DataImporter {
open override func `import`(toPath path: String, schema: ImportSchema) throws -> RLMRealm {
let realm = try! self.createNewRealmFile(atPath: path, schema: schema)
let workbook = TGSpreadsheetWriter.readWorkbook(URL(fileURLWithPath: "\(Path(files[0]).absolute())")) as! [String: [[String]]]
for (index, key) in workbook.keys.enumerated() {
let schema = schema.schemas[index]
if let sheet = workbook[key] {
let rows = sheet.dropFirst()
for row in rows {
let cls = NSClassFromString(schema.objectClassName) as! RLMObject.Type
let object = cls.init()
row.enumerated().forEach { (index, field) -> () in
let property = schema.properties[index]
switch property.type {
case .int:
if let number = Int64(field) {
object.setValue(NSNumber(value: number), forKey: property.originalName)
}
case .double:
if let number = Double(field) {
object.setValue(NSNumber(value: number), forKey: property.originalName)
}
default:
object.setValue(field, forKey: property.originalName)
}
}
try realm.transaction { () -> Void in
realm.add(object)
}
}
}
}
return realm
}
}
| 39.358209 | 134 | 0.505119 |
096bbbd3aa5635683dd1e8c8bf2a118656f3cfad | 1,356 | //
// AppDelegate.swift
// simpleAdditionExample
//
// Created by cedcoss on 19/04/21.
//
import UIKit
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
| 36.648649 | 179 | 0.747788 |
f74f575fa060c96e9670a19b79e55c789d5094e1 | 2,664 | //
// ProjectsViewModel.swift
// Peanut
//
// Created by Adam on 9/3/21.
//
import CoreData
import Foundation
extension ProjectsView {
class ViewModel: NSObject, ObservableObject, NSFetchedResultsControllerDelegate {
let persistenceController: PersistenceController
let showClosedProjects: Bool
private let projectsController: NSFetchedResultsController<Project>
@Published var sortOrder = Item.SortOrder.optimized
@Published var projects = [Project]()
@Published var showingUnlockView = false
init(persistenceController: PersistenceController, showClosedProjects: Bool) {
self.persistenceController = persistenceController
self.showClosedProjects = showClosedProjects
let request: NSFetchRequest<Project> = Project.fetchRequest()
request.sortDescriptors = [NSSortDescriptor(keyPath: \Project.creationDate, ascending: false)]
request.predicate = NSPredicate(format: "closed = %d", showClosedProjects)
projectsController = NSFetchedResultsController(
fetchRequest: request,
managedObjectContext: persistenceController.container.viewContext,
sectionNameKeyPath: nil,
cacheName: nil
)
super.init()
projectsController.delegate = self
do {
try projectsController.performFetch()
projects = projectsController.fetchedObjects ?? []
} catch {
print("Failed to fetch projects")
}
}
func addProject() {
if persistenceController.addProject() == false {
showingUnlockView.toggle()
}
}
func addItem(to project: Project) {
let item = Item(context: persistenceController.container.viewContext)
item.priority = 2
item.completed = false
item.project = project
item.creationDate = Date()
persistenceController.save()
}
func delete(_ offsets: IndexSet, from project: Project) {
let allItems = project.projectItems(using: sortOrder)
for offset in offsets {
let item = allItems[offset]
persistenceController.delete(item)
}
persistenceController.save()
}
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
if let newProjects = controller.fetchedObjects as? [Project] {
projects = newProjects
}
}
}
}
| 33.721519 | 106 | 0.615616 |
0a127f69f39fea9caa45bf8096114a2e70168210 | 1,401 | //
// StandardMode.swift
// Nudge
//
// Created by Erik Gomez on 2/2/21.
//
import Foundation
import SwiftUI
// Standard Mode
struct StandardMode: View {
// Nudge UI
var body: some View {
HStack {
// Life side of Nudge
StandardModeLeftSide()
// Vertical Line
VStack{
Rectangle()
.fill(Color.gray.opacity(0.5))
.frame(width: 1)
}
.frame(height: 525)
// Right side of Nudge
StandardModeRightSide()
}
.frame(width: 900, height: 450)
// https://www.hackingwithswift.com/books/ios-swiftui/running-code-when-our-app-launches
.onAppear(perform: nudgeStartLogic)
}
}
#if DEBUG
// Xcode preview for both light and dark mode
struct StandardModePreviews: PreviewProvider {
static var previews: some View {
Group {
ForEach(["en", "es", "fr"], id: \.self) { id in
StandardMode().environmentObject(PolicyManager(withVersion: try! OSVersion("11.2") ))
.preferredColorScheme(.light)
.environment(\.locale, .init(identifier: id))
}
StandardMode().environmentObject(PolicyManager(withVersion: try! OSVersion("11.2") ))
.preferredColorScheme(.dark)
}
}
}
#endif
| 26.942308 | 102 | 0.546039 |
b904f308352ec96b56bb38ca61188ff75472b213 | 2,026 | import SwiftUI
import PhotosUI
import Combine
/// `PHPickerViewController` wrapper for SwiftUI.
public struct PhotoPicker: UIViewControllerRepresentable
{
@Binding
public var datas: [PhotoPickerData?]
private let configuration: PHPickerConfiguration
private let pattern: PickerPattern
@Environment(\.presentationMode)
private var presentationMode
public init(
datas: Binding<[PhotoPickerData?]>,
configuration: PHPickerConfiguration,
pattern: PickerPattern
)
{
self._datas = datas
self.configuration = configuration
self.pattern = pattern
}
public func makeUIViewController(context: Context) -> PHPickerViewController
{
let vc = PHPickerViewController(configuration: configuration)
vc.delegate = context.coordinator
return vc
}
public func updateUIViewController(
_ uiViewController: PHPickerViewController,
context: Context
)
{
}
public func makeCoordinator() -> Coordinator
{
Coordinator(self)
}
// MARK: - Coordinator
public class Coordinator: PHPickerViewControllerDelegate
{
private let parent: PhotoPicker
private var cancellables: Set<AnyCancellable> = .init()
init(_ parent: PhotoPicker)
{
self.parent = parent
}
public func picker(
_ picker: PHPickerViewController,
didFinishPicking results: [PHPickerResult]
)
{
if results.isEmpty {
self.parent.presentationMode.wrappedValue.dismiss()
self.parent.datas = []
return
}
parent.pattern.makePublisher(results: results)
.sink(receiveValue: { (datas: [PhotoPickerData?]) in
self.parent.presentationMode.wrappedValue.dismiss()
self.parent.datas = datas
})
.store(in: &cancellables)
}
}
}
| 25.012346 | 80 | 0.612043 |
901e143cf58ae8cffd116728923ac64781c78164 | 2,515 | //
// ViewController.swift
// YYBottomSheet
//
// Created by DevYeom on 05/19/2019.
// Copyright (c) 2019 DevYeom. All rights reserved.
//
import UIKit
import YYBottomSheet
class ViewController: UIViewController {
@IBOutlet weak var selectedFruitLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func showBottomUpTable(_ sender: UIButton) {
let title = "Fruits"
let dataArray = ["apple", "grape", "watermelon", "banana", "strawberry", "cherry", "pineapple", "pear"]
/*
let options: [YYBottomSheet.BottomUpTableOptions: Any] = [
.allowTouchOutsideToDismiss: false,
.backgroundAlpha: 0.5,
.tableViewHeight: 200,
.tableRowHeight: 50,
.tableViewCellLabelTextColor: UIColor.blue,
.tableViewSeperatorStyle: UITableViewCell.SeparatorStyle.none,
.tableViewBackgroundColor: UIColor.white,
.headerViewBackgroundColor: UIColor.yellow,
.headerViewTitleLabelTextColor: UIColor.red
]
*/
let bottomUpTable = YYBottomSheet.init(bottomUpTableTitle: title, dataArray: dataArray, options: nil) { cell in
self.selectedFruitLabel.text = cell.titleLabel.text
}
bottomUpTable.show()
}
@IBAction func showSimpleToast(_ sender: UIButton) {
let id = sender.restorationIdentifier
if id == "oneLine" {
let message = "Hello World!"
let simpleToast = YYBottomSheet.init(simpleToastMessage: message, options: nil)
simpleToast.show()
} else if id == "multipleLines" {
let message = "Message is multiple lines\nit doesn't matter!"
let simpleToast = YYBottomSheet.init(simpleToastMessage: message, options: nil)
simpleToast.show()
} else if id == "customized" {
let options: [YYBottomSheet.SimpleToastOptions: Any] = [
.showDuration: 2,
.backgroundColor: UIColor.black,
.beginningAlpha: 0.8,
.messageFont: UIFont.italicSystemFont(ofSize: 15),
.messageColor: UIColor.white
]
let message = "SimpleToast can be customized!"
let simpleToast = YYBottomSheet.init(simpleToastMessage: message, options: options)
simpleToast.show()
}
}
}
| 32.24359 | 119 | 0.617495 |
11953a26aa10e99923458e751ced7aa58b980a6a | 1,502 | /*
See LICENSE folder for this sample’s licensing information.
Abstract:
A view controller that demonstrates how to use `UIImageView`.
*/
import UIKit
class ImageViewController: UIViewController {
// MARK: - View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
configureImageView()
}
// MARK: - Configuration
func configureImageView() {
// The root view of the view controller is set in Interface Builder and is an UIImageView.
if let imageView = view as? UIImageView {
// Fetch the images (each image is of the format Flowers_number).
imageView.animationImages = (1...2).map { UIImage(named: "Flowers_\($0)")! }
// We want the image to be scaled to the correct aspect ratio within imageView's bounds.
imageView.contentMode = .scaleAspectFit
imageView.animationDuration = 5
imageView.startAnimating()
imageView.isAccessibilityElement = true
imageView.accessibilityLabel = NSLocalizedString("Animated", comment: "")
if #available(iOS 15, *) {
// This case uses UIToolTipInteraction which is available on iOS 15 or later.
let interaction =
UIToolTipInteraction(defaultToolTip: NSLocalizedString("ImageToolTipTitle", comment: ""))
imageView.addInteraction(interaction)
}
}
}
}
| 33.377778 | 109 | 0.613848 |
f89ffcd9c4ba83101d1e7bca2abcbffab5c620ed | 2,404 | // Copyright 2018-2020 Tokamak contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Created by Max Desiatov on 16/10/2018.
//
public struct Color: Equatable {
public enum Space {
case sRGB
case displayP3
}
public let red: Double
public let green: Double
public let blue: Double
public let alpha: Double
public let space: Space
public init(red: Double,
green: Double,
blue: Double,
alpha: Double,
space: Space = .sRGB) {
self.red = red
self.green = green
self.blue = blue
self.alpha = alpha
self.space = space
}
public static var white = Color(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
public static var black = Color(red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0)
public static var red = Color(red: 1.0, green: 0.0, blue: 0.0, alpha: 1.0)
public static var green = Color(red: 0.0, green: 1.0, blue: 0.0, alpha: 1.0)
public static var blue = Color(red: 0.0, green: 0.0, blue: 1.0, alpha: 1.0)
}
extension Color: ExpressibleByIntegerLiteral {
/// Allows initializing value of `Color` type from hex values
public init(integerLiteral bitMask: UInt32) {
red = Double((bitMask & 0xFF0000) >> 16) / 255
green = Double((bitMask & 0x00FF00) >> 8) / 255
blue = Double(bitMask & 0x0000FF) / 255
alpha = 1
space = .sRGB
}
}
extension Color {
public init?(hex: String) {
let cArray = Array(hex.count > 6 ? String(hex.dropFirst()) : hex)
guard cArray.count == 6 else { return nil }
guard
let red = Int(String(cArray[0...1]), radix: 16),
let green = Int(String(cArray[2...3]), radix: 16),
let blue = Int(String(cArray[4...5]), radix: 16)
else {
return nil
}
self.red = Double(red) / 255
self.green = Double(green) / 255
self.blue = Double(blue) / 255
alpha = 1
space = .sRGB
}
}
| 30.05 | 78 | 0.640183 |
e5c041e1fca93b4e6fdef19cadc60821ee2817bc | 864 | //
// PostSessionResponse.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
/** Response from post (create) session */
open class PostSessionResponse: JSONEncodable {
/** Gets or sets user handle */
public var userHandle: String?
/** Gets or sets session token generated by our server. The client saves the session token and sends it with every request */
public var sessionToken: String?
public init() {}
// MARK: JSONEncodable
open func encodeToJSON() -> Any {
var nillableDictionary = [String:Any?]()
nillableDictionary["userHandle"] = self.userHandle
nillableDictionary["sessionToken"] = self.sessionToken
let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:]
return dictionary
}
}
| 27.870968 | 142 | 0.675926 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.