text stringlengths 8 1.32M |
|---|
//
// FilterViewCell.swift
// Yelp
//
// Created by Mohit Taneja on 9/23/17.
// Copyright © 2017 Mohit Taneja. All rights reserved.
//
import UIKit
import SevenSwitch
enum FilterViewCellType {
case Normal
case ExpandableExpanded
case ExpandableNotExpanded
case ShowAll
case ShowAllExpanded
}
@objc protocol FilterViewCellDelegate {
@objc optional func FilterViewCell(filterViewCell: FilterViewCell, didChangeValue value:Bool)
}
class FilterViewCell: UITableViewCell {
@IBOutlet weak var filterName: UILabel!
@IBOutlet weak var expandableImageView: UIImageView!
@IBOutlet weak var seeAllLabel: UILabel!
@IBOutlet weak var switchView: UIView!
var filterSwitch: SevenSwitch = SevenSwitch()
var delegate: FilterViewCellDelegate?
var cellType: FilterViewCellType? {
didSet {
configureCellForType()
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Add tap gesture recognizer for expandable image and show all
let tapRecognizerForExpandableImageView = UITapGestureRecognizer(target: self, action: #selector(FilterViewCell.tapGestureRecognizerTapped(_:)))
tapRecognizerForExpandableImageView.cancelsTouchesInView = true;
self.addGestureRecognizer(tapRecognizerForExpandableImageView)
self.switchView.addSubview(filterSwitch)
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
// Configure the cell if its type is set/changed
func configureCellForType() {
switch self.cellType! {
case FilterViewCellType.Normal:
expandableImageView.isHidden = true
seeAllLabel.isHidden = true
filterName.isHidden = false
filterSwitch.isHidden = false
case FilterViewCellType.ExpandableNotExpanded:
expandableImageView.isHidden = false
seeAllLabel.isHidden = true
filterName.isHidden = false
filterSwitch.isHidden = true
case FilterViewCellType.ExpandableExpanded:
expandableImageView.isHidden = true
seeAllLabel.isHidden = true
filterName.isHidden = false
filterSwitch.isHidden = false
case FilterViewCellType.ShowAll:
expandableImageView.isHidden = true
seeAllLabel.isHidden = false
filterName.isHidden = true
filterSwitch.isHidden = true
case FilterViewCellType.ShowAllExpanded:
expandableImageView.isHidden = true
seeAllLabel.isHidden = true
filterName.isHidden = false
filterSwitch.isHidden = false
}
updateSwitchStyle()
}
func updateSwitchStyle() {
if (cellType == FilterViewCellType.Normal || cellType == FilterViewCellType.ExpandableExpanded) {
filterSwitch.thumbTintColor = UIColor(red: 0.69, green: 0.73, blue: 0.83, alpha: 1)
filterSwitch.activeColor = UIColor.white
filterSwitch.inactiveColor = UIColor.white
filterSwitch.onTintColor = UIColor(red: 0.85, green: 0.1, blue: 0.1, alpha: 1)
filterSwitch.borderColor = UIColor(red: 0.85, green: 0.1, blue: 0.1, alpha: 1)
filterSwitch.shadowColor = UIColor.black
filterSwitch.frame = CGRect(x: 0, y: 0, width: 60, height: 25)
}
}
@IBAction func switchValueChanged(_ sender: Any) {
delegate?.FilterViewCell?(filterViewCell: self, didChangeValue: filterSwitch.on)
}
@IBAction func tapGestureRecognizerTapped(_ sender: Any) {
if cellType == FilterViewCellType.ExpandableNotExpanded ||
cellType == FilterViewCellType.ShowAll{
delegate?.FilterViewCell?(filterViewCell: self, didChangeValue: filterSwitch.on)
}
else if cellType == FilterViewCellType.Normal ||
cellType == FilterViewCellType.ExpandableExpanded {
filterSwitch.setOn(!filterSwitch.on, animated: true)
delegate?.FilterViewCell?(filterViewCell: self, didChangeValue: filterSwitch.on)
}
}
}
|
//
// BooksChaptersVerses.swift
// CBC
//
// Created by Steve Leeke on 6/17/17.
// Copyright © 2017 Steve Leeke. All rights reserved.
//
import Foundation
class BooksChaptersVerses : Swift.Comparable {
var data:[String:[Int:[Int]]]?
func bookChaptersVerses(book:String?) -> BooksChaptersVerses?
{
guard let book = book else {
return self
}
let bcv = BooksChaptersVerses()
bcv[book] = data?[book]
// print(bcv[book])
return bcv
}
func numberOfVerses() -> Int
{
var count = 0
if let books = data?.keys.sorted(by: { bookNumberInBible($0) < bookNumberInBible($1) }) {
for book in books {
if let chapters = data?[book]?.keys.sorted() {
for chapter in chapters {
if let verses = data?[book]?[chapter] {
count += verses.count
}
}
}
}
}
return count
}
subscript(key:String) -> [Int:[Int]]? {
get {
return data?[key]
}
set {
if data == nil {
data = [String:[Int:[Int]]]()
}
data?[key] = newValue
}
}
static func ==(lhs: BooksChaptersVerses, rhs: BooksChaptersVerses) -> Bool
{
let lhsBooks = lhs.data?.keys.sorted() { bookNumberInBible($0) < bookNumberInBible($1) }
let rhsBooks = rhs.data?.keys.sorted() { bookNumberInBible($0) < bookNumberInBible($1) }
if (lhsBooks == nil) && (rhsBooks == nil) {
} else
// JUST ADDED
if (lhsBooks?.count == 0) && (rhsBooks?.count == 0) {
} else
if (lhsBooks != nil) && (rhsBooks == nil) {
return false
} else
if (lhsBooks == nil) && (rhsBooks != nil) {
return false
} else {
if lhsBooks?.count != rhsBooks?.count {
return false
} else {
// print(lhsBooks)
if let count = lhsBooks?.count {
for index in 0...(count - 1) {
if lhsBooks?[index] != rhsBooks?[index] {
return false
}
}
}
if let books = lhsBooks {
for book in books {
let lhsChapters = lhs[book]?.keys.sorted()
let rhsChapters = rhs[book]?.keys.sorted()
if (lhsChapters == nil) && (rhsChapters == nil) {
} else
if (lhsChapters != nil) && (rhsChapters == nil) {
return false
} else
if (lhsChapters == nil) && (rhsChapters != nil) {
return false
} else {
if lhsChapters?.count != rhsChapters?.count {
return false
} else {
if let count = lhsChapters?.count {
for index in 0...(count - 1) {
if lhsChapters?[index] != rhsChapters?[index] {
return false
}
}
}
if let chapters = lhsChapters {
for chapter in chapters {
let lhsVerses = lhs[book]?[chapter]?.sorted()
let rhsVerses = rhs[book]?[chapter]?.sorted()
if (lhsVerses == nil) && (rhsVerses == nil) {
} else
if (lhsVerses != nil) && (rhsVerses == nil) {
return false
} else
if (lhsVerses == nil) && (rhsVerses != nil) {
return false
} else {
if lhsVerses?.count != rhsVerses?.count {
return false
} else {
if let count = lhsVerses?.count {
for index in 0...(count - 1) {
if lhsVerses?[index] != rhsVerses?[index] {
return false
}
}
}
}
}
}
}
}
}
}
}
}
}
return true
}
static func !=(lhs: BooksChaptersVerses, rhs: BooksChaptersVerses) -> Bool
{
return !(lhs == rhs)
}
static func <=(lhs: BooksChaptersVerses, rhs: BooksChaptersVerses) -> Bool
{
return (lhs < rhs) || (lhs == rhs)
}
static func <(lhs: BooksChaptersVerses, rhs: BooksChaptersVerses) -> Bool
{
let lhsBooks = lhs.data?.keys.sorted() { bookNumberInBible($0) < bookNumberInBible($1) }
let rhsBooks = rhs.data?.keys.sorted() { bookNumberInBible($0) < bookNumberInBible($1) }
if (lhsBooks == nil) && (rhsBooks == nil) {
return false
} else
if (lhsBooks != nil) && (rhsBooks == nil) {
return false
} else
if (lhsBooks == nil) && (rhsBooks != nil) {
return true
} else {
if let lhsBooks = lhsBooks, let rhsBooks = rhsBooks {
for lhsBook in lhsBooks {
for rhsBook in rhsBooks {
if lhsBook == rhsBook {
let lhsChapters = lhs[lhsBook]?.keys.sorted()
let rhsChapters = rhs[rhsBook]?.keys.sorted()
if (lhsChapters == nil) && (rhsChapters == nil) {
return lhsBooks.count < rhsBooks.count
} else
if (lhsChapters != nil) && (rhsChapters == nil) {
return true
} else
if (lhsChapters == nil) && (rhsChapters != nil) {
return false
} else {
if let lhsChapters = lhsChapters, let rhsChapters = rhsChapters {
for lhsChapter in lhsChapters {
for rhsChapter in rhsChapters {
if lhsChapter == rhsChapter {
let lhsVerses = lhs[lhsBook]?[lhsChapter]?.sorted()
let rhsVerses = rhs[rhsBook]?[rhsChapter]?.sorted()
if (lhsVerses == nil) && (rhsVerses == nil) {
return lhsChapters.count < rhsChapters.count
} else
if (lhsVerses != nil) && (rhsVerses == nil) {
return true
} else
if (lhsVerses == nil) && (rhsVerses != nil) {
return false
} else {
if let lhsVerses = lhsVerses, let rhsVerses = rhsVerses {
for lhsVerse in lhsVerses {
for rhsVerse in rhsVerses {
if lhsVerse == rhsVerse {
return lhs.numberOfVerses() < rhs.numberOfVerses()
} else {
return lhsVerse < rhsVerse
}
}
}
}
}
} else {
return lhsChapter < rhsChapter
}
}
}
}
}
} else {
return bookNumberInBible(lhsBook) < bookNumberInBible(rhsBook)
}
}
}
}
}
return false
}
static func >=(lhs: BooksChaptersVerses, rhs: BooksChaptersVerses) -> Bool
{
return !(lhs < rhs)
}
static func >(lhs: BooksChaptersVerses, rhs: BooksChaptersVerses) -> Bool
{
return !(lhs < rhs) && !(lhs == rhs)
}
}
|
//
// FlashError.swift
// flashcards
//
// Created by Bryan Workman on 7/26/20.
// Copyright © 2020 Bryan Workman. All rights reserved.
//
import Foundation
enum FlashError: LocalizedError {
case ckError(Error)
case couldNotUnwrap
case unableToDeleteRecord
var errorDescription: String? {
switch self {
case .ckError(let error):
return "There was an error: \(error) -- \(error.localizedDescription)"
case .couldNotUnwrap:
return "There was an error unwrapping the flashfile."
case .unableToDeleteRecord:
return "There was an error deleting a record from CloudKit."
}
}
} //End of enum
|
//
// String+Extension.swift
// Remote Cam Viewer
//
// Created by Dhiraj Das on 5/13/18.
// Copyright © 2018 Dhiraj Das. All rights reserved.
//
import Foundation
extension String {
func isvalidIpAddress() -> Bool {
var sin = sockaddr_in()
var sin6 = sockaddr_in6()
if self.withCString({ cstring in inet_pton(AF_INET6, cstring, &sin6.sin6_addr) }) == 1 {
// IPv6 peer.
return true
} else if self.withCString({ cstring in inet_pton(AF_INET, cstring, &sin.sin_addr) }) == 1 {
// IPv4 peer.
return true
}
return false
}
}
|
//
// DetailCollectionViewCell.swift
// MyWeather
//
// Created by RaymonLewis on 8/16/16.
// Copyright © 2016 RaymonLewis. All rights reserved.
//
import UIKit
class DetailCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var weatherIcon: UIImageView!
@IBOutlet weak var tempLabel: UILabel!
var hourlyWeatherData : HourlyWeatherData? {
didSet {
if let time = hourlyWeatherData?.timeInHours {
self.timeLabel.text = time
}
if let temp = hourlyWeatherData?.hourlyTemperature {
let celcius = ViewController.fahrenheitToCelcius(temp)
let formattedTemp = String(format: "%.f˚", celcius)
self.tempLabel.text = formattedTemp
}
if let icon = hourlyWeatherData?.hourlyIcon {
self.weatherIcon.image = UIImage(named: icon)
}
}
}
override func awakeFromNib() {
super.awakeFromNib()
self.backgroundColor = UIColor.clearColor()
}
}
|
//
// PokemonDataSource.swift
// PokeData
//
// Created by jikichi on 2021/02/28.
//
import Foundation
import RxSwift
import RxCocoa
final class DreamOfManDataSource: NSObject, UICollectionViewDataSource, RxCollectionViewDataSourceType {
typealias Element = [Video]
private var items: Element = []
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: NSStringFromClass(AvgleSearchResultsCollectionViewCell.self), for: indexPath) as! AvgleSearchResultsCollectionViewCell
cell.viewModel = AvgleVideoViewModel(video: items[indexPath.row])
return cell
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return items.count
}
func collectionView(_ collectionView: UICollectionView, observedEvent: Event<Element>) {
Binder(self) { dataSource, items in
if dataSource.items == items { return }
dataSource.items = items
collectionView.reloadData()
}
.on(observedEvent)
}
}
extension DreamOfManDataSource: SectionedViewDataSourceType {
func model(at indexPath: IndexPath) throws -> Any {
return items[indexPath.row]
}
}
|
//
// String_Extension.swift
// WatsonDemo
//
// Created by Etay Luz on 3/22/17.
// Copyright © 2017 Etay Luz. All rights reserved.
//
import Foundation
extension String {
func dictionary() -> [String: Any]? {
if let data = self.data(using: .utf8) {
do {
return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
} catch {
print(error.localizedDescription)
}
}
return nil
}
}
|
//
// ThirdViewController.swift
// kk
//
// Created by Воробьев Александр on 5/14/20.
// Copyright © 2020 Serioga. All rights reserved.
//
import UIKit
class SettingsArr {
var settingsSections: String?
var settingsName: [String]?
init( settingsSections: String, settingsName: [String]) {
self.settingsSections = settingsSections
self.settingsName = settingsName
}
}
class SettingsViewController: UIViewController {
// - UI
@IBOutlet weak var tableView: UITableView!
@IBOutlet var backgroundView: UIView!
// - Data
var images = ["image1", "image2", "image3", "image4"]
var images1 = ["image6", "image7"]
var settingsArr = [SettingsArr]()
override func viewDidLoad() {
super.viewDidLoad()
configure()
}
}
//MARK: -
//MARK: - TableView Delegate
extension SettingsViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 43
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 40
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if (indexPath.section == 2 ) && (indexPath.row == 1){
let vcc = UIStoryboard(name: "Restore", bundle: nil).instantiateViewController(withIdentifier: "RestoreViewController") as! RestoreViewController
vcc.modalPresentationStyle = .overFullScreen
self.present(vcc, animated: true, completion: nil)
}else {
}
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let view = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 40))
view.backgroundColor = .clear
let lbl = UILabel(frame: CGRect(x: 0, y: 0, width: view.frame.width - 15, height: 40))
lbl.font = UIFont.systemFont(ofSize: 20)
lbl.textColor = #colorLiteral(red: 0.6312749386, green: 0.9386207461, blue: 0.05994417518, alpha: 1)
lbl.text = settingsArr[section].settingsSections
view.addSubview(lbl)
return view
}
}
//MARK: -
//MARK: - TableView Data Source
extension SettingsViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return settingsArr.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return settingsArr[section].settingsName?.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ThirdTableViewCell", for: indexPath) as! ThirdTableViewCell
cell.settingsLabel.text = settingsArr[indexPath.section].settingsName?[indexPath.row]
if(indexPath.section == 0 ) {
cell.settingsImage.image = UIImage(named: images[indexPath.row])
}else if(indexPath.section == 1) {
cell.settingsImage.image = UIImage(named: "image5")
}else {
cell.settingsImage.image = UIImage(named: images1[indexPath.row])
}
return cell
}
}
//MARK: -
//MARK: - Configure
private extension SettingsViewController {
func configure() {
configureSettingsArr()
configureTableView()
configureBackgroundView()
}
func configureSettingsArr() {
settingsArr.append(SettingsArr.init(settingsSections: "MAIN", settingsName: ["Smart Autoconnect", "Terms of Use", "Privacy Policy", "Support"]))
settingsArr.append(SettingsArr.init(settingsSections: "APP", settingsName: ["Rate app"]))
settingsArr.append(SettingsArr.init(settingsSections: "SUBSCRIPTION", settingsName: ["Subscription Plans", "Restore"]))
}
func configureTableView() {
tableView.delegate = self
tableView.dataSource = self
}
func configureBackgroundView() {
backgroundView.setGradientBackground(colorOne: #colorLiteral(red: 0.3861683309, green: 0.431995213, blue: 0.5937667489, alpha: 1), colorTwo: #colorLiteral(red: 0.1782957613, green: 0.220055908, blue: 0.3693865538, alpha: 1))
}
}
|
//
// SearchFilmInputs.swift
// Liste
//
// Created by Thomas on 27/06/2021.
//
import Foundation
struct SearchFilmInputs {
let searchFilm: SearchFilmServicing
init(searchFilm: SearchFilmServicing) {
self.searchFilm = searchFilm
}
}
|
//
// COUserProfileModel.swift
// CoAssetsApps
//
// Created by Nikmesoft_M008 on 08/03/2016.
// Copyright © 2016 TruongVO07. All rights reserved.
//
import UIKit
import SwiftyJSON
class COUserProfileModel: NSObject {
var email = ""
var lastName = ""
var tokens: COUserProfileTokensModel?
var firstName = ""
var userName = ""
var userProfileId = 0
var account: COUserProfileAccountModel?
var profile: COUserProfileDetailModel?
}
//MARK: - ImportData
extension COUserProfileModel {
func importJsonData(jsonData: JSON) {
if let temp = jsonData[ServiceDefine.UserProfileField.Email].string {
self.email = temp
}
if let temp = jsonData[ServiceDefine.UserProfileField.LastName].string {
self.lastName = temp
}
if let _ = jsonData[ServiceDefine.UserProfileField.Tokens].dictionary {
let tokenObject = COUserProfileTokensModel()
tokenObject.importJsonData(jsonData[ServiceDefine.UserProfileField.Tokens])
self.tokens = tokenObject
}
if let temp = jsonData[ServiceDefine.UserProfileField.FirstName].string {
self.firstName = temp
}
if let temp = jsonData[ServiceDefine.UserProfileField.UserName].string {
self.userName = temp
}
if jsonData[ServiceDefine.UserProfileField.UserProfileId].isExists() {
self.userProfileId = jsonData[ServiceDefine.UserProfileField.UserProfileId].intValue
}
if let _ = jsonData[ServiceDefine.UserProfileField.Account].dictionary {
let accountObject = COUserProfileAccountModel()
accountObject.importJsonData(jsonData[ServiceDefine.UserProfileField.Account])
self.account = accountObject
}
if let _ = jsonData[ServiceDefine.UserProfileField.Profile].dictionary {
let profileObject = COUserProfileDetailModel()
profileObject.importJsonData(jsonData[ServiceDefine.UserProfileField.Profile])
self.profile = profileObject
}
}
}
|
//
// ViewController.swift
// Portefeuille
//
// Created by Jesus Enrique Nava Sanchez on 30/11/2018.
// Copyright © 2018 Jesus Enrique Nava Sanchez. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var table: UITableView!
@IBOutlet weak var dPicker: UIDatePicker!
@IBOutlet weak var label: UILabel!
@IBOutlet weak var inputTextField: UITextField!
private var datePicker:UIDatePicker?
override func viewDidLoad() {
super.viewDidLoad()
dPicker.addTarget(self, action: #selector(ViewController.dateChange(datepicker:)), for: .valueChanged)
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(ViewController.viewTapped(gestureRecognizer:)))
view.addGestureRecognizer(tapGesture)
self.view.addSubview(dPicker)
label.textAlignment = NSTextAlignment.center
label.textColor = UIColor.black
label.text = "500,00 €"
label.adjustsFontSizeToFitWidth = true
self.view.addSubview(label)
// Do any additional setup after loading the view, typically from a nib.
}
@objc func viewTapped(gestureRecognizer: UITapGestureRecognizer)
{
}
@objc func dateChange(datepicker: UIDatePicker)
{
label.text = "holaaaaa"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
//
// ViewController.swift
// ToDo
//
// Created by Apurva Patel on 4/10/18.
// Copyright © 2018 Apurva Patel. All rights reserved.
//
import UIKit
import RealmSwift
import ChameleonFramework
class TodoListViewController: SwipeTableViewController{
var todoItem : Results<Item>?
let realm = try! Realm ()
var selectedCategory : Category? {
didSet {
loadItems()
}
}
@IBOutlet weak var searchBar: UISearchBar!
override func viewDidLoad() {
super.viewDidLoad()
tableView.separatorStyle = .none
// Do any additional setup after loading the view, typically from a nib.
}
override func viewWillAppear(_ animated: Bool) {
title = selectedCategory?.name
guard let colorHex = selectedCategory?.color else { fatalError()}
updateNavbar(withHexCode: colorHex)
}
// override func viewWillDisappear(_ animated: Bool) {
// updateNavbar(withHexCode: "1D9BF6")
// }
override func willMove(toParentViewController parent: UIViewController?) {
updateNavbar(withHexCode: "1D9BF6")
}
//MARK - Nav bar set up
func updateNavbar (withHexCode colorHex : String){
guard let navBar = navigationController?.navigationBar else { fatalError("Navigation Controller doest not exit.") }
guard let navBarColor = UIColor(hexString: colorHex) else { fatalError() }
navBar.barTintColor = navBarColor
navBar.tintColor = ContrastColorOf(navBarColor, returnFlat: true)
navBar.largeTitleTextAttributes = [NSAttributedStringKey.foregroundColor : ContrastColorOf(navBarColor, returnFlat: true)]
searchBar.barTintColor = navBarColor
}
//MARK - Tableview Datasource Methods
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return todoItem?.count ?? 1
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//let cell = tableView.dequeueReusableCell(withIdentifier: "ToDoItemCell", for: indexPath)
let cell = super.tableView(tableView, cellForRowAt: indexPath)
if let item = todoItem?[indexPath.row] {
cell.textLabel?.text = item.title
if let color = UIColor(hexString: selectedCategory!.color)?.darken(byPercentage: CGFloat(CGFloat(indexPath.row) / CGFloat(todoItem!.count))) {
cell.backgroundColor = color
cell.textLabel?.textColor = ContrastColorOf(color, returnFlat: true)
}
cell.accessoryType = item.done ? .checkmark : .none
} else {
cell.textLabel?.text = "No items added"
}
return cell
}
//MARK - Tableview Delegate Methods
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let item = todoItem?[indexPath.row] {
do {
try realm.write {
item.done = !item.done
}
} catch{
print ("Error updating items \(error)")
}
}
tableView.reloadData()
tableView.deselectRow(at: indexPath, animated: true)
}
//MARK - Add new items
@IBAction func addButtonPressed(_ sender: UIBarButtonItem) {
var textField = UITextField()
let alert = UIAlertController(title: "Add new to item", message: "", preferredStyle: .alert)
let action = UIAlertAction(title: "Add item", style: .default) { (action) in
if let currentCategoty = self.selectedCategory {
do {
try self.realm.write {
let newItem = Item()
newItem.title = textField.text!
newItem.dateCreated = Date()
currentCategoty.items.append(newItem)
}
} catch {
print ("Error saving data \(error)")
}
}
self.tableView.reloadData()
}
alert.addTextField { (alertTextfield) in
alertTextfield.placeholder = "Create new item"
textField = alertTextfield
}
alert.addAction(action)
present(alert, animated: true, completion: nil)
}
//MARK - Model Manupulation Methods
func loadItems () {
todoItem = selectedCategory?.items.sorted(byKeyPath: "title", ascending: true)
tableView.reloadData()
}
//MARK - Swipe Item deletation
override func updateModel(at indexPath: IndexPath) {
if let deleteData = self.todoItem?[indexPath.row] {
do {
try self.realm.write {
self.realm.delete(deleteData)
}
}catch {
print ("Error deleting data \(error)")
}
}
}
}
//MARK: - Search bar methods
extension TodoListViewController : UISearchBarDelegate {
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
todoItem = todoItem?.filter(NSPredicate(format: "title CONTAINS[cd] %@", searchBar.text!)).sorted(byKeyPath: "dateCreated", ascending: true)
tableView.reloadData()
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchBar.text?.count == 0 {
loadItems()
DispatchQueue.main.async {
searchBar.resignFirstResponder()
}
}
}
}
|
//
// FirstViewController.swift
// CombineMobileSpielplatz
//
// Created by Dimitri Brukakis on 31.05.20.
// Copyright © 2020 Dimitri Brukakis. All rights reserved.
//
import UIKit
import Combine
class FirstViewController: UIViewController {
// MARK: - Combine
private var subscribers = Set<AnyCancellable>()
private weak var subscriber: AnyCancellable?
// MARK: - Output text view
@IBOutlet private weak var textView: UITextView?
// MARK: - Resource provider
@IBOutlet private weak var userTextField: UITextField?
// ---------------------------------------------------------------------
// MARK: - Resourcce provider
@IBAction func onCombineUser(_ sender: Any) {
subscriber?.cancel()
subscriber = nil
guard let user = userTextField?.text else { return }
textView?.text = ""
ResourceProvider(resource: user, withExtension: "json")
.publisher
.decode(type: User.self, decoder: JSONDecoder())
// .print()
// .replaceError(with: User(email: "nobody@nowhere.com", name: "Nobody Knows"))
.sink(
receiveCompletion: { (error) in self.textView?.text.append("Received error: \(error)") },
receiveValue: { (user) in self.textView?.text.append("\(user.name) => \(user.email)") }
)
.store(in: &subscribers)
}
@IBAction func onCombineAllUsers(_ sender: Any) {
textView?.text = ""
["user1", "user2", "user3"].publisher
.setFailureType(to: ResourceProvider.ResourcePublisher.Failure.self)
.flatMap { (resource) in
return ResourceProvider(resource: resource, withExtension: "json").publisher
}
.decode(type: User.self, decoder: JSONDecoder())
.replaceError(with: User(email: "nobody@nowhere.com", name: "Nobody Knows"))
.sink(receiveCompletion: { (error) in self.textView?.text.append("Error: \(error)") },
receiveValue: { (user) in
self.textView?.text.append("Found: \(user.email) -> \(user.name)\n")
})
.store(in: &subscribers)
}
// ---------------------------------------------------------------------
// ---------------------------------------------------------------------
// MARK: - Slider & Progress w/ PassThroughSubject
let sliderPassThroughSubject = PassthroughSubject<Float, Never>()
@IBOutlet private weak var slider: UISlider? {
didSet {
slider?.minimumValue = 0
slider?.maximumValue = 50000
slider?.value = 0
}
}
@IBOutlet private weak var sliderProgress: UIProgressView? {
didSet {
sliderProgress?.progress = 0
}
}
@IBAction func onSliderChangeValue(_ slider: UISlider) {
sliderPassThroughSubject.send(slider.value)
}
private func setupSliderProgress() {
sliderPassThroughSubject
.map {
guard let slider = self.slider else { return nil }
return Float((1 / slider.maximumValue) * $0)
}
.replaceNil(with: 0)
.assign(to: \.progress, on: sliderProgress!)
.store(in: &subscribers)
sliderPassThroughSubject
.debounce(for: 1, scheduler: DispatchQueue.main)
.map { "Neuer wert: \($0)" }
.sink { (wert) in
self.textView?.text = wert
}.store(in: &subscribers)
}
// ---------------------------------------------------------------------
// MARK: - Life cycle
override func viewDidLoad() {
super.viewDidLoad()
setupSliderProgress()
// Do any additional setup after loading the view.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
|
//
// AtlethIconSmall.swift
// SportSpot
//
// Created by Денис Мусатов on 16.11.2020.
//
import SwiftUI
struct AtlethIconSmall: View {
@State var isOnline: Bool
var body: some View {
ZStack {
Image("tempSportsman")
.resizable()
.scaledToFill()
.clipShape(Circle())
.frame(width: 50, height: 50)
Circle()
.frame(width: 12, height: 12)
.overlay(Circle().stroke(lineWidth: 1).foregroundColor(.white))
.foregroundColor(isOnline ? .green : .captionGrey)
.offset(x: 20, y: -20)
}
}
}
struct AtlethIconSmall_Previews: PreviewProvider {
static var previews: some View {
AtlethIconSmall(isOnline: true)
}
}
|
//
// AVDebugger.swift
// AVSQLDebugger
//
// Created by Umesh on 01/04/19.
// Copyright © 2019 Umesh. All rights reserved.
//
import Foundation
import Criollo
public class AVDebugger : NSObject, CRServerDelegate {
var server: CRHTTPServer!
weak var delegate: AVDebuggerProtocol? = nil
private var _port: UInt?
/*
* Port For App Server Run
*/
public var portNumber:UInt {
get {
return _port ?? 10781
}
set {
_port = newValue
}
}
private var name: String?
/*
* DB Container name
*/
public var containerName: String {
return name ?? ""
}
public static var sharedInstance: AVDebugger = {
let instance = AVDebugger()
return instance
}()
private override init() {}
public func config(with delegate: AVDebuggerProtocol, containerName: String, port: UInt = 10781) {
self.delegate = delegate
self.name = containerName
self._port = port
self.server = CRHTTPServer(delegate:self)
setMountsUrls()
setUpUrls()
do {
try checkStatus()
}catch let err {
print(err)
}
}
private var dataDic : Dictionary<String,String> {
return [
"index": "html",
"app" : "js",
"jquery.min" : "js",
"bootstrap.min": "js",
"dataTables.altEditor.free": "js",
"dataTables.buttons.min" : "js",
"dataTables.select.min" : "js",
"dataTables.responsive.min" : "js",
"custom" : "css",
"jquery.dataTables.min" : "css",
"buttons.dataTables.min" : "css",
"select.dataTables.min" : "css",
"responsive.dataTables.min" : "css",
"jquery.dataTables.min_" : "js",
"bootstrap.min_" : "css"
]
}
private func getFilepath(name:String, type:String = "js") -> String {
guard let path = Bundle(for: AVDebugger.self).path(forResource: name, ofType: type) else {
return ""
}
return path
}
private func setMountsUrls(){
for (key,value) in dataDic {
server.mount("/\(key.removeUnderScore()).\(value)",
fileAtPath:
getFilepath(name: key.removeUnderScore(), type: value))
}
}
private func setUpUrls(){
self.server.add("/getDBTableList", viewController: GetDBViewController.self, withNibName: String(describing: GetDBViewController.self), bundle: Bundle(for: AVDebugger.self))
self.server.add("/getAllDataFromTheTable/:pid", viewController: GetTableDataViewController.self, withNibName: String(describing: GetTableDataViewController.self), bundle: Bundle(for: AVDebugger.self))
self.server.add("/query/:pid", viewController: QueryDBViewController.self, withNibName: String(describing: QueryDBViewController.self), bundle: Bundle(for: AVDebugger.self))
}
}
|
//
// ListMemesViewController.swift
// MeMeShare
//
// Created by Kavya Joshi on 7/13/21.
//
import UIKit
class ListMemesViewController: UITableViewController {
var myMemes = ((UIApplication.shared.delegate) as! AppDelegate).memes
//Check for updated data every time the view appears
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
myMemes = ((UIApplication.shared.delegate) as! AppDelegate).memes
tableView.reloadData()
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return myMemes.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ListCell", for: indexPath) as! ListMemesViewCell
cell.listImageView.image = myMemes[indexPath.row].memeImage
cell.labelView.text = myMemes[indexPath.row].topText + " " + myMemes[indexPath.row].bottomText
// Configure the cell...
return cell
}
//When a row is selected from the List View
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let dvc = self.storyboard?.instantiateViewController(withIdentifier: "ListMemesDetail") as! DetailViewController
dvc.mydetailImage = myMemes[indexPath.row].memeImage
navigationController!.pushViewController(dvc, animated: true)
}
}
|
//
// Understanding_SwiftUI_DSL_App.swift
// SwiftUI_DSL
//
// Created by Geri Borbás on 2020. 06. 26..
//
import SwiftUI
@main
struct Understanding_SwiftUI_DSL_App: App {
var body: some Scene {
WindowGroup { ViewBuilder_extension() }
}
}
|
import Foundation
public final class LoginScreenAssembly {
public static func assembly(
with view: LoginScreenViewController,
moduleOutput: LoginScreenModuleOutput? = nil
) {
let loginScreenPresenter = LoginScreenPresenter()
let loginScreenInteractor = LoginScreenInteractor()
view.eventHandler = loginScreenPresenter
loginScreenPresenter.view = view
loginScreenPresenter.interactor = loginScreenInteractor
loginScreenPresenter.moduleOutput = moduleOutput
loginScreenInteractor.output = loginScreenPresenter
}
}
|
//
// Created by Daniel Heredia on 2/27/18.
// Copyright © 2018 Daniel Heredia. All rights reserved.
//
import Foundation
var elements = [9,0,12,2,3,1,5,6,8,7,11,10,4]
for i in 1..<elements.count {
let key = elements[i]
var j = i - 1
while j >= 0 && key < elements[j] {
elements[j + 1] = elements[j]
j -= 1
}
elements[j + 1] = key
}
print("Sorted elements \(elements)")
|
//
// NewViewController.swift
// SCORe1
//
// Created by C Manolas on 10/08/2017.
// Copyright © 2017 C Manolas. All rights reserved.
//
import UIKit
import AVFoundation
class UnitsController: UIViewController {
var audioPlayer = AVAudioPlayer()
@IBOutlet weak var imgHome: UIImageView!
@IBOutlet weak var imgGin: UIImageView!
@IBOutlet weak var imgHalfPint: UIImageView!
@IBOutlet weak var imgWine: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func playSND (sndName: String, sndTYP: String) {
do {
audioPlayer = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: sndName, ofType: sndTYP)!))
audioPlayer.numberOfLoops = -1
audioPlayer.prepareToPlay()
audioPlayer.currentTime = 0
audioPlayer.play()
}
catch {
print(error)
}
}
func stopSND () {
if audioPlayer.isPlaying {
audioPlayer.stop()
}
}
func animateIMG (img: UIImageView, pic1: String, pic2: String){
img.animationImages = [
UIImage(named: pic1)!,
UIImage(named: pic2)!
]
img.animationDuration = 2
img.startAnimating()
}
func stopIMG (img: UIImageView){
img.stopAnimating()
}
@IBAction func btnGin(_ sender: UIButton) {
imgHome.alpha = 0.0
imgGin.alpha = 1.0
playSND(sndName: "1_Gin", sndTYP: "wav")
}
@IBAction func btnGinRelease(_ sender: Any) {
imgHome.alpha = 1.0
imgGin.alpha = 0.0
stopSND()
}
@IBAction func btnHalfPint(_ sender: Any) {
imgHome.alpha = 0.0
imgHalfPint.alpha = 1.0
playSND(sndName: "1_5_Lager", sndTYP: "wav")
}
@IBAction func btnHalfPintRelease(_ sender: Any) {
imgHome.alpha = 1.0
imgHalfPint.alpha = 0.0
stopSND()
}
@IBAction func btnWine(_ sender: Any) {
imgHome.alpha = 0.0
imgWine.alpha = 1.0
playSND(sndName: "1_6_Wine", sndTYP: "wav")
}
@IBAction func btnWineRelease(_ sender: Any) {
imgHome.alpha = 1.0
imgWine.alpha = 0.0
stopSND()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
//: [Previous](@previous)
import Foundation
protocol Employee {
var name: String { get set }
var jobTitle: String { get set }
func doWork()
}
struct Executive: Employee {
var name = "Steve Jobs"
var jobTitle = "CEO"
func doWork() {
print("I'm strategizing!")
}
}
struct Manager: Employee {
var name = "Maurice Moss"
var jobTitle = "Head of IT"
func doWork() {
print("I'm turning it off and on again.")
}
}
let staff: [Employee] = [Executive(), Manager()]
for person in staff {
person.doWork()
}
//: [Next](@next)
|
//
// view2ViewController.swift
// deleget01
//
// Created by Mac on 3/22/19.
// Copyright © 2019 anh vu. All rights reserved.
//
import UIKit
class ViewController: UIViewController, Delegate {
@IBOutlet weak var textLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let detination = segue.destination as? View1Controller else { return }
detination.delegate = self
}
func duSomeThing(with dada: String) {
textLabel.text = dada
}
}
|
//
// HomeViewController.swift
// SideMenuHUB
//
// Created by Daniel Yo on 12/17/17.
// Copyright © 2017 Daniel Yo. All rights reserved.
// This is the base view for all the app that needs the functionality of the swRevealViewController
import UIKit
import SWRevealViewController
class HomeViewController: BaseViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.setupView()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK:Private methods
private func setupView() {
}
}
|
public extension MultiDimentionalArray {
var count: Int {
switch self {
case .val(_):
return 1
case .ary(let a):
return a.count
}
}
var flatCount: Int {
switch self {
case .val(_):
return 1
case .ary(let a):
return a.map(\.flatCount).reduce(0, +)
}
}
var depth: Int {
switch self {
case .val(_):
return 0
case .ary(let a):
return (a.map(\.depth).max() ?? 0) + 1
}
}
var flatten: Self {
flatMap(Self.val)
}
var flattenArray: [T] {
flatten.map { [$0] }.reduce([], +)
}
}
|
//
// Created by zh on 2021/6/28.
//
import Alamofire
public protocol BrickService {
var baseURL: String { get }
var path: String { get }
var method: HTTPMethod { get }
var parameters: Parameters { get }
var encoding: ParameterEncoding { get }
var headers: HTTPHeaders? { get }
var timeout: TimeInterval { get }
}
|
//
// ViewController.swift
// DropdownTableView
//
// Created by Quynh on 3/6/20.
// Copyright © 2020 Quynh. All rights reserved.
//
import UIKit
class ViewController: UIViewController, DropDownDelegate {
@IBOutlet weak var buttonSelect: UIButton!
var buttonFrame: CGRect?
var dropDownObject: DropDown!
var arrayName: [String] = ["Edit","Love","Music","Location"]
let imageArray = ["1","2","3","4"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
buttonFrame = buttonSelect.frame
}
@IBAction func onShowMenu(_ sender: UIButton) {
if dropDownObject == nil {
dropDownObject = DropDown()
dropDownObject.dropDelegate = self
dropDownObject.showDropDown(senderObject: buttonSelect, height: 150, arrayList: arrayName, arrayImages: imageArray, buttonFrame: buttonFrame!, direction : "down")
view.addSubview(dropDownObject)
} else {
dropDownObject.hideDropDown(senderObject: buttonSelect,buttonFrame:buttonFrame!)
dropDownObject = nil
}
}
func recievedSelectedValue(name: String, imageName: String) {
dropDownObject.hideDropDown(senderObject: buttonSelect, buttonFrame: buttonFrame!)
dropDownObject = nil
buttonSelect.setTitle(name, for: .normal)
var imageView : UIImageView?
imageView = UIImageView(image: UIImage(named:imageName))
imageView?.frame = CGRect(x: 20, y: 5, width: 25, height: 25)
buttonSelect.addSubview(imageView!)
}
}
|
import XCTest
protocol TabBar {
func goToInbox() -> InboxPage
func gotoSearchPage() -> SearchPage
func gotoBookmarksPage() -> BookmarksPage
func gotoSettingsPage() -> SettingsPage
}
extension TabBar {
private var inboxButton: XCUIElement {
return Page.app.buttons[AccessibilityIds.inboxTabBarItem.rawValue].firstMatch
}
private var searchButton: XCUIElement {
return Page.app.buttons[AccessibilityIds.searchTabBarItem.rawValue].firstMatch
}
private var bookmarksButton: XCUIElement {
return Page.app.buttons[AccessibilityIds.bookmarksTabBarItem.rawValue].firstMatch
}
private var settingsButton: XCUIElement {
return Page.app.buttons[AccessibilityIds.settingsTabBarItem.rawValue].firstMatch
}
@discardableResult
func goToInbox() -> InboxPage {
inboxButton.tap()
return InboxPage()
}
@discardableResult
func gotoSearchPage() -> SearchPage {
searchButton.tap()
return SearchPage()
}
@discardableResult
func gotoBookmarksPage() -> BookmarksPage {
bookmarksButton.tap()
return BookmarksPage()
}
@discardableResult
func gotoSettingsPage() -> SettingsPage {
settingsButton.tap()
return SettingsPage()
}
}
|
import Foundation
/// Creates a new type that is used to represent error information in Swift.
///
/// This is a new Swift-specific error type used to return error information. The primary usage of this object is to
/// return it as a `Failable` or `FailableOf<T>` from function that could fail.
///
/// Example:
/// `func readContentsOfFileAtPath(path: String) -> Failable<String>`
///
public struct Error {
public typealias ErrorInfoDictionary = [String:String]
/// The error code used to differentiate between various error states.
public let code: Int
/// A string that is used to group errors into related error buckets.
public let domain: String
/// A place to store any custom information that needs to be passed along with the error instance.
public let userInfo: ErrorInfoDictionary
/// Initializes a new `Error` instance.
public init(code: Int, domain: String, userInfo: ErrorInfoDictionary?) {
self.code = code
self.domain = domain
if let info = userInfo {
self.userInfo = info
}
else {
self.userInfo = ErrorInfoDictionary()
}
}
}
/// The standard keys used in `Error` and `userInfo`.
public struct ErrorKeys {
private init() {}
public static let LocalizedDescription = "NSLocalizedDescription"
public static let LocalizedFailureReason = "NSLoclalizedFailureReason"
public static let LocalizedRecoverySuggestion = "NSLocalizedRecoverySuggestion"
public static let LocalizedRecoveryOptions = "NSLocalizedRecoveryOptions"
public static let RecoveryAttempter = "NSRecoveryAttempter"
public static let HelpAnchor = "NSHelpAnchor"
public static let StringEncoding = "NSStringEncoding"
public static let URL = "NSURL"
public static let FilePath = "NSFilePath"
}
extension Error {
/// An initializer that is to be used within your own applications and libraries to hide any of the
/// ObjC interfaces from your purely Swift APIs.
public init(_ error: NSErrorPointer) {
if let memory = error.memory {
self.code = memory.code
self.domain = memory.domain
// TODO: Only supports pulling out one key at the moment, more will come later...
if let info = memory.userInfo {
self.userInfo = ErrorInfoDictionary()
if let localizedDescription = info[NSLocalizedDescriptionKey] as? NSString {
self.userInfo[ErrorKeys.LocalizedDescription] = localizedDescription
}
}
else {
self.userInfo = ErrorInfoDictionary()
}
}
else {
self.code = 0
self.domain = ""
self.userInfo = ErrorInfoDictionary()
}
}
}
extension Error: Printable {
public var description: String {
return "an error..."
}
} |
//
// ContentCollectionView.swift
// Jokes
//
// Created by Кирилл on 25.04.2020.
// Copyright © 2020 Кирилл. All rights reserved.
//
import UIKit
protocol ContentCollectionView {
var contentCollectionView: UICollectionView! { get }
}
|
//
// ManualMockingTests.swift
// ManualMockingTests
//
// Created by akio0911 on 2016/03/26.
// Copyright © 2016年 akio0911. All rights reserved.
//
//Manual Mocking in Swift - iOS Unit Testing
//http://iosunittesting.com/manual-mocking-swift/
import XCTest
@testable import ManualMocking
class ManualMockingTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testDataManager2_Test1() {
struct Manager : FileManagerProtocol2 {
func fileExistsAtPath(path: String) -> Bool {
return path == "XXX"
}
}
DataManager2.fileManager = Manager()
XCTAssertEqual(DataManager2.isExistFile("XXX"), true)
}
func testDataManager2_Test2() {
struct Manager : FileManagerProtocol2 {
func fileExistsAtPath(path: String) -> Bool {
return path == "YYY"
}
}
DataManager2.fileManager = Manager()
XCTAssertEqual(DataManager2.isExistFile("XXX"), false)
}
func testDataManager3_Test1() {
struct Manager : FileManagerProtocol3 {
func isExists(path: String) -> Bool {
return path == "XXX"
}
}
DataManager3.fileManager = Manager()
XCTAssertEqual(DataManager3.isExists("XXX"), true)
}
func testDataManager3_Test2() {
struct Manager : FileManagerProtocol3 {
func isExists(path: String) -> Bool {
return path == "YYY"
}
}
DataManager3.fileManager = Manager()
XCTAssertEqual(DataManager3.isExists("XXX"), false)
}
func testDataManager4_Test1() {
class CustomManager : DataManager4 {
override class func fileExistsAtPath(path: String) -> Bool {
return path == "XXX"
}
}
XCTAssertEqual(CustomManager.isExists("XXX"), true)
}
func testDataManager4_Test2() {
class CustomManager : DataManager4 {
override class func fileExistsAtPath(path: String) -> Bool {
return path == "YYY"
}
}
XCTAssertEqual(CustomManager.isExists("XXX"), false)
}
}
|
//
// HillClimbingAlgo.swift
// AdventOfCode
//
// Created by Shawn Veader on 12/12/22.
//
import Foundation
import OrderedCollections
class HillClimbingAlgo {
let start: Coordinate
let end: Coordinate
let map: GridMap<Character>
private var ascentHistory: [Coordinate: [Coordinate]]
init(_ input: String) {
var startCoordinate: Coordinate?
var endCoordinate: Coordinate?
let lines = input.split(separator: "\n").map(String.init)
let mapData = lines.enumerated().map { y, line -> [Character] in
line.enumerated().map { x, char -> Character in
var c = char
if char == "S" {
startCoordinate = Coordinate(x: x, y: y)
c = Character("a")
} else if char == "E" {
endCoordinate = Coordinate(x: x, y: y)
c = Character("z")
}
return c // Int(c.asciiValue ?? 0)
}
}
self.start = startCoordinate ?? Coordinate.origin
self.end = endCoordinate ?? Coordinate.origin
self.map = GridMap(items: mapData)
self.ascentHistory = [:]
}
/// Find all of the lowest points on the map.
func lowestPoints() -> [Coordinate] {
map.filter(by: { $1 == Character("a") })
}
/// Find the shortest possible path from any of the lowest points to the end
func shortestRoute() -> [Coordinate]? {
let lowestPoints = self.lowestPoints()
let bestRoutes = lowestPoints.map {
climb(start: $0)
}.filter { !$0.isEmpty }
return bestRoutes.sorted(by: { $0.count < $1.count }).first
}
/// Climb the terrain starting at our start coordinate and finding the shortest path to the end coordinate.
/// - Parameters:
/// - start: `Coordinate` to originate the search from. Defaults to `start`
func climb(start startingCoordinate: Coordinate? = nil) -> [Coordinate] {
ascentHistory = [:] // clear the history
var coordinatesToCheck = OrderedSet<Coordinate>()
// setup
let coord = startingCoordinate ?? start
coordinatesToCheck.append(coord)
saveHistory(for: coord, path: [coord])
while !coordinatesToCheck.isEmpty {
// pull first one off the ordered set to process
let coordinate = coordinatesToCheck.removeFirst()
let adjacent = ascend(to: coordinate)
// push valid adjacent coordinates into the set of ones to check
coordinatesToCheck.append(contentsOf: adjacent)
}
let finalPath = ascentHistory[end]
return finalPath ?? []
}
/// Ascend to the given coordinate and determine what possible options there are to go from here.
/// - Note: Using a bit of BFS (breadth first search) tactics to scan
private func ascend(to coordinate: Coordinate) -> [Coordinate] {
let path = ascentHistory[coordinate] ?? []
// see if we reached the end
guard coordinate != end else { return [] }
// determine the value at the current coordinate to help filter adjacent spaces
let sourceValue = value(at: coordinate)
let possibleRange = 0...(sourceValue + 1) // possible values are anything lower than +1 of the current pont
// find adjacent spaces and filter based on points not traveled and proper values
let adjacent = map.adjacentCoordinates(to: coordinate, allowDiagonals: false)
.filter { !path.contains($0) } // filter any that are already in our path (no back-tracking)
.filter { possibleRange.contains(value(at: $0)) } // filter based on height (+/- 1)
.filter { point in
let pointPath = path + [point]
if historySize(at: point) > pointPath.count {
saveHistory(for: point, path: pointPath)
return true
} else {
return false // shorter path already considered to this place
}
}
// .sorted(by: { value(at: $0) > value(at: $1) }) // prioritize going up
return adjacent
}
private func historySize(at coordinate: Coordinate) -> Int {
guard let path = ascentHistory[coordinate] else { return Int.max }
return path.count
}
private func saveHistory(for coordinate: Coordinate, path: [Coordinate]) {
ascentHistory[coordinate] = path
}
private func value(at coordinate: Coordinate) -> Int {
Int(map.item(at: coordinate)?.asciiValue ?? 0)
}
}
|
import Foundation
enum Forecast {
case Hot
case Cold
case Fair
case Snow
}
func getForecastFromServer () ->Forecast? {
return nil
}
let currentWeather = getForecastFromServer()
switch currentWeather ?? .Snow {
case .Cold :
print("Keep in the House ")
case .Fair :
print("Call the Emergency")
case .Hot :
print("Drink Water ")
case .Snow :
print("No Values")
}
func Fair() -> Forecast? {
return Forecast.Fair
}
|
//
// ConvertRequest.swift
// CurrencyConverter
//
// Created by Jan Bjelicic on 09/03/2021.
//
import Foundation
struct ConvertRequest: Encodable {
let from: String
let to: String
let amount: Float
}
extension ConvertRequest: NetworkRequest {
var path: String {
"fx-rates"
}
var method: HttpVerb {
.get
}
var parameters: [String: Any]? {
jsonObject
}
}
|
//
// CollectViewController.swift
// TractorApp
//
// Created by BillBo on 2018/8/23.
// Copyright © 2018年 BillBo. All rights reserved.
//
import UIKit
class CollectViewController: BaseViewController {
var tractorListVC:TractorListViewController!
override func viewDidLoad() {
super.viewDidLoad()
self.title = "收藏"
tractorListVC = TractorListViewController.init(type: .Collect)
tractorListVC.getCellClick {[weak self] args in
self?.view.backgroundColor = .white
}
self.addChildViewController(tractorListVC)
self.view.addSubview(tractorListVC.view)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
tractorListVC.view.frame = self.view.bounds
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
|
//
// UIViewExtension.swift
// Pham-Photo
//
// Created by Colin Smith on 7/23/19.
// Copyright © 2019 Colin Smith. All rights reserved.
//
import UIKit
extension UIViewController {
func presentSimpleAlertWith(title: String, message: String?) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let okayAction = UIAlertAction(title: "Okay", style: .cancel, handler: nil)
alertController.addAction(okayAction)
present(alertController, animated: true)
}
}
|
//
// UIViewController+Alert.swift
// AlbumRSS
//
// Created by Gavin Li on 8/15/20.
// Copyright © 2020 Gavin Li. All rights reserved.
//
import UIKit
extension UIViewController {
// present an alert with a confirm button
public func showAlert(title: String, message: String? = nil) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alert.addAction(defaultAction)
self.present(alert, animated: true, completion: nil)
}
}
|
import Foundation
var memo: [Int?] = []
func fib(n: Int) -> Int {
if memo.count <= n {
memo += Array(repeating: nil, count: n - memo.count + 1)
}
// print(n, memo)
var ret = 0
if let m = memo[n] {
ret = m
} else {
if n == 0 {
ret = 1
} else if n == 1 {
ret = 1
} else {
ret = fib(n: n - 1) + fib(n: n - 2)
}
memo[n] = ret
}
return ret
}
let startTime = Date()
for i in 0 ... 90 {
print(i, fib(n: i))
}
print("Time:", Date().timeIntervalSince(startTime) * 1000, "ms")
|
//
// TabBarViewController.swift
// Tumblr
//
// Created by Muddassar Sajjad on 10/12/15.
// Copyright © 2015 com.training.codepath. All rights reserved.
//
import UIKit
class TabBarViewController: UIViewController {
@IBOutlet weak var contentView: UIView!
var homeViewCtrlr: UIViewController!
var searchViewCtrlr: UIViewController!
var accountViewCtrlr: UIViewController!
var trendingViewCtrlr: UIViewController!
override func viewDidLoad() {
super.viewDidLoad()
let storyboard = UIStoryboard(name: "Main", bundle: nil)
homeViewCtrlr = storyboard.instantiateViewControllerWithIdentifier("HomeViewController")
searchViewCtrlr = storyboard.instantiateViewControllerWithIdentifier("SearchViewController")
accountViewCtrlr = storyboard.instantiateViewControllerWithIdentifier("AccountViewController")
trendingViewCtrlr = storyboard.instantiateViewControllerWithIdentifier("TrendingViewController")
// Do any additional setup after loading the view.
}
func handleTabBarButtonPress(button: UIButton, viewCtrlr: UIViewController) {
if previousButton != nil {
previousButton.selected = false
}
if currentViewCtrlr != nil {
currentViewCtrlr.willMoveToParentViewController(nil)
currentViewCtrlr.view.removeFromSuperview()
currentViewCtrlr.removeFromParentViewController()
}
button.selected = true
addChildViewController(viewCtrlr)
contentView.addSubview(viewCtrlr.view)
viewCtrlr.didMoveToParentViewController(self)
viewCtrlr.view.frame = contentView.bounds
previousButton = button
currentViewCtrlr = viewCtrlr
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
var previousButton: UIButton!
var currentViewCtrlr : UIViewController!
@IBAction func onHomeButton(button: UIButton) {
handleTabBarButtonPress(button, viewCtrlr: homeViewCtrlr)
}
@IBAction func onSearchButton(button: UIButton) {
handleTabBarButtonPress(button, viewCtrlr: searchViewCtrlr)
}
@IBAction func onAccountButton(button: UIButton) {
handleTabBarButtonPress(button, viewCtrlr: accountViewCtrlr)
}
@IBAction func onTrendingButton(button: UIButton) {
handleTabBarButtonPress(button, viewCtrlr: trendingViewCtrlr)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
//
// SKIntrinsicContentSizeView.swift
// AutoLayoutDemo
//
// Created by 董知樾 on 2017/3/29.
// Copyright © 2017年 董知樾. All rights reserved.
//
import UIKit
class SKIntrinsicContentSizeView: UIView {
var useIntrinsic = true
var label = UILabel()
var size : CGSize? {
didSet {
useIntrinsic = false
invalidateIntrinsicContentSize()
}
}
override var intrinsicContentSize: CGSize {
get {
if useIntrinsic {
return CGSize(width: UIViewNoIntrinsicMetric, height: UIViewNoIntrinsicMetric)
} else {
return size!
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor.hexValue(0x40a0ff)
let description = "Intrinsic Content Size 固有尺寸:在AutoLayout中,当开发者没有指定控件的尺寸时,控件会使用Intrinsic Content Size来计算自己的尺寸,UILabel,UIButton,设置了image的UIImageView,由子控件约束支撑的UIView等,都可以根据Intrinsic Content Size来计算自己的尺寸"
label.backgroundColor = UIColor.hexValue(0xf8f8f8)
label.textColor = UIColor.hexValue(0x666666)
label.numberOfLines = 0
addSubview(label)
label.font = UIFont.systemFont(ofSize: 14)
label.snp.makeConstraints { (make) in
make.edges.equalTo(UIEdgeInsetsMake(10, 10, 10, 10))
}
label.text = description
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
import Foundation
final class ComicListScreenInteractor: ComicListScreenInteractorType {
var webService: WebService
init(webService: WebService) {
self.webService = webService
}
func getLatestComic(
completionHandler: @escaping (Data?, WebServiceError?) -> Void
) {
let path = String(format: Constants.BackendAPI.current)
webService.request(
path: path,
method: .get,
headers: nil,
parameters: nil,
body: nil
) { (result: Result<Data?, WebServiceError>) in
switch result {
case let .success(data):
completionHandler(data, nil)
case let .failure(error):
completionHandler(nil, error)
}
}
}
func getComic(
comicNumber: Int,
completionHandler: @escaping (Data?, WebServiceError?) -> Void
) {
let path = String(format: Constants.BackendAPI.comicNumber, comicNumber.description)
webService.request(
path: path,
method: .get,
headers: nil,
parameters: nil,
body: nil
) { (result: Result<Data?, WebServiceError>) in
switch result {
case let .success(data):
completionHandler(data, nil)
case let .failure(error):
completionHandler(nil, error)
}
}
}
}
|
//
// motionEffect.swift
// Qnight
//
// Created by David Choi on 2017-06-14.
// Copyright © 2017 David Choi. All rights reserved.
//
import Foundation
class motionEffect {
private static let _instance = motionEffect()
static var Instance: motionEffect{
return _instance
}
func applyMotionEffect (toView view: UIView, magnitudex:Float, magnitudey: Float){
let xMotion = UIInterpolatingMotionEffect(keyPath: "center.x", type: .tiltAlongHorizontalAxis)
xMotion.minimumRelativeValue = -magnitudex
xMotion.maximumRelativeValue = magnitudex
let yMotion = UIInterpolatingMotionEffect(keyPath: "center.y", type: .tiltAlongHorizontalAxis)
yMotion.minimumRelativeValue = -magnitudey
yMotion.maximumRelativeValue = magnitudey
let group = UIMotionEffectGroup()
group.motionEffects = [xMotion, yMotion]
view.addMotionEffect(group)
}
}
|
//
// AddOrEditViewController.swift
// AkiosTask18
//
// Created by Nekokichi on 2020/09/13.
// Copyright © 2020 Nekokichi. All rights reserved.
//
import UIKit
final class AddOrEditViewController: UIViewController,UITextFieldDelegate {
enum SegueMode {
case add
case edit
}
@IBOutlet private weak var completeInputButton: UIBarButtonItem!
@IBOutlet private weak var inputNameTextField : UITextField!
var mode : SegueMode = .add
var selectedIndexPathRow: Int!
var inputText : String!
override func viewDidLoad() {
super.viewDidLoad()
inputNameTextField.delegate = self
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
switch mode {
case .add:
self.navigationItem.title = "項目追加"
completeInputButton.title = "追加"
case .edit:
self.navigationItem.title = "項目編集"
completeInputButton.title = "更新"
inputNameTextField.text = inputText
}
}
override func resignFirstResponder() -> Bool {
return true
}
func displayAlert() {
let alertController = UIAlertController(title: "エラー", message: "1文字以上の文字を入力してください", preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alertController.addAction(cancelAction)
present(alertController, animated: true, completion: nil)
}
@IBAction func completeInputButton(_ sender: UIButton) {
switch mode {
case .add:
// 文字が入力されてるかの確認
if let text = inputNameTextField.text, !text.isEmpty {
inputText = inputNameTextField.text!
performSegue(withIdentifier: "completeAdd", sender: nil)
} else {
displayAlert()
}
case .edit:
if let text = inputNameTextField.text, !text.isEmpty {
inputText = inputNameTextField.text!
performSegue(withIdentifier: "completeEdit", sender: nil)
} else {
displayAlert()
}
}
}
@IBAction func cancelButton(_ sender: UIButton) {
dismiss(animated: true, completion: nil)
}
}
|
//
// LocationService.swift
// Weather Plus
//
// Created by joe_mac on 02/09/2021.
//
import Foundation
class LocationService {
static var shared = LocationService()
var longitude: Double!
var latitude: Double!
}
|
//
// UCService.swift
// ZGHFinance
//
// Created by zhangyr on 16/3/16.
// Copyright © 2016年 cjxnfs. All rights reserved.
//
import UIKit
class UCService: BaseService {
class func loginActionWithUsername(username : String , loginPassword : String , completion : ((BaseData?) -> Void),failure : ((QCGError!) -> Void)) {
let request = UCLoginRequest(username: username, loginPassword: loginPassword)
self.doRequest(request, completion: completion, failure: failure)
}
class func sendMbCodeWithPhone(phone : String , completion : ((BaseData?) -> Void),failure : ((QCGError!) -> Void)) {
let request = UCMobileCodeRequest(phone: phone)
self.doRequest(request, completion: completion, failure: failure)
}
class func registerActionWithParams(params : Dictionary<String , AnyObject> , completion : ((BaseData?) -> Void),failure : ((QCGError!) -> Void)) {
let request = UCRegisterRequest(params: params)
self.doRequest(request, completion: completion, failure: failure)
}
class func getUserDataWithToken(token : String , completion : ((BaseData?) -> Void),failure : ((QCGError!) -> Void)) {
let request = UCGetUserDataRequest(token: token)
self.doRequest(request, completion: completion, failure: failure)
}
class func getAccountDataWithToken(token : String , completion : ((BaseData?) -> Void),failure : ((QCGError!) -> Void)) {
let request = UCGetAccountDataRequest(token: token)
self.doRequest(request, completion: completion, failure: failure)
}
}
|
//
// TweetsList+CoreDataClass.swift
//
//
// Created by Amit Majumdar on 08/03/18.
//
//
import Foundation
import CoreData
@objc(TweetsList)
public class TweetsList: NSManagedObject {
}
|
//
// ViewController.swift
// TestCollectionView
//
// Created by Nguyen Dinh Cong on 2019/11/18.
// Copyright © 2019 Cong Nguyen. All rights reserved.
//
import UIKit
enum Section {
case main
}
class Item: Hashable {
private let uuid = UUID()
static func == (lhs: Item, rhs: Item) -> Bool {
lhs.uuid == rhs.uuid
}
func hash(into hasher: inout Hasher) {
hasher.combine(uuid)
}
let title: String
let level: Int
let subItems: [Item]
let sceneClass: UIViewController.Type?
var isExpanded = false
init(title: String, level: Int, subItems: [Item], sceneClass: UIViewController.Type? = nil) {
self.title = title
self.level = level
self.subItems = subItems
self.sceneClass = sceneClass
}
}
let items: [Item] = [
Item(title: "Compositional Layout", level: 0, subItems: [
Item(title: "Adaptive Section", level: 1, subItems: [], sceneClass: AdaptiveSectionsVC.self),
Item(title: "Suplementary Views", level: 1, subItems: [], sceneClass: SuplementaryViewsVC.self),
Item(title: "Orthogonal Sections", level: 1, subItems: [
Item(title: "Orthogonal Section Behaviors", level: 2, subItems: [], sceneClass: OrthogonalSectionsVC.self),
])
]),
Item(title: "Diffable Data Source", level: 0, subItems: [
Item(title: "Sort Visualizer", level: 1, subItems: [], sceneClass: SortVisualizerVC.self),
])
]
class ViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
var dataSource: UITableViewDiffableDataSource<Section, Item>?
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UINib(nibName: "TableViewCell", bundle: nil), forCellReuseIdentifier: "TableViewCell")
dataSource = .init(tableView: tableView, cellProvider: { tableView, indexPath, item -> UITableViewCell? in
guard let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell", for: indexPath) as? TableViewCell else { return nil }
cell.title.text = item.title
cell.level = item.level
return cell
})
let snapshot = createSnapshot()
dataSource?.apply(snapshot, animatingDifferences: false)
}
func createSnapshot() -> NSDiffableDataSourceSnapshot<Section, Item> {
var snapshot = NSDiffableDataSourceSnapshot<Section, Item>()
snapshot.appendSections([Section.main])
func addItem(_ item: Item) {
snapshot.appendItems([item])
if item.isExpanded {
item.subItems.forEach { addItem($0) }
}
}
items.forEach { addItem($0) }
return snapshot
}
}
extension ViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
guard let menuItem = dataSource?.itemIdentifier(for: indexPath) else { return }
if menuItem.subItems.isEmpty {
if let sceneClass = menuItem.sceneClass {
let orthogonalSectionsVC = sceneClass.init(nibName: String(describing: sceneClass), bundle: nil)
show(orthogonalSectionsVC, sender: nil)
}
} else {
menuItem.isExpanded.toggle()
let snapshot = createSnapshot()
dataSource?.apply(snapshot, animatingDifferences: true)
}
}
}
|
//
// Constants.swift
// LadderPromise
//
// Created by Alexander Mason on 12/21/16.
// Copyright © 2016 Alexander Mason. All rights reserved.
//
import Foundation
import UIKit
struct Constants {
static func themeFont(size: CGFloat = 14) -> UIFont? {
return UIFont(name: "Avenir Next", size: size)
}
}
|
// Person.swift
/// Person
///
/// `Presenter`が参照できるモデルです。
///
/// `Presenter`は`Entity`を参照できないので、プロトコル経由で参照します。
protocol Person {
var firstName: String { get set }
var lastName: String { get set }
var fullName: String { get }
var age: Int { get set }
}
/// PersonEntity
///
/// `VIPER`で定義される`Entity`です。
struct PersonEntity: Person {
var firstName: String
var lastName: String
var fullName: String {
return lastName + " " + firstName
}
var age: Int
init(firstName: String, lastName: String, age: Int) {
self.firstName = firstName
self.lastName = lastName
self.age = age
}
func greeting() {
print("My name is " + fullName + ".")
}
}
|
/*
Copyright (c) Important Company
This is a block comment.
*/
import Combine
import UIKit
/// This classes uses a variety of spacing: \n, \t, etc, plus comment styles
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
/*
* Important comment here.
* Oh yes.
*/
var `default` = false
func someFunc() {
// Another comment
// Another comment
// Another comment
// Another comment
// This line uses tabs
// So does this
// Another comment
// Another comment
// Another comment
}
}
|
import Foundation
class MacaroonCrypto {
private static let magicMacaroonKey = "macaroons-key-generator".toInt8()
static func createVerificationId(verificationId: [UInt8], signature: [UInt8]) -> [UInt8] {
let caveatKey = generateDerivedKey(verificationId)
let derivedCaveatKey = caveatKey.trunc(32)
let truncatedSignature = signature.trunc(32)
return Crypto.secretBox(derivedCaveatKey, secretKey: truncatedSignature)
}
static func signWithThirdPartyCaveat(verification: [UInt8], caveatId: [UInt8], signature: [UInt8]) -> [UInt8] {
var verificationIdHash = Crypto.hmac(key: signature, data: verification)
let caveatIdHash = Crypto.hmac(key: signature, data: caveatId)
verificationIdHash.appendContentsOf(caveatIdHash)
return Crypto.hmac(key: signature, data: verificationIdHash)
}
static func initialSignature(key: [UInt8], identifier: [UInt8]) -> [UInt8] {
let derivedKey = generateDerivedKey(key)
return Crypto.hmac(key: derivedKey, data: identifier)
}
static func generateDerivedKey(key: [UInt8]) -> [UInt8] {
return Crypto.hmac(key: magicMacaroonKey, data: key)
}
static func bindSignature(signature: [UInt8], with anotherSignature: [UInt8]) -> [UInt8] {
let emptyArray = [UInt8].init(count: 32, repeatedValue: 0x00)
var hash1 = Crypto.hmac(key: emptyArray, data: signature)
let hash2 = Crypto.hmac(key: emptyArray, data: anotherSignature)
hash1.appendContentsOf(hash2)
return Crypto.hmac(key: emptyArray, data: hash1)
}
} |
//
// ErrorManager.swift
// WeatherApp
//
// Created by Lucky on 16/02/2020.
// Copyright © 2020 DmitriyYatsyuk. All rights reserved.
//
import Foundation
public let YATNetworkingErrorDomain = "ru.yatsyuk.dev@mail.WeatherApp.NetworkingError"
public let MissingHTTPResponseError = 100
public let UnexpectedResponseError = 200
|
//
// ATableViewCell.swift
// CLEAN
//
// Created by eunji on 2018. 6. 21..
// Copyright © 2018년 김장현. All rights reserved.
//
import UIKit
class ATableViewCell: UITableViewCell {
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
//
// MDBPopulatTvBroadcastTableViewCell.swift
// MovieDB
//
// Created by emirhan battalbaş on 21.04.2019.
// Copyright © 2019 emirhan battalbaş. All rights reserved.
//
protocol DetailVcProtocol {
func detailProtocol(row: Int)
}
import UIKit
class MDBPopulatTvBroadcastTableViewCell: UITableViewCell, Reusable {
// ImageView
@IBOutlet weak var posterImageView: UIImageView!
// Label
@IBOutlet var ratedLabel: [UILabel]!
@IBOutlet weak var nameLabel: UILabel!
var delegate: DetailVcProtocol?
var row: Int?
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
@IBAction func detailButtonTapped(_ sender: Any) {
guard row != nil else { return }
self.delegate?.detailProtocol(row: row!)
}
}
|
import SwiftUI
struct TimelineItemPreview: View {
var name: Binding<String>
var color: Binding<Color>
private let cornerRadius: CGFloat = 5
private let baseHeight: CGFloat = 70
var body: some View {
HStack {
Text(name.wrappedValue.uppercased())
.bold()
.lineLimit(1)
.truncationMode(.tail)
}
.formatted(fontSize: 20)
.frame(maxWidth: .infinity, minHeight: baseHeight, maxHeight: baseHeight)
.padding(10)
.background(color.wrappedValue)
.cornerRadius(cornerRadius)
.overlay(
RoundedRectangle(cornerRadius: cornerRadius)
.strokeBorder(Color.clouds, lineWidth: 5)
)
}
}
struct TimelineItemPreview_Previews: PreviewProvider {
static var previews: some View {
ZStack {
BackgroundView()
TimelineItemPreview(name: Binding.constant("Item name"), color: Binding.constant(Color.turquoise))
}
}
}
|
//
// AlertMessageVCExt.swift
// stckchck
//
// Created by Pho on 30/08/2018.
// Copyright © 2018 stckchck. All rights reserved.
//
import Foundation
import UIKit
extension UIViewController {
func alertMessage(_ title: String, message: String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction((UIAlertAction(title: "Ok", style: .default, handler: { (action) in
alert.dismiss(animated: true, completion: nil)
})))
self.present(alert, animated: true, completion: nil)
}
func noResultsFoundAlert() {
let title1 = "New products added every day!"
let title2 = "Broaden your horizons..."
let title3 = "GOOBAGABA"
let message1 = "We are a growing company, and unfortunately, we couldn't find a product matching your search... yet. Please try again soon!"
let message2 = "Pinch the screen to increase your search area! You may find what you're looking for further afield..."
let message3 = "Got your attention. Pinch the screen to increase your search area. Shops further away may have your product in stock..."
var titleToShow = String()
var messageToShow = String()
let randomNumber = arc4random_uniform(3) + 1
if randomNumber == 1 {
titleToShow = title1
messageToShow = message1
} else if randomNumber == 2 {
titleToShow = title2
messageToShow = message2
} else if randomNumber == 3 {
titleToShow = title3
messageToShow = message3
}
let alert = UIAlertController(title: titleToShow, message: messageToShow, preferredStyle: .alert)
alert.addAction((UIAlertAction(title: "Ok", style: .default, handler: { (action) in
alert.dismiss(animated: true, completion: nil)
})))
self.present(alert, animated: true, completion: nil)
}
}
|
//
// BasedView.swift
// BasedView
//
// Created by Michele Manniello on 10/09/21.
//
import SwiftUI
struct BasedView: View {
@State var showMenu : Bool = false
init(){
UITabBar.appearance().isHidden = true
}
@State var currentTab = "Home"
// Offset for Both Drag Gesture and showing Menu...
@State var offset : CGFloat = 0
@State var lastStoredOffset : CGFloat = 0
// Gesture Offset...
@GestureState var gestureOffset: CGFloat = 0
var body: some View {
let sideBarWidth = getRect().width - 90
// Hiding Native One...
// Whole Navigation View...
NavigationView{
HStack(spacing: 0){
// Side Menu...
SideMenu(showMenu: $showMenu)
// Main Tab View...
VStack(spacing: 0){
TabView(selection: $currentTab){
Home(showMenu: $showMenu)
.navigationBarTitleDisplayMode(.inline)
.navigationBarHidden(true)
.tag("Home")
Text("Search")
.navigationBarTitleDisplayMode(.inline)
.navigationBarHidden(true)
.tag("Search")
Text("Notifications")
.navigationBarTitleDisplayMode(.inline)
.navigationBarHidden(true)
.tag("Notifications")
Text("Message")
.navigationBarTitleDisplayMode(.inline)
.navigationBarHidden(true)
.tag("Message")
}
// Custom Tab Bar...
VStack(spacing: 0){
Divider()
HStack(spacing: 0) {
// Tap Buttons..
TabButton(image: "Home")
TabButton(image: "Search")
TabButton(image: "Notifications")
TabButton(image: "Message")
}
.padding([.top],15)
}
}
.frame(width: getRect().width)
// BG when menu is showing...
.overlay(
Rectangle()
.fill(
Color.primary
.opacity(Double((offset / sideBarWidth) / 5))
)
.ignoresSafeArea(.container, edges: .vertical)
.onTapGesture {
withAnimation {
showMenu.toggle()
}
}
)
}
// max Size...
.frame(width: getRect().width + sideBarWidth)
.offset(x: -sideBarWidth / 2)
.offset(x: offset > 0 ? offset : 0)
// Gesture...
.gesture(
DragGesture()
.updating($gestureOffset, body: { value, out, _ in
out = value.translation.width
})
.onEnded(onEnd(value: ))
)
// No Nav bar title
// Hiding nav bar..
.navigationBarTitleDisplayMode(.inline)
.navigationBarHidden(true)
}
.animation(.easeOut, value: offset == 0)
.onChange(of: showMenu) { newValue in
if showMenu && offset == 0{
offset = sideBarWidth
lastStoredOffset = offset
}
if !showMenu && offset == sideBarWidth {
offset = 0
lastStoredOffset = 0
}
}
.onChange(of: gestureOffset) { newValue in
onChange()
}
}
func onChange(){
let sideBarWidth = getRect().width - 90
offset = (gestureOffset != 0) ? (gestureOffset + lastStoredOffset < sideBarWidth ? gestureOffset + lastStoredOffset: offset) : offset
}
func onEnd(value: DragGesture.Value){
let sideBarWidth = getRect().width - 90
let translation = value.translation.width
withAnimation {
// Checking...
if translation > 0{
if translation > (sideBarWidth / 2){
// showing menu...
offset = sideBarWidth
showMenu = true
}else{
// Extra cases...
if offset == sideBarWidth{
return
}
offset = 0
showMenu = false
}
}else{
if -translation > (sideBarWidth / 2){
offset = 0
showMenu = false
}else{
if offset == 0 || !showMenu{
return
}
offset = sideBarWidth
showMenu = true
}
}
}
// string last offset...
lastStoredOffset = offset
}
@ViewBuilder
func TabButton(image: String)-> some View {
Button {
withAnimation {
currentTab = image
}
} label: {
Image(image)
.resizable()
.renderingMode(.template)
.aspectRatio(contentMode: .fit)
.frame(width: 23, height: 22)
.foregroundColor(currentTab == image ? .primary : .gray)
.frame(maxWidth: .infinity)
}
}
}
struct BasedView_Previews: PreviewProvider {
static var previews: some View {
BasedView()
}
}
|
import Fluent
import Vapor
func routes(_ app: Application) throws {
app.get { req in
return "It works!"
}
app.get("hello") { req -> String in
return "Hello, world!"
}
let bookingController = BookingsController()
app.post("Bookings", use: bookingController.create)
app.get("Bookings", use: bookingController.all)
let messegeController = MessageController()
app.post("Messages", use: messegeController.create)
app.get("Messages", use: messegeController.all)
}
|
//
// Protocols.swift
// Hospital
//
// Created by Nick Baidikoff on 21.04.16.
// Copyright © 2016 KPI. All rights reserved.
//
import Foundation
protocol Configurable {
func config(withItem item: Any)
}
protocol LoginView : class {
func loggedIn() -> Void
func showAlertWithMessage(message mess: String) -> Void
func errorInLog() -> Void
}
protocol LoginViewPresenter: class {
func tryLogin(email email: String, password: String) -> Void
}
protocol DoctorView: class {
func sheduleSegue() -> Void
}
protocol DoctorViewPresenter: class {
func refreshDoctors() -> Void
func getDoctor(atIndex index: Int) -> Doctor?
func getDoctorsCount() -> Int
}
protocol OverviewView : class {
}
protocol OverviewViewPresenter : class {
func refreshAppointments() -> Void
func getAppointment(atIndex index: Int) -> Appointment?
func getAppointmentsCount() -> Int
}
protocol SheduleView: class {
}
protocol SheduleViewPresenter: class {
func sheduleAppointment(newAppointment app: Dictionary<String, AnyObject>) -> Void
}
protocol BurgerMenuEnter : class {
func menuButton() -> Void
func toOverview() -> Void
func toDoctors() -> Void
func logout() -> Void
} |
//
// Object.swift
// AR Touch
//
// Created by Michel Kansou on 05/10/2017.
// Copyright © 2017 Michel Kansou. All rights reserved.
//
import Foundation
import SceneKit
class Object {
class func getObjectForName(objectName: String) -> SCNNode {
switch objectName {
case "ikea":
return Object.getIkeaCouch()
default:
return Object.getIkeaCouch()
}
}
class func getIkeaCouch() -> SCNNode {
let obj = SCNScene(named: "art.scnassets/ikea.dae")
let node = obj?.rootNode.childNode(withName: "ikea", recursively: true)!
node?.scale = SCNVector3Make(1, 1, 1)
node?.position = SCNVector3Make(-1, -1, -1)
return node!
}
class func startRotation(node: SCNNode) {
let rotate = SCNAction.repeatForever(SCNAction.rotateBy(x: 0, y: CGFloat(0.01 * Double.pi), z: 0, duration: 0.1))
node.runAction(rotate)
}
}
|
//
// ReportOverviewInteractorImpl.swift
// DeliriumOver
//
// Created by Mate Redecsi on 2019. 11. 02..
// Copyright © 2019. rmatesz. All rights reserved.
//
import Foundation
import RxSwift
class ReportOverviewInteractorImpl: ReportOverviewInteractor {
private let sessionRepository: SessionRepository
private let consumptionRepository: ConsumptionRepository
private let drinkRepository: DrinkRepository
private let alcoholCalculator: AlcoholCalculatorRxDecorator
private lazy var loadSessionTask: Observable<Session> = loadInProgressSession().replay(1).autoconnect()
private var sessionId: String?
init(sessionRepository: SessionRepository, consumptionRepository: ConsumptionRepository, drinkRepository: DrinkRepository, alcoholCalculator: AlcoholCalculatorRxDecorator) {
self.sessionRepository = sessionRepository
self.consumptionRepository = consumptionRepository
self.drinkRepository = drinkRepository
self.alcoholCalculator = alcoholCalculator
}
func loadSession() -> Observable<Session> {
return loadSessionTask
}
func loadStatistics() -> Observable<Statistics> {
return loadSession().flatMap { (session) -> Observable<Statistics> in
Observable.zip(
self.alcoholCalculator.calcTimeOfZeroBAC(session: session).asObservable(),
self.alcoholCalculator.calcBloodAlcoholConcentration(session: session, date: dateProvider.currentDate).asObservable(),
resultSelector: { (alcoholEliminationDate, bloodAlcoholConcentration) -> Statistics in
return Statistics(alcoholEliminationDate: alcoholEliminationDate, bloodAlcoholConcentration: bloodAlcoholConcentration)
}
)
}.asObservable()
}
func loadRecords() -> Observable<[Record]> {
return loadSession().flatMap { (session) ->Single<[Record]> in
// sessionRepository.getFriendsSessions(shareKey: session.shareKey)
// .map { (sessions) -> R in
//
// }
Single.zip(
Single.just(session.name),
self.alcoholCalculator.generateRecords(session: session)
).map { (name, data) -> Record in
Record(name: name, data: data)
}.asObservable().toArray()
}
// sessionRepository.getFriendsSessions(session.shareKey)
// .onErrorReturnItem(emptyList<Session>())
// .firstElement()
// .filter { session.shared }
// .defaultIfEmpty(emptyList())
// .flattenAsFlowable { it }
// .startWith(session)
// .flatMapSingle {
// Single.zip(
// just(it.name),
// alcoholCalculator.generateRecords(it),
// BiFunction<String, List<Data>, Record> { name, records -> Record(name, records) }
// )
// }
// .toList()
}
public func loadFrequentlyConsumedDrinks() -> Observable<[Drink]> {
return drinkRepository.getFrequentlyConsumedDrinks()
.map({ (drinks) -> [Drink] in
Array(drinks.prefix(3))
})
}
func saveSession(session: Session) -> Completable {
return sessionRepository.update(session: session)
}
private func loadInProgressSession() -> Observable<Session> {
if let sessionId = self.sessionId {
return sessionRepository.loadSession(sessionId: sessionId)
}
return sessionRepository.inProgressSession
// .doOnSuccess { this.sessionId = it }
// .flatMapPublisher { loadSession(it) }
// .switchIfEmpty(
// createNewSession()
// .doOnSuccess { this.sessionId = it }
// .flatMapPublisher { loadSession(it) }
}
public func add(drink: Drink) -> Completable {
return loadInProgressSession().first()
.flatMapCompletable {
guard let session = $0 else {
return Completable.empty()
}
return self.consumptionRepository.saveConsumption(sessionId: session.id, consumption: Consumption(drink: drink))
}
}
}
|
//
// Constants.swift
// PassportOCR
//
// Created by Михаил on 03.09.16.
// Copyright © 2016 empatika. All rights reserved.
//
import Foundation
public let DOErrorDomain = "DocumentsOCRErrorDomain"
struct NibNames {
static let cameraOverlayViewController = "CameraOverlayViewController"
}
struct Constants {
static let alphabet = Constants.getAlphabet()
private static func getAlphabet() -> String {
let aScalars = "a".unicodeScalars
let aCode = aScalars[aScalars.startIndex].value
var result = ""
for i: UInt32 in (0..<26) {
result.append(Character(UnicodeScalar(aCode + i)))
}
return result
}
}
|
//
// CleaningInfoSheetView.swift
// CovidAlert
//
// Created by Matthew Garlington on 12/26/20.
//
import SwiftUI
struct CleaningInfoSheetView: View {
var body: some View {
NavigationView {
ScrollView {
VStack(alignment: .leading, spacing: 10) {
Image(systemName: "wand.and.stars.inverse")
.foregroundColor(.yellow)
.font(.system(size: 40))
Text("Cleaning and Disinfecting Surfaces")
.bold()
.font(.system(size: 35))
Text("Commonly used surfaces should be regularly cleaned and disinfected")
.frame(height: 150)
.font(.system(size: 20))
Spacer()
Text("How To")
.bold()
.font(.title)
Text("It's always a good idea to routinely clean and disinfect frequently touched surfaces like tables, doorknobs, light switches, handles, desk, toilets, faucets, and sinks. But if you have a suspected or confirmed case of COVID-19, be vigilant about doing this daily.")
.frame(height: 200)
.font(.system(size: 20))
}.padding(.horizontal)
VStack(alignment: .leading, spacing: 10) {
Text("First, clean dirty surfaces with soap and water. Cleaning will remove dirt and lower the number of germs-but it will not kill germs.")
.frame(height: 150)
.font(.system(size: 20))
Text("Next, disinfect surfaces to kill germs. Disinfecting after cleaning can further lower the risk of spreading an infection. Most common EPA-registered household disinfectants will work. Or dilute your household bleach with 1/3 cup of bleach per gallon of water.")
.frame(height: 100)
.font(.system(size: 20))
Text("Wear dedicated gloves for COVID-19 related cleaning and disinfecting or use disposable gloves and discard them after each use.")
.frame(height: 100)
.font(.system(size: 20))
}.padding(.horizontal)
}.padding()
}
}
}
struct CleaningInfoSheetView_Previews: PreviewProvider {
static var previews: some View {
CleaningInfoSheetView()
}
}
|
//
// RoleInfoTableViewCell.swift
// WSwiftApp
//
// Created by LHWen on 2018/8/21.
// Copyright © 2018年 LHWen. All rights reserved.
//
import UIKit
// 角色信息
class RoleInfoTableViewCell: UITableViewCell {
public var titleLbl: UILabel?
public var contentLbl: UILabel?
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.contentView.backgroundColor = .white
p_setup()
}
private func p_setup() {
p_setTitleLable()
p_setContentLable()
}
private func p_setTitleLable() {
if titleLbl == nil {
titleLbl = CreateViewFactory.p_setLableWhiteBGAndOneLines("role", 15.0, ColorUtility.colorWithHexString(toConvert: "#999999", a: 1.0), .left)
self.contentView.addSubview(titleLbl!)
titleLbl?.snp.makeConstraints({ (make) -> Void in
make.left.equalTo(13.0)
make.top.equalTo(self.contentView)
})
}
}
private func p_setContentLable() {
if contentLbl == nil {
contentLbl = CreateViewFactory.p_setLableWhiteBGAndOneLines("content", 15.0, ColorUtility.colorWithHexString(toConvert: "#333333", a: 1.0), .left)
self.contentView.addSubview(contentLbl!)
contentLbl?.snp.makeConstraints({ (make) -> Void in
make.left.equalTo(130.0)
make.top.equalTo(self.contentView)
})
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
//
// InvestimentDetailsViewController.swift
// InvestimentApp
//
// Created by Israel on 10/12/19.
// Copyright © 2019 israel3D. All rights reserved.
//
import UIKit
protocol InvestimentDetailsViewControllerProtocol: AnyObject {
func showInvestiments()
}
class InvestimentDetailsViewController: UIViewController, InvestimentDetailsViewControllerProtocol {
@IBOutlet weak var titleResultLabel: UILabel! {
didSet {
titleResultLabel.isAccessibilityElement = true
titleResultLabel.accessibilityLabel = Constants.kInvestmentResultLabel
}
}
@IBOutlet weak var totalMoneyLabel: UILabel! {
didSet {
totalMoneyLabel.isAccessibilityElement = true
}
}
@IBOutlet weak var yieldMoneyIntroLabel: UILabel! {
didSet {
yieldMoneyIntroLabel.isAccessibilityElement = true
yieldMoneyIntroLabel.accessibilityLabel = Constants.kProfitabilityLabel
}
}
@IBOutlet weak var yieldMoneyLabel: UILabel! {
didSet {
yieldMoneyLabel.isAccessibilityElement = true
}
}
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var simulateAgainButton: UIButton! {
didSet {
simulateAgainButton.isAccessibilityElement = true
simulateAgainButton.accessibilityLabel = Constants.kSimulateAgainButton
}
}
private let presenter = InvestimentDetailsPresenter()
private let reuseIdentifier = "investimentCell"
private let numberOfLines = 12
private var investiment: Investiment!
override func viewDidLoad() {
super.viewDidLoad()
setupTableView()
updateFonts(label: simulateAgainButton.titleLabel ?? UILabel(), style: .headline)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
showInvestiments()
}
class func instantiate(withInjection injection: Investiment) -> InvestimentDetailsViewController? {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
guard let vcInvestiment =
storyboard.instantiateViewController(withIdentifier: "InvestimentDetailsViewController")
as? InvestimentDetailsViewController else { return nil }
vcInvestiment.investiment = injection
return vcInvestiment
}
private func setupTableView() {
tableView.dataSource = self
tableView.isUserInteractionEnabled = false
tableView.separatorStyle = .none
let nib = UINib(nibName: "InvestimentDetailsTableViewCell", bundle: nil)
tableView.register(nib, forCellReuseIdentifier: reuseIdentifier)
}
func showInvestiments() {
totalMoneyLabel.text = presenter.brMoney(investiment.grossAmount ?? 0.0)
yieldMoneyLabel.text = presenter.brMoney(investiment.grossAmountProfit ?? 0.0)
}
private func updateFonts(label: UILabel, style: UIFont.TextStyle) {
label.font = UIFont.preferredFont(forTextStyle: style)
}
@IBAction func backToSimulateAgain(_ sender: UIButton) {
self.navigationController?.popViewController(animated: true)
}
}
// MARK: - UITableViewDataSource
extension InvestimentDetailsViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return numberOfLines
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath)
as? InvestimentDetailsTableViewCell {
let labelsText = fillTableLabels(indexPath.row, cell)
cell.setupCell(contextual: labelsText.0, value: labelsText.1)
return cell
}
return UITableViewCell()
}
}
// MARK: - Data Formatter
extension InvestimentDetailsViewController {
private func fillTableLabels(_ index: Int, _ cell: UITableViewCell) -> (String, String) {
var labelsText: (String, String) = ("", "")
guard let param = investiment.investmentParameter else { return ("", "") }
switch index {
case 0:
labelsText = (Constants.kInvestedAmount, "\(presenter.brMoney(param.investedAmount ?? 0.0))")
case 1:
labelsText = (Constants.kGrossAmount, "\(presenter.brMoney(investiment.grossAmount ?? 0.0))")
case 2:
labelsText = (Constants.kGrossAmountProfit, "\(presenter.brMoney(investiment.grossAmountProfit ?? 0.0))")
case 3:
labelsText = (Constants.kTaxesAmount, "\(presenter.brMoney(investiment.taxesAmount ?? 0.0))"
+ "(\(presenter.percentSymbol(investiment.taxesRate ?? 0.0)))")
case 4:
labelsText = (Constants.kNetAmount, "\(presenter.brMoney(investiment.netAmount ?? 0.0))")
case 6:
labelsText = (Constants.kMaturityDate, "\(presenter.strDateFromAPI(from: param.maturityDate ?? ""))")
case 7:
labelsText = (Constants.kMaturityTotalDays, "\(param.maturityTotalDays?.description ?? "")")
case 8:
labelsText = (Constants.kMonthlyGrossRateProfit,
"\(presenter.percentSymbol(investiment.monthlyGrossRateProfit ?? 0.0))")
case 9:
labelsText = (Constants.kRate, "\(presenter.percentSymbol(param.rate ?? 0.0))")
case 10:
labelsText = (Constants.kAnnualNetRateProfit,
"\(presenter.percentSymbol(investiment.annualNetRateProfit ?? 0.0))")
case 11:
labelsText = (Constants.kAnnualGrossRateProfit,
"\(presenter.percentSymbol(investiment.annualGrossRateProfit ?? 0.0))")
default:
labelsText = ("", "")
cell.isAccessibilityElement = false
cell.contentView.isAccessibilityElement = false
}
return labelsText
}
}
|
//
// Upgrades.swift
// SailingThroughHistory
//
// Created by henry on 17/3/19.
// Copyright © 2019 Sailing Through History Team. All rights reserved.
//
/// Defines the requirements of an upgrade for a ship.
import Foundation
protocol Upgrade: Codable {
var name: String { get }
var cost: Int { get }
var type: UpgradeType { get }
func getNewSuppliesConsumed(baseConsumption: [GenericItem]) -> [GenericItem]
func getMovementModifier() -> Double
}
|
//
// UIViewController+Extension.swift
// JC Movies
//
// Created by Mohammed Shakeer on 06/08/18.
// Copyright © 2018 Just Movies. All rights reserved.
//
import UIKit
extension UIViewController {
static let rootVC = UIApplication.shared.keyWindow?.rootViewController
class func topViewController(base: UIViewController? = rootVC) -> UIViewController? {
if let nav = base as? UINavigationController {
return topViewController(base: nav.visibleViewController)
}
if let tab = base as? UITabBarController {
if let selected = tab.selectedViewController {
return topViewController(base: selected)
}
}
if let presented = base?.presentedViewController {
return topViewController(base: presented)
}
return base
}
class func topMostViewController() -> UIViewController? {
guard let rootVC = UIApplication.shared.keyWindow?.rootViewController else { return nil }
if rootVC.presentedViewController == nil {
return rootVC
} else if let presented = rootVC.presentedViewController {
if let navVC = presented as? UINavigationController {
return navVC.viewControllers.last!
} else if let tabBarVC = presented as? UITabBarController {
return tabBarVC.selectedViewController
}
return presented
}
return nil
}
}
|
//
// ActivityList.swift
//
// Created by shiliuhua on 17/04/2018
// Copyright (c) . All rights reserved.
//
import Foundation
import SwiftyJSON
public final class ActivityList: NSCoding {
// MARK: Declaration for string constants to be used to decode and also serialize.
private struct SerializationKeys {
static let likes = "likes"
static let address = "address"
static let expand = "expand"
static let date = "date"
static let haveRedPacket = "haveRedPacket"
static let lat = "lat"
static let catalog = "catalog"
static let member = "member"
static let activity = "activity"
static let lng = "lng"
static let liked = "liked"
static let id = "id"
static let comments = "comments"
static let images = "images"
static let note = "note"
}
// MARK: Properties
public var likes: Int?
public var address: String?
public var expand: Bool? = false
public var date: String?
public var haveRedPacket: Int?
public var lat: Float?
public var catalog: Int?
public var member: ActivityMember?
public var activity: ActivityActivity?
public var lng: Float?
public var liked: Bool? = false
public var id: Int?
public var comments: Int?
public var images: [ActivityImages]?
public var note:String?
// MARK: SwiftyJSON Initializers
/// Initiates the instance based on the object.
///
/// - parameter object: The object of either Dictionary or Array kind that was passed.
/// - returns: An initialized instance of the class.
public convenience init(object: Any) {
self.init(json: JSON(object))
}
/// Initiates the instance based on the JSON that was passed.
///
/// - parameter json: JSON object from SwiftyJSON.
public required init(json: JSON) {
likes = json[SerializationKeys.likes].int
address = json[SerializationKeys.address].string
note = json[SerializationKeys.note].string
expand = json[SerializationKeys.expand].boolValue
date = json[SerializationKeys.date].string
haveRedPacket = json[SerializationKeys.haveRedPacket].int
lat = json[SerializationKeys.lat].float
catalog = json[SerializationKeys.catalog].int
member = ActivityMember(json: json[SerializationKeys.member])
activity = ActivityActivity(json: json[SerializationKeys.activity])
lng = json[SerializationKeys.lng].float
liked = json[SerializationKeys.liked].boolValue
id = json[SerializationKeys.id].int
comments = json[SerializationKeys.comments].int
if let items = json[SerializationKeys.images].array { images = items.map { ActivityImages(json: $0) } }
}
/// Generates description of the object in the form of a NSDictionary.
///
/// - returns: A Key value pair containing all valid values in the object.
public func dictionaryRepresentation() -> [String: Any] {
var dictionary: [String: Any] = [:]
if let value = likes { dictionary[SerializationKeys.likes] = value }
if let value = address { dictionary[SerializationKeys.address] = value }
if let value = note { dictionary[SerializationKeys.note] = value }
dictionary[SerializationKeys.expand] = expand
if let value = date { dictionary[SerializationKeys.date] = value }
if let value = haveRedPacket { dictionary[SerializationKeys.haveRedPacket] = value }
if let value = lat { dictionary[SerializationKeys.lat] = value }
if let value = catalog { dictionary[SerializationKeys.catalog] = value }
if let value = member { dictionary[SerializationKeys.member] = value.dictionaryRepresentation() }
if let value = activity { dictionary[SerializationKeys.activity] = value.dictionaryRepresentation() }
if let value = lng { dictionary[SerializationKeys.lng] = value }
dictionary[SerializationKeys.liked] = liked
if let value = id { dictionary[SerializationKeys.id] = value }
if let value = comments { dictionary[SerializationKeys.comments] = value }
if let value = images { dictionary[SerializationKeys.images] = value.map { $0.dictionaryRepresentation() } }
return dictionary
}
// MARK: NSCoding Protocol
required public init(coder aDecoder: NSCoder) {
self.likes = aDecoder.decodeObject(forKey: SerializationKeys.likes) as? Int
self.address = aDecoder.decodeObject(forKey: SerializationKeys.address) as? String
self.note = aDecoder.decodeObject(forKey: SerializationKeys.note) as? String
self.expand = aDecoder.decodeBool(forKey: SerializationKeys.expand)
self.date = aDecoder.decodeObject(forKey: SerializationKeys.date) as? String
self.haveRedPacket = aDecoder.decodeObject(forKey: SerializationKeys.haveRedPacket) as? Int
self.lat = aDecoder.decodeObject(forKey: SerializationKeys.lat) as? Float
self.catalog = aDecoder.decodeObject(forKey: SerializationKeys.catalog) as? Int
self.member = aDecoder.decodeObject(forKey: SerializationKeys.member) as? ActivityMember
self.activity = aDecoder.decodeObject(forKey: SerializationKeys.activity) as? ActivityActivity
self.lng = aDecoder.decodeObject(forKey: SerializationKeys.lng) as? Float
self.liked = aDecoder.decodeBool(forKey: SerializationKeys.liked)
self.id = aDecoder.decodeObject(forKey: SerializationKeys.id) as? Int
self.comments = aDecoder.decodeObject(forKey: SerializationKeys.comments) as? Int
self.images = aDecoder.decodeObject(forKey: SerializationKeys.images) as? [ActivityImages]
}
public func encode(with aCoder: NSCoder) {
aCoder.encode(likes, forKey: SerializationKeys.likes)
aCoder.encode(address, forKey: SerializationKeys.address)
aCoder.encode(note, forKey: SerializationKeys.note)
aCoder.encode(expand, forKey: SerializationKeys.expand)
aCoder.encode(date, forKey: SerializationKeys.date)
aCoder.encode(haveRedPacket, forKey: SerializationKeys.haveRedPacket)
aCoder.encode(lat, forKey: SerializationKeys.lat)
aCoder.encode(catalog, forKey: SerializationKeys.catalog)
aCoder.encode(member, forKey: SerializationKeys.member)
aCoder.encode(activity, forKey: SerializationKeys.activity)
aCoder.encode(lng, forKey: SerializationKeys.lng)
aCoder.encode(liked, forKey: SerializationKeys.liked)
aCoder.encode(id, forKey: SerializationKeys.id)
aCoder.encode(comments, forKey: SerializationKeys.comments)
aCoder.encode(images, forKey: SerializationKeys.images)
}
}
|
//
// mapviewgoogle.swift
// remoteios
//
// Created by Hasanul Isyraf on 21/06/2017.
// Copyright © 2017 Hasanul Isyraf. All rights reserved.
//
import UIKit
import GoogleMaps
import GooglePlaces
class mapviewgoogle: UIView {
override func viewDidLoad() {
super.viewDidLoad()
func loadView() {
// Create a GMSCameraPosition that tells the map to display the
// coordinate -33.86,151.20 at zoom level 6.
let camera = GMSCameraPosition.camera(withLatitude: -33.86, longitude: 151.20, zoom: 6.0)
let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
view = mapView
// Creates a marker in the center of the map.
let marker = GMSMarker()
marker.position = CLLocationCoordinate2D(latitude: -33.86, longitude: 151.20)
marker.title = "Sydney"
marker.snippet = "Australia"
marker.map = mapView
}
}
}
|
//
// FinderSync.swift
// FinderExtention
//
// Created by zhangzhiyong-pd@360.cn on 16/12/21.
// Copyright © 2016年 zhangzhiyong-pd@360.cn. All rights reserved.
//
import Cocoa
import FinderSync
class FinderSync: FIFinderSync {
let fileTypes = [
"New Text": ".txt",
"New Markdown": ".md",
"New JS File": ".js",
"New Python File": ".py",
"New Html File": ".html"
]
var myFolderURL = URL(fileURLWithPath: "/Users")
override init() {
super.init()
NSLog("===> FinderSync() launched from %@", Bundle.main.bundlePath as NSString)
}
// MARK: - Menu and toolbar item support
override var toolbarItemName: String {
return "NewFile"
}
override var toolbarItemToolTip: String {
return "NewFile: Click the toolbar item for a menu."
}
override var toolbarItemImage: NSImage {
return NSImage(named: NSImage.addTemplateName)!
}
override func menu(for menuKind: FIMenuKind) -> NSMenu {
// Produce a menu for the extension.
let menu = NSMenu(title: "")
for (menuTitle, _) in fileTypes {
menu.addItem(withTitle: menuTitle, action: #selector(addFile(_:)), keyEquivalent: "")
}
return menu
}
func generateRandomStringWithLength(_ length:Int) -> String {
let randomString:NSMutableString = NSMutableString(capacity: length)
let letters:NSMutableString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
var i: Int = 0
while i < length {
let randomIndex:Int = Int(arc4random_uniform(UInt32(letters.length)))
randomString.append("\(Character( UnicodeScalar( letters.character(at: randomIndex))!))")
i += 1
}
return String(randomString)
}
@IBAction func addFile(_ item: NSMenuItem) {
if let ext = fileTypes[item.title], let target = FIFinderSyncController.default().targetedURL() {
let path = target.path + "/" + generateRandomStringWithLength(4) + ext
do {
try "".write(toFile: path, atomically: false, encoding: .utf8)
NSWorkspace().selectFile(path, inFileViewerRootedAtPath: "")
} catch {
print("add file to \(path) failed : \(error.localizedDescription)")
}
}
}
}
|
//
// CameraView.swift
// ACSwiftTest
//
// Created by Air_chen on 2016/10/29.
// Copyright © 2016年 Air_chen. All rights reserved.
//
import UIKit
class CameraView: UIView {
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
override func layoutSubviews() {
super.layoutSubviews()
self.backgroundColor = UIColor.yellow
}
}
|
//
// AppDelegate.swift
// PMI
//
// Created by João Victor Batista on 28/10/19.
// Copyright © 2019 João Victor Batista. All rights reserved.
//
import UIKit
import Firebase
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
//determines where the app will launch
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let rootViewController = storyboard.instantiateViewController(withIdentifier: UserDefaults.standard.bool(forKey: "tutorialSeen") ? "Start" : "Intro")
window?.rootViewController = rootViewController
if #available(iOS 13.0, *) {
window?.overrideUserInterfaceStyle = .light
}
FirebaseApp.configure()
return true
}
}
|
//
// ButtonsStripeView.swift
// Adamant
//
// Created by Anokhov Pavel on 23.03.2018.
// Copyright © 2018 Adamant. All rights reserved.
//
import UIKit
import MyLittlePinpad
// MARK: - Button types
enum StripeButtonType: Int, Equatable {
case pinpad = 555
case touchID = 888
case faceID = 999
case qrCameraReader = 777
case qrPhotoReader = 1111
var image: UIImage {
switch self {
case .pinpad:
return #imageLiteral(resourceName: "Stripe_Pinpad")
case .touchID:
return #imageLiteral(resourceName: "Stripe_TouchID")
case .faceID:
return #imageLiteral(resourceName: "Stripe_FaceID")
case .qrCameraReader:
return #imageLiteral(resourceName: "Stripe_QRCamera")
case .qrPhotoReader:
return #imageLiteral(resourceName: "Stripe_QRLibrary")
}
}
}
extension BiometryType {
var stripeButtonType: StripeButtonType? {
switch self {
case .touchID:
return .touchID
case .faceID:
return .faceID
case .none:
return nil
}
}
}
typealias Stripe = [StripeButtonType]
// MARK: - Delegate
protocol ButtonsStripeViewDelegate: class {
func buttonsStripe(_ stripe: ButtonsStripeView, didTapButton button: StripeButtonType)
}
// MARK: - View
class ButtonsStripeView: UIView {
// MARK: IBOutlet
@IBOutlet weak var stripeStackView: UIStackView!
// MARK: Properties
weak var delegate: ButtonsStripeViewDelegate?
private var buttons: [RoundedButton]? = nil
var stripe: Stripe? = nil {
didSet {
for aView in stripeStackView.subviews {
aView.removeFromSuperview()
}
guard let stripe = stripe else {
stripeStackView.addArrangedSubview(UIView())
buttons = nil
return
}
buttons = [RoundedButton]()
for aButton in stripe {
let button = RoundedButton()
button.tag = aButton.rawValue
button.addTarget(self, action: #selector(buttonTapped(_:)), for: .touchUpInside)
button.setImage(aButton.image, for: .normal)
button.imageView!.contentMode = .scaleAspectFit
button.clipsToBounds = true
button.normalBackgroundColor = buttonsNormalColor
button.highlightedBackgroundColor = buttonsHighlightedColor
button.backgroundColor = buttonsNormalColor
button.roundingMode = buttonsRoundingMode
button.layer.borderWidth = buttonsBorderWidth
button.layer.borderColor = buttonsBorderColor?.cgColor
button.heightAnchor.constraint(equalToConstant: buttonsSize).isActive = true
button.widthAnchor.constraint(equalToConstant: buttonsSize).isActive = true
button.constraints.forEach({$0.identifier = "wh"})
stripeStackView.addArrangedSubview(button)
buttons?.append(button)
}
}
}
// MARK: Buttons properties
var buttonsBorderColor: UIColor? = nil {
didSet {
if let buttons = buttons {
buttons.forEach { $0.borderColor = buttonsBorderColor }
}
}
}
var buttonsBorderWidth: CGFloat = 0.0 {
didSet {
if let buttons = buttons {
buttons.forEach { $0.borderWidth = buttonsBorderWidth }
}
}
}
var buttonsRoundingMode: RoundingMode = .none {
didSet {
if let buttons = buttons {
buttons.forEach { $0.roundingMode = buttonsRoundingMode }
}
}
}
var buttonsNormalColor: UIColor? = nil {
didSet {
if let buttons = buttons {
buttons.forEach { $0.normalBackgroundColor = buttonsNormalColor }
}
}
}
var buttonsHighlightedColor: UIColor? = nil {
didSet {
if let buttons = buttons {
buttons.forEach { $0.highlightedBackgroundColor = buttonsHighlightedColor }
}
}
}
var buttonsSize: CGFloat = 50.0 {
didSet {
buttons?.flatMap({ $0.constraints }).filter({ $0.identifier == "wh" }).forEach({ $0.constant = buttonsSize })
}
}
// MARK: Delegate
@objc private func buttonTapped(_ sender: UIButton) {
if let button = StripeButtonType(rawValue: sender.tag) {
delegate?.buttonsStripe(self, didTapButton: button)
}
}
}
// MARK: Adamant config
extension ButtonsStripeView {
static let adamantDefaultHeight: CGFloat = 85
static func adamantConfigured() -> ButtonsStripeView {
guard let view = UINib(nibName: "ButtonsStripe", bundle: nil).instantiate(withOwner: nil, options: nil).first as? ButtonsStripeView else {
fatalError("Can't get UINib")
}
view.buttonsBorderColor = UIColor.adamantSecondary
view.buttonsBorderWidth = 1
view.buttonsSize = 50
view.buttonsRoundingMode = .customRadius(radius: 13)
view.buttonsHighlightedColor = UIColor.adamantPinpadHighlightButton
view.buttonsNormalColor = .white
view.stripeStackView.spacing = 15
return view
}
}
|
//
// EFCollectionViewCell.swift
// lovegift
//
// Created by Eduardo Façanha on 30/08/18.
// Copyright © 2018 Eduardo Façanha. All rights reserved.
//
import UIKit
class EFGiftCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var imageView: EFImageView!
@IBOutlet weak var nameLabel: UILabel!
}
|
//
// MainMenuCoordinator.swift
// Lowes Presentation
//
// Created by Josh Jaslow on 6/29/20.
// Copyright © 2020 Josh Jaslow. All rights reserved.
//
import UIKit
class MainMenuCoordinator: NSObject, Coordinator, UINavigationControllerDelegate {
weak var parentCoordinator: Coordinator?
var childCoordinators = [Coordinator]()
var navigationController: UINavigationController
var viewModel: MainMenuViewModel?
required init(navigationController: UINavigationController, parentCoordinator: Coordinator?) {
self.navigationController = navigationController
self.parentCoordinator = parentCoordinator
}
func start() {
navigationController.delegate = self
let vc = MainMenuViewController.instantiate()
let vm = MainMenuViewModel(viewController: vc,
coordinator: self)
vc.viewModel = vm
self.viewModel = vm
vc.coordinator = self
navigationController.pushViewController(vc, animated: false)
}
func addShadow(for views: UIView...) {
guard let vm = viewModel else { return }
views.forEach {
vm.addShadow(for: $0)
} //Cannot pass array of type '[UIButton]' as variadic arguments of type 'UIButton' --> Unfortunately can't pass 1 variadic function into another
}
func showJoshPages() {
let child = PageViewControllerCoordinator(navigationController: navigationController,
parentCoordinator: self)
childCoordinators.append(child)
child.start()
}
func showJasminePages() {
let child = JasminePageViewControllerCoordinator(navigationController: navigationController, parentCoordinator: self)
child.parentCoordinator = self
childCoordinators.append(child)
child.start()
}
func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {
guard let fromViewController = navigationController.transitionCoordinator?.viewController(forKey: .from) else {
return
}
if navigationController.viewControllers.contains(fromViewController) {
return
}
}
}
|
//
// TextFieldMod.swift
// SimpleGroceryList
//
// Created by Payton Sides on 6/11/21.
//
import SwiftUI
import UIKit
@available(iOS 13.0, *)
extension CustomTextField {
/// Sets the maximum amount of characters allowed in this text field.
/// - Parameter limit: the maximum amount of characters allowed
/// - Returns: An updated text field limited to limit
public func characterLimit(_ limit: Int?) -> CustomTextField {
var view = self
view.characterLimit = limit
return view
}
/// Modifies the text field’s **font** from a `UIFont` object.
/// - Parameter font: The desired font
/// - Returns: An updated text field using the desired font
/// - Warning: Accepts a `UIFont` object rather than SwiftUI `Font`
/// - SeeAlso: [`UIFont`](https://developer.apple.com/documentation/uikit/uifont)
public func fontFromUIFont(_ font: UIFont?) -> CustomTextField {
var view = self
view.font = font
return view
}
/// Modifies the **text color** of the text field.
/// - Parameter color: The desired text color
/// - Returns: An updated text field using the desired text color
@available(iOS 13, *)
public func foregroundColor(_ color: Color?) -> CustomTextField {
var view = self
if let color = color {
view.foregroundColor = UIColor.from(color: color)
}
return view
}
/// Modifies the **cursor color** of the text field
/// - Parameter accentColor: The cursor color
/// - Returns: A phone number text field with updated cursor color
@available(iOS 13, *)
public func accentColor(_ accentColor: Color?) -> CustomTextField {
var view = self
if let accentColor = accentColor {
view.accentColor = UIColor.from(color: accentColor)
}
return view
}
/// Modifies the **text alignment** of a text field.
/// - Parameter alignment: The desired text alignment
/// - Returns: An updated text field using the desired text alignment
public func multilineTextAlignment(_ alignment: TextAlignment) -> CustomTextField {
var view = self
switch alignment {
case .leading:
view.textAlignment = layoutDirection ~= .leftToRight ? .left : .right
case .trailing:
view.textAlignment = layoutDirection ~= .leftToRight ? .right : .left
case .center:
view.textAlignment = .center
}
return view
}
/// Modifies the **content type** of a text field.
/// - Parameter textContentType: The type of text being inputted into the text field
/// - Returns: An updated text field using the desired text content type
public func textContentType(_ textContentType: UITextContentType?) -> CustomTextField {
var view = self
view.contentType = textContentType
return view
}
/// Modifies the text field’s **autocorrection** settings.
/// - Parameter disable: Whether autocorrection should be disabled
/// - Returns: An updated text field using the desired autocorrection settings
public func disableAutocorrection(_ disable: Bool?) -> CustomTextField {
var view = self
if let disable = disable {
view.autocorrection = disable ? .no : .yes
} else {
view.autocorrection = .default
}
return view
}
/// Modifies the text field’s **autocapitalization** style.
/// - Parameter style: What types of characters should be autocapitalized
/// - Returns: An updated text field using the desired autocapitalization style
public func autocapitalization(_ style: UITextAutocapitalizationType) -> CustomTextField {
var view = self
view.autocapitalization = style
return view
}
/// Modifies the text field’s **keyboard type**.
/// - Parameter type: The type of keyboard that the user should get to type in the text field
/// - Returns: An updated text field using the desired keyboard type
public func keyboardType(_ type: UIKeyboardType) -> CustomTextField {
var view = self
view.keyboardType = type
return view
}
/// Modifies the text field’s **return key** type.
/// - Parameter type: The type of return key the user should get on the keyboard when using this text field
/// - Returns: An updated text field using the desired return key type
public func returnKeyType(_ type: UIReturnKeyType) -> CustomTextField {
var view = self
view.returnKeyType = type
return view
}
/// Modifies the text field’s **secure entry** settings.
/// - Parameter isSecure: Whether the text field should hide the entered characters as dots
/// - Returns: An updated text field using the desired secure entry settings
public func isSecure(_ isSecure: Bool) -> CustomTextField {
var view = self
view.isSecure = isSecure
return view
}
/// Modifies the **clear-on-begin-editing** setting of a text field.
/// - Parameter shouldClear: Whether the text field should clear on editing beginning
/// - Returns: A text field with updated clear-on-begin-editing settings
public func clearsOnBeginEditing(_ shouldClear: Bool) -> CustomTextField {
var view = self
view.clearsOnBeginEditing = shouldClear
return view
}
/// Modifies the **clear-on-insertion** setting of a text field.
/// - Parameter shouldClear: Whether the text field should clear on insertion
/// - Returns: A text field with updated clear-on-insertion settings
public func clearsOnInsertion(_ shouldClear: Bool) -> CustomTextField {
var view = self
view.clearsOnInsertion = shouldClear
return view
}
/// Modifies whether and when the text field **clear button** appears on the view.
/// - Parameter showsButton: Whether the clear button should be visible
/// - Returns: A text field with updated clear button settings
public func showsClearButton(_ showsButton: Bool) -> CustomTextField {
var view = self
view.clearButtonMode = showsButton ? .always : .never
return view
}
/// Modifies whether the text field is **disabled**.
/// - Parameter disabled: Whether the text field is disabled
/// - Returns: A text field with updated disabled settings
public func disabled(_ disabled: Bool) -> CustomTextField {
var view = self
view.isUserInteractionEnabled = !disabled
return view
}
/// Modifies the text field's **password rules** . Sets secure entry to `true`.
/// - Parameter rules: The text field's password rules.
/// - Returns: A text field with updated password rules
public func passwordRules(_ rules: UITextInputPasswordRules) -> CustomTextField {
var view = self
view.isSecure = true
view.passwordRules = rules
return view
}
/// Modifies whether the text field includes **smart dashes**.
/// - Parameter smartDashes: Whether the text field includes smart dashes. Does nothing if `nil`.
/// - Returns: A text field with the updated smart dashes settings.
public func smartDashes(_ smartDashes: Bool? = nil) -> CustomTextField {
var view = self
if let smartDashes = smartDashes {
view.smartDashesType = smartDashes ? .yes : .no
}
return view
}
/// Modifies whether the text field uses **smart insert-delete**.
/// - Parameter smartInsertDelete: Whether the text field uses smart insert-delete. Does nothing if `nil`.
/// - Returns: A text field with the updated smart insert-delete settings.
public func smartInsertDelete(_ smartInsertDelete: Bool? = nil) -> CustomTextField {
var view = self
if let smartInsertDelete = smartInsertDelete {
view.smartInsertDeleteType = smartInsertDelete ? .yes : .no
}
return view
}
/// Modifies whether the text field uses **smart quotes**.
/// - Parameter smartQuotes: Whether the text field uses smart quotes. Does nothing if `nil`.
/// - Returns: A text field with the updated smart quotes settings
public func smartQuotes(_ smartQuotes: Bool? = nil) -> CustomTextField {
var view = self
if let smartQuotes = smartQuotes {
view.smartQuotesType = smartQuotes ? .yes : .no
}
return view
}
/// Modifies whether the text field should check the user's **spelling**
/// - Parameter spellChecking: Whether the text field should check the user's spelling. Does nothing if `nil`.
/// - Returns: A text field with updated spell checking settings
public func spellChecking(_ spellChecking: Bool? = nil) -> CustomTextField {
var view = self
if let spellChecking = spellChecking {
view.spellCheckingType = spellChecking ? .yes : .no
}
return view
}
/// Modifies the function called when text editing **begins**.
/// - Parameter action: The function called when text editing begins. Does nothing if `nil`.
/// - Returns: An updated text field using the desired function called when text editing begins
public func onEditingBegan(perform action: (() -> Void)? = nil) -> CustomTextField {
var view = self
if let action = action {
view.didBeginEditing = action
}
return view
}
/// Modifies the function called when the user makes any **changes** to the text in the text field.
/// - Parameter action: The function called when the user makes any changes to the text in the text field. Does nothing if `nil`.
/// - Returns: An updated text field using the desired function called when the user makes any changes to the text in the text field
public func onEdit(perform action: (() -> Void)? = nil) -> CustomTextField {
var view = self
if let action = action {
view.didChange = action
}
return view
}
/// Modifies the function called when text editing **ends**. 🔚
/// - Parameter action: The function called when text editing ends. Does nothing if `nil`.
/// - Returns: An updated text field using the desired function called when text editing ends
public func onEditingEnded(perform action: (() -> Void)? = nil) -> CustomTextField {
var view = self
if let action = action {
view.didEndEditing = action
}
return view
}
/// Modifies the function called when the user presses the return key.
/// - Parameter action: The function called when the user presses the return key. Does nothing if `nil`.
/// - Returns: An updated text field using the desired funtion called when the user presses the return key
public func onReturn(perform action: (() -> Void)? = nil) -> CustomTextField {
var view = self
if let action = action {
view.shouldReturn = action
}
return view
}
/// Modifies the function called when the user clears the text field.
/// - Parameter action: The function called when the user clears the text field. Does nothing if `nil`.
/// - Returns: An updated text field using the desired function called when the user clears the text field
public func onClear(perform action: (() -> Void)? = nil) -> CustomTextField {
var view = self
if let action = action {
view.shouldClear = action
}
return view
}
/// Gives the text field a default style.
/// - Parameters:
/// - height: How tall the text field should be, in points. Defaults to 58.
/// - backgroundColor: The background color of the text field. Defaults to clear.
/// - accentColor: The cursor and highlighting color of the text field. Defaults to light blue.
/// - inputFont: The font of the text field
/// - paddingLeading: Leading-edge padding size, in points. Defaults to 25.
/// - cornerRadius: Text field corner radius. Defaults to 6.
/// - hasShadow: Whether or not the text field has a shadow when selected. Defaults to true.
/// - Returns: A stylized view containing a text field.
public func style(height: CGFloat = 58,
backgroundColor: Color? = nil,
accentColor: Color = Color(red: 0.30, green: 0.76, blue: 0.85),
font inputFont: UIFont? = nil,
paddingLeading: CGFloat = 25,
cornerRadius: CGFloat = 6,
hasShadow: Bool = true,
image: Image? = nil) -> some View
{
var darkMode: Bool { colorScheme == .dark }
let cursorColor: Color = accentColor
let height: CGFloat = height
let leadingPadding: CGFloat = paddingLeading
var backgroundGray: Double { darkMode ? 0.25 : 0.95 }
let backgroundColor: Color = backgroundColor ?? .init(white: backgroundGray)
// {
// if backgroundColor != nil {
// return backgroundColor ?? .init(white: backgroundGray)
// } else {
// return .init(white: backgroundGray)
// }
// }
var shadowOpacity: Double { (designEditing && hasShadow) ? 0.5 : 0 }
var shadowGray: Double { darkMode ? 0.8 : 0.5 }
var shadowColor: Color { Color(white: shadowGray).opacity(shadowOpacity) }
var borderColor: Color {
designEditing && darkMode ? .init(white: 0.6) : .clear
}
var font: UIFont {
if let inputFont = inputFont {
return inputFont
} else {
let fontSize: CGFloat = 20
let systemFont = UIFont.systemFont(ofSize: fontSize, weight: .regular)
if let descriptor = systemFont.fontDescriptor.withDesign(.rounded) {
return UIFont(descriptor: descriptor, size: fontSize)
} else {
return systemFont
}
}
}
return ZStack {
HStack {
if let image = image {
image
}
self
.accentColor(cursorColor)
.fontFromUIFont(font)
}
.padding(.horizontal, leadingPadding)
}
.frame(height: height)
.background(backgroundColor)
.cornerRadius(cornerRadius)
.overlay(RoundedRectangle(cornerRadius: cornerRadius).stroke(borderColor))
.padding(.horizontal, leadingPadding)
.shadow(color: shadowColor, radius: 5, x: 0, y: 4)
}
/// Since Apple has not given us a way yet to parse a `Font` object, this function must be deprecated . Please use `.fontFromUIFont(_:)` instead .
/// - Parameter font:
/// - Returns:
@available(*, deprecated, renamed: "fontFromUIFont", message: "At this time, Apple will not let us parse a `Font` object Please use `.fontFromUIFont(_:)` instead.")
public func font(_ font: Font?) -> some View { return EmptyView() }
}
|
//
// AllUsersSongsAllUsersSongsRouter.swift
// SongGuesser
//
// Created by Denis Zhukoborsky on 06/08/2019.
// Copyright © 2019 denis.zhukoborsky. All rights reserved.
//
import Foundation
import UIKit
class AllUsersSongsRouter: AllUsersSongsRouterProtocol {
weak var viewController: AllUsersSongsViewController!
init(viewController: AllUsersSongsViewController) {
self.viewController = viewController
}
func moveToSongInfo() {
viewController.performSegue(withIdentifier: "fromRecentlyFoundSongsToSongInfo", sender: nil)
}
}
|
import Foundation
/// :nodoc:
extension NSMutableData {
func appendString(_ string: String) {
let data = string.data(using: .utf8, allowLossyConversion: false)
append(data!)
}
}
/// :nodoc:
public struct BodyParameterEncoder: ParameterEncoder {
public func encode(urlRequest: inout URLRequest, with parameters: Parameters) throws {
do {
let contentType = urlRequest.value(forHTTPHeaderField: "Content-Type")
if contentType == "application/json" {
let data = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
urlRequest.httpBody = data
} else if contentType == "application/x-www-form-urlencoded" {
let query = (parameters.compactMap({ (key, value) -> String in
return "\(key)=\(value)"
}) as Array).joined(separator: "&")
let data = query.data(using: .utf8, allowLossyConversion: false)
urlRequest.httpBody = data
} else {
guard let boundary = parameters["boundary"] as? String else {
throw EncoderError.encodingFailed
}
let body = NSMutableData()
let boundaryPrefix = "--\(boundary)\r\n"
if let params = parameters["dict"] as? Parameters {
for (key, value) in params {
body.appendString(boundaryPrefix)
body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
body.appendString("\(value)\r\n")
}
}
body.appendString(boundaryPrefix)
if let mimeType = parameters["mimeType"] as? String, let filename = parameters["filename"] as? String, let data = parameters["data"] as? Data {
body.appendString("Content-Disposition: form-data; name=\"image\"; filename=\"\(filename)\"\r\n")
body.appendString("Content-Type: \(mimeType)\r\n\r\n")
body.append(data)
}
body.appendString("\r\n")
body.appendString("--".appending(boundary.appending("--")))
urlRequest.httpBody = body as Data
}
} catch {
throw EncoderError.encodingFailed
}
}
}
|
//
// FlowSignUpAndConfrim.swift
// Prayer App
//
// Created by tomrunnels on 3/18/21.
//
import SwiftUI
import Combine
import Amplify
import AmplifyPlugins
struct FlowSignUpAndConfrim: View {
@EnvironmentObject var sessionManager: AuthSessionManager
@Binding var showThisSheet : Bool
@State var username : String = ""
@State var email : String = ""
@State var password : String = ""
@State var code : String = ""
@State var isConfirmView = false
@State var feedback: String = ""
// @ObservedObject private var userData: SessionData = .shared
var body: some View {
switch (isConfirmView) {
//if confirm is not ready, show signup
case false:
FakeFormView(viewTitle: "Sign Up", spacer: 40) {
Text(feedback).font(.caption).foregroundColor(.red)
FakeFormField(sectionText: "Username", placeholderText: "prayermaster500", text: $username)
.padding(.bottom, 20)
FakeFormField(sectionText: "Email", placeholderText: "pm500@gmail.com", text: $email)
.padding(.bottom, 20)
FakeFormField(sectionText: "password", placeholderText: "PM501pa$$", text: $password)
.padding(.bottom, 20)
Spacer()
.frame(height:25)
VStack {
Button(action: {
handleSignUp(username: self.username, password: self.password, email: self.email, returnBool: $isConfirmView, feedback: $feedback)
}
){
Text("Sign Up")
.padding()
.foregroundColor(.black)
.background(Color("Element"))
.cornerRadius(30)
.scaleEffect(1.2)
}
Spacer()
Button(action: {
print("login pressed on signin screen")
}, label: {
Text("Already have an account? Log in")
}).padding(.bottom)
}
}
case true:
FakeFormView(viewTitle: "Verify Email Address", spacer: 40) {
Text(feedback).font(.caption).foregroundColor(.red)
VStack {
HStack {
Text("for: ").font(.subheadline)
Text(username).font(.title)
}
Spacer()
FakeFormField(sectionText: "Confirmation Code", placeholderText: "012345", text: $code)
.padding(.bottom, 20)
Button(action: {
handleConfirm(for: username, with: self.code, confirmFailed: $showThisSheet, feedback: $feedback)
}
){
Text("Confirm")
.padding()
.foregroundColor(.black)
.background(Color("Element"))
.cornerRadius(30)
.scaleEffect(1.2)
}
Spacer()
Spacer()
Spacer()
}
}
}
}
// ///came from https://docs.amplify.aws/lib/auth/signin/q/platform/ios#register-a-user
func handleSignUp(username: String, password: String, email: String, returnBool: Binding<Bool>, feedback: Binding<String>) {
//TODO: email addresses are not totally verified by AWS. YOu can do it without a period
let userAttributes = [AuthUserAttribute(.email, value: email)]
let options = AuthSignUpRequest.Options(userAttributes: userAttributes)
Amplify.Auth.signUp(username: username, password: password, options: options) { result in
switch result {
case .success(let signUpResult):
if case let .confirmUser(deliveryDetails, _) = signUpResult.nextStep {
print("Delivery details \(String(describing: deliveryDetails))")
returnBool.wrappedValue = true
feedback.wrappedValue = ""
} else {
print("SignUp Complete")
returnBool.wrappedValue = true
feedback.wrappedValue = ""
}
case .failure(let error):
print("An error occurred while registering a user \(error)")
returnBool.wrappedValue = false
feedback.wrappedValue = "\(error)"
}
}
}
/// came from https://docs.amplify.aws/lib/auth/signin/q/platform/ios#register-a-user
func handleConfirm(for username: String, with confirmationCode: String, confirmFailed: Binding<Bool>, feedback: Binding<String>) {
Amplify.Auth.confirmSignUp(for: username, confirmationCode: confirmationCode) { result in
switch result {
case .success:
print("Confirm signUp succeeded")
print(result)
//TODO: Create new PrayerAppAPI User on AuthUser creation
confirmFailed.wrappedValue = false
feedback.wrappedValue = ""
case .failure(let error):
print("An error occurred while confirming sign up \(error)")
confirmFailed.wrappedValue = true
feedback.wrappedValue = "\(error)"
}
}
}
// func loadUserFromAuthID (userIDFromAuth: String) {
// Amplify.DataStore.query(
// User.self,
// where: User.keys.id == userIDFromAuth
// ) { result in
// do {
// let thisUser = try result.get()
//
// print("User has been found:::\(1)")
// } catch {
// print(error)
// }
// }
// }
}
struct FlowSignUpAndConfrim_Previews: PreviewProvider {
static var previews: some View {
SignUpView()
}
}
|
//
// Item.swift
// Todoey
//
// Created by Jared Talbert on 4/25/19.
// Copyright © 2019 Jared Talbert. All rights reserved.
//
import Foundation
import RealmSwift
class Item: Object {
@objc dynamic var title: String = ""
@objc dynamic var isDone: Bool = false
@objc dynamic var currentDate: Date = Date()
// creates a "one-to-one" relationship from items to category
var parentCategory = LinkingObjects(fromType: Category.self, property: "items")
}
|
//
// ProjectsTableViewCell.swift
// Developlan
//
// Created by Artem Nazarov on 5/1/17.
// Copyright © 2017 APPSkill. All rights reserved.
//
import UIKit
class ProjectsTableViewCell: UITableViewCell {
@IBOutlet weak var projectName: UILabel!
@IBOutlet weak var dateCreated: UILabel!
}
|
//
// FriendListTableViewController.swift
// Friends
//
// Created by Maria on 5/26/17.
// Copyright © 2017 Maria Notohusodo. All rights reserved.
//
import UIKit
import CoreData
class FriendListTableViewController: UITableViewController {
var coreDataStack: CoreDataStack!
var friendList: NSFetchedResultsController<Friend> = NSFetchedResultsController()
override func viewDidLoad() {
super.viewDidLoad()
friendList = friendListFetchedResultsController()
}
func friendListFetchedResultsController() -> NSFetchedResultsController<Friend> {
let fetchedResultController = NSFetchedResultsController(fetchRequest: friendFetchRequest(), managedObjectContext: coreDataStack.mainContext, sectionNameKeyPath: nil, cacheName: nil)
fetchedResultController.delegate = self
do {
try fetchedResultController.performFetch()
} catch let error as NSError {
fatalError("Error: \(error.localizedDescription)")
}
return fetchedResultController
}
func friendFetchRequest() -> NSFetchRequest<Friend> {
let fetchRequest = NSFetchRequest<Friend>(entityName: "Friend")
fetchRequest.fetchBatchSize = 20
let sortDescriptor = NSSortDescriptor(key: "last", ascending: false)
fetchRequest.sortDescriptors = [sortDescriptor]
return fetchRequest
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func numberOfSections(in tableView: UITableView) -> Int {
return friendList.sections?.count ?? 0
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return friendList.sections?[section].numberOfObjects ?? 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
let friend = friendList.object(at: indexPath)
cell.textLabel?.text = friend.first
cell.detailTextLabel?.text = friend.last
return cell
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "detailFriend" {
guard let navigationController = segue.destination as? UINavigationController,
let detailViewController = navigationController.topViewController as? FriendDetailTableViewController,
let indexPath = tableView.indexPathForSelectedRow else {
fatalError("Application storyboard mis-configuration")
}
let friend = friendList.object(at: indexPath)
let childContext =
NSManagedObjectContext(
concurrencyType: .mainQueueConcurrencyType)
childContext.parent = coreDataStack.mainContext
let childEntry =
childContext.object(with: friend.objectID)
as? Friend
detailViewController.friend = childEntry
detailViewController.context = childContext
detailViewController.delegate = self
} else if segue.identifier == "addFriend" {
guard let navigationController = segue.destination as? UINavigationController,
let detailViewController = navigationController.topViewController as? FriendDetailTableViewController else {
fatalError("Application storyboard mis-configuration")
}
let childContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
childContext.parent = coreDataStack.mainContext
let newFriend = Friend(context: childContext)
detailViewController.friend = newFriend
detailViewController.context = childContext
detailViewController.delegate = self
}
}
}
extension FriendListTableViewController: NSFetchedResultsControllerDelegate {
public func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
tableView.beginUpdates()
}
public func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) {
switch type {
case .insert: tableView.insertSections([sectionIndex], with: .fade)
case .delete: tableView.deleteSections([sectionIndex], with: .fade)
default: break
}
}
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
switch type {
case .insert:
tableView.insertRows(at: [newIndexPath!], with: .fade)
case .delete:
tableView.deleteRows(at: [indexPath!], with: .fade)
case .update:
tableView.reloadRows(at: [indexPath!], with: .fade)
case .move:
tableView.deleteRows(at: [indexPath!], with: .fade)
tableView.insertRows(at: [newIndexPath!], with: .fade)
}
}
public func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
tableView.endUpdates()
}
}
extension FriendListTableViewController: FriendDetailDelegate {
func didFinish(viewController: FriendDetailTableViewController, didSave: Bool) {
guard didSave,
let context = viewController.context,
context.hasChanges else {
dismiss(animated: true)
return
}
context.perform {
do {
try context.save()
} catch let error as NSError {
fatalError("Error: \(error.localizedDescription)")
}
self.coreDataStack.saveContext()
}
dismiss(animated: true)
}
}
|
//
// SetDashboardVc.swift
// KayakFirst Ergometer E2
//
// Created by Balazs Vidumanszki on 2017. 02. 17..
// Copyright © 2017. Balazs Vidumanszki. All rights reserved.
//
import UIKit
class SetDashboardVc: BaseTrainingVc<VcSetDashboardLayout> {
//MARK: properties
private var dragDropHelper: DragDropDashboardHelper!
//MARK: views
override func initView() {
super.initView()
contentLayout?.btnDone.target = self
contentLayout?.btnDone.action = #selector(btnDoneClick)
dragDropHelper = DragDropDashboardHelper(contentLayout: contentLayout!)
}
override func getContentLayout(contentView: UIView) -> VcSetDashboardLayout {
return VcSetDashboardLayout(contentView: contentView, showPullForceLayout: getTrainingEnvType() == TrainingEnvironmentType.ergometer)
}
override func initTabBarItems() {
let buttons: [UIBarButtonItem] = [contentLayout!.btnDone]
handleBluetoothMenu(barButtons: buttons, badGpsTabBarItem: nil)
showCloseButton()
showLogoOnLeft()
self.title = getString("navigation_set_dashboard")
}
//MARK: button listeners
@objc private func btnDoneClick() {
getTrainingVc().showDashboardVc(dashboardLayoutDict: dragDropHelper.dashboardLayoutDict)
}
}
|
//
// ArrayTests.swift
// ListableUI-Unit-Tests
//
// Created by Kyle Van Essen on 11/22/19.
//
import XCTest
@testable import ListableUI
class ArrayTests: XCTestCase
{
func test_forEachWithIndex()
{
let array = ["first", "second", "third"]
var iterations = [Iteration]()
array.forEachWithIndex { index, isLast, value in
iterations.append(Iteration(index: index, isLast: isLast, value: value))
}
XCTAssertEqual(iterations, [
Iteration(index: 0, isLast: false, value: "first"),
Iteration(index: 1, isLast: false, value: "second"),
Iteration(index: 2, isLast: true, value: "third"),
])
struct Iteration : Equatable
{
var index : Int
var isLast : Bool
var value : String
}
}
func test_mapWithIndex()
{
let array = [1, 2, 3]
var iterations = [Iteration]()
let mapped : [String] = array.mapWithIndex { index, isLast, value in
iterations.append(Iteration(index: index, isLast: isLast, value: value))
return String(value)
}
XCTAssertEqual(mapped, [
"1",
"2",
"3"
])
XCTAssertEqual(iterations, [
Iteration(index: 0, isLast: false, value: 1),
Iteration(index: 1, isLast: false, value: 2),
Iteration(index: 2, isLast: true, value: 3),
])
struct Iteration : Equatable
{
var index : Int
var isLast : Bool
var value : Int
}
}
func test_compactMapWithIndex()
{
let array = [1, nil, 3, 4]
var iterations = [Iteration]()
let mapped : [String] = array.compactMapWithIndex { index, isLast, value in
iterations.append(Iteration(index: index, isLast: isLast, value: value))
if let value = value {
return String(value)
} else {
return nil
}
}
XCTAssertEqual(mapped, [
"1",
"3",
"4"
])
XCTAssertEqual(iterations, [
Iteration(index: 0, isLast: false, value: 1),
Iteration(index: 1, isLast: false, value: nil),
Iteration(index: 2, isLast: false, value: 3),
Iteration(index: 3, isLast: true, value: 4)
])
struct Iteration : Equatable
{
var index : Int
var isLast : Bool
var value : Int?
}
}
}
|
import Guaka
import SwiftbrewCore
var rootCommand = Command(
usage: "swift-brew",
configuration: configuration,
run: nil
)
private func configuration(command: Command) {
command.add(flags: [
.init(shortName: "v",
longName: "version",
value: false,
description: "Print the version",
inheritable: true)
])
command.inheritablePreRun = { flags, args in
if let versionFlag = flags.getBool(name: "version"), versionFlag == true {
print(SwiftbrewCore.version)
return false
}
return true
}
}
private func run(flags: Flags, args: [String]) {
}
|
//
// IconSettingVC.swift
// ELRDRG
//
// Created by Jonas Wehner on 06.01.23.
// Copyright © 2023 Jonas Wehner. All rights reserved.
//
import Foundation
import UIKit
import SwiftUI
public class IconSettingVC : UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate{
@IBOutlet weak var imgRTW: UIImageView!
@IBOutlet weak var imgKTW: UIImageView!
@IBOutlet weak var imgNEF: UIImageView!
@IBOutlet weak var imgRTH: UIImageView!
var editingIcon : iconType = .none
enum iconType{
case none
case RTW
case NEF
case KTW
case RTH
}
public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let image = (info[.editedImage] as? UIImage)
{
changeIcon(image: image)
}
picker.dismiss(animated: true)
}
func changeIcon(image : UIImage)
{
let data = image.pngData()
let settings = SettingsHandler().getSettings()
switch editingIcon
{
case .none:
return
case .RTW:
settings.imageRTW = data
imgRTW.image = image
case .NEF:
settings.imageNEF = data
imgNEF.image = image
case .RTH:
settings.imageRTH = data
imgRTH.image = image
case .KTW:
settings.imageKTW = data
imgKTW.image = image
}
_ = SettingsHandler().save()
}
func resetIcon(type : iconType)
{
let settings = SettingsHandler().getSettings()
switch type
{
case .none:
return
case .RTW:
settings.imageRTW = nil
case .NEF:
settings.imageNEF = nil
case .RTH:
settings.imageRTH = nil
case .KTW:
settings.imageKTW = nil
}
_ = SettingsHandler().save()
self.viewDidLoad()
}
func createPicker()->UIImagePickerController
{
let pickerController = UIImagePickerController()
pickerController.delegate = self
pickerController.allowsEditing = true
pickerController.mediaTypes = ["public.image"]
pickerController.sourceType = .photoLibrary
return pickerController
}
func pick(type : iconType)
{
self.editingIcon = type
let picker = createPicker()
self.present(picker, animated: true)
}
@IBAction func cmdRTW(_ sender: Any) {
pick(type: .RTW)
}
@IBAction func cmdResetRTW(_ sender: Any) {
resetIcon(type: .RTW)
}
@IBAction func cmdKTW(_ sender: Any) {
pick(type: .KTW)
}
@IBAction func cmdResetKTW(_ sender: Any) {
resetIcon(type: .KTW)
}
@IBAction func cmdNEF(_ sender: Any) {
pick(type: .NEF)
}
@IBAction func cmdResetNEF(_ sender: Any) {
resetIcon(type: .NEF)
}
@IBAction func cmdRTH(_ sender: Any) {
pick(type: .RTH)
}
@IBAction func cmdResetRTH(_ sender: Any) {
resetIcon(type: .RTH)
}
public override func viewDidLoad() {
if let img = BaseUnit.getImage(type: UnitHandler.UnitType.RTW.rawValue)
{
imgRTW.image = img
}
if let img = BaseUnit.getImage(type: UnitHandler.UnitType.KTW.rawValue)
{
imgKTW.image = img
}
if let img = BaseUnit.getImage(type: UnitHandler.UnitType.NEF.rawValue)
{
imgNEF.image = img
}
if let img = BaseUnit.getImage(type: UnitHandler.UnitType.RTH.rawValue)
{
imgRTH.image = img
}
}
}
|
//
// CompanyInfoView.swift
// SpaceX
//
// Created by Carmelo Ruymán Quintana Santana on 25/2/21.
//
import SwiftUI
import SpaceXApi
struct CompanyInfoView: View {
@StateObject var companyInfoService: CompanyInfoService
var body: some View {
Form {
if let info = companyInfoService.company {
basicInfo(info: info)
people(info: info)
headquarters(headquarters: info.headquarters)
} else {
Text("Loading...") .onAppear(perform: {
companyInfoService.getCompanyInfo()
})
}
}.navigationTitle("Company info")
}
private func basicInfo(info: CompanyInfoDTO) -> some View {
Section(header: Text("Info")) {
Text(info.name).font(.largeTitle)
Text(info.summary).fixedSize(horizontal: false, vertical: true)
}
}
private func people(info: CompanyInfoDTO) -> some View {
Section(header: Text("People")) {
CustomSection(title: "Founder") {
Text(info.founder)
}
CustomSection(title: "CEO") {
Text(info.ceo)
}
CustomSection(title: "CTO") {
Text(info.cto)
}
CustomSection(title: "COO") {
Text(info.coo)
}
CustomSection(title: "CTO PROPULSION") {
Text(info.cto_propulsion)
}
}
}
private func headquarters(headquarters: HeadquartersDTO) -> some View {
Section(header: Text("Headquarters")) {
CustomSection(title: "State") {
Text(headquarters.state)
}
CustomSection(title: "City") {
Text(headquarters.city)
}
CustomSection(title: "Adress") {
Text(headquarters.address)
}
}
}
}
// struct CompanyInfoView_Previews: PreviewProvider {
// static var previews: some View {
// CompanyInfoView()
// }
// }
|
//
// ViewController.swift
// ActionKit
//
// Created by Kevin Choi, Benjamin Hendricks on 7/17/14.
// Licensed under the terms of the MIT license
//
import UIKit
import ActionKit
class ViewController: UIViewController {
// Test buttons used for our implementation of target action
@IBOutlet var testButton: UIButton!
@IBOutlet var testButton2: UIButton!
// Test buttons used for a regular usage of target action without ActionKit
@IBOutlet var oldTestButton: UIButton!
@IBOutlet var oldTestButton2: UIButton!
// Part of making old test button changed to tapped. This is what ActionKit tries to avoid doing
// by removing the need to explicitly declare selector functions when a closure is all that's needed
func tappedSelector(sender: UIButton!) {
self.oldTestButton.setTitle("Old Tapped!", forState: .Normal)
}
override func viewDidLoad() {
super.viewDidLoad()
// This is equivalent to oldTestButton's implementation of setting the action to Tapped
testButton.addControlEvent(.TouchUpInside) {
self.testButton.setTitle("Tapped!", forState: .Normal)
}
oldTestButton.addTarget(self, action: Selector("tappedSelector:"), forControlEvents: .TouchUpInside)
var tgr = UITapGestureRecognizer(name: "setRed") {
self.view.backgroundColor = UIColor.redColor()
}
// The following three lines will replace the action for the red color gesture recognizer to just change the text of the first test button only. Only one action per gesture recognizer (or a control event for that matter)
// More actions per gesture recognizer and for control events are in the works.
tgr.addClosure("setButton1") {
self.testButton.setTitle("tapped once on the screen!", forState: .Normal)
}
var dtgr = UITapGestureRecognizer(name: "setYellow") {
self.view.backgroundColor = UIColor.yellowColor()
}
dtgr.numberOfTapsRequired = 2
// These two gesture recognizers will change the background color of the screen. dtgr will make it yellow on a double tap, tgr makes it red on a single tap.
// tgr.removeClosure("setButton1")
view.addGestureRecognizer(dtgr)
view.addGestureRecognizer(tgr)
// This adds a closure to the second button on the screen to change the text to Tapped2! when being tapped
testButton2.addControlEvent(.TouchUpInside, closure: {
self.testButton2.setTitle("Tapped2!", forState: .Normal)
})
// This shows that you can remove a control event that has been set. Originally, tapping the first button on the screen
// would set the text to tapped! (line 31), but this removes that.
testButton.removeControlEvent(.TouchUpInside);
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
//
// BWFlipTransionPop.swift
// FlipTransion
//
// Created by BourneWeng on 15/7/13.
// Copyright (c) 2015年 Bourne. All rights reserved.
//
import UIKit
class BWFlipTransionPop: NSObject, UIViewControllerAnimatedTransitioning {
func transitionDuration(transitionContext: UIViewControllerContextTransitioning) -> NSTimeInterval {
return 0.8
}
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) as! SecondViewController
let toVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) as! FirstViewController
let container = transitionContext.containerView()
container.addSubview(toVC.view)
//改变m34
var transfrom = CATransform3DIdentity
transfrom.m34 = -0.002
container.layer.sublayerTransform = transfrom
//设置anrchPoint 和 position
let initalFrame = transitionContext.initialFrameForViewController(fromVC)
toVC.view.frame = initalFrame
toVC.view.layer.anchorPoint = CGPointMake(0, 0.5)
toVC.view.layer.position = CGPointMake(0, initalFrame.height / 2.0)
toVC.view.layer.transform = CATransform3DMakeRotation(CGFloat(-M_PI_2), 0, 1, 0)
//添加阴影效果
let shadowLayer = CAGradientLayer()
shadowLayer.colors = [UIColor(white: 0, alpha: 1).CGColor, UIColor(white: 0, alpha: 0.5).CGColor, UIColor(white: 1, alpha: 0.5)]
shadowLayer.startPoint = CGPointMake(0, 0.5)
shadowLayer.endPoint = CGPointMake(1, 0.5)
shadowLayer.frame = initalFrame
let shadow = UIView(frame: initalFrame)
shadow.backgroundColor = UIColor.clearColor()
shadow.layer.addSublayer(shadowLayer)
toVC.view.addSubview(shadow)
shadow.alpha = 1
//动画
UIView.animateWithDuration(transitionDuration(transitionContext), delay: 0, options: UIViewAnimationOptions.CurveEaseIn, animations: { () -> Void in
toVC.view.layer.transform = CATransform3DIdentity
shadow.alpha = 0
}) { (finished: Bool) -> Void in
toVC.view.layer.anchorPoint = CGPointMake(0.5, 0.5)
toVC.view.layer.position = CGPointMake(CGRectGetMidX(initalFrame), CGRectGetMidY(initalFrame))
shadow.removeFromSuperview()
transitionContext.completeTransition(!transitionContext.transitionWasCancelled())
}
}
} |
//
// UerInfomation.swift
// Piicto
//
// Created by kawaharadai on 2018/01/26.
// Copyright © 2018年 SmartTech Ventures Inc. All rights reserved.
//
import Foundation
struct Person {
var userId: String?
var name: String?
var email: String?
var gender: String?
var birthday: String?
var profilePic: String?
var photos: DataList?
init(userId: String?,
name: String?,
email: String?,
gender: String?,
birthday: String?,
profilePic: String?,
photos: DataList?) {
self.userId = userId
self.name = name
self.email = email
self.gender = gender
self.birthday = birthday
self.profilePic = profilePic
self.photos = photos
}
}
struct DataList {
var dataList = [ImageData?]()
init(dataList: [ImageData?]) {
self.dataList = dataList
}
}
struct ImageData {
var imageId: String?
var link: String?
init(imageId: String?, link: String?) {
self.imageId = imageId
self.link = link
}
}
|
//
// CalenderManager.swift
// CalenderPOC
//
// Created by Shubhakeerti on 20/03/18.
// Copyright © 2018 Shubhakeerti. All rights reserved.
//
import UIKit
class CalenderManager {
private let yearComponent = Calendar.Component.year
private let monthComponent = Calendar.Component.month
private let weekComponent = Calendar.Component.weekOfMonth
private let weekdayComponent = Calendar.Component.weekday
private let dayComponent = Calendar.Component.day
private let hourComponent = Calendar.Component.hour
private let minuteComponent = Calendar.Component.minute
private let secondsComponent = Calendar.Component.second
static var sharedmanager: CalenderManager = CalenderManager()
lazy var calendar: Calendar = {
var calendar: Calendar = Calendar(identifier: Calendar.Identifier.gregorian)
calendar.firstWeekday = 1 //sunday
return calendar
}()
lazy var fullMonthNameDateFormat: DateFormatter = {
let dateFormatter: DateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM" //March
return dateFormatter
}()
lazy var fullMonthWithYearDateFormat: DateFormatter = {
let dateFormatter: DateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM yyyy" // March 2018
return dateFormatter
}()
lazy var timeFormat: DateFormatter = {
let dateFormatter: DateFormatter = DateFormatter()
dateFormatter.dateFormat = "hh:mm a" // 10:45 AM
return dateFormatter
}()
func getDateComponents(date: Date) -> DateComponents {
return self.calendar.dateComponents([yearComponent, monthComponent, weekComponent, weekdayComponent, dayComponent], from: date)
}
func getDateComponentsWithTime(date: Date) -> DateComponents {
return self.calendar.dateComponents([yearComponent, monthComponent, weekComponent, weekdayComponent, dayComponent, hourComponent, minuteComponent, secondsComponent], from: date)
}
}
// Custom Date component
struct ComputedDate {
var date : Date {
didSet {
onlyDateComponent = nil
dateTimeComponent = nil
}
}
var onlyDateComponent: DateComponents?
var dateTimeComponent: DateComponents?
init(date : Date) {
self.date = date
}
mutating func getDateComponent() -> DateComponents {
if let onlyDateComponentUW = onlyDateComponent {
return onlyDateComponentUW
} else {
onlyDateComponent = CalenderManager.sharedmanager.getDateComponents(date: self.date)
return onlyDateComponent!
}
}
mutating func getDateComponentWithTime() -> DateComponents {
if let dateTimeComponentUW = dateTimeComponent {
return dateTimeComponentUW
} else {
dateTimeComponent = CalenderManager.sharedmanager.getDateComponentsWithTime(date: self.date)
return dateTimeComponent!
}
}
}
|
//
// PSImageColorControlView.swift
// PhotoSlice
//
// Created by 雷永麟 on 2020/1/7.
// Copyright © 2020 leiyonglin. All rights reserved.
//
import UIKit
@objc protocol PSImageColorControlDelegate {
@objc optional
func adjustImageColor(x : CGFloat, y : CGFloat, z : CGFloat, w : CGFloat)
@objc optional
func adjustImageColorControl(x : CGFloat, y : CGFloat, z : CGFloat)
}
class PSImageColorControlView: UIView {
enum ControlMode {
case clamp
case control
}
var mode : ControlMode? = .clamp {
didSet {
if self.mode == .control {
self.saturationSlider.minimumValue = 0.5
wSlider.value = 0
contrastSlider.value = 0
brightnessSlider.value = 0
}else {
wSlider.value = 0
contrastSlider.value = 0
brightnessSlider.value = 0
}
}
}
var x : CGFloat = 0
var y : CGFloat = 0.5
var z : CGFloat = 0
var w : CGFloat = 0
weak var colorDelegate : PSImageColorControlDelegate?
///亮度
lazy var brightnessSlider: UISlider = {
let slider = UISlider.init()
slider.setThumbImage(UIImage(named: "slider_thumb"), for: .normal)
slider.addTarget(self, action: #selector(adjustImage), for: .valueChanged)
slider.value = 0.0
slider.tag = 1
slider.tintAdjustmentMode = .automatic
return slider
}()
///对比度
lazy var contrastSlider: UISlider = {
let slider = UISlider.init()
slider.setThumbImage(UIImage(named: "slider_thumb"), for: .normal)
slider.value = 0.0
slider.tag = 2
slider.addTarget(self, action: #selector(adjustImage), for: .valueChanged)
slider.tintAdjustmentMode = .automatic
return slider
}()
///饱和度
lazy var saturationSlider: UISlider = {
let slider = UISlider.init()
slider.setThumbImage(UIImage(named: "slider_thumb"), for: .normal)
slider.value = 0.0
slider.tag = 3
slider.addTarget(self, action: #selector(adjustImage), for: .valueChanged)
slider.tintAdjustmentMode = .automatic
return slider
}()
lazy var wSlider: UISlider = {
let slider = UISlider.init()
slider.setThumbImage(UIImage(named: "slider_thumb"), for: .normal)
slider.addTarget(self, action: #selector(adjustImage), for: .valueChanged)
slider.value = 0.0
slider.tag = 4
slider.tintAdjustmentMode = .automatic
return slider
}()
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .black
addSubview(brightnessSlider)
addSubview(saturationSlider)
addSubview(contrastSlider)
addSubview(wSlider)
brightnessSlider.snp.makeConstraints { (make) in
make.top.equalToSuperview().offset(Scale(10))
make.width.equalToSuperview().multipliedBy(0.8)
make.height.equalTo(Scale(50))
make.centerX.equalToSuperview()
}
saturationSlider.snp.makeConstraints { (make) in
make.top.equalTo(brightnessSlider.snp_bottom).offset(Scale(10))
make.width.equalToSuperview().multipliedBy(0.8)
make.height.equalTo(Scale(50))
make.centerX.equalToSuperview()
}
contrastSlider.snp.makeConstraints { (make) in
make.top.equalTo(saturationSlider.snp_bottom).offset(Scale(10))
make.width.equalToSuperview().multipliedBy(0.8)
make.height.equalTo(Scale(50))
make.centerX.equalToSuperview()
}
wSlider.snp.makeConstraints { (make) in
make.top.equalTo(contrastSlider.snp_bottom).offset(Scale(10))
make.width.equalToSuperview().multipliedBy(0.8)
make.height.equalTo(Scale(50))
make.centerX.equalToSuperview()
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
@objc
private extension PSImageColorControlView {
func adjustImage(slider : UISlider) {
if slider.tag == 1 {
self.x = CGFloat(slider.value / 3)
}else if slider.tag == 2 {
self.y = CGFloat(slider.value)
}else if slider.tag == 3{
self.z = CGFloat(slider.value)
}else {
self.w = CGFloat(slider.value)
}
if mode == .clamp {
self.colorDelegate?.adjustImageColor?(x: x, y: y, z: z, w: w)
}else {
if y < 0.5 {
y = -2 * y
}
self.colorDelegate?.adjustImageColorControl?(x: x * 2, y: y, z: z * 4)
}
}
}
|
//
// AddressViewController.swift
// Project
//
// Created by MIS@NSYSU on 2020/7/17.
// Copyright © 2020年 huihuiteam. All rights reserved.
//
import UIKit
import FirebaseDatabase
import Firebase
import FirebaseAuth
import FirebaseFirestore
import SideMenu
class AddressViewController: BaseViewController{
var documentId:[String] = []
var nameList:[String] = []
var idList:[String] = []
var i = 0
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var menubutton: UIBarButtonItem!
override func viewDidLoad() {
super.viewDidLoad()
readData()
addSlideMenuButton()
}
func readData(){
let userID = Auth.auth().currentUser?.uid
db.collection("user").document(userID!).collection("contact").getDocuments { (querySnapshot, error) in
if let querySnapshot = querySnapshot {
for document in querySnapshot.documents {
self.documentId.append(document.documentID)
self.idList.append(document.data()["uid"] as! String)
print("\(self.idList)123")
}
print(self.idList)
// for i in 0..<self.documentId.count{
//
// print("\(self.idList[self.i]):\(self.i)...456")
//
// db.collection("user").document(self.idList[self.i]).collection("account").getDocuments { (querySnapshot, error) in
// if let querySnapshot = querySnapshot {
// for document in querySnapshot.documents {
// self.nameList.append(document.data()["username"] as! String)
// print(document.data()["username"] as! String)
// self.tableView.reloadData()
//
// }
//
// }
//
// }
// self.i = self.i + 1
// }
}
for i in 0..<self.documentId.count{
print("\(self.idList[self.i]):\(self.i)...456")
db.collection("alluserdata").document(self.idList[self.i]).getDocument { (document, error) in
if let document = document, document.exists {
self.nameList.append(document.data()?["username"] as! String)
print(self.nameList)
//print(document.documentID, document.data())
} else {
print("Document does not exist")
}
}
self.i = self.i + 1
}
print(self.idList)
}
print(self.idList)
}
}
extension AddressViewController: UITableViewDelegate, UITableViewDataSource{
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 200
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return documentId.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "addresscell", for: indexPath) as? CellTableViewCell
//cell?.lbl.text = "111"
//cell?.lbl.text = nameList[indexPath.row]
// cell?.img.image = UIImage(named: username[indexPath.row])
return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
// performSegue(withIdentifier: "AddressDetailViewController", sender: self)
let vc = storyboard?.instantiateViewController(withIdentifier: "AddressDetailViewController") as? AddressDetailViewController
vc?.id = idList[indexPath.row]
self.navigationController?.pushViewController(vc!, animated: true)
}
}
|
//
// Notification.swift
// Vlack
//
// Created by Yuma Antoine Decaux on 15/10/17.
// Copyright © 2017 Yuma Antoine Decaux. All rights reserved.
//
import Foundation
import SwiftyJSON
import AlamofireImage
import Alamofire
class Notify{
var id: String!
//var data:Data?
var date:Date?
var IDMemberCreator:String?
var type:String?
var unread:Bool?
init(_ json: JSON){
self.id = json["id"].stringValue
if json["idMemberCreator"].null == nil{
self.IDMemberCreator = json["idMemberCreator"].stringValue
}
if json["type"].null == nil{
self.type = json["type"].stringValue
}
if json["unread"].null == nil{
self.unread = json["unread"].boolValue
}
}
}
|
import UIKit
/// :nodoc:
public class StudentTableCell: UITableViewCell {
var selectedBefore = false {
willSet {
self.contentView.backgroundColor = newValue ? .groupTableViewBackground : .clear
}
}
let customImageView: UIImageView = {
let iv = UIImageView(image: UIImage(imageLiteralResourceName: "user_profile"))
iv.contentMode = .scaleAspectFill
iv.backgroundColor = .lightGray
return iv
}()
let usernameLabel: UILabel = {
return UILabel.uiLabel(1, .byTruncatingTail, "", .left, .black, .systemFont(ofSize: 15), true, false)
}()
let firstLastNameLabel: UILabel = {
return UILabel.uiLabel(1, .byTruncatingTail, "", .left, .black, .boldSystemFont(ofSize: 15), true, false)
}()
let emailLabel: UILabel = {
return UILabel.uiLabel(1, .byTruncatingTail, "", .left, .black, .systemFont(ofSize: 15), true, false)
}()
let studentIdLabel: UILabel = {
return UILabel.uiLabel(1, .byTruncatingTail, "", .left, .black, .boldSystemFont(ofSize: 15), true, false)
}()
public override func layoutSubviews() {
super.layoutSubviews()
customImageView.layoutIfNeeded()
customImageView.roundCorners(.allCorners, radius: customImageView.frame.size.height / 2)
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: .subtitle, reuseIdentifier: reuseIdentifier)
self.selectionStyle = .none
self.accessoryType = .none
let arrangedSubviews = [
firstLastNameLabel,
studentIdLabel,
emailLabel,
// usernameLabel
]
let stackView = UIStackView(arrangedSubviews: arrangedSubviews)
stackView.distribution = .fill
stackView.alignment = .fill
stackView.axis = .vertical
stackView.spacing = 8
let horizontalStack = UIStackView(arrangedSubviews: [customImageView, stackView])
horizontalStack.alignment = .center
horizontalStack.distribution = .fill
horizontalStack.axis = .horizontal
horizontalStack.spacing = 16
contentView.addSubview(horizontalStack)
horizontalStack.fillSafeArea(spacing: .init(top: 10, left: 16, bottom: -10, right: -16), size: .zero)
customImageView.widthAnchor.constraint(equalToConstant: 40).isActive = true
customImageView.setHeightConstraint(constant: 40, priority: 999)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func configure(_ element: User) {
// usernameLabel.text = "Username: \(element.username)"
firstLastNameLabel.text = "Name: \(element.firstName) \(element.lastName)"
emailLabel.text = "Email: \(element.email)"
if let studentId = element.studentID {
studentIdLabel.text = "Student ID: \(studentId)"
}
}
}
|
import Foundation
import AppKit
import Darwin
var pasteboard = NSPasteboard.general
func printInfo() {
print(toJson(obj: ["count": pasteboard.changeCount, "types": pasteboard.types!]))
}
func printByType(type: NSString!) {
let dataType = NSPasteboard.PasteboardType(rawValue: type as String)
if let data = pasteboard.data(forType: dataType) {
FileHandle.standardOutput.write(data)
}
}
func setByType(type: NSString!) -> Bool {
let dataType = NSPasteboard.PasteboardType(rawValue: type as String)
let data = FileHandle.standardInput.readDataToEndOfFile()
pasteboard.declareTypes([dataType], owner: nil)
return pasteboard.setData(data, forType: dataType)
}
func toJson(obj: Any) -> NSString {
let data = try! JSONSerialization.data(withJSONObject: obj)
return NSString(data: data, encoding: String.Encoding.utf8.rawValue)!
}
func printHelp() {
print("Usage:\n -h, --help\tShow help\n -c, --count\tShow clipboard change count\n -i, --input <type>\tSet clipboard by type with content from stdin\n -o, --output <type>\tOutput clipboard content by type\n -s, --status\tShow clipboard information")
}
let args = CommandLine.arguments
if (args.count <= 1) {
printHelp()
exit(1)
}
else if (args[1] == "--help" || args[1] == "-h") {
printHelp()
}
else if (args[1] == "--count" || args[1] == "-c") {
print(pasteboard.changeCount)
}
else if (args[1] == "--status" || args[1] == "-s") {
printInfo()
}
else if (args.count >= 2 && (args[1] == "--input" || args[1] == "-i")) {
exit(setByType(type: args[2] as NSString) ? 0 : 1)
}
else if (args.count >= 2 && (args[1] == "--output" || args[1] == "-o")) {
printByType(type: args[2] as NSString)
}
else {
printHelp()
exit(1)
}
|
//
// MyFucn.swift
// Election
//
// Created by xxx on 18/01/2019.
// Copyright © 2019 xxx. All rights reserved.
//
import Foundation
|
import Quick
import Nimble
@testable import EasyCalculator
class EasyCalculatorTests: QuickSpec {
override func spec() {
super.spec()
context("sample unit test") {
it("tests the environment") {
expect("test").to(equal("test"))
}
}
}
}
|
//
// WeatherCellObject.swift
// Weather
//
// Created by Алихан on 22/06/2020.
// Copyright © 2020 Nexen Origin, LLC. All rights reserved.
//
import Foundation
import UIKit
struct WeatherCellObject {
//MARK: - Properties
let icon: String
let temperature: Double
let time: String
let summary: String
let style: Style
enum Style {
case dark
case light
}
}
//MARK: - CellObject
extension WeatherCellObject: TableViewCellObject {
func cellReuseIdentifier() -> String {
return UITableViewCell.ReuseIdentifier.Weather.item
}
func height() -> CGFloat {
return 64
}
}
|
//
// AddOptionsViewController.swift
// AddOptionsApp
//
// Created by Roman Rybachenko on 10.03.2020.
// Copyright © 2020 Roman Rybachenko. All rights reserved.
//
import UIKit
import TPKeyboardAvoiding
class AddOptionsViewController: UIViewController, Storyboardable {
// MARK: - Outlets
@IBOutlet weak var tableView: TPKeyboardAvoidingTableView!
@IBOutlet weak var closeButton: UIButton!
@IBOutlet weak var doneButton: UIButton!
// MARK: - Properties
static var storyboardName: Storyboard {
return .main
}
private var viewModel = AddOptionsViewModel()
// MARK: - Overriden funcs
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = Constants.backgroundColor
setupNavigationView()
setupTableView()
}
var selectedConditions: (([ConditionItem]) -> Void)?
// MARK: - Actions
@IBAction func closeButtonTapped(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
@IBAction func doneButtonTapped(_ sender: Any) {
dismiss(animated: true, completion: { [weak self] in
guard let conditions = self?.viewModel.selectedConditions(),
conditions.count > 0
else { return }
self?.selectedConditions?(conditions)
})
}
// MARK: - Private funcs
private func setupNavigationView() {
let imgConfig = UIImage.SymbolConfiguration(weight: .medium)
let closeImage = UIImage(systemName: "xmark", withConfiguration: imgConfig)
closeButton.setImage(closeImage, for: .normal)
closeButton.tintColor = Constants.barButtonItemsTintColor
closeButton.backgroundColor = Constants.closeButtonColor
closeButton.setCornerRadius(Constants.barButtonItemsCornerRadius)
doneButton.setCornerRadius(Constants.barButtonItemsCornerRadius)
doneButton.setTitleColor(Constants.barButtonItemsTintColor, for: .normal)
doneButton.backgroundColor = Constants.doneButtonColor
let doneBtnTitle = "Done"
doneButton.setTitle(doneBtnTitle, for: .normal)
}
private func setupTableView() {
tableView.backgroundColor = Constants.tableViewBgColor
let footerView = UIView(frame: CGRect(x: 0, y: 0, width: 0.1, height: 0.1))
footerView.backgroundColor = .clear
tableView.tableFooterView = footerView
let size = CGSize(width: UIScreen.main.bounds.size.width, height: OptionsHeaderView.height)
let headerView = OptionsHeaderView(frame: CGRect(origin: .zero, size: size))
headerView.titleLabel.text = viewModel.titleForHeader(in: 0)
tableView.tableHeaderView = headerView
tableView.registerCell(OptionExpandableCell.self)
tableView.dataSource = self
tableView.delegate = self
}
private func configureCell(_ cell: OptionExpandableCell, with item: ConditionItem) {
cell.delegate = self
cell.optionNameLabel.text = item.title
cell.infoButton.isHidden = !item.hasInfoButton
cell.additionalInfoTextField.text = item.additionalInfo
cell.chekmarkImageView.isHidden = !viewModel.isConditionSelected(item)
let attrs = [NSAttributedString.Key.foregroundColor: UIColor.lightGray]
let attrPlaceholder = NSAttributedString(string: item.textFieldPlaceholder, attributes: attrs)
cell.additionalInfoTextField.attributedPlaceholder = attrPlaceholder
cell.isExpanded = viewModel.isConditionSelected(item) && item.isExpandable
}
private func setTextFieldActiveInCell(at indexPath: IndexPath) {
guard let cell = tableView.cellForRow(at: indexPath) as? OptionExpandableCell,
let cItem = viewModel.conditionItem(at: indexPath)
else { return }
if viewModel.isConditionSelected(cItem) && cItem.isExpandable {
DispatchQueue.main.asyncAfter(deadline: .now() + Constants.animationDuration, execute: {
cell.additionalInfoTextField.becomeFirstResponder()
})
} else {
view.endEditing(true)
}
}
}
// MARK: - UITableViewDataSource, UITableViewDelegate
extension AddOptionsViewController: UITableViewDataSource, UITableViewDelegate {
func numberOfSections(in tableView: UITableView) -> Int {
return viewModel.numberOfSections()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return viewModel.numberOfRows(in: section)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let optionItem = viewModel.conditionItem(at: indexPath) else { return UITableViewCell() }
let cell = tableView.dequeueReusableCell(for: indexPath, cellType: OptionExpandableCell.self)
configureCell(cell, with: optionItem)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
viewModel.userDidSelectCondition(at: indexPath)
tableView.beginUpdates()
tableView.reloadRows(at: [indexPath], with: .automatic)
tableView.endUpdates()
setTextFieldActiveInCell(at: indexPath)
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return viewModel.heightForRow(at: indexPath)
}
}
// MARK: - OptionExpandableCellDelegate
extension AddOptionsViewController: OptionExpandableCellDelegate {
func infoButtonTapped(in cell: OptionExpandableCell) {
AlertsManager.showFeatureInDevelopmentAlert(to: self)
}
func editedAdditionalInfo(_ info: String?, in cell: OptionExpandableCell) {
guard let ip = tableView.indexPath(for: cell),
let item = viewModel.conditionItem(at: ip)
else { return }
item.additionalInfo = info
}
}
// MARK: -
extension AddOptionsViewController {
private struct Constants {
static let closeButtonSize = CGSize(width: 40, height: 40)
static let doneButtonSize = CGSize(width: 68, height: 40)
static let barButtonItemsCornerRadius: CGFloat = 8
static let navBarColor = UIColor.clear
static let closeButtonColor = UIColor.rgba(34, 36, 38)
static let doneButtonColor = UIColor.rgba(81, 173, 202)
static let backgroundColor = UIColor.rgba(47, 48, 56)
static let tableViewBgColor = UIColor.clear
static let barButtonItemsTintColor = UIColor.white
static let animationDuration: TimeInterval = 0.35
}
}
|
//
// RMLocalStorage.swift
// RemMe
//
// Created by marco sportillo on 27/08/16.
// Copyright © 2016 msportillo.me. All rights reserved.
//
import Foundation
import RealmSwift
class RMLocalStorage: NSObject {
//MARK: Configuration
var manager : Realm //manager Alamofire
//singleton
static let sharedInstance = RMLocalStorage()
override init() {
self.manager = try! Realm()
}
//MARK: Song methods
internal func saveSong(title: String, artist: String) {
let newSong = RMSong()
newSong.title = title
newSong.artist = artist
try! manager.write({
manager.add(newSong)
})
}
internal func getSongs() -> Results<RMSong>{
let songs = manager.objects(RMSong.self)
return songs
}
internal func deleteSong(songToDelete: RMSong) {
try! manager.write {
manager.delete(songToDelete)
}
}
//MARK: Book methods
internal func saveBook(title: String, author: String) {
let newBook = RMBook()
newBook.title = title
newBook.author = author
try! manager.write({
manager.add(newBook)
})
}
internal func getBooks() -> Results<RMBook>{
let books = manager.objects(RMBook.self)
return books
}
internal func deleteBook(bookToDelete: RMBook) {
try! manager.write {
manager.delete(bookToDelete)
}
}
//MARK: Film methods
internal func saveFilm(title: String, picture: NSData, ratings: Double) {
let newFilm = RMFilm()
newFilm.title = title
newFilm.picture = picture
newFilm.ratings = ratings
try! manager.write({
manager.add(newFilm)
})
}
internal func getFilms() -> Results<RMFilm>{
let films = manager.objects(RMFilm.self)
return films
}
internal func deleteFilm(filmToDelete: RMFilm) {
try! manager.write {
manager.delete(filmToDelete)
}
}
//MARK: TVSerie methods
internal func saveTVSerie(title: String, picture: NSData, ratings: Double) {
let newTVSerie = RMTVSerie()
newTVSerie.title = title
newTVSerie.picture = picture
newTVSerie.ratings = ratings
try! manager.write({
manager.add(newTVSerie)
})
}
internal func getTVSeries() -> Results<RMTVSerie>{
let tvSeries = manager.objects(RMTVSerie.self)
return tvSeries
}
internal func deleteTVSerie(tvSerieToDelete: RMTVSerie) {
try! manager.write {
manager.delete(tvSerieToDelete)
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.