text
stringlengths
8
1.32M
// // AnimationPresenter.swift // PizzaDemo // // Created by Pietro Gandolfi on 02/01/2019. // Copyright © 2019 Pietro Gandolfi. All rights reserved. // import UIKit import NVActivityIndicatorView struct AnimationPresenter { var animationController: UIViewController! mutating func present(in viewController: UIViewController, animated: Bool, completion: (() -> Void)? = nil) { animationController = UIViewController() animationController.view.backgroundColor = .white let backgroundView = UIView(frame: viewController.view.frame) backgroundView.backgroundColor = UIColor.orange.withAlphaComponent(0.7) animationController.view.addSubview(backgroundView) let activityIndicatorView = NVActivityIndicatorView(frame: animationController.view.bounds, type: .ballClipRotateMultiple, color: .white, padding: 80.0) backgroundView.alpha = 0.0 activityIndicatorView.alpha = 0.0 backgroundView.addSubview(activityIndicatorView) animationController.modalPresentationStyle = .custom animationController.modalTransitionStyle = .crossDissolve activityIndicatorView.startAnimating() UIView.animate(withDuration: 1.0, animations: { backgroundView.alpha = 1.0 activityIndicatorView.alpha = 1.0 }) viewController.present(animationController, animated: animated, completion: completion) } }
// // BaseViewModel.swift // ET // // Created by HungNguyen on 10/30/19. // Copyright © 2019 HungNguyen. All rights reserved. // import Foundation import RxCocoa import RxSwift class BaseViewModel { let disposeBag = DisposeBag() let shouldReloadData = BehaviorRelay<Void?>(value: nil) let shouldReloadSections = BehaviorRelay<IndexSet?>(value: nil) let shouldReloadRows = BehaviorRelay<[IndexPath]?>(value: nil) lazy var activityIndicator = ActivityIndicator() // For checking loading status var requestProcessTracking: [PublishSubject<Void>] = [] // For tracking multithreads request let didRequestError = BehaviorRelay<Error?>(value: nil) let fromLanguageBehavior = BehaviorRelay<String>(value: "") let toLanguageBehavior = BehaviorRelay<String>(value: "") let swapLanguageBehavior = PublishRelay<Void>() // MARK: - Init BaseViewModel init() { TranslationManager.shared.loadListSupportedLanguage() firstSetupLanguage() } deinit { print("Deinit: \(type(of: self))") } /// Clear all data for refresh func clearAll() {} // Override /// Refresh data func refreshData() { clearAll() } func requestError(_ error: Error) { didRequestError.accept(error) } func reloadData() { shouldReloadData.accept(()) } func reloadSections(_ sections: IndexSet) { shouldReloadSections.accept(sections) } func reloadRows(_ rows: [IndexPath]) { shouldReloadRows.accept(rows) } } // ====================================================================== // MARK: - Request Tracking Flow // ====================================================================== extension BaseViewModel { func clearRequestTracking() { requestProcessTracking = [] } func requestTrackingCompletedAt(_ index: Int) { requestProcessTracking[safe: index]?.onCompleted() } func requestTrackingErrorAt(_ index: Int, error: Error) { requestProcessTracking[safe: index]?.onError(error) } } // MARK: - Support Method extension BaseViewModel { func firstSetupLanguage() { // Load current device's language let currentLanguage = TranslationManager.shared.supportedLanguage.filter({$0.language == TranslationManager.shared.getDefaultLanguage() }).first if getDefaultLanguage(of: .fromLanguage) == nil && getDefaultLanguage(of: .toLanguage) == nil { // If default language nil, save the current language TranslationManager.shared.saveLanguage(type: .fromLanguage(currentLanguage ?? LanguageModel("English", "en"))) TranslationManager.shared.saveLanguage(type: .toLanguage(currentLanguage ?? LanguageModel("English", "en"))) fromLanguageBehavior.accept(currentLanguage?.name ?? "") toLanguageBehavior.accept(currentLanguage?.name ?? "") } else { // Load the last default language let fromLanguage = TranslationManager.shared.loadLanguage(for: .fromLanguage) let toLanguage = TranslationManager.shared.loadLanguage(for: .toLanguage) fromLanguageBehavior.accept(fromLanguage?.name ?? "") toLanguageBehavior.accept(toLanguage?.name ?? "") } } func getDefaultLanguage(of type: UserDefaultKey) -> LanguageModel? { guard let model = TranslationManager.shared.loadLanguage(for: type) else { return nil } return model } func detectText(from image: UIImage) { } }
// // BaseCollectionReusableView.swift // ComicSwift // // Created by 曹来东 on 2020/7/6. // Copyright © 2020 曹来东. All rights reserved. // import UIKit class BaseCollectionReusableView: UICollectionReusableView,Reusable{ override init(frame: CGRect) { super.init(frame: frame) configUI() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } func configUI() { } }
// // Day15LinkedList.swift // Datasnok // // Created by Vladimir Urbano on 7/12/16. // Copyright © 2016 Vladimir Urbano. All rights reserved. // /* Objective Today we're working with Linked Lists. Check out the Tutorial tab for learning materials and an instructional video! A Node class is provided for you in the editor. A Node object has an integer data field, , and a Node instance pointer, , pointing to another node (i.e.: the next node in a list). A Node insert function is also declared in your editor. It has two parameters: a pointer, , pointing to the first node of a linked list, and an integer value that must be added to the end of the list as a new Node object. Task Complete the insert function in your editor so that it creates a new Node (pass as the Node constructor argument) and inserts it at the tail of the linked list referenced by the parameter. Once the new node is added, return the reference to the node. Note: If the argument passed to the insert function is null, then the initial list is empty. Input Format The insert function has parameters: a pointer to a Node named , and an integer value, . The constructor for Node has parameter: an integer value for the field. You do not need to read anything from stdin. Output Format Your insert function should return a reference to the node of the linked list. Sample Input The following input is handled for you by the locked code in the editor: The first line contains T, the number of test cases. The subsequent lines of test cases each contain an integer to be inserted at the list's tail. 4 2 3 4 1 Sample Output The locked code in your editor prints the ordered data values for each element in your list as a single line of space-separated integers: 2 3 4 1 Explanation , so the locked code in the editor will be inserting nodes. The list is initially empty, so is null; accounting for this, our code returns a new node containing the data value as the of our list. We then create and insert nodes , , and at the tail of our list. The resulting list returned by the last call to is , so the printed output is 2 3 4 1. LinkedListExplanation.png */ class Day15LinkedList { init() { var head: Node15! = nil var n: Int = Int(readLine(stripNewline: true)!)! while n > 0 { let element = Int(readLine()!) head = insert(head, data: element) n = n - 1 } display(head) } func insert(head: Node15!, data: Int!) -> Node15 { if head == nil { let n = Node15(data: data) return n } var last = head while let next = last.next { last = next } let n = Node15(data: data) last.next = n return head } func display(head: Node15!) { var current: Node15! = head while current != nil { print(current.data, terminator: " ") current = current.next } } } class Node15 { var data: Int var next: Node15? init(data: Int) { self.data = data self.next = nil } }
// // WeiHuListCell.swift // Project // // Created by 张凯强 on 2019/8/24. // Copyright © 2019年 HHCSZGD. All rights reserved. // import UIKit class WeiHuListCell: UITableViewCell { override func awakeFromNib() { super.awakeFromNib() self.evealuteLabel.layer.masksToBounds = true self.evealuteLabel.layer.cornerRadius = 10 self.evealuteLabel.layer.borderWidth = 1 self.selectionStyle = .none // Initialization code } @IBOutlet weak var timeAndContent: UILabel! @IBOutlet weak var evealuteLabel: UILabel! @IBOutlet weak var nameLabel: UILabel! override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } var model: WeiHuListModel? { didSet{ self.nameLabel.text = model?.member_name self.timeAndContent.text = (model?.rq ?? "") + " " + (model?.content ?? "") switch model?.evaluate { case "0": self.evealuteLabel.layer.borderColor = UIColor.colorWithHexStringSwift("cccccc").cgColor self.evealuteLabel.textColor = UIColor.colorWithHexStringSwift("cccccc") self.evealuteLabel.text = "未评价" case "3": self.evealuteLabel.layer.borderColor = UIColor.colorWithHexStringSwift("cccccc").cgColor self.evealuteLabel.textColor = UIColor.colorWithHexStringSwift("cccccc") self.evealuteLabel.text = "差评" case "1": self.evealuteLabel.layer.borderColor = UIColor.colorWithHexStringSwift("ff7d09").cgColor self.evealuteLabel.textColor = UIColor.colorWithHexStringSwift("ff7d09") self.evealuteLabel.text = "好评" case "2": self.evealuteLabel.layer.borderColor = UIColor.colorWithHexStringSwift("ffbd83").cgColor self.evealuteLabel.textColor = UIColor.colorWithHexStringSwift("ffbd83") self.evealuteLabel.text = "中评" default: break } } } }
// // HistoryCell.swift // Translator // // Created by admin on 23.11.2020. // import UIKit class HistoryViewCell: UICollectionViewCell { @IBOutlet weak var firstText: UITextView! @IBOutlet weak var secondText: UITextView! @IBOutlet weak var hSpeakerBTN: UIButton! func setLabels(item : Text) { firstText.text = item.inputText secondText.text = item.translatedText } }
// // SWBOrientationButton.swift // SweepBright // // Created by Kaio Henrique on 1/20/16. // Copyright © 2016 madewithlove. All rights reserved. // import UIKit class SWBOrientationButton: UIButton { var roomOrientation: SWBOrientationProtocol! var orientationHasChanged:((newOrientation: SWBOrientation)->())? = nil var orientation: SWBOrientation = .N { didSet { self.setTitle("Set \(orientation.fullName())", forState: .Normal) self.orientationHasChanged!(newOrientation: self.orientation) } } }
import Foundation protocol LoginPresenterViewable { var loginPresenter: LoginPresentable? { get set} func showEmailValidationFailure(withError error: AuthenticationError) func showPasswordValidationFailure(withError error: AuthenticationError) func showInvalidInputsFailure(withError error: AuthenticationError) func showAuthenticationFailure(withMessage message: String?) func startLoadingAnimation() func stopLoadingAnimation() func showSuccess() }
// // DayTwo2021.swift // AdventOfCode // // Created by Shawn Veader on 12/1/21. // import Foundation struct DayTwo2021: AdventDay { var year = 2021 var dayNumber = 2 var dayTitle = "Dive!" var stars = 2 func parse(_ input: String?) -> [Submarine.Command] { (input ?? "") .split(separator: "\n") .map(String.init) .compactMap { Submarine.Command.parse($0) } } func partOne(input: String?) -> Any { let commands = parse(input) let sub = Submarine(commands: commands, mode: .simple) sub.dive() return sub.output } func partTwo(input: String?) -> Any { let commands = parse(input) let sub = Submarine(commands: commands, mode: .useAim) sub.dive() return sub.output } class Submarine { enum Command{ /// Move sub forward X units case forward(distance: Int) /// Move sub down X units in depth case down(depth: Int) /// Move sub up X units in depth case up(depth: Int) /// Parse the given input string into a Command static func parse(_ input: String) -> Command? { // https://rubular.com/r/w78gSaYgWS3JsP let commandRegEx = "(\\w+)\\s(\\d+)" guard let match = input.matching(regex: commandRegEx), let cmd = match.captures.first, let int = Int(match.captures.last ?? "") else { return nil } switch cmd { case "forward": return .forward(distance: int) case "down": return .down(depth: int) case "up": return .up(depth: int) default: print("Unknown command: \(input)") return nil } } } enum Mode { case simple case useAim } var commands: [Command] var mode: Mode var depth: Int = 0 var distance: Int = 0 var aim: Int = 0 var output: Int { depth * distance } init(commands: [Command], mode: Mode = .useAim) { self.commands = commands self.mode = mode } /// Run the current set of commands func dive() { commands.forEach { cmd in switch cmd { case .forward(distance: let d): distance += d if case .useAim = mode { depth += (aim * d) } case .down(depth: let d): if case .simple = mode { depth += d } else { aim += d } case .up(depth: let d): if case .simple = mode { depth -= d } else { aim -= d } } } } } }
// // AddingProtocol.swift // MovieList // // Created by JETS Mobile Lab-10 on 5/5/19. // Copyright © 2019 iti. All rights reserved. // import Foundation protocol AddingProtocol { func addMovie(movie : Movie) }
// // AlertView.swift // SDS-iOS-APP // // Created by 石川諒 on 2018/01/31. // Copyright © 2018年 石川諒. All rights reserved. // import Foundation import UIKit struct SDSAlertView { func failureAlert(title: String, message: String, handler: ((UIAlertAction) -> ())?) -> UIAlertController { let aletController = UIAlertController( title: title, message: message, preferredStyle: UIAlertControllerStyle.alert) let action = UIAlertAction( title: "OK", style: UIAlertActionStyle.default) { action in guard let closure = handler else { return } closure(action) } aletController.addAction(action) return aletController } func deleteAlert(title: String, message: String, handler: @escaping (UIAlertAction) -> ()) -> UIAlertController { let alertController = UIAlertController ( title: title, message: message, preferredStyle: UIAlertControllerStyle.actionSheet ) let deleteAction = UIAlertAction( title: "OK", style: UIAlertActionStyle.destructive) { action in handler(action) } let cancelAction = UIAlertAction( title: "Cancel", style: .cancel, handler: nil ) alertController.addAction(deleteAction) alertController.addAction(cancelAction) return alertController } func oneTextFieldAlert(title: String, message: String, handler: @escaping (UIAlertAction,String?) -> ()) -> UIAlertController { let alertController = UIAlertController( title: title, message: message, preferredStyle: UIAlertControllerStyle.alert ) alertController.addTextField { textField in textField.placeholder = "userData(optional)" } let action = UIAlertAction(title: "OK", style: .default) { action in guard let paramsTextField = alertController.textFields else { return } let params = paramsTextField.map({ textField -> String? in textField.text }) guard let text = params[0] else { return } handler(action, text) } let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil) alertController.addAction(action) alertController.addAction(cancelAction) return alertController } func addAlert(title: String, message: String, handler: @escaping (UIAlertAction,String,String?) -> ()) -> UIAlertController { let alertController = UIAlertController( title: title, message: message, preferredStyle: UIAlertControllerStyle.alert ) alertController.addTextField { textField in textField.placeholder = "ユーザー名" } alertController.addTextField { textField in textField.placeholder = "userData(optional)" } let action = UIAlertAction(title: "OK", style: .default) { action in guard let paramsTextField = alertController.textFields else { return } let params = paramsTextField.map({ textField -> String? in textField.text }) guard let name = params[0] else { return } let userData = params[1] handler(action, name, userData) } let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil) alertController.addAction(action) alertController.addAction(cancelAction) return alertController } }
// // ListBuilder.swift // AppExtension // // Created by Apple on 2019/9/16. // Copyright © 2019 ZJaDe. All rights reserved. // import Foundation // TODO: reloadData一个分区时报错 @_functionBuilder public struct ListBuilder<Section, Item> { public typealias _Component<I> = (Section, [I]) public typealias Component = _Component<Item> public typealias Components = ListData<Section, Item> public static func buildBlock(_ content: Component...) -> Components { return Components(content.map(SectionData.init)) } public static func buildBlock(_ content: Components...) -> Components { return Components(content.flatMap({$0})) } } extension ListBuilder { public static func buildIf(_ content: Component?) -> Components { content.map(Components.init) ?? [] } public static func buildIf(_ content: Components?) -> Components { content ?? [] } public static func buildEither(first: Component) -> Components { [first] } public static func buildEither(second: Component) -> Components { [second] } public static func buildEither(first: Components) -> Components { first } public static func buildEither(second: Components) -> Components { second } } // MARK: - public extension ListDataUpdateProtocol { typealias ListItemBuilder = ListBuilder<Section, Item> func reloadData(@ListItemBuilder content: () -> _ListData) { self.reloadData(content()) } }
// // CharecterDetailHeaderView.swift // Marvel // // Created by MACBOOK on 21/05/2021. // import UIKit final class CharecterDetailHeaderView: UIView { // MARK: - Outlets @IBOutlet private var characterImageView: UIImageView! @IBOutlet private var nameTitleLabel: UILabel! @IBOutlet private var nameValueLabel: UILabel! @IBOutlet private var descriptionTitleLabel: UILabel! @IBOutlet private var descriptionValueLabel: UILabel! // MARK: - LifeCycle override init(frame: CGRect) { super.init(frame: frame) loadFromNib() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) loadFromNib() } } // MARK: - Configurations extension CharecterDetailHeaderView { func configure(with item: CharacterViewItem) { characterImageView.download(image: item.imageURL) nameTitleLabel.text = item.nameTitle nameValueLabel.text = item.name descriptionTitleLabel.text = item.descriptionTitle descriptionValueLabel.text = item.description } }
var x = 2 print(x * 1) print(x * 2) print(x * 3) print(x * 4) print(x * 5) print(x * 6) print(x * 7) print(x * 8) print(x * 9) x = 3 print(x * 1) print(x * 2) print(x * 3) print(x * 4) print(x * 5) print(x * 6) print(x * 7) print(x * 8) print(x * 9) //for文(繰り返し) x = 4 for n in 1...9 { print(x * n) } x = 5 for n in 1...9 { print(x * n) } for m in 1...9 { print("\(m)の段") for n in 1...9 { print("\(m) x \(n) = \(m * n)") } }
// // ProjectDetailViewModel.swift // GardenCoceral // // Created by shiliuhua on 2018/5/23. // Copyright © 2018年 tongna. All rights reserved. // import Foundation struct projectDetailViewModel { var projectDetailBassClass:ProjectDetailProjectDetailBaseClass! var headImageStr:String { return projectDetailBassClass.logo ?? "" } var titleName:String { return projectDetailBassClass.name ?? "" } var numOfPeople:Int { return projectDetailBassClass.num ?? 0 } var contentNote:String { return projectDetailBassClass.note ?? "" } var dateStr:String { return projectDetailBassClass.date ?? "" } } extension projectDetailViewModel:ProjectDetailRespertable {} extension projectDetailViewModel:ProjectImageRespertable {}
// // UIImageView+SWFBuilder.swift // TestSwift // // Created by wsy on 2018/1/10. // Copyright © 2018年 wangshengyuan. All rights reserved. // import Foundation import UIKit func ImageView() -> UIImageView { return UIImageView() } func ImageView(_ rect: CGRect) -> UIImageView { return UIImageView(frame: rect) } func ImageView(_ imageName: String) -> UIImageView { return UIImageView.init(image: UIImage(named: imageName)) } func ImageView(_ image: UIImage) -> UIImageView { return UIImageView.init(image: image) } extension UIImageView { func imgViewWithImage(image: UIImage) -> UIImageView { self.image = image return self } func imgViewWithMode(mode: UIViewContentMode) -> UIImageView { self.contentMode = mode return self } func imgViewWithImages(_ images: [UIImage], _ duration: TimeInterval) -> UIImageView { self.animationImages = images self.animationDuration = duration self.animationRepeatCount = 0 self.startAnimating() return self; } func imgViewWithImages(_ images: [UIImage], _ duration: TimeInterval, _ repeatCount: Int) -> UIImageView { self.animationImages = images self.animationDuration = duration self.animationRepeatCount = repeatCount self.startAnimating() return self; } }
// // WGProfileViewController.swift // LOLX // // Created by V on 2017/8/14. // Copyright © 2017年 com.fengxian. All rights reserved. // import UIKit let kScreenWidth = UIScreen.main.bounds.size.width let kScreenHeight = UIScreen.main.bounds.size.height let kHeaderViewHeight = CGFloat(175) let kStatusBarHeight = CGFloat(20) let kNavigationBarHeight = CGFloat(44) class WGProfileViewController: WGViewController, UITableViewDelegate, UITableViewDataSource { var headerContentView: UIView! var imageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() title = "我的" view.backgroundColor = UIColor.white setupUI() } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } fileprivate func setupUI() { navigationController?.setNavigationBarHidden(true, animated: true) tableView.tableHeaderView = tableViewHeaderView; view.addSubview(tableView) view.addSubview(customNavigationBarView) } fileprivate lazy var customNavigationBarView: WGHomeNavigationBar = { let navigationBar = WGHomeNavigationBar.homeNavigationBar() navigationBar.frame = CGRect(x: 0, y: 0, width: kScreenWidth, height: 64) return navigationBar }() fileprivate lazy var tableView: UITableView = { let tableView = UITableView(frame: CGRect(x: 0, y: -kStatusBarHeight, width: kScreenWidth, height: kScreenHeight + kNavigationBarHeight + kStatusBarHeight), style: .plain) tableView.delegate = self tableView.dataSource = self tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell") return tableView }() fileprivate lazy var tableViewHeaderView: UIView = { let headerViewFrame = CGRect(x: 0, y: 0, width: kScreenWidth, height: kHeaderViewHeight) let headerView = UIView.init(frame: headerViewFrame) self.headerContentView = UIView.init(frame: headerViewFrame) headerView.addSubview(self.headerContentView) self.imageView = UIImageView(image: UIImage(named: "personal_info_back_ground")) self.imageView.center = headerView.center self.imageView.frame = headerViewFrame self.headerContentView.addSubview(self.imageView) return headerView; }() } extension WGProfileViewController { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 10 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) cell.textLabel?.text = "LOL vim" return cell } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let sectionHeaderView = WGProfileSectionHeaderView.sectionHeaderView() return sectionHeaderView } } extension WGProfileViewController { func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 40 } } extension WGProfileViewController { func scrollViewDidScroll(_ scrollView: UIScrollView) { let offsetY = scrollView.contentOffset.y if offsetY < -kStatusBarHeight { let addTopHeight = -offsetY - kStatusBarHeight; let scale = (kHeaderViewHeight + addTopHeight) / kHeaderViewHeight let currentImageViewWidth = kScreenWidth * scale let currentImageViewX = -kScreenWidth * (scale - 1) / 2.0 self.headerContentView.frame = CGRect(x: 0, y: offsetY + kStatusBarHeight, width: kScreenWidth, height: kHeaderViewHeight + addTopHeight) self.imageView.frame = CGRect(x: currentImageViewX, y: 0, width: currentImageViewWidth, height: kHeaderViewHeight + addTopHeight) } } }
// // PokemonTypeVC.swift // pokedex // // Created by Mac on 9/18/17. // Copyright © 2017 Mac. All rights reserved. // import Foundation import UIKit class PokemonTypeVC:UITableViewController { let loadingSpinner = UIActivityIndicatorView() let sections = ["Double Damage To", "Half Damage To", "No Damage To","Double Damage From", "Half Damage From", "No Damage From", "Pokemon"] var sectionsData:[[String]]? var selectedTypeId:Int? var type:PokemonType? @IBOutlet weak var HomeButton: UIBarButtonItem! func assignBackground(background:UIImage) { DispatchQueue.main.async { self.tableView.backgroundView = UIImageView(image: background) self.tableView.backgroundView?.addSubview(self.loadingSpinner) } } override func viewDidLoad() { super.viewDidLoad() loadingSpinner.activityIndicatorViewStyle = .gray loadingSpinner.hidesWhenStopped = true loadingSpinner.startAnimating() loadingSpinner.frame = self.view.bounds loadingSpinner.transform = CGAffineTransform.init(scaleX: 2.0, y: 2.0) loadingSpinner.center = self.view.center loadingSpinner.color = .white Networking.getPokemonImage(callType: .Background1, forId: nil) { (image, err) in guard err == nil else {return print(err!)} guard let image = image else {return} self.assignBackground(background: image) } guard let typeId = selectedTypeId else {return print("didnt get id")} let type = PokemonType(id: typeId) type.fetchDataForView { self.type = type self.sectionsData = [type.doubleDamageTo, type.halfDamageTo, type.noDamageTo, type.doubleDamageFrom, type.halfDamageFrom, type.noDamageFrom, type.pokemon.map{$0.1}] DispatchQueue.main.async{ self.loadingSpinner.stopAnimating() self.tableView.reloadData() } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func numberOfSections(in tableView: UITableView) -> Int { print(self.sections.count) return self.sections.count } func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return self.sections[section] } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return sectionsData?[section].count ?? 0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = self.tableView.dequeueReusableCell(withIdentifier: "typeCell") else { fatalError("No cell created, bad Identifier") } guard let sectionData = sectionsData else {fatalError("u dun goofed")} let dataSet = sectionData[indexPath.section] let text = dataSet[indexPath.row] cell.textLabel?.text = text cell.textLabel?.textColor = .white return cell } @IBAction func pokedexNavButtonTouched() { self.navigationController?.popToRootViewController(animated: true) } }
// // ErrorNetPopupViewController.swift // MyRefah // // Created by tisa refah on 7/31/18. // Copyright © 2018 tisa refah. All rights reserved. // import UIKit class ErrorNetPopupViewController: UIViewController { @IBOutlet weak var popupView: GradientView! override func viewDidLoad() { super.viewDidLoad() self.popupView.frame.origin.y = self.view.frame.height setGradient(view : popupView) // Do any additional setup after loading the view. } override func viewDidAppear(_ animated: Bool) { runPopup() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func retry(_ sender: Any) { if(self.haveInternet()){ self.dissmissView() }else{ self.view.makeToast("اشکال در برقراری به اینترنت رفع نشده است") } } @IBAction func goSettings(_ sender: Any) { let alertController = UIAlertController (title: "تنظیمات", message: "برای بررسی اینترنت به تنظیمات می روید؟", preferredStyle: .alert) let settingsAction = UIAlertAction(title: "تنظیمات", style: .default) { (_) -> Void in guard let settingsUrl = URL(string: UIApplicationOpenSettingsURLString) else { return } if UIApplication.shared.canOpenURL(settingsUrl) { UIApplication.shared.open(settingsUrl, completionHandler: { (success) in print("Settings opened: \(success)") // Prints true }) } } alertController.addAction(settingsAction) let cancelAction = UIAlertAction(title: "بستن", style: .default, handler: nil) alertController.addAction(cancelAction) present(alertController, animated: true, completion: nil) } func dissmissView(){ UIView.animate(withDuration: 0.5, delay: 0 , options: .curveEaseInOut, animations: { self.popupView.frame.origin.y = self.view.frame.height }){ completion in if(self.parent is IntroLoadingViewController){ (self.parent as! IntroLoadingViewController).update2() } self.view.removeFromSuperview() self.removeFromParentViewController() } } func runPopup(){ UIView.animate(withDuration: 0.5, delay: 0.0 , options: .curveEaseInOut, animations: { self.popupView.frame.origin.y = 0 },completion : nil) } }
// // TableCell.swift // Ercan_IOS_496932 // // Created by Ercan kalan on 21/10/2019. // Copyright © 2019 Inholland. All rights reserved. // import Foundation import UIKit class MedicineCell: UITableViewCell{ @IBOutlet weak var amount: UILabel! @IBOutlet weak var medicine_intake_image: UIImageView! @IBOutlet weak var textMedicine: UILabel! override func awakeFromNib() { super.awakeFromNib() } override func prepareForReuse() { textMedicine.text = "Medicine naam" medicine_intake_image.image = UIImage(named: "placeholder") } }
// // HomePageViewController.swift // OrgTech // // Created by Maksym Balukhtin on 22.04.2020. // Copyright © 2020 Maksym Balukhtin. All rights reserved. // import Foundation import UIKit enum HomePageViewEvent { case onPageControlEvent(PageControllerManagerEvent) case onSegmentEvent(Int) } protocol HomePagePresenterToView: AnyObject { func setupInitialState() func populateData(_ items: [MainModelProtocol]) func adjustControls(with index: Int, segment: Bool) } final class HomePageViewController: BuildableViewController<HomePageView>, TabRepresentile { var presenter: HomePageViewToPresenter? var relatedTabBarItem: UITabBarItem? = AppDefaults.TabIndicator.home lazy var pageController: UIPageViewController = { return UIPageViewController(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil) }() var pageControllerManager: PageControllerManager? override func viewDidLoad() { super.viewDidLoad() presenter?.onViewLoaded() } } extension HomePageViewController: HomePagePresenterToView { func populateData(_ items: [MainModelProtocol]) { pageControllerManager?.populateControllers(relatedTo: items) setupActions() } func adjustControls(with index: Int, segment: Bool) { if segment { mainView.segmentControl.selectedSegmentIndex = index } else { pageControllerManager?.selectPage(at: index) } } func setupInitialState() { pageControllerManager = PageControllerManager(pageController) pageController.view.frame = mainView.contentView.frame addChild(pageController) mainView.contentView.addSubview(pageController.view) pageController.didMove(toParent: self) let headerView = UIImageView(image: AppDefaults.Images.logo) navigationItem.titleView = headerView } } private extension HomePageViewController { func setupActions() { pageControllerManager?.eventHandler = { [unowned self] event in self.presenter?.onViewEvent(.onPageControlEvent(event)) } mainView.segmentControl.addAction(for: .valueChanged) { [unowned self] in self.presenter?.onViewEvent(.onSegmentEvent(self.mainView.segmentControl.selectedSegmentIndex)) } } }
// // ViewController.swift // PlayWithContainerView // // Created by Do Hoang Viet on 2/22/19. // Copyright © 2019 Do Hoang Viet. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var view1Button: UIButton! @IBOutlet weak var view2Button: UIButton! @IBOutlet weak var containerView: UIView! let viewController1 = ViewController1.newInstance() let viewController2 = ViewController2.newInstance() override func viewDidLoad() { super.viewDidLoad() setupDefault() } private func setupDefault() { resizeFrameOfView(with: viewController1.view) containerView.addSubview(viewController1.view) } private func resizeFrameOfView(with view: UIView) { view.frame = containerView.bounds } @IBAction func switchButtonPressed(_ sender: UIButton) { switch sender { case view1Button: resizeFrameOfView(with: viewController1.view) containerView.addSubview(viewController1.view) case view2Button: resizeFrameOfView(with: viewController2.view) containerView.addSubview(viewController2.view) default: break } } } class Supports: NSObject { /// Instantiate view controller with storyboard and identifier /// /// - Parameters: /// - storyboardName: Name of storyboard /// - identifier: Name of identifier /// - Returns: A UIViewController class func instantiateViewController(_ storyboardName: String, with identifier: String = "") -> UIViewController { return UIStoryboard(name: storyboardName, bundle: nil).instantiateViewController(withIdentifier: identifier.isEmpty ? storyboardName : identifier) } }
// // PRKVerticalGestureRecognizer.swift // prkng-ios // // Created by Antonino Urbano on 2015-07-06. // Copyright (c) 2015 PRKNG. All rights reserved. // import UIKit /* NOTE: In order for this to work, a reference to it has to be kept. Otherwise, the gesture recogizer's target, which is the instance of this class, will have nothing to call and an error about the "handleVerticalGestureRecongizerSwipe:" selector will be produced. */ class PRKVerticalGestureRecognizer: NSObject { private var panRec: UIPanGestureRecognizer private var appliedToView: UIView private var superView: UIView private var beginTap: CGPoint? private var lastPanTap: CGPoint? private var panDirectionIsUp: Bool private var _delegate: PRKVerticalGestureRecognizerDelegate? var delegate: PRKVerticalGestureRecognizerDelegate? { get { return _delegate } set(newDelegate) { _delegate = newDelegate panRec.delegate = _delegate } } override init() { panDirectionIsUp = false panRec = UIPanGestureRecognizer() appliedToView = UIView() superView = UIView() super.init() } convenience init(view: UIView, superViewOfView: UIView) { self.init() appliedToView = view superView = superViewOfView panRec = UIPanGestureRecognizer(target: self, action: "handleVerticalGestureRecongizerSwipe:") appliedToView.addGestureRecognizer(panRec) } func handleVerticalGestureRecongizerSwipe(panRec: UIPanGestureRecognizer) { let tap = panRec.locationInView(self.superView) if panRec.state == UIGestureRecognizerState.Began { if self.delegate != nil && !self.delegate!.shouldIgnoreSwipe(tap) { beginTap = tap self.delegate?.swipeDidBegin() } else { beginTap = nil } } else if panRec.state == UIGestureRecognizerState.Changed { if beginTap != nil { let distance = tap.yDistanceToPointWithDirection(beginTap!) self.delegate?.swipeInProgress(distance) if lastPanTap != nil { let distanceSinceLastTap = tap.yDistanceToPointWithDirection(lastPanTap!) if distance != 0 { lastPanTap = tap } panDirectionIsUp = distanceSinceLastTap > 0 } else { lastPanTap = tap panDirectionIsUp = distance > 0 } } } else if panRec.state == UIGestureRecognizerState.Ended { if beginTap != nil { if panDirectionIsUp { self.delegate?.swipeDidEndUp() } else { self.delegate?.swipeDidEndDown() } } } else { beginTap = nil } } } protocol PRKVerticalGestureRecognizerDelegate: UIGestureRecognizerDelegate { func shouldIgnoreSwipe(beginTap: CGPoint) -> Bool func swipeDidBegin() func swipeInProgress(yDistanceFromBeginTap: CGFloat) func swipeDidEndUp() func swipeDidEndDown() }
// // Constants.swift // smack // // Created by Aziz Ur Rehman on 7/31/17. // Copyright © 2017 JAZIZ. All rights reserved. // import Foundation typealias CompletionHandler = (_ Success: Bool) -> () let BASE_URL = "https://slacky-slack-app.herokuapp.com/v1" let URL_REGISTER = "\(BASE_URL)/account/register" let URL_LOGIN = "\(BASE_URL)/account/login" let ADD_USER = "\(BASE_URL)/user/add" let URL_USER_BY_EMAIL = "\(BASE_URL)/user/byEmail/" let URL_GET_CHANNELS = "\(BASE_URL)/channel" let BEARER_HEADER = [ "Authorization": "Bearer \(AuthService.instance.authToken)", "Content-Type":"application/json; charset=utf-8" ] // Colors let smackPurplePlaceholder = #colorLiteral(red: 0.3254901961, green: 0.4196078431, blue: 0.7764705882, alpha: 0.5) // Notifications constants let NOTIF_USER_DATA_DID_CHANGE = Notification.Name("notifUserDataChanged") //Segues let TO_LOGIN = "toLogin" let TO_CREATE_ACCOUNT = "toCreateAccount" let UNWIND = "unwindToChannel" let TO_AVATAR_PICKER = "toAvatarPicker" //User Defautls let TOKEN_KEY = "token" let LOGGED_IN_KEY = "loggedIn" let USER_EMAIL = "userEmail"
// // ___FILENAME___ // ___PROJECTNAME___ // // Created by ___FULLUSERNAME___ on ___DATE___. // Copyright © ___YEAR___ ___ORGANIZATIONNAME___. All rights reserved. // import UIKit class ___FILEBASENAME___ViewController: UIViewController { // MARK: - View var contentView: ___FILEBASENAME___View { guard let contentView = self.view as? ___FILEBASENAME___View else { fatalError("Cannot create content view") } return contentView } // MARK: - View lifecycle override func loadView() { self.view = ___FILEBASENAME___View() // Relationships between view controller and view } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ // MARK: - Memory manager override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
// // AppContents.swift // SocialBannersApp // // Created by Ruslan Timchenko on 18.06.2017. // Copyright © 2017 Ruslan Timchenko. All rights reserved. // import Cocoa class AppContents: NSObject { static func getFontsModel() -> [FontModel] { return [ FontModel(type: .avenirNextDemiBold), FontModel(type: .avenitNextBold), FontModel(type: .avenirNextMedium), FontModel(type: .avenirNexRegular), FontModel(type: .avenirNextCondensedMedium), FontModel(type: .avenirNextCondensedBold), FontModel(type: .timesNewRoman), FontModel(type: .georgia), FontModel(type: .georgiaBold), FontModel(type: .gillSans), FontModel(type: .gillSansBold) ] } static func getContentColor() -> [ColorModel] { return [ ColorModel(name: "Sky", fillColor: NSColor.hexColor(rgbValue: 0x14ABFB)), ColorModel(name: "White", fillColor: .white), ColorModel(name: "Gray", fillColor: NSColor.hexColor(rgbValue: 0x5F6F7D)), ColorModel(name: "Night", fillColor: NSColor.hexColor(rgbValue: 0x415C8E)), ColorModel(name: "Black", fillColor: .black), ColorModel(name: "Orange", fillColor: NSColor.hexColor(rgbValue: 0xF6A623)), ColorModel(name: "Red", fillColor: NSColor.hexColor(rgbValue: 0xD0011B)), ColorModel(name: "Green", fillColor: NSColor.hexColor(rgbValue: 0x7ED321)), ColorModel(name: "Pink", fillColor: NSColor.hexColor(rgbValue: 0xBD0FE1)), ColorModel(name: "Purple", fillColor: NSColor.hexColor(rgbValue: 0x9012FE)), ColorModel(name: "Cian", fillColor: NSColor.hexColor(rgbValue: 0x02CBE4)), ColorModel(name: "Light Blue", fillColor: NSColor.hexColor(rgbValue: 0xA8C4F0)) ] } static func getBackgroundColors() -> [ColorModel] { return [ ColorModel(name: "White", fillColor: .white), ColorModel(name: "Gray", fillColor: NSColor.hexColor(rgbValue: 0x5F6F7D)), ColorModel(name: "Sky", fillColor: NSColor.hexColor(rgbValue: 0x14ABFB)), ColorModel(name: "Water", fillColor: NSColor.hexColor(rgbValue: 0x9CE2FF)), ColorModel(name: "Night", fillColor: NSColor.hexColor(rgbValue: 0x415C8E)), ColorModel(name: "Black", fillColor: .black), ColorModel(name: "Sea Water", firstGradientColor: NSColor.hexColor(rgbValue: 0x1AD6FD), secondGradientColor: NSColor.hexColor(rgbValue: 0x1D62F0)), ColorModel(name: "Salt", firstGradientColor: NSColor.hexColor(rgbValue: 0x7AFFE0), secondGradientColor: NSColor.hexColor(rgbValue: 0x2991F3)), ColorModel(name: "Pastel", firstGradientColor: NSColor.hexColor(rgbValue: 0x01DBFC), secondGradientColor: NSColor.hexColor(rgbValue: 0x0985CD)), ColorModel(name: "Fantasy", firstGradientColor: NSColor.hexColor(rgbValue: 0x9155E1), secondGradientColor: NSColor.hexColor(rgbValue: 0x67ECFF)), ColorModel(name: "Hot", firstGradientColor: NSColor.hexColor(rgbValue: 0xFBDA61), secondGradientColor: NSColor.hexColor(rgbValue: 0xF76B1C)), ColorModel(name: "Linier Hot", firstGradientColor: NSColor.hexColor(rgbValue: 0xFC6E51), secondGradientColor: NSColor.hexColor(rgbValue: 0xDB391E)), ColorModel(name: "Red", firstGradientColor: NSColor.hexColor(rgbValue: 0xF5515F), secondGradientColor: NSColor.hexColor(rgbValue: 0x9F031B)), ColorModel(name: "Nature", firstGradientColor: NSColor.hexColor(rgbValue: 0x81D86D), secondGradientColor: NSColor.hexColor(rgbValue: 0x23AE87)), ColorModel(name: "Linier", firstGradientColor: NSColor.hexColor(rgbValue: 0x48CFAD), secondGradientColor: NSColor.hexColor(rgbValue: 0x19A784)), ColorModel(name: "Pink", firstGradientColor: NSColor.hexColor(rgbValue: 0xEC87C0), secondGradientColor: NSColor.hexColor(rgbValue: 0xBF4C90)), ColorModel(name: "Light Buisness", firstGradientColor: NSColor.hexColor(rgbValue: 0xEDF1F7), secondGradientColor: NSColor.hexColor(rgbValue: 0xC9D7E9)), ColorModel(name: "Business", firstGradientColor: NSColor.hexColor(rgbValue: 0xCCD1D9), secondGradientColor: NSColor.hexColor(rgbValue: 0x8F9AA8)) ] } }
// // Person.swift // MHPatientsApp // // Created by Dileep Sanker on 8/28/19. // Copyright © 2019 Dileep Sanker. All rights reserved. // import Foundation struct Person { var firstName: String var lastName: String var birthdate: Date var location: String } extension Person { static func steveJobs() -> Person { var birthdateComponents = DateComponents() birthdateComponents.year = 1955 birthdateComponents.month = 2 birthdateComponents.day = 24 let birthdate = Calendar.current.date(from: birthdateComponents)! return Person(firstName: "Steve", lastName: "Jobs", birthdate: birthdate,location: "USA") } }
// // APODViewController.swift // TestApp // // Created by Михаил Красильник on 27.04.2021. // import UIKit import WebKit protocol APODDisplayLogic: AnyObject { func displayAPOD(viewModel: APOD.ShowAPOD.ViewModel) } class APODViewController: UIViewController, APODDisplayLogic { var webView = WKWebView() let titleLabel = UILabel() let textView = UITextView() var interactor: APODBusinessLogic? var router: (NSObjectProtocol & APODRoutingLogic & APODDataPassing)? var apod: APODModel? override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) APODConfigurator.shared.configure(view: self) } required init?(coder: NSCoder) { super.init(coder: coder) APODConfigurator.shared.configure(view: self) } override func viewDidLoad() { super.viewDidLoad() let request = APOD.ShowAPOD.Request() interactor?.fetchAPOD(request: request) webView.backgroundColor = .backgroundForElements() view.backgroundColor = .mainBackground() setupConstraints() settingElements() } private func settingElements() { titleLabel.font = UIFont.systemFont(ofSize: 22) titleLabel.textColor = .white textView.textColor = .white textView.backgroundColor = .mainBackground() textView.font = UIFont.systemFont(ofSize: 18) } func displayAPOD(viewModel: APOD.ShowAPOD.ViewModel) { self.titleLabel.text = viewModel.title self.textView.text = viewModel.explanation self.webView.load(URLRequest(url: viewModel.webContent)) } } extension APODViewController { private func setupConstraints() { let configuration = WKWebViewConfiguration() configuration.allowsInlineMediaPlayback = false self.webView = WKWebView(frame: .zero, configuration: configuration) webView.translatesAutoresizingMaskIntoConstraints = false titleLabel.translatesAutoresizingMaskIntoConstraints = false textView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(webView) view.addSubview(titleLabel) view.addSubview(textView) NSLayoutConstraint.activate([ webView.topAnchor.constraint(equalTo: view.topAnchor), webView.leadingAnchor.constraint(equalTo: view.leadingAnchor), webView.trailingAnchor.constraint(equalTo: view.trailingAnchor), webView.heightAnchor.constraint(equalToConstant: view.frame.height / 3) ]) NSLayoutConstraint.activate([ titleLabel.topAnchor.constraint(equalTo: webView.bottomAnchor, constant: 10), titleLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 16), titleLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -16), titleLabel.heightAnchor.constraint(equalToConstant: 50) ]) NSLayoutConstraint.activate([ textView.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 10), textView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 16), textView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -16), textView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -30) ]) } }
import UIKit public class CustomKeyboardHandler: KeyboardHandler { public init() {} public func willShow(info: KeyboardInfo) { show?(info: info) } public func willHide(info: KeyboardInfo) { hide?(info: info) } public var show: ((info: KeyboardInfo) -> Void)? public var hide: ((info: KeyboardInfo) -> Void)? }
// // ArtObjectsServiceTests.swift // RijksMuseumTests // // Created by Alexander Vorobjov on 1/2/21. // import XCTest @testable import RijksMuseum class ArtObjectsServiceTests: XCTestCase { func testError_noInternetConnection() throws { let service = createServiceWithError(.noInternetConnection) service.loadHome { result in switch result { case .failure(let error): XCTAssertEqual(error, .noInternetConnection) case .success: XCTAssert(false, "Should return error") } } service.search(query: "asd") { result in switch result { case .failure(let error): XCTAssertEqual(error, .noInternetConnection) case .success: XCTAssert(false, "Should return error") } } service.details(objectNumber: ArtObjectNumber(stringLiteral: "asd")) { result in switch result { case .failure(let error): XCTAssertEqual(error, .noInternetConnection) case .success: XCTAssert(false, "Should return error") } } } func testError_other() throws { let service = createServiceWithError(.connectionError) service.loadHome { result in switch result { case .failure(let error): XCTAssertEqual(error, .commonError) case .success: XCTAssert(false, "Should return error") } } service.search(query: "asd") { result in switch result { case .failure(let error): XCTAssertEqual(error, .commonError) case .success: XCTAssert(false, "Should return error") } } service.details(objectNumber: ArtObjectNumber(stringLiteral: "asd")) { result in switch result { case .failure(let error): XCTAssertEqual(error, .commonError) case .success: XCTAssert(false, "Should return error") } } } func testReturnsCachedHome_noInternetConnection() { let session = MockSession { $0(.failure(.noInternetConnection)) } let network = ArtObjectsNetworkImpl(session: session) let database = MockArtObjectsDatabase() let service = ArtObjectsServiceImpl(network: network, database: database) // no cached data, no outdated -> return error service.loadHome { result in switch result { case .failure(let error): XCTAssertEqual(error, .noInternetConnection) case .success: XCTAssert(false, "Should return error") } } // no cached data, has outdated -> return outdated database.outdatedHome = [testObject(id: "outdated")] service.loadHome { result in switch result { case .failure: XCTAssert(false, "Should return outdated items") case .success(let items): XCTAssertEqual(items.count, 1) XCTAssertEqual(items.first!.id.rawValue, "outdated") } } // has cached, has outdated -> returns cached database.home = [testObject(id: "home")] service.loadHome { result in switch result { case .failure: XCTAssert(false, "Should return home items") case .success(let items): XCTAssertEqual(items.count, 1) XCTAssertEqual(items.first!.id.rawValue, "home") } } } func testReturnsCachedHome_connected() { class MockNetwork: ArtObjectsNetwork { func fetchHome(completion: @escaping SessionCompletion<[ArtObject]>) { XCTAssert(false, "Should ot call network") } func fetchSearch(query: String, completion: @escaping SessionCompletion<[ArtObject]>) { XCTAssert(false, "Should ot call network") } func fetchDetails(objectNumber: ArtObjectNumber, completion: @escaping SessionCompletion<ArtObjectDetails>) { XCTAssert(false, "Should ot call network") } } let network = MockNetwork() let database = MockArtObjectsDatabase() database.home = [testObject(id: "home")] let service = ArtObjectsServiceImpl(network: network, database: database) service.loadHome { result in switch result { case .failure: XCTAssert(false, "Should return home items") case .success(let items): XCTAssertEqual(items.count, 1) XCTAssertEqual(items.first!.id.rawValue, "home") } } } private func createServiceWithError(_ error: SessionError) -> ArtObjectsService { let session = MockSession { $0(.failure(error)) } let network = ArtObjectsNetworkImpl(session: session) return ArtObjectsServiceImpl(network: network, database: MockArtObjectsDatabase()) } private func testObject(id: String) -> ArtObject { return ArtObject( id: ArtObjectId(stringLiteral: id), objectNumber: ArtObjectNumber(stringLiteral: "object_number"), title: "title", author: "author", imageURL: URL(string: "http://image.url")!, detailsURL: URL(string: "http://detauls.url")!, webURL: URL(string: "http://web.url")!) } }
/* * Version for iOS © 2015–2021 YANDEX * * You may not use this file except in compliance with the License. * You may obtain a copy of the License at https://yandex.com/legal/mobileads_sdk_agreement/ */ import YandexMobileAds class VideoAdsTableViewController: UITableViewController { private let cellID = "Cell" private let ads: [YMAVASTAd] init(ads: [YMAVASTAd]) { self.ads = ads super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() self.title = "Video ads" tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellID) } // MARK: - Table view data source override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return ads.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellID)! cell.textLabel?.text = ads[indexPath.row].adTitle return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let controller = VideoAdDescriptionViewController(ad: ads[indexPath.row]) navigationController?.pushViewController(controller, animated: true) } }
// // EWRequest.swift // MyDYZB // // Created by 王武 on 2020/11/15. // import Foundation extension EWNetworkTools { ///get请求 func getData(path: String, params: [String : Any], success: @escaping EWResponseSuccess, failure: @escaping EWResponseFail) { EWNetworkTools.ShareInstance.getWith(url: path, params: params) { (response) in // 1.将response转换成字典类型 guard let json = response as? [String : Any] else { failure(NSError(domain: "转字典失败", code: 2000, userInfo: nil)) return } /// 2. 保证接口调通,则返回错误信息 guard json["error"] as? NSNumber == 0 else { failure(response) return } // 3.获取数组 guard let dataArray = json["data"] as? [[String : Any]] else { failure(NSError(domain: "获取数组失败", code: 2000, userInfo: nil)) return } /// 4.成功 success(dataArray as AnyObject) } error: { (error) in failure(error) } } ///post请求 func postData(path: String, params: [String : Any], success: @escaping EWResponseSuccess, failure: @escaping EWResponseFail) { EWNetworkTools.ShareInstance.postWith(url: path, params: params) { (response) in guard let json = response as? [String : Any] else { return } guard json["status"] as? NSNumber == 1 else { print(json["msg"] as? String ?? "") failure(response) return } success(response as AnyObject) } error: { (error) in failure(error) } } }
// // FeedItemSwiftUIView.swift // LayoutFrameworkBenchmark // // Created by Tran Duc on 12/7/19. // import UIKit import SwiftUI @available(iOS 13.0.0, *) class FeedItemSwiftUIView: UIView, DataBinder { lazy var feedItem = FeedItemDataWrapper(data: FeedItemData()) lazy var childViewController = UIHostingController(rootView: SUIViewContent(feedItem: feedItem)) override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = .white childViewController.view.translatesAutoresizingMaskIntoConstraints = true childViewController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight] childViewController.view.frame = self.bounds addSubview(childViewController.view) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setData(_ data: FeedItemData) { feedItem.data = data } override func sizeThatFits(_ size: CGSize) -> CGSize { return childViewController.sizeThatFits(in: size) } } @available(iOS 13.0.0, *) final class FeedItemDataWrapper: ObservableObject { @Published var data: FeedItemData init(data: FeedItemData) { self.data = data } } @available(iOS 13.0.0, *) struct SUIViewContent: View { @ObservedObject var feedItem: FeedItemDataWrapper var body: some View { VStack(alignment: .leading) { SUITopBarView(feedItem: feedItem) SUIPosterCard(feedItem: feedItem) Text(feedItem.data.posterComment) Image("350x200") Text(feedItem.data.contentTitle) Text(feedItem.data.contentDomain) SUIActions() SUIComment(feedItem: feedItem) }.padding() } } @available(iOS 13.0.0, *) fileprivate struct SUITopBarView: View { @ObservedObject var feedItem: FeedItemDataWrapper var body: some View { HStack { Text(feedItem.data.actionText) Spacer() Text("...") } } } @available(iOS 13.0.0, *) fileprivate struct SUIPosterCard: View { @ObservedObject var feedItem: FeedItemDataWrapper var body: some View { HStack { Image("50x50") VStack(alignment: .leading) { Text(feedItem.data.posterName).background(Color.yellow) Text(feedItem.data.posterHeadline).lineLimit(3) Text(feedItem.data.posterTimestamp).background(Color.yellow) } } } } @available(iOS 13.0.0, *) fileprivate struct SUIActions: View { var body: some View { HStack { Text("Like").background(Color.green) Spacer() Text("Comment").background(Color.green) Spacer() Text("Share").background(Color.green) } } } @available(iOS 13.0.0, *) fileprivate struct SUIComment: View { @ObservedObject var feedItem: FeedItemDataWrapper var body: some View { HStack { Image("50x50") Text(feedItem.data.actorComment) } } }
// FriendsVC.swift // IvVk // Created by Iv on 15/03/2019. // Copyright © 2019 Iv. All rights reserved. import UIKit struct Section { var name: String var persons: [Person] } class FriendsVC: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var letterControl: LetterControl! @IBOutlet weak var searchBar: UISearchBar! private var groupedFriends: [Section] = [] override func viewDidLoad() { super.viewDidLoad() tableView.backgroundColor = UIColor.myLightGreen tableView.register(UINib(nibName: "FriendsHeader", bundle: Bundle.main), forHeaderFooterViewReuseIdentifier: "FriendsHeader") letterControl.changeLetterHandler = letterChanged searchBar.returnKeyType = .done tableView.contentOffset = CGPoint(x: 0, y: searchBar.frame.size.height) refresh() } // letter control change letter handler private func letterChanged(_ letter: String) { for (index, value) in groupedFriends.enumerated() { if value.name == letter { tableView.scrollToRow(at: IndexPath(row: 0, section: index), at: .top, animated: true) } } } // set friends group array private func groupFriends(_ friendList: [Person]) { groupedFriends.removeAll() var dict = [String: [Person]]() for friend in friendList { let letter = friend.name.prefix(1).uppercased() var p = dict[letter] if p == nil { p = [Person]() } p!.append(friend) dict[letter] = p } for letter in dict.keys.sorted() { groupedFriends.append(Section(name: letter, persons: dict[letter]!)) } letterControl.Letters = dict.keys.sorted() } // MARK: - Table view data source func numberOfSections(in tableView: UITableView) -> Int { return groupedFriends.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return groupedFriends[section].persons.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "FriendsCell", for: indexPath) as! FriendsCell let friend = groupedFriends[indexPath.section].persons[indexPath.row] cell.loadCell(friend: friend) return cell } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: "FriendsHeader") as? FriendsHeader header?.nameSection.text = groupedFriends[section].name header?.contentView.backgroundColor = .white header?.contentView.alpha = 0.5 return header } private func refresh() { /*VkUsersService().loadFriendsList { [weak self] list in friends = list self?.groupFriends(friends) self?.tableView.reloadData() }*/ let userServiceProxy = VkUsersServiceProxy(userService: VkUsersService()) userServiceProxy.loadFriendsList { [weak self] list in friends = list self?.groupFriends(friends) self?.tableView.reloadData() } } @IBAction func refreshFriends(_ sender: UIBarButtonItem) { refresh() } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let fc = segue.destination as? FriendVC { if let indexPath = tableView.indexPathForSelectedRow { let p = groupedFriends[indexPath.section].persons[indexPath.row] fc.loadUserPhotos(userId: p.id ?? 0, userName: p.firstName) } } } // Perform manual segue "showFriend" on select row func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { performSegue(withIdentifier: "showFriend", sender: nil) } // MARK: - Search bar func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { if searchText.isEmpty { clearSearching() } else { let filteredFriends = friends.filter({ (Person) -> Bool in //return Person.name.lowercased().starts(with: searchText.lowercased()) return Person.name.lowercased().contains(searchText.lowercased()) }) groupFriends(filteredFriends) tableView.reloadData() } } private func clearSearching(endEditing end: Bool = false) { searchBar.text = nil groupFriends(friends) tableView.reloadData() if end { view.endEditing(true) } } func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool { searchBar.showsCancelButton = true return true } func searchBarShouldEndEditing(_ searchBar: UISearchBar) -> Bool { searchBar.showsCancelButton = false return true } func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { clearSearching(endEditing: true) } func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { clearSearching(endEditing: true) } }
// // ContentView.swift // GithubJobs // // Created by Andres Felipe Rojas R. on 1/10/20. // import SwiftUI struct ContentView: View { var body: some View { Text("Hello, world!") .padding() } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
// // SawasdeeModel.swift // KokaiByWGO // // Created by Waleerat Gottlieb on 2021-06-07. // import Foundation struct LevelModel : Identifiable{ var id: UUID var level_code : String var order_id : Int var level_name : String var level_description : String var column_chapter_per_row : String var image : String var background : String func dictionaryFrom(level: LevelModel) -> [String : Any] { return NSDictionary(objects: [level.id, level.level_code, level.order_id, level.level_name, level.level_description, level.column_chapter_per_row, level.image, level.background ], forKeys: ["id" as NSCopying, "level_code" as NSCopying, "order_id" as NSCopying, "level_name" as NSCopying, "level_description" as NSCopying, "column_chapter_per_row" as NSCopying, "image" as NSCopying, "background" as NSCopying ]) as! [String : Any] } } struct ChapterModel : Identifiable{ var id: UUID var level_code: String var chapter_code: String var order_id: Int var chapter_name: String var chapter_desctiption: String var column_chapter_per_row: String var image: String var background: String func dictionaryFrom(chapter: ChapterModel) -> [String : Any] { return NSDictionary(objects: [chapter.id, chapter.level_code, chapter.chapter_code, chapter.order_id, chapter.chapter_name, chapter.chapter_desctiption, chapter.column_chapter_per_row, chapter.image, chapter.background ], forKeys: ["id" as NSCopying, "level_code" as NSCopying, "chapter_code" as NSCopying, "order_id" as NSCopying, "chapter_name" as NSCopying, "chapter_desctiption" as NSCopying, "column_chapter_per_row" as NSCopying, "image" as NSCopying, "background" as NSCopying ]) as! [String : Any] } } struct SectionGroupModel { var section_group_code: String var section_name: String func dictionaryFrom(section: SectionGroupModel) -> [String : Any] { return NSDictionary(objects: [section.section_group_code, section.section_name ], forKeys: ["section_group_code" as NSCopying, "section_name" as NSCopying ]) as! [String : Any] } } struct SectionModel : Identifiable{ var id: UUID var level_code: String var chapter_code: String var section_code: String var order_id: Int var section_group: String var section_name: String var section_descritpion: String var column_sentence_per_row: String var image: String func dictionaryFrom(section: SectionModel) -> [String : Any] { return NSDictionary(objects: [section.id, section.level_code, section.chapter_code, section.section_code, section.order_id, section.section_group, section.section_name, section.section_descritpion, section.column_sentence_per_row, section.image ], forKeys: ["id" as NSCopying, "level_code" as NSCopying, "chapter_code" as NSCopying, "section_code" as NSCopying, "order_id" as NSCopying, "section_group" as NSCopying, "section_name" as NSCopying, "section_descritpion" as NSCopying, "column_sentence_per_row" as NSCopying, "image" as NSCopying ]) as! [String : Any] } } struct SentenceModel : Hashable,Identifiable{ var id: UUID var sentence_id: String var level_code: String var chapter_code: String var section_code: String var sentence_code: String var order_id: Int var sentence_text: String var word_list: [String] func dictionaryFrom(sentence: SentenceModel) -> [String : Any] { return NSDictionary(objects: [sentence.id, sentence.sentence_id, sentence.level_code, sentence.chapter_code, sentence.section_code, sentence.sentence_code, sentence.order_id, sentence.sentence_text, sentence.word_list ], forKeys: ["id" as NSCopying, "sentence_id" as NSCopying, "level_code" as NSCopying, "chapter_code" as NSCopying, "section_code" as NSCopying, "sentence_code" as NSCopying, "order_id" as NSCopying, "sentence_text" as NSCopying, "word_list" as NSCopying ]) as! [String : Any] } }
import Fluent import Vapor /// Called before your application initializes. func configure(_ application: Vapor.Application) { /// Register providers first application.provider(FluentProvider()) /// Register middleware application.register(MiddlewareConfiguration.self, middleware) configureDatabases(application) application.register(Migrations.self, migration) registerRepositories(application) application.register(AddUserCommand.self) { container in return .init(userRepository: container.make()) } application.register(extension: CommandConfiguration.self) { commands, c in commands.use(c.make(AddUserCommand.self), as: "addUser") } /// Register routes routes(application) }
// // Colors.swift // Color Picker // // Created by Adam Thoma-Perry on 4/20/18. // Copyright © 2018 Thoma-Perry, Adam. All rights reserved. // import UIKit struct Colors { let color: String let background: UIColor }
// // PopUpViewController.swift // ReusableControlsDemo // // Created by Alejandro Rodriguez on 26-03-18. // Copyright © 2018 Alejandro Rodriguez. All rights reserved. // import UIKit class PopUpViewController: UIViewController { @IBOutlet weak var xtitle: UILabel! @IBOutlet weak var picker: UIDatePicker! @IBOutlet weak var button: UIButton! var delegate : PopUpDelegate? var showDateTimer: Bool = false var onSave: ((_ date: String) -> ())? var formattedDate: String { let formatter = DateFormatter() formatter.dateStyle = .medium return formatter.string(from: picker.date) } var formattedTime: String { let formatter = DateFormatter() formatter.timeStyle = .short return formatter.string(from: picker.date) } override func viewDidLoad() { super.viewDidLoad() picker.datePickerMode = .date if showDateTimer { picker.datePickerMode = .time } } @IBAction func click_saveDate(_ sender: Any) { NotificationCenter.default.post(name: .saveDateTime, object: self) if showDateTimer { onSave?(formattedTime) delegate?.popupValue(value: formattedTime) } else { onSave?(formattedDate) delegate?.popupValue(value: formattedDate) } dismiss(animated: true) } }
// // ImageUtil.swift // ArgumentParser // // Created by 姜振华 on 2020/3/7. // import Foundation import ArgumentParser import SwiftGD struct FppImageUitlCommand: ParsableCommand { static var configuration = CommandConfiguration( commandName: "util", abstract: "内置工具" ) } extension URL { func fetchImageData(completionHandler: @escaping (Swift.Error?, Data?) -> Void) { FppConfig.session.dataTask(with: self) { data, _, error in completionHandler(error, data) }.resume() } func fetchImageBase64(completionHandler: @escaping (Swift.Error?, String?) -> Void) { fetchImageData { error, data in completionHandler(error, data?.base64EncodedString(options: .lineLength64Characters)) } } func fetchImage(completionHandler: @escaping (Swift.Error?, Image?) -> Void) { fetchImageData { error, data in guard let data = data else { completionHandler(error, nil) return } do { let img = try Image(data: data) completionHandler(error, img) } catch let e { completionHandler(e, nil) } } } func createDirIfNotExist() -> URL? { if !FileManager.default.fileExists(atPath: path) { do { try FileManager.default .createDirectory(at: self, withIntermediateDirectories: false, attributes: nil) } catch { return nil } } return self } }
// // HasNavConCoordinator.swift // Wallet // // Created by 郑军铎 on 2018/11/5. // Copyright © 2018 ZJaDe. All rights reserved. // import Foundation open class HasNavConCoordinator: NSObject, Coordinator, Flow, PushJumpPlugin, CoordinatorContainer { public var coordinators: [Coordinator] = [] public weak var navCon: UINavigationController? public required init(_ navCon: UINavigationController?) { self.navCon = navCon } open func startNoViewCon() { } } public extension ViewControllerConvertible where Self: PushJumpPlugin { func jump(viewCon: UIViewController) { guard let navCon = navCon else { return } if navCon.viewControllers.isEmpty { navCon.viewControllers = [viewCon] } else { push(viewCon) } } func popToCurrentViewController() { if let viewCon = getViewCon(self.rootViewController) { self.navCon?.popToViewController(viewCon, animated: true) } } private func getViewCon(_ viewCon: UIViewController?) -> UIViewController? { guard let parentVC = viewCon?.parent else { return nil } if parentVC == viewCon?.navigationController { return viewCon } return getViewCon(parentVC) } }
// // NetworkServiceTests.swift // CroesusTests // // Created by Ian Wanyoike on 04/02/2020. // Copyright © 2020 Pocket Pot. All rights reserved. // import Foundation @testable import Croesus import Quick import Nimble import RxBlocking import OHHTTPStubs class NetworkServiceTests: QuickSpec { override func spec() { describe("Request") { var networkService: NetworkServiceMock<NetworkModelMock>? var modelStub: HTTPStubsDescriptor? beforeEach { networkService = NetworkServiceMock() } context("Successful Response") { beforeEach { guard let stubPath = OHPathForFile("NetworkModel.json", type(of: self)) else { return } modelStub = stub(condition: isAbsoluteURLString(NetworkModelMock.baseUrl.absoluteString)) { _ -> HTTPStubsResponse in return fixture(filePath: stubPath, headers: ["Content-Type": "application/json"]) .requestTime(0.0, responseTime: OHHTTPStubsDownloadSpeedWifi) } } it("Fetches And Decodes Associated Type") { let expectedModel = NetworkModelMock(id: 1, name: "Job") let networkModel = try? networkService?.request().toBlocking().first() expect(networkModel).notTo(beNil()) expect(networkModel).to(equal(expectedModel)) } } context("Unsuccessful Response") { it("Fails Retrieve and Decode Associated Type") { let networkModel = try? networkService?.request().toBlocking().first() expect(networkModel).to(beNil()) } } afterEach { guard let stub = modelStub else { return } HTTPStubs.removeStub(stub) } } } }
// // StudentFindTimeCell.swift // NewSwift // // Created by gail on 2019/7/2. // Copyright © 2019 NewSwift. All rights reserved. // import UIKit class StudentFindTimeCell: UITableViewCell { var model:StudyTimeModel? { didSet{ typeLabel.text = model?.StudyType timeLabel.text = "\(model?.StudyDate ?? "") \(model?.StartTime ?? "")-\(model?.EndTime ?? "")" state1Btn.setTitle(model?.UpState, for: .normal) state2Btn.setTitle(model?.ExeState, for: .normal) hoursLabel.text = "\(model?.Duration ?? "") (小时)" } } @IBOutlet weak var typeLabel: UILabel! @IBOutlet weak var hoursLabel: UILabel! @IBOutlet weak var state1Btn: StydyTimeBtn! @IBOutlet weak var state2Btn: StydyTimeBtn! @IBOutlet weak var photeBtn: ApplyBtn! @IBOutlet weak var timeLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() photeBtn.setTitle("照片", for: .normal) photeBtn.isEnabled = false selectionStyle = .none } @IBAction func FindPhotoClick(_ sender: ApplyBtn) { } override var frame:CGRect{ didSet { var newFrame = frame newFrame.origin.x += LINE_SPACE newFrame.size.width -= LINE_SPACE*2 newFrame.origin.y += LINE_SPACE newFrame.size.height -= LINE_SPACE super.frame = newFrame } } }
// // UIViewController+.swift // FruitSchool // // Created by Presto on 2018. 9. 4.. // Copyright © 2018년 YAPP. All rights reserved. // import UIKit extension UIViewController { static func instantiate(storyboard: String, identifier: String) -> UIViewController? { let storyboard = UIStoryboard(name: storyboard, bundle: nil) let controller = storyboard.instantiateViewController(withIdentifier: identifier) return controller } }
// // PendingAppointmentsViewController.swift // MyApp2 // // Created by Anıl Demirci on 24.08.2021. // import UIKit import Firebase class PendingAppointmentsViewController: UIViewController,UITableViewDelegate,UITableViewDataSource { @IBOutlet weak var tableView: UITableView! var firestoreDatabase=Firestore.firestore() var currentUser=Auth.auth().currentUser var stadiumName="" var appointmentsArray=[String]() var chosenAppointment="" var currentTime="" var daysArray=[String]() override func viewDidLoad() { super.viewDidLoad() tableView.dataSource=self tableView.delegate=self // Do any additional setup after loading the view. navigationItem.title="Bekleyen Randevular" navigationController?.navigationBar.titleTextAttributes=[NSAttributedString.Key.foregroundColor:UIColor.white] navigationController?.navigationBar.topItem?.title="Hesabım" for day in 0...13 { let hourToAdd=3 let daysToAdd=0 + day let UTCDate = getCurrentDate() var dateComponent = DateComponents() dateComponent.hour=hourToAdd dateComponent.day = daysToAdd let currentDate = Calendar.current.date(byAdding: dateComponent, to: UTCDate) let dateFormatter = DateFormatter() dateFormatter.dateStyle = .medium dateFormatter.dateFormat = "dd.MM.yyyy" let date = dateFormatter.string(from: currentDate! as Date) daysArray.append(date) } getFromDatabase() } func getFromDatabase(){ firestoreDatabase.collection("StadiumAppointments").document(stadiumName).collection(stadiumName).whereField("Status", isEqualTo: "Onay bekliyor.").addSnapshotListener { (snapshot, error) in if error == nil { for document in snapshot!.documents { let date=document.get("AppointmentDate") as! String if self.daysArray.contains(date) { self.appointmentsArray.append(document.documentID) print(self.appointmentsArray) } } if self.appointmentsArray.count == 0 { self.tableView.isUserInteractionEnabled=false } self.tableView.reloadData() } } } func getCurrentDate()->Date { var now=Date() var nowComponents = DateComponents() let calendar = Calendar.current nowComponents.year = Calendar.current.component(.year, from: now) nowComponents.month = Calendar.current.component(.month, from: now) nowComponents.day = Calendar.current.component(.day, from: now) nowComponents.hour = Calendar.current.component(.hour, from: now) nowComponents.minute = Calendar.current.component(.minute, from: now) nowComponents.second = Calendar.current.component(.second, from: now) nowComponents.timeZone = NSTimeZone.local now = calendar.date(from: nowComponents)! return now } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if appointmentsArray.count == 0 { return 1 } else { return appointmentsArray.count } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell=tableView.dequeueReusableCell(withIdentifier: "pendingAppointments", for: indexPath) as! PendingAppointmentsCellTableViewCell if appointmentsArray.count == 0 { cell.appointmentLabel.text="Henüz bekleyen randevunuz yok." return cell } else { cell.appointmentLabel.text=appointmentsArray[indexPath.row] return cell } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { chosenAppointment=appointmentsArray[indexPath.row] performSegue(withIdentifier: "toConfirmAppointment", sender: nil) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "toConfirmAppointment" { let destinationVC=segue.destination as! ConfirmAppointmentViewController destinationVC.documentID=chosenAppointment destinationVC.name=stadiumName } } func makeAlert(titleInput: String,messageInput: String){ let alert=UIAlertController(title: titleInput, message: messageInput, preferredStyle: UIAlertController.Style.alert) let okButton=UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil) alert.addAction(okButton) self.present(alert, animated: true, completion: nil) } }
// // DishGroupTBCell.swift // UBIEAT // // Created by UBIELIFE on 2016-09-02. // Copyright © 2016 UBIELIFE Inc. All rights reserved. // import UIKit class DishGroupTBCell: UITableViewCell { @IBOutlet weak var nameLabel: UILabel! func setName(name: String) { self.nameLabel.text = name } func setSelect(flag: Bool ) { if flag { self.contentView.backgroundColor = UIColor.lightGrayColor() } else{ self.contentView.backgroundColor = UIColor.init(floatValueRed: 239, green: 239, blue: 239, alpha: 1) } } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
// // buttonView.swift // MtoM fake // // Created by Trương Thắng on 12/29/15. // Copyright © 2015 Trương Thắng. All rights reserved. // import UIKit class buttonView: UIView { }
// // Constants.swift // imgurTestApp // // Created by MacBook Pro on 30.09.2018. // Copyright © 2018 MacBook Pro. All rights reserved. // import Foundation struct Constants { ///URL сервера struct ServerURL { static let imgur = "https://api.imgur.com/3" } /// Заголовок авторизации struct AuthHeader { static let clientId = "Client-ID 5b768967a941aa1" } ///Запрашиваема модель данных сервера struct ServerModel { static let gallery = "gallery" static let comment = "comment" static let album = "album" static let account = "account" } ///Раздел галереи struct Section { static let hot = "hot" static let top = "top" static let user = "user" } ///Порядок сортировки галереи struct Sort { static let viral = "viral" static let top = "top" static let time = "time" static let rising = "rising" } ///Период (только для раздела top) struct Window { static let day = "day" static let week = "week" static let month = "month" static let year = "year" static let all = "all" } /// насттройка CollectionView на ViewController struct CollectionViewSetup { static let itemsInRow = 2 static let aspectRatio = 2.0 / 3.0 } }
import GRDB class EnabledWallet_v_0_13: Record { let coinId: String let accountId: String var derivation: String? var syncMode: String? init(coinId: String, accountId: String, derivation: String?, syncMode: String?) { self.coinId = coinId self.accountId = accountId self.derivation = derivation self.syncMode = syncMode super.init() } override class var databaseTableName: String { "enabled_wallets" } enum Columns: String, ColumnExpression { case coinId, accountId, derivation, syncMode } required init(row: Row) { coinId = row[Columns.coinId] accountId = row[Columns.accountId] derivation = row[Columns.derivation] syncMode = row[Columns.syncMode] super.init(row: row) } override func encode(to container: inout PersistenceContainer) { container[Columns.coinId] = coinId container[Columns.accountId] = accountId container[Columns.derivation] = derivation container[Columns.syncMode] = syncMode } }
import Foundation import AudioToolbox public class Class { public static func Hello() -> Void { print(AudioStreamBasicDescription()) } }
// // ViewController.swift // NavegacaoTelaDemo // // Created by Douglas Del Frari on 23/07/21. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } @IBAction func proximaTela(_ sender: Any) { // temos que declarar na configuracao da propriedade da segue um valor, neste caso 'proximaTela' foi usado. performSegue(withIdentifier: "proximaTela", sender: nil) } @IBAction func unwindTela1(segue: UIStoryboardSegue) { print("--> unwindTela1 (( segue para voltar para tela 1 )) <<--") } }
// // DetailReqViewController.swift // Taxi // // Created by Bhavin on 10/03/17. // Copyright © 2017 icanStudioz. All rights reserved. // import UIKit import Firebase class DetailReqViewController: UIViewController { @IBOutlet var UserAvatar: UIImageView! @IBOutlet var name: UILabel! @IBOutlet var pickupLoc: UILabel! @IBOutlet var dropLoc: UILabel! @IBOutlet var fare: UILabel! @IBOutlet var status: UILabel! @IBOutlet var acceptButton: UIButton! @IBOutlet var cancelButton: UIButton! @IBOutlet var offlinePaymentButton: UIButton! @IBOutlet var time: UILabel! @IBOutlet var PickUpPoint: UILabel! @IBOutlet var date: UILabel! @IBOutlet var Namelbl: UILabel! @IBOutlet var PickupAddlbl: UILabel! @IBOutlet var DropAddlbl: UILabel! @IBOutlet var Farelbl: UILabel! @IBOutlet var PaymentStatuslbl: UILabel! @IBOutlet var Timelbl: UILabel! @IBOutlet var PickupPointlbl: UILabel! @IBOutlet var datelbl: UILabel! var requestPage:RequestView? var rideDetail:Ride? var travel_status = "" var paymentMode = "" var paymentStatus = "" var seeNewPostsButton:SeeNewPostsButton! var seeNewPostsButtonTopAnchor:NSLayoutConstraint! var postListenerHandle:UInt? override func viewDidLoad() { super.viewDidLoad() self.title = "Passenger Information" let homeButton = UIBarButtonItem(image: UIImage(named: "homeButton"), style: .plain, target: self, action: #selector(self.homeWasClicked(_:))) self.navigationItem.rightBarButtonItem = homeButton Namelbl.text = LocalizationSystem.sharedInstance.localizedStringForKey(key: "DetailReqVCNamelbl", comment: "") PickupAddlbl.text = LocalizationSystem.sharedInstance.localizedStringForKey(key: "DetailReqVCPickupAddlbl", comment: "") DropAddlbl.text = LocalizationSystem.sharedInstance.localizedStringForKey(key: "DetailReqVCDropAddlbl", comment: "") Farelbl.text = LocalizationSystem.sharedInstance.localizedStringForKey(key: "DetailReqVCFarelbl", comment: "") PaymentStatuslbl.text = LocalizationSystem.sharedInstance.localizedStringForKey(key: "DetailReqVCPaymentStatuslbl", comment: "") Timelbl.text = LocalizationSystem.sharedInstance.localizedStringForKey(key: "DetailReqVCTimelbl", comment: "") datelbl.text = LocalizationSystem.sharedInstance.localizedStringForKey(key: "DetailReqVCdatelbl", comment: "") PickupPointlbl.text = LocalizationSystem.sharedInstance.localizedStringForKey(key: "DetailReqVCPickupPointlbl", comment: "") var layoutGuide:UILayoutGuide! if #available(iOS 11.0, *) { layoutGuide = view.safeAreaLayoutGuide } else { // Fallback on earlier versions layoutGuide = view.layoutMarginsGuide } seeNewPostsButton = SeeNewPostsButton() seeNewPostsButton.button.setTitle(LocalizationSystem.sharedInstance.localizedStringForKey(key: "DetailReqVC_refreshButton", comment: ""), for: .normal) view.addSubview(seeNewPostsButton) seeNewPostsButton.translatesAutoresizingMaskIntoConstraints = false seeNewPostsButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true seeNewPostsButtonTopAnchor = seeNewPostsButton.topAnchor.constraint(equalTo: layoutGuide.topAnchor, constant: -44) seeNewPostsButtonTopAnchor.isActive = true seeNewPostsButton.heightAnchor.constraint(equalToConstant: 32.0).isActive = true seeNewPostsButton.widthAnchor.constraint(equalToConstant: seeNewPostsButton.button.bounds.width).isActive = true seeNewPostsButton.button.addTarget(self, action: #selector(handleRefresh), for: .touchUpInside) // self.travel_status = rideDetail?.Travel_Status as! String self.paymentMode = rideDetail?.paymentMode as! String self.paymentStatus = rideDetail?.paymentStatus as! String if (self.requestPage == RequestView.accepted && (self.travel_status == "STARTED" || self.travel_status == "PAID")){ let vc = self.storyboard?.instantiateViewController(withIdentifier: "AcceptDetailReqViewController") as! AcceptDetailReqViewController vc.requestPage = RequestView.accepted vc.rideDetail = self.rideDetail vc.rideDetail?.Travel_Status = self.travel_status vc.rideDetail?.paymentMode = self.paymentMode vc.rideDetail?.paymentStatus = self.paymentStatus self.navigationController?.pushViewController(vc, animated: true) } setupData() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) listenForNewRefresh() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func homeWasClicked(_ sender: UIButton) { let vc = self.storyboard?.instantiateViewController(withIdentifier: "HomeViewController") as! HomeViewController self.navigationController?.pushViewController(vc, animated: true) } func setupData(){ // -- setup title for button according to page requests -- if requestPage == RequestView.accepted { if (travel_status == "PENDING") { // print("yes") acceptButton.setTitle(LocalizationSystem.sharedInstance.localizedStringForKey(key: "DetailReqVC_Start", comment: ""), for: .normal) } else { // print("no") // acceptButton.isHidden = true acceptButton.setTitle(LocalizationSystem.sharedInstance.localizedStringForKey(key: "DetailReqVC_Track", comment: ""), for: .normal) acceptButton.isHidden = true cancelButton.setTitle(LocalizationSystem.sharedInstance.localizedStringForKey(key: "DetailReqVC_Cancel", comment: ""), for: .normal) } } if requestPage == RequestView.pending { acceptButton.setTitle(LocalizationSystem.sharedInstance.localizedStringForKey(key: "DetailReqVC_Accept", comment: ""), for: .normal) cancelButton.setTitle(LocalizationSystem.sharedInstance.localizedStringForKey(key: "DetailReqVC_Cancel", comment: ""), for: .normal) } // Buttons if requestPage == RequestView.accepted || requestPage == RequestView.pending { if (travel_status == "PENDING") { // print("buttons pending") cancelButton.isHidden = true acceptButton.isHidden = true } else { // print("buttons not pending") acceptButton.isHidden = false cancelButton.isHidden = false } } else { // print("buttons else") acceptButton.isHidden = true cancelButton.isHidden = true } // ibrahim commented on this code if requestPage == RequestView.cancelled || requestPage == RequestView.completed { // print("request page cancelled or completed") offlinePaymentButton.isHidden = true acceptButton.isHidden = true cancelButton.isHidden = true } // -- setup back button -- let backButton = UIBarButtonItem(image: UIImage(named: "arrow-left"), style: .plain, target: self, action: #selector(self.backWasPressed)) self.navigationItem.leftBarButtonItem = backButton // -- setup ride data -- name.text = rideDetail?.userName pickupLoc.text = rideDetail?.pickupAdress dropLoc.text = rideDetail?.dropAdress fare.text = rideDetail?.amount status.text = self.paymentStatus time.text = rideDetail?.time ?? "" date.text = rideDetail?.date ?? "" //by ibrahim PickUpPoint.text = rideDetail?.pickup_point ?? "" if let urlString = URL(string: (rideDetail?.userAvatar)!){ UserAvatar.kf.setImage(with: urlString) } // ibrahim was here // offline button if self.paymentMode != "OFFLINE" { offlinePaymentButton.isHidden = true } else { if (travel_status == "PENDING") { offlinePaymentButton.isHidden = true } else { if (travel_status == "STARTED"){ offlinePaymentButton.isHidden = false offlinePaymentButton.setTitle(LocalizationSystem.sharedInstance.localizedStringForKey(key: "DetailReqVC_offlinePayment", comment: ""), for: .normal) if self.paymentStatus == "PAID" { offlinePaymentButton.isHidden = true } } } } if self.paymentStatus != "" { if self.paymentMode == "OFFLINE" && self.paymentStatus != "PAID" { status.text = "Cash On Hand (Driver)" acceptButton.isHidden = false cancelButton.isHidden = false } else { //---------------------------------------------- // edit by ibrahim, to handle complete case //acceptButton.isHidden = true acceptButton.isHidden = false acceptButton.setTitle(LocalizationSystem.sharedInstance.localizedStringForKey(key: "DetailReqVC_Complete", comment: ""), for: .normal) //---------------------------------------------- cancelButton.isHidden = true status.text = self.paymentStatus } } if requestPage == RequestView.cancelled || requestPage == RequestView.completed { // print("request page cancelled or completed") offlinePaymentButton.isHidden = true acceptButton.isHidden = true cancelButton.isHidden = true } } @IBAction func acceptWasPressed(_ sender: UIButton) { if requestPage == RequestView.pending{ sendRequests(with: "ACCEPTED") // print("ACCEPTED") } //---------------------------------------------- // edit by ibrahim, to handle complete case else if self.paymentMode == "OFFLINE" && self.paymentStatus == "PAID" { // print("COMPLETED") sendRequests(with: "COMPLETED") } //---------------------------------------------- else { if (travel_status == "PENDING") { sendRequests(with: "ACCEPTED") //let vc } else { let vc = self.storyboard?.instantiateViewController(withIdentifier: "TrackRideViewController") as! TrackRideViewController vc.currentRide = rideDetail self.navigationController?.pushViewController(vc, animated: true) } } } @IBAction func offlinePaymentWasPressed(_ sender: Any) { sendPaymentRequests(with: "PAID") } @IBAction func cancelWasPressed(_ sender: UIButton) { sendRequests(with: "CANCELLED") } @objc func backWasPressed(){ _ = self.navigationController?.popViewController(animated: true) } func sendRequests(with status:String){ var params = [String:String]() if (requestPage == RequestView.accepted && travel_status == "PENDING") { print("sendRequests pending") travel_status = "STARTED" params = ["ride_id":rideDetail!.rideId,"status":status, "travel_id":rideDetail!.travelId, "travel_status":self.travel_status,"by":"driver"]//,"by":"driver" } else { if status == "ACCEPTED"{ print("status accepted") travel_status = "PENDING" } else if status == "COMPLETED" { travel_status = "COMPLETED" } else{ print("status not accepted") travel_status = "PENDING" // for later to be fixed by ibrahim } print("sendRequests not pending") params = ["ride_id":rideDetail!.rideId,"status":status, "travel_id":rideDetail!.travelId, "travel_status":self.travel_status,"by":"driver"]// } print("ibrahim before params") print(params) let headers = ["X-API-KEY":Common.instance.getAPIKey()] HUD.show(to: view) APIRequestManager.request(apiRequest: APIRouters.UpdateRides(params, headers), success: { (response) in HUD.hide(to: self.view) print("response") print(response) if response is String { let alert = UIAlertController(title: NSLocalizedString("Success!!", comment: ""), message: response as? String, preferredStyle: .alert) let done = UIAlertAction(title: NSLocalizedString("Done", comment: ""), style: .default, handler: { (action) in // self.backWasPressed() print("status by ibrahim") print(status) print(self.requestPage?.rawValue) print(self.travel_status) if (self.requestPage == RequestView.accepted && (self.travel_status == "STARTED" || self.travel_status == "PAID")){ let vc = self.storyboard?.instantiateViewController(withIdentifier: "AcceptDetailReqViewController") as! AcceptDetailReqViewController vc.requestPage = RequestView.accepted vc.rideDetail = self.rideDetail vc.rideDetail?.Travel_Status = self.travel_status vc.rideDetail?.paymentMode = self.paymentMode vc.rideDetail?.paymentStatus = self.paymentStatus self.navigationController?.pushViewController(vc, animated: true) } else if (self.travel_status == "COMPLETED"){ let vc = self.storyboard?.instantiateViewController(withIdentifier: "HomeViewController") as! HomeViewController self.navigationController?.pushViewController(vc, animated: true) } self.updateRideFirebase(with:status,travel_status: self.travel_status, paymentStatus: self.paymentStatus, paymentMode: self.paymentMode) self.updateNotificationFirebase(with:status) self.updateTravelCounterFirebase(with: status) if status == "ACCEPTED"{ print("ibrahim_accepted") self.updateTravelFirebase() } }) alert.addAction(done) self.present(alert, animated: true, completion: nil) } }, failure: { (message) in HUD.hide(to: self.view) Common.showAlert(with: NSLocalizedString("Alert!!", comment: ""), message: message, for: self) }, error: { (err) in HUD.hide(to: self.view) Common.showAlert(with: NSLocalizedString("Error!!" ,comment: ""), message: err.localizedDescription, for: self) }) } func sendPaymentRequests(with status:String){ let params = ["ride_id":rideDetail!.rideId,"travel_id":rideDetail!.travelId, "payment_status":status,"by":"driver"]//"by":"driver" let headers = ["X-API-KEY":Common.instance.getAPIKey()] HUD.show(to: view) APIRequestManager.request(apiRequest: APIRouters.UpdateRides(params, headers), success: { (response) in HUD.hide(to: self.view) if response is String { let alert = UIAlertController(title: NSLocalizedString("Success!!", comment: ""), message: response as? String, preferredStyle: .alert) let done = UIAlertAction(title: NSLocalizedString("Done", comment: ""), style: .default, handler: { (action) in // self.backWasPressed() }) var ride_status_st = "" if self.requestPage!.rawValue == RequestView.pending.rawValue {ride_status_st = "PENDING"} else if self.requestPage!.rawValue == RequestView.accepted.rawValue {ride_status_st = "ACCEPTED"} else if self.requestPage!.rawValue == RequestView.completed.rawValue {ride_status_st = "COMPLETED"} else if self.requestPage!.rawValue == RequestView.cancelled.rawValue {ride_status_st = "CANCELLED"} self.updateRideFirebase(with: ride_status_st, travel_status: self.travel_status, paymentStatus: status, paymentMode: self.paymentMode) self.updateNotificationFirebase(with: "offline_approved") self.updateTravelCounterFirebase(with: "PAID") alert.addAction(done) self.present(alert, animated: true, completion: nil) } }, failure: { (message) in HUD.hide(to: self.view) Common.showAlert(with: NSLocalizedString("Alert!!", comment: ""), message: message, for: self) }, error: { (err) in HUD.hide(to: self.view) Common.showAlert(with: NSLocalizedString("Error!!" ,comment: ""), message: err.localizedDescription, for: self) }) } @objc func handleRefresh() { // toggleSeeNewPostsButton(hidden: true) } func toggleSeeNewPostsButton(hidden:Bool) { if hidden { // hide it UIView.animate(withDuration: 0.5, delay: 0.0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.5, options: .curveEaseOut, animations: { self.seeNewPostsButtonTopAnchor.constant = -44.0 self.view.layoutIfNeeded() }, completion: nil) } else { // show it UIView.animate(withDuration: 0.5, delay: 0.0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.5, options: .curveEaseOut, animations: { self.seeNewPostsButtonTopAnchor.constant = 12 self.view.layoutIfNeeded() }, completion: nil) } } func listenForNewRefresh() { postListenerHandle = Database.database().reference().child("rides").child(rideDetail!.rideId).observe(.childChanged, with: { snapshot in print("ibrahim snapshot") print(snapshot.value) if let data = snapshot.value as? String{ if snapshot.key == "ride_status" { if data == "PENDING" { self.requestPage = RequestView.pending } else if data == "ACCEPTED" { self.requestPage = RequestView.accepted } else if data == "COMPLETED" { self.requestPage = RequestView.completed } else if data == "CANCELLED" { self.requestPage = RequestView.cancelled } } else if snapshot.key == "travel_status" { self.travel_status = data } else if snapshot.key == "payment_status" { self.paymentStatus = data } else if snapshot.key == "payment_mode" { self.paymentMode = data } else if snapshot.key == "timestamp" { print("timestamp") } // self.toggleSeeNewPostsButton(hidden: false) self.setupData() } }) } func updateRideFirebase(with status:String, travel_status:String, paymentStatus:String, paymentMode:String) { let postRef = Database.database().reference().child("rides").child(rideDetail!.rideId) let postObject = [ "timestamp": [".sv":"timestamp"], "ride_status": status, "travel_status": travel_status, "payment_status": paymentStatus, "payment_mode": paymentMode] as [String:Any] postRef.setValue(postObject, withCompletionBlock: { error, ref in if error == nil { } else { } }) } func updateNotificationFirebase(with status:String) { let postRef = Database.database().reference().child("Notifications").child(rideDetail!.userId).childByAutoId() let postObject = [ "ride_id": rideDetail!.rideId, "travel_id": rideDetail!.travelId, // "text": LocalizationSystem.sharedInstance.localizedStringForKey(key: "Notification_ride_updated", comment: "") + status, "text": status.lowercased(), "readStatus": "0", "timestamp": [".sv":"timestamp"], "uid": Auth.auth().currentUser?.uid] as [String:Any] postRef.setValue(postObject, withCompletionBlock: { error, ref in if error == nil { } else { } }) } func updateTravelCounterFirebase(with status:String) { print("updateTravelCounteR") if status == "ACCEPTED"{ Database.database().reference().child("Travels").child(rideDetail!.travelId).child("Counters").child("ACCEPTED").observeSingleEvent(of: .value, with: { snapshot in print("snapshot") print(snapshot) if let data = snapshot.value as? Int{ print("ibrahim") print("data") print(data) let postRef = Database.database().reference().child("Travels").child(self.rideDetail!.travelId).child("Counters").child("ACCEPTED") postRef.setValue(data + 1, withCompletionBlock: { error, ref in if error == nil { print("error") } else { print("else") // Handle the error } }) } }) } else if status == "COMPLETED"{ Database.database().reference().child("Travels").child(rideDetail!.travelId).child("Counters").child("COMPLETED").observeSingleEvent(of: .value, with: { snapshot in print("snapshot") print(snapshot) if let data = snapshot.value as? Int{ print("ibrahim") print("data") print(data) let postRef = Database.database().reference().child("Travels").child(self.rideDetail!.travelId).child("Counters").child("COMPLETED") postRef.setValue(data + 1, withCompletionBlock: { error, ref in if error == nil { print("error") } else { print("else") // Handle the error } }) } }) } else if status == "OFFLINE"{ Database.database().reference().child("Travels").child(rideDetail!.travelId).child("Counters").child("OFFLINE").observeSingleEvent(of: .value, with: { snapshot in print("snapshot") print(snapshot) if let data = snapshot.value as? Int{ print("ibrahim") print("data") print(data) let postRef = Database.database().reference().child("Travels").child(self.rideDetail!.travelId).child("Counters").child("OFFLINE") postRef.setValue(data + 1, withCompletionBlock: { error, ref in if error == nil { print("error") } else { print("else") // Handle the error } }) } }) } else if status == "PAID"{ Database.database().reference().child("Travels").child(rideDetail!.travelId).child("Counters").child("PAID").observeSingleEvent(of: .value, with: { snapshot in print("snapshot") print(snapshot) if let data = snapshot.value as? Int{ print("ibrahim") print("data") print(data) let postRef = Database.database().reference().child("Travels").child(self.rideDetail!.travelId).child("Counters").child("PAID") postRef.setValue(data + 1, withCompletionBlock: { error, ref in if error == nil { print("error") } else { print("else") // Handle the error } }) } }) } } func updateTravelFirebase() { print("updateTravelFirebase") let postRef = Database.database().reference().child("Travels").child(rideDetail!.travelId).child("Clients").child(rideDetail!.userId) postRef.setValue(rideDetail!.userId, withCompletionBlock: { error, ref in if error == nil { } else { } }) } }
// // CollectionHeaderView.swift // Live-zzu // // Created by 如是我闻 on 2017/3/26. // Copyright © 2017年 如是我闻. All rights reserved. // import UIKit class CollectionHeaderView: UICollectionReusableView { @IBOutlet weak var titleLabel: UILabel! //模型属性 var group : XinXiGroup?{ didSet{ titleLabel.text = group?.tag_name } } }
import UIKit class MainViewController: UIViewController, GameDelegate { @IBOutlet weak var userImageView: UIImageView! @IBOutlet weak var userNameLabel: UILabel! @IBOutlet weak var scoreLabel: UILabel! @IBOutlet weak var levelNameLabel: UILabel! @IBOutlet weak var scoreDescription: UILabel! var gameCoordinator: GameCoordinator? var imagePicker: ImagePicker! override func viewDidLoad() { super.viewDidLoad() imagePicker = ImagePicker(presentationController: self, delegate: self) userImageView.layer.cornerRadius = userImageView.bounds.height / 2 userImageView.isUserInteractionEnabled = true userImageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(editProfilePicture))) userNameLabel.text = gameCoordinator?.user?.username userImageView.image = gameCoordinator?.user?.image guard let user = gameCoordinator?.user else { return } gameCoordinator?.game.startGame(for: user) gameCoordinator?.game.delegate = self levelNameLabel.text = gameCoordinator?.user?.level.title userNameLabel.text = gameCoordinator?.user?.username scoreLabel.text = String(user.score) scoreDescription.text = gameCoordinator?.game.generateRandomCheer() } @objc func editProfilePicture() { imagePicker.present(from: view) } override var preferredStatusBarStyle: UIStatusBarStyle { return .darkContent } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) navigationController?.navigationBar.isHidden = true } func game(_ game: Game, stateChanged state: GameState) { scoreLabel.text = String(game.score) scoreDescription.text = game.generateRandomCheer() gameCoordinator?.saveUser() } @IBAction func settingsButtonTapped(_ sender: Any) { let settingsViewController = UIStoryboard.main.instantiateViewController(withIdentifier: Constants.Storyboards.ViewController.settings) settingsViewController.modalPresentationStyle = .fullScreen (settingsViewController as? SettingsViewController)?.gameCoordinator = gameCoordinator present(settingsViewController, animated: true, completion: nil) } @IBAction func friendsButtonTapped(_ sender: Any) { let friendsViewController = UIStoryboard.main.instantiateViewController(withIdentifier: Constants.Storyboards.ViewController.friends) friendsViewController.modalPresentationStyle = .fullScreen present(friendsViewController, animated: true, completion: nil) } @IBAction func challengeButtonTapped(_ sender: Any) { let challangesViewController = UIStoryboard.main.instantiateViewController(withIdentifier: Constants.Storyboards.ViewController.challenges) challangesViewController.modalPresentationStyle = .fullScreen present(challangesViewController, animated: true, completion: nil) } @IBAction func leaderBoardButtonTapped(_ sender: Any) { let leaderBoardViewController = UIStoryboard.main.instantiateViewController(withIdentifier: Constants.Storyboards.ViewController.leaderBoard) leaderBoardViewController.modalPresentationStyle = .fullScreen present(leaderBoardViewController, animated: true, completion: nil) } } extension MainViewController: ImagePickerDelegate { func didSelect(image: UIImage?) { userImageView.image = image gameCoordinator?.user?.image = image gameCoordinator?.saveUser() } }
import UIKit import RealmSwift class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UIImagePickerControllerDelegate, UINavigationControllerDelegate { @IBOutlet weak var collectionView: UICollectionView! override func viewDidLoad() { super.viewDidLoad() title = "Realm Pics" navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(importPicture)) collectionView.delegate = self collectionView.dataSource = self } func importPicture() { let picker = UIImagePickerController() picker.allowsEditing = true picker.delegate = self let actionSheet = UIAlertController(title: "Photo Source", message: "Choose Source", preferredStyle: .actionSheet) actionSheet.addAction(UIAlertAction(title: "Camera", style: .default, handler: { (action: UIAlertAction) in if UIImagePickerController.isSourceTypeAvailable(.camera) { picker.sourceType = .camera self.present(picker, animated: true, completion: nil) } else { print("Camera not available") } })) actionSheet.addAction(UIAlertAction(title: "Photo Library", style: .default, handler: { (action: UIAlertAction) in picker.sourceType = .photoLibrary self.present(picker, animated: true, completion: nil) })) actionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) present(actionSheet, animated: true) } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { guard let image = info[UIImagePickerControllerEditedImage] as? UIImage else { return } dismiss(animated: true) } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ImageCell", for: indexPath) as? ImageCell { cell.updateCell() } else { return UICollectionViewCell() } } }
// // AccentColor_Intro.swift // 100Views // // Created by Mark Moeykens on 9/17/19. // Copyright © 2019 Mark Moeykens. All rights reserved. // import SwiftUI struct AccentColor_Intro: View { @State private var slider = 0.5 var body: some View { VStack(spacing: 30) { Text("AccentColor").font(.largeTitle) Text("Introduction").foregroundColor(.gray) Text("Accent color is used to indicate to the user that a control can be interacted with. The default accent color is blue.") .frame(maxWidth: .infinity).padding() .background(Color.purple).layoutPriority(1) .foregroundColor(.white) Button("Button with Default Accent Color", action: {}) Button("Button with Purple Accent Color", action: {}) .accentColor(.purple) // Change accent color Button(action: {}) { HStack { Image(systemName: "bag.fill.badge.plus") Text("Add to Cart") } } .accentColor(.purple) Text("Slider with Default Accent Color") Slider(value: $slider) Text("Slider with Purple Accent Color") Slider(value: $slider) .accentColor(.purple) // Change accent color }.font(.title) } } struct AccentColor_Intro_Previews: PreviewProvider { static var previews: some View { AccentColor_Intro() } }
import UIKit import Photos import MediaPlayer protocol selecte_Asset_FromGalleryDelegate: class{ func selected_Assets(phAsset : PHAsset) } class ChoosePostFromGalleryVC : UIViewController { enum AppendOrignalImage{ case AppendOrignal case None } //MARK:- variables //==================== var allPhotosResult : PHFetchResult<AnyObject>? var allMedia = [PHAsset]() weak var player : AVPlayer? weak var playerLayer : AVPlayerLayer? var selectedImage : [Int] = [] var longPressRecognizer : UITapGestureRecognizer? var selectionBegin = false var selectedSingleAsset : PHAsset? weak var imageCropper : GoToImageCropper? var selectedImages : [UIImage] = [] var selectedVideoUrl : AVURLAsset? var lastCretaionDate :Date? var scroll = true var lastContentOffset : CGFloat = 0.0 weak var delegate : selecte_Asset_FromGalleryDelegate? //MARK:- IBOutlets //===================== @IBOutlet weak var deselectedMediaButton: UIButton! @IBOutlet weak var topView: UIView! @IBOutlet weak var galleryCollectionView : UICollectionView! @IBOutlet weak var videoView: UIView! @IBOutlet weak var galleryImageView: UIImageView! @IBOutlet weak var topViewHeight: NSLayoutConstraint! @IBOutlet weak var playPauseButton: UIButton! @IBOutlet weak var galleryTableView: UITableView! @IBOutlet weak var tableBackView: UIView! deinit { self.removeObservers() } //MARK:- view life cycle //======================= override func viewDidLoad() { super.viewDidLoad() self.setUpSubView() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationItem.hidesBackButton = false navigationController?.setNavigationBarHidden(false, animated: true) self.addObserVers() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) if let _ = self.player{ self.player?.seek(to: kCMTimeZero) self.pauseVideo() } self.removeObservers() } override func viewDidLayoutSubviews(){ super.viewDidLayoutSubviews() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() CommonFunctions.removeChahe() CommonFunctions.clearTempDirectory() } @IBAction func deselectedButtonTapped(_ sender: UIButton) { self.selectedImage.removeAll() self.selectedImages.removeAll() self.selectionBegin = false // self.galleryCollectionView.reloadData() self.showHideSelectDeselectButton() self.deselectedMediaButton.isHidden = true } @IBAction func playPauseButtontapped(_ sender: UIButton) { self.playPauseButton.isSelected = !self.playPauseButton.isSelected self.player?.timeControlStatus == AVPlayerTimeControlStatus.playing ? self.pauseVideo() : self.playVideo() } } //MARK:- privatefunctions //======================== fileprivate extension ChoosePostFromGalleryVC{ func setUpSubView(){ self.deselectedMediaButton.isHidden = true self.galleryImageView.contentMode = .scaleAspectFit self.topView.clipsToBounds = true self.playPauseButton.setImage(#imageLiteral(resourceName: "icPostVideoPlay"), for: .normal) self.getAllMedia() self.longPressRecognizer = UITapGestureRecognizer(target: self, action: #selector(ChoosePostFromGalleryVC.longPressOnImage)) self.tableBackView.frame = CGRect(x: 0, y: 0, width: Global.screenWidth, height: self.view.frame.height + Global.screenWidth) self.galleryTableView.contentSize = CGSize(width: Global.screenWidth, height: self.tableBackView.frame.size.height) self.topViewHeight.constant = Global.screenWidth self.galleryCollectionView.bounces = false self.galleryTableView.delegate = self self.galleryTableView.dataSource = self self.galleryTableView.showsVerticalScrollIndicator = false self.galleryCollectionView.showsVerticalScrollIndicator = false } //MARK:- get all media //======================= func getAllMedia() { self.allPhotosResult = PHFetchResult() let fetchOptions = PHFetchOptions() fetchOptions.fetchLimit = 15 fetchOptions.sortDescriptors = [NSSortDescriptor(key:"creationDate", ascending: false)] if let date = self.lastCretaionDate{ fetchOptions.predicate = NSPredicate(format: "(creationDate < %@)", date as CVarArg) } guard let result = PHAsset.fetchAssets(with: fetchOptions) as? PHFetchResult<AnyObject> else { return } self.allPhotosResult = result if self.allPhotosResult!.count > 0{ if let photo = self.allPhotosResult?.object(at: self.allPhotosResult!.count - 1) as? PHAsset{ print(photo) if let date = photo.creationDate{ lastCretaionDate = date } } } if let _ = self.lastCretaionDate{ }else{ self.allMedia.removeAll(keepingCapacity: false) } for i in 0..<self.allPhotosResult!.count{ if let photo = self.allPhotosResult?.object(at: i) as? PHAsset{ self.allMedia.append(photo) } } self.galleryCollectionView.delegate = self self.galleryCollectionView.dataSource = self self.galleryCollectionView.reloadData() if self.allPhotosResult!.count > 0 { if self.allMedia.count <= 15{ self.displayImageOrVideoOnTopView(indexPath: IndexPath(item: 0, section: 0),isAppend: false) } } } @objc func nextButtonTapped(){ if self.selectedSingleAsset?.mediaType == .image{ self.imageCropper?.goToImageCropper(image: self.galleryImageView.image!) }else{ if let url = self.selectedVideoUrl{ self.imageCropper?.takeVideoToCaptionVc(url: url) } } } } //MARK:- Dispaly views on top extension ChoosePostFromGalleryVC { //MARK:- display image or video on top view //============================================= func displayImageOrVideoOnTopView(indexPath : IndexPath,isAppend : Bool){ let asset = self.allMedia[indexPath.item] self.selectedSingleAsset = asset if asset.mediaType == .image { self.playPauseButton.isHidden = true self.displayImageOnTopView(asset: asset, isAppend: isAppend) }else if asset.mediaType == .video{ self.playPauseButton.isHidden = false self.displayVideoOnTopView(asset: asset) } } //MARK:- Display image on top view //=================================== func displayImageOnTopView(asset : PHAsset,isAppend:Bool){ self.galleryImageView.isHidden = false self.videoView.isHidden = true let imgManager = PHImageManager.default() let reqOptions = PHImageRequestOptions() DispatchQueue.global(qos: .background).async { let imageSize = CGSize(width: asset.pixelWidth, height: asset.pixelHeight) var appendOrignal = AppendOrignalImage.None imgManager.requestImage(for: asset , targetSize: imageSize, contentMode: PHImageContentMode.default, options: reqOptions, resultHandler: { (image, _) in DispatchQueue.main.async { guard let img = image else{ return } if appendOrignal == AppendOrignalImage.AppendOrignal{ self.galleryImageView.image = image Global.print_Debug("isAppend...\(isAppend)") if isAppend{ self.selectedImages.append(self.galleryImageView.image!) Global.print_Debug(self.selectedImage.count) Global.print_Debug(self.selectedImages.count) } } appendOrignal = AppendOrignalImage.AppendOrignal } }) } self.player?.pause() self.player = nil self.playerLayer = nil } //MARK:- display video on top view //===================================== func displayVideoOnTopView(asset : PHAsset){ self.selectedImage.removeAll() self.selectedImages.removeAll() self.selectionBegin = false //self.galleryCollectionView.reloadData() self.deselectedMediaButton.isHidden = true self.showHideSelectDeselectButton() PHCachingImageManager().requestAVAsset(forVideo: asset,options: nil, resultHandler: {(asset, audioMix, info) in DispatchQueue.main.async{ self.player?.seek(to: kCMTimeZero) if let asset = asset as? AVURLAsset{ self.setUpVideo(videoasset: asset) CommonFunctions.delayy(delay: 0.1, closure: { // self.galleryCollectionView.reloadData() self.showHideSelectDeselectButton() }) } } }) self.galleryImageView.isHidden = true self.videoView.isHidden = false } func showHideSelectDeselectButton(){ let visibleItem = self.galleryCollectionView.indexPathsForVisibleItems for indexPath in visibleItem{ guard let cell = self.galleryCollectionView.cellForItem(at: indexPath) as? GalleryCell else { return } cell.showHideDeselectButton(isSelectionBegin: self.selectionBegin, selectedImage: self.selectedImage, item: indexPath.item) } } } //MARK:- Manage player //======================== extension ChoosePostFromGalleryVC{ //MARK:- player didplay to end time //================================== @objc func playerItemDidPlayToEndTime(sender : Notification){ self.player?.seek(to: kCMTimeZero) self.pauseVideo() } //MARK:- Play video when tapped //================================== func setUpVideo(videoasset : AVURLAsset) { if let _ = self.player{ self.setVideo(url: videoasset.url) self.selectedVideoUrl = videoasset }else{ self.player = AVPlayer(url: videoasset.url) self.selectedVideoUrl = videoasset self.playerLayer = AVPlayerLayer(player: player) self.playerLayer?.frame = CGRect(x: 0, y: 0, width: Global.screenWidth, height: Global.screenWidth) self.view.bringSubview(toFront: self.videoView) self.videoView.clipsToBounds = true self.playerLayer?.videoGravity = AVLayerVideoGravity.resizeAspectFill self.videoView.layer.addSublayer(self.playerLayer!) // self.playVideo() } } func setVideo(url : URL) { let asset = AVAsset(url: url) let keys = ["playable","tracks","duration"] asset.loadValuesAsynchronously(forKeys: keys) { let playerItem = AVPlayerItem(asset: asset) self.player?.replaceCurrentItem(with: playerItem) self.playVideo() } } func playVideo(){ DispatchQueue.main.async { self.player?.play() //self.playPauseButton.setImageForAllStates(#imageLiteral(resourceName: "pauseButton")) } // self.playPauseButton.isHidden = true } func pauseVideo(){ self.player?.pause() //self.playPauseButton.setImageForAllStates(#imageLiteral(resourceName: "playButton")) } //MARK:- Add observers //===================== func addObserVers(){ NotificationCenter.default.addObserver(self, selector: #selector(playerItemDidPlayToEndTime), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil) } //MARK:- remove observers //============================== func removeObservers(){ NotificationCenter.default.removeObserver(self, name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil) } } //MARK:- collectionview delegate and datasource //================================================ extension ChoosePostFromGalleryVC : UICollectionViewDelegate , UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{ func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.allMedia.count } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout,minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return 0.8 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return 0.8 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: (Global.screenWidth / 3) - 0.8 , height: (Global.screenWidth / 3) - 0.8 ) } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "GalleryCell", for: indexPath) as! GalleryCell //dequeueReusableCell(withReuseIdentifier: GalleryCell.self, for: indexPath) let photo = self.allMedia[indexPath.item] let long = UILongPressGestureRecognizer(target: self, action: #selector(ChoosePostFromGalleryVC.longPressOnImage)) long.minimumPressDuration = 1.0 cell.playImageView.isHidden = photo.mediaType == .image if photo.mediaType == .image{ cell.playImageView.isHidden = true cell.setPhoto(item: photo) cell.galleryImageView.addGestureRecognizer(long) cell.showHideDeselectButton(isSelectionBegin: self.selectionBegin, selectedImage: self.selectedImage, item: indexPath.item) }else if photo.mediaType == .video{ cell.playImageView.isHidden = false cell.setVideo(item: photo) cell.deselectButton.isHidden = true cell.galleryImageView.removeGestureRecognizer(long) } return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { // if self.selectionBegin{ // if self.selectedImage.contains(indexPath.item){ // let index = self.selectedImage.index(of: indexPath.item) // self.selectedImage.remove(at: index!) // self.selectedImages.remove(at: index!) // self.displayImageOrVideoOnTopView(indexPath: indexPath, isAppend: false) // }else{ // // if self.selectedImage.count < 3{ // self.selectedImage.append(indexPath.item) // self.displayImageOrVideoOnTopView(indexPath: indexPath, isAppend: true) // }else{ // //showToastMessage(K_MAXIMUM_PHOTOS_SELECT.localized) // } // } // // self.galleryCollectionView.reloadItems(at: [IndexPath(item: indexPath.item, section: 0)]) // // }else{ let photo = self.allMedia[indexPath.item] self.delegate?.selected_Assets(phAsset: photo) self.galleryTableView.setContentOffset( CGPoint(x: 0, y: 0), animated: true) self.displayImageOrVideoOnTopView(indexPath: indexPath, isAppend: false) // } // if self.selectedImage.isEmpty{ // // self.deselectedMediaButton.isHidden = true // }else{ // self.deselectedMediaButton.isHidden = false // // } } func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { } //MARK:- Long press on asset @objc func longPressOnImage(sender : UILongPressGestureRecognizer){ if !self.selectionBegin{ let tapLocation = sender.location(in: self.galleryCollectionView) let indexPath : IndexPath = self.galleryCollectionView.indexPathForItem(at: tapLocation)! self.selectionBegin = true let asset = self.allMedia[indexPath.item] if !self.selectedImage.contains(indexPath.item) && asset.mediaType == .image{ self.selectedImage.removeAll() self.selectedImages.removeAll() self.selectedImage.append(indexPath.item) self.displayImageOrVideoOnTopView(indexPath: indexPath,isAppend: true) //self.galleryCollectionView.reloadData() self.showHideSelectDeselectButton() } } if self.selectedImage.isEmpty{ self.deselectedMediaButton.isHidden = true }else{ self.deselectedMediaButton.isHidden = false } } } extension ChoosePostFromGalleryVC : UIScrollViewDelegate{ func scrollViewDidScroll(_ scrollView: UIScrollView) { if scrollView == self.galleryCollectionView{ Global.print_Debug("table...\(scrollView.contentOffset)") } } func scrollView(_ scrollView: MXScrollView, shouldScrollWithSubView subView: UIScrollView) -> Bool { return true } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { let endScrolling = scrollView.contentOffset.y + scrollView.contentSize.height if endScrolling > scrollView.contentSize.height { self.getAllMedia() } } // func scrollViewShouldScrollToTop(_ scrollView: UIScrollView) -> Bool { // // if scrollView != self.galleryCollectionView{ // return true // }else{ // // return false // } // } } class GalleryCell : UICollectionViewCell{ @IBOutlet weak var galleryImageView: UIImageView! @IBOutlet weak var overLayView: UIView! @IBOutlet weak var deselectButton: UIButton! @IBOutlet weak var playImageView: UIImageView! let imgManager = PHImageManager.default() override func prepareForReuse() { galleryImageView.image = nil } override func awakeFromNib() { self.galleryImageView.contentMode = .scaleAspectFill self.galleryImageView.clipsToBounds = true self.overLayView.isHidden = true self.galleryImageView.isUserInteractionEnabled = true self.deselectButton.isUserInteractionEnabled = false } //MARK:- hide show deselecte button //====================================== func showHideDeselectButton(isSelectionBegin : Bool,selectedImage : [Int] , item : Int){ if isSelectionBegin{ self.deselectButton.isHidden = false if selectedImage.contains(item){ //self.deselectButton.setImageForAllStates(#imageLiteral(resourceName: "ic_signup_select")) }else{ //self.deselectButton.setImageForAllStates(#imageLiteral(resourceName: "deselectCircle")) } }else{ self.deselectButton.isHidden = true } } //MARK:- set photo to image view //=================================== func setPhoto(item : PHAsset){ let h:CGFloat = (Global.screenWidth / 3) - 0.8 let size = CGSize(width: h, height: h) self.imgManager.requestImage(for: item,targetSize: size, contentMode: .aspectFill,options: nil) {result, info in self.galleryImageView.image = result } } //MARK:- set video to image view //=================================== func setVideo(item : PHAsset){ DispatchQueue.global(qos: .background).async { PHCachingImageManager().requestAVAsset(forVideo: item,options: nil, resultHandler: {(asset, audioMix, info) in if let video = asset as? AVURLAsset{ let assetImgGenerate : AVAssetImageGenerator! let ast = AVAsset(url: video.url) assetImgGenerate = AVAssetImageGenerator(asset: ast) assetImgGenerate.appliesPreferredTrackTransform = true let time : CMTime = CMTimeMakeWithSeconds(1, Int32(NSEC_PER_SEC)) if let cgImage = try? assetImgGenerate.copyCGImage(at: time, actualTime: nil) { let thumbImage = UIImage(cgImage: cgImage) DispatchQueue.main.async { self.galleryImageView.image = thumbImage } } } }) } } } extension ChoosePostFromGalleryVC : UITableViewDelegate , UITableViewDataSource{ func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: AppClassID.AccountManagementCell.cellID) as? AccountManagementCell else { fatalError("AccountManagementCell not found ") } return cell } }
// // RecentSearches.swift // WynkImageSearch // // Created by Aashima Anand on 12/07/20. // Copyright © 2020 personal. All rights reserved. // import Foundation /// Reverse Queue final class RecentSearches { static let shared: RecentSearches = RecentSearches() private var elements: [String] = [] private init() { if let value = AppUserDefaults.value(forKey: .recentSearches) as? [String] { elements = value } } /// adds element to queue func enqueue(_ value: String) { if let index = elements.firstIndex(where: { $0 == value }) { bringToFirst(value, currentIndex: index) } else { if elements.count == 10 { let _ = dequeue() } elements.insert(value, at: 0) } } /// removes last element fron queue if overload limit has reached private func dequeue() -> String? { guard !elements.isEmpty else { return nil } return elements.removeLast() } /// points to the MRU element in the queue private var head: String? { return elements.first } /// points to the LRU element in the queue private var tail: String? { return elements.last } /// brings the recently used element on the top private func bringToFirst(_ value: String, currentIndex: Int) { elements.remove(at: currentIndex) elements.insert(value, at: 0) } /// return all the elements func searches() -> [String] { return elements } }
// // QTRomanNumerals.swift // QTRomanNumeralExample // // Created by Michael Ginn on 7/17/15. // Copyright (c) 2015 Michael Ginn. All rights reserved. // import UIKit class QTRomanNumerals: NSObject { static let conversions = [1: "I", 4: "IV", 5: "V", 9: "IX", 10: "X", 40: "XL", 50: "L", 90: "XC", 100: "C", 400: "CD", 500: "D", 900: "CM", 1000: "M" ] static let numbers = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1] class func convertToRomanNum(var decimalNum:Int)->String{ var finalString = "" //will use to build Roman num string while decimalNum > 0{ for number in numbers{ if decimalNum >= number{ decimalNum = decimalNum - number finalString += conversions[number]! break } } } return finalString } }
import Foundation struct OlympusSessionResponse: Codable { let user: User let provider: OlympusContentProvider let availableProviders: [OlympusContentProvider] let backingType: String let roles: [Role] let unverifiedRoles: [Role] // let featureFlags: [String] let agreeToTerms: Bool let modules: [ITCModule] let helpLinks: [HelpLink] }
// // CityCell.swift // Project // // Created by 张凯强 on 2018/3/7. // Copyright © 2018年 HHCSZGD. All rights reserved. // import UIKit class CityCell: UITableViewCell { override func awakeFromNib() { super.awakeFromNib() self.selectionStyle = UITableViewCellSelectionStyle.none // Initialization code } @IBOutlet var myTitlelabel: UILabel! @IBOutlet var rightImageView: UIImageView! var model: AreaModel? { didSet{ self.myTitlelabel.text = model?.name if model?.isSelected ?? false { self.rightImageView.image = UIImage.init(named: "multiselectselected") }else { self.rightImageView.image = UIImage.init(named: "checkboxisnotselected") } } } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
// // File.swift // OnlineStore // // Created by Stanislav Grigorov on 26.12.17. // Copyright © 2017 Stanislav Grigorov. All rights reserved. // import Foundation
// // book.swift // My Reads // // Created by Digital Media on 1/9/18. // Copyright © 2018 Chase Smith. All rights reserved. // import Foundation import UIKit import CoreData // This class represents the screen that the user sees when they are viewing/adding/editing // a book. class BookViewController: UIViewController { let managedContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext var book: Book! var delegate: AddBookDelegate? @IBOutlet weak var titleTextField: UITextField! // title field var @IBOutlet weak var authorTextField: UITextField! // author field var @IBOutlet weak var rankingsSwitch: UISwitch! // rankings switch var @IBOutlet weak var myBooksSwitch: UISwitch! // my books switch var @IBOutlet weak var readBooksSwitch: UISwitch! // read books var @IBOutlet weak var futureReadsSwitch: UISwitch! // to read switch @IBOutlet weak var editBookButton: UIButton! // edit book button var override func viewDidLoad() { super.viewDidLoad() // set book's author field to the current book's author authorTextField.text = book.author // set book's title field to the current book title titleTextField.text = book.title // set switch titles to saved/current set states of off/on readBooksSwitch.isOn = book.readBooks futureReadsSwitch.isOn = book.futureReads rankingsSwitch.isOn = book.rankings myBooksSwitch.isOn = book.myBooks } // Edit book function @IBAction func editBook(sender: UIButton) { // if the title is not blank and a book category is selected if titleTextField.text! != "" && (readBooksSwitch.isOn || rankingsSwitch.isOn || futureReadsSwitch.isOn || myBooksSwitch.isOn) { // book's author is set to text of author field book.author = authorTextField.text // book title is set to text of of title field book.title = titleTextField.text // all category switches are set to the current set values book.readBooks = readBooksSwitch.isOn book.futureReads = futureReadsSwitch.isOn book.rankings = rankingsSwitch.isOn book.myBooks = myBooksSwitch.isOn do { try managedContext.save() } catch { print(error) } delegate?.updateBook(book: book) dismiss(animated: true, completion: nil) } } // Function to send user back to the previous book list. @IBAction func backToBookList(sender: UIButton) { dismiss(animated: true, completion: nil) } // Function for remove book button. @IBAction func removeBook(sender: UIButton) { managedContext.delete(book) do { try managedContext.save() } catch { print(error) } delegate?.removeBook(book: book) dismiss(animated: true, completion: nil) } } extension BookViewController: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } }
// // DeliveryVC.swift // HelpingHand // // Created by amota511 on 12/30/17. // Copyright © 2017 Aaron Motayne. All rights reserved. // import UIKit class DeliveryVC: UICollectionViewController { override func viewDidLoad() { super.viewDidLoad() self.collectionView?.delegate = self self.view?.frame = CGRect(x: 0, y: 20, width: self.view.frame.width, height: self.view.frame.height) self.collectionView!.register(DeliveryItemCell.self, forCellWithReuseIdentifier: "DeliveryItemCell") //self.collectionView!.register(HeaderView.self, forCellWithReuseIdentifier: "HeaderView") self.collectionView?.register(HeaderView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "HeaderView") self.collectionView!.isScrollEnabled = true //self.collectionView!.backgroundColor = UIColor(r: 85, g: 185, b: 85) self.collectionView!.showsVerticalScrollIndicator = false self.collectionView!.allowsSelection = true self.collectionView!.alwaysBounceVertical = true self.collectionView!.bounces = true let FrigeLayout: UICollectionViewFlowLayout = UICollectionViewFlowLayout() FrigeLayout.sectionInset = UIEdgeInsets(top: 5, left: 10, bottom: 0, right: 10) FrigeLayout.itemSize = CGSize(width: view.frame.width * (1/3), height: view.frame.height * (1/3) * (3/4)) self.collectionView!.collectionViewLayout = FrigeLayout //self.collectionView!.collectionViewLayout.section //sectionHeadersPinToVisibleBounds = true } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "DeliveryItemCell", for: indexPath) as! DeliveryItemCell //cell.bounds = CGRect(x: 0, y: 0, width: 100, height: 100) cell.backgroundColor = UIColor.blue cell.clipsToBounds = true cell.layer.cornerRadius = 5 return cell } override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { print(indexPath.row) } override func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 10 } override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { let header = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "HeaderView", for: indexPath) as! HeaderView header.backgroundColor = UIColor.green header.frame = CGRect(origin: CGPoint(x:0, y:0), size: CGSize(width: 50, height: 50)) return header } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize { return CGSize(width:view.frame.size.width, height:100.0) } }
// // Problem3ViewController.swift // Assignment2 // // Created by stephen chang on 6/28/16. // Copyright © 2016 Stephen Chang. All rights reserved. // //import Foundation import UIKit class Problem3ViewController: UIViewController { //MARK: Properties @IBOutlet weak var textViewProblem3: UITextView! @IBAction func runButtonProblem3(sender: UIButton) { let NumColumns: Int = 10 let NumRows: Int = 10 var numOfLivingCellsInBefore: Int = 0 var numOfLivingCellsInAfter: Int = 0 //create before and after arrays var before = Array(count:NumColumns, repeatedValue: Array(count:NumRows, repeatedValue:false)) var afterStep = Array(count:NumColumns, repeatedValue: Array(count:NumRows, repeatedValue:false)) //set a random true or false value for each cell in the before array for y in 0..<NumColumns{//iterate 0-9 for x in 0..<NumRows{//iterate 0-9 // if arc4random_uniform generates 1, then it will set cell to true if arc4random_uniform(3) == 1 { before[y][x] = true numOfLivingCellsInBefore+=1 } //print(before[y][x]) //print entire array to see if random variables generated correctly } } //step checks neighbors and returns a 2D array of bools for x in 0..<step(before).count{//iterate 0-size of input array for y in 0..<afterStep[x].count{//iterate 0-9 if step(before)[x][y] == true{ numOfLivingCellsInAfter+=1 } } } //send results to the text box textViewProblem3.text="Run button pressed \nLiving cells in Before: \(numOfLivingCellsInBefore) \nLiving cells in After: \(numOfLivingCellsInAfter)" } override func viewDidLoad() { self.title = "Problem 3" } }
// // ViewController_1.swift // kamakuraMap // // Created by Yoshiki Kishimoto on 2018/04/28. // Copyright © 2018年 Yoshiki Kishimoto. All rights reserved. // import UIKit class SecondViewController: UIViewController { var number :Int = 0 @IBAction func kama() { number = 1 } @IBAction func hase() { number = 2 } @IBAction func eno(_ sender: Any) { number = 3 } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func toNextView() { let viewControler = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "map") as! MapViewController viewControler.num = self.number //ViewController self.navigationController?.pushViewController(viewControler, animated: true) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
// // SongInfoSongInfoInteractor.swift // SongGuesser // // Created by Denis Zhukoborsky on 02/08/2019. // Copyright © 2019 denis.zhukoborsky. All rights reserved. // import Foundation class SongInfoInteractor: SongInfoInteractorProtocol { weak var presenter: SongInfoPresenterProtocol! required init(presenter: SongInfoPresenterProtocol) { self.presenter = presenter } }
// // ViewController.swift // GeoFencing // // Created by Jorge on 13/12/17. // Copyright © 2017 kaleido. All rights reserved. // import UIKit import MapKit import CoreLocation import UserNotifications struct Region { let identifier : String let latitud : Double let longitud : Double let radio : Double } class ViewController: UIViewController { @IBOutlet weak var mapView: MKMapView! let locationManager = CLLocationManager() var regionsArray : [Region] = [] override func viewDidLoad() { super.viewDidLoad() updateRegions() UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in } locationManager.delegate = self locationManager.requestAlwaysAuthorization() locationManager.desiredAccuracy = kCLLocationAccuracyBest addRegions() locationManager.startUpdatingLocation() print(locationManager.monitoredRegions) } func updateRegions(){ let newRegion = Region(identifier: "Starbucks", latitud: 19.427845, longitud: -99.168495 , radio: 260.0) regionsArray.append(newRegion) /*newRegion = Region(identifier: "Garabatos cafe", latitud: 19.427314, longitud: -99.165898, radio: 24.0) regionsArray.append(newRegion) newRegion = Region(identifier: "Oxxo", latitud: 19.425731, longitud: -99.165917, radio: 65.0) regionsArray.append(newRegion) newRegion = Region(identifier: "Panaderia estocolmo", latitud: 19.426601, longitud: -99.166236, radio: 22.0) regionsArray.append(newRegion)*/ let newRegionn = Region(identifier: "MIDE", latitud: 19.435468, longitud: -99.138420, radio: 200.0) regionsArray.append(newRegionn) let hotelRegion = Region(identifier: "Hotel", latitud: 19.425142, longitud: -99.164289, radio: 200.0) regionsArray.append(hotelRegion) } func addRegions(){ //guard let longPress = sender as? UILongPressGestureRecognizer else { return } //let touchLocation = longPress.location(in: mapView) //let coordinate = mapView.convert(touchLocation, toCoordinateFrom: mapView) if CLLocationManager.isMonitoringAvailable(for: CLCircularRegion.self) { for reg in regionsArray { let centerCorrdinate = CLLocationCoordinate2D(latitude: reg.latitud, longitude: reg.longitud) let region = CLCircularRegion(center: centerCorrdinate, radius: reg.radio, identifier: reg.identifier) //mapView.removeOverlays(mapView.overlays) region.notifyOnEntry = true region.notifyOnExit = true locationManager.startMonitoring(for: region) let circle = MKCircle(center: centerCorrdinate, radius: reg.radio) mapView.add(circle) print("SIIIIIIII") } } else { print("NO SE PUEDEEEEE") } } func showAlert(title: String, message: String) { let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) let action = UIAlertAction(title: "OK", style: .default, handler: nil) alert.addAction(action) present(alert, animated: true, completion: nil) } func showNotification(title: String, message: String) { let content = UNMutableNotificationContent() content.title = title content.body = message content.badge = 1 content.sound = .default() let request = UNNotificationRequest(identifier: "notif", content: content, trigger: nil) UNUserNotificationCenter.current().add(request, withCompletionHandler: nil) } } extension ViewController: CLLocationManagerDelegate { func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { locationManager.stopUpdatingLocation() mapView.showsUserLocation = true } func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) { if let region = region as? CLCircularRegion{ print("Entraste a una region") let title = region.identifier let message = "You Entered the Region" showAlert(title: title, message: message) showNotification(title: title, message: message) }else{ print("no es una region") } } func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) { let title = region.identifier let message = "You Left the Region" showAlert(title: title, message: message) showNotification(title: title, message: message) } } extension ViewController: MKMapViewDelegate { func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer { guard let circleOverlay = overlay as? MKCircle else { return MKOverlayRenderer() } let circleRenderer = MKCircleRenderer(circle: circleOverlay) circleRenderer.strokeColor = .red circleRenderer.fillColor = .red circleRenderer.alpha = 0.4 return circleRenderer } }
// // COBarItem.swift // CoAssets-Agent // // Created by Linh NGUYEN on 12/12/15. // Copyright © 2015 Nikmesoft Ltd. All rights reserved. // import UIKit @objc protocol COBarItemViewDelegate { func barItemView(barItemView: COBarItemView, didSelect: Bool) } class COBarItemView: UIView { var backgroundNormalColor: UIColor = UIColor.whiteColor() var backgroundSelectedColor: UIColor = UIColor.lightGrayColor() var textNormalColor: UIColor = UIColor.blackColor() var textSelectedColor: UIColor = UIColor.whiteColor() weak var leftSeperatorView: UIView? weak var rightSeperatorView: UIView? weak var titleLabel: UILabel? weak var delegate: COBarItemViewDelegate! var selected: Bool = false { didSet { updateUI() } } private var didSetupUI: Bool = false var item: COBarItem? { didSet { titleLabel?.text = item?.title } } var index: Int? convenience init(item: COBarItem, index: Int, selected: Bool = false) { self.init() self.item = item self.index = index self.selected = selected } override func layoutSubviews() { super.layoutSubviews() if !didSetupUI { setupUI() didSetupUI = true } } private func updateUI() { if selected { self.backgroundColor = backgroundSelectedColor self.titleLabel?.textColor = textSelectedColor } else { self.backgroundColor = backgroundNormalColor self.titleLabel?.textColor = textNormalColor } leftSeperatorView?.hidden = selected rightSeperatorView?.hidden = selected } private func setupTitleLabel() { let titleLabel = UILabel() titleLabel.translatesAutoresizingMaskIntoConstraints = false titleLabel.text = item?.title titleLabel.font = UIFont(name: AppDefine.AppFontName.COAvenirRoman, size: 12.51*AppDefine.ScreenSize.ScreenScale) self.addSubview(titleLabel) let centerX = NSLayoutConstraint(item: titleLabel, attribute: .CenterX, relatedBy: .Equal, toItem: self, attribute: .CenterX, multiplier: 1.0, constant: 0.0) let centerY = NSLayoutConstraint(item: titleLabel, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1.0, constant: 0.0) self.addConstraints([centerX, centerY]) self.titleLabel = titleLabel } private func setupUI() { setupTitleLabel() updateUI() let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("actionTap:")) self.addGestureRecognizer(tapGestureRecognizer) } func actionTap(sender: UITapGestureRecognizer) { delegate.barItemView(self, didSelect: true) } }
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" let a = true; let b: Bool = false; if a { print("aaa\naaa"); } if b { print("bbbb"); } /// swift中没有非 0 及真的概念 //let i = 1 //if i { // // this example will not compile, and will report an error //} let i = 1 if i == 1 { // }
// // UserInfoViewController.swift // AboutMe // // Created by Евгений Панченко on 01.09.2021. // import UIKit class UserInfoViewController: UIViewController { var user: User! override func viewDidLoad() { super.viewDidLoad() title = user.person.fullName } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard let imageVC = segue.destination as? ImageViewController else { return } imageVC.user = user } }
// // RealmModel.swift // VeloGorod // // Created by Evgeny Knyazev on 21/07/2019. // Copyright © 2019 Evgeny Knyazev. All rights reserved. // import Foundation import RealmSwift class Point: Object { @objc dynamic var id = 0 @objc dynamic var latitude = 0.0 @objc dynamic var longitude = 0.0 @objc dynamic var type = 0 override static func primaryKey() -> String? { return "id" } } class Route: Object { @objc dynamic var id = 0 @objc dynamic var length = 0.0 @objc dynamic var cost = 0.0 @objc dynamic var priority = 0.0 @objc dynamic var traffic = 0.0 @objc dynamic var isEnable = true var points = List<Point>() override static func primaryKey() -> String? { return "id" } } class EcologicDB: Object { @objc dynamic var name: String = "Экология" @objc dynamic var value: Double = 0.0 override static func primaryKey() -> String? { return "name" } } class TrafficJamDB: Object { @objc dynamic var name: String = "Пробки" @objc dynamic var value: Double = 0.0 override static func primaryKey() -> String? { return "name" } } class CostDB: Object { @objc dynamic var name: String = "Стоимость" @objc dynamic var value: Double = 0.0 override static func primaryKey() -> String? { return "name" } } class TrafficDB: Object { @objc dynamic var name: String = "Человекопоток" @objc dynamic var value: Double = 0.0 override static func primaryKey() -> String? { return "name" } } class PriorityDB: Object { @objc dynamic var name: String = "Приоритет" @objc dynamic var value: Double = 0.0 override static func primaryKey() -> String? { return "name" } } //class Total: Object { // // @objc dynamic var totalString: String { // var string = "" // if let routes = realm?.objects(Route.self).filter("isEnable = %@", true) { // let totalCount = routes.count // var totalLength = 0.0 // var totalCost = 0.0 // var totalTraffic = 0.0 // for route in routes { // totalLength += route.length // totalCost += route.cost // totalTraffic += route.traffic // } // string = "\(totalCount) маршрутов, потенциальным трафиком \(totalTraffic) чел., протяженностью \(totalLength) км., оценочной стоимостью \(totalCost) тыс. рублей." // } // return string // } // //}
// // DayEightTests.swift // Test // // Created by Shawn Veader on 12/8/18. // Copyright © 2018 Shawn Veader. All rights reserved. // import XCTest class DayEightTests: XCTestCase { let input = "2 3 0 3 10 11 12 1 1 0 1 99 2 1 1 2" func testTimeStreamHeader() { let day = DayEight() var stream = DayEight.TreeStream(stream: day.parse(input: input)) let header = stream.pullHeader() XCTAssertEqual(2, header?.children) XCTAssertEqual(3, header?.metadata) XCTAssertEqual(14, stream.stream.count) } func testTimeStreamTrailingMeta() { let day = DayEight() var stream = DayEight.TreeStream(stream: day.parse(input: input)) let metadata = stream.pullTrailingMetadata(length: 3) XCTAssertEqual(3, metadata?.count) XCTAssertEqual([1, 1, 2], metadata) XCTAssertEqual(13, stream.stream.count) } func testTimeStreamMeta() { let day = DayEight() var stream = DayEight.TreeStream(stream: day.parse(input: input)) _ = stream.pullHeader() let metadata = stream.pullMetadata(length: 4) XCTAssertEqual(4, metadata?.count) XCTAssertEqual([0, 3, 10, 11], metadata) XCTAssertEqual(10, stream.stream.count) } func testTreeConstruction() { let day = DayEight() let stream = DayEight.TreeStream(stream: day.parse(input: input)) let tree = day.constructTree(stream: stream) XCTAssertNotNil(tree) let root = tree!.rootNode! XCTAssertEqual(2, root.nodes.count) XCTAssertEqual([1, 1, 2], root.metadata) let firstChild = root.nodes.first! XCTAssertEqual(0, firstChild.nodes.count) let secondChild = root.nodes.last! XCTAssertEqual(1, secondChild.nodes.count) } func testMetadataSum() { let day = DayEight() let stream = DayEight.TreeStream(stream: day.parse(input: input)) let tree = day.constructTree(stream: stream) let root = tree!.rootNode! XCTAssertEqual(138, day.metadataSum(for: root)) } func testNodeValueSum() { let day = DayEight() let stream = DayEight.TreeStream(stream: day.parse(input: input)) let tree = day.constructTree(stream: stream) let root = tree!.rootNode! XCTAssertEqual(66, day.sumNodeValue(for: root)) } func testNodeConsructionNoChildren() { let day = DayEight() let stream = DayEight.TreeStream(stream: [0, 3, 10, 11, 12]) let response = day.constructNodes(stream: stream) XCTAssertNotNil(response) XCTAssertEqual(true, response?.remainder.isEmpty) guard let node = response?.node else { XCTFail("Failed to get child node") return } XCTAssertEqual(0, node.header.children) XCTAssertEqual(3, node.header.metadata) XCTAssertEqual([10, 11, 12], node.metadata) XCTAssertEqual(0, node.nodes.count) } func testNodeConstructionWithChildren() { let day = DayEight() let stream = DayEight.TreeStream(stream: [1, 1, 0, 1, 99, 2]) let response = day.constructNodes(stream: stream) XCTAssertNotNil(response) XCTAssertEqual(true, response?.remainder.isEmpty) guard let node = response?.node else { XCTFail("Failed to get child node") return } XCTAssertEqual(1, node.header.children) XCTAssertEqual(1, node.header.metadata) XCTAssertEqual([2], node.metadata) XCTAssertEqual(1, node.nodes.count) guard let childNode = node.nodes.first else { XCTFail("Failed to get child's child node") return } XCTAssertEqual(0, childNode.header.children) XCTAssertEqual(1, childNode.header.metadata) XCTAssertEqual([99], childNode.metadata) } }
// // ScrollHorizontalView.swift // Basics // // Created by Venkatnarayansetty, Badarinath on 11/3/19. // Copyright © 2019 Badarinath Venkatnarayansetty. All rights reserved. // import Foundation import SwiftUI struct ScrollHorizontalView: View { var colors = [Color.green, Color.blue, Color.purple, Color.pink, Color.yellow, Color.orange] var body: some View { GeometryReader { gr in VStack { Spacer() ScrollView(Axis.Set.horizontal, showsIndicators: false) { HStack { ForEach(self.colors, id: \.self) { item in RoundedRectangle(cornerRadius: 15) .fill(item) .frame(width: gr.size.width - 60, height: 200) } } } Spacer() }.padding() } } }
// // Created by Daniel Heredia on 2/27/18. // Copyright © 2018 Daniel Heredia. All rights reserved. // // 14.7.5 Useless Tile Packers // Useless Tile Packer, Inc., prides itself on efficiency. As their name suggests, they // aim to use less space than other companies. Their marketing department has tried to // convince management to change the name, believing that “useless” has other // connotations, but has thus far been unsuccessful. // Tiles to be packed are of uniform thickness and have a simple polygonal shape. For // each tile, a container is custom-built. The floor of the container is a convex // polygon that has the minimum possible space inside to hold the tile it is built for. import Foundation func calculateWastedAreaProportion(_ tile: Polygon) -> Double { let convexHullPolygon = tile.extractConvexHull() let tileArea = tile.area() let boxArea = convexHullPolygon.area() let proportion = tileArea / boxArea return 1.0 - proportion } var points = [Point]() // first case //points.append(Point(x: 0.0, y: 0.0)) //points.append(Point(x: 2.0, y: 0.0)) //points.append(Point(x: 2.0, y: 2.0)) //points.append(Point(x: 1.0, y: 1.0)) //points.append(Point(x: 0.0, y: 2.0)) // second case points.append(Point(x: 0.0, y: 0.0)) points.append(Point(x: 0.0, y: 2.0)) points.append(Point(x: 1.0, y: 3.0)) points.append(Point(x: 2.0, y: 2.0)) points.append(Point(x: 2.0, y: 0.0)) let tile = Polygon(points: points) let wastedProportion = calculateWastedAreaProportion(tile) print("Wasted space: \(wastedProportion * 100)%")
// // Tests.swift // TestCloudTests // // Created by Алексей Петров on 26.08.2020. // Copyright © 2020 Алексей Петров. All rights reserved. // import XCTest class Tests: XCTestCase { func testBodyClip() { let body = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean m" //100 symbols let comment = Comment(name: "Tester", email: "tester@me.com", body: body) XCTAssert(comment.bodyCount == nil) } func testBodyCount() { let body = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et ma" //140 symbols let comment = Comment(name: "Tester", email: "tester@me.com", body: body) XCTAssert(comment.bodyCount != nil, "body count must be") } func testBodyRightCount() { let body = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et ma" //140 symbols let comment = Comment(name: "Tester", email: "tester@me.com", body: body) XCTAssert(comment.bodyCount == body.count, "wrong count") } func testLimits() { let body = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis nat" //120 symbols let comment = Comment(name: "Tester", email: "tester@me.com", body: body) XCTAssert(comment.bodyCount == nil) } }
// // GTextureLoader.swift // roulette // // Created by C.H Lee on 22/08/2017. // Copyright © 2017 gz. All rights reserved. // import UIKit import Metal import CoreGraphics class GTextureLoader { static var shared: GTextureLoader = GTextureLoader() func dataForImage(image: UIImage) -> UnsafeMutablePointer<UInt8> { let imageRef = image.cgImage! // Create a suitable bitmap context for extracting the bits of the image let width = imageRef.width let height = imageRef.height let colorSpace = CGColorSpaceCreateDeviceRGB() let rawData = UnsafeMutablePointer<UInt8>.allocate(capacity: width * height * 4) let bytesPerPixel = 4 let bytesPerRow = bytesPerPixel * width let bitsPerComponent = 8 let bitmapInfo: UInt32 = CGImageAlphaInfo.premultipliedLast.rawValue | CGBitmapInfo.byteOrder32Big.rawValue let context = CGContext.init(data: rawData, width: width, height: height, bitsPerComponent: bitsPerComponent, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo)! context.translateBy(x: 0, y: CGFloat(height)) context.scaleBy(x: 1, y: -1) let imageRect = CGRect(x: 0, y: 0, width: width, height: height) context.draw(imageRef, in: imageRect) return rawData; } func generateMipmaps(texture: MTLTexture, onQueue queue: MTLCommandQueue) -> Void { let commandBuffer = queue.makeCommandBuffer() let blitEncoder = commandBuffer?.makeBlitCommandEncoder() blitEncoder?.generateMipmaps(for: texture) blitEncoder?.endEncoding() commandBuffer?.commit() // block commandBuffer?.waitUntilCompleted() } func texture2D(imageNamed name: String, mipmapped: Bool, queue: MTLCommandQueue) -> MTLTexture? { guard let image = UIImage(named: name) else { return nil } let imageSize = CGSize(width: image.size.width * image.scale, height: image.size.height * image.scale) let bytesPerPixel: UInt = 4 let bytesPerRow: UInt = bytesPerPixel * UInt(imageSize.width) let imageData = dataForImage(image: image) let textureDescriptor = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: .rgba8Unorm, width: Int(imageSize.width), height: Int(imageSize.height), mipmapped: mipmapped) guard let texture = queue.device.makeTexture(descriptor: textureDescriptor) else { free(imageData) return nil } texture.label = name let region = MTLRegionMake2D(0, 0, Int(imageSize.width), Int(imageSize.height)) texture.replace(region: region, mipmapLevel: 0, withBytes: imageData, bytesPerRow: Int(bytesPerRow)) free(imageData) if mipmapped == true { generateMipmaps(texture: texture, onQueue: queue) } return texture } }
// // FetchedTableViewDataSource.swift // ViperTest // // Created by Alex Golub on 10/30/16. // Copyright © 2016 Alex Golub. All rights reserved. // import UIKit import CoreData class FetchedTableViewDataSource: NSObject, UITableViewDataSource, NSFetchedResultsControllerDelegate { weak var tableView: UITableView! // MARK: TableView DataSource func numberOfSections(in tableView: UITableView) -> Int { return self.fetchedResultsController.sections?.count ?? 0 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let sectionInfo = self.fetchedResultsController.sections![section] return sectionInfo.numberOfObjects } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) let event = self.fetchedResultsController.object(at: indexPath) self.configureCell(cell, withEvent: event) return cell } // MARK: Actions func insertNewObject() { let context = self.fetchedResultsController.managedObjectContext let newEvent = Event(context: context) newEvent.timestamp = NSDate() do { try context.save() } catch { let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } func deleteObjectAt(indexPath: IndexPath) { let context = self.fetchedResultsController.managedObjectContext context.delete(self.fetchedResultsController.object(at: indexPath)) do { try context.save() } catch { let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } func eventAt(indexPath: IndexPath) -> Event { return self.fetchedResultsController.object(at: indexPath) } // MARK: Fetched Results Controller fileprivate var fetchedResultsController: NSFetchedResultsController<Event> { if _fetchedResultsController != nil { return _fetchedResultsController! } let fetchRequest: NSFetchRequest<Event> = Event.fetchRequest() fetchRequest.fetchBatchSize = 20 let sortDescriptor = NSSortDescriptor(key: "timestamp", ascending: false) fetchRequest.sortDescriptors = [sortDescriptor] let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: DataManager.sharedInstance.managedObjectContext, sectionNameKeyPath: nil, cacheName: "Master") aFetchedResultsController.delegate = self _fetchedResultsController = aFetchedResultsController do { try _fetchedResultsController!.performFetch() } catch { let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } return _fetchedResultsController! } fileprivate var _fetchedResultsController: NSFetchedResultsController<Event>? = nil // MARK: NSFetchResultsControllerDelegate func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { self.tableView.beginUpdates() } func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) { switch type { case .insert: self.tableView.insertSections(IndexSet(integer: sectionIndex), with: .fade) case .delete: self.tableView.deleteSections(IndexSet(integer: sectionIndex), with: .fade) default: return } } func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) { switch type { case .insert: tableView.insertRows(at: [newIndexPath!], with: .fade) case .delete: tableView.deleteRows(at: [indexPath!], with: .fade) case .update: self.configureCell(tableView.cellForRow(at: indexPath!)!, withEvent: anObject as! Event) case .move: tableView.moveRow(at: indexPath!, to: newIndexPath!) } } func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { self.tableView.endUpdates() } // MARK: Utils func configureCell(_ cell: UITableViewCell, withEvent event: Event) { cell.textLabel!.text = event.timestamp!.description } }
// // NSDate+Extension.swift // InstagramApp // // Created by Seo Kyohei on 2015/11/01. // Copyright © 2015年 Kyohei Seo. All rights reserved. // import Foundation extension NSDate { class func getDateTime() -> String { let now = NSDate() let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyy/MM/dd HH:mm EEE" let dateTime = dateFormatter.stringFromDate(now) return dateTime } }
// // VcWelcomeLayout.swift // KayakFirst Ergometer E2 // // Created by Balazs Vidumanszki on 2017. 12. 29.. // Copyright © 2017. Balazs Vidumanszki. All rights reserved. // import Foundation class VcWelcomeLayout: BaseLayout { //MARK: constants private let segmentItems = [getString("user_login"), getString("user_register")] private let marginHorizontal: CGFloat = 30 //MARK: properties private let loginRegisterView = UIView() private let viewController: WelcomeViewController init(contentView: UIView, viewController: WelcomeViewController) { self.viewController = viewController super.init(contentView: contentView) } func setSegmentedItem(sender: UISegmentedControl) { let viewSub: UIView switch sender.selectedSegmentIndex { case 1: viewSub = registerView default: viewSub = loginView } loginRegisterView.removeAllSubviews() loginRegisterView.addSubview(viewSub) viewSub.snp.makeConstraints { make in make.edges.equalTo(loginRegisterView) } } override func setView() { contentView.addSubview(segmentedControl) segmentedControl.snp.makeConstraints { (make) in make.top.equalTo(contentView).inset(UIEdgeInsetsMake(margin2, 0, 0, 0)) make.width.equalTo(contentView).inset(UIEdgeInsetsMake(0, marginHorizontal, 0, marginHorizontal)) make.centerX.equalTo(contentView) } loginRegisterView.addSubview(loginView) loginView.snp.makeConstraints { (make) in make.edges.equalTo(loginRegisterView) } contentView.addSubview(loginRegisterView) loginRegisterView.snp.makeConstraints { (make) in make.top.equalTo(segmentedControl.snp.bottom).offset(margin) make.left.equalTo(contentView).inset(UIEdgeInsetsMake(0, marginHorizontal, 0, 0)) make.right.equalTo(contentView).inset(UIEdgeInsetsMake(0, 0, 0, marginHorizontal)) make.bottom.equalTo(contentView).inset(UIEdgeInsetsMake(0, 0, margin, 0)) } } //MARK: views lazy var segmentedControl: UISegmentedControl! = { let control = UISegmentedControl(items: self.segmentItems) control.tintColor = Colors.colorAccent control.selectedSegmentIndex = 0 return control }() lazy var loginView: LoginView! = { let view = LoginView(viewController: self.viewController) return view }() lazy var registerView: RegisterView! = { let view = RegisterView(viewController: self.viewController) return view }() }
// // WebViewController.swift // Bulldog Bucks // // Created by Rudy Bermudez on 12/12/16. // // import UIKit import MBProgressHUD typealias WebViewAction = ((WebViewController) -> Void) class WebViewController: UIViewController { public static let storyboardIdentifier: String = "webView" var url: String = "https://zagweb.gonzaga.edu/prod/hwgwcard.transactions" var logoutFunc: WebViewAction? @IBOutlet weak var webView: UIWebView! @IBOutlet weak var backBarButton: UIBarButtonItem! @IBOutlet weak var forwardBarButton: UIBarButtonItem! @IBOutlet weak var closeNavButton: UIBarButtonItem! @IBOutlet weak var refreshNavButton: UIBarButtonItem! @IBOutlet weak var navItem: UINavigationItem! @IBOutlet weak var navbar: UINavigationBar! override func viewWillAppear(_ animated: Bool) { closeNavButton.action = #selector(closeWebView) refreshNavButton.action = #selector(reloadWebPage) backBarButton.action = #selector(goBack) forwardBarButton.action = #selector(goForward) self.webView.delegate = self let bounds = navbar.bounds let height: CGFloat = 50 //whatever height you want to add to the existing height self.navigationController?.navigationBar.frame = CGRect(x: 0, y: 0, width: bounds.width, height: bounds.height + height) navigationController?.navigationBar.barStyle = .default showLoadingHUD() } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) navigationController?.navigationBar.barStyle = .blackOpaque } override var prefersStatusBarHidden: Bool { return true } override func viewDidLoad() { super.viewDidLoad() navItem.title = title } func loadWebView() { guard let url = URL(string: url) else { return } print(url) let request = URLRequest(url: url) webView.loadRequest(request) } /// Displays a Loading View fileprivate func showLoadingHUD() { let hud = MBProgressHUD.showAdded(to: view, animated: true) hud.label.text = "Loading..." hud.hide(animated: true, afterDelay: 10) } /// Hides the Loading View fileprivate func hideLoadingHUD() { MBProgressHUD.hide(for: view, animated: true) } @objc func reloadWebPage() { webView.reload() } @objc func goBack() { webView.goBack() } @objc func goForward() { webView.goForward() } @objc func closeWebView() { logoutFunc?(self) dismiss(animated: true, completion: nil) } } extension WebViewController: UIWebViewDelegate { /// Starts animating the activity indicator when webView is loading func webViewDidStartLoad(_ webView: UIWebView) { showLoadingHUD() } /// Stops animating the activity indicator when webView is done loading func webViewDidFinishLoad(_ webView: UIWebView) { DispatchQueue.main.async { self.hideLoadingHUD() self.backBarButton.isEnabled = webView.canGoBack self.forwardBarButton.isEnabled = webView.canGoForward } } }
import UIKit class AllStationsViewController: TableViewController, UISearchBarDelegate { var stationGroups: [StationGroup]? var selectedStation: Station? private var indexTitles: [String]? private var isSearching = false private var searchResults: [Station]? let viewModel = StationsViewModel() override func refresh() { viewModel.allStations() .subscribe( onNext: { stationGroups in self.stationGroups = stationGroups self.indexTitles = [] self.indexTitles?.append(UITableViewIndexSearch) for stationsSection in self.stationGroups ?? [] { self.indexTitles?.append(stationsSection.initial) } self.tableView.reloadData() }, onError: { error in self.refreshControl?.endRefreshing() }, onCompleted: { self.refreshControl?.endRefreshing() }) .disposed(by: rx.disposeBag) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "UnwindSegueFromAllStationsViewController" { if let indexPath = tableView.indexPathForSelectedRow { if isSearching == false { selectedStation = stationGroups?[indexPath.section].stations[indexPath.row] } else { selectedStation = searchResults?[indexPath.row] } } else { selectedStation = nil } } } // MARK: - Table View Data Source override func numberOfSections(in tableView: UITableView) -> Int { if isSearching == false { return stationGroups?.count ?? 0 } else { return 1 } } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if isSearching == false { return stationGroups?[section].stations.count ?? 0 } else { return searchResults?.count ?? 0 } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if isSearching == false { let cell = tableView.dequeueReusableCell(withIdentifier: "StationTableCell", for: indexPath) cell.textLabel?.text = stationGroups?[indexPath.section].stations[indexPath.row].stationName return cell } else { let cell = tableView.dequeueReusableCell(withIdentifier: "StationTableCell", for: indexPath) cell.textLabel?.text = searchResults?[indexPath.row].stationName return cell } } override func sectionIndexTitles(for tableView: UITableView) -> [String]? { if isSearching == false { return indexTitles } else { return nil } } override func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int { if index == 0 { tableView.contentOffset = CGPoint.zero return NSNotFound } return index } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if isSearching == false { return stationGroups?[section].initial } else { return nil } } // MARK: - Search Bar Delegate func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) { searchBar.showsCancelButton = true } func searchBarTextDidEndEditing(_ searchBar: UISearchBar) { searchBar.showsCancelButton = false } func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { isSearching = true searchResults = [] for stationsSection in stationGroups ?? [] { for station in stationsSection.stations { if station.stationName?.range(of: searchText, options: .caseInsensitive) != nil || station.stationNameThreeDigitPinyin?.range(of: searchText, options: .caseInsensitive) != nil || station.stationNameFullPinyin?.range(of: searchText, options: .caseInsensitive) != nil || station.stationNameIntials?.range(of: searchText, options: .caseInsensitive) != nil { searchResults?.append(station) } } } tableView.reloadData() } func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { searchBar.resignFirstResponder() } func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { searchBar.text = nil searchBar.resignFirstResponder() isSearching = false tableView.reloadData() } }
// // DetailTableViewController.swift // AppveloxTestApp // // Created by Vladislav Barinov on 10.06.2020. // Copyright © 2020 Vladislav Barinov. All rights reserved. // import UIKit import SDWebImage class DetailTableViewController: UITableViewController { @IBOutlet weak var imageNews: UIImageView! @IBOutlet weak var fullText: UILabel! @IBOutlet weak var titleNews: UILabel! var news: News? override func viewDidLoad() { super.viewDidLoad() titleNews.text = news?.title fullText.text = news?.yandexFullText guard let url = URL(string: news?.enclosureUrl ?? "") else { return } imageNews.sd_setImage(with: url, placeholderImage: nil, options: .continueInBackground, completed: nil) } }
// // SearchView.swift // NTGTags // // Created by Mena Gamal on 2/17/20. // Copyright © 2020 Mena Gamal. All rights reserved. // import Foundation import UIKit protocol SearchView :class{ var searchTable: UITableView! { get set } }
// // NetworkTool.swift // 新浪微博 // // Created by 李旭飞 on 15/10/10. // Copyright © 2015年 lee. All rights reserved. // import UIKit private let ErrorDomain="network.error" //网络访问错误枚举 private enum NetworkError:Int{ case emptyDataError = -1 case emptyTokenError = -2 ///错误描述 private var errorDescription:String{ switch self { case .emptyDataError: return "空数据" case .emptyTokenError: return "没有权限" } } ///根据枚举类型返回错误信息 private func error()->NSError{ return NSError(domain: ErrorDomain, code: rawValue, userInfo:[ErrorDomain:errorDescription]) } } class NetworkTool: NSObject { //MARK:- 检查token private func checkToken(finished:FinishedCallBack)->[String:AnyObject]?{ if UserAccess.loadUserAccount?.access_token == nil{ let error = NetworkError.emptyTokenError.error() finished(result: nil, error: error) return nil } //返回字典时为啦包成参数,这样直接再添加额外参数就可 return ["access_token":UserAccess.loadUserAccount!.access_token!] } //MARK:- 加载微博数据 func loadWeiboData(since_id:Int,max_id:Int,finished:FinishedCallBack){ guard var param=checkToken(finished) else{ return } if since_id>0{ param["since_id"]="\(since_id)"; } if max_id>0{ param["max_id"]="\(max_id-1)"; } let urlString = "https://api.weibo.com/2/statuses/home_timeline.json" networkRequest(.GET, URLString: urlString, paramater: param, finished: finished) } static let shareNetworkTool=NetworkTool() //MARK: - OAuth授权 private let clientId="2260003661" private let appSecret="84630ccd2050db7da66f9d1e7c25d105" let redirectURL="http://www.baidu.com" func oauthURL()->NSURL{ let path=NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(clientId)&redirect_uri=\(redirectURL)") return path! } //MARK:- 获取用户信息 func loadUserInfo(uid:String,finished:FinishedCallBack){ //判断token是否存在 guard var param = checkToken(finished) else{ finished(result: nil, error: NetworkError.emptyTokenError.error()) return } let url="https://api.weibo.com/2/users/show.json" param["uid"]=uid networkRequest(.GET, URLString: url, paramater: param, finished: finished) } // MARK:- 获取授权码token func oauthToken(code:String,finished:FinishedCallBack){ let dict=["client_id":clientId, "client_secret":appSecret, "grant_type":"authorization_code", "code":code, "redirect_uri":redirectURL] let url="https://api.weibo.com/oauth2/access_token" networkRequest(.POST, URLString: url, paramater: dict, finished: finished) } // 这里要加问号,有可能为空 typealias FinishedCallBack = (result:AnyObject?,error:NSError?)->() ///网络请求方式枚举 enum HttpMethod:String{ case GET = "GET" case POST = "POST" } //MARK:- 封装网络请求方法 func networkRequest(methed:HttpMethod,URLString:String,paramater:[String:AnyObject],finished:FinishedCallBack){ var body = "" for (key,value) in paramater{ body += "\(key)=\(value as! String)&" } body = (body as NSString).substringToIndex(body.characters.count-1) let request = NSMutableURLRequest() switch methed{ case .POST : request.URL = NSURL(string: URLString) request.HTTPMethod = "POST" request.HTTPBody = body.dataUsingEncoding(NSUTF8StringEncoding) case .GET : request.URL = NSURL(string: "\(URLString)?\(body)") request.HTTPMethod = "GET" } NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) -> Void in if error != nil || data == nil{ finished(result: nil, error: error) return } do{ let obj = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions(rawValue: 0)) dispatch_async(dispatch_get_main_queue(), { () -> Void in finished(result: obj, error: nil) }) }catch{ finished(result: nil, error: NetworkError.emptyDataError.error()) } }.resume() } }
// // ViewController.swift // MarvelComic // // Created by Alec Malcolm on 2018-03-06. // Copyright © 2018 Alec Malcolm. All rights reserved. // import UIKit class ViewController: UIViewController { // @IBOutlet weak var btnCharacter: UIButton! // @IBOutlet weak var btnComics: UIButton! // @IBOutlet weak var btnCreators: UIButton! // @IBOutlet weak var btnEvents: UIButton! // @IBOutlet weak var btnSeries: UIButton! // @IBOutlet weak var btnStories: UIButton! override func viewDidLoad() { super.viewDidLoad() //let api: MarvelApi = MarvelApi() //_ = api.getComic(id: 37500) // btnCharacter.layer.cornerRadius = 10 // btnCharacter.clipsToBounds = true // // btnComics.layer.cornerRadius = 10 // btnComics.clipsToBounds = true // // btnCreators.layer.cornerRadius = 10 // btnCreators.clipsToBounds = true // // btnEvents.layer.cornerRadius = 10 // btnEvents.clipsToBounds = true // // btnSeries.layer.cornerRadius = 10 // btnSeries.clipsToBounds = true // // btnStories.layer.cornerRadius = 10 // btnStories.clipsToBounds = true //api.printComics() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // @IBAction func viewCharacters(_ sender: Any) // { // performSegue(withIdentifier: "characterSeque", sender: self) // } // // @IBAction func viewComics(sender: UIButton) { // let comic:ComicViewController = ComicViewController() // self.present(comic, animated: true, completion: nil) // } // // @IBAction func viewCreators(sender: UIButton) { // let creator: CreatorViewController = CreatorViewController() // self.present(creator, animated: true, completion: nil) // } // // @IBAction func viewEvents(sender: UIButton) { // let event: EventViewController = EventViewController() // self.present(event, animated: true, completion: nil) // } // // @IBAction func viewSeries(sender: UIButton) { // let series: SeriesViewController = SeriesViewController() // self.present(series, animated: true, completion: nil) // } // // @IBAction func viewStories(sender: UIButton) { // let story: StoryViewController = StoryViewController() // self.present(story, animated: true, completion: nil) // } }
// // StextExt.swift // PageShare // // Created by cheny on 2016/10/13. // Copyright © 2016年 Oneplus Smartware. All rights reserved. // import Foundation struct StextExt : Glossy{ let x:Float let y:Float let client:String init?(json: JSON) { self.x = ("x" <~~ json)! self.y = ("y" <~~ json)! self.client = ("client" <~~ json)! } func toJSON() -> JSON? { return jsonify([ "x" ~~> self.x, "y" ~~> self.y, "client" ~~> self.client ]); } }
// // LoginViewController.swift // BlogApp // // Created by Thomas on 12/04/2016. // Copyright © 2016 Thomas Jezequel. All rights reserved. // //TODO: Add Spinner on login import UIKit class LoginViewController: UIViewController { @IBOutlet weak var loginButton: UIButton! @IBOutlet weak var ipAddrField: UITextField! @IBOutlet weak var loginField: UITextField! @IBOutlet weak var passwordField: UITextField! let apiServices = ApiServices() let spinner = UIActivityIndicatorView(activityIndicatorStyle: .WhiteLarge) override func viewDidLoad() { super.viewDidLoad() ipAddrField.text = "http://apitest.tjezequel.fr" apiServices.delegate = self ipAddrField.attributedPlaceholder = NSAttributedString(string: "IP address", attributes: [NSForegroundColorAttributeName: UIColor.whiteColor()]) loginField.attributedPlaceholder = NSAttributedString(string: "Username", attributes: [NSForegroundColorAttributeName: UIColor.whiteColor()]) passwordField.attributedPlaceholder = NSAttributedString(string: "Password", attributes: [NSForegroundColorAttributeName: UIColor.whiteColor()]) ipAddrField.tintColor = UIColor.whiteColor() loginField.tintColor = UIColor.whiteColor() passwordField.tintColor = UIColor.whiteColor() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidAppear(animated: Bool) { spinner.center = loginButton.center } @IBAction func loginButtonClicked(sender: AnyObject) { loginButton.hidden = true spinner.startAnimating() self.view.addSubview(spinner) BASEURL = "\(ipAddrField.text!)/" let data = ["username": loginField.text!, "password": passwordField.text!, "baseUrl": ipAddrField.text!] apiServices.sendLogin(data) } } extension LoginViewController: ApiServicesDelegate{ func didRecieveDataFromApi(data: [String : AnyObject]) { if data["code"] as! Int == 0 { apiServices.token = data["token"] as! String performSegueWithIdentifier("loginSuccess", sender: self) } else { self.spinner.removeFromSuperview() spinner.stopAnimating() loginButton.hidden = false let alert = UIAlertController(title: "Could not connect", message: "Bad Credentials", preferredStyle: .Alert) let action = UIAlertAction(title: "Ok :(", style: .Default, handler: nil) alert.addAction(action) self.presentViewController(alert, animated: true, completion: nil) } } }
// // Model.swift // GroupApp // // Created by Aleksandr Rybachev on 17.04.2021. // import Foundation struct User { let login: String let password: String let loginIcon: String let passwordIcon: String static func getUserData() -> User { User( login: DataManager.shared.loginDM, password: DataManager.shared.passwordDM, loginIcon: DataManager.shared.loginIconDM, passwordIcon: DataManager.shared.passwordIconDM ) } } enum Contacts: String { case login = "person" // case password = "tray" //tray }
//: [Previous](@previous) import Foundation var greeting = "Hello, playground" let driving = { print("I'm driving in my car") } driving() //: [Next](@next)
// // RouteInfoView.swift // CoreML_test // // Created by Осина П.М. on 27.02.18. // Copyright © 2018 Осина П.М. All rights reserved. // import UIKit class RouteInfoView: UIView { @IBOutlet private var startPlaceView: PlaceInfoView! @IBOutlet private var endPlaceView: PlaceInfoView! @IBOutlet private var routeView: UIView! func configure(){ routeView.backgroundColor = .red } }
//: [Previous](@previous) import Foundation protocol CustomView { associatedtype ViewType func configure(view with: ViewType) } struct Button {} struct CustomEnabledButton: CustomView { typealias ViewType = Button func configure(view with: ViewType) { // configure the view print("Enabled button") } } var customEnabledButton = CustomEnabledButton() customEnabledButton.configure(view: Button()) print(customEnabledButton) struct CustomDisabledButton: CustomView { typealias ViewType = Button func configure(view with: ViewType) { // configure the view print("Disabled button") } } // let customViews = [CustomSwitch(), CustomEnabledButton(), CustomDisabledButton()] /// Type Erasure // Type-erased CustomView struct AnyCustomView<ViewType>: CustomView { private let _configure: (ViewType) -> Void init<Base: CustomView>(_ base: Base) where ViewType == Base.ViewType { _configure = base.configure } func configure(view with: ViewType) { _configure(with) } } let views = [AnyCustomView(CustomEnabledButton()), AnyCustomView(CustomDisabledButton())] let button = Button() for view in views { view.configure(view: button) print(view) } struct Switch {} struct CustomSwitch: CustomView { typealias ViewType = Switch func configure(view with: ViewType) { // configure the view print("Custom switch") } } // let views = [AnyCustomView(CustomSwitch()), AnyCustomView(CustomDisabledButton())] // error: heterogeneous collection literal could only be inferred to '[Any]'; add explicit type annotation if this is intentional //: [Next](@next)
// // TermsAndConditionsCell.swift // Surface // // Created by Nandini on 07/03/18. // Copyright © 2018 Appinventiv. All rights reserved. // import UIKit class TermsAndConditionsCell: UITableViewCell { //MARK:- Properties //MARK:- @IBOutlets @IBOutlet weak var checkButton: UIButton! @IBOutlet weak var termsAndConditionLabel: TTTAttributedLabel! //MARK:- View Life Cycle override func awakeFromNib() { super.awakeFromNib() } }
// // CustomExtensions.swift // WayAlerts // // Created by SMTIOSDEV01 on 31/07/16. // Copyright © 2016 Cognizant. All rights reserved. // import Foundation import Toast_Swift public extension UIView{ // Start Busy icon spinning public func startBusySpinner(){ self.makeToastActivity(.Center) } // Stop Busy icon spinning public func stopBusySpinner(){ dispatch_async(dispatch_get_main_queue(), { self.hideToastActivity() }); } // Stop Busy icon spinning public func showToast(message: String){ dispatch_async(dispatch_get_main_queue(), { self.makeToast(message) }); } }
// // Webservice.swift // AxxessCodeTestApp // // Created by Shailesh Gole on 13/08/20. // Copyright © 2020 ShaileshG. All rights reserved. // import Foundation import Alamofire enum AppError: Error { case ServerResponseError case ServerDataError case DataParsingError case NetworkError } class Webservice { func getArticles(_ completion: @escaping ([Article]?, Error?) -> Void) { let url = URL(string: "https://raw.githubusercontent.com/AxxessTech/Mobile-Projects/master/challenge.json")! Alamofire.request(url).response { (response) in do { if response.error != nil { completion(nil, AppError.ServerResponseError) } guard let responseData = response.data else { completion(nil, AppError.ServerDataError) return } let article = try? JSONDecoder().decode(Articles.self, from: responseData) completion(article, nil) } } } } class Connectivity { class func isConnectedToInternet() -> Bool { return NetworkReachabilityManager()!.isReachable } }
// // 크기만큼 배치 // import UIKit // import RealityKit // 랜더링 SDK import ARKit // 증강 현실 구현하기 위한 framework class ViewController7: UIViewController { @IBOutlet weak var arView: ARView! var public_distance:Int = 0 // 잰 거리 var product_distance:Int = 0 // 가구의 길이 override func viewDidLoad() { //view load, layout 설정 super.viewDidLoad() print("ViewController7") print(public_distance) // if (public_distance > 30) { // showAlertAble() // } else { // showAlertUnAble() // } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) arView.session.delegate = self setupARView() arView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleTap(recognizer:)))) } //MARK: Setup Methods func setupARView() { arView.automaticallyConfigureSession = false // 자동으로 세션을 구성하지 않음 self.addCoaching() let configuration = ARWorldTrackingConfiguration() configuration.planeDetection = [.horizontal, .vertical] // 수평, 수직으로 planeDetection configuration.environmentTexturing = .automatic arView.session.run(configuration) } //MARK: Object Placement @objc func handleTap(recognizer: UITapGestureRecognizer) { let location = recognizer.location(in: arView) let results = arView.raycast(from: location, allowing: .estimatedPlane, alignment: .horizontal) // let transform_array_value = makeScaleMatrix(xScale:0.3, yScale:0.3, zScale:0.3) // print(transform_array_value) if let firstResult = results.first { let anchor = ARAnchor(name: "chair_swan", transform: firstResult.worldTransform) //print(anchor) //let anchor = ARAnchor(name: "blue", transform: firstResult.worldTransform) arView.session.add(anchor: anchor) } else { print("Object placement failed -couldn't find surface.") } } func placeObject(named entityName: String, for anchor: ARAnchor) { let entity = try! ModelEntity.loadModel(named: entityName) entity.generateCollisionShapes(recursive: true) arView.installGestures([.rotation,.translation], for: entity) let anchorEntity = AnchorEntity(anchor: anchor) anchorEntity.addChild(entity) arView.scene.addAnchor(anchorEntity) } // func showAlertAble() { // let alert = UIAlertController(title: "", message: "배치가 가능합니다", preferredStyle: .alert) // alert.addAction(UIAlertAction(title: "확인", style: .cancel, handler: { action in // print("tapped dismiss") // })) // present(alert, animated: true) // } // func showAlertUnAble() { // let alert = UIAlertController(title: "", message: "배치가 불가능합니다. 다른 장소를 선택하세요. (가구 길이: 30cm)", preferredStyle: .alert) // alert.addAction(UIAlertAction(title: "확인", style: .cancel, handler: { action in // print("tapped dismiss") // })) // present(alert, animated: true) // } // func makeScaleMatrix(xScale: Float, yScale: Float, zScale: Float) -> simd_float4x4 { // let rows = [ // simd_float4(xScale, 0, 0, 0), // simd_float4( 0, yScale, 0, 0), // simd_float4( 0, 0, zScale, 0), // simd_float4( 0, 0, 0, 1) // ] // // return float4x4(rows: rows) // } } extension ViewController7: ARSessionDelegate { func session(_ session: ARSession, didAdd anchors: [ARAnchor]) { for anchor in anchors { if let anchorName = anchor.name, anchorName == "chair_swan" { placeObject(named: anchorName, for: anchor) } } } } extension ViewController7: ARCoachingOverlayViewDelegate { // coachingOverlayView func addCoaching() { let coachingOverlay = ARCoachingOverlayView() coachingOverlay.delegate = self coachingOverlay.session = arView.session coachingOverlay.autoresizingMask = [.flexibleWidth,.flexibleHeight] coachingOverlay.translatesAutoresizingMaskIntoConstraints = false arView.addSubview(coachingOverlay) NSLayoutConstraint.activate([ coachingOverlay.centerXAnchor.constraint(equalTo: view.centerXAnchor), coachingOverlay.centerYAnchor.constraint(equalTo: view.centerYAnchor), coachingOverlay.widthAnchor.constraint(equalTo: view.widthAnchor), coachingOverlay.heightAnchor.constraint(equalTo: view.heightAnchor) ]) coachingOverlay.activatesAutomatically = true coachingOverlay.goal = .horizontalPlane } // public func coachingOverlayViewDidDeactivate(_ coachingOverlayView: ARCoachingOverlayView) { // <#code#>// Ready to add entities next? // } }
// // DetailProductQuestion.swift // MyLoqta // // Created by Ashish Chauhan on 28/07/18. // Copyright © 2018 AppVenturez. All rights reserved. // import UIKit class DetailProductQuestion: BaseTableViewCell, NibLoadableView, ReusableView { @IBOutlet weak var lblTimeAgo: UILabel! @IBOutlet weak var lblQuestion: UILabel! @IBOutlet weak var lblUserName: UILabel! @IBOutlet weak var lblUserImage: UIImageView! @IBOutlet weak var lblNoOfQuestion: UILabel! @IBOutlet weak var imgViewBlueCheck: UIImageView! @IBOutlet weak var lblReply: UILabel! @IBOutlet weak var lblReplyTimeAgo: UILabel! @IBOutlet weak var lblReplyTo: UILabel! @IBOutlet weak var lblStoreName: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state Threads.performTaskAfterDealy(0.2) { self.lblUserImage.roundCorners(24.0) } } func configreCell(question: Question, indexPath: IndexPath, product: Product? = nil) { if indexPath.row == 0, let producutDetail = product, let count = producutDetail.questionAnswersCount { lblNoOfQuestion.text = "Questions and Answers . \(count)" } else { lblNoOfQuestion.text = "" } if let profilePic = question.profilePic { self.lblUserImage.setImage(urlStr: profilePic, placeHolderImage: #imageLiteral(resourceName: "user_placeholder")) } if let name = question.userName { self.lblUserName.text = name } if let questionStr = question.question { self.lblQuestion.text = questionStr } if let questionTime = question.createdAt { self.lblTimeAgo.text = Date.timeSince(questionTime) } if let arrayReply = question.reply { if arrayReply.count > 0 { let reply = arrayReply[0] if let sellerName = reply.sellerName { self.lblStoreName.text = sellerName } if let text = self.lblUserName.text { let replyText = "replied to".localize() self.lblReplyTo.text = "\(replyText) \(text)" } if let replystr = reply.reply { self.lblReply.text = replystr } if let replyTime = reply.createdAt { self.lblReplyTimeAgo.text = Date.timeSince(replyTime) } } } } }
// // HandbookView.swift // McKendrickUI // // Created by Steven Lipton on 3/10/20. // Copyright © 2020 Steven Lipton. All rights reserved. // // An exercise file for iOS Development Tips Weekly // A weekely course on LinkedIn Learning for iOS developers // Season 10 (Q2 2020) video 10 // by Steven Lipton (C)2020, All rights reserved // Learn more at https://linkedin-learning.pxf.io/YxZgj // This Week: Create custom modifiers in SwiftUI while making the button panel a navigation panel. // For more code, go to http://bit.ly/AppPieGithub // Quarter Share, Ishmael Wang, Lois McKendrick, and // Trader Tales from the Golden Age of the Solar Clipper // copyright Nathan Lowell, used with permission // To read the novel behind this project, see https://www.amazon.com/Quarter-Share-Traders-Golden-Clipper-ebook/dp/B00AMO7VM4 import SwiftUI struct HandbookView: View { var isSelected:Bool = false init(){ self.isSelected = true } init(isSelected:Bool){ self.isSelected = isSelected } func isCompact(_ geometry:GeometryProxy)->Bool{ //a faked compact size class geometry.size.width < 412 } var body: some View { GeometryReader{ geometry in VStack{ ContentHeaderView(headerTitle: "Spacer Handbook", headerSubtitle: "With Federated Freight Amendations and Standing Orders of SC Lois McKendrick ") .frame(height:geometry.size.height * 0.1 ) Text("Spacer's Handbook") .font(self.isCompact(geometry) ? .headline : .largeTitle) .fontWeight(.heavy) .padding(.bottom,40) Text("Rules, Regulations, and Guidance for Spacers") .font(self.isCompact(geometry) ? .headline : .title) Text("Confederated Planets Joint Committee on Trade") .font(self.isCompact(geometry) ? .headline : .title) Text("Current Edition: 2352") .font(.headline) Spacer() Text("SC Lois McKendrick, Federated Freight") Spacer() }//Vstack root .selectedTransition(isSelected: self.isSelected, geometry: geometry) } } } struct HandbookView_Previews: PreviewProvider { static var previews: some View { HandbookView(isSelected: true) } }
// // PackLads.swift // Pack-Go // // Created by Lorraine Chong on 2019-12-09. // Copyright © 2019 Xcode User. All rights reserved. // // Done By Laurence Chong import UIKit class PackLads: NSObject, NSCoding { var pokemonName : String? var imageName : String? func initWithData( pokemonName:String, imageName:String) { self.pokemonName = pokemonName self.imageName = imageName } // step 3c -> create these two methods to handle serialization of data between // phone and watch. required convenience init?(coder decoder: NSCoder) { guard let pokemonName = decoder.decodeObject(forKey: "pokemonName") as? String, let imageName = decoder.decodeObject(forKey: "imageName") as? String else { return nil } // note this will cause crash if its not in here exactly as is self.init() self.initWithData( pokemonName: pokemonName as String, imageName: imageName as String ) } func encode(with coder: NSCoder) { coder.encode(self.pokemonName, forKey: "pokemonName") coder.encode(self.imageName, forKey: "imageName") } }
// // LocationResultsViewController.swift // Health Care Near Me // // Created by Rudy Bermudez on 4/30/17. // Copyright © 2017 Rudy Bermudez. All rights reserved. // import UIKit import MapKit import SideMenu class LocationResultsViewController: UIViewController { public static let storyboardIdentifier: String = "LocationResultsViewController" @IBOutlet weak var mapView: MKMapView! @IBOutlet weak var stackView: UIStackView! @IBOutlet weak var tableView: UITableView! var coordinate: Coordinate? let manager = LocationManager() let searchController = UISearchController(searchResultsController: nil) var regionHasBeenSet = false var unfilteredData: [LocationData] = [] var venues: [LocationData] = [] { didSet { if venues.count > 0 { tableView.reloadData() addMapAnnotations() } } } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() // Search bar configuration searchController.searchResultsUpdater = self searchController.hidesNavigationBarDuringPresentation = true searchController.dimsBackgroundDuringPresentation = false searchController.searchBar.isTranslucent = false definesPresentationContext = true stackView.insertArrangedSubview(searchController.searchBar, at: 0) self.view.layoutIfNeeded() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Left Nav Item - Menu self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "menu")!, style: .plain, target: self, action: #selector(toggleMenu)) navigationItem.title = "Locations" } override func viewDidLoad() { super.viewDidLoad() SideMenuManager.default.menuAddScreenEdgePanGesturesToPresent(toView: self.view, forMenu: UIRectEdge.left) LocationAPI.getLocations { (result) in switch result { case .failure(let error): print(error) case .success(let venues): self.unfilteredData = venues self.venues = venues } } manager.getPermission() manager.onLocationFix = { [weak self] coordinate in self?.coordinate = coordinate } } @objc func toggleMenu() { UIView.animate(withDuration: 1.5) { self.present(SideMenuManager.default.menuLeftNavigationController!, animated: true, completion: nil) } } } extension LocationResultsViewController: UITableViewDataSource, UITableViewDelegate { // MARK: UITableViewDataSource func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return venues.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "LocationCell", for: indexPath) as! LocationTableViewCell // TODO: Rudy - Add functionality, name, description, category etc cell.LocationTitleLabel.text = venues[indexPath.row].name return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let vc = storyboard?.instantiateViewController(withIdentifier: DetailViewController.storyboardID) as! DetailViewController vc.venue = venues[indexPath.row] navigationController?.pushViewController(vc, animated: true) } } // MARK: MKMAPViewDelegate extension LocationResultsViewController: MKMapViewDelegate { func addMapAnnotations() { removeMapAnnotations() guard venues.count > 0 else { return } let annotations: [MKPointAnnotation] = venues.map { venue in let point = MKPointAnnotation() point.coordinate = CLLocationCoordinate2D(latitude: venue.location.lat, longitude: venue.location.long) point.title = venue.name return point } //mapView.addAnnotations(annotations) mapView.showAnnotations(annotations, animated: false) } func removeMapAnnotations() { if mapView.annotations.count != 0 { for annotation in mapView.annotations { mapView.removeAnnotation(annotation) } } } func setMapRegion() { var region = MKCoordinateRegion() // region.center = mapView.userLocation.coordinate region.center = CLLocationCoordinate2D(latitude: 47.6671926, longitude: -117.4045736) region.span.latitudeDelta = 0.03 region.span.longitudeDelta = 0.03 mapView.setRegion(region, animated: false) } func mapView(_ mapView: MKMapView, didUpdate userLocation: MKUserLocation) { if !regionHasBeenSet { regionHasBeenSet = true setMapRegion() } } func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) { guard let annotation = view.annotation?.title, let title = annotation, let row = venues.index(where: { $0.name == title }) else { return } tableView.selectRow(at: IndexPath(row: row, section: 0), animated: true, scrollPosition: .top) } func mapView(_ mapView: MKMapView, didDeselect view: MKAnnotationView) { guard let annotation = view.annotation?.title, let title = annotation, let row = venues.index(where: { $0.name == title }) else { return } tableView.deselectRow(at: IndexPath(row: row, section: 0), animated: true) } } // MARK: UISearchResultsUpdating extension LocationResultsViewController: UISearchResultsUpdating { func updateSearchResults(for searchController: UISearchController) { guard let query = searchController.searchBar.text else { venues = unfilteredData return } guard !query.isEmpty else { venues = unfilteredData; return } venues = unfilteredData.filter { $0.name.lowercased().contains(query.lowercased()); } } }