text
stringlengths
8
1.32M
// // TimestampSignature.swift // WavesWallet-iOS // // Created by mefilt on 23.07.2018. // Copyright © 2018 Waves Platform. All rights reserved. // import Foundation import WavesSDKExtensions import WavesSDK import WavesSDKCrypto import DomainLayer import Extensions fileprivate enum Constants { static let timestamp = "timestamp" static let senderPublicKey = "senderPublicKey" static let signature = "signature" } struct TimestampSignature: SignatureProtocol { private(set) var signedWallet: DomainLayer.DTO.SignedWallet private(set) var timestamp: Int64 var toSign: [UInt8] { let s1 = signedWallet.publicKey.publicKey let s2 = toByteArray(timestamp) return s1 + s2 } var parameters: [String: String] { return [Constants.senderPublicKey: signedWallet.publicKey.getPublicKeyStr(), Constants.timestamp: "\(timestamp)", Constants.signature: signature()] } } extension TimestampSignature { init(signedWallet: DomainLayer.DTO.SignedWallet, timestampServerDiff: Int64) { self.init(signedWallet: signedWallet, timestamp: Date().millisecondsSince1970(timestampDiff: timestampServerDiff)) } } struct CreateOrderSignature: SignatureProtocol { struct AssetPair { let priceAssetId: String let amountAssetId: String func assetIdBytes(_ id: String) -> [UInt8] { return (id == WavesSDKConstants.wavesAssetId) ? [UInt8(0)] : ([UInt8(1)] + Base58Encoder.decode(id)) } var bytes: [UInt8] { return assetIdBytes(amountAssetId) + assetIdBytes(priceAssetId) } } enum OrderType { case buy case sell var bytes: [UInt8] { switch self { case .sell: return [UInt8(1)] case .buy: return [UInt8(0)] } } } enum Version: Int { case V2 = 2 case V3 = 3 } private(set) var signedWallet: DomainLayer.DTO.SignedWallet private(set) var timestamp: Int64 private(set) var matcherPublicKey: PublicKeyAccount private(set) var assetPair: AssetPair private(set) var orderType: OrderType private(set) var price: Int64 private(set) var amount: Int64 private(set) var expiration: Int64 private(set) var matcherFee: Int64 private(set) var matcherFeeAsset: String private(set) var version: Version var toSign: [UInt8] { let s1 = toByteArray(UInt8(version.rawValue)) + signedWallet.publicKey.publicKey + matcherPublicKey.publicKey let s2 = assetPair.bytes + orderType.bytes let s3 = toByteArray(price) + toByteArray(amount) let s4 = toByteArray(timestamp) + toByteArray(expiration) + toByteArray(matcherFee) var result = s1 + s2 + s3 + s4 if version == .V3 { result += [UInt8(1)] + (WavesCrypto.shared.base58decode(input: matcherFeeAsset) ?? []) } return result } private var id: [UInt8] { return Hash.fastHash(toSign) } } struct CancelOrderSignature: SignatureProtocol { private(set) var signedWallet: DomainLayer.DTO.SignedWallet private(set) var orderId: String var toSign: [UInt8] { let s1 = signedWallet.publicKey.publicKey let s2 = Base58Encoder.decode(orderId) return s1 + s2 } }
// // AppDelegate.swift // Todo-y // // Created by Benjamin, Matthew on 4/11/19. // Copyright © 2019 Benjamin, Matthew. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { self.window = UIWindow(frame: UIScreen.main.bounds) let navigation1 = UINavigationController() navigation1.navigationBar.tintColor = UIColor.white navigation1.navigationBar.barTintColor = UIColor.init(red: 66 / 255, green: 134 / 255, blue: 244 / 255, alpha: 1.0) // let todoListViewController = TodoListViewController(nibName: nil, bundle: nil) let categoryViewController = CategoryTableViewController() navigation1.viewControllers = [categoryViewController] window!.rootViewController = navigation1 window!.makeKeyAndVisible() return true } func applicationWillTerminate(_ application: UIApplication) { self.saveContext() } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { let container = NSPersistentContainer(name: "DataModel") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
// // ColorPalettes.swift // Connect2U // // Created by Cory Green on 11/21/14. // Copyright (c) 2014 com.Cory. All rights reserved. // import UIKit class ColorPalettes: NSObject { var whiteColor:UIColor = UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0) var lightBlueColor:UIColor = UIColor(red: 0.431, green: 0.808, blue: 0.933, alpha: 1.0) var greenColor:UIColor = UIColor(red: 0.192, green: 0.733, blue: 0.855, alpha: 1.0) var darkGreenColor:UIColor = UIColor(red: 0.075, green: 0.467, blue: 0.557, alpha: 1.0) var redColor:UIColor = UIColor(red: 0.553, green: 0.220, blue: 0.118, alpha: 1.0) var orangeColor:UIColor = UIColor(red: 0.855, green: 0.435, blue: 0.18, alpha: 1.0) }
// // SentMemesTableViewController.swift // MemeMe // // Created by Jubin Benny on 5/21/17. // Copyright © 2017 Jubin Benny. All rights reserved. // import UIKit //MARK: TableView Cell class SentMemeTableViewCell : UITableViewCell { @IBOutlet weak var memeImageView: UIImageView! @IBOutlet weak var memeDetailLabel: UILabel! } //MARK: TableView Controller class SentMemesTableViewController: UITableViewController { let appDelegate = UIApplication.shared.delegate as! AppDelegate override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) tableView.reloadData() } //MARK: TableView Datasource override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 100.0 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return appDelegate.memes.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "MemeDetailCell") as! SentMemeTableViewCell let meme = appDelegate.memes[indexPath.row] cell.memeImageView.image = meme.memedImage cell.memeDetailLabel.text = meme.topQuote + " " + meme.bottomQuote return cell } //MARK: TableView Delegate override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let image = appDelegate.memes[indexPath.row].memedImage self.performSegue(withIdentifier: "showTableDetail", sender: image) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "showTableDetail" { let memeImage = sender as! UIImage let detailVC = segue.destination as! MemeDetailViewController detailVC.memeImage = memeImage } } }
// // AllCommentsVC.swift // CofeeGo // // Created by NI Vol on 11/5/18. // Copyright © 2018 Ni VoL. All rights reserved. // import UIKit class AllCommentsVC: UIViewController,UITableViewDelegate,UITableViewDataSource { @IBOutlet weak var tableView: UITableView! var comments = [ElementComment]() var users = [ElementUser]() override func viewDidLoad() { super.viewDidLoad() tableView.delegate = self tableView.dataSource = self PageCoffee.LoadViewActive = true } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return comments.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "AllCommentsCell", for: indexPath) as! AllCommentsCell let commentElem = comments[indexPath.row] cell.commentLbl.text = commentElem.comment cell.userNameLbl.text = getUserById(userId: commentElem.user!)?.first_name cell.starsView.rating = commentElem.stars cell.dateLbl.text = commentElem.date! return cell } func getUserById(userId: Int) -> ElementUser?{ for user in users{ if user.id == userId{ return user } } return nil } }
// // CategoryCell.swift // intermine-ios // // Created by Nadia on 7/21/17. // Copyright © 2017 Nadia. All rights reserved. // import Foundation import UIKit class CategoryCell: TypeColorCell { @IBOutlet weak var checkImageView: UIImageView? static let identifier = "CategoryCell" @IBOutlet weak var titleLabel: UILabel? @IBOutlet weak var countLabel: UILabel? @IBOutlet weak var typeColorView: UIView? var index: Int = 0 var formattedFacet: FormattedFacet? { didSet { let title = formattedFacet?.getTitle() titleLabel?.text = title countLabel?.text = formattedFacet?.getCount() typeColorView?.backgroundColor = getSideColor(categoryType: title) } } override func awakeFromNib() { super.awakeFromNib() checkImageView?.image = Icons.check } override func prepareForReuse() { super.prepareForReuse() self.hideCheck() } func hideCheck() { checkImageView?.isHidden = true } func showCheck() { checkImageView?.isHidden = false } }
// // BASRoundedButton.swift // basiviti // // Created by BeeSightSoft on 10/31/18. // Copyright © 2018 hnc. All rights reserved. // import UIKit class BASRoundedButton: UIButton { @IBInspectable var cornerRadius: CGFloat = 0 { didSet { layer.cornerRadius = cornerRadius layer.masksToBounds = cornerRadius > 0 } } @IBInspectable var borderWidth: CGFloat = 0 { didSet { layer.borderWidth = borderWidth } } @IBInspectable var borderColor: UIColor? { didSet { layer.borderColor = borderColor?.cgColor } } }
// // TwitterData.swift // Twitter // // Created by Hoang Trong Anh on 7/10/17. // Copyright © 2017 Hoang Trong Anh. All rights reserved. // import Foundation class TwitterData { var tweet: [String:Any] var userOfTweet: [String:Any]? = nil var retweetedStatus: [String:Any]? = nil init(tweet: [String:Any]) { self.tweet = tweet // self.userOfTweet = tweet["user"] as! [String : Any] if let user = self.tweet["user"] as? [String : Any] { self.userOfTweet = user } if let retweeted = self.tweet["retweeted_status"] as? [String: Any] { self.retweetedStatus = retweeted } } public func asString(value: Any) -> String { return (value as? String)! } var getTweetID: String { get { return asString(value: self.tweet["id_str"]!) } } var getCreatedAt: String { let dateFormat = DateFormatter() dateFormat.dateFormat = "eee MMM dd HH:mm:ss ZZZZ yyyy" let date = dateFormat.date(from: self.tweet["created_at"] as! String) dateFormat.dateFormat = "yyyy/MM/dd HH:mm" let da = dateFormat.string(from: date!) return da } var getUserID: Int { get { return self.userOfTweet!["id"] as! Int } } var getAccountName: String { get { return asString(value: self.userOfTweet!["name"]!) } } var getScreenName: String { get { return asString(value: self.userOfTweet!["screen_name"]!) } } var getText: String { get { return asString(value: self.tweet["text"]!) } } var isRetweeted: Bool { get{ return self.tweet["retweeted"] as! Bool } set(newValue) { self.tweet["retweeted"] = newValue } } var isExistRetweetedStatus: Bool { return self.tweet["retweeted_status"] != nil } var retweeted: [String:Any]? { guard let retweeted = self.tweet["retweeted_status"] as? [String: Any] else { return nil } return retweeted } var userID_retweet: Int? { guard let user = retweeted?["user"] as? [String: Any] else { return nil } let userID = user["id"] as? Int return userID } var retweetCount: Int { get { return self.tweet["retweet_count"] as! Int } set(newValue) { self.tweet["retweet_count"] = newValue } } var isFavorited: Bool { get { return self.tweet["favorited"] as! Bool } set(newValue) { self.tweet["favorited"] = newValue } } var favoriteCount: Int { get { if isExistRetweetedStatus { return self.retweetedStatus!["favorite_count"]! as! Int } return self.tweet["favorite_count"] as! Int } set(newValue) { if isExistRetweetedStatus { self.retweetedStatus!["favorite_count"] = newValue } else { self.tweet["favorite_count"] = newValue } } } var infoUserOnRetweetedStatus: [String: Any]? { if let retweeted_status = self.retweeted { let user = retweeted_status["user"] as! [String:Any] return user } return nil } var imageOnTweet : String? { guard let entities = self.tweet["entities"] as? [String:Any] else { return nil } if let media = entities["media"] as? Array<Any> { let inforMedia = media[0] as! [String:Any] return asString(value: inforMedia["media_url_https"]!) } return nil } var tweetUrl: String? { if let id = self.tweet["id_str"] { return "https://twitter.com/\(self.getScreenName)/status/\(id)" } return nil } var tweetUrlShort: String? { guard let entities = self.tweet["entities"] as? [String:Any] else { return nil } if let media = entities["media"] as? Array<Any> { let inforMedia = media[0] as! [String:Any] return asString(value: inforMedia["url"]!) } return nil } func getAvatar() -> String { let tempSaveUrl = asString(value: self.userOfTweet?["profile_image_url_https"]! as Any) let url = tempSaveUrl.replacingOccurrences(of: "_normal", with: "") return url } var isQuote: Bool { if let isQuote = self.tweet["is_quote_status"] { if isQuote as? Bool == true && self.isRetweeted == false { return true } } return false } var quoted_status: [String: Any]? { guard let quoted = self.tweet["quoted_status"] as? [String:Any] else { return nil } return quoted } var q_user: [String: Any]? { guard let user = self.quoted_status?["user"] else { return nil } return (user as! [String : Any]) } var q_account_name: String? { if let name = self.q_user?["name"] { return asString(value: name) } return nil } var q_screen_name: String? { if let sname = self.q_user?["screen_name"] { return asString(value: sname) } return nil } var q_text: String? { if let text = self.quoted_status?["text"] { return asString(value: text) } return nil } var q_imageOnTweet : String? { guard let entities = self.quoted_status?["entities"] as? [String:Any] else { return nil } if let media = entities["media"] as? Array<Any> { let inforMedia = media[0] as! [String:Any] return asString(value: inforMedia["media_url_https"]!) } return nil } // User show var avt: String { let tempSaveUrl = asString(value: self.tweet["profile_image_url_https"]! as Any) let url = tempSaveUrl.replacingOccurrences(of: "_normal", with: "") return url } var description: String { return asString(value: self.tweet["description"]!) } var location: String { return asString(value: self.tweet["location"]!) } var backgroundImage: String { let urlString = asString(value: self.tweet["profile_banner_url"]! as Any) return urlString } var name: String { return asString(value: self.tweet["name"]!) } var scname: String { return asString(value: self.tweet["screen_name"]!) } var followers_count: String { return String(self.tweet["followers_count"] as! Int) } var friends_count: String { return String(self.tweet["friends_count"] as! Int) } var statuses_count: String { return String(self.tweet["statuses_count"] as! Int) } }
// // ViewController.swift // FlattenDictionaries // // Created by Noshaid Ali on 12/04/2020. // Copyright © 2020 Noshaid Ali. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. let dict: [String: Any] = [ "Key1": "1", "Key2": [ "a": "2", "b": "3", "c": [ "d": "3", "e": [ "": "1" ] ] ] ] print(flattenDictionary(dict: dict)) } func flattenDictionary(dict: Dictionary<String, Any>) -> Dictionary<String, Any> { // your code goes here var flatDictionary = [String: Any]() if dict.count == 0 { return flatDictionary } else { makeDict(dict: dict, inputkey: "", flatDictionary: &flatDictionary) } return flatDictionary } func makeDict(dict: Dictionary<String, Any>, inputkey: String, flatDictionary: inout Dictionary<String, Any>) { for (key, value) in dict { if value is Dictionary<String, Any> { if !key.isEmpty && inputkey != "" { makeDict(dict: value as! Dictionary<String, Any>, inputkey: "\(inputkey).\(key)", flatDictionary: &flatDictionary) } else { makeDict(dict: value as! Dictionary<String, Any>, inputkey: key, flatDictionary: &flatDictionary) } } else { if !key.isEmpty && inputkey != "" { flatDictionary["\(inputkey).\(key)"] = value } else { if inputkey != "" { flatDictionary[inputkey] = value } else { flatDictionary[key] = value } } } } } }
// Ver: 0.0000000100 // VerTitle: Cyprian import SpriteKit import GoogleMobileAds fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } public var thisScene = 1 public var topScene = 1 public var topActualScene = 100 public var buttonTitle : String = "" public var itsNewBlock = true public var n = [1,5,9,17,21,25,33,37,41,49] public var timer = 0 public var AdCounter = 0 public var timeForMedal = Array(repeating: [10,13,16], count: 300) public var bestTime = 99 public var MedalOnLvl: [Int] = [Int] (repeating:3, count: 300) public var onPause = false // Мета игра (фрии ту плей) // Показ рекламы // Просмотр видео за след уровень class GameScene: SKScene, SKPhysicsContactDelegate { func skinArrSync() { UserDefaults.standard.set(MainBGPub,forKey: "MainBGPub") UserDefaults.standard.set(skinCondArr,forKey: "skinCondArr") UserDefaults.standard.set(skinBoolArr,forKey: "skinBoolArr") UserDefaults.standard.set(MedalOnLvl, forKey: "MedalOnLvl") UserDefaults.standard.synchronize() } func initNewBlockScreen() { var ok = false for index in 0...(n.count - 1) { if (thisScene == topScene && topScene == n[index]){ ok = true n[index] = 999 } } if (ok == true && itsNewBlock == true && thisScene > 0){ itsNewBlock = false let currentScene = GameScene(fileNamed: "Level 0") thisScene = 0 let transition = SKTransition.doorway(withDuration: 0.5) currentScene!.scaleMode = SKSceneScaleMode.aspectFill currentScene?.viewController = self.viewController self.scene!.view?.presentScene(currentScene!, transition: transition) } if(thisScene == 0){ for ground in self.children { if ground.name == "NewBlock" { if let ground = ground as? SKSpriteNode { ground.size.width = 342 ground.size.height = 342 let text = self.childNode(withName: "Text") as? SKLabelNode let disc = self.childNode(withName: "Disc") as? SKLabelNode switch topScene { case 1: ground.texture = SKTexture(imageNamed: "WoodenBox") text?.text = "Wooden box" disc?.text = "Tap to destroy" case 5: ground.texture = SKTexture(imageNamed: "WoodenPlank") ground.size.width = 720 ground.size.height = 50 text?.text = "Wooden plank" disc?.text = "Tap to destroy" case 9: ground.texture = SKTexture(imageNamed: "SlimeBlock") text?.text = "Slime" disc?.text = "Tap to destroy.\n" + "Bounce block." case 17: ground.texture = SKTexture(imageNamed: "StoneBlock") text?.text = "Stone block" disc?.text = "Tap twice to destroy" case 21: ground.texture = SKTexture(imageNamed: "GlassBlock") text?.text = "Glass" disc?.text = "Tap to destroy.\n" + "No effect gravity." case 25: ground.texture = SKTexture(imageNamed: "SpearBlock") text?.text = "Spiked block" disc?.text = "Kill character" case 33: ground.texture = SKTexture(imageNamed: "ActivaBlock_Off") text?.text = "Non-gravity block" disc?.text = "Tap to stop affect gravity.\n" + "Tap again to start gravity." case 37: ground.texture = SKTexture(imageNamed: "RotationBlock") text?.text = "Rotating block" disc?.text = "Tap to change degree rotation" case 41: ground.texture = SKTexture(imageNamed: "Magnit_Off") text?.text = "Magnet" disc?.text = "Tap to start magnetize" case 49: ground.texture = SKTexture(imageNamed: "RandomBlockGreen") text?.text = "Random Block" disc?.text = "Tap to spawn random block" default: print("SHIT NEW BLOCK CONDITION") print("SHIT NEW BLOCK CONDITION") print("SHIT NEW BLOCK CONDITION") print("SHIT NEW BLOCK CONDITION") print("SHIT NEW BLOCK CONDITION") print("SHIT NEW BLOCK CONDITION") print("SHIT NEW BLOCK CONDITION") print("SHIT NEW BLOCK CONDITION") print("SHIT NEW BLOCK CONDITION") } } } } backgroundColor = #colorLiteral(red:Float(randomBetweenNumbers(firstNum: 0.2, secondNum:0.6)), green: Float(randomBetweenNumbers(firstNum: 0.2, secondNum:0.6)), blue: Float(randomBetweenNumbers(firstNum: 0.2, secondNum:0.6)), alpha: 1) } else { //Инициализация и установка кнопки pause stopButtonInit() } } var viewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "GameViewController") as UIViewController //Рандомные FLOAT цифры func randomBetweenNumbers(firstNum: CGFloat, secondNum: CGFloat) -> CGFloat{ return CGFloat(arc4random()) / CGFloat(UINT32_MAX) * abs(firstNum - secondNum) + min(firstNum, secondNum) } public var groundColorPub = UIColor.green func colorPicker(level: Int) -> UIColor { if (level > 0 && level <= 16) { MainBGPub = 1 return color1 } else { if (level > 16 && level <= 32) { MainBGPub = 2 return color2 } else { if (level > 32 && level <= 48) { MainBGPub = 3 return color3 } else { if (level > 48 && level <= 65) { MainBGPub = 4 return color4 } else { MainBGPub = 2 return color0 } } } } } //Палитра для интерфеса var color0 = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1) var color1 = #colorLiteral(red: 1, green: 0.7871779203, blue: 0.5874175429, alpha: 1) var color2 = #colorLiteral(red: 0.6314342022, green: 0.7059366107, blue: 0.7861329317, alpha: 1) var color3 = #colorLiteral(red: 0.8959465623, green: 0.9631058574, blue: 1, alpha: 1) var color4 = #colorLiteral(red: 0.3883877099, green: 0.7459719181, blue: 0.5895844102, alpha: 1) // ОТЛАДКА ДЛЯ РАЗРАБОТЧИКА public var myLabel1:SKLabelNode! public var myLabel2:SKLabelNode! public var myLabel3:SKLabelNode! public var myLabel4:SKLabelNode! public var myLabel5:SKLabelNode! //Сохранение топовой сцены func setTopScene(topStage: Int) { UserDefaults.standard.set(topStage, forKey: "topStage") UserDefaults.standard.synchronize() print("=======================") print("=======================") print("=======================") print("Был сохранен " + String(topStage)) print("=======================") print("Текущий topScene " + String(topScene)) print("=======================") print("=======================") print("=======================") } //Загрузка топовой сцены func getTopScene() -> (Int) { print("=======================") print("=======================") print("=======================") print("=======================") print("Был загружен " + String(UserDefaults.standard.integer(forKey: "topStage"))) print("=======================") print("=======================") print("=======================") print("=======================") return UserDefaults.standard.integer(forKey: "topStage") } //Инициализация кнопки стоп func stopButtonInit() { let stopButton = SKSpriteNode(imageNamed: "stopButton.png") stopButton.position = CGPoint(x: self.frame.width - 140, y: self.frame.height - 180) stopButton.name = "stop" stopButton.xScale = 0.35 stopButton.yScale = 0.35 stopButton.zPosition = 999 stopButton.alpha = 0.4 stopButton.color = colorPicker(level: thisScene) stopButton.colorBlendFactor = CGFloat(1.0) self.addChild(stopButton) } //Инициализация текста для разработчиков func statusBarInit() { myLabel1 = SKLabelNode(fontNamed: "Arial") myLabel1.fontSize = 40 myLabel1.zPosition = 5 myLabel1.position = CGPoint(x: 70, y: 70) myLabel1.name = "MedalLabel" self.addChild(myLabel1) // myLabel2 = SKLabelNode(fontNamed: "Arial") // myLabel2.fontSize = 40 // myLabel2.zPosition = 999 // myLabel2.position = CGPoint(x: 300, y: 1760) // self.addChild(myLabel2) // // // myLabel3 = SKLabelNode(fontNamed: "Arial") // myLabel3.fontSize = 40 // myLabel3.zPosition = 999 // myLabel3.position = CGPoint(x: 300, y: 1720) // self.addChild(myLabel3) // // // myLabel4 = SKLabelNode(fontNamed: "Arial") // myLabel4.fontSize = 40 // myLabel4.zPosition = 999 // myLabel4.position = CGPoint(x: 300, y: 1680) // self.addChild(myLabel4) // // // myLabel5 = SKLabelNode(fontNamed: "Arial") // myLabel5.fontSize = 30 // myLabel5.zPosition = 999 // myLabel5.position = CGPoint(x: 300, y: 1640) // self.addChild(myLabel5) } // //Изменение текста для разработчиков func statusBar() { if onPause == false { myLabel1.text = String(timer) for menuBoard in self.children { if menuBoard.name == "Medal" { if let menuBoard = menuBoard as? SKSpriteNode { menuBoard.removeAllChildren() menuBoard.removeFromParent() } } } if timer > timeForMedal[thisScene][0] { if timer > timeForMedal[thisScene][1] { if timer > timeForMedal[thisScene][2] { if timer <= timeForMedal[thisScene][2] { } else { print("!Ничего") let menuBoard = SKSpriteNode(imageNamed: "WithOutMedal.png") menuBoard.position = CGPoint(x: 70, y: 70) menuBoard.name = "Medal" menuBoard.xScale = 0.25 menuBoard.yScale = 0.25 menuBoard.zPosition = 4 //menuBoard.color = colorPicker(level: thisScene) //menuBoard.colorBlendFactor = CGFloat(0.7) self.addChild(menuBoard) } } else { print("!Бронза") let menuBoard = SKSpriteNode(imageNamed: "BronzeMedal.png") menuBoard.position = CGPoint(x: 70, y: 70) menuBoard.name = "Medal" menuBoard.xScale = 0.25 menuBoard.yScale = 0.25 menuBoard.zPosition = 4 //menuBoard.color = colorPicker(level: thisScene) //menuBoard.colorBlendFactor = CGFloat(0.7) self.addChild(menuBoard) } } else { print("!Серебро") let menuBoard = SKSpriteNode(imageNamed: "SilverMedal.png") menuBoard.position = CGPoint(x: 70, y: 70) menuBoard.name = "Medal" menuBoard.xScale = 0.25 menuBoard.yScale = 0.25 menuBoard.zPosition = 4 //menuBoard.color = colorPicker(level: thisScene) //menuBoard.colorBlendFactor = CGFloat(0.7) self.addChild(menuBoard) } } else { //print("!Золото") let menuBoard = SKSpriteNode(imageNamed: "GoldMedal.png") menuBoard.position = CGPoint(x: 70, y: 70) menuBoard.name = "Medal" menuBoard.xScale = 0.25 menuBoard.yScale = 0.25 menuBoard.zPosition = 4 //menuBoard.color = colorPicker(level: thisScene) //menuBoard.colorBlendFactor = CGFloat(0.7) self.addChild(menuBoard) } } else { timer = timer - 1 myLabel1.text = "" } // // myLabel2.text = "Топовая сцена = "+String(topScene) // myLabel3.text = "Текущая сцена = "+String(thisScene) //myLabel4.text = "NowScene = "+String(nowScene) //myLabel5.text = "ГГ dy = "+String(describing: dy) } //При вызове этой функции, показывается меню проигрыша. func showLMenu(){ onPause = true let articleParams = ["Loose lvl": thisScene]; Flurry.logEvent("Loose", withParameters: articleParams) Flurry.logEvent("Loose"); let blurEffect = SKSpriteNode(imageNamed: "blur.png") blurEffect.name = "blurEffect" blurEffect.zPosition = 10 blurEffect.size.height = 10000 blurEffect.size.width = 10000 self.addChild(blurEffect) let menuBoard = SKSpriteNode(imageNamed: "MenuBoard.png") menuBoard.position = CGPoint(x: self.frame.midX, y: self.frame.midY) menuBoard.name = "menuBoard" menuBoard.xScale = 1.4 menuBoard.yScale = 1.4 menuBoard.zPosition = 998 menuBoard.color = colorPicker(level: thisScene) menuBoard.colorBlendFactor = CGFloat(0.7) self.addChild(menuBoard) let retryButton = SKSpriteNode(imageNamed: "retryButton.png") retryButton.position = CGPoint(x: self.frame.midX/2, y: self.frame.midY) retryButton.name = "retry" retryButton.xScale = 0.5 retryButton.yScale = 0.5 retryButton.zPosition = 999 retryButton.color = colorPicker(level: thisScene) retryButton.colorBlendFactor = CGFloat(1.0) self.addChild(retryButton) let menuButton = SKSpriteNode(imageNamed: "menuButton.png") menuButton.position = CGPoint(x: self.frame.midX+(self.frame.midX/2), y: self.frame.midY) menuButton.name = "menu" menuButton.xScale = 0.5 menuButton.yScale = 0.5 menuButton.zPosition = 999 menuButton.color = colorPicker(level: thisScene) menuButton.colorBlendFactor = CGFloat(1.0) self.addChild(menuButton) // let button3 = SKSpriteNode(imageNamed: "Button3.png") // button3.position = CGPoint(x: self.frame.midX+(self.frame.midX/2), y: self.frame.midY) // button3.name = "button3" // button3.xScale = 0.5 // button3.yScale = 0.5 // button3.zPosition = 999 // button3.color = colorPicker(level: thisScene) // button3.colorBlendFactor = CGFloat(1.0) // self.addChild(button3) var myLabel:SKLabelNode! myLabel = SKLabelNode(fontNamed: "Arial") myLabel.name = "label" myLabel.text = "Lose" myLabel.fontSize = 100 myLabel.zPosition = 999 myLabel.position = CGPoint(x: self.frame.midX, y: self.frame.midY + 190) self.addChild(myLabel) } //При вызове этой функции, показывается меню перезапуска. func showRMenu(){ // let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.dark) // let blurEffectView = UIVisualEffectView(effect: blurEffect) // blurEffectView.frame = (view?.bounds)! // blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight] // view?.addSubview(blurEffectView) let blurEffect = SKSpriteNode(imageNamed: "blur.png") blurEffect.name = "blurEffect" blurEffect.zPosition = 10 blurEffect.size.height = 10000 blurEffect.size.width = 10000 self.addChild(blurEffect) onPause = true let menuBoard = SKSpriteNode(imageNamed: "MenuBoard.png") menuBoard.position = CGPoint(x: self.frame.midX, y: self.frame.midY) menuBoard.name = "menuBoard" menuBoard.xScale = 1.4 menuBoard.yScale = 1.4 menuBoard.zPosition = 998 menuBoard.color = colorPicker(level: thisScene) menuBoard.colorBlendFactor = CGFloat(0.7) self.addChild(menuBoard) // self.view?.insertSubview(menuBoard, at: 100) let retryButton = SKSpriteNode(imageNamed: "retryButton.png") retryButton.position = CGPoint(x: self.frame.midX/2, y: self.frame.midY) retryButton.name = "retry" retryButton.xScale = 0.5 retryButton.yScale = 0.5 retryButton.zPosition = 999 retryButton.color = colorPicker(level: thisScene) retryButton.colorBlendFactor = CGFloat(1.0) self.addChild(retryButton) let menuButton = SKSpriteNode(imageNamed: "menuButton.png") menuButton.position = CGPoint(x: self.frame.midX+(self.frame.midX/2), y: self.frame.midY) menuButton.name = "menu" menuButton.xScale = 0.5 menuButton.yScale = 0.5 menuButton.zPosition = 999 menuButton.color = colorPicker(level: thisScene) menuButton.colorBlendFactor = CGFloat(1.0) self.addChild(menuButton) // //Для отладки // let prevButton = SKSpriteNode(imageNamed: "prevButton.png") // prevButton.position = CGPoint(x: self.frame.midX - 200, y: self.frame.midY-(self.frame.midY/2)) // prevButton.name = "prev" // prevButton.xScale = 0.5 // prevButton.yScale = 0.5 // prevButton.zPosition = 999 // prevButton.color = colorPicker(level: thisScene) // prevButton.colorBlendFactor = CGFloat(1.0) // self.addChild(prevButton) // let nextButton = SKSpriteNode(imageNamed: "nextButton.png") // nextButton.position = CGPoint(x: self.frame.midX + 200, y: self.frame.midY-(self.frame.midY/2)) // nextButton.name = "next" // nextButton.xScale = 0.5 // nextButton.yScale = 0.5 // nextButton.zPosition = 999 // nextButton.color = colorPicker(level: thisScene) // nextButton.colorBlendFactor = CGFloat(1.0) // self.addChild(nextButton) // var myLabel1:SKLabelNode! // myLabel1 = SKLabelNode(fontNamed: "Arial") // myLabel1.name = "label" // myLabel1.text = "Developer buttons" // myLabel1.fontSize = 50 // myLabel1.zPosition = 1000 // myLabel1.position = CGPoint(x: self.frame.midX, y: self.frame.midY-(self.frame.midY/2) + 140) // self.addChild(myLabel1) // var myLabel:SKLabelNode! myLabel = SKLabelNode(fontNamed: "Arial") myLabel.name = "label" myLabel.text = "Retry" myLabel.fontSize = 100 myLabel.zPosition = 999 myLabel.position = CGPoint(x: self.frame.midX, y: self.frame.midY + 190) self.addChild(myLabel) } /// The interstitial ad. var interstitial: GADInterstitial! fileprivate func createAndLoadInterstitial() { interstitial = GADInterstitial(adUnitID: "ca-app-pub-2270286479492772/1486792443") let request = GADRequest() // Request test ads on devices you specify. Your test device ID is printed to the console when // an ad request is made. request.testDevices = [ kGADSimulatorID, "2077ef9a63d2b398840261c8221a0c9a" ] interstitial.load(request) } // func alertView(_ alertView: UIAlertView, willDismissWithButtonIndex buttonIndex: Int) { // print("Alert ADs") // if interstitial.isReady { // interstitial.present(fromRootViewController: self.viewController) // } else { // print("Ad wasn't ready :(") // } // //playAgainButton.isHidden = false // } func ads() { print("Alert ADs") if interstitial.isReady { interstitial.present(fromRootViewController: self.viewController) } else { print("Ad wasn't ready :(") } //playAgainButton.isHidden = false } //При вызове этой функции, показывается меню выигрыша. func showWMenu(){ onPause = true if thisScene == topScene { topScene+=1 } for menuBoard in self.children { if menuBoard.name == "Medal" { if let menuBoard = menuBoard as? SKSpriteNode { menuBoard.removeAllChildren() menuBoard.removeFromParent() } } } for menuBoard in self.children { if menuBoard.name == "MedalLabel" { if let menuBoard = menuBoard as? SKSpriteNode { menuBoard.removeAllChildren() menuBoard.removeFromParent() } } } let articleParams = ["Win lvl": thisScene]; Flurry.logEvent("Win", withParameters: articleParams) Flurry.logEvent("Win"); let menuBoard = SKSpriteNode(imageNamed: "MenuBoard.png") menuBoard.position = CGPoint(x: self.frame.midX, y: self.frame.midY) menuBoard.name = "menuBoard" menuBoard.xScale = 1.4 menuBoard.yScale = 1.4 menuBoard.zPosition = 998 menuBoard.color = colorPicker(level: thisScene) menuBoard.colorBlendFactor = CGFloat(0.7) self.addChild(menuBoard) let nextButton = SKSpriteNode(imageNamed: "nextButton.png") nextButton.position = CGPoint(x: self.frame.midX/2, y: self.frame.midY) nextButton.name = "next" nextButton.xScale = 0.5 nextButton.yScale = 0.5 nextButton.zPosition = 999 nextButton.color = colorPicker(level: thisScene) nextButton.colorBlendFactor = CGFloat(1.0) self.addChild(nextButton) let retryButton = SKSpriteNode(imageNamed: "retryButton.png") retryButton.position = CGPoint(x: self.frame.midX, y: self.frame.midY) retryButton.name = "retry" retryButton.xScale = 0.5 retryButton.yScale = 0.5 retryButton.zPosition = 999 retryButton.color = colorPicker(level: thisScene) retryButton.colorBlendFactor = CGFloat(1.0) self.addChild(retryButton) let menuButton = SKSpriteNode(imageNamed: "menuButton.png") menuButton.position = CGPoint(x: self.frame.midX+(self.frame.midX/2), y: self.frame.midY) menuButton.name = "menu" menuButton.xScale = 0.5 menuButton.yScale = 0.5 menuButton.zPosition = 999 menuButton.color = colorPicker(level: thisScene) menuButton.colorBlendFactor = CGFloat(1.0) self.addChild(menuButton) //Для отладки // let prevButton = SKSpriteNode(imageNamed: "prevButton.png") // prevButton.position = CGPoint(x: self.frame.midX, y: self.frame.midY-(self.frame.midY/2)) // prevButton.name = "prev" // prevButton.xScale = 0.5 // prevButton.yScale = 0.5 // prevButton.zPosition = 999 // prevButton.color = colorPicker(level: thisScene) // prevButton.colorBlendFactor = CGFloat(1.0) // self.addChild(prevButton) // var myLabel:SKLabelNode! myLabel = SKLabelNode(fontNamed: "Arial") myLabel.name = "label" myLabel.text = "Win" myLabel.fontSize = 100 myLabel.zPosition = 999 myLabel.position = CGPoint(x: self.frame.midX, y: self.frame.midY + 190) self.addChild(myLabel) initMedal() } func initMedal() { let timerWin = timer if bestTime > timerWin { bestTime = timerWin } print("Победное время - " + String(timerWin)) print("Лучшее время - " + String(bestTime)) var flag = false if timeForMedal[thisScene][2] < timerWin { print("Без медали") let menuButtonq = SKSpriteNode(imageNamed: "WithOutMedal.png") menuButtonq.position = CGPoint(x: self.frame.midX+(self.frame.midX/2), y: self.frame.midY - 350) menuButtonq.name = "medal" menuButtonq.xScale = 0.7 menuButtonq.yScale = 0.7 menuButtonq.zPosition = 999 self.addChild(menuButtonq) flag = true } for index in 0...2 { if timeForMedal[thisScene][index] >= timerWin && flag == false { switch index { case 0: print("Золото") let menuButtonq = SKSpriteNode(imageNamed: "GoldMedal.png") menuButtonq.position = CGPoint(x: self.frame.midX+(self.frame.midX/2), y: self.frame.midY - 350) menuButtonq.name = "medal" menuButtonq.xScale = 0.7 menuButtonq.yScale = 0.7 menuButtonq.zPosition = 999 self.addChild(menuButtonq) print("0 " + " - " + String(index) + " - " + String(thisScene) + " - " + String(timeForMedal[thisScene][index])) if MedalOnLvl[thisScene] > index { MedalOnLvl[thisScene] = index } flag = true break case 1: print("Серебро") let menuButtonq = SKSpriteNode(imageNamed: "SilverMedal.png") menuButtonq.position = CGPoint(x: self.frame.midX+(self.frame.midX/2), y: self.frame.midY - 350) menuButtonq.name = "medal" menuButtonq.xScale = 0.7 menuButtonq.yScale = 0.7 menuButtonq.zPosition = 999 self.addChild(menuButtonq) print("1 " + " - " + String(index) + " - " + String(thisScene) + " - " + String(timeForMedal[thisScene][index])) if MedalOnLvl[thisScene] > index { MedalOnLvl[thisScene] = index } flag = true break case 2: print("Бронза") let menuButtonq = SKSpriteNode(imageNamed: "BronzeMedal.png") menuButtonq.position = CGPoint(x: self.frame.midX+(self.frame.midX/2), y: self.frame.midY - 350) menuButtonq.name = "medal" menuButtonq.xScale = 0.7 menuButtonq.yScale = 0.7 menuButtonq.zPosition = 999 self.addChild(menuButtonq) print("2 " + " - " + String(index) + " - " + String(thisScene) + " - " + String(timeForMedal[thisScene][index])) if MedalOnLvl[thisScene] > index { MedalOnLvl[thisScene] = index } flag = true break default: break } } } if(MedalOnLvl[1] == 0 && MedalOnLvl[2] == 0 && MedalOnLvl[3] == 0 && MedalOnLvl[4] == 0 && skinBoolArr[1] == false){ skinBoolArr[1] = true skinArrSync() newSkinAlert() } if(MedalOnLvl[17] == 0 && MedalOnLvl[23] == 0 && MedalOnLvl[25] == 0 && skinBoolArr[5] == false){ skinBoolArr[5] = true skinArrSync() newSkinAlert() } UserDefaults.standard.set(MedalOnLvl, forKey: "MedalOnLvl") UserDefaults.standard.synchronize() } //При вызове этой функции, удаляется меню в игре. func removeMenu(){ onPause = false print("Удаляю МЕНЮ") for menuBoard in self.children { if menuBoard.name == "menuBoard" { if let menuBoard = menuBoard as? SKSpriteNode { menuBoard.removeAllChildren() menuBoard.removeFromParent() } } } for blurEffect in self.children { if blurEffect.name == "blurEffect" { if let blurEffect = blurEffect as? SKSpriteNode { blurEffect.removeAllChildren() blurEffect.removeFromParent() } } } for nextButton in self.children { if nextButton.name == "next" { if let nextButton = nextButton as? SKSpriteNode { nextButton.removeAllChildren() nextButton.removeFromParent() } } } for retryButton in self.children { if retryButton.name == "retry" { if let retryButton = retryButton as? SKSpriteNode { retryButton.removeAllChildren() retryButton.removeFromParent() } } } for menuButton in self.children { if menuButton.name == "menu" { if let menuButton = menuButton as? SKSpriteNode { menuButton.removeAllChildren() menuButton.removeFromParent() } } } for prevButton in self.children { if prevButton.name == "prev" { if let prevButton = prevButton as? SKSpriteNode { prevButton.removeAllChildren() prevButton.removeFromParent() } } } for myLabel in self.children { if myLabel.name == "label" { if let myLabel = myLabel as? SKLabelNode { myLabel.removeAllChildren() myLabel.removeFromParent() } } } //self.view!.isPaused = false } //Ициализация свойств игровых объектов func initGameObject(groundInit: Bool){ if groundInit == true { for main in self.children { if main.name == "MainCharacter" { if let main = main as? SKSpriteNode { //Маска коллизии для ГГ let offsetX: CGFloat = main.frame.size.width * (main.anchorPoint.x - 0.05) let offsetY: CGFloat = main.frame.size.height * (main.anchorPoint.y - 0.05) let path = CGMutablePath() path.move(to: CGPoint(x: 48 - offsetX, y: 35 - offsetY)) path.addLine(to: CGPoint(x: 110 - offsetX, y: 35 - offsetY)) path.addLine(to: CGPoint(x: 123 - offsetX, y: 52 - offsetY)) path.addLine(to: CGPoint(x: 127 - offsetX, y: 82 - offsetY)) path.addLine(to: CGPoint(x: 123 - offsetX, y: 202 - offsetY)) path.addLine(to: CGPoint(x: 104 - offsetX, y: 214 - offsetY)) path.addLine(to: CGPoint(x: 68 - offsetX, y: 218 - offsetY)) path.addLine(to: CGPoint(x: 36 - offsetX, y: 209 - offsetY)) path.addLine(to: CGPoint(x: 25 - offsetX, y: 199 - offsetY)) path.addLine(to: CGPoint(x: 27 - offsetX, y: 67 - offsetY)) path.addLine(to: CGPoint(x: 33 - offsetX, y: 47 - offsetY)) path.closeSubpath() main.physicsBody! = SKPhysicsBody(polygonFrom: path) main.physicsBody?.friction = 0.2 main.physicsBody?.restitution = 0.3 main.physicsBody?.restitution = 0.4 main.physicsBody?.linearDamping = 0.2 main.physicsBody?.angularDamping = 0.2 main.physicsBody?.mass = 2.0 main.physicsBody?.categoryBitMask = 1 main.physicsBody?.contactTestBitMask = 2 main.physicsBody?.collisionBitMask = 2 main.physicsBody?.fieldBitMask = 4 } } } //Цвет Ground let groundColor = #colorLiteral(red:Float(randomBetweenNumbers(firstNum: 0.0, secondNum:1.0)), green: Float(randomBetweenNumbers(firstNum: 0.0, secondNum:1.0)), blue: Float(randomBetweenNumbers(firstNum: 0.0, secondNum:1.0)), alpha: 1) groundColorPub = groundColor //Инициализация Ground for ground in self.children { if ground.name == "Ground" { if let ground = ground as? SKSpriteNode { ground.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: ground.size.width, height: ground.size.height)) ground.physicsBody?.pinned = true ground.physicsBody?.allowsRotation = false ground.physicsBody?.friction = 0.2 ground.physicsBody?.restitution = 0.2 ground.physicsBody?.linearDamping = 0.1 ground.physicsBody?.angularDamping = 0.1 ground.physicsBody?.mass = 6.0 ground.physicsBody?.categoryBitMask = 2; ground.physicsBody?.contactTestBitMask = 1; ground.physicsBody?.collisionBitMask = 1; ground.color = groundColor } } } } // Инициализация SpearBlock for spearBlock in self.children { if spearBlock.name == "SpearBlock" { if let spearBlock = spearBlock as? SKSpriteNode { // ground.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: ground.size.width, height: ground.size.height)) let spearBlockTexture = SKTexture(imageNamed: "SpearBlock.png") spearBlock.physicsBody = SKPhysicsBody(texture: spearBlockTexture, size: CGSize(width: spearBlock.size.width, height: spearBlock.size.height)) spearBlock.physicsBody?.friction = 0.1 spearBlock.physicsBody?.restitution = 0.1 spearBlock.physicsBody?.linearDamping = 0.1 spearBlock.physicsBody?.angularDamping = 0.1 spearBlock.physicsBody?.mass = 2.0 spearBlock.physicsBody?.pinned = true spearBlock.physicsBody?.allowsRotation = false spearBlock.physicsBody?.categoryBitMask = 3; spearBlock.physicsBody?.contactTestBitMask = 1; spearBlock.physicsBody?.collisionBitMask = 1; } } } // Инициализация WallBlockOpen for wallBlock in self.children { if wallBlock.name == "WallBlock" { if let wallBlock = wallBlock as? SKSpriteNode { wallBlock.physicsBody?.friction = 0.1 wallBlock.physicsBody?.restitution = 0.1 wallBlock.physicsBody?.linearDamping = 0.1 wallBlock.physicsBody?.angularDamping = 0.1 wallBlock.physicsBody?.mass = 3.0 wallBlock.physicsBody?.pinned = true wallBlock.physicsBody?.allowsRotation = false } } } // Инициализация SlimeBlock for slimeBlock in self.children { if slimeBlock.name == "SlimeBlock" { if let slimeBlock = slimeBlock as? SKSpriteNode { slimeBlock.physicsBody?.friction = 0.1 slimeBlock.physicsBody?.restitution = 1.1 slimeBlock.physicsBody?.linearDamping = 0.1 slimeBlock.physicsBody?.angularDamping = 0.1 slimeBlock.physicsBody?.mass = 2.0 slimeBlock.physicsBody?.fieldBitMask = 4 } } } // Инициализация WoodenBox for woodenBox in self.children { if woodenBox.name == "WoodenBox" { if let woodenBox = woodenBox as? SKSpriteNode { woodenBox.physicsBody?.friction = 0.2 woodenBox.physicsBody?.restitution = 0.3 woodenBox.physicsBody?.linearDamping = 0.2 woodenBox.physicsBody?.angularDamping = 0.2 woodenBox.physicsBody?.mass = 1.0 woodenBox.physicsBody?.pinned = false woodenBox.physicsBody?.fieldBitMask = 4 } } } // Инициализация RandomBlock for woodenBox in self.children { if woodenBox.name == "RandomBlock" { if let woodenBox = woodenBox as? SKSpriteNode { woodenBox.physicsBody?.friction = 0.2 woodenBox.physicsBody?.restitution = 0.3 woodenBox.physicsBody?.linearDamping = 0.2 woodenBox.physicsBody?.angularDamping = 0.2 woodenBox.physicsBody?.mass = 1.0 woodenBox.physicsBody?.pinned = false woodenBox.physicsBody?.fieldBitMask = 4 } } } // Инициализация RandomBlock2 for woodenBox in self.children { if woodenBox.name == "RandomBlock2" { if let woodenBox = woodenBox as? SKSpriteNode { woodenBox.physicsBody?.friction = 0.2 woodenBox.physicsBody?.restitution = 0.3 woodenBox.physicsBody?.linearDamping = 0.2 woodenBox.physicsBody?.angularDamping = 0.2 woodenBox.physicsBody?.mass = 1.0 woodenBox.physicsBody?.pinned = true woodenBox.physicsBody?.allowsRotation = false woodenBox.physicsBody?.fieldBitMask = 4 } } } // Инициализация GlassBlock for glassBlock in self.children { if glassBlock.name == "GlassBlock" { if let glassBlock = glassBlock as? SKSpriteNode { glassBlock.physicsBody?.friction = 0.2 glassBlock.physicsBody?.restitution = 0.3 glassBlock.physicsBody?.linearDamping = 0.2 glassBlock.physicsBody?.angularDamping = 0.2 glassBlock.physicsBody?.mass = 1.0 glassBlock.physicsBody?.pinned = true glassBlock.physicsBody?.isDynamic = false } } } // Инициализация WoodenPlank for woodenPlank in self.children { if woodenPlank.name == "WoodenPlank" { if let woodenPlank = woodenPlank as? SKSpriteNode { woodenPlank.physicsBody?.friction = 0.2 woodenPlank.physicsBody?.restitution = 0.3 woodenPlank.physicsBody?.linearDamping = 0.2 woodenPlank.physicsBody?.angularDamping = 0.2 woodenPlank.physicsBody?.mass = 1.5 woodenPlank.physicsBody?.fieldBitMask = 4 } } } // Инициализация StoneBlock for stoneBlock in self.children { if stoneBlock.name == "StoneBlock" { if let stoneBlock = stoneBlock as? SKSpriteNode { stoneBlock.physicsBody?.friction = 0.3 stoneBlock.physicsBody?.restitution = 0.2 stoneBlock.physicsBody?.linearDamping = 0.2 stoneBlock.physicsBody?.angularDamping = 0.2 stoneBlock.physicsBody?.mass = 10.0 stoneBlock.physicsBody?.fieldBitMask = 4 stoneBlock.texture = SKTexture(imageNamed: "StoneBlock") } } } // Инициализация ActiveBlock for activeBlock in self.children { if activeBlock.name == "ActiveBlock" { if let activeBlock = activeBlock as? SKSpriteNode { activeBlock.physicsBody?.friction = 0.3 activeBlock.physicsBody?.restitution = 0.3 activeBlock.physicsBody?.linearDamping = 0.4 activeBlock.physicsBody?.angularDamping = 0.4 activeBlock.physicsBody?.mass = 3.0 activeBlock.physicsBody?.fieldBitMask = 4 //Особые характеристики activeBlock.physicsBody?.pinned = true activeBlock.physicsBody?.isDynamic = false } } } // Инициализация Iron for activeBlock in self.children { if activeBlock.name == "IronBlock" { if let activeBlock = activeBlock as? SKSpriteNode { activeBlock.physicsBody?.friction = 0.3 activeBlock.physicsBody?.restitution = 0.3 activeBlock.physicsBody?.linearDamping = 0.4 activeBlock.physicsBody?.angularDamping = 0.4 activeBlock.physicsBody?.mass = 3.0 activeBlock.physicsBody?.fieldBitMask = 3 } } } // Инициализация Magnit for activeBlock in self.children { if activeBlock.name == "Magnit" { if let activeBlock = activeBlock as? SKSpriteNode { activeBlock.physicsBody?.friction = 0.3 activeBlock.physicsBody?.restitution = 0.3 activeBlock.physicsBody?.linearDamping = 0.4 activeBlock.physicsBody?.angularDamping = 0.4 activeBlock.physicsBody?.mass = 2.9 //activeBlock.physicsBody?.fieldBitMask = 3 } } } // Инициализация GravityBlock for activeBlock in self.children { if activeBlock.name == "GravityBlock" { if let activeBlock = activeBlock as? SKSpriteNode { activeBlock.physicsBody?.friction = 0.3 activeBlock.physicsBody?.restitution = 0.3 activeBlock.physicsBody?.linearDamping = 0.4 activeBlock.physicsBody?.angularDamping = 0.4 activeBlock.physicsBody?.mass = 2.9 activeBlock.physicsBody?.fieldBitMask = 4 } } } if groundInit == true { // Инициализация RotationBlock for activeBlock in self.children { if activeBlock.name == "RotationBlock" { if let activeBlock = activeBlock as? SKSpriteNode { activeBlock.physicsBody?.friction = 0.3 activeBlock.physicsBody?.restitution = 0.3 activeBlock.physicsBody?.linearDamping = 0.4 activeBlock.physicsBody?.angularDamping = 0.4 activeBlock.physicsBody?.mass = 2.9 activeBlock.physicsBody?.fieldBitMask = 4 activeBlock.zRotation = 1.57079637050629 activeBlock.physicsBody?.pinned = true activeBlock.physicsBody?.isDynamic = false //activeBlock.physicsBody?.allowsRotation = false } } } } } //Функция выполняемая до открытия сцены override func didMove(to view: SKView) { //for index in 0...300 { // print(index) timeForMedal[0] = [10,13,16] //} timeForMedal[1] = [10,13,16] //Инициализация игровых объектов initGameObject(groundInit: true) //Инициализация статус бара statusBarInit() //Определение макс уровня, до которого дошел игрок if thisScene >= topScene { topScene = thisScene setTopScene(topStage: topScene) } //Если текущая сцена больше либо равна актуальной, то в меню if (topActualScene + 1) <= thisScene { thisScene = 1 let currentScene = GameScene(fileNamed: "Level 1") let transition = SKTransition.doorway(withDuration: 0.5) currentScene!.scaleMode = SKSceneScaleMode.aspectFill currentScene?.viewController = self.viewController self.scene!.view?.presentScene(currentScene!, transition: transition) } self.physicsWorld.contactDelegate = self //Инициализация Экрана нового блока initNewBlockScreen() let node = self.childNode(withName: "MainCharacter")! as SKNode timer = 0 let wait = SKAction.wait(forDuration: 1.0) let run = SKAction.run { timer = timer + 1 print("Time - " + String(timer)) if thisScene > 0 { self.statusBar() } } node.run(SKAction.repeatForever(SKAction.sequence([wait, run]))) createAndLoadInterstitial() onPause = false if thisScene > 0 { statusBar() } skinArrSync() } func newSkinAlert() { let alertView = UIAlertView(title: "New skin unlock", message: "Go to skin manager", delegate: self, cancelButtonTitle: "Ок") //IMAGE // let imvImage = UIImageView(frame: CGRect(x: 0, y: 0, width: 10, height: 10)) // imvImage.contentMode = UIViewContentMode.center // imvImage.image = UIImage(named: "skinButton") // alertView.setValue(imvImage, forKey: "accessoryView") alertView.show() } //Вызывается когда просиходит нажатие override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { // Цикл считывающий нажатие на экран for touch: AnyObject in touches { print(timeForMedal) //Удаление блока при нажатии let touchLocation = touch.location(in: self) let touchedNode = self.atPoint(touchLocation) let touch = touches let location = touch.first!.location(in: self) let node = self.atPoint(location) if touchedNode.name == "SlimeBlock" { skinCondArr[4] = skinCondArr[4] + 1 if skinCondArr[4] == 250 { skinBoolArr[4] = true skinArrSync() newSkinAlert() } } if ( touchedNode.name == "WoodenBox" || touchedNode.name == "WoodenPlank" || touchedNode.name == "SlimeBlock" || touchedNode.name == "GlassBlock" ) { //Удаление touchedNode.removeFromParent() skinCondArr[2] = skinCondArr[2] + 1 if skinCondArr[2] == 500 { skinBoolArr[2] = true skinArrSync() newSkinAlert() } skinCondArr[3] = skinCondArr[3] + 1 if skinCondArr[3] == 1500 { skinBoolArr[3] = true skinArrSync() newSkinAlert() } print(skinCondArr) } if let spriteNode = touchedNode as? SKSpriteNode { if spriteNode.name == "RandomBlock"{ print("RANDOM") var x = randomBetweenNumbers(firstNum: 0.0,secondNum: 0.3) x = x * 10 x = floor(x) print(x) switch x { case 0.0: spriteNode.name = "WoodenBox" spriteNode.texture = SKTexture(imageNamed: "WoodenBox") initGameObject(groundInit: false) break case 1.0: spriteNode.name = "SlimeBlock" spriteNode.texture = SKTexture(imageNamed: "SlimeBlock") initGameObject(groundInit: false) break case 2.0: spriteNode.name = "GlassBlock" spriteNode.texture = SKTexture(imageNamed: "GlassBlock") initGameObject(groundInit: false) break default: break } } } if let spriteNode = touchedNode as? SKSpriteNode { if spriteNode.name == "RandomBlock2"{ print("RANDOM") var x = randomBetweenNumbers(firstNum: 0.0,secondNum: 0.3) x = x * 10 x = floor(x) print(x) switch x { case 0.0: spriteNode.name = "GlassBlock" spriteNode.texture = SKTexture(imageNamed: "GlassBlock") initGameObject(groundInit: false) break case 1.0: spriteNode.name = "SpearBlock" spriteNode.texture = SKTexture(imageNamed: "SpearBlock") initGameObject(groundInit: false) break case 2.0: spriteNode.name = "RotationBlock" spriteNode.texture = SKTexture(imageNamed: "RotationBlock") initGameObject(groundInit: false) break default: break } } } //Механика Волл блока if let spriteNode = touchedNode as? SKSpriteNode { if spriteNode.name == "WallBlock"{ if spriteNode.physicsBody?.allowsRotation == true { spriteNode.physicsBody?.pinned = true spriteNode.physicsBody?.allowsRotation = false spriteNode.texture = SKTexture(imageNamed: "WallBlockOpen") } else { spriteNode.physicsBody?.pinned = true spriteNode.physicsBody?.allowsRotation = true spriteNode.texture = SKTexture(imageNamed: "WallBlockClose") } } } //Механика Актив блока if let spriteNode = touchedNode as? SKSpriteNode { if spriteNode.name == "ActiveBlock"{ if spriteNode.physicsBody?.pinned == false{ spriteNode.physicsBody?.pinned = true spriteNode.physicsBody?.isDynamic = false print("ActiveBlock_TRUE") // OFF spriteNode.texture = SKTexture(imageNamed: "ActivaBlock_Off") } else{ spriteNode.physicsBody?.pinned = false spriteNode.physicsBody?.isDynamic = true print("ActiveBlock_FALSE") //ON spriteNode.texture = SKTexture(imageNamed: "ActivaBlock_On") } } } //Механика Гравити блока if let spriteNode = touchedNode as? SKSpriteNode { if spriteNode.name == "GravityBlock"{ let gravity = self.childNode(withName: "Gravity") as? SKFieldNode if (spriteNode.physicsBody?.mass == 3.0){ spriteNode.physicsBody?.mass = 2.9 print("STOP") let m5 = SKTexture(imageNamed: "GravityBlock_Off") let animation = SKAction.animate(with: [m5], timePerFrame: 10) spriteNode.run(SKAction.repeatForever(animation)) spriteNode.texture = SKTexture(imageNamed: "GravityBlock_Off") gravity?.isEnabled = false } else{ spriteNode.physicsBody?.mass = 3.0 print("START") let m1 = SKTexture(imageNamed: "GravityBlock_On1") let m2 = SKTexture(imageNamed: "GravityBlock_On2") let m3 = SKTexture(imageNamed: "GravityBlock_On3") let m4 = SKTexture(imageNamed: "GravityBlock_On4") let textures = [m1, m2, m3, m4] let animation = SKAction.animate(with: textures, timePerFrame: 0.1) spriteNode.run(SKAction.repeatForever(animation)) gravity?.isEnabled = true } } } //Механика Магнита блока if let spriteNode = touchedNode as? SKSpriteNode { if spriteNode.name == "Magnit"{ let gravity = self.childNode(withName: "MagnitGravity") as? SKFieldNode if (spriteNode.physicsBody?.mass == 3.0){ // OFF spriteNode.texture = SKTexture(imageNamed: "Magnit_Off") spriteNode.physicsBody?.mass = 2.9 gravity?.isEnabled = false } else{ //ON spriteNode.texture = SKTexture(imageNamed: "Magnit_On") spriteNode.physicsBody?.mass = 3.0 gravity?.isEnabled = true } } } //Механика Каменного блока if let spriteNode = touchedNode as? SKSpriteNode { if spriteNode.name == "StoneBlock"{ if spriteNode.physicsBody?.mass == 10.0 { spriteNode.texture = SKTexture(imageNamed: "BrokenStoneBlock") spriteNode.physicsBody?.mass = 9.0 } else{ //saveStat(info: "destroy") spriteNode.removeFromParent() } } } //Механика Поворотного блока if let spriteNode = touchedNode as? SKSpriteNode { if spriteNode.name == "RotationBlock"{ spriteNode.physicsBody?.isDynamic = true spriteNode.zRotation = spriteNode.zRotation - CGFloat(M_PI/8.0) spriteNode.physicsBody?.isDynamic = false //print(spriteNode.zRotation) } } //Блок кода для обработки кнопок меню if node.name == "retry" { let articleParams = ["Retry lvl": thisScene]; Flurry.logEvent("Retry level", withParameters: articleParams) if AdCounter >= 6 { //UIAlertView(title: "Реклама", message: "Сейчас должен быть баннер Admob", delegate: self, cancelButtonTitle: "Ок").show() ads() AdCounter = 0 } else { print("Время еще не пришло") AdCounter += 1 let currentScene = GameScene(fileNamed: "Level "+String(thisScene)) let transition = SKTransition.doorsCloseHorizontal(withDuration: 0.5) currentScene!.scaleMode = SKSceneScaleMode.aspectFill currentScene?.viewController = self.viewController self.scene!.view?.presentScene(currentScene!, transition: transition) } } if node.name == "next" { let articleParams = ["This lvl": thisScene, "Next lvl": thisScene+1]; Flurry.logEvent("Next Level", withParameters: articleParams) let articleParams2 = ["Top lvl": topScene]; Flurry.logEvent("Top lvl", withParameters: articleParams2) AdCounter += 1 thisScene += 1 let currentScene = GameScene(fileNamed: "Level "+String(thisScene)) let transition = SKTransition.doorway(withDuration: 0.5) currentScene!.scaleMode = SKSceneScaleMode.aspectFill currentScene?.viewController = self.viewController self.scene!.view?.presentScene(currentScene!, transition: transition) } if node.name == "prev" { thisScene-=1 if thisScene == 0 { thisScene = topActualScene let currentScene = GameScene(fileNamed: "Level "+String(topActualScene)) let transition = SKTransition.doorway(withDuration: 0.5) currentScene!.scaleMode = SKSceneScaleMode.aspectFill currentScene?.viewController = self.viewController self.scene!.view?.presentScene(currentScene!, transition: transition) } else { let currentScene = GameScene(fileNamed: "Level "+String(thisScene)) let transition = SKTransition.doorway(withDuration: 0.5) currentScene!.scaleMode = SKSceneScaleMode.aspectFill currentScene?.viewController = self.viewController self.scene!.view?.presentScene(currentScene!, transition: transition) } } if node.name == "menu" { //Просто создал Segue и задал ей имя, с помощью имени ищем Segue и переходим self.viewController.performSegue(withIdentifier: "GoToMainMenu", sender: self) //Удаляем все говно со сцены, чтобы при новом открытии фпс норм были self.scene!.removeFromParent() //Не работали кнопки в игровом меню из-за того, что не было строчки ниже self.scene!.view?.removeFromSuperview() self.removeFromParent() self.removeAllActions() self.removeAllChildren() } if touchedNode.name == "stop" { if showMenu == true { showMenu = false removeMenu() } else { showMenu = true showRMenu() } } if node.name == "button" { itsNewBlock = true thisScene = topScene let currentScene = GameScene(fileNamed: "Level "+String(topScene)) let transition = SKTransition.doorway(withDuration: 0.5) currentScene!.scaleMode = SKSceneScaleMode.aspectFill currentScene?.viewController = self.viewController self.scene!.view?.presentScene(currentScene!, transition: transition) } } } public var onGroundTime = 0; public var onGround = false public var spearKill = false func didBegin(_ contact: SKPhysicsContact) { var firstBody: SKPhysicsBody? var secondBody: SKPhysicsBody? firstBody = contact.bodyA secondBody = contact.bodyB //Столкновение ГГ с Землей if firstBody!.categoryBitMask == 1 && secondBody!.categoryBitMask == 2 { onGround = true //print("On Ground(true)") } else { //onGround = false //print("On Ground(false)") } //Столкновение ГГ с Шипами if firstBody!.categoryBitMask == 1 && secondBody!.categoryBitMask == 3 && showMenu == false { self.scene!.isPaused = true; //Прогресс бар становится красным for progressBar in self.children { if progressBar.name == "ProgressBar" { if let progressBar = progressBar as? SKSpriteNode { progressBar.size.width = 4000 progressBar.color = UIColor.red } } } sleep(UInt32(0.5)) showMenu = true showLMenu() } } var showMenu = false public var dy = CGFloat(0.0) override func didSimulatePhysics() { let mainChrctr = self.childNode(withName: "MainCharacter") as? SKSpriteNode if mainChrctr?.position.y < 0 { onGround = false } //Удаляет спрайт, когда он улетел за экран for allObject in self.children { if let allObject = allObject as? SKSpriteNode { if ((allObject.position.y < 0 || allObject.position.x < -100 || allObject.position.x > 1380) && allObject.name != "MainCharacter") { allObject.removeFromParent() } } } /* Меню в конце сцены */ if showMenu == false { if onGround == false { onGroundTime = 0 for progressBar in self.children { if progressBar.name == "ProgressBar" { if let progressBar = progressBar as? SKSpriteNode { progressBar.size.width = 0 progressBar.color = UIColor.green } } } } else{ //Время которое персонаж лежит на земле onGroundTime+=1 print(onGroundTime) //Прогресс бар for progressBar in self.children { if progressBar.name == "ProgressBar" { if let progressBar = progressBar as? SKSpriteNode { progressBar.size.width = CGFloat(onGroundTime) * (39 / 2) progressBar.color = UIColor.green } } } //Если свинья на земле и время которое она пролежала на земле равно 100, то победа if onGroundTime > 200 && showMenu == false { showMenu = true //если показывали меню, то true if (getTopScene() < (thisScene+1)){ setTopScene(topStage: (thisScene+1)) } showWMenu() //Показать меню выигрыша mainChrctr?.physicsBody?.pinned = true mainChrctr?.physicsBody?.allowsRotation = false } } } if showMenu == false { //ПЕРЕМЕННАЯ ДЛЯ ОТЛАДКИ //dy = (mainChrctr?.physicsBody?.velocity.dy)! //velocity > 0 - перс отлетает от поверхности, velocity < 0 персонаж летит вниз. Состояние покоя около 5.5 if ((mainChrctr?.physicsBody?.velocity.dy)! > CGFloat(400.0) || (mainChrctr?.physicsBody?.velocity.dy)! < CGFloat(-400.0)) { mainChrctr?.texture = SKTexture(imageNamed:"MainCharacter_scare" + String(indexCharacterTexture)) } else { if((mainChrctr?.physicsBody?.velocity.dy)! >= CGFloat(10.0)) { mainChrctr?.texture = SKTexture(imageNamed: "MainCharacter_pain" + String(indexCharacterTexture)) } else{ mainChrctr?.texture = SKTexture(imageNamed:"MainCharacter" + String(indexCharacterTexture)) } } } //если ГГ улетел за сцену, показываем меню if mainChrctr?.position.y < 0 && showMenu == false { //saveStat(info: "lose") showMenu = true //если показывали меню, то true showLMenu() //Показать меню проигрыша onGround = false //Свинья не на земле(за экраном она не может определить это) } //statusBar() } }
// // UIBlockHostController.swift // SwiftUIKit // // Created by Andrey Zonov on 21.12.2020. // import UIKit public class UIBlockHostController: UIViewController { public var block: Block! public var context: BlockContext! public init(_ block: Block, with context: BlockContext? = nil) { super.init(nibName: nil, bundle: nil) self.block = block self.context = (context ?? BlockContext()) .set(viewController: self) } required public init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { print("DEINIT UIBlockViewController") } override public func viewDidLoad() { super.viewDidLoad() build() } public func build() { view.build(block: block, with: context) } public func rebuild() { build() } }
// // RealmParser.swift // RealmVideo // // Created by Patrick Balestra on 5/6/16. // Copyright © 2016 Patrick Balestra. All rights reserved. // import Foundation import Ji enum ParserError: ErrorType { case Offline } class RealmParser { var videos = [Video]() init() throws { let url = NSURL(string: "https://realm.io/news/")! let document = Ji(htmlURL: url) let possiblePosts = document?.xPath("//div[contains(concat(' ', @class, ' '), ' article ')]") guard let posts = possiblePosts else { throw ParserError.Offline } for post in posts { if let attributes = post.attributes["data-tags"] where attributes.containsString("video") { for child in post.children { let link = child.attributes["href"] let content = child.firstDescendantWithAttributeName("class", attributeValue: "news-headline hidden-xs")?.content _ = attributes // TODO: show tags in UI for better discovery if let content = content where content != "Read More…", let link = link { videos.append(Video(title: content, url: "https://realm.io\(link)")) } } } } } }
// // MessageCell.swift // Tinder-App // // Created by Миронов Влад on 30.10.2019. // Copyright © 2019 Миронов Влад. All rights reserved. // import LBTATools class MessageCell: LBTAListCell<Message>{ let textView: UITextView = { let textView = UITextView() textView.font = .systemFont(ofSize: 20) textView.isScrollEnabled = false textView.isEditable = false textView.backgroundColor = .none return textView }() let bubbleContainer = UIView(backgroundColor: #colorLiteral(red: 0.4745098054, green: 0.8392156959, blue: 0.9764705896, alpha: 1)) override var item: Message!{ didSet{ textView.text = item.text if item.isFromCurrentUser { bubbleConstraint.trailing?.isActive = true bubbleConstraint.leading?.isActive = false bubbleContainer.backgroundColor = #colorLiteral(red: 0.1411764771, green: 0.3960784376, blue: 0.5647059083, alpha: 1) textView.textColor = .white textView.textAlignment = .right } else { bubbleConstraint.trailing?.isActive = false bubbleConstraint.leading?.isActive = true bubbleContainer.backgroundColor = #colorLiteral(red: 0.8039215803, green: 0.8039215803, blue: 0.8039215803, alpha: 1) textView.textColor = .black textView.textAlignment = .left } } } var bubbleConstraint: AnchoredConstraints! override func setupViews() { super.setupViews() backgroundColor = .none addSubview(bubbleContainer) bubbleContainer.layer.cornerRadius = 12 bubbleConstraint = bubbleContainer.anchor(top: topAnchor, leading: leadingAnchor, bottom: bottomAnchor, trailing: trailingAnchor) bubbleConstraint.leading?.constant = 20 bubbleConstraint.trailing?.constant = -20 bubbleContainer.addSubview(textView) bubbleContainer.widthAnchor.constraint(lessThanOrEqualToConstant: self.contentView.frame.width - 100).isActive = true textView.fillSuperview(padding: .init(top: 4, left: 12, bottom: 4, right: 12)) } }
// // StartScreenVC.swift // Tictactoe // // Created by Mikhail Kirsanov on 17.05.2021. // import UIKit class StartScreenVC: BaseViewController { var presenter: StartScreenPresenterInput? @IBOutlet weak var startNewGameButton: UIButton! override func viewDidLoad() { super.viewDidLoad() setupAppearance() presenter?.viewDidLoad() } func setupAppearance() { self.title = "startScreen.navigationBar.title".localized startNewGameButton.setTitle("startScreen.startNewGameButton.title".localized, for: .normal) } @IBAction func startNewGameButtonTap() { presenter?.startNewGameButtonTap() } } extension StartScreenVC: StartScreenPresenterOutput { }
// // UIColor+Extensions.swift // Pods-TappableTextView_Example // // Created by Willie Johnson on 5/20/18. // Copyright © 2018 Willie Johnson. All rights reserved. // import Foundation import UIKit extension UIColor { /// Returns this UIColor's constrast color. public func contrastColor() -> UIColor { var hue: CGFloat = 0 var saturation: CGFloat = 0 var brightness: CGFloat = 0 var alpha: CGFloat = 0 getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) return UIColor(hue: hue, saturation: 1.4 - saturation, brightness: 1.1 - brightness, alpha: alpha) } public static func randomColor() -> UIColor { let randomHue = CGFloat(Float(arc4random()) / Float(UINT32_MAX)) return UIColor(hue: randomHue, saturation: 0.6, brightness: 0.9, alpha: 1) } public func darken(_ factor: Float = 1) -> UIColor { var hue: CGFloat = 0 var saturation: CGFloat = 0 var brightness: CGFloat = 0 var alpha: CGFloat = 0 getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) return UIColor(hue: hue, saturation: saturation * (1 - CGFloat(factor)), brightness: brightness * (1 - CGFloat(factor)), alpha: alpha) } public func lighten(_ factor: Float = 1) -> UIColor { var hue: CGFloat = 0 var saturation: CGFloat = 0 var brightness: CGFloat = 0 var alpha: CGFloat = 0 getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) return UIColor(hue: hue, saturation: saturation, brightness: brightness * (1 + CGFloat(factor)), alpha: alpha) } public func opposite() -> UIColor { var hue: CGFloat = 0 var saturation: CGFloat = 0 var brightness: CGFloat = 0 var alpha: CGFloat = 0 getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) return UIColor(hue: 1 - hue, saturation: 1 - saturation, brightness: 1 - brightness, alpha: alpha) } }
// // ViewExtension.swift // AlbumDetail // // Created by Alex Tapia on 13/03/21. // import SwiftUI extension View { func navigationBarColor(_ backgroundColor: Color) -> some View { modifier(NavigationBarModifier(backgroundColor: backgroundColor)) } }
// // MyApiViewController.swift // Sample // // Created by PranayBansal on 08/04/19. // Copyright © 2019 PranayBansal. All rights reserved. // import UIKit import Foundation class MyApiViewController: UIViewController ,UITextFieldDelegate{ @IBOutlet weak var mLoader: UIActivityIndicatorView! @IBOutlet weak var ivUserProfile: UIImageView! @IBOutlet weak var mUserName: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. let apiUrl = URL(string: "https://api.github.com/users/pranay1494")! self.mLoader.isHidden = false self.mLoader.startAnimating() let session = URLSession.shared.dataTask(with: apiUrl) { (data, response, error) in guard let data = data else { print("url is nil"); return } //By json serializer // do{ // let json = try JSONSerialization.jsonObject(with: data, options: []) as! [String:Any] // let userName = json["login"] as! String // let avatarUrl = json["avatar_url"] as! String // DispatchQueue.main.async { // self.mUserName.text = userName // } // print(avatarUrl) // }catch{ // print(error) // } //using codable decoder(desiralization) and encoder(serialization) do{ let decoder = JSONDecoder() let gitData = try decoder.decode(GithubApi.self, from: data) print(gitData) DispatchQueue.main.async { self.mUserName.text = gitData.login } self.fetchImage(gitData.avatar_url) }catch{ print(error) } } session.resume() } func fetchImage(_ url : String){ let apiUrl = URL(string: url)! let session = URLSession.shared.dataTask(with: apiUrl) { (data, response, error) in guard let data = data else { print("data is nil"); return } DispatchQueue.main.async { let image = UIImage(data: data) self.ivUserProfile.image = image self.mLoader.isHidden = true self.mLoader.stopAnimating() } } session.resume() } }
// // ListViewController.swift // Film // // Created by Tomas Vosicky on 06.12.16. // Copyright © 2016 Tomas Vosicky. All rights reserved. // import UIKit import MagicalRecord private let reuseIdentifier = "Cell" class ListViewController: UITableViewController { var movies: [WatchMovie]! = [] var detailViewController: DetailViewController? = nil override func viewDidLoad() { super.viewDidLoad() title = "Shlédnuté" view.backgroundColor = .background tableView.backgroundView?.backgroundColor = .background tableView.separatorColor = .separator tableView.register(Movie2TableViewCell.self, forCellReuseIdentifier: reuseIdentifier) fetchAllMovies() tableView.reloadData() } func fetchAllMovies() { movies = WatchMovie.mr_findAll() as! [WatchMovie]! } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 96 } override func viewDidAppear(_ animated: Bool) { fetchAllMovies() tableView.reloadData() } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return movies.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath) as! Movie2TableViewCell cell.movie = movies[indexPath.row] return cell } func showDetail(for id: Int) { detailViewController = DetailViewController() detailViewController?.id = id navigationController?.pushViewController(detailViewController!, animated: true) } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { showDetail(for: movies[indexPath.row].id) } override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { let action: UITableViewRowAction = UITableViewRowAction.init(style: .destructive, title: "Viděl jsem") { (action, indexPath) in self.movies.remove(at: indexPath.row).mr_deleteEntity() tableView.deleteRows(at: [indexPath], with: .fade) NSManagedObjectContext.mr_default().mr_saveToPersistentStoreAndWait() } return [action] } }
// // Controllers.swift // iOSRappiTest // // Created by José Valderrama on 9/25/16. // Copyright © 2016 José Valderrama. All rights reserved. // import Foundation /// Use this to instantiate any controllers programatically. struct Controllers { private init() {} static func instantiateHomeViewController() -> HomeViewController { return Storyboards.home.instantiateViewControllerWithIdentifier("HomeViewController") as! HomeViewController } static func instantiateCategoriesViewController() -> CategoriesViewController { return Storyboards.category.instantiateViewControllerWithIdentifier("CategoriesViewController") as! CategoriesViewController } static func instantiateCategoriesCollectionViewController() -> CategoriesCollectionViewController { return Storyboards.category.instantiateViewControllerWithIdentifier("CategoriesCollectionViewController") as! CategoriesCollectionViewController } static func instantiateCategoriesTableViewController() -> CategoriesTableViewController { return Storyboards.category.instantiateViewControllerWithIdentifier("CategoriesTableViewController") as! CategoriesTableViewController } static func instantiateAppsViewController() -> AppsViewController { return Storyboards.app.instantiateViewControllerWithIdentifier("AppsViewController") as! AppsViewController } static func instantiateAppsCollectionViewController() -> AppsCollectionViewController { return Storyboards.app.instantiateViewControllerWithIdentifier("AppsCollectionViewController") as! AppsCollectionViewController } static func instantiateAppsTableViewController() -> AppsTableViewController { return Storyboards.app.instantiateViewControllerWithIdentifier("AppsTableViewController") as! AppsTableViewController } static func instantiateAppDetailTableViewController() -> AppDetailTableViewController { return Storyboards.app.instantiateViewControllerWithIdentifier("AppDetailTableViewController") as! AppDetailTableViewController } }
// // ViewController.swift // simple // // Created by Jonathan Sand on 9/28/21. // Copyright © 2021 Zones. All rights reserved. // import Foundation #if os(OSX) import Cocoa #elseif os(iOS) import UIKit #endif class ViewController: NSViewController { @IBOutlet var input: NSTextField? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override var representedObject: Any? { didSet { // Update the view, if already loaded. } } @IBAction func handleTextInput(sender: NSTextField) { gSimple?.name = sender.stringValue gSave() } }
// // TokenizedReportViewModel.swift // TextViewApp // // Created by Igor Malyarov on 29.12.2020. // import SwiftUI final class TokenizedReportViewModel: ObservableObject { @Published var headerModel: TokenizedReportHeaderModel @Published var groupModels: [TokenizedReportBodyModel] @Published var footerModel: TokenizedReportFooterModel init(reportContent: ReportContent) { headerModel = TokenizedReportHeaderModel(headerString: reportContent.headerString) groupModels = reportContent.groups .map { TokenizedReportBodyModel(groupString: $0) } footerModel = TokenizedReportFooterModel(footerString: reportContent.footerString) } }
// // SwiftyGif.swift // RotomPokedex // // Created by Ryo on 2020/01/12. // Copyright © 2020 Ryoga. All rights reserved. // import Foundation import SnapKit import SwiftyGif extension UIImageView { /// セットされているGIF画像をクリアする public func clearGifImage() { self.setImage(UIImage()) } /// この`UIImageView`をセットされているGIF画像の整数倍に設定する /// - Parameter scale: 倍率 public func setGifScale(_ scale: CGFloat) { let rawWidth = self.frameAtIndex(index: 0).size.width let rawHeight = self.frameAtIndex(index: 0).size.height let newWidth = scale * rawWidth let newHeight = scale * rawHeight self.snp.updateConstraints { update in update.width.equalTo(newWidth) update.height.equalTo(newHeight) } } }
// // ViewController.swift // PopupPickerViewDemo // // Created by Ibraheem rawlinson on 8/15/19. // Copyright © 2019 Ibraheem rawlinson. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var daysTxtField: UITextField! @IBOutlet weak var monthsTxtField: UITextField! @IBOutlet weak var birthdayTxtField: UITextField! let pickerView = UIPickerView() var dateOfBirthPicker = UIDatePicker() // content for picker view let days = ["Mon","Tue","Wed", "Thur", "Fri", "Sat", "Sun"] let months = ["Jan", "Feb","Mar","Apr","May","June","July", "Aug", "Sept", "Oct", "Nov", "Dec"] // holds current content var currentArr = [String]() // holds curent text field var currentTxtField: UITextField! override func viewDidLoad() { super.viewDidLoad() callMethods() } private func callMethods(){ setupDatePicker() setDelegate() setInputView() createToolBar() } private func setupDatePicker(){ dateOfBirthPicker.datePickerMode = .date addDateOfBirthPickerTarget() setupTapGesture() birthdayTxtField.inputView = dateOfBirthPicker } private func addDateOfBirthPickerTarget(){ dateOfBirthPicker.addTarget(self, action: #selector(datePickerDidChange), for: .valueChanged) } @objc private func datePickerDidChange(datePicker picker: UIDatePicker){ let dateFormatter = DateFormatter() dateFormatter.dateFormat = "MM/dd/yyyy" birthdayTxtField.text = dateFormatter.string(from: picker.date) view.endEditing(true) } private func setupTapGesture(){ let tapGesture = UITapGestureRecognizer(target: self, action: #selector(viewDidTapped)) view.addGestureRecognizer(tapGesture) } @objc private func viewDidTapped(){ view.endEditing(true) } private func setDelegate(){ daysTxtField.delegate = self monthsTxtField.delegate = self pickerView.dataSource = self pickerView.delegate = self } private func setInputView(){ daysTxtField.inputView = pickerView monthsTxtField.inputView = pickerView } private func createToolBar(){ let toolBar = UIToolbar() toolBar.barStyle = .default toolBar.sizeToFit() let doneBttn = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(doneBttnPressed)) let flexSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) let cancelBttn = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(cancelBttnPressed)) toolBar.setItems([cancelBttn,flexSpace,doneBttn], animated: false) daysTxtField.inputAccessoryView = toolBar monthsTxtField.inputAccessoryView = toolBar } @objc private func doneBttnPressed(){ currentTxtField.resignFirstResponder() birthdayTxtField.resignFirstResponder() } @objc private func cancelBttnPressed(){ currentTxtField.text = "" } } extension ViewController: UITextFieldDelegate { func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool { currentTxtField = textField switch textField { case daysTxtField: currentArr = days case monthsTxtField: currentArr = months default: print("Detfault") } pickerView.reloadAllComponents() return true } } extension ViewController: UIPickerViewDataSource { func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return currentArr.count } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { let myTitle = currentArr[row] return myTitle } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { print("Selected item is ", currentArr[row]) currentTxtField.text = currentArr[row] } } extension ViewController: UIPickerViewDelegate { }
/* A class should be open for extension but closed for modification */ import Foundation // MARK:- Protocols for abstract declaration of an Air Condition functionalities protocol SwitchOption { func turnOn() func turnOff() } protocol ModeOption { func changeMode() } protocol FanSpeedOption { func setFanSpeed(speed: Int) } // MARK:- Classes providing definition to AC functionalities class Switch: SwitchOption { func turnOn() { print("Turned ON") } func turnOff() { print("Turned OFF") } } class Mode: ModeOption { func changeMode() { print("Mode has been Changed") } } class FanSpeed: FanSpeedOption { func setFanSpeed(speed: Int) { print("Fan Speed is \(speed)") } } // MARK:- Class Implementation for Air Conditioning class AirCondition: SwitchOption, ModeOption, FanSpeedOption { let mode = Mode() let `switch` = Switch() let fanSpeed = FanSpeed() func turnOn() { `switch`.turnOn() } func turnOff() { `switch`.turnOff() } func changeMode() { mode.changeMode() } func setFanSpeed(speed: Int) { fanSpeed.setFanSpeed(speed: 5) } } // MARK:- New feature Humidity to be added to AirCondition class protocol HumidityOption { func setHumidityLevel(level: Int) } class Humidity: HumidityOption { func setHumidityLevel(level: Int) { print("Humidity set to \(level)") } } // MARK:- New feature implementation by extending AirCondition class extension AirCondition: HumidityOption { func setHumidityLevel(level: Int) { let humidity = Humidity() humidity.setHumidityLevel(level: level) } } // MARK:- Driver Program let acNew = AirCondition() acNew.turnOn() acNew.setFanSpeed(speed: 5) acNew.changeMode() acNew.setHumidityLevel(level: 10) acNew.turnOff()
// // PlacesAPIDataManagerSpy.swift // MusicBrainzTests // // Created by BOGU$ on 23/05/2019. // Copyright © 2019 lyzkov. All rights reserved. // import Foundation @testable import MusicBrainz final class PlacesAPIDataManagerSpy: PlacesAPIDataManagerInputProtocol { var resultFetch: Result<[Place], Error>? = nil func fetch(region: RegionType, since: Date, offset: Int, limit: Int, completion: @escaping (Result<[Place], Error>) -> Void) { if let result = resultFetch { completion(result) } } var resultFetchAll: Result<[Place], Error>? = nil func fetchAll(region: RegionType, since: Date, completion: @escaping (Result<[Place], Error>) -> Void) { if let result = resultFetchAll { completion(result) } } }
// // Blacklisted+CoreDataProperties.swift // // // Created by Pankaj Teckchandani on 12/04/20. // // import Foundation import CoreData extension Blacklisted { @nonobjc public class func fetchRequest() -> NSFetchRequest<Blacklisted> { return NSFetchRequest<Blacklisted>(entityName: "Blacklisted") } @NSManaged public var text: String? }
// // RestaurantDetailViewController.swift // FoodPin // // Created by yxu on 3/11/21. // import UIKit class RestaurantDetailViewController: UIViewController { @IBOutlet var restaurantImageView: UIImageView! @IBOutlet var nameLabel: UILabel! @IBOutlet var typeLabel: UILabel! @IBOutlet var locationLabel: UILabel! var restaurant: Restaurant = Restaurant() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. nameLabel.text = restaurant.name typeLabel.text = restaurant.type locationLabel.text = restaurant.location restaurantImageView.image = UIImage(named: restaurant.image) navigationItem.largeTitleDisplayMode = .never } }
// // ViewController.swift // WeakVars // // Created by Brennan Stehling on 3/28/16. // Copyright © 2016 Swift Curriculum. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { // An outlet is a weak var because the view is owned by the parent view // while the view controller is refernced as a data source and delegate. // This outlet is also defined as optional to avoid a force unwrapped value. @IBOutlet weak var tableView: UITableView? // define names using an initialization closure just for fun var names: [String] = { return ["Tim", "Chris", "Bill", "Steve", "Eliza", "Jony", "Angela", "Eddy", "Craig", "Phil", "Lisa"] }() // MARK: - UITableViewDataSource func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return names.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("BigLabelCell", forIndexPath: indexPath) let name = names[indexPath.row] // set the name as the text for the big label if let bigLabelCell = cell as? BigLabelCell, let bigLabel = bigLabelCell.bigLabel { bigLabel.text = name } return cell } // MARK: - UITableViewDelegate func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return UITableViewAutomaticDimension } } // Custom, internal class for Big Label Cell to allow for setting an outlet. // It is internal to ensure it is only be used by this view controller. internal class BigLabelCell : UITableViewCell { @IBOutlet weak var bigLabel: UILabel? }
// // UIBarButtonItem_Extension.swift // XWSwiftWB // // Created by 邱学伟 on 2016/10/26. // Copyright © 2016年 邱学伟. All rights reserved. // import UIKit extension UIBarButtonItem{ convenience init(imageName : String) { self.init() let customBtn : UIButton = UIButton(imageName : imageName) self.customView = customBtn } }
// // TinyLabel.swift // Pop the Box // // Created by Lucia Reynoso on 9/27/18. // Copyright © 2018 Lucia Reynoso. All rights reserved. // import Foundation import SpriteKit import GameplayKit class TinyLabel: SKLabelNode { init(score: Int) { super.init() self.fontName = "AmericanTypewriter-Bold" self.text = "\(score)!" self.fontColor = .white self.fontSize = 10 } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func floatUp() { let moveUp = SKAction.moveBy(x: 0, y: 50, duration: 1) self.run(moveUp) { self.removeFromParent() } } }
// // NewRuleViewController.swift // Timecode // // Created by Matthew Gray on 9/24/16. // Copyright © 2016 Matthew Gray. All rights reserved. // import UIKit protocol DataEnteredDelegate: class { func addRule(label: String, before: Int, length: Int, pause: Int, reps: Int) //used when adding a rule func editRule(index: Int, label: String, before: Int, length: Int, pause: Int, reps: Int) //used when editing a rule func setNewRuleList(list: RuleList) //used when resetting the current RuleList to a new/old RuleList } class NewRuleViewController: UIViewController { @IBOutlet weak var name: UITextField! @IBOutlet weak var before: UITextField! @IBOutlet weak var length: UITextField! @IBOutlet weak var pause: UITextField! @IBOutlet weak var reps: UITextField! weak var delegate: DataEnteredDelegate? = nil var rule: Rule? var editingRule = false var index = -1 override func viewDidLoad() { super.viewDidLoad() if editingRule { name.text = rule?.label before.text = "\(rule!.before)" length.text = "\(rule!.length)" pause.text = "\(rule!.pause)" reps.text = "\(rule!.repetitions)" self.navigationItem.title = "Edit Rule" } else { self.navigationItem.title = "New Rule" } // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func save(_ sender: AnyObject) { if ((name.text?.isEmpty)! || (before.text?.isEmpty)! || (length.text?.isEmpty)! || (pause.text?.isEmpty)! || (reps.text?.isEmpty)! || Int(pause.text!)! < 3) { /*let alert = UIAlertView() alert.title = "Error!" alert.message = "You cannot add a rule with any empty fields." alert.addButton(withTitle: "Got it!") alert.show() return*/ //thanks SO! //1. Create the alert controller. var alert: UIAlertController if (pause.text?.isEmpty)! == false && Int(pause.text!)! < 3 { alert = UIAlertController(title: "Error!", message: "You cannot add a rule with a break less than 3 seconds", preferredStyle: .alert) } else { alert = UIAlertController(title: "Error!", message: "You cannot add a rule with any empty fields", preferredStyle: .alert) } // 3. Grab the value from the text field, and print it when the user clicks OK. alert.addAction(UIAlertAction(title: "Got it!", style: .default)) // 4. Present the alert. self.present(alert, animated: true, completion: nil) return } let nameText = name.text! let beforeNum = Int(before.text!)! let lengthNum = Int(length.text!)! let pauseNum = Int(pause.text!)! let repsNum = Int(reps.text!)! if (editingRule) { editingRule = false; delegate?.editRule(index: index, label: nameText, before: beforeNum, length: lengthNum, pause: pauseNum, reps: repsNum) } else { delegate?.addRule(label: nameText, before: beforeNum, length: lengthNum, pause: pauseNum, reps: repsNum) } clearFields() self.navigationController?.popViewController(animated: true) } func clearFields() { name.text = "" before.text = "" length.text = "" pause.text = "" reps.text = "" } }
// // HomeViewController.swift // JYVideoEditor // // Created by aha on 2021/2/19. // import Foundation import UIKit class HomeViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() } @IBAction func clickChooseVideo(_ sender: UIButton) { let sourcePath = Bundle.main.path(forResource: "source.mp4", ofType: nil)! let editorVC = EditorViewController.instance(sourcePath: sourcePath) navigationController?.pushViewController(editorVC, animated: true) } }
//: Playground - noun: a place where people can play import UIKit /* NSNullは、nilを許容しないcollectionオブジェクト内で null値を表現するのに使用されるシングルトンオブジェクト */ let array: NSArray = [NSNull(), NSNull(), NSNull()] print(array) let dictionary: NSDictionary = ["key1": NSNull(), "key2": NSNull(), "key3": NSNull()] print(dictionary) /* <補足:Optional> Optional<Wrapped>型はWrapped型の値の存在と不在を表す 列挙型として下記のように定義されている enum Optional<Wrapped> { case none case some(Wrapped) } */ /* SwiftのnilはOptional<Wrapped>型の.noneを表すリテラル */ let none = Optional<Int>.none print(".none: \(none)") /* 型推論 */ // .someは型推論可能 let some = Optional.some(1) print(".some: \(some)") // .noneは<Wrapped>省略不可 推論のもととなる値が存在しないため // Wrapped? は Optional<Wrapped>の糖衣構文 let intNone: Int? = Optional.none print("intNone: \(intNone)") /* Optional<Wrapped>型の値の生成 */ var a: Int? a = nil print("nilリテラルの代入による.noneの生成: \(a)") a = Optional(1) print("イニシャライザによる.someの生成: \(a)") a = 2 print("値の代入による.someの生成: \(a)")
// // Int+AZLExtend.swift // AZLExtendSwift // // Created by lizihong on 2021/10/14. // import Foundation extension Int { /// 拆分为时分秒 /// - Returns: hour 时 minute 分 second秒 public func azl_timeData() -> (hour: Int, minute: Int, second: Int) { let intValue = self let hour = intValue/3600 let minute = (intValue/60)%60 let second = intValue%60 return (hour: hour, minute: minute, second: second) } }
import Foundation public extension String { public var quoted: String { return "\"\(self)\"" } }
// // NavigationBarView.swift // Created by Asianark on 16/2/5. // Copyright © 2016年 zn. All rights reserved. // import UIKit class NavigationTopBarView: UINavigationBar{ let kNaviBarHeight: CGFloat = 44.0 var naviItem:UINavigationItem! var titleView:UILabel! init() { super.init(frame: CGRectMake(0.0, Common.kStatusHeight, Common.kScreenSize.width, kNaviBarHeight)) self.barTintColor = UIColor.hecNaviBarGreenColor() self.backgroundColor = UIColor.hecNaviBarGreenColor() //去除自带阴影 self.shadowImage = UIImage() self.setBackgroundImage(UIImage(), forBarMetrics: UIBarMetrics.Default) self.naviItem = UINavigationItem() } override init(frame: CGRect) { super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
// // AppDelegate.swift // grokSwiftREST // // Created by Christina Moulton on 2018-03-22. // Copyright © 2018 Christina Moulton. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. let splitViewController = window!.rootViewController as! UISplitViewController let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem splitViewController.delegate = self return true } func application(_ application: UIApplication, handleOpen url: URL) -> Bool { if let mainVC = self.window?.rootViewController as? MasterViewController, let webVC = mainVC.safariViewController { webVC.dismiss(animated: true) } GitHubAPIManager.shared.processOAuthStep1Response(url) return true } // MARK: - Split view func splitViewController(_ splitViewController: UISplitViewController, collapseSecondary secondaryViewController:UIViewController, onto primaryViewController:UIViewController) -> Bool { guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false } guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false } if topAsDetailController.gist == nil { // Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded. return true } return false } }
import UIKit public final class TKImageView: UIImageView, ViewInitializable { // MARK: Life Cycle public convenience init(position: Position = (0, 0), size: Size, image: UIImage) { self.init(position: position, size: size) self.image = image } // MARK: Properties public var isRounded: Bool = false { willSet { if newValue { self.layer.cornerRadius = self.frame.size.width / 2.0 self.clipsToBounds = true }else { self.layer.cornerRadius = 0.0 self.clipsToBounds = false } } } }
// // SpeedPriceModel.swift // MMWallet // // Created by Dmitry Muravev on 31.07.2018. // Copyright © 2018 micromoney. All rights reserved. // import Foundation import RealmSwift import ObjectMapper class SpeedPriceModel: Object, Mappable { @objc dynamic var id = "" @objc dynamic var low: SpeedPriceRateModel? @objc dynamic var medium: SpeedPriceRateModel? @objc dynamic var high: SpeedPriceRateModel? override class func primaryKey() -> String? { return "id" } required convenience init?(map: Map) { self.init() } func mapping(map: Map) { id <- map["id"] low <- map["low"] medium <- map["medium"] high <- map["high"] } }
// // NotificationModel.swift // HowlTalk // // Created by Awesome S on 25/08/2018. // Copyright © 2018 Awesome S. All rights reserved. // import ObjectMapper class NotificationModel: Mappable { public var to : String? public var notification : Notification = Notification() public var data : Data = Data() init(){ } required init?(map : Map) { } func mapping(map : Map){ to <- map["to"] notification <- map["notification"] data <- map["data"] } class Notification : Mappable{ public var title : String? public var text : String? init(){} required init?(map : Map) {} func mapping(map : Map){ title <- map["title"] text <- map["text"] } } // 안드로이드 포그라운드 노티피케이션을 위한 클래스 class Data : Mappable{ public var title : String? public var text : String? init(){} required init?(map : Map) {} func mapping(map : Map){ title <- map["title"] text <- map["text"] } } }
//: [Previous](@previous) import Foundation var v: (Int, Int) -> Bool func f(_ x: Int, y: Int) -> Bool { return x + y > 0 } f(0, y: 1) // Assigning to a function typed variable loses labeled arguments. v = f v(1, 1) // No label needed for 'y' v(0, 1) // Can use variables to redefine argument labels. var q: (_ a: Int, _ b: Int) -> Bool q = f q(0, 1) // q(0, 1) // Error, missing argument labels. // variable of Member functions are curried. struct C { var m: Int func memberfunc(_ x: Int) -> Int { return x + m } } let o = C(m: 42) let w = C.memberfunc let y = C.memberfunc(o) y(10) w(o)(3) // Operators. let eq: (Int, Int) -> Bool = (==) eq(5, 6) eq(10,10) // Closure type inference // Infer argument and return type let zero = { return 0 } zero() // Infer return type let succ = { (x) in return x+1 } succ(42) let twotimes = { $0 * 2 } twotimes(100) let square = { (x) -> Int in return x * x } square(10) let mult = { (x, y) -> Int in return x * y } mult(6, 7) // Trailing closures func trail(closure: () -> Void) { closure() } trail { print("I'm in a trailing closure") } func multi(closure1: (() -> Void) = {}, closure2: (() -> Void) = {}) { print("closure1") closure1() print("closure2") closure2() } multi (closure1: {print("AAA")}) { print("Where am I?") } multi { print("Hmmm... I'm in closure2") } //: [Next](@next)
import Foundation @testable import Steem import XCTest class AssetTest: XCTestCase { func testEncodable() { AssertEncodes(Asset(10, .steem), Data("102700000000000003535445454d0000")) AssertEncodes(Asset(123_456.789, .vests), Data("081a99be1c0000000656455354530000")) AssertEncodes(Asset(10, .steem), "10.000 STEEM") AssertEncodes(Asset(123_456.789, .vests), "123456.789000 VESTS") AssertEncodes(Asset(42, .custom(name: "TOWELS", precision: 0)), "42 TOWELS") AssertEncodes(Asset(0.001, .sbd), "0.001 SBD") } func testProperties() { let mockAsset = Asset(0.001, .sbd) XCTAssertEqual(mockAsset.description, "0.001 SBD") XCTAssertEqual(mockAsset.amount, 1) XCTAssertEqual(mockAsset.symbol, Asset.Symbol.sbd) XCTAssertEqual(mockAsset.resolvedAmount, 0.001) } func testEquateable() { let mockAsset = Asset(0.1, .sbd) let mockAsset2 = Asset(0.1, .steem) let mockAsset3 = Asset(0.1, .sbd) let mockAsset4 = Asset(0.2, .sbd) XCTAssertFalse(mockAsset == mockAsset2) XCTAssertTrue(mockAsset == mockAsset3) XCTAssertFalse(mockAsset == mockAsset4) } func testDecodable() throws { AssertDecodes(string: "10.000 STEEM", Asset(10, .steem)) AssertDecodes(string: "0.001 SBD", Asset(0.001, .sbd)) AssertDecodes(string: "1.20 DUCKS", Asset(1.2, .custom(name: "DUCKS", precision: 2))) AssertDecodes(string: "0 BOO", Asset(0, .custom(name: "BOO", precision: 0))) AssertDecodes(string: "123456789.999999 VESTS", Asset(123_456_789.999999, .vests)) } }
// // ContactListViewController.swift // DemoBoostContact // // Created by Amit Gupta on 28/07/2019. // Copyright © 2019 Amit Gupta. All rights reserved. // import UIKit class ContactTblViewCell: UITableViewCell { @IBOutlet weak var lblName: UILabel! @IBOutlet weak var imgViewContact: UIImageView! } class ContactListViewController: UIViewController { // MARK: - Identifiers private var arrContactList: [Contact]? // MARK: - IBOutlets @IBOutlet weak var tblViewRoutesList: UITableView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.title = NSLocalizedString("Contacts", comment: "") } override func viewWillAppear(_ animated: Bool) { self.arrContactList = self.loadJson(filename: "data") self.tblViewRoutesList.reloadData() } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ // MARK: - Mapping JSON data to Array Objects func loadJson(filename fileName: String) -> [Contact]? { if let url = Bundle.main.url(forResource: fileName, withExtension: "json") { do { let data = try Data(contentsOf: url) let decoder = JSONDecoder() let jsonData = try decoder.decode([Contact].self, from: data) return jsonData } catch { print("error:\(error)") } } return nil } } extension ContactListViewController: UITableViewDataSource, UITableViewDelegate{ func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { //return self .arrayHotelList .count return self.arrContactList?.count ?? 0 } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 60.0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView .dequeueReusableCell(withIdentifier: .cellContactList, for: indexPath) as! ContactTblViewCell cell.imgViewContact.layer.cornerRadius = cell.imgViewContact.frame.height/2.0 let objContact = self.arrContactList?[indexPath.row] cell.lblName.text = "\(objContact?.firstName ?? "") \(objContact?.lastName ?? "")" cell .selectionStyle = .none return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { } }
func max(a: Int, b: Int) -> Int { return a > b ? a : b } print(max(1, 2)) print(max(3, 2)) print(max(5, 5)) print(max(-5, -3))
// // PlacesPresenter.swift // MusicBrainz // // Created BOGU$ on 20/05/2019. // Copyright © 2019 lyzkov. All rights reserved. // // import UIKit import MapKit final class PlacesPresenter { weak private var view: PlacesViewProtocol? private let interactor: PlacesInteractorProtocol private let wireframe: PlacesWireframeProtocol init(interface: PlacesViewProtocol, interactor: PlacesInteractorProtocol, wireframe: PlacesWireframeProtocol) { self.view = interface self.interactor = interactor self.wireframe = wireframe self.interactor.presenter = self } } extension PlacesPresenter: PlacesPresenterInputProtocol { func load() { interactor.loadRegion() } private func loadPlaces(region: RegionType) { interactor.loadPlaces(region: region) } } extension PlacesPresenter: PlacesPresenterOutputProtocol { func present(region: RegionType) { loadPlaces(region: region) view?.present(region: region) } func present(places: [PlaceAnnotation]) { for place in places { view?.add(place: place) Timer.scheduledTimer(withTimeInterval: TimeInterval(place.lifespan ?? 0), repeats: false) { [view] _ in view?.remove(place: place) } } } func show(error: Error) { wireframe.presentAlert(from: error) } }
protocol CalculationViewRoutable: BaseRoutable, TableViewRoute {} final class CalculationViewRouter: BaseRouter, CalculationViewRoutable {}
// BSD 3-Clause License // // Copyright (c) 2018, Allen Yee // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import XCTest class SentenceTests: XCTestCase { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } /// Test speech act, sentiment, emotions, and sarcasm func testTextUnderstandingMapping() { let json = """ { "position": 0, "raw_sentence": "I really loved this device the first few months I had it and was ready to purchase more in this collection (Big Echo, Show, etc.)", "speech_acts": ["Statement"], "sentiments": ["Positive"], "emotions": ["Joy/Like"], "sarcasm": "Non-sarcastic" } """ do { guard let jsonData = json.data(using: .utf16) else { XCTAssert(false) return } let jsonDecoder = JSONDecoder() let sentence = try jsonDecoder.decode(Sentence.self, from: jsonData) XCTAssertNotNil(sentence) XCTAssertEqual(sentence.position, 0) XCTAssertEqual(sentence.rawSentence, "I really loved this device the first few months I had it and was ready to purchase more in this collection (Big Echo, Show, etc.)") XCTAssertEqual(sentence.speechActs, ["Statement"]) XCTAssertEqual(sentence.sentiments, ["Positive"]) XCTAssertEqual(sentence.emotions, ["Joy/Like"]) XCTAssertEqual(sentence.sarcasm, "Non-sarcastic") } catch let decodeError { print("Decode Error: \(decodeError.localizedDescription)") XCTAssert(false) } } /// Test tokens, tokens_filtered, lemmas, stems, pos_tags, dependencies func testTextProcessing() { let json = """ { "position": 0, "raw_sentence": "The hotel location is perfect.", "tokens": ["The", "hotel", "location", "is", "perfect", "."], "tokens_filtered": ["hotel", "location", "perfect"], "lemmas": ["the", "hotel", "location", "be", "perfect", "."], "stems": ["the", "hotel", "locat", "is", "perfect", "."], "pos_tags": ["DT", "NN", "NN", "VBZ", "JJ", "."], "dependencies": [ ["location@@@3", "The@@@1", "det"], ["location@@@3", "hotel@@@2", "nn"], ["is@@@4", "location@@@3", "nsubj"], ["root@@@0", "is@@@4", "root"], ["is@@@4", "perfect@@@5", "acomp"], ["is@@@4", ".@@@6", "punct"] ] } """ do { guard let jsonData = json.data(using: .utf16) else { XCTAssert(false) return } let jsonDecoder = JSONDecoder() let sentence = try jsonDecoder.decode(Sentence.self, from: jsonData) XCTAssertNotNil(sentence) XCTAssertEqual(sentence.position, 0) XCTAssertEqual(sentence.rawSentence, "The hotel location is perfect.") XCTAssertEqual(sentence.tokens, ["The", "hotel", "location", "is", "perfect", "."]) XCTAssertEqual(sentence.tokensFiltered, ["hotel", "location", "perfect"]) XCTAssertEqual(sentence.lemmas, ["the", "hotel", "location", "be", "perfect", "."]) XCTAssertEqual(sentence.stems, ["the", "hotel", "locat", "is", "perfect", "."]) XCTAssertEqual(sentence.posTags, ["DT", "NN", "NN", "VBZ", "JJ", "."]) XCTAssertEqual(sentence.dependencies, [ ["location@@@3", "The@@@1", "det"], ["location@@@3", "hotel@@@2", "nn"], ["is@@@4", "location@@@3", "nsubj"], ["root@@@0", "is@@@4", "root"], ["is@@@4", "perfect@@@5", "acomp"], ["is@@@4", ".@@@6", "punct"] ]) } catch let decodeError { print("Decode Error: \(decodeError.localizedDescription)") XCTAssert(false) } } }
// // MainPageViewController.swift // SmokingMonitor // // Created by Minjiexie on 14/12/5. // Copyright (c) 2014年 MinjieXie. All rights reserved. // import UIKit class MainPageViewController:UIViewController,UITextFieldDelegate{ override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func ISmokeBtn(sender: UIButton) { userDate.addSmokeNumber()//add smoke func println(userDate.userSmokingInformation.smokeNumber)// update date or cache document } //UITextField Delegate func textFieldShouldReturn(textField: UITextField) -> Bool{ textField.resignFirstResponder() return true } }
// // MeditationCollectionViewCell.swift // iMPRESENT // // Created by codeplus on 11/17/19. // Copyright © 2019 CodePlus. All rights reserved. // import UIKit class MeditationCollectionViewCell: UICollectionViewCell { @IBOutlet weak var image: UIImageView! @IBOutlet weak var title: UILabel! var fontcolor = UIColor(red:1/255, green:33/255, blue:105/255,alpha:1.0) override func awakeFromNib() { super.awakeFromNib() self.backgroundColor = UIColor(red: 243/255, green: 242/255, blue: 241/255, alpha: 1.0) self.title.textColor = fontcolor self.heightAnchor.constraint(equalToConstant: 210).isActive = true self.widthAnchor.constraint(equalToConstant: 175).isActive = true self.layer.cornerRadius = 30.0 } class var reuseIdentifier: String { return "MeditationCellReuseIdentifier" } class var nibName: String { return "MeditationCollectionViewCell" } func configureCell(name: String, image: String) { self.title.text = name self.image.image = UIImage(named: image) self.title.attributedText = NSAttributedString(string: name.uppercased(), attributes: [NSAttributedString.Key.kern: 5.0, NSAttributedString.Key.font: UIFont(name: "Helvetica", size: 10)!]) } }
import Foundation import UIKit import WebKit import CoreBluetooth import PlaygroundSupport import PlaygroundBluetooth public class DroneViewController: UIViewController{ let droneCommand: DroneCommand = DroneCommand() var droneConnection:DroneConnection = DroneConnection() var page:Int = 1 var commandText: UITextView! var commandsForAssessment:[PlaygroundValue] = [PlaygroundValue]() var initialConstraints = [NSLayoutConstraint]() var btView:PlaygroundBluetoothConnectionView! var btViewConstraints = [NSLayoutConstraint]() let btViewDelegate = ConnectionViewDelegate() public required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! } public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } public convenience init(_ page:Int = 1) { self.init(nibName: nil, bundle: nil) self.page = page } public override func viewDidLoad() { super.viewDidLoad() // Setup Playground Bluetooth view btView = PlaygroundBluetoothConnectionView(centralManager: droneConnection.centralManager!) btView.delegate = btViewDelegate btView.dataSource = btViewDelegate self.view.addSubview(btView) NSLayoutConstraint.activate([ btView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -20), btView.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 20), ]) } public override func viewDidAppear(_ animated: Bool) { // Notifies the view controller that its view was added to a view hierarchy. super.viewDidAppear(animated) } public override func viewDidLayoutSubviews() { // Called to notify the view controller that its view has just laid out its subviews. super.viewDidLayoutSubviews() } public func processCommand(_ message: PlaygroundValue){ commandText.text = "msg: \(message)" } } class ConnectionViewDelegate: PlaygroundBluetoothConnectionViewDelegate, PlaygroundBluetoothConnectionViewDataSource { // MARK: PlaygroundBluetoothConnectionViewDataSource public func connectionView(_ connectionView: PlaygroundBluetoothConnectionView, itemForPeripheral peripheral: CBPeripheral, withAdvertisementData advertisementData: [String : Any]?) -> PlaygroundBluetoothConnectionView.Item { // Provide display information associated with a peripheral item. let name = peripheral.name ?? NSLocalizedString("Unknown Device", comment:"") let icon = UIImage(named: "BookIcon")! let issueIcon = icon return PlaygroundBluetoothConnectionView.Item(name: name, icon: icon, issueIcon: issueIcon, firmwareStatus: nil, batteryLevel: nil) } // MARK: PlaygroundBluetoothConnectionView Delegate public func connectionView(_ connectionView: PlaygroundBluetoothConnectionView, shouldDisplayDiscovered peripheral: CBPeripheral, withAdvertisementData advertisementData: [String : Any]?, rssi: Double) -> Bool { // Filter out peripheral items (optional) return true } public func connectionView(_ connectionView: PlaygroundBluetoothConnectionView, titleFor state: PlaygroundBluetoothConnectionView.State) -> String { // Provide a localized title for the given state of the connection view. switch state { case .noConnection: return NSLocalizedString("Connect Drone", comment:"") case .connecting: return NSLocalizedString("Connecting Drone", comment:"") case .searchingForPeripherals: return NSLocalizedString("Searching for Drone", comment:"") case .selectingPeripherals: return NSLocalizedString("Select Drone", comment:"") case .connectedPeripheralFirmwareOutOfDate: return NSLocalizedString("Connect to a Different Drone", comment:"") } } public func connectionView(_ connectionView: PlaygroundBluetoothConnectionView, firmwareUpdateInstructionsFor peripheral: CBPeripheral) -> String { // Provide firmware update instructions. return "Firmware update instructions here." } } extension DroneViewController: PlaygroundLiveViewMessageHandler { public func liveViewMessageConnectionOpened() { } public func liveViewMessageConnectionClosed() { } public func receive(_ message: PlaygroundValue) { if case let .string(command) = message { // Commands droneCommand.sendDroneCommand(droneConnection, message) //processCommand(message) } } public func sendMessage(_ message: PlaygroundValue) { // Send message to Constants.swift } }
/* var currentCircle: Circle? var circleCanvas: CircleView! var radius: CGFloat = 20 var count: Int = -1 @IBOutlet var slider: UISlider! @IBAction func clearScreen(_ sender: Any) { circleCanvas.theCircle = nil circleCanvas.circles = [] } @IBAction func undoAction(_ sender: Any) { if (circleCanvas.circles.count > 0){ circleCanvas.circles.removeLast() //circleCanvas.circles.remove(at: count) count -= 1 print(circleCanvas.circles) }else{ circleCanvas.theCircle = nil print(circleCanvas.circles) } } @IBAction func changeSize(_ sender: Any) { let value: Float = slider.value radius = CGFloat(value) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. circleCanvas = CircleView(frame: view.frame) //creating view that takes up entire screen view.addSubview(circleCanvas) //adding as a sub view } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { //this code creates a point value when the screen is touched and then prints the x,y let touchPoint = (touches.first)!.location(in: view) as CGPoint print("point is \(touchPoint)") count += 1 currentCircle = Circle(center: touchPoint, radius: 0, number: count) } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { let touchPoint = (touches.first)!.location(in: view) as CGPoint print("You moved to \(touchPoint)") currentCircle?.radius = radius circleCanvas.theCircle = currentCircle }*/ override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { //this code creates a point value when the screen is touched and then prints the x,y let touchPoint = (touches.first)!.location(in: view) as CGPoint print("point is \(touchPoint)") count += 1 currentCircle = Circle(center: touchPoint, radius: 0, number: count) currentCircle?.radius = radius circleCanvas.theCircle = currentCircle if let newCircle = currentCircle{ circleCanvas.circles.append(newCircle) } circleCanvas.theCircle = nil } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { let touchPoint = (touches.first)!.location(in: view) as CGPoint print("You moved to \(touchPoint)") count += 1 currentCircle = Circle(center: touchPoint, radius: 0, number: count) currentCircle?.radius = radius circleCanvas.theCircle = currentCircle if let newCircle = currentCircle{ circleCanvas.circles.append(newCircle) } circleCanvas.theCircle = nil } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { let touchPoint = (touches.first)!.location(in: view) as CGPoint print("You ended to \(touchPoint)") /* if let newCircle = currentCircle{ circleCanvas.circles.append(newCircle) } circleCanvas.theCircle = nil*/ }*/
// // PromoCodeVC.swift // TaxiApp // // Created by Hundily Cerqueira on 23/04/20. // Copyright © 2020 Hundily Cerqueira. All rights reserved. // import UIKit class PromoCodeVC: UIViewController { private lazy var tableView: UITableView = { let tableView = UITableView(frame: .zero) // tableView.backgroundColor = .purple tableView.separatorStyle = .none // tableView.delegate = self // tableView.dataSource = self return tableView }() private lazy var viewBotton: UIView = { let view = UIView() view.backgroundColor = .white return view }() let button: CustomButton = { let button = CustomButton() button.setTitle("Add promocode", for: .normal) button.layoutButton(.enabled) button.addTarget(self, action: #selector(handleAddPromoCodeToggle), for: .touchUpInside) return button }() private var kPromoCodeCell = "PromoCodeCell" override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white setupViews() setTableView() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) navigationController?.navigationBar.isTranslucent = false } override func viewWillAppear(_ animated: Bool) { navigationController?.navigationBar.isHidden = false navigationItem.title = "Promo" } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) navigationItem.title = " " } func setTableView() { tableView.delegate = self tableView.dataSource = self tableView.registerNib(PromoCodeCell.self) } @objc func handleAddPromoCodeToggle() { print("handleAddPromoCodeToggle") let addPromoCodeVC = AddPromoCodeVC() navigationController?.pushViewController(addPromoCodeVC, animated: true) } } extension PromoCodeVC: CodeViewProtocol { func buildViewHierarchy() { view.addSubview(tableView) view.addSubview(viewBotton) viewBotton.addSubview(button) } func setupConstraints() { tableView.anchor(top: view.topAnchor, leading: view.leadingAnchor, bottom: viewBotton.topAnchor, trailing: view.trailingAnchor) viewBotton.anchor(top: nil, leading: view.leadingAnchor, bottom: view.bottomAnchor, trailing: view.trailingAnchor, insets: .init(top: 20, left: 20, bottom: 0, right: 20)) viewBotton.anchor(height: 100, width: nil) button.anchor(top: viewBotton.topAnchor, leading: viewBotton.leadingAnchor, bottom: viewBotton.bottomAnchor, trailing: viewBotton.trailingAnchor, insets: .init(top: 20, left: 0, bottom: 20, right: 0)) } } extension PromoCodeVC: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 190 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 10 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: kPromoCodeCell, for: indexPath) as! PromoCodeCell return cell } }
import RxSwift import RxCocoa class OneInchSettingsViewModel { private let disposeBag = DisposeBag() private let service: OneInchSettingsService private let tradeService: OneInchTradeService private let actionRelay = BehaviorRelay<ActionState>(value: .enabled) init(service: OneInchSettingsService, tradeService: OneInchTradeService) { self.service = service self.tradeService = tradeService service.stateObservable .subscribeOn(ConcurrentDispatchQueueScheduler(qos: .userInitiated)) .subscribe(onNext: { [weak self] _ in self?.syncAction() }) .disposed(by: disposeBag) } private func syncAction() { switch service.state { case .valid: actionRelay.accept(.enabled) case .invalid: guard let error = service.errors.first else { return } switch error { case is SwapSettingsModule.AddressError: actionRelay.accept(.disabled(title: "swap.advanced_settings.error.invalid_address".localized)) case is SwapSettingsModule.SlippageError: actionRelay.accept(.disabled(title: "swap.advanced_settings.error.invalid_slippage".localized)) default: () } } } } extension OneInchSettingsViewModel { public var actionDriver: Driver<ActionState> { actionRelay.asDriver() } public func doneDidTap() -> Bool { if case let .valid(settings) = service.state { tradeService.settings = settings return true } return false } } extension OneInchSettingsViewModel { enum ActionState { case enabled case disabled(title: String) } }
// // SettingsIntegrationTests.swift // // // Created by Vladislav Fitc on 05/03/2020. // import Foundation import XCTest @testable import AlgoliaSearchClient class SettingsIntegrationTests: IntegrationTestCase { override var indexNameSuffix: String? { return "settings" } override var retryableTests: [() throws -> Void] { [settings] } func settings() throws { let indexInitialization = try index.saveObject(TestRecord(), autoGeneratingObjectID: true) try indexInitialization.wait() let settings = Settings() .set(\.searchableAttributes, to: ["attribute1", "attribute2", "attribute3", .unordered("attribute4"), .unordered("attribute5")]) .set(\.attributesForFaceting, to: [.default("attribute1"), .filterOnly("attribute2"), .searchable("attribute3")]) .set(\.unretrievableAttributes, to: ["attribute1", "attribute2"]) .set(\.attributesToRetrieve, to: ["attribute3", "attribute4"]) .set(\.ranking, to: [.asc("attribute1"), .desc("attribute2"), .attribute, .custom, .exact, .filters, .geo, .proximity, .typo, .words]) .set(\.customRanking, to: [.asc("attribute1"), .desc("attribute1")]) .set(\.replicas, to: ["\(index.name.rawValue)_replica1", "\(index.name.rawValue)_replica2"]) .set(\.maxValuesPerFacet, to: 100) .set(\.sortFacetsBy, to: .count) .set(\.attributesToHighlight, to: ["attribute1", "attribute2"]) .set(\.attributesToSnippet, to: [.init(attribute: "attribute1", count: 10), .init(attribute: "attribute2", count: 8)]) .set(\.highlightPreTag, to: "<strong>") .set(\.highlightPostTag, to: "</string>") .set(\.snippetEllipsisText, to: " and so on.") .set(\.restrictHighlightAndSnippetArrays, to: true) .set(\.hitsPerPage, to: 42) .set(\.paginationLimitedTo, to: 43) .set(\.minWordSizeFor1Typo, to: 2) .set(\.minWordSizeFor2Typos, to: 6) .set(\.typoTolerance, to: false) .set(\.allowTyposOnNumericTokens, to: false) .set(\.ignorePlurals, to: false) .set(\.disableTypoToleranceOnAttributes, to: ["attribute1", "attribute2"]) .set(\.disableTypoToleranceOnWords, to: ["word1", "word2"]) .set(\.separatorsToIndex, to: "()[]") .set(\.queryType, to: .prefixNone) .set(\.removeWordsIfNoResults, to: .allOptional) .set(\.advancedSyntax, to: true) .set(\.optionalWords, to: ["word1", "word2"]) .set(\.removeStopWords, to: true) .set(\.disablePrefixOnAttributes, to: ["attribute1", "attribute2"]) .set(\.disableExactOnAttributes, to: ["attribute1", "attribute2"]) .set(\.exactOnSingleWordQuery, to: .word) .set(\.enableRules, to: false) .set(\.numericAttributesForFiltering, to: [.default("attribute1"), .default("attribute2")]) .set(\.allowCompressionOfIntegerArray, to: true) .set(\.attributeForDistinct, to: "attribute1") .set(\.distinct, to: 2) .set(\.replaceSynonymsInHighlight, to: false) .set(\.minProximity, to: 7) .set(\.responseFields, to: [.hits, .hitsPerPage]) .set(\.maxFacetHits, to: 100) .set(\.camelCaseAttributes, to: ["attribute1", "attribute2"]) .set(\.decompoundedAttributes, to: [.german: ["attribute1", "attribute2"], .finnish: ["attribute3"]]) .set(\.keepDiacriticsOnCharacters, to: "øé") .set(\.queryLanguages, to: [.english, .french]) .set(\.alternativesAsExact, to: [.ignorePlurals]) .set(\.advancedSyntaxFeatures, to: [.exactPhrase]) .set(\.userData, to: ["customUserData": 42]) .set(\.indexLanguages, to: [.japanese]) .set(\.customNormalization, to: ["default": ["ä": "ae", "ö": "oe"]]) try index.setSettings(settings).wait() var fetchedSettings = try index.getSettings() XCTAssertEqual(fetchedSettings.searchableAttributes, ["attribute1", "attribute2", "attribute3", .unordered("attribute4"), .unordered("attribute5")]) XCTAssertEqual(fetchedSettings.attributesForFaceting, [.default("attribute1"), .filterOnly("attribute2"), .searchable("attribute3")]) XCTAssertEqual(fetchedSettings.unretrievableAttributes, ["attribute1", "attribute2"]) XCTAssertEqual(fetchedSettings.attributesToRetrieve, ["attribute3", "attribute4"]) XCTAssertEqual(fetchedSettings.ranking, [.asc("attribute1"), .desc("attribute2"), .attribute, .custom, .exact, .filters, .geo, .proximity, .typo, .words]) XCTAssertEqual(fetchedSettings.customRanking, [.asc("attribute1"), .desc("attribute1")]) XCTAssertEqual(fetchedSettings.replicas, ["\(index.name.rawValue)_replica1", "\(index.name.rawValue)_replica2"]) XCTAssertEqual(fetchedSettings.maxValuesPerFacet, 100) XCTAssertEqual(fetchedSettings.sortFacetsBy, .count) XCTAssertEqual(fetchedSettings.attributesToHighlight, ["attribute1", "attribute2"]) XCTAssertEqual(fetchedSettings.attributesToSnippet, [.init(attribute: "attribute1", count: 10), .init(attribute: "attribute2", count: 8)]) XCTAssertEqual(fetchedSettings.highlightPreTag, "<strong>") XCTAssertEqual(fetchedSettings.highlightPostTag, "</string>") XCTAssertEqual(fetchedSettings.snippetEllipsisText, " and so on.") XCTAssertEqual(fetchedSettings.restrictHighlightAndSnippetArrays, true) XCTAssertEqual(fetchedSettings.hitsPerPage, 42) XCTAssertEqual(fetchedSettings.paginationLimitedTo, 43) XCTAssertEqual(fetchedSettings.minWordSizeFor1Typo, 2) XCTAssertEqual(fetchedSettings.minWordSizeFor2Typos, 6) XCTAssertEqual(fetchedSettings.typoTolerance, false) XCTAssertEqual(fetchedSettings.allowTyposOnNumericTokens, false) XCTAssertEqual(fetchedSettings.ignorePlurals, false) XCTAssertEqual(fetchedSettings.disableTypoToleranceOnAttributes, ["attribute1", "attribute2"]) XCTAssertEqual(fetchedSettings.disableTypoToleranceOnWords, ["word1", "word2"]) XCTAssertEqual(fetchedSettings.separatorsToIndex, "()[]") XCTAssertEqual(fetchedSettings.queryType, .prefixNone) XCTAssertEqual(fetchedSettings.removeWordsIfNoResults, .allOptional) XCTAssertEqual(fetchedSettings.advancedSyntax, true) XCTAssertEqual(fetchedSettings.optionalWords, ["word1", "word2"]) XCTAssertEqual(fetchedSettings.removeStopWords, true) XCTAssertEqual(fetchedSettings.disablePrefixOnAttributes, ["attribute1", "attribute2"]) XCTAssertEqual(fetchedSettings.disableExactOnAttributes, ["attribute1", "attribute2"]) XCTAssertEqual(fetchedSettings.exactOnSingleWordQuery, .word) XCTAssertEqual(fetchedSettings.enableRules, false) XCTAssertEqual(fetchedSettings.numericAttributesForFiltering, [.default("attribute1"), .default("attribute2")]) XCTAssertEqual(fetchedSettings.allowCompressionOfIntegerArray, true) XCTAssertEqual(fetchedSettings.attributeForDistinct, "attribute1") XCTAssertEqual(fetchedSettings.distinct, 2) XCTAssertEqual(fetchedSettings.replaceSynonymsInHighlight, false) XCTAssertEqual(fetchedSettings.minProximity, 7) XCTAssertEqual(fetchedSettings.responseFields, [.hits, .hitsPerPage]) XCTAssertEqual(fetchedSettings.maxFacetHits, 100) XCTAssertEqual(fetchedSettings.camelCaseAttributes, ["attribute1", "attribute2"]) XCTAssertEqual(fetchedSettings.decompoundedAttributes, [.german: ["attribute1", "attribute2"], .finnish: ["attribute3"]]) XCTAssertEqual(fetchedSettings.keepDiacriticsOnCharacters, "øé") XCTAssertEqual(fetchedSettings.queryLanguages, [.english, .french]) XCTAssertEqual(fetchedSettings.alternativesAsExact, [.ignorePlurals]) XCTAssertEqual(fetchedSettings.advancedSyntaxFeatures, [.exactPhrase]) XCTAssertEqual(fetchedSettings.userData, ["customUserData": 42]) XCTAssertEqual(fetchedSettings.indexLanguages, [.japanese]) XCTAssertEqual(fetchedSettings.customNormalization, ["default": ["ä": "ae", "ö": "oe"]]) try index.setSettings(settings .set(\.typoTolerance, to: .min) .set(\.ignorePlurals, to: [.english, .french]) .set(\.removeStopWords, to: [.english, .french]) .set(\.distinct, to: true) ).wait() fetchedSettings = try index.getSettings() XCTAssertEqual(fetchedSettings.searchableAttributes, ["attribute1", "attribute2", "attribute3", .unordered("attribute4"), .unordered("attribute5")]) XCTAssertEqual(fetchedSettings.attributesForFaceting, [.default("attribute1"), .filterOnly("attribute2"), .searchable("attribute3")]) XCTAssertEqual(fetchedSettings.unretrievableAttributes, ["attribute1", "attribute2"]) XCTAssertEqual(fetchedSettings.attributesToRetrieve, ["attribute3", "attribute4"]) XCTAssertEqual(fetchedSettings.ranking, [.asc("attribute1"), .desc("attribute2"), .attribute, .custom, .exact, .filters, .geo, .proximity, .typo, .words]) XCTAssertEqual(fetchedSettings.customRanking, [.asc("attribute1"), .desc("attribute1")]) XCTAssertEqual(fetchedSettings.replicas, ["\(index.name.rawValue)_replica1", "\(index.name.rawValue)_replica2"]) XCTAssertEqual(fetchedSettings.maxValuesPerFacet, 100) XCTAssertEqual(fetchedSettings.sortFacetsBy, .count) XCTAssertEqual(fetchedSettings.attributesToHighlight, ["attribute1", "attribute2"]) XCTAssertEqual(fetchedSettings.attributesToSnippet, [.init(attribute: "attribute1", count: 10), .init(attribute: "attribute2", count: 8)]) XCTAssertEqual(fetchedSettings.highlightPreTag, "<strong>") XCTAssertEqual(fetchedSettings.highlightPostTag, "</string>") XCTAssertEqual(fetchedSettings.snippetEllipsisText, " and so on.") XCTAssertEqual(fetchedSettings.restrictHighlightAndSnippetArrays, true) XCTAssertEqual(fetchedSettings.hitsPerPage, 42) XCTAssertEqual(fetchedSettings.paginationLimitedTo, 43) XCTAssertEqual(fetchedSettings.minWordSizeFor1Typo, 2) XCTAssertEqual(fetchedSettings.minWordSizeFor2Typos, 6) XCTAssertEqual(fetchedSettings.typoTolerance, .min) XCTAssertEqual(fetchedSettings.allowTyposOnNumericTokens, false) XCTAssertEqual(fetchedSettings.ignorePlurals, [.english, .french]) XCTAssertEqual(fetchedSettings.disableTypoToleranceOnAttributes, ["attribute1", "attribute2"]) XCTAssertEqual(fetchedSettings.disableTypoToleranceOnWords, ["word1", "word2"]) XCTAssertEqual(fetchedSettings.separatorsToIndex, "()[]") XCTAssertEqual(fetchedSettings.queryType, .prefixNone) XCTAssertEqual(fetchedSettings.removeWordsIfNoResults, .allOptional) XCTAssertEqual(fetchedSettings.advancedSyntax, true) XCTAssertEqual(fetchedSettings.optionalWords, ["word1", "word2"]) XCTAssertEqual(fetchedSettings.removeStopWords, [.english, .french]) XCTAssertEqual(fetchedSettings.disablePrefixOnAttributes, ["attribute1", "attribute2"]) XCTAssertEqual(fetchedSettings.disableExactOnAttributes, ["attribute1", "attribute2"]) XCTAssertEqual(fetchedSettings.exactOnSingleWordQuery, .word) XCTAssertEqual(fetchedSettings.enableRules, false) XCTAssertEqual(fetchedSettings.numericAttributesForFiltering, [.default("attribute1"), .default("attribute2")]) XCTAssertEqual(fetchedSettings.allowCompressionOfIntegerArray, true) XCTAssertEqual(fetchedSettings.attributeForDistinct, "attribute1") XCTAssertEqual(fetchedSettings.distinct, true) XCTAssertEqual(fetchedSettings.replaceSynonymsInHighlight, false) XCTAssertEqual(fetchedSettings.minProximity, 7) XCTAssertEqual(fetchedSettings.responseFields, [.hits, .hitsPerPage]) XCTAssertEqual(fetchedSettings.maxFacetHits, 100) XCTAssertEqual(fetchedSettings.camelCaseAttributes, ["attribute1", "attribute2"]) XCTAssertEqual(fetchedSettings.decompoundedAttributes, [.german: ["attribute1", "attribute2"], .finnish: ["attribute3"]]) XCTAssertEqual(fetchedSettings.keepDiacriticsOnCharacters, "øé") XCTAssertEqual(fetchedSettings.queryLanguages, [.english, .french]) XCTAssertEqual(fetchedSettings.alternativesAsExact, [.ignorePlurals]) XCTAssertEqual(fetchedSettings.advancedSyntaxFeatures, [.exactPhrase]) XCTAssertEqual(fetchedSettings.userData, ["customUserData": 42]) XCTAssertEqual(fetchedSettings.indexLanguages, [.japanese]) XCTAssertEqual(fetchedSettings.customNormalization, ["default": ["ä": "ae", "ö": "oe"]]) } }
// // LoginTableViewCell.swift // Coordinate // // Created by James Wilkinson on 18/03/2016. // Copyright © 2016 James Wilkinson. All rights reserved. // import UIKit class LoginTableViewCell: UITableViewCell { @IBOutlet var button: UIButton! }
// // DescriptionEventCV.swift // Adelaide Fringe // // Created by Fan Liang on 26/10/20. // import UIKit import MapKit protocol DescriptionEventCVDelegate { func refreshTableView() func didSetEvents(_ newEvents: [Events]) } class DescriptionEventCV: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate{ @IBOutlet weak var mapView: MKMapView! @IBOutlet weak var name: UILabel! @IBOutlet weak var likes: UILabel! @IBOutlet weak var dislikes: UILabel! @IBOutlet weak var artist: UILabel! @IBOutlet weak var venue: UILabel! @IBOutlet weak var descriptionView: UITextView! @IBOutlet weak var eventImage: UIImageView! let regionInMeters: Double = 100000 var event:Events! var desriptionVenue: Venues! var locationManager = CLLocationManager() // var venueModel: FringeVenues! var displayIndex = 0; var delegate: DescriptionEventCVDelegate! var listEvent:[Events]! @IBOutlet weak var flag: UIImageView! //point out the interesting event let flagImage:UIImage = #imageLiteral(resourceName: "images") override func viewDidLoad() { super.viewDidLoad() let upSwipe = UISwipeGestureRecognizer(target: self, action: #selector(swipeAction(swipe:))) upSwipe.direction = UISwipeGestureRecognizer.Direction.up self.view.addGestureRecognizer(upSwipe) if (eventListinterested[displayIndex] == 1){ flag.image = flagImage } descriptionView?.text = event.description name?.text = event.name venue?.text = event.venue artist?.text = event.artist likes?.text = event.likes dislikes?.text = event.dislikes let imageString = "https://www.partiklezoo.com/fringer/images/\(event.image)" let imageurl = URL(string: imageString) var image:UIImage! do { let imageData = try Data(contentsOf: imageurl!) image = UIImage(data: imageData) } catch{ print("Error Image") } eventImage?.image = image locationManager.requestWhenInUseAuthorization() if CLLocationManager.locationServicesEnabled() { locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.distanceFilter = kCLDistanceFilterNone locationManager.startUpdatingLocation() } mapView.showsUserLocation = true //points out the event location if (venuemodel.hasVenue(event.id)){ let latitude1: Double = Double(venuemodel.findVenues(event.id).latitude)! let longtitude1: Double = Double(venuemodel.findVenues(event.id).longitude)! let location = CLLocationCoordinate2D.init(latitude: latitude1, longitude: longtitude1) let annotation = MKPointAnnotation() annotation.coordinate = location annotation.title = event.name annotation.subtitle = event.venue mapView.addAnnotation(annotation) } } //swipe up for the interesting @objc func swipeAction(swipe:UISwipeGestureRecognizer) { if (indexList[displayIndex] == 0){ indexList[displayIndex] = 1 eventListinterested[displayIndex] = 1 print("interested") flag.image = flagImage // Declare Alert message let dialogMessage = UIAlertController(title: "Success", message: "Your request was already sent", preferredStyle: .alert) let ok = UIAlertAction(title: "OK", style: .default) postinterested(postID: event.id) dialogMessage.addAction(ok) self.present(dialogMessage, animated: true, completion: nil) }else{ indexList[displayIndex] = 0 eventListinterested[displayIndex] = 0 print("uninterested") flag.image = nil } record.changeIndexList(changeIndex: displayIndex, newinterestedEvent: indexList[displayIndex]) } //when press the back button, it implement these functions @IBAction func back(_ sender: Any) { delegate.didSetEvents(listEvent) allimages = eventlistimages delegate.refreshTableView() eventListlikes = indexlikes eventListinterested = indexList } //this delegate function is for displaying the route overlay and styling it func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer { let renderer = MKPolylineRenderer(overlay: overlay) renderer.strokeColor = UIColor.red renderer.lineWidth = 5.0 return renderer } func centerViewOnUserLocation() { if let location = locationManager.location?.coordinate { let region = MKCoordinateRegion.init(center: location, latitudinalMeters: regionInMeters, longitudinalMeters: regionInMeters) mapView.setRegion(region, animated: true) } } //post the interested event to the server func postinterested(postID: String){ // let parameters = ["result": "success", "id": postID, "email": useremail] as [String : Any] let parameters = ["result": "success", "id": postID] print("post") guard let url = URL(string: "http://partiklezoo.com/fringer/?action=register&id=\(postID)") else { return } var request = URLRequest(url: url) request.httpMethod = "POST" request.addValue("application/json", forHTTPHeaderField: "Content-Type") guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: []) else { return } request.httpBody = httpBody let session = URLSession.shared session.dataTask(with: request) { (data, response, error) in if let response = response { print(response) } if let data = data { do { let json = try JSONSerialization.jsonObject(with: data, options: []) print(json) } catch { print(error) } } }.resume() } } extension DescriptionEventCV { func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { guard let location = locations.last else { return } let region = MKCoordinateRegion.init(center: location.coordinate, latitudinalMeters: regionInMeters, longitudinalMeters: regionInMeters) mapView.setRegion(region, animated: true) } }
import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let conn = Connection() let para = ["ext":"91","phone":"123456789","device_type":"IOS"] conn.TosendRequest(httpMethod: "POST", para: para, stringUrl: "http://104.130.26.84/beacon/public/api/auth/login") // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
// Generated using Sourcery 0.9.0 — https://github.com/krzysztofzablocki/Sourcery // DO NOT EDIT import UIKit public func barStyle<Object: UINavigationBar>() -> Lens<Object, UIBarStyle> { return Lens( get: { $0.barStyle }, setter: { $0.barStyle = $1 } ) } public func delegate<Object: UINavigationBar>() -> Lens<Object, UINavigationBarDelegate?> { return Lens( get: { $0.delegate }, setter: { $0.delegate = $1 } ) } public func isTranslucent<Object: UINavigationBar>() -> Lens<Object, Bool> { return Lens( get: { $0.isTranslucent }, setter: { $0.isTranslucent = $1 } ) } public func topItem<Object: UINavigationBar>() -> Lens<Object, UINavigationItem?> { return Lens { $0.topItem } } public func backItem<Object: UINavigationBar>() -> Lens<Object, UINavigationItem?> { return Lens { $0.backItem } } public func items<Object: UINavigationBar>() -> Lens<Object, [UINavigationItem]?> { return Lens( get: { $0.items }, setter: { $0.items = $1 } ) } public func barTintColor<Object: UINavigationBar>() -> Lens<Object, UIColor?> { return Lens( get: { $0.barTintColor }, setter: { $0.barTintColor = $1 } ) } public func shadowImage<Object: UINavigationBar>() -> Lens<Object, UIImage?> { return Lens( get: { $0.shadowImage }, setter: { $0.shadowImage = $1 } ) } public func titleTextAttributes<Object: UINavigationBar>() -> Lens<Object, [NSAttributedString.Key : Any]?> { return Lens( get: { $0.titleTextAttributes }, setter: { $0.titleTextAttributes = $1 } ) } public func backIndicatorImage<Object: UINavigationBar>() -> Lens<Object, UIImage?> { return Lens( get: { $0.backIndicatorImage }, setter: { $0.backIndicatorImage = $1 } ) } public func backIndicatorTransitionMaskImage<Object: UINavigationBar>() -> Lens<Object, UIImage?> { return Lens( get: { $0.backIndicatorTransitionMaskImage }, setter: { $0.backIndicatorTransitionMaskImage = $1 } ) }
// // MergeGraph.swift // Algorithms // // Created by Loc Tran on 3/21/17. // Copyright © 2017 LocTran. All rights reserved. // import Foundation import UIKit class MergeGraph: UIView { let widthRatio = 2 var arrayLabel: [SortingLabel]! var arrayLabelOne: [SortingLabel]! var arrayLabelTwo: [SortingLabel]! var arrayLabelThree: [SortingLabel]! var arrayLabelFour: [SortingLabel]! required init?(coder aDecoder: NSCoder) { fatalError(".....") } init(frame: CGRect, arrayDisplay: [Int], colors: [UIColor]) { super.init(frame: frame) self.arrayLabel = [SortingLabel]() self.arrayLabelOne = [SortingLabel]() self.arrayLabelTwo = [SortingLabel]() self.arrayLabelThree = [SortingLabel]() self.arrayLabelFour = [SortingLabel]() self.drawGraph(arrayDisplay: arrayDisplay, colors: colors) } private func drawGraph(arrayDisplay: [Int], colors: [UIColor]) { let spacing = frame.width/CGFloat(self.widthRatio * arrayDisplay.count + arrayDisplay.count + 1) let rectSize = CGFloat(widthRatio) * spacing var x = spacing SPACING = spacing var yFloor: CGFloat for index in 0..<arrayDisplay.count { let sortingLabel = SortingLabel(frame: CGRect(x: x, y: 0, width: rectSize, height: rectSize), color: colors[index], value: String(arrayDisplay[index])) let FloorOne = SortingLabel(frame: CGRect(x: x, y: 0, width: rectSize, height: rectSize), color: DEFAULT_COLOR, value: "0") FloorOne.isHidden = true yFloor = FloorOne.frame.origin.y + rectSize + spacing let FloorTwo = SortingLabel(frame: CGRect(x: x, y: yFloor, width: rectSize, height: rectSize), color: DEFAULT_COLOR, value: "0") FloorTwo.isHidden = true yFloor = FloorTwo.frame.origin.y + rectSize + spacing let FloorThree = SortingLabel(frame: CGRect(x: x, y: yFloor, width: rectSize, height: rectSize), color: colors[index], value: String(arrayDisplay[index])) FloorThree.isHidden = true yFloor = FloorThree.frame.origin.y + rectSize + spacing let FloorFour = SortingLabel(frame: CGRect(x: x, y: yFloor, width: rectSize, height: rectSize), color: colors[index], value: String(arrayDisplay[index])) FloorFour.isHidden = true self.arrayLabel.append(sortingLabel) self.arrayLabelOne.append(FloorOne) self.arrayLabelTwo.append(FloorTwo) self.arrayLabelThree.append(FloorThree) self.arrayLabelFour.append(FloorFour) self.addSubview(FloorOne) self.addSubview(FloorTwo) self.addSubview(FloorThree) self.addSubview(FloorFour) self.insertSubview(sortingLabel, at: 3) x = x + spacing + rectSize } } }
// // MeceviTableViewController.swift // mobilnoracunarstvo // // Created by mladen on 24.5.21.. // import UIKit import ChameleonFramework import Firebase class MeceviTableViewController: UITableViewController { @IBOutlet var tableMatches: UITableView! var ref: DatabaseReference! var matchHistory = [Match]() let gameVC = GameViewController() override func viewDidLoad() { super.viewDidLoad() tableView.separatorColor = UIColor.darkGray tableView.rowHeight = 90 navigationItem.backButtonDisplayMode = .default tableView.frame = tableView.frame.inset(by: UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)) tableView.backgroundColor = UIColor.darkGray // sad za citanje iz baze let player1UserDef = self.gameVC.defaults.string(forKey: "player1") let player2UserDef = self.gameVC.defaults.string(forKey: "player2") ref = Database.database().reference().child("matches") ref.observe(DataEventType.value) { (snapshot) in if snapshot.childrenCount > 0{ self.matchHistory.removeAll() for matches in snapshot.children.allObjects as! [DataSnapshot]{ print("OVO SU MECEVI : \(snapshot.children.allObjects)") let matchObject = matches.value as? [String : AnyObject] print("Ovo je match object: \(matchObject)") let player1Name = matchObject?["player1"] let player2Name = matchObject?["player2"] let player1Score = matchObject?["player1Score"] let player2Score = matchObject?["player2Score"] let winner = matchObject?["winner"] // ako je player iz baze = playeru u user defaults onda hocu iz baze da procitam taj mec if player1Name as! String? == player1UserDef && player2Name as! String? == player2UserDef { let match = Match(player1: player1Name as! String?, player1Score: player1Score as! String?, player2: player2Name as! String?, player2Score: player2Score as! String?, winner: winner as! String?) self.matchHistory.append(match) } // isto to samo drugacija kombinacija if player1Name as! String? == player2UserDef && player2Name as! String? == player1UserDef { let match1 = Match(player1: player1Name as! String?, player1Score: player1Score as! String?, player2: player2Name as! String?, player2Score: player2Score as! String?, winner: winner as! String?) self.matchHistory.append(match1) } // // let match = Match(player1: player1Name as! String?, // player1Score: player1Score as! String?, // player2: player2Name as! String?, // player2Score: player2Score as! String?, // winner: winner as! String?) // self.matchHistory.append(match) // } self.tableMatches.reloadData() } } } // MARK: - Table view data source // override func numberOfSections(in tableView: UITableView) -> Int { // // return matchHistory.count // } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // identifier je onaj identifier sto smo dali cell u main.storyboard //return matchHistory.count // napravice onoliko redova u tabeli koliko mi imamo elemenata u nizu return matchHistory.count } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 10 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "matchCell", for: indexPath) let match : Match match = matchHistory[indexPath.row] cell.textLabel?.numberOfLines = 0 cell.textLabel?.text = "\(match.player1 ?? "") : \(match.player1Score ?? "") vs \(match.player2 ?? "") : \(match.player2Score ?? "")\nWinner - \(match.winner ?? "")" cell.textLabel?.textAlignment = .center cell.selectionStyle = .none cell.textLabel?.font = UIFont(name:"Avenir", size:17) cell.widthAnchor.constraint(equalToConstant: 170).isActive = true //cell.layer.cornerRadius = 10 if let color = HexColor("#FFFF00")?.lighten(byPercentage: CGFloat(indexPath.row) / CGFloat(matchHistory.count)){ cell.backgroundColor = color cell.textLabel?.textColor = ContrastColorOf(color, returnFlat: true) // ova linija je za tekst } return cell } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let header = UIView() header.backgroundColor = UIColor.darkGray return header } }
// // ContentView.swift // WordSearch // // Created by Marshall Lee on 2020-04-24. // Copyright © 2020 Marshall Lee. All rights reserved. // import SwiftUI struct ContentView: View { @ObservedObject var game: Game = Game.sharedInstance var body: some View { ZStack { Color.orange.opacity(0.8).edgesIgnoringSafeArea(.all) // new try with swiftUI // This somehow adds up memory about 1-2mb whenever navigation happens. // NavigationLink probably could be better i guess if !self.game.isRunning { MainView(startFunction: self._startGame).animation(.easeInOut) } else { GameView(backButton: self._toMain).animation(.easeInOut) } } } //============== Behaviours ============== public func _startGame() -> Void { self.game.isRunning = true self.game._resetGame() // randomize whenever user starts a new game } public func _toMain() -> Void { self.game.isRunning = false } //======================================== } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
// // ViewController.swift // SetGame // // Created by Unal Celik on 20.03.2019. // Copyright © 2019 unalCe. All rights reserved. // import UIKit class GameViewController: UIViewController { // MARK: - Outlets @IBOutlet var cardCollection: [UIButton]! @IBOutlet weak var scoreLabel: UILabel! @IBOutlet weak var dealThreeMoreCardsButton: UIButton! @IBAction func dealThreeMoreCards(_ sender: UIButton) { // Works nice. Looks meh. if game.didThreeCardSelected { game.changeMatchedCards() initializeDeckView() } else { game.gameRange += 3 } updateViews() } @IBAction func startNewGame(_ sender: UIButton) { game = SetGame() initializeDeckView() updateViews() } @IBAction func chooseCard(_ sender: UIButton) { if let cardNo = cardCollection.index(of: sender) { game.selectCard(at: cardNo) initializeDeckView() updateViews() } else { print("There is no such a card on the table.") } } // MARK: - Variables var game = SetGame() let defaultBorderWidth: CGFloat = 0.5 let defaultBorderColor = UIColor.darkGray.cgColor let selectedBorderWidth: CGFloat = 3 var selectedBorderColor = #colorLiteral(red: 0.2588235438, green: 0.7568627596, blue: 0.9686274529, alpha: 1).cgColor // MARK: - Life Cycle override func viewDidLoad() { super.viewDidLoad() initializeDeckView() updateViews() } // MARK: - Functions /// Remove all cards on the table private func initializeDeckView() { cardCollection.forEach() { $0.setAttributedTitle(nil, for: .normal); $0.layer.borderWidth = 0; $0.alpha = 0.2; $0.layer.cornerRadius = 6; $0.isEnabled = false } } /// Update the cards on the table private func updateViews() { scoreLabel.text = "Score: \(game.score)" dealThreeMoreCardsButton.isEnabled = game.didThreeCardSelected || (game.gameRange < 24 && game.deck.count > 2) for index in 0..<game.gameRange { let button = cardCollection[index] let card = game.cardsOnTable[index] if game.matchedCardsThatWillBeRemoved.contains(card) { // skip drawing this one continue } button.isEnabled = true; button.alpha = 1 button.setAttributedTitle(attributedString(for: card), for: .normal) if let cardMatch = card.isMatched { selectedBorderColor = cardMatch ? #colorLiteral(red: 0, green: 1, blue: 0.08472456465, alpha: 1).cgColor : #colorLiteral(red: 1, green: 0, blue: 0, alpha: 1).cgColor } else { selectedBorderColor = #colorLiteral(red: 0.2392156869, green: 0.6745098233, blue: 0.9686274529, alpha: 1).cgColor } if card.isSelected { button.layer.borderWidth = selectedBorderWidth button.layer.borderColor = selectedBorderColor } else { button.layer.borderWidth = defaultBorderWidth button.layer.borderColor = defaultBorderColor } } } /** Returns an attributed string for a given card - parameter card: Card - returns: Attributed string */ private func attributedString(for card: Card) -> NSAttributedString { var attributes = [NSAttributedString.Key : Any]() var cardColor = UIColor() var cardString = "" let font = UIFont.preferredFont(forTextStyle: .body).withSize(25) attributes = [NSAttributedString.Key.font: font] switch card.shape { case .round: cardString = "●" case .square: cardString = "■" case .triangle: cardString = "▲" } switch card.color { case .red: cardColor = .red case .blue: cardColor = .blue case .green: cardColor = .green } switch card.filling { case .outlined: attributes[.strokeWidth] = 12 fallthrough case .filled: attributes[.foregroundColor] = cardColor case .striped: attributes[.foregroundColor] = cardColor.withAlphaComponent(0.3) } // Number of characters cardString = String(repeating: cardString, count: card.number.rawValue) return NSAttributedString(string: cardString, attributes: attributes) } }
// // Controller2ViewController.swift // ToDoListApp2 // // Created by Mac on 3/26/16. // Copyright © 2016 Mac. All rights reserved. // import UIKit class AddTaskController: UIViewController { var labelTaskText: String? var labelDescriptionText: String? var updateCondition: Bool? var saveCondition: Bool? var index2: Int? var addImage: String? @IBOutlet weak var btnSaveOutlet: UIButton! @IBOutlet weak var btnUpdateOutlet: UIButton! @IBOutlet weak var tbxDescription: UITextField! @IBOutlet weak var tbxtask: UITextField! @IBOutlet weak var btnImage3: UIButton! @IBOutlet weak var btnimage2: UIButton! @IBOutlet weak var btnImage: UIButton! override func viewDidLoad() { super.viewDidLoad() self.btnSaveOutlet.layer.cornerRadius = 10 self.btnUpdateOutlet.layer.cornerRadius = 10 self.btnUpdateOutlet.enabled = false self.btnImage.layer.cornerRadius = self.btnImage.frame.size.width / 2 self.btnimage2.layer.cornerRadius = self.btnImage3.frame.size.width / 2 self.btnImage3.layer.cornerRadius = self.btnimage2.frame.size.width / 2 self.btnImage.clipsToBounds = true self.btnimage2.clipsToBounds = true self.btnImage3.clipsToBounds = true if labelTaskText != "" && labelTaskText != nil { tbxtask.text = labelTaskText tbxDescription.text = labelDescriptionText btnUpdateOutlet.enabled = updateCondition! btnSaveOutlet.enabled = saveCondition! btnSaveOutlet.alpha = 0.2 } } @IBAction func updateButtonAction(sender: AnyObject) { } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { let mysegue: ViewController = segue.destinationViewController as! ViewController if segue.identifier == "saveIdentifier" { let objStruct = TaskStruct(myTask: tbxtask.text, Description: tbxDescription.text!, photo: addImage!) TaskStruct.structArray.append(objStruct) } if segue.identifier == "updateIdentifier" { mysegue.updateMyTask = tbxtask.text mysegue.updateDescription = tbxDescription.text mysegue.updatePhoto = addImage mysegue.index = index2 } } @IBAction func btnSaveAction(sender: AnyObject) { } @IBAction func btnImageAction1(sender: AnyObject) { addImage = "c.jpg" } @IBAction func btnImageAction2(sender: AnyObject) { addImage = "b.jpg" } @IBAction func btnImageAction3(sender: AnyObject) { addImage = "a.jpg" } }
// // EditController.swift // TestTaskApp // // Created by Pavel Samsonov on 23.02.17. // Copyright © 2017 Pavel Samsonov. All rights reserved. // import UIKit protocol EditControllerDelegate { func updateUI() } class EditController: ParentClass { var picker: UIPickerView? var datePicker: UIDatePicker? let pickerArr = ["Мужской" ,"Женский", "Не указан"] var firstNameTextView = UITextView() var lastNameTextView = UITextView() var patronymicTextView = UITextView() var firstNameText = "" var lastNameText = "" var patronymicText = "" var birthdayCell: CommonCell? var birthdayText: String? var genderText: String? var tap: UITapGestureRecognizer? var delegate: EditControllerDelegate? var isChanged = false var datePickerIndexPath: IndexPath? var pickerViewIndexPath: IndexPath? override func viewDidLoad() { super.viewDidLoad() tableView.estimatedRowHeight = 50.0 tableView.rowHeight = UITableViewAutomaticDimension navigationItem.title = "Редактирование" navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Сохранить", style: .plain, target: self, action: #selector(saveContent)) tap = UITapGestureRecognizer(target: self, action: #selector(textViewResponders)) self.navigationItem.hidesBackButton = true let backButton = UIBarButtonItem(title: "Назад", style: .plain, target: self, action: #selector(backButton(sender:))) self.navigationItem.leftBarButtonItem = backButton } } // MARK:- UITableViewDataSource extension EditController { override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if isExistIndexPathDatePicker || isExistIndexPathPickerView { return dataArray.count + 1 } return dataArray.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = UITableViewCell() if indexPath.row == rows.firstNameRow || indexPath.row == rows.lastNameRow || indexPath.row == rows.patronymicRow { cell = tableView.dequeueReusableCell(withIdentifier: fullNameCellReuseIdentifier, for: indexPath) as! FullNameCell (cell as! FullNameCell).title.text = dataArray[indexPath.row] if indexPath.row == rows.firstNameRow { configureFirstNameCell(cell: cell as! FullNameCell, indexPath: indexPath) } else if indexPath.row == rows.lastNameRow { configureLastNameCell(cell: cell as! FullNameCell, indexPath: indexPath) } else if indexPath.row == rows.patronymicRow { configurePatronymicCell(cell: cell as! FullNameCell, indexPath: indexPath) } } else if indexPath.row == rows.birthdayRow { cell = tableView.dequeueReusableCell(withIdentifier: commonCellReuseIdentifier, for: indexPath) as! CommonCell configureBirthdayCell(cell: cell as! CommonCell, indexPath: indexPath) } else if indexPath.row == rows.genderRow - 1 { cell = tableView.dequeueReusableCell(withIdentifier: commonCellReuseIdentifier, for: indexPath) as! CommonCell configureGenderCell(cell: cell as! CommonCell, indexPath: indexPath) } else if indexPath.row == rows.genderRow { cell = tableView.dequeueReusableCell(withIdentifier: genderCellReuseIdentifier, for: indexPath) as! GenderCell (cell as! GenderCell).pickerView.delegate = self } if isExistIndexPathDatePicker { if indexPath.row == rows.birthdayDatePickerRow { cell = tableView.dequeueReusableCell(withIdentifier: birthdayCellReuseIdentifier, for: indexPath) as! BirthdayCell datePicker = (cell as! BirthdayCell).datePicker datePicker?.addTarget(self, action: #selector(handleDatePicker(sender:)), for: UIControlEvents.valueChanged) } else if indexPath.row == rows.genderRow { cell = tableView.dequeueReusableCell(withIdentifier: commonCellReuseIdentifier, for: indexPath) as! CommonCell configureGenderCell(cell: cell as! CommonCell, indexPath: indexPath) } } return cell } } // MARK:- UITableViewDelegate extension EditController { override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if indexPath.row == rows.birthdayRow { if isExistIndexPathPickerView { let index = IndexPath(row: indexPath.row + 1, section: 0) togglePickerViewForSelectedIndexPath(indexPath: index) } toggleDatePickerForSelectedIndexPath(indexPath: indexPath) } else if isExistIndexPathDatePicker { if indexPath.row == rows.genderRow { toggleDatePickerForSelectedIndexPath(indexPath: indexPath) togglePickerViewForSelectedIndexPath(indexPath: indexPath) } } else { togglePickerViewForSelectedIndexPath(indexPath: indexPath) } tableView.reloadData() } } // MARK:- Additional handlers extension EditController { func handleDatePicker(sender: UIDatePicker) { let formatter = DateFormatter() formatter.dateFormat = "dd.MM.yyyy" birthdayText = formatter.string(from: sender.date) if birthdayText != userDefault.value(forKey: birthdayKey) as? String { isChanged = true } else { isChanged = false } tableView.reloadData() } func backButton(sender: UIBarButtonItem) { if isChanged { let title = "Предупреждение" let message = "Данные были изменены. Вы желаете сохранить изменения, в противном случае внесенные правки будут отменены." let titleSave = "Сохранить" let titleSkip = "Пропустить" let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) let alertSave = UIAlertAction(title: titleSave, style: .default, handler: { [weak self] (action) in guard let sself = self else { return } sself.saveContent() _ = sself.navigationController?.popViewController(animated: true) }) let alertSkip = UIAlertAction(title: titleSkip, style: .default, handler: { [weak self] (action) in guard let sself = self else { return } _ = sself.navigationController?.popViewController(animated: true) }) alertController.addAction(alertSave) alertController.addAction(alertSkip) self.present(alertController, animated: true, completion: nil) isChanged = false } else { _ = navigationController?.popViewController(animated: true) } textViewResponders() } fileprivate func toggleDatePickerForSelectedIndexPath(indexPath: IndexPath) { tableView.beginUpdates() var indexRow = indexPath.row if !isExistIndexPathDatePicker { indexRow += 1 } else { indexRow -= 1 } let index = [IndexPath(row: indexRow, section: 0)] if (datePickerIndexPath != nil) { tableView.deleteRows(at: index, with: .fade) datePickerIndexPath = nil } else { tableView.insertRows(at: index, with: .fade) datePickerIndexPath = IndexPath(row: indexPath.row + 1, section: 0) } tableView.endUpdates() } fileprivate func togglePickerViewForSelectedIndexPath(indexPath: IndexPath) { tableView.beginUpdates() var indexRow = indexPath.row if isExistIndexPathDatePicker { indexRow += 1 } let index = [IndexPath(row: indexRow, section: 0)] if (pickerViewIndexPath != nil) { tableView.deleteRows(at: index, with: .fade) pickerViewIndexPath = nil } else { tableView.insertRows(at: index, with: .fade) pickerViewIndexPath = IndexPath(row: indexPath.row + 1, section: 0) } tableView.endUpdates() } fileprivate var isExistIndexPathDatePicker: Bool { return (datePickerIndexPath != nil) } fileprivate var isExistIndexPathPickerView: Bool { return (pickerViewIndexPath != nil) } } // MARK:- ConfigureCell extension EditController { func configureFirstNameCell(cell: FullNameCell, indexPath: IndexPath) { cell.textView.delegate = self firstNameTextView = cell.textView cell.textView.tag = 1 if firstNameText != "" { cell.textView.text = firstNameText } else { cell.textView.text = userDefault.value(forKey: firstNameKey) as? String } } func configureLastNameCell(cell: FullNameCell, indexPath: IndexPath) { cell.textView.delegate = self lastNameTextView = cell.textView cell.textView.tag = 2 if lastNameText != "" { cell.textView.text = lastNameText } else { cell.textView.text = userDefault.value(forKey: lastNameKey) as? String } } func configurePatronymicCell(cell: FullNameCell, indexPath: IndexPath) { cell.textView.delegate = self patronymicTextView = cell.textView cell.textView.tag = 3 if patronymicText != "" { cell.textView.text = patronymicText } else { cell.textView.text = userDefault.value(forKey: patronymicKey) as? String } } func configureBirthdayCell(cell: CommonCell, indexPath: IndexPath) { birthdayCell = cell cell.titleLabel.text = dataArray[indexPath.row] if let text = birthdayText { cell.titleTextLabel.text = text } else { cell.titleTextLabel.text = userDefault.value(forKey: birthdayKey) as? String } } func configureGenderCell(cell: CommonCell, indexPath: IndexPath) { var index = indexPath.row if isExistIndexPathDatePicker { index -= 1 } cell.titleLabel.text = dataArray[index] if let text = genderText { cell.titleTextLabel.text = text } else { cell.titleTextLabel.text = userDefault.value(forKey: genderKey) as? String } } } // MARK:- UIPickerViewDelegate, UIPickerViewDataSource extension EditController: UIPickerViewDelegate, UIPickerViewDataSource { func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return 3 } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return pickerArr[row] } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { genderText = pickerArr[row] if genderText != userDefault.value(forKey: genderKey) as? String { isChanged = true } else { isChanged = false } tableView.reloadData() } } // MARK:- UITextViewDelegate extension EditController: UITextViewDelegate { func textViewShouldBeginEditing(_ textView: UITextView) -> Bool { view.addGestureRecognizer(tap!) return true } func textViewDidChange(_ textView: UITextView) { let currentOffset = tableView.contentOffset UIView.setAnimationsEnabled(false) tableView.beginUpdates() tableView.endUpdates() UIView.setAnimationsEnabled(true) tableView.contentOffset = currentOffset let firstName = userDefault.value(forKey: firstNameKey) ?? "Error" let lastName = userDefault.value(forKey: lastNameKey) ?? "Error" let patronymic = userDefault.value(forKey: patronymicKey) ?? "Error" switch textView.text { case firstName as! String: isChanged = false case lastName as! String: isChanged = false case patronymic as! String: isChanged = false default: isChanged = true } switch textView.tag { case 1: firstNameText = textView.text case 2: lastNameText = textView.text case 3: patronymicText = textView.text default: break } } } // MARK:- ViewControllerProtocol extension EditController: ViewControllerProtocol { static func storyBoardName() -> String { return "Main" } }
// // HomeViewModel.swift // BitTicker // // Created by Levin varghese on 06/06/20. // Copyright © 2020 Levin Varghese. All rights reserved. // import Foundation import Combine enum HomeState { case loading case subscriptionData(TickerData) case failure(Error) } class HomeViewModelInput { /// called when the user action is performed var viewLoaded: AnyPublisher<Void, Never>? = nil var userSelection: AnyPublisher<TickerData, Never>? = nil } typealias HomeViewModelOutput = AnyPublisher <HomeState, Never> protocol HomeViewModelType { func transform(input: HomeViewModelInput) -> HomeViewModelOutput } final class HomeViewModel: HomeViewModelType { let useCase: TickerUserCasetype private let navigator: LoginNavigator private var cancellables: [AnyCancellable] = [] init(useCase: TickerUserCasetype, navigator: LoginNavigator) { self.useCase = useCase self.navigator = navigator } func transform(input: HomeViewModelInput) -> HomeViewModelOutput { cancellables.forEach { $0.cancel() } cancellables.removeAll() input.userSelection? .receive(on: DispatchQueue.main) .sink(receiveValue: {[unowned self] in self.navigator.goToDetail($0)}) .store(in: &cancellables) let showLoading = input.viewLoaded!.flatMap({ (Void) -> HomeViewModelOutput in let pub: HomeViewModelOutput = .just(HomeState.loading) return pub }).receive(on: DispatchQueue.main) .eraseToAnyPublisher() let subscrptionResult = input.viewLoaded!.flatMapLatest { (Void) -> HomeViewModelOutput in return self.useCase.subscribeTicker() .map({HomeState.subscriptionData($0)}) .catch {Just(HomeState.failure($0)).eraseToAnyPublisher()} .eraseToAnyPublisher() } return Publishers.Merge(showLoading, subscrptionResult).eraseToAnyPublisher() } }
// // CharacterRowView.swift // RickAndMortySwiftUI // // Created by Edgar Luis Diaz on 26/09/2019. // Copyright © 2019 Edgar. All rights reserved. // import SwiftUI struct CharacterRowView: View { private let uiModel: UIModel init(_ uiModel: UIModel) { self.uiModel = uiModel } var body: some View { Text(uiModel.name) } } extension CharacterRowView { struct UIModel: Identifiable { var id: Int var name: String } }
// // MapViewController.swift // GauchoBack // // Created by Carson Holoien on 4/19/16. // Copyright © 2016 CS48 Group2. All rights reserved. // import UIKit import GoogleMaps var allNearbyEvents:[Event]! var currentLongitude: String! var currentLattitude: String! class MapViewController: UIViewController, CLLocationManagerDelegate, GMSMapViewDelegate { var locationManager = CLLocationManager() var userLocation = CLLocation() var markersPlaced = false var cam:GMSCameraPosition! = nil var viewLoaded = false var nearbyEvents:[Event]! = nil var firebaseAdapter:FirebaseAdapter! var eventMarker:Event! @IBOutlet var mapView: GMSMapView! override func viewDidLoad() { super.viewDidLoad() allNearbyEvents = nil viewLoaded = true locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.requestWhenInUseAuthorization() locationManager.requestAlwaysAuthorization() locationManager.startUpdatingLocation() mapView.delegate = self mapView.settings.myLocationButton = true mapView.accessibilityElementsHidden = false mapView.myLocationEnabled = true userLocation = CLLocation(latitude: 34.4140, longitude: -119.8489) cam = GMSCameraPosition.cameraWithTarget(userLocation.coordinate, zoom: 18) mapView.camera = cam let uid = NSUserDefaults.standardUserDefaults().objectForKey("uid") firebaseAdapter = FirebaseAdapter() if firebaseAdapter.loggedIn() { firebaseAdapter.getSubscribedEvents() print(uid as! String) } else { print("This is view-only") } } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) //markersPlaced = false if(currentLongitude != nil && currentLattitude != nil){ firebaseAdapter.getNearbyEvents(currentLongitude, currentLatitude: currentLattitude, maxDistance: maxDistance) } if firebaseAdapter.loggedIn() { firebaseAdapter.myEvents() } } func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { if viewLoaded{ userLocation = locations[0] cam = GMSCameraPosition.cameraWithTarget(userLocation.coordinate, zoom: 18) mapView.camera = cam firebaseAdapter.getNearbyEvents(String(userLocation.coordinate.longitude), currentLatitude: String(userLocation.coordinate.latitude), maxDistance: maxDistance) currentLongitude = String(userLocation.coordinate.longitude) currentLattitude = String(userLocation.coordinate.latitude) viewLoaded = false } if (allNearbyEvents != nil && markersPlaced == false){ for singleEvent in allNearbyEvents { let marker = GMSMarker() marker.map = mapView marker.position = CLLocationCoordinate2D(latitude: CLLocationDegrees(singleEvent.latitude)!, longitude: CLLocationDegrees(singleEvent.longitude)!) marker.snippet = singleEvent.eventName marker.appearAnimation = kGMSMarkerAnimationPop marker.userData = singleEvent if(singleEvent.eventType == "warning"){ marker.icon = GMSMarker.markerImageWithColor(UIColor.redColor()) } else if(singleEvent.eventType == "event"){ marker.icon = GMSMarker.markerImageWithColor(UIColor.blueColor()) } else{ marker.icon = GMSMarker.markerImageWithColor(UIColor.yellowColor()) } } markersPlaced = true } if viewLoaded == false{ var longitudeDelta = (Double(String(locations[0].coordinate.longitude))! - Double(userLocation.coordinate.longitude)) as Double! var latitudeDelta = (Double(locations[0].coordinate.latitude) - Double(userLocation.coordinate.latitude)) as Double! longitudeDelta = abs(longitudeDelta!) as Double! latitudeDelta = abs(latitudeDelta!) as Double! let distanceAway = sqrt((longitudeDelta * longitudeDelta) + (latitudeDelta * latitudeDelta)) if (distanceAway >= 1.0){ viewLoaded = true markersPlaced = false allNearbyEvents = nil } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func mapView(mapView: GMSMapView, didTapInfoWindowOfMarker marker: GMSMarker) { if(marker.userData == nil){ print("nil") } eventMarker = marker.userData as! Event? print(eventMarker.eventName) print("didTapInfoWindow") performSegueWithIdentifier("eventSegue", sender: self) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if(segue.identifier == "eventSegue"){ let yourNextViewController = (segue.destinationViewController as! EventDetailViewController) yourNextViewController.theEvent = eventMarker print("Performing Segue") } } /* // 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. } */ @IBAction func backToLoginAction(sender: AnyObject) { performSegueWithIdentifier("backToLoginSegue", sender: self) } }
// // URLComponentsExtension.swift // NetworkLayer // // Created by Marcin Jackowski on 06/09/2018. // Copyright © 2018 CocoApps. All rights reserved. // import Foundation private extension String { var encodedPlusSign: String { var queryCharSet = NSCharacterSet.urlQueryAllowed queryCharSet.remove(charactersIn: "+") return self.addingPercentEncoding(withAllowedCharacters: queryCharSet)! } } extension URLComponents { mutating func percentingEncodedPlusSign() { percentEncodedQuery = percentEncodedQuery?.replacingOccurrences(of: "+", with: "%2B") } init(service: ServiceProtocol) { let url = service.baseURL.appendingPathComponent(service.path) self.init(url: url, resolvingAgainstBaseURL: false)! guard case let .requestParameters(parameters) = service.task, service.parametersEncoding == .url else { return } queryItems = parameters.map { key, value in return URLQueryItem(name: key, value: String(describing: value)) } if service.supportsRFC3986 == false { percentingEncodedPlusSign() } } }
// // isKeyboardExtensionEnabled.swift // KeyboardKit // // Created by Valentin Shergin on 5/16/16. // Copyright © 2016 AnchorFree. All rights reserved. // import Foundation public func isKeyboardExtensionEnabled() -> Bool { guard let appBundleIdentifier = NSBundle.mainBundle().bundleIdentifier else { fatalError("isKeyboardExtensionEnabled(): Cannot retrieve bundle identifier.") } guard let keyboards = NSUserDefaults.standardUserDefaults().dictionaryRepresentation()["AppleKeyboards"] as? [String] else { // There is no key `AppleKeyboards` in NSUserDefaults. That happens sometimes. return false } let keyboardExtensionBundleIdentifierPrefix = appBundleIdentifier + "." for keyboard in keyboards { if keyboard.hasPrefix(keyboardExtensionBundleIdentifierPrefix) { return true } } return false }
// // quizBrain.swift // QuizApp // // Created by Aarish Rahman on 13/03/21. // import Foundation struct QuizBrain { let quiz = [["What jutsu did Itachi used on Kabuto to stop the reanimation jutsu","tsukiyomi","susano","Izanagi","Izanami"], ["which clan tobirama hates","Nara","Akimichi","Uzumaki","Uchiha"], ["What is the name of Two Tales Beast","Kurama","Izumi","Matatabi","Shukaku"], ["Who invented Rasengan?","Jiraiya","Naruto","Minato","Tobirama"]] var questionNumber = 0 }
// // BasePostsViewController.swift // inksell // // Created by Abhinav Gupta on 06/03/16. // Copyright © 2016 inksell. All rights reserved. // import Foundation import UIKit class BasePostsViewController : BaseTableViewController { @IBOutlet weak var EmailButton: UIButton! @IBOutlet weak var CallButton: UIButton! var postSummaryEntity : PostSummaryEntity? var postEntity : IPostEntity? var categoryType : CategoryType? override func initTableController() { self.postSummaryEntity = AppData.passedObject as? PostSummaryEntity categoryType = CategoryType(rawValue: (self.postSummaryEntity?.categoryid)!) var headerViewCell = ViewPostsViewType.HeaderViewCell.rawValue if(self.postSummaryEntity?.HasPostTitlePic == true) { headerViewCell = ViewPostsViewType.ImagesHeaderViewCell.rawValue } var bodyViewCell = ViewPostsViewType.CommonViewCell.rawValue if(categoryType == CategoryType.RealEstate) { bodyViewCell = ViewPostsViewType.RealEstateViewCell.rawValue } self.tableViewCellIdentifier = [headerViewCell, bodyViewCell] if(categoryType == CategoryType.RealEstate) { self.tableViewCellIdentifier.append(ViewPostsViewType.MapViewCell.rawValue) } self.tableViewCellIdentifier.append(ViewPostsViewType.ContactsViewCell.rawValue) self.items = self.tableViewCellIdentifier tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 100 } override func viewDidAppear(animated: Bool) { getPostEntity() } func getPostEntity() { RestClient.get.getFullPostEntity((self.postSummaryEntity?.PostId)!, categoryType: categoryType!, callback: InksellCallback<IPostEntity>(success: { entity in self.postEntity = entity; let cells = self.tableView.visibleCells for cell in cells { let cell = cell as! BaseViewPostCell cell.initData(self.postSummaryEntity!, postEntity: entity!, viewController: self) } } , failure: {responseStatus in })); } override func getTableCell(indexPath : NSIndexPath) -> UITableViewCell{ let view = tableView.dequeueReusableCellWithIdentifier(tableViewCellIdentifier[indexPath.row], forIndexPath: indexPath) as! BaseViewPostCell if(postEntity != nil) { view.initData(self.postSummaryEntity!, postEntity: postEntity!, viewController: self) } view.contentView.setNeedsLayout() view.contentView.layoutIfNeeded() return view } }
// // ConnectionState.swift // SignalR-Swift // // // Copyright © 2017 Jordan Camara. All rights reserved. // import Foundation public enum ConnectionState : Int { case connecting case connected case reconnecting case disconnected public func description() -> String { switch self { case .connecting: return "Connecting" case .connected: return "Connected" case .reconnecting: return "Reconnecting" case .disconnected: return "Disconnected" } } }
// // TabBarBuilder.swift // Slidecoin // // Created by Oleg Samoylov on 27.12.2019. // Copyright © 2019 Oleg Samoylov. All rights reserved. // import UIKit final class TabBarBuilder: UISplitViewControllerDelegate { static func build(login: Login, user: User) -> UITabBarController { Global.accessToken = login.accessToken Global.refreshToken = login.refreshToken let mainSvc = self.mainSvc(user: user) let usersSvc = self.usersSvc(user: user) let storeSvc = self.storeSvc(user: user) let tabBarController = UITabBarController() tabBarController.viewControllers = [mainSvc, usersSvc, storeSvc] return tabBarController } // MARK: Private private static func mainSvc(user: User) -> UISplitViewController { let mainVc = MainViewController(user: user) let mainNvc = UINavigationController(rootViewController: mainVc) let transactionsVc = TransactionsViewController(user: user) let transactionsNvc = UINavigationController(rootViewController: transactionsVc) let mainSvc = UISplitViewController() mainSvc.delegate = mainVc mainSvc.preferredDisplayMode = .allVisible mainSvc.viewControllers = [mainNvc, transactionsNvc] let mainImage = UIImage(systemName: "house") let mainSelectedImage = UIImage(systemName: "house.fill") mainSvc.tabBarItem = UITabBarItem(title: "Главная", image: mainImage, selectedImage: mainSelectedImage) return mainSvc } private static func usersSvc(user: User) -> UISplitViewController { let usersVc = UsersViewController(currentUser: user) let usersNvc = UINavigationController(rootViewController: usersVc) let userVc = NoUserViewController("пользовател") let usersSvc = UISplitViewController() usersSvc.delegate = usersVc usersSvc.preferredDisplayMode = .allVisible usersSvc.viewControllers = [usersNvc, userVc] let usersImage = UIImage(systemName: "person.3") let usersSelectedImage = UIImage(systemName: "person.3.fill") usersSvc.tabBarItem = UITabBarItem(title: "Пользователи", image: usersImage, selectedImage: usersSelectedImage) return usersSvc } private static func storeSvc(user: User) -> UISplitViewController { let storeVc = StoreViewController(user: user) let storeNvc = UINavigationController(rootViewController: storeVc) let userVc = NoUserViewController("товар") let storeSvc = UISplitViewController() storeSvc.delegate = storeVc storeSvc.preferredDisplayMode = .allVisible storeSvc.viewControllers = [storeNvc, userVc] let storeImage = UIImage(systemName: "bag") let storeSelectedImage = UIImage(systemName: "bag.fill") storeSvc.tabBarItem = UITabBarItem(title: "Магазин", image: storeImage, selectedImage: storeSelectedImage) return storeSvc } }
import Foundation import CoreData extension Animals { @nonobjc public class func fetchRequest() -> NSFetchRequest<Animals> { return NSFetchRequest<Animals>(entityName: "Animals") } @NSManaged public var title: String? @NSManaged public var creator: String? @NSManaged public var thumbnail: NSData? @NSManaged public var type: String? @NSManaged public var image: Images? }
// // GooglePlacesAutocompleteApi.swift // GooglePlacesSearch // // Created by Himanshi Bhardwaj on 8/28/17. // Copyright © 2017 Himanshi Bhardwaj. All rights reserved. // // parts of code taken/inspired from https://github.com/watsonbox/ios_google_places_autocomplete import Foundation open class GooglePlacesAutocompleteApi { //-------------------------------------- // MARK: Variables //-------------------------------------- private let apiKey = GooglePlaceAutoCompleteData.apiKey private let placeType = GooglePlaceAutoCompleteData.placeType private var placesFound: [Place] = [] private var errorInfindingPlaces : String = "" private var places = [Place]() //-------------------------------------- // MARK: Functions //-------------------------------------- open func getPlaces(_ searchString: String, completion: @escaping (([Place]?, Error?) -> Void)) { let params = ["input": searchString, "types": placeType.description, "key": apiKey] if (searchString == ""){ let error = NSError(domain: "GooglePlacesAutocompleteErrorDomain" , code: 1000, userInfo: [NSLocalizedDescriptionKey:"No search string given"]) completion(nil,error) return } GooglePlacesRequest.doRequest(GooglePlaceAutoCompleteData.httpURLDetails, params: params) { json, error in if let json = json { if let predictions = json["predictions"] as? Array<[String: Any]> { self.places = predictions.map { (prediction: [String: Any]) -> Place in return Place(prediction: prediction, apiKey: self.apiKey) } completion(self.places, error) self.placesFound = self.places } else { completion(nil, error) } } else { completion(nil,error) } } } }
// // NotificationManager.swift // CoreBluetoothExample // // Created by SaitoYuta on 2017/03/16. // Copyright © 2017年 bangohan. All rights reserved. // import Foundation import Cocoa class NotificationManager { static func show(text: String) { let notification = NSUserNotification() notification.title = "Wii Remote" notification.subtitle = text NSUserNotificationCenter.default.deliver(notification) } }
import CoreFoundation import Foundation import UIKit extension UIView{ var width: CGFloat { return frame.size.width } var height: CGFloat { return frame.size.height } var size: CGSize { return frame.size} var origin: CGPoint { return frame.origin } var x: CGFloat { return frame.origin.x } var y: CGFloat { return frame.origin.y } var centerX: CGFloat { return center.x } var centerY: CGFloat { return center.y } var left: CGFloat { return frame.origin.x } var right: CGFloat { return frame.origin.x + frame.size.width } var top: CGFloat { return frame.origin.y } var bottom: CGFloat { return frame.origin.y + frame.size.height } func setWidth(width:CGFloat) { frame.size.width = width } func setHeight(height:CGFloat) { frame.size.height = height } func setSize(size:CGSize) { frame.size = size } func setOrigin(point:CGPoint) { frame.origin = point } func setOriginX(x:CGFloat) { frame.origin = CGPointMake(x, frame.origin.y) } func setOriginY(y:CGFloat) { frame.origin = CGPointMake(frame.origin.x, y) } func setCenterX(x:CGFloat) { center = CGPointMake(x, center.y) } func setCenterY(y:CGFloat) { center = CGPointMake(center.x, y) } func roundCorner(radius:CGFloat) { layer.cornerRadius = radius } func setTop(top:CGFloat) { frame.origin.y = top } func setLeft(left:CGFloat) { frame.origin.x = left } func setRight(right:CGFloat) { frame.origin.x = right - frame.size.width } func setBottom(bottom:CGFloat) { frame.origin.y = bottom - frame.size.height } @IBInspectable var cornerRadius: CGFloat { get { return layer.cornerRadius } set { layer.cornerRadius = newValue layer.masksToBounds = newValue > 0 } } @IBInspectable var borderWidth: CGFloat { get { return layer.borderWidth } set { layer.borderWidth = newValue } } @IBInspectable var borderColor: UIColor? { get { return UIColor(CGColor: layer.borderColor) } set { layer.borderColor = newValue?.CGColor } } }
import UIKit import ThemeKit import SectionsTableView import SnapKit import RxSwift import RxCocoa import ComponentKit import ActionSheet class SwitchAccountViewController: ThemeActionSheetController { private let viewModel: SwitchAccountViewModel private let disposeBag = DisposeBag() private let titleView = BottomSheetTitleView() private let tableView = SelfSizedSectionsTableView(style: .plain) init(viewModel: SwitchAccountViewModel) { self.viewModel = viewModel super.init() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() view.addSubview(titleView) titleView.snp.makeConstraints { maker in maker.leading.top.trailing.equalToSuperview() } titleView.bind( image: .local(image: UIImage(named: "switch_wallet_24")?.withTintColor(.themeJacob)), title: "switch_account.title".localized, viewController: self ) view.addSubview(tableView) tableView.snp.makeConstraints { maker in maker.leading.trailing.equalToSuperview() maker.top.equalTo(titleView.snp.bottom).offset(CGFloat.margin12) maker.bottom.equalToSuperview() } if #available(iOS 15.0, *) { tableView.sectionHeaderTopPadding = 0 } tableView.sectionDataSource = self tableView.buildSections() subscribe(disposeBag, viewModel.finishSignal) { [weak self] in self?.dismiss(animated: true) } } } extension SwitchAccountViewController: SectionsDataSource { private func row(viewItem: SwitchAccountViewModel.ViewItem, watchIcon: Bool, index: Int, isFirst: Bool, isLast: Bool) -> RowProtocol { CellBuilderNew.row( rootElement: .hStack([ .image24 { component in component.imageView.image = viewItem.selected ? UIImage(named: "circle_radioon_24")?.withTintColor(.themeJacob) : UIImage(named: "circle_radiooff_24")?.withTintColor(.themeGray) }, .vStackCentered([ .text { component in component.font = .body component.textColor = .themeLeah component.text = viewItem.title }, .margin(1), .text { component in component.font = .subhead2 component.textColor = .themeGray component.text = viewItem.subtitle } ]), .image20 { component in component.isHidden = !watchIcon component.imageView.image = UIImage(named: "binocule_20")?.withTintColor(.themeGray) } ]), tableView: tableView, id: "item_\(index)", height: .heightDoubleLineCell, bind: { cell in cell.set(backgroundStyle: .bordered, isFirst: isFirst, isLast: isLast) }, action: { [weak self] in self?.viewModel.onSelect(accountId: viewItem.accountId) } ) } func buildSections() -> [SectionProtocol] { var sections = [SectionProtocol]() if !viewModel.regularViewItems.isEmpty { let section = Section( id: "regular", headerState: tableView.sectionHeader(text: "switch_account.wallets".localized, backgroundColor: .themeLawrence), footerState: .marginColor(height: .margin24, color: .clear), rows: viewModel.regularViewItems.enumerated().map { index, viewItem in row(viewItem: viewItem, watchIcon: false, index: index, isFirst: index == 0, isLast: index == viewModel.regularViewItems.count - 1) } ) sections.append(section) } if !viewModel.watchViewItems.isEmpty { let section = Section( id: "watch", headerState: tableView.sectionHeader(text: "switch_account.watch_wallets".localized, backgroundColor: .themeLawrence), footerState: .marginColor(height: .margin24, color: .clear), rows: viewModel.watchViewItems.enumerated().map { index, viewItem in row(viewItem: viewItem, watchIcon: true, index: index, isFirst: index == 0, isLast: index == viewModel.watchViewItems.count - 1) } ) sections.append(section) } return sections } }
// // NotificationObserver.swift // Habit-Calendar // // Created by Tiago Maia Lopes on 15/09/18. // Copyright © 2018 Tiago Maia Lopes. All rights reserved. // import Foundation /// The interface to register/unregister to notifications from the NotificationCenter api. @objc protocol NotificationObserver { /// Starts observing notifications from the NotificationCenter. func startObserving() /// Stops observing notifications from the NotificationCenter. func stopObserving() } /// Observer for the UIApplicationDidBecomeActive notification. @objc protocol AppActiveObserver: NotificationObserver { /// Handles the UIApplicationDidBecomeActive notification. @objc func handleActivationEvent(_ notification: Notification) }
// // CoronaGeoElement.swift // CoronaGotUs // // Created by Karim Alweheshy on 11/25/20. // import Foundation struct CoronaGeoElement: Codable, Equatable { let id: Int let casesPer100k: Double let type: String let cases7Per100k: Double let casesPerPopulation: Double let deaths: Int let cases: Int let stateName: String let regionName: String let deathRate: Double let county: String enum CodingKeys: String, CodingKey { case casesPer100k = "cases_per_100k" case type = "BEZ" case cases7Per100k = "cases7_per_100k" case casesPerPopulation = "cases_per_population" case deaths = "deaths" case cases = "cases" case stateName = "BL" case regionName = "GEN" case id = "OBJECTID" case deathRate = "death_rate" case county = "county" } }
// // MainView.swift // StetsonScene // // Created by Madison Gipson on 2/5/20. // Copyright © 2020 Madison Gipson. All rights reserved. // import Foundation import SwiftUI import UIKit struct ARNavigationIndicator: UIViewControllerRepresentable { @ObservedObject var evm:EventViewModel typealias UIViewControllerType = ARView @EnvironmentObject var config: Configuration var arFindMode: Bool var navToEvent: EventInstance? @Binding var internalAlert: Bool @Binding var externalAlert: Bool @Binding var tooFar: Bool @Binding var allVirtual: Bool @Binding var arrived: Bool @Binding var eventDetails: Bool @Binding var page:String @Binding var subPage:String func makeUIViewController(context: Context) -> ARView { return ARView(evm: self.evm, config: self.config, arFindMode: self.arFindMode, navToEvent: self.navToEvent ?? EventInstance(), internalAlert: self.$internalAlert, externalAlert: self.$externalAlert, tooFar: self.$tooFar, allVirtual: self.$allVirtual, arrived: self.$arrived, eventDetails: self.$eventDetails, page: self.$page, subPage: self.$subPage) } func updateUIViewController(_ uiViewController: ARNavigationIndicator.UIViewControllerType, context: UIViewControllerRepresentableContext<ARNavigationIndicator>) { } } struct ActivityIndicator: UIViewRepresentable { //loading wheel let color:UIColor //let brightYellow = UIColor(red: 255/255, green: 196/255, blue: 0/255, alpha: 1.0) @Binding var isAnimating: Bool let style: UIActivityIndicatorView.Style func makeUIView(context: UIViewRepresentableContext<ActivityIndicator>) -> UIActivityIndicatorView { let activityIndicator = UIActivityIndicatorView(style: style) activityIndicator.color = color return activityIndicator//UIActivityIndicatorView(style: style) } func updateUIView(_ uiView: UIActivityIndicatorView, context: UIViewRepresentableContext<ActivityIndicator>) { isAnimating ? uiView.startAnimating() : uiView.stopAnimating() } } struct MainView : View { @ObservedObject var evm:EventViewModel @EnvironmentObject var config: Configuration @Environment(\.colorScheme) var colorScheme @State var listVirtualEvents:Bool = false @State var noFavorites: Bool = false @State var showOptions: Bool = false //for alerts @State var externalAlert: Bool = false @State var tooFar: Bool = false @State var allVirtual: Bool = true @State var page:String = "Discover" //Discover, Favorites, Trending, Information @State var subPage:String = "List" //List, Calendar, AR, Map var body: some View { ZStack { Color((self.page == "Favorites" && colorScheme == .light) ? config.accentUIColor : UIColor.secondarySystemBackground).edgesIgnoringSafeArea(.all) VStack(spacing: 0) { ZStack { if self.page == "Trending" { TrendingView(evm: self.evm, page: self.$page, subPage: self.$subPage) } if self.page == "Discover" || self.page == "Favorites" { if self.subPage == "List" { VStack { DiscoverFavoritesView(evm: self.evm, page: self.$page, subPage: self.$subPage) //IF IT'S FAVORITES PAGE BUT THERE AREN'T ANY FAVORITES if self.page == "Favorites" && !evm.doFavoritesExist(list: self.evm.eventList) { VStack(alignment: .leading, spacing: 10) { Text("No Events Favorited").fontWeight(.light).font(.system(size: 16)).padding([.horizontal]).foregroundColor((self.page == "Favorites" && colorScheme == .light) ? Color.tertiarySystemBackground : Color.label) Text("Add some events to your favorites by using the hard-press shortcut on the event preview or the favorite button on the event detail page.").fontWeight(.light).font(.system(size: 16)).padding([.horizontal]).foregroundColor((self.page == "Favorites" && colorScheme == .light) ? Color.tertiarySystemBackground : Color.label) Spacer() Spacer() }.padding(.vertical, 10) } else { if self.evm.dataReturnedFromSnapshot { ListView(evm: self.evm, page: self.$page, subPage: self.$subPage) } else { Spacer() ActivityIndicator(color: config.accentUIColor ,isAnimating: .constant(true), style: .large) Spacer() } } }.blur(radius: self.showOptions ? 5 : 0).disabled(self.showOptions ? true : false) } if self.subPage == "Calendar" { VStack { DiscoverFavoritesView(evm: self.evm, page: self.$page, subPage: self.$subPage) //IF IT'S FAVORITES PAGE BUT THERE AREN'T ANY FAVORITES if self.page == "Favorites" && !evm.doFavoritesExist(list: self.evm.eventList) { VStack(alignment: .leading, spacing: 10) { Text("No Events Favorited").fontWeight(.light).font(.system(size: 16)).padding([.horizontal]).foregroundColor((self.page == "Favorites" && colorScheme == .light) ? Color.tertiarySystemBackground : Color.label) Text("Add some events to your favorites by using the hard-press shortcut on the event preview or the favorite button on the event detail page.").fontWeight(.light).font(.system(size: 16)).padding([.horizontal]).foregroundColor((self.page == "Favorites" && colorScheme == .light) ? Color.tertiarySystemBackground : Color.label) Spacer() Spacer() }.padding(.vertical, 10) } else { CalendarView(evm: self.evm, page: self.$page, subPage: self.$subPage) } }.blur(radius: self.showOptions ? 5 : 0).disabled(self.showOptions ? true : false) } if self.subPage == "AR" || self.subPage == "Map" { //AR or Map ZStack { if self.subPage == "AR" { ARNavigationIndicator(evm: self.evm, arFindMode: true, internalAlert: .constant(false), externalAlert: self.$externalAlert, tooFar: self.$tooFar, allVirtual: self.$allVirtual, arrived: .constant(false), eventDetails: .constant(false), page: self.$page, subPage: self.$subPage).environmentObject(self.config) .blur(radius: self.showOptions ? 5 : 0) .disabled(self.showOptions ? true : false) .edgesIgnoringSafeArea(.top) .alert(isPresented: self.$externalAlert) { () -> Alert in if self.tooFar { return self.evm.alert(title: "Too Far to Tour with AR", message: "You're currently too far away from campus to use the AR feature to tour. Try using the map instead.") } else if self.allVirtual { if self.page == "Favorites" { return self.evm.alert(title: "All Favorited Events are Virtual", message: "Unfortunately, there are no events in your favorites list that are on campus at the moment. Check out the virtual event list instead.") } else { return self.evm.alert(title: "All Events are Virtual", message: "Unfortunately, there are no events on campus at the moment. Check out the virtual event list instead.") } } else if self.page == "Favorites" && self.noFavorites { return self.evm.alert(title: "No Favorites to Show", message: "Add some favorites so we can show you them in \(self.subPage) Mode!") } return self.evm.alert(title: "ERROR", message: "Please report as a bug.") } } if self.subPage == "Map" { MapView(evm: self.evm, mapFindMode: true, internalAlert: .constant(false), externalAlert: self.$externalAlert, tooFar: .constant(false), allVirtual: self.$allVirtual, arrived: .constant(false), eventDetails: .constant(false), page: self.$page, subPage: self.$subPage).environmentObject(self.config) .blur(radius: self.showOptions ? 5 : 0) .disabled(self.showOptions ? true : false) .edgesIgnoringSafeArea(.top) .alert(isPresented: self.self.$externalAlert) { () -> Alert in if self.allVirtual { return self.evm.alert(title: "All Events are Virtual", message: "Unfortunately, there are no events on campus at the moment. Check out the virtual event list instead.") } else if self.page == "Favorites" && self.noFavorites { return self.evm.alert(title: "No Favorites to Show", message: "Add some favorites so we can show you them in \(self.subPage) Mode!") } return self.evm.alert(title: "ERROR", message: "Please report as a bug.") } } if config.appEventMode { ZStack { Text("Virtual Events").fontWeight(.light).font(.system(size: 18)).foregroundColor(config.accent) }.padding(10) .background(RoundedRectangle(cornerRadius: 15).stroke(Color.clear).foregroundColor(Color.tertiarySystemBackground.opacity(0.8)).background(RoundedRectangle(cornerRadius: 10).foregroundColor(Color.tertiarySystemBackground.opacity(0.8)))) .onTapGesture { withAnimation { self.listVirtualEvents = true } } .offset(y: Constants.height*0.38) } }.sheet(isPresented: $listVirtualEvents, content: { ListView(evm: self.evm, allVirtual: true, page: self.$page, subPage: self.$subPage).environmentObject(self.config).background(Color.secondarySystemBackground) }) // .alert(isPresented: self.$noFavorites) { () -> Alert in //if favorites map or favorites AR & there are no favorites // return self.evm.alert(title: "No Favorites to Show", message: "Add some favorites so we can show you them in \(self.subPage) Mode!") // } //end of ZStack } } if self.page == "Information" { InformationView() } //JUST FOR TOUR MODE WITH BUILDINGS if self.page == "AR" { ARNavigationIndicator(evm: self.evm, arFindMode: true, internalAlert: .constant(false), externalAlert: self.$externalAlert, tooFar: self.$tooFar, allVirtual: .constant(false), arrived: .constant(false), eventDetails: .constant(false), page: self.$page, subPage: self.$subPage).environmentObject(self.config) .blur(radius: self.showOptions ? 5 : 0) .disabled(self.showOptions ? true : false) .edgesIgnoringSafeArea(.top) .alert(isPresented: self.$externalAlert) { () -> Alert in if self.tooFar { return self.evm.alert(title: "Too Far to Tour with AR", message: "You're currently too far away from campus to use the AR feature to tour. Try using the map instead.") } return self.evm.alert(title: "ERROR", message: "Please report as a bug.") } } if self.page == "Map" { MapView(evm: self.evm, mapFindMode: true, internalAlert: .constant(false), externalAlert: .constant(false), tooFar: .constant(false), allVirtual: .constant(false), arrived: .constant(false), eventDetails: .constant(false), page: self.$page, subPage: self.$subPage).environmentObject(self.config) .blur(radius: self.showOptions ? 5 : 0) .disabled(self.showOptions ? true : false) .edgesIgnoringSafeArea(.top) } }//.onTapGesture { self.showOptions = false } //end of ZStack that holds everything above the tab bar //interferes with tapping on map pin, figure this out later TabBar(evm: self.evm, showOptions: self.$showOptions, externalAlert: self.$externalAlert, noFavorites: self.$noFavorites, page: self.$page, subPage: self.$subPage).padding(.bottom, Constants.height < 700 ? 0 : 10) }.edgesIgnoringSafeArea(.bottom)//end of VStack }.animation(.spring()) //end of ZStack } //end of view } //end of struct struct TabBar : View { @ObservedObject var evm:EventViewModel @EnvironmentObject var config: Configuration @Binding var showOptions: Bool @Binding var externalAlert: Bool @Binding var noFavorites: Bool @Binding var page:String @Binding var subPage:String var body: some View { ZStack { HStack(spacing: 20){ if config.appEventMode { //Discover HStack { Image(systemName: "magnifyingglass").resizable().frame(width: 20, height: 20).foregroundColor(self.page == "Discover" ? Color.white : Color.secondaryLabel) Text(self.page == "Discover" ? self.page : "").fontWeight(.light).font(.system(size: 14)).foregroundColor(Color.white) }.padding(15) .background(self.page == "Discover" ? config.accent : Color.clear) .clipShape(Capsule()) .onTapGesture { if self.page == "Discover" { self.showOptions.toggle() } else { self.showOptions = true } self.page = "Discover" } //Favorites HStack { Image(systemName: "heart").resizable().frame(width: 20, height: 20).foregroundColor(self.page == "Favorites" ? Color.white : Color.secondaryLabel) Text(self.page == "Favorites" ? self.page : "").fontWeight(.light).font(.system(size: 14)).foregroundColor(Color.white) }.padding(15) .background(self.page == "Favorites" ? config.accent : Color.clear) .clipShape(Capsule()) .onTapGesture { if self.page == "Favorites" { self.showOptions.toggle() } else { self.showOptions = true } self.page = "Favorites" //if there aren't any favorites, send alert through noFavorites & don't allow Map/AR to show by not getting rid of options if !self.evm.doFavoritesExist(list: self.evm.eventList) && (self.subPage == "AR" || self.subPage == "Map") { self.externalAlert = true self.noFavorites = true self.showOptions = true } } //Trending HStack { Image(systemName: "hand.thumbsup").resizable().frame(width: 20, height: 20).foregroundColor(self.page == "Trending" ? Color.white : Color.secondaryLabel) Text(self.page == "Trending" ? self.page : "").fontWeight(.light).font(.system(size: 14)).foregroundColor(Color.white) }.padding(15) .background(self.page == "Trending" ? config.accent : Color.clear) .clipShape(Capsule()) .onTapGesture { self.page = "Trending" self.showOptions = false } //Info HStack { Image(systemName: "info.circle").resizable().frame(width: 20, height: 20).foregroundColor(self.page == "Information" ? Color.white : Color.secondaryLabel) Text(self.page == "Information" ? self.page : "").fontWeight(.light).font(.system(size: 14)).foregroundColor(Color.white) }.padding(15) .background(self.page == "Information" ? config.accent : Color.clear) .clipShape(Capsule()) .onTapGesture { self.page = "Information" self.showOptions = false } } else { //tour mode with buildings //AR HStack { Image(systemName: "camera.viewfinder").resizable().frame(width: 20, height: 20).foregroundColor(self.page == "AR" ? Color.white : Color.secondaryLabel) Text(self.page == "AR" ? self.page : "").fontWeight(.light).font(.system(size: 14)).foregroundColor(Color.white) }.padding(15) .background(self.page == "AR" ? config.accent : Color.clear) .clipShape(Capsule()) .onTapGesture { self.page = "AR" self.showOptions = false } //Map HStack { Image(systemName: "map.fill").resizable().frame(width: 20, height: 20).foregroundColor(self.page == "Map" ? Color.white : Color.secondaryLabel) Text(self.page == "Map" ? self.page : "").fontWeight(.light).font(.system(size: 14)).foregroundColor(Color.white) }.padding(15) .background(self.page == "Map" ? config.accent : Color.clear) .clipShape(Capsule()) .onTapGesture { self.page = "Map" self.showOptions = false } //Info HStack { Image(systemName: "info.circle").resizable().frame(width: 20, height: 20).foregroundColor(self.page == "Information" ? Color.white : Color.secondaryLabel) Text(self.page == "Information" ? self.page : "").fontWeight(.light).font(.system(size: 14)).foregroundColor(Color.white) }.padding(15) .background(self.page == "Information" ? config.accent : Color.clear) .clipShape(Capsule()) .onTapGesture { self.page = "Information" self.showOptions = false } } }.padding(.vertical, 10) .frame(width: Constants.width) .background(Color.tertiarySystemBackground) .animation(.default) //hstack end //other tabs if self.showOptions { TabOptions(evm: self.evm, showOptions: self.$showOptions, externalAlert: self.$externalAlert, noFavorites: self.$noFavorites, page: self.$page, subPage: self.$subPage).offset(x: self.page == "Discover" ? -100 : -35, y: -65) } }//zstack end } } struct TabOptions: View { @ObservedObject var evm:EventViewModel @EnvironmentObject var config: Configuration @Binding var showOptions: Bool @Environment(\.colorScheme) var colorScheme @Binding var externalAlert: Bool @Binding var noFavorites: Bool @Binding var page:String @Binding var subPage:String var body: some View { HStack { //List ZStack { Circle() .stroke(self.subPage == "List" && colorScheme == .light ? Color.tertiarySystemBackground : Color.clear) .background(self.subPage == "List" ? selectedColor(element: "background") : nonselectedColor(element: "background")) .clipShape(Circle()) Image(systemName: "list.bullet") .resizable().frame(width: 20, height: 20) .foregroundColor(self.subPage == "List" ? selectedColor(element: "foreground") : nonselectedColor(element: "foreground")) }.frame(width: 50, height: 50) .offset(x: 25) .onTapGesture { withAnimation { self.subPage = "List" self.showOptions = false } } //Calendar ZStack { Circle() .stroke(self.subPage == "Calendar" && colorScheme == .light ? Color.tertiarySystemBackground : Color.clear) .background(self.subPage == "Calendar" ? selectedColor(element: "background") : nonselectedColor(element: "background")) .clipShape(Circle()) Image(systemName: "calendar") .resizable().frame(width: 20, height: 20) .foregroundColor(self.subPage == "Calendar" ? selectedColor(element: "foreground") : nonselectedColor(element: "foreground")) }.frame(width: 50, height: 50) .offset(y: -50) .onTapGesture { withAnimation { self.subPage = "Calendar" self.showOptions = false } } //AR ZStack { Circle() .stroke(self.subPage == "AR" && colorScheme == .light ? Color.tertiarySystemBackground : Color.clear) .background(self.subPage == "AR" ? selectedColor(element: "background") : nonselectedColor(element: "background")) .clipShape(Circle()) Image(systemName: "camera") .resizable().frame(width: 22, height: 18) .foregroundColor(self.subPage == "AR" ? selectedColor(element: "foreground") : nonselectedColor(element: "foreground")) }.frame(width: 50, height: 50) .offset(y: -50) .onTapGesture { withAnimation { self.subPage = "AR" self.showOptions = false } //if there aren't any favorites, send alert through noFavorites & don't allow AR to show by not getting rid of options if !self.evm.doFavoritesExist(list: self.evm.eventList) && self.page == "Favorites" { self.externalAlert = true self.noFavorites = true self.showOptions = true } } //Map ZStack { Circle() .stroke(self.subPage == "Map" && colorScheme == .light ? Color.tertiarySystemBackground : Color.clear) .background(self.subPage == "Map" ? selectedColor(element: "background") : nonselectedColor(element: "background")) .clipShape(Circle()) Image(systemName: "mappin.and.ellipse") .resizable().frame(width: 20, height: 22) .foregroundColor(self.subPage == "Map" ? selectedColor(element: "foreground") : nonselectedColor(element: "foreground")) }.frame(width: 50, height: 50) .offset(x: -25) .onTapGesture { withAnimation { self.subPage = "Map" self.showOptions = false } //if there aren't any favorites, send alert through noFavorites & don't allow Map to show by not getting rid of options if !self.evm.doFavoritesExist(list: self.evm.eventList) && self.page == "Favorites" { self.externalAlert = true self.noFavorites = true self.showOptions = true } } }.transition(.scale) //hstack } func selectedColor(element: String) -> Color { if element == "background" { return config.accent } //if element == stroke or foreground if colorScheme == .light { return Color.tertiarySystemBackground } else if colorScheme == .dark { return Color.secondaryLabel } return config.accent //absolute default } func nonselectedColor(element: String) -> Color { if element == "stroke" || element == "foreground" { return config.accent } else if element == "background" { if colorScheme == .light { return Color.tertiarySystemBackground } else if colorScheme == .dark { return Color.secondaryLabel } } return config.accent //absolute default } }
// // CoronaData.swift // PocketApp // // Created by marvin evins on 11/30/20. // import Foundation class CoronaData { // struct Returned: Codable{ // var state: String // var positive: Int // // } var stateArray: [StateData] = [] var urlString = "https://api.covidtracking.com/v1/states/current.json" func getData(completed: @escaping ()-> ()){ print("we are accessing the url \(urlString)") //create a url guard let url = URL(string: urlString) else{ print("Error: colud not create a url from \(urlString)") completed() return } //create a session let session = URLSession.shared //GET THE DATA WITH .dataTask method let task = session.dataTask(with: url) {(data, response, error) in if let error = error { print("error: \(error.localizedDescription )") } //deal with the data do { let returned = try JSONDecoder().decode([StateData].self, from: data!) self.stateArray = returned }catch{ print(" json error: \(error.localizedDescription )") } completed() } task.resume() } }
// // BaseInteractor.swift // Networkd // // Created by Cloud Stream on 5/5/17. // Copyright © 2017 CloudStream LLC. All rights reserved. // import UIKit class BaseInteractor { var repo: UserRepo var output: BaseInteractorOutput required init(output:BaseInteractorOutput, repo: UserRepo) { self.repo = repo self.output = output } class func createInstance<T:BaseInteractor>(typeThing:T.Type,view:BaseView) -> T { let adapter = AlamofireAdapter() let cloud = Cloud(adapter: adapter) let local = Local() let repo = Repo(local:local,cloud: cloud) let presenter = BasePresenter(view: view) return typeThing.init(output:presenter, repo:repo) } } enum ITError: Error { case Error(cause: String) var localizedDescription: String{ switch self { case .Error(let cause): return cause default: break } } }
// // RSSFeedViewModel.swift // Feedit // // Created by Tyler D Lawrence on 8/10/20. // import Foundation import CoreData import SwiftUI import Combine import UIKit import FeedKit import FaviconFinder import URLImage import BackgroundTasks import WidgetKit import Alamofire import SwiftyJSON public extension UIView { func getImage(from imageUrl: String, to imageView: UIImageView) { guard let url = URL(string: imageUrl ) else { return } DispatchQueue.global().async { guard let data = try? Data(contentsOf: url) else { return } DispatchQueue.main.async { imageView.image = UIImage(data: data) } } } } extension RSSFeedViewModel: Identifiable { } class RSSFeedViewModel: NSObject, ObservableObject { typealias Element = RSSItem typealias Context = RSSItem typealias Model = Post private(set) lazy var rssFeedViewModel = RSSFeedViewModel(rss: RSS(), dataSource: DataSourceService.current.rssItem) @Published var isOn = false @Published var unreadIsOn = false @Published var items = [RSSItem]() @Published var filteredArticles: [RSSItem] = [] @Published var selectedPost: RSSItem? @Published var shouldReload = false @ObservedObject var store = RSSStore.instance @Published var filteredPosts: [RSSItem] = [] @Published var filterType = FilterType.unreadIsOn @Published var showingDetail = false @Published var showFilter = false @Published var rss: RSS @Published var rssItem = RSSItem() private var cancellable: AnyCancellable? = nil private var cancellable2: AnyCancellable? = nil let dataSource: RSSItemDataSource var start = 0 var rssSource: RSS { return self.rssFeedViewModel.rss } init(rss: RSS, dataSource: RSSItemDataSource) { self.dataSource = dataSource self.rss = rss super.init() self.filteredPosts = rss.posts.filter { self.filterType == .unreadIsOn ? !$0.isRead : true } cancellable = Publishers.CombineLatest3(self.$rss, self.$filterType, self.$shouldReload) .receive(on: DispatchQueue.main) .sink(receiveValue: { (newValue) in self.filteredPosts = newValue.0.posts.filter { newValue.1 == .unreadIsOn ? !$0.isRead : true } }) } func archiveOrCancel(_ item: RSSItem) { let updatedItem = dataSource.readObject(item) updatedItem.isArchive = !item.isArchive updatedItem.updateTime = Date() dataSource.setUpdateObject(updatedItem) _ = dataSource.saveUpdateObject() } func unreadOrCancel(_ item: RSSItem) { let updatedItem = dataSource.readObject(item) updatedItem.isRead = !item.isRead updatedItem.updateTime = Date() dataSource.setUpdateObject(updatedItem) _ = dataSource.saveUpdateObject() } func loadMore() { start = items.count fecthResults(start: start) } func fecthResults(start: Int = 0) { if start == 0 { items.removeAll() } dataSource.performFetch(RSSItem.requestObjects(rssUUID: rss.uuid!, start: start)) if let objects = dataSource.fetchedResult.fetchedObjects { items.append(contentsOf: objects) } } func markAllPostsRead() { self.store.markAllPostsRead(feed: self.rss) shouldReload = true } func markPostRead(index: Int) { self.store.setPostRead(post: self.filteredArticles[index], feed: self.rss) shouldReload = true } func reloadPosts() { store.reloadFeedPosts(feed: rss) } func selectPost(index: Int) { self.selectedPost = self.filteredArticles[index] self.showingDetail.toggle() self.markPostRead(index: index) } func fetchRemoteRSSItems() { guard let url = URL(string: rss.url) else { return } guard let uuid = self.rss.uuid else { return } fetchNewRSS(url: url) { result in switch result { case .success(let feed): var items = [RSSItem]() switch feed { case .atom(let atomFeed): for item in atomFeed.entries ?? [] { if let fetchDate = self.rss.lastFetchTime, let pubDate = item.updated, pubDate < fetchDate { continue } guard let title = item.title, items.filter({ $0.title == title }).count <= 0 else { continue } items.append(item.asRSSItem(container: uuid, in: self.dataSource.createContext)) } case .json(let jsonFeed): for item in jsonFeed.items ?? [] { if let fetchDate = self.rss.lastFetchTime, let pubDate = item.datePublished, pubDate < fetchDate { continue } guard let title = item.title, items.filter({ $0.title == title }).count <= 0 else { continue } items.append(item.asRSSItem(container: uuid, in: self.dataSource.createContext)) } case .rss(let rssFeed): for item in rssFeed.items ?? [] { if let fetchDate = self.rss.lastFetchTime, let pubDate = item.pubDate, pubDate < fetchDate { continue } guard let title = item.title, items.filter({ $0.title == title }).count <= 0 else { continue } items.append(item.asRSSItem(container: uuid, in: self.dataSource.createContext)) } } self.rss.lastFetchTime = Date() self.dataSource.saveCreateContext() self.fecthResults() case .failure(let error): print("feed error \(error)") } } } } class FeedObject: Codable, Identifiable, ObservableObject { var id = UUID() var name: String var url: URL var posts: [Post] { didSet { objectWillChange.send() } } var imageURL: URL? var lastUpdateDate: Date init?(feed: Feed, url: URL) { self.url = url lastUpdateDate = Date() switch feed { case .rss(let rssFeed): self.name = rssFeed.title ?? "" let items = rssFeed.items ?? [] self.posts = items .compactMap { Post(feedItem: $0) } .sorted(by: { (lhs, rhs) -> Bool in return Calendar.current.compare(lhs.date, to: rhs.date, toGranularity: .minute) == ComparisonResult.orderedDescending }) if let urlStr = rssFeed.image?.url, let url = URL(string: urlStr) { self.imageURL = url } else { FaviconFinder(url: URL(string: rssFeed.link ?? "")!).downloadFavicon { (_) in self.imageURL = url } } case .atom(let atomFeed): self.name = atomFeed.title ?? "" let items = atomFeed.entries ?? [] self.posts = items .compactMap { Post(atomFeed: $0) } .sorted(by: { (lhs, rhs) -> Bool in return Calendar.current.compare(lhs.date, to: rhs.date, toGranularity: .minute) == ComparisonResult.orderedDescending }) if let urlStr = atomFeed.logo, let url = URL(string: urlStr) { self.imageURL = url } else { FaviconFinder(url: URL(string: atomFeed.links?.first?.attributes?.href ?? "")!).downloadFavicon { (_) in self.imageURL = url } } default: return nil } } init(name: String, url: URL, posts: [Post]) { self.name = name self.url = url self.posts = posts lastUpdateDate = Date() } static var testObject: FeedObject { return FeedObject(name: "Test feed", url: URL(string: "https://www.google.com")!, posts: [Post.testObject]) } } class Post: Codable, Identifiable, ObservableObject { var id = UUID() var title: String var description: String var url: URL var date: Date var isRead: Bool { return readDate != nil } var readDate: Date? { didSet { objectWillChange.send() } } var lastUpdateDate: Date init?(feedItem: RSSFeedItem) { self.title = feedItem.title ?? "" self.description = feedItem.description ?? "" if let link = feedItem.link, let url = URL(string: link) { self.url = url } else { return nil } self.date = feedItem.pubDate ?? Date() lastUpdateDate = Date() } init?(atomFeed: AtomFeedEntry) { self.title = atomFeed.title ?? "" let description = atomFeed.content?.value ?? "" let attributed = try? NSAttributedString(data: description.data(using: .unicode)!, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil) self.description = attributed?.string ?? "" if let link = atomFeed.links?.first?.attributes?.href, let url = URL(string: link) { self.url = url } else { return nil } self.date = atomFeed.updated ?? Date() lastUpdateDate = Date() } init(title: String, description: String, url: URL) { self.title = title self.description = description self.url = url self.date = Date() lastUpdateDate = Date() } static var testObject: Post { return Post(title: "This Is A Test Post Title", description: "This is a test post description", url: URL(string: "https://www.google.com")!) } } struct XMLElement { var value:String var attributes:[String:String] } typealias XMLDictionary = [String:Any] class XMLHelper:NSObject { func parseXML(atURL url:URL, completion:@escaping (XMLDictionary?) -> Void) { guard let data = try? Data(contentsOf: url) else { completion(nil) return } parseXML(data: data, completion: completion) } func parseXML(atURL url:URL, elementName:String, completion:@escaping (Array<XMLDictionary>?) -> Void) { guard let data = try? Data(contentsOf: url) else { completion(nil) return } parseXML(data: data, elementName: elementName, completion: completion) } func parseXML(data:Data, completion:@escaping (XMLDictionary?) -> Void) { let parser = XMLParser(data: data) self.completion = completion let helperParser = ParserAllTags(completion: completion) parser.delegate = helperParser parser.parse() } func parseXML(data:Data, elementName:String, completion:@escaping(Array<XMLDictionary>?) -> Void) { let parser = XMLParser(data: data) self.completionArray = completion //let helperParser = ParserSpecificElement(elementName: elementName, completion:completion) let helperParser = ParserAllTags(elementName:elementName, completion: completion) parser.delegate = helperParser parser.parse() } @available(iOS 13.0, *) func parseXML(atURL url:URL) -> AnyPublisher<XMLDictionary?, Never> { let subject = CurrentValueSubject<XMLDictionary?, Never>(nil) parseXML(atURL: url) { dictionary in subject.send(dictionary) } return subject.eraseToAnyPublisher() } @available(iOS 13.0, *) func parseXML(data: Data) -> AnyPublisher<XMLDictionary?, Never> { let subject = CurrentValueSubject<XMLDictionary?, Never>(nil) parseXML(data:data) { dictionary in subject.send(dictionary) } return subject.eraseToAnyPublisher() } @available(iOS 13.0, *) func parseXML(atURL url:URL, elementName:String) -> AnyPublisher<Array<XMLDictionary>?, Never> { let subject = CurrentValueSubject<Array<XMLDictionary>?, Never>(nil) parseXML(atURL: url, elementName: elementName) { arrayDictionary in subject.send(arrayDictionary) } return subject.eraseToAnyPublisher() } @available(iOS 13.0, *) func parseXML(data:Data, elementName:String) -> AnyPublisher<Array<XMLDictionary>?, Never> { let subject = CurrentValueSubject<Array<XMLDictionary>?, Never>(nil) parseXML(data:data, elementName: elementName) { arrayDictionary in subject.send(arrayDictionary) } return subject.eraseToAnyPublisher() } // MARK: - Private private var completionArray:((Array<XMLDictionary>?) -> Void)? private var completion:((XMLDictionary?) -> Void)? } // MARK: - ParserSpecificElement fileprivate class ParserSpecificElement:NSObject, XMLParserDelegate { init(elementName:String, completion:@escaping (Array<XMLDictionary>?) -> Void) { self.elementNameToGet = elementName self.completion = completion } func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) { currentElementName = nil if elementName == elementNameToGet { newDictionary() } else if currentDictionary != nil { currentElementName = elementName } if let currentElementName = currentElementName { addAttributes(attributeDict, forKey:currentElementName) } } func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) { if elementName == elementNameToGet { addCurrentDictionaryToResults() } } func parser(_ parser: XMLParser, foundCharacters string: String) { if let key = currentElementName { addString(string, forKey: key) } } func parserDidStartDocument(_ parser: XMLParser) { } func parserDidEndDocument(_ parser: XMLParser) { if let _ = elementNameToGet { completion(results) } } // MARK: - Private private var completion:(Array<XMLDictionary>?) -> Void private var currentDictionary:XMLDictionary? private var currentElementName:String? private var elementNameToGet:String? private var results:[XMLDictionary] = [] private func addAttributes(_ attributes:[String:String], forKey key:String) { currentDictionary?[key] = XMLElement(value: "", attributes: attributes) } private func addCurrentDictionaryToResults() { if let currentDictionary = currentDictionary { results.append(currentDictionary) } currentDictionary = nil } private func addString(_ string:String, forKey key:String) { if let currentValue = currentDictionary?[key] as? XMLElement { let valueString = currentValue.value + string currentDictionary?[key] = XMLElement(value: valueString, attributes: currentValue.attributes) } else { currentDictionary?[key] = XMLElement(value: string, attributes: [:]) } } private func newDictionary() { currentDictionary = [:] } } // MARK: - ParserAllTags fileprivate class ParserAllTags:NSObject, XMLParserDelegate { init(elementName:String, completion:@escaping(Array<XMLDictionary>?) -> Void) { self.arrayCompletion = completion elementNameToGet = elementName } init(completion:@escaping (XMLDictionary?) -> Void) { self.completion = completion } private var arrayCompletion:((Array<XMLDictionary>?) -> Void)? // used in case of specific element private var completion:((XMLDictionary?) -> Void)? // used when parsing all tags private var currentDictionary:XMLDictionary = [:] private var currentElementName:String = "" private var elementNameToGet:String? private var results:[XMLDictionary] = [] // used in case of specific element private var rootDictionary:XMLDictionary = [:] private var stack:[XMLDictionary] = [] private func addAttributes(_ attributes:[String:String], forKey key:String) { currentDictionary[key] = XMLElement(value: "", attributes: attributes) } private func addCurrentDictionaryToResults() { results.append(currentDictionary) currentDictionary = [:] } /// Add a dictionary to an existing one /// If the key is already in the dictionary we need to create an array /// - Parameters: /// - dictionary: the dictionary to add /// - toDictionary: the dictionary where the given dictionary will be added /// - key: the key /// - Returns: the dictionary passed as toDictionary with the new value added private func addDictionary(_ dictionary:XMLDictionary, toDictionary:XMLDictionary, key:String) -> XMLDictionary { var returnDictionary = toDictionary if let array = returnDictionary[key] as? Array<XMLDictionary> { var newArray = array newArray.append(dictionary) returnDictionary[key] = newArray } else if let dictionary = returnDictionary[key] as? XMLDictionary { var array:[XMLDictionary] = [dictionary] array.append(dictionary) returnDictionary[key] = array } else { returnDictionary[key] = dictionary } return returnDictionary } private func addString(_ string:String, forKey key:String) { if let currentValue = currentDictionary[key] as? XMLElement { let valueString = currentValue.value + string currentDictionary[key] = XMLElement(value: valueString, attributes: currentValue.attributes) } else { currentDictionary[key] = XMLElement(value: string, attributes: [:]) } } private func newDictionary() { currentDictionary = [:] } // MARK: - XMLParserDelegate func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) { if let elementNameToGet = elementNameToGet { currentElementName = "" if elementName == elementNameToGet { newDictionary() } else { currentElementName = elementName } if currentElementName != "" { addAttributes(attributeDict, forKey:currentElementName) } } else { stack.append(currentDictionary) currentDictionary = [:] currentElementName = elementName } } func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) { if let elementNameToGet = elementNameToGet { if elementName == elementNameToGet { addCurrentDictionaryToResults() } } else { var parentDictionary = stack.removeLast() parentDictionary = addDictionary(currentDictionary, toDictionary: parentDictionary, key: elementName) currentDictionary = parentDictionary } } func parser(_ parser: XMLParser, foundCharacters string: String) { if string.starts(with: "\n") { return } if let _ = elementNameToGet { if currentElementName != "" { addString(string, forKey: currentElementName) } return } if let currentValue = currentDictionary[currentElementName] as? XMLElement { let valueString = currentValue.value + string currentDictionary[currentElementName] = XMLElement(value: valueString, attributes: currentValue.attributes) } else { currentDictionary[currentElementName] = XMLElement(value: string, attributes: [:]) } } func parserDidEndDocument(_ parser: XMLParser) { if let arrayCompletion = arrayCompletion { arrayCompletion(results) } else if let completion = completion { completion(currentDictionary) } } }
// // File.swift // ray37_p5 // // Created by Raheel Yanful on 4/11/18. // Copyright © 2018 Raheel Yanful. All rights reserved. // import Foundation class Filter{ var name: String var section: Type init(name: String, section: Type) { self.name = name self.section = section } } enum Type{ case location case meal case type }
// // SharedMediaCell.swift // HippoAgent // // Created by Arohi Magotra on 06/04/21. // Copyright © 2021 Socomo Technologies Private Limited. All rights reserved. // import UIKit class SharedMediaCell: UICollectionViewCell { //MARK:- IBOutlets @IBOutlet weak var imageViewMedia : UIImageView! @IBOutlet weak var buttonPlay : UIButton! override func awakeFromNib() { super.awakeFromNib() // Initialization code } }
// // Configuration.swift // Swift-Base // // Created by Timur Shafigullin on 09/07/2020. // Copyright © 2020 Flatstack. All rights reserved. // import Foundation enum Configuration { // MARK: - Type Properties static let apiServerBaseURL = URL(string: "https://Swift-Base.com")! static let graphQLURL = URL(string: "https://rails-base-graphql-api.herokuapp.com/graphql")! }
// // PetDetailViewController.swift // Assessment // // Created by Flatiron School on 10/5/16. // Copyright © 2016 Flatiron School. All rights reserved. // import UIKit class PetDetailViewController: UIViewController { @IBOutlet weak var doctor: UILabel! @IBOutlet weak var hospital: UILabel! @IBOutlet weak var name: UILabel! var pet : Pet? override func viewDidLoad() { super.viewDidLoad() if let unwrappedName = pet?.name { self.name.text = unwrappedName self.title = unwrappedName } if let unwrappedHospital = pet?.hospital?.name { self.hospital.text = unwrappedHospital } if let unwrappedDoctor = pet?.doctors?.name { self.doctor.text = unwrappedDoctor } } }
// // PlayerDataModel.swift // radio // // Created by MacBook 13 on 9/11/18. // Copyright © 2018 MacBook 13. All rights reserved. // import Foundation /* Class to interchange data between player and ui controllers */ class PlayerCommonData{ // Can't init is singleton private init() { } /* Singleton internal instance */ static let shared = PlayerCommonData() /* The radio link to shared between controller and the player */ var radioLink:String! = nil }
import Foundation import UIKit // MARK: - WeatherModel struct WeatherModel: Codable { let weather: [Weather] let main: Main let name: String func temperatureCelsius() -> String { let tempCelsius = self.main.temp - 273.15 let formatedString = String(format: "%.2f", tempCelsius).celsiusString() return formatedString } func image(completion: @escaping (UIImage) -> Void) { guard let icon = self.weather.first?.icon else { return } let weatherService = OpenWeatherServices() weatherService.image(type: .image(string: icon), completion: { data in guard let image = UIImage(data: data) else { return } completion(image) }) } } // MARK: - Main struct Main: Codable { let temp: Double enum CodingKeys: String, CodingKey { case temp } } // MARK: - Weather struct Weather: Codable { let weatherDescription, icon: String enum CodingKeys: String, CodingKey { case weatherDescription = "description" case icon } }
// // UserDBManager.swift // Demo_Clock // // Created by edison on 2019/5/4. // Copyright © 2019年 EDC. All rights reserved. // import Foundation extension DBManager { func login_ornot() -> Bool { let cpath = plistFilePath.cString(using: String.Encoding.utf8) var flag = false if sqlite3_open(cpath!, &db) != SQLITE_OK { NSLog("db open failed") return false } else { let sql = "SELECT flag FROM LoginDB WHERE id=1" let cSql = sql.cString(using: String.Encoding.utf8) var statement: OpaquePointer? if sqlite3_prepare_v2(db, cSql!, -1, &statement, nil) == SQLITE_OK { while sqlite3_step(statement) == SQLITE_ROW { if let strflag = getColumnValue(index: 0, stmt: statement!) { if strflag == "1" { flag = true } else { flag = false } } } sqlite3_close(db) sqlite3_finalize(statement) return flag } } return false } func insert_user_db(user: UserItem) { let cpath = plistFilePath.cString(using: String.Encoding.utf8) if sqlite3_open(cpath!, &db) != SQLITE_OK { NSLog("db open failed") return } else { let sql = "INSERT OR REPLACE INTO UserDB (realname,name,password,email) VALUES ('\(user.realname)','\(user.name)','\(user.password)','\(user.email)');" let boolflag = DBManager.shareManager().execute_sql(sql: sql) if !boolflag { NSLog("insert user failed") return } else { NSLog("insert user success") } } } public func find_user_id(sql: String) -> Int { let cpath = plistFilePath.cString(using: String.Encoding.utf8) if sqlite3_open(cpath!, &db) != SQLITE_OK { NSLog("db open failed") } else { NSLog("find id sql:\(sql)") let cSql = sql.cString(using: String.Encoding.utf8) var statement: OpaquePointer? // 预处理过程 if sqlite3_prepare_v2(db, cSql!, -1, &statement, nil) == SQLITE_OK { // 执行查询 while sqlite3_step(statement) == SQLITE_ROW { if let strId = getColumnValue(index: 0, stmt: statement!) { sqlite3_close(db) sqlite3_finalize(statement) return Int(strId)! } } sqlite3_close(db) sqlite3_finalize(statement) } } return -1 } func find_current_login_id() -> Int { var result = 0 let useritem = UserItem() let cpath = plistFilePath.cString(using: String.Encoding.utf8) if sqlite3_open(cpath!, &db) != SQLITE_OK { NSLog("db open failed") } else { let sql = "SELECT userid FROM LoginDB WHERE id=1" let cSql = sql.cString(using: String.Encoding.utf8) var statement: OpaquePointer? // 预处理过程 NSLog("find_current_login_id:\(sql)") if sqlite3_prepare_v2(db, cSql!, -1, &statement, nil) == SQLITE_OK { while sqlite3_step(statement) == SQLITE_ROW { if let strid = getColumnValue(index: 0, stmt: statement!) { result = Int(strid)! } } sqlite3_close(db) sqlite3_finalize(statement) return result } } return result } func find_user_byid(id: Int) -> UserItem { let useritem = UserItem() let cpath = plistFilePath.cString(using: String.Encoding.utf8) if sqlite3_open(cpath!, &db) != SQLITE_OK { NSLog("db open failed") } else { let sql = "SELECT realname,name,password,email FROM UserDB WHERE id=\(id)" let cSql = sql.cString(using: String.Encoding.utf8) var statement: OpaquePointer? // 预处理过程 NSLog("find_user_byid:\(sql)") if sqlite3_prepare_v2(db, cSql!, -1, &statement, nil) == SQLITE_OK { while sqlite3_step(statement) == SQLITE_ROW { if let strrealname = getColumnValue(index: 0, stmt: statement!) { useritem.realname = strrealname } if let strname = getColumnValue(index: 1, stmt: statement!) { useritem.name = strname } if let strpass = getColumnValue(index: 2, stmt: statement!) { useritem.password = strpass } if let stremail = getColumnValue(index: 3, stmt: statement!) { useritem.email = stremail } useritem.id = id } sqlite3_close(db) sqlite3_finalize(statement) return useritem } } return useritem } func get_single_col(sql: String) -> String { var result = "" let cpath = plistFilePath.cString(using: String.Encoding.utf8) if sqlite3_open(cpath!, &db) != SQLITE_OK { NSLog("db open failed") } else { let cSql = sql.cString(using: String.Encoding.utf8) var statement: OpaquePointer? // 预处理过程 NSLog("find_user_byid:\(sql)") if sqlite3_prepare_v2(db, cSql!, -1, &statement, nil) == SQLITE_OK { while sqlite3_step(statement) == SQLITE_ROW { if let str = getColumnValue(index: 0, stmt: statement!) { result = str break } } } sqlite3_close(db) sqlite3_finalize(statement) NSLog("get col result" + result) return result } return "" } }
class FoodFactory { var nameOnLabel = "" var caloriesOnLabel = 0 init(foodName : String, numberCalories : Int) { nameOnLabel = foodName caloriesOnLabel = numberCalories } } class PantryFactory { var walkIn = false var temperature = 0 var contents = [FoodFactory]() init(walkInOption : Bool, chooseTemp : Int) { walkIn = walkInOption temperature = chooseTemp } func shopping (food : String, calories : Int) { let item = FoodFactory(foodName: food, numberCalories: calories) contents.append(item) } } var myOwnPantry = PantryFactory(walkInOption: true, chooseTemp: 62) print(myOwnPantry.walkIn) print(myOwnPantry.temperature) myOwnPantry.shopping(food: "almond flour", calories: 100) myOwnPantry.shopping(food: "gluten-free oats", calories: 230) myOwnPantry.shopping(food: "mini choclate chips", calories: 90) print(myOwnPantry.contents) for itemInPantry in myOwnPantry.contents { print("There is \(itemInPantry.nameOnLabel) in my pantry and it has \(itemInPantry.caloriesOnLabel) calories") }
// // AliasesTypes.swift // WavesWallet-iOS // // Created by mefilt on 29/10/2018. // Copyright © 2018 Waves Platform. All rights reserved. // import Foundation import Extensions import DomainLayer enum AliasesTypes { enum ViewModel { } } extension AliasesTypes { enum Query: Hashable { case calculateFee case createAlias } struct State: Mutating { var aliaces: [DomainLayer.DTO.Alias] var query: Query? var displayState: DisplayState } enum Event { case viewWillAppear case tapCreateAlias case completedQuery case handlerFeeError(Error) case setFee(Money) case refresh case showCreateAlias case hideCreateAlias } struct DisplayState: Mutating, DataSourceProtocol { enum Action { case none case update } enum TransactionFee { case progress case fee(Money) } var sections: [ViewModel.Section] var isAppeared: Bool var action: Action? var error: DisplayErrorState var transactionFee: TransactionFee var isEnabledCreateAliasButton: Bool } } extension AliasesTypes.ViewModel { enum Row { case alias(DomainLayer.DTO.Alias) case head } struct Section: SectionProtocol, Mutating { var rows: [Row] } }
// // SUCatalog.swift // FetchInstallerPkg // // Created by Armin Briegel on 2021-06-09. // import Foundation class SUCatalog: ObservableObject { @Published var catalog: Catalog? var products: [String: Product]? { return catalog?.products } @Published var installers = [Product]() @Published var isLoading = false @Published var hasLoaded = false init() { load() } func load() { let catalogURL = catalogURL(for: Prefs.seedProgram) //print(catalogURL.absoluteString) let sessionConfig = URLSessionConfiguration.ephemeral let session = URLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil) let task = session.dataTask(with: catalogURL) { data, response, error in if error != nil { print(error!.localizedDescription) return } let httpResponse = response as! HTTPURLResponse if httpResponse.statusCode != 200 { print(httpResponse.statusCode) } else { if data != nil { //print(String(decoding: data!, as: UTF8.self)) DispatchQueue.main.async { self.decode(data: data!) } } } } isLoading = true hasLoaded = false self.catalog = nil self.installers = [Product]() task.resume() } private func decode(data: Data) { self.isLoading = false self.hasLoaded = true let decoder = PropertyListDecoder() self.catalog = try! decoder.decode(Catalog.self, from: data) if let products = self.products { //print("loaded catalog with \(products.count) products") for (productKey, product) in products { product.key = productKey if let metainfo = product.extendedMetaInfo { if metainfo.sharedSupport != nil { // this is an installer, add to list self.installers.append(product) //print("\(productKey) is an installer") //print(" BuildManifest: \(product.buildManifestURL ?? "<no>")") //print(" InstallAssistant: \(String(describing: product.installAssistantURL))") product.loadDistribution() } } } //print("found \(self.installers.count) installer pkgs") installers.sort { $0.postDate > $1.postDate } } } }
// // String+Ext.swift // Norris // // Created by Bárbara Souza on 13/04/20. // Copyright © 2020 Bárbara Souza. All rights reserved. // import UIKit extension String { func addLineSpacing(_ spacing: CGFloat) -> NSAttributedString { let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineSpacing = spacing let attributedString = NSAttributedString(string: self, attributes: [NSAttributedString.Key.paragraphStyle: paragraphStyle]) return attributedString } }
// // cvImagesForPlayer.swift // ETBAROON // // Created by imac on 10/16/17. // Copyright © 2017 IAS. All rights reserved. // import UIKit import Alamofire import SwiftyJSON class cvImagesForPlayer: UICollectionViewCell { @IBOutlet weak var imgPlayer: UIImageView! override func awakeFromNib() { super.awakeFromNib() // Initialization code self.backgroundColor=UIColor.white self.layer.cornerRadius=5.0 self.layer.masksToBounds=false self.layer.shadowColor=UIColor.black.withAlphaComponent(0.2).cgColor self.layer.shadowOffset=CGSize(width: 0, height: 0) self.layer.shadowOpacity=0.8 //self.alwaysBounceVertical = true } var photo: Gallery? { didSet { guard let photo = photo else { return } Alamofire.request(photo.url).response { response in if let data = response.data, let image = UIImage(data: data) { self.imgPlayer.image = image } } } } }
// // MRInputTextFiled.swift // MVVM+ReactiveSwift // // Created by pxh on 2019/2/22. // Copyright © 2019 pxh. All rights reserved. // import UIKit /// 输入框视图 class MRInputTextFiled: UIView { enum InputType { case account case password case repassword } private var type: InputType = .account lazy var iconIV: UIImageView = { let imageView = UIImageView() imageView.image = UIImage.init(named: type == .account ? "icon_accout" : "icon_password") addSubview(imageView) return imageView }() lazy var inputTextField: UITextField = { let textField = UITextField() textField.font = UIFont.init(fontName: SystemFontName.Regular, size: 14) textField.attributedPlaceholder = NSAttributedString.init(string: type == .account ? "请输入您的手机号" : "请输入您的登录密码", attributes: [NSAttributedString.Key.foregroundColor : UIColor.init(rgb: 0xBCBCBC)]) addSubview(textField) return textField }() lazy var hLineView: UIView = { let view = UIView() view.backgroundColor = UIColor.init(rgb: 0x797979) addSubview(view) return view }() lazy var eyesBtn: UIButton = { let button = UIButton() button.setBackgroundImage(UIImage.init(named: "icon-Display password"), for: .selected) button.setBackgroundImage(UIImage.init(named: "icon-openeye"), for: .normal) addSubview(button) return button }() convenience init(inputType: InputType) { self.init() self.type = inputType } override func layoutSubviews() { super.layoutSubviews() switch type { case .account: layoutAccountView() case .password: layoutPasswordView() case .repassword: layoutPasswordView() } } /// 布局账号界面 private func layoutAccountView(){ iconIV.snp.makeConstraints { (make) in make.left.equalTo(10) make.centerY.equalTo(self) make.width.height.equalTo(24) } inputTextField.snp.makeConstraints { (make) in make.left.equalTo(iconIV.snp.right).offset(15) make.centerY.equalTo(self) make.right.equalTo(-14) } inputTextField.clearButtonMode = UITextField.ViewMode.whileEditing hLineView.snp.makeConstraints { (make) in make.height.equalTo(0.5) make.left.right.bottom.equalTo(0) } } /// 布局输入密码页面 private func layoutPasswordView(){ iconIV.snp.makeConstraints { (make) in make.left.equalTo(10) make.centerY.equalTo(self) make.width.height.equalTo(24) } eyesBtn.snp.makeConstraints { (make) in make.right.equalTo(-8) make.centerY.equalTo(self) make.width.height.equalTo(24) } eyesBtn.isSelected = true inputTextField.snp.makeConstraints { (make) in make.left.equalTo(iconIV.snp.right).offset(15) make.centerY.equalTo(self) make.right.equalTo(-14) } inputTextField.clearButtonMode = UITextField.ViewMode.never hLineView.snp.makeConstraints { (make) in make.height.equalTo(0.5) make.left.right.bottom.equalTo(0) } } }
// // BaseTabBarController.swift // Bliss // // Created by Andrew Solesa on 2020-02-05. // Copyright © 2020 KSG. All rights reserved. // import UIKit class BaseTabBarController: UITabBarController { var m: DataModelManager! override func viewDidLoad() { super.viewDidLoad() if let count = viewControllers?.count { for i in 0 ..< count { if let vc = viewControllers?[i] as? TabViewController { vc.m = m } } } viewControllers!.forEach { $0.view } } }
// // PageTitleView.swift // DouYuCopySwift // // Created by yckj on 2020/9/4. // Copyright © 2020 zxx. All rights reserved. // import UIKit private let kScrollLineH : CGFloat = 2 private let kNormalColor : (CGFloat , CGFloat , CGFloat) = (85, 85 ,85) private let kSelectColor :(CGFloat , CGFloat , CGFloat) = (255, 128 , 0) class PageTitleView: UIView { // 定义属性 private var titles : [String] // 懒加载属性 private lazy var scrollView : UIScrollView = { let scrollView = UIScrollView() scrollView.showsHorizontalScrollIndicator = false scrollView.scrollsToTop = false scrollView.bounces = false // 反之超出范围以外、 return scrollView }()// 闭包类型 // Mark - 自定义构造函数 ----- 必须创建 init with coder init(frame: CGRect , titles : [String]) { self.titles = titles super.init(frame: frame) // 设置UI 界面 setUI() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // 设置 UI 界面 extension PageTitleView { private func setUI() { //添加 uiscrollView addSubview(scrollView) scrollView.frame = bounds // 2. 添加 title对应的 label setUpTitles() // 3. 设置 底线和滚动的滑块 setUpBottomTitltLabelsLiones() } // 设置label private func setUpTitles() { // 0 抽出label 的共通属性 就不需要每次循环的时候 去创建了 let labelW : CGFloat = frame.width / CGFloat(titles.count) let labelH : CGFloat = frame.height - kScrollLineH let labelY : CGFloat = 0 for (index,title) in titles.enumerated() { // 1.循环创建label let label = UILabel() // 2. 设置 uiLabel的属性 label.text = title label.tag = index label.font = UIFont.systemFont(ofSize: 16.0) label.textAlignment = .center // 3. 设置label的的属性 let labelX : CGFloat = labelW * CGFloat(index) label.frame = CGRect(x: labelX, y: labelY, width: labelW, height: labelH) // 4. Label 添加到 scrollView中 scrollView.addSubview(label) } } private func setUpBottomTitltLabelsLiones() { // 添加底线 let bottomLine = UIView() bottomLine.backgroundColor = UIColor.lightGray let lineH : CGFloat = 0.5 bottomLine.frame = CGRect(x: 0, y: frame.height - lineH, width: frame.width, height: lineH) addSubview(bottomLine)// 添加到当前的view中 } }
// // UIViewController+Extensions.swift // MartiPlacesApp // // Created by MUSTAFA TOLGA TAS on 24.06.2020. // Copyright © 2020 MUSTAFA TOLGA TAS. All rights reserved. // import UIKit extension UIViewController { func push(storyboardName: String, withIdentifier: String, setupBlock: ((UIViewController) -> Void)? = nil) { let storyboard = UIStoryboard(name: storyboardName, bundle: nil) let viewController = storyboard.instantiateViewController(withIdentifier: withIdentifier) setupBlock?(viewController) self.navigationController?.pushViewController(viewController, animated: true) } }