text
stringlengths
8
1.32M
// // Outfit.swift // Looksie // // Created by Alex Fu on 5/8/15. // Copyright (c) 2015 Alex Fu. All rights reserved. // import UIKit class Outfit: NSObject { }
import AVFoundation import UIKit class ExactScannerVC: UIViewController, AVCaptureMetadataOutputObjectsDelegate { var captureSession: AVCaptureSession! var previewLayer: AVCaptureVideoPreviewLayer! var scanRect = UIImageView() var lblScan = UILabel() let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil) var screenWidth = UIScreen.main.bounds.width var screenHeight = UIScreen.main.bounds.height var scanQR = "" var connecting = "" override func viewDidLoad() { super.viewDidLoad() if !Reachability.isConnectedToNetwork(){ let alert = UIAlertController(title: "Connection Failed", message: "Please check the internet connection and try again.", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: close)) self.present(alert, animated: true) } let backBtn = UIBarButtonItem() backBtn.title = "" navigationItem.backBarButtonItem = backBtn let lang = UserDefaults.standard.string(forKey: "lang") if(lang != nil){ changeLanguage(str: lang!) } view.backgroundColor = UIColor.white captureSession = AVCaptureSession() guard let videoCaptureDevice = AVCaptureDevice.default(for: .video) else { return } let videoInput: AVCaptureDeviceInput do { videoInput = try AVCaptureDeviceInput(device: videoCaptureDevice) } catch { return } if (captureSession.canAddInput(videoInput)) { captureSession.addInput(videoInput) } else { failed() return } let metadataOutput = AVCaptureMetadataOutput() if (captureSession.canAddOutput(metadataOutput)) { captureSession.addOutput(metadataOutput) metadataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main) metadataOutput.metadataObjectTypes = [.qr] } else { failed() return } self.scanRect.frame = CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight*9/10) previewLayer = AVCaptureVideoPreviewLayer(session: captureSession) previewLayer.frame = CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight*9/10) previewLayer.videoGravity = .resizeAspectFill view.addSubview(self.scanRect) let scanRound = UIView(frame: CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight*9/10)) self.scanRect.addSubview(scanRound) scanRound.layer.addSublayer(previewLayer) self.lblScan.frame = CGRect(x: 0, y: screenHeight*9/10, width: screenWidth, height: screenHeight/10) self.lblScan.text = scanQR self.lblScan.font = UIFont.boldSystemFont(ofSize: 20.0) self.lblScan.textColor = UIColor.black self.lblScan.textAlignment = .center view.addSubview(lblScan) captureSession.startRunning() } func failed() { let ac = UIAlertController(title: "Scanning not supported", message: "Your device does not support scanning a code from an item. Please use a device with a camera.", preferredStyle: .alert) ac.addAction(UIAlertAction(title: "OK", style: .default)) present(ac, animated: true) captureSession = nil } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if (captureSession?.isRunning == false) { captureSession.startRunning() } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) if (captureSession?.isRunning == true) { captureSession.stopRunning() } } func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) { captureSession.stopRunning() if let metadataObject = metadataObjects.first { guard let readableObject = metadataObject as? AVMetadataMachineReadableCodeObject else { return } guard let stringValue = readableObject.stringValue else { return } AudioServicesPlaySystemSound(SystemSoundID(kSystemSoundID_Vibrate)) found(code: stringValue) } dismiss(animated: true) } func found(code: String) { self.lblScan.text = connecting let vc = storyBoard.instantiateViewController(withIdentifier: "Money2Device") as! Money2DeviceVC vc.vendName = code self.navigationController!.pushViewController(vc, animated:true) } override var prefersStatusBarHidden: Bool { return true } func close (action: UIAlertAction){ exit(-1) } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { return .portrait } func changeLanguage(str: String){ self.scanQR = "focus".addLocalizableString(str: str) self.connecting = "connecting".addLocalizableString(str: str) } }
// // AppDelegate.swift // Gravity // // Created by Luca Friedrich on 13/01/2016. // Copyright © 2016 YaLu. All rights reserved. // import UIKit import AVFoundation @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var gameSettings = Dictionary<String, AnyObject>() func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { return true } #if os(iOS) @available(iOS 9.0, *) func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) { completionHandler(handleQuickAction(shortcutItem)) } #endif func applicationWillResignActive(_ application: UIApplication) { if vars.musicPlaying == true { GameViewController.MusicPause() } if vars.currentGameState == .gameActive { vars.gameScene?.stopTimerAfter() vars.gameModeBefore = vars.extremeMode } } func applicationDidEnterBackground(_ application: UIApplication) { } func applicationWillEnterForeground(_ application: UIApplication) { } func applicationDidBecomeActive(_ application: UIApplication) { updateSoundState() if vars.currentGameState == .gameActive { vars.gameScene?.startTimerAfter() } #if os(iOS) gameSettings = ["motioncontrol": "Motion Control" as AnyObject] gameSettings = ["extreme": "Extreme Mode" as AnyObject] UserDefaults.standard.register(defaults: gameSettings) vars.motionControl = UserDefaults.standard.bool(forKey: "motioncontrol") vars.extremeMode = UserDefaults.standard.bool(forKey: "extreme") #endif if vars.currentGameState == .gameActive && vars.extremeMode == true && vars.gameModeBefore == false { vars.gameScene?.goToMenu() } else if vars.currentGameState == .gameActive && vars.extremeMode == false && vars.gameModeBefore == true { vars.gameScene?.goToMenu() } #if os(iOS) if vars.motionControl == true{ vars.gameScene?.initMotionControl() } else { vars.gameScene?.cancelMotionControl() } #endif if vars.extremeMode == true { vars.gameScene?.initExtremeMode() } else { vars.gameScene?.initNormalMode() } } func updateSoundState() { let hint = AVAudioSession.sharedInstance().secondaryAudioShouldBeSilencedHint if hint == true { vars.musicState = false } else { vars.musicState = true } if vars.musicState == true { GameViewController.MusicOff() } else { GameViewController.MusicOn() } } func applicationWillTerminate(_ application: UIApplication) { } @available(iOS 9.0, *) enum Shortcut: String { case motionControl = "MotionControl" case touchControl = "TouchControl" } #if os(iOS) @available(iOS 9.0, *) func handleQuickAction(_ shortcutItem: UIApplicationShortcutItem) -> Bool { var quickActionHandled = false let type = shortcutItem.type.components(separatedBy: ".").last! if let shortcutType = Shortcut.init(rawValue: type) { switch shortcutType { case .motionControl: UserDefaults.standard.set(true, forKey: "motioncontrol") UserDefaults.standard.synchronize() vars.motionControl = true quickActionHandled = true case .touchControl: UserDefaults.standard.set(false, forKey: "motioncontrol") UserDefaults.standard.synchronize() vars.motionControl = false quickActionHandled = true } } return quickActionHandled } #endif }
// // ViewController.swift // FootTracking // // Created by Yang on 2020/07/07. // Copyright © 2020 Minestrone. All rights reserved. // import UIKit import CoreML import ARKit import Vision class ViewController: UIViewController, ARSessionDelegate { @IBOutlet var sceneView: ARSCNView! var currentBuffer: CVPixelBuffer? var previewView = UIImageView() let footDetector = FootDetector() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. let configuration = ARWorldTrackingConfiguration() sceneView.session.delegate = self sceneView.session.run(configuration) view.addSubview(previewView) previewView.translatesAutoresizingMaskIntoConstraints = false previewView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true previewView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true } func session(_ session: ARSession, didUpdate frame: ARFrame) { guard currentBuffer == nil, case .normal = frame.camera.trackingState else { return } currentBuffer = frame.capturedImage startDetection() } private func startDetection() { guard let buffer = currentBuffer else { return } footDetector.performDetection(inputBuffer: buffer) { outputBuffer, _ in var previewImage: UIImage? defer { DispatchQueue.main.async { self.previewView.image = previewImage self.currentBuffer = nil } } guard let outBuffer = outputBuffer else { return } previewImage = UIImage(ciImage: CIImage(cvPixelBuffer: outBuffer)) } } }
// // NewProject // Copyright (c) Yuichi Nakayasu. All rights reserved. // import Foundation protocol TemplateInteractorInput: class { var output: TemplateInteractorOutput! { get set } func generate(type: TemplateType) -> TemplateModel func fetch(type: TemplateType, nameCondition: String?) func register(_ model: TemplateModel) func remove(_ model: TemplateModel) } protocol TemplateInteractorOutput: class { func fetched(_ models: [TemplateModel]) func updated(_ models: [TemplateModel]) } class TemplateRepository: TemplateInteractorInput { weak var output: TemplateInteractorOutput! func generate(type: TemplateType) -> TemplateModel { return TemplateModel() } func fetch(type: TemplateType, nameCondition: String?) { } func register(_ model: TemplateModel) { } func remove(_ model: TemplateModel) { } }
// // NurseCategoryCVCell.swift // NurseBookingSystem // // Created by mac on 6/20/20. // Copyright © 2020 mac. All rights reserved. // import UIKit class NurseCategoryCVCell: UICollectionViewCell { }
// // String+Util.swift // UserPost // // Created by Miguel Cazares on 1/21/18. // Copyright © 2018 Miguel Cazares. All rights reserved. // import UIKit extension String { func camelCaseToDashCase() -> String { let pattern = "([a-z0-9])([A-Z])" let regex = try? NSRegularExpression(pattern: pattern, options: []) let range = NSRange(location: 0, length: length) if regex == nil { return defaultString } return regex!.stringByReplacingMatches(in: self, options: [], range: range, withTemplate: "$1-$2").lowercased() } }
// // EventDetailController.swift // MC3 Volunteering // // Created by Silamitra Edvyn Tanu on 21/08/19. // Copyright © 2019 Silamitra Edvyn Tanu. All rights reserved. // import UIKit class EventDetailController: UIViewController{ var imageEvent: UIImage? var imageFriendPhoto1: UIImage? var imageFriendPhoto2: UIImage? var imageFriendPhoto3: UIImage? var imageEOPhoto: UIImage? var eventTitle: String? var numberOFfriends: String? var eventLocation: String? var eventTime: String? var eventDate: String? var eventOrganizer: String? var eventDescription: String? @IBOutlet weak var judulDetailEventLabel: UILabel! @IBOutlet weak var lblNumberOfFriends: UILabel! @IBOutlet weak var lblLocation: UILabel! @IBOutlet weak var lblTime: UILabel! @IBOutlet weak var lblDate: UILabel! @IBOutlet weak var lblEventOrganizer: UILabel! @IBOutlet weak var lblDescription: UILabel! @IBOutlet weak var imageEventDetailed: UIImageView! @IBOutlet weak var imageFriend2: UIImageView! @IBOutlet weak var imageFriend1: UIImageView! @IBOutlet weak var imageFriend3: UIImageView! @IBOutlet weak var imageEventOrganizer: UIImageView! @IBOutlet var goAloneButton: UIButton! @IBOutlet var inviteFriendButton: UIButton! override func viewDidLoad() { super.viewDidLoad() goAloneButton.layer.borderColor = #colorLiteral(red: 0.3039953709, green: 0.6345664263, blue: 0.8838434815, alpha: 1) goAloneButton.layer.borderWidth = 1 inviteFriendButton.layer.borderColor = #colorLiteral(red: 0.3039953709, green: 0.6345664263, blue: 0.8838434815, alpha: 1) inviteFriendButton.layer.borderWidth = 1 imageFriend1.layer.cornerRadius = imageFriend1.frame.height / 2 imageFriend2.layer.cornerRadius = imageFriend2.frame.height / 2 imageFriend3.layer.cornerRadius = imageFriend3.frame.height / 2 imageEventOrganizer.layer.cornerRadius = imageEventOrganizer.frame.height / 2 setUpContent() setUpView() } func setUpContent(){ judulDetailEventLabel.text = eventTitle lblNumberOfFriends.text = numberOFfriends lblLocation.text = eventLocation lblTime.text = eventTime lblDate.text = eventDate lblEventOrganizer.text = eventOrganizer lblDescription.text = eventDescription imageEventDetailed.image = imageEvent imageFriend2.image = imageFriendPhoto2 imageFriend1.image = imageFriendPhoto1 imageFriend3.image = imageFriendPhoto3 imageEventOrganizer.image = imageEOPhoto } func setUpView(){ self.navigationController?.navigationBar.isTranslucent = true } }
// // NSString+FirstLetter.swift // TypingTutor // // Created by Netiger on 14-11-21. // Copyright (c) 2014年 Sadcup. All rights reserved. // import Foundation extension String { func firstLetter() -> String { if countElements(self) < 2 { return self } return self.substringWithRange(Range<String.Index>(start: self.startIndex, end: advance(self.startIndex, 1))) } }
// // Constants.swift // AboutCanada // // Created by Rex Jason Alobba on 1/3/18. // Copyright © 2018 Rex Jason Alobba. All rights reserved. // import Foundation let CANADA_SOURCE = "https://dl.dropboxusercontent.com/s/2iodh4vg0eortkl/facts.json"
// // AddPromoCodeVC.swift // TaxiApp // // Created by Hundily Cerqueira on 11/05/20. // Copyright © 2020 Hundily Cerqueira. All rights reserved. // import UIKit class AddPromoCodeVC: UIViewController { @IBOutlet weak var textField: UITextField! override func viewDidLoad() { super.viewDidLoad() navigationItem.title = "Add promocode" textField.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged) } @objc func textFieldDidChange() { textField.text = textField.text?.uppercased() } } extension AddPromoCodeVC: UITextFieldDelegate { override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { view.endEditing(true) } }
// // Colors.swift // iosApp // // Created by Nagy Robert on 03/11/2020. // Copyright © 2020 orgName. All rights reserved. // import Foundation import UIKit class ApplicationColors{ static let accentColor = UIColor(red: 255/255, green: 66/255, blue: 66/255, alpha: 1.0) }
// // SavedLocation.swift // HotCold // // Created by user131306 on 2/9/18. // Copyright © 2018 Maryville App Development. All rights reserved. // import Foundation import MapKit class SavedLocation: NSObject, MKAnnotation { var coordinate: CLLocationCoordinate2D init (coordinate: CLLocationCoordinate2D) { self.coordinate = coordinate } }
// // BluetoothSetVC.swift // OBD // // Created by 苏沫离 on 2017/4/27. // Copyright © 2017年 苏沫离. All rights reserved. // import UIKit //蓝牙链接 class BluetoothSetVC: UIViewController { let logoImageView:UIImageView = UIImageView.init(image: UIImage.init(named: "FWD_Bluetooth1")) let mainLable = UILabel.init() let describeLable = UILabel.init() deinit{ OBDCentralMangerModel.shared().removeObserver(self, forKeyPath: "linkState") NotificationCenter.default.removeObserver(self) print("BluetoothSetVC ======= 释放") } override func viewDidLoad(){ super.viewDidLoad() // Do any additional setup after loading the view. NotificationCenter.default.addObserver(self, selector: #selector(enterForegroundNotification(notification:)), name: UIApplication.willEnterForegroundNotification, object: nil) OBDCentralMangerModel.shared().addObserver(self, forKeyPath: "linkState", options: .new, context: nil) let backImageView:UIImageView = UIImageView.init(image: UIImage.init(named: "FWD_BaseBack")) backImageView.backgroundColor = UIColor.clear self.view.addSubview(backImageView) backImageView.mas_makeConstraints { (make:MASConstraintMaker!) in make.edges.equalTo()(self.view) } let jumpView = BluetoothJumpView.init(frame: CGRect.init(x: UIScreen.ScrWidth() - 95, y: getNavigationBarHeight() - 14, width: 80, height: 33)) jumpView.jumpButton.addTarget(self, action: #selector(jumpJoinMainHomePage), for: .touchUpInside) self.view.addSubview(jumpView) let backButton = UIButton.init(type: .custom) backButton.addTarget(self, action: #selector(bluetoothSetButtonClick), for: .touchUpInside) backButton.adjustsImageWhenHighlighted = false backButton.setImage(UIImage.init(named: "FWD_BluetoothBack"), for: .normal) self.view.addSubview(backButton) backButton.mas_makeConstraints { (make:MASConstraintMaker!) in make.centerX.equalTo()(backImageView.mas_centerX) make.centerY.equalTo()(backImageView.mas_centerY) make.width.mas_equalTo()(170) make.height.equalTo()(backButton.mas_width)?.multipliedBy()(350.0/305.0) } logoImageView.contentMode = .scaleAspectFit logoImageView.backgroundColor = UIColor.clear self.view.addSubview(logoImageView) logoImageView.mas_makeConstraints { (make:MASConstraintMaker!) in make.centerX.equalTo()(self.view.mas_centerX) make.centerY.equalTo()(self.view.mas_centerY) make.width.equalTo()(backButton.mas_width)?.multipliedBy()(80/300) make.height.equalTo()(self.logoImageView.mas_width)?.multipliedBy()(1.0) } mainLable.textAlignment = .center mainLable.font = UIFont.systemFont(ofSize: 15) mainLable.textColor = UIColor.RGBA(234, 105, 86, 1) self.view.addSubview(mainLable) mainLable.mas_makeConstraints { (make:MASConstraintMaker!) in make.bottom.equalTo()(backButton.mas_top)?.with().offset()(-70) make.centerX.equalTo()(self.view) } describeLable.textAlignment = .center describeLable.font = UIFont.systemFont(ofSize: 12) describeLable.textColor = UIColor.RGBA(234, 105, 86, 1) self.view.addSubview(describeLable) describeLable.mas_makeConstraints { (make:MASConstraintMaker!) in make.top.equalTo()(self.mainLable.mas_bottom)?.with().offset()(10) make.centerX.equalTo()(self.view) } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) lookBluetoothLinkStatus() if mainLable.text == "连接中..." { logoImageView.image = UIImage.init(named: "FWD_Bluetooth3") self.rotationCircleAnimation(superView: logoImageView) } } private func lookBluetoothLinkStatus() { switch OBDCentralMangerModel.shared().linkState { case .bluetoothOff: print("蓝牙界面出现 --------- bluetoothOff") logoImageView.image = UIImage.init(named: "FWD_Bluetooth1") logoImageView.layer.removeAllAnimations() mainLable.text = "打开蓝牙连接OBD" describeLable.text = "请点击下方按钮" break case .bluetoothOn: print("蓝牙界面出现 --------- bluetoothOn") break case .startScan: print("蓝牙界面出现 --------- startScan") logoImageView.image = UIImage.init(named: "FWD_Bluetooth3") self.rotationCircleAnimation(superView: logoImageView) mainLable.text = "连接中..." describeLable.text = "" break case .scanSuccess: print("蓝牙界面出现 --------- scanSuccess") logoImageView.layer.removeAllAnimations() logoImageView.image = UIImage.init(named: "FWD_Bluetooth2") mainLable.text = "连接成功" describeLable.text = "请点击下方按钮" self.scanSuccessStateClick() break case .scanFail: print("蓝牙界面出现 --------- scanFail") //链接失败 重新扫描链接 logoImageView.layer.removeAllAnimations() logoImageView.image = UIImage.init(named: "FWD_Bluetooth4") mainLable.text = "连接错误" describeLable.text = "请点击下方按钮" break default: break } } //点击按钮事件 @objc func bluetoothSetButtonClick(){ switch OBDCentralMangerModel.shared().linkState { case .bluetoothOff: let url:NSURL = NSURL(string: "App-Prefs:root=Bluetooth")! if UIApplication.shared.canOpenURL(url as URL){ UIApplication.shared.openURL(url as URL) } break case .bluetoothOn: break case .startScan: break case .scanSuccess: self.scanSuccessStateClick() break case .scanFail: //链接失败 重新扫描链接 OBDCentralMangerModel.shared().scanPeripherals() break default: break } } //K-V-O 监听蓝牙状态 override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { let linkState = change?[NSKeyValueChangeKey.newKey] let state : OBDLinkState = OBDLinkState(rawValue: linkState as! UInt)! switch state { case .bluetoothOff: logoImageView.image = UIImage.init(named: "FWD_Bluetooth1") logoImageView.layer.removeAllAnimations() mainLable.text = "打开蓝牙连接OBD" describeLable.text = "请点击下方按钮" break case .bluetoothOn: break case .startScan: logoImageView.image = UIImage.init(named: "FWD_Bluetooth3") self.rotationCircleAnimation(superView: logoImageView) mainLable.text = "连接中..." describeLable.text = "" break case .scanSuccess: logoImageView.layer.removeAllAnimations() logoImageView.image = UIImage.init(named: "FWD_Bluetooth2") mainLable.text = "连接成功" describeLable.text = "请点击下方按钮" self.scanSuccessStateClick() break case .scanFail: logoImageView.layer.removeAllAnimations() logoImageView.image = UIImage.init(named: "FWD_Bluetooth4") mainLable.text = "连接错误" describeLable.text = "请点击下方按钮" break default: break } } //程序重新进入前台通知 @objc func enterForegroundNotification(notification:Notification) { print("程序重新进入前台通知") if mainLable.text == "连接中..." { logoImageView.image = UIImage.init(named: "FWD_Bluetooth3") self.rotationCircleAnimation(superView: logoImageView) } } func rotationCircleAnimation(superView:UIView) { let animation = CABasicAnimation.init(keyPath: "transform.rotation.z") animation.fromValue = NSNumber.init(value: 0) animation.toValue = NSNumber.init(value: M_PI * 2) animation.duration = 1 animation.autoreverses = false animation.fillMode = CAMediaTimingFillMode.forwards animation.repeatCount = MAXFLOAT superView.layer.add(animation, forKey: "rotationCircleAnimation") } @objc private func scanSuccessStateClick() { // 链接成功 //1、是否链接到盒子 //2、跳转至主界面 if LocalConfigurationData.getBoxControlIsLinked() { jumpJoinMainHomePage() } else { let boxSetVC = ControlBoxSetVC() let nav = UINavigationController.init(rootViewController: boxSetVC) nav.isNavigationBarHidden = true let window:UIWindow = ((UIApplication.shared.delegate?.window)!)! UIView.transition(from: self.view, to: boxSetVC.view, duration: 0.5, options: .transitionFlipFromLeft) { (finished) in window.rootViewController = nav } } } //跳过 @objc private func jumpJoinMainHomePage() { if AuthorizationManager.getUserBrandType() == .default { print("默认") let pageVC = PageOneViewController() let nav = UINavigationController.init(rootViewController: pageVC) nav.isNavigationBarHidden = true let window:UIWindow = ((UIApplication.shared.delegate?.window)!)! UIView.transition(from: self.view, to: pageVC.view, duration: 0.5, options: .transitionFlipFromLeft) { (finished) in window.rootViewController = nil window.rootViewController = nav } } else if AuthorizationManager.getUserBrandType() == .FWD { print("FWD") let fwdVC = FWDMainViewController() let nav = UINavigationController.init(rootViewController: fwdVC) UIView.transition(from: self.view, to: fwdVC.view, duration: 0.5, options: .transitionFlipFromLeft) { (finished) in UIApplication.shared.keyWindow?.rootViewController = nav } } else { print("其余品牌") let fwdVC = FWDMainViewController() let nav = UINavigationController.init(rootViewController: fwdVC) UIView.transition(from: self.view, to: fwdVC.view, duration: 0.5, options: .transitionFlipFromLeft) { (finished) in UIApplication.shared.keyWindow?.rootViewController = nav } } } }
// // ContentViewModel.swift // ContentViewModel // // Created by An Nguyen 2 on 9/9/21. // Copyright © 2021 orgName. All rights reserved. // import Combine import shared final class ContentViewModel: ObservableObject { @Published var email: String = "" @Published var password: String = "" @Published var isLoading: Bool = false var isValidEmail: Bool { Validators().validateEmailAddress(email: email) } var validsStatePassword: [ValidCasePasswords] { Validators().validatePassword(password: password) } var isValidInfo: Bool { isValidEmail && validsStatePassword.count == ValidCasePasswords.values().size } var currentUser: User { let user: User = User() user.email = email user.password = password return user } func saveUserInfo() { RealmDatabase.shared.addUser(user: currentUser) } func clearUser() { RealmDatabase.shared.deleteAll() } func getUser() -> User? { RealmDatabase.shared.getUser() } }
// // CZJWebViewController.swift // NewSwift // // Created by gail on 2017/12/20. // Copyright © 2017年 NewSwift. All rights reserved. // import UIKit import WebKit class CZJWebViewController: UIViewController { lazy var web : WKWebView = { var web = WKWebView(frame: CGRect(x: 0, y: NavBarHeight, width: SCREEN_WIDTH , height: SCREEN_HEIGHT-NavBarHeight)) // web.addObserver(self, forKeyPath: "title", options: .new, context: nil) web.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil) web.scrollView.bounces = false web.navigationDelegate = self return web }() lazy var progressView = { () -> UIProgressView in var progressView = UIProgressView(frame: CGRect(x: 0, y: NavBarHeight, width: SCREEN_WIDTH, height: 2)) progressView.setProgress(0.9, animated: true) progressView.progressTintColor = GlobalColor progressView.trackTintColor = UIColor.white progressView.backgroundColor = UIColor.clear return progressView }() lazy var backButton = UIButton(directionType: .left, target: self, action: #selector(backBtnClick), ImgName: "subBack.png") lazy var url = "" override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.white automaticallyAdjustsScrollViewInsets = false view.addSubview(web) view.addSubview(progressView) web.load(URLRequest(url: NSURL(string: self.url)! as URL)) navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .refresh, target: self, action: #selector(reloadBtnClick)) ///监听进度 } init(urlString:String) { super.init(nibName: nil, bundle: nil) self.url = urlString } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { // web.removeObserver(self, forKeyPath: "title") web.removeObserver(self, forKeyPath: "estimatedProgress") } } extension CZJWebViewController { /// 只要观察对象属性有新值就会调用 override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { // self.navigationItem.title = web.title progressView.progress = Float(web.estimatedProgress) progressView.isHidden = progressView.progress==1.0 } } // MARK: - BtnClick extension CZJWebViewController : WKNavigationDelegate { @objc fileprivate func reloadBtnClick () { web.reload() } @objc fileprivate func backBtnClick () { navigationController?.popViewController(animated: true) } func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { //修改字体大小 webView.evaluateJavaScript("document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '200%'", completionHandler: nil) // webView.evaluateJavaScript("document.getElementById('title').style.display='none'", completionHandler: nil)//隐藏网页title } }
import Foundation import UIKit import ThemeKit import SnapKit import RxSwift import RxCocoa import HUD import ComponentKit class CoinPageViewController: ThemeViewController { private let viewModel: CoinPageViewModel private let disposeBag = DisposeBag() private let tabsView = FilterView(buttonStyle: .tab) private let pageViewController = UIPageViewController(transitionStyle: .scroll, navigationOrientation: .horizontal) private let overviewController: CoinOverviewViewController private let marketsController: CoinMarketsViewController private let analyticsController: CoinAnalyticsViewController // private let tweetsController: CoinTweetsViewController private var favorite = false init(viewModel: CoinPageViewModel, overviewController: CoinOverviewViewController, analyticsController: CoinAnalyticsViewController, marketsController: CoinMarketsViewController) { self.viewModel = viewModel self.overviewController = overviewController self.analyticsController = analyticsController self.marketsController = marketsController // self.tweetsController = tweetsController super.init() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() view.addSubview(UIView()) // prevent Large Title from Collapsing title = viewModel.title navigationItem.leftBarButtonItem = UIBarButtonItem(title: "button.close".localized, style: .plain, target: self, action: #selector(onTapCloseButton)) navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil) view.addSubview(tabsView) tabsView.snp.makeConstraints { maker in maker.top.equalTo(view.safeAreaLayoutGuide) maker.leading.trailing.equalToSuperview() maker.height.equalTo(FilterView.height) } view.addSubview(pageViewController.view) pageViewController.view.snp.makeConstraints { maker in maker.top.equalTo(tabsView.snp.bottom) maker.leading.trailing.bottom.equalToSuperview() } tabsView.reload(filters: CoinPageModule.Tab.allCases.map { FilterView.ViewItem.item(title: $0.title) }) tabsView.onSelect = { [weak self] index in self?.onSelectTab(index: index) } overviewController.parentNavigationController = navigationController analyticsController.parentNavigationController = navigationController // tweetsController.parentNavigationController = navigationController subscribe(disposeBag, viewModel.favoriteDriver) { [weak self] in self?.favorite = $0 self?.syncButtons() } subscribe(disposeBag, viewModel.hudSignal) { HudHelper.instance.show(banner: $0) } onSelectTab(index: 0) } @objc private func onTapCloseButton() { dismiss(animated: true) } @objc private func onTapFavorite() { viewModel.onTapFavorite() } private func onSelectTab(index: Int) { guard let tab = CoinPageModule.Tab(rawValue: index) else { return } tabsView.select(index: tab.rawValue) setViewPager(tab: tab) } private func setViewPager(tab: CoinPageModule.Tab) { pageViewController.setViewControllers([viewController(tab: tab)], direction: .forward, animated: false) } private func viewController(tab: CoinPageModule.Tab) -> UIViewController { switch tab { case .overview: return overviewController case .analytics: return analyticsController case .markets: return marketsController // case .tweets: return tweetsController } } private func syncButtons() { var items = [UIBarButtonItem]() let favoriteItem = UIBarButtonItem( image: favorite ? UIImage(named: "filled_star_24") : UIImage(named: "star_24"), style: .plain, target: self, action: #selector(onTapFavorite) ) favoriteItem.tintColor = favorite ? .themeJacob : .themeGray items.append(favoriteItem) navigationItem.rightBarButtonItems = items } }
// // CategoriesCollectionViewCell.swift // moveTheViewPlease // // Created by Radharani Ribas-Valongo on 2/3/20. // Copyright © 2020 aglegaspi. All rights reserved. // import UIKit class CategoriesCollectionViewCell: UICollectionViewCell { //MARK: -- Object Properties lazy var categoryLabel: UILabel = { let label = UILabel() label.textAlignment = .center label.font = UIFont(name: "Avenir-Light", size: 15) label.textColor = .black label.numberOfLines = 0 return label }() override init(frame: CGRect) { super.init(frame: .zero) self.backgroundColor = .lightGray self.addSubview(categoryLabel) setUpConstraints() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } //MARK:-- Private constraints private func setUpConstraints() { categoryLabel.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ categoryLabel.topAnchor.constraint(equalTo: self.topAnchor, constant: 5), categoryLabel.centerXAnchor.constraint(equalTo: self.centerXAnchor), categoryLabel.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -5), categoryLabel.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 5), categoryLabel.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -5) ]) } func setUpCells(cell: CategoriesCollectionViewCell, data: CategoryData) { self.categoryLabel.text = data.name cell.layer.masksToBounds = true cell.layer.cornerRadius = 13 } }
// // HomeBannerListViewModel.swift // SwiftCaiYIQuan // // Created by 朴子hp on 2018/6/30. // Copyright © 2018年 朴子hp. All rights reserved. // import UIKit class HomeBannerListViewModel { //MARK: -- >> 广告轮播图url数组 \ 数据完成的回调 \ 失败的回调 lazy var imagesUrl:[String] = [] typealias finishCallback = () -> Void typealias failureCallback = () -> Void //MARK: -- >> 建立轮播图请求 func requestSrollViewData(_ finishCallback : @escaping finishCallback, failureCallback : @escaping failureCallback) -> Void { HttpServer.requestPostWithMethod(urlMethond: kGetBannerPhotoList, params: nil, successCallback: { (response) in if let test = HomePageModel.deserialize(from: response) { print(test.toJSON()!) } let jsonDic = NSDictionary.init(dictionary: response!) let imagesArray = jsonDic["Content"] as! NSArray for item in imagesArray { let imageInfo = item as! NSDictionary let imageUrl = IMAGE_SERVER + (imageInfo["PhotoUrl"] as! String) self.imagesUrl.append(imageUrl) } finishCallback() }) { (error) in failureCallback() } } }
func summary(list:[Int]) -> Int { return list.reduce(0){$0 + $1} } func average(list:[Int]) -> Double { let sum = Double(summary(list:list)) return sum/Double(list.count) } func dispersion(list:[Int]) -> Double{ var ave: Double = 0.0 // 平均 var dispersion: Double = 0.0 // 分散 ave = Double(average(list:list)) for i in list{ dispersion += (ave - Double(i)) * (ave - Double(i)) } dispersion /= Double(list.count) return dispersion } var list = [23, 53, 21, 67, 82] var sum_ans = summary(list: list) var ave_ans = average(list: list) var dis_ans = dispersion(list: list) print(sum_ans) print(ave_ans) print(dis_ans)
// // MoviewCell.swift // Lenna // // Created by MacBook Air on 3/18/19. // Copyright © 2019 sdtech. All rights reserved. // import UIKit protocol MovieButtonDelegate { func MovieButton(dataMovie : DataMovie) } class MoviewCell: UICollectionViewCell, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var movieImage: UIImageView! // @IBOutlet weak var title: UILabel! @IBOutlet weak var btnCell: UITableView! var arrBtn = [ActionMovie]() var movieBtn : MovieButtonDelegate? var userInterfaceStyle : UIUserInterfaceStyle? override func awakeFromNib() { super.awakeFromNib() // Initialization code btnCell.delegate = self btnCell.dataSource = self btnCell.register(UINib(nibName: "BtnMovie", bundle: nil), forCellReuseIdentifier: "BtnMovie") if self.traitCollection.userInterfaceStyle == .dark { // User Interface is Dark if #available(iOS 13.0, *) { layer.cornerRadius = 12 contentView.layer.cornerRadius = 12 contentView.layer.borderColor = UIColor.clear.cgColor contentView.layer.masksToBounds = true layer.backgroundColor = UIColor.secondarySystemBackground.cgColor } else { layer.cornerRadius = 12 contentView.layer.cornerRadius = 12 contentView.layer.borderColor = UIColor.clear.cgColor contentView.layer.masksToBounds = true layer.backgroundColor = UIColor.white.cgColor } layer.borderWidth = 0 print("dark mode") }else { layer.cornerRadius = 12 contentView.layer.cornerRadius = 12 contentView.layer.borderWidth = 0.7 contentView.layer.borderColor = UIColor.clear.cgColor contentView.layer.masksToBounds = true layer.shadowColor = UIColor.lightGray.cgColor layer.shadowOffset = CGSize(width: 0, height: 0.75) layer.shadowRadius = 3 layer.shadowOpacity = 0.7 layer.masksToBounds = false layer.shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: contentView.layer.cornerRadius).cgPath layer.backgroundColor = UIColor.white.cgColor } } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) let userInterfaceStyle1 = traitCollection.userInterfaceStyle // Either .unspecified, .light, or .dark // Update your user interface based on the appearance if #available(iOS 13.0, *) { if userInterfaceStyle1 == .dark { layer.cornerRadius = 12 print("dark mode") contentView.layer.cornerRadius = 12 contentView.layer.borderColor = UIColor.clear.cgColor contentView.layer.masksToBounds = true layer.backgroundColor = UIColor.secondarySystemBackground.cgColor } else { print("light mode") layer.cornerRadius = 12 contentView.layer.cornerRadius = 12 contentView.layer.borderWidth = 0.7 contentView.layer.borderColor = UIColor.clear.cgColor contentView.layer.masksToBounds = true layer.shadowColor = UIColor.lightGray.cgColor layer.shadowOffset = CGSize(width: 0, height: 0.75) layer.shadowRadius = 3 layer.shadowOpacity = 0.7 layer.masksToBounds = false layer.shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: contentView.layer.cornerRadius).cgPath layer.backgroundColor = UIColor.white.cgColor } } } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "BtnMovie", for: indexPath) as! BtnMovie cell.btnDetail.setTitle(arrBtn[indexPath.item].label, for: .normal) cell.btnDetail.tag = indexPath.row cell.btnDetail.addTarget(self, action: #selector(detailTapped), for: .touchUpInside) return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { movieBtn?.MovieButton(dataMovie: arrBtn[0].data) } @objc func detailTapped(sender: UIButton) { movieBtn?.MovieButton(dataMovie: arrBtn[0].data) } }
// // Copyright © 2020 Tasuku Tozawa. All rights reserved. // import UIKit public protocol UncategorizedCellDelegate: AnyObject { func didTap(_ cell: UncategorizedCell) } public class UncategorizedCell: UICollectionViewCell { public static var nib: UINib { return UINib(nibName: "UncategorizedCell", bundle: Bundle(for: Self.self)) } public weak var delegate: UncategorizedCellDelegate? @IBOutlet var button: UIButton! @IBAction func didTap(_ sender: Any) { self.delegate?.didTap(self) } override public func awakeFromNib() { super.awakeFromNib() self.setupAppearance() } // MARK: - Methods public func setupAppearance() { self.button.setTitle(L10n.uncategorizedCellTitle, for: .normal) self.button.titleLabel?.adjustsFontForContentSizeCategory = true self.button.titleLabel?.font = UIFont.preferredFont(forTextStyle: .body) } }
// // AddMovieViewController.swift // WatchList // // Created by Alex Grimes on 8/19/19. // Copyright © 2019 Alex Grimes. All rights reserved. // import UIKit protocol ModalHandler: class { func modalDismissed() } class AddMovieViewController: UIViewController { weak var delegate: ModalHandler? @IBOutlet weak var addMovieModuleView: UIView! @IBOutlet weak var cancelButton: UIButton! @IBOutlet weak var okButton: UIButton! @IBOutlet weak var listPickerView: UIPickerView! var lists = Defaults.getLists() var selectedList = "" var movieName = "movie name" @IBAction func okButtonTapped(_ sender: Any) { Defaults.addMovie(named: movieName, toList: selectedList) self.dismiss(animated: true, completion: delegate?.modalDismissed) } @IBAction func cancelButtonTapped(_ sender: Any) { self.dismiss(animated: true, completion: nil) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. addMovieModuleView.layer.cornerRadius = 10.0 addMovieModuleView.clipsToBounds = true okButton.layer.cornerRadius = 5 cancelButton.layer.cornerRadius = 5 listPickerView.delegate = self listPickerView.dataSource = self var middle: Int if lists.count % 2 == 0 { middle = lists.count / 2 - 1 } else { middle = lists.count / 2 } listPickerView.selectRow(middle, inComponent: 0, animated: false) selectedList = lists[middle] } } // MARK: - UIPickerViewDelegate, UIPickerViewDataSource extension AddMovieViewController: UIPickerViewDelegate, UIPickerViewDataSource { func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return lists.count } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return lists[row] } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { selectedList = lists[row] } }
// // STOrganizationShopViewController.swift // SpecialTraining // // Created by yintao on 2019/3/16. // Copyright © 2019 youpeixun. All rights reserved. // import UIKit class STOrganizationShopViewController: BaseViewController { @IBOutlet weak var navheightCns: NSLayoutConstraint! @IBOutlet weak var tableView: PhysicalStoreTableView! @IBOutlet weak var carouseView: CarouselView! @IBOutlet weak var navTitleOutlet: UILabel! private var agnId: String = "" var viewModel: OrganizationShopViewModel! @IBAction func actions(_ sender: UIButton) { navigationController?.popViewController(animated: true) } deinit { carouseView.dellocTimer() } override func viewWillAppear(_ animated: Bool) { navigationController?.setNavigationBarHidden(true, animated: animated) } override func setupUI() { if #available(iOS 11, *) { tableView.contentInsetAdjustmentBehavior = .never }else { automaticallyAdjustsScrollViewInsets = false } navheightCns.constant += LayoutSize.fitTopArea } override func rxBind() { viewModel = OrganizationShopViewModel(agnId: agnId) viewModel.navTitleObser.asDriver() .drive(navTitleOutlet.rx.text) .disposed(by: disposeBag) viewModel.datasource.asDriver() .drive(tableView.datasource) .disposed(by: disposeBag) viewModel.advDatasource.asDriver() .drive(onNext: { [weak self] data in self?.carouseView.setData(source: data) }) .disposed(by: disposeBag) tableView.rx.modelSelected(OrganazitonShopModel.self) .asDriver() .drive(onNext: { [weak self] model in self?.performSegue(withIdentifier: "shopCourseSegue", sender: model.shop_id) }) .disposed(by: disposeBag) viewModel.reloadSubject.onNext(Void()) } override func prepare(parameters: [String : Any]?) { agnId = parameters!["agn_id"] as! String } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "shopCourseSegue" { segue.destination.prepare(parameters: ["shop_id": sender as! String]) } } }
// // ReportTests.swift // MastodonKit // // Created by Ornithologist Coder on 4/15/17. // Copyright © 2017 MastodonKit. All rights reserved. // import XCTest @testable import MastodonKit class ReportTests: XCTestCase { func testReportFromJSON() { let fixture = try! Fixture.load(fileName: "Fixtures/Report.json") let report = try? Report.decode(data: fixture) XCTAssertEqual(report?.id, "42") XCTAssertEqual(report?.actionTaken, "account deleted") } func testReportWithInvalidData() { let parsed = try? Report.decode(data: Data()) XCTAssertNil(parsed) } func testReportsFromJSON() { let fixture = try! Fixture.load(fileName: "Fixtures/Reports.json") let parsed = try? [Report].decode(data: fixture) XCTAssertEqual(parsed?.count, 2) } func testReportsWithInvalidData() { let parsed = try? [Report].decode(data: Data()) XCTAssertNil(parsed) } }
#!/usr/bin/env DEVELOPER_DIR=/Applications/Xcode6-Beta2.app/Contents/Developer xcrun swift -sdk /Applications/Xcode6-Beta2.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk -i import Foundation import EventKit // // We create an object for our Calendar that we will use to add appointments, reminders, etc. // class Calendar { // // This is a class function that is called by the main script. We actually create our own // instance of the Calendar object, parse the command line, then add an appointment. // class func run() { // // Create a new calendar instance. // let calendar: Calendar = Calendar() // // Set default values for title and location. If the user doesn't set the title and // location on the command line, then we want to have some sort of default. // var title: String = "Untitled appointment" var location: String = "Unknown location" // // Loop all the arguments that were passed on the command line. We are not very robust // as this is a simple example. We simply look at the prefix of the string, if it is our // parameter then we fetch the rest of the string. We skip the prefix + the "=" sign and // get the rest of the string. // for argument in Process.arguments { if argument.hasPrefix("title") { title = argument.substringFromIndex(countElements("title") + 1) } if argument.hasPrefix("location") { location = argument.substringFromIndex(countElements("location") + 1) } } // // Add a new appoint to iCal. // calendar.addAppointment(title, location: location) } // // Using EventKit, we get the event store, create an event object for the default calendar // and then add a title, location, start time and end time (duration). Once done, add it // to iCal and commit the change. // func addAppointment(title: String, location: String) { let eventStore: EKEventStore = EKEventStore(accessToEntityTypes: EKEntityMaskEvent) let event: EKEvent = EKEvent(eventStore: eventStore) // // Setup our event based on the current date and time, the passed in location and title. // event.title = title event.location = location event.startDate = NSDate() event.endDate = NSDate(timeIntervalSinceNow: 600) event.calendar = eventStore.defaultCalendarForNewEvents // // Save the new event and force a commit. // eventStore.saveEvent(event, span: EKSpanThisEvent, commit: true, error: nil) } } // // Run the Calendar script.Calendar // Calendar.run()
// // SignInController.swift // PregBuddyTweets // // Created by Amit Majumdar on 07/03/18. // Copyright © 2018 Amit Majumdar. All rights reserved. // import UIKit import TwitterKit class SignInController: UIViewController { // MARK: - View LifeCycle Methods override func viewDidLoad() { super.viewDidLoad() setupLayout() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController?.setNavigationBarHidden(true, animated: true) } } extension SignInController{ // MARK: - Private Methods fileprivate func setupLayout(){ let store = TWTRTwitter.sharedInstance().sessionStore if let userID = store.session()?.userID { if userID.count != 0 { moveToHome(false) }else{ setupLoginLayout() } }else{ setupLoginLayout() } } private func setupLoginLayout(){ let logInButton = TWTRLogInButton(logInCompletion: { session, error in if (session != nil) { self.moveToHome(true) //print("signed in as \(String(describing: session?.userName))") } else { print("error: \(String(describing: error?.localizedDescription))") TWTRTwitter.sharedInstance().logIn(completion: { (loginsession, loginerror) in if (session != nil) { // print("signed in as \(String(describing: loginsession?.userName))") self.moveToHome(true) } else { //print("error: \(String(describing: loginerror?.localizedDescription))") self.showMessage((loginerror?.localizedDescription)!) } }) } }) logInButton.center = self.view.center self.view.addSubview(logInButton) } private func moveToHome(_ animated: Bool){ DispatchQueue.main.async { let appDelegate = UIApplication.shared.delegate as! AppDelegate self.navigationController?.pushViewController(appDelegate.tabBarController(), animated: animated) } } }
// // HopperConfigPool.swift // Cryptohopper-iOS-SDK // // Created by Kaan Baris Bayrak on 29/10/2020. // import Foundation public class HopperConfigPool : Codable { public private(set) var id : String? public private(set) var name : String? public private(set) var coins : String? public private(set) var config : HopperConfig? public private(set) var updated : String? public private(set) var status : String? private enum CodingKeys: String, CodingKey { case id = "id" case name = "name" case coins = "coins" case config = "config" case updated = "updated" case status = "status" } }
// // SongsViewModal.swift // MVVM // // Created by Himanshu Chimanji on 18/09/21. // import Foundation import UIKit class SongsViewModal: NSObject { static let instance = SongsViewModal() var songList = [SongsStruct]() } // MARK:- Api's extension SongsViewModal { func callAPI(vc:UIViewController, completion: @escaping (Bool) -> Void) { API_Manager.instance.get(API_URL.songUrl, type: SongsStruct.self, viewController: vc) { response, errorMessage in if response?.count ?? 0 > 0 { self.songList = response! completion(true) } else { completion(false) } } } }
// SELECT count(*) FROM users WHERE admin = 1 admins.count
// // QuizQuestion.swift // Physics Quiz // // Created by Dharamvir on 9/24/16. // Copyright © 2016 Dharamvir. All rights reserved. // import UIKit class QuizQuestion: NSObject { var question: String? var option1: String? var option2: String? var option3: String? var option4: String? var correctAnswer: String? }
// // yogaViewController.swift // FitnessTracker_FinalProject // // Created by Suryansh Soni on 7/13/20. // Copyright © 2020 Suryansh Soni. All rights reserved. // import UIKit class yogaViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UIPickerViewDelegate,UIPickerViewDataSource { var images = 1...10 let typeyoga = ["Arm balance poses", "Balancing poses","Binding poses","Chest opening poses","Core poses","Forward bending poses","Hip opening poses"] // let typeyoga = ["Arm balance poses", "Balancing poses","Binding poses","Chest opening poses","Core poses","Forward bending poses","Hip opening poses","Pranyam","Strengthening poses","twist yoga","Seated yoga", "restorative yoga","Standing yoga poses","Yoga bandha"] @IBOutlet weak var yogaPicke: UIPickerView! @IBOutlet weak var collection: UICollectionView! override func viewDidLoad() { super.viewDidLoad() let layout = UICollectionViewFlowLayout() layout.itemSize = CGSize(width: 240, height: 240) collection.collectionViewLayout = layout collection.register(yogaimageCollectionViewCell.nib(), forCellWithReuseIdentifier: yogaimageCollectionViewCell.identifier) collection.delegate = self collection.dataSource = self // Do any additional setup after loading the view. } @IBAction func showPoseButton(_ sender: Any) { } func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { typeyoga.count } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return typeyoga[row]} func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { images.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: yogaimageCollectionViewCell.identifier, for: indexPath) as! yogaimageCollectionViewCell cell.configure(with: UIImage(named: "thirdpic")!) return cell } } extension ViewController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: 240, height: 240) } }
// // Constans.swift // DevSlopFInalProject // // Created by mohamed sayed on 5/9/19. // Copyright © 2019 student. All rights reserved. // import Foundation let GoToLogin = "loginvc"
// // MasterViewController.swift // UIZaawansowane // // Created by Michal on 11/4/17. // Copyright © 2017 Michal. All rights reserved. // import UIKit class MasterViewController: UITableViewController { var detailViewController: DetailViewController? = nil var objects = [Any]() var schowek = AlbumSingleton.sharedInstance var indexToDelete: Int = 0 var czyNowyRekord: Bool = false var czyMogeKasowac: Bool = false override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let addButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(insertNewObject(_:))) navigationItem.rightBarButtonItem = addButton if let split = splitViewController { let controllers = split.viewControllers detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController } let url = URL(string: "https://isebi.net/albums.php") URLSession.shared.dataTask(with:url!, completionHandler: {(data, response, error) in guard let data = data, error == nil else { return } do { let utwory = try JSONSerialization.jsonObject(with: data, options: []) as? [[String: Any]] ?? [] self.schowek.album = utwory } catch let error as NSError { print(error) } }).resume() while (schowek.album.count == 0){ } } override func viewWillAppear(_ animated: Bool) { clearsSelectionOnViewWillAppear = splitViewController!.isCollapsed super.viewWillAppear(animated) self.tableView.reloadData() self.refreshControl?.endRefreshing() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @objc func insertNewObject(_ sender: Any) { var nowyRekord: [String:Any] = [:] nowyRekord["artist"] = " " nowyRekord["album"] = " " nowyRekord["genre"] = " " nowyRekord["year"] = " " nowyRekord["tracks"] = " " AlbumSingleton.sharedInstance.album.append(nowyRekord) czyNowyRekord = true indexToDelete = schowek.album.count-1 performSegue(withIdentifier: "showDetail", sender: self) } @objc func deleteObject(_ sender: Any?) { if(czyMogeKasowac==true && schowek.album.count != 0){ schowek.album.remove(at: indexToDelete) let indexPath = IndexPath(row: indexToDelete, section: 0) tableView.deleteRows(at: [indexPath], with: .fade) } czyMogeKasowac = false } // MARK: - Segues override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "showDetail" { czyMogeKasowac = true if (czyNowyRekord == true) { let controller = (segue.destination as! UINavigationController).topViewController as! DetailViewController controller.rowIndex = indexToDelete czyNowyRekord = false let object = schowek.album[indexToDelete] controller.detailItem = object controller.navigationItem.leftBarButtonItem = splitViewController?.displayModeButtonItem controller.navigationItem.leftItemsSupplementBackButton = true let deleteButton = UIBarButtonItem(barButtonSystemItem: .trash, target: self, action: #selector(deleteObject(_:))) controller.navigationItem.rightBarButtonItem = deleteButton } else { if let indexPath = tableView.indexPathForSelectedRow { let controller = (segue.destination as! UINavigationController).topViewController as! DetailViewController controller.rowIndex = indexPath.row indexToDelete = indexPath.row let object = schowek.album[indexToDelete] controller.detailItem = object controller.navigationItem.leftBarButtonItem = splitViewController?.displayModeButtonItem controller.navigationItem.leftItemsSupplementBackButton = true let deleteButton = UIBarButtonItem(barButtonSystemItem: .trash, target: self, action: #selector(deleteObject(_:))) controller.navigationItem.rightBarButtonItem = deleteButton } } } } // MARK: - Table View override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return schowek.album.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) let object = schowek.album[indexPath.row] cell.textLabel!.text = object["album"] as? String cell.detailTextLabel?.text = object["artist"] as! String + " " + String(describing: object["year"]!) return cell } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } }
// // YNOrderTableViewCell.swift // 2015-08-06 // // Created by 农盟 on 15/8/31. // Copyright (c) 2015年 农盟. All rights reserved. // import UIKit class YNOrderTableViewCell: UITableViewCell { //MARK: - public proterty var dataModel: Restaurant? { didSet { if let _ = self.dataModel { self.setData() } // dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in // // if let tempDataModel = self.dataModel { // // // if let tempImage = tempDataModel.image { // // let url: NSURL? = NSURL(string: tempImage) // // if let tempUrl = url { // // let imageData: NSData? = NSData(contentsOfURL: tempUrl) // // if let tempData = imageData { // // dispatch_async(dispatch_get_main_queue(), { () -> Void in // // self.businessImageView.image = UIImage(data: tempData) // }) // // } // // } else { // // print("\n 图片没有URL \n") // } // // } // // // } // // }) // // // // } } //MARK: - 初始化 override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.contentView.autoresizingMask = [UIViewAutoresizing.flexibleHeight, UIViewAutoresizing.flexibleWidth] self.accessoryType = UITableViewCellAccessoryType.disclosureIndicator self.contentView.addSubview(businessImageView) self.contentView.addSubview(businessTitleLabel) self.contentView.addSubview(levelButton1) self.contentView.addSubview(levelButton2) self.contentView.addSubview(levelButton3) self.contentView.addSubview(levelButton4) self.contentView.addSubview(levelButton5) self.contentView.addSubview(addressLabel) self.contentView.addSubview(distanceLabel) setLayout() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //MARK: - private method func setData() { setImage() self.businessTitleLabel.text = dataModel?.title self.addressLabel.text = dataModel?.address self.distanceLabel.text = "3.6km" self.setLevel(Int(dataModel!.level!)) } func setImage() { if let tempImage = dataModel!.image { let url: URL? = URL(string: tempImage) if let tempUrl = url { DispatchQueue.global(qos: DispatchQoS.QoSClass.default).async { let imageData: Data? = try? Data(contentsOf: tempUrl) if let tempData = imageData { DispatchQueue.main.async(execute: { () -> Void in self.businessImageView.image = UIImage(data: tempData) }) } } // DispatchQueue.global(priority: DispatchQueue.GlobalQueuePriority.default).async(execute: { () -> Void in // // let imageData: Data? = try? Data(contentsOf: tempUrl) // // if let tempData = imageData { // // DispatchQueue.main.async(execute: { () -> Void in // // self.businessImageView.image = UIImage(data: tempData) // }) // // } // // }) } else { print("\nYNOrderTableViewCell - 图片没有URL \n", terminator: "") } } } func setLevel(_ level: Int) { for i in 0 ..< ratingButtons.count { ratingButtons[i].isSelected = i < level } } func setLayout() { //图片 Layout().addLeftConstraint(businessImageView, toView: self.contentView, multiplier: 1, constant: 3) Layout().addTopConstraint(businessImageView, toView: self.contentView, multiplier: 1, constant: 10) Layout().addBottomConstraint(businessImageView, toView: self.contentView, multiplier: 1, constant: -10) Layout().addWidthConstraint(businessImageView, toView: nil, multiplier: 0, constant: 69) //标题 Layout().addTopConstraint(businessTitleLabel, toView: businessImageView, multiplier: 1, constant: -2) Layout().addHeightConstraint(businessTitleLabel, toView: nil, multiplier: 0, constant: 20) Layout().addLeftToRightConstraint(businessTitleLabel, toView: businessImageView, multiplier: 1, constant: 6) Layout().addRightConstraint(businessTitleLabel, toView: self.contentView, multiplier: 1, constant: 0) //第一颗星 Layout().addTopToBottomConstraint(levelButton1, toView: businessTitleLabel, multiplier: 1, constant: 0) Layout().addLeftConstraint(levelButton1, toView: businessTitleLabel, multiplier: 1, constant: 0) Layout().addWidthConstraint(levelButton1, toView: nil, multiplier: 0, constant: kImageViewWH + 4.8) Layout().addHeightConstraint(levelButton1, toView: nil, multiplier: 0, constant: kImageViewWH) //第二到第五颗星 addLevelButtonLayout(levelButton2, toView: levelButton1) addLevelButtonLayout(levelButton3, toView: levelButton2) addLevelButtonLayout(levelButton4, toView: levelButton3) addLevelButtonLayout(levelButton5, toView: levelButton4) //距离 Layout().addRightConstraint(distanceLabel, toView: self.contentView, multiplier: 1, constant: 0) Layout().addBottomConstraint(distanceLabel, toView: self.contentView, multiplier: 1, constant: 0) Layout().addTopToBottomConstraint(distanceLabel, toView: levelButton1, multiplier: 1, constant: 0) Layout().addWidthConstraint(distanceLabel, toView: nil, multiplier: 0, constant: 50) //地址 Layout().addTopConstraint(addressLabel, toView: distanceLabel, multiplier: 1, constant: 0) Layout().addBottomConstraint(addressLabel, toView: distanceLabel, multiplier: 1, constant: 0) Layout().addLeftConstraint(addressLabel, toView: levelButton1, multiplier: 1, constant: 0) Layout().addRightConstraint(addressLabel, toView: distanceLabel, multiplier: 1, constant: -55) } //设置后面4个星星button的位置 func addLevelButtonLayout(_ view: UIView, toView: UIView) { Layout().addTopConstraint(view, toView: toView, multiplier: 1, constant: 0) Layout().addBottomConstraint(view, toView: toView, multiplier: 1, constant: 0) Layout().addWidthConstraint(view, toView: toView, multiplier: 1, constant: 0) Layout().addHeightConstraint(view, toView: toView, multiplier: 1, constant: 0) Layout().addLeftToRightConstraint(view, toView: toView, multiplier: 1, constant: 0) } //初始化一个星星button func buttonWithNormalImage(_ normalImage: String, selectedImage: String)-> UIButton { let button: UIButton = UIButton() button.isUserInteractionEnabled = false button.setImage(UIImage(named: normalImage), for: UIControlState()) button.setImage(UIImage(named: selectedImage), for: UIControlState.selected) button.translatesAutoresizingMaskIntoConstraints = false self.ratingButtons += [button] return button } //MARK: - private UI fileprivate let kImageViewWH: CGFloat = 18 fileprivate lazy var businessImageView: UIImageView = { var tempImageView = UIImageView() tempImageView.contentMode = UIViewContentMode.scaleToFill tempImageView.translatesAutoresizingMaskIntoConstraints = false return tempImageView }() fileprivate lazy var businessTitleLabel: UILabel = { var tempLabel = UILabel() tempLabel.translatesAutoresizingMaskIntoConstraints = false return tempLabel }() fileprivate var rating = 0 fileprivate var ratingButtons = [UIButton]() fileprivate lazy var levelButton1: UIButton = { return self.buttonWithNormalImage("level_normal", selectedImage: "level_selected") }() fileprivate lazy var levelButton2: UIButton = { return self.buttonWithNormalImage("level_normal", selectedImage: "level_selected") }() fileprivate lazy var levelButton3: UIButton = { return self.buttonWithNormalImage("level_normal", selectedImage: "level_selected") }() fileprivate lazy var levelButton4: UIButton = { return self.buttonWithNormalImage("level_normal", selectedImage: "level_selected") }() fileprivate lazy var levelButton5: UIButton = { return self.buttonWithNormalImage("level_normal", selectedImage: "level_selected") }() fileprivate lazy var addressLabel: UILabel = { var tempLabel: UILabel = UILabel() tempLabel.font = UIFont.systemFont(ofSize: 13) tempLabel.numberOfLines = 0 tempLabel.textColor = UIColor.lightGray tempLabel.translatesAutoresizingMaskIntoConstraints = false return tempLabel }() fileprivate lazy var distanceLabel: UILabel = { var tempLabel: UILabel = UILabel() tempLabel.font = UIFont.systemFont(ofSize: 11) tempLabel.textAlignment = NSTextAlignment.left tempLabel.textColor = UIColor.lightGray tempLabel.translatesAutoresizingMaskIntoConstraints = false return tempLabel }() }
// // QuickLinkCell.swift // MVVM App Store // // Created by Jake Young on 3/4/17. // Copyright © 2017 Jake Young. All rights reserved. // import UIKit import MVVMAppStoreModel struct QuickLinkViewModel { let link: QuickLink var title: String { return link.title } } class QuickLinkCell: BaseCell { var viewModel: QuickLinkViewModel! { didSet { setupViews() } } lazy var titleLabel: UILabel = { let label = UILabel() label.text = "Title" label.textColor = .black label.font = .systemFont(ofSize: 12, weight: UIFontWeightRegular) label.numberOfLines = 2 return label }() override func setupViews() { addSubview(titleLabel) addConstraintsWithFormat("H:|[v0]|", views: titleLabel) addConstraintsWithFormat("V:|[v0]|", views: titleLabel) updateProperties() } func updateProperties() { titleLabel.text = viewModel.title } }
// // ViewController.swift // TicketApp // // Created by jacob n johar on 16/10/20. // Copyright © 2020 Jacob johar. All rights reserved. // import UIKit class ViewController: UIViewController,UIPickerViewDelegate,UIPickerViewDataSource { var ticket = Ticket() @IBOutlet weak var Quantity: UILabel! @IBOutlet weak var Price: UILabel! @IBOutlet weak var ticketType: UILabel! @IBOutlet weak var picker: UIPickerView! @IBOutlet weak var manager: UIButton! var currentNumber = 0 var result = 0 var data = [" "] var bData = " " var lData = " " var cData = " " var rowNo = [0] var information:[Ticket] = [Ticket]() override func viewDidLoad() { super.viewDidLoad() Quantity.text = " " ticketType.text = " " Price.text = "0" picker.dataSource = self picker.delegate = self manager.backgroundColor = UIColor.red fetchData() } //Function to update the values in picker func valueUpdate(bValue: Int,lValue: Int, cValue: Int, bPrice: Int,lPrice: Int, cPrice: Int, bType: String, lType: String, cType: String) { data.removeAll() if(bValue > 0){ bData = bType + String(bValue) + " Ticket: $" + String(bPrice) } else{ bData = "Balcony Full " } if(lValue > 0){ lData = lType + String(lValue) + " Ticket: $" + String(lPrice) } else{ lData = "Lower Level Full " } if(cValue > 0){ cData = cType + String(cValue) + " Ticket: $" + String(cPrice) } else{ cData = "Courtside Full " } data.append(bData) data.append(lData) data.append(cData) } //function to update the labels func labelUpdate(rowNo: Array<Int>) { if(rowNo.contains(0)){ result = currentNumber * ticket.bPrice Price.text = ("\(result)") ticketType.text = "Balcony Level" ticket.type = "Balcony Level" ticket.bType = "Balcony" ticket.price = result ticket.quantity = currentNumber } else if(rowNo.contains(1)){ result = currentNumber * ticket.lPrice Price.text = ("\(result)") ticketType.text = "Lower Level" ticket.type = "Lower Level" ticket.lType = "Lower Level" ticket.price = result ticket.quantity = currentNumber } else { result = currentNumber * ticket.cPrice Price.text = ("\(result)") ticketType.text = "Courtside" ticket.cType = "Courtside" ticket.type = "Courtside" ticket.price = result ticket.quantity = currentNumber } let now = Date() let formatter = DateFormatter() formatter.dateStyle = .full formatter.timeStyle = .full let datetime = formatter.string(from: now) ticket.date = datetime } func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return data.count } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return data[row] } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int){ let rowNo = [pickerView.selectedRow(inComponent: 0)] labelUpdate(rowNo: rowNo) } @IBAction func digit_Pressed(_ sender: Any) { currentNumber = (Int((sender as AnyObject).titleLabel?.text ?? "") ?? 0) Quantity.text = ("\(currentNumber)") } @IBAction func buy_Pressed(_ sender: Any) { let rowNo = [picker.selectedRow(inComponent: 0)] if(rowNo.contains(0)){ if(ticket.bValue > 0){ ticket.bValue -= currentNumber } else{ ticket.bValue = 0 } } else if(rowNo.contains(1)){ if(ticket.lValue > 0){ ticket.lValue -= currentNumber } else{ ticket.lValue = 0 } } else { if(ticket.cValue > 0){ ticket.cValue -= currentNumber } else{ ticket.cValue = 0 } } self.picker.reloadAllComponents() labelUpdate(rowNo: rowNo) valueUpdate(bValue: ticket.bValue, lValue:ticket.lValue,cValue: ticket.cValue,bPrice: ticket.bPrice,lPrice: ticket.lPrice,cPrice: ticket.cPrice, bType: ticket.bType, lType: ticket.lType, cType: ticket.cType) self.information.insert(ticket,at:0) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { print(information) if segue.identifier == "SecondSeque"{ let otherVc = segue.destination as! SecondViewController otherVc.tInformation = information } } //new method added for processing the values fetched from Json Github func fetchData(){ let manager = JSONManager() manager.fetchJSONData { (datavalue) in self.ticket.bValue = datavalue[0].quantity self.ticket.lValue = datavalue[1].quantity self.ticket.cValue = datavalue[2].quantity self.ticket.bPrice = datavalue[0].price self.ticket.lPrice = datavalue[1].price self.ticket.cPrice = datavalue[2].price self.ticket.bType = datavalue[0].type self.ticket.lType = datavalue[1].type self.ticket.cType = datavalue[2].type self.valueUpdate(bValue: datavalue[0].quantity, lValue: datavalue[1].quantity,cValue: datavalue[2].quantity,bPrice: datavalue[0].price,lPrice: datavalue[1].price,cPrice: datavalue[2].price, bType:datavalue[0].type, lType :datavalue[1].type, cType: datavalue[2].type ) DispatchQueue.main.async { self.picker.reloadAllComponents() } } } }
// // Color.swift // YourCityEvents // // Created by Yaroslav Zarechnyy on 10/24/19. // Copyright © 2019 Yaroslav Zarechnyy. All rights reserved. // import UIKit extension UIColor { static let appBlue = UIColor(displayP3Red: 0.145, green: 0.110, blue: 0.635, alpha: 1) }
// // MessageListCell.swift // CardSJD // // Created by X on 16/9/23. // Copyright © 2016年 QS. All rights reserved. // import UIKit class MessageListCell: UITableViewCell { @IBOutlet var mtitle: UILabel! @IBOutlet var time: UILabel! var model:MessageModel? { didSet { mtitle.text = model?.title time.text = model?.create_time } } override func awakeFromNib() { super.awakeFromNib() } override func layoutSubviews() { super.layoutSubviews() } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) if selected { self.deSelect() let vc = "MessageInfoVC".VC("Main") as! MessageInfoVC vc.model = model self.viewController?.navigationController?.pushViewController(vc, animated: true) } } }
// // TempScales.swift // umbrella // // Created by Pranav Shashikant Deshpande on 9/17/17. // Copyright © 2017 Pranav Shashikant Deshpande. All rights reserved. // import Foundation enum TempScales: Int { case f, c }
import UIKit import SpriteKit public class AppScreenView: UIView { public override init(frame: CGRect) { super.init(frame: frame) self.frame = CGRect.zero intializeUI() // createConstraints() } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } internal func intializeUI() { addSubview(mainView) } public let mainView: MagneticView = { let rand = MagneticView() // rand.backgroundColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1) return rand }() public let backView: UIView = { let rand = MagneticView() // rand.backgroundColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1) return rand }() }
// // WeatherCellController.swift // Wheather Logger // // Created by Gokhan Namal on 22.11.2019. // Copyright © 2019 Gokhan Namal. All rights reserved. // import UIKit class WheatherCell: UITableViewCell { override func awakeFromNib() { super.awakeFromNib() self.selectionStyle = .none } }
// // LoadingView.swift // GitXplore // // Created by Augusto Cesar do Nascimento dos Reis on 17/12/20. // import UIKit protocol LoadingViewble { } extension LoadingViewble where Self: UIViewController { var loadingRestorationIdentifier: String { return "LoadingIndicatorPresenterIdentifier" } func startLoading(size: CGSize? = nil, backgroundColor: UIColor? = nil) { guard let keyWindow = UIApplication.shared.windows.filter({ $0.isKeyWindow }).first else { return } let loadingView = LoadingView(frame: keyWindow.frame) loadingView.restorationIdentifier = loadingRestorationIdentifier keyWindow.addSubview(loadingView) } func stopLoading() { for window in UIApplication.shared.windows { for item in window.subviews where item.restorationIdentifier == loadingRestorationIdentifier { item.removeFromSuperview() } } } } final class LoadingView: UIView { lazy var activityView: UIActivityIndicatorView = { let activityView = UIActivityIndicatorView(style: .large) return activityView }() override func draw(_ rect: CGRect) { super.draw(rect) guard let superview = self.superview else { return } NSLayoutConstraint.activate([ self.leadingAnchor.constraint(equalTo: superview.leadingAnchor), self.trailingAnchor.constraint(equalTo: superview.trailingAnchor), self.topAnchor.constraint(equalTo: superview.topAnchor), self.bottomAnchor.constraint(equalTo: superview.bottomAnchor), ]) self.translatesAutoresizingMaskIntoConstraints = false let containerView = UIView(frame: superview.frame) containerView.translatesAutoresizingMaskIntoConstraints = false containerView.backgroundColor = UIColor(named: "Primary")?.withAlphaComponent(0.3) self.addSubview(containerView) NSLayoutConstraint.activate([ containerView.leadingAnchor.constraint(equalTo: self.leadingAnchor), containerView.trailingAnchor.constraint(equalTo: self.trailingAnchor), containerView.topAnchor.constraint(equalTo: self.topAnchor), containerView.bottomAnchor.constraint(equalTo: self.bottomAnchor), ]) containerView.addSubview(activityView) activityView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ activityView.heightAnchor.constraint(equalToConstant: 60), activityView.heightAnchor.constraint(equalToConstant: 60), activityView.centerYAnchor.constraint(equalTo: containerView.centerYAnchor), activityView.centerXAnchor.constraint(equalTo: containerView.centerXAnchor), ]) activityView.startAnimating() } }
// // PollenGETRequests.swift // Pulmonis // // Created by Sophie Seng on 31/12/2016. // Copyright © 2016 Manivannan Solan. All rights reserved. // import Foundation let APIkey : String = "DpHEIb9EeVYowvdiDobAZuyoNoSGc9mT" let baseURL : String = "http://dataservice.accuweather.com" let locationURL : String = "/locations/v1/cities/geoposition/search" let forecastURL : String = "/forecasts/v1/daily/5day/" public func generateLocationURL(latitude : Double, longitude : Double) -> NSURL { var url = baseURL + locationURL url += "?apikey=" + APIkey url += "&q=" + String(latitude) + "%2C" + String(longitude) return NSURL(string: url)! } public func generateForecastURL(key : String) -> NSURL { var url = baseURL + forecastURL + key url += "?apikey=" + APIkey url += "&details=true&metric=true" return NSURL(string: url)! }
// // KeyboardViewController.swift // KeyboardKit // // Created by Daniel Saidi on 2018-03-04. // Copyright © 2018 Daniel Saidi. All rights reserved. // import UIKit import KeyboardKit /** This demo app handles system actions as normal (e.g. change keyboard, space, new line etc.), injects strings and emojis into the text proxy and handles the rightmost images in the emoji keyboard by copying them to the pasteboard on tap and saving them to the user's photo album on long press. IMPORTANT: To use this demo keyboard, you have to enable it in system settings ("Settings/General/Keyboards") then give it full access (this requires enabling `RequestsOpenAccess` in `Info.plist`) if you want to use image buttons. You must also add a `NSPhotoLibraryAddUsageDescription` to your host app's `Info.plist` if you want to be able to save images to the photo album. This is already taken care of in this demo app, so you can just copy the setup into your own app. The keyboard is setup in `viewDidAppear(...)` since this is when `needsInputModeSwitchKey` first gets the correct value. Before this point, the value is `true` even if it should be `false`. If you find a way to solve this bug, you can setup the keyboard earlier. The autocomplete parts of this class is the first iteration of autocomplete support in KeyboardKit. The intention is to move these parts to `KeyboardInputViewController` and a new api for working with autocomplete. **IMPORTANT** `textWillChange` and `textDidChange` does not trigger when a user types and text is sent to the proxy. It however works when the text cursor changes its position, so I therefore use a (hopefully temporary) hack, by starting a timer that triggers each second and moves the cursor. Since this is a nasty hack, it may have yet to be discovered side effects. If so, please let me know. */ class KeyboardViewController: KeyboardInputViewController { // MARK: - View Controller Lifecycle override func viewDidLoad() { super.viewDidLoad() autocompleteBugFixTimer = createAutocompleteBugFixTimer() keyboardActionHandler = DemoKeyboardActionHandler(inputViewController: self) } override func viewDidAppear(_ animated: Bool) { super.viewWillAppear(animated) setupKeyboard() } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) setupKeyboard(for: size) } // MARK: - Keyboard Functionality override func textDidChange(_ textInput: UITextInput?) { super.textDidChange(textInput) requestAutocompleteSuggestions() } override func selectionWillChange(_ textInput: UITextInput?) { super.selectionWillChange(textInput) autocompleteToolbar.reset() } override func selectionDidChange(_ textInput: UITextInput?) { super.selectionDidChange(textInput) autocompleteToolbar.reset() } // MARK: - Properties let alerter = ToastAlert() var autocompleteBugFixTimer: AutocompleteBugFixTimer? var keyboardType = KeyboardType.alphabetic(uppercased: false) { didSet { setupKeyboard() } } var keyboardSwitcherAction: KeyboardAction { return needsInputModeSwitchKey ? .switchKeyboard : .switchToKeyboard(.emojis) } // MARK: - Autocomplete private lazy var autocompleteProvider = DemoAutocompleteSuggestionProvider() private lazy var autocompleteToolbar: AutocompleteToolbar = { let proxy = textDocumentProxy let toolbar = AutocompleteToolbar( buttonCreator: { DemoAutocompleteLabel(word: $0, proxy: proxy) } ) toolbar.update(with: ["foo", "bar", "baz"]) return toolbar }() private func requestAutocompleteSuggestions() { let word = textDocumentProxy.currentWord ?? "" autocompleteProvider.provideAutocompleteSuggestions(for: word) { [weak self] in switch $0 { case .failure(let error): print(error.localizedDescription) case .success(let result): self?.autocompleteToolbar.update(with: result) } } } private func resetAutocompleteSuggestions() { autocompleteToolbar.reset() } } // MARK: - Setup private extension KeyboardViewController { func setupKeyboard() { setupKeyboard(for: view.bounds.size) } func setupKeyboard(for size: CGSize) { DispatchQueue.main.async { self.setupKeyboardAsync(for: size) } } func setupKeyboardAsync(for size: CGSize) { keyboardStackView.removeAllArrangedSubviews() switch keyboardType { case .alphabetic(let uppercased): setupAlphabeticKeyboard(uppercased: uppercased) case .numeric: setupNumericKeyboard() case .symbolic: setupSymbolicKeyboard() case .emojis: setupEmojiKeyboard(for: size) default: return } } func setupAlphabeticKeyboard(uppercased: Bool = false) { let keyboard = AlphabeticKeyboard(uppercased: uppercased, in: self) let rows = buttonRows(for: keyboard.actions, distribution: .fillProportionally) keyboardStackView.addArrangedSubviews(rows) } func setupEmojiKeyboard(for size: CGSize) { let keyboard = EmojiKeyboard(in: self) let isLandscape = size.width > 400 let rowsPerPage = isLandscape ? 3 : 4 let buttonsPerRow = isLandscape ? 8 : 6 let config = KeyboardButtonRowCollectionView.Configuration(rowHeight: 50, rowsPerPage: rowsPerPage, buttonsPerRow: buttonsPerRow) let view = KeyboardButtonRowCollectionView(actions: keyboard.actions, configuration: config) { [unowned self] in return self.button(for: $0) } let bottom = buttonRow(for: keyboard.bottomActions, distribution: .fillProportionally) keyboardStackView.addArrangedSubview(view) keyboardStackView.addArrangedSubview(bottom) } func setupNumericKeyboard() { let keyboard = NumericKeyboard(in: self) let rows = buttonRows(for: keyboard.actions, distribution: .fillProportionally) keyboardStackView.addArrangedSubviews(rows) } func setupSymbolicKeyboard() { let keyboard = SymbolicKeyboard(in: self) let rows = buttonRows(for: keyboard.actions, distribution: .fillProportionally) keyboardStackView.addArrangedSubviews(rows) } } // MARK: - Private Button Functions private extension KeyboardViewController { func button(for action: KeyboardAction, distribution: UIStackView.Distribution = .equalSpacing) -> UIView { if action == .none { return KeyboardSpacerView(width: 10) } let view = DemoButton.fromNib(owner: self) view.setup(with: action, in: self, distribution: distribution) return view } func buttonRow(for actions: KeyboardActionRow, distribution: UIStackView.Distribution) -> KeyboardStackViewComponent { return KeyboardButtonRow(actions: actions, distribution: distribution) { button(for: $0, distribution: distribution) } } func buttonRows(for actionRows: KeyboardActionRows, distribution: UIStackView.Distribution) -> [KeyboardStackViewComponent] { var rows = actionRows.map { buttonRow(for: $0, distribution: distribution) } rows.insert(autocompleteToolbar, at: 0) return rows } }
// // GamersViewController.swift // eSponsorship // // Created by Jeremy Tay on 27/09/2017. // Copyright © 2017 Jeremy Tay. All rights reserved. // import UIKit import Foundation import Firebase import FirebaseAuth import FirebaseStorage import FirebaseDatabase class GamersViewController: UIViewController { var refreshControl : UIRefreshControl? var gamersProfiles: [Gamers] = [] var delegate : TitleDelegate? var databaseRef: DatabaseReference! var storageRef: StorageReference! @IBOutlet weak var gamersTableView: UITableView!{ didSet{ gamersTableView.register(GamersTableViewCell.cellNib, forCellReuseIdentifier: GamersTableViewCell.cellIdentifier) gamersTableView.delegate = self gamersTableView.dataSource = self gamersTableView.estimatedRowHeight = 130 gamersTableView.rowHeight = 130 } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) delegate?.changeTitle(to: "Gamers") } override func viewDidLoad() { super.viewDidLoad() fetchpost() } func fetchpost () { databaseRef = Database.database().reference() databaseRef.child("users").observe(.childAdded, with: { (snapshot) in guard let myGamers = snapshot.value as? [String: Any] else {return} if let userName = myGamers["user_name"] as? String, let userEmail = myGamers["email"] as? String, let userProfileImageURL = myGamers["user_image_url"] as? String, let userLocationBased = myGamers["user_location_based"] as? String, let userDescription = myGamers["user_bio_desc"] as? String, let userTwitchURL = myGamers["user_twitch_url"] as? String, let userYoutubeURL = myGamers["user_youtube_url"] as? String, let userFacebookURL = myGamers["user_facebook_url"] as? String, let userOtherURL = myGamers["user_others_url"] as? String, let userGameChoice1 = myGamers["user_GameChoice_1"] as? String, let userGameChoice1Level = myGamers["user_GameChoice_1_level"] as? String, let userGameChoice2 = myGamers["user_GameChoice_2"] as? String, let userGameChoice2Level = myGamers["user_GameChoice_2_level"] as? String, let userGameChoice3 = myGamers["user_GameChoice_3"] as? String, let userGameChoice3Level = myGamers["user_GameChoice_3_level"] as? String { DispatchQueue.main.async { let gamersPost = Gamers(userNameInput: userName, userEmailInput: userEmail, userProfileImageURLInput: userProfileImageURL, userLocationBasedInput: userLocationBased, userDescriptionInput: userDescription, userTwitchURLInput: userTwitchURL, userYoutubeURLInput: userYoutubeURL, userFacebookURLInput: userFacebookURL, userOtherURLInput: userOtherURL, userGameChoice1Input: userGameChoice1, userGameChoice1LevelInput: userGameChoice1Level, userGameChoice2Input: userGameChoice2, userGameChoice2LevelInput: userGameChoice2Level, userGameChoice3Input: userGameChoice3, userGameChoice3LevelInput: userGameChoice3Level) self.gamersProfiles.append(gamersPost) self.gamersTableView.reloadData() } } }, withCancel: nil) } } extension GamersViewController : UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard let destination = storyboard?.instantiateViewController(withIdentifier: "DetailedGamersViewController") as? DetailedGamersViewController else {return} let selectedGamer = gamersProfiles[indexPath.row] destination.selectedGamerProfile = selectedGamer navigationController?.pushViewController(destination, animated: true) } } extension GamersViewController : UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return gamersProfiles.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = gamersTableView.dequeueReusableCell(withIdentifier: GamersTableViewCell.cellIdentifier, for: indexPath) as? GamersTableViewCell else { return UITableViewCell() } let gamerSelected = gamersProfiles[indexPath.row] cell.mainLabel.text = gamerSelected.userName cell.subMainLabel.text = gamerSelected.userGameChoice1 cell.locationLabel.text = gamerSelected.userLocationBased if let profile_image_url = gamerSelected.userProfileImageURL { cell.profileImage.loadImage(from: profile_image_url) } return cell } }
// // LoggedOutViewController.swift // Fixee // // Created by Haydn Joel Gately on 21/10/2016. // Copyright © 2016 Fixee. All rights reserved. // import UIKit import Foundation class LoggedOutViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var loginBtnImg: UIImageView! @IBOutlet weak var tableView: UITableView! @IBAction func loginBtn(_ sender: AnyObject) { performSegue(withIdentifier: "LoginSegue", sender: self) } override var prefersStatusBarHidden: Bool { return true } @IBAction func searchBtn(_ sender: AnyObject) { performSegue(withIdentifier: "ShowSearch", sender: self) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 5 } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { //sortBoundaries() // var cell:UITableViewCell? = // tableView.dequeueReusableCellWithIdentifier("Cell") as? UITableViewCell! //let cell = self.tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! CustomCell let cell = self.tableView.dequeueReusableCell(withIdentifier: "Cell", for : indexPath) as! CustomCell return cell } override func viewDidLoad() { super.viewDidLoad() tableView.delegate = self tableView.dataSource = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
// // CharactersDatasource.swift // MarvelsApp // // Created by aliunco on 3/12/19. // Copyright © 2019 Zibazi. All rights reserved. // import Foundation import UIKit protocol CharactersDatasourceDelegate: class, LoadingPresenter { func listHasBeenUpdated(newItems: [Character]) func startLoading() } final class CharactersDatasource: NSObject { var items: [Character] = [] var isInProgress = false weak var delegate: CharactersDatasourceDelegate? private let itemsPerPage = 20 var query: String? { didSet { resetAndClear() getMoreItems() } } func resetAndClear() { DispatchQueue.main.async { self.items.removeAll() self.delegate?.listHasBeenUpdated(newItems: []) } } func getMoreItems() { if isInProgress { return } isInProgress = true DispatchQueue.main.async { self.delegate?.startLoading() } CharacterDataManager.getCharacters(target: delegate, name: query, limit: itemsPerPage, offset: self.items.count) .observe { result in self.isInProgress = false switch result{ case .value(let characters): DispatchQueue.main.async { let newItems = characters.data?.results ?? [] self.items.append(contentsOf: newItems) self.delegate?.listHasBeenUpdated(newItems: newItems) } case .error(let error): print(error) DispatchQueue.main.async { self.delegate?.listHasBeenUpdated(newItems: []) } } } } }
// // Hello.swift // CoreProject // // Created by hongsunmin on 2020/03/11. // Copyright © 2020 Sunmin, Hong. All rights reserved. // import Foundation public class Hello { public init() { } public func printHello() { print("Hello") } }
// // NNFW_UIViewController.swift // // Created by Saharat Sittipanya on 22/5/2563 BE. // import UIKit import SafariServices extension UIViewController { public func postAlert(_ title: String, message: String) { let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertController.Style.alert) alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil)) DispatchQueue.main.async { self.present(alert, animated: true, completion: nil) } } public func postConfirmAlert(_ title: String, _ message: String, _ button0: String, _ button1: String, action0: (() -> Void)? = nil, action1: (() -> Void)? = nil, _ isDestructive: Bool) { let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertController.Style.alert) if isDestructive { alert.addAction(UIAlertAction(title: button0, style: .cancel, handler: { (action: UIAlertAction!) in if action0 != nil { action0!() } })) alert.addAction(UIAlertAction(title: button1, style: .destructive, handler: { (action: UIAlertAction!) in if action1 != nil { action1!() } })) } else { alert.addAction(UIAlertAction(title: button1, style: .default, handler: { (action: UIAlertAction!) in if action1 != nil { action1!() } })) alert.addAction(UIAlertAction(title: button0, style: .cancel, handler: { (action: UIAlertAction!) in if action0 != nil { action0!() } })) } DispatchQueue.main.async { self.present(alert, animated: true, completion: nil) } } public func postAlertAction(_ title: String, _ message: String, _ buttonTitel: String, doAction: (() -> Void)? = nil, _ btnStyle: UIAlertAction.Style) { let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertController.Style.alert) alert.addAction(UIAlertAction(title: buttonTitel, style: btnStyle, handler: { (action: UIAlertAction!) in if doAction != nil { doAction!() } })) DispatchQueue.main.async { self.present(alert, animated: true, completion: nil) } } public func postActionSheet ( withTitle title: String?, Message message: String?, _ buttonTitles: [String], _ buttonStyles: [UIAlertAction.Style], _ buttonActions: [((UIAlertAction) -> Void)?] ) { let alertViewController = UIAlertController(title: title, message: message, preferredStyle: .actionSheet) for i in 0..<buttonTitles.count { let alertAction = UIAlertAction(title: buttonTitles[i], style: buttonStyles[i], handler: buttonActions[i]) alertViewController.addAction(alertAction) } self.present(alertViewController, animated: true, completion: nil) } public func showToast(message : String) { var font = UIFont(name: "Prompt-Regular", size: 12.0) if font == nil { font = UIFont(name: "HelveticaNeue-Regular", size: 12.0) } if font == nil { font = UIFont(name: "Helvetica Neue-Regular", size: 12.0) } if font == nil { font = UIFont(name: "Helvetica-Regular", size: 12.0) } if font == nil { font = UIFont(name: "System-Regular", size: 12.0) } guard let fontUse = font else { return } let width = self.view.frame.size.width - 60.0 let height = ceil(message.boundingRect(with: CGSize(width: width, height: .greatestFiniteMagnitude), options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: fontUse], context: nil).height) let toastLabel = UILabel(frame: CGRect(x: (self.view.frame.size.width/2.0) - (width/2), y: self.view.frame.size.height-70.0-height, width: width, height: height)) toastLabel.backgroundColor = UIColor.black.withAlphaComponent(0.6) toastLabel.textColor = .white toastLabel.textAlignment = .center; toastLabel.font = UIFont(name: "HelveticaNeue-Regular", size: 12.0) toastLabel.text = message toastLabel.numberOfLines = 0 toastLabel.alpha = 1.0 toastLabel.layer.cornerRadius = 10; toastLabel.clipsToBounds = true self.view.addSubview(toastLabel) UIView.animate(withDuration: 4.0, delay: 0.1, options: .curveEaseOut, animations: { toastLabel.alpha = 0.0 }, completion: {(isCompleted) in toastLabel.removeFromSuperview() }) } public func share(_ content: [Any]) { let activityViewController = UIActivityViewController(activityItems: content, applicationActivities: nil) activityViewController.popoverPresentationController?.sourceView = self.view self.present(activityViewController, animated: true, completion: nil) } public func openSafariWebview(withURL url: String) { if let URL_STR = URL(string: url) { let VC = SFSafariViewController(url: URL_STR) VC.modalPresentationStyle = .fullScreen self.present(VC, animated: true, completion: nil) } } }
import UIKit // Al capitán le gusta mucho escribir en una botella todo lo que hace para finalmente lanzarlo al mar. así en un futuro podrá ser recordado. A menudo, los piratas tienen batallas con otros barcos y en ocasiones algunos de ellos mueren en el combate. Esto quiere decir que cada vez que hay un combate tiene que reclutar tantos piratas como personas hayan muerto. // Como se ha dicho, al capitán le gusta poner todo lo que hace en un mensaje paa lanzarlo al mar, pero también es un poco vago. Como sabe de informática, hace un programa en el que guarda en un array los nombres de los nuevos piratas y de los piratas fallecidos para escribir los nuevos mensajes: // - Los (p: número de piratas fallecidos) piratas que han fallecido en combate son: (nombre pirata 1), ..., (nombre pirata p) // - Los (np: número de nuevos piratas) nuevos miembros de esta tripulación son: (nombre pirata 1), ..., (nombre pirata np) var deadPirates: [String] = ["Pepe", "Juan", "Jose"] var newPirates: [String] = ["Rudolf", "Benito", "Carlos"] print("Los \(deadPirates.count) piratas que han fallecido en combate son:") for (_, pirate) in deadPirates.enumerated() { print("- \(pirate)") } print("") print("Los \(newPirates.count) nuevos miembros de esta tripulación son:") for (_, pirate) in newPirates.enumerated() { print(" - \(pirate)") } print("") // Catch the current date let fecha = Date() let format = DateFormatter() // Tuesday, July 23, 2019 format.dateStyle = .full print(format.string(from: fecha))
// // GraphBackgroundSegment.swift // HeartRateGraphDemo // // Created by Joshua on 11/4/20. // import SwiftUI struct GraphBackgroundSegment: View { var graphData: HeartRateGraphData var size: CGSize var segmentData: [RectangleSegment] var totalSegmentWidth: Double { return segmentData.reduce(0, { $0 + $1.width }) } var maxSegmentHeight: Double { return segmentData.map { $0.height }.max()! } init(graphData: HeartRateGraphData, size: CGSize) { self.graphData = graphData self.size = size segmentData = GraphBackgroundSegment.makeSegmentData(from: graphData) } var body: some View { HStack(alignment: .center, spacing: 0) { ForEach(0..<segmentData.count) { i in Rectangle() .frame( width: scaleWidth(segmentData[i].width), height: scaleHeight(segmentData[i].height)) .foregroundColor(segmentData[i].color) } } } /// Scale a value to the width of the entire frame. /// - Parameter width: Width to be scaled. /// - Returns: Scaled width. func scaleWidth(_ width: Double) -> CGFloat { CGFloat(width.rangeMap(inMin: 0, inMax: totalSegmentWidth, outMin: 0, outMax: Double(size.width))) } /// Scale a value to the height of the entire frame. /// - Parameter height: Height to be scaled. /// - Returns: Scaled height. func scaleHeight(_ height: Double) -> CGFloat { CGFloat(height.rangeMap(inMin: 0, inMax: maxSegmentHeight, outMin: 0, outMax: Double(size.height))) } struct RectangleSegment { let width: Double let height: Double let color: Color } /// Create the data for building the segments. /// - Parameter graphData: The graph data. /// - Returns: The segment data. static func makeSegmentData(from graphData: HeartRateGraphData) -> [RectangleSegment] { var data = [RectangleSegment]() let groupIndices = Array(Set(graphData.data.map { $0.groupIndex })).sorted() let colors: [Color] = colorArray(numberOfColors: groupIndices.count) for idx in groupIndices { let xValues = graphData.data.filter { $0.groupIndex == idx }.map { $0.x } let minX = xValues.min()! let maxX = xValues.max()! let minY = graphData.minY let maxY = graphData.maxY data.append(RectangleSegment(width: maxX - minX, height: maxY - minY, color: colors[idx])) } return data } /// Create an array of colors across the complete rainbow. /// - Parameter n: The number of colors to create. /// - Returns: An array of SwiftUI `Color` views. static func colorArray(numberOfColors n: Int) -> [Color] { var colors = [Color]() let jump = 3.0 / Double(n) var val: Double = 0 for _ in 0..<n { if val <= 1 { colors.append(Color(red: 1 - val, green: val, blue: 0)) } else if val <= 2 { colors.append(Color(red: 0, green: 1 - (val - 1), blue: (val - 1))) } else { colors.append(Color(red: val - 2, green: 0, blue: 1 - (val - 2))) } val += jump } return colors } }
//===--- NSStringConversion.swift -----------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // <rdar://problem/19003201> import TestsUtils import Foundation public func run_NSStringConversion(_ N: Int) { let test:NSString = NSString(cString: "test", encoding: String.Encoding.ascii.rawValue)! for _ in 1...N * 10000 { _ = test as String } }
/** * Copyright IBM Corporation 2018 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import Foundation /** The pagination data for the returned objects. */ public struct LogPagination { /// The URL that will return the next page of results, if any. public var nextUrl: String? /// Reserved for future use. public var matched: Int? /** Initialize a `LogPagination` with member variables. - parameter nextUrl: The URL that will return the next page of results, if any. - parameter matched: Reserved for future use. - returns: An initialized `LogPagination`. */ public init(nextUrl: String? = nil, matched: Int? = nil) { self.nextUrl = nextUrl self.matched = matched } } extension LogPagination: Codable { private enum CodingKeys: String, CodingKey { case nextUrl = "next_url" case matched = "matched" static let allValues = [nextUrl, matched] } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) nextUrl = try container.decodeIfPresent(String.self, forKey: .nextUrl) matched = try container.decodeIfPresent(Int.self, forKey: .matched) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(nextUrl, forKey: .nextUrl) try container.encodeIfPresent(matched, forKey: .matched) } }
// // MainVC.swift // NakedKanban // // Created by Hunter Buxton on 4/22/19. // Copyright © 2019 GreyHydeTech. All rights reserved. // import UIKit import GHTUIKit enum HamburgerMenuItems: String { case Kanban = "Kanban Board" case Epics = "Epics" case Backlog = "Backlog" case Archive = "Archive" case More = "More" } class MainMenuController: HamburgerNavigatorVC, ChildPresentationDelegate { override open func viewWillAppear(_ animated: Bool) { let button1 = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addTask(_:))) rightBarBtns = [button1] } override func viewDidLoad() { super.viewDidLoad() } override func setMenuAndViewControllers() { let vc1 = KanbanBoardTableVC(delegate: self) let vc2 = EpicsTableVC(delegate: self) let vc3 = BacklogTC(delegate: self) let vc4 = ArchivedTVC(delegate: self) let vc5 = MoreVC(delegate: self) hamburgerMenuVCs = [vc1,vc2,vc3,vc4,vc5] menuButtonTitles = [HamburgerMenuItems.Kanban.rawValue, HamburgerMenuItems.Epics.rawValue, HamburgerMenuItems.Backlog.rawValue, HamburgerMenuItems.Archive.rawValue, HamburgerMenuItems.More.rawValue] } @objc func addTask(_ sender: UIBarButtonItem!) { super.slideMenuIn() let vc = TaskEditor() present(vc, animated: true, completion: nil) } @objc func addEpic(_ sender: UIBarButtonItem!) { super.slideMenuIn() let vc = EpicEditor() present(vc, animated: true, completion: nil) } override func didChangeSelection(_ vc: UIViewController) { if vc == hamburgerMenuVCs[1] { // print("overriden didChangeSelection says the epic board was selected") let button1 = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addEpic(_:))) rightBarBtns = [button1] } else if vc == hamburgerMenuVCs[4] { rightBarBtns = nil // print("overriden didChangeSelection says the more board was selected") } else { let button1 = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addTask(_:))) rightBarBtns = [button1] } } } // override func transitionToNewDisplay(_ vcToPresent: UIViewController) { // super.transitionToNewDisplay(vcToPresent) // }
enum Status: String, Decodable { case Alive case Dead case unknown } enum Gender: String, Decodable { case Female case Male case Genderless case unknown } class Character: Decodable, Identifiable { let id: Int let name: String var status: Status let species: String let type: String let gender: Gender let image: String }
// // HistoryTypes+ViewModels.swift // WavesWallet-iOS // // Created by Mac on 06/08/2018. // Copyright © 2018 Waves Platform. All rights reserved. // import Foundation import DomainLayer extension HistoryTypes.ViewModel { struct Section { var items: [Row] var date: Date? init(items: [Row], date: Date? = nil) { self.items = items self.date = date } } enum Row { case transaction(DomainLayer.DTO.SmartTransaction) case transactionSkeleton } } extension HistoryTypes.ViewModel.Section { static func map(from transactions: [DomainLayer.DTO.SmartTransaction]) -> [HistoryTypes.ViewModel.Section] { return sections(from: transactions) } static private func sections(from transactions: [DomainLayer.DTO.SmartTransaction]) -> [HistoryTypes.ViewModel.Section] { let calendar = NSCalendar.current let sections = transactions.reduce(into: [Date: [DomainLayer.DTO.SmartTransaction]]()) { result, tx in let components = calendar.dateComponents([.day, .month, .year], from: tx.timestamp) let date = calendar.date(from: components) ?? Date() var list = result[date] ?? [] list.append(tx) result[date] = list } let sortedKeys = Array(sections.keys).sorted(by: { $0 > $1 }) return sortedKeys.map { key -> HistoryTypes.ViewModel.Section? in guard let section = sections[key] else { return nil } let rows = section.map { HistoryTypes.ViewModel.Row.transaction($0) } return HistoryTypes.ViewModel.Section.init(items: rows, date: key) } .compactMap { $0 } } }
// // CartTableViewCell.swift // OrgTech // // Created by Maksym Balukhtin on 29.04.2020. // Copyright © 2020 Maksym Balukhtin. All rights reserved. // import UIKit final class CartTableViewCell: BuildableTableViewCell<CartTableViewCellView, ShortProductModel> { override func config(with object: ShortProductModel) { mainView.imageView.downloaded(fromURL: object.image) mainView.nameLabel.text = object.name mainView.colorPicker.fill(with: [object.color ?? ""]) mainView.colorPicker.preSelected = false mainView.qtyPriceLabel.text = [object.quantity ?? "", "x ₴", "\(object.price?.value ?? -1)"].joined(separator: " ") mainView.finalPriceLabel.text = ["₴", "\((object.price?.value ?? -1) * (object.quantity?.intValue ?? 0))"].joined(separator: " ") selectionStyle = .none } }
// // HMainViewController.swift // Stellar Hedron // // Created by David S Reich on 26/09/2015. // Copyright © 2015 Stellar Software Pty Ltd. All rights reserved. // import UIKit class HMainViewController: UIViewController, UITabBarDelegate, UIAlertViewDelegate { @IBOutlet weak var outerView: UIView! @IBOutlet weak var outerOuterView: UIView! @IBOutlet weak var boardContainerView: UIView! @IBOutlet weak var tabBar: UITabBar! @IBOutlet weak var newButton: UITabBarItem! @IBOutlet weak var rematchButton: UITabBarItem! @IBOutlet weak var infoButton: UITabBarItem! @IBOutlet weak var confirmMoveButton: UITabBarItem! @IBOutlet weak var playerPrompt: UILabel! @IBOutlet weak var player1Score: UILabel! @IBOutlet weak var player2Score: UILabel! @IBOutlet weak var p1ScoreContainer: UIView! var boardView: HBoardView! var gameCenterManager: HGameCenterManager! = nil let kNewGameCommand = 0 let kRematchCommand = 1 var firstTime = true 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. } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) if firstTime { firstTime = false tabBar.delegate = self gameCenterManager = HGameCenterManager(theViewController: self) createBoard() boardView.setupPlayers(HBoardView.LocationType.Local, otherPlayerName: nil) boardView.setupBoard(self) tabBar.tintColor = UIColor.grayColor() } } func createBoard() { self.view.clipsToBounds = false // print("view.bounds: \(view.bounds)") // print("view.frame: \(view.frame)") // print("bvbounds: \(boardContainerView.bounds)") // print("bvframe: \(boardContainerView.frame)") if boardView == nil { boardView = HBoardView(frame: boardContainerView.bounds) boardContainerView.addSubview(boardView) boardView.createBoard(boardContainerView.center) } let fontSize = floor(27 * boardView.bounds.width / 320) playerPrompt.font = UIFont(name: "Trebuchet-BoldItalic", size: fontSize) //adjust font sizes for different screens? player1Score.font = UIFont(name: "Verdana-Bold", size: fontSize) //adjust font sizes for different screens? player2Score.font = UIFont(name: "Verdana-Bold", size: fontSize) //adjust font sizes for different screens? let tHeight = floor(48 * boardView.bounds.width / 320) var frameRect = playerPrompt.frame playerPrompt.translatesAutoresizingMaskIntoConstraints = true playerPrompt.frame = CGRectMake(frameRect.origin.x, frameRect.origin.y, frameRect.width, tHeight) let tWidth = floor(64 * boardView.bounds.width / 320) frameRect = p1ScoreContainer.frame p1ScoreContainer.frame = CGRectMake(frameRect.origin.x, frameRect.origin.y, tWidth, frameRect.height) p1ScoreContainer.bounds = CGRectMake(0, 0, tWidth, frameRect.height) //this is probably redundant playerPrompt.backgroundColor = UIColor(red: 40.0 / 256.0, green: 40.0 / 256.0, blue: 40.0 / 256.0, alpha: 1.0) player1Score.backgroundColor = UIColor(red: 40.0 / 256.0, green: 40.0 / 256.0, blue: 40.0 / 256.0, alpha: 1.0) player2Score.backgroundColor = UIColor(red: 40.0 / 256.0, green: 40.0 / 256.0, blue: 40.0 / 256.0, alpha: 1.0) } func setPromptText(prompt: String) { playerPrompt.text = prompt } // MARK: game control mechanics func newGame() { var actionSheet: UIAlertController if UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Pad { actionSheet = UIAlertController(title: "New Game", message: "Do you want to play?", preferredStyle: UIAlertControllerStyle.Alert) } else { actionSheet = UIAlertController(title: "New Game", message: "Do you want to play?", preferredStyle: UIAlertControllerStyle.ActionSheet) } actionSheet.addAction(UIAlertAction(title: "Two Player", style: UIAlertActionStyle.Default, handler: { (action :UIAlertAction!)in self.boardView.startLocalGame() })) actionSheet.addAction(UIAlertAction(title: "You vs. AI", style: UIAlertActionStyle.Default, handler: { (action :UIAlertAction!)in self.newAIGame() })) actionSheet.addAction(UIAlertAction(title: "Two Player OnLine", style: UIAlertActionStyle.Default, handler: { (action :UIAlertAction!)in self.gameCenterManager.matchMakerMatchMaker() })) actionSheet.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil)) self.presentViewController(actionSheet, animated: true, completion: nil) } func newAIGame() { var actionSheet: UIAlertController if UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Pad { actionSheet = UIAlertController(title: "Select an AI", message: "Which AI do you want to play against?", preferredStyle: UIAlertControllerStyle.Alert) } else { actionSheet = UIAlertController(title: "Select an AI", message: "Which AI do you want to play against?", preferredStyle: UIAlertControllerStyle.ActionSheet) } actionSheet.addAction(UIAlertAction(title: "Very Easy", style: UIAlertActionStyle.Default, handler: { (action :UIAlertAction!)in self.startAIGame(0) })) actionSheet.addAction(UIAlertAction(title: "Easy", style: UIAlertActionStyle.Default, handler: { (action :UIAlertAction!)in self.startAIGame(1) })) actionSheet.addAction(UIAlertAction(title: "Normal", style: UIAlertActionStyle.Default, handler: { (action :UIAlertAction!)in self.startAIGame(2) })) actionSheet.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil)) self.presentViewController(actionSheet, animated: true, completion: nil) } func startAIGame(strength: Int) { boardView.aiStrength = strength boardView.startAIGame() } func rematchGame() { if boardView.gameType == HBoardView.LocationType.Remote { //ask other player gameCenterManager.sendRematchRequestMessage() //if the other player wants to rematch then they will start on their system and send a startRematch message. return } boardView.rematch() } // MARK: UIAlertViewDelegate func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) { if alertView.tag == kNewGameCommand { if buttonIndex == 1 { //canceled return } newGame() } else if alertView.tag == kRematchCommand { if buttonIndex == 1 { //canceled return } rematchGame() } } // MARK: UITabBarDelegate func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) { if boardView.insideGame && !boardView.gameOver { if item == newButton || item == rematchButton { //ask about abandoning game //then in completion handler either call newGame, rematchGame, or do nothing let alertController = UIAlertController(title: "Stop the current game?", message: "This will stop the current game. Are you sure you want to start a new game?", preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: "New Game", style: UIAlertActionStyle.Default, handler: { (action :UIAlertAction!)in if item == self.newButton { self.newGame() } else if item == self.rematchButton { self.rematchGame() } })) alertController.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil)) self.presentViewController(alertController, animated: true, completion: nil) return } } if item == newButton { newGame() } else if item == rematchButton { rematchGame() } else if item == confirmMoveButton { boardView.playerCommitted() } else if item == infoButton { performSegueWithIdentifier("InfoViewSegue", sender: self) } } func enableConfirmMoveButton(enabled: Bool) { confirmMoveButton.enabled = enabled } }
// // ViewController.swift // Movies // // Created by Ilshat Khairakhun on 31.05.2021. // import UIKit protocol MoviesCollectionViewDelegate { func cellDidtapped() } class MainController: UIViewController { //MARK: Properties private var moviesCollectionView: MoviesCollectionView! private let layout = UICollectionViewFlowLayout() //MARK: Methods override func loadView() { moviesCollectionView = MoviesCollectionView(frame: .zero, collectionViewLayout: layout) self.view = moviesCollectionView moviesCollectionView.moviesCVDelegate = self } override func viewDidLoad() { super.viewDidLoad() } override var prefersStatusBarHidden: Bool { return true } } //MARK: MoviesCollectionViewDelegate extension MainController: MoviesCollectionViewDelegate { func cellDidtapped() { let detailsVC = DetailsViewController() detailsVC.movie = moviesCollectionView.movieForDetail present(detailsVC, animated: true) } }
// // VerifyOTPViewController.swift // Pay-hub // // Created by RSTI E-Services on 19/05/17. // Copyright © 2017 RSTI E-Services. All rights reserved. // import UIKit import Alamofire class VerifyOTPViewController: UIViewController { public var mobilenumberfromsignup : String = "" public var type : String = "" public var guestType : String = "" public var OTPtype : String = "" @IBOutlet weak var otpTextField: UITextField! @IBOutlet weak var descriptionLabel: UILabel! @IBAction func verifyOTPButton(_ sender: UIButton) { if (otpTextField.text?.isEmpty)! { let alert = UIAlertController(title: "OTP is Mandetory", message: "Please check inbox in your phone's message to get OTP", preferredStyle: UIAlertControllerStyle.alert) // add an action (button) alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)) // show the alert self.present(alert, animated: true, completion: nil) } else { self.perform(#selector(VerifyOTPwithServer), with: nil) } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(false) descriptionLabel.text = "we sent you an SMS with your verification code to mobile number " + (mobilenumberfromsignup) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func VerifyOTPwithServer() { let currentDate : String = getCurrentDate() let MerchantID = "3" let MerchantUsername = "admin" // let VisitReference : String = UserDefaults.standard.value(forKey: "VisitReferenceNumber") as! String let otptext = self.otpTextField.text let mobilenumber = self.mobilenumberfromsignup let VisitReference : String = UserDefaults.standard.value(forKey: "VisitReferenceNumber") as! String let parameters2 = ["merchant_username": MerchantUsername, "merchant_id": MerchantID , "date" : currentDate, "otp" : otptext, "otp_for": mobilenumber, "guest":guestType,"visit_ref" : VisitReference, "type": type] as! [String:String] let HEADERS: HTTPHeaders = [ "Token": "d75542712c868c1690110db641ba01a", "Accept": "application/json", "user_name" : "admin", "user_id" : "3" ] Alamofire.request( URL(string: "https://pay-hub.in/payhub%20api/v1/opt_verify.php")!, method: .post, parameters: parameters2, headers: HEADERS ) .responseJSON { response in debugPrint(response) if let json = response.result.value { let dict = json as! NSDictionary let type : String = dict.value(forKeyPath: "Response.data.type") as! String let message : String = dict.value(forKeyPath: "Response.data.message") as! String if type == "success" { print(message) let storyboard : UIStoryboard = UIStoryboard(name: "Checkout", bundle: nil) let vc = storyboard.instantiateViewController(withIdentifier: "Deliverytype") self.navigationController?.pushViewController(vc, animated: true) } else { let alert = UIAlertController(title: "Try Again", message: message, preferredStyle: UIAlertControllerStyle.alert) // add an action (button) alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)) // show the alert self.present(alert, animated: true, completion: nil) } } } } func getCurrentDate() -> String { let date = Date() let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd HH:mm:ss" let currentDate = formatter.string(from: date) return currentDate } /* // 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. } */ }
// // LabelReusableView.swift // AllPeople // // Created by zzh_iPhone on 16/4/22. // Copyright © 2016年 zzh_iPhone. All rights reserved. // import UIKit class LabelReusableView: UICollectionReusableView { var topLabel: UILabel? var leftLabel:UILabel? var nameLabel:UILabel? var btn: UIButton? override init(frame: CGRect) { super.init(frame: frame) topLabel = UILabel() self.addSubview(topLabel!) topLabel?.snp_makeConstraints(closure: { (make) in make.left.right.top.equalTo(self) make.height.equalTo(6) }) topLabel?.backgroundColor = UIColor.grayColor() leftLabel = UILabel() self.addSubview(leftLabel!) leftLabel?.snp_makeConstraints(closure: { (make) in make.right.equalTo(self.snp_left).offset(15) make.width.equalTo(5) make.centerY.equalTo(self.snp_centerY).offset(6) make.height.equalTo(20) }) leftLabel?.backgroundColor = UIColor.redColor() nameLabel = UILabel() self.addSubview(nameLabel!) nameLabel?.snp_makeConstraints(closure: { (make) in make.width.equalTo(70) make.centerY.equalTo((leftLabel?.snp_centerY)!) make.height.equalTo(20) make.left.equalTo((leftLabel?.snp_right)!).offset(15) }) btn = UIButton() // btn?.backgroundColor = UIColor.greenColor() btn?.setTitle("进去看看", forState: UIControlState.Normal) btn?.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal) btn?.titleLabel?.font = UIFont.systemFontOfSize(14) self.addSubview(btn!) btn?.snp_makeConstraints(closure: { (make) in make.right.equalTo(-8) make.width.equalTo(70) make.centerY.equalTo((leftLabel?.snp_centerY)!) make.height.equalTo(20) }) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func releaseData(movieData:DirectData) { nameLabel?.text = movieData.THREE.title } }
// // CommandFilter.swift // Telegrammer // // Created by Givi Pataridze on 21.04.2018. // import Foundation import Vkontakter import Telegrammer /// Messages which contains command public extension Filters { static var command = Filters(vk: Vkontakter.Filters.command, tg: Telegrammer.Filters.command) }
/// Represents a client. public protocol SocketClient { /// The `SocketRoom` which contains this client. typealias Room = SocketRoom<Self> /// The shared data type stored in the room. associatedtype Share: SocketShare = SocketDefaultShare /// The initial data type sent by the client. associatedtype Query: SocketQuery = SocketDefaultQuery /// Initialize a new `SocketClient`. /// /// `room.clients` does not contain this client at this point. /// /// - Parameters: /// - room: The surrounding room. /// - socket: The `Socket` instance attached to this client. /// - query: The initial data sent by the client. init(room: Room, socket: Socket, query: Query) /// Called when the client successfully connects to the server. /// The `clients` property in the room is populated with this client by the time `onConnect` is called. func onConnect() }
// // Version.Array.swift // iOS Example // // Created by Leo Dion on 9/21/16. // Copyright © 2016 BrightDigit, LLC. All rights reserved. // import Foundation import SwiftVer let _exampleVersion = Version(bundle: Bundle.main, versionControl: VersionControlInfo(TYPE: VCS_TYPE, BASENAME: VCS_BASENAME, UUID: VCS_UUID, NUM: VCS_NUM, DATE: VCS_DATE, BRANCH: VCS_BRANCH, TAG: VCS_TAG, TICK: VCS_TICK, EXTRA: VCS_EXTRA, FULL_HASH: VCS_FULL_HASH, SHORT_HASH: VCS_SHORT_HASH, WC_MODIFIED: VCS_WC_MODIFIED)) extension Version { var values : [(label: String, value: String?)] { var values = [(label: String, value: String?)]() values.append((label: "semverDescription", value: self.semver.description)) values.append((label: "semverMajor", value: self.semver.major.description)) values.append((label: "semverMinor", value: self.semver.minor.description)) values.append((label: "semverPatch", value: self.semver.patch?.description)) values.append((label: "build", value: self.build.description)) values.append((label: "vcsBasename", value: self.versionControl!.BASENAME)) values.append((label: "vcsBranch", value: self.versionControl!.BRANCH)) values.append((label: "vcsDate", value: self.versionControl!.DATE?.description)) values.append((label: "vcsExtra", value: self.versionControl!.EXTRA)) values.append((label: "vcsFull_hash", value: self.versionControl!.FULL_HASH)) values.append((label: "vcsNum", value: self.versionControl!.NUM.description)) values.append((label: "vcsShortHash", value: self.versionControl!.SHORT_HASH)) values.append((label: "vcsTag", value: self.versionControl!.TAG)) values.append((label: "vcsTick", value: self.versionControl!.TICK?.description)) values.append((label: "vcsType", value: self.versionControl!.TYPE.description)) values.append((label: "vcsUuid", value: self.versionControl!.UUID)) values.append((label: "vcsWc_modified", value: self.versionControl!.WC_MODIFIED.description)) return values } static var example : Version! { return _exampleVersion } }
// // CheckinModel.swift // WoopEventsApp // // Created by Ludgero Gil Mascarenhas on 01/08/19. // Copyright © 2019 Ludgero Gil Mascarenhas. All rights reserved. // import Foundation struct CheckInModel: Codable { var eventId: String var name: String var email: String } struct CheckInResponse: Codable { var code: String }
// // GlobalTimer.swift // PracticalTest // // Created by Mittal Banker on 01/10/17. // Copyright © 2017 test. All rights reserved. // import Foundation class GlobalTimer: NSObject { static let sharedTimer: GlobalTimer = { let timer = GlobalTimer() return timer }() var internalTimer: Timer? func startTimer(){ self.internalTimer?.invalidate() self.internalTimer = Timer.scheduledTimer(timeInterval: TimeInterval(1) /*seconds*/, target: self, selector: #selector(fireTimerAction), userInfo: nil, repeats: true) } func stopTimer(){ self.internalTimer?.invalidate() PTLocationSingleton.sharedInstance.startUpdatingLocation() } func fireTimerAction(sender: AnyObject?){ if(AppDelegate.shared().vehicleStarted==false){ AppDelegate.shared().vehicleStarted = true PTLocationSingleton.sharedInstance.updateLocation() AppDelegate.shared().current_date = Date() } else { let nowDate = Date() let newDate = AppDelegate.shared().current_date?.addingTimeInterval(TimeInterval(AppDelegate.shared().next_time_interval)) let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss" let date1 = dateFormatter.date(from: dateFormatter.string(from: nowDate))! let date2 = dateFormatter.date(from: dateFormatter.string(from: newDate!))! if(Constants.DEBUG_MODE){ print(date1) print(date2) } if(date1==date2){ PTLocationSingleton.sharedInstance.updateLocation() AppDelegate.shared().current_date = Date() } } } }
// // ActionView.swift // MarvelCharacters // // Created by Osamu Chiba on 9/27/21. // import SwiftUI struct ActionView: View { @ObservedObject var viewModel: CharacterListViewModel @State private var showSortActionSheet: Bool = false @State private var showFilterActionSheet: Bool = false public init(viewModel: CharacterListViewModel) { self.viewModel = viewModel } var body: some View { HStack (alignment: .center) { ZStack { TextField("Search for a character", text: $viewModel.searchText, // This is triggered when return key is pressed. onCommit: { viewModel.search() self.hideKeyboard() }) .padding(8) .multilineTextAlignment(.leading) .overlay(RoundedRectangle(cornerRadius: kCornerRadius / 2).stroke(Color(UIColor.systemGray4), lineWidth: kBorderLineWidth)) .shadow(radius: kCornerRadius) // overlay above seems to be covering this button and therefore becomes non-responsive to tapping. So place this above the text. HStack { Spacer() Button (action: { viewModel.clearSearch() }) { Image("clear") .foregroundColor(appPrimaryColor) } .frame(width: 24, height: 24, alignment: .center) .padding(kHalfPadding) } } Button(action: { self.hideKeyboard() showFilterActionSheet = true }) { Image("filter").foregroundColor(appPrimaryColor) } .frame(width: 40, height: 40, alignment: .center) .overlay(RoundedRectangle(cornerRadius: kCornerRadius / 2).stroke(Color(UIColor.systemGray4), lineWidth: kBorderLineWidth)) .shadow(radius: kCornerRadius) .actionSheet(isPresented: $showFilterActionSheet) { generateFilterActionSheet() }.if(viewModel.hasData) { $0.foregroundColor(appPrimaryColor) } else: { $0.foregroundColor(Color(UIColor.systemGray2)) } .disabled(!viewModel.hasData) Button(action: { self.hideKeyboard() showSortActionSheet = true }) { Image("sort").foregroundColor(viewModel.hasData ? appPrimaryColor : Color(UIColor.systemGray2)) } .frame(width: 40, height: 40, alignment: .center) .overlay(RoundedRectangle(cornerRadius: kCornerRadius / 2).stroke(Color(UIColor.systemGray4), lineWidth: kBorderLineWidth)) .shadow(radius: kCornerRadius) // Note: confirmationDialog for iOS 15 or later .actionSheet(isPresented: $showSortActionSheet) { generateSortActionSheet() }.if(viewModel.hasData) { $0.foregroundColor(appPrimaryColor) } else: { $0.foregroundColor(Color(UIColor.systemGray2)) } .disabled(!viewModel.hasData) }.padding(.horizontal, kDefaultPadding) } private func generateSortActionSheet() -> ActionSheet { let buttons = SortOptions.allCases.enumerated().map { i, option in Alert.Button.default(viewModel.currentSort == option ? Text("\(option.title) ✔️") : Text(option.title), action: { viewModel.sort(by: option) } ) } return ActionSheet(title: Text("Sort By"), buttons: buttons + [Alert.Button.cancel()]) } private func generateFilterActionSheet() -> ActionSheet { let buttons = FilterOptions.allCases.enumerated().map { i, option in Alert.Button.default(viewModel.currentFilter == option ? Text("\(option.title) ✔️") : Text(option.title), action: { viewModel.filter(by: option) } ) } return ActionSheet(title: Text("Filter By"), buttons: buttons + [Alert.Button.cancel()]) } }
// // Coordinator.swift // WavesWallet-iOS // // Created by mefilt on 13.09.2018. // Copyright © 2018 Waves Platform. All rights reserved. // import Foundation import Extensions protocol Coordinator: AnyObject { var childCoordinators: [Coordinator] { get set } /** It variable need marked to weak */ var parent: Coordinator? { get set } func start() } extension Coordinator { func isHasCoordinator<C: Coordinator>(type: C.Type) -> Bool { return childCoordinators.first(where: { (coordinator) -> Bool in return coordinator is C }) != nil } func removeCoordinators() { childCoordinators = [] } func addChildCoordinatorAndStart(childCoordinator: Coordinator) { addChildCoordinator(childCoordinator: childCoordinator) childCoordinator.start() } func addChildCoordinator(childCoordinator: Coordinator) { self.childCoordinators.append(childCoordinator) childCoordinator.parent = self } func removeChildCoordinator(childCoordinator: Coordinator) { self.childCoordinators = self.childCoordinators.filter { $0 !== childCoordinator } childCoordinator.parent = nil } func removeFromParentCoordinator() { parent?.removeChildCoordinator(childCoordinator: self) } }
// // ViewController.swift // MyPlayer // // Created by Pallav Trivedi on 26/09/16. // Copyright © 2016 CodeIt. All rights reserved. // import UIKit class ViewController: UIViewController { 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 didClickOnClickHereButton(sender: UIButton) { let playerViewController = PlayerViewController(nibName: "PlayerViewController",bundle: nil) self.navigationController?.pushViewController(playerViewController, animated: true) } }
// // EVDatabaseType.swift // ElsevierKit // // Created by Yuto Mizutani on 2018/09/19. // import Foundation /** Database codes - SeeAlso: https://dev.elsevier.com/documentation/EngineeringVillageAPI.wadl */ public enum EVDatabaseType: String { /// Compendex/EI Backfile case eiCompendex = "c" /// Inspec/Inspec Archive case inspec = "i" /// NTIS case ntis = "n" /// Paperchem case paperchem = "pc" /// Chimica case chimica = "cm" /// CBNB case cbnb = "cb" /// EnCompassLIT case enCompassLIT = "el" /// EnCompassPAT case enCompassPAT = "ep" /// GEOBASE case geobase = "g" /// GeoRef case geoRef = "f" /// US Patents case usParents = "u" /// EP Patents case epParents = "e" }
// // OAuthSignInManager.swift // BeeSwift // // Created by Andy Brett on 11/30/17. // Copyright © 2017 APB. All rights reserved. // import Foundation import FBSDKLoginKit import SwiftyJSON import TwitterKit class OAuthSignInManager: NSObject, GIDSignInDelegate, FBSDKLoginButtonDelegate { static let sharedManager = OAuthSignInManager() func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) { if (result.token != nil) { self.signInWithOAuthUserId(result.token.userID, provider: "facebook") } } func loginButtonDidLogOut(_ loginButton: FBSDKLoginButton!) { // never called } func loginWithTwitterSession(_ session: TWTRSession!) { self.signInWithOAuthUserId(session.userID, provider: "twitter") } func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) { if error != nil { return } self.signInWithOAuthUserId(user.userID, provider: "google_oauth2") } func sign(_ signIn: GIDSignIn!, didDisconnectWith user: GIDGoogleUser!, withError error: Error!) { // never called } func signUpWith(email: String, password: String, username: String) { SignedRequestManager.signedPOST(url: "/api/v1/users", parameters: ["email": email, "password": password, "username": username], success: { (responseObject) -> Void in CurrentUserManager.sharedManager.handleSuccessfulSignin(JSON(responseObject!)) }) { (responseError) -> Void in if responseError != nil { CurrentUserManager.sharedManager.handleFailedSignup(responseError!) } } } func signInWithOAuthUserId(_ userId: String, provider: String) { let params = ["oauth_user_id": userId, "provider": provider] SignedRequestManager.signedPOST(url: "api/private/sign_in", parameters: params, success: { (responseObject) -> Void in CurrentUserManager.sharedManager.handleSuccessfulSignin(JSON(responseObject!)) }) { (responseError) -> Void in if responseError != nil { CurrentUserManager.sharedManager.handleFailedSignin(responseError!) } } } }
// // tempViewController.swift // Facilities // // Created by hager on 2/2/19. // Copyright © 2019 Vodafone. All rights reserved. // import UIKit import SDWebImage class ServiceDetailsViewController: UIViewController { @IBOutlet weak var cardView: CardView! @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var channelsSubtitleLabel: UILabel! @IBOutlet weak var channelsTitleLabel: UILabel! @IBOutlet weak var channelsImageView: UIImageView! @IBOutlet weak var timeFreeSubtitleLabel: UILabel! @IBOutlet weak var timeFreeTitleLabel: UILabel! @IBOutlet weak var timeFreeImageView: UIImageView! @IBOutlet weak var feesSubtitleLabel: UITextView! @IBOutlet weak var feesTitleLabel: UILabel! @IBOutlet weak var feesImageView: UIImageView! @IBOutlet weak var requiredDocSubtitleLabel: UILabel! @IBOutlet weak var requiredDocTitleLabel: UILabel! @IBOutlet weak var requiredDocImageView: UIImageView! @IBOutlet weak var prerequisitesTitleLabel: UILabel! @IBOutlet weak var prerequisitesSubtitleLabel: UILabel! @IBOutlet weak var prerequisitesImageView: UIImageView! @IBOutlet weak var subtitleLabel: UILabel! @IBOutlet weak var serviceImageView: UIImageView! var service : Data? override func viewDidLoad() { super.viewDidLoad() setupUI() } func setupUI() { self.navigationController?.navigationBar.backIndicatorImage = #imageLiteral(resourceName: "back") self.navigationController?.navigationBar.backIndicatorTransitionMaskImage = #imageLiteral(resourceName: "back") self.navigationItem.title = service?.title scrollView.layer.cornerRadius = cardView.cornerRadius if let imageSource = service?.imageSrc { serviceImageView.sd_setImage(with: URL(string: imageSource)) } subtitleLabel.text = service?.briefEN prerequisitesImageView.image = #imageLiteral(resourceName: "prerequisites") prerequisitesTitleLabel.text = NSLocalizedString("prerequisitesTitle", comment: "") if let data = service?.prerequisites?.data(using: String.Encoding.unicode){ try? prerequisitesSubtitleLabel.attributedText = NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil) } requiredDocImageView.image = #imageLiteral(resourceName: "requireddoc") requiredDocTitleLabel.text = NSLocalizedString("requiredDocTitle", comment: "") if let data = service?.requiredDocuments?.data(using: String.Encoding.unicode){ try? requiredDocSubtitleLabel.attributedText = NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil) } feesImageView.image = #imageLiteral(resourceName: "fees") feesTitleLabel.text = NSLocalizedString("feesTitle", comment: "") if let data = service?.fees?.data(using: String.Encoding.unicode) { let attributedText = try? NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil) feesSubtitleLabel.attributedText = attributedText } timeFreeImageView.image = #imageLiteral(resourceName: "time") timeFreeTitleLabel.text = NSLocalizedString("timeFreeTitle", comment: "") timeFreeSubtitleLabel.text = service?.timeFrame channelsImageView.image = #imageLiteral(resourceName: "service") channelsTitleLabel.text = NSLocalizedString("channelsTitle", comment: "") channelsSubtitleLabel.text = service?.serviceChannels } }
import Foundation import FirebaseAuth import FirebaseStorage import FirebaseFirestore protocol SendCompletionDelegate { func sendCompletion() func deleteCompletion() } class SendDBModel { var db = Firestore.firestore() var sendCompletionDelegate: SendCompletionDelegate? func sendToDB(shopData: ShopData, shopImageData: Data) { var shopDataArray = ["shopCategory": shopData.shopCategory as Any, "shopName" : shopData.name as Any, "foodCategory": shopData.foodCategory as Any, "latitude" : shopData.latitude as Any, "longitude" : shopData.longitude as Any, "telnumber" : shopData.tel as Any, "shopURL" : shopData.url as Any, "prefecture" : shopData.prefecture as Any, "address" : shopData.address as Any, "imageURL" : "", "postDate" : Date().timeIntervalSince1970] as [String : Any] // No image if shopImageData == Data() { self.db.collection(Auth.auth().currentUser!.uid).document().setData(shopDataArray) return } // Exist image let imageRef = Storage.storage().reference().child("Images").child("\(UUID().uuidString + String(Date().timeIntervalSince1970)).jpg") imageRef.putData(shopImageData, metadata: nil){ (metaData, error) in if error != nil {return} imageRef.downloadURL{ (url, error) in if error != nil {return} // urlは直前まで常にnilの為、代入不可 self.db.collection(Auth.auth().currentUser!.uid).document().setData( ["shopCategory": shopData.shopCategory as Any, "shopName" : shopData.name as Any, "foodCategory": shopData.foodCategory as Any, "latitude" : shopData.latitude as Any, "longitude" : shopData.longitude as Any, "telnumber" : shopData.tel as Any, "shopURL" : shopData.url as Any, "prefecture" : shopData.prefecture as Any, "address" : shopData.address as Any, "imageURL" : url?.absoluteString as Any, "postDate" : Date().timeIntervalSince1970] as [String : Any] ) } } } func addImageToDB(shopData: ShopData, shopImageData: Data) { // Delete let imageRefForDelete = Storage.storage().reference(forURL: shopData.shopImageURL!) imageRefForDelete.delete(completion: { (error) in if error != nil {return} }) // Add let imageRef = Storage.storage().reference().child("Images").child("\(UUID().uuidString + String(Date().timeIntervalSince1970)).jpg") imageRef.putData(shopImageData, metadata: nil) { (metaData, error) in if error != nil {return} imageRef.downloadURL { (url, error) in if error != nil {return} // Update DB let doc = self.db.collection(Auth.auth().currentUser!.uid).document(shopData.documentID!) doc.updateData(["imageURL":url?.absoluteString as Any]) { (error) in if error != nil {return} self.sendCompletionDelegate?.sendCompletion() } } } } func deleteFromDB(documentID: String) { db.collection(Auth.auth().currentUser!.uid).document(documentID).delete { (error) in if error != nil {return} self.sendCompletionDelegate?.deleteCompletion() } } }
// // ReactiveCodable.swift // ReactiveCodable // // Created by Gunter Hager on 01/08/2017. // Copyright © 2017 Gunter Hager. All rights reserved. // import Foundation import ReactiveSwift import Result public let ReactiveCodableErrorDomain = "name.gunterhager.ReactiveCodable.ErrorDomain" // Error sent by ReactiveCodable mapping methods public enum ReactiveCodableError: Error { case decoding(DecodingError) case underlying(Error) case invalidRootKey public var nsError: NSError { switch self { case let .decoding(error): return error as NSError case let .underlying(error): return error as NSError default: return NSError(domain: ReactiveCodableErrorDomain, code: -1, userInfo: nil) } } } let userInfoRootKey = CodingUserInfoKey(rawValue: "rootKey")! // MARK: Signal extension SignalProtocol where Value == Data { /// Maps the given JSON object within the stream to an object of given `type`. /// /// - Parameters: /// - type: The type of the object that should be returned /// - decoder: A `JSONDecoder` to use. This allows configuring the decoder. /// - Returns: A new Signal emitting the decoded object. public func mapToType<T: Decodable>(_ type: T.Type, decoder: JSONDecoder = JSONDecoder()) -> Signal<T, ReactiveCodableError> { return signal .mapError { ReactiveCodableError.underlying($0) } .attemptMap { json -> Result<T, ReactiveCodableError> in return unwrapThrowableResult { try decoder.decode(type.self, from: json) } // let info = [NSLocalizedFailureReasonErrorKey: "The provided `Value` could not be cast to `Data` or there is no value at the given `rootKeys`: \(String(describing: rootKeys))"] // let error = NSError(domain: ReactiveCodableErrorDomain, code: -1, userInfo: info) // return .failure(.underlying(error)) } } public func mapToType<T: Decodable>(_ type: T.Type, rootKey: CodingKey, decoder: JSONDecoder = JSONDecoder()) -> Signal<T, ReactiveCodableError> { return signal .mapError { ReactiveCodableError.underlying($0) } .attemptMap { json -> Result<T, ReactiveCodableError> in guard let key = RootKey(key: rootKey) else { return .failure(ReactiveCodableError.invalidRootKey) } return unwrapThrowableResult { decoder.userInfo = [userInfoRootKey: key] let result = try decoder.decode(ContainerModel<T>.self, from: json) return result.nestedModel } } } } // MARK: SignalProducer extension SignalProducerProtocol where Value == Data { /// Maps the given JSON object within the stream to an object of given `type` /// /// - Parameters: /// - type: The type of the object that should be returned /// - decoder: A `JSONDecoder` to use. This allows configuring the decoder. /// - Returns: A new SignalProducer emitting the decoded object. public func mapToType<T: Decodable>(_ type: T.Type, decoder: JSONDecoder = JSONDecoder()) -> SignalProducer<T, ReactiveCodableError> { return producer.lift { $0.mapToType(type, decoder: decoder) } } public func mapToType<T: Decodable>(_ type: T.Type, rootKey: CodingKey, decoder: JSONDecoder = JSONDecoder()) -> SignalProducer<T, ReactiveCodableError> { return producer.lift { $0.mapToType(type, rootKey: rootKey, decoder: decoder) } } } // MARK: Helper private func unwrapThrowableResult<T>(throwable: () throws -> T) -> Result<T, ReactiveCodableError> { do { return .success(try throwable()) } catch { if let error = error as? DecodingError { return .failure(.decoding(error)) } else { // For extra safety, but the above cast should never fail return .failure(.underlying(error)) } } } // MARK: RootKey Helper struct RootKey: CodingKey { var intValue: Int? var stringValue: String init?(intValue: Int) { self.intValue = intValue self.stringValue = "\(intValue)" } init?(stringValue: String) { self.stringValue = stringValue } init?(key: CodingKey) { if let intValue = key.intValue { self.init(intValue: intValue) } else { self.init(stringValue: key.stringValue) } } } struct ContainerModel<T: Decodable>: Decodable { let nestedModel: T init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: RootKey.self) guard let rootKey = decoder.userInfo[userInfoRootKey] as? RootKey else { throw ReactiveCodableError.invalidRootKey } self.nestedModel = try container.decode(T.self, forKey: rootKey) } }
// // MasterViewController.swift // EducationSystem // // Created by Serx on 16/5/25. // Copyright © 2016年 Serx.Lee. All rights reserved. // import UIKit import Observable import Masonry import SnapKit let themeColor: UIColor = UIColor(red: 0/255.0, green: 175/255.0, blue: 240/255.0, alpha: 1) //let themeColor: UIColor = UIColor.orangeColor() public var keyBoardHideWhileSlideTableView: Observable<Float> = Observable(0) public var height: Observable<CGFloat> = Observable(0) public var currentHeight: CGFloat = 0.0 public var limHeight: CGFloat = 0.0 public var currentAlpha: CGFloat = 0.0 public var observeScrollView: Observable<Int> = Observable(0) class MasterViewController: UIViewController { var personalView: PersonSideBar! /// // var firstViewHeight2: Constraint? //situation container view @IBOutlet weak var situationContainer: UIView! @IBOutlet weak var titleBarSegment: UISegmentedControl! @IBOutlet weak var leftBarItem: UIBarButtonItem! @IBOutlet weak var rightBarItem: UIBarButtonItem! @IBOutlet weak var firstView: UIView! @IBOutlet weak var containerView: UIView! @IBOutlet weak var viewHeaderImage: UIImageView! @IBOutlet weak var firstViewHeight: NSLayoutConstraint! @IBOutlet weak var passingButton: UIButton! @IBOutlet weak var semesterButton: UIButton! @IBOutlet weak var failButton: UIButton! // var failButton: UIButton! // @IBOutlet weak var passingButtonToLeftBargin: NSLayoutConstraint! @IBOutlet weak var failButtonToRightBargin: NSLayoutConstraint! var searchBar: UISearchBar! var isLogin: Bool = true var type: String! var userName: String! var passWord: String! var rawHeight: CGFloat = (MasterViewController.getUIScreenSize(false) / 3.0) var minHeight: CGFloat = 90.0 var maxCha: CGFloat! var currentPageIndex: Int = 0 var pageControlBar: UIView! var currentTitleIndex: Int = 0 var nextPageDone: Bool = false var lastPageDone: Bool = false var controlBarLenght: CGFloat = MasterViewController.getUIScreenSize(true) / 3.0 var pageIndex: Int = 0 var screenEdgeRecognizer: UIScreenEdgePanGestureRecognizer! var currentRadius:CGFloat = 0.0 var nowInSituation: Bool = false var masterPageViewController: MasterPageViewController? { didSet { masterPageViewController?.masterDelegate = self } } var searchBarShow: Bool = false var classViewModel: MasterViewModel! var logicManager: MasterLogicManager = { return MasterLogicManager() }() var testLengh: CGFloat = 0.0 override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if self.searchBarShow || self.nowInSituation{ self.navigationController?.navigationBar.lt_setBackgroundColor(themeColor.colorWithAlphaComponent(1)) } else { self.navigationController?.navigationBar.lt_setBackgroundColor(themeColor.colorWithAlphaComponent(currentAlpha)) } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() // self.initViewConstraint() // super.viewDidLayoutSubviews() // self.firstView.frame = CGRectMake(0, 0, MasterViewController.getUIScreenSize(true), rawHeight) // self.containerView.frame = CGRectMake(0, rawHeight, MasterViewController.getUIScreenSize(true), MasterViewController.getUIScreenSize(false) - rawHeight) } override func viewDidLoad() { super.viewDidLoad() // self.initViewConstraint() self.initView() self.initObservable() self.initSearchBar() } func initView() { let fullPath = ((NSHomeDirectory() as NSString).stringByAppendingPathComponent("Documents") as NSString).stringByAppendingPathComponent("image1") if let savedImage = UIImage(contentsOfFile: fullPath) { self.viewHeaderImage.image = savedImage } //set the page bar let reck = CGRectMake((self.controlBarLenght - 64.0) / 2.0 , -7, 64, 6) self.pageControlBar = UIView(frame: reck) self.pageControlBar.backgroundColor = themeColor.colorWithAlphaComponent(0.7) self.pageControlBar.layer.cornerRadius = 3.0 self.containerView.addSubview(self.pageControlBar) let img = UIImage(named: "search")!.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal) self.rightBarItem.image = img self.rightBarItem.style = .Plain let img2 = UIImage(named: "menu")!.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal) self.leftBarItem.image = img2 self.leftBarItem.style = .Plain //set segmentControl's properties self.titleBarSegment.tintColor = UIColor.whiteColor() self.classViewModel = self.logicManager.classViewModel self.type = "passing" self.classViewModel.userName = self.userName self.classViewModel.passWord = self.passWord //situation container view self.situationContainer.alpha = 0 //side menu self.personalView = PersonSideBar.init(frame: self.view.frame) self.personalView.alpha = 0 UIApplication.sharedApplication().keyWindow?.addSubview(self.personalView) self.navigationController?.navigationBar.lt_setBackgroundColor(themeColor.colorWithAlphaComponent(0)) self.navigationController?.navigationBar.barTintColor = UIColor.whiteColor() self.navigationController?.navigationBar.hideBottomHairline() self.minHeight = 90.0 self.firstViewHeight.constant = rawHeight self.maxCha = self.rawHeight - minHeight currentHeight = rawHeight self.screenEdgeRecognizer = UIScreenEdgePanGestureRecognizer(target: self, action: #selector(self.dragSideMenu(_:))) self.screenEdgeRecognizer.edges = .Left self.screenEdgeRecognizer.delegate = self self.view.addGestureRecognizer(screenEdgeRecognizer) // self.passingButtonToLeftBargin.constant = (self.controlBarLenght - 64.0) / 2.0 // self.failButtonToRightBargin.constant = (self.controlBarLenght - 46) / 2.0 } func initViewConstraint() { ///set firstView Constraint self.firstView.snp_makeConstraints { (make) in // self.firstViewHeight2 = make.height.equalTo(self.rawHeight).constraint make.left.equalTo(self.view) make.right.equalTo(self.view) make.top.equalTo(self.view) } ///container View constraint self.containerView.snp_makeConstraints { (make) in make.top.equalTo(self.firstView.snp_bottom) make.left.equalTo(self.view) make.right.equalTo(self.view) make.bottom.equalTo(self.view) } //image view self.viewHeaderImage.snp_makeConstraints { (make) in make.left.equalTo(self.firstView) make.right.equalTo(self.firstView) make.top.equalTo(self.firstView) make.bottom.equalTo(self.firstView) } ///all button constraint self.passingButton.snp_makeConstraints { (make) in make.height.equalTo(30) make.width.equalTo(64) make.bottom.equalTo(0) make.left.equalTo((self.controlBarLenght - 64.0) / 2.0) } self.semesterButton.snp_makeConstraints { (make) in make.centerX.equalTo(0) make.bottom.equalTo(0) make.height.equalTo(30) make.width.equalTo(46) } self.failButton.snp_makeConstraints { (make) in make.height.equalTo(30) make.width.equalTo(46) make.bottom.equalTo(0) make.right.equalTo((self.controlBarLenght - 46) / 2.0) } } //MARK: init all observable properties func initObservable() { height.afterChange += {old, new in self.testLengh = new self.changHeight() } keyBoardHideWhileSlideTableView.afterChange += { old, new in if self.searchBar.isFirstResponder() { self.searchBar.resignFirstResponder() } } masterImageChange.afterChange += { old, new in let fullPath = ((NSHomeDirectory() as NSString).stringByAppendingPathComponent("Documents") as NSString).stringByAppendingPathComponent("image1") let savedImage = UIImage(contentsOfFile: fullPath) self.viewHeaderImage.image = savedImage } webViewObservable.afterChange += { old, new in switch new { case 1: let urlString = "http://baike.baidu.com/view/2897424.htm" self.presentWebView(urlString) case 2: let urlString = "http://baike.baidu.com/subview/36656/11240874.htm" self.presentWebView(urlString) case 3: let urlString = "http://baike.baidu.com/subview/36656/11240874.htm" self.presentWebView(urlString) default: break } } /** via the observeScrollView to controller the control bar slide before the page animation finish there three state: 1: dicatied to slide to the next title 2: if the bar not slide before the gestrure finish before, it will not fire (slideControlBar) method if the bar slide before, change the current title index as older value, and fire (slideControlBar) method 3: dicatied to slide to the last title */ observeScrollView.afterChange += { old, new in if new == 1 { if !self.nextPageDone { self.currentTitleIndex += 1 self.slideControlBar() self.nextPageDone = true } } else if new == -1{ if !self.lastPageDone { self.currentTitleIndex -= 1 self.slideControlBar() self.lastPageDone = true } } else if new == 2{ if self.currentTitleIndex != self.currentPageIndex { self.currentTitleIndex = self.currentPageIndex self.slideControlBar() self.nextPageDone = false self.lastPageDone = false } } // print(self.currentTitleIndex) } } // func initSearchBar() { let rect = CGRectMake(0, 20.0, MasterViewController.getUIScreenSize(false), 44.0) self.searchBar = UISearchBar(frame: rect) self.searchBar.backgroundColor = themeColor self.searchBar.placeholder = "输入课程关键字" self.searchBar.alpha = 0 self.searchBar.backgroundImage = UIImage() self.searchBar.barTintColor = themeColor self.searchBar.delegate = self if let searchField = self.searchBar.valueForKey("searchField") { searchField.layer.cornerRadius = 14.0 searchField.layer.borderWidth = 0 searchField.layer.masksToBounds = true } self.firstView.addSubview(self.searchBar) } func slideControlBar() { var reck = CGRectMake((self.controlBarLenght - 64.0) / 2.0 , -7, 64, 6) if self.currentTitleIndex == 0 { reck = CGRectMake((self.controlBarLenght - 64.0) / 2.0 , -7, 64, 6) } else if self.currentTitleIndex == 1 { reck = CGRectMake((self.controlBarLenght - 46) / 2.0 + self.controlBarLenght, -7, 46, 6) } else if self.currentTitleIndex == 2 { reck = CGRectMake((self.controlBarLenght - 46) / 2.0 + 2 * self.controlBarLenght, -7, 46, 6) } UIView.animateWithDuration(0.4, animations: { self.pageControlBar.frame = reck }) // observeScrollView <- 0 } func presentWebView(url: String) { let webController = SituationWebViewController() webController.url = url self.navigationController?.pushViewController(webController, animated: true) webViewObservable <- 0 } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) // self.navigationController?.navigationBar.lt_reset() } func changHeight() { self.testLengh = height.value if self.rawHeight - self.testLengh <= minHeight { currentAlpha = 1.0 return } let limHeight: CGFloat = rawHeight - self.testLengh // self.firstViewHeight2?.updateOffset(limHeight) //TT self.firstViewHeight.constant = limHeight currentHeight = limHeight ///change the navigationbar alpha if self.testLengh > NAVBAR_CHANGE_POINT { let alpha: CGFloat = 1.0 - ((maxCha - self.testLengh) / maxCha) currentAlpha = alpha self.navigationController?.navigationBar.lt_setBackgroundColor(themeColor.colorWithAlphaComponent(alpha)) } else { self.navigationController?.navigationBar.lt_setBackgroundColor(themeColor.colorWithAlphaComponent(0)) } } @IBAction func showSideBar(sender: AnyObject) { showSideMenu() } @IBAction func rightBarItem(sender: AnyObject) { self.searchBarShow = !self.searchBarShow self.classViewModel.showSearch = self.searchBarShow if searchBarShow { //TT self.firstViewHeight.constant = 94 UIView.animateWithDuration(0.2, animations: { // self.firstViewHeight2?.updateOffset(94) self.navigationController?.navigationBar.lt_setBackgroundColor(themeColor) self.view.layoutIfNeeded() }) { (complete) in self.searchBar.alpha = 1.0 //TT self.firstViewHeight.constant = 130 UIView.animateWithDuration(0.1, animations: { // self.firstViewHeight2?.updateOffset(130) self.searchBar.frame = CGRectMake(0, 56, MasterViewController.getUIScreenSize(true), 44) self.view.layoutIfNeeded() }) } height.unshare(removeSubscriptions: true) } else if !self.searchBarShow { //TT self.firstViewHeight.constant = 94 self.recoverTableViewData() if searchBar.isFirstResponder() { searchBar.resignFirstResponder() } UIView.animateWithDuration(0.1, animations: { // self.firstViewHeight2?.updateOffset(94) self.searchBar.frame = CGRectMake(0, 20, MasterViewController.getUIScreenSize(true), 44) self.view.layoutIfNeeded() }, completion: { (complete) in self.searchBar.alpha = 0 self.searchBar.text = "" self.changHeight() UIView.animateWithDuration(0.2, animations: { self.navigationController?.navigationBar.lt_setBackgroundColor(themeColor.colorWithAlphaComponent(currentAlpha)) self.view.layoutIfNeeded() }, completion: { (complete) in height.afterChange += {old, new in self.testLengh = new self.changHeight() } }) }) } } func recoverTableViewData() { switch self.type { case "passing": searchFinished <- 11 case "semester": searchFinished <- 22 case "fail": searchFinished <- 33 default: NSLog("error current type:\(type)") } } func showSideMenu(){ self.personalView.userKey = self.userName self.personalView.showPersonal() } func dragSideMenu(sender: UIScreenEdgePanGestureRecognizer){ if sender.state == .Ended { self.personalView.dragSideBarEnd() } else if sender.state == .Began{ self.personalView.userKey = self.userName } else { let dragPoint = sender.translationInView(self.view) self.personalView.showPersionalViaDrag(dragPoint) } } var button: UIBarButtonItem! @IBAction func segmentAction(sender: UISegmentedControl) { let title = self.titleBarSegment.titleForSegmentAtIndex(self.titleBarSegment.selectedSegmentIndex)! if title == "学习情况" { self.nowInSituation = true self.button = self.navigationItem.rightBarButtonItem self.navigationItem.rightBarButtonItem = nil UIView.animateWithDuration(0.2, animations: { self.situationContainer.alpha = 1.0 self.navigationController?.navigationBar.lt_setBackgroundColor(themeColor.colorWithAlphaComponent(1.0)) }) startLoadChart <- 1 // let vc = UIStoryboard.init(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("SituationView") // self.navigationController?.pushViewController(vc, animated: true) } else if title == "成绩总览" { self.nowInSituation = false self.navigationItem.rightBarButtonItem = self.button UIView.animateWithDuration(0.2, animations: { self.situationContainer.alpha = 0 if self.searchBarShow { self.navigationController?.navigationBar.lt_setBackgroundColor(themeColor.colorWithAlphaComponent(1)) } else { self.navigationController?.navigationBar.lt_setBackgroundColor(themeColor.colorWithAlphaComponent(currentAlpha)) } }) startLoadChart <- 0 } } @IBAction func clickSemesterButton(sender: UIButton) { self.searchBar.text = "" self.type = "semester" self.logicManager.checkCurrentTypeCourseIsExist(self.type) self.masterPageViewController?.scrollToViewController(index: 1) } @IBAction func clickPassingButton(sender: UIButton) { self.searchBar.text = "" self.type = "passing" self.logicManager.checkCurrentTypeCourseIsExist(self.type) self.masterPageViewController?.scrollToViewController(index: 0) } @IBAction func clickFailButton(sender: UIButton) { self.searchBar.text = "" self.type = "fail" self.logicManager.checkCurrentTypeCourseIsExist(self.type) self.masterPageViewController?.scrollToViewController(index: 2) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if let masterPageViewController = segue.destinationViewController as? MasterPageViewController { self.masterPageViewController = masterPageViewController } } static func getUIScreenSize(isWidth: Bool) -> CGFloat{ let iOSDeviceScreenSize: CGSize = UIScreen.mainScreen().bounds.size if isWidth { return iOSDeviceScreenSize.width } else { return iOSDeviceScreenSize.height } } } extension MasterViewController: UIGestureRecognizerDelegate { func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true } } //extension MasterViewController: UISearchResultsUpdating { // func updateSearchResultsForSearchController(searchController: UISearchController) { // let searchText = self.searchBar.text // self.logicManager.filterContentForSearchText(searchText!, type: self.type) // } //} extension MasterViewController: UISearchBarDelegate { func searchBar(searchBar: UISearchBar, textDidChange searchText: String) { let searchText = searchBar.text! self.logicManager.filterContentForSearchText(searchText, ctype:self.type) } } extension MasterViewController: MasterPageViewControllerDelegate { //page View ture to page and reload the table view func masterPageViewController(masterPageViewController: MasterPageViewController, didUpdatePageIndex index: Int) { self.logicManager.getDataAfterScroll(index) if self.isLogin { isLogin = false } else { self.searchBar.text = "" } self.currentPageIndex = index } func masterPageViewController(masterPageViewController: MasterPageViewController, didUpdatePageCount count: Int){ print(count) } }
// // ExportKeystoreViewController.swift // MMWallet // // Created by Dmitry Muravev on 12.09.2018. // Copyright © 2018 micromoney. All rights reserved. // import UIKit import CarbonKit enum ExportKeystoreViewType: String { case bystore = "bystore" case byqr = "byqr" } struct ExportKeystoreViewCategory { var title: String var type: ExportKeystoreViewType? } class ExportKeystoreViewController: BaseViewController, Loadable { @IBOutlet fileprivate var containerView: UIView! @IBOutlet fileprivate var carbonToolbar: UIToolbar! @IBOutlet weak var contentHeightConstraint: NSLayoutConstraint! @IBOutlet weak var scrollView: UIScrollView! fileprivate var carbonTabSwipeNavigation: CarbonTabSwipeNavigation? @IBOutlet weak var lineView: UIView! fileprivate var items: [ExportKeystoreViewCategory] { let itemsArray = [ExportKeystoreViewCategory(title: "Keystore", type: .bystore), ExportKeystoreViewCategory(title: "QR code", type: .byqr)] return itemsArray } var assetId: Int = 0 var keystorePasswordString = "" var passwordString = "" var enterPasswordView: EnterPasswordView? var exportKeystoreModels: [ExportKeystoreModel]? { didSet { exportKeystoreStoreViewController?.exportKeystoreModels = exportKeystoreModels exportKeystoreQRViewController?.exportKeystoreModels = exportKeystoreModels } } var exportKeystoreStoreViewController: ExportKeystoreStoreViewController? var exportKeystoreQRViewController: ExportKeystoreQRViewController? override func viewDidLoad() { super.viewDidLoad() configureView(isRefresh: false) } func applyData(assetId: Int) { self.assetId = assetId } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } override func configureView(isRefresh: Bool) { self.view.backgroundColor = UIColor(componentType: .viewBackground) carbonToolbar.barTintColor = UIColor(componentType: .viewBackground) lineView.backgroundColor = UIColor(componentType: .carbonLine) if !isRefresh { carbonTabSwipeNavigation = CarbonTabSwipeNavigation(items: items.map {$0.title}, toolBar: carbonToolbar, delegate: self) carbonTabSwipeNavigation?.insert(intoRootViewController: self, andTargetView: containerView) setupCarbonPages(carbonSwipeTabsItem: carbonTabSwipeNavigation!) //carbonTabSwipeNavigation?.pagesScrollView?.isScrollEnabled = false let widthOfTabIcons = (carbonToolbar.bounds.width)/2 carbonTabSwipeNavigation?.carbonSegmentedControl!.setWidth(widthOfTabIcons, forSegmentAt: 0) carbonTabSwipeNavigation?.carbonSegmentedControl!.setWidth(widthOfTabIcons, forSegmentAt: 1) //carbonTabSwipeNavigation!.currentTabIndex = 1 } else { setupCarbonPages(carbonSwipeTabsItem: carbonTabSwipeNavigation!) //carbonTabSwipeNavigation!.setIndicatorColor(nil) for cvc in carbonTabSwipeNavigation!.viewControllers.allValues { if let vc = cvc as? BaseViewController { vc.configureView(isRefresh: true) } } } } func loadData() { self.showLoader() DataManager.shared.exportKeystore(assetId: assetId, pass: keystorePasswordString, password: passwordString) { [weak self] (exportKeystoreModels, error, errorString) in if error == nil { self?.exportKeystoreModels = exportKeystoreModels self?.hideLoaderSuccess() } else { if let _errorString = errorString { self?.hideLoaderFailure(errorLabelTitle: "Request Private Key failed", errorLabelMessage: _errorString) return } else if let _error = error { self?.hideLoaderFailure(errorLabelTitle: "Request Private Key failed", errorLabelMessage: _error.getErrorString()) return } self?.hideLoaderFailure(errorLabelTitle: "Request Private Key failed", errorLabelMessage: "Unknown Error") } } } func showPasswordRequest() { if let sessionWords = SessionManager.shared.getWords() { passwordString = sessionWords loadData() return } enterPasswordView = R.nib.enterPasswordView.firstView(owner: nil) UIApplication.shared.keyWindow?.addSubview(enterPasswordView!) enterPasswordView?.snp.makeConstraints { (make) -> Void in make.top.equalTo(0) make.left.equalTo(0) make.width.equalTo(UIScreen.main.bounds.width) make.height.equalTo(UIScreen.main.bounds.height) } enterPasswordView?.delegate = self enterPasswordView?.alpha = 0 UIView.animate(withDuration: 0.3, animations: { [weak self] in self?.enterPasswordView?.alpha = 1 }, completion: nil) } } extension ExportKeystoreViewController: CarbonTabSwipeNavigationDelegate { func carbonTabSwipeNavigation(_ carbonTabSwipeNavigation: CarbonTabSwipeNavigation, viewControllerAt index: UInt) -> UIViewController { switch index { case 0: let vcStore = R.storyboard.exportKeystore.exportKeystoreStoreViewController()! vcStore.delegate = self exportKeystoreStoreViewController = vcStore return vcStore case 1: let vcQR = R.storyboard.exportKeystore.exportKeystoreQRViewController()! vcQR.delegate = self exportKeystoreQRViewController = vcQR vcQR.exportKeystoreModels = exportKeystoreModels return vcQR default: break } return UIViewController() } func setupCarbonPages(carbonSwipeTabsItem: CarbonTabSwipeNavigation) { carbonSwipeTabsItem.toolbar.isTranslucent = false carbonSwipeTabsItem.toolbar.backgroundColor = UIColor(componentType: .viewBackground) carbonSwipeTabsItem.setIndicatorColor(UIColor(componentType: .carbonText)) carbonSwipeTabsItem.setSelectedColor(UIColor(componentType: .navigationItemTint), font: FontFamily.SFProText.semibold.font(size: 15)) carbonSwipeTabsItem.setNormalColor(UIColor(componentType: .carbonText), font: FontFamily.SFProText.semibold.font(size: 15)) carbonSwipeTabsItem.setIndicatorHeight(2) //carbonSwipeTabsItem.setTabExtraWidth(CGFloat(15)) } } extension ExportKeystoreViewController: ExportKeystoreStoreViewControllerDelegate { func exportKeystoreStoreViewController(_ exportKeystoreStoreViewController: ExportKeystoreStoreViewController, didHeightChanged value: CGFloat) { self.contentHeightConstraint.constant = value self.scrollView.contentSize = CGSize(width: self.view.bounds.height, height: self.containerView.frame.origin.x + value) } func exportKeystoreStoreViewController(_ exportKeystoreStoreViewController: ExportKeystoreStoreViewController, didChangedPassword value: String) { keystorePasswordString = value showPasswordRequest() } } extension ExportKeystoreViewController: ExportKeystoreQRViewControllerDelegate { func exportKeystoreQRViewController(_ exportKeystoreQRViewController: ExportKeystoreQRViewController, didHeightChanged value: CGFloat) { self.contentHeightConstraint.constant = value self.scrollView.contentSize = CGSize(width: self.view.bounds.height, height: self.containerView.frame.origin.x + value) } func exportKeystoreQRViewController(_ exportKeystoreQRViewController: ExportKeystoreQRViewController, didChangedPassword value: String) { keystorePasswordString = value showPasswordRequest() } } extension ExportKeystoreViewController: EnterPasswordViewDelegate { func enterPasswordView(_ enterPasswordView: EnterPasswordView, requestAction password: String) { passwordString = password loadData() } func enterPasswordViewClose(_ enterPasswordView: EnterPasswordView) { } }
// // SAT.swift // ChaseChallenge // // Created by Ty Schultz on 10/9/18. // Copyright © 2018 Ty Schultz. All rights reserved. // import UIKit struct SAT: Codable, Equatable { let dbn : String let numOfTestTakers : String? let criticalReadingAvg : String? let mathAvg : String let writingAvg : String let schoolName : String enum CodingKeys: String, CodingKey { case dbn = "dbn" case numOfTestTakers = "num_of_sat_test_takers" case criticalReadingAvg = "sat_critical_reading_avg_score" case mathAvg = "sat_math_avg_score" case writingAvg = "sat_writing_avg_score" case schoolName = "school_name" } }
// // EntryTableViewCell.swift // Journal-CoreData // // Created by Nikita Thomas on 11/5/18. // Copyright © 2018 Nikita Thomas. All rights reserved. // import UIKit class EntryTableViewCell: UITableViewCell { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var timeStampLabel: UILabel! @IBOutlet weak var bodyTextLabel: UILabel! var entry: Entry? { didSet { updateViews() } } func updateViews() { guard let title = entry?.title, !title.isEmpty else {return} titleLabel.text = title bodyTextLabel.text = entry?.bodyText if let date = entry?.timeStamp { let formatter = DateFormatter() formatter.dateStyle = .short formatter.timeStyle = .short timeStampLabel.text = formatter.string(from: date) } } 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 } }
// DO NOT EDIT // Highway sourcery version 9.0.3 // imports are set by running sourcery via Highway. Every file should have tags like below that needs imports to be added // imports:begin import Foo import Foundation // imports:end /** # types excluding protocols - Boe - AutoGenerateProtocol - mockAnnotations - Boe.Inner - AutoGenerateProtocol - BoeInternal - AutoGenerateProtocol - Foo - AutoGenerateProtocol - mockAnnotations - Foo.Inner - AutoGenerateProtocol - includeNonDefaultVariantInProtocol - FooClass - AutoGenerateProtocol - FooClassNoImplementationsExtra - AutoGenerateProtocol - FooGeneric - AutoGenerateProtocol - generic - mockAnnotations - ProtocolWithAnnotation - AutoGenerateProtocol - mockAnnotations - skipclass # protocols - BoeInnerProtocol - AutoMockable - BoeInternalProtocol - AutoMockable - BoeProtocol - AutoMockable - mockLite - FooClassNoImplementationsExtraProtocol - AutoMockable - FooClassProtocol - AutoMockable - FooGenericProtocol - AutoMockable - generic - FooInnerProtocol - AutoMockable - FooProtocol - AutoMockable - dummyAnnotation - mockInherit - FooSuper - AutoMockable - InheritProtocol - ProtocolWithAnnotationProtocol - AutoMockable - extendDefaultToProtocol - skipclass */ public enum SourceryMockError: Swift.Error, Hashable { case implementErrorCaseFor(String) case subclassMockBeforeUsing(String) public var debugDescription: String { switch self { case let .implementErrorCaseFor(message): return """ 🧙‍♂️ SourceryMockError.implementErrorCaseFor: message: \(message) """ case let .subclassMockBeforeUsing(message): return """ \n 🧙‍♂️ SourceryMockError.subclassMockBeforeUsing: message: \(message) """ } } }
// // PrivacyPolicyViewController.swift // TermsAndPrivacy // // Created by Administrator on 8/23/16. // Copyright © 2016 Administrator. All rights reserved. // import UIKit import Alamofire class PrivacyPolicyViewController: UIViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate { var pageViewController: UIPageViewController! var pageTitle: NSArray! var pageWebView: NSMutableArray! override func viewDidLoad() { super.viewDidLoad() self.tabBarController?.tabBar.hidden = true self.navigationController?.navigationBarHidden = true self.pageTitle = NSArray(objects: "Privacy Policy","Refund And Cancellation Policy","Shipping And Delivery Policy") self.pageWebView = NSMutableArray() let headers = [ "Authorization": authorizationWithoutLogin, "Content-Type" : "application/json" ] let button = UIButton(frame: CGRect(x: 0, y: 15, width: 60 , height: 40)) button.backgroundColor = UIColor.whiteColor() button.setTitleColor(UIColor(red: 31.0/255.0, green: 75.0/255.0, blue: 164.0/255.0, alpha: 1), forState: .Normal) button.setTitle("Cancel", forState: .Normal) button.addTarget(self, action: #selector(cancelClicked), forControlEvents: .TouchUpInside) self.view.addSubview(button) LoadingOverlay.shared.showOverlay(view) self .setupPageControl() var url : NSURL! url = NSURL(string:"\(baseUrl)MarketPlaceCMS?itemtype=staticcontent&page=Home&key=staticcontent") Alamofire.request(.GET, url,headers: headers).responseJSON { response in if let JSON = response.result.value{ if let staticcontent: AnyObject = JSON["staticContentList"]{ if let policy: AnyObject = staticcontent["privacyPolicy"]{ //print(termAndcond) let trm = policy["text"] as! String self.pageWebView.addObject(trm) //self.termsConditionWebView.loadHTMLString(trm, baseURL: nil) } if let policy: AnyObject = staticcontent["refundAndCancellationPolicy"]{ //print(termAndcond) let trm = policy["text"] as! String self.pageWebView.addObject(trm) //self.termsConditionWebView.loadHTMLString(trm, baseURL: nil) } if let policy: AnyObject = staticcontent["shippingAndDeliveryPolicy"]{ //print(termAndcond) let trm = policy["text"] as! String self.pageWebView.addObject(trm) //self.termsConditionWebView.loadHTMLString(trm, baseURL: nil) } LoadingOverlay.shared.hideOverlayView() self.pageViewController = self.storyboard?.instantiateViewControllerWithIdentifier("PageView") as! UIPageViewController self.pageViewController.dataSource = self self.pageViewController.view.contentMode = .ScaleToFill // self.pageViewController.delegate = self self.setupPageControl() let startVC = self.viewControllerAtIndex(0) let viewController = NSArray(object: startVC) self.pageViewController.setViewControllers(viewController as? [UIViewController], direction: .Forward, animated: true, completion: nil) self.view.addSubview(self.pageViewController.view) self.pageViewController.didMoveToParentViewController(self) self.view.addSubview(button) } } } // var b = UIBarButtonItem(title: "Cancel", style: .Plain, target: self, action:"cancelClicked") // //leftBarButton.title = "Cancel" // // rightBarButton.customView = btnName // self.navigationItem.leftBarButtonItem = b } @IBAction func cancelClicked(){ self.dismissViewControllerAnimated(true, completion: nil) } private func setupPageControl() { /*let appearance = UIPageControl.appearance() // appearance.tintColor = UIColor.clearColor() // appearance.translatesAutoresizingMaskIntoConstraints = true // appearance.frame = CGRectMake(0, 0, boundss.width, 5) appearance.pageIndicatorTintColor = UIColor.lightGrayColor() appearance.currentPageIndicatorTintColor = UIColor.blackColor() // appearance.indicatorDiameter appearance.backgroundColor = UIColor.redColor() // appearance.bounds = CGRectMake(0, 30, 0, 0)*/ let pageController = UIPageControl.appearance() pageController.translatesAutoresizingMaskIntoConstraints = true pageController.pageIndicatorTintColor = UIColor.lightGrayColor() pageController.currentPageIndicatorTintColor = UIColor.blackColor() pageController.backgroundColor = UIColor.whiteColor() pageController.bounds = CGRectMake(0, 0, 0, 0) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func viewControllerAtIndex(index: Int) -> ContentViewController{ if ((self.pageTitle.count == 0) || (index >= self.pageTitle.count)){ return ContentViewController() } let vc: ContentViewController = self.storyboard?.instantiateViewControllerWithIdentifier("ContentView") as! ContentViewController vc.webviewIndex = self.pageWebView[index] as! String vc.titleIndex = self.pageTitle[index] as! String vc.pageIndex = index return vc } func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? { let vc = viewController as! ContentViewController var index = vc.pageIndex as Int if(index == 0 || index == NSNotFound) { return nil } index -= 1 return self.viewControllerAtIndex(index) } func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? { let vc = viewController as! ContentViewController var index = vc.pageIndex as Int if(index == NSNotFound) { return nil } index += 1 if(index == self.pageTitle.count) { return nil } return self.viewControllerAtIndex(index) } func presentationCountForPageViewController(pageViewController: UIPageViewController) -> Int { return self.pageTitle.count } func presentationIndexForPageViewController(pageViewController: UIPageViewController) -> Int { return 0 } /* // 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. } */ }
// // rotatedLabel.swift // pass_ios // // Created by jinkyu on 26/02/2020. // Copyright © 2020 EOM JUEON. All rights reserved. // import UIKit import Foundation class rotatedLabel:UILabel{ override init(frame: CGRect) { super.init(frame: frame); self.transform=CGAffineTransform(rotationAngle: 90); } }
import Foundation public enum RequestCachePolicy { case useProtocolCachePolicy case reloadIgnoringLocalCacheData case returnCacheDataElseLoad case returnCacheDataDontLoad var toNSURLRequestCachePolicy: NSURLRequest.CachePolicy { switch self { case .useProtocolCachePolicy: return .useProtocolCachePolicy case .reloadIgnoringLocalCacheData: return .reloadIgnoringLocalCacheData case .returnCacheDataElseLoad: return .returnCacheDataElseLoad case .returnCacheDataDontLoad: return .returnCacheDataDontLoad } } }
// // NumberCardsSet.swift // TrailingTest // // Created by 唐泽宇 on 2019/3/28. // Copyright © 2019 唐泽宇. All rights reserved. // import Foundation struct NumberCardsSet: Codable{ var numberCards = [CardInfo]() struct CardInfo: Codable{ let x: Int let y: Int let text: String let size: Int } init?(json:Data){ if let newValue = try? JSONDecoder().decode(NumberCardsSet.self, from: json){ self = newValue }else{ return nil } } var json: Data? { return try? JSONEncoder().encode(self) } init (numberCards:[CardInfo]){ self.numberCards = numberCards } }
// // MapMarker.swift // DeindeApp // // Created by Juliya on 22.07.17. // Copyright © 2017 Andrey Krit. All rights reserved. // import Foundation import GoogleMaps import CoreGraphics class MapMarker { let marker: GMSMarker var timeGl = "" var totalTime: Int? init(position: CLLocationCoordinate2D, time: String, map: GMSMapView, totalTimeOfPlace: Int) { marker = GMSMarker(position: position) let markerImage = UIImage(named: "marker") marker.iconView = UIImageView(image: drawText(text: time + ":00", inImage: markerImage!)) marker.map = map timeGl = time totalTime = totalTimeOfPlace } func drawText(text: String, inImage: UIImage) -> UIImage? { let font = UIFont.systemFont(ofSize: 12) let size = inImage.size UIGraphicsBeginImageContext(size) let context = UIGraphicsGetCurrentContext() context?.setShouldAntialias(true) inImage.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height)) let style : NSMutableParagraphStyle = NSMutableParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle style.alignment = .center let attributes:NSDictionary = [ NSFontAttributeName : font, NSParagraphStyleAttributeName : style, NSForegroundColorAttributeName : UIColor.white ] let textSize = text.size(attributes: attributes as? [String : Any]) let rect = CGRect(x: 0, y: 0, width: inImage.size.width, height: inImage.size.height) let textRect = CGRect(x: (rect.size.width - textSize.width)/2, y: (rect.size.height - textSize.height)/2 - 4, width: textSize.width, height: textSize.height) text.draw(in: textRect.integral, withAttributes: attributes as? [String : Any]) let resultImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return resultImage } func hideMarker() { marker.map = nil } func showMarker(map: GMSMapView) { marker.map = map } }
// // EmoticonManager.swift // XWSwiftEmojiDemo // // Created by 邱学伟 on 2016/11/16. // Copyright © 2016年 邱学伟. All rights reserved. // import UIKit class EmoticonManager { var packages : [EmoticonPackage] = [EmoticonPackage]() init() { //最近 packages.append(EmoticonPackage(id: "")) //默认表情 packages.append(EmoticonPackage(id: "com.sina.default")) //emoji packages.append(EmoticonPackage(id: "com.apple.emoji")) //浪小花 packages.append(EmoticonPackage(id: "com.sina.lxh")) } }
// // TransactionView.swift // etdstats // // Created by Qiwei Li on 9/6/21. // import SwiftUI struct TransactionView: View { @State var text: String = "" @State var isLoading = false @State var searchResult: SearchResponse? func search(){ isLoading = true; if text.isEmpty{ return } ETDStatsDataFetcher.searchBy(id: text){ data in searchResult = data; isLoading = false } } func buildMacOS() -> some View{ return NavigationView { VStack(alignment:.leading){ HStack { TextField("Transaction/User/Block ID", text: $text) .frame(minWidth: 300) Button(action: { search() }) { Image(systemName: "magnifyingglass") } Spacer() } .padding() if(isLoading){ HStack { Spacer() ProgressView("Loading...") Spacer() } } if let searchResult = searchResult{ TransactionList(searchResult: searchResult) } Spacer() } .navigationTitle(Text("Transactions")) } } func buildIOS() -> some View{ return VStack(alignment:.leading){ HStack { TextField("Transaction/User/Block ID", text: $text) .frame(minWidth: 300) Button(action: { search() }) { Image(systemName: "magnifyingglass") } Spacer() } .padding() if(isLoading){ HStack { Spacer() ProgressView("Loading...") Spacer() } } if let searchResult = searchResult{ TransactionList(searchResult: searchResult) } Spacer() } .navigationTitle(Text("Transactions")) } var body: some View { Group{ #if os(macOS) buildMacOS() #else buildIOS() #endif } } } struct TransactionView_Previews: PreviewProvider { static var previews: some View { TransactionView() } }
// // UserSignUp.swift // Traffic Zoom // // Created by Thanh Phạm on 12/7/17. // Copyright © 2017 3T Asia. All rights reserved. // import UIKit import Alamofire import SwiftyJSON class UserSignUp: MyViewController { @IBOutlet weak var tfName: UITextField! @IBOutlet weak var tfEmail: UITextField! @IBOutlet weak var tfPhone: UITextField! @IBOutlet weak var tfPassword: UITextField! @IBOutlet weak var btSignUp: UIButton! @objc func signUp(_ sender: UIButton) { if (tfName.text == "") { self.showMessage(message: LocalizedString("Name is required")) return; } let email = tfEmail.text! as String if (email == "") { self.showMessage(message: LocalizedString("Email address is required")) return; } if (!isValidEmail(email: email)) { self.showMessage(message: LocalizedString("Email address is not valid")) return; } if (tfPhone.text == "") { self.showMessage(message: LocalizedString("Phone is required")) return; } if (tfPassword.text == "") { self.showMessage(message: LocalizedString("Password is required")) return; } let params:Parameters = [ "email": email, "phone": tfPhone.text!, "name": tfName.text!, "password": tfPassword.text! ] //Sending http post request Alamofire .request(URL_USER_SIGN_UP, method: .post, parameters: params) .responseJSON { response in switch response.result { case .success: if let jsonData = response.result.value { let json = JSON(jsonData) let state = json["state"].numberValue let message = json["message"].stringValue //print(json.description) switch (state) { case 0: self.showMessage(message: message, OKAction: UIAlertAction(title: "OK", style: .default) { (action:UIAlertAction!) in self.goToSignIn() }) break; case 1: var errorMessage:String = message; if let errorName = json["input_error"]["name"].string { errorMessage = errorName } else if let errorEmail = json["input_error"]["email"].string { errorMessage = errorEmail } else if let errorPhone = json["input_error"]["phone"].string { errorMessage = errorPhone } else if let errorPassword = json["input_error"]["password"].string { errorMessage = errorPassword } self.showMessage(message: errorMessage) break; default: self.showMessage(message: message) break; } } break case .failure(let error): self.showMessage(message: error.localizedDescription) break } } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. btSignUp.layer.cornerRadius = 3 btSignUp.addTarget(self, action: #selector(signUp(_:)), for: .touchUpInside) tfName.delegate = self tfEmail.delegate = self tfPassword.delegate = self tfPhone.delegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
/* # B. Канонический путь <table><tbody><tr class="time-limit"><td class="property-title">Ограничение времени</td><td>1&nbsp;секунда</td></tr><tr class="memory-limit"><td class="property-title">Ограничение памяти</td><td>64Mb</td></tr><tr class="input-file"><td class="property-title">Ввод</td><td colspan="1">стандартный ввод или input.txt</td></tr><tr class="output-file"><td class="property-title">Вывод</td><td colspan="1">стандартный вывод или output.txt</td></tr></tbody></table> По заданной строке, являющейся абсолютным адресом в Unix-системе, вам необходимо получить канонический адрес. В Unix-системе "." соответсвутет текущей директории, ".." — родительской директории, при этом будем считать, что любое количество точек подряд, большее двух, соответствует директории с таким названием (состоящем из точек). "/" является разделителем вложенных директорий, причем несколько "/" подряд должны интерпретироваться как один "/". Канонический путь должен обладать следующими свойствами: 1) всегда начинаться с одного "/" 2) любые две вложенные директории разделяются ровно одним знаком "/" 3) путь не заканчивается "/" (за исключением корневой директории, состоящего только из символа "/") 4) в каноническом пути есть только директории, т.е. нет ни одного вхождения "." или ".." как соответствия текущей или родительской директории ## Формат ввода Вводится строка с абсолютным адресом, её длина не превосходит 100. ## Формат вывода Выведите канонический путь. */ import Foundation let pathString = readLine()! let pathComponents = pathString.components(separatedBy: "/") var canonicalComponents = [String]() for component in pathComponents[1...] { if component == ".." { if canonicalComponents.count > 0 { canonicalComponents.removeLast(1) } } else if !component.isEmpty && component != "." { canonicalComponents.append(component) } } print("/" + canonicalComponents.joined(separator: "/"))
// // AwardsView.swift // MyCourses // // Created by Kris Siangchaew on 5/12/2563 BE. // import SwiftUI struct AwardsView: View { @EnvironmentObject var dataController: DataController let awards: [Award] @State private var selectedAward: Award = Award.example @State private var showAwardDetail = false static let tag: String? = "Awards" let cols: [GridItem] = [ GridItem(.adaptive(minimum: 100, maximum: 100)) ] var body: some View { NavigationView { ScrollView { LazyVGrid(columns: cols, alignment: .center) { ForEach(awards) { award in Button { selectedAward = award showAwardDetail = true } label: { Image(systemName: award.image) .resizable() .scaledToFit() .padding() .frame(width: 100, height: 100) .foregroundColor( dataController.hasEarned(award: award) ? Color(award.color) : Color.secondary.opacity(0.5)) } } .navigationTitle("Awards") } } } .alert(isPresented: $showAwardDetail) { if dataController.hasEarned(award: selectedAward) { return Alert(title: Text("Unlocked: \(selectedAward.name)"), message: Text(selectedAward.description), dismissButton: .default(Text("OK"))) } else { return Alert(title: Text("Locked"), message: Text(selectedAward.description), dismissButton: .default(Text("OK"))) } } } } struct AwardsView_Previews: PreviewProvider { static let dataController = DataController.preview static var previews: some View { AwardsView(awards: Award.allAwards) .environmentObject(dataController) } }
// Copyright 2019-2022 Spotify AB. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation /// A connectable adapter which imposes asynchronous dispatch blocks around calls to `accept`. /// /// Creates `Connection`s that forward invocations to `accept` to a connection returned by the underlying connectable, /// first switching to the provided `acceptQueue`. In other words, the real `accept` method will always be executed /// asynchronously on the provided queue. final class AsyncDispatchQueueConnectable<Input, Output>: Connectable { private let underlyingConnectable: AnyConnectable<Input, Output> private let acceptQueue: DispatchQueue init( _ underlyingConnectable: AnyConnectable<Input, Output>, acceptQueue: DispatchQueue ) { self.underlyingConnectable = underlyingConnectable self.acceptQueue = acceptQueue } convenience init<C: Connectable>( _ underlyingConnectable: C, acceptQueue: DispatchQueue ) where C.Input == Input, C.Output == Output { self.init(AnyConnectable(underlyingConnectable), acceptQueue: acceptQueue) } func connect(_ consumer: @escaping Consumer<Output>) -> Connection<Input> { // Synchronized values protect against state changes within the critical regions that are accessed on both the // loop queue and the accept queue. An optional consumer allows for clearing the reference when it is no longer // valid. let disposalStatus = Synchronized(value: false) let protectedConsumer = Synchronized<Consumer<Output>?>(value: consumer) let connection = underlyingConnectable.connect { value in protectedConsumer.read { consumer in guard let consumer = consumer else { MobiusHooks.errorHandler("cannot consume value after dispose", #file, #line) } consumer(value) } } return Connection( acceptClosure: { [acceptQueue] input in acceptQueue.async { // Prevents forwarding if the connection has since been disposed. disposalStatus.read { disposed in guard !disposed else { return } connection.accept(input) } } }, disposeClosure: { guard disposalStatus.compareAndSwap(expected: false, with: true) else { MobiusHooks.errorHandler("cannot dispose more than once", #file, #line) } connection.dispose() protectedConsumer.value = nil } ) } }
// // RegisterViewController.swift // The Pray Together App // // Created by Jason Mundie on 10/28/17. // Copyright © 2017 Jason Mundie. All rights reserved. // import UIKit import Firebase class RegisterViewController: UIViewController { // OUTLETS @IBOutlet weak var profileImage: UIImageView! @IBOutlet weak var fullNameTextField: UITextField! @IBOutlet weak var usernameTextField: UITextField! @IBOutlet weak var emailTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var registerButton: UIButton! @IBOutlet weak var registerButtonLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() profileImage.layer.cornerRadius = 75/2 profileImage.clipsToBounds = true let tapGesture = UITapGestureRecognizer(target: self, action: #selector(RegisterViewController.handleSelectProfileImageView)) profileImage.addGestureRecognizer(tapGesture) profileImage.isUserInteractionEnabled = true registerButton.isEnabled = false handleTextField() hideKeyboardWhenTappedAround() } func handleTextField() { usernameTextField.addTarget(self, action: #selector(RegisterViewController.textFieldDidChange), for: UIControlEvents.editingChanged) emailTextField.addTarget(self, action: #selector(RegisterViewController.textFieldDidChange), for: UIControlEvents.editingChanged) passwordTextField.addTarget(self, action: #selector(RegisterViewController.textFieldDidChange), for: UIControlEvents.editingChanged) fullNameTextField.addTarget(self, action: #selector(RegisterViewController.textFieldDidChange), for: UIControlEvents.editingChanged) } @objc func textFieldDidChange() { guard let username = usernameTextField.text, !username.isEmpty, let email = emailTextField.text, !email.isEmpty, let password = passwordTextField.text, !password.isEmpty, let fullName = fullNameTextField.text, !fullName.isEmpty else { registerButtonLabel.textColor = #colorLiteral(red: 0.8039215803, green: 0.8039215803, blue: 0.8039215803, alpha: 1) registerButton.isEnabled = false return } registerButtonLabel.textColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0) registerButton.isEnabled = true } @objc func handleSelectProfileImageView() { let imagePickerController = UIImagePickerController() imagePickerController.delegate = self imagePickerController.allowsEditing = true let actionSheet = UIAlertController(title: "Photo Source", message: "choose a source", preferredStyle: .actionSheet) actionSheet.addAction(UIAlertAction(title: "Camera", style: .default, handler: { (action:UIAlertAction) in if UIImagePickerController.isSourceTypeAvailable(.camera) { imagePickerController.sourceType = .camera self.present(imagePickerController, animated: true, completion: nil) } else { print("camera not available") } })) actionSheet.addAction(UIAlertAction(title: "Photo Library", style: .default, handler: { (action:UIAlertAction) in imagePickerController.sourceType = .photoLibrary self.present(imagePickerController, animated: true, completion: nil) })) actionSheet.addAction(UIAlertAction(title: "Cancel", style: .default, handler: nil)) self.present(actionSheet, animated: true, completion: nil) } @IBAction func registerButtonTapped(_ sender: Any) { AuthService.instance.registerUser(withEmail: self.emailTextField.text!, andPassword: self.passwordTextField.text!, andUsername: self.usernameTextField.text!, andBio: "", andFullName: fullNameTextField.text!, andProfileImage: "", userCreationComplete: { (success, registrationError) in if success { AuthService.instance.loginUser(withEmail: self.emailTextField.text!, andPassword: self.passwordTextField.text!, loginComplete: { (success, nil) in self.performSegue(withIdentifier: "registerToTabBarId", sender: self) }) } else { print(String(describing: registrationError?.localizedDescription)) } }) guard let image = self.profileImage.image else { return } guard let uploadData = UIImageJPEGRepresentation(image, 0.3) else { return } guard let uid = Auth.auth().currentUser?.uid else { return } Storage.storage().reference().child("Profile Images").child("users").child(uid).putData(uploadData, metadata: nil) { (metadata, error) in if let error = error { print("Failed to upload profile picture", error) return } guard let profileImageUrl = metadata?.downloadURL()?.absoluteString else { return } print("successfully uploaded profile picture", profileImageUrl) guard let uid = Auth.auth().currentUser?.uid else { return } Database.database().reference().child("users").child(uid).updateChildValues(["profileImage" : profileImageUrl]) } } @IBAction func backButtonPressed(_ sender: Any) { dismiss(animated: true, completion: nil) } } extension RegisterViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate { func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { if let editedImage = info[UIImagePickerControllerEditedImage] as? UIImage { profileImage.image = editedImage } else if let originalImage = info[UIImagePickerControllerOriginalImage] as? UIImage { profileImage.image = originalImage } profileImage.layer.cornerRadius = profileImage.frame.width/2 profileImage.layer.masksToBounds = true profileImage.layer.borderColor = #colorLiteral(red: 0.5352031589, green: 0.6165366173, blue: 0.6980209947, alpha: 1) profileImage.layer.borderWidth = 3 picker.dismiss(animated: true, completion: nil) } }
// // XFEmoticonController.swift // 表情键盘 // // Created by xiaofans on 16/8/13. // Copyright © 2016年 xiaofan. All rights reserved. // import UIKit private let XFEmoticonCellID = "XFEmoticonCellID" class XFEmoticonController: UIViewController { // MARK:- 定义属性 var emoticonCallBack : (emoticon : XFEmoticon) -> () // MARK:- 懒加载 private lazy var collectionView : UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: EmoticonCollectionViewLayout()) private lazy var toolBar : UIToolbar = UIToolbar() private lazy var emoManager = XFEmoticonManager() // MARK:- 自定义构造函数 init(emoticonCallBack : (emoticon : XFEmoticon) -> ()) { // 先赋个初始值 self.emoticonCallBack = emoticonCallBack super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK:- 系统回调 override func viewDidLoad() { super.viewDidLoad() setupUI() } } // MARK:- 设置 UI见面 extension XFEmoticonController { private func setupUI() { view.addSubview(collectionView) view.addSubview(toolBar) collectionView.backgroundColor = UIColor.brownColor() toolBar.backgroundColor = UIColor.blueColor() // 设置 frame - 代码约束要设置下面为 false collectionView.translatesAutoresizingMaskIntoConstraints = false toolBar.translatesAutoresizingMaskIntoConstraints = false let views = ["toolBar" : toolBar, "collectionView" : collectionView] var const = NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[toolBar]-0-|", options: [], metrics: nil, views: views) const += NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[collectionView]-0-[toolBar]-0-|", options: [.AlignAllLeft, .AlignAllRight], metrics: nil, views: views) view.addConstraints(const) // 准备 collectionview prepareForCollectionView() // 准备 toolBar prepareForToolBar() } /// 准备 collectionview private func prepareForCollectionView() { // 注册 cell 设置数据源 collectionView.registerClass(XFEmoticonCell.self, forCellWithReuseIdentifier: XFEmoticonCellID) collectionView.dataSource = self collectionView.delegate = self } /// 准备 toolBar private func prepareForToolBar() { // 定义 toolbartitle let titles = ["最近", "默认", "Emoji", "浪小花"] // 遍历标题,创建 item var index = 0 var temItems = [UIBarButtonItem]() for title in titles { let item = UIBarButtonItem(title: title, style: .Plain, target: self, action: "itemClick:") item.tag = index index++ temItems.append(item) temItems.append(UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)) } // 设置toolBar 的 items 数据 temItems.removeLast() toolBar.items = temItems } } // MARK:- 事件监听 extension XFEmoticonController { /// item 点击事件 @objc private func itemClick(item : UIBarButtonItem) { // 获取点击 itemtag let tag = item.tag // 根据 tag获取当前组 let indexPath = NSIndexPath(forItem: 0, inSection: tag) // 滚动到对应位置 collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Left, animated: true) } } // MARK: - UICollectionView数据源和代理方法 extension XFEmoticonController : UICollectionViewDataSource, UICollectionViewDelegate { func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { // 根据 manager 里的包数量确定分区数 return emoManager.packages.count } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { // 取出 package let package = emoManager.packages[section] // 根据包内表情数量确定 cell 数 return package.emoticons.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(XFEmoticonCellID, forIndexPath: indexPath) as! XFEmoticonCell // 取出包 let package = emoManager.packages[indexPath.section] let emoticon = package.emoticons[indexPath.item] cell.emoticon = emoticon return cell } func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { // 取出点击的表情 let package = emoManager.packages[indexPath.section] let emoticon = package.emoticons[indexPath.item] // 将点击的表情添加到最近分组中 insertRecentlyEmoticon(emoticon) // 将表情回调给外部控制器 emoticonCallBack(emoticon: emoticon) } /// 添加到最近分组 private func insertRecentlyEmoticon(emoticon : XFEmoticon) { // 如果是空白表情或者删除按钮, 就不需要添加 if emoticon.isRemove || emoticon.isEmpty { return } // 如果已经有这个表情, 就将原来的删除 if emoManager.packages.first!.emoticons.contains(emoticon) { let index = emoManager.packages.first?.emoticons.indexOf(emoticon) emoManager.packages.first?.emoticons.removeAtIndex(index!) } else { emoManager.packages.first?.emoticons.removeAtIndex(19) } // 添加 emoManager.packages.first?.emoticons.insert(emoticon, atIndex: 0) } } // MARK:- 自定义布局 class EmoticonCollectionViewLayout: UICollectionViewFlowLayout { override func prepareLayout() { super.prepareLayout() // 1. 计算 item 的宽高 let itemWH = UIScreen.mainScreen().bounds.width / 7 // 2. 设置 layout 属性 itemSize = CGSize(width: itemWH, height: itemWH) minimumLineSpacing = 0 minimumInteritemSpacing = 0 scrollDirection = .Horizontal // 3. 设置 collectionView 属性 collectionView?.pagingEnabled = true collectionView?.showsHorizontalScrollIndicator = false collectionView?.showsVerticalScrollIndicator = false let insetMargin = (collectionView!.bounds.height - 3 * itemWH) / 2 collectionView?.contentInset = UIEdgeInsets(top: insetMargin, left: 0, bottom: insetMargin, right: 0) } }
// // 100_相同的树.swift // algorithm.swift // // Created by yaoning on 6/1/20. // Copyright © 2020 yaoning. All rights reserved. // //给定两个二叉树,编写一个函数来检验它们是否相同。 // //如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。 // //示例 1: // //输入: 1 1 // / \ / \ // 2 3 2 3 // // [1,2,3], [1,2,3] // //输出: true //示例 2: // //输入: 1 1 // / \ // 2 2 // // [1,2], [1,null,2] // //输出: false //示例 3: // //输入: 1 1 // / \ / \ // 2 1 1 2 // // [1,2,1], [1,1,2] // //输出: false // //来源:力扣(LeetCode) //链接:https://leetcode-cn.com/problems/same-tree //著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 import Foundation class Solution100 { public class TreeNode { public var val: Int public var left: TreeNode? public var right: TreeNode? public init(_ val: Int) { self.val = val self.left = nil self.right = nil } } func preOrderDFS(root: TreeNode?) -> [String] { guard let r = root else { return ["null"] } var res: [String] = [] res.append(String(r.val)) res += preOrderDFS(root: r.left) res += preOrderDFS(root: r.right) return res } func isSameTree(_ p: TreeNode?, _ q: TreeNode?) -> Bool { let values1 = preOrderDFS(root: p) let values2 = preOrderDFS(root: q) if values1.elementsEqual(values2) { return true } return false } func isSameTree2(_ p: TreeNode?, _ q: TreeNode?) -> Bool { if p == nil && q == nil { return true } return p?.val == q?.val && isSameTree(p?.left, q?.left) && isSameTree(p?.right, q?.right) } }
// // ScriptsViewController.swift // PedScripts // // Created by Victor Yurkin on 8/1/17. // Copyright © 2017 Weill Cornell Medicine. All rights reserved. // import UIKit class ScriptsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate, UIScrollViewDelegate { @IBOutlet weak var searchBar: UISearchBar! @IBOutlet weak var tableView: UITableView! let data: [String] = [ "Abdominal Mass", "Abdominal Pain", "Anemia", "Bruising / petechiae", "Cough", "Diarrhea", "Fever and rash", "Fever without a focus", "Headache", "Heart murmur", "Hematuria", "Hepatomegaly", "Leukocoria, Red or Wandering Eye", "Limp", "Lymphadenopathy", "Otalgia", "Positive PPD", "Proteinuria", "Rash", "Rhinorrhea", "Seizure", "Sore throat", "Splenomegaly", "Vomiting" ] var filteredData: [String] = [] override func viewDidLoad() { super.viewDidLoad() self.filteredData = self.data self.searchBar.barTintColor = UIColor(red: 230/255, green: 230/255, blue: 230/255, alpha: 1.0) self.searchBar.layer.borderWidth = 1 self.searchBar.layer.borderColor = UIColor.white.cgColor } func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { if let searchStr = self.searchBar.text { let searchStr = searchStr.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) if searchStr.isEmpty { self.filteredData = self.data }else { self.filteredData = self.data.filter({(dataString: String) -> Bool in return dataString.range(of: searchText, options: .caseInsensitive) != nil }) } } self.tableView.reloadData() } func searchBarTextDidEndEditing(_ searchBar: UISearchBar) { self.view.endEditing(true) } func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { self.view.endEditing(true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.filteredData.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "ScriptsCell", for: indexPath) for subview in cell.contentView.subviews { if subview.tag == 1 { subview.removeFromSuperview() } } cell.textLabel?.text = self.filteredData[indexPath.row] if indexPath.row != 0 { let separator = UIView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 0.5)) separator.backgroundColor = UIColor(red: 230/255, green: 230/255, blue: 230/255, alpha: 1.0) separator.tag = 1 cell.contentView.addSubview(separator) } return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { self.view.endEditing(true) let path = Bundle.main.path(forResource: "01", ofType: "json") do { let jsonString = try NSString(contentsOfFile: path!, encoding: String.Encoding.utf8.rawValue) if let data = jsonString.data(using: String.Encoding.utf8.rawValue) { do { if let jsonObj = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] { if let question = jsonObj["question"] as? [String:Any] { let questionViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "QuestionViewController") as! QuestionViewController questionViewController.currentQuestion = question if let title = jsonObj["title"] as? String { questionViewController.diseaseTitle = title } self.navigationController?.pushViewController(questionViewController, animated: true) } } } catch { print(error.localizedDescription) } } }catch { print("Not working!") } tableView.deselectRow(at: indexPath, animated: true) } func scrollViewDidScroll(_ scrollView: UIScrollView) { self.view.endEditing(true) } @IBAction func unwindToScripts(segue: UIStoryboardSegue) { } }
// // Screens.swift // SearchProject // // Created by DUCH Chamroeun on 10/31/19. // Copyright © 2019 DUCH Chamroeurn. All rights reserved. // import Foundation enum ScreenType: CaseIterable { case welcome case search case auth var storyboard: String { get { switch self { case .welcome: return NameOfStroyboard.Welcome case .search: return NameOfStroyboard.Main case .auth: return NameOfStroyboard.Auth } } } var name: String { get { switch self { case .welcome: return "Welcome" case .search: return "DCR Search" case .auth: return "DCR Authentication" } } } }
// // KFMUserInfo.swift // KifuSF // // Created by Alexandru Turcanu on 01/10/2018. // Copyright © 2018 Alexandru Turcanu. All rights reserved. // import Foundation class KFMUserInfo { let profileImageURL: URL let username: String let name: String let userReputation: Double let userDonationsCount: Int let userDeliveriesCount: Int init(profileImageURL: URL, name: String, username: String, userReputation: Double, userDonationsCount: Int, userDeliveriesCount: Int) { self.profileImageURL = profileImageURL self.name = name self.username = username self.userReputation = userReputation self.userDonationsCount = userDonationsCount self.userDeliveriesCount = userDeliveriesCount } }
// // TaskViewController.swift // BMKToDo // // Created by Bharat Khatke on 28/07/21. // import UIKit import CoreData class TaskViewController: UIViewController { @IBOutlet weak var taskNameTF: UITextField! @IBOutlet weak var taskDescriptionTextView: UITextView! @IBOutlet weak var saveBtn: UIBarButtonItem! var todoTaskVM: TodoViewModel? override func viewDidLoad() { super.viewDidLoad() self.updateTodoTaskView() } //MARK:- Set UI Data Here private func updateTodoTaskView() { setTextViewBorder() if let todoTaskVM = todoTaskVM { taskNameTF.text = todoTaskVM.taskName taskDescriptionTextView.text = todoTaskVM.descriptionText if todoTaskVM.isUpdate { saveBtn.title = "Save" } else { saveBtn.title = "Update" } } } //MARK:- Set TextView Corners private func setTextViewBorder() { taskDescriptionTextView.layer.borderWidth = 0.5 taskDescriptionTextView.layer.masksToBounds = true taskDescriptionTextView.layer.cornerRadius = 10 taskDescriptionTextView.layer.borderColor = UIColor.lightGray.cgColor } //MARK:- Back btn action @IBAction func backBtnPressed(_ sender: UIBarButtonItem) { navigationController?.popViewController(animated: true) } //MARK:- Save btn action @IBAction func saveBtnPressed(_ sender: UIBarButtonItem) { if let taskName = taskNameTF.text, !taskName.isEmpty { self.storeTaskData(taskName, taskDescriptionTextView.text ?? "NA") navigationController?.popViewController(animated: true) } else { let alertVC = UIAlertController(title: "Error", message: "Task name should not be empty", preferredStyle: .alert) let alertAction = UIAlertAction(title: "Ok", style: .cancel) { action in } alertVC.addAction(alertAction) present(alertVC, animated: true, completion: nil) } } //MARK:- Save Todo data in CoreData func storeTaskData(_ taskName: String, _ taskDiscription: String) { if let todoTaskVM = self.todoTaskVM { if todoTaskVM.isUpdate { todoTaskVM.addNewTodoTask(taskName, taskDiscription, todoTaskVM.getTaskType()) } else { todoTaskVM.updateExistingTask(taskName, taskDiscription, todoTaskVM.taskModel) } } } } extension TaskViewController: UITextViewDelegate, UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { self.view.endEditing(true) return true } func textViewShouldEndEditing(_ textView: UITextView) -> Bool { self.view.endEditing(true) return true } }
// // InstagramLoginViewController.swift // SwiftInstagram // // Created by Ander Goig on 8/9/17. // Copyright © 2017 Ander Goig. All rights reserved. // import UIKit import WebKit class InstagramLoginViewController: UIViewController { // MARK: - Types typealias SuccessHandler = (_ accesToken: String, _ sender: UIViewController) -> Void typealias FailureHandler = (_ error: InstagramError, _ sender: UIViewController) -> Void // MARK: - Properties private var authURL: URL? private var success: SuccessHandler? private var failure: FailureHandler? // MARK: - Initializers static var instanceFromView: UIViewController? { let bundle = Bundle(for: self) let storyboard = UIStoryboard(name: "Instagram", bundle: bundle) return storyboard.instantiateInitialViewController() } func configure(authURL: URL, success: SuccessHandler?, failure: FailureHandler?) { self.authURL = authURL self.success = success self.failure = failure } @IBOutlet private weak var webView: UIWebView! fileprivate var stopButton: UIBarButtonItem { return UIBarButtonItem(barButtonSystemItem: .stop, target: self, action: #selector(stopAction(_:))) } fileprivate var refreshButton: UIBarButtonItem { return UIBarButtonItem(barButtonSystemItem: .refresh, target: self, action: #selector(refreshAction(_:))) } // MARK: - View Lifecycle override func viewDidLoad() { super.viewDidLoad() if #available(iOS 11.0, *) { navigationItem.largeTitleDisplayMode = .never } navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(doneClicked(_:))) // Starts authorization if let url = authURL { webView.loadRequest(URLRequest(url: url, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData)) } } @objc private func doneClicked(_ sender: Any) { self.dismiss(animated: true, completion: nil) self.failure?(InstagramError(kind: .canceled, message: "Canceled"), self) } private func clearCookies() { if let cookies = HTTPCookieStorage.shared.cookies { for cookie in cookies { if cookie.domain.range(of: "instagram") != nil { HTTPCookieStorage.shared.deleteCookie(cookie) } } } } @objc private func refreshAction(_ sender: Any) { webView.reload() } @objc private func stopAction(_ sender: Any) { webView.stopLoading() webViewDidFinishLoad(webView) } } // MARK: - WKNavigationDelegate extension InstagramLoginViewController: UIWebViewDelegate { func webViewDidFinishLoad(_ webView: UIWebView) { let title = webView.stringByEvaluatingJavaScript(from: "document.title") navigationItem.title = title self.navigationItem.setRightBarButton(refreshButton, animated: true) } func webViewDidStartLoad(_ webView: UIWebView) { self.navigationItem.setRightBarButton(stopButton, animated: true) } func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool { guard let urlString = request.url?.absoluteString, let range = urlString.range(of: "#access_token=") else { return true } DispatchQueue.main.async { self.clearCookies() self.success?(String(urlString[range.upperBound...]), self) } return true } }
// // DrawingView.swift // LanguageLearner // // Created by Marty Ulrich on 7/20/18. // Copyright © 2018 marty. All rights reserved. // import Foundation import UIKit protocol DrawingViewDelegate { func touchesBegan(at point: CGPoint) func touchesMoved(at point: CGPoint) func touchesEnded(at point: CGPoint) } class DrawingView: UIImageView { var shouldDrawTouches = false private var lastPoint: CGPoint? = nil var delegate: DrawingViewDelegate? init() { super.init(image: nil) isUserInteractionEnabled = true } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func reset() { image = nil shouldDrawTouches = false } //MARK: - Touch handling override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { guard let touchPoint = touches.first?.location(in: self) else { return } delegate?.touchesBegan(at: touchPoint) } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { guard let touchPoint = touches.first?.location(in: self) else { return } delegate?.touchesMoved(at: touchPoint) if let lastPoint = lastPoint { drawLine(from: lastPoint, to: touchPoint) } lastPoint = touchPoint } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { guard let touchPoint = touches.first?.location(in: self), let lastPoint = lastPoint else { return } delegate?.touchesEnded(at: touchPoint) drawLine(from: lastPoint, to: touchPoint) self.lastPoint = nil } //MARK: - Drawing func drawPath(_ points: [CGPoint]) { guard points.count >= 2 else { return } for i in 1..<points.count { drawLine(from: points[i-1], to: points[i]) } } private func drawLine(from pointA: CGPoint, to pointB: CGPoint) { guard shouldDrawTouches else { return } UIGraphicsBeginImageContext(frame.size) let context = UIGraphicsGetCurrentContext() image?.draw(in: CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height)) context?.move(to: pointA) context?.addLine(to: pointB) context?.setLineWidth(10) context?.setLineJoin(.round) context?.setStrokeColor(UIColor.black.cgColor) context?.setLineCap(.round) context?.strokePath() image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() } //MARK: - }