text
stringlengths
8
1.32M
// // ViewController.swift // SimulateButtons // // Created by Miyuki Hirose on 2018/11/27. // Copyright © 2018 Miyuki Hirose. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let screenWidth: CGFloat = self.view.frame.width let screenHeight: CGFloat = self.view.frame.height makeMap(screenWidth: screenWidth, screenHeight: screenHeight) } /// ボタン作成 /// /// - Parameters: /// - screenWidth: 画面横幅 /// - screenHeight: 画面縦幅 func makeMap(screenWidth: CGFloat, screenHeight: CGFloat) { let row1: [Int] = [1, 2, 2, 1, 1, 1] let row2: [Int] = [1, 2, 2, 2, 2, 2] let row3: [Int] = [1, 2, 1, 2, 3, 3] let row4: [Int] = [2, 2, 2, 2, 3, 2] let row5: [Int] = [2, 2, 2, 1, 3, 2] let row6: [Int] = [2, 2, 2, 1, 2, 1] let row7: [Int] = [2, 2, 2, 1, 3, 2] let row8: [Int] = [2, 2, 2, 1, 2, 1] let rowCollection: [[Int]] = [row1, row2, row3, row4, row5, row6, row7, row8] for(rowIndex, rowItem) in rowCollection.enumerated() { for (index, value) in rowItem.enumerated() { addAnimalButton(x: CGFloat(index), y: CGFloat(rowIndex), screenWidth: screenWidth, screenHeight: screenHeight, label: value) } } } /// ボタン追加 /// /// - Parameters: /// - x: 横位置 /// - y: 縦位置 /// - screenWidth: 画面横幅 /// - screenHeight: 画面縦幅 /// - label: ボタン表示ラベル func addAnimalButton(x: CGFloat, y: CGFloat, screenWidth: CGFloat, screenHeight: CGFloat, label: Int) { let button = UIButton() // 位置 button.frame = CGRect(x: screenWidth / 6 * x, y: screenHeight / 10 * y + (screenHeight / 10), width: screenWidth / 6, height: screenHeight / 10) // ボタンの色 button.backgroundColor = UIColor.accentColor2 button.setTitleColor(UIColor.white, for: UIControl.State.normal) button.setTitle(String(label), for: UIControl.State.normal) button.addTarget(self, action: #selector(ViewController.buttonPushed(sender:)), for: .touchUpInside) self.view.addSubview(button) } /// 背景色のスイッチング /// /// - Parameter sender: 切り替え対象のボタン @IBAction func buttonPushed(sender: UIButton) { if sender.backgroundColor == UIColor.accentColor2 { sender.backgroundColor = UIColor.subColor } else { sender.backgroundColor = UIColor.accentColor2 } } } extension UIColor { // メインカラー・ベースカラー class var mainColor: UIColor { return UIColor.hex(string: "#f7e9e3", alpha: 1.0) } // サブカラー class var subColor: UIColor { return UIColor.hex(string: "#6dc9c8", alpha: 1.0) } // アクセントカラー1ピンク class var accentColor1: UIColor { return UIColor.hex(string: "#ffc0c2", alpha: 1.0) } // アクセントカラー2黒 class var accentColor2: UIColor { return UIColor.hex(string: "#0e3150", alpha: 1.0) } // 16進数で受け取ったカラーをRGBに変換して返却する class func hex (string: String, alpha: CGFloat) -> UIColor { let string_ = string.replacingOccurrences(of: "#", with: "") let scanner = Scanner(string: string_ as String) var color: UInt32 = 0 if scanner.scanHexInt32(&color) { let r = CGFloat((color & 0xFF0000) >> 16) / 255.0 let g = CGFloat((color & 0x00FF00) >> 8) / 255.0 let b = CGFloat(color & 0x0000FF) / 255.0 return UIColor(red: r, green: g, blue: b, alpha: alpha) } else { return UIColor.white; } } }
// // ServerStatusTests.swift // NOC-AppTests // // Created by Hassan El Desouky on 2/26/19. // Copyright © 2019 Hassan El Desouky. All rights reserved. // import XCTest @testable import NOC_App class ServerStatusTests: XCTestCase { override func setUp() { // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testSetStatusColor() { // Green let serverStatusGreen = Status(id: 1, statusValue: nil, legacyValue: nil) let serverOne = Server(status: serverStatusGreen) XCTAssert(Status.setStatusColor(for: 0, [serverOne]) == UIColor.FlatColor.Green.MountainMeadow, "SetStatusColor failed") // Orange let serverStatusOrange = Status(id: 2, statusValue: nil, legacyValue: nil) let serverTwo = Server(status: serverStatusOrange) XCTAssert(Status.setStatusColor(for: 0, [serverTwo]) == UIColor.FlatColor.Orange.NeonCarrot, "SetStatusColor failed") // Yellow let serverStatusYellow = Status(id: 3, statusValue: nil, legacyValue: nil) let serverThree = Server(status: serverStatusYellow) XCTAssert(Status.setStatusColor(for: 0, [serverThree]) == UIColor.FlatColor.Yellow.Turbo, "SetStatusColor failed") // Red let serverStatusRed = Status(id: 4, statusValue: nil, legacyValue: nil) let serverFour = Server(status: serverStatusRed) XCTAssert(Status.setStatusColor(for: 0, [serverFour]) == UIColor.FlatColor.Red.WellRead, "SetStatusColor failed") // Gray let serverStatus = Status(id: 5, statusValue: nil, legacyValue: nil) let server = Server(status: serverStatus) XCTAssert(Status.setStatusColor(for: 0, [server]) == UIColor.FlatColor.Gray.AlmondFrost, "SetStatusColor failed") } }
// // NODGroup.swift // NuoDunProject // // Created by lxzhh on 15/7/11. // Copyright (c) 2015年 lxzhh. All rights reserved. // import UIKit class NODGroup: NODObject { var groupName : String? var groupID : String? required init?(_ map: Map) { super.init() mapping(map) } // Mappable override func mapping(map: Map) { groupName <- map["BZMC"] groupID <- map["BZBM"] } override var description: String { get{ return "groupName:\(groupName) \n groupID:\(groupID)" } } override class func saveKey() -> String?{ let string = toString(self.dynamicType) // let key = string.componentsSeparatedByString(".").last! return "\(string)" } override class func loadJsonRootKey() -> String?{ return "BZ" } }
// // FundingSourceTableViewController.swift // TheDocument // // Created by Scott Kacyn on 1/25/18. // Copyright © 2018 Refer To The Document. All rights reserved. // import UIKit protocol SelectedAccountProtocol { func setSelectedAccount(account: [String: Any]) } class FundingSourceTableViewController: UITableViewController { var accounts: [[String: Any]] = [] var selectedAccount: [String: Any]? var delegate: SelectedAccountProtocol? override func viewDidLoad() { super.viewDidLoad() self.getAccounts() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func refreshAccounts() { DispatchQueue.main.async { self.tableView.reloadData() } } func getAccounts() { API().getLinkedAccounts { success in if let nodes = currentUser.nodes { self.accounts = nodes self.refreshAccounts() } } } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return accounts.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "SourceCell", for: indexPath) let node = self.accounts[indexPath.row] cell.accessoryType = .none if let info = node["info"] as? [String: Any], let nodeID = node["_id"] as? String { let sourceLabel = cell.viewWithTag(5) as! UILabel let nodeName = info["bank_name"] as? String ?? "Example Checking Account" let lastFour = info["account_num"] as? String ?? "0000" sourceLabel.text = "\(nodeName) ••••\(lastFour)" if let selection = selectedAccount, let selectedID = selection["_id"] as? String, selectedID == nodeID { cell.accessoryType = .checkmark } } return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let node = self.accounts[indexPath.row] self.selectedAccount = node delegate?.setSelectedAccount(account: node) tableView.reloadData() self.navigationController!.popViewController(animated: true) } }
// // FRShareFacebook.swift // Pods // // Created by Admin on 19.09.17. // // import Foundation //import FBSDKShareKit class FRShareFacebook { // let obj = UIReferenceLibraryViewController( // // Create an object // let object = FBSDKShareOpenGraphObject() // object.setString("books.book", forKey: "og:type") // object.setString("A Game of Thrones", forKey: "og:title") // object.setString("In the frozen wastes to the north of Winterfell, sinister and supernatural forces are mustering.", forKey: "og:description") // object.setString("books.book", forKey: "og:image") // // // Create an action // let action = FBSDKShareOpenGraphAction() // action.actionType = "book.reads" // action.setObject(object, forKey: "books:book") // // // Create the content // let content = FBSDKShareOpenGraphContent() // content.action = action // content.previewPropertyName = "books:book" }
// // UploadSettingsViewController.swift // piwigo // // Created by Eddy Lelièvre-Berna on 15/07/2020. // Copyright © 2020 Piwigo.org. All rights reserved. // class UploadSettingsViewController: UITableViewController, UITextFieldDelegate { @IBOutlet var settingsTableView: UITableView! var stripGPSdataOnUpload = Model.sharedInstance()?.stripGPSdataOnUpload ?? false var resizeImageOnUpload = Model.sharedInstance()?.resizeImageOnUpload ?? false var photoResize: Int16 = Int16(Model.sharedInstance()?.photoResize ?? 100) var compressImageOnUpload = Model.sharedInstance()?.compressImageOnUpload ?? false var photoQuality: Int16 = Int16(Model.sharedInstance()?.photoQuality ?? 98) var prefixFileNameBeforeUpload = Model.sharedInstance()?.prefixFileNameBeforeUpload ?? false var defaultPrefix = Model.sharedInstance()?.defaultPrefix ?? "" private var shouldUpdateDefaultPrefix = false private var canDeleteImages = false var deleteImageAfterUpload = false // MARK: - View Lifecycle override func viewDidLoad() { super.viewDidLoad() // Collection view identifier settingsTableView.accessibilityIdentifier = "Settings" } @objc func applyColorPalette() { // Background color of the views view.backgroundColor = UIColor.piwigoColorBackground() // Table view settingsTableView.separatorColor = UIColor.piwigoColorSeparator() settingsTableView.indicatorStyle = Model.sharedInstance().isDarkPaletteActive ? .white : .black settingsTableView.reloadData() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Set colors, fonts, etc. applyColorPalette() // Register palette changes let name: NSNotification.Name = NSNotification.Name(kPiwigoNotificationPaletteChanged) NotificationCenter.default.addObserver(self, selector: #selector(applyColorPalette), name: name, object: nil) // Can we propose to delete images after upload? if let switchVC = parent as? UploadSwitchViewController { canDeleteImages = switchVC.canDeleteImages if canDeleteImages { deleteImageAfterUpload = Model.sharedInstance().deleteImageAfterUpload } } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) // Unregister palette changes let name: NSNotification.Name = NSNotification.Name(kPiwigoNotificationPaletteChanged) NotificationCenter.default.removeObserver(self, name: name, object: nil) } // MARK: - UITableView - Header override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { // Title let titleString = "\(NSLocalizedString("imageUploadHeaderTitle_upload", comment: "Upload Settings"))\n" let titleAttributes = [ NSAttributedString.Key.font: UIFont.piwigoFontBold() ] let context = NSStringDrawingContext() context.minimumScaleFactor = 1.0 let titleRect = titleString.boundingRect(with: CGSize(width: tableView.frame.size.width - 30.0, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, attributes: titleAttributes, context: context) // Text let textString = NSLocalizedString("imageUploadHeaderText_upload", comment: "Please set the upload parameters to apply to the selection of photos/videos") let textAttributes = [ NSAttributedString.Key.font: UIFont.piwigoFontSmall() ] let textRect = textString.boundingRect(with: CGSize(width: tableView.frame.size.width - 30.0, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, attributes: textAttributes, context: context) return CGFloat(fmax(44.0, ceil(titleRect.size.height + textRect.size.height))) } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerAttributedString = NSMutableAttributedString(string: "") // Title let titleString = "\(NSLocalizedString("imageUploadHeaderTitle_upload", comment: "Upload Settings"))\n" let titleAttributedString = NSMutableAttributedString(string: titleString) titleAttributedString.addAttribute(.font, value: UIFont.piwigoFontBold(), range: NSRange(location: 0, length: titleString.count)) headerAttributedString.append(titleAttributedString) // Text let textString = NSLocalizedString("imageUploadHeaderText_upload", comment: "Please set the upload parameters to apply to the selection of photos/videos") let textAttributedString = NSMutableAttributedString(string: textString) textAttributedString.addAttribute(.font, value: UIFont.piwigoFontSmall(), range: NSRange(location: 0, length: textString.count)) headerAttributedString.append(textAttributedString) // Header label let headerLabel = UILabel() headerLabel.translatesAutoresizingMaskIntoConstraints = false headerLabel.textColor = UIColor.piwigoColorHeader() headerLabel.numberOfLines = 0 headerLabel.adjustsFontSizeToFitWidth = false headerLabel.lineBreakMode = .byWordWrapping headerLabel.attributedText = headerAttributedString // Header view let header = UIView() header.addSubview(headerLabel) header.addConstraint(NSLayoutConstraint.constraintView(fromBottom: headerLabel, amount: 4)!) if #available(iOS 11, *) { header.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "|-[header]-|", options: [], metrics: nil, views: [ "header": headerLabel ])) } else { header.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "|-15-[header]-15-|", options: [], metrics: nil, views: [ "header": headerLabel ])) } return header } override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 0.0 } // MARK: - UITableView - Rows /// Remark: a UIView is added at the bottom of the table view in the storyboard /// to eliminate extra separators below the cells. override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 4 + (resizeImageOnUpload ? 1 : 0) + (compressImageOnUpload ? 1 : 0) + (prefixFileNameBeforeUpload ? 1 : 0) + (canDeleteImages ? 1 : 0) } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var tableViewCell = UITableViewCell() var row = indexPath.row row += (!resizeImageOnUpload && (row > 1)) ? 1 : 0 row += (!compressImageOnUpload && (row > 3)) ? 1 : 0 row += (!prefixFileNameBeforeUpload && (row > 5)) ? 1 : 0 switch row { case 0 /* Strip private Metadata? */: guard let cell = tableView.dequeueReusableCell(withIdentifier: "SwitchTableViewCell", for: indexPath) as? SwitchTableViewCell else { print("Error: tableView.dequeueReusableCell does not return a SwitchTableViewCell!") return SwitchTableViewCell() } // See https://www.paintcodeapp.com/news/ultimate-guide-to-iphone-resolutions if view.bounds.size.width > 414 { // i.e. larger than iPhones 6,7 screen width cell.configure(with: NSLocalizedString("settings_stripGPSdata>375px", comment: "Strip Private Metadata Before Upload")) } else { cell.configure(with: NSLocalizedString("settings_stripGPSdata", comment: "Strip Private Metadata")) } cell.cellSwitch.setOn(stripGPSdataOnUpload, animated: true) cell.cellSwitchBlock = { switchState in self.stripGPSdataOnUpload = switchState } cell.accessibilityIdentifier = "stripMetadataBeforeUpload" tableViewCell = cell case 1 /* Resize Before Upload? */: guard let cell = tableView.dequeueReusableCell(withIdentifier: "SwitchTableViewCell", for: indexPath) as? SwitchTableViewCell else { print("Error: tableView.dequeueReusableCell does not return a SwitchTableViewCell!") return SwitchTableViewCell() } // See https://www.paintcodeapp.com/news/ultimate-guide-to-iphone-resolutions if view.bounds.size.width > 375 { // i.e. larger than iPhones 6,7 screen width cell.configure(with: NSLocalizedString("settings_photoResize>375px", comment: "Resize Image Before Upload")) } else { cell.configure(with: NSLocalizedString("settings_photoResize", comment: "Resize Before Upload")) } cell.cellSwitch.setOn(resizeImageOnUpload, animated: true) cell.cellSwitchBlock = { switchState in // Number of rows will change accordingly self.resizeImageOnUpload = switchState // Position of the row that should be added/removed let rowAtIndexPath = IndexPath(row: 2, section: 0) if switchState { // Insert row in existing table self.settingsTableView?.insertRows(at: [rowAtIndexPath], with: .automatic) } else { // Remove row in existing table self.settingsTableView?.deleteRows(at: [rowAtIndexPath], with: .automatic) } } cell.accessibilityIdentifier = "resizeBeforeUpload" tableViewCell = cell case 2 /* Image Size slider */: guard let cell = tableView.dequeueReusableCell(withIdentifier: "SliderTableViewCell", for: indexPath) as? SliderTableViewCell else { print("Error: tableView.dequeueReusableCell does not return a SliderTableViewCell!") return SliderTableViewCell() } // Slider value let value = Float(photoResize) // Slider configuration let title = String(format: "… %@", NSLocalizedString("settings_photoSize", comment: "Size")) cell.configure(with: title, value: value, increment: 1, minValue: 5, maxValue: 100, prefix: "", suffix: "%") cell.cellSliderBlock = { newValue in // Update settings self.photoResize = Int16(newValue) } cell.accessibilityIdentifier = "maxNberRecentAlbums" tableViewCell = cell case 3 /* Compress before Upload? */: guard let cell = tableView.dequeueReusableCell(withIdentifier: "SwitchTableViewCell", for: indexPath) as? SwitchTableViewCell else { print("Error: tableView.dequeueReusableCell does not return a SwitchTableViewCell!") return SwitchTableViewCell() } // See https://www.paintcodeapp.com/news/ultimate-guide-to-iphone-resolutions if view.bounds.size.width > 375 { // i.e. larger than iPhones 6,7 screen width cell.configure(with: NSLocalizedString("settings_photoCompress>375px", comment: "Compress Image Before Upload")) } else { cell.configure(with: NSLocalizedString("settings_photoCompress", comment: "Compress Before Upload")) } cell.cellSwitch.setOn(compressImageOnUpload, animated: true) cell.cellSwitchBlock = { switchState in // Number of rows will change accordingly self.compressImageOnUpload = switchState // Position of the row that should be added/removed let rowAtIndexPath = IndexPath(row: 3 + (self.resizeImageOnUpload ? 1 : 0), section: 0) if switchState { // Insert row in existing table self.settingsTableView?.insertRows(at: [rowAtIndexPath], with: .automatic) } else { // Remove row in existing table self.settingsTableView?.deleteRows(at: [rowAtIndexPath], with: .automatic) } } cell.accessibilityIdentifier = "compressBeforeUpload" tableViewCell = cell case 4 /* Image Quality slider */: guard let cell = tableView.dequeueReusableCell(withIdentifier: "SliderTableViewCell", for: indexPath) as? SliderTableViewCell else { print("Error: tableView.dequeueReusableCell does not return a SliderTableViewCell!") return SliderTableViewCell() } // Slider value let value = Float(photoQuality) // Slider configuration let title = String(format: "… %@", NSLocalizedString("settings_photoQuality", comment: "Quality")) cell.configure(with: title, value: value, increment: 1, minValue: 50, maxValue: 98, prefix: "", suffix: "%") cell.cellSliderBlock = { newValue in // Update settings self.photoQuality = Int16(newValue) } cell.accessibilityIdentifier = "compressionRatio" tableViewCell = cell case 5 /* Prefix Filename Before Upload switch */: guard let cell = tableView.dequeueReusableCell(withIdentifier: "SwitchTableViewCell", for: indexPath) as? SwitchTableViewCell else { print("Error: tableView.dequeueReusableCell does not return a SwitchTableViewCell!") return SwitchTableViewCell() } // See https://www.paintcodeapp.com/news/ultimate-guide-to-iphone-resolutions if view.bounds.size.width > 414 { // i.e. larger than iPhones 6,7 screen width cell.configure(with: NSLocalizedString("settings_prefixFilename>414px", comment: "Prefix Photo Filename Before Upload")) } else if view.bounds.size.width > 375 { // i.e. larger than iPhones 6,7 screen width cell.configure(with: NSLocalizedString("settings_prefixFilename>375px", comment: "Prefix Filename Before Upload")) } else { cell.configure(with: NSLocalizedString("settings_prefixFilename", comment: "Prefix Filename")) } cell.cellSwitch.setOn(prefixFileNameBeforeUpload, animated: true) cell.cellSwitchBlock = { switchState in // Number of rows will change accordingly self.prefixFileNameBeforeUpload = switchState // Position of the row that should be added/removed let rowAtIndexPath = IndexPath(row: 4 + (self.resizeImageOnUpload ? 1 : 0) + (self.compressImageOnUpload ? 1 : 0),section: 0) if switchState { // Insert row in existing table self.settingsTableView?.insertRows(at: [rowAtIndexPath], with: .automatic) } else { // Remove row in existing table self.settingsTableView?.deleteRows(at: [rowAtIndexPath], with: .automatic) } } cell.accessibilityIdentifier = "prefixBeforeUpload" tableViewCell = cell case 6 /* Filename prefix? */: guard let cell = tableView.dequeueReusableCell(withIdentifier: "TextFieldTableViewCell", for: indexPath) as? TextFieldTableViewCell else { print("Error: tableView.dequeueReusableCell does not return a TextFieldTableViewCell!") return TextFieldTableViewCell() } // See https://www.paintcodeapp.com/news/ultimate-guide-to-iphone-resolutions var title: String let input: String = defaultPrefix let placeHolder: String = NSLocalizedString("settings_defaultPrefixPlaceholder", comment: "Prefix Filename") if view.bounds.size.width > 320 { // i.e. larger than iPhone 5 screen width title = String(format:"… %@", NSLocalizedString("settings_defaultPrefix>320px", comment: "Filename Prefix")) } else { title = String(format:"… %@", NSLocalizedString("settings_defaultPrefix", comment: "Prefix")) } cell.configure(with: title, input: input, placeHolder: placeHolder) cell.rightTextField.delegate = self cell.rightTextField.tag = kImageUploadSetting.prefix.rawValue cell.rightTextField.textColor = shouldUpdateDefaultPrefix ? UIColor.piwigoColorOrange() : UIColor.piwigoColorRightLabel() cell.accessibilityIdentifier = "prefixFileName" tableViewCell = cell case 7 /* Delete image after upload? */: guard let cell = tableView.dequeueReusableCell(withIdentifier: "SwitchTableViewCell", for: indexPath) as? SwitchTableViewCell else { print("Error: tableView.dequeueReusableCell does not return a SwitchTableViewCell!") return SwitchTableViewCell() } // See https://www.paintcodeapp.com/news/ultimate-guide-to-iphone-resolutions if view.bounds.size.width > 414 { // i.e. larger than iPhones 6,7 screen width cell.configure(with: NSLocalizedString("settings_deleteImage>375px", comment: "Delete Image After Upload")) } else { cell.configure(with: NSLocalizedString("settings_deleteImage", comment: "Delete After Upload")) } cell.cellSwitch.setOn(deleteImageAfterUpload, animated: true) cell.cellSwitchBlock = { switchState in self.deleteImageAfterUpload = switchState } cell.accessibilityIdentifier = "deleteAfterUpload" tableViewCell = cell default: break } tableViewCell.isAccessibilityElement = true return tableViewCell } override func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool { return false } // MARK: - UITextFieldDelegate Methods func textFieldDidBeginEditing(_ textField: UITextField) { let tag = kImageUploadSetting(rawValue: textField.tag) switch tag { case .prefix: shouldUpdateDefaultPrefix = true default: break } } func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { // Piwigo 2.10.2 supports the 3-byte UTF-8, not the standard UTF-8 (4 bytes) let newString = NetworkUtilities.utf8mb3String(from: string) ?? "" guard let finalString = (textField.text as NSString?)?.replacingCharacters(in: range, with: newString) else { return true } let tag = kImageUploadSetting(rawValue: textField.tag) switch tag { case .prefix: defaultPrefix = finalString default: break } return true } func textFieldShouldClear(_ textField: UITextField) -> Bool { let tag = kImageUploadSetting(rawValue: textField.tag) switch tag { case .prefix: defaultPrefix = "" default: break } return true } func textFieldShouldReturn(_ textField: UITextField) -> Bool { settingsTableView?.endEditing(true) return true } func textFieldDidEndEditing(_ textField: UITextField) { let tag = kImageUploadSetting(rawValue: textField.tag) switch tag { case .prefix: // Piwigo 2.10.2 supports the 3-byte UTF-8, not the standard UTF-8 (4 bytes) defaultPrefix = NetworkUtilities.utf8mb3String(from: textField.text) ?? "" if defaultPrefix.isEmpty { shouldUpdateDefaultPrefix = false } default: break } // Update cell let indexPath = IndexPath.init(row: kImageUploadSetting.prefix.rawValue, section: 0) settingsTableView.reloadRows(at: [indexPath], with: .automatic) } }
// // SCTitleView.swift // SCOptionPage // // Created by Kaito on 2018/1/18. // Copyright © 2018年 kaito. All rights reserved. // import UIKit protocol SCTitleViewDeleate : class { func titleView(titleView : SCTitleView, currentIndex : Int) } class SCTitleView: UIView { weak var delegate : SCTitleViewDeleate? fileprivate var titles : [String] fileprivate var style : SCOptionPageStyle fileprivate var superView: SCOpitonPageView? fileprivate lazy var currentIndex : Int = 0 fileprivate lazy var titleLabels : [UILabel] = [UILabel]() fileprivate lazy var scrollView : UIScrollView = { let scrollView = UIScrollView(frame: self.bounds) scrollView.showsHorizontalScrollIndicator = false scrollView.scrollsToTop = false return scrollView }() fileprivate lazy var bottomLine : UIView = { let bottomLine = UIView() bottomLine.backgroundColor = self.style.bottomLineColor bottomLine.frame.size.height = self.style.bottomLineHeight return bottomLine }() fileprivate lazy var coverView : UIView = { let coverView = UIView() coverView.backgroundColor = self.style.coverBgColor coverView.alpha = self.style.coverAlpha return coverView }() init(frame: CGRect, titles:[String], style:SCOptionPageStyle, superView: SCOpitonPageView? = nil) { self.titles = titles self.style = style self.superView = superView super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } //MARK: - UI界面 extension SCTitleView { fileprivate func setupUI() { backgroundColor = self.style.titleViewColor addSubview(scrollView) setupTitleLabels() setupTitleLabelsFrame() setupBottomLine() setupCoverView() } private func setupTitleLabels() { for (i, title) in titles.enumerated() { let titleLabel = UILabel() titleLabel.text = title titleLabel.tag = i titleLabel.font = style.titleFont titleLabel.textColor = i == 0 ? style.selectColor : style.normalColor titleLabel.textAlignment = .center scrollView.addSubview(titleLabel) titleLabels.append(titleLabel) let tapGes = UITapGestureRecognizer(target: self, action: #selector(titleLabelClick(_:))) titleLabel.addGestureRecognizer(tapGes) titleLabel.isUserInteractionEnabled = true } } private func setupTitleLabelsFrame() { let count = titles.count for (i, label) in titleLabels.enumerated() { var w : CGFloat = 0 let h : CGFloat = bounds.height var x : CGFloat = 0 let y : CGFloat = 0 if !style.isScrollEnable { w = bounds.width / CGFloat(count) x = w * CGFloat(i) } else { w = (titles[i] as NSString).boundingRect(with: CGSize(width : CGFloat.greatestFiniteMagnitude, height: 0), options: .usesLineFragmentOrigin, attributes: [NSAttributedStringKey.font : style.titleFont], context: nil).width if i == 0 { x = style.titleMargin * 0.5 } else { let preLabel = titleLabels[i - 1] x = preLabel.frame.maxX + style.titleMargin } } label.frame = CGRect(x: x, y: y, width: w, height: h) if style.isTitleScale && i == 0 { label.transform = CGAffineTransform(scaleX: style.scaleRange, y: style.scaleRange) } } if style.isScrollEnable { scrollView.contentSize.width = titleLabels.last!.frame.maxX + style.titleMargin * 0.5 } } private func setupBottomLine() { guard style.isShowBottomLine else { return } scrollView.addSubview(bottomLine) if !style.isScrollEnable { bottomLine.frame.origin.x = 0 bottomLine.frame.size.width = bounds.width / CGFloat(titles.count) } else { bottomLine.frame.origin.x = style.titleMargin * 0.5 bottomLine.frame.size.width = (titles[0] as NSString).boundingRect(with: CGSize(width : CGFloat.greatestFiniteMagnitude, height: 0), options: .usesLineFragmentOrigin, attributes: [NSAttributedStringKey.font : style.titleFont], context: nil).width } bottomLine.frame.origin.y = bounds.height - style.bottomLineHeight } private func setupCoverView() { guard style.isShowCoverView else { return } scrollView.addSubview(coverView) var coverW : CGFloat = titleLabels.first!.frame.width - 2 * style.coverMargin if style.isScrollEnable { coverW = titleLabels.first!.frame.width + style.titleMargin * 0.5 } let coverH : CGFloat = style.coverHeight coverView.bounds = CGRect(x: 0, y: 0, width: coverW, height: coverH) coverView.center = titleLabels.first!.center coverView.layer.cornerRadius = style.coverHeight * 0.5 coverView.layer.masksToBounds = true } } //MARK:- 事件处理函数 extension SCTitleView { @objc fileprivate func titleLabelClick(_ tapGes : UITapGestureRecognizer) { guard let newLabel = tapGes.view as? UILabel else { return } superView?.delegate?.optionPageClick(optionPage: superView!, index: newLabel.tag) guard currentIndex != newLabel.tag else { return } let oldLabel = titleLabels[currentIndex] oldLabel.textColor = style.normalColor newLabel.textColor = style.selectColor currentIndex = newLabel.tag adjustBottomLine(newLabel: newLabel, oldLabel: oldLabel) adjustScale(newLabel: newLabel, oldLabel: oldLabel) adjustPosition(newLabel) adjustCover(newLabel: newLabel) delegate?.titleView(titleView: self, currentIndex: currentIndex) } fileprivate func adjustCover(newLabel: UILabel){ if style.isShowCoverView { let coverW = style.isScrollEnable ? (newLabel.frame.width + style.titleMargin) : (newLabel.frame.width - 2 * style.coverMargin) UIView .animate(withDuration: 0.2, animations: { self.coverView.frame.size.width = coverW self.coverView.center = newLabel.center }) } } fileprivate func adjustBottomLine(newLabel: UILabel, oldLabel: UILabel) { if style.isShowBottomLine { let deltaX = newLabel.frame.origin.x - oldLabel.frame.origin.x let deltaW = newLabel.frame.width - oldLabel.frame.width UIView.animate(withDuration: 0.2, animations: { self.bottomLine.frame.origin.x = oldLabel.frame.origin.x + deltaX self.bottomLine.frame.size.width = oldLabel.frame.width + deltaW }) } } fileprivate func adjustScale(newLabel: UILabel, oldLabel:UILabel) { if style.isTitleScale { UIView.animate(withDuration: 0.2, animations: { newLabel.transform = oldLabel.transform oldLabel.transform = CGAffineTransform.identity }) } } func adjustPosition(_ newLabel : UILabel) { guard style.isScrollEnable else { return } var offsetX = newLabel.center.x - scrollView.bounds.width * 0.5 if offsetX < 0 { offsetX = 0 } let maxOffset = scrollView.contentSize.width - bounds.width if offsetX > maxOffset { offsetX = maxOffset } scrollView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: true) } } //MARK: - SCContentViewDelegate extension SCTitleView : SCContentViewDelegate { func contentView(contentView: SCContentView, inIndex: Int) { titleViewChange(inIndex: inIndex) } func titleViewChange(inIndex: Int) { guard inIndex != currentIndex else { return } let oldLabel = titleLabels[currentIndex] let newLabel = titleLabels[inIndex] oldLabel.textColor = style.normalColor newLabel.textColor = style.selectColor currentIndex = inIndex adjustBottomLine(newLabel: newLabel, oldLabel: oldLabel) adjustScale(newLabel: newLabel, oldLabel: oldLabel) adjustPosition(newLabel) adjustCover(newLabel: newLabel) } }
// // Item.swift // TodoNow // // Created by Lucas Dahl on 11/24/18. // Copyright © 2018 Lucas Dahl. All rights reserved. // import Foundation import RealmSwift class Item: Object { // Properties @objc dynamic var title = "" @objc dynamic var done = false @objc dynamic var dateCreated:Date? // Make the link(relationship) var parentCategory = LinkingObjects(fromType: Category.self, property: "items") }
// // CommodityUnitService.swift // FarmLeadTest // // Created by Yeral Yamil Castillo on 8/13/16. // Copyright © 2016 Yeral Yamil Castillo. All rights reserved. // import Foundation import Alamofire import SwiftyJSON class CommodityUnitService{ private static var cachedCommodityUnitArray : [CommodityUnit]? var parser : CommodityUnitParser init(parser: CommodityUnitParser = CommodityUnitParser()){ self.parser = parser } func requestCommodityUnitList(onResponse: ((response: [CommodityUnit]) -> Void)? = nil){ //if the results is cached if let commodityUnitArray = CommodityUnitService.cachedCommodityUnitArray{ if let onResponseUnwrapped = onResponse{ onResponseUnwrapped(response: commodityUnitArray) return } } let apiConstants = APIConstants.sharedInstance let headers = ["content-type": "application/json"] let parameters = ["data": [apiConstants.commodityUnitParameterName: apiConstants.commodityUnitParameterValue]] Alamofire.request(.POST, apiConstants.commodityUnitEndPoint, parameters: parameters, encoding: .JSON, headers: headers).responseJSON{ response in guard let json = response.result.value else { NSLog("Error parsing CommodityUnit") return } guard let commodityUnitArray = self.parser.parse(JSON(json)) else { NSLog("Error parsing CommodityUnit from Json") return } CommodityUnitService.cachedCommodityUnitArray = commodityUnitArray if let onResponseUnwrapped = onResponse{ onResponseUnwrapped(response: commodityUnitArray) } } } }
// // FooGeneric.swift // Foo // // Created by Stijn Willems on 27/06/2019. // import Foundation // sourcery:begin:AutoGenerateProtocol, mockAnnotations = "generic="M: Codable & Equatable"", generic="M: Codable & Equatable" public struct FooGeneric<M: Codable & Equatable> { var codeAndEquate: M }
import UIKit //클로저 -> 코드에서 전달 및 사용할 수 있는 독립 기능 블록이며, 일급 객체의 역할을 할 수 있음 ( 익명함수 ) //일급객체 -> 전달 인자로 보낼 수 있고, 변수/상수 등으로 저장하거나 전달할 수있으며 함수의 반환 값이 될 수도 있다. /* { (매개 변수) -> 리턴 타입 in 실행 구문 } */ let hello = { () -> () in print("hello") } hello() let hello2 = { (name: String) -> String in return "Hello, \(name)" } // hello2(name: "SangAu") -> error 클로저에서 전달인자 레이블을 적으면 오류가 난다. hello2("SangAu") func doSomthing(closure: () -> ()){ closure() } doSomthing(closure: { () -> () in print("hello") }) //위 코드를 축약하면 doSomthing() { print("Hello2") } //매개변수가 하나면 소괄호도 안써도댐 doSomthing { print("Hello2") } func doSomthing2() -> () -> () { return { () -> () in print("Hello4") } } doSomthing2()() func doSomething2(success: () -> (), fail: () -> ()){ } doSomething2 { <#code#> } fail: { <#code#> } func doSomthing3(closure: (Int, Int, Int) -> Int){ closure(1, 2, 3) } doSomthing3(closure: { (a, b, c) in return a + b + c }) doSomthing3(closure: { // 파라미터의 데이터 타입 생략가능 return $0 + $1 + $2 }) doSomthing3(closure: { // return문만 있을시 리턴 생략 가능 $0 + $1 + $2 }) doSomthing3() { $0 + $1 + $2 } doSomthing3{ // 하나의 클로저만 매개변수ㅗ 전달하면 ()도 생략가능 $0 + $1 + $2 }
// // Post.swift // VKClone // // Created by Петр on 04/11/2018. // Copyright © 2018 DreamTeam. All rights reserved. // import Foundation // Post model class Post: NSObject, NSCoding { // Uniq post identifier @objc var id: String // Group title @objc var groupName: String // Group avatar (picture) @objc var groupAvatar: String // Date of news posting @objc var postDate: String // News text @objc var postText: String // Attached image @objc var postImageLink: String // How many likes @objc var likesCount: Int // How many comments @objc var commentsCount: Int // How many watchers @objc var viewsCount: Int init(id: String, groupName: String, groupAvatar: String, postDate: String, postText: String, postImageLink: String, likesCount: Int, commentsCount: Int, viewsCount: Int) { self.id = id self.groupName = groupName self.groupAvatar = groupAvatar self.postDate = postDate self.postText = postText self.postImageLink = postImageLink self.likesCount = likesCount self.commentsCount = commentsCount self.viewsCount = viewsCount } func encode(with aCoder: NSCoder) { aCoder.encode(id, forKey: #keyPath(Post.id)) aCoder.encode(groupAvatar, forKey: #keyPath(Post.groupAvatar)) aCoder.encode(groupName, forKey: #keyPath(Post.groupName)) aCoder.encode(postDate, forKey: #keyPath(Post.postDate)) aCoder.encode(postText, forKey: #keyPath(Post.postText)) aCoder.encode(postImageLink, forKey: #keyPath(Post.postImageLink)) aCoder.encode(likesCount, forKey: #keyPath(Post.likesCount)) aCoder.encode(commentsCount, forKey: #keyPath(Post.commentsCount)) aCoder.encode(viewsCount, forKey: #keyPath(Post.viewsCount)) } required init?(coder aDecoder: NSCoder) { id = aDecoder.decodeObject(forKey: #keyPath(Post.id)) as? String ?? "" groupName = aDecoder.decodeObject(forKey: #keyPath(Post.groupName)) as? String ?? "" groupAvatar = aDecoder.decodeObject(forKey: #keyPath(Post.groupAvatar)) as? String ?? "" postDate = aDecoder.decodeObject(forKey: #keyPath(Post.postDate)) as? String ?? "" postText = aDecoder.decodeObject(forKey: #keyPath(Post.postText)) as? String ?? "" postImageLink = aDecoder.decodeObject(forKey: #keyPath(Post.postImageLink)) as? String ?? "" likesCount = aDecoder.decodeInteger(forKey: #keyPath(Post.likesCount)) commentsCount = aDecoder.decodeInteger(forKey: #keyPath(Post.commentsCount)) viewsCount = aDecoder.decodeInteger(forKey: #keyPath(Post.viewsCount)) } }
// // CategoryCell.swift // testingArea // // Created by Quast, Malte on 10.11.17. // Copyright © 2017 Quast, Malte. All rights reserved. // import UIKit //definiert die einzelne Zelle in TableView //updateviews notwendig um bilder neu zu laden bei scrollen??? class CategoryCell: UITableViewCell { @IBOutlet weak var categoryImage: UIImageView! @IBOutlet weak var categoryTitle: UILabel! func updateViews(category: Category){ categoryImage.image = UIImage(named: category.imageName) categoryTitle.text = category.title } }
// // ProfileViewController.swift // HugoTwitter // // Created by Hieu Nguyen on 2/26/16. // Copyright © 2016 Hugo Nguyen. All rights reserved. // import UIKit import FXBlurView class ProfileViewController: UIViewController, TweetsViewControllerDelegate, UIGestureRecognizerDelegate, ComposeViewControllerDelegate { @IBOutlet weak var containerView: UIView! @IBOutlet weak var contentView: UIView! @IBOutlet weak var headerView: UIView! @IBOutlet weak var headerBackground: UIView! @IBOutlet weak var profileImageView: UIImageView! @IBOutlet weak var navNameLabel: UILabel! @IBOutlet weak var navSublabel: UILabel! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var screenNameLabel: UILabel! @IBOutlet weak var followingCountLabel: UILabel! @IBOutlet weak var followingLabel: UILabel! @IBOutlet weak var followerCountLabel: UILabel! @IBOutlet weak var followerLabel: UILabel! @IBOutlet weak var segmentedControl: UISegmentedControl! @IBOutlet weak var profileImageTopMargin: NSLayoutConstraint! @IBOutlet weak var headerImageView:UIImageView! @IBOutlet weak var blurredHeaderImageView: UIImageView! @IBOutlet weak var lineHeightConstraint: NSLayoutConstraint! var offsetHeaderViewStop: CGFloat! var offsetHeader: CGFloat? var offsetHeaderBackgroundViewStop: CGFloat! var offsetNavLabelViewStop: CGFloat! var viewControllers: [UIViewController] = [] var selectedViewController: UIViewController? var pan: UIPanGestureRecognizer! var navHeight: CGFloat! var screenName: String? var userId: String? var user: User? var profileEndpoint: ((screenName: String?, userId: String?, params: NSDictionary?, completion: (user: User?, error: NSError?) -> ()) -> ())? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. segmentedControl.addTarget(self, action: "onTabChanged:", forControlEvents: UIControlEvents.ValueChanged) segmentedControl.tintColor = twitterColor segmentedControl.setTitle("Tweets", forSegmentAtIndex: 0) segmentedControl.setTitle("Likes", forSegmentAtIndex: 1) var params = NSMutableDictionary() if screenName != nil { params.setValue(screenName!, forKey: "screen_name") } else if userId != nil { params.setValue(userId!, forKey: "user_id") } let storyboard = UIStoryboard(name: "TweetsViewController", bundle: nil) let tweetsViewController = storyboard.instantiateViewControllerWithIdentifier("TweetsViewController") as! TweetsViewController tweetsViewController.isStandaloneController = false tweetsViewController.params = params tweetsViewController.tweetsEndpoint = TwitterClient.sharedInstance.userTweets tweetsViewController.delegate = self tweetsViewController.contentInsetHeight = headerView.frame.size.height tweetsViewController.view.layoutIfNeeded() let likesViewController = storyboard.instantiateViewControllerWithIdentifier("TweetsViewController") as! TweetsViewController likesViewController.isStandaloneController = false likesViewController.params = params likesViewController.tweetsEndpoint = TwitterClient.sharedInstance.userLikes likesViewController.delegate = self likesViewController.contentInsetHeight = headerView.frame.size.height likesViewController.view.layoutIfNeeded() viewControllers.append(tweetsViewController) viewControllers.append(likesViewController) // Initial Tab selectViewController(viewControllers[0]) navHeight = navigationController!.navigationBar.frame.size.height + navigationController!.navigationBar.frame.origin.y offsetHeaderViewStop = segmentedControl.frame.origin.y - navHeight - 8 offsetHeaderBackgroundViewStop = (headerBackground.frame.size.height + headerBackground.frame.origin.y) - navHeight offsetNavLabelViewStop = navNameLabel.frame.origin.y - (navHeight / 2) + 8 headerBackground.clipsToBounds = true lineHeightConstraint.constant = 1 / UIScreen.mainScreen().scale profileImageView.layer.cornerRadius = 10 profileImageView.clipsToBounds = true profileImageView.layer.borderColor = UIColor.whiteColor().CGColor profileImageView.layer.borderWidth = 4.0 profileImageTopMargin.constant = navHeight + 4.0 profileImageView.layer.zPosition = 1 let border = CAShapeLayer() let uiBezierPath = UIBezierPath.bezierPathByReversingPath(UIBezierPath(roundedRect: profileImageView.bounds, cornerRadius: self.profileImageView.layer.cornerRadius)) border.path = uiBezierPath().CGPath border.strokeColor = UIColor.whiteColor().CGColor border.fillColor = UIColor.clearColor().CGColor profileImageView.layer.addSublayer(border) pan = UIPanGestureRecognizer(target: self, action: Selector("onPanGesture:")) pan.delegate = self //headerView.addGestureRecognizer(pan) profileEndpoint?(screenName: screenName, userId: userId, params: nil, completion: { (user, error) -> () in if user != nil { self.loadViewWithUser(user!) } }) } override func viewWillAppear(animated: Bool) { setupNavBar() } override func viewWillDisappear(animated: Bool) { navigationController!.navigationBar.setBackgroundImage(nil, forBarMetrics: UIBarMetrics.Default) navigationController!.navigationBar.tintColor = twitterColor } func setupNavBar() { navigationController!.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: UIBarMetrics.Default) navigationController!.navigationBar.shadowImage = UIImage() navigationController!.navigationBar.translucent = true; navigationController!.view.backgroundColor = UIColor.clearColor() navigationController!.navigationBar.backgroundColor = UIColor.clearColor() let negativeSpacer = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FixedSpace, target: nil, action: nil) negativeSpacer.width = -10 let rightBtn = UIButton(type: .System) rightBtn.frame = CGRectMake(0, 0, 30, 30); let composeImage = UIImage(named: "icon_compose") rightBtn.setImage(composeImage!.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate), forState: UIControlState.Normal) rightBtn.tintColor = UIColor.whiteColor() rightBtn.addTarget(self, action: "onCompose", forControlEvents: UIControlEvents.TouchUpInside) let rightBarBtn = UIBarButtonItem(customView: rightBtn) navigationItem.rightBarButtonItems = [negativeSpacer, rightBarBtn] setupNavigationForBackBtn() } func loadViewWithUser(user: User!) { self.user = user nameLabel.text = user.name! navNameLabel.text = user.name! screenNameLabel.text = "@\(user.screenname!)" followingCountLabel.text = "\(user.followingCount!.prettify())" followerCountLabel.text = "\(user.followersCount!.prettify())" if segmentedControl.selectedSegmentIndex == 0 { navSublabel.text = "\(self.user!.tweetsCount!.prettify()) Tweets" } else { navSublabel.text = "\(self.user!.likesCount!.prettify()) Likes" } loadLowResThenHighResImg(profileImageView, smallImageUrl: user.profileImageLowResUrl!, largeImageUrl: user.profileImageUrl!, duration: 1.0) //fadeInImg(headerImageView, imageUrl: user.profileBackgroundImageUrl!, duration: 1.0) headerImageView.setImageWithURLRequest(NSURLRequest(URL: NSURL(string: user.profileBackgroundImageUrl!)!), placeholderImage: nil, success: { (request, response, image) -> Void in self.headerImageView.image = image self.blurredHeaderImageView.image = image.blurredImageWithRadius(10, iterations: 20, tintColor: UIColor.clearColor()) self.blurredHeaderImageView.alpha = 0.0 }) { (request, response, error) -> Void in print(error.debugDescription) } } func selectViewController(viewController: UIViewController) { var contentOffset: CGPoint? if let oldViewController = selectedViewController { if oldViewController.isKindOfClass(TweetsViewController.classForCoder()) { let oldTweetsVC = oldViewController as! TweetsViewController contentOffset = oldTweetsVC.tableView.contentOffset } oldViewController.willMoveToParentViewController(nil) oldViewController.view.removeFromSuperview() oldViewController.removeFromParentViewController() } self.addChildViewController(viewController) viewController.view.frame = self.contentView.bounds viewController.view.autoresizingMask = [.FlexibleWidth, .FlexibleHeight] self.contentView.addSubview(viewController.view) viewController.didMoveToParentViewController(self) selectedViewController = viewController if contentOffset != nil && viewController.isKindOfClass(TweetsViewController.classForCoder()) { let newTweetsVC = viewController as! TweetsViewController let currFrameOffset = min(contentOffset!.y, headerView.frame.size.height) let newFrameOffset = min(newTweetsVC.tableView.contentOffset.y, headerView.frame.size.height) if newFrameOffset != currFrameOffset { newTweetsVC.tableView.setContentOffset(CGPoint(x: 0, y: currFrameOffset), animated: false) } } } func onTabChanged(sender: UISegmentedControl) { let selectedSegment = sender.selectedSegmentIndex selectViewController(viewControllers[selectedSegment]) if self.user != nil { if selectedSegment == 0 { navSublabel.text = "\(self.user!.tweetsCount!.prettify()) Tweets" } else { navSublabel.text = "\(self.user!.likesCount!.prettify()) Likes" } } } var startPoint: CGPoint! func onPanGesture(gesture: UIPanGestureRecognizer) { let translation = gesture.translationInView(gesture.view) if gesture.state == UIGestureRecognizerState.Changed { // let tweetsVC = viewControllers[0] as! TweetsViewController // tweetsVC.tableView.contentOffset = CGPoint(x: 0, y: -translation.y) var scrollInfo: [NSObject : AnyObject] = [:] scrollInfo[ScrollNotificationKey] = -translation.y NSNotificationCenter.defaultCenter().postNotificationName(ScrollNotification, object: self, userInfo: scrollInfo) } } var initialOffset: CGFloat? = nil func tweetsViewOnScroll(scrollView: UIScrollView) { if initialOffset == nil { initialOffset = scrollView.contentOffset.y } let offset = scrollView.contentOffset.y - initialOffset! offsetHeader = max(-offsetHeaderViewStop, -offset) var headerTransform = CATransform3DIdentity headerTransform = CATransform3DTranslate(headerTransform, 0, offsetHeader!, 0) headerView.layer.transform = headerTransform var headerBackgroundTransform = CATransform3DIdentity if offset < 0 { let headerImageScaleFactor = (-offset) / headerBackground.bounds.height let headerImageHeightChanged = headerImageScaleFactor * headerBackground.bounds.height / 2.0 headerBackgroundTransform = CATransform3DTranslate(headerBackgroundTransform, 0, headerImageHeightChanged, 0) headerBackgroundTransform = CATransform3DScale(headerBackgroundTransform, 1.0 + headerImageScaleFactor, 1.0 + headerImageScaleFactor, 0) //print ("scale delta = \(headerImageScaleFactor) ; height delta = \(headerImageHeightChanged)") } else { headerBackgroundTransform = CATransform3DTranslate(headerBackgroundTransform, 0, max(-offsetHeaderBackgroundViewStop, -offset), 0) } headerBackground.layer.transform = headerBackgroundTransform if offset < 0 { blurredHeaderImageView.alpha = min(1.0, fabs(offset/offsetHeaderBackgroundViewStop)) } else { blurredHeaderImageView.alpha = min(1.0, (offset - offsetHeaderBackgroundViewStop) / offsetNavLabelViewStop) } let labelTransform = CATransform3DMakeTranslation(0, max(-offsetNavLabelViewStop, -offset), 0) navNameLabel.layer.transform = labelTransform navSublabel.layer.transform = labelTransform var avatarTransform = CATransform3DIdentity if offset < 0 { // pull down avatarTransform = CATransform3DTranslate(avatarTransform, 0, -offset, 0) } else { let avatarScaleFactor = (min(offsetHeaderBackgroundViewStop, offset)) / profileImageView.bounds.height / 1.4 // Slow down the animation let avatarHeightChanged = profileImageView.bounds.height * avatarScaleFactor avatarTransform = CATransform3DScale(avatarTransform, 1.0 - avatarScaleFactor, 1.0 - avatarScaleFactor, 0) var avatarYTranslation = avatarHeightChanged if offset > offsetHeaderBackgroundViewStop { avatarYTranslation += (offset - offsetHeaderBackgroundViewStop) * 1.5 } avatarTransform = CATransform3DTranslate(avatarTransform, 0, -avatarYTranslation, 0) //print("-avatarYTranslation \(-avatarYTranslation) ; scaleFactor = \(avatarScaleFactor)") } profileImageView.layer.transform = avatarTransform if offset <= offsetHeaderBackgroundViewStop { if profileImageView.layer.zPosition < headerBackground.layer.zPosition{ headerBackground.layer.zPosition = profileImageView.layer.zPosition - 1 navNameLabel.layer.zPosition = headerBackground.layer.zPosition navSublabel.layer.zPosition = headerBackground.layer.zPosition } } else { if profileImageView.layer.zPosition >= headerBackground.layer.zPosition{ headerBackground.layer.zPosition = profileImageView.layer.zPosition + 1 navNameLabel.layer.zPosition = headerBackground.layer.zPosition + 1 navSublabel.layer.zPosition = headerBackground.layer.zPosition + 1 } } } func setupNavigationForBackBtn() { if navigationController == nil { return } let stackCount = navigationController!.viewControllers.count - 2 if stackCount >= 0 { navigationController!.navigationBar.tintColor = UIColor.whiteColor() } } func onCompose() { let composeVC = ComposeViewController() composeVC.delegate = self composeVC.user = User.currentUser navigationController?.presentViewController(composeVC, animated: true, completion: nil) } func onComposeViewClosed(composeViewController: ComposeViewController, tweetStatus: String!) { dismissViewControllerAnimated(true, completion: nil) } func onTweetSend(composeViewController: ComposeViewController, tweetStatus: String!, replyToTweet: Tweet?) { dismissViewControllerAnimated(true, completion: nil) var params = ["status": tweetStatus] if replyToTweet != nil { params["in_reply_to_status_id"] = replyToTweet!.id! } TwitterClient.sharedInstance.updateStatus(params as! NSDictionary) { (tweet, error) -> () in var tweetComposedInfo: [NSObject : AnyObject] = [:] tweetComposedInfo[TweetComposeNotificationKey] = tweet NSNotificationCenter.defaultCenter().postNotificationName(TweetComposeNotification, object: self, userInfo: tweetComposedInfo) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
// // PostListViewModel.swift // Healios_IOS_Test // // Created by Neosoft on 31/07/21. // import Foundation import Alamofire_SwiftyJSON import SwiftyJSON class PostListViewModel { private var arrPostList = [PostModel]() private lazy var postListServices: PostListServices = { return PostListServices() }() internal func loadPost(completion: @escaping (Bool,String) -> Void) { let myjson = self.retrieveFromJsonFile() if myjson.count > 0 { self.mapData(myjson: myjson) completion(true, "success") } else { postListServices.getPostData(success: { (json) in //PARSE DATA. self.saveToJsonFile(json: json) let myjson = self.retrieveFromJsonFile() self.mapData(myjson: myjson) completion(true, "success") }, failure: { (error) in print(error) completion(false, error.localizedDescription) }) } } } extension PostListViewModel { func getPostCount() -> Int { return self.arrPostList.count } func getPostAt(index:Int) -> PostModel { return self.arrPostList[index] } } //Local Data extension PostListViewModel { func mapData(myjson : JSON) { for value in myjson.arrayValue { let body = value.dictionaryValue["body"]!.stringValue let id = value.dictionaryValue["id"]!.intValue let title = value.dictionaryValue["title"]!.stringValue let userId = value.dictionaryValue["userId"]!.intValue let data = PostModel(body: body, id: id, title: title, userId: userId) self.arrPostList.append(data) } } func saveToJsonFile(json: JSON) { // Get the url of Persons.json in document directory guard let documentDirectoryUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return } let fileUrl = documentDirectoryUrl.appendingPathComponent("Posts.json") // Transform array into data and save it into file if let data = try? json.rawData() { try? data.write(to: fileUrl) } } func retrieveFromJsonFile() -> JSON { // Get the url of Persons.json in document directory guard let documentsDirectoryUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return nil} let fileUrl = documentsDirectoryUrl.appendingPathComponent("Posts.json") // Read data from .json file and transform data into an array do { let data = try Data(contentsOf: fileUrl, options: []) if let json = try? JSON(data: data as Data) { print(json) return json } } catch { print(error) } return nil } }
// // WebView.swift // PdfTranslate // // Created by Viktor Kushnerov on 9/9/19. // Copyright © 2019 Viktor Kushnerov. All rights reserved. // import Combine import SwiftUI import WebKit struct GTranslatorRepresenter: ViewRepresentable, WKScriptsSetup { @Binding var selectedText: TranslateAction static var isMiniMode: Bool = false { didSet { setMiniMode() } } static var pageView: WKPageView? @ObservedObject private var store = Store.shared private let defaultURL = "https://translate.google.com?op=translate&sl=auto&tl=ru" func makeCoordinator() -> WKCoordinator { WKCoordinator(self, currentView: .gTranslator) } func makeView(context: Context) -> WKPageView { if let view = Self.pageView { return view } let view = WKPageView() view.load(urlString: defaultURL) Self.pageView = view setupScriptCoordinator(view: view, coordinator: context.coordinator) setupScript(view: view, file: "gtranslator-reverso-speaker") setupScript(view: view, file: "gtranslator") Self.setMiniMode() return view } func updateView(_ view: WKPageView, context _: Context) { if case let .gTranslator(text) = selectedText { Store.shared.translateAction.next() print("\(theClassName)_updateView_update", text) let (slValue, tlValue) = getParams(url: view.url) guard var urlComponent = URLComponents(string: defaultURL) else { return } urlComponent.queryItems = [ .init(name: "op", value: "translate"), .init(name: "sl", value: slValue), .init(name: "tl", value: tlValue), .init(name: "text", value: text) ] if let url = urlComponent.url { print("\(Self.self)_updateView_reload", url) DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { view.load(URLRequest(url: url)) } } } } private func getParams(url: URL?) -> (String?, String?) { let lastUrl = url?.absoluteString.replacingOccurrences(of: "#view=home", with: "") let url = lastUrl ?? defaultURL guard let urlComponent = URLComponents(string: url) else { return (nil, nil) } let queryItems = urlComponent.queryItems let slValue = queryItems?.last(where: { $0.name == "sl" })?.value let tlValue = queryItems?.last(where: { $0.name == "tl" })?.value return (slValue, tlValue) } static private func setMiniMode() { let mode = isMiniMode ? "mini" : "full" GTranslatorRepresenter.pageView?.evaluateJavaScript("readerTranslatorMode('\(mode)')") } }
// // DayBtConverterView.swift // animalHealthLog // // Created by 細川聖矢 on 2020/06/09. // Copyright © 2020 Seiya. All rights reserved. // import SwiftUI import CoreData struct DayBtConverterView: View { @State private var dayBtSelection = 0 init(){ UISegmentedControl.appearance().selectedSegmentTintColor = .gYellow UISegmentedControl.appearance().setTitleTextAttributes([.foregroundColor:UIColor.white],for:.selected) UISegmentedControl.appearance().setTitleTextAttributes([.foregroundColor:UIColor.gYellow],for:.normal) } @Environment(\.managedObjectContext) var managedObjectContext var body: some View { VStack{ HeaderView(headerColor: .gYellow, headerMenu: "検査結果") Picker(selection: $dayBtSelection, label: Text("")){ Text("血液検査").tag(0) Text("画像").tag(1) Text("日付別").tag(2) Text("メモ").tag(3) }//Pickerの閉じ .pickerStyle(SegmentedPickerStyle()) if dayBtSelection == 0{ BtResultCollection() }else if dayBtSelection == 1{ SavingImageView().environment(\.managedObjectContext, (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext) } else if dayBtSelection == 2{ DayListButtonView() } // DayListResultView() else if dayBtSelection == 3{ MemoListView().environment(\.managedObjectContext, (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext) } else{ Text("error") } }//VStack } } struct DayBtConverterView_Previews: PreviewProvider { static var previews: some View { DayBtConverterView() } }
@testable import SwiftDependencyManagerKit import XCTest class ManifestTests: XCTestCase { func testInitWithFileContents() { let manifestContents: String = """ [[dependencies]] name = "HandySwift" gitPath = "https://github.com/Flinesoft/HandySwift.git" version = "any" [[dependencies]] name = "HandyUIKit" gitPath = "https://github.com/Flinesoft/HandyUIKit.git" version = "upToNextMajor:1.8.0" """ if let manifest = mungo.make({ try Manifest(fileContents: manifestContents) }) { XCTAssertEqual(manifest.products.count, 0) XCTAssertEqual(manifest.dependencies.count, 2) XCTAssertEqual(manifest.dependencies[0].name, "HandySwift") XCTAssertEqual(manifest.dependencies[0].gitPath, "https://github.com/Flinesoft/HandySwift.git") XCTAssertEqual(manifest.dependencies[0].version, .any) XCTAssertEqual(manifest.dependencies[1].name, "HandyUIKit") XCTAssertEqual(manifest.dependencies[1].gitPath, "https://github.com/Flinesoft/HandyUIKit.git") XCTAssertEqual(manifest.dependencies[1].version, .upToNextMajor("1.8.0")) } } func testInitSimpleFrameworkManifest() { let manifestContents: String = """ [[products]] name = "CSVImporter" [[dependencies]] name = "HandySwift" gitPath = "https://github.com/Flinesoft/HandySwift.git" version = "commit:0000000000000000000000000000000000000000" [[dependencies]] name = "HandyUIKit" gitPath = "https://github.com/Flinesoft/HandyUIKit.git" version = "minimumVersion:1.4.4" """ if let manifest = mungo.make({ try Manifest(fileContents: manifestContents) }) { XCTAssertEqual(manifest.products.count, 1) XCTAssertEqual(manifest.dependencies.count, 2) XCTAssertEqual(manifest.products[0].name, "CSVImporter") XCTAssertEqual(manifest.products[0].paths, nil) XCTAssertEqual(manifest.products[0].dependencies, nil) XCTAssertEqual(manifest.dependencies[0].name, "HandySwift") XCTAssertEqual(manifest.dependencies[0].gitPath, "https://github.com/Flinesoft/HandySwift.git") XCTAssertEqual(manifest.dependencies[0].version, .commit("0000000000000000000000000000000000000000")) XCTAssertEqual(manifest.dependencies[1].name, "HandyUIKit") XCTAssertEqual(manifest.dependencies[1].gitPath, "https://github.com/Flinesoft/HandyUIKit.git") XCTAssertEqual(manifest.dependencies[1].version, .minimumVersion("1.4.4")) } } func testMakeKitFrameworkManifest() { let manifestContents: String = """ [[products]] name = "CSVImporter" paths = ["Sources/CSVImporter"] dependencies = ["CSVImporterKit"] [[products]] name = "CSVImporterKit" paths = ["Sources/CSVImporterKit"] dependencies = ["HandySwift", "HandyUIKit"] [[dependencies]] name = "HandySwift" gitPath = "https://github.com/Flinesoft/HandySwift.git" version = "branch:master" [[dependencies]] name = "HandyUIKit" gitPath = "https://github.com/Flinesoft/HandyUIKit.git" version = "exactVersion:1.9.1" """ if let manifest = mungo.make({ try Manifest(fileContents: manifestContents) }) { XCTAssertEqual(manifest.products.count, 2) XCTAssertEqual(manifest.dependencies.count, 2) XCTAssertEqual(manifest.products[0].name, "CSVImporter") XCTAssertEqual(manifest.products[0].paths, ["Sources/CSVImporter"]) XCTAssertEqual(manifest.products[0].dependencies, ["CSVImporterKit"]) XCTAssertEqual(manifest.products[1].name, "CSVImporterKit") XCTAssertEqual(manifest.products[1].paths, ["Sources/CSVImporterKit"]) XCTAssertEqual(manifest.products[1].dependencies, ["HandySwift", "HandyUIKit"]) XCTAssertEqual(manifest.dependencies[0].name, "HandySwift") XCTAssertEqual(manifest.dependencies[0].gitPath, "https://github.com/Flinesoft/HandySwift.git") XCTAssertEqual(manifest.dependencies[0].version, .branch("master")) XCTAssertEqual(manifest.dependencies[1].name, "HandyUIKit") XCTAssertEqual(manifest.dependencies[1].gitPath, "https://github.com/Flinesoft/HandyUIKit.git") XCTAssertEqual(manifest.dependencies[1].version, .exactVersion("1.9.1")) } } func testFileContentsAppManifest() { let manifestContents: String = """ [[dependencies]] name = "HandySwift" gitPath = "https://github.com/Flinesoft/HandySwift.git" version = "any" [[dependencies]] name = "HandyUIKit" gitPath = "https://github.com/Flinesoft/HandyUIKit.git" version = "upToNextMajor:1.8.0" """ if let manifest = mungo.make({ try Manifest(fileContents: manifestContents) }) { XCTAssertEqual(manifest.toFileContents(), manifestContents) } } func testFileContentsSimpleFrameworkManifest() { let manifestContents: String = """ [[products]] name = "CSVImporter" [[dependencies]] name = "HandySwift" gitPath = "https://github.com/Flinesoft/HandySwift.git" version = "commit:0000000000000000000000000000000000000000" [[dependencies]] name = "HandyUIKit" gitPath = "https://github.com/Flinesoft/HandyUIKit.git" version = "minimumVersion:1.4.4" """ if let manifest = mungo.make({ try Manifest(fileContents: manifestContents) }) { XCTAssertEqual(manifest.toFileContents(), manifestContents) } } func testFileContentsKitFrameworkManifest() { let manifestContents: String = """ [[products]] name = "CSVImporter" paths = ["Sources/CSVImporter"] dependencies = ["CSVImporterKit"] [[products]] name = "CSVImporterKit" paths = ["Sources/CSVImporterKit"] dependencies = ["HandySwift", "HandyUIKit"] [[dependencies]] name = "HandySwift" gitPath = "https://github.com/Flinesoft/HandySwift.git" version = "branch:master" [[dependencies]] name = "HandyUIKit" gitPath = "https://github.com/Flinesoft/HandyUIKit.git" version = "exactVersion:1.9.1" """ if let manifest = mungo.make({ try Manifest(fileContents: manifestContents) }) { XCTAssertEqual(manifest.toFileContents(), manifestContents) } } }
import UIKit class TimelineAPI:NSObject{ //先頭の10件 func latest() -> Timelines{ //let temp = jToCForTimeline("") let temp = DummyTimelines() let result = Timelines() for (index, one) in temp.all().enumerate(){ if (index < 10){ let temp:Timeline = Timeline() temp.setData(one.text) for (image) in one.allImages(){ temp.addImage(image.imageName) } result.addTimeline(temp) } else { break; } } return result } //次の10件 func next(prevLastNo:String) -> Timelines{ //let temp = jToCForTimeline("") let temp = DummyTimelines() let result = Timelines() var before = Timeline() var isSkip = true for one in temp.all(){ if (before.contentNo == prevLastNo){ isSkip = false } if (!isSkip){ result.addTimeline(one) } before = one } return result } //日付で検索→後で func findByDate(){ } //タイムラインNOで検索→後で func findByContentsNo(){ } //新規登録→後で func new(){ } //削除→後で func remove(){ } //記事修正→後で func override(){ } //JSONをClass(Timelines)に変換する func jToCForTimeline(json:String)->Timelines{ return Timelines() } func DummyTimelines() -> Timelines{ let result = Timelines() let closure = {(text:String, imageName:String)->(Void) in let one = Timeline() one.setData(text) one.addImage(imageName) result.addTimeline(one) } var i=0 i=i+1;closure(String(i) + "つ目の本文", "neko") i=i+1;closure(String(i) + "つ目の本文", "2footcat_180.jpg") i=i+1;closure(String(i) + "つ目の本文", "neko") i=i+1;closure(String(i) + "つ目の本文", "2footcat_180.jpg") i=i+1;closure(String(i) + "つ目の本文", "neko") i=i+1;closure(String(i) + "つ目の本文", "neko") i=i+1;closure(String(i) + "つ目の本文", "neko") i=i+1;closure(String(i) + "つ目の本文", "neko") i=i+1;closure(String(i) + "つ目の本文", "neko") i=i+1;closure(String(i) + "つ目の本文", "neko") i=i+1;closure(String(i) + "つ目の本文", "neko") i=i+1;closure(String(i) + "つ目の本文", "neko") i=i+1;closure(String(i) + "つ目の本文", "neko") i=i+1;closure(String(i) + "つ目の本文", "neko") i=i+1;closure(String(i) + "つ目の本文", "neko") i=i+1;closure(String(i) + "つ目の本文", "neko") i=i+1;closure(String(i) + "つ目の本文", "neko") i=i+1;closure(String(i) + "つ目の本文", "neko") i=i+1;closure(String(i) + "つ目の本文", "neko") i=i+1;closure(String(i) + "つ目の本文", "neko") i=i+1;closure(String(i) + "つ目の本文", "neko") i=i+1;closure(String(i) + "つ目の本文", "neko") i=i+1;closure(String(i) + "つ目の本文", "neko") i=i+1;closure(String(i) + "つ目の本文", "neko") i=i+1;closure(String(i) + "つ目の本文", "neko") i=i+1;closure(String(i) + "つ目の本文", "neko") i=i+1;closure(String(i) + "つ目の本文", "neko") i=i+1;closure(String(i) + "つ目の本文", "neko") return result } }
// // MultiAppViewModel.swift // LearnMath // // Created by varmabhupatiraju on 5/15/17. // Copyright © 2017 StellentSoft. All rights reserved. // import Foundation import UIKit import AudioToolbox class MultiAppViewModel{ var multiAppVCDelegate:MultiAppViewController! // Custom method for the images design and the buttons creation and also set the frames for views. func initialloading() { multiAppVCDelegate.alertPopOverView.isHidden = true multiAppVCDelegate.animationView.isHidden = true for index in 0...2 { //var imageData:Data! let imageData = try! Data(contentsOf: Bundle.main.url(forResource: Constant.gifsArray[index], withExtension: "gif")!) multiAppVCDelegate.gifImagesArray.append(imageData) } // Adding frame for the pagecontrol initially multiAppVCDelegate.pageControl.frame = CGRect(x: multiAppVCDelegate.pageControl.frame.origin.x, y: multiAppVCDelegate.applyFactsLbl.frame.origin.y+multiAppVCDelegate.applyFactsLbl.frame.size.height+5, width: multiAppVCDelegate.pageControl.frame.size.width, height: 5) multiAppVCDelegate.isRandom = true if DeviceModel.IS_IPHONE_4_OR_LESS { multiAppVCDelegate.headerView.frame = CGRect(x: multiAppVCDelegate.headerView.frame.origin.x, y: multiAppVCDelegate.headerView.frame.origin.y-5, width: multiAppVCDelegate.headerView.frame.size.width, height: multiAppVCDelegate.headerView.frame.size.height) multiAppVCDelegate.pageControl.frame = CGRect(x: multiAppVCDelegate.headerView.center.x-5, y: multiAppVCDelegate.headerView.frame.origin.y+multiAppVCDelegate.applyFactsLbl.frame.size.height+20, width: 10, height:1) multiAppVCDelegate.hundredsCarryLbl.frame = CGRect(x: multiAppVCDelegate.hundredsCarryLbl.frame.origin.x-3 , y: multiAppVCDelegate.hundredsCarryLbl.frame.origin.y, width: multiAppVCDelegate.hundredsCarryLbl.frame.size.width, height: multiAppVCDelegate.hundredsCarryLbl.frame.size.height) multiAppVCDelegate.thousandsCarryLbl.frame = CGRect(x: multiAppVCDelegate.thousandsCarryLbl.frame.origin.x-3, y: multiAppVCDelegate.thousandsCarryLbl.frame.origin.y, width: multiAppVCDelegate.thousandsCarryLbl.frame.size.width, height: multiAppVCDelegate.thousandsCarryLbl.frame.size.height) multiAppVCDelegate.firstNumber_LargeLbl.frame = CGRect(x: multiAppVCDelegate.firstNumber_LargeLbl.frame.origin.x, y: multiAppVCDelegate.firstNumber_LargeLbl.frame.origin.y+5, width: multiAppVCDelegate.firstNumber_LargeLbl.frame.size.width, height: multiAppVCDelegate.firstNumber_LargeLbl.frame.size.height) multiAppVCDelegate.numbersView.frame = CGRect(x: multiAppVCDelegate.numbersView.frame.origin.x, y: multiAppVCDelegate.numbersView.frame.origin.y+10, width: multiAppVCDelegate.numbersView.frame.size.width, height: multiAppVCDelegate.numbersView.frame.size.height) multiAppVCDelegate.firstResult_LargeLbl.frame = CGRect(x: multiAppVCDelegate.firstResult_LargeLbl.frame.origin.x, y: multiAppVCDelegate.firstResult_LargeLbl.frame.origin.y+10, width: multiAppVCDelegate.firstResult_LargeLbl.frame.size.width, height: multiAppVCDelegate.firstResult_LargeLbl.frame.size.height) multiAppVCDelegate.secondResult_LargeLbl.frame = CGRect(x: multiAppVCDelegate.secondResult_LargeLbl.frame.origin.x, y: multiAppVCDelegate.secondResult_LargeLbl.frame.origin.y+10, width: multiAppVCDelegate.secondResult_LargeLbl.frame.size.width, height: multiAppVCDelegate.secondResult_LargeLbl.frame.size.height) multiAppVCDelegate.finalAnswerView.frame = CGRect(x: multiAppVCDelegate.finalAnswerView.frame.origin.x-10, y: multiAppVCDelegate.finalAnswerView.frame.origin.y+8, width: multiAppVCDelegate.finalAnswerView.frame.size.width+10, height: multiAppVCDelegate.finalAnswerView.frame.size.height) multiAppVCDelegate.finalresponseCarryView.frame = CGRect(x: multiAppVCDelegate.finalresponseCarryView.frame.origin.x-2, y: multiAppVCDelegate.finalresponseCarryView.frame.origin.y+7, width: multiAppVCDelegate.finalresponseCarryView.frame.size.width, height: multiAppVCDelegate.finalresponseCarryView.frame.size.height) multiAppVCDelegate.sumLine_LargeLbl.frame = CGRect(x: multiAppVCDelegate.sumLine_LargeLbl.frame.origin.x, y: multiAppVCDelegate.sumLine_LargeLbl.frame.origin.y+6, width: multiAppVCDelegate.sumLine_LargeLbl.frame.size.width, height: multiAppVCDelegate.sumLine_LargeLbl.frame.size.height) multiAppVCDelegate.sumHunThousCarry_LargeLbl.frame = CGRect(x: multiAppVCDelegate.sumHunThousCarry_LargeLbl.frame.origin.x-2, y: multiAppVCDelegate.sumHunThousCarry_LargeLbl.frame.origin.y, width: multiAppVCDelegate.sumHunThousCarry_LargeLbl.frame.size.width, height: multiAppVCDelegate.sumHunThousCarry_LargeLbl.frame.size.height) multiAppVCDelegate.sumTenThousCarry_LargeLbl.frame = CGRect(x: multiAppVCDelegate.sumTenThousCarry_LargeLbl.frame.origin.x-1, y: multiAppVCDelegate.sumTenThousCarry_LargeLbl.frame.origin.y, width: multiAppVCDelegate.sumTenThousCarry_LargeLbl.frame.size.width, height: multiAppVCDelegate.sumTenThousCarry_LargeLbl.frame.size.height) multiAppVCDelegate.sumHundredsCarry_LargeLbl.frame = CGRect(x: multiAppVCDelegate.sumHundredsCarry_LargeLbl.frame.origin.x+1, y: multiAppVCDelegate.sumHundredsCarry_LargeLbl.frame.origin.y, width: multiAppVCDelegate.sumHundredsCarry_LargeLbl.frame.size.width, height: multiAppVCDelegate.sumHundredsCarry_LargeLbl.frame.size.height) multiAppVCDelegate.alertPopOverView.frame = CGRect(x: multiAppVCDelegate.alertPopOverView.frame.origin.x, y:0, width: multiAppVCDelegate.alertPopOverView.frame.size.width, height: multiAppVCDelegate.alertPopOverView.frame.size.height+20) multiAppVCDelegate.popUpTitleView.frame = CGRect(x: 0, y: 0, width: DeviceModel.SCREEN_WIDTH, height: 40) multiAppVCDelegate.popUpmessageView.frame = CGRect(x: 0, y: 40, width: DeviceModel.SCREEN_WIDTH, height: 430) } else if DeviceModel.IS_IPHONE_5 { // Frames for carry Lbls for Addition ,subtraction, Small Multiplication (Multiplication) multiAppVCDelegate.onesCarry_LargeLbl.frame = CGRect(x: multiAppVCDelegate.onesCarry_LargeLbl.frame.origin.x, y: multiAppVCDelegate.onesCarry_LargeLbl.frame.origin.y, width: multiAppVCDelegate.onesCarry_LargeLbl.frame.size.width, height: multiAppVCDelegate.onesCarry_LargeLbl.frame.size.height) multiAppVCDelegate.tensCarry_LargeLbl.frame = CGRect(x: multiAppVCDelegate.tensCarry_LargeLbl.frame.origin.x-2, y: multiAppVCDelegate.tensCarry_LargeLbl.frame.origin.y, width: multiAppVCDelegate.tensCarry_LargeLbl.frame.size.width, height: multiAppVCDelegate.tensCarry_LargeLbl.frame.size.height) multiAppVCDelegate.hundredsCarry_LargeLbl.frame = CGRect(x: multiAppVCDelegate.hundredsCarry_LargeLbl.frame.origin.x-3 , y: multiAppVCDelegate.hundredsCarry_LargeLbl.frame.origin.y, width: multiAppVCDelegate.hundredsCarry_LargeLbl.frame.size.width, height: multiAppVCDelegate.hundredsCarry_LargeLbl.frame.size.height) multiAppVCDelegate.thousandsCarry_LargeLbl.frame = CGRect(x: multiAppVCDelegate.thousandsCarry_LargeLbl.frame.origin.x-1, y: multiAppVCDelegate.thousandsCarry_LargeLbl.frame.origin.y, width: multiAppVCDelegate.thousandsCarry_LargeLbl.frame.size.width, height: multiAppVCDelegate.thousandsCarry_LargeLbl.frame.size.height) // Frames for carry for adding after multiplication carry Lbls (Multiplication) multiAppVCDelegate.sumOnesCarry_LargeLbl.frame = CGRect(x: multiAppVCDelegate.sumOnesCarry_LargeLbl.frame.origin.x, y: multiAppVCDelegate.sumOnesCarry_LargeLbl.frame.origin.y, width: multiAppVCDelegate.sumOnesCarry_LargeLbl.frame.size.width, height: multiAppVCDelegate.sumOnesCarry_LargeLbl.frame.size.height) multiAppVCDelegate.tensCarry_LargeLbl.frame = CGRect(x: multiAppVCDelegate.tensCarry_LargeLbl.frame.origin.x, y: multiAppVCDelegate.tensCarry_LargeLbl.frame.origin.y, width: multiAppVCDelegate.tensCarry_LargeLbl.frame.size.width, height: multiAppVCDelegate.tensCarry_LargeLbl.frame.size.height) multiAppVCDelegate.hundredsCarry_LargeLbl.frame = CGRect(x: multiAppVCDelegate.hundredsCarry_LargeLbl.frame.origin.x-2, y: multiAppVCDelegate.hundredsCarry_LargeLbl.frame.origin.y, width: multiAppVCDelegate.hundredsCarry_LargeLbl.frame.size.width, height: multiAppVCDelegate.hundredsCarry_LargeLbl.frame.size.height) multiAppVCDelegate.thousandsCarry_LargeLbl.frame = CGRect(x: multiAppVCDelegate.thousandsCarry_LargeLbl.frame.origin.x-1, y: multiAppVCDelegate.thousandsCarry_LargeLbl.frame.origin.y, width: multiAppVCDelegate.thousandsCarry_LargeLbl.frame.size.width, height: multiAppVCDelegate.thousandsCarry_LargeLbl.frame.size.height) multiAppVCDelegate.sumTenThousCarry_LargeLbl.frame = CGRect(x: multiAppVCDelegate.sumTenThousCarry_LargeLbl.frame.origin.x-2, y: multiAppVCDelegate.sumTenThousCarry_LargeLbl.frame.origin.y, width: multiAppVCDelegate.sumTenThousCarry_LargeLbl.frame.size.width, height: multiAppVCDelegate.sumTenThousCarry_LargeLbl.frame.size.height) multiAppVCDelegate.sumHunThousCarry_LargeLbl.frame = CGRect(x: multiAppVCDelegate.sumHunThousCarry_LargeLbl.frame.origin.x-3, y: multiAppVCDelegate.sumHunThousCarry_LargeLbl.frame.origin.y, width: multiAppVCDelegate.sumHunThousCarry_LargeLbl.frame.size.width, height: multiAppVCDelegate.sumHunThousCarry_LargeLbl.frame.size.height) } if DeviceModel.IS_IPHONE_6{ // Frames for carry Lbls for Addition ,subtraction, Small Multiplication (Multiplication) // Adding frames Addition ,subtraction, Small Multiplication for iPhone6 // Frames for respCarry Lbls (Substraction, Addition) multiAppVCDelegate.onesCarryLbl.frame = CGRect(x: multiAppVCDelegate.onesCarryLbl.frame.origin.x + 5, y: multiAppVCDelegate.onesCarryLbl.frame.origin.y, width: multiAppVCDelegate.onesCarryLbl.frame.size.width, height: multiAppVCDelegate.onesCarryLbl.frame.size.height) multiAppVCDelegate.tensCarryLbl.frame = CGRect(x: multiAppVCDelegate.tensCarryLbl.frame.origin.x + 5, y: multiAppVCDelegate.tensCarryLbl.frame.origin.y, width: multiAppVCDelegate.tensCarryLbl.frame.size.width, height: multiAppVCDelegate.tensCarryLbl.frame.size.height) multiAppVCDelegate.hundredsCarryLbl.frame = CGRect(x: multiAppVCDelegate.hundredsCarryLbl.frame.origin.x + 9.5, y: multiAppVCDelegate.hundredsCarryLbl.frame.origin.y, width: multiAppVCDelegate.hundredsCarryLbl.frame.size.width, height: multiAppVCDelegate.hundredsCarryLbl.frame.size.height) multiAppVCDelegate.thousandsCarryLbl.frame = CGRect(x: multiAppVCDelegate.thousandsCarryLbl.frame.origin.x + 8.8, y: multiAppVCDelegate.thousandsCarryLbl.frame.origin.y, width: multiAppVCDelegate.thousandsCarryLbl.frame.size.width, height: multiAppVCDelegate.thousandsCarryLbl.frame.size.height) // Frames for multiplication carry Lbls (Multiplication) multiAppVCDelegate.onesCarry_LargeLbl.frame = CGRect(x: multiAppVCDelegate.onesCarry_LargeLbl.frame.origin.x, y: multiAppVCDelegate.onesCarry_LargeLbl.frame.origin.y, width: multiAppVCDelegate.onesCarry_LargeLbl.frame.size.width, height: multiAppVCDelegate.onesCarry_LargeLbl.frame.size.height) multiAppVCDelegate.tensCarry_LargeLbl.frame = CGRect(x: multiAppVCDelegate.tensCarry_LargeLbl.frame.origin.x + 2, y: multiAppVCDelegate.tensCarry_LargeLbl.frame.origin.y, width: multiAppVCDelegate.tensCarry_LargeLbl.frame.size.width, height: multiAppVCDelegate.tensCarry_LargeLbl.frame.size.height) multiAppVCDelegate.hundredsCarry_LargeLbl.frame = CGRect(x: multiAppVCDelegate.hundredsCarry_LargeLbl.frame.origin.x + 3, y: multiAppVCDelegate.hundredsCarry_LargeLbl.frame.origin.y, width: multiAppVCDelegate.hundredsCarry_LargeLbl.frame.size.width, height: multiAppVCDelegate.hundredsCarry_LargeLbl.frame.size.height) multiAppVCDelegate.thousandsCarry_LargeLbl.frame = CGRect(x: multiAppVCDelegate.thousandsCarry_LargeLbl.frame.origin.x + 9, y: multiAppVCDelegate.thousandsCarry_LargeLbl.frame.origin.y, width: multiAppVCDelegate.thousandsCarry_LargeLbl.frame.size.width, height: multiAppVCDelegate.thousandsCarry_LargeLbl.frame.size.height) // Frames for carry for adding after multiplication carry Lbls (Multiplication) multiAppVCDelegate.sumOnesCarry_LargeLbl.frame = CGRect(x: multiAppVCDelegate.sumOnesCarry_LargeLbl.frame.origin.x, y: multiAppVCDelegate.sumOnesCarry_LargeLbl.frame.origin.y, width: multiAppVCDelegate.sumOnesCarry_LargeLbl.frame.size.width, height: multiAppVCDelegate.sumOnesCarry_LargeLbl.frame.size.height) multiAppVCDelegate.sumTensCarry_LargeLbl.frame = CGRect(x: multiAppVCDelegate.sumTensCarry_LargeLbl.frame.origin.x+2, y: multiAppVCDelegate.sumTensCarry_LargeLbl.frame.origin.y, width: multiAppVCDelegate.sumTensCarry_LargeLbl.frame.size.width, height: multiAppVCDelegate.sumTensCarry_LargeLbl.frame.size.height) multiAppVCDelegate.sumHundredsCarry_LargeLbl.frame = CGRect(x: multiAppVCDelegate.sumHundredsCarry_LargeLbl.frame.origin.x+7, y: multiAppVCDelegate.sumHundredsCarry_LargeLbl.frame.origin.y, width: multiAppVCDelegate.sumHundredsCarry_LargeLbl.frame.size.width, height: multiAppVCDelegate.sumHundredsCarry_LargeLbl.frame.size.height) multiAppVCDelegate.sumThousandsCarry_LargeLbl.frame = CGRect(x: multiAppVCDelegate.sumThousandsCarry_LargeLbl.frame.origin.x+10, y: multiAppVCDelegate.sumThousandsCarry_LargeLbl.frame.origin.y, width: multiAppVCDelegate.sumThousandsCarry_LargeLbl.frame.size.width, height: multiAppVCDelegate.sumThousandsCarry_LargeLbl.frame.size.height) multiAppVCDelegate.sumTenThousCarry_LargeLbl.frame = CGRect(x: multiAppVCDelegate.sumTenThousCarry_LargeLbl.frame.origin.x+9, y: multiAppVCDelegate.sumTenThousCarry_LargeLbl.frame.origin.y, width: multiAppVCDelegate.sumTenThousCarry_LargeLbl.frame.size.width, height: multiAppVCDelegate.sumTenThousCarry_LargeLbl.frame.size.height) multiAppVCDelegate.sumHunThousCarry_LargeLbl.frame = CGRect(x: multiAppVCDelegate.sumHunThousCarry_LargeLbl.frame.origin.x+7, y: multiAppVCDelegate.sumHunThousCarry_LargeLbl.frame.origin.y, width: multiAppVCDelegate.sumHunThousCarry_LargeLbl.frame.size.width, height: multiAppVCDelegate.sumHunThousCarry_LargeLbl.frame.size.height) } else if DeviceModel.IS_IPHONE_6P {// Adding frames for all carry labels for iPhone6plus // Frames for respCarry Lbls (Substraction, Addition,multiplication(small)) multiAppVCDelegate.onesCarryLbl.frame = CGRect(x: multiAppVCDelegate.onesCarryLbl.frame.origin.x + 10, y: multiAppVCDelegate.onesCarryLbl.frame.origin.y, width: multiAppVCDelegate.onesCarryLbl.frame.size.width, height: multiAppVCDelegate.onesCarryLbl.frame.size.height) multiAppVCDelegate.tensCarryLbl.frame = CGRect(x: multiAppVCDelegate.tensCarryLbl.frame.origin.x + 11, y: multiAppVCDelegate.tensCarryLbl.frame.origin.y, width: multiAppVCDelegate.tensCarryLbl.frame.size.width, height: multiAppVCDelegate.tensCarryLbl.frame.size.height) multiAppVCDelegate.hundredsCarryLbl.frame = CGRect(x: 45, y: multiAppVCDelegate.hundredsCarryLbl.frame.origin.y, width: multiAppVCDelegate.hundredsCarryLbl.frame.size.width, height: multiAppVCDelegate.hundredsCarryLbl.frame.size.height) multiAppVCDelegate.thousandsCarryLbl.frame = CGRect(x: 21, y: multiAppVCDelegate.thousandsCarryLbl.frame.origin.y, width: multiAppVCDelegate.thousandsCarryLbl.frame.size.width, height: multiAppVCDelegate.thousandsCarryLbl.frame.size.height) multiAppVCDelegate.answer1View.frame = CGRect(x: multiAppVCDelegate.answer1View.frame.origin.x + 10, y: multiAppVCDelegate.answer1View.frame.origin.y, width: multiAppVCDelegate.answer1View.frame.size.width-10, height: multiAppVCDelegate.answer1View.frame.size.height) // Frames for multiplication carry Lbls (Multiplication) multiAppVCDelegate.onesCarry_LargeLbl.frame = CGRect(x: multiAppVCDelegate.onesCarry_LargeLbl.frame.origin.x+8, y: multiAppVCDelegate.onesCarry_LargeLbl.frame.origin.y, width: multiAppVCDelegate.onesCarry_LargeLbl.frame.size.width, height: multiAppVCDelegate.onesCarry_LargeLbl.frame.size.height) multiAppVCDelegate.tensCarry_LargeLbl.frame = CGRect(x: multiAppVCDelegate.tensCarry_LargeLbl.frame.origin.x + 6, y: multiAppVCDelegate.tensCarry_LargeLbl.frame.origin.y, width: multiAppVCDelegate.tensCarry_LargeLbl.frame.size.width, height: multiAppVCDelegate.tensCarry_LargeLbl.frame.size.height) multiAppVCDelegate.hundredsCarry_LargeLbl.frame = CGRect(x: multiAppVCDelegate.hundredsCarry_LargeLbl.frame.origin.x + 7.5, y: multiAppVCDelegate.hundredsCarry_LargeLbl.frame.origin.y, width: multiAppVCDelegate.hundredsCarry_LargeLbl.frame.size.width, height: multiAppVCDelegate.hundredsCarry_LargeLbl.frame.size.height) multiAppVCDelegate.thousandsCarry_LargeLbl.frame = CGRect(x: multiAppVCDelegate.thousandsCarry_LargeLbl.frame.origin.x + 16, y: multiAppVCDelegate.thousandsCarry_LargeLbl.frame.origin.y, width: multiAppVCDelegate.thousandsCarry_LargeLbl.frame.size.width, height: multiAppVCDelegate.thousandsCarry_LargeLbl.frame.size.height) // Frames for carry for adding after multuplication carry Lbls (Multiplication) multiAppVCDelegate.sumOnesCarry_LargeLbl.frame = CGRect(x: multiAppVCDelegate.sumOnesCarry_LargeLbl.frame.origin.x, y: multiAppVCDelegate.sumOnesCarry_LargeLbl.frame.origin.y, width: multiAppVCDelegate.sumOnesCarry_LargeLbl.frame.size.width, height: multiAppVCDelegate.sumOnesCarry_LargeLbl.frame.size.height) multiAppVCDelegate.sumTensCarry_LargeLbl.frame = CGRect(x: multiAppVCDelegate.sumTensCarry_LargeLbl.frame.origin.x, y: multiAppVCDelegate.sumTensCarry_LargeLbl.frame.origin.y, width: multiAppVCDelegate.sumTensCarry_LargeLbl.frame.size.width, height: multiAppVCDelegate.sumTensCarry_LargeLbl.frame.size.height) multiAppVCDelegate.sumHundredsCarry_LargeLbl.frame = CGRect(x: multiAppVCDelegate.sumHundredsCarry_LargeLbl.frame.origin.x+12, y: multiAppVCDelegate.sumHundredsCarry_LargeLbl.frame.origin.y, width: multiAppVCDelegate.sumHundredsCarry_LargeLbl.frame.size.width, height: multiAppVCDelegate.sumHundredsCarry_LargeLbl.frame.size.height) multiAppVCDelegate.sumThousandsCarry_LargeLbl.frame = CGRect(x: multiAppVCDelegate.sumThousandsCarry_LargeLbl.frame.origin.x+16, y: multiAppVCDelegate.sumThousandsCarry_LargeLbl.frame.origin.y, width: multiAppVCDelegate.sumThousandsCarry_LargeLbl.frame.size.width, height: multiAppVCDelegate.sumThousandsCarry_LargeLbl.frame.size.height) multiAppVCDelegate.sumTenThousCarry_LargeLbl.frame = CGRect(x: multiAppVCDelegate.sumTenThousCarry_LargeLbl.frame.origin.x+19, y: multiAppVCDelegate.sumTenThousCarry_LargeLbl.frame.origin.y, width: multiAppVCDelegate.sumTenThousCarry_LargeLbl.frame.size.width, height: multiAppVCDelegate.sumTenThousCarry_LargeLbl.frame.size.height) multiAppVCDelegate.sumHunThousCarry_LargeLbl.frame = CGRect(x: multiAppVCDelegate.sumHunThousCarry_LargeLbl.frame.origin.x+19, y: multiAppVCDelegate.sumHunThousCarry_LargeLbl.frame.origin.y, width: multiAppVCDelegate.sumHunThousCarry_LargeLbl.frame.size.width, height: multiAppVCDelegate.sumHunThousCarry_LargeLbl.frame.size.height) } /// calling gesture recognizer. callGestures() multiAppVCDelegate.mfCategory = AppdelegateRef.appDelegate.mathFactsCatagory() multiAppVCDelegate.mfLevel = AppdelegateRef.appDelegate.MathFactsLevel multiAppVCDelegate.mfNumRange = AppdelegateRef.appDelegate.MathFactsRange // Get initial equation numbers multiAppVCDelegate.getNewNumbers() multiAppVCDelegate.elapsedTime = Timer.scheduledTimer(timeInterval: 1.0, target: multiAppVCDelegate, selector:#selector(multiAppVCDelegate.secondsCounter), userInfo: nil, repeats: true) // Set up images to flash math operators after swiping let xVal = (DeviceModel.SCREEN_WIDTH-150)/2 let yVal = 92.5 //30 multiAppVCDelegate.iconPlusSignLarge = UIImageView.init(image:#imageLiteral(resourceName: "Plus205x205dot")) let LPlusRect = CGRect(x: CGFloat(xVal), y: CGFloat(yVal), width: CGFloat(150), height: CGFloat(150)) multiAppVCDelegate.iconPlusSignLarge.frame = LPlusRect multiAppVCDelegate.view.addSubview(multiAppVCDelegate.iconPlusSignLarge) multiAppVCDelegate.iconPlusSignLarge.isHidden = false multiAppVCDelegate.iconPlusSignLarge.alpha = 0.0 multiAppVCDelegate.iconMinusSignLarge = UIImageView.init(image:#imageLiteral(resourceName: "Minus205x205dot")) let LMinusRect = CGRect(x: CGFloat(xVal), y: CGFloat(yVal), width: CGFloat(150), height: CGFloat(150)) multiAppVCDelegate.iconMinusSignLarge.frame = LMinusRect multiAppVCDelegate.view.addSubview(multiAppVCDelegate.iconMinusSignLarge) multiAppVCDelegate.iconMinusSignLarge.isHidden = false multiAppVCDelegate.iconMinusSignLarge.alpha = 0.0 multiAppVCDelegate.iconTimesSignLarge = UIImageView.init(image:#imageLiteral(resourceName: "Times205x205dot")) let LTimesRect = CGRect(x: CGFloat(xVal), y: CGFloat(yVal), width: CGFloat(150), height: CGFloat(150)) multiAppVCDelegate.iconTimesSignLarge.frame = LTimesRect multiAppVCDelegate.view.addSubview(multiAppVCDelegate.iconTimesSignLarge) multiAppVCDelegate.iconTimesSignLarge.isHidden = false multiAppVCDelegate.iconTimesSignLarge.alpha = 0.0 multiAppVCDelegate.iconDivideSignLarge = UIImageView.init(image:#imageLiteral(resourceName: "Divide205x205dot")) let LDivRect = CGRect(x: CGFloat(xVal), y: CGFloat(yVal), width: CGFloat(150), height: CGFloat(150)) multiAppVCDelegate.iconDivideSignLarge.frame = LDivRect multiAppVCDelegate.view.addSubview(multiAppVCDelegate.iconDivideSignLarge) multiAppVCDelegate.iconDivideSignLarge.isHidden = false multiAppVCDelegate.iconDivideSignLarge.alpha = 0.0 } // Custom Method to initialize the swipe Gestures to all directions in the view. func callGestures() { // Swipe Left let swipeLeft:UISwipeGestureRecognizer = UISwipeGestureRecognizer.init(target: multiAppVCDelegate, action: #selector(multiAppVCDelegate.swipeLeft)) swipeLeft.direction = .left multiAppVCDelegate.view.addGestureRecognizer(swipeLeft) // Swipe Right let swipeRight:UISwipeGestureRecognizer = UISwipeGestureRecognizer.init(target: multiAppVCDelegate, action: #selector(multiAppVCDelegate.swipeRight)) swipeRight.direction = .right multiAppVCDelegate.view.addGestureRecognizer(swipeRight) // Swipe up let swipeUp:UISwipeGestureRecognizer = UISwipeGestureRecognizer.init(target: multiAppVCDelegate, action: #selector(multiAppVCDelegate.swipeUp)) swipeUp.direction = .up multiAppVCDelegate.view.addGestureRecognizer(swipeUp) // Swipe Down let swipeDown:UISwipeGestureRecognizer = UISwipeGestureRecognizer.init(target: multiAppVCDelegate, action: #selector(multiAppVCDelegate.swipeDown)) swipeDown.direction = .down multiAppVCDelegate.view.addGestureRecognizer(swipeDown) multiAppVCDelegate.isRandom = true //TapGesture for PopView let popViewtapgeasture:UITapGestureRecognizer = UITapGestureRecognizer.init(target: multiAppVCDelegate, action: #selector(multiAppVCDelegate.alertCloseBtnAction)) popViewtapgeasture.numberOfTapsRequired = 1; multiAppVCDelegate.alertPopOverView.addGestureRecognizer(popViewtapgeasture) } // Custom mehod to show the flash image which was select in initial screen with the fade animations. func flashIcon() { AudioServicesPlaySystemSound (AudioFilesConstant.kSoundFileObject.ffftsoundFileObject) switch (multiAppVCDelegate.mfCategory) { // Selective call teh method to flash up the current Operator case 0: multiAppVCDelegate.iconCurrentSignLarge = multiAppVCDelegate.iconPlusSignLarge break case 1: multiAppVCDelegate.iconCurrentSignLarge = multiAppVCDelegate.iconMinusSignLarge break case 2: multiAppVCDelegate.iconCurrentSignLarge = multiAppVCDelegate.iconTimesSignLarge break case 3: multiAppVCDelegate.iconCurrentSignLarge = multiAppVCDelegate.iconDivideSignLarge break default: break } UIView.beginAnimations("fade in image", context: nil) UIView.setAnimationDuration(0.25) UIView.setAnimationDelay(0.0) UIView.setAnimationCurve(.easeIn) multiAppVCDelegate.iconCurrentSignLarge.alpha = 1.0 UIView.setAnimationDelegate(self) UIView.setAnimationDidStop(#selector(fadeInAnimationFinished(animationID:finished:context:))) UIView.commitAnimations() } // Custom method to start the fade out animation to dismis the selected flash image @objc func fadeInAnimationFinished(animationID:String,finished:NSNumber,context:UnsafeMutableRawPointer) { UIView.beginAnimations("fade out image", context: nil) UIView.setAnimationDelay(0.5) UIView.setAnimationDuration(0.25) UIView.setAnimationCurve(.easeInOut) // On occasion an icon would not get Faded out and would stay up until it specifically was rendered again and faded out. // So, now fade all icons (not just the current one) to catch any that might have been left behind //// iconCurrentSignLarge.alphac multiAppVCDelegate.iconPlusSignLarge.alpha = 0.0 multiAppVCDelegate.iconMinusSignLarge.alpha = 0.0 multiAppVCDelegate.iconTimesSignLarge.alpha = 0.0 multiAppVCDelegate.iconDivideSignLarge.alpha = 0.0 UIView.commitAnimations() } // Custom method to do the functionality of the arithmetic operation according to the button was selected in the number pad. If user selects the correct answer it will go to the next step of arithmetic operation otherwise gives a error sound. func buttonDigitPressed(sender: UIButton) { multiAppVCDelegate.spaceStr = " " switch (multiAppVCDelegate.inputPhase) { // Tens carry case 0: if (sender.tag == multiAppVCDelegate.calcTensCarry) { if (multiAppVCDelegate.equationSecondNum > 9) { multiAppVCDelegate.tensCarryLbl.text = String(format: "%1d",multiAppVCDelegate.calcTensCarry) } else { multiAppVCDelegate.answer1Lbl.text = String(format: "%1d",multiAppVCDelegate.calcTensCarry)+multiAppVCDelegate.spaceStr } } else { multiAppVCDelegate.responseError = true } break // Ones place case 1: if (sender.tag == multiAppVCDelegate.calcOnes) { if ((multiAppVCDelegate.calcTensCarry > 0) && (multiAppVCDelegate.equationSecondNum < 10)) { multiAppVCDelegate.answer1Lbl.text = String(multiAppVCDelegate.calculatedAnswer) multiAppVCDelegate.getNewProblem = 1 break } else { multiAppVCDelegate.answer1Lbl.text = String(format: "%1d",multiAppVCDelegate.calcOnes)+" " } if (multiAppVCDelegate.calculatedAnswer > 9) { multiAppVCDelegate.inputPhase = 2 if (multiAppVCDelegate.calcHunsCarry > 0 ){ multiAppVCDelegate.inputPhase = 1 } } else { multiAppVCDelegate.getNewProblem = 1 } } else { multiAppVCDelegate.responseError = true } break // Hundreds carry case 2: if (sender.tag == multiAppVCDelegate.calcHunsCarry) { if (multiAppVCDelegate.equationSecondNum > 100) { multiAppVCDelegate.hundredsCarryLbl.text = String(format: "%1d",multiAppVCDelegate.calcHunsCarry) } else { multiAppVCDelegate.answer1Lbl.text = String(format: "%1d",multiAppVCDelegate.calcHunsCarry)+multiAppVCDelegate.spaceStr+String(format: "%1d",multiAppVCDelegate.calcOnes) } } else { multiAppVCDelegate.responseError = true } break // Tens place case 3: if (sender.tag == multiAppVCDelegate.calcTens) { if ((multiAppVCDelegate.calcHunsCarry > 0) && (multiAppVCDelegate.equationSecondNum < 100)) { multiAppVCDelegate.answer1Lbl.text = String(multiAppVCDelegate.calcHunsCarry)+String(multiAppVCDelegate.calcTens)+String(multiAppVCDelegate.calcOnes) multiAppVCDelegate.getNewProblem = 1 break } else { multiAppVCDelegate.answer1Lbl.text = String(format: "%1d",multiAppVCDelegate.calcTens)+String(format: "%1d",multiAppVCDelegate.calcOnes) } if ((multiAppVCDelegate.calculatedAnswer % 100) == 0) { multiAppVCDelegate.answer1Lbl.text = "00" // Forces display to show multiple zeros instead of just one! } if (multiAppVCDelegate.calculatedAnswer > 99) { multiAppVCDelegate.inputPhase = 4 if (multiAppVCDelegate.calcThousCarry > 0) { multiAppVCDelegate.inputPhase = 3 } } else { multiAppVCDelegate.getNewProblem = 1 } } else { multiAppVCDelegate.responseError = true } break // Thousands carry case 4: if (sender.tag == multiAppVCDelegate.calcThousCarry) { if (multiAppVCDelegate.equationSecondNum > 1000) { multiAppVCDelegate.thousandsCarryLbl.text = String(format: "%1d",multiAppVCDelegate.calcThousCarry) } else { multiAppVCDelegate.answer1Lbl.text = String(multiAppVCDelegate.calcThousCarry)+multiAppVCDelegate.spaceStr+String(multiAppVCDelegate.calcTens)+String(multiAppVCDelegate.calcOnes) } AudioServicesPlaySystemSound (AudioFilesConstant.kSoundFileObject.clicksoundFileObject) // key click } else { multiAppVCDelegate.responseError = true } break // Hundreds place case 5: if (sender.tag == multiAppVCDelegate.calcHuns) { if ((multiAppVCDelegate.calcThousCarry > 0) && (multiAppVCDelegate.equationSecondNum < 1000)) { multiAppVCDelegate.answer1Lbl.text = String(multiAppVCDelegate.calcThousCarry)+String(multiAppVCDelegate.calcHuns)+String(multiAppVCDelegate.calcTens)+String(multiAppVCDelegate.calcOnes) multiAppVCDelegate.getNewProblem = 1 break } multiAppVCDelegate.answer1Lbl.text = String(format: "%1d",multiAppVCDelegate.calcHuns)+String(format: "%1d",multiAppVCDelegate.calcTens)+String(format: "%1d",multiAppVCDelegate.calcOnes) if ((multiAppVCDelegate.calculatedAnswer % 1000) == 0) { multiAppVCDelegate.answer1Lbl.text = "000" // Forces display to show multiple zeros instead of just one! } if (multiAppVCDelegate.calculatedAnswer < 1000) { multiAppVCDelegate.getNewProblem = 1 } } else { multiAppVCDelegate.responseError = true } break // Thousands place case 6: if(multiAppVCDelegate.calcTenThous > 0) { if (sender.tag == multiAppVCDelegate.calcTenThous) { if multiAppVCDelegate.calcTenThous == 0 { multiAppVCDelegate.answer1Lbl.text = String(format: "%1d",multiAppVCDelegate.calcThous)+String(format: "%1d",multiAppVCDelegate.calcHuns)+String(format: "%1d",multiAppVCDelegate.calcTens)+String(format: "%1d",multiAppVCDelegate.calcOnes) } else { multiAppVCDelegate.answer1Lbl.text = String(format: "%1d",multiAppVCDelegate.calcTenThous)+String(format: "%1d",multiAppVCDelegate.calcHuns)+String(format: "%1d",multiAppVCDelegate.calcTens)+String(format: "%1d",multiAppVCDelegate.calcOnes) } if (multiAppVCDelegate.calculatedAnswer > 9999) { multiAppVCDelegate.inputPhase = 7 } else { multiAppVCDelegate.getNewProblem = 1 } } else { multiAppVCDelegate.responseError = true } } else { if (sender.tag == multiAppVCDelegate.calcThous) { multiAppVCDelegate.answer1Lbl.text = String(format: "%1d",multiAppVCDelegate.calcThous)+String(format: "%1d",multiAppVCDelegate.calcHuns)+String(format: "%1d",multiAppVCDelegate.calcTens)+String(format: "%1d",multiAppVCDelegate.calcOnes) if (multiAppVCDelegate.calculatedAnswer > 9999) { multiAppVCDelegate.inputPhase = 7 } else { multiAppVCDelegate.getNewProblem = 1 } } else { multiAppVCDelegate.responseError = true } } break /////Ram///// case 7,8: if (sender.tag == multiAppVCDelegate.calcThous) { multiAppVCDelegate.answer1Lbl.text = String(format: "%1d",multiAppVCDelegate.calcTenThous)+String(format: "%1d",multiAppVCDelegate.calcThous)+String(format: "%1d",multiAppVCDelegate.calcHuns)+String(format: "%1d",multiAppVCDelegate.calcTens)+String(format: "%1d",multiAppVCDelegate.calcOnes) if (multiAppVCDelegate.calculatedAnswer > 9999) { // multiAppVCDelegate.inputPhase = 999 multiAppVCDelegate.getNewProblem = 1 } else { multiAppVCDelegate.getNewProblem = 1 } } else { multiAppVCDelegate.responseError = true } break // Subtraction case statements start here case 10: if (multiAppVCDelegate.equationOnes < multiAppVCDelegate.firstNumOnes ) { // Need to regroup if (sender.tag == 10) { //'10' is the TAG Id for the 'Regroup' button if (multiAppVCDelegate.equationTens > 0) { // We can get what we need from here multiAppVCDelegate.calcTensCarry = multiAppVCDelegate.equationTens - 1 multiAppVCDelegate.inputPhase = 12 // next phase is this + 1 (increments on exit from case) } else if (multiAppVCDelegate.equationHuns > 0) { // We can get what we need from here //multiplicandRegroupSlashes.text = [NSString stringWithFormat:@"/ / /"] multiAppVCDelegate.slashHunsStr = "∖" multiAppVCDelegate.calcHunsCarry = multiAppVCDelegate.equationHuns - 1 multiAppVCDelegate.calcTensCarry = 9 multiAppVCDelegate.inputPhase = 11 // next phase is this + 1 (increments on exit from case) } else if (multiAppVCDelegate.equationThous > 0) { // We can get what we need from here //multiplicandRegroupSlashes.text = [NSString stringWithFormat:@"/ / / /"] multiAppVCDelegate.slashThousStr = "∖" multiAppVCDelegate.slashHunsStr = "∖" multiAppVCDelegate.calcThousCarry = multiAppVCDelegate.equationThous - 1 multiAppVCDelegate.calcHunsCarry = 9 multiAppVCDelegate.calcTensCarry = 9 multiAppVCDelegate.inputPhase = 10 // next phase is this + 1 (increments on exit from case) } multiAppVCDelegate.calcOnesCarry = multiAppVCDelegate.equationOnes + 10 multiAppVCDelegate.TensCarryAlreadySet = true multiAppVCDelegate.slashOnesStr = "∖" multiAppVCDelegate.slashTensStr = "∖" } else { multiAppVCDelegate.responseError = true } } else {// No regrouping required if (sender.tag == multiAppVCDelegate.calcOnes) { multiAppVCDelegate.answer1Lbl.text = String(multiAppVCDelegate.calcOnes) multiAppVCDelegate.inputPhase = 16 // next phase is this + 1 (increments on exit from case) if (multiAppVCDelegate.calculatedAnswer < 10) { multiAppVCDelegate.getNewProblem = 1 // Exit route if answer is complete already } } else { multiAppVCDelegate.responseError = true } } break case 11: // Thousands regroup if (sender.tag == multiAppVCDelegate.calcThousCarry) { multiAppVCDelegate.thousandsCarryLbl.text = String(format: "%1d",multiAppVCDelegate.calcThousCarry) } else { multiAppVCDelegate.responseError = true } break case 12: // Hundreds Regroup if (sender.tag == multiAppVCDelegate.calcHunsCarry) { multiAppVCDelegate.hundredsCarryLbl.text = String(format: "%1d",multiAppVCDelegate.calcHunsCarry) } else { multiAppVCDelegate.responseError = true } break case 13: // Tens Regroup if (sender.tag == multiAppVCDelegate.calcTensCarry) { multiAppVCDelegate.tensCarryLbl.text = String(format: "%1d",multiAppVCDelegate.calcTensCarry) } else { multiAppVCDelegate.responseError = true } break case 14: // Ones Regroup first digit if (sender.tag == 1) { multiAppVCDelegate.onesCarryLbl.text = "1" } else { multiAppVCDelegate.responseError = true } break case 15: // Ones Regroup second digit if (sender.tag == multiAppVCDelegate.equationOnes % 10) { multiAppVCDelegate.onesCarryLbl.text = String(multiAppVCDelegate.calcOnesCarry) } else { multiAppVCDelegate.responseError = true } break case 16: if (sender.tag == multiAppVCDelegate.calcOnes) { multiAppVCDelegate.answer1Lbl.text = String(multiAppVCDelegate.calcOnes) if (multiAppVCDelegate.calculatedAnswer < 10) { multiAppVCDelegate.getNewProblem = 1 } } else { multiAppVCDelegate.responseError = true } break case 17: // May need to regroup here if (((multiAppVCDelegate.calcTensCarry >= 0) && (multiAppVCDelegate.calcTensCarry < multiAppVCDelegate.firstNumTens)) || // An additional regroup is required ((multiAppVCDelegate.calcTensCarry < 0 ) && (multiAppVCDelegate.equationTens < multiAppVCDelegate.firstNumTens ))) { // A first regroup is required if (sender.tag == 10) { //'10' is the TAG Id for the 'Regroup' button if (multiAppVCDelegate.equationHuns > 0) { // We can get what we need from here multiAppVCDelegate.slashHunsStr = "∖" multiAppVCDelegate.calcHunsCarry = multiAppVCDelegate.equationHuns - 1 multiAppVCDelegate.inputPhase = 18 // next phase is this + 1 (increments on exit from case) } else if (multiAppVCDelegate.equationThous > 0) { // We can get what we need from here multiAppVCDelegate.slashThousStr = "∖" multiAppVCDelegate.slashHunsStr = "∖" multiAppVCDelegate.calcThousCarry = multiAppVCDelegate.equationThous - 1 multiAppVCDelegate.calcHunsCarry = 9 multiAppVCDelegate.inputPhase = 17 // next phase is this + 1 (increments on exit from case) } if (multiAppVCDelegate.TensCarryAlreadySet) { multiAppVCDelegate.calcTensCarry += 10 } else { multiAppVCDelegate.calcTensCarry = 10 } multiAppVCDelegate.slashTensStr = "∖" } else { multiAppVCDelegate.responseError = true } } else {// No regrouping required if (sender.tag == multiAppVCDelegate.calcTens) { multiAppVCDelegate.answer1Lbl.text = String(multiAppVCDelegate.calcTens)+String(multiAppVCDelegate.calcOnes) multiAppVCDelegate.inputPhase = 22 // next phase is this + 1 (increments on exit from case) if (multiAppVCDelegate.calculatedAnswer < 100) { multiAppVCDelegate.getNewProblem = 1 // Exit route if answer is complete already } } else { multiAppVCDelegate.responseError = true } } break case 18: // Thousands regroup if (sender.tag == multiAppVCDelegate.calcThousCarry) { multiAppVCDelegate.thousandsCarryLbl.text = String(format: "%1d",multiAppVCDelegate.calcThousCarry) } else { multiAppVCDelegate.responseError = true } break case 19: // Hundreds Regroup if (sender.tag == multiAppVCDelegate.calcHunsCarry) { multiAppVCDelegate.hundredsCarryLbl.text = String(format: "%1d",multiAppVCDelegate.calcHunsCarry) } else { multiAppVCDelegate.responseError = true } break case 20: // Tens Regroup first digit if (sender.tag == 1) { if (multiAppVCDelegate.TensCarryAlreadySet) { multiAppVCDelegate.tensCarryLbl.text = String(multiAppVCDelegate.calcTensCarry) multiAppVCDelegate.inputPhase = 21 } else { multiAppVCDelegate.calcTensCarry = multiAppVCDelegate.equationTens + 10 multiAppVCDelegate.tensCarryLbl.text = "1" //[NSString stringWithFormat:@"%d", 1] } } else { multiAppVCDelegate.responseError = true } break case 21: // Tens Regroup second digit if (sender.tag == multiAppVCDelegate.calcTensCarry % 10) { multiAppVCDelegate.tensCarryLbl.text = String(multiAppVCDelegate.calcTensCarry) } else { multiAppVCDelegate.responseError = true } break case 22: //Response 10's place if (sender.tag == multiAppVCDelegate.calcTens) { multiAppVCDelegate.answer1Lbl.text = String(multiAppVCDelegate.calcTens)+String(multiAppVCDelegate.calcOnes) if (multiAppVCDelegate.calculatedAnswer < 100) { multiAppVCDelegate.getNewProblem = 1 // Exit route if answer is complete already } } else { multiAppVCDelegate.responseError = true } break case 23: //Response 100's place if (sender.tag == multiAppVCDelegate.calcHuns) { multiAppVCDelegate.answer1Lbl.text = String(multiAppVCDelegate.calcHuns)+String(multiAppVCDelegate.calcTens)+String(multiAppVCDelegate.calcOnes) if (multiAppVCDelegate.calculatedAnswer < 1000) { multiAppVCDelegate.getNewProblem = 1 } } else { multiAppVCDelegate.responseError = true } break case 24: //Response 1000's place if (sender.tag == multiAppVCDelegate.calcThous) { multiAppVCDelegate.answer1Lbl.text = String(multiAppVCDelegate.calcThous)+String(multiAppVCDelegate.calcHuns)+String(multiAppVCDelegate.calcTens)+String(multiAppVCDelegate.calcOnes) if (multiAppVCDelegate.calculatedAnswer < 10000) { multiAppVCDelegate.getNewProblem = 1 } } else { multiAppVCDelegate.responseError = true } break // Tens carry case 100: if (sender.tag == multiAppVCDelegate.altOnesCalcTensCarry) { if (multiAppVCDelegate.equationSecondNum > 9) { multiAppVCDelegate.tensCarry_LargeLbl.text = String(format: "%1d", multiAppVCDelegate.altOnesCalcTensCarry) } else { multiAppVCDelegate.firstResult_LargeLbl.text = String(format: "%1d", multiAppVCDelegate.altOnesCalcTensCarry)+multiAppVCDelegate.spaceStr } } else { multiAppVCDelegate.responseError = true } break // Ones place case 101: if (sender.tag == multiAppVCDelegate.calcOnes) { if ((multiAppVCDelegate.altOnesCalcTensCarry > 0) && (multiAppVCDelegate.equationSecondNum < 10)) { multiAppVCDelegate.finalAnswer_LargeLbl.text = String(multiAppVCDelegate.calculatedAnswer) multiAppVCDelegate.getNewProblem = 1 break } else { multiAppVCDelegate.firstResult_LargeLbl.text = String(format: "%1d", multiAppVCDelegate.calcOnes) } if (multiAppVCDelegate.altOnesCalcHunsCarry == 0 ) { multiAppVCDelegate.inputPhase=multiAppVCDelegate.inputPhase+1 } } else { multiAppVCDelegate.responseError = true } break // Hundreds carry case 102: if (sender.tag == multiAppVCDelegate.altOnesCalcHunsCarry) { if (multiAppVCDelegate.equationSecondNum > 100) { multiAppVCDelegate.hundredsCarry_LargeLbl.text = String(format: "%1d", multiAppVCDelegate.altOnesCalcHunsCarry) } else { multiAppVCDelegate.firstResult_LargeLbl.text = String(format: "%1d",multiAppVCDelegate.altOnesCalcHunsCarry)+multiAppVCDelegate.spaceStr+String(format: "%1d",multiAppVCDelegate.calcOnes) } } else { multiAppVCDelegate.responseError = true } break // Tens place case 103: if (sender.tag == multiAppVCDelegate.calcTens) { if ((multiAppVCDelegate.altOnesCalcHunsCarry > 0) && (multiAppVCDelegate.equationSecondNum < 100)) { multiAppVCDelegate.finalAnswer_LargeLbl.text = String(multiAppVCDelegate.altOnesCalcHunsCarry)+String(multiAppVCDelegate.calcTens)+String(multiAppVCDelegate.calcOnes) multiAppVCDelegate.getNewProblem = 1 break } else { multiAppVCDelegate.firstResult_LargeLbl.text = String(format: "%1d", multiAppVCDelegate.calcTens)+String(format: "%1d", multiAppVCDelegate.calcOnes) } if ((multiAppVCDelegate.calculatedAnswer % 100) == 0) { multiAppVCDelegate.firstResult_LargeLbl.text = "00" // Forces display to show multiple zeros instead of just one! } if (multiAppVCDelegate.altOnesCalcThousCarry == 0) { multiAppVCDelegate.inputPhase=multiAppVCDelegate.inputPhase+1 } } else { multiAppVCDelegate.responseError = true } break // Thousands carry case 104: if (sender.tag == multiAppVCDelegate.altOnesCalcThousCarry) { if (multiAppVCDelegate.equationSecondNum > 1000) { multiAppVCDelegate.thousandsCarry_LargeLbl.text = String(format: "%1d", multiAppVCDelegate.altOnesCalcThousCarry) } else { multiAppVCDelegate.firstResult_LargeLbl.text = String(multiAppVCDelegate.altOnesCalcThousCarry)+multiAppVCDelegate.spaceStr+String(multiAppVCDelegate.calcOnes) } AudioServicesPlaySystemSound (AudioFilesConstant.kSoundFileObject.clicksoundFileObject) // key click } else { multiAppVCDelegate.responseError = true } break // Hundreds place case 105: if (sender.tag == multiAppVCDelegate.calcHuns) { if ((multiAppVCDelegate.altOnesCalcThousCarry > 0) && (multiAppVCDelegate.equationSecondNum < 1000)) { multiAppVCDelegate.firstResult_LargeLbl.text = String(multiAppVCDelegate.altOnesCalcThousCarry)+String(multiAppVCDelegate.calcHuns)+String(multiAppVCDelegate.calcTens)+String(multiAppVCDelegate.calcOnes) multiAppVCDelegate.getNewProblem = 1 break } multiAppVCDelegate.firstResult_LargeLbl.text = String(format: "%1d", multiAppVCDelegate.calcHuns)+String(format: "%1d", multiAppVCDelegate.calcTens)+String(format: "%1d", multiAppVCDelegate.calcOnes) if (multiAppVCDelegate.altOnesCalcTenThousCarry == 0) { multiAppVCDelegate.inputPhase = multiAppVCDelegate.inputPhase+1 } } else { multiAppVCDelegate.responseError = true } break // Ten Thousands carry case 106: if (sender.tag == multiAppVCDelegate.calcTenThous) { multiAppVCDelegate.firstResult_LargeLbl.text = String(format: "%1d", multiAppVCDelegate.calcTenThous)+String(format: "%1d", multiAppVCDelegate.calcHuns)+String(format: "%1d", multiAppVCDelegate.calcTens)+String(format: "%1d", multiAppVCDelegate.calcOnes) } else { multiAppVCDelegate.responseError = true } break // Thousands place case 107: if (sender.tag == multiAppVCDelegate.calcThous) { if (multiAppVCDelegate.calcTenThous == 0) { // this would be a leading '0' - not good so we supress it multiAppVCDelegate.firstResult_LargeLbl.text = String(format: "%1d", multiAppVCDelegate.calcThous)+String(format: "%1d", multiAppVCDelegate.calcHuns)+String(format: "%1d", multiAppVCDelegate.calcTens)+String(format: "%1d", multiAppVCDelegate.calcOnes) } else { // print normally multiAppVCDelegate.firstResult_LargeLbl.text = String(format: "%1d", multiAppVCDelegate.calcTenThous)+String(format: "%1d", multiAppVCDelegate.calcThous)+String(format: "%1d", multiAppVCDelegate.calcHuns)+String(format: "%1d", multiAppVCDelegate.calcTens)+String(format: "%1d", multiAppVCDelegate.calcOnes) } // clean up regroup marks for next pass (tens) multiAppVCDelegate.onesCarry_LargeLbl.text = "" multiAppVCDelegate.tensCarry_LargeLbl.text = "" multiAppVCDelegate.hundredsCarry_LargeLbl.text = "" multiAppVCDelegate.thousandsCarry_LargeLbl.text = "" //Insert intial '0' for second mult row multiAppVCDelegate.secondResult_LargeLbl.text = "0" // Set start phase for second pass if (multiAppVCDelegate.altTensCalcTensCarry > 0) { multiAppVCDelegate.inputPhase = 107 } else { multiAppVCDelegate.inputPhase = 108 } } else { multiAppVCDelegate.responseError = true } break // Tens carry case 108: if (sender.tag == multiAppVCDelegate.altTensCalcTensCarry) { if ( multiAppVCDelegate.equationSecondNum > 9) { multiAppVCDelegate.tensCarry_LargeLbl.text = String(format: "%1d", multiAppVCDelegate.altTensCalcTensCarry) } else { multiAppVCDelegate.secondResult_LargeLbl.text = String(format: "%1d", multiAppVCDelegate.altTensCalcTensCarry)+multiAppVCDelegate.spaceStr } } else { multiAppVCDelegate.responseError = true } break // Ones place case 109: if (sender.tag == multiAppVCDelegate.altCalcOnes) { if ((multiAppVCDelegate.altTensCalcTensCarry > 0) && (multiAppVCDelegate.equationSecondNum < 10)) { multiAppVCDelegate.finalAnswer_LargeLbl.text = String(multiAppVCDelegate.calculatedAnswer)+"0" multiAppVCDelegate.getNewProblem = 1 break } else { multiAppVCDelegate.secondResult_LargeLbl.text = String(format: "%1d", multiAppVCDelegate.altCalcOnes)+"0" } if (multiAppVCDelegate.altTensCalcHunsCarry == 0 ) { multiAppVCDelegate.inputPhase = multiAppVCDelegate.inputPhase+1 } } else { multiAppVCDelegate.responseError = true } break // Hundreds carry case 110: if (sender.tag == multiAppVCDelegate.altTensCalcHunsCarry) { if (multiAppVCDelegate.equationSecondNum > 100) { multiAppVCDelegate.hundredsCarry_LargeLbl.text = String(format: "%1d", multiAppVCDelegate.altTensCalcHunsCarry) } else { multiAppVCDelegate.secondResult_LargeLbl.text = String(format: "%1d", multiAppVCDelegate.altTensCalcHunsCarry)+multiAppVCDelegate.spaceStr+String(format: "%1d", multiAppVCDelegate.altCalcOnes)+"0" } } else { multiAppVCDelegate.responseError = true } break // Tens place case 111: if (sender.tag == multiAppVCDelegate.altCalcTens) { if ((multiAppVCDelegate.altTensCalcHunsCarry > 0) && (multiAppVCDelegate.equationSecondNum < 100)) { multiAppVCDelegate.secondResult_LargeLbl.text = String(multiAppVCDelegate.altTensCalcHunsCarry)+String(multiAppVCDelegate.altCalcTens)+String(multiAppVCDelegate.altCalcOnes)+"0" multiAppVCDelegate.getNewProblem = 1 break } else { multiAppVCDelegate.secondResult_LargeLbl.text = String(format: "%1d", multiAppVCDelegate.altCalcTens)+String(format: "%1d", multiAppVCDelegate.altCalcOnes)+"0" } if (multiAppVCDelegate.altTensCalcThousCarry == 0) { multiAppVCDelegate.inputPhase = multiAppVCDelegate.inputPhase+1 } } else { multiAppVCDelegate.responseError = true } break // Thousands carry case 112: if (sender.tag == multiAppVCDelegate.altTensCalcThousCarry) { if (multiAppVCDelegate.equationSecondNum > 1000) { multiAppVCDelegate.thousandsCarry_LargeLbl.text = String(format: "%1d", multiAppVCDelegate.altTensCalcThousCarry) } else { multiAppVCDelegate.secondResult_LargeLbl.text = String(multiAppVCDelegate.altTensCalcThousCarry)+multiAppVCDelegate.spaceStr+String( multiAppVCDelegate.altCalcTens)+String(multiAppVCDelegate.altCalcOnes)+"0" } AudioServicesPlaySystemSound (AudioFilesConstant.kSoundFileObject.clicksoundFileObject) // key click } else { multiAppVCDelegate.responseError = true } break // Hundreds place case 113: if (sender.tag == multiAppVCDelegate.altCalcHuns) { if ((multiAppVCDelegate.altTensCalcThousCarry > 0) && (multiAppVCDelegate.equationSecondNum < 1000)) { multiAppVCDelegate.secondResult_LargeLbl.text = String(multiAppVCDelegate.altTensCalcThousCarry)+String(multiAppVCDelegate.altCalcHuns)+String(multiAppVCDelegate.altCalcTens)+String(multiAppVCDelegate.altCalcOnes)+"0" multiAppVCDelegate.getNewProblem = 1 break } multiAppVCDelegate.secondResult_LargeLbl.text = String(format: "%1d", multiAppVCDelegate.altCalcHuns)+String(format: "%1d", multiAppVCDelegate.altCalcTens)+String(format: "%1d", multiAppVCDelegate.altCalcOnes)+"0" if (multiAppVCDelegate.altTensCalcTenThousCarry == 0) { multiAppVCDelegate.inputPhase=multiAppVCDelegate.inputPhase+1 } } else { multiAppVCDelegate.responseError = true } break // Ten Thousands Carry case 114: if (sender.tag == multiAppVCDelegate.altCalcTenThous) { multiAppVCDelegate.secondResult_LargeLbl.text = String(format: "%1d", multiAppVCDelegate.altCalcTenThous)+" "+String(format: "%1d", multiAppVCDelegate.altCalcHuns)+String(format: "%1d", multiAppVCDelegate.altCalcTens)+String(format: "%1d", multiAppVCDelegate.altCalcOnes)+"0" if (multiAppVCDelegate.calculatedAnswer > 99999) { multiAppVCDelegate.inputPhase = 999 } } else { multiAppVCDelegate.responseError = true } break // Thousands place case 115: if (sender.tag == multiAppVCDelegate.altCalcThous) { if (multiAppVCDelegate.altCalcTenThous == 0) { // this would be a leading '0' - not good so we supress it multiAppVCDelegate.secondResult_LargeLbl.text = "+ "+String(format: "%1d", multiAppVCDelegate.altCalcThous)+String(format: "%1d", multiAppVCDelegate.altCalcHuns)+String(format: "%1d", multiAppVCDelegate.altCalcTens)+String(format: "%1d", multiAppVCDelegate.altCalcOnes)+"0" } else { // print normally multiAppVCDelegate.secondResult_LargeLbl.text = "+ "+String(format: "%1d", multiAppVCDelegate.altCalcTenThous)+String(format: "%1d", multiAppVCDelegate.altCalcThous)+String(format: "%1d", multiAppVCDelegate.altCalcHuns)+String(format: "%1d", multiAppVCDelegate.altCalcTens)+String(format: "%1d", multiAppVCDelegate.altCalcOnes)+"0" } // Reveal summing line multiAppVCDelegate.sumLine_LargeLbl.isHidden = false multiAppVCDelegate.finalAnswerView.isHidden = false if ( multiAppVCDelegate.altFinCalcTensCarry == 0) { multiAppVCDelegate.inputPhase = multiAppVCDelegate.inputPhase+1 } } else { multiAppVCDelegate.responseError = true } break // Final answer Tens carry case 116: if (sender.tag == multiAppVCDelegate.altFinCalcTensCarry) { if (multiAppVCDelegate.equationSecondNum > 9) { multiAppVCDelegate.sumTensCarry_LargeLbl.text = String(format: "%1d", multiAppVCDelegate.altFinCalcTensCarry) } } else { multiAppVCDelegate.responseError = true } break // Final answer ones place case 117: if (sender.tag == multiAppVCDelegate.finCalcOnes) { multiAppVCDelegate.finalAnswer_LargeLbl.text = String(format: "%1d", multiAppVCDelegate.finCalcOnes) if (multiAppVCDelegate.finalCalculatedAnswer < 10) { multiAppVCDelegate.getNewProblem = 1 } if (multiAppVCDelegate.altFinCalcHunsCarry == 0) { multiAppVCDelegate.inputPhase = multiAppVCDelegate.inputPhase+1 } } else { multiAppVCDelegate.responseError = true } break // Final answer Huns carry case 118: if (sender.tag == multiAppVCDelegate.altFinCalcHunsCarry) { multiAppVCDelegate.sumHundredsCarry_LargeLbl.text = String(format: "%1d", multiAppVCDelegate.altFinCalcHunsCarry) } else { multiAppVCDelegate.responseError = true } break // Final answer tens place case 119: if (sender.tag == multiAppVCDelegate.finCalcTens) { multiAppVCDelegate.finalAnswer_LargeLbl.text = String(format: "%1d", multiAppVCDelegate.finCalcTens)+String(format: "%1d", multiAppVCDelegate.finCalcOnes) if (multiAppVCDelegate.finalCalculatedAnswer < 100) { multiAppVCDelegate.getNewProblem = 1 } if (multiAppVCDelegate.altFinCalcThousCarry == 0) { multiAppVCDelegate.inputPhase=multiAppVCDelegate.inputPhase+1 } } else { multiAppVCDelegate.responseError = true } break // Final answer Thous carry case 120: if (sender.tag == multiAppVCDelegate.altFinCalcThousCarry) { multiAppVCDelegate.sumThousandsCarry_LargeLbl.text = String(format: "%1d", multiAppVCDelegate.altFinCalcThousCarry) } else { multiAppVCDelegate.responseError = true } break // Final answer Huns place case 121: if (sender.tag == multiAppVCDelegate.finCalcHuns) { multiAppVCDelegate.finalAnswer_LargeLbl.text = String(format: "%1d", multiAppVCDelegate.finCalcHuns)+String(format: "%1d", multiAppVCDelegate.finCalcTens)+String(format: "%1d", multiAppVCDelegate.finCalcOnes) if (multiAppVCDelegate.finalCalculatedAnswer < 1000) { multiAppVCDelegate.getNewProblem = 1 } if (multiAppVCDelegate.altFinCalcTenThousCarry == 0) { multiAppVCDelegate.inputPhase=multiAppVCDelegate.inputPhase+1 } } else { multiAppVCDelegate.responseError = true } break // Final answer Ten Thous carry case 122: if (sender.tag == multiAppVCDelegate.altFinCalcTenThousCarry) { multiAppVCDelegate.sumTenThousCarry_LargeLbl.text = String(format: "%1d", multiAppVCDelegate.altFinCalcTenThousCarry) } else { multiAppVCDelegate.responseError = true } break // Final answer Thous place case 123: if (sender.tag == multiAppVCDelegate.finCalcThous) { multiAppVCDelegate.finalAnswer_LargeLbl.text = String(format: "%1d", multiAppVCDelegate.finCalcThous)+String(format: "%1d", multiAppVCDelegate.finCalcHuns)+String(format: "%1d", multiAppVCDelegate.finCalcTens)+String(format: "%1d", multiAppVCDelegate.finCalcOnes) if (multiAppVCDelegate.finalCalculatedAnswer < 10000) { multiAppVCDelegate.getNewProblem = 1 } if (multiAppVCDelegate.altFinCalcHunThousCarry == 0) { multiAppVCDelegate.inputPhase=multiAppVCDelegate.inputPhase+1 } } else { multiAppVCDelegate.responseError = true } break // Final answer Hun Thous carry case 124: if (sender.tag == multiAppVCDelegate.altFinCalcHunThousCarry) { multiAppVCDelegate.sumHunThousCarry_LargeLbl.text = String(format: "%1d", multiAppVCDelegate.altFinCalcHunThousCarry) } else { multiAppVCDelegate.responseError = true } break // Final answer Ten Thous place case 125: if (sender.tag == multiAppVCDelegate.finCalcTenThous) { multiAppVCDelegate.finalAnswer_LargeLbl.text = String(format: "%1d", multiAppVCDelegate.finCalcTenThous)+String(format: "%1d", multiAppVCDelegate.finCalcThous)+String(format: "%1d", multiAppVCDelegate.finCalcHuns)+String(format: "%1d", multiAppVCDelegate.finCalcTens)+String(format: "%1d", multiAppVCDelegate.finCalcOnes) if (multiAppVCDelegate.finalCalculatedAnswer < 100000) { multiAppVCDelegate.getNewProblem = 1 } } else { multiAppVCDelegate.responseError = true } break // Final answer Hun Thous place case 126: if (sender.tag == multiAppVCDelegate.finCalcHunThous) { multiAppVCDelegate.finalAnswer_LargeLbl.text = String(format: "%1d", multiAppVCDelegate.finCalcHunThous)+String(format: "%1d", multiAppVCDelegate.finCalcTenThous)+String(format: "%1d", multiAppVCDelegate.finCalcThous)+String(format: "%1d", multiAppVCDelegate.finCalcHuns)+String(format: "%1d", multiAppVCDelegate.finCalcTens)+String(format: "%1d", multiAppVCDelegate.finCalcOnes) multiAppVCDelegate.getNewProblem = 1 } else { multiAppVCDelegate.responseError = true } break default: multiAppVCDelegate.responseError = true break } multiAppVCDelegate.regroupSlashesLbl.text = multiAppVCDelegate.slashThousStr+" "+multiAppVCDelegate.slashHunsStr+" "+multiAppVCDelegate.slashTensStr+" "+multiAppVCDelegate.slashOnesStr if (multiAppVCDelegate.responseError) { AppdelegateRef.appDelegate.setScore(inScore: 2) //Bump up score (up is bad) AudioServicesPlaySystemSound (AudioFilesConstant.kSoundFileObject.soundFileObject) //Quack multiAppVCDelegate.ErrorOnThisQuestion = true multiAppVCDelegate.responseError = false } else if (Bool(multiAppVCDelegate.getNewProblem as NSNumber) == true) { // Set the time it took to answer this question AppdelegateRef.appDelegate.setTime(inTime: multiAppVCDelegate.elapsedSeconds) // Timer get reset to '0' in the GetNexFact method multiAppVCDelegate.isRandom = true AudioServicesPlaySystemSound (AudioFilesConstant.kSoundFileObject.dingsoundFileObject) // Ding sound if (multiAppVCDelegate.ErrorOnThisQuestion == false && Bool(multiAppVCDelegate.getNewProblem as NSNumber) == true && (multiAppVCDelegate.questionCount > 4)) { multiAppVCDelegate.animationView.isHidden = false multiAppVCDelegate.animationImage.image = UIImage.gifImageWithData(multiAppVCDelegate.gifImagesArray[multiAppVCDelegate.selectedGifIndex]) if multiAppVCDelegate.selectedGifIndex==2 { multiAppVCDelegate.selectedGifIndex=0 } else { multiAppVCDelegate.selectedGifIndex = multiAppVCDelegate.selectedGifIndex+1 } multiAppVCDelegate.timeForNewNumbers = Timer.scheduledTimer(timeInterval: 8.1, target: multiAppVCDelegate, selector:#selector(multiAppVCDelegate.getNewNumbers), userInfo: nil, repeats: false) multiAppVCDelegate.questionCount = 0 } else { multiAppVCDelegate.timeForNewNumbers = Timer.scheduledTimer(timeInterval:2.5, target: multiAppVCDelegate, selector:#selector(multiAppVCDelegate.getNewNumbers), userInfo: nil, repeats: false) } multiAppVCDelegate.questionCount = multiAppVCDelegate.questionCount+1 multiAppVCDelegate.getNewProblem = 0 } else { AudioServicesPlaySystemSound (AudioFilesConstant.kSoundFileObject.clicksoundFileObject) // key click multiAppVCDelegate.inputPhase = multiAppVCDelegate.inputPhase+1 } let firstResultattributedString = NSMutableAttributedString(string: multiAppVCDelegate.firstResult_LargeLbl.text!) firstResultattributedString.addAttribute(NSKernAttributeName, value: CGFloat(1.0), range: NSRange(location: 0, length: firstResultattributedString.length)) multiAppVCDelegate.firstResult_LargeLbl.attributedText = firstResultattributedString let secondResultattributedString = NSMutableAttributedString(string: multiAppVCDelegate.secondResult_LargeLbl.text!) secondResultattributedString.addAttribute(NSKernAttributeName, value: CGFloat(1.0), range: NSRange(location: 0, length: secondResultattributedString.length)) multiAppVCDelegate.secondResult_LargeLbl.attributedText = secondResultattributedString let finalResultattributedString = NSMutableAttributedString(string: multiAppVCDelegate.finalAnswer_LargeLbl.text!) finalResultattributedString.addAttribute(NSKernAttributeName, value: CGFloat(1.0), range: NSRange(location: 0, length: finalResultattributedString.length)) multiAppVCDelegate.finalAnswer_LargeLbl.attributedText = finalResultattributedString } //Updating the frames for the iPhone 4 device func viewWillLayoutSubviews() { if DeviceModel.IS_IPHONE_4_OR_LESS { multiAppVCDelegate.firstView.frame = CGRect(x: multiAppVCDelegate.firstView.frame.origin.x, y: multiAppVCDelegate.firstView.frame.origin.y, width: multiAppVCDelegate.firstView.frame.size.width, height:69) multiAppVCDelegate.secondView.frame = CGRect(x: multiAppVCDelegate.secondView.frame.origin.x, y: multiAppVCDelegate.secondView.frame.origin.y, width: multiAppVCDelegate.secondView.frame.size.width, height:69) multiAppVCDelegate.thirdView.frame = CGRect(x: multiAppVCDelegate.thirdView.frame.origin.x, y: multiAppVCDelegate.thirdView.frame.origin.y, width: multiAppVCDelegate.thirdView.frame.size.width, height:69) multiAppVCDelegate.fourthView.frame = CGRect(x: multiAppVCDelegate.fourthView.frame.origin.x, y: multiAppVCDelegate.fourthView.frame.origin.y, width: multiAppVCDelegate.fourthView.frame.size.width, height:69) multiAppVCDelegate.responseCarryView.frame = CGRect(x: multiAppVCDelegate.responseCarryView.frame.origin.x+1, y: multiAppVCDelegate.responseCarryView.frame.origin.y, width: multiAppVCDelegate.responseCarryView.frame.size.width, height:multiAppVCDelegate.responseCarryView.frame.size.height) multiAppVCDelegate.popUpTitleView.frame = CGRect(x: 0, y: 0, width: DeviceModel.SCREEN_WIDTH, height: 40) multiAppVCDelegate.popUpmessageView.frame = CGRect(x: 0, y: 40, width: DeviceModel.SCREEN_WIDTH, height: 350) } } // Custom method to get the random numbers by using the level which was user selected. func getNewNumbers() { if(multiAppVCDelegate.isRandom == true) { multiAppVCDelegate.isRandom = false multiAppVCDelegate.animationView.isHidden = true multiAppVCDelegate.sumOnesCarry_LargeLbl.isHidden = false multiAppVCDelegate.onesCarryLbl.isHidden = false multiAppVCDelegate.tensCarryLbl.isHidden = false multiAppVCDelegate.hundredsCarryLbl.isHidden = false multiAppVCDelegate.thousandsCarryLbl.isHidden = false multiAppVCDelegate.answer1Lbl.isHidden = false multiAppVCDelegate.regroupSlashesLbl.isHidden = false multiAppVCDelegate.answer1View.isHidden = false multiAppVCDelegate.firstNumber_SmallLbl.isHidden = false multiAppVCDelegate.secondNumber_SmallLbl.isHidden = false multiAppVCDelegate.equationLineLbl.isHidden = false //ajay commented //multiAppVCDelegate.questionCount = multiAppVCDelegate.questionCount+1 multiAppVCDelegate.ErrorOnThisQuestion = false multiAppVCDelegate.firstNumber_LargeLbl.isHidden = true multiAppVCDelegate.secondNumber_LargeLbl.isHidden = true multiAppVCDelegate.onesCarry_LargeLbl.isHidden = true multiAppVCDelegate.tensCarry_LargeLbl.isHidden = true multiAppVCDelegate.hundredsCarry_LargeLbl.isHidden = true multiAppVCDelegate.thousandsCarry_LargeLbl.isHidden = true multiAppVCDelegate.sumOnesCarry_LargeLbl.isHidden = true multiAppVCDelegate.sumTensCarry_LargeLbl.isHidden = true multiAppVCDelegate.sumHundredsCarry_LargeLbl.isHidden = true multiAppVCDelegate.sumThousandsCarry_LargeLbl.isHidden = true multiAppVCDelegate.sumTenThousCarry_LargeLbl.isHidden = true multiAppVCDelegate.sumHunThousCarry_LargeLbl.isHidden = true multiAppVCDelegate.regroupSlashes_LargeLbl.isHidden = true multiAppVCDelegate.firstResult_LargeLbl.isHidden = true multiAppVCDelegate.secondResult_LargeLbl.isHidden = true multiAppVCDelegate.finalAnswer_LargeLbl.isHidden = true multiAppVCDelegate.finalAnswerView.isHidden = true multiAppVCDelegate.sumLine_LargeLbl.isHidden = true multiAppVCDelegate.equationLine_LargeLbl.isHidden = true multiAppVCDelegate.equationLine_LargeLbl.backgroundColor = UIColor.clear multiAppVCDelegate.finalAnswer_LargeLbl.backgroundColor = UIColor.clear var firstNum:Int = 0 var secondNum:Int = 0 var indexToRndArray:Int = 1 multiAppVCDelegate.TensCarryAlreadySet = false multiAppVCDelegate.elapsedSeconds = 0 // Reset elapsed timer //Define appDelegate objext so we can access common variables switch (multiAppVCDelegate.mfLevel) { case 0: repeat { indexToRndArray = AppdelegateRef.appDelegate.RandomNumInRange multiAppVCDelegate.equationSecondNum = AppdelegateRef.appDelegate.RandomNumSecondVal multiAppVCDelegate.equationFirstNum = AppdelegateRef.appDelegate.RandomNumFirstVal } while ((multiAppVCDelegate.equationFirstNum + multiAppVCDelegate.equationSecondNum) > 9) firstNum = multiAppVCDelegate.equationFirstNum /////////////////////////////////////////////////// <<<< KLUDGE secondNum = multiAppVCDelegate.equationSecondNum /////////////////////////////////////////////////// <<<< KLUDGE break case 1: indexToRndArray = AppdelegateRef.appDelegate.RandomNumInRange multiAppVCDelegate.equationSecondNum = AppdelegateRef.appDelegate.RandomNumSecondVal multiAppVCDelegate.equationFirstNum = AppdelegateRef.appDelegate.RandomNumFirstVal firstNum = multiAppVCDelegate.equationFirstNum /////////////////////////////////////////////////// <<<< KLUDGE secondNum = multiAppVCDelegate.equationSecondNum /////////////////////////////////////////////////// <<<< KLUDGE break case 2: // Force first num to be 2 digits firstNum = Int(((arc4random_uniform(9) + 1) * 10) + (arc4random_uniform(10))) // Force second num to be 3 digits (so not randomly smaller then first number ! secondNum = Int(((arc4random_uniform(9) + 1) * 100) + (arc4random_uniform(100))) break case 3: // Force first num to be 2 digits /// firstNum = (arc4random() % 10) firstNum = Int(((arc4random_uniform(9) + 1) * 10) + arc4random_uniform(10)) /// secondNum = (arc4random() % 1000) // Force second num to be 4 digits (so not randomly smaller then first number ! secondNum = Int(((arc4random_uniform(9) + 1) * 1000) + (arc4random_uniform(1000))) break default: break } // Check array index for absurdly large value if (indexToRndArray > 1000) { print("Index Out of Bounds") } // Ensures larger number is on top if (multiAppVCDelegate.equationFirstNum > multiAppVCDelegate.equationSecondNum) { // then reverse the order multiAppVCDelegate.equationSecondNum = AppdelegateRef.appDelegate.RandomNumFirstVal multiAppVCDelegate.equationFirstNum = AppdelegateRef.appDelegate.RandomNumSecondVal } multiAppVCDelegate.equationFirstNum = firstNum multiAppVCDelegate.equationSecondNum = secondNum // multiAppVCDelegate.equationFirstNum = 77 // multiAppVCDelegate.equationSecondNum = 1953 //NSString* mathOpp switch (multiAppVCDelegate.mfCategory) { // Math Opperation case 0: // Addition multiAppVCDelegate.mathOppStr = "+" multiAppVCDelegate.calculatedAnswer = multiAppVCDelegate.equationFirstNum + multiAppVCDelegate.equationSecondNum multiAppVCDelegate.calcTensCarry = ((multiAppVCDelegate.equationFirstNum % 10) + (multiAppVCDelegate.equationSecondNum % 10)) / 10 multiAppVCDelegate.calcHunsCarry = ((multiAppVCDelegate.equationFirstNum % 100) + (multiAppVCDelegate.equationSecondNum % 100)) / 100 multiAppVCDelegate.calcThousCarry = ((multiAppVCDelegate.equationFirstNum % 1000) + (multiAppVCDelegate.equationSecondNum % 1000)) / 1000 multiAppVCDelegate.calcTenThous = ((multiAppVCDelegate.equationFirstNum % 10000) + (multiAppVCDelegate.equationSecondNum % 10000)) / 10000 // Set initial input phase based on the randomly generated equation if (multiAppVCDelegate.calcTensCarry > 0) { multiAppVCDelegate.inputPhase = 0 } else { multiAppVCDelegate.inputPhase = 1 } break case 1: // Subtraction multiAppVCDelegate.mathOppStr = "-" // // Second number needs to be bigger than the first number // if (mfLevel == 0) equationSecondNum = (arc4random() % (10 - firstNum) + firstNum) // For Level 1, Force two digits, but don't want to regroup so 1's place digit needs to be smaller than fist number // (Ones place smaller than 1st + (Tens place not = zero. if (multiAppVCDelegate.mfLevel == 1) { multiAppVCDelegate.equationSecondNum = (10 * Int((arc4random_uniform(9)) + 1))+multiAppVCDelegate.equationSecondNum } // Precalculate discrete values multiAppVCDelegate.calculatedAnswer = multiAppVCDelegate.equationSecondNum - multiAppVCDelegate.equationFirstNum multiAppVCDelegate.equationOnes = multiAppVCDelegate.equationSecondNum % 10 multiAppVCDelegate.equationTens = (multiAppVCDelegate.equationSecondNum % 100) / 10 multiAppVCDelegate.equationHuns = (multiAppVCDelegate.equationSecondNum % 1000) / 100 multiAppVCDelegate.equationThous = (multiAppVCDelegate.equationSecondNum % 10000) / 1000 multiAppVCDelegate.firstNumOnes = multiAppVCDelegate.equationFirstNum % 10 multiAppVCDelegate.firstNumTens = (multiAppVCDelegate.equationFirstNum % 100) / 10 multiAppVCDelegate.firstNumHuns = (multiAppVCDelegate.equationFirstNum % 1000) / 100 multiAppVCDelegate.firstNumThous = (multiAppVCDelegate.equationFirstNum % 10000) / 1000 multiAppVCDelegate.calcOnesCarry = -1 multiAppVCDelegate.calcTensCarry = -1 multiAppVCDelegate.calcHunsCarry = -1 multiAppVCDelegate.calcThousCarry = -1 multiAppVCDelegate.inputPhase = 10 // Switch structure (state machine) entry point for subtraction break case 2: //Multiplication multiAppVCDelegate.mathOppStr = "×" if (multiAppVCDelegate.mfLevel == 0) { repeat { multiAppVCDelegate.equationSecondNum = Int(arc4random_uniform(9) + 1) } while (multiAppVCDelegate.equationSecondNum * multiAppVCDelegate.equationFirstNum > 10) } if (multiAppVCDelegate.mfLevel == 2) { // Force first num to be 1 digits multiAppVCDelegate.equationFirstNum = (Int(arc4random_uniform(10))) } // Seperate multipler into its ones and tens component if (multiAppVCDelegate.equationFirstNum > 9) { multiAppVCDelegate.equationMultiplierOnes = multiAppVCDelegate.equationFirstNum % 10 multiAppVCDelegate.equationMultiplierTens = multiAppVCDelegate.equationFirstNum / 10 } else { multiAppVCDelegate.equationMultiplierOnes = multiAppVCDelegate.equationFirstNum } multiAppVCDelegate.calculatedAnswer = multiAppVCDelegate.equationFirstNum * multiAppVCDelegate.equationSecondNum multiAppVCDelegate.calcTensCarry = ((multiAppVCDelegate.equationFirstNum % 10) * (multiAppVCDelegate.equationSecondNum % 10)) / 10 multiAppVCDelegate.calcHunsCarry = ((multiAppVCDelegate.equationFirstNum % 100) * (multiAppVCDelegate.equationSecondNum % 100)) / 100 multiAppVCDelegate.calcThousCarry = ((multiAppVCDelegate.equationFirstNum % 1000) * (multiAppVCDelegate.equationSecondNum % 1000)) / 1000 // Set initial input phase based on the size of the randomly generated equation if (multiAppVCDelegate.calcTensCarry > 0) { multiAppVCDelegate.inputPhase = 0 } else { multiAppVCDelegate.inputPhase = 1 } if (multiAppVCDelegate.mfLevel == 3) { multiAppVCDelegate.pageControl.frame = CGRect(x: multiAppVCDelegate.pageControl.frame.origin.x, y: multiAppVCDelegate.applyFactsLbl.frame.origin.y+multiAppVCDelegate.applyFactsLbl.frame.size.height+5, width: multiAppVCDelegate.pageControl.frame.size.width, height: 5) multiAppVCDelegate.onesCarryLbl.isHidden = true multiAppVCDelegate.tensCarryLbl.isHidden = true multiAppVCDelegate.hundredsCarryLbl.isHidden = true multiAppVCDelegate.thousandsCarryLbl.isHidden = true multiAppVCDelegate.answer1Lbl.isHidden = true multiAppVCDelegate.regroupSlashesLbl.isHidden = true multiAppVCDelegate.answer1View.isHidden = true multiAppVCDelegate.firstNumber_SmallLbl.isHidden = true multiAppVCDelegate.secondNumber_SmallLbl.isHidden = true multiAppVCDelegate.equationLineLbl.isHidden = true multiAppVCDelegate.firstNumber_LargeLbl.isHidden = false multiAppVCDelegate.secondNumber_LargeLbl.isHidden = false multiAppVCDelegate.onesCarry_LargeLbl.isHidden = false multiAppVCDelegate.tensCarry_LargeLbl.isHidden = false multiAppVCDelegate.hundredsCarry_LargeLbl.isHidden = false multiAppVCDelegate.thousandsCarry_LargeLbl.isHidden = false multiAppVCDelegate.sumOnesCarry_LargeLbl.isHidden = false multiAppVCDelegate.sumTensCarry_LargeLbl.isHidden = false multiAppVCDelegate.sumHundredsCarry_LargeLbl.isHidden = false multiAppVCDelegate.sumThousandsCarry_LargeLbl.isHidden = false multiAppVCDelegate.sumTenThousCarry_LargeLbl.isHidden = false multiAppVCDelegate.sumHunThousCarry_LargeLbl.isHidden = false multiAppVCDelegate.regroupSlashes_LargeLbl.isHidden = false multiAppVCDelegate.firstResult_LargeLbl.isHidden = false multiAppVCDelegate.secondResult_LargeLbl.isHidden = false multiAppVCDelegate.finalAnswer_LargeLbl.isHidden = false //multiAppVCDelegate.finalAnswerView.isHidden = false multiAppVCDelegate.equationLine_LargeLbl.isHidden = false multiAppVCDelegate.calculatedAnswer = multiAppVCDelegate.equationMultiplierOnes * multiAppVCDelegate.equationSecondNum multiAppVCDelegate.altOnesCalcTensCarry = ((multiAppVCDelegate.equationMultiplierOnes % 10) * (multiAppVCDelegate.equationSecondNum % 10)) / 10 multiAppVCDelegate.altOnesCalcHunsCarry = ((multiAppVCDelegate.equationMultiplierOnes % 100) * (multiAppVCDelegate.equationSecondNum % 100)) / 100 multiAppVCDelegate.altOnesCalcThousCarry = ((multiAppVCDelegate.equationMultiplierOnes % 1000) * (multiAppVCDelegate.equationSecondNum % 1000)) / 1000 multiAppVCDelegate.altOnesCalcTenThousCarry = ((multiAppVCDelegate.equationMultiplierOnes % 10000) * (multiAppVCDelegate.equationSecondNum % 10000)) / 10000 multiAppVCDelegate.altTensCalculatedAnswer = multiAppVCDelegate.equationMultiplierTens * multiAppVCDelegate.equationSecondNum multiAppVCDelegate.altTensCalcTensCarry = ((multiAppVCDelegate.equationMultiplierTens % 10) * (multiAppVCDelegate.equationSecondNum % 10)) / 10 multiAppVCDelegate.altTensCalcHunsCarry = ((multiAppVCDelegate.equationMultiplierTens % 100) * (multiAppVCDelegate.equationSecondNum % 100)) / 100 multiAppVCDelegate.altTensCalcThousCarry = ((multiAppVCDelegate.equationMultiplierTens % 1000) * (multiAppVCDelegate.equationSecondNum % 1000)) / 1000 multiAppVCDelegate.altTensCalcTenThousCarry = ((multiAppVCDelegate.equationMultiplierTens % 10000) * (multiAppVCDelegate.equationSecondNum % 10000)) / 10000 multiAppVCDelegate.finalCalculatedAnswer = multiAppVCDelegate.equationFirstNum * multiAppVCDelegate.equationSecondNum multiAppVCDelegate.altFinCalcTensCarry = ((multiAppVCDelegate.calculatedAnswer % 10) + ((multiAppVCDelegate.altTensCalculatedAnswer * 10) % 10)) / 10 multiAppVCDelegate.altFinCalcHunsCarry = ((multiAppVCDelegate.calculatedAnswer % 100) + ((multiAppVCDelegate.altTensCalculatedAnswer * 10) % 100)) / 100 multiAppVCDelegate.altFinCalcThousCarry = ((multiAppVCDelegate.calculatedAnswer % 1000) + ((multiAppVCDelegate.altTensCalculatedAnswer * 10) % 1000)) / 1000 multiAppVCDelegate.altFinCalcTenThousCarry = ((multiAppVCDelegate.calculatedAnswer % 10000) + ((multiAppVCDelegate.altTensCalculatedAnswer * 10) % 10000)) / 10000 multiAppVCDelegate.altFinCalcHunThousCarry = ((multiAppVCDelegate.calculatedAnswer % 100000) + ((multiAppVCDelegate.altTensCalculatedAnswer * 10) % 100000)) / 100000 // Set initial input phase based on the randomly generated equation if (multiAppVCDelegate.altOnesCalcTensCarry > 0){ multiAppVCDelegate.inputPhase = 100 } else { multiAppVCDelegate.inputPhase = 101 } } break case 3: // Division // Division is handled in it's own view break default: break } // Bottom of equation let countStr = NSMutableAttributedString(string: multiAppVCDelegate.mathOppStr,attributes: [NSFontAttributeName:UIFont(name: "SFNS Display", size: 40.0)!]) countStr.addAttribute(NSForegroundColorAttributeName, value: UIColor(red: 13.0/255.0, green: 44.0/255.0, blue: 66.0/255.0, alpha: 1.0), range: NSRange(location:0,length:(multiAppVCDelegate.mathOppStr.characters.count))) //let str = NSMutableAttributedString() countStr.append(NSMutableAttributedString(string: " ")) countStr.append(NSMutableAttributedString(string: String(multiAppVCDelegate.equationFirstNum))) /*if String(multiAppVCDelegate.equationFirstNum).characters.count == 1 { let paragraph = NSMutableParagraphStyle() paragraph.alignment = .center countStr.addAttributes([NSParagraphStyleAttributeName: paragraph], range: NSMakeRange(0, countStr.length)) }*/ multiAppVCDelegate.firstNumber_SmallLbl.attributedText = countStr // multiAppVCDelegate.multiplierLbl.text = multiAppVCDelegate.mathOpp+" "+String(multiAppVCDelegate.equationFirstNum) multiAppVCDelegate.firstNumber_LargeLbl.text = multiAppVCDelegate.mathOppStr+" "+String(multiAppVCDelegate.equationFirstNum) // Top of equation /*if String(multiAppVCDelegate.equationSecondNum).characters.count == 1 { multiAppVCDelegate.secondNumber_SmallLbl.textAlignment = .center multiAppVCDelegate.secondNumber_SmallLbl.text = " "+String(multiAppVCDelegate.equationSecondNum) } else{*/ multiAppVCDelegate.secondNumber_SmallLbl.text = String(multiAppVCDelegate.equationSecondNum) // } multiAppVCDelegate.secondNumber_LargeLbl.text = String(multiAppVCDelegate.equationSecondNum) // Calculate response digits multiAppVCDelegate.calcOnes = multiAppVCDelegate.calculatedAnswer % 10 multiAppVCDelegate.calcTens = (multiAppVCDelegate.calculatedAnswer / 10) % 10 multiAppVCDelegate.calcHuns = (multiAppVCDelegate.calculatedAnswer / 100) % 10 multiAppVCDelegate.calcThous = (multiAppVCDelegate.calculatedAnswer / 1000) % 10 multiAppVCDelegate.calcTenThous = (multiAppVCDelegate.calculatedAnswer / 10000) % 10 // Calculate alt response digits multiAppVCDelegate.altCalcOnes = multiAppVCDelegate.altTensCalculatedAnswer % 10 multiAppVCDelegate.altCalcTens = (multiAppVCDelegate.altTensCalculatedAnswer / 10) % 10 multiAppVCDelegate.altCalcHuns = (multiAppVCDelegate.altTensCalculatedAnswer / 100) % 10 multiAppVCDelegate.altCalcThous = (multiAppVCDelegate.altTensCalculatedAnswer / 1000) % 10 multiAppVCDelegate.altCalcTenThous = (multiAppVCDelegate.altTensCalculatedAnswer / 10000) % 10 // Calculate final summation digits multiAppVCDelegate.finCalcOnes = multiAppVCDelegate.finalCalculatedAnswer % 10 multiAppVCDelegate.finCalcTens = (multiAppVCDelegate.finalCalculatedAnswer / 10) % 10 multiAppVCDelegate.finCalcHuns = (multiAppVCDelegate.finalCalculatedAnswer / 100) % 10 multiAppVCDelegate.finCalcThous = (multiAppVCDelegate.finalCalculatedAnswer / 1000) % 10 multiAppVCDelegate.finCalcTenThous = (multiAppVCDelegate.finalCalculatedAnswer / 10000) % 10 multiAppVCDelegate.finCalcHunThous = (multiAppVCDelegate.finalCalculatedAnswer / 100000) % 10 // Clear old values multiAppVCDelegate.onesCarryLbl.text = "" multiAppVCDelegate.tensCarryLbl.text = "" multiAppVCDelegate.hundredsCarryLbl.text = "" multiAppVCDelegate.thousandsCarryLbl.text = "" multiAppVCDelegate.answer1Lbl.text = "" multiAppVCDelegate.regroupSlashesLbl.text = "" multiAppVCDelegate.onesCarry_LargeLbl.text = "" multiAppVCDelegate.tensCarry_LargeLbl.text = "" multiAppVCDelegate.hundredsCarry_LargeLbl.text = "" multiAppVCDelegate.thousandsCarry_LargeLbl.text = "" multiAppVCDelegate.sumOnesCarry_LargeLbl.text = "" multiAppVCDelegate.sumTensCarry_LargeLbl.text = "" multiAppVCDelegate.sumHundredsCarry_LargeLbl.text = "" multiAppVCDelegate.sumThousandsCarry_LargeLbl.text = "" multiAppVCDelegate.sumTenThousCarry_LargeLbl.text = "" multiAppVCDelegate.sumHunThousCarry_LargeLbl.text = "" multiAppVCDelegate.finalAnswer_LargeLbl.text = "" multiAppVCDelegate.firstResult_LargeLbl.text = "" multiAppVCDelegate.secondResult_LargeLbl.text = "" multiAppVCDelegate.regroupSlashes_LargeLbl.text = "" // Clear regroup slashes multiAppVCDelegate.slashOnesStr = " " multiAppVCDelegate.slashTensStr = " " multiAppVCDelegate.slashHunsStr = " " multiAppVCDelegate.slashThousStr = " " } } // MARK:- Custom button actions // Custom method to show information about the functionalty of the view controller in an alert. func showApplicationInfo() { multiAppVCDelegate.alertPopOverView.isHidden = false } // Custom method to present the menu view controller to select the range, category and the level. func showMenuView() { let nextVC = StoryBoards.kMainStoryBoard.instantiateViewController(withIdentifier: ViewControllerIdentifiers.kMenuVC) as! MenuViewController multiAppVCDelegate.present(nextVC, animated: true, completion: nil) } //MARK:- Custom Methods for Swipe // Custom method to present `Speed Drill ViewController` when user swipes to left side. func handleSwipeLeft(recognizer:UISwipeGestureRecognizer) { let nextVC = StoryBoards.kMainStoryBoard.instantiateViewController(withIdentifier: ViewControllerIdentifiers .kSpeedDrilVC) as! MultiSpeedDrillViewController nextVC.modalTransitionStyle = .flipHorizontal AppdelegateRef.appDelegate.islaunch = false multiAppVCDelegate.present(nextVC, animated: true, completion: nil) AudioServicesPlaySystemSound(AudioFilesConstant.kSoundFileObject.wooshsoundFileObject) multiAppVCDelegate.isRandom = true } // Custom method to present `Mathfacts ViewController` when user swipes to right side. func handleSwipeRight(recognizer:UISwipeGestureRecognizer) { let nextVC = StoryBoards.kMainStoryBoard.instantiateViewController(withIdentifier: ViewControllerIdentifiers .kMathFactsVC) as! MathFactsViewController nextVC.modalTransitionStyle = .flipHorizontal AppdelegateRef.appDelegate.islaunch = false multiAppVCDelegate.present(nextVC, animated: true, completion: nil) AudioServicesPlaySystemSound(AudioFilesConstant.kSoundFileObject.wooshsoundFileObject) multiAppVCDelegate.isRandom = true } // Custom method to present `LongDivision ViewController` if the category is 3 when user swipes to up side or it will present the new numbers. func handleSwipeUp(recognizer:UISwipeGestureRecognizer) { multiAppVCDelegate.mfCategory = multiAppVCDelegate.mfCategory+1 if (multiAppVCDelegate.mfCategory > 3) { // // Wrap through Add > Sub > Mult > Div > and around to Add... multiAppVCDelegate.mfCategory = 0; } AppdelegateRef.appDelegate.setMathFactsCatagory(newCatagory: multiAppVCDelegate.mfCategory) self.flashIcon() /// to flash up the new math operator sign briefly if (multiAppVCDelegate.mfCategory == 3) { let nextVC = StoryBoards.kMainStoryBoard.instantiateViewController(withIdentifier: ViewControllerIdentifiers.kLongDivisionVC) as! LongDivisionViewController nextVC.questionCount = multiAppVCDelegate.questionCount nextVC.selectedGifIndex = multiAppVCDelegate.selectedGifIndex nextVC.modalTransitionStyle = .crossDissolve multiAppVCDelegate.present(nextVC, animated: true, completion: nil) } else { // Start timer to get new numbers multiAppVCDelegate.timeForNewNumbers = Timer.scheduledTimer(timeInterval: 0.5, target: multiAppVCDelegate, selector: #selector(multiAppVCDelegate.getNewNumbers), userInfo: nil, repeats: false) } multiAppVCDelegate.isRandom = true } // Custom method to present `LongDivision ViewController` if the category is 3 when user swipes to down side or it will present the new numbers. func handleSwipeDown(recognizer:UISwipeGestureRecognizer) { multiAppVCDelegate.mfCategory = multiAppVCDelegate.mfCategory-1; if (multiAppVCDelegate.mfCategory < 0) { // Wrap through Add > Sub > Mult > Div > and around to Add... multiAppVCDelegate.mfCategory = 3; } AppdelegateRef.appDelegate.setMathFactsCatagory(newCatagory: multiAppVCDelegate.mfCategory) self.flashIcon() if (multiAppVCDelegate.mfCategory == 3) { let nextVC = StoryBoards.kMainStoryBoard.instantiateViewController(withIdentifier: ViewControllerIdentifiers.kLongDivisionVC) as! LongDivisionViewController nextVC.questionCount = multiAppVCDelegate.questionCount nextVC.selectedGifIndex = multiAppVCDelegate.selectedGifIndex nextVC.modalTransitionStyle = .crossDissolve multiAppVCDelegate.present(nextVC, animated: true, completion: nil) } else { // Start timer to get new numbers multiAppVCDelegate.timeForNewNumbers = Timer.scheduledTimer(timeInterval: 0.5, target: multiAppVCDelegate, selector: #selector(multiAppVCDelegate.getNewNumbers), userInfo: nil, repeats: false) } multiAppVCDelegate.isRandom = true } // This function is called whe home button is clicked func homeButtonAction(sender: UIButton) { let nextVC = StoryBoards.kMainStoryBoard.instantiateViewController(withIdentifier: ViewControllerIdentifiers .kMathFactsVC) as! MathFactsViewController AppdelegateRef.appDelegate.islaunch = true multiAppVCDelegate.present(nextVC, animated: false, completion: nil) AudioServicesPlaySystemSound(AudioFilesConstant.kSoundFileObject.wooshsoundFileObject) multiAppVCDelegate.isRandom = true } }
// // StdSocketTests.swift // StdSocket // // Created by Bernardo Breder. // // import XCTest @testable import StdSocketTests XCTMain([ ])
// // GenericXMLElement.swift // // Created by Denis Bystruev on 14/09/2019. // struct GenericXMLElement: XMLElement { var attributes: [String: String] var characters = "" var children: [XMLElement] var elementName: String init( attributes: [String: String] = [:], characters: String = "", children: [XMLElement] = [], elementName: String ) { self.attributes = attributes self.characters = characters self.children = children self.elementName = elementName } mutating func addChild(_ child: XMLElement) { children.append(child) } }
// // ViewController.swift // CompatibilitySlider // // Created by Jay Strawn on 6/16/20. // Copyright © 2020 Jay Strawn. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var compatibilityItemLabel: UILabel! @IBOutlet weak var slider: UISlider! @IBOutlet weak var questionLabel: UILabel! @IBOutlet weak var emo4: UIImageView! @IBOutlet weak var emo3: UIImageView! @IBOutlet weak var emo2: UIImageView! @IBOutlet weak var emo1: UIImageView! @IBOutlet weak var emo0: UIImageView! var compatibilityItems = ["Koala", "Dingo", "Kangaroo", "Wombat"] var currentItemIndex = 0 var isIndexInRange:Bool { currentItemIndex < compatibilityItems.count } var person1 = Person(id: 1, items: [:]) var person2 = Person(id: 2, items: [:]) var currentPerson: Person? var isperson1DonePlaying = false var isperson2DonePlaying = false override func viewDidLoad() { super.viewDidLoad() setupImageTap() startCompatibility() } @IBAction func didPressNextItemButton(_ sender: Any) { saveScore() } } // extension for app logic extension ViewController { /** Function to calculate calculate Compatibility for player 1 & player 2 - Returns: String percentage for Compatibility calculate **/ func calculateCompatibility() -> String { // If diff 0.0 is 100% and 5.0 is 0%, calculate match percentage var percentagesForAllItems: [Double] = [] for (key, person1Rating) in person1.items { let person2Rating = person2.items[key] ?? 0 let difference = abs(person1Rating - person2Rating) / 5.0 percentagesForAllItems.append(Double(difference)) } let sumOfAllPercentages = percentagesForAllItems.reduce(0, +) let matchPercentage = sumOfAllPercentages / Double(compatibilityItems.count) let matchString = 100 - (matchPercentage * 100).rounded() return "\(matchString)%" } /** Function to start Compatibility game flow **/ func startCompatibility() { self.currentItemIndex = 0 isperson1DonePlaying = false isperson2DonePlaying = false startCompatibilityRound() } /** Function to start Compatibility rounds for player 1 and player 2 **/ func startCompatibilityRound() { if !isperson1DonePlaying { currentPerson = person1 } else { currentPerson = person2 } if isIndexInRange { updateView(currentItemIndex) } else { saveScore() } } /** Function to update view based on the current index fo the compatibilityItems array **/ func updateView(_ currentItemIndex: Int) { slider.value = 3 UIView.transition( with: compatibilityItemLabel, duration: 1, options: .transitionFlipFromBottom, animations: { [weak self] in self?.compatibilityItemLabel.text = self?.compatibilityItems[currentItemIndex] }, completion: nil) if !isperson1DonePlaying { questionLabel.text = "Player 1, what do you think about.." } else { questionLabel.text = "Player 2, what do you think about.." } } /** Function to save player score **/ func saveScore() { if isIndexInRange { let currentItem = compatibilityItems[currentItemIndex] currentPerson?.items.updateValue(slider.value, forKey: currentItem) currentItemIndex += 1 startCompatibilityRound() } else { switch (isperson1DonePlaying, isperson2DonePlaying) { case (false, false): isperson1DonePlaying = true currentItemIndex = 0 startCompatibilityRound() case (true, false): isperson2DonePlaying = true currentItemIndex = 0 Alert.showBasic(title: "Results", message: "you two are \(calculateCompatibility()) compatible", vc: self) startCompatibility() default: Alert.showBasic(title: "Logic Error", message: "Please contact Developer", vc: self) } } } } // extension for emoji tap Gesture functions extension ViewController { /** Function to determine which emoji was touched using tag number and move the slider by the values below **/ @objc func imageTapped(tapGestureRecognizer: UITapGestureRecognizer) { let emo = tapGestureRecognizer.view as! UIImageView switch emo.tag { case 0: slider.value = 5 case 1: slider.value = 4 case 2: slider.value = 3 case 3: slider.value = 2 case 4: slider.value = 1 default: Alert.showBasic(title: "Logic Error", message: "Please contact Developer", vc: self) } } /** Function to add tap Gesture Recognizer to each emoji **/ fileprivate func setupImageTap() { let tapGestureRecognizer4 = UITapGestureRecognizer(target: self, action: #selector(imageTapped(tapGestureRecognizer:))) let tapGestureRecognizer3 = UITapGestureRecognizer(target: self, action: #selector(imageTapped(tapGestureRecognizer:))) let tapGestureRecognizer2 = UITapGestureRecognizer(target: self, action: #selector(imageTapped(tapGestureRecognizer:))) let tapGestureRecognizer1 = UITapGestureRecognizer(target: self, action: #selector(imageTapped(tapGestureRecognizer:))) let tapGestureRecognizer0 = UITapGestureRecognizer(target: self, action: #selector(imageTapped(tapGestureRecognizer:))) emo4.isUserInteractionEnabled = true emo4.addGestureRecognizer(tapGestureRecognizer4) emo3.isUserInteractionEnabled = true emo3.addGestureRecognizer(tapGestureRecognizer3) emo2.isUserInteractionEnabled = true emo2.addGestureRecognizer(tapGestureRecognizer2) emo1.isUserInteractionEnabled = true emo1.addGestureRecognizer(tapGestureRecognizer1) emo0.isUserInteractionEnabled = true emo0.addGestureRecognizer(tapGestureRecognizer0) } }
// // ExerciseRowView.swift // Portfolio // // Created by LouR on 12/9/20. // import SwiftUI struct ExerciseRowView: View { @ObservedObject var exercise: Exercise var body: some View { NavigationLink(destination: EditExerciseView(exercise: exercise)) { Text(exercise.exerciseTitle) } } } struct ExerciseRowView_Previews: PreviewProvider { static var previews: some View { ExerciseRowView(exercise: Exercise.example) } }
// // ViewController.swift // Slider-Game // // Created by Kaio on 1/17/18. // Copyright © 2018 Kaio. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var sliderVal: UISlider!//value of the slider @IBOutlet weak var NumberToMatch: UILabel!//this label shows the rand number to match @IBOutlet weak var rounds: UILabel!//keeps track of the rounds @IBOutlet weak var scoreValue: UILabel!//keep track of score var randomNumber = 0;//number to be put in the NumberToMatch label for user to match it var count: Int = 0;//keeps track of the rounds //innate function when app launches override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. startNewRound()//generates number to match } //innate function override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //This function will refresh the whole game starting at Round 1 @IBAction func refresh(_ sender: Any) { count = 0//reset count (rounds) startNewRound()//call function } //generates the random number to match func startNewRound(){ //random number repeat { randomNumber = Int(arc4random_uniform(97) + 2)//nums from 2 to 98 } while randomNumber == 50 //reset slider value to 50 sliderVal.value = Float(50) //call the function below updateLabels() } //This function updates the labels Score, round and number to match func updateLabels() { //The number above to match NumberToMatch.text = "\(randomNumber)" //Rounds count += 1 rounds.text = "\(count)" //Score if(count == 1){ scoreValue.text = String(0) } } //Action button Hit me! if match, displays a message then generates a new num, keeps track //of score and the rounds @IBAction func matchNumber(_ sender: Any) { //inside the statements we call two functions //updateScore and alertMessage if(Int(NumberToMatch.text!) == Int(sliderVal.value)){ updateScore(score: 100) alertMessage(titleText: "You got it!", messageText: "You scored \(Int(sliderVal.value))") print("you got it!") } else if(abs(Int(sliderVal.value)-Int(NumberToMatch.text!)!) > 5){ updateScore(score: 100 - abs(Int(sliderVal.value)-Int(NumberToMatch.text!)!)) alertMessage(titleText: "Not even close!", messageText: "You scored \(Int(sliderVal.value))") print("Not even close!") } else { updateScore(score: 100 - abs(Int(sliderVal.value)-Int(NumberToMatch.text!)!)) alertMessage(titleText: "You almost had it!", messageText: "You scored \(Int(sliderVal.value))") print("You almost had it!") } } //this func updates the score func updateScore(score: Int){ scoreValue.text = "\(score + Int(scoreValue.text!)!)" } //This function will show the pop up for a match or not a match func alertMessage(titleText: String, messageText: String){ let alertController = UIAlertController(title: titleText, message: messageText, preferredStyle: UIAlertControllerStyle.alert) let action = UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: { (UIAlertAction) in self.startNewRound()//call to generate new num and update score and rounds }) alertController.addAction(action) self.present(alertController, animated: true, completion: nil) } }
// // LoginController.swift // Budgetal // // Created by Dillon Hafer on 6/12/15. // Copyright (c) 2015 Budgetal. All rights reserved. // import Foundation import UIKit struct Login { var email: String var password: String func valid() -> Bool { return email != "" && password != "" ? true : false } func authorize() { println("Email: \(email)") println("Password: \(password)") } } class LoginController: UIViewController { @IBOutlet weak var submitButton: UIButton! @IBOutlet weak var emailField: UITextField! @IBOutlet weak var passwordField: UITextField! @IBOutlet weak var errorMessage: UILabel! override func viewDidLoad() { super.viewDidLoad() submitButton.layer.cornerRadius = 5.0; } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func sendLogin(sender: UIButton) { var login = Login(email: emailField.text, password: passwordField.text) if login.valid() { login.authorize() hideErrors() } else { showErrors() } } func showErrors() { var red : UIColor = UIColor.redColor() errorMessage.hidden = false emailField.layer.borderColor = red.CGColor emailField.layer.borderWidth = 1.0; emailField.layer.cornerRadius = 5.0; passwordField.layer.borderColor = red.CGColor passwordField.layer.borderWidth = 1.0; passwordField.layer.cornerRadius = 5.0; } func hideErrors() { var color : UIColor = UIColor.grayColor() errorMessage.hidden = true emailField.layer.borderColor = color.CGColor passwordField.layer.borderColor = color.CGColor } }
import Foundation public enum ShellError: Error { case fatal(Int, String, String) case badOS(String) } public protocol Shell { func run(command: String, arguments: [String]) throws -> String } struct ProcessShell: Shell { public func run(command: String, arguments: [String]) throws -> String { let process = Process() process.launchPath = command process.arguments = arguments let output = Pipe() let error = Pipe() process.standardOutput = output process.standardError = error #if os(OSX) guard #available(OSX 10.13, *) else { throw ShellError.badOS("Uses APIs unavailable on OS X 10.12 or earlier (before High Sierra)") } try process.run() #else try process.run() #endif process.waitUntilExit() let stdout = String(data: output.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) ?? "" let stderr = String(data: error.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) ?? "" guard process.terminationStatus == 0 else { throw ShellError.fatal(Int(process.terminationStatus), stdout, stderr) } return stdout } }
// // NewsFeedViewController.swift // Showcase // // Created by Thi Danny on 2/17/16. // Copyright © 2016 Spawn Camping Panda. All rights reserved. // import UIKit import Firebase class NewsFeedViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { // MARK: - Outlets - @IBOutlet weak var tableView: UITableView! // MARK: - Properties - let newsFeed = NewsFeed() // MARK: - View Controller Life-cycle - override func viewDidLoad() { super.viewDidLoad() setUpTableView() setUpObservers() getData() } private func getData() { newsFeed.getNewsFeedData() } private func setUpTableView() { tableView.delegate = self tableView.dataSource = self tableView.separatorStyle = .None tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 265 } private func setUpObservers() { NSNotificationCenter.defaultCenter().addObserver(self, selector: "updateTable", name: Keys_Notification.updateTableView, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "updateTable", name: Keys_Notification.userObjectCreated, object: nil) } func updateTable() { self.tableView.reloadData() } //MARK: - TableView - func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let postCell = tableView.dequeueReusableCellWithIdentifier("PostCell") as! PostCell postCell.tag = indexPath.row postCell.post = newsFeed.posts[indexPath.row] let tapGesture = UITapGestureRecognizer(target: self, action: Selector("heartTapped:")) postCell.likesImage.addGestureRecognizer(tapGesture) // check likes to see if this user has liked this post return postCell } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return newsFeed.posts.count } func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool { return false } // MARK: - UITapGestureRecognizer func heartTapped(tapRecognizer: UITapGestureRecognizer) { print("heart tapped") if let likesImageView = tapRecognizer.view as? UIImageView { // this should check if the likes dictionary has the user ID if likesImageView.image == UIImage(named: "heart-empty.png") { // add like likesImageView.image = UIImage(named: "heart-full.png") } else { likesImageView.image = UIImage(named: "heart-empty") } } } }
// Checks for palindrome using built-in reverse function func is_palindrome(s: String) -> (Bool) { let reverse = String(s.characters.reverse()) if reverse == s{ return (true) } else { return (false) } }
import UIKit import PlaygroundSupport /*: ### Scale To Fill This is the default mode. The image is stretched in both dimensions to fill the frame. The aspect ratio of the image is not maintained. */ let myView = StarView(frame: CGRect(x: 0, y: 0, width:200, height:350)) myView.starImageView.contentMode = .scaleToFill myView PlaygroundPage.current.liveView = myView //: [Previous](@previous) //: [Index](contentMode) //: [Next](@next)
// // Country.swift // d2020 // // Created by MacBook Pro on 3/3/20. // Copyright © 2020 rahma. All rights reserved. // import UIKit struct SubCategoryModel: Codable { var status: Bool? var Categories: [Data]? struct Data: Codable { var id: Int? var name: String? var seen: Int? var desc: String? var image: String? } }
import Foundation import CoreLocation import GEOSwift import AVFoundation import Repeat /** A polygonal geographic zone within which an ambient audio stream broadcasts continuously to listeners. Speakers can overlap, causing their audio to be mixed together accordingly. Volume attenuation happens linearly over a specified distance from the edge of the Speaker’s defined zone. */ public class Speaker: Codable { private static let fadeDuration: Float = 3.0 let id: Int let url: String let backupUrl: String let attenuationDistance: Double private let minVolume: Float private let maxVolume: Float var volume: ClosedRange<Float> { return minVolume...maxVolume } let shape: Geometry let attenuationBorder: Geometry private var player: AVPlayer? = nil private var looper: Any? = nil private var fadeTimer: Repeater? = nil enum CodingKeys: String, CodingKey { case id case shape case url = "uri" case backupUrl = "backupuri" case minVolume = "minvolume" case maxVolume = "maxvolume" case attenuationDistance = "attenuation_distance" case attenuationBorder = "attenuation_border" } } extension Speaker { func contains(_ point: CLLocation) -> Bool { return try! point.toWaypoint().isWithin(shape) } private func attenuationShapeContains(_ point: CLLocation) -> Bool { return try! point.toWaypoint().isWithin(attenuationBorder.convexHull()) } public func distance(to loc: CLLocation) -> Double { let pt = loc.toWaypoint() if try! pt.isWithin(shape) { return 0.0 } else { return shape.distanceInMeters(to: loc) } } private func attenuationRatio(at loc: CLLocation) -> Double { let distToInnerShape = attenuationBorder.distanceInMeters(to: loc) print("distance to speaker \(id): \(distToInnerShape) m") return 1 - (distToInnerShape / attenuationDistance) } func volume(at point: CLLocation) -> Float { if attenuationShapeContains(point) { return volume.upperBound } else if contains(point) { let range = volume.difference return volume.lowerBound + range * Float(attenuationRatio(at: point)) } else { return volume.lowerBound } } /** - returns: whether we're within range of the speaker */ @discardableResult func updateVolume(at point: CLLocation) -> Float { let vol = self.volume(at: point) return self.updateVolume(vol) } @discardableResult func updateVolume(_ vol: Float) -> Float { if vol > 0.05 { // definitely want to create the player if it needs volume if self.player == nil { player = AVPlayer(url: URL(string: url)!) looper = looper ?? NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: player!.currentItem, queue: .main) { [weak self] _ in self?.player?.seek(to: CMTime.zero) self?.player?.play() } } // make sure this speaker is playing if it needs to be audible if player!.rate == 0.0 && RWFramework.sharedInstance.isPlaying { player!.play() } } fadeTimer?.removeAllObservers(thenStop: true) if let player = self.player { let totalDiff = vol - player.volume let delta: Float = 0.075 fadeTimer = .every(.seconds(Double(delta))) { timer in let currDiff = vol - player.volume if currDiff.sign != totalDiff.sign || abs(currDiff) < 0.05 { // we went just enough or too far player.volume = vol if vol < 0.05 { // we can't hear it anymore, so pause it. player.pause() } timer.removeAllObservers(thenStop: true) } else { player.volume += totalDiff * delta / Speaker.fadeDuration } } } return vol } func resume() { player?.play() } func pause() { player?.pause() } }
// // ViewController.swift // TimerTime // // Created by E.Piper on 12/17/19. // Copyright © 2019 E.Piper. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } //did the push work? //v2 }
import Foundation /// An Alternative is an `Applicative` with `MonoidK` capabilities. public protocol Alternative: Applicative, MonoidK {}
// // IntroViewController.swift // SOSHospital // // Created by William kwong huang on 31/10/15. // Copyright © 2015 Quaddro. All rights reserved. // import UIKit /// /// ViewController para o carregamento das informações iniciais do app /// class IntroViewController: UIViewController { private var identifierSegue = "principalSegue" private var context = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext private var hospitalData = Hospital() override func viewDidLoad() { super.viewDidLoad() } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) // Caso o CoreData nao tenha dados, faz a primeira carga if hospitalData.findHospitals(context).count <= 0 { print("Carregando dados!") // Inicia o bloco assincrono em background dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) { if let arquivoJSON = NSBundle.mainBundle().URLForResource("data", withExtension: "json"), dataJSON = NSData(contentsOfURL: arquivoJSON) { let json = JSON(data: dataJSON) for (_, item): (String, JSON) in json { self.hospitalData.save(self.context, data: item) } } // Modo NSJSONSerialization //do { // if let arquivoJSON = NSBundle.mainBundle().URLForResource("data", withExtension: "json"), // dataJSON = NSData(contentsOfURL: arquivoJSON), // json = try NSJSONSerialization.JSONObjectWithData(dataJSON, options: []) as? [AnyObject] { // // let x = json[0] as! [String: AnyObject] // print(x) // // hosp.saveHospital(x) // } //} //catch { // print("Um erro aconteceu! \(error)") //} print("CoreData foi carregado!") // Chama imediatamente a próxima tela dispatch_sync(dispatch_get_main_queue()) { self.performSegueWithIdentifier(self.identifierSegue, sender: self) } } } else { print("Não há dados para carregar!") // Carga já foi feita, então carrega a página self.performSegueWithIdentifier(self.identifierSegue, sender: self) } } /* // 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. } */ }
// // AAComposeView.swift // weibo // // Created by dh on 16/9/5. // Copyright © 2016年 mac. All rights reserved. // import UIKit import pop class AAComposeView: UIView { var target: UIViewController? var composeArray: NSArray? lazy var buttons: [UIButton] = [UIButton]() override init(frame: CGRect) { super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setupUI() { frame.size = UIScreen.main.bounds.size self.addSubview(backImage) self.addSubview(iconImage) backImage.snp_updateConstraints { (make) in make.edges.equalTo(self) } iconImage.snp_makeConstraints { (make) in make.centerX.equalTo(self) make.top.equalTo(100) } addChildButtons() } func addChildButtons() { let itemW: CGFloat = 80 let itemH: CGFloat = 110 let itemMargin = (AAScreenW - 3 * itemW) / 4 let path = Bundle.main.path(forResource: "compose.plist", ofType: nil)! let array = NSArray(contentsOfFile: path)! self.composeArray = array for i in 0..<array.count { let dict = array[i] as! [String: String] let button = AAComposeButton() button.setTitle(dict["title"]!, for: .normal) button.setTitleColor(UIColor.darkGray, for: .normal) button.setImage(UIImage(named: dict["icon"]!), for: .normal) button.titleLabel?.font = UIFont.systemFont(ofSize: 14) button.addTarget(self, action: #selector(childButtonClick(button:)), for: .touchUpInside) button.frame.size = CGSize(width: itemW, height: itemH) let col = i % 3 let row = i / 3 let x = CGFloat(col) * itemW + CGFloat(col + 1) * itemMargin let y = CGFloat(row) * itemH + AAScreenH button.frame.origin = CGPoint(x: x, y: y) addSubview(button) buttons.append(button) } } @objc private func childButtonClick(button: UIButton) { UIView.animate(withDuration: 0.5, animations: { for value in self.buttons { if value == button { value.transform = CGAffineTransform.init(scaleX: 2, y: 2) } else { value.transform = CGAffineTransform.init(scaleX: 0.2, y: 0.2) } value.alpha = 0.1 } }) { (_) in let index = self.buttons.index(of: button) ?? 0 let compose = self.composeArray![index] as! [String: String] if let cla = compose["class"] { let type = NSClassFromString(cla)! as! UIViewController.Type let vc = type.init() self.target?.present(AANavigationController(rootViewController: vc), animated: true, completion: { self.removeFromSuperview() }) } } } // 外界调用. 显示控件 func show(controller: UIViewController) { self.target = controller self.target?.view.addSubview(self) for (index,button) in buttons.enumerated() { anim(button: button, index: index, isUp: true) } } func anim(button: UIButton, index: Int, isUp: Bool) { let anim = POPSpringAnimation(propertyNamed: kPOPViewCenter) anim?.toValue = NSValue.init(cgPoint: CGPoint(x: button.center.x, y: button.center.y + (isUp ? -350 : 350))) anim?.springBounciness = 12 anim?.springSpeed = 10 anim?.beginTime = CACurrentMediaTime() + Double(index) * 0.025 button.pop_add(anim, forKey: nil) } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { //self.removeFromSuperview() for (index,button) in buttons.reversed().enumerated() { anim(button: button, index: index, isUp: false) } DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.4) { self.removeFromSuperview() } } private lazy var backImage: UIImageView = { let imageView = UIImageView(image: UIImage.getScreenSnap()?.applyLightEffect()) return imageView }() private lazy var iconImage: UIImageView = { let imaView = UIImageView(image: #imageLiteral(resourceName: "compose_slogan")) return imaView }() }
// // Movie.swift // MovieList // // Created by Alexander Totsky on 03.05.2021. // import Foundation struct MovieInfo: Codable, Identifiable { var id: Int var title: String var posterPath: String var releaseDate: String? var credits: MovieCredit? static private let yearFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "yyyy" return formatter }() var posterStringURL: String { return "https://image.tmdb.org/t/p/w500\(posterPath)" } var yearText: String { guard let releaseDate = self.releaseDate, let date = Utils.dateFormatter.date(from: releaseDate) else { return "n/a" } return MovieInfo.yearFormatter.string(from: date) } var cast: [MovieCast]? { credits?.cast } var crew: [MovieCrew]? { credits?.crew } var directors: [MovieCrew]? { crew?.filter { $0.job.lowercased() == "director" } } var producers: [MovieCrew]? { crew?.filter { $0.job.lowercased() == "producer" } } var screenWriters: [MovieCrew]? { crew?.filter { $0.job.lowercased() == "story" } } } struct MovieCredit: Codable { let cast: [MovieCast] let crew: [MovieCrew] } struct MovieCast: Codable, Identifiable { let id: Int let character: String let name: String } struct MovieCrew: Codable, Identifiable { let id: Int let job: String let name: String }
// // VideosListView.swift // App04-TMDB // // Created by David Cantú Delgado on 28/10/21. // import SwiftUI struct VideosListView: View { @ObservedObject var mediaModel: MediaModel var media: Media var type: String @State var videos = [Video]() var body: some View { VStack { List { ForEach(videos) { video in NavigationLink(destination: WebView(html: "\(youtubeURL)\(video.key)")) { VStack(alignment: .leading) { Text(video.name) .font(.title2) Text(video.type) .font(.headline) } } } } .listStyle(InsetListStyle()) .navigationBarTitle(media.title) } .onAppear { mediaModel.loadVideos(type: type, id: media.id) { returnedVideos in if returnedVideos.count > 0 { videos.append(contentsOf: returnedVideos) } } } } } struct VideosListView_Previews: PreviewProvider { static var previews: some View { VideosListView(mediaModel: MediaModel(), media: Media.dummy, type: "movie") } }
// // ImageConstants.swift // FindOrOfferAJobApp // // Created by Haroldo on 19/02/20. // Copyright © 2020 HaroldoLeite. All rights reserved. // import Foundation import UIKit struct ImageConstants { // TabBar static let Home = UIImage(named: "home") static let Job = UIImage(named: "job") static let Profile = UIImage(named: "profile") // Profile static let Settings = UIImage(named: "settings") static let Logout = UIImage(named: "logout") // Work static let Work = UIImage(named: "work") // Settings static let Lock = UIImage(named: "lock") static let Delete = UIImage(named: "delete") static let Announce = UIImage(named: "announce") static let Records = UIImage(named: "records") // Others static let Back = UIImage(named: "back") static let ProflePlaceHolder = UIImage(named: "profile_placeholder") }
// // MWOtherWeatherCell.swift // MyWeather // // Created by zhang zhiyao on 11/16/15. // Copyright © 2015 NJIT656. All rights reserved. // import UIKit class MWOtherWeatherDetailView : UIView { weak var data : WeatherList? { didSet { self.calcData() self.setNeedsDisplay() } } var titles : [String] = [] var contents : [String] = [] var descriptionStr : String? func calcData() { var drawStr : String? if let descr = data?.weathers[0].description { drawStr = NSString(string: descr+" ") as String } if let tempMax = data?.temp.max, let tempMin = data?.temp.min { drawStr = NSString(format: "%@%@ - %@", drawStr!,tempMin.temperatureStr,tempMax.temperatureStr) as String } self.descriptionStr = drawStr titles.removeAll() contents.removeAll() if let humidity = data?.humidity { titles.append("Humidity") contents.append(humidity.humidityStr) } // if let pressure = data?.pressure { // titles.append("Pressure") // contents.append(pressure.pressureStr) // } // if let cloudiness = data?.clouds { // titles.append("Cloudiness") // contents.append(cloudiness.cloudiness) // } if let speed = data?.speed , let degree = data?.deg { titles.append("Wind") contents.append(Float(degree).windDirectionStr + " " + speed.windSpeedStr) } // if let rain3h = data?.rain { // titles.append("Rain") // contents.append(rain3h.rain3h) // } // if let snow3h = data?.snow { // titles.append("Snow") // contents.append(snow3h.snow3h) // } } override func awakeFromNib() { super.awakeFromNib() } override func drawRect(rect: CGRect) { super.drawRect(rect) let xBegin : [CGFloat] = [8.0,(rect.size.width - 16.0) / CGFloat(2.0)] self.descriptionStr?.drawAtPoint(CGPointMake(xBegin[0], 8.0), withAttributes: [NSFontAttributeName:UIFont.systemFontOfSize(16),NSForegroundColorAttributeName:UIColor(red: 80.0/255.0, green: 80.0/255.0, blue: 80.0/255.0, alpha: 1)]) let totalCount = titles.count let rowCount = ceil(Double(totalCount) / 2.0) var yBegin : [CGFloat] = [] let yConstant : CGFloat = 32 let heightConstant : CGFloat = rect.size.height - yConstant if rowCount < 3 { yBegin.append(yConstant) yBegin.append(yConstant + heightConstant * 0.5) } else { yBegin.append(yConstant) yBegin.append(yConstant + heightConstant*1/3) yBegin.append(yConstant + heightConstant*2/3) } var index : Int for index = 0;index < titles.count;index++ { let title = titles[index] let content = contents[index] let xIndex = index % 2 let yIndex = Int(ceil((Double(index) + 0.5) / 2.0) - 1) let drawStr = NSString(string: title + " " + content) drawStr.drawAtPoint(CGPointMake(xBegin[xIndex], yBegin[yIndex]), withAttributes: [NSFontAttributeName:UIFont.systemFontOfSize(12),NSForegroundColorAttributeName:UIColor(red: 180.0/255.0, green: 180.0/255.0, blue: 180.0/255.0, alpha: 1)]) } } } class MWOtherWeatherCell: UITableViewCell { @IBOutlet weak var weekdayLabel: UILabel! @IBOutlet weak var dateLabel: UILabel! @IBOutlet weak var descriptionView: MWOtherWeatherDetailView! @IBOutlet weak var iconImageView: UIImageView! var index : Int = 0 func setData(data:MWCityDataModel,index:Int) { self.index = index self.data = data } private var data : MWCityDataModel? { didSet { self.updateData() } } func updateData() { let calendar = NSCalendar.currentCalendar() let unitFlags: NSCalendarUnit = [.Weekday, .Day, .Month, .Year] if let timeDt = self.data?.sixteenDaysData?.lists[index].dt { let oDate = NSDate(timeIntervalSince1970: Double(timeDt)) let components = calendar.components(unitFlags, fromDate: oDate) self.dateLabel.text = NSString(format: "%d.%d", components.month, components.day) as String self.weekdayLabel.text = dateAbbrs[components.weekday] } self.descriptionView.data = self.data?.sixteenDaysData?.lists[index] if self.data?.sixteenDaysData?.lists[index].weathers.count > 0{ if let imageName = self.data?.sixteenDaysData?.lists[index].weathers[0].icon { self.iconImageView.image = UIImage(named: imageName) } else { self.iconImageView.image = nil } } else { self.iconImageView.image = nil } } }
// // TMSplashViewController.swift // consumer // // Created by Vladislav Zagorodnyuk on 1/27/16. // Copyright © 2016 Human Ventures Co. All rights reserved. // import UIKit import SVProgressHUD import EZSwiftExtensions class TMSplashViewController: UIViewController { var internalURLString: String? // MARK: - View Controller Lifecycle var radiantWave: TMLogoAnimationView? override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.radiantWave = TMLogoAnimationView.init(containerView: self.view, numberOfLines: 48, linesColor: UIColor.white, linesWidth: 0.7, linesHeight: 200.0) self.radiantWave!.show() self.view.sendSubview(toBack: self.radiantWave!) } override func viewDidLoad() { super.viewDidLoad() let nc = NotificationCenter.default nc.addObserver(self, selector: #selector(TMSplashViewController.dataSourceLoadedWithNotification(_:)), name: NSNotification.Name(rawValue: TMSynchronizerHandlerSynchronizedNotificationKey), object: nil) SVProgressHUD.setDefaultMaskType(.black) let manager = TMNetworkingManager.shared if manager.accessToken != nil { UIView.animate(withDuration: 0.1, animations: { void in if self.radiantWave != nil { self.radiantWave!.alpha = 1.0 } }) } else { // Return to initial onboarding TMOnboardingRouteHandler.initialTransition() } } @IBAction func partyMode() { self.radiantWave?.disco(true) } // Shaking overriding override var canBecomeFirstResponder : Bool { return true } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.becomeFirstResponder() } override func motionEnded(_ motion: UIEventSubtype, with event: UIEvent?) { if motion == .motionShake { self.radiantWave?.disco(true) } } // MARK: - Notificaitons func dataSourceLoadedWithNotification(_ notification: Notification?) { let netman = TMNetworkingManager.shared if netman.accessToken != nil { let appDelegate = TMAppDelegate.appDelegate if let internalURLString = appDelegate?.storedInternalURL { // Transition to requets flow TMDeepLinkHandler.requestFlow() ez.runThisAfterDelay(seconds: 1, after: { TMDeepLinkParser.handlePath(internalURLString, completion: nil) appDelegate?.storedInternalURL = nil }) } else { // Transition to requets flow TMDeepLinkHandler.requestFlow() } } } // MARK: - Utility func transitionToInitialController() { let onboardingStoryboard = UIStoryboard(name: "Onboarding", bundle: nil) let nextController = onboardingStoryboard.instantiateViewController(withIdentifier: "initialNavigationController") let snapshot:UIView = (self.view.window?.snapshotView(afterScreenUpdates: true))! nextController.view.addSubview(snapshot) self.view.window?.rootViewController = nextController; UIView.animate(withDuration: 0.3, animations: { () in snapshot.layer.opacity = 0 snapshot.layer.transform = CATransform3DMakeScale(1.5, 1.5, 1.5) }, completion: { (value: Bool) in snapshot.removeFromSuperview() }); } override var prefersStatusBarHidden : Bool { return true } override var preferredStatusBarStyle : UIStatusBarStyle { return .lightContent } } extension UINavigationController { open override var childViewControllerForStatusBarHidden : UIViewController? { return visibleViewController } open override var childViewControllerForStatusBarStyle : UIViewController? { return visibleViewController } }
// // RecipeViewController.swift // Recipe Me // // Created by Jora on 10/19/18. // Copyright © 2018 Jora. All rights reserved. // import UIKit import CoreData class RecipeViewController: UIViewController { @IBOutlet weak var tableView: UITableView! // Cell identifiers let titlePhotoCell = "TitlePhotoCell" let stepCell = "StepCell" let ingredientsCell = "IngredientsCell" weak var managedContext = TabBarController.managedContext var fetchResultsController: NSFetchedResultsController<Recipe>! // Query parameter var recipeTitle: String! //TODO: delete if var imagesCache = [UIImage?]() var titleImageCache: UIImage? override func viewDidLoad() { super.viewDidLoad() tableView.alpha = 0 title = recipeTitle navigationItem.largeTitleDisplayMode = .never tableView.rowHeight = UITableView.automaticDimension DispatchQueue.main.async { self.fetchSelectedRecipe() } } // refresh all ingredients override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) { if motion == .motionShake { for ingredient in fetchResultsController.fetchedObjects?.first!.ingredients?.array as! [Ingredient] { ingredient.isPresent = false } let tableViewCell = tableView.cellForRow(at: IndexPath(row: 0, section: 1)) if let cell = tableViewCell as! IngredientsTableViewCell? { cell.tableView.reloadData() } } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) DispatchQueue.main.async { try! self.managedContext?.save() } } deinit { print("RecipeViewController was deinitialized") } func fetchSelectedRecipe() { let fetchRequest: NSFetchRequest<Recipe> = Recipe.fetchRequest() let selectedRecipePredicate = NSPredicate(format: "%K = %@", #keyPath(Recipe.title), recipeTitle) let sortDescriptor = NSSortDescriptor(key: #keyPath(Recipe.title), ascending: true) fetchRequest.predicate = selectedRecipePredicate fetchRequest.sortDescriptors = [sortDescriptor] fetchResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: managedContext!, sectionNameKeyPath: nil, cacheName: "recipe") do { try fetchResultsController.performFetch() let recipe = fetchResultsController.fetchedObjects?.first! let steps = recipe?.steps!.array as! [Step] let arrayOfData = steps.map { $0.image! as Data} let fullResImages = arrayOfData.map { UIImage(data: $0)!} imagesCache = fullResImages.map { $0.renderResizedImage(newWidth: UIScreen.main.bounds.width)} let imageData = recipe?.image as Data? if let imageData = imageData { let image = UIImage(data: imageData) titleImageCache = image?.renderResizedImage(newWidth: UIScreen.main.bounds.width) } tableView.separatorStyle = UITableViewCell.SeparatorStyle.singleLine self.tableView.reloadData() UIView.animate(withDuration: 0.2) { self.tableView.alpha = 1 } } catch { print(error.localizedDescription) } } } extension RecipeViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 3 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { guard fetchResultsController != nil else { return 0 } if section == 0 { return 1 } if section == 1 { return 1 } if section == 2 { return fetchResultsController.fetchedObjects?.first?.steps?.count ?? 0 } return 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let recipe = fetchResultsController.fetchedObjects?.first! else { return UITableViewCell() } switch indexPath.section { case 0: let cell = tableView.dequeueReusableCell(withIdentifier: titlePhotoCell, for: indexPath) as! RecipeTitleTableViewCell cell.setImage(image: titleImageCache) cell.recipeTitleLabel.text = recipe.title cell.recipeTimeLabel.text = recipe.time < 60 ? String(recipe.time) + " min" : String(recipe.time / 60) + " h" cell.recipeDescriptionLabel.text = recipe.details return cell case 1: let cell = tableView.dequeueReusableCell(withIdentifier: ingredientsCell, for: indexPath) as! IngredientsTableViewCell cell.ingredients = (recipe.ingredients?.array as! [Ingredient]) return cell case 2: let cell = tableView.dequeueReusableCell(withIdentifier: stepCell, for: indexPath) as! StepTableViewCell let step = recipe.steps?.object(at: indexPath.row) as! Step cell.setImage(image: self.imagesCache[indexPath.row]) cell.stepLabel.text = step.details cell.stepNumber.text = String(indexPath.row + 1) return cell default: return UITableViewCell() } } } // image resizer extension UIImage { func renderResizedImage(newWidth: CGFloat) -> UIImage { let scale = newWidth / self.size.width // round the Height of an image to avoid subpixel rendering let newHeight = ceil(self.size.height * scale) let newSize = CGSize(width: newWidth, height: newHeight) let renderer = UIGraphicsImageRenderer(size: newSize) let image = renderer.image { (context) in self.draw(in: CGRect(origin: CGPoint(x: 0, y: 0), size: newSize)) } return image } }
// // JobTypeTableViewCell.swift // TimeTracker // // Created by Hoang Tung on 2/23/20. // Copyright © 2020 Hoang Tung. All rights reserved. // import UIKit class JobTypeTableViewCell: UITableViewCell { let lineView: UIView = { let view = UIView() view.translatesAutoresizingMaskIntoConstraints = false view.backgroundColor = hexStringToUIColor(hex: "ECF3F3") return view }() let jobTypeLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.textColor = hexStringToUIColor(hex: "303D3C") label.textAlignment = .center label.font = .systemFont(ofSize: 14) label.layer.borderWidth = 1 label.layer.cornerRadius = 20 return label }() let horizontalLineView: UIView = { let view = UIView() view.translatesAutoresizingMaskIntoConstraints = false view.backgroundColor = hexStringToUIColor(hex: "ECF3F3") return view }() let circleView: CircleView = { let view = CircleView() view.translatesAutoresizingMaskIntoConstraints = false return view }() let percentLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.font = .boldSystemFont(ofSize: 16) label.textColor = .white return label }() override func awakeFromNib() { super.awakeFromNib() } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) self.backgroundColor = hexStringToUIColor(hex: "F6F9F9") setupView() setupLayout() } func setupView() { self.addSubview(lineView) self.addSubview(jobTypeLabel) self.addSubview(horizontalLineView) self.addSubview(circleView) self.addSubview(percentLabel) } func setupLayout() { lineView.topAnchor.constraint(equalTo: self.topAnchor, constant: 0).isActive = true lineView.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 16).isActive = true lineView.widthAnchor.constraint(equalToConstant: 3).isActive = true lineView.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: 0).isActive = true jobTypeLabel.centerXAnchor.constraint(equalTo: self.centerXAnchor, constant: -16).isActive = true jobTypeLabel.centerYAnchor.constraint(equalTo: self.centerYAnchor, constant: 0).isActive = true jobTypeLabel.heightAnchor.constraint(equalToConstant: 40).isActive = true jobTypeLabel.widthAnchor.constraint(equalTo: self.widthAnchor, multiplier: 0.6).isActive = true horizontalLineView.centerYAnchor.constraint(equalTo: self.centerYAnchor, constant: 0).isActive = true horizontalLineView.heightAnchor.constraint(equalToConstant: 3).isActive = true horizontalLineView.leadingAnchor.constraint(equalTo: lineView.trailingAnchor, constant: 0).isActive = true horizontalLineView.trailingAnchor.constraint(equalTo: jobTypeLabel.leadingAnchor, constant: 0).isActive = true circleView.topAnchor.constraint(equalTo: self.topAnchor, constant: 8).isActive = true circleView.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -8).isActive = true circleView.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: 0).isActive = true circleView.widthAnchor.constraint(equalToConstant: 64).isActive = true circleView.heightAnchor.constraint(equalToConstant: 64).isActive = true percentLabel.centerXAnchor.constraint(equalTo: circleView.centerXAnchor, constant: 0).isActive = true percentLabel.centerYAnchor.constraint(equalTo: circleView.centerYAnchor, constant: 0).isActive = true percentLabel.widthAnchor.constraint(greaterThanOrEqualToConstant: 0).isActive = true percentLabel.heightAnchor.constraint(greaterThanOrEqualToConstant: 0).isActive = true } }
// // ViewController.swift // Tipsy // // Created by Angela Yu on 09/09/2019. // Copyright © 2019 The App Brewery. All rights reserved. // import UIKit class CalculatorViewController: UIViewController { @IBOutlet weak var billTextField: UITextField! @IBOutlet weak var zeroPctButton: UIButton! @IBOutlet weak var tenPctButton: UIButton! @IBOutlet weak var twentyPctButton: UIButton! @IBOutlet weak var splitNumberLabel: UILabel! var tip = 0.1 var splitNumber = 2.0 var amountToBeShared = "" override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } //MARK: - Tip button pressed action @IBAction func tipChanged(_ sender: UIButton) { zeroPctButton.isSelected = false tenPctButton.isSelected = false twentyPctButton.isSelected = false sender.isSelected = true //Get the current title of the button that was pressed. let buttonTitle = sender.currentTitle! //Remove the last character (%) from the title then turn it back into a String. let buttonTitleMinusPercentSign = String(buttonTitle.dropLast()) //Turn the String into a Double. let buttonTitleAsANumber = Double(buttonTitleMinusPercentSign)! //Divide the percent expressed out of 100 into a decimal e.g. 10 becomes 0.1 tip = buttonTitleAsANumber / 100 } //MARK: - Stepper Value Changed action @IBAction func stepperValueChanged(_ sender: UIStepper) { splitNumber = Double(sender.value) DispatchQueue.main.async { self.splitNumberLabel.text = String(Int(self.splitNumber)) } } //MARK: - Calculate button pressed action @IBAction func calculatePressed(_ sender: UIButton) { print(tip) if let amount = billTextField.text, let amountInDouble = Double(amount) { amountToBeShared = calculateLogic(amountToBeSplit: amountInDouble, splitNumbers: splitNumber, tip: tip) self.performSegue(withIdentifier: "resultSegue", sender: nil) } else { print("No value in textfield") } } //MARK: - Logic calculating the amount to be split func calculateLogic(amountToBeSplit: Double, splitNumbers: Double, tip: Double) -> String { let tipAmount = amountToBeSplit * tip let totalAmountIncludingTip = amountToBeSplit + tipAmount let finalAmountToBeSplit = totalAmountIncludingTip / splitNumbers return String(finalAmountToBeSplit) //print("finalAmountToBeSplit", finalAmountToBeSplit) } //MARK: - PrepareSegue Method override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if (segue.identifier == "resultSegue") { let resultVC = segue.destination as! ResultsViewController resultVC.amountToBeShared = amountToBeShared resultVC.splitPersonsCount = splitNumberLabel.text ?? "" resultVC.tipPercentage = String(tip * 100) } } }
// // InReadSASTableViewController.swift // TeadsSampleApp // // Created by Jérémy Grosjean on 19/11/2020. // Copyright © 2020 Teads. All rights reserved. // import SASDisplayKit import TeadsSASAdapter import TeadsSDK import UIKit class InReadSASTableViewController: TeadsViewController { @IBOutlet var tableView: UITableView! var banner: SASBannerView? let contentCell = "TeadsContentCell" let teadsAdCellIndentifier = "TeadsAdCell" let fakeArticleCell = "fakeArticleCell" let adRowNumber = 2 var adHeight: CGFloat? var adRatio: TeadsAdRatio? var teadsAdIsLoaded = false var tableViewAdCellWidth: CGFloat! override func viewDidLoad() { super.viewDidLoad() banner = SASBannerView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 200), loader: .activityIndicatorStyleWhite) banner?.modalParentViewController = self let teadsAdSettings = TeadsAdapterSettings { settings in settings.enableDebug() settings.pageUrl("https://teads.tv") try? settings.registerAdView(banner!, delegate: self) } let webSiteId = 385_317 let pageId = 1_331_331 let formatId = Int(pid) ?? 96445 var keywordsTargetting = "yourkw=something" keywordsTargetting = TeadsSASAdapterHelper.concatAdSettingsToKeywords(keywordsStrings: keywordsTargetting, adSettings: teadsAdSettings) // Create a placement let adPlacement = SASAdPlacement(siteId: webSiteId, pageId: pageId, formatId: formatId, keywordTargeting: keywordsTargetting) banner?.load(with: adPlacement) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() tableViewAdCellWidth = tableView.frame.width - 20 } @objc func rotationDetected() { if let adRatio = adRatio { resizeTeadsAd(adRatio: adRatio) } } func resizeTeadsAd(adRatio: TeadsAdRatio) { adHeight = adRatio.calculateHeight(for: tableViewAdCellWidth) updateAdCellHeight() } func closeSlot() { adHeight = 0 updateAdCellHeight() } func updateAdCellHeight() { tableView.reloadRows(at: [IndexPath(row: adRowNumber, section: 0)], with: .automatic) } } extension InReadSASTableViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_: UITableView, numberOfRowsInSection _: Int) -> Int { return 4 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch indexPath.row { case 0: let cell = tableView.dequeueReusableCell(withIdentifier: contentCell, for: indexPath) return cell case adRowNumber: // need to create a cell and just add a teadsAd to it, so we have only one teads ad let cellAd = tableView.dequeueReusableCell(withIdentifier: teadsAdCellIndentifier, for: indexPath) if let banner = banner { cellAd.addSubview(banner) banner.frame = CGRect(x: 10, y: 0, width: tableViewAdCellWidth, height: adHeight ?? 250) } return cellAd default: let cell = tableView.dequeueReusableCell(withIdentifier: fakeArticleCell, for: indexPath) return cell } } func tableView(_: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if indexPath.row == adRowNumber { return adHeight ?? 0 } else { return UITableView.automaticDimension } } } extension InReadSASTableViewController: TeadsMediatedAdViewDelegate { func didUpdateRatio(_: UIView, adRatio: TeadsAdRatio) { self.adRatio = adRatio resizeTeadsAd(adRatio: adRatio) } }
// // ViewController.swift // ShareExtension // // Created by Sohel Rana on 15/9/21. // import UIKit import WebKit class ViewController: UIViewController, UIDocumentInteractionControllerDelegate { @IBOutlet weak var imgView: UIImageView! @IBOutlet weak var webView: WKWebView! let link = "https://github.com/soheltanvir0699" override func viewDidLoad() { super.viewDidLoad() webView.load(URLRequest(url: URL(string: link)!)) imgView.image = UIImage(named: "messi") } @IBAction func shareWebLink(_ sender: Any) { let activityController = UIActivityViewController(activityItems: [link], applicationActivities: nil) activityController.completionWithItemsHandler = {(nil, completed, _, error) in if completed { print("completed") }else { print("cancled") } } present(activityController, animated: true, completion: nil) } @IBAction func shareImg(_ sender: Any) { guard let image = UIImage(named: "messi") else { return } let activityController = UIActivityViewController(activityItems: [image], applicationActivities: nil) activityController.completionWithItemsHandler = { (nil, completed, _, error) in if completed { print("completed") }else { print("cancled") } } present(activityController, animated: true, completion: nil) } @IBAction func sharePdf(_ sender: Any) { guard let pdf = Bundle.main.url(forResource: "linalg_notes", withExtension: "pdf") else { return } let controller = UIDocumentInteractionController(url: pdf) controller.delegate = self controller.presentPreview(animated: true) } func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController { return self } } //sohel
// // TTWorkspace.swift // Vizor // // Created by Gábor Librecz on 2018. 10. 26.. // Copyright © 2018. Gábor Librecz. All rights reserved. // import AppKit typealias TTWorkspace = NSObject extension TTWorkspace { @objc var windowControllers: Array<TTWindowController> { fatalError() } }
// // ViewController.swift // weatherApp // // Created by Tia Lendor on 10/9/19. // Copyright © 2019 Tia Lendor. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var weatherCollectionView: UICollectionView! @IBOutlet weak var cityName: UILabel! @IBOutlet weak var zipTextOutlet: UITextField! @IBAction func zipTextField(_ sender: UITextField) { } var weatherData = [Weather]() { didSet { weatherCollectionView.reloadData() print(weatherData) } } override func viewDidLoad() { super.viewDidLoad() setUp() loadDefaults() // Do any additional setup after loading the view. } private func setUp () { let layout = weatherCollectionView.collectionViewLayout as! UICollectionViewFlowLayout layout.scrollDirection = .horizontal zipTextOutlet.keyboardType = .numberPad zipTextOutlet.delegate = self weatherCollectionView.delegate = self weatherCollectionView.dataSource = self } var searchedCityName = "" private func loadData (zipCode: String) { ZipCodeHelper.getLatLong(fromZipCode: zipCode) { (result) in DispatchQueue.main.async { switch result { case let .failure(error): print(error) case let .success((lat, long, name)): UserDefaults.standard.set(lat, forKey: "latitude") UserDefaults.standard.set(long, forKey: "longitude") UserDefaults.standard.set(name, forKey: "name") self.cityName.text = name.description.capitalized self.searchedCityName = name.description.capitalized self.getData(latitude: lat, longitude: long) } } } } // pass city name to detailed view look into custom delegation. private func loadDefaults() { if let lat = UserDefaults.standard.value(forKey: "latitude") as? Double, let long = UserDefaults.standard.value(forKey: "longitude") as? Double, let name = UserDefaults.standard.value(forKey: "name") { self.searchedCityName = name as! String self.cityName.text = name as! String getData(latitude: lat, longitude: long) } } private func getData(latitude: Double, longitude: Double) { WeatherAPIHelper.shared.getWeather(lat: latitude, long: longitude) { (result) in DispatchQueue.main.async { switch result { case .failure(let error): print(error) case .success(let weatherDataFromOnline): self.weatherData = weatherDataFromOnline } } } } // func collectionLayout () { // let layout = weatherCollectionView.collectionViewLayout as! UICollectionViewFlowLayout // layout.scrollDirection = .horizontal // zipTextOutlet.keyboardType = .numberPad // zipTextOutlet.delegate = self // } } extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return weatherData.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = weatherCollectionView.dequeueReusableCell(withReuseIdentifier: "weatherCell", for: indexPath) as! WeatherCollectionViewCell let weather = weatherData[indexPath.row] cell.configureCell(weather: weather) return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: 175, height: 250) } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let detailedWeather = weatherData[indexPath.row] let detailedView = DayDetailViewController() detailedView.detailedDay = detailedWeather detailedView.cityName = searchedCityName self.navigationController?.pushViewController(detailedView, animated: true) } } extension ViewController: UITextFieldDelegate { func textFieldDidChangeSelection(_ textField: UITextField) { if textField.text?.count == 5 { textField.resignFirstResponder() loadData(zipCode: textField.text!) } } }
// // ScrumsView.swift // Scrumdinger // // Created by YOU-HSUAN YU on 2020/12/27. // import SwiftUI struct ScrumsView: View { let scrums: [DailyScrum] var body: some View { List { //ForEach needs a way to identify individual items in the collection. For now, because all of the scrums in the test data have different names, you can use the title property to identify each item. ForEach(scrums) { (scrum) in NavigationLink( destination: Text(scrum.title), label: { CardView(scrum: scrum) }) .listRowBackground(scrum.color) } } .navigationTitle("Daily Scrum") .navigationBarItems(trailing: Button(action: {}) { Image(systemName: "plus") }) } } struct ScrumsView_Previews: PreviewProvider { static var previews: some View { NavigationView { ScrumsView(scrums: DailyScrum.data) } } }
// // ViewController.swift // MyTodoList // // Created by JF on 04/06/16. // Copyright © 2016 Jorge Ferreiro. All rights reserved. // import UIKit class ViewController: UIViewController { let todoList = TodoList() @IBOutlet weak var saveNoteButton: UIButton! @IBOutlet weak var noteTextField: UITextField! @IBOutlet weak var notesTableView: UITableView! @IBAction func saveNoteButtonPressed(sender: UIButton) { if let item = noteTextField.text { todoList.addItem(item) todoList.displayItems() print("Note Saved!") } else { print("You have to enter some text to save the note") } notesTableView.reloadData() } override func viewDidLoad() { super.viewDidLoad() notesTableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell") notesTableView.dataSource = todoList // Este es el objecto al cual tienes que preguntar } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
// // NetworkService.swift // MVPtest // // Created by Муслим Курбанов on 18.06.2020. // Copyright © 2020 Муслим Курбанов. All rights reserved. // import Foundation import Alamofire //MARK: - NetworkServiceProtocol protocol NetworkServiceProtocol { // func getComments(completion: @escaping (Result<[Model]?, Error>) -> Void) func getMenu(complletion: @escaping (Result<[Model]?, Error>) -> Void) } //MARK: - NetworkService class NetworkService: NetworkServiceProtocol { func getMenu(complletion: @escaping (Result<[Model]?, Error>) -> Void) { let urlString = "https://peretz-group.ru/api/v2/products?category=51&key=47be9031474183ea92958d5e255d888e47bdad44afd5d7b7201d0eb572be5278" AF .request(urlString, method: .get, parameters: nil) .responseJSON { (response) in switch response.result { case .failure(let error): print(error) case .success(let value): if let arrayDictionary = value as? [[String: Any]] { do { let data = try JSONSerialization.data(withJSONObject: arrayDictionary, options: .fragmentsAllowed) print(data) // let decoder = JSONDecoder() // decoder.keyDecodingStrategy = .convertFromSnakeCase let result = try JSONDecoder().decode([Model].self, from: data) complletion(.success(result)) print(result) } catch { complletion(.failure(error)) print(error) } } } }.resume() } // static let shared = NetworkService() // func getComments(completion: @escaping (Result<[Model]?, Error>) -> Void) { // // let urlString = "https://peretz-group.ru/api/v2/products?category=93&key=47be9031474183ea92958d5e255d888e47bdad44afd5d7b7201d0eb572be5278" // guard let url = URL(string: urlString) else { return } // // //MARK: - URLSession // URLSession.shared.dataTask(with: url) { data, _, error in // if let error = error { // completion(.failure(error)) // return // } // // do { // let obj = try JSONDecoder().decode([Model].self, from: data!) // completion(.success(obj)) // } catch { // completion(.failure(error)) // } // }.resume() // } // func getMenu(completion: @escaping (Result<[Model]?, Error) -> Void { // // let urlString = "https://peretz-group.ru/api/v2/products?category=93&key=47be9031474183ea92958d5e255d888e47bdad44afd5d7b7201d0eb572be5278" // // AF // .request(urlString, method: .get, parameters: nil) // .responseJSON { (response) in // switch response.result { // case .failure(let error): // onError(error.localizedDescription) // // case .success(let value): // if let arrayDictionary = value as? [[String: Any]] { // do { // let data = try JSONSerialization.data(withJSONObject: arrayDictionary, options: .fragmentsAllowed) // let decoder = JSONDecoder() // decoder.keyDecodingStrategy = .convertFromSnakeCase // let result = try decoder.decode([Model].self, from: data) // onSuccess(result) // print(result) // } catch { // onError("Parse error: \(error.localizedDescription)") // } // } // } // } // } }
// // PinkyPresenterProtocol.swift // pinky // // Created by Lukasz on 16/01/16. // Copyright © 2016 Lukasz. All rights reserved. // import Foundation import UIKit protocol PinkyPresenterProtocol { func requestNewContent() func requestTableData() func respondWithTableData(pinkyData: [PinkyTableData]?) func requestCellImageWith(pinkyData: PinkyTableData, indexPath: NSIndexPath) func responseCellImageWith(image: UIImage?, indexPath: NSIndexPath) func openWebViewWith(pinkyData: PinkyTableData) }
// // EqualizePIX.swift // PixelKit // // Created by Anton Heestand on 2021-08-09. // import RenderKit import Resolution import CoreGraphics import MetalKit #if !os(tvOS) && !targetEnvironment(simulator) // MPS does not support the iOS simulator. import MetalPerformanceShaders #endif import SwiftUI final public class EqualizePIX: PIXSingleEffect, CustomRenderDelegate, PIXViewable { override public var shaderName: String { return "nilPIX" } // MARK: - Public Properties @LiveBool("includeAlpha") var includeAlpha: Bool = false // MARK: - Property Helpers public override var liveList: [LiveWrap] { [_includeAlpha] } // MARK: - Life Cycle public required init() { super.init(name: "Equalize", typeName: "pix-effect-single-equalize") customRenderDelegate = self customRenderActive = true } public required init(from decoder: Decoder) throws { try super.init(from: decoder) customRenderDelegate = self customRenderActive = true } // MARK: Histogram public func customRender(_ texture: MTLTexture, with commandBuffer: MTLCommandBuffer) -> MTLTexture? { #if !os(tvOS) && !targetEnvironment(simulator) return histogram(texture, with: commandBuffer) #else return nil #endif } #if !os(tvOS) && !targetEnvironment(simulator) func histogram(_ texture: MTLTexture, with commandBuffer: MTLCommandBuffer) -> MTLTexture? { var histogramInfo = MPSImageHistogramInfo( numberOfHistogramEntries: 256, histogramForAlpha: ObjCBool(includeAlpha), minPixelValue: vector_float4(0,0,0,0), maxPixelValue: vector_float4(1,1,1,1) ) let histogram = MPSImageHistogram(device: pixelKit.render.metalDevice, histogramInfo: &histogramInfo) let equalization = MPSImageHistogramEqualization(device: pixelKit.render.metalDevice, histogramInfo: &histogramInfo) let bufferLength: Int = histogram.histogramSize(forSourceFormat: texture.pixelFormat) guard let histogramInfoBuffer: MTLBuffer = pixelKit.render.metalDevice.makeBuffer(length: bufferLength, options: [.storageModePrivate]) else { return nil } histogram.encode(to: commandBuffer, sourceTexture: texture, histogram: histogramInfoBuffer, histogramOffset: 0) equalization.encodeTransform(to: commandBuffer, sourceTexture: texture, histogram: histogramInfoBuffer, histogramOffset: 0) guard let histogramTexture = try? Texture.emptyTexture(size: CGSize(width: texture.width, height: texture.height), bits: pixelKit.render.bits, on: pixelKit.render.metalDevice, write: true) else { pixelKit.logger.log(node: self, .error, .generator, "Guassian Blur: Make texture faild.") return nil } equalization.encode(commandBuffer: commandBuffer, sourceTexture: texture, destinationTexture: histogramTexture) return histogramTexture } #endif } public extension NODEOut { func pixEqualize() -> EqualizePIX { let equalizePix = EqualizePIX() equalizePix.name = ":equalize:" equalizePix.input = self as? PIX & NODEOut return equalizePix } } struct EqualizePIX_Previews: PreviewProvider { static var previews: some View { PixelView(pix: { let noisePix = NoisePIX() noisePix.octaves = 10 noisePix.colored = true let equalizePix = EqualizePIX() equalizePix.input = noisePix return equalizePix }()) } }
// // CategoryTableViewCell.swift // SDKDemo1 // // Created by Vishal on 22/08/18. // Copyright © 2018 CL-macmini-88. All rights reserved. // import UIKit class CategoryTableViewCell: UITableViewCell { @IBOutlet weak var titleLabel: UILabel! var cellData = HippoSupportList() override func awakeFromNib() { super.awakeFromNib() setTheme() } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } func setData(object: HippoSupportList) { self.cellData = object titleLabel.text = cellData.title } func setTheme() { titleLabel.font = HippoConfig.shared.theme.supportTheme.supportListHeadingFont titleLabel.textColor = HippoConfig.shared.theme.supportTheme.supportListHeadingColor } }
// // ViewControllerWebModal.swift // BoutTime // // Created by Nuno Trindade on 28/09/16. // Copyright © 2016 Remarkable Code Ltd. All rights reserved. // import UIKit import WebKit class ViewControllerWebModal: UIViewController, WKNavigationDelegate { @IBOutlet weak var viewContainer: UIView! @IBOutlet weak var activityIndicator: UIActivityIndicatorView! var webView: WKWebView! var urlString: String = "http://teamtreehouse.com" override func viewDidLoad() { super.viewDidLoad() webView = WKWebView() webView.navigationDelegate = self viewContainer.addSubview(webView) } override func viewDidAppear(_ animated: Bool) { let frame = CGRect(x: 0, y: 0, width: viewContainer.bounds.width, height: viewContainer.bounds.height) webView.frame = frame loadUrl() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func dismissWebModal() { dismiss(animated: true, completion: nil) } func loadUrl() { if webView != nil { let url = URL(string: urlString)! let urlRequest = URLRequest(url: url) webView.load(urlRequest) } } func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) { activityIndicator.startAnimating() } func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { activityIndicator.stopAnimating() } }
import XCTest import ReactiveSwift @testable import Relayr final class APIPublishersTest: XCTestCase { // API instance pointing to the environment being tested. fileprivate var api: Relayr.API! override func setUp() { super.setUp() let (hostURL, token): (String, String) = (Test.variables.server.api, Test.variables.user.token) self.api = API(withURLs: API.Addresses(root: hostURL, broker: hostURL), token: token) } override func tearDown() { self.api = nil super.tearDown() } static var allTests = [ ("testPublishers", testPublishers), ("testPublisherLifecycle", testPublisherLifecycle) ] } extension APIPublishersTest { /// Tests the publishers retrieval. func testPublishers() { let signal = self.api.publishers().on(value: { (response) in XCTAssertFalse(response.identifier.isEmpty) XCTAssertFalse(response.owner.isEmpty) }).collect().on { (response) in XCTAssertFalse(response.isEmpty) } Test.signal(signal, onTest: self, message: "Cloud's publishers", numEndpoints: 1, timeout: 2*Test.endPointTimeout) } func testPublisherLifecycle() { let (api, user, publisher) = (self.api!, Test.variables.user, Test.variables.publisher) var received: (identifier: String?, name: String) = (nil, "Manolo") let signal = api.createPublisher(withName: publisher.name, ownedByUserWithID: user.identifier).flatMap(.latest) { (response) -> SignalProducer<API.Publisher,API.Error> in Test.check(publisher: response, withIdentifier: nil, name: publisher.name, ownerID: user.identifier) received.identifier = response.identifier return api.setPublisherInfo(withID: response.identifier, name: received.name) }.flatMap(.latest) { (response) -> SignalProducer<API.Publisher,API.Error> in Test.check(publisher: response, withIdentifier: received.identifier!, name: received.name, ownerID: user.identifier) return api.publisherInfo(withID: response.identifier) }.flatMap(.latest) { (response) -> SignalProducer<API.Publisher,API.Error> in Test.check(publisher: response, withIdentifier: received.identifier!, name: received.name, ownerID: user.identifier) return api.publishersFromUser(withID: user.identifier) }.on(value: { (response) in XCTAssertFalse(response.identifier.isEmpty) XCTAssertEqual(response.owner, user.identifier) }).collect().flatMap(.latest) { (response) -> SignalProducer<(),API.Error> in XCTAssertFalse(response.isEmpty) let found = response.find { $0.identifier == received.identifier! && $0.name == received.name && $0.owner == user.identifier } XCTAssertNotNil(found) return api.delete(publisherWithID: received.identifier!) } Test.signal(signal, onTest: self, message: "Publisher lifecycle", numEndpoints: 5) { guard let publisherID = received.identifier else { return SignalProducer.empty } return api.delete(publisherWithID: publisherID) } } } fileprivate extension Test { /// Checks that the given publisher is in a correct state fileprivate static func check(publisher: API.Publisher, withIdentifier identifier: String?, name: String, ownerID: String) { if let identifier = identifier { XCTAssertEqual(publisher.identifier, identifier, "Received publisher identifier is not the same as before") } else { XCTAssertFalse(publisher.identifier.isEmpty, "The publisher identifier is empty") } XCTAssertEqual(publisher.name, name) XCTAssertEqual(publisher.owner, ownerID) } }
// // NetworkManager.swift // TestingTestPostApp // // Created by Artem Chuklov on 22.06.2021. // import Foundation class NetworkManager { static let shared = NetworkManager() @discardableResult func request(_ builder: URLBuilder, completion: @escaping(Result<Data, Error>) -> Void) -> URLSessionDataTask? { guard let url = builder.build() else { return nil } debugPrint("NetworkManager: request: \(url)") let task = URLSession.shared.dataTask(with: url) { data, response, error in if let error = error { debugPrint("NetworkManager: error: \(error)") completion(.failure(error)) } if let data = data { debugPrint("NetworkManager: success") completion(.success(data)) } } task.resume() return task } }
// // MusicSearchController.swift // Apple Music Swiftbook // // Created by Алексей Пархоменко on 17/07/2019. // Copyright © 2019 Алексей Пархоменко. All rights reserved. // import UIKit import Alamofire class MusicSearchController: UITableViewController { let searchController = UISearchController(searchResultsController: nil) var networkService = NetworkService() fileprivate var timer: Timer? var tracks = [Track]() override func viewDidLoad() { super.viewDidLoad() setupSearchBar() setupTableView() } fileprivate func setupSearchBar() { navigationItem.searchController = searchController navigationItem.hidesSearchBarWhenScrolling = false searchController.dimsBackgroundDuringPresentation = false searchController.searchBar.delegate = self } fileprivate func setupTableView() { let nib = UINib(nibName: "TrackCell", bundle: nil) tableView.register(nib, forCellReuseIdentifier: TrackCell.reuseId) } // MARK: - UITableViewDelegate, UITableViewDataSource override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tracks.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let track = tracks[indexPath.row] let cell = tableView.dequeueReusableCell(withIdentifier: TrackCell.reuseId, for: indexPath) as! TrackCell cell.set(track: track) return cell } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 132 } } // MARK: - UISearchBarDelegate extension MusicSearchController: UISearchBarDelegate { func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { print(searchText) timer?.invalidate() timer = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: false, block: { (_) in self.networkService.fetchTracks(searchText: searchText) { [weak self] (searchResults) in self?.tracks = searchResults?.results ?? [] searchResults?.results.map({ (track) in print("wrapperType: \(track.wrapperType ?? "nil") trackName: \(track.trackName ?? "nil")") }) self?.tableView.reloadData() } }) } }
// // AsyncOperation.swift // JatApp-Foundation // // Created by Developer on 11.11.2019. // Copyright © 2019 JatApp. All rights reserved. // import Foundation public class AsyncOperation: Operation { public typealias AsyncCompletionBlock = (@escaping VoidCompletion) -> Void // MARK: - Properties var internalAsyncCompletionBlock: AsyncCompletionBlock? var asyncCompletionBlock: AsyncCompletionBlock? { get { return internalAsyncCompletionBlock } set { guard internalAsyncCompletionBlock == nil else { return } internalAsyncCompletionBlock = newValue if isCancelled && internalExecuting { isExecuting = false } else if let asyncCompletionBlock = newValue, internalExecuting { asyncCompletionBlock(done) } } } private var internalExecuting: Bool = false public override var isExecuting: Bool { get { return internalExecuting } set { willChangeValue(forKey: "isExecuting") internalExecuting = newValue didChangeValue(forKey: "isExecuting") } } private var internalFinished: Bool = false public override var isFinished: Bool { get { return internalFinished } set { willChangeValue(forKey: "isFinished") internalFinished = newValue didChangeValue(forKey: "isFinished") } } public override var isAsynchronous: Bool { return true } public init(asyncCompletionBlock: AsyncCompletionBlock? = nil) { internalAsyncCompletionBlock = asyncCompletionBlock super.init() } public override func start() { guard !isFinished else { return } guard !isCancelled else { done() return } isExecuting = true asyncCompletionBlock?(done) } public func run(_ completionBlock: @escaping VoidCompletion = {}) { self.asyncCompletionBlock = { done in completionBlock() done() } } } private extension AsyncOperation { func done() { isExecuting = false isFinished = true } }
func test() { var language = "C" var code = { [language] in print(language) } code() language = "Objc" code() code = { print(language) } code() language = "Swift" code() } test()
// // McUtils.swift // mcwa // // Created by 陈强 on 15/10/13. // Copyright © 2015年 XingfuQiu. All rights reserved. // import Foundation let UMAppKey = "561bcfe1e0f55a0219005cab" let qq_AppId = "1104907496" let qq_AppKey = "DbdC0Qvfkj4yOLsG" let wx_AppId = "wxc49b6a0e3c78364d" let wx_AppKey = "d4624c36b6795d1d99dcf0547af5443d" let share_url = "http://wa.mckuai.com/down" //用户登录,注销Delegate @objc protocol LoginDelegate { // var isLogined: Int? {get set} optional func loginSuccessfull() optional func loginout() } extension DefaultsKeys { static let logined = DefaultsKey<Bool>("UserLogined") static let UserAvater = DefaultsKey<String?>("UserAvatar") static let NickName = DefaultsKey<String?>("UserNickName") static let UserId = DefaultsKey<Int>("UserLoginId") static let MusicStatus = DefaultsKey<Int>("AppMusicStatus") } //保存的用户ID var appUserIdSave: Int = 0 var appUserLogined: Bool = false var appUserNickName: String? var appMusicStatus: Int = 0 var appUserAvatar: String? var appNetWorkStatus: Bool = false let URL_MC = "http://wa.mckuai.com/interface.do?" //上传头像/图片 let upload_url = URL_MC+"act=uploadImg" let addTalk_url = URL_MC+"act=uploadQuestion" let qqlogin_url = URL_MC+"act=login" var player_bg = Player() var player_click = Player() let right_click = NSBundle.mainBundle().pathForResource("right", ofType: "mp3")! let error_click = NSBundle.mainBundle().pathForResource("error", ofType: "mp3")! let music_bg = NSBundle.mainBundle().pathForResource("background", ofType: "mp3")! //PageInfo 用于下拉刷新 class PageInfo { var currentPage: Int = 0 var pageCount: Int = 0 var pageSize: Int = 0 var allCount: Int = 0 init(currentPage: Int, pageCount: Int, pageSize: Int, allCount: Int) { self.currentPage = currentPage self.pageCount = pageCount self.pageSize = pageSize self.allCount = allCount } init(j: JSON) { self.currentPage = j["page"].intValue self.pageCount = j["pageCount"].intValue self.pageSize = j["pageSize"].intValue self.allCount = j["allCount"].intValue } } class MCUtils { /** 显示HUD提示框 :param: view 要显示HUD的窗口 :param: title HUD的标题 :param: imgName 自定义HUD显示的图片 */ class func showCustomHUD(VC: UIViewController, aMsg: String, aType: TSMessageNotificationType) { switch aType { case .Success: TSMessage.showNotificationInViewController(VC.navigationController, title: "成功", subtitle: aMsg, image: nil, type: aType, duration: 0, callback: nil, buttonTitle: nil, buttonCallback: nil, atPosition: .NavBarOverlay, canBeDismissedByUser: true) //TSMessage.showNotificationWithTitle("操作成功", subtitle: aMsg, type: aType) case .Warning: TSMessage.showNotificationInViewController(VC.navigationController, title: "提示", subtitle: aMsg, image: nil, type: aType, duration: 0, callback: nil, buttonTitle: nil, buttonCallback: nil, atPosition: .NavBarOverlay, canBeDismissedByUser: true) //TSMessage.showNotificationWithTitle("MC哇提示", subtitle: aMsg, type: aType) case .Error: TSMessage.showNotificationInViewController(VC.navigationController, title: "出错啦", subtitle: aMsg, image: nil, type: aType, duration: 0, callback: nil, buttonTitle: nil, buttonCallback: nil, atPosition: .NavBarOverlay, canBeDismissedByUser: true) // TSMessage.showNotificationWithTitle("出错啦~!", subtitle: aMsg, type: aType) default: TSMessage.showNotificationInViewController(VC.navigationController, title: "消息", subtitle: aMsg, image: nil, type: aType, duration: 0, callback: nil, buttonTitle: nil, buttonCallback: nil, atPosition: .NavBarOverlay, canBeDismissedByUser: true) //TSMessage.showNotificationWithTitle("消息", subtitle: aMsg, type: aType) } } /** 保存用户配置信息 :param: j JSON */ class func AnalysisUserInfo(j: JSON) { let userId = j["id"].intValue let nickName = j["nickName"].stringValue let userAvatar = j["headImg"].stringValue //保存登录信息 Defaults[DefaultsKeys.UserId] = userId Defaults[DefaultsKeys.NickName] = nickName Defaults[DefaultsKeys.UserAvater] = userAvatar Defaults[DefaultsKeys.logined] = true appUserIdSave = userId appUserNickName = nickName appUserAvatar = userAvatar appUserLogined = true } /** 检查网络状态 */ class func checkNetWorkState(VC: UIViewController) -> Void { //网络状态 AFNetworkReachabilityManager.sharedManager().startMonitoring() AFNetworkReachabilityManager.sharedManager().setReachabilityStatusChangeBlock({st in switch st { case .ReachableViaWiFi: print("网络状态:WIFI") appNetWorkStatus = true // TSMessage.showNotificationWithTitle("哇哦~", subtitle: "你在WIFI网络下面,随便畅玩吧", type: .Success) case .ReachableViaWWAN: print("网络状态:3G") appNetWorkStatus = true TSMessage.showNotificationInViewController(VC.navigationController, title: "警告!警告!", subtitle: "你正在使用流量上网,且玩且珍惜吧", image: nil, type: .Warning, duration: 0, callback: nil, buttonTitle: nil, buttonCallback: nil, atPosition: .NavBarOverlay, canBeDismissedByUser: true) case .NotReachable: print("网络状态:不可用") appNetWorkStatus = false TSMessage.showNotificationInViewController(VC.navigationController, title: "出错啦~!", subtitle: "网络状态异常,请检查网络连接", image: nil, type: .Error, duration: 0, callback: nil, buttonTitle: nil, buttonCallback: nil, atPosition: .NavBarOverlay, canBeDismissedByUser: true) default: print("网络状态:火星") appNetWorkStatus = false TSMessage.showNotificationInViewController(VC.navigationController, title: "出错啦~!", subtitle: "网络状态异常,请检查网络连接", image: nil, type: .Error, duration: 0, callback: nil, buttonTitle: nil, buttonCallback: nil, atPosition: .NavBarOverlay, canBeDismissedByUser: true) } }) AFNetworkReachabilityManager.sharedManager().stopMonitoring() } /** UITableView 空数据时显示的类型 :param: tv 要显示内容的TableView errorType: 1,空数据时; 2,加载失败 */ class func showEmptyView(tv: UITableView, aImg: UIImage, aText: String) { let v = UIView(frame: tv.frame) let img = UIImageView(image: aImg) let btnX = (v.bounds.size.width - img.bounds.size.width) / 2 let btnY = (v.bounds.size.height - img.bounds.size.height - 70) / 2 img.frame = CGRectMake(btnX, btnY, img.bounds.size.width, img.bounds.size.height) v.addSubview(img) let lb = UILabel(frame: CGRectMake(0, btnY+img.frame.size.height+10, v.bounds.size.width, 20)) lb.text = aText lb.numberOfLines = 2; lb.textAlignment = .Center; lb.textColor = UIColor(hexString: "#9494CC") v.addSubview(lb) tv.backgroundView = v tv.separatorStyle = UITableViewCellSeparatorStyle.None } } /** * UIImage 扩展 */ extension UIImage { enum AssetIdentifier : String { case Music_On = "music_on" case Music_Off = "music_off" } convenience init!(assetIdentifier : AssetIdentifier) { self.init(named: assetIdentifier.rawValue) } //通过颜色创建图片 class func applicationCreateImageWithColor(color: UIColor) -> UIImage { let rect = CGRect(x: 0, y: 0, width: 1, height: 1) UIGraphicsBeginImageContext(rect.size) let context = UIGraphicsGetCurrentContext() CGContextSetFillColorWithColor(context, color.CGColor) CGContextFillRect(context, rect) let theImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return theImage } } //CALayer 扩展 extension CALayer { var borderUIColor: UIColor { get { return UIColor(CGColor: self.borderColor!) } set { self.borderColor = newValue.CGColor } } }
// // GordanView.swift // Fish Spot // // Created by Sebastian Baldwin on 16/4/21. // import SwiftUI struct GordanView: View { var body: some View { ZStack { Image("background").resizable().aspectRatio(contentMode: .fill).ignoresSafeArea() VStack{ Image("Brighton").resizable().padding().aspectRatio(contentMode: .fit) Spacer() HStack{ Text("Fish at Cooks River").font(.title3).fontWeight(.bold).foregroundColor(.black).padding().aspectRatio(contentMode: .fit) } HStack{ NavigationLink(destination: FlatheadView()){ ZStack{ Rectangle().fill(Color.white).cornerRadius(20).opacity(0.5).frame(width: 175, height: 110) Image("flathead").resizable().aspectRatio(contentMode: .fit).frame(width: 150, height: 100) } } NavigationLink(destination: SnapperView()){ ZStack{ Rectangle().fill(Color.white).cornerRadius(20).opacity(0.5).frame(width: 175, height: 110) Image("snapper").resizable().aspectRatio(contentMode: .fit).frame(width: 150, height: 100) } } } Spacer(minLength: 20) NavigationLink(destination: BrightonMapView()){ ZStack{ Rectangle().fill(Color("homebutton")).frame(width: 340, height: 60).opacity(0.8).cornerRadius(15).aspectRatio(contentMode: .fit).padding(.bottom) HStack{ Image("map").resizable().aspectRatio(contentMode: .fit).frame(width: 50, height: 40).aspectRatio(contentMode: .fit).padding(.bottom) Text("Get Route").font(.title).fontWeight(.bold).foregroundColor(.white).padding().aspectRatio(contentMode: .fit).padding(.bottom).minimumScaleFactor(0.5) } } } ZStack{ Rectangle().fill(Color.blue).cornerRadius(40).offset(y: 35).frame(height: 150).padding(.top).opacity(0.5).ignoresSafeArea() VStack(spacing: 40){ HStack(spacing: 10){ Spacer() NavigationLink(destination: ContentView().navigationBarBackButtonHidden(true).navigationBarHidden(true)){ Image("home").resizable().aspectRatio(contentMode: .fit).frame(width: 50, height: 60).padding(.top) } NavigationLink(destination: CameraView().navigationBarBackButtonHidden(true).navigationBarHidden(true)){ Image("camera").resizable().aspectRatio(contentMode: .fit).frame(width:50, height: 60).padding(.top) } NavigationLink(destination: CollectionView().navigationBarBackButtonHidden(true).navigationBarHidden(true)){ Image("collection").resizable().aspectRatio(contentMode: .fit).frame(width:50, height: 60).padding(.top) } NavigationLink(destination: WeatherView(viewModel: WeatherModel(weatherServ: WeatherServ())).navigationBarBackButtonHidden(true).navigationBarHidden(true)){ Image("weather").resizable().aspectRatio(contentMode: .fit).frame(width:50, height: 60).padding(.top) } NavigationLink(destination: LawView().navigationBarBackButtonHidden(true).navigationBarHidden(true)){ Image("law").resizable().aspectRatio(contentMode: .fit).frame(width:50, height: 60).padding(.top) } NavigationLink(destination: FishingspotView().navigationBarBackButtonHidden(true).navigationBarHidden(true)){ Image("map").resizable().aspectRatio(contentMode: .fit).frame(width:50, height: 60).padding(.top) } Spacer(minLength: 20) } } } } } } } struct GordanView_Previews: PreviewProvider { static var previews: some View { GordanView() } }
import Foundation /// An object representing a numeric schema type. /// Get more info: https://swagger.io/specification/#schemaObject public struct SpecNumericSchema<T: Codable & Comparable>: Codable, Equatable, Changeable { // MARK: - Nested Types private enum CodingKeys: String, CodingKey { case rawFormat = "format" case multipleOf case defaultValue = "default" case enumeration = "enum" case minimumValue = "minimum" case isMinimumExclusive = "exclusiveMinimum" case maximumValue = "maximum" case isMaximumExclusive = "exclusiveMaximum" } // MARK: - Instance Properties /// The raw value of the format. public var rawFormat: String? /// Specifies that a number must be the multiple of given number. /// Must be a positive number. public var multipleOf: T? /// Default value. public var defaultValue: T? /// An enumeration of possible values. public var enumeration: [T]? /// Lower bound of possible values. public var minimum: SpecSchemaValueBound<T>? /// Upper bound of possible values. public var maximum: SpecSchemaValueBound<T>? // MARK: - Initializers /// Creates a new instance with the provided values. public init( rawFormat: String? = nil, multipleOf: T? = nil, defaultValue: T? = nil, enumeration: [T]? = nil, minimum: SpecSchemaValueBound<T>? = nil, maximum: SpecSchemaValueBound<T>? = nil ) { self.rawFormat = rawFormat self.multipleOf = multipleOf self.defaultValue = defaultValue self.enumeration = enumeration self.minimum = minimum self.maximum = maximum } /// Creates a new instance by decoding from the given decoder. /// /// This initializer throws an error if reading from the decoder fails, or /// if the data read is corrupted or otherwise invalid. /// /// - Parameter decoder: The decoder to read data from. public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) rawFormat = try container.decodeIfPresent(forKey: .rawFormat) multipleOf = try container.decodeIfPresent(forKey: .multipleOf) defaultValue = try container.decodeIfPresent(forKey: .defaultValue) enumeration = try container.decodeIfPresent(forKey: .enumeration) minimum = try container .decodeIfPresent(T.self, forKey: .minimumValue) .map { minimumValue in SpecSchemaValueBound( minimumValue, isExclusive: try container.decodeIfPresent(forKey: .isMinimumExclusive) ) } maximum = try container .decodeIfPresent(T.self, forKey: .maximumValue) .map { maximumValue in SpecSchemaValueBound( maximumValue, isExclusive: try container.decodeIfPresent(forKey: .isMaximumExclusive) ) } } // MARK: - Instance Methods /// Encodes this instance into the given encoder. /// /// This function throws an error if any values are invalid for the given encoder's format. /// /// - Parameter encoder: The encoder to write data to. public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(rawFormat, forKey: .rawFormat) try container.encodeIfPresent(multipleOf, forKey: .multipleOf) try container.encodeIfPresent(defaultValue, forKey: .defaultValue) try container.encodeIfPresent(enumeration, forKey: .enumeration) try container.encodeIfPresent(minimum?.value, forKey: .minimumValue) try container.encodeIfPresent(minimum?.isExclusive, forKey: .isMinimumExclusive) try container.encodeIfPresent(maximum?.value, forKey: .maximumValue) try container.encodeIfPresent(maximum?.isExclusive, forKey: .isMaximumExclusive) } }
// // radioButton.swift // Level // // Created by Nicholas Titzler on 5/18/21. // import SwiftUI struct radioButton: View { var body: some View { Text("hello") } } struct radioButton_Previews: PreviewProvider { static var previews: some View { radioButton() } }
// // Constants.swift // epg // // Created by Yakimovich, Kirill on 9/25/17. // Copyright © 2017 Yakimovich, Kirill. All rights reserved. // import UIKit struct Durations { static let dayInMinutes = 24 * 60 } struct Sizes { static let channelHeight: CGFloat = 120 static let channelHeaderWidth: CGFloat = 120 static let minuteWidth: CGFloat = 10 static let dayWidth = minuteWidth * CGFloat(Durations.dayInMinutes) } enum SupplementaryViews: String { case now = "NowSupplementaryView" case channelHeader = "ChannelHeaderSupplementaryView" }
// // PlayersTableViewController.swift // ChessProfiles // // Created by Shawn Bierman on 9/9/20. // Copyright © 2020 Shawn Bierman. All rights reserved. // import UIKit class PlayersTableViewController: UITableViewController { let searchController = UISearchController() var isSearching: Bool = false { didSet { if !isSearching { updateData() }}} var players = [String]() { didSet { updateData() }} var filteredPlayers = [String]() { didSet { updateData() }} // MARK: - Lifecycle Methods. override func viewDidLoad() { super.viewDidLoad() setup() fetchPlayers(withTitle: .GM) // a default offering of data } // MARK: - Private Methods. private func setup() { view.backgroundColor = .systemBackground let image = UIImage(systemName: "slider.horizontal.3") let btn = UIBarButtonItem(image: image, style: .plain, target: self, action: #selector(filterByTitle)) searchController.searchResultsUpdater = self searchController.searchBar.delegate = self searchController.searchBar.placeholder = "Search for a player" searchController.obscuresBackgroundDuringPresentation = false navigationItem.rightBarButtonItem = btn navigationItem.searchController = searchController navigationController?.navigationBar.prefersLargeTitles = true } private func fetchPlayers(withTitle title: Title) { Network.shared.fetchPlayers(with: title) { [weak self] (result) in guard let self = self else { return } switch result { case .success(let success): self.players = success.players DispatchQueue.main.async { self.title = title.localizedName self.tableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: true) } case .failure(let error): dump(error.localizedDescription) } } } private func updateData() { // There will likely be more here soon. DispatchQueue.main.async { self.tableView.reloadData() } } @objc func filterByTitle() { let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) for title in Title.allCases { let action = UIAlertAction(title: title.localizedName, style: .default) { [weak self] _ in guard let self = self else { return } self.fetchPlayers(withTitle: title) } alert.addAction(action) } alert.addAction(UIAlertAction(title: "Cancel", style: .cancel)) present(alert, animated: true, completion: nil) } } // MARK: - TableView datasource and delegate methods. extension PlayersTableViewController { override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { isSearching ? filteredPlayers.count : players.count } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let vc = ProfileDetailViewController() vc.modalPresentationStyle = .popover vc.player = isSearching ? filteredPlayers[indexPath.row] : players[indexPath.row] navigationController?.present(vc, animated: true, completion: nil) } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell() let model = isSearching ? filteredPlayers : players let player = model[indexPath.row] cell.textLabel?.text = player return cell } } // MARK: - SearchBar datasource and delegate methods. extension PlayersTableViewController: UISearchResultsUpdating, UISearchBarDelegate { func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { if searchText.count == 0 { isSearching = false } } func updateSearchResults(for searchController: UISearchController) { guard let filter = searchController.searchBar.text, !filter.isEmpty else { return } isSearching = true filteredPlayers = players.filter { $0.lowercased().contains(filter.lowercased()) } } func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { isSearching = false } }
// // ViewController.swift // TaskNew // // Created by Joe on 15/04/20. // Copyright © 2020 jess. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var taskView: UITableView! @IBOutlet weak var searchBar: UISearchBar! var filterdata : [CATransactionViewModel] = [] var tableviewArray : [CATransactionViewModel] = [] var testTransPerData:[CATransactionViewModel] = [CATransactionViewModel( description: "ATM Cash withdrawal and atm card needed to stayyyy", time: "06:00:00", date: "27/05/2019", transactionCurrency: "₹", transactionAmount: "3456", billingCurrency: "£", billingAmount: "666", debitCredit: "1"), CATransactionViewModel(description: "MOB/Mobile/Recharge", time: "11:00:00", date: "27/05/2019", transactionCurrency: "₹", transactionAmount: "5400", billingCurrency: "£", billingAmount: "+300", debitCredit: "1"), CATransactionViewModel(description: "Fast Cash ATM", time: "11:00:00", date: "27/05/2019", transactionCurrency: "₹", transactionAmount: "5300", billingCurrency: "£", billingAmount: "+800", debitCredit: "0"), CATransactionViewModel(description: "ATM Cash withdrawal", time: "06:00:00", date: "27/05/2019", transactionCurrency: "₹", transactionAmount: "3456", billingCurrency: "£", billingAmount: "666", debitCredit: "1"), CATransactionViewModel(description: "Amazon/Pay", time: "12:00:00", date: "27/05/2019", transactionCurrency: "₹", transactionAmount: "4300", billingCurrency: "$", billingAmount: "+400", debitCredit: "1"), CATransactionViewModel(description: "Mobile Recharge", time: "09:00:00", date: "27/05/2019", transactionCurrency: "₹", transactionAmount: "7300", billingCurrency: "£", billingAmount: "+600", debitCredit: "0"), CATransactionViewModel(description: "Mobile Recharge", time: "09:00:00", date: "27/05/2019", transactionCurrency: "₹", transactionAmount: "7300", billingCurrency: "£", billingAmount: "+600", debitCredit: "0"), CATransactionViewModel(description: "Mobile Recharge", time: "09:00:00", date: "27/05/2019", transactionCurrency: "₹", transactionAmount: "7300", billingCurrency: "£", billingAmount: "+600", debitCredit: "0"), CATransactionViewModel(description: "Mobile Recharge", time: "09:00:00", date: "27/05/2019", transactionCurrency: "₹", transactionAmount: "7300", billingCurrency: "£", billingAmount: "+600", debitCredit: "0"), CATransactionViewModel(description: "Mobile Recharge", time: "09:00:00", date: "27/05/2019", transactionCurrency: "₹", transactionAmount: "7300", billingCurrency: "£", billingAmount: "+600", debitCredit: "0" ) ] override func viewDidLoad() { super.viewDidLoad() self.taskView.delegate = self self.taskView.dataSource = self self.searchBar.delegate = self self.tableviewArray = self.testTransPerData.sorted(by: {$0.description < $1.description}) } } extension ViewController : UITableViewDataSource , UITableViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.tableviewArray.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let taskcelldata = self.taskView.dequeueReusableCell(withIdentifier: "cellID", for: indexPath) as! TaskTableViewCell taskcelldata.descriptionLabel.text = tableviewArray[indexPath.row].description taskcelldata.amountLabel.text = tableviewArray[indexPath.row].billingAmount taskcelldata.dateLabel.text = tableviewArray[indexPath.row].date taskcelldata.timeLabel.text = tableviewArray[indexPath.row].time taskcelldata.backgroundColor = UIColor.lightGray return taskcelldata } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 120 } override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) { } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { self.searchBar(searchText: "ATM" ) let vc = storyboard?.instantiateViewController(withIdentifier: "DetailsController") as? DetailsController vc?.descr = testTransPerData[indexPath.row].description vc?.amt = testTransPerData[indexPath.row].billingAmount vc?.date = testTransPerData[indexPath.row].date vc?.time = testTransPerData[indexPath.row].time self.navigationController?.pushViewController(vc! , animated: true) } } extension ViewController: UISearchBarDelegate{ func searchBar(searchText: String) { // let resultPredicate = NSPredicate(format: "description Contains(%@)", searchText).sorted(by: {$0.date > $1.date}) // filterdata = testTransPerData.filter { resultPredicate.evaluate(with: $0) } // print(filterdata) filterdata = testTransPerData.filter({ descri -> Bool in return descri.description.localizedCaseInsensitiveContains(searchText) || descri.billingAmount.localizedCaseInsensitiveContains(searchText) || descri.time.localizedCaseInsensitiveContains(searchText) || descri.date.localizedCaseInsensitiveContains(searchText) }) } func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { if(searchText.isEmpty) { tableviewArray = testTransPerData.sorted(by: {$0.description < $1.description}) return taskView.reloadData() } self.searchBar(searchText:searchText) tableviewArray = filterdata.sorted(by: {$0.description < $1.description}) taskView.reloadData() } }
// // AppReducer.swift // weather_forecast // // Created by Thinh Nguyen on 9/30/20. // Copyright © 2020 Thinh Nguyen. All rights reserved. // Email:thinhnguyen12389@gmail.com // import Foundation import ReSwift func appReducer(action: Action, state: AppState?) -> AppState { var state = state ?? AppState() switch action { default: state.forecastState = forecastReducer(action: action, state: state.forecastState) } return state }
// // ImageSectionController.swift // FeedExample // // Created by Simon Lee on 3/21/19. // Copyright © 2019 Shao Ping Lee. All rights reserved. // import UIKit import IGListKit class ImageSectionController: ListSectionController { var image: UIImage? override func sizeForItem(at index: Int) -> CGSize { let height = collectionContext?.containerSize.height ?? 0 return CGSize(width: height * 2 / 3.0, height: height) } override func cellForItem(at index: Int) -> UICollectionViewCell { guard let cell = collectionContext?.dequeueReusableCell(of: ImageCell.self, for: self, at: index) as? ImageCell else { fatalError() } guard let image = image else { return cell } cell.image = image return cell } override func didUpdate(to object: Any) { image = object as? UIImage } override init() { super.init() self.inset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 10) } }
import UIKit final class AddToDoItemRouter { private let navigationController: UINavigationController init(navigationController: UINavigationController) { self.navigationController = navigationController } func returnToCallerController() { navigationController.popViewController(animated: true) } }
// // ViewController.swift // TransitionAnimate // // Created by 句芒 on 2017/7/11. // Copyright © 2017年 fanwei. All rights reserved. // import UIKit extension TransitionAnimateType { static func count() -> NSInteger { return 9 } static func value(_ index:Int) -> String { return ["scaleAlpha","fromTop","toLeft","fromTopLeftCorner","rotateXZ","dragFromRight","flip","rightIn","flipOut"][index] } } class ViewController:UITableViewController { override func viewDidLoad() { self.tableView.register(UINib.init(nibName: "CellView", bundle: nil), forCellReuseIdentifier: "CellView") } let manager = AnimateManager() override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let cell = tableView.cellForRow(at: indexPath) as! CellView let controller = SecondViewController() if let value = TransitionAnimateType(rawValue:indexPath.row) { manager.animateType = value } manager.time = cell.timeStepper.value if cell.useModal.isOn { controller.transitioningDelegate = manager self.present(controller, animated: true, completion: nil) }else { self.navigationController?.delegate = manager self.navigationController?.pushViewController(controller, animated: true) } } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return TransitionAnimateType.count() } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 80 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView .dequeueReusableCell(withIdentifier: "CellView") as! CellView cell.animateName.text = TransitionAnimateType.value(indexPath.row) return cell } }
// // ListDiffableArray.swift // SideMenuHUB // // Created by Daniel Yo on 12/17/17. // Copyright © 2017 Daniel Yo. All rights reserved. // import UIKit import IGListKit class ListDiffableArray: NSObject, ListDiffable { var identifier:String? var array:Array<Any>? override init() { super.init() identifier = UUID().uuidString } init(withArray array:Array<Any>) { super.init() identifier = UUID().uuidString self.array = array } func diffIdentifier() -> NSObjectProtocol { return self.identifier! as NSObjectProtocol } func isEqual(toDiffableObject object: ListDiffable?) -> Bool { return self.diffIdentifier() === object!.diffIdentifier() } }
// // GCenterMagnificationFilter.swift // imageprocessing02 // // Created by C.H Lee on 13/05/2018. // Copyright © 2018 LEE CHUL HYUN. All rights reserved. // import Foundation import Metal struct CenterMagnificationUniforms { var width: Float var height: Float var minRadius: Float var radius: Float } class GCenterMagnificationFilter: GImageFilter { var _radius: Float = 0 var radius: Float { get { return _radius } set { self.isDirty = true _radius = newValue } } var uniforms: UnsafeMutablePointer<CenterMagnificationUniforms> override init?(context: GContext, filterType: GImageFilterType) { guard let buffer = context.device.makeBuffer(length: MemoryLayout<CenterMagnificationUniforms>.size, options: [MTLResourceOptions.init(rawValue: 0)]) else { return nil } uniforms = UnsafeMutableRawPointer(buffer.contents()).bindMemory(to:CenterMagnificationUniforms.self, capacity:1) super.init(functionName: "magnify_center", context: context, filterType: filterType) uniformBuffer = buffer } override func configureArgumentTable(commandEncoder: MTLComputeCommandEncoder) { uniforms[0].width = Float(self.provider0.texture!.width) uniforms[0].height = Float(self.provider0.texture!.height) uniforms[0].radius = radius; uniforms[0].minRadius = 0.5; commandEncoder.setBuffer(self.uniformBuffer, offset: 0, index: 0) } override func setValue(_ value: Float) { radius = value } }
// // PlayedDominoCollectionViewLayout.swift // MexicanTrain // // Created by Ceri on 27/06/2020. // import UIKit class PlayedDominoCollectionViewLayout: UICollectionViewLayout { fileprivate struct Placement { enum Direction { case right, down, left } let x: Int let y: Int let direction: Direction } private var cache: [UICollectionViewLayoutAttributes] = [] private var contentWidth: CGFloat { guard let collectionView = collectionView else { return 0 } return collectionView.bounds.width - (collectionView.contentInset.left + collectionView.contentInset.right) } private var contentHeight: CGFloat = 0 override var collectionViewContentSize: CGSize { return CGSize(width: contentWidth, height: contentHeight) } override func prepare() { super.prepare() guard let collectionView = collectionView else { return } let contentWidth = self.contentWidth let layoutAttributes = (0 ..< collectionView.numberOfItems(inSection: 0)) .map { $0.toPlacement() } .enumerated() .map { $0.element.toLayoutAttributes(index: $0.offset, width: contentWidth) } cache = layoutAttributes contentHeight = layoutAttributes.reduce(CGFloat(0)) { max($0, $1.frame.maxY) } } override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { cache[safe: indexPath.row] } override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { cache.filter { rect.intersects($0.frame) } } } private extension PlayedDominoCollectionViewLayout.Placement { private static func p(_ x: Int, _ y: Int, _ direction: Direction) -> PlayedDominoCollectionViewLayout.Placement { PlayedDominoCollectionViewLayout.Placement(x: x, y: y, direction: direction) } private static let placements: [PlayedDominoCollectionViewLayout.Placement] = [ .p(7, 0, .down), .p(7, 2, .right), .p(8, 1, .right), .p(9, 2, .down), .p(8, 3, .down), .p(9, 4, .down), .p(8, 5, .left), .p(7, 4, .left), .p(6, 5, .left), .p(5, 4, .left), .p(4, 5, .down), .p(5, 6, .down), .p(4, 7, .down), .p(5, 8, .right), .p(6, 7, .right), .p(7, 8, .right), .p(8, 7, .right), .p(9, 8, .right), .p(10, 7, .right), .p(11, 8, .right), .p(12, 7, .right), .p(13, 8, .down), .p(12, 9, .down), .p(13, 10, .down), .p(12, 11, .left), .p(11, 10, .left), .p(10, 11, .left), .p(9, 10, .left), .p(8, 11, .left), .p(7, 10, .left), .p(6, 11, .left), .p(5, 10, .left), .p(4, 11, .left), .p(3, 10, .left), .p(2, 11, .left) ] static func placement(for index: Int) -> PlayedDominoCollectionViewLayout.Placement { placements[safe: index] ?? .p(1, 10, .left) } func toLayoutAttributes(index: Int, width: CGFloat) -> UICollectionViewLayoutAttributes { let attributes = UICollectionViewLayoutAttributes(forCellWith: IndexPath(row: index, section: 0)) let frame = toRect(width: width) attributes.frame = frame attributes.transform = toTransform(size: frame.size) return attributes } private func toRect(width: CGFloat) -> CGRect { let multiple = width / 15.0 let origin = CGPoint(x: CGFloat(x) * multiple, y: CGFloat(y) * multiple) let size = CGSize(width: multiple, height: multiple * 2.0) return CGRect(origin: origin, size: size) } private func toTransform(size: CGSize) -> CGAffineTransform { switch direction { case .down: return .identity case .left: return .rotationAround(angle: .pi / 2.0, size: size) case .right: return .rotationAround(angle: .pi / -2.0, size: size) } } } private extension Int { func toPlacement() -> PlayedDominoCollectionViewLayout.Placement { PlayedDominoCollectionViewLayout.Placement.placement(for: self) } }
// // DetailsViewController.swift // TodoApp // // Created by Fatih Nayebi on 2016-04-29. // Copyright © 2016 Fatih Nayebi. All rights reserved. // import UIKit import ReactiveCocoa import ReactiveSwift class DetailsViewController: UIViewController { @IBOutlet weak var txtFieldName: UITextField! @IBOutlet weak var txtFieldDescription: UITextField! @IBOutlet weak var txtFieldNotes: UITextField! @IBOutlet weak var switchCompleted: UISwitch! var viewModel = TodoViewModel(todo: nil) override func viewDidLoad() { super.viewDidLoad() store.selectedTodo.startWithValues { todos in let model = todos.first! self.txtFieldName.text = model.name self.txtFieldDescription.text = model.description self.txtFieldNotes.text = model.notes self.switchCompleted.isOn = model.completed self.viewModel = TodoViewModel(todo: model) } setupUpdateSignals() } func setupUpdateSignals() { txtFieldName.reactive.continuousTextValues.observeValues { (values: String?) -> () in if let newName = values { let newTodo = todoNameLens.set(newName, self.viewModel.todo!) store.dispatch(UpdateTodoAction(todo: newTodo)) } } txtFieldDescription.reactive.continuousTextValues.observeValues { (values: String?) -> () in if let newDescription = values { let newTodo = todoDescriptionLens.set(newDescription, self.viewModel.todo!) store.dispatch(UpdateTodoAction(todo: newTodo)) } } txtFieldNotes.reactive.continuousTextValues.observeValues { (values: String?) -> () in if let newNotes = values { let newTodo = todoNotesLens.set(newNotes, self.viewModel.todo!) store.dispatch(UpdateTodoAction(todo: newTodo)) } } switchCompleted.reactive.isOnValues.observeValues { (value: Bool) -> () in let newTodo = todoCompletedLens.set(value, self.viewModel.todo!) store.dispatch(UpdateTodoAction(todo: newTodo)) } } }
// // DateFormatter.swift // TrainingNote // // Created by Mizuki Kubota on 2020/03/02. // Copyright © 2020 MizukiKubota. All rights reserved. // import Foundation struct DateStringFormatter { let dateFormatter = DateFormatter() init() { dateFormatter.dateFormat = DateFormatter.dateFormat( fromTemplate: "M/d/yyyy", options: 0, locale: Locale(identifier: "ja_JP") ) } func formatt(date: Date) -> String { var dateString: String dateString = dateFormatter.string(from: date) return dateString } }
// // CustomerDetailHeadTableViewCell.swift // neversitup // // Created by Kasidid Wachirachai on 27/1/21. // import UIKit class CustomerDetailHeadTableViewCell: UITableViewCell { static let identifier: String = "CustomerDetailHead" @IBOutlet weak var customerImageView: UIImageView! @IBOutlet weak var customerNameLabel: UILabel! @IBOutlet weak var customerIdLabel: UILabel! var customer: Customer? { didSet { guard let customer = customer else { return } customerImageView.image = customer.image customerNameLabel.text = customer.name customerIdLabel.text = customer.id } } override func awakeFromNib() { super.awakeFromNib() selectionStyle = .none } }
import UIKit // Nested Optional let name: String??? = "Bedu" //1.- Force Unwrap print(name!!!) //2.- Optional Biding if let name = name, let almostUnwrapped = name, let unwrapped = almostUnwrapped { print(unwrapped) } //3.- Guard within Function func unwrapp(_ value: String???) { guard let value = value, let almostUnwrapped = value, let unwrapped = almostUnwrapped else { return } print(unwrapped) } unwrapp(name)
// // ViewController.swift // Meal_Clone // // Created by 전상민 on 2021/06/11. // import UIKit class ViewController: UIViewController { var mealList: [MealModel] = [] // MealModel type의 배열 선언(MealModel은 구조체로 구현) @IBOutlet weak var mealTableView: UITableView! // 새로운 리스트를 추가/저장 하기위해 unwindToSegue를 사용(직접 만들어주어야 한다.) @IBAction func unwindToMealList(sender: UIStoryboardSegue){ guard let detailVC = sender.source as? MealDetailViewController else{ return } // 눌린 셀이 있는지 if let selectedIndexPath = self.mealTableView.indexPathForSelectedRow{ mealList[selectedIndexPath.row] = detailVC.mealModel // 화면에 갱신 self.mealTableView.reloadRows(at: [selectedIndexPath], with: .automatic) // reload 한 순간 select된 것이 없어지기 때문에 deselect는 안해도 된다. // self.mealTableView.deselectRow(at: [selectedIndexPath], animated:true) }else{ let insertIndexPath = IndexPath(row: mealList.count, section: 0) mealList.append(detailVC.mealModel) // 새로만든 데이터를 추가 // self.mealTableView.reloadData() // 화면에 출력 // insert를 사용하는 방법 self.mealTableView.insertRows(at: [insertIndexPath], with: .automatic) } saveMeal() } func saveMeal(){ // archive // 어디에 저장 할 것이진 path필요 DispatchQueue.global().async { // background Thread로 let documentDirectory = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first // 디렉토리 경로 추가 guard let archiveURL = documentDirectory?.appendingPathComponent("meals") else{ return } // let isSuccessSave = NSKeyedArchiver.archiveRootObject(mealList, toFile: archiveURL.path) do{ let archivedData = try NSKeyedArchiver.archivedData(withRootObject: self.mealList, requiringSecureCoding: true) try archivedData.write(to: archiveURL) }catch{ print(error) } } // if isSuccessSave{ // print("success saved") // }else{ // print("failed save") // } } var isEditMode = false @IBAction func doEdit(_ sender: Any) { // 누를때마다 토클 isEditing = !isEditing mealTableView.setEditing(isEditing, animated: true) } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete{ // 모델에서 해당되는 셀을 지움 mealList.remove(at: indexPath.row) // 화면에도 지워줌 mealTableView.deleteRows(at: [indexPath], with: .automatic) saveMeal() } } func loadMeals() -> [MealModel]? { let documentDirectory = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first // 디렉토리 경로 추가 guard let archiveURL = documentDirectory?.appendingPathComponent("meals") else{ return nil } guard let codedData = try? Data(contentsOf: archiveURL) else{ return nil } guard let unarchivedData = try? NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(codedData) else{ return nil } return unarchivedData as? [MealModel] // return NSKeyedUnarchiver.unarchiveObject(withFile:archiveURL.path ) as? [MealModel] } override func viewDidLoad() { super.viewDidLoad() // 저장한 데이터 가져옴 if let loadedMeals = loadMeals(){ self.mealList = loadedMeals } // 없으면 기본 dummy 데이터 출력 if mealList.count == 0{ let dummy1 = MealModel.init(name: "스파게티", photo: UIImage(named: "meal1"), rating: 3) let dummy2 = MealModel.init(name: "피자", photo: UIImage(named: "meal2"), rating: 1) let dummy3 = MealModel.init(name: "티라미슈", photo: UIImage(named: "meal3"), rating: 5) mealList.append(dummy1) mealList.append(dummy2) mealList.append(dummy3) } } // 화면에 있는 세그워이를 씀 override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "presentDetail"{ // 호출될때 identifier로 구분 }else if segue.identifier == "showDetail"{ let detailVC = segue.destination as! MealDetailViewController // 목적지에 있는 VC를 가져온다. // 선택한 index(음식의 데이터)를 가져오기 let selectedCell = sender as! MealCell // 해당되는 셀의 indexPath값을 가져옴 // Optional Type이라서 if let으로 unrapping if let selectedIndexPath = mealTableView.indexPath(for: selectedCell){ detailVC.mealModel = mealList[selectedIndexPath.row] } } } } extension ViewController: UITabBarDelegate{ func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 100 } } extension ViewController: UITableViewDataSource{ func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return mealList.count // 셀 개수는 meallist의 크기만큼 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let mealCell = tableView.dequeueReusableCell(withIdentifier: "mealCell", for: indexPath) as! MealCell // MealCell Type으로 Type casting mealCell.name.text = mealList[indexPath.row].name mealCell.ratingView.rating = mealList[indexPath.row].rating mealCell.ratingView.isUserInteractionEnabled = false mealCell.mealImageView.image = mealList[indexPath.row].photo ?? UIImage(named: "defaultPhoto") return mealCell } }
// // PokemonService.swift // DuckDuckGooseAPIApp // // Created by MAC Consultant on 3/1/19. // Copyright © 2019 William Benfer. All rights reserved. // import Foundation class CharacterService{ static let urlBeg = "https://api.duckduckgo.com/?q=" static let urlEnd = "+characters&format=json" static var urlString = urlBeg + "simpsons" + urlEnd static func setFranchise(_ u : String){ var s = "" var b = false for c in u{ if c != " "{ b = false s += String(c) }else{ if(!b){ s += "+" b = true } } } urlString = urlBeg + s + urlEnd } static func downloadPicture(for character: Simpson, completion: @escaping (Simpson)->()) { guard let url = URL(string: character.imageURL) else { return } URLSession.shared.dataTask(with: url) { (data, _, _) in character.image = data completion(character) }.resume() } static func downloadJSON(completion: @escaping ([Simpson])->() ){ guard let url = URL(string: CharacterService.urlString) else { print("Invalid url") return } var request = URLRequest(url: url, cachePolicy: .returnCacheDataElseLoad, timeoutInterval: 10.0) request.httpMethod = "GET" URLSession.shared.dataTask(with: request) { (data, response, error) in if let dat = data { let decoder = JSONDecoder() do { /* let t = try decoder.decode(TopLevel.self, from: dat) var characters = [Character]() for r in t.RelatedTopics{ characters.append(Character(r.Text, r.Icon.URL)) } */ let character = try decoder.decode(Simpsons.self, from: dat) completion(character.simpsons) } catch { print(error) } } }.resume() } }
// // Constants.swift // ShakeAuth // // Created by Mike Wang on 11/19/15. // Copyright © 2015 Cornell Tech. All rights reserved. // import Foundation import UIKit struct UIConstants { static let primaryColor = UIColor(red: 0.0/255, green: 212.0/255, blue: 225.0/255, alpha: 1) static let fadedPrimaryColor = UIColor(red: 0.0/255, green: 212.0/255, blue: 225.0/255, alpha: 0.5) static let lightGrayColor = UIColor.lightGrayColor() static let darkGrayColor = UIColor.darkGrayColor() static let whiteColor = UIColor.whiteColor() static let fieldWidthProp = 0.6 static let spacing0 = 8 static let spacing1 = 20 static let spacing2 = 32 static let spacing3 = 64 static let spacing4 = 128 static let borderThin = CGFloat(0.5) static let borderThick = CGFloat(1) static let logoSizeLarge = 50 static let logoSizeMed = 100 static let profilePictureSize = 96 static let profilePictureSizeSmall = 64 static let fontLarge = CGFloat(64) static let fontBig = CGFloat(32) static let fontMed = CGFloat(24) static let fontSmallish = CGFloat(18) static let fontSmall = CGFloat(14) static let fontTiny = CGFloat(10) static let titleFont = UIFont.systemFontOfSize(fontLarge, weight: UIFontWeightThin) }
// // GZEUserConvertible.swift // Gooze // // Created by Yussel Paredes Perez on 4/4/18. // Copyright © 2018 Gooze. All rights reserved. // import Foundation import Gloss class GZEUserConvertible: NSObject { static var subClassesConstructors: [GZEUserConvertible.Type.Type] = [] static func arrayFrom(jsonArray: [JSON]) -> [GZEUserConvertible]? { var models: [GZEUserConvertible] = [] for json in jsonArray { if let dateRequest = GZEDateRequest(json: json) { models.append(dateRequest) } else if let chatUser = GZEChatUser(json: json) { models.append(chatUser) } else { return nil } } return models } func getUser() -> GZEChatUser { fatalError("Must be overriden by subclas") } }
// // SupportTheme.swift // Hippo // // Created by Vishal on 20/11/18. // import UIKit public struct SupportTheme { var supportListHeadingFont: UIFont? = UIFont.regular(ofSize: 15.0) var supportListHeadingColor = #colorLiteral(red: 0.1725490196, green: 0.137254902, blue: 0.2, alpha: 1) var supportDescSubHeadingFont: UIFont? = UIFont.bold(ofSize: 17) var supportDescSubHeadingColor = #colorLiteral(red: 0.1725490196, green: 0.137254902, blue: 0.2, alpha: 1) var supportDescriptionFont: UIFont? = UIFont.regular(ofSize: 15.0) var supportDescriptionColor = #colorLiteral(red: 0.1725490196, green: 0.137254902, blue: 0.2, alpha: 1) var supportButtonTitleFont: UIFont? = UIFont.regular(ofSize: 15.0) var supportButtonTitleColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1) var supportButtonThemeColor = #colorLiteral(red: 0.3843137255, green: 0.4901960784, blue: 0.8823529412, alpha: 1) public init() { } }
// // AddressBookManager.swift // Pin // // Created by Ken on 6/24/14. // Copyright (c) 2014 Bacana. All rights reserved. // import Foundation class AddressBookManager: NSObject { var addressBook: APAddressBook var contactList: NSMutableArray = [] // MARK: - Public Methods - override init() { addressBook = APAddressBook() } func checkAddressBookAccess() { switch APAddressBook.access().value { case APAddressBookAccessGranted.value: accessGrantedForAddressBook() break case APAddressBookAccessUnknown.value: accessGrantedForAddressBook() break case APAddressBookAccessDenied.value: var alert: UIAlertView = UIAlertView(title: "Privacy Warning", message: "Permission was not granted for Contacts.", delegate: self, cancelButtonTitle: "OK") alert.show() break default: break } } func getMobileNumbersArray() -> NSMutableArray { var newContactsList: NSMutableArray = [] for person in self.contactList { if (person.valueForKey("phone") != nil) { var digitOnlyNumber: NSString = SHSPhoneNumberFormatter.digitOnlyString(person.valueForKey("phone") as NSString) newContactsList.addObject("+\(digitOnlyNumber)") } } return newContactsList } // MARK: - Private Methods - private func accessGrantedForAddressBook() { contactList = [] addressBook.loadContacts( { (contacts: [AnyObject]!, error: NSError!) in if (error == nil) { self.populatedContactList(contacts, contactList: self.contactList) } }) } private func populatedContactList(contacts: [AnyObject], contactList: [AnyObject]) { for contact: AnyObject in contacts { var currentContact = contact as APContact if !(isContactValid(currentContact)) { continue } for phone: AnyObject in currentContact.phones { self.contactList.addObject([ "name": currentContact.firstName, "phone": phone as NSString ]) } } } private func isContactValid(contact: APContact) -> Bool { return !(contact.firstName == nil || contact.phones.count == 0) } }
// // Articles.swift // // // Created by Deja Cespedes on 03/06/2016. // // import Foundation import CoreData import ArticleObject class Articles: NSManagedObject { @NSManaged var headline: String @NSManaged var summary: String @NSManaged var thumbnailURL: String @NSManaged var articleObject: ArticleObject }
import Foundation import Combine typealias AppStore = Store<AppState, AppAction> typealias Reducer<State, Action> = (inout State, Action) -> Void typealias Middleware<State, Action> = (State, Action) -> AnyPublisher<Action, Error>? typealias Dispatcher = (AppAction) -> Void
// // ViewController.swift // ghulistios // // Created by f4ni on 13.12.2020. // import UIKit import CoreData class MainViewController: UITableViewController, UISearchBarDelegate { let cellID = "cellID" var since = Int(0) let service = APIService() var word: String?{ didSet{ self.updateTableContent() } } var predicate = NSPredicate(value: true) lazy var fetchedhResultController: NSFetchedResultsController<NSFetchRequestResult> = { let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: String(describing: User.self)) fetchRequest.sortDescriptors = [NSSortDescriptor(key: "id", ascending: true)] if let word = self.searchBar.text, (word.trimmingCharacters(in: .whitespaces).count > 0){ self.predicate = NSPredicate(format: "login contains[c] %@ || notes contains[c] %@", argumentArray: [word, word]) } else{ } print("filter by \(word)") let frc = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: CoreDataStack.sharedInstance.persistentContainer.viewContext, sectionNameKeyPath: nil, cacheName: nil) frc.delegate = self return frc }() let refresh = UIRefreshControl() override func viewDidLoad() { super.viewDidLoad() self.title = "GitHub User" tableView.register(UserListTableViewCell.self, forCellReuseIdentifier: cellID) tableView.refreshControl = refresh refresh.addTarget(self, action: #selector(refreshHandle), for: .valueChanged) updateTableContent() setUpSearchBar() } @objc func refreshHandle(){ service.since = 0 Model.sharedInstance.clearData() updateTableContent() } lazy var searchBar: UISearchBar = { let s = UISearchBar(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width, height: 65)) s.delegate = self return s }() fileprivate func setUpSearchBar() { self.tableView.tableHeaderView = searchBar } func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { guard !searchText.isEmpty, (searchText.trimmingCharacters(in: .whitespaces).count > 0) else { self.predicate = NSPredicate(value: true) return } self.predicate = NSPredicate(format: "login contains[c] %@ || notes contains[c] %@", argumentArray: [searchText, searchText]) self.word = searchText //self.fetchedhResultController.fetchRequest.predicate = predicate updateTableContent() /*do { try self.fetchedhResultController.performFetch() print("COUNT FETCHED FIRST: \(String(describing: self.fetchedhResultController.sections?[0].numberOfObjects))") } catch let error { print("ERROR: \(error)") } */ print(self.searchBar.text) tableView.reloadData() } func updateTableContent() { do { self.fetchedhResultController.fetchRequest.predicate = self.predicate try self.fetchedhResultController.performFetch() print("COUNT FETCHED FIRST: \(String(describing: self.fetchedhResultController.sections?[0].numberOfObjects))") } catch let error { print("ERROR: \(error)") } service.getUserList (since: since, completion: { (result) in switch result { case .Success(let data): if self.service.since == 0 { } //Model.sharedInstance.clearData() Model.sharedInstance.saveInCoreDataWith(array: data) if let lastID = data.last?["id"] { self.since = lastID as! Int print("last id is \(lastID)") } self.tableView.reloadData() case .Error(let message): DispatchQueue.main.async { self.showAlertWith(title: "Error", message: message) } } self.refresh.endRefreshing() }) } func showAlertWith(title: String, message: String, style: UIAlertController.Style = .alert) { let alertController = UIAlertController(title: title, message: message, preferredStyle: style) let action = UIAlertAction(title: title, style: .default) { (action) in self.dismiss(animated: true, completion: nil) } alertController.addAction(action) self.present(alertController, animated: true, completion: nil) } override func scrollViewWillBeginDragging(_: UIScrollView) { self.searchBar.endEditing(true) } } extension MainViewController{ override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellID) as! UserListTableViewCell if let user = fetchedhResultController.object(at: indexPath) as? User { var invertAv = false if ((Int(indexPath.row + 1)%3) == 0){ invertAv = true } cell.setPhotoCellWith(user: user, invertAv: invertAv) if user.notes != nil, (user.notes?.trimmingCharacters(in: .whitespaces).count)! > 0 { cell.notedLbl.layer.opacity = 1 } else{ cell.notedLbl.layer.opacity = 0 } } return cell } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { var count = 0 if let cnt = fetchedhResultController.sections?.first!.numberOfObjects{ count = cnt } return count } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 120 //100 = sum of labels height + height of divider line } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let vc = UserDetailViewController() if let usr = fetchedhResultController.object(at: indexPath) as? User { vc.user = usr vc.mainVC = self self.present(vc, animated: true, completion: {(()->Void).self }) } } /* override func tableView(_: UITableView, willDisplay _: UITableViewCell, forRowAt indexPath: IndexPath) { if let lastElement = fetchedhResultController.sections?.first!.numberOfObjects { if indexPath.item == (lastElement - 2) { //appendHandler() tableView.beginUpdates() print(indexPath) updateTableContent() tableView.endUpdates() } } } */ } extension MainViewController{ class UserListTableViewCell: UITableViewCell { let nameTV: UILabel = { let label = UILabel() label.textColor = #colorLiteral(red: 0.2549019754, green: 0.2745098174, blue: 0.3019607961, alpha: 1) //label.backgroundColor = #colorLiteral(red: 0.9764705896, green: 0.850980401, blue: 0.5490196347, alpha: 1) label.font = UIFont.systemFont(ofSize: 18) label.numberOfLines = 0 label.textAlignment = .center label.lineBreakMode = .byWordWrapping return label }() let notedLbl: UILabel = { let label = UILabel() label.textColor = #colorLiteral(red: 0.7450980544, green: 0.1568627506, blue: 0.07450980693, alpha: 1) //label.backgroundColor = #colorLiteral(red: 0.9764705896, green: 0.850980401, blue: 0.5490196347, alpha: 1) label.font = UIFont.systemFont(ofSize: 14) label.numberOfLines = 0 label.textAlignment = .center label.lineBreakMode = .byWordWrapping label.text = "NOTED" return label }() let avatarIV: UIImageView = { let iv = UIImageView() iv.contentMode = .scaleAspectFill iv.backgroundColor = #colorLiteral(red: 0.1019607857, green: 0.2784313858, blue: 0.400000006, alpha: 1) iv.layer.cornerRadius = 40 iv.layer.masksToBounds = true return iv }() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?){ super.init(style: style, reuseIdentifier: reuseIdentifier) self.addSubview(nameTV) self.addSubview(avatarIV) self.addSubview(notedLbl) self.addConstraintsWithFormat("V:|-16-[v0(80)]", views: avatarIV) self.addConstraintsWithFormat("H:|-16-[v0(80)]-16-[v1]", views: avatarIV, nameTV) self.addConstraintsWithFormat("V:|-24-[v0(24)]", views: nameTV) self.addConstraintsWithFormat("V:[v0(24)]-24-|", views: notedLbl) self.addConstraintsWithFormat("H:[v0]-24-|", views: notedLbl) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } func setPhotoCellWith(user: User, invertAv: Bool) { //print("setPhoto for \( user.login )") DispatchQueue.main.async { self.nameTV.text = "\(user.login ?? "")" //self.tagsLabel.text = photo.tags if let url = user.avatar_url { self.avatarIV.loadImageUsingCacheWithURLString(url, placeHolder: UIImage(named: "placeholder"), invertAv: invertAv) } } } } } extension MainViewController: NSFetchedResultsControllerDelegate { func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) { switch type { case .insert: self.tableView.insertRows(at: [newIndexPath!], with: .automatic) case .delete: self.tableView.deleteRows(at: [indexPath!], with: .automatic) default: break } } func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { self.tableView.endUpdates() } func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { self.tableView.beginUpdates() } }
// // CustomTextField.swift // Follow // // Created by Tom Wicks on 04/04/2016. // Copyright © 2016 Miln. All rights reserved. // import Foundation import UIKit class CustomTextField: UITextField{ var change: Bool = false { didSet { if change { // Add some customization textColor = UIColor.yellowColor() backgroundColor = UIColor.blueColor() } else { // Change the colors back to original textColor = UIColor.blackColor() backgroundColor = UIColor.whiteColor() } } } }
// // EndPointTests.swift // StrutsTests // // Created by Yunarta on 24/9/18. // Copyright © 2018 mobilesolution works. All rights reserved. // import XCTest import Struts class EndPointTests: XCTestCase { func testDiscoverEndPoint() throws { class TestEndPoint: EndPoint { } class UnregisteredEndPoint: EndPoint { } let plant = PlantBuilder(credentialManager: TestPlantCredentialManager()) .add(withId: "app") { core in core.addEndPoint(of: TestEndPoint.self, TestEndPoint()) } .build() // test get without type reference let strut: CoreStrut? = plant.discover(core: .core(id: "app")) XCTAssertNotNil(strut?.endPoint(of: TestEndPoint.self)) XCTAssertNil(strut?.endPoint(of: UnregisteredEndPoint.self)) } func testGetEndPoint() throws { class TestEndPoint: EndPoint { } class UnregisteredEndPoint: EndPoint { } // let factory = RealmCredentialManagerFactory(app: "Plant") // // let coreStrut = try CoreStrutImplWithRealm(credentialManager: factory.createStrutManager(id: "app", for: RealmShortCredential.self)) // coreStrut.addEndPoint(TestEndPoint.self, endpoint: TestEndPoint()) let plant = PlantBuilder(credentialManager: TestPlantCredentialManager()) .add(withId: "app") { core in core.addEndPoint(of: TestEndPoint.self, TestEndPoint()) } .build() // test get without type reference let strut: CoreStrut? = plant.discover(core: .core(id: "app")) XCTAssertNotNil(try strut?.getEndPoint(of: TestEndPoint.self)) XCTAssertThrowsError(try strut?.getEndPoint(of: UnregisteredEndPoint.self)) } }
// // UserDefaultView.swift // demo_SwiftUI // // Created by li’Pro on 2020/11/13. // import SwiftUI struct UserDefaultView: View { var body: some View { Text("查看 UserDefaultView.swift 文件") } } struct UserDefaultView_Previews: PreviewProvider { static var previews: some View { UserDefaultView() } } // https://juejin.im/post/6844904018121064456 struct GlobalSetting_0 { static var isFirstLanch: Bool { get { return UserDefaults.standard.object(forKey: "isFirstLanch") as? Bool ?? false } set { UserDefaults.standard.set(newValue, forKey: "isFirstBoot") } } static var uiFontValue: Float { get { return UserDefaults.standard.object(forKey: "uiFontValue") as? Float ?? 14 } set { UserDefaults.standard.set(newValue, forKey: "uiFontValue") } } } @propertyWrapper struct UserDefault<T> { let key: String let defaultValue: T var wrappedValue: T { get { UserDefaults.standard.object(forKey: key) as? T ?? defaultValue } set { UserDefaults.standard.set(newValue, forKey: key) } } } struct GlobalSetting { @UserDefault(key: "isFirstLaunch", defaultValue: true) static var isFirstLaunch: Bool @UserDefault(key: "uiFontValue", defaultValue: 12.0) static var uiFontValue: Float }
// // ProfitLossCell.swift // APPFORMANAGEMENT // // Created by Chanakan Jumnongwit on 3/27/2560 BE. // Copyright © 2560 REVO. All rights reserved. // import UIKit class ProfitLossCell: UITableViewCell { //@IBOutlet weak var sawImage:UIImageView! @IBOutlet weak var fullname:UILabel! @IBOutlet weak var profitTotal:UILabel! @IBOutlet weak var detailView:UIView! @IBOutlet weak var detail:UILabel! override func awakeFromNib() { super.awakeFromNib() //set image corner radius /*sawImage.layer.cornerRadius = 5.0*/ //set border to UIView detailView.layer.borderWidth = 1 detailView.layer.cornerRadius = 5.0 detailView.layer.borderColor = UIColor(red:0, green:122/255.0, blue:255/255.0, alpha: 1.0).cgColor } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
// // CheckoutController.swift // productsApp // // Created by Samanta Clara Coutinho Rondon do Nascimento on 2019-07-03. // Copyright © 2019 Sam. All rights reserved. // import Foundation import UIKit import RxSwift import RxCocoa import RxDataSources class CheckoutController: BaseController { @IBOutlet weak var tableView: UITableView! private lazy var dataSource: RxTableViewSectionedReloadDataSource<CheckoutSection> = { RxTableViewSectionedReloadDataSource<CheckoutSection>( configureCell: { dataSource, tableView, indexPath, item in switch dataSource[indexPath] { case .details(let cart): let cell = tableView.dequeue(cellClass: CheckoutCell.self, indexPath: indexPath) cell.configure(total: cart.price) cell.payButton.rx.tap.asDriver() .drive(onNext: { [weak self] in guard let self = self else { return } self.viewModel.coordinator?.didEndPayment(self, didSelect: .checkout(cart: self.viewModel.cart)) }).disposed(by: cell.disposedCell) return cell case .discountDetails(let discount): let cell = tableView.dequeue(cellClass: DiscountCell.self, indexPath: indexPath) cell.configure(discount: discount) return cell case .productDetails(let product, let isLastItem): let cell = tableView.dequeue(cellClass: BuyProductCell.self, indexPath: indexPath) cell.configure(product: product, isLastItem: isLastItem) return cell } }) }() private var disposeBag = DisposeBag() var viewModel: CheckoutViewModel init(viewModel: CheckoutViewModel) { self.viewModel = viewModel super.init() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() loadNavBar() loadLayout() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) viewModel.viewDidAppear() } private func loadNavBar() { navigationItem.title = Constants.Screen.checkout navigationItem.leftBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "back"), style: .done, target: self, action: #selector(actionBackButton)) } @objc private func actionBackButton() { viewModel.coordinator?.didEndPayment(self, didSelect: .dismiss) } private func loadLayout() { tableView.estimatedRowHeight = UITableView.automaticDimension tableView.rx.setDelegate(self).disposed(by: disposeBag) tableView.registerNib(cellClass: CheckoutCell.self) tableView.registerNib(cellClass: DiscountCell.self) tableView.registerNib(cellClass: BuyProductCell.self) viewModel.productsObservable.flatMap { (products) -> Observable<[CheckoutSection]> in return .just(self.viewModel.updateTableView(by: products)) }.bind(to: tableView.rx.items(dataSource: dataSource)).disposed(by: disposeBag) } } extension CheckoutController: UITableViewDelegate { func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { switch dataSource[section] { case .cartSection: return 0 case .discountSection: return 30 case .productSection: return 50 } } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let view = UIView() view.backgroundColor = .clear return view } }
// // StadiumPhotosViewCell.swift // MyApp2 // // Created by Anıl Demirci on 6.07.2021. // import UIKit class StadiumPhotosViewCell: UITableViewCell { @IBOutlet weak var stadiumPhotosView: UIImageView! @IBOutlet weak var commentLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
// // BaseResponse.swift // MicroMarket // // Created by antran on 9/16/20. // Copyright © 2020 antran. All rights reserved. // import UIKit struct ResponseServerEntity<T : Codable> : Codable { var status: String? var message: String? var result: T? }
import UIKit extension CGColor { var uiColor: UIColor { return UIColor(cgColor: self) } }
// // HomeWireframe.swift // TestInfo // // Created by Thiago Santos on 28/09/2018. // Copyright © 2018 Thiago Santos. All rights reserved. // import Foundation import UIKit class Homewireframe { var viewController: UINavigationController? func make() -> UINavigationController? { let viewController = HomeviewControllerBuild().make(wireframe: self) self.viewController = viewController return viewController } func showDetails(item: ContentItem){ self.viewController?.pushViewController(DetailsWireframe.make(item: item), animated: true) } }
import GRDB class EvmSyncSourceRecord: Record { let blockchainTypeUid: String let url: String let auth: String? init(blockchainTypeUid: String, url: String, auth: String?) { self.blockchainTypeUid = blockchainTypeUid self.url = url self.auth = auth super.init() } override class var databaseTableName: String { "evmSyncSource" } enum Columns: String, ColumnExpression { case blockchainTypeUid, name, url, auth } required init(row: Row) { blockchainTypeUid = row[Columns.blockchainTypeUid] url = row[Columns.url] auth = row[Columns.auth] super.init(row: row) } override func encode(to container: inout PersistenceContainer) { container[Columns.blockchainTypeUid] = blockchainTypeUid container[Columns.url] = url container[Columns.auth] = auth } }
// // CaptureAndUploadController.swift // blueunicorn // // Created by Thomas Blom on 6/24/16. // Copyright © 2016 Good Karma Software. All rights reserved. // import UIKit class HomeViewController: UIViewController { var image: UIImage? // the last image we took or chose, which the user may upload. @IBAction func cameraButton() { pickPhoto() } override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: - 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. print( "prepareForSegue with identifier \(segue.identifier)" ) if segue.identifier == "Camera" { } } } extension HomeViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate { func takePhotoWithCamera() { let imagePicker = UIImagePickerController() imagePicker.sourceType = .Camera imagePicker.delegate = self imagePicker.allowsEditing = true imagePicker.view.tintColor = view.tintColor presentViewController(imagePicker, animated: true, completion: nil) } func choosePhotoFromLibrary() { let imagePicker = UIImagePickerController() imagePicker.sourceType = .PhotoLibrary imagePicker.delegate = self imagePicker.allowsEditing = true imagePicker.view.tintColor = view.tintColor presentViewController(imagePicker, animated: true, completion: nil) } func pickPhoto() { if UIImagePickerController.isSourceTypeAvailable(.Camera) { takePhotoWithCamera() // showPhotoMenu() } else { choosePhotoFromLibrary() } } /* func showPhotoMenu() { let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet) let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil) alertController.addAction(cancelAction) let takePhotoAction = UIAlertAction(title: "Take Photo", style: .Default, handler: { _ in self.takePhotoWithCamera() }) alertController.addAction(takePhotoAction) let chooseFromLibraryAction = UIAlertAction(title:"Choose From Library", style: .Default, handler:{ _ in self.choosePhotoFromLibrary() }) alertController.addAction(chooseFromLibraryAction) presentViewController(alertController, animated: true, completion: nil) } */ func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { image = info[UIImagePickerControllerEditedImage] as? UIImage if let metadata = info[UIImagePickerControllerMediaMetadata] as? NSDictionary { print( "Metadata for photograph:\n" ) print( "\(metadata)" ) } dismissViewControllerAnimated(false, completion: nil) if image != nil { performSegueWithIdentifier( "Upload", sender: self ) } } func imagePickerControllerDidCancel(picker: UIImagePickerController) { dismissViewControllerAnimated(true, completion: nil) } }
// // TCButton.swift // XXColorTheme // // Created by xixi197 on 16/1/20. // Copyright © 2016年 xixi197. All rights reserved. // import UIKit //TCButton @IBDesignable public class TCButton: UIButton { // tintColor ColorTheme private var _normalTintColor: UIColor? private var _highlightedTintColor: UIColor? private var _selectedTintColor: UIColor? // image private var _normalTemplateImage: UIImage? private var _highlightedTemplateImage: UIImage? // all image private var _imageBorderWidth: CGFloat = 0 private var _imageBorderRadius: CGFloat = 30 private var _imageBorderAlpha: CGFloat = 0.16 @IBInspectable var xx_isTextDown: Bool = false var xx_imageWidth: CGFloat = 60 // 82 * 82 var xx_textTopMargin: CGFloat = 8 public override init(frame: CGRect) { super.init(frame: frame) initButton() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initButton() } private func initButton() { clipsToBounds = true titleLabel?.textAlignment = .Center } private func xx_updateImageTintColor() { if selected { if highlighted { tintColor = _highlightedTintColor ?? _normalTintColor } else { tintColor = _selectedTintColor ?? _normalTintColor } } else { if highlighted { tintColor = _selectedTintColor ?? _highlightedTintColor ?? _normalTintColor } else { tintColor = _normalTintColor } } } public override var selected: Bool { didSet { xx_updateImageTintColor() } } public override var highlighted: Bool { didSet { xx_updateImageTintColor() } } @IBInspectable var xx_normalTintColor: UIColor? { get { return _normalTintColor } set { if newValue == _normalTintColor { return } _normalTintColor = newValue setTitleColor(_normalTintColor, forState: .Normal) xx_updateImageTintColor() } } @IBInspectable var xx_highlightedTintColor: UIColor? { get { return _highlightedTintColor } set { if newValue == _highlightedTintColor { return } _highlightedTintColor = newValue adjustsImageWhenHighlighted = _highlightedTintColor == nil setTitleColor(_highlightedTintColor, forState: .Highlighted) xx_updateImageTintColor() } } @IBInspectable var xx_selectedTintColor: UIColor? { get { return _selectedTintColor } set { if newValue == _selectedTintColor { return } _selectedTintColor = newValue adjustsImageWhenHighlighted = _highlightedTintColor == nil setTitleColor(_highlightedTintColor, forState: .Selected) xx_updateImageTintColor() } } private func xx_updateTemplateImage(templateImage: UIImage?, forState state: UIControlState) { setImage(templateImage?.borderedImage(xx_imageBorderWidth, radius: xx_imageBorderRadius, alpha: xx_imageBorderAlpha), forState: state) } private func xx_updateNormalTemplateImage() { xx_updateTemplateImage(_normalTemplateImage, forState: .Normal) } private func xx_updateHighlightedTemplateImage() { for state: UIControlState in [.Highlighted, .Selected] { xx_updateTemplateImage(_highlightedTemplateImage, forState: state) } } @IBInspectable var xx_normalTemplateImage: UIImage? { get { return _normalTemplateImage } set { if newValue == _normalTemplateImage { return } _normalTemplateImage = newValue xx_updateNormalTemplateImage() } } @IBInspectable var xx_highlightedTemplateImage: UIImage? { get { return _highlightedTemplateImage } set { if newValue == _highlightedTemplateImage { return } _highlightedTemplateImage = newValue xx_updateHighlightedTemplateImage() } } @IBInspectable var xx_imageBorderWidth: CGFloat { get { return _imageBorderWidth } set { if newValue == _imageBorderWidth { return } _imageBorderWidth = newValue xx_updateNormalTemplateImage() xx_updateHighlightedTemplateImage() } } @IBInspectable var xx_imageBorderRadius: CGFloat { get { return _imageBorderRadius } set { if newValue == _imageBorderRadius { return } _imageBorderRadius = newValue xx_updateNormalTemplateImage() xx_updateHighlightedTemplateImage() } } @IBInspectable var xx_imageBorderAlpha: CGFloat { get { return _imageBorderAlpha } set { if newValue == _imageBorderAlpha { return } _imageBorderAlpha = newValue xx_updateNormalTemplateImage() xx_updateHighlightedTemplateImage() } } public override func imageRectForContentRect(contentRect: CGRect) -> CGRect { return xx_isTextDown ? CGRectMake((contentRect.size.width - xx_imageWidth) / 2, 0, xx_imageWidth, xx_imageWidth) : super.imageRectForContentRect(contentRect) } public override func titleRectForContentRect(contentRect: CGRect) -> CGRect { return xx_isTextDown ? CGRectMake(0, xx_imageWidth + xx_textTopMargin, contentRect.size.width, contentRect.size.height - xx_imageWidth - xx_textTopMargin) : super.titleRectForContentRect(contentRect) } }
// // Articulo.swift // recetas // // Created by Eugenia Perez Velasco on 20/3/15. // Copyright (c) 2015 Roberto Dehesa. All rights reserved. // import Foundation import CoreData class Articulo: NSManagedObject { @NSManaged var categoria_id: NSNumber @NSManaged var descripcion: String @NSManaged var idarticulo: NSNumber @NSManaged var imagen: String @NSManaged var nombre: String @NSManaged var newRelationship: NSSet }