text
stringlengths
8
1.32M
// // CircleViewController.swift // Beibei // // Created by mac on 16/6/6. // Copyright © 2016年 wyq. All rights reserved. //圈儿 import UIKit class CircleViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.title = "圈儿" } }
// // ViewController.swift // UINavigationController // // Created by cedro_nds on 21/05/17. // Copyright © 2017 Cedro Technologies. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var NameTextFild: UITextField! @IBOutlet weak var LestNameTextField: UITextField! @IBAction func TelaAButton(_ sender: UIButton){ self.performSegue(withIdentifier: "sigTelaB", sender: nil) } override func prepare(for segue: UIStoryboardSegue, sender: Any?){ let vc = segue.destination as! TelaBViewController vc.name = self.NameTextFild.text vc.lastname = self.LestNameTextField.text } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.navigationController?.navigationBar.barTintColor = .red } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
// // ViewController.swift // SujitIOSTest // // Created by Admin on 12/17/19. // Copyright © 2019 Admin. All rights reserved. // import UIKit import Kingfisher class ViewController: UIViewController { @IBOutlet weak var tableView: UITableView! var countryInfo = [CountryModel]() override func viewDidLoad() { super.viewDidLoad() getCountry() } override func viewWillAppear(_ animated: Bool) { navigationController?.navigationBar.barTintColor = .white navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.red] } //MARK: Get Country Details. func getCountry() { ApiManager.sharedManager.getCountryInfo(url: "https://dl.dropboxusercontent.com/s/2iodh4vg0eortkl/facts.json", success: { (response) in guard let countryResponse = response else { return } self.countryInfo = [CountryModel]() for country in countryResponse { let info = CountryModel(json: country as! NSDictionary) if !(info.description == nil && info.title == nil && info.imageHref == nil) { self.countryInfo.append(info) } } DispatchQueue.main.async { if let title = UserDefaults.standard.value(forKey: "TITLE") { self.title = title as? String } self.tableView.reloadData() } }, failure: { (error) in print("Error while fetching user from profile:\(error.localizedDescription)") }) } // private func setupTableView() { // self.tableView.delegate = self // self.tableView.dataSource = self // tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell") // tableView.translatesAutoresizingMaskIntoConstraints = false // view.addSubview(tableView) // // NSLayoutConstraint.activate([ // tableView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor), // tableView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor), // tableView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor), // tableView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor) // ]) // // } } extension ViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return countryInfo.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let countryCell = tableView.dequeueReusableCell(withIdentifier: "CountryCell", for: indexPath) as! CountryCell let countryInfo = self.countryInfo[indexPath.row] countryCell.countryTitleLbl.text = countryInfo.title countryCell.countryDescriptionLbl.text = countryInfo.description if let imgStr = countryInfo.imageHref { countryCell.countryImg.kf.setImage(with: URL(string: imgStr)) //Image download using Kingfisher library. } else { countryCell.countryImg.kf.setImage(with: URL(string: "")) } return countryCell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableViewAutomaticDimension } }
// // PTVirtualController.swift // maqueta // // Created by Miguel Roncallo on 2/2/17. // Copyright © 2017 Nativapps. All rights reserved. // import UIKit class PTVirtualController: UIViewController { @IBOutlet var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() setNavigationBar() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func finishWorkout(_ sender: UIButton) { let vc = self.storyboard?.instantiateViewController(withIdentifier: "Finish Workout VC") as! FinishWorkoutController self.navigationController?.pushViewController(vc, animated: true) } //Supporting functions func setNavigationBar(){ self.navigationController?.navigationBar.barTintColor = UIColor.black let label = UILabel() label.text = "VIRTUAL PT" label.textColor = UIColor.white label.font = UIFont.boldSystemFont(ofSize: 15) label.sizeToFit() self.navigationItem.titleView = label } } extension PTVirtualController: UITableViewDelegate, UITableViewDataSource{ func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){ } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 3 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "PT Virtual Cell") as! PTVirtualCell return cell } }
// // ViewController.swift // Hello_Color // // Created by Zubieta on 10/2/20. // Copyright © 2020 zubie7a. All rights reserved. // import UIKit class ViewController: UIViewController { var isPurple = false override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } @IBAction func changeColor(_ sender: Any) { print("Button was pressed!") if isPurple { // XCode automatically knows this view exists. view.backgroundColor = UIColor.red } else { view.backgroundColor = UIColor.purple } // Flip the value of isPurple. isPurple = !isPurple } }
// // NSRegularExpression+Resolutions.swift // Resolutions // // Created by Daniel Ma on 12/21/16. // Copyright © 2016 Daniel Ma. All rights reserved. // import Foundation extension NSRegularExpression { func hasMatch(_ string: String, options: NSRegularExpression.MatchingOptions = NSRegularExpression.MatchingOptions()) -> Bool { let range = NSMakeRange(0, string.characters.count) return firstMatch(in: string, options: options, range: range) != nil } }
// // BallView.swift // Breakout // // Created by Zach Ziemann on 12/13/16. // Copyright © 2016 Zach Ziemann. All rights reserved. // import UIKit class BallView: UIView { //setup of ball settings init(myView: UIView) { super.init(frame: CGRectZero) backgroundColor = UserSettings.DefaultSettings.ballColor frame = CGRect(origin: CGPointZero, size: CGSize(width: 18,height: 18)) frame.origin.x = myView.bounds.midX frame.origin.y = myView.bounds.midY } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
// // CityInfoViewController.swift // Lect14Test // // Created by Artem on 25.05.2021. // import UIKit class CityInfoViewController: UIViewController { var cityName = "placeholder" var imageName = UIImage(named: "placeholder") var imageView: UIImageView = { let view = UIImageView(frame: CGRect( x: 0, y: UIScreen.main.bounds.height / 2 - 100, width: UIScreen.main.bounds.width, height: 200)) return view }() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white imageView.image = imageName view.addSubview(imageView) navigationController?.navigationBar.topItem?.title = cityName navigationController?.navigationBar.prefersLargeTitles = true self.navigationController?.navigationItem.largeTitleDisplayMode = .always } }
// // Spreadsheet.swift // MyLeaderboard // // Created by Joseph Roque on 2019-08-18. // Copyright © 2019 Joseph Roque. All rights reserved. // import FunctionalTableData enum Spreadsheet { static func section(key: String, builder: SpreadsheetBuilder, config: Config) -> TableSection? { return builder.spreadsheet(forKey: key, config: config) } }
// // APIController.swift // tut // // Created by Andreea Popescu on 4/22/16. // Copyright © 2016 a. All rights reserved. // import Foundation protocol APIControllerProtocol { func didReceiveAPIResults(results: NSArray) } class APIController { var delegate: APIControllerProtocol init (delegate: APIControllerProtocol) { self.delegate = delegate } func get(path: String) { let url = NSURL(string: path) let session = NSURLSession.sharedSession() let task = session.dataTaskWithURL(url!, completionHandler: {data, response, error -> Void in print("completion") if(error != nil){ print(error!.localizedDescription) } do{ if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary { if let results: NSArray = jsonResult["results"] as? NSArray { self.delegate.didReceiveAPIResults(results) } } } catch let err as NSError { print("JSON Error \(err.localizedDescription)") } }) task.resume() print("resume") } func searchItunesFor(searchTerm: String) { print("get search") let itunesSearchTerm = searchTerm.stringByReplacingOccurrencesOfString(" ", withString: "+", options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil) if let escapedSearchTerm = itunesSearchTerm.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet()) { let urlPath = "http://itunes.apple.com/search?term=\(escapedSearchTerm)&media=music&entity=album" get(urlPath) } } func lookupAlbum(collectionId: Int) { print("get album") get("https://itunes.apple.com/lookup?id=\(collectionId)&entity=song") } }
// // PhotoCell.swift // HeySen // // Created by Matthew on 16/7/9. // Copyright © 2016年 Matthew. All rights reserved. // import UIKit class PhotoCell: UICollectionViewCell { fileprivate let padding: CGFloat = 10.0 var page: ZoomingScrollView var representedAssetIdentifier: String? override init(frame: CGRect) { page = ZoomingScrollView(frame: CGRect( origin: CGPoint.zero, size: CGSize(width: frame.width - padding * 2.0, height: frame.height)) ) super.init(frame: frame) contentView.addSubview(page) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func prepareForReuse() { page.image = nil page.photoImageView.image = nil } }
// // SettingsViewCell.swift // HackMeet // // Created by Matthew Swenson on 5/21/19. // Copyright © 2019 Matthew Swenson. All rights reserved. // import UIKit class SettingsViewCell: UITableViewCell { }
// // DisciplinesCollectionViewCell.swift // Tutorbot // // Created by student on 29/05/19. // Copyright © 2019 student. All rights reserved. // import UIKit class DisciplinesCollectionViewCell: UICollectionViewCell { @IBOutlet weak var disciplineName: UILabel! @IBOutlet weak var disciplineImage: UIImageView! override func awakeFromNib() { } }
// // Date.swift // Crypier // // Created by Batuhan Saygılı on 14.01.2018. // Copyright © 2018 batuhansaygili. All rights reserved. // import Foundation extension Date { func string(with format: String) -> String { let date = Date(timeIntervalSince1970: TimeInterval(format.prefix(10))!) let dateFormatter = DateFormatter() var localTimeZoneAbbreviation: String { return TimeZone.current.abbreviation() ?? "" } dateFormatter.timeZone = TimeZone(abbreviation: localTimeZoneAbbreviation) //Set timezone that you want dateFormatter.locale = NSLocale.current dateFormatter.dateFormat = "dd/MM/yyyy" //Specify your format that you want let strDate = dateFormatter.string(from: date) return strDate } }
// // AppStyle.swift // Homework // // Created by Javier Quintero on 6/4/19. // Copyright © 2019 Javier Quintero. All rights reserved. // import Foundation import UIKit class AppStyle { let backgroundColor = UIColor.white let greyAccent = UIColor(red: 0, green: 0, blue: 0, alpha: 0.1) let mainTextColor = UIColor.black let greenColor = UIColor(red: 0/255, green: 200/255, blue: 136/255, alpha: 1) var backgroundColors: [UIColor] = [] var textColors: [UIColor] = [] init() { backgroundColors = [ makeColor(red: 12, green: 78, blue: 78, alpha: 0.4), makeColor(red: 203, green: 132, blue: 132, alpha: 1), makeColor(red: 0, green: 51, blue: 102, alpha: 0.45), makeColor(red: 12, green: 147, blue: 150, alpha: 0.65), makeColor(red: 170, green: 111, blue: 115, alpha: 0.3), makeColor(red: 0, green: 136, blue: 136 , alpha: 0.3), makeColor(red: 70, green: 2, blue: 70, alpha: 0.3), makeColor(red: 76, green: 165, blue: 230, alpha: 0.85), makeColor(red: 238, green: 168, blue: 168, alpha: 1), makeColor(red: 145, green: 63, blue: 252, alpha: 0.3), makeColor(red: 0, green: 238, blue: 101, alpha: 0.3), makeColor(red: 255, green: 34, blue: 129, alpha: 0.3), makeColor(red: 1, green: 205, blue: 254, alpha: 0.3), makeColor(red: 202, green: 250, blue: 1, alpha: 0.5), makeColor(red: 245, green: 66, blue: 245, alpha: 0.3) ] textColors = [ makeColor(red: 12, green: 78, blue: 78, alpha: 1), makeColor(red: 111, green: 16, blue: 16, alpha: 1), makeColor(red: 0, green: 51, blue: 102, alpha: 1), makeColor(red: 4, green: 106, blue: 108, alpha: 1), makeColor(red: 170, green: 111, blue: 115, alpha: 1), makeColor(red: 0, green: 136, blue: 136 , alpha: 1), makeColor(red: 70, green: 2, blue: 70, alpha: 1), makeColor(red: 0, green: 51, blue: 102, alpha: 1), makeColor(red: 228, green: 29, blue: 29, alpha: 1), makeColor(red: 145, green: 63, blue: 252, alpha: 1), makeColor(red: 0, green: 193, blue: 11, alpha: 1), makeColor(red: 255, green: 34, blue: 129, alpha: 1), makeColor(red: 0, green: 128, blue: 158, alpha: 1), makeColor(red: 129, green: 153, blue: 27, alpha: 1), makeColor(red: 245, green: 66, blue: 245, alpha: 1) ] } func makeColor(red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) ->UIColor { return UIColor(red: red/255, green: green/255, blue: blue/255, alpha: alpha) } func genGreenColor(alpha: CGFloat) ->UIColor { return UIColor(red: 0/255, green: 136/255, blue: 136/255, alpha: alpha) } func genRedColor(alpha: CGFloat) ->UIColor { return UIColor(red: 255/255, green: 0/255, blue: 0/255, alpha: alpha) } func genOrangeColor(alpha: CGFloat) ->UIColor { return UIColor(red: 252/255, green: 139/255, blue: 0/255, alpha: alpha) } func genPurpleColor(alpha: CGFloat) ->UIColor { return UIColor(red: 145/255, green: 63/255, blue: 252/255, alpha: alpha) } func genPinkColor(alpha: CGFloat) ->UIColor { return UIColor(red: 245/255, green: 66/255, blue: 245/255, alpha: alpha) } func genNeonGreenColor(alpha: CGFloat) ->UIColor { return UIColor(red: 0/255, green: 229/255, blue: 169/255, alpha: alpha) } func genNeonPinkColor(alpha: CGFloat) -> UIColor { return UIColor(red: 255/255, green: 0/255, blue: 180/255, alpha: alpha) } func genDarkPurple(alpha: CGFloat) -> UIColor { return UIColor(red: 70/255, green: 2/255, blue: 70/255, alpha: alpha) } func genPaleOrange(alpha: CGFloat) -> UIColor { return UIColor(red: 238/255, green: 169/255, blue: 144/255, alpha: alpha) } func genPaleMaroon(alpha: CGFloat) -> UIColor { return UIColor(red: 170/255, green: 111/255, blue: 115/255, alpha: alpha) } func genBlueVapor(alpha: CGFloat) -> UIColor { return UIColor(red: 1/255, green: 205/255, blue: 254/255, alpha: alpha) } func genAltRed(alpha: CGFloat) -> UIColor { return UIColor(red: 255/255, green: 34/255, blue: 129/255, alpha: alpha) } func genBlue(alpha: CGFloat) -> UIColor { return UIColor(red: 0/255, green: 51/255, blue: 102/255, alpha: alpha) } func genMaroon(alpha: CGFloat) ->UIColor { return UIColor(red: 120/255, green: 3/255, blue: 3/255, alpha: alpha) } func genDarkGreen(alpha: CGFloat) ->UIColor { return UIColor(red: 37/255, green: 80/255, blue: 96/255, alpha: alpha) } let buttonTextColor = UIColor(red: 0, green: 122/255, blue: 1, alpha: 1) }
// // ContentView.swift // DegreeConverter // // Created by Alice Nedosekina on 25/11/2020. // import SwiftUI protocol TempConvertor { func toKelvin(value: String) -> Double func toTarget(value: Double) -> String } struct CelsiusConvertor : TempConvertor { func toKelvin(value: String) -> Double { return Double(value)! + 273.15 } func toTarget(value: Double) -> String { return "\(roundTemp(value: value - 273.15))" } } struct FahrenheitConvertor : TempConvertor { func toKelvin(value: String) -> Double { return ( Double(value)! + 459.67 ) * 5 / 9 } func toTarget(value: Double) -> String{ return "\(roundTemp(value: ( value * 9 / 5) - 459.67))" } } struct KelvinConvertor : TempConvertor { func toKelvin(value: String) -> Double { return Double(value)! } func toTarget(value: Double) -> String { return "\(roundTemp(value: value))" } } func roundTemp (value: Double) -> Double { return round( 100 * value ) / 100 } struct ContentView: View { @State private var fromUnit: Int = 0 @State private var toUnit: Int = 0 @State private var valueToConvert: String = "" var isEmpty : Bool { return valueToConvert == "" } var isValid : Bool { return !isEmpty && Double(valueToConvert) != nil } var convertors : [TempConvertor] = [CelsiusConvertor(), KelvinConvertor(), FahrenheitConvertor()] var output: String { let convertedToKelvin = convertors[fromUnit].toKelvin(value: valueToConvert) let result = convertors[toUnit].toTarget(value: convertedToKelvin) return "\(result)" } let degreeScales = ["Celsius", "Kelvin", "Fahrenheit"] var body: some View { NavigationView { VStack { Form { Section (header: Text("Convert from")) { Picker(selection: $fromUnit, label: Text("Convert from"), content: { ForEach (0 ..< degreeScales.count){ Text("\(degreeScales[$0])") } }) .pickerStyle(SegmentedPickerStyle()) } Section (header: Text("Convert to")) { Picker(selection: $toUnit, label: Text("Convert from"), content: { ForEach (0 ..< degreeScales.count){ Text("\(degreeScales[$0])") } }) .pickerStyle(SegmentedPickerStyle()) } Section (header: Text("Enter value")) { TextField("Value", text: $valueToConvert) .keyboardType(.numberPad) } } Spacer() .frame(height: 40) if isEmpty { Text("Enter value to convert") } else if !isValid { Text("Value is not valid") } else { Text(""" \(valueToConvert) \(degreeScales[fromUnit]) equals \(output) \(degreeScales[toUnit]) """) .font(.title2) .multilineTextAlignment(.center) } Spacer() .frame(height: 40) } .navigationTitle("Degree convertor") } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
// // MineCollectionModel.swift // SpecialTraining // // Created by 徐军 on 2018/12/7. // Copyright © 2018年 youpeixun. All rights reserved. // import UIKit class MineCollectionModel: HJModel { var image: String = "" var title: String = "" var tag: String = "" var time: String = "" } class MineCollectionHeaderModel: HJModel { var title: String = "" var isSelected: Bool = false class func createModel(title:String, isSelected: Bool = false) -> MineCollectionHeaderModel { let model = MineCollectionHeaderModel() model.title = title model.isSelected = isSelected return model } }
// // ProfileViewController.swift // GitUserHandler // // Created by Akshay Patil on 14/03/21. // import Foundation import UIKit class ProfileViewController: UITableViewController { @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var followersLabel: UILabel! @IBOutlet weak var followingLabel: UILabel! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var companyLabel: UILabel! @IBOutlet weak var blogLabel: UILabel! @IBOutlet weak var noteTextView: UITextView! private var gitHubViewModel : GitHubUserViewModel? var inputId : Int32? override func viewDidLoad() { super.viewDidLoad() gitHubViewModel = GitHubUserViewModel(inputId) noteTextView?.layer.borderColor = UIColor.lightGray.cgColor imageView?.startShimmeringEffect() followersLabel?.startShimmeringEffect() followingLabel?.startShimmeringEffect() companyLabel?.startShimmeringEffect() nameLabel?.startShimmeringEffect() blogLabel?.startShimmeringEffect() noteTextView?.startShimmeringEffect() gitHubViewModel?.setGitHubUserViewModelDelegate(self) gitHubViewModel?.load() if let url = gitHubViewModel?.gitHubUser.avatar_url { gitHubViewModel?.loadImage(urlString: url, completionHandler: { (downloadedUrl, userName, data) in if (url == downloadedUrl) { self.imageView?.stopShimmeringEffect() self.imageView?.image = UIImage(data: data ?? Data()) } }) } } @IBAction func saveClicked(_ sender: Any) { gitHubViewModel?.saveNote(note: noteTextView.text) } } extension ProfileViewController : GitHubUserViewModelProtocol { func userFound() { followersLabel?.stopShimmeringEffect() followingLabel?.stopShimmeringEffect() companyLabel?.stopShimmeringEffect() nameLabel?.stopShimmeringEffect() blogLabel?.stopShimmeringEffect() noteTextView?.stopShimmeringEffect() followersLabel.text = "Followers: \(gitHubViewModel?.gitHubUser.followers ?? 0)" followingLabel.text = "Following: \(gitHubViewModel?.gitHubUser.following ?? 0)" companyLabel.text = "\(gitHubViewModel?.gitHubUser.company ?? "")" nameLabel.text = "\(gitHubViewModel?.gitHubUser.name ?? "")" blogLabel.text = "\(gitHubViewModel?.gitHubUser.blog ?? "")" noteTextView.text = "\(gitHubViewModel?.gitHubUser.note ?? "")" } func userSaved() { let toastLabel = UILabel(frame: CGRect(x: self.view.frame.size.width/2 - 75, y: self.view.frame.size.height-(self.view.frame.size.height/5), width: 150, height: 35)) toastLabel.backgroundColor = UIColor.darkGray toastLabel.textAlignment = .center; toastLabel.text = "Saved" toastLabel.alpha = 1.0 toastLabel.layer.cornerRadius = 10; toastLabel.clipsToBounds = true self.view.addSubview(toastLabel) UIView.animate(withDuration: 2.0, delay: 0.75, options: .curveEaseOut, animations: { toastLabel.alpha = 0.0 }, completion: {(isCompleted) in toastLabel.removeFromSuperview() }) } }
// // FeedListCell.swift // SocialFeedApp // // Created by Raul Mantilla on 28/02/19. // Copyright (c) 2019 Raul Mantilla Assia. All rights reserved. // import UIKit import Alamofire import AlamofireImage class FeedListCell: UICollectionViewCell { @IBOutlet weak var authorNameLabel: UILabel! { didSet { authorNameLabel.textColor = DefaultColors.blackColor authorNameLabel.font = DefaultFonts.regular } } @IBOutlet weak var accountNameLabel: UILabel! { didSet { accountNameLabel.textColor = DefaultColors.blackColor accountNameLabel.font = DefaultFonts.regular } } @IBOutlet weak var dateLabel: UILabel! { didSet { dateLabel.textColor = DefaultColors.blackColor dateLabel.font = DefaultFonts.regular } } @IBOutlet weak var plainTextView: UITextView! { didSet { dateLabel.textColor = DefaultColors.blackColor dateLabel.font = DefaultFonts.regular } } @IBOutlet weak var networkImage: UIImageView!{ didSet { networkImage.backgroundColor = DefaultColors.bgColor networkImage.layer.cornerRadius = 10 networkImage.layer.masksToBounds = false networkImage.clipsToBounds = true } } @IBOutlet weak var authorImage: UIImageView!{ didSet { authorImage.backgroundColor = DefaultColors.bgColor authorImage.layer.cornerRadius = 30 authorImage.layer.masksToBounds = false authorImage.clipsToBounds = true } } @IBOutlet weak var pictureImage: UIImageView! @IBOutlet weak var verifiedImage: UIImageView! @IBOutlet weak var bgView: UIView! { didSet { bgView.backgroundColor = DefaultColors.bgColor bgView.layer.cornerRadius = 10 } } var displayedFeed: DisplayedFeed! func setup(withDisplayedFeed displayedFeed: DisplayedFeed) { self.displayedFeed = displayedFeed showData() } private func showData() { authorNameLabel.text = displayedFeed.authorName dateLabel.text = displayedFeed.date plainTextView.attributedText = displayedFeed.text plainTextView.isUserInteractionEnabled = true plainTextView.isEditable = false plainTextView.linkTextAttributes = [ .foregroundColor: UIColor.blue, .underlineStyle: NSUnderlineStyle.single.rawValue ] if let accounName = displayedFeed.accountName { accountNameLabel.text = accounName accountNameLabel.isHidden = false } if let imageUrl = displayedFeed.authorPictureUrl, let url = URL(string: imageUrl) { authorImage.af_setImage(withURL: url) } if let imageUrl = displayedFeed.picture?.pictureLink, let url = URL(string: imageUrl) { pictureImage.af_setImage(withURL: url) } if let image = displayedFeed.network { networkImage.image = image } if displayedFeed.isVerified == true { verifiedImage.isHidden = false } } }
// // LoginView.swift // Foody2 // // Created by Sebastian Strus on 2018-06-01. // Copyright © 2018 Sebastian Strus. All rights reserved. // import UIKit class LoginView: UIView { var backgroundImageView: UIImageView = { let iv = UIImageView(image: #imageLiteral(resourceName: "restaurant")) iv.backgroundColor = .white iv.contentMode = .scaleAspectFill return iv }() let emailTextField: UITextField = { let tf = UITextField(placeHolder: "Email".localized) return tf }() let passwordTextField: UITextField = { let tf = UITextField(placeHolder: "Password".localized) return tf }() let loginButton: UIButton = { let button = UIButton(title: "Login".localized, borderColor: AppColors.GREEN_BORDER) button.addTarget(self, action: #selector(handleLogin), for: .touchUpInside) return button }() let cancelButton: UIButton = { let button = UIButton(title: "Cancel".localized, borderColor: AppColors.RED_BORDER) button.addTarget(self, action: #selector(handleSignup), for: .touchUpInside) return button }() @objc func handleLogin() { loginAction?() } @objc func handleSignup() { cancelAction?() } var loginAction: (() -> Void)? var cancelAction: (() -> Void)? override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setup() { let stackView = createStackView(views: [emailTextField, passwordTextField, loginButton, cancelButton]) addSubview(backgroundImageView) addSubview(stackView) backgroundImageView.setAnchor(top: self.topAnchor, leading: self.leadingAnchor, bottom: self.bottomAnchor, trailing: self.trailingAnchor, paddingTop: 0, paddingLeft: 0, paddingBottom: 0, paddingRight: 0) stackView.setAnchor(top: nil, leading: nil, bottom: nil, trailing: nil, paddingTop: 0, paddingLeft: 0, paddingBottom: 0, paddingRight: 0, width: self.frame.width - (Device.IS_IPHONE ? 60 : 300), height: Device.IS_IPHONE ? 190 : 380) stackView.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true stackView.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true } }
public extension Int { var binaryString: String { return String(self, radix: 2) } var hexaString: String { return String(self, radix: 16) } var doubleValue: Double { return Double(self) } }
// // Constants.swift // StarwarsV1 // // Created by Kyla Wilson on 4/27/19. // Copyright © 2019 Kyla Wilson. All rights reserved. // import Foundation // API let rootURL = "https://swapi.co/api" let planetsURL = "/planets" let filmsURL = "/films" // INDENTIFERS let characterCellIndetifer = "CharacterCell" // SEGUES
class Solution { func tree2str(_ t: TreeNode?) -> String { if t == nil { return "" } var left = "(\(tree2str(t?.left)))" var right = "(\(tree2str(t?.right)))" if right == "()" { right = "" if left == "()" { left = "" } } return t!.val.description + left + right } }
/* See LICENSE folder for this sample’s licensing information. Abstract: Types that conform to the QueryItemRepresentable protocol must implement properties that allow it to be saved as a query item in a URL. */ import Foundation protocol QueryItemRepresentable { var queryItem: URLQueryItem { get } static var queryItemKey: String { get } }
// // ChartViewController.swift // HSStockChartDemo // // Created by Hanson on 16/9/6. // Copyright © 2016年 hanson. All rights reserved. // import UIKit import SwiftyJSON enum HSChartType: Int { case timeLineForDay case timeLineForFiveday case kLineForDay case kLineForWeek case kLineForMonth } class ChartViewController: UIViewController { var chartType: HSChartType = .timeLineForDay var timeLineView: HSTimeLineView? // MARK: - Life Circle override func viewDidLoad() { super.viewDidLoad() setUpViewController() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func viewWillAppear(_ animated: Bool) { } // MARK: - Function func setUpViewController() { let stockBasicInfo = HSStockBasicInfoModel.getStockBasicInfoModel(getJsonDataFromFile("SZ300033")) switch chartType { case .timeLineForDay: timeLineView = HSTimeLineView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 300), topOffSet: 10, leftOffSet: 5, bottomOffSet: 5, rightOffSet: 5) let modelArray = HSTimeLineModel.getTimeLineModelArray(getJsonDataFromFile("OneDayTimeLine"), type: chartType, basicInfo: stockBasicInfo) timeLineView?.dataT = modelArray timeLineView!.isUserInteractionEnabled = true timeLineView!.tag = chartType.rawValue self.view.addSubview(timeLineView!) case .timeLineForFiveday: let stockChartView = HSTimeLineView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 300), topOffSet: 10, leftOffSet: 5, bottomOffSet: 5, rightOffSet: 5) let modelArray = HSTimeLineModel.getTimeLineModelArray(getJsonDataFromFile("FiveDayTimeLine"), type: chartType, basicInfo: stockBasicInfo) stockChartView.dataT = modelArray stockChartView.showFiveDayLabel = true stockChartView.isUserInteractionEnabled = true stockChartView.tag = chartType.rawValue self.view.addSubview(stockChartView) case .kLineForDay: let stockChartView = HSKLineStockChartView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 300)) let modelArray = HSKLineModel.getKLineModelArray(getJsonDataFromFile("DaylyKLine")) stockChartView.setUpData(modelArray) stockChartView.tag = chartType.rawValue stockChartView.tag = chartType.rawValue self.view.addSubview(stockChartView) case .kLineForWeek: let stockChartView = HSKLineStockChartView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 300)) let modelArray = HSKLineModel.getKLineModelArray(getJsonDataFromFile("WeeklyKLine")) stockChartView.monthInterval = 4 stockChartView.setUpData(modelArray) stockChartView.tag = chartType.rawValue self.view.addSubview(stockChartView) case .kLineForMonth: let stockChartView = HSKLineStockChartView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 300)) let modelArray = HSKLineModel.getKLineModelArray(getJsonDataFromFile("MonthlyKLine")) stockChartView.monthInterval = 12 stockChartView.setUpData(modelArray) stockChartView.tag = chartType.rawValue self.view.addSubview(stockChartView) } } func getJsonDataFromFile(_ fileName: String) -> JSON { let pathForResource = Bundle.main.path(forResource: fileName, ofType: "json") let content = try! String(contentsOfFile: pathForResource!, encoding: String.Encoding.utf8) let jsonContent = content.data(using: String.Encoding.utf8)! return JSON(data: jsonContent) } }
// // ChangePasswordViewController.swift // AV TEST AID // // Created by Timileyin Ogunsola on 05/07/2021. // Copyright © 2021 TopTier labs. All rights reserved. // import Foundation import UIKit import RxCocoa import RxSwift class ChangePasswordViewController: BaseViewController { @IBOutlet weak var currentPasswordEditText: PasswordToggleTextField! @IBOutlet weak var newPasswordEditText: PasswordToggleTextField! @IBOutlet weak var confirmPasswordEditText: PasswordToggleTextField! private var currentpasswordController: OutlinedTextInputController! private var newpasswordController: OutlinedTextInputController! private var confirmpasswordController: OutlinedTextInputController! var viewModel : ChangePasswordViewModel! override func viewDidLoad() { super.viewDidLoad() setupView() bindViewModel() } func setupView() { currentpasswordController = OutlinedTextInputController(textInput: currentPasswordEditText) newpasswordController = OutlinedTextInputController(textInput: newPasswordEditText) confirmpasswordController = OutlinedTextInputController(textInput: confirmPasswordEditText) } override func getViewModel() -> BaseViewModel { viewModel } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.setNavigationBarHidden(false, animated: true) } // MARK: - Navigation private func bindViewModel(){ viewModel.changePasswordState.subscribe(onNext: {state in if state { let action = UIAlertAction(title: "Continue", style: .default) { [weak self] _ in self?.navigationController?.popViewController(animated: true) } self.showDialog(withMessage: "Your password has been changed successfully", action: action) } }).disposed(by: disposeBag) } @IBAction func saveNewPassword(_ sender: Any) { Validator.clearErrors(textControllers: currentpasswordController, newpasswordController, confirmpasswordController) if !Validator.validate(textControllers: currentpasswordController, newpasswordController) { return } if newPasswordEditText.text != confirmPasswordEditText.text { let errorMessage = "Passwords dont match" confirmpasswordController.setErrorText(errorMessage, errorAccessibilityValue: errorMessage) return } viewModel.changePassword(oldPassword: currentPasswordEditText.text!, newPassword: newPasswordEditText.text!) } }
// // UIColor+Application.swift // import UIKit // MARK: - Application colors extension UIColor { convenience init(red: Int, green: Int, blue: Int, alpha: CGFloat) { self.init( red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: alpha ) } convenience init(hex: Int, alpha: CGFloat = 1.0) { self.init( red: (hex >> 16) & 0xFF, green: (hex >> 8) & 0xFF, blue: hex & 0xFF, alpha: alpha ) } }
import Foundation import Alamofire import HTTPClient public extension HttpMethod { var toAlamofireMethod: Alamofire.HTTPMethod { switch self { case .options: return .options case .get: return .get case .head: return .head case .post: return .post case .put: return .put case .patch: return .patch case .delete: return .delete case .trace: return .trace case .connect: return .connect } } }
// // SettingsMenu.swift // Bird-A-Poo // // Created by Báthory Krisztián on 2019. 04. 02.. // Copyright © 2019. Golden Games. All rights reserved. // import SpriteKit.SKSpriteNode class SettingsMenu: SKScene { var volumePower = SKLabelNode() var volumeUpButton = SKSpriteNode(imageNamed: "VolumeAdjuster") var volumeDownButton = SKSpriteNode(imageNamed: "VolumeAdjuster") var toggleButtons = [UserSetButton]() var returnButton = SKSpriteNode() var returnButtonPosX: CGFloat? var returnButtonPosy: CGFloat? var advancedSettingButton = SKSpriteNode() var buttonClickAudio = SKAudioNode(fileNamed: "ButtonClick.wav") override func didMove(to view: SKView) { let background = SKSpriteNode(imageNamed: "SettingsMenuBackground") background.name = "Background" background.size = CGSize(width: (scene!.frame.size.width), height: scene!.frame.size.height) background.anchorPoint = CGPoint(x: 0.5, y: 0.5) background.zPosition = -1 self.addChild(background) self.addChild(designLabel(SKLabelNode(), WithText: "TUTORIAL", withPosition: CGPoint(x: -(self.frame.size.width - self.frame.size.width * 0.85), y: -(self.frame.size.height - self.frame.size.height * 1.25)), withFontSize: 87)) self.addChild(designLabel(SKLabelNode(), WithText: "FPS", withPosition: CGPoint(x: -(self.frame.size.width - self.frame.size.width * 0.84), y: -(self.frame.size.height - self.frame.size.height * 1.05)), withFontSize: 110)) self.addChild(designLabel(SKLabelNode(), WithText: "VOLUME", withPosition: CGPoint(x: -(self.frame.size.width - self.frame.size.width * 0.839), y: -(self.frame.size.height - self.frame.size.height * 0.85)), withFontSize: 95)) self.addChild(designLabel(volumePower, WithText: UserDefaults.standard.value(forKey: "UserVolumePower") as? String ?? "50", withPosition: CGPoint(x: -(self.frame.size.width - self.frame.size.width * 1.333), y: -(self.frame.size.height - self.frame.size.height * 0.8542)), withFontSize: 70)) UserDefaults.standard.setValue(volumePower.text, forKey: "UserVolumePower") UserDefaults.standard.synchronize() toggleButtons = [UserSetButton(key: "TutorialState", defaultState: "ToggleButton1"), UserSetButton(key: "FPSState", defaultState: "ToggleButton2")] toggleButtons[0].createButton(posX: -(self.frame.size.width - self.frame.size.width * 1.33), posY: -(self.frame.size.height - self.frame.size.height * 1.2695)) toggleButtons[1].createButton(posX: -(self.frame.size.width - self.frame.size.width * 1.33), posY: -(self.frame.size.height - self.frame.size.height * 1.0728)) returnButton = ButtonGenerator.generateButton(imageName: "ReturnButton", scale: 0.1, position: CGPoint(x: returnButtonPosX!, y: returnButtonPosy!)) advancedSettingButton = ButtonGenerator.generateButton(imageName: "AdvancedSettingsButton", scale: 1, position: CGPoint(x: 0, y: -(self.frame.size.height - self.frame.size.height * 0.695))) positionVolumeButton(button: volumeUpButton, position: CGPoint(x: -(self.frame.size.width - self.frame.size.width * 1.333), y: -(self.frame.size.height - self.frame.size.height * 0.92))) positionVolumeButton(button: volumeDownButton, position: CGPoint(x: -(self.frame.size.width - self.frame.size.width * 1.333), y: -(self.frame.size.height - self.frame.size.height * 0.8185)), isRotated: true) if volumePower.text! == "100" { volumeUpButton.isHidden = true } else if volumePower.text! == "0" { volumeDownButton.isHidden = true } self.addChild(returnButton) self.addChild(advancedSettingButton) for i in 0...1 { self.addChild(toggleButtons[i].button) } buttonClickAudio.autoplayLooped = false buttonClickAudio.name = "button" self.addChild(buttonClickAudio) if !GameViewController.fullVersionEnabled { advancedSettingButton.isHidden = true } } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { for touch in touches { let pointOfTouch = touch.previousLocation(in: self) if returnButton.contains(pointOfTouch) { let fadeOut = SKAction.fadeAlpha(to: 0.3, duration: 0.1) let actionSequence = SKAction.sequence([fadeOut]) SoundManager.playSound(sound: buttonClickAudio) returnButton.run(actionSequence, completion: { if let scene = MainMenu(fileNamed: "MainMenu") { scene.scaleMode = .fill self.view?.presentScene(scene, transition: SKTransition.doorway(withDuration: 0.6)) } }) } else if toggleButtons[0].button.contains(pointOfTouch) || toggleButtons[1].button.contains(pointOfTouch) { var index: Int if toggleButtons[0].button.contains(pointOfTouch) { index = 0 } else { index = 1 } SoundManager.playSound(sound: buttonClickAudio) toggleButtons[index].changeState() toggleButtons[index].button.texture = SKTexture.init(imageNamed: toggleButtons[index].buttonState!) } else if volumeUpButton.contains(pointOfTouch) && volumeUpButton.isHidden == false { SoundManager.playSound(sound: buttonClickAudio) volumeUpButton.run(SKAction.sequence([ SKAction.fadeAlpha(by: -0.8, duration: 0.2), SKAction.fadeAlpha(by: 0.8, duration: 0.2) ])) let newVolumePower = Int(volumePower.text!)! + 10 volumePower.text = String(newVolumePower) UserDefaults.standard.setValue(volumePower.text, forKey: "UserVolumePower") UserDefaults.standard.synchronize() SongManager.shared.adjustVolume(volume: Float(newVolumePower) / 100) if volumePower.text! == "100" { volumeUpButton.isHidden = true } if volumePower.text! == "10" { volumeDownButton.isHidden = false } } else if volumeDownButton.contains(pointOfTouch) && volumeDownButton.isHidden == false { SoundManager.playSound(sound: buttonClickAudio) volumeDownButton.run(SKAction.sequence([ SKAction.fadeAlpha(by: -0.8, duration: 0.2), SKAction.fadeAlpha(by: 0.8, duration: 0.2) ])) let newVolumePower = Int(volumePower.text!)! - 10 volumePower.text = String(newVolumePower) UserDefaults.standard.setValue(volumePower.text, forKey: "UserVolumePower") UserDefaults.standard.synchronize() SongManager.shared.adjustVolume(volume: Float(newVolumePower) / 100) if volumePower.text! == "0" { volumeDownButton.isHidden = true } if volumePower.text! == "90" { volumeUpButton.isHidden = false } } else if advancedSettingButton.contains(pointOfTouch) && advancedSettingButton.isHidden == false { let fadeOut = SKAction.fadeAlpha(to: 0.3, duration: 0.1) let actionSequence = SKAction.sequence([fadeOut]) SoundManager.playSound(sound: buttonClickAudio) advancedSettingButton.run(actionSequence, completion: { if let scene = AdvancedSettingsMenu(fileNamed: "AdvancedSettingsMenu") { scene.returnButtonPosX = self.returnButton.position.x scene.returnButtonPosy = self.returnButton.position.y scene.scaleMode = .fill self.view?.presentScene(scene, transition: SKTransition.doorsOpenHorizontal(withDuration: 0.6)) } }) } } } func designLabel(_ label: SKLabelNode, WithText text: String, withPosition position: CGPoint, withFontSize fontSize: CGFloat) -> SKLabelNode { label.fontName = "Copperplate-Bold" label.fontSize = fontSize label.fontColor = .black label.text = text label.position = position label.zPosition = 1 return label } func positionVolumeButton(button: SKSpriteNode, position: CGPoint, isRotated: Bool = false) { button.setScale(0.5) button.position = position if isRotated { button.zRotation = .pi } self.addChild(button) } }
// // ModalCoordinator.swift // Wallet // // Created by 郑军铎 on 2018/11/1. // Copyright © 2018 ZJaDe. All rights reserved. // import UIKit public protocol ModalCoordinatorProtocol { associatedtype ViewConType: UIViewController func createViewCon() -> ViewConType func start(in viewCon: ViewConType) init() } public extension ModalCoordinatorProtocol { static func create() -> (coor: Self, viewCon: ViewConType) { let coor = self.init() return (coor, coor.createViewCon()) } } /// ZJaDe: 可以被modal出来的 协调器 public typealias AbstractModalCoordinator = Coordinator & Flow & ViewControllerConvertible & CoordinatorContainer & PresentJumpPlugin open class ModalCoordinator<ViewConType>: AbstractModalCoordinator, AssociatedViewControllerConvertible, ModalCoordinatorProtocol where ViewConType: CanCancelModalViewController & UIViewController { public required init() {} public var coordinators: [Coordinator] = [] public private(set) weak var viewCon: ViewConType? { didSet { oldValue?.coordinator = nil self.viewCon?.coordinator = self } } open func createViewCon() -> ViewConType { let viewCon = ViewConType() self.viewCon = viewCon return viewCon } open func start(in viewCon: ViewConType) { } open func didCancel() { } public func cancel(completion: (() -> Void)? = nil) { self.viewCon?.cancel(completion: completion) } }
// // SWBMatchAddFeedbackTableViewController.swift // SweepBright // // Created by Kaio Henrique on 4/7/16. // Copyright © 2016 madewithlove. All rights reserved. // import UIKit class SWBMatchAddFeedbackTableViewController: UITableViewController { @IBOutlet weak var feedbackButton: UIButton! @IBOutlet weak var feedbackRegistered: UIButton! override func viewDidLoad() { super.viewDidLoad() } @IBAction func registerFeedback(sender: AnyObject) { self.feedbackRegistered.hidden = false //Wait half second dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.5 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in self.dismissViewControllerAnimated(true, completion: nil) } } }
// // DarkCalculatorButton.swift // TipCalculator // // Created by Anthroman on 4/6/20. // Copyright © 2020 Anthroman. All rights reserved. // import UIKit class DarkCalculatorButton: CalculatorButton { override func awakeFromNib() { super.awakeFromNib() self.setUpDarkButtonUI() } func setUpDarkButtonUI() { self.backgroundColor = .darkGreen self.setTitleColor(.clayBrown, for: .normal) self.addCornerRadius(30) addAccentBorder() } }
// // DetailViewController.swift // Assignment920 // // Created by Hongfei Zheng on 9/20/21. // import UIKit class DetailViewController: UIViewController { var image: UIImage? var text: String? var company: String? @IBOutlet weak var imageView1: UIImageView! @IBOutlet weak var labelView1: UILabel! @IBOutlet weak var companyLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() imageView1.image = image labelView1.text = text companyLabel.text = company } }
// // WRImageBrowserDefine.swift // WRImageBrowser // // Created by 项辉 on 2020/9/29. // import UIKit // MARK:- Define fileprivate typealias Define = WRImageBrowserViewController extension Define { /** 浏览方向枚举. ``` case horizontal case vertical ``` */ public enum BrowserDirection { /// 左右浏览. case horizontal /// 上下浏览. case vertical } /** 支持的浏览样式枚举. ``` case linear case carousel ``` */ public enum BrowserStyle { /// 线性浏览,有头有尾. case linear /// 轮训浏览,无头无尾. case carousel } /** 绘制方向枚举. ``` case previousToNext case nextToPrevious ``` - note: 这是绘制的顺序,而不是绘制的位置,他决定了谁绘制在上层,谁绘制在下层. */ public enum ContentDrawOrder { /// 绘制顺序为 [previous]-[current]-[next]. case previousToNext /// 绘制顺序为 [next]-[current]-[previous] . case nextToPrevious } } // MARK:- WRImageBrowserViewControllerDataSource public protocol WRImageBrowserViewControllerDataSource: class { /** 完成回调. <必选> - parameter index: 图片索引. - parameter image: 需要展示的图片. - parameter zoomScale: 图片可缩放的级别. - parameter error: 收到图片后的错误. */ typealias CompletionBlock = (_ index: Int, _ image: UIImage?, _ zoomScale: ZoomScale?, _ error: Error?) -> Void /** 浏览器中展示的项目个数委托. - parameter imageBrowser: 图片浏览器. - returns: 展示的个数. */ func numberOfItems(in imageBrowser: WRImageBrowserViewController) -> Int /** 指定索引的图片配置. <必选> - parameter imageBrowser: 图片浏览器. - parameter index: 图片索引. - parameter completion: 获取图片资源时的完成回调. */ func mediaBrowser(_ imageBrowser: WRImageBrowserViewController, imageAt index: Int, completion: @escaping CompletionBlock) } // MARK:- WRImageBrowserViewControllerDelegate public protocol WRImageBrowserViewControllerDelegate: class { /** 当前展示的图片索引回调 . <可选> - parameter imageBrowser: 图片浏览器. - parameter index: 图片索引. - note: 第一次加载时不会调用此方法,并且仅在左右滑动时才会调用此方法. */ func mediaBrowser(_ imageBrowser: WRImageBrowserViewController, didChangeFocusTo index: Int) } extension WRImageBrowserViewControllerDelegate { public func mediaBrowser(_ mediaBrowser: WRImageBrowserViewController, didChangeFocusTo index: Int) {} } // MARK:- ZoomScale /// 图片的缩放倍数 public struct ZoomScale { /// 最小缩放级别. public var minimumZoomScale: CGFloat /// 最大缩放级别. public var maximumZoomScale: CGFloat /// 默认缩放级别,1.0 ~ 3.0 public static let `default` = ZoomScale( minimum: 1.0, maximum: 3.0 ) /// 缩放比例。通过此可禁用缩放. public static let identity = ZoomScale( minimum: 1.0, maximum: 1.0 ) /** 初始化. - parameter minimum: 最小缩放级别. - parameter maximum: 最大缩放级别. */ public init(minimum: CGFloat, maximum: CGFloat) { minimumZoomScale = minimum maximumZoomScale = maximum } } // MARK: - WRImageBrowserViewControllerConstants fileprivate typealias WRImageBrowserViewControllerConstants = WRImageBrowserViewController extension WRImageBrowserViewControllerConstants { internal enum Constants { static let gapBetweenContents: CGFloat = 50.0 static let minimumVelocity: CGFloat = 15.0 static let minimumTranslation: CGFloat = 0.3 static let animationDuration = 0.3 static let updateFrameRate: CGFloat = 60.0 static let bounceFactor: CGFloat = 0.1 static let controlHideDelay = 3.0 enum Close { static let top: CGFloat = 8.0 static let trailing: CGFloat = -8.0 static let height: CGFloat = 30.0 static let minWidth: CGFloat = 30.0 static let contentInsets = UIEdgeInsets(top: 0.0, left: 8.0, bottom: 0.0, right: 8.0) static let borderWidth: CGFloat = 2.0 static let borderColor: UIColor = .white static let title = "Close" } enum PageControl { static let bottom: CGFloat = -10.0 static let tintColor: UIColor = .lightGray static let selectedTintColor: UIColor = .white } enum Title { static let top: CGFloat = 16.0 static let rect: CGRect = CGRect(x: 0, y: 0, width: 30, height: 30) } } }
// // WeatherCondition.swift // weatherwake // // Created by Bogdan Dumitrescu on 4/1/16. // Copyright © 2016 mready. All rights reserved. // import Foundation class WeatherCondition : NSObject { var temperature: Double! var minTemperature: Double! var maxTemperature: Double! // TODO: Add weather condition member var city: String! var date: Date! static func deserializeArray(_ json:[String: AnyObject]) -> [WeatherCondition]{ // TODO: Deserialize json array received as parameter // TODO: Extract city information and the forecast array // TODO: Iterate throught forecasts and create a new WeatherCondition // TODO: Return an array of the create WeatherConditions return [WeatherCondition]() } init(json: [String : Any]) { city = json["name"] as! String let mainDict = json["main"] as! [String: Any] temperature = mainDict["temp"] as! Double minTemperature = mainDict["temp_min"] as! Double maxTemperature = mainDict["temp_max"] as! Double let timestamp = json["dt"] as! Int date = Date(timeIntervalSince1970: TimeInterval(timestamp)) } func getTemperature() -> String { // TODO: Create a string with the temperature and return it return "" } }
// // TableItemAction.swift // TaskManagerApp // // Created by Chris Braunschweiler on 14.01.19. // Copyright © 2019 braunsch. All rights reserved. // import Foundation protocol TableItemAction {}
// // ProfileBuildViewController.swift // Nodus // // Created by Super on 5/10/17. // Copyright © 2017 Eden. All rights reserved. // import UIKit import CoreData import Photos import MobileCoreServices import SwiftyJSON import MBProgressHUD import Alamofire import Kingfisher let cellGap: CGFloat = 3.0 protocol UpdateProgressDelegate: class { func updateprogress() } class ProfileBuildViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextFieldDelegate { @IBOutlet weak var progressTableView: UITableView! @IBOutlet weak var tableView: UITableView! @IBOutlet weak var lbProgressValue: UILabel! let progressDotCount: Float = 13.0 var progressValue: Float = 0.0 var myUserInfo: User? @IBOutlet weak var progressTableViewWidthConstraint: NSLayoutConstraint! weak var delegate: UpdateProgressDelegate? let imagePicker = UIImagePickerController() var profilePhoto: UIImage? enum Category : Int{ case name = 0, occupation, interests_skills, lifestyle_philosophy, music_film, food_drink } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.hideKeyboardWhenTappedAround() if let user = Global.getMyUserInfo() { self.myUserInfo = user appDelegate.myInfo = user } imagePicker.delegate = self self.profilePhoto = Global.getMyPhoto() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) updateVerticalProgress() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func updateVerticalProgress() { var progress = 1 if myUserInfo?.interest != nil { progress += 1 } if myUserInfo?.lifestyle != nil { progress += 1 } if myUserInfo?.music != nil { progress += 1 } if myUserInfo?.food != nil { progress += 1 } self.progressValue = Float(progress) * 0.2 self.lbProgressValue.text = "\(progress * 20) %" self.progressTableView.reloadData() if progress == 5 { UIView.animate(withDuration: 0.6, animations: { () -> Void in self.progressTableViewWidthConstraint.constant = 22.0 self.progressTableView.isHidden = true self.lbProgressValue.isHidden = true self.view.layoutIfNeeded() }, completion: { (finished) -> Void in }) } else { self.progressTableViewWidthConstraint.constant = 68.0 self.progressTableView.isHidden = false self.lbProgressValue.isHidden = false self.view.layoutIfNeeded() } } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if tableView == self.tableView { return 6 } else { return 13 } } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if tableView == self.tableView { let cell = self.tableView.dequeueReusableCell(withIdentifier: "profile_factor_cell", for: indexPath) as! ProfileBuildCell cell.selectionStyle = .none cell.btnChangePhoto.tag = indexPath.row cell.btnChangePhoto.isEnabled = false cell.lbTitle.text = "" cell.txtMain.delegate = self cell.txtSub.delegate = self cell.txtMain.autocapitalizationType = .words cell.txtSub.autocapitalizationType = .words switch indexPath.row { case Category.name.rawValue: cell.backgroundImageView.backgroundColor = UIColor(netHex: 0xD8D8D8) if profilePhoto != nil { cell.photoImageView.image = profilePhoto } cell.txtMain.text = myUserInfo?.name cell.txtMain.placeholder = "Add Name" cell.txtMain.tag = 0 cell.txtSub.text = myUserInfo?.occupation cell.txtSub.placeholder = "Add Occupation" cell.txtSub.tag = 1 cell.btnChangePhoto.isEnabled = true break case Category.occupation.rawValue: cell.backgroundImageView.backgroundColor = UIColor(netHex: 0xD8D8D8) cell.photoImageView.isHidden = true cell.txtMain.placeholder = "Add Education" cell.txtMain.tag = 2 cell.txtSub.placeholder = "Add Academic Achievements" cell.txtSub.tag = 3 cell.txtMain.text = myUserInfo?.education cell.txtSub.text = myUserInfo?.education_achievement break case Category.interests_skills.rawValue: cell.backgroundImageView.backgroundColor = UIColor(netHex: TagBackgroundColor.red.rawValue) cell.photoImageView.image = UIImage(named: "interest_skills_button.png") cell.lbTitle.text = "Interests & Skills" cell.lbTitle.textColor = UIColor(netHex: TagColor.red_plus.rawValue) cell.txtMain.isHidden = true cell.txtSub.isHidden = true break case Category.lifestyle_philosophy.rawValue: cell.backgroundImageView.backgroundColor = UIColor(netHex: TagBackgroundColor.green.rawValue) cell.photoImageView.image = UIImage(named: "lifestyle_button.png") cell.lbTitle.text = "Lifestyle & Philosophy" cell.lbTitle.textColor = UIColor(netHex: TagColor.green_plus.rawValue) cell.txtMain.isHidden = true cell.txtSub.isHidden = true break case Category.music_film.rawValue: cell.backgroundImageView.backgroundColor = UIColor(netHex: TagBackgroundColor.blue.rawValue) cell.photoImageView.image = UIImage(named: "music_button.png") cell.lbTitle.text = "Music & Film" cell.lbTitle.textColor = UIColor(netHex: TagColor.blue_plus.rawValue) cell.txtMain.isHidden = true cell.txtSub.isHidden = true break case Category.food_drink.rawValue: cell.backgroundImageView.backgroundColor = UIColor(netHex: TagBackgroundColor.yellow.rawValue) cell.photoImageView.image = UIImage(named: "food_button.png") cell.lbTitle.text = "Food & Drink" cell.lbTitle.textColor = UIColor(netHex: TagColor.yellow_plus.rawValue) cell.txtMain.isHidden = true cell.txtSub.isHidden = true break default: cell.backgroundImageView.image = UIImage(named: "") } return cell } else { let cell = tableView.dequeueReusableCell(withIdentifier: "progressCell", for: indexPath) cell.selectionStyle = .none let progressImgV: UIImageView = cell.contentView.viewWithTag(12) as! UIImageView if(indexPath.row <= Int(progressValue * progressDotCount)) { progressImgV.image = UIImage(named:"homeProgressBig") } else { progressImgV.image = UIImage(named:"homeProgressSmall") } return cell } } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if tableView == self.tableView { return tableView.bounds.height / 6 } else { return (self.view.frame.size.height - 160) / 13 } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let matchVC = self.storyboard?.instantiateViewController(withIdentifier: "MatchFactorViewController") as! MatchFactorViewController switch indexPath.row { case Category.interests_skills.rawValue: matchVC.category = .interests_skills break case Category.lifestyle_philosophy.rawValue: matchVC.category = .lifestyle_philosophy break case Category.music_film.rawValue: matchVC.category = .music_film break case Category.food_drink.rawValue: matchVC.category = .food_drink break default: return } self.navigationController?.pushViewController(matchVC, animated: true) } @IBAction func onProfileBtnClick(_ sender: Any) { let profileVC = self.storyboard?.instantiateViewController(withIdentifier: "MyProfileViewController") as! MyProfileViewController self.present(profileVC, animated: true, completion: nil) } @IBAction func onSwipeDeckBtnClick(_ sender: Any) { self.performSegue(withIdentifier: "toSwipeDeckSegue", sender: self) } @IBAction func onSettingsBtnClick(_ sender: UIButton) { self.performSegue(withIdentifier: "toSettingsViewSegue", sender: self) } @IBAction func onProfileImageChange(_ sender: Any) { let button = sender as! UIButton if button.tag > 0 { return } let actionSheetController: UIAlertController = UIAlertController() let cancelActionButton = UIAlertAction(title: "Cancel", style: .cancel) { _ in print("Cancel") } actionSheetController.addAction(cancelActionButton) let saveActionButton = UIAlertAction(title: "Take a photo", style: .default) { _ in self.takePhoto() } actionSheetController.addAction(saveActionButton) let deleteActionButton = UIAlertAction(title: "Select photo from library", style: .default) { _ in self.selectPhotoFromLibrary() } actionSheetController.addAction(deleteActionButton) self.present(actionSheetController, animated: true, completion: nil) } func takePhoto() { imagePicker.allowsEditing = false imagePicker.sourceType = .camera imagePicker.mediaTypes = [kUTTypeImage as String] imagePicker.modalPresentationStyle = .fullScreen self.present(imagePicker, animated: true, completion: nil) } func selectPhotoFromLibrary() { imagePicker.allowsEditing = false imagePicker.sourceType = .photoLibrary imagePicker.mediaTypes = UIImagePickerController.availableMediaTypes(for: .photoLibrary)! self.present(imagePicker, animated: true, completion: nil) } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { let chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage Global.saveImage(image: chosenImage, fileName: Constants.PROFILE_PHOTO) profilePhoto = chosenImage self.tableView.reloadData() dismiss(animated:true, completion: nil) updatePhoto(photo: chosenImage) } func updatePhoto(photo: UIImage) { let url = Constants.BASE_URL + "/users/photo" let imageData = UIImageJPEGRepresentation(photo, 0.3) let headers = ["Authorization": Global.getAuthToken()] MBProgressHUD.showAdded(to: self.view, animated: true) Alamofire.upload( multipartFormData:{ multipartFormData in multipartFormData.append(imageData!, withName: "img", fileName: Constants.PROFILE_PHOTO, mimeType: "image/jpeg")}, usingThreshold: UInt64.init(), to: url, method: .post, headers: headers, encodingCompletion: { encodingResult in switch encodingResult { case .success(let upload, _, _): upload.responseJSON { response in debugPrint(response) } case .failure(let encodingError): print(encodingError) } MBProgressHUD.hide(for: self.view, animated: true) } ) } // MARK: Textfield Delegate func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } func textFieldDidEndEditing(_ textField: UITextField) { var key = "" switch textField.tag { case 0: key = Fields.NAME.rawValue break case 1: key = Fields.OCCUPATION.rawValue break case 2: key = Fields.EDUCATION.rawValue break default: key = Fields.EDUCATION_ACHIEVEMENT.rawValue break } self.updateProfileInfo(value: textField.text!, key: key) } func updateProfileInfo(value: String, key: String) { var paramters = [String: Any]() paramters[key] = value RestApiManager.sharedInstance.getManager().request(Router.updateProfile(paramters)) .responseJSON { response in if let data = response.result.value { let result = JSON(data) if result[Fields.SUCCESS.rawValue].stringValue == SERVER_RESPONSE.success.rawValue { let user = UserAdapter(json: result) user.updateData(user: self.myUserInfo!) } else { print(result) } } else { print("\(response.error?.localizedDescription)") } } } }
import UIKit import GooglePlaces import EventKit class MapsViewController: UIViewController, UITextFieldDelegate, UIPickerViewDataSource, UIPickerViewDelegate { var resultsViewController: GMSAutocompleteResultsViewController? var searchController: UISearchController? let defaults = UserDefaults.standard var resultView: UITextView? var dateFormatter : DateFormatter! var dateFormatter1 : DateFormatter! @IBAction func backButton(_ sender: UIButton) { dismiss(animated: false, completion: nil) } @IBOutlet weak var titleEditor: UITextField! @IBOutlet weak var dateTextField: UITextField! @IBOutlet weak var dateTextEndField: UITextField! var dateStart: Date? var dateEnd: Date? @IBOutlet weak var durationTextField: UITextField! @IBOutlet weak var locationLabel: UILabel! @IBOutlet weak var textminutes: UITextField! @IBAction func schedule(_ sender: Any) { if var contacts = defaults.stringArray(forKey: "participants") { // let loggedInUser = defaults.value(forKey: "loggedInUser") as! String; for i in 0 ..< contacts.count { var s = contacts[i]; s = s.replacingOccurrences(of: "\\D", with: "", options: .regularExpression, range: s.startIndex..<s.endIndex); s = s.substring(from:s.index(s.endIndex, offsetBy: -10)) contacts[i] = s; } var duration = Double(durationTextField.text!) if(textminutes.text == "00") { duration = duration! + 0 } if(textminutes.text == "15") { duration = duration! + 0.25 } if(textminutes.text == "30") { duration = duration! + 0.5 } if(textminutes.text == "45") { duration = duration! + 0.75 } DataService.InitiateMeeting(mapsInstance: self, contacts: contacts, loggedInUser: loggedInUser, location: locationLabel.text!, startTime: dateTextField.text!, endTime: dateTextEndField.text!, duration: duration!, title: titleEditor.text!); } } func onIntiatiateMeetingComplete(){ let alert = UIAlertController(title: "Alert", message: "Meeting has been scheduled succesfully", preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { [weak alert] (_) in self.performSegue(withIdentifier: "back2Home", sender: self) })) self.present(alert, animated: true, completion: nil) } let hoursPicker = UIPickerView() var hData = ["0","1","2","3","4","5","6","7","8","9"] let minPicker = UIPickerView() var mData = ["00","15","30","45"] let datePicker = UIDatePicker() let datePickerEnd = UIDatePicker() func textFieldDidBeginEditing(_ textField: UITextField) { let toolBar = UIToolbar() toolBar.barStyle = UIBarStyle.default toolBar.isTranslucent = true toolBar.tintColor = UIColor(red: 76/255, green: 217/255, blue: 100/255, alpha: 1) toolBar.sizeToFit() let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.bordered, target: self, action: Selector(("donePicker"))) let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil) toolBar.setItems([spaceButton, spaceButton, doneButton], animated: false) toolBar.isUserInteractionEnabled = true textField.inputAccessoryView = toolBar if textField.placeholder == "End Date & Time" { self.datePickerEnd.minimumDate = NSDate() as Date self.datePickerEnd.minuteInterval = 30 textField.inputView = self.datePickerEnd self.datePickerEnd.addTarget(self, action: #selector(MapsViewController.datePickerValueChangedEnd), for: UIControlEvents.valueChanged) } else if(textField.placeholder == "Start Date & Time"){ self.datePicker.minimumDate = NSDate() as Date self.datePicker.minuteInterval = 30 textField.inputView = self.datePicker self.datePicker.addTarget(self, action: #selector(MapsViewController.datePickerValueChanged), for: UIControlEvents.valueChanged) } else if(textField.placeholder == "hh"){ durationTextField.inputView = self.hoursPicker } else if(textField.placeholder == "mm"){ textminutes.inputView = self.minPicker } } func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { if(pickerView.tag == 1) { return hData.count } else { return mData.count } } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { if(pickerView.tag == 1) { durationTextField.text = hData[row] } else { textminutes.text = mData[row] } } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { if(pickerView.tag == 1) { return hData[row] } else { return mData[row] } } static func getFreeTime(meetingId: Int, strtDate: Date?, endDate: Date?, duration: Double) { let eventStore = EKEventStore(); var oCalendars: [EKCalendar]? var dDateFormatter : DateFormatter! var dDateFormatter1 : DateFormatter! var strts = [String]() var ends = [String]() var sDate = strtDate; oCalendars = eventStore.calendars(for: EKEntityType.event) dDateFormatter = DateFormatter() dDateFormatter.dateFormat = "HH"; dDateFormatter1 = DateFormatter() dDateFormatter1.dateFormat = "YYYY-MM-dd HH:mm"; let dates = duration*3600 var f = true while(sDate!<endDate!.addingTimeInterval(-dates) ) { print(sDate) print(Int(dDateFormatter.string(from: sDate!))) print(Int(dDateFormatter.string(from: sDate!+TimeInterval(dates)))) for calendar in oCalendars! { let predicate = eventStore.predicateForEvents(withStart: sDate! as Date, end: (sDate! as Date)+TimeInterval(dates), calendars: [calendar]) let events = eventStore.events(matching: predicate) if(events.count == 0 && Int(dDateFormatter.string(from: sDate!))! >= 7 && Int(dDateFormatter.string(from: sDate!+TimeInterval(dates)))! <= 21 && Int(dDateFormatter.string(from: sDate!))! < Int(dDateFormatter.string(from: sDate!+TimeInterval(dates)))!) { } else{ f = false break; } } if(f) { print("added") strts.append(dDateFormatter1.string(from: sDate!)) ends.append(dDateFormatter1.string(from: sDate!+TimeInterval(dates))) } f = true; sDate = sDate?.addingTimeInterval(TimeInterval(3600)); } let userDefaults = UserDefaults.standard; var loggedInUser = userDefaults.value(forKey: "loggedInUser") as! String; DataService.SendAvailabilities(strts: strts, ends: ends, meetingId: meetingId, loggedInUser: loggedInUser); } func donePicker() { dateTextField.resignFirstResponder() dateTextEndField.resignFirstResponder() durationTextField.resignFirstResponder() textminutes.resignFirstResponder() titleEditor.resignFirstResponder() } func datePickerValueChangedEnd(sender:UIDatePicker) { dateTextEndField.text = dateFormatter.string(from: sender.date) dateEnd = sender.date } func datePickerValueChanged(sender:UIDatePicker) { dateTextField.text = dateFormatter.string(from: sender.date) dateStart = sender.date } @IBAction func nextFromLocation(_ sender: UIButton) { dismiss(animated: false, completion: nil) } override func viewDidLoad() { super.viewDidLoad() hoursPicker.dataSource = self hoursPicker.delegate = self minPicker.dataSource = self minPicker.delegate = self hoursPicker.tag = 1 minPicker.tag = 2 //durationTextField.keyboardType = UIKeyboardType.numberPad; dateFormatter = DateFormatter() dateFormatter.dateFormat = "MMMM dd YYYY hh:mm a"; resultsViewController = GMSAutocompleteResultsViewController() resultsViewController?.delegate = self GMSPlacesClient.provideAPIKey("AIzaSyDhYKzloCkhWrY7hqKtZZdvqmuU5i69zas") searchController = UISearchController(searchResultsController: resultsViewController) searchController?.searchResultsUpdater = resultsViewController let subView = UIView(frame: CGRect(x: 100, y: 110, width: 315, height: 300)) subView.addSubview((searchController?.searchBar)!) self.view.addSubview(subView) searchController?.searchBar.sizeToFit() searchController?.hidesNavigationBarDuringPresentation = false // When UISearchController presents the results view, present it in // this view controller, not one further up the chain. self.definesPresentationContext = true } } // Handle the user's selection. extension MapsViewController: GMSAutocompleteResultsViewControllerDelegate { func resultsController(_ resultsController: GMSAutocompleteResultsViewController, didAutocompleteWith place: GMSPlace) { searchController?.isActive = false // Do something with the selected place. print("Place name: ", place.name) print("Place address: ", place.formattedAddress) print("Place attributions: ", place.attributions) locationLabel.text = place.formattedAddress } func resultsController(_ resultsController: GMSAutocompleteResultsViewController, didFailAutocompleteWithError error: Error){ // TODO: handle the error. print(error) } // Turn the network activity indicator on and off again. func didRequestAutocompletePredictionsForResultsController(resultsController: GMSAutocompleteResultsViewController) { UIApplication.shared.isNetworkActivityIndicatorVisible = true } func didUpdateAutocompletePredictionsForResultsController(resultsController: GMSAutocompleteResultsViewController) { UIApplication.shared.isNetworkActivityIndicatorVisible = false } }
import UIKit extension UIViewController { /** Opens a popup dialog and if the given message is not empty shows the message, otherwise it opens the popup dialog with dynamic message for example an error occupied. - Parameters: - message: An error message that will be showed in popup dialog. - Postcondition: After completing this method a pop up will occur at the middle of the screen. */ func showErrorAlert(message: String? = nil) { let title = "Opps" let defaultMessage = "We're sorry. An error occupied. Please try again later." let alertController = UIAlertController(title: title, message: message ?? defaultMessage, preferredStyle: .alert) let okAction = UIAlertAction(title: "OK", style: .cancel, handler: nil) alertController.addAction(okAction) self.present(alertController, animated: true, completion: nil) } /** Opens a popup dialog that will gives feedback to user after he calls a function that changes the content of the system. For example when the user updates his quiz it opens a pop up dialog saying quiz is updated successfully. - Parameters: - message: A text message that gives feedback to user about intended action. - Precondition: `message` must be non-nil - Postcondition: After completing this method a pop up will occur at the middle of the screen. */ func showDismissAlert(_ message: String) { let alertController = UIAlertController(title: nil, message: message, preferredStyle: .alert) let okAction = UIAlertAction(title: "OK", style: .default) { (_) in alertController.dismiss(animated: true, completion: nil) self.navigationController?.popViewController(animated: true) } alertController.addAction(okAction) self.present(alertController, animated: true, completion: nil) } }
// // TwitterClient.swift // Twitter Demo // // Created by Fateh Singh on 4/11/17. // Copyright © 2017 Fateh Singh. All rights reserved. // import UIKit import BDBOAuth1Manager class TwitterClient: BDBOAuth1SessionManager { static let sharedInstance = TwitterClient(baseURL: URL(string: "https://api.twitter.com")!, consumerKey: "MhP3I2FndUVMKmKvJTbAQWLOk", consumerSecret: "vYtdvEkt42h3nrEbwOqVwsK5k3bNgNeqVoHkBQC6rcJYiWNlOs")! var loginSuccess: (() -> ())? var loginFailure: ((Error) -> ())? func login(success: @escaping () -> (), failure: @escaping (Error) -> ()) { loginSuccess = success loginFailure = failure deauthorize() fetchRequestToken(withPath: "oauth/request_token", method: "GET", callbackURL: URL(string: "twitterdemo://oauth"), scope: nil, success: { (requestToken: BDBOAuth1Credential!) -> Void in print("got token\n") let urlString = "https://api.twitter.com/oauth/authorize?oauth_token=" + requestToken.token let aURL = URL(string: urlString)! UIApplication.shared.open(aURL, options: [String : Any](), completionHandler: { (Bool) -> Void in }) }) { (error: Error!) -> Void in print("error \(error.localizedDescription)") self.loginFailure?(error) } } func logout() { User.currentUser = nil deauthorize() NotificationCenter.default.post(name: NSNotification.Name(rawValue: "didLogOut"), object: nil) } func handleOpenURL(url: URL) { let requestToken = BDBOAuth1Credential(queryString: url.query) fetchAccessToken(withPath: "oauth/access_token", method: "POST", requestToken: requestToken, success: { (accessToken: BDBOAuth1Credential!) in self.loginSuccess?() }) { (error: Error!) in print(error?.localizedDescription ?? 0) self.loginFailure?(error) } } func currentAccount(success: @escaping (User) -> (), failure: @escaping (Error) -> ()) { get("1.1/account/verify_credentials.json", parameters: nil, progress: nil, success: { (task: URLSessionDataTask, response: Any?) in print(response) let user: User = User(dictionary: response as! NSDictionary) success(user) }, failure: { (task: URLSessionDataTask?, error: Error) in failure(error) }) } func homeTimeline(success: @escaping ([Tweet]) -> (), failure: @escaping (Error) -> ()) { get("1.1/statuses/home_timeline.json", parameters: nil, progress: nil, success: { (task: URLSessionDataTask, response: Any?) in let dictionaries: [NSDictionary] = response as! [NSDictionary] let tweets: [Tweet] = Tweet.tweetsWithArray(dictionaries: dictionaries) success(tweets) }, failure: { (task: URLSessionDataTask?, error: Error) -> Void in failure(error) }) } func getMentions(success: @escaping ([Tweet]) -> (), failure: @escaping (Error) -> ()) { get("1.1/statuses/mentions_timeline.json", parameters: nil, progress: nil, success: { (task: URLSessionDataTask, response: Any?) in let dictionaries: [NSDictionary] = response as! [NSDictionary] let tweets: [Tweet] = Tweet.tweetsWithArray(dictionaries: dictionaries) success(tweets) }, failure: { (task: URLSessionDataTask?, error: Error) -> Void in failure(error) }) } func getUserTimeline(id: Int64, success: @escaping ([Tweet]) -> (), failure: @escaping (Error) -> ()) { let params: Dictionary = ["user_id": id] get("1.1/statuses/user_timeline.json", parameters: params, progress: nil, success: { (task: URLSessionDataTask, response: Any?) in let dictionaries: [NSDictionary] = response as! [NSDictionary] let tweets: [Tweet] = Tweet.tweetsWithArray(dictionaries: dictionaries) success(tweets) }, failure: { (task: URLSessionDataTask?, error: Error) -> Void in failure(error) }) } func getUserInfo(id: Int64, success: @escaping (User) -> (), failure: @escaping (Error) -> ()) { let params: Dictionary = ["user_id": id] get("1.1/users/show.json", parameters: params, progress: nil, success: { (task: URLSessionDataTask, response: Any?) in let user: User = User(dictionary: response as! NSDictionary) success(user) }, failure: { (task: URLSessionDataTask?, error: Error) -> Void in failure(error) }) } func sendTweet(message: String, success: @escaping () -> (), failure: @escaping (Error) -> ()) { let params: Dictionary = ["status": message] post("1.1/statuses/update.json", parameters: params, progress: nil, success: { (task: URLSessionDataTask, response: Any?) in success() }, failure: { (task: URLSessionDataTask?, error: Error) in failure(error) }) } func favouriteTweet(id: Int64, success: @escaping () -> (), failure: @escaping (Error) -> ()) { let params: Dictionary = ["id": id] post("1.1/favorites/create.json", parameters: params, progress: nil, success: { (task: URLSessionDataTask, response: Any?) in success() }, failure: { (task: URLSessionDataTask?, error: Error) in failure(error) }) } func retweetTweet(id: Int64, success: @escaping () -> (), failure: @escaping (Error) -> ()) { let params: Dictionary = ["id": id] post("1.1/statuses/retweet/\(id).json", parameters: params, progress: nil, success: { (task: URLSessionDataTask, response: Any?) in success() }, failure: { (task: URLSessionDataTask?, error: Error) in failure(error) }) } }
import SQLKit import SQLKitBenchmark import XCTest final class SQLKitTests: XCTestCase { func testBenchmarker() throws { let db = TestDatabase() let benchmarker = SQLBenchmarker(on: db) try benchmarker.run() } func testLockingClause_forUpdate() throws { let db = TestDatabase() try db.select().column("*") .from("planets") .where("name", .equal, "Earth") .for(.update) .run().wait() XCTAssertEqual(db.results[0], "SELECT * FROM `planets` WHERE `name` = ? FOR UPDATE") } func testLockingClause_lockInShareMode() throws { let db = TestDatabase() try db.select().column("*") .from("planets") .where("name", .equal, "Earth") .lockingClause(SQLRaw("LOCK IN SHARE MODE")) .run().wait() XCTAssertEqual(db.results[0], "SELECT * FROM `planets` WHERE `name` = ? LOCK IN SHARE MODE") } func testRawQueryStringInterpolation() throws { let db = TestDatabase() let (table, planet) = ("planets", "Earth") let builder = db.raw("SELECT * FROM \(table) WHERE name = \(bind: planet)") var serializer = SQLSerializer(dialect: GenericDialect()) builder.query.serialize(to: &serializer) XCTAssertEqual(serializer.sql, "SELECT * FROM planets WHERE name = ?") XCTAssert(serializer.binds.first! as! String == "Earth") } func testGroupByHaving() throws { let db = TestDatabase() try db.select().column("*") .from("planets") .groupBy("color") .having("color", .equal, "blue") .run().wait() XCTAssertEqual(db.results[0], "SELECT * FROM `planets` GROUP BY `color` HAVING `color` = ?") } func testIfExists() throws { let db = TestDatabase() try db.drop(table: "planets").ifExists().run().wait() XCTAssertEqual(db.results[0], "DROP TABLE IF EXISTS `planets`") db.dialect = GenericDialect(supportsIfExists: false) try db.drop(table: "planets").ifExists().run().wait() XCTAssertEqual(db.results[1], "DROP TABLE `planets`") } }
// // OfferListCell.swift // LocalStars // // Created by Michal Tuszynski on 21/11/2020. // import UIKit final class OfferListCell: UITableViewCell { @IBOutlet var offerImageView: UIImageView! @IBOutlet var titleLabel: UILabel! @IBOutlet var priceLabel: UILabel! @IBOutlet var categoryLabel: UILabel! }
// // CommandType.swift // // // Created by Igor Shelopaev on 01.06.2021. // import Foundation /// Type of an action to perfome public enum CommandType { case create case read case update case delete /// do nothing for a default state case idle }
// // Messageable.swift // MMWallet // // Created by Dmitry Muravev on 14.07.2018. // Copyright © 2018 micromoney. All rights reserved. // import UIKit protocol Messageable { func showMessage(title: String?, message: String?) } extension Messageable where Self: UIViewController { func showMessage(title: String?, message: String?) { let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil)) present(alert, animated: true, completion: nil) } }
// // SpeechBubbleView.swift // MB // // Created by Matt Beaney on 15/01/2017. // Copyright © 2017 Matt Beaney. All rights reserved. // import Foundation import UIKit class SpeechBubbleView: UITableViewCell { @IBOutlet weak var messageLabel: UILabel! @IBOutlet weak var leftTick: UIImageView! @IBOutlet weak var bg: UIView! @IBOutlet weak var loadingLbl: UILabel! @IBOutlet weak var loadingLblHeight: NSLayoutConstraint! var message: SpeechBubbleMessage? { didSet { configure() } } func configure() { self.backgroundColor = UIColor.clear self.leftTick.tintColor = #colorLiteral(red: 0.1764705926, green: 0.4980392158, blue: 0.7568627596, alpha: 1) bg.layer.cornerRadius = 7.0 self.clipsToBounds = true self.loadingLbl.alpha = 1.0 configureState() } func configureState() { guard let message = message else { return } messageLabel.text = message.message let showLeft = message.position == .left leftTick.alpha = showLeft ? 1.0 : 0.0 } }
// // MdHtmlViaMultimarkdown.swift // blog_content_updater // // Created by marc-medley on 2019.03.11. // Copyright © 2019 marc-medley. All rights reserved. // import Foundation func mdHtmlViaMultimarkdown(mdUrlIn: URL) -> String { let workPath = mdUrlIn.absoluteURL.deletingLastPathComponent().path mclog.debug("workPath = \(workPath)") var args: [String] = [] args = args + ["--nosmart"] args = args + ["--nolabels"] args = args + [mdUrlIn.path] let result = McProcess.run( commandPath: multimarkdownPath, withArguments: args, workDirectory: workPath ) //print("stdout:\n\(result.stdout)") //print("stderr:\n\(result.stderr)") return result.stdout } /******************************************************* ################################# ### MULTIMARKDOWN: `markdown` ### ################################# ### NOTE: Discount `markdown` and MultiMarkdown `markdown` have the same command name. ### Thus, Discount `markdown` and MultiMarkdown `markdown` mutually exclusive brew installs. # multimarkdown [OPTION...] [<FILE>...] # # <FILE> read input from file(s) -- use stdin if no files given # # Options: # --help Show help # --version Show version information # # -o, --output=FILE Send output to FILE # -t, --to=FORMAT Convert to FORMAT # FORMATs: html(default)|latex|beamer|memoir|mmd|odt|fodt|epub|opml|bundle|bundlezip # # -b, --batch Process each file separately # -c, --compatibility Markdown compatibility mode. # -f, --full Force a complete document # -s, --snippet Force a snippet # # -m, --metadata-keys List all metadata keys # -e, --extract Extract specified metadata # # --random Use random numbers for footnote anchors # # -a, --accept Accept all CriticMarkup changes # -r, --reject Reject all CriticMarkup changes # # --nosmart Disable smart typography # --nolabels Disable id attributes for headers # --notransclude Disable file transclusion # --opml Convert OPML source to plain text before processing # # -l, --lang=LANG language/smart quote localization, LANG = en|es|de|fr|he|nl|sv ### all preferred settings BODY_FILE="test.multimarkdown.a" multimarkdown \ --nosmart \ --nolabels \ $INPUT_FILE \ > $BODY_FILE.txt cat $HEADER_FILE $BODY_FILE.txt $FOOTER_FILE > $BODY_FILE.html *******************************************************/
// // plantDetailHeaderView.swift // swaybian // // Created by Eugene Liu on 6/1/18. // Copyright © 2018 csie. All rights reserved. // import UIKit class plantDetailHeaderView: UIView { @IBOutlet var headerImageView: UIImageView! @IBOutlet var nameLabel: UILabel! @IBOutlet var name2Label: UILabel! /* // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing code } */ }
// // CollectionViewController.swift // tiki-demo // // Created by Tom on 2/20/19. // Copyright © 2019 A Strange Studio. All rights reserved. // import UIKit private let reuseIdentifier = "cell" protocol CollectionViewDelegate: class { func sizeReady(_ size: CGSize) } class CollectionViewController: UICollectionViewController { private let itemSpacing: CGFloat = 16 weak var myDelegate: CollectionViewDelegate? var items = [Item]() { didSet { collectionView.reloadData() } } private var colors = [UIColor]() override func viewDidLoad() { super.viewDidLoad() prepareColors() collectionView.contentInset = UIEdgeInsets(top: 0, left: itemSpacing, bottom: 0, right: itemSpacing) } } private extension CollectionViewController { func prepareColors() { let codes: [UInt32] = [0x16702e, 0x005a51, 0x996c00, 0x5c0a6b, 0x006d90, 0x974e06, 0x99272e, 0x89221f, 0x00345d] for code in codes { let color = ColorUtils.UIColorFromHex(rgbValue: code) colors.append(color) } } } //MARK: DATA SOURCE extension CollectionViewController { // MARK: UICollectionViewDataSource override func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return items.count } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! CollectionViewCell let index = indexPath.row let item = items[index] let colorMaxIndex = colors.count - 1 let itemColorIndex = index % colorMaxIndex let labelBgColor = colors[itemColorIndex] cell.configure(item: item, labelBgColor: labelBgColor) return cell } } //MARK: FLOW LAYOUT DELEGATE extension CollectionViewController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { guard !items.isEmpty else { return CGSize.zero} let item = items[indexPath.item] let fontSize: CGFloat = 14 let stringWidth = item.keyword?.widthOfString(usingFont: UIFont.systemFont(ofSize: fontSize)) ?? 0 let itemMinWidth: CGFloat = 112 //Add 100 to stringWidth for the word line break space, won't work in all cases //But it's the only way I can think of in the given time, 32 for margin let itemWidth: CGFloat = max(itemMinWidth, (stringWidth + 100 + 32) / 2) let imageMaxHeight: CGFloat = 96 let imageHeight = min(itemWidth, imageMaxHeight) let labelPadding: CGFloat = 8 let labelHeight = labelPadding * 6 + fontSize * 2 let itemHeight = imageHeight + labelHeight let cellSize = CGSize(width: itemWidth, height: itemHeight) myDelegate?.sizeReady(cellSize) return cellSize } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return itemSpacing } }
// // ExerciseCollectionViewCell.swift // YourPersonTrainer // // Created by Pavel Procenko on 20/08/2019. // Copyright © 2019 Pavel Procenko. All rights reserved. // import UIKit class ExerciseCollectionViewCell: UICollectionViewCell { @IBOutlet weak var pictureImage: UIImageView! @IBOutlet weak var nameLabel: UILabel! var exercise: Exercise? { didSet { nameLabel.text = exercise?.name if let imageName = exercise?.picture { pictureImage.image = UIImage(named: imageName) } else { pictureImage.image = nil } } } }
// // MainPresenter.swift // DesafioHurb // // Created by Guilherme Siepmann on 27/08/19. // Copyright © 2019 Guilherme Siepmann. All rights reserved. // import Foundation class MainPresenter { weak var delegate: MainViewProtocol? private let maxNumberOfStars = 5 private var numberOfSections = 0 private var groupedHotels: Dictionary<Int?, [Hotel]>? { didSet { guard let keys = groupedHotels?.keys else { return } numberOfSections = keys.count } } init(delegate: MainViewProtocol) { self.delegate = delegate } func fetchHotels(from location: String) { self.delegate?.loadingState() let router = HotelsRouter.getHotelsFor(city: location, page: 1) let service = APIFactory.shared.hotelsService service.fetchHotels(router: router) { [weak self] (result: Result<HotelsModel>) in switch result { case .success(let value): if let hotels = value.hotels { //Group Hotels by stars self?.groupedHotels = Dictionary(grouping: hotels, by: { $0.stars }) self?.delegate?.didFetchWithSuccess() } else { self?.delegate?.didFetchWithError(error: NSError(domain: "Failed to parse data", code: -1, userInfo: nil)) } case .failure(let error): self?.delegate?.didFetchWithError(error: error) } } } func getHotelBy(indexPath: IndexPath) -> Hotel? { let currentSection = maxNumberOfStars - indexPath.section let currentHotelPosition = indexPath.row return groupedHotels?[currentSection]?[currentHotelPosition] } func getNumberOfRowsInSection(section: Int) -> Int { let currentSection = maxNumberOfStars - section guard let hotels = groupedHotels, let count = hotels[currentSection]?.count else { return 0 } return count } func getNumberOfSection() -> Int { return numberOfSections } }
// // GDGradient.swift // Todo // // Created by Buse ERKUŞ on 7.03.2019. // Copyright © 2019 Buse ERKUŞ. All rights reserved. // import UIKit class GDGradient: UIView { // var colors:[CGColor] = [ // UIColor.init(red: 100,green: 228,blue:255).cgColor, // UIColor.init(red: 58,green: 123,blue:213).cgColor // ] var hexColors: [CGColor] = [ UIColor.blueZero.cgColor, UIColor.blueOne.cgColor ] override init(frame: CGRect = .zero) { super.init(frame: frame) if frame == .zero{ translatesAutoresizingMaskIntoConstraints = false } if let layer = self.layer as? CAGradientLayer{ layer.colors = self.hexColors layer.locations = [0.0, 1.2] } } override class var layerClass: AnyClass{ return CAGradientLayer.self } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
// // ViewController.swift // Service Browser // // Created by Christopher Brind on 28/08/2017. // Copyright © 2017 Christopher Brind. All rights reserved. // import UIKit import CFNetwork class ViewController: UITableViewController { var browser: NetServiceBrowser! var services = [NetService]() var serviceDelegates = [NetService: NetServiceDelegate]() override func viewDidLoad() { super.viewDidLoad() refreshControl = UIRefreshControl() refreshControl?.addTarget(self, action: #selector(refresh), for: .valueChanged) browser = NetServiceBrowser() browser.delegate = self refresh() } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return services.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let service = services[indexPath.row] let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")! cell.textLabel?.text = service.name cell.detailTextLabel?.text = "\(service.hostName ?? ""):\(service.port)" return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let service = services[indexPath.row] var inputStream: InputStream? var outputStream: OutputStream? guard service.getInputStream(&inputStream, outputStream: &outputStream) else { print("getInputStream failed") return } guard let input = inputStream else { print("no input stream") return } guard let output = outputStream else { print("no output stream") return } input.open() output.open() let written = output.write([ 0, 0x54, 1 ], maxLength: 3) guard written > -1 else { print("output.write failed", written, output.streamError) return } var buffer:[UInt8] = Array<UInt8>(repeatElement(0, count: 3)) let read = input.read(&buffer, maxLength: 3) guard read > -1 else { print("input.read failed", read, input.streamError) return } print("response: ", buffer) } deinit { browser.stop() browser = nil } func refresh() { services = [NetService]() browser.searchForServices(ofType: "_spike._tcp", inDomain: "") } } extension ViewController: NetServiceBrowserDelegate { func netServiceBrowserWillSearch(_ browser: NetServiceBrowser) { print("netServiceBrowserWillSearch") } func netServiceBrowser(_ browser: NetServiceBrowser, didFindDomain domainString: String, moreComing: Bool) { print("netServiceBrowser:didFindDomain", domainString, "moreComing:", moreComing) } func netServiceBrowser(_ browser: NetServiceBrowser, didNotSearch errorDict: [String : NSNumber]) { refreshControl?.endRefreshing() print("netServiceBrowser:didNotSearch", errorDict) } func netServiceBrowser(_ browser: NetServiceBrowser, didFind service: NetService, moreComing: Bool) { print("netServiceBrowser:didFind", service, "moreComing:", moreComing) print("service.name", service.name) print("service.hostName", service.hostName ?? "<unknown host>") print("service.port", service.port) print("service.includesPeerToPeer", service.includesPeerToPeer) services.append(service) tableView.reloadData() if !moreComing { refreshControl?.endRefreshing() } } func netServiceBrowser(_ browser: NetServiceBrowser, didRemove service: NetService, moreComing: Bool) { print("netServiceBrowser:didRemove", service, "moreComing:", moreComing) if let index = services.index(of: service) { services.remove(at: index) } serviceDelegates[service] = nil tableView.reloadData() } func netServiceBrowserDidStopSearch(_ browser: NetServiceBrowser) { print("netServiceBrowserDidStopSearch") } func netServiceBrowser(_ browser: NetServiceBrowser, didRemoveDomain domainString: String, moreComing: Bool) { print("netServiceBrowser:didRemoveDomain", domainString, "moreComing:", moreComing) } }
// // Refeicao.swift // FoodCad // // Created by Ney on 11/3/17. // Copyright © 2017 Giltecnologia. All rights reserved. // import Foundation class Refeicao : NSObject, NSCoding{ let nome:String let felicidade:Int var itens = Array<Item>() init(nome:String, felicidade:Int, itens: Array<Item> = []) { self.nome = nome self.felicidade = felicidade self.itens = itens } init(nome:String, felicidade:Int) { self.nome = nome self.felicidade = felicidade } func todasCalorias() -> Double { var total = 0.0 for item in itens { total += item.calorias } return total } func detalhes() -> String { var msg = "Itens: " for item in itens { msg += "\n \(item.nome) = \(item.calorias.description)" } return msg } func encode(with aCoder: NSCoder) { aCoder.encode(nome, forKey : "nome") aCoder.encode(felicidade, forKey: "felicidade") aCoder.encode(itens, forKey: "itens") } required init?(coder aDecoder: NSCoder) { nome = aDecoder.decodeObject(forKey: "nome") as! String felicidade = aDecoder.decodeInteger(forKey: "felicidade") itens = aDecoder.decodeObject(forKey: "itens") as! Array } }
import Foundation import UIKit import ImageIO extension UIView { func blurredEffect() { let blurEffect = UIBlurEffect(style: .light) let blurEffectView = UIVisualEffectView(effect: blurEffect) blurEffectView.frame = self.bounds addSubview(blurEffectView) } func dismissBlurredEffect() { for subview in self.subviews { if subview is UIVisualEffectView{ subview.removeFromSuperview() } } } } extension UIViewController { @objc func dismissOnTap() { dismiss(animated: true, completion: nil) view.dismissBlurredEffect() } }
// // HospitalProvideFactory.swift // szenzormodalitasok // // Created by Tóth Zoltán on 2021. 05. 07.. // Copyright © 2021. Tóth Zoltán. All rights reserved. // // Imports import Foundation // Hospital providing protocol protocol HospitalProviding { func getHospitals(onCompletion: @escaping ([HospitalModel]) -> Void) } // Hospital provider class class HospitalProviderFactory { // Variables static var mockedIstance: HospitalProviding? // Functions class func getInstance() -> HospitalProviding { guard mockedIstance == nil else { return mockedIstance! } return HospitalProvider() } } // Hospital provider class private class HospitalProvider : HospitalProviding { // Get hospitals here func getHospitals(onCompletion: @escaping ([HospitalModel]) -> Void) { DispatchQueue.global(qos: .default).async { onCompletion([ // Here is the hospital list that you want to display in hospital page HospitalModel(name: "Dr. Kenessey Albert Kórház-Rendelőintézet", hospitalSCountry: "Nógrád", latitude: 48.080474, longitude: 19.311020, distanceFromUser: 0.0), HospitalModel(name: "Szent Lázár Megyei Kórház", hospitalSCountry: "Nógrád", latitude: 48.117368, longitude: 19.814767, distanceFromUser: 0.0), HospitalModel(name: "Szent Margit Kórház", hospitalSCountry: "Budapest - III. Kerület", latitude: 47.540093, longitude: 19.030192, distanceFromUser: 0.0), HospitalModel(name: "Szent János Kórház", hospitalSCountry: "Budapest - XII. Kerület", latitude: 47.508667, longitude: 19.005729, distanceFromUser: 0.0), HospitalModel(name: "Magyar Honvédség Egészségügyi Központ Honvédkórház", hospitalSCountry: "Budapest - XIII. Kerület", latitude: 47.531372, longitude: 19.074702, distanceFromUser: 0.0), HospitalModel(name: "Dél-pesti Centrumkórház - Országos Hematológiai és Infektológiai Intézet - Szent István telephely", hospitalSCountry: "Budapest - IX. Kerület", latitude: 47.477722, longitude: 19.089355, distanceFromUser: 0.0), HospitalModel(name: "SZTE Szent-Györgyi Albert Klinikai Központ Gyermekgyógyászati Klinika és Gyermek-Egészségügyi Központ", hospitalSCountry: "Csongrád", latitude: 46.245357, longitude: 20.150484, distanceFromUser: 0.0), HospitalModel(name: "Pécsi Honvéd Kórház", hospitalSCountry: "Baranya", latitude: 46.052106, longitude: 18.229541, distanceFromUser: 0.0), HospitalModel(name: "Petz Aladár Megyei Oktató Kórház", hospitalSCountry: "Győr-Moson-Sopron", latitude: 47.677856, longitude: 17.678832, distanceFromUser: 0.0), HospitalModel(name: "Borsod-Abaúj-Zemplén Megyei Központi Kórház és Egyetemi Oktatókórház Semmelweis Tagkórház", hospitalSCountry: "Szabolcs-Szatmár-Bereg", latitude: 48.097646, longitude: 20.815311, distanceFromUser: 0.0) ]) } } }
// // SwiftViewController.swift // CoreDataEnvirSample // // Created by NicholasXu on 2020/9/14. // Copyright © 2020 Nicholas.Xu. All rights reserved. // import UIKit import CoreDataEnvir @objc(SwiftViewController) class SwiftViewController: UIViewController { @objc override func viewDidLoad() { super.viewDidLoad() CoreDataEnvir.mainInstance() print("Team.totalCount:", Team.totalCount()) print("Member.totalCount:", Member.totalCount()) } }
//: [Previous](@previous) import Foundation class AClass { func instanceMethod(param1: String, param2: String) { // function body } class func classMethod(param1: String, param2: String) { // function body } } let aClassInstance = AClass() aClassInstance.instanceMethod(param1: "first string", param2: "second string") AClass.classMethod(param1: "first string", param2: "second string") //funcName(firstParam: "some String", secondParam: "some String") //func functionName(firstParameter: ParameterType, secondParameter: // ParameterType) { // // function body //} // //// To call: //functionName(firstParameter: paramName, secondParameter: secondParamName) func functionName(externalParamName localParamName: String) { } functionName(externalParamName: "") // Parameters with default values func functionName(param: Int = 3) { print("\(param) is provided.") } functionName(param: 5) // prints “5 is provided.” functionName() // prints “3 is provided” // Parameters as Tuples - deprecated let numbers = [3, 5, 9, 10] func convert(numbers: [Int], multiplier: Int) -> [String] { let convertedValues = numbers.enumerated().map { (index, element) in return "\(index): \(element * multiplier)" } return convertedValues } let resultOfConversion = convert(numbers: numbers, multiplier: 3) // Pre Swift 3.0 let parameters = (numbers: numbers, multiplier: 3) //convert(parameters) // Variadic functions func greet(names: String...) { for name in names { print("Greetings, \(name)") } } // To call this function greet(names: "Steve", "Craig") // prints twice greet(names: "Steve", "Craig", "Johny") // prints three times //: [Next](@next)
import Foundation public struct API { static var data: Data! static func setup() { data = FirebaseData.sharedInstance } }
import MetalPerformanceShaders public class LanczosScale: BasicMPSFilter { private var scaleTransform = MPSScaleTransform(scaleX: 1, scaleY: 1, translateX: 0, translateY: 0) @objc public var scaleX: Float { get { return Float(scaleTransform.scaleX) } set { scaleTransform.scaleX = Double(newValue) } } @objc public var scaleY: Float { get { return Float(scaleTransform.scaleY) } set { scaleTransform.scaleY = Double(newValue) } } @objc public var translateX: Float { get { return Float(scaleTransform.translateX) } set { scaleTransform.translateX = Double(newValue) } } @objc public var translateY: Float { get { return Float(scaleTransform.translateY) } set { scaleTransform.translateY = Double(newValue) } } public init(context: MIContext = .default) { super.init(context: context) if useMetalPerformanceShaders { internalImageKernel = MPSImageLanczosScale(device: renderTarget.context.device) } else { fatalError("Lanzos Scale isno't available on pre-MPS OS versions") } } public override func renderWithShader(commandBuffer: MTLCommandBuffer, sourceTexture: MTLTexture, destinationTexture: MTLTexture) { if useMetalPerformanceShaders { withUnsafePointer(to: &scaleTransform) { scale in (internalImageKernel as? MPSImageLanczosScale)?.scaleTransform = scale internalImageKernel?.encode(commandBuffer: commandBuffer, sourceTexture: sourceTexture, destinationTexture: destinationTexture) } } } }
// // Product.swift // KRPApplication // // Created by Omar Khaled on 11/03/2019. // Copyright © 2019 garana. All rights reserved. // import Foundation class Product : Codable { var name:String? var description:String? var id:Int? // let productType:ProductType // init(id:Int?,name: String?, description: String?) { self.id = id self.name = name self.description = description // self.productType = productType } } enum ProductType : Int{ case readymix = 1 case blocks = 2 }
// // main.swift // SimpleToolbarWire // // Created by George Villasboas on 7/18/14. // Copyright (c) 2014 CocoaHeads Brasil. All rights reserved. // import Cocoa NSApplicationMain(C_ARGC, C_ARGV)
// // Breed.swift // SwiftUICombineCollection // // import Foundation typealias BreedType = String struct Breed: Hashable, Equatable, Decodable { let name: String let subBreeds: [Breed] } extension Breed: Identifiable { var id: Self { self } } extension Breed { static var anyBreed: Breed { let anyID = UUID().uuidString return Breed(name: "test\(anyID)", subBreeds: []) } }
// swiftlint:disable all // Generated using SwiftGen — https://github.com/SwiftGen/SwiftGen import Foundation // swiftlint:disable superfluous_disable_command file_length implicit_return // MARK: - Strings // swiftlint:disable explicit_type_interface function_parameter_count identifier_name line_length // swiftlint:disable nesting type_body_length type_name vertical_whitespace_opening_braces internal enum L10n { /// キャンセル internal static let addingAlertActionCancel = L10n.tr("Localizable", "adding_alert_action_cancel") /// 保存 internal static let addingAlertActionSave = L10n.tr("Localizable", "adding_alert_action_save") /// %d件 internal static func albumListCollectionViewCellCount(_ p1: Int) -> String { return L10n.tr("Localizable", "album_list_collection_view_cell_count", p1) } /// コピー internal static let clipInformationViewContextMenuCopy = L10n.tr("Localizable", "clip_information_view_context_menu_copy") /// 開く internal static let clipInformationViewContextMenuOpen = L10n.tr("Localizable", "clip_information_view_context_menu_open") /// 画像のURL internal static let clipInformationViewImageUrlTitle = L10n.tr("Localizable", "clip_information_view_image_url_title") /// 編集 internal static let clipInformationViewLabelClipEditUrl = L10n.tr("Localizable", "clip_information_view_label_clip_edit_url") /// 隠す internal static let clipInformationViewLabelClipHide = L10n.tr("Localizable", "clip_information_view_label_clip_hide") /// なし internal static let clipInformationViewLabelClipItemNoUrl = L10n.tr("Localizable", "clip_information_view_label_clip_item_no_url") /// 登録日 internal static let clipInformationViewLabelClipItemRegisteredDate = L10n.tr("Localizable", "clip_information_view_label_clip_item_registered_date") /// サイズ internal static let clipInformationViewLabelClipItemSize = L10n.tr("Localizable", "clip_information_view_label_clip_item_size") /// 更新日 internal static let clipInformationViewLabelClipItemUpdatedDate = L10n.tr("Localizable", "clip_information_view_label_clip_item_updated_date") /// 画像のURL internal static let clipInformationViewLabelClipItemUrl = L10n.tr("Localizable", "clip_information_view_label_clip_item_url") /// 登録日 internal static let clipInformationViewLabelClipRegisteredDate = L10n.tr("Localizable", "clip_information_view_label_clip_registered_date") /// 更新日 internal static let clipInformationViewLabelClipUpdatedDate = L10n.tr("Localizable", "clip_information_view_label_clip_updated_date") /// サイトのURL internal static let clipInformationViewLabelClipUrl = L10n.tr("Localizable", "clip_information_view_label_clip_url") /// タグを追加する internal static let clipInformationViewLabelTagAddition = L10n.tr("Localizable", "clip_information_view_label_tag_addition") /// このクリップの情報 internal static let clipInformationViewSectionLabelClip = L10n.tr("Localizable", "clip_information_view_section_label_clip") /// この画像の情報 internal static let clipInformationViewSectionLabelClipItem = L10n.tr("Localizable", "clip_information_view_section_label_clip_item") /// タグ internal static let clipInformationViewSectionLabelTag = L10n.tr("Localizable", "clip_information_view_section_label_tag") /// サイトのURL internal static let clipInformationViewSiteUrlTitle = L10n.tr("Localizable", "clip_information_view_site_url_title") /// サイトURL internal static let clipItemEditContentViewSiteTitle = L10n.tr("Localizable", "clip_item_edit_content_view_site_title") /// 編集 internal static let clipItemEditContentViewSiteUrlEditTitle = L10n.tr("Localizable", "clip_item_edit_content_view_site_url_edit_title") /// なし internal static let clipItemEditContentViewSiteUrlEmpty = L10n.tr("Localizable", "clip_item_edit_content_view_site_url_empty") /// サイズ internal static let clipItemEditContentViewSizeTitle = L10n.tr("Localizable", "clip_item_edit_content_view_size_title") /// 未分類のクリップを閲覧する internal static let uncategorizedCellTitle = L10n.tr("Localizable", "uncategorized_cell_title") } // swiftlint:enable explicit_type_interface function_parameter_count identifier_name line_length // swiftlint:enable nesting type_body_length type_name vertical_whitespace_opening_braces // MARK: - Implementation Details extension L10n { private static func tr(_ table: String, _ key: String, _ args: CVarArg...) -> String { let format = BundleToken.bundle.localizedString(forKey: key, value: nil, table: table) return String(format: format, locale: Locale.current, arguments: args) } } // swiftlint:disable convenience_type private final class BundleToken { static let bundle: Bundle = { #if SWIFT_PACKAGE return Bundle.module #else return Bundle(for: BundleToken.self) #endif }() } // swiftlint:enable convenience_type
// // UICollectionDataSource.swift // CMoney // // Created by 黃仕杰 on 2021/7/24. // import Foundation import UIKit class UICollectionDataSource<CELL:UICollectionViewCell,T>:NSObject,UICollectionViewDataSource { private var cellIdentifier : String! private var items : [T]! var configureCell : (CELL, T) -> () = {_,_ in } private var selectIndex: Int = -1 init(cellIdentifier : String, items : [T], configureCell : @escaping (CELL, T) -> ()) { self.cellIdentifier = cellIdentifier self.items = items self.configureCell = configureCell } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return items.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! CELL let item = self.items[indexPath.row] self.configureCell(cell, item) return cell } func getObject(index: Int) -> T { return items[index] } func setSelectIndex(index: Int) { self.selectIndex = index } func getSelectObject() -> T { return items[selectIndex] } }
// // FoodListViewController.swift // sketch_001 // // Created by 이채운 on 11/02/2019. // Copyright © 2019 iOS App class. All rights reserved. // import UIKit class FoodListViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { var ingredients: [Ingredient]? var possibleFoodList: [Food]? var ingreStr: IngreStr? var delegate: ReloadRecipes? @IBOutlet weak var collectionView: UICollectionView! func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return ingredients!.count } // func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { // let cell = collectionView.cellForItem(at: indexPath)?.contentView as! IngredientsListCollectionViewCell // // if cell.ingredientName.text!.count > 3 { // return CGSize(width: 160, height: 40) // } else { // return CGSize(width: 80, height: 40) // } // } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { // let cell = collectionView.cellForItem(at: indexPath) as? IngredientsListCollectionViewCell // // if cell?.ingredientName.text?.count == 4 { // return CGSize(width: 150, height: 54) // } if ingredients![indexPath.row].name.count == 4 { return CGSize(width: 118, height: 54) }else if ingredients![indexPath.row].name.count == 3 { return CGSize(width: 105, height: 54) }else if ingredients![indexPath.row].name.count == 2 { return CGSize(width: 90, height: 54) }else{ return CGSize(width: 80, height: 54) } } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath) as! IngredientsListCollectionViewCell let ingredient = ingredients![indexPath.row] cell.ingredientImage.image = UIImage(named: ingredient.icon) cell.ingredientName.text = ingredient.name cell.ingredientButton.clipsToBounds = true cell.ingredientButton.layer.cornerRadius = 20.0 / 1.0 cell.ingredientButton.layer.borderWidth = 0.2 cell.ingredientButton.layer.borderColor = UIColor.lightGray.cgColor cell.ingreStr = ingreStr cell.delegate = delegate if let ingreStr = cell.ingreStr { if ingreStr.ingredientsList!.contains(ingredient.name){ cell.ingredientButton.isSelected = false cell.ingredientName.textColor = UIColor.black if let ingreImage = cell.translation!.ingreDictionary[ingredient.name]{ cell.ingredientImage.image = UIImage(named: ingreImage) } }else{ cell.ingredientButton.isSelected = true cell.ingredientName.textColor = UIColor.lightGray if let ingreImage = cell.translation!.ingreDictionary[ingredient.name]{ cell.ingredientImage.image = UIImage(named: ingreImage + "_gray") } } } if cell.ingredientName.text!.count == 4 { cell.ingredientButton.frame.size = CGSize(width: 97, height: 43) } else if cell.ingredientName.text!.count == 3 { cell.ingredientButton.frame.size = CGSize(width: 92, height: 43) }else if cell.ingredientName.text!.count == 2 { cell.ingredientButton.frame.size = CGSize(width: 79, height: 43) }else{ cell.ingredientButton.frame.size = CGSize(width: 67, height: 43) } // cell.contentView.layer.cornerRadius = 6.0 // cell.contentView.layer.borderWidth = 1.0 // cell.contentView.layer.borderColor = UIColor.clear.cgColor // cell.contentView.layer.masksToBounds = true // cell.layer.shadowColor = UIColor.lightGray.cgColor // cell.layer.shadowOffset = CGSize(width:0,height: 2.0) // cell.layer.shadowRadius = 2.0 // cell.layer.shadowOpacity = 1.0 // cell.layer.masksToBounds = false; // cell.layer.shadowPath = UIBezierPath(roundedRect:cell.bounds, cornerRadius:cell.contentView.layer.cornerRadius).cgPath return cell } override func viewDidLoad() { super.viewDidLoad() collectionView.dataSource = self collectionView.delegate = self // let myLayout = UICollectionViewFlowLayout() // myLayout.scrollDirection = .horizontal // myLayout.itemSize.width = CGFloat(exactly: 100.0)! // collectionView.setCollectionViewLayout(myLayout, animated: true) ingreStr = IngreStr() ingreStr?.ingredientsList = [] if let tmpIngredients = ingredients { for ingredient in tmpIngredients { ingreStr?.ingredientsList?.append(ingredient.name) } } // for ingredient in ingredients! { // ingreStr?.ingredientsList?.append(ingredient.name) // } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if (segue.identifier == "foodListEmbeddedSegue") { let childViewController = segue.destination as! TableViewController childViewController.possibleFoodList = possibleFoodList childViewController.vc = self } } } class IngredientsListCollectionViewCell: UICollectionViewCell { var possibleFoodList: [Food]? var ingreStr: IngreStr? var delegate: ReloadRecipes? var translation: Translation? @IBOutlet weak var ingredientImage: UIImageView! @IBOutlet weak var ingredientName: UILabel! @IBOutlet weak var ingredientButton: UIButton! override func awakeFromNib() { translation = Translation() // ingredientButton.layer.masksToBounds = true // ingredientButton.layer.cornerRadius = 10 // ingredientButton.clipsToBounds = true // // someView.layer.cornerRadius = 0.05 * showFoodButton.bounds.size.width // someView.alignmentRect() } @IBAction func selectedIngredient(_ sender: Any) { if ingredientButton.isSelected { print("append : \(ingredientName.text!)") ingredientButton.isSelected = !ingredientButton.isSelected ingreStr?.ingredientsList?.append(ingredientName.text!) ingredientName.textColor = UIColor.black if let ingreImage = translation!.ingreDictionary[ingredientName.text!]{ ingredientImage.image = UIImage(named: ingreImage) } } else { print("delete : \(ingredientName.text!)") ingredientButton.isSelected = !ingredientButton.isSelected ingreStr?.ingredientsList = ingreStr?.ingredientsList?.filter { $0 != ingredientName.text! } ingredientName.textColor = UIColor.lightGray if let ingreImage = translation!.ingreDictionary[ingredientName.text!]{ ingredientImage.image = UIImage(named: ingreImage + "_gray") } } delegate?.reloadRecipes(ingreStrArr: ingreStr!.ingredientsList!) // print(ingreStr?.ingredientsList!) } } class IngreStr { var ingredientsList: [String]? } protocol ReloadRecipes { func reloadRecipes(ingreStrArr: [String]) }
// // FilterScreenInteractor.swift // SuperHeroes // // Created by Òscar Muntal on 24/01/2018. //Copyright © 2018 Muntalapps. All rights reserved. // import Foundation import Viperit class FilterScreenInteractor: Interactor { func getFilterData(path: ApiManager.kAPI_ENDPOINT, successBlock: @escaping RequestSuccessBlock, errorBlock: @escaping RequestErrorBlock) { ApiManager.sharedInstance.get(path: path, path2: "", successBlock: { response in if let response = response { successBlock(response) } else { errorBlock(APIError()) } }) { error in errorBlock(error) } } func getHeroesFiltered(path: ApiManager.kAPI_ENDPOINT, path2: String, successBlock: @escaping RequestSuccessBlock, errorBlock: @escaping RequestErrorBlock) { ApiManager.sharedInstance.get(path: path, path2: path2, successBlock: { response in if let response = response { successBlock(response) } else { errorBlock(APIError()) } }) { error in errorBlock(error) } } } // MARK: - VIPER COMPONENTS API (Auto-generated code) private extension FilterScreenInteractor { var presenter: FilterScreenPresenter { return _presenter as! FilterScreenPresenter } }
// // AttributeForFaceting.swift // // // Created by Vladislav Fitc on 11.03.2020. // import Foundation public enum AttributeForFaceting: Equatable, Codable { case `default`(Attribute) case filterOnly(Attribute) case searchable(Attribute) } extension AttributeForFaceting: ExpressibleByStringInterpolation { public init(stringLiteral value: String) { self = .default(.init(rawValue: value)) } } extension AttributeForFaceting: RawRepresentable { private enum Prefix: String { case filterOnly case searchable } public var rawValue: String { switch self { case .default(let attribute): return attribute.rawValue case .filterOnly(let attribute): return PrefixedString(prefix: Prefix.filterOnly.rawValue, value: attribute.rawValue).description case .searchable(let attribute): return PrefixedString(prefix: Prefix.searchable.rawValue, value: attribute.rawValue).description } } public init(rawValue: String) { if let prefixedString = PrefixedString(rawValue: rawValue), let prefix = Prefix(rawValue: prefixedString.prefix) { switch prefix { case .filterOnly: self = .filterOnly(.init(rawValue: prefixedString.value)) case .searchable: self = .searchable(.init(rawValue: prefixedString.value)) } } else { self = .default(.init(rawValue: rawValue)) } } }
import Foundation enum SuggestionError:Error{ case noDataAvailable case canNotProcessData } struct SuggestionRequest { let resourceURL:URL init(){ let resourceString = "http://104.248.244.41:3000/odds/getAllOdds" guard let resourceURL = URL(string: resourceString) else {fatalError()} self.resourceURL = resourceURL } }
// // SentMemesTableViewController.swift // MemeMe2 // // Created by Michael Nienaber on 21/12/2015. // Copyright © 2015 Michael Nienaber. All rights reserved. // import Foundation import UIKit class SentMemesTableViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var tableView: UITableView! var memes: [Meme] { return (UIApplication.sharedApplication().delegate as! AppDelegate).memes } override func viewWillAppear(animated: Bool) { super.viewWillAppear(true) self.tableView.reloadData() } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return memes.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("TableCell", forIndexPath: indexPath) let info = self.memes[indexPath.row] cell.textLabel!.text = (info.topString + " " + info.bottomString) cell.imageView!.image = info.memedImage return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let detailController = self.storyboard!.instantiateViewControllerWithIdentifier("DetailImageViewController") as! DetailImageViewController detailController.image = self.memes[indexPath.row] self.navigationController!.pushViewController(detailController, animated: true) } func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate appDelegate.memes.removeAtIndex(indexPath.row) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Middle) } } }
// // FavoritesModel.swift // NYTBestsellers // // Created by Jeffrey Almonte on 1/28/19. // Copyright © 2019 Pursuit. All rights reserved. // import Foundation struct FavoritesBook: Codable { let imageData: Data? let weeksOnBestSellerList: String let bookDescription: String let createdAt: String }
// // Dictionary.swift // APIManager // // Created by Daniel Vdovenko on 09.05.2018. // Copyright © 2018 Daniel Vdovenko. All rights reserved. // extension Dictionary { subscript(i:Int) -> (key:Key,value:Value) { get { return self[i] } } }
// // LoadingViewController.swift // LoadingUI // // Created by Kobe McKee on 6/26/19. // Copyright © 2019 Kobe McKee. All rights reserved. // import UIKit open class LoadingViewController: UIViewController { open override func viewDidLoad() { super.viewDidLoad() } private var animationView = IndeterminateLoadingView(frame: CGRect(x: 0.0, y: 0.0, width: 300, height: 300)) open func animate() { animationView.center = view.center view.addSubview(animationView) animationView.startAnimating() // sleep(5) // animationView.stopAnimating() } open func stopAnimation() { animationView.stopAnimating() } }
// // CTimerViewController.swift // RxSwift-Study // // Created by apple on 2019/1/17. // Copyright © 2019 incich. All rights reserved. // import UIKit import RxSwift import RxCocoa class CTimerViewController: BaseViewController { @IBOutlet weak var startBtn: UIButton! @IBOutlet weak var datePicker: UIDatePicker! let bag = DisposeBag() var leftTime = BehaviorRelay.init(value: TimeInterval(180)) var countDownStop = BehaviorRelay.init(value: true) override func viewDidLoad() { super.viewDidLoad() _ = self.datePicker.rx.countDownDuration <-> self.leftTime //绑定button标题 Observable.combineLatest(leftTime, countDownStop) { leftTimeValue, countDownStopValue in if countDownStopValue { return "开始" } else { return "剩余: \(Int(leftTimeValue)) 秒" } }.bind(to: startBtn.rx.title()).disposed(by: bag) //绑定button和datePicker的可用状态 let countDown = countDownStop.asDriver() countDown.drive(datePicker.rx.isEnabled).disposed(by: bag) countDown.drive(startBtn.rx.isEnabled).disposed(by: bag) startBtn.rx.tap.bind { _ in self.startClicked() }.disposed(by: bag) } func startClicked() { self.countDownStop.accept(false) Observable<Int>.interval(1, scheduler: MainScheduler.instance).takeUntil(countDownStop.filter{$0 == true}).subscribe { (event) in self.leftTime.accept(self.leftTime.value - 60) if self.leftTime.value <= 0 { self.countDownStop.accept(true) self.leftTime.accept(180) } }.disposed(by: bag) } }
// // FixBackViewController.swift // NavigationGuide // // Created by deer on 2018/7/19. // Copyright © 2018年 deer. All rights reserved. // import UIKit class FixBackViewController: DXBaseViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. clearLeftItem() addFixBackBtn() } func addFixBackBtn() { let backbtn = UIButton() backbtn.addTarget(self, action: #selector(gotBack), for: .touchUpInside) backbtn.frame = CGRect(x: 0, y: 0, width: 50, height: 50) backbtn.backgroundColor = UIColor.clear // 返回箭头的位置 let imageNormal = UIImage.init(named: "backIcon") let imageHighlight = UIImage(named: "backIcon") backbtn.setImage(imageNormal, for: .normal) backbtn.setImage(imageHighlight, for: .highlighted) backbtn.contentHorizontalAlignment = .left let btn = UIBarButtonItem(customView: backbtn) let fixSpace = UIBarButtonItem.init(barButtonSystemItem: .fixedSpace, target: nil, action: nil) fixSpace.width = -15 self.navigationItem.leftBarButtonItems = [fixSpace, btn] } @objc func gotBack() { navigationController?.popViewController(animated: true) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ }
// // LoadGifsFromTable.swift // quickpicker // // Created by Yaniv Silberman on 2016-02-06. // Copyright © 2016 Yaniv Silberman. All rights reserved. // /* import Foundation import UIKit import FLAnimatedImage import AWSCore import AWSDynamoDB import AWSS3 import AWSSQS import AWSSNS import AWSCognito import Bolts var grabbedGif:AWSGif? func loadGifFromTable() { let mapper = AWSDynamoDBObjectMapper.defaultDynamoDBObjectMapper() mapper.load(AWSGif.self, hashKey: "12345678910"/*grabbedGif?.Id*/, rangeKey: "action"/*grabbedGif?.gifClass*/).continueWithExecutor(AWSExecutor.mainThreadExecutor(), withBlock: { (task:AWSTask!) -> AnyObject! in if (task.error == nil) { if (task.result != nil) { let grabbedGif = task.result as! AWSGif print(grabbedGif.Id) print(grabbedGif.gifClass) if (grabbedGif.gifTags != nil){ print(grabbedGif.gifGroup) } if (grabbedGif.gifTags != nil) { print(grabbedGif.gifTags) } print(grabbedGif.gifFrames?.stringValue) print(grabbedGif.gifSize?.stringValue) print(grabbedGif.gifHeight?.stringValue) print(grabbedGif.gifWidth?.stringValue) } } else { print("Error: \(task.error)") /*let alertController = UIAlertController(title: "Failed to get item from table.", message: task.error?.description, preferredStyle: UIAlertControllerStyle.Alert) let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Cancel, handler: { (action:UIAlertAction) -> Void in }) alertController.addAction(okAction) self.presentViewController(alertController, animated: true, completion: nil)*/ } return nil }) } */
import UIKit import AVFoundation class ViewController: UIViewController { var timer = Timer() var player: AVAudioPlayer! var totalTime = 0 var secondsPassed = 0 @IBOutlet weak var topView: UILabel! @IBOutlet weak var progressView: UIProgressView! @IBAction func hardnessSelected(_ sender: UIButton) { timer.invalidate() progressView.progress = 0.0 secondsPassed = 0 topView.text = sender.currentTitle var hardness = sender.currentTitle switch hardness { case "Soft": totalTime = 5 case "Medium": totalTime = 420 case "Hard": totalTime = 720 default: print("None") } timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true) } @objc func timerAction(){ if secondsPassed < totalTime { secondsPassed += 1 progressView.progress = Float(secondsPassed) / Float(totalTime) } else{ timer.invalidate() topView.text = "DONE!" playSound() } } func playSound() { let url = Bundle.main.url(forResource: "success", withExtension: "mp3") player = try! AVAudioPlayer(contentsOf: url!) player.play() } }
// // PortfolioVM.swift // Stocks // // Created by Ankita Gupta on 29/11/20. // import Foundation import SwiftyJSON import Alamofire class PortfolioVM: ObservableObject { @Published var BookMarkState: [String] @Published var BookMarks: [String: String] @Published var PurchasesState: [String] @Published var Purchases: [String: [String: Any]] @Published var NetWorth: Float @Published var Balance: Float @Published var PortfolioData: [String: portfolio] @Published var autoComplete: [String: String] @Published var isLoading: Bool init(){ self.BookMarkState = DefaultsStorage.getBookMarkStateArray() self.BookMarks = DefaultsStorage.getBookMarks() self.PurchasesState = DefaultsStorage.getPurchasesStateArray() self.Purchases = DefaultsStorage.getPurchases() self.Balance = DefaultsStorage.getBalance() self.isLoading=true self.PortfolioData = ["ticker" : portfolio(ticker: "ticker", last: 0.0, change: 0.0)] self.autoComplete=[:] self.NetWorth = 0.0 } func fetchPortfolio(){ self.BookMarkState = DefaultsStorage.getBookMarkStateArray() self.BookMarks = DefaultsStorage.getBookMarks() self.PurchasesState = DefaultsStorage.getPurchasesStateArray() self.Purchases = DefaultsStorage.getPurchases() self.Balance = DefaultsStorage.getBalance() let set = Set(self.BookMarkState) let tickers = set.union(self.PurchasesState) let tickerString = tickers.joined(separator: ",") let url: String = Constants.Host+"portfolio?tickers="+tickerString AF.request(url, encoding:JSONEncoding.default).validate().responseJSON { response in switch response.result{ case .success(let value): let json = JSON(value) var PortfoliosDict: [String: portfolio] = [:] for item in json.arrayValue { let portfolioObj = portfolio( ticker: item["ticker"].stringValue, last: item["last"].floatValue, change: item["change"].floatValue ) PortfoliosDict[item["ticker"].stringValue] = portfolioObj } self.PortfolioData=PortfoliosDict self.calculateNetWorth() self.isLoading=false debugPrint("Portfolio data fetched!") debugPrint(self.PortfolioData) case .failure(let error): print(error) } } } func calculateNetWorth(){ let Balance:Float = DefaultsStorage.getBalance() var Holdings:Float = 0.0 for stock in self.Purchases.keys { let stockData: portfolio = self.PortfolioData[stock] ?? portfolio(ticker: "", last: 0.0, change: 0.0) let currentPrice: Float = stockData.last let qty: Float = self.Purchases[stock]?["qty"] as! Float Holdings = Holdings + (currentPrice*qty) } self.NetWorth = Holdings+Balance } func fetchAutoComplete(keywork: String){ let url: String = Constants.Host+"autocomplete?tickers="+keywork AF.request(url, encoding:JSONEncoding.default).validate().responseJSON { response in switch response.result{ case .success(let value): let json = JSON(value) var autocompleteArray: [String: String] = [:] for item in json.arrayValue { autocompleteArray[item["ticker"].stringValue] = item["name"].stringValue } self.autoComplete = autocompleteArray debugPrint("Autocomplete data fetched!") debugPrint(self.autoComplete) case .failure(let error): print(error) } } } func reorder(type: String, source: IndexSet, destination: Int){ DefaultsStorage.reorder(category: type, source: source, destination: destination) if(type == "BOOKMARKS_ARRAY"){ self.BookMarkState = DefaultsStorage.getBookMarkStateArray() }else{ self.PurchasesState = DefaultsStorage.getPurchasesStateArray() } } func deleteBookMark(offset: IndexSet){ for eachIndex in offset { DefaultsStorage.deleteBookmark(from: eachIndex) } self.BookMarkState = DefaultsStorage.getBookMarkStateArray() self.BookMarks = DefaultsStorage.getBookMarks() } func buyStock(ticker: String, name: String, qty: Float, price: Float){ DefaultsStorage.buy(ticker: ticker, name: name, qty: qty, price: price) self.PurchasesState = DefaultsStorage.getPurchasesStateArray() self.Purchases = DefaultsStorage.getPurchases() self.Balance = DefaultsStorage.getBalance() self.calculateNetWorth() } func sellStock(ticker: String, qty: Float, price: Float){ DefaultsStorage.sell(ticker: ticker, qty: qty, price: price) self.PurchasesState = DefaultsStorage.getPurchasesStateArray() self.Purchases = DefaultsStorage.getPurchases() self.Balance = DefaultsStorage.getBalance() self.calculateNetWorth() } } struct portfolio{ var ticker: String var last: Float var change: Float }
// // GooglePlacesAPI.swift // GetGoingClass // // Created by shaunyan on 2019-01-21. // Copyright © 2019 SMU. All rights reserved. // import Foundation import CoreLocation class GooglePlacesAPI { class func requestPlaces(_ query: String, radius: Float, opennow: Bool?, completion: @escaping(_ status: Int, _ json: [String: Any]?) -> Void) { var urlComponents = URLComponents() urlComponents.scheme = Constants.scheme urlComponents.host = Constants.host urlComponents.path = Constants.textPlaceSearch urlComponents.queryItems = [ URLQueryItem(name: "query", value: query), URLQueryItem(name: "radius", value: "\(Int(radius))"), URLQueryItem(name: "key", value: Constants.apiKey) ] /* if users do not turn on "open now", we regard they want the whole result by default, while not in the staus of "close now". */ if opennow == true { urlComponents.queryItems?.append(URLQueryItem(name: "opennow", value: opennow?.description)) } if let url = urlComponents.url { NetworkingLayer.getRequest(with: url, timeoutInterval: 500) { (status, data) in if let responseData = data, let jsonResponse = try? JSONSerialization.jsonObject(with: responseData, options: .allowFragments) as? [String: Any] { completion(status, jsonResponse) } else { completion(status, nil) } } } } class func requestPlacesNearby(for coordinate: CLLocationCoordinate2D, radius: Float, _ query: String?,rankby: String,opennow: Bool?, completion: @escaping(_ status: Int, _ json: [String: Any]?) -> Void) { var urlComponents = URLComponents() urlComponents.scheme = Constants.scheme urlComponents.host = Constants.host urlComponents.path = Constants.nearbySearch urlComponents.queryItems = [ URLQueryItem(name: "location", value: "\(coordinate.latitude),\(coordinate.longitude)"), URLQueryItem(name: "key", value: Constants.apiKey), URLQueryItem(name: "rankby", value: rankby) ] // when rankby == "distance", radius can not be included if rankby == "prominence" { urlComponents.queryItems?.append(URLQueryItem(name: "radius", value: "\(Int(radius))")) } if let keyword = query { urlComponents.queryItems?.append(URLQueryItem(name: "keyword", value: keyword)) } /* if users do not turn on "open now", we regard they want the whole result by default, while not in the staus of "close now". */ if opennow == true { urlComponents.queryItems?.append(URLQueryItem(name: "opennow", value: opennow?.description)) } if let url = urlComponents.url { print(url) NetworkingLayer.getRequest(with: url, timeoutInterval: 500) { (status, data) in if let responseData = data, let jsonResponse = try? JSONSerialization.jsonObject(with: responseData, options: .allowFragments) as? [String: Any] { completion(status, jsonResponse) } else { completion(status, nil) } } } } class func requestPlaceDetail(_ placeid: String, completion: @escaping(_ status: Int, _ json: [String: Any]?) -> Void) { var urlComponents = URLComponents() urlComponents.scheme = Constants.scheme urlComponents.host = Constants.host urlComponents.path = Constants.placeDetail urlComponents.queryItems = [ URLQueryItem(name: "placeid", value: placeid), URLQueryItem(name: "key", value: Constants.apiKey) ] if let url = urlComponents.url { NetworkingLayer.getRequest(with: url, timeoutInterval: 500) { (status, data) in if let responseData = data, let jsonResponse = try? JSONSerialization.jsonObject(with: responseData, options: .allowFragments) as? [String: Any] { completion(status, jsonResponse) } else { completion(status, nil) } } } } }
// // BtResultCollection.swift // animalHealthLog // // Created by 細川聖矢 on 2020/04/04. // Copyright © 2020 Seiya. All rights reserved. // import SwiftUI struct CollectionContainer:View { @State var collectionName = "" @State var subCollectionName = "" var body:some View{ ZStack{ // GeometryReader{ geometry in RoundedRectangle(cornerRadius: 20,style:.continuous).fill(Color.white).frame(width:UIScreen.main.bounds.width*0.9,height:150,alignment: .center) VStack{ Text(self.collectionName).foregroundColor(Color .greyText).font(.largeTitle) Text(self.subCollectionName).foregroundColor(Color .greyText).font(.title) }//Vstack // }//Geometry }//Zstack } } struct BtResultCollection: View { // @ObservedObject var barHidden:BarHiddenView init(){ UINavigationBar.appearance().tintColor = UIColor.greyTitle UINavigationBar.appearance().titleTextAttributes = [NSAttributedString.Key.foregroundColor:UIColor.gGrey] UINavigationBar.appearance().backgroundColor = UIColor.greyBack } // @ObservedObject var barHidden = BarHidden() var body: some View { NavigationView{ ZStack{ Color.greyBack VStack{ // Text("結果を表示") ScrollView(.vertical,showsIndicators: false){ VStack{ // HStack{ Spacer() NavigationLink(destination: kidneyResultTab().environment(\.managedObjectContext, (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext)){ CollectionContainer(collectionName: "腎機能" , subCollectionName: "BUN,CRE" ) }//NavigationLinkの閉じ NavigationLink(destination: liverResultTab().environment(\.managedObjectContext, (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext)){ CollectionContainer(collectionName: "肝機能" , subCollectionName: "ALT(GPT),AST(GOT),ALP \n GGT,T-Bil,NH3") } // }//HStack // HStack{ NavigationLink(destination: proteinResultTab().environment(\.managedObjectContext, (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext)){ CollectionContainer(collectionName: "蛋白" , subCollectionName: "TP,ALB") } NavigationLink(destination: glucoseResultTab().environment(\.managedObjectContext, (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext)){ CollectionContainer(collectionName: "血糖" , subCollectionName: "GLU") } // }//HStack // HStack{ NavigationLink(destination: mineralResultTab().environment(\.managedObjectContext, (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext)){ CollectionContainer(collectionName: "電解質" , subCollectionName: "Na,K,Cl \n Ca,IP,Mg") } NavigationLink(destination: pancreaResultTab().environment(\.managedObjectContext, (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext)){ CollectionContainer(collectionName: "膵機能" , subCollectionName: "Amy,Lip") } // }//HStack // HStack{ NavigationLink(destination: lipidResultTab().environment(\.managedObjectContext, (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext)){ CollectionContainer(collectionName: "脂質" , subCollectionName: "TG,Tcho") } NavigationLink(destination: inflammationResultTab().environment(\.managedObjectContext, (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext)){ CollectionContainer(collectionName: "炎症" , subCollectionName: "CRP") } // }//HStack // HStack{ NavigationLink(destination: otherResultTab().environment(\.managedObjectContext, (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext)){ CollectionContainer(collectionName: "その他" , subCollectionName: "CPK") } // }//HStack }//VStackの閉じ }//ScrollViewの閉じ }//NavigationViewの閉じ .navigationBarTitle("血液検査一覧",displayMode: .inline) }//VStack }//ZStack }//bodyの閉じ }//Viewの閉じ struct BtResultCollection_Previews: PreviewProvider { static var previews: some View { BtResultCollection() } }
// // ViewController.swift // CoreDataBasics // // Created by Akhilesh Mishra on 15/03/21. // import UIKit import CoreData class ViewController: UIViewController { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var addButton: UIBarButtonItem! private var models: [ToDoListItem] = [] let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext override func viewDidLoad() { super.viewDidLoad() getAllItems() title = "CoreData To Do List" tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell") } @IBAction func addName(_ sender: UIBarButtonItem) { let alertController = UIAlertController(title: "New Item", message: "Enter new item", preferredStyle: .alert) let saveAction = UIAlertAction(title: "Submit", style: .default) { [unowned self] action in guard let textField = alertController.textFields?.first, let nameToSave = textField.text else { return } self.createItem(name: nameToSave) self.tableView.reloadData() } let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (action) in } alertController.addTextField { (textField) in } alertController.addAction(saveAction) alertController.addAction(cancelAction) present(alertController, animated: true, completion: nil) } //MARK: CoreData CRUD Operations func getAllItems() { do { models = try context.fetch(ToDoListItem.fetchRequest()) DispatchQueue.main.async { self.tableView.reloadData() } } catch let error as NSError { print("Could not fetch. \(error.localizedDescription)") } } func createItem(name: String) { let newItem = ToDoListItem(context: context) newItem.name = name newItem.createdAt = Date() do { try context.save() getAllItems() } catch let error as NSError { print("Could not create. \(error.localizedDescription)") } } func deleteItem(item: ToDoListItem) { context.delete(item) do { try context.save() getAllItems() } catch let error as NSError { print("Could not delete. \(error.localizedDescription)") } } func updateItem(item: ToDoListItem, newName: String) { item.name = newName do { try context.save() getAllItems() } catch let error as NSError { print("Could not create. \(error.localizedDescription)") } } } //MARK: TableView DataSource Methods extension ViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return models.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let model = models[indexPath.row] let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) cell.textLabel?.text = model.name return cell } } //MARK: TableView Delegate Methods extension ViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let item = self.models[indexPath.row] let sheet = UIAlertController(title: "Edit", message: nil, preferredStyle: .actionSheet) sheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) sheet.addAction(UIAlertAction(title: "Edit", style: .default, handler: { [weak self] _ in let alertController = UIAlertController(title: "Edit Item", message: "Edit your item", preferredStyle: .alert) let saveAction = UIAlertAction(title: "Save", style: .default) { _ in guard let textField = alertController.textFields?.first, let nameToSave = textField.text else { return } self?.updateItem(item: item, newName: nameToSave) } let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (action) in } alertController.addTextField(configurationHandler: nil) alertController.textFields?.first?.text = item.name alertController.addAction(saveAction) alertController.addAction(cancelAction) self?.present(alertController, animated: true, completion: nil) })) sheet.addAction(UIAlertAction(title: "Delete", style: .destructive, handler: { [weak self] _ in self?.deleteItem(item: item) })) present(sheet, animated: true, completion: nil) } }
// // PiViewController.swift // SwiftPi // // Created by Josselin Abel on 04/01/2021. // import UIKit class PiViewController: UIViewController { @IBOutlet weak var piView: PiView! var sliderValue = 0 @IBOutlet weak var sliderLabel: UILabel! @IBOutlet weak var piLabel: UILabel! @IBOutlet weak var slider: UISlider! @IBAction func sliderValueChanged(_ sender: UISlider) { sliderValue = Int(sender.value) piView.drawPoint(nbPoint: sliderValue) sliderLabel.text = "\(sliderValue)" piView.setNeedsDisplay() if piView.nbPointInCircle > 0 { let piValue = 4 * CGFloat(piView.nbPointInCircle)/CGFloat(piView.nbPointTotal) let piRounded = CGFloat(round(1000*piValue)/1000) piLabel.text = "\(piRounded)" } } }
// // PhotoLibraryCollectionViewCell.swift // PhotoFilter // // Created by Bilal Durnagöl on 5.03.2021. // import UIKit class PhotoLibraryCollectionViewCell: UICollectionViewCell { static let identifier = "PhotoLibraryCollectionViewCell" private let imageView: UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFill imageView.clipsToBounds = true imageView.layer.borderColor = UIColor(red: 153/255, green: 135/255, blue: 49/255, alpha: 1.0).cgColor return imageView }() override var isSelected: Bool { didSet { imageView.layer.borderWidth = isSelected ? 3 : 0 } } override init(frame: CGRect) { super.init(frame: frame) addSubview(imageView) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() imageView.frame = contentView.bounds } func configure(with image: UIImage?) { guard let image = image else {return} DispatchQueue.main.async {[weak self] in self?.imageView.image = image } } }
// // Constants.swift // Broeg // // Created by Rasmus Kjær Mortensen on 16/11/2020. // // this file is for all the constants which have hardcoded strings // (keeps us from making "typos" in larger projects) import Foundation struct Constants { struct Storyboard { // static = we can access this without having to create instances of the structure static let homeViewController = "home" static let UINavigationController = "navigation" static let welcomeViewController = "welcome" static let profileViewController = "profile" } }
import UIKit class ViewController: UIViewController { // 이미지가 부착될 뷰 var myView:UIView! @IBOutlet weak var t_row: UITextField! @IBOutlet weak var t_col: UITextField! @IBAction func btnCreate(_ sender: Any) { // 실행타임에 UIImageViewX를 생성하자!! 동적생성!! // programmatically creation!! // row값 입력 받기 // 값이 null인 경우를 대비 let row = t_row.text! let col = t_col.text! for a in 1...Int(row)!{ for i in 1...Int(col)!{ let imgView = UIImageView(image: UIImage(named: "chicken.jpeg")) // 크기를 먼저 설정 imgView.frame = CGRect(x: i*52, y: a*55, width: 50, height: 50) // 생성된 이미지뷰를 디폴트부모 뷰에 부착!! myView.addSubview(imgView) } } } @IBAction func btnRemove(_ sender: Any) { // 기존 디폴트뷰로부터 생성된 자식뷰들을 제거 // 배열에 들어있는 이미지 요소들을 하나씩 꺼내어 그 이미지뷰가 보유한 removeFromSuperView()를 호출 for obj in myView.subviews{ obj.removeFromSuperview() } } override func viewDidLoad() { super.viewDidLoad() // 이미지가 부착될 뷰를 준비하자!! // 프로그래밍 적으로 생성하자!! myView = UIView(frame: CGRect(x: 0, y: 200, width: 414, height: 500)) myView.backgroundColor = UIColor.yellow // 부모 뷰에 부착!! self.view.addSubview(myView) } }
// // mesiViewController.swift // APP-SCONTRINI // // Created by Mhscio on 19/12/2019. // Copyright © 2019 Mhscio. All rights reserved. // import UIKit import FirebaseStorage import FirebaseFirestore import FirebaseAuth class mesiViewController: UIViewController, UITableViewDataSource , UITableViewDelegate { var titoloCella:String = " " @IBOutlet weak var myTableView: UITableView! let db = Firestore.firestore() var arrayMesi : [String] = [] func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { print(arrayMesi) return arrayMesi.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) cell.selectionStyle = .none cell.textLabel?.text = intToMonth(meseNumero: arrayMesi[indexPath.row]) return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let vc = storyboard?.instantiateViewController(withIdentifier: "nonNeHoIdea") as? ProvaBottoneDentroCella vc?.meseCella = arrayMesi[indexPath.row] vc?.titoloCella = titoloCella self.navigationController?.pushViewController(vc!, animated: true) } override func viewDidLoad() { super.viewDidLoad() mesi() print(arrayMesi) print(titoloCella) // Do any additional setup after loading the view. } func mesi() { if let uid = Auth.auth().currentUser?.uid { let campo = self.db.collection("users").document(uid) campo.collection("scontrini").whereField("anno", isEqualTo: titoloCella).getDocuments() { (querySnapshot, err) in if let err = err { print("Error getting documents: \(err)") } else { for document in querySnapshot!.documents { let mese = (document.data()["mese"] ?? "nada") as! String if !self.arrayMesi.contains(mese){ self.arrayMesi.append(mese) } } print(self.arrayMesi) } self.myTableView.reloadData() } } } func intToMonth(meseNumero : String ) -> String { let a:Int? = Int(meseNumero) let mesi = ["Default ", "Gennaio","Febbraio", "Marzo" , "Aprile", "Maggio", "Giugno", "Luglio", "Agosto","Settembre","Ottobre","Novembre","Dicembre"] return mesi[a ?? 0] } }
// // ChatMessageCell.swift // PChat // // Created by Robin Ruf on 20.01.21. // import UIKit class ChatMessageCell: UICollectionViewCell { let textView: UITextView = { let textView = UITextView() textView.font = UIFont.systemFont(ofSize: 14) textView.backgroundColor = UIColor.clear textView.textColor = UIColor.white textView.translatesAutoresizingMaskIntoConstraints = false return textView }() let profileImageView: UIImageView = { let imageView = UIImageView() imageView.image = UIImage(named: "default_profile") imageView.layer.cornerRadius = 16 imageView.layer.masksToBounds = true imageView.contentMode = .scaleAspectFill imageView.clipsToBounds = true imageView.translatesAutoresizingMaskIntoConstraints = false return imageView }() static let greenColor = UIColor(red: 107 / 255, green: 142 / 255, blue: 35 / 255, alpha: 0.8) let bubbleView: UIView = { let view = UIView() view.backgroundColor = greenColor view.layer.cornerRadius = 16 view.layer.masksToBounds = true view.translatesAutoresizingMaskIntoConstraints = false return view }() var bubbleViewWidthAnchor: NSLayoutConstraint? var bubbleViewRightAnchor: NSLayoutConstraint? var bubbleViewLeftAnchor: NSLayoutConstraint? override init(frame: CGRect) { super.init(frame: frame) addSubview(bubbleView) addSubview(textView) addSubview(profileImageView) // Profilbild profileImageView.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 8).isActive = true profileImageView.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true profileImageView.widthAnchor.constraint(equalToConstant: 32).isActive = true profileImageView.heightAnchor.constraint(equalToConstant: 32).isActive = true // Textview textView.leftAnchor.constraint(equalTo: bubbleView.leftAnchor, constant: 8).isActive = true textView.rightAnchor.constraint(equalTo: bubbleView.rightAnchor).isActive = true textView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true textView.heightAnchor.constraint(equalTo: self.heightAnchor).isActive = true // Containerview / Bubbleview bubbleViewRightAnchor = bubbleView.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -8) bubbleViewRightAnchor?.isActive = true bubbleViewLeftAnchor = bubbleView.leftAnchor.constraint(equalTo: profileImageView.rightAnchor, constant: 8) bubbleView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true bubbleViewWidthAnchor = bubbleView.widthAnchor.constraint(equalToConstant: 200) bubbleViewWidthAnchor?.isActive = true bubbleView.heightAnchor.constraint(equalTo: self.heightAnchor).isActive = true } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
// // ViewController.swift // YelpApiProject // // Created by AT on 12/2/16. // Copyright © 2016 Martin. All rights reserved. // import UIKit import CoreLocation class PlacesTVController: UITableViewController { var places = [PlaceInformation]() var placesGetter = PlacesGetter() var PLACE_DETAIL_LOAD_SEGUE = "PlaceDetailLoadSegue" var rootLatitude:String! var rootLongitude:String! var placesTVControllerRootLocation:CLLocation! override func viewDidLoad() { super.viewDidLoad() title = "Nearby Places" func updatePlaces(inPlaces:[PlaceInformation]){ places = inPlaces var indexPaths = [IndexPath]() var itemPos = 0 for _ in inPlaces{ let index = itemPos let indexPath = IndexPath(row: index, section: 0) indexPaths.append(indexPath) itemPos += 1 //print("Place name is \(eachPlace.name)") } if places.count > 0{ tableView.insertRows(at: indexPaths, with: .automatic) } } // print("Root latitude is \(rootLatitude)") // print("Root longitude is \(rootLongitude)") print("PlacesTVControllerRootLocation in PlacesTVController is \(placesTVControllerRootLocation)") placesGetter.getPlaces(latitude: String(Int(placesTVControllerRootLocation.coordinate.latitude)), longitude: String(Int(placesTVControllerRootLocation.coordinate.longitude)), completionListener: updatePlaces) //placesGetter.getPlaces(latitude: rootLatitude, longitude: rootLongitude, completionListener: updatePlaces) // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "PlaceItemCell") as! PlaceItemCell //print("Long is \(long) Lat is \(lat)") cell.PlaceName.text = places[indexPath.row].name return cell } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 0{ return places.count } return 0 } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == PLACE_DETAIL_LOAD_SEGUE{ let indexPath = tableView.indexPathForSelectedRow let selectedPlaceInfo = places[(indexPath?.row)!] let destinationViewController = segue.destination as? PlaceDetailViewController destinationViewController?.currentPlaceInfo = selectedPlaceInfo destinationViewController?.PlaceLatitude = String(Int(placesTVControllerRootLocation.coordinate.latitude)) destinationViewController?.PlaceLongitude = String(Int(placesTVControllerRootLocation.coordinate.longitude)) } } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { //performSegue(withIdentifier: PLACE_DETAIL_LOAD_SEGUE, sender: self) tableView.deselectRow(at: indexPath, animated: true) } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } }
// // SecondViewController.swift // LayoutGuides // // Created by Jack Cox on 7/22/15. // Copyright © 2015 Jack Cox. All rights reserved. // import UIKit class SpacingViewController: UIViewController { @IBOutlet weak var shoe1: UIImageView! @IBOutlet weak var shoe2: UIImageView! @IBOutlet weak var shoe3: UIImageView! var layoutGuide1 = UILayoutGuide() var layoutGuide2 = UILayoutGuide() var layoutGuide3 = UILayoutGuide() var layoutGuide4 = UILayoutGuide() override func viewDidLoad() { super.viewDidLoad() // add the layout guides to the view self.view.addLayoutGuide(layoutGuide1) self.view.addLayoutGuide(layoutGuide2) self.view.addLayoutGuide(layoutGuide3) self.view.addLayoutGuide(layoutGuide4) // make them all the same size self.layoutGuide1.widthAnchor.constraintEqualToAnchor(layoutGuide2.widthAnchor).active = true self.layoutGuide1.widthAnchor.constraintEqualToAnchor(layoutGuide3.widthAnchor).active = true self.layoutGuide1.widthAnchor.constraintEqualToAnchor(layoutGuide4.widthAnchor).active = true // string the layout guides and show images together leading to trailing across the screen self.view.leadingAnchor.constraintEqualToAnchor(layoutGuide1.leadingAnchor).active = true self.layoutGuide1.trailingAnchor.constraintEqualToAnchor(shoe1.leadingAnchor).active = true self.shoe1.trailingAnchor.constraintEqualToAnchor(layoutGuide2.leadingAnchor).active = true self.layoutGuide2.trailingAnchor.constraintEqualToAnchor(shoe2.leadingAnchor).active = true self.shoe2.trailingAnchor.constraintEqualToAnchor(layoutGuide3.leadingAnchor).active = true self.layoutGuide3.trailingAnchor.constraintEqualToAnchor(shoe3.leadingAnchor).active = true self.shoe3.trailingAnchor.constraintEqualToAnchor(layoutGuide4.leadingAnchor).active = true self.layoutGuide4.trailingAnchor.constraintEqualToAnchor(self.view.trailingAnchor).active = true self.view.addConstraint(NSLayoutConstraint(item: self.view, attribute: .Leading, relatedBy: .Equal, toItem: layoutGuide1, attribute: .Leading, multiplier: 1, constant: 0)) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() self.view.showLayoutGuides() } }
// // GrowthFormViewController.swift // PlantID // // Created by Apurva Jakhanwal on 4/30/18. // Copyright © 2018 UCI-Nature. All rights reserved. // import UIKit class GrowthFormViewController: UIViewController { @IBOutlet var prostate: UISwitch! @IBOutlet var decumbent: UISwitch! @IBOutlet var ascending: UISwitch! @IBOutlet var erect: UISwitch! @IBOutlet var mat: UISwitch! @IBOutlet var clump: UISwitch! @IBOutlet var rosette: UISwitch! @IBOutlet var basil: UISwitch! @IBOutlet var vine: UISwitch! @IBOutlet var next_flower: UIButton! @IBOutlet var scroll: UIScrollView! @IBAction func prostate_selected(prostate: UISwitch){ if(prostate.isOn == true){ plantinfo.growth_form.insert("prostate") print(plantinfo.growth_form) next_flower.isEnabled = true } else{ if(plantinfo.growth_form.contains("prostate")){ plantinfo.growth_form.remove("prostate") if plantinfo.growth_form.count == 0{ next_flower.isEnabled = false } } } } @IBAction func decumbent_selected(decumbent: UISwitch){ if(decumbent.isOn == true){ plantinfo.growth_form.insert("decumbent") print(plantinfo.growth_form) next_flower.isEnabled = true } else{ if(plantinfo.growth_form.contains("decumbent")){ plantinfo.growth_form.remove("decumbent") if plantinfo.growth_form.count == 0{ next_flower.isEnabled = false } } } } @IBAction func ascending_selected(ascending: UISwitch){ if(ascending.isOn == true){ plantinfo.growth_form.insert("ascending") print(plantinfo.growth_form) next_flower.isEnabled = true } else{ if(plantinfo.growth_form.contains("ascending")){ plantinfo.growth_form.remove("ascending") if plantinfo.growth_form.count == 0{ next_flower.isEnabled = false } } } } @IBAction func erect_selected(erect: UISwitch){ if(erect.isOn == true){ plantinfo.growth_form.insert("erect") print(plantinfo.growth_form) next_flower.isEnabled = true } else{ if(plantinfo.growth_form.contains("erect")){ plantinfo.growth_form.remove("erect") if plantinfo.growth_form.count == 0{ next_flower.isEnabled = false } } } } @IBAction func mat_selected(mat: UISwitch){ if(mat.isOn == true){ plantinfo.growth_form.insert("mat") print(plantinfo.growth_form) next_flower.isEnabled = true } else{ if(plantinfo.growth_form.contains("mat")){ plantinfo.growth_form.remove("mat") if plantinfo.growth_form.count == 0{ next_flower.isEnabled = false } } } } @IBAction func clump_selected(clump: UISwitch){ if(clump.isOn == true){ plantinfo.growth_form.insert("clump") print(plantinfo.growth_form) next_flower.isEnabled = true } else{ if(plantinfo.growth_form.contains("clump")){ plantinfo.growth_form.remove("clump") if plantinfo.growth_form.count == 0{ next_flower.isEnabled = false } } } } @IBAction func rosette_selected(rosette: UISwitch){ if(rosette.isOn == true){ plantinfo.growth_form.insert("rosette") print(plantinfo.growth_form) next_flower.isEnabled = true } else{ if(plantinfo.growth_form.contains("rosette")){ plantinfo.growth_form.remove("rosette") if plantinfo.growth_form.count == 0{ next_flower.isEnabled = false } } } } @IBAction func basil_selected(basil: UISwitch){ if(basil.isOn == true){ plantinfo.growth_form.insert("basil") print(plantinfo.growth_form) next_flower.isEnabled = true } else{ if(plantinfo.growth_form.contains("basil")){ plantinfo.growth_form.remove("basil") if plantinfo.growth_form.count == 0{ next_flower.isEnabled = false } } } } @IBAction func vine_selected(vine: UISwitch){ if(vine.isOn == true){ plantinfo.growth_form.insert("vine") print(plantinfo.growth_form) next_flower.isEnabled = true } else{ if(plantinfo.growth_form.contains("vine")){ plantinfo.growth_form.remove("vine") if plantinfo.growth_form.count == 0{ next_flower.isEnabled = false } } } } override func viewDidLoad() { super.viewDidLoad() scroll.contentSize = CGSize(width: self.view.frame.size.width, height: self.view.frame.size.height+2500) prostate.addTarget(self, action: #selector(GrowthFormViewController.prostate_selected(prostate:)), for: UIControlEvents.valueChanged) decumbent.addTarget(self, action: #selector(GrowthFormViewController.decumbent_selected(decumbent:)), for: UIControlEvents.valueChanged) ascending.addTarget(self, action: #selector(GrowthFormViewController.ascending_selected(ascending:)), for: UIControlEvents.valueChanged) erect.addTarget(self, action: #selector(GrowthFormViewController.erect_selected(erect:)), for: UIControlEvents.valueChanged) mat.addTarget(self, action: #selector(GrowthFormViewController.mat_selected(mat:)), for: UIControlEvents.valueChanged) clump.addTarget(self, action: #selector(GrowthFormViewController.clump_selected(clump:)), for: UIControlEvents.valueChanged) rosette.addTarget(self, action: #selector(GrowthFormViewController.rosette_selected(rosette:)), for: UIControlEvents.valueChanged) basil.addTarget(self, action: #selector(GrowthFormViewController.basil_selected(basil:)), for: UIControlEvents.valueChanged) vine.addTarget(self, action: #selector(GrowthFormViewController.vine_selected(vine:)), for: UIControlEvents.valueChanged) if plantinfo.growth_form.count == 0{ next_flower.isEnabled = false } if plantinfo.growth_form.contains("prostate"){ prostate.setOn(!prostate.isOn, animated: true) } if plantinfo.growth_form.contains("decumbent"){ decumbent.setOn(!decumbent.isOn, animated: true) } if plantinfo.growth_form.contains("ascending"){ ascending.setOn(!ascending.isOn, animated: true) } if plantinfo.growth_form.contains("erect"){ erect.setOn(!erect.isOn, animated: true) } if plantinfo.growth_form.contains("mat"){ mat.setOn(!mat.isOn, animated: true) } if plantinfo.growth_form.contains("clump"){ clump.setOn(!clump.isOn, animated: true) } if plantinfo.growth_form.contains("rosette"){ rosette.setOn(!rosette.isOn, animated: true) } if plantinfo.growth_form.contains("basil"){ basil.setOn(!basil.isOn, animated: true) } if plantinfo.growth_form.contains("vine"){ vine.setOn(!vine.isOn, animated: true) } } }
// // Team.swift // CoreDataRelationships1 // // Created by Sophie on 3/7/18. // Copyright © 2018 Sophie Zhou. All rights reserved. // import UIKit import CoreData import Novagraph @objc(Team) class Team: NSManagedObject, FetchOrCreatable { typealias T = Team var id: String = "" @NSManaged var name: String! @NSManaged var players: Set<Player>? func parse(data: [String : Any]) { } }
// // ScrollingViewController.swift // Pop // // Created by Rob Crabtree on 11/13/17. // Copyright © 2017 Rob Crabtree. All rights reserved. // import UIKit class ScrollingViewController: BaseViewController { @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var textField: UITextField! @IBOutlet weak var scrollViewBottomConstraint: NSLayoutConstraint! lazy var tapGestureRecognizer: UITapGestureRecognizer = { let tapper = UITapGestureRecognizer() tapper.addTarget(self, action: #selector(viewTapped(sender:))) return tapper }() // TODO: uncomment // Implements constraint property declared in base class // override var constraintToAdjustForKeyboard: NSLayoutConstraint? { // return scrollViewBottomConstraint // } @IBAction func sayIt(_ sender: UIButton) { guard let text = textField.text, text.count > 0 else { return } view.endEditing(true) // Using base class ok alert showOkAlert(title: "You said", message: text, completion: nil) } override func viewDidLoad() { super.viewDidLoad() scrollView.addGestureRecognizer(tapGestureRecognizer) textField.delegate = self } @objc func viewTapped(sender: UITapGestureRecognizer) { view.endEditing(true) } } extension ScrollingViewController: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { view.endEditing(true) return true } }
// // NotesGroup.swift // Prynote3 // // Created by tongyi on 12/13/19. // Copyright © 2019 tongyi. All rights reserved. // import Foundation class NotesGroup { var notes: [Note] let title: String let type: GroupType init(type: GroupType, notebooks: [Notebook]) { self.type = type switch type { case .single: guard notebooks.count == 1 else { fatalError("Single group type must contains 1 notebook") } self.notes = notebooks[0].notes self.title = notebooks[0].title case .all: self.notes = notebooks.flatMap { $0.notes } self.title = "All Notes" case .sharedWithMe: self.title = "Shared With Me" self.notes = [] } } enum GroupType { case single case all case sharedWithMe } }
// // TeamCell.swift // ArenaComps_v1 // // Created by Max on 20.12.2020. // import UIKit class TeamCell: UITableViewCell { private enum Metrics { static let numberOfLines = 0 static let cornerRadius: CGFloat = 8 static let textLabelSize: CGFloat = 20 static let buttonTitle = "delete" static let ratingLabelText = "rating:" } private var matesList = MatesList().getAll() private lazy var nameLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.numberOfLines = Metrics.numberOfLines return label }() private lazy var firstMateImage: UIImageView = { let image = UIImageView() image.translatesAutoresizingMaskIntoConstraints = false image.layer.cornerRadius = Metrics.cornerRadius image.clipsToBounds = true return image }() private lazy var secondMateImage: UIImageView = { let image = UIImageView() image.translatesAutoresizingMaskIntoConstraints = false image.layer.cornerRadius = Metrics.cornerRadius image.clipsToBounds = true return image }() private lazy var thirdMateImage: UIImageView = { let image = UIImageView() image.translatesAutoresizingMaskIntoConstraints = false image.layer.cornerRadius = Metrics.cornerRadius image.clipsToBounds = true return image }() private lazy var ratingLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.numberOfLines = Metrics.numberOfLines label.font = UIFont.systemFont(ofSize: Metrics.textLabelSize) return label }() private lazy var scoreLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.numberOfLines = Metrics.numberOfLines label.text = Metrics.ratingLabelText return label }() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.configurateView() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setTeamCell(_ comp: Comp) { self.nameLabel.text = comp.name self.firstMateImage.image = getImageByClassName(comp.firstMate) self.secondMateImage.image = getImageByClassName(comp.secondMate) self.thirdMateImage.image = getImageByClassName(comp.thirdMate) self.ratingLabel.text = String(comp.rating) } } private extension TeamCell { func getImageByClassName(_ name: String) -> UIImage { var image: UIImage? for mate in matesList { if name == mate.getName() { image = mate.getImage() } } return image! } func configurateView() { self.addSubview(firstMateImage) self.addSubview(secondMateImage) self.addSubview(thirdMateImage) self.addSubview(nameLabel) self.addSubview(ratingLabel) self.addSubview(scoreLabel) self.backgroundColor = .systemTeal NSLayoutConstraint.activate([ self.firstMateImage.topAnchor.constraint(equalTo: topAnchor, constant: 6), self.firstMateImage.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 6), self.firstMateImage.widthAnchor.constraint(equalToConstant: 50), self.firstMateImage.heightAnchor.constraint(equalTo: firstMateImage.widthAnchor), self.secondMateImage.topAnchor.constraint(equalTo: topAnchor, constant: 6), self.secondMateImage.leadingAnchor.constraint(equalTo: firstMateImage.trailingAnchor, constant: 10), self.secondMateImage.widthAnchor.constraint(equalTo: firstMateImage.widthAnchor), self.secondMateImage.heightAnchor.constraint(equalTo: firstMateImage.widthAnchor), self.thirdMateImage.topAnchor.constraint(equalTo: topAnchor, constant: 6), self.thirdMateImage.leadingAnchor.constraint(equalTo: secondMateImage.trailingAnchor, constant: 10), self.thirdMateImage.widthAnchor.constraint(equalTo: firstMateImage.widthAnchor), self.thirdMateImage.heightAnchor.constraint(equalTo: firstMateImage.widthAnchor), self.nameLabel.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -12), self.nameLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 28), self.ratingLabel.topAnchor.constraint(equalTo: topAnchor, constant: 22), self.ratingLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -18), self.scoreLabel.topAnchor.constraint(equalTo: topAnchor, constant: 24), self.scoreLabel.trailingAnchor.constraint(equalTo: ratingLabel.leadingAnchor, constant: -4) ]) } }
// // BaseRouter.swift // GALiveApp // // Created by luguangqing on 16/2/29. // Copyright © 2016年 luguangqing. All rights reserved. // import UIKit let kMainBundle = NSBundle.mainBundle() class BaseRouter: NSObject { let kSBMain = "Main" var controllerIdentifier: String! var controller: UIViewController! var handler: BaseHandler! }
/** * Copyright (c) 2017 Razeware LLC */ import Foundation struct Candy { let category: String let name: String }
// // CardDeck.swift // SetGameModified // // Created by Harsha on 28/06/19. // Copyright © 2019 Ixigo. All rights reserved. // import Foundation struct SetGame { private(set) var cards = [Card]() private(set) var score = 0 private let date = Date() private lazy var lastNotedTime = date.timeIntervalSinceNow var hintEnabled = false mutating func draw() -> Card? { if cards.isEmpty { return nil } return cards.remove(at: cards.count.random4arc) } mutating func containsSet(in setOf: [Card]) -> Bool { let curTime = date.timeIntervalSinceNow let firstCard = setOf[0], secondCard = setOf[1], thirdCard = setOf[2] guard (firstCard.shape == secondCard.shape && secondCard.shape == thirdCard.shape && firstCard.shape == thirdCard.shape) || (firstCard.shape != secondCard.shape && secondCard.shape != thirdCard.shape && firstCard.shape != thirdCard.shape) else { if !hintEnabled { score += Constants.Penalties.wrongSetFormationPenalty } return false; } guard (firstCard.color == secondCard.color && secondCard.color == thirdCard.color && firstCard.color == thirdCard.color) || (firstCard.color != secondCard.color && secondCard.color != thirdCard.color && firstCard.color != thirdCard.color) else { if !hintEnabled { score += Constants.Penalties.wrongSetFormationPenalty } return false; } guard (firstCard.shade == secondCard.shade && secondCard.shade == thirdCard.shade && firstCard.shade == thirdCard.shade) || (firstCard.shade != secondCard.shade && secondCard.shade != thirdCard.shade && firstCard.shade != thirdCard.shade) else { if !hintEnabled { score += Constants.Penalties.wrongSetFormationPenalty } return false; } guard (firstCard.number == secondCard.number && secondCard.number == thirdCard.number && firstCard.number == thirdCard.number) || (firstCard.number != secondCard.number && secondCard.number != thirdCard.number && firstCard.number != thirdCard.number) else { if !hintEnabled { score += Constants.Penalties.wrongSetFormationPenalty } return false; } if !hintEnabled { score = score + Constants.Game.pointEarnedForSet + Int(0.01 * (curTime - lastNotedTime)) } return true } mutating func deselectionPenalty() { score += Constants.Penalties.deselectionPenalty } init() { for shape in Card.Shape.allCases { for color in Card.Color.allCases { for shade in Card.Shade.allCases { for number in Card.Number.allCases { cards.append(Card(shape: shape, color: color, shade: shade, number: number)) } } } } cards.shuffle() } }
// // AddFriendsViewModel.swift // SpecialTraining // // Created by yintao on 2019/5/15. // Copyright © 2019 youpeixun. All rights reserved. // import Foundation import RxCocoa class AddFriendsViewModel: BaseViewModel { init(searchTap: Driver<Void>, searchText: Driver<String>) { super.init() searchTap.withLatestFrom(searchText) .filter{ userName in if userName.count > 0 { return true } NoticesCenter.alert(message: "请输入用户名") return false } ._doNext(forNotice: hud) .drive(onNext: { [weak self] userName in EMClient.shared()?.contactManager.addContact(userName, message: "请求添加好友", completion: { (msg, error) in if let err = error { self?.hud.failureHidden(err.errorDescription) }else { self?.hud.successHidden("添加成功") } }) }) .disposed(by: disposeBag) } }
// // Constants.swift // CSVAssignment // // Created by Rukmani on 18/08/17. // Copyright © 2017 rukmani. All rights reserved. // import Foundation typealias GetDataCompletion = ([DataModel]) -> () struct StaticURL { static let url = "https://www.metoffice.gov.uk/climate/uk/summaries/datasets#Yearorder" }
// // Extensions.swift // MetalRenderer // // Created by junwoo on 2020/08/16. // Copyright © 2020 dominico park. All rights reserved. // import Foundation import MetalKit extension MTLVertexDescriptor { static func defaultVertexDescriptor() -> MTLVertexDescriptor { let descriptor = MTLVertexDescriptor() //position descriptor.attributes[0].format = .float3 descriptor.attributes[0].offset = 0 descriptor.attributes[0].bufferIndex = 0 //color // descriptor.attributes[1].format = .float3 // descriptor.attributes[1].offset = MemoryLayout<float3>.stride // descriptor.attributes[1].bufferIndex = 0 //stride descriptor.layouts[0].stride = MemoryLayout<float3>.stride return descriptor } } extension MDLVertexDescriptor { static func defaultVertexDescriptor() -> MDLVertexDescriptor { let descriptor = MTKModelIOVertexDescriptorFromMetal(.defaultVertexDescriptor()) let attributePosition = descriptor.attributes[0] as! MDLVertexAttribute attributePosition.name = MDLVertexAttributePosition return descriptor } }
// // KidHeadView.swift // Wolf Pack // // Created by Sean Hess on 9/5/14. // Copyright (c) 2014 Orbital Labs. All rights reserved. // import UIKit // this has a circle head, and a label name underneath it. // should I make an interface builder thing? // make just the head for now. // 100x100 class ChildHeadCell : UICollectionViewCell, InvitationStatusDelegate { var imageView:UIImageView! var checkView:UIImageView! var nameLabel:UILabel! var circle:CAShapeLayer! var drawAnimation:CABasicAnimation? var child:MOChild? var invitation:InvitationStatus? func configure() { self.backgroundColor = UIColor.clearColor() self.clipsToBounds = false checkView = UIImageView(image: UIImage(named: "check.png")) checkView.frame = CGRectMake(self.bounds.size.width-24, self.bounds.size.width-24, 26, 26) imageView = UIImageView(frame: self.bounds) imageView.layer.cornerRadius = imageView.frame.size.height / 2 imageView.layer.masksToBounds = true imageView.layer.borderColor = UIColor.clearColor().CGColor imageView.layer.borderWidth = 3 nameLabel = UILabel(frame: CGRectMake(0, self.bounds.size.height, self.bounds.size.width, 20)) nameLabel.textAlignment = NSTextAlignment.Center nameLabel.font = UIFont.systemFontOfSize(12.0) self.contentView.addSubview(imageView) self.contentView.addSubview(checkView) self.contentView.addSubview(nameLabel) circle = CAShapeLayer() imageView.layer.addSublayer(circle) } override init(frame: CGRect) { super.init(frame: frame) configure() } required init(coder aDecoder: NSCoder) { super.init(coder:aDecoder) configure() } // this RE-SETS the data, never animating func setData(child:MOChild, selected:Bool) { self.child = child let url = NSURL(string:child.imageUrl) imageView.sd_setImageWithURL(url) nameLabel.text = child.firstName renderSelected(selected) } // alternative to setData func setInvitationStatus(invite:InvitationStatus) { invitation?.delegate = nil invitation = invite invitation?.delegate = self setData(invite.child, selected:invite.invited) } // without animation func renderSelected(value:Bool) { circle.hidden = !value checkView.hidden = !value } func animateCircle() { let radius = imageView.bounds.size.width/2 // Make a circular shape circle.path = UIBezierPath(roundedRect: CGRectMake(0, 0, 2.0*radius, 2.0*radius), cornerRadius: radius).CGPath // Center the shape in self.view circle.position = CGPointMake(CGRectGetMidX(self.imageView.frame)-radius, CGRectGetMidY(self.imageView.frame)-radius); // Configure the apperence of the circle circle.fillColor = UIColor.clearColor().CGColor circle.strokeColor = WPColorGreen.CGColor circle.lineWidth = 5 circle.hidden = false // Configure animation drawAnimation = CABasicAnimation(keyPath: "strokeEnd") drawAnimation?.duration = 0.5 // "animate over 10 seconds or so.." drawAnimation?.repeatCount = 1.0 // Animate only once.. // Animate from no part of the stroke being drawn to the entire stroke being drawn drawAnimation?.fromValue = 0.0 drawAnimation?.toValue = 1.0 // Experiment with timing to get the appearence to look the way you want drawAnimation?.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn) // Add the animation to the circle circle.addAnimation(drawAnimation, forKey:"drawCircleAnimation") delay(0.5) { println("done") self.checkView.hidden = false var frame = self.checkView.frame frame.size = CGSize(width: 0, height: 0) self.checkView.frame = frame UIView.animateWithDuration(0.2, animations: { frame.size = CGSize(width: 26, height: 26) self.checkView.frame = frame }, completion: {(done) in }) } } func delay(delay:Double, closure:()->()) { dispatch_after( dispatch_time( DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC)) ), dispatch_get_main_queue(), closure) } // override func prepareForReuse() { // super.prepareForReuse() // circle.removeAllAnimations() // println("prepare for reuse") // } func didUpdateStatus() { if self.invitation!.invited { circle.hidden = false animateCircle() } else { circle.hidden = true checkView.hidden = true } } // func addHoverEffect() { // // make it a little bigger // // make it pop off the page // // add a drop shadow // // // // UIView.animateWithDuration(0.5) { // var frame = self.imageView.frame // frame.origin.x = 4 // frame.origin.y = 4 // frame.size.width = self.bounds.size.width + 10 // frame.size.height = self.bounds.size.height + 10 // self.imageView.frame = frame // } // // self.imageView.layer.cornerRadius = (self.bounds.size.height+10) / 2 // // self.imageView.layer.shadowColor = UIColor.blackColor().CGColor // self.imageView.layer.shadowOpacity = 0.7 // self.imageView.layer.shadowOffset = CGSizeMake(-4, -4) // self.imageView.layer.shadowRadius = 0.5 // self.imageView.layer.masksToBounds = false // } }