text
stringlengths
8
1.32M
// // CropArea.swift // Quota // // Created by Marcin Włoczko on 04/01/2019. // Copyright © 2019 Marcin Włoczko. All rights reserved. // import UIKit import SnapKit import RxSwift import RxCocoa final class CropArea: UIControl { // MARK: - Variables var viewModel: CropAreaViewModel? { didSet { updateView() setupBinding() } } private let disposeBag = DisposeBag() // MARK: - Initializer override init(frame: CGRect) { super.init(frame: frame) setupAppearance() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupAppearance() } // MARK: - View's life cycle override func draw(_ rect: CGRect) { guard let area = viewModel?.cropArea.value else { return } let cropArea = UIBezierPath(rect: area) cropArea.lineWidth = 3 UIColor.black.setStroke() cropArea.stroke() } // MARK: - Event hanlders override func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool { let location = touch.location(in: self) return viewModel?.shouldBeginTracking(location: location) ?? false } override func continueTracking(_ touch: UITouch, with event: UIEvent?) -> Bool { let location = touch.location(in: self) viewModel?.follow(location: location) return true } // MARK: - Setup private func updateView() { setNeedsDisplay() } private func setupBinding() { guard let viewModel = viewModel else { return } viewModel.cropArea .subscribe(onNext: { [weak self] rect in self?.setNeedsDisplay() }).disposed(by: disposeBag) } private func setupAppearance() { backgroundColor = .clear } }
// // Review_ResponsesViewController.swift // Junior_Design_Final_Deliverable // // Created by Aaron Wasserman on 11/20/17. // Copyright © 2017 TeamHeavyw8. All rights reserved. // import UIKit import CoreData class Review_ResponsesViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { var firstAnswer: String? var secondAnswer: String? var thirdAnswer: String? var questionSelected: String? //array containing all of the questions var full_questions: [String]? //array containing keywords for each question var questions : [String] = ["1. Hip Fracture importance: ", "2. Spinal Fracture importance: ", "3. Activity importance: ", "4. Pain Reduction Importance: ", "5. Risk of Breast Cancer importance: ", "6. Risk of Blood Clots Importance: ", "7. Risk of Gastro-Intestinal Side-Effects: ", "8. Medication Risk Importance: "] //array of the inputted answers by the user var answers : [Int]? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBOutlet var responseTable: UITableView! func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 8 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = self.responseTable.dequeueReusableCell(withIdentifier: "responseCell", for: indexPath) cell.textLabel!.text = questions[indexPath.row] + String(answers![indexPath.row + 1]) return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) questionSelected = String(indexPath.row + 1) self.performSegue(withIdentifier: "goUpdateResponse", sender: self) } @IBAction func backToQuestions(_ sender: Any) { performSegue(withIdentifier: "backToLastQuestion", sender: self) } @IBAction func submitPressed(_ sender: Any) { let currentDateTime = Date() let formatter = DateFormatter() formatter.timeStyle = .short formatter.dateStyle = .short let dateTime = formatter.string(from: currentDateTime) print(dateTime) // this is where we want to save to Core Data let appDelegate = UIApplication.shared.delegate as? AppDelegate let managedContext = appDelegate?.persistentContainer.viewContext let entity = NSEntityDescription.entity(forEntityName: "Survey_Record", in: managedContext!)! let record = NSManagedObject(entity: entity, insertInto: managedContext) //this needs to be done for all 8 questions record.setValue(String(answers![1]), forKeyPath: "firstQuestion") record.setValue(String(answers![2]), forKeyPath: "secondQuestion") record.setValue(String(answers![3]), forKeyPath: "thirdQuestion") record.setValue(String(answers![4]), forKeyPath: "fourthQuestion") record.setValue(String(answers![5]), forKeyPath: "fifthQuestion") record.setValue(String(answers![6]), forKeyPath: "sixthQuestion") record.setValue(String(answers![7]), forKeyPath: "seventhQuestion") record.setValue(String(answers![8]), forKeyPath: "eighthQuestion") record.setValue(dateTime, forKeyPath: "dateTime") do { try managedContext?.save() } catch let error as NSError { print("Could not save. \(error), \(error.userInfo)") } self.performSegue(withIdentifier: "submitPressed", sender: self) } 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. if (segue.identifier == "goUpdateResponse") { if let destination = segue.destination as? Update_ResponsesViewController { //problem passing back from here; a lot of things are nil so I need to update //pass full questions? destination.full_questions = self.full_questions destination.questions = self.questions destination.questionNumber = questionSelected //passing full array of answers destination.answers = self.answers destination.firstAnswer = firstAnswer destination.secondAnswer = secondAnswer destination.thirdAnswer = thirdAnswer } } if (segue.identifier == "backToLastQuestion") { if let destination = segue.destination as? First_SurveyViewController { destination.answers = self.answers! destination.questions = self.full_questions! destination.question_number = 8 } } } }
// // ErrorClassifications.swift // GooglePlacesSearch // // Created by Himanshi Bhardwaj on 8/27/17. // Copyright © 2017 Himanshi Bhardwaj. All rights reserved. // extension Error { public var errorString: String { switch self.localizedDescription { case "The Internet connection appears to be offline." : return "Your Internet connection appears to be offline. Please try again once you are back online." case "ZERO_RESULTS" : return "No results found with that search." default: return "Oops! Something wrong happened. Please try again." } } }
// // AddMemberCollectionViewCell.swift // Coordinate // // Created by James Wilkinson on 10/03/2016. // Copyright © 2016 James Wilkinson. All rights reserved. // import UIKit class AddMemberCollectionViewCell: UICollectionViewCell { @IBOutlet var imageView: UIImageView! }
// // PieChartView.swift // crypto-graph // // Created by Александр Пономарев on 10.04.18. // Copyright © 2018 Base team. All rights reserved. // import UIKit struct Piece { let color: UIColor let value: CGFloat let name: String } class PieChartView: UIView { var pieces = [Piece]() { didSet { setNeedsDisplay() } } /// Defines whether the segment labels should be shown when drawing the pie chart var showSegmentLabels = true { didSet { setNeedsDisplay() } } /// Defines whether the segment labels will show the value of the segment in brackets var showSegmentValueInLabel = false { didSet { setNeedsDisplay() } } /// The font to be used on the segment labels var segmentLabelFont = UIFont.systemFont(ofSize: 15, weight: .medium) { didSet { textAttributes[NSAttributedStringKey.font] = segmentLabelFont setNeedsDisplay() } } private let paragraphStyle : NSParagraphStyle = { var p = NSMutableParagraphStyle() p.alignment = .center return p.copy() as! NSParagraphStyle }() private lazy var textAttributes : [NSAttributedStringKey : Any] = { return [NSAttributedStringKey.paragraphStyle : self.paragraphStyle, NSAttributedStringKey.font : self.segmentLabelFont] }() override init(frame: CGRect) { super.init(frame: frame) isOpaque = false } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func draw(_ rect: CGRect) { let ctx = UIGraphicsGetCurrentContext() let radius = min(frame.size.width, frame.size.height) * 0.5 let viewCenter = CGPoint(x: bounds.size.width * 0.5, y: bounds.size.height * 0.5) let valueCount = pieces.reduce(0, {$0 + $1.value}) var startAngle = -CGFloat.pi * 0.5 for piece in pieces { ctx?.setFillColor(piece.color.cgColor) let endAngle = startAngle + 2 * .pi * (piece.value / valueCount) ctx?.move(to: viewCenter) ctx?.addArc(center: viewCenter, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: false) ctx?.fillPath() startAngle = endAngle } for piece in pieces { guard piece.value / valueCount > 0.1 else { continue } let endAngle = startAngle + 2 * .pi * (piece.value / valueCount) ctx?.move(to: viewCenter) if showSegmentLabels { // do text rendering let halfAngle = startAngle + (endAngle - startAngle) * 0.5; let textPositionValue : CGFloat = 0.8 let segmentCenter = CGPoint(x: viewCenter.x + radius * textPositionValue * cos(halfAngle), y: viewCenter.y + radius * textPositionValue * sin(halfAngle)) let textToRender = showSegmentValueInLabel ? " \(piece.name)\n $\(piece.value.formattedToOneDecimalPlace)" : piece.name textAttributes[NSAttributedStringKey.foregroundColor] = UIColor.darkGray var renderRect = CGRect(origin: .zero, size: textToRender.size(withAttributes: textAttributes)) if pieces.count > 1 { renderRect.origin = CGPoint(x: segmentCenter.x - renderRect.size.width * 0.5, y: segmentCenter.y - renderRect.size.height * 0.5) } else { renderRect.origin = CGPoint(x: viewCenter.x - renderRect.size.width / 2, y: viewCenter.y - renderRect.size.height / 2) } textToRender.draw(in: renderRect, withAttributes: textAttributes) } startAngle = endAngle } } }
// // TextField.swift // Yelnur // // Created by Дастан Сабет on 11.04.2018. // Copyright © 2018 Дастан Сабет. All rights reserved. // import UIKit class TextField: UITextField { let inset: CGFloat = 4 // placeholder position override func textRect(forBounds bounds: CGRect) -> CGRect { return bounds.insetBy(dx: inset, dy: inset) } // text position override func editingRect(forBounds bounds: CGRect) -> CGRect { return bounds.insetBy(dx: inset, dy: inset) } }
// // CartViewController.swift // SmartOrder // // Created by 하영 on 08/05/2019. // Copyright © 2019 하영. All rights reserved. // import UIKit class CartViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) tableView.reloadData() } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { //데이터 삭제 myCart.selectedMenu.remove(at: indexPath.row) //셀 삭제 tableView.deleteRows(at: [indexPath], with: .automatic) } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let selectedItem = myCart.selectedMenu[indexPath.row] print("장바구니...\(selectedItem)") } override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 2 //section 갯수 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows if section == 1 { return myCart.selectedMenu.count } else { return 1 } //cell 갯수 } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if indexPath.section == 1 { return 111 } else { return 68 } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.section == 1 { let cell = tableView.dequeueReusableCell(withIdentifier: "MyCart", for: indexPath) as! CartTableViewCell let CartForTheRow:Order = myCart.selectedMenu[indexPath.row] cell.price.text = "금액 \(CartForTheRow.price)원" cell.name.text = CartForTheRow.coffee if (indexPath.row % 2) == 0 { cell.img?.image = UIImage(named: "coffee_picture_blue") } else{ cell.img?.image = UIImage(named: "coffee_picture_white") } cell.option.text = "사이즈\(CartForTheRow.size) / 얼음\(CartForTheRow.ice) / 샷추가\(CartForTheRow.shot)" cell.cnt.text = "수량 \(CartForTheRow.count)개" // cell.selectBtn?.image = UIImage(named: "select") return cell } else { let cell = tableView.dequeueReusableCell(withIdentifier: "MyCartOrderInfo", for: indexPath) as! CartOrderInfoCell var totalPrice:Int = 0 for item in 0..<cartSelectedArray.count { if cartSelectedArray[item] == 1 { totalPrice += myCart.selectedMenu[item].price } } cell.orderPrice.text = "\(totalPrice) 원" cell.backgroundColor = UIColor(red: 229/255, green: 229/255, blue: 229/255, alpha: 1.0) // cell.backgroundColor = UIColor(red: 98/255, green: 92/255, blue: 89/255, alpha: 0.2) return cell } } /* // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. /* let destVC = segue.destination as! DetailViewController let selectedCoffee = coffeeSubscript[self.tableView.indexPathForSelectedRow.row] // 여기서 self : tableView Controller destVC.coffeeForview = selectedCoffee */ } }
// // RegisterVC.swift // ChurchApp // // Created by Jessica Gomes on 3/7/19. // Copyright © 2019 Jessica Gomes. All rights reserved. // import UIKit import FirebaseDatabase import FirebaseAuth import TinyConstraints class RegisterVC: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource { var ref: DatabaseReference? var countUsers = 0; override func viewDidLoad() { super.viewDidLoad() self.setupBackButton() ref = Database.database().reference(withPath: "User") ref!.observe(.value, with: {snapshot in guard let values = snapshot.value as? [AnyObject] else{ return } self.countUsers = values.count }) NameTextFild.delegate = self EmailTextFild.delegate = self ContactNumberTextFild.delegate = self Password.delegate = self Password2.delegate = self } //--------------------[Oltlets]----------------- @IBOutlet weak var NameTextFild: UITextField! @IBOutlet weak var EmailTextFild: UITextField! @IBOutlet var ContactNumberTextFild: UITextField! @IBOutlet weak var UserPosition: UILabel! @IBOutlet weak var Password: UITextField! @IBOutlet weak var Password2: UITextField! @IBOutlet weak var label: UILabel! //----------------------- //-----------[POSITION CHOICE]--------- @IBOutlet weak var pickerView: UIPickerView! //List of elements on PickerView let position = ["Member","Leader", "Admin"] // Func section row that we want func numberOfComponents(in pickerView: UIPickerView) ->Int{ return 1 } // what text should be in each row func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return position[row] } // return how many rows we want func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return position.count } // diplay which row picked func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { UserPosition.text = position[row] } //-------------------------------------------------------------------------------------------------- // validation override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { ContactNumberTextFild.resignFirstResponder() } //-------------------------------------------------------------------------------------------------- // insert onto the firebase @IBAction func CommitButton(_ sender: Any) { let pass = String(Password.text!) let email = String(EmailTextFild.text!) if !ValidTypeMember(){ return } if ValidPass(pass1: Password.text ?? "", pass2: Password2.text ?? "."){ Auth.auth().createUser(withEmail: email, password: pass ){ (authResult, error) in if authResult?.user != nil { self.ref?.child(String(self.countUsers)).child("name").setValue(self.NameTextFild.text) self.ref?.child(String(self.countUsers)).child("email").setValue(self.EmailTextFild.text) self.ref?.child(String(self.countUsers)).child("contact").setValue(self.ContactNumberTextFild.text) self.ref?.child(String(self.countUsers)).child("position").setValue(self.UserPosition.text) let storyboard = UIStoryboard(name: "Manager", bundle: nil); let vc = storyboard.instantiateViewController(withIdentifier: "LoginViewController") self.present(vc, animated: true, completion: nil); } } } } func ValidPass(pass1: String, pass2: String) -> Bool { if pass1 == pass2{ if (pass1.count <= 5) { label.text = "passwort greater than 5" return false } }else{ label.text = "Password doesn't match" return false } label.text = "" return true } func ValidTypeMember() -> Bool{ if UserPosition.text == "Select"{ label.text = "Select a type of member" return false } return true } } extension RegisterVC : UITextFieldDelegate{ func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } }
// // Example8ViewController.swift // StellarDemo // // Created by AugustRush on 6/29/16. // Copyright © 2016 August. All rights reserved. // import UIKit class Example8ViewController: UIViewController { @IBOutlet weak var animateView: Ball! @IBAction func segment1ValueChanged(sender: UISegmentedControl) { let index = sender.selectedSegmentIndex; switch index { case 0: animateView.moveX(200).duration(1.0).easing(.Default).autoreverses().animate() case 1: animateView.moveX(200).duration(1.0).easing(.EaseIn).autoreverses().animate() case 2: animateView.moveX(200).duration(1.0).easing(.EaseOut).autoreverses().animate() case 3: animateView.moveX(200).duration(1.0).easing(.EaseInEaseOut).autoreverses().animate() default: print("") } } @IBAction func segment2ValueChanged(sender: UISegmentedControl) { animateView.frame = CGRect(x: 20,y: 120,width: 40,height: 40) let index = sender.selectedSegmentIndex; switch index { case 0: animateView.moveX(200).duration(1.0).easing(.Linear).autoreverses().animate() case 1: animateView.moveX(200).duration(1.0).easing(.SwiftOut).autoreverses().animate() case 2: animateView.moveX(200).duration(1.0).easing(.BackEaseIn).autoreverses().animate() case 3: animateView.moveX(200).duration(1.0).easing(.BackEaseOut).autoreverses().animate() default: print("") } } @IBAction func segment3ValueChanged(sender: UISegmentedControl) { animateView.frame = CGRect(x: 20,y: 120,width: 40,height: 40) let index = sender.selectedSegmentIndex; switch index { case 0: animateView.moveX(200).duration(1.0).easing(.BackEaseInOut).autoreverses().animate() case 1: animateView.moveX(200).duration(1.0).easing(.BounceOut).autoreverses().animate() case 2: animateView.moveX(200).duration(1.0).easing(.Sine).autoreverses().animate() case 3: animateView.moveX(200).duration(1.0).easing(.Circ).autoreverses().animate() default: print("") } } @IBAction func segment4ValueChanged(sender: UISegmentedControl) { animateView.frame = CGRect(x: 20,y: 120,width: 40,height: 40) let index = sender.selectedSegmentIndex; switch index { case 0: animateView.moveX(200).duration(1.0).easing(.ExponentialIn).autoreverses().animate() case 1: animateView.moveX(200).duration(1.0).easing(.ExponentialOut).autoreverses().animate() case 2: animateView.moveX(200).duration(1.0).easing(.ElasticIn).autoreverses().animate() case 3: animateView.moveX(200).duration(1.0).easing(.ElasticOut).autoreverses().animate() default: print("") } } @IBAction func segment5ValueChanged(sender: UISegmentedControl) { animateView.frame = CGRect(x: 20,y: 120,width: 40,height: 40) let index = sender.selectedSegmentIndex; switch index { case 0: animateView.moveX(200).duration(1.0).easing(.BounceReverse).autoreverses().animate() case 1: fallthrough case 2: fallthrough case 3: fallthrough default: print("") } } }
// // MainVC.swift // WarrenMyObjectives // // Created by Leonardo Correa on 12/11/19. // Copyright © 2019 Leonardo Correa. All rights reserved. // import Foundation import UIKit class SplashScreenVC: UIViewController { var myView: SplashScreenView! var model: SplashScreenViewModel = SplashScreenViewModel() override func loadView() { super.loadView() myView = SplashScreenView() self.view = myView } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. checkUserIsAuthenticated() } private func checkUserIsAuthenticated() { myView.activityIndicator.startAnimating() DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .seconds(3)) { [weak self] in guard let wSelf = self else { return } wSelf.myView.activityIndicator.stopAnimating() if (wSelf.model.userIsAuthenticated()) { // navigate to main screen AppDelegate.shared.rootViewController.switchToMainScreen() } else { // navigate to login screen AppDelegate.shared.rootViewController.switchToLogout() } } } }
// // ItemTableViewCell.swift // PAssessment // // Created by Enam on 8/24/21. // import Foundation import UIKit class ItemTableViewCell: UITableViewCell { @IBOutlet weak var containerView: UIView! @IBOutlet weak var ItemCollectionView: UICollectionView! var items:[Item] = [] override func prepareForReuse() { super.prepareForReuse() resetCollectionView() } func resetCollectionView() { guard items.count <= 0 else { return } items = [] ItemCollectionView.reloadData() } override func layoutSubviews() { self.containerView.layer.cornerRadius = 5 self.containerView.clipsToBounds = true } override func awakeFromNib() { super.awakeFromNib() self.ItemCollectionView.dataSource = self self.ItemCollectionView.delegate = self } } extension ItemTableViewCell: UICollectionViewDelegate,UICollectionViewDataSource{ func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return items.count > 5 ? 5 : items.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if items.count > indexPath.row { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ItemCollectionViewCell", for: indexPath) as! ItemCollectionViewCell let item = items[indexPath.row] cell.item = item return cell }else{ return UICollectionViewCell() } } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { // self.delegate.didSelectItem(petModel) } } extension ItemTableViewCell: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: ItemCollectionView.frame.size.width-10, height: ItemCollectionView.frame.size.height) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return 10 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return 10 } }
// // SwiftClassExtension.swift // homework // // Created by Liu, Naitian on 8/25/16. // Copyright © 2016 naitianliu. All rights reserved. // import Foundation extension RangeReplaceableCollectionType where Generator.Element : Equatable { // Remove first collection element that is equal to the given `object`: mutating func removeObject(object : Generator.Element) { if let index = self.indexOf(object) { self.removeAtIndex(index) } } }
//===--- UnsafeBufferPointer.swift.gyb ------------------------*- 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 // //===----------------------------------------------------------------------===// /// An iterator for the elements in the buffer referenced by /// `UnsafeBufferPointer` or `UnsafeMutableBufferPointer`. public struct UnsafeBufferPointerIterator<Element> : IteratorProtocol, Sequence { /// Advances to the next element and returns it, or `nil` if no next element /// exists. /// /// Once `nil` has been returned, all subsequent calls return `nil`. public mutating func next() -> Element? { if _position == _end { return nil } let result = _position!.pointee _position! += 1 return result } internal var _position, _end: UnsafePointer<Element>? } %for Mutable in ('Mutable', ''): /// A non-owning pointer to buffer of ${Mutable.lower()} `Element`s stored /// contiguously in memory, presenting a `Collection` interface to the /// underlying elements. /// /// The pointer should be aligned to `alignof(Element.self)`. public struct Unsafe${Mutable}BufferPointer<Element> : ${Mutable}Indexable, ${Mutable}Collection, RandomAccessCollection { public typealias Index = Int public typealias IndexDistance = Int public typealias Iterator = IndexingIterator<Unsafe${Mutable}BufferPointer<Element>> /// Always zero, which is the index of the first element in a /// non-empty buffer. public var startIndex: Int { return 0 } /// The "past the end" position---that is, the position one greater than the /// last valid subscript argument. /// /// The `endIndex` property of an `Unsafe${Mutable}BufferPointer` instance is /// always identical to `count`. public var endIndex: Int { return count } public func index(after i: Int) -> Int { // NOTE: this is a manual specialization of index movement for a Strideable // index that is required for UnsafeBufferPointer performance. The // optimizer is not capable of creating partial specializations yet. // NOTE: Range checks are not performed here, because it is done later by // the subscript function. return i + 1 } public func formIndex(after i: inout Int) { // NOTE: this is a manual specialization of index movement for a Strideable // index that is required for UnsafeBufferPointer performance. The // optimizer is not capable of creating partial specializations yet. // NOTE: Range checks are not performed here, because it is done later by // the subscript function. i += 1 } public func index(before i: Int) -> Int { // NOTE: this is a manual specialization of index movement for a Strideable // index that is required for UnsafeBufferPointer performance. The // optimizer is not capable of creating partial specializations yet. // NOTE: Range checks are not performed here, because it is done later by // the subscript function. return i - 1 } public func formIndex(before i: inout Int) { // NOTE: this is a manual specialization of index movement for a Strideable // index that is required for UnsafeBufferPointer performance. The // optimizer is not capable of creating partial specializations yet. // NOTE: Range checks are not performed here, because it is done later by // the subscript function. i -= 1 } public func index(_ i: Int, offsetBy n: Int) -> Int { // NOTE: this is a manual specialization of index movement for a Strideable // index that is required for UnsafeBufferPointer performance. The // optimizer is not capable of creating partial specializations yet. // NOTE: Range checks are not performed here, because it is done later by // the subscript function. return i + n } public func index( _ i: Int, offsetBy n: Int, limitedBy limit: Int ) -> Int? { // NOTE: this is a manual specialization of index movement for a Strideable // index that is required for UnsafeBufferPointer performance. The // optimizer is not capable of creating partial specializations yet. // NOTE: Range checks are not performed here, because it is done later by // the subscript function. let l = limit - i if n > 0 ? l >= 0 && l < n : l <= 0 && n < l { return nil } return i + n } public func distance(from start: Int, to end: Int) -> Int { // NOTE: this is a manual specialization of index movement for a Strideable // index that is required for UnsafeBufferPointer performance. The // optimizer is not capable of creating partial specializations yet. // NOTE: Range checks are not performed here, because it is done later by // the subscript function. return end - start } public func _failEarlyRangeCheck(_ index: Int, bounds: Range<Int>) { // NOTE: This method is a no-op for performance reasons. } public func _failEarlyRangeCheck(_ range: Range<Int>, bounds: Range<Int>) { // NOTE: This method is a no-op for performance reasons. } public typealias Indices = CountableRange<Int> public var indices: Indices { return startIndex..<endIndex } /// Access the `i`th element in the buffer. public subscript(i: Int) -> Element { get { _debugPrecondition(i >= 0) _debugPrecondition(i < endIndex) return _position![i] } %if Mutable: nonmutating set { _debugPrecondition(i >= 0) _debugPrecondition(i < endIndex) _position![i] = newValue } %end } public subscript(bounds: Range<Int>) -> ${Mutable}RandomAccessSlice<Unsafe${Mutable}BufferPointer<Element>> { get { _debugPrecondition(bounds.lowerBound >= startIndex) _debugPrecondition(bounds.upperBound <= endIndex) return ${Mutable}RandomAccessSlice( base: self, bounds: bounds) } % if Mutable: set { _debugPrecondition(bounds.lowerBound >= startIndex) _debugPrecondition(bounds.upperBound <= endIndex) // FIXME: swift-3-indexing-model: tests. _writeBackMutableSlice(&self, bounds: bounds, slice: newValue) } % end } /// Construct an Unsafe${Mutable}Pointer over the `count` contiguous /// `Element` instances beginning at `start`. /// /// If `start` is nil, `count` must be 0. However, `count` may be 0 even for /// a nonzero `start`. public init(start: Unsafe${Mutable}Pointer<Element>?, count: Int) { _precondition( count >= 0, "Unsafe${Mutable}BufferPointer with negative count") _precondition( count == 0 || start != nil, "Unsafe${Mutable}BufferPointer has a nil start and nonzero count") _position = start _end = start.map { $0 + count } } /// Returns an iterator over the elements of this sequence. /// /// - Complexity: O(1). public func makeIterator() -> UnsafeBufferPointerIterator<Element> { return UnsafeBufferPointerIterator(_position: _position, _end: _end) } /// A pointer to the first element of the buffer. public var baseAddress: Unsafe${Mutable}Pointer<Element>? { return _position } /// The number of elements in the buffer. public var count: Int { if let pos = _position { return _end! - pos } return 0 } let _position, _end: Unsafe${Mutable}Pointer<Element>? } extension Unsafe${Mutable}BufferPointer : CustomDebugStringConvertible { /// A textual representation of `self`, suitable for debugging. public var debugDescription: String { return "Unsafe${Mutable}BufferPointer" + "(start: \(_position.map(String.init(_:)) ?? "nil"), count: \(count))" } } %end @available(*, unavailable, renamed: "UnsafeBufferPointerIterator") public struct UnsafeBufferPointerGenerator<Element> {} // ${'Local Variables'}: // eval: (read-only-mode 1) // End:
// // GVNLoginViewController.swift // GlobalVerificationNetwork-HUCM // // Created by Chetu India on 20/04/17. // import UIKit class GVNLoginViewController: BaseController { // MARK:  Widget elements declarations. @IBOutlet weak var scrollViewTop: UIScrollView! @IBOutlet weak var viewUsernameView: UIView! @IBOutlet weak var viewPasswordView: UIView! @IBOutlet weak var viewLoginButtonView: UIView! @IBOutlet weak var viewBackgroundCheckView: UIView! @IBOutlet weak var buttonLogin: UIButton! @IBOutlet weak var buttonBackgroundCheck: UIButton! @IBOutlet weak var textFieldUserName: UITextField! @IBOutlet weak var textFieldPassWord: UITextField! // MARK:  instance variables, constant decalaration and define with infer type with default values. /* * UIViewController class life cycle overrided method to handle viewController functionality on the basis of the state of method in application. * E.g viewDidLoad method to iniailize all the component before appear screem. viewWillAppear method to show loadder or UI related task. */ // MARK:  UIViewController class overrided method. override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.preparedScreenDesign() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.loadScreenData() } // MARK:  preparedScreenDesign method. func preparedScreenDesign() { self.automaticallyAdjustsScrollViewInsets = false buttonLogin.titleLabel?.font = HEADERLABELTITLEFONT self.viewUsernameView.layer.cornerRadius = 20.0 self.viewPasswordView.layer.cornerRadius = 20.0 self.viewLoginButtonView.layer.cornerRadius = 20.0 self.viewLoginButtonView.layer.masksToBounds = true self.viewLoginButtonView.layer.borderColor = LOGINBUTTONBORDERCOLOR.cgColor self.viewLoginButtonView.layer.borderWidth = 1.0 self.viewBackgroundCheckView.layer.cornerRadius = 17.0 self.viewBackgroundCheckView.layer.masksToBounds = true self.viewBackgroundCheckView.layer.borderColor = BACKGROUNDCHECKBUTTONBORDERCOLOR.cgColor self.viewBackgroundCheckView.layer.borderWidth = 1.0 } // MARK:  loadScreenData method. func loadScreenData() { self.textFieldUserName.text = "test@chetu.com" self.textFieldPassWord.text = "Chetu@123" } // MARK:  buttonLoginTapped method. @IBAction func buttonLoginTapped(sender: UIButton){ if self.isLoginFormValid(){ // Network validation checks. if Reachability.isConnectedToNetwork(){ SwiftLoader.show(title: "Validate...", animated: true) let delay = DispatchTime.now() + 1 // change 1 to desired number of seconds DispatchQueue.main.asyncAfter(deadline: delay) { // Code to execute login api service. self.executeUserLoginAuthApiService() } } else{ DispatchQueue.main.async { self.showAlertWith(message: NSLocalizedString("NETWORK_VALIDATION", comment: "")) } } } } // MARK:  buttonLoginTapped method. @IBAction func buttonCreateAccountTapped(sender: UIButton){ let storyBoard : UIStoryboard = UIStoryboard(name: MAIN, bundle:nil) let gvnSignUpViewController = storyBoard.instantiateViewController(withIdentifier: GVNSIGNUPVIEWCONTROLLER) as! GVNSignUpViewController self.navigationController?.pushViewController(gvnSignUpViewController, animated: true) } // MARK:  executeUserLoginAuthApiService method. func executeUserLoginAuthApiService() { var signInRequestDict = [String: String]() signInRequestDict["username"] = textFieldUserName.text signInRequestDict["password"] = textFieldPassWord.text AuthenticationServices.authUserWith(inputFields: signInRequestDict, serviceType: UserAuthApiRequestType.Login ,completion: { (apiStatus, response) -> () in DispatchQueue.main.async { // Hide the swift progress loader SwiftLoader.hide() switch apiStatus{ case NetworkResponseStatus.Success: let tabBarController = CustomTabBarController() self.navigationController?.pushViewController(tabBarController, animated: true) break case NetworkResponseStatus.Failure: self.showAlertWith(message: response as! String) break default: print(response) break } } }) } // MARK:  ---------- Helper methods. // MARK:  isLoginFormValid method. func isLoginFormValid() -> Bool { var message = "" if textFieldUserName.text?.characters.count == 0{ message = NSLocalizedString("USERNAMEVALIDATION", comment: "") } else if !UtilManager.sharedInstance.isValidEmail(emailStr: textFieldUserName.text!){ message = NSLocalizedString("VALIDAEMAILVALIDATION", comment: "") } else if textFieldPassWord.text?.characters.count == 0{ message = NSLocalizedString("PASSWORDVALIDATION", comment: "") } if message.characters.count == 0{ return true } else{ self.showAlertWith(message: message) return false } } // MARK:  Memory management method. override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } /* * Extension of GVNLoginViewController to add UITextField prototcol UITextFieldDelegate. * Override the protocol method of textfield delegate in GVNLoginViewController to handle textfield action event and slector method. */ // MARK:  UITextField Delegates methods extension GVNLoginViewController: UITextFieldDelegate{ func textFieldShouldReturn(_ textField: UITextField) -> Bool { let textFieldTagIndex = textField.tag switch textFieldTagIndex { case 101: // For Email and Username textFieldPassWord.becomeFirstResponder() return true case 201: // For Password textFieldPassWord.resignFirstResponder() return true default: return true } } }
import UIKit class ArtworkSetViewController: UIPageViewController, UIPageViewControllerDataSource { var artworks:[Artwork]! var initialIndex: Int! override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) dataSource = self guard let artworkVC = viewControllerForIndex(initialIndex) else { return print("Wrong current index given to artwork set VC") } setViewControllers([artworkVC], direction: .Forward, animated: false, completion: nil) } func isValidIndex(index: Int) -> Bool { return index > -1 && index <= artworks.count - 1 } func viewControllerForIndex(index: Int) -> ArtworkViewController? { guard let storyboard = storyboard else { return nil } guard isValidIndex(index) else { return nil } guard let artworkVC = storyboard.instantiateViewControllerWithIdentifier("artwork") as? ArtworkViewController else { return nil} artworkVC.artwork = artworks[index] artworkVC.index = index return artworkVC } func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? { guard let currentArtworkVC = viewController as? ArtworkViewController else { return nil } let newIndex = (currentArtworkVC.index + 1) % self.artworks.count; return viewControllerForIndex(newIndex) } func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? { guard let currentArtworkVC = viewController as? ArtworkViewController else { return nil } var newIndex = currentArtworkVC.index - 1 if (newIndex < 0) { newIndex = artworks.count - 1 } return viewControllerForIndex(newIndex) } }
// // TweetsProfileCell.swift // Twitter // // Created by Carly Burroughs on 2/29/16. // Copyright © 2016 Carly Burroughs. All rights reserved. // import UIKit class TweetsProfileCell: UITableViewCell { @IBOutlet weak var profileImageView: UIImageView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var usernameLabel: UILabel! @IBOutlet weak var tweetTextLabel: UILabel! @IBOutlet weak var replyButton: UIButton! @IBOutlet weak var retweetLabel: UIButton! @IBOutlet weak var favoriteButton: UIButton! var tweet: Tweet! { didSet { if let thumbURL = tweet.profileImageURL { profileImageView.setImageWithURL(thumbURL) } nameLabel.text = tweet.name usernameLabel.text = "@\(tweet.userName!)" tweetTextLabel.text = tweet.text } } override func awakeFromNib() { super.awakeFromNib() // Initialization code nameLabel.preferredMaxLayoutWidth = nameLabel.frame.size.width } override func layoutSubviews() { super.layoutSubviews() nameLabel.preferredMaxLayoutWidth = nameLabel.frame.size.width tweetTextLabel.sizeToFit() usernameLabel.sizeToFit() tweetTextLabel.numberOfLines = 0 nameLabel.sizeToFit() tweetTextLabel.preferredMaxLayoutWidth = 244 profileImageView.layer.cornerRadius = 3 profileImageView.clipsToBounds = true } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
import XCTest @testable import Cassowary import class Simplex.Variable class BasicTests: XCTestCase { func testVariable_equal() throws { var solver = Solver() try solver.addConstraints(x1 == 100) let solution = try solver.solve() XCTAssertEqual(solution, [x1: 100]) } func testVariable_greaterThanOrEqual() throws { var solver = Solver() try solver.addConstraints(x1 >= 100) let solution = try solver.solve() XCTAssertEqual(solution, [x1: 100]) } func testVariable_lessThanOrEqual() throws { var solver = Solver() try solver.addConstraints(x1 <= 100) let solution = try solver.solve() XCTAssertEqual(solution, [x1: 100]) } /// http://spa.jssst.or.jp/2002/spa02-6-2.pdf func testNonRequiredConstraints() throws { var solver = Solver() try solver.addConstraints( x1 + x2 == 5.0 ~ .high, x1 >= 2 ~ .high, x2 >= 1 ~ .high, x2 == 4 ~ .low ) let solution = try solver.solve() XCTAssertEqual(solution, [x1: 2, x2: 3]) } }
// // OrderedDictionaryType.swift // DictionaryTools // // Created by James Bean on 6/26/16. // Copyright © 2016 James Bean. All rights reserved. // /** Interface defining OrderedDictionary value types. */ public protocol OrderedDictionaryType: DictionaryType { // MARK: - Associated Types /// CollectionType storing the keys. associatedtype KeyStorage: Collection // MARK: - Instance Properties /// Keys of the backing dictionary. var keyStorage: KeyStorage { get set } /// Backing dictionary. var values: [Key: Value] { get set } } extension OrderedDictionaryType where KeyStorage.Index == Int { /** - returns: An array containing the transformed elements of this sequence. */ public func map<T>(transform: (Iterator.Element) throws -> T) rethrows -> [T] { let initialCapacity = underestimatedCount var result = ContiguousArray<T>() result.reserveCapacity(initialCapacity) var iterator = makeIterator() // Add elements up to the initial capacity without checking for regrowth. for _ in 0..<initialCapacity { result.append(try transform(iterator.next()!)) } // Add remaining elements, if any. while let element = iterator.next() { result.append(try transform(element)) } return Array(result) } } extension OrderedDictionaryType where Index == Int, KeyStorage.Index == Int, KeyStorage.Iterator.Element == Key { // MARK: - Collection public var startIndex: Int { return keyStorage.startIndex } public var endIndex: Int { return keyStorage.endIndex } public func index(after i: Int) -> Int { guard i != endIndex else { fatalError("Cannot increment endIndex") } return keyStorage.index(after: i) } /** - returns: Value at the given `index`. Will crash if index out-of-range. */ public subscript (index: Int) -> (Key,Value) { let key = keyStorage[index] guard let value = values[key] else { fatalError("Values not stored correctly") } return (key, value) } }
// // SecondViewController.swift // FinalProject // // Created by Van Simmons on 6/5/17. // Copyright © 2017 Harvard University. All rights reserved. // import UIKit class StatisticsViewController: UIViewController { @IBOutlet weak var aliveValue: UILabel! @IBOutlet weak var bornValue: UILabel! @IBOutlet weak var emptyValue: UILabel! @IBOutlet weak var diedValue: UILabel! var aliveCount: Int = 0 var bornCount: Int = 0 var emptyCount: Int = 0 var diedCount: Int = 0 override func viewDidLoad() { super.viewDidLoad() self.aliveValue.text = "0" self.bornValue.text = "0" self.emptyValue.text = "0" self.diedValue.text = "0" let nc = NotificationCenter.default nc.addObserver(self, selector: #selector(updateStats(notified:)), name: GridChangeNoticationName, object: nil) nc.addObserver(self, selector: #selector(resetStats(notified:)), name: GridResetNoticationName, object: nil) } @objc func gridEditorExtractor(){ let size = StandardEngine.onlyInstance.rows let totalPositions = positionSequence(from: (row:0, col:0), to: (row: size, col: size)) totalPositions.forEach{ pos in switch StandardEngine.onlyInstance.grid[pos.row, pos.col]{ case .alive: self.aliveCount += 1 case .born: self.bornCount += 1 case .empty: self.emptyCount += 1 case .died: self.diedCount += 1 } } } @objc func updateStats(notified: Notification){ self.gridEditorExtractor() self.aliveValue.text = "\(aliveCount)" self.bornValue.text = "\(bornCount)" self.emptyValue.text = "\(emptyCount)" self.diedValue.text = "\(diedCount)" } @objc func resetStats(notified: Notification){ self.aliveValue.text = "0" self.bornValue.text = "0" self.emptyValue.text = "0" self.diedValue.text = "0" self.aliveCount = 0 self.bornCount = 0 self.emptyCount = 0 self.diedCount = 0 } }
// // MessageError.swift // // // Created by Paul Schmiedmayer on 2/15/21. // /** Describing an `Error` that can occur when decoding `Message`s from a `ByteBuffer`. */ enum MessageError: Error, Equatable { /** Thrown if there is an error when decoding a LIFX `Message` due to a faulty formatted `Message`. */ case messageFormat /** Thrown if a `Message` type is unknown when decoding a `Message`. */ case unknownMessageType /** Thrown if a `Message` type is targeted for a `Device`. Messages to `Device`s are ignored and throw this error that can be used to log the message as this libary is a client implementation of the LIFX protocol. */ case deviceMessageType }
// // TagsViewController.swift // WebScraper // // Created by RSQ Technologies on 04/05/2019. // Copyright © 2019 RSQ Technologies. All rights reserved. // import UIKit class TagsViewController: UIViewController { @IBOutlet weak var tagsTableView: UITableView! let dataSource = TagsDataSource() var output: TagsViewInteractor? override func viewDidLoad() { super.viewDidLoad() TagsViewConfigurator.sharedInstance.configure(controller: self) self.navigationController?.isNavigationBarHidden = false dataSource.delegate = self tagsTableView.dataSource = dataSource tagsTableView.delegate = dataSource tagsTableView.register(UINib(nibName: String(describing: TagCell.self), bundle: nil), forCellReuseIdentifier: "TagCell") tagsTableView.register(UINib(nibName: String(describing: TagFooter.self), bundle: nil), forHeaderFooterViewReuseIdentifier: "TagFooter") output?.getTags() } func presentTags(_ tags: [String]) { dataSource.tags = tags tagsTableView.reloadData() } func displaySuccess() { NaviRouter.shared.popViewController() } @IBAction func saveButtonPressed(_ sender: Any) { output?.updateTags(dataSource.tags) } }
// // QuestionViewModel.swift // Croesus // // Created by Ian Wanyoike on 03/02/2020. // Copyright © 2020 Pocket Pot. All rights reserved. // import RxSwift import RxCocoa enum ControlType: String { case radio case text } class QuestionViewModel { private var question: QuestionType let id: String let title: BehaviorRelay<String> let label: BehaviorRelay<String> let type: BehaviorRelay<ControlType?> let answer: BehaviorRelay<String?> let options: BehaviorRelay<[String]> let skipRules: [SkipRule] let selectedOptionIndex: BehaviorRelay<Int> lazy var disposeBag = DisposeBag() init(question: QuestionType, surveyViewModel: SurveyViewModel) { self.question = question self.id = question.id self.title = BehaviorRelay(value: question.title) self.label = BehaviorRelay(value: question.label) self.type = BehaviorRelay(value: ControlType(rawValue: question.type)) let options = question.options ?? [] self.options = BehaviorRelay(value: options) self.skipRules = question.skipRules ?? [] let selectedOptionIndex: Int if self.type.value == .some(.radio), let answer = question.answer { selectedOptionIndex = options.firstIndex(of: answer) ?? 0 } else { selectedOptionIndex = 0 } self.selectedOptionIndex = BehaviorRelay(value: selectedOptionIndex) self.answer = BehaviorRelay( value: question.answer ?? (options.isEmpty ? nil : options[selectedOptionIndex]) ) self.selectedOptionIndex.bind { [weak self] index in guard let `self` = self, index < self.options.value.count else { return } self.answer.accept(self.options.value[index]) }.disposed(by: self.disposeBag) self.answer.bind { [weak self] answer in guard let `self` = self else { return } self.question.answer = answer surveyViewModel.questionPersistor .save(element: self.question) .subscribe().disposed(by: self.disposeBag) guard self.type.value == .some(.radio), !self.skipRules.isEmpty else { return } var questionsToSkip = surveyViewModel.questionsToSkip.value defer { surveyViewModel.questionsToSkip.accept(questionsToSkip) } let skipRules = self.skipRules.filter { $0.answer != answer } skipRules.forEach { questionsToSkip.subtract($0.skip) } guard let skipRule = self.skipRules.first(where: { $0.answer == answer }) else { return } questionsToSkip.formUnion(skipRule.skip) }.disposed(by: self.disposeBag) } } extension QuestionViewModel: Hashable { static func == (lhs: QuestionViewModel, rhs: QuestionViewModel) -> Bool { lhs.id == rhs.id } func hash(into hasher: inout Hasher) { hasher.combine(self.id) } }
// // SearchDetailsViewController.swift // OMDBAPI // // Created by Piyush on 6/3/20. // Copyright © 2020 Piyush Kandrikar. All rights reserved. // import UIKit import SafariServices class SearchDetailsViewController: UIViewController { //************************************************** //MARK: - Properties //************************************************** var name: String? var posterURL: String? var movieID: String? var movieDetails: MovieDetails? @IBOutlet weak var label_name: UILabel! @IBOutlet weak var movie_poster: UIImageView! @IBOutlet weak var view_imgHolder: UIView! @IBOutlet weak var view_gradient: UIView! @IBOutlet weak var label_year: UILabel! @IBOutlet weak var label_time: UILabel! @IBOutlet weak var label_genre: UILabel! @IBOutlet weak var label_synopsis: UILabel! @IBOutlet weak var label_score: UILabel! @IBOutlet weak var label_reviews: UILabel! @IBOutlet weak var label_popularity: UILabel! @IBOutlet weak var label_director: UILabel! @IBOutlet weak var label_writer: UILabel! @IBOutlet weak var label_actors: UILabel! var loadingView:UIActivityIndicatorView? lazy var viewModel = MovieDetailsViewModel() //************************************************** //MARK: - Constants //************************************************** enum Constants { } //************************************************** //MARK: - Methods //************************************************** override func viewDidLoad() { super.viewDidLoad() initialse() } func initialse(){ self.title = "Movie details" addLoadingView() if let name = name { label_name.text = name.capitalized } getMovieDetails() } func getMovieDetails(){ if let id = movieID { viewModel.getDetails(movieID: id) { (data, response, error) in if error == nil { self.movieDetails = data DispatchQueue.main.async { self.plotScreen() } } } } } func plotScreen() { guard let movieDetails = self.movieDetails else { return } Utility.addGradientToView(view_gradient) if let posterURL = movieDetails.poster { Utility.getImageFromURlString(posterURL, completion: { (img) in if let img = img { DispatchQueue.main.async { self.movie_poster.image = img self.movie_poster.backgroundColor = UIColor.black self.movie_poster.contentMode = .scaleAspectFill } } }) } label_year.text = movieDetails.year ?? "NA" label_time.text = movieDetails.runtime ?? "NA" label_genre.text = movieDetails.genre ?? "NA" label_synopsis.text = movieDetails.plot ?? "NA" label_score.text = movieDetails.metascore ?? "NA" label_reviews.text = movieDetails.imdbVotes ?? "NA" label_popularity.text = movieDetails.imdbRating ?? "NA" label_director.text = movieDetails.director ?? "NA" label_writer.text = movieDetails.writer ?? "NA" label_actors.text = movieDetails.actors ?? "NA" if let loadingView = self.loadingView { loadingView.stopAnimating() loadingView.removeFromSuperview() } } func addLoadingView() { loadingView = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height)) if let loadingView = loadingView { loadingView.backgroundColor = UIColor.black; loadingView.startAnimating() self.view.addSubview(loadingView) } } }
// // ViewController.swift // CollectionViewCompositionalLayoutPractice // // Created by mac on 2021/04/18. // import UIKit class ViewController: UIViewController { lazy var collectionView = UICollectionView(frame: .zero, collectionViewLayout: ViewController.createLayout()) let flowLayout = UICollectionViewFlowLayout() override func viewDidLoad() { super.viewDidLoad() setupUI() } func setupUI() { // flowLayout.sectionInset = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5) // flowLayout.scrollDirection = .vertical // flowLayout.itemSize = CGSize(width: <#T##CGFloat#>, height: <#T##CGFloat#>) // flowLayout.minimumLineSpacing = 1 // flowLayout.minimumInteritemSpacing = 1 collectionView.frame = view.bounds collectionView.dataSource = self collectionView.delegate = self collectionView.register(MyCustomCollectionCellCollectionViewCell.self, forCellWithReuseIdentifier: MyCustomCollectionCellCollectionViewCell.identifier) collectionView.backgroundColor = .white view.addSubview(collectionView) } static func createLayout() -> UICollectionViewCompositionalLayout { //Item let item = NSCollectionLayoutItem( layoutSize: NSCollectionLayoutSize( widthDimension: .fractionalWidth(2/3), heightDimension: .fractionalHeight(1))) item.contentInsets = NSDirectionalEdgeInsets(top: 5, leading: 5, bottom: 5, trailing: 5) let verticalStackItem = NSCollectionLayoutItem(layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .fractionalHeight(0.5))) verticalStackItem.contentInsets = NSDirectionalEdgeInsets(top: 5, leading: 5, bottom: 5, trailing: 5) //Group let verticalStackGroup = NSCollectionLayoutGroup.vertical(layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1/3), heightDimension: .fractionalHeight(1)), subitem: verticalStackItem, count: 2) let group = NSCollectionLayoutGroup.horizontal(layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .fractionalHeight(3/5)), subitems: [ item, verticalStackGroup ]) //Sections let section = NSCollectionLayoutSection(group: group) //Returns return UICollectionViewCompositionalLayout(section: section) } } //MARK: - CollectionView extension ViewController: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 30 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: MyCustomCollectionCellCollectionViewCell.identifier, for: indexPath) as! MyCustomCollectionCellCollectionViewCell return cell } // func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { // return CGSize(width: (view.frame.size.width / 3) - 4, height: view.frame.size.width / 2) // } }
// // TamGiac.swift // ChuaBaiTapBuoi2 // // Created by Taof on 1/2/20. // Copyright © 2020 Taof. All rights reserved. // import Foundation //Nhập 3 giá trị nguyên dương a, b, c. Kiểm tra xem a, b, c có phải là 3 cạnh của tam giác không? //- Nếu là 3 cạnh của tam giác thì tính diện tích của tam giác. //- Nếu không phải là tam giác in ra “a, b, c không phải là 3 cạnh của tam giác” // cách làm của anh Huy func tamGiac(a: Float, b: Float ,c: Float){ if a + b <= c || a + b == c { print("3 canh \(a), \(b), \(c) khong tao thanh 1 tam giac") } else{ if a + c <= b || a + c == b { print("3 canh \(a), \(b), \(c) khong tao thanh 1 tam giac") } else { if b + c <= a || b + c == a { print("3 canh \(a), \(b), \(c) khong tao thanh 1 tam giac") } else{ print("3 canh \(a), \(b), \(c) co the tao thanh 1 tam giac") let p: Float = Float((a + b + c) / 2) let s: Float = Float(sqrt(p * (p - a) * (p - b) * (p - c))) print("Dien tich tam giac duoc tao thanh tu 3 canh \(a), \(b), \(c) la: \(s)") } } } } // cách2 làm bài tam giác func tamGiac2(a: Float, b: Float, c: Float){ if a + b > c && b + c > a && a + c > b { let p: Float = Float((a + b + c) / 2) let s: Float = Float(sqrt(p * (p - a) * (p - b) * (p - c))) print("Dien tich tam giac duoc tao thanh tu 3 canh \(a), \(b), \(c) la: \(s)") }else{ print("3 cạnh \(a), \(b), \(c) không tạo thành một tam giác") } }
// // PublicMethods.swift // SEngage // // Created by Yan Wu on 4/14/16. // Copyright © 2016 Avaya. All rights reserved. // import UIKit class PublicMethods { // Scopia static func makeScopiaHttpLink(extensionStr:String)->String?{ if(extensionStr.characters.count>4){ if(extensionStr[extensionStr.startIndex] == "+"){ return PublicStrings.SCOPIA_PREFIX_HTTP + extensionStr.substringFromIndex(extensionStr.startIndex.advancedBy(1)) }else{ return PublicStrings.SCOPIA_PREFIX_HTTP + extensionStr } }else{ return nil } } static func makeScopiaLink(extensionStr:String)->String?{ if(extensionStr.characters.count>4){ if(extensionStr[extensionStr.startIndex] == "+"){ return PublicStrings.SCOPIA_PREFIX + extensionStr.substringFromIndex(extensionStr.startIndex.advancedBy(1)) }else{ return PublicStrings.SCOPIA_PREFIX + extensionStr } }else{ return nil } } static func enterScopiaRoomWithExtension(extensionStr:String) { // Process the extension string first var scopiaLink:String = ""; var httpLink:String = "" if(extensionStr.characters.count>4){ if(extensionStr[extensionStr.startIndex] == "+"){ scopiaLink = PublicStrings.SCOPIA_PREFIX + extensionStr.substringFromIndex(extensionStr.startIndex.advancedBy(1)) httpLink = PublicStrings.SCOPIA_PREFIX_HTTP + extensionStr.substringFromIndex(extensionStr.startIndex.advancedBy(1)) }else{ scopiaLink = PublicStrings.SCOPIA_PREFIX + extensionStr httpLink = PublicStrings.SCOPIA_PREFIX_HTTP + extensionStr } }else{ scopiaLink = PublicStrings.SCOPIA_PREFIX httpLink = PublicStrings.SCOPIA_PREFIX_HTTP } if (UIApplication.sharedApplication().canOpenURL(NSURL(string: scopiaLink)!)){ UIApplication.sharedApplication().openURL(NSURL(string: scopiaLink)!) } else{ UIApplication.sharedApplication().openURL(NSURL(string: httpLink)!) } } static func enterScopiaRoomWithMeetingId(meetingId:String) { let linkStr = PublicStrings.SCOPIA_PREFIX_HTTP_FORWARD + meetingId; enterScopiaRoomWithHttpLink(linkStr) } static func enterScopiaRoomWithHttpLink(linkStr:String) { if(linkStr.characters.count > 4){ let scopiaLink:String = "scopia:" + linkStr; if(UIApplication.sharedApplication().canOpenURL(NSURL(string: scopiaLink)!)){ UIApplication.sharedApplication().openURL(NSURL(string: scopiaLink)!) }else{ UIApplication.sharedApplication().openURL(NSURL(string: linkStr)!) } } } // }
// // DCAlarmManager.swift // Demo_Clock // // Created by luxiaoming on 16/1/21. // Copyright © 2016年 luxiaoming. All rights reserved. // import UIKit class DCAlarmManager { var alarmArray: [DCAlarm] static let sharedInstance = DCAlarmManager() private let kDCAlarmArraySavedKey = "kDCAlarmArraySavedKey" fileprivate init() { if let alarmArrayData = kLXMUserDefaults.object(forKey: kDCAlarmArraySavedKey) as? Data, let tempArray = NSKeyedUnarchiver.unarchiveObject(with: alarmArrayData) as? [DCAlarm] { alarmArray = tempArray } else { alarmArray = [DCAlarm]() } } func save() { let alarmArrayData = NSKeyedArchiver.archivedData(withRootObject: self.alarmArray) kLXMUserDefaults.set(alarmArrayData, forKey: kDCAlarmArraySavedKey) kLXMUserDefaults.synchronize() } }
// // ValidationError.swift // MyProject // // Created by username on 28/09/16. // Copyright © 2016 BCA. All rights reserved. // import Foundation import UIKit public class ValidationError: NSObject { /// the Validatable field of the field public let field:ValidatableField /// the error label of the field public var errorLabel:UILabel? /// the error message of the field public let errorMessage:String /** Initializes `ValidationError` object with a field, errorLabel, and errorMessage. - parameter field: Validatable field that holds field. - parameter errorLabel: UILabel that holds error label. - parameter errorMessage: String that holds error message. - returns: An initialized object, or nil if an object could not be created for some reason that would not result in an exception. */ public init(field:ValidatableField, errorLabel:UILabel?, error:String){ self.field = field self.errorLabel = errorLabel self.errorMessage = error } }
// // AgendaViewController.swift // K-Forum 2020 // // Created by Rafael Montoya on 10/29/19. // Copyright © 2019 Administra Servicios Integrales. All rights reserved. // import UIKit import FirebaseFirestore class AgendaViewController: UIViewController { var db: Firestore! var nombreReporteBD = "" var array: [Agenda] = [] var arrayDia2: [Agenda] = [] var arrayAcompananteDia1: [Agenda] = [] var arrayAcompananteDia2: [Agenda] = [] var secciones: [String] = ["Day 1 | November 14th", "Day 2 | November 15th"] var sectionData: [Int:[Agenda]] = [:] let coleccion = "agenda" var itemSeleccionado: Agenda = Agenda() @IBOutlet weak var tableView: UITableView! @IBOutlet weak var scSegment: UISegmentedControl! @IBAction func scSegmentTapped(_ sender: Any) { print(scSegment.selectedSegmentIndex) if(scSegment.selectedSegmentIndex==1){ setInfoAcompanante() } if(scSegment.selectedSegmentIndex==0){ setInfoParticipante() } } override func viewDidLoad() { super.viewDidLoad() let settings = FirestoreSettings() nombreReporteBD = ""; Firestore.firestore().settings = settings // [END setup] db = Firestore.firestore() tableView.delegate = self tableView.dataSource = self getInfoParticipante() getInfoAcompanante() } func getInfoAcompanante(){ db.collection(coleccion).order(by: "orden").addSnapshotListener(){(querySnapshot, err) in if let err = err{ print("Error obteniendo documentos \(err)") }else{ self.arrayAcompananteDia1=[] self.arrayAcompananteDia2=[] for document in querySnapshot!.documents{ let seleccionado = Agenda() if(document.data()["participante"]as? Int == 2){ if let hora = document.data()["hora"]as? String{ seleccionado.hora = hora } if let evento = document.data()["evento"]as? String{ seleccionado.evento = evento } if(document.data()["dia"]as? Int == 1){ self.arrayAcompananteDia1.append(seleccionado) }else{ self.arrayAcompananteDia2.append(seleccionado) } } } self.setInfoParticipante() } } } func getInfoParticipante(){ db.collection(coleccion).order(by: "orden").addSnapshotListener(){(querySnapshot, err) in if let err = err{ print("Error obteniendo documentos \(err)") }else{ self.array=[] self.arrayDia2=[] for document in querySnapshot!.documents{ let seleccionado = Agenda() if(document.data()["participante"]as? Int == 1){ seleccionado.id = document.documentID if let hora = document.data()["hora"]as? String{ seleccionado.hora = hora } if let evento = document.data()["evento"]as? String{ seleccionado.evento = evento } if let abre = document.data()["abrir"]as? Int{ seleccionado.abre = abre } if(document.data()["dia"]as? Int == 1){ self.array.append(seleccionado) }else{ self.arrayDia2.append(seleccionado) } } } self.setInfoParticipante() } } setInfoParticipante() } func setInfoParticipante(){ sectionData = [0:array,1:arrayDia2] tableView.reloadData() } func setInfoAcompanante(){ sectionData = [0:arrayAcompananteDia1,1:arrayAcompananteDia2] tableView.reloadData() } } extension AgendaViewController: UITableViewDelegate, UITableViewDataSource{ func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return (sectionData[section]?.count)! } func numberOfSections(in tableView: UITableView) -> Int { return secciones.count } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let view = UIView() view.backgroundColor = UIColor.white let label = UILabel() label.textColor = UIColor(red: CGFloat(0)/255.0, green: CGFloat(190)/255.0, blue: CGFloat(214)/255.0, alpha: 1.0) label.text = secciones[section] label.frame = CGRect(x: 45, y: 0, width: 300, height: 35) view.frame.size.height = 100 view.frame = CGRect(x: 0, y: 0, width: 0, height: 0) view.addSubview(label) return view } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = self.tableView.dequeueReusableCell(withIdentifier: "cell") as! AgendaTableViewCell let bgColorView = UIView() bgColorView.backgroundColor = UIColor.white cell.selectedBackgroundView = bgColorView cell.agregarCelda(agenda:sectionData[indexPath.section]![indexPath.row]) return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { self.itemSeleccionado = sectionData[indexPath.section]![indexPath.row] if(sectionData[indexPath.section]![indexPath.row].abre == 1){ performSegue(withIdentifier: "detalleSG", sender: self) } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let receiver = segue.destination as! DetalleAgendaViewController receiver.seleccionado = self.itemSeleccionado } }
// // ABC.swift // ABCProduct // // Created by Gw on 08/11/17. // Copyright © 2017 Gw. All rights reserved. // import Foundation class ABC { var title: String = "" var nomor_sertifikat:String = "" var produsen:String = "" var berlaku_hingga:String = "" }
// // WelcomeCoordinator.swift // macro-tracker // // Created by Felix on 2020-03-09. // Copyright © 2020 Felix. All rights reserved. // import UIKit protocol BackToMainViewControllerDelegate: AnyObject { func navigateToMainFlow() } class WelcomeCoordinator: Coordinator { var childCoordinators: [Coordinator] = [] private let navigationController: UINavigationController weak var delegate: BackToMainViewControllerDelegate? private var firstPageViewController: FirstPageViewController? private var secondPageViewController: SecondPageViewController? private var thirdPageViewController: ThirdPageViewController? private var fourthPageViewController: FourthPageViewController? private var pageViewController: MTPageViewController? init(_ navigationController: UINavigationController) { navigationController.setNavigationBarHidden(true, animated: false) self.navigationController = navigationController } func start() { let firstPageViewController = FirstPageViewController() firstPageViewController.delegate = self self.firstPageViewController = firstPageViewController let secondPageViewController = SecondPageViewController() secondPageViewController.delegate = self self.secondPageViewController = secondPageViewController let thirdPageViewController = ThirdPageViewController() thirdPageViewController.delegate = self self.thirdPageViewController = thirdPageViewController let fourthPageViewController = FourthPageViewController() fourthPageViewController.delegate = self self.fourthPageViewController = fourthPageViewController let pageViewController = MTPageViewController(pages: [firstPageViewController, secondPageViewController, thirdPageViewController, fourthPageViewController]) self.pageViewController = pageViewController navigationController.pushViewController(pageViewController, animated: false) } } extension WelcomeCoordinator: FirstPageViewControllerDelegate { func goToSecondPage() { if let secondPage = pageViewController?.pages[1] { pageViewController?.setViewControllers([secondPage], direction: .forward, animated: true, completion: nil) } } } extension WelcomeCoordinator: SecondPageViewControllerDelegate {} extension WelcomeCoordinator: ThirdPageViewControllerDelegate {} extension WelcomeCoordinator: FourthPageViewControllerDelegate { func userPressedGetStarted() { UserDefaults.standard.set(true, forKey: "alreadyLaunched") delegate?.navigateToMainFlow() } }
// // AlamofireRouterMethod.swift // ios_mvvm // // Created by prongbang on 28/7/2561 BE. // Copyright © 2561 prongbang. All rights reserved. // import Foundation import Alamofire extension AlamofireRouter { public var method: Alamofire.HTTPMethod { switch self { // Login case .login: return .post case .forgotPassword: return .post case .register: return .post // Logout case .logout: return .post // Profile case .getUserProfile: return .get // Todo case .todos: return .get } } }
// // BillboardCollectionViewCell.swift // VIBE // // Created by 조민호 on 2020/07/19. // Copyright © 2020 Jerry Jung. All rights reserved. // import UIKit class BillboardCollectionViewCell: UICollectionViewCell { @IBOutlet weak var BillImageView: UIImageView! @IBOutlet weak var BillRankLabel: UILabel! @IBOutlet weak var BillTitleLabel: UILabel! @IBOutlet weak var BillSubTitleLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } }
// // String+LeetCode.swift // LeetCode // // Created by Lex Tang on 5/5/15. // Copyright (c) 2015 Lex Tang. All rights reserved. // import Foundation extension String { subscript (i: Int) -> Character? { if i > count(self) - 1 { return .None } var index: Index = advance(self.startIndex, i) return self[index] } mutating func popBack() -> String { self.removeAtIndex(advance(self.startIndex, count(self) - 1)) return self } }
// // InfoView.swift // Slot Machine // // Created by Jaime Uribe on 15/12/20. // import SwiftUI struct InfoView: View { @Environment(\.presentationMode) var presentationMode var body: some View { VStack(alignment: .center, spacing: 10) { LogoView() Spacer() Form{ Section(header: Text("About the application")){ FormRowView(firstItem: "Application", secoundItem: "Slot Machine") FormRowView(firstItem: "Plataform", secoundItem: "iPhone, iPad, mac") FormRowView(firstItem: "Developer", secoundItem: "Jaime Uribe") FormRowView(firstItem: "Designer", secoundItem: "Robert Petras") FormRowView(firstItem: "Website", secoundItem: "www.udemy.com") FormRowView(firstItem: "Copyright ", secoundItem: "@ 2020 al right reserved.") FormRowView(firstItem: "Version", secoundItem: "1.0.0") } } .font(.system(.body, design: .rounded)) } .padding(.top, 40) .overlay( Button(action: { self.presentationMode.wrappedValue.dismiss() }){ Image(systemName: "xmark.circle") .font(.title) } .padding(.top, 20) .padding(.trailing, 20) .accentColor(Color.secondary) , alignment: .topTrailing ) } } struct FormRowView: View { var firstItem: String var secoundItem: String var body: some View { HStack{ Text(firstItem).foregroundColor(Color.gray) Spacer() Text(secoundItem) } } } struct InfoView_Previews: PreviewProvider { static var previews: some View { InfoView() } }
// // ViewController.swift // liw // // Created by donedeal-Stephenw on 01/25/2018. // Copyright (c) 2018 donedeal-Stephenw. All rights reserved. // import UIKit import liw class ViewController: UIViewController { @IBOutlet weak var pendingContentLabel: LIWPendingContentLabel! @IBAction func didTapReadyButton(sender: Any?) { self.pendingContentLabel.update(with: "Sample Text") } @IBAction func didTapPendingButton(sneder: Any?) { self.pendingContentLabel.state = LIWPendingContent.ContentState.pending } }
// // TestAViewController.swift // CMYKitDemo // // Created by  MarvinChan on 2019/3/28. // Copyright © 2019  MarvinChan. All rights reserved. // import UIKit class TestAViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let button = UIButton(type: .custom) button.frame = CGRect(x: 50, y: 100, width: 100, height: 60) button.backgroundColor = .orange button.addTarget(self, action: #selector(clickAction), for: .touchUpInside) view.addSubview(button) } @objc func clickAction() { if let controller = CMYRouter.shared.CMYRouter_viewControllerForTestB("测试B") { self.navigationController?.show(controller, sender: nil) } } }
// // ViewController.swift // Quiz // // Created by Arvind Mishra on 21/03/18. // Copyright © 2018 Arvind Mishra. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet var questionLabel: UILabel! @IBOutlet var answerLabel: UILabel! let questions = [ "Where was Rojer Fereder born in Switzerland?", "Rojer Fereder right Handed or left Handed?", "Which is the least grandslam won by federer?", "Which is the most win grandslam by federer?", "In Which year did Roger won his 1000th Win?" ] let answers = [ "Basel, Switzerland", "Right Handed", "French Open", "Wimbeldon", "2015" ] var currentQuestionIndex = 0 @IBAction func showNextQuestion(_ sender: UIButton) { currentQuestionIndex += 1 if currentQuestionIndex == questions.count { currentQuestionIndex = 0 } let question = questions[currentQuestionIndex] questionLabel.text = question answerLabel.text = "???" } @IBAction func showAnswer(_ sender: UIButton) { let answer = answers[currentQuestionIndex] answerLabel.text = answer } override func viewDidLoad() { super.viewDidLoad() questionLabel.text = questions[currentQuestionIndex] } @IBAction func exit(_ sender: UIButton) { Darwin.exit(0) } }
// // SellerSoldProductsVM.swift // MyLoqta // // Created by Shivansh Jaitly on 8/10/18. // Copyright © 2018 AppVenturez. All rights reserved. // import UIKit import SwiftyUserDefaults protocol SellerSoldProductsVModeling: class { func requestGetSellerSoldOrdersList(page: Int, isShowLoader: Bool, completion: @escaping (_ productList: [Product], _ count: Int) ->Void) } class SellerSoldProductsVM: BaseModeling, SellerSoldProductsVModeling { //MARK: - API Methods func requestGetSellerSoldOrdersList(page: Int, isShowLoader: Bool, completion: @escaping (_ productList: [Product], _ count: Int) ->Void) { let sellerId = Defaults[.sellerId] let params = ["sellerId": sellerId as AnyObject, "page": page as AnyObject] self.apiManagerInstance()?.request(apiRouter: APIRouter(endpoint: .SellerSoldOrders(param: params, isShowLoader: isShowLoader)), completionHandler: { (response, success) in if success, let data = response as? [String: AnyObject], let newResponse = data["orders"] as? [[String: AnyObject]], let orderCount = data["orderCount"] as? Int { if let productList = Product.formattedArray(data: newResponse) { completion(productList, orderCount) } } }) } }
// // ViewModelFavorites.swift // AliveCor // // Created by Sandeep Rana on 02/12/20. // import UIKit import CoreData class ViewModelFavorites { var results:[Movie] = [Movie]() var delegate:FavoriteViewModelDelegate? init(delegate:FavoriteViewModelDelegate) { self.delegate = delegate; self.loadDataFromLocalDatabase(); } func loadDataFromLocalDatabase() { self.results.removeAll() let context = AppDelegate.getAppDelegate().getContext(); let request:NSFetchRequest<Favorite> = Favorite.fetchRequest() do { let fet = try context.fetch(request); fet.forEach({ (favorite) in let movie = Movie( backdrop_path: nil, genre_ids: nil, original_language: nil, original_title: nil, poster_path: favorite.poster_cover, vote_count: nil, video: nil, vote_average: nil, title: favorite.title, overview: nil, release_date: nil, id: favorite.id, popularity: nil, adult: nil) self.results.append(movie) }) self.delegate?.refreshDataSource() }catch let error { print(error) } } func getMovieFor(index:Int) -> Movie? { return self.results[index] } func numberOfRows() -> Int { return self.results.count } }
// // FavoriteSongTableViewCell.swift // Shyrqa // // Created by Алпамыс on 24.07.17. // Copyright © 2017 Алпамыс. All rights reserved. // import UIKit import RealmSwift class FavoriteSongTableViewCell: UITableViewCell { let realm = try! Realm() var songTitle = "" var songLyrics = "" @IBOutlet weak var songImageView: UIImageView! @IBOutlet weak var favoriteSongNameLabel: UILabel! @IBOutlet weak var favoriteSongAuthorLabel: UILabel! @IBOutlet weak var shadowView: UIView! @IBOutlet weak var myView: UIView! override func awakeFromNib() { super.awakeFromNib() selectionStyle = .none songImageView.layer.borderWidth = 1 songImageView.layer.borderColor = UIColor.lightGray.cgColor layer.backgroundColor = UIColor.clear.cgColor myView.layer.borderWidth = 1 myView.layer.borderColor = UIColor.lightGray.cgColor shadowView.layer.shadowColor = UIColor.black.cgColor shadowView.layer.shadowOpacity = 0.2 shadowView.layer.shadowOffset = CGSize.init(width: 7, height: 7) shadowView.layer.shadowRadius = 7 shadowView.layer.shadowPath = UIBezierPath(rect: shadowView.bounds.offsetBy(dx: 7, dy: 7)).cgPath // Initialization code } }
// @copyright German Autolabs Assignment import Foundation enum VoiceCommand { case weather(city: String?, date: Date?) } protocol TranscriptionParser { func parse(transcription: String) -> VoiceCommand? }
// // TodoVC.swift // TODO // // Created by Marcin Jucha on 09.05.2017. // Copyright © 2017 Marcin Jucha. All rights reserved. // import UIKit class TodoDetailsVC: UIViewController { @IBOutlet weak var titleTextField: UITextField! @IBOutlet weak var segmentType: UISegmentedControl! @IBOutlet weak var tableView: UITableView! @IBOutlet weak var textView: UITextView! @IBOutlet weak var favoriteImg: UIImageView! @IBOutlet weak var completedImg: UIImageView! @IBOutlet weak var typeStackView: UIStackView! @IBOutlet weak var categoryStackView: UIStackView! @IBOutlet weak var categoryLbl: UILabel! var task: Task! fileprivate var _subtasks: [Subtask] { return (task.subtasks?.array as? [Subtask]) ?? [] } override func viewDidLoad() { super.viewDidLoad() initializeOutlets() tableView.setProperties(self) tableView.register(TodoListItemCell.self) tableView.register(TodoListItemAddCell.self) titleTextField.delegate = self } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) task.text = textView.text for subtask in _subtasks { if subtask.name == nil || subtask.name!.isEmpty { subtaskManager.delete(subtask) } } task.type = segmentType.selectedSegmentIndex.int64 saveChanges() } fileprivate func setGestures() { var tap = UITapGestureRecognizer(target: self, action: #selector(self.hideKeyboard)) view.addGestureRecognizer(tap) tap = UITapGestureRecognizer(target: self, action: #selector(self.showCategories)) categoryStackView.addGestureRecognizer(tap) } fileprivate func setCategoires() { let view = categoryStackView.arrangedSubviews.first! for arrangedView in categoryStackView.arrangedSubviews { if !arrangedView.isEqual(view) { categoryStackView.removeArrangedSubview(arrangedView) } } if let categoires = task.categories?.array as? [Category], categoires.count > 0 { categoryLbl.isHidden = true for cat in categoires { let font = categoryLbl.font let label = UILabel() label.text = cat.name label.font = font! categoryStackView.addArrangedSubview(label) } } else { categoryLbl.isHidden = false } } func showCategories() { if let vc = UIStoryboard.createTaskCategoryVC() as? TaskCategoryVC { vc.task = task vc.selectedCategoriesHandler = { self.setCategoires() } presentModalViewController(viewController: vc) { vc.backgroundView.alpha = 0.3 } } } func hideKeyboard() { view.endTextEditing() } @IBAction func changeTodoType(_ sender: Any) { if segmentType.selectedSegmentIndex == 0 { textView.isHidden = false tableView.isHidden = true } else { textView.isHidden = true tableView.isHidden = false } } @IBAction func changeFavorite(_ sender: Any) { task.favorite = !task.favorite favoriteImg.image = task.getFavoriteImage() } @IBAction func taskCompleted(_ sender: Any) { updateCompletedImg(!task.completed) } fileprivate func updateCompletedImg(_ flag: Bool) { task.completed = flag completedImg.image = task.getCompletedImage() } } // **************************************** // MARK: Table View // **************************************** extension TodoDetailsVC: UITableViewDataSource, UITableViewDelegate { private var numberOfNotCompletedSubtasks: Int { return _subtasks.filter({ $0.completed == false }).count + 1 } private var numberOfCompletedSubtasks: Int { return _subtasks.filter({ $0.completed == true }).count } private var listOfNotCompletedSubtasks: [Subtask] { return _subtasks.filter() { $0.completed == false } } private var listOfCompletedSubtasks: [Subtask] { return _subtasks.filter() { $0.completed == true } } func numberOfSections(in tableView: UITableView) -> Int { if numberOfCompletedSubtasks == 0 { return 1 } else { return 2 } } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 0 { return numberOfNotCompletedSubtasks } else { return numberOfCompletedSubtasks } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.section == 0 { return cellForZeroSection(tableView, forIndex: indexPath) } else { return todoListItemCell(tableView, forIndex: indexPath) } } private func cellForZeroSection(_ tableView: UITableView, forIndex indexPath: IndexPath) -> UITableViewCell { if numberOfNotCompletedSubtasks - 1 == indexPath.row { return todoListItemAddCell(tableView, forIndex: indexPath) } else { return todoListItemCell(tableView, forIndex: indexPath) } } private func todoListItemAddCell(_ tableView: UITableView, forIndex indexPath: IndexPath) -> TodoListItemAddCell { let cell = tableView.dequeueReusableCell(forIndex: indexPath) as TodoListItemAddCell cell.configureCell { self.insertSubtask() } return cell } private func insertSubtask() { let subtask = createSubtask() task.addToSubtasks(subtask) updateCompletedImg(false) let count = numberOfNotCompletedSubtasks - 2 tableView.insertRows(at: [IndexPath(row: count, section: 0)], with: .fade) } private func todoListItemCell(_ tableView: UITableView, forIndex indexPath: IndexPath) -> TodoListItemCell { let cell = tableView.dequeueReusableCell(forIndex: indexPath) as TodoListItemCell let item = getTodoItemList(indexPath) cell.configureCell(item) { [weak self] in self?.presentTextViewController(item) } cell.checkboxHandler = { [weak self] in self?.subtaskCheckboxHandler(item) } return cell } private func getTodoItemList(_ indexPath: IndexPath) -> Subtask { if indexPath.section == 0 { return listOfNotCompletedSubtasks[indexPath.row] } else { return listOfCompletedSubtasks[indexPath.row] } } private func subtaskCheckboxHandler(_ item: Subtask) { item.completed = !item.completed tableView.reloadData() if !task.completed && (_subtasks.filter() { $0.completed == false }).count == 0 { updateCompletedImg(true) } else { updateCompletedImg(false) } } private func presentTextViewController(_ item: Subtask) { let alertController = UIAlertController.createAlertWithTextField(title: "Wprowadź tekst dla zadania", text: item.name ?? "") { (text) in self.saveActionHandler(text, item) } present(alertController, animated: true, completion: nil) } private func saveActionHandler(_ text: String, _ item: Subtask) { item.name = text let row = item.completed ? listOfCompletedSubtasks.indexOfElement(element: item)! : listOfNotCompletedSubtasks.indexOfElement(element: item)! tableView.reloadRows(at: [IndexPath(row: row, section: 0)], with: .none) } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { let alert = UIAlertController.deleteAlertWithText(title: "Na pewno chcesz usunąć zadanie?") { self.deleteSubtask(indexPath) } present(alert, animated: true, completion: nil) } } func deleteSubtask(_ indexPath: IndexPath) { let item = indexPath.section == 0 ? listOfNotCompletedSubtasks[indexPath.row] : listOfCompletedSubtasks[indexPath.row] subtaskManager.delete(item) if indexPath.section == 1 && listOfCompletedSubtasks.count == 0 { tableView.reloadData() } else { tableView.deleteRows(at: [indexPath], with: .fade) } } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if section == 0 { return "Nie wykonane zadania" } else { return "Wykonane zadania" } } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 30.0 } } extension TodoDetailsVC: UITextFieldDelegate, UITextViewDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { view.endTextEditing() return false } } // **************************************** // MARK: Initialize // **************************************** fileprivate extension TodoDetailsVC { fileprivate func initializeOutlets() { setGestures() setCategoires() titleTextField.text = task.name favoriteImg.image = task.getFavoriteImage() completedImg.image = task.getCompletedImage() textView.text = task.text ?? "" if task.type == 0 { textView.isHidden = false tableView.isHidden = true segmentType.selectedSegmentIndex = 0 } else { textView.isHidden = true tableView.isHidden = false segmentType.selectedSegmentIndex = 1 } textView.lightGrayBorder() } }
//Immutable var maxValue = 900 maxValue = maxValue + 10 //Mutable //var x = 0.0, y = 0.0, z = 0.0 //A. 2.333333 //B. 2 //C. NoT let a = 7/3 print(a) typealias AudioSample = UInt16 var macAmplitudeFound = AudioSample.min print(macAmplitudeFound) let orangesAreOrange = true let turnipsAreDelicious = false if turnipsAreDelicious { print("Mmm, tasty turnips!") } else { print("Eww, turnips are horrible.") } /* In C/C++/Java - expr of type int expr is zero then it is treated false otherwise true(nonzero) if (expr) { } int x = 10; if (x) { } if (x = 1) { } if (x == 1) { } //Best Practice C/C++/Java if (1 == x) { } */ var x = 1 /* expr is Bool Type and Bool Value if else statement in Swift is Type Safe if (expr) { // expr is Bool Type and Bool Value } */ if ( x == 1 ) { print("Ding Dong") } //Tuple without Named let http404Error: (Int, String) = (404, "Not Found") //let http404Error1: (Int, Int, Int) = (404, 502) let status = http404Error.0 let message = http404Error.1 //Unpacking let (statusCode, statusMessage) = http404Error print("The status code is \(statusCode)") print("The status message is \(statusMessage)") print("The status code is \(http404Error.0)") print("The status message is \(http404Error.1)") //Far More Elegant Way of Tuple: Named Tuples let http200Status = (statusCode: 200, description: "OK") print("The status code is \(http200Status.statusCode)") print("The status message is \(http200Status.description)") print("The status code is \(http200Status.0)") print("The status message is \(http200Status.1)") let possibleNumber = "123ABC" let convertedNumber = Int(possibleNumber) if convertedNumber != nil { print("Happy World! \(convertedNumber!)") } else { print("Nothingnes...") } print("\n Idioms...1 ") if let actualNumber = Int(possibleNumber) { print("Happy World! \(actualNumber)") } else { print("Nothingnes...") } let optionalTemp = Int(possibleNumber) if optionalTemp != nil { let actualNumber = optionalTemp! print("Happy World! \(actualNumber)") } else { print("Nothingnes...") } print("\n Idioms...2 - Generated Code") print("\n Idioms...3 ") if var firstNumber = Int("4"), let secondNumber = Int("42"), firstNumber < secondNumber { firstNumber = firstNumber + 1 print("\(firstNumber) < \(secondNumber)") } else { print("Nothingnes...") } let aa: Int? = 4 let bb: Int? = nil let cc: Int? = 8 //Idomatic Style if let A = aa, let B = bb, let C = cc { print(A, B, C) } else { print("Nothingnes...") } //Vanila Style if aa != nil && bb != nil && cc != nil { let A = aa! let B = bb! let C = cc! print(A, B, C) } else { print("Nothingnes...") } let possibleString: String? = "An optional string." let possibleString1 = "An optional string." //let dingDong = nil //Do It IFF You Give Guarantee That It's Not Going to nil //In Any Scenario let forcedString: String = possibleString! //BAD PROGRAMMING PRACTICE // let assumedString: String = "An implicitly unwrapped optional string" // let assumedString: String? = "An implicitly unwrapped optional string" let assumedString: String! = "An implicitly unwrapped optional string" print(assumedString) let implicitly: String = assumedString print(implicitly)
// // Selection.swift // TaylorSource // // Created by Daniel Thorpe on 17/08/2015. // Copyright (c) 2015 Daniel Thorpe. All rights reserved. // import Foundation struct SelectionState<Item: Hashable> { var selectedItems = Set<Item>() init(initialSelection: Set<Item> = Set()) { selectedItems.unionInPlace(initialSelection) } } public class SelectionManager<Item: Hashable> { let state: Protector<SelectionState<Item>> public var allowsMultipleSelection = false public var enabled = false public var selectedItems: Set<Item> { return state.read { $0.selectedItems } } public init(initialSelection: Set<Item> = Set()) { state = Protector(SelectionState(initialSelection: initialSelection)) } public func contains(item: Item) -> Bool { return state.read { $0.selectedItems.contains(item) } } public func selectItem(item: Item, shouldRefreshItems: ((itemsToRefresh: [Item]) -> Void)? = .None) { if enabled { var itemsToUpdate = Set(arrayLiteral: item) state.write({ (inout state: SelectionState<Item>) in if state.selectedItems.contains(item) { state.selectedItems.remove(item) } else { if !self.allowsMultipleSelection { itemsToUpdate.unionInPlace(state.selectedItems) state.selectedItems.removeAll(keepCapacity: true) } state.selectedItems.insert(item) } }, completion: { shouldRefreshItems?(itemsToRefresh: Array(itemsToUpdate)) }) } } } public typealias IndexPathSelectionManager = SelectionManager<NSIndexPath>
import SwiftUI struct SignOutView: View { @EnvironmentObject var session: SessionStore func getUser() { session.listenFirebaseAuth() } var body: some View { Group { if (session.session != nil) { Text("Welcome back") Button(action: session.signOutFirebase) { Text("Sign Out") .frame(minWidth: 0, maxWidth: .infinity) .frame(height: 50) .font(.system(size: 15, weight: .bold)) } } else { SignInView() } }.onAppear(perform: getUser) } } struct ContentView_Previews: PreviewProvider { static var previews: some View { SignOutView().environmentObject(SessionStore() ) } }
// // NotificationMessageTableViewCell.swift // Spoint // // Created by kalyan on 20/11/17. // Copyright © 2017 Personal. All rights reserved. // import UIKit class NotificationMessageTableViewCell: UITableViewCell { @IBOutlet var messageLabel: UILabel! @IBOutlet var profileImage: RoundedImageView! @IBOutlet var senderLabel: UILabel! @IBOutlet var timeStampLabel:UILabel! @IBOutlet var statusIcon:UIImageView! 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 } }
// // TableViewHeaderFooterViewProvider.swift // DeclarativeTableView // // Created by Robin Charlton on 07/07/2021. // import UIKit struct TableViewHeaderFooterViewProvider< View: ReusableTableViewHeaderFooterView & TypeDepending & ViewHeightProviding >: TableViewHeaderFooterViewProviding { let dependency: (Int) -> View.DependentType func register(with tableView: UITableView) { tableView.register(View.self) } func viewForSectionAt(_ section: Int, with tableView: UITableView) -> UITableViewHeaderFooterView? { let view = tableView.dequeueReusableHeaderFooterView(withType: View.self) view.setDependency(dependency(section)) return view } func viewHeightForSectionAt(_ section: Int) -> CGFloat { View.viewHeight } }
// // MyService.swift // InterOfficeApp // // Created by Rahul Chopra on 01/11/18. // Copyright © 2018 Rahul Chopra. All rights reserved. // import Foundation class HRService: BaseService { private static let shared = HRService() static func sharedInstance() -> HRService { return shared } private override init() { } func sendGetRequestToGetUserDetails(dict: Dictionary<String, String>?, httpHeader: Dictionary<String, String>, delegate: GetResponseDataProtocol) { super.sendGetRequestWithObj(urlString: ServiceConstants.MSGraph.kBaseURL, obj: dict, httpHeader: httpHeader, serviceURL: ServiceConstants.RequestParameter.kGetUserInfo, serviceType: ServiceConstants.ServiceType.kSTGetUserInfo, requestType: ServiceConstants.RequestType.kRTGetUserInfo, delegate: delegate) } func sendGetRequestToGetUserPhoto(dict: Dictionary<String, String>?, httpHeader: Dictionary<String, String>, delegate: GetResponseDataProtocol) { super.sendGetRequestForGettingUserPhotoWithObj(urlString: ServiceConstants.MSGraph.kBaseURL, obj: dict, httpHeader: httpHeader, serviceURL: ServiceConstants.RequestParameter.kGetUserPhoto, serviceType: ServiceConstants.ServiceType.kSTGetUserPhoto, requestType: ServiceConstants.RequestType.kRTGetUserPhoto, delegate: delegate) } func sendPostRequestToGetToken(dict: Dictionary<String, String>, httpHeader: Dictionary<String, String>?, delegate: GetResponseDataProtocol) { super.sendPostRequestWithObj(urlString: ServiceConstants.MSAL.kBaseURL, obj: dict, header: httpHeader, serviceURL: ServiceConstants.RequestParameter.kGetToken, serviceType: ServiceConstants.ServiceType.kSTGetToken, requestType: ServiceConstants.RequestType.kRTGetToken, delegate: delegate) } func sendPostRequestToGetCustomFirebaseToken(dict: Dictionary<String, String>, httpHeader: Dictionary<String, String>?, delegate: GetResponseDataProtocol) { super.sendPostRequestWithObj(urlString: ServiceConstants.FirebaseFunction.kBaseURL, obj: dict, header: httpHeader, serviceURL: ServiceConstants.RequestParameter.kCustomFbToken, serviceType: ServiceConstants.ServiceType.kSTCustomFbToken, requestType: ServiceConstants.RequestType.kRTCustomFbToken, delegate: delegate) } func sendGetRequestToGetUserCalendar(filterEndpoint: String, dict: Dictionary<String, String>?, httpHeader: Dictionary<String, String>, delegate: GetResponseDataProtocol) { super.sendGetRequestWithObj(urlString: ServiceConstants.MSGraph.kBaseURL, obj: dict, httpHeader: httpHeader, serviceURL: ServiceConstants.RequestParameter.kCalendar + filterEndpoint, serviceType: ServiceConstants.ServiceType.kSTCalendar, requestType: ServiceConstants.RequestType.kRTCalendar, delegate: delegate) } func sendGetRequestToGetUserGroups(dict: Dictionary<String, String>?, httpHeader: Dictionary<String, String>, delegate: GetResponseDataProtocol) { super.sendGetRequestWithObj(urlString: ServiceConstants.MSGraph.kBaseURL, obj: dict, httpHeader: httpHeader, serviceURL: ServiceConstants.RequestParameter.kGroup, serviceType: ServiceConstants.ServiceType.kSTGroup, requestType: ServiceConstants.RequestType.kRTGroup, delegate: delegate) } func sendGetRequestToGetUserGroupItems(dict: Dictionary<String, String>?, httpHeader: Dictionary<String, String>, delegate: GetResponseDataProtocol) { super.sendGetRequestWithObj(urlString: ServiceConstants.MSGraph.kBaseURL, obj: dict, httpHeader: httpHeader, serviceURL: ServiceConstants.RequestParameter.kGroupItems, serviceType: ServiceConstants.ServiceType.kSTGroupItems, requestType: ServiceConstants.RequestType.kRTGroupItems, delegate: delegate) } func sendGetRequestToGetUserGroupFormItems(dict: Dictionary<String, String>?, httpHeader: Dictionary<String, String>, delegate: GetResponseDataProtocol) { super.sendGetRequestWithObj(urlString: ServiceConstants.MSGraph.kBaseURL, obj: dict, httpHeader: httpHeader, serviceURL: ServiceConstants.RequestParameter.kGroupFormItems, serviceType: ServiceConstants.ServiceType.kSTGroupFormItems, requestType: ServiceConstants.RequestType.kRTGroupFormItems, delegate: delegate) } func downloadFilesFromGuideFolder(downloadURL: String, fileName: String, delegate: GetResponseDataProtocol) { super.downloadFileWithObj(fileURL: downloadURL, fileName: fileName, serviceType: ServiceConstants.ServiceType.kSTDownloadGuideFile, delegate: delegate) } func downloadFilesFromFormFolder(downloadURL: String, fileName: String, delegate: GetResponseDataProtocol) { super.downloadFileWithObj(fileURL: downloadURL, fileName: fileName, serviceType: ServiceConstants.ServiceType.kSTDownloadFormFile, delegate: delegate) } func sendPostRequestToAddActivityOnGetStream(dict: Dictionary<String, String>, httpHeader: Dictionary<String, String>?, delegate: GetResponseDataProtocol) { super.sendPostRequestWithObj(urlString: ServiceConstants.FirebaseFunction.kBaseURL, obj: dict, header: httpHeader, serviceURL: ServiceConstants.RequestParameter.kAddActivity, serviceType: ServiceConstants.ServiceType.kSTAddActivity, requestType: ServiceConstants.RequestType.kRTAddActivity, delegate: delegate) } func sendPostRequestToGetActivityFromGetStream(dict: Dictionary<String, Any>, httpHeader: Dictionary<String, String>?, delegate: GetResponseDataProtocol) { super.sendPostRequestWithObj(urlString: ServiceConstants.FirebaseFunction.kBaseURL, obj: dict, header: httpHeader, serviceURL: ServiceConstants.RequestParameter.kGetActivity, serviceType: ServiceConstants.ServiceType.kSTGetActivity, requestType: ServiceConstants.RequestType.kRTGetActivity, delegate: delegate) } func sendPostRequestToGetActivityInChunksFromGetStream(dict: Dictionary<String, Any>, httpHeader: Dictionary<String, String>?, delegate: GetResponseDataProtocol) { super.sendPostRequestWithObj(urlString: ServiceConstants.FirebaseFunction.kBaseURL, obj: dict, header: httpHeader, serviceURL: ServiceConstants.RequestParameter.kGetActivity, serviceType: ServiceConstants.ServiceType.kSTGetActivityInChunks, requestType: ServiceConstants.RequestType.kRTGetActivityInChunks, delegate: delegate) } func sendPostRequestToGetStreamToken(dict: Dictionary<String, Any>, httpHeader: Dictionary<String, String>?, delegate: GetResponseDataProtocol) { super.sendPostRequestWithObj(urlString: ServiceConstants.FirebaseFunction.kBaseURL, obj: dict, header: httpHeader, serviceURL: ServiceConstants.RequestParameter.kGetStreamToken, serviceType: ServiceConstants.ServiceType.kSTGetStreamToken, requestType: ServiceConstants.RequestType.kRTGetStreamToken, delegate: delegate) } func sendPostRequestToWriteComment(dict: Dictionary<String, Any>, httpHeader: Dictionary<String, String>?, delegate: GetResponseDataProtocol) { super.sendPostRequestWithObj(urlString: ServiceConstants.FirebaseFunction.kBaseURL, obj: dict, header: httpHeader, serviceURL: ServiceConstants.RequestParameter.kDoComment, serviceType: ServiceConstants.ServiceType.kSTDoComment, requestType: ServiceConstants.RequestType.kRTDoComment, delegate: delegate) } func sendPostRequestToGetComment(dict: Dictionary<String, Any>, httpHeader: Dictionary<String, String>?, delegate: GetResponseDataProtocol) { super.sendPostRequestWithObj(urlString: ServiceConstants.FirebaseFunction.kBaseURL, obj: dict, header: httpHeader, serviceURL: ServiceConstants.RequestParameter.kGetComment, serviceType: ServiceConstants.ServiceType.kSTGetComment, requestType: ServiceConstants.RequestType.kRTGetComment, delegate: delegate) } override func serviceResult(responseObject: Any?, success: Bool, serviceType: ServiceConstants.ServiceType, delegate: GetResponseDataProtocol) { super.serviceResult(responseObject: responseObject, success: success, serviceType: serviceType, delegate: delegate) let response = super.getResponseWithSucess(responseObject: responseObject, success: success, serviceType: serviceType, delegate: delegate) delegate.didGetResponseFromServerWithObject(responseObject: response) } }
// // FlaggedWords.swift // InfiniteLegendsQuiz // // Created by Jordan LaGrone on 4/20/19. // Copyright © 2019 Jordan LaGrone. All rights reserved. // import Foundation let redBlackHeroes = ["Daredevil", "Deadpool", "Carnage", "Red Skull", "Wonder Man", "Crimson Dynamo", "Scarlet Witch", "Elektra"] let ffHeroes = ["Mr.Fantastic", "Reed Richards", "Susan Storm", "Human Torch", "The Thing", "Ben Grimm", "Johnny Storm", "Invisible"] let defenderHeroes = ["Dr.Strange", "Hercules", "Namor", "Pym", "Ant-Man", "Janet van Dyne", "Wasp", "Luke Cage", "Iron Fist"] let xMenHeroes = ["Beast", "Cyclops", "Xavier", "Summers", "Jean Grey", "Emma Frost", "Wolverine", "Sabretooth", "Magneto", "Nightcrawler", "Rogue", "Mystique", "Quicksilver", "Juggernaut", "Iceman", "Hank McCoy", "X-Men", "Cable", "Storm", "Colossus", "Gambit", "Psylocke", "Havok", "Banshee", "Bishop", "Apocalypse"] let cosmicHeroes = ["Galactus", "Sentry", "Warlock", "Moondragon", "Gamora", "Star-Lord", "Firelord", "Captain Marvel", "Drax", "Quasar", "Nova", "Beta Ray Bill", "Watcher", "Mantis", "Nebula"] let hulkHeroes = ["Hulk", "She-Hulk", "Banner", "Jennifer Walters", "Samson"] let doomHeroes = ["Doom", "Latveria", "Octopus", "Octavious", "Sandman", "Loki", "Vision"] let blackHeroes = ["Black Panther", "T'Challa", "Venom", "Black Widow", "War Machine", "Eddie Brock", "Kingpin", "Black Cat", "Punisher", "Frank Castle", "Ghost Rider", "Black Bolt", "Moon Knight", "Domino"] let spiderHeroes = ["Spider", "Parker", "Goblin", "Gwen Stacy", "Rhino", "Osborn", "Vulture", "Shocker", "Scorpion", "Electro"] let goldenRedHeroes = ["Stark", "Iron Man", "Phoenix"] let silverHeroes = ["Silver Surfer", "Ultron", "Silver Sable", "Norrin Radd"] let purpHeroes = ["Thanos", "Purple Man", "Hawkeye", "Clint Barton"] let bHeroes = ["Captain America", "Rogers", "Thor", "Winter Soldier", "Ares", "Donald Blake", "Kevin Masterson", "Thunderstrike"] let shieldHeroes = ["Nick Fury", "S.H.I.E.L.D.", "Squirrel Girl", "John Walker", "U.S. Agent"]
// // practice.swift // tvOSNativePlayer // // Created by DOMINGUEZ, LEO on 10/19/17. // Copyright © 2017 MilkshakeHQ. All rights reserved. // import Foundation import UIKit import AVKit class practice: AVPlayerViewController { }
// Chapter 3, 3.8.2 Where’s Waldorf? import Foundation var matrix = [[Character]]() var words = [[Character]]() func addInputRow(_ inputRow: String) { let inputArray = Array(inputRow.lowercased().characters) matrix.append(inputArray) } func addInputWord(_ inputWord: String) { let inputArray = Array(inputWord.lowercased().characters) words.append(inputArray) } addInputRow("abcDEFGhigg") addInputRow("hEbkWalDork") addInputRow("FtyAwaldORm") addInputRow("FtsimrLqsrc") addInputRow("byoArBeDeyv") addInputRow("Klcbqwikomk") addInputRow("strEBGadhrb") addInputRow("yUiqlxcnBjf") addInputWord("Waldor") addInputWord("Bambi") addInputWord("Betty") addInputWord("Dagbert") var results = [(Int, Int)](repeating: (-1, -1), count: words.count) func find(word: [Character]) -> (Int, Int)?{ for x in 0..<matrix[0].count { for y in 0..<matrix.count { for direction_x in -1...1 { for direction_y in -1...1 { if direction_y == 0 && direction_y == direction_x { continue } let found = find(word: word, x: x, y: y, direction_x: direction_x, direction_y: direction_y) if found { return (x, y) } } } } } return nil } func find(word: [Character], x: Int, y: Int, direction_x: Int, direction_y: Int) -> Bool{ var cx = x var cy = y let lastcx = (cx + word.count*direction_x) let lastcy = (cy + word.count*direction_y) if lastcx < 0 || lastcy < 0 || lastcx >= matrix[0].count || lastcy >= matrix.count { return false } for i in 0..<word.count { if cx < 0 || cy < 0 || cx >= matrix[0].count || cy >= matrix.count { return false } let char = matrix[cy][cx] if char != word[i] { return false } cx += direction_x cy += direction_y } return true } for i in 0..<words.count { let word = words[i] if let result = find(word: word) { results[i] = (result.1 + 1, result.0 + 1)// Format } print("Result \(i): \(results[i])") }
// // Copyright © 2017 Yellow Fork Technologies // // 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 class NamePart { var type:String? var value:String? var qualifiers = [Qualifier]() var fields = [Field]() static func convertJsonToNamePart(_ json:JSON) -> NamePart { let part = NamePart() part.type = json["type"].description part.value = json["value"].description if json["qualifiers"] != JSON.null { for q in json["qualifiers"].array! { part.qualifiers.append(Qualifier.convertJsonToQualifier(q)) } } if json["fields"] != JSON.null { for field in json["fields"].array! { part.fields.append(Field.convertJsonToField(field)) } } return part } }
// // LoginTopViewModel.swift // QiitaWithFluxSample // // Created by marty-suzuki on 2017/04/17. // Copyright © 2017年 marty-suzuki. All rights reserved. // import RxSwift import RxCocoa final class LoginTopViewModel { private let disposeBag = DisposeBag() init(loginButtonTap: ControlEvent<Void>, routeAction: RouteAction = .shared) { loginButtonTap .map { LoginDisplayType.webView } .bind(onNext: routeAction.show) .disposed(by: disposeBag) } }
// // AppDelegate.swift // SocialManager // // Created by Aynur Galiev on 23.09.15. // Copyright (c) 2015 Flatstack. All rights reserved. // import UIKit import TwitterKit @UIApplicationMain class AppDelegate: SocialAppDelegate { var window: UIWindow? override func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { super.application(application, didFinishLaunchingWithOptions: launchOptions) return true } } class SocialAppDelegate: UIResponder, UIApplicationDelegate, VKSdkDelegate { private let vkAppId: String? = nil private let fbAppID: String? = nil func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool { Twitter.sharedInstance().startWithConsumerKey(TWSocialNetwork.consumerKey, consumerSecret: TWSocialNetwork.consumerSecret) FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions) VKSdk.initializeWithDelegate(self, andAppId: VKSocialNetwork.appID) VKSdk.wakeUpSession() return true } func applicationDidBecomeActive(application: UIApplication) { FBSDKAppEvents.activateApp() } func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject?) -> Bool { FBSDKApplicationDelegate.sharedInstance().application(application, openURL: url, sourceApplication: sourceApplication, annotation: annotation) VKSdk.processOpenURL(url, fromApplication: sourceApplication) return true } func vkSdkNeedCaptchaEnter(captchaError: VKError!) { } func vkSdkTokenHasExpired(expiredToken: VKAccessToken!) { } func vkSdkUserDeniedAccess(authorizationError: VKError!) { } func vkSdkShouldPresentViewController(controller: UIViewController!) { } func vkSdkReceivedNewToken(newToken: VKAccessToken!) { } }
// // NodeAndText.swift // DiplomaApp // // Created by Zamkovoy Ilya on 22/05/2018. // Copyright © 2018 Zamkovoy Ilya. All rights reserved. // import Foundation import ARKit public extension SCNNode { convenience init(withPosition position: SCNVector3m, param: String) { let depth : Float = 0.01 let billboardConstraint = SCNBillboardConstraint() billboardConstraint.freeAxes = SCNBillboardAxis.Y let param = SCNText(string: param, extrusionDepth: CGFloat(bubbleDepth)) param.font = UIFont(name: "TimesNewRomanPSMT", size: 0.2)?.withTraits(traits: .traitBold) param.alignmentMode = kCAAlignmentCenter param.firstMaterial?.diffuse.contents = UIColor.black param.firstMaterial?.specular.contents = UIColor.black param.chamferRadius = CGFloat(bubbleDepth) let (minBound, maxBound) = param.boundingBox let paramNode = SCNNode(geometry: param) paramNode.pivot = SCNMatrix4MakeTranslation( (maxBound.x - minBound.x)/2, minBound.y, bubbleDepth/2) paramNode.scale = SCNVector3Make(0.2, 0.2, 0.2) paramNode.simdPosition = simd_float3.init(x: 0.05, y: 0.04, z: 0) let sphere = SCNSphere(radius: 0.004) sphere.firstMaterial?.diffuse.contents = UIColor.gray self.init() addChildNode(paramNode) constraints = [billboardConstraint] self.position = position } func move(_ position: SCNVector3) { SCNTransaction.begin() SCNTransaction.animationDuration = 0.4 SCNTransaction.animationTimingFunction = CAMediaTimingFunction.init(name: kCAMediaTimingFunctionLinear) self.position = position opacity = 1 SCNTransaction.commit() } func hide() { SCNTransaction.begin() SCNTransaction.animationDuration = 2.0 SCNTransaction.animationTimingFunction = CAMediaTimingFunction.init(name: kCAMediaTimingFunctionLinear) opacity = 0 SCNTransaction.commit() } func show() { opacity = 0 SCNTransaction.begin() SCNTransaction.animationDuration = 0.4 SCNTransaction.animationTimingFunction = CAMediaTimingFunction.init(name: kCAMediaTimingFunctionLinear) opacity = 1 SCNTransaction.commit() } } private extension UIFont { // Based on: https://stackoverflow.com/questions/4713236/how-do-i-set-bold-and-italic-on-uilabel-of-iphone-ipad func withTraits(traits:UIFontDescriptorSymbolicTraits...) -> UIFont { let descriptor = self.fontDescriptor.withSymbolicTraits(UIFontDescriptorSymbolicTraits(traits)) return UIFont(descriptor: descriptor!, size: 0) } }
// // PressAndHorizontalDragGesture.swift // RHLinePlot // // Created by Wirawit Rueopas on 4/18/20. // Copyright © 2020 Wirawit Rueopas. All rights reserved. // import SwiftUI /// A proxy view for press and horizontal drag detection. public struct PressAndHorizontalDragGestureView: UIViewRepresentable { public let minimumPressDuration: Double public var onBegan: ((Value) -> Void)? = nil public var onChanged: ((Value) -> Void)? = nil public var onEnded: ((Value) -> Void)? = nil public struct Value { /// The location of the current event. public let location: CGPoint } public class Coordinator: NSObject, UIGestureRecognizerDelegate { var parent: PressAndHorizontalDragGestureView var isDraggingActivated: Bool = false var longPress: UILongPressGestureRecognizer! var pan: UIPanGestureRecognizer! init(parent: PressAndHorizontalDragGestureView) { self.parent = parent } public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { // Only on horizontal drag if gestureRecognizer == pan { // Long pressed already, allow any direction if isDraggingActivated { return true } let v = pan.velocity(in: pan.view!) return abs(v.x) > abs(v.y) } else if gestureRecognizer == longPress { isDraggingActivated = true return true } else { fatalError("Unknown gesture recognizer") } } public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { // Only this combo works together return (gestureRecognizer == pan && otherGestureRecognizer == longPress) || (gestureRecognizer == longPress && otherGestureRecognizer == pan) } public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer) -> Bool { // Assume ScrollView's internal pan gesture to be any UIPanGestureRecognizer return otherGestureRecognizer != pan && otherGestureRecognizer.isKind(of: UIPanGestureRecognizer.self) } @objc func handlePan(_ gesture: UIPanGestureRecognizer) { guard let view = gesture.view else { assertionFailure("Missing view on gesture") return } // Must long press first guard isDraggingActivated else { return } switch gesture.state { case .changed: parent.onChanged?(.init(location: gesture.location(in: view))) default: break } } @objc func handleLongPress(_ gesture: UILongPressGestureRecognizer) { guard let view = gesture.view else { assertionFailure("Missing view on gesture") return } switch gesture.state { case .began: isDraggingActivated = true parent.onBegan?(.init(location: gesture.location(in: view))) case .ended: isDraggingActivated = false parent.onEnded?(.init(location: gesture.location(in: view))) default: break } } } public func makeCoordinator() -> Self.Coordinator { return Coordinator(parent: self) } public func makeUIView(context: UIViewRepresentableContext<Self>) -> UIView { let view = UIView() view.backgroundColor = .clear let longPress = UILongPressGestureRecognizer(target: context.coordinator, action: #selector(Coordinator.handleLongPress)) longPress.minimumPressDuration = minimumPressDuration longPress.delegate = context.coordinator view.addGestureRecognizer(longPress) context.coordinator.longPress = longPress let pan = UIPanGestureRecognizer(target: context.coordinator, action: #selector(Coordinator.handlePan)) pan.delegate = context.coordinator view.addGestureRecognizer(pan) context.coordinator.pan = pan return view } public func updateUIView(_ uiView: UIView, context: UIViewRepresentableContext<Self>) { // IMPORTANT: Must pass the new closures (onBegan etc.) to the Coordinator. // We do this just by passing self. // If not, those closures could capture invalid, old values. context.coordinator.parent = self } }
class TestClass { var language = "Objc" } func test() { let testClass = TestClass() let code = { [testClass] in print(testClass.language) } code() testClass.language = "Swift" code() } test()
// // SettingTableViewController.swift // MakeChoice // // Created by 吴梦宇 on 8/3/15. // Copyright (c) 2015 ___mengyu wu___. All rights reserved. // import UIKit import MBProgressHUD class SettingTableViewController: UITableViewController { struct IndexPaths { static let Acknowledgements = NSIndexPath(forRow: 0, inSection: 0) static let TermsOfService = NSIndexPath(forRow: 1, inSection: 0) static let PrivacyPolicy = NSIndexPath(forRow: 2, inSection: 0) static let ContactUs = NSIndexPath(forRow: 3, inSection: 0) } func acknowledgements() { // SwiftSpinner.show("Loading...", animated: true) let vc = CSSViewController() vc.filename = "Acknowledgements" vc.title = "Acknowledgements" let navVC = UINavigationController(rootViewController: vc) self.presentViewController(navVC, animated: true) { // SwiftSpinner.hide() } } func termsOfService() { // SwiftSpinner.show("Loading...", animated: true) let vc = CSSViewController() vc.filename = "TermsOfService" vc.title = "Terms of Service" let navVC = UINavigationController(rootViewController: vc) self.presentViewController(navVC, animated: true) { // SwiftSpinner.hide() } } func privacyPolicy() { // SwiftSpinner.show("Loading...", animated: true) let vc = CSSViewController() vc.filename = "PrivacyPolicy" vc.title = "Privacy Policy" let navVC = UINavigationController(rootViewController: vc) self.presentViewController(navVC, animated: true) { // SwiftSpinner.hide() } } func contactUs() { if MFMailComposeViewController.canSendMail() { UICustomSettingHelper.MBProgressHUDSimple(self.view) let mailer = MFMailComposeViewController() mailer.mailComposeDelegate = self mailer.setSubject("Contact Us/Report") mailer.setToRecipients([ADMIN_EMAIL]) mailer.setMessageBody("Enter message here...", isHTML: false) self.presentViewController(mailer, animated: true) { MBProgressHUD.hideAllHUDsForView(self.view, animated: true) } }else{ SweetAlert().showAlert("Could Not Send Email!", subTitle: "Your device could not send e-mail. Please check e-mail configuration and try again!", style: AlertStyle.Warning) } } override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Potentially incomplete method implementation. // Return the number of sections. return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete method implementation. // Return the number of rows in the section. return 4 } /* override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as! UITableViewCell // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ } extension SettingTableViewController: UITableViewDelegate { override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { self.tableView.deselectRowAtIndexPath(indexPath, animated: true) switch indexPath { case IndexPaths.Acknowledgements: self.acknowledgements() case IndexPaths.TermsOfService: self.termsOfService() case IndexPaths.PrivacyPolicy: self.privacyPolicy() case IndexPaths.ContactUs: self.contactUs() default: println("do nothing") } } } extension SettingTableViewController: MFMailComposeViewControllerDelegate { func mailComposeController(controller: MFMailComposeViewController!, didFinishWithResult result: MFMailComposeResult, error: NSError!) { switch result.value { case MFMailComposeResultCancelled.value: println("Mail cancelled") case MFMailComposeResultSaved.value: println("Mail saved") case MFMailComposeResultSent.value: println("Mail sent") case MFMailComposeResultFailed.value: println("Mail sent failure: \(error.localizedDescription)") default: break } self.dismissViewControllerAnimated(true, completion: nil) } }
// // CustomChecklist.swift // Umbrella // // Created by Lucas Correa on 05/12/2018. // Copyright © 2018 Security First. All rights reserved. // import Foundation import SQLite class CustomChecklist: Codable, TableProtocol { // Used in parser from the database to object var id: Int var languageId: Int var name: String! // // MARK: - Properties var items: [CustomCheckItem] // // MARK: - Initializers init() { self.id = -1 self.languageId = -1 self.name = "" self.items = [] } init(name: String) { self.id = -1 self.languageId = -1 self.name = name self.items = [] } init(name: String, languageId: Int) { self.id = -1 self.languageId = languageId self.name = name self.items = [] } init(name: String, items: [CustomCheckItem]) { self.id = -1 self.languageId = -1 self.name = name self.items = items } // // MARK: - Codable enum CodingKeys: String, CodingKey { case id case languageId = "language_id" case name case items = "list" } required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) if container.contains(.id) { self.id = try container.decode(Int.self, forKey: .id) } else { self.id = -1 } if container.contains(.languageId) { self.languageId = try container.decode(Int.self, forKey: .languageId) } else { self.languageId = -1 } if container.contains(.name) { self.name = try container.decode(String.self, forKey: .name) } else { self.name = "" } if container.contains(.items) { self.items = try container.decode([CustomCheckItem].self, forKey: .items) } else { self.items = [] } } // // MARK: - TableProtocol static var table: String = "custom_checklist" var tableName: String { return CustomChecklist.table } func columns() -> [Column] { let array = [ Column(name: "id", type: .primaryKey), Column(name: "name", type: .string), Column(foreignKey: ForeignKey(key: "language_id", table: Table("language"), tableKey: "id")) ] return array } }
// RUN: %target-swift-ide-test -code-completion -code-completion-token=A -source-filename=%s // REQUIRES: asserts var a{protocol A{struct a{func d<T{class B:T a{#^A^#
// // ViewController.swift // Multiples // // Created by Greg Willis on 8/31/16. // Copyright © 2016 Willis Programming. All rights reserved. // import UIKit class ViewController: UIViewController, UITextFieldDelegate { // MARK: - Variables var multiple: Int = 0 var numA: Int = 0 var answer: Int = 0 // MARK: - Outlets @IBOutlet weak var logo: UIImageView! @IBOutlet weak var numberTxtField: UITextField! @IBOutlet weak var playBtn: UIButton! @IBOutlet weak var addBtn: UIButton! @IBOutlet weak var addLbl: UILabel! //MARK: - Actions @IBAction func playBtnPressed(sender: AnyObject) { if numberTxtField.text != nil && numberTxtField.text != "" { multiple = Int(numberTxtField.text!)! logo.hidden = true numberTxtField.hidden = true playBtn.hidden = true addBtn.hidden = false addLbl.hidden = false } } @IBAction func addBtnPressed(sender: AnyObject) { if answer <= 50 { answer = numA + multiple addLbl.text = "\(numA) + \(multiple) = \(answer)" numA = answer } else { numberTxtField.text = "" logo.hidden = false numberTxtField.hidden = false playBtn.hidden = false addBtn.hidden = true addLbl.hidden = true multiple = 0 numA = 0 answer = 0 } } 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. } }
// // ViewController.swift // PTBH // // Created by Phuc on 5/17/18. // Copyright © 2018 Phuc. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var txtResult: UILabel! @IBAction func btnreset(_ sender: Any) { txtA.text=""; txtB.text=""; txtC.text=""; } @IBOutlet weak var txtC: UITextField! @IBOutlet weak var txtB: UITextField! @IBOutlet weak var txtA: UITextField! var a:Double = 0; var b:Double = 0; var c:Double = 0; @IBAction func btnGiai(_ sender: UIButton) { if (txtA.text == "" || txtB.text == "" || txtC.text == ""){ txtResult.text = "Nhap Gia Tri"; } else { if(!kiemtrasoam(character: txtA.text!) || !kiemtrasoam(character: txtB.text!) || !kiemtrasoam(character: txtC.text!)) { txtResult.text = "Sai Dinh Dang So"; } else { a = Double(txtA.text!)!; b = Double (txtB.text!)!; c = Double (txtC.text!)!; if (a == 0) { if (b == 0) { if (c == 0){ txtResult.text = "Phuong Trinh Vo So Nghiem";} else { txtResult.text = "Phuong Trinh Vo Nghiem";} } else{ txtResult.text = String (format: "Phuong Trinh Co 1 Nghiem x= %.1f",(-b/c)); } } else{ var delta: Double = b*b-4*a*c; if (delta < 0){ self.txtResult.text = "Phuong Trinh Vo Nghiem";} else if (delta == 0) { self.txtResult.text = String (format: "Phuong Trinh Co 1 Nghiem x= %.1f",(-self.b/(2*c))); }else{ var sq : Double = sqrt(delta); var x1: Double = (-self.b+sq)/(2*a); var x2: Double = (-self.b-sq)/(2*a); self.txtResult.text = String (format: "Phuong Trinh Co 2 Nghiem Phan Biet x1= %.1f , x2= %.1f",x1,x2); } } } } } func kiemtrasoam(character: String )->Bool { let charaterIndex = character [character.index(character.startIndex, offsetBy: 0)]; if (charaterIndex == "-") { var count: Int = 0; for charac in character.characters { if (charac == "-") { count += 1; } } if(count > 1 ){ return false;} else { return true;} } else { var count: Int = 0; for charac in character.characters { if (charac == "-") { count += 1; } } if(count > 0 ){ return false;} else { return true; } } return 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. } }
// // ViewController.swift // Parrot // // Created by Const. on 13.02.2020. // Copyright © 2020 Oleginc. All rights reserved. // import UIKit class ProfileViewController: UIViewController { // MARK: - UI weak var scrollView: UIScrollView! weak var profileImage: UIImageView! weak var setProfileImageButton: CustomButton! weak var nameLabel: UILabel! weak var nameTextField: UITextField! weak var descriptionTextView: UITextView! weak var editingDescriptionTextView: UITextView! weak var editingButton: UIButton! weak var saveButton: CustomButton! weak var cancelButton: CustomButton! weak var activityIndicator: UIActivityIndicatorView! // Dependencies private var model: IProfileVCModel private let presentationAssembly: IPresentationAssembly // MARK: - VC Lifecycle init(model: IProfileVCModel, presentationAssembly: IPresentationAssembly) { self.model = model self.presentationAssembly = presentationAssembly super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white fillView() let hideKeyboardGesture = UITapGestureRecognizer(target: self, action: #selector(hideKeyboard)) scrollView.addGestureRecognizer(hideKeyboardGesture) let data = model.getUserData() profileImage.image = UIImage(data: data.image) nameLabel.text = data.name descriptionTextView.text = data.description } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWasShown(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(successfulSave), name: NSNotification.Name.NSManagedObjectContextDidSave, object: model.getNotificationObject()) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil) NotificationCenter.default.removeObserver(self, name: NSNotification.Name.NSManagedObjectContextDidSave, object: model.getNotificationObject()) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() //Закругленные края setProfileImageButton.layer.cornerRadius = CGFloat(setProfileImageButton.frame.width/2) profileImage.layer.cornerRadius = CGFloat(setProfileImageButton.frame.width/2) } // MARK: - Fill View private func fillView() { // MARK: Scroll View let scroll = UIScrollView() scroll.translatesAutoresizingMaskIntoConstraints = false scrollView = scroll view.addSubview(scrollView) NSLayoutConstraint.activate([ scrollView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor), scrollView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor), scrollView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor), scrollView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor) ]) // MARK: profile Image let imageView = UIImageView() imageView.contentMode = .scaleAspectFill imageView.image = UIImage(named: "placeholder-user") imageView.clipsToBounds = true profileImage = imageView scrollView.addSubview(profileImage) profileImage.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ profileImage.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor, constant: 40), profileImage.topAnchor.constraint(equalTo: scrollView.topAnchor, constant: 40), profileImage.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor, constant: -40), profileImage.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.78), profileImage.heightAnchor.constraint(equalTo: profileImage.widthAnchor) ]) // MARK: setImageButton let setImageButton = CustomButton() setImageButton.changeBackroundColor(UIColor(red: 61/255, green: 119/255, blue: 236/255, alpha: 1)) setImageButton.addTarget(self, action: #selector(setProfileImageButtonAction(sender:)), for: .touchUpInside) setProfileImageButton = setImageButton scrollView.addSubview(setProfileImageButton) setProfileImageButton.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ setProfileImageButton.trailingAnchor.constraint(equalTo: profileImage.trailingAnchor), setProfileImageButton.bottomAnchor.constraint(equalTo: profileImage.bottomAnchor), setProfileImageButton.widthAnchor.constraint(equalTo: profileImage.widthAnchor, multiplier: 1/4), setProfileImageButton.heightAnchor.constraint(equalTo: profileImage.heightAnchor, multiplier: 1/4) ]) // MARK: Картинка для imButton let image = UIImageView() image.image = UIImage(named: "slr-camera-2-xxl") setProfileImageButton.addSubview(image) image.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ image.trailingAnchor.constraint(equalTo: setProfileImageButton.trailingAnchor, constant: -18), image.bottomAnchor.constraint(equalTo: setProfileImageButton.bottomAnchor, constant: -18), image.leadingAnchor.constraint(equalTo: setProfileImageButton.leadingAnchor, constant: 18), image.topAnchor.constraint(equalTo: setProfileImageButton.topAnchor, constant: 18) ]) // MARK: nameLabel let nLabel = UILabel() nLabel.textAlignment = .center nLabel.textColor = .black nLabel.font = UIFont.systemFont(ofSize: self.view.frame.width/14, weight: UIFont.Weight.heavy) nLabel.text = "Владислав Яндола" nameLabel = nLabel scrollView.addSubview(nameLabel) nameLabel.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ nameLabel.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor, constant: 40), nameLabel.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor, constant: -40), nameLabel.topAnchor.constraint(equalTo: profileImage.bottomAnchor, constant: 14) ]) // MARK: descriptionTextView let dTextView = UITextView() dTextView.textAlignment = .center dTextView.textColor = .black dTextView.font = UIFont.systemFont(ofSize: self.view.frame.width/20, weight: UIFont.Weight.medium) dTextView.text = "Меланхолик, анархист и просто хороший человек" dTextView.isEditable = false dTextView.isSelectable = false descriptionTextView = dTextView scrollView.addSubview(descriptionTextView) descriptionTextView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ descriptionTextView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor, constant: 20), descriptionTextView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor, constant: -20), descriptionTextView.topAnchor.constraint(equalTo: nameLabel.bottomAnchor, constant: 8), descriptionTextView.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.3) ]) // MARK: editingButton let eButton = UIButton() eButton.setTitle("Редактировать", for: .normal) eButton.setTitleColor(.black, for: .normal) eButton.titleLabel?.font = eButton.titleLabel?.font.withSize(self.view.frame.width/20) eButton.layer.cornerRadius = 10 eButton.layer.borderWidth = 1.5 eButton.layer.borderColor = (UIColor.black).cgColor eButton.addTarget(self, action: #selector(editProfileButton(sender:)), for: .touchUpInside) editingButton = eButton scrollView.addSubview(editingButton) var constant: CGFloat = 5 //constant для экрана, большего чем у iPhone 8 if view.frame.height > 736 { constant *= 12 } editingButton.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ editingButton.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor, constant: 40), editingButton.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor, constant: -40), editingButton.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor, constant: -29), editingButton.topAnchor.constraint(equalTo: descriptionTextView.bottomAnchor, constant: constant), editingButton.widthAnchor.constraint(equalTo: editingButton.heightAnchor, multiplier: 120/17) ]) // MARK: nameTextField let textField = UITextField() textField.textAlignment = .center textField.font = nameLabel.font textField.text = nameLabel.text textField.layer.cornerRadius = 10 textField.backgroundColor = UIColor(red: 240/255, green: 240/255, blue: 240/255, alpha: 1) nameTextField = textField scrollView.addSubview(nameTextField) nameTextField.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ nameTextField.trailingAnchor.constraint(equalTo: nameLabel.trailingAnchor), nameTextField.bottomAnchor.constraint(equalTo: nameLabel.bottomAnchor), nameTextField.leadingAnchor.constraint(equalTo: nameLabel.leadingAnchor), nameTextField.topAnchor.constraint(equalTo: nameLabel.topAnchor) ]) nameTextField.isHidden = true // MARK: editDescriptionTextView let textView = UITextView() textView.textAlignment = .center textView.font = descriptionTextView.font textView.text = descriptionTextView.text textView.layer.cornerRadius = 10 textView.backgroundColor = UIColor(red: 240/255, green: 240/255, blue: 240/255, alpha: 1) editingDescriptionTextView = textView scrollView.addSubview(editingDescriptionTextView) editingDescriptionTextView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ editingDescriptionTextView.trailingAnchor.constraint(equalTo: descriptionTextView.trailingAnchor), editingDescriptionTextView.bottomAnchor.constraint(equalTo: descriptionTextView.bottomAnchor), editingDescriptionTextView.leadingAnchor.constraint(equalTo: descriptionTextView.leadingAnchor), editingDescriptionTextView.topAnchor.constraint(equalTo: descriptionTextView.topAnchor) ]) editingDescriptionTextView.isHidden = true // MARK: SaveButton let button = CustomButton() button.changeBackroundColor(UIColor(red: 61/255, green: 119/255, blue: 236/255, alpha: 1)) button.layer.cornerRadius = editingButton.layer.cornerRadius button.titleLabel?.font = editingButton.titleLabel?.font button.setTitle("Сохранить", for: .normal) button.setTitleColor(.white, for: .normal) button.addTarget(self, action: #selector(saveButton(sender:)), for: .touchUpInside) button.layer.cornerRadius = 10 saveButton = button scrollView.addSubview(saveButton) saveButton.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ saveButton.trailingAnchor.constraint(equalTo: view.centerXAnchor, constant: 20), saveButton.bottomAnchor.constraint(equalTo: editingButton.bottomAnchor), saveButton.leadingAnchor.constraint(equalTo: editingButton.leadingAnchor), saveButton.topAnchor.constraint(equalTo: editingButton.topAnchor) ]) saveButton.isHidden = true // MARK: CancelButton let cancel = CustomButton() cancel.changeBackroundColor(UIColor(red: 61/255, green: 119/255, blue: 236/255, alpha: 1)) cancel.layer.cornerRadius = editingButton.layer.cornerRadius cancel.titleLabel?.font = editingButton.titleLabel?.font cancel.setTitle("Отмена", for: .normal) cancel.setTitleColor(.white, for: .normal) cancel.addTarget(self, action: #selector(cancelButton(sender:)), for: .touchUpInside) cancel.layer.cornerRadius = 10 cancelButton = cancel scrollView.addSubview(cancelButton) cancelButton.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ cancelButton.trailingAnchor.constraint(equalTo: editingButton.trailingAnchor), cancelButton.bottomAnchor.constraint(equalTo: editingButton.bottomAnchor), cancelButton.leadingAnchor.constraint(equalTo: view.centerXAnchor, constant: 40), cancelButton.topAnchor.constraint(equalTo: editingButton.topAnchor) ]) cancelButton.isHidden = true // MARK: IndicatorView let indicator = UIActivityIndicatorView() indicator.hidesWhenStopped = true indicator.color = .black indicator.style = .whiteLarge activityIndicator = indicator scrollView.addSubview(activityIndicator) activityIndicator.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ activityIndicator.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor, constant: -20), activityIndicator.topAnchor.constraint(equalTo: scrollView.topAnchor, constant: 20) ]) } // MARK: - Frontend // MARK: setProfileImage @objc func setProfileImageButtonAction(sender: UIButton) { selectionAlert() } func selectionAlert() { let imagePickerController = UIImagePickerController() imagePickerController.delegate = self let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) let cancelAction = UIAlertAction(title: "Назад", style: .cancel, handler: nil) let libraryAction = UIAlertAction(title: "Выбрать из галереи", style: .default) { (action: UIAlertAction) in imagePickerController.sourceType = .photoLibrary self.present(imagePickerController, animated: true, completion: nil) } let makePhotoAction = UIAlertAction(title: "Сделать фото", style: .default) { (action: UIAlertAction) in if UIImagePickerController.isSourceTypeAvailable(.camera) { imagePickerController.sourceType = .camera self.present(imagePickerController, animated: true, completion: nil) } else { print("Camera not available") } } let downloadAction = UIAlertAction(title: "Загрузить", style: .default) { (action: UIAlertAction) in let viewController = self.presentationAssembly.imagesViewController(unwindController: self) self.present(viewController, animated: true, completion: nil) } alert.addAction(cancelAction) alert.addAction(libraryAction) alert.addAction(makePhotoAction) alert.addAction(downloadAction) present(alert, animated: true, completion: nil) } // MARK: editProfileButton @objc func editProfileButton(sender: UIButton) { nameTextField.text = nameLabel.text editingDescriptionTextView.text = descriptionTextView.text editingMode() } // MARK: saveButton @objc func saveButton(sender: CustomButton) { activityIndicator.startAnimating() if let name = nameTextField.text, let description = editingDescriptionTextView.text, let image = profileImage.image { saveButton.changeBackroundColor(UIColor.lightGray) saveButton.isEnabled = false model.saveUserData(name: name, description: description, image: image) } hideKeyboard() } // MARK: cancelButton @objc func cancelButton(sender: UIButton) { presentMode() hideKeyboard() } // MARK: showSuccessesAlert @objc func showSuccessesAlert() { let alert = UIAlertController(title: "Уведомление", message: "Изменения сохранены", preferredStyle: .alert) let action = UIAlertAction(title: "OK", style: .cancel, handler: nil) alert.addAction(action) present(alert, animated: true, completion: nil) } // MARK: - Backend // MARK: profile modes private func changeMode() { nameTextField.isHidden = !nameTextField.isHidden editingDescriptionTextView.isHidden = !editingDescriptionTextView.isHidden nameLabel.isHidden = !nameLabel.isHidden descriptionTextView.isHidden = !descriptionTextView.isHidden } func editingMode() { changeMode() editingButton.isHidden = true saveButton.isHidden = false cancelButton.isHidden = false } func presentMode() { changeMode() editingButton.isHidden = false cancelButton.isHidden = true saveButton.isHidden = true } // MARK: - Save Notification @objc func successfulSave() { DispatchQueue.main.async { [weak self] in if let vc = self { if vc.nameTextField.isHidden { vc.activityIndicator.stopAnimating() vc.showSuccessesAlert() } else { vc.saveButton.changeBackroundColor(UIColor(red: 61/255, green: 119/255, blue: 236/255, alpha: 1)) vc.saveButton.isEnabled = true vc.activityIndicator.stopAnimating() vc.nameLabel.text = self?.nameTextField.text vc.descriptionTextView.text = self?.editingDescriptionTextView.text vc.presentMode() vc.showSuccessesAlert() } } } } func saveImage(image: UIImage) { model.saveImage(image: image) } // MARK: keyboard notification @objc func keyboardWasShown(notification: Notification) { let info = notification.userInfo! as NSDictionary let kbSize = (info.value(forKey: UIResponder.keyboardFrameEndUserInfoKey) as! NSValue).cgRectValue.size let contentInsets = UIEdgeInsets(top: 0.0, left: 0.0, bottom: kbSize.height, right: 0.0) scrollView.contentInset = contentInsets scrollView.scrollIndicatorInsets = contentInsets } @objc func keyboardWillBeHidden(notification: Notification) { let contentInsets = UIEdgeInsets.zero scrollView.contentInset = contentInsets } @objc func hideKeyboard() { scrollView.endEditing(true) } } // MARK: - ImagePickerDelegate extension ProfileViewController : UIImagePickerControllerDelegate, UINavigationControllerDelegate { func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { let image = info[UIImagePickerController.InfoKey.originalImage] as! UIImage profileImage.image = image picker.dismiss(animated: true, completion: nil) saveImage(image: image) } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { picker.dismiss(animated: true, completion: nil) } }
// // AppCoordinator.swift // Fast Foodz // // Created by Yoseob Lee on 3/31/20. // import Foundation import RxSwift import UIKit final class AppCoordinator: NSObject, Coordinator { var childCoordinators = [Coordinator]() var rootViewController: UIViewController var navController: UINavigationController? private let disposeBag = DisposeBag() init(rootViewController: UIViewController, navController: UINavigationController?) { self.rootViewController = rootViewController self.navController = navController } /// Special convenience init for AppCoordinator so that AppDelegate doesn't have to worry about initializing. /// The AppCoordinator's root controller is it's navigation controller instance. convenience override init() { let navVC = UINavigationController() self.init(rootViewController: navVC, navController: navVC) } func start(_ initialIndex: Int) { guard let viewType = FastFoodzViewModel.ViewType(rawValue: initialIndex) else { return } let vm = FastFoodzViewModel(viewType: viewType) let vc = FastFoodzViewController(viewModel: vm) startWithViewController(vc, animated: true) bindViewModel(vm) } private func bindViewModel(_ viewModel: FastFoodzViewModel) { viewModel .output$ .observeOn(MainScheduler.instance) .subscribe(onNext: { [weak self] output in switch output { case .didSelectRestaurant(let restaurant): self?.startDetailFlow(restaurant) default: break } }) .disposed(by: viewModel.disposeBag) } private func startDetailFlow(_ restaurant: Restaurant) { let vm = RestaurantDetailViewModel(restaurant: restaurant) let vc = RestaurantDetailViewController(viewModel: vm) navController?.pushViewController(vc, animated: true) } }
// // UIColor+pucolors.swift // PopUpCorn // // Created by Elias Paulino on 12/02/19. // Copyright © 2019 Elias Paulino. All rights reserved. // import Foundation import UIKit // MARK: - Including colors extension UIColor { static private var defaultColor: UIColor { return UIColor.cyan } static var puRed: UIColor { return UIColor.init(named: "red") ?? defaultColor } static var puExtraLightRed: UIColor { return UIColor.init(named: "light_extra_red") ?? defaultColor } static var puLightRed: UIColor { return UIColor.init(named: "light_red") ?? defaultColor } static var puPurple: UIColor { return UIColor.init(named: "purple") ?? defaultColor } static var puLightPurple: UIColor { return UIColor.init(named: "light_purple") ?? defaultColor } static var puTextPurple: UIColor { return UIColor.init(named: "text_purple") ?? defaultColor } static var puTextBlue: UIColor { return UIColor.init(named: "text_blue") ?? defaultColor } }
// // RowItemCell.swift // AarambhPlus // // Created by Santosh Kumar Sahoo on 9/8/18. // Copyright © 2018 Santosh Dev. All rights reserved. // import UIKit class RowItemCell: UICollectionViewCell { @IBOutlet weak private var imageView: UIImageView! @IBOutlet weak private var titleLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() // imageView.addGradientView() imageView.layer.cornerRadius = 5 imageView.layer.masksToBounds = true } func configureCell(dataSource: LayoutProtocol?) { imageView.setKfImage(dataSource?.getImageUrl()) titleLabel.text = dataSource?.getTitle() } }
// // PIP.swift // PIP // // Created by Felipe Kimio Nishikaku on 28/05/18. // import UIKit public class PIPConfiguration { public var basePipView: UIView public var viewToPip: UIView public var pipWidth: CGFloat = 0.0 public var pipHeight: CGFloat = 0.0 public var animateDuration: TimeInterval = 0.3 public var pipSizePercentage: CGFloat = 4.0 public var removeView: UIView? public init(viewToPip: UIView) { self.viewToPip = viewToPip self.basePipView = viewToPip.superview! } public init(viewToPip: UIView, basePipView: UIView) { self.viewToPip = viewToPip self.basePipView = basePipView } } public protocol PIPDelegate: class { func onRemove() func onFullScreen() func onMoveEnded(frame: CGRect) } public class PIP { public weak var delegate: PIPDelegate? public var configuration: PIPConfiguration! private var hangAroundPanGesture: UIPanGestureRecognizer! public init(configuration: PIPConfiguration) { self.configuration = configuration pipSize() hangAroundPanGesture = UIPanGestureRecognizer(target: self, action: #selector(hangAround(_:))) hangAroundPanGesture.isEnabled = true configuration.viewToPip.addGestureRecognizer(hangAroundPanGesture) configuration.viewToPip.isUserInteractionEnabled = true createRemoveView(configuration: configuration) } private func createRemoveView(configuration: PIPConfiguration) { if let view = configuration.removeView { let removeGesture = UITapGestureRecognizer(target: self, action: #selector(remove(_:))) removeGesture.isEnabled = true view.addGestureRecognizer(removeGesture) view.isUserInteractionEnabled = true } } private func pipSize() { configuration.pipWidth = (configuration.basePipView.frame.width / configuration.pipSizePercentage) * (16 / 9) configuration.pipHeight = (configuration.basePipView.frame.height / configuration.pipSizePercentage) * (9 / 16) } public func updatePipRect(_ rect: CGRect) { UIView.animate(withDuration: configuration.animateDuration, animations: { self.configuration.viewToPip.frame = rect self.configuration.viewToPip.layoutIfNeeded() if let removeView = self.configuration.removeView { var frame: CGRect = removeView.frame frame.origin.x = rect.width - frame.width removeView.frame = frame } }) } @objc func remove(_ gesture: UIPanGestureRecognizer) { configuration.viewToPip.removeFromSuperview() if let delegate = delegate { delegate.onRemove() } } @objc func hangAround(_ gesture: UIPanGestureRecognizer) { guard let window = UIApplication.shared.keyWindow else { return } let viewFrame = configuration.basePipView.frame let locationInWindow = gesture.location(in: window) let targetRect = CGRect(x: locationInWindow.x - configuration.pipWidth / 2, y: locationInWindow.y - configuration.pipHeight / 2, width: configuration.pipWidth, height: configuration.pipHeight) switch gesture.state { case .began, .changed: if targetRect.origin.x > 0, targetRect.origin.x + configuration.pipWidth < viewFrame.width, targetRect.origin.y > 0, targetRect.origin.y + configuration.pipHeight < viewFrame.height { updatePipRect(targetRect) } break case .ended: var xPosition: CGFloat = 0.0 var yPosition: CGFloat = 0.0 let percentageX = (targetRect.origin.x * 100 / viewFrame.width ) / 100 let percentageY = (targetRect.origin.y * 100 / viewFrame.height ) / 100 if percentageX > 0.4 { xPosition = viewFrame.width - configuration.pipWidth } if percentageY > 0.4 { yPosition = viewFrame.height - configuration.pipHeight } var endFrame: CGRect if xPosition == viewFrame.width - configuration.pipWidth, yPosition == 0 { let viewFrame = configuration.basePipView.frame endFrame = CGRect(x: 0, y: 0, width: viewFrame.width, height: viewFrame.height) if let delegate = delegate { delegate.onFullScreen() } } else { endFrame = CGRect(x: xPosition, y: yPosition, width: configuration.pipWidth, height: configuration.pipHeight) } updatePipRect(endFrame) if let delegate = delegate { delegate.onMoveEnded(frame: endFrame) } break default: break } } }
// // Recipient.swift // SwiftCRUD // // Created by Владислав on 09.04.2020. // Copyright © 2020 Владислав. All rights reserved. // import Foundation struct Recipient { var IdRecipient: Int var firstName: String var lastName: String var age: Int var phoneNumber: String var address: String init(id: Int, firstName: String, lastName: String, age: Int, phoneNumber: String, address: String) { self.IdRecipient = id self.firstName = firstName self.lastName = lastName self.age = age self.phoneNumber = phoneNumber self.address = address } }
//可選鏈 class 主謀類別{ } class 嫌犯B類別{ var 線索:主謀類別? } class 嫌犯A類別{ var 線索:嫌犯B類別? } class 警察類別{ var 線索:嫌犯A類別? } var 警察 = 警察類別() //線索都是nil所以不會輸出 抓住主謀 if let 主謀=警察.線索?.線索?.線索 { print(" 抓住了主謀了!") } //我們將線索的可選值都給予值,整個可選鏈就連貫起來了 let 嫌犯A=嫌犯A類別() let 嫌犯B=嫌犯B類別() let 主謀=主謀類別() 警察.線索=嫌犯A 嫌犯A.線索=嫌犯B 嫌犯B.線索=主謀 if let 主謀=警察.線索?.線索?.線索 { print(" 抓住了主謀了!") } //輸出 抓住主謀了!
// // ActualReview.swift // Cosmic Game Reviews // // Created by David Poulos on 11/27/15. // Copyright © 2015 ComputerScienceInc. All rights reserved. // For inquiries: (855) 836-3987 import UIKit import CoreData class ActualReview: UIViewController { var item: Review? @IBOutlet weak var lbl_game_name: UILabel! @IBOutlet weak var lbl_rating: UILabel! @IBOutlet weak var lbl_description: UITextView! @IBOutlet weak var img_game_pic: UIImageView! override func viewDidLoad() { super.viewDidLoad() if let r = item { lbl_game_name.text = "Game: \(r.game_name!)" lbl_game_name.textColor = UIColor.redColor() lbl_rating.text = "Rating: \(lroundf(Float(r.game_rating!)))/10" lbl_rating.textColor = UIColor.redColor() lbl_description.text = "Description: \(r.game_review_description!)" lbl_description.textColor = UIColor.redColor() img_game_pic.image = UIImage(data: r.game_picture!) } } }
// // ThirdComponentCell.swift // OptionalComponents // // Created by Florentin Lupascu on 21/05/2019. // Copyright © 2019 Florentin Lupascu. All rights reserved. // import UIKit protocol ThirdComponentCellDelegate { func thirdComponentSliderChanged(cell: ThirdComponentCell, thirdComponent slider: UISlider) } class ThirdComponentCell: UITableViewCell { @IBOutlet weak var thirdComponentSlider: UISlider! @IBOutlet weak var thirdComponentLabel: UILabel! var delegate: ThirdComponentCellDelegate? override func awakeFromNib() { super.awakeFromNib() } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } @IBAction func thirdComponentSliderValueChanged(_ sender: UISlider) { delegate?.thirdComponentSliderChanged(cell: self, thirdComponent: thirdComponentSlider) } }
// // CombinedMetrics.swift // GoogleAnalyticsReader // // Created by Fabio Milano on 26/03/16. // Copyright © 2016 Touchwonders. All rights reserved. // import Freddy typealias Response = [String: protocol<ReportDataResponse>] public struct CombinedMetrics { let results: Array<Response> } extension CombinedMetrics: ReportDataResponse { public init(json: JSON) throws { let jsonItems = try json.dictionary() var resultArray = Array<Response>() for key in jsonItems.keys { if let value = GoogleReportMetric(rawValue: key) { let model = try value.responseModelType().init(json: json) var dic = Response() dic.updateValue(model, forKey: key) resultArray.append(dic) } } results = resultArray } } // The operation to retrieve current data struct CombinedMetricsOperation: ReportDataOperation { typealias OperationResponseType = CombinedMetrics let request: CombinedMetricsRequest func HTTPMethod() -> Method { return .GET } } // The request to use to run the operation struct CombinedMetricsRequest: ReportDataRequest { let ids: String let startDate: String let endDate: String let metrics: [GoogleReportMetric] init(ids: String, startDate: String, endDate: String, metrics: [GoogleReportMetric]) { self.ids = ids self.startDate = startDate self.endDate = endDate self.metrics = metrics } }
// // WeatherRequest.swift // IOS_Weather // // Created by ThanhLong on 4/5/18. // Copyright © 2018 ThanhLong. All rights reserved. // import Foundation import Alamofire import ObjectMapper class WeatherRequest: BaseRequest { required init(lat: Float, lot: Float) { let body: [String: Any] = [:] let urltmp = URLs.APIBaseUrl + "\(lat),\(lot)" super.init(url: urltmp, requestType: .get, body: body) } }
// // ArrayExtension.swift // Jock // // Created by HD on 15/3/21. // Copyright (c) 2015年 Haidy. All rights reserved. // import Foundation extension Array { }
// // isKeyboardExtensionContext.swift // KeyboardKit // // Created by Valentin Shergin on 5/17/16. // Copyright © 2016 AnchorFree. All rights reserved. // import Foundation public func isKeyboardExtensionContext() -> Bool { return UIInputViewController.isRootInputViewControllerAvailable }
// // DetailVCests.swift // ToDoTests // // Created by Fernando Putallaz on 09/06/2020. // Copyright © 2020 myOwn. All rights reserved. // import XCTest @testable import ToDo class DetailVCTests: XCTestCase { var sut: DetailVC! override func setUp() { let sb = UIStoryboard(name: "Main", bundle: nil) sut = sb.instantiateViewController(withIdentifier: "DetailVC") as? DetailVC sut.loadViewIfNeeded() } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. } func test_HasTitleLabel() { let titleLabelIsSubView = sut.titleLabel?.isDescendant(of: sut.view) ?? false XCTAssertTrue(titleLabelIsSubView) } func test_HasDueDateLabel() { let dueDateLabelIsSubView = sut.dueDateLabel?.isDescendant(of: sut.view) ?? false XCTAssertTrue(dueDateLabelIsSubView) } func test_HasLocationLabel() { let locationLabelIsSubView = sut.locationLabel?.isDescendant(of: sut.view) ?? false XCTAssertTrue(locationLabelIsSubView) } func test_HasDescriptionLabel() { let descriptionLabelIsSubView = sut.descriptionLabel?.isDescendant(of: sut.view) ?? false XCTAssertTrue(descriptionLabelIsSubView) } }
// // NetworkClient.swift // Grimoire // // Created by Hesham Salman on 7/12/16. // import Foundation protocol NetworkClient { func performRequest(method: HTTPMethod, path: String, parameters: [String: AnyObject]?, callback: ((success: Bool, response: AnyObject?) -> Void)?) func fetchData(URL: NSURL, callback: (result: NetworkClientResult<NSData, NSError>) -> Void) } enum NetworkClientResult<Type, Error: ErrorType> { case Success(Type) case Failure(ErrorType) }
// // NSControl+Rx.swift // GoogleMusicClientMacOS // // Created by Anton Efimenko on 23/04/2019. // Copyright © 2019 Anton Efimenko. All rights reserved. // import Cocoa import RxSwift import RxCocoa extension Reactive where Base: NSControl { var clicked: ControlEvent<NSEvent> { let source = self.methodInvoked(#selector(Base.mouseDown)).map { $0.first as! NSEvent }.takeUntil(self.deallocated).share() return ControlEvent(events: source) } var mouseEntered: ControlEvent<NSEvent> { self.base.setupTrackingArea() let source = self.methodInvoked(#selector(Base.mouseEntered)).map { $0.first as! NSEvent }.takeUntil(self.deallocated).share() return ControlEvent(events: source) } var mouseExited: ControlEvent<NSEvent> { self.base.setupTrackingArea() let source = self.methodInvoked(#selector(Base.mouseExited)).map { $0.first as! NSEvent }.takeUntil(self.deallocated).share() return ControlEvent(events: source) } }
// // ViewController.swift // AR_APP // // Created by Yoki on 2017/10/29. // Copyright © 2017年 yoki. All rights reserved. // import UIKit import ARKit class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, ARSCNViewDelegate { @IBOutlet weak var itemCollectionView: UICollectionView! @IBOutlet weak var mainSceneView: ARSCNView! let configuration = ARWorldTrackingConfiguration() var selectedItem: String? let itemsArray: [String] = ["wine_glass","cup"] override func viewDidLoad() { super.viewDidLoad() initialize() registerGestureRecognizers() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func initialize (){ //ARSCNiew初期化 self.mainSceneView.debugOptions = [ARSCNDebugOptions.showWorldOrigin, ARSCNDebugOptions.showFeaturePoints] self.configuration.planeDetection = .horizontal self.mainSceneView.session.run(configuration) self.mainSceneView.delegate = self self.mainSceneView.autoenablesDefaultLighting = true self.itemCollectionView.dataSource = self self.itemCollectionView.delegate = self } func registerGestureRecognizers() { let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapped)) self.mainSceneView.addGestureRecognizer(tapGestureRecognizer) } @objc func tapped(sender: UITapGestureRecognizer) { let sceneView = sender.view as! ARSCNView let tapLocation = sender.location(in: sceneView) let hitTest = sceneView.hitTest(tapLocation, types: .existingPlaneUsingExtent) if !hitTest.isEmpty { self.addItem(hitTestResult: hitTest.first!) } } func addItem(hitTestResult: ARHitTestResult) { if let selectedItem = self.selectedItem { let scene = SCNScene(named: "Models.scnassets/\(selectedItem).scn") let node = (scene?.rootNode.childNode(withName: selectedItem, recursively: false))! let transform = hitTestResult.worldTransform let thirdColumn = transform.columns.3 node.position = SCNVector3(thirdColumn.x, thirdColumn.y, thirdColumn.z) self.mainSceneView.scene.rootNode.addChildNode(node) } } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return itemsArray.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "item", for: indexPath) as! itemCell cell.itemLabel.text = self.itemsArray[indexPath.row] return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let cell = collectionView.cellForItem(at: indexPath) self.selectedItem = itemsArray[indexPath.row] cell?.backgroundColor = UIColor.orange } func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) { let cell = collectionView.cellForItem(at: indexPath) cell?.backgroundColor = UIColor.green } }
// // OnlyVisibleTableViewCell.swift // Bottle // // Created by Will Schreiber on 6/14/17. // Copyright © 2017 lxv. All rights reserved. // import UIKit class OnlyVisibleTableViewCell: BTTableViewCell { @IBOutlet var visibleTo: UILabel! 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 } override func setupViews() { self.visibleTo.layer.cornerRadius = 4.0 self.visibleTo.clipsToBounds = true if let message = self.message { self.visibleTo.isHidden = !message.onlyVisibleByMe() } } }
// // HomeViewController.swift // Lilac12k // // Created by Kaitlin Anderson on 2/4/16. // Copyright © 2016 codemysource. All rights reserved. // import UIKit import Foundation import Darwin class HomeViewController : UIViewController{ @IBOutlet weak var scroller: UIScrollView! @IBOutlet weak var days: UILabel! @IBOutlet weak var hours: UILabel! @IBOutlet weak var minutes: UILabel! @IBOutlet weak var welcomeMessage: UILabel! @IBOutlet var scrollView: UIScrollView! @IBOutlet var textView: UITextView! @IBOutlet var startButton: UIButton! var timer = NSTimer(); @IBOutlet weak var Schedule: UIButton! @IBOutlet weak var Parking: UIButton! @IBOutlet weak var TrainingTips: UIButton! @IBOutlet weak var Registration: UIButton! @IBOutlet weak var Bloomsday40: UIButton! @IBOutlet weak var FAQ: UIButton! @IBAction func Schedule(sender: AnyObject) { if let url = NSURL(string: "http://bloomsdayrun.org/race-information/weekend-schedule") { UIApplication.sharedApplication().openURL(url) } } @IBAction func Parking(sender: AnyObject) { if let url = NSURL(string: "http://www.downtownspokane.org/documents/ParkingMap2010.pdf") { UIApplication.sharedApplication().openURL(url) } } @IBAction func TrainingTips(sender: AnyObject) { if let url = NSURL(string: "http://bloomsdayrun.org/training/training-program") { UIApplication.sharedApplication().openURL(url) } } @IBAction func Registration(sender: AnyObject) { if let url = NSURL(string: "http://bloomsdayrun.org/registration/register-online") { UIApplication.sharedApplication().openURL(url) } } @IBAction func Bloomsday40(sender: AnyObject) { if let url = NSURL(string: "http://bloomsdayrun.org/40th-year-video") { UIApplication.sharedApplication().openURL(url) } } @IBAction func FAQ(sender: AnyObject) { if let url = NSURL(string: "http://bloomsdayrun.org/faq") { UIApplication.sharedApplication().openURL(url) } } override func viewDidLoad() { print("HOMEVIEWCONTROLLER") timer = NSTimer.scheduledTimerWithTimeInterval(60.0, target: self, selector: #selector(HomeViewController.update), userInfo: nil, repeats: true) super.viewDidLoad() setCountdownText() self.scroller.contentSize.height = 4000; } func setCountdownText() { let bloomsdayDate = 1462118400.0 //9:00 AM, May 1, 2016 (4:00 PM UTC) let timeLeft = Int( bloomsdayDate - NSDate().timeIntervalSince1970 ) // s / (60*60*24) is whole days, then take remainder and divide by 3600 to get hours, then find minutes let (d,h,m) = (timeLeft / (3600*24), (timeLeft % (3600*24)) / 3600, (timeLeft % 3600) / 60) days.text = String(format: "%02d", max(d,0)) hours.text = String(format: "%02d", max(h,0)) minutes.text = String(format: "%02d", max(m,0)) } override func viewDidLayoutSubviews() { scroller.scrollEnabled = true } func update() { //Update countdown each minute setCountdownText() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func scrollViewDidEndDecelerating(scrollView: UIScrollView){ // Test the offset and calculate the current page after scrolling ends } }
import Foundation import UIKit enum ColorGroup { case neutral case lightBlue case darkBlue case burple case orange case green } struct Color { // MARK: Common colors static func defaultFontColor() -> UIColor { return slate() } static func defaultBackground() -> UIColor { return Color.white() } static func defaultBorderColor() -> UIColor { return Color.colorFromHex(0xE6E6E6) } // MARK: Category specific colors static func shamrock() -> UIColor { return colorFromHex(0x47DDB2) } static func gold() -> UIColor { return colorFromHex(0xFFBD25) } static func rose() -> UIColor { return colorFromHex(0xC26B84) } static func lavender() -> UIColor { return colorFromHex(0xAE85D4) } static func red() -> UIColor { return colorFromHex(0xFC5D77) } static func yellow() -> UIColor { return colorFromHex(0xF4BF55) } static func blue() -> UIColor { return colorFromHex(0x0A9ED8) } static func green() -> UIColor { return colorFromHex(0x00B1A6) } static func lilac() -> UIColor { return colorFromHex(0x7F7CBA) } static func fuchsia() -> UIColor { return colorFromHex(0xB5487A) } // MARK: Interest colors static func dislikeRed() -> UIColor { return colorFromHex(0xFF5454) } // MARK: Neutral static func n0() -> UIColor { return colorFromHex(0xF1F3F8) } static func n1() -> UIColor { return colorForGroup(.neutral, level: 1) } static func n2() -> UIColor { return colorForGroup(.neutral, level: 2) } static func n3() -> UIColor { return colorForGroup(.neutral, level: 3) } static func n4() -> UIColor { return colorForGroup(.neutral, level: 4) } static func n5() -> UIColor { return colorForGroup(.neutral, level: 5) } static func n6() -> UIColor { return colorForGroup(.neutral, level: 6) } static func n7() -> UIColor { return colorForGroup(.neutral, level: 7) } static func n8() -> UIColor { return colorForGroup(.neutral, level: 8) } static func n9() -> UIColor { return colorForGroup(.neutral, level: 9) } static func n10() -> UIColor { return colorForGroup(.neutral, level: 10) } // MARK: Light Blue static func lb1() -> UIColor { return colorForGroup(.lightBlue, level: 1) } static func lb2() -> UIColor { return colorForGroup(.lightBlue, level: 2) } static func lb3() -> UIColor { return colorForGroup(.lightBlue, level: 3) } static func lb4() -> UIColor { return colorForGroup(.lightBlue, level: 4) } static func lb5() -> UIColor { return colorForGroup(.lightBlue, level: 5) } static func lb7() -> UIColor { return colorForGroup(.lightBlue, level: 7) } static func lb8() -> UIColor { return colorForGroup(.lightBlue, level: 8) } static func lb9() -> UIColor { return colorForGroup(.lightBlue, level: 9) } // MARK: Dark Blue static func db2() -> UIColor { return colorForGroup(.darkBlue, level: 2) } static func db4() -> UIColor { return colorForGroup(.darkBlue, level: 4) } static func db5() -> UIColor { return colorForGroup(.darkBlue, level: 5) } static func db6() -> UIColor { return colorForGroup(.darkBlue, level: 6) } static func db9() -> UIColor { return colorForGroup(.darkBlue, level: 9) } // MARK: Burple static func bu1() -> UIColor { return colorForGroup(.burple, level: 1) } static func bu2() -> UIColor { return colorForGroup(.burple, level: 2) } static func bu3() -> UIColor { return colorForGroup(.burple, level: 3) } static func bu4() -> UIColor { return colorForGroup(.burple, level: 4) } static func bu5() -> UIColor { return colorForGroup(.burple, level: 5) } // MARK: Orange static func o5() -> UIColor { return colorForGroup(.orange, level: 5) } static func o6() -> UIColor { return colorForGroup(.orange, level: 6) } static func o9() -> UIColor { return colorForGroup(.orange, level: 9) } // MARK: Green static func g4() -> UIColor { return colorForGroup(.green, level: 4) } static func g5() -> UIColor { return colorForGroup(.green, level: 5) } // MARK: Basic static func clear() -> UIColor { return UIColor.clear } static func white() -> UIColor { return UIColor.white } static func black(_ alpha: CGFloat = 1) -> UIColor { return UIColor.black.withAlphaComponent(alpha) } static func beige() -> UIColor { return colorFromHex(0xCAAB56) } static func offBlack() -> UIColor { return onyx() } static func onyx() -> UIColor { return colorFromHex(0x35464B) } static func darkGray() -> UIColor { return colorFromHex(0x979797) } static func gray() -> UIColor { return colorFromHex(0x8EA4AD) } static func lightGray() -> UIColor { return colorFromHex(0xCBD1D4) } static func lighterGray() -> UIColor { return colorFromHex(0xF0F7F9) } static func darkGreen() -> UIColor { return colorFromHex(0x19485D) } static func offWhite() -> UIColor { return colorFromHex(0xEEF3F5)} static func turquoise() -> UIColor { return colorFromHex(0x00B1A6) } static func logoShadow() -> UIColor { return colorFromHex(0x0F3F59) } static func tabBarUnSelectedTint() -> UIColor { return colorFromHex(0xA9C5CE) } static func blueGray() -> UIColor { return colorFromHex(0x3D5055, alpha: 0.75) } static func burple() -> UIColor { return colorFromHex(0x8434D6) } static func slate() -> UIColor { return colorFromHex(0x333333) } static func facebookBlue() -> UIColor { return colorFromHex(0x3b5998) } static func colorForGroup(_ group: ColorGroup, level: Int) -> UIColor { let groupDictionary = palette[group]! let hex = groupDictionary[level]! return self.colorFromHex(hex) } static func colorFromHex(_ hex: Int, alpha: CGFloat = 1) -> UIColor { // convert the # color string to RGBA 0-1 values // for example: // 0xFFFF00 would translate to: // 1.0f red // 1.0f green // 0.0f blue // let red = CGFloat((hex & 0xFF0000) >> 16) / 255.0 let green = CGFloat((hex & 0x00FF00) >> 8) / 255.0 let blue = CGFloat(hex & 0x0000FF) / 255.0 return UIColor(red: red, green: green, blue: blue, alpha: alpha) } static var palette: [ColorGroup : [Int : Int]] = [ .lightBlue: [ 1: 0x002330, 2: 0x004561, 3: 0x006891, 4: 0x008AC2, 5: 0x00ADF2, 7: 0x61CEF7, 8: 0x97DFFB, 9: 0xD3F2FE ], .darkBlue: [ 2: 0x00202D, 4: 0x003F58, 5: 0x00506F, 6: 0x2F728B, 9: 0xCBDCE2 ], .burple: [ 1: 0xF2EAFA, 2: 0xAF79E9, 3: 0x8434D6, 4: 0x6105C4, 5: 0x5702AF ], .neutral: [ 1: 0x394245, 2: 0x556367, 3: 0x708389, 4: 0x8EA4AD, 5: 0xA9C5CE, 6: 0xB9D1D9, 7: 0xCBDCE3, 8: 0xDCE8EC, 9: 0xEEF3F5, 10: 0xF5F9FA ], .orange: [ 5: 0xFF8600, 6: 0xFF9E1E, 9: 0xFFE8CB ], .green: [ 4: 0x009F65, 5: 0x00C87B ] ] } extension UIColor { func isWhite() -> Bool { return self == Color.white() } func withAlpha(_ alpha: CGFloat) -> UIColor { return self.withAlphaComponent(alpha) } }
// // TableCellBasicData.swift // TSupportLibrary // // Created by Matteo Corradin on 28/05/18. // Copyright © 2018 Matteo Corradin. All rights reserved. // import Foundation import UIKit public struct TableCellBasicData { public let color: UIColor public let secondaryColor: UIColor public let text: String }
// // MineBankViewModel.swift // SpecialTraining // // Created by 徐军 on 2018/12/4. // Copyright © 2018年 youpeixun. All rights reserved. // import UIKit import RxSwift class MineBankViewModel: BaseViewModel { var datasource = Variable([MineBankModel]()) override init() { super.init() datasource.value = [MineBankModel(),MineBankModel(),MineBankModel(),MineBankModel(),MineBankModel()] } }
// // HistoryRouter.swift // GoingPlaces // // Created by Morgan Collino on 11/8/17. // Copyright © 2017 Morgan Collino. All rights reserved. // import Foundation import UIKit final class HistoryRouter { func routeToHistory(navigationController: UINavigationController?, mainPresenter: MainPresenter) { let builder = HistoryBuilder() guard let viewController = builder.build(with: mainPresenter) else { // Could not build History view controller. return } navigationController?.pushViewController(viewController, animated: true) } func routeBack(navigationController: UINavigationController?) { navigationController?.popViewController(animated: true) } }
// // PlayerView.swift // Janken // // Created by Rplay on 30/10/2016. // Copyright © 2016 rplay. All rights reserved. // import Foundation import UIKit class PlayerView: UIView { //-- Global var unowned var newGame: Janken var player: JankenPlayer var playerNameLabel: UILabel var chooseYourWeaponLabel: UILabel var weaponChooseLabel: UILabel var weaponCollection: UICollectionView var validateButton: UIButton var weaponsAvailables: Array<Weapon> = [] init(frame: CGRect, newGame: Janken, player: JankenPlayer) { //-- Set global var self.newGame = newGame self.player = player self.playerNameLabel = UILabel() self.chooseYourWeaponLabel = UILabel() self.weaponChooseLabel = UILabel() self.validateButton = UIButton() //-- Collection View needs a Layout let collectionLayout: UICollectionViewFlowLayout = UICollectionViewFlowLayout() collectionLayout.scrollDirection = .horizontal collectionLayout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10) collectionLayout.itemSize = CGSize(width: 80, height: 80) collectionLayout.minimumLineSpacing = 10 self.weaponCollection = UICollectionView(frame: CGRect(x: 0, y: 0, width: 0, height: 0), collectionViewLayout: collectionLayout) //-- Init superclass super.init(frame: frame) //-- Add action to validateButton self.validateButton.addTarget(self, action: #selector(self.validateAction(sender:)), for: .touchUpInside) //-- Delegate & Datasource for weaponCollection self.weaponCollection.dataSource = self self.weaponCollection.delegate = self //-- Display elements in view self.structureView() //-- Get weapons self.getWeaponsAvailables() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } internal func getWeaponsAvailables() { guard let weapons = newGame.weapons else { return } for weapon in weapons { self.weaponsAvailables.append(weapon) } } internal func validateAction(sender: UIButton) { if self.player.id == newGame.players?.last?.id { //-- All players played. Definie winners self.newGame.referee.defineWinners(players: self.newGame.players!) } //-- Remove this view UIView.animate(withDuration: 0.25, animations: { self.alpha = 0.0 }, completion: { completed in self.removeFromSuperview() }) } internal func structureView() { //-- This view self.backgroundColor = UIColor.white self.alpha = 0.0 //-- Player name label self.playerNameLabel.text = player.name self.playerNameLabel.textColor = Design.colors.lightBlue self.playerNameLabel.font = UIFont.boldSystemFont(ofSize: 24.0) self.playerNameLabel.sizeToFit() self.playerNameLabel.frame.origin = CGPoint(x: self.frame.width / 2 - self.playerNameLabel.frame.width / 2, y: 100) self.addSubview(playerNameLabel) //-- Choose your weapon label self.chooseYourWeaponLabel.text = "Choose your weapon" self.chooseYourWeaponLabel.font = UIFont.boldSystemFont(ofSize: 18.0) self.chooseYourWeaponLabel.sizeToFit() self.chooseYourWeaponLabel.frame.origin = CGPoint(x: self.frame.width / 2 - self.chooseYourWeaponLabel.frame.width / 2, y: self.playerNameLabel.frame.origin.y + self.playerNameLabel.frame.height + 20) self.addSubview(chooseYourWeaponLabel) //-- Validate Button Design.button(button: self.validateButton, callToAction: true) self.validateButton.frame = CGRect(x: 20, y: self.frame.height - 20 - 50, width: self.frame.width - 40, height: 50) self.validateButton.setTitle("Validate", for: .normal) self.addSubview(validateButton) //-- Weapon collection self.weaponCollection.frame = CGRect(x: 0, y: self.validateButton.frame.origin.y - self.validateButton.frame.height - 20 - 50, width: self.frame.width, height: 100) self.weaponCollection.register(WeaponCollectionCell.self, forCellWithReuseIdentifier: "weapon_collection_cell") self.weaponCollection.backgroundColor = UIColor(white: 1.0, alpha: 0.5) self.addSubview(weaponCollection) //-- Weapon choose label self.weaponChooseLabel.font = UIFont.boldSystemFont(ofSize: 24.0) self.weaponChooseLabel.frame = CGRect(x: 0, y: self.weaponCollection.frame.origin.y - 60, width: self.frame.width, height: 40) self.weaponChooseLabel.textAlignment = .center self.addSubview(weaponChooseLabel) UIView.animate(withDuration: 0.25, animations: { self.alpha = 1.0 }) } } extension PlayerView: UICollectionViewDataSource, UICollectionViewDelegate { internal func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { //-- Return nb weapons return weaponsAvailables.count } internal func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { //-- Create cell let collectionViewCell: WeaponCollectionCell = collectionView.dequeueReusableCell(withReuseIdentifier: "weapon_collection_cell", for: indexPath) as! WeaponCollectionCell collectionViewCell.weapon = weaponsAvailables[indexPath.row] //-- Pre-select the first cell if !collectionViewCell.isSelected && indexPath.row == 0 { self.player.weaponChoose = weaponsAvailables[0] self.weaponChooseLabel.text = weaponsAvailables[0].name collectionViewCell.layer.borderWidth = 4 collectionViewCell.layer.borderColor = Design.colors.blue.cgColor } return collectionViewCell } internal func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { //-- Change text and add borders for selected row self.player.weaponChoose = weaponsAvailables[indexPath.row] self.weaponChooseLabel.text = weaponsAvailables[indexPath.row].name for cell in collectionView.visibleCells { cell.layer.borderWidth = 0 } collectionView.cellForItem(at: indexPath)?.layer.borderWidth = 4 collectionView.cellForItem(at: indexPath)?.layer.borderColor = Design.colors.blue.cgColor } internal func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) { collectionView.cellForItem(at: indexPath)?.layer.borderWidth = 0 } }
// // MyCollectionVC.swift // testDinamicTableView // // Created by 백승엽 on 2020/11/23. // import Foundation import UIKit class MyCollectionVC: UIViewController { @IBOutlet var mySegmentControl: UISegmentedControl! @IBOutlet var myCollectionView: UICollectionView! fileprivate let systemImageNameArray = [ "moon", "zzz", "sparkles", "cloud", "tornado", "smoke.fill", "tv.fill", "gamecontroller", "headphones", "flame", "bolt.fill", "hare", "tortoise", "moon", "zzz", "sparkles", "cloud", "tornado", "smoke.fill", "tv.fill", "gamecontroller", "headphones", "flame", "bolt.fill", "hare", "tortoise", "ant", "hare", "car", "airplane", "heart", "bandage", "waveform.path.ecg", "staroflife", "bed.double.fill", "signature", "bag", "cart", "creditcard", "clock", "alarm", "stopwatch.fill", "timer" ] //MARK: - Lifecyles override func viewDidLoad() { super.viewDidLoad() print("MyCollectionVC - viewDidLoad() called") // 컬렉션뷰에 대한 설정 myCollectionView.autoresizingMask = [.flexibleWidth, .flexibleHeight] myCollectionView.dataSource = self myCollectionView.delegate = self // 데이터에 따른 셀 UI 변경 // 3. Nib 파일로 만들어서 제공하기 (사용할 컬렉션뷰 셀을 등록) // Nib파일을 가져옴 let myCustomCollectionViewCellNib = UINib(nibName: String(describing: MyCustomCollectionViewCell.self), bundle: nil) // 가져온 Nib파일로 컬렉션뷰에 셀로 등록 self.myCollectionView.register(myCustomCollectionViewCellNib, forCellWithReuseIdentifier: String(describing: MyCustomCollectionViewCell.self)) // 등록 이후 DataSource 설정 // ----- FlowView // 컬렉션뷰의 컬렉션뷰 레이아웃을 설정 self.myCollectionView.collectionViewLayout = createCompositionalLayoutForFirst() } @IBAction func onCollectionViewTypeChanged(_ sender: UISegmentedControl) { print("MyCollectionVC - onCollectionViewTypeChanged() called / sender : \(sender.selectedSegmentIndex)") switch sender.selectedSegmentIndex { case 0: // 테이블뷰 형태 self.myCollectionView.collectionViewLayout = createCompositionalLayoutForFirst() case 1: // 2 x 2 그리드 형태 self.myCollectionView.collectionViewLayout = createCompositionalLayoutForSecond() case 2: // 3 x 3 그리드 형태 self.myCollectionView.collectionViewLayout = createCompositionalLayoutForThird() default: break } } } //MARK: - 컬렉션뷰 콤포지셔널 레이아웃 관련 extension MyCollectionVC { // 콤포지셔널 레이아웃 설정 fileprivate func createCompositionalLayoutForFirst() -> UICollectionViewLayout { print("createCompositionalLayoutForFirst() called") // 콤포지셔널 레이아웃 생성 let layout = UICollectionViewCompositionalLayout { // 만들게 되면 튜플 (키: 값, 키: 값)의 묶음으로 들어옴 반환 하는 것은 NSCollectionLayoutSection 컬렉션 레이아웃 섹션을 반환해야함. (sectionIndex: Int, layoutEnvironment: NSCollectionLayoutEnvironment) -> NSCollectionLayoutSection? in // 아이템에 대한 사이즈 - absolute는 고정값, estimated는 추측, freaction 퍼센트 // .fractionalWidth(1.0) 가로 100% (1/3) 3분의1 let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .fractionalHeight(1.0)) // 위에서 만든 아이템 사이즈로 아이템 만들기 let item = NSCollectionLayoutItem(layoutSize: itemSize) // 아이템 사이 간격 설정 item.contentInsets = NSDirectionalEdgeInsets(top: 2, leading: 2, bottom: 2, trailing: 2) // 변경될 height 변수화 let groupHeight = NSCollectionLayoutDimension.fractionalWidth(1/3) // 그룹 사이즈 let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: groupHeight) // 그룹 사이즈로 그룹 만들기 let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitem: item, count: 1) // let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitems: [item, item, item]) // 그룹으로 섹션 만들기 let section = NSCollectionLayoutSection(group: group) // section.orthogonalScrollingBehavior = .continuous // section.orthogonalScrollingBehavior = .groupPaging // 섹션에 대한 간격 설정 section.contentInsets = NSDirectionalEdgeInsets(top: 20, leading: 20, bottom: 20, trailing: 20) return section } return layout } // 콤포지셔널 레이아웃 설정 fileprivate func createCompositionalLayoutForSecond() -> UICollectionViewLayout { print("createCompositionalLayoutForSecond() called") // 콤포지셔널 레이아웃 생성 let layout = UICollectionViewCompositionalLayout { // 만들게 되면 튜플 (키: 값, 키: 값)의 묶음으로 들어옴 반환 하는 것은 NSCollectionLayoutSection 컬렉션 레이아웃 섹션을 반환해야함. (sectionIndex: Int, layoutEnvironment: NSCollectionLayoutEnvironment) -> NSCollectionLayoutSection? in // 아이템에 대한 사이즈 - absolute는 고정값, estimated는 추측, freaction 퍼센트 // .fractionalWidth(1.0) 가로 100% (1/3) 3분의1 let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .fractionalHeight(1.0)) // 위에서 만든 아이템 사이즈로 아이템 만들기 let item = NSCollectionLayoutItem(layoutSize: itemSize) // 아이템 사이 간격 설정 item.contentInsets = NSDirectionalEdgeInsets(top: 2, leading: 2, bottom: 2, trailing: 2) // 변경될 height 변수화 let groupHeight = NSCollectionLayoutDimension.fractionalWidth(1/3) // 그룹 사이즈 let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: groupHeight) // 그룹 사이즈로 그룹 만들기 let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitem: item, count: 2) // let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitems: [item, item, item]) // 그룹으로 섹션 만들기 let section = NSCollectionLayoutSection(group: group) // section.orthogonalScrollingBehavior = .continuous // section.orthogonalScrollingBehavior = .groupPaging // 섹션에 대한 간격 설정 section.contentInsets = NSDirectionalEdgeInsets(top: 20, leading: 20, bottom: 20, trailing: 20) return section } return layout } // 콤포지셔널 레이아웃 설정 fileprivate func createCompositionalLayoutForThird() -> UICollectionViewLayout { print("createCompositionalLayoutForThird() called") // 콤포지셔널 레이아웃 생성 let layout = UICollectionViewCompositionalLayout { // 만들게 되면 튜플 (키: 값, 키: 값)의 묶음으로 들어옴 반환 하는 것은 NSCollectionLayoutSection 컬렉션 레이아웃 섹션을 반환해야함. (sectionIndex: Int, layoutEnvironment: NSCollectionLayoutEnvironment) -> NSCollectionLayoutSection? in // 아이템에 대한 사이즈 - absolute는 고정값, estimated는 추측, freaction 퍼센트 // .fractionalWidth(1.0) 가로 100% (1/3) 3분의1 let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .fractionalHeight(1.0)) // 위에서 만든 아이템 사이즈로 아이템 만들기 let item = NSCollectionLayoutItem(layoutSize: itemSize) // 아이템 사이 간격 설정 item.contentInsets = NSDirectionalEdgeInsets(top: 2, leading: 2, bottom: 2, trailing: 2) // 변경될 height 변수화 let groupHeight = NSCollectionLayoutDimension.fractionalWidth(1/3) // 그룹 사이즈 let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: groupHeight) // 그룹 사이즈로 그룹 만들기 let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitem: item, count: 3) // let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitems: [item, item, item]) // 그룹으로 섹션 만들기 let section = NSCollectionLayoutSection(group: group) // section.orthogonalScrollingBehavior = .continuous // section.orthogonalScrollingBehavior = .groupPaging // 섹션에 대한 간격 설정 section.contentInsets = NSDirectionalEdgeInsets(top: 20, leading: 20, bottom: 20, trailing: 20) return section } return layout } } // 데이터 소스 설정 - 데이터와 관련된 것들 extension MyCollectionVC: UICollectionViewDataSource { // 각 섹션에 들어가는 아이템 개수 func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.systemImageNameArray.count } // 각 컬렉션뷰 셀에 대한 설정 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { // 객체 인스턴스의 이름을 가져와서 cellId로 설정 let cellId = String(describing: MyCollectionViewCell.self) print("cellId: \(cellId)") // 셀의 인스턴스 - 1, 2 // let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! MyCollectionViewCell // 셀의 인스턴스 - 3 let cell = collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: MyCustomCollectionViewCell.self), for: indexPath) as! MyCustomCollectionViewCell // 데이터에 따른 셀 UI 변경 // 1. 컨트롤러에서 직접 만들기 // 이미지에 대한 설정 // cell.profileImg.image = UIImage(systemName: self.systemImageNameArray[indexPath.item]) // // 라벨 설정 // cell.profileLabel.text = self.systemImageNameArray[indexPath.item] // cell.contentView.backgroundColor = #colorLiteral(red: 0.9764705896, green: 0.850980401, blue: 0.5490196347, alpha: 1) // cell.contentView.layer.cornerRadius = 8 // cell.contentView.layer.borderWidth = 1 // cell.contentView.layer.borderColor = #colorLiteral(red: 0.3647058904, green: 0.06666667014, blue: 0.9686274529, alpha: 1) // 데이터에 따른 셀 UI 변경 // 2. Cell을 관리하는 별도의 파일로 분리하여 만들기 // 데이터에 따른 셀 UI 변경을 MyCollectionViewCell.swift 에서 직접 할 수도 있음 // MyCollectionViewCell.swift 에서 작업 이후 cell.imageName = self.systemImageNameArray[indexPath.item] return cell } } // 컬렉션뷰 델리겟 - 액션과 관련된 것들 extension MyCollectionVC: UICollectionViewDelegate { }
// // SignupViewController.swift // ThatDubaiGirl // // Created by Bozo Krkeljas on 7.12.20.. // import UIKit import Photos class SignupViewController: UIViewController { @IBOutlet weak var ivProfile: UIImageView! @IBOutlet weak var tfUserName: UITextField! @IBOutlet weak var tfUserMail: UITextField! @IBOutlet weak var tfBirthday: UITextField! @IBOutlet weak var tfAddress: UITextField! @IBOutlet weak var tfPassword: UITextField! @IBOutlet weak var tfConfirm: UITextField! var isPhotoSelected: Bool = false public var userMail: String! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. tfUserMail.text = userMail tfBirthday.setDatePicker(target: self, selector: #selector(tapDone)) let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageTapped(tapGestureRecognizer:))) ivProfile.addGestureRecognizer(tapGestureRecognizer) } override func viewDidLayoutSubviews() { ivProfile.layer.cornerRadius = ivProfile.frame.size.width / 2 } @IBAction func onBack(_ sender: Any) { self.navigationController?.popViewController(animated: true) } @objc func imageTapped(tapGestureRecognizer: UITapGestureRecognizer) { self.getImageData() } func getImageData() { let alertController = UIAlertController(title: "Choose Image", message: nil, preferredStyle: .actionSheet) alertController.addAction(UIAlertAction(title: "Camera", style: .default, handler: { _ in self.openImagePicker(sourceType: UIImagePickerController.SourceType.camera) })) alertController.addAction(UIAlertAction(title: "Photo Gallery", style: .default, handler: { _ in self.openImagePicker(sourceType: UIImagePickerController.SourceType.photoLibrary) })) alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) self.present(alertController, animated: true) } func openImagePicker(sourceType: UIImagePickerController.SourceType) { switch sourceType { case UIImagePickerController.SourceType.camera: isCameraPermissionAuthorized(objViewController: self) { (isAuthorized) in if isAuthorized { DispatchQueue.main.async { if (UIImagePickerController.isSourceTypeAvailable(.camera)) { let objImagePicker = UIImagePickerController() UINavigationBar.appearance().tintColor = UIColor.white objImagePicker.allowsEditing = true objImagePicker.delegate = self objImagePicker.sourceType = sourceType//.photoLibrary objImagePicker.mediaTypes = ["public.image"] //,String(kUTTypeVideo),String(kUTTypeMPEG4) objImagePicker.videoQuality = .typeIFrame960x540//.typeIFrame1280x720 //iFrame960x540 self.navigationController?.present(objImagePicker, animated: true, completion: nil) } } } } break case UIImagePickerController.SourceType.photoLibrary: isPhotoPermissionAuthorized(objViewController: self) { (isAuthorized) in if isAuthorized { DispatchQueue.main.async { if (UIImagePickerController.isSourceTypeAvailable(.photoLibrary)) { let objImagePicker = UIImagePickerController() UINavigationBar.appearance().tintColor = UIColor.white objImagePicker.allowsEditing = true objImagePicker.delegate = self objImagePicker.sourceType = sourceType//.photoLibrary objImagePicker.mediaTypes = ["public.image"] //,String(kUTTypeVideo),String(kUTTypeMPEG4) objImagePicker.videoQuality = .typeIFrame960x540//.typeIFrame1280x720 //iFrame960x540 self.navigationController?.present(objImagePicker, animated: true, completion: nil) } } } } break default: break } } func isCameraPermissionAuthorized(objViewController: UIViewController, completion:@escaping ((Bool) -> Void)) { let status = AVCaptureDevice.authorizationStatus(for: .video) switch status { case .authorized: completion(true) break case .notDetermined: AVCaptureDevice.requestAccess(for: .video, completionHandler: { (granted) in if granted { completion(true) } else { completion(false) } }) break case .denied, .restricted: let strMessage: String = "Please allow access to your photos." let alertController = UIAlertController(title: "ThatDubaiGirl", message: strMessage, preferredStyle: .alert) let cancelAction = UIAlertAction(title: "Ok", style: .default) { action in self.dismiss(animated: true, completion: nil) } alertController.addAction(cancelAction) self.present(alertController, animated: true) break default: completion(false) break } } func isPhotoPermissionAuthorized(objViewController: UIViewController, completion:@escaping ((Bool) -> Void)) { let status = PHPhotoLibrary.authorizationStatus() switch status { case .authorized: completion(true) break case .notDetermined: PHPhotoLibrary.requestAuthorization({ (newStatus) in if newStatus == PHAuthorizationStatus.authorized { completion(true) } else { completion(false) } }) break case .denied, .restricted: let strMessage: String = "Please allow access to your photos." let alertController = UIAlertController(title: "ThatDubaiGirl", message: strMessage, preferredStyle: .alert) let cancelAction = UIAlertAction(title: "Ok", style: .default) { action in self.dismiss(animated: true, completion: nil) } alertController.addAction(cancelAction) self.present(alertController, animated: true) break default: completion(false) break } } @objc func tapDone() { if let datePicker = self.tfBirthday.inputView as? UIDatePicker { let dateformatter = DateFormatter() dateformatter.dateFormat = "dd-MM-yyyy" self.tfBirthday.text = dateformatter.string(from: datePicker.date) } self.tfBirthday.resignFirstResponder() } @IBAction func onSignup(_ sender: Any) { if !isPhotoSelected { UIManager.shared.showAlert(vc: self, title: "ThatDubaiGirl", message: "Please select profile picture.") return } guard let name = tfUserName.text, !name.isEmpty else { UIManager.shared.showAlert(vc: self, title: "", message: "Please input name.") return } guard let email = tfUserMail.text, !email.isEmpty else { UIManager.shared.showAlert(vc: self, title: "", message: "Please input email address.") return } if (!DataManager.isValidEmail(email)) { UIManager.shared.showAlert(vc: self, title: "", message: "Invalid email address.") return } guard let address = tfAddress.text, !address.isEmpty else { UIManager.shared.showAlert(vc: self, title: "", message: "Please input address.") return } guard let birthday = tfBirthday.text, !birthday.isEmpty else { UIManager.shared.showAlert(vc: self, title: "", message: "Please input birthday.") return } if (!DataManager.validateBirthday(birthday)) { UIManager.shared.showAlert(vc: self, title: "", message: "You must be at least 18 years of age to sign up.") return } guard let password = tfPassword.text, !password.isEmpty else { UIManager.shared.showAlert(vc: self, title: "", message: "Please input password.") return } guard let confirm = tfConfirm.text, !confirm.isEmpty else { UIManager.shared.showAlert(vc: self, title: "", message: "Please input password") return } if (password != confirm) { UIManager.shared.showAlert(vc: self, title: "", message: "The password doesn't match.") return } if password.count < 6 { UIManager.shared.showAlert(vc: self, title: "", message: "Password must be at least 6 characters.") return } UIManager.shared.showHUD(view: self.view) let formatter = DateFormatter() formatter.dateFormat = "dd-MM-yyyy" let date = formatter.date(from: birthday) formatter.dateFormat = "yyyy-MM-dd" let birthdayString = formatter.string(from: date!) APIManager.shared.signup(email, username: name, birthday: birthdayString, address: address, password: password, password_confirmation: confirm, image: self.ivProfile.image!) { (success, user, msg) in UIManager.shared.hideHUD() if success { UserDefaults.standard.setValue(user?.email, forKey: "email") UserDefaults.standard.setValue(password, forKey: "password") DataManager.currentUser = user self.performSegue(withIdentifier: "video", sender: nil) } else { UIManager.shared.showAlert(vc: self, title: "", message: msg!) } } } } extension UITextField { func setDatePicker(target: Any, selector: Selector) { // Create a UIDatePicker object and assign to inputView let screenWidth = UIScreen.main.bounds.width let datePicker = UIDatePicker(frame: CGRect(x: 0, y: 0, width: screenWidth, height: 216)) datePicker.datePickerMode = .date if #available(iOS 14, *) {// Added condition for iOS 14 datePicker.preferredDatePickerStyle = .wheels datePicker.sizeToFit() } self.inputView = datePicker // Create a toolbar and assign it to inputAccessoryView let toolBar = UIToolbar(frame: CGRect(x: 0.0, y: 0.0, width: screenWidth, height: 44.0)) let flexible = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) let cancel = UIBarButtonItem(title: "Cancel", style: .plain, target: nil, action: #selector(tapCancel)) let barButton = UIBarButtonItem(title: "Done", style: .plain, target: target, action: selector) toolBar.setItems([cancel, flexible, barButton], animated: false) self.inputAccessoryView = toolBar } @objc func tapCancel() { self.resignFirstResponder() } } extension SignupViewController: UINavigationControllerDelegate, UIImagePickerControllerDelegate { func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { // Local variable inserted by Swift 4.2 migrator. let info = convertFromUIImagePickerControllerInfoKeyDictionary(info) if let possibleImage = info["UIImagePickerControllerEditedImage"] as? UIImage { self.ivProfile.image = possibleImage.resize(targetSize: CGSize(width: 128, height: 128)) isPhotoSelected = true } else if let possibleImage = info["UIImagePickerControllerOriginalImage"] as? UIImage { self.ivProfile.image = possibleImage.resize(targetSize: CGSize(width: 128, height: 128)) isPhotoSelected = true } else { isPhotoSelected = false return } picker.dismiss(animated: true) } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { isPhotoSelected = false picker.dismiss(animated: true, completion: nil) } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertFromUIImagePickerControllerInfoKeyDictionary(_ input: [UIImagePickerController.InfoKey: Any]) -> [String: Any] { return Dictionary(uniqueKeysWithValues: input.map {key, value in (key.rawValue, value)}) } } extension UIImage { func resize(targetSize: CGSize) -> UIImage { return UIGraphicsImageRenderer(size:targetSize).image { _ in self.draw(in: CGRect(origin: .zero, size: targetSize)) } } }
// // UIView+XIBCreation.swift // SPUIKitCategory module // // Created by LSP on 2020/12/15. // Copyright © 2020 LSP. All rights reserved. // #if !os(macOS) import UIKit extension UIView { /// 从XIB文件(与类名相同的xib)初始化。 /// - Parameters: /// - nibName: 默认与类名相同 /// - owner: owner /// - bundle: mainBundle /// - Returns: 实例 public class func loadFromNib(_ nibName: String = "", owner: Any? = nil, bundle: Bundle = Bundle.main) -> Self? { let name = nibName.isEmpty ? String(describing: self) : nibName if let arr = bundle.loadNibNamed(name, owner: owner, options: nil) { for obj in arr { if let cls = obj as? NSObject, cls is Self { return cls as? Self } } } return nil } } #endif
// // _RequestBuilder+Casting.swift // August // // Created by Bradley Hilton on 7/26/16. // Copyright © 2016 Brad Hilton. All rights reserved. // extension _RequestBuilder { public func GET<T : DataInitializable>(_ type: T.Type) -> August.GET<T> { return August.GET(self) } public func POST<T : DataInitializable>(_ type: T.Type) -> August.POST<T> { return August.POST(self) } public func PUT<T : DataInitializable>(_ type: T.Type) -> August.PUT<T> { return August.PUT(self) } public func DELETE<T : DataInitializable>(_ type: T.Type) -> August.DELETE<T> { return August.DELETE(self) } public func PATCH<T : DataInitializable>(_ type: T.Type) -> August.PATCH<T> { return August.PATCH(self) } }
// // SetValueVC.swift // random // // Created by Andrew Foster on 2/22/17. // Copyright © 2017 Andrii Halabuda. All rights reserved. // import UIKit class CustomizeVC: UIViewController, UITextFieldDelegate { @IBOutlet weak var minTextField: CustomTextField! @IBOutlet weak var maxTextField: CustomTextField! override func viewDidLoad() { super.viewDidLoad() self.minTextField.delegate = self self.maxTextField.delegate = self self.minTextField.text = String(value1) self.maxTextField.text = String(value2) } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { self.view.endEditing(true) } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } @IBAction func minValueSet(_ sender: Any) { setMinValue() } @IBAction func maxValueSet(_ sender: Any) { setMaxValue() } @IBAction func doneBtnPressed(_ sender: UIButton) { navigationController?.popViewController(animated: true) } func setMinValue() { if minTextField.text == nil || minTextField.text == "" { value1 = 0 minTextField.text = String(value1) } else if Int(minTextField.text!)! > 999999999 { value1 = 999999999 minTextField.text = String(value1) } else { value1 = Int(minTextField.text!)! } } func setMaxValue() { if maxTextField.text == nil || maxTextField.text == "" { value2 = 99 maxTextField.text = String(value2) } else if Int(maxTextField.text!)! > 999999999 { value2 = 999999999 maxTextField.text = String(value2) } else { value2 = Int(maxTextField.text!)! } } }
// // ViewController.swift // Stardust // // Created by sakamoto kazuhiro on 2017/03/04. // Copyright © 2017年 Stardust. All rights reserved. // import UIKit import Argo class ViewController: UIViewController, PersonEventProtocol, CallEventProtocol { internal func childChanged(call: Call, key: String) { print("[change]\(key):{\(call)}") } internal func childAdd(call: Call, key: String) { print("[add]\(key):{\(call)}") } internal func childChanged(person: Decoded<Person>) { print("[change]person{\(person)}") } internal func childAdd(person: Decoded<Person>) { print("[add]person{\(person)}") } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. FirebaseAccessor.sharedInstance } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
// // slideInput.swift // Level // // Created by Nicholas Titzler on 5/18/21. // import SwiftUI struct slideInput: View { @State var input: Double = 0 var modelData: Array<Double> var body: some View { VStack { HStack { Slider(value: $input, in: 0...8, step:1) } Text("\(input, specifier: "%.0f")") } .padding() .accentColor(.blue) } } struct slideInput_Previews: PreviewProvider { static var previews: some View { slideInput(modelData: ModelData().mood_data) } }
// // main.swift // 协议 // // Created by yunna on 2020/4/3. // Copyright © 2020 yunna. All rights reserved. // import Foundation protocol MyProtocol { func mustProtocolMethod() //必须实现方法 func mustProtocolMethod1() //必须实现方法 } class MyClass: MyProtocol { func mustProtocolMethod() { print("MyClass-->必须实现方法:mustProtocolMethod") } func mustProtocolMethod1() { print("MyClass-->必须实现方法:mustProtocolMethod1") } } let cls = MyClass() cls.mustProtocolMethod() cls.mustProtocolMethod1() @objc protocol MyProtocol1 { @objc optional func optionalProtocolMethod() //可选方法 func mustProtocolMethod1() //必须实现方法 } class MyClass1: MyProtocol1 { func mustProtocolMethod1() { print("MyClass1-->必须实现方法:protocolMethod1") } } let cls1 = MyClass1() cls1.mustProtocolMethod1() protocol MyProtocol2 { func optionalProtocolMethod1() //可选方法 func optionalProtocolMethod2() //可选方法 func mustProtocolMethod1() //必须实现方法 } extension MyProtocol2{ func optionalProtocolMethod1(){ } func optionalProtocolMethod2(){ } }
//// //// CreateDefaultData.swift //// //// //// Created by Vũ Quý Đạt on 25/04/2021. //// // //import Foundation //import MongoKitten // //func createTestingUsersSM(inDatabase database: MongoDatabase) throws { // let userCount = try database[UserSM.collection].count().wait() // if userCount > 0 { // // The testing users have already been created // return // } // // let ray = try UserSM( // _id: ObjectId(), // profile: UserProfileSM( // firstName: "Tim", lastName: "Tim", phoneNumber: "Tim", email: "Tim", // dob: "Ray", // bio: "Wenderlich" // ), // credentials: EncryptedCredentialsSM( // username: "ray", // password: "beachvacations" // ), // following: [], // followers: [] // ) // // let tim = try UserSM( // _id: ObjectId(), // profile: UserProfileSM( // firstName: "Tim", lastName: "Tim", phoneNumber: "Tim", email: "Tim", // dob: "Tim", // bio: "Cordon" // ), // credentials: EncryptedCredentialsSM( // username: "0xtim", // password: "0xpassword" // ), // following: [], // followers: [] // ) // // let joannis = try UserSM( // _id: ObjectId(), // profile: UserProfileSM( // firstName: "Joannis", lastName: "Joannis", phoneNumber: "Joannis", email: "Joannis", // dob: "Joannis", // bio: "Orlandos" // ), // credentials: EncryptedCredentialsSM( // username: "Joannis", // password: "hunter2" // ), // following: [], // followers: [] // ) // // let names = [ // ("Chris", "Lattner"), // ("Tim", "Cook"), // ] // // let otherUsers = try names.map { (firstName, lastName) in // try UserSM( // _id: ObjectId(), // profile: UserProfileSM( // firstName: "Tim", lastName: "Tim", phoneNumber: "Tim", email: "Tim", // dob: firstName, // bio: lastName // ), // credentials: EncryptedCredentialsSM( // username: "\(firstName).\(lastName)", // password: "1234" // ), // following: [], // followers: [] // ) // } // // var posts = [Message]() // // posts.append( // Message( // _id: ObjectId(), // text: "Breaking news: Vapor formed into clouds", // creationDate: Date(), // fileId: nil, // creator: joannis._id // ) // ) // // posts.append( // Message( // _id: ObjectId(), // text: "MongoKitten needs a sequel!", // creationDate: Date(), // fileId: nil, // creator: joannis._id // ) // ) // // let tutorialNames = [ // "Baking HTTP Cookies", // "Knitting TCP Socks" // ] // // let tutorialPosts = tutorialNames.map { tutorial in // Message( // _id: ObjectId(), // text: "A new tutorial on \(tutorial)!", // creationDate: Date(), // fileId: nil, // creator: ray._id // ) // } // // posts.append(contentsOf: tutorialPosts) // let mainUser = try UserSM( // _id: ObjectId(), // profile: UserProfileSM(firstName: "Me", lastName: "Tim", phoneNumber: "Tim", email: "Tim", // dob: "Tim", // bio: "Tim"), // credentials: EncryptedCredentialsSM( // username: "me", // password: "opensesame" // ), // // One user is being followed to start off, so that the timeline isn't empty // following: [ray._id], // followers: [] // ) // // let createdAdmin = database[UserSM.collection].insertEncoded(mainUser) // let createdUsers = database[UserSM.collection].insertManyEncoded([ // ray, // tim, // joannis // ] + otherUsers) // let createdPosts = database[Message.collection].insertManyEncoded(posts) // // _ = try createdAdmin.and(createdUsers).and(createdPosts).wait() //}
// // ViewController.swift // 2DA_EVA_6_PickerView // <Juan Chacon Holguin> // <Plataforma I> // Created by on 16/03/17. // // import UIKit class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate { let asDatos = ["Lunes","Martes","Miercoles","Jueves","Viernes","Sabado","Domingo","PASADOMAÑANA","ALFILO DEL MAÑANA","CAMION","OIGA ME NO"] let asData = ["Monday","Tuesday","Wensday","Thrusday","Friday","Saturday","Sunday","Summer","ALF","CAMION","OIGA ME NO"] 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. } //titulo del picker view func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { if component == 0{ return asDatos[row]//fila que se debe refrescar (mostrar el text) }else{ return asData[row]//fila que se debe refrescar (mostrar el text) } } //numero de componentes del pickerview func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 2 //numero de origen de datos, un arreglo } func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { var sMensa: String if component == 0{ sMensa = asDatos[row]//fila que se debe refrescar (mostrar el text) }else{ sMensa = asData[row]//fila que se debe refrescar (mostrar el text) } let actShow = UIAlertController(title: "picker view",message: sMensa,preferredStyle: .Alert) let acBotton = UIAlertAction(title: "ok", style: .Default, handler: nil) actShow.addAction(acBotton) presentViewController(actShow, animated: true, completion: nil) } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { if component == 0{ return asDatos.count //Cantidad de datos del componente }else{ return asData.count //Cantidad de datos del componente } } //regresa una vista, las genera, lee el arreglo y los pone en la vista }
import UIKit extension UIViewController: UITextFieldDelegate { func hideNavBackIcon() { navigationItem.hidesBackButton = true } func hideTabBarNavBackIcon() { self.tabBarController?.navigationItem.hidesBackButton = true } func hideNavigationBar() { navigationController?.setNavigationBarHidden(true, animated: false) } func showNavigationBar() { navigationController?.setNavigationBarHidden(false, animated: false) } func popBackStack() { guard let navigationController = navigationController else { return } if (navigationController.viewControllers.count > 1) { navigationController.popViewController(animated: true) } } func navigate(_ identifier: String, data:Any?=nil) { performSegue(withIdentifier: identifier, sender: data) } func dismiss() { dismiss(animated: true, completion: nil) } func getViewController(_ fromStoryboard: String, withName: String) -> UIViewController { let storyboard = UIStoryboard(name: fromStoryboard, bundle: nil) let viewController = storyboard.instantiateViewController(withIdentifier: withName) return viewController } func removeThisViewControllerFromStack() { guard let navigationController = navigationController else { return } var navigationArray = navigationController.viewControllers navigationArray.removeAll(where: { [weak self] in $0 === self }) self.navigationController?.viewControllers = navigationArray } public func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } }
// // ShowImageViewController.swift // Quick Share // // Created by Abhishek Thakur on 18/07/19. // Copyright © 2019 Abhishek Thakur. All rights reserved. // import UIKit import Photos import Social class ShowImageViewController: UIViewController { @IBOutlet weak var imageView: UIImageView! var asset: PHAsset? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. if let myasset = asset{ PHImageManager.default().requestImage(for: myasset, targetSize: CGSize(width: self.view.frame.width, height: self.view.frame.width * 0.5625), contentMode: .aspectFill, options: nil, resultHandler:{ (result, info) in if let image = result { self.imageView.image = image } }) } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ //Handling all sharing button action @IBAction func shareButtonClicked(_ sender: UIButton){ switch sender.tag { case 0: if let vc = SLComposeViewController(forServiceType: SLServiceTypeFacebook){ shareFacebookTwitter(vc: vc); } break case 1:if let vc = SLComposeViewController(forServiceType: SLServiceTypeTwitter){ shareFacebookTwitter(vc: vc); } break case 2: print("twitter") break case 4: print("whatsapp") default: print("No social media ") } } func shareFacebookTwitter(vc: SLComposeViewController){ vc.setInitialText("Look this great picture") vc.add(imageView.image) } }
// // MovieTableViewCell.swift // MyMovies // // Created by Alexander Supe on 31.01.20. // Copyright © 2020 Lambda School. All rights reserved. // import UIKit class MovieTableViewCell: UITableViewCell { @IBOutlet weak var label: UILabel! @IBOutlet weak var button: UIButton! var movie: Movie! @IBAction func watched(_ sender: Any) { if button.title(for: .normal) == "Unwatched" { MovieController.shared.update(movie, hasWatched: true) button.setTitle("Watched", for: .normal) } else { MovieController.shared.update(movie, hasWatched: false) button.setTitle("Unwatched", for: .normal) } } }