text
stringlengths
8
1.32M
// // EditViewController.swift // Quote // // Created by User on 11/12/18. // Copyright © 2018 User. All rights reserved. // import UIKit protocol EditViewControllerDelegate: class { func quoteWasSaved(quote: Quote) } class EditViewController: UIViewController { var quote: Quote? weak var delegate: EditViewControllerDelegate? @IBOutlet weak var textView: UITextView! @IBOutlet weak var textField: UITextField! override func viewDidLoad() { super.viewDidLoad() textView.text = quote?.text textField.text = quote?.author } @IBAction func save(_ sender: Any) { let newQuote = Quote(text: textView.text, author: textField.text!) delegate?.quoteWasSaved(quote: newQuote) self.navigationController?.popViewController(animated: true) } }
// // ShopCell.swift // SAC // // Created by Bala on 19/08/17. // Copyright © 2017 ShopAroundTheCorner. All rights reserved. // import UIKit protocol ShopCellProtocol: class { func didTapCall(shop: Shop) } class ShopCell: UITableViewCell { @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var contactNumberLabel: UILabel! @IBOutlet weak var callButton: UIButton! var shop: Shop? weak var delegate: ShopCellProtocol? 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 } func configureCell(shop: Shop) { self.shop = shop nameLabel.text = shop.name contactNumberLabel.text = shop.phone } @IBAction func didTapCall(_ sender: Any) { if let tappedShop = self.shop { self.delegate?.didTapCall(shop: tappedShop) } } }
//: [Previous](@previous) import UIKit import PlaygroundSupport PlaygroundPage.current.needsIndefiniteExecution = true //: # Use Group of Tasks let userQueue = DispatchQueue.global(qos: .userInitiated) let numberArray = [(0,1), (2,3), (4,5), (6,7), (8,9)] //: ## Creating a group print("=== Group of sync tasks ===\n") // TODO: Create slowAddGroup let slowAddGroup = DispatchGroup() //: ## Dispatching to a group // TODO: Loop to add slowAdd tasks to group for inValue in numberArray { userQueue.async(group: slowAddGroup){ let result = slowAdd(inValue) print("Result = \(result)") } } //: ## Notification of group completion //: Will be called only when every task in the dispatch group has completed let mainQueue = DispatchQueue.main // TODO: Call notify method slowAddGroup.notify(queue: mainQueue){ print("Slow add: completed all tasks") PlaygroundPage.current.finishExecution() } //: [Next](@next)
// // ColorsGameScene.swift // BookCore // // Created by Beatriz Carlos on 15/04/21. // import PlaygroundSupport import SpriteKit import UIKit public class PrimaryColorsGameScene: SKScene { var backgroundColorCustom = UIColor(red: 0.99, green: 0.97, blue: 0.92, alpha: 1.00) // nodes private var spinnyNode : SKShapeNode = { let node = SKShapeNode(circleOfRadius: 3) node.fillColor = .white node.lineWidth = 1 return node }() private var primaryColorsText: SKNode = { let node = SKSpriteNode(imageNamed: "PrimaryColorsText") node.position = CGPoint(x: 100, y: 170) node.setScale(0.15) return node }() private var circleDote: SKNode = { let node = SKSpriteNode(imageNamed: "circledote") node.position = CGPoint(x: 100, y: 100) node.setScale(0.17) node.isUserInteractionEnabled = false node.name = "circleDote" return node }() private var TriangleBlue: SKNode = { let node = SKSpriteNode(imageNamed: "TriangleBlue") node.position = CGPoint(x: 81.5, y: 92) node.setScale(0.18) node.isHidden = true node.name = "TriangleBlue" return node }() private var TriangleYellow: SKNode = { let node = SKSpriteNode(imageNamed: "TriangleYellow") node.position = CGPoint(x: 99.5, y: 118) node.setScale(0.18) node.isHidden = true node.name = "TriangleYellow" return node }() private var TriangleRed: SKNode = { let node = SKSpriteNode(imageNamed: "TriangleRed") node.position = CGPoint(x: 117.5, y: 92.5) node.setScale(0.18) node.isHidden = true node.name = "TriangleRed" return node }() private var yellowArrow: SKNode = { let node = SKSpriteNode(imageNamed: "setaYellow") node.position = CGPoint(x: 130, y: 130) node.setScale(0.15) node.zRotation = 0.8 node.zPosition = -1 node.isUserInteractionEnabled = false return node }() private var yellowText: SKNode = { let node = SKSpriteNode(imageNamed: "yellow") node.position = CGPoint(x: 130, y: 150) node.setScale(0.15) node.name = "yellowText" return node }() private var blueText: SKNode = { let node = SKSpriteNode(imageNamed: "Blue") node.position = CGPoint(x: 65, y: 50) node.setScale(0.15) node.name = "blueText" node.isUserInteractionEnabled = false return node }() private var blueArrow: SKNode = { let node = SKSpriteNode(imageNamed: "setaBlue") node.position = CGPoint(x: 70, y: 70) node.setScale(0.15) node.zRotation = 0.8 node.zPosition = -1 return node }() private var redText: SKNode = { let node = SKSpriteNode(imageNamed: "Red") node.position = CGPoint(x: 140, y: 50) node.setScale(0.15) node.name = "redText" node.isUserInteractionEnabled = false return node }() private var redArrow: SKNode = { let node = SKSpriteNode(imageNamed: "setaRed") node.position = CGPoint(x: 130, y: 70) node.setScale(0.15) node.zRotation = -0.5 node.zPosition = -1 return node }() override public func didMove(to view: SKView) { self.backgroundColor = backgroundColorCustom self.addChild(primaryColorsText) self.addChild(circleDote) self.addChild(TriangleBlue) self.addChild(TriangleYellow) self.addChild(TriangleRed) self.addChild(yellowText) self.addChild(yellowArrow) self.addChild(blueText) self.addChild(blueArrow) self.addChild(redText) self.addChild(redArrow) let fadeAndRemove = SKAction.sequence([.fadeOut(withDuration: 0.5), .removeFromParent()]) spinnyNode.run(fadeAndRemove) } @objc static override public var supportsSecureCoding: Bool { // SKNode conforms to NSSecureCoding, so any subclass going // through the decoding process must support secure coding get { return true } } func touchDown(atPoint pos : CGPoint) { } func touchMoved(toPoint pos : CGPoint) { } func touchUp(atPoint pos : CGPoint) { guard let n = spinnyNode.copy() as? SKShapeNode else { return } n.position = pos self.addChild(n) } var flagBlue: Bool = false var flagYellow: Bool = false var flagRed: Bool = false override public func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { for touch in touches { let location = touch.location(in: self) if (self.atPoint(location).contains(self.TriangleYellow.position)) { self.TriangleYellow.isHidden = false let nodes = self.nodes(at: location) if (nodes[0].name?.contains("TriangleYellow")) == false && (flagYellow == false) { self.TriangleYellow.isHidden = true } else { flagYellow = true } } if (self.atPoint(location).contains(self.TriangleBlue.position)) { self.TriangleBlue.isHidden = false let nodes = self.nodes(at: location) if (nodes[0].name?.contains("TriangleBlue") == false) && (flagBlue == false) { self.TriangleBlue.isHidden = true } else { flagBlue = true } } if (self.atPoint(location).contains(self.TriangleRed.position)) { self.TriangleRed.isHidden = false let nodes = self.nodes(at: location) if (nodes[0].name?.contains("TriangleRed") == false) && (flagRed == false) { self.TriangleRed.isHidden = true } else { flagRed = true } } if (self.TriangleYellow.isHidden == false && self.TriangleRed.isHidden == false) && (self.TriangleBlue.isHidden == false) { PlaygroundPage.current.assessmentStatus = .pass(message: "Let's see the next page! [Go to next page](@next)") } } } override public func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { for t in touches { touchMoved(toPoint: t.location(in: self)) } } override public func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { for t in touches { touchUp(atPoint: t.location(in: self)) } } override public func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { for t in touches { touchUp(atPoint: t.location(in: self)) } } override public func update(_ currentTime: TimeInterval) { // Called before each frame is rendered } }
// // Coordinator.swift // ExampleCoordinator // // Created by Karlo Pagtakhan on 3/27/18. // Copyright © 2018 kidap. All rights reserved. // import UIKit //-------------------------------------------------------------------------------- // Coordinator //-------------------------------------------------------------------------------- protocol Coordinator: class { typealias ChildCoordinatorsDictionary = [UIViewController: Coordinator] typealias CoordinatorDidFinish = () -> () var rootController: UIViewController { get } var didFinish: CoordinatorDidFinish? { get set } var childCoordinators: ChildCoordinatorsDictionary { get set } func start() // Should not be called on the actual type. This method does not ensure references are kept // Use present(_ childCoordinator: Coordinator, animated: Bool, completion: (() -> ())?) func unsafePresentChildCoordinator(_ childCoordinator: Coordinator, animated: Bool, completion: (() -> ())?) } // Methods that can be called on the actual type extension Coordinator { func present(_ childCoordinator: Coordinator, animated: Bool, completion: (() -> ())?) { addChildCoordinator(childCoordinator, animated: animated, completion: completion) unsafePresentChildCoordinator(childCoordinator, animated: animated, completion: completion) } func addChildCoordinator(_ childCoordinator: Coordinator, animated: Bool, completion: (() -> ())?) { addReference(to: childCoordinator) childCoordinator.didFinish = { [unowned childCoordinator, unowned self] in if let tabBarControllerCoordinator = childCoordinator as? TabBarControllerCoordinator { tabBarControllerCoordinator.willFinish(animated: animated) } self.removeReference(from: childCoordinator) } childCoordinator.start() } } // Methods that SHOULD NOT be called on the actual type extension Coordinator { func unsafePresentChildCoordinator(_ childCoordinator: Coordinator, animated: Bool, completion: (() -> ())?) { rootController.present(childCoordinator.rootController, animated: animated, completion: completion) } func addReference(to coordinator: Coordinator) { childCoordinators[coordinator.rootController] = coordinator } func removeReference(from coordinator: Coordinator) { childCoordinators[coordinator.rootController] = nil } }
import Foundation struct Temperature: Codable { public private(set) var temp: Double? public private(set) var temp_min: Double? public private(set) var temp_max: Double? public private(set) var pressure: Int? public private(set) var sea_level: Int? public private(set) var grnd_level: Int? public private(set) var humidity: Int? public private(set) var temp_kf: Double? public private(set) var feels_like : Double? enum CodingKeys: String, CodingKey { case temp = "temp" case feels_like = "feels_like" case temp_min = "temp_min" case temp_max = "temp_max" case pressure = "pressure" case sea_level = "sea_level" case grnd_level = "grnd_level" case humidity = "humidity" case temp_kf = "temp_kf" } init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) temp = try values.decodeIfPresent(Double.self, forKey: .temp) temp_min = try values.decodeIfPresent(Double.self, forKey: .temp_min) temp_max = try values.decodeIfPresent(Double.self, forKey: .temp_max) pressure = try values.decodeIfPresent(Int.self, forKey: .pressure) sea_level = try values.decodeIfPresent(Int.self, forKey: .sea_level) grnd_level = try values.decodeIfPresent(Int.self, forKey: .grnd_level) humidity = try values.decodeIfPresent(Int.self, forKey: .humidity) temp_kf = try values.decodeIfPresent(Double.self, forKey: .temp_kf) feels_like = try values.decodeIfPresent(Double.self, forKey: .feels_like) } }
// // PaginatorTests.swift // MarvelTests // // Created by MACBOOK on 21/05/2021. // @testable import Marvel import XCTest final class PaginatorTests: XCTestCase { func test() { // Given let offset = 0 let limit = 20 let total = 40 let count = 20 let totalResults = EntityTestDouble.items(numberOfElements: total) var paginator = Paginator.value( offset: offset, limit: limit, total: total, count: count, results: .init(totalResults.prefix(limit)) ) // Then XCTAssertTrue(paginator.hasMorePages) XCTAssertEqual(paginator.nextOffset, offset + limit) // Given paginator = paginator.next(with: .init(totalResults.suffix(limit))) // Then XCTAssertFalse(paginator.hasMorePages) XCTAssertEqual(paginator.nextOffset, paginator.offset) } } extension Paginator { static func value( offset: Int = 0, limit: Int = 20, total: Int = 40, count: Int = 20, results: [Value] ) -> Self { .init( offset: offset, limit: limit, total: total, count: count, results: results ) } func next(with results: [Value]) -> Self { .init( offset: nextOffset, limit: limit, total: total, count: count, results: results ) } }
import Glibc class Shape{ var numSides=0 var name:String init(name:String){ self.name=name } func desc()->String{ return "A shape of \(name) has \(numSides) sides" } } class Square:Shape{ var sideLen:Double init(len:Double, name:String){ sideLen = len super.init(name:name) numSides = 4 } func perimeter()->Double{ return sideLen * Double(numSides) } override func desc()->String{ return "A square of \(name) is \(perimeter()) round" } } class Circle:Shape{ var radius:Double init(r:Double, name:String){ radius = r super.init(name:name) } func perimeter()->Double{ return 2 * M_PI * radius } override func desc()->String{ return "A circle of \(name) is \(perimeter()) round" } } var s=Shape(name:"wuxing") print(s.desc()) var sq=Square(len:9, name:"zhengfangxing") print(sq.desc()) var c=Circle(r:2.5, name:"yuan") print(c.desc())
// // NSEntityDescription+JsonDecoder.swift // CoreDataJsonParser // // Created by Alex Belozierov on 9/7/19. // Copyright © 2019 Alex Belozierov. All rights reserved. // import CoreData extension NSEntityDescription { var sharedJsonDecoder: EntityJsonDecoder { set { _userInfo[.jsonDecoder] = newValue } get { if let entityDecoder = userInfo?[.jsonDecoder] as? EntityJsonDecoder { return entityDecoder } let model = entityModel(with: JsonDecoderStorage()) let entityDecoder = EntityJsonDecoder(model: model) _userInfo[.jsonDecoder] = entityDecoder return entityDecoder } } private var _userInfo: [AnyHashable: Any] { get { userInfo ?? [:] } set { userInfo = newValue } } func entityModel(with storage: JsonDecoderStorage) -> EntityModel { var properties = [String: PropertyModel]() for (name, attribute) in attributesByName { properties[name] = attribute.propertyModel } for (name, relation) in relationshipsByName { properties[name] = relation.sharedPropertyModel } return EntityModel(entity: self, properties: properties, findObjectStrategy: findObjectStrategy, storage: storage) } var findObjectStrategy: EntityModel.FindObjectStrategy { guard let constraints = uniquenessConstraints as? [[String]], !constraints.isEmpty else { return .none } return .byConstraints(constraints) } } extension AnyHashable { fileprivate static let jsonDecoder = "jsonDecoder" }
// // OAuthViewController.swift // MGWeiBo2 // // Created by MGBook on 2020/9/15. // Copyright © 2020 穆良. All rights reserved. // import UIKit import SVProgressHUD import AFNetworking class OAuthViewController: UIViewController { @IBOutlet weak var webView: UIWebView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. setupNavigationItem() loadWebView() } } //MARK:- 导航按钮相关 extension OAuthViewController { func setupNavigationItem() { navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .plain, target: self, action: #selector(closeItemClick)) navigationItem.rightBarButtonItem = UIBarButtonItem(title: "填充", style: .plain, target: self, action: #selector(fillItemClick)) title = "登录页面" } func loadWebView() { let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(app_key)&redirect_uri=\(redirect_uri)" guard let url = URL(string: urlString) else { return } let request = URLRequest(url: url) webView.loadRequest(request) } } //MARK:- 事件监听 extension OAuthViewController { @objc private func closeItemClick() { dismiss(animated: true, completion: nil) } @objc private func fillItemClick() { // java --- javaScript 雷锋、雷峰塔 let jsCode = "document.getElementById('loginName').value='467603639@qq.com';document.getElementById('loginPassword').value='9904529';" webView.stringByEvaluatingJavaScript(from: jsCode) } } //MARK:- xib已经连线,实现webView协议 extension OAuthViewController: UIWebViewDelegate{ /// 开始加载网页 func webViewDidStartLoad(_ webView: UIWebView) { SVProgressHUD.show() } /// 加载网页结束 func webViewDidFinishLoad(_ webView: UIWebView) { SVProgressHUD.dismiss() } /// 加载网页失败 func webView(_ webView: UIWebView, didFailLoadWithError error: Error) { SVProgressHUD.dismiss() } /// 正准备开始加载某页面 func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebView.NavigationType) -> Bool { // 1. 拿到网页的URL guard let url = request.url else { // 没有值,继续加载 return true } // 2. 获取url中的字符串 let urlString = url.absoluteString // 3.是否包含code= guard urlString.contains("code=") else { return true } // 把code取出来 let code = urlString.components(separatedBy: "code=").last! print("====== code = \(code)") loadAccessToken(code) // 有code的页面不加载 return false } } //MARK:- 请求数据 extension OAuthViewController { /// 用code交换access_token private func loadAccessToken(_ code: String) { var param: [String: Any] = [String: Any]() param["client_id"] = app_key param["client_secret"] = app_secret param["grant_type"] = "authorization_code" param["code"] = code param["redirect_uri"] = redirect_uri AFHTTPSessionManager().post("https://api.weibo.com/oauth2/access_token", parameters: param, headers: nil, progress: nil, success: { (task: URLSessionDataTask, result: Any?) in guard let result = result as? [String: Any] else { return } let account = UserAccount(dict: result) self.loadUserInfo(account) }) { (task: URLSessionDataTask?, error: Error) in print(error) } } /// 请求用户信息 private func loadUserInfo(_ account : UserAccount) { let param = ["access_token": account.access_token, "uid": account.uid] AFHTTPSessionManager().get("https://api.weibo.com/2/users/show.json", parameters: param, headers: nil, progress: nil, success: { (task: URLSessionDataTask, result: Any?) in print(result!) guard let result = result as? [String: Any] else { print("没有返回用户信息") return } account.screen_name = result["screen_name"] as? String account.avatar_large = result["avatar_large"] as? String // print(account) // 获取沙盒路径 // var accountPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! // // 拼接文件路径 // accountPath = accountPath + "/account.plist" // print(accountPath) // 保存对象 NSKeyedArchiver.archiveRootObject(account, toFile: UserAccountViewModel.shared.accountPath) // 必须重新赋值,否则后面用单例拿到的属性account,都是nil UserAccountViewModel.shared.account = account // 退出当前控制器 self.dismiss(animated: true) { UIApplication.shared.keyWindow?.rootViewController = WelcomeViewController() } }) { (task: URLSessionDataTask?, error: Error) in print("error: \(error)") } } }
// // MessageListTableViewCell.swift // GacyaMatch // // Created by 楊采庭 on 2017/8/1. // Copyright © 2017年 楊采庭. All rights reserved. // import UIKit class MessageListTableViewCell: UITableViewCell { @IBOutlet weak var messagerListCellView: UIView! @IBOutlet weak var userImageView: UIImageView! @IBOutlet weak var userNameLabel: UILabel! @IBOutlet weak var lastestMessageLabel: UILabel! @IBOutlet weak var redDot: UIView! @IBOutlet weak var timeLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() redDot.isHidden = true redDot.round() userImageView.radiusAndBorder() messagerListCellView.layer.cornerRadius = 4 messagerListCellView.layer.borderWidth = 1 messagerListCellView.layer.borderColor = UIColor.makalonBlue.cgColor messagerListCellView.layer.shadowOpacity = 1 messagerListCellView.layer.shadowRadius = 1 messagerListCellView.layer.shadowOffset = CGSize(width: 0, height: 1) messagerListCellView.layer.shadowColor = UIColor.gray.cgColor } }
// // Diamond.swift // MAPDTest // // Created by Sreeram Ramakrishnan on 2019-02-22. // Copyright © 2019 Centennial College. All rights reserved. // import Foundation import SpriteKit import GameplayKit class Diamond : GameObject{ init() { // initialize the object with an image super.init(imageString: "dimond", initialScale: 1.7) Start() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
import UIKit class DiaryViewController: UIViewController, UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate { // MARK: Properties @IBOutlet weak var nameTextField: UITextField! @IBOutlet weak var photoImageView: UIImageView! @IBOutlet weak var saveButton: UIButton! let imagePickerController = UIImagePickerController() var entry: Diary? override func viewDidLoad() { super.viewDidLoad() // Handle the text field’s user input through delegate callbacks. nameTextField.delegate = self // Set up views if editing an existing entry. if let entry = entry { navigationItem.title = entry.name nameTextField.text = entry.name photoImageView.image = entry.photo //ratingControl.rating = meal.rating } checkValidEntryName() let tapGestureRecognizer = UITapGestureRecognizer(target:self, action: #selector(DiaryViewController.imageTapped)) photoImageView.isUserInteractionEnabled = true photoImageView.addGestureRecognizer(tapGestureRecognizer) imagePickerController.delegate = self } // MARK: UITextFieldDelegate func textFieldShouldReturn(_ textField: UITextField) -> Bool { // Hide the keyboard. textField.resignFirstResponder() return true } func textFieldDidEndEditing(_ textField: UITextField) { checkValidEntryName() navigationItem.title = textField.text } func textFieldDidBeginEditing(_ textField: UITextField) { // Disable the Save button while editing. saveButton.isEnabled = false } func checkValidEntryName() { // Disable the Save button if the text field is empty. let text = nameTextField.text ?? "" saveButton.isEnabled = !text.isEmpty } // MARK: Navigation @IBAction func cancel(_ sender: UIBarButtonItem) { // Depending on style of presentation (modal or push presentation), this view controller needs to be dismissed in two different ways. if (nameTextField.text! == "") { dismiss(animated: true, completion: nil) } else { navigationController!.popViewController(animated: true) } } @IBAction func saveButton(_ sender: UIBarButtonItem) { let name = nameTextField.text ?? "" let photo = photoImageView.image // Set the entry to be passed to DiaryListTableViewController after the unwind segue. entry = Diary(name: name, photo: photo!) //navigationController?.pushViewController(DiaryTableViewController, animated: true) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { //if segue.identifier == "AddNew" { //segue.destination as! DiaryTableViewController let name = nameTextField.text ?? "" let photo = photoImageView.image // Set the entry to be passed to DiaryListTableViewController after the unwind segue. entry = Diary(name: name, photo: photo!) //} } // MARK: Actions func imageTapped() { // Your action // Hide the keyboard. nameTextField.resignFirstResponder() // UIImagePickerController is a view controller that lets a user pick media from their photo library. imagePickerController.allowsEditing = true // Only allow photos to be picked, not taken. imagePickerController.sourceType = .photoLibrary // Make sure ViewController is notified when the user picks an image. imagePickerController.delegate = self present(imagePickerController, animated: true, completion: nil) } // MARK: UIImagePickerControllerDelegate internal func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { // Dismiss the picker if the user canceled. dismiss(animated: true, completion: nil) } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { // The info dictionary contains multiple representations of the image, and this uses the original. if let selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage{ photoImageView.contentMode = .scaleAspectFit photoImageView.image = selectedImage } else { print("something went wrong with imagepicker") } // Dismiss the picker. self.dismiss(animated: true, completion: nil) } }
import UIKit class MyRoomViewController: UIViewController { var myHome : Home? var myRoom: Room? var closureToPerform: ((Home) -> Void)? @IBOutlet weak var nextButton: UIButton! @IBAction func nextButton(_ sender: Any) { } @IBAction func addButton(_ sender: Any) { if let myHome = myHome { var nameRoom : String = "" let alertGiveRoom = UIAlertController(title: "Create new room", message: "Enter name", preferredStyle: .alert) alertGiveRoom.addTextField { (textField) in textField.text = "" } alertGiveRoom.addAction(UIAlertAction(title: "OK", style: .default, handler: { [weak alertGiveRoom] (_) in if let alertGiveRoom = alertGiveRoom { if let textFields = alertGiveRoom.textFields { nameRoom = textFields[0].text! myHome.rooms.insert(Room(id: UUID().uuidString, name: nameRoom), at: 0) self.performSegue(withIdentifier: "SelectRoomTypeSegue", sender: nil) } } alertGiveRoom?.dismiss(animated: true, completion: nil) })) self.present(alertGiveRoom, animated: true, completion: nil) } } @IBAction func editButton(_ sender: Any) { let editButton = sender as! UIButton if myRoomTableView.isEditing{ activateEditingEnvironment( editingButton: editButton, title: "Edit", editing: false, animated: false) nextButton.isHidden = false } else{ activateEditingEnvironment( editingButton: editButton, title: "Done", editing: true, animated: true) nextButton.isHidden = true } } @IBOutlet weak var addButton: UIButton! private func activateEditingEnvironment( editingButton: UIButton, title: String, editing: Bool, animated: Bool) { myRoomTableView.setEditing(editing, animated: animated); editingButton.setTitle(title, for: .normal) } @IBOutlet weak var myRoomTableView: UITableView! override func prepare(for segue: UIStoryboardSegue, sender: Any?) { passInformationToNextScene(segue: segue) } private func passInformationToNextScene(segue: UIStoryboardSegue) { if segue.identifier == "SelectRoomTypeSegue" { passInformationToSomewhereScene(segue: segue) } if segue.identifier == "showRoom" { passInformationToSomewhereScene(segue: segue) } } private func passInformationToSomewhereScene(segue: UIStoryboardSegue) { if let destination = segue.destination as? SelectRoomTypeViewController { passDataToScene( destination: destination) passClosureToScene( destination: destination) } } private func passDataToScene (destination: SelectRoomTypeViewController) { if let myHome = myHome { destination.myHome = myHome } } private func passClosureToScene ( destination: SelectRoomTypeViewController) { destination.closureToPerform = { [weak self] (myHome: Home) in if let strongSelf = self { strongSelf.myHome = myHome } } } override func viewWillAppear(_ animated: Bool) { myRoomTableView.reloadData() self.navigationController?.navigationBar.isHidden = true myHome = DataSource.sharedInstance.myHome if myHome?.rooms.count == 0 { nextButton.isHidden = true } else { nextButton.isHidden = false } } override func viewDidLoad() { super.viewDidLoad() DataSource.sharedInstance.createData() myHome = DataSource.sharedInstance.myHome myRoomTableView.delegate = self myRoomTableView.dataSource = self myRoomTableView.reloadData() self.navigationController?.navigationBar.isHidden = true addButton.layer.cornerRadius = 0.5 * addButton.bounds.size.width addButton.layer.borderWidth = 1.0 addButton.layer.borderColor = UIColor.black.cgColor if myHome?.rooms.count == 0 { nextButton.isHidden = true } else { nextButton.isHidden = false } } } extension MyRoomViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { return tableView.dequeueReusableCell(withIdentifier: "myRoomCell", for: indexPath) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let myHome = myHome { return myHome.rooms.count } else { return 0 } } } extension MyRoomViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, canFocusRowAt indexPath: IndexPath) -> Bool { return true } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if (editingStyle == UITableViewCellEditingStyle.delete) { if let myHome = myHome { myHome.rooms.remove(at: indexPath.row) tableView.reloadData() } } } func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) { if let selectedCell = tableView.cellForRow(at: indexPath) { selectedCell.layer.borderColor = UIColor.clear.cgColor selectedCell.tintColor = UIColor.clear } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if let selectedCell = tableView.cellForRow(at: indexPath) { selectedCell.layer.borderColor = UIColor.lightGray.cgColor selectedCell.layer.borderWidth = 0.5 selectedCell.layer.cornerRadius = 5 selectedCell.tintColor = UIColor.black myHome?.selectedRoom = indexPath.row } } func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle { if let myHome = myHome { if (self.isEditing == false && indexPath.row == 0) { return .none } if (self.isEditing && indexPath.row == myHome.rooms.count){ return .insert } else{ return .delete } } else { return .none } } func moveRoomAtIndex( rooms: [Room], fromIndex: Int, toIndex: Int ) -> [Room] { var localRooms = rooms if fromIndex == toIndex { return localRooms } let movedRoom = localRooms[fromIndex] localRooms.remove(at: fromIndex) localRooms.insert(movedRoom, at: toIndex) return localRooms } func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) { if let myHome = myHome { myHome.rooms = moveRoomAtIndex(rooms: myHome.rooms, fromIndex: sourceIndexPath.row, toIndex: destinationIndexPath.row) } } func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { if let myHome = myHome { let cell = cell as! MyRoomTableViewCell cell.nameCell.text = myHome.rooms[indexPath.item].name cell.descriptionCell.text = myHome.rooms[indexPath.item].description cell.pictogramCell.image = myHome.rooms[indexPath.item].pictogram } } }
// // LineWriter.swift // Canvas // // Created by Russell Gordon on 5/11/17. // Copyright © 2017 Royal St. George's College. All rights reserved. // import Foundation // Write text file line by line class LineWriter { var fileHandle = FileHandle() init?(path: String, appending : Bool = false) { // See if we can open the specified path for writing if let handle = FileHandle(forWritingAtPath: path) { // File already exists, get a handle to it self.fileHandle = handle } else { // File does not exist, so create it let fileManager = FileManager.default if fileManager.createFile(atPath: path, contents: nil, attributes: nil) { // Try to get a handle to the newly created file guard let handle = FileHandle(forWritingAtPath: path) else { // This really should not happen, as the file was just craeted by the FileManager instance return nil } // Set the handle to the file self.fileHandle = handle } } // Truncate (wipe) existing contents of file if requested if !appending { self.fileHandle.truncateFile(atOffset: 0) } } func write(line : String, terminator : String = "\n") { // Move file pointer to end of the file fileHandle.seekToEndOfFile() // Create the line to be written to the file let lineToWrite = "\(line)\(terminator)" // Convert to NSString before writing to file if let data = (lineToWrite as NSString).data(using: String.Encoding.utf8.rawValue) { // Write the data to the file fileHandle.write(data) } } // This must be invoked when we are finished writing to the file func close() { fileHandle.closeFile() } }
// // ijomEBundle.swift // ijomE // // Created by Benny Pollak on 11/19/22. // Copyright © 2022 Alben Software. All rights reserved. // import WidgetKit import SwiftUI @main struct ijomEBundle: WidgetBundle { var body: some Widget { ijomE() ijomELiveActivity() } }
// // MapEditorViewController.swift // RPGMill // // Created by William Young on 1/18/19. // Copyright © 2019 William Young. All rights reserved. // import Cocoa class MapEditorViewController: NSViewController { var editorViewController: EditorViewController? var gameData: GameData? var map: MapData? @IBOutlet weak var mapNameTextField: NSTextField! @IBOutlet weak var tileSizeTextField: NSTextField! @IBOutlet weak var imageView: NSImageView! @IBOutlet var loreTextView: NSTextView! override func viewDidLoad() { super.viewDidLoad() // Do view setup here. NotificationCenter.default.addObserver(self, selector: #selector(reloadView), name: NSNotification.Name.NSUndoManagerDidUndoChange, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(reloadView), name: NSNotification.Name.NSUndoManagerDidRedoChange, object: nil) } override func mouseDown(with event: NSEvent) { view.window?.makeFirstResponder(nil) } @IBAction func mapNameTextFieldDidUpdate(_ sender: NSTextField) { guard let map = map else { return } map.id = sender.stringValue editorViewController?.viewController?.reloadOutline() } @IBAction func tileSizeTextFieldDidChange(_ sender: NSTextField) { guard let map = map else { return } map.tileSize = sender.integerValue } @IBAction func mapImageDidChange(_ sender: NSImageView) { guard let map = map else { return } map.image = sender.image } } extension MapEditorViewController: EditorTab { func setEditorViewController(editorViewController: EditorViewController?) { self.editorViewController = editorViewController } func loadNewEditingItem(item: Any?, on: Any?) { guard let map = item as? MapData, let gameData = on as? GameData else { return } self.map = map self.gameData = gameData reloadView() } @objc func reloadView() { if let rtf = map?.rtf, let attrString = NSAttributedString(rtf: rtf, documentAttributes: nil) { loreTextView.textStorage?.setAttributedString(attrString) } else { loreTextView.string = "" } mapNameTextField.stringValue = map?.id ?? "" if let map = map { tileSizeTextField.integerValue = map.tileSize } else { tileSizeTextField.stringValue = "" } imageView.image = map?.image } } extension MapEditorViewController: NSTextViewDelegate { func textDidEndEditing(_ notification: Notification) { let range = NSRange(location: 0, length: loreTextView.string.count) map?.rtf = loreTextView.rtf(from: range) } }
// // TransitionViewController.swift // Demo App // // Created by Vineeth on 8/8/17. // Copyright © 2017 Vineeth. All rights reserved. // import UIKit class TransitionViewController: UIViewController { @IBOutlet weak var addDepositButton: UIButton! @IBOutlet weak var viewGraphsButton: UIButton! override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func addDepositButtonTapped(_ sender: UIButton) { performSegue(withIdentifier: "navToDeposit", sender:UIButton.self) } @IBAction func viewGraphsButtonTapped(_ sender: UIButton) { performSegue(withIdentifier: "navToData", sender: UIButton.self) } @IBAction func unwindToVC1(segue:UIStoryboardSegue) { } }
// // ViewController.swift // CurrencyRates2 // // Created by Egor on 28.05.2020. // Copyright © 2020 Egor. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDataSource { //MARK: - OBJECTS @IBOutlet weak var testTable: UITableView! @IBOutlet weak var ratesField: UITextField! @IBOutlet weak var tableView: UITableView! @IBOutlet weak var dateLabel: UILabel! @IBOutlet weak var searchBar: UISearchBar! @IBOutlet weak var noteField: UITextView! @IBOutlet weak var keyBoardBut: UIButton! @IBOutlet weak var clearButton: UIButton! @IBOutlet weak var saveButton: UIButton! @IBOutlet weak var pickerBase: UIPickerView! @IBOutlet weak var imageFlag: UIImageView! var usd: Currency? var modelsOfCountry = Country() var arrayCountry: [String] = [] var testArray: [String] = [] var baseRate = 1.0 var searchCountry = [String]() var searchCurrency = [String:Double]() var searching = false var textStory = " " var userDefaultStore = UserDefaults.standard // user default object var myCurrency: [String] = [] var myValues: [Double] = [] var actualBase = String() override func viewDidLoad() { super.viewDidLoad() noteField.delegate = self keyBoardBut.isHidden = true noteField.tintColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1) ratesField.textAlignment = .center searchBar.searchTextField.textColor = .white //Button animation target clearButton.addTarget(self, action: #selector(changeState2(sender:)), for: .touchUpInside) saveButton.addTarget(self, action: #selector(changeState3(sender:)), for: .touchUpInside) } //MARK: - Data From Selection table @IBAction func unwindSegueToMainView(segue: UIStoryboardSegue) { guard segue.identifier == "Segue" else {return} guard let sourceChosen = segue.source as? ChoseCurrencyController else {return} self.testArray = sourceChosen.testArrayChosen } @IBAction func pushButton(_ sender: UIButton) { performSegue(withIdentifier: "VC", sender: nil) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) changePlaceHolderColor() fetchData() pickerBase.delegate = self pickerBase.dataSource = self tableView.dataSource = self tableView.allowsSelection = false tableView.showsVerticalScrollIndicator = true ratesField.addTarget(self, action: #selector(ViewController.textFieldDidChange(_ : )), for: .editingChanged) print("\(arrayCountry) + table view") } //MARK: - PlaceHolder func changePlaceHolderColor() { if let textfield = searchBar.value(forKey: "searchField") as? UITextField { textfield.backgroundColor = #colorLiteral(red: 0.2756531239, green: 0.3340065181, blue: 0.4149620831, alpha: 1) textfield.attributedPlaceholder = NSAttributedString(string: textfield.placeholder ?? "", attributes: [NSAttributedString.Key.foregroundColor : #colorLiteral(red: 0.4900909662, green: 0.7071692348, blue: 1, alpha: 1)]) textfield.textColor = #colorLiteral(red: 0.4900909662, green: 0.7071692348, blue: 1, alpha: 1) if let leftView = textfield.leftView as? UIImageView { leftView.image = leftView.image?.withRenderingMode(.alwaysTemplate) leftView.tintColor = #colorLiteral(red: 0.4900909662, green: 0.7071692348, blue: 1, alpha: 1) searchBar.tintColor = #colorLiteral(red: 0.4900909662, green: 0.7071692348, blue: 1, alpha: 1) } } } //Observer for textField @objc func textFieldDidChange(_ textField: UITextField ) { converInRealTime() } //MARK: - SaveButton Action + Animation @objc func changeState3(sender: UIButton) { self.animateView3(sender) } func animateView3(_ viewToAnimate: UIView) { UIView.animate(withDuration: 0.15, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0.1, options: .curveEaseIn, animations: { viewToAnimate.transform = CGAffineTransform(scaleX: 0.5, y: 0.5) }) { (_) in UIView.animate(withDuration: 0.15, delay: 0, usingSpringWithDamping: 0.4, initialSpringVelocity: 0.2, options: .curveEaseIn, animations: { viewToAnimate.transform = CGAffineTransform(scaleX: 1, y: 1) }, completion: nil) } } //MARK: - Saving the text to NoteVC @IBAction func saveText(_ sender: UIButton) { userDefaultStore.set(noteField.text, forKey: "key_value") // store textView in userDefault self.textStory = userDefaultStore.string(forKey: "key_value")! print(textStory) } //MARK: - ClearButton Animation @objc func changeState2(sender: UIButton) { self.animateView2(sender) } func animateView2(_ viewToAnimate: UIView) { UIView.animate(withDuration: 0.15, delay: 0, usingSpringWithDamping: 4, initialSpringVelocity: 0.1, options: .curveEaseIn, animations: { viewToAnimate.transform = CGAffineTransform(scaleX: 0.5, y: 0.5) viewToAnimate.tintColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1) }) { (_) in UIView.animate(withDuration: 0.2, delay: 0, usingSpringWithDamping: 0.4, initialSpringVelocity: 0.2, options: .curveLinear, animations: { viewToAnimate.transform = CGAffineTransform(scaleX: 1, y: 1) viewToAnimate.tintColor = .black }, completion: nil) } } @IBAction func clearTextField(_ sender: UIButton) { noteField.text = "" print(testArray) } @IBAction func keyBoard(_ sender: UIButton) { self.view.endEditing(true) } //MARK: - Table View Delegate func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if !testArray.isEmpty { return testArray.count } else if searching { return searchCountry.count } else { if let currencyFetched = usd { return currencyFetched.rates.count } } return 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "firstCell") as! FIrstCustomCell if let currencyFetched = self.usd { if searching { cell.currenFirstLbl.text = searchCountry[indexPath.row] let selectedRate2 = baseRate * currencyFetched.rates[searchCountry[indexPath.row]]! let round2 = String(format: "%0.1f", selectedRate2) cell.rateFirstlbl.text = round2 cell.rateFirstlbl.textColor = .black modelsOfCountry.conditionCode = searchCountry[indexPath.row] cell.imageForCell.image = UIImage(named: modelsOfCountry.stringFlagImag) } else { cell.currenFirstLbl.text = Array(currencyFetched.rates.keys)[indexPath.row] let selectedRate = baseRate * Array(currencyFetched.rates.values)[indexPath.row] let round = String(format: "%0.1f", selectedRate) modelsOfCountry.conditionCode = Array(currencyFetched.rates.keys)[indexPath.row] cell.imageForCell.image = UIImage(named: modelsOfCountry.stringFlagImag) cell.rateFirstlbl.text = round cell.rateFirstlbl.textColor = .black } return cell } return UITableViewCell() } //MARK: - Actions func converInRealTime() { if let isGetString = ratesField.text { if let isDouble = Double(isGetString) { baseRate = isDouble fetchData() } } } //Setup Date func setupDate() { DispatchQueue.main.async { if let currencyFetched2 = self.usd { self.dateLabel.text = currencyFetched2.date + " 🗓" } } } //MARK: - Parsing Json func fetchData () { let url = URL(string: "https://api.exchangeratesapi.io/latest?base=\(actualBase)") URLSession.shared.dataTask(with: url!) { (data, response, error) in if error == nil { do { self.usd = try JSONDecoder().decode(Currency.self, from: data!) if let currency2 = self.usd?.rates { for (key, value) in currency2 { self.myCurrency.append(key as String) self.myValues.append(value as Double) } } } catch { print("Parse Error") } DispatchQueue.main.async { self.tableView.reloadData() self.pickerBase.reloadAllComponents() self.setupDate() } } else { print("error") } } .resume() } //Скрытие клавиатуры override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { self.view.endEditing(true) } } //MARK: - SearchBar delegate extension ViewController: UISearchBarDelegate { func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { if let currencyCountry = self.usd { searchCountry = currencyCountry.rates.keys.filter({$0.prefix(searchText.count) == searchText}) searching = true converInRealTime() tableView.reloadData() } } } extension ViewController: UITextViewDelegate { func textViewDidEndEditing(_ textView: UITextView) { keyBoardBut.isHidden = true } func textViewDidBeginEditing(_ textView: UITextView) { keyBoardBut.isHidden = false } } extension ViewController: UIPickerViewDelegate, UIPickerViewDataSource { func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return myCurrency.count } func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView { let view = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100)) let currencyBase = UILabel(frame: CGRect(x: 20, y: 0, width: 100, height: 100)) currencyBase.text = myCurrency[row] currencyBase.textColor = .white currencyBase.font = UIFont.systemFont(ofSize: 24, weight: .heavy) view.addSubview(currencyBase) return view } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { actualBase = myCurrency[row] modelsOfCountry.conditionCode = myCurrency[row] imageFlag.image = UIImage(named: modelsOfCountry.stringFlagImag) converInRealTime() pickerBase.reloadAllComponents() } }
#if canImport(UIKit) import UIKit.UIColor /// These are the colors we use at Thumbtack. public enum Color { /// Blue 100 – #eaf6fa public static let blue100: UIColor = UIColor(red: 0.91764706, green: 0.9647059, blue: 0.98039216, alpha: 1.0) /// Blue 200 – #b3ebff public static let blue200: UIColor = UIColor(red: 0.7019608, green: 0.92156863, blue: 1.0, alpha: 1.0) /// Blue 300 – #79d2f2 public static let blue300: UIColor = UIColor(red: 0.4745098, green: 0.8235294, blue: 0.9490196, alpha: 1.0) /// Blue – #009fd9 public static let blue: UIColor = UIColor(red: 0.0, green: 0.62352943, blue: 0.8509804, alpha: 1.0) /// Blue 500 – #007fad public static let blue500: UIColor = UIColor(red: 0.0, green: 0.49803922, blue: 0.6784314, alpha: 1.0) /// Blue 600 – #005979 public static let blue600: UIColor = UIColor(red: 0.0, green: 0.349, blue: 0.475, alpha: 1.0) /// Indigo 100 – #e8f1fd public static let indigo100: UIColor = UIColor(red: 0.9098039, green: 0.94509804, blue: 0.99215686, alpha: 1.0) /// Indigo 200 – #cce1ff public static let indigo200: UIColor = UIColor(red: 0.8, green: 0.88235295, blue: 1.0, alpha: 1.0) /// Indigo 300 – #96c2ff public static let indigo300: UIColor = UIColor(red: 0.5882353, green: 0.7607843, blue: 1.0, alpha: 1.0) /// Indigo – #5968e2 public static let indigo: UIColor = UIColor(red: 0.34901962, green: 0.40784314, blue: 0.8862745, alpha: 1.0) /// Indigo 500 – #4f54b3 public static let indigo500: UIColor = UIColor(red: 0.30980393, green: 0.32941177, blue: 0.7019608, alpha: 1.0) /// Indigo 600 – #383c80 public static let indigo600: UIColor = UIColor(red: 0.21960784, green: 0.23529412, blue: 0.5019608, alpha: 1.0) /// Purple 100 – #f5efff public static let purple100: UIColor = UIColor(red: 0.9607843, green: 0.9372549, blue: 1.0, alpha: 1.0) /// Purple 200 – #dfccff public static let purple200: UIColor = UIColor(red: 0.8745098, green: 0.8, blue: 1.0, alpha: 1.0) /// Purple 300 – #c9acfd public static let purple300: UIColor = UIColor(red: 0.788, green: 0.675, blue: 0.992, alpha: 1.0) /// Purple – #8d56eb public static let purple: UIColor = UIColor(red: 0.553, green: 0.337, blue: 0.922, alpha: 1.0) /// Purple 500 – #6637b6 public static let purple500: UIColor = UIColor(red: 0.4, green: 0.216, blue: 0.714, alpha: 1.0) /// Purple 600 – #492782 public static let purple600: UIColor = UIColor(red: 0.285, green: 0.153, blue: 0.508, alpha: 1.0) /// Green 100 – #e1fdf3 public static let green100: UIColor = UIColor(red: 0.88235295, green: 0.99215686, blue: 0.9529412, alpha: 1.0) /// Green 200 – #c6f7da public static let green200: UIColor = UIColor(red: 0.7764706, green: 0.96862745, blue: 0.85490197, alpha: 1.0) /// Green 300 – #73e4a2 public static let green300: UIColor = UIColor(red: 0.4509804, green: 0.89411765, blue: 0.63529414, alpha: 1.0) /// Green – #2db783 public static let green: UIColor = UIColor(red: 0.1764706, green: 0.7176471, blue: 0.5137255, alpha: 1.0) /// Green 500 – #16855b public static let green500: UIColor = UIColor(red: 0.086, green: 0.522, blue: 0.357, alpha: 1.0) /// Green 600 – #054e33 public static let green600: UIColor = UIColor(red: 0.02, green: 0.306, blue: 0.2, alpha: 1.0) /// Yellow 100 – #fdf7e7 public static let yellow100: UIColor = UIColor(red: 0.99215686, green: 0.96862745, blue: 0.90588236, alpha: 1.0) /// Yellow 200 – #ffebb3 public static let yellow200: UIColor = UIColor(red: 1.0, green: 0.92156863, blue: 0.7019608, alpha: 1.0) /// Yellow 300 – #ffdd80 public static let yellow300: UIColor = UIColor(red: 1.0, green: 0.8666667, blue: 0.5019608, alpha: 1.0) /// Yellow – #febe14 public static let yellow: UIColor = UIColor(red: 0.99607843, green: 0.74509805, blue: 0.078431375, alpha: 1.0) /// Yellow 500 – #a77005 public static let yellow500: UIColor = UIColor(red: 0.654, green: 0.438, blue: 0.019, alpha: 1.0) /// Yellow 600 – #714601 public static let yellow600: UIColor = UIColor(red: 0.442, green: 0.273, blue: 0.004, alpha: 1.0) /// Red 100 – #ffeff0 public static let red100: UIColor = UIColor(red: 1.0, green: 0.9372549, blue: 0.9411765, alpha: 1.0) /// Red 200 – #ffd9d9 public static let red200: UIColor = UIColor(red: 1.0, green: 0.8509804, blue: 0.8509804, alpha: 1.0) /// Red 300 – #ffb0b0 public static let red300: UIColor = UIColor(red: 1.0, green: 0.6901961, blue: 0.6901961, alpha: 1.0) /// Red – #ff5a5f public static let red: UIColor = UIColor(red: 1.0, green: 0.3529412, blue: 0.37254903, alpha: 1.0) /// Red 500 – #b22d31 public static let red500: UIColor = UIColor(red: 0.808, green: 0.209, blue: 0.266, alpha: 1.0) /// Red 600 – #7d0d10 public static let red600: UIColor = UIColor(red: 0.492, green: 0.051, blue: 0.065, alpha: 1.0) /// Black 300 – #676d73 public static let black300: UIColor = UIColor(red: 0.40392157, green: 0.42745098, blue: 0.4509804, alpha: 1.0) /// Black – #2f3033 public static let black: UIColor = UIColor(red: 0.18431373, green: 0.1882353, blue: 0.2, alpha: 1.0) /// Gray 200 – #fafafa public static let gray200: UIColor = UIColor(red: 0.98039216, green: 0.98039216, blue: 0.98039216, alpha: 1.0) /// Gray 300 – #e9eced public static let gray300: UIColor = UIColor(red: 0.9137255, green: 0.9254902, blue: 0.92941177, alpha: 1.0) /// Gray – #d3d4d5 public static let gray: UIColor = UIColor(red: 0.827451, green: 0.83137256, blue: 0.8352941, alpha: 1.0) /// White – #ffffff public static let white: UIColor = UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0) } public enum CornerRadius { public static let base: CGFloat = 4 } public enum Duration { public static let one: TimeInterval = 0.075 public static let two: TimeInterval = 0.15 public static let three: TimeInterval = 0.2 public static let four: TimeInterval = 0.25 public static let five: TimeInterval = 0.3 public static let six: TimeInterval = 0.35 } public enum FontWeight { case normal case bold } public enum Font { public static let title1Size: CGFloat = 28 public static let title1Weight: FontWeight = .bold public static let title1UIFontTextStyle: UIFont.TextStyle = .headline public static let title2Size: CGFloat = 24 public static let title2Weight: FontWeight = .bold public static let title2UIFontTextStyle: UIFont.TextStyle = .subheadline public static let title3Size: CGFloat = 22 public static let title3Weight: FontWeight = .bold public static let title3UIFontTextStyle: UIFont.TextStyle = .title1 public static let title4Size: CGFloat = 20 public static let title4Weight: FontWeight = .bold public static let title4UIFontTextStyle: UIFont.TextStyle = .title2 public static let title5Size: CGFloat = 18 public static let title5Weight: FontWeight = .bold public static let title5UIFontTextStyle: UIFont.TextStyle = .title3 public static let title6Size: CGFloat = 16 public static let title6Weight: FontWeight = .bold public static let title6UIFontTextStyle: UIFont.TextStyle = .body public static let title7Size: CGFloat = 14 public static let title7Weight: FontWeight = .bold public static let title7UIFontTextStyle: UIFont.TextStyle = .body public static let title8Size: CGFloat = 12 public static let title8Weight: FontWeight = .bold public static let title8UIFontTextStyle: UIFont.TextStyle = .body public static let text1Size: CGFloat = 16 public static let text1Weight: FontWeight = .normal public static let text1UIFontTextStyle: UIFont.TextStyle = .body public static let text2Size: CGFloat = 14 public static let text2Weight: FontWeight = .normal public static let text2UIFontTextStyle: UIFont.TextStyle = .body public static let text3Size: CGFloat = 12 public static let text3Weight: FontWeight = .normal public static let text3UIFontTextStyle: UIFont.TextStyle = .body } /// Values for transparent light and dark curtains that cover content. public enum Scrim { public static let light80: UIColor = UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 0.8) public static let dark80: UIColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.8) } public enum Space { /// Space 1 – 4.0pt public static let one: CGFloat = 4.0 /// Space 2 – 8.0pt public static let two: CGFloat = 8.0 /// Space 3 – 16.0pt public static let three: CGFloat = 16.0 /// Space 4 – 24.0pt public static let four: CGFloat = 24.0 /// Space 5 – 32.0pt public static let five: CGFloat = 32.0 /// Space 6 – 48.0pt public static let six: CGFloat = 48.0 } #endif
//: [Previous](@previous) import Foundation class Cow { class var amountOfLiters: Int { return 100 } } class SubClassCow: Cow { override class var amountOfLiters: Int { return 200 } } Cow.amountOfLiters SubClassCow.amountOfLiters public class StaticCow { public static var amountOfLiters: Int { return 300 } } class SubClassStaticCow: StaticCow { // Cannot override static var // override static var amountOfLiters: Int { // return 400 // } } StaticCow.amountOfLiters //: [Next](@next)
// // NetworkingService.swift // FlickrViewer // // Created by Eugene Belyakov on 03/07/2019. // Copyright © 2019 Ievgen Bieliakov. All rights reserved. // import UIKit extension HTTPMethod { var urlRequestValue: String { switch self { case .get: return "GET" default: return "POST" } } } extension URLSessionDataTask: Cancellable {} class NetworkingServiceImpl: NetworkingService { let session = URLSession(configuration: .default) func executeRequest(withURL url: URL, method: HTTPMethod = .get, completionHandler: @escaping NetworkRequestCompletionHandler) -> Cancellable { var urlRequest = URLRequest(url: url) urlRequest.httpMethod = method.urlRequestValue let task = session.dataTask(with: urlRequest) { (data, response, error) in if let error = error { completionHandler(data, error) return } completionHandler(data, nil) } task.resume() return task } }
// // MovieListTableViewController.swift // MovieSearch-C // // Created by Brooke Kumpunen on 3/29/19. // Copyright © 2019 Rund LLC. All rights reserved. // //Woot! Back to Swift B) import UIKit class MovieListTableViewController: UITableViewController { //MARK: - IBOutlets @IBOutlet weak var movieSearchBar: UISearchBar! //Source of truth for this tableView. var movies: [RUNMovie] = [] { didSet { updateViews() } } //MARK: - Methods func updateViews() { DispatchQueue.main.async { self.tableView.reloadData() } } override func viewDidLoad() { super.viewDidLoad() movieSearchBar.delegate = self } // MARK: - Table view data source override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return movies.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "movieCell", for: indexPath) as! RUNMovieTableViewCell let movie = movies[indexPath.row] cell.movie = movie return cell } /* // 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. } */ } //Gotta make a searchBarDelegate to use this fancy thing. extension MovieListTableViewController: UISearchBarDelegate { func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { guard let searchText = movieSearchBar.text, !searchText.isEmpty else {return} RUNMovieClient.searchMovies(withSearchTerm: searchText) { (movies) in self.movies = movies } } } //Strange, but calling the searchMovies function in the extension loads my empty source of truth immediately after someone begins searching. I suppose I could do it in the viewDidLoad as well to make it load up with some data, but that caused some issues last time. Might be a bit much.g
// // ViewController.swift // Todo-Test // // Created by mitchell hudson on 11/15/15. // Copyright © 2015 mitchell hudson. All rights reserved. // /* This example collects some ideas for different ways of working with tableview. The app acts as a simple Todo list using Core Data. Some of the ideas contained are: * Working with UIAlertController. This is used to add new todo items * Using more than one section. Here a second section is used to add a button at the bottom of the tableview * Managing two different table views cells via their identifier * Commit editing style, to delete cells. * Row Edit actions, used for adding tag and delete. * Setting tag color for cell background. * Setting an image in the cells imageview * Setting the cell accessory */ import UIKit class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { // MARK: IBOutlets // A reference to tableView in storyboard @IBOutlet weak var tableView: UITableView! // MARK: IBActions // This action is connected to the button (New) in the cell id: lastCell @IBAction func addNewCellButtonTapped(sender: UIButton) { addTodo() } // This action is connected to the + button in the bar at the bottom of the screen. @IBAction func addButtonTapped(sender: UIBarButtonItem) { addTodo() } // This method opens an alert with a text field, which adds a new todo. func addTodo() { let alert = UIAlertController(title: "Add Todo", message: "Add a new Todo", preferredStyle: .Alert) let ok = UIAlertAction(title: "OK", style: .Default) { (action:UIAlertAction) -> Void in let textField = alert.textFields![0] TodoManager.sharedInstance.addTodoWithName(textField.text!) self.tableView.reloadData() } let cancel = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil) alert.addTextFieldWithConfigurationHandler { (textField: UITextField) -> Void in textField.placeholder = "Todo name" } alert.addAction(ok) alert.addAction(cancel) self.presentViewController(alert, animated: true, completion: nil) } // MARK: TableView Datasource // The tableview will use two sections. // All of the todos are in section 0 // The New button in the last row is in section 1 func numberOfSectionsInTableView(tableView: UITableView) -> Int { // return 2 sections return 2 } // since there are two sections we need to return a different number of cells for each section. // Section 1 contains only 1 cell. func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 1 { // Section 2 has only one cell return 1 } return TodoManager.sharedInstance.count } func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if section == 0 { return "Todo Items" } else { return "Add a new todo" } } // There two different cell types. One for todos, and the other for the cell with the // new button. Check indexPath.section to find the section the table view is asking for // and use the correct id, to generate correct cell type. func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cellId = "cell" // This is the cell id for Todo Cells if indexPath.section == 1 { cellId = "lastCell" // This is the cell id for the Add Button } // Get a cell with one or the other id let cell = tableView.dequeueReusableCellWithIdentifier(cellId)! // Configure the cell depending on what type it is... if cellId == "cell" { // Configure a todo cell let todo = TodoManager.sharedInstance.getTodoAtIndex(indexPath.row) cell.textLabel?.text = todo.name cell.detailTextLabel?.text = "\(todo.tag)" setCellAccessory(cell, forCompletedState: todo.completed) cell.imageView?.image = UIImage(named: "tag-\(todo.tag)") self.setCellColorForTag(TagType(rawValue: Int(todo.tag))!, cell: cell) } else { // No need to configure the New Todo Cell, it has a button already. // If there were need to configure it do it here. } // Return the cell return cell } // MARK: TableView Delegate func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Check the section. if indexPath.section == 1 { // Cells in section 1 can not be edited return false } // Cells in section 0 can be edited return true } func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { // Use this with canEditRowAtIndexPath to delete cells if editingStyle == UITableViewCellEditingStyle.Delete { deleteRowAtIndexPath(indexPath) } } // This is a helper function to delete rows. Pass the indexPath to delete. func deleteRowAtIndexPath(indexPath: NSIndexPath) { // Delete the todo from the Manager TodoManager.sharedInstance.removeTodoAtIndex(indexPath.row) // Then delete the row from the tableview self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Left) } // This method shows the button on swipe. func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? { // Each button is a UITableViewRowAction. Set the parameters, and define a block that will // be executed when the button is tapped. You can use unicode icons and emojis in the action // title. See the delete button. // Make a delete button let delete = UITableViewRowAction(style: .Normal, title: "\u{267A}\n Delete") { (action: UITableViewRowAction, indexPath: NSIndexPath) -> Void in // Call the helper method to delete the cell. self.deleteRowAtIndexPath(indexPath) } delete.backgroundColor = UIColor.redColor() // Set the color // This button sets the .Tag1 let tag1 = UITableViewRowAction(style: .Normal, title: "Tag A") { (action: UITableViewRowAction, index: NSIndexPath) -> Void in // Set the tag // Set the tag for the todo at this index. self.setTag(.Tag1, index: indexPath.row) // Call the helper method to update the background color of the cell. self.setCellColorForTag(.Tag1, cell: self.tableView.cellForRowAtIndexPath(indexPath)!) } tag1.backgroundColor = TagType.Tag1.tagColor() // Set the button to .Tag2 let tag2 = UITableViewRowAction(style: .Normal, title: "Tag b") { (action: UITableViewRowAction, index: NSIndexPath) -> Void in // Set the tag self.setTag(.Tag2, index: indexPath.row) self.setCellColorForTag(.Tag2, cell: self.tableView.cellForRowAtIndexPath(indexPath)!) } tag2.backgroundColor = TagType.Tag2.tagColor() // Set the button to .Tag3 let tag3 = UITableViewRowAction(style: .Normal, title: "Tag C") { (action: UITableViewRowAction, index: NSIndexPath) -> Void in // Set the tag self.setTag(.Tag3, index: indexPath.row) self.setCellColorForTag(.Tag3, cell: self.tableView.cellForRowAtIndexPath(indexPath)!) } tag3.backgroundColor = TagType.Tag3.tagColor() // Return an array of UITableViewRowActions. return [delete, tag1, tag2, tag3] } // This is a helper function to change the tag of a row, and update the todo item tag property. func setTag(tag: TagType, index: Int) { TodoManager.sharedInstance.setTagForTodoAtIndex(index, tagType: tag) tableView.editing = false tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: index, inSection: 0)], withRowAnimation: UITableViewRowAnimation.Fade) } // A helper function to set the background color for cells, based on the tag. func setCellColorForTag(tag: TagType, cell: UITableViewCell) { cell.backgroundColor = tag.tagColor() } // Tableview delegate method notifies us when a cell is selected. // I'm using this here to deselect the cell, and set the completed property. func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { // Get the cell. let cell = tableView.cellForRowAtIndexPath(indexPath)! // Get the todo associated with that cell. let todo = TodoManager.sharedInstance.getTodoAtIndex(indexPath.row) // Deselect the cell, otherwise we see the gray highlight color. cell.selected = false // Set the todo's completed property. todo.completed = !todo.completed // Call on a helper function to update the cell accessory. setCellAccessory(cell, forCompletedState: todo.completed) // Save changes to the todo item. TodoManager.sharedInstance.save() } // A helper function to update the cell acccessory. In this case the accessory is the // checkmark. The checkmark shows the completed state for the todo item. // Pass this function the cell, and the completed value (true or false) func setCellAccessory(cell: UITableViewCell, forCompletedState completed: Bool) { if completed { // Set the accessory to the checkmark. cell.accessoryType = .Checkmark } else { // Set the accessory to none. cell.accessoryType = .None } } // MARK: View Lifecycle override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. tableView.contentInset = UIEdgeInsetsMake(20, 0, 0, 0) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
// // MyCenterTableViewController.swift // HoyoServicer // // Created by 赵兵 on 16/3/28. // Copyright © 2016年 com.ozner.net. All rights reserved. // import UIKit class MyCenterTableViewController: UITableViewController,MyCenterTableViewCellDelegate { override func viewDidLoad() { super.viewDidLoad() self.title="我的" self.automaticallyAdjustsScrollViewInsets=false tableView.registerNib(UINib(nibName: "MyCenterTableViewCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "MyCenterTableViewCell") tableView.separatorStyle=UITableViewCellSeparatorStyle.None NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(CurrentUserDidChange), name: CurrentUserDidChangeNotificationName, object: nil) } func CurrentUserDidChange() { self.tableView.reloadData() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.navigationController?.navigationBarHidden=false self.tabBarController?.tabBar.hidden=false } 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 Incomplete implementation, return the number of sections return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 1 } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return HEIGHT_SCREEN-HEIGHT_NavBar-HEIGHT_TabBar } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("MyCenterTableViewCell", forIndexPath: indexPath) as! MyCenterTableViewCell cell.selectionStyle=UITableViewCellSelectionStyle.None cell.delegate=self if User.currentUser?.headimageurl != nil { cell.headImg.image=UIImage(data: (User.currentUser?.headimageurl)!) } cell.phone.text=User.currentUser?.mobile cell.jobNo.text="(工号:"+(User.currentUser?.id)!+")" cell.name.text=User.currentUser?.name return cell } /** MyCenterTableViewCellDelegate 方法 - parameter Whitch: 1...6,从上到下 */ func ToDetailController(Whitch: Int) { switch Whitch { case 1: self.navigationController?.pushViewController(UserInfoViewController(), animated: true) print("查看资料") case 2: presentViewController(AuthenticationController(dissCall: nil), animated: true, completion: nil) case 3: self.navigationController?.pushViewController(MyExamViewController(), animated: true) print("我的考试") case 4: self.navigationController?.pushViewController(SelectIDTableViewController(), animated: true) print("我的网点") case 5: self.navigationController?.pushViewController(MyEvaluatTableViewController(), animated: true) print("我的评价") case 6: self.navigationController?.pushViewController(SettingViewController(), animated: true) print("设置") default: break } } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> 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, 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 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 prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
// // ParseManagedObjects.swift // MBAAAAAAASexamples // // Created by Eloe,Wendy C on 3/27/18. // Copyright © 2018 Eloe,Wendy C. All rights reserved. // import Foundation import Parse class Movie:PFObject, PFSubclassing { @NSManaged var title:String @NSManaged var year:Int @NSManaged var producer:String static func parseClassName() -> String { return "Movie" } } class Actor: PFObject, PFSubclassing { @NSManaged var name : String @NSManaged var starredIn: [Movie] static func parseClassName() -> String { return "Actor" } }
// // Blyp.swift // blyp // // Created by Hayden Hong on 3/3/20. // Copyright © 2020 Team Sonar. All rights reserved. // import Foundation import UIKit struct Blyp: Identifiable, Codable, Comparable { // MARK: Properties that are expected for the JSON var id: UUID = UUID() var name: String var description: String var createdOn: Date = Date() // Default to now var createdBy: String? // UUID var imageUrl: String? var imageBlurHash: String? var imageBlurHashWidth: CGFloat? var imageBlurHashHeight: CGFloat? var longitude: Double? var latitude: Double? var hasLocation: Bool { return longitude != nil && latitude != nil } var trigger: Trigger? // MARK: CodingKeys for JUST properties listed above enum CodingKeys: String, CodingKey { case id case name case description case createdOn case createdBy case imageUrl case imageBlurHash case imageBlurHashWidth case imageBlurHashHeight case longitude case latitude case trigger } // MARK: Properties used for saving and using Blyps var image: UIImage? var hasImage: Bool { return imageUrl != nil && imageBlurHash != nil && imageBlurHashWidth != nil && imageBlurHashHeight != nil } // MARK: Make sure sortable by date in reverse chronological order static func < (lhs: Blyp, rhs: Blyp) -> Bool { lhs.createdOn > rhs.createdOn } } enum Trigger: String, Codable { case immediate = "Immediately" case delayed = "On a future date" case uponDeceased = "When I have passed away" }
// // TableViewController.swift // sayILoveYou // // Created by minagi on 2018/10/26. // Copyright © 2018年 minagi. All rights reserved. // import UIKit class TableViewController: UIViewController,UITableViewDataSource,UITableViewDelegate { var word = [String]() var lang = [String]() func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return word.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell(style: .subtitle, reuseIdentifier: "myCell") let Word = word[indexPath.row] let Lang = lang[indexPath.row] cell.textLabel?.text = Word cell.detailTextLabel?.text = Lang return cell } override func viewDidLoad() { super.viewDidLoad() } }
// // ChangePasswordResponseModel.swift // NV_ORG // // Created by Netventure on 27/03/20. // Copyright © 2020 netventure. All rights reserved. // import Foundation struct ChangePasswordResponseModel : Decodable{ let code : Int? let message : String? }
// // IParcelModel.swift // SwiftCRUD // // Created by Владислав on 30.06.2020. // Copyright © 2020 Владислав. All rights reserved. // import Foundation protocol ParcelModelProtocol{ var idParcel: Int { get set } var typeOfParcel: Int { get set } var weight: Int { get set } var recipient: Int { get set } var droneModel: Int { get set } var cost: Int { get set } var percelStatus: ParcelStatus { get set } }
// // ProductListComponent.swift // ProductViewer // // Copyright © 2016 Target. All rights reserved. // import Tempo struct ProductListComponent: Component { var dispatcher: Dispatcher? func prepareView(_ view: ProductListView, item: ListItemViewState) { // Called on first view or ProductListView view.contentView.layer.borderWidth = 1.0 view.contentView.layer.borderColor = UIColor(red: 214.0/255.0, green: 214.0/255.0, blue: 214.0/255.0, alpha: 1).cgColor view.contentView.layer.cornerRadius = 5.0 } func configureView(_ view: ProductListView, item: ListItemViewState) { view.titleLabel.text = item.title view.priceLabel.text = item.priceStr view.productImage.loadImage(placeHolder: nil, urlString: item.imageUrl ?? "", completion: nil) } func selectView(_ view: ProductListView, item: ListItemViewState) { dispatcher?.triggerEvent(ListItemPressed(), item: item) } } extension ProductListComponent: HarmonyLayoutComponent { func heightForLayout(_ layout: HarmonyLayout, item: TempoViewStateItem, width: CGFloat) -> CGFloat { return 145.0 } }
// // LabelFilterCell.swift // Yelp // // Created by Jamie Tsao on 2/12/15. // Copyright (c) 2015 Jamie Tsao. All rights reserved. // import UIKit protocol LabelFilterDelegate: class { func labelFilter(labelFilterCell: LabelFilterCell, onSelectionChange changeValue:Bool) } class LabelFilterCell: UITableViewCell { weak var labelFilterDelegate: LabelFilterDelegate? @IBOutlet weak var filterLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // NSLog("\(filterLabel.text): \(selected) - \(self.selected)") if let delegate = labelFilterDelegate { delegate.labelFilter(self, onSelectionChange: selected) } } }
import UIKit var person = [ "firstname": "Mohammad", "middlename": "Juyel", "lastname": "Rana", "email": "mjuyelrana@gmail.com", "phone": "01726903951", "age": "23", "sex": "Male", "nationality": "Bangladeshi", "religion": "Mushlim", "website": "www.juyelrana.com" ] print(person["middlename"]!) print(person["lastname"]!) print(person["website"]!)
// // AnimationCollection.swift // JiSeobApps // // Created by kimjiseob on 19/11/2018. // Copyright © 2018 kimjiseob. All rights reserved. // import Foundation import UIKit class RepeatVerticalMove: UIView { override init(frame: CGRect) { super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } var objectList: [UIView] = [] var speed:CGFloat = 1 var randomColor : [UIColor] = [.red, .blue, .green, .yellow] private var cellSize: CGFloat? private var cnt: Int? private var objectSize: CGFloat! convenience init(size: CGFloat, color: UIColor, cnt: Int, padding: CGFloat = 0) { self.init(frame: CGRect(x: 0, y: 0, width: size, height: size)) self.cellSize = size self.cnt = cnt for row in (0...cnt - 1) { let view = makeCircle(color: color, size: size, cnt: cnt, padding: padding) let positionX: CGFloat! // if row != 0 { // positionX = ((size / CGFloat(cnt)) * CGFloat(row)) + padding // } else { // positionX = ((size / CGFloat(cnt)) * CGFloat(row)) // } positionX = (((size + padding) / CGFloat(cnt)) * CGFloat(row)) let positionY: CGFloat = (self.cellSize! - (cellSize! / CGFloat(cnt))) / 2 view.frame.origin = CGPoint(x: positionX, y: positionY) UIView.animate(withDuration: 0.5) { view.alpha = 1 } self.objectList.append(view) self.addSubview(view) } } func makeCircle(color : UIColor, size : CGFloat, cnt: Int, padding: CGFloat = 0) -> UIView { let totalPadding = padding * CGFloat(cnt - 1) objectSize = (size - totalPadding) / CGFloat(cnt) let returnView = UIView(frame: CGRect(x: 0, y: 0, width: objectSize, height: objectSize)) returnView.alpha = 0 returnView.layer.cornerRadius = CGFloat(objectSize) / 2 returnView.backgroundColor = color return returnView } func startAnimation() { for row in objectList { let random = CGFloat.random(in: 0...1) let randomD = CGFloat.random(in: 0.5...1) UIView.animateKeyframes(withDuration: TimeInterval(speed * randomD), delay: TimeInterval(speed * random), options: [.repeat, .autoreverse], animations: { row.frame = CGRect(x: row.frame.origin.x, y: 0, width: row.frame.width, height: self.cellSize!) // row.alpha = 0.5 }, completion: nil) } } func stopAnimation() { for row in objectList { row.layer.removeAllAnimations() // row.layer.ani UIView.animateKeyframes(withDuration: TimeInterval(speed), delay: 0, options: [], animations: { // row.frame.size.height = self.cellSize! / CGFloat(self.cnt!) row.frame.size.height = 0 row.alpha = 1 }, completion: nil) } } func activeRandomColor() { // for row in objectList { // if tempColor.count == 0 { // tempColor = self.randomColor // } // let random = Int.random(in: 0...tempColor.count-1) // row.backgroundColor = randomColor[random] // tempColor.remove(at: random) // } for (c,row) in objectList.enumerated() { let number = c % randomColor.count row.backgroundColor = randomColor[number] } } func endingAnimation() { for (c,row) in objectList.enumerated() { UIView.animate(withDuration: 0.3, animations: { row.frame = CGRect(x: row.frame.origin.x, y: self.cellSize! / 2, width: self.objectSize, height: 0) }, completion: { (bool) in row.layer.removeAllAnimations() row.layer.cornerRadius = self.objectSize / 2 UIView.animate(withDuration: 0.5, animations: { row.frame.size.height = self.objectSize }, completion: { (bool) in UIView.animate(withDuration: 1, delay: TimeInterval(0.1 * Double(c)), options: [], animations: { row.frame = CGRect(x: self.cellSize! / 2, y: -self.objectSize, width: self.objectSize, height: self.objectSize) }) { (bool) in let factor = Float(c) * 1 / 5 let animation = self.rotateAnimation(factor, x: row.frame.width * 3.3, y: row.frame.height * 3, size: CGSize(width: self.cellSize!, height: self.cellSize!)) row.layer.add(animation, forKey: "animation") } }) // }) } } func rotateAnimation(_ rate: Float, x: CGFloat, y: CGFloat, size: CGSize) -> CAAnimationGroup { let duration: CFTimeInterval = 1.5 let fromScale = 1 - rate let toScale = 0.2 + rate let timeFunc = CAMediaTimingFunction(controlPoints: 0.5, 0.15 + rate, 0.25, 1) // Scale animation let scaleAnimation = CABasicAnimation(keyPath: "transform.scale") scaleAnimation.duration = duration scaleAnimation.repeatCount = HUGE scaleAnimation.fromValue = fromScale scaleAnimation.toValue = toScale // Position animation let positionAnimation = CAKeyframeAnimation(keyPath: "position") positionAnimation.duration = duration positionAnimation.repeatCount = HUGE positionAnimation.path = UIBezierPath(arcCenter: CGPoint(x: x, y: y), radius: size.width / 2, startAngle: CGFloat(3 * Double.pi * 0.5), endAngle: CGFloat(3 * Double.pi * 0.5 + 2 * Double.pi), clockwise: true).cgPath // Aniamtion let animation = CAAnimationGroup() animation.animations = [scaleAnimation, positionAnimation] animation.timingFunction = timeFunc animation.duration = duration animation.repeatCount = HUGE animation.isRemovedOnCompletion = false return animation } }
// // Dashboard.swift // CureadviserApp // // Created by BekGround-2 on 17/03/17. // Copyright © 2017 BekGround-2. All rights reserved. // import UIKit class Dashboard: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UITableViewDelegate,UITableViewDataSource { @IBOutlet var DasboardCollection: UICollectionView! @IBOutlet var tableHeightConstraint: NSLayoutConstraint! @IBOutlet var DasboardClcHeightConstraint: NSLayoutConstraint! @IBOutlet var DasboardTable: UITableView! var radius = 0.0 let titleArr = ["Search Doctor","Search Camps","Search Hospital","Compare","Cureted Advice","Success Story"] let detailarr = ["More than 51,00 Dotors","More than 51,00 Camps","More than 51,00 Hospital","Your Choice","More than 51,00 Camps","More than 51,00 Dotors",] let imageArr = ["doctorc.png","camps.png","Hospital.png","Hospital.png","hand.png","story.png"] @IBOutlet var scrView: UIScrollView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.DasboardCollection.register(UINib(nibName: "DasboardCollectionCell", bundle: nil), forCellWithReuseIdentifier: "Cell") self.DasboardTable.register(UINib(nibName: "DasBoardTableCell", bundle: nil), forCellReuseIdentifier: "TblCell") } func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } // collectionview func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { var width = 100 var height = 140 radius = 45 DasboardClcHeightConstraint.constant = 284 if(((screenWidth-16)/3) > 105) { height = 158 width = 119 radius = 54.5 DasboardClcHeightConstraint.constant = 320 } return CGSize(width: width , height: height) } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 6 } // make a cell for each cell index path func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath as IndexPath) as! DasboardCollectionCell cell.titleLbl.text = titleArr[indexPath.row] cell.detailLbl.text = detailarr[indexPath.row] cell.img.image = UIImage.init(named: imageArr[indexPath.row]) if (indexPath.row % 3 == 0) { cell.img.layer.borderColor = themeColor.cgColor } if (indexPath.row % 3 == 1) { cell.img.layer.borderColor = UIColor.init(red: 183.0/255.0, green: 68.0/255.0, blue: 133.0/255.0, alpha: 1.0).cgColor } if (indexPath.row % 3 == 2) { cell.img.layer.borderColor = UIColor.init(red: 26.0/255.0, green: 117.0/255.0, blue: 118.0/255.0, alpha: 1.0).cgColor } cell.img.layer.cornerRadius = CGFloat(radius) cell.img.layer.borderWidth = 4 cell.img.clipsToBounds = true print(cell.img.frame.size) return cell } // MARK: - UICollectionViewDelegate protocol func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { // handle tap events print("You selected cell #\(indexPath.item)!") if(indexPath.row == 0) { //let page = UINib(nibName: "DoctorSearchVC", bundle: nil) self.navigationController?.pushViewController(DoctorSearchVC(nibName: "DoctorSearchVC", bundle: nil), animated: true) } else if(indexPath.row == 1) { self.navigationController?.pushViewController(CampsSearchVC(nibName: "CampsSearchVC", bundle: nil), animated: true) } else if(indexPath.row == 2) { self.navigationController?.pushViewController(HospitalSearchVC(nibName: "HospitalSearchVC", bundle: nil), animated: true) } else if(indexPath.row == 3) { self.navigationController?.pushViewController(CompareHospitalVC(nibName: "CompareHospitalVC", bundle: nil), animated: true) } else if(indexPath.row == 5) { self.navigationController?.pushViewController(SuccessStoriesVC(nibName: "SuccessStoriesVC", bundle: nil), animated: true) } } //MARK: UITableView Delegate And DataSource func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { tableHeightConstraint.constant = 120*5 // let height = tableView.frame.origin.y scrView.contentSize = CGSize(width: screenWidth, height: 1000) return 5 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: DasBoardTableCell = tableView.dequeueReusableCell(withIdentifier: "TblCell", for: indexPath) as! DasBoardTableCell return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { self.navigationController?.pushViewController(DasboardNewsVC(nibName: "DasboardNewsVC", bundle: nil), animated: true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func MenuAction(_ sender: Any) { self.menuContainerViewController!.toggleLeftSideMenuCompletion({}) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
// // DetailsCastsCell.swift // MovieApp // // Created by Ahmad Aulia Noorhakim on 28/02/21. // import UIKit import Nuke class DetailsCastsCell: UICollectionViewCell, DetailsCell { private enum Config { static let castCellPerLine = CGFloat(4) static let castCellSpacing = CGFloat(10) static let castCellRatio = CGFloat(0.66666666666) // = 2 / 3 } @IBOutlet weak var collectionView: UICollectionView! @IBOutlet private var maxHeightConstraint: NSLayoutConstraint! { didSet { maxHeightConstraint.isActive = false } } @IBOutlet private var maxWidthConstraint: NSLayoutConstraint! { didSet { maxWidthConstraint.isActive = false } } var maxHeight: CGFloat? = 0 { didSet { guard let maxHeight = maxHeight else { return } maxHeightConstraint.isActive = true maxHeightConstraint.constant = maxHeight } } var maxWidth: CGFloat? = 0 { didSet { guard let maxWidth = maxWidth else { return } maxWidthConstraint.isActive = true maxWidthConstraint.constant = maxWidth } } var itemSize: CGSize = CGSize.zero var casts : [Details.ViewModel.Cast] = [] { didSet { collectionView.reloadData() } } override func awakeFromNib() { super.awakeFromNib() collectionView.isScrollEnabled = false collectionView.delegate = self collectionView.dataSource = self let nib = UINib(nibName: CastCell.nibName, bundle: nil) collectionView.register(nib, forCellWithReuseIdentifier: CastCell.identifier) } func render(parentView: UIView, model: Details.ViewModel) { calculateDimensions(parentView, withItemCount: model.casts.count) self.casts = model.casts } private func calculateDimensions(_ parentView: UIView, withItemCount: Int) { let contentWidth = parentView.bounds.width - (Config.castCellSpacing * (Config.castCellPerLine + 1)) let itemWidth = contentWidth / Config.castCellPerLine let itemHeight = itemWidth / Config.castCellRatio let rowCount = ceil(CGFloat(withItemCount) / Config.castCellPerLine) self.maxWidth = parentView.bounds.width self.maxHeight = (itemHeight * rowCount) + (Config.castCellSpacing * (rowCount + 1)) self.itemSize = CGSize(width: itemWidth, height: itemHeight) } } extension DetailsCastsCell: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return itemSize } } extension DetailsCastsCell: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return casts.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CastCell.identifier, for: indexPath) let cast = casts[indexPath.row] if let castCell = cell as? CastCell { castCell.render(cast) } return cell } }
// // DataService.swift // Social Media // // Created by Junior Silva on 23/01/17. // Copyright © 2017 NJDevelopment. All rights reserved. // import Foundation import Firebase import SwiftKeychainWrapper // Pegar o Database URL do Firebase let DB_BASE = FIRDatabase.database().reference() let STORAGE_BASE = FIRStorage.storage().reference() class DataService { // CRIAR SINGLETOM static let dataService = DataService() // DB REFERENCES private var _REF_BASE = DB_BASE private var _REF_POSTS = DB_BASE.child("posts") private var _REF_USERS = DB_BASE.child("users") // STORAGE REFERENCES private var _REF_POST_IMAGES = STORAGE_BASE.child("post-picks") var REF_BASE: FIRDatabaseReference { return _REF_BASE } var REF_POSTS: FIRDatabaseReference { return _REF_POSTS } var REF_USERS: FIRDatabaseReference { return _REF_USERS } var REF_USERS_CURRENT: FIRDatabaseReference { let uid = KeychainWrapper.standard.string(forKey: KEY_UID) let user = REF_USERS.child(uid!) return user } var REF_POST_IMAGES: FIRStorageReference { return _REF_POST_IMAGES } func criarfirebaseDBUSer(uid: String, userData: Dictionary<String, String>) { REF_USERS.child(uid).updateChildValues(userData) } }
// // KakaoImgSearch_RXTests.swift // KakaoImgSearch_RXTests // // Created by BHJ on 2021/02/24. // import Foundation import XCTest import Nimble import RxTest @testable import KakaoImgSearch_RX class KakaoImgSearch_RXTests: XCTestCase { var resModel: ResultViewModel! var viewModel: DetailViewModelType! var imageData = ImgRequestData(query: "제주", page: 1 ,size: 1) override func setUp() { resModel = ResultViewModel() } func testApi() { var resultOfTask: Result<(ResponseModel, ImgRequestData),SearchServiceError>? let expectation = XCTestExpectation(description: "API가 제대로 동작하지 않아요.") APIManager.shared.request(imageData) { (res) in resultOfTask = res expectation.fulfill() } wait(for: [expectation], timeout: 5) XCTAssertNotNil(resultOfTask) } func testNextPage() { var isMore = resModel.isMorePage isMore = true expect(isMore).to( beTrue(), description: "더이상 보여줄 페이지가 없습니다.." ) } }
import Bow /// Protocol for automatic Fold derivation public protocol AutoFold: AutoLens {} public extension AutoFold { /// Provides a Fold focused on the items of the field given by a key path. /// /// - Parameter path: Key path to a field containing an array of items. /// - Returns: A Fold optic focused on the items of the specified field. static func fold<T>(for path: WritableKeyPath<Self, Array<T>>) -> Fold<Self, T> { return Self.lens(for: path) + Array<T>.fold } /// Provides a Fold focused on the items of the field given by a key path. /// /// - Parameter path: Key path to a field containing an `ArrayK` of items. /// - Returns: A Fold optic focused on the items of the specified field. static func fold<T>(for path: WritableKeyPath<Self, ArrayK<T>>) -> Fold<Self, T> { return Self.lens(for: path) + ArrayK<T>.fold } /// Provides a Fold focused on the items of a `Foldable` field given by a key path. /// /// - Parameter path: Key path to a field of a type with an instance of `Foldable`. /// - Returns: A Fold optic focused on the item wrapped in a `Foldable`. static func fold<T, F: Foldable>(for path: WritableKeyPath<Self, Kind<F, T>>) -> Fold<Self, T> { return Self.lens(for: path) + Kind<F, T>.foldK } }
// // UIHelper.swift import Foundation import UIKit import SwiftMessages public class UIHelper: NSObject { public static func showSuccessMessage(_ message: String){ let view = MessageView.viewFromNib(layout: .cardView) view.configureTheme(.success) view.configureDropShadow() view.button?.removeFromSuperview() view.configureContent(title: Utils.localizedString(forKey: "successTitle"), body: message) let config = UIHelper.getShowMessageConfig() SwiftMessages.show(config: config, view: view) } public static func showErrorMessage(_ message: String){ let view = MessageView.viewFromNib(layout: .cardView) view.configureTheme(.error) view.configureDropShadow() view.button?.removeFromSuperview() view.configureContent(title: Utils.localizedString(forKey: "errorTitle"), body: message) let config = UIHelper.getShowMessageConfig() SwiftMessages.show(config: config, view: view) } private static func getShowMessageConfig() -> SwiftMessages.Config{ var config = SwiftMessages.Config() config.presentationStyle = .top config.presentationContext = .window(windowLevel: UIWindow.Level.statusBar) config.dimMode = .gray(interactive: true) config.interactiveHide = true return config } }
// // UIViewController+.swift // SwiftExtenions // // Created by sergey petrachkov on 17/08/16. // Copyright © 2016 actonica. All rights reserved. // import Foundation extension UIViewController { func setNavigationItemBackButtonImage(backIndicatorImageName backIndicatorImageName: String, backIndicatorTransitionMaskImageName : String, renderingMode : UIImageRenderingMode = .AlwaysOriginal) { self.navigationController?.navigationBar.backIndicatorImage = UIImage(named: backIndicatorImageName)?.imageWithRenderingMode(.AlwaysOriginal); self.navigationController?.navigationBar.backIndicatorTransitionMaskImage = UIImage(named: backIndicatorTransitionMaskImageName)?.imageWithRenderingMode(renderingMode); } func setupTransparentNavigationBar(){ setupNavigationBar(backgroundImage: UIImage(), shadowImage: UIImage()); } func setupNavigationBar(backgroundImage backgroundImage: UIImage?, shadowImage: UIImage?, barMetrics : UIBarMetrics = .Default){ self.navigationController?.navigationBar.setBackgroundImage(backgroundImage, forBarMetrics: barMetrics); self.navigationController?.navigationBar.shadowImage = shadowImage; } func showAlert(title: String, message : String){ let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert); alertController.addAction(UIAlertAction(title: "Ok!", style: .Cancel, handler: nil)); self.presentViewController(alertController, animated: true, completion: nil); } func setAudioState(active: Bool){ do{ if(active){ try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback) } else{ try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient) } } catch{ NSLog("an error occured while making some fun with avaudiosession. Look at setAudioState, active param = \(active)"); } } }
// // Scanner.swift // ACE // // Created by Frederick C. Lee on 9/13/17. // Copyright © 2017 Amourine Technologies. All rights reserved. // import Foundation import SwiftScanner final class SourceText { class func scanSomething() { } class func sayHello() -> NSString { return "Hello Ric" } }
// // UserFavoritesViewController.swift // SMSample // // Created by CX_One on 7/28/16. // Copyright © 2016 CX_One. All rights reserved. // import UIKit import SDWebImage class UserFavoritesViewController: UIViewController,UITableViewDataSource,UITableViewDelegate{ var userFavoritesArray = NSMutableArray() var userFavoritesCategories = NSMutableArray() @IBOutlet weak var favoritesTableView: UITableView! override func viewDidLoad() { super.viewDidLoad() self.userFavoritesArray = CXDBSettings.sharedInstance.getTheUserFavouritesFromProducts("1") favoritesTableView.delegate = self; favoritesTableView.dataSource = self; favoritesTableView.separatorStyle = .None } func parseProductDescription(desc:String) -> String { let normalString : String = desc.html2String return normalString } func getProductInfo(produkt:CX_Products, input:String) -> String { let json :NSDictionary = (CXConstant.sharedInstance.convertStringToDictionary(produkt.json!)) let info : String = json.valueForKey(input) as! String return info } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{ return 1 } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return userFavoritesArray.count } func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 15.0 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{ let identifier = "Custom" var cell: SMFavoritesCell! = tableView.dequeueReusableCellWithIdentifier(identifier) as? SMFavoritesCell if cell == nil { tableView.registerNib(UINib(nibName: "SMFavoritesCell", bundle: nil), forCellReuseIdentifier: identifier) cell = tableView.dequeueReusableCellWithIdentifier(identifier) as? SMFavoritesCell } let product: CX_Products = self.userFavoritesArray[indexPath.section] as! CX_Products cell.favouritesTitleLabel.text = product.name let prodImage :String = CXDBSettings.getProductImage(product) cell.favouritesImageview.sd_setImageWithURL(NSURL(string:prodImage)!, placeholderImage: UIImage(named: "smlogo.png"), options:SDWebImageOptions.RefreshCached) cell.favouritesDetailTextView.text = self.parseProductDescription(self.getProductInfo(product, input: "Description")) return cell } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 80.0;//Choose your custom row height } func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == UITableViewCellEditingStyle.Delete{ let product: CX_Products = self.userFavoritesArray[indexPath.section] as! CX_Products CXDBSettings.sharedInstance.userAddedToFavouriteList(product, isAddedToFavourite: false) self.favoritesTableView.beginUpdates() self.userFavoritesArray.removeObjectAtIndex(indexPath.section) // also remove an array object if exists. self.favoritesTableView.deleteSections(NSIndexSet(index: indexPath.section), withRowAnimation: .Left) self.favoritesTableView.endUpdates() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let products:CX_Products = self.userFavoritesArray[indexPath.section] as! CX_Products let predicate: NSPredicate = NSPredicate(format: "name = %@", products.type!) //let fetchRequest = CX_Product_Category.MR_requestAllSortedBy("pid", ascending: true) let fetchRequest = NSFetchRequest(entityName: "CX_Product_Category") fetchRequest.predicate = predicate //fetchRequest.entity = productEn // self.productCategories = CX_Product_Category.MR_executeFetchRequest(fetchRequest) let productCatList :NSArray = CX_Product_Category.MR_executeFetchRequest(fetchRequest) // let product: CX_Products = self.userFavoritesArray[indexPath.section] as! CX_Products let detailView = ViewPagerCntl.init() detailView.product = products detailView.itemIndex = indexPath.section detailView.productCategory = productCatList.lastObject as? CX_Product_Category self.navigationController?.pushViewController(detailView, animated: true) } func showAlertView(message:String, status:Int) { let alert = UIAlertController(title: "Silly Monks", message:message, preferredStyle: UIAlertControllerStyle.Alert) //alert.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.Default, handler: nil)) let okAction = UIAlertAction(title: "Okay", style: UIAlertActionStyle.Default) { UIAlertAction in if status == 1 { } } let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Default) { UIAlertAction in if status == 1 { } } alert.addAction(okAction) alert.addAction(cancelAction) self.presentViewController(alert, animated: true, completion: nil) } }
// // NDAdvertiseView.swift // NDYingKe_swift4 // // Created by 李家奇_南湖国旅 on 2017/8/11. // Copyright © 2017年 NorthDogLi. All rights reserved. // import UIKit import SDWebImage class NDAdvertiseView: UIView { fileprivate var adShowTime = 5 fileprivate let duration:CFTimeInterval = 0.25 fileprivate var timer = Timer() fileprivate let dataModel = NDLoginDataModel() //广告 fileprivate var adImageView = UIImageView() fileprivate var showTimeBtn = UIButton() override init(frame: CGRect) { super.init(frame: frame) //self.frame = CGRect.init(x: 0, y: 0, width: kSCREEN_WIDTH, height: kSCREEN_HEIGHT) setUpUI() initialization() advertiseShow() } func setUpUI() { self.addSubview(adImageView) self.adImageView.frame = self.frame adImageView.isUserInteractionEnabled = true let tapGes = UITapGestureRecognizer.init(target: self, action: #selector(adImageTap)) adImageView.addGestureRecognizer(tapGes) //showTimeBtn = UIButton.init(type: UIButtonType.custom) self.addSubview(showTimeBtn) //重新布局 showTimeBtn.frame = CGRect.init(x: self.ND_Width - __X(x: 70), y: __Y(y: 30), width: __X(x: 50), height: __X(x: 20)) showTimeBtn.setTitleColor(UIColor.white, for: UIControlState.normal) showTimeBtn.backgroundColor = UIColor.init(colorLiteralRed: 0, green: 0, blue: 0, alpha: 0.8) showTimeBtn.titleLabel?.font = __FONT(x: 15) showTimeBtn.setTitle("跳过5", for: UIControlState.normal) showTimeBtn.layer.cornerRadius = 3 showTimeBtn.layer.masksToBounds = true showTimeBtn.addTarget(self, action: #selector(goHomePage), for: UIControlEvents.touchUpInside) } fileprivate func initialization() { timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(timerGo), userInfo: nil, repeats: true) RunLoop.current.add(timer, forMode: RunLoopMode.commonModes) let launchImage = UIImage.init(named: self.getLaunchImage()) self.adImageView.image = launchImage//UIColor.init(patternImage: launchImage!) } /** 展示广告*/ fileprivate func advertiseShow() { let lastCacheImage = SDWebImageManager.shared().imageCache?.imageFromDiskCache(forKey: NDUserDefauls.getAdvertiseImage()) if lastCacheImage == nil { downloadAdvertise() }else { self.adImageView.image = lastCacheImage } } //下载广告 fileprivate func downloadAdvertise() { self.dataModel.getAdvertiseModel { [unowned self] (message) in if message == kFailer { return; } var imageURL = URL.init(string: self.dataModel.resources[0].image) if !self.dataModel.resources[0].image.hasPrefix("http://") { imageURL = URL.init(string: String.init(format: "%@%@", kTJPCommonServiceAPI, self.dataModel.resources[0].image)) } /** 优先级 userInteractive userInitiated default utility background unspecified */ let anotherQueue = DispatchQueue(label: "com.nh", qos: .userInitiated, attributes: .concurrent) anotherQueue.async { SDWebImageManager.shared().loadImage(with: imageURL, options: SDWebImageOptions.avoidAutoSetImage, progress: nil, completed: { (image, data, error, cacheType, isSuccees, imageURL) in NDUserDefauls.setAdvertiseImage(value: self.dataModel.resources[0].image) NDUserDefauls.setAdvertiseLink(value: self.dataModel.resources[0].link) //显示广告 if image != nil { DispatchQueue.main.async { self.adImageView.image = image } print("广告下载成功") } }) } } } //点击前往广告链接 @objc fileprivate func adImageTap() { } //前往主页 @objc fileprivate func goHomePage() { //销毁定时器 timer.invalidate() self.removeFromSuperview() } //获取启动图片 fileprivate func getLaunchImage() -> String { var launchImageName = "" let orentationStr = "Portrait" let viewSize = UIScreen.main.bounds.size let diction = Bundle.main.infoDictionary var launchImages = [NSDictionary]() launchImages = diction?["UILaunchImages"] as! [NSDictionary] for dic in launchImages { let imageSize = CGSizeFromString(dic["UILaunchImageSize"] as! String) if __CGSizeEqualToSize(imageSize, viewSize) && orentationStr == dic["UILaunchImageOrientation"] as! String { launchImageName = dic.value(forKey: "UILaunchImageName") as! String; } } return launchImageName } @objc fileprivate func timerGo() { if adShowTime == 0 { //销毁定时器 timer.invalidate() self.removeFromSuperview() }else { adShowTime = adShowTime - 1 //print("-------\(adShowTime)") let subString = String.init(format: "跳过%d", adShowTime) self.showTimeBtn.setTitle(subString, for: UIControlState.normal) } } deinit { print("销毁广告页面") } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
// // ChooseView.swift // ApZoo // // Created by Mac on 10/06/2021. // import SwiftUI struct ChooseView: View { @EnvironmentObject var ObservedTM: TaskManager var W_List: [Worker] { ObservedTM.WorkerList } var body: some View { NavigationView{ VStack{ Text("Choose worker") .font(.system(size: 40)) .fontWeight(.bold) ScrollView{ ForEach(0..<W_List.count, id: \.self) { worker in NavigationLink( destination: WorkerView(worker: W_List[worker]), label: { ZStack(alignment: Alignment(horizontal: .center, vertical: .center)){ Capsule() .frame(width: 200, height: 60, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/) .foregroundColor(.WhiteBlue) Text("\(W_List[worker].Name)") .foregroundColor(.DarkBlue) } }) } } } } } } struct ChooseView_Previews: PreviewProvider { static var previews: some View { ChooseView() } }
// // ListBeerViewController.swift // Bebida-Fractal // // Created by Fernanda de Lima on 12/12/2017. // Copyright © 2017 Empresinha. All rights reserved. // import UIKit class BeerListViewController: UIViewController { @IBOutlet weak var beerTableView: UITableView! let searchController = UISearchController(searchResultsController: nil) var presenter : BeerListPresenterProtocol? var listBeer: [Beer] = [] var filteredBeers: [Beer] = [] override func viewDidLoad() { super.viewDidLoad() presenter?.viewDidLoad() self.beerTableView.rowHeight = UITableViewAutomaticDimension self.beerTableView.estimatedRowHeight = 90 configSearchBar() } func configSearchBar(){ self.searchController.searchResultsUpdater = self self.searchController.obscuresBackgroundDuringPresentation = false self.searchController.hidesNavigationBarDuringPresentation = false self.searchController.searchBar.placeholder = "Search" let scb = searchController.searchBar scb.tintColor = .white scb.barTintColor = .white if let txt = scb.value(forKey: "searchField") as? UITextField{ txt.textColor = .white if let bg = txt.subviews.first{ bg.backgroundColor = #colorLiteral(red: 0.4745098054, green: 0.8392156959, blue: 0.9764705896, alpha: 1) bg.layer.cornerRadius = 10 bg.clipsToBounds = true bg.tintColor = .white } } self.navigationItem.searchController = searchController self.definesPresentationContext = true searchController.isActive = true } func searchBarIsEmpty() -> Bool { // Returns true if the text is empty or nil return searchController.searchBar.text?.isEmpty ?? true } func filterContentForSearchText(_ searchText: String) { filteredBeers = listBeer.filter({( beer : Beer) -> Bool in return beer.title.lowercased().contains(searchText.lowercased()) }) beerTableView.reloadData() } func isFiltering() -> Bool { return searchController.isActive && !searchBarIsEmpty() } } extension BeerListViewController : BeerListViewProtocol{ func showBeers(with beers: [Beer]) { listBeer = beers beerTableView.reloadData() } func showError() { //mostra erro } func showLoading() { //mostra progress } func hideLoading() { //esconder } func reloadInterface(_ beers: [Beer]){ self.listBeer = beers self.beerTableView.reloadData() } } extension BeerListViewController : UITableViewDataSource, UITableViewDelegate{ func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if isFiltering() { return filteredBeers.count } return listBeer.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: "beerCell") as? BeerViewCell else { return UITableViewCell() } let beer:Beer if isFiltering() { beer = filteredBeers[indexPath.row] } else { beer = listBeer[indexPath.row] } // let beer = listBeer[indexPath.row] cell.set(forBeer: beer, presenter: self.presenter!) return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let beer:Beer if isFiltering() { beer = filteredBeers[indexPath.row] } else { beer = listBeer[indexPath.row] } presenter?.showBeerDetail(forBeer: beer) } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 90 } } extension BeerListViewController: UISearchResultsUpdating{ func updateSearchResults(for searchController: UISearchController) { filterContentForSearchText(searchController.searchBar.text!) } }
/* Copyright Airship and Contributors */ import Foundation class ExpirableTask: AirshipTask { private let _taskID : String @objc public var taskID: String { get { return self._taskID } } private let _requestOptions : TaskRequestOptions @objc public var requestOptions: TaskRequestOptions { get { return self._requestOptions } } private var _expirationHandler: (() -> Void)? = nil @objc public var expirationHandler: (() -> Void)? { get { return _expirationHandler } set { if (isExpired) { newValue?() self._expirationHandler = nil } else { self._expirationHandler = newValue } } } private var _completionHandler: (() -> Void)? = nil @objc public var completionHandler: (() -> Void)? { get { return _completionHandler } set { if (isCompleted) { newValue?() self._completionHandler = nil } else { self._completionHandler = newValue } } } private var isExpired = false private var isCompleted = false private var onTaskFinshed: (Bool) -> Void @objc public init(taskID: String, requestOptions: TaskRequestOptions, onTaskFinshed: @escaping (Bool) -> Void) { self._taskID = taskID self._requestOptions = requestOptions self.onTaskFinshed = onTaskFinshed } @objc public func taskCompleted() { finishTask(true) } @objc public func taskFailed() { finishTask(false) } @objc public func expire() { guard !isCompleted && !self.isExpired else { return } self.isExpired = true if let handler = expirationHandler { handler() self._expirationHandler = nil } } private func finishTask(_ result: Bool) { guard !isCompleted else { return } self.isCompleted = true self.expirationHandler = nil self.completionHandler?() self.completionHandler = nil self.onTaskFinshed(result) } }
// // ViewController.swift // Conversor // // Created by ALgy Aly on 7/10/19. // Copyright © 2019 ALgy Aly. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var recept: UITextField! @IBOutlet weak var result: UITextField! @IBOutlet weak var toDecimal: CustomUIButton! @IBOutlet weak var toBinario: CustomUIButton! @IBAction func actionBin(_ sender: Any) { let b = recept.text! let letras : [Character] = Array(b) if procurarAlfabeto(letras: letras) { recept.backgroundColor = UIColor.white var decimal : Double = 0 var elevado : Int = b.count - 1 for letra in letras { if letra == "1" { decimal = decimal + pow(Double(2),Double(elevado)) } elevado -= 1 } result.text = "\(Int(decimal))" } else { //Erro! Introduza número binário de 2/4/8/16 bits!\nTente novamente recept.backgroundColor = UIColor.red toDecimal.shake() } } func procurarAlfabeto(letras: [Character]) -> Bool { for letra in letras { if letra != "0" && letra != "1" { return false } } return true } @IBAction func bottomDec(_ sender: Any) { if let dec = Int(recept.text!) { if dec > 0 { recept.backgroundColor = UIColor.white var binario = "" var div = dec while div != 0 { if Double(div%2) != 0.5 { binario.append(String(div%2)) } else { binario.append("1") } div = div/2 } let binar = Array(binario) var c = binario.count - 1 binario = "" while c >= 0 { binario.append(binar[c]) c-=1 } result.text = binario } else if dec == 0 { result.text = "0" } else { //Erro! Número decimal deve ser positivo //Tem que resolver ainda recept.backgroundColor = UIColor.red toBinario.shake() // recept.layer.borderColor = UIColor.red.cgColor } } else { //Erro de campo vazio //Tem que se resolver ainda recept.layer.borderColor = UIColor.red.cgColor } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } }
// // Spacebar.swift // Keyboard // // Created by Matt Zanchelli on 6/16/14. // Copyright (c) 2014 Matt Zanchelli. All rights reserved. // import UIKit class Spacebar: MetaKey { override func refreshAppearance() { UIView.animateWithDuration(0.18, delay: 0.0, usingSpringWithDamping: 1.0, initialSpringVelocity: 0.0, options: .BeginFromCurrentState | .AllowUserInteraction, animations: { if self.highlighted { self.horizontalLine.backgroundColor = self.enabledTintColor self.horizontalLine.frame.size.height = 3 } else { self.horizontalLine.backgroundColor = self.disabledTintColor self.horizontalLine.frame.size.height = 1 } // Center the line vertically self.horizontalLine.frame.origin.y = CGRectGetMidY(self.bounds) - (self.horizontalLine.frame.size.height/2) }, completion: nil) } let horizontalLine: UIView = { let view = UIView() view.autoresizingMask = .FlexibleWidth | .FlexibleTopMargin | .FlexibleBottomMargin return view }() override init(frame: CGRect) { super.init(frame: frame) // Initialization code horizontalLine.frame = CGRect(x: 0, y: CGRectGetMidY(self.bounds) - 0.5, width: self.bounds.size.width, height: 1) self.addSubview(horizontalLine) } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } }
// // MovieCollectionViewCell.swift // DemoBelatrix // // Created by everis on 2/29/20. // Copyright © 2020 everis. All rights reserved. // import UIKit import DemoInteractor class MovieCollectionViewCell: UICollectionViewCell { @IBOutlet weak var movieImageView : UIImageView! @IBOutlet weak var movieTitleLabel : UILabel! private var downloadTask : URLSessionTask? override func prepareForReuse() { movieImageView.image = nil movieTitleLabel.text = "" if downloadTask?.state == .running || downloadTask?.state == .suspended{ downloadTask?.cancel() downloadTask = nil } } func displayInfo(movie : Movie){ self.setTextAnimatedInLabel(labelAnimated: self.movieTitleLabel, textLabel: movie.title) if let url = URL(string: movie.posterImageUrl){ self.downloadTask = MTImageDownloadManager.downloadImage(url: url, success: {[weak self] (image) in guard let welf = self else {return} UIView.transition(with: welf.movieImageView, duration: 0.25, options: .transitionCrossDissolve, animations: { welf.movieImageView.image = image welf.movieTitleLabel.text = "" }, completion: nil) }, failure: { [weak self] in guard let welf = self else {return} UIView.transition(with: welf.movieImageView, duration: 0.25, options: .transitionCrossDissolve, animations: { welf.movieImageView.image = UIImage(named: "posterPlaceholder") }, completion: nil) }) } } func setTextAnimatedInLabel(labelAnimated : UILabel, textLabel : String){ UIView.transition(with: labelAnimated, duration: 0.25, options: .transitionCrossDissolve, animations: { labelAnimated.text = textLabel }, completion: nil) } }
import Foundation // FIZZBUZZ a list of numbers and print Fizz when divisible by 3, Buzz when divisible by 5, and FizzBuzz when divisible by both 3 and 5 let number = [2,5,8,15,345,6,7,78,89,9] for num in number { if num % 15 == 0 { print("FizzBuzz: \(num)") } else if num % 3 == 0 { print("Fizz: \(num)") } else if num % 5 == 0 { print("Buzz: \(num)") } else { print("num") } } for n in 1...100 { switch n { case n where (n % 3 == 0) && (n % 5 == 0): print("FizzBuzz: \(n)") case n where (n % 3 == 0): print("Buzz: \(n)") case n where (n % 5 == 0): print("Fizz: \(n)") default: print(n) } } func fizzbuzz (number: [Int]) { for n in number { switch n { case n where (n % 3 == 0) && n % 5 == 0: print("FizzBuzz") case n where (n % 3 == 0): print("Fizz") case n where (n % 5 == 0): print("Buzz") default: print(n) } } } fizzbuzz(number: [3,4,6,7,4,3,2]) let values = [7,8,9,9,35,67,89,0,97] func fizzbuzz(array: [Int]) { for n in array { switch n { case n where (n % 3 == 0) && (n % 5 == 0): print("fizzbuzz") case n where (n % 3 == 0): print("fizz") case n where (n % 5 == 0): print("buzz") default: print(n) } } } func fizzbuzz2(array: [Int]) { for n in array { switch n { case n where (n % 3 == 0) && (n % 5 == 0): print("fizzbuzz") case n where (n % 3 == 0): print("fizz") case n where (n % 5 == 0): print("buzz") default: print(n) } } } fizzbuzz2(array: [5,6,7,8,9,10]) func fizzbuzz(fizz: [Int]) { for i in fizz { switch i { case i where (i % 3 == 0) && (i % 5 == 0): print("fizz buzz") case i where i % 3 == 0: print("fizz") case i where i % 5 == 0: print("buzz") default: print(i) } } } func fizzbuzze(arrays: [Int]) { for array in arrays { switch array { case array where (array % 3 == 0) && (array % 5 == 0): print("fizz") case array where array % 3 == 0: print("buzz") case array where array % 5 == 0: print("fizzbuzz") default: print(array) } } }
// // ViewController.swift // TicTacToe // // Created by Alex Paul on 11/8/18. // Copyright © 2018 Pursuit. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var gamePrompt: UILabel! @IBOutlet var gameButtons: [GameButton]! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. for button in gameButtons { button.setBackgroundImage(nil, for: .normal) button.isEnabled = true } } var startGame = TicTacToeBrain() var gameB = GameButton() @IBAction func gameButtonPressed(_ gameButton: GameButton) { if startGame.playerOne == 0 { startGame.gameMatrix[gameButton.row][gameButton.col] = "x" gameButton.setBackgroundImage(UIImage(named: "knifeX"), for: .normal) startGame.playerOne = 1 } else { gameButton.setBackgroundImage(UIImage(named: "pumpkinO"), for: .normal) startGame.gameMatrix[gameButton.row][gameButton.col] = "o" startGame.playerOne = 0 } gamePrompt.text = startGame.winCondition("x", "o") print(gamePrompt.text ?? "bleep") print(startGame.gameMatrix) } @IBAction func resetButton(_ sender: UIButton) { } }
struct Count: Sequence, Generator { var start: Int var step: Int init(start: Int = 0, step: Int = 1) { self.start = start self.step = step } func generate() -> Count { return self } mutating func next() -> Int? { let val = start start += step return val } } func count(start: Int = 0, step: Int = 1) -> Count { return Count(start: start, step: step) } struct Interpose<S: Sequence, T where T == S.GeneratorType.Element> : Sequence, Generator { typealias Element = T let sep: T var gen: S.GeneratorType var needSep: Bool var nextOrNil: T? init(separator: T, sequence: S) { self.sep = separator self.needSep = false self.gen = sequence.generate() self.nextOrNil = self.gen.next() } func generate() -> Interpose<S, T> { return self } mutating func next() -> T? { if needSep { needSep = false return sep } else { let n = nextOrNil if n { nextOrNil = gen.next() needSep = nextOrNil != nil } return n } } } func interpose<S: Sequence, T where T == S.GeneratorType.Element> (separator: T, sequence: S) -> Interpose<S, T> { return Interpose(separator: separator, sequence: sequence) } struct TakeWhile<S: Sequence, T where T == S.GeneratorType.Element> : Sequence, Generator { var gen: S.GeneratorType let pred: T->Bool init(sequence: S, predicate: T->Bool) { gen = sequence.generate() pred = predicate } func generate() -> TakeWhile<S, T> { return self } mutating func next() -> T? { if let val: T = gen.next() { if pred(val) { return val } } return nil } } func takewhile<S: Sequence, T where T == S.GeneratorType.Element> (sequence: S, predicate: T->Bool) -> TakeWhile<S, T> { return TakeWhile(sequence: sequence, predicate: predicate) }
// // headerCollectionReusableView.swift // FlickrSearch // // Created by Hana Demas on 8/1/18. // Copyright © 2018 ___HANADEMAS___. All rights reserved. // import UIKit class FlickrHeaderCollectionReusableView: UICollectionReusableView { //MARK: UIOutlets @IBOutlet var headerLabel: UILabel! //MARK: Functions func styleElements() { headerLabel.font = Font.bold17 self.backgroundColor = UIColor.flickrYellow() } }
/** A `ColorLight` that can light up in a `Color` and color temperature. A `ColorLight` also allows users to execute `Effect`s on the `ColorLight`. */ class ColorLight: Device { /** The `LIFXColor` the `ColorLight` lights up with. */ let color: LIFXColor /** The `Effect` that the `ColorLight` currently displays. */ let currentEffect: Effect? = nil /** Initializes a new `ColorLight`. - parameters: - service: The `Service` that is used to communicate with this `ColorLight`. - port: The IP port number used by a LIFX light for the `service`. - hardwareInfo: Hardware information about the `ColorLight`. - firmware: Firmware information about the `ColorLight`. - transmissionInfo: Transmission information about the `ColorLight`. - powerLevel: The power level of the `ColorLight`. - runtimeInfo: Runtime information about the `ColorLight`. - label: The label describing the `ColorLight`. - location: The `Location` of the `ColorLight`. - group: The `Group` the `ColorLight` belongs to. - color: The `LIFXColor` the `ColorLight` lights up with. - precondition: The lenght of the UTF-8 encoding of the `label` MUST be less or equal to 32 bytes. */ init(service: Service, port: UInt32, hardwareInfo: HardwareInfo, firmware: Firmware, wifiInfo: TransmissionInfo, powerLevel: PowerLevel, runtimeInfo: RuntimeInfo, label: String, location: Location, group: Group, color: LIFXColor) { self.color = color // #warning("Use FutureValue here too") fatalError("Unimplemented") } /** Changes the `powerLevel` with a `transitionTime` that is used to be performed the transition. - parameters: - powerLevel: The power level of the `ColorLight`. - transitionTime: Transition time in milliseconds. */ func changePowerLevel(_ powerLevel: PowerLevel, transitionTime: UInt32) { fatalError("Not implemented") } }
// // PinteresLayout.swift // Movie // // Created by Daniel on 16/3/18. // Copyright © 2016年 Daniel. All rights reserved. // import UIKit protocol PinterestLayoutDelegate { func collectionView(collectionView:UICollectionView,heightForPhotoAtIndexPath indexPath:NSIndexPath,withWidth width:CGFloat) -> CGFloat } class PinterestLayout: UICollectionViewLayout { //MARK:- Property var delegate:PinterestLayoutDelegate! //MARK: - Private Property private var cache = [PinterestLayoutAttributes]() private var contentHeight:CGFloat = 0.0 private var numberOfColums = 2 private var cellPadding:CGFloat = 6.0 override func prepareLayout() { if cache.isEmpty{ let columnWidth:CGFloat = contentWidth / CGFloat(numberOfColums) let width:CGFloat = columnWidth - 2 * cellPadding let xOffset:[CGFloat] = [0.0,columnWidth] var yOffset = [CGFloat](count: numberOfColums, repeatedValue: 0) var column:Int = 0 for item in 0..<_collectionView.numberOfItemsInSection(0){ let indexPath = NSIndexPath(forItem: item, inSection: 0) let photoHeight = delegate.collectionView(_collectionView, heightForPhotoAtIndexPath: indexPath, withWidth: width) let height = photoHeight + 2 * cellPadding + 20 let frame = CGRect(x: xOffset[column], y: yOffset[column], width: columnWidth, height: height) let insetFrame = CGRectInset(frame, cellPadding, cellPadding) let attributes = PinterestLayoutAttributes(forCellWithIndexPath: indexPath) attributes.frame = insetFrame cache.append(attributes) yOffset[column] += height contentHeight = max(contentHeight, CGRectGetMaxY(frame)) column = column >= (numberOfColums - 1) ? 0 : 1 } } } override func collectionViewContentSize() -> CGSize { return _contentSize } override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? { var attributes = [UICollectionViewLayoutAttributes]() for attribute in cache { if CGRectIntersectsRect(attribute.frame, rect){ attributes.append(attribute) } } return attributes } override class func layoutAttributesClass() -> AnyClass { return PinterestLayoutAttributes.self } } //MARK: - Private Var extension PinterestLayout{ private var _collectionView:UICollectionView!{ return collectionView } private var contentWidth:CGFloat{ let insets = _collectionView.contentInset return _collectionView.bounds.size.width - (insets.left + insets.right) } private var _contentSize:CGSize{ return CGSize(width: contentWidth, height: contentHeight) } }
// // ViewController.swift // Olga's ChatApp // // Created by Ivo Patty on 07/06/16. // Copyright © 2016 Vrijhaven. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var webby: UIWebView! var theURL = "http://olgaschatapp.marksmediaontwerp.nl"; func loadWebPage() { let theRequestURL = NSURL (string: theURL) let theActualFuckingRequestYouDumbass = NSURLRequest(URL: theRequestURL!) webby.loadRequest(theActualFuckingRequestYouDumbass) } override func viewDidLoad() { super.viewDidLoad() loadWebPage() // 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. } }
// // LoginViewController.swift // SecLibraryManagement // // Created by MOSHIOUR on 5/22/17. // Copyright © 2017 Jonny B. All rights reserved. // import UIKit class LoginViewController: UIViewController { @IBOutlet weak var messageLabel: UILabel! @IBOutlet weak var userNameTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var menuButton: UIBarButtonItem! override func viewDidLoad() { super.viewDidLoad() menuButton.target = revealViewController() menuButton.action = #selector(SWRevealViewController.revealToggle(_:)) view.addGestureRecognizer(self.revealViewController().panGestureRecognizer()) // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func loginButton(_ sender: Any) { let userName = "sec" let password = "123" if(userNameTextField.text == userName && passwordTextField.text == password) { performSegue(withIdentifier: "login", sender: LoginViewController()) } else{ userNameTextField.text = "" passwordTextField.text = "" messageLabel.text = "Incorrect username or password" } } }
// // Comment.swift // InstagramFirebase // // Created by Jairo Eli de Leon on 5/4/17. // Copyright © 2017 DevMountain. All rights reserved. // import Foundation struct Comment { var user: User let text: String let uid: String init(user: User, dictionary: [String: Any]) { self.user = user self.text = dictionary["text"] as? String ?? "" self.uid = dictionary["uid"] as? String ?? "" } }
// // ViewController.swift // DogAge // // Created by Brandon Holland on 1/26/15. // Copyright (c) 2015 Brandon Holland. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var dogYearsLabel: UILabel! @IBOutlet weak var enterYearsField: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func convertButton(sender: UIButton) { if (enterYearsField.text == ""){ dogYearsLabel.text = "Dog Years: " } else{ dogYearsLabel.text = "Dog Years: \(enterYearsField.text.toInt()!*7)" } enterYearsField.resignFirstResponder() } @IBAction func realConvertButton(sender: UIButton) { if (enterYearsField.text == ""){ dogYearsLabel.text = "Dog Years: " } else{ var age:Double var y = Double(enterYearsField.text.toInt()!) if (y <= 2){ age = y*10.5; }else{ age = 21 + (y-2)*4 } dogYearsLabel.text = "Dog Years: \(age)" } enterYearsField.resignFirstResponder() } }
// // ExtensionLessonVCSubViews.swift // Meet Swift // // Created by Filip on 26/01/2019. // Copyright © 2019 Filip. All rights reserved. // import UIKit extension LessonViewController { func showCorrectSubView() { correctSubView.alpha = 0 UIView.animate(withDuration: 0.6, animations: { self.correctSubView.isHidden = false self.correctSubViewLabel.text = "Correct Answer Go To Next Lesson" self.hintSubView.isHidden = true self.incorrectSubView.isHidden = true self.correctSubView.alpha = 1 }) stuckTimer.invalidate() incorrectTimer.invalidate() hintTimer.invalidate() view.endEditing(true) } func showIncorectSubView() { incorrectSubView.alpha = 0 UIView.animate(withDuration: 0.6, animations: { self.hintSubView.isHidden = true self.correctSubView.isHidden = true self.incorrectSubViewLabel.text = "Wrong Answer maybe you need a hint?" self.incorrectSubView.isHidden = false self.incorrectSubView.alpha = 1 }) incorrectTimer = Timer.scheduledTimer(timeInterval: 3.0, target: self, selector: #selector(backToOryginalStage) , userInfo: nil, repeats: false) seconds = 65 hintTimer.invalidate() } func showHintSubView() { hintSubView.alpha = 0 UIView.animate(withDuration: 0.6, animations: { self.hintSubView.isHidden = false self.hintSubView.alpha = 1 self.hintSubViewLabel.text = self.resultsLesson[self.indexesLesson[1]].subLessons[self.indexesLesson[2]].lessonHint self.incorrectSubView.isHidden = true self.correctSubView.isHidden = true self.descriptionLabel.isHidden = true }) hintTimer = Timer.scheduledTimer(timeInterval: 15.0, target: self, selector: #selector(backToOryginalStage) , userInfo: nil, repeats: false) seconds = 75 incorrectTimer.invalidate() } @objc func stuckTimerStage() { if seconds == 30 && seconds == 1 { incorrectSubView.alpha = 0 UIView.animate(withDuration: 0.6, animations: { self.incorrectSubViewLabel.text = "Stuck? Maybe Need Help" self.incorrectSubView.isHidden = false self.incorrectSubView.alpha = 1 }) Timer.scheduledTimer(timeInterval: 3.0, target: self, selector: #selector(backToOryginalStage) , userInfo: nil, repeats: false) } else if seconds == 0 { seconds = 60 } } @objc func backToOryginalStage() { hintSubView.isHidden = true incorrectSubView.isHidden = true descriptionLabel.isHidden = false } }
// // RefreshConst.swift // RefreshExample // // Created by zhangyr on 15/5/7. // Copyright (c) 2015年 cjxnfs. All rights reserved. // import Foundation let RefreshViewHeight = 40 let RefreshSlowAnimationDuration:NSTimeInterval = 0.3 let RefreshFooterPullToRefresh:NSString = "上拉加载更多" let RefreshFooterReleaseToRefresh:NSString = "松开加载更多" let RefreshFooterRefreshing:String = "正在加载数据..." let RefreshHeaderPullToRefresh:String = "下拉刷新" let RefreshHeaderReleaseToRefresh:String = "松开刷新" let RefreshHeaderRefreshing:String = "正在刷新中..." let RefreshHeaderTimeKey:String = "RefreshHeaderView" let RefreshContentOffset:NSString = "contentOffset" let RefreshContentSize:String = "contentSize"
// // ProductViewController.swift // SwiftDemo // // Created by Harlan on 2020/4/1. // Copyright © 2020 Harlan. All rights reserved. // import UIKit class ProductViewController: UIViewController { @IBOutlet weak var productImageView: UIImageView! @IBOutlet weak var productNameLabel: UILabel! var product: Product? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. productNameLabel.text = product?.name if let imageName = product?.fullscreenImageName { productImageView.image = UIImage(named: imageName) } } }
// // BookTableViewCell.swift // ScripturesMapped // // Created by Victor Lazaro on 10/30/17. // Copyright © 2017 Victor Lazaro. All rights reserved. // import UIKit class BookTableViewCell: UITableViewCell { @IBOutlet weak var bookLabel: UILabel! }
// // ViewController.swift // NativeDemo // // Created by hello on 2021/10/13. // // MARK: 三种Channel // FlutterMethodChannel:调用方法,一次通讯 // FlutterBasicMessageChannel:传递字符串&半结构化的信息。持续通讯 // FlutterEventChannel:用于传输数据流(dart中的stream)。持续通讯 import UIKit import Flutter class ViewController: UIViewController { var clickCount: Int = 0 /// 初始化Flutter引擎,需要提前创建、run lazy var engine: FlutterEngine = { let e = FlutterEngine.init(name: "tank") e.run() // 此处可以添加一个逻辑:判断 run是否成功 return e }() /// 声明flutter控制器 var flutterVc: FlutterViewController? /// FlutterBasicMessageChannel 案例 var messageChannel: FlutterBasicMessageChannel? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. title = "原生项目,嵌套Flutter页面" let testBtn = UIButton.init(frame: CGRect.init(x: 20, y: 100, width: 300, height: 44)) testBtn.setTitle("页面 one", for: .normal) testBtn.setTitleColor(UIColor.white, for: .normal) testBtn.backgroundColor = .black testBtn.addTarget(self, action: #selector(test1BtnAction(sender:)), for: .touchUpInside) view.addSubview(testBtn) let testBtn2 = UIButton.init(frame: CGRect.init(x: 20, y: 160, width: 300, height: 44)) testBtn2.setTitle("页面 two", for: .normal) testBtn2.setTitleColor(UIColor.white, for: .normal) testBtn2.backgroundColor = .black testBtn2.addTarget(self, action: #selector(test2BtnAction(sender:)), for: .touchUpInside) view.addSubview(testBtn2) let testBtn3 = UIButton.init(frame: CGRect.init(x: 20, y: 220, width: 300, height: 44)) testBtn3.setTitle("FlutterBasicMessageChannel", for: .normal) testBtn3.setTitleColor(UIColor.white, for: .normal) testBtn3.backgroundColor = .black testBtn3.addTarget(self, action: #selector(messageChannelBtn(sender:)), for: .touchUpInside) view.addSubview(testBtn3) // 创建flutter控制器,提前保证引擎 run起来。 flutterVc = FlutterViewController.init(engine: engine, nibName: nil, bundle: nil) flutterVc?.modalPresentationStyle = .fullScreen // 接收Flutter的数据 -- FlutterBasicMessageChannel messageChannel = FlutterBasicMessageChannel.init(name: "message_channel", binaryMessenger: self.flutterVc as! FlutterBinaryMessenger) messageChannel!.setMessageHandler { (receiver, replay) in print("收到Flutter中的消息:\(String(describing: receiver))") } } @objc func test1BtnAction(sender: UIButton){ // 每次都创建 FlutterViewController,会非常占用内存,不建议这么做。 // initialRoute 对应 Flutter中的 window.defaultRouteName let temp = FlutterViewController.init(project: nil, initialRoute: "one", nibName: nil, bundle: nil) present(temp, animated: true, completion: nil) } @objc func test2BtnAction(sender: UIButton){ if flutterVc != nil { present(flutterVc!, animated: true, completion: nil) } let name = "two_page" let channel = FlutterMethodChannel.init(name: name, binaryMessenger: flutterVc as! FlutterBinaryMessenger) channel.setMethodCallHandler { [weak self] (call, result) in print(call.method) if call.method == "exit" { self?.flutterVc?.dismiss(animated: true, completion: nil) } } channel.invokeMethod(name, arguments: nil) } // MARK: FlutterBasicMessageChannel 案例 @objc func messageChannelBtn(sender: UIButton) { if flutterVc != nil { present(flutterVc!, animated: true, completion: nil) } // 监听 let name = "message_channel" let channel = FlutterMethodChannel.init(name: name, binaryMessenger: flutterVc as! FlutterBinaryMessenger) channel.setMethodCallHandler { [weak self] (call, result) in print(call.method) if call.method == "exit" { self?.flutterVc?.dismiss(animated: true, completion: nil) } } channel.invokeMethod(name, arguments: nil) } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { clickCount += 1 // 发送消息 messageChannel?.sendMessage(clickCount) } }
// // challengeRequestsVC.swift // ETBAROON // // Created by imac on 9/24/17. // Copyright © 2017 IAS. All rights reserved. // import UIKit class challengeRequestsVC: UIViewController,UITableViewDataSource ,UITableViewDelegate { @IBOutlet weak var tableview: UITableView! var tChallenges = [GetChallenge]() lazy var refresher: UIRefreshControl = { let refresher = UIRefreshControl() refresher.addTarget(self, action: #selector(handleRefersh), for: .valueChanged) return refresher }() override func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = " طلبات التحدي" tableview.addSubview(refresher) tableview.tableFooterView = UIView() tableview.separatorInset = .zero tableview.contentInset = .zero handleRefersh() SetBackBarButtonCustom() CustimizeNavigationBar () // Do any additional setup after loading the view. } public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tChallenges.count } func CustimizeNavigationBar (){ self.navigationController?.navigationBar.barTintColor = UIColor(red:0.93, green:0.79, blue:0.25, alpha:1.0) self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.white] } func SetBackBarButtonCustom() { //Back buttion let btnLeftMenu: UIButton = UIButton() btnLeftMenu.setImage(UIImage(named: "menubutton"), for: UIControlState()) btnLeftMenu.addTarget(revealViewController(), action: #selector(SWRevealViewController.revealToggle(_:)) , for: UIControlEvents.touchUpInside) btnLeftMenu.frame = CGRect(x: 0, y: 0, width: 33/2, height: 27/2) let barButton = UIBarButtonItem(customView: btnLeftMenu) self.navigationItem.leftBarButtonItem = barButton //self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer()) } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "tvChallengeRequests", for: indexPath) as! tvChallengeRequests // cell.btnSetLike.tintColor = red cell.lblFirstTeam?.text = tChallenges[indexPath.row].fldAppTeamName1 cell.lblSeconondTeam?.text = tChallenges[indexPath.row].fldAppTeamName2 cell.lblGameTime?.text = tChallenges[indexPath.row].fldAppGameDateTime cell.lblPlayGroundName?.text = tChallenges[indexPath.row].fldAppPlaygroundName cell.tapped = { [unowned self] (selectedCell) -> Void in // let path = tableView.indexPathForRow(at: selectedCell.center)! let fldAppGameID = self.tChallenges[indexPath.row].fldAppGameID print("the selected item is \(fldAppGameID)") API_AllCallenges.acceptChallenge(fldAppGameID: fldAppGameID) { (error: Error?, success: Bool) in if success { // print("Reigster succeed !! welcome to our small app :)") self.handleRefersh() self.setAlert(message: "تمت الموافقه") } else { self.setAlert(message: "لقد وافقت عليها بالفعل ") } } } cell.rejectTapped = { [unowned self] (selectedCell) -> Void in // let path = tableView.indexPathForRow(at: selectedCell.center)! let fldAppGameID = self.tChallenges[indexPath.row].fldAppGameID print("the selected item is \(fldAppGameID)") API_AllCallenges.rejectChallenge(fldAppGameID: fldAppGameID) { (error: Error?, success: Bool) in if success { // print("Reigster succeed !! welcome to our small app :)") self.handleRefersh() self.setAlert(message: "تم الرفض") } else { self.setAlert(message: "لقد رفضت بالفعل ") } } } return (cell) } var isLoading: Bool = false @objc private func handleRefersh() { self.refresher.endRefreshing() guard !isLoading else { return } isLoading = true API_AllCallenges.getAllChallenges{ (error: Error?,Challenge:[GetChallenge]?)in self.isLoading = false; if let Challenge = Challenge { self.tChallenges = Challenge self.tableview.reloadData() //self.hideActivityIndicator(uiView: self.CollectionView) //self.activityIndicator.stopAnimating() //self.activityIndicator.hidesWhenStopped = true // self.activityIndicator.isHidden=true // self.activityIndicator.removeFromSuperview() } } } func setAlert(message : String) { let attributedString = NSAttributedString(string: " ", attributes: [ NSFontAttributeName : UIFont.systemFont(ofSize: 15), //your font here NSForegroundColorAttributeName : UIColor.green ]) let alert = UIAlertController(title: "", message: "\(message)", preferredStyle: UIAlertControllerStyle.alert) alert.setValue(attributedString, forKey: "attributedTitle") alert.addAction(UIAlertAction(title: "موافق", style: UIAlertActionStyle.default, handler: nil)) present(alert, animated: true, completion: nil) } }
// // CallEditor.swift // TelerikUIExamplesInSwift // // Copyright (c) 2015 Telerik. All rights reserved. // class CallEditor: TKDataFormPhoneEditor { let actionButton = UIButton() override init(property: TKEntityProperty, owner: TKDataForm) { super.init(property: property, owner: owner) } override init(frame: CGRect) { super.init(frame: frame) actionButton.setTitle("Call", forState: UIControlState.Normal) actionButton.setTitleColor(UIColor(red: 0.780, green: 0.2, blue: 0.233, alpha: 1.0), forState: UIControlState.Normal) self.addSubview(actionButton) self.gridLayout.addArrangedView(actionButton) let btnDef = self.gridLayout.definitionForView(actionButton) btnDef.row = 0 btnDef.column = 3 self.gridLayout.setWidth(actionButton.sizeThatFits(CGSizeZero).width, forColumn: 3) } override init(property: TKEntityProperty) { super.init(property: property) } required convenience init(coder aDecoder: NSCoder) { self.init(frame: CGRectZero) } }
// // PokedexCollectionViewCell.swift // Pokedex // // Created by Luiz Vasconcellos on 24/04/21. // import UIKit import Kingfisher class PokedexCollectionViewCell: UICollectionViewCell { @IBOutlet weak var pokemonImage: UIImageView! @IBOutlet weak var idLbl: UILabel! @IBOutlet weak var namelbl: UILabel! func setup(with pokemon: Pokemon) { configureLayout() if let imageURL = pokemon.sprites.other?.officialArtwork.frontDefault { KF.url(URL(string: imageURL)).cacheMemoryOnly(true).onSuccess({ (result) in }).set(to: pokemonImage) self.idLbl.text = "№ \(String(pokemon.id))" self.namelbl.text = pokemon.name } } private func configureLayout() { pokemonImage.backgroundColor = UIColor.systemGray5 pokemonImage.layer.cornerRadius = 5 self.layer.borderWidth = 1 self.layer.cornerRadius = 5 self.layer.borderColor = UIColor.systemGray5.cgColor } }
// // NewProject // Copyright (c) Yuichi Nakayasu. All rights reserved. // import UIKit class TodoDetailViewController: UIViewController { var presenter: TodoDetailPresenterProtocol! var todo: TodoModel? private var adapter: TodoDetailAdapter! private var editTodo: TodoModel! @IBOutlet private weak var tableView: UITableView! @IBOutlet private weak var saveButton: UIButton! override func viewDidLoad() { super.viewDidLoad() title = "タスク詳細" presenter.fetchEditableTodo(from: todo) } @IBAction private func didTapSaveButton() { } } extension TodoDetailViewController: TodoDetailViewProtocol { func fetchedEditable(todo: TodoModel) { editTodo = todo adapter = TodoDetailAdapter(tableView, todo: editTodo, delegate: self) } func registered() { } func removed() { } } extension TodoDetailViewController: TodoDetailAdapterDelegate { func todoDetailAdapter(_ adapter: TodoDetailAdapter, didTapComplete todo: TodoModel?) { editTodo.completed = !editTodo.completed } func todoDetailAdapter(_ adapter: TodoDetailAdapter, didTapEditTitle todo: TodoModel?) { let options = TextViewControllerOptions( title: "タスクのタイトル", placeholder: "タスクのタイトルを入力してください", text: editTodo.title, multiLine: false ) Wireframe.showText(from: self, options: options) { [unowned self] text in self.editTodo.title = text self.tableView.reloadData() } } func todoDetailAdapter(_ adapter: TodoDetailAdapter, didTapEditSummery todo: TodoModel?) { let options = TextViewControllerOptions( title: "タスクの概要", placeholder: "タスクの概要を入力してください", text: editTodo.summery, multiLine: true ) Wireframe.showText(from: self, options: options) { [unowned self] text in self.editTodo.summery = text self.tableView.reloadData() } } func todoDetailAdapter(_ adapter: TodoDetailAdapter, didChangePriority priority: TodoPriority, todo: TodoModel?) { print("didChangePriority") } func todoDetailAdapter(_ adapter: TodoDetailAdapter, didSelectLimit todo: TodoModel?) { print("didSelectLimit") } func todoDetailAdapter(_ adapter: TodoDetailAdapter, didSelectNotify todo: TodoModel?) { print("didSelectNotify") } func todoDetailAdapter(_ adapter: TodoDetailAdapter, didTapAsset asset: AssetModel?, todo: TodoModel?) { print("didTapAsset") } func todoDetailAdapter(_ adapter: TodoDetailAdapter, didTapAddAsset todo: TodoModel?) { print("didTapAddAsset") } func todoDetailAdapter(_ adapter: TodoDetailAdapter, didTapDelete todo: TodoModel?) { Wireframe.showConfirmDeleteTodo(from: self) { Wireframe.pop(from: self) } } }
// // ViewController.swift // Lab3 // // Created by Local Account 436-01 on 9/27/17. // Copyright © 2017 Local Account 436-01. All rights reserved. // import UIKit class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate { @IBOutlet weak var ClassSelectedDisplay: UILabel! @IBOutlet weak var pickerView: UIPickerView! let courseNumbers = ["400", "402", "430", "436", "445", "466", "477", "480", "484", "491"]; let classNames = ["Special Problems", "Software Requirements Engineering", "Programming Languages I", "Mobile Application Development", "Theory of Computation I", "Knowledge Discovery from Data", "Scientific and Information Visualization", "Artificial Intelligence", "User-Centered Interface Design and Development", "Senior Project I"] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func selectClassOption(_ sender: UIButton) { let index = pickerView.selectedRow(inComponent: 0) ClassSelectedDisplay.text = courseNumbers[index] + " " + classNames[index]; } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return courseNumbers.count } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return courseNumbers[row] } func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } }
/* Copyright Airship and Contributors */ /** * Default predicate for the prompt permission action. */ @objc(UAPromptPermissionActionPredicate) public class PromptPermissionActionPredicate : NSObject, ActionPredicateProtocol { public func apply(_ args: ActionArguments) -> Bool { return args.metadata?[UAActionMetadataForegroundPresentationKey] == nil } }
// // RegExp.swift // LeetCode // // Created by 360JR on 2021/1/29. // Copyright © 2021 liangqili.com. All rights reserved. // import Foundation class RegExp { func test() { let invitation = "Fancy a game of Cluedo™?" let result = invitation[invitation.range(of: #"\bClue(do)?™?\b"#, options: .regularExpression)!] print(result) } }
// // ViewController.swift // Bouncer // // Created by Екатерина Колесникова on 30.03.15. // Copyright (c) 2015 kkate. All rights reserved. // import UIKit class ViewController: UIViewController { var bounser = BouncerBehavior() lazy var animator: UIDynamicAnimator = { UIDynamicAnimator(referenceView: self.view) }() override func viewDidLoad() { super.viewDidLoad() animator.addBehavior(bounser) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if (redBlock == nil) { redBlock = addBlock() redBlock?.backgroundColor = UIColor.redColor() bounser.addBlock(redBlock!) } let manager = AppDelegate.Motion.Manager if manager.deviceMotionAvailable { manager.startAccelerometerUpdatesToQueue(NSOperationQueue.mainQueue()) { (data, error) -> Void in self.bounser.gravity.gravityDirection = CGVector(dx: data.acceleration.x, dy: -data.acceleration.y) } } } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) AppDelegate.Motion.Manager.stopAccelerometerUpdates() } var redBlock: UIView? struct Constants { static let BlockSize = CGSize(width: 40, height: 40) } func addBlock() -> UIView { let block = UIView(frame: CGRect(origin: CGPoint.zeroPoint, size: Constants.BlockSize)) block.center = CGPoint(x: view.bounds.midX, y: view.bounds.midY) view.addSubview(block) return block } }
// // LoginViewModel.swift // TinderLikeSwipeAnimation // // Created by Khaled Rahman Ayon on 27.11.18. // Copyright © 2018 DocDevs. All rights reserved. // import Foundation import Firebase class LoginViewModel { var isLoggedIn = Bindable<Bool>() var isFormValid = Bindable<Bool>() var email: String? { didSet { checkFormValidity() } } var password: String? { didSet { checkFormValidity() } } fileprivate func checkFormValidity() { let isvalid = email?.isEmpty == false && password?.isEmpty == false isFormValid.value = isvalid } func performLogin(completion: @escaping (Error?) -> ()) { guard let email = email, let password = password else { return } isLoggedIn.value = true Auth.auth().signIn(withEmail: email, password: password) { (res, error) in completion(error) } } }
// // ChatRoom.swift // DogeChat // // Created by Dmitriy Roytman on 21.07.17. // Copyright © 2017 Luke Parham. All rights reserved. // import UIKit protocol ChatRoomDelegate: class { func receivedMessage(message: Message) } final class ChatRoom: NSObject { var inputStream: InputStream! var outputStream: OutputStream! var username = "" let maxReadLength = 4096 weak var delegate: ChatRoomDelegate? func setupNetworkCommunication() { var readStream: Unmanaged<CFReadStream>? var writeStream: Unmanaged<CFWriteStream>? CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, "127.0.0.1" as CFString, 80, &readStream, &writeStream) inputStream = readStream!.takeRetainedValue() as! InputStream outputStream = writeStream!.takeRetainedValue() as! OutputStream inputStream.delegate = self inputStream.schedule(in: .current, forMode: .commonModes) outputStream.schedule(in: .current, forMode: .commonModes) inputStream.open() outputStream.open() } func joinChat(username: String) { let data = user(username) self.username = username send(data) } } extension ChatRoom: StreamDelegate { enum Key: String { case iam = "iam", msg = "msg" } func convert(text: String) -> (_ key: Key ) -> Data { return { (key: Key)-> Data in return "\(key.rawValue):\(text)".data(using: .ascii)! } } func message(_ text: String) -> Data { return convert(text: text)(.msg) } func user(_ username: String) -> Data { return convert(text: username)(.iam) } func send(_ data: Data) { _ = data.withUnsafeBytes { [unowned self] in self.outputStream.write($0, maxLength: data.count) } } func stream(_ aStream: Stream, handle eventCode: Stream.Event) { switch eventCode { case .hasBytesAvailable: readAvailableBytes(stream: aStream as! InputStream) case .endEncountered: stopChatSession() case .hasSpaceAvailable: print("has space available") case .errorOccurred: print("error occurred") default: print("some other event") } } private func readAvailableBytes(stream: InputStream) { let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: maxReadLength) while stream.hasBytesAvailable { let numberOfBytesRead = inputStream.read(buffer, maxLength: maxReadLength) guard numberOfBytesRead > 0, stream.streamError == nil else { break } if let message = processedMessageString(buffer: buffer, length: numberOfBytesRead) { delegate?.receivedMessage(message: message) } } } private func processedMessageString(buffer: UnsafeMutablePointer<UInt8>, length: Int) -> Message? { let rawString = String(bytesNoCopy: buffer, length: length, encoding: .ascii, freeWhenDone: true) guard let stringArray = rawString?.components(separatedBy: ":"), let name = stringArray.first, let message = stringArray.last else { return nil } let messageSender: MessageSender = name == username ? .ourself : .someoneElse return Message(message: message, messageSender: messageSender, username: name) } func sendMessage(message: String) { let data = self.message(message) send(data) } func stopChatSession() { inputStream.close() outputStream.close() } }
// // MoveWithKeyboardViewController.swift // Carousel // // Created by Mel Ludowise on 10/15/14. // Copyright (c) 2014 Mel Ludowise. All rights reserved. // import UIKit class MoveWithKeyboardViewController: UIViewController { private var inputsViewOrigin : CGPoint? private var buttonsViewOrigin : CGPoint? private var screenSize : CGRect? private var inputsView : UIView! private var buttonsView : UIView! private var helpText : UIView! private var navigationBar : UINavigationBar? func setupKeyboardMovement(inputsView: UIView, buttonsView: UIView, helpText: UIView, navigationBar: UINavigationBar?) { self.inputsView = inputsView self.buttonsView = buttonsView self.helpText = helpText self.navigationBar = navigationBar // Get the original positions of the button and input views buttonsViewOrigin = buttonsView.frame.origin inputsViewOrigin = inputsView.frame.origin // Cache screen size screenSize = UIScreen.mainScreen().bounds // Setup listeners for keyboard NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil) } func keyboardWillShow(notification: NSNotification!) { var userInfo = notification.userInfo! // Get the keyboard height and width from the notification // Size varies depending on OS, language, orientation var kbSize = (userInfo[UIKeyboardFrameEndUserInfoKey] as NSValue).CGRectValue().size var durationValue = userInfo[UIKeyboardAnimationDurationUserInfoKey] as NSNumber var animationDuration = durationValue.doubleValue var curveValue = userInfo[UIKeyboardAnimationCurveUserInfoKey] as NSNumber var animationCurve = curveValue.integerValue UIView.animateWithDuration(animationDuration, delay: 0.0, options: UIViewAnimationOptions.fromRaw(UInt(animationCurve << 16))!, animations: { // We want the bottom of the buttons to align with the top of the keyboard var buttonsViewHeight = self.buttonsView.frame.height self.buttonsView.frame.origin.y = self.screenSize!.height - kbSize.height - buttonsViewHeight // We also want the inputs to move up such that the help text is hidden behind the nav (the bottom of the sign in message should be the same as the bottom of the nav) var helpTextY = self.helpText.frame.origin.y var helpTextHeight = self.helpText.frame.height var navBarHeight = self.navigationBar == nil ? 0 : self.navigationBar!.frame.height self.inputsView.frame.origin.y = navBarHeight - helpTextY - helpTextHeight }, completion: nil) } func keyboardWillHide(notification: NSNotification!) { var userInfo = notification.userInfo! // Get the keyboard height and width from the notification // Size varies depending on OS, language, orientation var kbSize = (userInfo[UIKeyboardFrameEndUserInfoKey] as NSValue).CGRectValue().size var durationValue = userInfo[UIKeyboardAnimationDurationUserInfoKey] as NSNumber var animationDuration = durationValue.doubleValue var curveValue = userInfo[UIKeyboardAnimationCurveUserInfoKey] as NSNumber var animationCurve = curveValue.integerValue UIView.animateWithDuration(animationDuration, delay: 0.0, options: UIViewAnimationOptions.fromRaw(UInt(animationCurve << 16))!, animations: { // Reset the y positions back to where they were before self.buttonsView.frame.origin = self.buttonsViewOrigin! self.inputsView.frame.origin = self.inputsViewOrigin! }, completion: nil) } func dismissKeyboard() { view.endEditing(true) } }
// // UIImageView.swift // SweetHealth // // Created by Miguel Jaimes on 11/02/2020. // Copyright © 2020 Miguel Jaimes. All rights reserved. // import UIKit extension UIImageView { func roundImage(){ self.layer.cornerRadius = self.frame.size.width / 2 self.clipsToBounds = true self.layer.borderColor = MyColors.pinkApp.cgColor self.layer.borderWidth = 4 } }
// // ViewController.swift // YTZTagView // // Created by Sodapig on 29/05/2017. // Copyright © 2017 Taozhu Ye. All rights reserved. // import UIKit class ViewController: UIViewController, YTZTagViewDelegate { @IBOutlet weak var textField: UITextField! var alertController: UIAlertController? = nil var touchedTagView: YTZTagView? = nil override func viewDidLoad() { super.viewDidLoad() alertController = UIAlertController(title: nil, message: "要删除标签吗?", preferredStyle: .alert) let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil) let confirmAction = UIAlertAction(title: "确定", style: .default, handler: { [weak self] action in self?.touchedTagView?.removeFromSuperview() self?.touchedTagView = nil }) alertController?.addAction(cancelAction) alertController?.addAction(confirmAction) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { if textField.isFirstResponder { textField.resignFirstResponder() } } @IBAction func tap(_ sender: UITapGestureRecognizer) { var text = textField.text if text?.characters.count == 0 { text = "This is a tag" } addTag(at: sender.location(in: sender.view), text: text!) } func addTag(at point: CGPoint, text: String) { let tagModel = YTZTagModel() tagModel.name = text let tagView = YTZTagView.instanceFromNib() tagView.tagModel = tagModel view.addSubview(tagView) tagView.delegate = self tagView.show(in: point) } // MARK: - YTZTagViewDelegate func didTap(tagView: YTZTagView, tapGestureRecognizer: UITapGestureRecognizer) { touchedTagView = tagView present(alertController!, animated: true, completion: nil) } }
// // BookCell.swift // // // Created by Presto on 19/11/2018. // import UIKit import FSPagerView class BookCell: FSPagerViewCell { @IBOutlet var coverImageView: UIImageView! @IBOutlet var stampImageView: UIImageView! override func awakeFromNib() { clipsToBounds = true layer.cornerRadius = 10 } override func prepareForReuse() { coverImageView.image = nil stampImageView.image = nil } func setProperties(at index: Int, isPassed: Bool, isPassedCompletely: Bool) { let allImageNames = BookCoverImage.all if isPassedCompletely { coverImageView.image = UIImage(named: allImageNames[index][1]) stampImageView.image = UIImage(named: "stamp_clear") } else { coverImageView.image = isPassed ? UIImage(named: allImageNames[index][1]) : UIImage(named: allImageNames[index][0]) stampImageView.image = nil } } }
// // Messenger.swift // SailingThroughHistory // // Created by Herald on 19/4/19. // Copyright © 2019 Sailing Through History Team. All rights reserved. // /** * Default implementation of GameMessenger */ class Messenger: GameMessenger { var messages: [GameMessage] = [] }
// // AppDelegate.swift // carWash // // Created by Juliett Kuroyan on 15.11.2019. // Copyright © 2019 VooDooLab. All rights reserved. // import UIKit import SwiftKeychainWrapper import Firebase @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? let gcmMessageIDKey = "gcm.message_id" let typeKey = "type" let washKey = "wash" let priceKey = "value" let operationIDKey = "operation_id" let stockIDKey = "stock_id" var reviewNotificationResponse: ReviewNotificationResponse? var stockNotificationResponse: SaleNotificationResponse? var didRecieveReviewNotificationResponse: (()->())? var didRecieveSaleNotificationResponse: ((SaleNotificationResponse)->())? private var application: UIApplication? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { self.application = application // UILabel.appearance().font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle(rawValue: "SanFrancisco")) if (launchOptions?[UIApplication.LaunchOptionsKey.remoteNotification] != nil) { // ! KeychainWrapper.standard.set("", forKey: "notification") } if #available(iOS 13.0, *) { // In iOS 13 setup is done in SceneDelegate } else { window = UIWindow(frame: UIScreen.main.bounds) try? window?.addReachabilityObserver() let configurator = LoginConfigurator() let vc = configurator.viewController let navigationController = UINavigationController(rootViewController: vc) navigationController.navigationBar.tintColor = .clear navigationController.interactivePopGestureRecognizer?.isEnabled = false navigationController.modalPresentationStyle = .fullScreen window?.rootViewController = navigationController window?.makeKeyAndVisible() let userDefaults = UserDefaults.standard if !userDefaults.bool(forKey: "hasRunBefore") { KeychainWrapper.standard.removeAllKeys() userDefaults.set(true, forKey: "hasRunBefore") } if let _ = KeychainWrapper.standard.data(forKey: "userToken") { navigationController.pushViewController(MainTabBarController(), animated: false) navigationController.navigationBar.isHidden = true } } if let _ = KeychainWrapper.standard.data(forKey: "userToken") { configureFirebase() } return true } func configureFirebase() { guard let application = self.application, FirebaseApp.app() == nil else { if let token = Messaging.messaging().fcmToken { sendToken(token: token) } return } FirebaseApp.configure() UNUserNotificationCenter.current().delegate = self Messaging.messaging().delegate = self let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound] UNUserNotificationCenter.current().requestAuthorization( options: authOptions, completionHandler: {_, _ in }) application.registerForRemoteNotifications() } // MARK: UISceneSession Lifecycle @available(iOS 13.0, *) func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } @available(iOS 13.0, *) func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { // Called when the user discards a scene session. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. // Use this method to release any resources that were specific to the discarded scenes, as they will not return. self.window?.removeReachabilityObserver() } func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) { // If you are receiving a notification message while your app is in the background, // this callback will not be fired till the user taps on the notification launching the application. // TODO: Handle data of notification // With swizzling disabled you must let Messaging know about the message, for Analytics Messaging.messaging().appDidReceiveMessage(userInfo) // Print message ID. if let messageID = userInfo[gcmMessageIDKey] { print("Message ID: \(messageID)") } // Print full message. print(userInfo) } func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { // If you are receiving a notification message while your app is in the background, // this callback will not be fired till the user taps on the notification launching the application. // TODO: Handle data of notification // With swizzling disabled you must let Messaging know about the message, for Analytics Messaging.messaging().appDidReceiveMessage(userInfo) // Print message ID. if let messageID = userInfo[gcmMessageIDKey] { print("Message ID: \(messageID)") } // Print full message. print(userInfo) completionHandler(UIBackgroundFetchResult.newData) } func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { Messaging.messaging().apnsToken = deviceToken } } extension AppDelegate: MessagingDelegate { func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) { print("Firebase registration token: \(fcmToken)") let dataDict:[String: String] = ["token": fcmToken] NotificationCenter.default.post(name: NSNotification.Name("FCMToken"), object: nil, userInfo: dataDict) UserDefaults.standard.set(fcmToken, forKey: "fcmToken") sendToken(token: fcmToken) } func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) { print("Messsage Data ", remoteMessage.appData) } private func sendToken(token: String) { let request = Request.User.SetFirebaseToken.Post(token: token) request.send().done { _ in () // ! }.catch { error in print(error) // ! } } } extension AppDelegate : UNUserNotificationCenterDelegate { func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { let content = notification.request.content let userInfo = content.userInfo Messaging.messaging().appDidReceiveMessage(userInfo) // if let badge = content.badge { // UIApplication.shared.applicationIconBadgeNumber = badge.intValue // self.badgeValue.value = badge.intValue // setBadges?(badge.intValue) // } // completionHandler([.alert, .badge]) completionHandler([.alert]) } func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { let userInfo = response.notification.request.content.userInfo if let type = userInfo[typeKey] as? String { switch type { case "review": if let price = userInfo[priceKey] as? String, let washJson = userInfo[washKey] as? String, let operationIdStr = userInfo[operationIDKey] as? String, let operationId = Int(operationIdStr), let jsonData = washJson.data(using: .utf8), let wash = try? JSONDecoder().decode(WashResponse.self, from: jsonData) { var rub = price rub.removeLast(2) rub += " ₽" reviewNotificationResponse = ReviewNotificationResponse(price: rub, type: type, wash: wash, operationId: operationId) didRecieveReviewNotificationResponse?() } case "stock": if let saleIdStr = userInfo[stockIDKey] as? String, let saleId = Int(saleIdStr) { stockNotificationResponse = SaleNotificationResponse(id: saleId) didRecieveSaleNotificationResponse?(stockNotificationResponse!) notificationViewed(stockId: saleId) } default: () } // let application = UIApplication.shared // // if(application.applicationState == .active){ // print("user tapped the notification bar when the app is in foreground") // } // // if(application.applicationState == .inactive) { // print("user tapped the notification bar when the app is in background") // } } completionHandler() } private func notificationViewed(stockId: Int) { let request = Request.User.SetStockViewed.Post(stockId: stockId) request.send().done { _ in () }.catch { error in print(error) } } func userNotificationCenter(_ center: UNUserNotificationCenter, openSettingsFor notification: UNNotification?) { print("userNotificationCenter") } }
// // Created by Daniel Heredia on 2/27/18. // Copyright © 2018 Daniel Heredia. All rights reserved. // // Shortest Supersequence import Foundation // MARK: - Heap struct Heap<T: Comparable> { private var items: [T] init() { self.items = [T]() } mutating func insert(_ element: T) { items.append(element) let index = items.count - 1 self.bubbleUp(index: index) } func peekMinimum() -> T? { return self.items.first } mutating func removeMinimum() -> T? { guard let firstValue = self.items.first else { return nil } let lastValue = self.items.last! self.items[0] = lastValue self.items.removeLast() self.bubbleDown(index: 0) return firstValue } } private extension Heap { mutating func bubbleUp(index: Int) { if index <= 0 || index >= self.items.count { return } let parent = index / 2 if items[parent] > items[index] { self.swapElements(aIndex: parent, bIndex: index) self.bubbleUp(index: parent) } } mutating func bubbleDown(index: Int) { if index < 0 || index >= self.items.count { return } var minIndex = index for child in self.childrenIndexes(forIndex: index) { if self.items[child] < self.items[minIndex] { minIndex = child } } if minIndex != index { self.swapElements(aIndex: minIndex, bIndex: index) self.bubbleDown(index: minIndex) } } func childrenIndexes(forIndex index: Int) -> [Int] { let rightIndex = (index + 1) * 2 let leftIndex = rightIndex - 1 var indexes = [Int]() if rightIndex < self.items.count { indexes.append(leftIndex) indexes.append(rightIndex) } else if leftIndex < self.items.count { indexes.append(leftIndex) } return indexes } mutating func swapElements(aIndex a: Int, bIndex b: Int) { if a < 0 || b < 0 || a >= items.count || b >= items.count { return } let aux = self.items[a] self.items[a] = self.items[b] self.items[b] = aux } } // MARK: - Queue class QueueNode<T> { let value: T var next: QueueNode? init(value: T) { self.value = value } } struct Queue<T> { var head: QueueNode<T>? var tail: QueueNode<T>? init() { } mutating func enqueue(_ value: T) { let node = QueueNode(value: value) if self.head == nil { self.head = node } if let tail = self.tail { tail.next = node } self.tail = node } mutating func dequeue() -> T? { guard let first = self.head else { return nil } self.head = first.next if first === self.tail { self.tail = nil } return first.value } func peek() -> T? { return self.head?.value } var isEmpty: Bool { return self.head == nil } } // MARK: - Exercise logic typealias SequenceRange = (start: Int, end: Int) struct QueueInt: Comparable { let value: Int let queueIndex: Int init(value: Int, queueIndex: Int) { self.value = value self.queueIndex = queueIndex } static func ==(lhs: QueueInt, rhs: QueueInt) -> Bool { return lhs.value == rhs.value } static func <(lhs: QueueInt, rhs: QueueInt) -> Bool { return lhs.value < rhs.value } } func getLocations(for elements: [Int], in array: [Int]) -> [Queue<Int>] { var locations = [Int: Queue<Int>]() for element in elements { locations[element] = Queue<Int>() } for (i, value) in array.enumerated() { if locations[value] != nil { locations[value]!.enqueue(i) } } return [Queue<Int>](locations.values) } func findShortestClosure(lists: inout [Queue<Int>]) -> SequenceRange? { var minHeap = Heap<QueueInt>() var maxIndex = Int.min for i in 0..<lists.count { guard let value = lists[i].dequeue() else { return nil } let node = QueueInt(value: value, queueIndex: i) minHeap.insert(node) maxIndex = max(maxIndex, value) } var minIndex = minHeap.peekMinimum()!.value var bestMinIndex = minIndex var bestMaxIndex = maxIndex while true { let discardedNode = minHeap.removeMinimum()! minIndex = discardedNode.value if (maxIndex - minIndex) < (bestMaxIndex - bestMinIndex) { bestMaxIndex = maxIndex bestMinIndex = minIndex } guard let newIndex = lists[discardedNode.queueIndex].dequeue() else { break } let newNode = QueueInt(value: newIndex, queueIndex: discardedNode.queueIndex) minHeap.insert(newNode) maxIndex = max(maxIndex, newIndex) } return (bestMinIndex, bestMaxIndex) } func findShortesSuperSequence(array: [Int], elements: [Int]) -> SequenceRange? { var locations = getLocations(for: elements, in: array) return findShortestClosure(lists: &locations) } // MARK: - Test let elements = [1, 5, 9] let array = [7, 5, 9, 0, 2, 1, 3, 5, 7, 9, 1, 1, 5, 8, 8, 9, 7] print("Elements: \(elements)") print("Array: \(array)") if let range = findShortesSuperSequence(array: array, elements: elements) { print("Super sequence: (start: \(range.start), end: \(range.end))") } else { print("Error: No super sequence found") }
import Bow import Foundation /// UsafeRun provides capabilities to run a computation unsafely, synchronous or asynchronously. public protocol UnsafeRun: MonadError { /// Unsafely runs a computation in a synchronous manner. /// /// - Parameters: /// - queue: Dispatch queue used to run the computation. /// - fa: Computation to be run. /// - Returns: Result of running the computation. /// - Throws: Error happened during the execution of the computation, of the error type of the underlying `MonadError`. static func runBlocking<A>( on queue: DispatchQueue, _ fa: @escaping () -> Kind<Self, A>) throws -> A /// Unsafely runs a computation in an asynchronous manner. /// /// - Parameters: /// - queue: Dispatch queue used to run the computation. /// - fa: Computation to be run. /// - callback: Callback to report the result of the evaluation. static func runNonBlocking<A>( on queue: DispatchQueue, _ fa: @escaping () -> Kind<Self, A>, _ callback: @escaping Callback<E, A>) } // MARK: Syntax for UnsafeRun public extension Kind where F: UnsafeRun { /// Unsafely runs a computation in a synchronous manner. /// /// - Parameters: /// - queue: Dispatch queue used to run the computation. Defaults to the main queue. /// - Returns: Result of running the computation. /// - Throws: Error happened during the execution of the computation, of the error type of the underlying `MonadError`. func runBlocking(on queue: DispatchQueue = .main) throws -> A { try F.runBlocking(on: queue, { self }) } /// Unsafely runs a computation in an asynchronous manner. /// /// - Parameters: /// - queue: Dispatch queue used to run the computation. Defaults to the main queue. /// - callback: Callback to report the result of the evaluation. func runNonBlocking( on queue: DispatchQueue = .main, _ callback: @escaping Callback<F.E, A> = { _ in }) { F.runNonBlocking(on: queue, { self }, callback) } } // MARK: Syntax for DispatchQueue and UnsafeRun public extension DispatchQueue { /// Unsafely runs a computation in a synchronous manner. /// /// - Parameter fa: Computation to be run. /// - Returns: Result of running the computation. /// - Throws: Error happened during the execution of the computation, of the error type of the underlying `MonadError`. func runBlocking<F: UnsafeRun, A>( _ fa: @escaping () -> Kind<F, A>) throws -> A { try F.runBlocking(on: self, fa) } /// Unsafely runs a computation in an asynchronous manner. /// /// - Parameters: /// - fa: Computation to be run. /// - callback: Callback to report the result of the evaluation. func runNonBlocking<F: UnsafeRun, A>( _ fa: @escaping () -> Kind<F, A>, _ callback: @escaping Callback<F.E, A> = { _ in }) { F.runNonBlocking(on: self, fa, callback) } }
import Foundation struct ApiResult : Codable { let html_attributions : [String]? let next_page_token : String? let results : [Results]? let status : String? enum CodingKeys: String, CodingKey { case html_attributions = "html_attributions" case next_page_token = "next_page_token" case results = "results" case status = "status" } }
// // Comment.swift // WebServices // // Created by apple on 27/02/19. // Copyright © 2019 iOSProofs. All rights reserved. // import Foundation class Comment: Codable { var postId: Int? var id: Int? var name: String? var email: String? var body: String? } // // "postId": 1, // "id": 1, // "name": "id labore ex et quam laborum", // "email": "Eliseo@gardner.biz", // "body": "laudantium enim quasi est quidem magnam voluptate ipsam eos\ntempora quo necessitatibus\ndolor quam autem quasi\nreiciendis et nam sapiente accusantium" class Response: Codable { let status: Int? let message: String? let products: [Product] } class Product: Codable { let productName: String? let price: Double? }
import Foundation struct Constant { struct Flickr { static let APIBaseURL = "https://api.flickr.com/services/rest/" } struct FlickersParameterKeys { static let Method = "method" static let APIKey = "api_key" static let USERId = "user_id" static let Extras = "extras" static let Format = "format" static let Nojsoncallback = "nojsoncallback" static let AuoToken = "auth_token" static let APISgi = "api_sig" } struct FlickersParameterValues { static let Method = "flickr.photos.search" static let APIKey = "e9a8cf28694771511e7cc036d86ef637" static let USERId = "154001873%40N02" static let Extras = "url_m" static let Format = "json" static let Nojsoncallback = "1" static let AuoToken = "72157680136613912-c8c74775987042da" static let APISgi = "59e718dbff0b5714801bc254930775b8" } }
// Podcast.swift // PodcastsApp // Created by MOAMEN on 9/6/1397 AP. // Copyright © 1397 MOAMEN. All rights reserved. import Foundation // podcast model class Podcast: NSObject, Decodable, NSCoding { var trackName: String? var artistName: String? var artworkUrl60: String? var trackCount: Int? var feedUrl: String? func encode(with aCoder: NSCoder) { print("Trying to transform Podcast into Data") aCoder.encode(trackName ?? "", forKey: "trackNameKey") aCoder.encode(artistName ?? "", forKey: "artistNameKey") aCoder.encode(artworkUrl60 ?? "", forKey: "artworkUrl60Key") aCoder.encode(trackCount ?? "", forKey: "trackCountKey") aCoder.encode(feedUrl ?? "", forKey: "feedUrlKey") } required init?(coder aDecoder: NSCoder) { print("Trying to turn Data into Podcast") self.trackName = aDecoder.decodeObject(forKey: "trackNameKey") as? String self.artistName = aDecoder.decodeObject(forKey: "artistNameKey") as? String self.artworkUrl60 = aDecoder.decodeObject(forKey: "artworkUrl60Key") as? String self.trackCount = aDecoder.decodeObject(forKey: "trackCountKey") as? Int self.feedUrl = aDecoder.decodeObject(forKey: "feedUrlKey") as? String } }
// // MenuVC.swift // KBTUApp // // Created by User on 02.03.2021. // Copyright © 2021 User. All rights reserved. // import UIKit class MenuVC: UITableViewController { override func viewDidLoad() { super.viewDidLoad() self.title = "Menu" } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { print (indexPath.row) NotificationCenter.default.post(name: NSNotification.Name("ToggleSideMenu"), object: nil) switch indexPath.row{ case 0: NotificationCenter.default.post(name: NSNotification.Name("ShowNews"), object: nil) case 1: NotificationCenter.default.post(name: NSNotification.Name("ShowAboutUs"), object: nil) case 2: NotificationCenter.default.post(name: NSNotification.Name("ShowFaculties"), object: nil) case 3: NotificationCenter.default.post(name: NSNotification.Name("ShowFavorites"), object: nil) default: break } } }
// // TextDocumentPosition.swift // swift-language-server // // Created by Koray Koska on 19.03.18. // import Foundation public struct TextDocumentPosition: Codable { /// Line position in a document (zero-based). public let line: Int /** * Character offset on a line in a document (zero-based). Assuming that the line is * represented as a string, the `character` value represents the gap between the * `character` and `character + 1`. * * If the character value is greater than the line length it defaults back to the * line length. */ public let character: Int }
// // LessonsView.swift // PerfectPhoto // // Created by Reinaldo Verdugo on 09/11/14. // Copyright (c) 2014 ___PruebaCorp___. All rights reserved. // import UIKit class LessonsView: UIViewController { var introCompleted : Bool = false @IBAction func introLessonPressed(sender: UIButton) { performSegueWithIdentifier("gotoLesson0", sender: self) } @IBAction func expoLessonPressed(sender: UIButton) { let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate let intro = appDelegate.introCompleted if intro { performSegueWithIdentifier("gotoLesson1", sender: self) } else { let alert = UIAlertController(title: "Atención", message: "Debes completar la lección de Introducción primero.", preferredStyle: .Alert) alert.addAction(UIAlertAction(title: "Aceptar", style: .Default, handler: {(alertAction)in // alert.dismissViewControllerAnimated(true, completion: nil) })) self.presentViewController(alert, animated: true, completion: nil) } } 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. } }
// // Scale_ContentNotFrame.swift // 100Views // // Created by Mark Moeykens on 9/4/19. // Copyright © 2019 Mark Moeykens. All rights reserved. // import SwiftUI struct Scale_FramesAndContent: View { var body: some View { VStack(spacing: 20) { Text("Scale Effect").font(.largeTitle) Text("Frames & Content") .font(.title).foregroundColor(.gray) Text("Notice when scaling, it is the content that is affected, not the frame. The frame size is unchanged.") .frame(maxWidth: .infinity) .font(.title).padding() .background(Color.pink) .layoutPriority(1) .foregroundColor(.white) Group { Text("Before") Text("Scale This") .font(.title) .border(Color.pink) Text("After (3X)") Text("Scale This") .font(.title) .scaleEffect(3) .border(Color.pink) Divider().padding(.top) Text("Before") Image("yosemite") .border(Color.pink) Text("After (1.6X)") Image("yosemite") .scaleEffect(1.6) .border(Color.pink) } } } } struct Scale_FramesAndContent_Previews: PreviewProvider { static var previews: some View { Scale_FramesAndContent() } }
// // TableViewController.swift // Surva // // Created by April on 9/12/15. // Copyright (c) 2015 Michael Lombardo. All rights reserved. // import UIKit import ParseUI import Parse class SurveyListController: PFQueryTableViewController { @IBAction func signOut(sender: AnyObject) { PFUser.logOut() let storyboard = UIStoryboard(name: "Main", bundle: nil) let vc = storyboard.instantiateViewControllerWithIdentifier("SignUpInViewController") as! UIViewController self.presentViewController(vc, animated: true, completion: nil) } 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() } //self.tableView.delegate = self //self.tableView.dataSource = self // Initialise the PFQueryTable tableview override init(style: UITableViewStyle, className: String!) { super.init(style: style, className: className) } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) // Configure the PFQueryTableView self.parseClassName = "Category" self.textKey = "Title" self.pullToRefreshEnabled = true self.paginationEnabled = false } // Define the query that will provide the data for the table view override func queryForTable() -> PFQuery { //show all that the current user hasn't completed yet var completedCategories = PFQuery(className: "Completed") completedCategories.whereKey("userID", equalTo: PFUser.currentUser()!.objectId!) var query = PFQuery(className: "Category") query.whereKey("objectId", doesNotMatchKey:"categoryID", inQuery:completedCategories) return query } //override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject?) -> PFTableViewCell { var cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! PFTableViewCell! if cell == nil { cell = PFTableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell") } // Extract values from the PFObject to display in the table cell if let Question = object?["Title"] as? String { cell?.textLabel?.text = Question } return cell } // 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]. if segue.destinationViewController is QuestionViewController { var detailScene = segue.destinationViewController as! QuestionViewController // Pass the selected object to the destination view controller. if let indexPath = self.tableView.indexPathForSelectedRow() { let row = Int(indexPath.row) detailScene.currentObject = (objects![row] as? PFObject)! } } } }
import UIKit struct CoinInvestorsModule { static func viewController(coinUid: String) -> UIViewController { let service = CoinInvestorsService(coinUid: coinUid, marketKit: App.shared.marketKit, currencyKit: App.shared.currencyKit) let viewModel = CoinInvestorsViewModel(service: service) return CoinInvestorsViewController(viewModel: viewModel, urlManager: UrlManager(inApp: true)) } }
// // Designables.swift // PupCare // // Created by Luis Filipe Campani on 14/07/16. // Copyright © 2016 PupCare. All rights reserved. // import UIKit @IBDesignable class TXTAttributedStyle: UITextField { @IBInspectable var borderColor: UIColor = UIColor.clear { didSet { layer.borderColor = borderColor.cgColor } } @IBInspectable var borderWidth : CGFloat = 0 { didSet { layer.borderWidth = borderWidth } } @IBInspectable var cornerRadius : CGFloat = 0 { didSet { layer.cornerRadius = cornerRadius } } @IBInspectable var placeHolderColor: UIColor? { get { return self.placeHolderColor } set { self.attributedPlaceholder = NSAttributedString(string:self.placeholder != nil ? self.placeholder! : "", attributes:[NSForegroundColorAttributeName: newValue!]) } } override func awakeFromNib() { } } @IBDesignable class BTNAttributedStyle: UIButton { @IBInspectable var borderColor: UIColor = UIColor.clear { didSet { layer.borderColor = borderColor.cgColor } } @IBInspectable var borderWidth : CGFloat = 0 { didSet { layer.borderWidth = borderWidth } } @IBInspectable var cornerRadius : CGFloat = 0 { didSet { layer.cornerRadius = cornerRadius } } override func awakeFromNib() { } } @IBDesignable class IMGAttributedStyle: UIImageView { @IBInspectable var borderColor: UIColor = UIColor.clear { didSet { layer.borderColor = borderColor.cgColor } } @IBInspectable var borderWidth : CGFloat = 0 { didSet { layer.borderWidth = borderWidth } } @IBInspectable var cornerRadius : CGFloat = 0 { didSet { layer.cornerRadius = cornerRadius } } override func awakeFromNib() { } } @IBDesignable class VIEWAtrributedStyle: UIView { @IBInspectable var cornerRadius: CGFloat = 0 { didSet{ layer.cornerRadius = cornerRadius } } }
/* Copyright (C) 2016 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: This class manages the CoreMotion interactions and provides a delegate to indicate changes in data. */ import Foundation import CoreMotion import WatchKit /** `MotionManagerDelegate` exists to inform delegates of motion changes. These contexts can be used to enable application specific behavior. */ protocol MotionManagerDelegate: class { func didUpdateForehandSwingCount(_ manager: MotionManager, forehandCount: Int, dataCollection: DataCollection) func didUpdateBackhandSwingCount(_ manager: MotionManager, backhandCount: Int, dataCollection: DataCollection) // func didUpdateDataCollection(_ manager: MotionManager, dataCollection: DataCollection) } struct DataCollection { var rotates = [CMRotationRate]() var gravities = [CMAcceleration]() var magnatics = [CMCalibratedMagneticField]() var userAcc = [CMAcceleration]() func friendlyPrint()->String { var res = "" /** print out the following format, r.x,r,y,r,z,g.x,g.y,g.z,m.x,m.y,m.z,u.x,u.y,u.z \n */ for index in 0..<rotates.count{ let rs = rotates[index] let rDesc = String(rs.x) + "," + String(rs.y) + "," + String(rs.z) let gs = gravities[index] let gDesc = String(gs.x) + "," + String(gs.y) + "," + String(gs.z) let us = userAcc[index] let uDesc = String(us.x) + "," + String(us.y) + "," + String(us.z) let ms = magnatics[index] let mDesc = String(ms.field.x) + "," + String(ms.field.y) + "," + String(ms.field.z) res += rDesc + "," + gDesc + "," + uDesc + "," + mDesc + "\n" } return res } } class MotionManager { // MARK: Properties let motionManager = CMMotionManager() let queue = OperationQueue() let wristLocationIsLeft = WKInterfaceDevice.current().wristLocation == .left // MARK: Application Specific Constants // These constants were derived from data and should be further tuned for your needs. let yawThreshold = 1.95 // Radians let rateThreshold = 5.5 // Radians/sec let resetThreshold = 5.5 * 0.05 // To avoid double counting on the return swing. // The app is using 50hz data and the buffer is going to hold 1s worth of data. let sampleInterval = 1.0 / 50 let rateAlongGravityBuffer = RunningBuffer(size: 50) weak var delegate: MotionManagerDelegate? /// Swing counts. var forehandCount = 0 var backhandCount = 0 var recentDetection = false var dataCollection = DataCollection() // MARK: Initialization init() { // Serial queue for sample handling and calculations. queue.maxConcurrentOperationCount = 1 queue.name = "MotionManagerQueue" } func initDataCollection(){ dataCollection.gravities = [CMAcceleration]() // dataCollection.magnatics = [CMCalibratedMagneticField]() dataCollection.rotates = [CMRotationRate]() dataCollection.userAcc = [CMAcceleration]() } // MARK: Motion Manager func startUpdates() { if !motionManager.isDeviceMotionAvailable { print("Device Motion is not available.") return } // Reset everything when we start. resetAllState() motionManager.deviceMotionUpdateInterval = sampleInterval motionManager.startDeviceMotionUpdates(to: queue) { (deviceMotion: CMDeviceMotion?, error:NSError?) in if error != nil { print("Encountered error: \(error!)") } if deviceMotion != nil { self.processDeviceMotion(deviceMotion!) } } } func stopUpdates() { if motionManager.isDeviceMotionAvailable { motionManager.stopDeviceMotionUpdates() } } // MARK: Motion Processing func processDeviceMotion(_ deviceMotion: CMDeviceMotion) { let gravity = deviceMotion.gravity dataCollection.gravities.append(gravity) let rotationRate = deviceMotion.rotationRate dataCollection.rotates.append(rotationRate) let magentic = deviceMotion.magneticField dataCollection.magnatics.append(magentic) dataCollection.userAcc.append(deviceMotion.userAcceleration) let rateAlongGravity = rotationRate.x * gravity.x // r⃗ · ĝ + rotationRate.y * gravity.y + rotationRate.z * gravity.z rateAlongGravityBuffer.addSample(rateAlongGravity) if !rateAlongGravityBuffer.isFull() { return } // Send back once reach 500 data incrementForehandCountAndUpdateDelegate() // Then start it over rateAlongGravityBuffer.reset() // let accumulatedYawRot = rateAlongGravityBuffer.sum() * sampleInterval // let peakRate = accumulatedYawRot > 0 ? // rateAlongGravityBuffer.max() : rateAlongGravityBuffer.min() // // if (accumulatedYawRot < -yawThreshold && peakRate < -rateThreshold) { // // Counter clockwise swing. // if (wristLocationIsLeft) { // incrementBackhandCountAndUpdateDelegate() // } else { // incrementForehandCountAndUpdateDelegate() // } // } else if (accumulatedYawRot > yawThreshold && peakRate > rateThreshold) { // // Clockwise swing. // if (wristLocationIsLeft) { // incrementForehandCountAndUpdateDelegate() // } else { // incrementBackhandCountAndUpdateDelegate() // } // } // // // Reset after letting the rate settle to catch the return swing. // if (recentDetection && abs(rateAlongGravityBuffer.recentMean()) < resetThreshold) { // recentDetection = false // rateAlongGravityBuffer.reset() // } } // MARK: Data and Delegate Management func resetAllState() { rateAlongGravityBuffer.reset() forehandCount = 0 backhandCount = 0 recentDetection = false initDataCollection() updateForehandSwingDelegate() updateBackhandSwingDelegate() } func incrementForehandCountAndUpdateDelegate() { if (!recentDetection) { forehandCount += 1 recentDetection = true // print("Forehand swing. Count: \(forehandCount)") updateForehandSwingDelegate() } } func incrementBackhandCountAndUpdateDelegate() { if (!recentDetection) { backhandCount += 1 recentDetection = true // print("Backhand swing. Count: \(backhandCount)") updateBackhandSwingDelegate() } } func updateForehandSwingDelegate() { delegate?.didUpdateForehandSwingCount(self, forehandCount:forehandCount, dataCollection: dataCollection) } func updateBackhandSwingDelegate() { delegate?.didUpdateBackhandSwingCount(self, backhandCount:backhandCount, dataCollection: dataCollection) } }
// // ServerConnectionViewController.swift // Emby // // Created by Aaron Alexander on 11/5/15. // // import UIKit #if !RX_NO_MODULE import RxSwift import RxCocoa #endif class ServerConnectionViewController: UIViewController { private let viewModel = ServerConnectionViewModel() private let disposeBag = DisposeBag() 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. } }
// // HeroObject.swift // AiviaProdTest // // Created by Adam on 2020-01-19. // Copyright © 2020 Adam. All rights reserved. // import Foundation //Codable object meant to directly absorb the JSON values using swift built-in decoding struct HeroData: Codable{ var id: Int? var name: String? var identity: String? var group: String? var place_of_origin: String? var publisher: String? } struct HeroObject: Codable{ var data: [HeroData] }
// // ViewController.swift // PJT2_autoLayout // // Created by mong on 10/12/2018. // Copyright © 2018 mong. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet var button: UIButton! @IBOutlet var label: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. // 오토 레이아웃을 걸기 전에는 유동적으로 뷰에 제약을 걸어둠. 그걸 코드상으로 해제를 시켜야 // 코드에서 작업한 오토레이아웃과 충돌 X button.translatesAutoresizingMaskIntoConstraints = false var constraintX: NSLayoutConstraint constraintX = button.centerXAnchor.constraint(equalTo: self.view.centerXAnchor) var constraintY: NSLayoutConstraint constraintY = button.centerYAnchor.constraint(equalTo: self.view.centerYAnchor) constraintX.isActive = true constraintY.isActive = true label.translatesAutoresizingMaskIntoConstraints = false var labelConstraintX: NSLayoutConstraint labelConstraintX = label.centerXAnchor.constraint(equalTo: button.centerXAnchor) var labelConstraintY: NSLayoutConstraint labelConstraintY = label.centerYAnchor.constraint(equalTo: button.centerYAnchor, constant: -50 ) labelConstraintX.isActive = true labelConstraintY.isActive = true } }
// // Slide.swift // ScrollProject // // Created by dirtbag on 11/27/19. // Copyright © 2019 dirtbag. All rights reserved. // import UIKit class Slide: UIView { @IBOutlet private weak var imageView: UIImageView! @IBOutlet private weak var lblWidth: UILabel! @IBOutlet private weak var lblHeight: UILabel! }
import Foundation extension NewBillController { func didSetUnitNumber() { guard let unitNumber = unitNumber else { return } API.shared.getLastBill(forUnitNumber: unitNumber) { (bill, error) in if let bill = bill { self.previousDate = bill.currentDate self.previousReading = bill.currentReading } else { self.didError?(AppError.api("Couldn't get last bill for unit \(unitNumber)")) } } } func getMeterNumber() -> String? { guard let unitNumber = unitNumber, let unit = units[unitNumber] else { return nil } return unit.meterNumber } func getTenantName() -> String? { guard let unitNumber = unitNumber, let unit = units[unitNumber] else { return nil } return unit.tenantName } func validateAndSave(completion: (Bool) -> ()) { guard let id = id, let unitNumber = unitNumber, let previousDate = previousDate, let currentDate = currentDate, let previousReading = previousReading, let currentReading = currentReading, let fixedCharge = fixedCharge, let surcharge = surcharge, let otherCharges = otherCharges, let meterNumber = meterNumber, let tenantName = tenantName, let consumption = consumption(), let rate = consumptionRate(), let bandA = bands()?["A"], let bandB = bands()?["B"], let bandC = bands()?["C"], let total = total() else { completion(false) return } let bill = Bill() bill.id = id bill.unitNumber = unitNumber bill.meterNumber = meterNumber bill.tenantName = tenantName bill.previousDate = previousDate bill.currentDate = currentDate bill.previousReading = previousReading bill.currentReading = currentReading bill.fixedCharge = fixedCharge bill.surcharge = surcharge bill.otherCharges = otherCharges bill.consumption = consumption bill.consumptionRate = rate bill.consumptionA = bandA.consumption bill.consumptionB = bandB.consumption bill.consumptionC = bandC.consumption bill.costA = bandA.cost bill.costB = bandB.cost bill.costC = bandC.cost bill.total = total do { try API.shared.realm().write { try API.shared.realm().add(bill) completion(true) } } catch { completion(false) } } }