text
stringlengths
8
1.32M
// // HomeCVC.swift // Nuooly // // Created by Mahnoor Fatima on 6/13/18. // Copyright © 2018 Mahnoor Fatima. All rights reserved. // import UIKit class HomeCVC: UICollectionViewCell { @IBOutlet weak var titleImgView: UIImageView! @IBOutlet weak var titleLbl: UILabel! @IBOutlet weak var countLbl: UILabel! let titles:[String] = ["Message","Project Alerts","Community Feed","Create Profile","My Project","My Watching List","Find a Project","Grow your Team","My Profile","Requests","My Connections"] override func awakeFromNib() { super.awakeFromNib() self.titleImgView.getRounded(cornerRaius: 0) self.giveShadow(cornerRaius: 0) self.titleImgView.layer.borderColor = UIColor.darkGray.cgColor } }
// // Vertex.swift // Stickies // // Created by Jacob Sawyer on 7/23/17. // Copyright © 2017 Jake Sawyer. All rights reserved. // import GLKit struct Vertex { let x, y, z:Float let u, v:Float }
import UIKit import CoreData @available(iOS 13.0, *) var appData = AppData() var statisticBrain = StatisticBrain() var sumAllCategories: [String: Double] = [:] var allSelectedTransactionsData: [Transactions] = [] var expenseLabelPressed = true var selectedPeroud = "" @available(iOS 13.0, *) class ViewController: UIViewController { @IBOutlet weak var filterView: UIView! @IBOutlet weak var buttonsFilterView: UIView! @IBOutlet weak var pressToShowFilterButtons: UIButton! @IBOutlet weak var thisMonthFilterButton: UIButton! @IBOutlet weak var customButton: UIButton! @IBOutlet weak var todayButton: UIButton! @IBOutlet weak var allTimeButton: UIButton! @IBOutlet weak var filterTextLabel: UILabel! @IBOutlet weak var calculationSView: UIStackView! @IBOutlet weak var mainTableView: UITableView! @IBOutlet weak var addTransitionButton: UIButton! @IBOutlet weak var noTableDataLabel: UILabel! @IBOutlet weak var balanceLabel: UILabel! @IBOutlet weak var incomeLabel: UILabel! @IBOutlet weak var expenseLabel: UILabel! var refreshControl = UIRefreshControl() var tableData = appData.transactions.sorted{ $0.dateFromString > $1.dateFromString } var alerts = Alerts() override func viewDidLoad() { super.viewDidLoad() updateUI() filterOptionsPressed(thisMonthFilterButton) } func updateUI() { addTransitionButton.layer.cornerRadius = 15 mainTableView.delegate = self mainTableView.dataSource = self loadItems() pressToShowFilterButtons.layer.cornerRadius = 6 buttonsFilterView.layer.cornerRadius = 6 buttonsFilterView.layer.shadowColor = UIColor.black.cgColor buttonsFilterView.layer.shadowOpacity = 0.2 buttonsFilterView.layer.shadowOffset = .zero buttonsFilterView.layer.shadowRadius = 6 customButton.layer.cornerRadius = 6 todayButton.layer.cornerRadius = 6 allTimeButton.layer.cornerRadius = 6 thisMonthFilterButton.layer.cornerRadius = 6 buttonsFilterView.alpha = 0 refreshControl.addTarget(self, action: #selector(refresh(sender:)), for: UIControl.Event.valueChanged) refreshControl.tintColor = K.Colors.separetor mainTableView.addSubview(refreshControl) } @objc func refresh(sender:AnyObject) { performSegue(withIdentifier: K.goToEditVCSeq, sender: self) Timer.scheduledTimer(withTimeInterval: 0.6, repeats: false) { (timer) in self.refreshControl.endRefreshing() } } func performFiltering() { var mydates: [String] = [] var dateFrom = Date() var dateTo = Date() let fmt = DateFormatter() if appData.filter.showAll == true { tableData = appData.transactions.sorted{ $0.dateFromString > $1.dateFromString } } else { fmt.dateFormat = "dd.MM.yyyy" dateFrom = fmt.date(from: appData.filter.from)! while fmt.date(from: appData.filter.to) == nil { appData.filter.lastNumber -= 1 appData.filter.to = appData.filter.getLastDay(appData.filter.filterObjects.currentDate) } dateTo = fmt.date(from: appData.filter.to)! while dateFrom <= dateTo { mydates.append(fmt.string(from: dateFrom)) dateFrom = Calendar.current.date(byAdding: .day, value: 1, to: dateFrom)! } appendFiltered(dates: mydates) } showNoDataLabel() allSelectedTransactionsData = tableData } var totalBalance = 0.0 func calculateBalance() { var totalExpenses = 0.0 var totalIncomes = 0.0 for i in 0..<appData.transactions.count { if appData.transactions[i].value > 0.0 { totalIncomes = totalIncomes + appData.transactions[i].value } else { totalExpenses = totalExpenses + appData.transactions[i].value } } totalBalance = totalIncomes + totalExpenses if totalBalance < Double(Int.max) { balanceLabel.text = "\(Int(totalBalance))" } else { balanceLabel.text = "\(totalBalance)" } if totalBalance < 0.0 { balanceLabel.textColor = K.Colors.negative } else { balanceLabel.textColor = K.Colors.balanceV } } func appendFiltered(dates: [String]) { var arr = appData.transactions arr.removeAll() for number in 0..<dates.count { for i in 0..<appData.transactions.count { if dates[number] == appData.transactions[i].date { arr.append(appData.transactions[i]) }}} tableData = arr.sorted{ $0.dateFromString > $1.dateFromString } } func loadItems(_ request: NSFetchRequest<Transactions> = Transactions.fetchRequest(), predicate: NSPredicate? = nil) { do { appData.transactions = try appData.context.fetch(request).sorted{ $0.dateFromString > $1.dateFromString } } catch { print("\n\nERROR FETCHING DATA FROM CONTEXTE\n\n", error)} mainTableView.reloadData() appData.recalculation(b: balanceLabel, i: incomeLabel, e: expenseLabel, data: tableData) statisticBrain.getData(from: self.tableData) sumAllCategories = statisticBrain.statisticData calculateBalance() } func saveItems() { do { try appData.context.save() } catch { print("\n\nERROR ENCODING CONTEXT\n\n", error) } loadItems() } func showFilterAlert() { let alert = UIAlertController(title: "Custom period", message: "", preferredStyle: .alert) let action = UIAlertAction(title: "Done", style: .default) { (acrion) in self.setFilterDates() self.performFiltering() self.loadItems() } alert.addAction(UIAlertAction(title: "Cancel", style: .default, handler: { (cancel) in self.filterOptionsPressed(self.thisMonthFilterButton) })) alerts.alertTextField(alert: alert) alert.addAction(action) present(alert, animated: true, completion: nil) } func setFilterDates() { appData.filter.showAll = false if appData.filter.filterObjects.startDateField.text == "" { appData.filter.filterObjects.startDateField.text = "\(appData.stringDate(appData.filter.filterObjects.startDatePicker))" } if appData.filter.filterObjects.endDateField.text == "" { appData.filter.filterObjects.endDateField.text = "\(appData.stringDate(appData.filter.filterObjects.endDatePicker))" } appData.filter.from = appData.filter.filterObjects.startDateField.text! appData.filter.to = appData.filter.filterObjects.endDateField.text! selectedPeroud = "\(appData.filter.from) → \(appData.filter.to)" filterTextLabel.text = "Filter: \(selectedPeroud)" } func showNoDataLabel() { if tableData.count == 0 { UIView.animate(withDuration: 0.2) { self.noTableDataLabel.alpha = 0.5 } } else { UIView.animate(withDuration: 0.2) { self.noTableDataLabel.alpha = 0 } } } func removeBackground() { buttonsFilterView.alpha = 0 thisMonthFilterButton.backgroundColor = K.Colors.pink customButton.backgroundColor = K.Colors.pink todayButton.backgroundColor = K.Colors.pink allTimeButton.backgroundColor = K.Colors.pink } func hideFilterView() { UIView.animate(withDuration: 0.3) { self.buttonsFilterView.alpha = 0 self.pressToShowFilterButtons.backgroundColor = K.Colors.background self.filterTextLabel.textColor = K.Colors.balanceT self.pressToShowFilterButtons.layer.shadowColor = UIColor.clear.cgColor } pressToShowFilterButtons.layer.shadowOpacity = 0 pressToShowFilterButtons.layer.shadowOffset = .zero pressToShowFilterButtons.layer.shadowRadius = 0 } func showFilterView() { UIView.animate(withDuration: 0.3) { self.buttonsFilterView.alpha = 1 self.pressToShowFilterButtons.backgroundColor = K.Colors.pink self.filterTextLabel.textColor = K.Colors.balanceV self.pressToShowFilterButtons.layer.shadowColor = UIColor.black.cgColor } pressToShowFilterButtons.layer.shadowOpacity = 0.2 pressToShowFilterButtons.layer.shadowOffset = .zero pressToShowFilterButtons.layer.shadowRadius = 6 } func toggleFilterView() { if buttonsFilterView.alpha == 1 { hideFilterView() } else { showFilterView() } } @IBAction func showFilterPressed(_ sender: UIButton) { toggleFilterView() } @IBAction func filterOptionsPressed(_ sender: UIButton) { UIView.animate(withDuration: 0.3) { self.pressToShowFilterButtons.backgroundColor = K.Colors.background } removeBackground() sender.backgroundColor = K.Colors.yellow switch sender.tag { case 0: appData.filter.showAll = true appData.filter.from = "" appData.filter.to = "" performFiltering() loadItems() selectedPeroud = "All time" case 1: appData.filter.showAll = false appData.filter.from = appData.filter.getFirstDay(appData.filter.filterObjects.currentDate) appData.filter.to = appData.filter.getLastDay(appData.filter.filterObjects.currentDate) performFiltering() loadItems() selectedPeroud = "This Month" case 2: appData.filter.showAll = false appData.filter.from = appData.stringDate(appData.filter.filterObjects.currentDate) appData.filter.to = appData.stringDate(appData.filter.filterObjects.currentDate) performFiltering() loadItems() selectedPeroud = "Today" case 3: showFilterAlert() pressToShowFilterButtons.layer.shadowColor = UIColor.clear.cgColor default: loadItems() } filterTextLabel.text = "Filter: \(selectedPeroud)" if sender.tag == 3 { filterTextLabel.text = "Filter: Custom..." } } @IBAction func statisticLabelPressed(_ sender: UIButton) { switch sender.tag { case 0: expenseLabelPressed = true case 1: expenseLabelPressed = false default: expenseLabelPressed = true } performSegue(withIdentifier: K.statisticSeque, sender: self) } @IBAction func unwindToViewControllerA(segue: UIStoryboardSegue) { DispatchQueue.global(qos: .userInitiated).async { DispatchQueue.main.async { self.performFiltering() self.loadItems() editingDate = "" editingCategory = "" editingValue = 0.0 } } } func dimNewCell(_ transactionsCell: mainVCcell, index: Int) { if transactionsCell.bigDate.text == highliteDate { DispatchQueue.main.async { self.mainTableView.scrollToRow(at: IndexPath(row: index, section: 1), at: .top, animated: true) } UIView.animate(withDuration: 0.6) { transactionsCell.contentView.backgroundColor = K.Colors.separetor } Timer.scheduledTimer(withTimeInterval: 0.6, repeats: false) { (timer) in UIView.animate(withDuration: 0.6) { transactionsCell.contentView.backgroundColor = K.Colors.background highliteDate = " " } } } } func deleteRow(at: Int) { appData.context.delete(tableData[at]) self.tableData.remove(at: at) self.saveItems() self.loadItems() } func editRow(at: Int) { editingDate = tableData[at].date ?? "" editingValue = tableData[at].value editingCategory = tableData[at].category ?? "" performSegue(withIdentifier: K.goToEditVCSeq, sender: self) deleteRow(at: at) } } @available(iOS 13.0, *) extension ViewController: UITableViewDataSource, UITableViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case 0: return 1 case 1: return tableData.count case 2: if tableData.count < 3 { return 0 } else { return 1 } default: return 0 } } func numberOfSections(in tableView: UITableView) -> Int { return 3 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch indexPath.section { case 0: let calculationCell = tableView.dequeueReusableCell(withIdentifier: K.calcCellIdent, for: indexPath) as! calcCell calculationCell.setupCell(totalBalance) return calculationCell case 1: let data = tableData[indexPath.row] let transactionsCell = tableView.dequeueReusableCell(withIdentifier: K.mainCellIdent, for: indexPath) as! mainVCcell transactionsCell.setupCell(data, i: indexPath.row, tableData: tableData) dimNewCell(transactionsCell, index: indexPath.row) return transactionsCell case 2: let highestExpenseCell = tableView.dequeueReusableCell(withIdentifier: K.plotCellIdent, for: indexPath) as! PlotCell highestExpenseCell.setupCell() return highestExpenseCell default: return UITableViewCell() } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { switch indexPath.section { case 0: hideFilterView() expenseLabelPressed = true performSegue(withIdentifier: K.statisticSeque, sender: self) case 1: hideFilterView() case 2: hideFilterView() expenseLabelPressed = true performSegue(withIdentifier: K.statisticSeque, sender: self) default: hideFilterView() } } func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? { if indexPath.section == 1 { let editeAction = UIContextualAction(style: .destructive, title: "Edit") { (contextualAction, view, boolValue) in self.editRow(at: indexPath.row) } let deleteAction = UIContextualAction(style: .destructive, title: "Delete") { (contextualAction, view, boolValue) in self.deleteRow(at: indexPath.row) } editeAction.backgroundColor = K.Colors.yellow deleteAction.backgroundColor = K.Colors.negative return UISwipeActionsConfiguration(actions: [editeAction, deleteAction]) } else { return UISwipeActionsConfiguration(actions: []) } } func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) { if indexPath.section == 0 { UIView.animate(withDuration: 0.3) { self.calculationSView.alpha = 1 } filterView.alpha = 0 hideFilterView() } } func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { if indexPath.section == 0 { filterView.alpha = 1 UIView.animate(withDuration: 0.3) { self.calculationSView.alpha = 0 } } } }
// // ViewController.swift // AUPickerCellExample // // Created by Aziz Uysal on 3/26/17. // Copyright © 2017 Aziz Uysal. All rights reserved. // import UIKit import AUPickerCell class ViewController: UITableViewController, AUPickerCellDelegate { override func numberOfSections(in tableView: UITableView) -> Int { return 2 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.section == 0 { let cell = AUPickerCell(type: .default, reuseIdentifier: "PickerDefaultCell") cell.delegate = self cell.separatorInset = UIEdgeInsets.zero cell.values = ["One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten"] cell.selectedRow = 2 cell.leftLabel.text = "Testing Strings" cell.leftLabel.textColor = UIColor.lightText cell.rightLabel.textColor = UIColor.darkText cell.tintColor = #colorLiteral(red: 0.9382581115, green: 0.8733785748, blue: 0.684623003, alpha: 1) cell.backgroundColor = #colorLiteral(red: 0.6344745755, green: 0.5274511576, blue: 0.4317585826, alpha: 1) return cell } else { let cell = AUPickerCell(type: .date, reuseIdentifier: "PickerDateCell") cell.delegate = self cell.separatorInset = UIEdgeInsets.zero cell.datePickerMode = .time cell.timeZone = TimeZone(abbreviation: "UTC") cell.dateStyle = .none cell.timeStyle = .short cell.leftLabel.text = "Testing Dates" cell.leftLabel.textColor = UIColor.lightText cell.rightLabel.textColor = UIColor.darkText cell.tintColor = #colorLiteral(red: 0.9382581115, green: 0.8733785748, blue: 0.684623003, alpha: 1) cell.backgroundColor = #colorLiteral(red: 0.6344745755, green: 0.5274511576, blue: 0.4317585826, alpha: 1) cell.separatorHeight = 1 cell.unexpandedHeight = 100 return cell } } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if let cell = tableView.cellForRow(at: indexPath) as? AUPickerCell { return cell.height } return super.tableView(tableView, heightForRowAt: indexPath) } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) if let cell = tableView.cellForRow(at: indexPath) as? AUPickerCell { cell.selectedInTableView(tableView) } } func auPickerCell(_ cell: AUPickerCell, didPick row: Int, value: Any) { print(value) } }
// // Constants.swift // Fix Colors // // Created by Nurassyl Nuridin on 4/11/17. // Copyright © 2017 Nurassyl Nuridin. All rights reserved. // import SpriteKit let MainSize = UIScreen.main.bounds.size let BgColor: SKColor = SKColor(red: 56.0/255.0, green: 84.0/255.0, blue: 116.0/255.0, alpha: 1.0) let FontColor: SKColor = SKColor(red: 255.0/255.0, green: 255.0/255.0, blue: 255.0/255.0, alpha: 1.0) let MovesColor: SKColor = SKColor(red: 93.0/255.0, green: 152.0/255.0, blue: 105.0/255.0, alpha: 1.0) let GoldenColor: SKColor = SKColor(red: 172.0/255.0, green: 148.0/255.0, blue: 82.0/255.0, alpha: 1.0) let MainFont: String = "Courier-Bold" let MaxLevel: Int = 60 let Treshold: CGFloat = 10.0 struct SpriteNames { static let PlayButtonName: String = "PLAY_BUTTON" static let RateUsButtonName: String = "RATE_US_BUTTON" static let ShareButtonName: String = "SHARE_BUTTON" static let PauseButtonName: String = "PAUSE_BUTTON" static let LevelsButtonName: String = "LEVELS_BUTTON" static let BackButtonName: String = "BACK_BUTTON" static let ReplayButtonName: String = "REPLAY_BUTTON" static let TutorialButtonName: String = "TUTORIAL_BUTTON" static let MuteButtonName: String = "MUTE_BUTTON" static let UnmuteButtonName: String = "UNMUTE_BUTTON" static let LevelSpriteName: String = "LEVEL_SPRITE" static let LeftName: String = "LEFT" static let RightName: String = "RIGHT" static let DotSpriteName: String = "DOT" static let BlueOvalName: String = "BLUE_OVAL" static let RedOvalName: String = "RED_OVAL" static let GreenOvalName: String = "GREEN_OVAL" static let YellowOvalName: String = "YELLOW_OVAL" static let PurpleOvalName: String = "PURPLE_OVAL" static let OrangeOvalName: String = "ORANGE_OVAL" static let BlueTileName: String = "BLUE_TILE" static let RedTileName: String = "RED_TILE" static let GreenTileName: String = "GREEN_TILE" static let YellowTileName: String = "YELLOW_TILE" static let PurpleTileName: String = "PURPLE_TILE" static let OrangeTileName: String = "ORANGE_TILE" } struct Titles { static let GameTitle: String = "FIX COLORS" static let CompletedTitle: String = "COMPLETED" static let LevelTitle: String = "LEVELS" static let TutorialsTitle: String = "TUTORIAL" static let ComingSoonTitle: String = "COMING SOON" } struct Names { static let MuteButtonName: String = "MuteButtonName" static let UnmuteButtonName: String = "UnmuteButtonName" static let LabelShadowName: String = "LabelShadowName" } struct SoundNames { static let ButtonClickSoundName: String = "button_click_sound" static let CompletionSoundName: String = "completion_sound" static let SwishSoundName: String = "swish_sound" static let GridSwishSoundName: String = "grid_swish_sound" } struct ActionNames { static let BlinkOvalName = "BlinkOvalName" static let BackActionName = "BackActionName" } struct SNames { static let SoundSName: String = "SoundSName" static let CurrentLevelSName: String = "CurrentLevelSName" static let CompletedLevelsSName: String = "CompletedLevelsSName" static let AllMovesSName: String = "AllMovesSName" } extension SKNode { func returnScaleFactor() -> CGFloat { return self.xScale } } extension Dictionary { static func loadJSONfromBundle(filename: String) -> Dictionary<String, AnyObject>? { var dataOk: Data var dicOK: NSDictionary = NSDictionary() if let path = Bundle.main.url(forResource: filename, withExtension: "json") { let _: Error? do { let data = try Data(contentsOf: path, options: Data.ReadingOptions()) dataOk = data } catch { print("Could not load level file: \(filename), error: \(error)") return nil } do { let dictionary = try JSONSerialization.jsonObject(with: dataOk, options: JSONSerialization.ReadingOptions()) as AnyObject! dicOK = (dictionary as? Dictionary<String, AnyObject>) as NSDictionary! } catch { print("Level file: \(filename) is not valid JSON: \(error)") return nil } } return dicOK as? Dictionary<String, AnyObject> } } extension Int { func getLevelName() -> String { return self < 10 ? "#00\(self)" : self < 100 ? "#0\(self)" : "#\(self)" } } extension SKLabelNode { func setShadow() { self.horizontalAlignmentMode = .center self.verticalAlignmentMode = .center let shadow = SKLabelNode(fontNamed: MainFont) shadow.text = self.text shadow.zPosition = self.zPosition - 1.0 shadow.fontColor = SKColor.black if self.fontSize > 20.0 { shadow.position = CGPoint(x: 0.0, y: -2.3) } else { shadow.position = CGPoint(x: 0.0, y: -1.6) } shadow.fontSize = self.fontSize shadow.horizontalAlignmentMode = .center shadow.verticalAlignmentMode = .center shadow.alpha = 0.6 shadow.name = Names.LabelShadowName self.addChild(shadow) } func updateShadowNode() { if let shadow = self.childNode(withName: Names.LabelShadowName) as? SKLabelNode { shadow.text = self.text } } }
/* * This file is part of Adblock Plus <https://adblockplus.org/>, * Copyright (C) 2006-present eyeo GmbH * * Adblock Plus is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as * published by the Free Software Foundation. * * Adblock Plus is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Adblock Plus. If not, see <http://www.gnu.org/licenses/>. */ import Foundation public final class ContentScript: NSObject { @objc public let allFrames: Bool public let filenames: [String] @objc public let runAt: String public let matches: [NSPredicate] public let excludeMatches: [NSPredicate] init(json: Any?) throws { let object = try parse(json) as [AnyHashable: Any] allFrames = try parse(object["all_frames"], defaultValue: false) filenames = try parse(object["js"], defaultValue: []) runAt = try parse(object["run_at"], defaultValue: "document_end") matches = try predicates(from: try parse(object["matches"])) excludeMatches = try predicates(from: parse(object["exclude_matches"], defaultValue: [])) } @objc public func applicableOnContentURL(_ url: URL) -> Bool { if excludeMatches.count > 0 { for excludeMatch in excludeMatches { if excludeMatch.evaluate(with: url.absoluteString) { return false // exclusion match } } } // no exclusion match, continue with includes (blacklist-whitelist order) if matches.count > 0 { for matche in matches { if matche.evaluate(with: url.absoluteString) { return true } } } return false } } private func predicates(from patterns: [String]) throws -> [NSPredicate] { return try patterns.map { pattern in do { let regex = try (pattern as NSString).regex(fromChromeGlobPattern: pattern) return NSPredicate(format: "SELF MATCHES %@", regex.pattern) } catch let error { throw Utils.error(forWrappingError: error, message: "Pattern bad format '\(pattern)'") } } }
// // CarVC.swift // Shopping_W // // Created by wanwu on 2017/5/22. // Copyright © 2017年 wanwu. All rights reserved. // import UIKit import MBProgressHUD import Realm import RealmSwift class CarVC: UIViewController, UITableViewDelegate { @IBOutlet weak var tableVIew: RefreshTableView! @IBOutlet weak var submitBtn: UIButton! @IBOutlet weak var allPriceLabel: UILabel! @IBOutlet weak var selectAllBtn: UIButton! static var needsReload = false var carList = [CarListModel]() override func viewDidLoad() { super.viewDidLoad() setupTableView() submitBtn.layer.cornerRadius = CustomValue.btnCornerRadius submitBtn.layer.masksToBounds = true tableVIew.addHeaderAction { self.requestData() } tableVIew.beginHeaderRefresh() } func requestData() { if !PersonMdel.isLogined() { self.carList = CarModel.readTreeDataFromDB() self.updateView() DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5, execute: { self.tableVIew.endHeaderRefresh() }) return } NetworkManager.requestListModel(params: ["method":"apimyshopcartlist"]).setSuccessAction { (bm: BaseModel<CarListModel>) in self.tableVIew.endHeaderRefresh() bm.whenSuccess { self.carList = bm.list! self.updateView() } }.seterrorAction { (err) in self.tableVIew.endHeaderRefresh() } } func updateView() { var arr = [[CarModel]]() for item in self.carList { arr.append(self.dealModels(models: item.goodList)) for goods in item.goodList { goods.carList = item } } self.tableVIew.dataArray = arr self.tableVIew.reloadData() let notSelected = (arr.flatMap({ $0 })).filter({ !$0.isSelected }) self.selectAllBtn.isSelected = arr.count > 0 && notSelected.count < 1 self.updateAllPrice() } func dealModels(models: [CarModel]) -> [CarModel] { let arr = models.map({ (model) -> CarModel in model.build(cellClass: CarTableViewCell.self) .build(isFromStoryBord: true) .build(heightForRow: 120) model.countAction = { _ in self.updateAllPrice() } model.setupCellAction { [unowned self] (idx) in let vc = Tools.getClassFromStorybord(sbName: .shoppingCar, clazz: GoodsDetailVC.self) switch model.fType { case 0: vc.type = .normal case 1: vc.type = .group case 2: vc.type = .seckill case 3, 4, 5, 6: vc.type = .promotions default: break } vc.promotionid = model.fPromotionid vc.goodsId = model.fGoodsid vc.picUrl = model.fGoodimg self.navigationController?.pushViewController(vc, animated: true) } return model }) for item in arr { item.selectedAction = { [unowned self] _ in if !self.updateByAllBtn { for model in arr { if !model.isSelected { self.selectAllBtn.isSelected = false return } } let notSelected = arr.filter({ !$0.isSelected }) self.selectAllBtn.isSelected = arr.count > 0 && notSelected.count < 1 self.updateAllPrice() self.tableVIew.reloadData() } } } CarModel.items = arr return arr } func setupTableView() { tableVIew.delegate = self let nib = UINib(nibName: "CarSectionHeader", bundle: Bundle.main) tableVIew.register(nib, forHeaderFooterViewReuseIdentifier: "CarSectionHeader") } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if self.tableVIew.dataArray.count > 0 { let arr = self.tableVIew.dataArray.flatMap({$0}) as! [CarModel] let notSelected = arr.filter({ !$0.isSelected }) self.selectAllBtn.isSelected = arr.count > 0 && notSelected.count < 1 } if CarVC.needsReload { self.tableVIew.beginHeaderRefresh() CarVC.needsReload = false } if let nav = self.tabBarController?.viewControllers?.first as? UINavigationController { nav.popToRootViewController(animated: true) } self.updateAllPrice() } func updateAllPrice() { if self.tableVIew.dataArray.count < 1 { return } var price = 0.0 let arr = self.tableVIew.dataArray.flatMap({ $0 }) as! [CarModel] for model in arr { if model.isSelected { switch model.fType { case 0, 4 , 5: price += Double(model.fCount) * model.fSalesprice case 1, 2: price += Double(model.fCount) * model.fPromotionprice case 3: let p = Double(model.fCount) * model.fSalesprice price += p >= model.fPrice ? p - model.fPrice : p case 6: price += Double(model.fCount) * model.fSalesprice * (model.fDiscount / 100) default: break } } } self.allPriceLabel.text = "¥" + price.moneyValue() } private var updateByAllBtn = false @IBAction func ac_selectAll(_ sender: UIButton) { if !sender.isSelected { let arr = self.tableVIew.dataArray.flatMap({ $0 }) as! [CarModel] for m in arr { if m.fType == 0 { break } if m.fState == 0 { MBProgressHUD.show(errorText: "商品已不在销售状态") return } if m.fType == 0 { if m.fCount > m.fStock { MBProgressHUD.show(errorText: "库存不足") return } } else { if m.fCount + m.fBuycount > m.fPurchasecount { MBProgressHUD.show(errorText: "超过限购数量") return } } } } sender.isSelected = !sender.isSelected if self.tableVIew.dataArray.count < 1 { return } updateByAllBtn = true for item in self.tableVIew.dataArray.flatMap({$0}) { let model = item as! CarModel model.isSelected = sender.isSelected } self.tableVIew.reloadData() updateByAllBtn = false self.updateAllPrice() } @IBAction func ac_submit(_ sender: UIButton) { if LoginVC.showLogin() || self.tableVIew.dataArray.isEmpty { return } let selectedArr = self.tableVIew.dataArray.flatMap({$0}) .filter({ (item) -> Bool in return (item as! CarModel).isSelected }) if selectedArr.isEmpty { return } let vc = OrderDetailVC() vc.showPayBtn = true vc.carModels = (selectedArr as! [CarModel]) self.navigationController?.pushViewController(vc, animated: true) } //MARK: 代理 func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: "CarSectionHeader") as! CarSectionHeader let model = carList[section] header.titleLabel.text = model.fShopName header.icon.sd_setImage(with: URL.encodeUrl(string: model.fImgurl), placeholderImage: #imageLiteral(resourceName: "店铺")) header.selectBtn.isSelected = model.isListSelected header.selectAction = { [unowned self] _ in for m in model.goodList { if m.fType == 0 { break } if m.fState == 0 { MBProgressHUD.show(errorText: "商品已不在销售状态") return } if m.fType == 0 { if m.fCount > m.fStock { MBProgressHUD.show(errorText: "库存不足") return } } else { if m.fCount + m.fBuycount > m.fPurchasecount { MBProgressHUD.show(errorText: "超过限购数量") return } } } model.isListSelected = !model.isListSelected model.setSelected() self.tableVIew.reloadSections([section], with: .none) } header.selectBtn.isSelected = model.goodList.filter({ !$0.isSelected }).count == 0 return header } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 38 } func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { let a = UITableViewRowAction(style: .default, title: "删除") { (action, idx) in if let model = self.tableVIew.dataArray[indexPath.section][indexPath.row] as? CarModel { if !PersonMdel.isLogined() { model.deleteFromDB() self.tableVIew.dataArray[indexPath.section].remove(at: indexPath.row) self.tableVIew.deleteRows(at: [indexPath], with: UITableViewRowAnimation.left) return } MBProgressHUD.showAdded(to: self.view, animated: true) model.delete(complete: { [unowned self] _ in MBProgressHUD.hideHUD(forView: self.view) self.tableVIew.dataArray[indexPath.section].remove(at: indexPath.row) if self.tableVIew.dataArray[indexPath.section].isEmpty { self.tableVIew.dataArray.remove(at: indexPath.section) tableView.deleteSections(IndexSet(integer: indexPath.section), with: .left) } else { self.tableVIew.deleteRows(at: [indexPath], with: UITableViewRowAnimation.left) } }) } } return [a] } }
// // APIResource.swift // StackExchange // // Created by John Ellie Go on 4/5/21. // import Foundation protocol APIResource { associatedtype ModelType: Decodable var methodPath: String { get } var filter: String? { get } } extension APIResource { var url: URL { var components = URLComponents(string: "https://api.stackexchange.com/2.2")! components.path = methodPath components.queryItems = [ URLQueryItem(name: "site", value: "stackoverflow"), URLQueryItem(name: "order", value: "desc"), URLQueryItem(name: "sort", value: "votes"), URLQueryItem(name: "tagged", value: "swiftui"), URLQueryItem(name: "pagesize", value: "10") ] if let filter = filter { components.queryItems?.append(URLQueryItem(name: "filter", value: filter)) } return components.url! } } struct Wrapper<T: Decodable>: Decodable { let items: [T] } // MARK: - Question Resource struct QuestionsResource: APIResource { typealias ModelType = Question var id: Int? var methodPath: String { guard let id = id else { return "/questions" } return "/questions/\(id)" } var filter: String? { id != nil ? "!9_bDDxJY5" : nil } }
// // SecureStoreQueryable.swift // JobFair // // Created by Bogdan Kostyuchenko on 30.08.2020. // Copyright © 2020 Bogdan Kostyuchenko. All rights reserved. // import Foundation public protocol SecureStoreQueryable { var query: [String: Any] { get } }
// // NYCSchoolsMainViewController.swift // 20210827-[DavidSchechter]-NYCSchools // // Created by David Schechter on 8/27/21. // import UIKit import Combine class NYCSchoolsMainViewController: UIViewController { //MARK: IBOutlet @IBOutlet weak var loadingIndicator: UIActivityIndicatorView! @IBOutlet weak var tableView: UITableView! //MARK: Public Paramters let viewModel: NYCSchoolsViewModelProtocol = NYCSchoolsViewModel(dataManager: DataManager()) //MARK: Private Paramters private let searchController = UISearchController(searchResultsController: nil) private var cancellables = Set<AnyCancellable>() private var currectData: [NYCHighSchool] = [NYCHighSchool]() //MARK: Lifecycle Methods override func viewDidLoad() { super.viewDidLoad() setSearchController() bindViewModel() tableView.isHidden = true loadingIndicator.isHidden = false loadingIndicator.startAnimating() viewModel.getData() } // MARK: Helper Methods private func setSearchController() { searchController.searchResultsUpdater = self searchController.obscuresBackgroundDuringPresentation = false searchController.searchBar.placeholder = "Search by Name" searchController.searchBar.tintColor = UIColor.black navigationItem.searchController = searchController definesPresentationContext = true } private func bindViewModel() { viewModel.modelPublisher .sink { [weak self] schools in self?.currectData = schools self?.tableView.reloadData() self?.tableView.isHidden = false self?.loadingIndicator.isHidden = true self?.loadingIndicator.stopAnimating() } .store(in: &cancellables) viewModel.filteredPublisher .sink(receiveValue: { [weak self] schools in if let schools = schools { self?.currectData = schools self?.tableView.reloadData() } }) .store(in: &cancellables) viewModel.titlePublisher .sink(receiveValue: { [weak self] title in self?.title = title }) .store(in: &cancellables) } // MARK: Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "ShowSchoolDetails" { let highSchoolWithSATScoreVC = segue.destination as! NYCSchoolDetailsViewController if let school = sender as? NYCHighSchool { highSchoolWithSATScoreVC.currectData = school } } } } // MARK: - UITableViewDataSource extension NYCSchoolsMainViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return currectData.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "NYCSchoolOverviewTableViewCell") as! NYCSchoolOverviewTableViewCell cell.configureWithModel(currectData[indexPath.row]) return cell } } // MARK: - UITableViewDelegate extension NYCSchoolsMainViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { self.performSegue(withIdentifier: "ShowSchoolDetails", sender: currectData[indexPath.row]) } } // MARK: - UISearchResultsUpdating extension NYCSchoolsMainViewController: UISearchResultsUpdating { func updateSearchResults(for searchController: UISearchController) { viewModel.filterByName(searchController.searchBar.text) } }
// // EtherKeystoreManagementSpec.swift // LooisKitTests // // Created by Daven on 2018/8/9. // Copyright © 2018年 Loois. All rights reserved. // import Foundation import Quick import Nimble import TrustCore @testable import LooisKit final class EtherKeystoreManagementSpec: QuickSpec { override func spec() { let timeout = 10.0 var keystore: EtherKeystore! var wallet: Wallet! beforeSuite { keystore = EtherKeystore(keysSubfolder: "/keystore_test_management") if keystore.wallets.count == 0 { let words = "length ball music side ripple wide armor army panel message crime garage".components(separatedBy: " ") let password = "12345678" keystore.buildWallet(type: .mnemonic(words: words, newPassword: password), completion: { (result) in wallet = result.value }) } else { wallet = keystore.wallets.first } } describe("manage wallet") { beforeEachWithMetadata({ (meta) in print("-------\(meta?.exampleIndex ?? -1)-------", wallet?.identifier ?? "wallet is being prepared") expect(wallet).toEventuallyNot(beNil(), timeout: timeout) }) it("update wallet password by using correct password", closure: { var res: Bool! keystore.update(wallet: wallet, password: "12345678", newPassword: "87654321", completion: { (result) in res = result.value }) expect(res).toEventually(beTrue(), timeout: timeout) keystore.update(wallet: wallet, password: "87654321", newPassword: "12345678", completion: { (result) in res = result.value }) expect(res).toEventually(beTrue(), timeout: timeout) }) it("update wallet password by using incorrect password", closure: { var error: KeystoreError! keystore.update(wallet: wallet, password: "---", newPassword: "87654321", completion: { (result) in error = result.error }) expect(error?.localizedDescription).toEventually(equal(KeystoreError.failedToUpdatePassword.localizedDescription), timeout: timeout) }) it("delete wallet by using incorrect password", closure: { var error: KeystoreError! keystore.delete(wallet: wallet, password: "====", completion: { (result) in error = result.error }) expect(error?.localizedDescription).toEventually(equal(KeystoreError.failedToDeleteAccount.localizedDescription), timeout: timeout) }) it("delete wallet by using correct password", closure: { var wallet: Wallet! keystore.buildWallet(type: BuildType.create(newPassword: "12345678"), completion: { (result) in wallet = result.value }) expect(wallet).toEventuallyNot(beNil(), timeout: timeout) var res: Bool! keystore.delete(wallet: wallet, password: "12345678", completion: { (result) in res = result.value }) expect(res).toEventually(beTrue(), timeout: timeout) }) } } }
// // User.swift // RandomUserApp // // Created by Dawid Markowski on 05.07.2016. // Copyright © 2016 Dawid Markowski. All rights reserved. // import UIKit import SwiftyJSON class User { let firstName: String let lastName: String let photoURL: NSURL var usersPhoto: UIImage? init(firstName: String, lastName: String, photoURL: NSURL, usersPhoto: UIImage?) { self.firstName = firstName self.lastName = lastName self.photoURL = photoURL self.usersPhoto = usersPhoto } }
import UIKit var str = "=== Jumps calculator" func solution(n: Int) -> Int { if (n <= 1) { return 1 } else if (n == 2) { return 2 } var res: [Int] = [1,1,2] for index in 3...n-1{ res.append(res[index - 1] + res[index - 2] + res[index - 3]) } return res.last! } print(solution(n: 1)) print(solution(n: 39))
// // StoryboardResource.swift // Resource // // Created by Justin Jia on 11/14/16. // Copyright © 2016 TintPoint. MIT license. // /// A protocol that describes an item that can represent a storyboard. public protocol StoryboardDescribing { /// The `String` that represents the name of the storyboard. var name: String { get } /// The `Bundle` that represents the bundle of the storyboard. var bundle: Bundle { get } } public extension StoryboardDescribing { var bundle: Bundle { return Bundle.main } } /// A struct that describes an item that can represent a storyboard. public struct StoryboardDescription: StoryboardDescribing { /// The `String` that represents the name of the storyboard. public let name: String /// The `Bundle` that represents the bundle of the storyboard. public let bundle: Bundle public init(name: String, bundle: Bundle = Bundle.main) { self.name = name self.bundle = bundle } } public extension Resource { /// Returns a `UIStoryboard` that is represented by the item that conforms to `StoryboardDescribing`. /// - Parameter describing: An item that conforms to `StoryboardDescribing`. /// - Returns: A represented storyboard. static func of(_ describing: StoryboardDescribing) -> UIStoryboard { return UIStoryboard(name: describing.name, bundle: describing.bundle) } }
// // FlikrImageCollectionViewController.swift // FlikrFeed // // Created by Apple on 24/03/2017. // Copyright © 2017 me. All rights reserved. // import UIKit private let reuseIdentifier = "image_cell" class FlickrImageCollectionViewController: UICollectionViewController { let queue1 = DispatchQueue(label: "com.mycompany.app.myqueue.1", qos: .userInitiated) let queue2 = DispatchQueue(label: "com.mycompany.app.myqueue.2", qos: .background) var api_key: String? var flickrPhotos: [Photo] = [] var urlArray: [String] = [] var urlArraySmall: [String] = [] var tag: String? var number: Int? override func viewDidLoad() { super.viewDidLoad() if let path = Bundle.main.path(forResource: "config", ofType: "plist"), let data = NSDictionary(contentsOfFile: path), let dict = data as? Dictionary<String, String> { api_key = dict["api_key"] print("******** api_key ********", api_key! ) /*for dict in (data as! [Dictionary<String, String>]) { quotes.append(Quote(author: dict["author"] ?? "unknow", body: dict["body"] ?? "unknow")) }*/ } else { print("******** api_key ********", "no api key") } FlickrService.sharedInstance.getPhotos(apiKey: api_key!, forTag: tag!, forNumber: number!) { (photos: [Photo]) in DispatchQueue.main.async { self.flickrPhotos = photos self.collectionView!.reloadData() for img in self.flickrPhotos { //print("********* url *********", img.getUrl_small()) self.urlArraySmall.append(img.getUrl_small()) self.urlArray.append(img.getUrl(size: "c")) } print("queue 1 : done") } } print(self.flickrPhotos) // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Register cell classes //self.collectionView!.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier) // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "image_detail_segue" { if let imageDetailController = segue.destination as? ImageDetailViewController { guard let cell = sender as? ImageCollectionViewCell else { print("error") return } //imageDetailController.image = cell.imageView.image! imageDetailController.url = cell.url } } } // MARK: UICollectionViewDataSource override func numberOfSections(in collectionView: UICollectionView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of items return flickrPhotos.count } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! ImageCollectionViewCell let urlString = URL(string: self.urlArraySmall[indexPath.row]) if let url = urlString { let urlTask = URLSession.shared.dataTask(with: url) { (data, response, error) in if error != nil { print(error ?? "error urlTask") } else { if let usableData = data { DispatchQueue.main.async { cell.imageView.image = UIImage(data: usableData) cell.lblTitle.text = self.flickrPhotos[indexPath.row].title cell.url = self.urlArray[indexPath.row] print("queue 2 . \(indexPath.row) : done") } } } } urlTask.resume() } //let url = URLSession(string: self.urlArraySmall[indexPath.row]) //let data = try? Data(contentsOf: url!) //} //print(image ?? "error") //print("usableData \(usableData)") return cell } // MARK: UICollectionViewDelegate /* // Uncomment this method to specify if the specified item should be highlighted during tracking override func collectionView(_ collectionView: UICollectionView, shouldHighlightItemAt indexPath: IndexPath) -> Bool { return true } */ /* // Uncomment this method to specify if the specified item should be selected override func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool { return true } */ /* // Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item override func collectionView(_ collectionView: UICollectionView, shouldShowMenuForItemAt indexPath: IndexPath) -> Bool { return false } override func collectionView(_ collectionView: UICollectionView, canPerformAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) -> Bool { return false } override func collectionView(_ collectionView: UICollectionView, performAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) { } */ }
// // CustomGestureRecognizer.swift // SwiftRecognizer // // Created by Mike Mikina on 2/14/16. // Copyright © 2016 FDT. All rights reserved. // import UIKit import UIKit.UIGestureRecognizerSubclass class CustomGestureRecognizer: UIGestureRecognizer { var pathFinder: PathFinder? var touchedPoints = [CGPoint]() var path = CGPathCreateMutable() var lastPoint = CGPoint.zero var red: CGFloat = 0.0 var green: CGFloat = 0.0 var blue: CGFloat = 0.0 var brushWidth: CGFloat = 5.0 var opacity: CGFloat = 1.0 var swiped = false var recognizedShape: GestureModel? override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent) { super.touchesBegan(touches, withEvent: event) touchedPoints.removeAll() let window = view?.window if let loc = touches.first?.locationInView(window) { CGPathMoveToPoint(path, nil, loc.x, loc.y) // start the path } if touches.count != 1 { state = .Failed } state = .Began self.recognizedShape = nil } override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent) { super.touchesEnded(touches, withEvent: event) if let pathFinder = self.pathFinder { let points = pathFinder.getDirections(self.touchedPoints) self.recognizedShape = pathFinder.recognizeShape(points) if let _ = self.recognizedShape { state = .Ended } else { state = .Failed } } } override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent) { super.touchesMoved(touches, withEvent: event) if state == .Failed { return } let window = view?.window if let loc = touches.first?.locationInView(window) { touchedPoints.append(loc) CGPathAddLineToPoint(path, nil, loc.x, loc.y) state = .Changed } } }
func intro() -> String { return ("Hi I am Pragyee") } //call the function print (intro())
// // Node.swift // node_view_framework // // Created by Kelong Wu on 2/15/17. // Copyright © 2017 alien_robot_cat. All rights reserved. // import Foundation class Node { var id: Int = -1 var type: Int = -1 var data: [String: String] = [:] var rules: [String:Any] = ["Touch": ["1", "Expand"] , "Expand":["0"], "Save":["0"], "Update":["0"]] init(){ } init(id:Int) { self.id = id } init(id: Int, type: Int, data: [String:String]){ self.id = id self.type = type self.data = data } }
// // LocationVC.swift // Lex // // Created by nbcb on 2016/12/26. // Copyright © 2016年 ZQC. All rights reserved. // import UIKit class LocationVC: BaseViewController, LocationSearchDelegate, AMapSearchDelegate { @IBOutlet weak var searchBtn : UIButton! var selectIndex : Int = 0 var hiddenSearch : Bool = false var isFirstLoading : Bool = true //是否是第一次定位 var displayMap : Bool = true //地图状态:是否展开 let minTableView_h : CGFloat = app_height - 379 let maxTableView_h : CGFloat = app_height - 244 let tableView_y : CGFloat = 379.0 let minMap_h : CGFloat = 135.0 let maxMap_h : CGFloat = 270.0 let headerYOffSet : CGFloat = 109.0 let default_Y_tableView : CGFloat = 244.0 var contentOffsetY : CGFloat = 0 var dataArray : Array<AMapPOI> = [] var locationBlock : ReturnLocationBlock? override func viewDidLoad() { super.viewDidLoad() UIApplication.shared.statusBarStyle = UIStatusBarStyle.lightContent self.view.addSubview(self.naBar) self.setupMapView() self.initSearchs() self.setupTableView() self.registerCell() } func registerCell() { self.tableView.register(UINib.init(nibName: "LocationCell", bundle: nil), forCellReuseIdentifier: "LocationCell") } func setupTableView() { self.view.addSubview(self.tableView) self.tableView.addSubview(self.activity) weak var weakSelf = self self.activity.snp.makeConstraints { (make) in make.centerX.equalTo((weakSelf?.tableView.centerX)!) make.top.equalTo(10) make.size.equalTo(CGSize.init(width: 37, height: 37)) } } lazy var activity : UIActivityIndicatorView = { let activity : UIActivityIndicatorView = UIActivityIndicatorView.init(activityIndicatorStyle: .gray) activity.isHidden = true return activity }() //MARK: 导航条相关 lazy var naBar: PresentNaBarView = { let bar : PresentNaBarView = PresentNaBarView.init(frame: CGRect.init(x: 0, y: 0, width: app_width, height: 64)) bar.naBarItem.text = "位置" bar.backgroundColor = nav_color() bar.saveBtn.setTitle("确定", for: .normal) bar.cancelBtn.addTarget(self, action: #selector(cancel), for: .touchUpInside) bar.saveBtn.addTarget(self, action: #selector(confirm), for: .touchUpInside) return bar }() func cancel() { self.dismiss(animated: true, completion: nil) } func confirm() { let mapPOI : AMapPOI = (self.dataArray[selectIndex]) let manager : ReturnLocationHelper = ReturnLocationHelper.sharedManager() if ((manager.locationBlock) != nil) { manager.returnLocation(manager.locationBlock!, true, mapPOI) } self.dismiss(animated: true, completion: nil) } //MARK: 搜索框相关 lazy var search: LocationSearch = { let se = LocationSearch.init(frame: UIScreen.main.bounds) se.searchField.placeholder = "搜索地址" se.delegate = self return se }() @IBAction func searchAction(_ sender: UIButton) { if self.mapView.height < self.maxMap_h { self.displayMap = false } else { self.displayMap = true } self.hiddenSearch = true self.touchSearchAnimation() if let window = UIApplication.shared.keyWindow { window.addSubview(self.search) self.search.animate() UIApplication.shared.statusBarStyle = UIStatusBarStyle.default } } func touchSearchAnimation() { weak var weakSelf = self if self.hiddenSearch { UIView.animate(withDuration: 0.25, delay: 0.01, options: .curveEaseIn, animations: { if (weakSelf?.displayMap)! { weakSelf?.mapView.frame = CGRect.init(x: 0, y: 69, width: app_width, height: (weakSelf?.maxMap_h)!) weakSelf?.tableView.frame = CGRect.init(x: 0, y: 339, width: app_width, height: app_height - 339) } else { let originY : CGFloat = 339 - (weakSelf?.minMap_h)! let height : CGFloat = app_height - 339 + (weakSelf?.minMap_h)! weakSelf?.mapView.frame = CGRect.init(x: 0, y: 69, width: app_width, height: (weakSelf?.minMap_h)!) weakSelf?.tableView.frame = CGRect.init(x: 0, y: originY, width: app_width, height: height) } weakSelf?.searchBtn.isHidden = true }, completion: { (finish : Bool) in }) } else { UIView.animate(withDuration: 0.25, delay: 0.01, options: .curveEaseIn, animations: { if (weakSelf?.displayMap)! { weakSelf?.mapView.frame = CGRect.init(x: 0, y: 109, width: app_width, height: (weakSelf?.maxMap_h)!) weakSelf?.tableView.frame = CGRect.init(x: 0, y: 379, width: app_width, height: app_height - 379) } else { let originY : CGFloat = 379 - (weakSelf?.minMap_h)! let height : CGFloat = app_height - 379 + (weakSelf?.minMap_h)! weakSelf?.mapView.frame = CGRect.init(x: 0, y: 109, width: app_width, height: (weakSelf?.minMap_h)!) weakSelf?.tableView.frame = CGRect.init(x: 0, y: originY, width: app_width, height: height) } weakSelf?.searchBtn.isHidden = false }, completion: { (finish : Bool) in }) } } //MARK: LocationSearchDelegate func hideSearchView(status : Bool) { self.hiddenSearch = false self.touchSearchAnimation() if status == true { self.search.removeFromSuperview() UIApplication.shared.statusBarStyle = UIStatusBarStyle.lightContent self.mapView.centerCoordinate = CLLocationCoordinate2DMake(CCSingleton.sharedUser().latitude, CCSingleton.sharedUser().longitude) } } lazy var tableView : UITableView = { let tab : UITableView = UITableView.init(frame: CGRect.init(x: 0, y: self.tableView_y, width: app_width, height: self.minTableView_h), style: .grouped) tab.tableHeaderView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: app_width, height: 1.0)) tab.tableHeaderView?.backgroundColor = globalBGColor() tab.tableFooterView = UIView() tab.dataSource = self tab.delegate = self return tab }() //MARK: 高德地图相关 lazy var mapView : MAMapView = { let map : MAMapView = MAMapView(frame: CGRect.init(x: 0, y: 109, width: app_width, height: self.maxMap_h)) map.desiredAccuracy = kCLLocationAccuracyBestForNavigation map.autoresizingMask = [UIViewAutoresizing.flexibleHeight, UIViewAutoresizing.flexibleWidth] map.showsUserLocation = true map.touchPOIEnabled = true map.pausesLocationUpdatesAutomatically = true //跟踪用户 map.userTrackingMode = .follow //最小更新距离 map.distanceFilter = 1 //设置比例尺缩放级别 map.zoomLevel = 15.5 map.centerCoordinate = CLLocationCoordinate2DMake(CCSingleton.sharedUser().latitude, CCSingleton.sharedUser().longitude) map.delegate = self return map }() lazy var pin : UIImageView = { let pin : UIImageView = UIImageView.init(image: UIImage.init(named: "redPin_lift")) pin.frame = CGRect.init(x: (self.mapView.width - (pin.image?.size.width)!) / 2.0, y: (self.mapView.height - (pin.image?.size.height)!) / 2.0, width: (pin.image?.size.width)!, height: (pin.image?.size.height)!) return pin }() lazy var gpsButton : UIButton = { let rect : CGRect = CGRect.init(x: 0, y: 0, width: 40, height: 40) let button = UIButton.init(frame: rect) button.backgroundColor = UIColor.white button.layer.cornerRadius = 4 button.setImage(UIImage.init(named: "gpsStat1"), for: UIControlState.normal) button.addTarget(self, action: #selector(LocationVC.gpsAction), for: UIControlEvents.touchUpInside) button.center = CGPoint.init(x: button.bounds.width / 2 + 10, y: self.mapView.bounds.size.height - button.bounds.width / 2 - 20) button.autoresizingMask = [UIViewAutoresizing.flexibleTopMargin , UIViewAutoresizing.flexibleRightMargin] return button }() lazy var makeZoomPannelView : UIView = { let ret = UIView.init(frame: CGRect.init(x: 0, y: 109, width: app_width, height: self.maxMap_h)) let incBtn = UIButton.init(frame: CGRect.init(x: app_width - 58, y: 49, width: 53, height: 49)) incBtn.setImage(UIImage.init(named: "increase"), for: UIControlState.normal) incBtn.sizeToFit() incBtn.addTarget(self, action: #selector(LocationVC.zoomPlusAction), for: UIControlEvents.touchUpInside) let decBtn = UIButton.init(frame: CGRect.init(x: app_width - 58, y: 98, width: 53, height: 49)) decBtn.setImage(UIImage.init(named: "decrease"), for: UIControlState.normal) decBtn.sizeToFit() decBtn.addTarget(self, action: #selector(LocationVC.zoomMinusAction), for: UIControlEvents.touchUpInside) ret.addSubview(incBtn) ret.addSubview(decBtn) return ret }() func setupMapView() { self.view.addSubview(self.mapView) let zoomPannelView = self.makeZoomPannelView zoomPannelView.autoresizingMask = [UIViewAutoresizing.flexibleTopMargin , UIViewAutoresizing.flexibleLeftMargin] self.mapView.addSubview(self.makeZoomPannelView) self.mapView.addSubview(self.gpsButton) self.mapView.addSubview(self.pin) self.pin.center = CGPoint.init(x: self.mapView.center.x, y: self.mapView.center.y - self.pin.height / 2.0 * 3) } func zoomPlusAction() { let oldZoom = self.mapView.zoomLevel self.mapView.setZoomLevel(oldZoom + 1, animated: true) } func zoomMinusAction() { let oldZoom = self.mapView.zoomLevel self.mapView.setZoomLevel(oldZoom - 1, animated: true) } func gpsAction() { self.isFirstLoading = false if (self.mapView.userLocation.isUpdating && self.mapView.userLocation.location != nil) { //设置当前位置为地图中心的位置 self.mapView.setCenter(self.mapView.userLocation.location.coordinate, animated: true) self.gpsButton.isSelected = true } } lazy var geoCoder: CLGeocoder = { return CLGeocoder() }() //MARK: 搜索周边 lazy var mapSearch : AMapSearchAPI = { let mapSearch : AMapSearchAPI = AMapSearchAPI() mapSearch.delegate = self return mapSearch }() lazy var mapRequest : AMapPOIAroundSearchRequest = { let request : AMapPOIAroundSearchRequest = AMapPOIAroundSearchRequest() request.types = "风景名胜|商务住宅|政府机构及社会团体|地名地址信息" request.sortrule = 0 request.requireExtension = true return request }() func initSearchs() { self.mapRequest.location = AMapGeoPoint.location(withLatitude: CGFloat(CCSingleton.sharedUser().latitude), longitude: CGFloat(CCSingleton.sharedUser().longitude)) self.mapSearch.aMapPOIAroundSearch(self.mapRequest) //搜索请求 } //MARK: AMapSearchDelegate //逆地理编码查询回调函数 func onReGeocodeSearchDone(_ request: AMapReGeocodeSearchRequest!, response: AMapReGeocodeSearchResponse!) { var str : NSString = response.regeocode.addressComponent.city as NSString // addressComponent包含用户当前地址 if str.length == 0 { str = response.regeocode.addressComponent.province as NSString } self.mapView.userLocation.title = str as String self.mapView.userLocation.subtitle = response.regeocode.formattedAddress } //POI查询回调函数 func onPOISearchDone(_ request: AMapPOISearchBaseRequest!, response: AMapPOISearchResponse!) { if response.pois.count == 0 { return } self.dataArray = response.pois as Array self.activity.stopAnimating() self.activity.isHidden = true self.tableView.reloadData() } //MARK: 展开地图 func openShutter() { weak var weakSelf = self UIView.animate(withDuration: 0.25, delay: 0.01, options: .curveEaseOut, animations: { weakSelf?.tableView.tableHeaderView = UIView.init(frame: CGRect.init(x: 0.0, y: 0.0, width: app_width, height:1.0)) weakSelf?.mapView.frame = CGRect.init(x: 0.0, y: (weakSelf?.headerYOffSet)!, width: (weakSelf?.mapView.width)!, height: (weakSelf?.maxMap_h)!) weakSelf?.tableView.frame = CGRect.init(x: 0.0, y: (weakSelf?.tableView_y)!, width: (weakSelf?.tableView.width)!, height: (weakSelf?.minTableView_h)!) weakSelf?.pin.center = CGPoint.init(x: (weakSelf?.mapView.center.x)!, y: (weakSelf?.mapView.center.y)! - (weakSelf?.pin.height)! / 2.0 * 3) }) { (finish : Bool) in weakSelf?.displayMap = true } } //MARK: 收缩地图 func closeShutter() { weak var weakSelf = self UIView.animate(withDuration: 0.25, delay: 0.01, options: .curveEaseOut, animations: { weakSelf?.mapView.frame = CGRect.init(x: 0, y: (weakSelf?.headerYOffSet)!, width: (weakSelf?.mapView.width)!, height: (weakSelf?.minMap_h)!) weakSelf?.tableView.tableHeaderView = UIView.init(frame: CGRect.init(x: 0.0, y: (weakSelf?.default_Y_tableView)!, width: app_width, height: 1.0)) weakSelf?.tableView.frame = CGRect.init(x: 0.0, y: (weakSelf?.default_Y_tableView)!, width: (weakSelf?.tableView.width)!, height: (weakSelf?.maxTableView_h)!) weakSelf?.pin.center = CGPoint.init(x: (weakSelf?.mapView.center.x)!, y: (weakSelf?.mapView.center.y)! - (weakSelf?.pin.height)! / 2.0 * 3) }) { (finish : Bool) in weakSelf?.displayMap = false } } //MARK: scrollViewDelegate func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { contentOffsetY = scrollView.contentOffset.y } func scrollViewDidScroll(_ scrollView: UIScrollView) { let scrollOffset : CGFloat = scrollView.contentOffset.y if scrollView.isDragging { // 拖拽 if (scrollOffset - contentOffsetY) > 0 { //向上拖拽 if self.mapView.height == self.maxMap_h { self.displayMap = false self.closeShutter() } } else if (contentOffsetY - scrollOffset) > 10 { //向下拖拽 if self.mapView.height == self.minMap_h { self.displayMap = true self.openShutter() } } } } } //MARK: MAMapViewDelegate extension LocationVC : MAMapViewDelegate { //地图移动结束后 func mapView(_ mapView: MAMapView!, mapDidMoveByUser wasUserAction: Bool) { //位置发生变化后的操作 if CCSingleton.sharedUser().latitude != mapView.centerCoordinate.latitude && CCSingleton.sharedUser().longitude != mapView.centerCoordinate.longitude { if self.dataArray.count > 0 { self.dataArray.removeAll() } self.tableView.rowHeight = self.tableView.height self.tableView.reloadData() self.activity.isHidden = false self.activity.startAnimating() CCSingleton.sharedUser().latitude = self.mapView.centerCoordinate.latitude CCSingleton.sharedUser().longitude = self.mapView.centerCoordinate.longitude self.initSearchs() weak var weakSelf = self UIView.animate(withDuration: 0.3, animations: { weakSelf?.pin.transform = CGAffineTransform(scaleX: 0.7, y: 0.7) }) { (finish : Bool) in UIView.animate(withDuration: 0.3, animations: { weakSelf?.pin.transform = CGAffineTransform(scaleX: 1, y: 1) }) { (finish : Bool) in } } } } //地图将要发生缩放 func mapView(_ mapView: MAMapView!, mapWillZoomByUser wasUserAction: Bool) { if !self.displayMap { self.openShutter() } } } //MARK: UITableViewDataSource && UITableViewDelegate extension LocationVC : UITableViewDataSource, UITableViewDelegate { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if self.dataArray.count == 0 { return 1 } return self.dataArray.count } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if self.dataArray.count == 0 { return tableView.height } return 44 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let row: Int = (indexPath as NSIndexPath).row let cell = tableView.dequeueReusableCell(withIdentifier: "LocationCell", for: indexPath) as! LocationCell cell.selectionStyle = .none if self.dataArray.count > 1 { if row == selectIndex { cell.mark.isHidden = false } else { cell.mark.isHidden = true } let mapPOI: AMapPOI = self.dataArray[row] cell.title.text = mapPOI.name let province : String = mapPOI.province //省 let city : String = mapPOI.city //市 let district : String = mapPOI.district; //区 let address : String = mapPOI.address; //地址 if district == address { cell.detail.text = province + city + address } else { cell.detail.text = province + city + district + address } } else { cell.mark.isHidden = true cell.title.text = "" cell.detail.text = "" } return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let row: Int = (indexPath as NSIndexPath).row self.selectIndex = row tableView.reloadData() let mapPOI: AMapPOI = self.dataArray[row] self.mapView.centerCoordinate = CLLocationCoordinate2D.init(latitude: CLLocationDegrees(mapPOI.location.latitude), longitude: CLLocationDegrees(mapPOI.location.longitude)) } }
// // BLEDeviceInfo.swift // TCP // // Created by salam on 25/04/16. // Copyright © 2016 Cabot. All rights reserved. // import Foundation import CoreBluetooth class BLEDeviceInfo : NSObject,CBPeripheralDelegate { var BLEPeripheral : CBPeripheral! var BLEPeripheralRSSI : NSNumber! var BLEPeripheralLocalName: String? var BLEPeripheralManufacturerData : String? var BLEPeripheralTxPowerLevel : String? var BLEPeripheralsConnectable : Bool init(peripheral:CBPeripheral!, advertisementData:[NSObject : AnyObject]!, RSSI:NSNumber!) { self.BLEPeripheral = peripheral self.BLEPeripheralRSSI = RSSI if let localName = advertisementData[CBAdvertisementDataLocalNameKey] as? String { self.BLEPeripheralLocalName = localName } else if let deviceName = peripheral.name { self.BLEPeripheralLocalName = deviceName } else { self.BLEPeripheralLocalName = "No Name" } if let _ = advertisementData[CBAdvertisementDataManufacturerDataKey] as? NSData { let newData = advertisementData[CBAdvertisementDataManufacturerDataKey] as? NSData if newData == nil { self.BLEPeripheralManufacturerData = nil } else { self.BLEPeripheralManufacturerData = newData?.hexRepresentation() } } else { self.BLEPeripheralManufacturerData = nil } let txNum = advertisementData[CBAdvertisementDataTxPowerLevelKey] as? NSNumber if txNum == nil {self.BLEPeripheralTxPowerLevel = nil} else { self.BLEPeripheralTxPowerLevel = txNum!.stringValue} let num = advertisementData[CBAdvertisementDataIsConnectable] as? NSNumber if num == nil { self.BLEPeripheralsConnectable = false } else {self.BLEPeripheralsConnectable = num!.boolValue} super.init() } }
// // SayHi.swift // HelloWord // // Created by Pankx on 16/1/31. // Copyright © 2016年 Pankx. All rights reserved. // import Foundation func sayHi ( name : String ) ->String { return "Hello \(name),This is my first Swift project! I like Swift!"; }
// // AddRegistrationTableViewController.swift // HotelManzana // // Created by Jeewoo Chung on 10/14/19. // Copyright © 2019 Jeewoo Chung. All rights reserved. // import UIKit class AddRegistrationTableViewController: UITableViewController, SelectRoomTypeTableViewControllerDelegate { let checkInDateLabelCellIndexPath = IndexPath(row: 0, section: 1) let checkOutDateLabelCellIndexPath = IndexPath(row: 2, section: 1) let checkInDatePickerCellIndexPath = IndexPath(row: 1, section: 1) let checkOutDatePickerCellIndexPath = IndexPath(row: 3, section: 1) var isCheckInDatePickerShown: Bool = false { didSet { checkInDatePicker.isHidden = !isCheckInDatePickerShown } } var isCheckOutDatePickerShown: Bool = false { didSet { checkOutDatePicker.isHidden = !isCheckOutDatePickerShown } } // text fields @IBOutlet var firstNameTextField: UITextField! @IBOutlet var lastNameTextField: UITextField! @IBOutlet var emailTextField: UITextField! // date picker fields @IBOutlet var checkInDateLabel: UILabel! @IBOutlet var checkInDatePicker: UIDatePicker! @IBOutlet var checkOutDateLabel: UILabel! @IBOutlet var checkOutDatePicker: UIDatePicker! // stepper fields @IBOutlet var numberOfAdultsLabel: UILabel! @IBOutlet var numberOfAdultsStepper: UIStepper! @IBOutlet var numberOfChildrenLabel: UILabel! @IBOutlet var numberOfChildrenStepper: UIStepper! // switch field @IBOutlet var wifiSwitch: UISwitch! // last field @IBOutlet var roomTypeLabel: UILabel! var roomType: RoomType? override func viewDidLoad() { super.viewDidLoad() let midnightToday = Calendar.current.startOfDay(for: Date()) checkInDatePicker.minimumDate = midnightToday checkInDatePicker.date = midnightToday updateDateViews() updateNumberOfGuests() updateRoomType() } func updateDateViews() { checkOutDatePicker.minimumDate = checkInDatePicker.date.addingTimeInterval(86400) let dateFormatter = DateFormatter() dateFormatter.dateStyle = .medium checkInDateLabel.text = dateFormatter.string(from: checkInDatePicker.date) checkOutDateLabel.text = dateFormatter.string(from: checkOutDatePicker.date) } func updateNumberOfGuests() { numberOfAdultsLabel.text = "\(Int(numberOfAdultsStepper.value))" numberOfChildrenLabel.text = "\(Int(numberOfChildrenStepper.value))" } func updateRoomType() { if let roomType = roomType { roomTypeLabel.text = roomType.name } else { roomTypeLabel.text = "Not Set" } } func didSelect(roomType: RoomType) { self.roomType = roomType updateRoomType() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "SelectRoomType" { let destinationVC = segue.destination as? SelectRoomTypeTableViewController destinationVC?.delegate = self destinationVC?.roomType = roomType } } @IBAction func doneBarButtonTapped(_ sender: UIBarButtonItem) { let firstName = firstNameTextField.text ?? "" let lastName = lastNameTextField.text ?? "" let email = emailTextField.text ?? "" let checkIn = checkInDatePicker.date let checkOut = checkOutDatePicker.date let numberOfAdults = Int(numberOfAdultsStepper.value) let numberOfChildren = Int(numberOfChildrenStepper.value) let hasWifi = wifiSwitch.isOn let roomChoice = roomType?.name ?? "Not Set" print("BUTTON TAPPED") print("firstName: \(firstName)") print("lastName: \(lastName)") print("email: \(email)") print("checkIn: \(checkIn)") print("checkOut: \(checkOut)") print("numberOfAdults: \(numberOfAdults)") print("numberOfChildren: \(numberOfChildren)") print("wifi: \(hasWifi)") print("roomChoice: \(roomChoice)") } @IBAction func datePickerValueChanged(_ sender: UIDatePicker) { updateDateViews() } @IBAction func stepperValueChanged(_ sender: UIStepper) { updateNumberOfGuests() } @IBAction func wifiSwitchChanged(_ sender: UISwitch) { } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { tableView.deselectRow(at: indexPath, animated: true) switch indexPath { case checkInDatePickerCellIndexPath: if isCheckInDatePickerShown { return 162.0 } else { return 0.0 } case checkOutDatePickerCellIndexPath: if isCheckOutDatePickerShown { return 162.0 } else { return 0.0 } default: return 44.0 } } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { switch indexPath { case checkInDateLabelCellIndexPath: if isCheckInDatePickerShown { isCheckInDatePickerShown = false } else if isCheckOutDatePickerShown { isCheckOutDatePickerShown = false isCheckInDatePickerShown = true } else { isCheckInDatePickerShown = true } tableView.beginUpdates() tableView.endUpdates() case checkOutDateLabelCellIndexPath: if isCheckOutDatePickerShown { isCheckOutDatePickerShown = false } else if isCheckInDatePickerShown { isCheckInDatePickerShown = false isCheckOutDatePickerShown = true } else { isCheckOutDatePickerShown = true } tableView.beginUpdates() tableView.endUpdates() default: break } } }
// // TeamListCellViewModel.swift // Sportsgram // // Created by Brian Palma on 10/27/15. // Copyright © 2015 Brian M. Palma. All rights reserved. // import UIKit class TeamListCellViewModel: NSObject { private var team: Team! var username: String { return team.prefixedUsername } var name: String { return team.name } init(team: Team) { self.team = team super.init() } }
// // SocialAppNavigationController.swift // SocialApp // // Created by Дима Давыдов on 26.10.2020. // import UIKit class SocialAppNavigationController: UINavigationController, UINavigationControllerDelegate { var interactiveTransition = SocialAppInteractiveTransition() override func viewDidLoad() { super.viewDidLoad() delegate = self } func navigationController(_ navigationController: UINavigationController, interactionControllerFor animationController: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { return interactiveTransition.hasStarted ? interactiveTransition : nil } func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationController.Operation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? { if operation == .pop { return SocialAppPopAnimator() } if operation == .push { if viewControllers.first != toVC { interactiveTransition.viewController = toVC } return SocialAppPushAnimator() } return nil } }
// // RideDetailsText.swift // Backfire // // Created by David Jensenius on 2021-04-12. // import SwiftUI import MapKit struct RideDetails { var title: String var value: String var image: Image? } struct RideDetailsText: View { @ObservedObject var ride: Ride let localizeNumber = LocalizeNumbers() @State var parsedRideDetails: [RideDetails?] = [] var body: some View { let helper = Helper() let rideDetails = helper.parseRide(ride: ride) let formattedWeather = helper.formatWeather(weather: ride.weather ?? nil) let gridItems = [GridItem(.adaptive(minimum: 150))] VStack { if parsedRideDetails.count > 0 { LazyVGrid(columns: gridItems, spacing: 5) { ForEach((0...(parsedRideDetails.count - 1)), id: \.self) { index in if (parsedRideDetails[index]?.image) != nil { boxViewImage( text: parsedRideDetails[index]!.image!, value: parsedRideDetails[index]?.value ?? "" ) } else { boxView( text: parsedRideDetails[index]?.title ?? "", value: parsedRideDetails[index]?.value ?? "" ) } } } } }.onAppear { if rideDetails != nil { parsedRideDetails = buildViews(rideDetails: rideDetails!, formattedWeather: formattedWeather) } } } func boxView(text: String, value: String, divider: Bool = false) -> AnyView { return AnyView( VStack { if divider { Divider() .padding([.top, .bottom]) } Text(text) .font(.title3) .padding(.bottom) .overlay(Divider(), alignment: .bottom) Text(value) .font(.largeTitle) }.padding(.bottom, 30) ) } func boxViewImage(text: Image, value: String, divider: Bool = false) -> AnyView { return AnyView( VStack { if divider { Divider() .padding([.top, .bottom]) } Text("\(text)") .font(.title3) .padding(.bottom) .overlay(Divider(), alignment: .bottom) Text(value) .font(.largeTitle) }.padding(.bottom, 30) ) } func buildViews(rideDetails: DetailRide, formattedWeather: DetailWeather?) -> [RideDetails] { let rideDistance = RideDetails( title: "Distance", value: localizeNumber.distance(distance: Double(rideDetails.distance) / 1000, length: 2) ) let maxSpeed = RideDetails(title: "Max Speed", value: localizeNumber.speed(speed: rideDetails.maxSpeed)) let climb = RideDetails(title: "Climb", value: localizeNumber.height(distance: rideDetails.climb)) let batteryStart = RideDetails(title: "Battery Start", value: "\(rideDetails.startBattery)%") let temprature = RideDetails( title: "Temprature", value: localizeNumber.temp(temp: formattedWeather?.temperature ?? 0) ) let feelsLike = RideDetails( title: "Feels Like", value: localizeNumber.temp(temp: formattedWeather?.feelsLike ?? 0) ) let rideTime = RideDetails(title: "Ride Time", value: rideDetails.rideTime) let avgSpeed = RideDetails(title: "Avg. Speed", value: localizeNumber.speed(speed: Int(rideDetails.avgSpeed))) let decline = RideDetails(title: "Decline", value: localizeNumber.height(distance: rideDetails.decline)) let batteryEnd = RideDetails(title: "Battery End", value: "\(rideDetails.endBattery)%") let weatherDescription = RideDetails( title: String("\(formattedWeather!.icon)"), value: formattedWeather?.description ?? "", image: formattedWeather!.icon ) let windSpeed = RideDetails( title: "Wind Speed", value: localizeNumber.speed(speed: Int(formattedWeather?.windSpeed ?? 0)) ) if (rideDetails.endBattery != 0 || rideDetails.startBattery != 0) { return [ rideDistance, rideTime, maxSpeed, avgSpeed, climb, decline, batteryStart, batteryEnd, temprature, weatherDescription, feelsLike, windSpeed ] } return [ rideDistance, rideTime, maxSpeed, avgSpeed, climb, decline, temprature, weatherDescription, feelsLike, windSpeed ] } func details(locations: [Location]) -> AnyView { let sortedLocations = locations.sorted { $0.timestamp?.compare($1.timestamp ?? Date()) == .orderedAscending } let diffComponents = Calendar.current.dateComponents( [.minute, .second], from: (sortedLocations.first?.timestamp)!, to: (sortedLocations.last?.timestamp)! ) let minutes = diffComponents.minute let seconds = diffComponents.second var timeText = "" timeText = "\(minutes ?? 0)" if seconds ?? 0 < 10 { timeText = "\(timeText):0\(seconds ?? 0)" } else { timeText = "\(timeText):\(seconds ?? 0)" } var totalDistance: Double = 0 var firstLat = sortedLocations.first?.latitude var firstLon = sortedLocations.first?.longitude sortedLocations.dropFirst().forEach { location in let firsLocation = CLLocation(latitude: firstLat!, longitude: firstLon!) let secondLocation = CLLocation(latitude: location.latitude, longitude: location.longitude) firstLat = location.latitude firstLon = location.longitude totalDistance += firsLocation.distance(from: secondLocation) } return AnyView( Text("\(timeText) / \(String(format: "%.02f", totalDistance / 1000)) KMs") .font(.subheadline) ) } } private let itemFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateStyle = .long formatter.timeStyle = .short return formatter }() /* struct RideDetailsText_Previews: PreviewProvider { static var previews: some View { RideDetailsText() } } */
// // LoginPresenter.swift // CleanSwiftSample // // Created by Okhan Okbay on 24.10.2020. // Copyright (c) 2020 ___ORGANIZATIONNAME___. All rights reserved. // // This file was generated by the Clean Swift Xcode Templates so // you can apply clean architecture to your iOS and Mac projects, // see http://clean-swift.com // import UIKit protocol LoginPresentationLogic: AnyObject { func presentMessages(response: Login.Response) func presentAlert(response: Login.Response) func presentAutoLogin(response: AutoLogin.Response) } final class LoginPresenter { private weak var displayer: LoginDisplayLogic! init(displayer: LoginDisplayLogic) { self.displayer = displayer } } extension LoginPresenter: LoginPresentationLogic { func presentMessages(response: Login.Response) { let viewModel = Login.ViewModel() displayer.displayMessages(viewModel: viewModel) } func presentAlert(response: Login.Response) { let alert = AlertViewModel(title: Strings.error, message: Strings.usernameCharacterLength, buttonText: Strings.confirm) let viewModel = Login.ViewModel(alert: alert) displayer.displayAlert(viewModel: viewModel) } func presentAutoLogin(response: AutoLogin.Response) { let viewModel = AutoLogin.ViewModel() displayer.displayAutoLogin(viewModel: viewModel) } }
// // URLSession+.swift // GISHelperKit // // Created by 游宗諭 on 2019/8/26. // Copyright © 2019 ytyubox. All rights reserved. // import Foundation extension URLSession { public typealias URLInfo = (data: Data?, response: URLResponse?) public func getData(with url: URL, timeout: TimeInterval = 15) throws -> URLInfo { let s = DispatchSemaphore(value: 0) var result: URLInfo = (nil, nil) var error: Error? dataTask(with: url) { (d, r, e) in error = e result.data = d result.response = r s.signal() }.resume() let some = s.wait(timeout: .now()+timeout) switch some { case .success: break case .timedOut: throw APIError.timeout } if let error = error { throw error } // let thedata = result.data if result.data == nil || result.data!.isEmpty { throw APIError.noData } return result } public func getData(with request: URLRequest, timeout: TimeInterval = 15) throws -> URLInfo { let s = DispatchSemaphore(value: 0) var result: URLInfo = (nil, nil) var error: Error? dataTask(with: request) { (d, r, e) in error = e result.data = d result.response = r s.signal() }.resume() let some = s.wait(timeout: .now()+timeout) switch some { case .success: break case .timedOut: throw APIError.timeout } if let error = error { throw error } // let thedata = result.data if result.data == nil || result.data!.isEmpty { throw APIError.noData } return result } } public enum URLResult<Model: Decodable, Failure: Decodable, Err: Error> { case success(Model) case apiError(Failure) case failure(Err) case decodeError(APIError) case retry(Int) public var isSuccess: Bool { switch self { case .success: return true default: return false } } } public enum APIError: Error { case timeout case noData case noResponse case JSONDecodeError case retryNumberRunout case other(String) public var localizedDescription: String { switch self { case .timeout: return "請求超時" case .noData: return "回传资料空" case .noResponse: break case .JSONDecodeError: break case .retryNumberRunout: return "重試請求超時" case .other(let s): return s } return "回传资料格式错误" } }
// // NewClimbViewController.swift // BoulderDash // // Created by Classroom Tech User on 3/7/16. // Copyright © 2016 Matt&Tim. All rights reserved. // import Foundation import UIKit class NewClimbViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate, ServerResponseDelegate { var ratings = ["V0", "V1", "V2", "V3", "V4", "V5", "V6", "V7", "V8", "V9", "V10", "V11", "V12", "V13", "V14", "V15", "V16"] @IBOutlet var picker: UIPickerView? @IBOutlet var climbName: UITextField? @IBOutlet var location: UITextField? @IBOutlet var flashed: UISwitch? @IBOutlet var downclimb: UISwitch? @IBOutlet var campus: UISwitch? @IBOutlet var toetouch: UISwitch? @IBOutlet var outdoor: UISwitch? override func viewDidLoad() { super.viewDidLoad() picker?.delegate = self picker?.dataSource = self ServerOverlord.delegate = self } func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 1 } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return ratings.count } func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return ratings[row] } func serverDidRespond(sender: String, data: JSON) { if sender == "addClimb" { NSOperationQueue.mainQueue().addOperationWithBlock { self.performSegueWithIdentifier("backFromNewClimb", sender: self) } } } @IBAction func newClimb() { ServerOverlord.addClimb((climbName?.text)!, loc: (location?.text)!, rating: (picker?.selectedRowInComponent(0))!, flash: (flashed?.on)!, down: (downclimb?.on)!, campus: (campus?.on)!, toe: (toetouch?.on)!, outdoor: (outdoor?.on)!) } }
//// //// GesturePasswordControllerViewController.swift //// MsdGateLock //// //// Created by ox o on 2017/7/26. //// Copyright © 2017年 xiaoxiao. All rights reserved. //// 手势密码验证 // //import UIKit // //class GesturePasswordController: UIViewController { // // var lockView : PCCircleView! //解锁界面 // var msgLabel : PCLockLabel! //提示label // // override func viewDidLoad() { // super.viewDidLoad() // self.view.backgroundColor = UIColor.globalBackColor // setupUI() // } // // override func viewWillAppear(_ animated: Bool) { // super.viewWillAppear(animated) // self.navigationController?.setNavigationBarHidden(true, animated: true) // } // // override func viewWillDisappear(_ animated: Bool) { // super.viewWillDisappear(animated) // self.navigationController?.setNavigationBarHidden(false, animated: true) // } //} // // //extension GesturePasswordController{ // // func setupUI(){ // let iconImageView = UIImageView(image: UIImage(named : "user1")) // iconImageView.layer.cornerRadius = 50 // iconImageView.layer.masksToBounds = true // self.view.addSubview(iconImageView) // iconImageView.snp.makeConstraints { (make) in // make.top.equalTo(65) // make.centerX.equalTo(self.view) // make.width.equalTo(100) // make.height.equalTo(100) // } // // let numberLabel = UILabel() // numberLabel.text = UserInfo.getPhoneNumber() // numberLabel.textColor = UIColor.textBlackColor // numberLabel.font = kGlobalTextFont // self.view.addSubview(numberLabel) // numberLabel.snp.makeConstraints { (make) in // make.top.equalTo(iconImageView.snp.bottom).offset(10) // make.centerX.equalTo(self.view) // } // // let gestureView = PCCircleView.init(cirCleViewCenterY: 0.6) // gestureView?.delegate = self // gestureView?.type = CircleViewTypeVerify // self.lockView = gestureView // self.view.addSubview(gestureView!) // // let lockLabel = PCLockLabel() // lockLabel.frame = CGRect(x: 0, y: 0, width: kScreenWidth, height: 14) // lockLabel.center = CGPoint(x: kScreenWidth/2, y:(gestureView?.frame.minY)! - 30) // self.msgLabel = lockLabel // self.view.addSubview(msgLabel) // // // let changeVertStyleBtn = UIButton(type: .custom) // changeVertStyleBtn.setTitle("更改验证方式", for: .normal) // changeVertStyleBtn.setTitleColor(UIColor.textBlueColor, for: .normal) // changeVertStyleBtn.titleLabel?.font = kGlobalTextFont // changeVertStyleBtn.addTarget(self, action: #selector(GesturePasswordController.changeVertStyleBtnDidClick), for: .touchUpInside) // self.view.addSubview(changeVertStyleBtn) // changeVertStyleBtn.snp.makeConstraints { (make) in // make.left.equalTo(45) // make.bottom.equalTo(-30) // } // // let changeUserBtn = UIButton(type: .custom) // changeUserBtn.setTitle("切换用户", for: .normal) // changeUserBtn.setTitleColor(UIColor.textBlueColor, for: .normal) // changeUserBtn.titleLabel?.font = kGlobalTextFont // changeUserBtn.addTarget(self, action: #selector(GesturePasswordController.changeUserBtnDidClick), for: .touchUpInside) // self.view.addSubview(changeUserBtn) // changeUserBtn.snp.makeConstraints { (make) in // make.centerX.equalTo(self.view) // make.bottom.equalTo(-30) // } // // let forgetPassBtn = UIButton(type: .custom) // forgetPassBtn.setTitle("忘记密码", for: .normal) // forgetPassBtn.setTitleColor(UIColor.textBlueColor, for: .normal) // forgetPassBtn.titleLabel?.font = kGlobalTextFont // forgetPassBtn.addTarget(self, action: #selector(GesturePasswordController.forgetPassBtnDidClick), for: .touchUpInside) // self.view.addSubview(forgetPassBtn) // forgetPassBtn.snp.makeConstraints { (make) in // make.right.equalTo(-45) // make.bottom.equalTo(-30) // } // } // //} // // //extension GesturePasswordController : CircleViewDelegate { // // func circleView(_ view: PCCircleView!, type: CircleViewType, didCompleteLoginGesture gesture: String!, result equal: Bool) { // if type == CircleViewTypeVerify { // if equal { // QPCLog("验证成功") // self.msgLabel.showNormalMsg("验证成功") // let homeNav = LockNavigationController(rootViewController: HomeViewController()) // UIApplication.shared.keyWindow?.rootViewController = homeNav // }else{ // self.msgLabel.showWarnMsgAndShake(gestureTextGestureVerifyError) // } // } // } //} // // ////MARK:- CLICK //extension GesturePasswordController { // // func changeVertStyleBtnDidClick(){ // let seletedVeriVC = SetNumberPassController() // seletedVeriVC.title = "选择验证方式" // seletedVeriVC.seletedTitleArr = ["数字密码","指纹密码"] // navigationController?.pushViewController(seletedVeriVC, animated: true) // } // // func changeUserBtnDidClick(){ // UserInfo.removeUserInfo() // UIApplication.shared.keyWindow?.rootViewController = LockNavigationController(rootViewController: LoginController()) // } // // func forgetPassBtnDidClick(){ // let numVC = ResetNumberController() // numVC.title = "重置手势密码" // navigationController?.pushViewController(numVC, animated: true) // } // //} //
// // PassBackDelegate.swift // UCSF // // Created by Kevin Nguyen on 5/3/16. // Copyright © 2016 Jimbus. All rights reserved. // import Foundation // Delegate for passing back a chosen string from a popover protocol PassBackDelegate { func sendString(myString:String) }
// // MTChatMoreCell.swift // MTChat // // Created by IT A on 2018/11/26. // Copyright © 2018 IT A. All rights reserved. // 更多页面 cell import UIKit class MTChatMoreCell: UICollectionViewCell { private var btItem: UIButton! private var lbItem: UILabel! var type: MTChatEnums.MoreType? var model: (name: String, icon: UIImage, type: MTChatEnums.MoreType)? { didSet { self.btItem.setImage(model?.icon, for: .normal) self.lbItem.text = model?.name self.type = model?.type } } override init(frame: CGRect) { super.init(frame: frame) setupViews() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() //FIXME: - 是否需要 // btItem.width = btItem.height } private func setupViews() { lbItem = UILabel().then({ (lb) in lb.textColor = UIColor.gray lb.font = UIFont.systemFont(ofSize: 11.0) lb.textAlignment = .center contentView.addSubview(lb) lb.snp.makeConstraints({ (m) in m.left.right.equalToSuperview() m.bottom.equalToSuperview().offset(-2) m.height.equalTo(21) }) }) btItem = UIButton(type: .custom).then({ (bt) in bt.backgroundColor = UIColor.white bt.isUserInteractionEnabled = false bt.layer.cornerRadius = 10 bt.layer.masksToBounds = true bt.layer.borderColor = UIColor.lightGray.cgColor bt.layer.borderWidth = 0.5 contentView.addSubview(bt) bt.snp.makeConstraints({ (m) in m.top.equalToSuperview().offset(6) m.bottom.equalTo(lbItem.snp.top).offset(-5) m.width.equalTo(bt.snp.height) m.centerX.equalToSuperview() }) }) } }
// // ProminentTabBar.swift // Phrase // // Created by Valentin Knabel on 17.11.18. // Copyright © 2018 Valentin Knabel. All rights reserved. // import Overture import UIKit public func marginUnits(_ n: Int) -> CGFloat { return CGFloat(n * 8) } public func prominentSubview(_ prominent: UIView) -> (UITabBarController) -> Void { prominent.translatesAutoresizingMaskIntoConstraints = false return { controller in controller.view.addSubview(prominent) NSLayoutConstraint.activate( [ controller.tabBar.centerXAnchor.constraint(equalTo: prominent.centerXAnchor), controller.tabBar.topAnchor.constraint(equalTo: prominent.centerYAnchor, constant: marginUnits(-2)), ] ) controller.view.bringSubviewToFront(prominent) } } public func prominentCreationButton(color: UIColor) -> (UIButton) -> Void { return { button in button.setImage( UIImage(named: "Create")?.withRenderingMode(.alwaysTemplate), for: .normal ) button.backgroundColor = color.isDark ? .init(rgb: 0xe5e5e5) : .init(rgb: 0x1b1b1b) button.tintColor = color button.layer.masksToBounds = false button.layer.shadowOpacity = 0.5 button.layer.shadowOffset = CGSize(width: 0, height: -2) button.layer.shadowRadius = marginUnits(1) button.layer.shadowColor = UIColor.black.cgColor // TODO: light mode button.clipsToBounds = true button.isUserInteractionEnabled = true button.sizeToFit() NSLayoutConstraint.activate( [ button.heightAnchor.constraint(equalToConstant: 64), button.widthAnchor.constraint(equalToConstant: 64), ] ) } }
// // HistoryViewModel.swift // Coremelysis // // Created by Rafael Galdino on 26/08/20. // Copyright © 2020 Rafael Galdino. All rights reserved. // import Foundation import CoremelysisML protocol HistoryViewModelDelegate: AnyObject { func updateUI() } /// The `HistoryViewController`'s ViewModel final class HistoryViewModel { // - MARK: Properties /// The array of `HistoryEntry`. private var model: [HistoryEntry] = HistoryEntry.create(30) { /// Currently, it uses a development-only implementation to create samples for testing purpose. didSet { self.delegate?.updateUI() } } private var numberOfPositiveEntries: Int { return model.filter { $0.inference == .good || $0.inference == .great }.count } private var numberOfNegativeEntries: Int { return model.filter { $0.inference == .awful || $0.inference == .bad }.count } private var numberOfNeutralEntries: Int { return model.filter { $0.inference == .neutral || $0.inference == .notFound }.count } var numberOfEntries: Int { return model.count } weak var delegate: HistoryViewModelDelegate? // - MARK: Init init() { } // - MARK: Functions func creationDateOfEntry(at index: Int) -> String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy mm dd" return dateFormatter.string(from: model[index].creationDate) } func sentimentOfEntry(at index: Int) -> Sentiment { return model[index].inference } func contentOfEntry(at index: Int) -> String { return model[index].content } func buildSummary() -> HistorySummaryViewModel { return HistorySummaryViewModel(numberOfEntries: numberOfEntries, numberOfPositiveEntries: numberOfPositiveEntries, numberOfNegativeEntries: numberOfNegativeEntries, numberOfNeutralEntries: numberOfNeutralEntries) } }
// // CardView.swift // caffinho-iOS // // Created by Jose Ricardo de Oliveira on 6/24/16. // Copyright © 2016 venturus. All rights reserved. // import UIKit class CardView: UIView { var contentView: CardContentView! override func awakeFromNib() { super.awakeFromNib() contentView = CardContentView.loadFromNibNamed(NibNames.cardContentView) as! CardContentView self.addSubview(contentView) } }
// // PartController.swift // Boatell-x-v2 // // Created by Austin Potts on 3/13/20. // Copyright © 2020 Potts Evolvements. All rights reserved. // import Foundation class PartController { var part: [Part] = [ Part(name: "Fluxer Control", price: "$19.99", imageName: "Cut", partNumber: "Fluxer Control made of stainless steel, this part will help reduce rust on cords."), Part(name: "Floater Control", price: "$30.99", imageName: "Engine", partNumber: "A Floater Control not only helps your boat maintain boyance, but also speed handling"), Part(name: "Bellbop Hinge", price: "$23.50", imageName: "Gadget", partNumber: "This part will help keep the oil heated to flow more easily through the shaft."), Part(name: "Fluxer Control", price: "$19.99", imageName: "Cut", partNumber: "Fluxer Control made of stainless steel, this part will help reduce rust on cords."), Part(name: "Floater Control", price: "$30.99", imageName: "Lights", partNumber: "A Floater Control not only helps your boat maintain boyance, but also speed handling"), Part(name: "Bellbop Hinge", price: "$23.50", imageName: "Cut", partNumber: "This part will help keep the oil heated to flow more easily through the shaft.") ] }
// // ResourcesViewController.swift // YumaApp // // Created by Yuma Usa on 2018-05-15. // Copyright © 2018 Yuma Usa. All rights reserved. // import UIKit import AwesomeEnum struct ResourceStringAndCount { let name: String let count: Int? } class ResourcesViewController: UIViewController { let cellId = "debugCell" let altRowColor = "#E0E0E0" let store = DataStore.sharedInstance var debugList: [ResourceStringAndCount]? = [] static var resource: String? var mirror: Mirror? = nil let stackAll: UIStackView = { let view = UIStackView() view.translatesAutoresizingMaskIntoConstraints = false view.axis = .vertical return view }() var navBar: UINavigationBar = { let view = UINavigationBar() view.backgroundColor = R.color.YumaDRed return view }() let navTitle: UINavigationItem = { let view = UINavigationItem() return view }() var navClose: UIBarButtonItem = { let view = UIBarButtonItem() view.image = Awesome.solid.times.asImage(size: 24) view.action = #selector(navCloseAct(_:)) view.style = UIBarButtonItemStyle.plain return view }() // var navHelp: UIBarButtonItem = // { // let view = UIBarButtonItem() // view.image = Awesome.solid.questionCircle.asImage(size: 24) //// view.action = #selector(navHelpAct(_:)) // view.style = UIBarButtonItemStyle.plain // return view // }() var tableView: UITableView = { let view = UITableView() view.translatesAutoresizingMaskIntoConstraints = false view.separatorStyle = .none return view }() var panel: UIView = { let view = UIView() view.translatesAutoresizingMaskIntoConstraints = false view.backgroundColor = UIColor.white view.shadowColor = UIColor.darkGray view.shadowOffset = .zero view.shadowRadius = 5 view.shadowOpacity = 1 return view }() var statusBarFrame: CGRect! override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.lightGray // print("frame-x: \(view.frame.origin.x), y: \(view.frame.origin.y), w: \(view.frame.size.width), h: \(view.frame.size.height)") // statusBarFrame = UIApplication.shared.statusBarFrame setNavigation() setViews() //panel = UIView(frame: CGRect(x: 5, y: statusBarFrame.height, width: view.frame.width-10, height: view.frame.height-statusBarFrame.height-5)) // tableView = UITableView()//frame: CGRect(x: 2, y: 0, width: /*view.frame.width-14*/panel.frame.width, height: /*view.frame.height-statusBarFrame.height-85*/panel.frame.height)) // tableView.translatesAutoresizingMaskIntoConstraints = false tableView.register(ResourceCell.self, forCellReuseIdentifier: cellId) tableView.delegate = self tableView.dataSource = self panel.addSubview(tableView) stackAll.addArrangedSubview(panel) // self.view.addSubview(panel) // let line = UIView() // line.translatesAutoresizingMaskIntoConstraints = false // line.backgroundColor = R.color.YumaDRed // self.view.addSubview(line) NSLayoutConstraint.activate([ tableView.leadingAnchor.constraint(equalTo: panel.leadingAnchor, constant: 5), tableView.trailingAnchor.constraint(equalTo: panel.trailingAnchor, constant: -5), tableView.topAnchor.constraint(equalTo: panel.topAnchor, constant: 0), tableView.bottomAnchor.constraint(equalTo: panel.bottomAnchor, constant: -5), // panel.leadingAnchor.constraint(equalTo: view.safeLeadingAnchor, constant: 5), // panel.trailingAnchor.constraint(equalTo: view.safeTrailingAnchor, constant: -5), // panel.topAnchor.constraint(equalTo: navBar.bottomAnchor, constant: 0), // panel.bottomAnchor.constraint(equalTo: view.safeBottomAnchor, constant: -5), panel.leadingAnchor.constraint(equalTo: stackAll.leadingAnchor, constant: 0), panel.trailingAnchor.constraint(equalTo: stackAll.trailingAnchor, constant: -5), panel.topAnchor.constraint(equalTo: navBar.bottomAnchor, constant: 0), // panel.topAnchor.constraint(equalTo: view.safeTopAnchor, constant: 2), panel.bottomAnchor.constraint(equalTo: stackAll.bottomAnchor, constant: -5), // line.topAnchor.constraint(equalTo: view.safeTopAnchor), // line.heightAnchor.constraint(equalToConstant: 2), // line.leadingAnchor.constraint(equalTo: view.safeLeadingAnchor), // line.trailingAnchor.constraint(equalTo: view.safeTrailingAnchor), ]) fillContent() } // override func viewWillDisappear(_ animated: Bool) // { // if let statusbar = UIApplication.shared.value(forKey: "statusBar") as? UIView // { // statusbar.backgroundColor = UIColor.clear // } // } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() debugList?.removeAll() } // override var prefersStatusBarHidden: Bool // { // return true // } fileprivate func setViews() { view.addSubview(stackAll) if #available(iOS 11.0, *) { stackAll.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true } else { let topMargin = stackAll.topAnchor.constraint(equalTo: view.layoutMarginsGuide.topAnchor, constant: 0) topMargin.priority = UILayoutPriority(rawValue: 250) topMargin.isActive = true let top20 = stackAll.topAnchor.constraint(equalTo: view.topAnchor, constant: 20) top20.priority = UILayoutPriority(rawValue: 750) top20.isActive = true } stackAll.leadingAnchor.constraint(equalTo: view.safeLeadingAnchor, constant: 0).isActive = true stackAll.bottomAnchor.constraint(equalTo: view.safeBottomAnchor, constant: 0).isActive = true stackAll.trailingAnchor.constraint(equalTo: view.safeTrailingAnchor, constant: 0).isActive = true } func setNavigation() { navBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 44)) // navTitle.title = "Resources" navBar.setItems([navTitle], animated: false) navBar.tintColor = UIColor.white stackAll.addArrangedSubview(navBar) navBar.applyNavigationGradient(colors: [R.color.YumaDRed, R.color.YumaRed], isVertical: true) navBar.topItem?.title = "Resources" navClose = UIBarButtonItem(barButtonSystemItem: .stop, target: nil, action: #selector(navCloseAct(_:))) navTitle.leftBarButtonItems = [navClose] // navTitle.rightBarButtonItems = [navHelp] } func fillContent() { debugList = [ ResourceStringAndCount(name: "addresses", count: store.addresses.count), ResourceStringAndCount(name: "carriers", count: store.carriers.count), ResourceStringAndCount(name: "cart_rules", count: nil/*store.cartRules.count*/), ResourceStringAndCount(name: "carts", count: store.carts.count), ResourceStringAndCount(name: "categories", count: store.categories.count), ResourceStringAndCount(name: "combinations", count: store.combinations.count), ResourceStringAndCount(name: "configurations", count: store.configurations.count), ResourceStringAndCount(name: "contacts", count: store.storeContacts.count), ResourceStringAndCount(name: "content_management_system", count: nil/*store.contentManagementSystem.count*/), ResourceStringAndCount(name: "countries", count: store.countries.count), ResourceStringAndCount(name: "currencies", count: store.currencies.count), ResourceStringAndCount(name: "customer_messages", count: nil/*store.customerMessages.count*/), ResourceStringAndCount(name: "customer_threads", count: nil/*store.customerThreads.count*/), ResourceStringAndCount(name: "customers", count: nil/*store.customers.count*/), ResourceStringAndCount(name: "customizations", count: nil/*store.customizations.count*/), ResourceStringAndCount(name: "deliveries", count: nil/*store.deliveries.count*/), ResourceStringAndCount(name: "employees", count: nil/*store.employees.count*/), ResourceStringAndCount(name: "groups", count: nil/*store.groups.count*/), ResourceStringAndCount(name: "guests", count: nil/*store.guests.count*/), ResourceStringAndCount(name: "image_types", count: nil/*store.imageTypes.count*/), ResourceStringAndCount(name: "images", count: nil/*store.images.count*/), ResourceStringAndCount(name: "languages", count: store.langs.count), ResourceStringAndCount(name: "manufacturers", count: store.manufacturers.count), ResourceStringAndCount(name: "messages", count: nil/*store.messages.count*/), ResourceStringAndCount(name: "order_carriers", count: store.orderCarriers.count), ResourceStringAndCount(name: "order_details", count: store.orderDetails.count), ResourceStringAndCount(name: "order_histories", count: store.orderHistories.count), ResourceStringAndCount(name: "order_invoices", count: nil/*store.orderInvoices.count*/), ResourceStringAndCount(name: "order_payments", count: nil/*store.orderPayments.count*/), ResourceStringAndCount(name: "order_slip", count: nil/*store.orderSlip.count*/), ResourceStringAndCount(name: "order_states", count: store.orderStates.count), ResourceStringAndCount(name: "orders", count: store.orders.count), ResourceStringAndCount(name: "price_ranges", count: nil/*store.priceRanges.count*/), ResourceStringAndCount(name: "product_customization_fields", count: nil/*store.productCustomizationFields.count*/), ResourceStringAndCount(name: "product_feature_values", count: nil/*store.productFeatureValues.count*/), ResourceStringAndCount(name: "product_features", count: nil/*store.productFeatures.count*/), ResourceStringAndCount(name: "product_option_values", count: store.productOptionValues.count), ResourceStringAndCount(name: "product_options", count: store.productOptions.count), ResourceStringAndCount(name: "product_suppliers", count: nil/*store.productSuppliers.count*/), ResourceStringAndCount(name: "products", count: store.products.count), ResourceStringAndCount(name: "search", count: nil/*store.search.count*/), ResourceStringAndCount(name: "shop_groups", count: nil/*store.shopGroups.count*/), ResourceStringAndCount(name: "shop_urls", count: nil/*store.shopUrls.count*/), ResourceStringAndCount(name: "shops", count: nil/*store.shops.count*/), ResourceStringAndCount(name: "specific_price_rules", count: nil/*store.specificPriceRules.count*/), ResourceStringAndCount(name: "specific_prices", count: nil/*store.specificPrices.count*/), ResourceStringAndCount(name: "states", count: store.states.count), ResourceStringAndCount(name: "stock_availables", count: nil/*store.stockAvailables.count*/), ResourceStringAndCount(name: "stock_movement_reasons", count: nil/*store.stockMovementReasons.count*/), ResourceStringAndCount(name: "stock_movement", count: nil/*store.stockMovement.count*/), ResourceStringAndCount(name: "stocks", count: nil/*store.stocks.count*/), ResourceStringAndCount(name: "stores", count: nil/*store.stores.count*/), ResourceStringAndCount(name: "suppliers", count: nil/*store.suppliers.count*/), ResourceStringAndCount(name: "supply_order_details", count: nil/*store.supplyOrderDetails.count*/), ResourceStringAndCount(name: "supply_order_histories", count: nil/*store.supplyOrderHistories.count*/), ResourceStringAndCount(name: "supply_order_receipt_histories", count: nil/*store.supplyOrderReceiptHistories.count*/), ResourceStringAndCount(name: "supply_order_states", count: nil/*store.supplyOrderStates.count*/), ResourceStringAndCount(name: "supply_orders", count: nil/*store.supplyOrders.count*/), ResourceStringAndCount(name: "tags", count: store.tags.count), ResourceStringAndCount(name: "tax_rule_groups", count: nil/*store.taxRuleGroups.count*/), ResourceStringAndCount(name: "tax_rules", count: nil/*store.taxRules.count*/), ResourceStringAndCount(name: "taxes", count: store.taxes.count), ResourceStringAndCount(name: "translated_configurations", count: nil/*store.translatedConfigurations.count*/), ResourceStringAndCount(name: "warehouse_product_locations", count: nil/*store.warehouseProductLocations.count*/), ResourceStringAndCount(name: "warehouses", count: nil/*store.warehouses.count*/), ResourceStringAndCount(name: "weight_ranges", count: nil/*store.weight.count*/), ResourceStringAndCount(name: "zones", count: nil/*store.zones.count*/) ] let mirror = Mirror(reflecting: store) for (key, val) in mirror.children { guard let key = key else { continue } if type(of: val) != Int.self && type(of: val) != String.self && type(of: val) != Bool.self { store.properties.append(key) } } } @objc func navCloseAct(_ sender: AnyObject) { self.dismiss(animated: false, completion: nil) } } extension ResourcesViewController: UITableViewDelegate, UITableViewDataSource { // func numberOfSections(in tableView: UITableView) -> Int // { // return 26 // } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return "" } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if self.debugList == nil { return 0 } return debugList!.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellId) as! ResourceCell if let debugList = debugList, debugList.count >= indexPath.row { if debugList[indexPath.row].count != nil { cell.setup(debugList[indexPath.row].name, String(debugList[indexPath.row].count!)) } else { cell.setup(debugList[indexPath.row].name) } cell.backgroundColor = (indexPath.row % 2 == 0) ? UIColor.init(hex: altRowColor) : UIColor.white } return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if debugList != nil && debugList?[indexPath.item] != nil && debugList?[indexPath.item].count != nil && debugList![indexPath.item].count! > 0 { let vc = ResourceStage2ViewController() vc.name = (debugList?[indexPath.row].name)! vc.count = (debugList?[indexPath.row].count)! // navigationController?.pushViewController(vc, animated: false) self.present(vc, animated: false) tableView.deselectRow(at: indexPath, animated: true) } } } class ResourceCell: UITableViewCell { var labelKey: UILabel = { let view = UILabel() view.translatesAutoresizingMaskIntoConstraints = false view.text = "key" view.textColor = UIColor.blueApple view.font = UIFont.boldSystemFont(ofSize: 17) // view.attributedText = NSMutableAttributedString(string: view.text!, attributes: [NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 17), NSAttributedStringKey.foregroundColor: UIColor.blueApple]) return view }() var labelValue: UILabel = { let view = UILabel() view.translatesAutoresizingMaskIntoConstraints = false view.text = "value" view.textColor = UIColor.gray view.font = UIFont.systemFont(ofSize: 17) // view.attributedText = NSMutableAttributedString(string: view.text!, attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 17)]) return view }() let store = DataStore.sharedInstance var properties: [String : String]? func setup(_ key: String, _ value: String? = nil) { addSubview(labelKey) addSubview(labelValue) addConstraintsWithFormat(format: "V:|-8-[v0]-8-|", views: labelKey) addConstraintsWithFormat(format: "V:|-8-[v0]-8-|", views: labelValue) addConstraintsWithFormat(format: "H:|-4-[v0]-2-[v1]-4-|", views: labelKey, labelValue) labelKey.text = key.replacingOccurrences(of: "_", with: " ").capitalized if value != nil { labelValue.text = value } else { labelValue.text = "-" } } } //struct Sections //{ // var opened = Bool() // var title = String() // var contents: ResourceStringAndCount //}
// // CustomTextFiledView.swift // SwiftUIPractice // // Created by Mac on 2020/5/11. // Copyright © 2020 灵 Q. All rights reserved. // import SwiftUI struct CustomTextFiledView: UIViewRepresentable { var changeHandler:((String) -> Void)? func makeCoordinator() -> Coordinator { Coordinator(self) } func makeUIView(context: UIViewRepresentableContext<CustomTextFiledView>) -> UITextField { let tv = UITextField() tv.tintColor = .secondaryLabel tv.font = UIFont.systemFont(ofSize: 16) tv.delegate = context.coordinator tv.returnKeyType = .default tv.placeholder = "请输入你想要记录的内容" return tv } func updateUIView(_ uiView: UITextField, context: UIViewRepresentableContext<CustomTextFiledView>) { } class Coordinator: NSObject, UITextFieldDelegate { var masTextView: CustomTextFiledView init(_ textView: CustomTextFiledView) { self.masTextView = textView } func textFieldDidChangeSelection(_ textField: UITextField) { masTextView.changeHandler?(textField.text ?? "") } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } } }
// // ViewController.swift // MotionEffect // // // A Demo for iOS Development Tips Weekly // by Steven Lipton (C)2020, All rights reserved // Check out the video series on LinkedIn learning at https://linkedin-learning.pxf.io/YxZgj // For code go to http://bit.ly/AppPieGithub import UIKit class ViewController : UIViewController { var surferImageView = UIImageView() @IBOutlet weak var backgroundImageView: UIImageView! func motionEffects(magnitude:Float)->UIMotionEffectGroup{ let group = UIMotionEffectGroup() let xMotion = UIInterpolatingMotionEffect(keyPath: "center.x", type: .tiltAlongHorizontalAxis) xMotion.minimumRelativeValue = -magnitude xMotion.maximumRelativeValue = magnitude let yMotion = UIInterpolatingMotionEffect(keyPath: "center.y", type: .tiltAlongVerticalAxis) yMotion.minimumRelativeValue = -magnitude yMotion.maximumRelativeValue = magnitude group.motionEffects = [xMotion,yMotion] return group } override func viewWillLayoutSubviews() { let inset:CGFloat = 200 let bounds = UIScreen.main.bounds surferImageView.frame = bounds.insetBy(dx: inset, dy: inset) } override func viewDidLoad() { super.viewDidLoad() surferImageView.image = UIImage(named: "Surfer Girl.jpg") surferImageView.contentMode = .scaleAspectFill surferImageView.addMotionEffect(motionEffects(magnitude: 300)) backgroundImageView.addMotionEffect(motionEffects(magnitude: 100)) view.addSubview(surferImageView) } }
//: [Previous](@previous) import Foundation enum TaterTotSize { case small, regular, huge func mass() -> Double { // This gets a switch self { case .small: return 5.0 case .regular: return 8.4 case .huge: return 12.8 } } } struct TaterTotStructure { let brand: String let size: TaterTotSize let extras: [String] } class TaterTotClass { let brand: String let size: TaterTotSize let extras: [String] init(brand: String, size: TaterTotSize, extras: [String]) { self.brand = brand self.size = size self.extras = extras } } let taterStruct = TaterTotStructure(brand: "Ore Ida", size: .regular, extras: []) let taterClass = TaterTotClass(brand: "Ore Ida", size: .regular, extras: []) struct BasicStruct { var number = 0 } class BasicClass { var number = 0 } let struct1 = BasicStruct() print(struct1.number) var struct2 = struct1 // make this a constant to start struct2.number = 42 print(struct1.number) print(struct2.number) let basic1 = BasicClass() let basic2 = basic1 print("Basic1: \(basic1.number)") basic1.number = 42 print("Basic1: \(basic1.number)") print("Basic2 after changing basic1: \(basic2.number)") basic1 === basic2 struct TaterTotBatch { let totSize: TaterTotSize let quantity: Int var totalMass: Double { return Double(quantity) * totSize.mass() } } let batch = TaterTotBatch(totSize: .huge, quantity: 20) print(batch.totalMass) //batch.totalMass = 100 class Counter { var count = 0 func increment() { count += 1 } func increment(by amount: Int) { count += amount } func reset() { count = 0 } } class PotatoSnack { var kindOfPotato: String init(kindOfPotato: String) { self.kindOfPotato = kindOfPotato } func printWhatAmI() { print("I am a potato snack.") } } class TaterTot: PotatoSnack { let size: TaterTotSize var brand: String? init(size: TaterTotSize) { self.size = size super.init(kindOfPotato: "Mixed") } convenience init() { self.init(size: .regular) } override func printWhatAmI() { if let brand = brand { print("I am a perfect \(brand) brand tater tot.") } else { print("I am a delicious tater tot.") } } deinit { print("About to deint.") } } let potatoSnack = PotatoSnack(kindOfPotato: "Russet") let taterTot = TaterTot(size: .huge) potatoSnack.printWhatAmI() taterTot.printWhatAmI() // Go back and add brand optional taterTot.brand = "Ore Ida" taterTot.printWhatAmI() // Deinitilization var tot: TaterTot? = TaterTot() tot = nil class Employee { var name: String weak var boss: Employee? { didSet { boss?.directReports.append(self) } } var directReports = [Employee]() init(_ name: String) { self.name = name } deinit { print("Calling deinit on \(name)") } } extension Employee: CustomDebugStringConvertible { var debugDescription: String { if let boss = boss { return "\(name) and their boss is \(boss.name)" } return "\(name)" } } // Start these off as let and then change to optional to show deinit var samantha: Employee? = Employee("Samantha") var kirk: Employee? = Employee("Kirk") kirk!.boss = samantha samantha = nil let snack: PotatoSnack = TaterTot() snack.printWhatAmI() // snack.size doesn't exist (snack as? TaterTot)?.size //: [Next](@next)
// // RemoteNotificationsManager.swift // BeeSwift // // Created by Andy Brett on 5/8/15. // Copyright (c) 2015 APB. All rights reserved. // import Foundation class RemoteNotificationsManager :NSObject { static let sharedManager = RemoteNotificationsManager() required override init() { super.init() NotificationCenter.default.addObserver(self, selector: #selector(RemoteNotificationsManager.handleUserSignoutNotification), name: NSNotification.Name(rawValue: CurrentUserManager.willSignOutNotificationName), object: nil) } fileprivate func remoteNotificationsOnKey() -> String { if CurrentUserManager.sharedManager.signedIn() { return "\(CurrentUserManager.sharedManager.username!)-remoteNotificationsOn" } return "remoteNotificationsOn" } @objc func handleUserSignoutNotification() { turnNotificationsOff() } func on() -> Bool { return UserDefaults.standard.object(forKey: self.remoteNotificationsOnKey()) != nil } func turnNotificationsOn() { UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [UIUserNotificationType.alert, UIUserNotificationType.sound, UIUserNotificationType.badge], categories: nil)) UIApplication.shared.registerForRemoteNotifications() } func turnNotificationsOff() { UserDefaults.standard.removeObject(forKey: self.remoteNotificationsOnKey()) UserDefaults.standard.synchronize() } func didRegisterForRemoteNotificationsWithDeviceToken(_ deviceToken: Data) { UserDefaults.standard.set(true, forKey: self.remoteNotificationsOnKey()) UserDefaults.standard.synchronize() let token = deviceToken.reduce("", {$0 + String(format: "%02X", $1)}) SignedRequestManager.signedPOST(url: "/api/private/device_tokens", parameters: ["device_token" : token], success: { (responseObject) -> Void in //foo }) { (error) -> Void in //bar } } func didFailToRegisterForRemoteNotificationsWithError(_ error: Error) { // nothing to do } func didRegisterUserNotificationSettings(_ notificationSettings: UIUserNotificationSettings) { // nothing to do } }
// // String.swift // Movie // // Created by Daniel on 16/3/16. // Copyright © 2016年 Daniel. All rights reserved. // import Foundation import UIKit extension NSString { func sizeForFont(font:UIFont,maxH:CGFloat) -> CGSize { let maxSize = CGSize(width: CGFloat.max, height: maxH) let rect = self.boundingRectWithSize(maxSize, options: .UsesLineFragmentOrigin, attributes: [NSFontAttributeName : font], context: nil) return rect.size } }
/* * This file is part of Adblock Plus <https://adblockplus.org/>, * Copyright (C) 2006-present eyeo GmbH * * Adblock Plus is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as * published by the Free Software Foundation. * * Adblock Plus is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Adblock Plus. If not, see <http://www.gnu.org/licenses/>. */ import Foundation struct CreateProperties: JSObjectConvertibleParameter { var windowId: UInt? var index: Int? var url: String? var active: Bool? init?(object: [AnyHashable: Any]) { windowId = object["windowId"] as? UInt index = object["index"] as? Int url = object["url"] as? String active = object["active"] as? Bool } } struct UpdateProperties: JSObjectConvertibleParameter { var url: String? init?(object: [AnyHashable: Any]) { url = object["url"] as? String } } struct QueryProperties: JSObjectConvertibleParameter { var active: Bool? init?(object: [AnyHashable: Any]) { active = object["active"] as? Bool } } protocol ChromeTabsProtocol { // MARK: - JS Interface func get(_ tabId: UInt) throws -> Any? func query(_ properties: QueryProperties) throws -> Any? func create(_ createProperties: CreateProperties) throws -> Any? func update(_ tabId: UInt, _ updateProperties: UpdateProperties) throws -> Any? func remove(_ tabIds: JSArray<UInt>) throws -> Any? func sendMessage(_ tabId: UInt, _ message: JSAny/*, object options*/, _ completion: StandardCompletion?) throws } extension ChromeTabsProtocol { func remove_1(_ tabId: UInt) throws -> Any? { return try remove([tabId]) } } struct ChromeTabsFactory: StandardHandlerFactory { typealias Handler = ChromeTabs let bridgeContext: JSBridgeContext } struct ChromeTabs: StandardHandler, MessageDispatcher { let context: CommandDispatcherContext let bridgeContext: JSBridgeContext var chrome: Chrome { return context.chrome } } extension ChromeTabs: ChromeTabsProtocol { // MARK: - ChromeTabsProtocol func get(_ tabId: UInt) throws -> Any? { if let (index, tab) = chrome.findTab(tabId) { return tab.chromeTabObjectWithIndex(index) } else { // Chrome interface asking for tab which does not exist anymore (was removed) throw IgnorableError(with: CodeRelatedError( KittCoreError.chromeTabNotFound, message: "Tab with '\(index)' hasn't been found")) } } func query(_ properties: QueryProperties) throws -> Any? { return chrome.windows .map { $0.typedTabs.enumerated() } .joined() .filter { _, tab in if let active = properties.active { return tab.active == active } else { return true } } .map { index, tab in return tab.chromeTabObjectWithIndex(index) } } func create(_ createProperties: CreateProperties) throws -> Any? { let window: ChromeWindow if let uwId = createProperties.windowId, let uwWindow = chrome[uwId] { window = uwWindow } else if let uwWindow = context.sourceWindow { window = uwWindow } else { window = chrome.focusedWindow! } // "value will be clamped to between zero and the number of tabs in the window" // index parameter is optional but Google doesn't document where the new tab // should be when index isn't defined. Guessing from Chrome behavior, the last one. // Because NSNotFound is big positive number, it will get clamped to the last one. let index = max(0, min(window.tabs.count, createProperties.index ?? window.tabs.count)) let url: URL? if let urlString = createProperties.url { url = URL(string: urlString) } else { url = nil } let tab = window.add(tabWithURL: url, atIndex: index) if let tab = tab, let active = createProperties.active, active { window.focused = true tab.active = true } return tab?.chromeTabObjectWithIndex(index) } func update(_ tabId: UInt, _ updateProperties: UpdateProperties) throws -> Any? { if let (index, tab) = chrome.findTab(tabId) { if let urlString = updateProperties.url, let url = URL(string: urlString) { // Is requested view active? if tab.active && tab.window.focused { context.source.bridgeSwitchboard?.browserControlDelegate?.load(url) } else { tab.URL = url as NSURL? } } return tab.chromeTabObjectWithIndex(index) } else { // Chrome interface asking for tab which does not exist anymore (was removed) throw IgnorableError(with: CodeRelatedError( KittCoreError.chromeTabNotFound, message: "Tab with '\(index)' hasn't been found")) } } func remove(_ tabIds: JSArray<UInt>) throws -> Any? { for window in chrome.windows { var tabsToRemove = [ChromeTab]() for tab in window.tabs.lazy.compactMap({ $0 as? ChromeTab }) { if tabIds.contains(tab.identifier) { // tab to be removed tabsToRemove.append(tab) } } window.remove(tabs: tabsToRemove) let tab: ChromeTab if let uwTab = chrome.focusedWindow?.activeTab { tab = uwTab } else if let uwTab = chrome.windows.compactMap({ $0.activeTab }).first { tab = uwTab } else if let uwTab = chrome.windows.compactMap({ Array($0.typedTabs.suffix(1)).first }).first { tab = uwTab } else { context.source.bridgeSwitchboard?.browserControlDelegate?.showNewTab(with: nil, fromSource: nil) return nil } tab.window.focused = true tab.active = true } return nil } func sendMessage(_ tabId: UInt, _ message: JSAny/*, object options*/, _ completion: StandardCompletion?) throws { let callbacks = context.`extension`.callbacksToContent(for: .runtimeMessage, andTab: Int(tabId)) dispatch(callbacks, message: message.any, completion: { result in if case let .failure(error) = result, error._code == KittCoreErrorCode.chromeMessageCallbackNotFound.rawValue { completion?(.failure(IgnorableError(with: error))) } else { completion?(result) } }) } // MARK: - fileprivate } func registerChromeTabsHandlers<F>(_ dispatcher: CommandDispatcher, withFactory factory: F) where F: HandlerFactory, F.Handler: ChromeTabsProtocol { typealias Handler = F.Handler dispatcher.register(factory, handler: Handler.get, forName: "tabs.get") dispatcher.register(factory, handler: Handler.query, forName: "tabs.query") dispatcher.register(factory, handler: Handler.create, forName: "tabs.create") dispatcher.register(factory, handler: Handler.update, forName: "tabs.update") dispatcher.register(factory, handler: Handler.remove, forName: "tabs.remove") dispatcher.register(factory, handler: Handler.remove_1, forName: "tabs.remove") dispatcher.register(factory, handler: Handler.sendMessage, forName: "tabs.sendMessage") }
// // ViewController.swift // CoreData // // Created by jianwei on 15/7/21. // Copyright (c) 2015年 Jianwei. All rights reserved. // import UIKit import CoreData class ViewController: UIViewController { lazy var appdelegate = { return UIApplication.sharedApplication().delegate as! AppDelegate }() @IBOutlet weak var booktext: UITextField! @IBOutlet weak var authortext: UITextField! @IBAction func insert(sender: AnyObject){ //为实体增加新的托管对象 var object:Book = NSEntityDescription.insertNewObjectForEntityForName("Book", inManagedObjectContext:appdelegate.managedObjectContext! ) as! Book //给托管对象属性赋值 object.name = booktext.text object.author = authortext.text //将插入的托管对象保存到数据库 appdelegate.saveContext() } @IBAction func deleteitem(sender: AnyObject) { var request = NSFetchRequest(entityName: "Book") var predicate = NSPredicate(format: "%K == %@", "name", booktext.text) request.predicate = predicate var error: NSError? var result = appdelegate.managedObjectContext!.executeFetchRequest(request, error: &error) as![NSManagedObject] for obj: NSManagedObject in result{ //删除查找到的书籍 appdelegate.managedObjectContext!.deleteObject(obj) } appdelegate.saveContext() } @IBAction func update(sender: AnyObject) { var request = NSFetchRequest(entityName: "Book") var predicate = NSPredicate(format: "%K == %@", "name", booktext.text) request.predicate = predicate var error:NSError? //按书名查找 var result = appdelegate.managedObjectContext!.executeFetchRequest(request, error: &error) as![NSManagedObject] for obj:NSManagedObject in result { //修改作者名字 obj.setValue(authortext.text, forKey: "author") } //保存数据更改 appdelegate.saveContext() } @IBAction func query(sender: AnyObject) { var request = NSFetchRequest(entityName: "Book") //如果书名不为空则按书名作为查询条件查找,否则列出所有对象 if !booktext.text.isEqual(""){ var predicate = NSPredicate(format: "%K == %@", "name", booktext.text) request.predicate = predicate } var error: NSError? var result = appdelegate.managedObjectContext?.executeFetchRequest(request, error: &error) as? [Book] if let r = result{ for book in r{ NSLog("---- query result --> name:%@ author:%@",book.name, book.author) } } } }
// // CheckAsthmaStatusViewController.swift // Pulmonis // // Created by Manivannan Solan on 02/01/2017. // Copyright © 2017 Manivannan Solan. All rights reserved. // import UIKit import CoreData import HealthKit class CheckAsthmaStatusViewController: UIViewController { @IBOutlet weak var resultLabel: UILabel! @IBOutlet weak var statusImage: UIImageView! @IBOutlet weak var asthmaStatusLabel: UILabel! @IBOutlet weak var nextButton: UIButton! @IBAction func popupHealth(_ sender: UIButton) { let refreshAlert = UIAlertController(title: "HealthKit Support", message: "The highest peak flow value will be automatically saved to the Health app", preferredStyle: UIAlertControllerStyle.alert) refreshAlert.addAction(UIAlertAction(title: "Dismiss", style: .default, handler: { (action: UIAlertAction!) in self.dismiss(animated: true, completion: nil) })) present(refreshAlert, animated: true, completion: nil) } let healthStore = HKHealthStore() var managedObjectContext: NSManagedObjectContext? = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext override func viewDidLoad() { super.viewDidLoad() /* Healthkit setup */ let typestoRead = Set([ HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.peakExpiratoryFlowRate)! ]) let typestoShare = Set([ HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.peakExpiratoryFlowRate)! ]) self.healthStore.requestAuthorization(toShare: typestoShare, read: typestoRead) { (success, error) -> Void in if success == false { NSLog(" Display not allowed") } } let request: NSFetchRequest<PeakFlowTable> = PeakFlowTable.fetchRequest() let sortDescriptor = NSSortDescriptor(key: "date", ascending: false) request.sortDescriptors = [sortDescriptor] request.fetchLimit = 1 let result = try? managedObjectContext!.fetch(request) resultLabel.text = "Your highest peak flow reading was \((result?[0].value)!) L/min" // SAVE PEAK FLOW VALUE TO HEALTH APP if let peakFlowType = HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.peakExpiratoryFlowRate) { let object = HKQuantitySample(type: peakFlowType, quantity: HKQuantity.init(unit: HKUnit.liter().unitDivided(by: HKUnit.minute()), doubleValue: Double((result?[0].value)!)), start: Date(), end: Date()) healthStore.save(object, withCompletion: { (success, error) -> Void in if error != nil { print("[DEBUG] Error occurred in saving to HealthKit!") return } if success { print("[DEBUG] My new data was saved in HealthKit!") } else { print("[DEBUG] Failure to save to HealthKit!") } }) } var worseVal: Int16 = 500 var criticalVal: Int16 = 200 if let plist = Plist(name: "PatientData") { let dict = plist.getMutablePlistFile()! if let yMinimumPeakFlow = dict[yMinimumPeakFlowStr] { if let yMinimumPeakFlowString = yMinimumPeakFlow as? String { if yMinimumPeakFlowString != "" { worseVal = Int16(yMinimumPeakFlowString)! } } } if let rMinimumPeakFlow = dict[rMinimumPeakFlowStr] { if let rMinimumPeakFlowString = rMinimumPeakFlow as? String { if rMinimumPeakFlowString != "" { criticalVal = Int16(rMinimumPeakFlowString)! } } } } else { //Error with opening the PList } let val = Int16((result?[0].value)!) /* Karow and Ziyi need to access plist to get the correct threshold value for patient. */ if (val < criticalVal) { //Action plan 'worse' value statusImage.image = UIImage(named: "red") nextButton.addTarget(self, action: #selector(criticalSegue), for: .touchUpInside) asthmaStatusLabel.text = "According to you doctor, your asthma condition seems to be in a critical condition" } else if (val < worseVal) { // Action Plan 'critical' value statusImage.image = UIImage(named: "yellow") nextButton.addTarget(self, action: #selector(worseSegue), for: .touchUpInside) asthmaStatusLabel.text = "According to you doctor, your asthma condition seems to be in a worse condition" } else { statusImage.image = UIImage(named: "green") nextButton.addTarget(self, action: #selector(wellSegue), for: .touchUpInside) asthmaStatusLabel.text = "According to you doctor, your asthma condition seems to be in a normal condition" } // Do any additional setup after loading the view. } func criticalSegue(){ performSegue(withIdentifier: "showCritical", sender: self) } func worseSegue(){ performSegue(withIdentifier: "showWorse", sender: self) } func wellSegue(){ performSegue(withIdentifier: "showWell", sender: self) } /* // 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. } */ }
// // DetailRow.swift // Timer // // Created by Ingrid on 16/11/2020. // Copyright © 2020 Ingrid. All rights reserved. // import Foundation import UIKit class DetailRow: UIView { let typeIcon: UIImageView = { let imageView = UIImageView() imageView.translatesAutoresizingMaskIntoConstraints = false imageView.backgroundColor = .clear imageView.image = UIImage(named: "Favourite") imageView.contentMode = .scaleAspectFit return imageView }() let unitLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.backgroundColor = .clear label.numberOfLines = 1 label.textColor = UIColor(named: Constants.lightText) label.textAlignment = .center label.font = Constants.mainFont return label }() let detailLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.backgroundColor = .clear label.numberOfLines = 1 label.textColor = UIColor(named: Constants.lightText) label.textAlignment = .center label.font = Constants.mainFontLargeSB return label }() let titleLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.backgroundColor = .clear label.numberOfLines = 0 label.textColor = UIColor(named: Constants.lightText) label.textAlignment = .left label.font = Constants.mainFont return label }() override init(frame: CGRect) { super.init(frame: frame) self.addSubview(typeIcon) self.addSubview(titleLabel) self.addSubview(detailLabel) self.addSubview(unitLabel) setConstraints() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setProperties(title: String, unit: String, icon: String, detail: String) { typeIcon.image = UIImage(named: icon) titleLabel.text = title detailLabel.text = detail unitLabel.text = unit } func setConstraints() { typeIcon.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true typeIcon.topAnchor.constraint(equalTo: self.topAnchor).isActive = true typeIcon.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true typeIcon.widthAnchor.constraint(equalTo: self.widthAnchor, multiplier: 1/16).isActive = true titleLabel.leadingAnchor.constraint(equalTo: typeIcon.trailingAnchor).isActive = true titleLabel.topAnchor.constraint(equalTo: self.topAnchor).isActive = true titleLabel.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true titleLabel.widthAnchor.constraint(equalTo: self.widthAnchor, multiplier: 9/16).isActive = true detailLabel.leadingAnchor.constraint(equalTo: titleLabel.trailingAnchor).isActive = true detailLabel.topAnchor.constraint(equalTo: self.topAnchor).isActive = true detailLabel.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true detailLabel.widthAnchor.constraint(equalTo: self.widthAnchor, multiplier: 4/16).isActive = true unitLabel.leadingAnchor.constraint(equalTo: detailLabel.trailingAnchor).isActive = true unitLabel.topAnchor.constraint(equalTo: self.topAnchor).isActive = true unitLabel.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true unitLabel.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true } }
// // NetworkingDataService.swift // Friendji // // Created by Kasra Abasi on 8/3/19. // Copyright © 2019 kasraabasi. All rights reserved. // /// This is singelton responsible for sending HTTP request and parsing the response when web service api and backend is ready /// it also have a decodeJSONFromFile for moking fake requests import Foundation class NetworkingDataService { // MARK: - Inner Types enum DecodeResult<T> { case success(T) case failure(NetworkingDataServiceError) } enum RequestMethod: String { case get = "GET" case post = "POST" case put = "PUT" case delete = "DELETE" } enum NetworkingDataServiceError: String, Error, LocalizedError { case invalidURL case decodeFailed case statusCodeNot200 case invalidPayload var errorDescription: String? { return NSLocalizedString((self.rawValue), comment: "") } } typealias JSON = [String: Any] // MARK: - Properties static let shared = NetworkingDataService() // MARK: - Initializers private init(){} // MARK: - Methods func decodeJSONFromFile<T: Decodable>(fileName: String, for: T.Type = T.self, completion: @escaping (DecodeResult<T>) -> Void) { guard let url = Bundle.main.url(forResource: fileName, withExtension: "json") else { completion(.failure(.invalidURL)) return } do { let data = try Data(contentsOf: url) let decoder = JSONDecoder() let jsonData = try decoder.decode(T.self, from: data) DispatchQueue.main.async { completion(.success(jsonData)) } } catch let error { print(error) completion(.failure(.decodeFailed)) } } func sendHTTPRequest<T: Decodable>(for: T.Type = T.self, url: String, method: RequestMethod, body: JSON? = nil, token: String? = nil, completion: @escaping (DecodeResult<T>) -> Void) { guard let url = URL(string: url) else { completion(.failure(.invalidURL)) return } let urlRequest = NSMutableURLRequest(url: url) urlRequest.httpMethod = method.rawValue urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type") if let token = token { urlRequest.addValue("Bearer \(token)", forHTTPHeaderField: "Authorization") } urlRequest.timeoutInterval = 10.0 if let body = body { urlRequest.httpBody = try? JSONSerialization.data(withJSONObject: body) } let session = URLSession(configuration: .default) let task = session.dataTask(with: urlRequest as URLRequest) { data, response, error in let status = (response as? HTTPURLResponse)?.statusCode ?? -1 DispatchQueue.main.async { if status == 200 { guard let data = data else { return completion(.failure(.invalidPayload)) } do { let decoder = JSONDecoder() let jsonData = try decoder.decode(T.self, from: data) completion(.success(jsonData)) } catch let decodingError { print(decodingError) completion(.failure(.decodeFailed)) } } else { completion(.failure(.statusCodeNot200)) } } } task.resume() } }
// // CalendarViewController.swift // OutlookCalendar // // Created by Pnina Eliyahu on 1/5/18. // Copyright © 2018 Pnina Eliyahu. All rights reserved. // import UIKit // A view controller for displaying the calendar collection view class CalendarViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource { var observer : CalendarObserver? private let rangedCalendar = RangedCalendar.shared private let numberOfDaysInWeek = 7 private let weekDaysHeaderHeight : CGFloat = 30.0 private lazy var daysCollectionView: UICollectionView! = { // We use the ContinuousSectionsLayout so sections dont break into new lines let layout = ContinuousSectionsGridLayout() layout.numberOfColumns = numberOfDaysInWeek layout.delegate = self let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout) collectionView.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1) collectionView.delegate = self collectionView.dataSource = self collectionView.register(DayCell.self, forCellWithReuseIdentifier: DayCell.reuseIdentifier) return collectionView }() // This view is displayed as the calendar header, and shows the week days titles private lazy var weekDaysStackView : UIStackView! = { let stackView = UIStackView() stackView.axis = .horizontal stackView.alignment = .fill stackView.distribution = .fillEqually let dateFormatter = DateFormatter() for weekDay in 0..<numberOfDaysInWeek { let view = WeekDayView() view.title.text = dateFormatter.shortWeekdaySymbols[weekDay] stackView.addArrangedSubview(view) } return stackView }() override func viewDidLoad() { super.viewDidLoad() view = UIView(frame: UIScreen.main.bounds) view.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0) view.addSubview(weekDaysStackView) view.addSubview(daysCollectionView) } // Scroll to the given date func chooseDate(date:Date, animated: Bool) { let day = rangedCalendar.calendar.component(.day, from: date) if let month = rangedCalendar.monthNumberInRange(forDate: date) { let indexPath = IndexPath(item: day-1, section: month) daysCollectionView.selectItem(at: indexPath, animated: animated, scrollPosition: .top) } } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return rangedCalendar.numberOfDaysInMonth(forMonthNumberInRange: section) ?? 0 } func numberOfSections(in collectionView: UICollectionView) -> Int { return rangedCalendar.numberOfMonthsInRange } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: DayCell.reuseIdentifier, for: indexPath) if let dayCell = cell as? DayCell { // get the date to display for the indexPath if let date = rangedCalendar.dateFromStartDateByAddingMonths(months: indexPath.section, andDays: indexPath.row) { dayCell.title.text = String(Calendar.current.component(.day, from: date)) dayCell.backgroundColor = indexPath.section % 2 == 0 ? #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0) : #colorLiteral(red: 0.9701757813, green: 0.9701757813, blue: 0.9701757813, alpha: 1) } } cell.selectedBackgroundView = { let backgroundView = UIView(frame: CGRect(origin: .zero, size: cell.frame.size)) backgroundView.backgroundColor = cell.backgroundColor let selectedCircleSize = backgroundView.frame.size.width * 0.8 let selectedCircleView = UIView(frame: CGRect(x: (cell.frame.size.width - selectedCircleSize) / 2, y: (cell.frame.size.height - selectedCircleSize) / 2, width: selectedCircleSize, height: selectedCircleSize)) selectedCircleView.backgroundColor = #colorLiteral(red: 0.8549019694, green: 0.250980407, blue: 0.4784313738, alpha: 1) selectedCircleView.layer.cornerRadius = selectedCircleSize/2 backgroundView.addSubview(selectedCircleView) return backgroundView }() return cell } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() var top = UIApplication.shared.statusBarFrame.size.height if let navigationBar = navigationController?.navigationBar { top += navigationBar.frame.size.height } weekDaysStackView.frame = CGRect(x: 0, y: top, width: view.frame.width, height: weekDaysHeaderHeight) daysCollectionView.frame = CGRect(x: 0, y: weekDaysStackView.frame.maxY, width: view.frame.width, height: view.frame.height - weekDaysHeaderHeight) } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if let date = rangedCalendar.dateFromStartDateByAddingMonths(months: indexPath.section, andDays: indexPath.row) { observer?.dateWasChosen(sender: self, date: date) } } func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { observer?.calendarWillStartScrolling(sender: self) } } extension CalendarViewController : ContinuousSectionsGridLayoutDelegte { func collectionView(collectionView: UICollectionView, heightForItemAtIndexPath indexPath: IndexPath) -> CGFloat { return 50 } }
// // LongPressGesture_4.swift // LearningSwiftUI // // Created by Metin HALILOGLU on 5/4/21. // import SwiftUI struct LongPressGesture_4: View { @State private var uzunBasiliyor = false @State private var normalBasiliyor = false var body: some View { VStack{ Text("Long Press Gesture Örnek - 1").font(.largeTitle) Text("Giriş").font(.title).foregroundColor(.gray) .padding(.bottom, 40) VStack { Image(systemName: uzunBasiliyor ? "lock.open.fill" : "lock.fill") .font(.largeTitle) } .frame(width: 100, height: 100) .modifier(LightButton()) .onLongPressGesture(minimumDuration: 3, pressing: { basiliyor in self.normalBasiliyor = basiliyor }){ uzunBasiliyor.toggle() } .padding(.bottom) Text("Basmaya Devam Edin").bold().foregroundColor(.red).opacity(normalBasiliyor ? 1 : 0) } } } struct LongPressGesture_4_Previews: PreviewProvider { static var previews: some View { LongPressGesture_4() } }
// // GroupLocationCell.swift // Flex // // Created by Joe Suzuki on 7/17/18. // Copyright © 2018 Joe Suzuki. All rights reserved. // import UIKit import MapKit class GroupLocationCell: UICollectionViewCell { // Location override init(frame: CGRect) { super.init(frame: frame) setupViews() } let mapView: MKMapView = { let map = MKMapView() return map }() let searchBar: UISearchBar = { let bar = UISearchBar() return bar }() func setupViews() { backgroundColor = .white addSubview(searchBar) addSubview(mapView) searchBar.anchor(top: self.topAnchor, leading: self.leadingAnchor, bottom: mapView.topAnchor, trailing: self.trailingAnchor) mapView.anchor(top: searchBar.bottomAnchor, leading: self.leadingAnchor, bottom: self.bottomAnchor, trailing: self.trailingAnchor) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
// // CoreDataStorageContext+Extension.swift // StorageAbstraction // // Created by Samvel on 9/12/19. // Copyright © 2019 Samo. All rights reserved. // import Foundation import CoreData extension CoreDataStorageContext { func create<T>(_ model: T.Type, completion: @escaping ((Any) -> Void)) throws where T : Storable { let managedContext = self.persistentContainer.viewContext let object = NSEntityDescription.insertNewObject(forEntityName: String(describing: model), into:self.persistentContainer.viewContext) managedContext.insert(object) completion(object) } func save(object: Storable) throws { let managedContext = self.persistentContainer.viewContext managedContext.insert(object as! NSManagedObject) try? managedContext.save() } func save(object: [Storable]) throws { let managedContext = self.persistentContainer.viewContext for obj in object { managedContext.insert(obj as! NSManagedObject) } try? managedContext.save() } func update(block: @escaping () -> ()) throws { // Nothing to do } } extension CoreDataStorageContext { func delete(object: Storable) throws { let managedContext = self.persistentContainer.viewContext managedContext.delete(object as! NSManagedObject) try managedContext.save() } func delete(object: [Storable]) throws { let managedContext = self.persistentContainer.viewContext for obj in object { managedContext.delete(obj as! NSManagedObject) } try managedContext.save() } func deleteAll<T>(_ model: T.Type) throws where T : Storable { let managedContext = self.persistentContainer.viewContext managedContext.delete(model as! T as! NSManagedObject) try managedContext.save() } func reset() throws { let managedContext = self.persistentContainer.viewContext managedContext.reset() try managedContext.save() } } extension CoreDataStorageContext { func fetch<T: Storable>(_ model: T.Type, predicate: NSPredicate? = nil, sorted: [Sorted]? = nil, completion: (([T]) -> ())) { let objects = getObjects(model, predicate: predicate, sorted: sorted) var accumulate: [T] = [T]() for object in objects { accumulate.append(object as! T) } completion(accumulate) } func fetch<T: Storable>(_ model: T.Type, predicate: NSPredicate? = nil, sorted: [Sorted]? = nil) -> [T] { let objects = getObjects(model, predicate: predicate, sorted: sorted) var accumulate: [T] = [T]() for object in objects { accumulate.append(object as! T) } return accumulate } fileprivate func getObjects<T: Storable>(_ model: T.Type, predicate: NSPredicate? = nil, sorted: [Sorted]? = nil) -> [NSManagedObject] { let managedContext = self.persistentContainer.viewContext let request = NSFetchRequest<NSFetchRequestResult>(entityName: String(describing: model)) request.predicate = predicate request.sortDescriptors = sorted?.map({NSSortDescriptor(key: $0.key, ascending: $0.asc)}) var result:[Any] = [] do { result = try managedContext.fetch(request) } catch { return [] } return result.map({$0 as! NSManagedObject}) } } extension NSManagedObject: Storable { }
// // MyChatCollectionViewCell.swift // Chat-App // // Created by Matheus Gois on 20/07/19. // Copyright © 2019 Matheus Gois. All rights reserved. // import UIKit class MyChatCollectionViewCell: UITableViewCell { @IBOutlet weak var titleMsg: UILabel! @IBOutlet weak var detailMsg: UILabel! }
// // ExtensionString.swift // test // // Created by 李远卓 on 2021/7/27. // import Foundation import UIKit extension String { // arrtibuted string setting: eg. line spacing, breakMode, color, font size func attributedString(lineSpaceing: CGFloat, lineBreakModel: NSLineBreakMode, keyword: String = "") -> NSAttributedString { let style = NSMutableParagraphStyle() style.lineSpacing = lineSpaceing style.lineBreakMode = lineBreakModel let attributes = [NSAttributedString.Key.paragraphStyle: style] as [NSAttributedString.Key: Any] let attrStr = NSMutableAttributedString.init(string: self, attributes: attributes) let theRange = NSString(string: self).range(of: keyword) attrStr.addAttributes([NSAttributedString.Key.foregroundColor: UIColor.greenColor], range: theRange) return attrStr } // divide string to array: "a/" -> ["a", ""] -> ["a"], "/" -> ["", ""] -> [] var array: [String] { let dividedFlag: CharacterSet = NSCharacterSet(charactersIn: "/") as CharacterSet var result = self.components(separatedBy: dividedFlag) result = result.filter({ label in return label != "" }) return result } } // set default optional value of string to "" extension Optional where Wrapped == String { var safe: String { return self ?? "" } }
import Errors import Foundation import HighwayDispatch import HWPod import Result import SignPost import SourceryAutoProtocols import ZFile // Generated using Sourcery 0.15.0 — https://github.com/krzysztofzablocki/Sourcery // DO NOT EDIT // MARK: - HWPodProtocolMock open class HWPodProtocolMock: HWPodProtocol { public init() {} public static var expectedCocoapodsVersion: String { get { return underlyingExpectedCocoapodsVersion } set(value) { underlyingExpectedCocoapodsVersion = value } } public static var underlyingExpectedCocoapodsVersion: String = "AutoMockable filled value" // MARK: - <attemptPodInstallIfOptionAddedToCommandline> - parameters public var attemptPodInstallIfOptionAddedToCommandlineThrowableError: Error? public var attemptPodInstallIfOptionAddedToCommandlineCallsCount = 0 public var attemptPodInstallIfOptionAddedToCommandlineCalled: Bool { return attemptPodInstallIfOptionAddedToCommandlineCallsCount > 0 } // MARK: - <attemptPodInstallIfOptionAddedToCommandline> - closure mocks public var attemptPodInstallIfOptionAddedToCommandlineClosure: (() throws -> Void)? // MARK: - <attemptPodInstallIfOptionAddedToCommandline> - method mocked open func attemptPodInstallIfOptionAddedToCommandline() throws { // <attemptPodInstallIfOptionAddedToCommandline> - Throwable method implementation if let error = attemptPodInstallIfOptionAddedToCommandlineThrowableError { throw error } attemptPodInstallIfOptionAddedToCommandlineCallsCount += 1 // <attemptPodInstallIfOptionAddedToCommandline> - Void return mock implementation try attemptPodInstallIfOptionAddedToCommandlineClosure?() } } // MARK: - OBJECTIVE-C // MARK: - Sourcery Errors public enum SourceryMockError: Swift.Error, Hashable { case implementErrorCaseFor(String) case subclassMockBeforeUsing(String) public var debugDescription: String { switch self { case let .implementErrorCaseFor(message): return """ 🧙‍♂️ SourceryMockError.implementErrorCaseFor: message: \(message) """ case let .subclassMockBeforeUsing(message): return """ \n 🧙‍♂️ SourceryMockError.subclassMockBeforeUsing: message: \(message) """ } } }
//: Playground - noun: a place where people can play import UIKit // 如果重写 setValue(value: AnyObject?, forUndefinedKey key: , 那么字典中没有的字段可以在类中没有对应的属性 //class Person : NSObject { //var age : Int = 0 //// override 重写, 如果写的某一个方法是对父类的方法进行的重写, 那么必须在该方法前加上override ////override func setValue(value: AnyObject?, forUndefinedKey key: String) { ////} //} //let p = Person() ////p.age = 15 //p.setValuesForKeysWithDictionary(["age" : 16]) //print("\(p.age)") /** * 类的存储属性 -- 存储常量和变量 */ class Student: NSObject { // 定义存储属性 var age : Int = 0 var name :String? var mathScore : Double = 0.0 var yuwenScore : Double = 0.0 // 最好定义为一个计算属性-- 通过别的方式计算结果的属性 var aveScore : Double { return (mathScore + yuwenScore) * 0.5 } // 方法 //func getAveScore() -> Double { //// 如果是使用当前对象的某一个属性或者是调用当前对象的某一个方法, 不需要加 self //return (mathScore + yuwenScore) * 0.5 //} // 定义类属性 -- 和整个类相关的属性, 而且是通过类名进行访问的 static var courseCount : Int = 0 } // 给累属性进行赋值 Student.courseCount = 2 // 常见对象 let stu = Student() // 给对象赋值 stu.age = 12 stu.name = "wangwang" stu.mathScore = 60 stu.yuwenScore = 90.4 print(stu.age) if let name = stu.name { print(name) } //let aveScore = stu.getAveScore() let aveScore = stu.aveScore
// // AppDelegate.swift // Sonar // // Created by Lucas Michael Dilts on 11/22/15. // Copyright © 2015 Lucas Dilts. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, GGLInstanceIDDelegate, GCMReceiverDelegate { var window: UIWindow? var deviceTokenStr = "" var connectedToGCM = false var subscribedToTopic = false var gcmSenderID: String? var registrationToken: String? var registrationOptions = [String: AnyObject]() let registrationKey = "onRegistrationCompleted" let messageKey = "onMessageReceived" // let subscriptionTopic = "/topics/global" func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. // [START_EXCLUDE] // Configure the Google context: parses the GoogleService-Info.plist, and initializes // the services that have entries in the file var configureError:NSError? GGLContext.sharedInstance().configureWithError(&configureError) assert(configureError == nil, "Error configuring Google services: \(configureError)") gcmSenderID = GGLContext.sharedInstance().configuration.gcmSenderID // [END_EXCLUDE] // if !NSUserDefaults.standardUserDefaults().boolForKey("NotificationsAccepted") { // Register for remote notifications let settings: UIUserNotificationSettings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil) application.registerUserNotificationSettings(settings) application.registerForRemoteNotifications() // [END register_for_remote_notifications] // } // [START start_gcm_service] let gcmConfig = GCMConfig.defaultConfig() gcmConfig.receiverDelegate = self GCMService.sharedInstance().startWithConfig(gcmConfig) // [END start_gcm_service] // let baseURL: NSURL = NSURL(string: "http://localhost:8000/")! // // startRestkitWithBaseURL(baseURL) return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. GCMService.sharedInstance().disconnect() // [START_EXCLUDE] self.connectedToGCM = false // [END_EXCLUDE] } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. // Connect to the GCM server to receive non-APNS notifications GCMService.sharedInstance().connectWithHandler({ (NSError error) -> Void in if error != nil { print("Could not connect to GCM: \(error.localizedDescription)") } else { self.connectedToGCM = true print("Connected to GCM") // [START_EXCLUDE] self.subscribeToTopic() // [END_EXCLUDE] } }) } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) { // self.deviceTokenStr = convertDeviceTokenToString(deviceToken) // [START get_gcm_reg_token] let instanceIDConfig = GGLInstanceIDConfig.defaultConfig() instanceIDConfig.delegate = self // Start the GGLInstanceID shared instance with that config and request a registration // token to enable reception of notifications GGLInstanceID.sharedInstance().startWithConfig(instanceIDConfig) registrationOptions = [kGGLInstanceIDRegisterAPNSOption:deviceToken, kGGLInstanceIDAPNSServerTypeSandboxOption:true] GGLInstanceID.sharedInstance().tokenWithAuthorizedEntity(gcmSenderID, scope: kGGLInstanceIDScopeGCM, options: registrationOptions, handler: registrationHandler) // [END get_gcm_reg_token] } func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) { print("\nDevice token for push notifications: FAIL -- ") print(error.description + "\n") } func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) { print("\nNotification received: \(userInfo)\n") // This works only if the app started the GCM service GCMService.sharedInstance().appDidReceiveMessage(userInfo); // Handle the received message // [START_EXCLUDE] NSNotificationCenter.defaultCenter().postNotificationName(messageKey, object: nil, userInfo: userInfo) // [END_EXCLUDE] } func application( application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler handler: (UIBackgroundFetchResult) -> Void) { print("\nNotification received: \(userInfo)\n") let state:UIApplicationState = application.applicationState if (state == UIApplicationState.Active) { NSNotificationCenter.defaultCenter().postNotificationName("ReloadDataNotification", object: nil) } // This works only if the app started the GCM service GCMService.sharedInstance().appDidReceiveMessage(userInfo); // Handle the received message // Invoke the completion handler passing the appropriate UIBackgroundFetchResult value // [START_EXCLUDE] NSNotificationCenter.defaultCenter().postNotificationName(messageKey, object: nil, userInfo: userInfo) handler(UIBackgroundFetchResult.NoData); // [END_EXCLUDE] } // private func convertDeviceTokenToString(deviceToken:NSData) -> String { // // Convert binary Device Token to a String (and remove the <,> and white space charaters). // var deviceTokenStr = deviceToken.description.stringByReplacingOccurrencesOfString(">", withString: "") // deviceTokenStr = deviceTokenStr.stringByReplacingOccurrencesOfString("<", withString: "") // deviceTokenStr = deviceTokenStr.stringByReplacingOccurrencesOfString(" ", withString: "") // // // Our API returns token in all uppercase, regardless how it was originally sent. // // To make the two consistent, I am uppercasing the token string here. // deviceTokenStr = deviceTokenStr.uppercaseString // return deviceTokenStr // } // [START on_token_refresh] func onTokenRefresh() { // A rotation of the registration tokens is happening, so the app needs to request a new token. print("The GCM registration token needs to be changed.") GGLInstanceID.sharedInstance().tokenWithAuthorizedEntity(gcmSenderID, scope: kGGLInstanceIDScopeGCM, options: registrationOptions, handler: registrationHandler) } // [END on_token_refresh] func registrationHandler(registrationToken: String!, error: NSError!) { if (registrationToken != nil) { self.registrationToken = registrationToken print("Registration Token: \(registrationToken)") self.subscribeToTopic() let userInfo = ["registrationToken": registrationToken] NSNotificationCenter.defaultCenter().postNotificationName( self.registrationKey, object: nil, userInfo: userInfo) } else { print("Registration to GCM failed with error: \(error.localizedDescription)") let userInfo = ["error": error.localizedDescription] NSNotificationCenter.defaultCenter().postNotificationName( self.registrationKey, object: nil, userInfo: userInfo) } } func subscribeToTopic() { // If the app has a registration token and is connected to GCM, proceed to subscribe to the // topic if(registrationToken != nil && connectedToGCM) { let httpClient: AFHTTPClient = AFHTTPClient(baseURL: NSURL(string: "http://dilts.koding.io:8000")) httpClient.parameterEncoding = AFJSONParameterEncoding httpClient.registerHTTPOperationClass(AFJSONRequestOperation) print("\n\(self.deviceTokenStr)\n") let parameter = ["dev_id": "271120152319", "dev_type": "IOS", "reg_id": "\(self.registrationToken!)"] httpClient.postPath("devices/", parameters: parameter, success: { (operation: AFHTTPRequestOperation!, responseObject: AnyObject!) -> Void in self.subscribedToTopic = true; print("\nSuccess!!\n") }, failure: { (operation: AFHTTPRequestOperation!, error: NSError!) -> Void in print("\n\(error.description)\n") }) // GCMPubSub.sharedInstance().subscribeWithToken(self.registrationToken, topic: subscriptionTopic, // options: nil, handler: {(NSError error) -> Void in // if (error != nil) { // // Treat the "already subscribed" error more gently // if error.code == 3001 { // print("Already subscribed to \(self.subscriptionTopic)") // } else { // print("Subscription failed: \(error.localizedDescription)"); // } // } else { // self.subscribedToTopic = true; // // } // }) } } }
// // SeachProductsViewModel.swift // StoreApp // // Created by Scizor on 15/11/20. // import Foundation import RxSwift import RxCocoa final class SearchProductViewModel { // MARK: - Private properties private let service: SearchProductService private let disposeBag = DisposeBag() private weak var coordinator: SearchProductRedirects? // MARK: - Public properties let isLoading = PublishRelay<Bool>() // MARK: - Initialization init(service: SearchProductService = SearchProductServiceImpl(), coordinator: SearchProductRedirects) { self.service = service self.coordinator = coordinator } // MARK: - Public methods func search(product: String) { isLoading.accept(true) service.search(typedValue: product).observeOn(MainScheduler.instance).subscribe (onNext: { [weak self] productList in self?.isLoading.accept(false) self?.goToProductList(productList: productList) }, onError: { [weak self] _ in self?.isLoading.accept(false) self?.showError(title: "Sorry =(", description: "We could not find any results with text typed") }).disposed(by: disposeBag) } // MARK: - Private methods private func goToProductList(productList: ListProductModel) { coordinator?.goToListProducts(productList: productList) } private func showError(title: String, description: String) { coordinator?.showError(title: title, description: description) } }
// // Watchlist.swift // Movies // // Created by Mathias Quintero on 10/20/15. // Copyright © 2015 LS1 TUM. All rights reserved. // import UIKit import Alamofire class Watchlist: MovieDataFetcher { var movies = [Movie]() func getMovies(ids: [Int]) { movies = [] for iterator in 0...(ids.count - 1) { Alamofire.request(.GET, getMovieURL(ids[iterator])).responseJSON() { (response) in if let movieAsDictionary = response.result.value as? [String:AnyObject] { if let id = movieAsDictionary["id"] as? Int, title = movieAsDictionary["title"] as? String, plot = movieAsDictionary["overview"] as? String, year = movieAsDictionary["release_date"] as? String, rating = movieAsDictionary["vote_average"] as? Double, poster = movieAsDictionary["poster_path"] as? String { if let alreadyKnownMovie = self.knownMovies[id.description] { self.movies.append(alreadyKnownMovie) } else { let yearOnly = year.componentsSeparatedByString("-") let newMovie = Movie(title: title, year: Int(yearOnly[0])!, rating: rating, description: plot, id: id.description, posterURL: "https://image.tmdb.org/t/p/w500" + poster, handler: self.receiver, dataSource: self) self.knownMovies[id.description] = newMovie self.movies.append(newMovie) } } } if iterator == ids.count - 1 { self.receiver?.moviesArrived(self.movies) } } } } func getListOfMovies(delegate: MovieReceiverProtocol) { receiver = delegate // Do Parsing of PList or XML file here getMovies([286217,99861,206647,140607]) } func getMovieURL(id: Int) -> String{ return "http://api.themoviedb.org/3/movie/" + id.description + "?api_key=18ec732ece653360e23d5835670c47a0" } }
// // EmoticonViewCell.swift // XWSwiftEmojiDemo // // Created by 邱学伟 on 2016/11/16. // Copyright © 2016年 邱学伟. All rights reserved. // import UIKit class EmoticonViewCell: UICollectionViewCell { fileprivate let emojiBtn : UIButton = UIButton() var emoji : Emoticon? = nil { didSet{ guard let emoji = emoji else { return } emojiBtn.setImage(UIImage(contentsOfFile: (emoji.pngPath) ?? ""), for: .normal) emojiBtn.setTitle(emoji.emojiCode, for: .normal) if emoji.isRemove == true { emojiBtn.setImage(UIImage(named: "compose_emotion_delete"), for: .normal) } } } override init(frame: CGRect) { super.init(frame: frame) setUpUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension EmoticonViewCell { fileprivate func setUpUI() { addSubview(emojiBtn) emojiBtn.frame = contentView.bounds emojiBtn.isUserInteractionEnabled = false emojiBtn.titleLabel?.font = UIFont.systemFont(ofSize: 32) } }
// // selectQustionswift // kaoshi // // Created by 李晓东 on 2017/11/3. // Copyright © 2017年 晓东. All rights reserved. // import UIKit @objc protocol QuestionCellDelegate { @objc optional func questionCellConfirmClick(_ sender: Any) @objc optional func questionCellAClick(_ sender: Any) @objc optional func questionCellBClick(_ sender: Any) @objc optional func questionCellCClick(_ sender: Any) @objc optional func questionCellDClick(_ sender: Any) } class selectQustionCell: UITableViewCell { @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var containerView: UIView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var questionLabel: UILabel! @IBOutlet weak var confirmBtn: UIButton! @IBOutlet weak var itemA: UILabel! @IBOutlet weak var itemB: UILabel! @IBOutlet weak var itemC: UILabel! @IBOutlet weak var itemD: UILabel! @IBOutlet weak var btnA: UIButton! @IBOutlet weak var btnB: UIButton! @IBOutlet weak var btnC: UIButton! @IBOutlet weak var btnD: UIButton! @IBOutlet weak var containerWidth: NSLayoutConstraint! @IBOutlet weak var containerHeight: NSLayoutConstraint! @IBOutlet weak var confirmTopConstraint: NSLayoutConstraint! var questionModel: QuestionModel? var isHeightCalculated: Bool = false override func awakeFromNib() { super.awakeFromNib() } override func layoutSubviews() { super.layoutSubviews() let bottom = confirmBtn.bottom+40 > self.height ? confirmBtn.bottom+40 : self.height containerWidth.constant = self.width containerHeight.constant = self.bottom scrollView.contentSize = CGSize.init(width: self.width, height: bottom) //print("layoutsubv-----\((questionModel?.qId)!)==========") //print("2-----subvi--\((questionModel?.qId)!)","bottom--\(confirmBtn.bottom)","size--",scrollView.contentSize) } // override func prepareForReuse() { // super.prepareForReuse() // // scrollView.contentSize = CGSize.init(width: self.width, height: self.height) // let bottom = confirmBtn.bottom+40 > self.height ? confirmBtn.bottom+40 : self.height // containerHeight.constant = self.bottom // print("reuse-----\((questionModel?.qId)!)",scrollView.contentSize) // } // // override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes { // print("layoutfitter-----\((questionModel?.qId)!)",scrollView.contentSize) // return super.preferredLayoutAttributesFitting(layoutAttributes) // } func layout(_ model: QuestionModel) { questionModel = model titleLabel.text = "\(model.qId). 选择题(\(model.qPoint)分)" questionLabel.text = model.qTitle itemD.isHidden = false btnD.isHidden = false let selects = model.qSelects confirmTopConstraint.constant = 20 if selects.count == 4 { itemA.text = selects[0] as? String itemB.text = selects[1] as? String itemC.text = selects[2] as? String itemD.text = selects[3] as? String } else if selects.count == 3 { itemA.text = selects[0] as? String itemB.text = selects[1] as? String itemC.text = selects[2] as? String itemD.isHidden = true btnD.isHidden = true confirmTopConstraint.constant = 0 } // let size = self.containerView.systemLayoutSizeFitting(CGSize.init(width: self.width, height: 0)) // let size1 = questionLabel.systemLayoutSizeFitting(CGSize.init(width: self.width, height: 0)) //print("1-----","layout--\(Int(model.qId)!-1)","bottom--\(confirmBtn.bottom)","size--\(size)",size1) } @IBAction func clickConfirm(_ sender: Any) { } @IBAction func clickA(_ sender: Any) { } @IBAction func clickB(_ sender: Any) { } @IBAction func clickC(_ sender: Any) { } @IBAction func clickD(_ sender: Any) { } private func clickSender(_ sender: Any) { let btn = sender as! UIButton btn.isSelected = true } }
//: Playground - noun: a place where people can play import UIKit //Типы коллекций //Массивы var myArray1 = [2, 3, 44, 45] var myArray2 = ["apple", "orange", "peach", "banana"] var myArray3 = [2, 3, "banana", "peach"] //Материал урока основан на Swift 2.0, но вероятно я упустил кое что в Swift 2.1 - теперь как я понял в массив можно ложить элементы разных типов, что прибавляет языку пару очков крутости =) простите за нестыковки) /* var arrayOfInts = [1,2,3,4,5,6] arrayOfInts.count //мы получили количество элементов массива var arrayOfStrings = ["apple", "orange", "banana"] arrayOfStrings.isEmpty //булевая проверка массива на пустоту */ /* var myArray = [Int]()//верное создание пустого массива var myArray2 = [Int](count: 5, repeatedValue: 1) */ /* var myArray = [2.3, 2.4, 2.5] myArray[2] myArray[1] myArray[0] */ /* var toDoList = ["Построить дом"] toDoList.append("Посадить дерево") toDoList += ["Родить сына"] var townsToVisit = ["Вена", "Нью-Йорк"] townsToVisit += ["Киев", "Москва", "Харьков"] townsToVisit.insert("Мухосранск", atIndex: 2) */ /* var fruits = ["Яблоко", "Груша", "Банан", "Апельсин", "Арбуз"] fruits[1] = "Ананас" fruits[0..<2] = ["Мандарин", "Манго"] fruits */ /* var fruits = ["Яблоко", "Груша", "Банан", "Апельсин", "Арбуз"] fruits.removeAtIndex(2) fruits.removeLast() fruits */ /* var fruits = ["Яблоко", "Груша", "Банан", "Апельсин", "Арбуз"] //for fruit in fruits { // print(fruit) //} for (index, fruitNew) in fruits .enumerate() { print("Фрукт номер \(index + 1) - \(fruitNew)") } */ //Множества /* var mySet = Set<Int>() mySet = [4,7,5,9,8, 2,2,2,3,3,3,4,5,5,5,6,6,6] var mySetTwo: Set = [2,4,6,7,8] */ /* var mySet: Set = [4,8,15,16,23,42] mySet.count mySet.isEmpty mySet.insert(56) mySet.remove(56) mySet mySet.sort() for digit in mySet{ print(digit) } if mySet.contains(16) { print("16 содержится") } else { print("16 не содержится") } */ /* var a: Set = [1,2,3] var b: Set = [4,5,6] var c = a.union(b) */ /* var a: Set = [1,2,3,4,5,6] var b: Set = [4,5,6] var c = a.subtract(b) */ /* var a: Set = [1,2,3,4,5,6] var b: Set = [1,2,3] var c = a.intersect(b) */ /* var a: Set = [1,2,3,4,5,6] var b: Set = [4,5,6,7,8,9] var c = a.exclusiveOr(b) */ /* var a: Set = [1,2,3,4,5,6] var b: Set = [4,5,6,1,2,3] a == b */ /* var a: Set = [1,2,3,4,5,6] var b: Set = [4,5,6] b.isSubsetOf(a) a.isSupersetOf(b) */ /* var a: Set = [4,5,6] var b: Set = [4,5,6] b.isStrictSubsetOf(a) b.isSubsetOf(a) a.isStrictSubsetOf(b) a.isStrictSupersetOf(b) */ /* var a: Set = [1,2,3] var b: Set = [4,5,6] a.isDisjointWith(b) */ //Словари /* var daysOfWeek = ["Пн":"Понедельник", "Вт":"Вторрник", "Ср":"Среда", "Чт":"Четверг", "Пт":"Пятница", "Сб":"Суббота", "Вс":"Воскресенье"] //var daysOfWeekTwo: [String : String] daysOfWeek["Вт"] daysOfWeek["Нд"] = "Новый день" daysOfWeek.updateValue("Второй новый день", forKey: "Нд") daysOfWeek daysOfWeek["Нд"] = "нет такого дня" daysOfWeek //daysOfWeek["Нд"] = nil //daysOfWeek daysOfWeek.removeValueForKey("Нд") daysOfWeek for (letter, day) in daysOfWeek { print("\(letter) - \(day)") } */
// // ConvertCurrencies.swift // crypto-graph // // Created by Александр Пономарев on 29.03.18. // Copyright © 2018 Base team. All rights reserved. // import Foundation struct Convert: Hashable { let symbol: String var hashValue: Int { return symbol.hashValue } static func ==(lhs: Convert, rhs: Convert) -> Bool { return lhs.symbol == rhs.symbol } static var feauturedConverts: [Convert] = [] }
import SwiftUI struct DefaultLogoSymbol: View { var body: some View { GeometryReader { geometry in paths( width: min( geometry.size.width, geometry.size.height ), lineWidth: 0.12, topLeftColor: 0x92CFAEFF, bottomRightColor: 0x2A8288FF ) } } } struct paths: View { var width, lineWidth: CGFloat var topLeftColor: UInt64, bottomRightColor: UInt64 private func triangle(width: CGFloat, flip: CGFloat) -> (inout Path) -> () {{ path in func point(x: CGFloat, y: CGFloat) -> CGPoint { CGPoint(x: width * abs(x - flip), y: width * abs(y - flip)) } let hlw = self.lineWidth / 2 path.addLines([ point(x: hlw, y: 1), point(x: 1, y: hlw), point(x: 1, y: 1) ]) }} var body: some View { ZStack { Path.init( self.triangle(width: self.width , flip: 1.0 ) ).fill( Color(UIColor(hex: self.topLeftColor)) ) Path.init( self.triangle(width: self.width, flip: 0.0) ).fill( Color(UIColor(hex: self.bottomRightColor)) ) } } } struct RbcLogoSymbol_Previews: PreviewProvider { static var previews: some View { DefaultLogoSymbol().previewLayout(.fixed(width: 200, height: 200)) } }
// // Renderer.swift // Bumblebees // // Created by Oliver Schaff on 28.07.18. // Copyright © 2018 Oliver Schaff. All rights reserved. // /// A Type that represents states of a view Controller. Typically this should be an Enum protocol ViewControllerState {} /// A Class that can render states with its render(state) function. It uses the help of a LogicController to compute the states protocol Renderer: class { associatedtype LC: LogicController associatedtype State: ViewControllerState var logicController: LC {get} var renderHandler: (State)->() {get} func render(_ state: State) } extension Renderer { var renderHandler: (State)->() { get { return {[weak self] (state) in self?.render(state)} } } }
// // Images.swift // Star Wars Challenge // // Created by Jack Higgins on 2/8/21. // import UIKit extension UIImage { static var vehiclesIcon = UIImage(named: "vehiclesIcon") static var starshipsIcon = UIImage(named: "starshipsIcon") static var speciesIcon = UIImage(named: "speciesIcon") static var rootheaderImage = UIImage(named: "rootheaderImage") static var planetIcon = UIImage(named: "planetIcon") static var peopleIcon = UIImage(named: "peopleIcon") static var footerImage = UIImage(named: "footerImage") static var filmsIcon = UIImage(named: "filmsIcon") static var detailedDisclosure = UIImage(named: "detailedDisclosure") static var bannerImage = UIImage(named: "bannerImage") }
// // PaymentProviderRepositoryMock.swift // PayoneerTestAppTests // // Created by Bozidar Kokot on 05.05.21. // import Foundation @testable import PayoneerTestApp class PaymentProviderRepositoryMock: PaymentProviderRepository { var isFailure = false func getPaymentProviders(completion: @escaping (Error?, ListResult?) -> Void) { if isFailure { completion(APIError.unrecognizedFormat, nil) } else { completion(nil, ListResult.fixture()) } } }
// // Camera.swift // aoc2019 // // Created by Shawn Veader on 12/26/19. // Copyright © 2019 Shawn Veader. All rights reserved. // import Foundation struct Camera { let pixels: [Coordinate: String] init(input: [Int]) { var tmpPixels = [Coordinate: String]() var y = 0 // print out comes in top first, reorient to be "corret" let lines = input.split(separator: 10).map(Array.init) //.reversed() for line in lines { for (x, ascii) in line.enumerated() { if let scalar = UnicodeScalar(ascii) { tmpPixels[Coordinate(x: x, y: y)] = String(Character(scalar)) } } y += 1 } pixels = tmpPixels } func intersections() -> [Coordinate] { let directions: [MoveDirection] = [.north, .east, .south, .west] // coordinates for all scaffold pieces let scaffold = pixels.filter { $0.value == "#" }.keys return scaffold.compactMap { coordinate -> Coordinate? in let neighbors = directions.compactMap { direction -> Coordinate? in let location = coordinate.location(for: direction) guard scaffold.contains(location) else { return nil } return location } // intersections have 4 neighbors guard neighbors.count == 4 else { return nil } return coordinate } } func printScreen() { let usedCoordinates = pixels.keys let minX = usedCoordinates.min(by: { $0.x < $1.x })?.x ?? 0 let maxX = usedCoordinates.max(by: { $0.x < $1.x })?.x ?? 0 let minY = usedCoordinates.min(by: { $0.y < $1.y })?.y ?? 0 let maxY = usedCoordinates.max(by: { $0.y < $1.y })?.y ?? 0 let xRange = min(0, minX - 2)..<(maxX + 2) let yRange = min(0, minY - 2)..<(maxY + 2) let ints = intersections() var output = "" for y in yRange { //.reversed() { for x in xRange { let location = Coordinate(x: x, y: y) if ints.contains(location) { output += "O" } else { output += pixels[location] ?? " " } } output += "\n" } print(output) } }
// // ViewController.swift // introduce // // Created by yuta on 2019/12/02. // Copyright © 2019 yuta. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var orderLabel: UILabel! @IBOutlet weak var questionLabel: UILabel! @IBOutlet weak var answer1: UIButton! @IBOutlet weak var answer2: UIButton! @IBOutlet weak var answer3: UIButton! @IBOutlet weak var answer4: UIButton! @IBOutlet weak var imageQuestion: UIImageView! @IBOutlet weak var imageQuestionLabel: UILabel! var questionsList = QuestionsList() var questionNumber:Int = 0 var sound = Sound() var correctCount:Int = 0 override func viewDidLoad() { super.viewDidLoad() answer1.layer.cornerRadius = 20 answer2.layer.cornerRadius = 20 answer3.layer.cornerRadius = 20 answer4.layer.cornerRadius = 20 imageQuestionLabel.text = "" } override func viewWillAppear(_ animated: Bool) { questionNumber = 0 orderLabel.text = "第" + String(questionNumber + 1) + "問" questionLabel.text = questionsList.list[questionNumber].question answer1.setTitle(questionsList.list[questionNumber].answer[0], for: .normal) answer2.setTitle(questionsList.list[questionNumber].answer[1], for: .normal) answer3.setTitle(questionsList.list[questionNumber].answer[2], for: .normal) answer4.setTitle(questionsList.list[questionNumber].answer[3], for: .normal) } @IBAction func answerButton(_ sender: Any) { // 正解を押した場合 if (sender as AnyObject).tag == questionsList.list[questionNumber].correct { correctCount += 1 sound.playSound(fileName: "pinpon", extensionName: "mp3") //不正解を押した場合 } else { sound.playSound(fileName: "bubu", extensionName: "mp3") } questionNumber += 1 nextQuestion() } //次の問題表示 func nextQuestion() { if questionNumber <= questionsList.list.count - 1 { orderLabel.text = "第" + String(questionNumber + 1) + "問" //画像の問題 if questionsList.list[questionNumber].question == "このぬいぐるみの名前は?" { questionLabel.text = "" imageQuestion.image = UIImage(named: "rasuo") imageQuestionLabel.text = questionsList.list[questionNumber].question answer1.setTitle(questionsList.list[questionNumber].answer[0], for: .normal) answer2.setTitle(questionsList.list[questionNumber].answer[1], for: .normal) answer3.setTitle(questionsList.list[questionNumber].answer[2], for: .normal) answer4.setTitle(questionsList.list[questionNumber].answer[3], for: .normal) //文字の問題 } else { imageQuestion.image = UIImage(named: "") imageQuestionLabel.text = "" questionLabel.text = questionsList.list[questionNumber].question answer1.setTitle(questionsList.list[questionNumber].answer[0], for: .normal) answer2.setTitle(questionsList.list[questionNumber].answer[1], for: .normal) answer3.setTitle(questionsList.list[questionNumber].answer[2], for: .normal) answer4.setTitle(questionsList.list[questionNumber].answer[3], for: .normal) } //全問終了 } else { performSegue(withIdentifier: "next", sender: nil) } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "next" { let nextVC = segue.destination as! NextViewController nextVC.correctCount = correctCount nextVC.questionCount = questionNumber } } }
// // Tela2ViewController.swift // CicloVidaDemo // // Created by Douglas Del Frari on 23/07/21. // import UIKit class Tela2ViewController: UIViewController { // propriedades que mapeam os elementos visuais que desejamos alterar o valor @IBOutlet weak var labelTitulo: UILabel! override func viewDidLoad() { super.viewDidLoad() print("-->> Tela2ViewController::viewDidLoad() <<-- ") } // ENTRANDO NA TELA (ciclo de vida da VIEW) override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) print("-->> Tela2ViewController::viewWillAppear() <<--") } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) print("-->> Tela2ViewController::viewDidAppear() <<--") } // SAINDO DA TELA (ciclo de vida da VIEW) override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) print("-->> Tela2ViewController::viewWillDisappear() <<--") } override func viewDidDisappear(_ animated: Bool) { super.viewWillDisappear(animated) print("-->> Tela2ViewController::viewDidDisappear() <<--") } @IBAction func mudarTitulo(_ sender: Any) { // pegar a referencia do meu outlet e mudar o seu valor labelTitulo.text = "TITULO NOVO TESTE" } /* // 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.destination. // Pass the selected object to the new view controller. } */ }
//func walkDog(numberOfDogs : Int) { //Declaring a Function // print("Get the leash.") //Code Block // print("Put leash on Dogs.") // print("Go on the walk.") // print("Pick up poop.") // print("Make sure you have all \(numberOfDogs) dogs.") // print("Go home.") //} // //walkDog(numberOfDogs: 7) //This a call function / calling your function // //func teachKids(numberOfKids : Int, myNameIs : String, theTime : String, theTime2 : String) { // print("At \(theTime) gather lesson and schoolbooks.") // print("At \(theTime2) let all \(numberOfKids) students in classroom.") // print("'Hello, my name is \(myNameIs).'") // print("\(myNameIs) teaches the kids.") // print("Give out all \(numberOfKids) kids have their homework.") // print("\(myNameIs) then dismisses kids to their guardians on her way home to her fiancé and her lovely dog.") //} //teachKids(numberOfKids: 35, myNameIs: "Brandi", theTime: "8am", theTime2: "9am" ) // //func bankAccount(currentBalance:Double,deposit: Double)-> // Double{ // let newBalance = currentBalance + deposit // return newBalance //} //let customerAmountInBank = bankAccount(currentBalance: 13.5, deposit: 54.0) //func interstAmount(percentIntrest:Double)->Double{ // let amountInBank = customerAmountInBank // let customerINtrestAccured = amountInBank * percentIntrest // return customerINtrestAccured //} //print(interstAmount(percentIntrest: 10)) //Lesson 5 Collections - arrays ////Example of Empty Array //var arrayOfStrings = [String] () //var arrayOfIntergers = [Int] () // ////examples of an array //var friendsOfKarlie = ["Michelle Obama","Serena Williams","T Swift","Jimmy Fallon"] // ////Example of accessing information //friendsOfKarlie[2] //friendsOfKarlie[3] // ////Example of Updating information //friendsOfKarlie[2] = "Josh Kusher" //friendsOfKarlie // ////example of adding information //friendsOfKarlie.append("Josh Kushner") // ////examples of removing information //friendsOfKarlie.remove(at:2) //friendsOfKarlie //Class practice //var roleModels = ["Rihanna","Malcom Gladwell","Lizzo"] //roleModels[1] //roleModels.append("Realistic Barbie") //roleModels[3] = "Mark Twain" //roleModels //roleModels.remove(at: 3) //roleModels // // ////Self Practice // //var favHobbies = ["danceing","cooking","sleeping","rollerskating","hanging out with friends"] //favHobbies[2] = "silks and lyra" //favHobbies.append("sleeping") //favHobbies //favHobbies.remove(at:5) //print(favHobbies[2]) //Dictionary //Example of Dictionary // var friendsOfKarlie = [ // "Poltician":"Michelle Obama", // "Athlete":"Serena Williams", // "Musician":"Taylor Swift", // "Comedian":"Jimmy Fallon" // ] // print(friendsOfKarlie) //var perfectTen : [String : String] = [:] //perfectTen["almond flour"] = "3 and a 1/2 cups" //perfectTen["gluten-free oats"] = "2 cups" //perfectTen["mini chocolate chips"] = "1 cup" // //print(perfectTen) // ////How to revome things from dictionary // // //perfectTen["gluten-free oats"] = nil // //print(perfectTen["gluten-free oats"]!) // //var birth : [String : String] = [:] //birth["Daniya"] = "Nov.12" //birth["Ella"] = "Nov.1" //birth["Gia"] = "Aug. 19" //birth["Mia"] = "Jul.28" //print(birth) var family : [String : String] = [:] family["Dylan"] = "brother" family["Gia"] = "sister" family["Jeannie"] = "mom" family["Bill"] = "dad" family["Uzi"] = "puppy" print(family["Dylan"]!) print(family["Uzi"]!) print(family["Jeannie"]!)
// // BudgetListInteractor.swift // Apps Challenge // // Created by Francisco Javier Sarasua Galan on 02/05/2021. // import Foundation protocol BudgetListInteractorInputProtocol: class { func getDataTable() func removeDataTable() } class BudgetListInteractor { weak var presenter: BudgetListInteractorOutputProtocol? let managerCoreData = CoreDataManager.sharedInstance let managerBudget = BudgetManager.sharedInstance } extension BudgetListInteractor: BudgetListInteractorInputProtocol { func getDataTable() { let viewModel = BudgetListViewModel() let allBudgets = self.managerBudget.getAllBudgets() for budgetEntity in allBudgets { viewModel.cellModels.append(BudgetCellModel(budget: budgetEntity)) } self.presenter?.setData(viewModel: viewModel) } func removeDataTable() { self.managerCoreData.deleteAll() self.presenter?.setData(viewModel: BudgetListViewModel()) } }
// // Address.swift // Electro // // Created by John Davis on 5/19/16. // Copyright © 2016 John Davis. All rights reserved. // import Foundation import CoreData @objc(Address) class Address: NSManagedObject { // Insert code here to add functionality to your managed object subclass /** Populates the object with information from a dictionary containing Address details. - parameter newAddress: A dictionary containing address details. */ func populateFromJSONDict( newAddress:[String:AnyObject] ) { //street //suite //city //zipcode //geo if let newStreet = newAddress["street"] as? String { self.street = newStreet } if let newSuite = newAddress["suite"] as? String { self.suite = newSuite } if let newCity = newAddress["city"] as? String { self.city = newCity } if let newZip = newAddress["zipcode"] as? String { self.zipcode = newZip } if let newGeoDict = newAddress["geo"] as? [String:AnyObject] { if let myGeo = self.geo { myGeo.populateFromJSONDict(newGeoDict) } else { if let newGeo = NSEntityDescription.insertNewObjectForEntityForName("Geo", inManagedObjectContext: self.managedObjectContext!) as? Geo { newGeo.populateFromJSONDict(newGeoDict) self.geo = newGeo } } } } }
../../../StellarKit/source/types/Transaction.swift
// // GameViewController.swift // MineSweeper // // Created by Or Milis on 24/03/2019. // Copyright © 2019 Or Milis. All rights reserved. // import UIKit import MapKit import CoreLocation import SpriteKit class GameViewController: UIViewController, CLLocationManagerDelegate { @IBOutlet weak var gameCollectionView: UICollectionView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var timerLabel: UILabel! @IBOutlet weak var flagLabel: UILabel! @IBOutlet weak var sceneView: SKView! var scene: AnimationScene?; let locationManager = CLLocationManager(); private let sectionInsets = UIEdgeInsets(top: 4.0, left: 4.0, bottom: 0.0, right: 4.0); var nickname: String = ""; var timer: Timer = Timer(); var timerCounter: Int = 0; var flagCounter: Int = 0; var difficulty: UtilManager.Difficulty = UtilManager.Difficulty.NORMAL; var boardSize = 5; var bombCount = 10; var gameBoard: GameBoard = GameBoard(); var userEntry: LeaderboardCellData = LeaderboardCellData(name: "", score: 0, lat: 0, lng: 0, difficulty: ""); public func setUpGameView(nickname: String, difficulty: UtilManager.Difficulty) { self.nickname = nickname; self.difficulty = difficulty; let boardSettings = difficulty.GetBoardSettings(); self.boardSize = boardSettings.boardSize; self.bombCount = boardSettings.bombCount; userEntry.SetName(name: nickname); userEntry.SetDifficulty(difficulty: difficulty.rawValue); startGame(); } public func startGame() { self.gameBoard = GameBoard(boardSize: self.boardSize, bombCount: self.bombCount); self.flagCounter = bombCount; if(timerCounter > 0) { self.timerCounter = 0; self.timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true, block: { timer in self.timerCounter += 1; let timerText = self.timerCounter > 999 ? 999 : self.timerCounter; self.timerLabel.text = String(format: "%03d", timerText); }); self.timer.fire(); self.sceneView.isHidden = true; } } override func viewDidLoad() { super.viewDidLoad() self.timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true, block: { timer in self.timerCounter += 1; let timerText = self.timerCounter > 999 ? 999 : self.timerCounter; self.timerLabel.text = String(format: "%03d", timerText); }); self.timer.fire(); if(CLLocationManager.locationServicesEnabled()) { locationManager.delegate = self; locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters locationManager.startUpdatingLocation(); } self.scene = AnimationScene(size: CGSize(width: self.sceneView.frame.size.width, height: self.sceneView.frame.size.height)); self.sceneView.presentScene(scene); // Do any additional setup after loading the view. } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated); self.nameLabel.text = nickname; self.flagLabel.text = String(format: "%02d", self.flagCounter); self.gameCollectionView.reloadData(); } @IBAction func handleLongPress(_ sender: UILongPressGestureRecognizer) { if(sender.state == UIGestureRecognizer.State.began) { let touchPoint = sender.location(in: gameCollectionView); guard let indexPath = gameCollectionView.indexPathForItem(at: touchPoint) else { return; }; if(flagCounter > 0){ let pressData = gameBoard.markCellAsFlag(cellIndexPath: indexPath); flagCounter -= pressData.placedFlags; flagLabel.text = String(format: "%02d", flagCounter); notifyDataSetChanged(collectionView: gameCollectionView, indexPathArr: pressData.modifiedCells); } } } func endGame(gameStatus: String) { self.timer.invalidate(); self.sceneView.isHidden = false; self.sceneView.isOpaque = false; self.sceneView.allowsTransparency = true; if let scene = self.scene { scene.play(gameStatus: gameStatus); } let maxScore = 2000; let location = locationManager.location?.coordinate ?? CLLocationCoordinate2D(latitude: 0, longitude: 0); userEntry.SetLat(lat: location.latitude); userEntry.SetLng(lng: location.longitude); let scorePenalty = gameStatus == "WON" ? 0 : 2000 - difficulty.GetReverseValue() * timerCounter; let score = maxScore - timerCounter * difficulty.GetReverseValue() - scorePenalty; userEntry.SetScore(score: score); DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(3), execute: { let storyBoard: UIStoryboard = UIStoryboard(name: UtilManager.StoryBoardName, bundle: nil); guard let endViewController = storyBoard.instantiateViewController(withIdentifier: UtilManager.EndGameID) as? EndGameViewController else { return; }; endViewController.setupView(nickname: self.nickname, gameStatus: gameStatus, difficulty: self.difficulty, entry: self.userEntry); self.navigationController?.pushViewController(endViewController, animated: true); }); } func notifyDataSetChanged(collectionView: UICollectionView, indexPathArr: [IndexPath]) { collectionView.reloadItems(at: indexPathArr); } @IBAction func OnBackBtnClick(_ sender: Any) { dismiss(animated: true, completion: nil) } /*func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let location = locations[0]; self.userEntry.SetLat(lat: location.coordinate.latitude); self.userEntry.SetLng(lng: location.coordinate.longitude); }*/ /* // 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.destination. // Pass the selected object to the new view controller. } */ } extension GameViewController: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout{ func numberOfSections(in collectionView: UICollectionView) -> Int { return boardSize; } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return boardSize; } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: UtilManager.GameCellID, for: indexPath) as! GameCollectionCell; let cellData = gameBoard.getCellDataAt(indexPath: indexPath); let cellValue = cellData.GetCellValue(); let cellType = cellData.GetCellType(); var cellText = ""; var cellTextColor = UtilManager.WarningColor.ONE; let cellBackgroundColor = UtilManager.GetCellBackgroundColor(isCellOpen: cellData.IsCellOpen()); //print("CELL VALUE: ", cellValue); if(cell.cellImage.image != nil) { cell.cellImage.image = nil; } switch cellType { case CellData.CellState.FLAG: cellText = ""; cellTextColor = UtilManager.WarningColor.ONE; cell.cellImage.image = UIImage(named: "FlagIcon"); case CellData.CellState.BOMB: cellText = ""; cellTextColor = UtilManager.WarningColor.EIGHT; cell.cellImage.image = UIImage(named: "Mine"); case CellData.CellState.VALUE: if(cellValue > 0){ cellText = "\(cellValue)"; cellTextColor = UtilManager.WarningColor(rawValue: cellValue) ?? UtilManager.WarningColor.ONE; } else { cellText = ""; cellTextColor = UtilManager.WarningColor.ONE; } default: break; } cell.cellText.text = cellText; cell.cellText.textColor = cellTextColor.GetColor(); cell.backgroundColor = cellBackgroundColor; return cell; } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { //let cell = collectionView.cellForItem(at: indexPath) as! GameCollectionCell; let pressData = gameBoard.touchCell(cellIndexPath: indexPath); /*print("AfterClick: "); dump(pressData.modifiedCells);*/ notifyDataSetChanged(collectionView: collectionView, indexPathArr: pressData.modifiedCells); if(pressData.isLost) { endGame(gameStatus: "LOST"); } else if(pressData.isWon) { endGame(gameStatus: "WON"); } } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let sizeOfBoard = CGFloat(boardSize); //print("top: ", collectionView.adjustedContentInset.top); let paddingSpace = sectionInsets.left * (sizeOfBoard + 1); let availableWidth = collectionView.frame.width - paddingSpace; let cellWidth = availableWidth / sizeOfBoard; return CGSize(width: cellWidth, height: cellWidth); } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { //print("Width: ", collectionView.frame.width, " Height: ", collectionView.frame.height); return sectionInsets; } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return sectionInsets.left; } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return sectionInsets.left; } }
import XCTest @testable import StencilViewEngineTests XCTMain([ testCase(StencilViewEngineTests.allTests), ])
// // EditStopTableView.swift // UBSetRoute // // Created by Gustavo Rocha on 18/12/19. // import UIKit protocol EditStopTableViewDelegate: class { func editStopTable(view: EditStopTableView, didSelect text: String, point: Points) } class EditStopTableView: UITableView { private lazy var viewProgress: UIView = { let view = UIView() view.backgroundColor = .clear view.translatesAutoresizingMaskIntoConstraints = false self.isHidden = false self.addSubview(view) // self.superView.addSubview(view) self.addConstraints([ view.leftAnchor.constraint(equalTo: self.leftAnchor), view.bottomAnchor.constraint(equalTo: self.topAnchor, constant: 1), view.rightAnchor.constraint(equalTo: self.rightAnchor), view.heightAnchor.constraint(equalToConstant: 1.5) ]) return view }() // MARK: Properties private var placeList: [PlaceViewModel] = [] { didSet { self.reloadData() } } public var lastPlaces: [PlaceViewModel] = [] { didSet { if self.hasLastPlaces { self.reloadData() } } } private var superView: EditStopView! private var cnstTableTop = NSLayoutConstraint() lazy var allowUpdateTableInsets: Bool = { return true }() private var allowVelocityHide = true private var updateConstraintsByScroll = true var isProgressAnimating = false var didSelectPlace: ((PlaceViewModel) -> Void)? var myDelegate: EditStopTableViewDelegate? private var hasLastPlaces: Bool = true // var isProgressAnimating = false // MARK: Init required init(superView: EditStopView) { super.init(frame: .zero, style: .plain) self.translatesAutoresizingMaskIntoConstraints = false self.superView = superView } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: Setup public func setup() { #warning("Evitar ao máximo esse tipo de código, da view ter acesso a superview e ela mesmo se atribuir como subview da superview") self.superView.addSubview(self) self.translatesAutoresizingMaskIntoConstraints = false self.setupTableConstraints() self.backgroundColor = .white self.separatorStyle = .none self.estimatedRowHeight = 70 self.rowHeight = UITableView.automaticDimension #warning("Hard code aqui, o identifier 'PlacesCell' está sendo repetido várias vezes ao longo do projeto, centralizar em uma única variável") self.register(PlacesCell.self, forCellReuseIdentifier: "PlacesCell") self.delegate = self self.dataSource = self self.keyboardDismissMode = .interactive // self.placeList = self.defaultOptions } fileprivate func setupTableConstraints() { #warning("Evitar ao máximo esse tipo de código, da subview adicionar as constraints") let topPadding: CGFloat = SetRouteViewSettings.shared.routeViewHeight + navBarSize - SetRouteViewSettings.shared.statusBarSizeAdjust self.cnstTableTop = self.topAnchor.constraint(equalTo: self.superView.topAnchor, constant: topPadding) // let height = UIScreen.main.bounds.height - SetRouteViewSettings.shared.routeViewHeight - navBarSize let topConstant = navBarSize + 100 - SetRouteViewSettings.shared.statusBarSizeAdjust let height = UIScreen.main.bounds.height - topConstant self.anchor(top: self.superView.topAnchor, left: self.superView.leftAnchor, bottom: nil, right: self.superView.rightAnchor, padding: .init(top: topConstant, left: 0, bottom: 0, right: 0), size: .init(width: 0, height: height)) self.cnstTableTop.isActive = true self.cnstTableTop.constant = UIScreen.main.bounds.height } public func setPlaces(_ placeList: [PlaceViewModel]) { self.hasLastPlaces = placeList.isEmpty if placeList.isEmpty { // self.placeList = self.defaultOptions } else { self.placeList = placeList } layoutIfNeeded() } public func setLastPlaces(_ placeList: [PlaceViewModel]) { self.hasLastPlaces = true self.lastPlaces = placeList layoutIfNeeded() } public func clearPlaces() { self.setPlaces([]) layoutIfNeeded() } func startProgress() { guard !self.isProgressAnimating else { return } self.isProgressAnimating = true self.viewProgress.isHidden = false let layer = CAShapeLayer() let size = CGSize(width: self.viewProgress.frame.width/4, height: self.viewProgress.frame.height) let rect = CGRect(origin: .zero, size: size) layer.path = UIBezierPath(roundedRect: rect, cornerRadius: 0).cgPath layer.fillColor = UIColor.black.cgColor self.viewProgress.layer.addSublayer(layer) let duration: TimeInterval = 1.2 let positionAnimation = CAKeyframeAnimation(keyPath: "position.x") positionAnimation.values = [0, self.viewProgress.frame.width, 0] positionAnimation.keyTimes = [0, 0.5, 1] positionAnimation.duration = duration positionAnimation.repeatCount = .greatestFiniteMagnitude positionAnimation.isAdditive = true let widthAnimation = CAKeyframeAnimation(keyPath: "transform.scale.x") widthAnimation.values = [0, 1, 0, 1, 0] widthAnimation.keyTimes = [0, 0.25, 0.5, 0.75, 1] widthAnimation.duration = duration widthAnimation.repeatCount = .greatestFiniteMagnitude layer.add(positionAnimation, forKey: "position") layer.add(widthAnimation, forKey: "width") } func stopProgress() { guard self.isProgressAnimating else { return } DispatchQueue.main.async { let animatingLayer = self.viewProgress.layer.sublayers?.first animatingLayer?.removeAllAnimations() animatingLayer?.removeFromSuperlayer() } self.viewProgress.isHidden = true } } extension EditStopTableView: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let row = indexPath.row var selectedPlace: PlaceViewModel #warning("Substituir por operador ternário") if self.hasLastPlaces { selectedPlace = self.lastPlaces[row] }else{ selectedPlace = self.placeList[row] } #warning("Instância 'stop' deveria estar dentro do if, pois se o if não for satisfeito, estará sendo instanciado sem propósito") let stop = Points(visited: false, address: Address(placeId: selectedPlace.objectId, text: selectedPlace.mainText, location: Location(latitude: selectedPlace.coordinates?.latitude ?? 0.0, longitude: selectedPlace.coordinates?.longitude ?? 0.0)), type: "") // let selectedPlace = self.placeList[row] if let cell = tableView.cellForRow(at: indexPath) as? PlacesCell { cell.select() self.startProgress() self.myDelegate?.editStopTable(view: self, didSelect: selectedPlace.mainText, point: stop) self.didSelectPlace?(selectedPlace) DispatchQueue.main.asyncAfter(deadline: .now() + 0.15) { cell.isSelected = false cell.deselect() } } } func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) { if let cell = tableView.cellForRow(at: indexPath) as? PlacesCell { cell.deselect() } } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableView.automaticDimension } } extension EditStopTableView: UITableViewDataSource { // func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { // switch section { // case 0: // return nil // default: // if self.hasLastPlaces && !self.lastPlaces.isEmpty { // let view = HeaderView() // return view // } else { // return nil // } // } // } // // func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { // // return CGFloat(section * 40) // return section != 0 && self.hasLastPlaces && !self.lastPlaces.isEmpty ? 40 : 0 // } // func numberOfSections(in tableView: UITableView) -> Int { // return self.hasLastPlaces && !self.lastPlaces.isEmpty ? 2 : 1 // } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.hasLastPlaces ? self.lastPlaces.count : self.placeList.count // return self.placeList.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // let section = indexPath.section let row = indexPath.row let cell = tableView.dequeueReusableCell(withIdentifier: "PlacesCell", for: indexPath) as! PlacesCell // switch section { // case 0: // cell.placeModel = self.placeList[row] // default: // cell.placeModel = self.lastPlaces[row] // } if self.hasLastPlaces { if self.lastPlaces.count > 0{ cell.placeModel = self.lastPlaces[row] } }else{ if self.placeList.count > 0{ cell.placeModel = self.placeList[row] } } return cell } }
// // Enums.swift // GiftManager // // Created by David Johnson on 2/5/17. // Copyright © 2017 David Johnson. All rights reserved. // import Foundation /// An enumeration of data operations /// /// - Add: add a data element /// - Update: update a data element /// - Delete: delete a data slement enum DataOperation:Int { /// Add a data element case Add /// Update a data element case Update /// Delete a data slement case Delete }
// // SLAlertView.swift // SolarExtensionExample // // Created by wyh on 2018/2/12. // Copyright © 2018年 SolarKit. All rights reserved. // import UIKit public class SLAlertView: UIAlertView, UIAlertViewDelegate { private lazy var actionDict: [Int: SLEmptyClosure] = { return [:] }() public init(title aTitle: String?, message aMessage: String?) { super.init(frame: CGRect.zero) if let atitle = aTitle { title = atitle } message = aMessage delegate = self } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } public extension SLAlertView { public func addAction(_ title:String?, _ style: UIAlertActionStyle, _ action: SLEmptyClosure? = nil) { let index = addButton(title, action) switch style { case .cancel: cancelButtonIndex = index case .destructive, .default: break } } private func addButton(_ title: String?, _ action: SLEmptyClosure? = nil) -> Int { let index = addButton(withTitle: title) if let action = action { actionDict[index] = action } return index } } public extension SLAlertView { public var textField: UITextField? { return textField(at: 0) } public var passwordTextField: UITextField? { return textField(at: 1) } } extension SLAlertView { public func alertView(_ alertView: UIAlertView, clickedButtonAt buttonIndex: Int) { if let action = actionDict[buttonIndex] { action() actionDict.removeAll() } } }
// // ViewController.swift // BackpacDevelopmentTask // // Created by Hansub Yoo on 2020/05/23. // Copyright © 2020 Hansub Yoo. All rights reserved. // import UIKit import Alamofire class MainViewController: UIViewController { /// 검색된 데이터 var searchedData: ItunesAppInfo? var mainTableView: UITableView = { let tableView = UITableView() tableView.bounces = false tableView.register(MainTableViewCell.self, forCellReuseIdentifier: "mainCell") tableView.translatesAutoresizingMaskIntoConstraints = false return tableView }() override func viewDidLoad() { super.viewDidLoad() DispatchQueue.global(qos: .background).async { DataFetch.shared.getData { (appInfo) in self.searchedData = appInfo DispatchQueue.main.async { self.mainTableView.reloadData() } self.checkNoData(self.searchedData?.resultCount) } } self.setViewFoundations() self.setAddSubViews() self.setLayouts() self.setDelegates() self.setOtherProperties() } func setViewFoundations() { self.title = CommonValue.wordToSearch if #available(iOS 11.0, *) { self.navigationController?.navigationBar.prefersLargeTitles = true } } func setAddSubViews() { self.view.addSubviews([ self.mainTableView ]) } func setLayouts() { var safeAreaTopAnchor: NSLayoutYAxisAnchor if #available(iOS 11.0, *) { safeAreaTopAnchor = self.view.safeAreaLayoutGuide.topAnchor } else { safeAreaTopAnchor = self.view.topAnchor } NSLayoutConstraint.activate([ self.mainTableView.topAnchor.constraint(equalTo: safeAreaTopAnchor), self.mainTableView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor), self.mainTableView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor), self.mainTableView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor) ]) } func setDelegates() { self.mainTableView.delegate = self self.mainTableView.dataSource = self } func setOtherProperties() { self.mainTableView.separatorStyle = .none } } // MARK: - 기능 extension MainViewController { /// 데이터가 없을 경우 alert을 띄워준다. func checkNoData(_ count: Int?) { if let count = count, count == 0 { CommonFunctions.shared.showAlert(controller: self, title: "", message: "찾으시는 데이터가 없습니다.", alertStyle: .alert) } } } // MARK: - extension MainViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return self.view.frame.width * 1.33 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { self.mainTableView.deselectRow(at: indexPath, animated: false) let detailVC = DetailViewController() detailVC.appInfo = self.searchedData?.results![indexPath.row] self.navigationController?.pushViewController(detailVC, animated: true) } } extension MainViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.searchedData?.resultCount ?? 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let mainCell = tableView.dequeueReusableCell(withIdentifier: "mainCell", for: indexPath) as! MainTableViewCell mainCell.titleImageView.image = CommonFunctions.shared.getImageByURL(urlString: self.searchedData?.results![indexPath.row].artworkUrl512) mainCell.appNameLabel.text = self.searchedData?.results![indexPath.row].trackName mainCell.sellerNameLabel.text = self.searchedData?.results![indexPath.row].sellerName mainCell.genrelabel.text = self.searchedData?.results![indexPath.row].primaryGenreName mainCell.priceLabel.text = self.searchedData?.results![indexPath.row].formattedPrice mainCell.ratingView.rating = CommonFunctions.shared.roundingNumber(self.searchedData?.results![indexPath.row].averageUserRating) return mainCell } }
// // MeetingInformationVC.swift // auto_scheduler // // Created by macbook_user on 10/31/16. // // import UIKit import EventKit import MapKit import CoreLocation class MeetingInformationVC: UIViewController { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var mapView: MKMapView! // @IBOutlet weak var contact1: UILabel! @IBOutlet weak var Control: UISegmentedControl! // @IBOutlet weak var contact2: UILabel! @IBOutlet weak var Location: UILabel! @IBOutlet weak var meetingTitle: UILabel! var meetingName: [String] = [] var events_complete_info: [EKEvent] = [] var contactsAttending: [EKParticipant] = [] var geocoder = CLGeocoder() let regionRadius: CLLocationDistance = 1000 var initialLocation = CLLocation(latitude: 41.8781, longitude: -87.6298) @IBAction func canmetgc(_ sender: AnyObject) { if Control.selectedSegmentIndex == 0{ navigationController?.popViewController(animated: true) } if Control.selectedSegmentIndex == 1{ } } /* func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return contactsAttending.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { tableView.flashScrollIndicators() let cell = UITableViewCell(style: .default, reuseIdentifier: "CELL") cell.textLabel!.text = String(describing: contactsAttending[indexPath.row]) return cell } */ override func viewDidAppear(_ animated: Bool) { // InitUI() meetingTitle.text! = events_complete_info[0].title //contactsAttending = events_complete_info[0].attendees! // contact1.text! = meetingName[1] // contact2.text! = meetingName[2] Location.text! = events_complete_info[0].location! showLocationOnMap() // print("Is it working") // print(self.initialLocation) // centerMapOnLocation(location: self.initialLocation) // print(type(of:events_complete_info[0].attendees)) // print(events_complete_info[0].attendees) } func showLocationOnMap(){ print("SHOW LOCATION FUNCTION CALLED") var address = String(events_complete_info[0].location!) // var initialLocationCoordinates = CLLocationCoordinate2D(latitude: 21.282778, longitude: -157.829444) geocoder.geocodeAddressString(address!, completionHandler: {(placemarks, error) -> Void in if((error) != nil){ // print("Error", error) } if let placemark = placemarks?.first { let dropPin = MKPointAnnotation() let coordinates:CLLocationCoordinate2D = placemark.location!.coordinate self.initialLocation = CLLocation(latitude: coordinates.latitude, longitude: coordinates.longitude) print("--------------location---------") print(self.initialLocation.coordinate) dropPin.coordinate = self.initialLocation.coordinate self.mapView.addAnnotation(dropPin) let coordinateRegion = MKCoordinateRegionMakeWithDistance(self.initialLocation.coordinate,self.regionRadius * 2.0, self.regionRadius * 2.0) self.mapView.setRegion(coordinateRegion, animated: true) } }) } /* func centerMapOnLocation(location: CLLocation) { let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate,regionRadius * 2.0, regionRadius * 2.0) mapView.setRegion(coordinateRegion, animated: true) }*/ override func viewDidLoad() { super.viewDidLoad() // tableView.delegate = self // tableView.dataSource = self // contactsAttending.append(meetingName[1]) // contactsAttending.append(meetingName[2]) /* contactsAttending.append("A") contactsAttending.append("B") contactsAttending.append("C") contactsAttending.append("D") contactsAttending.append("E") contactsAttending.append("F") contactsAttending.append("G") contactsAttending.append("H")*/ // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning(); } }
// // Bookmark.swift // AEXML // // Created by Aleksandr Vdovichenko on 3/7/18. // import Foundation import RealmSwift //values.put(BooksDBContract.BookMarkups.USER_ID, userId); //values.put(BooksDBContract.BookMarkups.BOOK_SKU, bookSku); //values.put(BooksDBContract.BookMarkups.BOOK_CODE, bc); //values.put(BooksDBContract.BookMarkups.CHAPTER_INDEX, ci); //values.put(BooksDBContract.BookMarkups.CHAPTER_TITLE, title); //values.put(BooksDBContract.BookMarkups.PAGE_POSITION_IN_CHAPTER, ppc); //values.put(BooksDBContract.BookMarkups.PAGE_POSITION_IN_BOOK, ppb); //values.put(BooksDBContract.BookMarkups.PAGE_INDEX_IN_BOOK, piib); //values.put(BooksDBContract.BookMarkups.CREATED_DATE, dateInString); open class Bookmark: Object { @objc open dynamic var userId: String! @objc open dynamic var bookSku: String! @objc open dynamic var bookName: String! @objc open dynamic var chapterIndex: Int = 0 @objc open dynamic var pagePositionInChapter: Float = 0.0 @objc open dynamic var pagePositionInBook: Float = 0.0 @objc open dynamic var pageIndexInBook: Int = 0 @objc open dynamic var createdDateString: String = "" override open class func primaryKey()-> String { return "createdDateString" } open func json() -> Dictionary<String, Any> { return ["userId" : userId, "bookSku" : bookSku, "bookName" : bookName, "chapterIndex" : chapterIndex, "pagePositionInChapter" : pagePositionInChapter, "pagePositionInBook" : pagePositionInBook, "pageIndexInBook" : pageIndexInBook, "createdDateString" : createdDateString] } } extension Bookmark { // SkyEpub uses pagePositionInBook double value to locate the exact position in epub. // In Reflowable Layout in epub, there’s no fixed page index because total page number will be // changed according to screen size, font and font size, line space or etc. // So we need to think about another concept to express the one position in book for navigation // or bookmark. // pagePosition could be calculated as blow. // so to locate a specific position in book, you need to use pagePositionInBook concept. // assuming that you have 3 chapters in epub, and if you want to goto 25% of second // chapter. // Assuming that there are 3 chapters (which is defined in spine tag of opf file) in a epub and if // you want to goto 25% of 2nd chapter. // numberOfChapter = 3; // chapterDelta = 1/numberOfChapter; // chapterIndex = 1; // positionInChapter = 0.25; // pagePositionInBook = chapterDelta* chapterIndex + // chapterDelta*positionInChapter; // e.g) pagePositionInBook = (1/3)*1 + (1/3)*.25 = 0.416667f static func save(_ readerCenter: FolioReaderCenter, completion: Completion?) { guard let readerConfig = readerCenter.readerContainer?.readerConfig, let readerProgressManager = readerCenter.readerProgressManager else { return } var bookMark = Bookmark() bookMark.userId = readerConfig.userId bookMark.bookSku = readerConfig.bookSku bookMark.bookName = readerConfig.bookTitle ?? "" let dateFormatter = DateFormatter() dateFormatter.dateFormat = readerConfig.localizedHighlightsDateFormat dateFormatter.locale = Locale.current bookMark.createdDateString = dateFormatter.string(from: Foundation.Date()) let currentPage = readerProgressManager.currentPage bookMark.pageIndexInBook = currentPage let chapterIndex = readerCenter.currentPageNumber - 1 bookMark.chapterIndex = chapterIndex let pageWidth = Float(readerCenter.pageWidth) let pagesInChapter = Float(readerProgressManager.currentTotalPages(section: chapterIndex)) guard let pageWebView = readerCenter.currentPage else { return } let contentOffsetY = Float(pageWebView.webView.scrollView.contentSize.width - pageWebView.webView.scrollView.contentOffset.x) let tempWidth: Float = pagesInChapter * pageWidth if contentOffsetY > 0 && tempWidth > 0 { bookMark.pagePositionInChapter = Float(contentOffsetY/tempWidth) } let totalPages = readerProgressManager.allCountPages if totalPages > 0 { bookMark.pagePositionInBook = Float(Float(currentPage)/Float(totalPages)) } do { let realm = try Realm(configuration: readerConfig.realmConfiguration) realm.beginWrite() realm.add(bookMark, update: .modified) try realm.commitWrite() completion?(nil) NotificationCenter.default.post(name: NSNotification.Name(rawValue: "com.app.GetBooksApp.Notification.Name.Bookmark.add"), object: nil, userInfo: ["bookmark": bookMark]) } catch let error as NSError { print("Error on persist highlight: \(error)") completion?(error) } } open static func allOld(withConfiguration readerConfig: FolioReaderConfig) -> [Bookmark] { var bookmarks: [Bookmark] = [] var predicate = NSPredicate(format: "bookSku = %@ AND userId = %@", readerConfig.bookSku, readerConfig.userId) do { let realm = try Realm(configuration: readerConfig.realmConfiguration) bookmarks = realm.objects(Bookmark.self).filter(predicate).toArray(Bookmark.self) return bookmarks } catch let error as NSError { print("Error on fetch all by book Id: \(error)") return [] } } open static func all(withConfiguration readerConfig: FolioReaderConfig) -> [Bookmark] { var bookmarks: [Bookmark] = [] var predicate = NSPredicate(format: "bookSku = %@ AND userId = %@", readerConfig.bookSku, readerConfig.userId) do { let realm = try Realm(configuration: readerConfig.realmConfiguration) bookmarks = realm.objects(Bookmark.self).filter(predicate).toArray(Bookmark.self) return bookmarks } catch let error as NSError { print("Error on fetch all by book Id: \(error)") return [] } } static func all(withConfiguration readerConfig: FolioReaderConfig, andChapterIndex chapterIndex: Int) -> [Bookmark] { var bookmarks: [Bookmark] = [] var predicate = NSPredicate(format: "bookSku = %@ AND userId = %@ AND chapterIndex = \(chapterIndex)", readerConfig.bookSku, readerConfig.userId) do { let realm = try Realm(configuration: readerConfig.realmConfiguration) bookmarks = realm.objects(Bookmark.self).filter(predicate).toArray(Bookmark.self) return bookmarks } catch let error as NSError { print("Error on fetch all by book Id: \(error)") return [] } } func remove(withConfiguration readerConfig: FolioReaderConfig, completion: Completion? = nil) { do { guard let realm = try? Realm(configuration: readerConfig.realmConfiguration) else { return } try realm.write { realm.delete(self) try realm.commitWrite() completion?(nil) } } catch let error as NSError { print("Error on remove highlight: \(error)") completion?(error) } } static func remove(bookmarkWithUpdateDate date: String, withConfiguration readerConfig: FolioReaderConfig){ var predicate = NSPredicate(format: "createdDateString = %@", date) do { let realm = try Realm(configuration: readerConfig.realmConfiguration) guard let bookmark = realm.objects(Bookmark.self).filter(predicate).toArray(Bookmark.self).first else { return } try realm.write { realm.delete(bookmark) try realm.commitWrite() } } catch let error as NSError { print("Error on fetch all by book Id: \(error)") } } }
// // SQLite.Query // Copyright (c) 2014 Stephen Celis. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // /// A dictionary mapping column names to values. public typealias Values = [String: Datatype?] /// A query object. Used to build SQL statements with a collection of chainable /// helper functions. public struct Query { private var database: Database internal init(_ database: Database, _ tableName: String) { self.database = database self.tableName = tableName self.columnNames = ["*"] } // MARK: - Keywords /// Determines the join operator for a query’s JOIN clause. public enum JoinType: String { /// A CROSS JOIN. case Cross = "CROSS" /// An INNER JOIN. case Inner = "INNER" /// A LEFT OUTER JOIN. case LeftOuter = "LEFT OUTER" } /// Determines the direction in which rows are returned for a query’s ORDER /// BY clause. public enum SortDirection: String { /// Ascending order (smaller to larger values). case Asc = "ASC" /// Descending order (larger to smaller values). case Desc = "DESC" } private var columnNames: [String] private var tableName: String private var joins = [JoinType, String, String]() private var conditions: String? private var bindings = [Datatype?]() private var groupByHaving: ([String], String?, [Datatype?])? private var order = [String, SortDirection]() private var limit: Int? private var offset: Int? // MARK: - /// Sets a SELECT clause on the query. /// /// :param: columnNames A list of columns to retrieve. /// /// :returns: A query with the given SELECT clause applied. public func select(columnNames: String...) -> Query { var query = self query.columnNames = columnNames return query } /// Adds an INNER JOIN clause to the query. /// /// :param: tableName The table being joined. /// /// :param: constraint The condition in which the table is joined. /// /// :returns: A query with the given INNER JOIN clause applied. public func join(tableName: String, on constraint: String) -> Query { return join(.Inner, tableName, on: constraint) } /// Adds a JOIN clause to the query. /// /// :param: type The JOIN operator used. /// /// :param: tableName The table being joined. /// /// :param: constraint The condition in which the table is joined. /// /// :returns: A query with the given JOIN clause applied. public func join(type: JoinType, _ tableName: String, on constraint: String) -> Query { var query = self query.joins.append(type, tableName, constraint) return query } /// Adds a condition to the query’s WHERE clause. /// /// :param: condition A dictionary of conditions where the keys map to /// column names and the columns must equal the given /// values. /// /// :returns: A query with the given condition applied. public func filter(condition: [String: Datatype?]) -> Query { var query = self for (column, value) in condition { if let value = value { query = query.filter("\(column) = ?", value) } else { query = query.filter("\(column) IS NULL") } } return query } /// Adds a condition to the query’s WHERE clause. /// /// :param: condition A dictionary of conditions where the keys map to /// column names and the columns must be in the lists of /// given values. /// /// :returns: A query with the given condition applied. public func filter(condition: [String: [Datatype?]]) -> Query { var query = self for (column, values) in condition { let templates = Swift.join(", ", [String](count: values.count, repeatedValue: "?")) query = query.filter("\(column) IN (\(templates))", values) } return query } /// Adds a condition to the query’s WHERE clause. /// /// :param: condition A dictionary of conditions where the keys map to /// column names and the columns must be in the ranges of /// given values. /// /// :returns: A query with the given condition applied. public func filter<T: Datatype>(condition: [String: Range<T>]) -> Query { var query = self for (column, value) in condition { query = query.filter("\(column) BETWEEN ? AND ?", value.startIndex, value.endIndex) } return query } /// Adds a condition to the query’s WHERE clause. /// /// :param: condition A string condition with optional "?"-parameterized /// bindings. /// /// :param: bindings A list of parameters to bind to the WHERE clause. /// /// :returns: A query with the given condition applied. public func filter(condition: String, _ bindings: Datatype?...) -> Query { return filter(condition, bindings) } /// Adds a condition to the query’s WHERE clause. /// /// :param: condition A string condition with optional "?"-parameterized /// bindings. /// /// :param: bindings A list of parameters to bind to the WHERE clause. /// /// :returns: A query with the given condition applied. public func filter(condition: String, _ bindings: [Datatype?]) -> Query { var query = self if let conditions = query.conditions { query.conditions = "\(conditions) AND \(condition)" } else { query.conditions = condition } query.bindings += bindings return query } /// Sets a GROUP BY clause on the query. /// /// :param: by A list of columns to group by. /// /// :returns: A query with the given GROUP BY clause applied. public func group(by: String...) -> Query { return group(by, []) } /// Sets a GROUP BY-HAVING clause on the query. /// /// :param: by A column to group by. /// /// :param: having A condition determining which groups are returned. /// /// :param: bindings A list of parameters to bind to the HAVING clause. /// /// :returns: A query with the given GROUP BY clause applied. public func group(by: String, having: String, _ bindings: Datatype?...) -> Query { return group([by], having: having, bindings) } /// Sets a GROUP BY-HAVING clause on the query. /// /// :param: by A list of columns to group by. /// /// :param: having A condition determining which groups are returned. /// /// :param: bindings A list of parameters to bind to the HAVING clause. /// /// :returns: A query with the given GROUP BY clause applied. public func group(by: [String], having: String, _ bindings: Datatype?...) -> Query { return group(by, having: having, bindings) } private func group(by: [String], having: String? = nil, _ bindings: [Datatype?]) -> Query { var query = self query.groupByHaving = (by, having, bindings) return query } /// Adds sorting instructions to the query’s ORDER BY clause. /// /// :param: by A list of columns to order by with an ascending sort. /// /// :returns: A query with the given sorting instructions applied. public func order(by: String...) -> Query { return order(by) } private func order(by: [String]) -> Query { return order(by.map { ($0, .Asc) }) } /// Adds sorting instructions to the query’s ORDER BY clause. /// /// :param: by A column to order by. /// /// :param: direction The direction in which the column is ordered. /// /// :returns: A query with the given sorting instructions applied. public func order(by: String, _ direction: SortDirection) -> Query { return order([(by, direction)]) } /// Adds sorting instructions to the query’s ORDER BY clause. /// /// :param: by An ordered list of columns and directions to sort them by. /// /// :returns: A query with the given sorting instructions applied. public func order(by: (String, SortDirection)...) -> Query { return order(by) } private func order(by: [(String, SortDirection)]) -> Query { var query = self query.order += by return query } /// Sets the LIMIT clause (and resets any OFFSET clause) on the query. /// /// :param: to The maximum number of rows to return. /// /// :returns A query with the given LIMIT clause applied. public func limit(to: Int?) -> Query { return limit(to: to, offset: nil) } /// Sets LIMIT and OFFSET clauses on the query. /// /// :param: to The maximum number of rows to return. /// /// :param: offset The number of rows to skip. /// /// :returns A query with the given LIMIT and OFFSET clauses applied. public func limit(to: Int, offset: Int) -> Query { return limit(to: to, offset: offset) } // prevent limit(nil, offset: 5) private func limit(#to: Int?, offset: Int? = nil) -> Query { var query = self (query.limit, query.offset) = (to, offset) return query } // MARK: - Compiling Statements private var selectStatement: Statement { let columnNames = Swift.join(", ", self.columnNames) var parts = ["SELECT \(columnNames) FROM \(tableName)"] joinClause.map(parts.append) whereClause.map(parts.append) groupClause.map(parts.append) orderClause.map(parts.append) limitClause.map(parts.append) var bindings = self.bindings if let (_, _, values) = groupByHaving { bindings += values } return database.prepare(Swift.join(" ", parts), bindings) } private func insertStatement(values: Values) -> Statement { var (parts, bindings) = (["INSERT INTO \(tableName)"], self.bindings) let valuesClause = Swift.join(", ", map(values) { columnName, value in bindings.append(value) return columnName }) let templates = Swift.join(", ", [String](count: values.count, repeatedValue: "?")) parts.append("(\(valuesClause)) VALUES (\(templates))") return database.prepare(Swift.join(" ", parts), bindings) } private func updateStatement(values: Values) -> Statement { var (parts, bindings) = (["UPDATE \(tableName)"], [Datatype?]()) let valuesClause = Swift.join(", ", map(values) { columnName, value in bindings.append(value) return "\(columnName) = ?" }) parts.append("SET \(valuesClause)") whereClause.map(parts.append) return database.prepare(Swift.join(" ", parts), bindings + self.bindings) } private var deleteStatement: Statement { var parts = ["DELETE FROM \(tableName)"] whereClause.map(parts.append) return database.prepare(Swift.join(" ", parts), bindings) } // MARK: - private var joinClause: String? { if joins.count == 0 { return nil } let clause = joins.map { "\($0.rawValue) JOIN \($1) ON \($2)" } return Swift.join(" ", clause) } private var whereClause: String? { if let conditions = conditions { return "WHERE \(conditions)" } return nil } private var groupClause: String? { if let (groupBy, having, _) = groupByHaving { let groups = Swift.join(", ", groupBy) var clause = ["GROUP BY \(groups)"] having.map { clause.append("HAVING \($0)") } return Swift.join(" ", clause) } return nil } private var orderClause: String? { if order.count == 0 { return nil } let mapped = order.map { "\($0.0) \($0.1.rawValue)" } let joined = Swift.join(", ", mapped) return "ORDER BY \(joined)" } private var limitClause: String? { if let to = limit { var clause = ["LIMIT \(to)"] offset.map { clause.append("OFFSET \($0)") } return Swift.join(" ", clause) } return nil } // MARK: - Array /// The first result (or nil if the query has no results). public var first: Values? { return limit(1).generate().next() } /// The last result (or nil if the query has no results). public var last: Values? { return reverse(self).first } /// Returns true if the query has no results. public var isEmpty: Bool { return first == nil } // MARK: - Modifying /// Runs an INSERT statement with the given row of values. /// /// :param: values A dictionary of column names to values. /// /// :returns: The statement. public func insert(values: Values) -> Statement { return insert(values).statement } /// Runs an INSERT statement with the given row of values. /// /// :param: values A dictionary of column names to values. /// /// :returns: The row ID. public func insert(values: Values) -> Int? { return insert(values).ID } /// Runs an INSERT statement with the given row of values. /// /// :param: values A dictionary of column names to values. /// /// :returns: The row ID and statement. public func insert(values: Values) -> (ID: Int?, statement: Statement) { let statement = insertStatement(values).run() return (statement.failed ? nil : database.lastID, statement) } /// Runs an UPDATE statement against the query with the given values. /// /// :param: values A dictionary of column names to values. /// /// :returns: The statement. public func update(values: Values) -> Statement { return update(values).statement } /// Runs an UPDATE statement against the query with the given values. /// /// :param: values A dictionary of column names to values. /// /// :returns: The number of updated rows. public func update(values: Values) -> Int { return update(values).changes } /// Runs an UPDATE statement against the query with the given values. /// /// :param: values A dictionary of column names to values. /// /// :returns: The number of updated rows and statement. public func update(values: Values) -> (changes: Int, statement: Statement) { let statement = updateStatement(values).run() return (statement.failed ? 0 : database.lastChanges ?? 0, statement) } /// Runs an DELETE statement against the query. /// /// :returns: The statement. public func delete() -> Statement { return delete().statement } /// Runs an DELETE statement against the query. /// /// :returns: The number of deleted rows. public func delete() -> Int { return delete().changes } /// Runs an DELETE statement against the query. /// /// :returns: The number of deleted rows and statement. public func delete() -> (changes: Int, statement: Statement) { let statement = deleteStatement.run() return (statement.failed ? 0 : database.lastChanges ?? 0, statement) } // MARK: - Aggregate Functions /// Runs count(*) against the query and returns it. public var count: Int { return count("*") } /// Runs count() against the query. /// /// :param: columnName The column used for the calculation. /// /// :returns: The number of rows matching the given column. public func count(columnName: String) -> Int { return calculate("count", columnName) as Int } /// Runs max() against the query. /// /// :param: columnName The column used for the calculation. /// /// :returns: The largest value of the given column. public func max(columnName: String) -> Datatype? { return calculate("max", columnName) } /// Runs min() against the query. /// /// :param: columnName The column used for the calculation. /// /// :returns: The smallest value of the given column. public func min(columnName: String) -> Datatype? { return calculate("min", columnName) } /// Runs avg() against the query. /// /// :param: columnName The column used for the calculation. /// :returns: The average value of the given column. public func average(columnName: String) -> Double? { return calculate("avg", columnName) as? Double } /// Runs sum() against the query. /// /// :param: columnName The column used for the calculation. /// /// :returns: The sum of the given column’s values. public func sum(columnName: String) -> Datatype? { return calculate("sum", columnName) } /// Runs total() against the query. /// /// :param: columnName The column used for the calculation. /// /// :returns: The total of the given column’s values. public func total(columnName: String) -> Double { return calculate("total", columnName) as Double } private func calculate(function: String, _ columnName: String) -> Datatype? { return select("\(function)(\(columnName))").selectStatement.scalar() } } // MARK: - SequenceType extension Query: SequenceType { public typealias Generator = QueryGenerator public func generate() -> Generator { return Generator(selectStatement) } } // MARK: - GeneratorType public struct QueryGenerator: GeneratorType { private var statement: Statement private init(_ statement: Statement) { self.statement = statement } public func next() -> Values? { statement.next() return statement.values } } /// Reverses the order of a given query. /// /// :param: query A query object to reverse. /// /// :returns: A reversed query. public func reverse(query: Query) -> Query { if query.order.count == 0 { return query.order("\(query.tableName).ROWID", .Desc) } var reversed = query reversed.order = query.order.map { ($0, $1 == .Asc ? .Desc : .Asc) } return reversed }
// // SettingViewController.swift // TaskManager // // Created by Истина on 20/06/2019. // Copyright © 2019 Истина. All rights reserved. // import UIKit class SettingViewController: UIViewController { @IBAction func backToMain(_ sender: Any) { dismiss(animated: true, completion: nil) } @IBOutlet weak var switchNotification: UISwitch! @IBAction func notificSwitch(_ sender: Any) { if switchNotification.isOn { NotificationsManager.sharedInstance.rescheduleAllNotifications() SettingsData.sharedInstance.editSettings(notificationsEnabled: true) } else { NotificationsManager.sharedInstance.unscheduleAllNotifications() SettingsData.sharedInstance.editSettings(notificationsEnabled: false) } } override func viewDidLoad() { super.viewDidLoad() } }
import Foundation class JobScheduler { private var statuses = [String:JobStatus]() func scheduleChunk(jobs:[JobQueue], finishedCompletion:@escaping ([String: Int64])->()){ var testResults = [String: Int64]() var finishedTasks = 0 for job in jobs { self.statuses[job.label] = JobStatus.STARTED job.finishedClosure = {(time, label) in self.statuses[job.label] = JobStatus.FINISHED testResults[job.label] = time finishedTasks += 1 print("finished: \(label) time: \(time)") if(finishedTasks == jobs.count) { finishedCompletion(testResults) } } job.run() } } enum JobStatus { case STARTED case FINISHED } }
// // SignUpViewController.swift // logU // // Created by Brett Alcox on 1/27/16. // Copyright © 2016 Brett Alcox. All rights reserved. // import UIKit import Eureka class SignUpViewController : FormViewController { override func viewDidLoad() { super.viewDidLoad() form +++ Section("Account") <<< AccountRow("Username") { $0.title = "Username" } <<< PasswordRow("Password") { $0.title = "Password" } <<< PasswordRow("Confirm Password") { $0.title = "Confirm Password" } +++ Section("Options") <<< SegmentedRow<String>("Unit") { $0.title = "Unit" $0.options = ["Pounds", "Kilograms"] $0.value = "Pounds" } <<< SegmentedRow<String>("Gender") { $0.title = "Gender" $0.options = ["Male", "Female"] $0.value = "Male" } <<< DecimalRow("Current Weight") { $0.title = "Current Weight" } +++ Section() <<< ButtonRow("Create Account") { $0.title = "Create Account" $0.onCellSelection({ (cell, row) -> () in self.createTapped() }) } //+++ Section("Save") } func createTapped() { if form.values()["Username"]! == nil || form.values()["Password"]! == nil || form.values()["Confirm Password"]! == nil || form.values()["Current Weight"]! == nil { let actionSheetController: UIAlertController = UIAlertController(title: "Create Account Failed", message: "Please fill out all fields!", preferredStyle: .Alert) let cancelAction: UIAlertAction = UIAlertAction(title: "Dismiss", style: .Cancel) { action -> Void in //Do some stuff } actionSheetController.addAction(cancelAction) self.presentViewController(actionSheetController, animated: true, completion: nil) } else { if String((form.values()["Password"]!)!) != String((form.values()["Confirm Password"]!)!) { let actionSheetController: UIAlertController = UIAlertController(title: "Create Account Failed", message: "Passwords do not match!", preferredStyle: .Alert) let cancelAction: UIAlertAction = UIAlertAction(title: "Dismiss", style: .Cancel) { action -> Void in //Do some stuff } actionSheetController.addAction(cancelAction) self.presentViewController(actionSheetController, animated: true, completion: nil) } else { var convertedUnit = String((form.values()["Unit"]!)!) if convertedUnit == "Pounds" { convertedUnit = "1" } else { convertedUnit = "0" } signUpRequest(String((form.values()["Username"]!)!), passwordInput: String((form.values()["Password"]!)!), unitInput: convertedUnit, genderInput: String((form.values()["Gender"]!)!), weightInput: String((form.values()["Current Weight"]!)!)) } } } func signUpRequest(usernameInput: String, passwordInput: String, unitInput: String, genderInput: String, weightInput: String) { let post: NSString = "username=\(usernameInput)&password=\(passwordInput)&unit=\(unitInput)&gender=\(genderInput)&bodyweight=\(weightInput)" NSLog("PostData: %@", post); let url:NSURL = NSURL(string: "https://loguapp.com/swift_register.php")! let postData:NSData = post.dataUsingEncoding(NSASCIIStringEncoding)! let request:NSMutableURLRequest = NSMutableURLRequest(URL: url) request.HTTPMethod = "POST" request.timeoutInterval = 10 var response: NSURLResponse? do { let urlData: NSData? = try NSURLConnection.sendSynchronousRequest(request, returningResponse:&response) } catch let error as NSError { let actionSheetController: UIAlertController = UIAlertController(title: "Connection Time Out", message: "Do you have a network connection?", preferredStyle: .Alert) let cancelAction: UIAlertAction = UIAlertAction(title: "Dismiss", style: .Cancel) { action -> Void in //Do some stuff } actionSheetController.addAction(cancelAction) self.presentViewController(actionSheetController, animated: true, completion: nil) } let session = NSURLSession.sharedSession() let task = session.uploadTaskWithRequest(request, fromData: postData, completionHandler: {(data,response,error) in guard let _:NSData = data, let _:NSURLResponse = response where error == nil else { if error?.code == NSURLErrorTimedOut { //Call your method here. } return } let dataString = NSString(data: data!, encoding: NSUTF8StringEncoding) as! String dataResult = dataString if dataResult == " 1" { dispatch_async(dispatch_get_main_queue(), { let actionSheetController: UIAlertController = UIAlertController(title: "Creating Account Successful", message: "Login now!", preferredStyle: .Alert) let cancelAction: UIAlertAction = UIAlertAction(title: "Dismiss", style: .Cancel) { action -> Void in //Do some stuff self.performSegueWithIdentifier("exitToLogin", sender: self) } actionSheetController.addAction(cancelAction) self.presentViewController(actionSheetController, animated: true, completion: nil) }) } else { dispatch_async(dispatch_get_main_queue(), { let actionSheetController: UIAlertController = UIAlertController(title: "Creating Account Failed", message: "Username is taken", preferredStyle: .Alert) let cancelAction: UIAlertAction = UIAlertAction(title: "Dismiss", style: .Cancel) { action -> Void in //Do some stuff } actionSheetController.addAction(cancelAction) self.presentViewController(actionSheetController, animated: true, completion: nil) }) } } ); task.resume() } }
import Foundation import CoreMotion import UIKit class TurnLeft: Task { var motionManager = CMMotionManager() @IBOutlet var flatSurfaceLabel: UILabel! override func setupTask() { print("TurnLeft >>>") motionManager.startAccelerometerUpdates() motionManager.accelerometerUpdateInterval = 0.1 motionManager.startAccelerometerUpdates(to: OperationQueue.main){ (data, error) in if let acceleration = data?.acceleration { if(-1.2 < acceleration.x && acceleration.x < -0.8){ self.motionManager.stopAccelerometerUpdates() print("<<< TurnLeft") self.doneTask() } } } } }
// // TrainingSET500Av.swift // KayakFirst Ergometer E2 // // Created by Balazs Vidumanszki on 2017. 02. 09.. // Copyright © 2017. Balazs Vidumanszki. All rights reserved. // import Foundation class TrainingSET500Av: TrainingSumElementAvgTime { override func getTrainingType() -> String { return CalculateEnum.T_500_AV.rawValue } override func getTitleMetric() -> String { return getString("training_sum_t_500_metric") } override func getTitleImperial() -> String { return getString("training_sum_t_500_imperial") } override func isMetric() -> Bool { return UnitHelper.isMetricPace() } override func calculate() -> Double { return UnitHelper.getPaceValue(pace: Pace.pace500, metricValue: sumData) } }
// // TranslationDIPart.swift // CoreML_test // // Created Осина П.М. on 19.03.18. // Copyright © 2018 Осина П.М.. All rights reserved. // import Foundation import DITranquillity class TranslationDIPart: DIPart { static func load(container: DIContainer) { container.register { () -> TranslationViewController in let storyboard = UIStoryboard(name: "Translation", bundle: nil) return storyboard.instantiateInitialViewController() as! TranslationViewController } .as(TranslationView.self) .injection(cycle: true) { $0.presenter = $1 } .lifetime(.objectGraph) container.register(TranslationPresenterImpl.init(view:router:translationService:)) .as(TranslationPresenter.self) container.register(TranslationRouterImpl.init) .as(TranslationRouter.self) } }
// // Extensions.swift // SearchNews // // Created by Leandro Fernandes De Oliveira on 2019-09-06. // Copyright © 2019 Leandro Oliveira. All rights reserved. // import Foundation import UIKit extension UIButton { func setBorder(borderWidth:CGFloat, borderColor:UIColor){ layer.borderColor = borderColor.cgColor layer.borderWidth = borderWidth } func setRadius(cornerRadius:CGFloat, maskToBounds:Bool){ layer.masksToBounds = maskToBounds layer.cornerRadius = cornerRadius } } extension String { func addPercentEncodingURL() -> String { return self.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? "" } }
import Foundation /// /// A model representing combined movie and tv show credits for a person. /// /// A person can be both a cast member and crew member of the same show. /// public struct PersonCombinedCredits: Identifiable, Decodable, Equatable, Hashable { /// /// Person identifier. /// public let id: Int /// /// Shows where the person is in the cast. /// public let cast: [Show] /// /// Shows where the person is in the crew. /// public let crew: [Show] /// /// All shows the person is in. /// public var allShows: [Show] { (cast + crew).uniqued() } /// Creates a person combined credits object. /// /// - Parameters: /// - id: Person identifier. /// - cast: Shows where person is in the cast. /// - crew: Shows where person is in the case. /// public init(id: Int, cast: [Show], crew: [Show]) { self.id = id self.cast = cast self.crew = crew } }
// // ModelSerialization.swift // RESS // // Created by Luiz Fernando Silva on 17/07/15. // Copyright (c) 2015 Luiz Fernando Silva. All rights reserved. // import Cocoa import SwiftyJSON /// Serializes the given array of model objects into an array of JSON objects func jsonSerialize<T: JsonSerializable, S: Sequence>(models: S) -> [JSON] where S.Iterator.Element == T { return models.jsonSerialize() } /// Unserializes the given array of JSON objects into a type provided through the generic T argument. /// In case any of the objects being unserialized fails to initialize, a JSONError error is raised func jsonUnserializeStrict<T: JsonInitializable, S: Sequence>(_ source: S, type: T.Type) throws -> [T] where S.Iterator.Element == JSON { return try source.jsonUnserializeStrict(withType: type) } /// Unserializes this array of JSON objects into a type provided through the generic T argument. /// In case any of the objects being unserialized fails to initialize, a nil value is returned func jsonUnserializeOptional<T: JsonInitializable, S: Sequence>(_ source: S, type: T.Type) -> [T]? where S.Iterator.Element == JSON { return source.jsonUnserializeOptional(withType: type) } /// Unserializes the given array of JSON objects into a type provided through the generic T argument. /// This version returns an array of all successful initializations, ignoring any failed initializations func jsonUnserialize<T: JsonInitializable, S: Sequence>(_ source: S, type: T.Type) -> [T] where S.Iterator.Element == JSON { return source.jsonUnserialize(withType: type) } extension Sequence where Iterator.Element == JSON { /// Unserializes this array of JSON objects into a type provided through the generic T argument. /// In case any of the objects being unserialized fails to initialize, a JSONError error is raised func jsonUnserializeStrict<T: JsonInitializable>(withType type: T.Type) throws -> [T] { do { return try self.map { json in try autoreleasepool { try T(json: json) } } } catch { print("Error while trying to parse \(T.self) objects: \(error)") throw error } } /// Unserializes this array of JSON objects into a type provided through the generic T argument. /// In case any of the objects being unserialized fails to initialize, a nil value is returned func jsonUnserializeOptional<T: JsonInitializable>(withType type: T.Type) -> [T]? { return try? jsonUnserializeStrict(withType: type) } /// Unserializes this array of JSON objects into a type provided through the generic T argument. /// This version returns an array of all successful initializations, ignoring any failed initializations func jsonUnserialize<T: JsonInitializable>(withType type: T.Type) -> [T] { return self.flatMap { json in try? autoreleasepool { try T(json: json) } } } } extension Sequence where Iterator.Element: JsonSerializable { /// Serializes this sequence of model objects into an array of JSON objects func jsonSerialize() -> [JSON] { return self.map { $0.serialize() } } }
// // sheetViewIdentifiable.swift // Basics // // Created by Venkatnarayansetty, Badarinath on 11/9/19. // Copyright © 2019 Badarinath Venkatnarayansetty. All rights reserved. // import Foundation import SwiftUI struct DetailInfo: Identifiable { var id = UUID() let image: Image } //struct SheetViewIDentifiable: View { // @State var detailInfo:DetailInfo = nil // var body: some View { // VStack { // Button(action : { // self.detailInfo = DetailInfo(image: Image(systemName: "star.circle")) // }) { // Text("Show Sheet") // .padding() // .foregroundColor(Color.pink) // } // .background(Capsule().strokeBorder(Color.purple, lineWidth: 2)) // .sheet(item: $detailInfo) { (detailInfo) in // DetailSheetView(details: detailInfo) // } // } // } //} //struct DetailSheetView: View { // @Environment(\.presentationMode) var presentation // var details: DetailInfo // var body: some View { // VStack(spacing: 20) { // details.image.font(.largeTitle).foregroundColor(Color.purple) // Text("Sheet").font(.largeTitle) // Text("Presenting with Identifiable") // Spacer() // Button(action: { // self.presentation.wrappedValue.dismiss() // }) { // Text("Dismiss") // }.accentColor(Color.purple) // }.padding(.top, 40) // } //}
import UIKit class productlistTableViewCell: UITableViewCell { @IBOutlet weak var productlistimage: UIImageView! @IBOutlet weak var productlisttitle: UILabel! } class productlistTableViewController: UITableViewController { var delegate : DataBackDelegate? var data : [String : Any] = ["category_name" : " " , "row" : -1] var listproduct = [productme]() var getproduct : productme? var listcategory = [categories]() var getcategory : category? override func viewDidLoad() { super.viewDidLoad() } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let emptyLabel = UILabel(frame: CGRect.init(x: 0, y: 0, width: self.view.bounds.width, height: self.view.bounds.height)) if listproduct.count > 0 { self.tableView.backgroundView = nil return listproduct.count } else { emptyLabel.text = "Press Button Add(+) and start add product" emptyLabel.textAlignment = NSTextAlignment.center emptyLabel.numberOfLines = 3 self.tableView.backgroundView = emptyLabel return 0 } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "productlist", for: indexPath) as! productlistTableViewCell cell.productlistimage.image = listproduct[indexPath.row].img cell.productlisttitle.text = listproduct[indexPath.row].title cell.selectionStyle = .none return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { getproduct = productme(id: 1, title: listproduct[indexPath.row].title, price: listproduct[indexPath.row].price, img: listproduct[indexPath.row].img, description: listproduct[indexPath.row].description) data = ["category_name" : listcategory[indexPath.row].name ?? "" , "row" : indexPath.row ] performSegue(withIdentifier: "toaddproductfromproductlist", sender: self) } override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { let deleteaction = UITableViewRowAction(style: .destructive, title: "Delete", handler: {(action,index) in self.deleteproductfromlist(index: indexPath.row , indexp: indexPath)}) return [deleteaction] } func deleteproductfromlist(index: Int , indexp: IndexPath){ listproduct.remove(at: index) listcategory.remove(at: index) tableView.deleteRows(at: [indexp], with: .left) } @IBAction func unwindfromaddproduct(sender: UIStoryboardSegue) { if sender.source is AddproductViewController { if let fromaddproduct = sender.source as? AddproductViewController { if fromaddproduct.editstep { listproduct[fromaddproduct.data["row"] as! Int] = fromaddproduct.myaddproducts! listcategory[fromaddproduct.data["row"] as! Int] = fromaddproduct.add_category! } else { listproduct.append(fromaddproduct.myaddproducts!) listcategory.append(fromaddproduct.add_category!) } } tableView.reloadData() } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { switch segue.identifier! { case "toaddproductfromproductlist": if let toaddproductfromproductlist = segue.destination as? AddproductViewController { toaddproductfromproductlist.navigationController?.title = "Edit Product" toaddproductfromproductlist.myaddproducts = getproduct toaddproductfromproductlist.editstep = true toaddproductfromproductlist.data = self.data } default: print("default switch prepare segue") } } override func viewWillDisappear(_ animated: Bool) { self.delegate?.savePreferences(category: listcategory , p : listproduct) } }
import Persist import SwiftUI import OverampedCore import os.log @main struct OverampedApp: App { @UIApplicationDelegateAdaptor(AppDelegate.self) private var appDelegate @PersistStorage(persister: .extensionHasBeenEnabled) private(set) var extensionHasBeenEnabled: Bool @State private var showDebugView = false var body: some Scene { WindowGroup { Group { if extensionHasBeenEnabled { OverampedTabs() .defaultAppStorage(UserDefaults(suiteName: "group.net.yetii.overamped")!) } else { InstallationInstructionsView(hasAlreadyInstalled: false) } } .environmentObject(FAQLoader()) .onOpenURL(perform: { url in Logger(subsystem: "net.yetii.Overamped", category: "URL Handler") .log("Opened via URL \(url.absoluteString)") guard let deepLink = DeepLink(url: url) else { return } switch deepLink { case .debug: showDebugView = true case .unlock: extensionHasBeenEnabled = true default: break } }) .onReceive(NotificationCenter.default.publisher(for: .motionShakeDidEndNotification)) { _ in switch DistributionMethod.current { case .debug, .testFlight: showDebugView = true case .appStore, .unknown: break } } .sheet(isPresented: $showDebugView) { NavigationView { List { Section("Installation") { Button("Reset extension has been enabled") { extensionHasBeenEnabled = false } } Section("Receipt") { HStack { Text("Path") Spacer() Text(Bundle.main.appStoreReceiptURL?.path ?? "nil") .foregroundColor(Color(.secondaryLabel)) } HStack { Text("Exists") Spacer() Text( Bundle .main .appStoreReceiptURL .flatMap { url in FileManager.default.fileExists(atPath: url.path).description } ?? "-" ) .foregroundColor(Color(.secondaryLabel)) } HStack { Text("Distribution Method") Spacer() Text(String(describing: DistributionMethod.current)) .foregroundColor(Color(.secondaryLabel)) } } } .navigationTitle("Debug") } } } } } private final class AppDelegate: NSObject, UIApplicationDelegate { func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool { if CommandLine.arguments.contains("--uiTests") { do { try Persister<Any>.enabledAdvancedStatistics.persist(true) try Persister<Any>.extensionHasBeenEnabled.persist(true) let ignoredHostnames = [ "nytimes.com", "9to5mac.com", "vice.com", ] try Persister<Any>.ignoredHostnames.persist(ignoredHostnames) try Persister<Any>.replacedLinksCount.persist(387) try Persister<Any>.redirectedLinksCount.persist(22) let redirectsDomains: [String] let replacedLinks: [String] switch Locale.current.regionCode { case "GB": redirectsDomains = Array(repeating: "bbc.co.uk", count: 7) + Array(repeating: "reddit.com", count: 5) + Array(repeating: "theguardian.com", count: 2) + Array(repeating: "amp.dev", count: 1) replacedLinks = Array(repeating: "reddit.com", count: 27) + Array(repeating: "theguardian.com", count: 14) + Array(repeating: "bbc.co.uk", count: 9) + Array(repeating: "amp.dev", count: 1) case "RU": redirectsDomains = Array(repeating: "applinsider.ru", count: 7) + Array(repeating: "reddit.com", count: 5) + Array(repeating: "bbc.com", count: 2) + Array(repeating: "amp.dev", count: 1) replacedLinks = Array(repeating: "reddit.com", count: 27) + Array(repeating: "applinsider.ru", count: 14) + Array(repeating: "bbc.com", count: 9) + Array(repeating: "amp.dev", count: 1) default: redirectsDomains = Array(repeating: "cnn.com", count: 7) + Array(repeating: "reddit.com", count: 5) + Array(repeating: "newegg.com", count: 2) + Array(repeating: "amp.dev", count: 1) replacedLinks = Array(repeating: "reddit.com", count: 27) + Array(repeating: "newegg.com", count: 14) + Array(repeating: "cnn.com", count: 9) + Array(repeating: "amp.dev", count: 1) } let replacedLinksEvent = ReplacedLinksEvent(id: UUID(), date: .now, domains: replacedLinks) try Persister<Any>.replacedLinks.persist([replacedLinksEvent]) let redirectsLinks: [RedirectLinkEvent] = redirectsDomains.enumerated().map { element in let (offset, domain) = element return RedirectLinkEvent(id: UUID(), date: .now.addingTimeInterval(TimeInterval(-offset)), domain: domain) } try Persister<Any>.redirectedLinks.persist(redirectsLinks) } catch {} } if let linksToMigrate = UserDefaults.groupSuite.dictionary(forKey: "replacedLinks") { lazy var dateFormatter = ISO8601DateFormatter() let migratedEvents = linksToMigrate.compactMap { element -> ReplacedLinksEvent? in let (dateString, domains) = element guard let domains = domains as? [String] else { return nil } guard let date = dateFormatter.date(from: dateString) else { return nil } return ReplacedLinksEvent(id: UUID(), date: date, domains: domains) } let persister = Persister<Any>.replacedLinks let existingEvents = persister.retrieveValue() try? persister.persist(migratedEvents + existingEvents) UserDefaults.groupSuite.removeObject(forKey: "replacedLinks") } if let linksToMigrate = UserDefaults.groupSuite.dictionary(forKey: "redirectedLinks") { lazy var dateFormatter = ISO8601DateFormatter() let migratedEvents = linksToMigrate.compactMap { element -> RedirectLinkEvent? in let (dateString, domain) = element guard let domain = domain as? String else { return nil } guard let date = dateFormatter.date(from: dateString) else { return nil } return RedirectLinkEvent(id: UUID(), date: date, domain: domain) } let persister = Persister<Any>.redirectedLinks let existingEvents = persister.retrieveValue() try? persister.persist(migratedEvents + existingEvents) UserDefaults.groupSuite.removeObject(forKey: "redirectedLinks") } return true } } extension NSNotification.Name { public static let motionShakeDidEndNotification = NSNotification.Name("motionShakeDidEndNotification") } extension UIWindow { open override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) { super.motionEnded(motion, with: event) guard motion == .motionShake else { return } NotificationCenter.default.post(name: .motionShakeDidEndNotification, object: event) } }
// // SecondViewController.swift // 42 user information // // Created by Yolankyi SERHII on 7/27/19. // Copyright © 2019 Yolankyi SERHII. All rights reserved. // import UIKit import Alamofire import SwiftyJSON class SecondViewController: UIViewController { @IBOutlet weak var imageViewPhoto: UIImageView! @IBOutlet weak var imageViewCoalition: UIImageView! @IBOutlet weak var backGraund: UIImageView! @IBOutlet weak var coalition: UILabel! @IBOutlet weak var login: UILabel! @IBOutlet weak var name: UILabel! @IBOutlet weak var phone: UILabel! @IBOutlet weak var emalLable: UILabel! @IBOutlet weak var points: UILabel! @IBOutlet weak var numPoints: UILabel! @IBOutlet weak var walet: UILabel! @IBOutlet weak var numWalet: UILabel! @IBOutlet weak var etec: UILabel! @IBOutlet weak var numEtec: UILabel! @IBOutlet weak var lvlProgress: UILabel! @IBOutlet weak var progressViewLvl: UIProgressView! @IBOutlet weak var tableViewSkill: UITableView! @IBOutlet weak var tableViewProjects: UITableView! override func viewDidLoad() { super.viewDidLoad() progressViewLvl.layer.cornerRadius = 4 progressViewLvl.clipsToBounds = true userInfor() userSkills() userProjects() } func userInfor() { if let imageUrl = URL(string: allInfoUser!["image_url"].string ?? "") { if let photoData = try? Data(contentsOf: imageUrl) { imageViewPhoto.image = UIImage(data:photoData)?.circularImage(size: nil) } } coalition.text = allInfoCoalition![0]["name"].string ?? "" switch coalition.text { case "The Alliance": imageViewCoalition.image = UIImage(imageLiteralResourceName: "The_Alliance") backGraund.image = UIImage(imageLiteralResourceName: "Alliance_Background") case "The Empire": imageViewCoalition.image = UIImage(imageLiteralResourceName: "The_Empire") backGraund.image = UIImage(imageLiteralResourceName: "Empire_Background") case "The Hive": imageViewCoalition.image = UIImage(imageLiteralResourceName: "The_Hive") backGraund.image = UIImage(imageLiteralResourceName: "Hive_Background") case "The Union": imageViewCoalition.image = UIImage(imageLiteralResourceName: "The_Union") backGraund.image = UIImage(imageLiteralResourceName: "Union_Background") default : if let imageUrlCoalitionsBackground = URL(string: allInfoCoalition![0]["cover_url"].string ?? "") { if let coalitionsData = try? Data(contentsOf: imageUrlCoalitionsBackground) { backGraund.image = UIImage(data: coalitionsData)! } } } self.imageViewCoalition.changePngColorTo(color: #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)) name.text = allInfoUser!["displayname"].string ?? "" login.text = allInfoUser!["login"].string ?? "" let phoneNum = allInfoUser!["phone"].string ?? "" phone.text = phoneNum let pointNum = allInfoUser!["correction_point"].int ?? 0 numPoints.text = "\(pointNum)" let walletNum = allInfoUser!["wallet"].int ?? 0 numWalet.text = "\(walletNum)" let year = allInfoUser!["pool_year"].string ?? "" numEtec.text = "\(year)" let email = allInfoUser!["email"].string ?? "" emalLable.text = "\(email)" if let level = allInfoUser!["cursus_users"][0]["level"].float { lvlProgress.text = "Level progress: \(level)%" progressViewLvl.progress = level / 21 } } func userSkills() { let skills = allInfoUser!["cursus_users"][0]["skills"] for skill in skills { var sk = Skill.init() sk.name = skill.1["name"].string ?? "" sk.level = skill.1["level"].float ?? 0.0 allUserSkils.append(sk) } } func userProjects() { let projects = allInfoUser!["projects_users"] for project in projects { if project.1["status"].string == "finished" { var pr = Project.init() pr.name = project.1["project"]["name"].string ?? "" pr.mark = project.1["final_mark"].int ?? 0 pr.isValidate = project.1["validated?"].bool ?? false allUserrProgects.append(pr) } } } } extension SecondViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { var num: Int if tableView == tableViewSkill { num = allUserSkils.count } else { num = allUserrProgects.count } return num } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if tableView == tableViewSkill { let cell = tableView.dequeueReusableCell(withIdentifier: "skills") as? SkillsCell cell?.skills.text = "\(allUserSkils[indexPath.row].name ?? "No skill")" cell?.progressViewSkills.progress = (allUserSkils[indexPath.row].level ?? 0.0) / 21 return cell! } else { let cell = tableView.dequeueReusableCell(withIdentifier: "projects") as? ProgectCell cell?.projects.text = allUserrProgects[indexPath.row].name cell?.projectMark.text = String(describing: allUserrProgects[indexPath.row].mark!) if allUserrProgects[indexPath.row].isValidate! && allUserrProgects[indexPath.row].mark! != 0{ cell?.projectMark?.textColor = .green } else { cell?.projectMark?.textColor = .red } return cell! } } }
// // ContentView.swift // MeekoUI // // Created by Kyujin Cho on 7/19/19. // Copyright © 2019 Kyujin Cho. All rights reserved. // import SwiftUI struct ContentView: View { var body: some View { TabbedView { BoardList() .tabItem { Text("Boards") } .tag(0) } } } #if DEBUG struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } } #endif
// We are a way for the cosmos to know itself. -- C. Sagan import AppKit struct AppConfig { static let pathFadeDurationSeconds = CGFloat(5) static let ringColors: [NSColor] = [ NSColor(calibratedWhite: 0.2, alpha: 0.5), NSColor(calibratedWhite: 0.2, alpha: 0.4), NSColor(calibratedWhite: 0.2, alpha: 0.3), NSColor(calibratedWhite: 0.2, alpha: 0.2) ] static let ringLineWidth = CGFloat(0.1) static let ringRadiiFractions = [0.95, 0.2, 0.25, 0.4] static let rotationRateHz: Double = 0 static let simulationSpeed: Double = 0.25 static let zoomLevel = 1.0 static var screenDimensions_ = CGSize.zero static var screenDimensions: CGSize { guard let mainScreen = NSScreen.main else { preconditionFailure("You're gonna have a bad day") } if mainScreen.visibleFrame.size != screenDimensions_ { print("ContentView mainScreen \(mainScreen.frame.size), visibleFrame \(mainScreen.visibleFrame.size)") screenDimensions_ = mainScreen.visibleFrame.size } return screenDimensions_ } }
// // ContainerRefreshReducer.swift // GworldSuperOffice // // Created by 陈琪 on 2020/7/20. // Copyright © 2020 Gworld. All rights reserved. // import Foundation func refreshReducer(_ state: Bool?, action: Action) -> Bool { var state = state ?? true switch action { case let refresh as RefreshLoading: state = refresh.hasNextPage default: break } return state }
// // HomeViewController.swift // GitHubTest // // Created by bruno on 08/02/20. // Copyright © 2020 bruno. All rights reserved. // import UIKit import RxSwift import RxCocoa final class HomeViewController: BaseViewController { @IBOutlet weak var homeCollectionView: UICollectionView! @IBOutlet weak var homeFlowLayout: UICollectionViewFlowLayout! private var viewModel: HomeViewModel! private var refreshControl: UIRefreshControl! private var bottomRefreshControl: UIRefreshControl! private var dispatchGroup: DispatchGroup! private var pageCount: Int = 1 var carouselFilterHeight: CGFloat = 1 private var disposeBag: DisposeBag = DisposeBag() enum HomeSection: Int { case filter case repos static var count: Int { return 2 } } init(viewModel: HomeViewModel) { super.init(nibName: nil, bundle: nil) dispatchGroup = DispatchGroup() self.viewModel = viewModel } override func viewDidLoad() { super.viewDidLoad() viewModel.delegate = self title = "GitHub" homeCollectionView.accessibilityIdentifier = "homeCollection" setup() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) filterRepos() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setup() { registerBarButtonItems() registerCells() addRefreshControl() refreshHome() } private func filterRepos() { let indexPath = IndexPath(row: 0, section: HomeSection.filter.rawValue) if let carousel = homeCollectionView.cellForItem(at: indexPath) as? FilterCarouselCollectionViewCell { let filter: [String] = !carousel.tasks.value.isEmpty ? carousel.tasks.value.map {$0.title} : [""] viewModel.fetchFilteredRepoList(values: filter) } } private func registerBarButtonItems() { let filterButton = UIBarButtonItem(image: UIImage(named: "ICO_FILTER"), landscapeImagePhone: nil, style: .done, target: self, action: nil) filterButton.accessibilityIdentifier = "filterButton" filterButton.isAccessibilityElement = true filterButton.accessibilityTraits = UIAccessibilityTraits.button filterButton.accessibilityLabel = "Filter Button" filterButton.accessibilityHint = "Filter the list of repositories" filterButton .rx .tap .asDriver() .throttle(.seconds(2)) .drive(onNext: { [weak self] in self?.showFilters() }).disposed(by: disposeBag) filterButton.tintColor = .imBarButtonItems navigationItem.rightBarButtonItems = [ filterButton ] } private func registerCells() { homeCollectionView.register(DefaultCollectionViewCell.self) homeCollectionView.register(RepoCollectionViewCell.self) homeCollectionView.register(FilterCarouselCollectionViewCell.self) } // MARK: Add a Activity Indicator in the homeCollectionView private func addRefreshControl() { refreshControl = UIRefreshControl() bottomRefreshControl = UIRefreshControl() refreshControl.tintColor = .imActivityIndicatorPullToRefresh bottomRefreshControl.tintColor = .imActivityIndicatorPullToRefresh refreshControl.addTarget(self, action: #selector(refreshHome), for: .valueChanged) bottomRefreshControl.addTarget(self, action: #selector(fetchMoreRepos), for: .valueChanged) homeCollectionView.refreshControl = refreshControl homeCollectionView.bottomRefreshControl = bottomRefreshControl } private func requests() { dispatchGroup.enter() viewModel.requesReposList() } @objc func refreshHome() { requests() dispatchGroup.notify(queue: .main) { DispatchQueue.main.async { [weak self] in self?.pageCount = 1 self?.refreshControl.endRefreshing() self?.homeCollectionView.reloadData() NotificationCenter.default.post(name: .pullToRefresh, object: nil, userInfo: nil) } } } @objc func fetchMoreRepos() { dispatchGroup.enter() viewModel.requesReposList(in: pageCount+1) dispatchGroup.notify(queue: .main) { [weak self] in DispatchQueue.main.async { [weak self] in self?.pageCount += 1 self?.bottomRefreshControl.endRefreshing() self?.homeCollectionView.reloadData() } } } private func showFilters() { viewModel.showFilters() } @objc private func bringTextField() { } } extension HomeViewController: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { guard let selectedRepo = viewModel.getRepository(in: indexPath) else { return } viewModel.showRepoDetail(with: selectedRepo) } } extension HomeViewController: UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { return HomeSection.count } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { switch HomeSection(rawValue: section) { case .filter: return 1 case .repos: return viewModel.numberOfRepos default: return 0 } } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { switch HomeSection(rawValue: indexPath.section) { case .filter: return homeCollectionView.dequeueReusableCell(of: FilterCarouselCollectionViewCell.self, for: indexPath) { cell in cell.delegate = self } case .repos: return homeCollectionView.dequeueReusableCell(of: RepoCollectionViewCell.self, for: indexPath) { [weak self] cell in guard let repo = self?.viewModel.getRepository(in: indexPath) else { return } cell.setup(repo: repo, index: indexPath.row) } default: return homeCollectionView.dequeueReusableCell(of: DefaultCollectionViewCell.self, for: indexPath) } } } extension HomeViewController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { switch HomeSection(rawValue: indexPath.section) { case .filter: return CGSize(width: collectionView.frame.width, height: carouselFilterHeight) case .repos: return CGSize(width: collectionView.frame.width - 16, height: 155) default: return .zero } } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { switch HomeSection(rawValue: section) { case .filter: return UIEdgeInsets(top: 20, left: 0, bottom: 0, right: 0) case .repos: return UIEdgeInsets(top: 16, left: 8, bottom: 0, right: 8) default: return .zero } } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { switch HomeSection(rawValue: section) { case .filter: return .zero case .repos: return 10 default: return .zero } } } extension HomeViewController: HomeViewModelViewDelegate { func homeViewModel(_ viewModel: HomeViewModel, didFetch result: Result<Any?, IMError>) { dispatchGroup.leave() } func homeViewModelDidFinishFilter(_ viewModel: HomeViewModel) { DispatchQueue.main.async { [weak self] in self?.homeCollectionView.reloadSections(IndexSet(integer: HomeSection.repos.rawValue)) } } } extension HomeViewController: FilterCarouselCollectionViewDelegate { func performBatchUpdates(height: CGFloat) { carouselFilterHeight = height filterRepos() DispatchQueue.main.async { [weak self] in self?.homeCollectionView.performBatchUpdates(nil, completion: nil) } } }
// // FontScheme.swift // Yoga // // Created by User on 07.10.2020. // Copyright © 2020 Александр Сенин. All rights reserved. // import RelizKit enum FontType{ case bold case semiBold case extraLight case light case regular case medium func name() -> String { switch self { case .bold: return "HelveticaNeue-Bold" case .extraLight: return "NotoSans-ExtraLight" case .light: return "NotoSans-Light" case .medium: return "HelveticaNeue-Medium" case .regular: return "HelveticaNeue" case .semiBold: return "NotoSans-SemiBold" } } } extension UIFont{ class var largeTitle: UIFont {.getFont(fontType: .bold, smartSize: 26)} class var title1: UIFont {.getFont(fontType: .bold, smartSize: 22)} class var title2: UIFont {.getFont(fontType: .bold, smartSize: 18)} class var title3: UIFont {.getFont(fontType: .bold, smartSize: 16)} class var title4: UIFont {.getFont(fontType: .medium, smartSize: 16)} class var title5: UIFont {.getFont(fontType: .bold, smartSize: 12.5)} class var title5r: UIFont {.getFont(fontType: .regular, smartSize: 12.5)} class var title6: UIFont {.getFont(fontType: .regular, smartSize: 13)} class var h1: UIFont {.getFont(fontType: .semiBold, smartSize: 22)} class var headline: UIFont {.getFont(fontType: .semiBold, smartSize: 17)} class var boby: UIFont {.getFont(fontType: .regular, smartSize: 15)} class var caption: UIFont {.getFont(fontType: .regular, smartSize: 12)} static func getFont(fontType: FontType, smartSize: CGFloat) -> UIFont{ if Device.get == .mac{ return getFont(fontType: fontType, pt: smartSize) }else{ return getFont(fontType: fontType, del: 370.0 / smartSize) } } static func getFont(fontType: FontType, del: CGFloat) -> UIFont{ if Device.get == .iPad{ return getFont(fontType: fontType, pt: (RZProtoValue.screenTag(.w, .vertical) * 0.8*).getValue() / del) }else{ return getFont(fontType: fontType, pt: RZProtoValue.screenTag(.w, .vertical).getValue() / del) } } static func getFont(fontType: FontType, pt: CGFloat) -> UIFont{ return UIFont(descriptor: UIFontDescriptor(name: fontType.name(), size: 0), size: pt) } static func creatorDel(_ fontType: FontType, _ del: CGFloat) -> UIFont {.getFont(fontType: fontType, del: del)} static func creatorPT(_ fontType: FontType, _ pt: CGFloat) -> UIFont {.getFont(fontType: fontType, pt: pt)} }
import Foundation import MapKit class Message : NSObject, MKAnnotation { let text: String let latitude: Double let longitude: Double let expiry: Date? init(text: String, latitude: Double, longitude: Double) { self.text = text self.latitude = latitude self.longitude = longitude self.expiry = nil } init?(json: [String: Any]) { guard let text = json["Text"] as? String, let latitude = json["Latitude"] as? Double, let longitude = json["Longitude"] as? Double, let expiry = json["Expiry"] as? String else { return nil } self.text = text self.latitude = latitude self.longitude = longitude let dateFormatter = DateFormatter() dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") as Locale! dateFormatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.SSSSZ" self.expiry = dateFormatter.date(from: expiry)! } var coordinate: CLLocationCoordinate2D { return CLLocationCoordinate2DMake(latitude, longitude) } var title: String? { return text } }