text
stringlengths
8
1.32M
// // AddItemTableViewController.swift // GroceryListApp // // Created by Ella on 2/27/17. // Copyright © 2017 Ellatronic. All rights reserved. // import UIKit class AddItemTableViewController: UITableViewController { // MARK: Properties var groceries = [Grocery]() // Initialize an empty array of Grocery objects @IBAction func addItem(_ sender: UIButton) { self.performSegue(withIdentifier: "unwindToGroceryList", sender: self) // groceryList.append("Hello") } override func viewDidLoad() { super.viewDidLoad() // Load the grocery list loadAddGroceryItems() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return groceries.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // Table view cells are reused and should be dequeued using a cell identifier let cellIdentifier = "AddItemCell" guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? AddItemTableViewCell else { fatalError("The dequeued cell is not instance of AddItemTableViewCell") } // Fetch the appropriate grocery for the data source layout let grocery = groceries[indexPath.row] cell.addGroceryItemLabel.text = grocery.name cell.addItemGroceryImageView.image = grocery.photo return cell } /* // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ // MARK: Private Methods private func loadAddGroceryItems() { let photo1 = UIImage(named: "apple") let photo2 = UIImage(named: "banana") let photo3 = UIImage(named: "orange") let photo4 = UIImage(named: "milk") let photo5 = UIImage(named: "cereal") let photo6 = UIImage(named: "bread") let photo7 = UIImage(named: "cheese") guard let grocery1 = Grocery(name: "Apple", photo: photo1, quantity: 0) else { fatalError("Unable to instantiate grocery1") } guard let grocery2 = Grocery(name: "Banana", photo: photo2, quantity: 0) else { fatalError("Unable to instantiate grocery2") } guard let grocery3 = Grocery(name: "Orange", photo: photo3, quantity: 0) else { fatalError("Unable to instantiate grocery3") } guard let grocery4 = Grocery(name: "Milk", photo: photo4, quantity: 0) else { fatalError("Unable to instantiate grocery4") } guard let grocery5 = Grocery(name: "Cereal", photo: photo5, quantity: 0) else { fatalError("Unable to instantiate grocery5") } guard let grocery6 = Grocery(name: "Bread", photo: photo6, quantity: 0) else { fatalError("Unable to instantiate grocery6") } guard let grocery7 = Grocery(name: "Cheese", photo: photo7, quantity: 0) else { fatalError("Unable to instantiate grocery7") } groceries += [grocery1, grocery2, grocery3, grocery4, grocery5, grocery6, grocery7] } }
// // PhotoCell.swift // ios-gemini-demo // // Created by OkuderaYuki on 2018/04/15. // Copyright © 2018年 OkuderaYuki. All rights reserved. // import Gemini import UIKit final class PhotoCell: GeminiCell { static var identifier: String { return String(describing: self) } @IBOutlet weak var imageView: UIImageView! }
// // GeoFireUtils.swift // MakerMobile // // Created by Ronélio on 19/12/17. // Copyright © 2017 SoftwellSolutions. All rights reserved. // import UIKit import Foundation import FirebaseDatabase import GeoFire open class GeoFireUtils: NSObject { fileprivate var mDatabase: DatabaseReference? fileprivate var geoFire: GeoFire? fileprivate var watchDatabase: DatabaseReference? fileprivate var watchGeoFire: GeoFire? fileprivate var watchGeoQuery: GFCircleQuery? open func setPosition(_ formGUID: String, success: String, successArgs: [Any], node: String!, key: String!, lat: Double!, lng: Double!) { if (lat == nil || lng == nil){ return } if mDatabase == nil{ mDatabase = Database.database().reference().child(node) } if(geoFire == nil){ geoFire = GeoFire(firebaseRef: mDatabase) } let location = CLLocation.init(latitude: lat, longitude: lng) geoFire!.setLocation(location, forKey: key!, withCompletionBlock: { (error) in if error == nil{ if(success != ""){ var array = [Any]() array.append(true) var i = 1; while i <= successArgs.count - 1 { array.append(successArgs[i] is NSNull ? "" : successArgs[i]); i = i + 1; } Singleton.shared.ansycCallback(formGUID, funName: success, funArgs: array) } }}) } open func watch(_ formGUID: String, success: String, successArgs: [Any], node: String, lat: Double, lng: Double, radius: Double) { if watchDatabase == nil{ watchDatabase = Database.database().reference().child(node) } if(watchGeoFire == nil){ watchGeoFire = GeoFire(firebaseRef: watchDatabase) } if(watchGeoQuery != nil){ watchGeoQuery?.removeAllObservers(); } let location = CLLocation.init(latitude: lat, longitude: lng); watchGeoQuery = watchGeoFire!.query(at: location, withRadius: radius); watchGeoQuery?.observe(.keyEntered, with: {(snapshot: DataSnapshot!, key: String!, location: CLLocation!) in self.observe(formGUID, funName: success, funArgs: successArgs, snapshot: snapshot, with: "enter", previous: snapshot.key) }) watchGeoQuery?.observe(.keyExited, with: {(snapshot: DataSnapshot!, key: String!, location: CLLocation!) in self.observe(formGUID, funName: success, funArgs: successArgs, snapshot: snapshot, with: "exit", previous: snapshot.key) }) watchGeoQuery?.observe(.keyMoved, with: {(snapshot: DataSnapshot!, key: String!, location: CLLocation!) in self.observe(formGUID, funName: success, funArgs: successArgs, snapshot: snapshot, with: "moved", previous: snapshot.key) }) } open func stopWatching(){ watchGeoQuery?.removeAllObservers() } fileprivate func observe(_ formGUID: String, funName: String, funArgs: [Any], snapshot: DataSnapshot, with action: String, previous: String?) { var array = [Any]() var json = [String: Any]() if let dict = snapshot.value as? [String: Any] { for (key, value) in dict { json[key] = value } } array.append(action) array.append(json) if let _ = previous { array.append(previous!) } var i = 1; while i <= funArgs.count - 1 { array.append(funArgs[i] is NSNull ? "" : funArgs[i]); i = i + 1; } Singleton.shared.ansycCallback(formGUID, funName: funName, funArgs: array) } }
// // SpellListTableViewCell.swift // GlyphMaker // // Created by Patrik Hora on 18/03/2018. // Copyright © 2018 Manicek. All rights reserved. // import UIKit class SpellListTableViewCell: UITableViewCell { static let cellIdentifier = "SpellListTableViewCell" private let nameLabel = UILabel() private let damageLabel = UILabel() override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) backgroundColor = .gray layer.cornerRadius = 8 nameLabel.font = UIFont.systemFont(ofSize: 15) nameLabel.textColor = .black damageLabel.font = UIFont.systemFont(ofSize: 15) damageLabel.textColor = .black addSubviewsAndSetupConstraints() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func configure(with spell: Spell) { nameLabel.text = spell.name damageLabel.text = "Damage: " + String(format: "%.0f", spell.damage) } } private extension SpellListTableViewCell { func addSubviewsAndSetupConstraints() { addSubviews( [ nameLabel, damageLabel ] ) nameLabel.snp.makeConstraints { (make) in make.centerY.equalToSuperview() make.left.equalToSuperview().offset(10) } damageLabel.snp.makeConstraints { (make) in make.centerY.equalToSuperview() make.left.equalTo(self.snp.centerX) } } }
// // PhotoCell.swift // CoreData-Lab // // Created by Juan Ceballos on 4/26/20. // Copyright © 2020 Juan Ceballos. All rights reserved. // import UIKit import NetworkHelper class PhotoCell: UICollectionViewCell { private lazy var photoImageView: UIImageView = { let imageView = UIImageView() imageView.image = UIImage(systemName: "photo") imageView.backgroundColor = .cyan return imageView }() override init(frame: CGRect) { super.init(frame: UIScreen.main.bounds) commnonInit() } required init?(coder: NSCoder) { super.init(coder: coder) commnonInit() } public func configureCell(photo: Photo) { photoImageView.setImage(with: photo.largeImageURL) { (result) in switch result { case .failure(let error): print("\(error)") case .success(let image): DispatchQueue.main.async { self.photoImageView.image = image } } } } private func commnonInit() { setupPhotoImageViewConstraints() } private func setupPhotoImageViewConstraints() { addSubview(photoImageView) photoImageView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ photoImageView.leadingAnchor.constraint(equalTo: leadingAnchor), photoImageView.trailingAnchor.constraint(equalTo: trailingAnchor), photoImageView.topAnchor.constraint(equalTo: topAnchor), photoImageView.bottomAnchor.constraint(equalTo: bottomAnchor) ]) } }
// // LifestyleEntryViewController.swift // DissTest // // Created by Owen Malcolmson-Priest on 13/03/2020. // Copyright © 2020 Owen Malcolmson-Priest. All rights reserved. // View that takes in the lifestyle vaulues in the data entry import UIKit class LifestyleEntryViewController: UIViewController{ /** Values that will be used to create the mood object, mood value are passed here through the segue from the previous screen. */ var valueForMood = 0 var valueForStress = 0 var valueForProductivity = 0 var valueForSleepHours = 0 var ValueForExerciseHours = 0 var valueForWater = 0 var valueForAlcohol = 0 var valueForExerciseMinutes = 0 var valueForSleepMinutes = 0 var valueForLocation = "" var optionHour = "" var sleepHour = "" //function that runs when the screen is loaded override func viewDidLoad() { super.viewDidLoad() //Formats the views sleepView.layer.cornerRadius = 7 sleepView.layer.masksToBounds = true sleepView.layer.backgroundColor = UIColor.systemGray6.cgColor waterView.layer.cornerRadius = 7 waterView.layer.masksToBounds = true waterView.layer.backgroundColor = UIColor.systemGray6.cgColor alcoholView.layer.cornerRadius = 7 alcoholView.layer.masksToBounds = true alcoholView.layer.backgroundColor = UIColor.systemGray6.cgColor locationView.layer.cornerRadius = 7 locationView.layer.masksToBounds = true locationView.layer.backgroundColor = UIColor.systemGray6.cgColor exerciseView.layer.cornerRadius = 7 exerciseView.layer.masksToBounds = true exerciseView.layer.backgroundColor = UIColor.systemGray6.cgColor advanceBtn.layer.backgroundColor = UIColor.systemIndigo.cgColor advanceBtn.layer.cornerRadius = 7 advanceBtn.layer.masksToBounds = true errorTxt.isHidden = true informationView.isHidden = true informationView.layer.cornerRadius = 7 informationView.layer.masksToBounds = true informationView.layer.shadowColor = UIColor.systemGray.cgColor informationView.layer.shadowRadius = 2.5 informationView.layer.backgroundColor = UIColor.systemGray6.cgColor //Keyboard locked to numberpad where only integers are allowed as data values sleepHoursTxt.keyboardType = UIKeyboardType.numberPad waterTxt.keyboardType = UIKeyboardType.numberPad sleepMinutes.keyboardType = UIKeyboardType.numberPad exerciseHouseTxt.keyboardType = UIKeyboardType.numberPad exerciseMinutes.keyboardType = UIKeyboardType.numberPad alcoholTxt.keyboardType = UIKeyboardType.numberPad //scales the label to be visible on smaller screen sizes errorTxt.adjustsFontSizeToFitWidth = true } //IBOutlets @IBOutlet weak var errorTxt: UILabel! @IBOutlet weak var locationTxtField: UITextField! @IBOutlet weak var waterLbl: UILabel! @IBOutlet weak var sleepTxt: UILabel! @IBOutlet weak var exerciseMinutes: UITextField! @IBOutlet weak var informationView: UIView! @IBOutlet weak var sleepMinutes: UITextField! @IBOutlet weak var advanceBtn: UIButton! @IBOutlet weak var locationView: UIView! @IBOutlet weak var alcoholView: UIView! @IBOutlet weak var sleepView: UIView! @IBOutlet weak var exerciseView: UIView! @IBOutlet weak var waterView: UIView! @IBOutlet weak var informationLbl: UILabel! @IBOutlet weak var sleepHoursTxt: UITextField! @IBOutlet weak var exerciseHouseTxt: UITextField! @IBOutlet weak var waterTxt: UITextField! @IBOutlet weak var alcoholTxt: UITextField! //Shows the information view @IBAction func informationBtn(_ sender: Any) { alcoholView.alpha = 1 sleepView.alpha = 1 locationView.alpha = 1 exerciseView.alpha = 1 waterView.alpha = 1 advanceBtn.alpha = 1 informationView.alpha = 0 UIView.animate(withDuration: 1.5, animations: { self.alcoholView.alpha = 0 self.alcoholView.isHidden = true self.sleepView.alpha = 0 self.sleepView.isHidden = true self.locationView.alpha = 0 self.locationView.isHidden = true self.exerciseView.alpha = 0 self.exerciseView.isHidden = true self.waterView.alpha = 0 self.waterView.isHidden = true self.advanceBtn.alpha = 0 self.advanceBtn.isHidden = true self.informationView.alpha = 1 self.informationView.isHidden = false self.informationLbl.text = "An individuals lifestyle can have a big effect on mood. Enter accurately your lifestyle details from today and it will be used to find trends" }) } //Closes the information view @IBAction func closeBtn(_ sender: Any) { alcoholView.alpha = 0 sleepView.alpha = 0 locationView.alpha = 0 exerciseView.alpha = 0 waterView.alpha = 0 advanceBtn.alpha = 0 informationView.alpha = 1 UIView.animate(withDuration: 1.5, animations: { self.alcoholView.alpha = 1 self.alcoholView.isHidden = false self.sleepView.alpha = 1 self.sleepView.isHidden = false self.locationView.alpha = 1 self.locationView.isHidden = false self.exerciseView.alpha = 1 self.exerciseView.isHidden = false self.waterView.alpha = 1 self.waterView.isHidden = false self.advanceBtn.alpha = 1 self.advanceBtn.isHidden = false self.informationView.alpha = 0 self.informationView.isHidden = false }) sleepTxt.adjustsFontSizeToFitWidth = true waterLbl.adjustsFontSizeToFitWidth = true informationLbl.text = "An individuals lifestyle can have a big effect on mood. Enter accurately your lifestyle details from today and it will be used to find trends" } //Sets the Sleep Hours variable @IBAction func sleepHoursField(_ sender: Any) { if sleepHoursTxt.text == "" { valueForSleepHours = 0 } else { var text: String = sleepHoursTxt.text! var value = Int(text) valueForSleepHours = value! } } //Sets the exercise hours variable @IBAction func exerciseHouseTxt(_ sender: Any) { if exerciseHouseTxt.text == "" { ValueForExerciseHours = 0 } else { var text: String = exerciseHouseTxt.text! var value = Int(text) ValueForExerciseHours = value! } } //Sets the water value @IBAction func waterTxt(_ sender: Any) { if waterTxt.text == "" { valueForWater = 0 } else { var text: String = waterTxt.text! var value = Int(text) valueForWater = value! } } //Sets the exercise minutes value @IBAction func exerciseMinutes(_ sender: Any) { if exerciseMinutes.text == "" { valueForExerciseMinutes = 0 } else { var text: String = exerciseMinutes.text! var value = Int(text)! valueForExerciseMinutes = value } } // @IBAction func sleepMinutes(_ sender: Any) { // if sleepMinutes.text == "" { // valueForSleepMinutes = 0 // // } else { // var text: String = sleepMinutes.text! // var value = Int(text)! // valueForSleepMinutes = value // } // } //sets the sleep minutes value @IBAction func sleepMinutes(_ sender: Any) { if sleepMinutes.text == "" { valueForSleepMinutes = 0 //defaults 0 if the entry is empty } else { var text: String = sleepMinutes.text! var value = Int(text)! valueForSleepMinutes = value } } //Sets the alcohol value @IBAction func AlcoholTxt(_ sender: Any) { if alcoholTxt.text == ""{ valueForAlcohol = 0 }else { var text: String = alcoholTxt.text! var value = Int(text) valueForAlcohol = value! } } // @IBAction func locationTxtField(_ sender: Any) { // var text: String = locationTxtField.text! // valueForLocation = text // print(valueForLocation) // } // //sets the location value @IBAction func locationTxtField(_ sender: Any) { var text: String = locationTxtField.text! valueForLocation = text //print(valueForLocation) } //stops the user advancing if the fields haven't been completed override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool { if locationTxtField.text == "" || sleepHoursTxt.text == "" || sleepMinutes.text == "" || exerciseMinutes.text == "" || exerciseHouseTxt.text == "" || alcoholTxt.text == "" { errorTxt.isHidden = false errorTxt.text = "Not all fields completed" return false }else if valueForSleepHours > 23 || valueForSleepHours < 0 { errorTxt.text = "Hours for sleep cannot be over 23" errorTxt.isHidden = false return false } else if valueForSleepMinutes > 59 || valueForSleepMinutes < 0{ errorTxt.text = "Minutes for sleep must be under 59" errorTxt.isHidden = false return false }else if valueForExerciseMinutes > 59 || valueForExerciseMinutes < 0 { errorTxt.text = "Minutes for exercise must be under 59" errorTxt.isHidden = false return false } else if ValueForExerciseHours > 23 || ValueForExerciseHours < 0 { errorTxt.text = "Hours for exercise must be between 0 and 23" errorTxt.isHidden = false return false } else{ errorTxt.isHidden = true return true } } @IBAction func nextBtn(_ sender: Any) { guard var tester = sleepHoursTxt.text else { return } let valueForSlee = Int(tester) ?? 0 /////////////////// guard var exercise = exerciseHouseTxt.text else { return } let valueForEx = Int(exercise) ?? 0 ////////////////// guard var water = waterTxt.text else{ return} let valueForWate = Int(water) ?? 0 //////////////// guard var alcohol = alcoholTxt.text else { return} let valueForAlc = Int(alcohol) ?? 0 guard var minutesSleep = sleepMinutes.text else { return} let minSleep = Int(minutesSleep) ?? 0 guard var minutesExercise = exerciseMinutes.text else { return} let minExercise = Int(minutesExercise) ?? 0 //////////// valueForExerciseMinutes = minExercise valueForSleepMinutes = minSleep valueForAlcohol = valueForAlc valueForWater = valueForWate ValueForExerciseHours = valueForEx valueForSleepHours = valueForSlee print(valueForSleepHours) } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation //Passes the mood values into the next screen override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "lifestyleSegue" { let activitiesVC = segue.destination as! ActivitiesViewController activitiesVC.valueForSleepHours = valueForSleepHours activitiesVC.ValueForExercise = ValueForExerciseHours activitiesVC.valueForWater = valueForWater activitiesVC.valueForAlcohol = valueForAlcohol activitiesVC.valueForMood = valueForMood activitiesVC.valueForProductivity = valueForProductivity activitiesVC.valueForStress = valueForStress activitiesVC.valueForSleepMinutes = valueForSleepMinutes activitiesVC.valueForExerciseMinutes = valueForExerciseMinutes activitiesVC.valueForLocation = valueForLocation // let activitiesVC = segue.destination as! } // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } }
// // DayCell.swift // Viewer // // Created by Kenta Nakai on 2015/09/23. // Copyright © 2015年 UROURO. All rights reserved. // import UIKit class DayCell: UITableViewCell { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var countLabel: UILabel! @IBOutlet weak var thumbnailImageView: UIImageView! }
// // XcodeDeviceParser.swift // Buildasaur // // Created by Honza Dvorsky on 30/06/2015. // Copyright © 2015 Honza Dvorsky. All rights reserved. // import Foundation import XcodeServerSDK import BuildaUtils public class XcodeDeviceParser { public enum DeviceType: String { case iPhoneOS = "iphoneos" case macOSX = "macosx" case watchOS = "watchos" public func toPlatformType() -> DevicePlatform.PlatformType { switch self { case .iPhoneOS: return .iOS case .macOSX: return .OSX case .watchOS: return .watchOS } } } public class func parseDeviceTypeFromProjectUrlAndScheme(projectUrl: NSURL, scheme: String) throws -> DeviceType { let typeString = try self.parseTargetTypeFromSchemeAndProjectAtUrl(scheme, projectFolderUrl: projectUrl) guard let deviceType = DeviceType(rawValue: typeString) else { throw Error.withInfo("Unrecognized type: \(typeString)") } return deviceType } private class func parseTargetTypeFromSchemeAndProjectAtUrl(schemeName: String, projectFolderUrl: NSURL) throws -> String { let folder = projectFolderUrl.URLByDeletingLastPathComponent?.path ?? "~" let script = "cd \"\(folder)\"; xcodebuild -scheme \"\(schemeName)\" -showBuildSettings 2>/dev/null | egrep '^\\s*PLATFORM_NAME' | cut -d = -f 2 | uniq | xargs echo" let res = Script.runTemporaryScript(script) if res.terminationStatus == 0 { let deviceType = res.standardOutput.stripTrailingNewline() return deviceType } throw Error.withInfo("Termination status: \(res.terminationStatus), output: \(res.standardOutput), error: \(res.standardError)") } }
// Generated using Sourcery 0.9.0 — https://github.com/krzysztofzablocki/Sourcery // DO NOT EDIT import UIKit public func lineSpacing<Object: NSMutableParagraphStyle>() -> Lens<Object, CGFloat> { return Lens( get: { $0.lineSpacing }, setter: { $0.lineSpacing = $1 } ) } public func paragraphSpacing<Object: NSMutableParagraphStyle>() -> Lens<Object, CGFloat> { return Lens( get: { $0.paragraphSpacing }, setter: { $0.paragraphSpacing = $1 } ) } public func alignment<Object: NSMutableParagraphStyle>() -> Lens<Object, NSTextAlignment> { return Lens( get: { $0.alignment }, setter: { $0.alignment = $1 } ) } public func firstLineHeadIndent<Object: NSMutableParagraphStyle>() -> Lens<Object, CGFloat> { return Lens( get: { $0.firstLineHeadIndent }, setter: { $0.firstLineHeadIndent = $1 } ) } public func headIndent<Object: NSMutableParagraphStyle>() -> Lens<Object, CGFloat> { return Lens( get: { $0.headIndent }, setter: { $0.headIndent = $1 } ) } public func tailIndent<Object: NSMutableParagraphStyle>() -> Lens<Object, CGFloat> { return Lens( get: { $0.tailIndent }, setter: { $0.tailIndent = $1 } ) } public func lineBreakMode<Object: NSMutableParagraphStyle>() -> Lens<Object, NSLineBreakMode> { return Lens( get: { $0.lineBreakMode }, setter: { $0.lineBreakMode = $1 } ) } public func minimumLineHeight<Object: NSMutableParagraphStyle>() -> Lens<Object, CGFloat> { return Lens( get: { $0.minimumLineHeight }, setter: { $0.minimumLineHeight = $1 } ) } public func maximumLineHeight<Object: NSMutableParagraphStyle>() -> Lens<Object, CGFloat> { return Lens( get: { $0.maximumLineHeight }, setter: { $0.maximumLineHeight = $1 } ) } public func baseWritingDirection<Object: NSMutableParagraphStyle>() -> Lens<Object, NSWritingDirection> { return Lens( get: { $0.baseWritingDirection }, setter: { $0.baseWritingDirection = $1 } ) } public func lineHeightMultiple<Object: NSMutableParagraphStyle>() -> Lens<Object, CGFloat> { return Lens( get: { $0.lineHeightMultiple }, setter: { $0.lineHeightMultiple = $1 } ) } public func paragraphSpacingBefore<Object: NSMutableParagraphStyle>() -> Lens<Object, CGFloat> { return Lens( get: { $0.paragraphSpacingBefore }, setter: { $0.paragraphSpacingBefore = $1 } ) } public func hyphenationFactor<Object: NSMutableParagraphStyle>() -> Lens<Object, Float> { return Lens( get: { $0.hyphenationFactor }, setter: { $0.hyphenationFactor = $1 } ) } public func defaultTabInterval<Object: NSMutableParagraphStyle>() -> Lens<Object, CGFloat> { return Lens( get: { $0.defaultTabInterval }, setter: { $0.defaultTabInterval = $1 } ) } public func allowsDefaultTighteningForTruncation<Object: NSMutableParagraphStyle>() -> Lens<Object, Bool> { return Lens( get: { $0.allowsDefaultTighteningForTruncation }, setter: { $0.allowsDefaultTighteningForTruncation = $1 } ) }
// // FollowsTableViewCell.swift // oneone // // Created by levi.luo on 2017/10/12. // Copyright © 2017年 levi.luo. All rights reserved. // import UIKit import SwiftyJSON class FollowsTableViewCell: UITableViewCell,UICollectionViewDelegate,UICollectionViewDataSource { var worksData:JSON = [] var type = "image" func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return worksData.count; } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) let data = worksData[indexPath.row] if type == "image"{ let img = UIImageView.init(frame:CGRect(x:0,y:0,width:60,height:60)) img.contentMode = .scaleAspectFill let url = "/img?from=speciality&name=\(data["workName"].string ?? "")&width=400" asyncCache.asyncLoadImg(name: url,isCache: true) { (result) in DispatchQueue.main.async { img.image = result } } cell.contentView.addSubview(img) }else if type == "video"{ if let url = URL(string:NetService.indexPath + "/videos?from=video&name=\(data["workName"].string ?? "")"){ let vc = SHAVPlayerController(frame:CGRect(x:0,y:0,width:60,height:60),url:url) cell.contentView.addSubview(vc) } } // cell.contentView.backgroundColor = UIColor.red return cell; } @IBOutlet weak var head: UIImageView! @IBOutlet weak var brief: UILabel! @IBOutlet weak var nickname: UILabel! @IBOutlet weak var focusBtn: UIButton! @IBOutlet weak var works: UICollectionView! @IBOutlet weak var time: UILabel! @IBOutlet weak var focusoutBtn: UIButton! override func awakeFromNib() { super.awakeFromNib() if (works != nil){ works.dataSource = self; works.delegate = self; } // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
// // TodoListCheckCell.swift // ToDoListApp // // Created by desmond on 10/28/14. // Copyright (c) 2014 Phoenix. All rights reserved. // import UIKit class TodoListCheckCell: TodoListBaseCell { override func configure() { super.configure() selectionStyle = .Default accessoryType = .None } override func update() { super.update() textLabel?.text = rowDescriptor.title if rowDescriptor.value == nil { rowDescriptor.value = false } accessoryType = (rowDescriptor.value as Bool) ? .Checkmark : .None } override class func todoListViewController(todoListViewController: TodoListTableViewController, didSelectRow selectedRow: TodoListBaseCell) { if let row = selectedRow as? TodoListCheckCell { row.check() } } private func check() { if rowDescriptor.value != nil { rowDescriptor.value = !(rowDescriptor.value as Bool) } else { rowDescriptor.value = true } accessoryType = (rowDescriptor.value as Bool) ? .Checkmark : .None } }
// // String+Ext.swift // JSONMapping // // Created by BraveShine on 2020/12/29. // import Foundation import JavaScriptCore class JSHelpers { public static func readScript(_ scriptName: String) -> String { if let filepath = Bundle.main.path(forResource: scriptName, ofType: "js") { do { let contents = try String(contentsOfFile: filepath) return contents } catch { // log.error("\(scriptName) could not be loaded") } } else { // log.error("\(scriptName) not found") } return "" } public static func readJSONFormatter() -> String { return readScript("JSONFormatterHelper") } public static func readPrettyDiff() -> String { return readScript("prettydiff.browser.min") } } public class JSONParseError { var error: Int var offset: Int var length: Int enum ParseErrorCode: Int { case InvalidSymbol = 1 case InvalidNumberFormat = 2 case PropertyNameExpected = 3 case ValueExpected = 4 case ColonExpected = 5 case CommaExpected = 6 case CloseBraceExpected = 7 case CloseBracketExpected = 8 case EndOfFileExpected = 9 case InvalidCommentToken = 10 case UnexpectedEndOfComment = 11 case UnexpectedEndOfString = 12 case UnexpectedEndOfNumber = 13 case InvalidUnicode = 14 case InvalidEscapeCharacter = 15 case InvalidCharacter = 16 } init(object: NSObject) { self.error = object.value(forKey: "error") as? Int ?? 0 self.offset = object.value(forKey: "offset") as? Int ?? 0 self.length = object.value(forKey: "length") as? Int ?? 0 } func toString() -> String { switch self.error { case ParseErrorCode.InvalidSymbol.rawValue: return "Invalid symbol at offset: \(self.offset)" case ParseErrorCode.InvalidNumberFormat.rawValue: return "Invalid number format at offset: \(self.offset)" case ParseErrorCode.PropertyNameExpected.rawValue: return "Property name expected at offset: \(self.offset)" case ParseErrorCode.ValueExpected.rawValue: return "Value expected at offset: \(self.offset)" case ParseErrorCode.ColonExpected.rawValue: return "Colon expected at offset: \(self.offset)" case ParseErrorCode.CommaExpected.rawValue: return "Comma expected at offset: \(self.offset)" case ParseErrorCode.CloseBraceExpected.rawValue: return "Close brace expected at offset: \(self.offset)" case ParseErrorCode.CloseBracketExpected.rawValue: return "Close bracket expected at offset: \(self.offset)" case ParseErrorCode.EndOfFileExpected.rawValue: return "End of file expected at offset: \(self.offset)" case ParseErrorCode.InvalidCommentToken.rawValue: return "Invalid comment token at offset: \(self.offset)" case ParseErrorCode.UnexpectedEndOfComment.rawValue: return "Unexpected end of comment at offset: \(self.offset)" case ParseErrorCode.UnexpectedEndOfString.rawValue: return "Unexpected end of string at offset: \(self.offset)" case ParseErrorCode.UnexpectedEndOfNumber.rawValue: return "Unexpected end of number at offset: \(self.offset)" case ParseErrorCode.InvalidUnicode.rawValue: return "Invalid unicode at offset: \(self.offset)" case ParseErrorCode.InvalidEscapeCharacter.rawValue: return "Invalid escape character at offset: \(self.offset)" case ParseErrorCode.InvalidCharacter.rawValue: return "Invalid character at offset: \(self.offset)" default: return "Unknown parse error" } } } extension String { func encodeUrl() -> String? { return self.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlUserAllowed) } func decodeUrl() -> String? { return self.removingPercentEncoding?.replacingOccurrences(of: "+", with: " ") } /** Returns a new string made from the receiver by replacing characters which are reserved in a URI query with percent encoded characters. The following characters are not considered reserved in a URI query by RFC 3986: - Alpha "a...z" "A...Z" - Numberic "0...9" - Unreserved "-._~" In addition the reserved characters "/" and "?" have no reserved purpose in the query component of a URI so do not need to be percent escaped. - Returns: The encoded string, or nil if the transformation is not possible. */ public func stringByAddingPercentEncodingForRFC3986() -> String? { let unreserved = "-._~/?" let allowedCharacterSet = NSMutableCharacterSet.alphanumeric() allowedCharacterSet.addCharacters(in: unreserved) return addingPercentEncoding(withAllowedCharacters: allowedCharacterSet as CharacterSet) } /** Returns a new string made from the receiver by replacing characters which are reserved in HTML forms (media type application/x-www-form-urlencoded) with percent encoded characters. The W3C HTML5 specification, section 4.10.22.5 URL-encoded form data percent encodes all characters except the following: - Space (0x20) is replaced by a "+" (0x2B) - Bytes in the range 0x2A, 0x2D, 0x2E, 0x30-0x39, 0x41-0x5A, 0x5F, 0x61-0x7A (alphanumeric + "*-._") - Parameter plusForSpace: Boolean, when true replaces space with a '+' otherwise uses percent encoding (%20). Default is false. - Returns: The encoded string, or nil if the transformation is not possible. */ public func stringByAddingPercentEncodingForFormData(plusForSpace: Bool=false) -> String? { let unreserved = "*-._" let allowedCharacterSet = NSMutableCharacterSet.alphanumeric() allowedCharacterSet.addCharacters(in: unreserved) if plusForSpace { allowedCharacterSet.addCharacters(in: " ") } var encoded = addingPercentEncoding(withAllowedCharacters: allowedCharacterSet as CharacterSet) if plusForSpace { encoded = encoded?.replacingOccurrences(of: " ", with: "+") } return encoded } public func pretifyJSON(format: Any? = nil) -> String? { let context = JSContext()! context.setObject(format, forKeyedSubscript: "format" as NSString) context.setObject(self, forKeyedSubscript: "json" as NSString) let result = context.evaluateScript("JSON.stringify(JSON.parse(json), null, format)") return result?.toString() } // TODO: move this to JSONTextView public func pretifyJSONv2(format: Int? = nil, spaces: Bool = true, allowWeakJSON: Bool = false, errors: inout [JSONParseError]) -> String? { let context = JSContext()! context.setObject(format, forKeyedSubscript: "tabSize" as NSString) context.setObject(spaces, forKeyedSubscript: "useSpace" as NSString) context.setObject(self, forKeyedSubscript: "input" as NSString) context.setObject(allowWeakJSON, forKeyedSubscript: "allowWeakJSON" as NSString) context.evaluateScript(JSHelpers.readJSONFormatter()) var result: JSValue? if format == nil && spaces { result = context.evaluateScript( """ var result = input; try { result = JSON.stringify(JSON.parse(input)); } catch { /* It's ok to skip error here, we parse error later. */ } result; """ ) } else { // Return best effort formatted JSON result = context.evaluateScript( """ var result = applyEditOperations( input, jsonFormatter.format( input, undefined, { insertSpaces: useSpace, tabSize: tabSize || 2 } ) ); result; """ ) } // Get syntax errors if let errs = context.evaluateScript(""" var errors = []; json.parse( result, errors, { allowTrailingComma: allowWeakJSON, disallowComments: !allowWeakJSON } ); errors; """) { if let objArray = errs.toArray() as? [NSObject] { (objArray.map({ (obj) -> JSONParseError in return JSONParseError.init(object: obj) })).forEach { (e) in errors.append(e) } } } return result?.toString() } var unescaped: String { let entities = ["\0", "\t", "\n", "\r", "\"", "\'"] let parts = self.components(separatedBy: "\\".debugDescription.dropFirst().dropLast()).map { (part) -> String in var current = part for entity in entities { let descriptionCharacters = entity.debugDescription.dropFirst().dropLast() let description = String(descriptionCharacters) current = current.replacingOccurrences(of: description, with: entity) } return current } return parts.joined(separator: "\\") } func fromBase64(_ encoding: String.Encoding = .utf8) -> String? { // The ==== part is to make the decoding process easier by providing fake padding // Remove all newlines and spaces let string = "\(self)====".replacingOccurrences(of: "\\s*", with: "", options: .regularExpression) guard let data = Data(base64Encoded: string) else { return nil } return String(data: data, encoding: encoding) } func toBase64(_ encoding: String.Encoding = .utf8) -> String? { return self.data(using: encoding)?.base64EncodedString() } init?(htmlEncodedString: String) { guard let data = htmlEncodedString.data(using: .utf8) else { return nil } let options: [NSAttributedString.DocumentReadingOptionKey: Any] = [ .documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue ] guard let attributedString = try? NSAttributedString(data: data, options: options, documentAttributes: nil) else { return nil } self.init(attributedString.string) } var isInt: Bool { return Int(self) != nil } var fullRange: NSRange { return NSRange(self.startIndex ..< self.endIndex, in: self) } } extension String{ func format() -> String{ var errors: [JSONParseError] = [] if let s = self.pretifyJSONv2(format: 2, spaces: true, allowWeakJSON: true, errors: &errors){ return s } return self } }
// // DayTwentyFourTests.swift // AdventOfCode2017 // // Created by Shawn Veader on 1/7/18. // Copyright © 2018 v8logic. All rights reserved. // import Foundation extension DayTwentyFour: Testable { func runTests() { let input = """ 0/2 2/2 2/3 3/4 3/5 0/1 10/1 9/10 """ guard testValue(31, equals: partOne(input: input)) else { print("Part 1 Tests Failed!") return } // guard // testValue(0, equals: partTwo(input: input)) // else { // print("Part 2 Tests Failed!") // return // } print("Done with tests... all pass") } }
// // MapViewController.swift // To Do // // Created by alper on 5/22/17. // Copyright © 2017 alper. All rights reserved. // import UIKit import MapKit import CoreLocation protocol ScreenshotProtocol { func screenshotImage(image: UIImage) } enum mapViewMode: UInt { case callingFromListItemViewController case callingFromAddNewItemViewController } class MapViewController: UIViewController, UISearchBarDelegate, CLLocationManagerDelegate { let database = FirebaseDataAdapter() var delegate: ScreenshotProtocol? var searchController:UISearchController! var annotation:MKAnnotation! var localSearchRequest:MKLocalSearchRequest! var localSearch:MKLocalSearch! var localSearchResponse:MKLocalSearchResponse! var error:NSError! var pointAnnotation:MKPointAnnotation! var pinAnnotationView:MKPinAnnotationView! var locationManager = CLLocationManager() @IBOutlet weak var mapView: MKMapView! override func viewDidLoad() { super.viewDidLoad() locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.requestWhenInUseAuthorization() locationManager.startUpdatingLocation() self.mapView.showsUserLocation = true } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(true) } @IBAction func searchPressed(_ sender: UIBarButtonItem) { searchController = UISearchController(searchResultsController: nil) searchController.hidesNavigationBarDuringPresentation = false self.searchController.searchBar.delegate = self present(searchController, animated: true, completion: nil) searchController = UISearchController(searchResultsController: nil) searchController.hidesNavigationBarDuringPresentation = false self.searchController.searchBar.delegate = self present(searchController, animated: true, completion: nil) } func searchBarSearchButtonClicked(_ searchBar: UISearchBar){ searchBar.resignFirstResponder() dismiss(animated: true, completion: nil) if self.mapView.annotations.count != 0 { annotation = self.mapView.annotations[0] self.mapView.removeAnnotation(annotation) } localSearchRequest = MKLocalSearchRequest() localSearchRequest.naturalLanguageQuery = searchBar.text localSearch = MKLocalSearch(request: localSearchRequest) localSearch.start { (localSearchResponse, error) -> Void in if localSearchResponse == nil{ let alertController = UIAlertController(title: nil, message: "Place Not Found", preferredStyle: UIAlertControllerStyle.alert) alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.default, handler: nil)) self.present(alertController, animated: true, completion: nil) return } let location = CLLocationCoordinate2DMake(localSearchResponse!.boundingRegion.center.latitude, localSearchResponse!.boundingRegion.center.longitude) // Lattitude - Longitude let span = MKCoordinateSpanMake(0.01, 0.01) let region = MKCoordinateRegionMake(location, span) self.mapView.setRegion(region, animated: true) let annotation = MKPointAnnotation() annotation.coordinate = location annotation.title = searchBar.text // annotation.subtitle = "" self.mapView.addAnnotation(annotation) self.mapView.showsUserLocation = false self.locationManager.stopUpdatingLocation() } } // MARK: CLLocation delegate func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let location = locations[0] let latitude = location.coordinate.latitude let longitude = location.coordinate.longitude let span: MKCoordinateSpan = MKCoordinateSpanMake(0.01, 0.01) let myLocation = CLLocationCoordinate2D(latitude: latitude, longitude: longitude) let region = MKCoordinateRegionMake(myLocation, span) self.mapView.setRegion(region, animated: true) } //MARK: screenshot func screenShotMethod() { let layer = UIApplication.shared.keyWindow!.layer let scale = UIScreen.main.scale UIGraphicsBeginImageContextWithOptions(layer.frame.size, false, scale); layer.render(in: UIGraphicsGetCurrentContext()!) guard let screenshot = UIGraphicsGetImageFromCurrentImageContext() else { return } UIGraphicsEndImageContext() //pass the image via protocol to addViewController delegate?.screenshotImage(image: screenshot) } override func viewWillDisappear(_ animated: Bool) { print("view will disappear") self.screenShotMethod() super.viewWillDisappear(true) } }
// // CookDetailVC.swift // Cookbook // // Created by wanglei on 2017/10/18. // Copyright © 2017年 wanglei. All rights reserved. // import Foundation import Cocoa class CookDetailVC: NSViewController { @IBOutlet var splitView: NSSplitView! @IBOutlet var leftView: NSView! @IBOutlet var rightView: NSView! @IBOutlet var maskBox: NSBox! @IBOutlet var infoLabel: NSTextField! lazy var leftVC: CookDetailLeftVC? = { let vc = CookDetailLeftVC.init(nibName: NSNib.Name("CookDetailLeftVC"), bundle: nil) return vc }() lazy var rightVC: CookDetailRightVC? = { let vc = CookDetailRightVC.init(nibName: NSNib.Name("CookDetailRightVC"), bundle: nil) return vc }() var cookbookDetailResultModel: CookbookDtailResultModel? { didSet{ if cookbookDetailResultModel?.result?.result?.num != nil { if Int((cookbookDetailResultModel?.result?.result?.num)!)! > 0 { maskBox.isHidden = true leftVC?.cookbookDtailSecondeResult = cookbookDetailResultModel?.result?.result }else{ maskBox.isHidden = false infoLabel.stringValue = "暂无菜谱信息." infoLabel.font = NSFont.systemFont(ofSize: 20, weight: .ultraLight) } }else{ maskBox.isHidden = false infoLabel.stringValue = "暂无菜谱信息." infoLabel.font = NSFont.systemFont(ofSize: 20, weight: .ultraLight) } } } override func viewDidLoad() { super.viewDidLoad() // Do view setup here. infoLabel.stringValue = "欢迎使用cookbook!" infoLabel.font = NSFont.systemFont(ofSize: 30, weight: .ultraLight) NotificationCenter.default.addObserver(self, selector: #selector(showMaskBox), name: NSNotification.Name(rawValue: "CookDetailVC_showMaskBox"), object: nil) self.leftView.snp.makeConstraints { (make) in make.width.equalTo(150) } rightView.addSubview((self.rightVC?.view)!) leftView.addSubview((self.leftVC?.view)!) leftVC?.view.snp.makeConstraints({ (make) in make.top.left.bottom.right.equalTo(0) }) rightVC?.view.snp.makeConstraints({ (make) in make.top.left.bottom.right.equalTo(0) }) } @objc func showMaskBox() { infoLabel.stringValue = "正在加载..." infoLabel.font = NSFont.systemFont(ofSize: 20, weight: .ultraLight) maskBox.isHidden = false } deinit { NotificationCenter.default.removeObserver(self) } }
import UIKit import MarketKit class DepositViewModel { private let service: DepositService private let depositViewItemHelper: DepositAddressViewHelper init(service: DepositService, depositViewItemHelper: DepositAddressViewHelper) { self.service = service self.depositViewItemHelper = depositViewItemHelper } } extension DepositViewModel { var coin: Coin { service.coin } var placeholderImageName: String { service.token.placeholderImageName } var address: String { service.address } var watchAccount: Bool { service.watchAccount } var testNet: Bool { depositViewItemHelper.testNet } var additionalInfo: DepositAddressViewHelper.AdditionalInfo { depositViewItemHelper.additionalInfo } } extension DepositAddressViewHelper.AdditionalInfo { var customColor: UIColor? { switch self { case .none, .plain: return nil case .warning: return .themeJacob } } }
// // AddPortRespDTO.swift // VitelityClient // // Created by Jorge Enrique Dominguez on 10/20/18. // Copyright © 2018 sigmatric. All rights reserved. // import Foundation public struct AddPortResponseDTO { public let portid: String public let signatureRequired : Bool public let billRequired : Bool }
// // CharacterDetailsViewController.swift // MarvelCharacters // // Created by Alexander Gurzhiev on 08.04.2021. // import UIKit final class CharacterDetailsViewController: MarvelViewController { private let presenter: CharacterDetailsPresenter private lazy var tableView: UITableView = { let tableView = UITableView() tableView.backgroundColor = .clear tableView.tableHeaderView = headerView tableView.tableFooterView = UIView() tableView.contentInsetAdjustmentBehavior = .never tableView.translatesAutoresizingMaskIntoConstraints = false tableView.dataSource = self return tableView }() private lazy var headerView: UIView = { let headerSize = CGSize(width: view.bounds.width, height: Constants.headerHeight) let headerView = UIImageView(frame: .init(origin: .zero, size: headerSize)) headerView.contentMode = .scaleAspectFill headerView.clipsToBounds = true headerView.setImage(by: presenter.model.avatar) return headerView }() enum Constants { static let headerHeight: CGFloat = 360 } init(router: Router, model: CharacterDetailsViewModel) { presenter = CharacterDetailsPresenter(model: model) super.init(router: router) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupUI() { view.backgroundColor = .white view.addSubview(tableView) NSLayoutConstraint.activate([ tableView.topAnchor.constraint(equalTo: view.topAnchor), tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor), tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor), tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor) ]) } private func setupNavBar() { let titleView = UILabel() titleView.font = UIFont.systemFont(ofSize: 24, weight: .heavy) titleView.backgroundColor = UIColor.marvelRed titleView.textColor = .white titleView.text = presenter.model.name navigationItem.titleView = titleView } override func viewDidLoad() { super.viewDidLoad() setupUI() setupNavBar() } override func viewSafeAreaInsetsDidChange() { super.viewSafeAreaInsetsDidChange() tableView.contentInset = view.safeAreaInsets tableView.contentInset.top = 0 } } // MARK: - UITableViewDataSource extension CharacterDetailsViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { presenter.sectionsCount } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { presenter.rowsCount(for: section) } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { presenter.sectionTitle(for: section) } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell() cell.textLabel?.numberOfLines = 0 cell.textLabel?.text = presenter.rowText(for: indexPath) cell.selectionStyle = .none return cell } }
// // ChangeManager.swift // Essentials // // Created by Ziggy Moens on 21/12/2020. // import Foundation struct ChangeManager : Codable{ public let id: Int public let firstName: String public let lastName: String public let email: String public let createdChangeInitiatives: [ChangeInitiative]? public enum CodingKeys: String, CodingKey{ case id = "id" case firstName = "firstName" case lastName = "lastName" case email = "email" case createdChangeInitiatives = "createdChangeInitiatives" } }
// // RoleCell.swift // QueroRoleSP // // Created by Giovanna Bertho on 10/11/18. // Copyright © 2018 querorole. All rights reserved. // import UIKit let google = "comgooglemaps://?daddr=" let waze = "waze://?q=" let maps = "http://maps.apple.com/?daddr=" class RoleCell: UITableViewCell { @IBOutlet weak var photoView: UIImageView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var dateLabel: UILabel! // @IBOutlet weak var typeLabel: UILabel! @IBOutlet weak var companionView: UIImageView! @IBOutlet weak var companionLabel: UILabel! var r: Role! var controller: UIViewController! var role: Role! { willSet(r) { self.photoView.image = r.place.photo self.nameLabel.text = r.place.name // self.typeLabel.text = r.place.type self.companionView.image = r.companion.photo self.companionLabel.text = r.companion.nick + " - " + r.companion.name let formatter = DateFormatter() formatter.dateFormat = "dd/MM/yyyy" self.dateLabel.text = formatter.string(from: r.date) + " " + r.place.address self.r = r } } override func awakeFromNib() { super.awakeFromNib() self.companionView.layer.cornerRadius = self.companionView.frame.height/2 } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } func goTo() { let controller = UIAlertController(title: "Navegação", message: "Escolha seu aplicativo preferido para navegar até este local", preferredStyle: .alert) if UIApplication.shared.canOpenURL(URL(string: "comgooglemaps://")!) { let goGoogle = UIAlertAction(title: "Google Maps", style: .default) { (action) in let url = google + self.r.place.address.replacingOccurrences(of: " ", with: "%20").replacingOccurrences(of: ",", with: "%20").replacingOccurrences(of: "-", with: "") UIApplication.shared.open(URL(string: url)!, options: [:], completionHandler: nil) } controller.addAction(goGoogle) } if UIApplication.shared.canOpenURL(URL(string: "waze://")!) { let goWaze = UIAlertAction(title: "Google Maps", style: .default) { (action) in let url = waze + self.r.place.address.replacingOccurrences(of: " ", with: "%20").replacingOccurrences(of: ",", with: "%20").replacingOccurrences(of: "-", with: "") UIApplication.shared.open(URL(string: url)!, options: [:], completionHandler: nil) } controller.addAction(goWaze) } if UIApplication.shared.canOpenURL(URL(string: "http://maps.apple.com/")!) { let goMaps = UIAlertAction(title: "Google Maps", style: .default) { (action) in let url = maps + self.r.place.address.replacingOccurrences(of: " ", with: "%20").replacingOccurrences(of: ",", with: "%20").replacingOccurrences(of: "-", with: "") UIApplication.shared.open(URL(string: url)!, options: [:], completionHandler: nil) } controller.addAction(goMaps) } let nope = UIAlertAction(title: "Cancelar", style: .cancel, handler: nil) controller.addAction(nope) self.controller.present(controller, animated: true, completion: nil) } }
// // MockHTTPServer.swift // Punos // // Created by Ali Rantakari on 9.2.16. // Copyright © 2016 Ali Rantakari. All rights reserved. // import Foundation public typealias MockResponseMatcher = (request: HTTPRequest) -> Bool /// Data for a mocked HTTP server response. /// public struct MockResponse { /// The HTTP status code public let statusCode: Int /// The body data public let data: NSData? /// The HTTP headers public let headers: [String:String]? public init(statusCode: Int, data: NSData?, headers: [String:String]?) { self.statusCode = statusCode self.data = data self.headers = headers } /// Returns a copy of self by replacing members with the supplied /// values. /// public func copyWithChanges(statusCode statusCode: Int? = nil, data: NSData? = nil, headers: [String:String]? = nil) -> MockResponse { return MockResponse( statusCode: statusCode ?? self.statusCode, data: data ?? self.data, headers: headers ?? self.headers ) } } private struct MockResponseConfiguration { let response: MockResponse let matcher: MockResponseMatcher? let onlyOnce: Bool let delay: NSTimeInterval } private func printMessageToLog(message: String) { print("Punos: \(message)") } /// A web server that runs on `localhost` and can be told how to respond /// to incoming requests. Meant for automated tests. /// public class MockHTTPServer { private let server: PunosHTTPServer private let log: Logger /// Create a new MockHTTPServer. /// /// - parameter loggingEnabled: Whether to print status messages to stdout. /// public init(loggingEnabled: Bool = false) { log = loggingEnabled ? printMessageToLog : { _ in } server = PunosHTTPServer( queue: dispatch_queue_create("org.hasseg.Punos.server", DISPATCH_QUEUE_CONCURRENT), logger: log ) server.responder = respondToRequest } // ------------------------------------ // MARK: Starting and stopping /// Start the server on the given `port` (`8080` by default.) /// /// - throws: `NSError` if the server could not be started. /// public func start(port: in_port_t = 8080) throws { do { try server.start(port) self.port = port isRunning = true log("\(self.dynamicType) started at port \(port)") } catch let error { throw punosError(Int(port), "The mock server failed to start on port \(port). Error: \(error)") } } /// Stop the server. /// public func stop() { server.stop() port = 0 isRunning = false log("\(self.dynamicType) stopped.") } /// Whether the server is currently running. /// public private(set) var isRunning: Bool = false /// The port the server is running on, or 0 if the server /// is not running. /// public private(set) var port: in_port_t = 0 /// The “base URL” (protocol, hostname, port) for the /// running server, or `nil` if the server is not running. /// public var baseURLString: String? { if !isRunning { return nil } return "http://localhost:\(port)" } // ------------------------------------ // MARK: Responding private func mockResponseConfigForRequest(request: HTTPRequest) -> MockResponseConfiguration? { for i in mockResponsesWithMatchers.indices { let responseConfig = mockResponsesWithMatchers[i] guard let matcher = responseConfig.matcher else { continue } if matcher(request: request) { if responseConfig.onlyOnce { mockResponsesWithMatchers.removeAtIndex(i) } return responseConfig } } for i in defaultMockResponses.indices { let responseConfig = defaultMockResponses[i] if responseConfig.onlyOnce { defaultMockResponses.removeAtIndex(i) } return responseConfig } return nil } private let defaultMockResponseConfiguration = MockResponseConfiguration( response: MockResponse(statusCode: 200, data: nil, headers: nil), matcher: nil, onlyOnce: false, delay: 0) private let responseLock = NSLock() private func respondToRequest(request: HttpRequest, _ callback: (HttpResponse) -> Void) { let mockConfig: MockResponseConfiguration = lock(responseLock) { let publicRequest = HTTPRequest(request) self.latestRequests.append(publicRequest) return self.mockResponseConfigForRequest(publicRequest) ?? self.defaultMockResponseConfiguration } let mockData = commonResponseModifier(mockConfig.response) let statusCode = mockData.statusCode let content: HttpResponseContent? = { if let bodyData = mockData.data { return (length: bodyData.length, write: { responseBodyWriter in let bytes = Array(UnsafeBufferPointer(start: UnsafePointer<UInt8>(bodyData.bytes), count: bodyData.length)) responseBodyWriter.write(bytes) }) } return nil }() let response = HttpResponse( statusCode, RFC2616.reasonsForStatusCodes[statusCode] ?? "", mockData.headers, content) if 0 < mockConfig.delay { dispatchAfterInterval(mockConfig.delay, queue: server.queue) { callback(response) } } else { callback(response) } } /// The latest HTTP requests this server has received, in order of receipt. /// public var latestRequests = [HTTPRequest]() /// The `.endpoint` values for `latestRequests`. /// public var latestRequestEndpoints: [String] { return latestRequests.map { $0.endpoint } } /// The most recent HTTP request this server has received, or `nil` if none. /// public var lastRequest: HTTPRequest? { return latestRequests.last } /// Clear the `latestRequests` list (and `lastRequest`.) /// public func clearLatestRequests() { latestRequests.removeAll() } // ------------------------------------ // MARK: Response mocking private var defaultMockResponses: [MockResponseConfiguration] = [] private var mockResponsesWithMatchers: [MockResponseConfiguration] = [] private func matcherForEndpoint(endpoint: String?) -> MockResponseMatcher? { guard let endpoint = endpoint else { return nil } let parts = endpoint.componentsSeparatedByString(" ") let method = parts.first let path: String? = 1 < parts.count ? parts[1] : nil return { request in return request.method == method && (path == nil || request.path == path) } } /// A function that modifies each response before it is sent. /// Useful for e.g. setting common headers like `"Server"`. /// By default, the “identity” function (`{ $0 }`). /// public var commonResponseModifier: (MockResponse -> MockResponse) = { $0 } /// Tell the server to send this response to incoming requests. /// /// - If multiple configured responses match an incoming request, the _first_ one added wins. /// - Responses with `endpoint` or `matcher` take precedence over ones without. /// - “Permanent default fallback responses” (i.e. ones with no `endpoint` or `matcher`, and /// `onlyOnce == false`) can be overridden — configuring such a response will override /// previously added ones. /// /// - parameters: /// - endpoint: The “endpoint,” requests to which this response should be sent for, /// in the format `"HTTPVERB path"`, e.g. `"POST /foo/bar"`. The HTTP verb is required /// but the path is optional. If set, this will supersede `matcher`. /// - response: The mock response to send /// - onlyOnce: Whether to only mock this response once — if `true`, this /// mock response will only be sent for the first matching request and not /// thereafter /// - delay: How long to wait (after processing the incoming request) before sending /// the response /// - matcher: An “evaluator” function that determines what requests this response /// should be sent for. If omitted or `nil`, this response will match _all_ /// incoming requests. /// public func mockResponse(endpoint endpoint: String? = nil, response: MockResponse, onlyOnce: Bool = false, delay: NSTimeInterval = 0, matcher: MockResponseMatcher? = nil) { let config = MockResponseConfiguration( response: response, matcher: matcherForEndpoint(endpoint) ?? matcher, onlyOnce: onlyOnce, delay: delay) if config.matcher == nil { // "Permanent" response overrides any previously added permanent response: if !config.onlyOnce, let indexToOverride = defaultMockResponses.indexOf({ !$0.onlyOnce }) { defaultMockResponses[indexToOverride] = config } else { defaultMockResponses.append(config) } } else { mockResponsesWithMatchers.append(config) } } /// Tell the server to send this response to incoming requests. /// /// - If multiple configured responses match an incoming request, the _first_ one added wins. /// - Responses with `endpoint` or `matcher` take precedence over ones without. /// - “Permanent default fallback responses” (i.e. ones with no `endpoint` or `matcher`, and /// `onlyOnce == false`) can be overridden — configuring such a response will override /// previously added ones. /// /// - parameters: /// - endpoint: The “endpoint,” requests to which this response should be sent for, /// in the format `"HTTPVERB path"`, e.g. `"POST /foo/bar"`. The HTTP verb is required /// but the path is optional. If set, this will supersede `matcher`. /// - status: The response HTTP status code. Default: 200 /// - data: The response body data. If non-nil, the `"Content-Length"` header will /// be given an appropriate value. /// - headers: The response headers /// - onlyOnce: Whether to only mock this response once — if `true`, this /// mock response will only be sent for the first matching request and not /// thereafter /// - delay: How long to wait (after processing the incoming request) before sending /// the response /// - matcher: An “evaluator” function that determines what requests this response /// should be sent for. If omitted or `nil`, this response will match _all_ /// incoming requests. /// public func mockResponse(endpoint endpoint: String? = nil, status: Int? = nil, data: NSData? = nil, headers: [String:String]? = nil, onlyOnce: Bool = false, delay: NSTimeInterval = 0, matcher: MockResponseMatcher? = nil) { let response = MockResponse( statusCode: status ?? 200, data: data, headers: headers) mockResponse(endpoint: endpoint, response: response, onlyOnce: onlyOnce, delay: delay, matcher: matcher) } /// Tell the server to send this JSON response to incoming requests (sending /// the `Content-Type` header as `"application/json"`.) /// /// - If multiple configured responses match an incoming request, the _first_ one added wins. /// - Responses with `endpoint` or `matcher` take precedence over ones without. /// - “Permanent default fallback responses” (i.e. ones with no `endpoint` or `matcher`, and /// `onlyOnce == false`) can be overridden — configuring such a response will override /// previously added ones. /// /// - parameters: /// - endpoint: The “endpoint,” requests to which this response should be sent for, /// in the format `"HTTPVERB path"`, e.g. `"POST /foo/bar"`. The HTTP verb is required /// but the path is optional. If set, this will supersede `matcher`. /// - json: The UTF-8 encoded JSON to be sent in the response body /// - status: The response HTTP status code. Default: 200 /// - headers: The response headers /// - onlyOnce: Whether to only mock this response once — if `true`, this /// mock response will only be sent for the first matching request and not /// thereafter /// - delay: How long to wait (after processing the incoming request) before sending /// the response /// - matcher: An “evaluator” function that determines what requests this response /// should be sent for. If omitted or `nil`, this response will match _all_ /// incoming requests. /// public func mockJSONResponse(endpoint endpoint: String? = nil, json: String? = nil, status: Int? = nil, headers: [String:String]? = nil, onlyOnce: Bool = false, delay: NSTimeInterval = 0, matcher: MockResponseMatcher? = nil) { mockResponse( status: status, data: json?.dataUsingEncoding(NSUTF8StringEncoding), headers: ["Content-Type": "application/json"].merged(headers), onlyOnce: onlyOnce, delay: delay, endpoint: endpoint, matcher: matcher) } /// Tell the server to send this JSON response to incoming requests (sending /// the `Content-Type` header as `"application/json"`.) /// /// - If multiple configured responses match an incoming request, the _first_ one added wins. /// - Responses with `endpoint` or `matcher` take precedence over ones without. /// - “Permanent default fallback responses” (i.e. ones with no `endpoint` or `matcher`, and /// `onlyOnce == false`) can be overridden — configuring such a response will override /// previously added ones. /// /// - parameters: /// - endpoint: The “endpoint,” requests to which this response should be sent for, /// in the format `"HTTPVERB path"`, e.g. `"POST /foo/bar"`. The HTTP verb is required /// but the path is optional. If set, this will supersede `matcher`. /// - object: The object to be sent in the response body, serialized as JSON. Serialization /// failures will be silent and yield an empty response body. /// - status: The response HTTP status code. Default: 200 /// - headers: The response headers /// - onlyOnce: Whether to only mock this response once — if `true`, this /// mock response will only be sent for the first matching request and not /// thereafter /// - delay: How long to wait (after processing the incoming request) before sending /// the response /// - matcher: An “evaluator” function that determines what requests this response /// should be sent for. If omitted or `nil`, this response will match _all_ /// incoming requests. /// public func mockJSONResponse(endpoint endpoint: String? = nil, object: AnyObject? = nil, status: Int? = nil, headers: [String:String]? = nil, onlyOnce: Bool = false, delay: NSTimeInterval = 0, matcher: MockResponseMatcher? = nil) { let jsonData: NSData? = { guard let o = object else { return nil } return try? NSJSONSerialization.dataWithJSONObject(o, options: NSJSONWritingOptions()) }() mockResponse( status: status, data: jsonData, headers: ["Content-Type": "application/json"].merged(headers), onlyOnce: onlyOnce, delay: delay, endpoint: endpoint, matcher: matcher) } /// Remove all mock responses previously added with `mockResponse()`. /// public func clearMockResponses() { defaultMockResponses.removeAll() mockResponsesWithMatchers.removeAll() } /// Removes all “mocking” state: the mock responses, the /// common response modifier, and the latest request list. /// public func clearAllMockingState() { clearLatestRequests() clearMockResponses() commonResponseModifier = { $0 } } }
// // ProductsAPI.swift // // Generated by swagger-codegen // https://github.com/swagger-api/swagger-codegen // import Alamofire public class ProductsAPI: APIBase { /** - parameter product: (body) Product to add to the store - parameter completion: completion handler to receive the data and the error objects */ public class func addProduct(product product: Product, completion: ((data: InlineResponse2014?, error: ErrorType?) -> Void)) { addProductWithRequestBuilder(product: product).execute { (response, error) -> Void in completion(data: response?.body, error: error); } } /** - POST /products - Creates a new product in the store. - API Key: - type: apiKey APIToken - name: APIKeyHeader - examples: [{contentType=application/json, example={ "data" : [ { "visibility" : [ "facebook", "facebook" ], "is_prefered" : true, "is_new" : false, "is_digital" : true, "url_digital" : "http://example.com", "active" : true, "created_at" : "2016-10-10T13:26:17+00:00", "manual" : "Lorem Ipsum dolus", "i18n" : { "characteristics" : "Characteristics of product", "name" : "name", "description" : "Description of product", "synopsis" : "synopsis", "locale" : "pt_PT", "seo" : { "keywords" : "keywords", "description" : "description", "title" : "title" } }, "url_video" : "http://youtube.com/foobar/qwocqpeibas2www", "expires_at" : "2016-10-10T13:26:17+00:00", "updated_at" : "2016-10-10T13:26:17+00:00", "in_homepage" : true, "id" : 1, "sku" : "a123b" }, { "visibility" : [ "facebook", "facebook" ], "is_prefered" : true, "is_new" : false, "is_digital" : true, "url_digital" : "http://example.com", "active" : true, "created_at" : "2016-10-10T13:26:17+00:00", "manual" : "Lorem Ipsum dolus", "i18n" : { "characteristics" : "Characteristics of product", "name" : "name", "description" : "Description of product", "synopsis" : "synopsis", "locale" : "pt_PT", "seo" : { "keywords" : "keywords", "description" : "description", "title" : "title" } }, "url_video" : "http://youtube.com/foobar/qwocqpeibas2www", "expires_at" : "2016-10-10T13:26:17+00:00", "updated_at" : "2016-10-10T13:26:17+00:00", "in_homepage" : true, "id" : 1, "sku" : "a123b" } ] }}] - parameter product: (body) Product to add to the store - returns: RequestBuilder<InlineResponse2014> */ public class func addProductWithRequestBuilder(product product: Product) -> RequestBuilder<InlineResponse2014> { let path = "/products" let URLString = SwaggerClientAPI.basePath + path let parameters = product.encodeToJSON() as? [String:AnyObject] let convertedParameters = APIHelper.convertBoolToString(parameters) let requestBuilder: RequestBuilder<InlineResponse2014>.Type = SwaggerClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true) } /** - parameter id: (path) ID of product to delete - parameter completion: completion handler to receive the data and the error objects */ public class func deleteProductById(id id: Int64, completion: ((error: ErrorType?) -> Void)) { deleteProductByIdWithRequestBuilder(id: id).execute { (response, error) -> Void in completion(error: error); } } /** - DELETE /products/{id}/ - deletes a single product based on the ID supplied - API Key: - type: apiKey APIToken - name: APIKeyHeader - parameter id: (path) ID of product to delete - returns: RequestBuilder<Void> */ public class func deleteProductByIdWithRequestBuilder(id id: Int64) -> RequestBuilder<Void> { var path = "/products/{id}/" path = path.stringByReplacingOccurrencesOfString("{id}", withString: "\(id)", options: .LiteralSearch, range: nil) let URLString = SwaggerClientAPI.basePath + path let nillableParameters: [String:AnyObject?] = [:] let parameters = APIHelper.rejectNil(nillableParameters) let convertedParameters = APIHelper.convertBoolToString(parameters) let requestBuilder: RequestBuilder<Void>.Type = SwaggerClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: convertedParameters, isBody: true) } /** - parameter id: (path) ID of product to fetch - parameter includes: (query) Include associated objects within response (optional) - parameter limit: (query) max records to return (optional) - parameter completion: completion handler to receive the data and the error objects */ public class func getProductById(id id: Int64, includes: [String]? = nil, limit: Int32? = nil, completion: ((data: InlineResponse2014?, error: ErrorType?) -> Void)) { getProductByIdWithRequestBuilder(id: id, includes: includes, limit: limit).execute { (response, error) -> Void in completion(data: response?.body, error: error); } } /** - GET /products/{id}/ - Returns a product based on a single ID ### Includes You can give the following values on includes parameter: `brands, categories, routes, stocks` - API Key: - type: apiKey APIToken - name: APIKeyHeader - examples: [{contentType=application/json, example={ "data" : [ { "visibility" : [ "facebook", "facebook" ], "is_prefered" : true, "is_new" : false, "is_digital" : true, "url_digital" : "http://example.com", "active" : true, "created_at" : "2016-10-10T13:26:17+00:00", "manual" : "Lorem Ipsum dolus", "i18n" : { "characteristics" : "Characteristics of product", "name" : "name", "description" : "Description of product", "synopsis" : "synopsis", "locale" : "pt_PT", "seo" : { "keywords" : "keywords", "description" : "description", "title" : "title" } }, "url_video" : "http://youtube.com/foobar/qwocqpeibas2www", "expires_at" : "2016-10-10T13:26:17+00:00", "updated_at" : "2016-10-10T13:26:17+00:00", "in_homepage" : true, "id" : 1, "sku" : "a123b" }, { "visibility" : [ "facebook", "facebook" ], "is_prefered" : true, "is_new" : false, "is_digital" : true, "url_digital" : "http://example.com", "active" : true, "created_at" : "2016-10-10T13:26:17+00:00", "manual" : "Lorem Ipsum dolus", "i18n" : { "characteristics" : "Characteristics of product", "name" : "name", "description" : "Description of product", "synopsis" : "synopsis", "locale" : "pt_PT", "seo" : { "keywords" : "keywords", "description" : "description", "title" : "title" } }, "url_video" : "http://youtube.com/foobar/qwocqpeibas2www", "expires_at" : "2016-10-10T13:26:17+00:00", "updated_at" : "2016-10-10T13:26:17+00:00", "in_homepage" : true, "id" : 1, "sku" : "a123b" } ] }}] - parameter id: (path) ID of product to fetch - parameter includes: (query) Include associated objects within response (optional) - parameter limit: (query) max records to return (optional) - returns: RequestBuilder<InlineResponse2014> */ public class func getProductByIdWithRequestBuilder(id id: Int64, includes: [String]? = nil, limit: Int32? = nil) -> RequestBuilder<InlineResponse2014> { var path = "/products/{id}/" path = path.stringByReplacingOccurrencesOfString("{id}", withString: "\(id)", options: .LiteralSearch, range: nil) let URLString = SwaggerClientAPI.basePath + path let nillableParameters: [String:AnyObject?] = [ "includes": includes, "limit": limit?.encodeToJSON() ] let parameters = APIHelper.rejectNil(nillableParameters) let convertedParameters = APIHelper.convertBoolToString(parameters) let requestBuilder: RequestBuilder<InlineResponse2014>.Type = SwaggerClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) } /** - parameter includes: (query) Include associated objects within response (optional) - parameter limit: (query) max records to return (optional) - parameter orderBy: (query) Specify the field to be sorted, examples: - &#x60;?order_by&#x3D;id|desc&#x60; - &#x60;?order_by&#x3D;updated_at|desc,position|asc&#x60; (optional) - parameter completion: completion handler to receive the data and the error objects */ public class func getProducts(includes includes: [String]? = nil, limit: Int32? = nil, orderBy: [String]? = nil, completion: ((data: InlineResponse2006?, error: ErrorType?) -> Void)) { getProductsWithRequestBuilder(includes: includes, limit: limit, orderBy: orderBy).execute { (response, error) -> Void in completion(data: response?.body, error: error); } } /** - GET /products - Returns all products from the system that the user has access to ### Includes You can give the following values on includes parameter: `brands, categories, routes, stocks` - API Key: - type: apiKey APIToken - name: APIKeyHeader - examples: [{contentType=application/json, example={ "data" : [ { "visibility" : [ "facebook", "facebook" ], "is_prefered" : true, "is_new" : false, "is_digital" : true, "url_digital" : "http://example.com", "active" : true, "created_at" : "2016-10-10T13:26:17+00:00", "manual" : "Lorem Ipsum dolus", "i18n" : { "characteristics" : "Characteristics of product", "name" : "name", "description" : "Description of product", "synopsis" : "synopsis", "locale" : "pt_PT", "seo" : { "keywords" : "keywords", "description" : "description", "title" : "title" } }, "url_video" : "http://youtube.com/foobar/qwocqpeibas2www", "expires_at" : "2016-10-10T13:26:17+00:00", "updated_at" : "2016-10-10T13:26:17+00:00", "in_homepage" : true, "id" : 1, "sku" : "a123b" }, { "visibility" : [ "facebook", "facebook" ], "is_prefered" : true, "is_new" : false, "is_digital" : true, "url_digital" : "http://example.com", "active" : true, "created_at" : "2016-10-10T13:26:17+00:00", "manual" : "Lorem Ipsum dolus", "i18n" : { "characteristics" : "Characteristics of product", "name" : "name", "description" : "Description of product", "synopsis" : "synopsis", "locale" : "pt_PT", "seo" : { "keywords" : "keywords", "description" : "description", "title" : "title" } }, "url_video" : "http://youtube.com/foobar/qwocqpeibas2www", "expires_at" : "2016-10-10T13:26:17+00:00", "updated_at" : "2016-10-10T13:26:17+00:00", "in_homepage" : true, "id" : 1, "sku" : "a123b" } ], "meta" : { "total" : "total" } }}] - parameter includes: (query) Include associated objects within response (optional) - parameter limit: (query) max records to return (optional) - parameter orderBy: (query) Specify the field to be sorted, examples: - &#x60;?order_by&#x3D;id|desc&#x60; - &#x60;?order_by&#x3D;updated_at|desc,position|asc&#x60; (optional) - returns: RequestBuilder<InlineResponse2006> */ public class func getProductsWithRequestBuilder(includes includes: [String]? = nil, limit: Int32? = nil, orderBy: [String]? = nil) -> RequestBuilder<InlineResponse2006> { let path = "/products" let URLString = SwaggerClientAPI.basePath + path let nillableParameters: [String:AnyObject?] = [ "includes": includes, "limit": limit?.encodeToJSON(), "order_by": orderBy ] let parameters = APIHelper.rejectNil(nillableParameters) let convertedParameters = APIHelper.convertBoolToString(parameters) let requestBuilder: RequestBuilder<InlineResponse2006>.Type = SwaggerClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) } /** - parameter id: (path) ID of product to update - parameter tax: (body) Product to add to the store - parameter completion: completion handler to receive the data and the error objects */ public class func updateProductById(id id: Int64, tax: Product, completion: ((error: ErrorType?) -> Void)) { updateProductByIdWithRequestBuilder(id: id, tax: tax).execute { (response, error) -> Void in completion(error: error); } } /** - PUT /products/{id}/ - update a single product based on the ID supplied - API Key: - type: apiKey APIToken - name: APIKeyHeader - parameter id: (path) ID of product to update - parameter tax: (body) Product to add to the store - returns: RequestBuilder<Void> */ public class func updateProductByIdWithRequestBuilder(id id: Int64, tax: Product) -> RequestBuilder<Void> { var path = "/products/{id}/" path = path.stringByReplacingOccurrencesOfString("{id}", withString: "\(id)", options: .LiteralSearch, range: nil) let URLString = SwaggerClientAPI.basePath + path let parameters = tax.encodeToJSON() as? [String:AnyObject] let convertedParameters = APIHelper.convertBoolToString(parameters) let requestBuilder: RequestBuilder<Void>.Type = SwaggerClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "PUT", URLString: URLString, parameters: convertedParameters, isBody: true) } /** - parameter id: (path) ID of product to update - parameter tax: (body) Product to add to the store - parameter completion: completion handler to receive the data and the error objects */ public class func updateProductById_0(id id: Int64, tax: Product, completion: ((error: ErrorType?) -> Void)) { updateProductById_0WithRequestBuilder(id: id, tax: tax).execute { (response, error) -> Void in completion(error: error); } } /** - PATCH /products/{id}/ - update a single product based on the ID supplied - API Key: - type: apiKey APIToken - name: APIKeyHeader - parameter id: (path) ID of product to update - parameter tax: (body) Product to add to the store - returns: RequestBuilder<Void> */ public class func updateProductById_0WithRequestBuilder(id id: Int64, tax: Product) -> RequestBuilder<Void> { var path = "/products/{id}/" path = path.stringByReplacingOccurrencesOfString("{id}", withString: "\(id)", options: .LiteralSearch, range: nil) let URLString = SwaggerClientAPI.basePath + path let parameters = tax.encodeToJSON() as? [String:AnyObject] let convertedParameters = APIHelper.convertBoolToString(parameters) let requestBuilder: RequestBuilder<Void>.Type = SwaggerClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "PATCH", URLString: URLString, parameters: convertedParameters, isBody: true) } }
import UIKit let myName = "Pasquale" var myAge = 29 let twitterName: String = "pasql" var colors = ["red", "green", "blue"] colors[1] colors.append("orange") colors.remove(at: 1) colors for color in colors{ print (color) } func pointToRetina(point: Int) -> Int { return point * 2 } pointToRetina(point: 4) struct UserStruct { var name: String var job: String var age: Int } var user = UserStruct(name: "Pasquale", job: "Animator", age: 29) print(user.age, user.job) class UserClass{ var name: String var age: Int var hired: Bool init(name:String, age:Int, hired: Bool){ self.name = name self.age = age self.hired = hired } } //Structs are copies, and Classes are references var answer: String? UILabel().text = answer var answerString: String! UILabel().text = answer ?? "some default" answer = "haha" print(answer ?? "poop")
// // WeatherService.swift // Weather // // Created by Lisandro on 16/08/2020. // import Foundation enum NetworkError: Error { case badUrl case noData case decodingError } class WeatherService { func getWeather(city: String, completion: @escaping (Result<WeatherData?, NetworkError>) -> Void) { guard let url = URL.urlForWeather(city) else { return completion(.failure(.badUrl)) } URLSession.shared.dataTask(with: url) { (data, response, error) in guard let data = data, error == nil else { return completion(.failure(.badUrl)) } let weatherRespone = try? JSONDecoder().decode(WeatherResponse.self, from: data) if let weatherRespone = weatherRespone { completion(.success(weatherRespone.main)) } else { completion(.failure(.decodingError)) } }.resume() } }
// // FlickrImage.swift // comets // // Created by Matt Ariane Clarke on 29/07/2017. // Copyright © 2017 MN MobileDevelopers. All rights reserved. // import Foundation import Alamofire protocol FlickrDelegate: class { func receiveImage(dictionary:Dictionary<String, Any>) func noImageAvailable() func noInternet() } class FlickrImage { weak var delegate:FlickrDelegate? func researchRandonImage(countryToSearch:String) { guard ConnectionManager.sharedInstance.hasConnection() else { delegate?.noInternet() return } let tag = countryToSearch.replacingOccurrences(of: " ", with: "") let flickrConst = flickrConstant() let url = flickrConst.taggedSearch(tag: tag) Alamofire.request(url).responseJSON { response in if(response.result.isSuccess) { if let responseValue = response.result.value as? Dictionary<String, Any> { if let items = responseValue[flickrConstant.flickrItems] as? Array<Any> { if let firstValue = items[items.getTotalRandom()] as? Dictionary<String, Any> { self.delegate?.receiveImage(dictionary:firstValue) } } } } else { self.delegate?.noImageAvailable() } } } } extension Array { func getTotalRandom() -> Int { let total = UInt32(self.count) let random = Int(arc4random_uniform(total)) return random } } struct flickrConstant { public func taggedSearch(tag:String) ->String { return "https://api.flickr.com/services/feeds/photos_public.gne?tags=\(tag)&;tagmode=any&format=json&nojsoncallback=1" } public static let flickrItems = "items" }
// // ProductStats.swift // MyLoqta // // Created by Shivansh Jaitly on 9/10/18. // Copyright © 2018 AppVenturez. All rights reserved. // import UIKit import ObjectMapper class ProductStats: Mappable { var viewCount : Int? var averageView : Double? var likeCount : Int? var averageLike : Double? var viewPercent: Double? var likePercent: Double? var viewedProductsGraph: [GraphView]? var likedProductsGraph: [GraphView]? required init?(map: Map) { } func mapping(map: Map) { viewCount <- map["viewCount"] averageView <- map["averageView"] likeCount <- map["likeCount"] averageLike <- map["averageLike"] viewPercent <- map["viewPercent"] likePercent <- map["likePercent"] viewedProductsGraph <- map["viewedProductsGraph"] likedProductsGraph <- map["likedProductsGraph"] } }
// // NewFeatureTableViewCell.swift // TrocoSimples // // Created by gustavo r meyer on 8/16/17. // Copyright © 2017 gustavo r meyer. All rights reserved. // import UIKit class NewFeatureTableViewCell: UITableViewCell { public static let Identifier = "NewFeatureTableViewCell" @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var descriptionLabel: UILabel! var newFeature:NewFeatures? { didSet{ configureLayout() guard let newFeature = newFeature else { return } nameLabel.text = newFeature.name descriptionLabel.text = newFeature.description descriptionLabel.sizeToFit() } } func configureLayout(){ self.layer.cornerRadius = 6 self.layer.borderColor = UIColor.flatColor.orange.system.cgColor self.layer.borderWidth = 1 } }
import Foundation protocol DayAdventProtocol { func processPart1() func processPart2() }
//: Playground - noun: a place where people can play import UIKit //creating an empty array var someInts = [Int]() print("someInts is of type [Int] with \(someInts.count) items.") someInts.append(42) print("someInts array now contain \(someInts[0]) value") var fourGhosts = Array(repeating: "S", count: 4) var twoCats = Array(repeating: "B", count: 2) var combinedArrays = fourGhosts + twoCats var shoppingList = ["Eggs", "Milk"] if shoppingList.isEmpty { print("Shopping list is empty") } else { print("Shopping list isn't empty") } shoppingList.append("Flour") shoppingList += ["Chocolate", "Beer"] var firstItem = shoppingList[0] shoppingList[2...4] = ["Mango", "Apples"] print(shoppingList) shoppingList[0] = "Six Eggs" print(shoppingList) for item in shoppingList { print(item) } shoppingList.insert("Vodka", at: 2) let drink = shoppingList.remove(at: 2) print(drink) print(shoppingList) let apples = shoppingList.removeLast() for (index, value) in shoppingList.enumerated() { print("Item \(index): \(value)") } /***** Set *****/ var letters = Set<Character>() letters.insert("a") letters.insert("b") print(letters) letters = [] var favoriteGenres: Set<String> = ["Rock", "House", "R&B", "Classical"] var otherGenres: Set<String> = ["Rap", "Drum&Bass"] var unionSet = favoriteGenres.union(otherGenres) if favoriteGenres.contains("Rap") { print("contains Rap") } else { print("Not contains Rap") } for genre in unionSet.sorted() { print(genre) } let houseAnimals: Set = ["🐶", "🐱"] let farmAnimals: Set = ["🐮", "🐔", "🐑", "🐶", "🐱"] let cityAnimals: Set = ["🐦", "🐭"] houseAnimals.isSubset(of: farmAnimals) // true farmAnimals.isSuperset(of: houseAnimals) // true farmAnimals.isDisjoint(with: cityAnimals) // true /***** Dictionaries *****/ var namesOfIntegers = [Int: String]() namesOfIntegers[16] = "sixteen" namesOfIntegers = [:] var airports = ["YYZ": "Toronto Pearson", "DUB": "Dublin", "???": "Uknown Airport"] if let oldValue = airports.updateValue("Dublin Airport", forKey: "DUB") { print("The old value for DUB was \(oldValue).") } if let removedValue = airports.removeValue(forKey: "DUB") { print("The removed airport's name is \(removedValue).") } else { print("The airports dictionary does not contain a value for DUB.") } for (airportCode, airport) in airports { print("\(airportCode): \(airport)") } let airportCodes = [String](airports.keys) let airportNames = [String](airports.values) for items in airports.sorted(by: <#T##((key: String, value: String), (key: String, value: String)) -> Bool#>)
import Foundation struct RingBuffer<T> { private var array: [T?] private var readIndex = 0 private var writeIndex = 0 init(count: Int) { self.array = [T?](repeating: nil, count: count) } mutating func write(_ element: T) { self.readIndex += self.isFull ? 1 : 0 self.array[self.writeIndex % self.array.count] = element self.writeIndex += 1 } mutating func read() -> T? { guard isEmpty == false else { return nil } defer { self.array[self.readIndex % self.array.count] = nil self.readIndex += 1 } return self.array[self.readIndex % self.array.count] } } private extension RingBuffer { var isEmpty: Bool { return self.availableSpaceForReading == 0 } var isFull: Bool { return self.availableSpaceForWriting == 0 } var availableSpaceForReading: Int { return self.writeIndex - self.readIndex } var availableSpaceForWriting: Int { return self.array.count - self.availableSpaceForReading } } extension RingBuffer: Sequence { func makeIterator() -> AnyIterator<T> { var index = self.readIndex return AnyIterator { guard index < self.writeIndex else { return nil } defer { index += 1 } return self.array[index % self.array.count] } } }
// // DynamicKey.swift // // // Created by Vladislav Fitc on 27/03/2020. // import Foundation struct DynamicKey: CodingKey { var intValue: Int? var stringValue: String init(intValue: Int) { self.intValue = intValue self.stringValue = String(intValue) } init(stringValue: String) { self.stringValue = stringValue } }
// // ReminderVC.swift // Pilly // // Created by Murtaza on 02/05/2019. // Copyright © 2019 Murtaza. All rights reserved. // import UIKit var nowfrom = "reminder" class ReminderVC: UIViewController,UIPickerViewDelegate,UIPickerViewDataSource ,UITableViewDelegate,UITableViewDataSource{ var datePickerIndexPath: IndexPath? let pickerData = ["Every Day", "Every Week", "Every Month"] @IBOutlet weak var intervalLabel: UILabel! @IBOutlet weak var userField: UITextField! @IBOutlet weak var dosefield: UITextField! @IBOutlet weak var pillField: UITextField! @IBOutlet weak var notefield: UITextField! // var Itemsarray:[(name:String,value:String)] = [] var inputTexts: [String] = ["Alert Time 1"] var inputDates: [Date] = [] @IBOutlet weak var reminderTableView: UITableView! { didSet{ reminderTableView.register(UINib(nibName: DateTableViewCell.nibName(), bundle: nil), forCellReuseIdentifier: DateTableViewCell.reuseIdentifier()) reminderTableView.register(UINib(nibName: DatePickerTableViewCell.nibName(), bundle: nil), forCellReuseIdentifier: DatePickerTableViewCell.reuseIdentifier()) reminderTableView.dataSource = self reminderTableView.delegate = self } } var toolBar = UIToolbar() var picker: UIPickerView = UIPickerView() override func viewDidLoad() { super.viewDidLoad() addInitailValues() // Do any additional setup after loading the view. self.pillField.text = medname picker.backgroundColor = .white // self.Itemsarray.append((name: "Alert Time 1", value: "")) //picker.showsSelectionIndicator = true picker.delegate = self picker.dataSource = self } @IBAction func backBtn(_ sender: Any) { self.dismiss(animated: true, completion: nil) } @IBAction func pillBtn(_ sender: Any) { self.NextViewController(storybordid: "MedicationVC") } func addInitailValues() { inputDates = Array(repeating: Date(), count: inputTexts.count) } func indexPathToInsertDatePicker(indexPath: IndexPath) -> IndexPath { if let datePickerIndexPath = datePickerIndexPath, datePickerIndexPath.row < indexPath.row { return indexPath } else { return IndexPath(row: indexPath.row + 1, section: indexPath.section) } } @IBAction func addtimeBtn(_ sender: Any) { let item = "Alert Time \(self.inputTexts.count + 1)" reminderTableView.beginUpdates() inputTexts.append(item) inputDates.append(Date()) let indexPath:IndexPath = IndexPath(row:(self.inputTexts.count - 1), section:0) reminderTableView.insertRows(at: [indexPath], with: .left) reminderTableView.endUpdates() print(inputTexts) } @IBAction func InterValBtn(_ sender: Any) { print("button clickd") picker = UIPickerView.init() self.picker.delegate = self self.picker.dataSource = self picker.backgroundColor = UIColor.white picker.setValue(UIColor.black, forKey: "textColor") picker.autoresizingMask = .flexibleWidth picker.contentMode = .center picker.frame = CGRect.init(x: 0.0, y: UIScreen.main.bounds.size.height - 300, width: UIScreen.main.bounds.size.width, height: 300) self.view.addSubview(picker) toolBar = UIToolbar.init(frame: CGRect.init(x: 0.0, y: UIScreen.main.bounds.size.height - 300, width: UIScreen.main.bounds.size.width, height: 50)) toolBar.barStyle = .blackTranslucent toolBar.barTintColor = .red toolBar.items = [UIBarButtonItem.init(title: "Done", style: .done, target: self, action: #selector(onDoneButtonTapped))] self.view.addSubview(toolBar) } @objc func onDoneButtonTapped() { toolBar.removeFromSuperview() picker.removeFromSuperview() } } extension ReminderVC{ //<---------------------------- Picker View -----------------> func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return pickerData.count } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { print("row valu is \(pickerData[row])") return pickerData[row] } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { intervalLabel.text = self.pickerData[row] self.view.endEditing(true) } //<----------------------- table View delegate--------------------------> } extension ReminderVC { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if datePickerIndexPath != nil { return inputTexts.count + 1 } else { return inputTexts.count } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if datePickerIndexPath == indexPath { let datePickerCell = tableView.dequeueReusableCell(withIdentifier: DatePickerTableViewCell.reuseIdentifier()) as! DatePickerTableViewCell datePickerCell.updateCell(date: inputDates[indexPath.row - 1], indexPath: indexPath) datePickerCell.delegate = self return datePickerCell } else { let dateCell = tableView.dequeueReusableCell(withIdentifier: DateTableViewCell.reuseIdentifier()) as! DateTableViewCell dateCell.updateText(text: inputTexts[indexPath.row], date: inputDates[indexPath.row]) return dateCell } } //<----------------------- table View delegate--------------------------> func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.beginUpdates() if let datePickerIndexPath = datePickerIndexPath, datePickerIndexPath.row - 1 == indexPath.row { tableView.deleteRows(at: [datePickerIndexPath], with: .fade) self.datePickerIndexPath = nil } else { if let datePickerIndexPath = datePickerIndexPath { tableView.deleteRows(at: [datePickerIndexPath], with: .fade) } datePickerIndexPath = indexPathToInsertDatePicker(indexPath: indexPath) tableView.insertRows(at: [datePickerIndexPath!], with: .fade) tableView.deselectRow(at: indexPath, animated: true) } tableView.endUpdates() } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if datePickerIndexPath == indexPath { return DatePickerTableViewCell.cellHeight() } else { return DateTableViewCell.cellHeight() } } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if indexPath.row != 0{ if (editingStyle == .delete) { self.inputTexts.remove(at: indexPath.row) self.reminderTableView.reloadData() } // handle delete (by removing the data from your array and updating the tableview) } } } extension ReminderVC: DatePickerDelegate { func didChangeDate(date: Date, indexPath: IndexPath) { inputDates[indexPath.row] = date reminderTableView.reloadRows(at: [indexPath], with: .none) } }
// // MexicanTrainUI.swift // MexicanTrain // // Created by Ceri on 09/05/2020. // import Madog import UIKit class MexicanTrainUI { private let window: UIWindow private let madog = Madog<MadogToken>() init(window: UIWindow) { self.window = window madog.resolve(resolver: MadogResolver()) } func showInitialUI() -> Bool { let context = madog.renderUI(identifier: .navigation, tokenData: .single(MadogToken.welcome), in: window) { $0.setNavigationBarHidden(true, animated: false) } return context != nil } // MARK: - Private private var serviceProvider: MadogServiceProvider? { return madog.serviceProviders[serviceProviderName] as? MadogServiceProvider } } extension Context { func navigate(to token: MadogToken) { change(to: .basic, tokenData: .single(token), transition: Transition(duration: 1, options: .transitionCrossDissolve)) } }
// // TemplateDetailTableViewController.swift // intermine-ios // // Created by Nadia on 5/12/17. // Copyright © 2017 Nadia. All rights reserved. // import UIKit class TemplateDetailTableViewController: UITableViewController, TemplateDetailCellDelegate, OperationSelectViewControllerDelegate, ActionCellDelegate { private var sortedQueries: [TemplateQuery] = [] private var popover: OperationSelectViewController? private var displayedQueries: [TemplateQuery] = [] // we don't want to show non-editable queries, but still need them to make a request var template: Template? { didSet { UIView.transition(with: self.tableView, duration: 0.5, options: .transitionCrossDissolve, animations: { self.tableView.reloadData() }, completion: nil) if let template = self.template { self.sortedQueries = template.getQueriesSortedByType() self.displayedQueries = self.sortedQueries.filter({ (query: TemplateQuery) -> Bool in return query.isEditable() }) } } } // MARK: Load from storyboard class func templateDetailTableViewController(withTemplate: Template) -> TemplateDetailTableViewController? { let storyboard = UIStoryboard(name: "Main", bundle: nil) let vc = storyboard.instantiateViewController(withIdentifier: "TemplateDetailVC") as? TemplateDetailTableViewController vc?.template = withTemplate return vc } // MARK: View controller methods override func viewDidLoad() { super.viewDidLoad() self.tableView.rowHeight = UITableViewAutomaticDimension self.tableView.estimatedRowHeight = 200 self.tableView.sectionHeaderHeight = UITableViewAutomaticDimension self.tableView.estimatedSectionHeaderHeight = 60 self.navigationItem.titleView = UIView() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) NotificationCenter.default.addObserver(self, selector: #selector(self.operationChanged(_:)), name: NSNotification.Name(rawValue: Notifications.operationChanged), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(self.valueChanged(_:)), name: NSNotification.Name(rawValue: Notifications.valueChanged), object: nil) } override func viewWillDisappear(_ animated: Bool) { super.viewWillAppear(animated) NotificationCenter.default.removeObserver(self) } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return displayedQueries.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: TemplateDetailCell.identifier, for: indexPath) as! TemplateDetailCell cell.templateQuery = displayedQueries[indexPath.row] cell.index = indexPath.row cell.delegate = self return cell } // MARK: Header and footer override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let cell = tableView.dequeueReusableCell(withIdentifier: DescriptionCell.identifier) as! DescriptionCell cell.info = template?.getInfo() cell.title = template?.getTitle() return cell } override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { let cell = tableView.dequeueReusableCell(withIdentifier: ActionCell.identifier) as! ActionCell cell.delegate = self return cell } override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 60 } // MARK: Template detail cell delegate func templateDetailCellDidTapSelectButton(cell: TemplateDetailCell) { let ip = self.tableView.indexPath(for: cell) if let popover = OperationSelectViewController.operationSelectViewController(forCellIndex: ip?.row) { popover.modalPresentationStyle = UIModalPresentationStyle.popover popover.delegate = self self.popover = popover self.present(popover, animated: true, completion: nil) } } // MARK: Operation select view controller delegate func operationSelectViewControllerDidTapClose(controller: OperationSelectViewController) { self.popover?.dismiss(animated: true, completion: nil) } // MARK: Action cell delegate func actionCellDidTapSearchButton(actionCell: ActionCell) { guard let template = self.template else { return } var gen = 0 var params = ["name": template.getName(), "start": "0", "size": "15", "format": "json"] for query in self.sortedQueries { gen += 1 let queryParams = query.constructDictForGen(gen: gen) params.update(other: queryParams) } print(params) if let mineUrl = self.template?.getMineUrl() { if let fetchedVC = FetchedTemplatesViewController.fetchedTemplatesViewController(withMineUrl: mineUrl, params: params) { self.navigationController?.pushViewController(fetchedVC, animated: true) } } } // MARK: Notification when operation is changed func operationChanged(_ notification: NSNotification) { if let op = notification.userInfo?["op"] as? String, let index = notification.userInfo?["index"] as? Int { let updatedQuery = self.displayedQueries[index] updatedQuery.changeOperation(operation: op) } } // MARK: Notification when value is changed func valueChanged(_ notification: NSNotification) { if let value = notification.userInfo?["value"] as? String, let index = notification.userInfo?["index"] as? Int { let updatedQuery = self.displayedQueries[index] updatedQuery.changeValue(value: value) } } }
// // BannerView.swift // StarbucksImitation // // Created by lh on 16/6/18. // Copyright © 2016年 codwam. All rights reserved. // import iCarousel final class BannerView: BaseView { var localImageNames = [String]() { didSet { self.imageCarousel.reloadData() self.pageControl.numberOfPages = self.localImageNames.count } } var currentIndex = 0 private var imageCarousel: iCarousel! private var tipLabel: UILabel! private var pageControl: UIPageControl! override func constructView() { // Image self.imageCarousel = iCarousel() // self.imageCarousel.type = .Rotary self.imageCarousel.pagingEnabled = true self.imageCarousel.dataSource = self self.imageCarousel.delegate = self // Tip self.tipLabel = UILabel() self.tipLabel.text = "Swipe to change the card" self.tipLabel.textColor = UIColor(hexString: "BBBBBB").flatten() self.tipLabel.font = UIFont.systemFontOfSize(14) self.tipLabel.textAlignment = .Center // PageControl self.pageControl = UIPageControl() self.pageControl.hidesForSinglePage = true self.pageControl.currentPageIndicatorTintColor = UIColor(hexString: "BEBEBE").flatten() self.pageControl.pageIndicatorTintColor = UIColor(hexString: "E3E3E3").flatten() self.addSubview(self.imageCarousel) self.addSubview(self.tipLabel) self.addSubview(self.pageControl) } override func constructLayout() { // Image self.imageCarousel.snp_makeConstraints { (make) in make.edges.equalTo(self) } // Tip self.tipLabel.snp_makeConstraints { (make) in make.left.right.equalTo(self.pageControl) make.bottom.equalTo(self.pageControl.snp_top) make.height.equalTo(12) } // PageControl self.pageControl.snp_makeConstraints { (make) in make.left.right.equalTo(self) make.bottom.equalTo(self).offset(-8) make.height.equalTo(30) } } override func layoutSubviews() { super.layoutSubviews() if self.imageCarousel.currentItemIndex != self.currentIndex { self.imageCarousel.scrollToItemAtIndex(self.currentIndex, animated: false) self.pageControl.currentPage = self.currentIndex } } } extension BannerView: iCarouselDataSource, iCarouselDelegate { func numberOfItemsInCarousel(carousel: iCarousel) -> Int { return self.localImageNames.count } func carousel(carousel: iCarousel, viewForItemAtIndex index: Int, reusingView view: UIView?) -> UIView { var reusingView = view if reusingView == nil { let image = UIImage(named: self.localImageNames[index]) reusingView = UIImageView(image: image) reusingView?.frame = self.bounds } return reusingView! } func carousel(carousel: iCarousel, valueForOption option: iCarouselOption, withDefault value: CGFloat) -> CGFloat { switch option { case .Wrap: return 1 default: return value } } func carouselCurrentItemIndexDidChange(carousel: iCarousel) { self.pageControl.currentPage = carousel.currentItemIndex } }
// // BooksDB.swift // IZA-2019-cvika-2 // // Created by Martin Hruby on 13/03/2019. // Copyright © 2019 Martin Hruby. All rights reserved. // import Foundation // -------------------------------------------------------------------- // V aplikaci existuje jeden singleton BooksDB (AppDelegate::booksDB) // -------------------------------------------------------------------- // Objekt drzi original vsech objektu Book // Sem smeruje editace obsahu databaze: add/remove/edit class BooksDB { // ---------------------------------------------------------------- // original vsech evidovanych objektu. Slo by nejak zapouzdrit... var items: [Book] = [] // tuto zpravu bude BooksDB rozesilat pres Notifikacni centrum // BooksDB nema explicitne registrovane observery static let ncMessage = Notification.Name("BooksDB:ping:toall") // ---------------------------------------------------------------- // ping v MT private func pingObservers(with aBook: Book? = nil) { // Notifikace laskave posilejme vyhradne v MT DispatchQueue.main.async { // zprava: nazev + Optional<aBook> let nn = Notification(name: BooksDB.ncMessage, object: aBook, userInfo: nil) // NotificationCenter.default.post(nn) } } // ---------------------------------------------------------------- // Simulace nacteni DB z nejakeho zdroje (sitovy dotaz na SQL..) // Smi pracovat v Global-queue (gt*) func gtLoadContent() { // let _data = [Book(existingBookCalled: "Honzikova cesta", by: "B. Riha", state: .reading), Book(existingBookCalled: "Tri musketyru", by: "A. Dumas", state: .reading)] // DispatchQueue.main.async { // self.items = _data // self.pingObservers() } } } // -------------------------------------------------------------------- // extension BooksDB { // func updated(aBook: Book) { // switch aBook.state { case .new: // aBook.state = .reading items.append(aBook); // pingObservers(); default: pingObservers(with: aBook) } } }
// // ReadyDoingQuizViewController.swift // FinanceQuizApp // // Created by Gibson Kong on 08/05/2017. // Copyright © 2017 訪客使用者. All rights reserved. // import UIKit class ReadyDoingQuizViewController: UIViewController { @IBOutlet var Button: [UIButton]! var QuizSet : ExamSet! var QuizDetail : [String:Int] = ["ProfessionSet":0,"LicenseGrade":0,"LicenseType":0,"ExamSet":0] @IBAction func StartBtn(_ sender: Any) { QuizSet.shuffle() } override func viewDidLoad() { super.viewDidLoad() ButtonAdjust(Button) // Do any additional setup after loading the view. } override func viewWillAppear(_ animated: Bool) { super.viewDidLoad() self.tabBarController?.tabBar.isHidden = true // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "StartQuiz" { let destination = segue.destination as! DoingQuizViewController destination.ExamSet = QuizSet destination.QuizDetail["ProfessionSet"] = self.QuizDetail["ProfessionSet"] destination.QuizDetail["LicenseGrade"] = self.QuizDetail["LicenseGrade"] destination.QuizDetail["LicenseType"] = self.QuizDetail["LicenseType"] destination.QuizDetail["ExamSet"] = self.QuizDetail["ExamSet"] } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
// // HomeMiddleware.swift // Breeze // // Created by Alex Littlejohn on 27/04/2020. // Copyright © 2020 zero. All rights reserved. // import Ducks
// // Created by Przemysław Pająk on 08.01.2018. // Copyright (c) 2018 FEARLESS SPIDER. All rights reserved. // import Foundation protocol FollowersViewRouter: ViewRouter { } class FollowersViewRouterImplementation: FollowersViewRouter { fileprivate weak var followersViewController: FollowersViewController? init(followersViewController: FollowersViewController) { self.followersViewController = followersViewController } }
// // CustomCategoryTableViewCell.swift // iWorldLocation // // Created by iappscrazy on 07/01/2015. // Copyright (c) 2015 iappscrazy. All rights reserved. // import UIKit class CustomCategoryTableViewCell: UITableViewCell { @IBOutlet weak var searchtermLbl: UILabel! @IBOutlet weak var searchTermImg: UIImageView! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } func updateCell(searchTerm:NSString){ searchtermLbl.text = searchTerm.capitalizedString as String searchTermImg.image = UIImage(named: (searchTerm as String)+".png") } }
// // BottomMarginCell.swift // MinervaExample // // Copyright © 2019 Optimize Fitness, Inc. All rights reserved. // import Foundation import UIKit import Minerva final class BottomMarginCellModel: BaseListCellModel { var backgroundColor: UIColor? // MARK: - BaseListCellModel override var identifier: String { return "BottomMarginCellModel" } override func isEqual(to model: ListCellModel) -> Bool { guard let model = model as? BottomMarginCellModel else { return false } return backgroundColor == model.backgroundColor } override func size(constrainedTo containerSize: CGSize) -> ListCellSize { let device = UIDevice.current let height: CGFloat if device.userInterfaceIdiom == .pad && device.orientation.isLandscape { height = 60 } else if device.userInterfaceIdiom == .pad { height = 120 } else { height = 40 } let width = containerSize.width return .explicit(size: CGSize(width: width, height: height)) } } final class BottomMarginCell: BaseListCell, ListCellHelper { typealias ModelType = BottomMarginCellModel override func updatedCellModel() { super.updatedCellModel() guard let model = self.model else { return } self.contentView.backgroundColor = model.backgroundColor } }
// // CategoryListViewController.swift // GaoXiao // // Created by 汪红亮 on 2017/9/9. // Copyright © 2017年 rekuu. All rights reserved. // import UIKit import WebKit import MJRefresh class CategoryListTableViewController: UITableViewController { var webView: WKWebView! var articleList: [ArticleRecord] = [] let imageOperations = ImageOperations() var parentNav: UINavigationController? var categoryid:Int! let timeZone = TimeZone.init(identifier: "UTC") let formatter = DateFormatter() //加载视频播放器 var player:CJVideoPlayer! = nil var _indexPath = IndexPath() var videoCell = VideoCell() //加载动态图片 var imageView = UIImageView() var gifCell = GifCell() // 顶部刷新 let header = MJRefreshNormalHeader() var refreshTime = Date() // 底部加载 let footer = MJRefreshAutoNormalFooter() var pageIndex = 1 var pageSize = 12 var pageCount = 1 override func viewDidLoad() { super.viewDidLoad() //首次加载数据 refreshTime = Date() loadMore() self.tableView!.delegate = self self.tableView!.dataSource = self //下拉刷新相关设置 header.setRefreshingTarget(self, refreshingAction: #selector(self.loadNew)) self.tableView!.mj_header = header //上刷新相关设置 footer.setRefreshingTarget(self, refreshingAction: #selector(self.loadMore)) //是否自动加载(默认为true,即表格滑到底部就自动加载) footer.isAutomaticallyRefresh = false self.tableView!.mj_footer = footer //设置表格预估高度和自动高度 tableView.estimatedRowHeight = 200 tableView.rowHeight = UITableViewAutomaticDimension } //加载最新数据 func loadNew() -> Void { formatter.locale = Locale.current formatter.dateFormat = "yyyy-MM-dd HH:mm:ss" let strtime = formatter.string(from: refreshTime) //请求最新数据 Article.getArticleNew(categoryid: categoryid, top:10, refreshtime: strtime){ (contents) in if contents != nil{ //网络请求是异步线程,需要加到主线程 OperationQueue.main.addOperation { //更新刷新时间 self.refreshTime = Date() for item in contents!.articles!{ self.articleList.insert(ArticleRecord(article: item, url: ""), at: 0) } //重现加载表格数据 self.tableView.reloadData() //结束刷新 self.tableView!.mj_header.endRefreshing() } }else{ print("网络错误") } //重现加载表格数据 self.tableView!.reloadData() //结束刷新 self.tableView!.mj_header.endRefreshing() } } //加载更多数据 func loadMore(){ //判断是否到达最后一页 if(self.pageIndex > self.pageCount){ //结束刷新状态 self.tableView!.mj_footer.endRefreshing() return } else{ Article.getArticle(categoryid: categoryid, pagesize:pageSize, pageindex: pageIndex){ (contents) in if contents != nil{ //网络请求是异步线程,需要加到主线程 OperationQueue.main.addOperation { //设置页数 self.pageCount = contents!.pageCount for item in contents!.articles{ self.articleList.append(ArticleRecord(article: item, url: "")) } //重现加载表格数据 self.tableView.reloadData() //结束刷新 self.tableView!.mj_footer.endRefreshing() } } else{ print("网络错误") } } //当前页码+1 pageIndex+=1 } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.articleList.count //return newsList.count; } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { //获取当前行所对应的记录。 let articleRecord = self.articleList[indexPath.row] as ArticleRecord let article = articleRecord.article switch categoryid { case 52: let cell = tableView.dequeueReusableCell(withIdentifier: "TextCell", for: indexPath) as! TextCell cell.lblTitle.text = article.title cell.lblText.text = article.content.pregReplace(pattern: "<[^>]*>", with:"") cell.lblComment.text = article.add_time! return cell case 53: let cell = tableView.dequeueReusableCell(withIdentifier: "ImgCell", for: indexPath) as! ImgCell //let outcome = article.content.matches(pattern: "(https?|ftp|mms)://([A-z0-9]+[_-]?[A-z0-9]+.)*[A-z0-9]+-?[A-z0-9]+.[A-z]{2,}(/.[A-z])*/?") //if outcome.count == 0{ //没有匹配到 //}else{ // articleRecord.url = outcome.first!.extraction //} articleRecord.url = article.zhaiyao //cell.loadImage(urlString: articleRecord.url) cell.lblTitle.text = article.title cell.imgContent.image = articleRecord.image cell.SetImageRect() //检查图片状态。然后开始执行任务 switch (articleRecord.state){ case .filtered: break case .failed: cell.textLabel?.text = "Failed to load" case .new, .downloaded: //只有停止拖动的时候才加载 //if (!tableView.isDragging && !tableView.isDecelerating) { self.startOperationsForMovieRecord(articleRecord, indexPath: indexPath) //} } return cell case 54: let cell = tableView.dequeueReusableCell(withIdentifier: "VideoCell", for: indexPath) as! VideoCell articleRecord.type = .video articleRecord.url = article.zhaiyao //设置默认图片 cell.imgVideo.image = articleRecord.image cell.mp4_url = article.zhaiyao cell.lblTitle.text = article.title cell.SetImageRect(); //cell.loadImage(urlString: article.zhaiyao) //检查图片状态。然后开始执行任务 switch (articleRecord.state){ case .filtered: break case .failed: break case .new, .downloaded: //只有停止拖动的时候才加载 //if (!tableView.isDragging && !tableView.isDecelerating) { self.startOperationsForMovieRecord(articleRecord, indexPath: indexPath) //} } let tap = UITapGestureRecognizer(target: self, action: #selector(self.showVideoPlayer(sender:))) cell.player.addGestureRecognizer(tap) cell.player.isUserInteractionEnabled = true cell.player.tag = indexPath.row+100 return cell case 55: let cell = tableView.dequeueReusableCell(withIdentifier: "GifCell", for: indexPath) as! GifCell articleRecord.url = article.zhaiyao //设置 articleRecord.type = .gif cell.lblTitle.text = article.title cell.gifContent.image = articleRecord.image cell.gifUrl = articleRecord.url //cell.loadImage(urlString: articleRecord.url) cell.SetImageRect(); //检查图片状态。然后开始执行任务 switch (articleRecord.state){ case .filtered: break case .failed: break case .new, .downloaded: //只有停止拖动的时候才加载 //if (!tableView.isDragging && !tableView.isDecelerating) { self.startOperationsForMovieRecord(articleRecord, indexPath: indexPath) //} } let tap = UITapGestureRecognizer(target: self, action: #selector(self.showGifImage(sender:))) cell.btnLoadGif.addGestureRecognizer(tap) cell.btnLoadGif.isUserInteractionEnabled = true cell.btnLoadGif.tag = indexPath.row+100 return cell default: return UITableViewCell() } } //显示视频播放器 func showVideoPlayer(sender:UITapGestureRecognizer) -> Void { if player != nil{ player.destroy() } let tapView = sender.view _indexPath = IndexPath(row: tapView!.tag - 100, section: 0) videoCell = tableView.cellForRow(at: _indexPath) as! VideoCell player = CJVideoPlayer() player.videoUrl = videoCell.mp4_url player.palyerBindTableView(self.tableView, at: _indexPath) player.frame = videoCell.imgVideo.bounds// tapView!.bounds player.frame.origin.x += 5 player.frame.origin.y += 58 player.isSupportSmallWindowPlaying(false) player.accessibilityNavigationStyle = UIAccessibilityNavigationStyle(rawValue: accessibilityNavigationStyle.hashValue)! videoCell.contentView.addSubview(player) player.completedPlayingBlock = {(player) -> (Void) in player?.destroy() } } //显示Gif func showGifImage(sender:UITapGestureRecognizer) -> Void { let tapView = sender.view _indexPath = IndexPath(row: tapView!.tag - 100, section: 0) gifCell = tableView.cellForRow(at: _indexPath) as! GifCell if imageView.image != nil{ imageView.image = nil imageView.removeFromSuperview() } //定义NSURL对象 let url = URL(string: gifCell.gifUrl) let data = try? Data(contentsOf: url!) //从网络获取数据流,再通过数据流初始化图片 if let imageData = data, let image = UIImage.gif(data: imageData){ imageView.image = image imageView.frame = gifCell.gifContent.bounds// tapView!.bounds imageView.frame.origin.x += 10 imageView.frame.origin.y += 60 gifCell.contentView.addSubview(imageView) } } //图片任务 func startOperationsForMovieRecord(_ articleRecord: ArticleRecord, indexPath: IndexPath){ switch (articleRecord.state) { case .new: //判断是否为图片列 if articleRecord.url == ""{ break } startDownloadForRecord(articleRecord, indexPath: indexPath) case .downloaded: break //startFiltrationForRecord(articleRecord, indexPath: indexPath) default: NSLog("do nothing") } } //执行图片下载任务 func startDownloadForRecord(_ articleRecord: ArticleRecord, indexPath: IndexPath){ //判断队列中是否已有该图片任务 if let _ = imageOperations.downloadsInProgress[indexPath] { return } //创建一个下载任务 let downloader = ImageDownloader(articleRecord: articleRecord) //任务完成后重新加载对应的单元格 downloader.completionBlock = { if downloader.isCancelled { return } DispatchQueue.main.async(execute: { self.imageOperations.downloadsInProgress.removeValue(forKey: indexPath) self.tableView.reloadRows(at: [indexPath], with: .fade) }) } //记录当前下载任务 imageOperations.downloadsInProgress[indexPath] = downloader //将任务添加到队列中 imageOperations.downloadQueue.addOperation(downloader) } //执行图片滤镜任务 func startFiltrationForRecord(_ articleRecord: ArticleRecord, indexPath: IndexPath){ if let _ = imageOperations.filtrationsInProgress[indexPath]{ return } let filterer = ImageFiltration(articleRecord: articleRecord) filterer.completionBlock = { if filterer.isCancelled { return } DispatchQueue.main.async(execute: { self.imageOperations.filtrationsInProgress.removeValue(forKey: indexPath) self.tableView.reloadRows(at: [indexPath], with: .fade) }) } imageOperations.filtrationsInProgress[indexPath] = filterer imageOperations.filtrationQueue.addOperation(filterer) } override func scrollViewDidScroll(_ scrollView: UIScrollView) { if scrollView.isEqual(self.tableView) { if player != nil { player.isSupportSmallWindowPlaying(false) } } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(true) if player != nil { player.destroy() } //只有停止拖动的时候才加载 if (!tableView.isDragging && !tableView.isDecelerating) { if self.imageView.isAnimating{ self.imageView.removeFromSuperview() } } } //视图开始滚动 override func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { /*//一旦用户开始滚动屏幕,你将挂起所有任务并留意用户想要看哪些行。 if scrollView.isEqual(self.tableView) { if player != nil { suspendAllOperations() } }*/ } //视图停止拖动 override func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { /*//如果减速(decelerate)是 false ,表示用户停止拖拽tableview。 //此时你要继续执行之前挂起的任务,撤销不在屏幕中的cell的任务并开始在屏幕中的cell的任务。 if scrollView.isEqual(self.tableView) { if player != nil { if !decelerate { loadImagesForOnscreenCells() resumeAllOperations() } } }*/ } //视图停止减速 override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { /*//这个代理方法告诉你tableview停止滚动,执行操作同上 if scrollView.isEqual(self.tableView) { if player != nil { loadImagesForOnscreenCells() resumeAllOperations() } }*/ } //暂停所有队列 func suspendAllOperations () { imageOperations.downloadQueue.isSuspended = true imageOperations.filtrationQueue.isSuspended = true } //恢复运行所有队列 func resumeAllOperations () { imageOperations.downloadQueue.isSuspended = false imageOperations.filtrationQueue.isSuspended = false } //加载可见区域的单元格图片 func loadImagesForOnscreenCells () { //开始将tableview可见行的index path放入数组中。 if let pathsArray = self.tableView.indexPathsForVisibleRows { //通过组合所有下载队列和滤镜队列中的任务来创建一个包含所有等待任务的集合 let allMovieOperations = NSMutableSet() for key in imageOperations.downloadsInProgress.keys{ allMovieOperations.add(key) } for key in imageOperations.filtrationsInProgress.keys{ allMovieOperations.add(key) } //构建一个需要撤销的任务的集合。从所有任务中除掉可见行的index path, //剩下的就是屏幕外的行所代表的任务。 let toBeCancelled = allMovieOperations.mutableCopy() as! NSMutableSet let visiblePaths = NSSet(array: pathsArray) toBeCancelled.minus(visiblePaths as Set<NSObject>) //创建一个需要执行的任务的集合。从所有可见index path的集合中除去那些已经在等待队列中的。 let toBeStarted = visiblePaths.mutableCopy() as! NSMutableSet toBeStarted.minus(allMovieOperations as Set<NSObject>) // 遍历需要撤销的任务,撤消它们,然后从 movieOperations 中去掉它们 for indexPath in toBeCancelled { let indexPath = indexPath as! IndexPath if let imageDownload = imageOperations.downloadsInProgress[indexPath] { imageDownload.cancel() } imageOperations.downloadsInProgress.removeValue(forKey: indexPath) if let imageFiltration = imageOperations.filtrationsInProgress[indexPath] { imageFiltration.cancel() } imageOperations.filtrationsInProgress.removeValue(forKey: indexPath) } // 遍历需要开始的任务,调用 startOperationsForPhotoRecord for indexPath in toBeStarted { let indexPath = indexPath as! IndexPath let recordToProcess = self.articleList[indexPath.row] startOperationsForMovieRecord(recordToProcess, indexPath: indexPath) } } } }
// // ClientObject.swift // TravelstartInterviewPractice // // Created by 潘立祥 on 2019/11/2. // Copyright © 2019 PanLiHsiang. All rights reserved. // import Foundation struct ClientObject: Codable { let limit: Int let offset: Int let count: Int let sort: String let results: [Results] } struct Results: Codable { let info: String? let stitle: String let xpostDate: String let longitude: String let refWp: String let avBegin: String let langinfo: String let mrt: String? let serialNo: String let rowNumber: String let cat1: String let cat2: String let memoTime: String? let poi: String let file: String let idpt: String let latitude: String let xbody: String let id: Int let avEnd: String let address: String var filteredStringArray: [String] { return StringSeparator.urlStrSeparate(string: file) } enum CodingKeys: String, CodingKey { case refWp = "REF_WP" case mrt = "MRT" case serialNo = "SERIAL_NO" case rowNumber = "RowNumber" case cat1 = "CAT1" case cat2 = "CAT2" case memoTime = "MEMO_TIME" case poi = "POI" case id = "_id" case info, stitle, xpostDate, longitude, avBegin, langinfo, file, idpt, latitude, xbody, avEnd, address } }
var code = [ "a" : "b", "b" : "c", "c" : "d", "d" : "e", "e" : "f", "f" : "g", "g" : "h", "h" : "i", "i" : "j", "j" : "k", "k" : "l", "l" : "m", "m" : "n", "n" : "o", "o" : "p", "p" : "q", "q" : "r", "r" : "s", "s" : "t", "t" : "u", "u" : "v", "v" : "w", "w" : "x", "x" : "y", "y" : "z", "z" : "a" ] var encodedMessage = "uijt nfttbhf jt ibse up sfbe" var decoder: [String:String] = [:] // reverse the code for (key, value) in code { decoder[value] = key } var decodedMessage = "" for char in encodedMessage.characters { var character = "\(char)" if let encodedChar = decoder[character] { // letter decodedMessage += encodedChar } else { // space decodedMessage += character } } print(decodedMessage)
import MetalKit enum TextureTypes{ case None case SnakeHead case SnakeHeadDead case SnakeBody case SnakeBodyHit case SnakeTail case SnakeTurn case SnakeTurnHit case Apple case Apple0 case Apple1 case Apple2 case Apple3 case Apple4 } class Textures { private static var _library: [TextureTypes: Texture] = [:] public static func Initialize() { _library.updateValue(Texture("SnakeHead"), forKey: .SnakeHead) _library.updateValue(Texture("SnakeHeadDead"), forKey: .SnakeHeadDead) _library.updateValue(Texture("SnakeBody"), forKey: .SnakeBody) _library.updateValue(Texture("SnakeBodyHit"), forKey: .SnakeBodyHit) _library.updateValue(Texture("SnakeTail"), forKey: .SnakeTail) _library.updateValue(Texture("SnakeTurn"), forKey: .SnakeTurn) _library.updateValue(Texture("SnakeTurnHit"), forKey: .SnakeTurnHit) _library.updateValue(Texture("apple"), forKey: .Apple) _library.updateValue(Texture("apple0"), forKey: .Apple0) _library.updateValue(Texture("apple1"), forKey: .Apple1) _library.updateValue(Texture("apple2"), forKey: .Apple2) _library.updateValue(Texture("apple3"), forKey: .Apple3) _library.updateValue(Texture("apple4"), forKey: .Apple4) } public static func get(_ type: TextureTypes)->MTLTexture { return self._library[type]!.texture } } class Texture { var texture: MTLTexture! init(_ textureName: String, ext: String = "png", origin: MTKTextureLoader.Origin = .topLeft){ let textureLoader = TextureLoader(textureName: textureName, textureExtension: ext, origin: origin) let texture: MTLTexture = textureLoader.loadTextureFromBundle() setTexture(texture) } func setTexture(_ texture: MTLTexture){ self.texture = texture } } class TextureLoader { private var _textureName: String! private var _textureExtension: String! private var _origin: MTKTextureLoader.Origin! init(textureName: String, textureExtension: String = "png", origin: MTKTextureLoader.Origin = .topLeft){ self._textureName = textureName self._textureExtension = textureExtension self._origin = origin } public func loadTextureFromBundle()->MTLTexture{ var result: MTLTexture! if let url = Bundle.main.url(forResource: _textureName, withExtension: self._textureExtension) { let textureLoader = MTKTextureLoader(device: Engine.Device) let options: [MTKTextureLoader.Option : MTKTextureLoader.Origin] = [MTKTextureLoader.Option.origin : _origin] do{ result = try textureLoader.newTexture(URL: url, options: options) result.label = _textureName }catch let error as NSError { print("ERROR::CREATING::TEXTURE::__\(_textureName!)__::\(error)") } }else { print("ERROR::CREATING::TEXTURE::__\(_textureName!) does not exist") } return result } } import MetalKit class TextureArray: NSObject { var texture: MTLTexture! var width: Int = 0 var height: Int = 0 var arrayLength: Int = 0 private var _textureCollection: [Int32:MTLTexture] = [:] init(arrayLength: Int = 1) { self.arrayLength = arrayLength } private func generateTexture() { let textureDescriptor = MTLTextureDescriptor() textureDescriptor.textureType = .type2DArray textureDescriptor.pixelFormat = GameSettings.MainPixelFormat textureDescriptor.width = self.width textureDescriptor.height = self.height textureDescriptor.arrayLength = self.arrayLength self.texture = Engine.Device.makeTexture(descriptor: textureDescriptor) } func setSlice(slice: Int32, tex: MTLTexture) { if(width == 0 || height == 0){ width = tex.width height = tex.height generateTexture() }else{ assert(tex.width == width, "The collection of textures needs to have the same size dimension") } //Add the texture to the collection for later use _textureCollection.updateValue(tex, forKey: slice) //Replace the slice region with the new texture let rowBytes = width * 4 let length = rowBytes * height let bgraBytes = [UInt8](repeating: 0, count: length) tex.getBytes(UnsafeMutableRawPointer(mutating: bgraBytes), bytesPerRow: rowBytes, from: MTLRegionMake2D(0, 0, width, height), mipmapLevel: 0) texture.replace(region: MTLRegionMake2D(0, 0, width, height), mipmapLevel: 0, slice: Int(slice), withBytes: bgraBytes, bytesPerRow: rowBytes, bytesPerImage: bgraBytes.count) } }
// // MusicVideoCollectionViewCell.swift // VIBE // // Created by 조민호 on 2020/07/20. // Copyright © 2020 Jerry Jung. All rights reserved. // import UIKit class MusicVideoCollectionViewCell: UICollectionViewCell { @IBOutlet weak var MusicVideoImageView: UIImageView! @IBOutlet weak var MusicVideoTitleLabel: UILabel! @IBOutlet weak var MusicVideoSubTitleLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } }
// // ThreeDCoordinate.swift // AdventOfCode // // Created by Shawn Veader on 12/17/20. // import Foundation struct ThreeDCoordinate: Equatable, Hashable { let x: Int let y: Int let z: Int var neighboringCoordinates: [ThreeDCoordinate] { (x-1...x+1).flatMap { nx -> [ThreeDCoordinate] in (y-1...y+1).flatMap { ny -> [ThreeDCoordinate] in (z-1...z+1).compactMap { nz -> ThreeDCoordinate? in let neighbor = ThreeDCoordinate(x: nx, y: ny, z: nz) guard neighbor != self else { return nil } // don't include ourselves return neighbor } } } } } extension ThreeDCoordinate: CustomStringConvertible, CustomDebugStringConvertible { var description: String { "(x: \(x), y: \(y), z: \(z))" } var debugDescription: String { description } }
// // ZMapEditor.swift // Seriously // // Created by Jonathan Sand on 10/29/16. // Copyright © 2016 Jonathan Sand. All rights reserved. // import Foundation #if os(OSX) import Cocoa #elseif os(iOS) import UIKit #endif let gMapEditor = ZMapEditor() enum ZReorderMenuType: String { case eAlphabetical = "a" case eByLength = "l" case eByKind = "k" case eReversed = "r" case eBySizeOfList = "s" static var activeTypes: [ZReorderMenuType] { return [.eReversed, .eByLength, .eAlphabetical, .eBySizeOfList, .eByKind] } var title: String { switch self { case .eAlphabetical: return "alphabetically" case .eReversed: return "reverse order" case .eByLength: return "by length of idea" case .eBySizeOfList: return "by size of list" case .eByKind: return "by kind of idea" } } } // mix of zone mutations and web services requests class ZMapEditor: ZBaseEditor { var priorHere : Zone? override var canHandleKey : Bool { return gIsMapOrEditIdeaMode } var moveables : ZoneArray? { return (gIsEssayMode && !gMapIsResponder) ? gEssayView?.grabbedZones : gSelecting.sortedGrabs } func forceRedraw() { gMapController?.setNeedsDisplay() } // MARK: - events // MARK: - class ZStalledEvent: NSObject { var event: ZEvent? var isWindow: Bool = true convenience init(_ iEvent: ZEvent, iIsWindow: Bool) { self.init() isWindow = iIsWindow event = iEvent } } var undoManager: UndoManager { if let w = gCurrentlyEditingWidget, w.undoManager != nil { return w.undoManager! } return gUndoManager } @discardableResult override func handleKey(_ iKey: String?, flags: ZEventFlags, isWindow: Bool) -> Bool { // false means key not handled if !gIsEditingStateChanging, !gIsPrinting, var key = iKey { let arrow = key.arrow let CONTROL = flags.hasControl let SPECIAL = flags.exactlySpecial let SPLAYED = flags.exactlySplayed let COMMAND = flags.hasCommand let OPTION = flags.hasOption var SHIFT = flags.hasShift let ANY = flags.isAny let ALL = flags.exactlyAll if key != key.lowercased() { key = key.lowercased() SHIFT = true } if "{}".contains(key) { key = (key == "{") ? "[" : "]" SHIFT = true } gTemporarilySetKey(key) gHideExplanation() if gIsEditIdeaMode { if !gTextEditor.handleKey(iKey, flags: flags) { if !ANY { return false } // ignore key events which have no modifier keys switch key { case "a": gCurrentlyEditingWidget?.selectAllText() case "d": gCurrentlyEditingWidget?.widgetZone?.tearApartCombine(ALL, SPLAYED) case "e": gToggleShowExplanations() case "f": gSearching.showSearch(OPTION) case "k": toggleColorized() case "n": editNote(flags: flags) case "p": printCurrentFocus() case "t": if SPECIAL { gCurrentlyEditingWidget?.swapWithParent() } else if COMMAND { showThesaurus(for: gCurrentlySelectedText) } case "/": return handleSlash(flags) case kComma, kPeriod: commaAndPeriod(COMMAND, OPTION, with: key == kComma) case kTab: gSelecting.addSibling(OPTION) case kSpace: gSelecting.currentMoveable.addIdea() case kReturn: if COMMAND { editNote(flags: flags) } case kEscape: editNote(flags: flags, useGrabbed: false) case kBackspace, kDelete: if CONTROL { gFocusing.grabAndFocusOn(gTrash) { gRelayoutMaps() } } default: return false // false means key not handled } } } else if isValid(key, flags) { let widget = gWidgets.widgetForZone(gSelecting.currentMoveableMaybe) if let a = arrow, isWindow { handleArrow(a, flags: flags) } else if kMarkingCharacters.contains(key), !COMMAND, !CONTROL, !OPTION { prefix(with: key) } else if !super.handleKey(iKey, flags: flags, isWindow: isWindow) { let moveable = gSelecting.currentMoveable switch key { case "a": if COMMAND { moveable.selectAll(progeny: OPTION) } case "b": gSelecting.firstSortedGrab?.addBookmark() case "c": if OPTION { divideChildren() } else if COMMAND { gSelecting.simplifiedGrabs.copyToPaste() } else { gMapController?.recenter(SPECIAL) } case "d": if ALL { gRemoteStorage.removeAllDuplicates() } else if ANY { widget?.widgetZone?.combineIntoParent() } else { duplicate() } case "e": gToggleShowExplanations() case "f": gSearching.showSearch(OPTION) case "h": showTraitsPopup() case "i": showMutateTextPopup() case "j": if SPECIAL { gRemoteStorage.recount(); gSignal([.spDataDetails]) } else { gSelecting.handleDuplicates(COMMAND) } case "k": toggleColorized() case "l": alterCase(up: false) case "n": editNote(flags: flags) case "o": moveable.importFromFile(OPTION ? .eOutline : SPLAYED ? .eCSV : .eSeriously) { gRelayoutMaps() } case "p": printCurrentFocus() case "r": if ANY { gNeedsRecount = true } else if gSelecting.hasMultipleGrabs { showReorderPopup() } else { reverseWordsInZoneName() } case "s": gFiles.export(moveable, toFileAs: OPTION ? .eOutline : .eSeriously) case "t": if SPECIAL { gControllers.showEssay(forGuide: false) } else if COMMAND { showThesaurus() } else { swapWithParent() } case "u": if SPECIAL { gControllers.showEssay(forGuide: true) } else { alterCase(up: true) } case "v": if COMMAND { paste() } case "w": rotateWritable() case "x": return handleX(flags) case "z": if !SHIFT { gUndoManager.undo() } else { gUndoManager.redo() } case "8": if OPTION { prefix(with: kSoftArrow, withParentheses: false) } // option-8 is a dot case "#": if gSelecting.hasMultipleGrabs { prefix(with: key) } else { debugAnalyze() } case "+": gSelecting.currentMapGrabs.toggleGroupOwnership() case "/": return handleSlash(flags) case "?": if CONTROL { openBrowserForSeriouslyWebsite() } else { gCurrentKeyPressed = nil; return false } case "[", "]": nextBookmark(down: key == "]", flags: flags) case kTab: gSelecting.addSibling(OPTION) case kSpace: if CONTROL || OPTION || isWindow { moveable.addIdea() } else { gCurrentKeyPressed = nil; return false } case kReturn: if COMMAND { editNote(flags: flags) } else { editIdea(OPTION) } case kEscape: editNote(flags: flags, useGrabbed: false) case kBackSlash: mapControl(OPTION) case kHyphen: return handleHyphen(COMMAND, OPTION) case kComma, kPeriod: commaAndPeriod(COMMAND, OPTION, with: key == kComma) case kEquals: if COMMAND { gUpdateBaseFontSize(up: true) } else { gSelecting.sortedGrabs.invokeTravel() { reveal in gRelayoutMaps() } } case kBackspace, kDelete: handleDelete(flags, isWindow) default: return false // indicate key was not handled } } } } gCurrentKeyPressed = nil return true // indicate key was handled } func handleArrow(_ arrow: ZArrowKey, flags: ZEventFlags, onCompletion: Closure? = nil) { if !gIsExportingToAFile { if gTextEditorHandlesArrows || gIsEditIdeaMode { gTextEditor.handleArrow(arrow, flags: flags) } else if !((flags.hasOption && !gSelecting.currentMoveable.userCanMove) || gIsHelpFrontmost) || gIsEssayMode { switch arrow { case .down, .up: moveUp (arrow == .up, flags: flags); forceRedraw() case .left, .right: moveLeft(arrow == .left, flags: flags, onCompletion: onCompletion); forceRedraw(); return } } } onCompletion?() } enum ZMenuType: Int { case eUndo case eHelp case eSort case eFind case eColor case eChild case eAlter case eFiles case eCloud case eAlways case eParent case eTravel case eRedo case ePaste case eUseGrabs case eMultiple } func menuType(for key: String, _ flags: ZEventFlags) -> ZMenuType { let alterers = "ehlnuw#" + kMarkingCharacters + kReturn let ALTERER = alterers.contains(key) let COMMAND = flags.hasCommand let CONTROL = flags.hasControl let ANY = COMMAND || CONTROL if !ANY && ALTERER { return .eAlter } else { switch key { case "f": return .eFind case "z": return .eUndo case "k": return .eColor case "g": return .eCloud case "?", "/": return .eHelp case "o", "s": return .eFiles case "x", kSpace: return .eChild case "b", "t", kTab: return .eParent case "d": return COMMAND ? .eAlter : .eParent case kDelete: return CONTROL ? .eAlways : .eParent case kEquals: return COMMAND ? .eAlways : .eTravel default: return .eAlways } } } override func invalidMenuItemAlert(_ menuItem: ZMenuItem) -> ZAlert? { let type = menuType(for: menuItem.keyEquivalent, menuItem.keyEquivalentModifierMask) let subtitle = type != .eTravel ? "is not editable" : "cannot be activated" let prefix = type != .eParent ? kEmpty : "parent of " let selected = "selected item " return gAlerts.alert("Menu item disabled", prefix + selected + subtitle, "OK", nil, nil, nil) } override func isValid(_ key: String, _ flags: ZEventFlags, inWindow: Bool = true) -> Bool { if gIsEditIdeaMode { return true } if !gIsMapMode && !gIsEssayMode { return false } if key.arrow != nil { return true } let type = menuType(for: key, flags) var valid = true if type != .eAlways { let undo = undoManager let select = gSelecting let wGrabs = select.writableGrabsCount let paste = select.pasteableZones .count let grabs = select.currentMapGrabs.count let shown = select.currentMapGrabsHaveVisibleChildren let mover = select.currentMoveable let canColor = mover.isReadOnlyRoot || mover.bookmarkTarget?.isReadOnlyRoot ?? false let write = mover.userCanWrite let sort = mover.userCanMutateProgeny let parent = mover.userCanMove switch type { case .eParent: valid = parent case .eChild: valid = sort case .eAlter: valid = write case .eColor: valid = canColor || write case .ePaste: valid = paste > 0 && write case .eUseGrabs: valid = wGrabs > 0 && write case .eMultiple: valid = grabs > 1 case .eSort: valid = (grabs > 1 && parent) || (shown && sort) case .eUndo: valid = undo.canUndo case .eRedo: valid = undo.canRedo case .eTravel: valid = mover.isTraveller case .eCloud: valid = gHasInternet && (gCloudStatusIsActive || gCloudStatusIsAvailable) default: break } } return valid } // MARK: - handlers // MARK: - @objc func handleMutateTextPopupMenu(_ iItem: ZMenuItem) { handleMutateTextKey(iItem.keyEquivalent) } @objc func handleMutateTextKey(_ key: String) { if let type = ZMutateTextMenuType(rawValue: key) { UNDO(self) { iUndoSelf in iUndoSelf.handleMutateTextKey(key) } gSelecting.simplifiedGrabs.applyMutator(type) gRelayoutMaps() } } @objc func handleTraitsPopupMenu(_ iItem: ZMenuItem) { handleTraitsKey(iItem.keyEquivalent) } @objc func handleTraitsKey(_ key: String) { if let type = ZTraitType(rawValue: key) { UNDO(self) { iUndoSelf in iUndoSelf.handleTraitsKey(key) } gTemporarilySetKey(key) editTraitForType(type) } } @objc func handleReorderPopupMenu(_ iItem: ZMenuItem) { gSelecting.simplifiedGrabs.sortAccordingToKey(iItem.keyEquivalent, iItem.keyEquivalentModifierMask == .shift) } func handleHyphen(_ COMMAND: Bool = false, _ OPTION: Bool = false) -> Bool { if COMMAND && OPTION { delete(preserveChildren: true, convertToTitledLine: true) } else if OPTION { return gSelecting.currentMoveable.convertToFromLine() } else if COMMAND { gUpdateBaseFontSize(up: false) } else { addDashedLine() } return true } func handleX(_ flags: ZEventFlags) -> Bool { if flags.hasCommand { delete(permanently: flags.hasOption) return true } return moveToDone() } func handleSlash(_ flags: ZEventFlags) -> Bool { // false means not handled here if !flags.isAnyMultiple { gFocusing.pushPopFavorite(flags, kind: .eSelected) return true } else if let controller = gHelpController { // should always succeed controller.show(flags: flags) return true } return false } func handleDelete(_ flags: ZEventFlags, _ isWindow: Bool) { let CONTROL = flags.hasControl let SPECIAL = flags.exactlySpecial let COMMAND = flags.hasCommand let OPTION = flags.hasOption let ANY = flags.isAny if CONTROL { gFocusing.grabAndFocusOn(gTrash) { gRelayoutMaps() } } else if OPTION || isWindow || COMMAND { delete(permanently: SPECIAL && isWindow, preserveChildren: ANY && isWindow, convertToTitledLine: SPECIAL) } } // MARK: - features // MARK: - func mapControl(_ OPTION: Bool) { if !OPTION { gMapController?.toggleMaps() } else if let root = gRecords.rootZone { gHere = root gHere.grab() } gRelayoutMaps() } func browseBreadcrumbs(_ out: Bool) { if let here = out ? gHere.parentZone : gBreadcrumbs.nextCrumb(false) { let last = gSelecting.currentMapGrabs gHere = here here.traverseAllProgeny { child in child.collapse() } gSelecting.grab(last) gSelecting.firstGrab()?.asssureIsVisible() gRelayoutMaps(for: here) } } func duplicate() { var grabs = gSelecting.simplifiedGrabs // convert to mutable, otherwise can't invoke duplicate grabs.duplicate() } func addDashedLine(onCompletion: Closure? = nil) { // three states: // 1) plain line -> insert and edit stub title // 2) titled line selected only -> convert back to plain line // 3) titled line is first of multiple -> convert titled line to plain title, selected, as parent of others let grabs = gSelecting.currentMapGrabs let isMultiple = grabs.count > 1 if let original = gSelecting.currentMoveableLine, let name = original.zoneName { let promoteToParent: ClosureClosure = { innerClosure in original.convertFromLineWithTitle() grabs.reversed().moveIntoAndGrab(original) { reveal in original.grab() innerClosure() onCompletion?() } } if name.contains(kLineOfDashes) { // ////////// // state 1 // // ////////// original.assignAndColorize(kLineWithStubTitle) // convert into a stub title if !isMultiple { original.editAndSelect(range: NSMakeRange(12, 1)) // edit selecting stub } else { promoteToParent { original.edit() } } return } else if name.isLineWithTitle { if !isMultiple { // ////////// // state 2 // // ////////// original.assignAndColorize(kLineOfDashes) } else { // ////////// // state 3 // // ////////// promoteToParent {} } return } } gSelecting.rootMostMoveable?.addNext(with: kLineOfDashes) { iChild in iChild.grab() onCompletion?() } } func showMutateTextPopup() { if let widget = gSelecting.currentMoveable.widget?.textWidget { let menu = ZMenu.mutateTextPopup(target: self, action: #selector(handleMutateTextPopupMenu(_:))) let point = CGPoint(x: -30.0, y: 30.0) menu.popUp(positioning: nil, at: point, in: widget) } } func showTraitsPopup() { applyToMenu { return ZMenu .traitsPopup(target: self, action: #selector(handleTraitsPopupMenu(_:))) } } func showReorderPopup() { applyToMenu { return ZMenu.reorderPopup(target: self, action: #selector(handleReorderPopupMenu(_:))) } } func applyToMenu(_ createMenu: ToMenuClosure) { if let widget = gSelecting.lastGrab.widget?.textWidget { var point = widget.bounds.bottomRight point = widget.convert(point, to: gMapView).offsetBy(-160.0, -20.0) createMenu().popUp(positioning: nil, at: point, in: gMapView) } } func commaAndPeriod(_ COMMAND: Bool, _ OPTION: Bool, with COMMA: Bool) { if !COMMAND || (OPTION && COMMA) { toggleGrowthAndConfinementModes(changesDirection: COMMA) if gIsEditIdeaMode && COMMA { swapAndResumeEdit() } gSignal([.spMain, .sDetails, .spBigMap]) } else if COMMA { gDetailsController?.displayPreferences() } else if gIsEditIdeaMode { gTextEditor.cancel() } } func toggleColorized() { for zone in gSelecting.currentMapGrabs { zone.toggleColorized() } gRelayoutMaps() } func grabDuplicatesAndRedraw() { if let zones = gSelecting.currentMapGrabs.forDetectingDuplicates { gSelecting.ungrabAll() if zones.grabDuplicates() { gRelayoutMaps() } } } func prefix(with iMark: String, withParentheses: Bool = true) { let before = withParentheses ? "(" : kEmpty let after = withParentheses ? ") " : kSpace let zones = gSelecting.currentMapGrabs var digit = 0 let count = iMark == "#" for zone in zones { if var name = zone.zoneName { var prefix = before + iMark + after var add = true digit += 1 if name.starts(with: prefix) { let nameParts = name.components(separatedBy: prefix) name = nameParts[1] // remove prefix } else { if withParentheses, name.starts(with: before) { let nameParts = name.components(separatedBy: after) var index = 0 while index < nameParts.count - 1 { let mark = nameParts[index] // found: "(m" let markParts = mark.components(separatedBy: before) // markParts[1] == m index += 1 if markParts.count > 1 && markParts[0].count == 0 { let part = markParts[1] if part.count <= 2 && part.isDigit { add = false break } } } name = nameParts[index] // remove all (m) where m is any character } if add { if count { prefix = before + "\(digit)" + after // increment prefix } name = prefix + name // replace or prepend with prefix } } zone.zoneName = name gTextEditor.updateText(inZone: zone)?.updateBookmarkAssociates() } } gRelayoutMaps() } func divideChildren() { let grabs = gSelecting.currentMapGrabs for zone in grabs { zone.divideEvenly() } gRelayoutMaps() } func rotateWritable() { for zone in gSelecting.currentMapGrabs { zone.rotateWritable() } gRelayoutMaps() } func alterCase(up: Bool) { for grab in gSelecting.currentMapGrabs { if let tWidget = grab.widget?.textWidget { tWidget.alterCase(up: up) } } } func debugAnalyze() { var count = 0 for cloud in gRemoteStorage.allClouds { cloud.applyToAllOrphans { zone in print("orphan: \(zone)") count += 1 } } print(" total: \(count)") } func reverseWordsInZoneName() { let zone = gSelecting.currentMoveable if zone.reverseWordsInZoneName() { gRelayoutMaps(for: zone) } } // MARK: - edit text // MARK: - func editIdea(_ OPTION: Bool) { gSelecting.currentMoveable.edit() if OPTION { gTextEditor.placeCursorAtEnd() } } func editTraitForType(_ type: ZTraitType) { gSelecting.firstSortedGrab?.editTraitForType(type) } func editNote(flags: ZEventFlags?, useGrabbed: Bool = true) { gSelecting.firstGrab()?.editNote(flags: flags, useGrabbed: useGrabbed) } // MARK: - parents // MARK: - func swapWithParent() { if gSelecting.currentMapGrabs.count == 1, let zone = gSelecting.firstSortedGrab { zone.swapWithParent { gRelayoutMaps(for: zone) } } } func swapAndResumeEdit() { let t = gTextEditor // ////////////////////////////////////////////////////////// // swap currently editing zone with sibling, resuming edit // // ////////////////////////////////////////////////////////// if let zone = t.currentlyEditedZone, zone.hasSiblings { let upward = gListGrowthMode == .up let select = t.selectedRange t.stopCurrentEdit(forceCapture: true) zone.ungrab() gCurrentBrowseLevel = zone.level // so cousin list will not be empty moveUp(upward, [zone], selectionOnly: false, extreme: false, growSelection: false, targeting: nil) { kind in t.edit(zone) t.selectedRange = select } } } // MARK: - cut and paste // MARK: - func prepareUndoForDelete() { gSelecting.clearPaste() UNDO(self) { iUndoSelf in iUndoSelf.undoDelete() } } func undoDelete() { gSelecting.ungrabAll() for (child, (parent, index)) in gSelecting.pasteableZones { child.orphan() parent?.addChildAndUpdateOrder(child, at: index) child.addToGrabs() } gSelecting.clearPaste() UNDO(self) { iUndoSelf in iUndoSelf.delete() } gRelayoutMaps() } func preserveChildrenOfGrabbedZones(convertToTitledLine: Bool = false, onCompletion: Closure?) { let grabs = gSelecting.simplifiedGrabs let candidate = gSelecting.rootMostMoveable if grabs.count > 1 && convertToTitledLine { addDashedLine { onCompletion?() } return } for grab in grabs { grab.expand() } if let parent = candidate?.parentZone { let siblingIndex = candidate?.siblingIndex var children = ZoneArray () gSelecting.clearPaste() gSelecting.currentMapGrabs = [] for grab in grabs { if !convertToTitledLine { // delete, add to paste grab.addToPaste() grab.moveZone(to: grab.trashZone) } else { grab.addToGrabs() if let name = grab.zoneName, !name.contains(kHalfLineOfDashes) { // convert to titled line and insert above grab.convertToTitledLine() children.append(grab) } } for child in grab.children { children.append(child) child.addToGrabs() } } for child in children.reversed() { child.orphan() parent.addChildAndUpdateOrder(child, at: siblingIndex) } UNDO(self) { iUndoSelf in iUndoSelf.prepareUndoForDelete() children .deleteZones(iShouldGrab: false) {} iUndoSelf.pasteInto(parent, honorFormerParents: true) } } onCompletion?() } func delete(permanently: Bool = false, preserveChildren: Bool = false, convertToTitledLine: Bool = false) { if preserveChildren && !permanently { preserveChildrenOfGrabbedZones(convertToTitledLine: convertToTitledLine) { gFavorites.updateFavoritesAndRedraw(needsRedraw: false) { FOREGROUND(after: 0.05) { gRelayoutMaps() } } } } else if let grab = gSelecting.rootMostMoveable { let inSmall = grab.isInFavorites // these three values let parent = grab.parentZone // are out of date let index = grab.siblingIndex // after delete zones, below prepareUndoForDelete() gSelecting.simplifiedGrabs.deleteZones(permanently: permanently) { if inSmall, let i = index, let p = parent { let c = p.count if c == 0 || c <= i { // no more siblings if p.isInFavorites { gFavorites.updateAllFavorites() } else if c == 0 { ZBookmarks.newOrExistingBookmark(targeting: gHere, addTo: gFavoritesHere) // assure at least one bookmark in recents (targeting here) if p.isInBigMap { gHere.grab() // as though user clicked on background } } } else { let z = p.children[i] z.grab() } } gRelayoutMaps() } } } func paste() { pasteInto(gSelecting.firstSortedGrab) } func pasteInto(_ iZone: Zone? = nil, honorFormerParents: Bool = false) { let pastables = gSelecting.pasteableZones if pastables.count > 0, let zone = iZone { let isBookmark = zone.isBookmark let action = { [self] in var forUndo = ZoneArray () gSelecting.ungrabAll() for (pastable, (parent, index)) in pastables { let pasteMe = pastable.isInTrash ? pastable : pastable.deepCopy(dbID: nil) // for zones not in trash, paste a deep copy let insertAt = index != nil ? index : gListsGrowDown ? nil : 0 let into = parent != nil ? honorFormerParents ? parent! : zone : zone pasteMe.orphan() into.expand() into.addChildAndUpdateOrder(pasteMe, at: insertAt) pasteMe.recursivelyApplyDatabaseID(into.databaseID) forUndo.append(pasteMe) pasteMe.addToGrabs() } UNDO(self) { iUndoSelf in iUndoSelf.prepareUndoForDelete() forUndo.deleteZones(iShouldGrab: false, onCompletion: nil) zone.grab() gRelayoutMaps() } if isBookmark, undoManager.groupingLevel > 0 { undoManager.endUndoGrouping() } gFavorites.updateFavoritesAndRedraw() } if !isBookmark { action() } else { undoManager.beginUndoGrouping() zone.focusOnBookmarkTarget() { (iAny, iSignalKind) in action() } } } } // MARK: - move vertically // MARK: - func moveToDone() -> Bool { if let zone = gSelecting.rootMostMoveable, let parent = zone.parentZone { let grabs = gSelecting.currentMapGrabs var done = zone.visibleDoneZone if done == nil { done = Zone.uniqueZone(recordName: nil, in: parent.databaseID) done?.zoneName = kDone done?.moveZone(to: parent) } for zone in grabs { zone.orphan() } grabs.moveIntoAndGrab(done!) { good in done?.grab() gRelayoutMaps() } return true } return false } func moveUp(_ up: Bool, flags: ZEventFlags) { let COMMAND = flags.hasCommand let OPTION = flags.hasOption let SHIFT = flags.hasShift moveUp(up, selectionOnly: !OPTION, extreme: COMMAND, growSelection: SHIFT) } func moveUp(_ up: Bool = true, selectionOnly: Bool = true, extreme: Bool = false, growSelection: Bool = false, targeting iOffset: CGFloat? = nil) { priorHere = gHere if let grabs = moveables { moveUp(up, grabs, selectionOnly: selectionOnly, extreme: extreme, growSelection: growSelection, targeting: iOffset) { kinds in gSignal(kinds) } } } func moveUp(_ up: Bool = true, _ originalGrabs: ZoneArray, selectionOnly: Bool = true, extreme: Bool = false, growSelection: Bool = false, targeting iOffset: CGFloat? = nil, forcedResponse: ZSignalKindArray? = nil, onCompletion: SignalArrayClosure? = nil) { let minimalResponse : ZSignalKindArray = [.spDataDetails, .spCrumbs, .sToolTips] var response = forcedResponse ?? [ZSignalKind.spRelayout] let doCousinJump = !gBrowsingIsConfined let hereIsGrabbed = gHereMaybe != nil && originalGrabs.contains(gHereMaybe!) guard let rootMost = originalGrabs.rootMost(goingUp: up) else { onCompletion?([.sData]) return } let rootMostParent = rootMost.parentZone if hereIsGrabbed { if rootMost.isARoot { onCompletion?([.sData]) } else { // //////////////////////// // parent is not visible // // //////////////////////// let snapshot = gSelecting.snapshot let hasSiblings = rootMost.hasSiblings rootMost.revealParentAndSiblings() let recurse = hasSiblings && snapshot.isSame && (rootMostParent != nil) if let parent = rootMostParent { gHere = parent if recurse { if !hereIsGrabbed { response = minimalResponse } gSelecting.updateCousinList() moveUp(up, originalGrabs, selectionOnly: selectionOnly, extreme: extreme, growSelection: growSelection, targeting: iOffset, forcedResponse: response, onCompletion: onCompletion) } else { gFavorites.updateAllFavorites() onCompletion?([.spRelayout]) } } } } else if let parent = rootMostParent { let targetZones = doCousinJump ? gSelecting.cousinList : parent.children // FUBAR : cousin list is empty let targetCount = targetZones.count let targetMax = targetCount - 1 // //////////////////// // parent is visible // // //////////////////// if let index = targetZones.firstIndex(of: rootMost) { var toIndex = index + (up ? -1 : 1) // TODO: need to account for essay mode when not all children are visible var allGrabbed = true var soloGrabbed = false var hasGrab = false let moveClosure: ZonesClosure = { iZones in if extreme { toIndex = up ? 0 : targetMax } var moveUp = up if !extreme { // /////////////////////// // vertical wrap around // // /////////////////////// if toIndex > targetMax { toIndex = 0 moveUp = !moveUp } else if toIndex < 0 { toIndex = targetMax moveUp = !moveUp } } let indexer = targetZones[toIndex] if let intoParent = indexer.parentZone { let newIndex = indexer.siblingIndex let moveThese = moveUp ? iZones.reversed() : iZones moveThese.moveIntoAndGrab(intoParent, at: newIndex, orphan: true) { reveal in gSelecting.grab(moveThese) intoParent.children.updateOrder() onCompletion?([.spRelayout]) } } } // ////////////////////////////////// // detect grab for extend behavior // // ////////////////////////////////// for child in targetZones { if !child.isGrabbed { allGrabbed = false } else if hasGrab { soloGrabbed = false } else { hasGrab = true soloGrabbed = true } } // /////////////////////// // vertical wrap around // // /////////////////////// if !growSelection { let aboveTop = toIndex < 0 let belowBottom = toIndex >= targetCount // /////////////////////// // vertical wrap around // // /////////////////////// if (!up && (allGrabbed || extreme || (!allGrabbed && !soloGrabbed && belowBottom))) || ( up && soloGrabbed && aboveTop) { toIndex = targetMax // bottom } else if ( up && (allGrabbed || extreme || (!allGrabbed && !soloGrabbed && aboveTop))) || (!up && soloGrabbed && belowBottom) { toIndex = 0 // top } } if toIndex >= 0 && toIndex < targetCount { var grabThis = targetZones[toIndex] // ////////////////////////// // no vertical wrap around // // ////////////////////////// UNDO(self) { iUndoSelf in iUndoSelf.moveUp(!up, selectionOnly: selectionOnly, extreme: extreme, growSelection: growSelection) } if !selectionOnly { moveClosure(originalGrabs) } else if !growSelection { findChildMatching(&grabThis, up, iOffset) // TODO: should look at siblings, not children grabThis.grab(updateBrowsingLevel: false) if !hereIsGrabbed && forcedResponse == nil { response = minimalResponse } } else if !grabThis.isGrabbed || extreme { var grabThese = [grabThis] if extreme { // //////////////// // expand to end // // //////////////// if up { for i in 0 ..< toIndex { grabThese.append(targetZones[i]) } } else { for i in toIndex ..< targetCount { grabThese.append(targetZones[i]) } } } gSelecting.addMultipleGrabs(grabThese) if !hereIsGrabbed && forcedResponse == nil { response = minimalResponse } } } else if doCousinJump, var index = targetZones.firstIndex(of: rootMost) { // ////////////// // cousin jump // // ////////////// index += (up ? -1 : 1) if index >= targetCount { index = growSelection ? targetMax : 0 } else if index < 0 { index = growSelection ? 0 : targetMax } var grab = targetZones[index] findChildMatching(&grab, up, iOffset) if !selectionOnly { moveClosure(originalGrabs) } else if growSelection { grab.addToGrabs() } else { grab.grab(updateBrowsingLevel: false) } } onCompletion?(response) } } } fileprivate func findChildMatching(_ grabThis: inout Zone, _ up: Bool, _ iOffset: CGFloat?) { // /////////////////////////////////////////////////////////// // IF text is being edited by user, grab another zone whose // // text contains offset // // else whose // // level equals gCurrentBrowsingLevel // // /////////////////////////////////////////////////////////// while grabThis.hasVisibleChildren, let length = grabThis.zoneName?.length { let range = NSRange(location: length, length: 0) let index = up ? grabThis.count - 1 : 0 let child = grabThis.children[index] if let offset = iOffset, let anOffset = grabThis.widget?.textWidget?.offset(for: range, up), offset > anOffset + 25.0 { // half the distance from end of parent's text field to beginning of child's text field grabThis = child } else if let level = gCurrentBrowseLevel, child.level == level { grabThis = child } else { break // done } } } // MARK: - move horizontally // MARK: - func moveLeft(_ out: Bool, flags: ZEventFlags, onCompletion: Closure? = nil) { if let moveable = gSelecting.rootMostMoveable { let COMMAND = flags.hasCommand let OPTION = flags.hasOption let SHIFT = flags.hasShift if OPTION, !moveable.canRelocateInOrOut { return } if !SHIFT || moveable.isInFavorites { move(out: out, selectionOnly: !OPTION, extreme: COMMAND) { neededReveal in gSelecting.updateAfterMove(!OPTION, needsRedraw: neededReveal) // relayout map when travelling through a bookmark onCompletion?() // invoke closure from essay editor } } else { // /////////////// // GENERATIONAL // // /////////////// if OPTION { browseBreadcrumbs(out) } else { gSelecting.currentMapGrabs.applyGenerationally(!out, extreme: COMMAND) } } } } func moveOut(selectionOnly: Bool = true, extreme: Bool = false, force: Bool = false, onCompletion: BoolClosure?) { if let zone: Zone = moveables?.first, !zone.isARoot { if selectionOnly { // ///////////////// // MOVE SELECTION // // ///////////////// zone.moveSelectionOut(extreme: extreme, onCompletion: onCompletion) return } else if let p = zone.parentZone, !p.isARoot { // //////////// // MOVE ZONE // // //////////// let grandParentZone = p.parentZone if zone == gHere && !force { let grandParentName = grandParentZone?.zoneName let parenthetical = grandParentName == nil ? kEmpty : " (\(grandParentName!))" // ///////////////////////////////////////////////////////////////////// // present an alert asking if user really wants to move here leftward // // ///////////////////////////////////////////////////////////////////// gAlerts.showAlert("WARNING", "This will relocate \"\(zone.zoneName ?? kEmpty)\" to its parent's parent\(parenthetical)", "Relocate", "Cancel") { [self] iStatus in if iStatus == .sYes { moveOut(selectionOnly: selectionOnly, extreme: extreme, force: true, onCompletion: onCompletion) } } } else { let moveOutToHere = { [self] (iHere: Zone?) in if let here = iHere { gHere = here moveOut(to: here, onCompletion: onCompletion) } } if extreme { if gHere.isARoot { moveOut(to: gHere, onCompletion: onCompletion) } else { zone.revealZonesToRoot() { moveOutToHere(gRoot) onCompletion?(true) } return } } else if let gp = grandParentZone { let inSmallMap = p.isInFavorites if inSmallMap { p.collapse() } if !gIsEssayMode { p.revealParentAndSiblings() } if gp.isProgenyOf(gHere) || gp == gHere { moveOut(to: gp, onCompletion: onCompletion) return } else if inSmallMap { moveOut(to: gp) { reveal in zone.grab() gFavorites.setHere(to: gp) onCompletion?(reveal) } return } else { moveOutToHere(gp) } } } } onCompletion?(true) } onCompletion?(false) } func move(out: Bool, selectionOnly: Bool = true, extreme: Bool = false, onCompletion: BoolClosure?) { if out { moveOut (selectionOnly: selectionOnly, extreme: extreme, onCompletion: onCompletion) } else { moveInto(selectionOnly: selectionOnly, extreme: extreme, onCompletion: onCompletion) } } func moveInto(selectionOnly: Bool = true, extreme: Bool = false, onCompletion: BoolClosure?) { if selectionOnly { moveables?.first?.browseRight(extreme: extreme, onCompletion: onCompletion) } else { moveables?.actuallyMoveInto(onCompletion: onCompletion) } } func moveOut(to into: Zone, onCompletion: BoolClosure?) { if let zones = moveables?.reversed() as ZoneArray? { var completedYet = false zones.recursivelyRevealSiblings(untilReaching: into) { [self] iRevealedZone in if !completedYet && iRevealedZone == into { completedYet = true for zone in zones { var insert: Int? = zone.parentZone?.siblingIndex // first compute insertion index if zone.parentZone?.parentZone == into, let i = insert { insert = i + 1 if insert! >= into.count { insert = nil // append at end } } if let from = zone.parentZone { let index = zone.siblingIndex UNDO(self) { iUndoSelf in zone.moveZone(into: from, at: index, orphan: true) { onCompletion?(true) } } } zone.orphan() into.addChildAndUpdateOrder(zone, at: insert) } onCompletion?(true) } } } } }
// // TableView.swift // Imovies // // Created by Khaled Bohout on 3/25/19. // Copyright © 2019 Khaled Bohout. All rights reserved. // import UIKit class TableView: UITableViewController { var movie : Movie! @IBOutlet weak var headernamelbl: UILabel! @IBOutlet weak var movieposterimg: UIImageView! @IBOutlet weak var movietitlelbl: UILabel! @IBOutlet weak var movieyearlbl: UILabel! @IBOutlet weak var movieratedlbl: UILabel! @IBOutlet weak var movirreleaseddate: UILabel! @IBOutlet weak var movieruntimelbl: UILabel! @IBOutlet weak var moviegenrelbl: UILabel! @IBOutlet weak var moviedirectorlbl: UILabel! @IBOutlet weak var moviewriterlbl: UILabel! @IBOutlet weak var movieactorslbl: UILabel! @IBOutlet weak var movieplotslbl: UILabel! @IBOutlet weak var movielanguagelbl: UILabel! @IBOutlet weak var moviecountrylbl: UILabel! @IBOutlet weak var movieawardslbl: UILabel! @IBOutlet weak var moviemetascore: UILabel! @IBOutlet weak var imdbratinglbl: UILabel! @IBOutlet weak var imdbvoteslbl: UILabel! @IBOutlet weak var totalseasonslbl: UILabel! @IBOutlet weak var boxofficelbl: UILabel! @IBOutlet weak var productionlbl: UILabel! @IBOutlet weak var ratingsourcelbl: UILabel! @IBOutlet weak var ratingvalue: UILabel! @IBOutlet weak var rating2source: UILabel! @IBOutlet weak var rating2value: UILabel! @IBOutlet weak var rating3source: UILabel! @IBOutlet weak var rating3value: UILabel! override func viewDidLoad() { super.viewDidLoad() self.headernamelbl.text = movie.movietitle self.movietitlelbl.text = movie.movietitle self.movieyearlbl.text = movie.movieyear self.movieratedlbl.text = movie.movierated self.movirreleaseddate.text = movie.moviereleaseddate self.movieruntimelbl.text = movie.movieruntime self.moviegenrelbl.text = movie.moviegenre self.moviedirectorlbl.text = movie.moviedirector self.moviewriterlbl.text = movie.moviewriter self.movieactorslbl.text = movie.movieactors self.movieplotslbl.text = movie.movieplots self.movielanguagelbl.text = movie.movielanguage self.moviecountrylbl.text = movie.moviecountry self.movieawardslbl.text = movie.movieawards self.moviemetascore.text = movie.moviemetascore self.imdbratinglbl.text = movie.imdbrating self.imdbvoteslbl.text = movie.imdbvotes self.totalseasonslbl.text = movie.totalseasons self.boxofficelbl.text = movie.boxoffice self.productionlbl.text = movie.production if let url = URL(string: movie.posterimgurl){ let data = try? Data(contentsOf: url) self.movieposterimg.image = UIImage(data: data!) } } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if section == 0 { return movie.type } else{ return "rating" } } @IBAction func backbtntapped(_ sender: Any) { self.dismiss(animated: false, completion: nil) } }
// // FirstViewController.swift // Contest // // Created by Souley on 17/01/2019. // Copyright © 2019 Souley. All rights reserved. // import UIKit class FirstViewController: UIViewController { let secondViewController = SecondViewController() let enterEmailLabel: UILabel = { let label = UILabel() label.text = "Please Enter Your Email Address" label.font = .boldSystemFont(ofSize: 20) label.textColor = .white label.translatesAutoresizingMaskIntoConstraints = false return label }() let emailEntryTextField: UITextField = { let textField = UITextField() textField.placeholder = "Email Address" textField.backgroundColor = .white textField.clipsToBounds = true textField.translatesAutoresizingMaskIntoConstraints = false return textField }() let sumbitEmailAddressButton: UIButton = { let button = UIButton() button.setTitle("Submit", for: .normal) button.backgroundColor = .white button.setTitleColor(.purple, for: .normal) button.layer.cornerRadius = 15 button.clipsToBounds = true button.translatesAutoresizingMaskIntoConstraints = false return button }() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .purple setupLayout() setupActions() } @objc func submitButtonTapped() { if emailEntryTextField.text?.isEmpty == true { UIView.animate(withDuration: 0.25, animations: { self.emailEntryTextField.transform = CGAffineTransform(translationX: -10, y: 0) self.emailEntryTextField.transform = CGAffineTransform(translationX: 10, y: 0) }) { (_) in self.emailEntryTextField.transform = CGAffineTransform.identity } } else { show(secondViewController, sender: self) } } func setupActions() { sumbitEmailAddressButton.addTarget(self, action: #selector(submitButtonTapped), for: .touchUpInside) } func setupLayout() { let safeArea = view.safeAreaLayoutGuide view.addSubview(enterEmailLabel) view.addSubview(emailEntryTextField) view.addSubview(sumbitEmailAddressButton) enterEmailLabel.centerXAnchor.constraint(equalTo: safeArea.centerXAnchor).isActive = true enterEmailLabel.centerYAnchor.constraint(equalTo: safeArea.centerYAnchor, constant: -30).isActive = true emailEntryTextField.topAnchor.constraint(equalTo: enterEmailLabel.bottomAnchor, constant: 20).isActive = true emailEntryTextField.leadingAnchor.constraint(equalTo: safeArea.leadingAnchor, constant: 30).isActive = true emailEntryTextField.trailingAnchor.constraint(equalTo: safeArea.trailingAnchor, constant: -30).isActive = true emailEntryTextField.heightAnchor.constraint(equalToConstant: 30).isActive = true sumbitEmailAddressButton.topAnchor.constraint(equalTo: emailEntryTextField.bottomAnchor, constant: 20).isActive = true sumbitEmailAddressButton.leadingAnchor.constraint(equalTo: safeArea.leadingAnchor, constant: 50).isActive = true sumbitEmailAddressButton.trailingAnchor.constraint(equalTo: safeArea.trailingAnchor, constant: -50).isActive = true sumbitEmailAddressButton.heightAnchor.constraint(equalToConstant: 30).isActive = true } }
// // Constants.swift // City Sights App // // Created by Marco Lau on 25/08/2021. // import Foundation struct Constants { static var apiKey = "9lZ0gZqYI6BsDYSDjXTAbbDLpG6pDiMw9y9KlwRLx9NQtKIm3v-BH9N9T7j3id-rU0pSdZ4Ea1hTjzyOY8mK3T8tc4Jt5mWFQaNs_fPx7bjNcswRlL5Tw9AiYK4lYXYx" static var yelpSearchURL = "https://api.yelp.com/v3/businesses/search" static var yelpSearchHTTPMethod = "GET" static var restaurantKey = "restaurants" static var sightsKey = "arts" static var reusableAnnotationId = "business" }
// // InternalNotificationManager.swift // TearBud // // Created by Michael Rose on 12/1/16. // Copyright © 2016 Path Finder. All rights reserved. // import UIKit /* Managages views that confirm to the InternalNotification protocol and displays them on screen */ class InternalNotificationManager { static let shared = InternalNotificationManager() fileprivate var notificationWindow: UIWindow! fileprivate var notificationViewController: InternalNotificationViewController! fileprivate var queue = [InternalNotificationView]() fileprivate var sortedQueue: [InternalNotificationView] { return queue.sorted { $0.priority.rawValue == $1.priority.rawValue ? $0.dateCreated < $1.dateCreated : $0.priority.rawValue > $1.priority.rawValue } } fileprivate var notificationProcessRunning = false // We want the internal notification bar to be slightly taller than the status bar fileprivate let statusBarHeightOffset: CGFloat = 0 fileprivate init() { // Register for status bar frame changes NotificationCenter.default.addObserver(self, selector: #selector(statusBarFrameWillChange), name: Notification.Name.UIApplicationWillChangeStatusBarFrame, object: nil) // Current status bar height let statusBarHeight = UIApplication.shared.statusBarFrame.size.height let notificationBarHeight = statusBarHeight + statusBarHeightOffset // Init Notification Window notificationWindow = UIWindow(frame: CGRect(x: 0, y: -notificationBarHeight, width: UIScreen.main.bounds.width, height: notificationBarHeight)) notificationWindow.windowLevel = UIWindowLevelStatusBar + 1 notificationWindow.backgroundColor = UIColor.clear notificationWindow.isHidden = true // Init Notification View Controller notificationViewController = InternalNotificationViewController() notificationWindow.rootViewController = notificationViewController } deinit { // Clear queue clearQueue() // Unregister for status bar frame changes NotificationCenter.default.removeObserver(self, name: Notification.Name.UIApplicationWillChangeStatusBarFrame, object: nil) } // MARK: - Notifiation Management func queue(notification: InternalNotificationView) { // Add notification to the queue queue.append(notification) // Become delegate notification.delegate = self // Attempt to start notification dispaly process (could already be running) beginNotifcationProcess() } // MARK: - Internal // Starts to the process of running through the queue until it's empty fileprivate func beginNotifcationProcess() { // Check if the process is already running, or there are no notifications in the queue if notificationProcessRunning || queue.count <= 0 { return } // Set flag to true notificationProcessRunning = true // Show the notification bar showNotificationBar() // Load next notification loadNextNotification() } fileprivate func loadNextNotification() { if let notification = sortedQueue.first { // Add the notification to the notification view controller hierarchy for display notificationViewController.transitionToInternalNotificationView(toView: notification, completion: { (completed) in if completed { // Tell the notification it's about to be displayed notification.prepareForDisplay() } }) } else { endNotificationProcess() } } // Called when the queue is emptied fileprivate func endNotificationProcess() { // Set flag to false notificationProcessRunning = false // Clear queue clearQueue() // Clear notification view controller hierarchy notificationViewController.transitionToInternalNotificationView(toView: nil) // Hide the notificaiton bar hideNotificationBar() } fileprivate func clearQueue() { for notification in queue { notification.delegate = nil } queue.removeAll() } fileprivate func showNotificationBar() { notificationWindow.isHidden = false var frame = notificationWindow.frame frame.origin.y = 0 UIView.animate(withDuration: 0.35, delay: 0, options: .beginFromCurrentState, animations: { self.notificationWindow.frame = frame }) { (completed) in // } notificationViewController.showShadowView() } fileprivate func hideNotificationBar() { var frame = notificationWindow.frame frame.origin.y = -frame.size.height UIView.animate(withDuration: 0.35, delay: 0, options: .beginFromCurrentState, animations: { self.notificationWindow.frame = frame }) { (completed) in if completed { self.notificationWindow.isHidden = false } } notificationViewController.hideShadowView() } // MARK: - Application Notifications @objc func statusBarFrameWillChange(notification: Notification) { if let value = notification.userInfo?[UIApplicationStatusBarFrameUserInfoKey] as? NSValue { let statusBarHeight = value.cgRectValue.size.height let notificationBarHeight = statusBarHeight + statusBarHeightOffset var frame = notificationWindow.frame frame.size.height = notificationBarHeight UIView.animate(withDuration: 0.35, delay: 0, options: .beginFromCurrentState, animations: { self.notificationWindow.frame = frame self.notificationViewController.currentNotification?.layoutIfNeeded() }, completion: nil) } } } extension InternalNotificationManager: InternalNotificationViewDelegate { func userDidTapInternalNotificationView(notification: InternalNotificationView) { /* if appDelegate.rootViewController.presentedViewController == nil { let tearBudInfo = UIStoryboard(name: "TearBudInfo", bundle: nil).instantiateViewController(withIdentifier: "TearBudInfoViewController") let navigationController = UINavigationController(rootViewController: tearBudInfo) appDelegate.rootViewController.present(navigationController, animated: true, completion: nil) } */ } func internalNotificationViewDidFinish(notification: InternalNotificationView) { // Kill the finished notification (remove from queue, and clear delegate) notification.delegate = nil if let index = queue.index(of: notification) { queue.remove(at: index) } // If the complete notification is the current notification, then try to load the next notification // It is possible a notification will finish before it's even displayed (sync progress) if notification == notificationViewController.currentNotification { loadNextNotification() } } }
// // SharingGroupsController+MoveFileGroups.swift // Server // // Created by Christopher G Prince on 7/3/21. // import Foundation import ServerShared import LoggerAPI extension SharingGroupsController { func moveFileGroups(params:RequestProcessingParameters) { guard let requestWithData = params.request as? MoveFileGroupsRequest else { let message = "Did not receive MoveFileGroupsRequest" Log.error(message) params.completion(.failure(.message(message))) return } let request:MoveFileGroupsRequest do { request = try MoveFileGroupsRequest.decode(data: requestWithData.data) } catch let error { let message = "Could not decode MoveFileGroupsRequest from data: \(error)" Log.error(message) params.completion(.failure(.message(message))) return } guard let destinationSharingGroupUUID = request.destinationSharingGroupUUID, let sourceSharingGroupUUID = request.sourceSharingGroupUUID else { let message = "Could not get source or destination sharing group" Log.error(message) params.completion(.failure(.message(message))) return } // User must have permissions on the source and dest sharing groups. guard sharingGroupSecurityCheck(sharingGroupUUID: destinationSharingGroupUUID, params: params) else { let message = "Failed in sharing group security check: For dest sharing group" Log.error(message) params.completion(.failure(.message(message))) return } guard sourceSharingGroupUUID != destinationSharingGroupUUID else { let message = "The source sharing group is the same as the destination." Log.error(message) params.completion(.failure(.message(message))) return } guard sharingGroupSecurityCheck(sharingGroupUUID: sourceSharingGroupUUID, params: params) else { let message = "Failed in sharing group security check: For source sharing group" Log.error(message) params.completion(.failure(.message(message))) return } guard let userId = params.currentSignedInUser?.userId else { let message = "Could not get current signed in user." Log.error(message) params.completion(.failure(.message(message))) return } guard case .success = params.repos.sharingGroupUser.checkPermissions(userId: userId, sharingGroupUUID: sourceSharingGroupUUID, minPermission: .admin, sharingGroupRepo: params.repos.sharingGroup) else { let message = "User didn't have admin permission on source sharing group" Log.error(message) params.completion(.failure(.message(message))) return } guard case .success = params.repos.sharingGroupUser.checkPermissions(userId: userId, sharingGroupUUID: destinationSharingGroupUUID, minPermission: .admin, sharingGroupRepo: params.repos.sharingGroup) else { let message = "User didn't have admin permission on destination sharing group" Log.error(message) params.completion(.failure(.message(message))) return } guard let fileGroupUUIDs = request.fileGroupUUIDs, fileGroupUUIDs.count > 0 else { let message = "No file groups passed!" Log.error(message) params.completion(.failure(.message(message))) return } guard Set<String>(fileGroupUUIDs).count == fileGroupUUIDs.count else { let message = "Duplicate file group(s) passed." Log.error(message) params.completion(.failure(.message(message))) return } let userConstraintResult = checkUserConstraint(request: request, params: params) switch userConstraintResult { case .error: let message = "There was an error checking the user constraint." Log.error(message) params.completion(.failure(.message(message))) return case .notSatisfied: let message = "The user constraint was not satisfied." Log.debug(message) let response = MoveFileGroupsResponse() response.result = .failedWithUserConstraintNotSatisfied params.completion(.success(response)) return case .satisifed: break } guard let fileGroups = checkOwners(fileGroupUUIDs: fileGroupUUIDs, sourceSharingGroup: sourceSharingGroupUUID, destinationSharingGroup: destinationSharingGroupUUID, params: params) else { // `checkOwners` already did the completion. return } let deleted = fileGroups.filter { $0.deleted } guard deleted.count == 0 else { let message = "Some of the file groups in the attempted move were deleted." Log.error(message) params.completion(.failure(.message(message))) return } // Need to change the `sharingGroupUUID` field of each FileGroup in the database. guard params.repos.fileGroups.updateFileGroups(fileGroupUUIDs, sourceSharingGroupUUID: sourceSharingGroupUUID, destinationSharingGroupUUID: destinationSharingGroupUUID) else { let message = "Failed updating file groups to dest sharing group." Log.error(message) params.completion(.failure(.message(message))) return } let response = MoveFileGroupsResponse() response.result = .success params.completion(.success(response)) } } extension SharingGroupsController { // All of the file groups must be in the source sharing group, and // the v0 uploading user of all of the file groups (media items) to be moved must also have membership in the target/destination sharing group (album). // If nil is returned a return has been carried out using `params.completion`. // If non-nil is returned, these are the collection of `FileGroupModel`'s. corresponding to the passsed `fileGroupUUIDs`. private func checkOwners(fileGroupUUIDs: [String], sourceSharingGroup: String, destinationSharingGroup: String, params:RequestProcessingParameters) -> [FileGroupModel]? { let keys = fileGroupUUIDs.map { fileGroupUUID in FileGroupRepository.LookupKey.fileGroupUUID(fileGroupUUID: fileGroupUUID) } guard let fileGroups = params.repos.fileGroups.lookupAll(keys: keys, modelInit: FileGroupModel.init) else { let message = "Could not lookup FileGroupModel's" Log.error(message) params.completion(.failure(.message(message))) return nil } guard fileGroupUUIDs.count == fileGroups.count else { let message = "Did not find all file groups passed as parameter: parameter had \(fileGroupUUIDs.count) file groups; found: \(fileGroups.count) in db." Log.error(message) params.completion(.failure(.message(message))) return nil } // Make sure that all file groups are in the source sharing group let sourceFilter = fileGroups.filter { $0.sharingGroupUUID == sourceSharingGroup } guard sourceFilter.count == fileGroups.count else { let message = "Some of the file groups were not in the source sharing group." Log.error(message) params.completion(.failure(.message(message))) return nil } // Get all the unique uploading users from the file groups let uploadingUserIds = Set<UserId>(fileGroups.map { $0.userId }) let sharingGroupUserKeys = uploadingUserIds.map { uploadingUserIds in SharingGroupUserRepository.LookupKey.primaryKeys(sharingGroupUUID: destinationSharingGroup, userId: uploadingUserIds, deleted: nil) } guard let sharingGroupUsers = params.repos.sharingGroupUser.lookupAll(keys: sharingGroupUserKeys, modelInit: SharingGroupUser.init) else { let message = "Could not lookup SharingGroupUser's" Log.error(message) params.completion(.failure(.message(message))) return nil } guard uploadingUserIds.count == sharingGroupUsers.count else { let message = "Not all file group users were in the destination sharing group" Log.error(message) let response = MoveFileGroupsResponse() response.result = .failedWithNotAllOwnersInTarget params.completion(.success(response)) return nil } return fileGroups } enum UserConstraint { case satisifed case notSatisfied case error } // Constrain by `usersThatMustBeInDestination`. func checkUserConstraint(request:MoveFileGroupsRequest, params:RequestProcessingParameters) -> UserConstraint { guard let usersThatMustBeInDestination = request.usersThatMustBeInDestination else { Log.info("There was no usersThatMustBeInDestination field in request.") return .satisifed } guard let sourceUsers = params.repos.sharingGroupUser.usersInSharingGroup(sharingGroupUUID: request.sourceSharingGroupUUID) else { return .error } // See which users are still in the source sharing group. // Note that if for some reason there are invalid user id's in `usersThatMustBeInDestination` -- e.g., ids of users that just are not on the system, `usersInConstraint` will not have those users as they will not intersect with `sourceUsers`. let usersInConstraint = sourceUsers.intersection(usersThatMustBeInDestination) guard let destUsers = params.repos.sharingGroupUser.usersInSharingGroup(sharingGroupUUID: request.destinationSharingGroupUUID) else { return .error } guard destUsers.intersection(usersInConstraint).count == usersInConstraint.count else { return .notSatisfied } return .satisifed } }
// // MessageModel.swift // FIFA2018 // // Created by Mikhail Lutskiy on 14.04.2018. // Copyright © 2018 Mikhail Lutskii. All rights reserved. // import Foundation import RealmSwift import ObjectMapper class MessageModel : Object, Mappable { // @objc dynamic var id = 0 @objc dynamic var message = "" @objc dynamic var time: Date? @objc dynamic var uuid = "" @objc dynamic var countryId = 0 required convenience init?(map: Map) { self.init() } // override static func primaryKey() -> String? { // return "id" // } func mapping(map: Map) { // id <- map["id"] message <- map["message"] time <- map["time"] uuid <- map["uuid"] countryId <- map["country_id"] } }
// // Notification.swift // KifuSF // // Created by Alexandru Turcanu on 16/12/2018. // Copyright © 2018 Alexandru Turcanu. All rights reserved. // import Foundation import UIKit extension Notification { func getKeyboardHeight() -> CGFloat? { return (self.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue.height } }
// // DetailSetViewController.swift // CLEAN // // Created by eunjiev on 2018. 6. 2.. // Copyright © 2018년 clean. All rights reserved. // import Foundation import UIKit import UserNotifications class DetailSetViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, UITextViewDelegate, UITextFieldDelegate { @IBOutlet weak var start_picker: UIDatePicker! @IBOutlet weak var cycle_picker: UIPickerView! @IBOutlet weak var alarm_picker: UIPickerView! @IBOutlet weak var txt_memo: UITextView! @IBOutlet weak var label_cycle: UILabel! @IBOutlet weak var label_alarm: UILabel! @IBOutlet weak var label_start: UILabel! @IBOutlet weak var btn_done: UIBarButtonItem! let alarm_data = Constants.DetailSet.alarm_data let week = Constants.DetailSet.week let day = Constants.DetailSet.day let memo_place_holder = Constants.DetailSet.memo_place_holder let event_data = EventData() let event_info = EventInfo(valid: -1, eid: -1, sid: -1, ename: "", front_date: "", cycle: "", alarm: 0, memo: "") var offset = 0 var isInsert = false func init_space_holder (_ text: String?, _ textView: UITextView) { textView.text = text if text != nil { txt_memo.textColor = Constants.TextShow.space_holder_color } else { txt_memo.textColor = Constants.TextShow.text_color } } @IBAction func alarmStart() { CreateNotice() } func CreateNotice() { let content = UNMutableNotificationContent() content.title = "청소지역(화장실) 해당청소(변기)" //content.subtitle = "Too hard" content.body = "청소해야돼 or 청소했니?" content.sound = UNNotificationSound.default() content.badge = 1 content.categoryIdentifier = "selectCategory" // 버튼 클릭 후에 홈으로 나갔을 때 5초뒤에 알람 나오는것, 시간차이를 이용해서 알람내고싶을때 이거 사용 // let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5.0, repeats: false) // 년,월,일 까지 받음 let date = start_picker.date var triggerDate = Calendar.current.dateComponents([.year,.month,.day,], from: date) // 해당 날짜의 알람 울릴 시각 설정 triggerDate.hour = 14 triggerDate.minute = 16 triggerDate.second = 0 let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDate, repeats: false) let requestIdentifier = "requset Identifier" let request = UNNotificationRequest(identifier: requestIdentifier, content: content, trigger: trigger) //foreground 에서도 작동하기위해 추가한것중하나 as 추가 UNUserNotificationCenter.current().delegate = self as UNUserNotificationCenterDelegate UNUserNotificationCenter.current().add(request) { (error) in print(error as Any) } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. alarm_picker.delegate = self alarm_picker.dataSource = self cycle_picker.delegate = self cycle_picker.dataSource = self let now = Date() let formmater = DateFormatter() let format: String = "yyyy-MM-dd" btn_done.title = Constants.Button.done UNUserNotificationCenter.current().delegate = self as UNUserNotificationCenterDelegate txt_memo.text = String(offset) event_data.find_event(event_id: offset, get_data: event_info) formmater.dateFormat = format event_info.front_date = formmater.string(from: now as Date) event_info.debug() //event_info.cycle = "0/0" print(isInsert) //navigationController?.title = String(offset) self.navigationItem.title = cleanArray[CleanObjects(rawValue: offset) ?? .floor]?.name ?? String(offset) print("offset: " + String(offset)) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) init_space_holder(memo_place_holder, txt_memo) txt_memo.delegate = self } @IBAction func btn_done(_ sender: Any) { print("haha") if(event_info.valid == 0){ event_info.valid = 1 } print("\n\n\n\n\n\nbtn_done\n\n\nn\n\n") event_info.memo = txt_memo.text event_info.eid = offset if offset == 00 { event_info.ename = "쇼파" } else if offset == 01{ event_info.ename = "바닥" } else if offset == 10{ event_info.ename = "전자레인지" } else if offset == 11{ event_info.ename = "바닥" } else if offset == 20{ event_info.ename = "욕실" } else if offset == 21{ event_info.ename = "세면대" } else if offset == 22{ event_info.ename = "바닥" } else if offset == 23{ event_info.ename = "변기" } else if offset == 30{ event_info.ename = "침대" } else if offset == 31{ event_info.ename = "바닥" } else if offset == 40{ event_info.ename = "침대" } else if offset == 41{ event_info.ename = "바닥" } else if offset == 50{ event_info.ename = "침대" } else if offset == 51{ event_info.ename = "바닥" } else if offset == 60{ event_info.ename = "옷장" } else if offset == 61{ event_info.ename = "바닥" } else if offset == 70{ event_info.ename = "TV" } else if offset == 71{ event_info.ename = "컴퓨터" } else if offset == 72{ event_info.ename = "드라이기" } event_data.undate_event(get_data: event_info) event_info.debug() event_data.debug() let alert = UIAlertController(title: "알림", message: "저장 되었습니다.", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "확인", style: .default, handler: { action in self.navigationController?.popViewController(animated: true) })) self.present(alert, animated: true) // let vc = self.storyboard?.instantiateViewController(withIdentifier: "MainBoard") // vc?.modalTransitionStyle = UIModalTransitionStyle.coverVertical // self.present(vc!, animated: true, completion: nil) // if let uvc = self.storyboard?.instantiateViewController(withIdentifier: "MainBoard") { // uvc.modalTransitionStyle = UIModalTransitionStyle.coverVertical // // 인자값으로 받은 뷰 컨트롤러로 화면 // self.present(uvc, animated: true, completion: nil) // } if let vc = UIStoryboard.init(name: "Calendar", bundle: nil).instantiateInitialViewController() as? DetailSetViewController { self.navigationController?.pushViewController(vc, animated: true) } } func textViewDidBeginEditing(_ textView: UITextView) { if txt_memo.textColor == UIColor.lightGray { init_space_holder( nil, txt_memo) } } func textViewDidEndEditing(_ textView: UITextView) { if txt_memo.text.isEmpty { init_space_holder(memo_place_holder, txt_memo) } } func textFieldDidBeginEditing(_ textField: UITextField) { if txt_memo.textColor == UIColor.lightGray { init_space_holder(nil, txt_memo) } } func textFieldDidEndEditing(_ textField: UITextField) { if (txt_memo.text?.isEmpty)! { init_space_holder(memo_place_holder, txt_memo) } } @IBAction func date_picker_changed(_ sender: UIDatePicker) { let formatter = DateFormatter() formatter.dateFormat = Constants.DetailSet.date_format label_start.text = "시작일: " + formatter.string(from: start_picker.date) event_info.front_date = formatter.string(from: start_picker.date) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func numberOfComponents(in pickerView: UIPickerView) -> Int { if pickerView == cycle_picker{ return Constants.DetailSet.cycle_picker_num } else{ return Constants.DetailSet.alarm_picker_num } } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { if pickerView == cycle_picker { if component == 0 { return week.count } else { return day.count } } else { return alarm_data.count } } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { if(pickerView == cycle_picker){ if component == 0 { return week[row] } else { return day[row] } } else { return alarm_data[row] } } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { if pickerView == cycle_picker { label_cycle.text = "주기: \(week[pickerView.selectedRow(inComponent: 0)])주 \(day[pickerView.selectedRow(inComponent: 1)])일" event_info.cycle = "\(week[pickerView.selectedRow(inComponent: 0)])/\(day[pickerView.selectedRow(inComponent: 1)])" pickerView.reloadComponent(1) } else { label_alarm.text = "알람: \(alarm_data[pickerView.selectedRow(inComponent: 0)])" event_info.alarm = pickerView.selectedRow(inComponent: 0) } } } extension DetailSetViewController: UNUserNotificationCenterDelegate { func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { completionHandler([.alert, .badge, .sound]) } // 알람 눌러서 스크롤내리면 2가지 항목이 나오는데 각각 선택했을때 어떤식으로 처리할지 여기서 func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { switch response.actionIdentifier { case "answerYes": let alert1 = UIAlertController(title: "화장실-변기", message: "청소 완료", preferredStyle: .alert) let action1 = UIAlertAction(title: "확인", style: .default, handler: nil) alert1.addAction(action1) present(alert1, animated: true, completion: nil) // test print("*******************") case "answerNo": let alert2 = UIAlertController(title: "화장실-변기", message: "청소 처리 안됨", preferredStyle: .alert) let action2 = UIAlertAction(title: "확인", style: .default, handler: nil) alert2.addAction(action2) present(alert2, animated: true, completion: nil) default: break } completionHandler() } }
// // LanguageDownloadTests.swift // iVerbs French // // Created by Brad Reed on 03/01/2016. // Copyright © 2016 Brad Reed. All rights reserved. // import XCTest @testable import iVerbs_French /// These tests validate that Language objects can be created with valid data, /// and return nil for invalid data class LanguageTests: XCTestCase { /// Test: language initialised with missing data returns nil func testLanguageInitWithMissingData() { let data = [ "data": [ "id": 1, "code": "fr", "lang": "French" // Missing some keys, should be nil ] ] XCTAssertNil(Language(dict: data as JSONDict)) } /// Test: language initialised with invalid data returns nil func testLanguageInitWithInvalidData() { let data = [ "data": [ "id": "1", // should be int "code": "fr", // should be string "lang": "French", "locale": 1234, // should be string "version": "1478079010" // should be int ] ] XCTAssertNil(Language(dict: data as JSONDict)) } /// Test: language can be initialised with valid data func testLanguageInitWithValidData() { let data = [ "data": [ "id": 1, "code": "fr", "lang": "French", "locale": "fr_FR", "version": 1478079010 // Example valid response from API ] ] XCTAssertNotNil(Language(dict: data as JSONDict)) } /// Test: language is still initialised if there are extra keys in the data func testLanguageInitWithExtraData() { let data = [ "data": [ "id": 1, "code": "fr", "lang": "French", "locale": "fr_FR", "version": 1478079010, "extra": "key", "foo": 12345, "bar": true // Example valid response from API, with extra keys // Future versions of the API could introduce new data ] ] XCTAssertNotNil(Language(dict: data as JSONDict)) } }
// // ViewController.swift // testArtjoker // // Created by Admin on 21.05.16. // Copyright © 2016 Ievgen Tkachenko. All rights reserved. // import UIKit class EVMainViewController: UITableViewController { @IBOutlet weak var searchBar: UISearchBar! private var aActivityIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray) private var aNamesArray = Array<EVSection>() // промежуточный массив, сузествует для того, чтобы из него получился aSectionArray private var aSectionArray = Array<EVSection>() // основной массив для хранения секций с данными private var aCharString = String?() // хранится переведенной слово private var aDetailString = String?() // хранятся другие возможные переводы слова private var aOriginaString = String?() // хранится оригинальное слово private var aCurrentOperation = NSOperation?() private var aCell = EVTranslateCell() private let kHeightForRowAtSectionZero : CGFloat = 88.0 // размер первой секции для первой ячейки private let kHeightForRowAtIndexOthers : CGFloat = 44.0 // размер для остальных ячеек // MARK: - Life Cycle override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) let customButton = UIBarButtonItem.init(customView: aActivityIndicator) navigationItem.rightBarButtonItem = customButton // проверяется, существуют-ли данные, если их нет, то получаем из локальной базы if aNamesArray.count == 0 { aNamesArray = EVCoreDataHelper.fetchAllDictionary() } p_generateSectionInBackground(aNamesArray, filter: searchBar.text) tableView.reloadData() } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: Action @IBAction func actionSave(sender: UIButton) { aActivityIndicator.startAnimating() let result = p_generateSection(self.aNamesArray, filter: searchBar.text) let result2 = p_generateSection(self.aNamesArray, filter: aCharString) // проверяется на наличие либо на отсутствие слова\символа. // если есть текст в searchBar.text или его нет, возвращает true // иначе сохраняется слово в локальную базу данных if result.count != 0 || result.count != result2.count { aCell.saveOutlet.enabled = false p_showAlertView("Worning!", message: "Еhe word already exists", actionTitle: "OK") aActivityIndicator.stopAnimating() return } aCell.saveOutlet.enabled = true EVCoreDataHelper.saveContext(aCharString!, detailString: aDetailString!, originaString: aOriginaString!) aNamesArray.removeAll() aNamesArray = EVCoreDataHelper.fetchAllDictionary() p_generateSectionInBackground(self.aNamesArray, filter: nil) aActivityIndicator.stopAnimating() } // MARK: - Private Methods private func p_showAlertView(title : String?, message : String?, actionTitle : String?) { let alert = UIAlertController(title: title!, message: message!, preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: actionTitle, style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) } // приватный метод для получения ответа с сервера // shape равен EVShapeReturnStringСharacter, то посылаем запрос к серверу, в других случаях выходим из функции // result.status == 0 означает ошибку private func p_connectToTranslate(filterString : String?, shape : EVShapeReturnString) { if shape != .EVShapeReturnStringСharacter { return } aActivityIndicator.startAnimating() EVLazyAPI.getTranslated({ (result) -> Void in if result.status == 0 { self.p_showAlertView("Worning!", message: "Request limit exceeded", actionTitle: "OK") return } self.aCell.saveOutlet.enabled = true self.aCharString = result.quote self.aDetailString = result.detailQuote self.aOriginaString = filterString self.tableView.reloadData() self.aActivityIndicator.stopAnimating() }, q: filterString!, langpair:EVCurrentStringHelper.languageIdentifier(filterString!)) } // метод с реалтзацией NSBlockOperation для повышения производительности при поиске слова private func p_generateSectionInBackground(object : Array<EVSection>?, filter : String?) -> Void { aCurrentOperation?.cancel() aCurrentOperation = NSBlockOperation(block: { () -> Void in let sectionArray = self.p_generateSection(object, filter: filter) dispatch_async(dispatch_get_main_queue(), { self.aSectionArray = sectionArray self.tableView.reloadData() self.aCurrentOperation = nil }); }) aCurrentOperation?.start() } // реализация поиска. // разбиение данных по секциям // если данных нет или слово не нашлось, то вызывается метод p_connectToTranslate() private func p_generateSection(object : Array<EVSection>?, filter : String?) -> Array<EVSection> { var itemsArray = Array<EVSection>() var currentLetter = String() if object!.count == 0 && filter?.characters.count == 0 { return []; } for item in object! { if filter?.characters.count > 0 && item.sectionName.rangeOfString(filter!) == nil { continue } let firstLetter = EVCurrentStringHelper.languageIdentifier(item.sectionName) var section = EVSection() if currentLetter != firstLetter { section.sectionName = firstLetter section.dedailText = item.dedailText section.originText = item.originText currentLetter = firstLetter itemsArray.append(section) } else { section = itemsArray.last! } section.itemsArray.append(item.sectionName) section.originArray.append(item.originText) section.dedailArray.append(item.dedailText) } if itemsArray.count == 0 && filter != nil { p_connectToTranslate(filter, shape: .EVShapeReturnStringСharacter) } return itemsArray } // MARK: - UITableViewDataSource override func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle { return indexPath.section == 0 ? UITableViewCellEditingStyle.None : UITableViewCellEditingStyle.Delete; } // удаление слова из UI и SQL с анимацией .Automatic // удаление по ключу из локальной базы данных EVCoreDataHelper.removeForKey() override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == UITableViewCellEditingStyle.Delete { aActivityIndicator.startAnimating() EVCoreDataHelper.removeForKey(aSectionArray[indexPath.section - 1].itemsArray[indexPath.row] as! String) aSectionArray[indexPath.section - 1].itemsArray.removeAtIndex(indexPath.row) tableView.beginUpdates() tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic) tableView.endUpdates() aActivityIndicator.stopAnimating() } } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if aSectionArray.count != 0 && section > 0 { let item : EVSection? = aSectionArray[section - 1] return item!.sectionName } return "" } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return aSectionArray.count + 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section > 0 { let item : EVSection? = aSectionArray[section - 1] return item!.itemsArray.count } return 1; } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if indexPath.section == 0 { let identifier = "cell" aCell = (tableView.dequeueReusableCellWithIdentifier(identifier) as? EVTranslateCell)! if let text = self.aCharString { aCell.translateTextLabel!.text = text } return aCell } let cellIdentifier = "cellDictionary" let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) let section = aSectionArray[indexPath.section - 1] cell!.textLabel!.text = section.itemsArray[indexPath.row] as? String return cell! } // MARK: - UITableViewDelegate override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if indexPath.row == 0 { tableView.deselectRowAtIndexPath(indexPath, animated: true) } } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { if indexPath.row == 0 && indexPath.section == 0 { return kHeightForRowAtSectionZero } return kHeightForRowAtIndexOthers } // MARK: - Navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "EVDetailDictionaryViewController" { let indexPath = tableView.indexPathForSelectedRow let section = aSectionArray[indexPath!.section - 1] let vc = segue.destinationViewController as! EVDetailDictionaryViewController vc.translateTitle = section.originArray[(indexPath?.row)!] as! String vc.optionalDetail = section.dedailArray[(indexPath?.row)!] as! String vc.language = section.sectionName } } } // MARK: - UISearchBarDelegate extension EVMainViewController : UISearchBarDelegate { func searchBar(searchBar: UISearchBar, textDidChange searchText: String) { if (EVCurrentStringHelper.validateStringOnSpace(self.searchBar.text) == .EVShapeReturnStringСharacter) { p_generateSectionInBackground(self.aNamesArray, filter: self.searchBar.text) } else if searchText == "" { self.aCell.translateTextLabel.text = " " aCharString = "" } } func searchBarTextDidBeginEditing(searchBar: UISearchBar) { searchBar.setValue("Done", forKey: "_cancelButtonText") searchBar.setShowsCancelButton(true, animated: true) } func searchBarCancelButtonClicked(searchBar: UISearchBar) { searchBar.setShowsCancelButton(false, animated: true) aNamesArray.removeAll() aNamesArray = EVCoreDataHelper.fetchAllDictionary() p_generateSectionInBackground(self.aNamesArray, filter: nil) searchBar.resignFirstResponder() } }
import XCTest extension SwiftDemanglerTests { static let __allTests = [ ("testIsEven", testIsEven), ] } #if !os(macOS) public func __allTests() -> [XCTestCaseEntry] { return [ testCase(SwiftDemanglerTests.__allTests), ] } #endif
// // Test2.swift // AnimationDemo // // Created by Manas Mishra on 29/05/18. // Copyright © 2018 Manas Mishra. All rights reserved. // import UIKit class Test2: NSObject { func startTest() { } func createATree(arr: [Int]) { for each in arr { let node = TreeNode(data: each, left: nil, right: nil) } } } class TreeNode { var data: Int var leftNode: TreeNode? var rightNode: TreeNode? init(data: Int, left: TreeNode?, right: TreeNode?) { self.data = data self.leftNode = left self.rightNode = right } } class Tree { var root: TreeNode? //var prevNode: TreeNode? func insert(data: Int) { var temp = root if temp == nil { root = TreeNode(data: data, left: nil, right: nil) //prevNode = root } else { } } }
// // TableViewController.swift // NotUseStoryboardUI // // Created by Terry Yang on 2017/5/26. // Copyright © 2017年 terryyamg. All rights reserved. // import UIKit class TableViewController : UIViewController, UITableViewDelegate, UITableViewDataSource{ let data : [String] = ["WinterIsComing","OursIsTheFury","HearMeRoar","BloodAndFire"] override func viewDidLoad() { super.viewDidLoad() self.title = "TableViewController" let fullScreenSize = UIScreen.main.bounds.size let myTabview = UITableView(frame: CGRect(x: 0,y: 20, width: fullScreenSize.width, height: fullScreenSize.height - 20),style: .plain) myTabview.register(TableViewControllerCell.self, forCellReuseIdentifier: "MyCell") myTabview.delegate = self myTabview.dataSource = self myTabview.separatorStyle = .singleLine myTabview.separatorInset = UIEdgeInsetsMake(0, 20, 0, 20) myTabview.allowsSelection = true myTabview.allowsMultipleSelection = false self.view.addSubview(myTabview) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return data.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath) as! TableViewControllerCell cell.awakeFromNib() cell.lab.textColor = .black cell.lab.text = data[indexPath.row] cell.iv.image = UIImage(named: data[indexPath.row]+".jpeg")! return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let vc = TabBarViewController() vc.titles = data[indexPath.row] self.navigationController?.pushViewController(vc, animated: true) } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 100.0 } }
import UIKit class TimelineDao : NSObject{ func latest() -> Timelines{ return TimelineAPI().latest() } func next(prevLastNo:String) -> Timelines{ return TimelineAPI().next(prevLastNo) } }
// // MineConcernTableViewCell.swift // TodayHeadline // // Created by LiDinggui on 2018/11/21. // Copyright © 2018年 LiDinggui. All rights reserved. // import UIKit import Kingfisher import SwiftTheme class MineConcernTableViewCell: UITableViewCell, RegisterReusableViewOrNib { @IBOutlet private weak var titleLabel: UILabel! @IBOutlet private weak var arrowImageView: UIImageView! @IBOutlet private weak var subtitleLabel: UILabel! @IBOutlet private weak var iconImageView: UIImageView! @IBOutlet private weak var collectionView: UICollectionView! override func awakeFromNib() { super.awakeFromNib() collectionView.registerCell(MyConcernCollectionViewCell.self) arrowImageView.theme_image = "images.setting_rightarrow" titleLabel.theme_textColor = "colors.black" subtitleLabel.theme_textColor = "colors.subtitleLabelTextColor" contentView.theme_backgroundColor = "colors.cellBackgroundColor" } var model: MineCellModel? { didSet { titleLabel.text = model?.text // subtitleLabel.text = model?.grey_text } } var concerns: [MineConcernModel]? { didSet { guard let concerns = concerns else { return } let firstConcern = concerns.first subtitleLabel.text = firstConcern?.name iconImageView.kf.setImage(with: URL(string: firstConcern?.icon ?? ""), placeholder: nil) collectionView.reloadData() subtitleLabel.isHidden = concerns.count != 1 iconImageView.isHidden = concerns.count != 1 collectionView.isHidden = concerns.count < 2 } } } extension MineConcernTableViewCell: UICollectionViewDataSource, UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return concerns?.count ?? 0 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(indexPath: indexPath) as MyConcernCollectionViewCell let concern = concerns![indexPath.item] cell.concern = concern return cell } }
// // DayFive.swift // aoc2019 // // Created by Shawn Veader on 12/5/19. // Copyright © 2019 Shawn Veader. All rights reserved. // import Foundation struct DayFive: AdventDay { var dayNumber: Int = 5 func partOne(input: String?) -> Any { let machine = IntCodeMachine(instructions: input ?? "") machine.inputs = [1] machine.run() return machine.outputs.last ?? 0 } func partTwo(input: String?) -> Any { let machine = IntCodeMachine(instructions: input ?? "") machine.inputs = [5] machine.run() // return machine.memory(at: 0) return machine.outputs.last ?? 0 } }
// // TabBarViewController.swift // On The Map // // Created by Kim Lyndon on 11/2/18. // Copyright © 2018 Kim Lyndon. All rights reserved. // import UIKit class TabBarViewController: UITabBarController { @IBOutlet weak var logoutBarButton: UIBarButtonItem! @IBOutlet weak var refreshBarButton: UIBarButtonItem! @IBOutlet weak var addBarButton: UIBarButtonItem! // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) refreshThings() } @IBAction func logoutButtonTapped(_ sender: UIBarButtonItem) { UdacityClient.sharedInstance().taskForDELETELogoutMethod() performUIUpdatesOnMain { self.dismiss(animated: true, completion: nil) } } @IBAction func refreshBarButtonTapped(_ sender: UIBarButtonItem) { refreshThings() } func refreshThings() { print("refresh bar button pressed") //Create constants to prepare for refreshing the two view controllers let mapViewController = self.viewControllers?[0] as! MapViewController let tableViewController = self.viewControllers![1] as! TableViewController //Get 100 student locations from Parse ParseClient.sharedInstance().getLocationsRequest() { (success, errorString) in guard (success == true) else { print("Unsuccessful in obtaining student locations from Parse: \(errorString)") performUIUpdatesOnMain { self.createAlert(title: "Error", message: "Failure to download student location data.") } return } performUIUpdatesOnMain { //Update UI in both MapVC and TableVC print("RefreshUI") mapViewController.displayUpdatedAnnotations() tableViewController.refreshTableView() } } } @IBAction func addBarButtonTapped(_ sender: Any) { //Segues to AddLocationViewController } //MARK: Navigation (Per Mentor:) // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. if segue.identifier == "AddButtonSegue" { print("Add Segue: was the click button clicked?") // if no prior user location posted (mapString should be "") if StudentInformation.UserData.objectId == "" { print("User has not posted their location yet.") print("User Object ID: \(StudentInformation.UserData.objectId)") // performSegue(withIdentifier: "AddButtonSegue", sender: nil) performUIUpdatesOnMain { let controller = self.storyboard!.instantiateViewController(withIdentifier: "AddLocationNavigationController") as! UINavigationController self.present(controller, animated: true, completion: nil) } return } else { // mapString contains data, so the user has already posted a location print("User has already posted a location") print("User Object ID: \(StudentInformation.UserData.objectId)") // display the errorString using createAlert createTwoButtonAlert() return } } } func createTwoButtonAlert() { let alertController = UIAlertController(title: "Warning", message: "User \(StudentInformation.UserData.firstName) \(StudentInformation.UserData.lastName) has already posted a Student Location. Would you like to overwrite the location of '\(StudentInformation.UserData.mapString)'?", preferredStyle: .alert) // Create OK button let OKAction = UIAlertAction(title: "OK", style: .default) { (action:UIAlertAction!) in print("Ok button tapped"); performUIUpdatesOnMain { let controller = self.storyboard!.instantiateViewController(withIdentifier: "AddLocationNavigationController") as! UINavigationController self.present(controller, animated: true, completion: nil) } return } alertController.addAction(OKAction) // Create Cancel button let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (action:UIAlertAction!) in print("Cancel button tapped"); } alertController.addAction(cancelAction) // Present Dialog message self.present(alertController, animated: true, completion:nil) } }
// // Empty.swift // // // Created by Vladislav Fitc on 30/03/2020. // import Foundation public struct Empty: Codable { public static let empty: Self = .init() public init() {} public init(from decoder: Decoder) throws { self.init() } public func encode(to encoder: Encoder) throws {} }
// Copyright 2019 Kakao Corp. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation import KakaoSDKCommon import KakaoSDKAuth import KakaoSDKTemplate /// 카카오 Open API의 카카오톡 API 호출을 담당하는 클래스입니다. /// /// 프로필 가져오기, 친구 목록 가져오기, 메시지 보내기 등이 기능을 제공합니다. public class TalkApi { // MARK: Fields /// 간편하게 API를 호출할 수 있도록 제공되는 공용 싱글톤 객체입니다. public static let shared = TalkApi() /// 카카오톡 채널을 추가하기 위한 URL을 반환합니다. URL을 브라우저나 웹뷰에서 로드하면 연결 페이지(bridge page)를 통해 카카오톡을 실행합니다. /// /// - parameter channelPublicId: 카카오톡 채널 홈 URL에 들어간 {_영문}으로 구성된 고유 아이디입니다. 홈 URL은 카카오톡 채널 관리자센터 > 관리 > 상세설정 페이지에서 확인할 수 있습니다. /// /// 아래는 SFSafariViewController를 이용해 카카오톡 채널을 추가하는 예제입니다. /// ``` /// guard let url = TalkApi.shared.makeUrlForAddChannel(channelPublicId:"<#Your Channel Public ID#>" else { /// return /// } /// let safariViewController = SFSafariViewController(url: url) /// self.present(safariViewController, animated: true, completion: nil) /// ``` public func makeUrlForAddChannel(channelPublicId:String) -> URL? { SdkLog.d("===================================================================================================") let url = SdkUtils.makeUrlWithParameters("\(Urls.compose(.Channel, path:Paths.channel))/\(channelPublicId)/friend",parameters:["app_key":try! KakaoSDKCommon.shared.appKey(), "kakao_agent":Constants.kaHeader, "api_ver":"1.0"].filterNil()) SdkLog.d("url: \(url?.absoluteString ?? "something wrong!") \n") return url } /// 카카오톡 채널 1:1 대화방 실행을 위한 URL을 반환합니다. URL을 브라우저나 웹뷰에서 로드하면 브릿지 웹페이지를 통해 카카오톡을 실행합니다. /// /// - parameter channelPublicId: 카카오톡 채널 홈 URL에 들어간 {_영문}으로 구성된 고유 아이디입니다. 홈 URL은 카카오톡 채널 관리자센터 > 관리 > 상세설정 페이지에서 확인할 수 있습니다. /// /// 아래는 SFSafariViewController를 이용해 1:1 대화방을 실행하는 예제입니다. /// ``` /// guard let url = TalkApi.shared.makeUrlForChannelChat(channelPublicId:"<#Your Channel Public ID#>" else { /// return /// } /// let safariViewController = SFSafariViewController(url: url) /// self.present(safariViewController, animated: true, completion: nil) /// ``` public func makeUrlForChannelChat(channelPublicId:String) -> URL? { SdkLog.d("===================================================================================================") let url = SdkUtils.makeUrlWithParameters("\(Urls.compose(.Channel, path:Paths.channel))/\(channelPublicId)/chat", parameters:["app_key":try! KakaoSDKCommon.shared.appKey(), "kakao_agent":Constants.kaHeader, "api_ver":"1.0"].filterNil()) SdkLog.d("url: \(url?.absoluteString ?? "something wrong!") \n") return url } } extension TalkApi { // MARK: Profile /// 로그인된 사용자의 카카오톡 프로필 정보를 얻을 수 있습니다. /// - seealso: `TalkProfile` public func profile(completion:@escaping (TalkProfile?, Error?) -> Void) { AUTH.responseData(.get, Urls.compose(path:Paths.talkProfile), apiType: .KApi) { (response, data, error) in if let error = error { completion(nil, error) return } if let data = data { completion(try? SdkJSONDecoder.custom.decode(TalkProfile.self, from: data), nil) return } completion(nil, SdkError()) } } // MARK: Memo /// 카카오 디벨로퍼스에서 생성한 서비스만의 커스텀 메시지 템플릿을 사용하여, 카카오톡의 "나와의 채팅방"으로 메시지를 전송합니다. 템플릿을 생성하는 방법은 https://developers.kakao.com/docs/latest/ko/message/ios#create-message 을 참고하시기 바랍니다. public func sendCustomMemo(templateId: Int64, templateArgs: [String:String]? = nil, completion:@escaping (Error?) -> Void) { AUTH.responseData(.post, Urls.compose(path:Paths.customMemo), parameters: ["template_id":templateId, "template_args":templateArgs?.toJsonString()].filterNil(), apiType: .KApi) { (_, _, error) in completion(error) return } } /// 기본 템플릿을 이용하여, 카카오톡의 "나와의 채팅방"으로 메시지를 전송합니다. /// - seealso: [Template](../../KakaoSDKTemplate/Protocols/Templatable.html) public func sendDefaultMemo(templatable: Templatable, completion:@escaping (Error?) -> Void) { AUTH.responseData(.post, Urls.compose(path:Paths.defaultMemo), parameters: ["template_object":templatable.toJsonObject()?.toJsonString()].filterNil(), apiType: .KApi) { (_, _, error) in completion(error) return } } /// 지정된 URL을 스크랩하여, 카카오톡의 "나와의 채팅방"으로 메시지를 전송합니다. public func sendScrapMemo(requestUrl: String, templateId: Int64? = nil, templateArgs: [String:String]? = nil, completion:@escaping (Error?) -> Void) { AUTH.responseData(.post, Urls.compose(path:Paths.scrapMemo), parameters: ["request_url":requestUrl,"template_id":templateId, "template_args":templateArgs?.toJsonString()].filterNil(), apiType: .KApi) { (_, _, error) in completion(error) return } } // MARK: Friends /// 카카오톡 친구 목록을 조회합니다. /// - seealso: `Friends` public func friends(offset: Int? = nil, limit: Int? = nil, order: Order? = nil, completion:@escaping (Friends<Friend>?, Error?) -> Void) { AUTH.responseData(.get, Urls.compose(path:Paths.friends), parameters: ["offset": offset, "limit": limit, "order": order?.rawValue].filterNil(), apiType: .KApi) { (response, data, error) in if let error = error { completion(nil, error) return } if let data = data { completion(try? SdkJSONDecoder.custom.decode(Friends<Friend>.self, from: data), nil) return } completion(nil, SdkError()) } } /// 카카오톡 친구 목록을 FriendContext를 파라미터로 조회합니다. /// - seealso: `FriendsContext` public func friends(context: FriendsContext?, completion:@escaping (Friends<Friend>?, Error?) -> Void) { friends(offset: context?.offset, limit: context?.limit, order: context?.order, completion: completion) } // MARK: Message /// 기본 템플릿을 사용하여, 조회한 친구를 대상으로 카카오톡으로 메시지를 전송합니다. /// - seealso: [Template](../../KakaoSDKTemplate/Protocols/Templatable.html) <br> `MessageSendResult` public func sendDefaultMessage(templatable:Templatable, receiverUuids:[String], completion:@escaping (MessageSendResult?, Error?) -> Void) { AUTH.responseData(.post, Urls.compose(path:Paths.defaultMessage), parameters: ["template_object":templatable.toJsonObject()?.toJsonString(), "receiver_uuids":receiverUuids.toJsonString()].filterNil(), apiType: .KApi) { (response, data, error) in if let error = error { completion(nil, error) return } if let data = data { completion(try? SdkJSONDecoder.custom.decode(MessageSendResult.self, from: data), nil) return } completion(nil, SdkError()) } } /// 카카오 디벨로퍼스에서 생성한 메시지 템플릿을 사용하여, 조회한 친구를 대상으로 카카오톡으로 메시지를 전송합니다. 템플릿을 생성하는 방법은 https://developers.kakao.com/docs/latest/ko/message/ios#create-message 을 참고하시기 바랍니다. /// - seealso: `MessageSendResult` public func sendCustomMessage(templateId: Int64, templateArgs:[String:String]? = nil, receiverUuids:[String], completion:@escaping (MessageSendResult?, Error?) -> Void) { AUTH.responseData(.post, Urls.compose(path:Paths.customMessage), parameters: ["receiver_uuids":receiverUuids.toJsonString(), "template_id":templateId, "template_args":templateArgs?.toJsonString()].filterNil(), apiType: .KApi) { (response, data, error) in if let error = error { completion(nil, error) return } if let data = data { completion(try? SdkJSONDecoder.custom.decode(MessageSendResult.self, from: data), nil) return } completion(nil, SdkError()) } } /// 지정된 URL을 스크랩하여, 조회한 친구를 대상으로 카카오톡으로 메시지를 전송합니다. 스크랩 커스텀 템플릿 가이드(https://developers.kakao.com/docs/latest/ko/message/ios#send-kakaotalk-msg) 를 참고하여 템플릿을 직접 만들고 스크랩 메시지 전송에 이용할 수도 있습니다. /// - seealso: `MessageSendResult` public func sendScrapMessage(requestUrl: String, templateId: Int64? = nil, templateArgs:[String:String]? = nil, receiverUuids:[String], completion:@escaping (MessageSendResult?, Error?) -> Void) { AUTH.responseData(.post, Urls.compose(path:Paths.scrapMessage), parameters: ["receiver_uuids":receiverUuids.toJsonString(), "request_url": requestUrl, "template_id":templateId, "template_args":templateArgs?.toJsonString()].filterNil(), apiType: .KApi) { (response, data, error) in if let error = error { completion(nil, error) return } if let data = data { completion(try? SdkJSONDecoder.custom.decode(MessageSendResult.self, from: data), nil) return } completion(nil, SdkError()) } } // MARK: Kakaotalk Channel /// 사용자가 특정 카카오톡 채널을 추가했는지 확인합니다. /// - seealso: `Channels` public func channels(publicIds: [String]? = nil, completion:@escaping (Channels?, Error?) -> Void) { AUTH.responseData(.get, Urls.compose(path:Paths.channels), parameters: ["channel_public_ids":publicIds?.toJsonString()].filterNil(), apiType: .KApi) { (response, data, error) in if let error = error { completion(nil, error) return } if let data = data { completion(try? SdkJSONDecoder.customIso8601Date.decode(Channels.self, from: data), nil) return } completion(nil, SdkError()) } } }
import Foundation struct IOSMVCTableViewControllerTemplate: ViewControllerTemplate { var dirPath: String { "./" + Const.templateDirName + "/" + FrontType.ios.name + "/" + ArchitectureType.mvc_table.name + "/ViewController/" } var code: String { """ // // \(Const.prefix)ViewController.swift // \(Const.targetName) // // Created by \(Const.userName) on \(Const.yearStr)/\(Const.monthStr)/\(Const.dayStr). // import UIKit final class \(Const.prefix)ViewController: UIViewController { @IBOutlet private weak var tableView: UITableView! { didSet { } } } extension \(Const.prefix)ViewController: UITableViewDelegate { } extension \(Const.prefix)ViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { UITableViewCell() } } """ } }
import Foundation // MARK: - ℹ️ Инструкция // // Чтобы выполнить практическое задание, вам потребуется: // 1. Прочитайте условие задания // 2. Напишите ваше решение ниже в этом файле в разделе "Решение". // 3. После того как решение будет готово, запустите Playground, // чтобы проверить свое решение тестами // MARK: - ℹ️ Условие задания // // 1. Создайте перечисление `Objects` // 2. Добавьте в него кейсы со следующими ассоциированными типами // - `planet` - название типа `String` // - `satelite` - радиус типа `Double` и название типа `String` // - `star` - название типа `String` // 3. Создайте переменную `moon` и задайте ей значение кейса `satelite` со следующими ассоциированными значениями: // радиус - 1_737.4 // название - "Луна" // 4. Создайте переменную `objectName` типа `String` // 5. C помощью `switch` проверьте переменную `moon` и в каждом кейсе сохраните в `objectName` следущий результат: // - для planet сохраните в переменную `objectName` название из ассоциированного значения // - для satelite сохраните в переменную `objectName` конкатенированную строку радиуса и названия через пробел, в таком формате: "<радиус> <пробел>" // - для star сохраните в переменную `objectName` название из ассоциированного значения // MARK: - 🧑‍💻 Решение // --- НАЧАЛО КОДА С РЕШЕНИЕМ --- enum Objects { case planet(String) case satelite(Double, String) case start(String) } var moon: Objects = .satelite(1_737.4, "Луна") var objectName: String switch moon { case .planet(let name): objectName = name case .satelite(let radius, let name): objectName = "\(radius) \(name)" case .start(let name): objectName = name } // --- КОНЕЦ КОДА С РЕШЕНИЕМ --- // MARK: - 🛠 Тесты // - Здесь содержится код запуска тестов для вашего решения // - ⚠️ Не меняйте этот код TestRunner.runTests(.default(moon, objectName))
// // DrawingToolCell.swift // spriteMaker // // Created by 박찬울 on 2021/10/20. // import UIKit class DrawingToolCell: UICollectionViewCell { @IBOutlet weak var toolImage: UIImageView! @IBOutlet weak var cellBG: UIView! var cellHeight: CGFloat! var isExtToolExist: Bool! var cellIndex: Int! override func layoutSubviews() { super.layoutSubviews() setSideCorner(target: cellBG, side: "all", radius: cellHeight / 7) drawExtToolTriangle() } func drawExtToolTriangle() { if isExtToolExist { let triangle = TriangleCornerView(frame: CGRect(x: 0, y: 0, width: cellHeight, height: cellHeight)) triangle.backgroundColor = .clear self.addSubview(triangle) } else { for subview in self.subviews where subview is TriangleCornerView { subview.removeFromSuperview() } } } }
// // FirstViewController.swift // PicassoHouse // // Created by Antony Alkmim on 20/03/17. // Copyright © 2017 CoderUP. All rights reserved. // import UIKit import Charts class InfoViewController: UIViewController { fileprivate var viewModel : LightsInfoViewModel! init(viewModel: LightsInfoViewModel) { self.viewModel = viewModel super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } lazy var infoView = InfoView() } // MARK: - Lifecycler // --------------------------------- extension InfoViewController { override func viewDidLoad() { super.viewDidLoad() setup() bindViews() } override func loadView() { view = infoView } } // MARK - Setup // --------------------------------- extension InfoViewController { fileprivate func setup() { edgesForExtendedLayout = [] title = "Info" } } // MARK: - RxBindings // --------------------------------- extension InfoViewController { fileprivate func bindViews() { viewModel.timeOff .bindTo(infoView.timeOffLabel.rx.text) .disposed(by: rx_disposeBag) viewModel.timeOn .bindTo(infoView.timeOnLabel.rx.text) .disposed(by: rx_disposeBag) viewModel.lightHistory .bindNext(infoView.setupChartWith) .disposed(by: rx_disposeBag) } }
// // MusicPurchase.swift // SoTube // // Created by .jsber on 24/05/17. // Copyright © 2017 NV Met Talent. All rights reserved. // import Foundation class Track { let id: String let name: String let trackNumber: Int let discNumber: Int let duration: Int let coverUrl: String let artistName: String let artistId: String let albumName: String let albumId: String var bought = false var artistCoverUrl: String? var dateOfPurchase: Date? var priceInCoins: Int? var dateString: String { return DateFormatter.localizedString(from: dateOfPurchase!, dateStyle: .medium, timeStyle: .none) } var keyDate: TimeInterval { return dateOfPurchase!.timeIntervalSinceReferenceDate } var dictionary: [String : [String : String]] { return [ id : [ "name" : name, "trackNumber" : String(trackNumber), "discNumber" : String(discNumber), "duration" : String(duration), "coverUrl" : coverUrl, "artistName" : artistName, "artistId" : artistId, "albumName" : albumName, "albumId" : albumId, "dateOfPurchase" : String(keyDate), "priceInCoins" : String(priceInCoins!) ]] } var albumDictionary: [String : Any] { return [ "albumName" : albumName, "artistName" : artistName, "artistId" : artistId, "coverUrl" : coverUrl ] } var artistDictionary: [String : Any] { return [ "artistName" : artistName, "artistCoverUrl" : artistCoverUrl ?? "" ] } init(id: String, name: String, trackNumber: Int, discNumber: Int, duration: Int, coverUrl: String, artistName: String, artistId: String, albumName: String, albumId: String, bought: Bool, dateOfPurchase: Date?, priceInCoins: Int?) { self.id = id self.name = name self.trackNumber = trackNumber self.discNumber = discNumber self.duration = duration self.coverUrl = coverUrl self.artistName = artistName self.artistId = artistId self.albumName = albumName self.albumId = albumId self.bought = bought self.dateOfPurchase = dateOfPurchase self.priceInCoins = priceInCoins } convenience init(id: String, name: String, trackNumber: Int, discNumber: Int, duration: Int, coverUrl: String, artistName: String, artistId: String, albumName: String, albumId: String) { self.init(id: id, name: name, trackNumber: trackNumber, discNumber: discNumber, duration: duration, coverUrl: coverUrl, artistName: artistName, artistId: artistId, albumName: albumName, albumId: albumId, bought: false, dateOfPurchase: nil, priceInCoins: nil) } convenience init(id: String, name: String, trackNumber: Int, discNumber: Int, duration: Int, coverUrl: String, artistName: String, artistId: String, albumName: String, albumId: String, bought: Bool, databaseDate: TimeInterval, priceInCoins: Int) { let date = Date(timeIntervalSinceReferenceDate: databaseDate) self.init(id: id, name: name, trackNumber: trackNumber, discNumber: discNumber, duration: duration, coverUrl: coverUrl, artistName: artistName, artistId: artistId, albumName: albumName, albumId: albumId, bought: bought, dateOfPurchase: date, priceInCoins: priceInCoins) } }
// // ExampleInteractor.swift // Template // // Created Domagoj Kulundzic on 27/05/2019. // import Foundation protocol ExampleBusinessLogic: AnyObject { func loadTodos() } class ExampleInteractor { weak var presenter: ExampleBusinessPresentingLogic? } // MARK: - ExampleBusinessLogic extension ExampleInteractor: ExampleBusinessLogic { func loadTodos() { print(#function) } }
// // LessonsInteractor.swift // HseTimetable // // Created by Pavel on 21.04.2020. // Copyright © 2020 Hse. All rights reserved. // import RxSwift import RxCocoa import Action import Foundation final class LessonsInteractor: LessonsInteractorProtocol, LessonsInteractorInputsProtocol, LessonsInteractorOutputsProtocol { var inputs: LessonsInteractorInputsProtocol { return self } var outputs: LessonsInteractorOutputsProtocol { return self } /// Inputs let dataBaseLessonsTrigger = PublishSubject<Void>() let searchLessonsTrigger = PublishSubject<Int>() let removeStudentTrigger = PublishSubject<Void>() let checkConnectionTrigger = PublishSubject<Void>() /// Outputs let searchLessonsResponse = PublishSubject<[Lesson]>() let removeStudentResponse = PublishSubject<Void>() let errorResponse = PublishSubject<Error>() let connectionResponse = PublishSubject<Bool>() private let dbGetAction: Action<Void, [Lesson]> private let dbUpdateAction: Action<[Lesson], Void> private let searchLessonsAction: Action<Int, [Lesson]> private let removeStrudentAction: Action<Void, Void> private let checkConnectionAction: Action<Void, Bool> private let disposeBag = DisposeBag() static private let dataService: DataServiceProtocol = DataService() static private let networkService: NetworkLessonsServiceProtocol = NetworkService() required init() { self.dbGetAction = Action { return LessonsInteractor.getLessonsFromDB() } self.dbUpdateAction = Action { lessons in return LessonsInteractor.updateLessonsToDB(lessons: lessons) } self.searchLessonsAction = Action { daysOffset in return LessonsInteractor.getLessonsFromNetwork(daysOffset: daysOffset) } self.removeStrudentAction = Action { return LessonsInteractor.removeStudent() } self.checkConnectionAction = Action { return LessonsInteractor.checkConnection() } /// Inputs setup self.dataBaseLessonsTrigger.asObserver() .bind(to: self.dbGetAction.inputs) .disposed(by: self.disposeBag) self.searchLessonsTrigger.asObserver() .bind(to: self.searchLessonsAction.inputs) .disposed(by: self.disposeBag) self.removeStudentTrigger.asObserver() .bind(to: self.removeStrudentAction.inputs) .disposed(by: self.disposeBag) self.checkConnectionTrigger.asObserver() .bind(to: self.checkConnectionAction.inputs) .disposed(by: self.disposeBag) /// Outputs setup self.dbGetAction.elements.asObservable() .bind(to: self.searchLessonsResponse) .disposed(by: self.disposeBag) self.dbUpdateAction.elements.asObservable() .bind(to: self.dbGetAction.inputs) .disposed(by: self.disposeBag) self.searchLessonsAction.elements.asObservable() .bind(to: self.dbUpdateAction.inputs) .disposed(by: self.disposeBag) self.removeStrudentAction.elements.asObservable() .bind(to: self.removeStudentResponse) .disposed(by: self.disposeBag) self.checkConnectionAction.elements.asObservable() .bind(to: self.connectionResponse) .disposed(by: self.disposeBag) /// Errors setup self.dbGetAction.errors.asObservable() .map{ $0.get() } .bind(to: self.errorResponse) .disposed(by: self.disposeBag) self.dbUpdateAction.errors.asObservable() .map{ $0.get() } .bind(to: self.errorResponse) .disposed(by: self.disposeBag) self.searchLessonsAction.errors.asObservable() .map{ $0.get() } .bind(to: self.errorResponse) .disposed(by: self.disposeBag) self.removeStrudentAction.errors.asObservable() .map{ $0.get() } .bind(to: self.errorResponse) .disposed(by: self.disposeBag) } } extension LessonsInteractor { private static func getLessonsFromDB() -> Single<[Lesson]> { return Single<[Lesson]>.create{ observer in let (data, error) = LessonsInteractor.dataService.getLessonsData(filter: nil, sortedByKeyPath: "dateStart", ascending: true) guard error == nil else { observer(.error(error!)) return Disposables.create() } guard let list = data else { observer(.success([])) return Disposables.create() } let lessons = list.map{ Lesson(adress: $0.adress, type: $0.type, lecturer: $0.lecturer, auditorium: $0.auditorium, dateStart: $0.dateStart, dateEnd: $0.dateEnd, importance: $0.importance, discipline: $0.discipline) } observer(.success(lessons)) return Disposables.create() } } private static func updateLessonsToDB(lessons: [Lesson]) -> Single<Void> { return Single<Void>.create{ observer in if let error = LessonsInteractor.dataService.deleteLessonsData(filter: nil) { observer(.error(error)) return Disposables.create() } let listData = lessons.map{ (adress: $0.adress, type: $0.type, lecturer: $0.lecturer, auditorium: $0.auditorium, dateStart: $0.dateStart, dateEnd: $0.dateEnd, importance: $0.importance?.rawValue, discipline: $0.discipline) } if let error = LessonsInteractor.dataService.putLessonsData(listLessonsData: listData) { observer(.error(error)) } else { observer(.success(())) } return Disposables.create() } } private static func getLessonsFromNetwork(daysOffset: Int) -> Single<[Lesson]> { return Single<[Lesson]>.create{ observer in let studentId = UserDefaults.standard.integer(forKey: "studentId") let dateFrom = Date.init() LessonsInteractor.networkService.lessonsGet(studentId: studentId, daysOffset: daysOffset, dateFrom: dateFrom) { (lessons: [Lesson]?, responseError: ResponseError?, error) in guard responseError == nil else { observer(.error(responseError!)) return } guard error == nil else { observer(.error(error!)) return } if let lessons = lessons { observer(.success(lessons)) } } return Disposables.create() } } private static func removeStudent() -> Single<Void> { return Single<Void>.create{ observer in if let error = LessonsInteractor.dataService.deleteLessonsData(filter: nil) { observer(.error(error)) return Disposables.create() } let defaults = UserDefaults.standard defaults.removeObject(forKey: "studentId") observer(.success(())) return Disposables.create() } } private static func checkConnection() -> Single<Bool> { return Single<Bool>.create{ observer in NetStatus.shared.stopMonitoring() NetStatus.shared.netStatusChangeHandler = { observer(.success(NetStatus.shared.isConnected)) } NetStatus.shared.startMonitoring() return Disposables.create() } } } // MARK:- Interactorable extension LessonsInteractor: Interactorable {}
// // SectionFooter.swift // GoodNews // // Created by Muhammad Osama Naeem on 3/21/20. // Copyright © 2020 Muhammad Osama Naeem. All rights reserved. // import UIKit protocol SectionFooterDelegate { func didTapButton() } class SectionFooter: UICollectionReusableView { static let reuseIdentifier = "FooterHeader" let button = UIButton(type: .system) var delegate: SectionFooterDelegate? override init(frame: CGRect) { super.init(frame: frame) button.setTitle("See All Domains", for: .normal) button.setTitleColor(.red, for: .normal) button.addTarget(self, action: #selector(handleSeeAllTopicsbutton), for: .touchUpInside) button.titleLabel?.font = UIFontMetrics.default.scaledFont(for: UIFont.systemFont(ofSize: 12, weight: .medium)) let stackView = UIStackView(arrangedSubviews: [button]) stackView.translatesAutoresizingMaskIntoConstraints = false stackView.axis = .vertical stackView.alignment = .trailing addSubview(stackView) NSLayoutConstraint.activate([ stackView.leadingAnchor.constraint(equalTo: leadingAnchor), stackView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -30), stackView.topAnchor.constraint(equalTo: topAnchor, constant: 16), stackView.bottomAnchor.constraint(equalTo: bottomAnchor) ]) } @objc func handleSeeAllTopicsbutton() { delegate?.didTapButton() } required init?(coder aDecoder: NSCoder) { fatalError("Stop trying to make storyboards happen.") } }
// // ViewController.swift // BlurMyPhoto // // Created by Alexander Shive on 4/23/15. // Copyright (c) 2015 Alexander Shive. All rights reserved. // import UIKit class ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate { var imagePicker = UIImagePickerController() @IBOutlet var toolbar: UIToolbar! @IBOutlet var userImage: UIImageView! @IBOutlet var blurImage: UIImageView! @IBOutlet var slider: UISlider! var blurRadiusValue:CGFloat = 0.0 var tintColorValue = UIColor.clearColor() var saturationValue:CGFloat = 1.0 // 0.0 = desaturated, 1.0 = saturated @IBAction func selectBlur(sender: AnyObject) { selectBlurMenu() } @IBAction func sliderUpdate(sender: AnyObject) { blurRadiusValue = CGFloat(slider.value) applyBlur() } func selectBlurMenu() { let actionSheet = AHKActionSheet(title: "Options") actionSheet.buttonTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()] actionSheet.blurTintColor = UIColor(white: 0.1, alpha: 0.9) actionSheet.addButtonWithTitle("No tint", type: .Default) { (_as) -> Void in self.tintColorValue = UIColor.clearColor() self.applyBlur() } actionSheet.addButtonWithTitle("Dark Tint", type: .Default) { (_as) -> Void in self.tintColorValue = UIColor(white: 0.11, alpha: 0.73) self.applyBlur() } actionSheet.addButtonWithTitle("Light Tint", type: .Default) { (_as) -> Void in self.tintColorValue = UIColor(white: 1.0, alpha: 0.3) self.applyBlur() } actionSheet.addButtonWithTitle("Black and White", type: .Default) { (_as) -> Void in self.saturationValue = 0.0 self.applyBlur() } actionSheet.addButtonWithTitle("Color", type: .Default) { (_as) -> Void in self.saturationValue = 1.0 self.applyBlur() } actionSheet.addButtonWithTitle("Save", type: .Default) { (_as) -> Void in self.savePhoto() } actionSheet.show() } func applyBlur() { var newImage = userImage.image?.applyBlurWithRadius(blurRadiusValue, tintColor: tintColorValue, saturationDeltaFactor: saturationValue, maskImage: nil) blurImage.image = newImage blurImage.hidden = false } func savePhoto() { UIImageWriteToSavedPhotosAlbum(blurImage.image, nil, nil, nil) RKDropdownAlert.title("Image saved!", backgroundColor: UIColor.blackColor(), textColor: UIColor.whiteColor()) } func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) { self.dismissViewControllerAnimated(true, completion: { () -> Void in }) userImage.image = image blurImage.hidden = true } @IBAction func selectPhoto(sender: AnyObject) { if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.SavedPhotosAlbum){ imagePicker.delegate = self imagePicker.sourceType = UIImagePickerControllerSourceType.SavedPhotosAlbum; imagePicker.allowsEditing = false self.presentViewController(imagePicker, animated: true, completion: nil) } } override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(animated: Bool) { UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.LightContent super.viewWillAppear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
// // CityPickerView.swift // SwiftTool // // Created by liujun on 2021/5/24. // Copyright © 2021 yinhe. All rights reserved. // import Foundation import UIKit fileprivate struct _SelectionLocation { let firstSelectedIndex: Int let secondSelectedIndex: Int let thirdSelectedIndex: Int } public final class CityPickerView: UIView { deinit { removeNotification() #if DEBUG print("\(NSStringFromClass(self.classForCoder)) deinit") #endif } public enum PickerType { case province_city_district /// 省、市、区 case province_city /// 省、市 case province /// 省 } /// 选择类型 public var cityPickerType: CityPickerView.PickerType = .province_city_district /// 默认选中的地区名字集合 public var defaultSelectAreaNames: [String]? /// 默认选中的地区`ID`集合 public var defaultSelectAreaIds: [String]? /// 数据源 public private(set) var cityModels: [CityModel] = [] /// 当前选中`Model` public private(set) var currentSelectModel: CityModel? /// DEBUG模式下是否开启日志打印 public var enableDebugLog: Bool = false /// 数据源 /// /// 数据源的设置要在其他属性设置的最前面 public var titlesForComponents: [[String]]? /// 文本颜色 /// /// 当`titlesForComponents`不为空时,有效 public var titleColor: UIColor = .black /// 文本字体 /// /// 当`titlesForComponents`不为空时,有效 public var titleFont: UIFont = UIFont.boldSystemFont(ofSize: 17) /// 分割线颜色 /// /// `iOS 14`之后,`UIPickerView`没有分割线了,取而代之的是显示在中间的一个选中背景`view` public var separatorLineColor: UIColor = UIColor.gray.withAlphaComponent(0.4) { didSet { setNeedsLayout() layoutIfNeeded() } } /// `toolBar` /// /// 可以传入自定义的`view`,当为`nil`时,将使用`defaultToolBar` public var toolBar: UIView? /// 框架默认的`toolBar` public private(set) lazy var defaultToolBar: PickerToolBar = { let toolBar = PickerToolBar() return toolBar }() /// 工具栏高度 public var toolBarHeight: CGFloat = 49.0 { didSet { invalidateIntrinsicContentSize() AlertEngine.default.refresh() } } private lazy var pickerView: UIPickerView = { let pickerView = UIPickerView() pickerView.dataSource = self pickerView.delegate = self return pickerView }() /// `UIPickerView`实时变化的回调 private var currentSelectRowClosure: (([Int])->())? { didSet { self.currentSelectRowClosure?(self.currentSelectIndexs) } } /// 手动触发`UIPickerView`滚动结束停止后的回调 public var didSelectRowClosure: ((Int, Int)->())? private var doneClosure: (([Int])->())? private var currentSelectIndexs: [Int] = [] private var beforeSelectIndexs: [Int] = [] public init() { super.init(frame: .zero) addNotification() setupUI() addAction() } public override init(frame: CGRect) { super.init(frame: frame) addNotification() setupUI() addAction() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } public override func layoutSubviews() { super.layoutSubviews() if #available(iOS 13.4, *) { // } else { self.pickerView.subviews.forEach { (view) in if view.isKind(of: UIPickerView.classForCoder()) { view.subviews.forEach({ (view1) in if view1.frame.height.isLessThanOrEqualTo(1.0) { view1.backgroundColor = self.separatorLineColor } }) } } } } public override var intrinsicContentSize: CGSize { self.pickerView.sizeToFit() let height = self.toolBarHeight + self.pickerView.bounds.height return CGSize(width: GL.deviceWidth, height: height) } } extension CityPickerView { private func setupUI() { backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 1) // 白色 if let toolBar = toolBar { addSubview(toolBar) addSubview(pickerView) toolBar.snp.makeConstraints { make in make.left.top.right.equalToSuperview() make.height.equalTo(toolBarHeight) } pickerView.snp.makeConstraints { make in make.left.right.equalTo(toolBar) make.bottom.equalToSuperview() make.top.equalTo(toolBar.snp.bottom) } } else { addSubview(defaultToolBar) addSubview(pickerView) defaultToolBar.snp.makeConstraints { make in make.left.top.equalToSuperview() make.width.equalTo(GL.deviceWidth) make.height.equalTo(toolBarHeight) } pickerView.snp.makeConstraints { make in make.left.right.equalTo(defaultToolBar) make.bottom.equalToSuperview() make.top.equalTo(defaultToolBar.snp.bottom) } } } private func addAction() { self.defaultToolBar.cancelButton.addTarget(self, action: #selector(cancelAction), for: .touchUpInside) self.defaultToolBar.sureButton.addTarget(self, action: #selector(sureAction), for: .touchUpInside) } private func handleDatasource(dataSource: [[String: Any]]) { self.cityModels.removeAll() // dataSource.forEach { (d) in let model = CityModel(with: d) self.cityModels.append(model) } if self.enableDebugLog { self.printCityData() } // let location = self.check() self.currentSelectModel = self.cityModels[location.firstSelectedIndex] let firstTitles = self.cityModels.map{ "\($0.areaName)" } let secondModels = self.currentSelectModel?.nexts ?? [] let secondTitles = secondModels.map{ "\($0.areaName)" } let thirdModels = secondModels[location.secondSelectedIndex].nexts let thirdTitles = thirdModels.map{ "\($0.areaName)" } switch self.cityPickerType { case .province_city_district: self.titlesForComponents = [firstTitles, secondTitles, thirdTitles] self.currentSelectIndexs = [0, 0, 0] self.reloadAllComponents() self.selectRow(location.firstSelectedIndex, inComponent: 0, animated: true) self.selectRow(location.secondSelectedIndex, inComponent: 1, animated: true) self.selectRow(location.thirdSelectedIndex, inComponent: 2, animated: true) self.reloadAllComponents() self.beforeSelectIndexs = [location.firstSelectedIndex, location.secondSelectedIndex, location.thirdSelectedIndex] case .province_city: self.titlesForComponents = [firstTitles, secondTitles] self.currentSelectIndexs = [0, 0] self.reloadAllComponents() self.selectRow(location.firstSelectedIndex, inComponent: 0, animated: true) self.selectRow(location.secondSelectedIndex, inComponent: 1, animated: true) self.reloadAllComponents() self.beforeSelectIndexs = [location.firstSelectedIndex, location.secondSelectedIndex] case .province: self.titlesForComponents = [firstTitles] self.currentSelectIndexs = [0] self.reloadAllComponents() self.selectRow(location.firstSelectedIndex, inComponent: 0, animated: true) self.reloadAllComponents() self.beforeSelectIndexs = [location.firstSelectedIndex] } self.didSelectRowClosure = { [weak self] (component, row) in guard let self = self else { return } if self.beforeSelectIndexs[component] == row { return } self.beforeSelectIndexs[component] = row self.reloadWhenSelect(component: component, row: row) } } private func reloadWhenSelect(component: Int, row: Int) { switch self.cityPickerType { case .province_city_district: switch component { case 0: self.currentSelectModel = self.cityModels[row] let secondModels = self.currentSelectModel?.nexts ?? [] let secondTitles = secondModels.map{ "\($0.areaName)" } let thirdModels = secondModels.first?.nexts ?? [] let thirdTitles = thirdModels.map{ "\($0.areaName)" } self.titlesForComponents?[1] = secondTitles self.titlesForComponents?[2] = thirdTitles self.selectRow(0, inComponent: 1, animated: true) self.selectRow(0, inComponent: 2, animated: true) self.reload(component: 1) self.reload(component: 2) case 1: let secondModel = self.currentSelectModel?.nexts[row] let thirdTitles = secondModel?.nexts.map{ "\($0.areaName)" } self.titlesForComponents?[2] = thirdTitles ?? [] self.selectRow(0, inComponent: 2, animated: true) self.reload(component: 2) default: break } case .province_city: switch component { case 0: self.currentSelectModel = self.cityModels[row] let secondModels = self.currentSelectModel?.nexts ?? [] let secondTitles = secondModels.map{ "\($0.areaName)" } self.titlesForComponents?[1] = secondTitles self.selectRow(0, inComponent: 1, animated: true) self.reload(component: 1) default: break } default: break } } private func check() -> _SelectionLocation { var defaultFirstSelectedIndex: Int = 0 var defaultSecondSelectedIndex: Int = 0 var defaultThirdSelectedIndex: Int = 0 // if let defaultSelectAreaNames = self.defaultSelectAreaNames { switch self.cityPickerType { case .province_city_district: if defaultSelectAreaNames.count != 3 { return _SelectionLocation(firstSelectedIndex: defaultFirstSelectedIndex, secondSelectedIndex: defaultSecondSelectedIndex, thirdSelectedIndex: defaultThirdSelectedIndex) } for (i, m1) in self.cityModels.enumerated() { if m1.areaName == defaultSelectAreaNames[0] { defaultFirstSelectedIndex = i for (j, m2) in m1.nexts.enumerated() { if m2.areaName == defaultSelectAreaNames[1] { defaultSecondSelectedIndex = j for (k, m3) in m2.nexts.enumerated() { if m3.areaName == defaultSelectAreaNames[2] { defaultThirdSelectedIndex = k break } } break } } break } } case .province_city: if defaultSelectAreaNames.count != 2 { return _SelectionLocation(firstSelectedIndex: defaultFirstSelectedIndex, secondSelectedIndex: defaultSecondSelectedIndex, thirdSelectedIndex: defaultThirdSelectedIndex) } for (i, m1) in self.cityModels.enumerated() { if m1.areaName == defaultSelectAreaNames[0] { defaultFirstSelectedIndex = i for (j, m2) in m1.nexts.enumerated() { if m2.areaName == defaultSelectAreaNames[1] { defaultSecondSelectedIndex = j break } } break } } case .province: if defaultSelectAreaNames.count != 1 { return _SelectionLocation(firstSelectedIndex: defaultFirstSelectedIndex, secondSelectedIndex: defaultSecondSelectedIndex, thirdSelectedIndex: defaultThirdSelectedIndex) } for (i, m1) in self.cityModels.enumerated() { if m1.areaName == defaultSelectAreaNames[0] { defaultFirstSelectedIndex = i break } } } } else if let defaultSelectAreaIds = self.defaultSelectAreaIds { switch self.cityPickerType { case .province_city_district: if defaultSelectAreaIds.count != 3 { return _SelectionLocation(firstSelectedIndex: defaultFirstSelectedIndex, secondSelectedIndex: defaultSecondSelectedIndex, thirdSelectedIndex: defaultThirdSelectedIndex) } for (i, m1) in self.cityModels.enumerated() { if m1.areaId == defaultSelectAreaIds[0] { defaultFirstSelectedIndex = i for (j, m2) in m1.nexts.enumerated() { if m2.areaId == defaultSelectAreaIds[1] { defaultSecondSelectedIndex = j for (k, m3) in m2.nexts.enumerated() { if m3.areaId == defaultSelectAreaIds[2] { defaultThirdSelectedIndex = k break } } break } } break } } case .province_city: if defaultSelectAreaIds.count != 2 { return _SelectionLocation(firstSelectedIndex: defaultFirstSelectedIndex, secondSelectedIndex: defaultSecondSelectedIndex, thirdSelectedIndex: defaultThirdSelectedIndex) } for (i, m1) in self.cityModels.enumerated() { if m1.areaId == defaultSelectAreaIds[0] { defaultFirstSelectedIndex = i for (j, m2) in m1.nexts.enumerated() { if m2.areaId == defaultSelectAreaIds[1] { defaultSecondSelectedIndex = j break } } break } } case .province: if defaultSelectAreaIds.count != 1 { return _SelectionLocation(firstSelectedIndex: defaultFirstSelectedIndex, secondSelectedIndex: defaultSecondSelectedIndex, thirdSelectedIndex: defaultThirdSelectedIndex) } for (i, m1) in self.cityModels.enumerated() { if m1.areaId == defaultSelectAreaIds[0] { defaultFirstSelectedIndex = i break } } } } return _SelectionLocation(firstSelectedIndex: defaultFirstSelectedIndex, secondSelectedIndex: defaultSecondSelectedIndex, thirdSelectedIndex: defaultThirdSelectedIndex) } private func printCityData() { var infos: [[String: Any]] = [] for (_, model) in self.cityModels.enumerated() { infos.append(model.info()) } let objct = NSString(format: "%@", infos as NSArray) print("\(objct)") } private func addNotification() { NotificationCenter.default.addObserver(self, selector: #selector(orientationDidChange), name: UIApplication.didChangeStatusBarOrientationNotification, object: nil) } private func removeNotification() { NotificationCenter.default.removeObserver(self, name: UIApplication.didChangeStatusBarOrientationNotification, object: nil) } private func update() { if let toolBar = toolBar { toolBar.snp.remakeConstraints { make in make.left.top.equalToSuperview() make.width.equalTo(GL.deviceWidth) make.height.equalTo(toolBarHeight) } pickerView.snp.remakeConstraints { make in make.left.right.equalTo(toolBar) make.bottom.equalToSuperview() make.top.equalTo(toolBar.snp.bottom) } } else { defaultToolBar.snp.remakeConstraints { make in make.left.top.equalToSuperview() make.width.equalTo(GL.deviceWidth) make.height.equalTo(toolBarHeight) } pickerView.snp.remakeConstraints { make in make.left.right.equalTo(defaultToolBar) make.bottom.equalToSuperview() make.top.equalTo(defaultToolBar.snp.bottom) } } } private func getResult() { var results: [Int] = [] for component in 0..<self.pickerView.numberOfComponents { let selectRow = self.pickerView.selectedRow(inComponent: component) results.append(selectRow) } self.currentSelectIndexs = results self.currentSelectRowClosure?(self.currentSelectIndexs) self.doneClosure?(results) } } extension CityPickerView { /// 显示城市选择器 /// /// let cityPickerView = CityPickerView() /// cityPickerView.enableDebugLog = true /// cityPickerView.cityPickerType = .province_city_district /// cityPickerView.defaultSelectAreaNames = ["四川省", "成都市", "双流县"] /// cityPickerView.show { [weak cityPickerView] selectIndexs in /// print("selectIndexs:\(selectIndexs)") /// guard let cityPickerView = cityPickerView else { return } /// guard let currentSelectModel = cityPickerView.currentSelectModel else { return } /// switch cityPickerView.cityPickerType { /// case .province_city_district: /// let secondIndex = selectIndexs[1] /// let thirdIndex = selectIndexs[2] /// let province = currentSelectModel.areaName /// let cityModel = currentSelectModel.nexts[secondIndex] /// let city = cityModel.areaName /// let districtModel = cityModel.nexts[thirdIndex] /// let district = districtModel.areaName /// print("\(province) - \(city) - \(district)") /// case .province_city: /// let secondIndex = selectIndexs[1] /// let province = currentSelectModel.areaName /// let cityModel = currentSelectModel.nexts[secondIndex] /// let city = cityModel.areaName /// print("\(province) - \(city)") /// case .province: /// let province = currentSelectModel.areaName /// print("\(province)") /// } /// } currentSelectRowClosure: { indexes in /// print("indexes: \(indexes)") /// } public func show(doneClosure: (([Int])->())?, currentSelectRowClosure: (([Int])->())? = nil) { guard let window = UIApplication.shared.keyWindow else { return } // guard let datas = CityData.gl.jsonDecode as? [[String: Any]] else { return } self.handleDatasource(dataSource: datas) // self.doneClosure = doneClosure self.currentSelectRowClosure = currentSelectRowClosure // let options = AlertEngine.Options() options.fromPosition = .bottomCenter(top: .zero) options.toPosition = .bottomCenter(bottom: .zero) options.dismissPosition = .bottomCenter(top: .zero) options.translucentColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0).withAlphaComponent(0.4) // AlertEngine.default.show(parentView: window, alertView: self, options: options) } } extension CityPickerView { @objc private func sureAction() { getResult() AlertEngine.default.dismiss() } @objc private func cancelAction() { AlertEngine.default.dismiss() } @objc private func orientationDidChange() { invalidateIntrinsicContentSize() update() } } extension CityPickerView { /// 刷新所有列 public func reloadAllComponents() { pickerView.reloadAllComponents() } /// 刷新某一列 public func reload(component: Int) { pickerView.reloadComponent(component) } /// 选中某一列的某一行 /// /// 该方法不会执行`didSelectRow`方法。已经对`row`和`component`进行了纠错处理 public func selectRow(_ row: Int, inComponent component: Int, animated: Bool) { var row = row var component = component if component < 0 { component = 0 } else if let titlesForComponents = titlesForComponents, component >= titlesForComponents.count { component = titlesForComponents.count - 1 } if let titlesForComponents = titlesForComponents { let rows = titlesForComponents[component] if row < 0 { row = 0 } else if row >= rows.count { row = rows.count - 1 } } if titlesForComponents == nil { return } if let titlesForComponents = titlesForComponents, titlesForComponents.count <= 0 { return } pickerView.selectRow(row, inComponent: component, animated: animated) if let titlesForComponents = titlesForComponents { if currentSelectIndexs.count < titlesForComponents.count { return } } if component <= currentSelectIndexs.count { currentSelectIndexs[component] = row } self.currentSelectRowClosure?(currentSelectIndexs) } } extension CityPickerView: UIPickerViewDataSource, UIPickerViewDelegate { public func numberOfComponents(in pickerView: UIPickerView) -> Int { if let titlesForComponents = self.titlesForComponents { return titlesForComponents.count } return 0 } public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { if let titlesForComponents = self.titlesForComponents { return titlesForComponents[component].count } return 0 } public func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView { let label = UILabel() if let titlesForComponents = self.titlesForComponents { let title = titlesForComponents[component][row] label.textAlignment = .center label.textColor = self.titleColor label.font = self.titleFont label.text = title label.adjustsFontSizeToFitWidth = true } return label } public func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { //print(" component:\(component) -- row: \(row)") if component <= self.currentSelectIndexs.count { self.currentSelectIndexs[component] = row } self.currentSelectRowClosure?(self.currentSelectIndexs) self.didSelectRowClosure?(component, row) } }
// // TokenResponse.swift // MostActivePosts // // Created by Eugene Lobyr on 4/16/19. // Copyright © 2019 Eugene Lobyr. All rights reserved. // class TokenResponse: Codable { /// Your access token let accessToken: String /// The string "bearer" let tokenType: String /// A unique, per-device ID generated by your client. See note below. Only for https://oauth.reddit.com/grants/installed_client requests. let deviceId: String /// Seconds until the token expires let expiresIn: Double /// The scope of the token let scope: String enum CodingKeys: String, CodingKey { case accessToken = "access_token" case tokenType = "token_type" case deviceId = "device_id" case expiresIn = "expires_in" case scope } }
//Solution goes in Sources import Foundation typealias Second = Int typealias Year = Double enum Planet: Year { case earth = 365.25 case mercury = 0.2408467 case venus = 0.61519726 case mars = 1.8808158 case jupiter = 11.862615 case saturn = 29.447498 case uranus = 84.016846 case neptune = 164.79132 } struct SpaceAge { let seconds: Second var onEarth: Year { return convert(ageInseconds: seconds, planet: .earth) } var onMercury: Year { return convert(ageInseconds: seconds, planet: .mercury) } var onVenus: Year { return convert(ageInseconds: seconds, planet: .venus) } var onMars: Year { return convert(ageInseconds: seconds, planet: .mars) } var onJupiter: Year { return convert(ageInseconds: seconds, planet: .jupiter) } var onSaturn: Year { return convert(ageInseconds: seconds, planet: .saturn) } var onUranus: Year { return convert(ageInseconds: seconds, planet: .uranus) } var onNeptune: Year { return convert(ageInseconds: seconds, planet: .neptune) } init(_ seconds: Second) { self.seconds = seconds } private func convert(ageInseconds: Second, planet: Planet) -> Year { let day = 60 * 60 * 24 var result = Double(ageInseconds) / Double(day) var earthDaysPerYear: Year switch planet { case .earth: earthDaysPerYear = planet.rawValue default: earthDaysPerYear = planet.rawValue * Planet.earth.rawValue } var value = result.roundToTheNearest(100) / Double(earthDaysPerYear) return value.roundToTheNearest(100) } } extension Double { mutating func roundToTheNearest(_ decimal: Double) -> Double { return Darwin.round(self * decimal) / decimal } }
// // ContentView.swift // GuessTheFlag // // Created by Vikram Ho on 10/22/20. // import SwiftUI //struct ContentView: View { // var body: some View { // ZStack(alignment: .center){ // Color(red: 1, green: 0.8, blue: 2).frame(width: 200, height: 200, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/) // Text("First") // } // .background(Color.red) // // } //} struct Title: ViewModifier{ func body(content: Content) -> some View{ content .foregroundColor(.white) .padding() .background(Color.black) .clipShape(RoundedRectangle(cornerRadius: 10)) } } struct watermark: ViewModifier{ var text:String func body(content:Content) -> some View{ ZStack(alignment: .bottomTrailing){ content Text(text) .font(.caption) .foregroundColor(.white) .padding(5) .background(Color.black) } } } extension View{ func watermark(with text:String) -> some View{ self.modifier(GuessTheFlag.watermark(text: text)) } } extension View{ func titleStyle() -> some View{ self.modifier(Title()) } } struct FlagImage :View{ let country: String var body: some View{ Image(country) .renderingMode(.original) .clipShape(Capsule()) .overlay(Capsule().stroke(Color.black, lineWidth: 4)) .shadow(color:.black, radius: 2) } } struct ContentView: View{ @State private var countries = ["Estonia", "France", "Germany", "Ireland", "Italy", "Nigeria", "Poland", "Russia", "Spain", "UK", "US"] @State private var correctAns = Int.random(in: 0...2) @State private var showingScore = false @State private var scoreTitle = "" @State private var score = 0 @State private var spreeCounter = 0 @State private var onASpree = false @State private var animationAmount = 0.0 @State private var rotationAmount = 0.0 @State var attempts: Int = 0 var body: some View{ ZStack{ LinearGradient(gradient: Gradient(colors: [.blue,.black]), startPoint: .top, endPoint: .bottom ).edgesIgnoringSafeArea(.all) .watermark(with: "Created by Vikram") VStack(spacing: 20){ VStack(spacing: 40){ Text("Tap the flag off") .foregroundColor(.white) Text(countries[correctAns]) .foregroundColor(.white) .font(.largeTitle) .fontWeight(.black) ForEach(0..<3){ number in Button(action: { self.flagTapped(number) }) { FlagImage(country: self.countries[number]) } // if a correct flag is tapped rotate the flag .rotation3DEffect(.degrees(number == self.correctAns ? self.rotationAmount : 0), axis: (x: 0, y: 1, z: 0)) .opacity(self.showingScore && number != self.correctAns ? 0.25 : 1) } .modifier(Shake(animatableData: CGFloat(self.attempts))) Text("Current score is: \(score)") .titleStyle() Spacer() } } } .alert(isPresented: $showingScore){ if onASpree == false{ return Alert(title: Text(scoreTitle), message: Text("Your score is: \(score) "), dismissButton: .default(Text("Continue")){ self.askQuestion() }) }else{ return Alert(title: Text(scoreTitle), message: Text("Your score is: \(score). You are on a winning spree!"), dismissButton: .default(Text("Continue")){ self.askQuestion() }) } } } func flagTapped(_ number:Int){ if number == correctAns{ scoreTitle = "Correct" score = score + 1 spreeCounter = spreeCounter + 1 if(spreeCounter > 3){ onASpree = true } withAnimation(.spring()){ self.rotationAmount += 360 } }else{ scoreTitle = "Wrong, that's the country of: \(countries[number])" if(score > 0){ score = score - 1 } spreeCounter = 0 onASpree = false withAnimation(.default){ attempts += 9 } } showingScore = true } func askQuestion(){ countries.shuffle() correctAns = Int.random(in: 0...2) attempts = 0 } } struct Shake: GeometryEffect{ var amount: CGFloat = 10 var shakesPerUnit = 3 var animatableData: CGFloat func effectValue(size: CGSize) -> ProjectionTransform { ProjectionTransform(CGAffineTransform(translationX: amount * sin(animatableData * .pi * CGFloat(shakesPerUnit)), y: 0)) } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
// // FeedImageCell.swift // MVP // // Created by Stas Lee on 12/3/19. // Copyright © 2019 Stas Lee. All rights reserved. // import Foundation import UIKit public final class FeedImageCell: UITableViewCell { @IBOutlet weak var authorLabel: UILabel! @IBOutlet weak var feedImageContainer: UIView! @IBOutlet weak var feedImageView: UIImageView! @IBOutlet weak var timeAgoLabel: UILabel! @IBOutlet weak var descriptionLabel: UILabel! }
// // PrincipalViewController.swift // nano4 // // Created by Gustavo Rigor on 29/05/20. // Copyright © 2020 Gustavo Rigor. All rights reserved. // import Foundation import UIKit class Principal: UIViewController, UITableViewDataSource, UITableViewDelegate{ @IBOutlet weak var imgRelogio: UIImageView! @IBOutlet weak var telaPrincipalLabel: UILabel! @IBOutlet weak var horasMesTabView: UITableView! @IBOutlet weak var TotalHoras: UILabel! let notificacao = Notification.Name(rawValue: "atualizarEstilo") let notificacao1 = Notification.Name(rawValue: "novoFilme") let meses = ["Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"] deinit { NotificationCenter.default.removeObserver(self) } func observer(){ NotificationCenter.default.addObserver(self, selector: #selector(self.atualizaTelaEstilo(notificacao:)), name: notificacao, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(self.atualizaQtdFilme(notificacao:)), name: notificacao1, object: nil) } @objc func atualizaTelaEstilo(notificacao: NSNotification){ print("a notificacao chegou") atualizarEstilo() } @objc func atualizaQtdFilme(notificacao: NSNotification){ print("a notificacao chegou1") carregaBancoDeDados() atualizaHorasTotais() } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return meses.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell") let aux = meses[indexPath.row] if isDarkMode{ cell?.backgroundColor = .some(#colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)) cell?.textLabel?.textColor = .some(#colorLiteral(red: 0.8039215803, green: 0.8039215803, blue: 0.8039215803, alpha: 1)) cell?.detailTextLabel?.textColor = .some(#colorLiteral(red: 0.8039215803, green: 0.8039215803, blue: 0.8039215803, alpha: 1)) }else{ cell?.backgroundColor = .some(#colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)) cell?.textLabel?.textColor = .some(#colorLiteral(red: 0.3333333433, green: 0.3333333433, blue: 0.3333333433, alpha: 1)) cell?.detailTextLabel?.textColor = .some(#colorLiteral(red: 0.3333333433, green: 0.3333333433, blue: 0.3333333433, alpha: 1)) } if aux == "Junho"{ cell?.textLabel?.text = aux cell?.detailTextLabel?.text = minutosToHora(Int(minutosTotais())) return cell! } cell?.textLabel?.text = aux cell?.detailTextLabel?.text = "0h 0" return cell! } let appDelegate = UIApplication.shared.delegate as! AppDelegate override func viewDidLoad() { super.viewDidLoad() observer() carregaBancoDeDados() atualizaHorasTotais() carregarPreferenciasEstilo() print(UserDefaults.standard.bool(forKey: "taSalvo")) print(UserDefaults.standard.object(forKey: "NomeUsuario") ?? " ") } override func viewDidAppear(_ animated: Bool) { super.viewWillAppear(animated) atualizarTabela() carregarPreferenciasEstilo() } func minutosTotais() -> Int32{ var aux:Int32 = 0 if dataSourceArray.count != 0 { for x in 0...(dataSourceArray.count-1){ aux = aux + dataSourceArray[x].duracao } } return aux } func minutosToHora(_ x : Int) -> String { if x < 60 { return "0h \(x)" } return "\(x/60)h \(x%60)" } func carregaBancoDeDados(){ dataSourceArray = appDelegate.fetchRecords() print("Minutos totais: \(minutosTotais())") } func atualizaHorasTotais(){ TotalHoras.text = minutosToHora(Int(minutosTotais())) } func atualizarEstilo(){ if isDarkMode{ self.view.backgroundColor = .some(#colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)) self.imgRelogio.tintColor = .some(#colorLiteral(red: 0.8039215803, green: 0.8039215803, blue: 0.8039215803, alpha: 1)) self.TotalHoras.textColor = .some(#colorLiteral(red: 0.8039215803, green: 0.8039215803, blue: 0.8039215803, alpha: 1)) self.telaPrincipalLabel.textColor = .some(#colorLiteral(red: 0.8039215803, green: 0.8039215803, blue: 0.8039215803, alpha: 1)) self.horasMesTabView.backgroundColor = .some(#colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)) }else{ self.view.backgroundColor = .some(#colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)) self.imgRelogio.tintColor = .some(#colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)) self.TotalHoras.textColor = .some(#colorLiteral(red: 0.3333333433, green: 0.3333333433, blue: 0.3333333433, alpha: 1)) self.telaPrincipalLabel.textColor = .some(#colorLiteral(red: 0.3333333433, green: 0.3333333433, blue: 0.3333333433, alpha: 1)) self.horasMesTabView.backgroundColor = .some(#colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)) } atualizarTabela() } func carregarPreferenciasEstilo(){ let preferencia = UserDefaults.standard.bool(forKey: "DarkMode") if preferencia{ isDarkMode = true atualizarEstilo() } } func atualizarTabela(){ horasMesTabView.reloadData() } }
// // FeedTCell.swift // SWAVE // // Created by San Byn Nguyen on 7/12/19. // Copyright © 2019 San Byn Nguyen. All rights reserved. // import UIKit @IBDesignable class FeedTCell: UITableViewCell { @IBOutlet weak var topicLbl: UILabel! @IBOutlet weak var messageLbl: UILabel! @IBOutlet weak var timeLbl: UILabel! @IBOutlet weak var view: UIView! func configure(feed: Feed) { topicLbl.text = feed.topic messageLbl.text = feed.message + "\n" timeLbl.text = "\(feed.hours_left)h" } override func awakeFromNib() { super.awakeFromNib() dashedBorder() } override func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() dashedBorder() } func dashedBorder() { } }
// // ViewController.swift // Guardianes Monarca // // Created by Juan David Torres on 9/1/19. // Copyright © 2019 Juan David Torres. All rights reserved. // import UIKit class SplashViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // // // Show the selected screen // let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil) // // // Instantiate the selected screen view controller // let nextViewController: UIViewController = storyboard.instantiateViewController(withIdentifier: "LoginViewController") // // // Every storyboard must have a NavigationController named "MainNavigation" // let navigationController = storyboard.instantiateViewController(withIdentifier: "MainNavigation") as! UINavigationController // navigationController.setViewControllers([nextViewController], animated: true) // // // Present the navigaton controller and within it, the view controller // self.present(navigationController, animated: false) DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+3){ self.performSegue(withIdentifier: "LoginViewController", sender: nil) } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } }
// // day7.swift // AdventOfCode // // Created by Robbie Plankenhorn on 4/28/16. // Copyright © 2016 Plankenhorn.net. All rights reserved. // import Foundation private typealias CommandValue = UInt16 private var registers: [String:[String]] = [:] private var values:[String:CommandValue] = [:] private func commands() -> [String] { return readInputFile("day7_input")!.componentsSeparatedByString("\n") } func day7Part1() -> UInt16 { registers = [:] values = [:] for command in commands() { let tokens = command.componentsSeparatedByString(" -> ") registers[tokens.last!] = tokens.first!.componentsSeparatedByString(" ") } return calculate("a") } func day7Part2() -> UInt16 { let signalA = day7Part1() registers = [:] values = [:] for command in commands() { let tokens = command.componentsSeparatedByString(" -> ") registers[tokens.last!] = tokens.first!.componentsSeparatedByString(" ") } registers["b"] = [String(signalA)] return calculate("a") } private func calculate(wire:String) -> CommandValue { if let value = values[wire] { return value } if let value = CommandValue(wire) { return value } let command = registers[wire]! let value:CommandValue if command.contains("AND") { value = calculate(command.first!) & calculate(command.last!) } else if command.contains("OR") { value = calculate(command.first!) | calculate(command.last!) } else if command.contains("LSHIFT") { value = calculate(command.first!) << calculate(command.last!) } else if command.contains("RSHIFT") { value = calculate(command.first!) >> calculate(command.last!) } else if command.contains("NOT") { value = ~(calculate(command.last!)) } else { value = calculate(command.first!) } values[wire] = value return value }
// // DynamicRow.swift // DynamicTableViewRowsDemo // // Created by Subash Poudel on 2/11/17. // Copyright © 2017 leapfrog. All rights reserved. // import UIKit protocol DynamicRow: class { func getCellFor(_ tableView: UITableView, indexPath: IndexPath) -> UITableViewCell func didSelectRow() } // empty implementation so that only intrested cells need to worry about this function extension DynamicRow { func didSelectRow() { } }
// // ViewController.swift // GitHubRepositoryViewer // // Created by AtsuyaSato on 2017/04/03. // Copyright © 2017年 Atsuya Sato. All rights reserved. // import UIKit import APIKit import RxSwift import RxCocoa class ViewController: UIViewController, UITableViewDelegate, UISearchBarDelegate { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var searchBar: UISearchBar! private let viewModel = ListViewModel() let disposeBag = DisposeBag() override func viewDidLoad() { super.viewDidLoad() searchBar.delegate = self tableView.delegate = self tableView.dataSource = viewModel bind() } func bind() { // Connection viewModel.repos.asObservable().filter { x in return !x.isEmpty }.subscribe(onNext: { [unowned self] x in self.tableView.reloadData() }, onError: { error in }, onCompleted: { () in }, onDisposed: { () in }).addDisposableTo(disposeBag) //search searchBar.rx.text .subscribe(onNext: { [unowned self] q in self.navigationItem.title = q! self.viewModel.reloadData(userName: q!) }, onError: { error in }, onCompleted: { () in }, onDisposed: { () in }).addDisposableTo(disposeBag) } // MARK: - TableView func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 130 } // MARK: - SearchBar func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { searchBar.resignFirstResponder() } func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { searchBar.resignFirstResponder() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
// // DetailOpeningCell.swift // stckchck // // Created by Pho on 05/10/2018. // Copyright © 2018 stckchck. All rights reserved. // import Foundation import UIKit import IGListKit class DetailOpeningCell: UICollectionViewCell, ListBindable { var openingTimes: String? @IBOutlet weak var openingTimesTextView: UITextView! func bindViewModel(_ viewModel: Any) { guard let viewModel = viewModel as? DetailOpeningVM else { print("deadBeef IGLK failed to make dOpeningVM") return } openingTimes = viewModel.openingTimes guard let openingTimes = openingTimes else { print("deadBeef no opening times") return } let formattedOpeningTimes = openingTimes.replacingOccurrences(of: ", ", with: "\r\n") openingTimesTextView.text = formattedOpeningTimes } }
// // TFLLineSearch-Cell.swift // Brunel // // Created by Aaron McTavish on 21/01/2016. // Copyright © 2016 ustwo Fampany Ltd. All rights reserved. // import UIKit extension TFLLineSearch: SearchableTableItem { func configureTableViewCell(_ cell: UITableViewCell) { cell.textLabel?.text = name cell.contentView.backgroundColor = color if color.isLight() { cell.textLabel?.textColor = UIColor.black } else { cell.textLabel?.textColor = UIColor.white } cell.accessibilityIdentifier = AccessibilityIdentifiers.Lines.LineCellPrefix + "_\(name)" } func searchableStrings() -> [String] { return [name, mode.description] } }
// // CharacterExpensiveComicViewController.swift // desafio-ios-gabriel-leal // // Created by Gabriel Sousa on 05/04/20. // Copyright © 2020 Gabriel Sousa. All rights reserved. // import UIKit class CharacterExpensiveComicViewController: UIViewController { //**************************************************************** // MARK: - Private Properties //**************************************************************** @IBOutlet var tableView: UITableView! //**************************************************************** // MARK: - Public Properties //**************************************************************** var viewModel: CharacterExpensiveComicViewModel! = nil //**************************************************************** // MARK: - Life Cicle //**************************************************************** override func viewDidLoad() { super.viewDidLoad() registerNibs() setDelegates() } //**************************************************************** // MARK: - Private Methods //**************************************************************** private func setDelegates() { tableView.dataSource = self tableView.delegate = self } private func registerNibs() { let nib = UINib(nibName: "CharacterExpensiveComicCell", bundle: nil) tableView.register(nib, forCellReuseIdentifier: "CharacterExpensiveComicCell") } } //**************************************************************** // MARK: - TableView DataSource/Delegate //**************************************************************** extension CharacterExpensiveComicViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "CharacterExpensiveComicCell", for: indexPath) as! CharacterExpensiveComicTableViewCell cell.setupViewModel(model: viewModel.expensiveComic, service: Services()) return cell } } //**************************************************************** // MARK: - StatusBar //**************************************************************** extension CharacterExpensiveComicViewController { override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } }
// // DateExtension.swift // BankApp // // Created by Hai Le Thanh on 12/1/18. // Copyright © 2018 Hai Le Thanh. All rights reserved. // import Foundation extension Date { func numberOfDaysSinceNow() -> String { let days = Calendar.current.dateComponents([.day], from: self, to: Date()).day if let days = days { switch days { case 0: return "Today" case 1: return "Yesterday" default: return "\(days) Days Ago" } } else { return "" } } func numberOfDaysSince(date: Date) -> Int { return Calendar.current.dateComponents([.day], from: self, to: date).day ?? 0 } }
// // Reachability.swift // GV24 // // Created by HuyNguyen on 6/23/17. // Copyright © 2017 admin. All rights reserved. // import Foundation import Foundation import SystemConfiguration import Alamofire class NetworkStatus { static let sharedInstance = NetworkStatus() private init() {} let reachabilityManager = Alamofire.NetworkReachabilityManager(host: "https://www.google.com") func startNetworkReachabilityObserver() { reachabilityManager?.listener = { status in switch status { case .notReachable: print("The network is not reachable") case .unknown : print("It is unknown whether the network is reachable") case .reachable(.ethernetOrWiFi): print("The network is reachable over the WiFi connection") case .reachable(.wwan): print("The network is reachable over the WWAN connection") } } reachabilityManager?.startListening() } }
// // RowBasicStyle.swift // SpaceX // // Created by Carmelo Ruymán Quintana Santana on 25/2/21. // import SwiftUI struct RowMission: View { let mission: Mission var body: some View { VStack(alignment: .leading, spacing: 8, content: { Text(mission.name).font(.title3) Text(mission.description).lineLimit(2).opacity(0.8).font(.footnote) }) .padding() .background(Color.white) } } // struct RowBasicStyle_Previews: PreviewProvider { // static var previews: some View { // RowBasicStyle() // } // }
// // ViewController.swift // VirtualCourses // // Created by Emanuel Flores Martínez on 31/03/21. // import UIKit import Firebase class CoursesViewController: UIViewController { @IBOutlet weak var greetLabel: UILabel! @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var Spinner: UIActivityIndicatorView! private let db = Firestore.firestore() var courses: [Course] = [] let cellScale: CGFloat = 1.0 override func viewDidLoad() { super.viewDidLoad() Spinner.startAnimating() Spinner.hidesWhenStopped = true collectionView.dataSource = self greeting() let screenSize = UIScreen.main.bounds.size let cellWidth = floor(screenSize.width * cellScale) let cellHeight = floor(screenSize.height * cellScale) let insetX = (view.bounds.width - cellWidth) / 2.0 let insetY = (view.bounds.height - cellHeight) / 10.0 let layout = collectionView!.collectionViewLayout as! UICollectionViewFlowLayout layout.itemSize = CGSize(width: cellWidth, height: cellHeight) collectionView.contentInset = UIEdgeInsets(top: insetY, left: insetX, bottom: insetY, right: insetX) self.getAllCoures() // Spinner.stopAnimating() } func getAllCoures() { let userEmail = Auth.auth().currentUser?.email db.collection("courses").whereField("owner", isEqualTo: userEmail!) .addSnapshotListener{ (querySnapshot, error) in self.courses.removeAll() if let error = error { print(error) }else { for document in querySnapshot!.documents { let course = document.data() let courseName = course["courseName"] as! String let description = course["description"] as! String let schedule = course["schedule"] as! String let linkClass = course["linkClass"] as! String let urlImage = URL(string: course["urlImage"] as! String) guard let data = try? Data(contentsOf: urlImage!) else { return } print("AQUI:", courseName, linkClass ?? "") self.courses.append(Course(courseName: courseName, description: description, schedule: schedule, linkClass: linkClass, imageCourse: UIImage(data: data)!)) DispatchQueue.main.async { self.collectionView.reloadData() } } self.Spinner.stopAnimating() } } } func greeting() { CoursesService.getName { (name) in if let name = name{ print("Este es el nombre: \(name)") self.greetLabel.text = "Hola, \(name)" } } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.isNavigationBarHidden = true } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) navigationController?.isNavigationBarHidden = false } @IBAction func logOutPressed(_ sender: Any) { do { try Auth.auth().signOut() navigationController?.popToRootViewController(animated: true) } catch let signOutError as NSError { print(signOutError) } } } // MARK: - UICollectionViewDataSource extension CoursesViewController: UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return courses.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CourseCollectionViewCell", for: indexPath) as! CourseCollectionViewCell let course = courses[indexPath.item] cell.course = course return cell } }
// // Copyright © 2018 Netguru Sp. z o.o. All rights reserved. // Licensed under the MIT License. // import Foundation internal extension String { /// Validates if String is a proper shoretened UUID which means its 4 or 6 characters long and contains only hexadecimal characters. func isValidShortenedUUID() -> Bool { var evaluation = self if hasPrefix("0x") { evaluation = evaluation.replacingOccurrences(of: "0x", with: "") } return isHexadecimal && (evaluation.count == 4 || evaluation.count == 6) } /// Checks if string contains only hexadecimal characters. var isHexadecimal: Bool { let invertedHexCharacterSet = NSCharacterSet(charactersIn: "0123456789ABCDEF").inverted return uppercased().rangeOfCharacter(from: invertedHexCharacterSet) == nil } } /// String extension allowing conversion of strings like 0x2A01 into Data with the same format. internal extension String { /// Returns Data with decoded string. func hexDecodedData() throws -> Data { guard isHexadecimal else { throw Command.ConversionError.incorrectInputFormat } var data = Data(capacity: count / 2) let regex = try! NSRegularExpression(pattern: "[0-9a-f]{1,2}", options: .caseInsensitive) regex.enumerateMatches(in: self, range: NSMakeRange(0, utf16.count)) { match, _, _ in guard let nsRange = match?.range, let range = Range(nsRange, in: self) else { return } let byteString = self[range] guard var num = UInt8(byteString, radix: 16) else { return } data.append(&num, count: 1) } return data } }
import UIKit // MARK: Decorators protocol ViewDecorator { associatedtype View: UIView func decorate(view: View) } struct RoundViewDecorator: ViewDecorator { typealias View = UIView func decorate(view: UIView) { view.layer.cornerRadius = 12 view.layer.backgroundColor = .init(gray: 1, alpha: 1) } } struct TextFieldViewDecorator: ViewDecorator { typealias View = UITextField func decorate(view: UITextField) { let decorator = RoundViewDecorator() decorator.decorate(view: view) view.textColor = .white view.font = .systemFont(ofSize: 20) view.tintColor = .white setupAttributedPlaceholder(for: view) } private func setupAttributedPlaceholder(for view: UITextField) { if let placeholder = view.placeholder { let attributes = [NSAttributedString.Key.foregroundColor: UIColor.white] view.attributedPlaceholder = NSAttributedString(string: placeholder, attributes: attributes) } } } struct CredentialTextFieldViewDecorator: ViewDecorator { typealias View = UITextField func decorate(view: UITextField) { let decorator = TextFieldViewDecorator() decorator.decorate(view: view) view.autocapitalizationType = .none view.autocorrectionType = .no } } struct SecureTextFieldViewDecorator: ViewDecorator { typealias View = UITextField func decorate(view: UITextField) { let decorator = CredentialTextFieldViewDecorator() decorator.decorate(view: view) view.isSecureTextEntry = true } } struct ButtonViewDecorator: ViewDecorator { typealias View = UIButton func decorate(view: UIButton) { view.titleLabel?.font = .boldSystemFont(ofSize: 14) view.layer.cornerRadius = 26 view.clipsToBounds = true view.setTitleColor(.purple, for: .normal) } } // MARK: Example let button = UIButton() let decorator = ButtonViewDecorator() decorator.decorate(view: button) // Functional example: https://github.com/pointfreeco/episode-code-samples/blob/main/0003-styling-with-functions/Styling%20with%20Functions.playground/Pages/Complete.xcplaygroundpage/Contents.swift
// // InitializeResult.swift // SwiftLanguageServerLib // // Created by Koray Koska on 03.04.18. // import Foundation public struct InitializeResult: Codable { /** * The capabilities the language server provides. */ public let capabilities: ServerCapabilities } public enum InitializeErrorCode: Int, Error, Codable { case unknownProtocolVersion = 1 } public struct InitializeErrorData: Codable { /** * Indicates whether the client execute the following retry logic: * (1) show the message provided by the ResponseError to the user * (2) user selects retry or cancel * (3) if user selected retry the initialize method is sent again. */ public let retry: Bool }
// // CalendarViewController.swift // EzOrder(Cus) // // Created by 李泰儀 on 2019/5/19. // Copyright © 2019 TerryLee. All rights reserved. // import UIKit import JTAppleCalendar class CalendarViewController: UIViewController { @IBOutlet weak var showEventTableView: UITableView! @IBOutlet weak var dateLabel: UILabel! @IBOutlet weak var calendarView: JTAppleCalendarView! // @IBOutlet weak var eventTableView: UITableView! var now = Date() var selectDateText = "" var eventDic = [String : [String]]() let dateFormatter: DateFormatter = DateFormatter() override func viewDidLoad() { super.viewDidLoad() self.title = "行事曆" // 讓app一啟動就是今天的日曆 calendarView.scrollToDate(now, animateScroll: false) // 讓今天被選取 calendarView.selectDates([now]) // 設定日曆屬性(水平/垂直滑)、滑動方式 calendarView.scrollDirection = .horizontal calendarView.scrollingMode = .stopAtEachCalendarFrame calendarView.showsHorizontalScrollIndicator = false self.title = "行事曆" dateLabel.text = "2019-01" // 寫死今天有三項訂位 selectDateText = dateFormatter.string(from: now) print(selectDateText) eventDic = ["2019-05-15" : ["12:00 全家", "17:00 711"], "2019-04-15" : ["12:00 馬辣", "17:00 新馬辣"], "2019-03-15" : ["12:00 屋馬", "17:00 大呼過癮"], "2019-02-15" : ["12:00 三媽", "22:00 老四川"], "2019-01-15" : ["12:00 麥當勞", "22:00 肯德基"]] } } extension CalendarViewController: JTAppleCalendarViewDataSource, JTAppleCalendarViewDelegate{ func configureCalendar(_ calendar: JTAppleCalendarView) -> ConfigurationParameters { // 設定dateFormatter格式 /* 這邊比viewdidload先執行,所以可以在這邊設定dateFormatter格式 */ dateFormatter.dateFormat = "yyyy-MM-dd" dateFormatter.locale = Locale.current dateFormatter.timeZone = TimeZone.current // 設定日曆起始日期和最終日期 let startDate = dateFormatter.date(from: "2019-01-01")! let endDate = dateFormatter.date(from: "2030-02-01")! return ConfigurationParameters(startDate: startDate, endDate: endDate, generateInDates: .forAllMonths, generateOutDates: .tillEndOfGrid) } /* cellForItemAt 和 willDisplay 裡面要放的東西幾乎一樣 除了 cell 在 cellForItemAt 要做重複利用(dequeueReusableJTAppleCell) */ // 每一格cell要呈現的日期 func calendar(_ calendar: JTAppleCalendarView, cellForItemAt date: Date, cellState: CellState, indexPath: IndexPath) -> JTAppleCell { let cell = calendar.dequeueReusableJTAppleCell(withReuseIdentifier: "dateCell", for: indexPath) as! DateCell self.calendar(calendar, willDisplay: cell, forItemAt: date, cellState: cellState, indexPath: indexPath) return cell } func calendar(_ calendar: JTAppleCalendarView, willDisplay cell: JTAppleCell, forItemAt date: Date, cellState: CellState, indexPath: IndexPath) { configureCell(view: cell, cellState: cellState) } // 滑動日曆的話 func calendar(_ calendar: JTAppleCalendarView, didScrollToDateSegmentWith visibleDates: DateSegmentInfo) { // 讓 navigation 的 title 顯示現在的年跟月 let formatter: DateFormatter = DateFormatter() formatter.dateFormat = "yyyy-MM" if let slideYearMonth = visibleDates.monthDates.first?.date{ let yearMonth = formatter.string(from: slideYearMonth) dateLabel.text = "\(yearMonth)" } } // 選取日期的話 func calendar(_ calendar: JTAppleCalendarView, didSelectDate date: Date, cell: JTAppleCell?, cellState: CellState) { // 判斷是不是點第二次,如果是點兩次的話跳出細項 // let cell = cell as! DateCell configureCell(view: cell, cellState: cellState) selectDateText = dateFormatter.string(from: date) // eventTableView.reloadData() print(selectDateText) // 讓標籤改成選取到的日期 dateLabel.text = selectDateText showEventTableView.reloadData() } // 取消選取的話 func calendar(_ calendar: JTAppleCalendarView, didDeselectDate date: Date, cell: JTAppleCell?, cellState: CellState) { configureCell(view: cell, cellState: cellState) } func configureCell(view: JTAppleCell?, cellState: CellState) { guard let cell = view as? DateCell else{return} cell.dateLabel.text = cellState.text handleCellTextColor(cell: cell, cellState: cellState) handleCellSelected(cell: cell, cellState: cellState) handleCellEvents(cell: cell, cellState: cellState) } // 讓不是這個月的日期變灰色 func handleCellTextColor(cell: DateCell, cellState: CellState) { if cellState.dateBelongsTo == .thisMonth { cell.dateLabel.textColor = .black cell.isHidden = false } else { cell.dateLabel.textColor = .lightGray } } // 按日期讓日期上有粉色的圓圈 func handleCellSelected(cell: DateCell, cellState: CellState) { if cellState.isSelected { cell.selectedView.isHidden = false } else { cell.selectedView.isHidden = true } } // 日期裡有事件的話,在日期下方標示 func handleCellEvents(cell: DateCell, cellState: CellState) { let everyCellDayDate = dateFormatter.string(from: cellState.date) if eventDic[everyCellDayDate] == nil{ cell.dotView.isHidden = true } else { cell.dotView.isHidden = false } } } extension CalendarViewController: UITableViewDelegate, UITableViewDataSource{ func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let eventArray = eventDic[selectDateText]{ return eventArray.count } return 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell cell.restaurantLabel.text = "" cell.timeLabel.text = "" cell.restaurantLabel.text = "" tableView.separatorStyle = .none if let eventArray = eventDic[selectDateText]{ tableView.separatorStyle = .singleLine tableView.separatorColor = .lightGray if eventArray.isEmpty{ cell.restaurantLabel.text = "" } else{ cell.timeLabel.text = selectDateText cell.restaurantLabel.text = eventArray[indexPath.row] } } return cell } }
// // LivePresentationOnlineCell.swift // UIDebugging // // Created by Xu on 2020/11/5. // import UIKit class LivePresentationOnlineCell: UITableViewCell { @IBOutlet weak var index: UILabel! @IBOutlet weak var headImage: UIImageView! @IBOutlet weak var userName: UILabel! @IBOutlet weak var tickets: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code index.textColor = .app_main_content tickets.textColor = .app_main_thinRed userName.textColor = .app_main_title headImage.layer.cornerRadius = 15 userName.text = "一夜暴富" headImage.backgroundColor = .gray tickets.text = "9527票" } func buildUI() { } }
// // TodayViewController.swift // WeatherApp // // Created by webwerks on 07/08/19. // Copyright © 2019 Priya Gupta. All rights reserved. // import UIKit import XLPagerTabStrip class TodayViewController: UIViewController { //MARK:- Varible declaration @IBOutlet weak var mainLbl: UILabel! @IBOutlet weak var todayTblView: UITableView! @IBOutlet weak var tempLbl: UILabel! @IBOutlet weak var descLbl: UILabel! var weatherViewModel = WeatherViewModel() var todayParams : [String:String]? //MARK:- View life cycle override func viewDidLoad() { super.viewDidLoad() setUpTableView() // Do any additional setup after loading the view. } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(true) self.todayParams = FORCAST_MANAGER.locationParamsDict if todayParams != nil{ getTodayWeatherData(parameter: todayParams!) } } // MARK:- Helper function private func setUpTableView(){ todayTblView.register(UINib(nibName: TodayTableViewCell.cellIdentifier(),bundle:nil), forCellReuseIdentifier: TodayTableViewCell.cellIdentifier()) } private func configUI(){ self.tempLbl.text = self.weatherViewModel.getTemp() + "°C" self.descLbl.text = self.weatherViewModel.getDesc() self.mainLbl.text = self.weatherViewModel.getMainWeatherValue() } //MARK:- API functionality private func getTodayWeatherData(parameter : [String : String]){ weatherViewModel.fetchWeatherData(for: parameter) { (status) in if status == 1 { self.configUI() self.todayTblView.reloadData() } } } } //MARK:- XLPager functionality extension TodayViewController :IndicatorInfoProvider{ func indicatorInfo(for pagerTabStripController: PagerTabStripViewController) -> IndicatorInfo { return IndicatorInfo(title: "Today") } } //MARK:- UITableView datasource & delegate extension TodayViewController : UITableViewDataSource{ func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return COMMON_SETTINGS.nameArray.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: TodayTableViewCell = tableView.dequeueReusableCell(withIdentifier: TodayTableViewCell.cellIdentifier(), for: indexPath) as! TodayTableViewCell cell.nameLbl.text = COMMON_SETTINGS.nameArray[indexPath.row] let image = COMMON_SETTINGS.weatherImgArray[indexPath.row] cell.imgView.image = UIImage(named: image) if let weatherResponse = self.weatherViewModel.responseData{ cell.configCell(weatherData: weatherResponse, indexPath: indexPath.row) } return cell } }