text
stringlengths
8
1.32M
// // AppDelegate.swift // MapBoxTest // // Created by YanQi on 2020/04/13. // Copyright © 2020 MapBoxTest. All rights reserved. // import UIKit import CoreLocation import UserNotifications @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { /// 位置情報を管理するマネージャー private var locationManager: MBCLLocationManager = MBCLLocationManager.shared func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { locationManager.startRequestLocation() requestLocalNotificationAuth() if launchOptions?[UIApplication.LaunchOptionsKey.location] != nil { // 位置情報の更新を開始する locationManager.startUpdatingLocation() } return true } // MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { } private func requestLocalNotificationAuth() { var options: UNAuthorizationOptions // iOS12以降の場合お試しプッシュ通知を送る if #available(iOS 12.0, *) { options = [.alert, .sound, .badge, .provisional] } else { options = [.alert, .sound, .badge] } UNUserNotificationCenter.current().requestAuthorization(options: options) { (isAcceped, error) in guard error == nil else { print(error?.localizedDescription ?? "Unknown Error") return } if isAcceped { // 同意された場合 DispatchQueue.main.async { UIApplication.shared.registerForRemoteNotifications() } } else { // 拒否された場合 print("ローカル通知は拒否された") } } } } extension AppDelegate { func currentKeyWindow() -> UIWindow? { if #available(iOS 13.0, *) { return UIApplication.shared.windows[0] } else { return UIApplication.shared.keyWindow } } }
// // AppModelEditorDelegate.swift // myEats // // Created by JABE on 11/5/15. // Copyright © 2015 JABELabs. All rights reserved. // protocol AppModelEditorDelegate { func didAddInstance<T>(sourceViewController: UIViewController, instance: T) func didUpdateInstance<T>(sourceViewController: UIViewController, instance: T) }
// // ViewController.swift // NationInfo // // Created by 601 on 2020/02/26. // Copyright © 2020 601. All rights reserved. // import UIKit //나라 정보를 담을 구조체 선언 struct Nation{ var url:String //이미지명 var name:String //나라명 var city:String //수도 var rank:Int //소득순위 } class ViewController: UIViewController { //구조체를 담게될 배열 선언 var nationArray:Array = Array<Nation>() var index:Int=0 @IBOutlet weak var gonfalon: UIImageView! @IBOutlet weak var tv_country: UITextField! @IBOutlet weak var tv_Incomeranking: UITextField! @IBOutlet weak var tv_Capital: UITextField! override func viewDidLoad() { super.viewDidLoad() var aa = Nation(url: "1.png", name: "미국", city: "워싱턴.D.C", rank: 7) var bb = Nation(url: "2.jpg", name: "말레이시아", city: "쿠알라룸푸르", rank: 64) var cc = Nation(url: "3.jpg", name: "그리스", city: "아테네", rank: 41) var dd = Nation(url: "4.png", name: "영국", city: "런던", rank: 21) var ee = Nation(url: "5.jpg", name: "독일", city: "베를린", rank: 16) nationArray.append(aa) nationArray.append(bb) nationArray.append(cc) nationArray.append(dd) nationArray.append(ee) } @IBAction func btnClick(_ sender: Any) { next() } func next(){ //nationArray[index] gonfalon.image = UIImage(named: nationArray[index].url) tv_country.text = nationArray[index].name tv_Capital.text = nationArray[index].city tv_Incomeranking.text = String(nationArray[index].rank) if index == nationArray.count-1{ index = 0 }else{ index += 1 } } }
// // ViewController.swift // map_simple // // Created by yoshiyuki oshige on 2016/09/28. // Copyright © 2016年 yoshiyuki oshige. All rights reserved. // import UIKit import MapKit import CoreLocation class ViewController: UIViewController { // マップビュー @IBOutlet weak var myMap: MKMapView! // ツールバー @IBOutlet weak var toolBar: UIToolbar! // ツールバーのTintColorの初期値 var defaultColor:UIColor! // 横浜みなとみらいの領域を表示する @IBAction func gotoSpot(_ sender: Any) { // 緯度と経度 let ido = 35.454954 let keido = 139.6313859 // 中央に表示する座標 let center = CLLocationCoordinate2D(latitude: ido, longitude: keido) // スパン let span = MKCoordinateSpan(latitudeDelta: 0.02, longitudeDelta: 0.02) // 表示する領域 let theRegion = MKCoordinateRegion(center: center, span: span) // 領域の地図を表示する myMap.setRegion(theRegion, animated: true) } // 地図のタイプを切り替える @IBAction func changedMapType(_ sender: UISegmentedControl) { switch sender.selectedSegmentIndex { case 0 : // 地図 myMap.mapType = .standard // 俯角(見下ろす角度) myMap.camera.pitch = 0.0 // ツールバーを標準に戻す toolBar.tintColor = defaultColor toolBar.alpha = 1.0 case 1 : // 衛星写真 myMap.mapType = .satellite // ツールバーを白色の半透明にする toolBar.tintColor = UIColor.white toolBar.alpha = 0.8 case 2 : // 写真+地図(ハイブリッド) myMap.mapType = .hybrid // ツールバーを白色の半透明にする toolBar.tintColor = UIColor.white toolBar.alpha = 0.8 case 3: // 地図 myMap.mapType = .standard // ツールバーを標準に戻す toolBar.tintColor = defaultColor toolBar.alpha = 1.0 // 3Dビュー myMap.camera.pitch = 70 // 俯角(見下ろす角度) myMap.camera.altitude = 700 // 標高 default: break } } override func viewDidLoad() { super.viewDidLoad() // ツールバーの初期カラー defaultColor = toolBar.tintColor // スケールを表示する myMap.showsScale = true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
// // ViewController.swift // transinfoFinal // // Created by Jessica Cotrina Revilla on 7/26/16. // Copyright © 2016 Universidad de puerto rico-Mayaguez. All rights reserved. // import UIKit import CoreData class ViewController: UIViewController { @IBOutlet weak var userTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var login: UIButton! var myAO: AnyObject? var officerID = Dictionary<String,AnyObject>() override func viewDidLoad() { super.viewDidLoad() // 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. } @IBAction func login(sender: AnyObject) { print ("------------") print ("------outtt------") //let url = "http://localhost:9000/login" //let url = "http://136.145.116.83:8080/login" let url = "http://136.145.59.111:9000/login" var loginPostResults = WebService.post(url, parameters: ["username":userTextField.text!,"password":passwordTextField.text!] ) //print("Here's this Thing",loginPostResults["payload"]) //print(loginPostResults["error_code"]) //................................... //print("Aqui estoy",loginPostResults.popFirst()) //myAO = loginPostResults.first!.1 //myAO = loginPostResults["payload"] myAO = loginPostResults["payload"] let error = loginPostResults["error_code"] if error?.integerValue != 403 && error?.integerValue != 0 { officerID = (myAO as? Dictionary<String,AnyObject>)! //officerID = (myAO?.firstItem)! as! Dictionary<String, AnyObject> print("Here's the OfficerID",officerID["OfficerID"]) let singleton = Global.sharedGlobal singleton.foreignKeys.removeAll() singleton.listPeople.removeAll() singleton.listVehicle.removeAll() singleton.listNum = [0,0] singleton.selectedKey = 0 singleton.testString = "" let accidentConditionFK = Info(officerPlate: (officerID["PlateNumber"]!.stringValue), officerID: (officerID["OfficerID"] as? Int)!,crashBasicInformation: 0, accidentCondition: 0, newVehicle:0,newPerson: 0,personExtended:0,vehicleExtended:0,narrative:0,numCaso:"") singleton.foreignKeys.append(accidentConditionFK) let listPeopleInit = People(person: ["":""]) singleton.listPeople.append(listPeopleInit) print(singleton.foreignKeys) print(singleton.listPeople) }else{ let alert = UIAlertController(title: "Alert", message: "Username or password invalid", preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) } } }
// // ContactsTableViewController.swift // Desafio-Mobile-PicPay // // Created by Luiz Hammerli on 25/07/2018. // Copyright © 2018 Luiz Hammerli. All rights reserved. // import UIKit class ContactsTableViewController: UITableViewController, UISearchBarDelegate { var contacts = [Contact]() let cellID = "cellID" let appDelegate = UIApplication.shared.delegate as! AppDelegate let searchController = UISearchController(searchResultsController: nil) override func viewDidLoad() { super.viewDidLoad() tableView.tableFooterView = UIView() self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "list"), style: .done, target: self, action: #selector(showPaymentHistoryController)) getContacts() } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return contacts.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) as! ContactsTableViewCell cell.contact = contacts[indexPath.item] return cell } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let view = UIView() return view } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 10 } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { performSegue(withIdentifier: Strings.goToPaymentViewController, sender: contacts[indexPath.item]) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard let paymentViewController = segue.destination as? PaymentViewController, let contact = sender as? Contact else {return} paymentViewController.contact = contact } @objc func showPaymentHistoryController(){ let layout = UICollectionViewFlowLayout() let paymentHistoryCollectionViewController = PaymentHistoryCollectionViewController(collectionViewLayout: layout) self.navigationController?.show(paymentHistoryCollectionViewController, sender: self) } func getContacts(){ appDelegate.customActivityIndicator.showActivityIndicator() self.tableView.isUserInteractionEnabled = false appDelegate.apiClient.fetchUserContacts { (contacts, message) in if let contacts = contacts{ self.contacts = contacts DispatchQueue.main.async { self.tableView.isUserInteractionEnabled = true self.appDelegate.customActivityIndicator.hideActivityIndicator() self.tableView.reloadData()} } } } }
// // StartNewGameVC.swift // Shiso // // Created by Lucy DeLaurentis on 2/19/18. // Copyright © 2018 Micah DeLaurentis. All rights reserved. // import Foundation import UIKit import SpriteKit class StartNewGameVC: UIViewController, UITableViewDelegate, UITableViewDataSource { var tableView: UITableView! var contacts = [String]() var mainVC: UIViewController? let contactCellID = "contactCellID" var backBtn: UIButton = { let bb = UIButton() bb.frame = CGRect(origin: CGPoint(x: 10, y: 30), size: CGSize(width: 50, height: 50)) bb.backgroundColor = .white bb.layer.cornerRadius = 3 bb.setImage(UIImage(named: "homeBtnImage"), for: .normal) return bb }() var findOpponentBtn: UIButton! var timeBtn_2Min: UIButton! var timeBtn_5Min: UIButton! var timeBtn_10Min: UIButton! var timeBtn_untimed: UIButton! var singlePlayerModeBtn: UIButton! var playAFriendlbl: UILabel! var exitOutOfSinglePlayerModeBtn: UIButton! var userNameToChallenge: UITextField! var submitUserNameChallengeBtn: UIButton! override func viewDidLoad() { super.viewDidLoad() print("IN STARTNEWGAMEVC VIEW DID LOAD.") mainVC = UIApplication.shared.keyWindow?.rootViewController // print("main VC in new games vc: \(mainVC)") tableView = UITableView(frame: CGRect(x: view.frame.midX - 150, y: view.frame.midY + 90, width: 300, height: 100), style: UITableView.Style.plain) tableView.delegate = self tableView.dataSource = self view.addSubview(tableView) tableView.isHidden = true view.addSubview(backBtn) findOpponentBtn = UIButton() findOpponentBtn.setTitle("Find me an opponent", for: .normal) findOpponentBtn.setTitleColor(.white, for: .normal) findOpponentBtn.layer.cornerRadius = 10 findOpponentBtn.backgroundColor = UIColor(red: 85/255, green: 158/255, blue: 131/255, alpha: 1.0) view.addSubview(findOpponentBtn) findOpponentBtn.translatesAutoresizingMaskIntoConstraints = false findOpponentBtn.topAnchor.constraint(equalTo: backBtn.bottomAnchor, constant: 20).isActive = true findOpponentBtn.centerXAnchor.constraint(equalTo: tableView.centerXAnchor).isActive = true findOpponentBtn.widthAnchor.constraint(equalTo: tableView.widthAnchor).isActive = true findOpponentBtn.heightAnchor.constraint(equalToConstant: 60).isActive = true findOpponentBtn.addTarget(self, action: #selector(findOpponentBtnPressed), for: .touchUpInside) singlePlayerModeBtn = UIButton() singlePlayerModeBtn.setTitle("Single Player Mode", for: .normal) singlePlayerModeBtn.setTitleColor(.white, for: .normal) singlePlayerModeBtn.layer.cornerRadius = findOpponentBtn.layer.cornerRadius singlePlayerModeBtn.backgroundColor = findOpponentBtn.backgroundColor singlePlayerModeBtn.translatesAutoresizingMaskIntoConstraints = false view.addSubview(singlePlayerModeBtn) singlePlayerModeBtn.topAnchor.constraint(equalTo: findOpponentBtn.bottomAnchor, constant: 30).isActive = true singlePlayerModeBtn.centerXAnchor.constraint(equalTo: tableView.centerXAnchor).isActive = true singlePlayerModeBtn.widthAnchor.constraint(equalTo: findOpponentBtn.widthAnchor).isActive = true singlePlayerModeBtn.heightAnchor.constraint(equalTo: findOpponentBtn.heightAnchor).isActive = true singlePlayerModeBtn.addTarget(self, action: #selector(singlePlayerModeBtnPressed), for: .touchUpInside) //Add time option buttons to appear where single player mode button is timeBtn_2Min = UIButton() timeBtn_2Min.setTitle("2 min.", for: .normal) timeBtn_2Min.setTitleColor(.white, for: .normal) timeBtn_2Min.backgroundColor = .gray timeBtn_2Min.translatesAutoresizingMaskIntoConstraints = false view.addSubview(timeBtn_2Min) timeBtn_2Min.leftAnchor.constraint(equalTo: singlePlayerModeBtn.leftAnchor).isActive = true timeBtn_2Min.widthAnchor.constraint(equalToConstant: 75).isActive = true timeBtn_2Min.centerYAnchor.constraint(equalTo: singlePlayerModeBtn.centerYAnchor).isActive = true timeBtn_2Min.isHidden = true timeBtn_2Min.addTarget(self, action: #selector(timeBtn_2min_Pressed), for: .touchUpInside) timeBtn_5Min = UIButton() timeBtn_5Min.setTitle("5 min.", for: .normal) timeBtn_5Min.setTitleColor(.white, for: .normal) timeBtn_5Min.backgroundColor = .gray timeBtn_5Min.translatesAutoresizingMaskIntoConstraints = false view.addSubview(timeBtn_5Min) timeBtn_5Min.leftAnchor.constraint(equalTo: timeBtn_2Min.rightAnchor,constant: 10).isActive = true timeBtn_5Min.widthAnchor.constraint(equalToConstant: 75).isActive = true timeBtn_5Min.centerYAnchor.constraint(equalTo: singlePlayerModeBtn.centerYAnchor).isActive = true timeBtn_5Min.isHidden = true timeBtn_5Min.addTarget(self, action: #selector(timeBtn_5min_Pressed), for: .touchUpInside) exitOutOfSinglePlayerModeBtn = UIButton() /* exitOutOfSinglePlayerModeBtn.setImage(UIImage(named: "goBackIconBlue"), for: .normal) exitOutOfSinglePlayerModeBtn.translatesAutoresizingMaskIntoConstraints = false view.addSubview(exitOutOfSinglePlayerModeBtn) exitOutOfSinglePlayerModeBtn.rightAnchor.constraint(equalTo: findOpponentBtn.leftAnchor).isActive = true exitOutOfSinglePlayerModeBtn.topAnchor.constraint(equalTo: findOpponentBtn.bottomAnchor, constant: 40).isActive = true exitOutOfSinglePlayerModeBtn.widthAnchor.constraint(equalToConstant: 20).isActive = true exitOutOfSinglePlayerModeBtn.heightAnchor.constraint(equalToConstant: 20).isActive = true exitOutOfSinglePlayerModeBtn.isHidden = true exitOutOfSinglePlayerModeBtn.addTarget(self, action: #selector(exitOutOfSinglePlayerModeBtnPressed), for: .touchUpInside) */ userNameToChallenge = UITextField() view.addSubview(userNameToChallenge) userNameToChallenge.attributedPlaceholder = NSAttributedString(string: "Enter username to challenge... ", attributes: [NSAttributedString.Key.foregroundColor: UIColor.darkGray]) userNameToChallenge.layer.cornerRadius = 5 userNameToChallenge.backgroundColor = .white let leftPaddingView = UIView(frame: CGRect(x: 0, y: 0, width: 15, height: singlePlayerModeBtn.frame.size.height)) userNameToChallenge.translatesAutoresizingMaskIntoConstraints = false userNameToChallenge.topAnchor.constraint(equalTo: singlePlayerModeBtn.bottomAnchor, constant: 30).isActive = true userNameToChallenge.centerXAnchor.constraint(equalTo: singlePlayerModeBtn.centerXAnchor).isActive = true userNameToChallenge.widthAnchor.constraint(equalTo: singlePlayerModeBtn.widthAnchor, constant: 0).isActive = true userNameToChallenge.heightAnchor.constraint(equalTo: singlePlayerModeBtn.heightAnchor, constant: 0).isActive = true userNameToChallenge.addTarget(self, action: #selector(textEditingChanged), for: UIControl.Event.editingChanged) userNameToChallenge.autocorrectionType = UITextAutocorrectionType.no userNameToChallenge.autocapitalizationType = UITextAutocapitalizationType.none userNameToChallenge.leftView = leftPaddingView userNameToChallenge.leftViewMode = UITextField.ViewMode.always submitUserNameChallengeBtn = UIButton() submitUserNameChallengeBtn.setTitle("Submit Challenge", for: .normal) submitUserNameChallengeBtn.titleLabel?.font = UIFont(name: "AvenirNext-Bold", size: 20) submitUserNameChallengeBtn.setTitleColor(UIColor(red: 50/255, green: 115/255, blue: 50/255, alpha: 1.0), for: .normal) submitUserNameChallengeBtn.backgroundColor = .lightGray submitUserNameChallengeBtn.isHidden = true submitUserNameChallengeBtn.layer.cornerRadius = 4 // submitUserNameChallengeBtn.backgroundColor = .white submitUserNameChallengeBtn.translatesAutoresizingMaskIntoConstraints = false view.addSubview(submitUserNameChallengeBtn) submitUserNameChallengeBtn.topAnchor.constraint(equalTo: userNameToChallenge.bottomAnchor, constant: 10).isActive = true submitUserNameChallengeBtn.centerXAnchor.constraint(equalTo: tableView.centerXAnchor).isActive = true submitUserNameChallengeBtn.addTarget(self, action: #selector(submitUserNameChallengeBtnPressed), for: .touchUpInside) submitUserNameChallengeBtn.titleLabel?.adjustsFontSizeToFitWidth = true submitUserNameChallengeBtn.titleEdgeInsets = UIEdgeInsets(top: 5, left: 2, bottom: 2, right: 5) playAFriendlbl = UILabel() playAFriendlbl.text = "Play a friend:" playAFriendlbl.font = UIFont(name: GameConstants.TileLabelFontName, size: 25) playAFriendlbl.backgroundColor = .black playAFriendlbl.textColor = .white view.addSubview(playAFriendlbl) playAFriendlbl.isHidden = true playAFriendlbl.translatesAutoresizingMaskIntoConstraints = false //playAFriendlbl.bottomAnchor.constraint(equalTo: tableView.topAnchor).isActive = true playAFriendlbl.topAnchor.constraint(equalTo: submitUserNameChallengeBtn.bottomAnchor,constant: 5).isActive = true playAFriendlbl.centerXAnchor.constraint(equalTo: tableView.centerXAnchor).isActive = true backBtn.addTarget(self, action: #selector(backBtnPressed), for: .touchUpInside) Fire.dataService.loadContacts { (contacts) in if contacts.count > 0 { self.tableView.isHidden = false self.playAFriendlbl.isHidden = false } self.contacts = contacts DispatchQueue.main.async { self.tableView.reloadData() } } tableView.backgroundColor = .white } @objc func submitUserNameChallengeBtnPressed() { guard userNameToChallenge.text != "" else { print("NO USER NAME!! returning") return } challengeUser(contactName: userNameToChallenge.text!) userNameToChallenge.text = "" } @objc func backBtnPressed() { print("Back btn pressed in start new game VC") print("Presenting vc: \(presentingViewController) presentedVc: \(presentedViewController)") if let mainVC = UIApplication.shared.keyWindow?.rootViewController as? GameViewController { print("can let root vc be game vc") dismiss(animated: true, completion: nil) if let mainV = mainVC.view as? SKView { mainV.presentScene(nil) } if presentingViewController is LoginVC { print("YES< LOGIN PRESENTING!!") presentingViewController?.dismiss(animated: true){ mainVC.presentDisplayVC() } } else { print("LOGIN VC NOT PRESENTING") mainVC.presentDisplayVC() } } } @objc func textEditingChanged(textField: UITextField) { if textField.text != "" { submitUserNameChallengeBtn.isHidden = false } else { submitUserNameChallengeBtn.isHidden = true } } @objc func findOpponentBtnPressed() { Fire.dataService.createOpenInvite() let confirmationAction = UIAlertController(title: "The search is on!", message: "Once we find you an opponent your game will appear in your games menu. Check back soon!", preferredStyle: .alert) let ok = UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil) confirmationAction.addAction(ok) self.present(confirmationAction, animated: true, completion: nil) } @objc func singlePlayerModeBtnPressed(){ timeBtn_2Min.isHidden = false timeBtn_5Min.isHidden = false // timeBtn_10Min.isHidden = false singlePlayerModeBtn.isHidden = true exitOutOfSinglePlayerModeBtn.isHidden = false } @objc func exitOutOfSinglePlayerModeBtnPressed(){ timeBtn_2Min.isHidden = true timeBtn_5Min.isHidden = true // timeBtn_10Min.isHidden = true exitOutOfSinglePlayerModeBtn.isHidden = true singlePlayerModeBtn.isHidden = false } @objc func timeBtn_2min_Pressed() { timeBtn_Pressed(timeSelection: .twoMinute) } @objc func timeBtn_5min_Pressed() { timeBtn_Pressed(timeSelection: .fiveMinute) } func timeBtn_10min_Pressed() { timeBtn_Pressed(timeSelection: .tenMinute) } func timeBtn_untimed_Pressed() { timeBtn_Pressed(timeSelection: .untimed) } func timeBtn_Pressed(timeSelection: TimeSelection) { if let gameVC = mainVC as? GameViewController, let gameView = gameVC.view as? SKView { if let scene = GameplayScene(fileNamed: "GameplayScene") { print("success: about to set up game in skview in gameVC") let game = Game() game.timeSelection = timeSelection scene.game = game Fire.dataService.getCurrentUserName{ (userName) in guard userName != nil else { print("no user name!") return } print("User name: \(userName)") let p1 = Player(score: 0, userID: FirebaseConstants.CurrentUserID!, player1: true, userName: userName!, imageURL: nil, tileRack: TileRack()) game.singlePlayerMode = true game.player1 = p1 game.currentPlayerID = p1.userID scene.name = "Shiso GameScene" scene.scaleMode = .aspectFit scene.size = gameView.bounds.size gameVC.dismiss(animated: true, completion: nil) print("gameVC presenting: \(gameVC.presentingViewController)") print("about to present game view 2 mins from new game vc") gameView.presentScene(scene) } } } } deinit { print("Start new game VC deinitialized!") } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return contacts.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let contactCell = UITableViewCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: contactCellID) let contact = contacts[indexPath.row] contactCell.textLabel?.text = contact /* let inviteBtn = UIButton(type: .system) inviteBtn.setTitle("Invite!", for: .normal) inviteBtn.frame.size = CGSize(width: 100, height: 30) inviteBtn.frame.origin.x = contactCell.frame.origin.x + contactCell.frame.size.width - inviteBtn.frame.size.width - 5 contactCell.addSubview(inviteBtn) */ return contactCell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let contactName = contacts[indexPath.row] challengeUser(contactName: contactName) } func challengeUser(contactName: String) { let msg = "Send \(contactName) an Invitation?" let alert = UIAlertController(title: "Challenge", message: msg, preferredStyle: UIAlertController.Style.alert) alert.addAction(UIAlertAction(title: "Yes", style: UIAlertAction.Style.default, handler: {(action) in Fire.dataService.postChallenge(opponentUserName: contactName, completion: { (success) in guard success else { let failureNotification = UIAlertController(title: "Oops!", message: "We can't find a user named '\(contactName)'. Please check your spelling and try again. Case matters!", preferredStyle: UIAlertController.Style.alert) failureNotification.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) self.present(failureNotification, animated: false, completion: nil) return } let confirmationAction = UIAlertController(title: "Invitation successfully sent to \(contactName)!", message: nil, preferredStyle: .alert) // self.present(confirmationAction, animated: true, completion: {(action) // in // DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: { // confirmationAction.dismiss(animated: true, completion: nil) // }) // // /* UIView.animate(withDuration: 3.0, delay: 0, options: UIViewAnimationOptions.curveEaseInOut, animations: { // confirmationAction.view.alpha = 0 // confirmationAction.view.backgroundColor = .green // }, completion: {(done) in confirmationAction.dismiss(animated: true, completion: nil)}) // */ // // }) self.present(confirmationAction, animated: true, completion: { DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: { confirmationAction.dismiss(animated: true, completion: nil) }) }) }) })) alert.addAction(UIAlertAction(title: "No", style: .default, handler: nil)) present(alert, animated: true, completion: nil) } }
// // Copyright © 2016 Landet. All rights reserved. // import Foundation protocol DictionaryInitializable { init(dictionary: [String : AnyObject]) } protocol DictionaryPersistable { func asDictionary() -> [String : AnyObject] } class APIUtil { static func parse<T: DictionaryInitializable>(response response: APIResponse) -> (objects: T?, error: NSError?) { var object: T? var error: NSError? if let apiError = response.error { error = apiError } else if let objectData = response.body as? [String : AnyObject] { object = T(dictionary: objectData) } return (object, error) } static func parseAsArray<T: DictionaryInitializable>(response response: APIResponse) -> (objects: [T]?, error: NSError?) { var objects: [T]? var error: NSError? if let apiError = response.error { error = apiError } else if let objectData = response.body as? [[String : AnyObject]] { objects = objectData.map(T.init) } return (objects, error) } static func parseArray<T: DictionaryInitializable>(json json: AnyObject, key: String) -> [T]? { guard let json = json as? [String : AnyObject] else { return nil } guard let array = json[key] as? [[String : AnyObject]] else { return nil } return array.map(T.init) } static func parseBool(json json: AnyObject, key: String) -> Bool { guard let json = json as? [String : AnyObject] else { return false } return (json[key] as? Bool) ?? false } }
// // CommentObject.swift // Heyoe // // Created by Nam Phong Nguyen on 8/4/15. // Copyright (c) 2015 Nam Phong Nguyen. All rights reserved. // import UIKit class CommentObject { var comment: String? var userID: UInt? var userName: String? init(obj: QBCOCustomObject) { self.comment = obj.fields["comment"] as? String ?? "" self.userName = obj.fields["userName"] as? String ?? "" self.userID = obj.userID } }
// // Font.swift // cosmos // // Created by Tue Nguyen on 4/14/16. // Copyright © 2016 Savvycom. All rights reserved. // import Foundation import UIKit extension UIFont { class func applicationFont(_ size: CGFloat) -> UIFont { return UIFont(name: "HelveticaNeue", size: size)! } class func boldApplicationFont(_ size: CGFloat) -> UIFont { return UIFont(name: "HelveticaNeue-Bold", size: size)! } class func mediumAppicationFont(_ size: CGFloat) -> UIFont { return UIFont(name: "HelveticaNeue-Medium", size: size)! } class func lightApplicationFont(_ size: CGFloat) -> UIFont { return UIFont(name: "HelveticaNeue-Light", size: size)! } class func italicApplicationFont(_ size: CGFloat) -> UIFont { return UIFont(name: "HelveticaNeue-Italic", size: size)! } class func ubuntuMediumFont(_ size: CGFloat) -> UIFont { return UIFont(name: "Ubuntu-Medium", size: size)! } class func notosansFont(_ size: CGFloat) -> UIFont { return UIFont(name: "NotoSans", size: size)! } // class func notosansMediumFont(_ size: CGFloat) -> UIFont { // return UIFont(name: "NotoSans-Medium", size: size)! // } class func notosansBoldFont(_ size: CGFloat) -> UIFont { return UIFont(name: "NotoSans-Bold", size: size)! } class func robotoLightFont(_ size: CGFloat) -> UIFont { return UIFont(name: "Roboto-Light", size: size)! } }
// // RPBRelaxGameScene.swift // GameProject // // Created by AppCodin <info@appcodin.com> on 5/5/17. // Copyright © 2017 AppCodin <info@appcodin.com>. All rights reserved. // import SpriteKit import GameplayKit class RPBRelaxGameScene: RPBBaseGameScene { // MARK: - Constants let offsetScoreImage = CGFloat(60) let scoreImageName = "star" // MARK: - Properties let player = RPBPlayer() // MARK: - Movies override func didMove(to view: SKView) { setupBackground() showTopBar() showScoreStarAndLabel() setupPhysicsBody() } private func showScoreStarAndLabel() { let playersScoreImageTexture = SKTexture(imageNamed: scoreImageName) playersScoreImage = SKSpriteNode(texture: playersScoreImageTexture) playersScoreImage.position = CGPoint(x: offsetScoreImage - topBar.frame.size.width / 2, y: 0) topBar.addChild(playersScoreImage) let vx = offsetScoreImage + playersScoreImage.frame.width - topBar.frame.size.width / 2 let vy = 0 - playersScoreImage.frame.height / 4 playersScoreLabel.position = CGPoint(x: vx, y: vy) playersScoreLabel.fontSize = CGFloat(playersScoreLabelFontSize) playersScoreLabel.fontColor = .black playersScoreLabel.text = "0" playersScoreLabel.horizontalAlignmentMode = .left topBar.addChild(playersScoreLabel) } // MARK: - Touches override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { if gamePaused { return } if let touch = touches.first { let position = touch.location(in: self) let nodesList = self.nodes(at: position) for element in nodesList { if element.name == redBallNodeName || element.name == greenBallNodeName { if view != nil { element.removeFromParent() counterDecriment() playersScoreLabel.text = String(player.ballsCounter) return } } } counterIncrement() playersScoreLabel.text = String(player.ballsCounter) addBall(isRed: false, point: position) } } private func counterDecriment() { if player.ballsCounter > 0 { player.ballsCounter -= 1 } } private func counterIncrement() { player.ballsCounter += 1 } }
// // LessLogo.swift // LessLogoAnimation // // Created by 宋宋 on 16/2/27. // Copyright © 2016年 DianQK. All rights reserved. // import RxSwift import RxCocoa private let _animationKey = "_less_animation_load" /// 第一种实现姿势,也是最常见的姿势 @IBDesignable class LessLogoView: UIView { let lessLayer = CAShapeLayer() let pathFull = UIBezierPath() lazy private(set) var animation: CAKeyframeAnimation = { [unowned self] in let keyAni = CAKeyframeAnimation(keyPath: "position") keyAni.path = self.pathFull.CGPath keyAni.duration = 5 keyAni.delegate = self return keyAni }() lazy private(set) var ball: CALayer = { [unowned self] in let ball = CALayer() ball.bounds.size = CGSize(width: self.lineWidth * 4, height: self.lineWidth * 4) ball.cornerRadius = self.lineWidth * 2 ball.backgroundColor = self.backgroundColor?.CGColor return ball }() override func drawRect(rect: CGRect) { assert(rect.size.width / rect.size.height > (1 + sqrt(2)) / 2, "width/height > 1.207") /// 我们假设都是 r2 >= r1 ,1 是左边的半球,2 是右边的半球 let r2 = rect.size.height / 2 // 先计算 r2 let r1 = rect.size.width / (1 + sqrt(2)) - r2 // 再计算 r1 /// 计算两个中心 let center1 = CGPoint(x: r1, y: r2) let center2 = CGPoint(x: rect.size.width - r2, y: r2) /// 交界点 A let keyPointA = CGPoint(x: (1 + sqrt(2)) * r1, y: r2) pathFull.moveToPoint(keyPointA) pathFull.addArcWithCenter(center2, radius: r2, startAngle: CGFloat(M_PI/4 * 3), endAngle: CGFloat(M_PI * 2 - M_PI/4 * 3), clockwise: false) pathFull.addArcWithCenter(center1, radius: r1, startAngle: CGFloat(M_PI/4), endAngle: CGFloat(M_PI * 2 - M_PI/4), clockwise: true) pathFull.closePath() lessLayer.path = pathFull.CGPath lessLayer.fillColor = UIColor.clearColor().CGColor layer.addSublayer(lessLayer) } func startAnimation() { layer.addSublayer(ball) ball.addAnimation(animation, forKey: _animationKey) } func stopAnimation() { ball.removeAnimationForKey(_animationKey) ball.removeFromSuperlayer() } override func animationDidStop(anim: CAAnimation, finished flag: Bool) { if flag { startAnimation() } } } // MARK: - Support IB extension LessLogoView { @IBInspectable var strokeColor: UIColor? { get { if let strokeColor = lessLayer.strokeColor { return UIColor(CGColor: strokeColor) } return nil } set { lessLayer.strokeColor = newValue?.CGColor } } @IBInspectable var lineWidth: CGFloat { get { return lessLayer.lineWidth } set { lessLayer.lineWidth = newValue } } } // MARK: - Support RxSwift extension LessLogoView { var rx_run: AnyObserver<Bool> { return UIBindingObserver(UIElement: self) { lessLogo, run in run ? lessLogo.startAnimation() : lessLogo.stopAnimation() }.asObserver() } var rx_duration: AnyObserver<CFTimeInterval> { return UIBindingObserver(UIElement: self) { lessLogo, value in lessLogo.animation.duration = value }.asObserver() } }
// // AccountViewController.swift // Adamant // // Created by Anokhov Pavel on 07.01.2018. // Copyright © 2018 Adamant. All rights reserved. // import UIKit import SafariServices import Eureka // MARK: - Localization extension String.adamantLocalized { struct account { static let title = NSLocalizedString("AccountTab.Title", comment: "Account page: scene title") static let sorryAlert = NSLocalizedString("AccountTab.TransferBlocked.Title", comment: "Account tab: 'Transfer not allowed' alert title") static let webApp = NSLocalizedString("AccountTab.TransferBlocked.GoToPWA", comment: "Account tab: 'Transfer not allowed' alert 'go to WebApp button'") static let transferNotAllowed = NSLocalizedString("AccountTab.TransferBlocked.Message", comment: "Account tab: Inform user that sending tokens not allowed by Apple until the end of ICO") // URLs static let joinIcoUrlFormat = NSLocalizedString("AccountTab.JoinIco.UrlFormat", comment: "Account tab: A full 'Join ICO' link, with %@ as address") static let getFreeTokensUrlFormat = NSLocalizedString("AccountTab.FreeTokens.UrlFormat", comment: "Account atb: A full 'Get free tokens' link, with %@ as address") // Errors static let failedToUpdate = NSLocalizedString("AccountTab.Error.FailedToUpdateAccountFormat", comment: "Account tab: Failed to update account message. %@ for error message") private init() { } } } fileprivate extension String.adamantLocalized.alert { static let logoutMessageFormat = NSLocalizedString("AccountTab.ConfirmLogout.MessageFormat", comment: "Account tab: Confirm logout alert") static let logoutButton = NSLocalizedString("AccountTab.ConfirmLogout.Logout", comment: "Account tab: Confirm logout alert: Logout (Ok) button") } // MARK: - class AccountViewController: FormViewController { // MARK: - Constants private let webAppUrl = URL.init(string: "https://msg.adamant.im") // MARK: - Rows & Sections private enum Sections { case account case wallet case actions var localized: String { switch self { case .account: return NSLocalizedString("AccountTab.Section.Account", comment: "Account tab: Account section title.") case .wallet: return NSLocalizedString("AccountTab.Section.Wallet", comment: "Account tab: Wallet section title") case .actions: return NSLocalizedString("AccountTab.Section.Actions", comment: "Account tab: Actions section title") } } } private enum Rows { case account case balance case sendTokens case invest case logout case freeTokens var tag: String { switch self { case .account: return "acc" case .balance: return "balance" case .sendTokens: return "sendTokens" case .invest: return "invest" case .logout: return "logout" case .freeTokens: return "frrtkns" } } var localized: String { switch self { case .account: return "" case .balance: return NSLocalizedString("AccountTab.Row.Balance", comment: "Account tab: Balance row title") case .sendTokens: return NSLocalizedString("AccountTab.Row.SendTokens", comment: "Account tab: 'Send tokens' button") case .invest: return NSLocalizedString("AccountTab.Row.JoinIco", comment: "Account tab: 'Join the ICO' button") case .logout: return NSLocalizedString("AccountTab.Row.Logout", comment: "Account tab: 'Logout' button") case .freeTokens: return NSLocalizedString("AccountTab.Row.FreeTokens", comment: "Account tab: 'Get free tokens' button") } } } // MARK: - Dependencies var accountService: AccountService! var dialogService: DialogService! var router: Router! // MARK: - Properties var hideFreeTokensRow = false private lazy var refreshControl: UIRefreshControl = { let refreshControl = UIRefreshControl() refreshControl.addTarget(self, action: #selector(AccountViewController.handleRefresh(_:)), for: UIControlEvents.valueChanged) refreshControl.tintColor = UIColor.adamantPrimary return refreshControl }() // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() navigationItem.title = String.adamantLocalized.account.title navigationOptions = .Disabled self.tableView.addSubview(self.refreshControl) // MARK: Account Section form +++ Section(Sections.account.localized) <<< AccountRow() { $0.tag = Rows.account.tag $0.cell.height = {65} } .cellUpdate({ [weak self] (cell, row) in cell.avatarImageView.tintColor = UIColor.adamantChatIcons if let label = cell.addressLabel { label.font = UIFont.adamantPrimary(size: 17) label.textColor = UIColor.adamantPrimary } row.value = self?.accountService.account?.address cell.accessoryType = .disclosureIndicator }) .onCellSelection({ [weak self] (_, row) in guard let address = self?.accountService.account?.address else { return } let encodedAddress = AdamantUriTools.encode(request: AdamantUri.address(address: address, params: nil)) self?.dialogService.presentShareAlertFor(string: encodedAddress, types: [.copyToPasteboard, .share, .generateQr(sharingTip: address)], excludedActivityTypes: ShareContentType.address.excludedActivityTypes, animated: true, completion: { guard let indexPath = row.indexPath else { return } self?.tableView.deselectRow(at: indexPath, animated: true) }) }) // MARK: Wallet section +++ Section(Sections.wallet.localized) // MARK: Balance <<< LabelRow() { [weak self] in $0.tag = Rows.balance.tag $0.title = Rows.balance.localized if let balance = self?.accountService?.account?.balance { $0.value = AdamantUtilities.format(balance: balance) } } .cellSetup({ (cell, _) in cell.selectionStyle = .gray }) .cellUpdate({ (cell, _) in if let label = cell.textLabel { label.font = UIFont.adamantPrimary(size: 17) label.textColor = UIColor.adamantPrimary } cell.accessoryType = .disclosureIndicator }) .onCellSelection({ [weak self] (_, _) in guard let vc = self?.router.get(scene: AdamantScene.Transactions.transactions), let nav = self?.navigationController else { return } nav.pushViewController(vc, animated: true) }) // MARK: Send tokens <<< LabelRow() { $0.tag = Rows.sendTokens.tag $0.title = Rows.sendTokens.localized } .cellSetup({ (cell, _) in cell.selectionStyle = .gray }) .cellUpdate({ (cell, _) in if let label = cell.textLabel { label.font = UIFont.adamantPrimary(size: 17) label.textColor = UIColor.adamantPrimary } cell.accessoryType = .disclosureIndicator }) .onCellSelection({ [weak self] (_, row) in let alert = UIAlertController(title: String.adamantLocalized.account.sorryAlert, message: String.adamantLocalized.account.transferNotAllowed, preferredStyle: .alert) let cancel = UIAlertAction(title: String.adamantLocalized.alert.cancel, style: .cancel) { _ in guard let indexPath = row.indexPath else { return } self?.tableView.deselectRow(at: indexPath, animated: true) } alert.addAction(cancel) if let url = self?.webAppUrl { let webApp = UIAlertAction(title: String.adamantLocalized.account.webApp, style: .default) { [weak self] _ in let safari = SFSafariViewController(url: url) safari.preferredControlTintColor = UIColor.adamantPrimary self?.present(safari, animated: true, completion: nil) } alert.addAction(webApp) } self?.present(alert, animated: true, completion: nil) }) // MARK: ICO <<< LabelRow() { $0.tag = Rows.invest.tag $0.title = Rows.invest.localized } .cellSetup({ (cell, _) in cell.selectionStyle = .gray }) .cellUpdate({ (cell, _) in if let label = cell.textLabel { label.font = UIFont.adamantPrimary(size: 17) label.textColor = UIColor.adamantPrimary } cell.accessoryType = .disclosureIndicator }) .onCellSelection({ [weak self] (_, _) in guard let address = self?.accountService.account?.address, let url = URL(string: String.localizedStringWithFormat(String.adamantLocalized.account.joinIcoUrlFormat, address)) else { return } let safari = SFSafariViewController(url: url) safari.preferredControlTintColor = UIColor.adamantPrimary self?.present(safari, animated: true, completion: nil) }) // MARK: Free Tokens <<< LabelRow() { $0.tag = Rows.freeTokens.tag $0.title = Rows.freeTokens.localized $0.hidden = Condition.function([], { [weak self] _ -> Bool in guard let hideFreeTokensRow = self?.hideFreeTokensRow else { return true } return hideFreeTokensRow }) } .cellSetup({ (cell, _) in cell.selectionStyle = .gray }) .cellUpdate({ (cell, _) in if let label = cell.textLabel { label.font = UIFont.adamantPrimary(size: 17) label.textColor = UIColor.adamantPrimary } cell.accessoryType = .disclosureIndicator }) .onCellSelection({ [weak self] (_, _) in guard let address = self?.accountService.account?.address, let url = URL(string: String.localizedStringWithFormat(String.adamantLocalized.account.getFreeTokensUrlFormat, address)) else { return } let safari = SFSafariViewController(url: url) safari.preferredControlTintColor = UIColor.adamantPrimary self?.present(safari, animated: true, completion: nil) }) // MARK: Actions section +++ Section(Sections.actions.localized) <<< LabelRow() { $0.tag = Rows.logout.tag $0.title = Rows.logout.localized } .cellSetup({ (cell, _) in cell.selectionStyle = .gray }) .cellUpdate({ (cell, _) in if let label = cell.textLabel { label.font = UIFont.adamantPrimary(size: 17) label.textColor = UIColor.adamantPrimary } cell.accessoryType = .disclosureIndicator }) .onCellSelection({ [weak self] (_, row) in guard let address = self?.accountService.account?.address else { return } let alert = UIAlertController(title: String.localizedStringWithFormat(String.adamantLocalized.alert.logoutMessageFormat, address), message: nil, preferredStyle: .alert) let cancel = UIAlertAction(title: String.adamantLocalized.alert.cancel, style: .cancel) { _ in guard let indexPath = row.indexPath else { return } self?.tableView.deselectRow(at: indexPath, animated: true) } let logout = UIAlertAction(title: String.adamantLocalized.alert.logoutButton, style: .default) { [weak self] _ in self?.accountService.logout() if let vc = self?.router.get(scene: AdamantScene.Login.login) { self?.dialogService.present(vc, animated: true, completion: nil) } } alert.addAction(cancel) alert.addAction(logout) self?.present(alert, animated: true, completion: nil) }) // MARK: Notifications NotificationCenter.default.addObserver(forName: Notification.Name.AdamantAccountService.userLoggedIn, object: nil, queue: OperationQueue.main) { [weak self] _ in self?.refreshBalanceCell() } NotificationCenter.default.addObserver(forName: Notification.Name.AdamantAccountService.userLoggedOut, object: nil, queue: OperationQueue.main) { [weak self] _ in self?.refreshBalanceCell() } NotificationCenter.default.addObserver(forName: Notification.Name.AdamantAccountService.accountDataUpdated, object: nil, queue: OperationQueue.main) { [weak self] _ in self?.refreshBalanceCell() } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if let indexPath = tableView.indexPathForSelectedRow { tableView.deselectRow(at: indexPath, animated: animated) } } deinit { NotificationCenter.default.removeObserver(self) } } // MARK: - Other extension AccountViewController { private func refreshBalanceCell() { let address: String? let balance: String? if let account = accountService.account { address = account.address balance = AdamantUtilities.format(balance: account.balance) hideFreeTokensRow = account.balance > 0 } else { address = nil balance = nil hideFreeTokensRow = true } if let row: AccountRow = form.rowBy(tag: Rows.account.tag) { row.value = address row.reload() } if let row: LabelRow = form.rowBy(tag: Rows.balance.tag) { row.value = balance row.reload() } if let row: LabelRow = form.rowBy(tag: Rows.freeTokens.tag) { row.evaluateHidden() } } @objc private func handleRefresh(_ refreshControl: UIRefreshControl) { accountService.update { [weak self] (result) in switch result { case .success: guard let tableView = self?.tableView else { break } DispatchQueue.main.async { tableView.reloadData() } case .failure(let error): self?.dialogService.showRichError(error: error) } DispatchQueue.main.async { refreshControl.endRefreshing() } } } }
// // ClassificationService.swift // ImageClassifier // // Created by Illya Sirosh on 16.01.2021. // import Foundation import UIKit import CoreML import Vision class ClassificationService: ObservableObject { let model: MLModel @Published var result: ClassificationResult? init(with model: MLModel){ self.model = model } func proccess(image: UIImage) { guard let ciImage = CIImage(image: image) else { result = .unrecognized return } DispatchQueue.global(qos: .userInitiated).async { let handler = VNImageRequestHandler(ciImage: ciImage) do { let request = try self.getRequest() try handler.perform([request]) } catch { self.setResultSafe(.unrecognized) } } result = .proccessing } private func getRequest() throws -> VNCoreMLRequest { guard let visionModel = try? VNCoreMLModel(for: model) else { throw ServiceError.cannotConvertModel } let request = VNCoreMLRequest(model: visionModel, completionHandler: { [weak self] request, error in self?.processClassifications(for: request, error: error) }) return request } private func processClassifications(for request: VNRequest, error: Error?) { guard let results = request.results else { self.setResultSafe(.unrecognized) return } let classifications = results as! [VNClassificationObservation] if let mostPossibleClassification = classifications.first { let title = self.extractFirstTitle(from: mostPossibleClassification.identifier) self.setResultSafe(.recognized(title)) } } private func extractFirstTitle(from string: String) -> String { return String(string.split(separator: ",").first ?? "") } private func setResultSafe(_ result: ClassificationResult) { DispatchQueue.main.async { self.result = result } } } extension ClassificationService { enum ServiceError: Error { case cannotConvertModel } }
// // PhotoGridEnums.swift // Carmen Grid // // Created by Abbey Jackson on 2019-04-08. // Copyright © 2019 Abbey Jackson. All rights reserved. // import UIKit extension PhotoGrid { enum GridColor: Int { case white, black, red, blue var color: CGColor { switch self { case .white: return UIColor.white.cgColor case .black: return UIColor.black.cgColor case .red: return UIColor.red.cgColor case .blue: return UIColor.blue.cgColor } } } enum GridType: Int { case none, squares, triangles, smallTriangles var numberOfColumns: Int { switch self { case .triangles, .squares: return 4 case .smallTriangles: return GridType.triangles.numberOfColumns * 2 default: return 0 } } } }
// // ListTableViewController.swift // TodoList // // Created by Corey Harrilal on 11/21/16. // Copyright © 2016 coreyarchharrilal. All rights reserved. // import UIKit class ListTableViewController: UITableViewController, AddStuffViewControllerDelegate, viewStuffViewControllerDelegate{ var stuffArray: [Stuff] = [] override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return stuffArray.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "ListTableViewCell") as! ListTableViewCell let stuff = stuffArray[indexPath.row] cell.stuff = stuff if stuff.buttonStatus == .NotDone{ cell.checkStatusButton.setImage(UIImage(named: "uncheckbox"), for: UIControlState.normal) } else if stuff.buttonStatus == .Done{ cell.checkStatusButton.setImage(UIImage(named: "checkbox"), for: UIControlState.normal) cell.deadLineLabel.text = "You are done here!" } return cell } override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { let done = UITableViewRowAction(style: .default, title: "Done", handler: { (action, indexPath) -> Void in // find stuff from index path // let stuffItem = self.stuffArray[indexPath.row] self.updateStuffDone(stuff: stuffItem, status: true) print("Done") }) let undone = UITableViewRowAction(style: .default, title: "Un-Done", handler: {(action, indexPath) -> Void in // let stuffItem = self.stuffArray[indexPath.row] self.updateStuffDone(stuff: stuffItem, status: true) print("un-done") }) return [done, undone] } //Conforms to the delegate protocol in AddStuffViewController func addStuff(stuff: Stuff){ stuffArray.append(stuff)//Updates the model tableView.reloadData() //Updates the view } //Conforms to the delegate protocol in ViewStuffViewController func deleteStuff(stuff: Stuff){ for (n , c) in stuffArray.enumerated(){ if c === stuff{ stuffArray.remove(at: n) } } tableView.reloadData() } //Conforms to the delegate protocol in ViewStuffViewController func updateStuffDone(stuff: Stuff, status: Bool){ for (n , c) in stuffArray.enumerated(){ if c === stuff{ if status == true{ stuffArray[n].buttonStatus = .Done } else if status == false{ stuffArray[n].buttonStatus = .NotDone } } } tableView.reloadData() } //Conforms to the delegate protocol in ListViewCell func updateTableView() { tableView.reloadData() } //Provides the value of the delegate (self) for the delegator class (AddStuffViewController) override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "AddStuffViewController"{ let addStuffViewController = segue.destination as! AddStuffViewController addStuffViewController.delegate = self } if segue.identifier == "ViewStuffViewController" { if let indexPath = tableView.indexPathForSelectedRow, let stuff = stuffArray[indexPath.row] as? Stuff { let destinationViewController = segue.destination as! ViewStuffViewController destinationViewController.delegate = self destinationViewController.stuffItem = stuff destinationViewController.stuffTitle = stuff.title destinationViewController.stuffDeadLine = stuff.deadline } } } //MARK:Implement code to tap on a stuff item and view it singularly func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { // Perform Segue performSegue(withIdentifier: "ViewStuffViewController", sender: self) tableView.deselectRow(at: indexPath as IndexPath, animated: true) } }
// // RequestsTableViewCell.swift // Bombchat // // Created by Mohaned Al-Feky on 7/27/18. // Copyright © 2018 mohaned. All rights reserved. // import UIKit class RequestsTableViewCell: UITableViewCell { @IBOutlet weak var label: UILabel! @IBOutlet weak var acceptButton: UIButton! @IBOutlet weak var rejectButton: UIButton! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
// // FeedViewController.swift // LocalReads // // Created by Tong Lin on 2/18/17. // Copyright © 2017 C4Q-3.2. All rights reserved. // import UIKit import SnapKit import FirebaseDatabase import FirebaseStorage class FeedViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { var allPosts: [Post] = [] { didSet { if let library = FeedViewController.libraryToFilterBy { self.filteredPosts = allPosts.filter { $0.libraryName == library.name } navigationItem.title = library.name } else { self.filteredPosts = allPosts navigationItem.title = "All Queens Libraries" } } } var filteredPosts: [Post] = [] { didSet { self.tableView.reloadData() } } static var libraryToFilterBy: Library? var databaseReference: FIRDatabaseReference! override func viewDidLoad() { super.viewDidLoad() self.databaseReference = FIRDatabase.database().reference().child("posts") setNavBar() setupViews() setConstraints() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) fetchPosts() if let library = FeedViewController.libraryToFilterBy { navigationItem.title = library.name } else { } } // MARK: - Setup func setNavBar() { self.navigationController?.navigationBar.tintColor = ColorManager.shared.accent let filterButton = UIBarButtonItem(image: #imageLiteral(resourceName: "filterIcon"), style: .done, target: self, action: #selector(libraryFilterTapped)) // let filterButton = UIBarButtonItem(title: "Library Filter", style: .done, target: self, action: #selector(libraryFilterTapped)) self.navigationItem.rightBarButtonItem = filterButton } func setupViews() { self.view.addSubview(tableView) self.tableView.register(UINib(nibName: "PostTableViewCell", bundle: nil), forCellReuseIdentifier: "postCellIdentifyer") self.tableView.addSubview(self.refreshControl) self.tableView.backgroundColor = ColorManager.shared.primaryLight self.tableView.delegate = self self.tableView.dataSource = self self.tableView.estimatedRowHeight = 200 self.tableView.rowHeight = UITableViewAutomaticDimension self.tableView.separatorStyle = .none self.view.addSubview(floatingButton) } func setConstraints() { self.edgesForExtendedLayout = [] tableView.snp.makeConstraints { (view) in view.top.bottom.leading.trailing.equalToSuperview() } floatingButton.snp.makeConstraints { (view) in view.width.height.equalTo(54) view.trailing.bottom.equalToSuperview().offset(-20) } } // MARK: - Posts func fetchPosts() { databaseReference.observe(.value, with: { (snapshot) in var fetchedPosts: [Post] = [] for child in snapshot.children { if let snap = child as? FIRDataSnapshot, let valueDict = snap.value as? [String: AnyObject] { if let post = Post(from: valueDict, key: snap.key) { fetchedPosts.append(post) } } } self.allPosts = fetchedPosts.reversed() }) } //MARK: - Tableview delegates/datasource func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return filteredPosts.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "postCellIdentifyer", for: indexPath) as! PostTableViewCell let post = filteredPosts[indexPath.row] cell.usernameLabel.text = post.userName cell.bookTitileLabel.text = post.bookTitle cell.bookAuthorLabel.text = "by: \(post.bookAuthor)" cell.libraryNameLabel.text = "Library: \(post.libraryName)" cell.rating(post.userRating) cell.userCommentLabel.text = post.userComment cell.bookCoverImageView.image = nil cell.coverLoadActivityIndicator.hidesWhenStopped = true cell.coverLoadActivityIndicator.startAnimating() APIRequestManager.manager.getData(endPoint: post.bookImageURL) { (data) in if let data = data { DispatchQueue.main.async { cell.bookCoverImageView.image = UIImage(data: data) cell.coverLoadActivityIndicator.stopAnimating() cell.setNeedsLayout() } } } cell.userProfileImageView.image = nil let storageReference: FIRStorageReference = FIRStorage.storage().reference(forURL: "gs://localreads-8eb86.appspot.com/") let spaceRef = storageReference.child("profileImages/\(post.userID)") spaceRef.data(withMaxSize: 1 * 1024 * 1024) { data, error in if let error = error { print(error) } else { let image = UIImage(data: data!) cell.userProfileImageView.image = image } } return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let post = filteredPosts[indexPath.row] let profileVC = ProfileViewController() profileVC.viewType = .vistor profileVC.profileUserID = post.userID navigationItem.backBarButtonItem = UIBarButtonItem(title:"", style:.plain, target:nil, action:nil) navigationController?.pushViewController(profileVC, animated: true) } // Actions func libraryFilterTapped() { let libraryVC = LibraryFilterViewController() libraryVC.viewStyle = .fromFeed navigationItem.backBarButtonItem = UIBarButtonItem(title:"", style:.plain, target:nil, action:nil) navigationController?.pushViewController(libraryVC, animated: true) } func handleRefresh(_ refreshControl: UIRefreshControl) { fetchPosts() refreshControl.endRefreshing() } func floatingButtonClicked(sender: UIButton) { let newTransform = CGAffineTransform(scaleX: 1.1, y: 1.1) let originalTransform = sender.imageView!.transform UIView.animate(withDuration: 0.1, animations: { sender.layer.transform = CATransform3DMakeAffineTransform(newTransform) }, completion: { (complete) in sender.layer.transform = CATransform3DMakeAffineTransform(originalTransform) }) present(AddPostViewController(), animated: true, completion: nil) } // Lazy vars internal lazy var floatingButton: UIButton = { let button = UIButton(type: .custom) button.addTarget(self, action: #selector(floatingButtonClicked(sender:)), for: UIControlEvents.touchUpInside) button.setImage(UIImage(named: "plus_symbol")!, for: .normal) button.backgroundColor = ColorManager.shared.accent button.layer.cornerRadius = 26 button.layer.shadowColor = UIColor.black.cgColor button.layer.shadowOpacity = 0.8 button.layer.shadowOffset = CGSize(width: 0, height: 5) button.layer.shadowRadius = 5 button.clipsToBounds = false return button }() lazy var tableView: UITableView = { let view = UITableView() return view }() lazy var refreshControl: UIRefreshControl = { let refreshControl = UIRefreshControl() refreshControl.addTarget(self, action: #selector(self.handleRefresh(_:)), for: UIControlEvents.valueChanged) return refreshControl }() }
import UIKit var str = "Hello, playground" // Question 1 let pi = 3.14159265 let fullName = "Christopher Tyler Averette" print("\t \n \n \" ") //Question 2 func seven() -> Int {return 7} func disney() -> String {return "Goofy"} // Question 3 func min(num1 n1: Int, num2 n2: Int) -> Int { if n1 < n2{ return n1} else {return n2} } min(num1: 50, num2: 10) func compose(strings s1: String, _ s2: String) -> String{ return ("\(s1) \(s2)") } //Question 4 func median(_ num1: Int,_ num2: Int,_ num3: Int) -> Int{ if num1 >= num2 && num1 <= num3 || num1 >= num3 && num1 <= num2 { return num1 } else if num1 <= num2 && num2 <= num3 || num1 >= num2 && num2 >= num3{ return num2 } else{ return num3 } } median(6, 4, 5) median(43, 88, 55) median(12, 22, 16) // Question 5 compose(strings: "first", "second") func isLeap(_ year: Int) -> Bool{ var leapYear: Bool = false if year % 4 == 0{ if year % 100 != 0{ leapYear = true } else if year % 400 == 0{ leapYear = true } } return leapYear } isLeap(1600) // true isLeap(1700) // false isLeap(2000) // true isLeap(2004) // true isLeap(2019) // false isLeap(2100) // false
// // TabBarAppViewModel.swift // BookSeeker // // Created by Edwy Lugo on 28/06/20. // Copyright © 2020 CIT. All rights reserved. // import Foundation protocol TabBarAppNavigationProtocol: AnyObject {} protocol TabBarAppViewModelProtocol {} struct TabBarAppViewModel { private var navigationDelegate: TabBarAppNavigationProtocol init(navigationDelegate: TabBarAppNavigationProtocol) { self.navigationDelegate = navigationDelegate } }
// // AppPreference.swift // TemplateSwiftAPP // // Created by wenhua on 2018/9/1. // Copyright © 2018年 wenhua yu. All rights reserved. // import Foundation class AppPreference: NSObject { /// 账户 var account: String = "" var password: String = "" /// 配置 var isFirstOpen: Bool = false var isLoginSuccess: Bool = false /// token var token: String = "" }
// // StartUps.swift // Elshams // // Created by mac on 12/3/18. // Copyright © 2018 mac. All rights reserved. // import UIKit import XLPagerTabStrip //import AlamofireImage import Alamofire import SwiftyJSON class StartUps: BaseViewController , UITableViewDelegate , UITableViewDataSource { var startUpList = Array<StartUpsData>() var startUpListPaging = Array<StartUpsData>() @IBOutlet weak var noDataErrorContainer: UIView! @IBOutlet weak var startupTableView: UITableView! var availableAppointmentList = Array<AvailableAppointment>() @IBOutlet weak var activeLoader: UIActivityIndicatorView! override func viewDidLoad() { super.viewDidLoad() if MenuViewController.startupEventOrMenu == true { addSlideMenuButton() // btnRightBar() self.navigationItem.title = "Startups" MenuViewController.startupEventOrMenu = false } startupTableView.isHidden = true activeLoader.startAnimating() noDataErrorContainer.isHidden = true NotificationCenter.default.addObserver(self, selector: #selector(errorAlert), name: NSNotification.Name("ErrorConnections"), object: nil) // loadAllStartUpData() } override func viewWillAppear(_ animated: Bool) { UIApplication.shared.isStatusBarHidden = false loadAllStartUpData() // self.startupTableView.reloadData() } @objc func errorAlert(){ let alert = UIAlertController(title: "Error!", message: Service.errorConnection, preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) startupTableView.isHidden = true activeLoader.isHidden = true activeLoader.stopAnimating() //reload after // } func loadAllStartUpData() { startUpList.removeAll() startUpListPaging.removeAll() self.startupTableView.reloadData() startupTableView.isHidden = true activeLoader.startAnimating() if let apiToken = Helper.getApiToken() { Service.getServiceWithAuth(url: URLs.getAllStartups) { //WithAuth (response) in print(response) let json = JSON(response) let result = json["AllStartups"] if !(result.isEmpty){ var iDNotNull = true var index = 0 while iDNotNull { let startUp_ID = result[index]["id"].string let startUp_Name = result[index]["startupName"].string let startUp_RankNo = result[index]["rankNo"].string let startUp_Appoimentstatus = result[index]["appoimentstatus"].string let startUp_AppoimentTime = result[index]["AppoimentTime"].string let startUp_ImageUrl = result[index]["imageURl"].string let startUp_About = result[index]["about"].string let startUp_ContectInforamtion = result[index]["ContectInforamtion"].dictionaryObject let startUp_Email = result[index]["ContectInforamtion"]["Email"].string let startUp_Linkedin = result[index]["ContectInforamtion"]["linkedin"].string let startUp_Phone = result[index]["ContectInforamtion"]["phone"].string let contect = ["Email": "","linkedin": "","phone": ""] if startUp_ID == nil || startUp_ID?.trimmingCharacters(in: .whitespacesAndNewlines) == "" || startUp_ID == "null" || startUp_ID == "nil" { iDNotNull = false break } self.startUpListPaging.append(StartUpsData(StartupName: startUp_Name ?? "", StartupID: startUp_ID ?? "", StartupImageURL: startUp_ImageUrl ?? "", StartUpAbout: startUp_About ?? "", AppoimentStatus: startUp_Appoimentstatus ?? "", AppoimentTime: startUp_AppoimentTime ?? "", ContectInforamtion: startUp_ContectInforamtion ?? contect, StartupOrder: startUp_RankNo ?? "")) if index <= 10 { self.startUpList.append(StartUpsData(StartupName: startUp_Name ?? "", StartupID: startUp_ID ?? "", StartupImageURL: startUp_ImageUrl ?? "", StartUpAbout: startUp_About ?? "", AppoimentStatus: startUp_Appoimentstatus ?? "", AppoimentTime: startUp_AppoimentTime ?? "", ContectInforamtion: startUp_ContectInforamtion ?? contect, StartupOrder: startUp_RankNo ?? "")) } index = index + 1 } self.startupTableView.reloadData() self.activeLoader.isHidden = true self.activeLoader.stopAnimating() self.startupTableView.isHidden = false self.noDataErrorContainer.isHidden = true } else { self.noDataErrorContainer.isHidden = false let alert = UIAlertController(title: "No Data", message: "No Data found till now", preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) self.activeLoader.isHidden = true } } } else { Service.getService(url: URLs.getAllStartups) { //WithAuth (response) in print(response) let json = JSON(response) let result = json["AllStartups"] if !(result.isEmpty){ var iDNotNull = true var index = 0 while iDNotNull { let startUp_ID = result[index]["id"].string let startUp_Name = result[index]["startupName"].string let startUp_RankNo = result[index]["rankNo"].string let startUp_Appoimentstatus = result[index]["appoimentstatus"].string let startUp_AppoimentTime = result[index]["AppoimentTime"].string let startUp_ImageUrl = result[index]["imageURl"].string let startUp_About = result[index]["about"].string let startUp_ContectInforamtion = result[index]["ContectInforamtion"].dictionaryObject let startUp_Email = result[index]["ContectInforamtion"]["Email"].string let startUp_Linkedin = result[index]["ContectInforamtion"]["linkedin"].string let startUp_Phone = result[index]["ContectInforamtion"]["phone"].string let contect = ["Email": "", "linkedin": "", "phone": ""] if startUp_ID == nil || startUp_ID?.trimmingCharacters(in: .whitespacesAndNewlines) == "" || startUp_ID == "null" || startUp_ID == "nil" { iDNotNull = false break } self.startUpListPaging.append(StartUpsData(StartupName: startUp_Name ?? "", StartupID: startUp_ID ?? "", StartupImageURL: startUp_ImageUrl ?? "", StartUpAbout: startUp_About ?? "", AppoimentStatus: startUp_Appoimentstatus ?? "", AppoimentTime: startUp_AppoimentTime ?? "", ContectInforamtion: startUp_ContectInforamtion ?? contect, StartupOrder: startUp_RankNo ?? "")) if index <= 10 { self.startUpList.append(StartUpsData(StartupName: startUp_Name ?? "", StartupID: startUp_ID ?? "", StartupImageURL: startUp_ImageUrl ?? "", StartUpAbout: startUp_About ?? "", AppoimentStatus: startUp_Appoimentstatus ?? "", AppoimentTime: startUp_AppoimentTime ?? "", ContectInforamtion: startUp_ContectInforamtion ?? contect, StartupOrder: startUp_RankNo ?? "")) } index = index + 1 } self.startupTableView.reloadData() self.activeLoader.isHidden = true self.activeLoader.stopAnimating() self.startupTableView.isHidden = false self.noDataErrorContainer.isHidden = true } else { self.noDataErrorContainer.isHidden = false let alert = UIAlertController(title: "No Data", message: "No Data found till now", preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) self.activeLoader.isHidden = true } } } } func btnRightBar() { // let btnSearch = UIButton(type: UIButton.ButtonType.system) let btnSearch = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.search, target: nil, action: #selector(searchTool)) // btnSearch.setImage(UIImage(named: "fav_resic"), for: UIControl.State()) // btnSearch.frame = CGRect(x: 0, y: 0, width: 30, height: 30) // btnSearch.addTarget(self, action: #selector(searchTool), for: UIControl.Event.touchUpInside) // btnSearch.ba // let customBarItem = UIBarButtonItem(customView: btnSearch) // self.navigationItem.rightBarButtonItem = customBarItem; self.navigationItem.rightBarButtonItem = btnSearch; } @objc func searchTool() { print("gooooood") } @IBAction func btnSechaduale(_ sender: Any) { let buttonPosition:CGPoint = (sender as AnyObject).convert(CGPoint.zero, to:self.startupTableView) var indexPath = self.startupTableView.indexPathForRow(at: buttonPosition) // StartupDetailsVC.sechadualeBTNSend = true let startUpId = (startUpList[indexPath!.row].startup_id)! print(startUpId) Service.getServiceWithAuth(url: "\(URLs.getAvaliableAppoiments)/\(startUpId)") { (response) in print("this is SessionDetails ") print(response) let result = JSON(response) var iDNotNull = true var index = 0 var availableAppointmentListCount = 0 while iDNotNull { let avaAppointment_ID = result[index]["appoimentID"].string if avaAppointment_ID == nil || avaAppointment_ID?.trimmed == "" || avaAppointment_ID == "null" || avaAppointment_ID == "nil"{ iDNotNull = false // self.popUpViewMethod() break } let avaAppointment = result[index].dictionaryObject let avaAppointment_Name = result[index]["appoimentName"].string let avaAppointmentOptinal = ["appoimentName": "", "appoimentID": ""] self.availableAppointmentList.append(AvailableAppointment(AvailableAppointmentDict: avaAppointment ?? avaAppointmentOptinal, AppoimentName: avaAppointment_Name ?? "name", AppoimentID: avaAppointment_ID ?? "id")) index = index + 1 availableAppointmentListCount = self.availableAppointmentList.count } if availableAppointmentListCount != 0 { StartupDetailsVC.sechadualeBTNSend = true self.performSegue(withIdentifier: "startupdetail", sender: self.startUpList[indexPath!.row]) } else { let alert = UIAlertController(title: "Error!", message: "There's no Available Appointments", preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) } } } func loadNewItems(){ let lastindex = startUpList.count - 1 for i in 1 ..< 5 { let lastItem = startUpList.last let lastIt = lastindex + i if lastIt != startUpListPaging.count { let newItem = startUpListPaging[lastIt] startUpList.append(newItem) startupTableView.reloadData() } else { print("that's end") break } } } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { let lastItem = startUpList.count - 1 if indexPath.row == lastItem { loadNewItems() } } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return startUpList.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "startupcell", for: indexPath) as! StartUpsCell cell.setStartupCell(startupsList: startUpList[indexPath.row]) return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 80.0 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) performSegue(withIdentifier: "startupdetail", sender: startUpList[indexPath.row]) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let dis = segue.destination as? StartupDetailsVC { if let favDetail = sender as? StartUpsData { dis.singleItem = favDetail } } } } extension StartUps : IndicatorInfoProvider { func indicatorInfo(for pagerTabStripController: PagerTabStripViewController) -> IndicatorInfo { return IndicatorInfo(title: "Startup") } }
// // HapticFeedbackView.swift // HapticFeedback // // Created by Anton Paliakou on 8/6/21. // import SwiftUI struct HapticFeedbackView: View { var body: some View { VStack(spacing: 48) { VStack(spacing: 16) { Text("UIImpactFeedbackGenerator:") .font(.title3) Button(action: { impactFeedback(.heavy) }) { Text("Heavy") } Button(action: { impactFeedback(.light) }) { Text("Light") } Button(action: { impactFeedback(.medium) }) { Text("Medium") } Button(action: { impactFeedback(.rigid) }) { Text("Rigid") } Button(action: { impactFeedback(.soft) }) { Text("Soft") } } VStack(spacing: 16) { Text("UINotificationFeedbackGenerator:") .font(.title3) Button(action: { notificationFeedback(.error) }) { Text("Error") } Button(action: { notificationFeedback(.success) }) { Text("Success") } Button(action: { notificationFeedback(.warning) }) { Text("Warning") } } VStack(spacing: 16) { Text("UISelectionFeedbackGenerator:") .font(.title3) Button(action: { selectionFeedback() }) { Text("SelectionChanged") } } } } // MARK: - UIImpactFeedbackGenerator private func impactFeedback(_ style: UIImpactFeedbackGenerator.FeedbackStyle) { let impactFeedback = UIImpactFeedbackGenerator(style: style) impactFeedback.prepare() impactFeedback.impactOccurred() } // MARK: - UINotificationFeedbackGenerator private func notificationFeedback(_ feedbackType: UINotificationFeedbackGenerator.FeedbackType) { let notificationFeedback = UINotificationFeedbackGenerator() notificationFeedback.prepare() notificationFeedback.notificationOccurred(feedbackType) } // MARK: - UISelectionFeedbackGenerator private func selectionFeedback() { let selectionFeedback = UISelectionFeedbackGenerator() selectionFeedback.selectionChanged() } }
// // GroupTabBarViewModel.swift // Quota // // Created by Marcin Włoczko on 24/11/2018. // Copyright © 2018 Marcin Włoczko. All rights reserved. // import UIKit import RxSwift import RxCocoa protocol GroupTabBarViewModelDelegate: class { func groupTabBarViewModelDidTapAddExpense() } protocol GroupTabBarViewModel: class { var delegate: GroupTabBarViewModelDelegate? { get set } var expensesTitle: String { get } var membersTitle: String { get } var expensesAsset: String { get } var membersAsset: String { get } var addExpenseTitle: String { get } var addExpenseAction: PublishRelay<Void> { get } } final class GroupTabBarViewModelImp: GroupTabBarViewModel { // MARK: - View's constants let expensesTitle: String = "expenses".localized let membersTitle: String = "members".localized let expensesAsset: String = "expenses" let membersAsset: String = "members" let addExpenseTitle: String = "add" // MARK: - Observers let addExpenseAction = PublishRelay<Void>() // MARK: - Delegate weak var delegate: GroupTabBarViewModelDelegate? // MARK: - Constants private let disposeBag = DisposeBag() // MARK: - Initializer init() { setupBinding() } // MARK: - Setup private func setupBinding() { addExpenseAction.subscribe(onNext: { [weak self] in self?.delegate?.groupTabBarViewModelDidTapAddExpense() }).disposed(by: disposeBag) } }
// // TreatmentOptionsViewController.swift // Junior_Design_Final_Deliverable // // Created by Daham Eom on 2018. 2. 13.. // Copyright © 2018년 TeamHeavyw8. All rights reserved. // import UIKit import CoreData class TreatmentOptionsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { var taken = false var mostOne: [String] = ["Boniva prescription"] var treatmentList: [String] = ["Reclast Infusion", "Kyphoplasty Surgery"] //var mostOne = [String]() var treatment: String? @IBOutlet weak var mostOneTable: UITableView! @IBOutlet weak var restTable: UITableView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. //setList() //splitList() if !self.taken { mostOne = [] treatmentList = [] } mostOneTable.dataSource = self mostOneTable.delegate = self mostOneTable.register(UITableViewCell.self, forCellReuseIdentifier: "cell") restTable.dataSource = self restTable.delegate = self restTable.register(UITableViewCell.self, forCellReuseIdentifier: "cell1") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { var count:Int? if tableView == self.mostOneTable { count = 1 } if tableView == self.restTable { count = treatmentList.count } return count! } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // if tableView == self.mostOneTable { // cell = self.mostOneTable.dequeueReusableCell(withIdentifier: "mostOne", for: IndexPath) // cell.textLabel!.text = mostOne[0] // } var cell:UITableViewCell? if tableView == self.restTable { cell = self.restTable.dequeueReusableCell(withIdentifier: "cell1", for: indexPath) if taken { cell!.textLabel!.text = treatmentList[indexPath.row] } } if tableView == self.mostOneTable { cell = self.mostOneTable.dequeueReusableCell(withIdentifier: "cell", for: indexPath) if taken { cell!.textLabel!.text = mostOne[0] } } //let cell = self.cellTable.dequeueReusableCell(withIdentifier: "cell", for: indexPath) return cell! } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if self.taken { if tableView == self.mostOneTable { tableView.deselectRow(at: indexPath, animated: true) treatment = mostOne[0] performSegue(withIdentifier: "moveToDetail", sender: self) } if tableView == self.restTable { tableView.deselectRow(at: indexPath, animated: true) treatment = treatmentList[indexPath.row] performSegue(withIdentifier: "moveToDetail", sender: self) } } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if (segue.identifier == "moveToDetail") { if let destination = segue.destination as? DetailOptionViewController { //destination.mostOne = self.mostOne destination.others = self.treatmentList destination.treatName = self.treatment destination.mostOne = self.mostOne destination.taken = self.taken } } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.setNavigationBarHidden(true, animated: false) } // Assign treatment options from result view controller to treatmentList // func setList() { // let temp = ResultsViewController() // treatmentList = temp.results // // // Remove "#. " string from each element // for index in (treatmentList?.indices)! { // var tempStr = treatmentList![index] // let ind = tempStr.index(tempStr.startIndex, offsetBy: 3) // tempStr = tempStr.substring(from: ind) // treatmentList![index] = tempStr // } // } // /* // Set the most recommended treatment option and remove it from original list func splitList() { mostOne = [treatmentList[0]] let i = treatmentList.index(of: mostOne[0]) treatmentList.remove(at: i!) }*/ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
// // DetailViewController.swift // Noam News // // Created by Noam Mizrachi on 22/06/2019. // Copyright © 2019 Noam Mizrachi. All rights reserved. // /* ------------------------ Noam Comments ------------------------ 1. This custom class was created for connecting our detail view ('Note' scene) to this custom class, and then connecting the text view of the Note scene to a property of this custom class. In order to modify the text in the 'detail' view (Note scene) inside our code, we created this custom class for this view controller (Note scene). * For connecting our 'Note' view controller to the 'DetailViewController' class we select the view controller object of the 'Note' scene (top left at the bar) and then at the utility area we select the 'identity inspector'. At the 'Class' field we select 'DetailViewController' and now they are connected. 2. Connection between our text view in the 'Note' screen to our detailViewController class. 3. For setting the content of the text view we created a setter. 4. We create an 'masterView' variable of type ViewController that will reference the main (master) view controller of our app. 5. The func viewWillDisappear is for when the detailView is on is way our, that is, returning to the master view, we want to modify (main) view controller on the way in it, using that initial data. 6. Every time view appears, when we call this method it authomaticly brings up the software keyboard to pop up. Generally, this method is executes when this view appears. */ // ------------------------ End Comments ------------------------ import UIKit class DetailViewController: UIViewController { // Properties: @IBOutlet weak var textView: UITextView! // Comment #2 var text: String = "" var masterView: ViewController! // Comment #4 // Methods: override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. textView.text = text self.navigationItem.largeTitleDisplayMode = .never // Detail view controller will never distlay large titles } // Comment #6 override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) textView.becomeFirstResponder() textView.resignFirstResponder() // When returning to the main view controller the keyboard will slide down } // Comment #3 func setText(t: String) { text = t if isViewLoaded { textView.text = t } } // Comment #5 override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) masterView.newRowText = textView.text } }
// // Apparel.swift // Mercari // // Created by Anh Doan on 6/18/17. // Copyright © 2017 Mercari. All rights reserved. // import Foundation struct Apparel { enum SerializationError: Error { case missing(String) } internal var price: String? internal var name: String? internal var status: String? init(price: String, name: String, status: String) { self.price = price self.name = name self.status = status } init(dict: [String: Any]) throws { guard let name = dict["name"] as? String else { throw SerializationError.missing("name") } guard let price = dict["price"] as? Int else { throw SerializationError.missing("price") } guard let status = dict["status"] as? String else { throw SerializationError.missing("status") } self.name = name self.price = "$\(price)" self.status = status } } extension Apparel { // method to parse json in main bundle. static func downloadJson() -> [Apparel] { var apparels = [Apparel]() let jsonPath = Bundle.main.path(forResource: "all", ofType: "json") let jsonURL = URL(fileURLWithPath: jsonPath!) let jsonData = try? Data(contentsOf: jsonURL) if let jsonDict = ParseJsonManager.parseJSONData(data: jsonData) { guard let data = jsonDict["data"] as? [[String: Any]] else { print("data does not exist in json file") return apparels } for d in data { do { let apparel = try Apparel(dict: d) apparels.append(apparel) } catch { print(error) } } } return apparels } // method to request json from web. static func downloadJsonFromAPI(urlString: String) -> [Apparel] { var apparels = [Apparel]() let url = URL(string: urlString) URLSession.shared.dataTask(with: url!) { (data, response, error) in let jsonDict = ParseJsonManager.parseJSONData(data: data) guard let data = jsonDict?["data"] as? [[String: Any]] else { print("data does not exist in json file") return } for d in data { do { let apparel = try Apparel(dict: d) apparels.append(apparel) } catch { print(error) } } }.resume() return apparels } }
// // SceneDelegate.swift // FastBus // // Created by Jonorsky Navarrete on 6/22/20. // Copyright © 2020 Nitrogen. All rights reserved. // import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? }
import SafariServices import SwiftUI struct SafariView: UIViewControllerRepresentable { typealias DidFinishHandler = () -> Void let url: URL private let delegate: SafariViewDelegate? public init(url: URL, didFinishHandler: DidFinishHandler?) { self.url = url delegate = didFinishHandler.map(SafariViewDelegate.init(didFinishHandler:)) } func makeUIViewController(context: UIViewControllerRepresentableContext<SafariView>) -> SFSafariViewController { let safariViewController = SFSafariViewController(url: url) safariViewController.delegate = delegate return safariViewController } func updateUIViewController(_ uiViewController: SFSafariViewController, context: UIViewControllerRepresentableContext<SafariView>) {} } private final class SafariViewDelegate: NSObject, SFSafariViewControllerDelegate { typealias DidFinishHandler = () -> Void private let didFinishHandler: DidFinishHandler init(didFinishHandler: @escaping DidFinishHandler) { self.didFinishHandler = didFinishHandler super.init() } func safariViewControllerDidFinish(_ controller: SFSafariViewController) { didFinishHandler() } }
import Foundation infix operator |> : AdditionPrecedence /// Applies an argument to a 1-ary function. /// /// - Parameters: /// - a: Argument to apply. /// - fun: Function receiving the argument. /// - Returns: Result of running the function with the argument as input. public func |><A, B>(_ a: A, _ fun: (A) -> B) -> B { fun(a) } /// Applies the first argument to a 2-ary function, returning a 1-ary function with the rest of the arguments of the original function. /// /// - Parameters: /// - a: Input to the first argument of the function /// - fun: Function to be applied. /// - Returns: A function with the same behavior of the input function where the first argument is fixed to the value of the provided argument. public func |><A, B, C>(_ a: A, _ fun: @escaping (A, B) -> C) -> (B) -> C { { b in fun(a,b) } } /// Applies the first argument to a 3-ary function, returning a 2-ary function with the rest of the arguments of the original function. /// /// - Parameters: /// - a: Input to the first argument of the function /// - fun: Function to be applied. /// - Returns: A function with the same behavior of the input function where the first argument is fixed to the value of the provided argument. public func |><A, B, C, D>(_ a: A, _ fun: @escaping (A, B, C) -> D) -> (B, C) -> D { { b, c in fun(a, b, c) } } /// Applies the first argument to a 4-ary function, returning a 3-ary function with the rest of the arguments of the original function. /// /// - Parameters: /// - a: Input to the first argument of the function /// - fun: Function to be applied. /// - Returns: A function with the same behavior of the input function where the first argument is fixed to the value of the provided argument. public func |><A, B, C, D, E>(_ a: A, _ fun: @escaping (A, B, C, D) -> E) -> (B, C, D) -> E { { b, c, d in fun(a, b, c, d) } } /// Applies the first argument to a 5-ary function, returning a 4-ary function with the rest of the arguments of the original function. /// /// - Parameters: /// - a: Input to the first argument of the function /// - fun: Function to be applied. /// - Returns: A function with the same behavior of the input function where the first argument is fixed to the value of the provided argument. public func |><A, B, C, D, E, F>(_ a: A, _ fun: @escaping (A, B, C, D, E) -> F) -> (B, C, D, E) -> F { { b, c, d, e in fun(a, b, c, d, e) } } /// Applies the first argument to a 6-ary function, returning a 5-ary function with the rest of the arguments of the original function. /// /// - Parameters: /// - a: Input to the first argument of the function /// - fun: Function to be applied. /// - Returns: A function with the same behavior of the input function where the first argument is fixed to the value of the provided argument. public func |><A, B, C, D, E, F, G>(_ a: A, _ fun: @escaping (A, B, C, D, E, F) -> G) -> (B, C, D, E, F) -> G { { b, c, d, e, f in fun(a, b, c, d, e, f) } } /// Applies the first argument to a 7-ary function, returning a 6-ary function with the rest of the arguments of the original function. /// /// - Parameters: /// - a: Input to the first argument of the function /// - fun: Function to be applied. /// - Returns: A function with the same behavior of the input function where the first argument is fixed to the value of the provided argument. public func |><A, B, C, D, E, F, G, H>(_ a: A, _ fun: @escaping (A, B, C, D, E, F, G) -> H) -> (B, C, D, E, F, G) -> H { { b, c, d, e, f, g in fun(a, b, c, d, e, f, g) } } /// Applies the first argument to a 8-ary function, returning a 7-ary function with the rest of the arguments of the original function. /// /// - Parameters: /// - a: Input to the first argument of the function /// - fun: Function to be applied. /// - Returns: A function with the same behavior of the input function where the first argument is fixed to the value of the provided argument. public func |><A, B, C, D, E, F, G, H, I>(_ a: A, _ fun: @escaping (A, B, C, D, E, F, G, H) -> I) -> (B, C, D, E, F, G, H) -> I { { b, c, d, e, f, g, h in fun(a, b, c, d, e, f, g, h) } }
// // LoginDto.swift // KayakFirst Ergometer E2 // // Created by Balazs Vidumanszki on 2017. 02. 01.. // Copyright © 2017. Balazs Vidumanszki. All rights reserved. // import Foundation import SwiftyJSON class LoginDto { var user: User? let userToken: String let refreshToken: String init(json: JSON) { self.userToken = json["user_token"].stringValue self.refreshToken = json["refresh_token"].stringValue } }
// // HomeViewController.swift // CardinalHealth // // Created by Volkov Alexander on 22.06.15. // Copyright (c) 2015 Topcoder. All rights reserved. // import UIKit /// key for the flag that is used to define either to show overlay or not let kHomeOverlayShown = "kHomeOverlayShown" /** * Home Screen * * @author Alexander Volkov * @version 1.0 */ class HomeViewController: UIViewController { @IBOutlet weak var mainImage: UIImageView! @IBOutlet weak var newideasLabel: UILabel! // Middle @IBOutlet weak var middleTopLine1Height: NSLayoutConstraint! @IBOutlet weak var middleTopLine2Height: NSLayoutConstraint! @IBOutlet weak var leftLabel: UILabel! @IBOutlet weak var leftCounterLabel: UILabel! @IBOutlet weak var leftButton: UIButton! @IBOutlet weak var rightLabel: UILabel! @IBOutlet weak var rightCounterLabel: UILabel! @IBOutlet weak var rightButton: UIButton! @IBOutlet weak var browseButton: UIButton! @IBOutlet weak var submitButton: UIButton! @IBOutlet weak var settingsButton: UIButton! /// flag: true - overlay was already shown, false - overlay is not yet shown var overlayShown = false var notificationsWidget: NotificationsWidget! override func viewDidLoad() { super.viewDidLoad() fixUI() initNavigation() newideasLabel.text = "0" leftCounterLabel.text = "0" rightCounterLabel.text = "0" } /** Show overlay if needed :param: animated the animation flag */ override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) initNavigation() loadData() if isFirstTime(kHomeOverlayShown) { // Check if Home Screen is first time opened self.showOverlay() } } /** Initialize navigation bar */ func initNavigation() { initNavigationBarTitle("DASHBOARD".localized().uppercaseString) /// Bell icon let button = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton button.frame = CGRectMake(0, 0, 30, 30) button.setImage(UIImage(named: "iconBell"), forState: UIControlState.Normal) button.addTarget(self, action: "openNewIdeasAction:", forControlEvents: .TouchUpInside) let view = UIView(frame: button.frame) view.addSubview(button) // Add widget var widget = NotificationsWidget() widget.number = 0 widget.backgroundColor = UIColor.clearColor() let size = CGSize(width: 20, height: 20) widget.frame = CGRect(origin: CGPoint(x: 11, y: 0), size: size) view.addSubview(widget) self.navigationItem.rightBarButtonItems = [UIBarButtonItem(customView: view)] self.notificationsWidget = widget initBackButtonFromParent() } /** Fixes UI constraints, image modes */ func fixUI() { if isIPhone5() { mainImage.contentMode = UIViewContentMode.ScaleAspectFit } // Float values for heights of the lines middleTopLine1Height.constant = 0.5 middleTopLine2Height.constant = 1.5 fixConstraints(browseButton) fixConstraints(submitButton) fixConstraints(settingsButton) } /** Changes not zero constrains to have 0.5 value (this is not possible in Interface Builder) :param: button the button */ private func fixConstraints(button: UIButton) { for constraint in button.superview!.constraints() { if let c = constraint as? NSLayoutConstraint { if c.firstItem as? UIButton == button ?? false || c.secondItem as? UIButton == button ?? false { if c.constant > 0 { c.constant = 0.5 } } } } button.layoutIfNeeded() } /** Shows overlay screen */ func showOverlay() { overlayShown = true let navigationBarHeight: CGFloat = 64 let rect1 = leftButton.convertRectCorrectly(leftButton.frame, toView: self.view) let rect2 = rightButton.convertRectCorrectly(rightButton.frame, toView: self.view) let rect3 = submitButton.convertRectCorrectly(submitButton.frame, toView: self.view) let coord1 = CGPointMake(CGRectGetMidX(rect1), CGRectGetMidY(rect1) - navigationBarHeight) let coord2 = CGPointMake(CGRectGetMidX(rect2), CGRectGetMidY(rect2) - navigationBarHeight) let coord3 = CGPointMake(CGRectGetMidX(rect3), CGRectGetMidY(rect3) - navigationBarHeight) let string1 = getAttributedString("OVERLAY1") let string2 = getAttributedString("OVERLAY2") let paragrahStyle = NSMutableParagraphStyle() paragrahStyle.alignment = NSTextAlignment.Right string2.addAttribute(NSParagraphStyleAttributeName, value: paragrahStyle, range: NSMakeRange(0, string2.length)) if let vc = create(OverlayViewController.self) { self.view.layoutIfNeeded() let referenceImage = navigationController!.createSnapshort() let data1 = HomeOverlay(text: nil, attributedString: string1, icon: nil, coordirantes: coord1 ) let data2 = HomeOverlay(text: nil, attributedString: string2, icon: nil, coordirantes: coord2 ) let data3 = HomeOverlay(text: "What's your ideas? Share & discuss with others", attributedString: nil, icon: UIImage(named: "iconOverlaySubmit"), coordirantes: coord3 ) vc.homeOverlayData = [data1, data2, data3] let view = vc.view vc.hideViews() RootViewControllerSingleton?.loadViewController(vc, RootViewControllerSingleton!.view) vc.fadeIn() } } /** Get attributed string for overlay screen text :param: localizedPrefix the prefix for localized string key :returns: NSMutableAttributedString */ func getAttributedString(localizedPrefix: String) -> NSMutableAttributedString { let str1 = "\(localizedPrefix)_TEXT1".localized() let str2 = "\(localizedPrefix)_TEXT2".localized() let str3 = "\(localizedPrefix)_TEXT3".localized() let range1 = NSMakeRange(0,count(str1)) let range2 = NSMakeRange(count(str1), count(str2)) let range3 = NSMakeRange(count(str1 + str2), count(str3)) var fontSize: CGFloat = 19.7 if isIPhone5() { fontSize = 15 } let font1 = UIFont(name: Fonts.regular, size: fontSize)! let font2 = UIFont(name: Fonts.bold, size: fontSize)! let string = NSMutableAttributedString(string: str1 + str2 + str3, attributes: [NSForegroundColorAttributeName: UIColor.whiteColor()]) string.addAttributes([NSFontAttributeName: font1], range: range1) string.addAttributes([NSFontAttributeName: font2, NSForegroundColorAttributeName:Colors.red], range: range2) string.addAttributes([NSFontAttributeName: font1], range: range3) return string } /** Load ideas and update UI */ func loadData() { IdeasDataSource.sharedInstance.getIdeas(callback: { (list: [Idea]) -> () in // My ideas self.leftCounterLabel.text = Idea.filterMyIdeas(list).count.description // All ideas self.rightCounterLabel.text = list.count.description // New ideas let n = Idea.filterNewIdeas(list).count self.newideasLabel.text = n.description self.notificationsWidget.number = n }) { (error: RestError, res: RestResponse?) -> () in error.showError() } } /** Open new ideas list :param: sender the button */ @IBAction func openNewIdeasAction(sender: AnyObject) { showIdeas(IdeasListType.New) } /** "My Ideas" button action handler :param: sender the button */ @IBAction func myIdeasAction(sender: AnyObject) { showIdeas(IdeasListType.My) } /** "All Ideas" button action handler :param: sender the button */ @IBAction func allIdeasAction(sender: AnyObject) { showIdeas(IdeasListType.All) } /** "Browse" button action handler :param: sender the button */ @IBAction func browseButtonAction(sender: AnyObject) { showIdeas(IdeasListType.Random) } /** "Submit Ideas" button action handler :param: sender the button */ @IBAction func submitButtonAction(sender: AnyObject) { openSubmitIdeaScreen() } /** "Settings" button action handler :param: sender the button */ @IBAction func settingsButtonAction(sender: AnyObject) { if let vc = create(SettingsViewController.self) { self.navigationController?.pushViewController(vc, animated: true) } } internal func showIdeas(type: IdeasListType) { if let vc = create(IdeasListViewController.self) { vc.listType = type navigationController?.pushViewController(vc, animated: true) } } } class MainNavigationViewController: UINavigationController { override func preferredStatusBarStyle() -> UIStatusBarStyle { return UIStatusBarStyle.LightContent } } /** * Shortcut method related to application screen transition logic * * @author Alexander Volkov * @version 1.0 */ extension UIViewController { /** Opens Submit Idea screen */ func openSubmitIdeaScreen() { if let vc = create(SubmitIdeaViewController.self) { navigationController?.pushViewController(vc, animated: true) } } }
// // ViewController.swift // travel-app // // Created by Y u l i a on 21.07.2021. // import UIKit struct LandingItem { let title: String let detail: String let backgroundImage: UIImage? } class ViewController: UIViewController { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var detailLabel: UILabel! @IBOutlet weak var pageControl: UIPageControl! @IBOutlet weak var backgroundView: UIView! @IBOutlet weak var backgroundImage: UIImageView! private let items: [LandingItem] = [ .init( title: "Explore The World", detail: "Travel doesn't become adventure until you leave yourself behind", backgroundImage: UIImage(named: "1")), .init( title: "Let's Make Your Best Trip Ever", detail: "The best travel for your journey respectful for the environment", backgroundImage: UIImage(named: "2")), .init( title: "Live Your Dream Now", detail: "Never stop exploring", backgroundImage: UIImage(named: "3")) ] private var currentItem: Int = 0 func setupPageControl() { pageControl.numberOfPages = items.count } func setupScreen(index: Int) { titleLabel.text = items[index].title detailLabel.text = items[index].detail pageControl.currentPage = index titleLabel.alpha = 1.0 detailLabel.alpha = 1.0 titleLabel.transform = .identity detailLabel.transform = .identity } func setupGestures() { let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTapAnimation)) view.addGestureRecognizer(tapGesture) } func setupImage(index: Int) { backgroundImage.image = items[index].backgroundImage UIView.transition( with: backgroundImage, duration: 0.5, options: .transitionCrossDissolve, animations: { self.backgroundImage.image = self.items[index].backgroundImage }, completion: nil) } @objc private func handleTapAnimation() { print("Tap") UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.5, options: .curveEaseInOut, animations: { self.titleLabel.alpha = 0.8 self.titleLabel.transform = CGAffineTransform(translationX: -30, y: 0) }) { _ in UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.5, options: .curveEaseInOut, animations: { self.titleLabel.alpha = 0 self.titleLabel.transform = CGAffineTransform(translationX: 0, y: -550) }, completion: nil) } UIView.animate(withDuration: 0.5, delay: 0.5, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.5, options: .curveEaseInOut, animations: { self.detailLabel.alpha = 0.8 self.detailLabel.transform = CGAffineTransform(translationX: -30, y: 0) }) { _ in UIView.animate(withDuration: 0.5, delay: 0.5, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.5, options: .curveEaseInOut, animations: { self.detailLabel.alpha = 0 self.detailLabel.transform = CGAffineTransform(translationX: 0, y: -550) }) { _ in self.currentItem += 1 if (self.currentItem == self.items.count) { print("Last!") self.showMainApp() } else { print(self.currentItem, self.items.count) self.setupScreen(index: self.currentItem) self.setupImage(index: self.currentItem) } } } } private func showMainApp() { let mainAppViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(identifier: "MainAppViewController") if let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene, let sceneDelegate = windowScene.delegate as? SceneDelegate, let window = sceneDelegate.window { window.rootViewController = mainAppViewController } } override func viewDidLoad() { super.viewDidLoad() setupPageControl() setupScreen(index: currentItem) setupGestures() } }
// // ViewController.swift // Uploading // // Created by 柯東爵 on 2018/6/3. // Copyright © 2018年 CSIE. All rights reserved. // import UIKit enum MyError: Error { case message(String) } class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate { @IBOutlet var imgView: UIImageView! let imagePicker = UIImagePickerController() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. imagePicker.delegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func Choose(_ sender: Any) { imagePicker.delegate = self imagePicker.sourceType = UIImagePickerControllerSourceType.savedPhotosAlbum self.present(imagePicker, animated: true, completion: nil) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let image = imgView.image { let SpotTableScene = segue.destination as! SpotTableViewController SpotTableScene.img = image } else { self.addAlert(title: "No Image", message: "Please choose a image to upload!") } } func addAlert(title: String, message: String) { let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) self.present(alert, animated: true) } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { if let image = info[UIImagePickerControllerOriginalImage] as? UIImage { imgView.image = image } else{ print("Something went wrong!") } dismiss(animated: true, completion: nil) } }
import Foundation import UIKit class BookPriceAttribute { static func cretePriceAttribute(book: Book) -> NSAttributedString { var attributeString: NSMutableAttributedString! if book.beforeOffPrice > 0 { let priceText = "\(book.beforeOffPrice.clean) تومان \n \("\(book.price.clean) تومان")" attributeString = NSMutableAttributedString(string: priceText) let beforeOfPriceStringRange = (priceText as NSString).range(of: "\(book.beforeOffPrice.clean) تومان") attributeString.addAttribute(NSAttributedString.Key.strikethroughStyle, value: 2, range: beforeOfPriceStringRange) attributeString.addAttributes([NSAttributedString.Key.foregroundColor: R.color.discountPrice()!], range: beforeOfPriceStringRange) let priceStringRange = (priceText as NSString).range(of: "\(book.price.clean) تومان") attributeString.addAttributes([NSAttributedString.Key.foregroundColor: R.color.price()!], range: priceStringRange) attributeString.addAttribute(.font, value: R.font.iranSansFaNumLight(size: 14)!, range: beforeOfPriceStringRange) attributeString.addAttribute(.font, value: R.font.iranSansFaNumBold(size: 14)!, range: priceStringRange) } else { let priceText = "\("\(book.price.clean) تومان")" attributeString = NSMutableAttributedString(string: priceText) let priceStringRange = (priceText as NSString).range(of: "\(book.price.clean) تومان") attributeString.addAttributes([NSAttributedString.Key.foregroundColor: R.color.price()], range: priceStringRange) attributeString.addAttribute(.font, value: R.font.iranSansFaNumBold(size: 14)!, range: priceStringRange) } return attributeString } } extension Double { var clean: String { return self.truncatingRemainder(dividingBy: 1) == 0 ? String(format: "%.0f", self) : String(self) } }
// // BabySitterInfosView.swift // CuidooApp // // Created by Victor Toon de Araújo on 19/11/19. // Copyright © 2019 Júlio John Tavares Ramos. All rights reserved. // import UIKit class BabySitterInfosView: UIView, Nibable { @IBOutlet var babysitterView: UIView! @IBOutlet weak var babySitterImage: UIImageView! @IBOutlet weak var bottomView: UIView! @IBOutlet weak var descriptionText: UILabel! @IBOutlet weak var heartbutton: UIButton! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var profissionLabel: UILabel! @IBOutlet weak var descriptionLabel: UILabel! @IBOutlet weak var cuidadosLabel: UILabel! @IBOutlet weak var avaliationLabel: UILabel! @IBOutlet weak var twoYearsLabel: UILabel! func setInformations(name: String, informations: Informations) { self.nameLabel.text = name self.profissionLabel.text = informations.profission self.descriptionText.text = informations.description self.cuidadosLabel.text = "\(informations.cuidados)" self.avaliationLabel.text = "\(informations.avaliation)" self.twoYearsLabel.text = informations.experience } @IBAction func heartButtonClick(_ sender: Any) { if self.heartbutton.backgroundImage(for: .normal) == UIImage(named: "heart"){ self.heartbutton.setBackgroundImage(UIImage(named: "heart.fill"), for: .normal) } else{ self.heartbutton.setBackgroundImage(UIImage(named: "heart"), for: .normal) } } override init(frame: CGRect) { super.init(frame: frame) loadNib() babysitterView.layer.cornerRadius = 13.0 } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) loadNib() babysitterView.layer.cornerRadius = 13.0 } }
// // ReminderTableViewController.swift // watchout // // Created by Rafael Fernandes de Oliveira Carvalho on 6/20/15. // Copyright (c) 2015 Rafael Fernandes de Oliveira Carvalho. All rights reserved. // import UIKit class ReminderTableViewController: UITableViewController { var reminder: Reminder? @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var dateLabel: UILabel! override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if let title = reminder?.title { titleLabel.text = title } let formatter = NSDateFormatter() formatter.dateStyle = .LongStyle formatter.timeStyle = .MediumStyle if let date = reminder?.date { dateLabel.text = formatter.stringFromDate(date) } } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "presentEditingReminder" { if let nav = segue.destinationViewController as? UINavigationController { if let vc = nav.visibleViewController as? NewReminderTableViewController { vc.reminder = reminder vc.editingReminder = true } } } } }
// // SCNNode+Text.swift // faceIT // // Created by Michael Ruhl on 18.08.17. // Copyright © 2017 NovaTec GmbH. All rights reserved. // import Foundation import ARKit import Async import HoundifySDK public extension SCNNode { convenience init(withText text : String, position: SCNVector3) { self.init() print("text ", text) if text == "Negative" || text == "AlLVIN LIN" { return } let bubbleDepth : Float = 0.01 // the 'depth' of 3D text // TEXT BILLBOARD CONSTRAINT let billboardConstraint = SCNBillboardConstraint() billboardConstraint.freeAxes = SCNBillboardAxis.Y // BUBBLE-TEXT let bubble = SCNText(string: text, extrusionDepth: CGFloat(bubbleDepth)) bubble.font = UIFont(name: "Futura", size: 0.08)?.withTraits(traits: .traitBold) bubble.alignmentMode = CATextLayerAlignmentMode.left.rawValue bubble.firstMaterial?.diffuse.contents = UIColor.orange bubble.firstMaterial?.specular.contents = UIColor.white bubble.firstMaterial?.isDoubleSided = true bubble.chamferRadius = CGFloat(bubbleDepth) // // BUBBLE NODE let (minBound, maxBound) = bubble.boundingBox let bubbleNode = SCNNode(geometry: bubble) // Centre Node - to Centre-Bottom point bubbleNode.pivot = SCNMatrix4MakeTranslation( (maxBound.x - minBound.x)/2, minBound.y, bubbleDepth/2) // Reduce default text size bubbleNode.scale = SCNVector3Make(0.2, 0.2, 0.2) bubbleNode.simdPosition = simd_float3.init(x: 0.05, y: 0.04, z: 0) // get the relation and dob var relation = "" var dob = "" if let jsonData = jsonData { for contact in jsonData.items { print("contact: ", contact.username, "text ", text) if let username = contact.username, let rela = contact.relation, let dateOfBirth = contact.dob { if username == text { relation = rela dob = dateOfBirth } } } } // DETAIL-TEXT let detailInfoText = SCNText(string: "Relation: "+relation, extrusionDepth: CGFloat(bubbleDepth)) detailInfoText.isWrapped = true detailInfoText.font = UIFont(name: "Futura", size: 0.08)?.withTraits(traits: .traitBold) // detailInfoText.containerFrame = CGRect(origin: .zero, size: CGSize(width: 100, height: 500)) detailInfoText.alignmentMode = CATextLayerAlignmentMode.left.rawValue detailInfoText.firstMaterial?.diffuse.contents = UIColor.blue detailInfoText.firstMaterial?.specular.contents = UIColor.white detailInfoText.firstMaterial?.isDoubleSided = true detailInfoText.chamferRadius = CGFloat(bubbleDepth) // DETAIL NODE // let (minBoundDetail, maxBoundDetail) = bubble.boundingBox let detailNode = SCNNode(geometry: detailInfoText) // Centre Node - to Centre-Bottom point detailNode.pivot = SCNMatrix4MakeTranslation( (maxBound.x - minBound.x)/2, minBound.y, bubbleDepth/2) // Reduce default text size detailNode.scale = SCNVector3Make(0.2, 0.2, 0.2) detailNode.simdPosition = simd_float3.init(x: 0.05, y: 0.02, z: 0) // DETAIL-TEXT let dobText = SCNText(string: "DOB: "+dob, extrusionDepth: CGFloat(bubbleDepth)) dobText.isWrapped = true dobText.font = UIFont(name: "Futura", size: 0.08)?.withTraits(traits: .traitBold) // detailInfoText.containerFrame = CGRect(origin: .zero, size: CGSize(width: 100, height: 500)) dobText.alignmentMode = CATextLayerAlignmentMode.left.rawValue dobText.firstMaterial?.diffuse.contents = UIColor.blue dobText.firstMaterial?.specular.contents = UIColor.white dobText.firstMaterial?.isDoubleSided = true dobText.chamferRadius = CGFloat(bubbleDepth) // DETAIL NODE // let (minBoundDOB, maxBoundDOB) = bubble.boundingBox let dobNode = SCNNode(geometry: dobText) // Centre Node - to Centre-Bottom point dobNode.pivot = SCNMatrix4MakeTranslation( (maxBound.x - minBound.x)/2, minBound.y, bubbleDepth/2) // Reduce default text size dobNode.scale = SCNVector3Make(0.2, 0.2, 0.2) dobNode.simdPosition = simd_float3.init(x: 0.05, y: 0, z: 0) // CENTRE POINT NODE let sphere = SCNSphere(radius: 0.004) sphere.firstMaterial?.diffuse.contents = UIColor.gray let sphereNode = SCNNode(geometry: sphere) sphereNode.opacity = 0.6 // addChildNode(boxNode) addChildNode(dobNode) addChildNode(detailNode) addChildNode(bubbleNode) addChildNode(sphereNode) constraints = [billboardConstraint] self.position = position } func move(_ position: SCNVector3) { SCNTransaction.begin() SCNTransaction.animationDuration = 0.2 SCNTransaction.animationTimingFunction = CAMediaTimingFunction.init(name: CAMediaTimingFunctionName.linear) self.position = position opacity = 1 SCNTransaction.commit() } func hide() { SCNTransaction.begin() SCNTransaction.animationDuration = 0.4 SCNTransaction.animationTimingFunction = CAMediaTimingFunction.init(name: CAMediaTimingFunctionName.linear) opacity = 0 SCNTransaction.commit() } func show() { opacity = 0 SCNTransaction.begin() SCNTransaction.animationDuration = 0.4 SCNTransaction.animationTimingFunction = CAMediaTimingFunction.init(name: CAMediaTimingFunctionName.linear) opacity = 1 SCNTransaction.commit() } } private extension UIFont { // Based on: https://stackoverflow.com/questions/4713236/how-do-i-set-bold-and-italic-on-uilabel-of-iphone-ipad func withTraits(traits:UIFontDescriptor.SymbolicTraits...) -> UIFont { let descriptor = self.fontDescriptor.withSymbolicTraits(UIFontDescriptor.SymbolicTraits(traits)) return UIFont(descriptor: descriptor!, size: 0) } }
// // HomeViewController.swift // FirebaseCRUDExample // // Created by Luis Sergio da Silva Junior on 06/02/17. // Copyright © 2017 Luis Sergio. All rights reserved. // import UIKit import FirebaseAuth import FirebaseDatabase class HomeViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var tableView: UITableView! let userID = FIRAuth.auth()?.currentUser?.uid var ref:FIRDatabaseReference! var tasksDesc = [Task]() var selectedIndex = -1 override func viewDidLoad() { super.viewDidLoad() ref = FIRDatabase.database().reference() self.tableView.allowsMultipleSelectionDuringEditing = true ref.child("tasks").child(userID!).observe(.value, with: { (snapshot) in // Get user value if snapshot.exists(){ self.tasksDesc = [Task]() let task = snapshot.value as? NSDictionary for (key, value) in task!{ self.convertToJson(dic: value as! NSDictionary,key: key as! String) } self.tableView.reloadData() // ... } }) // Do any additional setup after loading the view. } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { selectedIndex = indexPath.row performSegue(withIdentifier: "show", sender: self) } func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete{ let taskId = self.tasksDesc[indexPath.row].id ref.child("tasks").observe(.value, with: { (snapshot) -> Void in if snapshot.exists(){ self.ref.child("tasks").child(self.userID!).child(taskId!).removeValue() } }) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tasksDesc.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "taskcell", for: indexPath) cell.textLabel!.text = tasksDesc[indexPath.row].desc return cell } func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? { return "Delete" } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "logout"{ do{ try FIRAuth.auth()!.signOut() print("logout done") }catch{ print("logout error") } } if segue.identifier == "show"{ let upController = segue.destination as! UpdateViewController upController.task = tasksDesc[selectedIndex] upController.userID = userID print("show task") } } @IBAction func unwindToHomeLoggedUser(segue: UIStoryboardSegue) { if segue.identifier == "createtask"{ } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ private func convertToJson(dic: NSDictionary, key: String){ do { let jsonData = try JSONSerialization.data(withJSONObject: dic, options: .prettyPrinted) let decoded = try JSONSerialization.jsonObject(with: jsonData, options: []) if let dictFromJSON = decoded as? [String:String] { tasksDesc.append(Task(id: key, desc: (dictFromJSON["desc"])!)) } } catch { print(error.localizedDescription) } } }
// // UIView + AutoLayout.swift // Utils // // Created by luolun on 2017/5/31. // Copyright © 2017年 Aaron. All rights reserved. // import UIKit public extension UIView { public func autolayout_addSubview(_ view: UIView, translatesAutoResizingMaskIntoConstraints: Bool = false) { view.translatesAutoresizingMaskIntoConstraints = translatesAutoresizingMaskIntoConstraints self.addSubview(view) } public func autolayout_addSubviews(_ views: [UIView], translatesAutoResizingMaskIntoConstraints: Bool = false) { for view in views { view.translatesAutoresizingMaskIntoConstraints = translatesAutoresizingMaskIntoConstraints self.addSubview(view) } } public func makeConstraintsEqualTo(_ view: UIView) { NSLayoutConstraint(item: self, attribute: .left, relatedBy: .equal, toItem: view, attribute: .left, multiplier: 1.0, constant: 0).isActive = true NSLayoutConstraint(item: self, attribute: .right, relatedBy: .equal, toItem: view, attribute: .right, multiplier: 1.0, constant: 0).isActive = true NSLayoutConstraint(item: self, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1.0, constant: 0).isActive = true NSLayoutConstraint(item: self, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1.0, constant: 0).isActive = true } public func makeConstraintsEqualTo(_ view: UIView, edgeInsets: UIEdgeInsets) { NSLayoutConstraint(item: self, attribute: .left, relatedBy: .equal, toItem: view, attribute: .left, multiplier: 1.0, constant: edgeInsets.left).isActive = true NSLayoutConstraint(item: self, attribute: .right, relatedBy: .equal, toItem: view, attribute: .right, multiplier: 1.0, constant: -edgeInsets.right).isActive = true NSLayoutConstraint(item: self, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1.0, constant: edgeInsets.top).isActive = true NSLayoutConstraint(item: self, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1.0, constant: -edgeInsets.bottom).isActive = true } }
// // MyViewController.swift // CustomPresentationDemo // // Created by 顾超 on Feb/10/16. // Copyright © 2016 axl411. All rights reserved. // import UIKit class MyViewController: UIViewController { override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) modalPresentationStyle = .Custom } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.redColor() let btn = UIButton(type: .System) btn.setTitle("Dismiss!", forState: .Normal) btn.addTarget(self, action: "dismissVC", forControlEvents: .TouchUpInside) btn.translatesAutoresizingMaskIntoConstraints = false view.addSubview(btn) view.addConstraint(btn.centerXAnchor.constraintEqualToAnchor(view.centerXAnchor)) view.addConstraint(btn.centerYAnchor.constraintEqualToAnchor(view.centerYAnchor)) } func dismissVC() { printSeparator() print("Begin dismiss view controller") dismissViewControllerAnimated(true) { () -> Void in printSeparator() print("dismissViewControllerAnimated - Dismiss completed") } } }
// // dropShadow.swift // Saucesy // // Created by Meeky Dekowski on 11/25/16. // Copyright © 2016 Meek Apps. All rights reserved. // import UIKit class dropShadow: UIView { override func awakeFromNib() { let grey: CGFloat = 190/225 self.layer.shadowColor = UIColor(red: grey, green: grey, blue: grey, alpha: 1.0).cgColor self.layer.shadowOffset = CGSize(width: 0.0, height: 1.0) self.layer.shadowRadius = 0 self.layer.shadowOpacity = 1.0 self.layer.masksToBounds = false self.layer.shadowPath = UIBezierPath(rect: self.layer.bounds).cgPath } }
// RUN: %target-swift-frontend -primary-file %s -emit-ir struct A<T1, T2> { var b: T1 var c: T2 var d: B<T1, T2> } struct B<T1, T2> { var c: T1 var d: T2 } struct C<T1> {} struct D<T2> {} struct Foo<A1, A2> { var a: A1 var b: Bar<A1, A2> } struct Bar<A1, A2> { }
// // MapViewController.swift // 美团 // // Created by wxqdev on 15/6/23. // Copyright (c) 2015年 meituan.iteasysoft.com. All rights reserved. // import UIKit import MapKit class MapViewController: UIViewController,MKMapViewDelegate { @IBOutlet weak var mapView: MKMapView! override func viewDidLoad() { super.viewDidLoad() self.mapView.delegate = self } deinit { println("MapViewController deinit...") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillAppear(animated: Bool) { startLocation() } override func viewDidDisappear(animated: Bool){ LocationManager.getInstance().stopMonitoringSignificantLocationChanges() } func startLocation(){ LocationManager.getInstance().startMonitoringSignificantLocationChanges { (issuccess,location) -> () in println("startMonitoringSignificantLocationChanges callback...") var resultTxt:String!="failed" if issuccess { let geoCoder = CLGeocoder() geoCoder.reverseGeocodeLocation(location, completionHandler: { (placemarks:[AnyObject]!, error:NSError!) -> Void in println("reverseGeocodeLocation callback...") if error != nil{ println(error) return } if placemarks != nil && placemarks.count > 0 { let placemark = placemarks[0] as! CLPlacemark let annotation = MKPointAnnotation() annotation.title = "这里是我的位置" annotation.subtitle = "测试用" annotation.coordinate = placemark.location.coordinate self.mapView.showAnnotations([annotation], animated: true) self.mapView.selectAnnotation(annotation, animated: true) } }) } } } func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! { let identifier = "我的位置" if annotation.isKindOfClass(MKUserLocation) { return nil } var annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier(identifier) if annotationView == nil { annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: identifier) annotationView.canShowCallout = true } let leftIconView = UIImageView(frame: CGRectMake(0, 0, 47, 47)) leftIconView.image = UIImage(named: "menu1_1") annotationView.leftCalloutAccessoryView = leftIconView return annotationView } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
// // PersionSearchViewController.swift // huicheng // // Created by lvxin on 2018/10/21. // Copyright © 2018年 lvxin. All rights reserved. // import UIKit typealias PersionSearchViewControllerBlock = (_ subStr : String,_ bidStr : String,_ uStr : String,_ nStr : String,_ dStr : String,_ caStr : String,_ dpStr : String,_ sStr : String,_ bdStr : String,_ edStr : String) ->() class PersionSearchViewController: BaseTableViewController,WorkRequestVCDelegate ,DatePickViewDelegate,TitleTableViewCellDelegate,OptionViewDelgate{ let mainTabelView : UITableView = UITableView() var sucessBlock : PersionSearchViewControllerBlock! var dataModel : getoptionsModle! let nameArr = ["账号","姓名","部门","类别","学历","状态","入职时间","至"] /// 时间 var startTimeCell : endTimeTableViewCell! var endTimeCell : endTimeTableViewCell! /// 开始时间 var startTimeStr : String = "" /// 结束时间 var endTimeStr : String = "" /// 时间 var timeView : DatePickView = DatePickView.loadNib() /// 选项 let optionView : OptionView = OptionView.loadNib() let request : WorkRequestVC = WorkRequestVC() var optionCell : OptionTableViewCell! /// 当前选中的行 var currectIndexpath : IndexPath! /// 分所 var bidStr = "" /// 帐号 var uStr = "" /// 姓名 var nStr = "" /// 部门 var dStr = "" ///类别 var caStr = "" ///学历 var dpStr = "" ///状态 var sStr = "" ///入职时间 var bdStr = "" ///离职 var edStr = "" var subStr = "" //选项 var typeSub : Int = 0 //默认没有 0 没有权限 1 有权限 var isHaveSub : Int = 0 var userDataModel : LoginModel! var sectionNum : Int! var branch : [branchModel] = [] var showNum = 0 var showArr : [getoptionsModle_content] = [] // MARK: - life override func viewWillLayoutSubviews() { } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.view.backgroundColor = viewBackColor request.delegate = self self.navigation_title_fontsize(name: "人员查询", fontsize: 18) self.navigationBar_rightBtn_title(name: "确定") self.navigationBar_leftBtn_image(image: #imageLiteral(resourceName: "pub_arrow")) request.usermanageRequest() userDataModel = UserInfoLoaclManger.getsetUserWorkData() if typeSub < userDataModel.searchpower.count { isHaveSub = userDataModel.searchpower[typeSub] // isHaveSub = 1 if isHaveSub == 1 { // rowNum = rowNum + 1 sectionNum = 2 } else { sectionNum = 1 } } self.creatUI() } // MARK: - UI func creatUI() { // mainTabelView.backgroundColor = viewBackColor mainTabelView.delegate = self; mainTabelView.dataSource = self; mainTabelView.tableFooterView = UIView() mainTabelView.separatorStyle = .none mainTabelView.showsVerticalScrollIndicator = false mainTabelView.showsHorizontalScrollIndicator = false mainTabelView.backgroundView?.backgroundColor = .clear mainTabelView.register(UINib.init(nibName: "TitleTableViewCell", bundle: nil), forCellReuseIdentifier: TitleTableViewCellID) mainTabelView.register(UINib.init(nibName: "OptionTableViewCell", bundle: nil), forCellReuseIdentifier: OptionTableViewCellID) mainTabelView.register(UINib.init(nibName: "endTimeTableViewCell", bundle: nil), forCellReuseIdentifier: endTimeTableViewCellid) self.tableView = mainTabelView } // MARK: - delegate override func numberOfSections(in tableView: UITableView) -> Int { return sectionNum } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if isHaveSub == 1 { if section == 0 { return 1 } else { return self.nameArr.count } } else { return self.nameArr.count } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if isHaveSub == 1 && indexPath.section == 0 { optionCell = tableView.dequeueReusableCell(withIdentifier: OptionTableViewCellID, for: indexPath) as! OptionTableViewCell optionCell.setData_caseDetail(titleStr: "分所", contentStr: "") return optionCell } else { if indexPath.row == 0 { let cell = tableView.dequeueReusableCell(withIdentifier: TitleTableViewCellID, for: indexPath) as! TitleTableViewCell //账号 cell.setData_dealcheck(titleStr: nameArr[indexPath.row], tagNum: indexPath.row) cell.delegate = self return cell } else if indexPath.row == 1 { //账号 let cell = tableView.dequeueReusableCell(withIdentifier: TitleTableViewCellID, for: indexPath) as! TitleTableViewCell cell.setData_dealcheck(titleStr: nameArr[indexPath.row], tagNum: indexPath.row) cell.delegate = self return cell } else if indexPath.row == 2 { //部门 let cell : OptionTableViewCell = tableView.dequeueReusableCell(withIdentifier: OptionTableViewCellID, for: indexPath) as! OptionTableViewCell cell.setData_caseDetail(titleStr: nameArr[indexPath.row], contentStr: dStr) cell.contentLabel.text = "请选择" return cell }else if indexPath.row == 3 { //类别 let cell : OptionTableViewCell = tableView.dequeueReusableCell(withIdentifier: OptionTableViewCellID, for: indexPath) as! OptionTableViewCell cell.setData_caseDetail(titleStr: nameArr[indexPath.row], contentStr: caStr) cell.contentLabel.text = "请选择" return cell }else if indexPath.row == 4 { //学历 let cell : OptionTableViewCell = tableView.dequeueReusableCell(withIdentifier: OptionTableViewCellID, for: indexPath) as! OptionTableViewCell cell.setData_caseDetail(titleStr: nameArr[indexPath.row], contentStr: dpStr) cell.contentLabel.text = "请选择" return cell }else if indexPath.row == 5 { //状态 let cell : OptionTableViewCell = tableView.dequeueReusableCell(withIdentifier: OptionTableViewCellID, for: indexPath) as! OptionTableViewCell cell.setData_caseDetail(titleStr: nameArr[indexPath.row], contentStr: sStr) cell.contentLabel.text = "请选择" return cell } else if indexPath.row == 6 { //入职时间 startTimeCell = tableView.dequeueReusableCell(withIdentifier: endTimeTableViewCellid, for: indexPath) as! endTimeTableViewCell startTimeCell.setData(titleStr: "开始时间", tag: 0) startTimeCell.timeLabel.text = "请选择" return startTimeCell } else{ //至 endTimeCell = tableView.dequeueReusableCell(withIdentifier: endTimeTableViewCellid, for: indexPath) as! endTimeTableViewCell endTimeCell.setData(titleStr: "至", tag: 1) endTimeCell.timeLabel.text = "请选择" return endTimeCell } } } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { self.view.endEditing(true) showNum = indexPath.row currectIndexpath = indexPath if isHaveSub == 1 && indexPath.section == 0 { //案件组别 if branch.count > 0 { self.showOption_branch() } else { request.branchRequest() } } else { if indexPath.row == 2 { //部门 showArr = self.dataModel.department self.showOptionView_part() } else if indexPath.row == 3 { //类别 showArr = self.dataModel.category self.showOptionView_part() } else if indexPath.row == 4 { //学历 showArr = self.dataModel.diploma self.showOptionView_part() } else if indexPath.row == 5 { //状态 showArr = self.dataModel.state self.showOptionView_part() } else if indexPath.row == 6 { //入职时间 self.showTime_start() } else if indexPath.row == 7 { //至 self.showTime_end() } } } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return TitleTableViewCellH } func endEdite(inputStr: String, tagNum: Int) { if tagNum == 0 { uStr = inputStr } else { nStr = inputStr } } func requestSucceed_work(data: Any, type: WorkRequestVC_enum) { if type == .branch { branch = data as! [branchModel] self.showOption_branch() } else { dataModel = data as! getoptionsModle let model : getoptionsModle_content = getoptionsModle_content() model.id = 0 model.name = "禁用" let model2 : getoptionsModle_content = getoptionsModle_content() model2.id = 1 model2.name = "可用" dataModel.state.append(model) dataModel.state.append(model2) } } func requestFail_work(){ } func showOption_branch() { self.maskView.addSubview(self.optionView) self.view.window?.addSubview(self.maskView) self.optionView.setData_branch(arr: branch) self.optionView.delegate = self self.optionView.snp.makeConstraints { (make) in make.left.right.equalTo(0) make.bottom.equalTo(0) make.height.equalTo(200) } } /// 显示时间 func showTime_end() { timeView.removeFromSuperview() self.maskView.addSubview(self.timeView) self.view.window?.addSubview(self.maskView) timeView.delegate = self timeView.setData(type: 1) timeView.snp.makeConstraints { (make) in make.left.right.equalTo(0) make.bottom.equalTo(0) make.height.equalTo(200) } } func showTime_start() { timeView.removeFromSuperview() self.maskView.addSubview(self.timeView) self.view.window?.addSubview(self.maskView) timeView.delegate = self timeView.setData(type: 0) timeView.snp.makeConstraints { (make) in make.left.right.equalTo(0) make.bottom.equalTo(0) make.height.equalTo(200) } } func datePickViewTime(timeStr: String,type : Int) { self.timeView.removeFromSuperview() self.maskView.removeFromSuperview() if type == 0 { startTimeStr = timeStr startTimeCell.setTime(str: startTimeStr) } else { endTimeStr = timeStr endTimeCell.setTime(str: endTimeStr) } } func showOptionView_part() { self.maskView.addSubview(self.optionView) self.view.window?.addSubview(self.maskView) self.optionView.setData_getoptions(dataArr: showArr, index: showNum) self.optionView.delegate = self self.optionView.snp.makeConstraints { (make) in make.left.right.equalTo(0) make.bottom.equalTo(0) make.height.equalTo(200) } } func optionSure(idStr: String, titleStr: String,noteStr : String, pickTag: Int) { HCLog(message: idStr) HCLog(message: titleStr) HCLog(message: noteStr) HCLog(message: pickTag) if isHaveSub == 1 && sectionNum > 1 && currectIndexpath.section == 0 { let cell : OptionTableViewCell = self.mainTabelView.cellForRow(at: IndexPath(row: 0, section: 0)) as! OptionTableViewCell cell.setOptionData(contentStr: titleStr) subStr = idStr } else { if pickTag == 2 { //部门 dStr = idStr } else if pickTag == 3 { //类别 caStr = idStr } else if pickTag == 4 { //学历 dpStr = idStr } else if pickTag == 5 { //状态 sStr = idStr } let cell : OptionTableViewCell = self.mainTabelView.cellForRow(at: IndexPath(row: pickTag, section: sectionNum - 1)) as! OptionTableViewCell cell.setOptionData(contentStr: titleStr) } self.optionView.removeFromSuperview() self.maskView.removeFromSuperview() } override func navigationRightBtnClick() { self.sucessBlock(subStr,bidStr,uStr,nStr,dStr, caStr, dpStr ,sStr , startTimeStr , endTimeStr) self.navigationController?.popViewController(animated: true) } override func navigationLeftBtnClick() { self.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. } */ }
// // GoingPlacesTests.swift // GoingPlacesTests // // Created by Morgan Collino on 11/1/17. // Copyright © 2017 Morgan Collino. All rights reserved. // import XCTest @testable import GoingPlaces class GoingPlacesTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testOpenURL() { let deepLinkManager = DeepLinkManager() let result = deepLinkManager.canOpenURL(url: URL(string: "goingplaces://openLocation?from=__morgan__&location=40.6875012,-73.9796053&name=Flatbush%20Jewelry%20Exchange&address=41%20Flatbush%20Ave%20%235,%20Brooklyn,%20NY%2011217,%20USA")!) XCTAssertTrue(result) } func testOpenBadURL() { let deepLinkManager = DeepLinkManager() let result = deepLinkManager.canOpenURL(url: URL(string: "goingplaces://what/really?")!) XCTAssertFalse(result) } }
// // BarEntry+DataEntry.swift // bm-persona // // Created by Shawn Huang on 7/12/20. // Copyright © 2020 RJ Pimentel. All rights reserved. // import Foundation import UIKit /// The frames associated with a single bar struct BarEntry { let origin: CGPoint let barWidth: CGFloat let barHeight: CGFloat let horizontalSpace: CGFloat let data: DataEntry var bottomTitleFrame: CGRect { return CGRect(x: origin.x - horizontalSpace / 2, y: origin.y + 9 + barHeight, width: barWidth + horizontalSpace, height: 11) } var barFrame: CGRect { return CGRect(x: origin.x, y: origin.y, width: barWidth, height: barHeight) } } /// The data required for a single bar struct DataEntry { let color: UIColor let height: CGFloat let bottomText: String var index: Int }
// // BorderedView.swift // MyMacOSApp // // Created by steve.ham on 2021/01/05. // import Cocoa class BorderedView: NSView { @IBInspectable var backgroundColor: NSColor? { didSet { needsDisplay = true } } @IBInspectable var cornerRadius: CGFloat = 0 { didSet { needsDisplay = true } } @IBInspectable var borderColor: NSColor? { didSet { needsDisplay = true } } @IBInspectable var borderWidth: CGFloat = 0 { didSet { needsDisplay = true } } override func animation(forKey key: NSAnimatablePropertyKey) -> Any? { key == "borderWidth" ? CABasicAnimation() : super.animation(forKey: key) } override var wantsUpdateLayer: Bool { true } override func updateLayer() { guard let layer = layer else { return } layer.backgroundColor = backgroundColor?.cgColor layer.cornerRadius = cornerRadius layer.borderColor = borderColor?.cgColor layer.borderWidth = borderWidth } }
// // FileHelper.swift // homework // // Created by Liu, Naitian on 7/4/16. // Copyright © 2016 naitianliu. All rights reserved. // import Foundation import UIKit class FileHelper { init() { } func saveImageToFile(image: UIImage, objectKey: String) -> String? { let filepath: String = "\(getDocumentsDirectory())/\(objectKey)-image.png" do { try UIImagePNGRepresentation(image)?.writeToFile(filepath, options: .AtomicWrite) return filepath } catch { print(error) return nil } } func saveCompressedJPEGImageToFile(image: UIImage, objectKey: String) -> String? { let newImage = self.resizeImage(image, newWidth: 500) let filepath: String = "\(getDocumentsDirectory())/\(objectKey)-image.jpg" do { try UIImageJPEGRepresentation(newImage, 0.5)?.writeToFile(filepath, options: .AtomicWrite) return filepath } catch { print(error) return nil } } func getDocumentsDirectory() -> String { let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) let documentsDirectory = paths[0] return documentsDirectory } private func resizeImage(image: UIImage, newWidth: CGFloat) -> UIImage { print(image.size.width) let scale = newWidth / image.size.width let newHeight = image.size.height * scale UIGraphicsBeginImageContext(CGSizeMake(newWidth, newHeight)) image.drawInRect(CGRectMake(0, 0, newWidth, newHeight)) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage } }
// // BasicAlertError.swift // // // Created by Carmelo Ruymán Quintana Santana on 21/1/21. // import Foundation import SwiftUI import SpaceXClient enum BasicAlertError: Int, AlertsBuilderType, Error { case genericError = 0 case noReachability = 1 case noLocation = 4 var id: UUID { UUID() } var title: Text { var text: LocalizedStringKey = "Ups!" switch self { case .genericError: text = "Ups!" case .noReachability: text = "Ups!" case .noLocation: text = "Ups!" } return Text(text, bundle: .main) } var message: Text { var text: LocalizedStringKey = "Something has happened" switch self { case .genericError: text = "generic.message" case .noReachability: text = "connection.error.message" case .noLocation: text = "location.disabled.info.alert" } return Text(text, bundle: .main) } var primary: Alert.Button? { var text: LocalizedStringKey = "Ok!" switch self { case .genericError, .noReachability: text = "Ok!" case .noLocation: text = "Ok!" } return Alert.Button.default(Text(text)) } var secondary: Alert.Button? { nil } } func mapError(error: Error) -> BasicAlertError { if let error = error as? ClientError { switch error { case .couldNotDecodeJSON: return BasicAlertError.genericError case .badStatus: return BasicAlertError.genericError case .noReachability: return BasicAlertError.genericError case .badRefreshToken: return BasicAlertError.genericError case .unauthorizedError: return BasicAlertError.genericError case .requestEntityTooLarge: return BasicAlertError.genericError case .clientError: return BasicAlertError.genericError case .serverError: return BasicAlertError.genericError } } else { return BasicAlertError.genericError } }
// // BookWireFrame.swift // Book-Store-App // // Created by Anderson F Carvalho on 07/03/20. // Copyright © 2020 Anderson F Carvalho. All rights reserved. // import UIKit class BookWireFrame: BookWireFrameProtocol { class func createViewController(_ myBook: MyBook?) -> UIViewController { var presenter: BookPresenterProtocol & BookDataModuleOutputProtocol = BookPresenter() presenter.myBook = myBook let whireFrame: BookWireFrameProtocol = BookWireFrame() var dataModule: BookDataModuleInputProtocol = BookDataModule() let viewController = BookVC() viewController.presenter = presenter presenter.viewController = viewController presenter.whireFrame = whireFrame presenter.dataModule = dataModule dataModule.presenter = presenter return viewController } func showBuyLink(from viewController: BookVCProtocol?, _ link: String?) { guard let link = link, let url = URL(string: link), UIApplication.shared.canOpenURL(url) else { return } UIApplication.shared.open(url, options: [:], completionHandler: nil) } func showAlert(from viewController: BookVCProtocol?, message: String) { if let viewController = viewController as? UIViewController { let alert = UIAlertController(title: "Attention", message: message, preferredStyle: .alert) viewController.present(alert, animated: true, completion: nil) } } }
// // File.swift // // // Created by Guerson Perez on 23/07/20. // import Foundation extension Array where Element == String { func updateIndexes<T: DBModel>(for obj: T, newObj: T, withDBName dbName: String, idKey: String, indexesManager: IndexesManager) { let objDict = obj.toDictionary() let newObjDict = newObj.toDictionary() let noDBIndexKey = NoDBConstant.index.rawValue guard let objIndex = objDict[noDBIndexKey] else { return } for (indexKey, newIndexVal) in newObjDict { // Ignore id if it is defined as an indexable key. if indexKey == idKey { continue } if self.contains(indexKey) { let indexDBName = dbName + ":" + indexKey if let indexVal = objDict[indexKey] { let dictObj: [String: Any] = [indexKey: indexVal, noDBIndexKey: objIndex] indexesManager.delete(indexDBName: indexDBName, sortKey: indexKey, indexDict: dictObj) } let newDictObj: [String: Any] = [indexKey: newIndexVal, noDBIndexKey: objIndex] indexesManager.insert(indexDBName: indexDBName, sortKey: indexKey, indexDict: newDictObj) } } // TODO: Check if we need to update default indexed id values? // We shouldn't since changing the id value of the object would mean it is a new object. } func updateIndex<T: DBModel>(for obj: T, newNoDBIndexes: [String], withDBName dbName: String, indexesManager: IndexesManager) { for indexKey in newNoDBIndexes { let objDict = obj.toDictionary() guard let objIndex = objDict[NoDBConstant.index.rawValue], let indexVal = objDict[indexKey] else { return } let indexDBName = dbName + ":" + indexKey let newDictObj: [String: Any] = [indexKey: indexVal, NoDBConstant.index.rawValue: objIndex] indexesManager.insert(indexDBName: indexDBName, sortKey: indexKey, indexDict: newDictObj) } } }
// // ContentView.swift // Practica200222AreasApp // // Created by ByRamon on 22/02/20. // Copyright © 2020 ByRamon. All rights reserved. // import SwiftUI struct ContentView: View { var body: some View { NavigationView{ List{ NavigationLink (destination: AreaTriangulo()){ Image("IconAreaTriangulo") Text("Area del Triangulo") } NavigationLink(destination: AreaCirculo()){ Image("IconAreaCirculo") Text("Area del Circulo") } NavigationLink(destination: AreaCuadrado()){ Image("IconAreaRectangulo") Text("Area del Rectangulo") } }.navigationBarTitle("Areas App") } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
// // ViewController.swift // DemoPassData1 // // Created by Taof on 12/21/19. // Copyright © 2019 Taof. All rights reserved. // import UIKit class ViewController: UIViewController { var topView = CustomView(frame: .zero) override func viewDidLoad() { super.viewDidLoad() view.addSubview(topView) topView.translatesAutoresizingMaskIntoConstraints = false // layout topView.topAnchor.constraint(equalTo: view.topAnchor, constant: 100).isActive = true topView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 32).isActive = true topView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -32).isActive = true topView.heightAnchor.constraint(equalToConstant: 300).isActive = true // tạo dữ liệu var data1: CustomModel? = CustomModel(nameImage: "he", name: "Hoa Phượng", isFavorite: true) // đổ dữ liệu vào view: cách 1 (cách này k hay, hạn chế dùng) // topView.imageView.image = UIImage(named: data1.nameImage) // topView.nameLabel.text = data1.name // topView.isFavorite = data1.isFavorite // topView.favoriteImageView.image = data1.isFavorite ? UIImage(named: "heart-fill") : UIImage(named: "heart") // đổ dữ liệu vào view: cách 2 (cách này dùng hay hơn) topView.setData = data1 data1 = nil // Bước 3: gọi closure ở đây topView.passAction = { [weak self] in guard let new = self else { return } data1?.isFavorite.toggle() new.topView.setData = data1 print(new.topView.nameLabel.text) } } }
// // Chapter3StackMin.swift // CtCI // // Created by Jordan Doczy on 2/19/21. // import Foundation class Chapter3StackMin { static func test() -> Bool { var s = StackWithMin<Int>() s.push(LinkedNode(data: 10)) s.push(LinkedNode(data: 1)) s.push(LinkedNode(data: 12)) s.push(LinkedNode(data: 8)) s.push(LinkedNode(data: 10)) s.push(LinkedNode(data: 9)) s.push(LinkedNode(data: 2)) s.push(LinkedNode(data: 3)) // while s.isEmpty == false { // _ = s.pop() // print (s.stringValue) // print (s.minimum) // } return s.minimum == 1 } } struct StackWithMin<T: Hashable & Comparable>: StackProtocol { private var values = Stack<T>() private var minValues = Stack<T>() var stringValue: String { return values.stringValue } var stringValueMin: String { return minValues.stringValue } var minimum: T? { return minValues.peek() } var isEmpty: Bool { return values.isEmpty } func peek() -> T? { return values.peek() } mutating func pop() -> T? { let value = values.pop() if let unwrappedValue = value, unwrappedValue == minimum { _ = minValues.pop() } return value } mutating func push(_ node: LinkedNode<T>) { if minValues.isEmpty { minValues.push(node) } values.push(node) if(node.data < minimum!) { let copy = LinkedNode(data: node.data) minValues.push(copy) } } }
import UIKit protocol AddToDoItemViewControllerInterface: class { func presentError(error: ApplicationErrorType) } final class AddToDoItemViewController: UIViewController, AlertPresentable { // MARK: - View Private properties private let nameLabel: UILabel = { let label = UILabel() label.text = "Name" return label }() private let nameEditText: UITextField = { let textField = UITextField() textField.placeholder = "place holder" var bottomLine = CALayer() bottomLine.frame = CGRect.init(x: 0, y: 30, width: 300, height: 1) bottomLine.backgroundColor = UIColor.gray.cgColor textField.borderStyle = UITextField.BorderStyle.none textField.layer.addSublayer(bottomLine) return textField }() // MARK: - Public properties var presenter: AddToDoItemPresenterInterface? // MARK: - init init() { super.init(nibName: nil, bundle: nil) configureNavigation() configureViews() configureConstraints() view.backgroundColor = .white } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: - AddToDoItemViewControllerInterface extension AddToDoItemViewController: AddToDoItemViewControllerInterface { func presentError(error: ApplicationErrorType) { presentAlert(with: error) } } // MARK: - View - private methods extension AddToDoItemViewController { private func configureNavigation() { navigationItem.rightBarButtonItem = UIBarButtonItem( barButtonSystemItem: .done, target: self, action: #selector(navigationRightButtonAction) ) } @objc private func navigationRightButtonAction() { presenter?.doneButtonWasTapped(descriptionSelected: nameEditText.text ?? "") } private func configureViews() { view.addSubview(nameLabel) view.addSubview(nameEditText) } private func configureConstraints() { nameLabel.snp.makeConstraints { $0.top.equalTo(view.safeAreaLayoutGuide.snp.top).offset(20) $0.leading.equalTo(view.safeAreaLayoutGuide.snp.leading).offset(20) $0.trailing.equalTo(view.safeAreaLayoutGuide.snp.trailing).offset(-20) } nameEditText.snp.makeConstraints { $0.top.equalTo(nameLabel.snp.top).offset(20) $0.leading.equalTo(view.safeAreaLayoutGuide.snp.leading).offset(20) $0.trailing.equalTo(view.safeAreaLayoutGuide.snp.trailing).offset(-20) } } }
// // ViewController.swift // Concentration // // Created by Марина on 25.12.2019. // Copyright © 2019 Marina Potashenkova. All rights reserved. // import UIKit class ViewController: UIViewController { private var game: Concentration! var numberOfPairsOfCards: Int { return (cardButtons.count + 1) / 2 } var theme: String! @IBOutlet private weak var flipCountLabel: UILabel! @IBOutlet private weak var scoreLabel: UILabel! @IBOutlet private var cardButtons: [UIButton]! @IBAction private func touchCard(_ sender: UIButton) { if let cardNumber = cardButtons.firstIndex(of: sender) { game.chooseCard(at: cardNumber) updateViewFromModel() } else { print("choosen card was not in cardButton") } } @IBAction private func startNewGame(_ sender: UIButton) { initialSetup() } private func updateViewFromModel() { flipCountLabel.text = "Flips: \(game.flipCount)" scoreLabel.text = "Score: \(game.score)" for index in cardButtons.indices { let button = cardButtons[index] let card = game.cards[index] if card.isFaceUp { button.setTitle(emoji(for: card), for: .normal) button.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0) } else { button.setTitle("", for: .normal) button.backgroundColor = card.isMatched ? #colorLiteral(red: 1, green: 0.5763723254, blue: 0, alpha: 0) : #colorLiteral(red: 1, green: 0.5763723254, blue: 0, alpha: 1) } } } private func initialSetup() { let themes = Array(emojiThemes.keys) theme = themes[Int(arc4random_uniform(UInt32(themes.count)))] emojiChoices = emojiThemes[theme] ?? [] game = Concentration(numberOfPairsOfCards: (cardButtons.count + 1) / 2) updateViewFromModel() } private let emojiThemes = [ "halloween" : ["🦇", "😱", "🙀", "😈", "🎃", "👻", "🍭", "🍬", "🍎"], "animals" : ["🐶", "🐱", "🐭", "🐰", "🦊", "🐻", "🦄", "🦁", "🐷"], "food" : ["🍏", "🍎", "🍐", "🍊", "🍋", "🍌", "🍉", "🍇", "🍓"], "sport" : ["⚽️", "🏀", "🏈", "⚾️", "🎾", "🏓", "🏸", "🏒", "🥊"], "transport" : ["🚗", "🚕", "🚌", "🚎", "🚂", "✈️", "🚀", "🚁", "⛴"], "emotions" : ["😄", "😳", "😍", "😭", "😤", "😪", "😱", "😏", "😛"] ] private var emojiChoices: [String]! private var emoji = [Int: String]() private func emoji(for card: Card) -> String { if emoji[card.identifier] == nil, emojiChoices.count > 0 { emoji[card.identifier] = emojiChoices.remove(at: emojiChoices.count.arc4random) } return emoji[card.identifier] ?? "?" } override func viewDidLoad() { super.viewDidLoad() initialSetup() } } extension Int { var arc4random: Int { if self > 0 { return Int(arc4random_uniform(UInt32(self))) } else if self < 0 { return -Int(arc4random_uniform(UInt32(abs(self)))) } else { return 0 } } }
let slides = Slides(pages: [ Cover(title: "The Architecture of LLVM", bulletPoints: ["yan.li@ef.com"]), Image(title: "images/LLVM-logo.png", bulletPoints: [ "竜神の剣を喰らえ", "Ryūjin no ken o kurae", ]), Page(title: "What is LLVM?", bulletPoints: [ "The name LLVM was once an acronym for:", " Low Level Virtual Machine", "Begins in December 2000", " Designed as a set of reusable libs...", " ...with well-defined interfaces", "Now, LLVM is an umbrella project for:", " llvm - the compiler", " clang - the C family frontend", " lldb - the debugger", " libc++ - the C++ STL implementation", " lld - the linker", " and more...", ]), Page(title: "Classical Compiler Design", bulletPoints: [ "Frontend", " Source Code -> Lexer -> Token", " Token -> Parser -> Abstract Syntax Tree", "Optimizer", " AST -> Optimizer -> AST", "Backend", " AST -> Code Generator -> Target Instructions", ]), Image(title: "images/RetargetableCompiler.png", bulletPoints: ["Retargetablity"]), Page(title: "Before LLVM", bulletPoints: [ "The benifits of a three-phase design was never fully realized", "Java and .NET virtual machines", " JIT compiler + a runtime + a bytecode format as media", " Enforces JIT compilation and GC, leads to subopimal performance", "Translate source code to C", " Perhaps the most unfortunate, but also most popular way", " Source Code -> C Code -> C Compiler", " Poor debugging, slow compilation, feature constrained by C", "GNU C Compiler (GCC)", " Supports many frontends and backends", " GCC can only be used as a whole", " This is due to some architectural problems from its early design", ]), Image(title: "images/LLVMCompiler.png", bulletPoints: [ "LLVM's Three-Phase Compiler Design", ]), Page(title: "LLVM's Three-Phase Compiler Design", bulletPoints: [ "Frontend", " Source code -> Parsing and Emit Errors -> AST", " AST -> LLVM IR", "Optimizer", " LLVM IR -> Optimization Passes -> LLVM IR", "Backend", " LLVM IR -> Code Generator -> Instructions", ]), Page(title: "LLVM IR", bulletPoints: [ "A low-level RISC-like virtual instruction set", "Strongly typed", "Uses temporaries with a % prefix", " Rather than %rax, %rbp, %rip, etc", "Three forms of LLVM IR", " Textual format (.ll)", " In-memory data structure", " Binary format, bitcode (.bc)", "No programming language or target constraints", "Good for the optimizer to do its job", ]), Cover(title: "clang -S -emit-ir", bulletPoints: ["An example of LLVM IR"]), Page(title: "IR is a complete representation", bulletPoints: [ "IR represents everything in the code", " GCC GIMPLE references back to the source level tree data", "In practice", " -> Frontend -> LLVM IR", " -> Unix Pipline", " -> Optimizer Sequence -> Code Generator", ]), Page(title: "LLVM is a collection of libs", bulletPoints: [ "Optimization Passes", " IR -> Pass -> .. -> Pass -> IR", " -O0, no passes", " -O3, 67 passes", "Written in C++, built into static libs", "Can be referenced by a minimum subset", ]), Page(title: "The LLVM Code Generator", bulletPoints: [ "Collect target infos into a target description file (.td)", ".td -> Assembler/Disassembler", " IR -> Assembler -> Machine Code", "x86_64.td -> x86_64_assembler", " IR -> x86_64_assembler -> x86_64 executable" ]), Page(title: "Extra Benefits of the Design", bulletPoints: [ "Link time optimization", "Install time optimization", " Apple App Thinning", "Unit testing", ]), Page(title: "Retrospective and the Future", bulletPoints: [ "The design was developed by self-defense", "The API changes often without backwards compatibility", " Swift", "Make things more modular", " Code Generator", ]), Page(title: "Swift and LLVM", bulletPoints: [ "Chris Lattner:", " Swift is really just a syntax sugar for LLVM IR.", "SIL, Swift Intermediate Language", " Higher level than LLVM IR, more sementically aware", " Enables more useful diagnoses and optimizations", "*.swift -> Parser -> AST -> SIL -> IR -> *.o", " Encourages more language-specific IR (e.g. C++)", ]), Cover(title: "swiftc -emit-sil", bulletPoints: ["An Example of SIL"]), Cover(title: "Q&A", bulletPoints: []), Cover(title: "Who's next?", bulletPoints: []), ])
// // RootNavigationViewController.swift // WorkTest // // Created by wxqdev on 14-10-15. // Copyright (c) 2014年 wxqdev. All rights reserved. // import UIKit var globals_attributes = [ NSForegroundColorAttributeName: UIColor.whiteColor(), //NSFontAttributeName: UIFont(name: "AvenirNext-Medium", size: 18)! NSFontAttributeName: UIFont.boldSystemFontOfSize(20) ] class RootNavigationViewController: UINavigationController ,UINavigationControllerDelegate{ // let arraytilte = ["首页标题","第二个标题","第三个标题"] // let arrayurl = ["http://i.meituan.com/","http://i.meituan.com/jiudian/touch/poi_prepose?stid=_b1&cevent=imt%2Fhomepage%2Fcategory1%2F20","http://i.meituan.com/nanjing?cid=10&stid=_b1&cateType=poi"] var tabindex = 0 override func viewDidLoad() { super.viewDidLoad() self.delegate = self self.navigationBar.barTintColor = UIColor.colorWithHex("#f96429") self.navigationBar.titleTextAttributes = globals_attributes // if(self.viewControllers[0] is WebPageViewController){ // let vc = self.viewControllers[0] as! WebPageViewController // vc.url = arrayurl[tabindex] // vc.title = arraytilte[tabindex] // } // } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func navigationController(navigationController: UINavigationController, willShowViewController viewController: UIViewController, animated: Bool){ if(viewController is TabIndexTuangouViewController || viewController is TabIndexShangjiaViewController || viewController is TabIndexWodeViewController || viewController is TabIndexGengduoViewController ){ self.navigationBarHidden = false if(viewController is TabIndexWodeViewController){ } else{ viewController.navigationItem.leftBarButtonItem = nil viewController.navigationItem.hidesBackButton = true viewController.navigationItem.rightBarButtonItem = nil } } if(viewController is WebPageViewController){ let vc = viewController as! WebPageViewController if(self.navigationBarHidden){ //显示导航条 self.navigationBarHidden = false } if(vc.level == 0){ viewController.navigationItem.leftBarButtonItem = nil viewController.navigationItem.hidesBackButton = true viewController.navigationItem.rightBarButtonItem = nil } else{ var btnBack = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton btnBack.frame = CGRectMake(0, 0, 32, 32); btnBack.setBackgroundImage(UIImage(named: "fh"), forState: UIControlState.Normal) btnBack.addTarget(self, action: "onClickBack:", forControlEvents: UIControlEvents.TouchUpInside) var leftBarButtonItem = UIBarButtonItem(customView:btnBack) leftBarButtonItem.tintColor = UIColor.colorWithHex("#f96429") viewController.navigationItem.leftBarButtonItem = leftBarButtonItem } } if(viewController is SearchIndexViewController){ self.navigationBarHidden = false var btnBack = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton btnBack.frame = CGRectMake(0, 0, 32, 32); btnBack.setBackgroundImage(UIImage(named: "fh"), forState: UIControlState.Normal) btnBack.addTarget(self, action: "onClickBack:", forControlEvents: UIControlEvents.TouchUpInside) var leftBarButtonItem = UIBarButtonItem(customView:btnBack) leftBarButtonItem.tintColor = UIColor.colorWithHex("#f96429") viewController.navigationItem.leftBarButtonItem = leftBarButtonItem } } func onClickBack(sender: UIViewController) { self.popViewControllerAnimated(true) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
// // ViewController.swift // not100 // // Created by Eriri Matsui on 2017/05/03. // Copyright © 2017年 Eriri Matsui. All rights reserved. // import UIKit class ViewController: UIViewController { var totalNumber: Int = 0 var countNumber: Int = 0 var turnCount: Int = 0 var peopleCount: Int = 1 var playpeopleCount2: Int = 1 var playNumber2: Int = 0 var totalNumberArray: [Int] = [] var number: Int! var skillNumber: Int = 0 var nameArray: [String] = [] var notNumber: Int = 0 let userDefaults = UserDefaults.standard @IBOutlet var label: UILabel! @IBOutlet var peopleLabel: UILabel! @IBOutlet var skillLabel: UILabel! @IBOutlet var skillLabel2: UILabel! @IBOutlet var skillLabel3: UILabel! @IBOutlet var skillLabel4: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. // label.layer.borderWidth = 3.0 // label.layer.borderColor = UIColor.black.cgColor // label.layer.cornerRadius = 10.0 print(playpeopleCount2) print(playNumber2) skillLabel.isHidden = true skillLabel2.isHidden = true skillLabel3.isHidden = true skillLabel4.isHidden = true peopleLabel.text = nameArray[0] notNumber = userDefaults.integer(forKey: "notNumber") print(notNumber) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func plus() { skillLabel.isHidden = true skillLabel2.isHidden = true skillLabel3.isHidden = true skillLabel4.isHidden = true skillNumber = Int(arc4random_uniform(20)) if totalNumber < notNumber && countNumber < 3 { totalNumber = totalNumber + 1 label.text = String(totalNumber) countNumber = countNumber + 1 if totalNumber == notNumber{ performSegue(withIdentifier: "goNext", sender: nil) } if skillNumber == 3 { totalNumber = totalNumber - 3 skillLabel.isHidden = false skillLabel.text = "3" skillLabel2.isHidden = false skillLabel3.isHidden = false skillLabel4.isHidden = false } if skillNumber == 4 { totalNumber = totalNumber - 2 skillLabel.isHidden = false skillLabel.text = "2" skillLabel2.isHidden = false skillLabel3.isHidden = false skillLabel4.isHidden = false } } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let finalViewController = segue.destination as! FinalViewController finalViewController.text1 = peopleLabel.text } @IBAction func changeTurn() { skillLabel.isHidden = true skillLabel2.isHidden = true skillLabel3.isHidden = true skillLabel4.isHidden = true countNumber = 0 turnCount = turnCount + 1 peopleLabel.text = nameArray[turnCount % playpeopleCount2] } }
// // EditPostController.swift // Instagram // // Created by Fahad Almehawas on 5/12/17. // Copyright © 2017 Fahad Almehawas. All rights reserved. // import UIKit import Firebase class EditPostController: UICollectionViewController, EditPostCellDelegate { let editCellId = "Cellid" override func viewDidLoad() { super.viewDidLoad() collectionView?.backgroundColor = .white collectionView?.register(EditPostCell.self, forCellWithReuseIdentifier: editCellId) setupNavItems() } var post: Post? var caption: String? func setupNavItems() { navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(handleCancel)) navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(handleDone)) navigationItem.title = "Edit Info" navigationItem.leftBarButtonItem?.tintColor = .black navigationItem.rightBarButtonItem?.tintColor = .black } @objc func handleCancel() { dismiss(animated: true, completion: nil) } @objc func handleDone() { guard let uid = post?.user.uid else {return} guard let postId = post?.id else {return} guard let text = caption else {return} let ref = Database.database().reference().child("posts").child(uid).child(postId).child("caption") ref.setValue(text) { (err, _) in if err != nil { print("Failed to edit Post:", err?.localizedDescription ?? "") return } print("Successfully edited Post Caption!") self.dismiss(animated: true, completion: { self.postNotifications() }) } } func didChangeText(text: String) { caption = text } //updates user profile controller UI func postNotifications() { let name: Notification.Name = Notification.Name(rawValue: "Notification") NotificationCenter.default.post(name: name, object: self, userInfo: nil) } }
// // SelectQuestionGroupViewController.swift // Pruebas // // Created by Julio Banda on 7/29/19. // Copyright © 2019 Julio Banda. All rights reserved. // import UIKit class SelectQuestionGroupViewController: UIViewController { // MARK: Outlets @IBOutlet internal var tableView: UITableView! { didSet { tableView.tableFooterView = UIView() } } // MARK: Properties private let questionGroupTaker = QuestionGroupCaretaker() public var questionGroups: [QuestionGroup] { return questionGroupTaker.questionGroups } private var selectedQuestionGroup: QuestionGroup! { get { return questionGroupTaker.selectedQuestionGroup } set { questionGroupTaker.selectedQuestionGroup = newValue } } private let appSettings = AppSettings.shared } extension SelectQuestionGroupViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return questionGroups.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "QuestionGroupCell", for: indexPath) as! QuestionGroupCell let questionGroup = questionGroups[indexPath.row] cell.titleLabel.text = questionGroup.title return cell } } extension SelectQuestionGroupViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? { selectedQuestionGroup = questionGroups[indexPath.row] return indexPath } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) } public override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard let viewController = segue.destination as? QuestionsViewController else { return } viewController.questionStrategy = appSettings.questionStrategy(for: questionGroupTaker) viewController.delegate = self } } extension SelectQuestionGroupViewController: QuestionViewControllerProtocol { func questionViewController(_ viewController: QuestionsViewController, didCancel questionGroup: QuestionStrategy, at questionIndex: Int) { navigationController?.popToViewController(self, animated: true) } func questionViewController(_ viewController: QuestionsViewController, didComplete questionGroup: QuestionStrategy) { navigationController?.popToViewController(self, animated: true) } }
// // FavoritesViewController.swift // CoreData-Lab // // Created by Juan Ceballos on 4/19/20. // Copyright © 2020 Juan Ceballos. All rights reserved. // import UIKit class FavoritesViewController: UIViewController { let favoritesView = FavoritesView() override func loadView() { view = favoritesView } var favorites = [Favorite]() { didSet { DispatchQueue.main.async { self.favoritesView.favoritesCollectionView.reloadData() } } } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .systemOrange navigationItem.title = "Favorites" favoritesView.favoritesCollectionView.register(FavoriteCell.self, forCellWithReuseIdentifier: "favoriteCell") favoritesView.favoritesCollectionView.dataSource = self favoritesView.favoritesCollectionView.delegate = self fetchFavoritePhotos() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(true) fetchFavoritePhotos() } private func fetchFavoritePhotos() { favorites = CoreDataManager.shared.fetchFavorites() } } extension FavoritesViewController: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return favorites.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "favoriteCell", for: indexPath) as? FavoriteCell else { fatalError() } let favorite = favorites[indexPath.row] cell.configureCell(favorite: favorite) return cell } } extension FavoritesViewController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let maxSize: CGSize = UIScreen.main.bounds.size let itemWidth: CGFloat = maxSize.width let itemHeight: CGFloat = maxSize.height * 0.40 return CGSize(width: itemWidth, height: itemHeight) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let vc = DetailFavoritesViewController() let favorite = favorites[indexPath.row] print(favorite.description) print(favorite.tags ?? "frfef") vc.favorite = favorite navigationController?.pushViewController(vc, animated: true) } }
// // PasswordListController.swift // SudoLikeAnOP // // Created by Russell Teabeault on 11/21/18. // Copyright © 2018 Russell Teabeault. All rights reserved. // import Cocoa class PasswordListController: NSViewController { @IBOutlet weak var tableView: NSTableView! let passwords = ["Gnip Sudo", "Synology Sudo", "Your mother"] override func viewDidLoad() { super.viewDidLoad() print("ViewDidLoad") tableView.delegate = self tableView.dataSource = self // Do view setup here. tableView.reloadData() } } extension PasswordListController: NSTableViewDataSource { func numberOfRows(in tableView: NSTableView) -> Int { print("Getting number of rows") return passwords.count } } extension PasswordListController: NSTableViewDelegate { fileprivate enum CellIdentifiers { static let NameCell = "PasswordCellID" } func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { // var image: NSImage? var text: String = "" var cellIdentifier: String = "" let dateFormatter = DateFormatter() dateFormatter.dateStyle = .long dateFormatter.timeStyle = .long let item = passwords[row] if tableColumn == tableView.tableColumns[0] { text = item cellIdentifier = CellIdentifiers.NameCell } if let cell = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(cellIdentifier), owner: nil) as? NSTableCellView { cell.textField?.stringValue = text // cell.imageView?.image = image ?? nil return cell } return nil } }
// // ViewController.swift // ticket-provider-ios // // Created by Suwijak Chaipipat on 5/1/2559 BE. // Copyright © 2559 Suwijak Chaipipat. All rights reserved. // import UIKit class TPSplashScreenViewController: UIViewController { @IBOutlet weak var progressBar: UIProgressView! override func viewDidLoad() { super.viewDidLoad() self.navigationController?.navigationBar.hidden = true self.progressBar?.setProgress(Float(0), animated: false) NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(TPSplashScreenViewController.updateProgress), userInfo: nil, repeats: true) let accessToken = NSUserDefaults.standardUserDefaults().valueForKey(TPConstants.ACCESS_TOKEN) let tokenType = NSUserDefaults.standardUserDefaults().valueForKey(TPConstants.TOKEN_TYPE) if accessToken != nil && tokenType != nil { TPHttpManager.sharedInstance.currentUser({ responseCode, data in self.navigateToTicketList() }, errorBlock: { responseCode in self.navigateToLogin() }) } else { self.navigateToLogin() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func navigateToLogin() { let storyBoard = UIStoryboard(name: "Main", bundle: nil) let loginVC = storyBoard.instantiateViewControllerWithIdentifier("TPLogin") as! TPLoginViewController self.navigationController?.pushViewController(loginVC, animated: false) } func navigateToTicketList() { let storyBoard = UIStoryboard(name: "Main", bundle: nil) let ticketListVC = storyBoard.instantiateViewControllerWithIdentifier("TPTicketList") as! TPTicketListViewController self.navigationController?.pushViewController(ticketListVC, animated: false) } func updateProgress() { self.progressBar?.setProgress((progressBar?.progress)! + 0.5, animated: true) } }
import Foundation extension PDFViewModel { enum Strings { static let dateFormat = "dd.MM.yyyy" static let pdfExtension = ".pdf" static let noIdFilename = "no-id" static let filenamePrefix = "Water Bill " static let logoImageName = "Logo-Letterhead-Horizontal" static let title = "Jenin Residences" static let subtitle = "In-House Water Bill" static let address = "H. Jenin (Ground Floor)\nAbadhah Fehi Magu\nK. Malé 20081" static let contact = "T: (+960) 332 7631,\n (+960) 332 7636\nF: (+960) 332 7620" } }
// // CalendarViewController.swift // bm-persona // // Created by Oscar Bjorkman on 2/2/20. // Copyright © 2020 RJ Pimentel. All rights reserved. // import UIKit import Firebase fileprivate let kCardPadding: UIEdgeInsets = UIEdgeInsets(top: 16, left: 16, bottom: 16, right: 16) fileprivate let kViewMargin: CGFloat = 16 fileprivate let kBookingURL = "https://berkeley.libcal.com" class LibraryDetailViewController: SearchDrawerViewController { var library : Library! var overviewCard: OverviewCardView! var openTimesCard: OpenTimesCardView? var occupancyCard: OccupancyGraphCardView? override func viewDidLoad() { super.viewDidLoad() setUpScrollView() setUpOverviewCard() setUpOpenTimesCard() setUpOccupancyCard() setUpBookButton() setupDescriptionCard() } override func viewDidLayoutSubviews() { /* Set the bottom cutoff point for when the drawer appears The "middle" position for the view will show everything in the overview card When collapsible open time card is added, change this to show that card as well. */ middleCutoffPosition = (openTimesCard?.frame.maxY ?? overviewCard.frame.maxY) + scrollingStackView.yOffset + 8 } /// Opens `kBookingURL` in Safari. @objc private func bookButtonClicked(sender: UIButton) { guard let url = URL(string: kBookingURL) else { return } presentAlertLinkUrl(title: "Are you sure you want to open Safari?", message: "Berkeley Mobile wants to open Libcal to book a study room", website_url: url) } var scrollingStackView: ScrollingStackView = { let scrollingStackView = ScrollingStackView() scrollingStackView.scrollView.showsVerticalScrollIndicator = false scrollingStackView.stackView.spacing = kViewMargin return scrollingStackView }() var bookButton: ActionButton = { let button = ActionButton(title: "Book a Study Room") button.addTarget(self, action: #selector(bookButtonClicked), for: .touchUpInside) return button }() } extension LibraryDetailViewController { func setUpOverviewCard() { overviewCard = OverviewCardView(item: library, excludedElements: [.openTimes, .occupancy]) overviewCard.heightAnchor.constraint(equalToConstant: 200).isActive = true scrollingStackView.stackView.addArrangedSubview(overviewCard) } func setUpOpenTimesCard() { guard library.weeklyHours != nil else { return } openTimesCard = OpenTimesCardView(item: library, animationView: scrollingStackView, toggleAction: { open in if open, self.currState != .full { self.delegate.moveDrawer(to: .full) } }, toggleCompletionAction: nil) guard let openTimesCard = self.openTimesCard else { return } scrollingStackView.stackView.addArrangedSubview(openTimesCard) } func setUpOccupancyCard() { guard let occupancy = library.occupancy, let forDay = occupancy.occupancy(for: DayOfWeek.weekday(Date())), forDay.count > 0 else { return } occupancyCard = OccupancyGraphCardView(occupancy: occupancy, isOpen: library.isOpen) guard let occupancyCard = self.occupancyCard else { return } scrollingStackView.stackView.addArrangedSubview(occupancyCard) } func setupDescriptionCard() { guard let descriptionCard = DescriptionCardView(description: library.description) else { return } scrollingStackView.stackView.addArrangedSubview(descriptionCard) } func setUpBookButton() { scrollingStackView.stackView.addArrangedSubview(bookButton) } func setUpScrollView() { scrollingStackView.scrollView.drawerViewController = self scrollingStackView.scrollView.setupDummyGesture() scrollingStackView.setLayoutMargins(UIEdgeInsets(top: 8, left: 16, bottom: 8, right: 16)) view.addSubview(scrollingStackView) scrollingStackView.topAnchor.constraint(equalTo: barView.bottomAnchor, constant: kViewMargin).isActive = true scrollingStackView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true scrollingStackView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true scrollingStackView.bottomAnchor.constraint(equalTo: view.layoutMarginsGuide.bottomAnchor).isActive = true } } // MARK: - Analytics extension LibraryDetailViewController { override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) Analytics.logEvent("opened_library", parameters: ["library" : library.name]) } }
// // ZXDiscoverViewModel.swift // YDHYK // // Created by screson on 2017/11/3. // Copyright © 2017年 screson. All rights reserved. // import UIKit class ZXDiscoverViewModel: NSObject { static func loadList(pageNum: Int, pageSize: Int, completion: ((_ success: Bool,_ code: Int,_ list: [ZXDiscoverModel]?,_ errorMsg: String) -> Void)?) { ZXNetwork.asyncRequest(withUrl: ZXAPI.api(address: ZXAPIConst.Discover.list), params: ["pageNum": pageNum, "pageSize": pageSize].zx_signDic(), method: .post) { (s, c, obj, _, error) in if s { if let data = obj["data"] as? Dictionary<String,Any>,let list = data["listData"] as? Array<Dictionary<String,Any>> { var dList: Array<ZXDiscoverModel> = [] for m in list { if let discover = ZXDiscoverModel.mj_object(withKeyValues: m) { dList.append(discover) } } completion?(s,c,dList,"") } else { completion?(s,c,[],"无相关数据") } } else { completion?(s,c,nil,error?.errorMessage ?? "") } } } /// 发现-详情 /// /// - Parameters: /// - promotionId: /// - completion: static func loadDetail(promotionId: String, completion: ((_ success: Bool,_ code: Int,_ model: ZXDiscoverModel?,_ errorMsg: String) -> Void)?) { ZXNetwork.asyncRequest(withUrl: ZXAPI.api(address: ZXAPIConst.Discover.detail), params: ["promotionId": promotionId].zx_signDic(), method: .post) { (s, c, obj, _, error) in if s { if let data = obj["data"] as? Dictionary<String,Any> { completion?(s,c,ZXDiscoverModel.mj_object(withKeyValues: data),"") } else { completion?(s,c,nil,"无相关数据") } } else { completion?(s,c,nil,error?.errorMessage ?? "") } } } }
// // SideDrawerCustomTransition.swift // TelerikUIExamplesInSwift // // Copyright (c) 2015 Telerik. All rights reserved. // class SideDrawerCustomTransition: SideDrawerGettingStarted { override func viewDidLoad() { super.viewDidLoad() let sideDrawer = self.sideDrawerView.sideDrawers[0] sideDrawer.fill = TKSolidFill(color: UIColor.grayColor()) // >> drawer-transition-manager-swift sideDrawer.transitionManager = MyTransition(sideDrawer: sideDrawer) // << drawer-transition-manager-swift sideDrawer.headerView = SideDrawerHeaderView(addButton: false, target: nil, selector: nil) } }
import SwiftUI struct NameTextField: View { @Binding var firstName: String @Binding var lastName: String var body: some View { HStack { VStack{ HStack{ TextField(TEXT_FIRSTNAME, text: $firstName) }.modifier(TextFieldModifier()) Divider().modifier(DividerShort()) } VStack{ HStack{ TextField(TEXT_LASTNAME, text: $lastName) }.modifier(TextFieldModifier()) Divider().modifier(DividerShort()) } } } }
class Solution { class func majorityElement(_ nums: [Int]) -> Int { var temp = nums[0] var result = 1 for i in 1..<nums.count { result += nums[i] == temp ? 1 : -1 if result == 0 { temp = nums[i + 1] } } return temp } }
// // FormDetailTableView.swift // projectForm // // Created by 林信沂 on 2020/12/31. // import UIKit class FormDetailTableView: UITableView { override init(frame: CGRect, style: UITableView.Style) { super.init(frame: frame, style: style) self.register(FormDetailTableViewCell.self, forCellReuseIdentifier: "FormDetailTableViewCell") self.backgroundColor = .white self.delegate = FormDetailViewModel.sharedInstance self.dataSource = FormDetailViewModel.sharedInstance } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
// // TableViewPagination.swift // Sberleasing // // Created by Пользователь on 25/02/2019. // Copyright © 2019 Sberbank Leasing Frontend System. All rights reserved. // import Foundation // MARK: PaginationModel protocol TableViewPaginationModelProtocol { var current: Int { get set } var count: Int { get set } var limit: Int { get set } var items: Int { get set } } class TableViewPaginationModel: TableViewPaginationModelProtocol { var current: Int var count: Int var limit: Int var items: Int init(current: Int = 1, count: Int = 0, limit: Int = 0, items: Int = 0) { self.current = current self.count = count self.limit = limit self.items = items } static func initial(current: Int, count: Int, limit: Int) -> TableViewPaginationModelProtocol { return TableViewPaginationModel(current: current, count: count, limit: limit) } }
// // LoginViewController.swift // PChat // // Created by Yawen on 23/2/2017. // Copyright © 2017 YangSzu Kai. All rights reserved. // import UIKit import Parse extension CGRect{ init(_ x:CGFloat,_ y:CGFloat,_ width:CGFloat,_ height:CGFloat) { self.init(x:x,y:y,width:width,height:height) } } class LoginViewController: UIViewController,UITextFieldDelegate { @IBOutlet weak var emailTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var signUpButton: UIButton! @IBOutlet weak var loginButton: UIButton! override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor(patternImage: UIImage(named: "asses.png")!) self.passwordTextField.delegate=self self.emailTextField.delegate=self let tap:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(LoginViewController.DismissKeyboard)) self.view.addGestureRecognizer(tap) //signUpButton.backgroundColor = UIColor(white:0.000, alpha:0.07) let borderAlpha : CGFloat = 0.7 let cornerRadius : CGFloat = 5.0 signUpButton.frame = CGRect(100, 100, 200, 40) signUpButton.setTitle("Sign Up", for: UIControlState.normal) signUpButton.setTitleColor(UIColor.white, for: UIControlState.normal) signUpButton.backgroundColor = UIColor(white:0.000, alpha:0.07) signUpButton.layer.borderWidth = 1.0 signUpButton.layer.borderColor = UIColor(white: 1.0, alpha: borderAlpha).cgColor signUpButton.layer.cornerRadius = cornerRadius loginButton.frame = CGRect(100, 100, 200, 40) loginButton.setTitle("Login", for: UIControlState.normal) loginButton.setTitleColor(UIColor.white, for: UIControlState.normal) loginButton.backgroundColor = UIColor(white:0.000, alpha:0.07) loginButton.layer.borderWidth = 1.0 loginButton.layer.borderColor = UIColor(white: 1.0, alpha: borderAlpha).cgColor loginButton.layer.cornerRadius = cornerRadius /* let alertController = UIAlertController(title: "Error", message: "Failed to signup", preferredStyle: .alert) // let cancelAction = UIAlertAction(title: "OK", style: .cancel) { (action) in} // alertController.addAction(cancelAction) let OKAction = UIAlertAction(title: "OK", style: .default) { (action) in } alertController.addAction(OKAction) present(alertController, animated: true) { } */ // Do any additional setup after loading the view. } @IBAction func onSignUp(_ sender: Any) { signUp() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func presentChatView() { let mainStoryboard = UIStoryboard(name: "Main", bundle: nil) let chatView = mainStoryboard.instantiateViewController(withIdentifier: "ChatViewController") present(chatView, animated: true, completion: nil) } @IBAction func onLogin(_ sender: Any) { /* do{ try PFUser.logIn(withUsername: emailTextField.text!, password: passwordTextField.text!) } catch{ let alertController = UIAlertController(title: "Error", message: "Failed to login", preferredStyle: .alert) let OKAction = UIAlertAction(title: "OK", style: .default) { (action) in } alertController.addAction(OKAction) present(alertController, animated: true) { } }*/ PFUser.logInWithUsername(inBackground: emailTextField.text!, password: passwordTextField.text!) { (response: PFUser?, error: Error?) in if let error = error { //error print(error.localizedDescription) let alertController = UIAlertController(title: "Error", message: "\(error.localizedDescription)" , preferredStyle: .alert) let OKAction = UIAlertAction(title: "OK", style: .default) { (action) in } alertController.addAction(OKAction) self.present(alertController, animated: true) { } } else { self.presentChatView() } } } func signUp() { let user = PFUser() user.username = emailTextField.text user.password = passwordTextField.text //user.email = emailTextField.text // other fields can be set just like with PFObject //user["phone"] = "415-392-0202" user.signUpInBackground { (succeded, error) in if let error = error { let alertController = UIAlertController(title: "Error", message: "\(error.localizedDescription)", preferredStyle: .alert) print(error.localizedDescription) let OKAction = UIAlertAction(title: "OK", style: .default) { (action) in } alertController.addAction(OKAction) self.present(alertController, animated: true) { } // Show the errorString somewhere and let the user try again. } else { print("sign up!!") // Hooray! Let them use the app now. // Go to next screen self.presentChatView() } } } func textFieldShouldReturn(_ textField: UITextField) -> Bool // called when 'return' key pressed. return NO to ignore. { textField.resignFirstResponder() return true; } func DismissKeyboard(){ self.view.endEditing(true) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
import RxSwift import RxRelay import RxCocoa class AddEvmSyncSourceViewModel { private let service: AddEvmSyncSourceService private let disposeBag = DisposeBag() private let urlCautionRelay = BehaviorRelay<Caution?>(value: nil) private let finishRelay = PublishRelay<Void>() init(service: AddEvmSyncSourceService) { self.service = service } } extension AddEvmSyncSourceViewModel { var urlCautionDriver: Driver<Caution?> { urlCautionRelay.asDriver() } var finishSignal: Signal<Void> { finishRelay.asSignal() } func onChange(url: String?) { service.set(urlString: url ?? "") urlCautionRelay.accept(nil) } func onChange(basicAuth: String?) { service.set(basicAuth: basicAuth ?? "") } func onTapAdd() { do { try service.save() finishRelay.accept(()) } catch AddEvmSyncSourceService.UrlError.alreadyExists { urlCautionRelay.accept(Caution(text: "add_evm_sync_source.warning.url_exists".localized, type: .warning)) } catch AddEvmSyncSourceService.UrlError.invalid { urlCautionRelay.accept(Caution(text: "add_evm_sync_source.error.invalid_url".localized, type: .error)) } catch { } } }
public enum CoinSettingType: String, CaseIterable { case derivation case bitcoinCashCoinType } typealias CoinSettings = [CoinSettingType: String] extension CoinSettings: Identifiable { public typealias ID = String public init(id: ID) { var settings = CoinSettings() let chunks = id.split(separator: "|") for chunk in chunks { let subChunks = chunk.split(separator: ":") guard subChunks.count == 2 else { continue } guard let type = CoinSettingType(rawValue: String(subChunks[0])) else { continue } settings[type] = String(subChunks[1]) } self = settings } public var id: ID { var chunks = [String]() for type in CoinSettingType.allCases { if let value = self[type] { chunks.append("\(type.rawValue):\(value)") } } return chunks.joined(separator: "|") } } extension CoinSettings { var derivation: MnemonicDerivation? { self[.derivation].flatMap { MnemonicDerivation(rawValue: $0) } } var bitcoinCashCoinType: BitcoinCashCoinType? { self[.bitcoinCashCoinType].flatMap { BitcoinCashCoinType(rawValue: $0) } } var order: Int { if let derivation = derivation { return derivation.order } else if let bitcoinCashCoinType = bitcoinCashCoinType { return bitcoinCashCoinType.order } else { return 0 } } }
// // ViewController.swift // Login // // Created by Souley on 06/12/2018. // Copyright © 2018 Souley. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var userNameEntryTextField: UITextField! @IBOutlet weak var forgotUserNameButton: UIButton! @IBOutlet weak var forgotPasswordButton: UIButton! @IBOutlet weak var loginButton: UIButton! override func viewDidLoad() { super.viewDidLoad() } @IBAction func forgotUserNameButton(_ sender: UIButton) { performSegue(withIdentifier: "landingRed", sender: forgotUserNameButton) } @IBAction func forgotUserPasswordButton(_ sender: UIButton) { performSegue(withIdentifier: "landingRed", sender: forgotPasswordButton) } @IBAction func loginButton(_ sender: UIButton) { performSegue(withIdentifier: "landingRed", sender: loginButton) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard let sender = sender as? UIButton else {return} if sender == forgotPasswordButton { segue.destination.navigationItem.title = "Forgot Passeword" } else if sender == forgotUserNameButton { segue.destination.navigationItem.title = "Forgot Username" } else { segue.destination.navigationItem.title = userNameEntryTextField.text } } @IBAction func unwindToLogin(unwindSegue: UIStoryboardSegue) { } }
// // KeyboardDelegate.swift // journal // // Created by Diqing Chang on 11.04.18. // Copyright © 2018 Diqing Chang. All rights reserved. // import UIKit // The view controller will adopt this protocol (delegate) // and thus must contain the keyWasTapped method protocol KeyboardDelegate: class { func keyWasTapped(color: UIColor) //func touchblockKeyTapped(fileName: String, isAppended: Bool) func cutomKeyTapped(keyId: String) }
// // MNToolButton.swift // Moon // // Created by YKing on 16/6/10. // Copyright © 2016年 YKing. All rights reserved. // import UIKit class MNToolButton: UIButton { override func layoutSubviews() { super.layoutSubviews() let paddingW: CGFloat = 20 let paddingH: CGFloat = 23 let imageWidth:CGFloat = self.width - 2 * paddingW let imageH:CGFloat = self.height - 2 * paddingH self.imageView?.frame = CGRect(x: paddingW, y: paddingH, width: imageWidth, height: imageH) } }
// // BWIcon.swift // IconMagick // // Created by wangzhi on 2019/11/23. // Copyright © 2019 BTStudio. All rights reserved. // import Cocoa /// 图标模型 class BWIcon { /// 适用设备的类型 var idiom: String? /// 大小 (pt) var size: Float = 0.0 /// 倍数 (几倍图) var scale: Float = 1.0 /// 用途 var use: String? /// 适用系统版本的描述 var system_version: String? /** * 1. 计算属性并不存储实际的值,而是提供一个getter和一个可选的setter * 来间接获取和设置其它属性 * 2. 计算属性一般只提供getter方法 * 3. 如果只提供getter,而不提供setter,则该计算属性为只读属性, * 并且可以省略get{} */ /// 大小 (px) var size_px: Int { return Int(size * scale) } /// 字符串格式的大小 var sizeString: String { var sizeString = String(format: "%.f", size) // 针对 83.5 的处理 if size == 83.5 { sizeString = "83.5" } return sizeString } /// 字符串格式的倍数 (1倍为"", 2倍为"@2x", 3倍为"@3x") var scaleString: String { var scaleString = "" if scale == 1.0 { scaleString = "" } else { scaleString = "@\(Int(scale))x" } return scaleString } /// 图标图像 var image: NSImage? init(iconInfo infoDict: [String : Any]?) { guard let infoDict = infoDict else { return } let idiom = infoDict["idiom"] as? String let size = infoDict["size"] as? Float let scale = infoDict["scale"] as? Float let use = infoDict["use"] as? String let system_version = infoDict["system_version"] as? String self.idiom = idiom if let size = size, let scale = scale { self.size = size self.scale = scale } self.use = use self.system_version = system_version } /// 根据模板图标生成图标 /// - Parameter templateIcon: 模板图标 func generateIcon(with templateIcon: NSImage) { let size = NSSize(width: size_px, height: size_px) image = resizeImage(sourceImage: templateIcon, toSize: size) } } extension BWIcon { /// 从plist文件加载图标数据 class func loadIcons() -> ([BWIcon], [BWIcon], [BWIcon]) { var iPhoneIcons = [BWIcon]() var iPadIcons = [BWIcon]() var MacIcons = [BWIcon]() var icons = (iPhoneIcons, iPadIcons, MacIcons) /** * try的含义: * throws 表示会抛出异常 * * 1. 方法一(推荐) try? (弱try),如果解析成功,就有值;否则为nil * let array = try? JSONSerialization.jsonObject(with: , options: ) * * 2. 方法二(不推荐) try! (强try),如果解析成功,就有值;否则会崩溃 * let array = try! JSONSerialization.jsonObject(with: , options: ) * * 3. 方法三(不推荐) try 处理异常,能够接收到错误,并且输出错误 * do { * let array = try JSONSerialization.jsonObject(with: , options: ) * } catch { * print(error) * } * * 小知识: OC中有人用 try catch吗? 为什么? * ARC开发环境下,编译器会自动添加 retain / release / autorelease, * 如果用try catch,一旦出现不平衡,就会造成内存泄漏! */ guard let path = Bundle.main.path(forResource: "BWIconsInfo", ofType: "plist"), let data = try? Data(contentsOf: URL(fileURLWithPath: path)), let dict = try? PropertyListSerialization.propertyList(from: data, options: [], format: nil) as? [String : Any] else { return icons } if let icons = dict["iPhone"] as? [[String : Any]] { icons.forEach { (iconInfo) in iPhoneIcons.append(BWIcon(iconInfo: iconInfo)) } } if let icons = dict["iPad"] as? [[String : Any]] { icons.forEach { (iconInfo) in iPadIcons.append(BWIcon(iconInfo: iconInfo)) } } if let icons = dict["Mac"] as? [[String : Any]] { icons.forEach { (iconInfo) in MacIcons.append(BWIcon(iconInfo: iconInfo)) } } icons = (iPhoneIcons, iPadIcons, MacIcons) return icons } /// 修改图片大小 /// - Parameter sourceImage: 源图片 /// - Parameter size: 目标大小 func resizeImage(sourceImage image: NSImage, toSize size: CGSize) -> NSImage { /// NSImage的size属性: /// 文件名 size /// xxx.png 等于实际像素大小 /// xxx@2x.png 等于实际像素大小的一半 /// xxx@3x.png 等于实际像素大小的1/3 /// 以此类推... // 获取实际像素大小 (通过CGImage获取) // let imageSize = image.size // var pixelSize = imageSize // if let cgImageRef = image.cgImage(forProposedRect: nil, context: nil, hints: nil) { // pixelSize = NSSize(width: cgImageRef.width, height: cgImageRef.height) // } // print("size: (\(imageSize.width), \(imageSize.height)), size (pixel): (\(pixelSize.width), \(pixelSize.height))") // 1. 目标图像尺寸 // 屏幕倍数(几倍屏) var screenScale = NSScreen.main?.backingScaleFactor ?? 1.0 // if let deviceDes = NSScreen.main?.deviceDescription { // let screenSize = deviceDes[NSDeviceDescriptionKey.size] ?? NSSize(width: 0, height: 0) // 当前屏幕尺寸 // let resolution = deviceDes[NSDeviceDescriptionKey.resolution] as? NSSize // 当前屏幕分辨率 // let screenDPI = resolution?.width ?? 0 // 当前屏幕DPI // if screenDPI == 72 { // print("Current screen : scale=1, DPI=\(screenDPI), size=\(screenSize)") // } else if screenDPI == 144 { // print("Current screen : scale=2, DPI=\(screenDPI), size=\(screenSize)") // } else { // print("Current screen : scale=\(screenScale), DPI=\(screenDPI), size=\(screenSize)") // } // } // 在外接显示器屏幕上时,获取的screenScale为1.0,会导致尺寸错误,所以设置screenScale=2.0 screenScale = 2.0 let targetRect = NSRect(x: 0, y: 0, width: size.width / screenScale, height: size.height / screenScale) // 2. 获取源图像数据 let sourceImageRep = image.bestRepresentation(for: targetRect, context: nil, hints: nil) // 3. 创建目标图像并绘制 let targetImage = NSImage(size: targetRect.size) // 使用源图像数据绘制目标图像 targetImage.lockFocus() sourceImageRep?.draw(in: targetRect) targetImage.unlockFocus() return targetImage } /// 修改图片大小 /// - Parameter image: 源图片 /// - Parameter size: 目标大小(点pt) // func resize(sourceImage image: NSImage, to size: NSSize) -> NSImage { // // 源尺寸 // let fromRect = NSRect(x: 0, y: 0, width: image.size.width, height: image.size.height) // // 目标尺寸 // let targetRect = NSRect(x: 0, y: 0, width: size.width, height: size.height) // // // 创建目标图像 // let newImage = NSImage(size: targetRect.size) // // 绘制目标图像 // newImage.lockFocus() // image.draw(in: targetRect, from: fromRect, operation: .copy, fraction: 1.0) // newImage.unlockFocus() // // return newImage // } /// 修改图片大小 /// - Parameter image: 源图片 /// - Parameter size: 目标大小(像素px) // func resize(sourceImage image: NSImage, toPixel size: NSSize) -> NSImage { // // 屏幕倍数(几倍屏) // let screenScale = NSScreen.main?.backingScaleFactor ?? 1.0 // // // 源尺寸 // let fromRect = NSRect(x: 0, y: 0, width: image.size.width, height: image.size.height) // // 目标尺寸 // let targetRect = NSRect(x: 0, y: 0, width: size.width / screenScale, height: size.height / screenScale) // // // 创建目标图像 // let newImage = NSImage(size: targetRect.size) // // 绘制目标图像 // newImage.lockFocus() // image.draw(in: targetRect, from: fromRect, operation: .copy, fraction: 1.0) // newImage.unlockFocus() // // return newImage // } }
// // TypingView.swift // KokaiByWGO // // Created by Waleerat Gottlieb on 2021-05-31. // import SwiftUI struct NewWordView: View { @AppStorage("isDarkMode") private var isDarkMode: Bool = false @State var isShowing: Bool = false @State var isShowInputItemView: Bool = false @State var spellingImages: [String] = [] var body: some View { NavigationView { ZStack { // MARK: - MAIN VIEW VStack { HeroHeaderView(heroTextHeader: text._newWord) WordFormView(isShowInputItemView: $isShowInputItemView, spellingImages: $spellingImages) Spacer() } .blur(radius: isShowInputItemView ? 6.0 : 0, opaque: false) .modifier(loadViewEffectModifier()) .padding(7) // MARK: - NEW TASK ITEM if isShowInputItemView { BlankView( backgroundColor: isDarkMode ? Color.black : Color.gray, backgroundOpacity: isDarkMode ? 0.3 : 0.5) .onTapGesture { withAnimation() { isShowInputItemView = false } } SheetTypingView(isShowInputItemView: $isShowInputItemView, spellingImages: $spellingImages) } } //: ZSTACK .onAppear() { UITableView.appearance().backgroundColor = UIColor.clear } .navigationBarTitle(text._newWord, displayMode: .large) .navigationBarHidden(true) /*.background( BackgroundImageView() .blur(radius: isShowInputItemView ? 8.0 : 0, opaque: false) )*/ .background( backgroundGradient.ignoresSafeArea(.all) ) } //: NAVIGATION //.navigationViewStyle(StackNavigationViewStyle()) } } struct NewWordView_Previews: PreviewProvider { static var previews: some View { NewWordView() } } /* */
// // ViewController.swift // CardDeckExample // // Created by Uribe, Martin on 1/16/17. // Copyright © 2017 MUGBY. All rights reserved. // import UIKit extension MutableCollection where Indices.Iterator.Element == Index { /// Shuffles the contents of this collection. mutating func shuffle() { let c = count guard c > 1 else { return } for (firstUnshuffled , unshuffledCount) in zip(indices, stride(from: c, to: 1, by: -1)) { let d: IndexDistance = numericCast(arc4random_uniform(numericCast(unshuffledCount))) guard d != 0 else { continue } let i = index(firstUnshuffled, offsetBy: d) swap(&self[firstUnshuffled], &self[i]) } } } typealias Listener = ([Card]) -> Void public enum CardSuit { case Clubs, Diamonds, Hearts, Spades func stringRepresentation() -> String { switch self { case .Clubs: return "\u{2663}" case .Diamonds: return "\u{2666}" case .Hearts: return "\u{2665}" case .Spades: return "\u{2660}" } } func rank() -> Int { switch self { case .Clubs: return 0 case .Diamonds: return 1 case .Hearts: return 2 case .Spades: return 3 } } } public enum CardDeck { case Red, Blue func reuseIdentifier() -> String { switch self { case .Red: return "RedDeckCard" case .Blue: return "BlueDeckCard" } } } public struct Card { let suit: CardSuit! let rank: String! let deck: CardDeck! func stringRepresentation() -> String { return "\(suit.stringRepresentation()) " + rank } static func intFromRank(rank: String) -> Int { switch rank { case "A": return 1 case "J": return 11 case "Q": return 12 case "K": return 13 default: return Int(rank) ?? -1 } } static func rankFromInt(rank: Int) -> String { switch rank { case 1: return "A" case 11: return "J" case 12: return "Q" case 13: return "K" default: return String(rank) } } } public struct Deck { var clubsDeck = [Card]() var diamondsDeck = [Card]() var heartsDeck = [Card]() var spadesDeck = [Card]() func deckForSection(section: Int) -> [Card] { switch section { case 0: return clubsDeck case 1: return diamondsDeck case 2: return heartsDeck case 3: return spadesDeck default: return [] } } } class ViewController: UIViewController { @IBOutlet weak var redDeckCollectionView: UICollectionView! @IBOutlet weak var blueDeckCollectionView: UICollectionView! @IBOutlet weak var scrambledDeckCollectionView: UICollectionView! var redDeck = Deck() var blueDeck = Deck() var scrambledDeck = [Card]() let standard52DeckRanks = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"] fileprivate var listener: Listener! var mergeProcessCounter = [Int:Int]() var threadSleep: UInt32 = 1 var currentSubArray:[Card]? override func viewDidLoad() { super.viewDidLoad() initListener() // Do any additional setup after loading the view, typically from a nib. let suits: [CardSuit] = [.Clubs, .Diamonds, .Hearts, .Spades] let decks: [CardDeck] = [.Red, .Blue] for deck in decks { for suit in suits { for rank in 1...13 { scrambledDeck.append(Card(suit: suit, rank: Card.rankFromInt(rank: rank), deck: deck)) } } } scrambledDeck.shuffle() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func initListener() { listener = { [weak self] sortedSubArray in self?.currentSubArray = sortedSubArray guard let levelCounter = self?.mergeProcessCounter[sortedSubArray.count] as Int? else { self?.mergeProcessCounter[sortedSubArray.count] = 1 self?.scrambledDeckCollectionView.reloadData() self?.scrambledDeck.replaceSubrange(0..<sortedSubArray.count, with: sortedSubArray) self?.scrambledDeckCollectionView.reloadData() return } let startIndex = levelCounter*sortedSubArray.count if (startIndex + sortedSubArray.count) <= self?.scrambledDeck.count ?? 0 { self?.mergeProcessCounter[sortedSubArray.count] = levelCounter + 1 self?.scrambledDeckCollectionView.reloadData() self?.scrambledDeck.replaceSubrange(startIndex..<(startIndex + sortedSubArray.count), with: sortedSubArray) self?.scrambledDeckCollectionView.reloadData() } } } @IBAction func reorderDecks(_ sender: Any) { reorderDecks() } @IBAction func scrambleDecks(_ sender: Any) { listener = nil initListener() mergeProcessCounter.removeAll() scrambledDeck.shuffle() scrambledDeckCollectionView.reloadData() scrambledDeckCollectionView.scrollToItem(at: IndexPath(item: 0, section: 0), at: .left, animated: true) } func reorderDecks() { mergeProcessCounter.removeAll() listener = nil initListener() DispatchQueue.global(qos: .background).async { let deck = self.scrambledDeck self.scrambledDeck = deck.mergeSortWithListener(listener: self.listener, threadSleep: self.threadSleep) } } func threadSleepStringForRow(row: Int) -> String { switch row { case 0: return "0" case 1: return "0.5" case 2: return "1" case 3: return "1.5" default: return "0" } } func threadSleepIntForRow(row: Int) -> useconds_t { let second: Double = 1000000 return UInt32(Double(threadSleepStringForRow(row: row))! * second) } } extension ViewController: UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { if collectionView == scrambledDeckCollectionView { return 1 } return 4 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { switch collectionView { case scrambledDeckCollectionView: return scrambledDeck.count case redDeckCollectionView: return redDeck.deckForSection(section: section).count case blueDeckCollectionView: return blueDeck.deckForSection(section: section).count default: return 0 } } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { var card: Card! switch collectionView { case scrambledDeckCollectionView: card = scrambledDeck[indexPath.item] case redDeckCollectionView: card = redDeck.deckForSection(section: indexPath.section)[indexPath.item] case blueDeckCollectionView: card = blueDeck.deckForSection(section: indexPath.section)[indexPath.item] default: return UICollectionViewCell() } guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: card.deck.reuseIdentifier(), for: indexPath) as? CardCell else { return UICollectionViewCell() } cell.cardLabel.text = card.stringRepresentation() cell.alpha = 1 if mergeProcessCounter.count > 0 && currentSubArray != nil { if currentSubArray!.contains(scrambledDeck[indexPath.row]) { cell.alpha = 0.5 } } return cell } } extension ViewController: UICollectionViewDelegate { } extension ViewController: UIPickerViewDataSource { func numberOfComponents(in pickerView: UIPickerView) -> Int { return 2 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return component == 0 ? 1 : 4 } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { if component == 0 { return "Thread Sleep:" } else { return threadSleepStringForRow(row: row) } } } extension ViewController: UIPickerViewDelegate { func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { threadSleep = threadSleepIntForRow(row: row) } }
// // AppDelegate.swift // StetsonScene // // Created by Lannie Hough on 1/1/20. // Copyright © 2020 Lannie Hough. All rights reserved. // import UIKit import Firebase import FirebaseDatabase import SwiftUI import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, ObservableObject { var eventListRef:DatabaseReference! //references to Firebase Realtime Database var eventListOrderRef:DatabaseReference! var eventTypeAssociationRef:DatabaseReference! var locationAssocationRef:DatabaseReference! var connectedRef:DatabaseReference! var buildingsRef:DatabaseReference! var updateListRef:DatabaseReference! lazy var persistentContainer:NSPersistentContainer = { let container = NSPersistentContainer(name: "PersistentData") container.loadPersistentStores{ description, error in if let error = error { fatalError("Unable to load persistent stores: \(error)") } } return container }() ///Function used in Core Data to keep persistent data func saveContext() { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { print("error in saving persistent changes") } } } ///First function called on app launch. Establishes interaction with Firebase Database & extracts import information for the app to run. func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. //Firebase & Firebase Realtime Database inititiation FirebaseApp.configure() //References to relevant data on the Firebase Database are established eventListRef = Database.database().reference(withPath: "Test/eventList") eventTypeAssociationRef = Database.database().reference(withPath: "EventTypeAssociationsTest") locationAssocationRef = Database.database().reference(withPath: "LocationAssociationsTest") eventListOrderRef = Database.database().reference(withPath: "eLocsTest") connectedRef = Database.database().reference(withPath: ".info/connected") buildingsRef = Database.database().reference(withPath: "Buildings") updateListRef = Database.database().reference(withPath: "UpdateList") // eventListRef = Database.database().reference(withPath: "Events/eventList") // eventTypeAssociationRef = Database.database().reference(withPath: "EventTypeAssociations") // locationAssocationRef = Database.database().reference(withPath: "LocationAssociations") // eventListOrderRef = Database.database().reference(withPath: "EventLocs") // connectedRef = Database.database().reference(withPath: ".info/connected") // buildingsRef = Database.database().reference(withPath: "Buildings") return true } ///Allows for access to important information from outside the AppDelegate static func shared() -> AppDelegate { return UIApplication.shared.delegate as! AppDelegate } // MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { } //ADD PUSH NOTIFICATION CONTENT HERE!!! }
// // FormService.swift // GForm // // Created by Kennan Trevyn Zenjaya on 29/01/21. // import LBTAComponents import Firebase public func checkFormTitleAvailability(newtitle: String, type: String) -> Bool { var counter = 0 if type == "Private" { for item in privateForms { if newtitle.lowercased() == item.title?.lowercased() { return false } else { counter += 1 if counter == privateForms.count { item.title = newtitle return true } } } } else { for item in developerForms { if newtitle.lowercased() == item.title?.lowercased() { return false } else { counter += 1 if counter == developerForms.count { item.title = newtitle return true } } } } return false }
// // ProfileViewController.swift // Pennies // // Created by Bria Wallace on 4/23/17. // Copyright © 2017 Bria Wallace. All rights reserved. // import UIKit class ProfileViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet var profileView: ProfileView! @IBOutlet weak var tableView: UITableView! var userDetails: User! var userID = User.currentUser?.id var userTweets:[Tweet]! = [] func setUserDetails() { profileView.user = userDetails } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return userTweets.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "TweetCell", for: indexPath) as! TweetCell cell.tweetInfo = userTweets[indexPath.row] return cell } func loadData() { TwitterClient.sharedInstance.userAccount(userID: userID, success: { (user: User) in self.userDetails = user self.setUserDetails() }) { (error: Error) in print(error.localizedDescription) } TwitterClient.sharedInstance.userTimeline(userID: userID, success: { (tweets: [Tweet]) in self.userTweets = tweets self.tableView.reloadData() }) { (error: Error) in print(error.localizedDescription) } } override func viewDidLoad() { super.viewDidLoad() tableView.estimatedRowHeight = 100.0 tableView.rowHeight = UITableViewAutomaticDimension tableView.delegate = self tableView.dataSource = self loadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
// // FirstViewController.swift // Feed // // Created by Arnau Marti Font on 19/2/16. // Copyright © 2016 Arnau Marti Font. All rights reserved. // import UIKit import Alamofire var Plats = [Plat]() class FirstViewController: UITableViewController { @IBOutlet var TableViewPlats: UITableView! override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(true) Alamofire.request(.GET, "http://54.201.234.52/plat/getList") .responseJSON { response in do { Plats.removeAll() let json = try NSJSONSerialization.JSONObjectWithData(response.data!, options: NSJSONReadingOptions.AllowFragments) for item in (json as? NSArray)! { print(item) print(item.valueForKey("nom")) print(item.valueForKey("descripcio")) var nom = item.valueForKey("nom") var descripcio = item.valueForKey("descripcio") //var usuari = item.valueForKey("usuari") // var foto = UIImage(); //print(item.valueForKey("foto")) /*if (item.valueForKey("foto") != nil) { foto = UIImage(data: (item.valueForKey("foto") as? NSData)!)! } */ let newPlat = Plat(nom: (nom as? String)!, descripcio: (descripcio as? String)! /*usuari: (usuari as? String)!*/ /*, imatge: foto*/) Plats.append(newPlat!) } self.TableViewPlats.reloadData() } catch let error as NSError { print("hola") } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return Plats.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) cell.textLabel?.text = String(Plats[indexPath.row].nom) //cell.imageView?.image = plats[indexPath.row].imatge //cell.detailTextLabel?.text = String(Plats[indexPath.row].usuari) /* cell.imageView!.layer.cornerRadius = 10 cell.imageView!.layer.borderWidth = 2 */ return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){ DescripcioVista = Plats[indexPath.row].descripcio NomVista = Plats[indexPath.row].nom // ImatgeVista = (Plats[indexPath.row].imatge)! } //borrar index override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath){ if editingStyle == UITableViewCellEditingStyle.Delete{ Plats.removeAtIndex(indexPath.row) } TableViewPlats.reloadData() } }
// // WeatherLifeStyle.swift // HeWeatherIO // // Created by iMac on 2018/5/30. // Copyright © 2018年 iMac. All rights reserved. // import Foundation public final class WeatherLifeStyle : HeWeatherBase { let lifestyle: [Lifestyle]? required public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: WeatherLifeStyle.CodingKeys.self) lifestyle = try? container.decode([Lifestyle].self, forKey: .lifestyle) try super.init(from: decoder) } private enum CodingKeys: String, CodingKey { case lifestyle = "lifestyle" } } public struct Lifestyle : Codable { let brf : String? let txt : String? let type : String? public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) brf = try values.decodeIfPresent(String.self, forKey: .brf) txt = try values.decodeIfPresent(String.self, forKey: .txt) type = try values.decodeIfPresent(String.self, forKey: .type) } enum CodingKeys: String, CodingKey { case brf = "brf" case txt = "txt" case type = "type" } }
import Foundation public extension String { static func stringFromBytes(_ bytes: Int64) -> String { let bcf = ByteCountFormatter() bcf.allowedUnits = [.useGB, .useMB] bcf.countStyle = .file return bcf.string(fromByteCount: bytes) } }
// // AudioListViewController.swift // IVY // // Created by SS108 on 12/09/16. // Copyright © 2016 Singsys Pte Ltd. All rights reserved. // import UIKit import MediaPlayer import AVKit class AudioListViewController: UIViewController, UITableViewDelegate,UITableViewDataSource, AVAudioPlayerDelegate, UIAlertViewDelegate { var audioPlayer: AVAudioPlayer! //var isPlaying = true var sound = String() var listOfSounds = ["emergency_1","emergency_2", "emergency_3","ringtone_1","ringtone_2"] var listOfPlaySounds = ["emergency 1","emergency 2", "emergency 3","ringtone 1","ringtone 2"] var ringNo: Int! var flag = false @IBOutlet weak var tableView: UITableView! var oldIndexRef:Int = -1 var newIndexRef:Int = -1 var oldImgViewRef: UIImageView! //MARK:- override func //MARK:- override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //MARK:- UITableView Delegates //MARK:- func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return listOfSounds.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cellIdentifier:String cellIdentifier = "soundCell" var cell=tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as UITableViewCell! if(cell==nil) { cell=UITableViewCell(style:UITableViewCellStyle.subtitle, reuseIdentifier: cellIdentifier) } let soundText = cell?.viewWithTag(5) as! UILabel soundText.text = listOfPlaySounds[(indexPath as NSIndexPath).row].capitalized let playBtnImg = cell?.viewWithTag(13) as! UIImageView playBtnImg.image = UIImage(named:"Play_1") let check = cell?.viewWithTag(11) as! UIImageView if (indexPath as NSIndexPath).row == Int(UserDefaults.standard.object(forKey: "defaultRingtone") as! String) { check.image = UIImage(named: "done_prof") } else { check.image = UIImage(named: "") } cell?.selectionStyle=UITableViewCellSelectionStyle.none return cell! } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { ringNo = (indexPath as NSIndexPath).row let alertView : UIAlertView = UIAlertView( title:"IVY", message:"Do you want to change audio for emergency alert?", delegate:self, cancelButtonTitle:"Cancel", otherButtonTitles:"Ok") alertView.show() } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 50 } //MARK:- @IBAction func //MARK:- // Action for navigating on previous screen @IBAction func backBtnClicked(_ sender: UIButton) { navigationController?.popViewController(animated: true) } @IBAction func playBtn(_ sender: AnyObject) { let hitPoint: CGPoint = sender.convert(CGPoint.zero, to: tableView) let hitIndex = tableView.indexPathForRow(at: hitPoint) let hitCell = tableView.cellForRow(at: hitIndex!) let playBtnImg = hitCell?.viewWithTag(13) as! UIImageView newIndexRef = ((hitIndex as NSIndexPath?)?.row)! if oldIndexRef == newIndexRef { oldIndexRef = ((hitIndex as NSIndexPath?)?.row)! if audioPlayer.isPlaying == true { audioPlayer.pause() playBtnImg.image = UIImage(named:"Play_1") } else { playBtnImg.image = UIImage(named:"Pause_11") sound = listOfSounds[((hitIndex as NSIndexPath?)?.row)!] audioPlayerCondition() } } else { if oldIndexRef == -1 { oldImgViewRef = playBtnImg oldIndexRef = newIndexRef } else { oldImgViewRef.image = UIImage(named:"Play_1") oldImgViewRef = playBtnImg oldIndexRef = newIndexRef } playBtnImg.image = UIImage(named:"Pause_11") sound = listOfSounds[((hitIndex as NSIndexPath?)?.row)!] audioPlayerCondition() } } // MARK: AVAudioPlayerDelegate //Audio player func func audioPlayerCondition() { // Construct URL to sound file let soundUrl = URL(fileURLWithPath: Bundle.main.path(forResource: sound, ofType: "mp3")!) // Create audio player object and initialize with URL to sound do { self.audioPlayer = try AVAudioPlayer(contentsOf: soundUrl) audioPlayer.delegate = self } catch let error { } audioPlayer.play() } // extension MicroStepViewController : AVAudioPlayerDelegate { func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) { tableView.reloadData() } // MARK: alertViewDelegate func alertView(_ alertView: UIAlertView, clickedButtonAt buttonIndex: Int) { switch buttonIndex { case 1: userRingSet() break case 0: break default : break } } //MARK:- selected sound web service func userRingSet() { if appdelegate.hasConnectivity() { appdelegate.showProgressHudForViewMy(self.view, withDetailsLabel: "Please wait", labelText: "Requesting...") let manager: AFHTTPSessionManager = AFHTTPSessionManager () let serializer: AFJSONResponseSerializer = AFJSONResponseSerializer () manager.responseSerializer = serializer let param=["user_id":UserDefaults.standard.object(forKey: "user_id") as! String,"default_ringtone":ringNo] as NSDictionary print(param) let url="\(base_URL)\(userRing_URL)" manager.post("\(url)", parameters: param,progress: nil, success: { (task, responseObject) in print(responseObject) appdelegate.hideProgressHudInView(self.view) if let result = responseObject as? NSDictionary{ let status = result.object(forKey: "success")! as! Int if(status == 0) { let msg = result.object(forKey: "message")! as! String appdelegate.showMessageHudWithMessage(msg as NSString, delay: 2.0) } else { let msg = result.object(forKey: "message")! as! String appdelegate.showMessageHudWithMessage(msg as NSString, delay: 2.0) //self.contactList.removeObjectAtIndex(self.indexpath.row) UserDefaults.standard.setValue(String(self.ringNo), forKey: "defaultRingtone") self.tableView.reloadData() } } }, failure: {(operation: URLSessionTask?, error: Error) -> Void in print("Error: \(error)") print("ERROR") appdelegate.hideProgressHudInView(self.view) let msg:AnyObject = "Failed due to an error" as AnyObject appdelegate.showMessageHudWithMessage(msg as! NSString, delay: 2.0) }) } else { let msg:AnyObject = "No internet connection available. Please check your internet connection." as AnyObject appdelegate.showMessageHudWithMessage(msg as! NSString, delay: 2.0) } } }
// // Rotation.swift // 100Views // // Created by Mark Moeykens on 9/6/19. // Copyright © 2019 Mark Moeykens. All rights reserved. // import SwiftUI struct Rotation: View { @State private var applyEffect = false var body: some View { VStack(spacing: 20) { Text("Transform Effect").font(.largeTitle) Text("Rotation").font(.title).foregroundColor(.gray) Text("Use this transform effect to rotate a view.") .frame(maxWidth: .infinity) .font(.title).padding() .background(Color.purple) .layoutPriority(1) .foregroundColor(.white) Spacer() Image(systemName: "arrow.turn.up.left") .font(.system(size: 40)) Image(systemName: "pencil.and.outline") .border(Color.purple) .font(.system(size: 100)) .foregroundColor(.purple) .transformEffect(applyEffect ? CGAffineTransform(rotationAngle: CGFloat(Angle.degrees(180).radians)) : .identity) // Identify removes all transformations .border(Color.purple) Spacer() Text("Notice the rotation anchor is the top leading corner. At this time, I'm not sure how to change the anchor through SwiftUI.") .frame(maxWidth: .infinity) .font(.title).padding() .background(Color.purple) .layoutPriority(1) .foregroundColor(.white) HStack { Spacer() Button("Apply Effect") { self.applyEffect = true } Spacer() Button("Remove Effect") { self.applyEffect = false } Spacer() } } } } struct Rotation_Previews: PreviewProvider { static var previews: some View { Rotation() } }
// // LoginViewController.swift // movieroll // // Created by Angelo Polotto on 13/08/2018. // Copyright © 2018 Mobify. All rights reserved. // import Foundation import Alamofire import AlamofireObjectMapper class LoginViewController: BaseViewController, LoginContractView { var presenter: LoginPresenter? @IBOutlet weak var email: UITextField! @IBOutlet weak var password: UITextField! @IBOutlet weak var emailError: UILabel! @IBOutlet weak var passwordError: UILabel! @IBAction func login(_ sender: Any) { presenter?.requestLogin(email: email.text ?? "", password: password.text ?? "") } override func viewDidLoad() { super.viewDidLoad() emailError.isHidden = true passwordError.isHidden = true Repository.shared.view = self presenter = LoginPresenter(view: self, repository: Repository.shared, userSettings: UserSettings.shared, validators: Validators.shared) } func showDiscover() { navigationController?.popViewController(animated: true) } func emailError(_ message: String) { emailError.isHidden = false emailError.text = message } func passwordError(_ message: String) { passwordError.isHidden = false passwordError.text = message } func emailErrorHide() { emailError.isHidden = true } func passwordErrorHide() { passwordError.isHidden = true } }
// // HereViewController.swift // prkng-ios // // Created by Cagdas Altinkaya on 19/04/15. // Copyright (c) 2015 PRKNG. All rights reserved. // import UIKit class HereViewController: AbstractViewController, SpotDetailViewDelegate, PRKModalViewControllerDelegate, CLLocationManagerDelegate, UITextFieldDelegate, PRKVerticalGestureRecognizerDelegate, FilterViewControllerDelegate { var showFiltersOnAppear: Bool = false var mapMessageView: MapMessageView var canShowMapMessage: Bool = false var prkModalViewController: PRKModalDelegatedViewController? var firstUseMessageVC: HereFirstUseViewController? var detailView: SpotDetailView var filterVC: FilterViewController var carSharingInfoVC: CarSharingInfoViewController? var statusBar: UIView var modeSelection: PRKModeSlider var showModeSelection: Bool = true var activeDetailObject: DetailObject? var forceShowSpotDetails: Bool let viewHeight = UIScreen.mainScreen().bounds.height - CGFloat(Styles.Sizes.tabbarHeight) private var filterButtonImageName: String private var filterButtonText: String private var verticalRec: PRKVerticalGestureRecognizer private var isShowingModal: Bool private var timer: NSTimer? var delegate : HereViewControllerDelegate? init() { detailView = SpotDetailView() filterVC = FilterViewController() mapMessageView = MapMessageView() statusBar = UIView() filterButtonImageName = "icon_filter" filterButtonText = "" modeSelection = PRKModeSlider(titles: ["garages".localizedString, "on-street".localizedString, "car_sharing".localizedString]) forceShowSpotDetails = false verticalRec = PRKVerticalGestureRecognizer() isShowingModal = false super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("NSCoding not supported") } override func loadView() { self.view = TouchForwardingView() setupViews() setupConstraints() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) modeSelection.setValue(Double(modeSelection.selectedIndex), animated: true) if (Settings.firstMapUse()) { Settings.setFirstMapUsePassed(true) NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("showFirstUseMessage"), userInfo: nil, repeats: false) } else { if showFiltersOnAppear { self.filterVC.showFilters(resettingTimeFilterValue: true) self.filterVC.makeActive() showFiltersOnAppear = false } else { self.filterVC.hideFilters(completely: false) self.delegate?.updateMapAnnotations(nil) } } } override func viewDidLoad() { super.viewDidLoad() self.screenName = "Here - General View" } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) NSLog("HereViewController disappeared") hideModalView() hideSpotDetails() } func setupViews () { verticalRec = PRKVerticalGestureRecognizer(view: detailView, superViewOfView: self.view) verticalRec.delegate = self detailView.delegate = self view.addSubview(detailView) self.filterVC.delegate = self self.view.addSubview(self.filterVC.view) self.filterVC.willMoveToParentViewController(self) modeSelection.addTarget(self, action: "modeSelectionValueChanged", forControlEvents: UIControlEvents.ValueChanged) view.addSubview(modeSelection) statusBar.backgroundColor = Styles.Colors.statusBar view.addSubview(statusBar) let mapMessageTapRec = UITapGestureRecognizer(target: self, action: "didTapMapMessage") mapMessageView.addGestureRecognizer(mapMessageTapRec) view.addSubview(mapMessageView) } func setupConstraints() { mapMessageView.snp_makeConstraints { (make) -> () in make.left.equalTo(self.view) make.right.equalTo(self.view) make.bottom.equalTo(self.view.snp_top) } statusBar.snp_makeConstraints { (make) -> () in make.top.equalTo(self.view) make.left.equalTo(self.view) make.right.equalTo(self.view) make.height.equalTo(20) } detailView.snp_makeConstraints { (make) -> () in make.bottom.equalTo(self.view).offset(180) make.left.equalTo(self.view) make.right.equalTo(self.view) make.height.equalTo(Styles.Sizes.spotDetailViewHeight) } self.filterVC.view.snp_makeConstraints { (make) -> () in make.top.equalTo(self.mapMessageView.snp_bottom) make.left.equalTo(self.view) make.right.equalTo(self.view) make.bottom.equalTo(self.view) } modeSelection.snp_makeConstraints { (make) -> () in make.height.equalTo(60) make.left.equalTo(self.view) make.right.equalTo(self.view) make.bottom.equalTo(self.view) } } func showFirstUseMessage() { firstUseMessageVC = HereFirstUseViewController() self.addChildViewController(firstUseMessageVC!) self.view.addSubview(firstUseMessageVC!.view) firstUseMessageVC!.didMoveToParentViewController(self) firstUseMessageVC!.view.snp_makeConstraints(closure: { (make) -> () in make.edges.equalTo(self.view) }) let tap = UITapGestureRecognizer(target: self, action: "dismissFirstUseMessage") firstUseMessageVC!.view.addGestureRecognizer(tap) firstUseMessageVC!.view.alpha = 0.0 UIView.animateWithDuration(0.2, animations: { () -> Void in self.firstUseMessageVC!.view.alpha = 1.0 }) } func dismissFirstUseMessage() { if let firstUse = self.firstUseMessageVC { UIView.animateWithDuration(0.2, animations: { () -> Void in firstUse.view.alpha = 0.0 }, completion: { (finished) -> Void in firstUse.removeFromParentViewController() firstUse.view.removeFromSuperview() firstUse.didMoveToParentViewController(nil) self.firstUseMessageVC = nil }) } } func topContainerTapped() { if activeDetailObject?.compact == true { return } if let lot = activeDetailObject as? Lot { if lot.isParkingPanda { ParkingPandaOperations.login(username: nil, password: nil, completion: {(user, error) -> Void in if user != nil { dispatch_async(dispatch_get_main_queue(), { () -> Void in let lotBookingVC = LotBookingViewController(lot: lot, user: user!, view: self.view) self.showModalView(self.activeDetailObject, modalVC: lotBookingVC) }) } else { dispatch_async(dispatch_get_main_queue(), { () -> Void in let ppIntroVC = PPIntroViewController() ppIntroVC.presentWithVC(self) }) } }) } else { showModalView(activeDetailObject, modalVC: LotViewController(lot: lot, view: self.view)) } } else { checkin() } } func bottomContainerTapped() { if activeDetailObject?.compact == true { return } if activeDetailObject != nil { showModalView(activeDetailObject, modalVC: nil) } } //MARK: PRKVerticalGestureRecognizerDelegate methods func shouldIgnoreSwipe(beginTap: CGPoint) -> Bool { if activeDetailObject?.compact == true { return true } if let lot = activeDetailObject as? Lot where lot.isParkingPanda { return true } return false } func swipeDidBegin() { if activeDetailObject != nil { setupModalView(activeDetailObject, modalVC: nil) } } func swipeInProgress(yDistanceFromBeginTap: CGFloat) { adjustSpotDetailsWithDistanceFromBottom(-yDistanceFromBeginTap, animated: false) //parallax for the top image/street view! let topViewOffset = (yDistanceFromBeginTap / prkModalViewController!.FULL_HEIGHT) * prkModalViewController!.TOP_PARALLAX_HEIGHT prkModalViewController?.topParallaxView?.snp_updateConstraints { (make) -> () in make.top.equalTo(self.prkModalViewController!.view).offset(prkModalViewController!.TOP_PARALLAX_HEIGHT - topViewOffset) } prkModalViewController?.topParallaxView?.layoutIfNeeded() } func swipeDidEndUp() { animateModalView() } func swipeDidEndDown() { showSpotDetails() } // MARK: Schedule/Agenda/Modal methods func showModalView(detailObject : DetailObject?, modalVC: PRKModalDelegatedViewController?) { setupModalView(detailObject, modalVC: modalVC) animateModalView() } func setupModalView(detailObject : DetailObject?, modalVC: PRKModalDelegatedViewController?) { //this prevents the "double modal view" bug that we sometimes see self.prkModalViewController?.view.removeFromSuperview() self.prkModalViewController?.willMoveToParentViewController(nil) self.prkModalViewController?.removeFromParentViewController() self.prkModalViewController = nil if let spot = detailObject as? ParkingSpot { self.prkModalViewController = modalVC ?? PRKModalViewController(spot: spot, view: self.view) self.view.addSubview(self.prkModalViewController!.view) self.prkModalViewController!.willMoveToParentViewController(self) self.prkModalViewController!.delegate = self self.prkModalViewController!.view.snp_makeConstraints(closure: { (make) -> () in make.top.equalTo(self.detailView.snp_bottom) make.size.equalTo(self.view) make.left.equalTo(self.view) make.right.equalTo(self.view) }) self.prkModalViewController!.view.layoutIfNeeded() } else if let lot = detailObject as? Lot { self.prkModalViewController = modalVC ?? LotViewController(lot: lot, view: self.view) self.view.addSubview(self.prkModalViewController!.view) self.prkModalViewController!.willMoveToParentViewController(self) self.prkModalViewController!.delegate = self self.prkModalViewController!.view.snp_makeConstraints(closure: { (make) -> () in make.top.equalTo(self.detailView.snp_bottom) make.size.equalTo(self.view) make.left.equalTo(self.view) make.right.equalTo(self.view) }) self.prkModalViewController!.view.layoutIfNeeded() } } func animateModalView() { adjustSpotDetailsWithDistanceFromBottom(-viewHeight, animated: true) isShowingModal = true //fix parallax effect just in case prkModalViewController?.topParallaxView?.snp_updateConstraints { (make) -> () in make.top.equalTo(self.prkModalViewController!.view) } UIView.animateWithDuration(0.2, animations: { () -> Void in self.prkModalViewController?.topParallaxView?.updateConstraints() }, completion: nil ) } func hideModalView () { if(self.prkModalViewController == nil) { return } detailView.snp_updateConstraints { (make) -> () in make.bottom.equalTo(self.view).offset(0) } self.prkModalViewController?.view.snp_updateConstraints(closure: { (make) -> () in make.top.equalTo(self.detailView.snp_bottom).offset(0) }) UIView.animateWithDuration(0.2, animations: { () -> Void in self.detailView.alpha = 1 self.view.layoutIfNeeded() }, completion: { (Bool) -> Void in self.prkModalViewController!.view.removeFromSuperview() self.prkModalViewController!.willMoveToParentViewController(nil) self.prkModalViewController!.removeFromParentViewController() self.prkModalViewController = nil self.isShowingModal = false }) } func shouldAdjustTopConstraintWithOffset(distanceFromTop: CGFloat, animated: Bool) { let height = UIScreen.mainScreen().bounds.height - CGFloat(Styles.Sizes.tabbarHeight) let distanceFromBottom = height - distanceFromTop adjustSpotDetailsWithDistanceFromBottom(-distanceFromBottom, animated: animated) } func checkin() { if let activeSpot = activeDetailObject as? ParkingSpot { //OLD RULE FOR WHETHER WE COULD/COULDN'T CHECK-IN: // let checkedInSpotID = Settings.checkedInSpotId() // if (activeDetailObject != nil && checkedInSpotID != nil) { // checkinButton.enabled = checkedInSpotID != activeDetailObject?.identifier // } else { // checkinButton.enabled = true // } SVProgressHUD.setBackgroundColor(UIColor.clearColor()) SVProgressHUD.show() Settings.checkOut() SpotOperations.checkin(activeSpot.identifier, completion: { (completed) -> Void in Settings.saveCheckInData(activeSpot, time: NSDate()) if (Settings.notificationTime() > 0) { Settings.cancelScheduledNotifications() if activeSpot.currentlyActiveRuleType != .Paid && activeSpot.currentlyActiveRuleType != .PaidTimeMax && !activeSpot.isAlwaysAuthorized() { Settings.scheduleNotification(NSDate(timeIntervalSinceNow: activeSpot.availableTimeInterval() - NSTimeInterval(Settings.notificationTime() * 60))) } } Settings.scheduleNotification(activeSpot) SVProgressHUD.dismiss() self.delegate?.loadMyCarTab() if Settings.shouldPromptUserToRateApp() { let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let dialogVC = PRKDialogViewController(titleIconName: "icon_review", headerImageName: "review_header", titleText: "review_title_text".localizedString, subTitleText: "review_message_text".localizedString, messageText: "", buttonLabels: ["review_rate_us".localizedString, "review_feedback".localizedString, "dismiss".localizedString]) dialogVC.delegate = appDelegate dialogVC.showOnViewController(appDelegate.window!.rootViewController!) } }) } } //start here func updateDetailsTime() { if self.activeDetailObject != nil { detailView.leftBottomLabel.attributedText = self.activeDetailObject!.bottomLeftPrimaryText detailView.rightTopLabel.text = self.activeDetailObject!.bottomRightTitleText detailView.rightBottomLabel.attributedText = self.activeDetailObject!.bottomRightPrimaryText } } func updateDetails(detailObject: DetailObject?) { self.activeDetailObject = detailObject if detailObject != nil { forceShowSpotDetails = true if (activeDetailObject != nil) { print("selected spot/lot : " + activeDetailObject!.identifier) } detailView.checkinImageView.image = UIImage(named: detailObject!.headerIconName) detailView.checkinImageLabel.text = detailObject!.headerIconSubtitle detailView.bottomLeftContainer.snp_updateConstraints(closure: { (make) -> () in make.width.equalTo(detailObject!.showsBottomLeftContainer ? detailObject!.bottomLeftWidth : 0) }) if let iconName = detailObject!.bottomRightIconName { if let colorForIcon = detailObject?.bottomRightIconColor { let image = UIImage(named: iconName) detailView.scheduleImageView.image = image?.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate) detailView.scheduleImageView.tintColor = colorForIcon } else { detailView.scheduleImageView.image = UIImage(named:iconName) } } else { detailView.scheduleImageView.image = UIImage() } if let iconName = detailObject!.bottomLeftIconName { detailView.bottomLeftImageView.image = UIImage(named:iconName) } else { detailView.bottomLeftImageView.image = UIImage() } detailView.leftTopLabel.text = detailObject!.bottomLeftTitleText detailView.topText = activeDetailObject!.headerText updateDetailsTime() if detailObject!.doesHeaderIconWiggle { detailView.checkinImageView.layer.wigglewigglewiggle() } else { detailView.checkinImageView.layer.removeAllAnimations() } hideModeSelection() showSpotDetails() self.timer?.invalidate() self.timer = NSTimer.scheduledTimerWithTimeInterval(60, target: self, selector: "updateDetailsTime", userInfo: nil, repeats: true) } else { self.activeDetailObject = nil self.timer?.invalidate() dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(10 * NSEC_PER_MSEC)), dispatch_get_main_queue(), { self.hideSpotDetails() }) } } //end here private func showSpotDetails() { adjustSpotDetailsWithDistanceFromBottom(0, animated: true) } private func hideSpotDetails() { adjustSpotDetailsWithDistanceFromBottom(180, animated: true) } private func adjustSpotDetailsWithDistanceFromBottom(distance: CGFloat, animated: Bool) { let fullLayout = distance == 0 || distance == 180 || distance == viewHeight || distance == -viewHeight let alpha = abs(distance) / self.viewHeight let parallaxOffset = fullLayout ? 0 : alpha * CGFloat(Styles.Sizes.spotDetailViewHeight) if isShowingModal { detailView.snp_updateConstraints { (make) -> () in make.bottom.equalTo(self.view).offset(distance + parallaxOffset) } self.prkModalViewController?.view.snp_updateConstraints(closure: { (make) -> () in make.top.equalTo(self.detailView.snp_bottom).offset(-parallaxOffset) }) } else { detailView.snp_updateConstraints { (make) -> () in make.bottom.equalTo(self.view).offset(distance) } self.prkModalViewController?.view.snp_updateConstraints(closure: { (make) -> () in make.top.equalTo(self.detailView.snp_bottom).offset(-2*parallaxOffset) }) } let changeView = { () -> () in if fullLayout { self.view.layoutIfNeeded() } else { self.view.updateConstraints() } if self.isShowingModal { self.detailView.alpha = (self.viewHeight/2 - abs(distance)) / (self.viewHeight/2) } else { self.detailView.alpha = (self.viewHeight/3 - abs(distance)) / (self.viewHeight/3) } } if animated { UIView.animateWithDuration(0.2, animations: { () -> Void in self.showModeSelection(false) changeView() }, completion: { (completed: Bool) -> Void in self.showModeSelection(false) }) } else { changeView() } } func isSpotDetailsHidden() -> Bool { //we know if the view is hidden based on the bottom offset, as can be seen in the two methods above //make.bottom.equalTo(self.view).offset(180) is to hide it and //make.bottom.equalTo(self.view).offset(0) is to show it for constraint: LayoutConstraint in detailView.snp_installedLayoutConstraints { if constraint.firstItem.isEqual(self.detailView) && (constraint.secondItem != nil && constraint.secondItem!.isEqual(self.view)) && Float(constraint.constant) == 180 { return true } } return false } func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { } // MARK: Helper Methods func hideModeSelection() { modeSelection.hidden = true } func showModeSelection(forceShow: Bool) { //only shows the button if the searchField is 'hidden' if !forceShow && !self.isSpotDetailsHidden() { return } modeSelection.hidden = false } func modeSelectionValueChanged() { var mapMode = MapMode.StreetParking let tracker = GAI.sharedInstance().defaultTracker switch(self.modeSelection.selectedIndex) { case 0: //oh em gee you wanna see garages! mapMode = .Garage self.screenName = "Here - General View - ParkingLot" tracker.send(GAIDictionaryBuilder.createEventWithCategory("Here - General View", action: "Mode Slider Value Changed", label: "Parking Lot", value: nil).build() as [NSObject: AnyObject]) filterVC.showingCarSharingTabBar = false Settings.setShouldFilterForCarSharing(mapMode == .CarSharing) self.delegate?.didSelectMapMode(mapMode) self.filterVC.hideFilters(completely: false, resettingTimeFilterValue: true) filterVC.shouldShowTimeFilter = false break case 1: //oh. em. gee. you wanna see street parking! mapMode = .StreetParking self.screenName = "Here - General View - On-Street" tracker.send(GAIDictionaryBuilder.createEventWithCategory("Here - General View", action: "Mode Slider Value Changed", label: "On Street", value: nil).build() as [NSObject: AnyObject]) filterVC.showingCarSharingTabBar = false Settings.setShouldFilterForCarSharing(mapMode == .CarSharing) self.delegate?.didSelectMapMode(mapMode) self.filterVC.hideFilters(completely: false, resettingTimeFilterValue: true) filterVC.shouldShowTimeFilter = true break case 2: //oh. em. geeeeeeee you wanna see car sharing spots! mapMode = .CarSharing if Settings.firstCarSharingUse() { Settings.setFirstCarSharingUsePassed(true) showCarSharingInfo() } self.screenName = "Here - General View - CarSharing" tracker.send(GAIDictionaryBuilder.createEventWithCategory("Here - General View", action: "Mode Slider Value Changed", label: "CarSharing", value: nil).build() as [NSObject: AnyObject]) filterVC.showingCarSharingTabBar = true filterVC.shouldShowTimeFilter = false Settings.setShouldFilterForCarSharing(mapMode == .CarSharing) self.delegate?.didSelectMapMode(mapMode) self.filterVC.hideFilters(completely: false, resettingTimeFilterValue: true) break default:break } AnalyticsOperations.sendMapModeChange(mapMode) } // MARK: TimeFilterViewDelegate func filterValueWasChanged(hours hours:Float?, selectedLabelText: String, permit: Bool, fromReset: Bool) { self.delegate?.updateMapAnnotations(nil) // filterButtonText = selectedLabelText // filterButton.setLabelText(selectedLabelText) // hideFilters(alsoHideFilterButton: false) } func filterLabelUpdate(labelText: String) { // filterButtonText = labelText // filterButton.setLabelText(labelText) } func didTapCarSharing() { self.delegate?.loadSettingsTab() } func didTapTrackUserButton() { self.delegate?.didTapTrackUserButton() } func didTapMapMessage() { if (mapMessageView.mapMessageLabel.text ?? "") == "map_message_too_zoomed_out".localizedString { self.delegate?.setDefaultMapZoom() } else if (mapMessageView.mapMessageLabel.text ?? "") == "map_message_no_carsharing".localizedString { self.delegate?.loadSettingsTab() } else if (mapMessageView.mapMessageLabel.text ?? "") == "map_message_no_parking".localizedString { self.delegate?.updateMapAnnotations(1) } else if (mapMessageView.mapMessageLabel.text ?? "") == "map_message_no_cars".localizedString { self.delegate?.updateMapAnnotations(1) } } func didChangeCarSharingMode(mode: CarSharingMode) { self.delegate?.setDefaultMapZoom() //zooming should automatically generate an update, so we don't have to do it manually self.delegate?.updateMapAnnotations(1) } // MARK: Car sharing popup func showCarSharingInfo() { carSharingInfoVC = CarSharingInfoViewController() self.addChildViewController(carSharingInfoVC!) self.view.addSubview(carSharingInfoVC!.view) carSharingInfoVC!.didMoveToParentViewController(self) carSharingInfoVC!.view.snp_makeConstraints(closure: { (make) -> () in make.edges.equalTo(self.view) }) let tap = UITapGestureRecognizer(target: self, action: "dismissCarSharingInfo") carSharingInfoVC!.view.addGestureRecognizer(tap) carSharingInfoVC!.view.alpha = 0.0 UIView.animateWithDuration(0.2, animations: { () -> Void in self.carSharingInfoVC!.view.alpha = 1.0 }) } func dismissCarSharingInfo() { if let carShareingInfo = self.carSharingInfoVC { UIView.animateWithDuration(0.2, animations: { () -> Void in carShareingInfo.view.alpha = 0.0 }, completion: { (finished) -> Void in carShareingInfo.removeFromParentViewController() carShareingInfo.view.removeFromSuperview() carShareingInfo.didMoveToParentViewController(nil) self.carSharingInfoVC = nil }) } } } protocol HereViewControllerDelegate { func loadMyCarTab() func loadSettingsTab() func updateMapAnnotations(returnNearestAnnotations: Int?) func cityDidChange(fromCity fromCity: City, toCity: City) func didSelectMapMode(mapMode: MapMode) func setDefaultMapZoom() func didTapTrackUserButton() }
// // GameScene.swift // EscapeGame // // Created by MrChen on 2019/4/5. // Copyright © 2019 MrChen. All rights reserved. // import SpriteKit import GameplayKit class GameScene: SKScene, SKPhysicsContactDelegate { // 手指开始点击屏幕的位置 var touchBeginLocation: CGPoint! // 背景 lazy var backgroundNode: SKSpriteNode = { let bgNode = SKSpriteNode(imageNamed: "bg") bgNode.size = self.size bgNode.anchorPoint = CGPoint(x: 0.0, y: 0.0) bgNode.position = CGPoint(x: 0.0, y: 0.0) return bgNode }() // 小球 lazy var ballNode: SKSpriteNode = { let ball = SKSpriteNode(imageNamed: "ball") ball.name = BallCategoryName ball.zPosition = BallzPosition let trailNode = SKNode() trailNode.zPosition = 1 addChild(trailNode) let trail = SKEmitterNode(fileNamed: "BallTrail")! trail.targetNode = trailNode ball.addChild(trail) return ball }() // 挡板 lazy var paddle: SKSpriteNode = { let paddleNode = SKSpriteNode(imageNamed: "paddle") paddleNode.zPosition = PaddlezPosition return paddleNode }() // 地面 private var groundNode: SKNode = SKNode() // 游戏提示文字 lazy var gameMessageNode: SKSpriteNode = { let gameMessage = SKSpriteNode(imageNamed: "TapToPlay") gameMessage.name = GameMessageName gameMessage.position = CGPoint(x: frame.midX, y: frame.midY) gameMessage.zPosition = GameMessagezPosition gameMessage.setScale(0.0) return gameMessage }() // 游戏状态 lazy var gameState: GKStateMachine = GKStateMachine(states: [ WaitingForTap(scene:self), Playing(scene: self), Pause(scene: self), GameOver(scene: self)]) // 游戏赢了还是输了 var gameWon : Bool = false { didSet { let gameOver = childNode(withName: GameMessageName) as! SKSpriteNode let textureName = gameWon ? "YouWon" : "GameOver" let texture = SKTexture(imageNamed: textureName) let actionSequence = SKAction.sequence([SKAction.setTexture(texture), SKAction.scale(to: 1.0, duration: 0.25)]) gameOver.run(actionSequence) run(gameWon ? gameWonSound : gameOverSound) } } // 游戏音效 let blipSound = SKAction.playSoundFileNamed("pongblip", waitForCompletion: false) let blipPaddleSound = SKAction.playSoundFileNamed("paddleBlip", waitForCompletion: false) let bambooBreakSound = SKAction.playSoundFileNamed("BambooBreak", waitForCompletion: false) let gameWonSound = SKAction.playSoundFileNamed("game-won", waitForCompletion: false) let gameOverSound = SKAction.playSoundFileNamed("game-over", waitForCompletion: false) override func didMove(to view: SKView) { // 设置场景(添加Nodes) setScene() // 设置场景内物体的物理体 setPhysicsBody() // 初始化游戏 shuffleGame() // 设置游戏初始状态 gameState.enter(WaitingForTap.self) } // 点击屏幕 override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { let touch = touches.first touchBeginLocation = touch!.location(in: self) } // 手指在屏幕上滑动 override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { // 只有游戏处于playing状态的时候挡板才能被拖拽 if gameState.currentState is Playing { // 获取手指的位置 计算移动的距离 let touch = touches.first let touchLocation = touch!.location(in: self) let previousLocation = touch!.previousLocation(in: self) // 计算挡板的x左边值(当前x值加上手指在屏幕上的移动差值) var paddleX = paddle.position.x + (touchLocation.x - previousLocation.x) // 调整挡板x值 防止移出屏幕外 paddleX = max(paddleX, paddle.size.width/2) paddleX = min(paddleX, size.width - paddle.size.width/2) // 更新挡板位置 paddle.position = CGPoint(x: paddleX, y: paddle.position.y) } } // 点击事件结束 override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { // 通过计算手指在屏幕上的移动距离来判断是点击屏幕还是滑动 let touch = touches.first let touchEndLocation = touch!.location(in: self) // 求x方向和y方向的移动距离绝对值 let offsetX = abs(touchEndLocation.x - touchBeginLocation.x) let offsetY = abs(touchEndLocation.y - touchBeginLocation.y) if offsetX < 5 && offsetY < 5 { // 如果手指移动范围在5以内 视作点击屏幕 更新游戏状态 updateGameState() }else { // 否则视为滑动屏幕 移动逻辑处理在touchesMoved方法里面做 } } // 监听场景内物体碰撞 func didBegin(_ contact: SKPhysicsContact) { if gameState.currentState is Playing { var firstBody: SKPhysicsBody var secondBody: SKPhysicsBody // 获取碰撞的两个物体,并区分大小 if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask { firstBody = contact.bodyA secondBody = contact.bodyB }else { firstBody = contact.bodyB secondBody = contact.bodyA } // 如果是小球和地板碰撞 游戏结束 if firstBody.categoryBitMask == BallCategory && secondBody.categoryBitMask == GroundCategory { // 设置游戏状态为结束 gameState.enter(GameOver.self) // 设置玩家输赢标识 gameWon = false } // 小球和砖块碰撞 if firstBody.categoryBitMask == BallCategory && secondBody.categoryBitMask == BlockCategory { // 碰撞到的砖块消失 breakBlock(node: secondBody.node!) // 播放破碎音效 run(bambooBreakSound) // 检测玩家是否赢了 if isGameWon() { gameState.enter(GameOver.self) // 玩家赢了 gameWon = true } } // 小球与挡板碰撞 if firstBody.categoryBitMask == BallCategory && secondBody.categoryBitMask == PaddleCategory{ // 播放音效 run(blipPaddleSound) } // 小球与墙壁碰撞 if firstBody.categoryBitMask == BallCategory && secondBody.categoryBitMask == BorderCategory { // 播放音效 run(blipSound) } } } // 设置场景(添加Nodes) func setScene() { // 背景图片 addChild(backgroundNode) // 添加小球 addChild(ballNode) // 添加挡板 addChild(paddle) // 添加地面 addChild(groundNode) // 添加游戏提示节点 addChild(gameMessageNode) } // 添加砖块 func addBlocks() { // 移除上局残留的砖块 for vestigitalBlock in self.children where vestigitalBlock.name == BlockCategoryName { vestigitalBlock.removeFromParent() } // 添加4行砖 let blockRowNumber: Int = 1 // 获取每一块砖头的size let blockSize: CGSize = SKSpriteNode(imageNamed: "block").size // 计算一行最多添加几块砖 let blockCountInRow: Int = Int(ceil(self.size.width / blockSize.width)) // 循环把所有的砖添加上(双循环添加4行blockCountInRow列的砖块) for i in 0..<blockRowNumber { for j in 0..<blockCountInRow { // 计算当前砖块的position let blockX = blockSize.width * 0.5 + blockSize.width * CGFloat(j) let blockY = self.size.height - blockSize.height * 0.5 - CGFloat(i) * blockSize.height - 50.0 let block: SKSpriteNode = SKSpriteNode(imageNamed: "block") block.name = BlockCategoryName block.position = CGPoint(x: blockX, y: blockY) block.zPosition = BlockzPosition addChild(block) // 设置砖头物理体 let blockPhysicsBody: SKPhysicsBody = SKPhysicsBody(rectangleOf: block.frame.size) // 不允许旋转 blockPhysicsBody.allowsRotation = false // 摩擦系数为0 blockPhysicsBody.friction = 0.0 // 不受重力影响 blockPhysicsBody.affectedByGravity = false // 不受物理因素影响 blockPhysicsBody.isDynamic = false // 标识 blockPhysicsBody.categoryBitMask = BlockCategory block.physicsBody = blockPhysicsBody } } } // 设置场景内物体的物理体 func setPhysicsBody() { // 给场景添加一个物理体,这个物理体就是一条沿着场景四周的边,限制了游戏范围,其他物理体就不会跑出这个场景 self.physicsBody = SKPhysicsBody(edgeLoopFrom: self.frame) // 物理世界的碰撞检测代理为场景自己,这样如果这个物理世界里面有两个可以碰撞接触的物理体碰到一起了就会通知他的代理 self.physicsBody?.categoryBitMask = BorderCategory self.physicsWorld.contactDelegate = self // 设置挡板的物理体 let paddlePhysicsBody = SKPhysicsBody(texture: paddle.texture!, size: paddle.size) // 挡板摩擦系数设为0 paddlePhysicsBody.friction = 0.0 // 恢复系数1.0 paddlePhysicsBody.restitution = 1.0 // 不受物理环境因素影响 paddlePhysicsBody.isDynamic = false paddle.physicsBody = paddlePhysicsBody paddle.physicsBody?.categoryBitMask = PaddleCategory // 设置地面物理体 let groundPhysicsBody = SKPhysicsBody(edgeLoopFrom: CGRect(x: frame.origin.x, y: frame.origin.y, width: size.width, height: 1.0)) groundNode.physicsBody = groundPhysicsBody groundNode.physicsBody?.categoryBitMask = GroundCategory // 设置小球的物理体 let ballPhysicsBody = SKPhysicsBody(texture: ballNode.texture!, size: ballNode.size) // 不允许小球旋转 ballPhysicsBody.allowsRotation = false // 摩擦系数为0 ballPhysicsBody.friction = 0.0 // 小球恢复系数为1(与物体碰撞以后,小球以相同的力弹回去) ballPhysicsBody.restitution = 1.0 // 小球线性阻尼(小球是否收到空气阻力,设为0表示不受空气阻力) ballPhysicsBody.linearDamping = 0.0 // 小球角补偿(因为不允许旋转所以设置为0) ballPhysicsBody.angularDamping = 0.0 ballNode.physicsBody = ballPhysicsBody ballNode.physicsBody?.categoryBitMask = BallCategory // 小球和地面、砖头接触会发生碰撞 ballNode.physicsBody?.contactTestBitMask = GroundCategory | BlockCategory | PaddleCategory | BorderCategory // 小球不受物理环境影响 ballNode.physicsBody?.isDynamic = false } // 初始化游戏 func shuffleGame() { // 设置小球初始位置 ballNode.position = CGPoint(x: self.size.width * 0.5, y: self.size.height * 0.5 + 50) // 设置挡板初始位置 paddle.position = CGPoint(x: self.size.width * 0.5, y: 20.0) // 添加砖块 addBlocks() // 小球受物理环境影响 ballNode.physicsBody?.isDynamic = true // 去掉重力加速度 physicsWorld.gravity = CGVector(dx: 0.0, dy: 0.0) } // 判断游戏是否赢了 func isGameWon() -> Bool { // 遍历所有子节点 计算剩余砖块数量 var numberOfBricks = 0 self.enumerateChildNodes(withName: BlockCategoryName) { (node, stop) in numberOfBricks += 1 } return numberOfBricks == 0 } // 断开砖块 func breakBlock(node: SKNode) { let particles: SKEmitterNode = SKEmitterNode(fileNamed: "BrokenPlatform")! particles.position = node.position particles.zPosition = BallzPosition + 2 addChild(particles) particles.run(SKAction.sequence([SKAction.wait(forDuration: 1.0),SKAction.removeFromParent()])) node.removeFromParent() } override func update(_ currentTime: TimeInterval) { gameState.update(deltaTime: currentTime) } // 更新游戏状态 func updateGameState() { switch gameState.currentState { case is WaitingForTap: // 当前是等待点击开始状态 点击屏幕开始游戏 gameState.enter(Playing.self) case is Playing: // 当前是正在游戏状态 点击屏幕暂停 gameState.enter(Pause.self) print("游戏暂停了") case is Pause: // 当前是暂停状态 点击屏幕继续游戏 gameState.enter(Playing.self) print("游戏继续了") case is GameOver: // 当前是游戏结束状态 点击重新开始游戏 // 创建新的场景替换当前场景 let newScene = GameScene(size: self.size) newScene.scaleMode = .aspectFit let reveal = SKTransition.flipHorizontal(withDuration: 0.5) self.view?.presentScene(newScene, transition: reveal) default: break } } }
// // DatabaseWarningError.swift // RepoDB // // Created by Groot on 13.09.2020. // Copyright © 2020 K. All rights reserved. // import Foundation struct DatabaseWarningError: RepoDatabaseError { var code: Int { return 28 } var message: String { return ErrorLocalizer.error_code_28.localize() } }
// // SettingsVC.swift // DrawingApp // // Created by Alex Nguyen on 2016-05-09. // Copyright © 2016 Alex Nguyen. All rights reserved. // import UIKit import pop class SettingsVC: UIViewController { weak var drawingVC : ViewController? = nil @IBOutlet weak var brushSizeSlider: UISlider! @IBOutlet weak var opacitySlider: UISlider! @IBOutlet weak var BrushSizeTxtConstraint: NSLayoutConstraint! @IBOutlet weak var demoImageView: UIImageView! @IBOutlet weak var bottomConstraint: NSLayoutConstraint! @IBOutlet weak var demoViewConstraint: NSLayoutConstraint! @IBOutlet weak var brushSliderConstraint: NSLayoutConstraint! @IBOutlet weak var opacitySliderConstraint: NSLayoutConstraint! var animationEngine: AnimationEngine! override func viewDidLoad() { super.viewDidLoad() self.navigationController?.navigationBarHidden = false self.animationEngine = AnimationEngine(constraints: [bottomConstraint, demoViewConstraint, brushSliderConstraint, opacitySliderConstraint, BrushSizeTxtConstraint]) } override func viewWillAppear(animated: Bool) { brushSizeSlider.value = Float((drawingVC?.brushSize)!) opacitySlider.value = Float((drawingVC?.opacity)!) adjustDemoView() } override func viewDidAppear(animated: Bool) { self.animationEngine.animateOnScreen(0) } @IBAction func eraseTapped(sender: AnyObject) { drawingVC?.eraseDrawing() self.navigationController?.popViewControllerAnimated(true) } @IBAction func sharedTapped(sender: AnyObject) { if let image = self.drawingVC?.drawingView.image { let activityVC = UIActivityViewController(activityItems: [image], applicationActivities: nil) self.presentViewController(activityVC, animated: true, completion: nil) } } func adjustDemoView() { //Reset demo image view demoImageView.image = nil //Set the context size UIGraphicsBeginImageContext(self.demoImageView.frame.size) //Grab the context let context = UIGraphicsGetCurrentContext() //Set the drawing size self.demoImageView.image?.drawInRect(CGRect(x: 0, y: 0, width: self.demoImageView.frame.size.width, height: self.demoImageView.frame.size.height)) //Move content to the last point CGContextMoveToPoint(context, self.demoImageView.frame.size.width/2, self.demoImageView.frame.size.height/2) CGContextAddLineToPoint(context, self.demoImageView.frame.size.width/2, self.demoImageView.frame.size.height/2) CGContextSetRGBStrokeColor(context, drawingVC!.red, drawingVC!.green, drawingVC!.blue, drawingVC!.opacity) //Set the shape of the line CGContextSetLineCap(context, .Round) //Set the size of the line CGContextSetLineWidth(context, (drawingVC?.brushSize)!) //Stroke the path CGContextStrokePath(context) //Draw context onto image self.demoImageView.image = UIGraphicsGetImageFromCurrentImageContext() //End context editing UIGraphicsEndImageContext() } @IBAction func brushSizeChanged(sender: AnyObject) { drawingVC?.changeBrushSizeTo(CGFloat(brushSizeSlider.value)) adjustDemoView() } @IBAction func opacityChanged(sender: AnyObject) { drawingVC?.changeOpacityTo(CGFloat(opacitySlider.value)) adjustDemoView() } }
// // UIViewController+Ext.swift // Jocelyn-Boyd-TandemFor400 // // Created by Jocelyn Boyd on 10/29/20. // import UIKit extension UIViewController { func showAlert(title: String?, message: String?, action: (() -> ())?) { let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) let nextQuestionAction = UIAlertAction(title: "Next", style: .default) { (_) in action?() } alert.addAction(nextQuestionAction) present(alert, animated: true) } }
import UIKit import SkeletonView class TvShowsTableViewController: UITableViewController { //MARK: Propiedades private let cellName: String = "CeldaPeliculaTableViewCell" private var tvShows: Array<TvShowRes> = [] private var seleccion: Int! //MARK: Ciclo de vida override func viewDidLoad() { super.viewDidLoad() disenoBarra() self.startSkeleton() self.traerInformacion() self.tableView.register(UINib(nibName: cellName, bundle: nil), forCellReuseIdentifier: cellName) } //MARK: Metodos private func disenoBarra() -> Void { if #available(iOS 13.0, *) { let statusBar = UIView(frame: UIApplication.shared.windows.first?.windowScene?.statusBarManager?.statusBarFrame ?? CGRect.zero) statusBar.backgroundColor = UIColor(named: "Barras") UIApplication.shared.windows.first?.addSubview(statusBar) } } private func traerInformacion() -> Void { let tvShowService = TvShowService() tvShowService.consulta { (error, resultado) in DispatchQueue.main.async { self.stopSkeleton() if error != nil { self.alertaRecarga() return } self.tvShows = resultado self.tableView.reloadData() } } } private func alertaRecarga() -> Void { Alertas.errorInternet(controlador: self) { (res) in if res { self.traerInformacion() } } } private func startSkeleton() -> Void { self.tableView.showAnimatedGradientSkeleton() } private func stopSkeleton() -> Void { self.tableView.hideSkeleton() } // MARK: - Data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tvShows.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let celda = tableView.dequeueReusableCell(withIdentifier: cellName, for: indexPath) as! CeldaPeliculaTableViewCell celda.llenarInfo(tvShows: tvShows[indexPath.row]) return celda } override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? { let serie = self.tvShows[indexPath.row] let serieEncontrada = ShowsRepository.consultar(id: serie.id!) var swipeActions = UISwipeActionsConfiguration() let accion = UIContextualAction(style: .normal, title: serieEncontrada == nil ? "Favoritos" : "Eliminar") { (contextualAction, view, boolValue) in if serieEncontrada == nil { self.present(Alertas.eliminaGuarda(status: ShowsRepository.guardar(tvShow: self.tvShows[indexPath.row]), eliminar: false), animated: true, completion: nil) } else { Alertas.preguntaEliminar(controlador: self) { (res) in if res { let res = serieEncontrada == nil ? ShowsRepository.guardar(tvShow: self.tvShows[indexPath.row]) : ShowsRepository.eliminar(id: serie.id!) self.present(Alertas.eliminaGuarda(status: res, eliminar: serieEncontrada != nil), animated: true, completion: nil) } } } } accion.backgroundColor = serieEncontrada == nil ? .green : .red swipeActions = UISwipeActionsConfiguration(actions: [accion]) return swipeActions } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 96 } //MARK: Delegados override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { seleccion = indexPath.row performSegue(withIdentifier: "detalle", sender: self) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "detalle" { let detalle = segue.destination as! DetalleViewController let serie = tvShows[seleccion] detalle.idTvShow = serie.id detalle.tvShowRes = serie } } }
// // LSHTTPSession.swift // LetSing // // Created by MACBOOK on 2018/5/4. // Copyright © 2018年 MACBOOK. All rights reserved. // import Foundation import Alamofire typealias DataCallBack = (Data) -> Void typealias ErrorCallBack = (Error) -> Void protocol LSHTTPApiClient { @discardableResult func requestAlamofire( _ request: URLRequestConvertible, success: @escaping DataCallBack, failure: @escaping ErrorCallBack ) -> DataRequest? } struct ApiClient: LSHTTPApiClient { let queue: DispatchQueue @discardableResult func requestAlamofire( _ request: URLRequestConvertible, success: @escaping (Data) -> Void, failure: @escaping (Error) -> Void ) -> DataRequest? { return Alamofire.SessionManager.default.request(request).validate().responseData( queue: queue, completionHandler: { response in switch response.result { case .success(let data): success(data) case .failure(let error): failure(error) } } ) } } class LSHTTPClient { static let shared = LSHTTPClient() let queue: DispatchQueue var apiClient: LSHTTPApiClient private init () { queue = DispatchQueue(label: String(describing: LSHTTPClient.self) + UUID().uuidString, qos: .default, attributes: .concurrent) apiClient = ApiClient(queue: queue) } // 當你 return 的東西沒有進入一個值,為避免compiler給予警告,所以會加discardable // ex: _ = LSHTTPClient.shared.request @discardableResult func request( _ LSHTTPRequest: LSHTTPRequest, success: @escaping (Data) -> Void, failure: @escaping (Error) -> Void ) -> DataRequest? { do { return try apiClient.requestAlamofire(LSHTTPRequest.request(), success: success, failure: failure) } catch { failure(error) return nil } } }
// // InterfaceController.swift // WatchOSSample Extension // // Created by Motoki on 2015/06/20. // Copyright © 2015年 MotokiNarita. All rights reserved. // import WatchKit import Foundation import WatchConnectivity class InterfaceController: WKInterfaceController, WCSessionDelegate { @IBOutlet var picker: WKInterfacePicker! override func awakeWithContext(context: AnyObject?) { super.awakeWithContext(context) let hapticNames = [ "Notification", "DirectionUp", "DirectionDown", "Success", "Failure", "Retry", "Start", "Stop", "Click",] var pickerItems: [WKPickerItem] = [WKPickerItem]() for i in 0...8 { let item = WKPickerItem() item.title = hapticNames[i] item.caption = "WKHapticType" pickerItems.append(item) } self.picker.setItems(pickerItems) } override func willActivate() { // This method is called when watch view controller is about to be visible to user super.willActivate() } override func didDeactivate() { // This method is called when watch view controller is no longer visible super.didDeactivate() } @IBAction func action(value: Int) { let device = WKInterfaceDevice() device.playHaptic(WKHapticType(rawValue: value)!) } @IBAction func connect() { if WCSession.isSupported() { let session = WCSession.defaultSession() session.delegate = self session.activateSession() let device = WKInterfaceDevice() device.playHaptic(WKHapticType.Success) let message = ["message": "Messagekey"] session.sendMessage(message, replyHandler: { (replyMassage) -> Void in print("\(replyMassage)") }, errorHandler: { (error) -> Void in print("error") }) } } }
import Fineliner Fineliner().printShhuffledPens()