text
stringlengths
8
1.32M
// // Data.swift // weatherOrNot // // Created by John Gibson on 9/3/19. // Copyright © 2019 John Gibson. All rights reserved. // import Foundation class Data { static var locationModels = [LocationData]() }
import AudioKit import AudioKitUI import AVFoundation import SoundpipeAudioKit import SwiftUI struct KorgLowPassFilterData { var cutoffFrequency: AUValue = 1_000.0 var resonance: AUValue = 1.0 var saturation: AUValue = 0.0 var rampDuration: AUValue = 0.02 var balance: AUValue = 0.5 } class KorgLowPassFilterConductor: ObservableObject, ProcessesPlayerInput { let engine = AudioEngine() let player = AudioPlayer() let filter: KorgLowPassFilter let dryWetMixer: DryWetMixer let buffer: AVAudioPCMBuffer init() { buffer = Cookbook.sourceBuffer player.buffer = buffer player.isLooping = true filter = KorgLowPassFilter(player) dryWetMixer = DryWetMixer(player, filter) engine.output = dryWetMixer } @Published var data = KorgLowPassFilterData() { didSet { filter.$cutoffFrequency.ramp(to: data.cutoffFrequency, duration: data.rampDuration) filter.$resonance.ramp(to: data.resonance, duration: data.rampDuration) filter.$saturation.ramp(to: data.saturation, duration: data.rampDuration) dryWetMixer.balance = data.balance } } func start() { do { try engine.start() } catch let err { Log(err) } } func stop() { engine.stop() } } struct KorgLowPassFilterView: View { @StateObject var conductor = KorgLowPassFilterConductor() var body: some View { ScrollView { PlayerControls(conductor: conductor) ParameterSlider(text: "Cutoff Frequency", parameter: self.$conductor.data.cutoffFrequency, range: 0.0...22_050.0, units: "Hertz") ParameterSlider(text: "Resonance", parameter: self.$conductor.data.resonance, range: 0.0...2.0, units: "Generic") ParameterSlider(text: "Saturation", parameter: self.$conductor.data.saturation, range: 0.0...10.0, units: "Generic") ParameterSlider(text: "Mix", parameter: self.$conductor.data.balance, range: 0...1, units: "%") DryWetMixView(dry: conductor.player, wet: conductor.filter, mix: conductor.dryWetMixer) } .padding() .navigationBarTitle(Text("Korg Low Pass Filter")) .onAppear { self.conductor.start() } .onDisappear { self.conductor.stop() } } } struct KorgLowPassFilter_Previews: PreviewProvider { static var previews: some View { KorgLowPassFilterView() } }
// // TimelineAnimationTypedExtension.swift // TimelineAnimations // // Created by Georges Boumis on 11/01/2017. // Copyright © 2017 AbZorba Games. All rights reserved. // import Foundation import QuartzCore fileprivate extension Optional { fileprivate func unwrap(defaultValue value: Wrapped) -> Wrapped { if let v = self { return v } else { return value } } } public extension TimelineAnimation { public typealias Radians = Double public enum Transition { public enum Subtype { case fromRight case fromLeft case fromTop case fromBottom internal var value: CATransitionSubtype { switch self { case TimelineAnimation.Transition.Subtype.fromRight: return CATransitionSubtype.fromRight case TimelineAnimation.Transition.Subtype.fromLeft: return CATransitionSubtype.fromLeft case TimelineAnimation.Transition.Subtype.fromTop: return CATransitionSubtype.fromTop case TimelineAnimation.Transition.Subtype.fromBottom: return CATransitionSubtype.fromBottom } } } case fade case moveIn(subtype: TimelineAnimation.Transition.Subtype) case push(subtype: TimelineAnimation.Transition.Subtype) case reveal(subtype: TimelineAnimation.Transition.Subtype) var transition: CATransition { let transition = CATransition() switch self { case TimelineAnimation.Transition.fade: transition.type = CATransitionType.fade case let TimelineAnimation.Transition.moveIn(subtype): transition.type = CATransitionType.moveIn transition.subtype = subtype.value case let TimelineAnimation.Transition.push(subtype): transition.type = CATransitionType.push transition.subtype = subtype.value case let TimelineAnimation.Transition.reveal(subtype): transition.type = CATransitionType.reveal transition.subtype = subtype.value } return transition } } } public extension TimelineAnimation { public enum TimingFunction: UInt { case Default = 0 case linear case easeIn case easeOut case easeInOut case sineIn case sineOut case sineInOut case quadIn case quadOut case quadInOut case cubicIn case cubicOut case cubicInOut case quartIn case quartOut case quartInOut case quintIn case quintOut case quintInOut case expoIn case expoOut case expoInOut case circIn case circOut case circInOut case backIn case backOut case backInOut // special case elasticIn case elasticOut case elasticInOut case bounceIn case bounceOut case bounceInOut private var isSpecial: Bool { return (self == TimelineAnimation.TimingFunction.elasticIn) || (self == TimelineAnimation.TimingFunction.elasticOut) || (self == TimelineAnimation.TimingFunction.elasticInOut) || (self == TimelineAnimation.TimingFunction.bounceIn) || (self == TimelineAnimation.TimingFunction.bounceOut) || (self == TimelineAnimation.TimingFunction.bounceInOut) } public var customTimingFunction: ECustomTimingFunction { return ECustomTimingFunction(rawValue: self.rawValue)! } } } public extension TimelineAnimation { public enum Animation { case move(from: CGPoint?, to: CGPoint?, timingFunction: TimelineAnimation.TimingFunction?) case fade(from: CGFloat?, to: CGFloat?, timingFunction: TimelineAnimation.TimingFunction?) case fadeIn(timingFunction: TimelineAnimation.TimingFunction?) case fadeOut(timingFunction: TimelineAnimation.TimingFunction?) case hide case unhide case scale(from: CGFloat?, to: CGFloat?, timingFunction: TimelineAnimation.TimingFunction?) case scaleX(from: CGFloat?, to: CGFloat?, timingFunction: TimelineAnimation.TimingFunction?) case scaleY(from: CGFloat?, to: CGFloat?, timingFunction: TimelineAnimation.TimingFunction?) case rotate(from: TimelineAnimation.Radians?, to: TimelineAnimation.Radians?, timingFunction: TimelineAnimation.TimingFunction?) case rotateY(from: TimelineAnimation.Radians?, to: TimelineAnimation.Radians?, timingFunction: TimelineAnimation.TimingFunction?) case shadowOpacity(from: CGFloat?, to: CGFloat?, timingFunction: TimelineAnimation.TimingFunction?) case strokeStart(from: CGFloat?, to: CGFloat?, timingFunction: TimelineAnimation.TimingFunction?) case strokeEnd(from: CGFloat?, to: CGFloat?, timingFunction: TimelineAnimation.TimingFunction?) case transform(from: CATransform3D?, to: CATransform3D?, timingFunction: TimelineAnimation.TimingFunction?) case custom(apply: () -> CAPropertyAnimation) } } public extension TimelineAnimation.Animation { public var animation: CAPropertyAnimation { var anim: CAPropertyAnimation! switch self { case let TimelineAnimation.Animation.move(from, to, tf): anim = AnimationsFactory.move(fromPoint: from, toPoint: to, timingFunction: tf.unwrap(defaultValue: TimelineAnimation.TimingFunction.linear).customTimingFunction) case let TimelineAnimation.Animation.fade(from, to, tf): anim = AnimationsFactory.fade(fromOpacity: from, toOpacity: to, timingFunction: tf.unwrap(defaultValue: TimelineAnimation.TimingFunction.linear).customTimingFunction) case let TimelineAnimation.Animation.fadeIn(tf): anim = AnimationsFactory.fadeIn(timingFunction: tf.unwrap(defaultValue: TimelineAnimation.TimingFunction.linear).customTimingFunction) case let TimelineAnimation.Animation.fadeOut(tf): anim = AnimationsFactory.fadeOut(timinFunction: tf.unwrap(defaultValue: TimelineAnimation.TimingFunction.linear).customTimingFunction) case let TimelineAnimation.Animation.scale(from, to, tf): anim = AnimationsFactory.scale(from: from, to: to, timingFunction: tf.unwrap(defaultValue: TimelineAnimation.TimingFunction.linear).customTimingFunction) case let TimelineAnimation.Animation.scaleX(from, to, tf): anim = AnimationsFactory.scaleX(from: from, to: to, timingFunction: tf.unwrap(defaultValue: TimelineAnimation.TimingFunction.linear).customTimingFunction) case let TimelineAnimation.Animation.scaleY(from, to, tf): anim = AnimationsFactory.scaleY(from: from, to: to, timingFunction: tf.unwrap(defaultValue: TimelineAnimation.TimingFunction.linear).customTimingFunction) case let TimelineAnimation.Animation.rotate(from, to, tf): let _from = (from == nil) ? nil : CGFloat(from!) let _to = (to == nil) ? nil : CGFloat(to!) anim = AnimationsFactory.animate(keyPath: AnimationKeyPath.rotation, fromValue: _from.asTypedValue, toValue: _to.asTypedValue, timingFunction: tf.unwrap(defaultValue: TimelineAnimation.TimingFunction.linear).customTimingFunction) case let TimelineAnimation.Animation.rotateY(from, to, tf): let _from = (from == nil) ? nil : CGFloat(from!) let _to = (to == nil) ? nil : CGFloat(to!) anim = AnimationsFactory.animate(keyPath: AnimationKeyPath.rotationY, fromValue: _from.asTypedValue, toValue: _to.asTypedValue, timingFunction: tf.unwrap(defaultValue: TimelineAnimation.TimingFunction.linear).customTimingFunction) case let TimelineAnimation.Animation.transform(from, to, tf): anim = AnimationsFactory.animate(keyPath: AnimationKeyPath.transform, fromValue: from.asTypedValue, toValue: to.asTypedValue, timingFunction: tf.unwrap(defaultValue: TimelineAnimation.TimingFunction.linear).customTimingFunction) case TimelineAnimation.Animation.hide: anim = AnimationsFactory.animate(keyPath: AnimationKeyPath.isHidden, fromValue: false.asTypedValue, toValue: true.asTypedValue, timingFunction: TimelineAnimation.TimingFunction.linear.customTimingFunction) case TimelineAnimation.Animation.unhide: anim = AnimationsFactory.animate(keyPath: AnimationKeyPath.isHidden, fromValue: true.asTypedValue, toValue: false.asTypedValue, timingFunction: TimelineAnimation.TimingFunction.linear.customTimingFunction) case let TimelineAnimation.Animation.shadowOpacity(from, to, tf): anim = AnimationsFactory.animate(keyPath: AnimationKeyPath.shadowOpacity, fromValue: from.asTypedValue, toValue: to.asTypedValue, timingFunction: tf.unwrap(defaultValue: TimelineAnimation.TimingFunction.linear).customTimingFunction) case let TimelineAnimation.Animation.strokeStart(from, to, tf): anim = AnimationsFactory.animate(keyPath: AnimationKeyPath.strokeStart, fromValue: from.asTypedValue, toValue: to.asTypedValue, timingFunction: tf.unwrap(defaultValue: TimelineAnimation.TimingFunction.linear).customTimingFunction) case let TimelineAnimation.Animation.strokeEnd(from, to, tf): anim = AnimationsFactory.animate(keyPath: AnimationKeyPath.strokeEnd, fromValue: from.asTypedValue, toValue: to.asTypedValue, timingFunction: tf.unwrap(defaultValue: TimelineAnimation.TimingFunction.linear).customTimingFunction) case let TimelineAnimation.Animation.custom(application): anim = application() } return anim } } public extension TimelineAnimation { /// Inserts an animation in the TimelineAnimation for the provided layer at the given time. /// /// - Parameter animation: a `TimelineAnimation.Animation` to be applied to the layer /// - Parameter layer: the layer whose property is to be animated in the TimelineAnimation /// - Parameter time: the time, in the TimelineAnimation's relative time (seconds), to insert the animation. If not provided equals to 0. /// - Parameter duration: the duration this animation has. If not provided equals to 1. /// - Parameter onStart: an optional block to be called on the beginning of the animation /// - Parameter onComplete: an optional block to be called when the animation completes /// /// - Precondition: the animation is not `nil`. /// - Precondition: the layer is not `nil`. /// - Precondition: the timeline has not started. /// - Throws: /// `NSInvalidArgumentException` if either `layer` on `animation` are `nil`. /// `ImmutableTimelineAnimationException` if called on an ongoing timeline. /// `TimelineAnimationConflictingAnimationsException` if the animation is conflicting with existing animations in the timeline. /// public func insert(animation: TimelineAnimation.Animation, forLayer layer: CALayer, atTime time: RelativeTime = RelativeTime(0.0), withDuration duration: TimeInterval = TimeInterval(1.0), onStart: TimelineAnimation.VoidBlock? = nil, onComplete: TimelineAnimation.BoolBlock? = nil) { self.insert(animation: animation.animation, forLayer: layer, atTime: time, withDuration: duration, onStart: onStart, onComplete: onComplete) } } public extension TimelineAnimation { /// Appends an animation at the end of the timeline, after a delay /// /// - Parameter animation: a `TimelineAnimation.Animation` to be applied to the layer /// - Parameter layer: the layer whose property is to be animated in the TimelineAnimation /// - Parameter duration: the duration this animation has. If not provided equals to 1. /// - Parameter delay: the delay, must be >= 0.0, in seconds. If not provided equals to 0.0 /// - Parameter onStart: an optional block to be called on the beginning of the animation /// - Parameter onComplete: an optional block to be called when the animation completes /// /// - Precondition: the `animation` is not `nil`. /// - Precondition: the `layer` is not `nil`. /// - Precondition: the `timeline` has not started. /// - Throws: /// `NSInvalidArgumentException` if either `layer` on `animation` are `nil`. /// `ImmutableTimelineAnimationException` if called on an ongoing timeline. /// `TimelineAnimationConflictingAnimationsException` if the animation is conflicting with existing animations in the timeline. /// public func add(animation: TimelineAnimation.Animation, forLayer layer: CALayer, withDuration duration: TimeInterval = TimeInterval(1.0), withDelay delay: RelativeTime = RelativeTime(0.0), onStart: TimelineAnimation.VoidBlock? = nil, onComplete: TimelineAnimation.BoolBlock? = nil) { self.add(animation: animation.animation, forLayer: layer, withDelay: delay, withDuration: duration, onStart: onStart, onComplete: onComplete) } } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertToOptionalCATransitionSubtype(_ input: String?) -> CATransitionSubtype? { guard let input = input else { return nil } return CATransitionSubtype(rawValue: input) }
// // WYUserAccount.swift // wy // // Created by chu on 03/04/2018. // Copyright © 2018 chu. All rights reserved. // import Foundation import YYModel private let accountFile: NSString = "useraccount.json" class WYUserAccount: NSObject { @objc var uid: String? @objc var name: String? @objc var loginpw: String? @objc var avatar: String? @objc var gender: String? @objc var mobile: String? @objc var college: String? @objc var major: String? @objc var level: String? override var description: String{ return yy_modelDescription() } func saveAccount(){ let dict = (self.yy_modelToJSONObject() as? [String:String]) ?? [:] print(dict) guard let data = try? JSONSerialization.data(withJSONObject: dict, options: []), let filePath = accountFile.cz_appendDocumentDir() else{ return } (data as NSData).write(toFile: filePath, atomically: true) print("保存成功\(filePath)") } override init() { super.init() //加载保存文件 guard let path = accountFile.cz_appendDocumentDir(), let data = NSData(contentsOfFile: path), let dict = try? JSONSerialization.jsonObject(with: data as Data, options: []) as? [String:AnyObject] else{ return } yy_modelSet(with: dict ?? [:]) print("沙盒") } }
import UIKit class ViewController: UIViewController { let viewModel = ViewModel() @IBOutlet weak var categoryTableView: UITableView! override func viewDidLoad() { super.viewDidLoad() viewModel.configureTableView(tableView: categoryTableView) viewModel.updateArray() } }
import UIKit class TransactionDetailSwitchCell: UITableViewCell { @IBOutlet weak var overrideTextLabel : UILabel? @IBOutlet weak var detailSwitch : UISwitch? override var textLabel: UILabel? { return self.overrideTextLabel } var detailTextChanged : ((String) -> ())? } extension TransactionDetailSwitchCell : TransactionDetailViewDataItemConfigurable, TransactionDetailViewDataItemEditable { func configure(transactionDetailViewDataItem item: TransactionDetailViewDataItem) { self.textLabel?.text = item.title self.detailSwitch?.isOn = (item.detail != nil && item.detail! != "") } func showDetailTextField() { } func hideDetailTextField() { } } extension TransactionDetailSwitchCell { @IBAction func switchChanged(_ sender: AnyObject?) { if let detailSwitch = sender as? UISwitch { let text = (detailSwitch.isOn) ? "enabled" : "" self.detailTextChanged?(text) } } }
// // HouseholdMemberCellViewModel.swift // Choreboard // // Created by Joseph Delle Donne on 4/13/21. // import Foundation struct HouseholdMemberCellViewModel { let name: String let points: Int let pictureURL: String let user: Member }
// // Created by Utkarsh Phirke // Copyright © 2018 CakeSoft. All rights reserved. // import CoreLocation protocol RegionProtocol { var coordinate: CLLocation {get} var radius: CLLocationDistance {get} var identifier: String {get} func updateRegion() }
// // MainControllerTableViewController.swift // SwiftAFNetworkingDemo // // Created by Richard Lee on 8/14/14. // Copyright (c) 2014 Weimed. All rights reserved. // import UIKit import CoreLocation class MainController: UITableViewController, UIActionSheetDelegate, WeatherHTTPClientDelegate, CLLocationManagerDelegate { // Properties var weather: NSDictionary = [:] var locationManager: CLLocationManager? = nil override func viewDidLoad() { super.viewDidLoad() // Initial location manager self.locationManager = CLLocationManager() if CLLocationManager.locationServicesEnabled() { NSLog("Staring CLLocationManager") switch(CLLocationManager.authorizationStatus()) { case CLAuthorizationStatus.NotDetermined: // User has not yet made a choice with regards to this application NSLog("User has not yet made a choice") break case CLAuthorizationStatus.Restricted: // This application is not authorized to use location services. Due // to active restrictions on location services, the user cannot change // this status, and may not have personally denied authorization NSLog("This application is not authorized to use location services.") break case CLAuthorizationStatus.Denied: // User has explicitly denied authorization for this application, or // location services are disabled in Settings NSLog("User has explicitly denied authorization for this application.") break case CLAuthorizationStatus.Authorized: // User has authorized this application to use location services NSLog("User has authorized this application to use location services") break default: break } self.locationManager?.delegate = self self.locationManager?.distanceFilter = 200 self.locationManager?.desiredAccuracy = kCLLocationAccuracyBest } else { NSLog("Cann't staring CLLocationManager") } // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillAppear(animated: Bool) { // Display toolbar self.navigationController.setToolbarHidden(false, animated: true) } override func viewWillDisappear(animated: Bool) { // Hide toolbar self.navigationController.setToolbarHidden(true, animated: true) } @IBAction func clear(sender: AnyObject) { self.title = "" self.weather = [:] self.tableView.reloadData() } @IBAction func actionTapped(sender: AnyObject) { var actionSheet = UIActionSheet(title: "AFHTTPSessionManager", delegate: self, cancelButtonTitle: "Cancel", destructiveButtonTitle: nil) actionSheet.addButtonWithTitle("HTTP GET") actionSheet.addButtonWithTitle("HTTP POST") //actionSheet.addButtonWithTitle("HTTP PUT") //actionSheet.addButtonWithTitle("HTTP DELETE") actionSheet.addButtonWithTitle("Test SubClass") // Refer to https://medium.com/@aommiez/afnetwork-integrate-swfit-80514b545b40 actionSheet.showFromBarButtonItem(sender as UIBarButtonItem, animated: true) } // #pragma mark - UIActionSheetDelegate func actionSheet(actionSheet: UIActionSheet!, clickedButtonAtIndex buttonIndex: Int) { // actionSheet.cancelButtonIndex = 0 if buttonIndex == 0 { return } NSLog("the index is %d", buttonIndex) var baseURL = NSURL(string: "http://www.raywenderlich.com/demos/weather_sample/") var parameters = ["format": "json"] var manager = AFHTTPSessionManager(baseURL: baseURL) manager.responseSerializer = AFJSONResponseSerializer() //manager.requestSerializer.setValue(“608c6c08443c6d933576b90966b727358d0066b4", forHTTPHeaderField: “X-Auth-Token”) if buttonIndex == 1 { manager.GET("weather.php", parameters: parameters, success: { (task: NSURLSessionDataTask!, responseObject: AnyObject!) -> Void in self.weather = responseObject as NSDictionary self.title = "JSON GETTED" NSLog(self.weather.description) self.tableView.reloadData() }, failure: { ( task: NSURLSessionDataTask!, error: NSError!) -> Void in NSLog("GET failed: %@", error) var alert = UIAlertController(title: "Error Retrieving Weather", message: error.localizedDescription, preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) }) } else if buttonIndex == 2 { manager.POST("weather.php", parameters: parameters, success: { (task: NSURLSessionDataTask!, responseObject: AnyObject!) -> Void in self.weather = responseObject as NSDictionary self.title = "JSON POSTED" NSLog(self.weather.description) self.tableView.reloadData() }, failure: { ( task: NSURLSessionDataTask!, error: NSError!) -> Void in NSLog("POST failed: %@", error) var alert = UIAlertController(title: "Error Retrieving Weather", message: error.localizedDescription, preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) // Handle actions within Alert /*alert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { action in switch action.style{ case .Default: println("default") break case .Cancel: println("cancel") break case .Destructive: println("destructive") break } }))*/ }) } else if buttonIndex == 3 { NSLog("Starting update location") self.locationManager!.startUpdatingLocation() } } // #pragma mark - CLLocationManagerDelegate func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) { // Last object contains the most recent location var newLocation = locations.last as CLLocation // If the location is more than 5 minutes old, ignore it if newLocation.timestamp.timeIntervalSinceNow > 300 { return } self.locationManager!.stopUpdatingLocation() var client = WeatherHTTPClient.sharedInstance client.delegate = self client.updateWeatherAtLocation(location: newLocation, forNumberOfDays: 5) } // #pragma mark - WeatherHTTPClientDelegate func weatherHTTPClient(#client: WeatherHTTPClient, didUpdateWithWeather weather: AnyObject) { self.weather = weather as NSDictionary self.title = "API Updated" self.tableView.reloadData() } func weatherHTTPClient(#client: WeatherHTTPClient, didFailWithError error: NSError) { var alert = UIAlertController(title: "Error Retrieving Weather", message: error.localizedDescription, preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView!) -> Int { // Return the number of sections. return 2 } override func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int { // Return the number of rows in the section. if self.weather.count == 0 { return 0 } switch section { case 0: return 1 case 1: let upcomingWeather = self.weather["data"]["weather"] as NSArray return upcomingWeather.count default: return 0 } } override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! { let cell = tableView.dequeueReusableCellWithIdentifier("WeatherCell", forIndexPath: indexPath) as UITableViewCell var daysWeather: NSDictionary = [:] switch (indexPath.section) { case 0: let currentCondition = self.weather["data"]["current_condition"] as NSArray daysWeather = currentCondition[0] as NSDictionary case 1: let upcomingWeather: AnyObject! = self.weather["data"]["weather"] as NSArray daysWeather = upcomingWeather[indexPath.row] as NSDictionary default: break } // Display string let weatherDesc = daysWeather["weatherDesc"] as NSArray cell.textLabel.text = weatherDesc[0]["value"] as NSString // Fetch icon according to the icon url in json let weatherIconUrl = daysWeather["weatherIconUrl"] as NSArray let url = NSURL(string: weatherIconUrl[0]["value"] as NSString) let request = NSURLRequest(URL: url) var placeholderImage = UIImage(named: "placeholder") // Display icon cell.imageView.setImageWithURLRequest(request, placeholderImage: placeholderImage, success: { [weak cell] request, response, image in if cell != nil { cell!.imageView.image = image } if (tableView.visibleCells() as NSArray).containsObject(cell) { tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .None) } }, failure: {request, response, error in NSLog("%@", error) }) return cell } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView!, canEditRowAtIndexPath indexPath: NSIndexPath!) -> Bool { // Return NO if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView!, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath!) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView!, moveRowAtIndexPath fromIndexPath: NSIndexPath!, toIndexPath: NSIndexPath!) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView!, canMoveRowAtIndexPath indexPath: NSIndexPath!) -> Bool { // Return NO if you do not want the item to be re-orderable. return true } */ // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. if segue.identifier == "WeatherDetailSegue" { var cell = sender as UITableViewCell var indexPath = self.tableView.indexPathForCell(cell) let vc = segue.destinationViewController as ViewController switch indexPath.section { case 0: let currentCondition = self.weather["data"]["current_condition"] as NSArray vc.weather = currentCondition[0] as NSDictionary NSLog(vc.weather.description) case 1: let upcomingWeather: AnyObject! = self.weather["data"]["weather"] as NSArray vc.weather = upcomingWeather[indexPath.row] as NSDictionary NSLog(vc.weather.description) default: break } } } }
import Foundation import TMDb extension TVShowEpisodeImageCollection { static func mock( id: Int = .randomID, stills: [ImageMetadata] = .mocks ) -> Self { .init( id: id, stills: stills ) } }
import UIKit import Foundation import RxSwift import RxCocoa import ThemeKit import ComponentKit import SectionsTableView import Kingfisher class NftViewController: ThemeViewController { private let viewModel: NftViewModel private let headerView: NftHeaderView private let disposeBag = DisposeBag() private var viewItems = [NftViewModel.ViewItem]() private var expandedUids = Set<String>() private let tableView = SectionsTableView(style: .plain) private let refreshControl = UIRefreshControl() private let emptyView = PlaceholderView() private var loaded = false init(viewModel: NftViewModel, headerViewModel: NftHeaderViewModel) { self.viewModel = viewModel headerView = NftHeaderView(viewModel: headerViewModel) super.init() hidesBottomBarWhenPushed = true } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() title = "nft_collections.title".localized view.addSubview(tableView) tableView.snp.makeConstraints { maker in maker.edges.equalToSuperview() } if #available(iOS 15.0, *) { tableView.sectionHeaderTopPadding = 0 } tableView.separatorStyle = .none tableView.backgroundColor = .clear tableView.registerCell(forClass: NftDoubleCell.self) tableView.sectionDataSource = self refreshControl.tintColor = .themeLeah refreshControl.alpha = 0.6 refreshControl.addTarget(self, action: #selector(onRefresh), for: .valueChanged) view.addSubview(emptyView) emptyView.snp.makeConstraints { maker in maker.edges.equalTo(view.safeAreaLayoutGuide) } emptyView.image = UIImage(named: "image_empty_48") emptyView.text = "nft_collections.empty".localized subscribe(disposeBag, viewModel.viewItemsDriver) { [weak self] in self?.sync(viewItems: $0) } subscribe(disposeBag, viewModel.expandedUidsDriver) { [weak self] in self?.sync(expandedUids: $0) } tableView.buildSections() loaded = true } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) tableView.refreshControl = refreshControl } @objc func onRefresh() { viewModel.onTriggerRefresh() DispatchQueue.main.asyncAfter(deadline: .now() + 1) { [weak self] in self?.refreshControl.endRefreshing() } } private func sync(viewItems: [NftViewModel.ViewItem]) { self.viewItems = viewItems emptyView.isHidden = !viewItems.isEmpty if loaded { tableView.reload(animated: true) } } private func sync(expandedUids: Set<String>) { self.expandedUids = expandedUids if loaded { tableView.reload(animated: true) } } private func openAsset(viewItem: NftDoubleCell.ViewItem) { guard let providerCollectionUid = viewItem.providerCollectionUid else { return } let module = NftAssetModule.viewController(providerCollectionUid: providerCollectionUid, nftUid: viewItem.nftUid) present(ThemeNavigationController(rootViewController: module), animated: true) } } extension NftViewController: SectionsDataSource { private func row(leftViewItem: NftDoubleCell.ViewItem, rightViewItem: NftDoubleCell.ViewItem?, isLast: Bool) -> RowProtocol { Row<NftDoubleCell>( id: "token-\(leftViewItem.nftUid.uid)-\(rightViewItem?.nftUid.uid ?? "nil")", hash: "\(leftViewItem.hash)-\(rightViewItem?.hash ?? "nil")", dynamicHeight: { width in NftDoubleCell.height(containerWidth: width, isLast: isLast) }, bind: { cell, _ in cell.bind(leftViewItem: leftViewItem, rightViewItem: rightViewItem) { [weak self] viewItem in self?.openAsset(viewItem: viewItem) } } ) } private func row(viewItem: NftViewModel.ViewItem, expanded: Bool, index: Int) -> RowProtocol { CellBuilderNew.row( rootElement: .hStack([ .image32 { (component: ImageComponent) -> () in component.imageView.cornerRadius = .cornerRadius4 component.imageView.layer.cornerCurve = .continuous component.imageView.backgroundColor = .themeSteel20 component.imageView.kf.setImage( with: viewItem.imageUrl.flatMap { URL(string: $0) }, options: [.onlyLoadFirstFrame] ) }, .text { (component: TextComponent) -> () in component.font = .headline2 component.textColor = .themeLeah component.text = viewItem.name }, .text { (component: TextComponent) -> () in component.font = .subhead1 component.textColor = .themeGray component.text = viewItem.count component.setContentHuggingPriority(.required, for: .horizontal) component.setContentCompressionResistancePriority(.required, for: .horizontal) }, .margin8, .image20 { (component: ImageComponent) -> () in component.imageView.image = UIImage(named: expanded ? "arrow_big_up_20" : "arrow_big_down_20")?.withTintColor(.themeGray) } ]), tableView: tableView, id: "collection-\(viewItem.uid)", hash: "\(viewItem.name)-\(viewItem.count)-\(expanded)", height: .heightCell56, bind: { cell in cell.set(backgroundStyle: .transparent) cell.wrapperView.backgroundColor = .themeTyler cell.selectionStyle = .none }, action: { [weak self] in self?.viewModel.onTap(uid: viewItem.uid) } ) } func rows(viewItems: [NftViewModel.ViewItem]) -> [RowProtocol] { var rows = [RowProtocol]() for (index, viewItem) in viewItems.enumerated() { let expanded = expandedUids.contains(viewItem.uid) rows.append(row(viewItem: viewItem, expanded: expanded, index: index)) if expanded { let doubleRowCount = viewItem.assetViewItems.count / 2 let hasSingleRow = viewItem.assetViewItems.count % 2 == 1 for i in 0..<doubleRowCount { let row = row( leftViewItem: viewItem.assetViewItems[i * 2], rightViewItem: viewItem.assetViewItems[(i * 2) + 1], isLast: i == doubleRowCount - 1 && !hasSingleRow ) rows.append(row) } if let assetViewItem = viewItem.assetViewItems.last, hasSingleRow { let row = row( leftViewItem: assetViewItem, rightViewItem: nil, isLast: true ) rows.append(row) } } } return rows } func buildSections() -> [SectionProtocol] { [ Section( id: "main", headerState: viewItems.isEmpty ? .margin(height: 0) : .static(view: headerView, height: NftHeaderView.height), footerState: .marginColor(height: .margin32, color: .clear), rows: rows(viewItems: viewItems) ) ] } }
// // SCSUIColor+Extension.swift // leShou365 // // Created by 张鹏 on 15/8/21. // Copyright © 2015年 SmallCobblerStudio. All rights reserved. // import Foundation import UIKit extension UIColor { class func costomGreen() -> UIColor { return UIColor(red: 53/256.0, green: 153/256.0, blue: 41/256.0, alpha: 1.0) } }
// // RecipeBook+CoreDataClass.swift // RecipeManager // // Created by Anton Stamme on 09.04.20. // Copyright © 2020 Anton Stamme. All rights reserved. // // import Foundation import CoreData import UIKit @objc(RecipeBook) public class RecipeBook: NSManagedObject { static var recipeBooksUpdatedKey = Notification.Name("RecipeBook.recipeBooksUpdated") var color: Color { return Color.colorForKey(appearenceString) } var icon: UIImage? { get { guard let data = imageData else { return nil } return UIImage(data: data) } set { if let img = newValue, let imgData = UIImage.pngData(img)() { imageData = imgData } } } var recipesArr: [Recipe] { return (recipes.array as? [Recipe])?.sorted(by: {$0.creationDate ?? Date(timeIntervalSince1970: 0) > $1.creationDate ?? Date(timeIntervalSince1970: 0)}) ?? [] } }
// // AdaSpotifyBot.swift // AdaSpotifyBot // // Created by Vladislav Prusakov on 12.04.2019. // import Foundation import Telegrammer import Vapor import FluentSQLite final class AdaSpotifyBot: ServiceType { let bot: Bot let worker: Container var updater: Updater? var dispatcher: Dispatcher? var familyCreateContexts: [Int64: FamilyCreateContext] = [:] var familyDeleteContexts: [Int64: FamilyDeleteContext] = [:] ///Conformance to `ServiceType` protocol, fabric methhod static func makeService(for worker: Container) throws -> AdaSpotifyBot { guard let token = Environment.get("TELEGRAM_BOT_TOKEN") else { throw CoreError(identifier: "Enviroment variables", reason: "Cannot find telegram bot token") } let settings = Bot.Settings(token: token, debugMode: true) /// Setting up webhooks https://core.telegram.org/bots/webhooks /// Internal server address (Local IP), where server will starts // settings.webhooksIp = "127.0.0.1" /// Internal server port, must be different from Vapor port // settings.webhooksPort = 8181 /// External endpoint for your bot server // settings.webhooksUrl = "https://website.com/webhooks" /// If you are using self-signed certificate, point it's filename // settings.webhooksPublicCert = "public.pem" return try AdaSpotifyBot(settings: settings, worker: worker) } init(settings: Bot.Settings, worker: Container) throws { self.bot = try Bot(settings: settings) self.worker = worker let dispatcher = try configureDispatcher() self.dispatcher = dispatcher self.updater = Updater(bot: bot, dispatcher: dispatcher) } /// Initializing dispatcher, object that receive updates from Updater /// and pass them throught handlers pipeline func configureDispatcher() throws -> Dispatcher { ///Dispatcher - handle all incoming messages let dispatcher = Dispatcher(bot: bot) try setupHelps(dispatcher: dispatcher) try setupFamilyManaging(dispatcher: dispatcher) try setupMembers(dispatcher: dispatcher) try setupOthers(dispatcher: dispatcher) return dispatcher } }
// // ChannelManager.swift // Tourney // // Created by Hakan Eren on 9.02.2021. // Copyright © 2021 Will Cohen. All rights reserved. // import Foundation import Firebase /** Interface for `Channel` between database and client. */ struct ChannelManager { let db = Firestore.firestore() private let channelsCollectionKey = "channels" private var baseQuery: Query { return db.collection(channelsCollectionKey) } func fetchFeaturedChannels(completion: @escaping ( ([Channel]?) -> Void)) { baseQuery.getDocuments { (snapshot, error) in guard let snapshot = snapshot else { completion(nil) return } completion(snapshot.documents.compactMap { Channel(id: $0.documentID, dictionary: $0.data()) }) } } }
// // Podcast.swift // PodcastKoCore // // Created by John Roque Jorillo on 5/22/21. // Copyright © 2021 JohnRoque Inc. All rights reserved. // import Foundation public struct Podcast: Equatable, Codable, Hashable { public let trackName: String? public let artistName: String? public let artworkUrl600: String? public let trackCount: Int? public let feedUrl: String? public init(trackName: String?, artistName: String?, artworkUrl600: String?, trackCount: Int?, feedUrl: String?) { self.trackName = trackName self.artistName = artistName self.artworkUrl600 = artworkUrl600 self.trackCount = trackCount self.feedUrl = feedUrl } }
// // TextView.swift // Terminal // // Created by Kienle, Christian on 30.10.17. // import Foundation public struct Label { public init(_ text: String) { self.text = text } public var text: String } extension String { var words: [String] { return substrings(options: .byWords) } var lines: [String] { return substrings(options: .byLines) } func substrings(options: EnumerationOptions) -> [String] { var result = [String]() enumerateSubstrings(in: (startIndex..<endIndex), options: options) { (word, wordRange, _, _) in guard let word = word else { return } result.append(word) } return result } } public struct Table { public let width: Int public init(width: Int) { self.width = width } public var rows = [Row]() public mutating func add(_ row: Row) { add(rowsIn: [row]) } public mutating func add(rowsIn rowArray: [Row]) { rows += rowArray } public enum Alignment { case left, center } public mutating func addFullWidthRow(_ text: SubText, alignment: Alignment = .left) { let _text: SubText switch alignment { case .left: _text = text case .center: _text = text.wrappedInWhitespace(toLength: width) } add(Row(values: [.init(width: width, text: _text)])) } public mutating func addRowsFor(key: SubText, keyWidth: Int, values: [SubText], valuesWidth: Int) { let keyRowValueText = values.first ?? SubText("<none>") let keyRow = Row(values: [.init(width: keyWidth, text: key), .init(width: valuesWidth, text: keyRowValueText)]) let otherRows = values.dropFirst().map { Row(values: [.init(width: keyWidth, text: SubText(" ")), .init(width: valuesWidth, text: $0)]) } add(rowsIn: [keyRow] + otherRows) } public mutating func addEmptyRow() { addFullWidthRow(SubText(String(repeatElement(" ", count: width)))) } public mutating func addEmptyRows(_ count: Int) { let text = SubText(String.whitespace(width)) let value = Row.Value(width: width, text: text) let row = Row(values: [value]) let rows = Array(repeating: row, count: count) add(rowsIn: rows) } public mutating func addFullWidthSeparator() { addFullWidthRow(SubText(String(repeatElement("-", count: width)))) } public mutating func addFullWidthBoldSeparator() { addFullWidthRow(SubText(String(repeatElement("=", count: width)))) } public func text() -> Text { let texts = rows.map { $0.text() } let withNL = texts.joined(separator: Text.newline) return Text(Array(withNL)) } } public struct Column { public init(width: Int, title: SubText) { self.width = width self.title = title } public var width: Int public var title: SubText } public struct Row { public struct Value { public init(width: Int, text: SubText) { self.width = width self.text = text } public var width: Int public var text: SubText } public init(values: [Value]) { self.values = values } public var values: [Value] public func text() -> Text { let paddedValues:[SubText] = values.map { value in value.text.padding(toLength: value.width) } return Text(paddedValues) } } extension String { func padding(toLength length: Int) -> String { return (self as NSString).padding(toLength: length, withPad: " ", startingAt: 0) } func wrappedInWhitespace(toLength length: Int) -> String { let spaceLeft = max(length - count, 0) let ws = String.whitespace(spaceLeft / 2) return ws + self + ws } } extension SubText { func wrappedInWhitespace(toLength length: Int) -> SubText { var result = self result.text = result.text.wrappedInWhitespace(toLength: length) return result } func padding(toLength length: Int) -> SubText { var result = self result.text = result.text.padding(toLength: length) return result } }
// // ViewController.swift // SwiftSamples // // Created by Tsukasa Hasegawa on 2018/12/15. // Copyright © 2018 Tsukasa Hasegawa. All rights reserved. // import UIKit class TopViewController: UIViewController { @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. tableView.dataSource = self tableView.delegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: - Show Basic View private func showSegmentedControlViewController() { DispatchQueue.main.async { guard let navigation = UIStoryboard(name: "SegmentedControl", bundle: nil).instantiateInitialViewController() as? UINavigationController, let viewController = navigation.topViewController as? SegmentedControlViewController else { return } self.navigationController?.pushViewController(viewController, animated: true) } } private func showPickerTextFieldViewController() { DispatchQueue.main.async { guard let navigation = UIStoryboard(name: "PickerTextField", bundle: nil).instantiateInitialViewController() as? UINavigationController, let viewController = navigation.topViewController as? PickerTextFieldViewController else { return } self.navigationController?.pushViewController(viewController, animated: true) } } private func showScrollableTextFieldViewController() { DispatchQueue.main.async { guard let navigation = UIStoryboard(name: "ScrollableTextField", bundle: nil).instantiateInitialViewController() as? UINavigationController, let viewController = navigation.topViewController as? ScrollableTextFieldViewController else { return } self.navigationController?.pushViewController(viewController, animated: true) } } private func showDateSampleViewController() { DispatchQueue.main.async { guard let navigation = UIStoryboard(name: "DateSample", bundle: nil).instantiateInitialViewController() as? UINavigationController, let viewController = navigation.topViewController as? DateSampleViewController else { return } self.navigationController?.pushViewController(viewController, animated: true) } } private func showWKWebViewController() { DispatchQueue.main.async { guard let navigation = UIStoryboard(name: "WKWebView", bundle: nil).instantiateInitialViewController() as? UINavigationController, let viewController = navigation.topViewController as? WKWebViewController else { return } self.navigationController?.pushViewController(viewController, animated: true) } } private func showRealTimeObjectTrackingViewController() { DispatchQueue.main.async { guard let navigation = UIStoryboard(name: "RealTimeObjectTracking", bundle: nil).instantiateInitialViewController() as? UINavigationController, let viewController = navigation.topViewController as? RealTimeObjectTrackingViewController else { return } self.navigationController?.pushViewController(viewController, animated: true) } } private func showOverlayMatViewController() { DispatchQueue.main.async { guard let navigation = UIStoryboard(name: "OverlayMat", bundle: nil).instantiateInitialViewController() as? UINavigationController, let viewController = navigation.topViewController as? OverlayMatViewController else { return } self.navigationController?.pushViewController(viewController, animated: true) } } private func showEscapingRefererViewController() { DispatchQueue.main.async { guard let navigation = UIStoryboard(name: "EscapingReferer", bundle: nil).instantiateInitialViewController() as? UINavigationController, let viewController = navigation.topViewController as? EscapingRefererViewController else { return } self.navigationController?.pushViewController(viewController, animated: true) } } private func showVariableHeightTableViewController() { DispatchQueue.main.async { guard let navigation = UIStoryboard(name: "VariableHeightTable", bundle: nil).instantiateInitialViewController() as? UINavigationController, let viewController = navigation.topViewController as? VariableHeightTableViewController else { return } self.navigationController?.pushViewController(viewController, animated: true) } } // Mark: - Show Advance View private func showPagingTabMenuViewController() { DispatchQueue.main.async { guard let navigation = UIStoryboard(name: "PagingTabMenu", bundle: nil).instantiateInitialViewController() as? UINavigationController, let viewController = navigation.topViewController as? PagingTabMenuViewController else { return } self.navigationController?.pushViewController(viewController, animated: true) } } private func showCarouselViewController() { DispatchQueue.main.async { guard let navigation = UIStoryboard(name: "Carousel", bundle: nil).instantiateInitialViewController() as? UINavigationController, let viewController = navigation.topViewController as? CarouselViewController else { return } self.navigationController?.pushViewController(viewController, animated: true) } } // Mark: - Show Badge View private func showBadgeBarButtonItemViewController() { DispatchQueue.main.async { guard let navigation = UIStoryboard(name: "BadgeBarButtonItem", bundle: nil).instantiateInitialViewController() as? UINavigationController, let viewController = navigation.topViewController as? BadgeBarButtonItemViewController else { return } self.navigationController?.pushViewController(viewController, animated: true) } } private func showBadgeTableViewController() { DispatchQueue.main.async { guard let navigation = UIStoryboard(name: "BadgeTable", bundle: nil).instantiateInitialViewController() as? UINavigationController, let viewController = navigation.topViewController as? BadgeTableViewController else { return } self.navigationController?.pushViewController(viewController, animated: true) } } } extension TopViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return Top.Sections.allCases.count } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return Top.sectionTitle(section: Top.Sections.allCases[section]) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch Top.Sections.allCases[section] { case .basic: return Top.BasicCell.allCases.count case .advanced: return Top.AdvancedCell.allCases.count case .badge: return Top.BadgeCell.allCases.count } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell() switch Top.Sections.allCases[indexPath.section] { case .basic: cell.textLabel?.text = Top.basicCellTitle(cell: Top.BasicCell.allCases[indexPath.row]) return cell case .advanced: cell.textLabel?.text = Top.advancedCellTitle(cell: Top.AdvancedCell.allCases[indexPath.row]) return cell case .badge: cell.textLabel?.text = Top.badgeCellTitle(cell: Top.BadgeCell.allCases[indexPath.row]) return cell } } } extension TopViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) switch Top.Sections.allCases[indexPath.section] { case .basic: switch Top.BasicCell.allCases[indexPath.row] { case .segmentedControl: showSegmentedControlViewController() case .pickerTextField: showPickerTextFieldViewController() case .scrollableTextField: showScrollableTextFieldViewController() case .dateToString: showDateSampleViewController() case .wkWebView: showWKWebViewController() case .realTimeObjectTracking: showRealTimeObjectTrackingViewController() case .overlay: showOverlayMatViewController() case .escaping: showEscapingRefererViewController() case .variableHeightTable: showVariableHeightTableViewController() } case .advanced: switch Top.AdvancedCell.allCases[indexPath.row] { case .pagingTabMenu: showPagingTabMenuViewController() case .carousel: showCarouselViewController() } case .badge: switch Top.BadgeCell.allCases[indexPath.row] { case .barButtonItem: showBadgeBarButtonItemViewController() case .tableViewCell: showBadgeTableViewController() } } } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return CGFloat(44.0) } }
// // ContentView.swift // SwiftUI-Alerts // // Created by Ben Scheirman on 4/6/20. // Copyright © 2020 NSScreencast. All rights reserved. // import SwiftUI struct ContentView: View { struct RequestError : Identifiable { let id: UUID = UUID() let message: String } @State var isShowingConfirmation = false @State var hasAgreed = false @State var requestError: RequestError? var body: some View { Group { if !hasAgreed { showTerms() } else { VStack { Text("Welcome") .onAppear(perform: { self.fetchData() }) .alert(item: $requestError) { requestError in Alert( title: Text("Error"), message: Text(requestError.message), primaryButton: .default(Text("Retry"), action: { self.fetchData() }), secondaryButton: .cancel() ) } }.padding(20) } } } private func fetchData() { DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1)) { self.requestError = RequestError(message: "Unable to load data.") } } private func showTerms() -> some View { VStack(alignment: .leading, spacing: 20) { Text("Terms").font(.largeTitle) Text("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum").font(.body) Button(action: { self.isShowingConfirmation = true }) { Text("Continue") } .alert(isPresented: $isShowingConfirmation) { Alert(title: Text("You must agree to the terms to continue."), message: Text("Do you agree?"), primaryButton: .default(Text("Agree"), action: { self.hasAgreed = true }), secondaryButton: .cancel(Text("No")) ) } }.padding(20) } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
// // AboutModal.swift // iOS // // Created by Chris Sanders on 6/25/20. // import SwiftUI struct AboutModal: View { var body: some View { VStack { Text("What is Good Service?") .font(.headline) .padding(.bottom) Text("goodservice.io's goal is to provide an up-to-date and detailed view of the New York City subway system using the publicly available GTFS and GTFS-RT data. It is an open source project, and the source code can be found on GitHub. Currently, it displays maximum wait times (i.e. train headways or frequency), train delays and traffic conditions.") .font(.caption) Spacer() } .padding() } } struct AboutModal_Previews: PreviewProvider { static var previews: some View { AboutModal() } }
// // PQPublicFunction.swift // BaseAPP // // Created by pgq on 2017/11/20. // Copyright © 2017年 pgq. All rights reserved. // import UIKit //public extension NSObject{ public var pqScreenW: CGFloat { return UIScreen.main.bounds.width } public var pqScreenH: CGFloat { return UIScreen.main.bounds.height } public func pq_iPhoneXBottom() -> CGFloat{ if let window = UIApplication.shared.keyWindow { if window.frame.size == CGSize(width: 375, height: 812){ return -20 } } return -0 } public func pq_isIpad() -> Bool { return (UI_USER_INTERFACE_IDIOM() == .pad) } public func pq_isiPhone() -> Bool { return (UI_USER_INTERFACE_IDIOM() == .phone) } public func pq_isiPhoneX() -> Bool { var bottomInsets: CGFloat = 0 if #available(iOS 11.0, *) { bottomInsets = UIApplication.shared.delegate?.window??.safeAreaInsets.bottom ?? 0 } return bottomInsets > 0 } @discardableResult public func dPrintData(_ item: Data?) -> Bool{ if let data = item { var dataStr = "data is <0-3> " var i :Int = 0 for c in data{ dataStr.append(String(format: "%02x", c) ) i += 1 if i%4 == 0 { dataStr.append(" <\(i)-\(i+3)> ") } } dPrint(dataStr) return true } dPrint("空的Data") return false } public func dPrint(_ items: Any..., function:String = #function,file : String = #file, lineNumber : Int = #line){ #if DEBUG //获取文件名 let fileName = (file as NSString).lastPathComponent let interval = TimeZone.current.secondsFromGMT(for: Date()) let date = Date().addingTimeInterval(TimeInterval(interval)) //打印日志内容 // print("[日志] \(date) \(fileName):\(lineNumber) > \(function) info:\(items)") print("[日志] \(date) \(fileName):\(lineNumber) > \(function) ",items) #endif } public func pqLog<T>(message : T, file : String = #file, lineNumber : Int = #line) { #if DEBUG let fileName = (file as NSString).lastPathComponent print("[\(fileName):line:\(lineNumber)]- \(message)") #endif } // 锁 public func synchronized(lock: AnyObject, closure:()->()) { objc_sync_enter(lock) closure() objc_sync_exit(lock) } //关闭定时器 public func closeTimer(_ timer:inout Timer?){ timer?.invalidate() timer?.fireDate = Date.distantFuture timer = nil } // 创建定时器 public func openTimer(timeInterval: TimeInterval, target: Any, selector: Selector, repeats: Bool) -> Timer { let timer = Timer.scheduledTimer(timeInterval: timeInterval, target: target, selector: selector, userInfo: nil, repeats: repeats) RunLoop.current.add(timer, forMode: RunLoop.Mode.common) return timer } // MARK: block public typealias callbackFloat = (_ value: Float) -> () //}
// // StoryViewController.swift // MythRetelling // // Created by Cody Craig on 4/2/18. // Copyright © 2018 Cody Craig. All rights reserved. // import UIKit class StoryViewController: UIViewController { // MARK: IBOutlets @IBOutlet var storyTextView: UITextView! // MARK: Lifecycle override func viewDidLoad() { super.viewDidLoad() setStoryTextView() storyTextView.isEditable = false storyTextView.backgroundColor = .clear view.backgroundColor = UIColor(patternImage: UIImage(named: "paper_bg")!) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) storyTextView.scrollRectToVisible(CGRect(x: 0, y: 0, width: 100, height: 100), animated: false) } // MARK: Story handling fileprivate func setStoryTextView() { if var myStrings = readInGameData() { storyTextView.text = "" while myStrings.count > 0 && myStrings[0] != "" { let characterString = myStrings[0] let sentence = myStrings[1] storyTextView.text = "\(storyTextView.text!)\n\n\(characterString): \"\(sentence)\"" myStrings = Array(myStrings.dropFirst(3)) } } else { displayAlert(self, title: "ERROR", message: "Story data could not be read") } } }
/// /// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. /// Use of this file is governed by the BSD 3-clause license that /// can be found in the LICENSE.txt file in the project root. /// import Foundation open class ATNSimulator { /// /// Must distinguish between missing edge and edge we know leads nowhere /// public static let ERROR: DFAState = { let error = DFAState(ATNConfigSet()) error.stateNumber = Int.max return error }() public let atn: ATN /// /// The context cache maps all PredictionContext objects that are equals() /// to a single cached copy. This cache is shared across all contexts /// in all ATNConfigs in all DFA states. We rebuild each ATNConfigSet /// to use only cached nodes/graphs in addDFAState(). We don't want to /// fill this during closure() since there are lots of contexts that /// pop up but are not used ever again. It also greatly slows down closure(). /// /// This cache makes a huge difference in memory and a little bit in speed. /// For the Java grammar on java.*, it dropped the memory requirements /// at the end from 25M to 16M. We don't store any of the full context /// graphs in the DFA because they are limited to local context only, /// but apparently there's a lot of repetition there as well. We optimize /// the config contexts before storing the config set in the DFA states /// by literally rebuilding them with cached subgraphs only. /// /// I tried a cache for use during closure operations, that was /// whacked after each adaptivePredict(). It cost a little bit /// more time I think and doesn't save on the overall footprint /// so it's not worth the complexity. /// internal let sharedContextCache: PredictionContextCache public init(_ atn: ATN, _ sharedContextCache: PredictionContextCache) { self.atn = atn self.sharedContextCache = sharedContextCache } open func reset() { fatalError(#function + " must be overridden") } /// /// Clear the DFA cache used by the current instance. Since the DFA cache may /// be shared by multiple ATN simulators, this method may affect the /// performance (but not accuracy) of other parsers which are being used /// concurrently. /// /// - throws: ANTLRError.unsupportedOperation if the current instance does not /// support clearing the DFA. /// /// - since: 4.3 /// open func clearDFA() throws { throw ANTLRError.unsupportedOperation(msg: "This ATN simulator does not support clearing the DFA. ") } open func getSharedContextCache() -> PredictionContextCache { return sharedContextCache } open func getCachedContext(_ context: PredictionContext) -> PredictionContext { //TODO: synced (sharedContextCache!) //synced (sharedContextCache!) { var visited = [PredictionContext: PredictionContext]() return PredictionContext.getCachedContext(context, sharedContextCache, &visited) } public static func edgeFactory(_ atn: ATN, _ type: Int, _ src: Int, _ trg: Int, _ arg1: Int, _ arg2: Int, _ arg3: Int, _ sets: Array<IntervalSet>) throws -> Transition { return try ATNDeserializer().edgeFactory(atn, type, src, trg, arg1, arg2, arg3, sets) } }
// // RSCountryTableViewCell.swift // Bang // // Created by RohitSingh-MacMINI on 07/05/19. // Copyright © 2019 mindiii. All rights reserved. // import UIKit class RSCountryTableViewCell: UITableViewCell { @IBOutlet var imgCountryFlag: UIImageView! @IBOutlet var lblCountryName: UILabel! @IBOutlet var lblCountryDialCode: UILabel! @IBOutlet var imgRadioCheck: UIImageView! override func awakeFromNib() { super.awakeFromNib() //imgCountryFlag.setImageCircle() //imgCountryFlag.layer.cornerRadius = 6.0 // imgCountryFlag.layer.masksToBounds = true imgCountryFlag.layer.borderColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1) imgCountryFlag.layer.borderWidth = 1.0 } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } }
public protocol PrettyPrintable { var descriptionLines: [IndentedLine] { get } } extension PrettyPrintable { public var prettyDescription: String { return format(self.descriptionLines) } } public indirect enum IndentedLine: Equatable { case indent(IndentedLine) case content(String) public func format(indentWidth: Int) -> String { switch self { case .indent(let line): let indent = String(repeating: " ", count: indentWidth) return indent + line.format(indentWidth: indentWidth) case .content(let content): return content } } } public func format<Lines: Sequence>( _ lines: Lines, indentWidth: Int = 4 ) -> String where Lines.Element == IndentedLine { return lines .map { line in line.format(indentWidth: indentWidth) } .joined(separator: "\n") } public func indent<Lines: Sequence>( _ lines: Lines ) -> [IndentedLine] where Lines.Element == IndentedLine { return lines.map { .indent($0) } } public func lines<Lines: Sequence>( _ lines: Lines ) -> [IndentedLine] where Lines.Element == String { return lines.map { .content($0) } } public func verticalPadding<Lines: Sequence>( _ lines: Lines ) -> [IndentedLine] where Lines.Element == IndentedLine { var result = [IndentedLine.content("")] result.append(contentsOf: lines) result.append(.content("")) return result } public func section<Lines: Collection>( name: String, body: Lines ) -> [IndentedLine] where Lines.Element == IndentedLine { let bodyMustNotBeEmpty: [IndentedLine] if body.isEmpty { bodyMustNotBeEmpty = lines(["(empty)"]) } else { bodyMustNotBeEmpty = Array(body) } return [.content("\(name):")] + indent(bodyMustNotBeEmpty) } public func sections<Sections: Sequence, Lines: Collection>( _ sectionsInfo: Sections ) -> [IndentedLine] where Sections.Element == (name: String, body: Lines), Lines.Element == IndentedLine { let sectionLines = sectionsInfo.map { sectionInfo in return section(name: sectionInfo.name, body: sectionInfo.body) } let verticalSpace = [IndentedLine.content("")] return intersperse(sectionLines, verticalSpace).flatMap { $0 } } public func sections<Sections: Sequence, Lines: Collection>( _ sectionsInfo: Sections ) -> [IndentedLine] where Sections.Element == Lines, Lines.Element == IndentedLine { return sections(sectionsInfo .enumerated() .map { (name: "\($0.0)", body: $0.1) }) } public func descriptionList<Items: Sequence>( _ items: Items ) -> [IndentedLine] where Items.Element == (label: String, description: String) { return items.map { item in .content("\(item.label): \(item.description)") } }
// // TrackCellView.swift // AlbumDetail // // Created by Alex Tapia on 13/03/21. // import SwiftUI struct TrackCellView: View { let track: Track init(track: Track) { self.track = track } var body: some View { HStack { VStack { Text(track.title) .frame(maxWidth: .infinity, alignment: .leading) .font(.custom("Roboto-Regular", size: 16)) .foregroundColor(.xEEEEEE) .padding(.bottom, 2) Text(track.artists) .frame(maxWidth: .infinity, alignment: .leading) .font(.custom("Roboto-Regular", size: 14)) .foregroundColor(.x5C5C5C) } Button(action: {}, label: { Image(systemName: "ellipsis").font(.largeTitle) }) .frame(width: 32, height: 32) .foregroundColor(.x4A4A4A) }.padding([.leading, .top, .trailing], 12) } } struct TrackCellView_Previews: PreviewProvider { static var previews: some View { TrackCellView(track: Album.tracks.first ?? Track(title: "Title", artists: "Artists")) .background(Color.x2A2A2A) .previewLayout(.sizeThatFits) } }
// // NetworkTool.swift // TodayHeadline // // Created by LiDinggui on 2018/11/14. // Copyright © 2018年 LiDinggui. All rights reserved. // import Foundation import HandyJSON import SwiftyJSON private let kDeviceId: Int = 6096495334 private let kIid: Int = 5034850950 protocol NetworkToolProtocol { /// "我的"界面普通数据 /// /// - Parameter completionHandler: 成功获取到数据后的回调 static func requestMineCellData(_ completionHandler: @escaping (_ sections: [[MineCellModel]]) -> ()) /// "我的"界面我的关注数据 /// /// - Parameter completionHandler: 成功获取到数据后的回调 static func requestMyConcernData(_ completionHandler: @escaping ([MineConcernModel]) -> ()) } extension NetworkToolProtocol { static func requestMineCellData(_ completionHandler: @escaping (_ sections: [[MineCellModel]]) -> ()) { Network.request(urlString: UserTabsURL, parameters: ["device_id": kDeviceId]) { (value, error) in guard let value = value else { return } let json = JSON(value) guard json["message"] == "success" else { return } guard let sections = json["data"]["sections"].array else { return } var modelArrays = [[MineCellModel]]() for section in sections { guard let rows = section.array else { continue } var modelArray = [MineCellModel]() for row in rows { guard let model = MineCellModel.deserialize(from: row.dictionaryObject) else { continue } modelArray.append(model) } modelArrays.append(modelArray) } completionHandler(modelArrays) } } static func requestMyConcernData(_ completionHandler: @escaping ([MineConcernModel]) -> ()) { Network.request(urlString: MyFollowURL, parameters: ["device_id": kDeviceId]) { (value, error) in guard let value = value else { return } let json = JSON(value) guard json["message"] == "success" else { return } guard let data = json["data"].array else { return } var models = [MineConcernModel]() for element in data { let model = MineConcernModel.deserialize(from: element.dictionaryObject) models.append(model!) } completionHandler(models) } } } struct NetworkTool: NetworkToolProtocol {}
// // VistaMasasViewController.swift // CrearPizza // // Created by Isaias Varela on 14/02/16. // Copyright © 2016 Isaias Varela. All rights reserved. // import UIKit class VistaMasasViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate { var masaDATA = ["Gruesa", "Delgada", "Crujiente"] var sigTamanio2 :String = " " @IBOutlet weak var Seleccion1: UILabel! @IBOutlet weak var masaSeleccionada: UILabel! @IBOutlet weak var tamanio2: UILabel! @IBOutlet weak var PickerMasa: UIPickerView! @IBOutlet weak var BtnAvanzar: UIButton! func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 1; } // returns the # of rows in each component.. func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return masaDATA.count } func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { masaSeleccionada.text = masaDATA[row] if BtnAvanzar.enabled == false { BtnAvanzar.enabled = true } } func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return masaDATA[row] } override func viewDidLoad() { super.viewDidLoad() self.PickerMasa.delegate = self self.PickerMasa.dataSource = self masaSeleccionada.hidden = true if masaSeleccionada.text == "-" { BtnAvanzar.enabled = false } // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillAppear(animated: Bool) { tamanio2.text = sigTamanio2 tamanio2.hidden = true } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { let sigVistaQuesos = segue.destinationViewController as! VistaQuesos let sigMasas1 :String = masaSeleccionada.text! let sigTamanio :String = tamanio2.text! sigVistaQuesos.sigMasas2 = sigMasas1 sigVistaQuesos.sigTamanio3 = sigTamanio } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
// // calculatorModelTests.swift // calculatorTests // // Created by Dina Vaingolts on 03/02/2018. // Copyright © 2018 Test. All rights reserved. // import Foundation import XCTest import RxSwift @testable import calculator class calculatorModelTests: XCTestCase { var model: CalculationModel? var disposeBag = DisposeBag() override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func updateModel(operation: Operator, op1: Double?, op2: Double?) { model = CalculationModel(operation: operation) Observable.just(op1).bind(to: (model?.operand1)!).disposed(by: disposeBag) Observable.just(op2).bind(to: (model?.operand2)!).disposed(by: disposeBag) } func updateModel(operation: Operator, observableOp1: Observable<Double?>, observableOp2: Observable<Double?>) { model = CalculationModel(operation: operation) observableOp1.bind(to: (model?.operand1)!).disposed(by: disposeBag) observableOp2.bind(to: (model?.operand2)!).disposed(by: disposeBag) } func testOperations() { let op1 = Double(arc4random_uniform(1000)) let op2 = Double(arc4random_uniform(1000)) updateModel(operation: .addition, op1: op1, op2: op2) model?.result.subscribe(onNext: { value in XCTAssertNotNil(value) XCTAssertEqual(Double(value!), op1+op2) }) .disposed(by: disposeBag) updateModel(operation: .substraction, op1: op1, op2: op2) model?.result.subscribe(onNext: { value in XCTAssertNotNil(value) XCTAssertEqual(Double(value!), op1-op2) }) .disposed(by: disposeBag) updateModel(operation: .multiplication, op1: op1, op2: op2) model?.result.subscribe(onNext: { value in XCTAssertNotNil(value) XCTAssertEqual(Double(value!), op1*op2) }) .disposed(by: disposeBag) updateModel(operation: .division, op1: op1, op2: op2) model?.result.subscribe(onNext: { value in XCTAssertNotNil(value) if let result = Double(value!) { XCTAssertTrue(result - Double(op1/op2) < 0.000001) } }) .disposed(by: disposeBag) } func testEmpty() { let op1 : Double? = nil let op2 = Double(arc4random_uniform(1000)) updateModel(operation: .addition, op1: op1, op2: op2) model?.result.subscribe(onNext: { value in XCTAssertEqual(value, "") }) .disposed(by: disposeBag) updateModel(operation: .substraction, op1: op1, op2: op2) model?.result.subscribe(onNext: { value in XCTAssertEqual(value, "") }) .disposed(by: disposeBag) updateModel(operation: .multiplication, op1: op1, op2: op2) model?.result.subscribe(onNext: { value in XCTAssertEqual(value, "") }) .disposed(by: disposeBag) updateModel(operation: .division, op1: op1, op2: op2) model?.result.subscribe(onNext: { value in XCTAssertEqual(value, "") }) .disposed(by: disposeBag) } func testEmptyAfterNonEmptyResult() { let op1: Observable<Double?> = Observable.from([Double(arc4random_uniform(1000))]) let op2: Observable<Double?> = Observable.from([Double(arc4random_uniform(1000)), nil]) updateModel(operation: .addition, observableOp1: op1, observableOp2: op2) model?.result.subscribe(onNext: { [unowned self] value in if self.model?.operand2.value != nil{ guard let op1Value = self.model?.operand1.value, let op2Value = self.model?.operand2.value else { XCTFail() return; } XCTAssertEqual(Double(value!), op1Value + op2Value) }else{ XCTAssertEqual(value, "") } }) .disposed(by: disposeBag) } func test2Zero() { let op1 = Double(arc4random_uniform(1000)) let op2 = 0.0 updateModel(operation: .addition, op1: op1, op2: op2) model?.result.subscribe(onNext: { value in XCTAssertNotNil(value) XCTAssertEqual(Double(value!), op1) }) .disposed(by: disposeBag) updateModel(operation: .substraction, op1: op1, op2: op2) model?.result.subscribe(onNext: { value in XCTAssertNotNil(value) XCTAssertEqual(Double(value!), op1) }) .disposed(by: disposeBag) updateModel(operation: .multiplication, op1: op1, op2: op2) model?.result.subscribe(onNext: { value in XCTAssertNotNil(value) XCTAssertEqual(Double(value!), 0) }) .disposed(by: disposeBag) updateModel(operation: .division, op1: op1, op2: op2) model?.result.subscribe(onNext: { value in XCTAssertNotNil(value) XCTAssertEqual(value, "inf") }) .disposed(by: disposeBag) } func test1Zero() { let op1 = 0.0 let op2 = Double(arc4random_uniform(1000)) updateModel(operation: .substraction, op1: op1, op2: op2) model?.result.subscribe(onNext: { value in XCTAssertNotNil(value) XCTAssertEqual(Double(value!), -op2) }) .disposed(by: disposeBag) updateModel(operation: .multiplication, op1: op1, op2: op2) model?.result.subscribe(onNext: { value in XCTAssertNotNil(value) XCTAssertEqual(Double(value!), 0) }) .disposed(by: disposeBag) updateModel(operation: .division, op1: op1, op2: op2) model?.result.subscribe(onNext: { value in XCTAssertNotNil(value) XCTAssertEqual(Double(value!), 0.0) }) .disposed(by: disposeBag) } }
import CoreService import JWT import Vapor extension Assembly { var jwtTokenGeneratorService: TokenGeneratorService { return JWTTokenGeneratorService( jwtPayloadBuilder: jwtPayloadBuilder, signer: signer ) } private var jwtPayloadBuilder: JWTPayloadBuilder { return JWTPayloadBuilder( hasher: hasher ) } private var signer: Signer { guard let appConfig = config["app"] else { fatalError() } guard let signerKey = appConfig["SIGNER_KEY"]?.string else { fatalError("You must configure the signer key for the service") } return HS512( key: signerKey.makeBytes() ) } }
// // LoginNavigator.swift // MapBoxTest // // Created by YanQi on 2020/04/15. // Copyright © 2020 Prageeth. All rights reserved. // import UIKit class LoginNavigator: MBNavigatorProtocol { internal weak var viewController: UIViewController? init(with viewController: UIViewController) { self.viewController = viewController } func toSignup() { performSegue(with: .loginToSignup) } }
import PathKit import XCTest @testable import XcodeProj final class PathExtrasTests: XCTestCase { func testThat_GivenAbsoluteSubPath_WhenRelativeToAbsoluteSuperPath_ThenResultIsTheRemainder() { XCTAssertEqual(Path("/absolute/dir/file.txt").relative(to: Path("/absolute")), Path("dir/file.txt")) } func testThat_GivenAbsolutePath_WhenRelativeToNotSuperseedingAbsolutePath_ThenResultHasDoubleDot() { XCTAssertEqual(Path("/absolute/dir/file.txt").relative(to: Path("/absolute/anotherDir")), Path("../dir/file.txt")) } func testThat_GivenAbsoluteSubPath_WhenRelativeToIntersectingAbsolutePath_ThenResultIsTheFullPathToTheRootAndThenFullAbsolutePath() { XCTAssertEqual(Path("/absolute/dir/file.txt").relative(to: Path("/var")), Path("../absolute/dir/file.txt")) } func testThat_GivenSubPath_WhenRelativeToSuperPath_ThenResultIsTheRemainder() { XCTAssertEqual(Path("some/dir/file.txt").relative(to: Path("some")), Path("dir/file.txt")) } func testThat_GivenPath_WhenRelativeToNotSuperseedingPath_ThenResultHasDoubleDot() { XCTAssertEqual(Path("some/dir/file.txt").relative(to: Path("anotherDir")), Path("../some/dir/file.txt")) } }
// // hostHome.swift // coalay // // Created by 落合裕也 on 2020/11/07. // Copyright © 2020 落合裕也. All rights reserved. // import SwiftUI struct HostHome: View { @ObservedObject var viewModel:ChatViewModel var body: some View { VStack { Icon() Spacer() Text(viewModel.roomInfo.id) .frame(width: 300, height: 50, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/) .border(Color.white) Spacer() Button(action:{ self.viewModel.changeState(newState: .hostStarted) WindowControllers.shared.HostToolBarController.showWindow(nil) WindowControllers.shared.layerController.showWindow(nil) WindowControllers.shared.MainController.close() }) { Text("部屋を作成する") } .background(Color.blue) .cornerRadius(5) .scaleEffect(1.5) Spacer() } } }
import Foundation import EvmKit import Eip20Kit import NftKit import UniswapKit import OneInchKit import MarketKit import BigInt class EvmTransactionConverter { private let coinManager: CoinManager private let evmKitWrapper: EvmKitWrapper private let evmLabelManager: EvmLabelManager private let source: TransactionSource private let baseToken: MarketKit.Token init(source: TransactionSource, baseToken: MarketKit.Token, coinManager: CoinManager, evmKitWrapper: EvmKitWrapper, evmLabelManager: EvmLabelManager) { self.coinManager = coinManager self.evmKitWrapper = evmKitWrapper self.evmLabelManager = evmLabelManager self.source = source self.baseToken = baseToken } private var evmKit: EvmKit.Kit { evmKitWrapper.evmKit } private func convertAmount(amount: BigUInt, decimals: Int, sign: FloatingPointSign) -> Decimal { guard let significand = Decimal(string: amount.description), significand != 0 else { return 0 } return Decimal(sign: sign, exponent: -decimals, significand: significand) } private func baseCoinValue(value: BigUInt, sign: FloatingPointSign) -> TransactionValue { let amount = convertAmount(amount: value, decimals: baseToken.decimals, sign: sign) return .coinValue(token: baseToken, value: amount) } private func eip20Value(tokenAddress: EvmKit.Address, value: BigUInt, sign: FloatingPointSign, tokenInfo: Eip20Kit.TokenInfo?) -> TransactionValue { let query = TokenQuery(blockchainType: evmKitWrapper.blockchainType, tokenType: .eip20(address: tokenAddress.hex)) if let token = try? coinManager.token(query: query) { let value = convertAmount(amount: value, decimals: token.decimals, sign: sign) return .coinValue(token: token, value: value) } else if let tokenInfo = tokenInfo { let value = convertAmount(amount: value, decimals: tokenInfo.tokenDecimal, sign: sign) return .tokenValue(tokenName: tokenInfo.tokenName, tokenCode: tokenInfo.tokenSymbol, tokenDecimals: tokenInfo.tokenDecimal, value: value) } return .rawValue(value: value) } private func convertToAmount(token: SwapDecoration.Token, amount: SwapDecoration.Amount, sign: FloatingPointSign) -> SwapTransactionRecord.Amount { switch amount { case .exact(let value): return .exact(value: convertToTransactionValue(token: token, value: value, sign: sign)) case .extremum(let value): return .extremum(value: convertToTransactionValue(token: token, value: value, sign: sign)) } } private func convertToTransactionValue(token: SwapDecoration.Token, value: BigUInt, sign: FloatingPointSign) -> TransactionValue { switch token { case .evmCoin: return baseCoinValue(value: value, sign: sign) case .eip20Coin(let tokenAddress, let tokenInfo): return eip20Value(tokenAddress: tokenAddress, value: value, sign: sign, tokenInfo: tokenInfo) } } private func convertToAmount(token: OneInchDecoration.Token, amount: OneInchDecoration.Amount, sign: FloatingPointSign) -> SwapTransactionRecord.Amount { switch amount { case .exact(let value): return .exact(value: convertToTransactionValue(token: token, value: value, sign: sign)) case .extremum(let value): return .extremum(value: convertToTransactionValue(token: token, value: value, sign: sign)) } } private func convertToTransactionValue(token: OneInchDecoration.Token, value: BigUInt, sign: FloatingPointSign) -> TransactionValue { switch token { case .evmCoin: return baseCoinValue(value: value, sign: sign) case .eip20Coin(let tokenAddress, let tokenInfo): return eip20Value(tokenAddress: tokenAddress, value: value, sign: sign, tokenInfo: tokenInfo) } } private func transferEvents(incomingEip20Transfers: [TransferEventInstance]) -> [ContractCallTransactionRecord.TransferEvent] { incomingEip20Transfers.map { transfer in ContractCallTransactionRecord.TransferEvent( address: transfer.from.eip55, value: eip20Value(tokenAddress: transfer.contractAddress, value: transfer.value, sign: .plus, tokenInfo: transfer.tokenInfo) ) } } private func transferEvents(outgoingEip20Transfers: [TransferEventInstance]) -> [ContractCallTransactionRecord.TransferEvent] { outgoingEip20Transfers.map { transfer in ContractCallTransactionRecord.TransferEvent( address: transfer.to.eip55, value: eip20Value(tokenAddress: transfer.contractAddress, value: transfer.value, sign: .minus, tokenInfo: transfer.tokenInfo) ) } } private func transferEvents(incomingEip721Transfers: [Eip721TransferEventInstance]) -> [ContractCallTransactionRecord.TransferEvent] { incomingEip721Transfers.map { transfer in ContractCallTransactionRecord.TransferEvent( address: transfer.from.eip55, value: .nftValue( nftUid: .evm(blockchainType: source.blockchainType, contractAddress: transfer.contractAddress.hex, tokenId: transfer.tokenId.description), value: 1, tokenName: transfer.tokenInfo?.tokenName, tokenSymbol: transfer.tokenInfo?.tokenSymbol ) ) } } private func transferEvents(outgoingEip721Transfers: [Eip721TransferEventInstance]) -> [ContractCallTransactionRecord.TransferEvent] { outgoingEip721Transfers.map { transfer in ContractCallTransactionRecord.TransferEvent( address: transfer.to.eip55, value: .nftValue( nftUid: .evm(blockchainType: source.blockchainType, contractAddress: transfer.contractAddress.hex, tokenId: transfer.tokenId.description), value: -1, tokenName: transfer.tokenInfo?.tokenName, tokenSymbol: transfer.tokenInfo?.tokenSymbol ) ) } } private func transferEvents(incomingEip1155Transfers: [Eip1155TransferEventInstance]) -> [ContractCallTransactionRecord.TransferEvent] { incomingEip1155Transfers.map { transfer in ContractCallTransactionRecord.TransferEvent( address: transfer.from.eip55, value: .nftValue( nftUid: .evm(blockchainType: source.blockchainType, contractAddress: transfer.contractAddress.hex, tokenId: transfer.tokenId.description), value: convertAmount(amount: transfer.value, decimals: 0, sign: .plus), tokenName: transfer.tokenInfo?.tokenName, tokenSymbol: transfer.tokenInfo?.tokenSymbol ) ) } } private func transferEvents(outgoingEip1155Transfers: [Eip1155TransferEventInstance]) -> [ContractCallTransactionRecord.TransferEvent] { outgoingEip1155Transfers.map { transfer in ContractCallTransactionRecord.TransferEvent( address: transfer.to.eip55, value: .nftValue( nftUid: .evm(blockchainType: source.blockchainType, contractAddress: transfer.contractAddress.hex, tokenId: transfer.tokenId.description), value: convertAmount(amount: transfer.value, decimals: 0, sign: .minus), tokenName: transfer.tokenInfo?.tokenName, tokenSymbol: transfer.tokenInfo?.tokenSymbol ) ) } } private func transferEvents(internalTransactions: [InternalTransaction]) -> [ContractCallTransactionRecord.TransferEvent] { internalTransactions.map { internalTransaction in ContractCallTransactionRecord.TransferEvent( address: internalTransaction.from.eip55, value: baseCoinValue(value: internalTransaction.value, sign: .plus) ) } } private func transferEvents(contractAddress: EvmKit.Address, value: BigUInt) -> [ContractCallTransactionRecord.TransferEvent] { guard value != 0 else { return [] } let event = ContractCallTransactionRecord.TransferEvent( address: contractAddress.eip55, value: baseCoinValue(value: value, sign: .minus) ) return [event] } } extension EvmTransactionConverter { func transactionRecord(fromTransaction fullTransaction: FullTransaction) -> EvmTransactionRecord { let transaction = fullTransaction.transaction switch fullTransaction.decoration { case is ContractCreationDecoration: return ContractCreationTransactionRecord( source: source, transaction: transaction, baseToken: baseToken ) case let decoration as IncomingDecoration: return EvmIncomingTransactionRecord( source: source, transaction: transaction, baseToken: baseToken, from: decoration.from.eip55, value: baseCoinValue(value: decoration.value, sign: .plus) ) case let decoration as OutgoingDecoration: return EvmOutgoingTransactionRecord( source: source, transaction: transaction, baseToken: baseToken, to: decoration.to.eip55, value: baseCoinValue(value: decoration.value, sign: .minus), sentToSelf: decoration.sentToSelf ) case let decoration as OutgoingEip20Decoration: return EvmOutgoingTransactionRecord( source: source, transaction: transaction, baseToken: baseToken, to: decoration.to.eip55, value: eip20Value(tokenAddress: decoration.contractAddress, value: decoration.value, sign: .minus, tokenInfo: decoration.tokenInfo), sentToSelf: decoration.sentToSelf ) case let decoration as ApproveEip20Decoration: return ApproveTransactionRecord( source: source, transaction: transaction, baseToken: baseToken, spender: decoration.spender.eip55, value: eip20Value(tokenAddress: decoration.contractAddress, value: decoration.value, sign: .plus, tokenInfo: nil) ) case let decoration as SwapDecoration: return SwapTransactionRecord( source: source, transaction: transaction, baseToken: baseToken, exchangeAddress: decoration.contractAddress.eip55, amountIn: convertToAmount(token: decoration.tokenIn, amount: decoration.amountIn, sign: .minus), amountOut: convertToAmount(token: decoration.tokenOut, amount: decoration.amountOut, sign: .plus), recipient: decoration.recipient?.eip55 ) case let decoration as OneInchSwapDecoration: return SwapTransactionRecord( source: source, transaction: transaction, baseToken: baseToken, exchangeAddress: decoration.contractAddress.eip55, amountIn: .exact(value: convertToTransactionValue(token: decoration.tokenIn, value: decoration.amountIn, sign: .minus)), amountOut: convertToAmount(token: decoration.tokenOut, amount: decoration.amountOut, sign: .plus), recipient: decoration.recipient?.eip55 ) case let decoration as OneInchUnoswapDecoration: return SwapTransactionRecord( source: source, transaction: transaction, baseToken: baseToken, exchangeAddress: decoration.contractAddress.eip55, amountIn: .exact(value: convertToTransactionValue(token: decoration.tokenIn, value: decoration.amountIn, sign: .minus)), amountOut: decoration.tokenOut.map { convertToAmount(token: $0, amount: decoration.amountOut, sign: .plus) }, recipient: nil ) case let decoration as OneInchUnknownSwapDecoration: return UnknownSwapTransactionRecord( source: source, transaction: transaction, baseToken: baseToken, exchangeAddress: decoration.contractAddress.eip55, valueIn: decoration.tokenAmountIn.map { convertToTransactionValue(token: $0.token, value: $0.value, sign: .minus) }, valueOut: decoration.tokenAmountOut.map { convertToTransactionValue(token: $0.token, value: $0.value, sign: .plus) } ) case let decoration as Eip721SafeTransferFromDecoration: return EvmOutgoingTransactionRecord( source: source, transaction: transaction, baseToken: baseToken, to: decoration.to.eip55, value: .nftValue( nftUid: .evm(blockchainType: source.blockchainType, contractAddress: decoration.contractAddress.hex, tokenId: decoration.tokenId.description), value: convertAmount(amount: 1, decimals: 0, sign: .minus), tokenName: decoration.tokenInfo?.tokenName, tokenSymbol: decoration.tokenInfo?.tokenSymbol ), sentToSelf: decoration.sentToSelf ) case let decoration as Eip1155SafeTransferFromDecoration: return EvmOutgoingTransactionRecord( source: source, transaction: transaction, baseToken: baseToken, to: decoration.to.eip55, value: .nftValue( nftUid: .evm(blockchainType: source.blockchainType, contractAddress: decoration.contractAddress.hex, tokenId: decoration.tokenId.description), value: convertAmount(amount: decoration.value, decimals: 0, sign: .minus), tokenName: decoration.tokenInfo?.tokenName, tokenSymbol: decoration.tokenInfo?.tokenSymbol ), sentToSelf: decoration.sentToSelf ) case let decoration as UnknownTransactionDecoration: let address = evmKit.address let internalTransactions = decoration.internalTransactions.filter { $0.to == address } let eip20Transfers = decoration.eventInstances.compactMap { $0 as? TransferEventInstance } let incomingEip20Transfers = eip20Transfers.filter { $0.to == address && $0.from != address } let outgoingEip20Transfers = eip20Transfers.filter { $0.from == address } let eip721Transfers = decoration.eventInstances.compactMap { $0 as? Eip721TransferEventInstance } let incomingEip721Transfers = eip721Transfers.filter { $0.to == address && $0.from != address } let outgoingEip721Transfers = eip721Transfers.filter { $0.from == address } let eip1155Transfers = decoration.eventInstances.compactMap { $0 as? Eip1155TransferEventInstance } let incomingEip1155Transfers = eip1155Transfers.filter { $0.to == address && $0.from != address } let outgoingEip1155Transfers = eip1155Transfers.filter { $0.from == address } if transaction.from == address, let contractAddress = transaction.to, let value = transaction.value { return ContractCallTransactionRecord( source: source, transaction: transaction, baseToken: baseToken, contractAddress: contractAddress.eip55, method: transaction.input.flatMap { evmLabelManager.methodLabel(input: $0) }, incomingEvents: transferEvents(internalTransactions: internalTransactions) + transferEvents(incomingEip20Transfers: incomingEip20Transfers) + transferEvents(incomingEip721Transfers: incomingEip721Transfers) + transferEvents(incomingEip1155Transfers: incomingEip1155Transfers), outgoingEvents: transferEvents(contractAddress: contractAddress, value: value) + transferEvents(outgoingEip20Transfers: outgoingEip20Transfers) + transferEvents(outgoingEip721Transfers: outgoingEip721Transfers) + transferEvents(outgoingEip1155Transfers: outgoingEip1155Transfers) ) } else if transaction.from != address && transaction.to != address { return ExternalContractCallTransactionRecord( source: source, transaction: transaction, baseToken: baseToken, incomingEvents: transferEvents(internalTransactions: internalTransactions) + transferEvents(incomingEip20Transfers: incomingEip20Transfers) + transferEvents(incomingEip721Transfers: incomingEip721Transfers) + transferEvents(incomingEip1155Transfers: incomingEip1155Transfers), outgoingEvents: transferEvents(outgoingEip20Transfers: outgoingEip20Transfers) + transferEvents(outgoingEip721Transfers: outgoingEip721Transfers) + transferEvents(outgoingEip1155Transfers: outgoingEip1155Transfers) ) } default: () } return EvmTransactionRecord( source: source, transaction: transaction, baseToken: baseToken, ownTransaction: transaction.from == evmKit.address ) } }
// // UIStartScreenViewController.swift // tachistoscope // // Created by Giovanni Gorgone on 19/11/2019. // Copyright © 2019 undesigned. All rights reserved. // import UIKit class UIStartScreenViewController: UIViewController { @IBOutlet weak var hiddenButton: UIButton! override func viewDidLoad() { super.viewDidLoad() hiddenButton.sendActions(for: .touchUpInside) } }
// // InviteFriendsController.swift // 惠豆商城 // // Created by 张昊 on 2019/11/8. // Copyright © 2019 张兴栋. All rights reserved. // import UIKit class InviteFriendsController: ZXDBaseViewController { // lazy的作用是只会赋值一次 lazy var whiteView : UIView = { let whiteView = UIView(frame: AutoFrame(x: 30, y: 36, width: 315, height: 402)) whiteView.backgroundColor = .white whiteView.layer.cornerRadius = 5*ScalePpth whiteView.layer.masksToBounds = true return whiteView }() lazy var imageView : UIImageView = { let imageView = UIImageView(frame: AutoFrame(x: 87.5, y: 140, width: 140, height: 140)) imageView.image = UIImage(named: "QRCode.png") return imageView }() lazy var button : UIButton = { let button = UIButton(frame: AutoFrame(x: 17, y: 343, width: 281, height: 44)) button.backgroundColor = UIColor(rgb: 0xE60121) button.setTitle("转发邀请", for: .normal) button.setTitleColor(.white, for: .normal) button.layer.masksToBounds = true button.layer.cornerRadius = 22*ScalePpth return button }() override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) title = "邀请好友" titleLabel.textColor = .white backButton.setImage(UIImage(named: "de_lefttop"), for: .normal) navigationController?.navigationBar.barTintColor = UIColor(rgb: 0xFF6D38) } override func viewDidLoad() { super.viewDidLoad() setUpUI() } func setUpUI () { let TColor = UIColor(rgb: 0xFF6D38) //蓝色 let BColor = UIColor(rgb: 0xFF4425) //将颜色和颜色的位置定义在数组内 let gradientColors: [CGColor] = [TColor.cgColor, BColor.cgColor] //创建并实例化CAGradientLayer let gradientLayer: CAGradientLayer = CAGradientLayer() gradientLayer.colors = gradientColors //(这里的起始和终止位置就是按照坐标系,四个角分别是左上(0,0),左下(0,1),右上(1,0),右下(1,1)) //渲染的起始位置 gradientLayer.startPoint = CGPoint(x:0,y: 0) //渲染的终止位置 gradientLayer.endPoint = CGPoint(x:0,y: 1) //设置frame和插入view的layer gradientLayer.frame = view.bounds view.layer.insertSublayer(gradientLayer, at: 0) view.addSubview(whiteView) addWhiteSubViews() } func addWhiteSubViews () { let topLabel = UILabel(frame: AutoFrame(x: 0, y: 27, width: 315, height: 16)) topLabel.textAlignment = NSTextAlignment.center topLabel.font = UIFont.systemFont(ofSize: 16*ScalePpth) topLabel.textColor = UIColor(rgb: 0x333333) topLabel.text = "您的邀请码" whiteView.addSubview(topLabel) let array = ["2","0","3","0","0","1"] for i in 0..<6 { let backGroundView = UIView(frame: AutoFrame(x: (CGFloat(82+i*26)), y: 57, width: 21, height: 30)) backGroundView.backgroundColor = .init(rgb: 0xEFEFEF) backGroundView.layer.masksToBounds = true backGroundView.layer.cornerRadius = 2*ScalePpth whiteView.addSubview(backGroundView) let label = UILabel(frame: AutoFrame(x: (CGFloat(82+i*26)), y: 57, width: 21, height: 30)) label.textAlignment = .center label.font = .boldSystemFont(ofSize: 15*ScalePpth) label.text = array[i] label.textColor = .init(rgb: 0x333333) whiteView.addSubview(label) } let centerLabel = UILabel(frame: AutoFrame(x: 0, y: 101, width: 315, height: 12)) centerLabel.textAlignment = NSTextAlignment.center centerLabel.font = UIFont.systemFont(ofSize: 12*ScalePpth) centerLabel.textColor = UIColor(rgb: 0x999999) centerLabel.text = "邀请的好友也可在注册时直接填写邀请码" whiteView.addSubview(centerLabel) whiteView.addSubview(imageView) let bottomLabel = UILabel(frame: AutoFrame(x: 0, y: 296, width: 315, height: 13)) bottomLabel.textAlignment = NSTextAlignment.center bottomLabel.font = UIFont.systemFont(ofSize: 13*ScalePpth) bottomLabel.textColor = UIColor(rgb: 0x999999) bottomLabel.text = "长按图片即可保存" whiteView.addSubview(bottomLabel) whiteView.addSubview(button) let titleArray = ["1","2"]; let textArray = ["长按图片下载二维码,朋友扫码加入","点击按钮邀请朋友进入界面,输入邀请码"]; for i in 0..<2 { let leftLabel = UILabel(frame: AutoFrame(x: 30, y: (CGFloat(522-64+i*26)), width: 18, height: 18)) leftLabel.textAlignment = NSTextAlignment.center leftLabel.font = UIFont.systemFont(ofSize: 11*ScalePpth) leftLabel.textColor = UIColor(rgb: 0xffffff) leftLabel.text = titleArray[i] leftLabel.backgroundColor = UIColor(rgbs: 0xffffff, alpha: 0.2) leftLabel.layer.masksToBounds = true leftLabel.layer.cornerRadius = 9*ScalePpth view.addSubview(leftLabel) let rightLabel = UILabel(frame: AutoFrame(x: 54, y:(CGFloat(526-64+i*26)), width: 290, height: 11)) rightLabel.font = UIFont.systemFont(ofSize: 11*ScalePpth) rightLabel.textColor = UIColor(rgb: 0xffffff) rightLabel.text = textArray[i] view.addSubview(rightLabel) } } }
// // String.swift // ShapeApp // // Created by Sam on 15/09/2016. // Copyright © 2016 Sam Payne. All rights reserved. // import Foundation public extension String { func trim() -> String { return self.trimmingCharacters(in:CharacterSet.whitespacesAndNewlines) } func containsWhitespace() -> Bool { return self.components(separatedBy: CharacterSet.whitespacesAndNewlines).count > 1 } }
import UIKit public class PagingCollectionViewLayout<T: PagingItem where T: Equatable>: UICollectionViewFlowLayout { var state: PagingState<T>? var dataStructure: PagingDataStructure<T> private let options: PagingOptions private let indicatorLayoutAttributes: PagingIndicatorLayoutAttributes private let borderLayoutAttributes: PagingBorderLayoutAttributes private var range: Range<Int> { guard let collectionView = collectionView else { return 0...0 } return 0..<(collectionView.numberOfItemsInSection(0) - 1) } init(options: PagingOptions, dataStructure: PagingDataStructure<T>) { self.options = options self.dataStructure = dataStructure indicatorLayoutAttributes = PagingIndicatorLayoutAttributes( forDecorationViewOfKind: PagingIndicatorView.reuseIdentifier, withIndexPath: NSIndexPath(forItem: 0, inSection: 0)) borderLayoutAttributes = PagingBorderLayoutAttributes( forDecorationViewOfKind: PagingBorderView.reuseIdentifier, withIndexPath: NSIndexPath(forItem: 1, inSection: 0)) super.init() configure() } public required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func configure() { sectionInset = options.menuInsets minimumLineSpacing = options.menuItemSpacing minimumInteritemSpacing = 0 scrollDirection = .Horizontal registerDecorationView(PagingIndicatorView.self) registerDecorationView(PagingBorderView.self) indicatorLayoutAttributes.configure(options) borderLayoutAttributes.configure(options) } public override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool { return true } public override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? { var layoutAttributes = super.layoutAttributesForElementsInRect(rect)! let indicatorAttributes = layoutAttributesForDecorationViewOfKind(PagingIndicatorView.reuseIdentifier, atIndexPath: NSIndexPath(forItem: 0, inSection: 0)) let borderAttributes = layoutAttributesForDecorationViewOfKind(PagingBorderView.reuseIdentifier, atIndexPath: NSIndexPath(forItem: 1, inSection: 0)) if let indicatorAttributes = indicatorAttributes, borderAttributes = borderAttributes { layoutAttributes.append(indicatorAttributes) layoutAttributes.append(borderAttributes) } return layoutAttributes } public override func layoutAttributesForDecorationViewOfKind(elementKind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? { guard let state = state, let currentIndexPath = dataStructure.indexPathForPagingItem(state.currentPagingItem) else { return nil } let upcomingIndexPath = upcomingIndexPathForIndexPath(currentIndexPath) if elementKind == PagingIndicatorView.reuseIdentifier { let from = PagingIndicatorMetric( frame: indicatorFrameForIndex(currentIndexPath.item), insets: indicatorInsetsForIndex(currentIndexPath.item)) let to = PagingIndicatorMetric( frame: indicatorFrameForIndex(upcomingIndexPath.item), insets: indicatorInsetsForIndex(upcomingIndexPath.item)) indicatorLayoutAttributes.update(from: from, to: to, progress: fabs(state.offset)) return indicatorLayoutAttributes } if elementKind == PagingBorderView.reuseIdentifier { borderLayoutAttributes.update( contentSize: collectionViewContentSize(), bounds: collectionView?.bounds ?? .zero) return borderLayoutAttributes } return super.layoutAttributesForDecorationViewOfKind(elementKind, atIndexPath: indexPath) } // MARK: Private private func upcomingIndexPathForIndexPath(indexPath: NSIndexPath) -> NSIndexPath { guard let state = state else { return indexPath } if let upcomingPagingItem = state.upcomingPagingItem, upcomingIndexPath = dataStructure.indexPathForPagingItem(upcomingPagingItem) { return upcomingIndexPath } else if indexPath.item == range.startIndex { return NSIndexPath(forItem: indexPath.item - 1, inSection: 0) } else if indexPath.item == range.endIndex { return NSIndexPath(forItem: indexPath.item + 1, inSection: 0) } return indexPath } private func indicatorInsetsForIndex(index: Int) -> PagingIndicatorMetric.Inset { if case let .Visible(_, _, insets) = options.indicatorOptions { if index == range.startIndex { return .Left(insets.left) } else if index >= range.endIndex { return .Right(insets.right) } } return .None } private func indicatorFrameForIndex(index: Int) -> CGRect { guard let state = state, let currentIndexPath = dataStructure.indexPathForPagingItem(state.currentPagingItem) else { return .zero } if index < range.startIndex { let frame = frameForIndex(currentIndexPath.item) return frame.offsetBy(dx: -frame.width, dy: 0) } else if index > range.endIndex { let frame = frameForIndex(currentIndexPath.item) return frame.offsetBy(dx: frame.width, dy: 0) } else { return frameForIndex(index) } } private func frameForIndex(index: Int) -> CGRect { let currentIndexPath = NSIndexPath(forItem: index, inSection: 0) let layoutAttributes = layoutAttributesForItemAtIndexPath(currentIndexPath)! return layoutAttributes.frame } }
// // SAHTTPMultipartFormPost.swift // SAHTTPMultipartFormPostDemo // // Created by Siavash on 9/07/2015. // Copyright (c) 2015 Siavash. All rights reserved. // import Foundation import MobileCoreServices /** Conform to this porotocal in order to get notify about the response **/ protocol SAHTTPMultipartFormPostDelegate { func didFinishReceivingResultAsString(result: String) func didFailedReceivingResultWithError(error: NSError) } class SAHTTPMultipartFormPost : NSObject { var delegate:SAHTTPMultipartFormPostDelegate? var params:[String: AnyObject]? var urlString:String? var fileFeildName:String? var filesToPostPaths:[String]? /** Call this function after setting up all the needed variables to Post your request **/ func postToWeb() { if let safeParams = self.params { var boundary = self.generateBoundaryString() if let safeUrlString = self.urlString { var request:NSMutableURLRequest = NSMutableURLRequest(URL: NSURL(string: safeUrlString)!) request.HTTPMethod = "POST" var contentType = "multipart/form-data; boundary=\(boundary)" request.setValue(contentType, forHTTPHeaderField: "Content-Type") if let safeArray = self.filesToPostPaths { var paths:Array = safeArray if let safeFeildName = self.fileFeildName { var httpBody = self.createBodyWithBoundary(boundary, parameters: safeParams, paths:paths, fieldName: safeFeildName) var session = NSURLSession.sharedSession() var task = session.uploadTaskWithRequest(request, fromData: httpBody, completionHandler: { (data, response, error) -> Void in if (error != nil) { self.delegate?.didFailedReceivingResultWithError(error) return } var result = NSString(data: data, encoding: NSUTF8StringEncoding) self.delegate?.didFinishReceivingResultAsString(result as! String) return }) task.resume() } } } } } // MARK: Internal Helper Methods private func createBodyWithBoundary(boundray: String, parameters:[String:AnyObject], paths:NSArray, fieldName:NSString) -> NSData { var httpBody = NSMutableData() for (key, value) in parameters { httpBody.appendData("--\(boundray)\r\n" .dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!) httpBody.appendData("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n" .dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!) httpBody.appendData("\(value)\r\n" .dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!) } for path in paths { if let pathStr = path as? String { var fileName = pathStr.lastPathComponent var data = NSData(contentsOfFile: pathStr) var mimeType = self.mimeTypeForPath(pathStr) httpBody.appendData("--\(boundray)\r\n" .dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!) httpBody.appendData("Content-Disposition: form-data; form-data; name=\"\(fieldName)\"; filename=\"\(fileName)\"\r\n" .dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!) httpBody.appendData("Content-Type: \(mimeType)\r\n\r\n" .dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!) if let safeData = data { httpBody.appendData(data!) } httpBody.appendData("\r\n" .dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!) } } httpBody.appendData("--\(boundray)--\r\n".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!) return httpBody } private func mimeTypeForPath(path:String) -> String { var extensions:CFStringRef = path.pathExtension var UTI:CFStringRef = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, extensions, nil).takeRetainedValue() var mimeType = (UTTypeCopyPreferredTagWithClass(UTI, kUTTagClassMIMEType)) var result = "" if mimeType != nil { result = mimeType.takeRetainedValue() as String } return result } private func generateBoundaryString() -> String { return "Boundary-\(NSUUID().UUIDString)" } }
// // Category.swift // Enjoit // // Created by Miguel Roncallo on 9/11/17. // // import Foundation import SwiftyJSON class Category{ var descripcion: String! var idCategory: Int! var image: String! var name: String! }
// // FacultyCell.swift // KBTUApp // // Created by User on 09.03.2021. // Copyright © 2021 User. All rights reserved. // import UIKit class FacultyCell: UICollectionViewCell { @IBOutlet weak var deleteBtn: UIButton! var delegateDelete: DeleteProtocol? @IBOutlet weak var facultyLabel: UITextView! @IBOutlet weak var facultyImageView: UIImageView! var faculty: Faculty? override func awakeFromNib() { super.awakeFromNib() // Initialization code } @IBAction func deleteFromFav(_ sender: UIButton) { delegateDelete?.deleteFav(item: faculty!) } func visibilityBtn(visibility : Bool){ self.deleteBtn.isHidden = !visibility } }
import UIKit import SnapKit class BalanceLockedAmountView: UIView { static let height: CGFloat = 37 private let coinValueLabel = UILabel() private let currencyValueLabel = UILabel() init() { super.init(frame: .zero) backgroundColor = .clear let wrapperView = UIView() addSubview(wrapperView) wrapperView.snp.makeConstraints { maker in maker.leading.trailing.equalToSuperview() maker.top.equalToSuperview() maker.height.equalTo(Self.height) } let separatorView = UIView() wrapperView.addSubview(separatorView) separatorView.snp.makeConstraints { maker in maker.leading.trailing.equalToSuperview().inset(CGFloat.margin12) maker.bottom.equalToSuperview() maker.height.equalTo(CGFloat.heightOneDp) } separatorView.backgroundColor = .themeSteel20 let iconImageView = UIImageView() wrapperView.addSubview(iconImageView) iconImageView.snp.makeConstraints { maker in maker.leading.equalToSuperview().inset(CGFloat.margin16) maker.centerY.equalToSuperview() maker.size.equalTo(16) } iconImageView.image = UIImage(named: "lock_16") iconImageView.tintColor = .themeGray wrapperView.addSubview(coinValueLabel) coinValueLabel.snp.makeConstraints { maker in maker.leading.equalTo(iconImageView.snp.trailing).offset(CGFloat.margin4) maker.centerY.equalToSuperview() } coinValueLabel.font = .subhead2 wrapperView.addSubview(currencyValueLabel) currencyValueLabel.snp.makeConstraints { maker in maker.leading.equalTo(coinValueLabel.snp.trailing).offset(CGFloat.margin8) maker.trailing.equalToSuperview().inset(CGFloat.margin16) maker.centerY.equalToSuperview() } currencyValueLabel.font = .subhead2 currencyValueLabel.setContentHuggingPriority(.defaultHigh, for: .horizontal) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } func bind(viewItem: BalanceLockedAmountViewItem) { coinValueLabel.text = viewItem.coinValue.text coinValueLabel.textColor = viewItem.coinValue.dimmed ? .themeGray50 : .themeGray if let currencyValue = viewItem.currencyValue { currencyValueLabel.text = currencyValue.text currencyValueLabel.textColor = currencyValue.dimmed ? .themeGray50 : .themeLeah } else { currencyValueLabel.text = nil } } }
import os.log struct Log { static var general = OSLog(subsystem: "com.leboncoin", category: "general") static var network = OSLog(subsystem: "com.leboncoin", category: "network") }
// // LXMToolFunction.swift // S_ojia // // Created by kook on 16/1/2. // Copyright © 2016年 luxiaoming. All rights reserved. // import Foundation import UIKit func DLog(_ message: String, function: String = #function, line: Int = #line, file: String = #file) -> Void { #if DEBUG let tempArray = file.components(separatedBy: "/") let fileName = tempArray.last! let string = "file: \(fileName) line: \(line) func: \(function) log:\(message)" ConsoleInfoString += "\n" + string + "\n" NSLog(string) #endif } func delay(_ delay: Double, closure: @escaping ()->()) { DispatchQueue.main.asyncAfter( deadline: DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: closure) } /** 截取当前屏幕的某个区域为一个image */ func imageFromScreenshotWithRect(_ rect: CGRect) -> UIImage? { if let window = UIApplication.shared.delegate?.window { UIGraphicsBeginImageContextWithOptions(rect.size, false, 0) let targetRect = CGRect(x: -rect.origin.x, y: -rect.origin.y, width: kLXMScreenWidth, height: kLXMScreenHeight) window!.drawHierarchy(in: targetRect, afterScreenUpdates: false) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } else { return nil } } /** 把秒转换为时分秒的格式 */ func timeDurationFromSeconds(_ seconds: TimeInterval) -> String { let datecomponents = DateComponents() if let date = Calendar.current.date(from: datecomponents) { let timeInterval = date.timeIntervalSince1970 + seconds let newDate = Date(timeIntervalSince1970: timeInterval) let dateFormatter = DateFormatter() dateFormatter.dateFormat = "HH:mm:ss" return dateFormatter.string(from: newDate) } else { return "" } } extension UIColor { static func LXMColor(_ r: Int, g: Int, b: Int, a: Float) -> UIColor { return UIColor(red: CGFloat(r)/255.0, green: CGFloat(g)/255.0, blue: CGFloat(b)/255.0, alpha: CGFloat(a)) } static func LXMColorFromHex(_ hexRGBValue: Int) -> UIColor { let red = (hexRGBValue & 0xFF0000) >> 16 let green = (hexRGBValue & 0xFF00) >> 8 let blue = (hexRGBValue & 0xFF) return LXMColor(red, g: green, b: blue, a: 1.0) } }
// // // consumer // // Created by Vladislav Zagorodnyuk on 5/2/16. // Copyright © 2016 Human Ventures Co. All rights reserved. // import UIKit @objc public protocol ScrollPagerDelegate: NSObjectProtocol { @objc optional func scrollPager(_ scrollPager: ScrollPager, changedIndex: Int) } @IBDesignable open class ScrollPager: UIView, UIScrollViewDelegate{ fileprivate var selectedIndex = 0 fileprivate let indicatorView = UIView() var buttons = [UIButton]() fileprivate var visibleButtons = [UIButton]() fileprivate var views = [UIView]() fileprivate var animationInProgress = false @IBOutlet open weak var delegate: ScrollPagerDelegate! @IBOutlet open var scrollView: UIScrollView? { didSet { scrollView?.delegate = self scrollView?.isPagingEnabled = true scrollView?.showsHorizontalScrollIndicator = false } } @IBInspectable open var textColor: UIColor = UIColor.lightGray { didSet { redrawComponents() } } @IBInspectable open var selectedTextColor: UIColor = UIColor.darkGray { didSet { redrawComponents() } } @IBInspectable open var font: UIFont = UIFont.systemFont(ofSize: 13) { didSet { redrawComponents() } } @IBInspectable open var selectedFont: UIFont = UIFont.boldSystemFont(ofSize: 13) { didSet { redrawComponents() } } @IBInspectable open var indicatorColor: UIColor = UIColor.black { didSet { indicatorView.backgroundColor = indicatorColor } } @IBInspectable open var indicatorSizeMatchesTitle: Bool = false { didSet { redrawComponents() } } @IBInspectable open var indicatorHeight: CGFloat = 2.0 { didSet { redrawComponents() } } @IBInspectable open var borderColor: UIColor? { didSet { self.layer.borderColor = borderColor?.cgColor } } @IBInspectable open var borderWidth: CGFloat = 0 { didSet { self.layer.borderWidth = borderWidth } } @IBInspectable open var animationDuration: CGFloat = 0.2 // MARK: - Initializarion - required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initialize() } public override init(frame: CGRect) { super.init(frame: frame) initialize() } fileprivate func initialize() { #if TARGET_INTERFACE_BUILDER addSegmentsWithTitles(["One", "Two", "Three", "Four"]) #endif } // MARK: - UIView Methods - open override func layoutSubviews() { super.layoutSubviews() redrawComponents() //moveToIndex(selectedIndex, animated: false, moveScrollView: true) } // MARK: - Public Methods - open func addSegmentsWithTitlesAndViews(_ segments: [(title: String, view: UIView)]) { addButtons(segments.map { $0.title }) addViews(segments.map { $0.view }) redrawComponents() } open func addSegmentsWithImagesAndViews(_ segments: [(image: UIImage, view: UIView)]) { addButtons(segments.map { $0.image }) addViews(segments.map { $0.view }) redrawComponents() } open func addSegmentsWithTitles(_ segmentTitles: [Any]) { addButtons(segmentTitles) redrawComponents() } open func addSegmentsWithTitles(_ segmentTitles: [String], segmentImages: [UIImage]) { addButtons(segmentTitles as [AnyObject]) redrawComponents() } open func addSegmentsWithImages(_ segmentImages: [UIImage]) { addButtons(segmentImages) redrawComponents() } open func setSelectedIndex(_ index: Int, animated: Bool) { setSelectedIndex(index, animated: animated, moveScrollView: true) } // MARK: - Private - fileprivate func setSelectedIndex(_ index: Int, animated: Bool, moveScrollView: Bool) { selectedIndex = index moveToIndex(index, animated: animated, moveScrollView: moveScrollView) } fileprivate func addViews(_ segmentViews: [UIView]) { for view in scrollView!.subviews { view.removeFromSuperview() } for i in 0..<segmentViews.count { let view = segmentViews[i] scrollView!.addSubview(view) views.append(view) } } fileprivate func addButtons(_ titleOrImages: [Any]) { for button in buttons { button.removeFromSuperview() } buttons.removeAll(keepingCapacity: true) visibleButtons.removeAll(keepingCapacity: true) for i in 0..<titleOrImages.count { let button = UIButton(type: .custom) let visibleButton = UIButton(type: .custom) button.tag = i visibleButton.tag = i button.addTarget(self, action: #selector(ScrollPager.buttonSelected(_:)), for: .touchUpInside) visibleButton.addTarget(self, action: #selector(ScrollPager.buttonSelected(_:)), for: .touchUpInside) buttons.append(button) visibleButtons.append(visibleButton) if let title = titleOrImages[i] as? String { button.setTitle(title, for: UIControlState()) } else if let image = titleOrImages[i] as? UIImage { button.setImage(image, for: UIControlState()) } addSubview(button) button.addSubview(visibleButton) addSubview(indicatorView) } } fileprivate func moveToIndex(_ index: Int, animated: Bool, moveScrollView: Bool) { animationInProgress = true UIView.animate(withDuration: animated ? TimeInterval(animationDuration) : 0.0, delay: 0.0, options: .curveEaseOut, animations: { [weak self] in let width = self!.frame.size.width / CGFloat(self!.buttons.count) let button = self!.buttons[index] self?.redrawButtons() if self!.indicatorSizeMatchesTitle { let string: NSString? = button.titleLabel?.text as NSString? let size = string?.size(attributes: [NSFontAttributeName: button.titleLabel!.font]) let x = width * CGFloat(index) + ((width - size!.width) / CGFloat(2)) self!.indicatorView.frame = CGRect(x: x, y: self!.frame.size.height - self!.indicatorHeight, width: size!.width, height: self!.indicatorHeight) } else { self!.indicatorView.frame = CGRect(x: width * CGFloat(index), y: self!.frame.size.height - self!.indicatorHeight, width: button.frame.size.width, height: self!.indicatorHeight) } if self!.scrollView != nil && moveScrollView { self!.scrollView?.contentOffset = CGPoint(x: CGFloat(index) * self!.scrollView!.frame.size.width, y: 0) } }, completion: { [weak self] finished in // Storyboard crashes on here for some odd reasons, do a nil check if self != nil { self!.animationInProgress = false } }) } fileprivate func redrawComponents() { redrawButtons() if buttons.count > 0 { moveToIndex(selectedIndex, animated: false, moveScrollView: false) } if scrollView != nil { scrollView!.contentSize = CGSize(width: scrollView!.frame.size.width * CGFloat(buttons.count), height: scrollView!.frame.size.height) for i in 0..<views.count { views[i].frame = CGRect(x: scrollView!.frame.size.width * CGFloat(i), y: 0, width: scrollView!.frame.size.width, height: scrollView!.frame.size.height) } } } fileprivate func redrawButtons() { if buttons.count == 0 { return } let width = frame.size.width / CGFloat(buttons.count) let height = frame.size.height - indicatorHeight for i in 0..<buttons.count { let button = buttons[i] let visibleButton = visibleButtons[i] button.frame = CGRect(x: width * CGFloat(i), y: 0, width: width, height: height) button.setTitleColor((i == selectedIndex) ? selectedTextColor : textColor, for: UIControlState()) button.titleLabel?.font = (i == selectedIndex) ? selectedFont : font visibleButton.frame = CGRect(x: (button.frameWidth() / 2.0) - 20.0/2.0, y: 0.0, width: 20.0, height: 27.0) visibleButton.setTitleColor((i == selectedIndex) ? selectedTextColor : textColor, for: UIControlState()) if button.currentImage == nil { visibleButton.backgroundColor = (i == selectedIndex) ? UIColor.black : UIColor.clear } else { var imageName = button.imageView?.image?.accessibilityIdentifier if imageName != nil { if i != selectedIndex { if imageName!.contains("_dark") { imageName = imageName!.replacingOccurrences(of: "_dark", with: "") } else { imageName = imageName! } } else { if !imageName!.contains("_dark") { imageName = imageName! + "_dark" } } let image = UIImage(named: imageName!) image?.accessibilityIdentifier = imageName! button.setImage(image, for: UIControlState()) } } visibleButton.titleLabel?.font = (i == selectedIndex) ? selectedFont : font visibleButton.layer.cornerRadius = 2.0 visibleButton.setFrameY(20.0) } } func buttonSelected(_ sender: UIButton) { if sender.tag == selectedIndex { return } delegate?.scrollPager?(self, changedIndex: sender.tag) setSelectedIndex(sender.tag, animated: true, moveScrollView: true) } // MARK: - UIScrollView Delegate - open func scrollViewDidScroll(_ scrollView: UIScrollView) { if !animationInProgress { var page = scrollView.contentOffset.x / scrollView.frame.size.width if page.truncatingRemainder(dividingBy: 1) > 0.5 { page = page + CGFloat(1) } if Int(page) != selectedIndex { setSelectedIndex(Int(page), animated: true, moveScrollView: false) delegate?.scrollPager?(self, changedIndex: Int(page)) } } } }
// // FinishBlockHelper.swift // Lex // // Created by nbcb on 2017/1/10. // Copyright © 2017年 ZQC. All rights reserved. // import Foundation
// // DexTraderContainerModuleBuilder.swift // WavesWallet-iOS // // Created by Pavel Gubin on 8/15/18. // Copyright © 2018 Waves Platform. All rights reserved. // import UIKit import Extensions struct DexTraderContainerModuleBuilder: ModuleBuilderOutput { weak var output: DexTraderContainerModuleOutput? weak var orderBookOutput: DexOrderBookModuleOutput? weak var lastTradesOutput: DexLastTradesModuleOutput? weak var myOrdersOutpout: DexMyOrdersModuleOutput? var backAction:(() -> Void)? func build(input: DexTraderContainer.DTO.Pair) -> UIViewController { let vc = StoryboardScene.Dex.dexTraderContainerViewController.instantiate() vc.pair = input vc.moduleOutput = output vc.backAction = backAction vc.addViewController(DexOrderBookModuleBuilder(output: orderBookOutput).build(input: input), isScrollEnabled: true) vc.addViewController(DexChartModuleBuilder().build(input: input), isScrollEnabled: false) vc.addViewController(DexLastTradesModuleBuilder(output: lastTradesOutput).build(input: input), isScrollEnabled: true) vc.addViewController(DexMyOrdersModuleBuilder(output: myOrdersOutpout).build(input: input), isScrollEnabled: true) return vc } }
// // Food_2nd_ViewController.swift // EliminateWaste // // Created by YutaroHagiwara on 2020/01/13. // Copyright © 2020 YutaroHagiwara. All rights reserved. // import UIKit import RealmSwift class Food_2nd_ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate { // MARK: - Instance @IBOutlet weak var foodSearchBar: UISearchBar! @IBOutlet weak var tableView: UITableView! @IBOutlet weak var energyContentLabel: UILabel! @IBOutlet weak var daylyAmountLabel: UILabel! var segmentWord = "" // Canine or Feline var dER = "" let realm = try! Realm() let sections : [String] = ["Hills","ROYAL CANIN","JP Dietics"] var twoDimArray : [[String]] = [] override func viewDidLoad() { super.viewDidLoad() // MARK: - Realm // Reflect initial data in TableView loadSeedRealm() // MARK: - UISearchBar // Customizing UISearchBar foodSearchBar.textField?.borderStyle = .none // No border (otherwise it will cover the original border) foodSearchBar.textField?.layer.borderWidth = 1 // Border thickness foodSearchBar.textField?.layer.cornerRadius = 8.0 // Rounded corners foodSearchBar.textField?.layer.masksToBounds = true // Mask TextField to fit round corners foodSearchBar.textField?.layer.borderColor = UIColor(red: 51/255, green: 89/255, blue: 121/255, alpha: 0.5).cgColor // border color foodSearchBar.textField?.textColor = UIColor(red: 51/255, green: 89/255, blue: 121/255, alpha: 1) // Change text color of UISearchBar // Change color of the magnifying glass icon foodSearchBar.textField?.lupeImageView?.becomeImageAlwaysTemplate() foodSearchBar.textField?.lupeImageView?.tintColor = UIColor(red: 51/255, green: 89/255, blue: 121/255, alpha: 0.5) // Change color of placeholder(Asynchronous processing) DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { [weak self] in self?.foodSearchBar.textField?.attributedPlaceholder = NSAttributedString( string: "Please search for Food or Disease", attributes: [.foregroundColor: UIColor(red: 51/255, green: 89/255, blue: 121/255, alpha: 0.5)] ) } foodSearchBar.keyboardType = UIKeyboardType.default // Press return key even if nothing is entered in search bar foodSearchBar.enablesReturnKeyAutomatically = false // MARK: - UITableView // Erase extra Cell at the bottom of TableView tableView.tableFooterView = UIView() } // MARK: - UISearchBar // Called before editing the SearchBar and activates the cancel button when editing starts func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool { searchBar.showsCancelButton = true return true } // Disable if cancel button is pressed and remove focus func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { searchBar.showsCancelButton = false self.view.endEditing(true) searchBar.text = "" self.tableView.reloadData() } // Call method when search button is pressed func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { // Close keyboard foodSearchBar.endEditing(true) } // Tap another location to close the keyboard override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { self.view.endEditing(true) } // MARK: - UITableView関連 // Number of sections func numberOfSections(in tableView: UITableView) -> Int { return sections.count } // Section title func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return sections[section] } // Number of cells func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // print(twoDimArray.count) return twoDimArray[section].count } // Set value in cell func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // Get cell let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) // Set the value to display in the cell cell.textLabel?.textColor = UIColor(red: 51/255, green: 89/255, blue: 121/255, alpha: 1.0) cell.textLabel?.text = twoDimArray[indexPath.section][indexPath.row] return cell } // Change the text color of a section func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { let header = view as! UITableViewHeaderFooterView header.textLabel?.textColor = UIColor(red: 51/255, green: 89/255, blue: 121/255, alpha: 1.0) } // Method called when Cell is selected func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // Get text of tapped cell let tapCellText = twoDimArray[indexPath.section][indexPath.row] // Configuration of seed data let config = Realm.Configuration(fileURL: Bundle.main.url(forResource: "FoodList", withExtension: "realm"),readOnly: true) // Apply Configuration let realm = try! Realm(configuration: config) // Search for EnergyContent from realm using tapCellText let energyContent = realm.objects(FoodList.self).filter("productName == %@" , tapCellText)[0].energyContent energyContentLabel.text = String("\(energyContent)") // let daylyAmount : Double = atof(dER) / energyContent // DER/EnergyContent let daylyAmount_10 : Double = daylyAmount*10 // Multiply by 10 to shift the decimal point daylyAmountLabel.text = String("\(round(daylyAmount_10) / 10)") // Return decimal point after processing self.view.endEditing(true) } // MARK: - Realm // Call method when the text of Serchbar changes func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { // Empty the Array twoDimArray.removeAll() // Start search if foodSearchBar.text == "" { // Show all if Serchbar is empty。 loadSeedRealm() } else { // Configuration of seed data let config = Realm.Configuration(fileURL: Bundle.main.url(forResource: "FoodList", withExtension: "realm"),readOnly: true) // Apply Configuration let realm = try! Realm(configuration: config) // Add section number for _ in 0 ... 2 { twoDimArray.append([]) } // Search for species and manufacturer in realm (Separate variables for section) let hills = realm.objects(FoodList.self).filter("species == %@ AND manufacturer == 'Hills' " , segmentWord) let royalCanine = realm.objects(FoodList.self).filter("species == %@ AND manufacturer == 'ROYAL CANIN' " , segmentWord) let jp = realm.objects(FoodList.self).filter("species == %@ AND manufacturer == 'JP Dietics' " , segmentWord) // Search realm for SearchWord included in ProductName and DiseaseClassification let hills2 = hills.filter("productName CONTAINS %@ OR diseaseClassification_1 CONTAINS %@ OR diseaseClassification_2 CONTAINS %@ OR diseaseClassification_3 CONTAINS %@ " ,foodSearchBar.text!,foodSearchBar.text!,foodSearchBar.text!,foodSearchBar.text!) let royalCanine2 = royalCanine.filter("productName CONTAINS %@ OR diseaseClassification_1 CONTAINS %@ OR diseaseClassification_2 CONTAINS %@ OR diseaseClassification_3 CONTAINS %@ " , foodSearchBar.text!,foodSearchBar.text!,foodSearchBar.text!,foodSearchBar.text!) let jp2 = jp.filter("productName CONTAINS %@ OR diseaseClassification_1 CONTAINS %@ OR diseaseClassification_2 CONTAINS %@ OR diseaseClassification_3 CONTAINS %@ " , foodSearchBar.text!,foodSearchBar.text!,foodSearchBar.text!,foodSearchBar.text!) // Add search result to array for i in 0 ..< hills2.count { twoDimArray[0].append(hills2[i].productName) } for i in 0 ..< royalCanine2.count { twoDimArray[1].append(royalCanine2[i].productName) } for i in 0 ..< jp2.count { twoDimArray[2].append(jp2[i].productName) } } // Reload the TableView tableView.reloadData() } // Creating initial data func loadSeedRealm(){ // // Configuration of seed data let config = Realm.Configuration(fileURL: Bundle.main.url(forResource: "FoodList", withExtension: "realm"),readOnly: true) // Apply Configuration let realm = try! Realm(configuration: config) // Add section number for _ in 0 ... 2 { twoDimArray.append([]) } // Search for species and manufacturer in realm (Separate variables for section) let hills = realm.objects(FoodList.self).filter("species == %@ AND manufacturer == 'Hills' " , segmentWord) let royalCanine = realm.objects(FoodList.self).filter("species == %@ AND manufacturer == 'ROYAL CANIN' " , segmentWord) let jp = realm.objects(FoodList.self).filter("species == %@ AND manufacturer == 'JP Dietics' " , segmentWord) // Add search result to array for i in 0 ..< hills.count { twoDimArray[0].append(hills[i].productName) } for i in 0 ..< royalCanine.count { twoDimArray[1].append(royalCanine[i].productName) } for i in 0 ..< jp.count { twoDimArray[2].append(jp[i].productName) } // Reload the TableView tableView.reloadData() } }
// // CustomVC.swift // kanjiJisho2 // // Created by Alexandra Matreata on 1/10/15. // Copyright (c) 2015 tt. All rights reserved. // import Foundation import UIKit public class CustomVC: UIViewController, UITextFieldDelegate { // view pour la recherche customisee @IBOutlet weak var radicalLbl: UILabel! @IBOutlet weak var search: UITextField! @IBOutlet weak var strokesTF: UITextField! @IBOutlet weak var img: UIImageView! @IBOutlet weak var scr: UIScrollView! override public func viewDidLoad() { super.viewDidLoad() search.delegate = self strokesTF.delegate = self scr.scrollEnabled = true scr.bounces = true scr.contentSize = CGSizeMake(320, 2515) } @IBAction func showButton(sender: AnyObject) { buttonMake() } let RegexRadical = "^.{1}$" let myRegex = "(.){1,2}" var dataArray : NSArray = [] var radicals : Array<String> = [] var i = 0 var j = 0 var aux = "" var dict : Dictionary<String, String> = ["":""] var x:CGFloat = 35 var y:CGFloat = 310 //search variables var searchedRadicals : Array<String> = [] var searchedNrStrokes = "" var texte = String() public func textFieldShouldReturn(textField: UITextField) -> Bool { search.resignFirstResponder() strokesTF.resignFirstResponder() return true } func radicalSelected(sender:UIButton) { var t = 0 var j = 0 var gasit:Bool = false if let lbl = sender.titleLabel?.text { var match = lbl.rangeOfString(myRegex, options: .RegularExpressionSearch) if(searchedRadicals.count>1) {for t in 0...searchedRadicals.count-1 {if(searchedRadicals[t] == lbl.substringWithRange(match!)) { gasit = true for j in t...searchedRadicals.count-2 {searchedRadicals[j] = searchedRadicals[j+1] searchedRadicals.removeLast() } } } } if(!gasit) {searchedRadicals.append(lbl.substringWithRange(match!))} else {gasit = false} radicalLbl.text = searchedRadicals[0] if searchedRadicals.count > 1 {for j in 1...searchedRadicals.count-1 {radicalLbl.text = radicalLbl.text! + ", " + searchedRadicals[j]} } } } public func buttonMake() { var edeja = false var caleKanji = NSBundle.mainBundle().pathForResource("kanjiXML-2", ofType: "xml") var urlKanji:NSURL = NSURL (fileURLWithPath: caleKanji!)! var parserKanji : kanjiXMLParser = kanjiXMLParser.alloc().initWithURL(urlKanji) as kanjiXMLParser //verification du radical dans le xml dataArray = parserKanji.posts j = dataArray.count - 1 for i in 0...j { aux = dataArray.objectAtIndex(i).objectForKey("radical") as String if(edeja) {edeja = false} if(radicals.count>=2) {for k in 0...radicals.count - 1 { if radicals[k] as NSString == aux {edeja = true} }} if (!edeja) { radicals.append(aux) } } for i in 0...radicals.count-1 { aux = radicals[i] let button = UIButton.buttonWithType(UIButtonType.System) as UIButton button.frame = CGRectMake(x, y , 50, 50) button.backgroundColor = UIColor.lightGrayColor() button.setTitle(aux, forState: UIControlState.Normal) button.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal) button.addTarget(self, action: "radicalSelected:", forControlEvents: UIControlEvents.TouchUpInside) self.scr.addSubview(button) if(x<=185) {x = x+50} else {y = y+50 x = 35} } } override public func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override public func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) { var tvc:TVC tvc = segue.destinationViewController as TVC tvc.search = search.text tvc.searchedRadicals = searchedRadicals searchedNrStrokes = strokesTF.text + "\n" tvc.searchedNrStrokes = searchedNrStrokes } }
// // ApiServices.swift // ToolboxApp // // Created by Laura Sarmiento Almanza on 10/13/19. // Copyright © 2019 Laura Sarmiento Almanza. All rights reserved. // import Foundation import Moya import RxSwift protocol ApiServicesType { func request(to target: ToolboxApiTarget) -> Observable<Response> func request(imageUrl url: URL) -> Observable<UIImage> } let provider = MoyaProvider<ToolboxApiTarget>() private let queue = DispatchQueue(label: "com.toolbox.ios.api.services", qos: .userInitiated) private var disposable: Disposable? struct ApiServices: ApiServicesType { func request(to target: ToolboxApiTarget) -> Observable<Response> { provider.rx.request(target) .subscribeOn(ConcurrentDispatchQueueScheduler(queue: queue)) .observeOn(MainScheduler.instance) .retryWhenFailAuth() .asObservable() } func request(imageUrl url: URL) -> Observable<UIImage> { Observable<UIImage>.create { (observer: AnyObserver<UIImage>) -> Disposable in let configuration: URLSessionConfiguration = .default configuration.requestCachePolicy = .reloadIgnoringLocalAndRemoteCacheData let session = URLSession(configuration: configuration) let task = session.dataTask(with: url, completionHandler: { (data: Data?, response: URLResponse?, error: Error?) in if let error = error { observer.on(.error(error)) return } guard (response?.mimeType ?? "").hasPrefix("image"), let data = data, let image = UIImage(data: data) else { observer.on(.error(RxError.noElements)) return } observer.on(.next(image)) observer.on(.completed) }) task.resume() return Disposables.create { task.cancel() } } .observeOn(MainScheduler.instance) } } extension PrimitiveSequence where Trait == SingleTrait, Element == Response { func retryWhenFailAuth() -> PrimitiveSequence<SingleTrait, Response> { filterSuccessfulStatusCodes() .retryWhen { (observable: Observable<Error>) -> Observable<AuthToken> in observable.flatMapLatest { (error: Error) -> Observable<AuthToken> in if case MoyaError.statusCode(let response) = error, response.statusCode == 401 || response.statusCode == 403 { return Api.services.request(to: .authorization) .mapObject(AuthToken.self) .do(onNext: { (token :AuthToken) in UserDefaults.standard.set(token.token, forKey: "authToken") UserDefaults.standard.set(token.type, forKey: "authType") }) } return Observable<AuthToken>.error(error) } } } }
/* ======================= - Jiffy - made by Pawan Litt ©2016 ==========================*/ import UIKit import CloudKit class Favorites: UITableViewController { /* Variables */ var favoritesArray = NSMutableArray() override func viewWillAppear(animated: Bool) { navigationController?.navigationBar.barTintColor = UIColor(red: 0.0/255.0, green: 199.0/255.0, blue: 87.0/255.0, alpha: 1.0) if CurrentUser[USER_USERNAME] != nil { queryFavAds() } else { self.simpleAlert("You must login/signup into your Account to add Favorites") } } override func viewDidLoad() { super.viewDidLoad() } func queryFavAds() { showHUD() let predicate = NSPredicate(format: "\(FAV_USER_POINTER) = %@", CurrentUser) let query = CKQuery(recordType: FAV_CLASS_NAME, predicate: predicate) let sort = NSSortDescriptor(key: "creationDate", ascending: false) query.sortDescriptors = [sort] publicDatabase.performQuery(query, inZoneWithID: nil) { (results, error) -> Void in if error == nil { dispatch_async(dispatch_get_main_queue()) { self.favoritesArray = NSMutableArray(array: results!) self.tableView.reloadData() self.hideHUD() // Error }} else { dispatch_async(dispatch_get_main_queue()) { self.simpleAlert("\(error!.localizedDescription)") self.hideHUD() } } } } // MARK: - TABLEVIEW DELEGATES */ override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return favoritesArray.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("FavoritesCell", forIndexPath: indexPath) as! FavoritesCell let favClass = favoritesArray[indexPath.row] as! CKRecord // Get Ads as a Pointer let adRef = favClass[FAV_AD_POINTER] as! CKReference publicDatabase.fetchRecordWithID(adRef.recordID) { (adPointer, error) -> Void in if error == nil { dispatch_async(dispatch_get_main_queue()) { cell.adTitleLabel.text = "\(adPointer![CLASSIF_TITLE]!)" cell.adDescrLabel.text = "\(adPointer![CLASSIF_DESCRIPTION]!)" // Get image let imageFile = adPointer![CLASSIF_IMAGE1] as? CKAsset if imageFile != nil { cell.adImage.image = UIImage(contentsOfFile: imageFile!.fileURL.path!) } } } } return cell } // MARK: - SELECT AN AD -> SHOW IT override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let favClass = favoritesArray[indexPath.row] as! CKRecord // Get Ads as a Pointer let adRef = favClass[FAV_AD_POINTER] as! CKReference publicDatabase.fetchRecordWithID(adRef.recordID) { (adPointer, error) -> Void in if error == nil { dispatch_async(dispatch_get_main_queue()) { let showAdVC = self.storyboard?.instantiateViewControllerWithIdentifier("ShowSingleAd") as! ShowSingleAd // Pass the Ad ID to the Controller showAdVC.singleAdObj = adPointer! self.navigationController?.pushViewController(showAdVC, animated: true) } } } } // MARK: - REMOVE THIS AD FROM YOUR FAVORITES override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete selected Ad let favClass = favoritesArray[indexPath.row] as! CKRecord publicDatabase.deleteRecordWithID(favClass.recordID, completionHandler: { (recID, error) -> Void in if error == nil { dispatch_async(dispatch_get_main_queue()) { // Remove record in favoritesArray and the tableView's row self.favoritesArray.removeObjectAtIndex(indexPath.row) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) }} else { self.simpleAlert("\(error!.localizedDescription)") } }) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
// // HotItemsViewModel.swift // Tiki // // Created by Mac on 4/19/19. // Copyright © 2019 Truong Hoang Minh. All rights reserved. // import ObjectMapper class HotItemsViewModel { var hotItemsViewModel: [HotItemViewModel] = [] //MARK: - API func getCourse(completion: @escaping (_ success: Bool) -> ()) { API.sharedInstance.getHotItems() { (response) in if response != nil { guard let hotItemsModel = Mapper<HotItemsModel>().map(JSON: response as! [String : Any]) else { return } self.bindingToViewModel(hotItemsModel: hotItemsModel.items) completion(true) } else { completion(false) } } } //MARK: - BindingToViewModel func bindingToViewModel(hotItemsModel : [HotItemModel]) { // self.hotItemsViewModel = hotItemsModel.map { (hotItemModel) -> HotItemViewModel in // return HotItemViewModel.init(hotItemModel: hotItemModel) // } for (index, hotItemModel) in hotItemsModel.enumerated(){ self.hotItemsViewModel.append(HotItemViewModel.init(hotItemModel: hotItemModel, index: index)) } } }
// // CircleGraphView.swift // RingMeter // // Created by Michał Kreft on 27/03/15. // Copyright (c) 2015 Michał Kreft. All rights reserved. // import UIKit public class RingGraphView: UIView { let graph: RingGraph let foregroundView :ForegroundView required public init(frame: CGRect, graph: RingGraph, preset: GraphViewDescriptionPreset) { self.graph = graph let foregroundViewFrame = CGRect(origin: CGPoint(), size: frame.size) foregroundView = ForegroundView(frame: foregroundViewFrame, graph: graph, preset: preset) super.init(frame: frame) self.addSubview(foregroundView) } required public init?(coder aDecoder: NSCoder) { //ugh! fatalError("init(coder:) has not been implemented") } override public func drawRect(rect: CGRect) { let painter = RignGraphPainter(ringGraph: graph, drawingRect: rect, context: UIGraphicsGetCurrentContext()!) painter.drawBackground() } public func animateGraph() { foregroundView.animate() } }
// // ProjectsViewController.swift // DevChallenge // // Created by Lynk on 1/26/21. // import UIKit import CoreData class ProjectsViewController: UIViewController { let projectsView = ProjectsView() var store: ProjectStore! var projects = [NSManagedObject]() { didSet { projectsView.reload() } } override func viewDidLoad() { super.viewDidLoad() view.addSubview(projectsView) projectsView.setDeleagate(delegate: self) projectsView.setDataSource(dataSource: self) fetch() } func fetch() { store.fetchProjects { [weak self] (projects, error) in if let projects = projects { self?.projects = projects } else if let error = error { print(error) } } } } extension ProjectsViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return projects.count + 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.row == projects.count { guard let cell = tableView.dequeueReusableCell(withIdentifier: "createCell", for: indexPath) as? CreateProjectCell else { return UITableViewCell() } cell.delegate = self return cell } else { guard let cell = tableView.dequeueReusableCell(withIdentifier: "projectCell", for: indexPath) as? ProjectCell else { return UITableViewCell() } let project = projects[indexPath.row] cell.titleLabel.text = project.value(forKey: "title") as? String guard let date = project.value(forKey: "date") as? Date else { return cell} cell.dateLabel.text = date.formattedDate() if let headerdata = project.value(forKey: "header") as? Data, let header = UIImage(data: headerdata) { cell.header.image = header cell.header.clipsToBounds = true cell.header.contentMode = .scaleAspectFill } else if let colorData = project.value(forKey: "headerColor") as? Data, let color = UIColor.color(data: colorData) { cell.header.backgroundColor = color } return cell } } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return projectsView.frame.height * 0.2 + 16 } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let header = PageHeader() header.setTitleText(title: "Projects") return header } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 80 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard indexPath.row != projects.count else { return } let project = projects[indexPath.row] guard let date = project.value(forKey: "date") as? Date, let title = project.value(forKey: "title") as? String, let description = project.value(forKey: "projectDescription") as? String else { return } let dateString = date.formattedDate() var image: UIImage? var headerColor: UIColor? if let headerdata = project.value(forKey: "header") as? Data, let header = UIImage(data: headerdata) { image = header } else if let colorData = project.value(forKey: "headerColor") as? Data, let color = UIColor.color(data: colorData) { headerColor = color } let createViewController = CreateProjectViewController(type: .view) createViewController.setInfo(title: title, description: description, date: dateString, color: headerColor, header: image) createViewController.modalPresentationStyle = .overFullScreen createViewController.store = store present(createViewController, animated: true, completion: nil) } } extension ProjectsViewController: CreateProjectViewControllerDelegate { func reloadList() { fetch() } } extension ProjectsViewController: CreateProjectCellDelegate { func addButtonPressed() { let createViewController = CreateProjectViewController(type: .create) createViewController.modalPresentationStyle = .overFullScreen createViewController.store = store createViewController.delegate = self present(createViewController, animated: true, completion: nil) } }
// // ViewController.swift // Calculator // // Created by Vicente Lee on 2/27/17. // Copyright © 2017 Vicente Lee. All rights reserved. // import UIKit class ViewController: UIViewController { }
// // GridController.swift // SwiftPractic // // Created by hiro on 2018. 6. 20.. // Copyright © 2018년 hiro. All rights reserved. // import UIKit import Foundation import Hero import SwiftyJSON import Alamofire class ListCell: UITableViewCell { override func layoutSubviews() { super.layoutSubviews() imageView?.frame.origin.x = 0 imageView?.frame.size = CGSize(width: bounds.height, height: bounds.height) textLabel?.frame.origin.x = bounds.height + 10 detailTextLabel?.frame.origin.x = bounds.height + 10 } } class ListController: UITableViewController { /** TableView 관련 Swipe Refresh 이벤트 **/ var name: String = "" var detail: String = "" override func loadView() { super.loadView() GameData.goData() print(GameData.varDatas.count) } override func viewDidLoad() { super.viewDidLoad() // set up the refresh control refreshControl = UIRefreshControl() refreshControl?.attributedTitle = NSAttributedString(string: "Pull to refresh") //Swift3에서부터는 action사용 시 #selector가 필요.// refreshControl?.addTarget(self, action: #selector(self.refresh(_:)), for: UIControlEvents.valueChanged) tableView.addSubview(refreshControl!) //리플래시 화면을 보일(빙글빙글 돌아가는 프로그래스바)뷰를 장착.// //////////////////////////////// //////////////////////////////// } //당겨서 새로고침// @objc func refresh(_ sender:AnyObject) { // Code to refresh table view print("refresh table") tableView.reloadData() //뷰를 재로드// refreshControl?.endRefreshing() //다시 새로고침을 끝낸다.// } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return ImageLibrary.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "item", for: indexPath) if indexPath.item < GameData.varDatas.count { self.name = GameData.varDatas[indexPath.item]["name"].stringValue self.detail = GameData.varDatas[indexPath.item]["detail"].stringValue }else{ self.name = "Hyunho" self.detail = "Programer" } print(self.name) print(self.detail) cell.hero.modifiers = [.fade, .translate(x:-100)] cell.imageView!.hero.id = "image_\(indexPath.item)" cell.imageView!.hero.modifiers = [.arc] cell.imageView!.image = ImageLibrary.thumbnail(index:indexPath.item) cell.imageView!.isOpaque = true cell.textLabel!.text = self.name cell.detailTextLabel!.text = self.detail // cell.textLabel!.text = "Item \(indexPath.item)" // cell.detailTextLabel!.text = "Detail \(indexPath.item)" return cell } /* override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 52 //cell 의 높이 } */ //table Click override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let vc = (GameData.viewController(forStoryboardName: "ImageViewer") as? ImageViewController)! vc.selectedIndex = indexPath //hero.replaceViewController(with: vc ) //StoryBoard 전환 navigationController!.pushViewController(vc, animated: true) } @objc func showImage() { //StoryBoard 전환 hero.replaceViewController(with: (GameData.viewController(forStoryboardName: "ImageViewer") as? ImageViewController)! ) } }
// // Potocol.swift // POP // // Created by 陈刚 on 16/9/6. // Copyright © 2016年 陈刚. All rights reserved. // import UIKit protocol HasDate { var date:String {get set} } //视图使用的协议 protocol View{ func get<M:Model>(data model:M) } extension View { func get<M:Model>(data model:M){ //默认不执行任何操作,因为此时的ViewType和ModelType都是协议,没有具体的信息 } } extension View where Self:DemoShowedCell { func get<M:Model>(data model: M) { //先从公有的底层协议开始筛选,对于不是HasDate协议遵守者的模型提前返回 guard let hasDate = model as? HasDate else{ return } //公有部分 dateLabel.text = hasDate.date //再筛选顶层类型 if let festival = model as? Festival { //筛选出Festival模型进行绑定 tagImageView.image = UIImage(named: "fes") titleLabel.text = festival.festivalName } else if let event = model as? Event { //筛选出Event模型进行绑定 //组合 var styleTuple:(imgName:String,color:UIColor,btnHidden:Bool) { if event.warning { return ("eve_hl",UIColor.red,false) } else { return ("eve",UIColor.black,true) } } //应用组合后的样式 tagImageView.image = UIImage(named: styleTuple.imgName) titleLabel.textColor = styleTuple.color dateLabel.textColor = styleTuple.color warningBtn.isHidden = styleTuple.btnHidden titleLabel.text = event.eventTitle } } } //数据使用的协议 protocol Model{ } extension Model { //使用Enum重构后应该是用不到了 func give<V:View>(data view:V){ view.get(data:self) } } //复用绑定逻辑的协议 protocol DemoShowedCell { weak var tagImageView: UIImageView!{get set} weak var titleLabel: UILabel!{get set} weak var dateLabel: UILabel!{get set} weak var warningBtn: UIButton!{get set} //新增一个泛型的闭包类型 var buttonPressedClouse:(Self) -> Void{get set} } //别名,新语法很赞 typealias DateModel = HasDate & Model protocol SearchDate { } extension SearchDate { //静态多态的搜索版本 func search<D:DateModel>(_ source:[D],key:String) -> [D] { return source.filter{ $0.date.contains(key) } } //动态多态的搜索版本 func search(_ source:[DateModel],key:String) -> [DateModel] { return source.filter{ $0.date.contains(key) } } }
// // FriendsViewController.swift // SwiftNetwork // // Created by Дэвид Бердников on 05.05.2021. // import UIKit class FriendViewController: UITableViewController { private var friends: [Friend] = [] // MARK: - Table view data source override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { friends.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! FriendCell let friend = friends[indexPath.row] cell.configure(with: friend) return cell } } extension FriendViewController { func fetchFriends(from url: String?) { NetworkManager.shared.fetchFriend(from: url ?? "") { (friend) in self.friends = friend self.tableView.reloadData() } } }
// // DeployTasks.swift // Flock // // Created by Jake Heiser on 12/28/15. // Copyright © 2015 jakeheis. All rights reserved. // import Foundation public extension TaskSource { static let deploy = TaskSource(tasks: [ DeployTask(), GitTask(), BuildTask(), LinkTask() ]) } public extension Config { static var projectName = "" // Must be supplied static var executableName = "" // Must be supplied static var repoURL = "" // Must be supplied static var deployDirectory = "/var/www" static var repoBranch: String? = nil } private let deploy = "deploy" class DeployTask: Task { let name = deploy func run(on server: Server) throws { try invoke("deploy:git", on: server) try invoke("deploy:build", on: server) try invoke("deploy:link", on: server) } } class GitTask: Task { let name = "git" let namespace = deploy func run(on server: Server) throws { guard !Config.projectName.isEmpty else { throw TaskError(message: "You must supply a projectName in your configuration") } guard !Config.repoURL.isEmpty else { throw TaskError(message: "You must supply a repoURL in your configuration") } let currentTime = Date() let formatter = DateFormatter() formatter.dateFormat = "YYYYMMddHHMMSS" let timestamp = formatter.string(from: currentTime) let cloneDirectory = "\(Paths.releasesDirectory)/\(timestamp)" let branchSegment: String if let branch = Config.repoBranch { branchSegment = " -b \(branch)" } else { branchSegment = "" } try server.execute("git clone\(branchSegment) --depth 1 \(Config.repoURL) \(cloneDirectory)") try server.execute("ln -sfn \(cloneDirectory) \(Paths.nextDirectory)") } } class BuildTask: Task { let name = "build" let namespace = deploy func run(on server: Server) throws { let buildPath: String if server.directoryExists(Paths.nextDirectory) { buildPath = Paths.nextDirectory } else { buildPath = Paths.currentDirectory } let suggestion = ErrorSuggestion(error: "error while loading shared libraries", command: "sudo apt-get update && sudo apt-get -y install clang libicu-dev libpython2.7 libcurl4-openssl-dev") let suggestions = [suggestion] + Config.serverFramework.buildErrorSuggestions let pathPrefix = TaskSource.swiftenv.beingUsed ? "PATH=\"\(Config.swiftenvLocation)/shims:${PATH}\" " : "" try server.executeWithSuggestions("\(pathPrefix)swift build -C \(buildPath) -c release", suggestions: suggestions) } } class LinkTask: Task { let name = "link" let namespace = deploy func run(on server: Server) throws { guard let nextDestination = try? server.capture("readlink \(Paths.nextDirectory)").trimmingCharacters(in: .whitespacesAndNewlines) else { throw TaskError(message: "Couldn't find location of next directory to link", commandSuggestion: "flock deploy (not just flock deploy:link)") } try server.execute("ln -sfn \(nextDestination) \(Paths.currentDirectory)") try server.execute("rm \(Paths.nextDirectory)") } }
// // ConversionResponse.swift // Currency Converter // // Created by Jagan Kumar Mudila on 06/01/2021. // import Foundation struct ConversionResponse: ResponseBase { var error: ResponseError? let success: Bool let info: Info? let date: String? let result: Double? } struct Info: Codable { let timestamp: Int let rate: Double }
// // BoxCell.swift // English Flashcards // // Created by Quang Luong on 11/1/20. // import UIKit class BoxCell: UITableViewCell { //MARK: Outlets @IBOutlet weak var placeholderView: UIView! @IBOutlet weak var boxName: UILabel! //MARK: Defaults override func awakeFromNib() { super.awakeFromNib() updateUI() } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } //Private Methods func updateUI() { placeholderView.layer.cornerRadius = 10.0 placeholderView.layer.shadowColor = UIColor.blue.withAlphaComponent(0.2).cgColor placeholderView.layer.shadowOffset = CGSize.zero placeholderView.layer.shadowOpacity = 0.8 placeholderView.layer.shadowPath = UIBezierPath(rect: placeholderView.bounds).cgPath } }
// // ViewController.swift // GetDirectionsDemo // // Created by Alex Nagy on 12/02/2020. // Copyright © 2020 Alex Nagy. All rights reserved. // import UIKit import MapKit import CoreLocation import Layoutless import AVFoundation class ViewController: UIViewController { var steps: [MKRoute.Step] = [] var stepsCounter = 0 var route : MKRoute? var showMapRoute = false var navigationStarted = false var locationDistante : Double = 500 var speechSynthesizer = AVSpeechSynthesizer() lazy var locationManager:CLLocationManager = { let locationManager = CLLocationManager() //check service is enable if CLLocationManager.locationServicesEnabled() { locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest //authorization handleAuthorizationStatus(locationManager: locationManager, status: CLLocationManager.authorizationStatus()) } else { print("Location not are enable") } return locationManager }() lazy var directionLabel: UILabel = { let label = UILabel() label.text = "Where do you want to go?" label.font = .boldSystemFont(ofSize: 16) label.textAlignment = .center label.numberOfLines = 0 return label }() lazy var textField: UITextField = { let tf = UITextField() tf.placeholder = "Enter your destination" tf.borderStyle = .roundedRect tf.layer.cornerRadius = 10 tf.backgroundColor = .systemGray5 return tf }() lazy var getDirectionButton: UIButton = { let button = UIButton() button.setTitle("Get Direction", for: .normal) button.setTitleColor(.white, for: .normal) button.titleLabel?.font = .boldSystemFont(ofSize: 16) button.backgroundColor = .blue button.layer.cornerRadius = 10 button.addTarget(self, action: #selector(getDirectionButtonTapped), for: .touchUpInside) return button }() lazy var uiView: UIView = { let view = UIView() view.backgroundColor = .systemBackground return view }() lazy var startStopButton: UIButton = { let button = UIButton() button.setTitle("Start Navigation", for: .normal) button.setTitleColor(.white, for: .normal) button.titleLabel?.font = .boldSystemFont(ofSize: 16) button.addTarget(self, action: #selector(startStopButtonTapped), for: .touchUpInside) button.backgroundColor = .blue button.layer.cornerRadius = 10 return button }() lazy var mapView: MKMapView = { let mapView = MKMapView() mapView.delegate = self mapView.showsUserLocation = true return mapView }() @objc fileprivate func getDirectionButtonTapped() { guard let text = textField.text else { return } showMapRoute = true textField.endEditing(true) //geoCoder let geoCoder = CLGeocoder() geoCoder.geocodeAddressString(text) { (placemarks, error) in if let error = error { print(error.localizedDescription) return } guard let placemarks = placemarks, let placemark = placemarks.first, let location = placemark.location else { return } let destionationCoordinate = location.coordinate self.mapRoute(destinationCoordinate: destionationCoordinate) } } @objc fileprivate func startStopButtonTapped() { if !navigationStarted { showMapRoute = true if let location = locationManager.location { let center = location.coordinate centerViewToUserLocation(center: center) } } else { if let route = route{ self.mapView.setVisibleMapRect(route.polyline.boundingMapRect, edgePadding: UIEdgeInsets(top: 16, left: 16, bottom: 16, right: 16), animated: true) self.steps.removeAll() self.stepsCounter = 0 } } navigationStarted.toggle() startStopButton.setTitle(navigationStarted ? "Stop Navigation" : "Start Navigation", for: .normal) } override func viewDidLoad() { super.viewDidLoad() locationManager.startUpdatingLocation() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() mapView.frame = view.bounds setUpView() } fileprivate func setUpView(){ view.backgroundColor = .systemBackground view.addSubview(mapView) view.addSubview(uiView) uiView.addSubview(directionLabel) uiView.addSubview(textField) uiView.addSubview(getDirectionButton) uiView.addSubview(startStopButton) uiView.frame = CGRect(x: uiView.frame.size.width , y: uiView.frame.size.height, width: view.frame.size.width , height: view.frame.size.height-580) let xPosition : CGFloat = uiView.frame.origin.x + directionLabel.frame.size.width + 10 directionLabel.frame = CGRect(x: xPosition, y: 40, width: directionLabel.frame.size.width + uiView.frame.size.width - 20, height: 70) textField.frame = CGRect(x: textField.frame.size.height + 10, y: 120, width: 200, height: 50) getDirectionButton.frame = CGRect (x: textField.frame.size.width + 20 , y: 120, width: 145, height: 50) startStopButton.frame = CGRect (x: 10 , y: textField.frame.size.height + 130 , width: 355, height: 45) } fileprivate func centerViewToUserLocation(center: CLLocationCoordinate2D) { let region = MKCoordinateRegion(center: center, latitudinalMeters: locationDistante, longitudinalMeters: locationDistante) mapView.setRegion(region, animated: true) } fileprivate func handleAuthorizationStatus(locationManager: CLLocationManager, status: CLAuthorizationStatus) { switch status { case .notDetermined: locationManager.requestWhenInUseAuthorization() break case .restricted: break case .denied: break case .authorizedAlways: break case .authorizedWhenInUse: //toDo Next if let center = locationManager.location?.coordinate{ centerViewToUserLocation(center: center) } break @unknown default: fatalError() break } } fileprivate func mapRoute(destinationCoordinate: CLLocationCoordinate2D) { guard let sourceCoordinate = locationManager.location?.coordinate else { return } let sourcePlacemark = MKPlacemark(coordinate: sourceCoordinate) let destinationPlaceMark = MKPlacemark(coordinate: destinationCoordinate) let sourceItem = MKMapItem(placemark: sourcePlacemark) let destinationItem = MKMapItem(placemark: destinationPlaceMark) let routeRequest = MKDirections.Request() routeRequest.source = sourceItem routeRequest.destination = destinationItem routeRequest.transportType = .automobile let directions = MKDirections(request: routeRequest) directions.calculate { response, error in if let error = error { print(error.localizedDescription) return } guard let response = response, let route = response.routes.first else { return } self.route = route self.mapView.addOverlay(route.polyline) self.mapView.setVisibleMapRect(route.polyline.boundingMapRect, edgePadding: UIEdgeInsets(top: 16, left: 16, bottom: 16, right: 16), animated: true) self.getRouteSteps(route: route) } } fileprivate func getRouteSteps(route: MKRoute) { for monitoredRegion in locationManager.monitoredRegions{ locationManager.stopMonitoring(for: monitoredRegion) } let steps = route.steps self.steps = steps for i in 0..<steps.count{ let step = steps[i] print(step.instructions) print(step.distance) let region = CLCircularRegion(center: step.polyline.coordinate, radius: 20, identifier: "\(i)") locationManager.startMonitoring(for: region) } stepsCounter += 1 let initialMessage = "In \(steps[stepsCounter].distance) meters, then in \(steps[stepsCounter].instructions) meters, then in \(steps[stepsCounter + 1].distance) meters, \(steps[stepsCounter + 1].instructions)" directionLabel.text = initialMessage directionLabel.font = .boldSystemFont(ofSize: 12) directionLabel.textAlignment = .left print(initialMessage) let speechUtterance = AVSpeechUtterance(string: initialMessage) speechSynthesizer.speak(speechUtterance) } } extension ViewController: CLLocationManagerDelegate{ func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { if !showMapRoute { if let location = locations.last{ let center = location.coordinate centerViewToUserLocation(center: center) } } else { } } func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { handleAuthorizationStatus(locationManager: locationManager, status: status) } func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) { stepsCounter += 1 if stepsCounter < steps.count { let message = "In \(steps[stepsCounter].distance) meters, then in \(steps[stepsCounter].instructions)" directionLabel.text = message let speechUtterance = AVSpeechUtterance(string: message) speechSynthesizer.speak(speechUtterance) } else { let messege = "you have arrive at yout destination" directionLabel.text = messege stepsCounter = 0 navigationStarted = false for monitoredRegion in locationManager.monitoredRegions{ locationManager.stopMonitoring(for: monitoredRegion) } } } } extension ViewController: MKMapViewDelegate{ func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer { let renderer = MKPolylineRenderer(overlay: overlay) renderer.strokeColor = .systemBlue return renderer } }
// // calendarView.swift // VoiceRecorderFinished // // Created by Muhammad Tafani Rabbani on 11/11/19. // Copyright © 2019 Andreas Schultz. All rights reserved. // import SwiftUI struct CalendarView: View { // get the current date and time @ObservedObject var dateModel: DateModel @ObservedObject var recordModel: RecordModel // get the user's calendar var body: some View { VStack { DateView(weekDay: dateModel.dateStruct.dayWeek,mDate: dateModel.dateStruct.currentDate,dateModel: dateModel,recordModel: recordModel) }.background(Color.white) } } struct DateView:View { var weekDay : Int var mDate : Date @ObservedObject var dateModel: DateModel @ObservedObject var recordModel: RecordModel @State var viewState = CGSize.zero @State var arrDate:[Date] = [Date(),Date(),Date(),Date(),Date(),Date(),Date()] @State var arrPicked:[Bool] = [false,false,false,false,false,false,false] @State var arrday:[Int] = [0,0,0,0,0,0,0] var body: some View{ VStack { HStack { Button(action: { self.prevWeek() }) { Image("prevWeek") }.buttonStyle(PlainButtonStyle()) Text("\(dateModel.dateStruct.date) \(dateModel.dateStruct.month) \(dateModel.dateStruct.year)").bold().foregroundColor(Color("Primary")) Button(action: { self.nextWeek() }) { Image("nextWeek") }.buttonStyle(PlainButtonStyle()) }.padding() HStack { Spacer() HStack { DayView(date: $arrday[0], isPicked: $arrPicked[0]).padding(.horizontal,4).onTapGesture { self.taped(index: 0) } DayView(day:"Sel", date: $arrday[1],isPicked: $arrPicked[1]).padding(.horizontal,4).onTapGesture { // self.mDate = self.arrDate[1] // print("tap") self.taped(index: 1) } DayView(day:"Rab", date: $arrday[2],isPicked: $arrPicked[2]).padding(.horizontal,4).onTapGesture { // self.mDate = self.arrDate[2] // print("tap") self.taped(index: 2) } DayView(day:"Kam", date: $arrday[3],isPicked: $arrPicked[3]).padding(.horizontal,4).onTapGesture { // self.mDate = self.arrDate[3] self.taped(index: 3) } DayView(day:"Jum", date: $arrday[4],isPicked: $arrPicked[4]).padding(.horizontal,4).onTapGesture { // self.mDate = self.arrDate[4] self.taped(index: 4) } DayView(day:"Sab", date: $arrday[5],isPicked: $arrPicked[5]).padding(.horizontal,4).onTapGesture { // self.mDate = self.arrDate[5] self.taped(index: 5) } DayView(day:"Min", date: $arrday[6],isPicked: $arrPicked[6]).padding(.horizontal,4).onTapGesture { // self.mDate = self.arrDate[6] self.taped(index: 6) } }.onAppear{ self.setDate() } Spacer() } .offset(x: viewState.width) .animation(.easeOut) .opacity(1 - Double(abs(viewState.width)/200)) .gesture( DragGesture() .onChanged{ value in self.viewState.width = value.translation.width } .onEnded{ value in withAnimation { if self.viewState.width > 100{ self.prevWeek() }else if self.viewState.width < -100{ self.nextWeek() } self.viewState = CGSize.zero } } ) } } func nextWeek(){ let mDate = self.dateModel.dateStruct.currentDate.addingTimeInterval(7 * 60 * 60 * 24) self.dateModel.updateCalendar(newDate: mDate) recordModel.readData(date: dateModel.dateStruct.currentDate) self.setDate() } func prevWeek(){ let mDate = self.dateModel.dateStruct.currentDate.addingTimeInterval(-7 * 60 * 60 * 24) self.dateModel.updateCalendar(newDate: mDate) recordModel.readData(date: dateModel.dateStruct.currentDate) self.setDate() } func taped(index:Int){ self.dateModel.updateCalendar(newDate: self.arrDate[index]) recordModel.readData(date: dateModel.dateStruct.currentDate) for i in 0...6{ self.arrPicked[i]=false } self.arrPicked[index] = true } func setDate(){ arrDate[dateModel.dateStruct.dayWeek] = dateModel.dateStruct.currentDate arrPicked[dateModel.dateStruct.dayWeek] = true var mDate = dateModel.dateStruct.currentDate var i = dateModel.dateStruct.dayWeek - 1 while i>=0{ mDate = mDate.addingTimeInterval((-60 * 60 * 24)) arrDate[i] = mDate i-=1 } i = dateModel.dateStruct.dayWeek + 1 mDate = dateModel.dateStruct.currentDate while i<7 { mDate = mDate.addingTimeInterval(60 * 60 * 24) arrDate[i] = mDate i+=1 } for i in 0...6{ let requestedComponents: Set<Calendar.Component> = [ .year, .month, .day, .weekday ] let userCalendar = Calendar.current let dateTimeComponents = userCalendar.dateComponents(requestedComponents, from: arrDate[i]) arrday[i] = dateTimeComponents.day ?? 0 } } } struct DayView:View { @State var day = "Sen" @Binding var date:Int @Binding var isPicked : Bool var body: some View{ let mTitile = NSLocalizedString(day, comment: "Time to sell 1000 apps") return VStack { Text(mTitile).font(.system(size: 14, design: .default)).bold().foregroundColor(isPicked ? Color.init(#colorLiteral(red: 0.5215686275, green: 0.3176470588, blue: 0.8392156863, alpha: 1)):Color.black).padding(.bottom,15) ZStack { Text("\(date)").font(.system(size: 20, design: .default)).foregroundColor(isPicked ? Color.white:Color.black).padding(.bottom,15) .background(Circle().foregroundColor(isPicked ? Color("Primary"): Color.white).frame(width: 30, height: 30).offset(x: 0, y: -7)) } }.padding(.horizontal,3) } } struct YearView:View { @Binding var year : String var body: some View{ ZStack { Circle().foregroundColor(Color.init(#colorLiteral(red: 0.5215686275, green: 0.3176470588, blue: 0.8392156863, alpha: 1).withAlphaComponent(0.3))).padding() Circle().foregroundColor(Color.init(#colorLiteral(red: 0.5215686275, green: 0.3176470588, blue: 0.8392156863, alpha: 1).withAlphaComponent(0.3))).padding().offset(x: 10, y: 10) Circle().foregroundColor(Color.init(#colorLiteral(red: 0.5215686275, green: 0.3176470588, blue: 0.8392156863, alpha: 1).withAlphaComponent(0.3))).padding().offset(x: -10, y: -10) Circle().foregroundColor(Color.init(#colorLiteral(red: 0.5215686275, green: 0.3176470588, blue: 0.8392156863, alpha: 1).withAlphaComponent(0.3))).padding().offset(x: -10, y: 10) Circle().foregroundColor(Color.init(#colorLiteral(red: 0.5215686275, green: 0.3176470588, blue: 0.8392156863, alpha: 1).withAlphaComponent(0.3))).padding().offset(x: 10, y: -10) Text(year).foregroundColor(.white).font(.title).bold() }.shadow(color:Color("Primary"),radius: 10) } } struct calendarView_Previews: PreviewProvider { static var previews: some View { CalendarView(dateModel: DateModel(), recordModel: RecordModel()) } }
// // Location.swift // WeatherForcast // // Created by Armando D Gonzalez on 9/18/18. // Copyright © 2018 Armando D Gonzalez. All rights reserved. // import Foundation struct Location: Codable { let title: String let locationType: String let latLon: String let woeid: Int private enum CodingKeys: String, CodingKey { case title case woeid case latLon = "latt_long" case locationType = "location_type" } }
// // ViewController.swift // testingArea // // Created by Quast, Malte on 09.11.17. // Copyright © 2017 Quast, Malte. All rights reserved. // import UIKit class HomeVC: UIViewController { @IBOutlet weak var textName: UITextField! @IBOutlet weak var MenuBtn: UIButton! override func viewDidLoad() { super.viewDidLoad() MenuBtn.addTarget(self.revealViewController(), action: #selector(SWRevealViewController.revealToggle(_:)), for: .touchUpInside) self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer()) self.view.addGestureRecognizer(self.revealViewController().tapGestureRecognizer()) } @IBAction func pressedBtn(_ sender: Any) { if textName.text != "" { performSegue(withIdentifier: "moveSegue", sender: self) }else{ let alert = UIAlertController(title: "My Alert", message: "This is an alert.", preferredStyle: .alert) alert.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: "Default action"), style: .`default`, handler: { _ in NSLog("The \"OK\" alert occured.") })) self.present(alert, animated: true, completion: nil) } } // darf nicht in fkt eingebettet sein & muss override sein //Übergabe der Variable an anderen Controller /dieser ist nach as! definiert override func prepare(for segue: UIStoryboardSegue, sender: Any?){ let destView: SecondVC = segue.destination as! SecondVC // erstellen einer variablen mit der klasse SecondViewController // danach wird das Ziel von homeVC auf SecondVC gestellt destView.labelText = textName.text! // links steht der die Variable:String als Label und wir im viewdidload übergeben label // auf der rechten Seite steht das textfeld mit text und wird übergeben an den String im zweiten Controller } @IBAction func backBtn(unwind: UIStoryboardSegue) { } // @IBAction func menu(sender: any){ // // } }
// // AuthorizationContext.swift // Helios // // Created by Lars Stegman on 27-07-17. // Copyright © 2017 Stegman. All rights reserved. // import Foundation /// Holds all contextual information for an authorization process. struct AuthorizationContext { let redirectUri: URL let grantType: GrantType let preferredDuration: AuthorizationDuration let clientId: String let responseType: AuthorizationFlowType let compact: Bool let scopes: [Scope] let sentState: String var receivedState: String? = nil var receivedCode: String? = nil private var scopeList: String { return scopes.map( { return $0.rawValue }).joined(separator: " ") } func authorizationUrl() -> URL { var urlComponents = URLComponents() urlComponents.scheme = "https" urlComponents.host = "www.reddit.com" urlComponents.path = compact ? "/api/v1/authorize.compact" : "/api/v1/authorize" let encodedState = sentState.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? "INVALID_STATE" urlComponents.queryItems = [URLQueryItem(name: "client_id", value: clientId), URLQueryItem(name: "response_type", value: responseType.rawValue), URLQueryItem(name: "state", value: encodedState), URLQueryItem(name: "redirect_uri", value: redirectUri.absoluteString), URLQueryItem(name: "duration", value: preferredDuration.rawValue), URLQueryItem(name: "scope", value: scopeList)] return urlComponents.url! } }
// // CDLocationInfo.swift // easy-test // // Created by German Murillo Bolaños on 6/30/16. // Copyright © 2016 German Murillo Bolaños. All rights reserved. // import Foundation import CoreData /* Objects of this class hold information about a location that can be save and obtained from CoreData */ class CDLocationInfo: NSManagedObject { // Will populate this object with the data in locationInfo func configure(locationInfo:LocationInfo) { self.formattedAddress = locationInfo.formattedAddress self.location = locationInfo.location self.locationType = locationInfo.locationType self.placeId = locationInfo.placeId self.types = locationInfo.types self.viewport = locationInfo.viewport } }
// // CryptoUtil.swift // CryptoFile // // Created by hanwe on 2021/01/25. // import Cocoa import CommonCrypto class CryptoUtil: NSObject { func sha256(data : Data) -> Data { var hash = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH)) data.withUnsafeBytes { _ = CC_SHA256($0.baseAddress, CC_LONG(data.count), &hash) } return Data(hash) } func sha512(data : Data) -> Data { var hash = [UInt8](repeating: 0, count: Int(CC_SHA512_DIGEST_LENGTH)) data.withUnsafeBytes { _ = CC_SHA512($0.baseAddress, CC_LONG(data.count), &hash) } return Data(hash) } }
// // ViewController.swift // Navegador // // Created by Aluno03 on 20/01/17. // Copyright © 2017 pedronobre. All rights reserved. // import UIKit class ViewController: UIViewController, UIWebViewDelegate { @IBOutlet weak var labelComponent: UILabel! @IBOutlet weak var indicatorComponent: UIActivityIndicatorView! @IBOutlet weak var webViewComponent: UIWebView! final let LOAD_ONLINE: Bool = true override func viewDidLoad() { super.viewDidLoad() indicatorComponent.hidesWhenStopped = true if LOAD_ONLINE { self.loadOnline() }else{ self.loadOffline() } } func loadOffline() { if let sourcePath = Bundle.main.path(forResource: "blog-dos-smurfs/blog.html", ofType: nil){ let webPage = URL(fileURLWithPath: sourcePath) let request = URLRequest(url: webPage) webViewComponent.loadRequest(request) } } func loadOnline() { if let pageWeb = URL(string: "https://www.google.com/"){ let request = URLRequest(url: pageWeb) webViewComponent.loadRequest(request) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func home(_ sender: Any) { if LOAD_ONLINE { self.loadOnline() }else{ self.loadOffline() } } @IBAction func back(_ sender: Any) { if webViewComponent.canGoBack { webViewComponent.goBack() } } @IBAction func foward(_ sender: Any) { if webViewComponent.canGoForward { webViewComponent.goForward() } } func webViewDidStartLoad(_ webView: UIWebView) { indicatorComponent.startAnimating() } func webViewDidFinishLoad(_ webView: UIWebView) { indicatorComponent.stopAnimating() } func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool { labelComponent.text = request.url?.absoluteString return true } func webView(_ webView: UIWebView, didFailLoadWithError error: Error) { labelComponent.text = error.localizedDescription } }
// // NSDate+Time.swift // Flex // // Created by Joe Suzuki on 4/27/18. // Copyright © 2018 Joe Suzuki. All rights reserved. // import Foundation import UIKit extension NSDate { func hour() -> Int { //Get Hour let date = Date() let calendar = NSCalendar.current let hour = calendar.component(.hour, from: date) //Return Hour return hour } func minute() -> Int { //Get Minute let date = Date() let calendar = NSCalendar.current let minute = calendar.component(.minute, from: date) //Return Minute return minute } func toShortTimeString() -> String { //Get Short Time String let formatter = DateFormatter() formatter.timeStyle = .short let timeString = formatter.string(from: self as Date) //Return Short Time String return timeString } }
import UIKit protocol RowConfigurable { func configure(cell: UITableViewCell) } protocol Row: RowConfigurable { var reuseIdentifier: String { get } } protocol ConfigurableCell { associatedtype CellData static var reuseIdentifier: String { get } func configure(with data: CellData) } extension ConfigurableCell where Self: UITableViewCell { static var reuseIdentifier: String { return String(describing: self) } } struct TableRow<CellType: ConfigurableCell>: Row where CellType: UITableViewCell { let data: CellType.CellData var reuseIdentifier = CellType.reuseIdentifier init(data: CellType.CellData) { self.data = data } func configure(cell: UITableViewCell) { (cell as? CellType)?.configure(with: data) } } struct TableSection { var rows: [Row] var footerView: UIView? var footerHeight: CGFloat? var footerTitle: String? var headerView: UIView? var headerHeight: CGFloat? var headerTitle: String? init(rows: [Row]) { self.rows = rows } } class TableDataSource: NSObject, UITableViewDataSource { //MARK: - Private Properties private var _sections = [TableSection]() private let queue = DispatchQueue(label: "TableDataSource_Queue") //MARK: - Getter var sections: [TableSection] { queue.sync { return _sections } } //MARK: - LifeCircle init(sections: [TableSection]) { super.init() append(sections: sections) } //MARK: - UITableViewDataSource func numberOfSections(in tableView: UITableView) -> Int { return sections.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return sections[section].rows.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let row = sections[indexPath.section].rows[indexPath.row] let cell = tableView.dequeueReusableCell(withIdentifier: row.reuseIdentifier, for: indexPath) row.configure(cell: cell) return cell } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { return sections[safe: section]?.headerView } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return sections[safe: section]?.headerHeight ?? UITableView.automaticDimension } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return sections[safe: section]?.headerTitle } func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { return sections[safe: section]?.footerView } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return sections[safe: section]?.footerHeight ?? UITableView.automaticDimension } func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? { return sections[safe: section]?.footerTitle } } //MARK: - Setters extension TableDataSource { func append(sections: [TableSection]) { queue.async { self._sections.append(contentsOf: sections) } } func append(section: TableSection) { queue.async { self._sections.append(section) } } func removeAll(keepingCapacity keepCapacity: Bool = false) { queue.async { self._sections.removeAll(keepingCapacity: keepCapacity) } } func insert(section: TableSection, at index: Int) { queue.async { self._sections.insert(section, at: index) } } func insert(sections: [TableSection], at index: Int) { queue.async { self._sections.insert(contentsOf: sections, at: index) } } } extension Collection { subscript(safe index: Index) -> Element? { return indices.contains(index) ? self[index] : nil } }
//: [Previous](@previous) import Foundation struct Person { var clothes: String var shoes: String } let taylor = Person(clothes: "T-shirts", shoes: "sneakers") let other = Person(clothes: "short skirts", shoes: "high heels") print(taylor.clothes) print(other.shoes) var taylorCopy = taylor taylorCopy.shoes = "flip flops" print(taylor) print(taylorCopy) struct Person2 { var clothes: String var shoes: String func describe() { print("I like wearing \(clothes) with \(shoes)") } } //: [Next](@next)
// // MainPageVieController.swift // XyloLearn // // Created by Deepanshu Nautiyal on 31/7/20. // Copyright © 2020 Deepanshu Nautiyal. All rights reserved. // import Foundation import UIKit class HomePageViewController: UIViewController { @IBAction func colourButtonPressed(_ sender: UIButton) { let cVC = self.storyboard?.instantiateViewController(withIdentifier: "colourVC") as! ColorsViewController self.navigationController?.pushViewController(cVC, animated: false) } @IBAction func animalButtonPressed(_ sender: UIButton) { let aVC = self.storyboard?.instantiateViewController(withIdentifier: "animalVC") as! AnimalsViewController self.navigationController?.pushViewController(aVC, animated: false) } @IBAction func xyloButtonPressed(_ sender: UIButton) { let xVC = self.storyboard?.instantiateViewController(withIdentifier: "xyloVC") as! xyloViewController self.navigationController?.pushViewController(xVC, animated: false) } @IBAction func fruitsButtonPressed(_ sender: UIButton) { let fVC = self.storyboard?.instantiateViewController(withIdentifier: "fruitVC") as! FruitsViewController self.navigationController?.pushViewController(fVC, animated: false) } @IBAction func vegesButtonPressed(_ sender: UIButton) { let vVC = self.storyboard?.instantiateViewController(withIdentifier: "vegetableVC") as! VegetablesViewController self.navigationController?.pushViewController(vVC, animated: false) } @IBAction func shapesButtonPressed(_ sender: UIButton) { let sVC = self.storyboard?.instantiateViewController(withIdentifier: "shapesVC") as! ShapesViewController self.navigationController?.pushViewController(sVC, animated: false) } @IBAction func numbersButtonPressed(_ sender: UIButton) { let nVC = self.storyboard?.instantiateViewController(withIdentifier: "numbersVC") as! NumbersViewController self.navigationController?.pushViewController(nVC, animated: false) } }
// // PlatillosViewController.swift // MenuDeslizante // // Created by sergio ivan lopez monzon on 06/12/15. // Copyright © 2015 sergio ivan lopez monzon. All rights reserved. // import UIKit import Parse import ParseFacebookUtilsV4 class PlatillosViewController: UIViewController{ @IBOutlet weak var imageViewReceta: UIImageView! @IBOutlet weak var labelTitulo: UILabel! @IBOutlet weak var imgButtonLike: UIImageView! @IBOutlet weak var textAreaReceta: UITextView! @IBOutlet weak var labelPorciones: UILabel! @IBOutlet weak var labelTiempo: UILabel! var objReceta:PFObject! var imagenReceta:UIImage! @IBOutlet weak var imagenDificultad: UIImageView! @IBOutlet weak var contenidoDeLaRecetaView: UIView! var popViewController: PopUpViewControllerCompartir! @IBOutlet weak var activityLoader: UIActivityIndicatorView! var posicionInicialContenedor:CGFloat! var scrollHaciaArriba = true override func viewWillAppear(_ animated: Bool) { let query = PFQuery(className: "Favoritos") query.includeKey("Recetas") query.whereKey("username", equalTo: PFUser.current()!) query.whereKey("Recetas", equalTo: self.objReceta) query.findObjectsInBackground { (recetas, error) in // comments now contains the comments for myPost if error == nil { //Revisa si ese cliente tiene esa receta para mandar un mensaje de error al tratar de añadirla de nuevo if recetas != nil && (recetas?.count)!>0 { self.imgButtonLike.image = UIImage(named: "like release") } else{ } } else { //print(error!) } } //let navBackgroundImage:UIImage! = UIImage(named: "bandasuperior") //let nav = self.navigationController?.navigationBar //nav?.tintColor = UIColor.white //nav!.setBackgroundImage(navBackgroundImage, for:.default) } override func viewDidLoad() { super.viewDidLoad() activityLoader.isHidden = false activityLoader.startAnimating() self.loadRecetaInformation() let pangesture = UIPanGestureRecognizer(target: self, action: #selector(PlatillosViewController.dragview(_:))) contenidoDeLaRecetaView.addGestureRecognizer(pangesture) self.posicionInicialContenedor = CGFloat(0.0) let backButton = UIBarButtonItem(title: "atrás", style: UIBarButtonItemStyle.plain, target: self, action: nil) backButton.setTitleTextAttributes([NSFontAttributeName: UIFont(name: "AvenirNext-DemiBold", size: 20)!], for: UIControlState()) navigationItem.backBarButtonItem = backButton } func dragview(_ panGestureRecognizer:UIPanGestureRecognizer) { let touchlocation = panGestureRecognizer.velocity(in: self.view) if self.posicionInicialContenedor == CGFloat(0){ self.posicionInicialContenedor = contenidoDeLaRecetaView.center.y scrollHaciaArriba = true } //CGFloat(8)// var delta = abs(touchlocation.y * 0.03) if touchlocation.y < 0 && contenidoDeLaRecetaView.center.y>0{ let ajuste = contenidoDeLaRecetaView.center.y - delta if ajuste < 0{ delta = abs(delta + ajuste) } contenidoDeLaRecetaView.center.y -= delta }else{ let ajuste = contenidoDeLaRecetaView.center.y + delta if ajuste > self.posicionInicialContenedor + pantallaSizeScroll(){ delta = 0 } if touchlocation.y > 0 && contenidoDeLaRecetaView.center.y < self.posicionInicialContenedor + pantallaSizeScroll(){ contenidoDeLaRecetaView.center.y += delta } } } override func viewWillDisappear(_ animated: Bool) { func display_image() { self.labelTitulo.text = "" self.imagenDificultad.image = nil self.labelPorciones.text = "" self.labelTiempo.text = "" self.textAreaReceta.text = "" self.textAreaReceta.text = "" self.imageViewReceta.image = nil self.imageViewReceta.alpha = 0.0 } DispatchQueue.main.async(execute: display_image) } func loadRecetaInformation() { func display_image() { if (self.imagenReceta == nil){ cargarImagen(self.objReceta["Url_Imagen"] as! String) } else{ self.imageViewReceta.image = self.imagenReceta } self.labelTitulo.text = (self.objReceta["Nombre"] as! String) let nivelRecetaStr = (self.objReceta["Nivel"] as! String) if (nivelRecetaStr.lowercased() == "Principiante"){ self.imagenDificultad.image = UIImage(named: "dificultadprincipiante") }else if(nivelRecetaStr.lowercased() == "intermedio"){ self.imagenDificultad.image = UIImage(named: "dificultadmedia") } else{ self.imagenDificultad.image = UIImage(named: "dificultadavanzado") } self.labelPorciones.text = (self.objReceta["Porciones"] as! String) self.labelTiempo.text = (self.objReceta["Tiempo"] as! String) var text: String = "Ingredientes \n" + (self.objReceta["Ingredientes"] as! String) text = text + ("\n\nProcedimiento\n" + (self.objReceta["Procedimiento"] as! String)) let attributedText: NSMutableAttributedString = NSMutableAttributedString(string: text) let str = NSString(string: text) let theRange1 = str.range(of: "Ingredientes") attributedText.addAttribute(NSFontAttributeName, value:UIFont.boldSystemFont(ofSize: pantallaSizeTitulo()), range: theRange1) let theRange2 = str.range(of: "Procedimiento") attributedText.addAttribute(NSFontAttributeName, value:UIFont.boldSystemFont(ofSize: pantallaSizeTitulo()), range: theRange2) let theRangeIngrediente = str.range(of: self.objReceta["Ingredientes"] as! String) attributedText.addAttribute(NSFontAttributeName, value:UIFont.systemFont(ofSize: pantallaSizeCuerpo()), range: theRangeIngrediente) let theRangeProcedimiento = str.range(of: self.objReceta["Procedimiento"] as! String) attributedText.addAttribute(NSFontAttributeName, value:UIFont.systemFont(ofSize: pantallaSizeCuerpo()), range: theRangeProcedimiento) self.textAreaReceta.attributedText = attributedText UIView.animate(withDuration: 0.4, delay: 0, options: UIViewAnimationOptions.curveEaseIn, animations: { self.imageViewReceta.alpha = 100 }, completion: nil) } DispatchQueue.main.async(execute: display_image) } func pantallaSizeCuerpo()->CGFloat! { var strPantalla = 15 //iphone 5 if (UIDevice.current.userInterfaceIdiom == .pad) { strPantalla = 25 } else { if UIScreen.main.bounds.size.width > 320 { if UIScreen.main.scale == 3 { //iphone 6 plus strPantalla = 15 } else{ strPantalla = 15 //iphone 6 } } } return CGFloat(strPantalla) } func pantallaSizeScroll()->CGFloat! { var strPantalla = 0 //iphone 5 if (UIDevice.current.userInterfaceIdiom == .pad) { strPantalla = 0 } else { if UIScreen.main.bounds.size.width > 320 { if UIScreen.main.scale == 3 { //iphone 6 plus strPantalla = 100 } else{ strPantalla = 100 //iphone 6 } } } return CGFloat(strPantalla) } func pantallaSizeTitulo()->CGFloat! { var strPantalla = 20 //iphone 5 if (UIDevice.current.userInterfaceIdiom == .pad) { strPantalla = 40 } else { if UIScreen.main.bounds.size.width > 320 { if UIScreen.main.scale == 3 { //iphone 6 plus strPantalla = 20 } else{ strPantalla = 20 //iphone 6 } } } return CGFloat(strPantalla) } func cargarImagen(_ url:String){ let imgURL: URL = URL(string: url)! let request: URLRequest = URLRequest(url: imgURL) let session = URLSession.shared let task = session.dataTask(with: request, completionHandler: { (data, response, error) -> Void in if (error == nil && data != nil) { self.imageViewReceta.image = UIImage(data: data!) } }) task.resume() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func bCompartir(_ sender: AnyObject) { abrirVentanaPop() } @IBAction func bLike(_ sender: AnyObject) { var usuario = false if PFUser.current() != nil { if PFFacebookUtils.isLinked(with: PFUser.current()!){ usuario = true } /* else if PFTwitterUtils.isLinkedWithUser(PFUser.currentUser()!) { usuario = true }*/ else if PFUser.current() != nil{ usuario = true } } if (usuario == false){ let alertController = UIAlertController(title: "Iniciar sesión obligatorio", message: "Para poder añadir esta reseta a favoritos es necesario iniciar sesión", preferredStyle: UIAlertControllerStyle.alert) alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)) // Display alert self.present(alertController, animated: true, completion: nil) } else{ let query = PFQuery(className: "Favoritos") query.includeKey("Recetas") query.whereKey("username", equalTo: PFUser.current()!) query.whereKey("Recetas", equalTo: self.objReceta) query.findObjectsInBackground { (recetas, error) -> Void in // comments now contains the comments for myPost if error == nil { //Revisa si ese cliente tiene esa receta para mandar un mensaje de error al tratar de añadirla de nuevo if recetas != nil && (recetas?.count)!>0 { // The object has been saved. let alertController = UIAlertController(title: "¡Esta receta ya fue añadida!", message: "Tu receta ya esta en la seccion de favoritos", preferredStyle: UIAlertControllerStyle.alert) alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)) // Display alert self.present(alertController, animated: true, completion: nil) } //Añade la receta a favoritos else{ let date = Date() let calendar = Calendar.current let components = (calendar as NSCalendar).components([.day , .month , .year], from: date) let year = components.year let month = components.month let trimestre = Int( (Double(month!)/3) + 0.7) let favorito = PFObject(className:"Favoritos") favorito["username"] = PFUser.current() favorito["Anio"] = year favorito["Mes"] = month favorito["Trimestre"] = trimestre favorito["Recetas"] = self.objReceta favorito.saveInBackground { (success, error) -> Void in if (success) { self.imgButtonLike.image = UIImage(named: "like release") // The object has been saved. let alertController = UIAlertController(title: "Añadido a favoritos", message: "¡Tu receta ya esta disponible en la seccion de favoritos!", preferredStyle: UIAlertControllerStyle.alert) alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)) // Display alert self.present(alertController, animated: true, completion: nil) } else { // There was a problem, check error.description } } } } else { //print(error!) } } } } func abrirVentanaPop(){ self.popViewController = PopUpViewControllerCompartir(nibName: "PopUpViewControllerCompartir", bundle: nil) self.popViewController.showInView(self.view, animated: true, receta: self.objReceta, imagenReceta: self.imageViewReceta.image!) } }
// // FourthController.swift // Arbel-IOS // // Created by Mac on 19/03/2019. // Copyright © 2019 Mac. All rights reserved. // import UIKit class FourthController: UIViewController { @IBOutlet weak var mailForm: UITextField! @IBOutlet weak var objectForm: UITextField! override func viewDidLoad() { super.viewDidLoad() self.mailForm.layer.cornerRadius = 17 self.objectForm.layer.cornerRadius = 17 // Do any additional setup after loading the view, typically from a nib. print("fourth") } @IBAction func swipeControl(sender: UISwipeGestureRecognizer) { if sender.direction == UISwipeGestureRecognizer.Direction.left { self.tabBarController?.selectedIndex = 4 } else if sender.direction == UISwipeGestureRecognizer.Direction.right { self.tabBarController?.selectedIndex = 2 } } }
// // NoEvent.swift // Ananas // // Created by Thierry Soulie on 30/11/2020. // import SwiftUI struct NoEvent: View { var body: some View { HStack { VStack { Text("Chargement des données") ActivityIndicator(isAnimating: .constant(true), style: .medium) Text("Veuillez patienter") } .padding(10) } } } struct NoEvent_Previews: PreviewProvider { static var previews: some View { NoEvent() } }
import XCTest import BoxAPI class BxAPIManagerTest: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() BxAPIManager.shared.delegate = nil } func testBasicResponseContentsWhenAPIReturnsSuccess() { let expect = XCTestExpectation(description: "timeout") let api = TestAPI() api.request.userId = 2 api.send { (isSuccess) in expect.fulfill() XCTAssertNotNil(api.request.raw) XCTAssertTrue(isSuccess) XCTAssertNotNil(api.response) let resp = api.response XCTAssertEqual(api.status, .succeed) XCTAssertNotNil(resp?.raw) XCTAssertEqual(resp?.statusCode, 200) XCTAssertNotNil(resp?.headers) XCTAssertNotNil(resp?.body) XCTAssertNil(resp?.error) } wait(for: [expect], timeout: 10) } func testBasicResponseContentsWhenAPIReturnsFail() { let expect = XCTestExpectation(description: "timeout") let api = TestAPI() api.request.userId = 123456789 api.send { (isSuccess) in expect.fulfill() XCTAssertNotNil(api.request.raw) XCTAssertFalse(isSuccess) XCTAssertNotNil(api.response) let resp = api.response XCTAssertEqual(api.status, .failed) XCTAssertNotNil(resp?.raw) XCTAssertEqual(resp?.statusCode, 404) XCTAssertNotNil(resp?.headers) XCTAssertNotNil(resp?.body) XCTAssertNotNil(resp?.error) print(resp?.error ?? "") } wait(for: [expect], timeout: 10) } func testExitWhenAPIURLIsInvalid() { let expect = XCTestExpectation(description: "timeout") let api = TestAPI() api.request._domain = "" api.request._action = "" api.send { (isSuccess) in expect.fulfill() XCTAssertFalse(isSuccess) XCTAssertNotNil(api.response) XCTAssertNotNil(api.response?.error) XCTAssertEqual(api.response?.error?.localizedDescription, "Invalid or no request url.") } wait(for: [expect], timeout: 10) } func testAPIManagerShouldDropRequestWhenDelegateReadyToFlyReturnFalse() { let expect = XCTestExpectation(description: "timeout") let delegate = TestAPIDelegate() delegate.apiReadyToFly = false BxAPIManager.shared.delegate = delegate let api = TestAPI() api.send { (_) in expect.fulfill() XCTAssert(false, "The api should drop silently.") } DispatchQueue.main.asyncAfter(deadline: .now() + 8) { expect.fulfill() } wait(for: [expect], timeout: 10) } func testAPIManagerShouldContinueRequestWhenDelegateReadyToFlyReturnTrue() { let expect = XCTestExpectation(description: "timeout") let delegate = TestAPIDelegate() delegate.apiReadyToFly = true BxAPIManager.shared.delegate = delegate let api = TestAPI() api.send { (_) in expect.fulfill() } wait(for: [expect], timeout: 10) } func testAPIManagerShouldDropResponseWhenDelegateAPIReturnReturnFalse() { let expect = XCTestExpectation(description: "timeout") let delegate = TestAPIDelegate() delegate.apiReturned = false BxAPIManager.shared.delegate = delegate let api = TestAPI() api.send { (_) in expect.fulfill() XCTAssert(false, "The api should drop silently.") } DispatchQueue.main.asyncAfter(deadline: .now() + 8) { expect.fulfill() } wait(for: [expect], timeout: 10) } func testAPIManagerShouldContinueResponseWhenDelegateAPIReturnReturnTrue() { let expect = XCTestExpectation(description: "timeout") let delegate = TestAPIDelegate() delegate.apiReturned = true BxAPIManager.shared.delegate = delegate let api = TestAPI() api.send { (_) in expect.fulfill() } wait(for: [expect], timeout: 10) } } class TestAPIDelegate : BxAPIManagerDelegate { var apiReadyToFly = true var apiReturned = true func bxAPIManager<T, U>(_ manager: BxAPIManager, apiReadyToFly api: BoxAPI<T, U>) -> Bool where T : BxRequestProtocol, U : BxResponseProtocol { return apiReadyToFly } func bxAPIManager<T, U>(_ manager: BxAPIManager, apiReturned api: BoxAPI<T, U>, resumeHandler: ((Bool) -> Void)?) -> Bool where T : BxRequestProtocol, U : BxResponseProtocol { return apiReturned } }
// // ViewController.swift // TweetAlarm // // Created by Oliver James Richards on 14/07/2020. // Copyright © 2020 Oliver James Richards. All rights reserved. // // Object oriented programing was trialed, but does not work well in iOS for this kind of simple, system-level integration. // As such, the notification objects were treated as the "alarms" import UIKit import UserNotifications import CoreData class ViewController: UIViewController { //alarm var alarm : Alarm = Alarm() //core data //persistance access var alarmCoreDataManager : CoreDataManager = CoreDataManager.init() var alarmCoreDataSignature : String = "alarmCoreDataSignature" // view variables @IBOutlet weak var alarmSwitch: UISwitch! @IBOutlet weak var alarmTime: UIDatePicker! @IBOutlet weak var demoModeSwitch: UISwitch! //viewDidLoad override func viewDidLoad() { super.viewDidLoad() interfaceSetup() alarm.scheduleAlarm() } //method sets up the display to match the persistent Alarm data func interfaceSetup() { let alarmDate : Date = alarm.getDate() let alarmEnabled : Bool = alarm.getEnabled() let demoMode : Bool = alarm.getDemo() alarmTime.setDate(alarmDate, animated: false) alarmSwitch.setOn(alarmEnabled , animated: false) demoModeSwitch.setOn(demoMode, animated: false) } // method handles toggling of alarm on and off, creating or removing notification @IBAction func alarmToggled(_ sender: Any) { print("we made it") if alarmSwitch.isOn { alarm.setEnabled(enabled: true) alarm.scheduleAlarm() } else { alarm.setEnabled(enabled: false) alarm.descheduleAlarm() } } // method reschedules alarm notification via the Alarm class @IBAction func timeChanged(_ sender: Any) { print("made it to the time change") //change time alarm.setDate(date: alarmTime.date) //resschdule notifications if (alarmSwitch.isOn) { alarm.scheduleAlarm() } else { alarm.descheduleAlarm() } } @IBAction func demoSwitch(_ sender: Any) { alarm.setDemo(demo: demoModeSwitch.isOn) } @IBAction func snoozeButton(_ sender: Any) { alarm.snooze() } //attempt to get segue going @IBAction func unwindToController1(segue: UIStoryboardSegue) {} }
// // IntCodeMachine.swift // aoc2019 // // Created by Shawn Veader on 12/2/19. // Copyright © 2019 Shawn Veader. All rights reserved. // import Foundation class IntCodeMachine { enum State { case halted /// no instructions have been run case running /// started running an instruction case awaitingInput /// machine stopped waiting for input case finished(output: Int) /// machine finished with last output case error } // MARK: - Properties /// Internal (protected) memory used when running the machine private var internalMemory: [Int] /// Contents of memory (read only) for external use. var memory: [Int] { get { return internalMemory } } /// Memory used when accessing outside of the original memory space. /// Stored with address as the key. private var overflowMemory: [Int: Int] /// Location (in memory space) of the current instruction var instructionPointer: Int /// Collection of inputs to use as required. /// If no inputs are found, the machine will sit waiting for input. var inputs: [Int] = [Int]() /// Collections of outputs given over the course of the machine's run. var outputs: [Int] = [Int]() /// Relative base used for instructions in relative mode. var relativeBase: Int = 0 /// Should extra information be printed for debugging? var debug: Bool = false /// Avoid all output, including OUTPUT data. var silent: Bool = false /// Current state of this machine. var state: IntCodeMachine.State = .halted { didSet { if case .running = self.state { runloop() } } } // MARK: - Inits init(memory: [Int]) { instructionPointer = 0 overflowMemory = [Int: Int]() internalMemory = memory } init(instructions: String) { instructionPointer = 0 overflowMemory = [Int: Int]() internalMemory = IntCodeMachine.parse(instructions: instructions) } // MARK: - Static Methods static func parse(instructions: String) -> [Int] { return instructions .trimmingCharacters(in: .whitespacesAndNewlines) .split(separator: ",") .compactMap { Int($0) } } // MARK: - Public Methods func run() { state = .running } /// Run the next func runNextInstruction() { // read instruction let instruction = currentInstruction() printDebug("+==================================================================") printDebug("| Running step: Position: \(instructionPointer)") printDebug("| Instruction: \(instruction)") printDebug("| Memory Size: \(memory.count)") printDebug("| Overflow Memory: \(overflowMemory)") printDebug("| Relative Base: \(relativeBase)") // print(memory) // terminate at the end or bogus instruction guard instruction.opcode != .unknownInstruction, instruction.opcode != .terminate else { state = .finished(output: outputs.last ?? 0) return } printDebug("| Mem Slice: \(memory[instructionPointer..<(instructionPointer + instruction.offset)])") var movedPointer = false switch instruction.opcode { case .add: let value1 = value(for: instruction.parameters[0]) let value2 = value(for: instruction.parameters[1]) let storeAddr = address(for: instruction.parameters[2]) store(value: value1 + value2, at: storeAddr) case .multiply: let value1 = value(for: instruction.parameters[0]) let value2 = value(for: instruction.parameters[1]) let storeAddr = address(for: instruction.parameters[2]) store(value: value1 * value2, at: storeAddr) case .input: guard let input = gatherInput() else { // stop processing and leave the machine in current configuration state = .awaitingInput return } let storeAddr = address(for: instruction.parameters[0]) store(value: input, at: storeAddr) case .output: let outputValue = value(for: instruction.parameters[0]) outputs.append(outputValue) if !silent { print("OUTPUT: \(outputValue)") } case .jumpIfTrue, .jumpIfFalse: let value1 = value(for: instruction.parameters[0]) let value2 = value(for: instruction.parameters[1]) if case .jumpIfTrue = instruction.opcode, value1 != 0 { printDebug("Jumping to \(value2)") instructionPointer = value2 movedPointer = true } else if case .jumpIfFalse = instruction.opcode, value1 == 0 { printDebug("Jumping to \(value2)") instructionPointer = value2 movedPointer = true } case .lessThan, .equals: let value1 = value(for: instruction.parameters[0]) let value2 = value(for: instruction.parameters[1]) let storeAddr = address(for: instruction.parameters[2]) if case .lessThan = instruction.opcode, value1 < value2 { store(value: 1, at: storeAddr) } else if case .equals = instruction.opcode, value1 == value2 { store(value: 1, at: storeAddr) } else { store(value: 0, at: storeAddr) } case .adjustRelativeBase: let value1 = value(for: instruction.parameters[0]) printDebug("Adjusting relative base: from \(relativeBase) to \(relativeBase + value1)") relativeBase += value1 case .terminate, .error: break // nothing to do here case .unknownInstruction: print("Unknown: \(instruction)") } // move to next instruction if !movedPointer { instructionPointer = instructionPointer + instruction.offset } } /// What is the memory value at a given location? /// - parameters: /// - position: Memory location /// - returns: Value of memory location. `-1` for negative address func memory(at position: Int) -> Int { guard position >= 0 else { printDebug("ERROR: Attempted to read from address \(position)") return -1 } if internalMemory.indices.contains(position) { printDebug("Read \(internalMemory[position]) from address: \(position)") return internalMemory[position] } else if overflowMemory.keys.contains(position) { printDebug("Read \(overflowMemory[position] ?? 0) from address: \(position)") return overflowMemory[position] ?? 0 } return 0 // assume uninitialized memory } /// Store a value into the machine's memory at a given position. /// - parameters: /// - value: Value to store in memory /// - position: Memory location func store(value: Int, at position: Int) { printDebug("Storing \(value) at address: \(position)") guard position >= 0 else { printDebug("ERROR: Attempted to store to address \(position)") return } if internalMemory.indices.contains(position) { internalMemory[position] = value } else { overflowMemory[position] = value } } /// Give input to the machine. /// If the machine is waiting for input, it will continue to run again. /// - parameters: /// - input: Input to give to the machine func set(input: Int) { set(inputs: [input]) } /// Give a series of inputs to the machine at once. /// If the machine is waiting for input, it will continue to run again. /// - parameters: /// - inputs: A collection of inputs to give the machine func set(inputs newInputs: [Int]) { inputs.append(contentsOf: newInputs) // if the machine is awaiting input, kick it off again if case .awaitingInput = state { state = .running } } /// Attempts to reset the machine. /// Instruction pointer, relative base, and outputs reset. /// - warning: The memory is not reset, use with caution func reset() { instructionPointer = 0 relativeBase = 0 outputs = [Int]() state = .halted } // MARK: - Private Methods private func runloop() { while case .running = self.state { runNextInstruction() } } private func address(for param: IntCodeInstruction.OpCodeParam) -> Int { switch param { case .position(offset: let offset): // in position mode, memory location needs to be dereferenced when used return memory(at: instructionPointer + offset) case .immediate(offset: let offset): return instructionPointer + offset case .relative(offset: let offset): // in relative mode, the contents of this memory location should be used in conjunction with relativeBase return memory(at: instructionPointer + offset) + relativeBase } } private func value(for param: IntCodeInstruction.OpCodeParam) -> Int { let addr = address(for: param) switch param { case .position(offset: _): return memory(at: addr) case .immediate(offset: _): return memory(at: addr) case .relative(offset: _): return memory(at: addr) } } private func gatherInput() -> Int? { guard !inputs.isEmpty else { return nil } return inputs.removeFirst() } private func currentInstruction() -> IntCodeInstruction { // TODO: can the instruction pointer move into overflow memory? guard memory.indices.contains(instructionPointer) else { return IntCodeInstruction(opcode: .unknownInstruction) } return IntCodeInstruction(input: memory[instructionPointer]) } private func printDebug(_ output: String) { if debug && !silent { print(output) } } }
// // UIView+ReuseIdentifier.swift // Cocktail DB // // Created by Constantine Likhachov on 9/17/19. // Copyright © 2019 Constantine Likhachov. All rights reserved. // import UIKit extension UIView { static var reuseIdentifier: String { return String(describing: self) } static var nib: UINib { return UINib(nibName: self.reuseIdentifier, bundle: nil) } }
// // STBalanceToFundsViewController.swift // SpecialTraining // // Created by yintao on 2019/3/10. // Copyright © 2019 youpeixun. All rights reserved. // 零钱提现 import UIKit class STBalanceToFundsViewController: BaseViewController { @IBOutlet weak var tixianAccountOutlet: UILabel! @IBOutlet weak var tixianCountOutlet: UILabel! @IBOutlet weak var serverChargeOutlet: UILabel! @IBOutlet weak var receiveCountOutlet: UILabel! @IBOutlet weak var applyFundsOutlet: UIButton! private var viewModel: BalanceToFundsViewModel! private var model: MineAccountModel! override func setupUI() { tixianAccountOutlet.text = "微信账户: \(UserAccountServer.share.loginUser.member.nickname)" tixianCountOutlet.text = "¥: \(model.can_commission)" receiveCountOutlet.text = "¥: \(model.can_commission)" } override func rxBind() { viewModel = BalanceToFundsViewModel.init(applyFunds: applyFundsOutlet.rx.tap.asDriver()) viewModel.popSubject .subscribe(onNext: { [weak self] _ in self?.navigationController?.popToRootViewController(animated: true) }) .disposed(by: disposeBag) } override func prepare(parameters: [String : Any]?) { model = (parameters!["model"] as! MineAccountModel) } }
import UIKit class MainViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { var tableView: UITableView? var viewModel: ViewModelType = { return PokemonViewModel() }() override func viewDidLoad() { super.viewDidLoad() self.setUp() // understand what this does self.viewModel.bind(updateHandler: { DispatchQueue.main.async { self.tableView?.reloadData() } }) self.viewModel.fetchPokes() } private func setUp() { let tableView = UITableView(frame: .zero) tableView.translatesAutoresizingMaskIntoConstraints = false tableView.delegate = self tableView.dataSource = self tableView.register(MyTableViewCell.self, forCellReuseIdentifier: MyTableViewCell.reuseId) self.view.addSubview(tableView) tableView.boundToSuperView() self.tableView = tableView } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.viewModel.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: MyTableViewCell.reuseId, for: indexPath) as? MyTableViewCell else { return UITableViewCell() } cell.pokemonName?.text = self.viewModel.name(index: indexPath.row) return cell } }
import Foundation enum Tokens { static let `struct`: String = "struct" static let `class`: String = "class" static let `var`: String = "var" static let `let`: String = "let" static let openCurlyBracket: String = "{" static let closedCurlyBracket: String = "}" static let whitespace: String = " " static let newLine: String = "\n" static let tab: String = "\t" static let empty: String = "" static let colon: String = ":" static let comma: String = "," static let `init`: String = "init" static let openBracket: String = "(" static let closedBracket: String = ")" static let `default`: String = "default" static let `self`: String = "self" static let `Self`: String = "Self" static let equals: String = "=" static let dot: String = "." static let `extension`: String = "extension" static let `static`: String = "static" static let backTick: String = "`" static let `import`: String = "import" static let `final`: String = "final" static let `func`: String = "func" static let minus: String = "-" static let greaterThan: String = ">" static let and: String = "&" static let open: String = "open" static let `public`: String = "public" static let swiftFileExtensions: String = ".swift" static let `case`: String = "case" enum Signatures { static let hasher: String = "func hash(into hasher: inout Hasher)" static func equatable(identifier: String) -> String { "static func ==(lhs: \(identifier), rhs: \(identifier)) -> Bool" } static let codingKeys: String = "enum CodingKeys: String, CodingKey" static let decoderInit: String = "required init(from decoder: Decoder) throws" static let encoder: String = "func encode(to encoder: Encoder) throws" } enum Expression { static func equatable(property: String) -> String { "lhs.\(property) == rhs.\(property)" } static func hasher(property: String) -> String { "hasher.combine(\(property))" } static let decoderContainer: String = "let container = try decoder.container(keyedBy: CodingKeys.self)" static func decodeProperty(identifier: String, type: String) -> String { "self.\(identifier) = try container.decode(\(type).self, forKey: .\(identifier))" } static let encoderContainer: String = "var container = encoder.container(keyedBy: CodingKeys.self)" static func encodeProperty(identifier: String) -> String { "try container.encode(self.\(identifier), forKey: .\(identifier))" } static func mark(description: String) -> String { "// MARK: - Equatable" } } enum Protocols { static let hashable: String = "Hashable" static let equatable: String = "Equatable" static let codable: String = "Codable" static let decodable: String = "Decodable" static let encodable: String = "Encodable" } }
// // ContactDetailTableViewController.swift // KCProgrammingChallenge // // Created by Alejandro Villa Cardenas // import UIKit final class ContactDetailTableViewController: UITableViewController { // MARK: - Variables private let presenter: ContactDetailPresenter private let updateListCompletion: ((_ contact: Contact) -> Void) //MARK: - Init init(presenter: ContactDetailPresenter, updateListCompletion: @escaping (_ contact: Contact) -> Void) { self.presenter = presenter self.updateListCompletion = updateListCompletion super.init(nibName: nil, bundle: nil) setupTableView() setupNavbar() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Private Functions private func setupTableView() { tableView.backgroundColor = .background tableView.dataSource = presenter tableView.showsVerticalScrollIndicator = false tableView.separatorStyle = .none tableView.allowsSelection = false tableView.estimatedRowHeight = UITableView.automaticDimension tableView.register(ContactDetailSummaryTableViewCell.self, forCellReuseIdentifier: ContactDetailSummaryTableViewCell.reuseIdentifier) tableView.register(ContactDetailItemTableViewCell.self, forCellReuseIdentifier: ContactDetailItemTableViewCell.reuseIdentifier) } private func setupNavbar() { let starIcon = UIBarButtonItem(image: presenter.getContactDetailStar(), style: .plain, target: self, action: #selector(handleUserTappingStar)) navigationItem.rightBarButtonItem = starIcon } @objc private func handleUserTappingStar() { presenter.updateContactFavoriteStatus() setupNavbar() updateListCompletion(presenter.contact) } }
//// //// SecondViewController.swift //// FinalProject //// //// Created by Alejandrina Gonzalez on 12/3/17. //// Copyright © 2017 Alejandrina Gonzalez. All rights reserved. //// // //import UIKit //import MapKit // ////IGNORE THIS FILE // //class SecondViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource { // // @IBOutlet weak var map: MKMapView! // @IBOutlet weak var levelsCollectionView: UICollectionView! { // didSet { // levelsCollectionView.delegate = self // levelsCollectionView.dataSource = self // } // } // // // var levels: [Level]! // // @IBOutlet weak var segmentControl: UISegmentedControl! { // didSet { // segmentControl.addTarget(self, action: #selector(changeView), for: .touchUpInside) // } // } // // override func viewDidLoad() { // super.viewDidLoad() // // if UserDefaults.standard.bool(forKey: "hasLaunched") {// get data previosuly saved // // } else { // UserDefaults.standard.set(true, forKey: "hasLaunched") // get data from initial json // UserDefaults.standard.synchronize() // // if let path = Bundle.main.url(forResource: "Levels", withExtension: "json") { // do { // let jsonData = try Data(contentsOf: path, options: .mappedIfSafe) // //let dict = try JSONDecoder().decode([Level].self, from: jsonData) // levels = dict // // } catch let error as NSError { // print("Error: \(error)") // } // } // // } // // // } // // @objc private func changeView() { // if segmentControl.selectedSegmentIndex == 0 { // levelsCollectionView.isHidden = false // map.isHidden = true // } else { // levelsCollectionView.isHidden = true // map.isHidden = false // } // } // // func numberOfSections(in collectionView: UICollectionView) -> Int { // return 1 // } // // func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { // return 6 // } // // func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { // let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! LevelCollectionViewCell // cell.image.image = #imageLiteral(resourceName: "question_mark") // cell.titleLabel.text = "\(indexPath.row)" // return cell // } // // override func didReceiveMemoryWarning() { // super.didReceiveMemoryWarning() // // Dispose of any resources that can be recreated. // } // // // //}
// // OtherProfileTopCell.swift // Clique // // Created by Chris Shadek on 4/21/16. // Copyright © 2016 BuckMe. All rights reserved. // import ParseUI class OtherProfileTopCell: UITableViewCell { @IBOutlet weak var profilePic: PFImageView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var bioTextView: UITextView! var connection = Connection() override func awakeFromNib() { self.profilePic.layer.cornerRadius = 10 self.profilePic.layer.masksToBounds = true } func updateCell(){ self.nameLabel.text = connection.getRealUserName() self.bioTextView.text = connection.bio if self.connection.messageFile == "NONE"{ self.profilePic.file = connection.profilePicture self.profilePic.loadInBackground() } else{ self.profilePic.image = UIImage(named: self.connection.messageFile) } } }
// // Group_Attributes.swift // 100Views // // Created by Mark Moeykens on 8/21/19. // Copyright © 2019 Mark Moeykens. All rights reserved. // import SwiftUI struct Group_SharedAttributes: View { var body: some View { VStack(spacing: 20) { Text("Group") .font(.largeTitle) Text("Shared Attributes") .font(.title) .foregroundColor(.gray) Text("You can use a Group to apply a modifier to all its child views.") .frame(maxWidth: .infinity, minHeight: 70) .padding().font(.title) .background(Color.blue) .foregroundColor(.white) Group { Image(systemName: "leaf.arrow.circlepath") .font(.largeTitle) .padding() Text("Please Recycle") } .padding() .background(Color.blue) .foregroundColor(.white) .cornerRadius(10) Text("Notice the difference between these two:") .font(.system(size: 22)) VStack { Image(systemName: "leaf.arrow.circlepath") .font(.largeTitle) .padding() Text("Please Recycle") } .padding() .background(Color.blue) .foregroundColor(.white) .cornerRadius(10) Text("The modifiers are applied to child views in Groups INDIVIDUALLY.") .frame(maxWidth: .infinity, minHeight: 110) .padding().font(.title) .background(Color.blue) .foregroundColor(.white) } } } struct Group_SharedAttributes_Previews: PreviewProvider { static var previews: some View { Group_SharedAttributes() } }
/* Written by Andrew Walz. Enhanced by Felipe Ricieri (@felipericieri 13/July/17) */ import UIKit import AVFoundation /** * SwiftyCamAudioDelegate * @description Delegate for Audio methods */ public protocol SwiftyCamAudioDelegate { func swiftyCamAudio(_ swiftyCamAudio: SwiftyCamAudioViewController, canStartRecording: Bool) func swiftyCamAudio(_ swiftyCamAudio: SwiftyCamAudioViewController, didStartRecordingAudio recorder: AVAudioRecorder?) func swiftyCamAudio(_ swiftyCamAudio: SwiftyCamAudioViewController, didFinishRecordingAudio recorder: AVAudioRecorder?) func swiftyCamAudio(_ swiftyCamAudio: SwiftyCamAudioViewController, didCaptureAudio audioURL: URL) func swiftyCamAudio(_ swiftyCamAudio: SwiftyCamAudioViewController, didFailedCaptureAudio errorDescription: String) } /** * SwiftyCamAudioViewController * @description SwiftyCamViewController subclass to support Audio Recording */ open class SwiftyCamAudioViewController : SwiftyCamViewController { /** * SwiftyCamAudioDelegate handler */ open var audioDelegate: SwiftyCamAudioDelegate! /** * Max of audio length file */ open var maximumAudioDuration : Double = 10.0 /** * The active record session */ fileprivate lazy var recordingSession: AVAudioSession = AVAudioSession.sharedInstance() /** * the active audio recorder */ fileprivate var audioRecorder: AVAudioRecorder! /** * output filename */ fileprivate(set) public var audioFilename : URL? /** * get-only recording state */ fileprivate(set) public var isAudioRecording : Bool = false /** * tells to the view controller it should substitute the AVCaptureSession to AVAudioRecorder */ public var audioRecordingEnabled : Bool = false /** * prepareAudioRecorder * @description Prepares AVAudioRecorder to work */ public func prepareAudioRecorder() { // Inside delegation handler audioDelegate = self // Set session up do { try recordingSession.setCategory(AVAudioSessionCategoryPlayAndRecord) try recordingSession.setActive(true) recordingSession.requestRecordPermission() { [unowned self] allowed in DispatchQueue.main.async { self.audioDelegate?.swiftyCamAudio(self, canStartRecording: allowed) } } } catch { self.audioDelegate?.swiftyCamAudio(self, canStartRecording: false) } } /** * startAudioRecording * @description Starts the recording session */ public func startAudioRecording() { // Set the filename audioFilename = documentsDirectory()?.appendingPathComponent("swiftyCamAudio.m4a") // Don't proceed with nil filename guard let safeAudioFilename = audioFilename else { audioDelegate?.swiftyCamAudio(self, didFailedCaptureAudio: "Couldn't load the URL of recording media.") return } // Settings let settings = [ AVFormatIDKey: Int(kAudioFormatMPEG4AAC), AVSampleRateKey: 12000, AVNumberOfChannelsKey: 1, AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue ] // Record do { audioRecorder = try AVAudioRecorder(url: safeAudioFilename, settings: settings) audioRecorder.delegate = self audioRecorder.record() // Set is recording isAudioRecording = true audioDelegate?.swiftyCamAudio(self, didStartRecordingAudio: audioRecorder) } catch { // Cancel recording isAudioRecording = false stopAudioRecording(success: false) } } /** * stopAudioRecording * @description Stops the recording session */ public func stopAudioRecording(success: Bool = true, errorString: String? = nil) { audioDelegate?.swiftyCamAudio(self, didFinishRecordingAudio: audioRecorder) audioRecorder.stop() audioRecorder = nil if success { audioDelegate?.swiftyCamAudio(self, didCaptureAudio: audioFilename!) } else { // recording failed :( if let safeError = errorString { audioDelegate?.swiftyCamAudio(self, didFailedCaptureAudio: safeError) } else { audioDelegate?.swiftyCamAudio(self, didFailedCaptureAudio: "Unknown error ocurred") } } } /** * documentsDirectory * @description Fetch the documents' directory * @return Documents Directory */ fileprivate func documentsDirectory() -> URL? { let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) let documentsDirectory = paths.first return documentsDirectory } } // MARK: - SwiftyCamButtonDelegate (Audio Settings) extension SwiftyCamAudioViewController { /** * Only allow proceeding to video record if audio session is disabled */ open override func buttonWasTapped() { if !audioRecordingEnabled { super.buttonWasTapped() } } /** * Only allow proceeding to video record if audio session is disabled */ open override func buttonDidBeginLongPress() { if audioRecordingEnabled { startAudioRecording() } else { super.buttonDidBeginLongPress() } } /** * Only allow proceeding to video record if audio session is disabled */ open override func buttonDidEndLongPress() { if audioRecordingEnabled { stopAudioRecording() } else { super.buttonDidEndLongPress() } } /** * Set maximum audio duration */ open override func setMaxiumVideoDuration() -> Double { if audioRecordingEnabled { return maximumAudioDuration } else { return super.setMaxiumVideoDuration() } } /** * when long press reach maximum, stop recording audio */ open override func longPressDidReachMaximumDuration() { if audioRecordingEnabled { stopAudioRecording() } else { super.longPressDidReachMaximumDuration() } } } // MARK: - AudioRecorderDelegate extension SwiftyCamAudioViewController : AVAudioRecorderDelegate { public func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) { if !flag { stopAudioRecording(success: false, errorString: "Audio Record did stopped with fail (AVAudioRecorder)") } } } // MARK: - SwiftyCamAudioDelegate extension SwiftyCamAudioViewController : SwiftyCamAudioDelegate { open func swiftyCamAudio(_ swiftyCamAudio: SwiftyCamAudioViewController, canStartRecording: Bool) { } open func swiftyCamAudio(_ swiftyCamAudio: SwiftyCamAudioViewController, didStartRecordingAudio recorder: AVAudioRecorder?) { } open func swiftyCamAudio(_ swiftyCamAudio: SwiftyCamAudioViewController, didFinishRecordingAudio recorder: AVAudioRecorder?) { } open func swiftyCamAudio(_ swiftyCamAudio: SwiftyCamAudioViewController, didCaptureAudio audioURL: URL) { } open func swiftyCamAudio(_ swiftyCamAudio: SwiftyCamAudioViewController, didFailedCaptureAudio errorDescription: String) { } }
// // ViewControllerFirst.swift // count down3 // // Created by 新井山詠斗 on 2017/02/01. // Copyright © 2017年 新井山詠斗. All rights reserved. // import UIKit class ViewControllerFirst: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout { let weekArray = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] let numOfDays = 7 let cellMargin : CGFloat = 2.0 var datemanager: DateManager! @IBOutlet weak var calenderCollectionView: UICollectionView! @IBOutlet weak var headerTitle: UILabel! @IBOutlet weak var headerTitle2: UILabel! let dateformatter = DateFormatter() var mister: String = "" override func viewDidLoad() { super.viewDidLoad() datemanager = DateManager() calenderCollectionView.delegate = self calenderCollectionView.dataSource = self headerTitle.text = datemanager.CalendarHeader2() headerTitle2.text = datemanager.CalendarHeader() let rightSwipe = UISwipeGestureRecognizer(target: self, action: Selector(("didSwipe"))) rightSwipe.direction = .right view.addGestureRecognizer(rightSwipe) let leftSwipe = UISwipeGestureRecognizer(target: self, action: Selector(("didSwipe"))) leftSwipe.direction = .left view.addGestureRecognizer(leftSwipe) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func numberOfSections(in collectionView: UICollectionView) -> Int { return 2 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if(section == 0){ return numOfDays }else{ return datemanager.daysAcquisition() } } final func didSwipe(sender: UISwipeGestureRecognizer) { if sender.direction == .right { print("Right") } else if sender.direction == .left { print("Left") } } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CalenderViewCell", for: indexPath) as! CalenderViewCell if(indexPath.section == 0){ cell.backgroundColor = UIColor.green cell.textLabel.text = weekArray[indexPath.row] }else{ cell.backgroundColor = UIColor.white cell.textLabel.text = datemanager.conversionDateFormat(index: indexPath.row) } return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { headerTitle.text = datemanager.CalendarHeader2() headerTitle2.text = datemanager.CalendarHeader() dateformatter.locale = Locale(identifier: "ja_JP") dateformatter.timeStyle = .none dateformatter.dateStyle = .full let iphone = datemanager.currentdayback(index: indexPath.row) let alert: UIAlertController = UIAlertController(title: "確認", message: "\(dateformatter.string(from: iphone))でよろしいですか?", preferredStyle: UIAlertControllerStyle.alert) let defaultAction: UIAlertAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler:{ (action: UIAlertAction!) -> Void in self.mister = self.dateformatter.string(from: iphone) self.performSegue(withIdentifier: "send", sender: nil) }) let cancelAction: UIAlertAction = UIAlertAction(title: "キャンセル", style: UIAlertActionStyle.cancel, handler:{ (action: UIAlertAction!) -> Void in }) alert.addAction(cancelAction) alert.addAction(defaultAction) present(alert, animated: true, completion: nil) print("Num:\(datemanager.conversionDateFormat(index: indexPath.row)) Section:\(indexPath.section)") } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "send"{ let viewcontroller2 = segue.destination as! ViewController2 viewcontroller2.date = self.mister } } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let numberOfMargin:CGFloat = 8.0 let widths:CGFloat = (collectionView.frame.size.width - cellMargin * numberOfMargin)/CGFloat(numOfDays) let heights:CGFloat = widths * 0.8 return CGSize(width:widths,height:heights) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return UIEdgeInsetsMake(0.0 , 0.0 , 0.0 , 0.0 ) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return cellMargin } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return cellMargin } //前月ボタン @IBAction func prevMonthBtn(_ sender: UIButton) { datemanager.preMonthCalendar() calenderCollectionView.reloadData() headerTitle2.text = datemanager.CalendarHeader() } //次月ボタン @IBAction func nextMonthBtn(_ sender: UIButton) { datemanager.nextMonthCalendar() calenderCollectionView.reloadData() headerTitle2.text = datemanager.CalendarHeader() } }
import Foundation enum FontProperties: String { case Name = "font" case Size = "size" } enum LabelProperties: String { case FontStyle = "fontStyle" } enum ButtonProperties: String { case FontStyle = "fontStyle" case BorderWidth = "borderWidth" case BorderColor = "borderColor" case CornerRadius = "cornerRadius" case Normal = "normal" } enum TextFieldProperties: String { case FontStyle = "fontStyle" case BorderWidth = "borderWidth" case BorderColor = "borderColor" case CornerRadius = "cornerRadius" case TextAlignment = "textAlignment" case BorderStyle = "borderStyle" case TextColor = "textColor" } enum SegmentedControlProperties: String { case FontStyle = "fontStyle" case NormalState = "normalState" case SelectedState = "selectedState" case TintColor = "tintColor" } enum SliderProperties: String { case MinimumTrackTintColor = "minimumTrackTintColor" case MaximumTrackTintColor = "maximumTrackTintColor" case ThumbImage = "thumbImage" case MinimumTrackImage = "minimumTrackImage" case MaximumTrackImage = "maximumTrackImage" } enum ColorProperties: String { case Red = "red" case Green = "green" case Blue = "blue" case Alpha = "alpha" } enum UIElements: String { case SegmentedControls = "SegmentedControls" case TextFields = "TextFields" case Buttons = "Buttons" case Labels = "Labels" case Sliders = "Sliders" } enum CommonObjects: String { case Fonts = "Fonts" case Colors = "Colors" case Images = "Images" } enum CommonProperties: String { case TitleColor = "titleColor" case TextColor = "textColor" }
// // FMLabel.swift // FitMom // // Created by Alexandru Vorojbit on 4/25/20. // Copyright © 2020 Alexandru Vorojbit. All rights reserved. // import UIKit class QMLabel: UILabel { override init(frame: CGRect) { super.init(frame: frame) configure() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } init(text: String, textColor: UIColor, font: UIFont, textAlign: NSTextAlignment, lineBreak: NSLineBreakMode, numberOfLines: Int) { super.init(frame: .zero) self.text = text self.textColor = textColor self.font = font self.textAlignment = textAlign self.lineBreakMode = lineBreak self.numberOfLines = numberOfLines configure() } private func configure() { translatesAutoresizingMaskIntoConstraints = false adjustsFontSizeToFitWidth = true } } class TakeCreateQuizLabel: UILabel { override init(frame: CGRect) { super.init(frame: frame) configure() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } init(text: String, textColor: UIColor, font: UIFont) { super.init(frame: .zero) self.text = text self.textColor = textColor self.font = font configure() } private func configure() { translatesAutoresizingMaskIntoConstraints = false adjustsFontSizeToFitWidth = true setContentHuggingPriority(.defaultHigh, for: .horizontal) textAlignment = .left } } // MARK: - Personal Plan Label - class PersonalPlanSmallLabel: UILabel { override init(frame: CGRect) { super.init(frame: frame) configure() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } init(text: String) { super.init(frame: .zero) self.text = text configure() } private func configure() { translatesAutoresizingMaskIntoConstraints = false adjustsFontSizeToFitWidth = true textColor = Colors.lightBlue_darkWhite textAlignment = .left font = .systemFont(ofSize: 17.0, weight: .medium) } } // MARK: - Hero Label - class HeroLabel: UILabel { override init(frame: CGRect) { super.init(frame: frame) configure() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } init(text: String) { super.init(frame: .zero) self.text = text configure() } private func configure() { translatesAutoresizingMaskIntoConstraints = false font = .systemFont(ofSize: 28, weight: .bold) textColor = Colors.lightBlue_darkWhite textAlignment = .left lineBreakMode = .byWordWrapping numberOfLines = 3 } } // MARK: - Offer Plan Label - class OfferPlanLabel: UILabel { override init(frame: CGRect) { super.init(frame: frame) configure() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } init(text: String, textColor: UIColor) { super.init(frame: .zero) self.text = text self.textColor = textColor configure() } private func configure() { translatesAutoresizingMaskIntoConstraints = false adjustsFontSizeToFitWidth = true font = .preferredFont(forTextStyle: .subheadline) textAlignment = .center minimumScaleFactor = 12 } } // MARK: - Discount Label - class DiscountLabel: UILabel { override init(frame: CGRect) { super.init(frame: frame) configure() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } init(text: String) { super.init(frame: .zero) self.text = text configure() } private func configure() { translatesAutoresizingMaskIntoConstraints = false adjustsFontSizeToFitWidth = true font = .systemFont(ofSize: 12, weight: .semibold) textColor = Colors.lightBlue_darkWhite textAlignment = .center minimumScaleFactor = 10 } } // MARK: - Offer Screen Feature Title Label - class FeaturesTitleLabel: UILabel { override init(frame: CGRect) { super.init(frame: frame) configure() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } init(text: String) { super.init(frame: .zero) self.text = text configure() } private func configure() { translatesAutoresizingMaskIntoConstraints = false font = .systemFont(ofSize: 14, weight: .heavy) textColor = Colors.darkGray textAlignment = .left adjustsFontSizeToFitWidth = true minimumScaleFactor = 12 } } // MARK: - Offer Screen Feature List Label - class FeaturesListLabel: UILabel { override init(frame: CGRect) { super.init(frame: frame) configure() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } init(text: String) { super.init(frame: .zero) self.text = text configure() } private func configure() { translatesAutoresizingMaskIntoConstraints = false font = .systemFont(ofSize: 14, weight: .medium) textColor = Colors.darkGray textAlignment = .left adjustsFontSizeToFitWidth = true minimumScaleFactor = 12 } } // MARK: - Restore Purchase Text Label - class RestorePurchaseTextLabel: UILabel { override init(frame: CGRect) { super.init(frame: frame) configure() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } init(text: String) { super.init(frame: .zero) self.text = text configure() } private func configure() { translatesAutoresizingMaskIntoConstraints = false font = .systemFont(ofSize: 13, weight: .regular) textColor = Colors.darkGray textAlignment = .left lineBreakMode = .byWordWrapping numberOfLines = 30 } } // MARK: - Water Settings Labels - class WaterSettingsDailyDrinkLabel: UILabel { override init(frame: CGRect) { super.init(frame: frame) configure() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } init(text: String) { super.init(frame: .zero) self.text = text configure() } private func configure() { translatesAutoresizingMaskIntoConstraints = false font = .systemFont(ofSize: 20, weight: .semibold) textColor = Colors.black textAlignment = .center } } class WaterSettingsDailyGoalQuantityLabel: UILabel { override init(frame: CGRect) { super.init(frame: frame) configure() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } init(text: String) { super.init(frame: .zero) self.text = text configure() } private func configure() { translatesAutoresizingMaskIntoConstraints = false font = .systemFont(ofSize: 22, weight: .semibold) textColor = Colors.black textAlignment = .center } } class WaterSettingsLitreDropLabel: UILabel { override init(frame: CGRect) { super.init(frame: frame) configure() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } init(text: String) { super.init(frame: .zero) self.text = text configure() } private func configure() { translatesAutoresizingMaskIntoConstraints = false font = .systemFont(ofSize: 12, weight: .regular) textColor = Colors.gray textAlignment = .center } }
import Cryptor import Foundation import func Evergreen.getLogger fileprivate let logger = getLogger("hap.device") func generateIdentifier() -> String { do { return Data(bytes: try Random.generate(byteCount: 6)) .map { String($0, radix: 16, uppercase: false) } .joined(separator: ":") } catch { fatalError("Could not generate identifier: \(error)") } } struct Box<T: Any>: Hashable, Equatable { let value: T init(_ value: T) { self.value = value } var object: AnyObject { #if os(macOS) return value as AnyObject #elseif os(Linux) return value as! AnyObject #endif } var hashValue: Int { return ObjectIdentifier(object).hashValue } static func == (lhs: Box<T>, rhs: Box<T>) -> Bool { return ObjectIdentifier(lhs.object) == ObjectIdentifier(rhs.object) } } public class Device { public let name: String public let identifier: String public let publicKey: Data let privateKey: Data public let pin: String let storage: Storage let pairings: Pairings public let accessories: [Accessory] internal var characteristicEventListeners: [Box<Characteristic>: WeakObjectSet<Server.Connection>] public var onIdentify: [(Accessory?) -> ()] = [] public init(name: String, pin: String, storage: Storage, accessories: [Accessory]) { self.name = name self.pin = pin self.storage = storage if let pk = storage["pk"], let sk = storage["sk"], let identifier = storage["uuid"] { self.identifier = String(data: identifier, encoding: .utf8)! publicKey = pk privateKey = sk } else { (publicKey, privateKey) = Ed25519.generateSignKeypair() identifier = generateIdentifier() storage["pk"] = publicKey storage["sk"] = privateKey storage["uuid"] = identifier.data(using: .utf8) } pairings = Pairings(storage: PrefixedKeyStorage(prefix: "pairing.", backing: storage)) self.accessories = accessories characteristicEventListeners = [:] for (offset, accessory) in accessories.enumerated() { accessory.aid = offset + 1 accessory.device = self } } class Pairings { fileprivate let storage: Storage fileprivate init(storage: Storage) { self.storage = storage } public subscript(username: Data) -> Data? { get { return storage[username.hex] } set { storage[username.hex] = newValue } } } public var isPaired: Bool { return !pairings.storage.keys.isEmpty } func add(characteristic: Characteristic, listener: Server.Connection) { if let _ = characteristicEventListeners[Box(characteristic)] { characteristicEventListeners[Box(characteristic)]!.addObject(object: listener) } else { characteristicEventListeners[Box(characteristic)] = [listener] } } @discardableResult func remove(characteristic: Characteristic, listener connection: Server.Connection) -> Server.Connection? { guard let _ = characteristicEventListeners[Box(characteristic)] else { return nil } return characteristicEventListeners[Box(characteristic)]!.remove(connection) } func notify(characteristicListeners characteristic: Characteristic, exceptListener except: Server.Connection? = nil) { guard let listeners = characteristicEventListeners[Box(characteristic)]?.filter({$0 != except}), listeners.count > 0 else { return logger.info("Value changed, but nobody listening") } guard let event = Event(valueChangedOfCharacteristic: characteristic) else { return logger.error("Could not create value change event") } let data = event.serialized() logger.info("Value changed, notifying \(listeners.count) listener(s)") logger.debug("Listeners: \(listeners), event: \(event)") for listener in listeners { listener.writeOutOfBand(data) } } var config: [String: String] { let category: AccessoryType = accessories.count == 1 ? accessories[0].type : .bridge return [ "pv": "1.0", // state "id": identifier, // identifier "c#": "1", // version "s#": "1", // state "sf": (isPaired ? "0" : "1"), // discoverable "ff": "0", // mfi compliant "md": name, // name "ci": category.rawValue // category identifier ] } }
// // ViewController.swift // ViewsProgrammatically // // Created by Douglas Galante on 3/16/17. // Copyright © 2017 Dougly. All rights reserved. // import UIKit // let frame = self.view.frame //let layout = UICollectionViewFlowLayout() //frame: frame, collectionViewLayout: layout class ViewController: RootViewController { var addBtn: UIButton = { let btn = UIButton() btn.backgroundColor = #colorLiteral(red: 0.7444462865, green: 0.09182948204, blue: 0.3330006729, alpha: 1) btn.setImage(UIImage.init(named: "plus.png"), for: .normal) btn.translatesAutoresizingMaskIntoConstraints = false return btn }() override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = #colorLiteral(red: 0, green: 0.4784313725, blue: 1, alpha: 1) self.view.addSubview(self.addBtn) self.addBtn.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true self.addBtn.centerYAnchor.constraint(equalTo: self.view.centerYAnchor).isActive = true self.addBtn.heightAnchor.constraint(equalToConstant: 70).isActive = true self.addBtn.widthAnchor.constraint(equalToConstant: 70).isActive = true self.addBtn.layer.cornerRadius = self.addBtn.frame.height/2.0 } }
// // Stories.swift // TVNews // // Created by SpringML_IOS on 01/03/21. // import SwiftUI struct Stories: View { var body: some View { Text("Stories") } } struct Stories_Previews: PreviewProvider { static var previews: some View { Stories() } }
// // TableNewsCell.swift // RssBankNews // // Created by Nick Chekmazov on 02.12.2020. // import UIKit final class TableNewsCell: UITableViewCell { static var identifier = "TableNewsCell" var cellIndex: IndexPath? lazy var titleLable: UILabel = { let label = UILabel(font: .boldSystemFont(ofSize: Constants.titleFont), textColor: .black) return label }() lazy var dateLabel: UILabel = { let label = UILabel(font: .systemFont(ofSize: Constants.defaultFont), textColor: .black) return label }() lazy var stateLabel: UILabel = { let label = UILabel(font: .systemFont(ofSize: Constants.defaultFont), textColor: .darkGray) return label }() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) configure() addSubViews() addConstraints() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func configure() { backgroundColor = .white accessoryType = .disclosureIndicator } private func addSubViews() { [titleLable, dateLabel, stateLabel].forEach { contentView.addSubview($0) } } private func addConstraints() { NSLayoutConstraint.activate([ titleLable.topAnchor.constraint(equalTo: topAnchor, constant: Constants.topCellAnchor), titleLable.widthAnchor.constraint(equalTo: contentView.widthAnchor), titleLable.leadingAnchor.constraint(equalTo: leadingAnchor), dateLabel.bottomAnchor.constraint(equalTo: bottomAnchor), dateLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: Constants.leadingAnchor), stateLabel.bottomAnchor.constraint(equalTo: bottomAnchor), stateLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: Constants.trailingAnchor), ]) } func update(post: Post) { titleLable.text = post.title dateLabel.text = post.pubDate } override func prepareForReuse() { super.prepareForReuse() stateLabel.text = "" } func state(index: IndexPath) { if cellIndex?.row == index.row { stateLabel.text = "Просмотрено" } else { stateLabel.text = "" } } }
// // CustomPresentationController.swift // PopUpView // // Created by Shi Feng on 2017/4/6. // Copyright © 2017年 Shi Feng. All rights reserved. // import UIKit class CustomPresentationController: UIPresentationController { lazy var backgroundView = BackgroundView(frame: CGRect.zero) override func presentationTransitionWillBegin() { backgroundView.frame = containerView!.bounds containerView!.insertSubview(backgroundView, at: 0) // 以下代码用于设置背景View淡入效果 // backgroundView.alpha = 0 // if let coordinator = presentedViewController.transitionCoordinator { // coordinator.animate(alongsideTransition: { (_) in // self.backgroundView.alpha = 1 // }, completion: nil) // } } // 以下代码用于设置背景View淡出效果 // override func dismissalTransitionWillBegin() { // if let coordinator = presentedViewController.transitionCoordinator { // coordinator.animate(alongsideTransition: { _ in // self.backgroundView.alpha = 0 }, completion: nil) // } // } override var shouldRemovePresentersView: Bool { return false } }
// // AddWishlistVC.swift // TheHoneymoonPlanner // // Created by Brandi Bailey on 2/7/20. // Copyright © 2020 Jonalynn Masters. All rights reserved. // import UIKit import CoreData class AddWishlistVC: UIViewController { @IBOutlet weak var wishlistNameTextField: UITextField! @IBOutlet weak var tableView: UITableView! // MARK: - FetchedResultsController lazy var wishlistFetchedResultsController: NSFetchedResultsController<Wishlist> = { let fetchRequest: NSFetchRequest<Wishlist> = Wishlist.fetchRequest() let descriptor = NSSortDescriptor(keyPath: \Wishlist.item, ascending: true) fetchRequest.sortDescriptors = [descriptor] let moc = CoreDataStack.shared.mainContext let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: moc, sectionNameKeyPath: "item", cacheName: nil) fetchedResultsController.delegate = self do { try fetchedResultsController.performFetch() } catch { print("error performing initial fetch for frc: \(error)") } return fetchedResultsController }() override func viewDidLoad() { super.viewDidLoad() tableView.delegate = self tableView.dataSource = self self.wishlistNameTextField.delegate = self } // MARK: - IBActions @IBAction func doneTapped(_ sender: Any) { self.navigationController?.popViewController(animated: true) } } // MARK: - Extensions extension AddWishlistVC: UITableViewDelegate, UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return wishlistFetchedResultsController.sections?.count ?? 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return wishlistFetchedResultsController.sections?[section].numberOfObjects ?? 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let wishlistCell = tableView.dequeueReusableCell(withIdentifier: "ItemCell", for: indexPath) let wishlist = wishlistFetchedResultsController.object(at: indexPath) wishlistCell.textLabel?.text = wishlist.item return wishlistCell } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { let item = wishlistFetchedResultsController.object(at: indexPath) WishlistController.shared.delete(item) } } } extension AddWishlistVC: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { guard let str = textField.text, !str.isEmpty else { return false } WishlistController.shared.create(with: str) wishlistNameTextField.text = "" wishlistNameTextField.resignFirstResponder() return true } } extension AddWishlistVC: NSFetchedResultsControllerDelegate { func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { tableView.beginUpdates() } func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { tableView.endUpdates() } func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) { let indexSet = IndexSet([sectionIndex]) switch type { case .insert: tableView.insertSections(indexSet, with: .automatic) case .delete: tableView.deleteSections(indexSet, with: .automatic) default: print(#line, #file, "unexpected NSFetchedResultsChangeType: \(type)") } } func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) { switch type { case .delete: guard let indexPath = indexPath else { return } tableView.deleteRows(at: [indexPath], with: .fade) case .insert: guard let newIndexPath = newIndexPath else { return } tableView.insertRows(at: [newIndexPath], with: .fade) case .move: guard let indexPath = indexPath, let newIndexPath = newIndexPath else { return } tableView.moveRow(at: indexPath, to: newIndexPath) case .update: guard let indexPath = indexPath else { return } tableView.reloadRows(at: [indexPath], with: .fade) default: fatalError() } } }
// // AlertPickerView.swift // HyperWerewolfSupporter // // Created by Ichiro Miura on 2018/12/25. // Copyright © 2018年 mycompany. All rights reserved. // import UIKit class AlertPickerView: UIView { var pickerView: UIPickerView! var pickerToolbar: UIToolbar! var toolbarItems: [UIBarItem]! var items:Array<String>! let heightOfPickerView:CGFloat = 216 let heightOfToolbar:CGFloat = 44 var backgroundColorOfPickerView = UIColor.white var backgroundColorOfToolbar = UIColor.white var textColorOfToolbar = UIColor.black var delegate: AlertPickerViewDelegate? { didSet { pickerView.delegate = delegate } } var dataSource: AlertPickerViewDataSource? { didSet { pickerView.dataSource = dataSource } } private var selectedRows: [Int]? override init(frame: CGRect) { super.init(frame: frame) initFunc() } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! initFunc() // println("initfunc") } private func initFunc() { let screenSize = UIScreen.main.bounds.size self.backgroundColor = UIColor.black pickerToolbar = UIToolbar() pickerView = UIPickerView() toolbarItems = [] pickerToolbar.isTranslucent = false pickerView.showsSelectionIndicator = true pickerView.backgroundColor = self.backgroundColorOfPickerView self.frame = CGRect(x:0, y:screenSize.height, width:screenSize.width, height:self.heightOfPickerView + self.heightOfToolbar) //pickerToolbar pickerToolbar.frame = CGRect(x:0, y:0, width:screenSize.width, height:self.heightOfToolbar) pickerToolbar.barTintColor = self.backgroundColorOfPickerView //pickerView pickerView.frame = CGRect(x:0,y:self.heightOfToolbar, width:screenSize.width, height:self.heightOfPickerView) pickerView.backgroundColor = self.backgroundColorOfPickerView let space = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.fixedSpace, target: nil, action: nil) space.width = 12 let cancelItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.cancel, target: self, action: #selector(cancelPicker(sender:))) let flexSpaceItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: self, action: nil) let doneButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.done, target: self, action: #selector(endPicker(sender:))) toolbarItems! += [space, cancelItem, flexSpaceItem, doneButtonItem, space] pickerToolbar.setItems(toolbarItems as? [UIBarButtonItem], animated: false) pickerToolbar.tintColor = self.textColorOfToolbar pickerToolbar.barTintColor = self.backgroundColorOfToolbar self.addSubview(pickerToolbar) self.addSubview(pickerView) } func showPicker() { if selectedRows == nil { selectedRows = getSelectedRows() } delegate?.pickerViewWillShow?(pickerView: pickerView) dataSource?.pickerViewWillShow?(pickerView: pickerView) let screenSize = UIScreen.main.bounds.size UIView.animate(withDuration: 0.2 ,animations: { () -> Void in self.frame = CGRect(x:0, y:screenSize.height - (self.heightOfToolbar + self.heightOfPickerView), width:screenSize.width, height:self.heightOfPickerView + self.heightOfToolbar) }) { (completed:Bool) -> Void in self.delegate?.pickerViewDidSHow?(pickerView: self.pickerView) self.dataSource?.pickerViewDidSHow?(pickerView: self.pickerView) } } @objc func cancelPicker(sender: AnyObject) { hidePicker() restoreSelectedRows() selectedRows = nil } @objc func endPicker(sender: AnyObject) { hidePicker() delegate?.pickerView?(pickerView: pickerView, didSelect: getSelectedRows()) selectedRows = nil } private func hidePicker() { let screenSize = UIScreen.main.bounds.size delegate?.pickerViewWillHide?(pickerView: pickerView) UIView.animate(withDuration: 0.2 ,animations: { () -> Void in self.frame = CGRect(x:0, y:screenSize.height, width:screenSize.width, height:self.heightOfToolbar + self.heightOfPickerView) }) { (completed:Bool) -> Void in self.delegate?.pickerViewDidHide?(pickerView: self.pickerView) } } private func getSelectedRows() -> [Int] { var selectedRows = [Int]() for i in 0 ... pickerView.numberOfComponents - 1 { selectedRows.append(pickerView.selectedRow(inComponent: i)) } return selectedRows } private func restoreSelectedRows() { for i in 0..<selectedRows!.count { pickerView.selectRow(selectedRows![i], inComponent: i, animated: true) } } } @objc protocol AlertPickerViewDelegate: UIPickerViewDelegate { @objc optional func pickerView(pickerView: UIPickerView, didSelect numbers: [Int]) @objc optional func pickerViewDidSHow(pickerView: UIPickerView) @objc optional func pickerViewDidHide(pickerView: UIPickerView) @objc optional func pickerViewWillHide(pickerView: UIPickerView) @objc optional func pickerViewWillShow(pickerView: UIPickerView) @objc optional func pickerViewDidShow(pickerView: UIPickerView) } @objc protocol AlertPickerViewDataSource: UIPickerViewDataSource { @objc optional func pickerView(pickerView: UIPickerView, didSelect numbers: [Int]) @objc optional func pickerViewDidSHow(pickerView: UIPickerView) @objc optional func pickerViewDidHide(pickerView: UIPickerView) @objc optional func pickerViewWillHide(pickerView: UIPickerView) @objc optional func pickerViewWillShow(pickerView: UIPickerView) @objc optional func pickerViewDidShow(pickerView: UIPickerView) }
import Bow import BowGenerators import SwiftCheck public final class DivideLaws<F: Divide & ArbitraryK & EquatableK> { public static func check(isEqual: @escaping (Kind<F, ((Int, Int), Int)>, Kind<F, (Int, (Int, Int))>) -> Bool) { associativity(isEqual: isEqual) } private static func associativity(isEqual: @escaping (Kind<F, ((Int, Int), Int)>, Kind<F, (Int, (Int, Int))>) -> Bool) { func tuple<A, B>(_ a: A, _ b: B) -> (A, B) { (a, b) } property("Associativity") <~ forAll { (fa: KindOf<F, Int>) in isEqual( F.divide(fa.value.divide(fa.value, tuple), fa.value, tuple), fa.value.divide(fa.value.divide(fa.value, tuple), tuple) ) } } }
// // MovieManager.swift // Video Club App // // Created by Rodrigo Camargo on 4/21/21. // import UIKit struct MovieManager { var api = MoviesApi() mutating func getMovies(completion: @escaping (MovieData?, Error?) -> Void) { api.getMovies() { (result) in switch result { case .success(let listOf): completion(listOf, nil) case .failure(let error): completion(nil, error) } } } }